/* Driver for Theobroma Systems UCAN devices, Protocol Version 3 * * Copyright (C) 2018 Theobroma Systems Design und Consulting GmbH * * * General Description: * * The USB Device uses three Endpoints: * * CONTROL Endpoint: Is used the setup the device (start, stop, * info, configure). * * IN Endpoint: The device sends CAN Frame Messages and Device * Information using the IN endpoint. * * OUT Endpoint: The driver sends configuration requests, and CAN * Frames on the out endpoint. * * Error Handling: * * If error reporting is turned on the device encodes error into CAN * error frames (see uapi/linux/can/error.h) and sends it using the * IN Endpoint. The driver updates statistics and forward it.
*/
#define UCAN_DRIVER_NAME "ucan" #define UCAN_MAX_RX_URBS 8 /* the CAN controller needs a while to enable/disable the bus */ #define UCAN_USB_CTL_PIPE_TIMEOUT 1000 /* this driver currently supports protocol version 3 only */ #define UCAN_PROTOCOL_VERSION_MIN 3 #define UCAN_PROTOCOL_VERSION_MAX 3
/* UCAN Message Definitions * ------------------------ * * ucan_message_out_t and ucan_message_in_t define the messages * transmitted on the OUT and IN endpoint. * * Multibyte fields are transmitted with little endianness * * INTR Endpoint: a single uint32_t storing the current space in the fifo * * OUT Endpoint: single message of type ucan_message_out_t is * transmitted on the out endpoint * * IN Endpoint: multiple messages ucan_message_in_t concateted in * the following way: * * m[n].len <=> the length if message n(including the header in bytes) * m[n] is is aligned to a 4 byte boundary, hence * offset(m[0]) := 0; * offset(m[n+1]) := offset(m[n]) + (m[n].len + 3) & 3 * * this implies that * offset(m[n]) % 4 <=> 0
*/
/* UCAN Commands */ enum { /* start the can transceiver - val defines the operation mode */
UCAN_COMMAND_START = 0, /* cancel pending transmissions and stop the can transceiver */
UCAN_COMMAND_STOP = 1, /* send can transceiver into low-power sleep mode */
UCAN_COMMAND_SLEEP = 2, /* wake up can transceiver from low-power sleep mode */
UCAN_COMMAND_WAKEUP = 3, /* reset the can transceiver */
UCAN_COMMAND_RESET = 4, /* get piece of info from the can transceiver - subcmd defines what * piece
*/
UCAN_COMMAND_GET = 5, /* clear or disable hardware filter - subcmd defines which of the two */
UCAN_COMMAND_FILTER = 6, /* Setup bittiming */
UCAN_COMMAND_SET_BITTIMING = 7, /* recover from bus-off state */
UCAN_COMMAND_RESTART = 8,
};
/* UCAN_COMMAND_START and UCAN_COMMAND_GET_INFO operation modes (bitmap). * Undefined bits must be set to 0.
*/ enum {
UCAN_MODE_LOOPBACK = BIT(0),
UCAN_MODE_SILENT = BIT(1),
UCAN_MODE_3_SAMPLES = BIT(2),
UCAN_MODE_ONE_SHOT = BIT(3),
UCAN_MODE_BERR_REPORT = BIT(4),
};
/* CAN Data message format within ucan_message_in/out */ struct ucan_can_msg { /* note DLC is computed by * msg.len - sizeof (msg.len) * - sizeof (msg.type) * - sizeof (msg.can_msg.id)
*/
__le32 id;
union {
u8 data[CAN_MAX_DLEN]; /* Data of CAN frames */
u8 dlc; /* RTR dlc */
};
} __packed;
/* OUT Endpoint, outbound messages */ struct ucan_message_out {
__le16 len; /* Length of the content include header */
u8 type; /* UCAN_OUT_TX and friends */
u8 subtype; /* command sub type */
union { /* Transmit CAN frame * (type == UCAN_TX) && ((msg.can_msg.id & CAN_RTR_FLAG) == 0) * subtype stores the echo id
*/ struct ucan_can_msg can_msg;
} msg;
} __packed __aligned(0x4);
/* IN Endpoint, inbound messages */ struct ucan_message_in {
__le16 len; /* Length of the content include header */
u8 type; /* UCAN_IN_RX and friends */
u8 subtype; /* command sub type */
union { /* CAN Frame received * (type == UCAN_IN_RX) * && ((msg.can_msg.id & CAN_RTR_FLAG) == 0)
*/ struct ucan_can_msg can_msg;
for (i = 0; i < up->device_info.tx_fifo; i++) { if (!up->context_array[i].allocated) { /* update context */
ret = &up->context_array[i];
up->context_array[i].allocated = true;
/* stop queue if necessary */
up->available_tx_urbs--; if (!up->available_tx_urbs)
netif_stop_queue(up->netdev);
if (ctrlmodes & UCAN_MODE_LOOPBACK)
up->can.ctrlmode_supported |= CAN_CTRLMODE_LOOPBACK; if (ctrlmodes & UCAN_MODE_SILENT)
up->can.ctrlmode_supported |= CAN_CTRLMODE_LISTENONLY; if (ctrlmodes & UCAN_MODE_3_SAMPLES)
up->can.ctrlmode_supported |= CAN_CTRLMODE_3_SAMPLES; if (ctrlmodes & UCAN_MODE_ONE_SHOT)
up->can.ctrlmode_supported |= CAN_CTRLMODE_ONE_SHOT; if (ctrlmodes & UCAN_MODE_BERR_REPORT)
up->can.ctrlmode_supported |= CAN_CTRLMODE_BERR_REPORTING;
}
/* Handle a CAN error frame that we have received from the device. * Returns true if the can state has changed.
*/ staticbool ucan_handle_error_frame(struct ucan_priv *up, struct ucan_message_in *m,
canid_t canid)
{ enum can_state new_state = up->can.state; struct net_device_stats *net_stats = &up->netdev->stats; struct can_device_stats *can_stats = &up->can.can_stats;
if (canid & CAN_ERR_LOSTARB)
can_stats->arbitration_lost++;
if (canid & CAN_ERR_BUSERROR)
can_stats->bus_error++;
if (canid & CAN_ERR_ACK)
net_stats->tx_errors++;
if (canid & CAN_ERR_BUSOFF)
new_state = CAN_STATE_BUS_OFF;
/* controller problems, details in data[1] */ if (canid & CAN_ERR_CRTL) {
u8 d1 = m->msg.can_msg.data[1];
if (d1 & CAN_ERR_CRTL_RX_OVERFLOW)
net_stats->rx_over_errors++;
/* controller state bits: if multiple are set the worst wins */ if (d1 & CAN_ERR_CRTL_ACTIVE)
new_state = CAN_STATE_ERROR_ACTIVE;
if (d1 & (CAN_ERR_CRTL_RX_WARNING | CAN_ERR_CRTL_TX_WARNING))
new_state = CAN_STATE_ERROR_WARNING;
if (d1 & (CAN_ERR_CRTL_RX_PASSIVE | CAN_ERR_CRTL_TX_PASSIVE))
new_state = CAN_STATE_ERROR_PASSIVE;
}
/* protocol error, details in data[2] */ if (canid & CAN_ERR_PROT) {
u8 d2 = m->msg.can_msg.data[2];
if (d2 & CAN_ERR_PROT_TX)
net_stats->tx_errors++; else
net_stats->rx_errors++;
}
/* no state change - we are done */ if (up->can.state == new_state) returnfalse;
/* we switched into a better state */ if (up->can.state > new_state) {
up->can.state = new_state; returntrue;
}
/* we switched into a worse state */
up->can.state = new_state; switch (new_state) { case CAN_STATE_BUS_OFF:
can_stats->bus_off++;
can_bus_off(up->netdev); break; case CAN_STATE_ERROR_PASSIVE:
can_stats->error_passive++; break; case CAN_STATE_ERROR_WARNING:
can_stats->error_warning++; break; default: break;
} returntrue;
}
/* Callback on reception of a can frame via the IN endpoint * * This function allocates an skb and transferres it to the Linux * network stack
*/ staticvoid ucan_rx_can_msg(struct ucan_priv *up, struct ucan_message_in *m)
{ int len;
canid_t canid; struct can_frame *cf; struct sk_buff *skb; struct net_device_stats *stats = &up->netdev->stats;
/* get the contents of the length field */
len = le16_to_cpu(m->len);
/* handle error frames */
canid = le32_to_cpu(m->msg.can_msg.id); if (canid & CAN_ERR_FLAG) { bool busstate_changed = ucan_handle_error_frame(up, m, canid);
/* if berr-reporting is off only state changes get through */ if (!(up->can.ctrlmode & CAN_CTRLMODE_BERR_REPORTING) &&
!busstate_changed) return;
} else {
canid_t canid_mask; /* compute the mask for canid */
canid_mask = CAN_RTR_FLAG; if (canid & CAN_EFF_FLAG)
canid_mask |= CAN_EFF_MASK | CAN_EFF_FLAG; else
canid_mask |= CAN_SFF_MASK;
if (canid & ~canid_mask)
netdev_warn(up->netdev, "unexpected bits set (canid %x, mask %x)",
canid, canid_mask);
/* copy the payload of non RTR frames */ if (!(cf->can_id & CAN_RTR_FLAG) || (cf->can_id & CAN_ERR_FLAG))
memcpy(cf->data, m->msg.can_msg.data, cf->len);
/* don't count error frames as real packets */ if (!(cf->can_id & CAN_ERR_FLAG)) {
stats->rx_packets++; if (!(cf->can_id & CAN_RTR_FLAG))
stats->rx_bytes += cf->len;
}
/* callback on reception of a USB message */ staticvoid ucan_read_bulk_callback(struct urb *urb)
{ int ret; int pos; struct ucan_priv *up = urb->context; struct net_device *netdev = up->netdev; struct ucan_message_in *m;
/* the device is not up and the driver should not receive any * data on the bulk in pipe
*/ if (WARN_ON(!up->context_array)) {
usb_free_coherent(up->udev,
up->in_ep_size,
urb->transfer_buffer,
urb->transfer_dma); return;
}
/* check URB status */ switch (urb->status) { case 0: break; case -ENOENT: case -EPIPE: case -EPROTO: case -ESHUTDOWN: case -ETIME: /* urb is not resubmitted -> free dma data */
usb_free_coherent(up->udev,
up->in_ep_size,
urb->transfer_buffer,
urb->transfer_dma);
netdev_dbg(up->netdev, "not resubmitting urb; status: %d\n",
urb->status); return; default: goto resubmit;
}
/* sanity check */ if (!netif_device_present(netdev)) return;
/* iterate over input */
pos = 0; while (pos < urb->actual_length) { int len;
/* check sanity (length of header) */ if ((urb->actual_length - pos) < UCAN_IN_HDR_SIZE) {
netdev_warn(up->netdev, "invalid message (short; no hdr; l:%d)\n",
urb->actual_length); goto resubmit;
}
/* setup the message address */
m = (struct ucan_message_in *)
((u8 *)urb->transfer_buffer + pos);
len = le16_to_cpu(m->len);
/* sanity check */ if (!netif_device_present(up->netdev)) return;
/* transmission failed (USB - the device will not send a TX complete) */ if (urb->status) {
netdev_warn(up->netdev, "failed to transmit USB message to device: %d\n",
urb->status);
/* release context and restart the queue if necessary */ if (!ucan_release_context(up, context))
netdev_err(up->netdev, "urb failed, failed to release context\n");
}
}
staticvoid ucan_cleanup_rx_urbs(struct ucan_priv *up, struct urb **urbs)
{ int i;
for (i = 0; i < UCAN_MAX_RX_URBS; i++) { if (urbs[i]) {
usb_unanchor_urb(urbs[i]);
usb_free_coherent(up->udev,
up->in_ep_size,
urbs[i]->transfer_buffer,
urbs[i]->transfer_dma);
usb_free_urb(urbs[i]);
}
}
err: /* cleanup other unsubmitted urbs */
ucan_cleanup_rx_urbs(up, urbs); return -ENOMEM;
}
/* Submits rx urbs with the semantic: Either submit all, or cleanup * everything. I case of errors submitted urbs are killed and all urbs in * the array are freed. I case of no errors every entry in the urb * array is set to NULL.
*/ staticint ucan_submit_rx_urbs(struct ucan_priv *up, struct urb **urbs)
{ int i, ret;
/* Iterate over all urbs to submit. On success remove the urb * from the list.
*/ for (i = 0; i < UCAN_MAX_RX_URBS; i++) {
ret = usb_submit_urb(urbs[i], GFP_KERNEL); if (ret) {
netdev_err(up->netdev, "could not submit urb; code: %d\n",
ret); goto err;
}
/* Anchor URB and drop reference, USB core will take * care of freeing it
*/
usb_free_urb(urbs[i]);
urbs[i] = NULL;
} return 0;
err: /* Cleanup unsubmitted urbs */
ucan_cleanup_rx_urbs(up, urbs);
/* Kill urbs that are already submitted */
usb_kill_anchored_urbs(&up->rx_urbs);
return ret;
}
/* Open the network device */ staticint ucan_open(struct net_device *netdev)
{ int ret, ret_cleanup;
u16 ctrlmode; struct urb *urbs[UCAN_MAX_RX_URBS]; struct ucan_priv *up = netdev_priv(netdev);
ret = ucan_alloc_context_array(up); if (ret) return ret;
/* Allocate and prepare IN URBS - allocated and anchored * urbs are stored in urbs[] for clean
*/
ret = ucan_prepare_and_anchor_rx_urbs(up, urbs); if (ret) goto err_contexts;
/* Check the control mode */
ctrlmode = 0; if (up->can.ctrlmode & CAN_CTRLMODE_LOOPBACK)
ctrlmode |= UCAN_MODE_LOOPBACK; if (up->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)
ctrlmode |= UCAN_MODE_SILENT; if (up->can.ctrlmode & CAN_CTRLMODE_3_SAMPLES)
ctrlmode |= UCAN_MODE_3_SAMPLES; if (up->can.ctrlmode & CAN_CTRLMODE_ONE_SHOT)
ctrlmode |= UCAN_MODE_ONE_SHOT;
/* Enable this in any case - filtering is down within the * receive path
*/
ctrlmode |= UCAN_MODE_BERR_REPORT;
up->ctl_msg_buffer->cmd_start.mode = cpu_to_le16(ctrlmode);
/* Driver is ready to receive data - start the USB device */
ret = ucan_ctrl_command_out(up, UCAN_COMMAND_START, 0, 2); if (ret < 0) {
netdev_err(up->netdev, "could not start device, code: %d\n",
ret); goto err_reset;
}
/* Call CAN layer open */
ret = open_candev(netdev); if (ret) goto err_stop;
/* Driver is ready to receive data. Submit RX URBS */
ret = ucan_submit_rx_urbs(up, urbs); if (ret) goto err_stop;
up->can.state = CAN_STATE_ERROR_ACTIVE;
/* Start the network queue */
netif_start_queue(netdev);
return 0;
err_stop: /* The device have started already stop it */
ret_cleanup = ucan_ctrl_command_out(up, UCAN_COMMAND_STOP, 0, 0); if (ret_cleanup < 0)
netdev_err(up->netdev, "could not stop device, code: %d\n",
ret_cleanup);
err_reset: /* The device might have received data, reset it for * consistent state
*/
ret_cleanup = ucan_ctrl_command_out(up, UCAN_COMMAND_RESET, 0, 0); if (ret_cleanup < 0)
netdev_err(up->netdev, "could not reset device, code: %d\n",
ret_cleanup);
/* clean up unsubmitted urbs */
ucan_cleanup_rx_urbs(up, urbs);
/* create a URB, and a buffer for it, and copy the data to the URB */
urb = usb_alloc_urb(0, GFP_ATOMIC); if (!urb) {
netdev_err(up->netdev, "no memory left for URBs\n"); return NULL;
}
m = usb_alloc_coherent(up->udev, sizeof(struct ucan_message_out),
GFP_ATOMIC,
&urb->transfer_dma); if (!m) {
netdev_err(up->netdev, "no memory left for USB buffer\n");
usb_free_urb(urb); return NULL;
}
/* build the USB message */
m->type = UCAN_OUT_TX;
m->msg.can_msg.id = cpu_to_le32(cf->can_id);
/* callback when Linux needs to send a can frame */ static netdev_tx_t ucan_start_xmit(struct sk_buff *skb, struct net_device *netdev)
{ unsignedlong flags; int ret;
u8 echo_index; struct urb *urb; struct ucan_urb_context *context; struct ucan_priv *up = netdev_priv(netdev); struct can_frame *cf = (struct can_frame *)skb->data;
/* check skb */ if (can_dev_dropped_skb(netdev, skb)) return NETDEV_TX_OK;
/* allocate a context and slow down tx path, if fifo state is low */
context = ucan_alloc_context(up);
echo_index = context - up->context_array;
if (WARN_ON_ONCE(!context)) return NETDEV_TX_BUSY;
/* prepare urb for transmission */
urb = ucan_prepare_tx_urb(up, context, cf, echo_index); if (!urb) goto drop;
/* put the skb on can loopback stack */
spin_lock_irqsave(&up->echo_skb_lock, flags);
can_put_echo_skb(skb, up->netdev, echo_index, 0);
spin_unlock_irqrestore(&up->echo_skb_lock, flags);
/* transmit it */
usb_anchor_urb(urb, &up->tx_urbs);
ret = usb_submit_urb(urb, GFP_ATOMIC);
/* cleanup urb */ if (ret) { /* on error, clean up */
usb_unanchor_urb(urb);
ucan_clean_up_tx_urb(up, urb); if (!ucan_release_context(up, context))
netdev_err(up->netdev, "xmit err: failed to release context\n");
/* remove the skb from the echo stack - this also * frees the skb
*/
spin_lock_irqsave(&up->echo_skb_lock, flags);
can_free_echo_skb(up->netdev, echo_index, NULL);
spin_unlock_irqrestore(&up->echo_skb_lock, flags);
/* release ref, as we do not need the urb anymore */
usb_free_urb(urb);
return NETDEV_TX_OK;
drop: if (!ucan_release_context(up, context))
netdev_err(up->netdev, "xmit drop: failed to release context\n");
dev_kfree_skb(skb);
up->netdev->stats.tx_dropped++;
return NETDEV_TX_OK;
}
/* Device goes down * * Clean up used resources
*/ staticint ucan_close(struct net_device *netdev)
{ int ret; struct ucan_priv *up = netdev_priv(netdev);
up->can.state = CAN_STATE_STOPPED;
/* stop sending data */
usb_kill_anchored_urbs(&up->tx_urbs);
/* stop receiving data */
usb_kill_anchored_urbs(&up->rx_urbs);
/* stop and reset can device */
ret = ucan_ctrl_command_out(up, UCAN_COMMAND_STOP, 0, 0); if (ret < 0)
netdev_err(up->netdev, "could not stop device, code: %d\n",
ret);
ret = ucan_ctrl_command_out(up, UCAN_COMMAND_RESET, 0, 0); if (ret < 0)
netdev_err(up->netdev, "could not reset device, code: %d\n",
ret);
/* Request to set bittiming * * This function generates an USB set bittiming message and transmits * it to the device
*/ staticint ucan_set_bittiming(struct net_device *netdev)
{ int ret; struct ucan_priv *up = netdev_priv(netdev); struct ucan_ctl_cmd_set_bittiming *cmd_set_bittiming;
ret = ucan_ctrl_command_out(up, UCAN_COMMAND_SET_BITTIMING, 0, sizeof(*cmd_set_bittiming)); return (ret < 0) ? ret : 0;
}
/* Restart the device to get it out of BUS-OFF state. * Called when the user runs "ip link set can1 type can restart".
*/ staticint ucan_set_mode(struct net_device *netdev, enum can_mode mode)
{ int ret; unsignedlong flags; struct ucan_priv *up = netdev_priv(netdev);
switch (mode) { case CAN_MODE_START:
netdev_dbg(up->netdev, "restarting device\n");
ret = ucan_ctrl_command_out(up, UCAN_COMMAND_RESTART, 0, 0);
up->can.state = CAN_STATE_ERROR_ACTIVE;
/* check if queue can be restarted, * up->available_tx_urbs must be protected by the * lock
*/
spin_lock_irqsave(&up->context_lock, flags);
if (up->available_tx_urbs > 0)
netif_wake_queue(up->netdev);
spin_unlock_irqrestore(&up->context_lock, flags);
return ret; default: return -EOPNOTSUPP;
}
}
/* Probe the device, reset it and gather general device information */ staticint ucan_probe(struct usb_interface *intf, conststruct usb_device_id *id)
{ int ret; int i;
u32 protocol_version; struct usb_device *udev; struct net_device *netdev; struct usb_host_interface *iface_desc; struct ucan_priv *up; struct usb_endpoint_descriptor *ep;
u16 in_ep_size;
u16 out_ep_size;
u8 in_ep_addr;
u8 out_ep_addr; union ucan_ctl_payload *ctl_msg_buffer;
udev = interface_to_usbdev(intf);
/* Stage 1 - Interface Parsing * --------------------------- * * Identifie the device USB interface descriptor and its * endpoints. Probing is aborted on errors.
*/
/* check if the interface is sane */
iface_desc = intf->cur_altsetting; if (!iface_desc) return -ENODEV;
dev_info(&udev->dev, "%s: probing device on interface #%d\n",
UCAN_DRIVER_NAME,
iface_desc->desc.bInterfaceNumber);
/* Stage 2 - Device Identification * ------------------------------- * * The device interface seems to be a ucan device. Do further * compatibility checks. On error probing is aborted, on * success this stage leaves the ctl_msg_buffer with the * reported contents of a GET_INFO command (supported * bittimings, tx_fifo depth). This information is used in * Stage 3 for the final driver initialisation.
*/
/* Prepare Memory for control transfers */
ctl_msg_buffer = devm_kzalloc(&udev->dev, sizeof(union ucan_ctl_payload),
GFP_KERNEL); if (!ctl_msg_buffer) {
dev_err(&udev->dev, "%s: failed to allocate control pipe memory\n",
UCAN_DRIVER_NAME); return -ENOMEM;
}
/* get protocol version * * note: ucan_ctrl_command_* wrappers cannot be used yet * because `up` is initialised in Stage 3
*/
ret = usb_control_msg(udev,
usb_rcvctrlpipe(udev, 0),
UCAN_COMMAND_GET,
USB_DIR_IN | USB_TYPE_VENDOR |
USB_RECIP_INTERFACE,
UCAN_COMMAND_GET_PROTOCOL_VERSION,
iface_desc->desc.bInterfaceNumber,
ctl_msg_buffer, sizeof(union ucan_ctl_payload),
UCAN_USB_CTL_PIPE_TIMEOUT);
/* older firmware version do not support this command - those * are not supported by this drive
*/ if (ret != 4) {
dev_err(&udev->dev, "%s: could not read protocol version, ret=%d\n",
UCAN_DRIVER_NAME, ret); if (ret >= 0)
ret = -EINVAL; goto err_firmware_needs_update;
}
/* this driver currently supports protocol version 3 only */
protocol_version =
le32_to_cpu(ctl_msg_buffer->cmd_get_protocol_version.version); if (protocol_version < UCAN_PROTOCOL_VERSION_MIN ||
protocol_version > UCAN_PROTOCOL_VERSION_MAX) {
dev_err(&udev->dev, "%s: device protocol version %d is not supported\n",
UCAN_DRIVER_NAME, protocol_version); goto err_firmware_needs_update;
}
/* request the device information and store it in ctl_msg_buffer * * note: ucan_ctrl_command_* wrappers cannot be used yet * because `up` is initialised in Stage 3
*/
ret = usb_control_msg(udev,
usb_rcvctrlpipe(udev, 0),
UCAN_COMMAND_GET,
USB_DIR_IN | USB_TYPE_VENDOR |
USB_RECIP_INTERFACE,
UCAN_COMMAND_GET_INFO,
iface_desc->desc.bInterfaceNumber,
ctl_msg_buffer, sizeof(ctl_msg_buffer->cmd_get_device_info),
UCAN_USB_CTL_PIPE_TIMEOUT);
/* parse device information * the data retrieved in Stage 2 is still available in * up->ctl_msg_buffer
*/
ucan_parse_device_info(up, &ctl_msg_buffer->cmd_get_device_info);
/* device is compatible, reset it */
ret = ucan_ctrl_command_out(up, UCAN_COMMAND_RESET, 0, 0); if (ret < 0) goto err_free_candev;
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.