CTU CAN FD Driver

Author: Martin Jerabek <martin.jerabek01@gmail.com>

About CTU CAN FD IP Core

CTU CAN FD is an open source soft core written in VHDL. It originated in 2015 as Ondrej Ille’s project at the Department of Measurement of FEE at CTU.

The SocketCAN driver for Xilinx Zynq SoC based MicroZed board Vivado integration and Intel Cyclone V 5CSEMA4U23C6 based DE0-Nano-SoC Terasic board QSys integration has been developed as well as support for PCIe integration of the core.

In the case of Zynq, the core is connected via the APB system bus, which does not have enumeration support, and the device must be specified in Device Tree. This kind of devices is called platform device in the kernel and is handled by a platform device driver.

The basic functional model of the CTU CAN FD peripheral has been accepted into QEMU mainline. See QEMU CAN emulation support for CAN FD buses, host connection and CTU CAN FD core emulation. The development version of emulation support can be cloned from ctu-canfd branch of QEMU local development repository.

About SocketCAN

SocketCAN is a standard common interface for CAN devices in the Linux kernel. As the name suggests, the bus is accessed via sockets, similarly to common network devices. The reasoning behind this is in depth described in Linux SocketCAN. In short, it offers a natural way to implement and work with higher layer protocols over CAN, in the same way as, e.g., UDP/IP over Ethernet.

Device probe

Before going into detail about the structure of a CAN bus device driver, let’s reiterate how the kernel gets to know about the device at all. Some buses, like PCI or PCIe, support device enumeration. That is, when the system boots, it discovers all the devices on the bus and reads their configuration. The kernel identifies the device via its vendor ID and device ID, and if there is a driver registered for this identifier combination, its probe method is invoked to populate the driver’s instance for the given hardware. A similar situation goes with USB, only it allows for device hot-plug.

The situation is different for peripherals which are directly embedded in the SoC and connected to an internal system bus (AXI, APB, Avalon, and others). These buses do not support enumeration, and thus the kernel has to learn about the devices from elsewhere. This is exactly what the Device Tree was made for.

Device tree

An entry in device tree states that a device exists in the system, how it is reachable (on which bus it resides) and its configuration – registers address, interrupts and so on. An example of such a device tree is given in .

/ {
    /* ... */
    amba: amba {
        #address-cells = <1>;
        #size-cells = <1>;
        compatible = "simple-bus";

        CTU_CAN_FD_0: CTU_CAN_FD@43c30000 {
            compatible = "ctu,ctucanfd";
            interrupt-parent = <&intc>;
            interrupts = <0 30 4>;
            clocks = <&clkc 15>;
            reg = <0x43c30000 0x10000>;
        };
    };
};

Driver structure

The driver can be divided into two parts – platform-dependent device discovery and set up, and platform-independent CAN network device implementation.

Platform device driver

In the case of Zynq, the core is connected via the AXI system bus, which does not have enumeration support, and the device must be specified in Device Tree. This kind of devices is called platform device in the kernel and is handled by a platform device driver [1].

A platform device driver provides the following things:

  • A probe function
  • A remove function
  • A table of compatible devices that the driver can handle

The probe function is called exactly once when the device appears (or the driver is loaded, whichever happens later). If there are more devices handled by the same driver, the probe function is called for each one of them. Its role is to allocate and initialize resources required for handling the device, as well as set up low-level functions for the platform-independent layer, e.g., read_reg and write_reg. After that, the driver registers the device to a higher layer, in our case as a network device.

The remove function is called when the device disappears, or the driver is about to be unloaded. It serves to free the resources allocated in probe and to unregister the device from higher layers.

Finally, the table of compatible devices states which devices the driver can handle. The Device Tree entry compatible is matched against the tables of all platform drivers.

/* Match table for OF platform binding */
static const struct of_device_id ctucan_of_match[] = {
    { .compatible = "ctu,canfd-2", },
    { .compatible = "ctu,ctucanfd", },
    { /* end of list */ },
};
MODULE_DEVICE_TABLE(of, ctucan_of_match);

static int ctucan_probe(struct platform_device *pdev);
static int ctucan_remove(struct platform_device *pdev);

static struct platform_driver ctucanfd_driver = {
    .probe  = ctucan_probe,
    .remove = ctucan_remove,
    .driver = {
        .name = DRIVER_NAME,
        .of_match_table = ctucan_of_match,
    },
};
module_platform_driver(ctucanfd_driver);

Network device driver

Each network device must support at least these operations:

  • Bring the device up: ndo_open
  • Bring the device down: ndo_close
  • Submit TX frames to the device: ndo_start_xmit
  • Signal TX completion and errors to the network subsystem: ISR
  • Submit RX frames to the network subsystem: ISR and NAPI

There are two possible event sources: the device and the network subsystem. Device events are usually signaled via an interrupt, handled in an Interrupt Service Routine (ISR). Handlers for the events originating in the network subsystem are then specified in struct net_device_ops.

When the device is brought up, e.g., by calling ip link set can0 up, the driver’s function ndo_open is called. It should validate the interface configuration and configure and enable the device. The analogous opposite is ndo_close, called when the device is being brought down, be it explicitly or implicitly.

When the system should transmit a frame, it does so by calling ndo_start_xmit, which enqueues the frame into the device. If the device HW queue (FIFO, mailboxes or whatever the implementation is) becomes full, the ndo_start_xmit implementation informs the network subsystem that it should stop the TX queue (via netif_stop_queue). It is then re-enabled later in ISR when the device has some space available again and is able to enqueue another frame.

