Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 
0003 /* Driver for Theobroma Systems UCAN devices, Protocol Version 3
0004  *
0005  * Copyright (C) 2018 Theobroma Systems Design und Consulting GmbH
0006  *
0007  *
0008  * General Description:
0009  *
0010  * The USB Device uses three Endpoints:
0011  *
0012  *   CONTROL Endpoint: Is used the setup the device (start, stop,
0013  *   info, configure).
0014  *
0015  *   IN Endpoint: The device sends CAN Frame Messages and Device
0016  *   Information using the IN endpoint.
0017  *
0018  *   OUT Endpoint: The driver sends configuration requests, and CAN
0019  *   Frames on the out endpoint.
0020  *
0021  * Error Handling:
0022  *
0023  *   If error reporting is turned on the device encodes error into CAN
0024  *   error frames (see uapi/linux/can/error.h) and sends it using the
0025  *   IN Endpoint. The driver updates statistics and forward it.
0026  */
0027 
0028 #include <linux/can.h>
0029 #include <linux/can/dev.h>
0030 #include <linux/can/error.h>
0031 #include <linux/ethtool.h>
0032 #include <linux/module.h>
0033 #include <linux/netdevice.h>
0034 #include <linux/signal.h>
0035 #include <linux/skbuff.h>
0036 #include <linux/slab.h>
0037 #include <linux/usb.h>
0038 
0039 #define UCAN_DRIVER_NAME "ucan"
0040 #define UCAN_MAX_RX_URBS 8
0041 /* the CAN controller needs a while to enable/disable the bus */
0042 #define UCAN_USB_CTL_PIPE_TIMEOUT 1000
0043 /* this driver currently supports protocol version 3 only */
0044 #define UCAN_PROTOCOL_VERSION_MIN 3
0045 #define UCAN_PROTOCOL_VERSION_MAX 3
0046 
0047 /* UCAN Message Definitions
0048  * ------------------------
0049  *
0050  *  ucan_message_out_t and ucan_message_in_t define the messages
0051  *  transmitted on the OUT and IN endpoint.
0052  *
0053  *  Multibyte fields are transmitted with little endianness
0054  *
0055  *  INTR Endpoint: a single uint32_t storing the current space in the fifo
0056  *
0057  *  OUT Endpoint: single message of type ucan_message_out_t is
0058  *    transmitted on the out endpoint
0059  *
0060  *  IN Endpoint: multiple messages ucan_message_in_t concateted in
0061  *    the following way:
0062  *
0063  *  m[n].len <=> the length if message n(including the header in bytes)
0064  *  m[n] is is aligned to a 4 byte boundary, hence
0065  *    offset(m[0])   := 0;
0066  *    offset(m[n+1]) := offset(m[n]) + (m[n].len + 3) & 3
0067  *
0068  *  this implies that
0069  *    offset(m[n]) % 4 <=> 0
0070  */
0071 
0072 /* Device Global Commands */
0073 enum {
0074     UCAN_DEVICE_GET_FW_STRING = 0,
0075 };
0076 
0077 /* UCAN Commands */
0078 enum {
0079     /* start the can transceiver - val defines the operation mode */
0080     UCAN_COMMAND_START = 0,
0081     /* cancel pending transmissions and stop the can transceiver */
0082     UCAN_COMMAND_STOP = 1,
0083     /* send can transceiver into low-power sleep mode */
0084     UCAN_COMMAND_SLEEP = 2,
0085     /* wake up can transceiver from low-power sleep mode */
0086     UCAN_COMMAND_WAKEUP = 3,
0087     /* reset the can transceiver */
0088     UCAN_COMMAND_RESET = 4,
0089     /* get piece of info from the can transceiver - subcmd defines what
0090      * piece
0091      */
0092     UCAN_COMMAND_GET = 5,
0093     /* clear or disable hardware filter - subcmd defines which of the two */
0094     UCAN_COMMAND_FILTER = 6,
0095     /* Setup bittiming */
0096     UCAN_COMMAND_SET_BITTIMING = 7,
0097     /* recover from bus-off state */
0098     UCAN_COMMAND_RESTART = 8,
0099 };
0100 
0101 /* UCAN_COMMAND_START and UCAN_COMMAND_GET_INFO operation modes (bitmap).
0102  * Undefined bits must be set to 0.
0103  */
0104 enum {
0105     UCAN_MODE_LOOPBACK = BIT(0),
0106     UCAN_MODE_SILENT = BIT(1),
0107     UCAN_MODE_3_SAMPLES = BIT(2),
0108     UCAN_MODE_ONE_SHOT = BIT(3),
0109     UCAN_MODE_BERR_REPORT = BIT(4),
0110 };
0111 
0112 /* UCAN_COMMAND_GET subcommands */
0113 enum {
0114     UCAN_COMMAND_GET_INFO = 0,
0115     UCAN_COMMAND_GET_PROTOCOL_VERSION = 1,
0116 };
0117 
0118 /* UCAN_COMMAND_FILTER subcommands */
0119 enum {
0120     UCAN_FILTER_CLEAR = 0,
0121     UCAN_FILTER_DISABLE = 1,
0122     UCAN_FILTER_ENABLE = 2,
0123 };
0124 
0125 /* OUT endpoint message types */
0126 enum {
0127     UCAN_OUT_TX = 2,     /* transmit a CAN frame */
0128 };
0129 
0130 /* IN endpoint message types */
0131 enum {
0132     UCAN_IN_TX_COMPLETE = 1,  /* CAN frame transmission completed */
0133     UCAN_IN_RX = 2,           /* CAN frame received */
0134 };
0135 
0136 struct ucan_ctl_cmd_start {
0137     __le16 mode;         /* OR-ing any of UCAN_MODE_* */
0138 } __packed;
0139 
0140 struct ucan_ctl_cmd_set_bittiming {
0141     __le32 tq;           /* Time quanta (TQ) in nanoseconds */
0142     __le16 brp;          /* TQ Prescaler */
0143     __le16 sample_point; /* Samplepoint on tenth percent */
0144     u8 prop_seg;         /* Propagation segment in TQs */
0145     u8 phase_seg1;       /* Phase buffer segment 1 in TQs */
0146     u8 phase_seg2;       /* Phase buffer segment 2 in TQs */
0147     u8 sjw;              /* Synchronisation jump width in TQs */
0148 } __packed;
0149 
0150 struct ucan_ctl_cmd_device_info {
0151     __le32 freq;         /* Clock Frequency for tq generation */
0152     u8 tx_fifo;          /* Size of the transmission fifo */
0153     u8 sjw_max;          /* can_bittiming fields... */
0154     u8 tseg1_min;
0155     u8 tseg1_max;
0156     u8 tseg2_min;
0157     u8 tseg2_max;
0158     __le16 brp_inc;
0159     __le32 brp_min;
0160     __le32 brp_max;      /* ...can_bittiming fields */
0161     __le16 ctrlmodes;    /* supported control modes */
0162     __le16 hwfilter;     /* Number of HW filter banks */
0163     __le16 rxmboxes;     /* Number of receive Mailboxes */
0164 } __packed;
0165 
0166 struct ucan_ctl_cmd_get_protocol_version {
0167     __le32 version;
0168 } __packed;
0169 
0170 union ucan_ctl_payload {
0171     /* Setup Bittiming
0172      * bmRequest == UCAN_COMMAND_START
0173      */
0174     struct ucan_ctl_cmd_start cmd_start;
0175     /* Setup Bittiming
0176      * bmRequest == UCAN_COMMAND_SET_BITTIMING
0177      */
0178     struct ucan_ctl_cmd_set_bittiming cmd_set_bittiming;
0179     /* Get Device Information
0180      * bmRequest == UCAN_COMMAND_GET; wValue = UCAN_COMMAND_GET_INFO
0181      */
0182     struct ucan_ctl_cmd_device_info cmd_get_device_info;
0183     /* Get Protocol Version
0184      * bmRequest == UCAN_COMMAND_GET;
0185      * wValue = UCAN_COMMAND_GET_PROTOCOL_VERSION
0186      */
0187     struct ucan_ctl_cmd_get_protocol_version cmd_get_protocol_version;
0188 
0189     u8 raw[128];
0190 } __packed;
0191 
0192 enum {
0193     UCAN_TX_COMPLETE_SUCCESS = BIT(0),
0194 };
0195 
0196 /* Transmission Complete within ucan_message_in */
0197 struct ucan_tx_complete_entry_t {
0198     u8 echo_index;
0199     u8 flags;
0200 } __packed __aligned(0x2);
0201 
0202 /* CAN Data message format within ucan_message_in/out */
0203 struct ucan_can_msg {
0204     /* note DLC is computed by
0205      *    msg.len - sizeof (msg.len)
0206      *            - sizeof (msg.type)
0207      *            - sizeof (msg.can_msg.id)
0208      */
0209     __le32 id;
0210 
0211     union {
0212         u8 data[CAN_MAX_DLEN];  /* Data of CAN frames */
0213         u8 dlc;                 /* RTR dlc */
0214     };
0215 } __packed;
0216 
0217 /* OUT Endpoint, outbound messages */
0218 struct ucan_message_out {
0219     __le16 len; /* Length of the content include header */
0220     u8 type;    /* UCAN_OUT_TX and friends */
0221     u8 subtype; /* command sub type */
0222 
0223     union {
0224         /* Transmit CAN frame
0225          * (type == UCAN_TX) && ((msg.can_msg.id & CAN_RTR_FLAG) == 0)
0226          * subtype stores the echo id
0227          */
0228         struct ucan_can_msg can_msg;
0229     } msg;
0230 } __packed __aligned(0x4);
0231 
0232 /* IN Endpoint, inbound messages */
0233 struct ucan_message_in {
0234     __le16 len; /* Length of the content include header */
0235     u8 type;    /* UCAN_IN_RX and friends */
0236     u8 subtype; /* command sub type */
0237 
0238     union {
0239         /* CAN Frame received
0240          * (type == UCAN_IN_RX)
0241          * && ((msg.can_msg.id & CAN_RTR_FLAG) == 0)
0242          */
0243         struct ucan_can_msg can_msg;
0244 
0245         /* CAN transmission complete
0246          * (type == UCAN_IN_TX_COMPLETE)
0247          */
0248         struct ucan_tx_complete_entry_t can_tx_complete_msg[0];
0249     } __aligned(0x4) msg;
0250 } __packed __aligned(0x4);
0251 
0252 /* Macros to calculate message lengths */
0253 #define UCAN_OUT_HDR_SIZE offsetof(struct ucan_message_out, msg)
0254 
0255 #define UCAN_IN_HDR_SIZE offsetof(struct ucan_message_in, msg)
0256 #define UCAN_IN_LEN(member) (UCAN_OUT_HDR_SIZE + sizeof(member))
0257 
0258 struct ucan_priv;
0259 
0260 /* Context Information for transmission URBs */
0261 struct ucan_urb_context {
0262     struct ucan_priv *up;
0263     bool allocated;
0264 };
0265 
0266 /* Information reported by the USB device */
0267 struct ucan_device_info {
0268     struct can_bittiming_const bittiming_const;
0269     u8 tx_fifo;
0270 };
0271 
0272 /* Driver private data */
0273 struct ucan_priv {
0274     /* must be the first member */
0275     struct can_priv can;
0276 
0277     /* linux USB device structures */
0278     struct usb_device *udev;
0279     struct usb_interface *intf;
0280     struct net_device *netdev;
0281 
0282     /* lock for can->echo_skb (used around
0283      * can_put/get/free_echo_skb
0284      */
0285     spinlock_t echo_skb_lock;
0286 
0287     /* usb device information information */
0288     u8 intf_index;
0289     u8 in_ep_addr;
0290     u8 out_ep_addr;
0291     u16 in_ep_size;
0292 
0293     /* transmission and reception buffers */
0294     struct usb_anchor rx_urbs;
0295     struct usb_anchor tx_urbs;
0296 
0297     union ucan_ctl_payload *ctl_msg_buffer;
0298     struct ucan_device_info device_info;
0299 
0300     /* transmission control information and locks */
0301     spinlock_t context_lock;
0302     unsigned int available_tx_urbs;
0303     struct ucan_urb_context *context_array;
0304 };
0305 
0306 static u8 ucan_can_cc_dlc2len(struct ucan_can_msg *msg, u16 len)
0307 {
0308     if (le32_to_cpu(msg->id) & CAN_RTR_FLAG)
0309         return can_cc_dlc2len(msg->dlc);
0310     else
0311         return can_cc_dlc2len(len - (UCAN_IN_HDR_SIZE + sizeof(msg->id)));
0312 }
0313 
0314 static void ucan_release_context_array(struct ucan_priv *up)
0315 {
0316     if (!up->context_array)
0317         return;
0318 
0319     /* lock is not needed because, driver is currently opening or closing */
0320     up->available_tx_urbs = 0;
0321 
0322     kfree(up->context_array);
0323     up->context_array = NULL;
0324 }
0325 
0326 static int ucan_alloc_context_array(struct ucan_priv *up)
0327 {
0328     int i;
0329 
0330     /* release contexts if any */
0331     ucan_release_context_array(up);
0332 
0333     up->context_array = kcalloc(up->device_info.tx_fifo,
0334                     sizeof(*up->context_array),
0335                     GFP_KERNEL);
0336     if (!up->context_array) {
0337         netdev_err(up->netdev,
0338                "Not enough memory to allocate tx contexts\n");
0339         return -ENOMEM;
0340     }
0341 
0342     for (i = 0; i < up->device_info.tx_fifo; i++) {
0343         up->context_array[i].allocated = false;
0344         up->context_array[i].up = up;
0345     }
0346 
0347     /* lock is not needed because, driver is currently opening */
0348     up->available_tx_urbs = up->device_info.tx_fifo;
0349 
0350     return 0;
0351 }
0352 
0353 static struct ucan_urb_context *ucan_alloc_context(struct ucan_priv *up)
0354 {
0355     int i;
0356     unsigned long flags;
0357     struct ucan_urb_context *ret = NULL;
0358 
0359     if (WARN_ON_ONCE(!up->context_array))
0360         return NULL;
0361 
0362     /* execute context operation atomically */
0363     spin_lock_irqsave(&up->context_lock, flags);
0364 
0365     for (i = 0; i < up->device_info.tx_fifo; i++) {
0366         if (!up->context_array[i].allocated) {
0367             /* update context */
0368             ret = &up->context_array[i];
0369             up->context_array[i].allocated = true;
0370 
0371             /* stop queue if necessary */
0372             up->available_tx_urbs--;
0373             if (!up->available_tx_urbs)
0374                 netif_stop_queue(up->netdev);
0375 
0376             break;
0377         }
0378     }
0379 
0380     spin_unlock_irqrestore(&up->context_lock, flags);
0381     return ret;
0382 }
0383 
0384 static bool ucan_release_context(struct ucan_priv *up,
0385                  struct ucan_urb_context *ctx)
0386 {
0387     unsigned long flags;
0388     bool ret = false;
0389 
0390     if (WARN_ON_ONCE(!up->context_array))
0391         return false;
0392 
0393     /* execute context operation atomically */
0394     spin_lock_irqsave(&up->context_lock, flags);
0395 
0396     /* context was not allocated, maybe the device sent garbage */
0397     if (ctx->allocated) {
0398         ctx->allocated = false;
0399 
0400         /* check if the queue needs to be woken */
0401         if (!up->available_tx_urbs)
0402             netif_wake_queue(up->netdev);
0403         up->available_tx_urbs++;
0404 
0405         ret = true;
0406     }
0407 
0408     spin_unlock_irqrestore(&up->context_lock, flags);
0409     return ret;
0410 }
0411 
0412 static int ucan_ctrl_command_out(struct ucan_priv *up,
0413                  u8 cmd, u16 subcmd, u16 datalen)
0414 {
0415     return usb_control_msg(up->udev,
0416                    usb_sndctrlpipe(up->udev, 0),
0417                    cmd,
0418                    USB_DIR_OUT | USB_TYPE_VENDOR |
0419                         USB_RECIP_INTERFACE,
0420                    subcmd,
0421                    up->intf_index,
0422                    up->ctl_msg_buffer,
0423                    datalen,
0424                    UCAN_USB_CTL_PIPE_TIMEOUT);
0425 }
0426 
0427 static int ucan_device_request_in(struct ucan_priv *up,
0428                   u8 cmd, u16 subcmd, u16 datalen)
0429 {
0430     return usb_control_msg(up->udev,
0431                    usb_rcvctrlpipe(up->udev, 0),
0432                    cmd,
0433                    USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
0434                    subcmd,
0435                    0,
0436                    up->ctl_msg_buffer,
0437                    datalen,
0438                    UCAN_USB_CTL_PIPE_TIMEOUT);
0439 }
0440 
0441 /* Parse the device information structure reported by the device and
0442  * setup private variables accordingly
0443  */
0444 static void ucan_parse_device_info(struct ucan_priv *up,
0445                    struct ucan_ctl_cmd_device_info *device_info)
0446 {
0447     struct can_bittiming_const *bittiming =
0448         &up->device_info.bittiming_const;
0449     u16 ctrlmodes;
0450 
0451     /* store the data */
0452     up->can.clock.freq = le32_to_cpu(device_info->freq);
0453     up->device_info.tx_fifo = device_info->tx_fifo;
0454     strcpy(bittiming->name, "ucan");
0455     bittiming->tseg1_min = device_info->tseg1_min;
0456     bittiming->tseg1_max = device_info->tseg1_max;
0457     bittiming->tseg2_min = device_info->tseg2_min;
0458     bittiming->tseg2_max = device_info->tseg2_max;
0459     bittiming->sjw_max = device_info->sjw_max;
0460     bittiming->brp_min = le32_to_cpu(device_info->brp_min);
0461     bittiming->brp_max = le32_to_cpu(device_info->brp_max);
0462     bittiming->brp_inc = le16_to_cpu(device_info->brp_inc);
0463 
0464     ctrlmodes = le16_to_cpu(device_info->ctrlmodes);
0465 
0466     up->can.ctrlmode_supported = 0;
0467 
0468     if (ctrlmodes & UCAN_MODE_LOOPBACK)
0469         up->can.ctrlmode_supported |= CAN_CTRLMODE_LOOPBACK;
0470     if (ctrlmodes & UCAN_MODE_SILENT)
0471         up->can.ctrlmode_supported |= CAN_CTRLMODE_LISTENONLY;
0472     if (ctrlmodes & UCAN_MODE_3_SAMPLES)
0473         up->can.ctrlmode_supported |= CAN_CTRLMODE_3_SAMPLES;
0474     if (ctrlmodes & UCAN_MODE_ONE_SHOT)
0475         up->can.ctrlmode_supported |= CAN_CTRLMODE_ONE_SHOT;
0476     if (ctrlmodes & UCAN_MODE_BERR_REPORT)
0477         up->can.ctrlmode_supported |= CAN_CTRLMODE_BERR_REPORTING;
0478 }
0479 
0480 /* Handle a CAN error frame that we have received from the device.
0481  * Returns true if the can state has changed.
0482  */
0483 static bool ucan_handle_error_frame(struct ucan_priv *up,
0484                     struct ucan_message_in *m,
0485                     canid_t canid)
0486 {
0487     enum can_state new_state = up->can.state;
0488     struct net_device_stats *net_stats = &up->netdev->stats;
0489     struct can_device_stats *can_stats = &up->can.can_stats;
0490 
0491     if (canid & CAN_ERR_LOSTARB)
0492         can_stats->arbitration_lost++;
0493 
0494     if (canid & CAN_ERR_BUSERROR)
0495         can_stats->bus_error++;
0496 
0497     if (canid & CAN_ERR_ACK)
0498         net_stats->tx_errors++;
0499 
0500     if (canid & CAN_ERR_BUSOFF)
0501         new_state = CAN_STATE_BUS_OFF;
0502 
0503     /* controller problems, details in data[1] */
0504     if (canid & CAN_ERR_CRTL) {
0505         u8 d1 = m->msg.can_msg.data[1];
0506 
0507         if (d1 & CAN_ERR_CRTL_RX_OVERFLOW)
0508             net_stats->rx_over_errors++;
0509 
0510         /* controller state bits: if multiple are set the worst wins */
0511         if (d1 & CAN_ERR_CRTL_ACTIVE)
0512             new_state = CAN_STATE_ERROR_ACTIVE;
0513 
0514         if (d1 & (CAN_ERR_CRTL_RX_WARNING | CAN_ERR_CRTL_TX_WARNING))
0515             new_state = CAN_STATE_ERROR_WARNING;
0516 
0517         if (d1 & (CAN_ERR_CRTL_RX_PASSIVE | CAN_ERR_CRTL_TX_PASSIVE))
0518             new_state = CAN_STATE_ERROR_PASSIVE;
0519     }
0520 
0521     /* protocol error, details in data[2] */
0522     if (canid & CAN_ERR_PROT) {
0523         u8 d2 = m->msg.can_msg.data[2];
0524 
0525         if (d2 & CAN_ERR_PROT_TX)
0526             net_stats->tx_errors++;
0527         else
0528             net_stats->rx_errors++;
0529     }
0530 
0531     /* no state change - we are done */
0532     if (up->can.state == new_state)
0533         return false;
0534 
0535     /* we switched into a better state */
0536     if (up->can.state > new_state) {
0537         up->can.state = new_state;
0538         return true;
0539     }
0540 
0541     /* we switched into a worse state */
0542     up->can.state = new_state;
0543     switch (new_state) {
0544     case CAN_STATE_BUS_OFF:
0545         can_stats->bus_off++;
0546         can_bus_off(up->netdev);
0547         break;
0548     case CAN_STATE_ERROR_PASSIVE:
0549         can_stats->error_passive++;
0550         break;
0551     case CAN_STATE_ERROR_WARNING:
0552         can_stats->error_warning++;
0553         break;
0554     default:
0555         break;
0556     }
0557     return true;
0558 }
0559 
0560 /* Callback on reception of a can frame via the IN endpoint
0561  *
0562  * This function allocates an skb and transferres it to the Linux
0563  * network stack
0564  */
0565 static void ucan_rx_can_msg(struct ucan_priv *up, struct ucan_message_in *m)
0566 {
0567     int len;
0568     canid_t canid;
0569     struct can_frame *cf;
0570     struct sk_buff *skb;
0571     struct net_device_stats *stats = &up->netdev->stats;
0572 
0573     /* get the contents of the length field */
0574     len = le16_to_cpu(m->len);
0575 
0576     /* check sanity */
0577     if (len < UCAN_IN_HDR_SIZE + sizeof(m->msg.can_msg.id)) {
0578         netdev_warn(up->netdev, "invalid input message len: %d\n", len);
0579         return;
0580     }
0581 
0582     /* handle error frames */
0583     canid = le32_to_cpu(m->msg.can_msg.id);
0584     if (canid & CAN_ERR_FLAG) {
0585         bool busstate_changed = ucan_handle_error_frame(up, m, canid);
0586 
0587         /* if berr-reporting is off only state changes get through */
0588         if (!(up->can.ctrlmode & CAN_CTRLMODE_BERR_REPORTING) &&
0589             !busstate_changed)
0590             return;
0591     } else {
0592         canid_t canid_mask;
0593         /* compute the mask for canid */
0594         canid_mask = CAN_RTR_FLAG;
0595         if (canid & CAN_EFF_FLAG)
0596             canid_mask |= CAN_EFF_MASK | CAN_EFF_FLAG;
0597         else
0598             canid_mask |= CAN_SFF_MASK;
0599 
0600         if (canid & ~canid_mask)
0601             netdev_warn(up->netdev,
0602                     "unexpected bits set (canid %x, mask %x)",
0603                     canid, canid_mask);
0604 
0605         canid &= canid_mask;
0606     }
0607 
0608     /* allocate skb */
0609     skb = alloc_can_skb(up->netdev, &cf);
0610     if (!skb)
0611         return;
0612 
0613     /* fill the can frame */
0614     cf->can_id = canid;
0615 
0616     /* compute DLC taking RTR_FLAG into account */
0617     cf->len = ucan_can_cc_dlc2len(&m->msg.can_msg, len);
0618 
0619     /* copy the payload of non RTR frames */
0620     if (!(cf->can_id & CAN_RTR_FLAG) || (cf->can_id & CAN_ERR_FLAG))
0621         memcpy(cf->data, m->msg.can_msg.data, cf->len);
0622 
0623     /* don't count error frames as real packets */
0624     if (!(cf->can_id & CAN_ERR_FLAG)) {
0625         stats->rx_packets++;
0626         if (!(cf->can_id & CAN_RTR_FLAG))
0627             stats->rx_bytes += cf->len;
0628     }
0629 
0630     /* pass it to Linux */
0631     netif_rx(skb);
0632 }
0633 
0634 /* callback indicating completed transmission */
0635 static void ucan_tx_complete_msg(struct ucan_priv *up,
0636                  struct ucan_message_in *m)
0637 {
0638     unsigned long flags;
0639     u16 count, i;
0640     u8 echo_index;
0641     u16 len = le16_to_cpu(m->len);
0642 
0643     struct ucan_urb_context *context;
0644 
0645     if (len < UCAN_IN_HDR_SIZE || (len % 2 != 0)) {
0646         netdev_err(up->netdev, "invalid tx complete length\n");
0647         return;
0648     }
0649 
0650     count = (len - UCAN_IN_HDR_SIZE) / 2;
0651     for (i = 0; i < count; i++) {
0652         /* we did not submit such echo ids */
0653         echo_index = m->msg.can_tx_complete_msg[i].echo_index;
0654         if (echo_index >= up->device_info.tx_fifo) {
0655             up->netdev->stats.tx_errors++;
0656             netdev_err(up->netdev,
0657                    "invalid echo_index %d received\n",
0658                    echo_index);
0659             continue;
0660         }
0661 
0662         /* gather information from the context */
0663         context = &up->context_array[echo_index];
0664 
0665         /* Release context and restart queue if necessary.
0666          * Also check if the context was allocated
0667          */
0668         if (!ucan_release_context(up, context))
0669             continue;
0670 
0671         spin_lock_irqsave(&up->echo_skb_lock, flags);
0672         if (m->msg.can_tx_complete_msg[i].flags &
0673             UCAN_TX_COMPLETE_SUCCESS) {
0674             /* update statistics */
0675             up->netdev->stats.tx_packets++;
0676             up->netdev->stats.tx_bytes +=
0677                 can_get_echo_skb(up->netdev, echo_index, NULL);
0678         } else {
0679             up->netdev->stats.tx_dropped++;
0680             can_free_echo_skb(up->netdev, echo_index, NULL);
0681         }
0682         spin_unlock_irqrestore(&up->echo_skb_lock, flags);
0683     }
0684 }
0685 
0686 /* callback on reception of a USB message */
0687 static void ucan_read_bulk_callback(struct urb *urb)
0688 {
0689     int ret;
0690     int pos;
0691     struct ucan_priv *up = urb->context;
0692     struct net_device *netdev = up->netdev;
0693     struct ucan_message_in *m;
0694 
0695     /* the device is not up and the driver should not receive any
0696      * data on the bulk in pipe
0697      */
0698     if (WARN_ON(!up->context_array)) {
0699         usb_free_coherent(up->udev,
0700                   up->in_ep_size,
0701                   urb->transfer_buffer,
0702                   urb->transfer_dma);
0703         return;
0704     }
0705 
0706     /* check URB status */
0707     switch (urb->status) {
0708     case 0:
0709         break;
0710     case -ENOENT:
0711     case -EPIPE:
0712     case -EPROTO:
0713     case -ESHUTDOWN:
0714     case -ETIME:
0715         /* urb is not resubmitted -> free dma data */
0716         usb_free_coherent(up->udev,
0717                   up->in_ep_size,
0718                   urb->transfer_buffer,
0719                   urb->transfer_dma);
0720         netdev_dbg(up->netdev, "not resubmitting urb; status: %d\n",
0721                urb->status);
0722         return;
0723     default:
0724         goto resubmit;
0725     }
0726 
0727     /* sanity check */
0728     if (!netif_device_present(netdev))
0729         return;
0730 
0731     /* iterate over input */
0732     pos = 0;
0733     while (pos < urb->actual_length) {
0734         int len;
0735 
0736         /* check sanity (length of header) */
0737         if ((urb->actual_length - pos) < UCAN_IN_HDR_SIZE) {
0738             netdev_warn(up->netdev,
0739                     "invalid message (short; no hdr; l:%d)\n",
0740                     urb->actual_length);
0741             goto resubmit;
0742         }
0743 
0744         /* setup the message address */
0745         m = (struct ucan_message_in *)
0746             ((u8 *)urb->transfer_buffer + pos);
0747         len = le16_to_cpu(m->len);
0748 
0749         /* check sanity (length of content) */
0750         if (urb->actual_length - pos < len) {
0751             netdev_warn(up->netdev,
0752                     "invalid message (short; no data; l:%d)\n",
0753                     urb->actual_length);
0754             print_hex_dump(KERN_WARNING,
0755                        "raw data: ",
0756                        DUMP_PREFIX_ADDRESS,
0757                        16,
0758                        1,
0759                        urb->transfer_buffer,
0760                        urb->actual_length,
0761                        true);
0762 
0763             goto resubmit;
0764         }
0765 
0766         switch (m->type) {
0767         case UCAN_IN_RX:
0768             ucan_rx_can_msg(up, m);
0769             break;
0770         case UCAN_IN_TX_COMPLETE:
0771             ucan_tx_complete_msg(up, m);
0772             break;
0773         default:
0774             netdev_warn(up->netdev,
0775                     "invalid message (type; t:%d)\n",
0776                     m->type);
0777             break;
0778         }
0779 
0780         /* proceed to next message */
0781         pos += len;
0782         /* align to 4 byte boundary */
0783         pos = round_up(pos, 4);
0784     }
0785 
0786 resubmit:
0787     /* resubmit urb when done */
0788     usb_fill_bulk_urb(urb, up->udev,
0789               usb_rcvbulkpipe(up->udev,
0790                       up->in_ep_addr),
0791               urb->transfer_buffer,
0792               up->in_ep_size,
0793               ucan_read_bulk_callback,
0794               up);
0795 
0796     usb_anchor_urb(urb, &up->rx_urbs);
0797     ret = usb_submit_urb(urb, GFP_ATOMIC);
0798 
0799     if (ret < 0) {
0800         netdev_err(up->netdev,
0801                "failed resubmitting read bulk urb: %d\n",
0802                ret);
0803 
0804         usb_unanchor_urb(urb);
0805         usb_free_coherent(up->udev,
0806                   up->in_ep_size,
0807                   urb->transfer_buffer,
0808                   urb->transfer_dma);
0809 
0810         if (ret == -ENODEV)
0811             netif_device_detach(netdev);
0812     }
0813 }
0814 
0815 /* callback after transmission of a USB message */
0816 static void ucan_write_bulk_callback(struct urb *urb)
0817 {
0818     unsigned long flags;
0819     struct ucan_priv *up;
0820     struct ucan_urb_context *context = urb->context;
0821 
0822     /* get the urb context */
0823     if (WARN_ON_ONCE(!context))
0824         return;
0825 
0826     /* free up our allocated buffer */
0827     usb_free_coherent(urb->dev,
0828               sizeof(struct ucan_message_out),
0829               urb->transfer_buffer,
0830               urb->transfer_dma);
0831 
0832     up = context->up;
0833     if (WARN_ON_ONCE(!up))
0834         return;
0835 
0836     /* sanity check */
0837     if (!netif_device_present(up->netdev))
0838         return;
0839 
0840     /* transmission failed (USB - the device will not send a TX complete) */
0841     if (urb->status) {
0842         netdev_warn(up->netdev,
0843                 "failed to transmit USB message to device: %d\n",
0844                  urb->status);
0845 
0846         /* update counters an cleanup */
0847         spin_lock_irqsave(&up->echo_skb_lock, flags);
0848         can_free_echo_skb(up->netdev, context - up->context_array, NULL);
0849         spin_unlock_irqrestore(&up->echo_skb_lock, flags);
0850 
0851         up->netdev->stats.tx_dropped++;
0852 
0853         /* release context and restart the queue if necessary */
0854         if (!ucan_release_context(up, context))
0855             netdev_err(up->netdev,
0856                    "urb failed, failed to release context\n");
0857     }
0858 }
0859 
0860 static void ucan_cleanup_rx_urbs(struct ucan_priv *up, struct urb **urbs)
0861 {
0862     int i;
0863 
0864     for (i = 0; i < UCAN_MAX_RX_URBS; i++) {
0865         if (urbs[i]) {
0866             usb_unanchor_urb(urbs[i]);
0867             usb_free_coherent(up->udev,
0868                       up->in_ep_size,
0869                       urbs[i]->transfer_buffer,
0870                       urbs[i]->transfer_dma);
0871             usb_free_urb(urbs[i]);
0872         }
0873     }
0874 
0875     memset(urbs, 0, sizeof(*urbs) * UCAN_MAX_RX_URBS);
0876 }
0877 
0878 static int ucan_prepare_and_anchor_rx_urbs(struct ucan_priv *up,
0879                        struct urb **urbs)
0880 {
0881     int i;
0882 
0883     memset(urbs, 0, sizeof(*urbs) * UCAN_MAX_RX_URBS);
0884 
0885     for (i = 0; i < UCAN_MAX_RX_URBS; i++) {
0886         void *buf;
0887 
0888         urbs[i] = usb_alloc_urb(0, GFP_KERNEL);
0889         if (!urbs[i])
0890             goto err;
0891 
0892         buf = usb_alloc_coherent(up->udev,
0893                      up->in_ep_size,
0894                      GFP_KERNEL, &urbs[i]->transfer_dma);
0895         if (!buf) {
0896             /* cleanup this urb */
0897             usb_free_urb(urbs[i]);
0898             urbs[i] = NULL;
0899             goto err;
0900         }
0901 
0902         usb_fill_bulk_urb(urbs[i], up->udev,
0903                   usb_rcvbulkpipe(up->udev,
0904                           up->in_ep_addr),
0905                   buf,
0906                   up->in_ep_size,
0907                   ucan_read_bulk_callback,
0908                   up);
0909 
0910         urbs[i]->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
0911 
0912         usb_anchor_urb(urbs[i], &up->rx_urbs);
0913     }
0914     return 0;
0915 
0916 err:
0917     /* cleanup other unsubmitted urbs */
0918     ucan_cleanup_rx_urbs(up, urbs);
0919     return -ENOMEM;
0920 }
0921 
0922 /* Submits rx urbs with the semantic: Either submit all, or cleanup
0923  * everything. I case of errors submitted urbs are killed and all urbs in
0924  * the array are freed. I case of no errors every entry in the urb
0925  * array is set to NULL.
0926  */
0927 static int ucan_submit_rx_urbs(struct ucan_priv *up, struct urb **urbs)
0928 {
0929     int i, ret;
0930 
0931     /* Iterate over all urbs to submit. On success remove the urb
0932      * from the list.
0933      */
0934     for (i = 0; i < UCAN_MAX_RX_URBS; i++) {
0935         ret = usb_submit_urb(urbs[i], GFP_KERNEL);
0936         if (ret) {
0937             netdev_err(up->netdev,
0938                    "could not submit urb; code: %d\n",
0939                    ret);
0940             goto err;
0941         }
0942 
0943         /* Anchor URB and drop reference, USB core will take
0944          * care of freeing it
0945          */
0946         usb_free_urb(urbs[i]);
0947         urbs[i] = NULL;
0948     }
0949     return 0;
0950 
0951 err:
0952     /* Cleanup unsubmitted urbs */
0953     ucan_cleanup_rx_urbs(up, urbs);
0954 
0955     /* Kill urbs that are already submitted */
0956     usb_kill_anchored_urbs(&up->rx_urbs);
0957 
0958     return ret;
0959 }
0960 
0961 /* Open the network device */
0962 static int ucan_open(struct net_device *netdev)
0963 {
0964     int ret, ret_cleanup;
0965     u16 ctrlmode;
0966     struct urb *urbs[UCAN_MAX_RX_URBS];
0967     struct ucan_priv *up = netdev_priv(netdev);
0968 
0969     ret = ucan_alloc_context_array(up);
0970     if (ret)
0971         return ret;
0972 
0973     /* Allocate and prepare IN URBS - allocated and anchored
0974      * urbs are stored in urbs[] for clean
0975      */
0976     ret = ucan_prepare_and_anchor_rx_urbs(up, urbs);
0977     if (ret)
0978         goto err_contexts;
0979 
0980     /* Check the control mode */
0981     ctrlmode = 0;
0982     if (up->can.ctrlmode & CAN_CTRLMODE_LOOPBACK)
0983         ctrlmode |= UCAN_MODE_LOOPBACK;
0984     if (up->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)
0985         ctrlmode |= UCAN_MODE_SILENT;
0986     if (up->can.ctrlmode & CAN_CTRLMODE_3_SAMPLES)
0987         ctrlmode |= UCAN_MODE_3_SAMPLES;
0988     if (up->can.ctrlmode & CAN_CTRLMODE_ONE_SHOT)
0989         ctrlmode |= UCAN_MODE_ONE_SHOT;
0990 
0991     /* Enable this in any case - filtering is down within the
0992      * receive path
0993      */
0994     ctrlmode |= UCAN_MODE_BERR_REPORT;
0995     up->ctl_msg_buffer->cmd_start.mode = cpu_to_le16(ctrlmode);
0996 
0997     /* Driver is ready to receive data - start the USB device */
0998     ret = ucan_ctrl_command_out(up, UCAN_COMMAND_START, 0, 2);
0999     if (ret < 0) {
1000         netdev_err(up->netdev,
1001                "could not start device, code: %d\n",
1002                ret);
1003         goto err_reset;
1004     }
1005 
1006     /* Call CAN layer open */
1007     ret = open_candev(netdev);
1008     if (ret)
1009         goto err_stop;
1010 
1011     /* Driver is ready to receive data. Submit RX URBS */
1012     ret = ucan_submit_rx_urbs(up, urbs);
1013     if (ret)
1014         goto err_stop;
1015 
1016     up->can.state = CAN_STATE_ERROR_ACTIVE;
1017 
1018     /* Start the network queue */
1019     netif_start_queue(netdev);
1020 
1021     return 0;
1022 
1023 err_stop:
1024     /* The device have started already stop it */
1025     ret_cleanup = ucan_ctrl_command_out(up, UCAN_COMMAND_STOP, 0, 0);
1026     if (ret_cleanup < 0)
1027         netdev_err(up->netdev,
1028                "could not stop device, code: %d\n",
1029                ret_cleanup);
1030 
1031 err_reset:
1032     /* The device might have received data, reset it for
1033      * consistent state
1034      */
1035     ret_cleanup = ucan_ctrl_command_out(up, UCAN_COMMAND_RESET, 0, 0);
1036     if (ret_cleanup < 0)
1037         netdev_err(up->netdev,
1038                "could not reset device, code: %d\n",
1039                ret_cleanup);
1040 
1041     /* clean up unsubmitted urbs */
1042     ucan_cleanup_rx_urbs(up, urbs);
1043 
1044 err_contexts:
1045     ucan_release_context_array(up);
1046     return ret;
1047 }
1048 
1049 static struct urb *ucan_prepare_tx_urb(struct ucan_priv *up,
1050                        struct ucan_urb_context *context,
1051                        struct can_frame *cf,
1052                        u8 echo_index)
1053 {
1054     int mlen;
1055     struct urb *urb;
1056     struct ucan_message_out *m;
1057 
1058     /* create a URB, and a buffer for it, and copy the data to the URB */
1059     urb = usb_alloc_urb(0, GFP_ATOMIC);
1060     if (!urb) {
1061         netdev_err(up->netdev, "no memory left for URBs\n");
1062         return NULL;
1063     }
1064 
1065     m = usb_alloc_coherent(up->udev,
1066                    sizeof(struct ucan_message_out),
1067                    GFP_ATOMIC,
1068                    &urb->transfer_dma);
1069     if (!m) {
1070         netdev_err(up->netdev, "no memory left for USB buffer\n");
1071         usb_free_urb(urb);
1072         return NULL;
1073     }
1074 
1075     /* build the USB message */
1076     m->type = UCAN_OUT_TX;
1077     m->msg.can_msg.id = cpu_to_le32(cf->can_id);
1078 
1079     if (cf->can_id & CAN_RTR_FLAG) {
1080         mlen = UCAN_OUT_HDR_SIZE +
1081             offsetof(struct ucan_can_msg, dlc) +
1082             sizeof(m->msg.can_msg.dlc);
1083         m->msg.can_msg.dlc = cf->len;
1084     } else {
1085         mlen = UCAN_OUT_HDR_SIZE +
1086             sizeof(m->msg.can_msg.id) + cf->len;
1087         memcpy(m->msg.can_msg.data, cf->data, cf->len);
1088     }
1089     m->len = cpu_to_le16(mlen);
1090 
1091     m->subtype = echo_index;
1092 
1093     /* build the urb */
1094     usb_fill_bulk_urb(urb, up->udev,
1095               usb_sndbulkpipe(up->udev,
1096                       up->out_ep_addr),
1097               m, mlen, ucan_write_bulk_callback, context);
1098     urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
1099 
1100     return urb;
1101 }
1102 
1103 static void ucan_clean_up_tx_urb(struct ucan_priv *up, struct urb *urb)
1104 {
1105     usb_free_coherent(up->udev, sizeof(struct ucan_message_out),
1106               urb->transfer_buffer, urb->transfer_dma);
1107     usb_free_urb(urb);
1108 }
1109 
1110 /* callback when Linux needs to send a can frame */
1111 static netdev_tx_t ucan_start_xmit(struct sk_buff *skb,
1112                    struct net_device *netdev)
1113 {
1114     unsigned long flags;
1115     int ret;
1116     u8 echo_index;
1117     struct urb *urb;
1118     struct ucan_urb_context *context;
1119     struct ucan_priv *up = netdev_priv(netdev);
1120     struct can_frame *cf = (struct can_frame *)skb->data;
1121 
1122     /* check skb */
1123     if (can_dropped_invalid_skb(netdev, skb))
1124         return NETDEV_TX_OK;
1125 
1126     /* allocate a context and slow down tx path, if fifo state is low */
1127     context = ucan_alloc_context(up);
1128     echo_index = context - up->context_array;
1129 
1130     if (WARN_ON_ONCE(!context))
1131         return NETDEV_TX_BUSY;
1132 
1133     /* prepare urb for transmission */
1134     urb = ucan_prepare_tx_urb(up, context, cf, echo_index);
1135     if (!urb)
1136         goto drop;
1137 
1138     /* put the skb on can loopback stack */
1139     spin_lock_irqsave(&up->echo_skb_lock, flags);
1140     can_put_echo_skb(skb, up->netdev, echo_index, 0);
1141     spin_unlock_irqrestore(&up->echo_skb_lock, flags);
1142 
1143     /* transmit it */
1144     usb_anchor_urb(urb, &up->tx_urbs);
1145     ret = usb_submit_urb(urb, GFP_ATOMIC);
1146 
1147     /* cleanup urb */
1148     if (ret) {
1149         /* on error, clean up */
1150         usb_unanchor_urb(urb);
1151         ucan_clean_up_tx_urb(up, urb);
1152         if (!ucan_release_context(up, context))
1153             netdev_err(up->netdev,
1154                    "xmit err: failed to release context\n");
1155 
1156         /* remove the skb from the echo stack - this also
1157          * frees the skb
1158          */
1159         spin_lock_irqsave(&up->echo_skb_lock, flags);
1160         can_free_echo_skb(up->netdev, echo_index, NULL);
1161         spin_unlock_irqrestore(&up->echo_skb_lock, flags);
1162 
1163         if (ret == -ENODEV) {
1164             netif_device_detach(up->netdev);
1165         } else {
1166             netdev_warn(up->netdev,
1167                     "xmit err: failed to submit urb %d\n",
1168                     ret);
1169             up->netdev->stats.tx_dropped++;
1170         }
1171         return NETDEV_TX_OK;
1172     }
1173 
1174     netif_trans_update(netdev);
1175 
1176     /* release ref, as we do not need the urb anymore */
1177     usb_free_urb(urb);
1178 
1179     return NETDEV_TX_OK;
1180 
1181 drop:
1182     if (!ucan_release_context(up, context))
1183         netdev_err(up->netdev,
1184                "xmit drop: failed to release context\n");
1185     dev_kfree_skb(skb);
1186     up->netdev->stats.tx_dropped++;
1187 
1188     return NETDEV_TX_OK;
1189 }
1190 
1191 /* Device goes down
1192  *
1193  * Clean up used resources
1194  */
1195 static int ucan_close(struct net_device *netdev)
1196 {
1197     int ret;
1198     struct ucan_priv *up = netdev_priv(netdev);
1199 
1200     up->can.state = CAN_STATE_STOPPED;
1201 
1202     /* stop sending data */
1203     usb_kill_anchored_urbs(&up->tx_urbs);
1204 
1205     /* stop receiving data */
1206     usb_kill_anchored_urbs(&up->rx_urbs);
1207 
1208     /* stop and reset can device */
1209     ret = ucan_ctrl_command_out(up, UCAN_COMMAND_STOP, 0, 0);
1210     if (ret < 0)
1211         netdev_err(up->netdev,
1212                "could not stop device, code: %d\n",
1213                ret);
1214 
1215     ret = ucan_ctrl_command_out(up, UCAN_COMMAND_RESET, 0, 0);
1216     if (ret < 0)
1217         netdev_err(up->netdev,
1218                "could not reset device, code: %d\n",
1219                ret);
1220 
1221     netif_stop_queue(netdev);
1222 
1223     ucan_release_context_array(up);
1224 
1225     close_candev(up->netdev);
1226     return 0;
1227 }
1228 
1229 /* CAN driver callbacks */
1230 static const struct net_device_ops ucan_netdev_ops = {
1231     .ndo_open = ucan_open,
1232     .ndo_stop = ucan_close,
1233     .ndo_start_xmit = ucan_start_xmit,
1234     .ndo_change_mtu = can_change_mtu,
1235 };
1236 
1237 static const struct ethtool_ops ucan_ethtool_ops = {
1238     .get_ts_info = ethtool_op_get_ts_info,
1239 };
1240 
1241 /* Request to set bittiming
1242  *
1243  * This function generates an USB set bittiming message and transmits
1244  * it to the device
1245  */
1246 static int ucan_set_bittiming(struct net_device *netdev)
1247 {
1248     int ret;
1249     struct ucan_priv *up = netdev_priv(netdev);
1250     struct ucan_ctl_cmd_set_bittiming *cmd_set_bittiming;
1251 
1252     cmd_set_bittiming = &up->ctl_msg_buffer->cmd_set_bittiming;
1253     cmd_set_bittiming->tq = cpu_to_le32(up->can.bittiming.tq);
1254     cmd_set_bittiming->brp = cpu_to_le16(up->can.bittiming.brp);
1255     cmd_set_bittiming->sample_point =
1256         cpu_to_le16(up->can.bittiming.sample_point);
1257     cmd_set_bittiming->prop_seg = up->can.bittiming.prop_seg;
1258     cmd_set_bittiming->phase_seg1 = up->can.bittiming.phase_seg1;
1259     cmd_set_bittiming->phase_seg2 = up->can.bittiming.phase_seg2;
1260     cmd_set_bittiming->sjw = up->can.bittiming.sjw;
1261 
1262     ret = ucan_ctrl_command_out(up, UCAN_COMMAND_SET_BITTIMING, 0,
1263                     sizeof(*cmd_set_bittiming));
1264     return (ret < 0) ? ret : 0;
1265 }
1266 
1267 /* Restart the device to get it out of BUS-OFF state.
1268  * Called when the user runs "ip link set can1 type can restart".
1269  */
1270 static int ucan_set_mode(struct net_device *netdev, enum can_mode mode)
1271 {
1272     int ret;
1273     unsigned long flags;
1274     struct ucan_priv *up = netdev_priv(netdev);
1275 
1276     switch (mode) {
1277     case CAN_MODE_START:
1278         netdev_dbg(up->netdev, "restarting device\n");
1279 
1280         ret = ucan_ctrl_command_out(up, UCAN_COMMAND_RESTART, 0, 0);
1281         up->can.state = CAN_STATE_ERROR_ACTIVE;
1282 
1283         /* check if queue can be restarted,
1284          * up->available_tx_urbs must be protected by the
1285          * lock
1286          */
1287         spin_lock_irqsave(&up->context_lock, flags);
1288 
1289         if (up->available_tx_urbs > 0)
1290             netif_wake_queue(up->netdev);
1291 
1292         spin_unlock_irqrestore(&up->context_lock, flags);
1293 
1294         return ret;
1295     default:
1296         return -EOPNOTSUPP;
1297     }
1298 }
1299 
1300 /* Probe the device, reset it and gather general device information */
1301 static int ucan_probe(struct usb_interface *intf,
1302               const struct usb_device_id *id)
1303 {
1304     int ret;
1305     int i;
1306     u32 protocol_version;
1307     struct usb_device *udev;
1308     struct net_device *netdev;
1309     struct usb_host_interface *iface_desc;
1310     struct ucan_priv *up;
1311     struct usb_endpoint_descriptor *ep;
1312     u16 in_ep_size;
1313     u16 out_ep_size;
1314     u8 in_ep_addr;
1315     u8 out_ep_addr;
1316     union ucan_ctl_payload *ctl_msg_buffer;
1317     char firmware_str[sizeof(union ucan_ctl_payload) + 1];
1318 
1319     udev = interface_to_usbdev(intf);
1320 
1321     /* Stage 1 - Interface Parsing
1322      * ---------------------------
1323      *
1324      * Identifie the device USB interface descriptor and its
1325      * endpoints. Probing is aborted on errors.
1326      */
1327 
1328     /* check if the interface is sane */
1329     iface_desc = intf->cur_altsetting;
1330     if (!iface_desc)
1331         return -ENODEV;
1332 
1333     dev_info(&udev->dev,
1334          "%s: probing device on interface #%d\n",
1335          UCAN_DRIVER_NAME,
1336          iface_desc->desc.bInterfaceNumber);
1337 
1338     /* interface sanity check */
1339     if (iface_desc->desc.bNumEndpoints != 2) {
1340         dev_err(&udev->dev,
1341             "%s: invalid EP count (%d)",
1342             UCAN_DRIVER_NAME, iface_desc->desc.bNumEndpoints);
1343         goto err_firmware_needs_update;
1344     }
1345 
1346     /* check interface endpoints */
1347     in_ep_addr = 0;
1348     out_ep_addr = 0;
1349     in_ep_size = 0;
1350     out_ep_size = 0;
1351     for (i = 0; i < iface_desc->desc.bNumEndpoints; i++) {
1352         ep = &iface_desc->endpoint[i].desc;
1353 
1354         if (((ep->bEndpointAddress & USB_ENDPOINT_DIR_MASK) != 0) &&
1355             ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
1356              USB_ENDPOINT_XFER_BULK)) {
1357             /* In Endpoint */
1358             in_ep_addr = ep->bEndpointAddress;
1359             in_ep_addr &= USB_ENDPOINT_NUMBER_MASK;
1360             in_ep_size = le16_to_cpu(ep->wMaxPacketSize);
1361         } else if (((ep->bEndpointAddress & USB_ENDPOINT_DIR_MASK) ==
1362                 0) &&
1363                ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
1364                 USB_ENDPOINT_XFER_BULK)) {
1365             /* Out Endpoint */
1366             out_ep_addr = ep->bEndpointAddress;
1367             out_ep_addr &= USB_ENDPOINT_NUMBER_MASK;
1368             out_ep_size = le16_to_cpu(ep->wMaxPacketSize);
1369         }
1370     }
1371 
1372     /* check if interface is sane */
1373     if (!in_ep_addr || !out_ep_addr) {
1374         dev_err(&udev->dev, "%s: invalid endpoint configuration\n",
1375             UCAN_DRIVER_NAME);
1376         goto err_firmware_needs_update;
1377     }
1378     if (in_ep_size < sizeof(struct ucan_message_in)) {
1379         dev_err(&udev->dev, "%s: invalid in_ep MaxPacketSize\n",
1380             UCAN_DRIVER_NAME);
1381         goto err_firmware_needs_update;
1382     }
1383     if (out_ep_size < sizeof(struct ucan_message_out)) {
1384         dev_err(&udev->dev, "%s: invalid out_ep MaxPacketSize\n",
1385             UCAN_DRIVER_NAME);
1386         goto err_firmware_needs_update;
1387     }
1388 
1389     /* Stage 2 - Device Identification
1390      * -------------------------------
1391      *
1392      * The device interface seems to be a ucan device. Do further
1393      * compatibility checks. On error probing is aborted, on
1394      * success this stage leaves the ctl_msg_buffer with the
1395      * reported contents of a GET_INFO command (supported
1396      * bittimings, tx_fifo depth). This information is used in
1397      * Stage 3 for the final driver initialisation.
1398      */
1399 
1400     /* Prepare Memory for control transfers */
1401     ctl_msg_buffer = devm_kzalloc(&udev->dev,
1402                       sizeof(union ucan_ctl_payload),
1403                       GFP_KERNEL);
1404     if (!ctl_msg_buffer) {
1405         dev_err(&udev->dev,
1406             "%s: failed to allocate control pipe memory\n",
1407             UCAN_DRIVER_NAME);
1408         return -ENOMEM;
1409     }
1410 
1411     /* get protocol version
1412      *
1413      * note: ucan_ctrl_command_* wrappers cannot be used yet
1414      * because `up` is initialised in Stage 3
1415      */
1416     ret = usb_control_msg(udev,
1417                   usb_rcvctrlpipe(udev, 0),
1418                   UCAN_COMMAND_GET,
1419                   USB_DIR_IN | USB_TYPE_VENDOR |
1420                     USB_RECIP_INTERFACE,
1421                   UCAN_COMMAND_GET_PROTOCOL_VERSION,
1422                   iface_desc->desc.bInterfaceNumber,
1423                   ctl_msg_buffer,
1424                   sizeof(union ucan_ctl_payload),
1425                   UCAN_USB_CTL_PIPE_TIMEOUT);
1426 
1427     /* older firmware version do not support this command - those
1428      * are not supported by this drive
1429      */
1430     if (ret != 4) {
1431         dev_err(&udev->dev,
1432             "%s: could not read protocol version, ret=%d\n",
1433             UCAN_DRIVER_NAME, ret);
1434         if (ret >= 0)
1435             ret = -EINVAL;
1436         goto err_firmware_needs_update;
1437     }
1438 
1439     /* this driver currently supports protocol version 3 only */
1440     protocol_version =
1441         le32_to_cpu(ctl_msg_buffer->cmd_get_protocol_version.version);
1442     if (protocol_version < UCAN_PROTOCOL_VERSION_MIN ||
1443         protocol_version > UCAN_PROTOCOL_VERSION_MAX) {
1444         dev_err(&udev->dev,
1445             "%s: device protocol version %d is not supported\n",
1446             UCAN_DRIVER_NAME, protocol_version);
1447         goto err_firmware_needs_update;
1448     }
1449 
1450     /* request the device information and store it in ctl_msg_buffer
1451      *
1452      * note: ucan_ctrl_command_* wrappers cannot be used yet
1453      * because `up` is initialised in Stage 3
1454      */
1455     ret = usb_control_msg(udev,
1456                   usb_rcvctrlpipe(udev, 0),
1457                   UCAN_COMMAND_GET,
1458                   USB_DIR_IN | USB_TYPE_VENDOR |
1459                     USB_RECIP_INTERFACE,
1460                   UCAN_COMMAND_GET_INFO,
1461                   iface_desc->desc.bInterfaceNumber,
1462                   ctl_msg_buffer,
1463                   sizeof(ctl_msg_buffer->cmd_get_device_info),
1464                   UCAN_USB_CTL_PIPE_TIMEOUT);
1465 
1466     if (ret < 0) {
1467         dev_err(&udev->dev, "%s: failed to retrieve device info\n",
1468             UCAN_DRIVER_NAME);
1469         goto err_firmware_needs_update;
1470     }
1471     if (ret < sizeof(ctl_msg_buffer->cmd_get_device_info)) {
1472         dev_err(&udev->dev, "%s: device reported invalid device info\n",
1473             UCAN_DRIVER_NAME);
1474         goto err_firmware_needs_update;
1475     }
1476     if (ctl_msg_buffer->cmd_get_device_info.tx_fifo == 0) {
1477         dev_err(&udev->dev,
1478             "%s: device reported invalid tx-fifo size\n",
1479             UCAN_DRIVER_NAME);
1480         goto err_firmware_needs_update;
1481     }
1482 
1483     /* Stage 3 - Driver Initialisation
1484      * -------------------------------
1485      *
1486      * Register device to Linux, prepare private structures and
1487      * reset the device.
1488      */
1489 
1490     /* allocate driver resources */
1491     netdev = alloc_candev(sizeof(struct ucan_priv),
1492                   ctl_msg_buffer->cmd_get_device_info.tx_fifo);
1493     if (!netdev) {
1494         dev_err(&udev->dev,
1495             "%s: cannot allocate candev\n", UCAN_DRIVER_NAME);
1496         return -ENOMEM;
1497     }
1498 
1499     up = netdev_priv(netdev);
1500 
1501     /* initialize data */
1502     up->udev = udev;
1503     up->intf = intf;
1504     up->netdev = netdev;
1505     up->intf_index = iface_desc->desc.bInterfaceNumber;
1506     up->in_ep_addr = in_ep_addr;
1507     up->out_ep_addr = out_ep_addr;
1508     up->in_ep_size = in_ep_size;
1509     up->ctl_msg_buffer = ctl_msg_buffer;
1510     up->context_array = NULL;
1511     up->available_tx_urbs = 0;
1512 
1513     up->can.state = CAN_STATE_STOPPED;
1514     up->can.bittiming_const = &up->device_info.bittiming_const;
1515     up->can.do_set_bittiming = ucan_set_bittiming;
1516     up->can.do_set_mode = &ucan_set_mode;
1517     spin_lock_init(&up->context_lock);
1518     spin_lock_init(&up->echo_skb_lock);
1519     netdev->netdev_ops = &ucan_netdev_ops;
1520     netdev->ethtool_ops = &ucan_ethtool_ops;
1521 
1522     usb_set_intfdata(intf, up);
1523     SET_NETDEV_DEV(netdev, &intf->dev);
1524 
1525     /* parse device information
1526      * the data retrieved in Stage 2 is still available in
1527      * up->ctl_msg_buffer
1528      */
1529     ucan_parse_device_info(up, &ctl_msg_buffer->cmd_get_device_info);
1530 
1531     /* just print some device information - if available */
1532     ret = ucan_device_request_in(up, UCAN_DEVICE_GET_FW_STRING, 0,
1533                      sizeof(union ucan_ctl_payload));
1534     if (ret > 0) {
1535         /* copy string while ensuring zero termination */
1536         strncpy(firmware_str, up->ctl_msg_buffer->raw,
1537             sizeof(union ucan_ctl_payload));
1538         firmware_str[sizeof(union ucan_ctl_payload)] = '\0';
1539     } else {
1540         strcpy(firmware_str, "unknown");
1541     }
1542 
1543     /* device is compatible, reset it */
1544     ret = ucan_ctrl_command_out(up, UCAN_COMMAND_RESET, 0, 0);
1545     if (ret < 0)
1546         goto err_free_candev;
1547 
1548     init_usb_anchor(&up->rx_urbs);
1549     init_usb_anchor(&up->tx_urbs);
1550 
1551     up->can.state = CAN_STATE_STOPPED;
1552 
1553     /* register the device */
1554     ret = register_candev(netdev);
1555     if (ret)
1556         goto err_free_candev;
1557 
1558     /* initialisation complete, log device info */
1559     netdev_info(up->netdev, "registered device\n");
1560     netdev_info(up->netdev, "firmware string: %s\n", firmware_str);
1561 
1562     /* success */
1563     return 0;
1564 
1565 err_free_candev:
1566     free_candev(netdev);
1567     return ret;
1568 
1569 err_firmware_needs_update:
1570     dev_err(&udev->dev,
1571         "%s: probe failed; try to update the device firmware\n",
1572         UCAN_DRIVER_NAME);
1573     return -ENODEV;
1574 }
1575 
1576 /* disconnect the device */
1577 static void ucan_disconnect(struct usb_interface *intf)
1578 {
1579     struct ucan_priv *up = usb_get_intfdata(intf);
1580 
1581     usb_set_intfdata(intf, NULL);
1582 
1583     if (up) {
1584         unregister_netdev(up->netdev);
1585         free_candev(up->netdev);
1586     }
1587 }
1588 
1589 static struct usb_device_id ucan_table[] = {
1590     /* Mule (soldered onto compute modules) */
1591     {USB_DEVICE_INTERFACE_NUMBER(0x2294, 0x425a, 0)},
1592     /* Seal (standalone USB stick) */
1593     {USB_DEVICE_INTERFACE_NUMBER(0x2294, 0x425b, 0)},
1594     {} /* Terminating entry */
1595 };
1596 
1597 MODULE_DEVICE_TABLE(usb, ucan_table);
1598 /* driver callbacks */
1599 static struct usb_driver ucan_driver = {
1600     .name = UCAN_DRIVER_NAME,
1601     .probe = ucan_probe,
1602     .disconnect = ucan_disconnect,
1603     .id_table = ucan_table,
1604 };
1605 
1606 module_usb_driver(ucan_driver);
1607 
1608 MODULE_LICENSE("GPL v2");
1609 MODULE_AUTHOR("Martin Elshuber <martin.elshuber@theobroma-systems.com>");
1610 MODULE_AUTHOR("Jakob Unterwurzacher <jakob.unterwurzacher@theobroma-systems.com>");
1611 MODULE_DESCRIPTION("Driver for Theobroma Systems UCAN devices");