1 // SPDX-License-Identifier: GPL-2.0
3 /* Driver for Theobroma Systems UCAN devices, Protocol Version 3
5 * Copyright (C) 2018 Theobroma Systems Design und Consulting GmbH
10 * The USB Device uses three Endpoints:
12 * CONTROL Endpoint: Is used the setup the device (start, stop,
15 * IN Endpoint: The device sends CAN Frame Messages and Device
16 * Information using the IN endpoint.
18 * OUT Endpoint: The driver sends configuration requests, and CAN
19 * Frames on the out endpoint.
23 * If error reporting is turned on the device encodes error into CAN
24 * error frames (see uapi/linux/can/error.h) and sends it using the
25 * IN Endpoint. The driver updates statistics and forward it.
28 #include <linux/can.h>
29 #include <linux/can/dev.h>
30 #include <linux/can/error.h>
31 #include <linux/module.h>
32 #include <linux/netdevice.h>
33 #include <linux/signal.h>
34 #include <linux/skbuff.h>
35 #include <linux/slab.h>
36 #include <linux/usb.h>
38 #include <linux/can.h>
39 #include <linux/can/dev.h>
40 #include <linux/can/error.h>
42 #define UCAN_DRIVER_NAME "ucan"
43 #define UCAN_MAX_RX_URBS 8
44 /* the CAN controller needs a while to enable/disable the bus */
45 #define UCAN_USB_CTL_PIPE_TIMEOUT 1000
46 /* this driver currently supports protocol version 3 only */
47 #define UCAN_PROTOCOL_VERSION_MIN 3
48 #define UCAN_PROTOCOL_VERSION_MAX 3
50 /* UCAN Message Definitions
51 * ------------------------
53 * ucan_message_out_t and ucan_message_in_t define the messages
54 * transmitted on the OUT and IN endpoint.
56 * Multibyte fields are transmitted with little endianness
58 * INTR Endpoint: a single uint32_t storing the current space in the fifo
60 * OUT Endpoint: single message of type ucan_message_out_t is
61 * transmitted on the out endpoint
63 * IN Endpoint: multiple messages ucan_message_in_t concateted in
66 * m[n].len <=> the length if message n(including the header in bytes)
67 * m[n] is is aligned to a 4 byte boundary, hence
69 * offset(m[n+1]) := offset(m[n]) + (m[n].len + 3) & 3
72 * offset(m[n]) % 4 <=> 0
75 /* Device Global Commands */
77 UCAN_DEVICE_GET_FW_STRING = 0,
82 /* start the can transceiver - val defines the operation mode */
83 UCAN_COMMAND_START = 0,
84 /* cancel pending transmissions and stop the can transceiver */
85 UCAN_COMMAND_STOP = 1,
86 /* send can transceiver into low-power sleep mode */
87 UCAN_COMMAND_SLEEP = 2,
88 /* wake up can transceiver from low-power sleep mode */
89 UCAN_COMMAND_WAKEUP = 3,
90 /* reset the can transceiver */
91 UCAN_COMMAND_RESET = 4,
92 /* get piece of info from the can transceiver - subcmd defines what
96 /* clear or disable hardware filter - subcmd defines which of the two */
97 UCAN_COMMAND_FILTER = 6,
99 UCAN_COMMAND_SET_BITTIMING = 7,
100 /* recover from bus-off state */
101 UCAN_COMMAND_RESTART = 8,
104 /* UCAN_COMMAND_START and UCAN_COMMAND_GET_INFO operation modes (bitmap).
105 * Undefined bits must be set to 0.
108 UCAN_MODE_LOOPBACK = BIT(0),
109 UCAN_MODE_SILENT = BIT(1),
110 UCAN_MODE_3_SAMPLES = BIT(2),
111 UCAN_MODE_ONE_SHOT = BIT(3),
112 UCAN_MODE_BERR_REPORT = BIT(4),
115 /* UCAN_COMMAND_GET subcommands */
117 UCAN_COMMAND_GET_INFO = 0,
118 UCAN_COMMAND_GET_PROTOCOL_VERSION = 1,
121 /* UCAN_COMMAND_FILTER subcommands */
123 UCAN_FILTER_CLEAR = 0,
124 UCAN_FILTER_DISABLE = 1,
125 UCAN_FILTER_ENABLE = 2,
128 /* OUT endpoint message types */
130 UCAN_OUT_TX = 2, /* transmit a CAN frame */
133 /* IN endpoint message types */
135 UCAN_IN_TX_COMPLETE = 1, /* CAN frame transmission completed */
136 UCAN_IN_RX = 2, /* CAN frame received */
139 struct ucan_ctl_cmd_start {
140 __le16 mode; /* OR-ing any of UCAN_MODE_* */
143 struct ucan_ctl_cmd_set_bittiming {
144 __le32 tq; /* Time quanta (TQ) in nanoseconds */
145 __le16 brp; /* TQ Prescaler */
146 __le16 sample_point; /* Samplepoint on tenth percent */
147 u8 prop_seg; /* Propagation segment in TQs */
148 u8 phase_seg1; /* Phase buffer segment 1 in TQs */
149 u8 phase_seg2; /* Phase buffer segment 2 in TQs */
150 u8 sjw; /* Synchronisation jump width in TQs */
153 struct ucan_ctl_cmd_device_info {
154 __le32 freq; /* Clock Frequency for tq generation */
155 u8 tx_fifo; /* Size of the transmission fifo */
156 u8 sjw_max; /* can_bittiming fields... */
163 __le32 brp_max; /* ...can_bittiming fields */
164 __le16 ctrlmodes; /* supported control modes */
165 __le16 hwfilter; /* Number of HW filter banks */
166 __le16 rxmboxes; /* Number of receive Mailboxes */
169 struct ucan_ctl_cmd_get_protocol_version {
173 union ucan_ctl_payload {
175 * bmRequest == UCAN_COMMAND_START
177 struct ucan_ctl_cmd_start cmd_start;
179 * bmRequest == UCAN_COMMAND_SET_BITTIMING
181 struct ucan_ctl_cmd_set_bittiming cmd_set_bittiming;
182 /* Get Device Information
183 * bmRequest == UCAN_COMMAND_GET; wValue = UCAN_COMMAND_GET_INFO
185 struct ucan_ctl_cmd_device_info cmd_get_device_info;
186 /* Get Protocol Version
187 * bmRequest == UCAN_COMMAND_GET;
188 * wValue = UCAN_COMMAND_GET_PROTOCOL_VERSION
190 struct ucan_ctl_cmd_get_protocol_version cmd_get_protocol_version;
196 UCAN_TX_COMPLETE_SUCCESS = BIT(0),
199 /* Transmission Complete within ucan_message_in */
200 struct ucan_tx_complete_entry_t {
203 } __packed __aligned(0x2);
205 /* CAN Data message format within ucan_message_in/out */
206 struct ucan_can_msg {
207 /* note DLC is computed by
208 * msg.len - sizeof (msg.len)
209 * - sizeof (msg.type)
210 * - sizeof (msg.can_msg.id)
215 u8 data[CAN_MAX_DLEN]; /* Data of CAN frames */
216 u8 dlc; /* RTR dlc */
220 /* OUT Endpoint, outbound messages */
221 struct ucan_message_out {
222 __le16 len; /* Length of the content include header */
223 u8 type; /* UCAN_OUT_TX and friends */
224 u8 subtype; /* command sub type */
227 /* Transmit CAN frame
228 * (type == UCAN_TX) && ((msg.can_msg.id & CAN_RTR_FLAG) == 0)
229 * subtype stores the echo id
231 struct ucan_can_msg can_msg;
233 } __packed __aligned(0x4);
235 /* IN Endpoint, inbound messages */
236 struct ucan_message_in {
237 __le16 len; /* Length of the content include header */
238 u8 type; /* UCAN_IN_RX and friends */
239 u8 subtype; /* command sub type */
242 /* CAN Frame received
243 * (type == UCAN_IN_RX)
244 * && ((msg.can_msg.id & CAN_RTR_FLAG) == 0)
246 struct ucan_can_msg can_msg;
248 /* CAN transmission complete
249 * (type == UCAN_IN_TX_COMPLETE)
251 struct ucan_tx_complete_entry_t can_tx_complete_msg[0];
252 } __aligned(0x4) msg;
255 /* Macros to calculate message lengths */
256 #define UCAN_OUT_HDR_SIZE offsetof(struct ucan_message_out, msg)
258 #define UCAN_IN_HDR_SIZE offsetof(struct ucan_message_in, msg)
259 #define UCAN_IN_LEN(member) (UCAN_OUT_HDR_SIZE + sizeof(member))
263 /* Context Information for transmission URBs */
264 struct ucan_urb_context {
265 struct ucan_priv *up;
270 /* Information reported by the USB device */
271 struct ucan_device_info {
272 struct can_bittiming_const bittiming_const;
276 /* Driver private data */
278 /* must be the first member */
281 /* linux USB device structures */
282 struct usb_device *udev;
283 struct usb_interface *intf;
284 struct net_device *netdev;
286 /* lock for can->echo_skb (used around
287 * can_put/get/free_echo_skb
289 spinlock_t echo_skb_lock;
291 /* usb device information information */
297 /* transmission and reception buffers */
298 struct usb_anchor rx_urbs;
299 struct usb_anchor tx_urbs;
301 union ucan_ctl_payload *ctl_msg_buffer;
302 struct ucan_device_info device_info;
304 /* transmission control information and locks */
305 spinlock_t context_lock;
306 unsigned int available_tx_urbs;
307 struct ucan_urb_context *context_array;
310 static u8 ucan_get_can_dlc(struct ucan_can_msg *msg, u16 len)
312 if (le32_to_cpu(msg->id) & CAN_RTR_FLAG)
313 return get_can_dlc(msg->dlc);
315 return get_can_dlc(len - (UCAN_IN_HDR_SIZE + sizeof(msg->id)));
318 static void ucan_release_context_array(struct ucan_priv *up)
320 if (!up->context_array)
323 /* lock is not needed because, driver is currently opening or closing */
324 up->available_tx_urbs = 0;
326 kfree(up->context_array);
327 up->context_array = NULL;
330 static int ucan_alloc_context_array(struct ucan_priv *up)
334 /* release contexts if any */
335 ucan_release_context_array(up);
337 up->context_array = kcalloc(up->device_info.tx_fifo,
338 sizeof(*up->context_array),
340 if (!up->context_array) {
341 netdev_err(up->netdev,
342 "Not enough memory to allocate tx contexts\n");
346 for (i = 0; i < up->device_info.tx_fifo; i++) {
347 up->context_array[i].allocated = false;
348 up->context_array[i].up = up;
351 /* lock is not needed because, driver is currently opening */
352 up->available_tx_urbs = up->device_info.tx_fifo;
357 static struct ucan_urb_context *ucan_alloc_context(struct ucan_priv *up)
361 struct ucan_urb_context *ret = NULL;
363 if (WARN_ON_ONCE(!up->context_array))
366 /* execute context operation atomically */
367 spin_lock_irqsave(&up->context_lock, flags);
369 for (i = 0; i < up->device_info.tx_fifo; i++) {
370 if (!up->context_array[i].allocated) {
372 ret = &up->context_array[i];
373 up->context_array[i].allocated = true;
375 /* stop queue if necessary */
376 up->available_tx_urbs--;
377 if (!up->available_tx_urbs)
378 netif_stop_queue(up->netdev);
384 spin_unlock_irqrestore(&up->context_lock, flags);
388 static bool ucan_release_context(struct ucan_priv *up,
389 struct ucan_urb_context *ctx)
394 if (WARN_ON_ONCE(!up->context_array))
397 /* execute context operation atomically */
398 spin_lock_irqsave(&up->context_lock, flags);
400 /* context was not allocated, maybe the device sent garbage */
401 if (ctx->allocated) {
402 ctx->allocated = false;
404 /* check if the queue needs to be woken */
405 if (!up->available_tx_urbs)
406 netif_wake_queue(up->netdev);
407 up->available_tx_urbs++;
412 spin_unlock_irqrestore(&up->context_lock, flags);
416 static int ucan_ctrl_command_out(struct ucan_priv *up,
417 u8 cmd, u16 subcmd, u16 datalen)
419 return usb_control_msg(up->udev,
420 usb_sndctrlpipe(up->udev, 0),
422 USB_DIR_OUT | USB_TYPE_VENDOR |
428 UCAN_USB_CTL_PIPE_TIMEOUT);
431 static int ucan_device_request_in(struct ucan_priv *up,
432 u8 cmd, u16 subcmd, u16 datalen)
434 return usb_control_msg(up->udev,
435 usb_rcvctrlpipe(up->udev, 0),
437 USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
442 UCAN_USB_CTL_PIPE_TIMEOUT);
445 /* Parse the device information structure reported by the device and
446 * setup private variables accordingly
448 static void ucan_parse_device_info(struct ucan_priv *up,
449 struct ucan_ctl_cmd_device_info *device_info)
451 struct can_bittiming_const *bittiming =
452 &up->device_info.bittiming_const;
456 up->can.clock.freq = le32_to_cpu(device_info->freq);
457 up->device_info.tx_fifo = device_info->tx_fifo;
458 strcpy(bittiming->name, "ucan");
459 bittiming->tseg1_min = device_info->tseg1_min;
460 bittiming->tseg1_max = device_info->tseg1_max;
461 bittiming->tseg2_min = device_info->tseg2_min;
462 bittiming->tseg2_max = device_info->tseg2_max;
463 bittiming->sjw_max = device_info->sjw_max;
464 bittiming->brp_min = le32_to_cpu(device_info->brp_min);
465 bittiming->brp_max = le32_to_cpu(device_info->brp_max);
466 bittiming->brp_inc = le16_to_cpu(device_info->brp_inc);
468 ctrlmodes = le16_to_cpu(device_info->ctrlmodes);
470 up->can.ctrlmode_supported = 0;
472 if (ctrlmodes & UCAN_MODE_LOOPBACK)
473 up->can.ctrlmode_supported |= CAN_CTRLMODE_LOOPBACK;
474 if (ctrlmodes & UCAN_MODE_SILENT)
475 up->can.ctrlmode_supported |= CAN_CTRLMODE_LISTENONLY;
476 if (ctrlmodes & UCAN_MODE_3_SAMPLES)
477 up->can.ctrlmode_supported |= CAN_CTRLMODE_3_SAMPLES;
478 if (ctrlmodes & UCAN_MODE_ONE_SHOT)
479 up->can.ctrlmode_supported |= CAN_CTRLMODE_ONE_SHOT;
480 if (ctrlmodes & UCAN_MODE_BERR_REPORT)
481 up->can.ctrlmode_supported |= CAN_CTRLMODE_BERR_REPORTING;
484 /* Handle a CAN error frame that we have received from the device.
485 * Returns true if the can state has changed.
487 static bool ucan_handle_error_frame(struct ucan_priv *up,
488 struct ucan_message_in *m,
491 enum can_state new_state = up->can.state;
492 struct net_device_stats *net_stats = &up->netdev->stats;
493 struct can_device_stats *can_stats = &up->can.can_stats;
495 if (canid & CAN_ERR_LOSTARB)
496 can_stats->arbitration_lost++;
498 if (canid & CAN_ERR_BUSERROR)
499 can_stats->bus_error++;
501 if (canid & CAN_ERR_ACK)
502 net_stats->tx_errors++;
504 if (canid & CAN_ERR_BUSOFF)
505 new_state = CAN_STATE_BUS_OFF;
507 /* controller problems, details in data[1] */
508 if (canid & CAN_ERR_CRTL) {
509 u8 d1 = m->msg.can_msg.data[1];
511 if (d1 & CAN_ERR_CRTL_RX_OVERFLOW)
512 net_stats->rx_over_errors++;
514 /* controller state bits: if multiple are set the worst wins */
515 if (d1 & CAN_ERR_CRTL_ACTIVE)
516 new_state = CAN_STATE_ERROR_ACTIVE;
518 if (d1 & (CAN_ERR_CRTL_RX_WARNING | CAN_ERR_CRTL_TX_WARNING))
519 new_state = CAN_STATE_ERROR_WARNING;
521 if (d1 & (CAN_ERR_CRTL_RX_PASSIVE | CAN_ERR_CRTL_TX_PASSIVE))
522 new_state = CAN_STATE_ERROR_PASSIVE;
525 /* protocol error, details in data[2] */
526 if (canid & CAN_ERR_PROT) {
527 u8 d2 = m->msg.can_msg.data[2];
529 if (d2 & CAN_ERR_PROT_TX)
530 net_stats->tx_errors++;
532 net_stats->rx_errors++;
535 /* no state change - we are done */
536 if (up->can.state == new_state)
539 /* we switched into a better state */
540 if (up->can.state > new_state) {
541 up->can.state = new_state;
545 /* we switched into a worse state */
546 up->can.state = new_state;
548 case CAN_STATE_BUS_OFF:
549 can_stats->bus_off++;
550 can_bus_off(up->netdev);
552 case CAN_STATE_ERROR_PASSIVE:
553 can_stats->error_passive++;
555 case CAN_STATE_ERROR_WARNING:
556 can_stats->error_warning++;
564 /* Callback on reception of a can frame via the IN endpoint
566 * This function allocates an skb and transferres it to the Linux
569 static void ucan_rx_can_msg(struct ucan_priv *up, struct ucan_message_in *m)
573 struct can_frame *cf;
575 struct net_device_stats *stats = &up->netdev->stats;
577 /* get the contents of the length field */
578 len = le16_to_cpu(m->len);
581 if (len < UCAN_IN_HDR_SIZE + sizeof(m->msg.can_msg.id)) {
582 netdev_warn(up->netdev, "invalid input message len: %d\n", len);
586 /* handle error frames */
587 canid = le32_to_cpu(m->msg.can_msg.id);
588 if (canid & CAN_ERR_FLAG) {
589 bool busstate_changed = ucan_handle_error_frame(up, m, canid);
591 /* if berr-reporting is off only state changes get through */
592 if (!(up->can.ctrlmode & CAN_CTRLMODE_BERR_REPORTING) &&
597 /* compute the mask for canid */
598 canid_mask = CAN_RTR_FLAG;
599 if (canid & CAN_EFF_FLAG)
600 canid_mask |= CAN_EFF_MASK | CAN_EFF_FLAG;
602 canid_mask |= CAN_SFF_MASK;
604 if (canid & ~canid_mask)
605 netdev_warn(up->netdev,
606 "unexpected bits set (canid %x, mask %x)",
613 skb = alloc_can_skb(up->netdev, &cf);
617 /* fill the can frame */
620 /* compute DLC taking RTR_FLAG into account */
621 cf->can_dlc = ucan_get_can_dlc(&m->msg.can_msg, len);
623 /* copy the payload of non RTR frames */
624 if (!(cf->can_id & CAN_RTR_FLAG) || (cf->can_id & CAN_ERR_FLAG))
625 memcpy(cf->data, m->msg.can_msg.data, cf->can_dlc);
627 /* don't count error frames as real packets */
629 stats->rx_bytes += cf->can_dlc;
631 /* pass it to Linux */
635 /* callback indicating completed transmission */
636 static void ucan_tx_complete_msg(struct ucan_priv *up,
637 struct ucan_message_in *m)
642 u16 len = le16_to_cpu(m->len);
644 struct ucan_urb_context *context;
646 if (len < UCAN_IN_HDR_SIZE || (len % 2 != 0)) {
647 netdev_err(up->netdev, "invalid tx complete length\n");
651 count = (len - UCAN_IN_HDR_SIZE) / 2;
652 for (i = 0; i < count; i++) {
653 /* we did not submit such echo ids */
654 echo_index = m->msg.can_tx_complete_msg[i].echo_index;
655 if (echo_index >= up->device_info.tx_fifo) {
656 up->netdev->stats.tx_errors++;
657 netdev_err(up->netdev,
658 "invalid echo_index %d received\n",
663 /* gather information from the context */
664 context = &up->context_array[echo_index];
665 dlc = READ_ONCE(context->dlc);
667 /* Release context and restart queue if necessary.
668 * Also check if the context was allocated
670 if (!ucan_release_context(up, context))
673 spin_lock_irqsave(&up->echo_skb_lock, flags);
674 if (m->msg.can_tx_complete_msg[i].flags &
675 UCAN_TX_COMPLETE_SUCCESS) {
676 /* update statistics */
677 up->netdev->stats.tx_packets++;
678 up->netdev->stats.tx_bytes += dlc;
679 can_get_echo_skb(up->netdev, echo_index);
681 up->netdev->stats.tx_dropped++;
682 can_free_echo_skb(up->netdev, echo_index);
684 spin_unlock_irqrestore(&up->echo_skb_lock, flags);
688 /* callback on reception of a USB message */
689 static void ucan_read_bulk_callback(struct urb *urb)
693 struct ucan_priv *up = urb->context;
694 struct net_device *netdev = up->netdev;
695 struct ucan_message_in *m;
697 /* the device is not up and the driver should not receive any
698 * data on the bulk in pipe
700 if (WARN_ON(!up->context_array)) {
701 usb_free_coherent(up->udev,
703 urb->transfer_buffer,
708 /* check URB status */
709 switch (urb->status) {
717 /* urb is not resubmitted -> free dma data */
718 usb_free_coherent(up->udev,
720 urb->transfer_buffer,
722 netdev_dbg(up->netdev, "not resumbmitting urb; status: %d\n",
730 if (!netif_device_present(netdev))
733 /* iterate over input */
735 while (pos < urb->actual_length) {
738 /* check sanity (length of header) */
739 if ((urb->actual_length - pos) < UCAN_IN_HDR_SIZE) {
740 netdev_warn(up->netdev,
741 "invalid message (short; no hdr; l:%d)\n",
746 /* setup the message address */
747 m = (struct ucan_message_in *)
748 ((u8 *)urb->transfer_buffer + pos);
749 len = le16_to_cpu(m->len);
751 /* check sanity (length of content) */
752 if (urb->actual_length - pos < len) {
753 netdev_warn(up->netdev,
754 "invalid message (short; no data; l:%d)\n",
756 print_hex_dump(KERN_WARNING,
761 urb->transfer_buffer,
770 ucan_rx_can_msg(up, m);
772 case UCAN_IN_TX_COMPLETE:
773 ucan_tx_complete_msg(up, m);
776 netdev_warn(up->netdev,
777 "invalid message (type; t:%d)\n",
782 /* proceed to next message */
784 /* align to 4 byte boundary */
785 pos = round_up(pos, 4);
789 /* resubmit urb when done */
790 usb_fill_bulk_urb(urb, up->udev,
791 usb_rcvbulkpipe(up->udev,
793 urb->transfer_buffer,
795 ucan_read_bulk_callback,
798 usb_anchor_urb(urb, &up->rx_urbs);
799 ret = usb_submit_urb(urb, GFP_KERNEL);
802 netdev_err(up->netdev,
803 "failed resubmitting read bulk urb: %d\n",
806 usb_unanchor_urb(urb);
807 usb_free_coherent(up->udev,
809 urb->transfer_buffer,
813 netif_device_detach(netdev);
817 /* callback after transmission of a USB message */
818 static void ucan_write_bulk_callback(struct urb *urb)
821 struct ucan_priv *up;
822 struct ucan_urb_context *context = urb->context;
824 /* get the urb context */
825 if (WARN_ON_ONCE(!context))
828 /* free up our allocated buffer */
829 usb_free_coherent(urb->dev,
830 sizeof(struct ucan_message_out),
831 urb->transfer_buffer,
835 if (WARN_ON_ONCE(!up))
839 if (!netif_device_present(up->netdev))
842 /* transmission failed (USB - the device will not send a TX complete) */
844 netdev_warn(up->netdev,
845 "failed to transmit USB message to device: %d\n",
848 /* update counters an cleanup */
849 spin_lock_irqsave(&up->echo_skb_lock, flags);
850 can_free_echo_skb(up->netdev, context - up->context_array);
851 spin_unlock_irqrestore(&up->echo_skb_lock, flags);
853 up->netdev->stats.tx_dropped++;
855 /* release context and restart the queue if necessary */
856 if (!ucan_release_context(up, context))
857 netdev_err(up->netdev,
858 "urb failed, failed to release context\n");
862 static void ucan_cleanup_rx_urbs(struct ucan_priv *up, struct urb **urbs)
866 for (i = 0; i < UCAN_MAX_RX_URBS; i++) {
868 usb_unanchor_urb(urbs[i]);
869 usb_free_coherent(up->udev,
871 urbs[i]->transfer_buffer,
872 urbs[i]->transfer_dma);
873 usb_free_urb(urbs[i]);
877 memset(urbs, 0, sizeof(*urbs) * UCAN_MAX_RX_URBS);
880 static int ucan_prepare_and_anchor_rx_urbs(struct ucan_priv *up,
885 memset(urbs, 0, sizeof(*urbs) * UCAN_MAX_RX_URBS);
887 for (i = 0; i < UCAN_MAX_RX_URBS; i++) {
890 urbs[i] = usb_alloc_urb(0, GFP_KERNEL);
894 buf = usb_alloc_coherent(up->udev,
896 GFP_KERNEL, &urbs[i]->transfer_dma);
898 /* cleanup this urb */
899 usb_free_urb(urbs[i]);
904 usb_fill_bulk_urb(urbs[i], up->udev,
905 usb_rcvbulkpipe(up->udev,
909 ucan_read_bulk_callback,
912 urbs[i]->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
914 usb_anchor_urb(urbs[i], &up->rx_urbs);
919 /* cleanup other unsubmitted urbs */
920 ucan_cleanup_rx_urbs(up, urbs);
924 /* Submits rx urbs with the semantic: Either submit all, or cleanup
925 * everything. I case of errors submitted urbs are killed and all urbs in
926 * the array are freed. I case of no errors every entry in the urb
927 * array is set to NULL.
929 static int ucan_submit_rx_urbs(struct ucan_priv *up, struct urb **urbs)
933 /* Iterate over all urbs to submit. On success remove the urb
936 for (i = 0; i < UCAN_MAX_RX_URBS; i++) {
937 ret = usb_submit_urb(urbs[i], GFP_KERNEL);
939 netdev_err(up->netdev,
940 "could not submit urb; code: %d\n",
945 /* Anchor URB and drop reference, USB core will take
948 usb_free_urb(urbs[i]);
954 /* Cleanup unsubmitted urbs */
955 ucan_cleanup_rx_urbs(up, urbs);
957 /* Kill urbs that are already submitted */
958 usb_kill_anchored_urbs(&up->rx_urbs);
963 /* Open the network device */
964 static int ucan_open(struct net_device *netdev)
966 int ret, ret_cleanup;
968 struct urb *urbs[UCAN_MAX_RX_URBS];
969 struct ucan_priv *up = netdev_priv(netdev);
971 ret = ucan_alloc_context_array(up);
975 /* Allocate and prepare IN URBS - allocated and anchored
976 * urbs are stored in urbs[] for clean
978 ret = ucan_prepare_and_anchor_rx_urbs(up, urbs);
982 /* Check the control mode */
984 if (up->can.ctrlmode & CAN_CTRLMODE_LOOPBACK)
985 ctrlmode |= UCAN_MODE_LOOPBACK;
986 if (up->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)
987 ctrlmode |= UCAN_MODE_SILENT;
988 if (up->can.ctrlmode & CAN_CTRLMODE_3_SAMPLES)
989 ctrlmode |= UCAN_MODE_3_SAMPLES;
990 if (up->can.ctrlmode & CAN_CTRLMODE_ONE_SHOT)
991 ctrlmode |= UCAN_MODE_ONE_SHOT;
993 /* Enable this in any case - filtering is down within the
996 ctrlmode |= UCAN_MODE_BERR_REPORT;
997 up->ctl_msg_buffer->cmd_start.mode = cpu_to_le16(ctrlmode);
999 /* Driver is ready to receive data - start the USB device */
1000 ret = ucan_ctrl_command_out(up, UCAN_COMMAND_START, 0, 2);
1002 netdev_err(up->netdev,
1003 "could not start device, code: %d\n",
1008 /* Call CAN layer open */
1009 ret = open_candev(netdev);
1013 /* Driver is ready to receive data. Submit RX URBS */
1014 ret = ucan_submit_rx_urbs(up, urbs);
1018 up->can.state = CAN_STATE_ERROR_ACTIVE;
1020 /* Start the network queue */
1021 netif_start_queue(netdev);
1026 /* The device have started already stop it */
1027 ret_cleanup = ucan_ctrl_command_out(up, UCAN_COMMAND_STOP, 0, 0);
1028 if (ret_cleanup < 0)
1029 netdev_err(up->netdev,
1030 "could not stop device, code: %d\n",
1034 /* The device might have received data, reset it for
1037 ret_cleanup = ucan_ctrl_command_out(up, UCAN_COMMAND_RESET, 0, 0);
1038 if (ret_cleanup < 0)
1039 netdev_err(up->netdev,
1040 "could not reset device, code: %d\n",
1043 /* clean up unsubmitted urbs */
1044 ucan_cleanup_rx_urbs(up, urbs);
1047 ucan_release_context_array(up);
1051 static struct urb *ucan_prepare_tx_urb(struct ucan_priv *up,
1052 struct ucan_urb_context *context,
1053 struct can_frame *cf,
1058 struct ucan_message_out *m;
1060 /* create a URB, and a buffer for it, and copy the data to the URB */
1061 urb = usb_alloc_urb(0, GFP_ATOMIC);
1063 netdev_err(up->netdev, "no memory left for URBs\n");
1067 m = usb_alloc_coherent(up->udev,
1068 sizeof(struct ucan_message_out),
1070 &urb->transfer_dma);
1072 netdev_err(up->netdev, "no memory left for USB buffer\n");
1077 /* build the USB message */
1078 m->type = UCAN_OUT_TX;
1079 m->msg.can_msg.id = cpu_to_le32(cf->can_id);
1081 if (cf->can_id & CAN_RTR_FLAG) {
1082 mlen = UCAN_OUT_HDR_SIZE +
1083 offsetof(struct ucan_can_msg, dlc) +
1084 sizeof(m->msg.can_msg.dlc);
1085 m->msg.can_msg.dlc = cf->can_dlc;
1087 mlen = UCAN_OUT_HDR_SIZE +
1088 sizeof(m->msg.can_msg.id) + cf->can_dlc;
1089 memcpy(m->msg.can_msg.data, cf->data, cf->can_dlc);
1091 m->len = cpu_to_le16(mlen);
1093 context->dlc = cf->can_dlc;
1095 m->subtype = echo_index;
1098 usb_fill_bulk_urb(urb, up->udev,
1099 usb_sndbulkpipe(up->udev,
1101 m, mlen, ucan_write_bulk_callback, context);
1102 urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
1107 static void ucan_clean_up_tx_urb(struct ucan_priv *up, struct urb *urb)
1109 usb_free_coherent(up->udev, sizeof(struct ucan_message_out),
1110 urb->transfer_buffer, urb->transfer_dma);
1114 /* callback when Linux needs to send a can frame */
1115 static netdev_tx_t ucan_start_xmit(struct sk_buff *skb,
1116 struct net_device *netdev)
1118 unsigned long flags;
1122 struct ucan_urb_context *context;
1123 struct ucan_priv *up = netdev_priv(netdev);
1124 struct can_frame *cf = (struct can_frame *)skb->data;
1127 if (can_dropped_invalid_skb(netdev, skb))
1128 return NETDEV_TX_OK;
1130 /* allocate a context and slow down tx path, if fifo state is low */
1131 context = ucan_alloc_context(up);
1132 echo_index = context - up->context_array;
1134 if (WARN_ON_ONCE(!context))
1135 return NETDEV_TX_BUSY;
1137 /* prepare urb for transmission */
1138 urb = ucan_prepare_tx_urb(up, context, cf, echo_index);
1142 /* put the skb on can loopback stack */
1143 spin_lock_irqsave(&up->echo_skb_lock, flags);
1144 can_put_echo_skb(skb, up->netdev, echo_index);
1145 spin_unlock_irqrestore(&up->echo_skb_lock, flags);
1148 usb_anchor_urb(urb, &up->tx_urbs);
1149 ret = usb_submit_urb(urb, GFP_ATOMIC);
1153 /* on error, clean up */
1154 usb_unanchor_urb(urb);
1155 ucan_clean_up_tx_urb(up, urb);
1156 if (!ucan_release_context(up, context))
1157 netdev_err(up->netdev,
1158 "xmit err: failed to release context\n");
1160 /* remove the skb from the echo stack - this also
1163 spin_lock_irqsave(&up->echo_skb_lock, flags);
1164 can_free_echo_skb(up->netdev, echo_index);
1165 spin_unlock_irqrestore(&up->echo_skb_lock, flags);
1167 if (ret == -ENODEV) {
1168 netif_device_detach(up->netdev);
1170 netdev_warn(up->netdev,
1171 "xmit err: failed to submit urb %d\n",
1173 up->netdev->stats.tx_dropped++;
1175 return NETDEV_TX_OK;
1178 netif_trans_update(netdev);
1180 /* release ref, as we do not need the urb anymore */
1183 return NETDEV_TX_OK;
1186 if (!ucan_release_context(up, context))
1187 netdev_err(up->netdev,
1188 "xmit drop: failed to release context\n");
1190 up->netdev->stats.tx_dropped++;
1192 return NETDEV_TX_OK;
1197 * Clean up used resources
1199 static int ucan_close(struct net_device *netdev)
1202 struct ucan_priv *up = netdev_priv(netdev);
1204 up->can.state = CAN_STATE_STOPPED;
1206 /* stop sending data */
1207 usb_kill_anchored_urbs(&up->tx_urbs);
1209 /* stop receiving data */
1210 usb_kill_anchored_urbs(&up->rx_urbs);
1212 /* stop and reset can device */
1213 ret = ucan_ctrl_command_out(up, UCAN_COMMAND_STOP, 0, 0);
1215 netdev_err(up->netdev,
1216 "could not stop device, code: %d\n",
1219 ret = ucan_ctrl_command_out(up, UCAN_COMMAND_RESET, 0, 0);
1221 netdev_err(up->netdev,
1222 "could not reset device, code: %d\n",
1225 netif_stop_queue(netdev);
1227 ucan_release_context_array(up);
1229 close_candev(up->netdev);
1233 /* CAN driver callbacks */
1234 static const struct net_device_ops ucan_netdev_ops = {
1235 .ndo_open = ucan_open,
1236 .ndo_stop = ucan_close,
1237 .ndo_start_xmit = ucan_start_xmit,
1238 .ndo_change_mtu = can_change_mtu,
1241 /* Request to set bittiming
1243 * This function generates an USB set bittiming message and transmits
1246 static int ucan_set_bittiming(struct net_device *netdev)
1249 struct ucan_priv *up = netdev_priv(netdev);
1250 struct ucan_ctl_cmd_set_bittiming *cmd_set_bittiming;
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;
1262 ret = ucan_ctrl_command_out(up, UCAN_COMMAND_SET_BITTIMING, 0,
1263 sizeof(*cmd_set_bittiming));
1264 return (ret < 0) ? ret : 0;
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".
1270 static int ucan_set_mode(struct net_device *netdev, enum can_mode mode)
1273 unsigned long flags;
1274 struct ucan_priv *up = netdev_priv(netdev);
1277 case CAN_MODE_START:
1278 netdev_dbg(up->netdev, "restarting device\n");
1280 ret = ucan_ctrl_command_out(up, UCAN_COMMAND_RESTART, 0, 0);
1281 up->can.state = CAN_STATE_ERROR_ACTIVE;
1283 /* check if queue can be restarted,
1284 * up->available_tx_urbs must be protected by the
1287 spin_lock_irqsave(&up->context_lock, flags);
1289 if (up->available_tx_urbs > 0)
1290 netif_wake_queue(up->netdev);
1292 spin_unlock_irqrestore(&up->context_lock, flags);
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)
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;
1316 union ucan_ctl_payload *ctl_msg_buffer;
1317 char firmware_str[sizeof(union ucan_ctl_payload) + 1];
1319 udev = interface_to_usbdev(intf);
1321 /* Stage 1 - Interface Parsing
1322 * ---------------------------
1324 * Identifie the device USB interface descriptor and its
1325 * endpoints. Probing is aborted on errors.
1328 /* check if the interface is sane */
1329 iface_desc = intf->cur_altsetting;
1333 dev_info(&udev->dev,
1334 "%s: probing device on interface #%d\n",
1336 iface_desc->desc.bInterfaceNumber);
1338 /* interface sanity check */
1339 if (iface_desc->desc.bNumEndpoints != 2) {
1341 "%s: invalid EP count (%d)",
1342 UCAN_DRIVER_NAME, iface_desc->desc.bNumEndpoints);
1343 goto err_firmware_needs_update;
1346 /* check interface endpoints */
1351 for (i = 0; i < iface_desc->desc.bNumEndpoints; i++) {
1352 ep = &iface_desc->endpoint[i].desc;
1354 if (((ep->bEndpointAddress & USB_ENDPOINT_DIR_MASK) != 0) &&
1355 ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
1356 USB_ENDPOINT_XFER_BULK)) {
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) ==
1363 ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
1364 USB_ENDPOINT_XFER_BULK)) {
1366 out_ep_addr = ep->bEndpointAddress;
1367 out_ep_addr &= USB_ENDPOINT_NUMBER_MASK;
1368 out_ep_size = le16_to_cpu(ep->wMaxPacketSize);
1372 /* check if interface is sane */
1373 if (!in_ep_addr || !out_ep_addr) {
1374 dev_err(&udev->dev, "%s: invalid endpoint configuration\n",
1376 goto err_firmware_needs_update;
1378 if (in_ep_size < sizeof(struct ucan_message_in)) {
1379 dev_err(&udev->dev, "%s: invalid in_ep MaxPacketSize\n",
1381 goto err_firmware_needs_update;
1383 if (out_ep_size < sizeof(struct ucan_message_out)) {
1384 dev_err(&udev->dev, "%s: invalid out_ep MaxPacketSize\n",
1386 goto err_firmware_needs_update;
1389 /* Stage 2 - Device Identification
1390 * -------------------------------
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.
1400 /* Prepare Memory for control transferes */
1401 ctl_msg_buffer = devm_kzalloc(&udev->dev,
1402 sizeof(union ucan_ctl_payload),
1404 if (!ctl_msg_buffer) {
1406 "%s: failed to allocate control pipe memory\n",
1411 /* get protocol version
1413 * note: ucan_ctrl_command_* wrappers cannot be used yet
1414 * because `up` is initialised in Stage 3
1416 ret = usb_control_msg(udev,
1417 usb_rcvctrlpipe(udev, 0),
1419 USB_DIR_IN | USB_TYPE_VENDOR |
1420 USB_RECIP_INTERFACE,
1421 UCAN_COMMAND_GET_PROTOCOL_VERSION,
1422 iface_desc->desc.bInterfaceNumber,
1424 sizeof(union ucan_ctl_payload),
1425 UCAN_USB_CTL_PIPE_TIMEOUT);
1427 /* older firmware version do not support this command - those
1428 * are not supported by this drive
1432 "%s: could not read protocol version, ret=%d\n",
1433 UCAN_DRIVER_NAME, ret);
1436 goto err_firmware_needs_update;
1439 /* this driver currently supports protocol version 3 only */
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) {
1445 "%s: device protocol version %d is not supported\n",
1446 UCAN_DRIVER_NAME, protocol_version);
1447 goto err_firmware_needs_update;
1450 /* request the device information and store it in ctl_msg_buffer
1452 * note: ucan_ctrl_command_* wrappers connot be used yet
1453 * because `up` is initialised in Stage 3
1455 ret = usb_control_msg(udev,
1456 usb_rcvctrlpipe(udev, 0),
1458 USB_DIR_IN | USB_TYPE_VENDOR |
1459 USB_RECIP_INTERFACE,
1460 UCAN_COMMAND_GET_INFO,
1461 iface_desc->desc.bInterfaceNumber,
1463 sizeof(ctl_msg_buffer->cmd_get_device_info),
1464 UCAN_USB_CTL_PIPE_TIMEOUT);
1467 dev_err(&udev->dev, "%s: failed to retrieve device info\n",
1469 goto err_firmware_needs_update;
1471 if (ret < sizeof(ctl_msg_buffer->cmd_get_device_info)) {
1472 dev_err(&udev->dev, "%s: device reported invalid device info\n",
1474 goto err_firmware_needs_update;
1476 if (ctl_msg_buffer->cmd_get_device_info.tx_fifo == 0) {
1478 "%s: device reported invalid tx-fifo size\n",
1480 goto err_firmware_needs_update;
1483 /* Stage 3 - Driver Initialisation
1484 * -------------------------------
1486 * Register device to Linux, prepare private structures and
1490 /* allocate driver resources */
1491 netdev = alloc_candev(sizeof(struct ucan_priv),
1492 ctl_msg_buffer->cmd_get_device_info.tx_fifo);
1495 "%s: cannot allocate candev\n", UCAN_DRIVER_NAME);
1499 up = netdev_priv(netdev);
1501 /* initialze data */
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;
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;
1521 usb_set_intfdata(intf, up);
1522 SET_NETDEV_DEV(netdev, &intf->dev);
1524 /* parse device information
1525 * the data retrieved in Stage 2 is still available in
1526 * up->ctl_msg_buffer
1528 ucan_parse_device_info(up, &ctl_msg_buffer->cmd_get_device_info);
1530 /* just print some device information - if available */
1531 ret = ucan_device_request_in(up, UCAN_DEVICE_GET_FW_STRING, 0,
1532 sizeof(union ucan_ctl_payload));
1534 /* copy string while ensuring zero terminiation */
1535 strncpy(firmware_str, up->ctl_msg_buffer->raw,
1536 sizeof(union ucan_ctl_payload));
1537 firmware_str[sizeof(union ucan_ctl_payload)] = '\0';
1539 strcpy(firmware_str, "unknown");
1542 /* device is compatible, reset it */
1543 ret = ucan_ctrl_command_out(up, UCAN_COMMAND_RESET, 0, 0);
1545 goto err_free_candev;
1547 init_usb_anchor(&up->rx_urbs);
1548 init_usb_anchor(&up->tx_urbs);
1550 up->can.state = CAN_STATE_STOPPED;
1552 /* register the device */
1553 ret = register_candev(netdev);
1555 goto err_free_candev;
1557 /* initialisation complete, log device info */
1558 netdev_info(up->netdev, "registered device\n");
1559 netdev_info(up->netdev, "firmware string: %s\n", firmware_str);
1565 free_candev(netdev);
1568 err_firmware_needs_update:
1570 "%s: probe failed; try to update the device firmware\n",
1575 /* disconnect the device */
1576 static void ucan_disconnect(struct usb_interface *intf)
1578 struct usb_device *udev;
1579 struct ucan_priv *up = usb_get_intfdata(intf);
1581 udev = interface_to_usbdev(intf);
1583 usb_set_intfdata(intf, NULL);
1586 unregister_netdev(up->netdev);
1587 free_candev(up->netdev);
1591 static struct usb_device_id ucan_table[] = {
1592 /* Mule (soldered onto compute modules) */
1593 {USB_DEVICE_INTERFACE_NUMBER(0x2294, 0x425a, 0)},
1594 /* Seal (standalone USB stick) */
1595 {USB_DEVICE_INTERFACE_NUMBER(0x2294, 0x425b, 0)},
1596 {} /* Terminating entry */
1599 MODULE_DEVICE_TABLE(usb, ucan_table);
1600 /* driver callbacks */
1601 static struct usb_driver ucan_driver = {
1602 .name = UCAN_DRIVER_NAME,
1603 .probe = ucan_probe,
1604 .disconnect = ucan_disconnect,
1605 .id_table = ucan_table,
1608 module_usb_driver(ucan_driver);
1610 MODULE_LICENSE("GPL v2");
1613 MODULE_DESCRIPTION("Driver for Theobroma Systems UCAN devices");