All the device events are handled in ISR, namely:

  1. TX completion. When the device successfully finishes transmitting a frame, the frame is echoed locally. On error, an informative error frame [2] is sent to the network subsystem instead. In both cases, the software TX queue is resumed so that more frames may be sent.
  2. Error condition. If something goes wrong (e.g., the device goes bus-off or RX overrun happens), error counters are updated, and informative error frames are enqueued to SW RX queue.
  3. RX buffer not empty. In this case, read the RX frames and enqueue them to SW RX queue. Usually NAPI is used as a middle layer (see ).

NAPI

The frequency of incoming frames can be high and the overhead to invoke the interrupt service routine for each frame can cause significant system load. There are multiple mechanisms in the Linux kernel to deal with this situation. They evolved over the years of Linux kernel development and enhancements. For network devices, the current standard is NAPI – the New API. It is similar to classical top-half/bottom-half interrupt handling in that it only acknowledges the interrupt in the ISR and signals that the rest of the processing should be done in softirq context. On top of that, it offers the possibility to poll for new frames for a while. This has a potential to avoid the costly round of enabling interrupts, handling an incoming IRQ in ISR, re-enabling the softirq and switching context back to softirq.

More detailed documentation of NAPI may be found on the pages of Linux Foundation https://wiki.linuxfoundation.org/networking/napi.

Integrating the core to Xilinx Zynq

The core interfaces a simple subset of the Avalon Avalon Interface Specifications bus as it was originally used on Alterra FPGA chips, yet Xilinx natively interfaces with AXI AMBA AXI and ACE Protocol Specification AXI3, AXI4, and AXI4-Lite, ACE and ACE-Lite. The most obvious solution would be to use an Avalon/AXI bridge or implement some simple conversion entity. However, the core’s interface is half-duplex with no handshake signaling, whereas AXI is full duplex with two-way signaling. Moreover, even AXI-Lite slave interface is quite resource-intensive, and the flexibility and speed of AXI are not required for a CAN core.

Thus a much simpler bus was chosen – APB (Advanced Peripheral Bus) AMBA APB Protocol Specification v2.0. APB-AXI bridge is directly available in Xilinx Vivado, and the interface adaptor entity is just a few simple combinatorial assignments.

Finally, to be able to include the core in a block diagram as a custom IP, the core, together with the APB interface, has been packaged as a Vivado component.

CTU CAN FD Driver design

The general structure of a CAN device driver has already been examined in . The next paragraphs provide a more detailed description of the CTU CAN FD core driver in particular.

Low-level driver

The core is not intended to be used solely with SocketCAN, and thus it is desirable to have an OS-independent low-level driver. This low-level driver can then be used in implementations of OS driver or directly either on bare metal or in a user-space application. Another advantage is that if the hardware slightly changes, only the low-level driver needs to be modified.

The code [3] is in part automatically generated and in part written manually by the core author, with contributions of the thesis’ author. The low-level driver supports operations such as: set bit timing, set controller mode, enable/disable, read RX frame, write TX frame, and so on.

Configuring bit timing

On CAN, each bit is divided into four segments: SYNC, PROP, PHASE1, and PHASE2. Their duration is expressed in multiples of a Time Quantum (details in CAN Specification, Version 2.0, chapter 8). When configuring bitrate, the durations of all the segments (and time quantum) must be computed from the bitrate and Sample Point. This is performed independently for both the Nominal bitrate and Data bitrate for CAN FD.

SocketCAN is fairly flexible and offers either highly customized configuration by setting all the segment durations manually, or a convenient configuration by setting just the bitrate and sample point (and even that is chosen automatically per Bosch recommendation if not specified). However, each CAN controller may have different base clock frequency and different width of segment duration registers. The algorithm thus needs the minimum and maximum values for the durations (and clock prescaler) and tries to optimize the numbers to fit both the constraints and the requested parameters.

struct can_bittiming_const {
    char name[16];      /* Name of the CAN controller hardware */
    __u32 tseg1_min;    /* Time segment 1 = prop_seg + phase_seg1 */
    __u32 tseg1_max;
    __u32 tseg2_min;    /* Time segment 2 = phase_seg2 */
    __u32 tseg2_max;
    __u32 sjw_max;      /* Synchronisation jump width */
    __u32 brp_min;      /* Bit-rate prescaler */
    __u32 brp_max;
    __u32 brp_inc;
};

[lst:can_bittiming_const]

A curious reader will notice that the durations of the segments PROP_SEG and PHASE_SEG1 are not determined separately but rather combined and then, by default, the resulting TSEG1 is evenly divided between PROP_SEG and PHASE_SEG1. In practice, this has virtually no consequences as the sample point is between PHASE_SEG1 and PHASE_SEG2. In CTU CAN FD, however, the duration registers PROP and PH1 have different widths (6 and 7 bits, respectively), so the auto-computed values might overflow the shorter register and must thus be redistributed among the two [4].

Handling RX

Frame reception is handled in NAPI queue, which is enabled from ISR when the RXNE (RX FIFO Not Empty) bit is set. Frames are read one by one until either no frame is left in the RX FIFO or the maximum work quota has been reached for the NAPI poll run (see ). Each frame is then passed to the network interface RX queue.

An incoming frame may be either a CAN 2.0 frame or a CAN FD frame. The way to distinguish between these two in the kernel is to allocate either struct can_frame or struct canfd_frame, the two having different sizes. In the controller, the information about the frame type is stored in the first word of RX FIFO.

This brings us a chicken-egg problem: we want to allocate the skb for the frame, and only if it succeeds, fetch the frame from FIFO; otherwise keep it there for later. But to be able to allocate the correct skb, we have to fetch the first work of FIFO. There are several possible solutions:

  1. Read the word, then allocate. If it fails, discard the rest of the frame. When the system is low on memory, the situation is bad anyway.
  2. Always allocate skb big enough for an FD frame beforehand. Then tweak the skb internals to look like it has been allocated for the smaller CAN 2.0 frame.
  3. Add option to peek into the FIFO instead of consuming the word.
  4. If the allocation fails, store the read word into driver’s data. On the next try, use the stored word instead of reading it again.

Option 1 is simple enough, but not very satisfying if we could do better. Option 2 is not acceptable, as it would require modifying the private state of an integral kernel structure. The slightly higher memory consumption is just a virtual cherry on top of the “cake”. Option 3 requires non-trivial HW changes and is not ideal from the HW point of view.

Option 4 seems like a good compromise, with its disadvantage being that a partial frame may stay in the FIFO for a prolonged time. Nonetheless, there may be just one owner of the RX FIFO, and thus no one else should see the partial frame (disregarding some exotic debugging scenarios). Basides, the driver resets the core on its initialization, so the partial frame cannot be “adopted” either. In the end, option 4 was selected [5].

Timestamping RX frames

The CTU CAN FD core reports the exact timestamp when the frame has been received. The timestamp is by default captured at the sample point of the last bit of EOF but is configurable to be captured at the SOF bit. The timestamp source is external to the core and may be up to 64 bits wide. At the time of writing, passing the timestamp from kernel to userspace is not yet implemented, but is planned in the future.

Handling TX

The CTU CAN FD core has 4 independent TX buffers, each with its own state and priority. When the core wants to transmit, a TX buffer in Ready state with the highest priority is selected.

The priorities are 3bit numbers in register TX_PRIORITY (nibble-aligned). This should be flexible enough for most use cases. SocketCAN, however, supports only one FIFO queue for outgoing frames [6]. The buffer priorities may be used to simulate the FIFO behavior by assigning each buffer a distinct priority and rotating the priorities after a frame transmission is completed.

In addition to priority rotation, the SW must maintain head and tail pointers into the FIFO formed by the TX buffers to be able to determine which buffer should be used for next frame (txb_head) and which should be the first completed one (txb_tail). The actual buffer indices are (obviously) modulo 4 (number of TX buffers), but the pointers must be at least one bit wider to be able to distinguish between FIFO full and FIFO empty – in this situation, . An example of how the FIFO is maintained, together with priority rotation, is depicted in


TXB# 0 1 2 3
Seq A B C  
Prio 7 6 5 4
    T   H

TXB# 0 1 2 3
Seq   B C  
Prio 4 7 6 5
    T   H

TXB# 0 1 2 3 0’
Seq E B C D  
Prio 4 7 6 5  
    T     H

_images/fsm_txt_buffer_user.svg

TX Buffer states with possible transitions

Timestamping TX frames

When submitting a frame to a TX buffer, one may specify the timestamp at which the frame should be transmitted. The frame transmission may start later, but not sooner. Note that the timestamp does not participate in buffer prioritization – that is decided solely by the mechanism described above.

Support for time-based packet transmission was recently merged to Linux v4.19 Time-based packet transmission, but it remains yet to be researched whether this functionality will be practical for CAN.

Also similarly to retrieving the timestamp of RX frames, the core supports retrieving the timestamp of TX frames – that is the time when the frame was successfully delivered. The particulars are very similar to timestamping RX frames and are described in .

Handling RX buffer overrun

When a received frame does no more fit into the hardware RX FIFO in its entirety, RX FIFO overrun flag (STATUS[DOR]) is set and Data Overrun Interrupt (DOI) is triggered. When servicing the interrupt, care must be taken first to clear the DOR flag (via COMMAND[CDO]) and after that clear the DOI interrupt flag. Otherwise, the interrupt would be immediately [7] rearmed.

Note: During development, it was discussed whether the internal HW pipelining cannot disrupt this clear sequence and whether an additional dummy cycle is necessary between clearing the flag and the interrupt. On the Avalon interface, it indeed proved to be the case, but APB being safe because it uses 2-cycle transactions. Essentially, the DOR flag would be cleared, but DOI register’s Preset input would still be high the cycle when the DOI clear request would also be applied (by setting the register’s Reset input high). As Set had higher priority than Reset, the DOI flag would not be reset. This has been already fixed by swapping the Set/Reset priority (see issue #187).

Reporting Error Passive and Bus Off conditions

It may be desirable to report when the node reaches Error Passive, Error Warning, and Bus Off conditions. The driver is notified about error state change by an interrupt (EPI, EWLI), and then proceeds to determine the core’s error state by reading its error counters.

There is, however, a slight race condition here – there is a delay between the time when the state transition occurs (and the interrupt is triggered) and when the error counters are read. When EPI is received, the node may be either Error Passive or Bus Off. If the node goes Bus Off, it obviously remains in the state until it is reset. Otherwise, the node is or was Error Passive. However, it may happen that the read state is Error Warning or even Error Active. It may be unclear whether and what exactly to report in that case, but I personally entertain the idea that the past error condition should still be reported. Similarly, when EWLI is received but the state is later detected to be Error Passive, Error Passive should be reported.

CTU CAN FD Driver Sources Reference

bool ctucan_hw_check_access(struct ctucan_hw_priv * priv)

Checks whether the core is mapped correctly at it’s base address.

Parameters

struct ctucan_hw_priv * priv
Private info

Return

true if the core is accessible correctly, false otherwise.

u32 ctucan_hw_get_version(struct ctucan_hw_priv * priv)

Returns version of CTU CAN FD IP Core.

Parameters

struct ctucan_hw_priv * priv
Private info

Return

IP Core version in format major*10 + minor

void ctucan_hw_enable(struct ctucan_hw_priv * priv, bool enable)

Enables/disables the operation of CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info
bool enable
Enable/disable the core.

Description

If disabled, the Core will never start transmitting on the CAN bus, nor receiving.

void ctucan_hw_reset(struct ctucan_hw_priv * priv)

Resets the CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info

NOTE

After resetting, you must wait until ctucan_hw_check_access() succeeds!

bool ctucan_hw_set_ret_limit(struct ctucan_hw_priv * priv, bool enable, u8 limit)

Set retransmit limit for sent messages

Parameters

struct ctucan_hw_priv * priv
Private info
bool enable
Enable/disable the retransmit limitation
u8 limit
Number to which limit the retransmission (1-CTU_CAN_FD_RETR_MAX)

Description

Configures CTU CAN FD Core to limit the amount of retransmit attempts after occurrence of error (Error frame, Arbitration lost). If retransmit limit is disabled, the Core will attempt to retransmit inifinitely. If retransmit limit is reached, the Core will finish and according TXT buffer will end up in TX Error state.

Return

True if set correctly. False if “limit” is too high.

void ctucan_hw_set_mode_reg(struct ctucan_hw_priv * priv, const struct can_ctrlmode * mode)

Configures CTU CAN FD Core for special operating modes by access to MODEregister.

Parameters

struct ctucan_hw_priv * priv
Private info
const struct can_ctrlmode * mode
CAN mode to be set to on the Core.

Description

Following flags from “mode” are not configured by this function:
CAN_CTRLMODE_ONE_SHOT, CAN_CTRLMODE_BERR_REPORTING.

Following flags are configured:

CAN_CTRLMODE_LOOPBACK - Bit loopback mode. Every dominant bit is
re-routed internally and not send on the bus.
CAN_CTRLMODE_LISTENONLY - No frame is transmitted, no dominant bit is
sent on the bus.

CAN_CTRLMODE_3_SAMPLES - Tripple sampling mode

CAN_CTRLMODE_FD - Flexible data-rate support. When not set, Core
does not accept CAN FD Frames and interprets, them as form error. Capability to transmit CAN FD Frames is not affected by this setting.
CAN_CTRLMODE_PRESUME_ACK - When set, Core does not require dominant bit
in ACK field to consider the transmission as valid.
CAN_CTRLMODE_FD_NON_ISO - When set, the Core transmits the frames
according to NON-ISO FD standard.
void ctucan_hw_rel_rx_buf(struct ctucan_hw_priv * priv)

Gives command to CTU CAN FD Core to erase and reset the RX FIFO.

Parameters

struct ctucan_hw_priv * priv
Private info

Description

This action is finished immediately and does not need waiting.

void ctucan_hw_clr_overrun_flag(struct ctucan_hw_priv * priv)

Gives command to CTU CAN FD Core to clear the Data overrun flag on the RX FIFO Buffer.

Parameters

struct ctucan_hw_priv * priv
Private info
union ctu_can_fd_status ctu_can_get_status(struct ctucan_hw_priv * priv)

Returns mode/status vector of CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info

Return

Mode/status structure with multiple mode flags.

bool ctucan_hw_is_enabled(struct ctucan_hw_priv * priv)

Test if core is enabled..

Parameters

struct ctucan_hw_priv * priv
Private info

Return

Return true if core is in enabled/active state..

union ctu_can_fd_int_stat ctu_can_fd_int_sts(struct ctucan_hw_priv * priv)

Reads the interrupt status vector from CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info

Return

Interrupt status vector.

void ctucan_hw_int_clr(struct ctucan_hw_priv * priv, union ctu_can_fd_int_stat mask)

Clears the interrupts from CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info
union ctu_can_fd_int_stat mask
Mask of interrupts which should be cleared.
void ctucan_hw_int_ena_set(struct ctucan_hw_priv * priv, union ctu_can_fd_int_stat mask)

Sets enable interrupt bits.

Parameters

struct ctucan_hw_priv * priv
Private info
union ctu_can_fd_int_stat mask
Mask of interrupts which should be disabled.
void ctucan_hw_int_ena_clr(struct ctucan_hw_priv * priv, union ctu_can_fd_int_stat mask)

Clears enable interrupt bits.

Parameters

struct ctucan_hw_priv * priv
Private info
union ctu_can_fd_int_stat mask
Mask of interrupts which should be disabled.
void ctucan_hw_int_ena(struct ctucan_hw_priv * priv, union ctu_can_fd_int_stat mask, union ctu_can_fd_int_stat val)

Enable/Disable interrupts of CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info
union ctu_can_fd_int_stat mask
Mask of interrupts which should be enabled/disabled.
union ctu_can_fd_int_stat val
0 - disable, 1 - enable the interrupt.
void ctucan_hw_int_mask_set(struct ctucan_hw_priv * priv, union ctu_can_fd_int_stat mask)

Mask interrupts of CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info
union ctu_can_fd_int_stat mask
Mask of interrupts which should be masked.
void ctucan_hw_int_mask_clr(struct ctucan_hw_priv * priv, union ctu_can_fd_int_stat mask)

Unmask interrupts of CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info
union ctu_can_fd_int_stat mask
Mask of interrupts which should be unmasked.
void ctucan_hw_int_mask(struct ctucan_hw_priv * priv, union ctu_can_fd_int_stat mask, union ctu_can_fd_int_stat val)

Mask/Unmask interrupts of CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info
union ctu_can_fd_int_stat mask
Mask of interrupts which should be enabled/disabled.
union ctu_can_fd_int_stat val
0 - unmask, 1 - mask the interrupt.
void ctucan_hw_set_mode(struct ctucan_hw_priv * priv, const struct can_ctrlmode * mode)

Set the modes of CTU CAN FD IP Core.

Parameters

struct ctucan_hw_priv * priv
Private info
const struct can_ctrlmode * mode
Mode of the controller from Socket CAN.

Description

All flags from “ctucan_hw_set_mode_reg” are configured, plus CAN_CTRLMODE_ONE_SHOT, CAN_CTRLMODE_BERR_REPORTING, which are configured via “retransmit limit” and enabling error interrupts.

void ctucan_hw_set_nom_bittiming(struct ctucan_hw_priv * priv, struct can_bittiming * nbt)

Set Nominal bit timing of CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info
struct can_bittiming * nbt
Nominal bit timing settings of CAN Controller.

NOTE

phase_seg1 and prop_seg may be modified if phase_seg1 > 63
This is because in Linux, the constraints are only on phase_seg1+prop_seg.
void ctucan_hw_set_data_bittiming(struct ctucan_hw_priv * priv, struct can_bittiming * dbt)

Set Data bit timing of CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info
struct can_bittiming * dbt
Data bit timing settings of CAN Controller.

NOTE

phase_seg1 and prop_seg may be modified if phase_seg1 > 63
This is because in Linux, the constraints are only on phase_seg1+prop_seg.
void ctucan_hw_set_err_limits(struct ctucan_hw_priv * priv, u8 ewl, u8 erp)

Set limits for error warning and passive transition

Parameters

struct ctucan_hw_priv * priv
Private info
u8 ewl
Error warning limit
u8 erp
Error passive limit

Description

Set error limit when CTU CAN FD Core should transfer to Error warning and error passive states. If any of RX/TX counters reach this value according state is changed. By default these counters are set as in CAN Standard (96, 128).

void ctucan_hw_set_def_err_limits(struct ctucan_hw_priv * priv)

Set default error limits to the CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info
void ctucan_hw_read_err_ctrs(struct ctucan_hw_priv * priv, struct can_berr_counter * ctr)

Read TX/RX error counters of CTU CAN FD IP Core.

Parameters

struct ctucan_hw_priv * priv
Private info
struct can_berr_counter * ctr
Pointer to error counter structure to fill
u16 ctucan_hw_read_nom_errs(struct ctucan_hw_priv * priv)

Read special error counter which returns number of Errors which were detected during Nominal Bit-rate.

Parameters

struct ctucan_hw_priv * priv
Private info

Return

Number of Error frames detected during Nominal Bit-rate

void ctucan_hw_erase_nom_errs(struct ctucan_hw_priv * priv)

Give command to CTU CAN FD Core to erase the nominal error counter.

Parameters

struct ctucan_hw_priv * priv
Private info
u16 ctucan_hw_read_fd_errs(struct ctucan_hw_priv * priv)

Read special error counter which returns number of Errors which were detected during Data Bit-rate.

Parameters

struct ctucan_hw_priv * priv
Private info

Return

Number of Error frames detected during Data Bit-rate

void ctucan_hw_erase_fd_errs(struct ctucan_hw_priv * priv)

Give command to CTU CAN FD Core to erase the Data error counter.

Parameters

struct ctucan_hw_priv * priv
Private info
enum can_state ctucan_hw_read_error_state(struct ctucan_hw_priv * priv)

Read fault confinement state of CTU CAN FD Core (determined by TX/RX Counters).

Parameters

struct ctucan_hw_priv * priv
Private info

Return

Error state of the CTU CAN FD Core.

void ctucan_hw_set_err_ctrs(struct ctucan_hw_priv * priv, const struct can_berr_counter * ctr)

Set value to TX/RX error counters of CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info
const struct can_berr_counter * ctr
Value to be set into counters

Return

Error state of the CTU CAN FD Core.

union ctu_can_fd_err_capt_alc ctu_can_fd_read_err_capt_alc(struct ctucan_hw_priv * priv)

Read core captured last error or arbitration lost reason.

Parameters

struct ctucan_hw_priv * priv
Private info

Return

Error state of the CTU CAN FD.

bool ctucan_hw_get_mask_filter_support(struct ctucan_hw_priv * priv, u8 fnum)

Check Mask filters support of given filter.

Parameters

struct ctucan_hw_priv * priv
Private info
u8 fnum
Filter number.

Return

True if filter is present and can be used, False otherwise.

bool ctucan_hw_get_range_filter_support(struct ctucan_hw_priv * priv)

Check Range filter support of given filter.

Parameters

struct ctucan_hw_priv * priv
Private info

Return

True if Range filter is present and can be used, False otherwise.

bool ctucan_hw_set_mask_filter(struct ctucan_hw_priv * priv, u8 fnum, bool enable, const struct can_filter * filter)

Configure mask filter of CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info
u8 fnum
Filter number.
bool enable
True if filter should be enabled.
const struct can_filter * filter
Filter configuration.

Return

True if mask filter was configured properly, false otherwise.

void ctucan_hw_set_range_filter(struct ctucan_hw_priv * priv, canid_t low_th, canid_t high_th, bool enable)

Configure range filter of CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info
canid_t low_th
Lower threshold of identifiers which should be accepted
canid_t high_th
Upper threshold of identifiers which should be accepted
bool enable
Enable the range filter.

Description

An identifier of RX Frame will pass the Range filter if its decimal value is between lower and upper threshold of range filter.

u16 ctucan_hw_get_rx_fifo_size(struct ctucan_hw_priv * priv)

Get size of the RX FIFO Buffer of CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info

Return

Size of the RX Buffer in words (32 bit)

u16 ctucan_hw_get_rx_fifo_mem_free(struct ctucan_hw_priv * priv)

Get number of free words in RX FIFO Buffer of CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info

Return

Number of free words (32 bit) in RX Buffer.

bool ctucan_hw_is_rx_fifo_empty(struct ctucan_hw_priv * priv)

Check if RX FIFO Buffer is empty.

Parameters

struct ctucan_hw_priv * priv
Private info

Return

True if empty, false otherwise.

bool ctucan_hw_is_rx_fifo_full(struct ctucan_hw_priv * priv)

Check if RX FIFO Buffer is full.

Parameters

struct ctucan_hw_priv * priv
Private info

Return

True if Full, false otherwise.

u16 ctucan_hw_get_rx_frame_count(struct ctucan_hw_priv * priv)

Get number of CAN Frames stored in RX Buffer of CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info

Return

True if Full, false otherwise.

void ctucan_hw_set_rx_tsop(struct ctucan_hw_priv * priv, enum ctu_can_fd_rx_settings_rtsop val)

Set timestamp option on RX Frame.

Parameters

struct ctucan_hw_priv * priv
Private info
enum ctu_can_fd_rx_settings_rtsop val
Timestamp option settings.
union ctu_can_fd_frame_format_w ctu_can_fd_read_rx_ffw(struct ctucan_hw_priv * priv)

Reads the first word of CAN Frame from RX FIFO Buffer.

Parameters

struct ctucan_hw_priv * priv
Private info

Return

The firts word of received frame

u32 ctucan_hw_read_rx_word(struct ctucan_hw_priv * priv)

Reads one word of CAN Frame from RX FIFO Buffer.

Parameters

struct ctucan_hw_priv * priv
Private info

Return

One word of received frame

void ctucan_hw_read_rx_frame(struct ctucan_hw_priv * priv, struct canfd_frame * data, u64 * ts)

Reads CAN Frame from RX FIFO Buffer and stores it to a buffer.

Parameters

struct ctucan_hw_priv * priv
Private info
struct canfd_frame * data
Pointer to buffer where the CAN Frame should be stored.
u64 * ts
Pointer to u64 where RX Timestamp should be stored.
void ctucan_hw_read_rx_frame_ffw(struct ctucan_hw_priv * priv, struct canfd_frame * cf, u64 * ts, union ctu_can_fd_frame_format_w ffw)

Reads rest of CAN Frame from RX FIFO Buffer and stores it to a buffer.

Parameters

struct ctucan_hw_priv * priv
Private info
struct canfd_frame * cf
Pointer to buffer where the CAN Frame should be stored.
u64 * ts
Pointer to u64 where RX Timestamp should be stored.
union ctu_can_fd_frame_format_w ffw
Already read the first frame control word by the caller
enum ctu_can_fd_tx_status_tx1s ctucan_hw_get_tx_status(struct ctucan_hw_priv * priv, u8 buf)

Returns status of TXT Buffer.

Parameters

struct ctucan_hw_priv * priv
Private info
u8 buf
TXT Buffer index (1 to CTU_CAN_FD_TXT_BUFFER_COUNT)

Return

Status of the TXT Buffer.

bool ctucan_hw_is_txt_buf_accessible(struct ctucan_hw_priv * priv, u8 buf)

Checks if TXT Buffer is accessible and can be written to.

Parameters

struct ctucan_hw_priv * priv
Private info
u8 buf
TXT Buffer index (1 to CTU_CAN_FD_TXT_BUFFER_COUNT)

Return

Status of the TXT Buffer.

void ctucan_hw_txt_buf_give_command(struct ctucan_hw_priv * priv, union ctu_can_fd_tx_command_txtb_info cmd, u8 buf)

Give command to TXT Buffer of CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info
union ctu_can_fd_tx_command_txtb_info cmd
Command to issue for given Tx buffer.
u8 buf
TXT Buffer index (1 to CTU_CAN_FD_TXT_BUFFER_COUNT)
void ctucan_hw_txt_set_empty(struct ctucan_hw_priv * priv, u8 buf)

Give “set_empty” command to TXT Buffer.

Parameters

struct ctucan_hw_priv * priv
Private info
u8 buf
TXT Buffer index (1 to CTU_CAN_FD_TXT_BUFFER_COUNT)
void ctucan_hw_txt_set_rdy(struct ctucan_hw_priv * priv, u8 buf)

Give “set_ready” command to TXT Buffer.

Parameters

struct ctucan_hw_priv * priv
Private info
u8 buf
TXT Buffer index (1 to CTU_CAN_FD_TXT_BUFFER_COUNT)
void ctucan_hw_txt_set_abort(struct ctucan_hw_priv * priv, u8 buf)

Give “set_abort” command to TXT Buffer.

Parameters

struct ctucan_hw_priv * priv
Private info
u8 buf
TXT Buffer index (1 to CTU_CAN_FD_TXT_BUFFER_COUNT)
void ctucan_hw_set_txt_priority(struct ctucan_hw_priv * priv, const u8 * prio)

Set priority of TXT Buffers in CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info
const u8 * prio
Pointer to array with CTU_CAN_FD_TXT_BUFFER_COUNT number of elements with TXT Buffer priorities.
bool ctucan_hw_insert_frame(struct ctucan_hw_priv * priv, const struct canfd_frame * data, u64 ts, u8 buf, bool isfdf)

Insert CAN FD frame to TXT Buffer of CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info
const struct canfd_frame * data
Pointer to CAN Frame buffer.
u64 ts
Timestamp when the buffer should be sent.
u8 buf
Index of TXT Buffer where to insert the CAN Frame.
bool isfdf
True if the frame is a FD frame.

Return

True if the frame was inserted successfully, False otherwise.

u16 ctucan_hw_get_tran_delay(struct ctucan_hw_priv * priv)

Read transceiver delay as measured by CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info

Description

Note that transceiver delay can be measured only after at least one CAN FD Frame with BRS bit was sent since the last re-start of the Core.

Return

True if the frame was inserted successfully, False otherwise.

u32 ctucan_hw_get_tx_frame_ctr(struct ctucan_hw_priv * priv)

Read number of transmitted CAN/CAN FD Frames by CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info

Return

Number of received CAN/CAN FD frames.

u32 ctucan_hw_get_rx_frame_ctr(struct ctucan_hw_priv * priv)

Read number of received CAN/CAN FD Frames by CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info

Return

Number of received CAN/CAN FD frames.

union ctu_can_fd_debug_register ctu_can_fd_read_debug_info(struct ctucan_hw_priv * priv)

Returns debug information of CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info

Return

Content of Debug register.

u64 ctucan_hw_read_timestamp(struct ctucan_hw_priv * priv)

Read timestamp value which is used internally by CTU CAN FD Core.

Parameters

struct ctucan_hw_priv * priv
Private info

Description

Reads timestamp twice and checks consistency betwen upper and lower timestamp word.

Return

Value of timestamp in CTU CAN FD Core

void ctucan_hw_configure_ssp(struct ctucan_hw_priv * priv, bool enable_ssp, bool use_trv_delay, int ssp_offset)

Configure Secondary sample point usage and position.

Parameters

struct ctucan_hw_priv * priv
Private info
bool enable_ssp
Enable Secondary Sampling point. When false, regular sampling point is used.
bool use_trv_delay
Add Transmitter delay to secondary sampling point position.
int ssp_offset
Position of secondary sampling point.
const char * ctucan_state_to_str(enum can_state state)

Convert CAN controller state code to corresponding text

Parameters

enum can_state state
CAN controller state code

Return

pointer to string representation of the error state

int ctucan_reset(struct net_device * ndev)

Issue software reset request to CTU CAN FD IP core

Parameters

struct net_device * ndev
Pointer to net_device structure

Return

0 for success, -ETIMEDOUT if CAN controller does not leave reset

int ctucan_set_bittiming(struct net_device * ndev)

CAN set bit timing routine

Parameters

struct net_device * ndev
Pointer to net_device structure

Description

This is the driver set bittiming routine.

Return

0 on success and failure value on error

int ctucan_set_data_bittiming(struct net_device * ndev)

CAN set data bit timing routine

Parameters

struct net_device * ndev
Pointer to net_device structure

Description

This is the driver set data bittiming routine.

Return

0 on success and failure value on error

int ctucan_set_secondary_sample_point(struct net_device * ndev)

CAN set secondary sample point routine

Parameters

struct net_device * ndev
Pointer to net_device structure

Return

0 on success and failure value on error

int ctucan_chip_start(struct net_device * ndev)

This routine starts the driver

Parameters

struct net_device * ndev
Pointer to net_device structure

Description

Routine expects that chip is in reset state. It setups initial Tx buffers for FIFO priorities, sets bittiming, enables interrupts, switches core to operational mode and changes controller state to CAN_STATE_STOPPED.

Return

0 on success and failure value on error

int ctucan_do_set_mode(struct net_device * ndev, enum can_mode mode)

This sets the mode of the driver

Parameters

struct net_device * ndev
Pointer to net_device structure
enum can_mode mode
Tells the mode of the driver

Description

This check the drivers state and calls the the corresponding modes to set.

Return

0 on success and failure value on error

netdev_tx_t ctucan_start_xmit(struct sk_buff * skb, struct net_device * ndev)

Starts the transmission

Parameters

struct sk_buff * skb
sk_buff pointer that contains data to be Txed
struct net_device * ndev
Pointer to net_device structure

Description

This function is invoked from upper layers to initiate transmission. This function uses the next available free txbuf and populates their fields to start the transmission.

Return

NETDEV_TX_OK on success, NETDEV_TX_BUSY when no free Tx buffer is available,
negative return values reserver for error cases
int ctucan_rx(struct net_device * ndev)

Is called from CAN isr to complete the received frame processing

Parameters

struct net_device * ndev
Pointer to net_device structure

Description

This function is invoked from the CAN isr(poll) to process the Rx frames. It does minimal processing and invokes “netif_receive_skb” to complete further processing.

Return

1 when frame is passed to the network layer, 0 when the first frame word
is read but system is out of free SKBs temporally and left code to resolve SKB allocation later and -EAGAIN in a case of empty Rx FIFO.
void ctucan_err_interrupt(struct net_device * ndev, union ctu_can_fd_int_stat isr)

error frame Isr

Parameters

struct net_device * ndev
net_device pointer
union ctu_can_fd_int_stat isr
interrupt status register value

Description

This is the CAN error interrupt and it will check the the type of error and forward the error frame to upper layers.

int ctucan_rx_poll(struct napi_struct * napi, int quota)

Poll routine for rx packets (NAPI)

Parameters

struct napi_struct * napi
napi structure pointer
int quota
Max number of rx packets to be processed.

Description

This is the poll routine for rx part. It will process the packets maximux quota value.

Return

number of packets received

void ctucan_tx_interrupt(struct net_device * ndev)

Tx Done Isr

Parameters

struct net_device * ndev
net_device pointer
irqreturn_t ctucan_interrupt(int irq, void * dev_id)

CAN Isr

Parameters

int irq
irq number
void * dev_id
device id poniter

Description

This is the CTU CAN FD ISR. It checks for the type of interrupt and invokes the corresponding ISR.

Return

IRQ_NONE - If CAN device is in sleep mode, IRQ_HANDLED otherwise

void ctucan_chip_stop(struct net_device * ndev)

Driver stop routine

Parameters

struct net_device * ndev
Pointer to net_device structure

Description

This is the drivers stop routine. It will disable the interrupts and disable the controller.

int ctucan_open(struct net_device * ndev)

Driver open routine

Parameters

struct net_device * ndev
Pointer to net_device structure

Description

This is the driver open routine.

Return

0 on success and failure value on error

int ctucan_close(struct net_device * ndev)

Driver close routine

Parameters

struct net_device * ndev
Pointer to net_device structure

Return

0 always

int ctucan_get_berr_counter(const struct net_device * ndev, struct can_berr_counter * bec)

error counter routine

Parameters

const struct net_device * ndev
Pointer to net_device structure
struct can_berr_counter * bec
Pointer to can_berr_counter structure

Description

This is the driver error counter routine.

Return

0 on success and failure value on error

int ctucan_pci_probe(struct pci_dev * pdev, const struct pci_device_id * ent)

PCI registration call

Parameters

struct pci_dev * pdev
Handle to the pci device structure
const struct pci_device_id * ent
Pointer to the entry from ctucan_pci_tbl

Description

This function does all the memory allocation and registration for the CAN device.

Return

0 on success and failure value on error

void ctucan_pci_remove(struct pci_dev * pdev)

Unregister the device after releasing the resources

Parameters

struct pci_dev * pdev
Handle to the pci device structure

Description

This function frees all the resources allocated to the device.

Return

0 always

int ctucan_platform_probe(struct platform_device * pdev)

Platform registration call

Parameters

struct platform_device * pdev
Handle to the platform device structure

Description

This function does all the memory allocation and registration for the CAN device.

Return

0 on success and failure value on error

int ctucan_platform_remove(struct platform_device * pdev)

Unregister the device after releasing the resources

Parameters

struct platform_device * pdev
Handle to the platform device structure

Description

This function frees all the resources allocated to the device.

Return

0 always

CTU CAN FD IP Core and Driver Development Acknowledgment

  • system integration for Intel SoC, core and driver testing and updates
  • provided OSADL expertise to discuss IP core licensing
  • pointed to possible deadlock for LGPL and CAN bus possible patent case which lead to relicense IP core design to BSD like license
  • provided suggestions and help to inform community about the project and invited us to events focused on CAN bus future development directions
  • Jan Charvat
  • implemented CTU CAN FD functional model for QEMU which has been integrated into QEMU mainline (docs/can.txt)
  • Bachelor theses Model of CAN FD Communication Controller for QEMU Emulator

Notes

[1]Other buses have their own specific driver interface to set up the device.
[2]Not to be mistaken with CAN Error Frame. This is a can_frame with CAN_ERR_FLAG set and some error info in its data field.
[3]Available in in CTU CAN FD repository https://gitlab.fel.cvut.cz/canbus/ctucanfd_ip_core
[4]As is done in the low-level driver functions ctucan_hw_set_nom_bittiming and ctucan_hw_set_data_bittiming.
[5]At the time of writing this thesis, option 1 is still being used and the modification is queued in gitlab issue #222
[6]Strictly speaking, multiple CAN TX queues are supported since v4.19 can: enable multi-queue for SocketCAN devices but no mainline driver is using them yet.
[7]Or rather in the next clock cycle