python_code
stringlengths 0
1.8M
| repo_name
stringclasses 7
values | file_path
stringlengths 5
99
|
---|---|---|
// SPDX-License-Identifier: GPL-2.0-only
/* Copyright (c) 2013-2018, The Linux Foundation. All rights reserved.
*
* RMNET Data virtual network driver
*/
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/if_arp.h>
#include <net/pkt_sched.h>
#include "rmnet_config.h"
#include "rmnet_handlers.h"
#include "rmnet_private.h"
#include "rmnet_map.h"
#include "rmnet_vnd.h"
/* RX/TX Fixup */
void rmnet_vnd_rx_fixup(struct sk_buff *skb, struct net_device *dev)
{
struct rmnet_priv *priv = netdev_priv(dev);
struct rmnet_pcpu_stats *pcpu_ptr;
pcpu_ptr = this_cpu_ptr(priv->pcpu_stats);
u64_stats_update_begin(&pcpu_ptr->syncp);
pcpu_ptr->stats.rx_pkts++;
pcpu_ptr->stats.rx_bytes += skb->len;
u64_stats_update_end(&pcpu_ptr->syncp);
}
void rmnet_vnd_tx_fixup_len(unsigned int len, struct net_device *dev)
{
struct rmnet_priv *priv = netdev_priv(dev);
struct rmnet_pcpu_stats *pcpu_ptr;
pcpu_ptr = this_cpu_ptr(priv->pcpu_stats);
u64_stats_update_begin(&pcpu_ptr->syncp);
pcpu_ptr->stats.tx_pkts++;
pcpu_ptr->stats.tx_bytes += len;
u64_stats_update_end(&pcpu_ptr->syncp);
}
void rmnet_vnd_tx_fixup(struct sk_buff *skb, struct net_device *dev)
{
rmnet_vnd_tx_fixup_len(skb->len, dev);
}
/* Network Device Operations */
static netdev_tx_t rmnet_vnd_start_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct rmnet_priv *priv;
priv = netdev_priv(dev);
if (priv->real_dev) {
rmnet_egress_handler(skb);
} else {
this_cpu_inc(priv->pcpu_stats->stats.tx_drops);
kfree_skb(skb);
}
return NETDEV_TX_OK;
}
static int rmnet_vnd_headroom(struct rmnet_port *port)
{
u32 headroom;
headroom = sizeof(struct rmnet_map_header);
if (port->data_format & RMNET_FLAGS_EGRESS_MAP_CKSUMV4)
headroom += sizeof(struct rmnet_map_ul_csum_header);
return headroom;
}
static int rmnet_vnd_change_mtu(struct net_device *rmnet_dev, int new_mtu)
{
struct rmnet_priv *priv = netdev_priv(rmnet_dev);
struct rmnet_port *port;
u32 headroom;
port = rmnet_get_port_rtnl(priv->real_dev);
headroom = rmnet_vnd_headroom(port);
if (new_mtu < 0 || new_mtu > RMNET_MAX_PACKET_SIZE ||
new_mtu > (priv->real_dev->mtu - headroom))
return -EINVAL;
rmnet_dev->mtu = new_mtu;
return 0;
}
static int rmnet_vnd_get_iflink(const struct net_device *dev)
{
struct rmnet_priv *priv = netdev_priv(dev);
return priv->real_dev->ifindex;
}
static int rmnet_vnd_init(struct net_device *dev)
{
struct rmnet_priv *priv = netdev_priv(dev);
int err;
priv->pcpu_stats = alloc_percpu(struct rmnet_pcpu_stats);
if (!priv->pcpu_stats)
return -ENOMEM;
err = gro_cells_init(&priv->gro_cells, dev);
if (err) {
free_percpu(priv->pcpu_stats);
return err;
}
return 0;
}
static void rmnet_vnd_uninit(struct net_device *dev)
{
struct rmnet_priv *priv = netdev_priv(dev);
gro_cells_destroy(&priv->gro_cells);
free_percpu(priv->pcpu_stats);
}
static void rmnet_get_stats64(struct net_device *dev,
struct rtnl_link_stats64 *s)
{
struct rmnet_priv *priv = netdev_priv(dev);
struct rmnet_vnd_stats total_stats = { };
struct rmnet_pcpu_stats *pcpu_ptr;
struct rmnet_vnd_stats snapshot;
unsigned int cpu, start;
for_each_possible_cpu(cpu) {
pcpu_ptr = per_cpu_ptr(priv->pcpu_stats, cpu);
do {
start = u64_stats_fetch_begin(&pcpu_ptr->syncp);
snapshot = pcpu_ptr->stats; /* struct assignment */
} while (u64_stats_fetch_retry(&pcpu_ptr->syncp, start));
total_stats.rx_pkts += snapshot.rx_pkts;
total_stats.rx_bytes += snapshot.rx_bytes;
total_stats.tx_pkts += snapshot.tx_pkts;
total_stats.tx_bytes += snapshot.tx_bytes;
total_stats.tx_drops += snapshot.tx_drops;
}
s->rx_packets = total_stats.rx_pkts;
s->rx_bytes = total_stats.rx_bytes;
s->tx_packets = total_stats.tx_pkts;
s->tx_bytes = total_stats.tx_bytes;
s->tx_dropped = total_stats.tx_drops;
}
static const struct net_device_ops rmnet_vnd_ops = {
.ndo_start_xmit = rmnet_vnd_start_xmit,
.ndo_change_mtu = rmnet_vnd_change_mtu,
.ndo_get_iflink = rmnet_vnd_get_iflink,
.ndo_add_slave = rmnet_add_bridge,
.ndo_del_slave = rmnet_del_bridge,
.ndo_init = rmnet_vnd_init,
.ndo_uninit = rmnet_vnd_uninit,
.ndo_get_stats64 = rmnet_get_stats64,
};
static const char rmnet_gstrings_stats[][ETH_GSTRING_LEN] = {
"Checksum ok",
"Bad IPv4 header checksum",
"Checksum valid bit not set",
"Checksum validation failed",
"Checksum error bad buffer",
"Checksum error bad ip version",
"Checksum error bad transport",
"Checksum skipped on ip fragment",
"Checksum skipped",
"Checksum computed in software",
"Checksum computed in hardware",
};
static void rmnet_get_strings(struct net_device *dev, u32 stringset, u8 *buf)
{
switch (stringset) {
case ETH_SS_STATS:
memcpy(buf, &rmnet_gstrings_stats,
sizeof(rmnet_gstrings_stats));
break;
}
}
static int rmnet_get_sset_count(struct net_device *dev, int sset)
{
switch (sset) {
case ETH_SS_STATS:
return ARRAY_SIZE(rmnet_gstrings_stats);
default:
return -EOPNOTSUPP;
}
}
static void rmnet_get_ethtool_stats(struct net_device *dev,
struct ethtool_stats *stats, u64 *data)
{
struct rmnet_priv *priv = netdev_priv(dev);
struct rmnet_priv_stats *st = &priv->stats;
if (!data)
return;
memcpy(data, st, ARRAY_SIZE(rmnet_gstrings_stats) * sizeof(u64));
}
static int rmnet_get_coalesce(struct net_device *dev,
struct ethtool_coalesce *coal,
struct kernel_ethtool_coalesce *kernel_coal,
struct netlink_ext_ack *extack)
{
struct rmnet_priv *priv = netdev_priv(dev);
struct rmnet_port *port;
port = rmnet_get_port_rtnl(priv->real_dev);
memset(kernel_coal, 0, sizeof(*kernel_coal));
kernel_coal->tx_aggr_max_bytes = port->egress_agg_params.bytes;
kernel_coal->tx_aggr_max_frames = port->egress_agg_params.count;
kernel_coal->tx_aggr_time_usecs = div_u64(port->egress_agg_params.time_nsec,
NSEC_PER_USEC);
return 0;
}
static int rmnet_set_coalesce(struct net_device *dev,
struct ethtool_coalesce *coal,
struct kernel_ethtool_coalesce *kernel_coal,
struct netlink_ext_ack *extack)
{
struct rmnet_priv *priv = netdev_priv(dev);
struct rmnet_port *port;
port = rmnet_get_port_rtnl(priv->real_dev);
if (kernel_coal->tx_aggr_max_frames < 1 || kernel_coal->tx_aggr_max_frames > 64)
return -EINVAL;
if (kernel_coal->tx_aggr_max_bytes > 32768)
return -EINVAL;
rmnet_map_update_ul_agg_config(port, kernel_coal->tx_aggr_max_bytes,
kernel_coal->tx_aggr_max_frames,
kernel_coal->tx_aggr_time_usecs);
return 0;
}
static const struct ethtool_ops rmnet_ethtool_ops = {
.supported_coalesce_params = ETHTOOL_COALESCE_TX_AGGR,
.get_coalesce = rmnet_get_coalesce,
.set_coalesce = rmnet_set_coalesce,
.get_ethtool_stats = rmnet_get_ethtool_stats,
.get_strings = rmnet_get_strings,
.get_sset_count = rmnet_get_sset_count,
};
/* Called by kernel whenever a new rmnet<n> device is created. Sets MTU,
* flags, ARP type, needed headroom, etc...
*/
void rmnet_vnd_setup(struct net_device *rmnet_dev)
{
rmnet_dev->netdev_ops = &rmnet_vnd_ops;
rmnet_dev->mtu = RMNET_DFLT_PACKET_SIZE;
rmnet_dev->needed_headroom = RMNET_NEEDED_HEADROOM;
eth_hw_addr_random(rmnet_dev);
rmnet_dev->tx_queue_len = RMNET_TX_QUEUE_LEN;
/* Raw IP mode */
rmnet_dev->header_ops = NULL; /* No header */
rmnet_dev->type = ARPHRD_RAWIP;
rmnet_dev->hard_header_len = 0;
rmnet_dev->flags &= ~(IFF_BROADCAST | IFF_MULTICAST);
rmnet_dev->needs_free_netdev = true;
rmnet_dev->ethtool_ops = &rmnet_ethtool_ops;
rmnet_dev->features |= NETIF_F_LLTX;
/* This perm addr will be used as interface identifier by IPv6 */
rmnet_dev->addr_assign_type = NET_ADDR_RANDOM;
eth_random_addr(rmnet_dev->perm_addr);
}
/* Exposed API */
int rmnet_vnd_newlink(u8 id, struct net_device *rmnet_dev,
struct rmnet_port *port,
struct net_device *real_dev,
struct rmnet_endpoint *ep,
struct netlink_ext_ack *extack)
{
struct rmnet_priv *priv = netdev_priv(rmnet_dev);
u32 headroom;
int rc;
if (rmnet_get_endpoint(port, id)) {
NL_SET_ERR_MSG_MOD(extack, "MUX ID already exists");
return -EBUSY;
}
rmnet_dev->hw_features = NETIF_F_RXCSUM;
rmnet_dev->hw_features |= NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM;
rmnet_dev->hw_features |= NETIF_F_SG;
priv->real_dev = real_dev;
headroom = rmnet_vnd_headroom(port);
if (rmnet_vnd_change_mtu(rmnet_dev, real_dev->mtu - headroom)) {
NL_SET_ERR_MSG_MOD(extack, "Invalid MTU on real dev");
return -EINVAL;
}
rc = register_netdevice(rmnet_dev);
if (!rc) {
ep->egress_dev = rmnet_dev;
ep->mux_id = id;
port->nr_rmnet_devs++;
rmnet_dev->rtnl_link_ops = &rmnet_link_ops;
priv->mux_id = id;
netdev_dbg(rmnet_dev, "rmnet dev created\n");
}
return rc;
}
int rmnet_vnd_dellink(u8 id, struct rmnet_port *port,
struct rmnet_endpoint *ep)
{
if (id >= RMNET_MAX_LOGICAL_EP || !ep->egress_dev)
return -EINVAL;
ep->egress_dev = NULL;
port->nr_rmnet_devs--;
return 0;
}
int rmnet_vnd_do_flow_control(struct net_device *rmnet_dev, int enable)
{
netdev_dbg(rmnet_dev, "Setting VND TX queue state to %d\n", enable);
/* Although we expect similar number of enable/disable
* commands, optimize for the disable. That is more
* latency sensitive than enable
*/
if (unlikely(enable))
netif_wake_queue(rmnet_dev);
else
netif_stop_queue(rmnet_dev);
return 0;
}
int rmnet_vnd_validate_real_dev_mtu(struct net_device *real_dev)
{
struct hlist_node *tmp_ep;
struct rmnet_endpoint *ep;
struct rmnet_port *port;
unsigned long bkt_ep;
u32 headroom;
port = rmnet_get_port_rtnl(real_dev);
headroom = rmnet_vnd_headroom(port);
hash_for_each_safe(port->muxed_ep, bkt_ep, tmp_ep, ep, hlnode) {
if (ep->egress_dev->mtu > (real_dev->mtu - headroom))
return -1;
}
return 0;
}
int rmnet_vnd_update_dev_mtu(struct rmnet_port *port,
struct net_device *real_dev)
{
struct hlist_node *tmp_ep;
struct rmnet_endpoint *ep;
unsigned long bkt_ep;
u32 headroom;
headroom = rmnet_vnd_headroom(port);
hash_for_each_safe(port->muxed_ep, bkt_ep, tmp_ep, ep, hlnode) {
if (ep->egress_dev->mtu <= (real_dev->mtu - headroom))
continue;
if (rmnet_vnd_change_mtu(ep->egress_dev,
real_dev->mtu - headroom))
return -1;
}
return 0;
}
|
linux-master
|
drivers/net/ethernet/qualcomm/rmnet/rmnet_vnd.c
|
// SPDX-License-Identifier: GPL-2.0-only
/* Copyright (c) 2013-2018, 2021, The Linux Foundation. All rights reserved.
*
* RMNET Data MAP protocol
*/
#include <linux/netdevice.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <net/ip6_checksum.h>
#include <linux/bitfield.h>
#include "rmnet_config.h"
#include "rmnet_map.h"
#include "rmnet_private.h"
#include "rmnet_vnd.h"
#define RMNET_MAP_DEAGGR_SPACING 64
#define RMNET_MAP_DEAGGR_HEADROOM (RMNET_MAP_DEAGGR_SPACING / 2)
static __sum16 *rmnet_map_get_csum_field(unsigned char protocol,
const void *txporthdr)
{
if (protocol == IPPROTO_TCP)
return &((struct tcphdr *)txporthdr)->check;
if (protocol == IPPROTO_UDP)
return &((struct udphdr *)txporthdr)->check;
return NULL;
}
static int
rmnet_map_ipv4_dl_csum_trailer(struct sk_buff *skb,
struct rmnet_map_dl_csum_trailer *csum_trailer,
struct rmnet_priv *priv)
{
struct iphdr *ip4h = (struct iphdr *)skb->data;
void *txporthdr = skb->data + ip4h->ihl * 4;
__sum16 *csum_field, pseudo_csum;
__sum16 ip_payload_csum;
/* Computing the checksum over just the IPv4 header--including its
* checksum field--should yield 0. If it doesn't, the IP header
* is bad, so return an error and let the IP layer drop it.
*/
if (ip_fast_csum(ip4h, ip4h->ihl)) {
priv->stats.csum_ip4_header_bad++;
return -EINVAL;
}
/* We don't support checksum offload on IPv4 fragments */
if (ip_is_fragment(ip4h)) {
priv->stats.csum_fragmented_pkt++;
return -EOPNOTSUPP;
}
/* Checksum offload is only supported for UDP and TCP protocols */
csum_field = rmnet_map_get_csum_field(ip4h->protocol, txporthdr);
if (!csum_field) {
priv->stats.csum_err_invalid_transport++;
return -EPROTONOSUPPORT;
}
/* RFC 768: UDP checksum is optional for IPv4, and is 0 if unused */
if (!*csum_field && ip4h->protocol == IPPROTO_UDP) {
priv->stats.csum_skipped++;
return 0;
}
/* The checksum value in the trailer is computed over the entire
* IP packet, including the IP header and payload. To derive the
* transport checksum from this, we first subract the contribution
* of the IP header from the trailer checksum. We then add the
* checksum computed over the pseudo header.
*
* We verified above that the IP header contributes zero to the
* trailer checksum. Therefore the checksum in the trailer is
* just the checksum computed over the IP payload.
* If the IP payload arrives intact, adding the pseudo header
* checksum to the IP payload checksum will yield 0xffff (negative
* zero). This means the trailer checksum and the pseudo checksum
* are additive inverses of each other. Put another way, the
* message passes the checksum test if the trailer checksum value
* is the negated pseudo header checksum.
*
* Knowing this, we don't even need to examine the transport
* header checksum value; it is already accounted for in the
* checksum value found in the trailer.
*/
ip_payload_csum = csum_trailer->csum_value;
pseudo_csum = csum_tcpudp_magic(ip4h->saddr, ip4h->daddr,
ntohs(ip4h->tot_len) - ip4h->ihl * 4,
ip4h->protocol, 0);
/* The cast is required to ensure only the low 16 bits are examined */
if (ip_payload_csum != (__sum16)~pseudo_csum) {
priv->stats.csum_validation_failed++;
return -EINVAL;
}
priv->stats.csum_ok++;
return 0;
}
#if IS_ENABLED(CONFIG_IPV6)
static int
rmnet_map_ipv6_dl_csum_trailer(struct sk_buff *skb,
struct rmnet_map_dl_csum_trailer *csum_trailer,
struct rmnet_priv *priv)
{
struct ipv6hdr *ip6h = (struct ipv6hdr *)skb->data;
void *txporthdr = skb->data + sizeof(*ip6h);
__sum16 *csum_field, pseudo_csum;
__sum16 ip6_payload_csum;
__be16 ip_header_csum;
/* Checksum offload is only supported for UDP and TCP protocols;
* the packet cannot include any IPv6 extension headers
*/
csum_field = rmnet_map_get_csum_field(ip6h->nexthdr, txporthdr);
if (!csum_field) {
priv->stats.csum_err_invalid_transport++;
return -EPROTONOSUPPORT;
}
/* The checksum value in the trailer is computed over the entire
* IP packet, including the IP header and payload. To derive the
* transport checksum from this, we first subract the contribution
* of the IP header from the trailer checksum. We then add the
* checksum computed over the pseudo header.
*/
ip_header_csum = (__force __be16)ip_fast_csum(ip6h, sizeof(*ip6h) / 4);
ip6_payload_csum = csum16_sub(csum_trailer->csum_value, ip_header_csum);
pseudo_csum = csum_ipv6_magic(&ip6h->saddr, &ip6h->daddr,
ntohs(ip6h->payload_len),
ip6h->nexthdr, 0);
/* It's sufficient to compare the IP payload checksum with the
* negated pseudo checksum to determine whether the packet
* checksum was good. (See further explanation in comments
* in rmnet_map_ipv4_dl_csum_trailer()).
*
* The cast is required to ensure only the low 16 bits are
* examined.
*/
if (ip6_payload_csum != (__sum16)~pseudo_csum) {
priv->stats.csum_validation_failed++;
return -EINVAL;
}
priv->stats.csum_ok++;
return 0;
}
#else
static int
rmnet_map_ipv6_dl_csum_trailer(struct sk_buff *skb,
struct rmnet_map_dl_csum_trailer *csum_trailer,
struct rmnet_priv *priv)
{
return 0;
}
#endif
static void rmnet_map_complement_ipv4_txporthdr_csum_field(struct iphdr *ip4h)
{
void *txphdr;
u16 *csum;
txphdr = (void *)ip4h + ip4h->ihl * 4;
if (ip4h->protocol == IPPROTO_TCP || ip4h->protocol == IPPROTO_UDP) {
csum = (u16 *)rmnet_map_get_csum_field(ip4h->protocol, txphdr);
*csum = ~(*csum);
}
}
static void
rmnet_map_ipv4_ul_csum_header(struct iphdr *iphdr,
struct rmnet_map_ul_csum_header *ul_header,
struct sk_buff *skb)
{
u16 val;
val = MAP_CSUM_UL_ENABLED_FLAG;
if (iphdr->protocol == IPPROTO_UDP)
val |= MAP_CSUM_UL_UDP_FLAG;
val |= skb->csum_offset & MAP_CSUM_UL_OFFSET_MASK;
ul_header->csum_start_offset = htons(skb_network_header_len(skb));
ul_header->csum_info = htons(val);
skb->ip_summed = CHECKSUM_NONE;
rmnet_map_complement_ipv4_txporthdr_csum_field(iphdr);
}
#if IS_ENABLED(CONFIG_IPV6)
static void
rmnet_map_complement_ipv6_txporthdr_csum_field(struct ipv6hdr *ip6h)
{
void *txphdr;
u16 *csum;
txphdr = ip6h + 1;
if (ip6h->nexthdr == IPPROTO_TCP || ip6h->nexthdr == IPPROTO_UDP) {
csum = (u16 *)rmnet_map_get_csum_field(ip6h->nexthdr, txphdr);
*csum = ~(*csum);
}
}
static void
rmnet_map_ipv6_ul_csum_header(struct ipv6hdr *ipv6hdr,
struct rmnet_map_ul_csum_header *ul_header,
struct sk_buff *skb)
{
u16 val;
val = MAP_CSUM_UL_ENABLED_FLAG;
if (ipv6hdr->nexthdr == IPPROTO_UDP)
val |= MAP_CSUM_UL_UDP_FLAG;
val |= skb->csum_offset & MAP_CSUM_UL_OFFSET_MASK;
ul_header->csum_start_offset = htons(skb_network_header_len(skb));
ul_header->csum_info = htons(val);
skb->ip_summed = CHECKSUM_NONE;
rmnet_map_complement_ipv6_txporthdr_csum_field(ipv6hdr);
}
#else
static void
rmnet_map_ipv6_ul_csum_header(void *ip6hdr,
struct rmnet_map_ul_csum_header *ul_header,
struct sk_buff *skb)
{
}
#endif
static void rmnet_map_v5_checksum_uplink_packet(struct sk_buff *skb,
struct rmnet_port *port,
struct net_device *orig_dev)
{
struct rmnet_priv *priv = netdev_priv(orig_dev);
struct rmnet_map_v5_csum_header *ul_header;
ul_header = skb_push(skb, sizeof(*ul_header));
memset(ul_header, 0, sizeof(*ul_header));
ul_header->header_info = u8_encode_bits(RMNET_MAP_HEADER_TYPE_CSUM_OFFLOAD,
MAPV5_HDRINFO_HDR_TYPE_FMASK);
if (skb->ip_summed == CHECKSUM_PARTIAL) {
void *iph = ip_hdr(skb);
__sum16 *check;
void *trans;
u8 proto;
if (skb->protocol == htons(ETH_P_IP)) {
u16 ip_len = ((struct iphdr *)iph)->ihl * 4;
proto = ((struct iphdr *)iph)->protocol;
trans = iph + ip_len;
} else if (IS_ENABLED(CONFIG_IPV6) &&
skb->protocol == htons(ETH_P_IPV6)) {
u16 ip_len = sizeof(struct ipv6hdr);
proto = ((struct ipv6hdr *)iph)->nexthdr;
trans = iph + ip_len;
} else {
priv->stats.csum_err_invalid_ip_version++;
goto sw_csum;
}
check = rmnet_map_get_csum_field(proto, trans);
if (check) {
skb->ip_summed = CHECKSUM_NONE;
/* Ask for checksum offloading */
ul_header->csum_info |= MAPV5_CSUMINFO_VALID_FLAG;
priv->stats.csum_hw++;
return;
}
}
sw_csum:
priv->stats.csum_sw++;
}
/* Adds MAP header to front of skb->data
* Padding is calculated and set appropriately in MAP header. Mux ID is
* initialized to 0.
*/
struct rmnet_map_header *rmnet_map_add_map_header(struct sk_buff *skb,
int hdrlen,
struct rmnet_port *port,
int pad)
{
struct rmnet_map_header *map_header;
u32 padding, map_datalen;
map_datalen = skb->len - hdrlen;
map_header = (struct rmnet_map_header *)
skb_push(skb, sizeof(struct rmnet_map_header));
memset(map_header, 0, sizeof(struct rmnet_map_header));
/* Set next_hdr bit for csum offload packets */
if (port->data_format & RMNET_FLAGS_EGRESS_MAP_CKSUMV5)
map_header->flags |= MAP_NEXT_HEADER_FLAG;
if (pad == RMNET_MAP_NO_PAD_BYTES) {
map_header->pkt_len = htons(map_datalen);
return map_header;
}
BUILD_BUG_ON(MAP_PAD_LEN_MASK < 3);
padding = ALIGN(map_datalen, 4) - map_datalen;
if (padding == 0)
goto done;
if (skb_tailroom(skb) < padding)
return NULL;
skb_put_zero(skb, padding);
done:
map_header->pkt_len = htons(map_datalen + padding);
/* This is a data packet, so the CMD bit is 0 */
map_header->flags = padding & MAP_PAD_LEN_MASK;
return map_header;
}
/* Deaggregates a single packet
* A whole new buffer is allocated for each portion of an aggregated frame.
* Caller should keep calling deaggregate() on the source skb until 0 is
* returned, indicating that there are no more packets to deaggregate. Caller
* is responsible for freeing the original skb.
*/
struct sk_buff *rmnet_map_deaggregate(struct sk_buff *skb,
struct rmnet_port *port)
{
struct rmnet_map_v5_csum_header *next_hdr = NULL;
struct rmnet_map_header *maph;
void *data = skb->data;
struct sk_buff *skbn;
u8 nexthdr_type;
u32 packet_len;
if (skb->len == 0)
return NULL;
maph = (struct rmnet_map_header *)skb->data;
packet_len = ntohs(maph->pkt_len) + sizeof(*maph);
if (port->data_format & RMNET_FLAGS_INGRESS_MAP_CKSUMV4) {
packet_len += sizeof(struct rmnet_map_dl_csum_trailer);
} else if (port->data_format & RMNET_FLAGS_INGRESS_MAP_CKSUMV5) {
if (!(maph->flags & MAP_CMD_FLAG)) {
packet_len += sizeof(*next_hdr);
if (maph->flags & MAP_NEXT_HEADER_FLAG)
next_hdr = data + sizeof(*maph);
else
/* Mapv5 data pkt without csum hdr is invalid */
return NULL;
}
}
if (((int)skb->len - (int)packet_len) < 0)
return NULL;
/* Some hardware can send us empty frames. Catch them */
if (!maph->pkt_len)
return NULL;
if (next_hdr) {
nexthdr_type = u8_get_bits(next_hdr->header_info,
MAPV5_HDRINFO_HDR_TYPE_FMASK);
if (nexthdr_type != RMNET_MAP_HEADER_TYPE_CSUM_OFFLOAD)
return NULL;
}
skbn = alloc_skb(packet_len + RMNET_MAP_DEAGGR_SPACING, GFP_ATOMIC);
if (!skbn)
return NULL;
skb_reserve(skbn, RMNET_MAP_DEAGGR_HEADROOM);
skb_put(skbn, packet_len);
memcpy(skbn->data, skb->data, packet_len);
skb_pull(skb, packet_len);
return skbn;
}
/* Validates packet checksums. Function takes a pointer to
* the beginning of a buffer which contains the IP payload +
* padding + checksum trailer.
* Only IPv4 and IPv6 are supported along with TCP & UDP.
* Fragmented or tunneled packets are not supported.
*/
int rmnet_map_checksum_downlink_packet(struct sk_buff *skb, u16 len)
{
struct rmnet_priv *priv = netdev_priv(skb->dev);
struct rmnet_map_dl_csum_trailer *csum_trailer;
if (unlikely(!(skb->dev->features & NETIF_F_RXCSUM))) {
priv->stats.csum_sw++;
return -EOPNOTSUPP;
}
csum_trailer = (struct rmnet_map_dl_csum_trailer *)(skb->data + len);
if (!(csum_trailer->flags & MAP_CSUM_DL_VALID_FLAG)) {
priv->stats.csum_valid_unset++;
return -EINVAL;
}
if (skb->protocol == htons(ETH_P_IP))
return rmnet_map_ipv4_dl_csum_trailer(skb, csum_trailer, priv);
if (IS_ENABLED(CONFIG_IPV6) && skb->protocol == htons(ETH_P_IPV6))
return rmnet_map_ipv6_dl_csum_trailer(skb, csum_trailer, priv);
priv->stats.csum_err_invalid_ip_version++;
return -EPROTONOSUPPORT;
}
static void rmnet_map_v4_checksum_uplink_packet(struct sk_buff *skb,
struct net_device *orig_dev)
{
struct rmnet_priv *priv = netdev_priv(orig_dev);
struct rmnet_map_ul_csum_header *ul_header;
void *iphdr;
ul_header = (struct rmnet_map_ul_csum_header *)
skb_push(skb, sizeof(struct rmnet_map_ul_csum_header));
if (unlikely(!(orig_dev->features &
(NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM))))
goto sw_csum;
if (skb->ip_summed != CHECKSUM_PARTIAL)
goto sw_csum;
iphdr = (char *)ul_header +
sizeof(struct rmnet_map_ul_csum_header);
if (skb->protocol == htons(ETH_P_IP)) {
rmnet_map_ipv4_ul_csum_header(iphdr, ul_header, skb);
priv->stats.csum_hw++;
return;
}
if (IS_ENABLED(CONFIG_IPV6) && skb->protocol == htons(ETH_P_IPV6)) {
rmnet_map_ipv6_ul_csum_header(iphdr, ul_header, skb);
priv->stats.csum_hw++;
return;
}
priv->stats.csum_err_invalid_ip_version++;
sw_csum:
memset(ul_header, 0, sizeof(*ul_header));
priv->stats.csum_sw++;
}
/* Generates UL checksum meta info header for IPv4 and IPv6 over TCP and UDP
* packets that are supported for UL checksum offload.
*/
void rmnet_map_checksum_uplink_packet(struct sk_buff *skb,
struct rmnet_port *port,
struct net_device *orig_dev,
int csum_type)
{
switch (csum_type) {
case RMNET_FLAGS_EGRESS_MAP_CKSUMV4:
rmnet_map_v4_checksum_uplink_packet(skb, orig_dev);
break;
case RMNET_FLAGS_EGRESS_MAP_CKSUMV5:
rmnet_map_v5_checksum_uplink_packet(skb, port, orig_dev);
break;
default:
break;
}
}
/* Process a MAPv5 packet header */
int rmnet_map_process_next_hdr_packet(struct sk_buff *skb,
u16 len)
{
struct rmnet_priv *priv = netdev_priv(skb->dev);
struct rmnet_map_v5_csum_header *next_hdr;
u8 nexthdr_type;
next_hdr = (struct rmnet_map_v5_csum_header *)(skb->data +
sizeof(struct rmnet_map_header));
nexthdr_type = u8_get_bits(next_hdr->header_info,
MAPV5_HDRINFO_HDR_TYPE_FMASK);
if (nexthdr_type != RMNET_MAP_HEADER_TYPE_CSUM_OFFLOAD)
return -EINVAL;
if (unlikely(!(skb->dev->features & NETIF_F_RXCSUM))) {
priv->stats.csum_sw++;
} else if (next_hdr->csum_info & MAPV5_CSUMINFO_VALID_FLAG) {
priv->stats.csum_ok++;
skb->ip_summed = CHECKSUM_UNNECESSARY;
} else {
priv->stats.csum_valid_unset++;
}
/* Pull csum v5 header */
skb_pull(skb, sizeof(*next_hdr));
return 0;
}
#define RMNET_AGG_BYPASS_TIME_NSEC 10000000L
static void reset_aggr_params(struct rmnet_port *port)
{
port->skbagg_head = NULL;
port->agg_count = 0;
port->agg_state = 0;
memset(&port->agg_time, 0, sizeof(struct timespec64));
}
static void rmnet_send_skb(struct rmnet_port *port, struct sk_buff *skb)
{
if (skb_needs_linearize(skb, port->dev->features)) {
if (unlikely(__skb_linearize(skb))) {
struct rmnet_priv *priv;
priv = netdev_priv(port->rmnet_dev);
this_cpu_inc(priv->pcpu_stats->stats.tx_drops);
dev_kfree_skb_any(skb);
return;
}
}
dev_queue_xmit(skb);
}
static void rmnet_map_flush_tx_packet_work(struct work_struct *work)
{
struct sk_buff *skb = NULL;
struct rmnet_port *port;
port = container_of(work, struct rmnet_port, agg_wq);
spin_lock_bh(&port->agg_lock);
if (likely(port->agg_state == -EINPROGRESS)) {
/* Buffer may have already been shipped out */
if (likely(port->skbagg_head)) {
skb = port->skbagg_head;
reset_aggr_params(port);
}
port->agg_state = 0;
}
spin_unlock_bh(&port->agg_lock);
if (skb)
rmnet_send_skb(port, skb);
}
static enum hrtimer_restart rmnet_map_flush_tx_packet_queue(struct hrtimer *t)
{
struct rmnet_port *port;
port = container_of(t, struct rmnet_port, hrtimer);
schedule_work(&port->agg_wq);
return HRTIMER_NORESTART;
}
unsigned int rmnet_map_tx_aggregate(struct sk_buff *skb, struct rmnet_port *port,
struct net_device *orig_dev)
{
struct timespec64 diff, last;
unsigned int len = skb->len;
struct sk_buff *agg_skb;
int size;
spin_lock_bh(&port->agg_lock);
memcpy(&last, &port->agg_last, sizeof(struct timespec64));
ktime_get_real_ts64(&port->agg_last);
if (!port->skbagg_head) {
/* Check to see if we should agg first. If the traffic is very
* sparse, don't aggregate.
*/
new_packet:
diff = timespec64_sub(port->agg_last, last);
size = port->egress_agg_params.bytes - skb->len;
if (size < 0) {
/* dropped */
spin_unlock_bh(&port->agg_lock);
return 0;
}
if (diff.tv_sec > 0 || diff.tv_nsec > RMNET_AGG_BYPASS_TIME_NSEC ||
size == 0)
goto no_aggr;
port->skbagg_head = skb_copy_expand(skb, 0, size, GFP_ATOMIC);
if (!port->skbagg_head)
goto no_aggr;
dev_kfree_skb_any(skb);
port->skbagg_head->protocol = htons(ETH_P_MAP);
port->agg_count = 1;
ktime_get_real_ts64(&port->agg_time);
skb_frag_list_init(port->skbagg_head);
goto schedule;
}
diff = timespec64_sub(port->agg_last, port->agg_time);
size = port->egress_agg_params.bytes - port->skbagg_head->len;
if (skb->len > size) {
agg_skb = port->skbagg_head;
reset_aggr_params(port);
spin_unlock_bh(&port->agg_lock);
hrtimer_cancel(&port->hrtimer);
rmnet_send_skb(port, agg_skb);
spin_lock_bh(&port->agg_lock);
goto new_packet;
}
if (skb_has_frag_list(port->skbagg_head))
port->skbagg_tail->next = skb;
else
skb_shinfo(port->skbagg_head)->frag_list = skb;
port->skbagg_head->len += skb->len;
port->skbagg_head->data_len += skb->len;
port->skbagg_head->truesize += skb->truesize;
port->skbagg_tail = skb;
port->agg_count++;
if (diff.tv_sec > 0 || diff.tv_nsec > port->egress_agg_params.time_nsec ||
port->agg_count >= port->egress_agg_params.count ||
port->skbagg_head->len == port->egress_agg_params.bytes) {
agg_skb = port->skbagg_head;
reset_aggr_params(port);
spin_unlock_bh(&port->agg_lock);
hrtimer_cancel(&port->hrtimer);
rmnet_send_skb(port, agg_skb);
return len;
}
schedule:
if (!hrtimer_active(&port->hrtimer) && port->agg_state != -EINPROGRESS) {
port->agg_state = -EINPROGRESS;
hrtimer_start(&port->hrtimer,
ns_to_ktime(port->egress_agg_params.time_nsec),
HRTIMER_MODE_REL);
}
spin_unlock_bh(&port->agg_lock);
return len;
no_aggr:
spin_unlock_bh(&port->agg_lock);
skb->protocol = htons(ETH_P_MAP);
dev_queue_xmit(skb);
return len;
}
void rmnet_map_update_ul_agg_config(struct rmnet_port *port, u32 size,
u32 count, u32 time)
{
spin_lock_bh(&port->agg_lock);
port->egress_agg_params.bytes = size;
WRITE_ONCE(port->egress_agg_params.count, count);
port->egress_agg_params.time_nsec = time * NSEC_PER_USEC;
spin_unlock_bh(&port->agg_lock);
}
void rmnet_map_tx_aggregate_init(struct rmnet_port *port)
{
hrtimer_init(&port->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
port->hrtimer.function = rmnet_map_flush_tx_packet_queue;
spin_lock_init(&port->agg_lock);
rmnet_map_update_ul_agg_config(port, 4096, 1, 800);
INIT_WORK(&port->agg_wq, rmnet_map_flush_tx_packet_work);
}
void rmnet_map_tx_aggregate_exit(struct rmnet_port *port)
{
hrtimer_cancel(&port->hrtimer);
cancel_work_sync(&port->agg_wq);
spin_lock_bh(&port->agg_lock);
if (port->agg_state == -EINPROGRESS) {
if (port->skbagg_head) {
dev_kfree_skb_any(port->skbagg_head);
reset_aggr_params(port);
}
port->agg_state = 0;
}
spin_unlock_bh(&port->agg_lock);
}
|
linux-master
|
drivers/net/ethernet/qualcomm/rmnet/rmnet_map_data.c
|
// SPDX-License-Identifier: GPL-2.0-only
/* Copyright (c) 2013-2018, 2021, The Linux Foundation. All rights reserved.
*
* RMNET Data ingress/egress handler
*/
#include <linux/netdevice.h>
#include <linux/netdev_features.h>
#include <linux/if_arp.h>
#include <net/sock.h>
#include "rmnet_private.h"
#include "rmnet_config.h"
#include "rmnet_vnd.h"
#include "rmnet_map.h"
#include "rmnet_handlers.h"
#define RMNET_IP_VERSION_4 0x40
#define RMNET_IP_VERSION_6 0x60
/* Helper Functions */
static void rmnet_set_skb_proto(struct sk_buff *skb)
{
switch (skb->data[0] & 0xF0) {
case RMNET_IP_VERSION_4:
skb->protocol = htons(ETH_P_IP);
break;
case RMNET_IP_VERSION_6:
skb->protocol = htons(ETH_P_IPV6);
break;
default:
skb->protocol = htons(ETH_P_MAP);
break;
}
}
/* Generic handler */
static void
rmnet_deliver_skb(struct sk_buff *skb)
{
struct rmnet_priv *priv = netdev_priv(skb->dev);
skb_reset_transport_header(skb);
skb_reset_network_header(skb);
rmnet_vnd_rx_fixup(skb, skb->dev);
skb->pkt_type = PACKET_HOST;
skb_set_mac_header(skb, 0);
gro_cells_receive(&priv->gro_cells, skb);
}
/* MAP handler */
static void
__rmnet_map_ingress_handler(struct sk_buff *skb,
struct rmnet_port *port)
{
struct rmnet_map_header *map_header = (void *)skb->data;
struct rmnet_endpoint *ep;
u16 len, pad;
u8 mux_id;
if (map_header->flags & MAP_CMD_FLAG) {
/* Packet contains a MAP command (not data) */
if (port->data_format & RMNET_FLAGS_INGRESS_MAP_COMMANDS)
return rmnet_map_command(skb, port);
goto free_skb;
}
mux_id = map_header->mux_id;
pad = map_header->flags & MAP_PAD_LEN_MASK;
len = ntohs(map_header->pkt_len) - pad;
if (mux_id >= RMNET_MAX_LOGICAL_EP)
goto free_skb;
ep = rmnet_get_endpoint(port, mux_id);
if (!ep)
goto free_skb;
skb->dev = ep->egress_dev;
if ((port->data_format & RMNET_FLAGS_INGRESS_MAP_CKSUMV5) &&
(map_header->flags & MAP_NEXT_HEADER_FLAG)) {
if (rmnet_map_process_next_hdr_packet(skb, len))
goto free_skb;
skb_pull(skb, sizeof(*map_header));
rmnet_set_skb_proto(skb);
} else {
/* Subtract MAP header */
skb_pull(skb, sizeof(*map_header));
rmnet_set_skb_proto(skb);
if (port->data_format & RMNET_FLAGS_INGRESS_MAP_CKSUMV4 &&
!rmnet_map_checksum_downlink_packet(skb, len + pad))
skb->ip_summed = CHECKSUM_UNNECESSARY;
}
skb_trim(skb, len);
rmnet_deliver_skb(skb);
return;
free_skb:
kfree_skb(skb);
}
static void
rmnet_map_ingress_handler(struct sk_buff *skb,
struct rmnet_port *port)
{
struct sk_buff *skbn;
if (skb->dev->type == ARPHRD_ETHER) {
if (pskb_expand_head(skb, ETH_HLEN, 0, GFP_ATOMIC)) {
kfree_skb(skb);
return;
}
skb_push(skb, ETH_HLEN);
}
if (port->data_format & RMNET_FLAGS_INGRESS_DEAGGREGATION) {
while ((skbn = rmnet_map_deaggregate(skb, port)) != NULL)
__rmnet_map_ingress_handler(skbn, port);
consume_skb(skb);
} else {
__rmnet_map_ingress_handler(skb, port);
}
}
static int rmnet_map_egress_handler(struct sk_buff *skb,
struct rmnet_port *port, u8 mux_id,
struct net_device *orig_dev)
{
int required_headroom, additional_header_len, csum_type = 0;
struct rmnet_map_header *map_header;
additional_header_len = 0;
required_headroom = sizeof(struct rmnet_map_header);
if (port->data_format & RMNET_FLAGS_EGRESS_MAP_CKSUMV4) {
additional_header_len = sizeof(struct rmnet_map_ul_csum_header);
csum_type = RMNET_FLAGS_EGRESS_MAP_CKSUMV4;
} else if (port->data_format & RMNET_FLAGS_EGRESS_MAP_CKSUMV5) {
additional_header_len = sizeof(struct rmnet_map_v5_csum_header);
csum_type = RMNET_FLAGS_EGRESS_MAP_CKSUMV5;
}
required_headroom += additional_header_len;
if (skb_cow_head(skb, required_headroom) < 0)
return -ENOMEM;
if (csum_type)
rmnet_map_checksum_uplink_packet(skb, port, orig_dev,
csum_type);
map_header = rmnet_map_add_map_header(skb, additional_header_len,
port, 0);
if (!map_header)
return -ENOMEM;
map_header->mux_id = mux_id;
if (READ_ONCE(port->egress_agg_params.count) > 1) {
unsigned int len;
len = rmnet_map_tx_aggregate(skb, port, orig_dev);
if (likely(len)) {
rmnet_vnd_tx_fixup_len(len, orig_dev);
return -EINPROGRESS;
}
return -ENOMEM;
}
skb->protocol = htons(ETH_P_MAP);
return 0;
}
static void
rmnet_bridge_handler(struct sk_buff *skb, struct net_device *bridge_dev)
{
if (skb_mac_header_was_set(skb))
skb_push(skb, skb->mac_len);
if (bridge_dev) {
skb->dev = bridge_dev;
dev_queue_xmit(skb);
}
}
/* Ingress / Egress Entry Points */
/* Processes packet as per ingress data format for receiving device. Logical
* endpoint is determined from packet inspection. Packet is then sent to the
* egress device listed in the logical endpoint configuration.
*/
rx_handler_result_t rmnet_rx_handler(struct sk_buff **pskb)
{
struct sk_buff *skb = *pskb;
struct rmnet_port *port;
struct net_device *dev;
if (!skb)
goto done;
if (skb_linearize(skb)) {
kfree_skb(skb);
goto done;
}
if (skb->pkt_type == PACKET_LOOPBACK)
return RX_HANDLER_PASS;
dev = skb->dev;
port = rmnet_get_port_rcu(dev);
if (unlikely(!port)) {
dev_core_stats_rx_nohandler_inc(skb->dev);
kfree_skb(skb);
goto done;
}
switch (port->rmnet_mode) {
case RMNET_EPMODE_VND:
rmnet_map_ingress_handler(skb, port);
break;
case RMNET_EPMODE_BRIDGE:
rmnet_bridge_handler(skb, port->bridge_ep);
break;
}
done:
return RX_HANDLER_CONSUMED;
}
/* Modifies packet as per logical endpoint configuration and egress data format
* for egress device configured in logical endpoint. Packet is then transmitted
* on the egress device.
*/
void rmnet_egress_handler(struct sk_buff *skb)
{
struct net_device *orig_dev;
struct rmnet_port *port;
struct rmnet_priv *priv;
u8 mux_id;
int err;
sk_pacing_shift_update(skb->sk, 8);
orig_dev = skb->dev;
priv = netdev_priv(orig_dev);
skb->dev = priv->real_dev;
mux_id = priv->mux_id;
port = rmnet_get_port_rcu(skb->dev);
if (!port)
goto drop;
err = rmnet_map_egress_handler(skb, port, mux_id, orig_dev);
if (err == -ENOMEM)
goto drop;
else if (err == -EINPROGRESS)
return;
rmnet_vnd_tx_fixup(skb, orig_dev);
dev_queue_xmit(skb);
return;
drop:
this_cpu_inc(priv->pcpu_stats->stats.tx_drops);
kfree_skb(skb);
}
|
linux-master
|
drivers/net/ethernet/qualcomm/rmnet/rmnet_handlers.c
|
// SPDX-License-Identifier: GPL-2.0-only
/* Copyright (c) 2013-2018, The Linux Foundation. All rights reserved.
*/
#include <linux/netdevice.h>
#include "rmnet_config.h"
#include "rmnet_map.h"
#include "rmnet_private.h"
#include "rmnet_vnd.h"
static u8 rmnet_map_do_flow_control(struct sk_buff *skb,
struct rmnet_port *port,
int enable)
{
struct rmnet_map_header *map_header = (void *)skb->data;
struct rmnet_endpoint *ep;
struct net_device *vnd;
u8 mux_id;
int r;
mux_id = map_header->mux_id;
if (mux_id >= RMNET_MAX_LOGICAL_EP) {
kfree_skb(skb);
return RX_HANDLER_CONSUMED;
}
ep = rmnet_get_endpoint(port, mux_id);
if (!ep) {
kfree_skb(skb);
return RX_HANDLER_CONSUMED;
}
vnd = ep->egress_dev;
/* Ignore the ip family and pass the sequence number for both v4 and v6
* sequence. User space does not support creating dedicated flows for
* the 2 protocols
*/
r = rmnet_vnd_do_flow_control(vnd, enable);
if (r) {
kfree_skb(skb);
return RMNET_MAP_COMMAND_UNSUPPORTED;
} else {
return RMNET_MAP_COMMAND_ACK;
}
}
static void rmnet_map_send_ack(struct sk_buff *skb,
unsigned char type,
struct rmnet_port *port)
{
struct rmnet_map_header *map_header = (void *)skb->data;
struct rmnet_map_control_command *cmd;
struct net_device *dev = skb->dev;
if (port->data_format & RMNET_FLAGS_INGRESS_MAP_CKSUMV4)
skb_trim(skb,
skb->len - sizeof(struct rmnet_map_dl_csum_trailer));
skb->protocol = htons(ETH_P_MAP);
/* Command data immediately follows the MAP header */
cmd = (struct rmnet_map_control_command *)(map_header + 1);
cmd->cmd_type = type & 0x03;
netif_tx_lock(dev);
dev->netdev_ops->ndo_start_xmit(skb, dev);
netif_tx_unlock(dev);
}
/* Process MAP command frame and send N/ACK message as appropriate. Message cmd
* name is decoded here and appropriate handler is called.
*/
void rmnet_map_command(struct sk_buff *skb, struct rmnet_port *port)
{
struct rmnet_map_header *map_header = (void *)skb->data;
struct rmnet_map_control_command *cmd;
unsigned char command_name;
unsigned char rc = 0;
/* Command data immediately follows the MAP header */
cmd = (struct rmnet_map_control_command *)(map_header + 1);
command_name = cmd->command_name;
switch (command_name) {
case RMNET_MAP_COMMAND_FLOW_ENABLE:
rc = rmnet_map_do_flow_control(skb, port, 1);
break;
case RMNET_MAP_COMMAND_FLOW_DISABLE:
rc = rmnet_map_do_flow_control(skb, port, 0);
break;
default:
rc = RMNET_MAP_COMMAND_UNSUPPORTED;
kfree_skb(skb);
break;
}
if (rc == RMNET_MAP_COMMAND_ACK)
rmnet_map_send_ack(skb, rc, port);
}
|
linux-master
|
drivers/net/ethernet/qualcomm/rmnet/rmnet_map_command.c
|
// SPDX-License-Identifier: GPL-2.0-only
/* Copyright (c) 2013-2018, The Linux Foundation. All rights reserved.
*
* RMNET configuration engine
*/
#include <net/sock.h>
#include <linux/module.h>
#include <linux/netlink.h>
#include <linux/netdevice.h>
#include "rmnet_config.h"
#include "rmnet_handlers.h"
#include "rmnet_vnd.h"
#include "rmnet_private.h"
#include "rmnet_map.h"
/* Local Definitions and Declarations */
static const struct nla_policy rmnet_policy[IFLA_RMNET_MAX + 1] = {
[IFLA_RMNET_MUX_ID] = { .type = NLA_U16 },
[IFLA_RMNET_FLAGS] = { .len = sizeof(struct ifla_rmnet_flags) },
};
static int rmnet_is_real_dev_registered(const struct net_device *real_dev)
{
return rcu_access_pointer(real_dev->rx_handler) == rmnet_rx_handler;
}
/* Needs rtnl lock */
struct rmnet_port*
rmnet_get_port_rtnl(const struct net_device *real_dev)
{
return rtnl_dereference(real_dev->rx_handler_data);
}
static int rmnet_unregister_real_device(struct net_device *real_dev)
{
struct rmnet_port *port = rmnet_get_port_rtnl(real_dev);
if (port->nr_rmnet_devs)
return -EINVAL;
rmnet_map_tx_aggregate_exit(port);
netdev_rx_handler_unregister(real_dev);
kfree(port);
netdev_dbg(real_dev, "Removed from rmnet\n");
return 0;
}
static int rmnet_register_real_device(struct net_device *real_dev,
struct netlink_ext_ack *extack)
{
struct rmnet_port *port;
int rc, entry;
ASSERT_RTNL();
if (rmnet_is_real_dev_registered(real_dev)) {
port = rmnet_get_port_rtnl(real_dev);
if (port->rmnet_mode != RMNET_EPMODE_VND) {
NL_SET_ERR_MSG_MOD(extack, "bridge device already exists");
return -EINVAL;
}
return 0;
}
port = kzalloc(sizeof(*port), GFP_KERNEL);
if (!port)
return -ENOMEM;
port->dev = real_dev;
rc = netdev_rx_handler_register(real_dev, rmnet_rx_handler, port);
if (rc) {
kfree(port);
return -EBUSY;
}
for (entry = 0; entry < RMNET_MAX_LOGICAL_EP; entry++)
INIT_HLIST_HEAD(&port->muxed_ep[entry]);
rmnet_map_tx_aggregate_init(port);
netdev_dbg(real_dev, "registered with rmnet\n");
return 0;
}
static void rmnet_unregister_bridge(struct rmnet_port *port)
{
struct net_device *bridge_dev, *real_dev, *rmnet_dev;
struct rmnet_port *real_port;
if (port->rmnet_mode != RMNET_EPMODE_BRIDGE)
return;
rmnet_dev = port->rmnet_dev;
if (!port->nr_rmnet_devs) {
/* bridge device */
real_dev = port->bridge_ep;
bridge_dev = port->dev;
real_port = rmnet_get_port_rtnl(real_dev);
real_port->bridge_ep = NULL;
real_port->rmnet_mode = RMNET_EPMODE_VND;
} else {
/* real device */
bridge_dev = port->bridge_ep;
port->bridge_ep = NULL;
port->rmnet_mode = RMNET_EPMODE_VND;
}
netdev_upper_dev_unlink(bridge_dev, rmnet_dev);
rmnet_unregister_real_device(bridge_dev);
}
static int rmnet_newlink(struct net *src_net, struct net_device *dev,
struct nlattr *tb[], struct nlattr *data[],
struct netlink_ext_ack *extack)
{
u32 data_format = RMNET_FLAGS_INGRESS_DEAGGREGATION;
struct net_device *real_dev;
int mode = RMNET_EPMODE_VND;
struct rmnet_endpoint *ep;
struct rmnet_port *port;
int err = 0;
u16 mux_id;
if (!tb[IFLA_LINK]) {
NL_SET_ERR_MSG_MOD(extack, "link not specified");
return -EINVAL;
}
real_dev = __dev_get_by_index(src_net, nla_get_u32(tb[IFLA_LINK]));
if (!real_dev) {
NL_SET_ERR_MSG_MOD(extack, "link does not exist");
return -ENODEV;
}
ep = kzalloc(sizeof(*ep), GFP_KERNEL);
if (!ep)
return -ENOMEM;
mux_id = nla_get_u16(data[IFLA_RMNET_MUX_ID]);
err = rmnet_register_real_device(real_dev, extack);
if (err)
goto err0;
port = rmnet_get_port_rtnl(real_dev);
err = rmnet_vnd_newlink(mux_id, dev, port, real_dev, ep, extack);
if (err)
goto err1;
err = netdev_upper_dev_link(real_dev, dev, extack);
if (err < 0)
goto err2;
port->rmnet_mode = mode;
port->rmnet_dev = dev;
hlist_add_head_rcu(&ep->hlnode, &port->muxed_ep[mux_id]);
if (data[IFLA_RMNET_FLAGS]) {
struct ifla_rmnet_flags *flags;
flags = nla_data(data[IFLA_RMNET_FLAGS]);
data_format &= ~flags->mask;
data_format |= flags->flags & flags->mask;
}
netdev_dbg(dev, "data format [0x%08X]\n", data_format);
port->data_format = data_format;
return 0;
err2:
unregister_netdevice(dev);
rmnet_vnd_dellink(mux_id, port, ep);
err1:
rmnet_unregister_real_device(real_dev);
err0:
kfree(ep);
return err;
}
static void rmnet_dellink(struct net_device *dev, struct list_head *head)
{
struct rmnet_priv *priv = netdev_priv(dev);
struct net_device *real_dev, *bridge_dev;
struct rmnet_port *real_port, *bridge_port;
struct rmnet_endpoint *ep;
u8 mux_id = priv->mux_id;
real_dev = priv->real_dev;
if (!rmnet_is_real_dev_registered(real_dev))
return;
real_port = rmnet_get_port_rtnl(real_dev);
bridge_dev = real_port->bridge_ep;
if (bridge_dev) {
bridge_port = rmnet_get_port_rtnl(bridge_dev);
rmnet_unregister_bridge(bridge_port);
}
ep = rmnet_get_endpoint(real_port, mux_id);
if (ep) {
hlist_del_init_rcu(&ep->hlnode);
rmnet_vnd_dellink(mux_id, real_port, ep);
kfree(ep);
}
netdev_upper_dev_unlink(real_dev, dev);
rmnet_unregister_real_device(real_dev);
unregister_netdevice_queue(dev, head);
}
static void rmnet_force_unassociate_device(struct net_device *real_dev)
{
struct hlist_node *tmp_ep;
struct rmnet_endpoint *ep;
struct rmnet_port *port;
unsigned long bkt_ep;
LIST_HEAD(list);
port = rmnet_get_port_rtnl(real_dev);
if (port->nr_rmnet_devs) {
/* real device */
rmnet_unregister_bridge(port);
hash_for_each_safe(port->muxed_ep, bkt_ep, tmp_ep, ep, hlnode) {
unregister_netdevice_queue(ep->egress_dev, &list);
netdev_upper_dev_unlink(real_dev, ep->egress_dev);
rmnet_vnd_dellink(ep->mux_id, port, ep);
hlist_del_init_rcu(&ep->hlnode);
kfree(ep);
}
rmnet_unregister_real_device(real_dev);
unregister_netdevice_many(&list);
} else {
rmnet_unregister_bridge(port);
}
}
static int rmnet_config_notify_cb(struct notifier_block *nb,
unsigned long event, void *data)
{
struct net_device *real_dev = netdev_notifier_info_to_dev(data);
if (!rmnet_is_real_dev_registered(real_dev))
return NOTIFY_DONE;
switch (event) {
case NETDEV_UNREGISTER:
netdev_dbg(real_dev, "Kernel unregister\n");
rmnet_force_unassociate_device(real_dev);
break;
case NETDEV_CHANGEMTU:
if (rmnet_vnd_validate_real_dev_mtu(real_dev))
return NOTIFY_BAD;
break;
default:
break;
}
return NOTIFY_DONE;
}
static struct notifier_block rmnet_dev_notifier __read_mostly = {
.notifier_call = rmnet_config_notify_cb,
};
static int rmnet_rtnl_validate(struct nlattr *tb[], struct nlattr *data[],
struct netlink_ext_ack *extack)
{
u16 mux_id;
if (!data || !data[IFLA_RMNET_MUX_ID]) {
NL_SET_ERR_MSG_MOD(extack, "MUX ID not specified");
return -EINVAL;
}
mux_id = nla_get_u16(data[IFLA_RMNET_MUX_ID]);
if (mux_id > (RMNET_MAX_LOGICAL_EP - 1)) {
NL_SET_ERR_MSG_MOD(extack, "invalid MUX ID");
return -ERANGE;
}
return 0;
}
static int rmnet_changelink(struct net_device *dev, struct nlattr *tb[],
struct nlattr *data[],
struct netlink_ext_ack *extack)
{
struct rmnet_priv *priv = netdev_priv(dev);
struct net_device *real_dev;
struct rmnet_port *port;
u16 mux_id;
if (!dev)
return -ENODEV;
real_dev = priv->real_dev;
if (!rmnet_is_real_dev_registered(real_dev))
return -ENODEV;
port = rmnet_get_port_rtnl(real_dev);
if (data[IFLA_RMNET_MUX_ID]) {
mux_id = nla_get_u16(data[IFLA_RMNET_MUX_ID]);
if (mux_id != priv->mux_id) {
struct rmnet_endpoint *ep;
ep = rmnet_get_endpoint(port, priv->mux_id);
if (!ep)
return -ENODEV;
if (rmnet_get_endpoint(port, mux_id)) {
NL_SET_ERR_MSG_MOD(extack,
"MUX ID already exists");
return -EINVAL;
}
hlist_del_init_rcu(&ep->hlnode);
hlist_add_head_rcu(&ep->hlnode,
&port->muxed_ep[mux_id]);
ep->mux_id = mux_id;
priv->mux_id = mux_id;
}
}
if (data[IFLA_RMNET_FLAGS]) {
struct ifla_rmnet_flags *flags;
u32 old_data_format;
old_data_format = port->data_format;
flags = nla_data(data[IFLA_RMNET_FLAGS]);
port->data_format &= ~flags->mask;
port->data_format |= flags->flags & flags->mask;
if (rmnet_vnd_update_dev_mtu(port, real_dev)) {
port->data_format = old_data_format;
NL_SET_ERR_MSG_MOD(extack, "Invalid MTU on real dev");
return -EINVAL;
}
}
return 0;
}
static size_t rmnet_get_size(const struct net_device *dev)
{
return
/* IFLA_RMNET_MUX_ID */
nla_total_size(2) +
/* IFLA_RMNET_FLAGS */
nla_total_size(sizeof(struct ifla_rmnet_flags));
}
static int rmnet_fill_info(struct sk_buff *skb, const struct net_device *dev)
{
struct rmnet_priv *priv = netdev_priv(dev);
struct net_device *real_dev;
struct ifla_rmnet_flags f;
struct rmnet_port *port;
real_dev = priv->real_dev;
if (nla_put_u16(skb, IFLA_RMNET_MUX_ID, priv->mux_id))
goto nla_put_failure;
if (rmnet_is_real_dev_registered(real_dev)) {
port = rmnet_get_port_rtnl(real_dev);
f.flags = port->data_format;
} else {
f.flags = 0;
}
f.mask = ~0;
if (nla_put(skb, IFLA_RMNET_FLAGS, sizeof(f), &f))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
struct rtnl_link_ops rmnet_link_ops __read_mostly = {
.kind = "rmnet",
.maxtype = __IFLA_RMNET_MAX,
.priv_size = sizeof(struct rmnet_priv),
.setup = rmnet_vnd_setup,
.validate = rmnet_rtnl_validate,
.newlink = rmnet_newlink,
.dellink = rmnet_dellink,
.get_size = rmnet_get_size,
.changelink = rmnet_changelink,
.policy = rmnet_policy,
.fill_info = rmnet_fill_info,
};
struct rmnet_port *rmnet_get_port_rcu(struct net_device *real_dev)
{
if (rmnet_is_real_dev_registered(real_dev))
return rcu_dereference_bh(real_dev->rx_handler_data);
else
return NULL;
}
struct rmnet_endpoint *rmnet_get_endpoint(struct rmnet_port *port, u8 mux_id)
{
struct rmnet_endpoint *ep;
hlist_for_each_entry_rcu(ep, &port->muxed_ep[mux_id], hlnode) {
if (ep->mux_id == mux_id)
return ep;
}
return NULL;
}
int rmnet_add_bridge(struct net_device *rmnet_dev,
struct net_device *slave_dev,
struct netlink_ext_ack *extack)
{
struct rmnet_priv *priv = netdev_priv(rmnet_dev);
struct net_device *real_dev = priv->real_dev;
struct rmnet_port *port, *slave_port;
int err;
port = rmnet_get_port_rtnl(real_dev);
/* If there is more than one rmnet dev attached, its probably being
* used for muxing. Skip the briding in that case
*/
if (port->nr_rmnet_devs > 1) {
NL_SET_ERR_MSG_MOD(extack, "more than one rmnet dev attached");
return -EINVAL;
}
if (port->rmnet_mode != RMNET_EPMODE_VND) {
NL_SET_ERR_MSG_MOD(extack, "more than one bridge dev attached");
return -EINVAL;
}
if (rmnet_is_real_dev_registered(slave_dev)) {
NL_SET_ERR_MSG_MOD(extack,
"slave cannot be another rmnet dev");
return -EBUSY;
}
err = rmnet_register_real_device(slave_dev, extack);
if (err)
return -EBUSY;
err = netdev_master_upper_dev_link(slave_dev, rmnet_dev, NULL, NULL,
extack);
if (err) {
rmnet_unregister_real_device(slave_dev);
return err;
}
slave_port = rmnet_get_port_rtnl(slave_dev);
slave_port->rmnet_mode = RMNET_EPMODE_BRIDGE;
slave_port->bridge_ep = real_dev;
slave_port->rmnet_dev = rmnet_dev;
port->rmnet_mode = RMNET_EPMODE_BRIDGE;
port->bridge_ep = slave_dev;
netdev_dbg(slave_dev, "registered with rmnet as slave\n");
return 0;
}
int rmnet_del_bridge(struct net_device *rmnet_dev,
struct net_device *slave_dev)
{
struct rmnet_port *port = rmnet_get_port_rtnl(slave_dev);
rmnet_unregister_bridge(port);
netdev_dbg(slave_dev, "removed from rmnet as slave\n");
return 0;
}
/* Startup/Shutdown */
static int __init rmnet_init(void)
{
int rc;
rc = register_netdevice_notifier(&rmnet_dev_notifier);
if (rc != 0)
return rc;
rc = rtnl_link_register(&rmnet_link_ops);
if (rc != 0) {
unregister_netdevice_notifier(&rmnet_dev_notifier);
return rc;
}
return rc;
}
static void __exit rmnet_exit(void)
{
rtnl_link_unregister(&rmnet_link_ops);
unregister_netdevice_notifier(&rmnet_dev_notifier);
}
module_init(rmnet_init)
module_exit(rmnet_exit)
MODULE_ALIAS_RTNL_LINK("rmnet");
MODULE_LICENSE("GPL v2");
|
linux-master
|
drivers/net/ethernet/qualcomm/rmnet/rmnet_config.c
|
// SPDX-License-Identifier: GPL-2.0-only
/* Copyright (c) 2015-2016, The Linux Foundation. All rights reserved.
*/
/* Qualcomm Technologies, Inc. QDF2432 EMAC SGMII Controller driver.
*/
#include <linux/iopoll.h>
#include "emac.h"
/* EMAC_SGMII register offsets */
#define EMAC_SGMII_PHY_TX_PWR_CTRL 0x000C
#define EMAC_SGMII_PHY_LANE_CTRL1 0x0018
#define EMAC_SGMII_PHY_CDR_CTRL0 0x0058
#define EMAC_SGMII_PHY_POW_DWN_CTRL0 0x0080
#define EMAC_SGMII_PHY_RESET_CTRL 0x00a8
#define EMAC_SGMII_PHY_INTERRUPT_MASK 0x00b4
/* SGMII digital lane registers */
#define EMAC_SGMII_LN_DRVR_CTRL0 0x000C
#define EMAC_SGMII_LN_DRVR_TAP_EN 0x0018
#define EMAC_SGMII_LN_TX_MARGINING 0x001C
#define EMAC_SGMII_LN_TX_PRE 0x0020
#define EMAC_SGMII_LN_TX_POST 0x0024
#define EMAC_SGMII_LN_TX_BAND_MODE 0x0060
#define EMAC_SGMII_LN_LANE_MODE 0x0064
#define EMAC_SGMII_LN_PARALLEL_RATE 0x0078
#define EMAC_SGMII_LN_CML_CTRL_MODE0 0x00B8
#define EMAC_SGMII_LN_MIXER_CTRL_MODE0 0x00D0
#define EMAC_SGMII_LN_VGA_INITVAL 0x0134
#define EMAC_SGMII_LN_UCDR_FO_GAIN_MODE0 0x017C
#define EMAC_SGMII_LN_UCDR_SO_GAIN_MODE0 0x0188
#define EMAC_SGMII_LN_UCDR_SO_CONFIG 0x0194
#define EMAC_SGMII_LN_RX_BAND 0x019C
#define EMAC_SGMII_LN_RX_RCVR_PATH1_MODE0 0x01B8
#define EMAC_SGMII_LN_RSM_CONFIG 0x01F0
#define EMAC_SGMII_LN_SIGDET_ENABLES 0x0224
#define EMAC_SGMII_LN_SIGDET_CNTRL 0x0228
#define EMAC_SGMII_LN_SIGDET_DEGLITCH_CNTRL 0x022C
#define EMAC_SGMII_LN_RX_EN_SIGNAL 0x02A0
#define EMAC_SGMII_LN_RX_MISC_CNTRL0 0x02AC
#define EMAC_SGMII_LN_DRVR_LOGIC_CLKDIV 0x02BC
/* SGMII digital lane register values */
#define UCDR_STEP_BY_TWO_MODE0 BIT(7)
#define UCDR_xO_GAIN_MODE(x) ((x) & 0x7f)
#define UCDR_ENABLE BIT(6)
#define UCDR_SO_SATURATION(x) ((x) & 0x3f)
#define SIGDET_LP_BYP_PS4 BIT(7)
#define SIGDET_EN_PS0_TO_PS2 BIT(6)
#define TXVAL_VALID_INIT BIT(4)
#define KR_PCIGEN3_MODE BIT(0)
#define MAIN_EN BIT(0)
#define TX_MARGINING_MUX BIT(6)
#define TX_MARGINING(x) ((x) & 0x3f)
#define TX_PRE_MUX BIT(6)
#define TX_POST_MUX BIT(6)
#define CML_GEAR_MODE(x) (((x) & 7) << 3)
#define CML2CMOS_IBOOST_MODE(x) ((x) & 7)
#define MIXER_LOADB_MODE(x) (((x) & 0xf) << 2)
#define MIXER_DATARATE_MODE(x) ((x) & 3)
#define VGA_THRESH_DFE(x) ((x) & 0x3f)
#define SIGDET_LP_BYP_PS0_TO_PS2 BIT(5)
#define SIGDET_FLT_BYP BIT(0)
#define SIGDET_LVL(x) (((x) & 0xf) << 4)
#define SIGDET_DEGLITCH_CTRL(x) (((x) & 0xf) << 1)
#define DRVR_LOGIC_CLK_EN BIT(4)
#define DRVR_LOGIC_CLK_DIV(x) ((x) & 0xf)
#define PARALLEL_RATE_MODE0(x) ((x) & 0x3)
#define BAND_MODE0(x) ((x) & 0x3)
#define LANE_MODE(x) ((x) & 0x1f)
#define CDR_PD_SEL_MODE0(x) (((x) & 0x3) << 5)
#define BYPASS_RSM_SAMP_CAL BIT(1)
#define BYPASS_RSM_DLL_CAL BIT(0)
#define L0_RX_EQUALIZE_ENABLE BIT(6)
#define PWRDN_B BIT(0)
#define CDR_MAX_CNT(x) ((x) & 0xff)
#define SERDES_START_WAIT_TIMES 100
struct emac_reg_write {
unsigned int offset;
u32 val;
};
static void emac_reg_write_all(void __iomem *base,
const struct emac_reg_write *itr, size_t size)
{
size_t i;
for (i = 0; i < size; ++itr, ++i)
writel(itr->val, base + itr->offset);
}
static const struct emac_reg_write sgmii_laned[] = {
/* CDR Settings */
{EMAC_SGMII_LN_UCDR_FO_GAIN_MODE0,
UCDR_STEP_BY_TWO_MODE0 | UCDR_xO_GAIN_MODE(10)},
{EMAC_SGMII_LN_UCDR_SO_GAIN_MODE0, UCDR_xO_GAIN_MODE(0)},
{EMAC_SGMII_LN_UCDR_SO_CONFIG, UCDR_ENABLE | UCDR_SO_SATURATION(12)},
/* TX/RX Settings */
{EMAC_SGMII_LN_RX_EN_SIGNAL, SIGDET_LP_BYP_PS4 | SIGDET_EN_PS0_TO_PS2},
{EMAC_SGMII_LN_DRVR_CTRL0, TXVAL_VALID_INIT | KR_PCIGEN3_MODE},
{EMAC_SGMII_LN_DRVR_TAP_EN, MAIN_EN},
{EMAC_SGMII_LN_TX_MARGINING, TX_MARGINING_MUX | TX_MARGINING(25)},
{EMAC_SGMII_LN_TX_PRE, TX_PRE_MUX},
{EMAC_SGMII_LN_TX_POST, TX_POST_MUX},
{EMAC_SGMII_LN_CML_CTRL_MODE0,
CML_GEAR_MODE(1) | CML2CMOS_IBOOST_MODE(1)},
{EMAC_SGMII_LN_MIXER_CTRL_MODE0,
MIXER_LOADB_MODE(12) | MIXER_DATARATE_MODE(1)},
{EMAC_SGMII_LN_VGA_INITVAL, VGA_THRESH_DFE(31)},
{EMAC_SGMII_LN_SIGDET_ENABLES,
SIGDET_LP_BYP_PS0_TO_PS2 | SIGDET_FLT_BYP},
{EMAC_SGMII_LN_SIGDET_CNTRL, SIGDET_LVL(8)},
{EMAC_SGMII_LN_SIGDET_DEGLITCH_CNTRL, SIGDET_DEGLITCH_CTRL(4)},
{EMAC_SGMII_LN_RX_MISC_CNTRL0, 0},
{EMAC_SGMII_LN_DRVR_LOGIC_CLKDIV,
DRVR_LOGIC_CLK_EN | DRVR_LOGIC_CLK_DIV(4)},
{EMAC_SGMII_LN_PARALLEL_RATE, PARALLEL_RATE_MODE0(1)},
{EMAC_SGMII_LN_TX_BAND_MODE, BAND_MODE0(2)},
{EMAC_SGMII_LN_RX_BAND, BAND_MODE0(3)},
{EMAC_SGMII_LN_LANE_MODE, LANE_MODE(26)},
{EMAC_SGMII_LN_RX_RCVR_PATH1_MODE0, CDR_PD_SEL_MODE0(3)},
{EMAC_SGMII_LN_RSM_CONFIG, BYPASS_RSM_SAMP_CAL | BYPASS_RSM_DLL_CAL},
};
static const struct emac_reg_write physical_coding_sublayer_programming[] = {
{EMAC_SGMII_PHY_POW_DWN_CTRL0, PWRDN_B},
{EMAC_SGMII_PHY_CDR_CTRL0, CDR_MAX_CNT(15)},
{EMAC_SGMII_PHY_TX_PWR_CTRL, 0},
{EMAC_SGMII_PHY_LANE_CTRL1, L0_RX_EQUALIZE_ENABLE},
};
int emac_sgmii_init_qdf2432(struct emac_adapter *adpt)
{
struct emac_sgmii *phy = &adpt->phy;
void __iomem *phy_regs = phy->base;
void __iomem *laned = phy->digital;
unsigned int i;
u32 lnstatus;
/* PCS lane-x init */
emac_reg_write_all(phy->base, physical_coding_sublayer_programming,
ARRAY_SIZE(physical_coding_sublayer_programming));
/* SGMII lane-x init */
emac_reg_write_all(phy->digital, sgmii_laned, ARRAY_SIZE(sgmii_laned));
/* Power up PCS and start reset lane state machine */
writel(0, phy_regs + EMAC_SGMII_PHY_RESET_CTRL);
writel(1, laned + SGMII_LN_RSM_START);
/* Wait for c_ready assertion */
for (i = 0; i < SERDES_START_WAIT_TIMES; i++) {
lnstatus = readl(phy_regs + SGMII_PHY_LN_LANE_STATUS);
if (lnstatus & BIT(1))
break;
usleep_range(100, 200);
}
if (i == SERDES_START_WAIT_TIMES) {
netdev_err(adpt->netdev, "SGMII failed to start\n");
return -EIO;
}
/* Disable digital and SERDES loopback */
writel(0, phy_regs + SGMII_PHY_LN_BIST_GEN0);
writel(0, phy_regs + SGMII_PHY_LN_BIST_GEN2);
writel(0, phy_regs + SGMII_PHY_LN_CDR_CTRL1);
/* Mask out all the SGMII Interrupt */
writel(0, phy_regs + EMAC_SGMII_PHY_INTERRUPT_MASK);
return 0;
}
|
linux-master
|
drivers/net/ethernet/qualcomm/emac/emac-sgmii-qdf2432.c
|
// SPDX-License-Identifier: GPL-2.0-only
/* Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
*/
/* Qualcomm Technologies, Inc. EMAC Gigabit Ethernet Driver */
#include <linux/if_ether.h>
#include <linux/if_vlan.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_net.h>
#include <linux/phy.h>
#include <linux/platform_device.h>
#include <linux/acpi.h>
#include "emac.h"
#include "emac-mac.h"
#include "emac-phy.h"
#include "emac-sgmii.h"
#define EMAC_MSG_DEFAULT (NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_LINK | \
NETIF_MSG_TIMER | NETIF_MSG_IFDOWN | NETIF_MSG_IFUP)
#define EMAC_RRD_SIZE 4
/* The RRD size if timestamping is enabled: */
#define EMAC_TS_RRD_SIZE 6
#define EMAC_TPD_SIZE 4
#define EMAC_RFD_SIZE 2
#define REG_MAC_RX_STATUS_BIN EMAC_RXMAC_STATC_REG0
#define REG_MAC_RX_STATUS_END EMAC_RXMAC_STATC_REG22
#define REG_MAC_TX_STATUS_BIN EMAC_TXMAC_STATC_REG0
#define REG_MAC_TX_STATUS_END EMAC_TXMAC_STATC_REG24
#define RXQ0_NUM_RFD_PREF_DEF 8
#define TXQ0_NUM_TPD_PREF_DEF 5
#define EMAC_PREAMBLE_DEF 7
#define DMAR_DLY_CNT_DEF 15
#define DMAW_DLY_CNT_DEF 4
#define IMR_NORMAL_MASK (ISR_ERROR | ISR_OVER | ISR_TX_PKT)
#define ISR_TX_PKT (\
TX_PKT_INT |\
TX_PKT_INT1 |\
TX_PKT_INT2 |\
TX_PKT_INT3)
#define ISR_OVER (\
RFD0_UR_INT |\
RFD1_UR_INT |\
RFD2_UR_INT |\
RFD3_UR_INT |\
RFD4_UR_INT |\
RXF_OF_INT |\
TXF_UR_INT)
#define ISR_ERROR (\
DMAR_TO_INT |\
DMAW_TO_INT |\
TXQ_TO_INT)
/* in sync with enum emac_clk_id */
static const char * const emac_clk_name[] = {
"axi_clk", "cfg_ahb_clk", "high_speed_clk", "mdio_clk", "tx_clk",
"rx_clk", "sys_clk"
};
void emac_reg_update32(void __iomem *addr, u32 mask, u32 val)
{
u32 data = readl(addr);
writel(((data & ~mask) | val), addr);
}
/* reinitialize */
int emac_reinit_locked(struct emac_adapter *adpt)
{
int ret;
mutex_lock(&adpt->reset_lock);
emac_mac_down(adpt);
emac_sgmii_reset(adpt);
ret = emac_mac_up(adpt);
mutex_unlock(&adpt->reset_lock);
return ret;
}
/* NAPI */
static int emac_napi_rtx(struct napi_struct *napi, int budget)
{
struct emac_rx_queue *rx_q =
container_of(napi, struct emac_rx_queue, napi);
struct emac_adapter *adpt = netdev_priv(rx_q->netdev);
struct emac_irq *irq = rx_q->irq;
int work_done = 0;
emac_mac_rx_process(adpt, rx_q, &work_done, budget);
if (work_done < budget) {
napi_complete_done(napi, work_done);
irq->mask |= rx_q->intr;
writel(irq->mask, adpt->base + EMAC_INT_MASK);
}
return work_done;
}
/* Transmit the packet */
static netdev_tx_t emac_start_xmit(struct sk_buff *skb,
struct net_device *netdev)
{
struct emac_adapter *adpt = netdev_priv(netdev);
return emac_mac_tx_buf_send(adpt, &adpt->tx_q, skb);
}
static irqreturn_t emac_isr(int _irq, void *data)
{
struct emac_irq *irq = data;
struct emac_adapter *adpt =
container_of(irq, struct emac_adapter, irq);
struct emac_rx_queue *rx_q = &adpt->rx_q;
u32 isr, status;
/* disable the interrupt */
writel(0, adpt->base + EMAC_INT_MASK);
isr = readl_relaxed(adpt->base + EMAC_INT_STATUS);
status = isr & irq->mask;
if (status == 0)
goto exit;
if (status & ISR_ERROR) {
net_err_ratelimited("%s: error interrupt 0x%lx\n",
adpt->netdev->name, status & ISR_ERROR);
/* reset MAC */
schedule_work(&adpt->work_thread);
}
/* Schedule the napi for receive queue with interrupt
* status bit set
*/
if (status & rx_q->intr) {
if (napi_schedule_prep(&rx_q->napi)) {
irq->mask &= ~rx_q->intr;
__napi_schedule(&rx_q->napi);
}
}
if (status & TX_PKT_INT)
emac_mac_tx_process(adpt, &adpt->tx_q);
if (status & ISR_OVER)
net_warn_ratelimited("%s: TX/RX overflow interrupt\n",
adpt->netdev->name);
exit:
/* enable the interrupt */
writel(irq->mask, adpt->base + EMAC_INT_MASK);
return IRQ_HANDLED;
}
/* Configure VLAN tag strip/insert feature */
static int emac_set_features(struct net_device *netdev,
netdev_features_t features)
{
netdev_features_t changed = features ^ netdev->features;
struct emac_adapter *adpt = netdev_priv(netdev);
/* We only need to reprogram the hardware if the VLAN tag features
* have changed, and if it's already running.
*/
if (!(changed & (NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX)))
return 0;
if (!netif_running(netdev))
return 0;
/* emac_mac_mode_config() uses netdev->features to configure the EMAC,
* so make sure it's set first.
*/
netdev->features = features;
return emac_reinit_locked(adpt);
}
/* Configure Multicast and Promiscuous modes */
static void emac_rx_mode_set(struct net_device *netdev)
{
struct emac_adapter *adpt = netdev_priv(netdev);
struct netdev_hw_addr *ha;
emac_mac_mode_config(adpt);
/* update multicast address filtering */
emac_mac_multicast_addr_clear(adpt);
netdev_for_each_mc_addr(ha, netdev)
emac_mac_multicast_addr_set(adpt, ha->addr);
}
/* Change the Maximum Transfer Unit (MTU) */
static int emac_change_mtu(struct net_device *netdev, int new_mtu)
{
struct emac_adapter *adpt = netdev_priv(netdev);
netif_dbg(adpt, hw, adpt->netdev,
"changing MTU from %d to %d\n", netdev->mtu,
new_mtu);
netdev->mtu = new_mtu;
if (netif_running(netdev))
return emac_reinit_locked(adpt);
return 0;
}
/* Called when the network interface is made active */
static int emac_open(struct net_device *netdev)
{
struct emac_adapter *adpt = netdev_priv(netdev);
struct emac_irq *irq = &adpt->irq;
int ret;
ret = request_irq(irq->irq, emac_isr, 0, "emac-core0", irq);
if (ret) {
netdev_err(adpt->netdev, "could not request emac-core0 irq\n");
return ret;
}
/* allocate rx/tx dma buffer & descriptors */
ret = emac_mac_rx_tx_rings_alloc_all(adpt);
if (ret) {
netdev_err(adpt->netdev, "error allocating rx/tx rings\n");
free_irq(irq->irq, irq);
return ret;
}
ret = emac_sgmii_open(adpt);
if (ret) {
emac_mac_rx_tx_rings_free_all(adpt);
free_irq(irq->irq, irq);
return ret;
}
ret = emac_mac_up(adpt);
if (ret) {
emac_mac_rx_tx_rings_free_all(adpt);
free_irq(irq->irq, irq);
emac_sgmii_close(adpt);
return ret;
}
return 0;
}
/* Called when the network interface is disabled */
static int emac_close(struct net_device *netdev)
{
struct emac_adapter *adpt = netdev_priv(netdev);
mutex_lock(&adpt->reset_lock);
emac_sgmii_close(adpt);
emac_mac_down(adpt);
emac_mac_rx_tx_rings_free_all(adpt);
free_irq(adpt->irq.irq, &adpt->irq);
mutex_unlock(&adpt->reset_lock);
return 0;
}
/* Respond to a TX hang */
static void emac_tx_timeout(struct net_device *netdev, unsigned int txqueue)
{
struct emac_adapter *adpt = netdev_priv(netdev);
schedule_work(&adpt->work_thread);
}
/**
* emac_update_hw_stats - read the EMAC stat registers
* @adpt: pointer to adapter struct
*
* Reads the stats registers and write the values to adpt->stats.
*
* adpt->stats.lock must be held while calling this function,
* and while reading from adpt->stats.
*/
void emac_update_hw_stats(struct emac_adapter *adpt)
{
struct emac_stats *stats = &adpt->stats;
u64 *stats_itr = &adpt->stats.rx_ok;
void __iomem *base = adpt->base;
unsigned int addr;
addr = REG_MAC_RX_STATUS_BIN;
while (addr <= REG_MAC_RX_STATUS_END) {
*stats_itr += readl_relaxed(base + addr);
stats_itr++;
addr += sizeof(u32);
}
/* additional rx status */
stats->rx_crc_align += readl_relaxed(base + EMAC_RXMAC_STATC_REG23);
stats->rx_jabbers += readl_relaxed(base + EMAC_RXMAC_STATC_REG24);
/* update tx status */
addr = REG_MAC_TX_STATUS_BIN;
stats_itr = &stats->tx_ok;
while (addr <= REG_MAC_TX_STATUS_END) {
*stats_itr += readl_relaxed(base + addr);
stats_itr++;
addr += sizeof(u32);
}
/* additional tx status */
stats->tx_col += readl_relaxed(base + EMAC_TXMAC_STATC_REG25);
}
/* Provide network statistics info for the interface */
static void emac_get_stats64(struct net_device *netdev,
struct rtnl_link_stats64 *net_stats)
{
struct emac_adapter *adpt = netdev_priv(netdev);
struct emac_stats *stats = &adpt->stats;
spin_lock(&stats->lock);
emac_update_hw_stats(adpt);
/* return parsed statistics */
net_stats->rx_packets = stats->rx_ok;
net_stats->tx_packets = stats->tx_ok;
net_stats->rx_bytes = stats->rx_byte_cnt;
net_stats->tx_bytes = stats->tx_byte_cnt;
net_stats->multicast = stats->rx_mcast;
net_stats->collisions = stats->tx_1_col + stats->tx_2_col * 2 +
stats->tx_late_col + stats->tx_abort_col;
net_stats->rx_errors = stats->rx_frag + stats->rx_fcs_err +
stats->rx_len_err + stats->rx_sz_ov +
stats->rx_align_err;
net_stats->rx_fifo_errors = stats->rx_rxf_ov;
net_stats->rx_length_errors = stats->rx_len_err;
net_stats->rx_crc_errors = stats->rx_fcs_err;
net_stats->rx_frame_errors = stats->rx_align_err;
net_stats->rx_over_errors = stats->rx_rxf_ov;
net_stats->rx_missed_errors = stats->rx_rxf_ov;
net_stats->tx_errors = stats->tx_late_col + stats->tx_abort_col +
stats->tx_underrun + stats->tx_trunc;
net_stats->tx_fifo_errors = stats->tx_underrun;
net_stats->tx_aborted_errors = stats->tx_abort_col;
net_stats->tx_window_errors = stats->tx_late_col;
spin_unlock(&stats->lock);
}
static const struct net_device_ops emac_netdev_ops = {
.ndo_open = emac_open,
.ndo_stop = emac_close,
.ndo_validate_addr = eth_validate_addr,
.ndo_start_xmit = emac_start_xmit,
.ndo_set_mac_address = eth_mac_addr,
.ndo_change_mtu = emac_change_mtu,
.ndo_eth_ioctl = phy_do_ioctl_running,
.ndo_tx_timeout = emac_tx_timeout,
.ndo_get_stats64 = emac_get_stats64,
.ndo_set_features = emac_set_features,
.ndo_set_rx_mode = emac_rx_mode_set,
};
/* Watchdog task routine, called to reinitialize the EMAC */
static void emac_work_thread(struct work_struct *work)
{
struct emac_adapter *adpt =
container_of(work, struct emac_adapter, work_thread);
emac_reinit_locked(adpt);
}
/* Initialize various data structures */
static void emac_init_adapter(struct emac_adapter *adpt)
{
u32 reg;
adpt->rrd_size = EMAC_RRD_SIZE;
adpt->tpd_size = EMAC_TPD_SIZE;
adpt->rfd_size = EMAC_RFD_SIZE;
/* descriptors */
adpt->tx_desc_cnt = EMAC_DEF_TX_DESCS;
adpt->rx_desc_cnt = EMAC_DEF_RX_DESCS;
/* dma */
adpt->dma_order = emac_dma_ord_out;
adpt->dmar_block = emac_dma_req_4096;
adpt->dmaw_block = emac_dma_req_128;
adpt->dmar_dly_cnt = DMAR_DLY_CNT_DEF;
adpt->dmaw_dly_cnt = DMAW_DLY_CNT_DEF;
adpt->tpd_burst = TXQ0_NUM_TPD_PREF_DEF;
adpt->rfd_burst = RXQ0_NUM_RFD_PREF_DEF;
/* irq moderator */
reg = ((EMAC_DEF_RX_IRQ_MOD >> 1) << IRQ_MODERATOR2_INIT_SHFT) |
((EMAC_DEF_TX_IRQ_MOD >> 1) << IRQ_MODERATOR_INIT_SHFT);
adpt->irq_mod = reg;
/* others */
adpt->preamble = EMAC_PREAMBLE_DEF;
/* default to automatic flow control */
adpt->automatic = true;
/* Disable single-pause-frame mode by default */
adpt->single_pause_mode = false;
}
/* Get the clock */
static int emac_clks_get(struct platform_device *pdev,
struct emac_adapter *adpt)
{
unsigned int i;
for (i = 0; i < EMAC_CLK_CNT; i++) {
struct clk *clk = devm_clk_get(&pdev->dev, emac_clk_name[i]);
if (IS_ERR(clk)) {
dev_err(&pdev->dev,
"could not claim clock %s (error=%li)\n",
emac_clk_name[i], PTR_ERR(clk));
return PTR_ERR(clk);
}
adpt->clk[i] = clk;
}
return 0;
}
/* Initialize clocks */
static int emac_clks_phase1_init(struct platform_device *pdev,
struct emac_adapter *adpt)
{
int ret;
/* On ACPI platforms, clocks are controlled by firmware and/or
* ACPI, not by drivers.
*/
if (has_acpi_companion(&pdev->dev))
return 0;
ret = emac_clks_get(pdev, adpt);
if (ret)
return ret;
ret = clk_prepare_enable(adpt->clk[EMAC_CLK_AXI]);
if (ret)
return ret;
ret = clk_prepare_enable(adpt->clk[EMAC_CLK_CFG_AHB]);
if (ret)
goto disable_clk_axi;
ret = clk_set_rate(adpt->clk[EMAC_CLK_HIGH_SPEED], 19200000);
if (ret)
goto disable_clk_cfg_ahb;
ret = clk_prepare_enable(adpt->clk[EMAC_CLK_HIGH_SPEED]);
if (ret)
goto disable_clk_cfg_ahb;
return 0;
disable_clk_cfg_ahb:
clk_disable_unprepare(adpt->clk[EMAC_CLK_CFG_AHB]);
disable_clk_axi:
clk_disable_unprepare(adpt->clk[EMAC_CLK_AXI]);
return ret;
}
/* Enable clocks; needs emac_clks_phase1_init to be called before */
static int emac_clks_phase2_init(struct platform_device *pdev,
struct emac_adapter *adpt)
{
int ret;
if (has_acpi_companion(&pdev->dev))
return 0;
ret = clk_set_rate(adpt->clk[EMAC_CLK_TX], 125000000);
if (ret)
return ret;
ret = clk_prepare_enable(adpt->clk[EMAC_CLK_TX]);
if (ret)
return ret;
ret = clk_set_rate(adpt->clk[EMAC_CLK_HIGH_SPEED], 125000000);
if (ret)
return ret;
ret = clk_set_rate(adpt->clk[EMAC_CLK_MDIO], 25000000);
if (ret)
return ret;
ret = clk_prepare_enable(adpt->clk[EMAC_CLK_MDIO]);
if (ret)
return ret;
ret = clk_prepare_enable(adpt->clk[EMAC_CLK_RX]);
if (ret)
return ret;
return clk_prepare_enable(adpt->clk[EMAC_CLK_SYS]);
}
static void emac_clks_teardown(struct emac_adapter *adpt)
{
unsigned int i;
for (i = 0; i < EMAC_CLK_CNT; i++)
clk_disable_unprepare(adpt->clk[i]);
}
/* Get the resources */
static int emac_probe_resources(struct platform_device *pdev,
struct emac_adapter *adpt)
{
struct net_device *netdev = adpt->netdev;
int ret = 0;
/* get mac address */
if (device_get_ethdev_address(&pdev->dev, netdev))
eth_hw_addr_random(netdev);
/* Core 0 interrupt */
ret = platform_get_irq(pdev, 0);
if (ret < 0)
return ret;
adpt->irq.irq = ret;
/* base register address */
adpt->base = devm_platform_ioremap_resource(pdev, 0);
if (IS_ERR(adpt->base))
return PTR_ERR(adpt->base);
/* CSR register address */
adpt->csr = devm_platform_ioremap_resource(pdev, 1);
if (IS_ERR(adpt->csr))
return PTR_ERR(adpt->csr);
netdev->base_addr = (unsigned long)adpt->base;
return 0;
}
static const struct of_device_id emac_dt_match[] = {
{
.compatible = "qcom,fsm9900-emac",
},
{}
};
MODULE_DEVICE_TABLE(of, emac_dt_match);
#if IS_ENABLED(CONFIG_ACPI)
static const struct acpi_device_id emac_acpi_match[] = {
{
.id = "QCOM8070",
},
{}
};
MODULE_DEVICE_TABLE(acpi, emac_acpi_match);
#endif
static int emac_probe(struct platform_device *pdev)
{
struct net_device *netdev;
struct emac_adapter *adpt;
struct emac_sgmii *phy;
u16 devid, revid;
u32 reg;
int ret;
/* The TPD buffer address is limited to:
* 1. PTP: 45bits. (Driver doesn't support yet.)
* 2. NON-PTP: 46bits.
*/
ret = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(46));
if (ret) {
dev_err(&pdev->dev, "could not set DMA mask\n");
return ret;
}
netdev = alloc_etherdev(sizeof(struct emac_adapter));
if (!netdev)
return -ENOMEM;
dev_set_drvdata(&pdev->dev, netdev);
SET_NETDEV_DEV(netdev, &pdev->dev);
emac_set_ethtool_ops(netdev);
adpt = netdev_priv(netdev);
adpt->netdev = netdev;
adpt->msg_enable = EMAC_MSG_DEFAULT;
phy = &adpt->phy;
atomic_set(&phy->decode_error_count, 0);
mutex_init(&adpt->reset_lock);
spin_lock_init(&adpt->stats.lock);
adpt->irq.mask = RX_PKT_INT0 | IMR_NORMAL_MASK;
ret = emac_probe_resources(pdev, adpt);
if (ret)
goto err_undo_netdev;
/* initialize clocks */
ret = emac_clks_phase1_init(pdev, adpt);
if (ret) {
dev_err(&pdev->dev, "could not initialize clocks\n");
goto err_undo_netdev;
}
netdev->watchdog_timeo = EMAC_WATCHDOG_TIME;
netdev->irq = adpt->irq.irq;
netdev->netdev_ops = &emac_netdev_ops;
emac_init_adapter(adpt);
/* init external phy */
ret = emac_phy_config(pdev, adpt);
if (ret)
goto err_undo_clocks;
/* init internal sgmii phy */
ret = emac_sgmii_config(pdev, adpt);
if (ret)
goto err_undo_mdiobus;
/* enable clocks */
ret = emac_clks_phase2_init(pdev, adpt);
if (ret) {
dev_err(&pdev->dev, "could not initialize clocks\n");
goto err_undo_mdiobus;
}
/* set hw features */
netdev->features = NETIF_F_SG | NETIF_F_HW_CSUM | NETIF_F_RXCSUM |
NETIF_F_TSO | NETIF_F_TSO6 | NETIF_F_HW_VLAN_CTAG_RX |
NETIF_F_HW_VLAN_CTAG_TX;
netdev->hw_features = netdev->features;
netdev->vlan_features |= NETIF_F_SG | NETIF_F_HW_CSUM |
NETIF_F_TSO | NETIF_F_TSO6;
/* MTU range: 46 - 9194 */
netdev->min_mtu = EMAC_MIN_ETH_FRAME_SIZE -
(ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN);
netdev->max_mtu = EMAC_MAX_ETH_FRAME_SIZE -
(ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN);
INIT_WORK(&adpt->work_thread, emac_work_thread);
/* Initialize queues */
emac_mac_rx_tx_ring_init_all(pdev, adpt);
netif_napi_add(netdev, &adpt->rx_q.napi, emac_napi_rtx);
ret = register_netdev(netdev);
if (ret) {
dev_err(&pdev->dev, "could not register net device\n");
goto err_undo_napi;
}
reg = readl_relaxed(adpt->base + EMAC_DMA_MAS_CTRL);
devid = (reg & DEV_ID_NUM_BMSK) >> DEV_ID_NUM_SHFT;
revid = (reg & DEV_REV_NUM_BMSK) >> DEV_REV_NUM_SHFT;
reg = readl_relaxed(adpt->base + EMAC_CORE_HW_VERSION);
netif_info(adpt, probe, netdev,
"hardware id %d.%d, hardware version %d.%d.%d\n",
devid, revid,
(reg & MAJOR_BMSK) >> MAJOR_SHFT,
(reg & MINOR_BMSK) >> MINOR_SHFT,
(reg & STEP_BMSK) >> STEP_SHFT);
return 0;
err_undo_napi:
netif_napi_del(&adpt->rx_q.napi);
err_undo_mdiobus:
put_device(&adpt->phydev->mdio.dev);
mdiobus_unregister(adpt->mii_bus);
err_undo_clocks:
emac_clks_teardown(adpt);
err_undo_netdev:
free_netdev(netdev);
return ret;
}
static int emac_remove(struct platform_device *pdev)
{
struct net_device *netdev = dev_get_drvdata(&pdev->dev);
struct emac_adapter *adpt = netdev_priv(netdev);
netif_carrier_off(netdev);
netif_tx_disable(netdev);
unregister_netdev(netdev);
netif_napi_del(&adpt->rx_q.napi);
free_irq(adpt->irq.irq, &adpt->irq);
cancel_work_sync(&adpt->work_thread);
emac_clks_teardown(adpt);
put_device(&adpt->phydev->mdio.dev);
mdiobus_unregister(adpt->mii_bus);
if (adpt->phy.digital)
iounmap(adpt->phy.digital);
iounmap(adpt->phy.base);
free_netdev(netdev);
return 0;
}
static void emac_shutdown(struct platform_device *pdev)
{
struct net_device *netdev = dev_get_drvdata(&pdev->dev);
struct emac_adapter *adpt = netdev_priv(netdev);
if (netdev->flags & IFF_UP) {
/* Closing the SGMII turns off its interrupts */
emac_sgmii_close(adpt);
/* Resetting the MAC turns off all DMA and its interrupts */
emac_mac_reset(adpt);
}
}
static struct platform_driver emac_platform_driver = {
.probe = emac_probe,
.remove = emac_remove,
.driver = {
.name = "qcom-emac",
.of_match_table = emac_dt_match,
.acpi_match_table = ACPI_PTR(emac_acpi_match),
},
.shutdown = emac_shutdown,
};
module_platform_driver(emac_platform_driver);
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:qcom-emac");
|
linux-master
|
drivers/net/ethernet/qualcomm/emac/emac.c
|
// SPDX-License-Identifier: GPL-2.0-only
/* Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
*/
/* Qualcomm Technologies, Inc. EMAC Ethernet Controller MAC layer support
*/
#include <linux/tcp.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/crc32.h>
#include <linux/if_vlan.h>
#include <linux/jiffies.h>
#include <linux/phy.h>
#include <linux/of.h>
#include <net/ip6_checksum.h>
#include "emac.h"
#include "emac-sgmii.h"
/* EMAC_MAC_CTRL */
#define SINGLE_PAUSE_MODE 0x10000000
#define DEBUG_MODE 0x08000000
#define BROAD_EN 0x04000000
#define MULTI_ALL 0x02000000
#define RX_CHKSUM_EN 0x01000000
#define HUGE 0x00800000
#define SPEED(x) (((x) & 0x3) << 20)
#define SPEED_MASK SPEED(0x3)
#define SIMR 0x00080000
#define TPAUSE 0x00010000
#define PROM_MODE 0x00008000
#define VLAN_STRIP 0x00004000
#define PRLEN_BMSK 0x00003c00
#define PRLEN_SHFT 10
#define HUGEN 0x00000200
#define FLCHK 0x00000100
#define PCRCE 0x00000080
#define CRCE 0x00000040
#define FULLD 0x00000020
#define MAC_LP_EN 0x00000010
#define RXFC 0x00000008
#define TXFC 0x00000004
#define RXEN 0x00000002
#define TXEN 0x00000001
/* EMAC_DESC_CTRL_3 */
#define RFD_RING_SIZE_BMSK 0xfff
/* EMAC_DESC_CTRL_4 */
#define RX_BUFFER_SIZE_BMSK 0xffff
/* EMAC_DESC_CTRL_6 */
#define RRD_RING_SIZE_BMSK 0xfff
/* EMAC_DESC_CTRL_9 */
#define TPD_RING_SIZE_BMSK 0xffff
/* EMAC_TXQ_CTRL_0 */
#define NUM_TXF_BURST_PREF_BMSK 0xffff0000
#define NUM_TXF_BURST_PREF_SHFT 16
#define LS_8023_SP 0x80
#define TXQ_MODE 0x40
#define TXQ_EN 0x20
#define IP_OP_SP 0x10
#define NUM_TPD_BURST_PREF_BMSK 0xf
#define NUM_TPD_BURST_PREF_SHFT 0
/* EMAC_TXQ_CTRL_1 */
#define JUMBO_TASK_OFFLOAD_THRESHOLD_BMSK 0x7ff
/* EMAC_TXQ_CTRL_2 */
#define TXF_HWM_BMSK 0xfff0000
#define TXF_LWM_BMSK 0xfff
/* EMAC_RXQ_CTRL_0 */
#define RXQ_EN BIT(31)
#define CUT_THRU_EN BIT(30)
#define RSS_HASH_EN BIT(29)
#define NUM_RFD_BURST_PREF_BMSK 0x3f00000
#define NUM_RFD_BURST_PREF_SHFT 20
#define IDT_TABLE_SIZE_BMSK 0x1ff00
#define IDT_TABLE_SIZE_SHFT 8
#define SP_IPV6 0x80
/* EMAC_RXQ_CTRL_1 */
#define JUMBO_1KAH_BMSK 0xf000
#define JUMBO_1KAH_SHFT 12
#define RFD_PREF_LOW_TH 0x10
#define RFD_PREF_LOW_THRESHOLD_BMSK 0xfc0
#define RFD_PREF_LOW_THRESHOLD_SHFT 6
#define RFD_PREF_UP_TH 0x10
#define RFD_PREF_UP_THRESHOLD_BMSK 0x3f
#define RFD_PREF_UP_THRESHOLD_SHFT 0
/* EMAC_RXQ_CTRL_2 */
#define RXF_DOF_THRESFHOLD 0x1a0
#define RXF_DOF_THRESHOLD_BMSK 0xfff0000
#define RXF_DOF_THRESHOLD_SHFT 16
#define RXF_UOF_THRESFHOLD 0xbe
#define RXF_UOF_THRESHOLD_BMSK 0xfff
#define RXF_UOF_THRESHOLD_SHFT 0
/* EMAC_RXQ_CTRL_3 */
#define RXD_TIMER_BMSK 0xffff0000
#define RXD_THRESHOLD_BMSK 0xfff
#define RXD_THRESHOLD_SHFT 0
/* EMAC_DMA_CTRL */
#define DMAW_DLY_CNT_BMSK 0xf0000
#define DMAW_DLY_CNT_SHFT 16
#define DMAR_DLY_CNT_BMSK 0xf800
#define DMAR_DLY_CNT_SHFT 11
#define DMAR_REQ_PRI 0x400
#define REGWRBLEN_BMSK 0x380
#define REGWRBLEN_SHFT 7
#define REGRDBLEN_BMSK 0x70
#define REGRDBLEN_SHFT 4
#define OUT_ORDER_MODE 0x4
#define ENH_ORDER_MODE 0x2
#define IN_ORDER_MODE 0x1
/* EMAC_MAILBOX_13 */
#define RFD3_PROC_IDX_BMSK 0xfff0000
#define RFD3_PROC_IDX_SHFT 16
#define RFD3_PROD_IDX_BMSK 0xfff
#define RFD3_PROD_IDX_SHFT 0
/* EMAC_MAILBOX_2 */
#define NTPD_CONS_IDX_BMSK 0xffff0000
#define NTPD_CONS_IDX_SHFT 16
/* EMAC_MAILBOX_3 */
#define RFD0_CONS_IDX_BMSK 0xfff
#define RFD0_CONS_IDX_SHFT 0
/* EMAC_MAILBOX_11 */
#define H3TPD_PROD_IDX_BMSK 0xffff0000
#define H3TPD_PROD_IDX_SHFT 16
/* EMAC_AXI_MAST_CTRL */
#define DATA_BYTE_SWAP 0x8
#define MAX_BOUND 0x2
#define MAX_BTYPE 0x1
/* EMAC_MAILBOX_12 */
#define H3TPD_CONS_IDX_BMSK 0xffff0000
#define H3TPD_CONS_IDX_SHFT 16
/* EMAC_MAILBOX_9 */
#define H2TPD_PROD_IDX_BMSK 0xffff
#define H2TPD_PROD_IDX_SHFT 0
/* EMAC_MAILBOX_10 */
#define H1TPD_CONS_IDX_BMSK 0xffff0000
#define H1TPD_CONS_IDX_SHFT 16
#define H2TPD_CONS_IDX_BMSK 0xffff
#define H2TPD_CONS_IDX_SHFT 0
/* EMAC_ATHR_HEADER_CTRL */
#define HEADER_CNT_EN 0x2
#define HEADER_ENABLE 0x1
/* EMAC_MAILBOX_0 */
#define RFD0_PROC_IDX_BMSK 0xfff0000
#define RFD0_PROC_IDX_SHFT 16
#define RFD0_PROD_IDX_BMSK 0xfff
#define RFD0_PROD_IDX_SHFT 0
/* EMAC_MAILBOX_5 */
#define RFD1_PROC_IDX_BMSK 0xfff0000
#define RFD1_PROC_IDX_SHFT 16
#define RFD1_PROD_IDX_BMSK 0xfff
#define RFD1_PROD_IDX_SHFT 0
/* EMAC_MISC_CTRL */
#define RX_UNCPL_INT_EN 0x1
/* EMAC_MAILBOX_7 */
#define RFD2_CONS_IDX_BMSK 0xfff0000
#define RFD2_CONS_IDX_SHFT 16
#define RFD1_CONS_IDX_BMSK 0xfff
#define RFD1_CONS_IDX_SHFT 0
/* EMAC_MAILBOX_8 */
#define RFD3_CONS_IDX_BMSK 0xfff
#define RFD3_CONS_IDX_SHFT 0
/* EMAC_MAILBOX_15 */
#define NTPD_PROD_IDX_BMSK 0xffff
#define NTPD_PROD_IDX_SHFT 0
/* EMAC_MAILBOX_16 */
#define H1TPD_PROD_IDX_BMSK 0xffff
#define H1TPD_PROD_IDX_SHFT 0
#define RXQ0_RSS_HSTYP_IPV6_TCP_EN 0x20
#define RXQ0_RSS_HSTYP_IPV6_EN 0x10
#define RXQ0_RSS_HSTYP_IPV4_TCP_EN 0x8
#define RXQ0_RSS_HSTYP_IPV4_EN 0x4
/* EMAC_EMAC_WRAPPER_TX_TS_INX */
#define EMAC_WRAPPER_TX_TS_EMPTY BIT(31)
#define EMAC_WRAPPER_TX_TS_INX_BMSK 0xffff
struct emac_skb_cb {
u32 tpd_idx;
unsigned long jiffies;
};
#define EMAC_SKB_CB(skb) ((struct emac_skb_cb *)(skb)->cb)
#define EMAC_RSS_IDT_SIZE 256
#define JUMBO_1KAH 0x4
#define RXD_TH 0x100
#define EMAC_TPD_LAST_FRAGMENT 0x80000000
#define EMAC_TPD_TSTAMP_SAVE 0x80000000
/* EMAC Errors in emac_rrd.word[3] */
#define EMAC_RRD_L4F BIT(14)
#define EMAC_RRD_IPF BIT(15)
#define EMAC_RRD_CRC BIT(21)
#define EMAC_RRD_FAE BIT(22)
#define EMAC_RRD_TRN BIT(23)
#define EMAC_RRD_RNT BIT(24)
#define EMAC_RRD_INC BIT(25)
#define EMAC_RRD_FOV BIT(29)
#define EMAC_RRD_LEN BIT(30)
/* Error bits that will result in a received frame being discarded */
#define EMAC_RRD_ERROR (EMAC_RRD_IPF | EMAC_RRD_CRC | EMAC_RRD_FAE | \
EMAC_RRD_TRN | EMAC_RRD_RNT | EMAC_RRD_INC | \
EMAC_RRD_FOV | EMAC_RRD_LEN)
#define EMAC_RRD_STATS_DW_IDX 3
#define EMAC_RRD(RXQ, SIZE, IDX) ((RXQ)->rrd.v_addr + (SIZE * (IDX)))
#define EMAC_RFD(RXQ, SIZE, IDX) ((RXQ)->rfd.v_addr + (SIZE * (IDX)))
#define EMAC_TPD(TXQ, SIZE, IDX) ((TXQ)->tpd.v_addr + (SIZE * (IDX)))
#define GET_RFD_BUFFER(RXQ, IDX) (&((RXQ)->rfd.rfbuff[(IDX)]))
#define GET_TPD_BUFFER(RTQ, IDX) (&((RTQ)->tpd.tpbuff[(IDX)]))
#define EMAC_TX_POLL_HWTXTSTAMP_THRESHOLD 8
#define ISR_RX_PKT (\
RX_PKT_INT0 |\
RX_PKT_INT1 |\
RX_PKT_INT2 |\
RX_PKT_INT3)
void emac_mac_multicast_addr_set(struct emac_adapter *adpt, u8 *addr)
{
u32 crc32, bit, reg, mta;
/* Calculate the CRC of the MAC address */
crc32 = ether_crc(ETH_ALEN, addr);
/* The HASH Table is an array of 2 32-bit registers. It is
* treated like an array of 64 bits (BitArray[hash_value]).
* Use the upper 6 bits of the above CRC as the hash value.
*/
reg = (crc32 >> 31) & 0x1;
bit = (crc32 >> 26) & 0x1F;
mta = readl(adpt->base + EMAC_HASH_TAB_REG0 + (reg << 2));
mta |= BIT(bit);
writel(mta, adpt->base + EMAC_HASH_TAB_REG0 + (reg << 2));
}
void emac_mac_multicast_addr_clear(struct emac_adapter *adpt)
{
writel(0, adpt->base + EMAC_HASH_TAB_REG0);
writel(0, adpt->base + EMAC_HASH_TAB_REG1);
}
/* definitions for RSS */
#define EMAC_RSS_KEY(_i, _type) \
(EMAC_RSS_KEY0 + ((_i) * sizeof(_type)))
#define EMAC_RSS_TBL(_i, _type) \
(EMAC_IDT_TABLE0 + ((_i) * sizeof(_type)))
/* Config MAC modes */
void emac_mac_mode_config(struct emac_adapter *adpt)
{
struct net_device *netdev = adpt->netdev;
u32 mac;
mac = readl(adpt->base + EMAC_MAC_CTRL);
mac &= ~(VLAN_STRIP | PROM_MODE | MULTI_ALL | MAC_LP_EN);
if (netdev->features & NETIF_F_HW_VLAN_CTAG_RX)
mac |= VLAN_STRIP;
if (netdev->flags & IFF_PROMISC)
mac |= PROM_MODE;
if (netdev->flags & IFF_ALLMULTI)
mac |= MULTI_ALL;
writel(mac, adpt->base + EMAC_MAC_CTRL);
}
/* Config descriptor rings */
static void emac_mac_dma_rings_config(struct emac_adapter *adpt)
{
/* TPD (Transmit Packet Descriptor) */
writel(upper_32_bits(adpt->tx_q.tpd.dma_addr),
adpt->base + EMAC_DESC_CTRL_1);
writel(lower_32_bits(adpt->tx_q.tpd.dma_addr),
adpt->base + EMAC_DESC_CTRL_8);
writel(adpt->tx_q.tpd.count & TPD_RING_SIZE_BMSK,
adpt->base + EMAC_DESC_CTRL_9);
/* RFD (Receive Free Descriptor) & RRD (Receive Return Descriptor) */
writel(upper_32_bits(adpt->rx_q.rfd.dma_addr),
adpt->base + EMAC_DESC_CTRL_0);
writel(lower_32_bits(adpt->rx_q.rfd.dma_addr),
adpt->base + EMAC_DESC_CTRL_2);
writel(lower_32_bits(adpt->rx_q.rrd.dma_addr),
adpt->base + EMAC_DESC_CTRL_5);
writel(adpt->rx_q.rfd.count & RFD_RING_SIZE_BMSK,
adpt->base + EMAC_DESC_CTRL_3);
writel(adpt->rx_q.rrd.count & RRD_RING_SIZE_BMSK,
adpt->base + EMAC_DESC_CTRL_6);
writel(adpt->rxbuf_size & RX_BUFFER_SIZE_BMSK,
adpt->base + EMAC_DESC_CTRL_4);
writel(0, adpt->base + EMAC_DESC_CTRL_11);
/* Load all of the base addresses above and ensure that triggering HW to
* read ring pointers is flushed
*/
writel(1, adpt->base + EMAC_INTER_SRAM_PART9);
}
/* Config transmit parameters */
static void emac_mac_tx_config(struct emac_adapter *adpt)
{
u32 val;
writel((EMAC_MAX_TX_OFFLOAD_THRESH >> 3) &
JUMBO_TASK_OFFLOAD_THRESHOLD_BMSK, adpt->base + EMAC_TXQ_CTRL_1);
val = (adpt->tpd_burst << NUM_TPD_BURST_PREF_SHFT) &
NUM_TPD_BURST_PREF_BMSK;
val |= TXQ_MODE | LS_8023_SP;
val |= (0x0100 << NUM_TXF_BURST_PREF_SHFT) &
NUM_TXF_BURST_PREF_BMSK;
writel(val, adpt->base + EMAC_TXQ_CTRL_0);
emac_reg_update32(adpt->base + EMAC_TXQ_CTRL_2,
(TXF_HWM_BMSK | TXF_LWM_BMSK), 0);
}
/* Config receive parameters */
static void emac_mac_rx_config(struct emac_adapter *adpt)
{
u32 val;
val = (adpt->rfd_burst << NUM_RFD_BURST_PREF_SHFT) &
NUM_RFD_BURST_PREF_BMSK;
val |= (SP_IPV6 | CUT_THRU_EN);
writel(val, adpt->base + EMAC_RXQ_CTRL_0);
val = readl(adpt->base + EMAC_RXQ_CTRL_1);
val &= ~(JUMBO_1KAH_BMSK | RFD_PREF_LOW_THRESHOLD_BMSK |
RFD_PREF_UP_THRESHOLD_BMSK);
val |= (JUMBO_1KAH << JUMBO_1KAH_SHFT) |
(RFD_PREF_LOW_TH << RFD_PREF_LOW_THRESHOLD_SHFT) |
(RFD_PREF_UP_TH << RFD_PREF_UP_THRESHOLD_SHFT);
writel(val, adpt->base + EMAC_RXQ_CTRL_1);
val = readl(adpt->base + EMAC_RXQ_CTRL_2);
val &= ~(RXF_DOF_THRESHOLD_BMSK | RXF_UOF_THRESHOLD_BMSK);
val |= (RXF_DOF_THRESFHOLD << RXF_DOF_THRESHOLD_SHFT) |
(RXF_UOF_THRESFHOLD << RXF_UOF_THRESHOLD_SHFT);
writel(val, adpt->base + EMAC_RXQ_CTRL_2);
val = readl(adpt->base + EMAC_RXQ_CTRL_3);
val &= ~(RXD_TIMER_BMSK | RXD_THRESHOLD_BMSK);
val |= RXD_TH << RXD_THRESHOLD_SHFT;
writel(val, adpt->base + EMAC_RXQ_CTRL_3);
}
/* Config dma */
static void emac_mac_dma_config(struct emac_adapter *adpt)
{
u32 dma_ctrl = DMAR_REQ_PRI;
switch (adpt->dma_order) {
case emac_dma_ord_in:
dma_ctrl |= IN_ORDER_MODE;
break;
case emac_dma_ord_enh:
dma_ctrl |= ENH_ORDER_MODE;
break;
case emac_dma_ord_out:
dma_ctrl |= OUT_ORDER_MODE;
break;
default:
break;
}
dma_ctrl |= (((u32)adpt->dmar_block) << REGRDBLEN_SHFT) &
REGRDBLEN_BMSK;
dma_ctrl |= (((u32)adpt->dmaw_block) << REGWRBLEN_SHFT) &
REGWRBLEN_BMSK;
dma_ctrl |= (((u32)adpt->dmar_dly_cnt) << DMAR_DLY_CNT_SHFT) &
DMAR_DLY_CNT_BMSK;
dma_ctrl |= (((u32)adpt->dmaw_dly_cnt) << DMAW_DLY_CNT_SHFT) &
DMAW_DLY_CNT_BMSK;
/* config DMA and ensure that configuration is flushed to HW */
writel(dma_ctrl, adpt->base + EMAC_DMA_CTRL);
}
/* set MAC address */
static void emac_set_mac_address(struct emac_adapter *adpt, const u8 *addr)
{
u32 sta;
/* for example: 00-A0-C6-11-22-33
* 0<-->C6112233, 1<-->00A0.
*/
/* low 32bit word */
sta = (((u32)addr[2]) << 24) | (((u32)addr[3]) << 16) |
(((u32)addr[4]) << 8) | (((u32)addr[5]));
writel(sta, adpt->base + EMAC_MAC_STA_ADDR0);
/* hight 32bit word */
sta = (((u32)addr[0]) << 8) | (u32)addr[1];
writel(sta, adpt->base + EMAC_MAC_STA_ADDR1);
}
static void emac_mac_config(struct emac_adapter *adpt)
{
struct net_device *netdev = adpt->netdev;
unsigned int max_frame;
u32 val;
emac_set_mac_address(adpt, netdev->dev_addr);
max_frame = netdev->mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN;
adpt->rxbuf_size = netdev->mtu > EMAC_DEF_RX_BUF_SIZE ?
ALIGN(max_frame, 8) : EMAC_DEF_RX_BUF_SIZE;
emac_mac_dma_rings_config(adpt);
writel(netdev->mtu + ETH_HLEN + VLAN_HLEN + ETH_FCS_LEN,
adpt->base + EMAC_MAX_FRAM_LEN_CTRL);
emac_mac_tx_config(adpt);
emac_mac_rx_config(adpt);
emac_mac_dma_config(adpt);
val = readl(adpt->base + EMAC_AXI_MAST_CTRL);
val &= ~(DATA_BYTE_SWAP | MAX_BOUND);
val |= MAX_BTYPE;
writel(val, adpt->base + EMAC_AXI_MAST_CTRL);
writel(0, adpt->base + EMAC_CLK_GATE_CTRL);
writel(RX_UNCPL_INT_EN, adpt->base + EMAC_MISC_CTRL);
}
void emac_mac_reset(struct emac_adapter *adpt)
{
emac_mac_stop(adpt);
emac_reg_update32(adpt->base + EMAC_DMA_MAS_CTRL, 0, SOFT_RST);
usleep_range(100, 150); /* reset may take up to 100usec */
/* interrupt clear-on-read */
emac_reg_update32(adpt->base + EMAC_DMA_MAS_CTRL, 0, INT_RD_CLR_EN);
}
static void emac_mac_start(struct emac_adapter *adpt)
{
struct phy_device *phydev = adpt->phydev;
u32 mac, csr1;
/* enable tx queue */
emac_reg_update32(adpt->base + EMAC_TXQ_CTRL_0, 0, TXQ_EN);
/* enable rx queue */
emac_reg_update32(adpt->base + EMAC_RXQ_CTRL_0, 0, RXQ_EN);
/* enable mac control */
mac = readl(adpt->base + EMAC_MAC_CTRL);
csr1 = readl(adpt->csr + EMAC_EMAC_WRAPPER_CSR1);
mac |= TXEN | RXEN; /* enable RX/TX */
/* Configure MAC flow control. If set to automatic, then match
* whatever the PHY does. Otherwise, enable or disable it, depending
* on what the user configured via ethtool.
*/
mac &= ~(RXFC | TXFC);
if (adpt->automatic) {
/* If it's set to automatic, then update our local values */
adpt->rx_flow_control = phydev->pause;
adpt->tx_flow_control = phydev->pause != phydev->asym_pause;
}
mac |= adpt->rx_flow_control ? RXFC : 0;
mac |= adpt->tx_flow_control ? TXFC : 0;
/* setup link speed */
mac &= ~SPEED_MASK;
if (phydev->speed == SPEED_1000) {
mac |= SPEED(2);
csr1 |= FREQ_MODE;
} else {
mac |= SPEED(1);
csr1 &= ~FREQ_MODE;
}
if (phydev->duplex == DUPLEX_FULL)
mac |= FULLD;
else
mac &= ~FULLD;
/* other parameters */
mac |= (CRCE | PCRCE);
mac |= ((adpt->preamble << PRLEN_SHFT) & PRLEN_BMSK);
mac |= BROAD_EN;
mac |= FLCHK;
mac &= ~RX_CHKSUM_EN;
mac &= ~(HUGEN | VLAN_STRIP | TPAUSE | SIMR | HUGE | MULTI_ALL |
DEBUG_MODE | SINGLE_PAUSE_MODE);
/* Enable single-pause-frame mode if requested.
*
* If enabled, the EMAC will send a single pause frame when the RX
* queue is full. This normally leads to packet loss because
* the pause frame disables the remote MAC only for 33ms (the quanta),
* and then the remote MAC continues sending packets even though
* the RX queue is still full.
*
* If disabled, the EMAC sends a pause frame every 31ms until the RX
* queue is no longer full. Normally, this is the preferred
* method of operation. However, when the system is hung (e.g.
* cores are halted), the EMAC interrupt handler is never called
* and so the RX queue fills up quickly and stays full. The resuling
* non-stop "flood" of pause frames sometimes has the effect of
* disabling nearby switches. In some cases, other nearby switches
* are also affected, shutting down the entire network.
*
* The user can enable or disable single-pause-frame mode
* via ethtool.
*/
mac |= adpt->single_pause_mode ? SINGLE_PAUSE_MODE : 0;
writel_relaxed(csr1, adpt->csr + EMAC_EMAC_WRAPPER_CSR1);
writel_relaxed(mac, adpt->base + EMAC_MAC_CTRL);
/* enable interrupt read clear, low power sleep mode and
* the irq moderators
*/
writel_relaxed(adpt->irq_mod, adpt->base + EMAC_IRQ_MOD_TIM_INIT);
writel_relaxed(INT_RD_CLR_EN | LPW_MODE | IRQ_MODERATOR_EN |
IRQ_MODERATOR2_EN, adpt->base + EMAC_DMA_MAS_CTRL);
emac_mac_mode_config(adpt);
emac_reg_update32(adpt->base + EMAC_ATHR_HEADER_CTRL,
(HEADER_ENABLE | HEADER_CNT_EN), 0);
}
void emac_mac_stop(struct emac_adapter *adpt)
{
emac_reg_update32(adpt->base + EMAC_RXQ_CTRL_0, RXQ_EN, 0);
emac_reg_update32(adpt->base + EMAC_TXQ_CTRL_0, TXQ_EN, 0);
emac_reg_update32(adpt->base + EMAC_MAC_CTRL, TXEN | RXEN, 0);
usleep_range(1000, 1050); /* stopping mac may take upto 1msec */
}
/* Free all descriptors of given transmit queue */
static void emac_tx_q_descs_free(struct emac_adapter *adpt)
{
struct emac_tx_queue *tx_q = &adpt->tx_q;
unsigned int i;
size_t size;
/* ring already cleared, nothing to do */
if (!tx_q->tpd.tpbuff)
return;
for (i = 0; i < tx_q->tpd.count; i++) {
struct emac_buffer *tpbuf = GET_TPD_BUFFER(tx_q, i);
if (tpbuf->dma_addr) {
dma_unmap_single(adpt->netdev->dev.parent,
tpbuf->dma_addr, tpbuf->length,
DMA_TO_DEVICE);
tpbuf->dma_addr = 0;
}
if (tpbuf->skb) {
dev_kfree_skb_any(tpbuf->skb);
tpbuf->skb = NULL;
}
}
size = sizeof(struct emac_buffer) * tx_q->tpd.count;
memset(tx_q->tpd.tpbuff, 0, size);
/* clear the descriptor ring */
memset(tx_q->tpd.v_addr, 0, tx_q->tpd.size);
tx_q->tpd.consume_idx = 0;
tx_q->tpd.produce_idx = 0;
}
/* Free all descriptors of given receive queue */
static void emac_rx_q_free_descs(struct emac_adapter *adpt)
{
struct device *dev = adpt->netdev->dev.parent;
struct emac_rx_queue *rx_q = &adpt->rx_q;
unsigned int i;
size_t size;
/* ring already cleared, nothing to do */
if (!rx_q->rfd.rfbuff)
return;
for (i = 0; i < rx_q->rfd.count; i++) {
struct emac_buffer *rfbuf = GET_RFD_BUFFER(rx_q, i);
if (rfbuf->dma_addr) {
dma_unmap_single(dev, rfbuf->dma_addr, rfbuf->length,
DMA_FROM_DEVICE);
rfbuf->dma_addr = 0;
}
if (rfbuf->skb) {
dev_kfree_skb(rfbuf->skb);
rfbuf->skb = NULL;
}
}
size = sizeof(struct emac_buffer) * rx_q->rfd.count;
memset(rx_q->rfd.rfbuff, 0, size);
/* clear the descriptor rings */
memset(rx_q->rrd.v_addr, 0, rx_q->rrd.size);
rx_q->rrd.produce_idx = 0;
rx_q->rrd.consume_idx = 0;
memset(rx_q->rfd.v_addr, 0, rx_q->rfd.size);
rx_q->rfd.produce_idx = 0;
rx_q->rfd.consume_idx = 0;
}
/* Free all buffers associated with given transmit queue */
static void emac_tx_q_bufs_free(struct emac_adapter *adpt)
{
struct emac_tx_queue *tx_q = &adpt->tx_q;
emac_tx_q_descs_free(adpt);
kfree(tx_q->tpd.tpbuff);
tx_q->tpd.tpbuff = NULL;
tx_q->tpd.v_addr = NULL;
tx_q->tpd.dma_addr = 0;
tx_q->tpd.size = 0;
}
/* Allocate TX descriptor ring for the given transmit queue */
static int emac_tx_q_desc_alloc(struct emac_adapter *adpt,
struct emac_tx_queue *tx_q)
{
struct emac_ring_header *ring_header = &adpt->ring_header;
int node = dev_to_node(adpt->netdev->dev.parent);
size_t size;
size = sizeof(struct emac_buffer) * tx_q->tpd.count;
tx_q->tpd.tpbuff = kzalloc_node(size, GFP_KERNEL, node);
if (!tx_q->tpd.tpbuff)
return -ENOMEM;
tx_q->tpd.size = tx_q->tpd.count * (adpt->tpd_size * 4);
tx_q->tpd.dma_addr = ring_header->dma_addr + ring_header->used;
tx_q->tpd.v_addr = ring_header->v_addr + ring_header->used;
ring_header->used += ALIGN(tx_q->tpd.size, 8);
tx_q->tpd.produce_idx = 0;
tx_q->tpd.consume_idx = 0;
return 0;
}
/* Free all buffers associated with given transmit queue */
static void emac_rx_q_bufs_free(struct emac_adapter *adpt)
{
struct emac_rx_queue *rx_q = &adpt->rx_q;
emac_rx_q_free_descs(adpt);
kfree(rx_q->rfd.rfbuff);
rx_q->rfd.rfbuff = NULL;
rx_q->rfd.v_addr = NULL;
rx_q->rfd.dma_addr = 0;
rx_q->rfd.size = 0;
rx_q->rrd.v_addr = NULL;
rx_q->rrd.dma_addr = 0;
rx_q->rrd.size = 0;
}
/* Allocate RX descriptor rings for the given receive queue */
static int emac_rx_descs_alloc(struct emac_adapter *adpt)
{
struct emac_ring_header *ring_header = &adpt->ring_header;
int node = dev_to_node(adpt->netdev->dev.parent);
struct emac_rx_queue *rx_q = &adpt->rx_q;
size_t size;
size = sizeof(struct emac_buffer) * rx_q->rfd.count;
rx_q->rfd.rfbuff = kzalloc_node(size, GFP_KERNEL, node);
if (!rx_q->rfd.rfbuff)
return -ENOMEM;
rx_q->rrd.size = rx_q->rrd.count * (adpt->rrd_size * 4);
rx_q->rfd.size = rx_q->rfd.count * (adpt->rfd_size * 4);
rx_q->rrd.dma_addr = ring_header->dma_addr + ring_header->used;
rx_q->rrd.v_addr = ring_header->v_addr + ring_header->used;
ring_header->used += ALIGN(rx_q->rrd.size, 8);
rx_q->rfd.dma_addr = ring_header->dma_addr + ring_header->used;
rx_q->rfd.v_addr = ring_header->v_addr + ring_header->used;
ring_header->used += ALIGN(rx_q->rfd.size, 8);
rx_q->rrd.produce_idx = 0;
rx_q->rrd.consume_idx = 0;
rx_q->rfd.produce_idx = 0;
rx_q->rfd.consume_idx = 0;
return 0;
}
/* Allocate all TX and RX descriptor rings */
int emac_mac_rx_tx_rings_alloc_all(struct emac_adapter *adpt)
{
struct emac_ring_header *ring_header = &adpt->ring_header;
struct device *dev = adpt->netdev->dev.parent;
unsigned int num_tx_descs = adpt->tx_desc_cnt;
unsigned int num_rx_descs = adpt->rx_desc_cnt;
int ret;
adpt->tx_q.tpd.count = adpt->tx_desc_cnt;
adpt->rx_q.rrd.count = adpt->rx_desc_cnt;
adpt->rx_q.rfd.count = adpt->rx_desc_cnt;
/* Ring DMA buffer. Each ring may need up to 8 bytes for alignment,
* hence the additional padding bytes are allocated.
*/
ring_header->size = num_tx_descs * (adpt->tpd_size * 4) +
num_rx_descs * (adpt->rfd_size * 4) +
num_rx_descs * (adpt->rrd_size * 4) +
8 + 2 * 8; /* 8 byte per one Tx and two Rx rings */
ring_header->used = 0;
ring_header->v_addr = dma_alloc_coherent(dev, ring_header->size,
&ring_header->dma_addr,
GFP_KERNEL);
if (!ring_header->v_addr)
return -ENOMEM;
ring_header->used = ALIGN(ring_header->dma_addr, 8) -
ring_header->dma_addr;
ret = emac_tx_q_desc_alloc(adpt, &adpt->tx_q);
if (ret) {
netdev_err(adpt->netdev, "error: Tx Queue alloc failed\n");
goto err_alloc_tx;
}
ret = emac_rx_descs_alloc(adpt);
if (ret) {
netdev_err(adpt->netdev, "error: Rx Queue alloc failed\n");
goto err_alloc_rx;
}
return 0;
err_alloc_rx:
emac_tx_q_bufs_free(adpt);
err_alloc_tx:
dma_free_coherent(dev, ring_header->size,
ring_header->v_addr, ring_header->dma_addr);
ring_header->v_addr = NULL;
ring_header->dma_addr = 0;
ring_header->size = 0;
ring_header->used = 0;
return ret;
}
/* Free all TX and RX descriptor rings */
void emac_mac_rx_tx_rings_free_all(struct emac_adapter *adpt)
{
struct emac_ring_header *ring_header = &adpt->ring_header;
struct device *dev = adpt->netdev->dev.parent;
emac_tx_q_bufs_free(adpt);
emac_rx_q_bufs_free(adpt);
dma_free_coherent(dev, ring_header->size,
ring_header->v_addr, ring_header->dma_addr);
ring_header->v_addr = NULL;
ring_header->dma_addr = 0;
ring_header->size = 0;
ring_header->used = 0;
}
/* Initialize descriptor rings */
static void emac_mac_rx_tx_ring_reset_all(struct emac_adapter *adpt)
{
unsigned int i;
adpt->tx_q.tpd.produce_idx = 0;
adpt->tx_q.tpd.consume_idx = 0;
for (i = 0; i < adpt->tx_q.tpd.count; i++)
adpt->tx_q.tpd.tpbuff[i].dma_addr = 0;
adpt->rx_q.rrd.produce_idx = 0;
adpt->rx_q.rrd.consume_idx = 0;
adpt->rx_q.rfd.produce_idx = 0;
adpt->rx_q.rfd.consume_idx = 0;
for (i = 0; i < adpt->rx_q.rfd.count; i++)
adpt->rx_q.rfd.rfbuff[i].dma_addr = 0;
}
/* Produce new receive free descriptor */
static void emac_mac_rx_rfd_create(struct emac_adapter *adpt,
struct emac_rx_queue *rx_q,
dma_addr_t addr)
{
u32 *hw_rfd = EMAC_RFD(rx_q, adpt->rfd_size, rx_q->rfd.produce_idx);
*(hw_rfd++) = lower_32_bits(addr);
*hw_rfd = upper_32_bits(addr);
if (++rx_q->rfd.produce_idx == rx_q->rfd.count)
rx_q->rfd.produce_idx = 0;
}
/* Fill up receive queue's RFD with preallocated receive buffers */
static void emac_mac_rx_descs_refill(struct emac_adapter *adpt,
struct emac_rx_queue *rx_q)
{
struct emac_buffer *curr_rxbuf;
struct emac_buffer *next_rxbuf;
unsigned int count = 0;
u32 next_produce_idx;
next_produce_idx = rx_q->rfd.produce_idx + 1;
if (next_produce_idx == rx_q->rfd.count)
next_produce_idx = 0;
curr_rxbuf = GET_RFD_BUFFER(rx_q, rx_q->rfd.produce_idx);
next_rxbuf = GET_RFD_BUFFER(rx_q, next_produce_idx);
/* this always has a blank rx_buffer*/
while (!next_rxbuf->dma_addr) {
struct sk_buff *skb;
int ret;
skb = netdev_alloc_skb_ip_align(adpt->netdev, adpt->rxbuf_size);
if (!skb)
break;
curr_rxbuf->dma_addr =
dma_map_single(adpt->netdev->dev.parent, skb->data,
adpt->rxbuf_size, DMA_FROM_DEVICE);
ret = dma_mapping_error(adpt->netdev->dev.parent,
curr_rxbuf->dma_addr);
if (ret) {
dev_kfree_skb(skb);
break;
}
curr_rxbuf->skb = skb;
curr_rxbuf->length = adpt->rxbuf_size;
emac_mac_rx_rfd_create(adpt, rx_q, curr_rxbuf->dma_addr);
next_produce_idx = rx_q->rfd.produce_idx + 1;
if (next_produce_idx == rx_q->rfd.count)
next_produce_idx = 0;
curr_rxbuf = GET_RFD_BUFFER(rx_q, rx_q->rfd.produce_idx);
next_rxbuf = GET_RFD_BUFFER(rx_q, next_produce_idx);
count++;
}
if (count) {
u32 prod_idx = (rx_q->rfd.produce_idx << rx_q->produce_shift) &
rx_q->produce_mask;
emac_reg_update32(adpt->base + rx_q->produce_reg,
rx_q->produce_mask, prod_idx);
}
}
static void emac_adjust_link(struct net_device *netdev)
{
struct emac_adapter *adpt = netdev_priv(netdev);
struct phy_device *phydev = netdev->phydev;
if (phydev->link) {
emac_mac_start(adpt);
emac_sgmii_link_change(adpt, true);
} else {
emac_sgmii_link_change(adpt, false);
emac_mac_stop(adpt);
}
phy_print_status(phydev);
}
/* Bringup the interface/HW */
int emac_mac_up(struct emac_adapter *adpt)
{
struct net_device *netdev = adpt->netdev;
int ret;
emac_mac_rx_tx_ring_reset_all(adpt);
emac_mac_config(adpt);
emac_mac_rx_descs_refill(adpt, &adpt->rx_q);
adpt->phydev->irq = PHY_POLL;
ret = phy_connect_direct(netdev, adpt->phydev, emac_adjust_link,
PHY_INTERFACE_MODE_SGMII);
if (ret) {
netdev_err(adpt->netdev, "could not connect phy\n");
return ret;
}
phy_attached_print(adpt->phydev, NULL);
/* enable mac irq */
writel((u32)~DIS_INT, adpt->base + EMAC_INT_STATUS);
writel(adpt->irq.mask, adpt->base + EMAC_INT_MASK);
phy_start(adpt->phydev);
napi_enable(&adpt->rx_q.napi);
netif_start_queue(netdev);
return 0;
}
/* Bring down the interface/HW */
void emac_mac_down(struct emac_adapter *adpt)
{
struct net_device *netdev = adpt->netdev;
netif_stop_queue(netdev);
napi_disable(&adpt->rx_q.napi);
phy_stop(adpt->phydev);
/* Interrupts must be disabled before the PHY is disconnected, to
* avoid a race condition where adjust_link is null when we get
* an interrupt.
*/
writel(DIS_INT, adpt->base + EMAC_INT_STATUS);
writel(0, adpt->base + EMAC_INT_MASK);
synchronize_irq(adpt->irq.irq);
phy_disconnect(adpt->phydev);
emac_mac_reset(adpt);
emac_tx_q_descs_free(adpt);
netdev_reset_queue(adpt->netdev);
emac_rx_q_free_descs(adpt);
}
/* Consume next received packet descriptor */
static bool emac_rx_process_rrd(struct emac_adapter *adpt,
struct emac_rx_queue *rx_q,
struct emac_rrd *rrd)
{
u32 *hw_rrd = EMAC_RRD(rx_q, adpt->rrd_size, rx_q->rrd.consume_idx);
rrd->word[3] = *(hw_rrd + 3);
if (!RRD_UPDT(rrd))
return false;
rrd->word[4] = 0;
rrd->word[5] = 0;
rrd->word[0] = *(hw_rrd++);
rrd->word[1] = *(hw_rrd++);
rrd->word[2] = *(hw_rrd++);
if (unlikely(RRD_NOR(rrd) != 1)) {
netdev_err(adpt->netdev,
"error: multi-RFD not support yet! nor:%lu\n",
RRD_NOR(rrd));
}
/* mark rrd as processed */
RRD_UPDT_SET(rrd, 0);
*hw_rrd = rrd->word[3];
if (++rx_q->rrd.consume_idx == rx_q->rrd.count)
rx_q->rrd.consume_idx = 0;
return true;
}
/* Produce new transmit descriptor */
static void emac_tx_tpd_create(struct emac_adapter *adpt,
struct emac_tx_queue *tx_q, struct emac_tpd *tpd)
{
u32 *hw_tpd;
tx_q->tpd.last_produce_idx = tx_q->tpd.produce_idx;
hw_tpd = EMAC_TPD(tx_q, adpt->tpd_size, tx_q->tpd.produce_idx);
if (++tx_q->tpd.produce_idx == tx_q->tpd.count)
tx_q->tpd.produce_idx = 0;
*(hw_tpd++) = tpd->word[0];
*(hw_tpd++) = tpd->word[1];
*(hw_tpd++) = tpd->word[2];
*hw_tpd = tpd->word[3];
}
/* Mark the last transmit descriptor as such (for the transmit packet) */
static void emac_tx_tpd_mark_last(struct emac_adapter *adpt,
struct emac_tx_queue *tx_q)
{
u32 *hw_tpd =
EMAC_TPD(tx_q, adpt->tpd_size, tx_q->tpd.last_produce_idx);
u32 tmp_tpd;
tmp_tpd = *(hw_tpd + 1);
tmp_tpd |= EMAC_TPD_LAST_FRAGMENT;
*(hw_tpd + 1) = tmp_tpd;
}
static void emac_rx_rfd_clean(struct emac_rx_queue *rx_q, struct emac_rrd *rrd)
{
struct emac_buffer *rfbuf = rx_q->rfd.rfbuff;
u32 consume_idx = RRD_SI(rrd);
unsigned int i;
for (i = 0; i < RRD_NOR(rrd); i++) {
rfbuf[consume_idx].skb = NULL;
if (++consume_idx == rx_q->rfd.count)
consume_idx = 0;
}
rx_q->rfd.consume_idx = consume_idx;
rx_q->rfd.process_idx = consume_idx;
}
/* Push the received skb to upper layers */
static void emac_receive_skb(struct emac_rx_queue *rx_q,
struct sk_buff *skb,
u16 vlan_tag, bool vlan_flag)
{
if (vlan_flag) {
u16 vlan;
EMAC_TAG_TO_VLAN(vlan_tag, vlan);
__vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vlan);
}
napi_gro_receive(&rx_q->napi, skb);
}
/* Process receive event */
void emac_mac_rx_process(struct emac_adapter *adpt, struct emac_rx_queue *rx_q,
int *num_pkts, int max_pkts)
{
u32 proc_idx, hw_consume_idx, num_consume_pkts;
struct net_device *netdev = adpt->netdev;
struct emac_buffer *rfbuf;
unsigned int count = 0;
struct emac_rrd rrd;
struct sk_buff *skb;
u32 reg;
reg = readl_relaxed(adpt->base + rx_q->consume_reg);
hw_consume_idx = (reg & rx_q->consume_mask) >> rx_q->consume_shift;
num_consume_pkts = (hw_consume_idx >= rx_q->rrd.consume_idx) ?
(hw_consume_idx - rx_q->rrd.consume_idx) :
(hw_consume_idx + rx_q->rrd.count - rx_q->rrd.consume_idx);
do {
if (!num_consume_pkts)
break;
if (!emac_rx_process_rrd(adpt, rx_q, &rrd))
break;
if (likely(RRD_NOR(&rrd) == 1)) {
/* good receive */
rfbuf = GET_RFD_BUFFER(rx_q, RRD_SI(&rrd));
dma_unmap_single(adpt->netdev->dev.parent,
rfbuf->dma_addr, rfbuf->length,
DMA_FROM_DEVICE);
rfbuf->dma_addr = 0;
skb = rfbuf->skb;
} else {
netdev_err(adpt->netdev,
"error: multi-RFD not support yet!\n");
break;
}
emac_rx_rfd_clean(rx_q, &rrd);
num_consume_pkts--;
count++;
/* Due to a HW issue in L4 check sum detection (UDP/TCP frags
* with DF set are marked as error), drop packets based on the
* error mask rather than the summary bit (ignoring L4F errors)
*/
if (rrd.word[EMAC_RRD_STATS_DW_IDX] & EMAC_RRD_ERROR) {
netif_dbg(adpt, rx_status, adpt->netdev,
"Drop error packet[RRD: 0x%x:0x%x:0x%x:0x%x]\n",
rrd.word[0], rrd.word[1],
rrd.word[2], rrd.word[3]);
dev_kfree_skb(skb);
continue;
}
skb_put(skb, RRD_PKT_SIZE(&rrd) - ETH_FCS_LEN);
skb->dev = netdev;
skb->protocol = eth_type_trans(skb, skb->dev);
if (netdev->features & NETIF_F_RXCSUM)
skb->ip_summed = RRD_L4F(&rrd) ?
CHECKSUM_NONE : CHECKSUM_UNNECESSARY;
else
skb_checksum_none_assert(skb);
emac_receive_skb(rx_q, skb, (u16)RRD_CVALN_TAG(&rrd),
(bool)RRD_CVTAG(&rrd));
(*num_pkts)++;
} while (*num_pkts < max_pkts);
if (count) {
proc_idx = (rx_q->rfd.process_idx << rx_q->process_shft) &
rx_q->process_mask;
emac_reg_update32(adpt->base + rx_q->process_reg,
rx_q->process_mask, proc_idx);
emac_mac_rx_descs_refill(adpt, rx_q);
}
}
/* get the number of free transmit descriptors */
static unsigned int emac_tpd_num_free_descs(struct emac_tx_queue *tx_q)
{
u32 produce_idx = tx_q->tpd.produce_idx;
u32 consume_idx = tx_q->tpd.consume_idx;
return (consume_idx > produce_idx) ?
(consume_idx - produce_idx - 1) :
(tx_q->tpd.count + consume_idx - produce_idx - 1);
}
/* Process transmit event */
void emac_mac_tx_process(struct emac_adapter *adpt, struct emac_tx_queue *tx_q)
{
u32 reg = readl_relaxed(adpt->base + tx_q->consume_reg);
u32 hw_consume_idx, pkts_compl = 0, bytes_compl = 0;
struct emac_buffer *tpbuf;
hw_consume_idx = (reg & tx_q->consume_mask) >> tx_q->consume_shift;
while (tx_q->tpd.consume_idx != hw_consume_idx) {
tpbuf = GET_TPD_BUFFER(tx_q, tx_q->tpd.consume_idx);
if (tpbuf->dma_addr) {
dma_unmap_page(adpt->netdev->dev.parent,
tpbuf->dma_addr, tpbuf->length,
DMA_TO_DEVICE);
tpbuf->dma_addr = 0;
}
if (tpbuf->skb) {
pkts_compl++;
bytes_compl += tpbuf->skb->len;
dev_consume_skb_irq(tpbuf->skb);
tpbuf->skb = NULL;
}
if (++tx_q->tpd.consume_idx == tx_q->tpd.count)
tx_q->tpd.consume_idx = 0;
}
netdev_completed_queue(adpt->netdev, pkts_compl, bytes_compl);
if (netif_queue_stopped(adpt->netdev))
if (emac_tpd_num_free_descs(tx_q) > (MAX_SKB_FRAGS + 1))
netif_wake_queue(adpt->netdev);
}
/* Initialize all queue data structures */
void emac_mac_rx_tx_ring_init_all(struct platform_device *pdev,
struct emac_adapter *adpt)
{
adpt->rx_q.netdev = adpt->netdev;
adpt->rx_q.produce_reg = EMAC_MAILBOX_0;
adpt->rx_q.produce_mask = RFD0_PROD_IDX_BMSK;
adpt->rx_q.produce_shift = RFD0_PROD_IDX_SHFT;
adpt->rx_q.process_reg = EMAC_MAILBOX_0;
adpt->rx_q.process_mask = RFD0_PROC_IDX_BMSK;
adpt->rx_q.process_shft = RFD0_PROC_IDX_SHFT;
adpt->rx_q.consume_reg = EMAC_MAILBOX_3;
adpt->rx_q.consume_mask = RFD0_CONS_IDX_BMSK;
adpt->rx_q.consume_shift = RFD0_CONS_IDX_SHFT;
adpt->rx_q.irq = &adpt->irq;
adpt->rx_q.intr = adpt->irq.mask & ISR_RX_PKT;
adpt->tx_q.produce_reg = EMAC_MAILBOX_15;
adpt->tx_q.produce_mask = NTPD_PROD_IDX_BMSK;
adpt->tx_q.produce_shift = NTPD_PROD_IDX_SHFT;
adpt->tx_q.consume_reg = EMAC_MAILBOX_2;
adpt->tx_q.consume_mask = NTPD_CONS_IDX_BMSK;
adpt->tx_q.consume_shift = NTPD_CONS_IDX_SHFT;
}
/* Fill up transmit descriptors with TSO and Checksum offload information */
static int emac_tso_csum(struct emac_adapter *adpt,
struct emac_tx_queue *tx_q,
struct sk_buff *skb,
struct emac_tpd *tpd)
{
unsigned int hdr_len;
int ret;
if (skb_is_gso(skb)) {
if (skb_header_cloned(skb)) {
ret = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
if (unlikely(ret))
return ret;
}
if (skb->protocol == htons(ETH_P_IP)) {
u32 pkt_len = ((unsigned char *)ip_hdr(skb) - skb->data)
+ ntohs(ip_hdr(skb)->tot_len);
if (skb->len > pkt_len) {
ret = pskb_trim(skb, pkt_len);
if (unlikely(ret))
return ret;
}
}
hdr_len = skb_tcp_all_headers(skb);
if (unlikely(skb->len == hdr_len)) {
/* we only need to do csum */
netif_warn(adpt, tx_err, adpt->netdev,
"tso not needed for packet with 0 data\n");
goto do_csum;
}
if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
ip_hdr(skb)->check = 0;
tcp_hdr(skb)->check =
~csum_tcpudp_magic(ip_hdr(skb)->saddr,
ip_hdr(skb)->daddr,
0, IPPROTO_TCP, 0);
TPD_IPV4_SET(tpd, 1);
}
if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6) {
/* ipv6 tso need an extra tpd */
struct emac_tpd extra_tpd;
memset(tpd, 0, sizeof(*tpd));
memset(&extra_tpd, 0, sizeof(extra_tpd));
tcp_v6_gso_csum_prep(skb);
TPD_PKT_LEN_SET(&extra_tpd, skb->len);
TPD_LSO_SET(&extra_tpd, 1);
TPD_LSOV_SET(&extra_tpd, 1);
emac_tx_tpd_create(adpt, tx_q, &extra_tpd);
TPD_LSOV_SET(tpd, 1);
}
TPD_LSO_SET(tpd, 1);
TPD_TCPHDR_OFFSET_SET(tpd, skb_transport_offset(skb));
TPD_MSS_SET(tpd, skb_shinfo(skb)->gso_size);
return 0;
}
do_csum:
if (likely(skb->ip_summed == CHECKSUM_PARTIAL)) {
unsigned int css, cso;
cso = skb_transport_offset(skb);
if (unlikely(cso & 0x1)) {
netdev_err(adpt->netdev,
"error: payload offset should be even\n");
return -EINVAL;
}
css = cso + skb->csum_offset;
TPD_PAYLOAD_OFFSET_SET(tpd, cso >> 1);
TPD_CXSUM_OFFSET_SET(tpd, css >> 1);
TPD_CSX_SET(tpd, 1);
}
return 0;
}
/* Fill up transmit descriptors */
static void emac_tx_fill_tpd(struct emac_adapter *adpt,
struct emac_tx_queue *tx_q, struct sk_buff *skb,
struct emac_tpd *tpd)
{
unsigned int nr_frags = skb_shinfo(skb)->nr_frags;
unsigned int first = tx_q->tpd.produce_idx;
unsigned int len = skb_headlen(skb);
struct emac_buffer *tpbuf = NULL;
unsigned int mapped_len = 0;
unsigned int i;
int count = 0;
int ret;
/* if Large Segment Offload is (in TCP Segmentation Offload struct) */
if (TPD_LSO(tpd)) {
mapped_len = skb_tcp_all_headers(skb);
tpbuf = GET_TPD_BUFFER(tx_q, tx_q->tpd.produce_idx);
tpbuf->length = mapped_len;
tpbuf->dma_addr = dma_map_page(adpt->netdev->dev.parent,
virt_to_page(skb->data),
offset_in_page(skb->data),
tpbuf->length,
DMA_TO_DEVICE);
ret = dma_mapping_error(adpt->netdev->dev.parent,
tpbuf->dma_addr);
if (ret)
goto error;
TPD_BUFFER_ADDR_L_SET(tpd, lower_32_bits(tpbuf->dma_addr));
TPD_BUFFER_ADDR_H_SET(tpd, upper_32_bits(tpbuf->dma_addr));
TPD_BUF_LEN_SET(tpd, tpbuf->length);
emac_tx_tpd_create(adpt, tx_q, tpd);
count++;
}
if (mapped_len < len) {
tpbuf = GET_TPD_BUFFER(tx_q, tx_q->tpd.produce_idx);
tpbuf->length = len - mapped_len;
tpbuf->dma_addr = dma_map_page(adpt->netdev->dev.parent,
virt_to_page(skb->data +
mapped_len),
offset_in_page(skb->data +
mapped_len),
tpbuf->length, DMA_TO_DEVICE);
ret = dma_mapping_error(adpt->netdev->dev.parent,
tpbuf->dma_addr);
if (ret)
goto error;
TPD_BUFFER_ADDR_L_SET(tpd, lower_32_bits(tpbuf->dma_addr));
TPD_BUFFER_ADDR_H_SET(tpd, upper_32_bits(tpbuf->dma_addr));
TPD_BUF_LEN_SET(tpd, tpbuf->length);
emac_tx_tpd_create(adpt, tx_q, tpd);
count++;
}
for (i = 0; i < nr_frags; i++) {
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
tpbuf = GET_TPD_BUFFER(tx_q, tx_q->tpd.produce_idx);
tpbuf->length = skb_frag_size(frag);
tpbuf->dma_addr = skb_frag_dma_map(adpt->netdev->dev.parent,
frag, 0, tpbuf->length,
DMA_TO_DEVICE);
ret = dma_mapping_error(adpt->netdev->dev.parent,
tpbuf->dma_addr);
if (ret)
goto error;
TPD_BUFFER_ADDR_L_SET(tpd, lower_32_bits(tpbuf->dma_addr));
TPD_BUFFER_ADDR_H_SET(tpd, upper_32_bits(tpbuf->dma_addr));
TPD_BUF_LEN_SET(tpd, tpbuf->length);
emac_tx_tpd_create(adpt, tx_q, tpd);
count++;
}
/* The last tpd */
wmb();
emac_tx_tpd_mark_last(adpt, tx_q);
/* The last buffer info contain the skb address,
* so it will be freed after unmap
*/
tpbuf->skb = skb;
return;
error:
/* One of the memory mappings failed, so undo everything */
tx_q->tpd.produce_idx = first;
while (count--) {
tpbuf = GET_TPD_BUFFER(tx_q, first);
dma_unmap_page(adpt->netdev->dev.parent, tpbuf->dma_addr,
tpbuf->length, DMA_TO_DEVICE);
tpbuf->dma_addr = 0;
tpbuf->length = 0;
if (++first == tx_q->tpd.count)
first = 0;
}
dev_kfree_skb(skb);
}
/* Transmit the packet using specified transmit queue */
netdev_tx_t emac_mac_tx_buf_send(struct emac_adapter *adpt,
struct emac_tx_queue *tx_q,
struct sk_buff *skb)
{
struct emac_tpd tpd;
u32 prod_idx;
int len;
memset(&tpd, 0, sizeof(tpd));
if (emac_tso_csum(adpt, tx_q, skb, &tpd) != 0) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
if (skb_vlan_tag_present(skb)) {
u16 tag;
EMAC_VLAN_TO_TAG(skb_vlan_tag_get(skb), tag);
TPD_CVLAN_TAG_SET(&tpd, tag);
TPD_INSTC_SET(&tpd, 1);
}
if (skb_network_offset(skb) != ETH_HLEN)
TPD_TYP_SET(&tpd, 1);
len = skb->len;
emac_tx_fill_tpd(adpt, tx_q, skb, &tpd);
netdev_sent_queue(adpt->netdev, len);
/* Make sure the are enough free descriptors to hold one
* maximum-sized SKB. We need one desc for each fragment,
* one for the checksum (emac_tso_csum), one for TSO, and
* one for the SKB header.
*/
if (emac_tpd_num_free_descs(tx_q) < (MAX_SKB_FRAGS + 3))
netif_stop_queue(adpt->netdev);
/* update produce idx */
prod_idx = (tx_q->tpd.produce_idx << tx_q->produce_shift) &
tx_q->produce_mask;
emac_reg_update32(adpt->base + tx_q->produce_reg,
tx_q->produce_mask, prod_idx);
return NETDEV_TX_OK;
}
|
linux-master
|
drivers/net/ethernet/qualcomm/emac/emac-mac.c
|
// SPDX-License-Identifier: GPL-2.0-only
/* Copyright (c) 2015-2016, The Linux Foundation. All rights reserved.
*/
/* Qualcomm Technologies, Inc. QDF2400 EMAC SGMII Controller driver.
*/
#include <linux/iopoll.h>
#include "emac.h"
/* EMAC_SGMII register offsets */
#define EMAC_SGMII_PHY_TX_PWR_CTRL 0x000C
#define EMAC_SGMII_PHY_LANE_CTRL1 0x0018
#define EMAC_SGMII_PHY_CDR_CTRL0 0x0058
#define EMAC_SGMII_PHY_POW_DWN_CTRL0 0x0080
#define EMAC_SGMII_PHY_RESET_CTRL 0x00a8
#define EMAC_SGMII_PHY_INTERRUPT_MASK 0x00b4
/* SGMII digital lane registers */
#define EMAC_SGMII_LN_DRVR_CTRL0 0x000C
#define EMAC_SGMII_LN_DRVR_CTRL1 0x0010
#define EMAC_SGMII_LN_DRVR_TAP_EN 0x0018
#define EMAC_SGMII_LN_TX_MARGINING 0x001C
#define EMAC_SGMII_LN_TX_PRE 0x0020
#define EMAC_SGMII_LN_TX_POST 0x0024
#define EMAC_SGMII_LN_TX_BAND_MODE 0x0060
#define EMAC_SGMII_LN_LANE_MODE 0x0064
#define EMAC_SGMII_LN_PARALLEL_RATE 0x007C
#define EMAC_SGMII_LN_CML_CTRL_MODE0 0x00C0
#define EMAC_SGMII_LN_MIXER_CTRL_MODE0 0x00D8
#define EMAC_SGMII_LN_VGA_INITVAL 0x013C
#define EMAC_SGMII_LN_UCDR_FO_GAIN_MODE0 0x0184
#define EMAC_SGMII_LN_UCDR_SO_GAIN_MODE0 0x0190
#define EMAC_SGMII_LN_UCDR_SO_CONFIG 0x019C
#define EMAC_SGMII_LN_RX_BAND 0x01A4
#define EMAC_SGMII_LN_RX_RCVR_PATH1_MODE0 0x01C0
#define EMAC_SGMII_LN_RSM_CONFIG 0x01F8
#define EMAC_SGMII_LN_SIGDET_ENABLES 0x0230
#define EMAC_SGMII_LN_SIGDET_CNTRL 0x0234
#define EMAC_SGMII_LN_SIGDET_DEGLITCH_CNTRL 0x0238
#define EMAC_SGMII_LN_RX_EN_SIGNAL 0x02AC
#define EMAC_SGMII_LN_RX_MISC_CNTRL0 0x02B8
#define EMAC_SGMII_LN_DRVR_LOGIC_CLKDIV 0x02C8
#define EMAC_SGMII_LN_RX_RESECODE_OFFSET 0x02CC
/* SGMII digital lane register values */
#define UCDR_STEP_BY_TWO_MODE0 BIT(7)
#define UCDR_xO_GAIN_MODE(x) ((x) & 0x7f)
#define UCDR_ENABLE BIT(6)
#define UCDR_SO_SATURATION(x) ((x) & 0x3f)
#define SIGDET_LP_BYP_PS4 BIT(7)
#define SIGDET_EN_PS0_TO_PS2 BIT(6)
#define TXVAL_VALID_INIT BIT(4)
#define KR_PCIGEN3_MODE BIT(0)
#define MAIN_EN BIT(0)
#define TX_MARGINING_MUX BIT(6)
#define TX_MARGINING(x) ((x) & 0x3f)
#define TX_PRE_MUX BIT(6)
#define TX_POST_MUX BIT(6)
#define CML_GEAR_MODE(x) (((x) & 7) << 3)
#define CML2CMOS_IBOOST_MODE(x) ((x) & 7)
#define RESCODE_OFFSET(x) ((x) & 0x1f)
#define MIXER_LOADB_MODE(x) (((x) & 0xf) << 2)
#define MIXER_DATARATE_MODE(x) ((x) & 3)
#define VGA_THRESH_DFE(x) ((x) & 0x3f)
#define SIGDET_LP_BYP_PS0_TO_PS2 BIT(5)
#define SIGDET_FLT_BYP BIT(0)
#define SIGDET_LVL(x) (((x) & 0xf) << 4)
#define SIGDET_DEGLITCH_CTRL(x) (((x) & 0xf) << 1)
#define INVERT_PCS_RX_CLK BIT(7)
#define DRVR_LOGIC_CLK_EN BIT(4)
#define DRVR_LOGIC_CLK_DIV(x) ((x) & 0xf)
#define PARALLEL_RATE_MODE0(x) ((x) & 0x3)
#define BAND_MODE0(x) ((x) & 0x3)
#define LANE_MODE(x) ((x) & 0x1f)
#define CDR_PD_SEL_MODE0(x) (((x) & 0x3) << 5)
#define EN_DLL_MODE0 BIT(4)
#define EN_IQ_DCC_MODE0 BIT(3)
#define EN_IQCAL_MODE0 BIT(2)
#define BYPASS_RSM_SAMP_CAL BIT(1)
#define BYPASS_RSM_DLL_CAL BIT(0)
#define L0_RX_EQUALIZE_ENABLE BIT(6)
#define PWRDN_B BIT(0)
#define CDR_MAX_CNT(x) ((x) & 0xff)
#define SERDES_START_WAIT_TIMES 100
struct emac_reg_write {
unsigned int offset;
u32 val;
};
static void emac_reg_write_all(void __iomem *base,
const struct emac_reg_write *itr, size_t size)
{
size_t i;
for (i = 0; i < size; ++itr, ++i)
writel(itr->val, base + itr->offset);
}
static const struct emac_reg_write sgmii_laned[] = {
/* CDR Settings */
{EMAC_SGMII_LN_UCDR_FO_GAIN_MODE0,
UCDR_STEP_BY_TWO_MODE0 | UCDR_xO_GAIN_MODE(10)},
{EMAC_SGMII_LN_UCDR_SO_GAIN_MODE0, UCDR_xO_GAIN_MODE(0)},
{EMAC_SGMII_LN_UCDR_SO_CONFIG, UCDR_ENABLE | UCDR_SO_SATURATION(12)},
/* TX/RX Settings */
{EMAC_SGMII_LN_RX_EN_SIGNAL, SIGDET_LP_BYP_PS4 | SIGDET_EN_PS0_TO_PS2},
{EMAC_SGMII_LN_DRVR_CTRL0, TXVAL_VALID_INIT | KR_PCIGEN3_MODE},
{EMAC_SGMII_LN_DRVR_TAP_EN, MAIN_EN},
{EMAC_SGMII_LN_TX_MARGINING, TX_MARGINING_MUX | TX_MARGINING(25)},
{EMAC_SGMII_LN_TX_PRE, TX_PRE_MUX},
{EMAC_SGMII_LN_TX_POST, TX_POST_MUX},
{EMAC_SGMII_LN_CML_CTRL_MODE0,
CML_GEAR_MODE(1) | CML2CMOS_IBOOST_MODE(1)},
{EMAC_SGMII_LN_MIXER_CTRL_MODE0,
MIXER_LOADB_MODE(12) | MIXER_DATARATE_MODE(1)},
{EMAC_SGMII_LN_VGA_INITVAL, VGA_THRESH_DFE(31)},
{EMAC_SGMII_LN_SIGDET_ENABLES,
SIGDET_LP_BYP_PS0_TO_PS2 | SIGDET_FLT_BYP},
{EMAC_SGMII_LN_SIGDET_CNTRL, SIGDET_LVL(8)},
{EMAC_SGMII_LN_SIGDET_DEGLITCH_CNTRL, SIGDET_DEGLITCH_CTRL(4)},
{EMAC_SGMII_LN_RX_MISC_CNTRL0, INVERT_PCS_RX_CLK},
{EMAC_SGMII_LN_DRVR_LOGIC_CLKDIV,
DRVR_LOGIC_CLK_EN | DRVR_LOGIC_CLK_DIV(4)},
{EMAC_SGMII_LN_PARALLEL_RATE, PARALLEL_RATE_MODE0(1)},
{EMAC_SGMII_LN_TX_BAND_MODE, BAND_MODE0(1)},
{EMAC_SGMII_LN_RX_BAND, BAND_MODE0(2)},
{EMAC_SGMII_LN_DRVR_CTRL1, RESCODE_OFFSET(7)},
{EMAC_SGMII_LN_RX_RESECODE_OFFSET, RESCODE_OFFSET(9)},
{EMAC_SGMII_LN_LANE_MODE, LANE_MODE(26)},
{EMAC_SGMII_LN_RX_RCVR_PATH1_MODE0, CDR_PD_SEL_MODE0(2) |
EN_DLL_MODE0 | EN_IQ_DCC_MODE0 | EN_IQCAL_MODE0},
{EMAC_SGMII_LN_RSM_CONFIG, BYPASS_RSM_SAMP_CAL | BYPASS_RSM_DLL_CAL},
};
static const struct emac_reg_write physical_coding_sublayer_programming[] = {
{EMAC_SGMII_PHY_POW_DWN_CTRL0, PWRDN_B},
{EMAC_SGMII_PHY_CDR_CTRL0, CDR_MAX_CNT(15)},
{EMAC_SGMII_PHY_TX_PWR_CTRL, 0},
{EMAC_SGMII_PHY_LANE_CTRL1, L0_RX_EQUALIZE_ENABLE},
};
int emac_sgmii_init_qdf2400(struct emac_adapter *adpt)
{
struct emac_sgmii *phy = &adpt->phy;
void __iomem *phy_regs = phy->base;
void __iomem *laned = phy->digital;
unsigned int i;
u32 lnstatus;
/* PCS lane-x init */
emac_reg_write_all(phy->base, physical_coding_sublayer_programming,
ARRAY_SIZE(physical_coding_sublayer_programming));
/* SGMII lane-x init */
emac_reg_write_all(phy->digital, sgmii_laned, ARRAY_SIZE(sgmii_laned));
/* Power up PCS and start reset lane state machine */
writel(0, phy_regs + EMAC_SGMII_PHY_RESET_CTRL);
writel(1, laned + SGMII_LN_RSM_START);
/* Wait for c_ready assertion */
for (i = 0; i < SERDES_START_WAIT_TIMES; i++) {
lnstatus = readl(phy_regs + SGMII_PHY_LN_LANE_STATUS);
if (lnstatus & BIT(1))
break;
usleep_range(100, 200);
}
if (i == SERDES_START_WAIT_TIMES) {
netdev_err(adpt->netdev, "SGMII failed to start\n");
return -EIO;
}
/* Disable digital and SERDES loopback */
writel(0, phy_regs + SGMII_PHY_LN_BIST_GEN0);
writel(0, phy_regs + SGMII_PHY_LN_BIST_GEN2);
writel(0, phy_regs + SGMII_PHY_LN_CDR_CTRL1);
/* Mask out all the SGMII Interrupt */
writel(0, phy_regs + EMAC_SGMII_PHY_INTERRUPT_MASK);
return 0;
}
|
linux-master
|
drivers/net/ethernet/qualcomm/emac/emac-sgmii-qdf2400.c
|
// SPDX-License-Identifier: GPL-2.0-only
/* Copyright (c) 2015-2016, The Linux Foundation. All rights reserved.
*/
/* Qualcomm Technologies, Inc. EMAC SGMII Controller driver.
*/
#include <linux/interrupt.h>
#include <linux/iopoll.h>
#include <linux/acpi.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/of_platform.h>
#include "emac.h"
#include "emac-mac.h"
#include "emac-sgmii.h"
/* EMAC_SGMII register offsets */
#define EMAC_SGMII_PHY_AUTONEG_CFG2 0x0048
#define EMAC_SGMII_PHY_SPEED_CFG1 0x0074
#define EMAC_SGMII_PHY_IRQ_CMD 0x00ac
#define EMAC_SGMII_PHY_INTERRUPT_CLEAR 0x00b0
#define EMAC_SGMII_PHY_INTERRUPT_MASK 0x00b4
#define EMAC_SGMII_PHY_INTERRUPT_STATUS 0x00b8
#define EMAC_SGMII_PHY_RX_CHK_STATUS 0x00d4
#define FORCE_AN_TX_CFG BIT(5)
#define FORCE_AN_RX_CFG BIT(4)
#define AN_ENABLE BIT(0)
#define DUPLEX_MODE BIT(4)
#define SPDMODE_1000 BIT(1)
#define SPDMODE_100 BIT(0)
#define SPDMODE_10 0
#define CDR_ALIGN_DET BIT(6)
#define IRQ_GLOBAL_CLEAR BIT(0)
#define DECODE_CODE_ERR BIT(7)
#define DECODE_DISP_ERR BIT(6)
#define SGMII_PHY_IRQ_CLR_WAIT_TIME 10
#define SGMII_PHY_INTERRUPT_ERR (DECODE_CODE_ERR | DECODE_DISP_ERR)
#define SGMII_ISR_MASK (SGMII_PHY_INTERRUPT_ERR)
#define SERDES_START_WAIT_TIMES 100
int emac_sgmii_init(struct emac_adapter *adpt)
{
if (!(adpt->phy.sgmii_ops && adpt->phy.sgmii_ops->init))
return 0;
return adpt->phy.sgmii_ops->init(adpt);
}
int emac_sgmii_open(struct emac_adapter *adpt)
{
if (!(adpt->phy.sgmii_ops && adpt->phy.sgmii_ops->open))
return 0;
return adpt->phy.sgmii_ops->open(adpt);
}
void emac_sgmii_close(struct emac_adapter *adpt)
{
if (!(adpt->phy.sgmii_ops && adpt->phy.sgmii_ops->close))
return;
adpt->phy.sgmii_ops->close(adpt);
}
int emac_sgmii_link_change(struct emac_adapter *adpt, bool link_state)
{
if (!(adpt->phy.sgmii_ops && adpt->phy.sgmii_ops->link_change))
return 0;
return adpt->phy.sgmii_ops->link_change(adpt, link_state);
}
void emac_sgmii_reset(struct emac_adapter *adpt)
{
if (!(adpt->phy.sgmii_ops && adpt->phy.sgmii_ops->reset))
return;
adpt->phy.sgmii_ops->reset(adpt);
}
/* Initialize the SGMII link between the internal and external PHYs. */
static void emac_sgmii_link_init(struct emac_adapter *adpt)
{
struct emac_sgmii *phy = &adpt->phy;
u32 val;
/* Always use autonegotiation. It works no matter how the external
* PHY is configured.
*/
val = readl(phy->base + EMAC_SGMII_PHY_AUTONEG_CFG2);
val &= ~(FORCE_AN_RX_CFG | FORCE_AN_TX_CFG);
val |= AN_ENABLE;
writel(val, phy->base + EMAC_SGMII_PHY_AUTONEG_CFG2);
}
static int emac_sgmii_irq_clear(struct emac_adapter *adpt, u8 irq_bits)
{
struct emac_sgmii *phy = &adpt->phy;
u8 status;
writel_relaxed(irq_bits, phy->base + EMAC_SGMII_PHY_INTERRUPT_CLEAR);
writel_relaxed(IRQ_GLOBAL_CLEAR, phy->base + EMAC_SGMII_PHY_IRQ_CMD);
/* Ensure interrupt clear command is written to HW */
wmb();
/* After set the IRQ_GLOBAL_CLEAR bit, the status clearing must
* be confirmed before clearing the bits in other registers.
* It takes a few cycles for hw to clear the interrupt status.
*/
if (readl_poll_timeout_atomic(phy->base +
EMAC_SGMII_PHY_INTERRUPT_STATUS,
status, !(status & irq_bits), 1,
SGMII_PHY_IRQ_CLR_WAIT_TIME)) {
net_err_ratelimited("%s: failed to clear SGMII irq: status:0x%x bits:0x%x\n",
adpt->netdev->name, status, irq_bits);
return -EIO;
}
/* Finalize clearing procedure */
writel_relaxed(0, phy->base + EMAC_SGMII_PHY_IRQ_CMD);
writel_relaxed(0, phy->base + EMAC_SGMII_PHY_INTERRUPT_CLEAR);
/* Ensure that clearing procedure finalization is written to HW */
wmb();
return 0;
}
/* The number of decode errors that triggers a reset */
#define DECODE_ERROR_LIMIT 2
static irqreturn_t emac_sgmii_interrupt(int irq, void *data)
{
struct emac_adapter *adpt = data;
struct emac_sgmii *phy = &adpt->phy;
u8 status;
status = readl(phy->base + EMAC_SGMII_PHY_INTERRUPT_STATUS);
status &= SGMII_ISR_MASK;
if (!status)
return IRQ_HANDLED;
/* If we get a decoding error and CDR is not locked, then try
* resetting the internal PHY. The internal PHY uses an embedded
* clock with Clock and Data Recovery (CDR) to recover the
* clock and data.
*/
if (status & SGMII_PHY_INTERRUPT_ERR) {
int count;
/* The SGMII is capable of recovering from some decode
* errors automatically. However, if we get multiple
* decode errors in a row, then assume that something
* is wrong and reset the interface.
*/
count = atomic_inc_return(&phy->decode_error_count);
if (count == DECODE_ERROR_LIMIT) {
schedule_work(&adpt->work_thread);
atomic_set(&phy->decode_error_count, 0);
}
} else {
/* We only care about consecutive decode errors. */
atomic_set(&phy->decode_error_count, 0);
}
if (emac_sgmii_irq_clear(adpt, status))
schedule_work(&adpt->work_thread);
return IRQ_HANDLED;
}
static void emac_sgmii_reset_prepare(struct emac_adapter *adpt)
{
struct emac_sgmii *phy = &adpt->phy;
u32 val;
/* Reset PHY */
val = readl(phy->base + EMAC_EMAC_WRAPPER_CSR2);
writel(((val & ~PHY_RESET) | PHY_RESET), phy->base +
EMAC_EMAC_WRAPPER_CSR2);
/* Ensure phy-reset command is written to HW before the release cmd */
msleep(50);
val = readl(phy->base + EMAC_EMAC_WRAPPER_CSR2);
writel((val & ~PHY_RESET), phy->base + EMAC_EMAC_WRAPPER_CSR2);
/* Ensure phy-reset release command is written to HW before initializing
* SGMII
*/
msleep(50);
}
static void emac_sgmii_common_reset(struct emac_adapter *adpt)
{
int ret;
emac_sgmii_reset_prepare(adpt);
emac_sgmii_link_init(adpt);
ret = emac_sgmii_init(adpt);
if (ret)
netdev_err(adpt->netdev,
"could not reinitialize internal PHY (error=%i)\n",
ret);
}
static int emac_sgmii_common_open(struct emac_adapter *adpt)
{
struct emac_sgmii *sgmii = &adpt->phy;
int ret;
if (sgmii->irq) {
/* Make sure interrupts are cleared and disabled first */
ret = emac_sgmii_irq_clear(adpt, 0xff);
if (ret)
return ret;
writel(0, sgmii->base + EMAC_SGMII_PHY_INTERRUPT_MASK);
ret = request_irq(sgmii->irq, emac_sgmii_interrupt, 0,
"emac-sgmii", adpt);
if (ret) {
netdev_err(adpt->netdev,
"could not register handler for internal PHY\n");
return ret;
}
}
return 0;
}
static void emac_sgmii_common_close(struct emac_adapter *adpt)
{
struct emac_sgmii *sgmii = &adpt->phy;
/* Make sure interrupts are disabled */
writel(0, sgmii->base + EMAC_SGMII_PHY_INTERRUPT_MASK);
free_irq(sgmii->irq, adpt);
}
/* The error interrupts are only valid after the link is up */
static int emac_sgmii_common_link_change(struct emac_adapter *adpt, bool linkup)
{
struct emac_sgmii *sgmii = &adpt->phy;
int ret;
if (linkup) {
/* Clear and enable interrupts */
ret = emac_sgmii_irq_clear(adpt, 0xff);
if (ret)
return ret;
writel(SGMII_ISR_MASK,
sgmii->base + EMAC_SGMII_PHY_INTERRUPT_MASK);
} else {
/* Disable interrupts */
writel(0, sgmii->base + EMAC_SGMII_PHY_INTERRUPT_MASK);
synchronize_irq(sgmii->irq);
}
return 0;
}
static struct sgmii_ops fsm9900_ops = {
.init = emac_sgmii_init_fsm9900,
.open = emac_sgmii_common_open,
.close = emac_sgmii_common_close,
.link_change = emac_sgmii_common_link_change,
.reset = emac_sgmii_common_reset,
};
static struct sgmii_ops qdf2432_ops = {
.init = emac_sgmii_init_qdf2432,
.open = emac_sgmii_common_open,
.close = emac_sgmii_common_close,
.link_change = emac_sgmii_common_link_change,
.reset = emac_sgmii_common_reset,
};
#ifdef CONFIG_ACPI
static struct sgmii_ops qdf2400_ops = {
.init = emac_sgmii_init_qdf2400,
.open = emac_sgmii_common_open,
.close = emac_sgmii_common_close,
.link_change = emac_sgmii_common_link_change,
.reset = emac_sgmii_common_reset,
};
#endif
static int emac_sgmii_acpi_match(struct device *dev, void *data)
{
#ifdef CONFIG_ACPI
static const struct acpi_device_id match_table[] = {
{
.id = "QCOM8071",
},
{}
};
const struct acpi_device_id *id = acpi_match_device(match_table, dev);
struct sgmii_ops **ops = data;
if (id) {
acpi_handle handle = ACPI_HANDLE(dev);
unsigned long long hrv;
acpi_status status;
status = acpi_evaluate_integer(handle, "_HRV", NULL, &hrv);
if (status) {
if (status == AE_NOT_FOUND)
/* Older versions of the QDF2432 ACPI tables do
* not have an _HRV property.
*/
hrv = 1;
else
/* Something is wrong with the tables */
return 0;
}
switch (hrv) {
case 1:
*ops = &qdf2432_ops;
return 1;
case 2:
*ops = &qdf2400_ops;
return 1;
}
}
#endif
return 0;
}
static const struct of_device_id emac_sgmii_dt_match[] = {
{
.compatible = "qcom,fsm9900-emac-sgmii",
.data = &fsm9900_ops,
},
{
.compatible = "qcom,qdf2432-emac-sgmii",
.data = &qdf2432_ops,
},
{}
};
int emac_sgmii_config(struct platform_device *pdev, struct emac_adapter *adpt)
{
struct platform_device *sgmii_pdev = NULL;
struct emac_sgmii *phy = &adpt->phy;
struct resource *res;
int ret;
if (has_acpi_companion(&pdev->dev)) {
struct device *dev;
dev = device_find_child(&pdev->dev, &phy->sgmii_ops,
emac_sgmii_acpi_match);
if (!dev) {
dev_warn(&pdev->dev, "cannot find internal phy node\n");
return 0;
}
sgmii_pdev = to_platform_device(dev);
} else {
const struct of_device_id *match;
struct device_node *np;
np = of_parse_phandle(pdev->dev.of_node, "internal-phy", 0);
if (!np) {
dev_err(&pdev->dev, "missing internal-phy property\n");
return -ENODEV;
}
sgmii_pdev = of_find_device_by_node(np);
of_node_put(np);
if (!sgmii_pdev) {
dev_err(&pdev->dev, "invalid internal-phy property\n");
return -ENODEV;
}
match = of_match_device(emac_sgmii_dt_match, &sgmii_pdev->dev);
if (!match) {
dev_err(&pdev->dev, "unrecognized internal phy node\n");
ret = -ENODEV;
goto error_put_device;
}
phy->sgmii_ops = (struct sgmii_ops *)match->data;
}
/* Base address is the first address */
res = platform_get_resource(sgmii_pdev, IORESOURCE_MEM, 0);
if (!res) {
ret = -EINVAL;
goto error_put_device;
}
phy->base = ioremap(res->start, resource_size(res));
if (!phy->base) {
ret = -ENOMEM;
goto error_put_device;
}
/* v2 SGMII has a per-lane digital digital, so parse it if it exists */
res = platform_get_resource(sgmii_pdev, IORESOURCE_MEM, 1);
if (res) {
phy->digital = ioremap(res->start, resource_size(res));
if (!phy->digital) {
ret = -ENOMEM;
goto error_unmap_base;
}
}
ret = emac_sgmii_init(adpt);
if (ret)
goto error;
emac_sgmii_link_init(adpt);
ret = platform_get_irq(sgmii_pdev, 0);
if (ret > 0)
phy->irq = ret;
/* We've remapped the addresses, so we don't need the device any
* more. of_find_device_by_node() says we should release it.
*/
put_device(&sgmii_pdev->dev);
return 0;
error:
if (phy->digital)
iounmap(phy->digital);
error_unmap_base:
iounmap(phy->base);
error_put_device:
put_device(&sgmii_pdev->dev);
return ret;
}
|
linux-master
|
drivers/net/ethernet/qualcomm/emac/emac-sgmii.c
|
// SPDX-License-Identifier: GPL-2.0-only
/* Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
*/
/* Qualcomm Technologies, Inc. EMAC PHY Controller driver.
*/
#include <linux/of_mdio.h>
#include <linux/phy.h>
#include <linux/iopoll.h>
#include <linux/acpi.h>
#include "emac.h"
/* EMAC base register offsets */
#define EMAC_MDIO_CTRL 0x001414
#define EMAC_PHY_STS 0x001418
#define EMAC_MDIO_EX_CTRL 0x001440
/* EMAC_MDIO_CTRL */
#define MDIO_MODE BIT(30)
#define MDIO_PR BIT(29)
#define MDIO_AP_EN BIT(28)
#define MDIO_BUSY BIT(27)
#define MDIO_CLK_SEL_BMSK 0x7000000
#define MDIO_CLK_SEL_SHFT 24
#define MDIO_START BIT(23)
#define SUP_PREAMBLE BIT(22)
#define MDIO_RD_NWR BIT(21)
#define MDIO_REG_ADDR_BMSK 0x1f0000
#define MDIO_REG_ADDR_SHFT 16
#define MDIO_DATA_BMSK 0xffff
#define MDIO_DATA_SHFT 0
/* EMAC_PHY_STS */
#define PHY_ADDR_BMSK 0x1f0000
#define PHY_ADDR_SHFT 16
#define MDIO_CLK_25_4 0
#define MDIO_CLK_25_28 7
#define MDIO_WAIT_TIMES 1000
#define MDIO_STATUS_DELAY_TIME 1
static int emac_mdio_read(struct mii_bus *bus, int addr, int regnum)
{
struct emac_adapter *adpt = bus->priv;
u32 reg;
emac_reg_update32(adpt->base + EMAC_PHY_STS, PHY_ADDR_BMSK,
(addr << PHY_ADDR_SHFT));
reg = SUP_PREAMBLE |
((MDIO_CLK_25_4 << MDIO_CLK_SEL_SHFT) & MDIO_CLK_SEL_BMSK) |
((regnum << MDIO_REG_ADDR_SHFT) & MDIO_REG_ADDR_BMSK) |
MDIO_START | MDIO_RD_NWR;
writel(reg, adpt->base + EMAC_MDIO_CTRL);
if (readl_poll_timeout(adpt->base + EMAC_MDIO_CTRL, reg,
!(reg & (MDIO_START | MDIO_BUSY)),
MDIO_STATUS_DELAY_TIME, MDIO_WAIT_TIMES * 100))
return -EIO;
return (reg >> MDIO_DATA_SHFT) & MDIO_DATA_BMSK;
}
static int emac_mdio_write(struct mii_bus *bus, int addr, int regnum, u16 val)
{
struct emac_adapter *adpt = bus->priv;
u32 reg;
emac_reg_update32(adpt->base + EMAC_PHY_STS, PHY_ADDR_BMSK,
(addr << PHY_ADDR_SHFT));
reg = SUP_PREAMBLE |
((MDIO_CLK_25_4 << MDIO_CLK_SEL_SHFT) & MDIO_CLK_SEL_BMSK) |
((regnum << MDIO_REG_ADDR_SHFT) & MDIO_REG_ADDR_BMSK) |
((val << MDIO_DATA_SHFT) & MDIO_DATA_BMSK) |
MDIO_START;
writel(reg, adpt->base + EMAC_MDIO_CTRL);
if (readl_poll_timeout(adpt->base + EMAC_MDIO_CTRL, reg,
!(reg & (MDIO_START | MDIO_BUSY)),
MDIO_STATUS_DELAY_TIME, MDIO_WAIT_TIMES * 100))
return -EIO;
return 0;
}
/* Configure the MDIO bus and connect the external PHY */
int emac_phy_config(struct platform_device *pdev, struct emac_adapter *adpt)
{
struct device_node *np = pdev->dev.of_node;
struct mii_bus *mii_bus;
int ret;
/* Create the mii_bus object for talking to the MDIO bus */
adpt->mii_bus = mii_bus = devm_mdiobus_alloc(&pdev->dev);
if (!mii_bus)
return -ENOMEM;
mii_bus->name = "emac-mdio";
snprintf(mii_bus->id, MII_BUS_ID_SIZE, "%s", pdev->name);
mii_bus->read = emac_mdio_read;
mii_bus->write = emac_mdio_write;
mii_bus->parent = &pdev->dev;
mii_bus->priv = adpt;
if (has_acpi_companion(&pdev->dev)) {
u32 phy_addr;
ret = mdiobus_register(mii_bus);
if (ret) {
dev_err(&pdev->dev, "could not register mdio bus\n");
return ret;
}
ret = device_property_read_u32(&pdev->dev, "phy-channel",
&phy_addr);
if (ret)
/* If we can't read a valid phy address, then assume
* that there is only one phy on this mdio bus.
*/
adpt->phydev = phy_find_first(mii_bus);
else
adpt->phydev = mdiobus_get_phy(mii_bus, phy_addr);
/* of_phy_find_device() claims a reference to the phydev,
* so we do that here manually as well. When the driver
* later unloads, it can unilaterally drop the reference
* without worrying about ACPI vs DT.
*/
if (adpt->phydev)
get_device(&adpt->phydev->mdio.dev);
} else {
struct device_node *phy_np;
ret = of_mdiobus_register(mii_bus, np);
if (ret) {
dev_err(&pdev->dev, "could not register mdio bus\n");
return ret;
}
phy_np = of_parse_phandle(np, "phy-handle", 0);
adpt->phydev = of_phy_find_device(phy_np);
of_node_put(phy_np);
}
if (!adpt->phydev) {
dev_err(&pdev->dev, "could not find external phy\n");
mdiobus_unregister(mii_bus);
return -ENODEV;
}
return 0;
}
|
linux-master
|
drivers/net/ethernet/qualcomm/emac/emac-phy.c
|
// SPDX-License-Identifier: GPL-2.0-only
/* Copyright (c) 2015-2016, The Linux Foundation. All rights reserved.
*/
/* Qualcomm Technologies, Inc. FSM9900 EMAC SGMII Controller driver.
*/
#include <linux/iopoll.h>
#include "emac.h"
/* EMAC_QSERDES register offsets */
#define EMAC_QSERDES_COM_SYS_CLK_CTRL 0x0000
#define EMAC_QSERDES_COM_PLL_CNTRL 0x0014
#define EMAC_QSERDES_COM_PLL_IP_SETI 0x0018
#define EMAC_QSERDES_COM_PLL_CP_SETI 0x0024
#define EMAC_QSERDES_COM_PLL_IP_SETP 0x0028
#define EMAC_QSERDES_COM_PLL_CP_SETP 0x002c
#define EMAC_QSERDES_COM_SYSCLK_EN_SEL 0x0038
#define EMAC_QSERDES_COM_RESETSM_CNTRL 0x0040
#define EMAC_QSERDES_COM_PLLLOCK_CMP1 0x0044
#define EMAC_QSERDES_COM_PLLLOCK_CMP2 0x0048
#define EMAC_QSERDES_COM_PLLLOCK_CMP3 0x004c
#define EMAC_QSERDES_COM_PLLLOCK_CMP_EN 0x0050
#define EMAC_QSERDES_COM_DEC_START1 0x0064
#define EMAC_QSERDES_COM_DIV_FRAC_START1 0x0098
#define EMAC_QSERDES_COM_DIV_FRAC_START2 0x009c
#define EMAC_QSERDES_COM_DIV_FRAC_START3 0x00a0
#define EMAC_QSERDES_COM_DEC_START2 0x00a4
#define EMAC_QSERDES_COM_PLL_CRCTRL 0x00ac
#define EMAC_QSERDES_COM_RESET_SM 0x00bc
#define EMAC_QSERDES_TX_BIST_MODE_LANENO 0x0100
#define EMAC_QSERDES_TX_TX_EMP_POST1_LVL 0x0108
#define EMAC_QSERDES_TX_TX_DRV_LVL 0x010c
#define EMAC_QSERDES_TX_LANE_MODE 0x0150
#define EMAC_QSERDES_TX_TRAN_DRVR_EMP_EN 0x0170
#define EMAC_QSERDES_RX_CDR_CONTROL 0x0200
#define EMAC_QSERDES_RX_CDR_CONTROL2 0x0210
#define EMAC_QSERDES_RX_RX_EQ_GAIN12 0x0230
/* EMAC_SGMII register offsets */
#define EMAC_SGMII_PHY_SERDES_START 0x0000
#define EMAC_SGMII_PHY_CMN_PWR_CTRL 0x0004
#define EMAC_SGMII_PHY_RX_PWR_CTRL 0x0008
#define EMAC_SGMII_PHY_TX_PWR_CTRL 0x000C
#define EMAC_SGMII_PHY_LANE_CTRL1 0x0018
#define EMAC_SGMII_PHY_CDR_CTRL0 0x0058
#define EMAC_SGMII_PHY_POW_DWN_CTRL0 0x0080
#define EMAC_SGMII_PHY_INTERRUPT_MASK 0x00b4
#define PLL_IPSETI(x) ((x) & 0x3f)
#define PLL_CPSETI(x) ((x) & 0xff)
#define PLL_IPSETP(x) ((x) & 0x3f)
#define PLL_CPSETP(x) ((x) & 0x1f)
#define PLL_RCTRL(x) (((x) & 0xf) << 4)
#define PLL_CCTRL(x) ((x) & 0xf)
#define LANE_MODE(x) ((x) & 0x1f)
#define SYSCLK_CM BIT(4)
#define SYSCLK_AC_COUPLE BIT(3)
#define OCP_EN BIT(5)
#define PLL_DIV_FFEN BIT(2)
#define PLL_DIV_ORD BIT(1)
#define SYSCLK_SEL_CMOS BIT(3)
#define FRQ_TUNE_MODE BIT(4)
#define PLLLOCK_CMP_EN BIT(0)
#define DEC_START1_MUX BIT(7)
#define DEC_START1(x) ((x) & 0x7f)
#define DIV_FRAC_START_MUX BIT(7)
#define DIV_FRAC_START(x) ((x) & 0x7f)
#define DIV_FRAC_START3_MUX BIT(4)
#define DIV_FRAC_START3(x) ((x) & 0xf)
#define DEC_START2_MUX BIT(1)
#define DEC_START2 BIT(0)
#define READY BIT(5)
#define TX_EMP_POST1_LVL_MUX BIT(5)
#define TX_EMP_POST1_LVL(x) ((x) & 0x1f)
#define TX_DRV_LVL_MUX BIT(4)
#define TX_DRV_LVL(x) ((x) & 0xf)
#define EMP_EN_MUX BIT(1)
#define EMP_EN BIT(0)
#define SECONDORDERENABLE BIT(6)
#define FIRSTORDER_THRESH(x) (((x) & 0x7) << 3)
#define SECONDORDERGAIN(x) ((x) & 0x7)
#define RX_EQ_GAIN2(x) (((x) & 0xf) << 4)
#define RX_EQ_GAIN1(x) ((x) & 0xf)
#define SERDES_START BIT(0)
#define BIAS_EN BIT(6)
#define PLL_EN BIT(5)
#define SYSCLK_EN BIT(4)
#define CLKBUF_L_EN BIT(3)
#define PLL_TXCLK_EN BIT(1)
#define PLL_RXCLK_EN BIT(0)
#define L0_RX_SIGDET_EN BIT(7)
#define L0_RX_TERM_MODE(x) (((x) & 3) << 4)
#define L0_RX_I_EN BIT(1)
#define L0_TX_EN BIT(5)
#define L0_CLKBUF_EN BIT(4)
#define L0_TRAN_BIAS_EN BIT(1)
#define L0_RX_EQUALIZE_ENABLE BIT(6)
#define L0_RESET_TSYNC_EN BIT(4)
#define L0_DRV_LVL(x) ((x) & 0xf)
#define PWRDN_B BIT(0)
#define CDR_MAX_CNT(x) ((x) & 0xff)
#define PLLLOCK_CMP(x) ((x) & 0xff)
#define SERDES_START_WAIT_TIMES 100
struct emac_reg_write {
unsigned int offset;
u32 val;
};
static void emac_reg_write_all(void __iomem *base,
const struct emac_reg_write *itr, size_t size)
{
size_t i;
for (i = 0; i < size; ++itr, ++i)
writel(itr->val, base + itr->offset);
}
static const struct emac_reg_write physical_coding_sublayer_programming[] = {
{EMAC_SGMII_PHY_CDR_CTRL0, CDR_MAX_CNT(15)},
{EMAC_SGMII_PHY_POW_DWN_CTRL0, PWRDN_B},
{EMAC_SGMII_PHY_CMN_PWR_CTRL,
BIAS_EN | SYSCLK_EN | CLKBUF_L_EN | PLL_TXCLK_EN | PLL_RXCLK_EN},
{EMAC_SGMII_PHY_TX_PWR_CTRL, L0_TX_EN | L0_CLKBUF_EN | L0_TRAN_BIAS_EN},
{EMAC_SGMII_PHY_RX_PWR_CTRL,
L0_RX_SIGDET_EN | L0_RX_TERM_MODE(1) | L0_RX_I_EN},
{EMAC_SGMII_PHY_CMN_PWR_CTRL,
BIAS_EN | PLL_EN | SYSCLK_EN | CLKBUF_L_EN | PLL_TXCLK_EN |
PLL_RXCLK_EN},
{EMAC_SGMII_PHY_LANE_CTRL1,
L0_RX_EQUALIZE_ENABLE | L0_RESET_TSYNC_EN | L0_DRV_LVL(15)},
};
static const struct emac_reg_write sysclk_refclk_setting[] = {
{EMAC_QSERDES_COM_SYSCLK_EN_SEL, SYSCLK_SEL_CMOS},
{EMAC_QSERDES_COM_SYS_CLK_CTRL, SYSCLK_CM | SYSCLK_AC_COUPLE},
};
static const struct emac_reg_write pll_setting[] = {
{EMAC_QSERDES_COM_PLL_IP_SETI, PLL_IPSETI(1)},
{EMAC_QSERDES_COM_PLL_CP_SETI, PLL_CPSETI(59)},
{EMAC_QSERDES_COM_PLL_IP_SETP, PLL_IPSETP(10)},
{EMAC_QSERDES_COM_PLL_CP_SETP, PLL_CPSETP(9)},
{EMAC_QSERDES_COM_PLL_CRCTRL, PLL_RCTRL(15) | PLL_CCTRL(11)},
{EMAC_QSERDES_COM_PLL_CNTRL, OCP_EN | PLL_DIV_FFEN | PLL_DIV_ORD},
{EMAC_QSERDES_COM_DEC_START1, DEC_START1_MUX | DEC_START1(2)},
{EMAC_QSERDES_COM_DEC_START2, DEC_START2_MUX | DEC_START2},
{EMAC_QSERDES_COM_DIV_FRAC_START1,
DIV_FRAC_START_MUX | DIV_FRAC_START(85)},
{EMAC_QSERDES_COM_DIV_FRAC_START2,
DIV_FRAC_START_MUX | DIV_FRAC_START(42)},
{EMAC_QSERDES_COM_DIV_FRAC_START3,
DIV_FRAC_START3_MUX | DIV_FRAC_START3(3)},
{EMAC_QSERDES_COM_PLLLOCK_CMP1, PLLLOCK_CMP(43)},
{EMAC_QSERDES_COM_PLLLOCK_CMP2, PLLLOCK_CMP(104)},
{EMAC_QSERDES_COM_PLLLOCK_CMP3, PLLLOCK_CMP(0)},
{EMAC_QSERDES_COM_PLLLOCK_CMP_EN, PLLLOCK_CMP_EN},
{EMAC_QSERDES_COM_RESETSM_CNTRL, FRQ_TUNE_MODE},
};
static const struct emac_reg_write cdr_setting[] = {
{EMAC_QSERDES_RX_CDR_CONTROL,
SECONDORDERENABLE | FIRSTORDER_THRESH(3) | SECONDORDERGAIN(2)},
{EMAC_QSERDES_RX_CDR_CONTROL2,
SECONDORDERENABLE | FIRSTORDER_THRESH(3) | SECONDORDERGAIN(4)},
};
static const struct emac_reg_write tx_rx_setting[] = {
{EMAC_QSERDES_TX_BIST_MODE_LANENO, 0},
{EMAC_QSERDES_TX_TX_DRV_LVL, TX_DRV_LVL_MUX | TX_DRV_LVL(15)},
{EMAC_QSERDES_TX_TRAN_DRVR_EMP_EN, EMP_EN_MUX | EMP_EN},
{EMAC_QSERDES_TX_TX_EMP_POST1_LVL,
TX_EMP_POST1_LVL_MUX | TX_EMP_POST1_LVL(1)},
{EMAC_QSERDES_RX_RX_EQ_GAIN12, RX_EQ_GAIN2(15) | RX_EQ_GAIN1(15)},
{EMAC_QSERDES_TX_LANE_MODE, LANE_MODE(8)},
};
int emac_sgmii_init_fsm9900(struct emac_adapter *adpt)
{
struct emac_sgmii *phy = &adpt->phy;
unsigned int i;
emac_reg_write_all(phy->base, physical_coding_sublayer_programming,
ARRAY_SIZE(physical_coding_sublayer_programming));
emac_reg_write_all(phy->base, sysclk_refclk_setting,
ARRAY_SIZE(sysclk_refclk_setting));
emac_reg_write_all(phy->base, pll_setting, ARRAY_SIZE(pll_setting));
emac_reg_write_all(phy->base, cdr_setting, ARRAY_SIZE(cdr_setting));
emac_reg_write_all(phy->base, tx_rx_setting, ARRAY_SIZE(tx_rx_setting));
/* Power up the Ser/Des engine */
writel(SERDES_START, phy->base + EMAC_SGMII_PHY_SERDES_START);
for (i = 0; i < SERDES_START_WAIT_TIMES; i++) {
if (readl(phy->base + EMAC_QSERDES_COM_RESET_SM) & READY)
break;
usleep_range(100, 200);
}
if (i == SERDES_START_WAIT_TIMES) {
netdev_err(adpt->netdev, "error: ser/des failed to start\n");
return -EIO;
}
/* Mask out all the SGMII Interrupt */
writel(0, phy->base + EMAC_SGMII_PHY_INTERRUPT_MASK);
return 0;
}
|
linux-master
|
drivers/net/ethernet/qualcomm/emac/emac-sgmii-fsm9900.c
|
// SPDX-License-Identifier: GPL-2.0-only
/* Copyright (c) 2016, The Linux Foundation. All rights reserved.
*/
#include <linux/ethtool.h>
#include <linux/phy.h>
#include "emac.h"
static const char * const emac_ethtool_stat_strings[] = {
"rx_ok",
"rx_bcast",
"rx_mcast",
"rx_pause",
"rx_ctrl",
"rx_fcs_err",
"rx_len_err",
"rx_byte_cnt",
"rx_runt",
"rx_frag",
"rx_sz_64",
"rx_sz_65_127",
"rx_sz_128_255",
"rx_sz_256_511",
"rx_sz_512_1023",
"rx_sz_1024_1518",
"rx_sz_1519_max",
"rx_sz_ov",
"rx_rxf_ov",
"rx_align_err",
"rx_bcast_byte_cnt",
"rx_mcast_byte_cnt",
"rx_err_addr",
"rx_crc_align",
"rx_jabbers",
"tx_ok",
"tx_bcast",
"tx_mcast",
"tx_pause",
"tx_exc_defer",
"tx_ctrl",
"tx_defer",
"tx_byte_cnt",
"tx_sz_64",
"tx_sz_65_127",
"tx_sz_128_255",
"tx_sz_256_511",
"tx_sz_512_1023",
"tx_sz_1024_1518",
"tx_sz_1519_max",
"tx_1_col",
"tx_2_col",
"tx_late_col",
"tx_abort_col",
"tx_underrun",
"tx_rd_eop",
"tx_len_err",
"tx_trunc",
"tx_bcast_byte",
"tx_mcast_byte",
"tx_col",
};
#define EMAC_STATS_LEN ARRAY_SIZE(emac_ethtool_stat_strings)
static u32 emac_get_msglevel(struct net_device *netdev)
{
struct emac_adapter *adpt = netdev_priv(netdev);
return adpt->msg_enable;
}
static void emac_set_msglevel(struct net_device *netdev, u32 data)
{
struct emac_adapter *adpt = netdev_priv(netdev);
adpt->msg_enable = data;
}
static int emac_get_sset_count(struct net_device *netdev, int sset)
{
switch (sset) {
case ETH_SS_PRIV_FLAGS:
return 1;
case ETH_SS_STATS:
return EMAC_STATS_LEN;
default:
return -EOPNOTSUPP;
}
}
static void emac_get_strings(struct net_device *netdev, u32 stringset, u8 *data)
{
unsigned int i;
switch (stringset) {
case ETH_SS_PRIV_FLAGS:
strcpy(data, "single-pause-mode");
break;
case ETH_SS_STATS:
for (i = 0; i < EMAC_STATS_LEN; i++) {
strscpy(data, emac_ethtool_stat_strings[i],
ETH_GSTRING_LEN);
data += ETH_GSTRING_LEN;
}
break;
}
}
static void emac_get_ethtool_stats(struct net_device *netdev,
struct ethtool_stats *stats,
u64 *data)
{
struct emac_adapter *adpt = netdev_priv(netdev);
spin_lock(&adpt->stats.lock);
emac_update_hw_stats(adpt);
memcpy(data, &adpt->stats, EMAC_STATS_LEN * sizeof(u64));
spin_unlock(&adpt->stats.lock);
}
static int emac_nway_reset(struct net_device *netdev)
{
struct phy_device *phydev = netdev->phydev;
if (!phydev)
return -ENODEV;
return genphy_restart_aneg(phydev);
}
static void emac_get_ringparam(struct net_device *netdev,
struct ethtool_ringparam *ring,
struct kernel_ethtool_ringparam *kernel_ring,
struct netlink_ext_ack *extack)
{
struct emac_adapter *adpt = netdev_priv(netdev);
ring->rx_max_pending = EMAC_MAX_RX_DESCS;
ring->tx_max_pending = EMAC_MAX_TX_DESCS;
ring->rx_pending = adpt->rx_desc_cnt;
ring->tx_pending = adpt->tx_desc_cnt;
}
static int emac_set_ringparam(struct net_device *netdev,
struct ethtool_ringparam *ring,
struct kernel_ethtool_ringparam *kernel_ring,
struct netlink_ext_ack *extack)
{
struct emac_adapter *adpt = netdev_priv(netdev);
/* We don't have separate queues/rings for small/large frames, so
* reject any attempt to specify those values separately.
*/
if (ring->rx_mini_pending || ring->rx_jumbo_pending)
return -EINVAL;
adpt->tx_desc_cnt =
clamp_val(ring->tx_pending, EMAC_MIN_TX_DESCS, EMAC_MAX_TX_DESCS);
adpt->rx_desc_cnt =
clamp_val(ring->rx_pending, EMAC_MIN_RX_DESCS, EMAC_MAX_RX_DESCS);
if (netif_running(netdev))
return emac_reinit_locked(adpt);
return 0;
}
static void emac_get_pauseparam(struct net_device *netdev,
struct ethtool_pauseparam *pause)
{
struct emac_adapter *adpt = netdev_priv(netdev);
pause->autoneg = adpt->automatic ? AUTONEG_ENABLE : AUTONEG_DISABLE;
pause->rx_pause = adpt->rx_flow_control ? 1 : 0;
pause->tx_pause = adpt->tx_flow_control ? 1 : 0;
}
static int emac_set_pauseparam(struct net_device *netdev,
struct ethtool_pauseparam *pause)
{
struct emac_adapter *adpt = netdev_priv(netdev);
adpt->automatic = pause->autoneg == AUTONEG_ENABLE;
adpt->rx_flow_control = pause->rx_pause != 0;
adpt->tx_flow_control = pause->tx_pause != 0;
if (netif_running(netdev))
return emac_reinit_locked(adpt);
return 0;
}
/* Selected registers that might want to track during runtime. */
static const u16 emac_regs[] = {
EMAC_DMA_MAS_CTRL,
EMAC_MAC_CTRL,
EMAC_TXQ_CTRL_0,
EMAC_RXQ_CTRL_0,
EMAC_DMA_CTRL,
EMAC_INT_MASK,
EMAC_AXI_MAST_CTRL,
EMAC_CORE_HW_VERSION,
EMAC_MISC_CTRL,
};
/* Every time emac_regs[] above is changed, increase this version number. */
#define EMAC_REGS_VERSION 0
#define EMAC_MAX_REG_SIZE ARRAY_SIZE(emac_regs)
static void emac_get_regs(struct net_device *netdev,
struct ethtool_regs *regs, void *buff)
{
struct emac_adapter *adpt = netdev_priv(netdev);
u32 *val = buff;
unsigned int i;
regs->version = EMAC_REGS_VERSION;
regs->len = EMAC_MAX_REG_SIZE * sizeof(u32);
for (i = 0; i < EMAC_MAX_REG_SIZE; i++)
val[i] = readl(adpt->base + emac_regs[i]);
}
static int emac_get_regs_len(struct net_device *netdev)
{
return EMAC_MAX_REG_SIZE * sizeof(u32);
}
#define EMAC_PRIV_ENABLE_SINGLE_PAUSE BIT(0)
static int emac_set_priv_flags(struct net_device *netdev, u32 flags)
{
struct emac_adapter *adpt = netdev_priv(netdev);
adpt->single_pause_mode = !!(flags & EMAC_PRIV_ENABLE_SINGLE_PAUSE);
if (netif_running(netdev))
return emac_reinit_locked(adpt);
return 0;
}
static u32 emac_get_priv_flags(struct net_device *netdev)
{
struct emac_adapter *adpt = netdev_priv(netdev);
return adpt->single_pause_mode ? EMAC_PRIV_ENABLE_SINGLE_PAUSE : 0;
}
static const struct ethtool_ops emac_ethtool_ops = {
.get_link_ksettings = phy_ethtool_get_link_ksettings,
.set_link_ksettings = phy_ethtool_set_link_ksettings,
.get_msglevel = emac_get_msglevel,
.set_msglevel = emac_set_msglevel,
.get_sset_count = emac_get_sset_count,
.get_strings = emac_get_strings,
.get_ethtool_stats = emac_get_ethtool_stats,
.get_ringparam = emac_get_ringparam,
.set_ringparam = emac_set_ringparam,
.get_pauseparam = emac_get_pauseparam,
.set_pauseparam = emac_set_pauseparam,
.nway_reset = emac_nway_reset,
.get_link = ethtool_op_get_link,
.get_regs_len = emac_get_regs_len,
.get_regs = emac_get_regs,
.set_priv_flags = emac_set_priv_flags,
.get_priv_flags = emac_get_priv_flags,
};
void emac_set_ethtool_ops(struct net_device *netdev)
{
netdev->ethtool_ops = &emac_ethtool_ops;
}
|
linux-master
|
drivers/net/ethernet/qualcomm/emac/emac-ethtool.c
|
// SPDX-License-Identifier: GPL-2.0-only
/* Altera TSE SGDMA and MSGDMA Linux driver
* Copyright (C) 2014 Altera Corporation. All rights reserved
*/
#include <linux/list.h>
#include "altera_utils.h"
#include "altera_tse.h"
#include "altera_sgdmahw.h"
#include "altera_sgdma.h"
static void sgdma_setup_descrip(struct sgdma_descrip __iomem *desc,
struct sgdma_descrip __iomem *ndesc,
dma_addr_t ndesc_phys,
dma_addr_t raddr,
dma_addr_t waddr,
u16 length,
int generate_eop,
int rfixed,
int wfixed);
static int sgdma_async_write(struct altera_tse_private *priv,
struct sgdma_descrip __iomem *desc);
static int sgdma_async_read(struct altera_tse_private *priv);
static dma_addr_t
sgdma_txphysaddr(struct altera_tse_private *priv,
struct sgdma_descrip __iomem *desc);
static dma_addr_t
sgdma_rxphysaddr(struct altera_tse_private *priv,
struct sgdma_descrip __iomem *desc);
static int sgdma_txbusy(struct altera_tse_private *priv);
static int sgdma_rxbusy(struct altera_tse_private *priv);
static void
queue_tx(struct altera_tse_private *priv, struct tse_buffer *buffer);
static void
queue_rx(struct altera_tse_private *priv, struct tse_buffer *buffer);
static struct tse_buffer *
dequeue_tx(struct altera_tse_private *priv);
static struct tse_buffer *
dequeue_rx(struct altera_tse_private *priv);
static struct tse_buffer *
queue_rx_peekhead(struct altera_tse_private *priv);
int sgdma_initialize(struct altera_tse_private *priv)
{
priv->txctrlreg = SGDMA_CTRLREG_ILASTD |
SGDMA_CTRLREG_INTEN;
priv->rxctrlreg = SGDMA_CTRLREG_IDESCRIP |
SGDMA_CTRLREG_INTEN |
SGDMA_CTRLREG_ILASTD;
INIT_LIST_HEAD(&priv->txlisthd);
INIT_LIST_HEAD(&priv->rxlisthd);
priv->rxdescphys = (dma_addr_t) 0;
priv->txdescphys = (dma_addr_t) 0;
priv->rxdescphys = dma_map_single(priv->device,
(void __force *)priv->rx_dma_desc,
priv->rxdescmem, DMA_BIDIRECTIONAL);
if (dma_mapping_error(priv->device, priv->rxdescphys)) {
sgdma_uninitialize(priv);
netdev_err(priv->dev, "error mapping rx descriptor memory\n");
return -EINVAL;
}
priv->txdescphys = dma_map_single(priv->device,
(void __force *)priv->tx_dma_desc,
priv->txdescmem, DMA_TO_DEVICE);
if (dma_mapping_error(priv->device, priv->txdescphys)) {
sgdma_uninitialize(priv);
netdev_err(priv->dev, "error mapping tx descriptor memory\n");
return -EINVAL;
}
/* Initialize descriptor memory to all 0's, sync memory to cache */
memset_io(priv->tx_dma_desc, 0, priv->txdescmem);
memset_io(priv->rx_dma_desc, 0, priv->rxdescmem);
dma_sync_single_for_device(priv->device, priv->txdescphys,
priv->txdescmem, DMA_TO_DEVICE);
dma_sync_single_for_device(priv->device, priv->rxdescphys,
priv->rxdescmem, DMA_TO_DEVICE);
return 0;
}
void sgdma_uninitialize(struct altera_tse_private *priv)
{
if (priv->rxdescphys)
dma_unmap_single(priv->device, priv->rxdescphys,
priv->rxdescmem, DMA_BIDIRECTIONAL);
if (priv->txdescphys)
dma_unmap_single(priv->device, priv->txdescphys,
priv->txdescmem, DMA_TO_DEVICE);
}
/* This function resets the SGDMA controller and clears the
* descriptor memory used for transmits and receives.
*/
void sgdma_reset(struct altera_tse_private *priv)
{
/* Initialize descriptor memory to 0 */
memset_io(priv->tx_dma_desc, 0, priv->txdescmem);
memset_io(priv->rx_dma_desc, 0, priv->rxdescmem);
csrwr32(SGDMA_CTRLREG_RESET, priv->tx_dma_csr, sgdma_csroffs(control));
csrwr32(0, priv->tx_dma_csr, sgdma_csroffs(control));
csrwr32(SGDMA_CTRLREG_RESET, priv->rx_dma_csr, sgdma_csroffs(control));
csrwr32(0, priv->rx_dma_csr, sgdma_csroffs(control));
}
/* For SGDMA, interrupts remain enabled after initially enabling,
* so no need to provide implementations for abstract enable
* and disable
*/
void sgdma_enable_rxirq(struct altera_tse_private *priv)
{
}
void sgdma_enable_txirq(struct altera_tse_private *priv)
{
}
void sgdma_disable_rxirq(struct altera_tse_private *priv)
{
}
void sgdma_disable_txirq(struct altera_tse_private *priv)
{
}
void sgdma_clear_rxirq(struct altera_tse_private *priv)
{
tse_set_bit(priv->rx_dma_csr, sgdma_csroffs(control),
SGDMA_CTRLREG_CLRINT);
}
void sgdma_clear_txirq(struct altera_tse_private *priv)
{
tse_set_bit(priv->tx_dma_csr, sgdma_csroffs(control),
SGDMA_CTRLREG_CLRINT);
}
/* transmits buffer through SGDMA. Returns number of buffers
* transmitted, 0 if not possible.
*
* tx_lock is held by the caller
*/
int sgdma_tx_buffer(struct altera_tse_private *priv, struct tse_buffer *buffer)
{
struct sgdma_descrip __iomem *descbase =
(struct sgdma_descrip __iomem *)priv->tx_dma_desc;
struct sgdma_descrip __iomem *cdesc = &descbase[0];
struct sgdma_descrip __iomem *ndesc = &descbase[1];
/* wait 'til the tx sgdma is ready for the next transmit request */
if (sgdma_txbusy(priv))
return 0;
sgdma_setup_descrip(cdesc, /* current descriptor */
ndesc, /* next descriptor */
sgdma_txphysaddr(priv, ndesc),
buffer->dma_addr, /* address of packet to xmit */
0, /* write addr 0 for tx dma */
buffer->len, /* length of packet */
SGDMA_CONTROL_EOP, /* Generate EOP */
0, /* read fixed */
SGDMA_CONTROL_WR_FIXED); /* Generate SOP */
sgdma_async_write(priv, cdesc);
/* enqueue the request to the pending transmit queue */
queue_tx(priv, buffer);
return 1;
}
/* tx_lock held to protect access to queued tx list
*/
u32 sgdma_tx_completions(struct altera_tse_private *priv)
{
u32 ready = 0;
if (!sgdma_txbusy(priv) &&
((csrrd8(priv->tx_dma_desc, sgdma_descroffs(control))
& SGDMA_CONTROL_HW_OWNED) == 0) &&
(dequeue_tx(priv))) {
ready = 1;
}
return ready;
}
void sgdma_start_rxdma(struct altera_tse_private *priv)
{
sgdma_async_read(priv);
}
void sgdma_add_rx_desc(struct altera_tse_private *priv,
struct tse_buffer *rxbuffer)
{
queue_rx(priv, rxbuffer);
}
/* status is returned on upper 16 bits,
* length is returned in lower 16 bits
*/
u32 sgdma_rx_status(struct altera_tse_private *priv)
{
struct sgdma_descrip __iomem *base =
(struct sgdma_descrip __iomem *)priv->rx_dma_desc;
struct sgdma_descrip __iomem *desc = NULL;
struct tse_buffer *rxbuffer = NULL;
unsigned int rxstatus = 0;
u32 sts = csrrd32(priv->rx_dma_csr, sgdma_csroffs(status));
desc = &base[0];
if (sts & SGDMA_STSREG_EOP) {
unsigned int pktlength = 0;
unsigned int pktstatus = 0;
dma_sync_single_for_cpu(priv->device,
priv->rxdescphys,
SGDMA_DESC_LEN,
DMA_FROM_DEVICE);
pktlength = csrrd16(desc, sgdma_descroffs(bytes_xferred));
pktstatus = csrrd8(desc, sgdma_descroffs(status));
rxstatus = pktstatus & ~SGDMA_STATUS_EOP;
rxstatus = rxstatus << 16;
rxstatus |= (pktlength & 0xffff);
if (rxstatus) {
csrwr8(0, desc, sgdma_descroffs(status));
rxbuffer = dequeue_rx(priv);
if (rxbuffer == NULL)
netdev_info(priv->dev,
"sgdma rx and rx queue empty!\n");
/* Clear control */
csrwr32(0, priv->rx_dma_csr, sgdma_csroffs(control));
/* clear status */
csrwr32(0xf, priv->rx_dma_csr, sgdma_csroffs(status));
/* kick the rx sgdma after reaping this descriptor */
sgdma_async_read(priv);
} else {
/* If the SGDMA indicated an end of packet on recv,
* then it's expected that the rxstatus from the
* descriptor is non-zero - meaning a valid packet
* with a nonzero length, or an error has been
* indicated. if not, then all we can do is signal
* an error and return no packet received. Most likely
* there is a system design error, or an error in the
* underlying kernel (cache or cache management problem)
*/
netdev_err(priv->dev,
"SGDMA RX Error Info: %x, %x, %x\n",
sts, csrrd8(desc, sgdma_descroffs(status)),
rxstatus);
}
} else if (sts == 0) {
sgdma_async_read(priv);
}
return rxstatus;
}
/* Private functions */
static void sgdma_setup_descrip(struct sgdma_descrip __iomem *desc,
struct sgdma_descrip __iomem *ndesc,
dma_addr_t ndesc_phys,
dma_addr_t raddr,
dma_addr_t waddr,
u16 length,
int generate_eop,
int rfixed,
int wfixed)
{
/* Clear the next descriptor as not owned by hardware */
u32 ctrl = csrrd8(ndesc, sgdma_descroffs(control));
ctrl &= ~SGDMA_CONTROL_HW_OWNED;
csrwr8(ctrl, ndesc, sgdma_descroffs(control));
ctrl = SGDMA_CONTROL_HW_OWNED;
ctrl |= generate_eop;
ctrl |= rfixed;
ctrl |= wfixed;
/* Channel is implicitly zero, initialized to 0 by default */
csrwr32(lower_32_bits(raddr), desc, sgdma_descroffs(raddr));
csrwr32(lower_32_bits(waddr), desc, sgdma_descroffs(waddr));
csrwr32(0, desc, sgdma_descroffs(pad1));
csrwr32(0, desc, sgdma_descroffs(pad2));
csrwr32(lower_32_bits(ndesc_phys), desc, sgdma_descroffs(next));
csrwr8(ctrl, desc, sgdma_descroffs(control));
csrwr8(0, desc, sgdma_descroffs(status));
csrwr8(0, desc, sgdma_descroffs(wburst));
csrwr8(0, desc, sgdma_descroffs(rburst));
csrwr16(length, desc, sgdma_descroffs(bytes));
csrwr16(0, desc, sgdma_descroffs(bytes_xferred));
}
/* If hardware is busy, don't restart async read.
* if status register is 0 - meaning initial state, restart async read,
* probably for the first time when populating a receive buffer.
* If read status indicate not busy and a status, restart the async
* DMA read.
*/
static int sgdma_async_read(struct altera_tse_private *priv)
{
struct sgdma_descrip __iomem *descbase =
(struct sgdma_descrip __iomem *)priv->rx_dma_desc;
struct sgdma_descrip __iomem *cdesc = &descbase[0];
struct sgdma_descrip __iomem *ndesc = &descbase[1];
struct tse_buffer *rxbuffer = NULL;
if (!sgdma_rxbusy(priv)) {
rxbuffer = queue_rx_peekhead(priv);
if (rxbuffer == NULL) {
netdev_err(priv->dev, "no rx buffers available\n");
return 0;
}
sgdma_setup_descrip(cdesc, /* current descriptor */
ndesc, /* next descriptor */
sgdma_rxphysaddr(priv, ndesc),
0, /* read addr 0 for rx dma */
rxbuffer->dma_addr, /* write addr for rx dma */
0, /* read 'til EOP */
0, /* EOP: NA for rx dma */
0, /* read fixed: NA for rx dma */
0); /* SOP: NA for rx DMA */
dma_sync_single_for_device(priv->device,
priv->rxdescphys,
SGDMA_DESC_LEN,
DMA_TO_DEVICE);
csrwr32(lower_32_bits(sgdma_rxphysaddr(priv, cdesc)),
priv->rx_dma_csr,
sgdma_csroffs(next_descrip));
csrwr32((priv->rxctrlreg | SGDMA_CTRLREG_START),
priv->rx_dma_csr,
sgdma_csroffs(control));
return 1;
}
return 0;
}
static int sgdma_async_write(struct altera_tse_private *priv,
struct sgdma_descrip __iomem *desc)
{
if (sgdma_txbusy(priv))
return 0;
/* clear control and status */
csrwr32(0, priv->tx_dma_csr, sgdma_csroffs(control));
csrwr32(0x1f, priv->tx_dma_csr, sgdma_csroffs(status));
dma_sync_single_for_device(priv->device, priv->txdescphys,
SGDMA_DESC_LEN, DMA_TO_DEVICE);
csrwr32(lower_32_bits(sgdma_txphysaddr(priv, desc)),
priv->tx_dma_csr,
sgdma_csroffs(next_descrip));
csrwr32((priv->txctrlreg | SGDMA_CTRLREG_START),
priv->tx_dma_csr,
sgdma_csroffs(control));
return 1;
}
static dma_addr_t
sgdma_txphysaddr(struct altera_tse_private *priv,
struct sgdma_descrip __iomem *desc)
{
dma_addr_t paddr = priv->txdescmem_busaddr;
uintptr_t offs = (uintptr_t)desc - (uintptr_t)priv->tx_dma_desc;
return (dma_addr_t)((uintptr_t)paddr + offs);
}
static dma_addr_t
sgdma_rxphysaddr(struct altera_tse_private *priv,
struct sgdma_descrip __iomem *desc)
{
dma_addr_t paddr = priv->rxdescmem_busaddr;
uintptr_t offs = (uintptr_t)desc - (uintptr_t)priv->rx_dma_desc;
return (dma_addr_t)((uintptr_t)paddr + offs);
}
#define list_remove_head(list, entry, type, member) \
do { \
entry = NULL; \
if (!list_empty(list)) { \
entry = list_entry((list)->next, type, member); \
list_del_init(&entry->member); \
} \
} while (0)
#define list_peek_head(list, entry, type, member) \
do { \
entry = NULL; \
if (!list_empty(list)) { \
entry = list_entry((list)->next, type, member); \
} \
} while (0)
/* adds a tse_buffer to the tail of a tx buffer list.
* assumes the caller is managing and holding a mutual exclusion
* primitive to avoid simultaneous pushes/pops to the list.
*/
static void
queue_tx(struct altera_tse_private *priv, struct tse_buffer *buffer)
{
list_add_tail(&buffer->lh, &priv->txlisthd);
}
/* adds a tse_buffer to the tail of a rx buffer list
* assumes the caller is managing and holding a mutual exclusion
* primitive to avoid simultaneous pushes/pops to the list.
*/
static void
queue_rx(struct altera_tse_private *priv, struct tse_buffer *buffer)
{
list_add_tail(&buffer->lh, &priv->rxlisthd);
}
/* dequeues a tse_buffer from the transmit buffer list, otherwise
* returns NULL if empty.
* assumes the caller is managing and holding a mutual exclusion
* primitive to avoid simultaneous pushes/pops to the list.
*/
static struct tse_buffer *
dequeue_tx(struct altera_tse_private *priv)
{
struct tse_buffer *buffer = NULL;
list_remove_head(&priv->txlisthd, buffer, struct tse_buffer, lh);
return buffer;
}
/* dequeues a tse_buffer from the receive buffer list, otherwise
* returns NULL if empty
* assumes the caller is managing and holding a mutual exclusion
* primitive to avoid simultaneous pushes/pops to the list.
*/
static struct tse_buffer *
dequeue_rx(struct altera_tse_private *priv)
{
struct tse_buffer *buffer = NULL;
list_remove_head(&priv->rxlisthd, buffer, struct tse_buffer, lh);
return buffer;
}
/* dequeues a tse_buffer from the receive buffer list, otherwise
* returns NULL if empty
* assumes the caller is managing and holding a mutual exclusion
* primitive to avoid simultaneous pushes/pops to the list while the
* head is being examined.
*/
static struct tse_buffer *
queue_rx_peekhead(struct altera_tse_private *priv)
{
struct tse_buffer *buffer = NULL;
list_peek_head(&priv->rxlisthd, buffer, struct tse_buffer, lh);
return buffer;
}
/* check and return rx sgdma status without polling
*/
static int sgdma_rxbusy(struct altera_tse_private *priv)
{
return csrrd32(priv->rx_dma_csr, sgdma_csroffs(status))
& SGDMA_STSREG_BUSY;
}
/* waits for the tx sgdma to finish it's current operation, returns 0
* when it transitions to nonbusy, returns 1 if the operation times out
*/
static int sgdma_txbusy(struct altera_tse_private *priv)
{
int delay = 0;
/* if DMA is busy, wait for current transaction to finish */
while ((csrrd32(priv->tx_dma_csr, sgdma_csroffs(status))
& SGDMA_STSREG_BUSY) && (delay++ < 100))
udelay(1);
if (csrrd32(priv->tx_dma_csr, sgdma_csroffs(status))
& SGDMA_STSREG_BUSY) {
netdev_err(priv->dev, "timeout waiting for tx dma\n");
return 1;
}
return 0;
}
|
linux-master
|
drivers/net/ethernet/altera/altera_sgdma.c
|
// SPDX-License-Identifier: GPL-2.0-only
/* Altera Triple-Speed Ethernet MAC driver
* Copyright (C) 2008-2014 Altera Corporation. All rights reserved
*
* Contributors:
* Dalon Westergreen
* Thomas Chou
* Ian Abbott
* Yuriy Kozlov
* Tobias Klauser
* Andriy Smolskyy
* Roman Bulgakov
* Dmytro Mytarchuk
* Matthew Gerlach
*
* Original driver contributed by SLS.
* Major updates contributed by GlobalLogic
*/
#include <linux/atomic.h>
#include <linux/delay.h>
#include <linux/etherdevice.h>
#include <linux/if_vlan.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mii.h>
#include <linux/mdio/mdio-regmap.h>
#include <linux/netdevice.h>
#include <linux/of_device.h>
#include <linux/of_mdio.h>
#include <linux/of_net.h>
#include <linux/of_platform.h>
#include <linux/pcs-lynx.h>
#include <linux/phy.h>
#include <linux/platform_device.h>
#include <linux/regmap.h>
#include <linux/skbuff.h>
#include <asm/cacheflush.h>
#include "altera_utils.h"
#include "altera_tse.h"
#include "altera_sgdma.h"
#include "altera_msgdma.h"
static atomic_t instance_count = ATOMIC_INIT(~0);
/* Module parameters */
static int debug = -1;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Message Level (-1: default, 0: no output, 16: all)");
static const u32 default_msg_level = (NETIF_MSG_DRV | NETIF_MSG_PROBE |
NETIF_MSG_LINK | NETIF_MSG_IFUP |
NETIF_MSG_IFDOWN);
#define RX_DESCRIPTORS 64
static int dma_rx_num = RX_DESCRIPTORS;
module_param(dma_rx_num, int, 0644);
MODULE_PARM_DESC(dma_rx_num, "Number of descriptors in the RX list");
#define TX_DESCRIPTORS 64
static int dma_tx_num = TX_DESCRIPTORS;
module_param(dma_tx_num, int, 0644);
MODULE_PARM_DESC(dma_tx_num, "Number of descriptors in the TX list");
#define POLL_PHY (-1)
/* Make sure DMA buffer size is larger than the max frame size
* plus some alignment offset and a VLAN header. If the max frame size is
* 1518, a VLAN header would be additional 4 bytes and additional
* headroom for alignment is 2 bytes, 2048 is just fine.
*/
#define ALTERA_RXDMABUFFER_SIZE 2048
/* Allow network stack to resume queuing packets after we've
* finished transmitting at least 1/4 of the packets in the queue.
*/
#define TSE_TX_THRESH(x) (x->tx_ring_size / 4)
#define TXQUEUESTOP_THRESHHOLD 2
static const struct of_device_id altera_tse_ids[];
static inline u32 tse_tx_avail(struct altera_tse_private *priv)
{
return priv->tx_cons + priv->tx_ring_size - priv->tx_prod - 1;
}
/* MDIO specific functions
*/
static int altera_tse_mdio_read(struct mii_bus *bus, int mii_id, int regnum)
{
struct net_device *ndev = bus->priv;
struct altera_tse_private *priv = netdev_priv(ndev);
/* set MDIO address */
csrwr32((mii_id & 0x1f), priv->mac_dev,
tse_csroffs(mdio_phy1_addr));
/* get the data */
return csrrd32(priv->mac_dev,
tse_csroffs(mdio_phy1) + regnum * 4) & 0xffff;
}
static int altera_tse_mdio_write(struct mii_bus *bus, int mii_id, int regnum,
u16 value)
{
struct net_device *ndev = bus->priv;
struct altera_tse_private *priv = netdev_priv(ndev);
/* set MDIO address */
csrwr32((mii_id & 0x1f), priv->mac_dev,
tse_csroffs(mdio_phy1_addr));
/* write the data */
csrwr32(value, priv->mac_dev, tse_csroffs(mdio_phy1) + regnum * 4);
return 0;
}
static int altera_tse_mdio_create(struct net_device *dev, unsigned int id)
{
struct altera_tse_private *priv = netdev_priv(dev);
struct device_node *mdio_node = NULL;
struct device_node *child_node = NULL;
struct mii_bus *mdio = NULL;
int ret;
for_each_child_of_node(priv->device->of_node, child_node) {
if (of_device_is_compatible(child_node, "altr,tse-mdio")) {
mdio_node = child_node;
break;
}
}
if (mdio_node) {
netdev_dbg(dev, "FOUND MDIO subnode\n");
} else {
netdev_dbg(dev, "NO MDIO subnode\n");
return 0;
}
mdio = mdiobus_alloc();
if (mdio == NULL) {
netdev_err(dev, "Error allocating MDIO bus\n");
ret = -ENOMEM;
goto put_node;
}
mdio->name = ALTERA_TSE_RESOURCE_NAME;
mdio->read = &altera_tse_mdio_read;
mdio->write = &altera_tse_mdio_write;
snprintf(mdio->id, MII_BUS_ID_SIZE, "%s-%u", mdio->name, id);
mdio->priv = dev;
mdio->parent = priv->device;
ret = of_mdiobus_register(mdio, mdio_node);
if (ret != 0) {
netdev_err(dev, "Cannot register MDIO bus %s\n",
mdio->id);
goto out_free_mdio;
}
of_node_put(mdio_node);
if (netif_msg_drv(priv))
netdev_info(dev, "MDIO bus %s: created\n", mdio->id);
priv->mdio = mdio;
return 0;
out_free_mdio:
mdiobus_free(mdio);
mdio = NULL;
put_node:
of_node_put(mdio_node);
return ret;
}
static void altera_tse_mdio_destroy(struct net_device *dev)
{
struct altera_tse_private *priv = netdev_priv(dev);
if (priv->mdio == NULL)
return;
if (netif_msg_drv(priv))
netdev_info(dev, "MDIO bus %s: removed\n",
priv->mdio->id);
mdiobus_unregister(priv->mdio);
mdiobus_free(priv->mdio);
priv->mdio = NULL;
}
static int tse_init_rx_buffer(struct altera_tse_private *priv,
struct tse_buffer *rxbuffer, int len)
{
rxbuffer->skb = netdev_alloc_skb_ip_align(priv->dev, len);
if (!rxbuffer->skb)
return -ENOMEM;
rxbuffer->dma_addr = dma_map_single(priv->device, rxbuffer->skb->data,
len,
DMA_FROM_DEVICE);
if (dma_mapping_error(priv->device, rxbuffer->dma_addr)) {
netdev_err(priv->dev, "%s: DMA mapping error\n", __func__);
dev_kfree_skb_any(rxbuffer->skb);
return -EINVAL;
}
rxbuffer->dma_addr &= (dma_addr_t)~3;
rxbuffer->len = len;
return 0;
}
static void tse_free_rx_buffer(struct altera_tse_private *priv,
struct tse_buffer *rxbuffer)
{
dma_addr_t dma_addr = rxbuffer->dma_addr;
struct sk_buff *skb = rxbuffer->skb;
if (skb != NULL) {
if (dma_addr)
dma_unmap_single(priv->device, dma_addr,
rxbuffer->len,
DMA_FROM_DEVICE);
dev_kfree_skb_any(skb);
rxbuffer->skb = NULL;
rxbuffer->dma_addr = 0;
}
}
/* Unmap and free Tx buffer resources
*/
static void tse_free_tx_buffer(struct altera_tse_private *priv,
struct tse_buffer *buffer)
{
if (buffer->dma_addr) {
if (buffer->mapped_as_page)
dma_unmap_page(priv->device, buffer->dma_addr,
buffer->len, DMA_TO_DEVICE);
else
dma_unmap_single(priv->device, buffer->dma_addr,
buffer->len, DMA_TO_DEVICE);
buffer->dma_addr = 0;
}
if (buffer->skb) {
dev_kfree_skb_any(buffer->skb);
buffer->skb = NULL;
}
}
static int alloc_init_skbufs(struct altera_tse_private *priv)
{
unsigned int rx_descs = priv->rx_ring_size;
unsigned int tx_descs = priv->tx_ring_size;
int ret = -ENOMEM;
int i;
/* Create Rx ring buffer */
priv->rx_ring = kcalloc(rx_descs, sizeof(struct tse_buffer),
GFP_KERNEL);
if (!priv->rx_ring)
goto err_rx_ring;
/* Create Tx ring buffer */
priv->tx_ring = kcalloc(tx_descs, sizeof(struct tse_buffer),
GFP_KERNEL);
if (!priv->tx_ring)
goto err_tx_ring;
priv->tx_cons = 0;
priv->tx_prod = 0;
/* Init Rx ring */
for (i = 0; i < rx_descs; i++) {
ret = tse_init_rx_buffer(priv, &priv->rx_ring[i],
priv->rx_dma_buf_sz);
if (ret)
goto err_init_rx_buffers;
}
priv->rx_cons = 0;
priv->rx_prod = 0;
return 0;
err_init_rx_buffers:
while (--i >= 0)
tse_free_rx_buffer(priv, &priv->rx_ring[i]);
kfree(priv->tx_ring);
err_tx_ring:
kfree(priv->rx_ring);
err_rx_ring:
return ret;
}
static void free_skbufs(struct net_device *dev)
{
struct altera_tse_private *priv = netdev_priv(dev);
unsigned int rx_descs = priv->rx_ring_size;
unsigned int tx_descs = priv->tx_ring_size;
int i;
/* Release the DMA TX/RX socket buffers */
for (i = 0; i < rx_descs; i++)
tse_free_rx_buffer(priv, &priv->rx_ring[i]);
for (i = 0; i < tx_descs; i++)
tse_free_tx_buffer(priv, &priv->tx_ring[i]);
kfree(priv->tx_ring);
}
/* Reallocate the skb for the reception process
*/
static inline void tse_rx_refill(struct altera_tse_private *priv)
{
unsigned int rxsize = priv->rx_ring_size;
unsigned int entry;
int ret;
for (; priv->rx_cons - priv->rx_prod > 0;
priv->rx_prod++) {
entry = priv->rx_prod % rxsize;
if (likely(priv->rx_ring[entry].skb == NULL)) {
ret = tse_init_rx_buffer(priv, &priv->rx_ring[entry],
priv->rx_dma_buf_sz);
if (unlikely(ret != 0))
break;
priv->dmaops->add_rx_desc(priv, &priv->rx_ring[entry]);
}
}
}
/* Pull out the VLAN tag and fix up the packet
*/
static inline void tse_rx_vlan(struct net_device *dev, struct sk_buff *skb)
{
struct ethhdr *eth_hdr;
u16 vid;
if ((dev->features & NETIF_F_HW_VLAN_CTAG_RX) &&
!__vlan_get_tag(skb, &vid)) {
eth_hdr = (struct ethhdr *)skb->data;
memmove(skb->data + VLAN_HLEN, eth_hdr, ETH_ALEN * 2);
skb_pull(skb, VLAN_HLEN);
__vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vid);
}
}
/* Receive a packet: retrieve and pass over to upper levels
*/
static int tse_rx(struct altera_tse_private *priv, int limit)
{
unsigned int entry = priv->rx_cons % priv->rx_ring_size;
unsigned int next_entry;
unsigned int count = 0;
struct sk_buff *skb;
u32 rxstatus;
u16 pktlength;
u16 pktstatus;
/* Check for count < limit first as get_rx_status is changing
* the response-fifo so we must process the next packet
* after calling get_rx_status if a response is pending.
* (reading the last byte of the response pops the value from the fifo.)
*/
while ((count < limit) &&
((rxstatus = priv->dmaops->get_rx_status(priv)) != 0)) {
pktstatus = rxstatus >> 16;
pktlength = rxstatus & 0xffff;
if ((pktstatus & 0xFF) || (pktlength == 0))
netdev_err(priv->dev,
"RCV pktstatus %08X pktlength %08X\n",
pktstatus, pktlength);
/* DMA transfer from TSE starts with 2 additional bytes for
* IP payload alignment. Status returned by get_rx_status()
* contains DMA transfer length. Packet is 2 bytes shorter.
*/
pktlength -= 2;
count++;
next_entry = (++priv->rx_cons) % priv->rx_ring_size;
skb = priv->rx_ring[entry].skb;
if (unlikely(!skb)) {
netdev_err(priv->dev,
"%s: Inconsistent Rx descriptor chain\n",
__func__);
priv->dev->stats.rx_dropped++;
break;
}
priv->rx_ring[entry].skb = NULL;
skb_put(skb, pktlength);
dma_unmap_single(priv->device, priv->rx_ring[entry].dma_addr,
priv->rx_ring[entry].len, DMA_FROM_DEVICE);
if (netif_msg_pktdata(priv)) {
netdev_info(priv->dev, "frame received %d bytes\n",
pktlength);
print_hex_dump(KERN_ERR, "data: ", DUMP_PREFIX_OFFSET,
16, 1, skb->data, pktlength, true);
}
tse_rx_vlan(priv->dev, skb);
skb->protocol = eth_type_trans(skb, priv->dev);
skb_checksum_none_assert(skb);
napi_gro_receive(&priv->napi, skb);
priv->dev->stats.rx_packets++;
priv->dev->stats.rx_bytes += pktlength;
entry = next_entry;
tse_rx_refill(priv);
}
return count;
}
/* Reclaim resources after transmission completes
*/
static int tse_tx_complete(struct altera_tse_private *priv)
{
unsigned int txsize = priv->tx_ring_size;
struct tse_buffer *tx_buff;
unsigned int entry;
int txcomplete = 0;
u32 ready;
spin_lock(&priv->tx_lock);
ready = priv->dmaops->tx_completions(priv);
/* Free sent buffers */
while (ready && (priv->tx_cons != priv->tx_prod)) {
entry = priv->tx_cons % txsize;
tx_buff = &priv->tx_ring[entry];
if (netif_msg_tx_done(priv))
netdev_dbg(priv->dev, "%s: curr %d, dirty %d\n",
__func__, priv->tx_prod, priv->tx_cons);
if (likely(tx_buff->skb))
priv->dev->stats.tx_packets++;
tse_free_tx_buffer(priv, tx_buff);
priv->tx_cons++;
txcomplete++;
ready--;
}
if (unlikely(netif_queue_stopped(priv->dev) &&
tse_tx_avail(priv) > TSE_TX_THRESH(priv))) {
if (netif_queue_stopped(priv->dev) &&
tse_tx_avail(priv) > TSE_TX_THRESH(priv)) {
if (netif_msg_tx_done(priv))
netdev_dbg(priv->dev, "%s: restart transmit\n",
__func__);
netif_wake_queue(priv->dev);
}
}
spin_unlock(&priv->tx_lock);
return txcomplete;
}
/* NAPI polling function
*/
static int tse_poll(struct napi_struct *napi, int budget)
{
struct altera_tse_private *priv =
container_of(napi, struct altera_tse_private, napi);
unsigned long int flags;
int rxcomplete = 0;
tse_tx_complete(priv);
rxcomplete = tse_rx(priv, budget);
if (rxcomplete < budget) {
napi_complete_done(napi, rxcomplete);
netdev_dbg(priv->dev,
"NAPI Complete, did %d packets with budget %d\n",
rxcomplete, budget);
spin_lock_irqsave(&priv->rxdma_irq_lock, flags);
priv->dmaops->enable_rxirq(priv);
priv->dmaops->enable_txirq(priv);
spin_unlock_irqrestore(&priv->rxdma_irq_lock, flags);
}
return rxcomplete;
}
/* DMA TX & RX FIFO interrupt routing
*/
static irqreturn_t altera_isr(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
struct altera_tse_private *priv;
if (unlikely(!dev)) {
pr_err("%s: invalid dev pointer\n", __func__);
return IRQ_NONE;
}
priv = netdev_priv(dev);
spin_lock(&priv->rxdma_irq_lock);
/* reset IRQs */
priv->dmaops->clear_rxirq(priv);
priv->dmaops->clear_txirq(priv);
spin_unlock(&priv->rxdma_irq_lock);
if (likely(napi_schedule_prep(&priv->napi))) {
spin_lock(&priv->rxdma_irq_lock);
priv->dmaops->disable_rxirq(priv);
priv->dmaops->disable_txirq(priv);
spin_unlock(&priv->rxdma_irq_lock);
__napi_schedule(&priv->napi);
}
return IRQ_HANDLED;
}
/* Transmit a packet (called by the kernel). Dispatches
* either the SGDMA method for transmitting or the
* MSGDMA method, assumes no scatter/gather support,
* implying an assumption that there's only one
* physically contiguous fragment starting at
* skb->data, for length of skb_headlen(skb).
*/
static netdev_tx_t tse_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct altera_tse_private *priv = netdev_priv(dev);
unsigned int nopaged_len = skb_headlen(skb);
unsigned int txsize = priv->tx_ring_size;
int nfrags = skb_shinfo(skb)->nr_frags;
struct tse_buffer *buffer = NULL;
netdev_tx_t ret = NETDEV_TX_OK;
dma_addr_t dma_addr;
unsigned int entry;
spin_lock_bh(&priv->tx_lock);
if (unlikely(tse_tx_avail(priv) < nfrags + 1)) {
if (!netif_queue_stopped(dev)) {
netif_stop_queue(dev);
/* This is a hard error, log it. */
netdev_err(priv->dev,
"%s: Tx list full when queue awake\n",
__func__);
}
ret = NETDEV_TX_BUSY;
goto out;
}
/* Map the first skb fragment */
entry = priv->tx_prod % txsize;
buffer = &priv->tx_ring[entry];
dma_addr = dma_map_single(priv->device, skb->data, nopaged_len,
DMA_TO_DEVICE);
if (dma_mapping_error(priv->device, dma_addr)) {
netdev_err(priv->dev, "%s: DMA mapping error\n", __func__);
ret = NETDEV_TX_OK;
goto out;
}
buffer->skb = skb;
buffer->dma_addr = dma_addr;
buffer->len = nopaged_len;
priv->dmaops->tx_buffer(priv, buffer);
skb_tx_timestamp(skb);
priv->tx_prod++;
dev->stats.tx_bytes += skb->len;
if (unlikely(tse_tx_avail(priv) <= TXQUEUESTOP_THRESHHOLD)) {
if (netif_msg_hw(priv))
netdev_dbg(priv->dev, "%s: stop transmitted packets\n",
__func__);
netif_stop_queue(dev);
}
out:
spin_unlock_bh(&priv->tx_lock);
return ret;
}
static int altera_tse_phy_get_addr_mdio_create(struct net_device *dev)
{
struct altera_tse_private *priv = netdev_priv(dev);
struct device_node *np = priv->device->of_node;
int ret;
ret = of_get_phy_mode(np, &priv->phy_iface);
/* Avoid get phy addr and create mdio if no phy is present */
if (ret)
return 0;
/* try to get PHY address from device tree, use PHY autodetection if
* no valid address is given
*/
if (of_property_read_u32(priv->device->of_node, "phy-addr",
&priv->phy_addr)) {
priv->phy_addr = POLL_PHY;
}
if (!((priv->phy_addr == POLL_PHY) ||
((priv->phy_addr >= 0) && (priv->phy_addr < PHY_MAX_ADDR)))) {
netdev_err(dev, "invalid phy-addr specified %d\n",
priv->phy_addr);
return -ENODEV;
}
/* Create/attach to MDIO bus */
ret = altera_tse_mdio_create(dev,
atomic_add_return(1, &instance_count));
if (ret)
return -ENODEV;
return 0;
}
static void tse_update_mac_addr(struct altera_tse_private *priv, const u8 *addr)
{
u32 msb;
u32 lsb;
msb = (addr[3] << 24) | (addr[2] << 16) | (addr[1] << 8) | addr[0];
lsb = ((addr[5] << 8) | addr[4]) & 0xffff;
/* Set primary MAC address */
csrwr32(msb, priv->mac_dev, tse_csroffs(mac_addr_0));
csrwr32(lsb, priv->mac_dev, tse_csroffs(mac_addr_1));
}
/* MAC software reset.
* When reset is triggered, the MAC function completes the current
* transmission or reception, and subsequently disables the transmit and
* receive logic, flushes the receive FIFO buffer, and resets the statistics
* counters.
*/
static int reset_mac(struct altera_tse_private *priv)
{
int counter;
u32 dat;
dat = csrrd32(priv->mac_dev, tse_csroffs(command_config));
dat &= ~(MAC_CMDCFG_TX_ENA | MAC_CMDCFG_RX_ENA);
dat |= MAC_CMDCFG_SW_RESET | MAC_CMDCFG_CNT_RESET;
csrwr32(dat, priv->mac_dev, tse_csroffs(command_config));
counter = 0;
while (counter++ < ALTERA_TSE_SW_RESET_WATCHDOG_CNTR) {
if (tse_bit_is_clear(priv->mac_dev, tse_csroffs(command_config),
MAC_CMDCFG_SW_RESET))
break;
udelay(1);
}
if (counter >= ALTERA_TSE_SW_RESET_WATCHDOG_CNTR) {
dat = csrrd32(priv->mac_dev, tse_csroffs(command_config));
dat &= ~MAC_CMDCFG_SW_RESET;
csrwr32(dat, priv->mac_dev, tse_csroffs(command_config));
return -1;
}
return 0;
}
/* Initialize MAC core registers
*/
static int init_mac(struct altera_tse_private *priv)
{
unsigned int cmd = 0;
u32 frm_length;
/* Setup Rx FIFO */
csrwr32(priv->rx_fifo_depth - ALTERA_TSE_RX_SECTION_EMPTY,
priv->mac_dev, tse_csroffs(rx_section_empty));
csrwr32(ALTERA_TSE_RX_SECTION_FULL, priv->mac_dev,
tse_csroffs(rx_section_full));
csrwr32(ALTERA_TSE_RX_ALMOST_EMPTY, priv->mac_dev,
tse_csroffs(rx_almost_empty));
csrwr32(ALTERA_TSE_RX_ALMOST_FULL, priv->mac_dev,
tse_csroffs(rx_almost_full));
/* Setup Tx FIFO */
csrwr32(priv->tx_fifo_depth - ALTERA_TSE_TX_SECTION_EMPTY,
priv->mac_dev, tse_csroffs(tx_section_empty));
csrwr32(ALTERA_TSE_TX_SECTION_FULL, priv->mac_dev,
tse_csroffs(tx_section_full));
csrwr32(ALTERA_TSE_TX_ALMOST_EMPTY, priv->mac_dev,
tse_csroffs(tx_almost_empty));
csrwr32(ALTERA_TSE_TX_ALMOST_FULL, priv->mac_dev,
tse_csroffs(tx_almost_full));
/* MAC Address Configuration */
tse_update_mac_addr(priv, priv->dev->dev_addr);
/* MAC Function Configuration */
frm_length = ETH_HLEN + priv->dev->mtu + ETH_FCS_LEN;
csrwr32(frm_length, priv->mac_dev, tse_csroffs(frm_length));
csrwr32(ALTERA_TSE_TX_IPG_LENGTH, priv->mac_dev,
tse_csroffs(tx_ipg_length));
/* Disable RX/TX shift 16 for alignment of all received frames on 16-bit
* start address
*/
tse_set_bit(priv->mac_dev, tse_csroffs(rx_cmd_stat),
ALTERA_TSE_RX_CMD_STAT_RX_SHIFT16);
tse_clear_bit(priv->mac_dev, tse_csroffs(tx_cmd_stat),
ALTERA_TSE_TX_CMD_STAT_TX_SHIFT16 |
ALTERA_TSE_TX_CMD_STAT_OMIT_CRC);
/* Set the MAC options */
cmd = csrrd32(priv->mac_dev, tse_csroffs(command_config));
cmd &= ~MAC_CMDCFG_PAD_EN; /* No padding Removal on Receive */
cmd &= ~MAC_CMDCFG_CRC_FWD; /* CRC Removal */
cmd |= MAC_CMDCFG_RX_ERR_DISC; /* Automatically discard frames
* with CRC errors
*/
cmd |= MAC_CMDCFG_CNTL_FRM_ENA;
cmd &= ~MAC_CMDCFG_TX_ENA;
cmd &= ~MAC_CMDCFG_RX_ENA;
/* Default speed and duplex setting, full/100 */
cmd &= ~MAC_CMDCFG_HD_ENA;
cmd &= ~MAC_CMDCFG_ETH_SPEED;
cmd &= ~MAC_CMDCFG_ENA_10;
csrwr32(cmd, priv->mac_dev, tse_csroffs(command_config));
csrwr32(ALTERA_TSE_PAUSE_QUANTA, priv->mac_dev,
tse_csroffs(pause_quanta));
if (netif_msg_hw(priv))
dev_dbg(priv->device,
"MAC post-initialization: CMD_CONFIG = 0x%08x\n", cmd);
return 0;
}
/* Start/stop MAC transmission logic
*/
static void tse_set_mac(struct altera_tse_private *priv, bool enable)
{
u32 value = csrrd32(priv->mac_dev, tse_csroffs(command_config));
if (enable)
value |= MAC_CMDCFG_TX_ENA | MAC_CMDCFG_RX_ENA;
else
value &= ~(MAC_CMDCFG_TX_ENA | MAC_CMDCFG_RX_ENA);
csrwr32(value, priv->mac_dev, tse_csroffs(command_config));
}
/* Change the MTU
*/
static int tse_change_mtu(struct net_device *dev, int new_mtu)
{
if (netif_running(dev)) {
netdev_err(dev, "must be stopped to change its MTU\n");
return -EBUSY;
}
dev->mtu = new_mtu;
netdev_update_features(dev);
return 0;
}
static void altera_tse_set_mcfilter(struct net_device *dev)
{
struct altera_tse_private *priv = netdev_priv(dev);
struct netdev_hw_addr *ha;
int i;
/* clear the hash filter */
for (i = 0; i < 64; i++)
csrwr32(0, priv->mac_dev, tse_csroffs(hash_table) + i * 4);
netdev_for_each_mc_addr(ha, dev) {
unsigned int hash = 0;
int mac_octet;
for (mac_octet = 5; mac_octet >= 0; mac_octet--) {
unsigned char xor_bit = 0;
unsigned char octet = ha->addr[mac_octet];
unsigned int bitshift;
for (bitshift = 0; bitshift < 8; bitshift++)
xor_bit ^= ((octet >> bitshift) & 0x01);
hash = (hash << 1) | xor_bit;
}
csrwr32(1, priv->mac_dev, tse_csroffs(hash_table) + hash * 4);
}
}
static void altera_tse_set_mcfilterall(struct net_device *dev)
{
struct altera_tse_private *priv = netdev_priv(dev);
int i;
/* set the hash filter */
for (i = 0; i < 64; i++)
csrwr32(1, priv->mac_dev, tse_csroffs(hash_table) + i * 4);
}
/* Set or clear the multicast filter for this adapter
*/
static void tse_set_rx_mode_hashfilter(struct net_device *dev)
{
struct altera_tse_private *priv = netdev_priv(dev);
spin_lock(&priv->mac_cfg_lock);
if (dev->flags & IFF_PROMISC)
tse_set_bit(priv->mac_dev, tse_csroffs(command_config),
MAC_CMDCFG_PROMIS_EN);
if (dev->flags & IFF_ALLMULTI)
altera_tse_set_mcfilterall(dev);
else
altera_tse_set_mcfilter(dev);
spin_unlock(&priv->mac_cfg_lock);
}
/* Set or clear the multicast filter for this adapter
*/
static void tse_set_rx_mode(struct net_device *dev)
{
struct altera_tse_private *priv = netdev_priv(dev);
spin_lock(&priv->mac_cfg_lock);
if ((dev->flags & IFF_PROMISC) || (dev->flags & IFF_ALLMULTI) ||
!netdev_mc_empty(dev) || !netdev_uc_empty(dev))
tse_set_bit(priv->mac_dev, tse_csroffs(command_config),
MAC_CMDCFG_PROMIS_EN);
else
tse_clear_bit(priv->mac_dev, tse_csroffs(command_config),
MAC_CMDCFG_PROMIS_EN);
spin_unlock(&priv->mac_cfg_lock);
}
/* Open and initialize the interface
*/
static int tse_open(struct net_device *dev)
{
struct altera_tse_private *priv = netdev_priv(dev);
unsigned long flags;
int ret = 0;
int i;
/* Reset and configure TSE MAC and probe associated PHY */
ret = priv->dmaops->init_dma(priv);
if (ret != 0) {
netdev_err(dev, "Cannot initialize DMA\n");
goto phy_error;
}
if (netif_msg_ifup(priv))
netdev_warn(dev, "device MAC address %pM\n",
dev->dev_addr);
if ((priv->revision < 0xd00) || (priv->revision > 0xe00))
netdev_warn(dev, "TSE revision %x\n", priv->revision);
spin_lock(&priv->mac_cfg_lock);
ret = reset_mac(priv);
/* Note that reset_mac will fail if the clocks are gated by the PHY
* due to the PHY being put into isolation or power down mode.
* This is not an error if reset fails due to no clock.
*/
if (ret)
netdev_dbg(dev, "Cannot reset MAC core (error: %d)\n", ret);
ret = init_mac(priv);
spin_unlock(&priv->mac_cfg_lock);
if (ret) {
netdev_err(dev, "Cannot init MAC core (error: %d)\n", ret);
goto alloc_skbuf_error;
}
priv->dmaops->reset_dma(priv);
/* Create and initialize the TX/RX descriptors chains. */
priv->rx_ring_size = dma_rx_num;
priv->tx_ring_size = dma_tx_num;
ret = alloc_init_skbufs(priv);
if (ret) {
netdev_err(dev, "DMA descriptors initialization failed\n");
goto alloc_skbuf_error;
}
/* Register RX interrupt */
ret = request_irq(priv->rx_irq, altera_isr, IRQF_SHARED,
dev->name, dev);
if (ret) {
netdev_err(dev, "Unable to register RX interrupt %d\n",
priv->rx_irq);
goto init_error;
}
/* Register TX interrupt */
ret = request_irq(priv->tx_irq, altera_isr, IRQF_SHARED,
dev->name, dev);
if (ret) {
netdev_err(dev, "Unable to register TX interrupt %d\n",
priv->tx_irq);
goto tx_request_irq_error;
}
/* Enable DMA interrupts */
spin_lock_irqsave(&priv->rxdma_irq_lock, flags);
priv->dmaops->enable_rxirq(priv);
priv->dmaops->enable_txirq(priv);
/* Setup RX descriptor chain */
for (i = 0; i < priv->rx_ring_size; i++)
priv->dmaops->add_rx_desc(priv, &priv->rx_ring[i]);
spin_unlock_irqrestore(&priv->rxdma_irq_lock, flags);
ret = phylink_of_phy_connect(priv->phylink, priv->device->of_node, 0);
if (ret) {
netdev_err(dev, "could not connect phylink (%d)\n", ret);
goto tx_request_irq_error;
}
phylink_start(priv->phylink);
napi_enable(&priv->napi);
netif_start_queue(dev);
priv->dmaops->start_rxdma(priv);
/* Start MAC Rx/Tx */
spin_lock(&priv->mac_cfg_lock);
tse_set_mac(priv, true);
spin_unlock(&priv->mac_cfg_lock);
return 0;
tx_request_irq_error:
free_irq(priv->rx_irq, dev);
init_error:
free_skbufs(dev);
alloc_skbuf_error:
phy_error:
return ret;
}
/* Stop TSE MAC interface and put the device in an inactive state
*/
static int tse_shutdown(struct net_device *dev)
{
struct altera_tse_private *priv = netdev_priv(dev);
unsigned long int flags;
int ret;
phylink_stop(priv->phylink);
phylink_disconnect_phy(priv->phylink);
netif_stop_queue(dev);
napi_disable(&priv->napi);
/* Disable DMA interrupts */
spin_lock_irqsave(&priv->rxdma_irq_lock, flags);
priv->dmaops->disable_rxirq(priv);
priv->dmaops->disable_txirq(priv);
spin_unlock_irqrestore(&priv->rxdma_irq_lock, flags);
/* Free the IRQ lines */
free_irq(priv->rx_irq, dev);
free_irq(priv->tx_irq, dev);
/* disable and reset the MAC, empties fifo */
spin_lock(&priv->mac_cfg_lock);
spin_lock(&priv->tx_lock);
ret = reset_mac(priv);
/* Note that reset_mac will fail if the clocks are gated by the PHY
* due to the PHY being put into isolation or power down mode.
* This is not an error if reset fails due to no clock.
*/
if (ret)
netdev_dbg(dev, "Cannot reset MAC core (error: %d)\n", ret);
priv->dmaops->reset_dma(priv);
free_skbufs(dev);
spin_unlock(&priv->tx_lock);
spin_unlock(&priv->mac_cfg_lock);
priv->dmaops->uninit_dma(priv);
return 0;
}
static struct net_device_ops altera_tse_netdev_ops = {
.ndo_open = tse_open,
.ndo_stop = tse_shutdown,
.ndo_start_xmit = tse_start_xmit,
.ndo_set_mac_address = eth_mac_addr,
.ndo_set_rx_mode = tse_set_rx_mode,
.ndo_change_mtu = tse_change_mtu,
.ndo_validate_addr = eth_validate_addr,
};
static void alt_tse_mac_config(struct phylink_config *config, unsigned int mode,
const struct phylink_link_state *state)
{
struct net_device *ndev = to_net_dev(config->dev);
struct altera_tse_private *priv = netdev_priv(ndev);
spin_lock(&priv->mac_cfg_lock);
reset_mac(priv);
tse_set_mac(priv, true);
spin_unlock(&priv->mac_cfg_lock);
}
static void alt_tse_mac_link_down(struct phylink_config *config,
unsigned int mode, phy_interface_t interface)
{
}
static void alt_tse_mac_link_up(struct phylink_config *config,
struct phy_device *phy, unsigned int mode,
phy_interface_t interface, int speed,
int duplex, bool tx_pause, bool rx_pause)
{
struct net_device *ndev = to_net_dev(config->dev);
struct altera_tse_private *priv = netdev_priv(ndev);
u32 ctrl;
ctrl = csrrd32(priv->mac_dev, tse_csroffs(command_config));
ctrl &= ~(MAC_CMDCFG_ENA_10 | MAC_CMDCFG_ETH_SPEED | MAC_CMDCFG_HD_ENA);
if (duplex == DUPLEX_HALF)
ctrl |= MAC_CMDCFG_HD_ENA;
if (speed == SPEED_1000)
ctrl |= MAC_CMDCFG_ETH_SPEED;
else if (speed == SPEED_10)
ctrl |= MAC_CMDCFG_ENA_10;
spin_lock(&priv->mac_cfg_lock);
csrwr32(ctrl, priv->mac_dev, tse_csroffs(command_config));
spin_unlock(&priv->mac_cfg_lock);
}
static struct phylink_pcs *alt_tse_select_pcs(struct phylink_config *config,
phy_interface_t interface)
{
struct net_device *ndev = to_net_dev(config->dev);
struct altera_tse_private *priv = netdev_priv(ndev);
if (interface == PHY_INTERFACE_MODE_SGMII ||
interface == PHY_INTERFACE_MODE_1000BASEX)
return priv->pcs;
else
return NULL;
}
static const struct phylink_mac_ops alt_tse_phylink_ops = {
.mac_config = alt_tse_mac_config,
.mac_link_down = alt_tse_mac_link_down,
.mac_link_up = alt_tse_mac_link_up,
.mac_select_pcs = alt_tse_select_pcs,
};
static int request_and_map(struct platform_device *pdev, const char *name,
struct resource **res, void __iomem **ptr)
{
struct device *device = &pdev->dev;
struct resource *region;
*res = platform_get_resource_byname(pdev, IORESOURCE_MEM, name);
if (*res == NULL) {
dev_err(device, "resource %s not defined\n", name);
return -ENODEV;
}
region = devm_request_mem_region(device, (*res)->start,
resource_size(*res), dev_name(device));
if (region == NULL) {
dev_err(device, "unable to request %s\n", name);
return -EBUSY;
}
*ptr = devm_ioremap(device, region->start,
resource_size(region));
if (*ptr == NULL) {
dev_err(device, "ioremap of %s failed!", name);
return -ENOMEM;
}
return 0;
}
/* Probe Altera TSE MAC device
*/
static int altera_tse_probe(struct platform_device *pdev)
{
const struct of_device_id *of_id = NULL;
struct regmap_config pcs_regmap_cfg;
struct altera_tse_private *priv;
struct mdio_regmap_config mrc;
struct resource *control_port;
struct regmap *pcs_regmap;
struct resource *dma_res;
struct resource *pcs_res;
struct mii_bus *pcs_bus;
struct net_device *ndev;
void __iomem *descmap;
int ret = -ENODEV;
ndev = alloc_etherdev(sizeof(struct altera_tse_private));
if (!ndev) {
dev_err(&pdev->dev, "Could not allocate network device\n");
return -ENODEV;
}
SET_NETDEV_DEV(ndev, &pdev->dev);
priv = netdev_priv(ndev);
priv->device = &pdev->dev;
priv->dev = ndev;
priv->msg_enable = netif_msg_init(debug, default_msg_level);
of_id = of_match_device(altera_tse_ids, &pdev->dev);
if (of_id)
priv->dmaops = (struct altera_dmaops *)of_id->data;
if (priv->dmaops &&
priv->dmaops->altera_dtype == ALTERA_DTYPE_SGDMA) {
/* Get the mapped address to the SGDMA descriptor memory */
ret = request_and_map(pdev, "s1", &dma_res, &descmap);
if (ret)
goto err_free_netdev;
/* Start of that memory is for transmit descriptors */
priv->tx_dma_desc = descmap;
/* First half is for tx descriptors, other half for tx */
priv->txdescmem = resource_size(dma_res)/2;
priv->txdescmem_busaddr = (dma_addr_t)dma_res->start;
priv->rx_dma_desc = (void __iomem *)((uintptr_t)(descmap +
priv->txdescmem));
priv->rxdescmem = resource_size(dma_res)/2;
priv->rxdescmem_busaddr = dma_res->start;
priv->rxdescmem_busaddr += priv->txdescmem;
if (upper_32_bits(priv->rxdescmem_busaddr)) {
dev_dbg(priv->device,
"SGDMA bus addresses greater than 32-bits\n");
ret = -EINVAL;
goto err_free_netdev;
}
if (upper_32_bits(priv->txdescmem_busaddr)) {
dev_dbg(priv->device,
"SGDMA bus addresses greater than 32-bits\n");
ret = -EINVAL;
goto err_free_netdev;
}
} else if (priv->dmaops &&
priv->dmaops->altera_dtype == ALTERA_DTYPE_MSGDMA) {
ret = request_and_map(pdev, "rx_resp", &dma_res,
&priv->rx_dma_resp);
if (ret)
goto err_free_netdev;
ret = request_and_map(pdev, "tx_desc", &dma_res,
&priv->tx_dma_desc);
if (ret)
goto err_free_netdev;
priv->txdescmem = resource_size(dma_res);
priv->txdescmem_busaddr = dma_res->start;
ret = request_and_map(pdev, "rx_desc", &dma_res,
&priv->rx_dma_desc);
if (ret)
goto err_free_netdev;
priv->rxdescmem = resource_size(dma_res);
priv->rxdescmem_busaddr = dma_res->start;
} else {
ret = -ENODEV;
goto err_free_netdev;
}
if (!dma_set_mask(priv->device, DMA_BIT_MASK(priv->dmaops->dmamask))) {
dma_set_coherent_mask(priv->device,
DMA_BIT_MASK(priv->dmaops->dmamask));
} else if (!dma_set_mask(priv->device, DMA_BIT_MASK(32))) {
dma_set_coherent_mask(priv->device, DMA_BIT_MASK(32));
} else {
ret = -EIO;
goto err_free_netdev;
}
/* MAC address space */
ret = request_and_map(pdev, "control_port", &control_port,
(void __iomem **)&priv->mac_dev);
if (ret)
goto err_free_netdev;
/* xSGDMA Rx Dispatcher address space */
ret = request_and_map(pdev, "rx_csr", &dma_res,
&priv->rx_dma_csr);
if (ret)
goto err_free_netdev;
/* xSGDMA Tx Dispatcher address space */
ret = request_and_map(pdev, "tx_csr", &dma_res,
&priv->tx_dma_csr);
if (ret)
goto err_free_netdev;
memset(&pcs_regmap_cfg, 0, sizeof(pcs_regmap_cfg));
memset(&mrc, 0, sizeof(mrc));
/* SGMII PCS address space. The location can vary depending on how the
* IP is integrated. We can have a resource dedicated to it at a specific
* address space, but if it's not the case, we fallback to the mdiophy0
* from the MAC's address space
*/
ret = request_and_map(pdev, "pcs", &pcs_res, &priv->pcs_base);
if (ret) {
/* If we can't find a dedicated resource for the PCS, fallback
* to the internal PCS, that has a different address stride
*/
priv->pcs_base = priv->mac_dev + tse_csroffs(mdio_phy0);
pcs_regmap_cfg.reg_bits = 32;
/* Values are MDIO-like values, on 16 bits */
pcs_regmap_cfg.val_bits = 16;
pcs_regmap_cfg.reg_shift = REGMAP_UPSHIFT(2);
} else {
pcs_regmap_cfg.reg_bits = 16;
pcs_regmap_cfg.val_bits = 16;
pcs_regmap_cfg.reg_shift = REGMAP_UPSHIFT(1);
}
/* Create a regmap for the PCS so that it can be used by the PCS driver */
pcs_regmap = devm_regmap_init_mmio(&pdev->dev, priv->pcs_base,
&pcs_regmap_cfg);
if (IS_ERR(pcs_regmap)) {
ret = PTR_ERR(pcs_regmap);
goto err_free_netdev;
}
mrc.regmap = pcs_regmap;
mrc.parent = &pdev->dev;
mrc.valid_addr = 0x0;
mrc.autoscan = false;
/* Rx IRQ */
priv->rx_irq = platform_get_irq_byname(pdev, "rx_irq");
if (priv->rx_irq == -ENXIO) {
dev_err(&pdev->dev, "cannot obtain Rx IRQ\n");
ret = -ENXIO;
goto err_free_netdev;
}
/* Tx IRQ */
priv->tx_irq = platform_get_irq_byname(pdev, "tx_irq");
if (priv->tx_irq == -ENXIO) {
dev_err(&pdev->dev, "cannot obtain Tx IRQ\n");
ret = -ENXIO;
goto err_free_netdev;
}
/* get FIFO depths from device tree */
if (of_property_read_u32(pdev->dev.of_node, "rx-fifo-depth",
&priv->rx_fifo_depth)) {
dev_err(&pdev->dev, "cannot obtain rx-fifo-depth\n");
ret = -ENXIO;
goto err_free_netdev;
}
if (of_property_read_u32(pdev->dev.of_node, "tx-fifo-depth",
&priv->tx_fifo_depth)) {
dev_err(&pdev->dev, "cannot obtain tx-fifo-depth\n");
ret = -ENXIO;
goto err_free_netdev;
}
/* get hash filter settings for this instance */
priv->hash_filter =
of_property_read_bool(pdev->dev.of_node,
"altr,has-hash-multicast-filter");
/* Set hash filter to not set for now until the
* multicast filter receive issue is debugged
*/
priv->hash_filter = 0;
/* get supplemental address settings for this instance */
priv->added_unicast =
of_property_read_bool(pdev->dev.of_node,
"altr,has-supplementary-unicast");
priv->dev->min_mtu = ETH_ZLEN + ETH_FCS_LEN;
/* Max MTU is 1500, ETH_DATA_LEN */
priv->dev->max_mtu = ETH_DATA_LEN;
/* Get the max mtu from the device tree. Note that the
* "max-frame-size" parameter is actually max mtu. Definition
* in the ePAPR v1.1 spec and usage differ, so go with usage.
*/
of_property_read_u32(pdev->dev.of_node, "max-frame-size",
&priv->dev->max_mtu);
/* The DMA buffer size already accounts for an alignment bias
* to avoid unaligned access exceptions for the NIOS processor,
*/
priv->rx_dma_buf_sz = ALTERA_RXDMABUFFER_SIZE;
/* get default MAC address from device tree */
ret = of_get_ethdev_address(pdev->dev.of_node, ndev);
if (ret)
eth_hw_addr_random(ndev);
/* get phy addr and create mdio */
ret = altera_tse_phy_get_addr_mdio_create(ndev);
if (ret)
goto err_free_netdev;
/* initialize netdev */
ndev->mem_start = control_port->start;
ndev->mem_end = control_port->end;
ndev->netdev_ops = &altera_tse_netdev_ops;
altera_tse_set_ethtool_ops(ndev);
altera_tse_netdev_ops.ndo_set_rx_mode = tse_set_rx_mode;
if (priv->hash_filter)
altera_tse_netdev_ops.ndo_set_rx_mode =
tse_set_rx_mode_hashfilter;
/* Scatter/gather IO is not supported,
* so it is turned off
*/
ndev->hw_features &= ~NETIF_F_SG;
ndev->features |= ndev->hw_features | NETIF_F_HIGHDMA;
/* VLAN offloading of tagging, stripping and filtering is not
* supported by hardware, but driver will accommodate the
* extra 4-byte VLAN tag for processing by upper layers
*/
ndev->features |= NETIF_F_HW_VLAN_CTAG_RX;
/* setup NAPI interface */
netif_napi_add(ndev, &priv->napi, tse_poll);
spin_lock_init(&priv->mac_cfg_lock);
spin_lock_init(&priv->tx_lock);
spin_lock_init(&priv->rxdma_irq_lock);
netif_carrier_off(ndev);
ret = register_netdev(ndev);
if (ret) {
dev_err(&pdev->dev, "failed to register TSE net device\n");
goto err_register_netdev;
}
platform_set_drvdata(pdev, ndev);
priv->revision = ioread32(&priv->mac_dev->megacore_revision);
if (netif_msg_probe(priv))
dev_info(&pdev->dev, "Altera TSE MAC version %d.%d at 0x%08lx irq %d/%d\n",
(priv->revision >> 8) & 0xff,
priv->revision & 0xff,
(unsigned long) control_port->start, priv->rx_irq,
priv->tx_irq);
snprintf(mrc.name, MII_BUS_ID_SIZE, "%s-pcs-mii", ndev->name);
pcs_bus = devm_mdio_regmap_register(&pdev->dev, &mrc);
if (IS_ERR(pcs_bus)) {
ret = PTR_ERR(pcs_bus);
goto err_init_pcs;
}
priv->pcs = lynx_pcs_create_mdiodev(pcs_bus, 0);
if (IS_ERR(priv->pcs)) {
ret = PTR_ERR(priv->pcs);
goto err_init_pcs;
}
priv->phylink_config.dev = &ndev->dev;
priv->phylink_config.type = PHYLINK_NETDEV;
priv->phylink_config.mac_capabilities = MAC_SYM_PAUSE | MAC_10 |
MAC_100 | MAC_1000FD;
phy_interface_set_rgmii(priv->phylink_config.supported_interfaces);
__set_bit(PHY_INTERFACE_MODE_MII,
priv->phylink_config.supported_interfaces);
__set_bit(PHY_INTERFACE_MODE_GMII,
priv->phylink_config.supported_interfaces);
__set_bit(PHY_INTERFACE_MODE_SGMII,
priv->phylink_config.supported_interfaces);
__set_bit(PHY_INTERFACE_MODE_1000BASEX,
priv->phylink_config.supported_interfaces);
priv->phylink = phylink_create(&priv->phylink_config,
of_fwnode_handle(priv->device->of_node),
priv->phy_iface, &alt_tse_phylink_ops);
if (IS_ERR(priv->phylink)) {
dev_err(&pdev->dev, "failed to create phylink\n");
ret = PTR_ERR(priv->phylink);
goto err_init_phylink;
}
return 0;
err_init_phylink:
lynx_pcs_destroy(priv->pcs);
err_init_pcs:
unregister_netdev(ndev);
err_register_netdev:
netif_napi_del(&priv->napi);
altera_tse_mdio_destroy(ndev);
err_free_netdev:
free_netdev(ndev);
return ret;
}
/* Remove Altera TSE MAC device
*/
static int altera_tse_remove(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct altera_tse_private *priv = netdev_priv(ndev);
platform_set_drvdata(pdev, NULL);
altera_tse_mdio_destroy(ndev);
unregister_netdev(ndev);
phylink_destroy(priv->phylink);
lynx_pcs_destroy(priv->pcs);
free_netdev(ndev);
return 0;
}
static const struct altera_dmaops altera_dtype_sgdma = {
.altera_dtype = ALTERA_DTYPE_SGDMA,
.dmamask = 32,
.reset_dma = sgdma_reset,
.enable_txirq = sgdma_enable_txirq,
.enable_rxirq = sgdma_enable_rxirq,
.disable_txirq = sgdma_disable_txirq,
.disable_rxirq = sgdma_disable_rxirq,
.clear_txirq = sgdma_clear_txirq,
.clear_rxirq = sgdma_clear_rxirq,
.tx_buffer = sgdma_tx_buffer,
.tx_completions = sgdma_tx_completions,
.add_rx_desc = sgdma_add_rx_desc,
.get_rx_status = sgdma_rx_status,
.init_dma = sgdma_initialize,
.uninit_dma = sgdma_uninitialize,
.start_rxdma = sgdma_start_rxdma,
};
static const struct altera_dmaops altera_dtype_msgdma = {
.altera_dtype = ALTERA_DTYPE_MSGDMA,
.dmamask = 64,
.reset_dma = msgdma_reset,
.enable_txirq = msgdma_enable_txirq,
.enable_rxirq = msgdma_enable_rxirq,
.disable_txirq = msgdma_disable_txirq,
.disable_rxirq = msgdma_disable_rxirq,
.clear_txirq = msgdma_clear_txirq,
.clear_rxirq = msgdma_clear_rxirq,
.tx_buffer = msgdma_tx_buffer,
.tx_completions = msgdma_tx_completions,
.add_rx_desc = msgdma_add_rx_desc,
.get_rx_status = msgdma_rx_status,
.init_dma = msgdma_initialize,
.uninit_dma = msgdma_uninitialize,
.start_rxdma = msgdma_start_rxdma,
};
static const struct of_device_id altera_tse_ids[] = {
{ .compatible = "altr,tse-msgdma-1.0", .data = &altera_dtype_msgdma, },
{ .compatible = "altr,tse-1.0", .data = &altera_dtype_sgdma, },
{ .compatible = "ALTR,tse-1.0", .data = &altera_dtype_sgdma, },
{},
};
MODULE_DEVICE_TABLE(of, altera_tse_ids);
static struct platform_driver altera_tse_driver = {
.probe = altera_tse_probe,
.remove = altera_tse_remove,
.suspend = NULL,
.resume = NULL,
.driver = {
.name = ALTERA_TSE_RESOURCE_NAME,
.of_match_table = altera_tse_ids,
},
};
module_platform_driver(altera_tse_driver);
MODULE_AUTHOR("Altera Corporation");
MODULE_DESCRIPTION("Altera Triple Speed Ethernet MAC driver");
MODULE_LICENSE("GPL v2");
|
linux-master
|
drivers/net/ethernet/altera/altera_tse_main.c
|
// SPDX-License-Identifier: GPL-2.0-only
/* Altera TSE SGDMA and MSGDMA Linux driver
* Copyright (C) 2014 Altera Corporation. All rights reserved
*/
#include "altera_tse.h"
#include "altera_utils.h"
void tse_set_bit(void __iomem *ioaddr, size_t offs, u32 bit_mask)
{
u32 value = csrrd32(ioaddr, offs);
value |= bit_mask;
csrwr32(value, ioaddr, offs);
}
void tse_clear_bit(void __iomem *ioaddr, size_t offs, u32 bit_mask)
{
u32 value = csrrd32(ioaddr, offs);
value &= ~bit_mask;
csrwr32(value, ioaddr, offs);
}
int tse_bit_is_set(void __iomem *ioaddr, size_t offs, u32 bit_mask)
{
u32 value = csrrd32(ioaddr, offs);
return (value & bit_mask) ? 1 : 0;
}
int tse_bit_is_clear(void __iomem *ioaddr, size_t offs, u32 bit_mask)
{
u32 value = csrrd32(ioaddr, offs);
return (value & bit_mask) ? 0 : 1;
}
|
linux-master
|
drivers/net/ethernet/altera/altera_utils.c
|
// SPDX-License-Identifier: GPL-2.0-only
/* Ethtool support for Altera Triple-Speed Ethernet MAC driver
* Copyright (C) 2008-2014 Altera Corporation. All rights reserved
*
* Contributors:
* Dalon Westergreen
* Thomas Chou
* Ian Abbott
* Yuriy Kozlov
* Tobias Klauser
* Andriy Smolskyy
* Roman Bulgakov
* Dmytro Mytarchuk
*
* Original driver contributed by SLS.
* Major updates contributed by GlobalLogic
*/
#include <linux/ethtool.h>
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/phy.h>
#include "altera_tse.h"
#define TSE_STATS_LEN 31
#define TSE_NUM_REGS 128
static char const stat_gstrings[][ETH_GSTRING_LEN] = {
"tx_packets",
"rx_packets",
"rx_crc_errors",
"rx_align_errors",
"tx_bytes",
"rx_bytes",
"tx_pause",
"rx_pause",
"rx_errors",
"tx_errors",
"rx_unicast",
"rx_multicast",
"rx_broadcast",
"tx_discards",
"tx_unicast",
"tx_multicast",
"tx_broadcast",
"ether_drops",
"rx_total_bytes",
"rx_total_packets",
"rx_undersize",
"rx_oversize",
"rx_64_bytes",
"rx_65_127_bytes",
"rx_128_255_bytes",
"rx_256_511_bytes",
"rx_512_1023_bytes",
"rx_1024_1518_bytes",
"rx_gte_1519_bytes",
"rx_jabbers",
"rx_runts",
};
static void tse_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
struct altera_tse_private *priv = netdev_priv(dev);
u32 rev = ioread32(&priv->mac_dev->megacore_revision);
strcpy(info->driver, "altera_tse");
snprintf(info->fw_version, ETHTOOL_FWVERS_LEN, "v%d.%d",
rev & 0xFFFF, (rev & 0xFFFF0000) >> 16);
sprintf(info->bus_info, "platform");
}
/* Fill in a buffer with the strings which correspond to the
* stats
*/
static void tse_gstrings(struct net_device *dev, u32 stringset, u8 *buf)
{
memcpy(buf, stat_gstrings, TSE_STATS_LEN * ETH_GSTRING_LEN);
}
static void tse_fill_stats(struct net_device *dev, struct ethtool_stats *dummy,
u64 *buf)
{
struct altera_tse_private *priv = netdev_priv(dev);
u64 ext;
buf[0] = csrrd32(priv->mac_dev,
tse_csroffs(frames_transmitted_ok));
buf[1] = csrrd32(priv->mac_dev,
tse_csroffs(frames_received_ok));
buf[2] = csrrd32(priv->mac_dev,
tse_csroffs(frames_check_sequence_errors));
buf[3] = csrrd32(priv->mac_dev,
tse_csroffs(alignment_errors));
/* Extended aOctetsTransmittedOK counter */
ext = (u64) csrrd32(priv->mac_dev,
tse_csroffs(msb_octets_transmitted_ok)) << 32;
ext |= csrrd32(priv->mac_dev,
tse_csroffs(octets_transmitted_ok));
buf[4] = ext;
/* Extended aOctetsReceivedOK counter */
ext = (u64) csrrd32(priv->mac_dev,
tse_csroffs(msb_octets_received_ok)) << 32;
ext |= csrrd32(priv->mac_dev,
tse_csroffs(octets_received_ok));
buf[5] = ext;
buf[6] = csrrd32(priv->mac_dev,
tse_csroffs(tx_pause_mac_ctrl_frames));
buf[7] = csrrd32(priv->mac_dev,
tse_csroffs(rx_pause_mac_ctrl_frames));
buf[8] = csrrd32(priv->mac_dev,
tse_csroffs(if_in_errors));
buf[9] = csrrd32(priv->mac_dev,
tse_csroffs(if_out_errors));
buf[10] = csrrd32(priv->mac_dev,
tse_csroffs(if_in_ucast_pkts));
buf[11] = csrrd32(priv->mac_dev,
tse_csroffs(if_in_multicast_pkts));
buf[12] = csrrd32(priv->mac_dev,
tse_csroffs(if_in_broadcast_pkts));
buf[13] = csrrd32(priv->mac_dev,
tse_csroffs(if_out_discards));
buf[14] = csrrd32(priv->mac_dev,
tse_csroffs(if_out_ucast_pkts));
buf[15] = csrrd32(priv->mac_dev,
tse_csroffs(if_out_multicast_pkts));
buf[16] = csrrd32(priv->mac_dev,
tse_csroffs(if_out_broadcast_pkts));
buf[17] = csrrd32(priv->mac_dev,
tse_csroffs(ether_stats_drop_events));
/* Extended etherStatsOctets counter */
ext = (u64) csrrd32(priv->mac_dev,
tse_csroffs(msb_ether_stats_octets)) << 32;
ext |= csrrd32(priv->mac_dev,
tse_csroffs(ether_stats_octets));
buf[18] = ext;
buf[19] = csrrd32(priv->mac_dev,
tse_csroffs(ether_stats_pkts));
buf[20] = csrrd32(priv->mac_dev,
tse_csroffs(ether_stats_undersize_pkts));
buf[21] = csrrd32(priv->mac_dev,
tse_csroffs(ether_stats_oversize_pkts));
buf[22] = csrrd32(priv->mac_dev,
tse_csroffs(ether_stats_pkts_64_octets));
buf[23] = csrrd32(priv->mac_dev,
tse_csroffs(ether_stats_pkts_65to127_octets));
buf[24] = csrrd32(priv->mac_dev,
tse_csroffs(ether_stats_pkts_128to255_octets));
buf[25] = csrrd32(priv->mac_dev,
tse_csroffs(ether_stats_pkts_256to511_octets));
buf[26] = csrrd32(priv->mac_dev,
tse_csroffs(ether_stats_pkts_512to1023_octets));
buf[27] = csrrd32(priv->mac_dev,
tse_csroffs(ether_stats_pkts_1024to1518_octets));
buf[28] = csrrd32(priv->mac_dev,
tse_csroffs(ether_stats_pkts_1519tox_octets));
buf[29] = csrrd32(priv->mac_dev,
tse_csroffs(ether_stats_jabbers));
buf[30] = csrrd32(priv->mac_dev,
tse_csroffs(ether_stats_fragments));
}
static int tse_sset_count(struct net_device *dev, int sset)
{
switch (sset) {
case ETH_SS_STATS:
return TSE_STATS_LEN;
default:
return -EOPNOTSUPP;
}
}
static u32 tse_get_msglevel(struct net_device *dev)
{
struct altera_tse_private *priv = netdev_priv(dev);
return priv->msg_enable;
}
static void tse_set_msglevel(struct net_device *dev, uint32_t data)
{
struct altera_tse_private *priv = netdev_priv(dev);
priv->msg_enable = data;
}
static int tse_reglen(struct net_device *dev)
{
return TSE_NUM_REGS * sizeof(u32);
}
static void tse_get_regs(struct net_device *dev, struct ethtool_regs *regs,
void *regbuf)
{
struct altera_tse_private *priv = netdev_priv(dev);
u32 *buf = regbuf;
int i;
/* Set version to a known value, so ethtool knows
* how to do any special formatting of this data.
* This version number will need to change if and
* when this register table is changed.
*
* version[31:0] = 1: Dump the first 128 TSE Registers
* Upper bits are all 0 by default
*
* Upper 16-bits will indicate feature presence for
* Ethtool register decoding in future version.
*/
regs->version = 1;
for (i = 0; i < TSE_NUM_REGS; i++)
buf[i] = csrrd32(priv->mac_dev, i * 4);
}
static int tse_ethtool_set_link_ksettings(struct net_device *dev,
const struct ethtool_link_ksettings *cmd)
{
struct altera_tse_private *priv = netdev_priv(dev);
return phylink_ethtool_ksettings_set(priv->phylink, cmd);
}
static int tse_ethtool_get_link_ksettings(struct net_device *dev,
struct ethtool_link_ksettings *cmd)
{
struct altera_tse_private *priv = netdev_priv(dev);
return phylink_ethtool_ksettings_get(priv->phylink, cmd);
}
static const struct ethtool_ops tse_ethtool_ops = {
.get_drvinfo = tse_get_drvinfo,
.get_regs_len = tse_reglen,
.get_regs = tse_get_regs,
.get_link = ethtool_op_get_link,
.get_strings = tse_gstrings,
.get_sset_count = tse_sset_count,
.get_ethtool_stats = tse_fill_stats,
.get_msglevel = tse_get_msglevel,
.set_msglevel = tse_set_msglevel,
.get_link_ksettings = tse_ethtool_get_link_ksettings,
.set_link_ksettings = tse_ethtool_set_link_ksettings,
.get_ts_info = ethtool_op_get_ts_info,
};
void altera_tse_set_ethtool_ops(struct net_device *netdev)
{
netdev->ethtool_ops = &tse_ethtool_ops;
}
|
linux-master
|
drivers/net/ethernet/altera/altera_tse_ethtool.c
|
// SPDX-License-Identifier: GPL-2.0-only
/* Altera TSE SGDMA and MSGDMA Linux driver
* Copyright (C) 2014 Altera Corporation. All rights reserved
*/
#include <linux/netdevice.h>
#include "altera_utils.h"
#include "altera_tse.h"
#include "altera_msgdmahw.h"
#include "altera_msgdma.h"
/* No initialization work to do for MSGDMA */
int msgdma_initialize(struct altera_tse_private *priv)
{
return 0;
}
void msgdma_uninitialize(struct altera_tse_private *priv)
{
}
void msgdma_start_rxdma(struct altera_tse_private *priv)
{
}
void msgdma_reset(struct altera_tse_private *priv)
{
int counter;
/* Reset Rx mSGDMA */
csrwr32(MSGDMA_CSR_STAT_MASK, priv->rx_dma_csr,
msgdma_csroffs(status));
csrwr32(MSGDMA_CSR_CTL_RESET, priv->rx_dma_csr,
msgdma_csroffs(control));
counter = 0;
while (counter++ < ALTERA_TSE_SW_RESET_WATCHDOG_CNTR) {
if (tse_bit_is_clear(priv->rx_dma_csr, msgdma_csroffs(status),
MSGDMA_CSR_STAT_RESETTING))
break;
udelay(1);
}
if (counter >= ALTERA_TSE_SW_RESET_WATCHDOG_CNTR)
netif_warn(priv, drv, priv->dev,
"TSE Rx mSGDMA resetting bit never cleared!\n");
/* clear all status bits */
csrwr32(MSGDMA_CSR_STAT_MASK, priv->rx_dma_csr, msgdma_csroffs(status));
/* Reset Tx mSGDMA */
csrwr32(MSGDMA_CSR_STAT_MASK, priv->tx_dma_csr,
msgdma_csroffs(status));
csrwr32(MSGDMA_CSR_CTL_RESET, priv->tx_dma_csr,
msgdma_csroffs(control));
counter = 0;
while (counter++ < ALTERA_TSE_SW_RESET_WATCHDOG_CNTR) {
if (tse_bit_is_clear(priv->tx_dma_csr, msgdma_csroffs(status),
MSGDMA_CSR_STAT_RESETTING))
break;
udelay(1);
}
if (counter >= ALTERA_TSE_SW_RESET_WATCHDOG_CNTR)
netif_warn(priv, drv, priv->dev,
"TSE Tx mSGDMA resetting bit never cleared!\n");
/* clear all status bits */
csrwr32(MSGDMA_CSR_STAT_MASK, priv->tx_dma_csr, msgdma_csroffs(status));
}
void msgdma_disable_rxirq(struct altera_tse_private *priv)
{
tse_clear_bit(priv->rx_dma_csr, msgdma_csroffs(control),
MSGDMA_CSR_CTL_GLOBAL_INTR);
}
void msgdma_enable_rxirq(struct altera_tse_private *priv)
{
tse_set_bit(priv->rx_dma_csr, msgdma_csroffs(control),
MSGDMA_CSR_CTL_GLOBAL_INTR);
}
void msgdma_disable_txirq(struct altera_tse_private *priv)
{
tse_clear_bit(priv->tx_dma_csr, msgdma_csroffs(control),
MSGDMA_CSR_CTL_GLOBAL_INTR);
}
void msgdma_enable_txirq(struct altera_tse_private *priv)
{
tse_set_bit(priv->tx_dma_csr, msgdma_csroffs(control),
MSGDMA_CSR_CTL_GLOBAL_INTR);
}
void msgdma_clear_rxirq(struct altera_tse_private *priv)
{
csrwr32(MSGDMA_CSR_STAT_IRQ, priv->rx_dma_csr, msgdma_csroffs(status));
}
void msgdma_clear_txirq(struct altera_tse_private *priv)
{
csrwr32(MSGDMA_CSR_STAT_IRQ, priv->tx_dma_csr, msgdma_csroffs(status));
}
/* return 0 to indicate transmit is pending */
int msgdma_tx_buffer(struct altera_tse_private *priv, struct tse_buffer *buffer)
{
csrwr32(lower_32_bits(buffer->dma_addr), priv->tx_dma_desc,
msgdma_descroffs(read_addr_lo));
csrwr32(upper_32_bits(buffer->dma_addr), priv->tx_dma_desc,
msgdma_descroffs(read_addr_hi));
csrwr32(0, priv->tx_dma_desc, msgdma_descroffs(write_addr_lo));
csrwr32(0, priv->tx_dma_desc, msgdma_descroffs(write_addr_hi));
csrwr32(buffer->len, priv->tx_dma_desc, msgdma_descroffs(len));
csrwr32(0, priv->tx_dma_desc, msgdma_descroffs(burst_seq_num));
csrwr32(MSGDMA_DESC_TX_STRIDE, priv->tx_dma_desc,
msgdma_descroffs(stride));
csrwr32(MSGDMA_DESC_CTL_TX_SINGLE, priv->tx_dma_desc,
msgdma_descroffs(control));
return 0;
}
u32 msgdma_tx_completions(struct altera_tse_private *priv)
{
u32 ready = 0;
u32 inuse;
u32 status;
/* Get number of sent descriptors */
inuse = csrrd32(priv->tx_dma_csr, msgdma_csroffs(rw_fill_level))
& 0xffff;
if (inuse) { /* Tx FIFO is not empty */
ready = max_t(int,
priv->tx_prod - priv->tx_cons - inuse - 1, 0);
} else {
/* Check for buffered last packet */
status = csrrd32(priv->tx_dma_csr, msgdma_csroffs(status));
if (status & MSGDMA_CSR_STAT_BUSY)
ready = priv->tx_prod - priv->tx_cons - 1;
else
ready = priv->tx_prod - priv->tx_cons;
}
return ready;
}
/* Put buffer to the mSGDMA RX FIFO
*/
void msgdma_add_rx_desc(struct altera_tse_private *priv,
struct tse_buffer *rxbuffer)
{
u32 len = priv->rx_dma_buf_sz;
dma_addr_t dma_addr = rxbuffer->dma_addr;
u32 control = (MSGDMA_DESC_CTL_END_ON_EOP
| MSGDMA_DESC_CTL_END_ON_LEN
| MSGDMA_DESC_CTL_TR_COMP_IRQ
| MSGDMA_DESC_CTL_EARLY_IRQ
| MSGDMA_DESC_CTL_TR_ERR_IRQ
| MSGDMA_DESC_CTL_GO);
csrwr32(0, priv->rx_dma_desc, msgdma_descroffs(read_addr_lo));
csrwr32(0, priv->rx_dma_desc, msgdma_descroffs(read_addr_hi));
csrwr32(lower_32_bits(dma_addr), priv->rx_dma_desc,
msgdma_descroffs(write_addr_lo));
csrwr32(upper_32_bits(dma_addr), priv->rx_dma_desc,
msgdma_descroffs(write_addr_hi));
csrwr32(len, priv->rx_dma_desc, msgdma_descroffs(len));
csrwr32(0, priv->rx_dma_desc, msgdma_descroffs(burst_seq_num));
csrwr32(0x00010001, priv->rx_dma_desc, msgdma_descroffs(stride));
csrwr32(control, priv->rx_dma_desc, msgdma_descroffs(control));
}
/* status is returned on upper 16 bits,
* length is returned in lower 16 bits
*/
u32 msgdma_rx_status(struct altera_tse_private *priv)
{
u32 rxstatus = 0;
u32 pktlength;
u32 pktstatus;
if (csrrd32(priv->rx_dma_csr, msgdma_csroffs(resp_fill_level))
& 0xffff) {
pktlength = csrrd32(priv->rx_dma_resp,
msgdma_respoffs(bytes_transferred));
pktstatus = csrrd32(priv->rx_dma_resp,
msgdma_respoffs(status));
rxstatus = pktstatus;
rxstatus = rxstatus << 16;
rxstatus |= (pktlength & 0xffff);
}
return rxstatus;
}
|
linux-master
|
drivers/net/ethernet/altera/altera_msgdma.c
|
/* sis900.c: A SiS 900/7016 PCI Fast Ethernet driver for Linux.
Copyright 1999 Silicon Integrated System Corporation
Revision: 1.08.10 Apr. 2 2006
Modified from the driver which is originally written by Donald Becker.
This software may be used and distributed according to the terms
of the GNU General Public License (GPL), incorporated herein by reference.
Drivers based on this skeleton fall under the GPL and must retain
the authorship (implicit copyright) notice.
References:
SiS 7016 Fast Ethernet PCI Bus 10/100 Mbps LAN Controller with OnNow Support,
preliminary Rev. 1.0 Jan. 14, 1998
SiS 900 Fast Ethernet PCI Bus 10/100 Mbps LAN Single Chip with OnNow Support,
preliminary Rev. 1.0 Nov. 10, 1998
SiS 7014 Single Chip 100BASE-TX/10BASE-T Physical Layer Solution,
preliminary Rev. 1.0 Jan. 18, 1998
Rev 1.08.10 Apr. 2 2006 Daniele Venzano add vlan (jumbo packets) support
Rev 1.08.09 Sep. 19 2005 Daniele Venzano add Wake on LAN support
Rev 1.08.08 Jan. 22 2005 Daniele Venzano use netif_msg for debugging messages
Rev 1.08.07 Nov. 2 2003 Daniele Venzano <[email protected]> add suspend/resume support
Rev 1.08.06 Sep. 24 2002 Mufasa Yang bug fix for Tx timeout & add SiS963 support
Rev 1.08.05 Jun. 6 2002 Mufasa Yang bug fix for read_eeprom & Tx descriptor over-boundary
Rev 1.08.04 Apr. 25 2002 Mufasa Yang <[email protected]> added SiS962 support
Rev 1.08.03 Feb. 1 2002 Matt Domsch <[email protected]> update to use library crc32 function
Rev 1.08.02 Nov. 30 2001 Hui-Fen Hsu workaround for EDB & bug fix for dhcp problem
Rev 1.08.01 Aug. 25 2001 Hui-Fen Hsu update for 630ET & workaround for ICS1893 PHY
Rev 1.08.00 Jun. 11 2001 Hui-Fen Hsu workaround for RTL8201 PHY and some bug fix
Rev 1.07.11 Apr. 2 2001 Hui-Fen Hsu updates PCI drivers to use the new pci_set_dma_mask for kernel 2.4.3
Rev 1.07.10 Mar. 1 2001 Hui-Fen Hsu <[email protected]> some bug fix & 635M/B support
Rev 1.07.09 Feb. 9 2001 Dave Jones <[email protected]> PCI enable cleanup
Rev 1.07.08 Jan. 8 2001 Lei-Chun Chang added RTL8201 PHY support
Rev 1.07.07 Nov. 29 2000 Lei-Chun Chang added kernel-doc extractable documentation and 630 workaround fix
Rev 1.07.06 Nov. 7 2000 Jeff Garzik <[email protected]> some bug fix and cleaning
Rev 1.07.05 Nov. 6 2000 metapirat<[email protected]> contribute media type select by ifconfig
Rev 1.07.04 Sep. 6 2000 Lei-Chun Chang added ICS1893 PHY support
Rev 1.07.03 Aug. 24 2000 Lei-Chun Chang ([email protected]) modified 630E equalizer workaround rule
Rev 1.07.01 Aug. 08 2000 Ollie Lho minor update for SiS 630E and SiS 630E A1
Rev 1.07 Mar. 07 2000 Ollie Lho bug fix in Rx buffer ring
Rev 1.06.04 Feb. 11 2000 Jeff Garzik <[email protected]> softnet and init for kernel 2.4
Rev 1.06.03 Dec. 23 1999 Ollie Lho Third release
Rev 1.06.02 Nov. 23 1999 Ollie Lho bug in mac probing fixed
Rev 1.06.01 Nov. 16 1999 Ollie Lho CRC calculation provide by Joseph Zbiciak ([email protected])
Rev 1.06 Nov. 4 1999 Ollie Lho ([email protected]) Second release
Rev 1.05.05 Oct. 29 1999 Ollie Lho ([email protected]) Single buffer Tx/Rx
Chin-Shan Li ([email protected]) Added AMD Am79c901 HomePNA PHY support
Rev 1.05 Aug. 7 1999 Jim Huang ([email protected]) Initial release
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/init.h>
#include <linux/mii.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/delay.h>
#include <linux/ethtool.h>
#include <linux/crc32.h>
#include <linux/bitops.h>
#include <linux/dma-mapping.h>
#include <asm/processor.h> /* Processor type for cache alignment. */
#include <asm/io.h>
#include <asm/irq.h>
#include <linux/uaccess.h> /* User space memory access functions */
#include "sis900.h"
#define SIS900_MODULE_NAME "sis900"
#define SIS900_DRV_VERSION "v1.08.10 Apr. 2 2006"
static const char version[] =
KERN_INFO "sis900.c: " SIS900_DRV_VERSION "\n";
static int max_interrupt_work = 40;
static int multicast_filter_limit = 128;
static int sis900_debug = -1; /* Use SIS900_DEF_MSG as value */
#define SIS900_DEF_MSG \
(NETIF_MSG_DRV | \
NETIF_MSG_LINK | \
NETIF_MSG_RX_ERR | \
NETIF_MSG_TX_ERR)
/* Time in jiffies before concluding the transmitter is hung. */
#define TX_TIMEOUT (4*HZ)
enum {
SIS_900 = 0,
SIS_7016
};
static const char * card_names[] = {
"SiS 900 PCI Fast Ethernet",
"SiS 7016 PCI Fast Ethernet"
};
static const struct pci_device_id sis900_pci_tbl[] = {
{PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_900,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, SIS_900},
{PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_7016,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, SIS_7016},
{0,}
};
MODULE_DEVICE_TABLE (pci, sis900_pci_tbl);
static void sis900_read_mode(struct net_device *net_dev, int *speed, int *duplex);
static const struct mii_chip_info {
const char * name;
u16 phy_id0;
u16 phy_id1;
u8 phy_types;
#define HOME 0x0001
#define LAN 0x0002
#define MIX 0x0003
#define UNKNOWN 0x0
} mii_chip_table[] = {
{ "SiS 900 Internal MII PHY", 0x001d, 0x8000, LAN },
{ "SiS 7014 Physical Layer Solution", 0x0016, 0xf830, LAN },
{ "SiS 900 on Foxconn 661 7MI", 0x0143, 0xBC70, LAN },
{ "Altimata AC101LF PHY", 0x0022, 0x5520, LAN },
{ "ADM 7001 LAN PHY", 0x002e, 0xcc60, LAN },
{ "AMD 79C901 10BASE-T PHY", 0x0000, 0x6B70, LAN },
{ "AMD 79C901 HomePNA PHY", 0x0000, 0x6B90, HOME},
{ "ICS LAN PHY", 0x0015, 0xF440, LAN },
{ "ICS LAN PHY", 0x0143, 0xBC70, LAN },
{ "NS 83851 PHY", 0x2000, 0x5C20, MIX },
{ "NS 83847 PHY", 0x2000, 0x5C30, MIX },
{ "Realtek RTL8201 PHY", 0x0000, 0x8200, LAN },
{ "VIA 6103 PHY", 0x0101, 0x8f20, LAN },
{NULL,},
};
struct mii_phy {
struct mii_phy * next;
int phy_addr;
u16 phy_id0;
u16 phy_id1;
u16 status;
u8 phy_types;
};
typedef struct _BufferDesc {
u32 link;
u32 cmdsts;
u32 bufptr;
} BufferDesc;
struct sis900_private {
struct pci_dev * pci_dev;
spinlock_t lock;
struct mii_phy * mii;
struct mii_phy * first_mii; /* record the first mii structure */
unsigned int cur_phy;
struct mii_if_info mii_info;
void __iomem *ioaddr;
struct timer_list timer; /* Link status detection timer. */
u8 autong_complete; /* 1: auto-negotiate complete */
u32 msg_enable;
unsigned int cur_rx, dirty_rx; /* producer/consumer pointers for Tx/Rx ring */
unsigned int cur_tx, dirty_tx;
/* The saved address of a sent/receive-in-place packet buffer */
struct sk_buff *tx_skbuff[NUM_TX_DESC];
struct sk_buff *rx_skbuff[NUM_RX_DESC];
BufferDesc *tx_ring;
BufferDesc *rx_ring;
dma_addr_t tx_ring_dma;
dma_addr_t rx_ring_dma;
unsigned int tx_full; /* The Tx queue is full. */
u8 host_bridge_rev;
u8 chipset_rev;
/* EEPROM data */
int eeprom_size;
};
MODULE_AUTHOR("Jim Huang <[email protected]>, Ollie Lho <[email protected]>");
MODULE_DESCRIPTION("SiS 900 PCI Fast Ethernet driver");
MODULE_LICENSE("GPL");
module_param(multicast_filter_limit, int, 0444);
module_param(max_interrupt_work, int, 0444);
module_param(sis900_debug, int, 0444);
MODULE_PARM_DESC(multicast_filter_limit, "SiS 900/7016 maximum number of filtered multicast addresses");
MODULE_PARM_DESC(max_interrupt_work, "SiS 900/7016 maximum events handled per interrupt");
MODULE_PARM_DESC(sis900_debug, "SiS 900/7016 bitmapped debugging message level");
#define sw32(reg, val) iowrite32(val, ioaddr + (reg))
#define sw8(reg, val) iowrite8(val, ioaddr + (reg))
#define sr32(reg) ioread32(ioaddr + (reg))
#define sr16(reg) ioread16(ioaddr + (reg))
#ifdef CONFIG_NET_POLL_CONTROLLER
static void sis900_poll(struct net_device *dev);
#endif
static int sis900_open(struct net_device *net_dev);
static int sis900_mii_probe (struct net_device * net_dev);
static void sis900_init_rxfilter (struct net_device * net_dev);
static u16 read_eeprom(void __iomem *ioaddr, int location);
static int mdio_read(struct net_device *net_dev, int phy_id, int location);
static void mdio_write(struct net_device *net_dev, int phy_id, int location, int val);
static void sis900_timer(struct timer_list *t);
static void sis900_check_mode (struct net_device *net_dev, struct mii_phy *mii_phy);
static void sis900_tx_timeout(struct net_device *net_dev, unsigned int txqueue);
static void sis900_init_tx_ring(struct net_device *net_dev);
static void sis900_init_rx_ring(struct net_device *net_dev);
static netdev_tx_t sis900_start_xmit(struct sk_buff *skb,
struct net_device *net_dev);
static int sis900_rx(struct net_device *net_dev);
static void sis900_finish_xmit (struct net_device *net_dev);
static irqreturn_t sis900_interrupt(int irq, void *dev_instance);
static int sis900_close(struct net_device *net_dev);
static int mii_ioctl(struct net_device *net_dev, struct ifreq *rq, int cmd);
static u16 sis900_mcast_bitnr(u8 *addr, u8 revision);
static void set_rx_mode(struct net_device *net_dev);
static void sis900_reset(struct net_device *net_dev);
static void sis630_set_eq(struct net_device *net_dev, u8 revision);
static int sis900_set_config(struct net_device *dev, struct ifmap *map);
static u16 sis900_default_phy(struct net_device * net_dev);
static void sis900_set_capability( struct net_device *net_dev ,struct mii_phy *phy);
static u16 sis900_reset_phy(struct net_device *net_dev, int phy_addr);
static void sis900_auto_negotiate(struct net_device *net_dev, int phy_addr);
static void sis900_set_mode(struct sis900_private *, int speed, int duplex);
static const struct ethtool_ops sis900_ethtool_ops;
/**
* sis900_get_mac_addr - Get MAC address for stand alone SiS900 model
* @pci_dev: the sis900 pci device
* @net_dev: the net device to get address for
*
* Older SiS900 and friends, use EEPROM to store MAC address.
* MAC address is read from read_eeprom() into @net_dev->dev_addr.
*/
static int sis900_get_mac_addr(struct pci_dev *pci_dev,
struct net_device *net_dev)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
void __iomem *ioaddr = sis_priv->ioaddr;
u16 addr[ETH_ALEN / 2];
u16 signature;
int i;
/* check to see if we have sane EEPROM */
signature = (u16) read_eeprom(ioaddr, EEPROMSignature);
if (signature == 0xffff || signature == 0x0000) {
printk (KERN_WARNING "%s: Error EEPROM read %x\n",
pci_name(pci_dev), signature);
return 0;
}
/* get MAC address from EEPROM */
for (i = 0; i < 3; i++)
addr[i] = read_eeprom(ioaddr, i+EEPROMMACAddr);
eth_hw_addr_set(net_dev, (u8 *)addr);
return 1;
}
/**
* sis630e_get_mac_addr - Get MAC address for SiS630E model
* @pci_dev: the sis900 pci device
* @net_dev: the net device to get address for
*
* SiS630E model, use APC CMOS RAM to store MAC address.
* APC CMOS RAM is accessed through ISA bridge.
* MAC address is read into @net_dev->dev_addr.
*/
static int sis630e_get_mac_addr(struct pci_dev *pci_dev,
struct net_device *net_dev)
{
struct pci_dev *isa_bridge = NULL;
u8 addr[ETH_ALEN];
u8 reg;
int i;
isa_bridge = pci_get_device(PCI_VENDOR_ID_SI, 0x0008, isa_bridge);
if (!isa_bridge)
isa_bridge = pci_get_device(PCI_VENDOR_ID_SI, 0x0018, isa_bridge);
if (!isa_bridge) {
printk(KERN_WARNING "%s: Can not find ISA bridge\n",
pci_name(pci_dev));
return 0;
}
pci_read_config_byte(isa_bridge, 0x48, ®);
pci_write_config_byte(isa_bridge, 0x48, reg | 0x40);
for (i = 0; i < 6; i++) {
outb(0x09 + i, 0x70);
addr[i] = inb(0x71);
}
eth_hw_addr_set(net_dev, addr);
pci_write_config_byte(isa_bridge, 0x48, reg & ~0x40);
pci_dev_put(isa_bridge);
return 1;
}
/**
* sis635_get_mac_addr - Get MAC address for SIS635 model
* @pci_dev: the sis900 pci device
* @net_dev: the net device to get address for
*
* SiS635 model, set MAC Reload Bit to load Mac address from APC
* to rfdr. rfdr is accessed through rfcr. MAC address is read into
* @net_dev->dev_addr.
*/
static int sis635_get_mac_addr(struct pci_dev *pci_dev,
struct net_device *net_dev)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
void __iomem *ioaddr = sis_priv->ioaddr;
u16 addr[ETH_ALEN / 2];
u32 rfcrSave;
u32 i;
rfcrSave = sr32(rfcr);
sw32(cr, rfcrSave | RELOAD);
sw32(cr, 0);
/* disable packet filtering before setting filter */
sw32(rfcr, rfcrSave & ~RFEN);
/* load MAC addr to filter data register */
for (i = 0 ; i < 3 ; i++) {
sw32(rfcr, (i << RFADDR_shift));
addr[i] = sr16(rfdr);
}
eth_hw_addr_set(net_dev, (u8 *)addr);
/* enable packet filtering */
sw32(rfcr, rfcrSave | RFEN);
return 1;
}
/**
* sis96x_get_mac_addr - Get MAC address for SiS962 or SiS963 model
* @pci_dev: the sis900 pci device
* @net_dev: the net device to get address for
*
* SiS962 or SiS963 model, use EEPROM to store MAC address. And EEPROM
* is shared by
* LAN and 1394. When accessing EEPROM, send EEREQ signal to hardware first
* and wait for EEGNT. If EEGNT is ON, EEPROM is permitted to be accessed
* by LAN, otherwise it is not. After MAC address is read from EEPROM, send
* EEDONE signal to refuse EEPROM access by LAN.
* The EEPROM map of SiS962 or SiS963 is different to SiS900.
* The signature field in SiS962 or SiS963 spec is meaningless.
* MAC address is read into @net_dev->dev_addr.
*/
static int sis96x_get_mac_addr(struct pci_dev *pci_dev,
struct net_device *net_dev)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
void __iomem *ioaddr = sis_priv->ioaddr;
u16 addr[ETH_ALEN / 2];
int wait, rc = 0;
sw32(mear, EEREQ);
for (wait = 0; wait < 2000; wait++) {
if (sr32(mear) & EEGNT) {
int i;
/* get MAC address from EEPROM */
for (i = 0; i < 3; i++)
addr[i] = read_eeprom(ioaddr, i + EEPROMMACAddr);
eth_hw_addr_set(net_dev, (u8 *)addr);
rc = 1;
break;
}
udelay(1);
}
sw32(mear, EEDONE);
return rc;
}
static const struct net_device_ops sis900_netdev_ops = {
.ndo_open = sis900_open,
.ndo_stop = sis900_close,
.ndo_start_xmit = sis900_start_xmit,
.ndo_set_config = sis900_set_config,
.ndo_set_rx_mode = set_rx_mode,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = eth_mac_addr,
.ndo_eth_ioctl = mii_ioctl,
.ndo_tx_timeout = sis900_tx_timeout,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = sis900_poll,
#endif
};
/**
* sis900_probe - Probe for sis900 device
* @pci_dev: the sis900 pci device
* @pci_id: the pci device ID
*
* Check and probe sis900 net device for @pci_dev.
* Get mac address according to the chip revision,
* and assign SiS900-specific entries in the device structure.
* ie: sis900_open(), sis900_start_xmit(), sis900_close(), etc.
*/
static int sis900_probe(struct pci_dev *pci_dev,
const struct pci_device_id *pci_id)
{
struct sis900_private *sis_priv;
struct net_device *net_dev;
struct pci_dev *dev;
dma_addr_t ring_dma;
void *ring_space;
void __iomem *ioaddr;
int i, ret;
const char *card_name = card_names[pci_id->driver_data];
const char *dev_name = pci_name(pci_dev);
/* when built into the kernel, we only print version if device is found */
#ifndef MODULE
static int printed_version;
if (!printed_version++)
printk(version);
#endif
/* setup various bits in PCI command register */
ret = pcim_enable_device(pci_dev);
if(ret) return ret;
i = dma_set_mask(&pci_dev->dev, DMA_BIT_MASK(32));
if(i){
printk(KERN_ERR "sis900.c: architecture does not support "
"32bit PCI busmaster DMA\n");
return i;
}
pci_set_master(pci_dev);
net_dev = alloc_etherdev(sizeof(struct sis900_private));
if (!net_dev)
return -ENOMEM;
SET_NETDEV_DEV(net_dev, &pci_dev->dev);
/* We do a request_region() to register /proc/ioports info. */
ret = pci_request_regions(pci_dev, "sis900");
if (ret)
goto err_out;
/* IO region. */
ioaddr = pci_iomap(pci_dev, 0, 0);
if (!ioaddr) {
ret = -ENOMEM;
goto err_out;
}
sis_priv = netdev_priv(net_dev);
sis_priv->ioaddr = ioaddr;
sis_priv->pci_dev = pci_dev;
spin_lock_init(&sis_priv->lock);
sis_priv->eeprom_size = 24;
pci_set_drvdata(pci_dev, net_dev);
ring_space = dma_alloc_coherent(&pci_dev->dev, TX_TOTAL_SIZE,
&ring_dma, GFP_KERNEL);
if (!ring_space) {
ret = -ENOMEM;
goto err_out_unmap;
}
sis_priv->tx_ring = ring_space;
sis_priv->tx_ring_dma = ring_dma;
ring_space = dma_alloc_coherent(&pci_dev->dev, RX_TOTAL_SIZE,
&ring_dma, GFP_KERNEL);
if (!ring_space) {
ret = -ENOMEM;
goto err_unmap_tx;
}
sis_priv->rx_ring = ring_space;
sis_priv->rx_ring_dma = ring_dma;
/* The SiS900-specific entries in the device structure. */
net_dev->netdev_ops = &sis900_netdev_ops;
net_dev->watchdog_timeo = TX_TIMEOUT;
net_dev->ethtool_ops = &sis900_ethtool_ops;
if (sis900_debug > 0)
sis_priv->msg_enable = sis900_debug;
else
sis_priv->msg_enable = SIS900_DEF_MSG;
sis_priv->mii_info.dev = net_dev;
sis_priv->mii_info.mdio_read = mdio_read;
sis_priv->mii_info.mdio_write = mdio_write;
sis_priv->mii_info.phy_id_mask = 0x1f;
sis_priv->mii_info.reg_num_mask = 0x1f;
/* Get Mac address according to the chip revision */
sis_priv->chipset_rev = pci_dev->revision;
if(netif_msg_probe(sis_priv))
printk(KERN_DEBUG "%s: detected revision %2.2x, "
"trying to get MAC address...\n",
dev_name, sis_priv->chipset_rev);
ret = 0;
if (sis_priv->chipset_rev == SIS630E_900_REV)
ret = sis630e_get_mac_addr(pci_dev, net_dev);
else if ((sis_priv->chipset_rev > 0x81) && (sis_priv->chipset_rev <= 0x90) )
ret = sis635_get_mac_addr(pci_dev, net_dev);
else if (sis_priv->chipset_rev == SIS96x_900_REV)
ret = sis96x_get_mac_addr(pci_dev, net_dev);
else
ret = sis900_get_mac_addr(pci_dev, net_dev);
if (!ret || !is_valid_ether_addr(net_dev->dev_addr)) {
eth_hw_addr_random(net_dev);
printk(KERN_WARNING "%s: Unreadable or invalid MAC address,"
"using random generated one\n", dev_name);
}
/* 630ET : set the mii access mode as software-mode */
if (sis_priv->chipset_rev == SIS630ET_900_REV)
sw32(cr, ACCESSMODE | sr32(cr));
/* probe for mii transceiver */
if (sis900_mii_probe(net_dev) == 0) {
printk(KERN_WARNING "%s: Error probing MII device.\n",
dev_name);
ret = -ENODEV;
goto err_unmap_rx;
}
/* save our host bridge revision */
dev = pci_get_device(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_630, NULL);
if (dev) {
sis_priv->host_bridge_rev = dev->revision;
pci_dev_put(dev);
}
ret = register_netdev(net_dev);
if (ret)
goto err_unmap_rx;
/* print some information about our NIC */
printk(KERN_INFO "%s: %s at 0x%p, IRQ %d, %pM\n",
net_dev->name, card_name, ioaddr, pci_dev->irq,
net_dev->dev_addr);
/* Detect Wake on Lan support */
ret = (sr32(CFGPMC) & PMESP) >> 27;
if (netif_msg_probe(sis_priv) && (ret & PME_D3C) == 0)
printk(KERN_INFO "%s: Wake on LAN only available from suspend to RAM.", net_dev->name);
return 0;
err_unmap_rx:
dma_free_coherent(&pci_dev->dev, RX_TOTAL_SIZE, sis_priv->rx_ring,
sis_priv->rx_ring_dma);
err_unmap_tx:
dma_free_coherent(&pci_dev->dev, TX_TOTAL_SIZE, sis_priv->tx_ring,
sis_priv->tx_ring_dma);
err_out_unmap:
pci_iounmap(pci_dev, ioaddr);
err_out:
free_netdev(net_dev);
return ret;
}
/**
* sis900_mii_probe - Probe MII PHY for sis900
* @net_dev: the net device to probe for
*
* Search for total of 32 possible mii phy addresses.
* Identify and set current phy if found one,
* return error if it failed to found.
*/
static int sis900_mii_probe(struct net_device *net_dev)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
const char *dev_name = pci_name(sis_priv->pci_dev);
u16 poll_bit = MII_STAT_LINK, status = 0;
unsigned long timeout = jiffies + 5 * HZ;
int phy_addr;
sis_priv->mii = NULL;
/* search for total of 32 possible mii phy addresses */
for (phy_addr = 0; phy_addr < 32; phy_addr++) {
struct mii_phy * mii_phy = NULL;
u16 mii_status;
int i;
mii_phy = NULL;
for(i = 0; i < 2; i++)
mii_status = mdio_read(net_dev, phy_addr, MII_STATUS);
if (mii_status == 0xffff || mii_status == 0x0000) {
if (netif_msg_probe(sis_priv))
printk(KERN_DEBUG "%s: MII at address %d"
" not accessible\n",
dev_name, phy_addr);
continue;
}
if ((mii_phy = kmalloc(sizeof(struct mii_phy), GFP_KERNEL)) == NULL) {
mii_phy = sis_priv->first_mii;
while (mii_phy) {
struct mii_phy *phy;
phy = mii_phy;
mii_phy = mii_phy->next;
kfree(phy);
}
return 0;
}
mii_phy->phy_id0 = mdio_read(net_dev, phy_addr, MII_PHY_ID0);
mii_phy->phy_id1 = mdio_read(net_dev, phy_addr, MII_PHY_ID1);
mii_phy->phy_addr = phy_addr;
mii_phy->status = mii_status;
mii_phy->next = sis_priv->mii;
sis_priv->mii = mii_phy;
sis_priv->first_mii = mii_phy;
for (i = 0; mii_chip_table[i].phy_id1; i++)
if ((mii_phy->phy_id0 == mii_chip_table[i].phy_id0 ) &&
((mii_phy->phy_id1 & 0xFFF0) == mii_chip_table[i].phy_id1)){
mii_phy->phy_types = mii_chip_table[i].phy_types;
if (mii_chip_table[i].phy_types == MIX)
mii_phy->phy_types =
(mii_status & (MII_STAT_CAN_TX_FDX | MII_STAT_CAN_TX)) ? LAN : HOME;
printk(KERN_INFO "%s: %s transceiver found "
"at address %d.\n",
dev_name,
mii_chip_table[i].name,
phy_addr);
break;
}
if( !mii_chip_table[i].phy_id1 ) {
printk(KERN_INFO "%s: Unknown PHY transceiver found at address %d.\n",
dev_name, phy_addr);
mii_phy->phy_types = UNKNOWN;
}
}
if (sis_priv->mii == NULL) {
printk(KERN_INFO "%s: No MII transceivers found!\n", dev_name);
return 0;
}
/* select default PHY for mac */
sis_priv->mii = NULL;
sis900_default_phy( net_dev );
/* Reset phy if default phy is internal sis900 */
if ((sis_priv->mii->phy_id0 == 0x001D) &&
((sis_priv->mii->phy_id1&0xFFF0) == 0x8000))
status = sis900_reset_phy(net_dev, sis_priv->cur_phy);
/* workaround for ICS1893 PHY */
if ((sis_priv->mii->phy_id0 == 0x0015) &&
((sis_priv->mii->phy_id1&0xFFF0) == 0xF440))
mdio_write(net_dev, sis_priv->cur_phy, 0x0018, 0xD200);
if(status & MII_STAT_LINK){
while (poll_bit) {
yield();
poll_bit ^= (mdio_read(net_dev, sis_priv->cur_phy, MII_STATUS) & poll_bit);
if (time_after_eq(jiffies, timeout)) {
printk(KERN_WARNING "%s: reset phy and link down now\n",
dev_name);
return -ETIME;
}
}
}
if (sis_priv->chipset_rev == SIS630E_900_REV) {
/* SiS 630E has some bugs on default value of PHY registers */
mdio_write(net_dev, sis_priv->cur_phy, MII_ANADV, 0x05e1);
mdio_write(net_dev, sis_priv->cur_phy, MII_CONFIG1, 0x22);
mdio_write(net_dev, sis_priv->cur_phy, MII_CONFIG2, 0xff00);
mdio_write(net_dev, sis_priv->cur_phy, MII_MASK, 0xffc0);
//mdio_write(net_dev, sis_priv->cur_phy, MII_CONTROL, 0x1000);
}
if (sis_priv->mii->status & MII_STAT_LINK)
netif_carrier_on(net_dev);
else
netif_carrier_off(net_dev);
return 1;
}
/**
* sis900_default_phy - Select default PHY for sis900 mac.
* @net_dev: the net device to probe for
*
* Select first detected PHY with link as default.
* If no one is link on, select PHY whose types is HOME as default.
* If HOME doesn't exist, select LAN.
*/
static u16 sis900_default_phy(struct net_device * net_dev)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
struct mii_phy *phy = NULL, *phy_home = NULL,
*default_phy = NULL, *phy_lan = NULL;
u16 status;
for (phy=sis_priv->first_mii; phy; phy=phy->next) {
status = mdio_read(net_dev, phy->phy_addr, MII_STATUS);
status = mdio_read(net_dev, phy->phy_addr, MII_STATUS);
/* Link ON & Not select default PHY & not ghost PHY */
if ((status & MII_STAT_LINK) && !default_phy &&
(phy->phy_types != UNKNOWN)) {
default_phy = phy;
} else {
status = mdio_read(net_dev, phy->phy_addr, MII_CONTROL);
mdio_write(net_dev, phy->phy_addr, MII_CONTROL,
status | MII_CNTL_AUTO | MII_CNTL_ISOLATE);
if (phy->phy_types == HOME)
phy_home = phy;
else if(phy->phy_types == LAN)
phy_lan = phy;
}
}
if (!default_phy && phy_home)
default_phy = phy_home;
else if (!default_phy && phy_lan)
default_phy = phy_lan;
else if (!default_phy)
default_phy = sis_priv->first_mii;
if (sis_priv->mii != default_phy) {
sis_priv->mii = default_phy;
sis_priv->cur_phy = default_phy->phy_addr;
printk(KERN_INFO "%s: Using transceiver found at address %d as default\n",
pci_name(sis_priv->pci_dev), sis_priv->cur_phy);
}
sis_priv->mii_info.phy_id = sis_priv->cur_phy;
status = mdio_read(net_dev, sis_priv->cur_phy, MII_CONTROL);
status &= (~MII_CNTL_ISOLATE);
mdio_write(net_dev, sis_priv->cur_phy, MII_CONTROL, status);
status = mdio_read(net_dev, sis_priv->cur_phy, MII_STATUS);
status = mdio_read(net_dev, sis_priv->cur_phy, MII_STATUS);
return status;
}
/**
* sis900_set_capability - set the media capability of network adapter.
* @net_dev : the net device to probe for
* @phy : default PHY
*
* Set the media capability of network adapter according to
* mii status register. It's necessary before auto-negotiate.
*/
static void sis900_set_capability(struct net_device *net_dev, struct mii_phy *phy)
{
u16 cap;
mdio_read(net_dev, phy->phy_addr, MII_STATUS);
mdio_read(net_dev, phy->phy_addr, MII_STATUS);
cap = MII_NWAY_CSMA_CD |
((phy->status & MII_STAT_CAN_TX_FDX)? MII_NWAY_TX_FDX:0) |
((phy->status & MII_STAT_CAN_TX) ? MII_NWAY_TX:0) |
((phy->status & MII_STAT_CAN_T_FDX) ? MII_NWAY_T_FDX:0)|
((phy->status & MII_STAT_CAN_T) ? MII_NWAY_T:0);
mdio_write(net_dev, phy->phy_addr, MII_ANADV, cap);
}
/* Delay between EEPROM clock transitions. */
#define eeprom_delay() sr32(mear)
/**
* read_eeprom - Read Serial EEPROM
* @ioaddr: base i/o address
* @location: the EEPROM location to read
*
* Read Serial EEPROM through EEPROM Access Register.
* Note that location is in word (16 bits) unit
*/
static u16 read_eeprom(void __iomem *ioaddr, int location)
{
u32 read_cmd = location | EEread;
int i;
u16 retval = 0;
sw32(mear, 0);
eeprom_delay();
sw32(mear, EECS);
eeprom_delay();
/* Shift the read command (9) bits out. */
for (i = 8; i >= 0; i--) {
u32 dataval = (read_cmd & (1 << i)) ? EEDI | EECS : EECS;
sw32(mear, dataval);
eeprom_delay();
sw32(mear, dataval | EECLK);
eeprom_delay();
}
sw32(mear, EECS);
eeprom_delay();
/* read the 16-bits data in */
for (i = 16; i > 0; i--) {
sw32(mear, EECS);
eeprom_delay();
sw32(mear, EECS | EECLK);
eeprom_delay();
retval = (retval << 1) | ((sr32(mear) & EEDO) ? 1 : 0);
eeprom_delay();
}
/* Terminate the EEPROM access. */
sw32(mear, 0);
eeprom_delay();
return retval;
}
/* Read and write the MII management registers using software-generated
serial MDIO protocol. Note that the command bits and data bits are
send out separately */
#define mdio_delay() sr32(mear)
static void mdio_idle(struct sis900_private *sp)
{
void __iomem *ioaddr = sp->ioaddr;
sw32(mear, MDIO | MDDIR);
mdio_delay();
sw32(mear, MDIO | MDDIR | MDC);
}
/* Synchronize the MII management interface by shifting 32 one bits out. */
static void mdio_reset(struct sis900_private *sp)
{
void __iomem *ioaddr = sp->ioaddr;
int i;
for (i = 31; i >= 0; i--) {
sw32(mear, MDDIR | MDIO);
mdio_delay();
sw32(mear, MDDIR | MDIO | MDC);
mdio_delay();
}
}
/**
* mdio_read - read MII PHY register
* @net_dev: the net device to read
* @phy_id: the phy address to read
* @location: the phy register id to read
*
* Read MII registers through MDIO and MDC
* using MDIO management frame structure and protocol(defined by ISO/IEC).
* Please see SiS7014 or ICS spec
*/
static int mdio_read(struct net_device *net_dev, int phy_id, int location)
{
int mii_cmd = MIIread|(phy_id<<MIIpmdShift)|(location<<MIIregShift);
struct sis900_private *sp = netdev_priv(net_dev);
void __iomem *ioaddr = sp->ioaddr;
u16 retval = 0;
int i;
mdio_reset(sp);
mdio_idle(sp);
for (i = 15; i >= 0; i--) {
int dataval = (mii_cmd & (1 << i)) ? MDDIR | MDIO : MDDIR;
sw32(mear, dataval);
mdio_delay();
sw32(mear, dataval | MDC);
mdio_delay();
}
/* Read the 16 data bits. */
for (i = 16; i > 0; i--) {
sw32(mear, 0);
mdio_delay();
retval = (retval << 1) | ((sr32(mear) & MDIO) ? 1 : 0);
sw32(mear, MDC);
mdio_delay();
}
sw32(mear, 0x00);
return retval;
}
/**
* mdio_write - write MII PHY register
* @net_dev: the net device to write
* @phy_id: the phy address to write
* @location: the phy register id to write
* @value: the register value to write with
*
* Write MII registers with @value through MDIO and MDC
* using MDIO management frame structure and protocol(defined by ISO/IEC)
* please see SiS7014 or ICS spec
*/
static void mdio_write(struct net_device *net_dev, int phy_id, int location,
int value)
{
int mii_cmd = MIIwrite|(phy_id<<MIIpmdShift)|(location<<MIIregShift);
struct sis900_private *sp = netdev_priv(net_dev);
void __iomem *ioaddr = sp->ioaddr;
int i;
mdio_reset(sp);
mdio_idle(sp);
/* Shift the command bits out. */
for (i = 15; i >= 0; i--) {
int dataval = (mii_cmd & (1 << i)) ? MDDIR | MDIO : MDDIR;
sw8(mear, dataval);
mdio_delay();
sw8(mear, dataval | MDC);
mdio_delay();
}
mdio_delay();
/* Shift the value bits out. */
for (i = 15; i >= 0; i--) {
int dataval = (value & (1 << i)) ? MDDIR | MDIO : MDDIR;
sw32(mear, dataval);
mdio_delay();
sw32(mear, dataval | MDC);
mdio_delay();
}
mdio_delay();
/* Clear out extra bits. */
for (i = 2; i > 0; i--) {
sw8(mear, 0);
mdio_delay();
sw8(mear, MDC);
mdio_delay();
}
sw32(mear, 0x00);
}
/**
* sis900_reset_phy - reset sis900 mii phy.
* @net_dev: the net device to write
* @phy_addr: default phy address
*
* Some specific phy can't work properly without reset.
* This function will be called during initialization and
* link status change from ON to DOWN.
*/
static u16 sis900_reset_phy(struct net_device *net_dev, int phy_addr)
{
int i;
u16 status;
for (i = 0; i < 2; i++)
status = mdio_read(net_dev, phy_addr, MII_STATUS);
mdio_write( net_dev, phy_addr, MII_CONTROL, MII_CNTL_RESET );
return status;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
/*
* Polling 'interrupt' - used by things like netconsole to send skbs
* without having to re-enable interrupts. It's not called while
* the interrupt routine is executing.
*/
static void sis900_poll(struct net_device *dev)
{
struct sis900_private *sp = netdev_priv(dev);
const int irq = sp->pci_dev->irq;
disable_irq(irq);
sis900_interrupt(irq, dev);
enable_irq(irq);
}
#endif
/**
* sis900_open - open sis900 device
* @net_dev: the net device to open
*
* Do some initialization and start net interface.
* enable interrupts and set sis900 timer.
*/
static int
sis900_open(struct net_device *net_dev)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
void __iomem *ioaddr = sis_priv->ioaddr;
int ret;
/* Soft reset the chip. */
sis900_reset(net_dev);
/* Equalizer workaround Rule */
sis630_set_eq(net_dev, sis_priv->chipset_rev);
ret = request_irq(sis_priv->pci_dev->irq, sis900_interrupt, IRQF_SHARED,
net_dev->name, net_dev);
if (ret)
return ret;
sis900_init_rxfilter(net_dev);
sis900_init_tx_ring(net_dev);
sis900_init_rx_ring(net_dev);
set_rx_mode(net_dev);
netif_start_queue(net_dev);
/* Workaround for EDB */
sis900_set_mode(sis_priv, HW_SPEED_10_MBPS, FDX_CAPABLE_HALF_SELECTED);
/* Enable all known interrupts by setting the interrupt mask. */
sw32(imr, RxSOVR | RxORN | RxERR | RxOK | TxURN | TxERR | TxDESC);
sw32(cr, RxENA | sr32(cr));
sw32(ier, IE);
sis900_check_mode(net_dev, sis_priv->mii);
/* Set the timer to switch to check for link beat and perhaps switch
to an alternate media type. */
timer_setup(&sis_priv->timer, sis900_timer, 0);
sis_priv->timer.expires = jiffies + HZ;
add_timer(&sis_priv->timer);
return 0;
}
/**
* sis900_init_rxfilter - Initialize the Rx filter
* @net_dev: the net device to initialize for
*
* Set receive filter address to our MAC address
* and enable packet filtering.
*/
static void
sis900_init_rxfilter (struct net_device * net_dev)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
void __iomem *ioaddr = sis_priv->ioaddr;
u32 rfcrSave;
u32 i;
rfcrSave = sr32(rfcr);
/* disable packet filtering before setting filter */
sw32(rfcr, rfcrSave & ~RFEN);
/* load MAC addr to filter data register */
for (i = 0 ; i < 3 ; i++) {
u32 w = (u32) *((const u16 *)(net_dev->dev_addr)+i);
sw32(rfcr, i << RFADDR_shift);
sw32(rfdr, w);
if (netif_msg_hw(sis_priv)) {
printk(KERN_DEBUG "%s: Receive Filter Address[%d]=%x\n",
net_dev->name, i, sr32(rfdr));
}
}
/* enable packet filtering */
sw32(rfcr, rfcrSave | RFEN);
}
/**
* sis900_init_tx_ring - Initialize the Tx descriptor ring
* @net_dev: the net device to initialize for
*
* Initialize the Tx descriptor ring,
*/
static void
sis900_init_tx_ring(struct net_device *net_dev)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
void __iomem *ioaddr = sis_priv->ioaddr;
int i;
sis_priv->tx_full = 0;
sis_priv->dirty_tx = sis_priv->cur_tx = 0;
for (i = 0; i < NUM_TX_DESC; i++) {
sis_priv->tx_skbuff[i] = NULL;
sis_priv->tx_ring[i].link = sis_priv->tx_ring_dma +
((i+1)%NUM_TX_DESC)*sizeof(BufferDesc);
sis_priv->tx_ring[i].cmdsts = 0;
sis_priv->tx_ring[i].bufptr = 0;
}
/* load Transmit Descriptor Register */
sw32(txdp, sis_priv->tx_ring_dma);
if (netif_msg_hw(sis_priv))
printk(KERN_DEBUG "%s: TX descriptor register loaded with: %8.8x\n",
net_dev->name, sr32(txdp));
}
/**
* sis900_init_rx_ring - Initialize the Rx descriptor ring
* @net_dev: the net device to initialize for
*
* Initialize the Rx descriptor ring,
* and pre-allocate receive buffers (socket buffer)
*/
static void
sis900_init_rx_ring(struct net_device *net_dev)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
void __iomem *ioaddr = sis_priv->ioaddr;
int i;
sis_priv->cur_rx = 0;
sis_priv->dirty_rx = 0;
/* init RX descriptor */
for (i = 0; i < NUM_RX_DESC; i++) {
sis_priv->rx_skbuff[i] = NULL;
sis_priv->rx_ring[i].link = sis_priv->rx_ring_dma +
((i+1)%NUM_RX_DESC)*sizeof(BufferDesc);
sis_priv->rx_ring[i].cmdsts = 0;
sis_priv->rx_ring[i].bufptr = 0;
}
/* allocate sock buffers */
for (i = 0; i < NUM_RX_DESC; i++) {
struct sk_buff *skb;
if ((skb = netdev_alloc_skb(net_dev, RX_BUF_SIZE)) == NULL) {
/* not enough memory for skbuff, this makes a "hole"
on the buffer ring, it is not clear how the
hardware will react to this kind of degenerated
buffer */
break;
}
sis_priv->rx_skbuff[i] = skb;
sis_priv->rx_ring[i].cmdsts = RX_BUF_SIZE;
sis_priv->rx_ring[i].bufptr = dma_map_single(&sis_priv->pci_dev->dev,
skb->data,
RX_BUF_SIZE,
DMA_FROM_DEVICE);
if (unlikely(dma_mapping_error(&sis_priv->pci_dev->dev,
sis_priv->rx_ring[i].bufptr))) {
dev_kfree_skb(skb);
sis_priv->rx_skbuff[i] = NULL;
break;
}
}
sis_priv->dirty_rx = (unsigned int) (i - NUM_RX_DESC);
/* load Receive Descriptor Register */
sw32(rxdp, sis_priv->rx_ring_dma);
if (netif_msg_hw(sis_priv))
printk(KERN_DEBUG "%s: RX descriptor register loaded with: %8.8x\n",
net_dev->name, sr32(rxdp));
}
/**
* sis630_set_eq - set phy equalizer value for 630 LAN
* @net_dev: the net device to set equalizer value
* @revision: 630 LAN revision number
*
* 630E equalizer workaround rule(Cyrus Huang 08/15)
* PHY register 14h(Test)
* Bit 14: 0 -- Automatically detect (default)
* 1 -- Manually set Equalizer filter
* Bit 13: 0 -- (Default)
* 1 -- Speed up convergence of equalizer setting
* Bit 9 : 0 -- (Default)
* 1 -- Disable Baseline Wander
* Bit 3~7 -- Equalizer filter setting
* Link ON: Set Bit 9, 13 to 1, Bit 14 to 0
* Then calculate equalizer value
* Then set equalizer value, and set Bit 14 to 1, Bit 9 to 0
* Link Off:Set Bit 13 to 1, Bit 14 to 0
* Calculate Equalizer value:
* When Link is ON and Bit 14 is 0, SIS900PHY will auto-detect proper equalizer value.
* When the equalizer is stable, this value is not a fixed value. It will be within
* a small range(eg. 7~9). Then we get a minimum and a maximum value(eg. min=7, max=9)
* 0 <= max <= 4 --> set equalizer to max
* 5 <= max <= 14 --> set equalizer to max+1 or set equalizer to max+2 if max == min
* max >= 15 --> set equalizer to max+5 or set equalizer to max+6 if max == min
*/
static void sis630_set_eq(struct net_device *net_dev, u8 revision)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
u16 reg14h, eq_value=0, max_value=0, min_value=0;
int i, maxcount=10;
if ( !(revision == SIS630E_900_REV || revision == SIS630EA1_900_REV ||
revision == SIS630A_900_REV || revision == SIS630ET_900_REV) )
return;
if (netif_carrier_ok(net_dev)) {
reg14h = mdio_read(net_dev, sis_priv->cur_phy, MII_RESV);
mdio_write(net_dev, sis_priv->cur_phy, MII_RESV,
(0x2200 | reg14h) & 0xBFFF);
for (i=0; i < maxcount; i++) {
eq_value = (0x00F8 & mdio_read(net_dev,
sis_priv->cur_phy, MII_RESV)) >> 3;
if (i == 0)
max_value=min_value=eq_value;
max_value = (eq_value > max_value) ?
eq_value : max_value;
min_value = (eq_value < min_value) ?
eq_value : min_value;
}
/* 630E rule to determine the equalizer value */
if (revision == SIS630E_900_REV || revision == SIS630EA1_900_REV ||
revision == SIS630ET_900_REV) {
if (max_value < 5)
eq_value = max_value;
else if (max_value >= 5 && max_value < 15)
eq_value = (max_value == min_value) ?
max_value+2 : max_value+1;
else if (max_value >= 15)
eq_value=(max_value == min_value) ?
max_value+6 : max_value+5;
}
/* 630B0&B1 rule to determine the equalizer value */
if (revision == SIS630A_900_REV &&
(sis_priv->host_bridge_rev == SIS630B0 ||
sis_priv->host_bridge_rev == SIS630B1)) {
if (max_value == 0)
eq_value = 3;
else
eq_value = (max_value + min_value + 1)/2;
}
/* write equalizer value and setting */
reg14h = mdio_read(net_dev, sis_priv->cur_phy, MII_RESV);
reg14h = (reg14h & 0xFF07) | ((eq_value << 3) & 0x00F8);
reg14h = (reg14h | 0x6000) & 0xFDFF;
mdio_write(net_dev, sis_priv->cur_phy, MII_RESV, reg14h);
} else {
reg14h = mdio_read(net_dev, sis_priv->cur_phy, MII_RESV);
if (revision == SIS630A_900_REV &&
(sis_priv->host_bridge_rev == SIS630B0 ||
sis_priv->host_bridge_rev == SIS630B1))
mdio_write(net_dev, sis_priv->cur_phy, MII_RESV,
(reg14h | 0x2200) & 0xBFFF);
else
mdio_write(net_dev, sis_priv->cur_phy, MII_RESV,
(reg14h | 0x2000) & 0xBFFF);
}
}
/**
* sis900_timer - sis900 timer routine
* @t: timer list containing a pointer to sis900 net device
*
* On each timer ticks we check two things,
* link status (ON/OFF) and link mode (10/100/Full/Half)
*/
static void sis900_timer(struct timer_list *t)
{
struct sis900_private *sis_priv = from_timer(sis_priv, t, timer);
struct net_device *net_dev = sis_priv->mii_info.dev;
struct mii_phy *mii_phy = sis_priv->mii;
static const int next_tick = 5*HZ;
int speed = 0, duplex = 0;
u16 status;
status = mdio_read(net_dev, sis_priv->cur_phy, MII_STATUS);
status = mdio_read(net_dev, sis_priv->cur_phy, MII_STATUS);
/* Link OFF -> ON */
if (!netif_carrier_ok(net_dev)) {
LookForLink:
/* Search for new PHY */
status = sis900_default_phy(net_dev);
mii_phy = sis_priv->mii;
if (status & MII_STAT_LINK) {
WARN_ON(!(status & MII_STAT_AUTO_DONE));
sis900_read_mode(net_dev, &speed, &duplex);
if (duplex) {
sis900_set_mode(sis_priv, speed, duplex);
sis630_set_eq(net_dev, sis_priv->chipset_rev);
netif_carrier_on(net_dev);
}
}
} else {
/* Link ON -> OFF */
if (!(status & MII_STAT_LINK)){
netif_carrier_off(net_dev);
if(netif_msg_link(sis_priv))
printk(KERN_INFO "%s: Media Link Off\n", net_dev->name);
/* Change mode issue */
if ((mii_phy->phy_id0 == 0x001D) &&
((mii_phy->phy_id1 & 0xFFF0) == 0x8000))
sis900_reset_phy(net_dev, sis_priv->cur_phy);
sis630_set_eq(net_dev, sis_priv->chipset_rev);
goto LookForLink;
}
}
sis_priv->timer.expires = jiffies + next_tick;
add_timer(&sis_priv->timer);
}
/**
* sis900_check_mode - check the media mode for sis900
* @net_dev: the net device to be checked
* @mii_phy: the mii phy
*
* Older driver gets the media mode from mii status output
* register. Now we set our media capability and auto-negotiate
* to get the upper bound of speed and duplex between two ends.
* If the types of mii phy is HOME, it doesn't need to auto-negotiate
* and autong_complete should be set to 1.
*/
static void sis900_check_mode(struct net_device *net_dev, struct mii_phy *mii_phy)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
void __iomem *ioaddr = sis_priv->ioaddr;
int speed, duplex;
if (mii_phy->phy_types == LAN) {
sw32(cfg, ~EXD & sr32(cfg));
sis900_set_capability(net_dev , mii_phy);
sis900_auto_negotiate(net_dev, sis_priv->cur_phy);
} else {
sw32(cfg, EXD | sr32(cfg));
speed = HW_SPEED_HOME;
duplex = FDX_CAPABLE_HALF_SELECTED;
sis900_set_mode(sis_priv, speed, duplex);
sis_priv->autong_complete = 1;
}
}
/**
* sis900_set_mode - Set the media mode of mac register.
* @sp: the device private data
* @speed : the transmit speed to be determined
* @duplex: the duplex mode to be determined
*
* Set the media mode of mac register txcfg/rxcfg according to
* speed and duplex of phy. Bit EDB_MASTER_EN indicates the EDB
* bus is used instead of PCI bus. When this bit is set 1, the
* Max DMA Burst Size for TX/RX DMA should be no larger than 16
* double words.
*/
static void sis900_set_mode(struct sis900_private *sp, int speed, int duplex)
{
void __iomem *ioaddr = sp->ioaddr;
u32 tx_flags = 0, rx_flags = 0;
if (sr32( cfg) & EDB_MASTER_EN) {
tx_flags = TxATP | (DMA_BURST_64 << TxMXDMA_shift) |
(TX_FILL_THRESH << TxFILLT_shift);
rx_flags = DMA_BURST_64 << RxMXDMA_shift;
} else {
tx_flags = TxATP | (DMA_BURST_512 << TxMXDMA_shift) |
(TX_FILL_THRESH << TxFILLT_shift);
rx_flags = DMA_BURST_512 << RxMXDMA_shift;
}
if (speed == HW_SPEED_HOME || speed == HW_SPEED_10_MBPS) {
rx_flags |= (RxDRNT_10 << RxDRNT_shift);
tx_flags |= (TxDRNT_10 << TxDRNT_shift);
} else {
rx_flags |= (RxDRNT_100 << RxDRNT_shift);
tx_flags |= (TxDRNT_100 << TxDRNT_shift);
}
if (duplex == FDX_CAPABLE_FULL_SELECTED) {
tx_flags |= (TxCSI | TxHBI);
rx_flags |= RxATX;
}
#if IS_ENABLED(CONFIG_VLAN_8021Q)
/* Can accept Jumbo packet */
rx_flags |= RxAJAB;
#endif
sw32(txcfg, tx_flags);
sw32(rxcfg, rx_flags);
}
/**
* sis900_auto_negotiate - Set the Auto-Negotiation Enable/Reset bit.
* @net_dev: the net device to read mode for
* @phy_addr: mii phy address
*
* If the adapter is link-on, set the auto-negotiate enable/reset bit.
* autong_complete should be set to 0 when starting auto-negotiation.
* autong_complete should be set to 1 if we didn't start auto-negotiation.
* sis900_timer will wait for link on again if autong_complete = 0.
*/
static void sis900_auto_negotiate(struct net_device *net_dev, int phy_addr)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
int i = 0;
u32 status;
for (i = 0; i < 2; i++)
status = mdio_read(net_dev, phy_addr, MII_STATUS);
if (!(status & MII_STAT_LINK)){
if(netif_msg_link(sis_priv))
printk(KERN_INFO "%s: Media Link Off\n", net_dev->name);
sis_priv->autong_complete = 1;
netif_carrier_off(net_dev);
return;
}
/* (Re)start AutoNegotiate */
mdio_write(net_dev, phy_addr, MII_CONTROL,
MII_CNTL_AUTO | MII_CNTL_RST_AUTO);
sis_priv->autong_complete = 0;
}
/**
* sis900_read_mode - read media mode for sis900 internal phy
* @net_dev: the net device to read mode for
* @speed : the transmit speed to be determined
* @duplex : the duplex mode to be determined
*
* The capability of remote end will be put in mii register autorec
* after auto-negotiation. Use AND operation to get the upper bound
* of speed and duplex between two ends.
*/
static void sis900_read_mode(struct net_device *net_dev, int *speed, int *duplex)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
struct mii_phy *phy = sis_priv->mii;
int phy_addr = sis_priv->cur_phy;
u32 status;
u16 autoadv, autorec;
int i;
for (i = 0; i < 2; i++)
status = mdio_read(net_dev, phy_addr, MII_STATUS);
if (!(status & MII_STAT_LINK))
return;
/* AutoNegotiate completed */
autoadv = mdio_read(net_dev, phy_addr, MII_ANADV);
autorec = mdio_read(net_dev, phy_addr, MII_ANLPAR);
status = autoadv & autorec;
*speed = HW_SPEED_10_MBPS;
*duplex = FDX_CAPABLE_HALF_SELECTED;
if (status & (MII_NWAY_TX | MII_NWAY_TX_FDX))
*speed = HW_SPEED_100_MBPS;
if (status & ( MII_NWAY_TX_FDX | MII_NWAY_T_FDX))
*duplex = FDX_CAPABLE_FULL_SELECTED;
sis_priv->autong_complete = 1;
/* Workaround for Realtek RTL8201 PHY issue */
if ((phy->phy_id0 == 0x0000) && ((phy->phy_id1 & 0xFFF0) == 0x8200)) {
if (mdio_read(net_dev, phy_addr, MII_CONTROL) & MII_CNTL_FDX)
*duplex = FDX_CAPABLE_FULL_SELECTED;
if (mdio_read(net_dev, phy_addr, 0x0019) & 0x01)
*speed = HW_SPEED_100_MBPS;
}
if(netif_msg_link(sis_priv))
printk(KERN_INFO "%s: Media Link On %s %s-duplex\n",
net_dev->name,
*speed == HW_SPEED_100_MBPS ?
"100mbps" : "10mbps",
*duplex == FDX_CAPABLE_FULL_SELECTED ?
"full" : "half");
}
/**
* sis900_tx_timeout - sis900 transmit timeout routine
* @net_dev: the net device to transmit
* @txqueue: index of hanging queue
*
* print transmit timeout status
* disable interrupts and do some tasks
*/
static void sis900_tx_timeout(struct net_device *net_dev, unsigned int txqueue)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
void __iomem *ioaddr = sis_priv->ioaddr;
unsigned long flags;
int i;
if (netif_msg_tx_err(sis_priv)) {
printk(KERN_INFO "%s: Transmit timeout, status %8.8x %8.8x\n",
net_dev->name, sr32(cr), sr32(isr));
}
/* Disable interrupts by clearing the interrupt mask. */
sw32(imr, 0x0000);
/* use spinlock to prevent interrupt handler accessing buffer ring */
spin_lock_irqsave(&sis_priv->lock, flags);
/* discard unsent packets */
sis_priv->dirty_tx = sis_priv->cur_tx = 0;
for (i = 0; i < NUM_TX_DESC; i++) {
struct sk_buff *skb = sis_priv->tx_skbuff[i];
if (skb) {
dma_unmap_single(&sis_priv->pci_dev->dev,
sis_priv->tx_ring[i].bufptr,
skb->len, DMA_TO_DEVICE);
dev_kfree_skb_irq(skb);
sis_priv->tx_skbuff[i] = NULL;
sis_priv->tx_ring[i].cmdsts = 0;
sis_priv->tx_ring[i].bufptr = 0;
net_dev->stats.tx_dropped++;
}
}
sis_priv->tx_full = 0;
netif_wake_queue(net_dev);
spin_unlock_irqrestore(&sis_priv->lock, flags);
netif_trans_update(net_dev); /* prevent tx timeout */
/* load Transmit Descriptor Register */
sw32(txdp, sis_priv->tx_ring_dma);
/* Enable all known interrupts by setting the interrupt mask. */
sw32(imr, RxSOVR | RxORN | RxERR | RxOK | TxURN | TxERR | TxDESC);
}
/**
* sis900_start_xmit - sis900 start transmit routine
* @skb: socket buffer pointer to put the data being transmitted
* @net_dev: the net device to transmit with
*
* Set the transmit buffer descriptor,
* and write TxENA to enable transmit state machine.
* tell upper layer if the buffer is full
*/
static netdev_tx_t
sis900_start_xmit(struct sk_buff *skb, struct net_device *net_dev)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
void __iomem *ioaddr = sis_priv->ioaddr;
unsigned int entry;
unsigned long flags;
unsigned int index_cur_tx, index_dirty_tx;
unsigned int count_dirty_tx;
spin_lock_irqsave(&sis_priv->lock, flags);
/* Calculate the next Tx descriptor entry. */
entry = sis_priv->cur_tx % NUM_TX_DESC;
sis_priv->tx_skbuff[entry] = skb;
/* set the transmit buffer descriptor and enable Transmit State Machine */
sis_priv->tx_ring[entry].bufptr = dma_map_single(&sis_priv->pci_dev->dev,
skb->data, skb->len,
DMA_TO_DEVICE);
if (unlikely(dma_mapping_error(&sis_priv->pci_dev->dev,
sis_priv->tx_ring[entry].bufptr))) {
dev_kfree_skb_any(skb);
sis_priv->tx_skbuff[entry] = NULL;
net_dev->stats.tx_dropped++;
spin_unlock_irqrestore(&sis_priv->lock, flags);
return NETDEV_TX_OK;
}
sis_priv->tx_ring[entry].cmdsts = (OWN | INTR | skb->len);
sw32(cr, TxENA | sr32(cr));
sis_priv->cur_tx ++;
index_cur_tx = sis_priv->cur_tx;
index_dirty_tx = sis_priv->dirty_tx;
for (count_dirty_tx = 0; index_cur_tx != index_dirty_tx; index_dirty_tx++)
count_dirty_tx ++;
if (index_cur_tx == index_dirty_tx) {
/* dirty_tx is met in the cycle of cur_tx, buffer full */
sis_priv->tx_full = 1;
netif_stop_queue(net_dev);
} else if (count_dirty_tx < NUM_TX_DESC) {
/* Typical path, tell upper layer that more transmission is possible */
netif_start_queue(net_dev);
} else {
/* buffer full, tell upper layer no more transmission */
sis_priv->tx_full = 1;
netif_stop_queue(net_dev);
}
spin_unlock_irqrestore(&sis_priv->lock, flags);
if (netif_msg_tx_queued(sis_priv))
printk(KERN_DEBUG "%s: Queued Tx packet at %p size %d "
"to slot %d.\n",
net_dev->name, skb->data, (int)skb->len, entry);
return NETDEV_TX_OK;
}
/**
* sis900_interrupt - sis900 interrupt handler
* @irq: the irq number
* @dev_instance: the client data object
*
* The interrupt handler does all of the Rx thread work,
* and cleans up after the Tx thread
*/
static irqreturn_t sis900_interrupt(int irq, void *dev_instance)
{
struct net_device *net_dev = dev_instance;
struct sis900_private *sis_priv = netdev_priv(net_dev);
int boguscnt = max_interrupt_work;
void __iomem *ioaddr = sis_priv->ioaddr;
u32 status;
unsigned int handled = 0;
spin_lock (&sis_priv->lock);
do {
status = sr32(isr);
if ((status & (HIBERR|TxURN|TxERR|TxDESC|RxORN|RxERR|RxOK)) == 0)
/* nothing interesting happened */
break;
handled = 1;
/* why dow't we break after Tx/Rx case ?? keyword: full-duplex */
if (status & (RxORN | RxERR | RxOK))
/* Rx interrupt */
sis900_rx(net_dev);
if (status & (TxURN | TxERR | TxDESC))
/* Tx interrupt */
sis900_finish_xmit(net_dev);
/* something strange happened !!! */
if (status & HIBERR) {
if(netif_msg_intr(sis_priv))
printk(KERN_INFO "%s: Abnormal interrupt, "
"status %#8.8x.\n", net_dev->name, status);
break;
}
if (--boguscnt < 0) {
if(netif_msg_intr(sis_priv))
printk(KERN_INFO "%s: Too much work at interrupt, "
"interrupt status = %#8.8x.\n",
net_dev->name, status);
break;
}
} while (1);
if(netif_msg_intr(sis_priv))
printk(KERN_DEBUG "%s: exiting interrupt, "
"interrupt status = %#8.8x\n",
net_dev->name, sr32(isr));
spin_unlock (&sis_priv->lock);
return IRQ_RETVAL(handled);
}
/**
* sis900_rx - sis900 receive routine
* @net_dev: the net device which receives data
*
* Process receive interrupt events,
* put buffer to higher layer and refill buffer pool
* Note: This function is called by interrupt handler,
* don't do "too much" work here
*/
static int sis900_rx(struct net_device *net_dev)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
void __iomem *ioaddr = sis_priv->ioaddr;
unsigned int entry = sis_priv->cur_rx % NUM_RX_DESC;
u32 rx_status = sis_priv->rx_ring[entry].cmdsts;
int rx_work_limit;
if (netif_msg_rx_status(sis_priv))
printk(KERN_DEBUG "sis900_rx, cur_rx:%4.4d, dirty_rx:%4.4d "
"status:0x%8.8x\n",
sis_priv->cur_rx, sis_priv->dirty_rx, rx_status);
rx_work_limit = sis_priv->dirty_rx + NUM_RX_DESC - sis_priv->cur_rx;
while (rx_status & OWN) {
unsigned int rx_size;
unsigned int data_size;
if (--rx_work_limit < 0)
break;
data_size = rx_status & DSIZE;
rx_size = data_size - CRC_SIZE;
#if IS_ENABLED(CONFIG_VLAN_8021Q)
/* ``TOOLONG'' flag means jumbo packet received. */
if ((rx_status & TOOLONG) && data_size <= MAX_FRAME_SIZE)
rx_status &= (~ ((unsigned int)TOOLONG));
#endif
if (rx_status & (ABORT|OVERRUN|TOOLONG|RUNT|RXISERR|CRCERR|FAERR)) {
/* corrupted packet received */
if (netif_msg_rx_err(sis_priv))
printk(KERN_DEBUG "%s: Corrupted packet "
"received, buffer status = 0x%8.8x/%d.\n",
net_dev->name, rx_status, data_size);
net_dev->stats.rx_errors++;
if (rx_status & OVERRUN)
net_dev->stats.rx_over_errors++;
if (rx_status & (TOOLONG|RUNT))
net_dev->stats.rx_length_errors++;
if (rx_status & (RXISERR | FAERR))
net_dev->stats.rx_frame_errors++;
if (rx_status & CRCERR)
net_dev->stats.rx_crc_errors++;
/* reset buffer descriptor state */
sis_priv->rx_ring[entry].cmdsts = RX_BUF_SIZE;
} else {
struct sk_buff * skb;
struct sk_buff * rx_skb;
dma_unmap_single(&sis_priv->pci_dev->dev,
sis_priv->rx_ring[entry].bufptr,
RX_BUF_SIZE, DMA_FROM_DEVICE);
/* refill the Rx buffer, what if there is not enough
* memory for new socket buffer ?? */
if ((skb = netdev_alloc_skb(net_dev, RX_BUF_SIZE)) == NULL) {
/*
* Not enough memory to refill the buffer
* so we need to recycle the old one so
* as to avoid creating a memory hole
* in the rx ring
*/
skb = sis_priv->rx_skbuff[entry];
net_dev->stats.rx_dropped++;
goto refill_rx_ring;
}
/* This situation should never happen, but due to
some unknown bugs, it is possible that
we are working on NULL sk_buff :-( */
if (sis_priv->rx_skbuff[entry] == NULL) {
if (netif_msg_rx_err(sis_priv))
printk(KERN_WARNING "%s: NULL pointer "
"encountered in Rx ring\n"
"cur_rx:%4.4d, dirty_rx:%4.4d\n",
net_dev->name, sis_priv->cur_rx,
sis_priv->dirty_rx);
dev_kfree_skb(skb);
break;
}
/* give the socket buffer to upper layers */
rx_skb = sis_priv->rx_skbuff[entry];
skb_put(rx_skb, rx_size);
rx_skb->protocol = eth_type_trans(rx_skb, net_dev);
netif_rx(rx_skb);
/* some network statistics */
if ((rx_status & BCAST) == MCAST)
net_dev->stats.multicast++;
net_dev->stats.rx_bytes += rx_size;
net_dev->stats.rx_packets++;
sis_priv->dirty_rx++;
refill_rx_ring:
sis_priv->rx_skbuff[entry] = skb;
sis_priv->rx_ring[entry].cmdsts = RX_BUF_SIZE;
sis_priv->rx_ring[entry].bufptr =
dma_map_single(&sis_priv->pci_dev->dev,
skb->data, RX_BUF_SIZE,
DMA_FROM_DEVICE);
if (unlikely(dma_mapping_error(&sis_priv->pci_dev->dev,
sis_priv->rx_ring[entry].bufptr))) {
dev_kfree_skb_irq(skb);
sis_priv->rx_skbuff[entry] = NULL;
break;
}
}
sis_priv->cur_rx++;
entry = sis_priv->cur_rx % NUM_RX_DESC;
rx_status = sis_priv->rx_ring[entry].cmdsts;
} // while
/* refill the Rx buffer, what if the rate of refilling is slower
* than consuming ?? */
for (; sis_priv->cur_rx != sis_priv->dirty_rx; sis_priv->dirty_rx++) {
struct sk_buff *skb;
entry = sis_priv->dirty_rx % NUM_RX_DESC;
if (sis_priv->rx_skbuff[entry] == NULL) {
skb = netdev_alloc_skb(net_dev, RX_BUF_SIZE);
if (skb == NULL) {
/* not enough memory for skbuff, this makes a
* "hole" on the buffer ring, it is not clear
* how the hardware will react to this kind
* of degenerated buffer */
net_dev->stats.rx_dropped++;
break;
}
sis_priv->rx_skbuff[entry] = skb;
sis_priv->rx_ring[entry].cmdsts = RX_BUF_SIZE;
sis_priv->rx_ring[entry].bufptr =
dma_map_single(&sis_priv->pci_dev->dev,
skb->data, RX_BUF_SIZE,
DMA_FROM_DEVICE);
if (unlikely(dma_mapping_error(&sis_priv->pci_dev->dev,
sis_priv->rx_ring[entry].bufptr))) {
dev_kfree_skb_irq(skb);
sis_priv->rx_skbuff[entry] = NULL;
break;
}
}
}
/* re-enable the potentially idle receive state matchine */
sw32(cr , RxENA | sr32(cr));
return 0;
}
/**
* sis900_finish_xmit - finish up transmission of packets
* @net_dev: the net device to be transmitted on
*
* Check for error condition and free socket buffer etc
* schedule for more transmission as needed
* Note: This function is called by interrupt handler,
* don't do "too much" work here
*/
static void sis900_finish_xmit (struct net_device *net_dev)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
for (; sis_priv->dirty_tx != sis_priv->cur_tx; sis_priv->dirty_tx++) {
struct sk_buff *skb;
unsigned int entry;
u32 tx_status;
entry = sis_priv->dirty_tx % NUM_TX_DESC;
tx_status = sis_priv->tx_ring[entry].cmdsts;
if (tx_status & OWN) {
/* The packet is not transmitted yet (owned by hardware) !
* Note: this is an almost impossible condition
* on TxDESC interrupt ('descriptor interrupt') */
break;
}
if (tx_status & (ABORT | UNDERRUN | OWCOLL)) {
/* packet unsuccessfully transmitted */
if (netif_msg_tx_err(sis_priv))
printk(KERN_DEBUG "%s: Transmit "
"error, Tx status %8.8x.\n",
net_dev->name, tx_status);
net_dev->stats.tx_errors++;
if (tx_status & UNDERRUN)
net_dev->stats.tx_fifo_errors++;
if (tx_status & ABORT)
net_dev->stats.tx_aborted_errors++;
if (tx_status & NOCARRIER)
net_dev->stats.tx_carrier_errors++;
if (tx_status & OWCOLL)
net_dev->stats.tx_window_errors++;
} else {
/* packet successfully transmitted */
net_dev->stats.collisions += (tx_status & COLCNT) >> 16;
net_dev->stats.tx_bytes += tx_status & DSIZE;
net_dev->stats.tx_packets++;
}
/* Free the original skb. */
skb = sis_priv->tx_skbuff[entry];
dma_unmap_single(&sis_priv->pci_dev->dev,
sis_priv->tx_ring[entry].bufptr, skb->len,
DMA_TO_DEVICE);
dev_consume_skb_irq(skb);
sis_priv->tx_skbuff[entry] = NULL;
sis_priv->tx_ring[entry].bufptr = 0;
sis_priv->tx_ring[entry].cmdsts = 0;
}
if (sis_priv->tx_full && netif_queue_stopped(net_dev) &&
sis_priv->cur_tx - sis_priv->dirty_tx < NUM_TX_DESC - 4) {
/* The ring is no longer full, clear tx_full and schedule
* more transmission by netif_wake_queue(net_dev) */
sis_priv->tx_full = 0;
netif_wake_queue (net_dev);
}
}
/**
* sis900_close - close sis900 device
* @net_dev: the net device to be closed
*
* Disable interrupts, stop the Tx and Rx Status Machine
* free Tx and RX socket buffer
*/
static int sis900_close(struct net_device *net_dev)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
struct pci_dev *pdev = sis_priv->pci_dev;
void __iomem *ioaddr = sis_priv->ioaddr;
struct sk_buff *skb;
int i;
netif_stop_queue(net_dev);
/* Disable interrupts by clearing the interrupt mask. */
sw32(imr, 0x0000);
sw32(ier, 0x0000);
/* Stop the chip's Tx and Rx Status Machine */
sw32(cr, RxDIS | TxDIS | sr32(cr));
del_timer(&sis_priv->timer);
free_irq(pdev->irq, net_dev);
/* Free Tx and RX skbuff */
for (i = 0; i < NUM_RX_DESC; i++) {
skb = sis_priv->rx_skbuff[i];
if (skb) {
dma_unmap_single(&pdev->dev,
sis_priv->rx_ring[i].bufptr,
RX_BUF_SIZE, DMA_FROM_DEVICE);
dev_kfree_skb(skb);
sis_priv->rx_skbuff[i] = NULL;
}
}
for (i = 0; i < NUM_TX_DESC; i++) {
skb = sis_priv->tx_skbuff[i];
if (skb) {
dma_unmap_single(&pdev->dev,
sis_priv->tx_ring[i].bufptr,
skb->len, DMA_TO_DEVICE);
dev_kfree_skb(skb);
sis_priv->tx_skbuff[i] = NULL;
}
}
/* Green! Put the chip in low-power mode. */
return 0;
}
/**
* sis900_get_drvinfo - Return information about driver
* @net_dev: the net device to probe
* @info: container for info returned
*
* Process ethtool command such as "ehtool -i" to show information
*/
static void sis900_get_drvinfo(struct net_device *net_dev,
struct ethtool_drvinfo *info)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
strscpy(info->driver, SIS900_MODULE_NAME, sizeof(info->driver));
strscpy(info->version, SIS900_DRV_VERSION, sizeof(info->version));
strscpy(info->bus_info, pci_name(sis_priv->pci_dev),
sizeof(info->bus_info));
}
static u32 sis900_get_msglevel(struct net_device *net_dev)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
return sis_priv->msg_enable;
}
static void sis900_set_msglevel(struct net_device *net_dev, u32 value)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
sis_priv->msg_enable = value;
}
static u32 sis900_get_link(struct net_device *net_dev)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
return mii_link_ok(&sis_priv->mii_info);
}
static int sis900_get_link_ksettings(struct net_device *net_dev,
struct ethtool_link_ksettings *cmd)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
spin_lock_irq(&sis_priv->lock);
mii_ethtool_get_link_ksettings(&sis_priv->mii_info, cmd);
spin_unlock_irq(&sis_priv->lock);
return 0;
}
static int sis900_set_link_ksettings(struct net_device *net_dev,
const struct ethtool_link_ksettings *cmd)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
int rt;
spin_lock_irq(&sis_priv->lock);
rt = mii_ethtool_set_link_ksettings(&sis_priv->mii_info, cmd);
spin_unlock_irq(&sis_priv->lock);
return rt;
}
static int sis900_nway_reset(struct net_device *net_dev)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
return mii_nway_restart(&sis_priv->mii_info);
}
/**
* sis900_set_wol - Set up Wake on Lan registers
* @net_dev: the net device to probe
* @wol: container for info passed to the driver
*
* Process ethtool command "wol" to setup wake on lan features.
* SiS900 supports sending WoL events if a correct packet is received,
* but there is no simple way to filter them to only a subset (broadcast,
* multicast, unicast or arp).
*/
static int sis900_set_wol(struct net_device *net_dev, struct ethtool_wolinfo *wol)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
void __iomem *ioaddr = sis_priv->ioaddr;
u32 cfgpmcsr = 0, pmctrl_bits = 0;
if (wol->wolopts == 0) {
pci_read_config_dword(sis_priv->pci_dev, CFGPMCSR, &cfgpmcsr);
cfgpmcsr &= ~PME_EN;
pci_write_config_dword(sis_priv->pci_dev, CFGPMCSR, cfgpmcsr);
sw32(pmctrl, pmctrl_bits);
if (netif_msg_wol(sis_priv))
printk(KERN_DEBUG "%s: Wake on LAN disabled\n", net_dev->name);
return 0;
}
if (wol->wolopts & (WAKE_MAGICSECURE | WAKE_UCAST | WAKE_MCAST
| WAKE_BCAST | WAKE_ARP))
return -EINVAL;
if (wol->wolopts & WAKE_MAGIC)
pmctrl_bits |= MAGICPKT;
if (wol->wolopts & WAKE_PHY)
pmctrl_bits |= LINKON;
sw32(pmctrl, pmctrl_bits);
pci_read_config_dword(sis_priv->pci_dev, CFGPMCSR, &cfgpmcsr);
cfgpmcsr |= PME_EN;
pci_write_config_dword(sis_priv->pci_dev, CFGPMCSR, cfgpmcsr);
if (netif_msg_wol(sis_priv))
printk(KERN_DEBUG "%s: Wake on LAN enabled\n", net_dev->name);
return 0;
}
static void sis900_get_wol(struct net_device *net_dev, struct ethtool_wolinfo *wol)
{
struct sis900_private *sp = netdev_priv(net_dev);
void __iomem *ioaddr = sp->ioaddr;
u32 pmctrl_bits;
pmctrl_bits = sr32(pmctrl);
if (pmctrl_bits & MAGICPKT)
wol->wolopts |= WAKE_MAGIC;
if (pmctrl_bits & LINKON)
wol->wolopts |= WAKE_PHY;
wol->supported = (WAKE_PHY | WAKE_MAGIC);
}
static int sis900_get_eeprom_len(struct net_device *dev)
{
struct sis900_private *sis_priv = netdev_priv(dev);
return sis_priv->eeprom_size;
}
static int sis900_read_eeprom(struct net_device *net_dev, u8 *buf)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
void __iomem *ioaddr = sis_priv->ioaddr;
int wait, ret = -EAGAIN;
u16 signature;
u16 *ebuf = (u16 *)buf;
int i;
if (sis_priv->chipset_rev == SIS96x_900_REV) {
sw32(mear, EEREQ);
for (wait = 0; wait < 2000; wait++) {
if (sr32(mear) & EEGNT) {
/* read 16 bits, and index by 16 bits */
for (i = 0; i < sis_priv->eeprom_size / 2; i++)
ebuf[i] = (u16)read_eeprom(ioaddr, i);
ret = 0;
break;
}
udelay(1);
}
sw32(mear, EEDONE);
} else {
signature = (u16)read_eeprom(ioaddr, EEPROMSignature);
if (signature != 0xffff && signature != 0x0000) {
/* read 16 bits, and index by 16 bits */
for (i = 0; i < sis_priv->eeprom_size / 2; i++)
ebuf[i] = (u16)read_eeprom(ioaddr, i);
ret = 0;
}
}
return ret;
}
#define SIS900_EEPROM_MAGIC 0xBABE
static int sis900_get_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom, u8 *data)
{
struct sis900_private *sis_priv = netdev_priv(dev);
u8 *eebuf;
int res;
eebuf = kmalloc(sis_priv->eeprom_size, GFP_KERNEL);
if (!eebuf)
return -ENOMEM;
eeprom->magic = SIS900_EEPROM_MAGIC;
spin_lock_irq(&sis_priv->lock);
res = sis900_read_eeprom(dev, eebuf);
spin_unlock_irq(&sis_priv->lock);
if (!res)
memcpy(data, eebuf + eeprom->offset, eeprom->len);
kfree(eebuf);
return res;
}
static const struct ethtool_ops sis900_ethtool_ops = {
.get_drvinfo = sis900_get_drvinfo,
.get_msglevel = sis900_get_msglevel,
.set_msglevel = sis900_set_msglevel,
.get_link = sis900_get_link,
.nway_reset = sis900_nway_reset,
.get_wol = sis900_get_wol,
.set_wol = sis900_set_wol,
.get_link_ksettings = sis900_get_link_ksettings,
.set_link_ksettings = sis900_set_link_ksettings,
.get_eeprom_len = sis900_get_eeprom_len,
.get_eeprom = sis900_get_eeprom,
};
/**
* mii_ioctl - process MII i/o control command
* @net_dev: the net device to command for
* @rq: parameter for command
* @cmd: the i/o command
*
* Process MII command like read/write MII register
*/
static int mii_ioctl(struct net_device *net_dev, struct ifreq *rq, int cmd)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
struct mii_ioctl_data *data = if_mii(rq);
switch(cmd) {
case SIOCGMIIPHY: /* Get address of MII PHY in use. */
data->phy_id = sis_priv->mii->phy_addr;
fallthrough;
case SIOCGMIIREG: /* Read MII PHY register. */
data->val_out = mdio_read(net_dev, data->phy_id & 0x1f, data->reg_num & 0x1f);
return 0;
case SIOCSMIIREG: /* Write MII PHY register. */
mdio_write(net_dev, data->phy_id & 0x1f, data->reg_num & 0x1f, data->val_in);
return 0;
default:
return -EOPNOTSUPP;
}
}
/**
* sis900_set_config - Set media type by net_device.set_config
* @dev: the net device for media type change
* @map: ifmap passed by ifconfig
*
* Set media type to 10baseT, 100baseT or 0(for auto) by ifconfig
* we support only port changes. All other runtime configuration
* changes will be ignored
*/
static int sis900_set_config(struct net_device *dev, struct ifmap *map)
{
struct sis900_private *sis_priv = netdev_priv(dev);
struct mii_phy *mii_phy = sis_priv->mii;
u16 status;
if ((map->port != (u_char)(-1)) && (map->port != dev->if_port)) {
/* we switch on the ifmap->port field. I couldn't find anything
* like a definition or standard for the values of that field.
* I think the meaning of those values is device specific. But
* since I would like to change the media type via the ifconfig
* command I use the definition from linux/netdevice.h
* (which seems to be different from the ifport(pcmcia) definition) */
switch(map->port){
case IF_PORT_UNKNOWN: /* use auto here */
dev->if_port = map->port;
/* we are going to change the media type, so the Link
* will be temporary down and we need to reflect that
* here. When the Link comes up again, it will be
* sensed by the sis_timer procedure, which also does
* all the rest for us */
netif_carrier_off(dev);
/* read current state */
status = mdio_read(dev, mii_phy->phy_addr, MII_CONTROL);
/* enable auto negotiation and reset the negotioation
* (I don't really know what the auto negatiotiation
* reset really means, but it sounds for me right to
* do one here) */
mdio_write(dev, mii_phy->phy_addr,
MII_CONTROL, status | MII_CNTL_AUTO | MII_CNTL_RST_AUTO);
break;
case IF_PORT_10BASET: /* 10BaseT */
dev->if_port = map->port;
/* we are going to change the media type, so the Link
* will be temporary down and we need to reflect that
* here. When the Link comes up again, it will be
* sensed by the sis_timer procedure, which also does
* all the rest for us */
netif_carrier_off(dev);
/* set Speed to 10Mbps */
/* read current state */
status = mdio_read(dev, mii_phy->phy_addr, MII_CONTROL);
/* disable auto negotiation and force 10MBit mode*/
mdio_write(dev, mii_phy->phy_addr,
MII_CONTROL, status & ~(MII_CNTL_SPEED |
MII_CNTL_AUTO));
break;
case IF_PORT_100BASET: /* 100BaseT */
case IF_PORT_100BASETX: /* 100BaseTx */
dev->if_port = map->port;
/* we are going to change the media type, so the Link
* will be temporary down and we need to reflect that
* here. When the Link comes up again, it will be
* sensed by the sis_timer procedure, which also does
* all the rest for us */
netif_carrier_off(dev);
/* set Speed to 100Mbps */
/* disable auto negotiation and enable 100MBit Mode */
status = mdio_read(dev, mii_phy->phy_addr, MII_CONTROL);
mdio_write(dev, mii_phy->phy_addr,
MII_CONTROL, (status & ~MII_CNTL_SPEED) |
MII_CNTL_SPEED);
break;
case IF_PORT_10BASE2: /* 10Base2 */
case IF_PORT_AUI: /* AUI */
case IF_PORT_100BASEFX: /* 100BaseFx */
/* These Modes are not supported (are they?)*/
return -EOPNOTSUPP;
default:
return -EINVAL;
}
}
return 0;
}
/**
* sis900_mcast_bitnr - compute hashtable index
* @addr: multicast address
* @revision: revision id of chip
*
* SiS 900 uses the most sigificant 7 bits to index a 128 bits multicast
* hash table, which makes this function a little bit different from other drivers
* SiS 900 B0 & 635 M/B uses the most significat 8 bits to index 256 bits
* multicast hash table.
*/
static inline u16 sis900_mcast_bitnr(u8 *addr, u8 revision)
{
u32 crc = ether_crc(6, addr);
/* leave 8 or 7 most siginifant bits */
if ((revision >= SIS635A_900_REV) || (revision == SIS900B_900_REV))
return (int)(crc >> 24);
else
return (int)(crc >> 25);
}
/**
* set_rx_mode - Set SiS900 receive mode
* @net_dev: the net device to be set
*
* Set SiS900 receive mode for promiscuous, multicast, or broadcast mode.
* And set the appropriate multicast filter.
* Multicast hash table changes from 128 to 256 bits for 635M/B & 900B0.
*/
static void set_rx_mode(struct net_device *net_dev)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
void __iomem *ioaddr = sis_priv->ioaddr;
u16 mc_filter[16] = {0}; /* 256/128 bits multicast hash table */
int i, table_entries;
u32 rx_mode;
/* 635 Hash Table entries = 256(2^16) */
if((sis_priv->chipset_rev >= SIS635A_900_REV) ||
(sis_priv->chipset_rev == SIS900B_900_REV))
table_entries = 16;
else
table_entries = 8;
if (net_dev->flags & IFF_PROMISC) {
/* Accept any kinds of packets */
rx_mode = RFPromiscuous;
for (i = 0; i < table_entries; i++)
mc_filter[i] = 0xffff;
} else if ((netdev_mc_count(net_dev) > multicast_filter_limit) ||
(net_dev->flags & IFF_ALLMULTI)) {
/* too many multicast addresses or accept all multicast packet */
rx_mode = RFAAB | RFAAM;
for (i = 0; i < table_entries; i++)
mc_filter[i] = 0xffff;
} else {
/* Accept Broadcast packet, destination address matchs our
* MAC address, use Receive Filter to reject unwanted MCAST
* packets */
struct netdev_hw_addr *ha;
rx_mode = RFAAB;
netdev_for_each_mc_addr(ha, net_dev) {
unsigned int bit_nr;
bit_nr = sis900_mcast_bitnr(ha->addr,
sis_priv->chipset_rev);
mc_filter[bit_nr >> 4] |= (1 << (bit_nr & 0xf));
}
}
/* update Multicast Hash Table in Receive Filter */
for (i = 0; i < table_entries; i++) {
/* why plus 0x04 ??, That makes the correct value for hash table. */
sw32(rfcr, (u32)(0x00000004 + i) << RFADDR_shift);
sw32(rfdr, mc_filter[i]);
}
sw32(rfcr, RFEN | rx_mode);
/* sis900 is capable of looping back packets at MAC level for
* debugging purpose */
if (net_dev->flags & IFF_LOOPBACK) {
u32 cr_saved;
/* We must disable Tx/Rx before setting loopback mode */
cr_saved = sr32(cr);
sw32(cr, cr_saved | TxDIS | RxDIS);
/* enable loopback */
sw32(txcfg, sr32(txcfg) | TxMLB);
sw32(rxcfg, sr32(rxcfg) | RxATX);
/* restore cr */
sw32(cr, cr_saved);
}
}
/**
* sis900_reset - Reset sis900 MAC
* @net_dev: the net device to reset
*
* reset sis900 MAC and wait until finished
* reset through command register
* change backoff algorithm for 900B0 & 635 M/B
*/
static void sis900_reset(struct net_device *net_dev)
{
struct sis900_private *sis_priv = netdev_priv(net_dev);
void __iomem *ioaddr = sis_priv->ioaddr;
u32 status = TxRCMP | RxRCMP;
int i;
sw32(ier, 0);
sw32(imr, 0);
sw32(rfcr, 0);
sw32(cr, RxRESET | TxRESET | RESET | sr32(cr));
/* Check that the chip has finished the reset. */
for (i = 0; status && (i < 1000); i++)
status ^= sr32(isr) & status;
if (sis_priv->chipset_rev >= SIS635A_900_REV ||
sis_priv->chipset_rev == SIS900B_900_REV)
sw32(cfg, PESEL | RND_CNT);
else
sw32(cfg, PESEL);
}
/**
* sis900_remove - Remove sis900 device
* @pci_dev: the pci device to be removed
*
* remove and release SiS900 net device
*/
static void sis900_remove(struct pci_dev *pci_dev)
{
struct net_device *net_dev = pci_get_drvdata(pci_dev);
struct sis900_private *sis_priv = netdev_priv(net_dev);
unregister_netdev(net_dev);
while (sis_priv->first_mii) {
struct mii_phy *phy = sis_priv->first_mii;
sis_priv->first_mii = phy->next;
kfree(phy);
}
dma_free_coherent(&pci_dev->dev, RX_TOTAL_SIZE, sis_priv->rx_ring,
sis_priv->rx_ring_dma);
dma_free_coherent(&pci_dev->dev, TX_TOTAL_SIZE, sis_priv->tx_ring,
sis_priv->tx_ring_dma);
pci_iounmap(pci_dev, sis_priv->ioaddr);
free_netdev(net_dev);
}
static int __maybe_unused sis900_suspend(struct device *dev)
{
struct net_device *net_dev = dev_get_drvdata(dev);
struct sis900_private *sis_priv = netdev_priv(net_dev);
void __iomem *ioaddr = sis_priv->ioaddr;
if(!netif_running(net_dev))
return 0;
netif_stop_queue(net_dev);
netif_device_detach(net_dev);
/* Stop the chip's Tx and Rx Status Machine */
sw32(cr, RxDIS | TxDIS | sr32(cr));
return 0;
}
static int __maybe_unused sis900_resume(struct device *dev)
{
struct net_device *net_dev = dev_get_drvdata(dev);
struct sis900_private *sis_priv = netdev_priv(net_dev);
void __iomem *ioaddr = sis_priv->ioaddr;
if(!netif_running(net_dev))
return 0;
sis900_init_rxfilter(net_dev);
sis900_init_tx_ring(net_dev);
sis900_init_rx_ring(net_dev);
set_rx_mode(net_dev);
netif_device_attach(net_dev);
netif_start_queue(net_dev);
/* Workaround for EDB */
sis900_set_mode(sis_priv, HW_SPEED_10_MBPS, FDX_CAPABLE_HALF_SELECTED);
/* Enable all known interrupts by setting the interrupt mask. */
sw32(imr, RxSOVR | RxORN | RxERR | RxOK | TxURN | TxERR | TxDESC);
sw32(cr, RxENA | sr32(cr));
sw32(ier, IE);
sis900_check_mode(net_dev, sis_priv->mii);
return 0;
}
static SIMPLE_DEV_PM_OPS(sis900_pm_ops, sis900_suspend, sis900_resume);
static struct pci_driver sis900_pci_driver = {
.name = SIS900_MODULE_NAME,
.id_table = sis900_pci_tbl,
.probe = sis900_probe,
.remove = sis900_remove,
.driver.pm = &sis900_pm_ops,
};
static int __init sis900_init_module(void)
{
/* when a module, this is printed whether or not devices are found in probe */
#ifdef MODULE
printk(version);
#endif
return pci_register_driver(&sis900_pci_driver);
}
static void __exit sis900_cleanup_module(void)
{
pci_unregister_driver(&sis900_pci_driver);
}
module_init(sis900_init_module);
module_exit(sis900_cleanup_module);
|
linux-master
|
drivers/net/ethernet/sis/sis900.c
|
/*
sis190.c: Silicon Integrated Systems SiS190 ethernet driver
Copyright (c) 2003 K.M. Liu <[email protected]>
Copyright (c) 2003, 2004 Jeff Garzik <[email protected]>
Copyright (c) 2003, 2004, 2005 Francois Romieu <[email protected]>
Based on r8169.c, tg3.c, 8139cp.c, skge.c, epic100.c and SiS 190/191
genuine driver.
This software may be used and distributed according to the terms of
the GNU General Public License (GPL), incorporated herein by reference.
Drivers based on or derived from this code fall under the GPL and must
retain the authorship, copyright and license notice. This file is not
a complete program and may only be used when the entire operating
system is licensed under the GPL.
See the file COPYING in this distribution for more information.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/netdevice.h>
#include <linux/rtnetlink.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/pci.h>
#include <linux/mii.h>
#include <linux/delay.h>
#include <linux/crc32.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <asm/irq.h>
#define PHY_MAX_ADDR 32
#define PHY_ID_ANY 0x1f
#define MII_REG_ANY 0x1f
#define DRV_VERSION "1.4"
#define DRV_NAME "sis190"
#define SIS190_DRIVER_NAME DRV_NAME " Gigabit Ethernet driver " DRV_VERSION
#define sis190_rx_skb netif_rx
#define sis190_rx_quota(count, quota) count
#define NUM_TX_DESC 64 /* [8..1024] */
#define NUM_RX_DESC 64 /* [8..8192] */
#define TX_RING_BYTES (NUM_TX_DESC * sizeof(struct TxDesc))
#define RX_RING_BYTES (NUM_RX_DESC * sizeof(struct RxDesc))
#define RX_BUF_SIZE 1536
#define RX_BUF_MASK 0xfff8
#define SIS190_REGS_SIZE 0x80
#define SIS190_TX_TIMEOUT (6*HZ)
#define SIS190_PHY_TIMEOUT (10*HZ)
#define SIS190_MSG_DEFAULT (NETIF_MSG_DRV | NETIF_MSG_PROBE | \
NETIF_MSG_LINK | NETIF_MSG_IFUP | \
NETIF_MSG_IFDOWN)
/* Enhanced PHY access register bit definitions */
#define EhnMIIread 0x0000
#define EhnMIIwrite 0x0020
#define EhnMIIdataShift 16
#define EhnMIIpmdShift 6 /* 7016 only */
#define EhnMIIregShift 11
#define EhnMIIreq 0x0010
#define EhnMIInotDone 0x0010
/* Write/read MMIO register */
#define SIS_W8(reg, val) writeb ((val), ioaddr + (reg))
#define SIS_W16(reg, val) writew ((val), ioaddr + (reg))
#define SIS_W32(reg, val) writel ((val), ioaddr + (reg))
#define SIS_R8(reg) readb (ioaddr + (reg))
#define SIS_R16(reg) readw (ioaddr + (reg))
#define SIS_R32(reg) readl (ioaddr + (reg))
#define SIS_PCI_COMMIT() SIS_R32(IntrControl)
enum sis190_registers {
TxControl = 0x00,
TxDescStartAddr = 0x04,
rsv0 = 0x08, // reserved
TxSts = 0x0c, // unused (Control/Status)
RxControl = 0x10,
RxDescStartAddr = 0x14,
rsv1 = 0x18, // reserved
RxSts = 0x1c, // unused
IntrStatus = 0x20,
IntrMask = 0x24,
IntrControl = 0x28,
IntrTimer = 0x2c, // unused (Interrupt Timer)
PMControl = 0x30, // unused (Power Mgmt Control/Status)
rsv2 = 0x34, // reserved
ROMControl = 0x38,
ROMInterface = 0x3c,
StationControl = 0x40,
GMIIControl = 0x44,
GIoCR = 0x48, // unused (GMAC IO Compensation)
GIoCtrl = 0x4c, // unused (GMAC IO Control)
TxMacControl = 0x50,
TxLimit = 0x54, // unused (Tx MAC Timer/TryLimit)
RGDelay = 0x58, // unused (RGMII Tx Internal Delay)
rsv3 = 0x5c, // reserved
RxMacControl = 0x60,
RxMacAddr = 0x62,
RxHashTable = 0x68,
// Undocumented = 0x6c,
RxWolCtrl = 0x70,
RxWolData = 0x74, // unused (Rx WOL Data Access)
RxMPSControl = 0x78, // unused (Rx MPS Control)
rsv4 = 0x7c, // reserved
};
enum sis190_register_content {
/* IntrStatus */
SoftInt = 0x40000000, // unused
Timeup = 0x20000000, // unused
PauseFrame = 0x00080000, // unused
MagicPacket = 0x00040000, // unused
WakeupFrame = 0x00020000, // unused
LinkChange = 0x00010000,
RxQEmpty = 0x00000080,
RxQInt = 0x00000040,
TxQ1Empty = 0x00000020, // unused
TxQ1Int = 0x00000010,
TxQ0Empty = 0x00000008, // unused
TxQ0Int = 0x00000004,
RxHalt = 0x00000002,
TxHalt = 0x00000001,
/* {Rx/Tx}CmdBits */
CmdReset = 0x10,
CmdRxEnb = 0x08, // unused
CmdTxEnb = 0x01,
RxBufEmpty = 0x01, // unused
/* Cfg9346Bits */
Cfg9346_Lock = 0x00, // unused
Cfg9346_Unlock = 0xc0, // unused
/* RxMacControl */
AcceptErr = 0x20, // unused
AcceptRunt = 0x10, // unused
AcceptBroadcast = 0x0800,
AcceptMulticast = 0x0400,
AcceptMyPhys = 0x0200,
AcceptAllPhys = 0x0100,
/* RxConfigBits */
RxCfgFIFOShift = 13,
RxCfgDMAShift = 8, // 0x1a in RxControl ?
/* TxConfigBits */
TxInterFrameGapShift = 24,
TxDMAShift = 8, /* DMA burst value (0-7) is shift this many bits */
LinkStatus = 0x02, // unused
FullDup = 0x01, // unused
/* TBICSRBit */
TBILinkOK = 0x02000000, // unused
};
struct TxDesc {
__le32 PSize;
__le32 status;
__le32 addr;
__le32 size;
};
struct RxDesc {
__le32 PSize;
__le32 status;
__le32 addr;
__le32 size;
};
enum _DescStatusBit {
/* _Desc.status */
OWNbit = 0x80000000, // RXOWN/TXOWN
INTbit = 0x40000000, // RXINT/TXINT
CRCbit = 0x00020000, // CRCOFF/CRCEN
PADbit = 0x00010000, // PREADD/PADEN
/* _Desc.size */
RingEnd = 0x80000000,
/* TxDesc.status */
LSEN = 0x08000000, // TSO ? -- FR
IPCS = 0x04000000,
TCPCS = 0x02000000,
UDPCS = 0x01000000,
BSTEN = 0x00800000,
EXTEN = 0x00400000,
DEFEN = 0x00200000,
BKFEN = 0x00100000,
CRSEN = 0x00080000,
COLEN = 0x00040000,
THOL3 = 0x30000000,
THOL2 = 0x20000000,
THOL1 = 0x10000000,
THOL0 = 0x00000000,
WND = 0x00080000,
TABRT = 0x00040000,
FIFO = 0x00020000,
LINK = 0x00010000,
ColCountMask = 0x0000ffff,
/* RxDesc.status */
IPON = 0x20000000,
TCPON = 0x10000000,
UDPON = 0x08000000,
Wakup = 0x00400000,
Magic = 0x00200000,
Pause = 0x00100000,
DEFbit = 0x00200000,
BCAST = 0x000c0000,
MCAST = 0x00080000,
UCAST = 0x00040000,
/* RxDesc.PSize */
TAGON = 0x80000000,
RxDescCountMask = 0x7f000000, // multi-desc pkt when > 1 ? -- FR
ABORT = 0x00800000,
SHORT = 0x00400000,
LIMIT = 0x00200000,
MIIER = 0x00100000,
OVRUN = 0x00080000,
NIBON = 0x00040000,
COLON = 0x00020000,
CRCOK = 0x00010000,
RxSizeMask = 0x0000ffff
/*
* The asic could apparently do vlan, TSO, jumbo (sis191 only) and
* provide two (unused with Linux) Tx queues. No publicly
* available documentation alas.
*/
};
enum sis190_eeprom_access_register_bits {
EECS = 0x00000001, // unused
EECLK = 0x00000002, // unused
EEDO = 0x00000008, // unused
EEDI = 0x00000004, // unused
EEREQ = 0x00000080,
EEROP = 0x00000200,
EEWOP = 0x00000100 // unused
};
/* EEPROM Addresses */
enum sis190_eeprom_address {
EEPROMSignature = 0x00,
EEPROMCLK = 0x01, // unused
EEPROMInfo = 0x02,
EEPROMMACAddr = 0x03
};
enum sis190_feature {
F_HAS_RGMII = 1,
F_PHY_88E1111 = 2,
F_PHY_BCM5461 = 4
};
struct sis190_private {
void __iomem *mmio_addr;
struct pci_dev *pci_dev;
struct net_device *dev;
spinlock_t lock;
u32 rx_buf_sz;
u32 cur_rx;
u32 cur_tx;
u32 dirty_rx;
u32 dirty_tx;
dma_addr_t rx_dma;
dma_addr_t tx_dma;
struct RxDesc *RxDescRing;
struct TxDesc *TxDescRing;
struct sk_buff *Rx_skbuff[NUM_RX_DESC];
struct sk_buff *Tx_skbuff[NUM_TX_DESC];
struct work_struct phy_task;
struct timer_list timer;
u32 msg_enable;
struct mii_if_info mii_if;
struct list_head first_phy;
u32 features;
u32 negotiated_lpa;
enum {
LNK_OFF,
LNK_ON,
LNK_AUTONEG,
} link_status;
};
struct sis190_phy {
struct list_head list;
int phy_id;
u16 id[2];
u16 status;
u8 type;
};
enum sis190_phy_type {
UNKNOWN = 0x00,
HOME = 0x01,
LAN = 0x02,
MIX = 0x03
};
static struct mii_chip_info {
const char *name;
u16 id[2];
unsigned int type;
u32 feature;
} mii_chip_table[] = {
{ "Atheros PHY", { 0x004d, 0xd010 }, LAN, 0 },
{ "Atheros PHY AR8012", { 0x004d, 0xd020 }, LAN, 0 },
{ "Broadcom PHY BCM5461", { 0x0020, 0x60c0 }, LAN, F_PHY_BCM5461 },
{ "Broadcom PHY AC131", { 0x0143, 0xbc70 }, LAN, 0 },
{ "Agere PHY ET1101B", { 0x0282, 0xf010 }, LAN, 0 },
{ "Marvell PHY 88E1111", { 0x0141, 0x0cc0 }, LAN, F_PHY_88E1111 },
{ "Realtek PHY RTL8201", { 0x0000, 0x8200 }, LAN, 0 },
{ NULL, }
};
static const struct {
const char *name;
} sis_chip_info[] = {
{ "SiS 190 PCI Fast Ethernet adapter" },
{ "SiS 191 PCI Gigabit Ethernet adapter" },
};
static const struct pci_device_id sis190_pci_tbl[] = {
{ PCI_DEVICE(PCI_VENDOR_ID_SI, 0x0190), 0, 0, 0 },
{ PCI_DEVICE(PCI_VENDOR_ID_SI, 0x0191), 0, 0, 1 },
{ 0, },
};
MODULE_DEVICE_TABLE(pci, sis190_pci_tbl);
static int rx_copybreak = 200;
static struct {
u32 msg_enable;
} debug = { -1 };
MODULE_DESCRIPTION("SiS sis190/191 Gigabit Ethernet driver");
module_param(rx_copybreak, int, 0);
MODULE_PARM_DESC(rx_copybreak, "Copy breakpoint for copy-only-tiny-frames");
module_param_named(debug, debug.msg_enable, int, 0);
MODULE_PARM_DESC(debug, "Debug verbosity level (0=none, ..., 16=all)");
MODULE_AUTHOR("K.M. Liu <[email protected]>, Ueimor <[email protected]>");
MODULE_VERSION(DRV_VERSION);
MODULE_LICENSE("GPL");
static const u32 sis190_intr_mask =
RxQEmpty | RxQInt | TxQ1Int | TxQ0Int | RxHalt | TxHalt | LinkChange;
/*
* Maximum number of multicast addresses to filter (vs. Rx-all-multicast).
* The chips use a 64 element hash table based on the Ethernet CRC.
*/
static const int multicast_filter_limit = 32;
static void __mdio_cmd(void __iomem *ioaddr, u32 ctl)
{
unsigned int i;
SIS_W32(GMIIControl, ctl);
msleep(1);
for (i = 0; i < 100; i++) {
if (!(SIS_R32(GMIIControl) & EhnMIInotDone))
break;
msleep(1);
}
if (i > 99)
pr_err("PHY command failed !\n");
}
static void mdio_write(void __iomem *ioaddr, int phy_id, int reg, int val)
{
__mdio_cmd(ioaddr, EhnMIIreq | EhnMIIwrite |
(((u32) reg) << EhnMIIregShift) | (phy_id << EhnMIIpmdShift) |
(((u32) val) << EhnMIIdataShift));
}
static int mdio_read(void __iomem *ioaddr, int phy_id, int reg)
{
__mdio_cmd(ioaddr, EhnMIIreq | EhnMIIread |
(((u32) reg) << EhnMIIregShift) | (phy_id << EhnMIIpmdShift));
return (u16) (SIS_R32(GMIIControl) >> EhnMIIdataShift);
}
static void __mdio_write(struct net_device *dev, int phy_id, int reg, int val)
{
struct sis190_private *tp = netdev_priv(dev);
mdio_write(tp->mmio_addr, phy_id, reg, val);
}
static int __mdio_read(struct net_device *dev, int phy_id, int reg)
{
struct sis190_private *tp = netdev_priv(dev);
return mdio_read(tp->mmio_addr, phy_id, reg);
}
static u16 mdio_read_latched(void __iomem *ioaddr, int phy_id, int reg)
{
mdio_read(ioaddr, phy_id, reg);
return mdio_read(ioaddr, phy_id, reg);
}
static u16 sis190_read_eeprom(void __iomem *ioaddr, u32 reg)
{
u16 data = 0xffff;
unsigned int i;
if (!(SIS_R32(ROMControl) & 0x0002))
return 0;
SIS_W32(ROMInterface, EEREQ | EEROP | (reg << 10));
for (i = 0; i < 200; i++) {
if (!(SIS_R32(ROMInterface) & EEREQ)) {
data = (SIS_R32(ROMInterface) & 0xffff0000) >> 16;
break;
}
msleep(1);
}
return data;
}
static void sis190_irq_mask_and_ack(void __iomem *ioaddr)
{
SIS_W32(IntrMask, 0x00);
SIS_W32(IntrStatus, 0xffffffff);
SIS_PCI_COMMIT();
}
static void sis190_asic_down(void __iomem *ioaddr)
{
/* Stop the chip's Tx and Rx DMA processes. */
SIS_W32(TxControl, 0x1a00);
SIS_W32(RxControl, 0x1a00);
sis190_irq_mask_and_ack(ioaddr);
}
static void sis190_mark_as_last_descriptor(struct RxDesc *desc)
{
desc->size |= cpu_to_le32(RingEnd);
}
static inline void sis190_give_to_asic(struct RxDesc *desc, u32 rx_buf_sz)
{
u32 eor = le32_to_cpu(desc->size) & RingEnd;
desc->PSize = 0x0;
desc->size = cpu_to_le32((rx_buf_sz & RX_BUF_MASK) | eor);
wmb();
desc->status = cpu_to_le32(OWNbit | INTbit);
}
static inline void sis190_map_to_asic(struct RxDesc *desc, dma_addr_t mapping,
u32 rx_buf_sz)
{
desc->addr = cpu_to_le32(mapping);
sis190_give_to_asic(desc, rx_buf_sz);
}
static inline void sis190_make_unusable_by_asic(struct RxDesc *desc)
{
desc->PSize = 0x0;
desc->addr = cpu_to_le32(0xdeadbeef);
desc->size &= cpu_to_le32(RingEnd);
wmb();
desc->status = 0x0;
}
static struct sk_buff *sis190_alloc_rx_skb(struct sis190_private *tp,
struct RxDesc *desc)
{
u32 rx_buf_sz = tp->rx_buf_sz;
struct sk_buff *skb;
dma_addr_t mapping;
skb = netdev_alloc_skb(tp->dev, rx_buf_sz);
if (unlikely(!skb))
goto skb_alloc_failed;
mapping = dma_map_single(&tp->pci_dev->dev, skb->data, tp->rx_buf_sz,
DMA_FROM_DEVICE);
if (dma_mapping_error(&tp->pci_dev->dev, mapping))
goto out;
sis190_map_to_asic(desc, mapping, rx_buf_sz);
return skb;
out:
dev_kfree_skb_any(skb);
skb_alloc_failed:
sis190_make_unusable_by_asic(desc);
return NULL;
}
static u32 sis190_rx_fill(struct sis190_private *tp, struct net_device *dev,
u32 start, u32 end)
{
u32 cur;
for (cur = start; cur < end; cur++) {
unsigned int i = cur % NUM_RX_DESC;
if (tp->Rx_skbuff[i])
continue;
tp->Rx_skbuff[i] = sis190_alloc_rx_skb(tp, tp->RxDescRing + i);
if (!tp->Rx_skbuff[i])
break;
}
return cur - start;
}
static bool sis190_try_rx_copy(struct sis190_private *tp,
struct sk_buff **sk_buff, int pkt_size,
dma_addr_t addr)
{
struct sk_buff *skb;
bool done = false;
if (pkt_size >= rx_copybreak)
goto out;
skb = netdev_alloc_skb_ip_align(tp->dev, pkt_size);
if (!skb)
goto out;
dma_sync_single_for_cpu(&tp->pci_dev->dev, addr, tp->rx_buf_sz,
DMA_FROM_DEVICE);
skb_copy_to_linear_data(skb, sk_buff[0]->data, pkt_size);
*sk_buff = skb;
done = true;
out:
return done;
}
static inline int sis190_rx_pkt_err(u32 status, struct net_device_stats *stats)
{
#define ErrMask (OVRUN | SHORT | LIMIT | MIIER | NIBON | COLON | ABORT)
if ((status & CRCOK) && !(status & ErrMask))
return 0;
if (!(status & CRCOK))
stats->rx_crc_errors++;
else if (status & OVRUN)
stats->rx_over_errors++;
else if (status & (SHORT | LIMIT))
stats->rx_length_errors++;
else if (status & (MIIER | NIBON | COLON))
stats->rx_frame_errors++;
stats->rx_errors++;
return -1;
}
static int sis190_rx_interrupt(struct net_device *dev,
struct sis190_private *tp, void __iomem *ioaddr)
{
struct net_device_stats *stats = &dev->stats;
u32 rx_left, cur_rx = tp->cur_rx;
u32 delta, count;
rx_left = NUM_RX_DESC + tp->dirty_rx - cur_rx;
rx_left = sis190_rx_quota(rx_left, (u32) dev->quota);
for (; rx_left > 0; rx_left--, cur_rx++) {
unsigned int entry = cur_rx % NUM_RX_DESC;
struct RxDesc *desc = tp->RxDescRing + entry;
u32 status;
if (le32_to_cpu(desc->status) & OWNbit)
break;
status = le32_to_cpu(desc->PSize);
//netif_info(tp, intr, dev, "Rx PSize = %08x\n", status);
if (sis190_rx_pkt_err(status, stats) < 0)
sis190_give_to_asic(desc, tp->rx_buf_sz);
else {
struct sk_buff *skb = tp->Rx_skbuff[entry];
dma_addr_t addr = le32_to_cpu(desc->addr);
int pkt_size = (status & RxSizeMask) - 4;
struct pci_dev *pdev = tp->pci_dev;
if (unlikely(pkt_size > tp->rx_buf_sz)) {
netif_info(tp, intr, dev,
"(frag) status = %08x\n", status);
stats->rx_dropped++;
stats->rx_length_errors++;
sis190_give_to_asic(desc, tp->rx_buf_sz);
continue;
}
if (sis190_try_rx_copy(tp, &skb, pkt_size, addr)) {
dma_sync_single_for_device(&pdev->dev, addr,
tp->rx_buf_sz,
DMA_FROM_DEVICE);
sis190_give_to_asic(desc, tp->rx_buf_sz);
} else {
dma_unmap_single(&pdev->dev, addr,
tp->rx_buf_sz,
DMA_FROM_DEVICE);
tp->Rx_skbuff[entry] = NULL;
sis190_make_unusable_by_asic(desc);
}
skb_put(skb, pkt_size);
skb->protocol = eth_type_trans(skb, dev);
sis190_rx_skb(skb);
stats->rx_packets++;
stats->rx_bytes += pkt_size;
if ((status & BCAST) == MCAST)
stats->multicast++;
}
}
count = cur_rx - tp->cur_rx;
tp->cur_rx = cur_rx;
delta = sis190_rx_fill(tp, dev, tp->dirty_rx, tp->cur_rx);
if (!delta && count)
netif_info(tp, intr, dev, "no Rx buffer allocated\n");
tp->dirty_rx += delta;
if ((tp->dirty_rx + NUM_RX_DESC) == tp->cur_rx)
netif_emerg(tp, intr, dev, "Rx buffers exhausted\n");
return count;
}
static void sis190_unmap_tx_skb(struct pci_dev *pdev, struct sk_buff *skb,
struct TxDesc *desc)
{
unsigned int len;
len = skb->len < ETH_ZLEN ? ETH_ZLEN : skb->len;
dma_unmap_single(&pdev->dev, le32_to_cpu(desc->addr), len,
DMA_TO_DEVICE);
memset(desc, 0x00, sizeof(*desc));
}
static inline int sis190_tx_pkt_err(u32 status, struct net_device_stats *stats)
{
#define TxErrMask (WND | TABRT | FIFO | LINK)
if (!unlikely(status & TxErrMask))
return 0;
if (status & WND)
stats->tx_window_errors++;
if (status & TABRT)
stats->tx_aborted_errors++;
if (status & FIFO)
stats->tx_fifo_errors++;
if (status & LINK)
stats->tx_carrier_errors++;
stats->tx_errors++;
return -1;
}
static void sis190_tx_interrupt(struct net_device *dev,
struct sis190_private *tp, void __iomem *ioaddr)
{
struct net_device_stats *stats = &dev->stats;
u32 pending, dirty_tx = tp->dirty_tx;
/*
* It would not be needed if queueing was allowed to be enabled
* again too early (hint: think preempt and unclocked smp systems).
*/
unsigned int queue_stopped;
smp_rmb();
pending = tp->cur_tx - dirty_tx;
queue_stopped = (pending == NUM_TX_DESC);
for (; pending; pending--, dirty_tx++) {
unsigned int entry = dirty_tx % NUM_TX_DESC;
struct TxDesc *txd = tp->TxDescRing + entry;
u32 status = le32_to_cpu(txd->status);
struct sk_buff *skb;
if (status & OWNbit)
break;
skb = tp->Tx_skbuff[entry];
if (likely(sis190_tx_pkt_err(status, stats) == 0)) {
stats->tx_packets++;
stats->tx_bytes += skb->len;
stats->collisions += ((status & ColCountMask) - 1);
}
sis190_unmap_tx_skb(tp->pci_dev, skb, txd);
tp->Tx_skbuff[entry] = NULL;
dev_consume_skb_irq(skb);
}
if (tp->dirty_tx != dirty_tx) {
tp->dirty_tx = dirty_tx;
smp_wmb();
if (queue_stopped)
netif_wake_queue(dev);
}
}
/*
* The interrupt handler does all of the Rx thread work and cleans up after
* the Tx thread.
*/
static irqreturn_t sis190_irq(int irq, void *__dev)
{
struct net_device *dev = __dev;
struct sis190_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
unsigned int handled = 0;
u32 status;
status = SIS_R32(IntrStatus);
if ((status == 0xffffffff) || !status)
goto out;
handled = 1;
if (unlikely(!netif_running(dev))) {
sis190_asic_down(ioaddr);
goto out;
}
SIS_W32(IntrStatus, status);
// netif_info(tp, intr, dev, "status = %08x\n", status);
if (status & LinkChange) {
netif_info(tp, intr, dev, "link change\n");
del_timer(&tp->timer);
schedule_work(&tp->phy_task);
}
if (status & RxQInt)
sis190_rx_interrupt(dev, tp, ioaddr);
if (status & TxQ0Int)
sis190_tx_interrupt(dev, tp, ioaddr);
out:
return IRQ_RETVAL(handled);
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void sis190_netpoll(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
const int irq = tp->pci_dev->irq;
disable_irq(irq);
sis190_irq(irq, dev);
enable_irq(irq);
}
#endif
static void sis190_free_rx_skb(struct sis190_private *tp,
struct sk_buff **sk_buff, struct RxDesc *desc)
{
struct pci_dev *pdev = tp->pci_dev;
dma_unmap_single(&pdev->dev, le32_to_cpu(desc->addr), tp->rx_buf_sz,
DMA_FROM_DEVICE);
dev_kfree_skb(*sk_buff);
*sk_buff = NULL;
sis190_make_unusable_by_asic(desc);
}
static void sis190_rx_clear(struct sis190_private *tp)
{
unsigned int i;
for (i = 0; i < NUM_RX_DESC; i++) {
if (!tp->Rx_skbuff[i])
continue;
sis190_free_rx_skb(tp, tp->Rx_skbuff + i, tp->RxDescRing + i);
}
}
static void sis190_init_ring_indexes(struct sis190_private *tp)
{
tp->dirty_tx = tp->dirty_rx = tp->cur_tx = tp->cur_rx = 0;
}
static int sis190_init_ring(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
sis190_init_ring_indexes(tp);
memset(tp->Tx_skbuff, 0x0, NUM_TX_DESC * sizeof(struct sk_buff *));
memset(tp->Rx_skbuff, 0x0, NUM_RX_DESC * sizeof(struct sk_buff *));
if (sis190_rx_fill(tp, dev, 0, NUM_RX_DESC) != NUM_RX_DESC)
goto err_rx_clear;
sis190_mark_as_last_descriptor(tp->RxDescRing + NUM_RX_DESC - 1);
return 0;
err_rx_clear:
sis190_rx_clear(tp);
return -ENOMEM;
}
static void sis190_set_rx_mode(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
unsigned long flags;
u32 mc_filter[2]; /* Multicast hash filter */
u16 rx_mode;
if (dev->flags & IFF_PROMISC) {
rx_mode =
AcceptBroadcast | AcceptMulticast | AcceptMyPhys |
AcceptAllPhys;
mc_filter[1] = mc_filter[0] = 0xffffffff;
} else if ((netdev_mc_count(dev) > multicast_filter_limit) ||
(dev->flags & IFF_ALLMULTI)) {
/* Too many to filter perfectly -- accept all multicasts. */
rx_mode = AcceptBroadcast | AcceptMulticast | AcceptMyPhys;
mc_filter[1] = mc_filter[0] = 0xffffffff;
} else {
struct netdev_hw_addr *ha;
rx_mode = AcceptBroadcast | AcceptMyPhys;
mc_filter[1] = mc_filter[0] = 0;
netdev_for_each_mc_addr(ha, dev) {
int bit_nr =
ether_crc(ETH_ALEN, ha->addr) & 0x3f;
mc_filter[bit_nr >> 5] |= 1 << (bit_nr & 31);
rx_mode |= AcceptMulticast;
}
}
spin_lock_irqsave(&tp->lock, flags);
SIS_W16(RxMacControl, rx_mode | 0x2);
SIS_W32(RxHashTable, mc_filter[0]);
SIS_W32(RxHashTable + 4, mc_filter[1]);
spin_unlock_irqrestore(&tp->lock, flags);
}
static void sis190_soft_reset(void __iomem *ioaddr)
{
SIS_W32(IntrControl, 0x8000);
SIS_PCI_COMMIT();
SIS_W32(IntrControl, 0x0);
sis190_asic_down(ioaddr);
}
static void sis190_hw_start(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
sis190_soft_reset(ioaddr);
SIS_W32(TxDescStartAddr, tp->tx_dma);
SIS_W32(RxDescStartAddr, tp->rx_dma);
SIS_W32(IntrStatus, 0xffffffff);
SIS_W32(IntrMask, 0x0);
SIS_W32(GMIIControl, 0x0);
SIS_W32(TxMacControl, 0x60);
SIS_W16(RxMacControl, 0x02);
SIS_W32(RxHashTable, 0x0);
SIS_W32(0x6c, 0x0);
SIS_W32(RxWolCtrl, 0x0);
SIS_W32(RxWolData, 0x0);
SIS_PCI_COMMIT();
sis190_set_rx_mode(dev);
/* Enable all known interrupts by setting the interrupt mask. */
SIS_W32(IntrMask, sis190_intr_mask);
SIS_W32(TxControl, 0x1a00 | CmdTxEnb);
SIS_W32(RxControl, 0x1a1d);
netif_start_queue(dev);
}
static void sis190_phy_task(struct work_struct *work)
{
struct sis190_private *tp =
container_of(work, struct sis190_private, phy_task);
struct net_device *dev = tp->dev;
void __iomem *ioaddr = tp->mmio_addr;
int phy_id = tp->mii_if.phy_id;
u16 val;
rtnl_lock();
if (!netif_running(dev))
goto out_unlock;
val = mdio_read(ioaddr, phy_id, MII_BMCR);
if (val & BMCR_RESET) {
// FIXME: needlessly high ? -- FR 02/07/2005
mod_timer(&tp->timer, jiffies + HZ/10);
goto out_unlock;
}
val = mdio_read_latched(ioaddr, phy_id, MII_BMSR);
if (!(val & BMSR_ANEGCOMPLETE) && tp->link_status != LNK_AUTONEG) {
netif_carrier_off(dev);
netif_warn(tp, link, dev, "auto-negotiating...\n");
tp->link_status = LNK_AUTONEG;
} else if ((val & BMSR_LSTATUS) && tp->link_status != LNK_ON) {
/* Rejoice ! */
struct {
int val;
u32 ctl;
const char *msg;
} reg31[] = {
{ LPA_1000FULL, 0x07000c00 | 0x00001000,
"1000 Mbps Full Duplex" },
{ LPA_1000HALF, 0x07000c00,
"1000 Mbps Half Duplex" },
{ LPA_100FULL, 0x04000800 | 0x00001000,
"100 Mbps Full Duplex" },
{ LPA_100HALF, 0x04000800,
"100 Mbps Half Duplex" },
{ LPA_10FULL, 0x04000400 | 0x00001000,
"10 Mbps Full Duplex" },
{ LPA_10HALF, 0x04000400,
"10 Mbps Half Duplex" },
{ 0, 0x04000400, "unknown" }
}, *p = NULL;
u16 adv, autoexp, gigadv, gigrec;
val = mdio_read(ioaddr, phy_id, 0x1f);
netif_info(tp, link, dev, "mii ext = %04x\n", val);
val = mdio_read(ioaddr, phy_id, MII_LPA);
adv = mdio_read(ioaddr, phy_id, MII_ADVERTISE);
autoexp = mdio_read(ioaddr, phy_id, MII_EXPANSION);
netif_info(tp, link, dev, "mii lpa=%04x adv=%04x exp=%04x\n",
val, adv, autoexp);
if (val & LPA_NPAGE && autoexp & EXPANSION_NWAY) {
/* check for gigabit speed */
gigadv = mdio_read(ioaddr, phy_id, MII_CTRL1000);
gigrec = mdio_read(ioaddr, phy_id, MII_STAT1000);
val = (gigadv & (gigrec >> 2));
if (val & ADVERTISE_1000FULL)
p = reg31;
else if (val & ADVERTISE_1000HALF)
p = reg31 + 1;
}
if (!p) {
val &= adv;
for (p = reg31; p->val; p++) {
if ((val & p->val) == p->val)
break;
}
}
p->ctl |= SIS_R32(StationControl) & ~0x0f001c00;
if ((tp->features & F_HAS_RGMII) &&
(tp->features & F_PHY_BCM5461)) {
// Set Tx Delay in RGMII mode.
mdio_write(ioaddr, phy_id, 0x18, 0xf1c7);
udelay(200);
mdio_write(ioaddr, phy_id, 0x1c, 0x8c00);
p->ctl |= 0x03000000;
}
SIS_W32(StationControl, p->ctl);
if (tp->features & F_HAS_RGMII) {
SIS_W32(RGDelay, 0x0441);
SIS_W32(RGDelay, 0x0440);
}
tp->negotiated_lpa = p->val;
netif_info(tp, link, dev, "link on %s mode\n", p->msg);
netif_carrier_on(dev);
tp->link_status = LNK_ON;
} else if (!(val & BMSR_LSTATUS) && tp->link_status != LNK_AUTONEG)
tp->link_status = LNK_OFF;
mod_timer(&tp->timer, jiffies + SIS190_PHY_TIMEOUT);
out_unlock:
rtnl_unlock();
}
static void sis190_phy_timer(struct timer_list *t)
{
struct sis190_private *tp = from_timer(tp, t, timer);
struct net_device *dev = tp->dev;
if (likely(netif_running(dev)))
schedule_work(&tp->phy_task);
}
static inline void sis190_delete_timer(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
del_timer_sync(&tp->timer);
}
static inline void sis190_request_timer(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
struct timer_list *timer = &tp->timer;
timer_setup(timer, sis190_phy_timer, 0);
timer->expires = jiffies + SIS190_PHY_TIMEOUT;
add_timer(timer);
}
static void sis190_set_rxbufsize(struct sis190_private *tp,
struct net_device *dev)
{
unsigned int mtu = dev->mtu;
tp->rx_buf_sz = (mtu > RX_BUF_SIZE) ? mtu + ETH_HLEN + 8 : RX_BUF_SIZE;
/* RxDesc->size has a licence to kill the lower bits */
if (tp->rx_buf_sz & 0x07) {
tp->rx_buf_sz += 8;
tp->rx_buf_sz &= RX_BUF_MASK;
}
}
static int sis190_open(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
struct pci_dev *pdev = tp->pci_dev;
int rc = -ENOMEM;
sis190_set_rxbufsize(tp, dev);
/*
* Rx and Tx descriptors need 256 bytes alignment.
* dma_alloc_coherent() guarantees a stronger alignment.
*/
tp->TxDescRing = dma_alloc_coherent(&pdev->dev, TX_RING_BYTES,
&tp->tx_dma, GFP_KERNEL);
if (!tp->TxDescRing)
goto out;
tp->RxDescRing = dma_alloc_coherent(&pdev->dev, RX_RING_BYTES,
&tp->rx_dma, GFP_KERNEL);
if (!tp->RxDescRing)
goto err_free_tx_0;
rc = sis190_init_ring(dev);
if (rc < 0)
goto err_free_rx_1;
sis190_request_timer(dev);
rc = request_irq(pdev->irq, sis190_irq, IRQF_SHARED, dev->name, dev);
if (rc < 0)
goto err_release_timer_2;
sis190_hw_start(dev);
out:
return rc;
err_release_timer_2:
sis190_delete_timer(dev);
sis190_rx_clear(tp);
err_free_rx_1:
dma_free_coherent(&pdev->dev, RX_RING_BYTES, tp->RxDescRing,
tp->rx_dma);
err_free_tx_0:
dma_free_coherent(&pdev->dev, TX_RING_BYTES, tp->TxDescRing,
tp->tx_dma);
goto out;
}
static void sis190_tx_clear(struct sis190_private *tp)
{
unsigned int i;
for (i = 0; i < NUM_TX_DESC; i++) {
struct sk_buff *skb = tp->Tx_skbuff[i];
if (!skb)
continue;
sis190_unmap_tx_skb(tp->pci_dev, skb, tp->TxDescRing + i);
tp->Tx_skbuff[i] = NULL;
dev_kfree_skb(skb);
tp->dev->stats.tx_dropped++;
}
tp->cur_tx = tp->dirty_tx = 0;
}
static void sis190_down(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
unsigned int poll_locked = 0;
sis190_delete_timer(dev);
netif_stop_queue(dev);
do {
spin_lock_irq(&tp->lock);
sis190_asic_down(ioaddr);
spin_unlock_irq(&tp->lock);
synchronize_irq(tp->pci_dev->irq);
if (!poll_locked)
poll_locked++;
synchronize_rcu();
} while (SIS_R32(IntrMask));
sis190_tx_clear(tp);
sis190_rx_clear(tp);
}
static int sis190_close(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
struct pci_dev *pdev = tp->pci_dev;
sis190_down(dev);
free_irq(pdev->irq, dev);
dma_free_coherent(&pdev->dev, TX_RING_BYTES, tp->TxDescRing,
tp->tx_dma);
dma_free_coherent(&pdev->dev, RX_RING_BYTES, tp->RxDescRing,
tp->rx_dma);
tp->TxDescRing = NULL;
tp->RxDescRing = NULL;
return 0;
}
static netdev_tx_t sis190_start_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
u32 len, entry, dirty_tx;
struct TxDesc *desc;
dma_addr_t mapping;
if (unlikely(skb->len < ETH_ZLEN)) {
if (skb_padto(skb, ETH_ZLEN)) {
dev->stats.tx_dropped++;
goto out;
}
len = ETH_ZLEN;
} else {
len = skb->len;
}
entry = tp->cur_tx % NUM_TX_DESC;
desc = tp->TxDescRing + entry;
if (unlikely(le32_to_cpu(desc->status) & OWNbit)) {
netif_stop_queue(dev);
netif_err(tp, tx_err, dev,
"BUG! Tx Ring full when queue awake!\n");
return NETDEV_TX_BUSY;
}
mapping = dma_map_single(&tp->pci_dev->dev, skb->data, len,
DMA_TO_DEVICE);
if (dma_mapping_error(&tp->pci_dev->dev, mapping)) {
netif_err(tp, tx_err, dev,
"PCI mapping failed, dropping packet");
return NETDEV_TX_BUSY;
}
tp->Tx_skbuff[entry] = skb;
desc->PSize = cpu_to_le32(len);
desc->addr = cpu_to_le32(mapping);
desc->size = cpu_to_le32(len);
if (entry == (NUM_TX_DESC - 1))
desc->size |= cpu_to_le32(RingEnd);
wmb();
desc->status = cpu_to_le32(OWNbit | INTbit | DEFbit | CRCbit | PADbit);
if (tp->negotiated_lpa & (LPA_1000HALF | LPA_100HALF | LPA_10HALF)) {
/* Half Duplex */
desc->status |= cpu_to_le32(COLEN | CRSEN | BKFEN);
if (tp->negotiated_lpa & (LPA_1000HALF | LPA_1000FULL))
desc->status |= cpu_to_le32(EXTEN | BSTEN); /* gigabit HD */
}
tp->cur_tx++;
smp_wmb();
SIS_W32(TxControl, 0x1a00 | CmdReset | CmdTxEnb);
dirty_tx = tp->dirty_tx;
if ((tp->cur_tx - NUM_TX_DESC) == dirty_tx) {
netif_stop_queue(dev);
smp_rmb();
if (dirty_tx != tp->dirty_tx)
netif_wake_queue(dev);
}
out:
return NETDEV_TX_OK;
}
static void sis190_free_phy(struct list_head *first_phy)
{
struct sis190_phy *cur, *next;
list_for_each_entry_safe(cur, next, first_phy, list) {
kfree(cur);
}
}
/**
* sis190_default_phy - Select default PHY for sis190 mac.
* @dev: the net device to probe for
*
* Select first detected PHY with link as default.
* If no one is link on, select PHY whose types is HOME as default.
* If HOME doesn't exist, select LAN.
*/
static u16 sis190_default_phy(struct net_device *dev)
{
struct sis190_phy *phy, *phy_home, *phy_default, *phy_lan;
struct sis190_private *tp = netdev_priv(dev);
struct mii_if_info *mii_if = &tp->mii_if;
void __iomem *ioaddr = tp->mmio_addr;
u16 status;
phy_home = phy_default = phy_lan = NULL;
list_for_each_entry(phy, &tp->first_phy, list) {
status = mdio_read_latched(ioaddr, phy->phy_id, MII_BMSR);
// Link ON & Not select default PHY & not ghost PHY.
if ((status & BMSR_LSTATUS) &&
!phy_default &&
(phy->type != UNKNOWN)) {
phy_default = phy;
} else {
status = mdio_read(ioaddr, phy->phy_id, MII_BMCR);
mdio_write(ioaddr, phy->phy_id, MII_BMCR,
status | BMCR_ANENABLE | BMCR_ISOLATE);
if (phy->type == HOME)
phy_home = phy;
else if (phy->type == LAN)
phy_lan = phy;
}
}
if (!phy_default) {
if (phy_home)
phy_default = phy_home;
else if (phy_lan)
phy_default = phy_lan;
else
phy_default = list_first_entry(&tp->first_phy,
struct sis190_phy, list);
}
if (mii_if->phy_id != phy_default->phy_id) {
mii_if->phy_id = phy_default->phy_id;
if (netif_msg_probe(tp))
pr_info("%s: Using transceiver at address %d as default\n",
pci_name(tp->pci_dev), mii_if->phy_id);
}
status = mdio_read(ioaddr, mii_if->phy_id, MII_BMCR);
status &= (~BMCR_ISOLATE);
mdio_write(ioaddr, mii_if->phy_id, MII_BMCR, status);
status = mdio_read_latched(ioaddr, mii_if->phy_id, MII_BMSR);
return status;
}
static void sis190_init_phy(struct net_device *dev, struct sis190_private *tp,
struct sis190_phy *phy, unsigned int phy_id,
u16 mii_status)
{
void __iomem *ioaddr = tp->mmio_addr;
struct mii_chip_info *p;
INIT_LIST_HEAD(&phy->list);
phy->status = mii_status;
phy->phy_id = phy_id;
phy->id[0] = mdio_read(ioaddr, phy_id, MII_PHYSID1);
phy->id[1] = mdio_read(ioaddr, phy_id, MII_PHYSID2);
for (p = mii_chip_table; p->type; p++) {
if ((p->id[0] == phy->id[0]) &&
(p->id[1] == (phy->id[1] & 0xfff0))) {
break;
}
}
if (p->id[1]) {
phy->type = (p->type == MIX) ?
((mii_status & (BMSR_100FULL | BMSR_100HALF)) ?
LAN : HOME) : p->type;
tp->features |= p->feature;
if (netif_msg_probe(tp))
pr_info("%s: %s transceiver at address %d\n",
pci_name(tp->pci_dev), p->name, phy_id);
} else {
phy->type = UNKNOWN;
if (netif_msg_probe(tp))
pr_info("%s: unknown PHY 0x%x:0x%x transceiver at address %d\n",
pci_name(tp->pci_dev),
phy->id[0], (phy->id[1] & 0xfff0), phy_id);
}
}
static void sis190_mii_probe_88e1111_fixup(struct sis190_private *tp)
{
if (tp->features & F_PHY_88E1111) {
void __iomem *ioaddr = tp->mmio_addr;
int phy_id = tp->mii_if.phy_id;
u16 reg[2][2] = {
{ 0x808b, 0x0ce1 },
{ 0x808f, 0x0c60 }
}, *p;
p = (tp->features & F_HAS_RGMII) ? reg[0] : reg[1];
mdio_write(ioaddr, phy_id, 0x1b, p[0]);
udelay(200);
mdio_write(ioaddr, phy_id, 0x14, p[1]);
udelay(200);
}
}
/**
* sis190_mii_probe - Probe MII PHY for sis190
* @dev: the net device to probe for
*
* Search for total of 32 possible mii phy addresses.
* Identify and set current phy if found one,
* return error if it failed to found.
*/
static int sis190_mii_probe(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
struct mii_if_info *mii_if = &tp->mii_if;
void __iomem *ioaddr = tp->mmio_addr;
int phy_id;
int rc = 0;
INIT_LIST_HEAD(&tp->first_phy);
for (phy_id = 0; phy_id < PHY_MAX_ADDR; phy_id++) {
struct sis190_phy *phy;
u16 status;
status = mdio_read_latched(ioaddr, phy_id, MII_BMSR);
// Try next mii if the current one is not accessible.
if (status == 0xffff || status == 0x0000)
continue;
phy = kmalloc(sizeof(*phy), GFP_KERNEL);
if (!phy) {
sis190_free_phy(&tp->first_phy);
rc = -ENOMEM;
goto out;
}
sis190_init_phy(dev, tp, phy, phy_id, status);
list_add(&tp->first_phy, &phy->list);
}
if (list_empty(&tp->first_phy)) {
if (netif_msg_probe(tp))
pr_info("%s: No MII transceivers found!\n",
pci_name(tp->pci_dev));
rc = -EIO;
goto out;
}
/* Select default PHY for mac */
sis190_default_phy(dev);
sis190_mii_probe_88e1111_fixup(tp);
mii_if->dev = dev;
mii_if->mdio_read = __mdio_read;
mii_if->mdio_write = __mdio_write;
mii_if->phy_id_mask = PHY_ID_ANY;
mii_if->reg_num_mask = MII_REG_ANY;
out:
return rc;
}
static void sis190_mii_remove(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
sis190_free_phy(&tp->first_phy);
}
static void sis190_release_board(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct sis190_private *tp = netdev_priv(dev);
iounmap(tp->mmio_addr);
pci_release_regions(pdev);
pci_disable_device(pdev);
free_netdev(dev);
}
static struct net_device *sis190_init_board(struct pci_dev *pdev)
{
struct sis190_private *tp;
struct net_device *dev;
void __iomem *ioaddr;
int rc;
dev = alloc_etherdev(sizeof(*tp));
if (!dev) {
rc = -ENOMEM;
goto err_out_0;
}
SET_NETDEV_DEV(dev, &pdev->dev);
tp = netdev_priv(dev);
tp->dev = dev;
tp->msg_enable = netif_msg_init(debug.msg_enable, SIS190_MSG_DEFAULT);
rc = pci_enable_device(pdev);
if (rc < 0) {
if (netif_msg_probe(tp))
pr_err("%s: enable failure\n", pci_name(pdev));
goto err_free_dev_1;
}
rc = -ENODEV;
if (!(pci_resource_flags(pdev, 0) & IORESOURCE_MEM)) {
if (netif_msg_probe(tp))
pr_err("%s: region #0 is no MMIO resource\n",
pci_name(pdev));
goto err_pci_disable_2;
}
if (pci_resource_len(pdev, 0) < SIS190_REGS_SIZE) {
if (netif_msg_probe(tp))
pr_err("%s: invalid PCI region size(s)\n",
pci_name(pdev));
goto err_pci_disable_2;
}
rc = pci_request_regions(pdev, DRV_NAME);
if (rc < 0) {
if (netif_msg_probe(tp))
pr_err("%s: could not request regions\n",
pci_name(pdev));
goto err_pci_disable_2;
}
rc = dma_set_mask(&pdev->dev, DMA_BIT_MASK(32));
if (rc < 0) {
if (netif_msg_probe(tp))
pr_err("%s: DMA configuration failed\n",
pci_name(pdev));
goto err_free_res_3;
}
pci_set_master(pdev);
ioaddr = ioremap(pci_resource_start(pdev, 0), SIS190_REGS_SIZE);
if (!ioaddr) {
if (netif_msg_probe(tp))
pr_err("%s: cannot remap MMIO, aborting\n",
pci_name(pdev));
rc = -EIO;
goto err_free_res_3;
}
tp->pci_dev = pdev;
tp->mmio_addr = ioaddr;
tp->link_status = LNK_OFF;
sis190_irq_mask_and_ack(ioaddr);
sis190_soft_reset(ioaddr);
out:
return dev;
err_free_res_3:
pci_release_regions(pdev);
err_pci_disable_2:
pci_disable_device(pdev);
err_free_dev_1:
free_netdev(dev);
err_out_0:
dev = ERR_PTR(rc);
goto out;
}
static void sis190_tx_timeout(struct net_device *dev, unsigned int txqueue)
{
struct sis190_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
u8 tmp8;
/* Disable Tx, if not already */
tmp8 = SIS_R8(TxControl);
if (tmp8 & CmdTxEnb)
SIS_W8(TxControl, tmp8 & ~CmdTxEnb);
netif_info(tp, tx_err, dev, "Transmit timeout, status %08x %08x\n",
SIS_R32(TxControl), SIS_R32(TxSts));
/* Disable interrupts by clearing the interrupt mask. */
SIS_W32(IntrMask, 0x0000);
/* Stop a shared interrupt from scavenging while we are. */
spin_lock_irq(&tp->lock);
sis190_tx_clear(tp);
spin_unlock_irq(&tp->lock);
/* ...and finally, reset everything. */
sis190_hw_start(dev);
netif_wake_queue(dev);
}
static void sis190_set_rgmii(struct sis190_private *tp, u8 reg)
{
tp->features |= (reg & 0x80) ? F_HAS_RGMII : 0;
}
static int sis190_get_mac_addr_from_eeprom(struct pci_dev *pdev,
struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
__le16 addr[ETH_ALEN / 2];
u16 sig;
int i;
if (netif_msg_probe(tp))
pr_info("%s: Read MAC address from EEPROM\n", pci_name(pdev));
/* Check to see if there is a sane EEPROM */
sig = (u16) sis190_read_eeprom(ioaddr, EEPROMSignature);
if ((sig == 0xffff) || (sig == 0x0000)) {
if (netif_msg_probe(tp))
pr_info("%s: Error EEPROM read %x\n",
pci_name(pdev), sig);
return -EIO;
}
/* Get MAC address from EEPROM */
for (i = 0; i < ETH_ALEN / 2; i++) {
u16 w = sis190_read_eeprom(ioaddr, EEPROMMACAddr + i);
addr[i] = cpu_to_le16(w);
}
eth_hw_addr_set(dev, (u8 *)addr);
sis190_set_rgmii(tp, sis190_read_eeprom(ioaddr, EEPROMInfo));
return 0;
}
/**
* sis190_get_mac_addr_from_apc - Get MAC address for SiS96x model
* @pdev: PCI device
* @dev: network device to get address for
*
* SiS96x model, use APC CMOS RAM to store MAC address.
* APC CMOS RAM is accessed through ISA bridge.
* MAC address is read into @net_dev->dev_addr.
*/
static int sis190_get_mac_addr_from_apc(struct pci_dev *pdev,
struct net_device *dev)
{
static const u16 ids[] = { 0x0965, 0x0966, 0x0968 };
struct sis190_private *tp = netdev_priv(dev);
struct pci_dev *isa_bridge;
u8 addr[ETH_ALEN];
u8 reg, tmp8;
unsigned int i;
if (netif_msg_probe(tp))
pr_info("%s: Read MAC address from APC\n", pci_name(pdev));
for (i = 0; i < ARRAY_SIZE(ids); i++) {
isa_bridge = pci_get_device(PCI_VENDOR_ID_SI, ids[i], NULL);
if (isa_bridge)
break;
}
if (!isa_bridge) {
if (netif_msg_probe(tp))
pr_info("%s: Can not find ISA bridge\n",
pci_name(pdev));
return -EIO;
}
/* Enable port 78h & 79h to access APC Registers. */
pci_read_config_byte(isa_bridge, 0x48, &tmp8);
reg = (tmp8 & ~0x02);
pci_write_config_byte(isa_bridge, 0x48, reg);
udelay(50);
pci_read_config_byte(isa_bridge, 0x48, ®);
for (i = 0; i < ETH_ALEN; i++) {
outb(0x9 + i, 0x78);
addr[i] = inb(0x79);
}
eth_hw_addr_set(dev, addr);
outb(0x12, 0x78);
reg = inb(0x79);
sis190_set_rgmii(tp, reg);
/* Restore the value to ISA Bridge */
pci_write_config_byte(isa_bridge, 0x48, tmp8);
pci_dev_put(isa_bridge);
return 0;
}
/**
* sis190_init_rxfilter - Initialize the Rx filter
* @dev: network device to initialize
*
* Set receive filter address to our MAC address
* and enable packet filtering.
*/
static inline void sis190_init_rxfilter(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
u16 ctl;
int i;
ctl = SIS_R16(RxMacControl);
/*
* Disable packet filtering before setting filter.
* Note: SiS's driver writes 32 bits but RxMacControl is 16 bits
* only and followed by RxMacAddr (6 bytes). Strange. -- FR
*/
SIS_W16(RxMacControl, ctl & ~0x0f00);
for (i = 0; i < ETH_ALEN; i++)
SIS_W8(RxMacAddr + i, dev->dev_addr[i]);
SIS_W16(RxMacControl, ctl);
SIS_PCI_COMMIT();
}
static int sis190_get_mac_addr(struct pci_dev *pdev, struct net_device *dev)
{
int rc;
rc = sis190_get_mac_addr_from_eeprom(pdev, dev);
if (rc < 0) {
u8 reg;
pci_read_config_byte(pdev, 0x73, ®);
if (reg & 0x00000001)
rc = sis190_get_mac_addr_from_apc(pdev, dev);
}
return rc;
}
static void sis190_set_speed_auto(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
int phy_id = tp->mii_if.phy_id;
int val;
netif_info(tp, link, dev, "Enabling Auto-negotiation\n");
val = mdio_read(ioaddr, phy_id, MII_ADVERTISE);
// Enable 10/100 Full/Half Mode, leave MII_ADVERTISE bit4:0
// unchanged.
mdio_write(ioaddr, phy_id, MII_ADVERTISE, (val & ADVERTISE_SLCT) |
ADVERTISE_100FULL | ADVERTISE_10FULL |
ADVERTISE_100HALF | ADVERTISE_10HALF);
// Enable 1000 Full Mode.
mdio_write(ioaddr, phy_id, MII_CTRL1000, ADVERTISE_1000FULL);
// Enable auto-negotiation and restart auto-negotiation.
mdio_write(ioaddr, phy_id, MII_BMCR,
BMCR_ANENABLE | BMCR_ANRESTART | BMCR_RESET);
}
static int sis190_get_link_ksettings(struct net_device *dev,
struct ethtool_link_ksettings *cmd)
{
struct sis190_private *tp = netdev_priv(dev);
mii_ethtool_get_link_ksettings(&tp->mii_if, cmd);
return 0;
}
static int sis190_set_link_ksettings(struct net_device *dev,
const struct ethtool_link_ksettings *cmd)
{
struct sis190_private *tp = netdev_priv(dev);
return mii_ethtool_set_link_ksettings(&tp->mii_if, cmd);
}
static void sis190_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
struct sis190_private *tp = netdev_priv(dev);
strscpy(info->driver, DRV_NAME, sizeof(info->driver));
strscpy(info->version, DRV_VERSION, sizeof(info->version));
strscpy(info->bus_info, pci_name(tp->pci_dev),
sizeof(info->bus_info));
}
static int sis190_get_regs_len(struct net_device *dev)
{
return SIS190_REGS_SIZE;
}
static void sis190_get_regs(struct net_device *dev, struct ethtool_regs *regs,
void *p)
{
struct sis190_private *tp = netdev_priv(dev);
unsigned long flags;
spin_lock_irqsave(&tp->lock, flags);
memcpy_fromio(p, tp->mmio_addr, regs->len);
spin_unlock_irqrestore(&tp->lock, flags);
}
static int sis190_nway_reset(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
return mii_nway_restart(&tp->mii_if);
}
static u32 sis190_get_msglevel(struct net_device *dev)
{
struct sis190_private *tp = netdev_priv(dev);
return tp->msg_enable;
}
static void sis190_set_msglevel(struct net_device *dev, u32 value)
{
struct sis190_private *tp = netdev_priv(dev);
tp->msg_enable = value;
}
static const struct ethtool_ops sis190_ethtool_ops = {
.get_drvinfo = sis190_get_drvinfo,
.get_regs_len = sis190_get_regs_len,
.get_regs = sis190_get_regs,
.get_link = ethtool_op_get_link,
.get_msglevel = sis190_get_msglevel,
.set_msglevel = sis190_set_msglevel,
.nway_reset = sis190_nway_reset,
.get_link_ksettings = sis190_get_link_ksettings,
.set_link_ksettings = sis190_set_link_ksettings,
};
static int sis190_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
struct sis190_private *tp = netdev_priv(dev);
return !netif_running(dev) ? -EINVAL :
generic_mii_ioctl(&tp->mii_if, if_mii(ifr), cmd, NULL);
}
static int sis190_mac_addr(struct net_device *dev, void *p)
{
int rc;
rc = eth_mac_addr(dev, p);
if (!rc)
sis190_init_rxfilter(dev);
return rc;
}
static const struct net_device_ops sis190_netdev_ops = {
.ndo_open = sis190_open,
.ndo_stop = sis190_close,
.ndo_eth_ioctl = sis190_ioctl,
.ndo_start_xmit = sis190_start_xmit,
.ndo_tx_timeout = sis190_tx_timeout,
.ndo_set_rx_mode = sis190_set_rx_mode,
.ndo_set_mac_address = sis190_mac_addr,
.ndo_validate_addr = eth_validate_addr,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = sis190_netpoll,
#endif
};
static int sis190_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
static int printed_version = 0;
struct sis190_private *tp;
struct net_device *dev;
void __iomem *ioaddr;
int rc;
if (!printed_version) {
if (netif_msg_drv(&debug))
pr_info(SIS190_DRIVER_NAME " loaded\n");
printed_version = 1;
}
dev = sis190_init_board(pdev);
if (IS_ERR(dev)) {
rc = PTR_ERR(dev);
goto out;
}
pci_set_drvdata(pdev, dev);
tp = netdev_priv(dev);
ioaddr = tp->mmio_addr;
rc = sis190_get_mac_addr(pdev, dev);
if (rc < 0)
goto err_release_board;
sis190_init_rxfilter(dev);
INIT_WORK(&tp->phy_task, sis190_phy_task);
dev->netdev_ops = &sis190_netdev_ops;
dev->ethtool_ops = &sis190_ethtool_ops;
dev->watchdog_timeo = SIS190_TX_TIMEOUT;
spin_lock_init(&tp->lock);
rc = sis190_mii_probe(dev);
if (rc < 0)
goto err_release_board;
rc = register_netdev(dev);
if (rc < 0)
goto err_remove_mii;
if (netif_msg_probe(tp)) {
netdev_info(dev, "%s: %s at %p (IRQ: %d), %pM\n",
pci_name(pdev),
sis_chip_info[ent->driver_data].name,
ioaddr, pdev->irq, dev->dev_addr);
netdev_info(dev, "%s mode.\n",
(tp->features & F_HAS_RGMII) ? "RGMII" : "GMII");
}
netif_carrier_off(dev);
sis190_set_speed_auto(dev);
out:
return rc;
err_remove_mii:
sis190_mii_remove(dev);
err_release_board:
sis190_release_board(pdev);
goto out;
}
static void sis190_remove_one(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct sis190_private *tp = netdev_priv(dev);
sis190_mii_remove(dev);
cancel_work_sync(&tp->phy_task);
unregister_netdev(dev);
sis190_release_board(pdev);
}
static struct pci_driver sis190_pci_driver = {
.name = DRV_NAME,
.id_table = sis190_pci_tbl,
.probe = sis190_init_one,
.remove = sis190_remove_one,
};
module_pci_driver(sis190_pci_driver);
|
linux-master
|
drivers/net/ethernet/sis/sis190.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Linux network driver for QLogic BR-series Converged Network Adapter.
*/
/*
* Copyright (c) 2005-2014 Brocade Communications Systems, Inc.
* Copyright (c) 2014-2015 QLogic Corporation
* All rights reserved
* www.qlogic.com
*/
#include <linux/bitops.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <linux/etherdevice.h>
#include <linux/in.h>
#include <linux/ethtool.h>
#include <linux/if_vlan.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/prefetch.h>
#include <linux/module.h>
#include "bnad.h"
#include "bna.h"
#include "cna.h"
static DEFINE_MUTEX(bnad_fwimg_mutex);
/*
* Module params
*/
static uint bnad_msix_disable;
module_param(bnad_msix_disable, uint, 0444);
MODULE_PARM_DESC(bnad_msix_disable, "Disable MSIX mode");
static uint bnad_ioc_auto_recover = 1;
module_param(bnad_ioc_auto_recover, uint, 0444);
MODULE_PARM_DESC(bnad_ioc_auto_recover, "Enable / Disable auto recovery");
static uint bna_debugfs_enable = 1;
module_param(bna_debugfs_enable, uint, 0644);
MODULE_PARM_DESC(bna_debugfs_enable, "Enables debugfs feature, default=1,"
" Range[false:0|true:1]");
/*
* Global variables
*/
static u32 bnad_rxqs_per_cq = 2;
static atomic_t bna_id;
static const u8 bnad_bcast_addr[] __aligned(2) =
{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
/*
* Local MACROS
*/
#define BNAD_GET_MBOX_IRQ(_bnad) \
(((_bnad)->cfg_flags & BNAD_CF_MSIX) ? \
((_bnad)->msix_table[BNAD_MAILBOX_MSIX_INDEX].vector) : \
((_bnad)->pcidev->irq))
#define BNAD_FILL_UNMAPQ_MEM_REQ(_res_info, _num, _size) \
do { \
(_res_info)->res_type = BNA_RES_T_MEM; \
(_res_info)->res_u.mem_info.mem_type = BNA_MEM_T_KVA; \
(_res_info)->res_u.mem_info.num = (_num); \
(_res_info)->res_u.mem_info.len = (_size); \
} while (0)
/*
* Reinitialize completions in CQ, once Rx is taken down
*/
static void
bnad_cq_cleanup(struct bnad *bnad, struct bna_ccb *ccb)
{
struct bna_cq_entry *cmpl;
int i;
for (i = 0; i < ccb->q_depth; i++) {
cmpl = &((struct bna_cq_entry *)ccb->sw_q)[i];
cmpl->valid = 0;
}
}
/* Tx Datapath functions */
/* Caller should ensure that the entry at unmap_q[index] is valid */
static u32
bnad_tx_buff_unmap(struct bnad *bnad,
struct bnad_tx_unmap *unmap_q,
u32 q_depth, u32 index)
{
struct bnad_tx_unmap *unmap;
struct sk_buff *skb;
int vector, nvecs;
unmap = &unmap_q[index];
nvecs = unmap->nvecs;
skb = unmap->skb;
unmap->skb = NULL;
unmap->nvecs = 0;
dma_unmap_single(&bnad->pcidev->dev,
dma_unmap_addr(&unmap->vectors[0], dma_addr),
skb_headlen(skb), DMA_TO_DEVICE);
dma_unmap_addr_set(&unmap->vectors[0], dma_addr, 0);
nvecs--;
vector = 0;
while (nvecs) {
vector++;
if (vector == BFI_TX_MAX_VECTORS_PER_WI) {
vector = 0;
BNA_QE_INDX_INC(index, q_depth);
unmap = &unmap_q[index];
}
dma_unmap_page(&bnad->pcidev->dev,
dma_unmap_addr(&unmap->vectors[vector], dma_addr),
dma_unmap_len(&unmap->vectors[vector], dma_len),
DMA_TO_DEVICE);
dma_unmap_addr_set(&unmap->vectors[vector], dma_addr, 0);
nvecs--;
}
BNA_QE_INDX_INC(index, q_depth);
return index;
}
/*
* Frees all pending Tx Bufs
* At this point no activity is expected on the Q,
* so DMA unmap & freeing is fine.
*/
static void
bnad_txq_cleanup(struct bnad *bnad, struct bna_tcb *tcb)
{
struct bnad_tx_unmap *unmap_q = tcb->unmap_q;
struct sk_buff *skb;
int i;
for (i = 0; i < tcb->q_depth; i++) {
skb = unmap_q[i].skb;
if (!skb)
continue;
bnad_tx_buff_unmap(bnad, unmap_q, tcb->q_depth, i);
dev_kfree_skb_any(skb);
}
}
/*
* bnad_txcmpl_process : Frees the Tx bufs on Tx completion
* Can be called in a) Interrupt context
* b) Sending context
*/
static u32
bnad_txcmpl_process(struct bnad *bnad, struct bna_tcb *tcb)
{
u32 sent_packets = 0, sent_bytes = 0;
u32 wis, unmap_wis, hw_cons, cons, q_depth;
struct bnad_tx_unmap *unmap_q = tcb->unmap_q;
struct bnad_tx_unmap *unmap;
struct sk_buff *skb;
/* Just return if TX is stopped */
if (!test_bit(BNAD_TXQ_TX_STARTED, &tcb->flags))
return 0;
hw_cons = *(tcb->hw_consumer_index);
rmb();
cons = tcb->consumer_index;
q_depth = tcb->q_depth;
wis = BNA_Q_INDEX_CHANGE(cons, hw_cons, q_depth);
BUG_ON(!(wis <= BNA_QE_IN_USE_CNT(tcb, tcb->q_depth)));
while (wis) {
unmap = &unmap_q[cons];
skb = unmap->skb;
sent_packets++;
sent_bytes += skb->len;
unmap_wis = BNA_TXQ_WI_NEEDED(unmap->nvecs);
wis -= unmap_wis;
cons = bnad_tx_buff_unmap(bnad, unmap_q, q_depth, cons);
dev_kfree_skb_any(skb);
}
/* Update consumer pointers. */
tcb->consumer_index = hw_cons;
tcb->txq->tx_packets += sent_packets;
tcb->txq->tx_bytes += sent_bytes;
return sent_packets;
}
static u32
bnad_tx_complete(struct bnad *bnad, struct bna_tcb *tcb)
{
struct net_device *netdev = bnad->netdev;
u32 sent = 0;
if (test_and_set_bit(BNAD_TXQ_FREE_SENT, &tcb->flags))
return 0;
sent = bnad_txcmpl_process(bnad, tcb);
if (sent) {
if (netif_queue_stopped(netdev) &&
netif_carrier_ok(netdev) &&
BNA_QE_FREE_CNT(tcb, tcb->q_depth) >=
BNAD_NETIF_WAKE_THRESHOLD) {
if (test_bit(BNAD_TXQ_TX_STARTED, &tcb->flags)) {
netif_wake_queue(netdev);
BNAD_UPDATE_CTR(bnad, netif_queue_wakeup);
}
}
}
if (likely(test_bit(BNAD_TXQ_TX_STARTED, &tcb->flags)))
bna_ib_ack(tcb->i_dbell, sent);
smp_mb__before_atomic();
clear_bit(BNAD_TXQ_FREE_SENT, &tcb->flags);
return sent;
}
/* MSIX Tx Completion Handler */
static irqreturn_t
bnad_msix_tx(int irq, void *data)
{
struct bna_tcb *tcb = (struct bna_tcb *)data;
struct bnad *bnad = tcb->bnad;
bnad_tx_complete(bnad, tcb);
return IRQ_HANDLED;
}
static inline void
bnad_rxq_alloc_uninit(struct bnad *bnad, struct bna_rcb *rcb)
{
struct bnad_rx_unmap_q *unmap_q = rcb->unmap_q;
unmap_q->reuse_pi = -1;
unmap_q->alloc_order = -1;
unmap_q->map_size = 0;
unmap_q->type = BNAD_RXBUF_NONE;
}
/* Default is page-based allocation. Multi-buffer support - TBD */
static int
bnad_rxq_alloc_init(struct bnad *bnad, struct bna_rcb *rcb)
{
struct bnad_rx_unmap_q *unmap_q = rcb->unmap_q;
int order;
bnad_rxq_alloc_uninit(bnad, rcb);
order = get_order(rcb->rxq->buffer_size);
unmap_q->type = BNAD_RXBUF_PAGE;
if (bna_is_small_rxq(rcb->id)) {
unmap_q->alloc_order = 0;
unmap_q->map_size = rcb->rxq->buffer_size;
} else {
if (rcb->rxq->multi_buffer) {
unmap_q->alloc_order = 0;
unmap_q->map_size = rcb->rxq->buffer_size;
unmap_q->type = BNAD_RXBUF_MULTI_BUFF;
} else {
unmap_q->alloc_order = order;
unmap_q->map_size =
(rcb->rxq->buffer_size > 2048) ?
PAGE_SIZE << order : 2048;
}
}
BUG_ON((PAGE_SIZE << order) % unmap_q->map_size);
return 0;
}
static inline void
bnad_rxq_cleanup_page(struct bnad *bnad, struct bnad_rx_unmap *unmap)
{
if (!unmap->page)
return;
dma_unmap_page(&bnad->pcidev->dev,
dma_unmap_addr(&unmap->vector, dma_addr),
unmap->vector.len, DMA_FROM_DEVICE);
put_page(unmap->page);
unmap->page = NULL;
dma_unmap_addr_set(&unmap->vector, dma_addr, 0);
unmap->vector.len = 0;
}
static inline void
bnad_rxq_cleanup_skb(struct bnad *bnad, struct bnad_rx_unmap *unmap)
{
if (!unmap->skb)
return;
dma_unmap_single(&bnad->pcidev->dev,
dma_unmap_addr(&unmap->vector, dma_addr),
unmap->vector.len, DMA_FROM_DEVICE);
dev_kfree_skb_any(unmap->skb);
unmap->skb = NULL;
dma_unmap_addr_set(&unmap->vector, dma_addr, 0);
unmap->vector.len = 0;
}
static void
bnad_rxq_cleanup(struct bnad *bnad, struct bna_rcb *rcb)
{
struct bnad_rx_unmap_q *unmap_q = rcb->unmap_q;
int i;
for (i = 0; i < rcb->q_depth; i++) {
struct bnad_rx_unmap *unmap = &unmap_q->unmap[i];
if (BNAD_RXBUF_IS_SK_BUFF(unmap_q->type))
bnad_rxq_cleanup_skb(bnad, unmap);
else
bnad_rxq_cleanup_page(bnad, unmap);
}
bnad_rxq_alloc_uninit(bnad, rcb);
}
static u32
bnad_rxq_refill_page(struct bnad *bnad, struct bna_rcb *rcb, u32 nalloc)
{
u32 alloced, prod, q_depth;
struct bnad_rx_unmap_q *unmap_q = rcb->unmap_q;
struct bnad_rx_unmap *unmap, *prev;
struct bna_rxq_entry *rxent;
struct page *page;
u32 page_offset, alloc_size;
dma_addr_t dma_addr;
prod = rcb->producer_index;
q_depth = rcb->q_depth;
alloc_size = PAGE_SIZE << unmap_q->alloc_order;
alloced = 0;
while (nalloc--) {
unmap = &unmap_q->unmap[prod];
if (unmap_q->reuse_pi < 0) {
page = alloc_pages(GFP_ATOMIC | __GFP_COMP,
unmap_q->alloc_order);
page_offset = 0;
} else {
prev = &unmap_q->unmap[unmap_q->reuse_pi];
page = prev->page;
page_offset = prev->page_offset + unmap_q->map_size;
get_page(page);
}
if (unlikely(!page)) {
BNAD_UPDATE_CTR(bnad, rxbuf_alloc_failed);
rcb->rxq->rxbuf_alloc_failed++;
goto finishing;
}
dma_addr = dma_map_page(&bnad->pcidev->dev, page, page_offset,
unmap_q->map_size, DMA_FROM_DEVICE);
if (dma_mapping_error(&bnad->pcidev->dev, dma_addr)) {
put_page(page);
BNAD_UPDATE_CTR(bnad, rxbuf_map_failed);
rcb->rxq->rxbuf_map_failed++;
goto finishing;
}
unmap->page = page;
unmap->page_offset = page_offset;
dma_unmap_addr_set(&unmap->vector, dma_addr, dma_addr);
unmap->vector.len = unmap_q->map_size;
page_offset += unmap_q->map_size;
if (page_offset < alloc_size)
unmap_q->reuse_pi = prod;
else
unmap_q->reuse_pi = -1;
rxent = &((struct bna_rxq_entry *)rcb->sw_q)[prod];
BNA_SET_DMA_ADDR(dma_addr, &rxent->host_addr);
BNA_QE_INDX_INC(prod, q_depth);
alloced++;
}
finishing:
if (likely(alloced)) {
rcb->producer_index = prod;
smp_mb();
if (likely(test_bit(BNAD_RXQ_POST_OK, &rcb->flags)))
bna_rxq_prod_indx_doorbell(rcb);
}
return alloced;
}
static u32
bnad_rxq_refill_skb(struct bnad *bnad, struct bna_rcb *rcb, u32 nalloc)
{
u32 alloced, prod, q_depth, buff_sz;
struct bnad_rx_unmap_q *unmap_q = rcb->unmap_q;
struct bnad_rx_unmap *unmap;
struct bna_rxq_entry *rxent;
struct sk_buff *skb;
dma_addr_t dma_addr;
buff_sz = rcb->rxq->buffer_size;
prod = rcb->producer_index;
q_depth = rcb->q_depth;
alloced = 0;
while (nalloc--) {
unmap = &unmap_q->unmap[prod];
skb = netdev_alloc_skb_ip_align(bnad->netdev, buff_sz);
if (unlikely(!skb)) {
BNAD_UPDATE_CTR(bnad, rxbuf_alloc_failed);
rcb->rxq->rxbuf_alloc_failed++;
goto finishing;
}
dma_addr = dma_map_single(&bnad->pcidev->dev, skb->data,
buff_sz, DMA_FROM_DEVICE);
if (dma_mapping_error(&bnad->pcidev->dev, dma_addr)) {
dev_kfree_skb_any(skb);
BNAD_UPDATE_CTR(bnad, rxbuf_map_failed);
rcb->rxq->rxbuf_map_failed++;
goto finishing;
}
unmap->skb = skb;
dma_unmap_addr_set(&unmap->vector, dma_addr, dma_addr);
unmap->vector.len = buff_sz;
rxent = &((struct bna_rxq_entry *)rcb->sw_q)[prod];
BNA_SET_DMA_ADDR(dma_addr, &rxent->host_addr);
BNA_QE_INDX_INC(prod, q_depth);
alloced++;
}
finishing:
if (likely(alloced)) {
rcb->producer_index = prod;
smp_mb();
if (likely(test_bit(BNAD_RXQ_POST_OK, &rcb->flags)))
bna_rxq_prod_indx_doorbell(rcb);
}
return alloced;
}
static inline void
bnad_rxq_post(struct bnad *bnad, struct bna_rcb *rcb)
{
struct bnad_rx_unmap_q *unmap_q = rcb->unmap_q;
u32 to_alloc;
to_alloc = BNA_QE_FREE_CNT(rcb, rcb->q_depth);
if (!(to_alloc >> BNAD_RXQ_REFILL_THRESHOLD_SHIFT))
return;
if (BNAD_RXBUF_IS_SK_BUFF(unmap_q->type))
bnad_rxq_refill_skb(bnad, rcb, to_alloc);
else
bnad_rxq_refill_page(bnad, rcb, to_alloc);
}
#define flags_cksum_prot_mask (BNA_CQ_EF_IPV4 | BNA_CQ_EF_L3_CKSUM_OK | \
BNA_CQ_EF_IPV6 | \
BNA_CQ_EF_TCP | BNA_CQ_EF_UDP | \
BNA_CQ_EF_L4_CKSUM_OK)
#define flags_tcp4 (BNA_CQ_EF_IPV4 | BNA_CQ_EF_L3_CKSUM_OK | \
BNA_CQ_EF_TCP | BNA_CQ_EF_L4_CKSUM_OK)
#define flags_tcp6 (BNA_CQ_EF_IPV6 | \
BNA_CQ_EF_TCP | BNA_CQ_EF_L4_CKSUM_OK)
#define flags_udp4 (BNA_CQ_EF_IPV4 | BNA_CQ_EF_L3_CKSUM_OK | \
BNA_CQ_EF_UDP | BNA_CQ_EF_L4_CKSUM_OK)
#define flags_udp6 (BNA_CQ_EF_IPV6 | \
BNA_CQ_EF_UDP | BNA_CQ_EF_L4_CKSUM_OK)
static void
bnad_cq_drop_packet(struct bnad *bnad, struct bna_rcb *rcb,
u32 sop_ci, u32 nvecs)
{
struct bnad_rx_unmap_q *unmap_q;
struct bnad_rx_unmap *unmap;
u32 ci, vec;
unmap_q = rcb->unmap_q;
for (vec = 0, ci = sop_ci; vec < nvecs; vec++) {
unmap = &unmap_q->unmap[ci];
BNA_QE_INDX_INC(ci, rcb->q_depth);
if (BNAD_RXBUF_IS_SK_BUFF(unmap_q->type))
bnad_rxq_cleanup_skb(bnad, unmap);
else
bnad_rxq_cleanup_page(bnad, unmap);
}
}
static void
bnad_cq_setup_skb_frags(struct bna_ccb *ccb, struct sk_buff *skb, u32 nvecs)
{
struct bna_rcb *rcb;
struct bnad *bnad;
struct bnad_rx_unmap_q *unmap_q;
struct bna_cq_entry *cq, *cmpl;
u32 ci, pi, totlen = 0;
cq = ccb->sw_q;
pi = ccb->producer_index;
cmpl = &cq[pi];
rcb = bna_is_small_rxq(cmpl->rxq_id) ? ccb->rcb[1] : ccb->rcb[0];
unmap_q = rcb->unmap_q;
bnad = rcb->bnad;
ci = rcb->consumer_index;
/* prefetch header */
prefetch(page_address(unmap_q->unmap[ci].page) +
unmap_q->unmap[ci].page_offset);
while (nvecs--) {
struct bnad_rx_unmap *unmap;
u32 len;
unmap = &unmap_q->unmap[ci];
BNA_QE_INDX_INC(ci, rcb->q_depth);
dma_unmap_page(&bnad->pcidev->dev,
dma_unmap_addr(&unmap->vector, dma_addr),
unmap->vector.len, DMA_FROM_DEVICE);
len = ntohs(cmpl->length);
skb->truesize += unmap->vector.len;
totlen += len;
skb_fill_page_desc(skb, skb_shinfo(skb)->nr_frags,
unmap->page, unmap->page_offset, len);
unmap->page = NULL;
unmap->vector.len = 0;
BNA_QE_INDX_INC(pi, ccb->q_depth);
cmpl = &cq[pi];
}
skb->len += totlen;
skb->data_len += totlen;
}
static inline void
bnad_cq_setup_skb(struct bnad *bnad, struct sk_buff *skb,
struct bnad_rx_unmap *unmap, u32 len)
{
prefetch(skb->data);
dma_unmap_single(&bnad->pcidev->dev,
dma_unmap_addr(&unmap->vector, dma_addr),
unmap->vector.len, DMA_FROM_DEVICE);
skb_put(skb, len);
skb->protocol = eth_type_trans(skb, bnad->netdev);
unmap->skb = NULL;
unmap->vector.len = 0;
}
static u32
bnad_cq_process(struct bnad *bnad, struct bna_ccb *ccb, int budget)
{
struct bna_cq_entry *cq, *cmpl, *next_cmpl;
struct bna_rcb *rcb = NULL;
struct bnad_rx_unmap_q *unmap_q;
struct bnad_rx_unmap *unmap = NULL;
struct sk_buff *skb = NULL;
struct bna_pkt_rate *pkt_rt = &ccb->pkt_rate;
struct bnad_rx_ctrl *rx_ctrl = ccb->ctrl;
u32 packets = 0, len = 0, totlen = 0;
u32 pi, vec, sop_ci = 0, nvecs = 0;
u32 flags, masked_flags;
prefetch(bnad->netdev);
cq = ccb->sw_q;
while (packets < budget) {
cmpl = &cq[ccb->producer_index];
if (!cmpl->valid)
break;
/* The 'valid' field is set by the adapter, only after writing
* the other fields of completion entry. Hence, do not load
* other fields of completion entry *before* the 'valid' is
* loaded. Adding the rmb() here prevents the compiler and/or
* CPU from reordering the reads which would potentially result
* in reading stale values in completion entry.
*/
rmb();
BNA_UPDATE_PKT_CNT(pkt_rt, ntohs(cmpl->length));
if (bna_is_small_rxq(cmpl->rxq_id))
rcb = ccb->rcb[1];
else
rcb = ccb->rcb[0];
unmap_q = rcb->unmap_q;
/* start of packet ci */
sop_ci = rcb->consumer_index;
if (BNAD_RXBUF_IS_SK_BUFF(unmap_q->type)) {
unmap = &unmap_q->unmap[sop_ci];
skb = unmap->skb;
} else {
skb = napi_get_frags(&rx_ctrl->napi);
if (unlikely(!skb))
break;
}
prefetch(skb);
flags = ntohl(cmpl->flags);
len = ntohs(cmpl->length);
totlen = len;
nvecs = 1;
/* Check all the completions for this frame.
* busy-wait doesn't help much, break here.
*/
if (BNAD_RXBUF_IS_MULTI_BUFF(unmap_q->type) &&
(flags & BNA_CQ_EF_EOP) == 0) {
pi = ccb->producer_index;
do {
BNA_QE_INDX_INC(pi, ccb->q_depth);
next_cmpl = &cq[pi];
if (!next_cmpl->valid)
break;
/* The 'valid' field is set by the adapter, only
* after writing the other fields of completion
* entry. Hence, do not load other fields of
* completion entry *before* the 'valid' is
* loaded. Adding the rmb() here prevents the
* compiler and/or CPU from reordering the reads
* which would potentially result in reading
* stale values in completion entry.
*/
rmb();
len = ntohs(next_cmpl->length);
flags = ntohl(next_cmpl->flags);
nvecs++;
totlen += len;
} while ((flags & BNA_CQ_EF_EOP) == 0);
if (!next_cmpl->valid)
break;
}
packets++;
/* TODO: BNA_CQ_EF_LOCAL ? */
if (unlikely(flags & (BNA_CQ_EF_MAC_ERROR |
BNA_CQ_EF_FCS_ERROR |
BNA_CQ_EF_TOO_LONG))) {
bnad_cq_drop_packet(bnad, rcb, sop_ci, nvecs);
rcb->rxq->rx_packets_with_error++;
goto next;
}
if (BNAD_RXBUF_IS_SK_BUFF(unmap_q->type))
bnad_cq_setup_skb(bnad, skb, unmap, len);
else
bnad_cq_setup_skb_frags(ccb, skb, nvecs);
rcb->rxq->rx_packets++;
rcb->rxq->rx_bytes += totlen;
ccb->bytes_per_intr += totlen;
masked_flags = flags & flags_cksum_prot_mask;
if (likely
((bnad->netdev->features & NETIF_F_RXCSUM) &&
((masked_flags == flags_tcp4) ||
(masked_flags == flags_udp4) ||
(masked_flags == flags_tcp6) ||
(masked_flags == flags_udp6))))
skb->ip_summed = CHECKSUM_UNNECESSARY;
else
skb_checksum_none_assert(skb);
if ((flags & BNA_CQ_EF_VLAN) &&
(bnad->netdev->features & NETIF_F_HW_VLAN_CTAG_RX))
__vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), ntohs(cmpl->vlan_tag));
if (BNAD_RXBUF_IS_SK_BUFF(unmap_q->type))
netif_receive_skb(skb);
else
napi_gro_frags(&rx_ctrl->napi);
next:
BNA_QE_INDX_ADD(rcb->consumer_index, nvecs, rcb->q_depth);
for (vec = 0; vec < nvecs; vec++) {
cmpl = &cq[ccb->producer_index];
cmpl->valid = 0;
BNA_QE_INDX_INC(ccb->producer_index, ccb->q_depth);
}
}
napi_gro_flush(&rx_ctrl->napi, false);
if (likely(test_bit(BNAD_RXQ_STARTED, &ccb->rcb[0]->flags)))
bna_ib_ack_disable_irq(ccb->i_dbell, packets);
bnad_rxq_post(bnad, ccb->rcb[0]);
if (ccb->rcb[1])
bnad_rxq_post(bnad, ccb->rcb[1]);
return packets;
}
static void
bnad_netif_rx_schedule_poll(struct bnad *bnad, struct bna_ccb *ccb)
{
struct bnad_rx_ctrl *rx_ctrl = (struct bnad_rx_ctrl *)(ccb->ctrl);
struct napi_struct *napi = &rx_ctrl->napi;
if (likely(napi_schedule_prep(napi))) {
__napi_schedule(napi);
rx_ctrl->rx_schedule++;
}
}
/* MSIX Rx Path Handler */
static irqreturn_t
bnad_msix_rx(int irq, void *data)
{
struct bna_ccb *ccb = (struct bna_ccb *)data;
if (ccb) {
((struct bnad_rx_ctrl *)ccb->ctrl)->rx_intr_ctr++;
bnad_netif_rx_schedule_poll(ccb->bnad, ccb);
}
return IRQ_HANDLED;
}
/* Interrupt handlers */
/* Mbox Interrupt Handlers */
static irqreturn_t
bnad_msix_mbox_handler(int irq, void *data)
{
u32 intr_status;
unsigned long flags;
struct bnad *bnad = (struct bnad *)data;
spin_lock_irqsave(&bnad->bna_lock, flags);
if (unlikely(test_bit(BNAD_RF_MBOX_IRQ_DISABLED, &bnad->run_flags))) {
spin_unlock_irqrestore(&bnad->bna_lock, flags);
return IRQ_HANDLED;
}
bna_intr_status_get(&bnad->bna, intr_status);
if (BNA_IS_MBOX_ERR_INTR(&bnad->bna, intr_status))
bna_mbox_handler(&bnad->bna, intr_status);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
return IRQ_HANDLED;
}
static irqreturn_t
bnad_isr(int irq, void *data)
{
int i, j;
u32 intr_status;
unsigned long flags;
struct bnad *bnad = (struct bnad *)data;
struct bnad_rx_info *rx_info;
struct bnad_rx_ctrl *rx_ctrl;
struct bna_tcb *tcb = NULL;
spin_lock_irqsave(&bnad->bna_lock, flags);
if (unlikely(test_bit(BNAD_RF_MBOX_IRQ_DISABLED, &bnad->run_flags))) {
spin_unlock_irqrestore(&bnad->bna_lock, flags);
return IRQ_NONE;
}
bna_intr_status_get(&bnad->bna, intr_status);
if (unlikely(!intr_status)) {
spin_unlock_irqrestore(&bnad->bna_lock, flags);
return IRQ_NONE;
}
if (BNA_IS_MBOX_ERR_INTR(&bnad->bna, intr_status))
bna_mbox_handler(&bnad->bna, intr_status);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
if (!BNA_IS_INTX_DATA_INTR(intr_status))
return IRQ_HANDLED;
/* Process data interrupts */
/* Tx processing */
for (i = 0; i < bnad->num_tx; i++) {
for (j = 0; j < bnad->num_txq_per_tx; j++) {
tcb = bnad->tx_info[i].tcb[j];
if (tcb && test_bit(BNAD_TXQ_TX_STARTED, &tcb->flags))
bnad_tx_complete(bnad, bnad->tx_info[i].tcb[j]);
}
}
/* Rx processing */
for (i = 0; i < bnad->num_rx; i++) {
rx_info = &bnad->rx_info[i];
if (!rx_info->rx)
continue;
for (j = 0; j < bnad->num_rxp_per_rx; j++) {
rx_ctrl = &rx_info->rx_ctrl[j];
if (rx_ctrl->ccb)
bnad_netif_rx_schedule_poll(bnad,
rx_ctrl->ccb);
}
}
return IRQ_HANDLED;
}
/*
* Called in interrupt / callback context
* with bna_lock held, so cfg_flags access is OK
*/
static void
bnad_enable_mbox_irq(struct bnad *bnad)
{
clear_bit(BNAD_RF_MBOX_IRQ_DISABLED, &bnad->run_flags);
BNAD_UPDATE_CTR(bnad, mbox_intr_enabled);
}
/*
* Called with bnad->bna_lock held b'cos of
* bnad->cfg_flags access.
*/
static void
bnad_disable_mbox_irq(struct bnad *bnad)
{
set_bit(BNAD_RF_MBOX_IRQ_DISABLED, &bnad->run_flags);
BNAD_UPDATE_CTR(bnad, mbox_intr_disabled);
}
static void
bnad_set_netdev_perm_addr(struct bnad *bnad)
{
struct net_device *netdev = bnad->netdev;
ether_addr_copy(netdev->perm_addr, bnad->perm_addr);
if (is_zero_ether_addr(netdev->dev_addr))
eth_hw_addr_set(netdev, bnad->perm_addr);
}
/* Control Path Handlers */
/* Callbacks */
void
bnad_cb_mbox_intr_enable(struct bnad *bnad)
{
bnad_enable_mbox_irq(bnad);
}
void
bnad_cb_mbox_intr_disable(struct bnad *bnad)
{
bnad_disable_mbox_irq(bnad);
}
void
bnad_cb_ioceth_ready(struct bnad *bnad)
{
bnad->bnad_completions.ioc_comp_status = BNA_CB_SUCCESS;
complete(&bnad->bnad_completions.ioc_comp);
}
void
bnad_cb_ioceth_failed(struct bnad *bnad)
{
bnad->bnad_completions.ioc_comp_status = BNA_CB_FAIL;
complete(&bnad->bnad_completions.ioc_comp);
}
void
bnad_cb_ioceth_disabled(struct bnad *bnad)
{
bnad->bnad_completions.ioc_comp_status = BNA_CB_SUCCESS;
complete(&bnad->bnad_completions.ioc_comp);
}
static void
bnad_cb_enet_disabled(void *arg)
{
struct bnad *bnad = (struct bnad *)arg;
netif_carrier_off(bnad->netdev);
complete(&bnad->bnad_completions.enet_comp);
}
void
bnad_cb_ethport_link_status(struct bnad *bnad,
enum bna_link_status link_status)
{
bool link_up = false;
link_up = (link_status == BNA_LINK_UP) || (link_status == BNA_CEE_UP);
if (link_status == BNA_CEE_UP) {
if (!test_bit(BNAD_RF_CEE_RUNNING, &bnad->run_flags))
BNAD_UPDATE_CTR(bnad, cee_toggle);
set_bit(BNAD_RF_CEE_RUNNING, &bnad->run_flags);
} else {
if (test_bit(BNAD_RF_CEE_RUNNING, &bnad->run_flags))
BNAD_UPDATE_CTR(bnad, cee_toggle);
clear_bit(BNAD_RF_CEE_RUNNING, &bnad->run_flags);
}
if (link_up) {
if (!netif_carrier_ok(bnad->netdev)) {
uint tx_id, tcb_id;
netdev_info(bnad->netdev, "link up\n");
netif_carrier_on(bnad->netdev);
BNAD_UPDATE_CTR(bnad, link_toggle);
for (tx_id = 0; tx_id < bnad->num_tx; tx_id++) {
for (tcb_id = 0; tcb_id < bnad->num_txq_per_tx;
tcb_id++) {
struct bna_tcb *tcb =
bnad->tx_info[tx_id].tcb[tcb_id];
u32 txq_id;
if (!tcb)
continue;
txq_id = tcb->id;
if (test_bit(BNAD_TXQ_TX_STARTED,
&tcb->flags)) {
/*
* Force an immediate
* Transmit Schedule */
netif_wake_subqueue(
bnad->netdev,
txq_id);
BNAD_UPDATE_CTR(bnad,
netif_queue_wakeup);
} else {
netif_stop_subqueue(
bnad->netdev,
txq_id);
BNAD_UPDATE_CTR(bnad,
netif_queue_stop);
}
}
}
}
} else {
if (netif_carrier_ok(bnad->netdev)) {
netdev_info(bnad->netdev, "link down\n");
netif_carrier_off(bnad->netdev);
BNAD_UPDATE_CTR(bnad, link_toggle);
}
}
}
static void
bnad_cb_tx_disabled(void *arg, struct bna_tx *tx)
{
struct bnad *bnad = (struct bnad *)arg;
complete(&bnad->bnad_completions.tx_comp);
}
static void
bnad_cb_tcb_setup(struct bnad *bnad, struct bna_tcb *tcb)
{
struct bnad_tx_info *tx_info =
(struct bnad_tx_info *)tcb->txq->tx->priv;
tcb->priv = tcb;
tx_info->tcb[tcb->id] = tcb;
}
static void
bnad_cb_tcb_destroy(struct bnad *bnad, struct bna_tcb *tcb)
{
struct bnad_tx_info *tx_info =
(struct bnad_tx_info *)tcb->txq->tx->priv;
tx_info->tcb[tcb->id] = NULL;
tcb->priv = NULL;
}
static void
bnad_cb_ccb_setup(struct bnad *bnad, struct bna_ccb *ccb)
{
struct bnad_rx_info *rx_info =
(struct bnad_rx_info *)ccb->cq->rx->priv;
rx_info->rx_ctrl[ccb->id].ccb = ccb;
ccb->ctrl = &rx_info->rx_ctrl[ccb->id];
}
static void
bnad_cb_ccb_destroy(struct bnad *bnad, struct bna_ccb *ccb)
{
struct bnad_rx_info *rx_info =
(struct bnad_rx_info *)ccb->cq->rx->priv;
rx_info->rx_ctrl[ccb->id].ccb = NULL;
}
static void
bnad_cb_tx_stall(struct bnad *bnad, struct bna_tx *tx)
{
struct bnad_tx_info *tx_info = tx->priv;
struct bna_tcb *tcb;
u32 txq_id;
int i;
for (i = 0; i < BNAD_MAX_TXQ_PER_TX; i++) {
tcb = tx_info->tcb[i];
if (!tcb)
continue;
txq_id = tcb->id;
clear_bit(BNAD_TXQ_TX_STARTED, &tcb->flags);
netif_stop_subqueue(bnad->netdev, txq_id);
}
}
static void
bnad_cb_tx_resume(struct bnad *bnad, struct bna_tx *tx)
{
struct bnad_tx_info *tx_info = tx->priv;
struct bna_tcb *tcb;
u32 txq_id;
int i;
for (i = 0; i < BNAD_MAX_TXQ_PER_TX; i++) {
tcb = tx_info->tcb[i];
if (!tcb)
continue;
txq_id = tcb->id;
BUG_ON(test_bit(BNAD_TXQ_TX_STARTED, &tcb->flags));
set_bit(BNAD_TXQ_TX_STARTED, &tcb->flags);
BUG_ON(*(tcb->hw_consumer_index) != 0);
if (netif_carrier_ok(bnad->netdev)) {
netif_wake_subqueue(bnad->netdev, txq_id);
BNAD_UPDATE_CTR(bnad, netif_queue_wakeup);
}
}
/*
* Workaround for first ioceth enable failure & we
* get a 0 MAC address. We try to get the MAC address
* again here.
*/
if (is_zero_ether_addr(bnad->perm_addr)) {
bna_enet_perm_mac_get(&bnad->bna.enet, bnad->perm_addr);
bnad_set_netdev_perm_addr(bnad);
}
}
/*
* Free all TxQs buffers and then notify TX_E_CLEANUP_DONE to Tx fsm.
*/
static void
bnad_tx_cleanup(struct delayed_work *work)
{
struct bnad_tx_info *tx_info =
container_of(work, struct bnad_tx_info, tx_cleanup_work);
struct bnad *bnad = NULL;
struct bna_tcb *tcb;
unsigned long flags;
u32 i, pending = 0;
for (i = 0; i < BNAD_MAX_TXQ_PER_TX; i++) {
tcb = tx_info->tcb[i];
if (!tcb)
continue;
bnad = tcb->bnad;
if (test_and_set_bit(BNAD_TXQ_FREE_SENT, &tcb->flags)) {
pending++;
continue;
}
bnad_txq_cleanup(bnad, tcb);
smp_mb__before_atomic();
clear_bit(BNAD_TXQ_FREE_SENT, &tcb->flags);
}
if (pending) {
queue_delayed_work(bnad->work_q, &tx_info->tx_cleanup_work,
msecs_to_jiffies(1));
return;
}
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_tx_cleanup_complete(tx_info->tx);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
}
static void
bnad_cb_tx_cleanup(struct bnad *bnad, struct bna_tx *tx)
{
struct bnad_tx_info *tx_info = tx->priv;
struct bna_tcb *tcb;
int i;
for (i = 0; i < BNAD_MAX_TXQ_PER_TX; i++) {
tcb = tx_info->tcb[i];
if (!tcb)
continue;
}
queue_delayed_work(bnad->work_q, &tx_info->tx_cleanup_work, 0);
}
static void
bnad_cb_rx_stall(struct bnad *bnad, struct bna_rx *rx)
{
struct bnad_rx_info *rx_info = rx->priv;
struct bna_ccb *ccb;
struct bnad_rx_ctrl *rx_ctrl;
int i;
for (i = 0; i < BNAD_MAX_RXP_PER_RX; i++) {
rx_ctrl = &rx_info->rx_ctrl[i];
ccb = rx_ctrl->ccb;
if (!ccb)
continue;
clear_bit(BNAD_RXQ_POST_OK, &ccb->rcb[0]->flags);
if (ccb->rcb[1])
clear_bit(BNAD_RXQ_POST_OK, &ccb->rcb[1]->flags);
}
}
/*
* Free all RxQs buffers and then notify RX_E_CLEANUP_DONE to Rx fsm.
*/
static void
bnad_rx_cleanup(void *work)
{
struct bnad_rx_info *rx_info =
container_of(work, struct bnad_rx_info, rx_cleanup_work);
struct bnad_rx_ctrl *rx_ctrl;
struct bnad *bnad = NULL;
unsigned long flags;
u32 i;
for (i = 0; i < BNAD_MAX_RXP_PER_RX; i++) {
rx_ctrl = &rx_info->rx_ctrl[i];
if (!rx_ctrl->ccb)
continue;
bnad = rx_ctrl->ccb->bnad;
/*
* Wait till the poll handler has exited
* and nothing can be scheduled anymore
*/
napi_disable(&rx_ctrl->napi);
bnad_cq_cleanup(bnad, rx_ctrl->ccb);
bnad_rxq_cleanup(bnad, rx_ctrl->ccb->rcb[0]);
if (rx_ctrl->ccb->rcb[1])
bnad_rxq_cleanup(bnad, rx_ctrl->ccb->rcb[1]);
}
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_rx_cleanup_complete(rx_info->rx);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
}
static void
bnad_cb_rx_cleanup(struct bnad *bnad, struct bna_rx *rx)
{
struct bnad_rx_info *rx_info = rx->priv;
struct bna_ccb *ccb;
struct bnad_rx_ctrl *rx_ctrl;
int i;
for (i = 0; i < BNAD_MAX_RXP_PER_RX; i++) {
rx_ctrl = &rx_info->rx_ctrl[i];
ccb = rx_ctrl->ccb;
if (!ccb)
continue;
clear_bit(BNAD_RXQ_STARTED, &ccb->rcb[0]->flags);
if (ccb->rcb[1])
clear_bit(BNAD_RXQ_STARTED, &ccb->rcb[1]->flags);
}
queue_work(bnad->work_q, &rx_info->rx_cleanup_work);
}
static void
bnad_cb_rx_post(struct bnad *bnad, struct bna_rx *rx)
{
struct bnad_rx_info *rx_info = rx->priv;
struct bna_ccb *ccb;
struct bna_rcb *rcb;
struct bnad_rx_ctrl *rx_ctrl;
int i, j;
for (i = 0; i < BNAD_MAX_RXP_PER_RX; i++) {
rx_ctrl = &rx_info->rx_ctrl[i];
ccb = rx_ctrl->ccb;
if (!ccb)
continue;
napi_enable(&rx_ctrl->napi);
for (j = 0; j < BNAD_MAX_RXQ_PER_RXP; j++) {
rcb = ccb->rcb[j];
if (!rcb)
continue;
bnad_rxq_alloc_init(bnad, rcb);
set_bit(BNAD_RXQ_STARTED, &rcb->flags);
set_bit(BNAD_RXQ_POST_OK, &rcb->flags);
bnad_rxq_post(bnad, rcb);
}
}
}
static void
bnad_cb_rx_disabled(void *arg, struct bna_rx *rx)
{
struct bnad *bnad = (struct bnad *)arg;
complete(&bnad->bnad_completions.rx_comp);
}
static void
bnad_cb_rx_mcast_add(struct bnad *bnad, struct bna_rx *rx)
{
bnad->bnad_completions.mcast_comp_status = BNA_CB_SUCCESS;
complete(&bnad->bnad_completions.mcast_comp);
}
void
bnad_cb_stats_get(struct bnad *bnad, enum bna_cb_status status,
struct bna_stats *stats)
{
if (status == BNA_CB_SUCCESS)
BNAD_UPDATE_CTR(bnad, hw_stats_updates);
if (!netif_running(bnad->netdev) ||
!test_bit(BNAD_RF_STATS_TIMER_RUNNING, &bnad->run_flags))
return;
mod_timer(&bnad->stats_timer,
jiffies + msecs_to_jiffies(BNAD_STATS_TIMER_FREQ));
}
static void
bnad_cb_enet_mtu_set(struct bnad *bnad)
{
bnad->bnad_completions.mtu_comp_status = BNA_CB_SUCCESS;
complete(&bnad->bnad_completions.mtu_comp);
}
void
bnad_cb_completion(void *arg, enum bfa_status status)
{
struct bnad_iocmd_comp *iocmd_comp =
(struct bnad_iocmd_comp *)arg;
iocmd_comp->comp_status = (u32) status;
complete(&iocmd_comp->comp);
}
/* Resource allocation, free functions */
static void
bnad_mem_free(struct bnad *bnad,
struct bna_mem_info *mem_info)
{
int i;
dma_addr_t dma_pa;
if (mem_info->mdl == NULL)
return;
for (i = 0; i < mem_info->num; i++) {
if (mem_info->mdl[i].kva != NULL) {
if (mem_info->mem_type == BNA_MEM_T_DMA) {
BNA_GET_DMA_ADDR(&(mem_info->mdl[i].dma),
dma_pa);
dma_free_coherent(&bnad->pcidev->dev,
mem_info->mdl[i].len,
mem_info->mdl[i].kva, dma_pa);
} else
kfree(mem_info->mdl[i].kva);
}
}
kfree(mem_info->mdl);
mem_info->mdl = NULL;
}
static int
bnad_mem_alloc(struct bnad *bnad,
struct bna_mem_info *mem_info)
{
int i;
dma_addr_t dma_pa;
if ((mem_info->num == 0) || (mem_info->len == 0)) {
mem_info->mdl = NULL;
return 0;
}
mem_info->mdl = kcalloc(mem_info->num, sizeof(struct bna_mem_descr),
GFP_KERNEL);
if (mem_info->mdl == NULL)
return -ENOMEM;
if (mem_info->mem_type == BNA_MEM_T_DMA) {
for (i = 0; i < mem_info->num; i++) {
mem_info->mdl[i].len = mem_info->len;
mem_info->mdl[i].kva =
dma_alloc_coherent(&bnad->pcidev->dev,
mem_info->len, &dma_pa,
GFP_KERNEL);
if (mem_info->mdl[i].kva == NULL)
goto err_return;
BNA_SET_DMA_ADDR(dma_pa,
&(mem_info->mdl[i].dma));
}
} else {
for (i = 0; i < mem_info->num; i++) {
mem_info->mdl[i].len = mem_info->len;
mem_info->mdl[i].kva = kzalloc(mem_info->len,
GFP_KERNEL);
if (mem_info->mdl[i].kva == NULL)
goto err_return;
}
}
return 0;
err_return:
bnad_mem_free(bnad, mem_info);
return -ENOMEM;
}
/* Free IRQ for Mailbox */
static void
bnad_mbox_irq_free(struct bnad *bnad)
{
int irq;
unsigned long flags;
spin_lock_irqsave(&bnad->bna_lock, flags);
bnad_disable_mbox_irq(bnad);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
irq = BNAD_GET_MBOX_IRQ(bnad);
free_irq(irq, bnad);
}
/*
* Allocates IRQ for Mailbox, but keep it disabled
* This will be enabled once we get the mbox enable callback
* from bna
*/
static int
bnad_mbox_irq_alloc(struct bnad *bnad)
{
int err = 0;
unsigned long irq_flags, flags;
u32 irq;
irq_handler_t irq_handler;
spin_lock_irqsave(&bnad->bna_lock, flags);
if (bnad->cfg_flags & BNAD_CF_MSIX) {
irq_handler = (irq_handler_t)bnad_msix_mbox_handler;
irq = bnad->msix_table[BNAD_MAILBOX_MSIX_INDEX].vector;
irq_flags = 0;
} else {
irq_handler = (irq_handler_t)bnad_isr;
irq = bnad->pcidev->irq;
irq_flags = IRQF_SHARED;
}
spin_unlock_irqrestore(&bnad->bna_lock, flags);
sprintf(bnad->mbox_irq_name, "%s", BNAD_NAME);
/*
* Set the Mbox IRQ disable flag, so that the IRQ handler
* called from request_irq() for SHARED IRQs do not execute
*/
set_bit(BNAD_RF_MBOX_IRQ_DISABLED, &bnad->run_flags);
BNAD_UPDATE_CTR(bnad, mbox_intr_disabled);
err = request_irq(irq, irq_handler, irq_flags,
bnad->mbox_irq_name, bnad);
return err;
}
static void
bnad_txrx_irq_free(struct bnad *bnad, struct bna_intr_info *intr_info)
{
kfree(intr_info->idl);
intr_info->idl = NULL;
}
/* Allocates Interrupt Descriptor List for MSIX/INT-X vectors */
static int
bnad_txrx_irq_alloc(struct bnad *bnad, enum bnad_intr_source src,
u32 txrx_id, struct bna_intr_info *intr_info)
{
int i, vector_start = 0;
u32 cfg_flags;
unsigned long flags;
spin_lock_irqsave(&bnad->bna_lock, flags);
cfg_flags = bnad->cfg_flags;
spin_unlock_irqrestore(&bnad->bna_lock, flags);
if (cfg_flags & BNAD_CF_MSIX) {
intr_info->intr_type = BNA_INTR_T_MSIX;
intr_info->idl = kcalloc(intr_info->num,
sizeof(struct bna_intr_descr),
GFP_KERNEL);
if (!intr_info->idl)
return -ENOMEM;
switch (src) {
case BNAD_INTR_TX:
vector_start = BNAD_MAILBOX_MSIX_VECTORS + txrx_id;
break;
case BNAD_INTR_RX:
vector_start = BNAD_MAILBOX_MSIX_VECTORS +
(bnad->num_tx * bnad->num_txq_per_tx) +
txrx_id;
break;
default:
BUG();
}
for (i = 0; i < intr_info->num; i++)
intr_info->idl[i].vector = vector_start + i;
} else {
intr_info->intr_type = BNA_INTR_T_INTX;
intr_info->num = 1;
intr_info->idl = kcalloc(intr_info->num,
sizeof(struct bna_intr_descr),
GFP_KERNEL);
if (!intr_info->idl)
return -ENOMEM;
switch (src) {
case BNAD_INTR_TX:
intr_info->idl[0].vector = BNAD_INTX_TX_IB_BITMASK;
break;
case BNAD_INTR_RX:
intr_info->idl[0].vector = BNAD_INTX_RX_IB_BITMASK;
break;
}
}
return 0;
}
/* NOTE: Should be called for MSIX only
* Unregisters Tx MSIX vector(s) from the kernel
*/
static void
bnad_tx_msix_unregister(struct bnad *bnad, struct bnad_tx_info *tx_info,
int num_txqs)
{
int i;
int vector_num;
for (i = 0; i < num_txqs; i++) {
if (tx_info->tcb[i] == NULL)
continue;
vector_num = tx_info->tcb[i]->intr_vector;
free_irq(bnad->msix_table[vector_num].vector, tx_info->tcb[i]);
}
}
/* NOTE: Should be called for MSIX only
* Registers Tx MSIX vector(s) and ISR(s), cookie with the kernel
*/
static int
bnad_tx_msix_register(struct bnad *bnad, struct bnad_tx_info *tx_info,
u32 tx_id, int num_txqs)
{
int i;
int err;
int vector_num;
for (i = 0; i < num_txqs; i++) {
vector_num = tx_info->tcb[i]->intr_vector;
sprintf(tx_info->tcb[i]->name, "%s TXQ %d", bnad->netdev->name,
tx_id + tx_info->tcb[i]->id);
err = request_irq(bnad->msix_table[vector_num].vector,
(irq_handler_t)bnad_msix_tx, 0,
tx_info->tcb[i]->name,
tx_info->tcb[i]);
if (err)
goto err_return;
}
return 0;
err_return:
if (i > 0)
bnad_tx_msix_unregister(bnad, tx_info, (i - 1));
return -1;
}
/* NOTE: Should be called for MSIX only
* Unregisters Rx MSIX vector(s) from the kernel
*/
static void
bnad_rx_msix_unregister(struct bnad *bnad, struct bnad_rx_info *rx_info,
int num_rxps)
{
int i;
int vector_num;
for (i = 0; i < num_rxps; i++) {
if (rx_info->rx_ctrl[i].ccb == NULL)
continue;
vector_num = rx_info->rx_ctrl[i].ccb->intr_vector;
free_irq(bnad->msix_table[vector_num].vector,
rx_info->rx_ctrl[i].ccb);
}
}
/* NOTE: Should be called for MSIX only
* Registers Tx MSIX vector(s) and ISR(s), cookie with the kernel
*/
static int
bnad_rx_msix_register(struct bnad *bnad, struct bnad_rx_info *rx_info,
u32 rx_id, int num_rxps)
{
int i;
int err;
int vector_num;
for (i = 0; i < num_rxps; i++) {
vector_num = rx_info->rx_ctrl[i].ccb->intr_vector;
sprintf(rx_info->rx_ctrl[i].ccb->name, "%s CQ %d",
bnad->netdev->name,
rx_id + rx_info->rx_ctrl[i].ccb->id);
err = request_irq(bnad->msix_table[vector_num].vector,
(irq_handler_t)bnad_msix_rx, 0,
rx_info->rx_ctrl[i].ccb->name,
rx_info->rx_ctrl[i].ccb);
if (err)
goto err_return;
}
return 0;
err_return:
if (i > 0)
bnad_rx_msix_unregister(bnad, rx_info, (i - 1));
return -1;
}
/* Free Tx object Resources */
static void
bnad_tx_res_free(struct bnad *bnad, struct bna_res_info *res_info)
{
int i;
for (i = 0; i < BNA_TX_RES_T_MAX; i++) {
if (res_info[i].res_type == BNA_RES_T_MEM)
bnad_mem_free(bnad, &res_info[i].res_u.mem_info);
else if (res_info[i].res_type == BNA_RES_T_INTR)
bnad_txrx_irq_free(bnad, &res_info[i].res_u.intr_info);
}
}
/* Allocates memory and interrupt resources for Tx object */
static int
bnad_tx_res_alloc(struct bnad *bnad, struct bna_res_info *res_info,
u32 tx_id)
{
int i, err = 0;
for (i = 0; i < BNA_TX_RES_T_MAX; i++) {
if (res_info[i].res_type == BNA_RES_T_MEM)
err = bnad_mem_alloc(bnad,
&res_info[i].res_u.mem_info);
else if (res_info[i].res_type == BNA_RES_T_INTR)
err = bnad_txrx_irq_alloc(bnad, BNAD_INTR_TX, tx_id,
&res_info[i].res_u.intr_info);
if (err)
goto err_return;
}
return 0;
err_return:
bnad_tx_res_free(bnad, res_info);
return err;
}
/* Free Rx object Resources */
static void
bnad_rx_res_free(struct bnad *bnad, struct bna_res_info *res_info)
{
int i;
for (i = 0; i < BNA_RX_RES_T_MAX; i++) {
if (res_info[i].res_type == BNA_RES_T_MEM)
bnad_mem_free(bnad, &res_info[i].res_u.mem_info);
else if (res_info[i].res_type == BNA_RES_T_INTR)
bnad_txrx_irq_free(bnad, &res_info[i].res_u.intr_info);
}
}
/* Allocates memory and interrupt resources for Rx object */
static int
bnad_rx_res_alloc(struct bnad *bnad, struct bna_res_info *res_info,
uint rx_id)
{
int i, err = 0;
/* All memory needs to be allocated before setup_ccbs */
for (i = 0; i < BNA_RX_RES_T_MAX; i++) {
if (res_info[i].res_type == BNA_RES_T_MEM)
err = bnad_mem_alloc(bnad,
&res_info[i].res_u.mem_info);
else if (res_info[i].res_type == BNA_RES_T_INTR)
err = bnad_txrx_irq_alloc(bnad, BNAD_INTR_RX, rx_id,
&res_info[i].res_u.intr_info);
if (err)
goto err_return;
}
return 0;
err_return:
bnad_rx_res_free(bnad, res_info);
return err;
}
/* Timer callbacks */
/* a) IOC timer */
static void
bnad_ioc_timeout(struct timer_list *t)
{
struct bnad *bnad = from_timer(bnad, t, bna.ioceth.ioc.ioc_timer);
unsigned long flags;
spin_lock_irqsave(&bnad->bna_lock, flags);
bfa_nw_ioc_timeout(&bnad->bna.ioceth.ioc);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
}
static void
bnad_ioc_hb_check(struct timer_list *t)
{
struct bnad *bnad = from_timer(bnad, t, bna.ioceth.ioc.hb_timer);
unsigned long flags;
spin_lock_irqsave(&bnad->bna_lock, flags);
bfa_nw_ioc_hb_check(&bnad->bna.ioceth.ioc);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
}
static void
bnad_iocpf_timeout(struct timer_list *t)
{
struct bnad *bnad = from_timer(bnad, t, bna.ioceth.ioc.iocpf_timer);
unsigned long flags;
spin_lock_irqsave(&bnad->bna_lock, flags);
bfa_nw_iocpf_timeout(&bnad->bna.ioceth.ioc);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
}
static void
bnad_iocpf_sem_timeout(struct timer_list *t)
{
struct bnad *bnad = from_timer(bnad, t, bna.ioceth.ioc.sem_timer);
unsigned long flags;
spin_lock_irqsave(&bnad->bna_lock, flags);
bfa_nw_iocpf_sem_timeout(&bnad->bna.ioceth.ioc);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
}
/*
* All timer routines use bnad->bna_lock to protect against
* the following race, which may occur in case of no locking:
* Time CPU m CPU n
* 0 1 = test_bit
* 1 clear_bit
* 2 del_timer_sync
* 3 mod_timer
*/
/* b) Dynamic Interrupt Moderation Timer */
static void
bnad_dim_timeout(struct timer_list *t)
{
struct bnad *bnad = from_timer(bnad, t, dim_timer);
struct bnad_rx_info *rx_info;
struct bnad_rx_ctrl *rx_ctrl;
int i, j;
unsigned long flags;
if (!netif_carrier_ok(bnad->netdev))
return;
spin_lock_irqsave(&bnad->bna_lock, flags);
for (i = 0; i < bnad->num_rx; i++) {
rx_info = &bnad->rx_info[i];
if (!rx_info->rx)
continue;
for (j = 0; j < bnad->num_rxp_per_rx; j++) {
rx_ctrl = &rx_info->rx_ctrl[j];
if (!rx_ctrl->ccb)
continue;
bna_rx_dim_update(rx_ctrl->ccb);
}
}
/* Check for BNAD_CF_DIM_ENABLED, does not eliminate a race */
if (test_bit(BNAD_RF_DIM_TIMER_RUNNING, &bnad->run_flags))
mod_timer(&bnad->dim_timer,
jiffies + msecs_to_jiffies(BNAD_DIM_TIMER_FREQ));
spin_unlock_irqrestore(&bnad->bna_lock, flags);
}
/* c) Statistics Timer */
static void
bnad_stats_timeout(struct timer_list *t)
{
struct bnad *bnad = from_timer(bnad, t, stats_timer);
unsigned long flags;
if (!netif_running(bnad->netdev) ||
!test_bit(BNAD_RF_STATS_TIMER_RUNNING, &bnad->run_flags))
return;
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_hw_stats_get(&bnad->bna);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
}
/*
* Set up timer for DIM
* Called with bnad->bna_lock held
*/
void
bnad_dim_timer_start(struct bnad *bnad)
{
if (bnad->cfg_flags & BNAD_CF_DIM_ENABLED &&
!test_bit(BNAD_RF_DIM_TIMER_RUNNING, &bnad->run_flags)) {
timer_setup(&bnad->dim_timer, bnad_dim_timeout, 0);
set_bit(BNAD_RF_DIM_TIMER_RUNNING, &bnad->run_flags);
mod_timer(&bnad->dim_timer,
jiffies + msecs_to_jiffies(BNAD_DIM_TIMER_FREQ));
}
}
/*
* Set up timer for statistics
* Called with mutex_lock(&bnad->conf_mutex) held
*/
static void
bnad_stats_timer_start(struct bnad *bnad)
{
unsigned long flags;
spin_lock_irqsave(&bnad->bna_lock, flags);
if (!test_and_set_bit(BNAD_RF_STATS_TIMER_RUNNING, &bnad->run_flags)) {
timer_setup(&bnad->stats_timer, bnad_stats_timeout, 0);
mod_timer(&bnad->stats_timer,
jiffies + msecs_to_jiffies(BNAD_STATS_TIMER_FREQ));
}
spin_unlock_irqrestore(&bnad->bna_lock, flags);
}
/*
* Stops the stats timer
* Called with mutex_lock(&bnad->conf_mutex) held
*/
static void
bnad_stats_timer_stop(struct bnad *bnad)
{
int to_del = 0;
unsigned long flags;
spin_lock_irqsave(&bnad->bna_lock, flags);
if (test_and_clear_bit(BNAD_RF_STATS_TIMER_RUNNING, &bnad->run_flags))
to_del = 1;
spin_unlock_irqrestore(&bnad->bna_lock, flags);
if (to_del)
del_timer_sync(&bnad->stats_timer);
}
/* Utilities */
static void
bnad_netdev_mc_list_get(struct net_device *netdev, u8 *mc_list)
{
int i = 1; /* Index 0 has broadcast address */
struct netdev_hw_addr *mc_addr;
netdev_for_each_mc_addr(mc_addr, netdev) {
ether_addr_copy(&mc_list[i * ETH_ALEN], &mc_addr->addr[0]);
i++;
}
}
static int
bnad_napi_poll_rx(struct napi_struct *napi, int budget)
{
struct bnad_rx_ctrl *rx_ctrl =
container_of(napi, struct bnad_rx_ctrl, napi);
struct bnad *bnad = rx_ctrl->bnad;
int rcvd = 0;
rx_ctrl->rx_poll_ctr++;
if (!netif_carrier_ok(bnad->netdev))
goto poll_exit;
rcvd = bnad_cq_process(bnad, rx_ctrl->ccb, budget);
if (rcvd >= budget)
return rcvd;
poll_exit:
napi_complete_done(napi, rcvd);
rx_ctrl->rx_complete++;
if (rx_ctrl->ccb)
bnad_enable_rx_irq_unsafe(rx_ctrl->ccb);
return rcvd;
}
static void
bnad_napi_add(struct bnad *bnad, u32 rx_id)
{
struct bnad_rx_ctrl *rx_ctrl;
int i;
/* Initialize & enable NAPI */
for (i = 0; i < bnad->num_rxp_per_rx; i++) {
rx_ctrl = &bnad->rx_info[rx_id].rx_ctrl[i];
netif_napi_add(bnad->netdev, &rx_ctrl->napi,
bnad_napi_poll_rx);
}
}
static void
bnad_napi_delete(struct bnad *bnad, u32 rx_id)
{
int i;
/* First disable and then clean up */
for (i = 0; i < bnad->num_rxp_per_rx; i++)
netif_napi_del(&bnad->rx_info[rx_id].rx_ctrl[i].napi);
}
/* Should be held with conf_lock held */
void
bnad_destroy_tx(struct bnad *bnad, u32 tx_id)
{
struct bnad_tx_info *tx_info = &bnad->tx_info[tx_id];
struct bna_res_info *res_info = &bnad->tx_res_info[tx_id].res_info[0];
unsigned long flags;
if (!tx_info->tx)
return;
init_completion(&bnad->bnad_completions.tx_comp);
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_tx_disable(tx_info->tx, BNA_HARD_CLEANUP, bnad_cb_tx_disabled);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
wait_for_completion(&bnad->bnad_completions.tx_comp);
if (tx_info->tcb[0]->intr_type == BNA_INTR_T_MSIX)
bnad_tx_msix_unregister(bnad, tx_info,
bnad->num_txq_per_tx);
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_tx_destroy(tx_info->tx);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
tx_info->tx = NULL;
tx_info->tx_id = 0;
bnad_tx_res_free(bnad, res_info);
}
/* Should be held with conf_lock held */
int
bnad_setup_tx(struct bnad *bnad, u32 tx_id)
{
int err;
struct bnad_tx_info *tx_info = &bnad->tx_info[tx_id];
struct bna_res_info *res_info = &bnad->tx_res_info[tx_id].res_info[0];
struct bna_intr_info *intr_info =
&res_info[BNA_TX_RES_INTR_T_TXCMPL].res_u.intr_info;
struct bna_tx_config *tx_config = &bnad->tx_config[tx_id];
static const struct bna_tx_event_cbfn tx_cbfn = {
.tcb_setup_cbfn = bnad_cb_tcb_setup,
.tcb_destroy_cbfn = bnad_cb_tcb_destroy,
.tx_stall_cbfn = bnad_cb_tx_stall,
.tx_resume_cbfn = bnad_cb_tx_resume,
.tx_cleanup_cbfn = bnad_cb_tx_cleanup,
};
struct bna_tx *tx;
unsigned long flags;
tx_info->tx_id = tx_id;
/* Initialize the Tx object configuration */
tx_config->num_txq = bnad->num_txq_per_tx;
tx_config->txq_depth = bnad->txq_depth;
tx_config->tx_type = BNA_TX_T_REGULAR;
tx_config->coalescing_timeo = bnad->tx_coalescing_timeo;
/* Get BNA's resource requirement for one tx object */
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_tx_res_req(bnad->num_txq_per_tx,
bnad->txq_depth, res_info);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
/* Fill Unmap Q memory requirements */
BNAD_FILL_UNMAPQ_MEM_REQ(&res_info[BNA_TX_RES_MEM_T_UNMAPQ],
bnad->num_txq_per_tx, (sizeof(struct bnad_tx_unmap) *
bnad->txq_depth));
/* Allocate resources */
err = bnad_tx_res_alloc(bnad, res_info, tx_id);
if (err)
return err;
/* Ask BNA to create one Tx object, supplying required resources */
spin_lock_irqsave(&bnad->bna_lock, flags);
tx = bna_tx_create(&bnad->bna, bnad, tx_config, &tx_cbfn, res_info,
tx_info);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
if (!tx) {
err = -ENOMEM;
goto err_return;
}
tx_info->tx = tx;
INIT_DELAYED_WORK(&tx_info->tx_cleanup_work,
(work_func_t)bnad_tx_cleanup);
/* Register ISR for the Tx object */
if (intr_info->intr_type == BNA_INTR_T_MSIX) {
err = bnad_tx_msix_register(bnad, tx_info,
tx_id, bnad->num_txq_per_tx);
if (err)
goto cleanup_tx;
}
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_tx_enable(tx);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
return 0;
cleanup_tx:
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_tx_destroy(tx_info->tx);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
tx_info->tx = NULL;
tx_info->tx_id = 0;
err_return:
bnad_tx_res_free(bnad, res_info);
return err;
}
/* Setup the rx config for bna_rx_create */
/* bnad decides the configuration */
static void
bnad_init_rx_config(struct bnad *bnad, struct bna_rx_config *rx_config)
{
memset(rx_config, 0, sizeof(*rx_config));
rx_config->rx_type = BNA_RX_T_REGULAR;
rx_config->num_paths = bnad->num_rxp_per_rx;
rx_config->coalescing_timeo = bnad->rx_coalescing_timeo;
if (bnad->num_rxp_per_rx > 1) {
rx_config->rss_status = BNA_STATUS_T_ENABLED;
rx_config->rss_config.hash_type =
(BFI_ENET_RSS_IPV6 |
BFI_ENET_RSS_IPV6_TCP |
BFI_ENET_RSS_IPV4 |
BFI_ENET_RSS_IPV4_TCP);
rx_config->rss_config.hash_mask =
bnad->num_rxp_per_rx - 1;
netdev_rss_key_fill(rx_config->rss_config.toeplitz_hash_key,
sizeof(rx_config->rss_config.toeplitz_hash_key));
} else {
rx_config->rss_status = BNA_STATUS_T_DISABLED;
memset(&rx_config->rss_config, 0,
sizeof(rx_config->rss_config));
}
rx_config->frame_size = BNAD_FRAME_SIZE(bnad->netdev->mtu);
rx_config->q0_multi_buf = BNA_STATUS_T_DISABLED;
/* BNA_RXP_SINGLE - one data-buffer queue
* BNA_RXP_SLR - one small-buffer and one large-buffer queues
* BNA_RXP_HDS - one header-buffer and one data-buffer queues
*/
/* TODO: configurable param for queue type */
rx_config->rxp_type = BNA_RXP_SLR;
if (BNAD_PCI_DEV_IS_CAT2(bnad) &&
rx_config->frame_size > 4096) {
/* though size_routing_enable is set in SLR,
* small packets may get routed to same rxq.
* set buf_size to 2048 instead of PAGE_SIZE.
*/
rx_config->q0_buf_size = 2048;
/* this should be in multiples of 2 */
rx_config->q0_num_vecs = 4;
rx_config->q0_depth = bnad->rxq_depth * rx_config->q0_num_vecs;
rx_config->q0_multi_buf = BNA_STATUS_T_ENABLED;
} else {
rx_config->q0_buf_size = rx_config->frame_size;
rx_config->q0_num_vecs = 1;
rx_config->q0_depth = bnad->rxq_depth;
}
/* initialize for q1 for BNA_RXP_SLR/BNA_RXP_HDS */
if (rx_config->rxp_type == BNA_RXP_SLR) {
rx_config->q1_depth = bnad->rxq_depth;
rx_config->q1_buf_size = BFI_SMALL_RXBUF_SIZE;
}
rx_config->vlan_strip_status =
(bnad->netdev->features & NETIF_F_HW_VLAN_CTAG_RX) ?
BNA_STATUS_T_ENABLED : BNA_STATUS_T_DISABLED;
}
static void
bnad_rx_ctrl_init(struct bnad *bnad, u32 rx_id)
{
struct bnad_rx_info *rx_info = &bnad->rx_info[rx_id];
int i;
for (i = 0; i < bnad->num_rxp_per_rx; i++)
rx_info->rx_ctrl[i].bnad = bnad;
}
/* Called with mutex_lock(&bnad->conf_mutex) held */
static u32
bnad_reinit_rx(struct bnad *bnad)
{
struct net_device *netdev = bnad->netdev;
u32 err = 0, current_err = 0;
u32 rx_id = 0, count = 0;
unsigned long flags;
/* destroy and create new rx objects */
for (rx_id = 0; rx_id < bnad->num_rx; rx_id++) {
if (!bnad->rx_info[rx_id].rx)
continue;
bnad_destroy_rx(bnad, rx_id);
}
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_enet_mtu_set(&bnad->bna.enet,
BNAD_FRAME_SIZE(bnad->netdev->mtu), NULL);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
for (rx_id = 0; rx_id < bnad->num_rx; rx_id++) {
count++;
current_err = bnad_setup_rx(bnad, rx_id);
if (current_err && !err) {
err = current_err;
netdev_err(netdev, "RXQ:%u setup failed\n", rx_id);
}
}
/* restore rx configuration */
if (bnad->rx_info[0].rx && !err) {
bnad_restore_vlans(bnad, 0);
bnad_enable_default_bcast(bnad);
spin_lock_irqsave(&bnad->bna_lock, flags);
bnad_mac_addr_set_locked(bnad, netdev->dev_addr);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
bnad_set_rx_mode(netdev);
}
return count;
}
/* Called with bnad_conf_lock() held */
void
bnad_destroy_rx(struct bnad *bnad, u32 rx_id)
{
struct bnad_rx_info *rx_info = &bnad->rx_info[rx_id];
struct bna_rx_config *rx_config = &bnad->rx_config[rx_id];
struct bna_res_info *res_info = &bnad->rx_res_info[rx_id].res_info[0];
unsigned long flags;
int to_del = 0;
if (!rx_info->rx)
return;
if (0 == rx_id) {
spin_lock_irqsave(&bnad->bna_lock, flags);
if (bnad->cfg_flags & BNAD_CF_DIM_ENABLED &&
test_bit(BNAD_RF_DIM_TIMER_RUNNING, &bnad->run_flags)) {
clear_bit(BNAD_RF_DIM_TIMER_RUNNING, &bnad->run_flags);
to_del = 1;
}
spin_unlock_irqrestore(&bnad->bna_lock, flags);
if (to_del)
del_timer_sync(&bnad->dim_timer);
}
init_completion(&bnad->bnad_completions.rx_comp);
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_rx_disable(rx_info->rx, BNA_HARD_CLEANUP, bnad_cb_rx_disabled);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
wait_for_completion(&bnad->bnad_completions.rx_comp);
if (rx_info->rx_ctrl[0].ccb->intr_type == BNA_INTR_T_MSIX)
bnad_rx_msix_unregister(bnad, rx_info, rx_config->num_paths);
bnad_napi_delete(bnad, rx_id);
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_rx_destroy(rx_info->rx);
rx_info->rx = NULL;
rx_info->rx_id = 0;
spin_unlock_irqrestore(&bnad->bna_lock, flags);
bnad_rx_res_free(bnad, res_info);
}
/* Called with mutex_lock(&bnad->conf_mutex) held */
int
bnad_setup_rx(struct bnad *bnad, u32 rx_id)
{
int err;
struct bnad_rx_info *rx_info = &bnad->rx_info[rx_id];
struct bna_res_info *res_info = &bnad->rx_res_info[rx_id].res_info[0];
struct bna_intr_info *intr_info =
&res_info[BNA_RX_RES_T_INTR].res_u.intr_info;
struct bna_rx_config *rx_config = &bnad->rx_config[rx_id];
static const struct bna_rx_event_cbfn rx_cbfn = {
.rcb_setup_cbfn = NULL,
.rcb_destroy_cbfn = NULL,
.ccb_setup_cbfn = bnad_cb_ccb_setup,
.ccb_destroy_cbfn = bnad_cb_ccb_destroy,
.rx_stall_cbfn = bnad_cb_rx_stall,
.rx_cleanup_cbfn = bnad_cb_rx_cleanup,
.rx_post_cbfn = bnad_cb_rx_post,
};
struct bna_rx *rx;
unsigned long flags;
rx_info->rx_id = rx_id;
/* Initialize the Rx object configuration */
bnad_init_rx_config(bnad, rx_config);
/* Get BNA's resource requirement for one Rx object */
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_rx_res_req(rx_config, res_info);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
/* Fill Unmap Q memory requirements */
BNAD_FILL_UNMAPQ_MEM_REQ(&res_info[BNA_RX_RES_MEM_T_UNMAPDQ],
rx_config->num_paths,
(rx_config->q0_depth *
sizeof(struct bnad_rx_unmap)) +
sizeof(struct bnad_rx_unmap_q));
if (rx_config->rxp_type != BNA_RXP_SINGLE) {
BNAD_FILL_UNMAPQ_MEM_REQ(&res_info[BNA_RX_RES_MEM_T_UNMAPHQ],
rx_config->num_paths,
(rx_config->q1_depth *
sizeof(struct bnad_rx_unmap) +
sizeof(struct bnad_rx_unmap_q)));
}
/* Allocate resource */
err = bnad_rx_res_alloc(bnad, res_info, rx_id);
if (err)
return err;
bnad_rx_ctrl_init(bnad, rx_id);
/* Ask BNA to create one Rx object, supplying required resources */
spin_lock_irqsave(&bnad->bna_lock, flags);
rx = bna_rx_create(&bnad->bna, bnad, rx_config, &rx_cbfn, res_info,
rx_info);
if (!rx) {
err = -ENOMEM;
spin_unlock_irqrestore(&bnad->bna_lock, flags);
goto err_return;
}
rx_info->rx = rx;
spin_unlock_irqrestore(&bnad->bna_lock, flags);
INIT_WORK(&rx_info->rx_cleanup_work,
(work_func_t)(bnad_rx_cleanup));
/*
* Init NAPI, so that state is set to NAPI_STATE_SCHED,
* so that IRQ handler cannot schedule NAPI at this point.
*/
bnad_napi_add(bnad, rx_id);
/* Register ISR for the Rx object */
if (intr_info->intr_type == BNA_INTR_T_MSIX) {
err = bnad_rx_msix_register(bnad, rx_info, rx_id,
rx_config->num_paths);
if (err)
goto err_return;
}
spin_lock_irqsave(&bnad->bna_lock, flags);
if (0 == rx_id) {
/* Set up Dynamic Interrupt Moderation Vector */
if (bnad->cfg_flags & BNAD_CF_DIM_ENABLED)
bna_rx_dim_reconfig(&bnad->bna, bna_napi_dim_vector);
/* Enable VLAN filtering only on the default Rx */
bna_rx_vlanfilter_enable(rx);
/* Start the DIM timer */
bnad_dim_timer_start(bnad);
}
bna_rx_enable(rx);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
return 0;
err_return:
bnad_destroy_rx(bnad, rx_id);
return err;
}
/* Called with conf_lock & bnad->bna_lock held */
void
bnad_tx_coalescing_timeo_set(struct bnad *bnad)
{
struct bnad_tx_info *tx_info;
tx_info = &bnad->tx_info[0];
if (!tx_info->tx)
return;
bna_tx_coalescing_timeo_set(tx_info->tx, bnad->tx_coalescing_timeo);
}
/* Called with conf_lock & bnad->bna_lock held */
void
bnad_rx_coalescing_timeo_set(struct bnad *bnad)
{
struct bnad_rx_info *rx_info;
int i;
for (i = 0; i < bnad->num_rx; i++) {
rx_info = &bnad->rx_info[i];
if (!rx_info->rx)
continue;
bna_rx_coalescing_timeo_set(rx_info->rx,
bnad->rx_coalescing_timeo);
}
}
/*
* Called with bnad->bna_lock held
*/
int
bnad_mac_addr_set_locked(struct bnad *bnad, const u8 *mac_addr)
{
int ret;
if (!is_valid_ether_addr(mac_addr))
return -EADDRNOTAVAIL;
/* If datapath is down, pretend everything went through */
if (!bnad->rx_info[0].rx)
return 0;
ret = bna_rx_ucast_set(bnad->rx_info[0].rx, mac_addr);
if (ret != BNA_CB_SUCCESS)
return -EADDRNOTAVAIL;
return 0;
}
/* Should be called with conf_lock held */
int
bnad_enable_default_bcast(struct bnad *bnad)
{
struct bnad_rx_info *rx_info = &bnad->rx_info[0];
int ret;
unsigned long flags;
init_completion(&bnad->bnad_completions.mcast_comp);
spin_lock_irqsave(&bnad->bna_lock, flags);
ret = bna_rx_mcast_add(rx_info->rx, bnad_bcast_addr,
bnad_cb_rx_mcast_add);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
if (ret == BNA_CB_SUCCESS)
wait_for_completion(&bnad->bnad_completions.mcast_comp);
else
return -ENODEV;
if (bnad->bnad_completions.mcast_comp_status != BNA_CB_SUCCESS)
return -ENODEV;
return 0;
}
/* Called with mutex_lock(&bnad->conf_mutex) held */
void
bnad_restore_vlans(struct bnad *bnad, u32 rx_id)
{
u16 vid;
unsigned long flags;
for_each_set_bit(vid, bnad->active_vlans, VLAN_N_VID) {
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_rx_vlan_add(bnad->rx_info[rx_id].rx, vid);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
}
}
/* Statistics utilities */
void
bnad_netdev_qstats_fill(struct bnad *bnad, struct rtnl_link_stats64 *stats)
{
int i, j;
for (i = 0; i < bnad->num_rx; i++) {
for (j = 0; j < bnad->num_rxp_per_rx; j++) {
if (bnad->rx_info[i].rx_ctrl[j].ccb) {
stats->rx_packets += bnad->rx_info[i].
rx_ctrl[j].ccb->rcb[0]->rxq->rx_packets;
stats->rx_bytes += bnad->rx_info[i].
rx_ctrl[j].ccb->rcb[0]->rxq->rx_bytes;
if (bnad->rx_info[i].rx_ctrl[j].ccb->rcb[1] &&
bnad->rx_info[i].rx_ctrl[j].ccb->
rcb[1]->rxq) {
stats->rx_packets +=
bnad->rx_info[i].rx_ctrl[j].
ccb->rcb[1]->rxq->rx_packets;
stats->rx_bytes +=
bnad->rx_info[i].rx_ctrl[j].
ccb->rcb[1]->rxq->rx_bytes;
}
}
}
}
for (i = 0; i < bnad->num_tx; i++) {
for (j = 0; j < bnad->num_txq_per_tx; j++) {
if (bnad->tx_info[i].tcb[j]) {
stats->tx_packets +=
bnad->tx_info[i].tcb[j]->txq->tx_packets;
stats->tx_bytes +=
bnad->tx_info[i].tcb[j]->txq->tx_bytes;
}
}
}
}
/*
* Must be called with the bna_lock held.
*/
void
bnad_netdev_hwstats_fill(struct bnad *bnad, struct rtnl_link_stats64 *stats)
{
struct bfi_enet_stats_mac *mac_stats;
u32 bmap;
int i;
mac_stats = &bnad->stats.bna_stats->hw_stats.mac_stats;
stats->rx_errors =
mac_stats->rx_fcs_error + mac_stats->rx_alignment_error +
mac_stats->rx_frame_length_error + mac_stats->rx_code_error +
mac_stats->rx_undersize;
stats->tx_errors = mac_stats->tx_fcs_error +
mac_stats->tx_undersize;
stats->rx_dropped = mac_stats->rx_drop;
stats->tx_dropped = mac_stats->tx_drop;
stats->multicast = mac_stats->rx_multicast;
stats->collisions = mac_stats->tx_total_collision;
stats->rx_length_errors = mac_stats->rx_frame_length_error;
/* receive ring buffer overflow ?? */
stats->rx_crc_errors = mac_stats->rx_fcs_error;
stats->rx_frame_errors = mac_stats->rx_alignment_error;
/* recv'r fifo overrun */
bmap = bna_rx_rid_mask(&bnad->bna);
for (i = 0; bmap; i++) {
if (bmap & 1) {
stats->rx_fifo_errors +=
bnad->stats.bna_stats->
hw_stats.rxf_stats[i].frame_drops;
break;
}
bmap >>= 1;
}
}
static void
bnad_mbox_irq_sync(struct bnad *bnad)
{
u32 irq;
unsigned long flags;
spin_lock_irqsave(&bnad->bna_lock, flags);
if (bnad->cfg_flags & BNAD_CF_MSIX)
irq = bnad->msix_table[BNAD_MAILBOX_MSIX_INDEX].vector;
else
irq = bnad->pcidev->irq;
spin_unlock_irqrestore(&bnad->bna_lock, flags);
synchronize_irq(irq);
}
/* Utility used by bnad_start_xmit, for doing TSO */
static int
bnad_tso_prepare(struct bnad *bnad, struct sk_buff *skb)
{
int err;
err = skb_cow_head(skb, 0);
if (err < 0) {
BNAD_UPDATE_CTR(bnad, tso_err);
return err;
}
/*
* For TSO, the TCP checksum field is seeded with pseudo-header sum
* excluding the length field.
*/
if (vlan_get_protocol(skb) == htons(ETH_P_IP)) {
struct iphdr *iph = ip_hdr(skb);
/* Do we really need these? */
iph->tot_len = 0;
iph->check = 0;
tcp_hdr(skb)->check =
~csum_tcpudp_magic(iph->saddr, iph->daddr, 0,
IPPROTO_TCP, 0);
BNAD_UPDATE_CTR(bnad, tso4);
} else {
tcp_v6_gso_csum_prep(skb);
BNAD_UPDATE_CTR(bnad, tso6);
}
return 0;
}
/*
* Initialize Q numbers depending on Rx Paths
* Called with bnad->bna_lock held, because of cfg_flags
* access.
*/
static void
bnad_q_num_init(struct bnad *bnad)
{
int rxps;
rxps = min((uint)num_online_cpus(),
(uint)(BNAD_MAX_RX * BNAD_MAX_RXP_PER_RX));
if (!(bnad->cfg_flags & BNAD_CF_MSIX))
rxps = 1; /* INTx */
bnad->num_rx = 1;
bnad->num_tx = 1;
bnad->num_rxp_per_rx = rxps;
bnad->num_txq_per_tx = BNAD_TXQ_NUM;
}
/*
* Adjusts the Q numbers, given a number of msix vectors
* Give preference to RSS as opposed to Tx priority Queues,
* in such a case, just use 1 Tx Q
* Called with bnad->bna_lock held b'cos of cfg_flags access
*/
static void
bnad_q_num_adjust(struct bnad *bnad, int msix_vectors, int temp)
{
bnad->num_txq_per_tx = 1;
if ((msix_vectors >= (bnad->num_tx * bnad->num_txq_per_tx) +
bnad_rxqs_per_cq + BNAD_MAILBOX_MSIX_VECTORS) &&
(bnad->cfg_flags & BNAD_CF_MSIX)) {
bnad->num_rxp_per_rx = msix_vectors -
(bnad->num_tx * bnad->num_txq_per_tx) -
BNAD_MAILBOX_MSIX_VECTORS;
} else
bnad->num_rxp_per_rx = 1;
}
/* Enable / disable ioceth */
static int
bnad_ioceth_disable(struct bnad *bnad)
{
unsigned long flags;
int err = 0;
spin_lock_irqsave(&bnad->bna_lock, flags);
init_completion(&bnad->bnad_completions.ioc_comp);
bna_ioceth_disable(&bnad->bna.ioceth, BNA_HARD_CLEANUP);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
wait_for_completion_timeout(&bnad->bnad_completions.ioc_comp,
msecs_to_jiffies(BNAD_IOCETH_TIMEOUT));
err = bnad->bnad_completions.ioc_comp_status;
return err;
}
static int
bnad_ioceth_enable(struct bnad *bnad)
{
int err = 0;
unsigned long flags;
spin_lock_irqsave(&bnad->bna_lock, flags);
init_completion(&bnad->bnad_completions.ioc_comp);
bnad->bnad_completions.ioc_comp_status = BNA_CB_WAITING;
bna_ioceth_enable(&bnad->bna.ioceth);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
wait_for_completion_timeout(&bnad->bnad_completions.ioc_comp,
msecs_to_jiffies(BNAD_IOCETH_TIMEOUT));
err = bnad->bnad_completions.ioc_comp_status;
return err;
}
/* Free BNA resources */
static void
bnad_res_free(struct bnad *bnad, struct bna_res_info *res_info,
u32 res_val_max)
{
int i;
for (i = 0; i < res_val_max; i++)
bnad_mem_free(bnad, &res_info[i].res_u.mem_info);
}
/* Allocates memory and interrupt resources for BNA */
static int
bnad_res_alloc(struct bnad *bnad, struct bna_res_info *res_info,
u32 res_val_max)
{
int i, err;
for (i = 0; i < res_val_max; i++) {
err = bnad_mem_alloc(bnad, &res_info[i].res_u.mem_info);
if (err)
goto err_return;
}
return 0;
err_return:
bnad_res_free(bnad, res_info, res_val_max);
return err;
}
/* Interrupt enable / disable */
static void
bnad_enable_msix(struct bnad *bnad)
{
int i, ret;
unsigned long flags;
spin_lock_irqsave(&bnad->bna_lock, flags);
if (!(bnad->cfg_flags & BNAD_CF_MSIX)) {
spin_unlock_irqrestore(&bnad->bna_lock, flags);
return;
}
spin_unlock_irqrestore(&bnad->bna_lock, flags);
if (bnad->msix_table)
return;
bnad->msix_table =
kcalloc(bnad->msix_num, sizeof(struct msix_entry), GFP_KERNEL);
if (!bnad->msix_table)
goto intx_mode;
for (i = 0; i < bnad->msix_num; i++)
bnad->msix_table[i].entry = i;
ret = pci_enable_msix_range(bnad->pcidev, bnad->msix_table,
1, bnad->msix_num);
if (ret < 0) {
goto intx_mode;
} else if (ret < bnad->msix_num) {
dev_warn(&bnad->pcidev->dev,
"%d MSI-X vectors allocated < %d requested\n",
ret, bnad->msix_num);
spin_lock_irqsave(&bnad->bna_lock, flags);
/* ret = #of vectors that we got */
bnad_q_num_adjust(bnad, (ret - BNAD_MAILBOX_MSIX_VECTORS) / 2,
(ret - BNAD_MAILBOX_MSIX_VECTORS) / 2);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
bnad->msix_num = BNAD_NUM_TXQ + BNAD_NUM_RXP +
BNAD_MAILBOX_MSIX_VECTORS;
if (bnad->msix_num > ret) {
pci_disable_msix(bnad->pcidev);
goto intx_mode;
}
}
pci_intx(bnad->pcidev, 0);
return;
intx_mode:
dev_warn(&bnad->pcidev->dev,
"MSI-X enable failed - operating in INTx mode\n");
kfree(bnad->msix_table);
bnad->msix_table = NULL;
bnad->msix_num = 0;
spin_lock_irqsave(&bnad->bna_lock, flags);
bnad->cfg_flags &= ~BNAD_CF_MSIX;
bnad_q_num_init(bnad);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
}
static void
bnad_disable_msix(struct bnad *bnad)
{
u32 cfg_flags;
unsigned long flags;
spin_lock_irqsave(&bnad->bna_lock, flags);
cfg_flags = bnad->cfg_flags;
if (bnad->cfg_flags & BNAD_CF_MSIX)
bnad->cfg_flags &= ~BNAD_CF_MSIX;
spin_unlock_irqrestore(&bnad->bna_lock, flags);
if (cfg_flags & BNAD_CF_MSIX) {
pci_disable_msix(bnad->pcidev);
kfree(bnad->msix_table);
bnad->msix_table = NULL;
}
}
/* Netdev entry points */
static int
bnad_open(struct net_device *netdev)
{
int err;
struct bnad *bnad = netdev_priv(netdev);
struct bna_pause_config pause_config;
unsigned long flags;
mutex_lock(&bnad->conf_mutex);
/* Tx */
err = bnad_setup_tx(bnad, 0);
if (err)
goto err_return;
/* Rx */
err = bnad_setup_rx(bnad, 0);
if (err)
goto cleanup_tx;
/* Port */
pause_config.tx_pause = 0;
pause_config.rx_pause = 0;
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_enet_mtu_set(&bnad->bna.enet,
BNAD_FRAME_SIZE(bnad->netdev->mtu), NULL);
bna_enet_pause_config(&bnad->bna.enet, &pause_config);
bna_enet_enable(&bnad->bna.enet);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
/* Enable broadcast */
bnad_enable_default_bcast(bnad);
/* Restore VLANs, if any */
bnad_restore_vlans(bnad, 0);
/* Set the UCAST address */
spin_lock_irqsave(&bnad->bna_lock, flags);
bnad_mac_addr_set_locked(bnad, netdev->dev_addr);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
/* Start the stats timer */
bnad_stats_timer_start(bnad);
mutex_unlock(&bnad->conf_mutex);
return 0;
cleanup_tx:
bnad_destroy_tx(bnad, 0);
err_return:
mutex_unlock(&bnad->conf_mutex);
return err;
}
static int
bnad_stop(struct net_device *netdev)
{
struct bnad *bnad = netdev_priv(netdev);
unsigned long flags;
mutex_lock(&bnad->conf_mutex);
/* Stop the stats timer */
bnad_stats_timer_stop(bnad);
init_completion(&bnad->bnad_completions.enet_comp);
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_enet_disable(&bnad->bna.enet, BNA_HARD_CLEANUP,
bnad_cb_enet_disabled);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
wait_for_completion(&bnad->bnad_completions.enet_comp);
bnad_destroy_tx(bnad, 0);
bnad_destroy_rx(bnad, 0);
/* Synchronize mailbox IRQ */
bnad_mbox_irq_sync(bnad);
mutex_unlock(&bnad->conf_mutex);
return 0;
}
/* TX */
/* Returns 0 for success */
static int
bnad_txq_wi_prepare(struct bnad *bnad, struct bna_tcb *tcb,
struct sk_buff *skb, struct bna_txq_entry *txqent)
{
u16 flags = 0;
u32 gso_size;
u16 vlan_tag = 0;
if (skb_vlan_tag_present(skb)) {
vlan_tag = (u16)skb_vlan_tag_get(skb);
flags |= (BNA_TXQ_WI_CF_INS_PRIO | BNA_TXQ_WI_CF_INS_VLAN);
}
if (test_bit(BNAD_RF_CEE_RUNNING, &bnad->run_flags)) {
vlan_tag = ((tcb->priority & 0x7) << VLAN_PRIO_SHIFT)
| (vlan_tag & 0x1fff);
flags |= (BNA_TXQ_WI_CF_INS_PRIO | BNA_TXQ_WI_CF_INS_VLAN);
}
txqent->hdr.wi.vlan_tag = htons(vlan_tag);
if (skb_is_gso(skb)) {
gso_size = skb_shinfo(skb)->gso_size;
if (unlikely(gso_size > bnad->netdev->mtu)) {
BNAD_UPDATE_CTR(bnad, tx_skb_mss_too_long);
return -EINVAL;
}
if (unlikely((gso_size + skb_tcp_all_headers(skb)) >= skb->len)) {
txqent->hdr.wi.opcode = htons(BNA_TXQ_WI_SEND);
txqent->hdr.wi.lso_mss = 0;
BNAD_UPDATE_CTR(bnad, tx_skb_tso_too_short);
} else {
txqent->hdr.wi.opcode = htons(BNA_TXQ_WI_SEND_LSO);
txqent->hdr.wi.lso_mss = htons(gso_size);
}
if (bnad_tso_prepare(bnad, skb)) {
BNAD_UPDATE_CTR(bnad, tx_skb_tso_prepare);
return -EINVAL;
}
flags |= (BNA_TXQ_WI_CF_IP_CKSUM | BNA_TXQ_WI_CF_TCP_CKSUM);
txqent->hdr.wi.l4_hdr_size_n_offset =
htons(BNA_TXQ_WI_L4_HDR_N_OFFSET(
tcp_hdrlen(skb) >> 2, skb_transport_offset(skb)));
} else {
txqent->hdr.wi.opcode = htons(BNA_TXQ_WI_SEND);
txqent->hdr.wi.lso_mss = 0;
if (unlikely(skb->len > (bnad->netdev->mtu + VLAN_ETH_HLEN))) {
BNAD_UPDATE_CTR(bnad, tx_skb_non_tso_too_long);
return -EINVAL;
}
if (skb->ip_summed == CHECKSUM_PARTIAL) {
__be16 net_proto = vlan_get_protocol(skb);
u8 proto = 0;
if (net_proto == htons(ETH_P_IP))
proto = ip_hdr(skb)->protocol;
#ifdef NETIF_F_IPV6_CSUM
else if (net_proto == htons(ETH_P_IPV6)) {
/* nexthdr may not be TCP immediately. */
proto = ipv6_hdr(skb)->nexthdr;
}
#endif
if (proto == IPPROTO_TCP) {
flags |= BNA_TXQ_WI_CF_TCP_CKSUM;
txqent->hdr.wi.l4_hdr_size_n_offset =
htons(BNA_TXQ_WI_L4_HDR_N_OFFSET
(0, skb_transport_offset(skb)));
BNAD_UPDATE_CTR(bnad, tcpcsum_offload);
if (unlikely(skb_headlen(skb) <
skb_tcp_all_headers(skb))) {
BNAD_UPDATE_CTR(bnad, tx_skb_tcp_hdr);
return -EINVAL;
}
} else if (proto == IPPROTO_UDP) {
flags |= BNA_TXQ_WI_CF_UDP_CKSUM;
txqent->hdr.wi.l4_hdr_size_n_offset =
htons(BNA_TXQ_WI_L4_HDR_N_OFFSET
(0, skb_transport_offset(skb)));
BNAD_UPDATE_CTR(bnad, udpcsum_offload);
if (unlikely(skb_headlen(skb) <
skb_transport_offset(skb) +
sizeof(struct udphdr))) {
BNAD_UPDATE_CTR(bnad, tx_skb_udp_hdr);
return -EINVAL;
}
} else {
BNAD_UPDATE_CTR(bnad, tx_skb_csum_err);
return -EINVAL;
}
} else
txqent->hdr.wi.l4_hdr_size_n_offset = 0;
}
txqent->hdr.wi.flags = htons(flags);
txqent->hdr.wi.frame_length = htonl(skb->len);
return 0;
}
/*
* bnad_start_xmit : Netdev entry point for Transmit
* Called under lock held by net_device
*/
static netdev_tx_t
bnad_start_xmit(struct sk_buff *skb, struct net_device *netdev)
{
struct bnad *bnad = netdev_priv(netdev);
u32 txq_id = 0;
struct bna_tcb *tcb = NULL;
struct bnad_tx_unmap *unmap_q, *unmap, *head_unmap;
u32 prod, q_depth, vect_id;
u32 wis, vectors, len;
int i;
dma_addr_t dma_addr;
struct bna_txq_entry *txqent;
len = skb_headlen(skb);
/* Sanity checks for the skb */
if (unlikely(skb->len <= ETH_HLEN)) {
dev_kfree_skb_any(skb);
BNAD_UPDATE_CTR(bnad, tx_skb_too_short);
return NETDEV_TX_OK;
}
if (unlikely(len > BFI_TX_MAX_DATA_PER_VECTOR)) {
dev_kfree_skb_any(skb);
BNAD_UPDATE_CTR(bnad, tx_skb_headlen_zero);
return NETDEV_TX_OK;
}
if (unlikely(len == 0)) {
dev_kfree_skb_any(skb);
BNAD_UPDATE_CTR(bnad, tx_skb_headlen_zero);
return NETDEV_TX_OK;
}
tcb = bnad->tx_info[0].tcb[txq_id];
/*
* Takes care of the Tx that is scheduled between clearing the flag
* and the netif_tx_stop_all_queues() call.
*/
if (unlikely(!tcb || !test_bit(BNAD_TXQ_TX_STARTED, &tcb->flags))) {
dev_kfree_skb_any(skb);
BNAD_UPDATE_CTR(bnad, tx_skb_stopping);
return NETDEV_TX_OK;
}
q_depth = tcb->q_depth;
prod = tcb->producer_index;
unmap_q = tcb->unmap_q;
vectors = 1 + skb_shinfo(skb)->nr_frags;
wis = BNA_TXQ_WI_NEEDED(vectors); /* 4 vectors per work item */
if (unlikely(vectors > BFI_TX_MAX_VECTORS_PER_PKT)) {
dev_kfree_skb_any(skb);
BNAD_UPDATE_CTR(bnad, tx_skb_max_vectors);
return NETDEV_TX_OK;
}
/* Check for available TxQ resources */
if (unlikely(wis > BNA_QE_FREE_CNT(tcb, q_depth))) {
if ((*tcb->hw_consumer_index != tcb->consumer_index) &&
!test_and_set_bit(BNAD_TXQ_FREE_SENT, &tcb->flags)) {
u32 sent;
sent = bnad_txcmpl_process(bnad, tcb);
if (likely(test_bit(BNAD_TXQ_TX_STARTED, &tcb->flags)))
bna_ib_ack(tcb->i_dbell, sent);
smp_mb__before_atomic();
clear_bit(BNAD_TXQ_FREE_SENT, &tcb->flags);
} else {
netif_stop_queue(netdev);
BNAD_UPDATE_CTR(bnad, netif_queue_stop);
}
smp_mb();
/*
* Check again to deal with race condition between
* netif_stop_queue here, and netif_wake_queue in
* interrupt handler which is not inside netif tx lock.
*/
if (likely(wis > BNA_QE_FREE_CNT(tcb, q_depth))) {
BNAD_UPDATE_CTR(bnad, netif_queue_stop);
return NETDEV_TX_BUSY;
} else {
netif_wake_queue(netdev);
BNAD_UPDATE_CTR(bnad, netif_queue_wakeup);
}
}
txqent = &((struct bna_txq_entry *)tcb->sw_q)[prod];
head_unmap = &unmap_q[prod];
/* Program the opcode, flags, frame_len, num_vectors in WI */
if (bnad_txq_wi_prepare(bnad, tcb, skb, txqent)) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
txqent->hdr.wi.reserved = 0;
txqent->hdr.wi.num_vectors = vectors;
head_unmap->skb = skb;
head_unmap->nvecs = 0;
/* Program the vectors */
unmap = head_unmap;
dma_addr = dma_map_single(&bnad->pcidev->dev, skb->data,
len, DMA_TO_DEVICE);
if (dma_mapping_error(&bnad->pcidev->dev, dma_addr)) {
dev_kfree_skb_any(skb);
BNAD_UPDATE_CTR(bnad, tx_skb_map_failed);
return NETDEV_TX_OK;
}
BNA_SET_DMA_ADDR(dma_addr, &txqent->vector[0].host_addr);
txqent->vector[0].length = htons(len);
dma_unmap_addr_set(&unmap->vectors[0], dma_addr, dma_addr);
head_unmap->nvecs++;
for (i = 0, vect_id = 0; i < vectors - 1; i++) {
const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
u32 size = skb_frag_size(frag);
if (unlikely(size == 0)) {
/* Undo the changes starting at tcb->producer_index */
bnad_tx_buff_unmap(bnad, unmap_q, q_depth,
tcb->producer_index);
dev_kfree_skb_any(skb);
BNAD_UPDATE_CTR(bnad, tx_skb_frag_zero);
return NETDEV_TX_OK;
}
len += size;
vect_id++;
if (vect_id == BFI_TX_MAX_VECTORS_PER_WI) {
vect_id = 0;
BNA_QE_INDX_INC(prod, q_depth);
txqent = &((struct bna_txq_entry *)tcb->sw_q)[prod];
txqent->hdr.wi_ext.opcode = htons(BNA_TXQ_WI_EXTENSION);
unmap = &unmap_q[prod];
}
dma_addr = skb_frag_dma_map(&bnad->pcidev->dev, frag,
0, size, DMA_TO_DEVICE);
if (dma_mapping_error(&bnad->pcidev->dev, dma_addr)) {
/* Undo the changes starting at tcb->producer_index */
bnad_tx_buff_unmap(bnad, unmap_q, q_depth,
tcb->producer_index);
dev_kfree_skb_any(skb);
BNAD_UPDATE_CTR(bnad, tx_skb_map_failed);
return NETDEV_TX_OK;
}
dma_unmap_len_set(&unmap->vectors[vect_id], dma_len, size);
BNA_SET_DMA_ADDR(dma_addr, &txqent->vector[vect_id].host_addr);
txqent->vector[vect_id].length = htons(size);
dma_unmap_addr_set(&unmap->vectors[vect_id], dma_addr,
dma_addr);
head_unmap->nvecs++;
}
if (unlikely(len != skb->len)) {
/* Undo the changes starting at tcb->producer_index */
bnad_tx_buff_unmap(bnad, unmap_q, q_depth, tcb->producer_index);
dev_kfree_skb_any(skb);
BNAD_UPDATE_CTR(bnad, tx_skb_len_mismatch);
return NETDEV_TX_OK;
}
BNA_QE_INDX_INC(prod, q_depth);
tcb->producer_index = prod;
wmb();
if (unlikely(!test_bit(BNAD_TXQ_TX_STARTED, &tcb->flags)))
return NETDEV_TX_OK;
skb_tx_timestamp(skb);
bna_txq_prod_indx_doorbell(tcb);
return NETDEV_TX_OK;
}
/*
* Used spin_lock to synchronize reading of stats structures, which
* is written by BNA under the same lock.
*/
static void
bnad_get_stats64(struct net_device *netdev, struct rtnl_link_stats64 *stats)
{
struct bnad *bnad = netdev_priv(netdev);
unsigned long flags;
spin_lock_irqsave(&bnad->bna_lock, flags);
bnad_netdev_qstats_fill(bnad, stats);
bnad_netdev_hwstats_fill(bnad, stats);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
}
static void
bnad_set_rx_ucast_fltr(struct bnad *bnad)
{
struct net_device *netdev = bnad->netdev;
int uc_count = netdev_uc_count(netdev);
enum bna_cb_status ret;
u8 *mac_list;
struct netdev_hw_addr *ha;
int entry;
if (netdev_uc_empty(bnad->netdev)) {
bna_rx_ucast_listset(bnad->rx_info[0].rx, 0, NULL);
return;
}
if (uc_count > bna_attr(&bnad->bna)->num_ucmac)
goto mode_default;
mac_list = kcalloc(ETH_ALEN, uc_count, GFP_ATOMIC);
if (mac_list == NULL)
goto mode_default;
entry = 0;
netdev_for_each_uc_addr(ha, netdev) {
ether_addr_copy(&mac_list[entry * ETH_ALEN], &ha->addr[0]);
entry++;
}
ret = bna_rx_ucast_listset(bnad->rx_info[0].rx, entry, mac_list);
kfree(mac_list);
if (ret != BNA_CB_SUCCESS)
goto mode_default;
return;
/* ucast packets not in UCAM are routed to default function */
mode_default:
bnad->cfg_flags |= BNAD_CF_DEFAULT;
bna_rx_ucast_listset(bnad->rx_info[0].rx, 0, NULL);
}
static void
bnad_set_rx_mcast_fltr(struct bnad *bnad)
{
struct net_device *netdev = bnad->netdev;
int mc_count = netdev_mc_count(netdev);
enum bna_cb_status ret;
u8 *mac_list;
if (netdev->flags & IFF_ALLMULTI)
goto mode_allmulti;
if (netdev_mc_empty(netdev))
return;
if (mc_count > bna_attr(&bnad->bna)->num_mcmac)
goto mode_allmulti;
mac_list = kcalloc(mc_count + 1, ETH_ALEN, GFP_ATOMIC);
if (mac_list == NULL)
goto mode_allmulti;
ether_addr_copy(&mac_list[0], &bnad_bcast_addr[0]);
/* copy rest of the MCAST addresses */
bnad_netdev_mc_list_get(netdev, mac_list);
ret = bna_rx_mcast_listset(bnad->rx_info[0].rx, mc_count + 1, mac_list);
kfree(mac_list);
if (ret != BNA_CB_SUCCESS)
goto mode_allmulti;
return;
mode_allmulti:
bnad->cfg_flags |= BNAD_CF_ALLMULTI;
bna_rx_mcast_delall(bnad->rx_info[0].rx);
}
void
bnad_set_rx_mode(struct net_device *netdev)
{
struct bnad *bnad = netdev_priv(netdev);
enum bna_rxmode new_mode, mode_mask;
unsigned long flags;
spin_lock_irqsave(&bnad->bna_lock, flags);
if (bnad->rx_info[0].rx == NULL) {
spin_unlock_irqrestore(&bnad->bna_lock, flags);
return;
}
/* clear bnad flags to update it with new settings */
bnad->cfg_flags &= ~(BNAD_CF_PROMISC | BNAD_CF_DEFAULT |
BNAD_CF_ALLMULTI);
new_mode = 0;
if (netdev->flags & IFF_PROMISC) {
new_mode |= BNAD_RXMODE_PROMISC_DEFAULT;
bnad->cfg_flags |= BNAD_CF_PROMISC;
} else {
bnad_set_rx_mcast_fltr(bnad);
if (bnad->cfg_flags & BNAD_CF_ALLMULTI)
new_mode |= BNA_RXMODE_ALLMULTI;
bnad_set_rx_ucast_fltr(bnad);
if (bnad->cfg_flags & BNAD_CF_DEFAULT)
new_mode |= BNA_RXMODE_DEFAULT;
}
mode_mask = BNA_RXMODE_PROMISC | BNA_RXMODE_DEFAULT |
BNA_RXMODE_ALLMULTI;
bna_rx_mode_set(bnad->rx_info[0].rx, new_mode, mode_mask);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
}
/*
* bna_lock is used to sync writes to netdev->addr
* conf_lock cannot be used since this call may be made
* in a non-blocking context.
*/
static int
bnad_set_mac_address(struct net_device *netdev, void *addr)
{
int err;
struct bnad *bnad = netdev_priv(netdev);
struct sockaddr *sa = (struct sockaddr *)addr;
unsigned long flags;
spin_lock_irqsave(&bnad->bna_lock, flags);
err = bnad_mac_addr_set_locked(bnad, sa->sa_data);
if (!err)
eth_hw_addr_set(netdev, sa->sa_data);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
return err;
}
static int
bnad_mtu_set(struct bnad *bnad, int frame_size)
{
unsigned long flags;
init_completion(&bnad->bnad_completions.mtu_comp);
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_enet_mtu_set(&bnad->bna.enet, frame_size, bnad_cb_enet_mtu_set);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
wait_for_completion(&bnad->bnad_completions.mtu_comp);
return bnad->bnad_completions.mtu_comp_status;
}
static int
bnad_change_mtu(struct net_device *netdev, int new_mtu)
{
int err, mtu;
struct bnad *bnad = netdev_priv(netdev);
u32 frame, new_frame;
mutex_lock(&bnad->conf_mutex);
mtu = netdev->mtu;
netdev->mtu = new_mtu;
frame = BNAD_FRAME_SIZE(mtu);
new_frame = BNAD_FRAME_SIZE(new_mtu);
/* check if multi-buffer needs to be enabled */
if (BNAD_PCI_DEV_IS_CAT2(bnad) &&
netif_running(bnad->netdev)) {
/* only when transition is over 4K */
if ((frame <= 4096 && new_frame > 4096) ||
(frame > 4096 && new_frame <= 4096))
bnad_reinit_rx(bnad);
}
err = bnad_mtu_set(bnad, new_frame);
if (err)
err = -EBUSY;
mutex_unlock(&bnad->conf_mutex);
return err;
}
static int
bnad_vlan_rx_add_vid(struct net_device *netdev, __be16 proto, u16 vid)
{
struct bnad *bnad = netdev_priv(netdev);
unsigned long flags;
if (!bnad->rx_info[0].rx)
return 0;
mutex_lock(&bnad->conf_mutex);
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_rx_vlan_add(bnad->rx_info[0].rx, vid);
set_bit(vid, bnad->active_vlans);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
mutex_unlock(&bnad->conf_mutex);
return 0;
}
static int
bnad_vlan_rx_kill_vid(struct net_device *netdev, __be16 proto, u16 vid)
{
struct bnad *bnad = netdev_priv(netdev);
unsigned long flags;
if (!bnad->rx_info[0].rx)
return 0;
mutex_lock(&bnad->conf_mutex);
spin_lock_irqsave(&bnad->bna_lock, flags);
clear_bit(vid, bnad->active_vlans);
bna_rx_vlan_del(bnad->rx_info[0].rx, vid);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
mutex_unlock(&bnad->conf_mutex);
return 0;
}
static int bnad_set_features(struct net_device *dev, netdev_features_t features)
{
struct bnad *bnad = netdev_priv(dev);
netdev_features_t changed = features ^ dev->features;
if ((changed & NETIF_F_HW_VLAN_CTAG_RX) && netif_running(dev)) {
unsigned long flags;
spin_lock_irqsave(&bnad->bna_lock, flags);
if (features & NETIF_F_HW_VLAN_CTAG_RX)
bna_rx_vlan_strip_enable(bnad->rx_info[0].rx);
else
bna_rx_vlan_strip_disable(bnad->rx_info[0].rx);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
}
return 0;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void
bnad_netpoll(struct net_device *netdev)
{
struct bnad *bnad = netdev_priv(netdev);
struct bnad_rx_info *rx_info;
struct bnad_rx_ctrl *rx_ctrl;
u32 curr_mask;
int i, j;
if (!(bnad->cfg_flags & BNAD_CF_MSIX)) {
bna_intx_disable(&bnad->bna, curr_mask);
bnad_isr(bnad->pcidev->irq, netdev);
bna_intx_enable(&bnad->bna, curr_mask);
} else {
/*
* Tx processing may happen in sending context, so no need
* to explicitly process completions here
*/
/* Rx processing */
for (i = 0; i < bnad->num_rx; i++) {
rx_info = &bnad->rx_info[i];
if (!rx_info->rx)
continue;
for (j = 0; j < bnad->num_rxp_per_rx; j++) {
rx_ctrl = &rx_info->rx_ctrl[j];
if (rx_ctrl->ccb)
bnad_netif_rx_schedule_poll(bnad,
rx_ctrl->ccb);
}
}
}
}
#endif
static const struct net_device_ops bnad_netdev_ops = {
.ndo_open = bnad_open,
.ndo_stop = bnad_stop,
.ndo_start_xmit = bnad_start_xmit,
.ndo_get_stats64 = bnad_get_stats64,
.ndo_set_rx_mode = bnad_set_rx_mode,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = bnad_set_mac_address,
.ndo_change_mtu = bnad_change_mtu,
.ndo_vlan_rx_add_vid = bnad_vlan_rx_add_vid,
.ndo_vlan_rx_kill_vid = bnad_vlan_rx_kill_vid,
.ndo_set_features = bnad_set_features,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = bnad_netpoll
#endif
};
static void
bnad_netdev_init(struct bnad *bnad)
{
struct net_device *netdev = bnad->netdev;
netdev->hw_features = NETIF_F_SG | NETIF_F_RXCSUM |
NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM |
NETIF_F_TSO | NETIF_F_TSO6 | NETIF_F_HW_VLAN_CTAG_TX |
NETIF_F_HW_VLAN_CTAG_RX;
netdev->vlan_features = NETIF_F_SG | NETIF_F_HIGHDMA |
NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM |
NETIF_F_TSO | NETIF_F_TSO6;
netdev->features |= netdev->hw_features | NETIF_F_HW_VLAN_CTAG_FILTER |
NETIF_F_HIGHDMA;
netdev->mem_start = bnad->mmio_start;
netdev->mem_end = bnad->mmio_start + bnad->mmio_len - 1;
/* MTU range: 46 - 9000 */
netdev->min_mtu = ETH_ZLEN - ETH_HLEN;
netdev->max_mtu = BNAD_JUMBO_MTU;
netdev->netdev_ops = &bnad_netdev_ops;
bnad_set_ethtool_ops(netdev);
}
/*
* 1. Initialize the bnad structure
* 2. Setup netdev pointer in pci_dev
* 3. Initialize no. of TxQ & CQs & MSIX vectors
* 4. Initialize work queue.
*/
static int
bnad_init(struct bnad *bnad,
struct pci_dev *pdev, struct net_device *netdev)
{
unsigned long flags;
SET_NETDEV_DEV(netdev, &pdev->dev);
pci_set_drvdata(pdev, netdev);
bnad->netdev = netdev;
bnad->pcidev = pdev;
bnad->mmio_start = pci_resource_start(pdev, 0);
bnad->mmio_len = pci_resource_len(pdev, 0);
bnad->bar0 = ioremap(bnad->mmio_start, bnad->mmio_len);
if (!bnad->bar0) {
dev_err(&pdev->dev, "ioremap for bar0 failed\n");
return -ENOMEM;
}
dev_info(&pdev->dev, "bar0 mapped to %p, len %llu\n", bnad->bar0,
(unsigned long long) bnad->mmio_len);
spin_lock_irqsave(&bnad->bna_lock, flags);
if (!bnad_msix_disable)
bnad->cfg_flags = BNAD_CF_MSIX;
bnad->cfg_flags |= BNAD_CF_DIM_ENABLED;
bnad_q_num_init(bnad);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
bnad->msix_num = (bnad->num_tx * bnad->num_txq_per_tx) +
(bnad->num_rx * bnad->num_rxp_per_rx) +
BNAD_MAILBOX_MSIX_VECTORS;
bnad->txq_depth = BNAD_TXQ_DEPTH;
bnad->rxq_depth = BNAD_RXQ_DEPTH;
bnad->tx_coalescing_timeo = BFI_TX_COALESCING_TIMEO;
bnad->rx_coalescing_timeo = BFI_RX_COALESCING_TIMEO;
sprintf(bnad->wq_name, "%s_wq_%d", BNAD_NAME, bnad->id);
bnad->work_q = create_singlethread_workqueue(bnad->wq_name);
if (!bnad->work_q) {
iounmap(bnad->bar0);
return -ENOMEM;
}
return 0;
}
/*
* Must be called after bnad_pci_uninit()
* so that iounmap() and pci_set_drvdata(NULL)
* happens only after PCI uninitialization.
*/
static void
bnad_uninit(struct bnad *bnad)
{
if (bnad->work_q) {
destroy_workqueue(bnad->work_q);
bnad->work_q = NULL;
}
if (bnad->bar0)
iounmap(bnad->bar0);
}
/*
* Initialize locks
a) Per ioceth mutes used for serializing configuration
changes from OS interface
b) spin lock used to protect bna state machine
*/
static void
bnad_lock_init(struct bnad *bnad)
{
spin_lock_init(&bnad->bna_lock);
mutex_init(&bnad->conf_mutex);
}
static void
bnad_lock_uninit(struct bnad *bnad)
{
mutex_destroy(&bnad->conf_mutex);
}
/* PCI Initialization */
static int
bnad_pci_init(struct bnad *bnad, struct pci_dev *pdev)
{
int err;
err = pci_enable_device(pdev);
if (err)
return err;
err = pci_request_regions(pdev, BNAD_NAME);
if (err)
goto disable_device;
err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
if (err)
goto release_regions;
pci_set_master(pdev);
return 0;
release_regions:
pci_release_regions(pdev);
disable_device:
pci_disable_device(pdev);
return err;
}
static void
bnad_pci_uninit(struct pci_dev *pdev)
{
pci_release_regions(pdev);
pci_disable_device(pdev);
}
static int
bnad_pci_probe(struct pci_dev *pdev,
const struct pci_device_id *pcidev_id)
{
int err;
struct bnad *bnad;
struct bna *bna;
struct net_device *netdev;
struct bfa_pcidev pcidev_info;
unsigned long flags;
mutex_lock(&bnad_fwimg_mutex);
if (!cna_get_firmware_buf(pdev)) {
mutex_unlock(&bnad_fwimg_mutex);
dev_err(&pdev->dev, "failed to load firmware image!\n");
return -ENODEV;
}
mutex_unlock(&bnad_fwimg_mutex);
/*
* Allocates sizeof(struct net_device + struct bnad)
* bnad = netdev->priv
*/
netdev = alloc_etherdev(sizeof(struct bnad));
if (!netdev) {
err = -ENOMEM;
return err;
}
bnad = netdev_priv(netdev);
bnad_lock_init(bnad);
bnad->id = atomic_inc_return(&bna_id) - 1;
mutex_lock(&bnad->conf_mutex);
/* PCI initialization */
err = bnad_pci_init(bnad, pdev);
if (err)
goto unlock_mutex;
/*
* Initialize bnad structure
* Setup relation between pci_dev & netdev
*/
err = bnad_init(bnad, pdev, netdev);
if (err)
goto pci_uninit;
/* Initialize netdev structure, set up ethtool ops */
bnad_netdev_init(bnad);
/* Set link to down state */
netif_carrier_off(netdev);
/* Setup the debugfs node for this bfad */
if (bna_debugfs_enable)
bnad_debugfs_init(bnad);
/* Get resource requirement form bna */
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_res_req(&bnad->res_info[0]);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
/* Allocate resources from bna */
err = bnad_res_alloc(bnad, &bnad->res_info[0], BNA_RES_T_MAX);
if (err)
goto drv_uninit;
bna = &bnad->bna;
/* Setup pcidev_info for bna_init() */
pcidev_info.pci_slot = PCI_SLOT(bnad->pcidev->devfn);
pcidev_info.pci_func = PCI_FUNC(bnad->pcidev->devfn);
pcidev_info.device_id = bnad->pcidev->device;
pcidev_info.pci_bar_kva = bnad->bar0;
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_init(bna, bnad, &pcidev_info, &bnad->res_info[0]);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
bnad->stats.bna_stats = &bna->stats;
bnad_enable_msix(bnad);
err = bnad_mbox_irq_alloc(bnad);
if (err)
goto res_free;
/* Set up timers */
timer_setup(&bnad->bna.ioceth.ioc.ioc_timer, bnad_ioc_timeout, 0);
timer_setup(&bnad->bna.ioceth.ioc.hb_timer, bnad_ioc_hb_check, 0);
timer_setup(&bnad->bna.ioceth.ioc.iocpf_timer, bnad_iocpf_timeout, 0);
timer_setup(&bnad->bna.ioceth.ioc.sem_timer, bnad_iocpf_sem_timeout,
0);
/*
* Start the chip
* If the call back comes with error, we bail out.
* This is a catastrophic error.
*/
err = bnad_ioceth_enable(bnad);
if (err) {
dev_err(&pdev->dev, "initialization failed err=%d\n", err);
goto probe_success;
}
spin_lock_irqsave(&bnad->bna_lock, flags);
if (bna_num_txq_set(bna, BNAD_NUM_TXQ + 1) ||
bna_num_rxp_set(bna, BNAD_NUM_RXP + 1)) {
bnad_q_num_adjust(bnad, bna_attr(bna)->num_txq - 1,
bna_attr(bna)->num_rxp - 1);
if (bna_num_txq_set(bna, BNAD_NUM_TXQ + 1) ||
bna_num_rxp_set(bna, BNAD_NUM_RXP + 1))
err = -EIO;
}
spin_unlock_irqrestore(&bnad->bna_lock, flags);
if (err)
goto disable_ioceth;
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_mod_res_req(&bnad->bna, &bnad->mod_res_info[0]);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
err = bnad_res_alloc(bnad, &bnad->mod_res_info[0], BNA_MOD_RES_T_MAX);
if (err) {
err = -EIO;
goto disable_ioceth;
}
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_mod_init(&bnad->bna, &bnad->mod_res_info[0]);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
/* Get the burnt-in mac */
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_enet_perm_mac_get(&bna->enet, bnad->perm_addr);
bnad_set_netdev_perm_addr(bnad);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
mutex_unlock(&bnad->conf_mutex);
/* Finally, reguister with net_device layer */
err = register_netdev(netdev);
if (err) {
dev_err(&pdev->dev, "registering net device failed\n");
goto probe_uninit;
}
set_bit(BNAD_RF_NETDEV_REGISTERED, &bnad->run_flags);
return 0;
probe_success:
mutex_unlock(&bnad->conf_mutex);
return 0;
probe_uninit:
mutex_lock(&bnad->conf_mutex);
bnad_res_free(bnad, &bnad->mod_res_info[0], BNA_MOD_RES_T_MAX);
disable_ioceth:
bnad_ioceth_disable(bnad);
del_timer_sync(&bnad->bna.ioceth.ioc.ioc_timer);
del_timer_sync(&bnad->bna.ioceth.ioc.sem_timer);
del_timer_sync(&bnad->bna.ioceth.ioc.hb_timer);
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_uninit(bna);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
bnad_mbox_irq_free(bnad);
bnad_disable_msix(bnad);
res_free:
bnad_res_free(bnad, &bnad->res_info[0], BNA_RES_T_MAX);
drv_uninit:
/* Remove the debugfs node for this bnad */
kfree(bnad->regdata);
bnad_debugfs_uninit(bnad);
bnad_uninit(bnad);
pci_uninit:
bnad_pci_uninit(pdev);
unlock_mutex:
mutex_unlock(&bnad->conf_mutex);
bnad_lock_uninit(bnad);
free_netdev(netdev);
return err;
}
static void
bnad_pci_remove(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct bnad *bnad;
struct bna *bna;
unsigned long flags;
if (!netdev)
return;
bnad = netdev_priv(netdev);
bna = &bnad->bna;
if (test_and_clear_bit(BNAD_RF_NETDEV_REGISTERED, &bnad->run_flags))
unregister_netdev(netdev);
mutex_lock(&bnad->conf_mutex);
bnad_ioceth_disable(bnad);
del_timer_sync(&bnad->bna.ioceth.ioc.ioc_timer);
del_timer_sync(&bnad->bna.ioceth.ioc.sem_timer);
del_timer_sync(&bnad->bna.ioceth.ioc.hb_timer);
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_uninit(bna);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
bnad_res_free(bnad, &bnad->mod_res_info[0], BNA_MOD_RES_T_MAX);
bnad_res_free(bnad, &bnad->res_info[0], BNA_RES_T_MAX);
bnad_mbox_irq_free(bnad);
bnad_disable_msix(bnad);
bnad_pci_uninit(pdev);
mutex_unlock(&bnad->conf_mutex);
bnad_lock_uninit(bnad);
/* Remove the debugfs node for this bnad */
kfree(bnad->regdata);
bnad_debugfs_uninit(bnad);
bnad_uninit(bnad);
free_netdev(netdev);
}
static const struct pci_device_id bnad_pci_id_table[] = {
{
PCI_DEVICE(PCI_VENDOR_ID_BROCADE,
PCI_DEVICE_ID_BROCADE_CT),
.class = PCI_CLASS_NETWORK_ETHERNET << 8,
.class_mask = 0xffff00
},
{
PCI_DEVICE(PCI_VENDOR_ID_BROCADE,
BFA_PCI_DEVICE_ID_CT2),
.class = PCI_CLASS_NETWORK_ETHERNET << 8,
.class_mask = 0xffff00
},
{0, },
};
MODULE_DEVICE_TABLE(pci, bnad_pci_id_table);
static struct pci_driver bnad_pci_driver = {
.name = BNAD_NAME,
.id_table = bnad_pci_id_table,
.probe = bnad_pci_probe,
.remove = bnad_pci_remove,
};
static int __init
bnad_module_init(void)
{
int err;
bfa_nw_ioc_auto_recover(bnad_ioc_auto_recover);
err = pci_register_driver(&bnad_pci_driver);
if (err < 0) {
pr_err("bna: PCI driver registration failed err=%d\n", err);
return err;
}
return 0;
}
static void __exit
bnad_module_exit(void)
{
pci_unregister_driver(&bnad_pci_driver);
release_firmware(bfi_fw);
}
module_init(bnad_module_init);
module_exit(bnad_module_exit);
MODULE_AUTHOR("Brocade");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("QLogic BR-series 10G PCIe Ethernet driver");
MODULE_FIRMWARE(CNA_FW_FILE_CT);
MODULE_FIRMWARE(CNA_FW_FILE_CT2);
|
linux-master
|
drivers/net/ethernet/brocade/bna/bnad.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Linux network driver for QLogic BR-series Converged Network Adapter.
*/
/*
* Copyright (c) 2005-2014 Brocade Communications Systems, Inc.
* Copyright (c) 2014-2015 QLogic Corporation
* All rights reserved
* www.qlogic.com
*/
#include <linux/firmware.h>
#include "bnad.h"
#include "bfi.h"
#include "cna.h"
const struct firmware *bfi_fw;
static u32 *bfi_image_ct_cna, *bfi_image_ct2_cna;
static u32 bfi_image_ct_cna_size, bfi_image_ct2_cna_size;
static u32 *
cna_read_firmware(struct pci_dev *pdev, u32 **bfi_image,
u32 *bfi_image_size, char *fw_name)
{
const struct firmware *fw;
u32 n;
if (request_firmware(&fw, fw_name, &pdev->dev)) {
dev_alert(&pdev->dev, "can't load firmware %s\n", fw_name);
goto error;
}
*bfi_image = (u32 *)fw->data;
*bfi_image_size = fw->size/sizeof(u32);
bfi_fw = fw;
/* Convert loaded firmware to host order as it is stored in file
* as sequence of LE32 integers.
*/
for (n = 0; n < *bfi_image_size; n++)
le32_to_cpus(*bfi_image + n);
return *bfi_image;
error:
return NULL;
}
u32 *
cna_get_firmware_buf(struct pci_dev *pdev)
{
if (pdev->device == BFA_PCI_DEVICE_ID_CT2) {
if (bfi_image_ct2_cna_size == 0)
cna_read_firmware(pdev, &bfi_image_ct2_cna,
&bfi_image_ct2_cna_size, CNA_FW_FILE_CT2);
return bfi_image_ct2_cna;
} else if (bfa_asic_id_ct(pdev->device)) {
if (bfi_image_ct_cna_size == 0)
cna_read_firmware(pdev, &bfi_image_ct_cna,
&bfi_image_ct_cna_size, CNA_FW_FILE_CT);
return bfi_image_ct_cna;
}
return NULL;
}
u32 *
bfa_cb_image_get_chunk(enum bfi_asic_gen asic_gen, u32 off)
{
switch (asic_gen) {
case BFI_ASIC_GEN_CT:
return (bfi_image_ct_cna + off);
case BFI_ASIC_GEN_CT2:
return (bfi_image_ct2_cna + off);
default:
return NULL;
}
}
u32
bfa_cb_image_get_size(enum bfi_asic_gen asic_gen)
{
switch (asic_gen) {
case BFI_ASIC_GEN_CT:
return bfi_image_ct_cna_size;
case BFI_ASIC_GEN_CT2:
return bfi_image_ct2_cna_size;
default:
return 0;
}
}
|
linux-master
|
drivers/net/ethernet/brocade/bna/cna_fwimg.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Linux network driver for QLogic BR-series Converged Network Adapter.
*/
/*
* Copyright (c) 2005-2014 Brocade Communications Systems, Inc.
* Copyright (c) 2014-2015 QLogic Corporation
* All rights reserved
* www.qlogic.com
*/
#include "bfa_ioc.h"
#include "cna.h"
#include "bfi.h"
#include "bfi_reg.h"
#include "bfa_defs.h"
#define bfa_ioc_ct_sync_pos(__ioc) BIT(bfa_ioc_pcifn(__ioc))
#define BFA_IOC_SYNC_REQD_SH 16
#define bfa_ioc_ct_get_sync_ackd(__val) (__val & 0x0000ffff)
#define bfa_ioc_ct_clear_sync_ackd(__val) (__val & 0xffff0000)
#define bfa_ioc_ct_get_sync_reqd(__val) (__val >> BFA_IOC_SYNC_REQD_SH)
#define bfa_ioc_ct_sync_reqd_pos(__ioc) \
(bfa_ioc_ct_sync_pos(__ioc) << BFA_IOC_SYNC_REQD_SH)
/*
* forward declarations
*/
static bool bfa_ioc_ct_firmware_lock(struct bfa_ioc *ioc);
static void bfa_ioc_ct_firmware_unlock(struct bfa_ioc *ioc);
static void bfa_ioc_ct_reg_init(struct bfa_ioc *ioc);
static void bfa_ioc_ct2_reg_init(struct bfa_ioc *ioc);
static void bfa_ioc_ct_map_port(struct bfa_ioc *ioc);
static void bfa_ioc_ct2_map_port(struct bfa_ioc *ioc);
static void bfa_ioc_ct_isr_mode_set(struct bfa_ioc *ioc, bool msix);
static void bfa_ioc_ct_notify_fail(struct bfa_ioc *ioc);
static void bfa_ioc_ct_ownership_reset(struct bfa_ioc *ioc);
static bool bfa_ioc_ct_sync_start(struct bfa_ioc *ioc);
static void bfa_ioc_ct_sync_join(struct bfa_ioc *ioc);
static void bfa_ioc_ct_sync_leave(struct bfa_ioc *ioc);
static void bfa_ioc_ct_sync_ack(struct bfa_ioc *ioc);
static bool bfa_ioc_ct_sync_complete(struct bfa_ioc *ioc);
static void bfa_ioc_ct_set_cur_ioc_fwstate(
struct bfa_ioc *ioc, enum bfi_ioc_state fwstate);
static enum bfi_ioc_state bfa_ioc_ct_get_cur_ioc_fwstate(struct bfa_ioc *ioc);
static void bfa_ioc_ct_set_alt_ioc_fwstate(
struct bfa_ioc *ioc, enum bfi_ioc_state fwstate);
static enum bfi_ioc_state bfa_ioc_ct_get_alt_ioc_fwstate(struct bfa_ioc *ioc);
static enum bfa_status bfa_ioc_ct_pll_init(void __iomem *rb,
enum bfi_asic_mode asic_mode);
static enum bfa_status bfa_ioc_ct2_pll_init(void __iomem *rb,
enum bfi_asic_mode asic_mode);
static bool bfa_ioc_ct2_lpu_read_stat(struct bfa_ioc *ioc);
static const struct bfa_ioc_hwif nw_hwif_ct = {
.ioc_pll_init = bfa_ioc_ct_pll_init,
.ioc_firmware_lock = bfa_ioc_ct_firmware_lock,
.ioc_firmware_unlock = bfa_ioc_ct_firmware_unlock,
.ioc_reg_init = bfa_ioc_ct_reg_init,
.ioc_map_port = bfa_ioc_ct_map_port,
.ioc_isr_mode_set = bfa_ioc_ct_isr_mode_set,
.ioc_notify_fail = bfa_ioc_ct_notify_fail,
.ioc_ownership_reset = bfa_ioc_ct_ownership_reset,
.ioc_sync_start = bfa_ioc_ct_sync_start,
.ioc_sync_join = bfa_ioc_ct_sync_join,
.ioc_sync_leave = bfa_ioc_ct_sync_leave,
.ioc_sync_ack = bfa_ioc_ct_sync_ack,
.ioc_sync_complete = bfa_ioc_ct_sync_complete,
.ioc_set_fwstate = bfa_ioc_ct_set_cur_ioc_fwstate,
.ioc_get_fwstate = bfa_ioc_ct_get_cur_ioc_fwstate,
.ioc_set_alt_fwstate = bfa_ioc_ct_set_alt_ioc_fwstate,
.ioc_get_alt_fwstate = bfa_ioc_ct_get_alt_ioc_fwstate,
};
static const struct bfa_ioc_hwif nw_hwif_ct2 = {
.ioc_pll_init = bfa_ioc_ct2_pll_init,
.ioc_firmware_lock = bfa_ioc_ct_firmware_lock,
.ioc_firmware_unlock = bfa_ioc_ct_firmware_unlock,
.ioc_reg_init = bfa_ioc_ct2_reg_init,
.ioc_map_port = bfa_ioc_ct2_map_port,
.ioc_lpu_read_stat = bfa_ioc_ct2_lpu_read_stat,
.ioc_isr_mode_set = NULL,
.ioc_notify_fail = bfa_ioc_ct_notify_fail,
.ioc_ownership_reset = bfa_ioc_ct_ownership_reset,
.ioc_sync_start = bfa_ioc_ct_sync_start,
.ioc_sync_join = bfa_ioc_ct_sync_join,
.ioc_sync_leave = bfa_ioc_ct_sync_leave,
.ioc_sync_ack = bfa_ioc_ct_sync_ack,
.ioc_sync_complete = bfa_ioc_ct_sync_complete,
.ioc_set_fwstate = bfa_ioc_ct_set_cur_ioc_fwstate,
.ioc_get_fwstate = bfa_ioc_ct_get_cur_ioc_fwstate,
.ioc_set_alt_fwstate = bfa_ioc_ct_set_alt_ioc_fwstate,
.ioc_get_alt_fwstate = bfa_ioc_ct_get_alt_ioc_fwstate,
};
/* Called from bfa_ioc_attach() to map asic specific calls. */
void
bfa_nw_ioc_set_ct_hwif(struct bfa_ioc *ioc)
{
ioc->ioc_hwif = &nw_hwif_ct;
}
void
bfa_nw_ioc_set_ct2_hwif(struct bfa_ioc *ioc)
{
ioc->ioc_hwif = &nw_hwif_ct2;
}
/* Return true if firmware of current driver matches the running firmware. */
static bool
bfa_ioc_ct_firmware_lock(struct bfa_ioc *ioc)
{
enum bfi_ioc_state ioc_fwstate;
u32 usecnt;
struct bfi_ioc_image_hdr fwhdr;
/**
* If bios boot (flash based) -- do not increment usage count
*/
if (bfa_cb_image_get_size(bfa_ioc_asic_gen(ioc)) <
BFA_IOC_FWIMG_MINSZ)
return true;
bfa_nw_ioc_sem_get(ioc->ioc_regs.ioc_usage_sem_reg);
usecnt = readl(ioc->ioc_regs.ioc_usage_reg);
/**
* If usage count is 0, always return TRUE.
*/
if (usecnt == 0) {
writel(1, ioc->ioc_regs.ioc_usage_reg);
bfa_nw_ioc_sem_release(ioc->ioc_regs.ioc_usage_sem_reg);
writel(0, ioc->ioc_regs.ioc_fail_sync);
return true;
}
ioc_fwstate = readl(ioc->ioc_regs.ioc_fwstate);
/**
* Use count cannot be non-zero and chip in uninitialized state.
*/
BUG_ON(!(ioc_fwstate != BFI_IOC_UNINIT));
/**
* Check if another driver with a different firmware is active
*/
bfa_nw_ioc_fwver_get(ioc, &fwhdr);
if (!bfa_nw_ioc_fwver_cmp(ioc, &fwhdr)) {
bfa_nw_ioc_sem_release(ioc->ioc_regs.ioc_usage_sem_reg);
return false;
}
/**
* Same firmware version. Increment the reference count.
*/
usecnt++;
writel(usecnt, ioc->ioc_regs.ioc_usage_reg);
bfa_nw_ioc_sem_release(ioc->ioc_regs.ioc_usage_sem_reg);
return true;
}
static void
bfa_ioc_ct_firmware_unlock(struct bfa_ioc *ioc)
{
u32 usecnt;
/**
* If bios boot (flash based) -- do not decrement usage count
*/
if (bfa_cb_image_get_size(bfa_ioc_asic_gen(ioc)) <
BFA_IOC_FWIMG_MINSZ)
return;
/**
* decrement usage count
*/
bfa_nw_ioc_sem_get(ioc->ioc_regs.ioc_usage_sem_reg);
usecnt = readl(ioc->ioc_regs.ioc_usage_reg);
BUG_ON(!(usecnt > 0));
usecnt--;
writel(usecnt, ioc->ioc_regs.ioc_usage_reg);
bfa_nw_ioc_sem_release(ioc->ioc_regs.ioc_usage_sem_reg);
}
/* Notify other functions on HB failure. */
static void
bfa_ioc_ct_notify_fail(struct bfa_ioc *ioc)
{
writel(__FW_INIT_HALT_P, ioc->ioc_regs.ll_halt);
writel(__FW_INIT_HALT_P, ioc->ioc_regs.alt_ll_halt);
/* Wait for halt to take effect */
readl(ioc->ioc_regs.ll_halt);
readl(ioc->ioc_regs.alt_ll_halt);
}
/* Host to LPU mailbox message addresses */
static const struct {
u32 hfn_mbox;
u32 lpu_mbox;
u32 hfn_pgn;
} ct_fnreg[] = {
{ HOSTFN0_LPU_MBOX0_0, LPU_HOSTFN0_MBOX0_0, HOST_PAGE_NUM_FN0 },
{ HOSTFN1_LPU_MBOX0_8, LPU_HOSTFN1_MBOX0_8, HOST_PAGE_NUM_FN1 },
{ HOSTFN2_LPU_MBOX0_0, LPU_HOSTFN2_MBOX0_0, HOST_PAGE_NUM_FN2 },
{ HOSTFN3_LPU_MBOX0_8, LPU_HOSTFN3_MBOX0_8, HOST_PAGE_NUM_FN3 }
};
/* Host <-> LPU mailbox command/status registers - port 0 */
static const struct {
u32 hfn;
u32 lpu;
} ct_p0reg[] = {
{ HOSTFN0_LPU0_CMD_STAT, LPU0_HOSTFN0_CMD_STAT },
{ HOSTFN1_LPU0_CMD_STAT, LPU0_HOSTFN1_CMD_STAT },
{ HOSTFN2_LPU0_CMD_STAT, LPU0_HOSTFN2_CMD_STAT },
{ HOSTFN3_LPU0_CMD_STAT, LPU0_HOSTFN3_CMD_STAT }
};
/* Host <-> LPU mailbox command/status registers - port 1 */
static const struct {
u32 hfn;
u32 lpu;
} ct_p1reg[] = {
{ HOSTFN0_LPU1_CMD_STAT, LPU1_HOSTFN0_CMD_STAT },
{ HOSTFN1_LPU1_CMD_STAT, LPU1_HOSTFN1_CMD_STAT },
{ HOSTFN2_LPU1_CMD_STAT, LPU1_HOSTFN2_CMD_STAT },
{ HOSTFN3_LPU1_CMD_STAT, LPU1_HOSTFN3_CMD_STAT }
};
static const struct {
u32 hfn_mbox;
u32 lpu_mbox;
u32 hfn_pgn;
u32 hfn;
u32 lpu;
u32 lpu_read;
} ct2_reg[] = {
{ CT2_HOSTFN_LPU0_MBOX0, CT2_LPU0_HOSTFN_MBOX0, CT2_HOSTFN_PAGE_NUM,
CT2_HOSTFN_LPU0_CMD_STAT, CT2_LPU0_HOSTFN_CMD_STAT,
CT2_HOSTFN_LPU0_READ_STAT},
{ CT2_HOSTFN_LPU1_MBOX0, CT2_LPU1_HOSTFN_MBOX0, CT2_HOSTFN_PAGE_NUM,
CT2_HOSTFN_LPU1_CMD_STAT, CT2_LPU1_HOSTFN_CMD_STAT,
CT2_HOSTFN_LPU1_READ_STAT},
};
static void
bfa_ioc_ct_reg_init(struct bfa_ioc *ioc)
{
void __iomem *rb;
int pcifn = bfa_ioc_pcifn(ioc);
rb = bfa_ioc_bar0(ioc);
ioc->ioc_regs.hfn_mbox = rb + ct_fnreg[pcifn].hfn_mbox;
ioc->ioc_regs.lpu_mbox = rb + ct_fnreg[pcifn].lpu_mbox;
ioc->ioc_regs.host_page_num_fn = rb + ct_fnreg[pcifn].hfn_pgn;
if (ioc->port_id == 0) {
ioc->ioc_regs.heartbeat = rb + BFA_IOC0_HBEAT_REG;
ioc->ioc_regs.ioc_fwstate = rb + BFA_IOC0_STATE_REG;
ioc->ioc_regs.alt_ioc_fwstate = rb + BFA_IOC1_STATE_REG;
ioc->ioc_regs.hfn_mbox_cmd = rb + ct_p0reg[pcifn].hfn;
ioc->ioc_regs.lpu_mbox_cmd = rb + ct_p0reg[pcifn].lpu;
ioc->ioc_regs.ll_halt = rb + FW_INIT_HALT_P0;
ioc->ioc_regs.alt_ll_halt = rb + FW_INIT_HALT_P1;
} else {
ioc->ioc_regs.heartbeat = rb + BFA_IOC1_HBEAT_REG;
ioc->ioc_regs.ioc_fwstate = rb + BFA_IOC1_STATE_REG;
ioc->ioc_regs.alt_ioc_fwstate = rb + BFA_IOC0_STATE_REG;
ioc->ioc_regs.hfn_mbox_cmd = rb + ct_p1reg[pcifn].hfn;
ioc->ioc_regs.lpu_mbox_cmd = rb + ct_p1reg[pcifn].lpu;
ioc->ioc_regs.ll_halt = rb + FW_INIT_HALT_P1;
ioc->ioc_regs.alt_ll_halt = rb + FW_INIT_HALT_P0;
}
/*
* PSS control registers
*/
ioc->ioc_regs.pss_ctl_reg = rb + PSS_CTL_REG;
ioc->ioc_regs.pss_err_status_reg = rb + PSS_ERR_STATUS_REG;
ioc->ioc_regs.app_pll_fast_ctl_reg = rb + APP_PLL_LCLK_CTL_REG;
ioc->ioc_regs.app_pll_slow_ctl_reg = rb + APP_PLL_SCLK_CTL_REG;
/*
* IOC semaphore registers and serialization
*/
ioc->ioc_regs.ioc_sem_reg = rb + HOST_SEM0_REG;
ioc->ioc_regs.ioc_usage_sem_reg = rb + HOST_SEM1_REG;
ioc->ioc_regs.ioc_init_sem_reg = rb + HOST_SEM2_REG;
ioc->ioc_regs.ioc_usage_reg = rb + BFA_FW_USE_COUNT;
ioc->ioc_regs.ioc_fail_sync = rb + BFA_IOC_FAIL_SYNC;
/**
* sram memory access
*/
ioc->ioc_regs.smem_page_start = rb + PSS_SMEM_PAGE_START;
ioc->ioc_regs.smem_pg0 = BFI_IOC_SMEM_PG0_CT;
/*
* err set reg : for notification of hb failure in fcmode
*/
ioc->ioc_regs.err_set = (rb + ERR_SET_REG);
}
static void
bfa_ioc_ct2_reg_init(struct bfa_ioc *ioc)
{
void __iomem *rb;
int port = bfa_ioc_portid(ioc);
rb = bfa_ioc_bar0(ioc);
ioc->ioc_regs.hfn_mbox = rb + ct2_reg[port].hfn_mbox;
ioc->ioc_regs.lpu_mbox = rb + ct2_reg[port].lpu_mbox;
ioc->ioc_regs.host_page_num_fn = rb + ct2_reg[port].hfn_pgn;
ioc->ioc_regs.hfn_mbox_cmd = rb + ct2_reg[port].hfn;
ioc->ioc_regs.lpu_mbox_cmd = rb + ct2_reg[port].lpu;
ioc->ioc_regs.lpu_read_stat = rb + ct2_reg[port].lpu_read;
if (port == 0) {
ioc->ioc_regs.heartbeat = rb + CT2_BFA_IOC0_HBEAT_REG;
ioc->ioc_regs.ioc_fwstate = rb + CT2_BFA_IOC0_STATE_REG;
ioc->ioc_regs.alt_ioc_fwstate = rb + CT2_BFA_IOC1_STATE_REG;
ioc->ioc_regs.ll_halt = rb + FW_INIT_HALT_P0;
ioc->ioc_regs.alt_ll_halt = rb + FW_INIT_HALT_P1;
} else {
ioc->ioc_regs.heartbeat = rb + CT2_BFA_IOC1_HBEAT_REG;
ioc->ioc_regs.ioc_fwstate = rb + CT2_BFA_IOC1_STATE_REG;
ioc->ioc_regs.alt_ioc_fwstate = rb + CT2_BFA_IOC0_STATE_REG;
ioc->ioc_regs.ll_halt = rb + FW_INIT_HALT_P1;
ioc->ioc_regs.alt_ll_halt = rb + FW_INIT_HALT_P0;
}
/*
* PSS control registers
*/
ioc->ioc_regs.pss_ctl_reg = rb + PSS_CTL_REG;
ioc->ioc_regs.pss_err_status_reg = rb + PSS_ERR_STATUS_REG;
ioc->ioc_regs.app_pll_fast_ctl_reg = rb + CT2_APP_PLL_LCLK_CTL_REG;
ioc->ioc_regs.app_pll_slow_ctl_reg = rb + CT2_APP_PLL_SCLK_CTL_REG;
/*
* IOC semaphore registers and serialization
*/
ioc->ioc_regs.ioc_sem_reg = rb + CT2_HOST_SEM0_REG;
ioc->ioc_regs.ioc_usage_sem_reg = rb + CT2_HOST_SEM1_REG;
ioc->ioc_regs.ioc_init_sem_reg = rb + CT2_HOST_SEM2_REG;
ioc->ioc_regs.ioc_usage_reg = rb + CT2_BFA_FW_USE_COUNT;
ioc->ioc_regs.ioc_fail_sync = rb + CT2_BFA_IOC_FAIL_SYNC;
/**
* sram memory access
*/
ioc->ioc_regs.smem_page_start = rb + PSS_SMEM_PAGE_START;
ioc->ioc_regs.smem_pg0 = BFI_IOC_SMEM_PG0_CT;
/*
* err set reg : for notification of hb failure in fcmode
*/
ioc->ioc_regs.err_set = rb + ERR_SET_REG;
}
/* Initialize IOC to port mapping. */
#define FNC_PERS_FN_SHIFT(__fn) ((__fn) * 8)
static void
bfa_ioc_ct_map_port(struct bfa_ioc *ioc)
{
void __iomem *rb = ioc->pcidev.pci_bar_kva;
u32 r32;
/**
* For catapult, base port id on personality register and IOC type
*/
r32 = readl(rb + FNC_PERS_REG);
r32 >>= FNC_PERS_FN_SHIFT(bfa_ioc_pcifn(ioc));
ioc->port_id = (r32 & __F0_PORT_MAP_MK) >> __F0_PORT_MAP_SH;
}
static void
bfa_ioc_ct2_map_port(struct bfa_ioc *ioc)
{
void __iomem *rb = ioc->pcidev.pci_bar_kva;
u32 r32;
r32 = readl(rb + CT2_HOSTFN_PERSONALITY0);
ioc->port_id = ((r32 & __FC_LL_PORT_MAP__MK) >> __FC_LL_PORT_MAP__SH);
}
/* Set interrupt mode for a function: INTX or MSIX */
static void
bfa_ioc_ct_isr_mode_set(struct bfa_ioc *ioc, bool msix)
{
void __iomem *rb = ioc->pcidev.pci_bar_kva;
u32 r32, mode;
r32 = readl(rb + FNC_PERS_REG);
mode = (r32 >> FNC_PERS_FN_SHIFT(bfa_ioc_pcifn(ioc))) &
__F0_INTX_STATUS;
/**
* If already in desired mode, do not change anything
*/
if ((!msix && mode) || (msix && !mode))
return;
if (msix)
mode = __F0_INTX_STATUS_MSIX;
else
mode = __F0_INTX_STATUS_INTA;
r32 &= ~(__F0_INTX_STATUS << FNC_PERS_FN_SHIFT(bfa_ioc_pcifn(ioc)));
r32 |= (mode << FNC_PERS_FN_SHIFT(bfa_ioc_pcifn(ioc)));
writel(r32, rb + FNC_PERS_REG);
}
static bool
bfa_ioc_ct2_lpu_read_stat(struct bfa_ioc *ioc)
{
u32 r32;
r32 = readl(ioc->ioc_regs.lpu_read_stat);
if (r32) {
writel(1, ioc->ioc_regs.lpu_read_stat);
return true;
}
return false;
}
/* MSI-X resource allocation for 1860 with no asic block */
#define HOSTFN_MSIX_DEFAULT 64
#define HOSTFN_MSIX_VT_INDEX_MBOX_ERR 0x30138
#define HOSTFN_MSIX_VT_OFST_NUMVT 0x3013c
#define __MSIX_VT_NUMVT__MK 0x003ff800
#define __MSIX_VT_NUMVT__SH 11
#define __MSIX_VT_NUMVT_(_v) ((_v) << __MSIX_VT_NUMVT__SH)
#define __MSIX_VT_OFST_ 0x000007ff
void
bfa_nw_ioc_ct2_poweron(struct bfa_ioc *ioc)
{
void __iomem *rb = ioc->pcidev.pci_bar_kva;
u32 r32;
r32 = readl(rb + HOSTFN_MSIX_VT_OFST_NUMVT);
if (r32 & __MSIX_VT_NUMVT__MK) {
writel(r32 & __MSIX_VT_OFST_,
rb + HOSTFN_MSIX_VT_INDEX_MBOX_ERR);
return;
}
writel(__MSIX_VT_NUMVT_(HOSTFN_MSIX_DEFAULT - 1) |
HOSTFN_MSIX_DEFAULT * bfa_ioc_pcifn(ioc),
rb + HOSTFN_MSIX_VT_OFST_NUMVT);
writel(HOSTFN_MSIX_DEFAULT * bfa_ioc_pcifn(ioc),
rb + HOSTFN_MSIX_VT_INDEX_MBOX_ERR);
}
/* Cleanup hw semaphore and usecnt registers */
static void
bfa_ioc_ct_ownership_reset(struct bfa_ioc *ioc)
{
bfa_nw_ioc_sem_get(ioc->ioc_regs.ioc_usage_sem_reg);
writel(0, ioc->ioc_regs.ioc_usage_reg);
bfa_nw_ioc_sem_release(ioc->ioc_regs.ioc_usage_sem_reg);
/*
* Read the hw sem reg to make sure that it is locked
* before we clear it. If it is not locked, writing 1
* will lock it instead of clearing it.
*/
readl(ioc->ioc_regs.ioc_sem_reg);
bfa_nw_ioc_hw_sem_release(ioc);
}
/* Synchronized IOC failure processing routines */
static bool
bfa_ioc_ct_sync_start(struct bfa_ioc *ioc)
{
u32 r32 = readl(ioc->ioc_regs.ioc_fail_sync);
u32 sync_reqd = bfa_ioc_ct_get_sync_reqd(r32);
/*
* Driver load time. If the sync required bit for this PCI fn
* is set, it is due to an unclean exit by the driver for this
* PCI fn in the previous incarnation. Whoever comes here first
* should clean it up, no matter which PCI fn.
*/
if (sync_reqd & bfa_ioc_ct_sync_pos(ioc)) {
writel(0, ioc->ioc_regs.ioc_fail_sync);
writel(1, ioc->ioc_regs.ioc_usage_reg);
writel(BFI_IOC_UNINIT, ioc->ioc_regs.ioc_fwstate);
writel(BFI_IOC_UNINIT, ioc->ioc_regs.alt_ioc_fwstate);
return true;
}
return bfa_ioc_ct_sync_complete(ioc);
}
/* Synchronized IOC failure processing routines */
static void
bfa_ioc_ct_sync_join(struct bfa_ioc *ioc)
{
u32 r32 = readl(ioc->ioc_regs.ioc_fail_sync);
u32 sync_pos = bfa_ioc_ct_sync_reqd_pos(ioc);
writel((r32 | sync_pos), ioc->ioc_regs.ioc_fail_sync);
}
static void
bfa_ioc_ct_sync_leave(struct bfa_ioc *ioc)
{
u32 r32 = readl(ioc->ioc_regs.ioc_fail_sync);
u32 sync_msk = bfa_ioc_ct_sync_reqd_pos(ioc) |
bfa_ioc_ct_sync_pos(ioc);
writel((r32 & ~sync_msk), ioc->ioc_regs.ioc_fail_sync);
}
static void
bfa_ioc_ct_sync_ack(struct bfa_ioc *ioc)
{
u32 r32 = readl(ioc->ioc_regs.ioc_fail_sync);
writel(r32 | bfa_ioc_ct_sync_pos(ioc), ioc->ioc_regs.ioc_fail_sync);
}
static bool
bfa_ioc_ct_sync_complete(struct bfa_ioc *ioc)
{
u32 r32 = readl(ioc->ioc_regs.ioc_fail_sync);
u32 sync_reqd = bfa_ioc_ct_get_sync_reqd(r32);
u32 sync_ackd = bfa_ioc_ct_get_sync_ackd(r32);
u32 tmp_ackd;
if (sync_ackd == 0)
return true;
/**
* The check below is to see whether any other PCI fn
* has reinitialized the ASIC (reset sync_ackd bits)
* and failed again while this IOC was waiting for hw
* semaphore (in bfa_iocpf_sm_semwait()).
*/
tmp_ackd = sync_ackd;
if ((sync_reqd & bfa_ioc_ct_sync_pos(ioc)) &&
!(sync_ackd & bfa_ioc_ct_sync_pos(ioc)))
sync_ackd |= bfa_ioc_ct_sync_pos(ioc);
if (sync_reqd == sync_ackd) {
writel(bfa_ioc_ct_clear_sync_ackd(r32),
ioc->ioc_regs.ioc_fail_sync);
writel(BFI_IOC_FAIL, ioc->ioc_regs.ioc_fwstate);
writel(BFI_IOC_FAIL, ioc->ioc_regs.alt_ioc_fwstate);
return true;
}
/**
* If another PCI fn reinitialized and failed again while
* this IOC was waiting for hw sem, the sync_ackd bit for
* this IOC need to be set again to allow reinitialization.
*/
if (tmp_ackd != sync_ackd)
writel((r32 | sync_ackd), ioc->ioc_regs.ioc_fail_sync);
return false;
}
static void
bfa_ioc_ct_set_cur_ioc_fwstate(struct bfa_ioc *ioc,
enum bfi_ioc_state fwstate)
{
writel(fwstate, ioc->ioc_regs.ioc_fwstate);
}
static enum bfi_ioc_state
bfa_ioc_ct_get_cur_ioc_fwstate(struct bfa_ioc *ioc)
{
return (enum bfi_ioc_state)readl(ioc->ioc_regs.ioc_fwstate);
}
static void
bfa_ioc_ct_set_alt_ioc_fwstate(struct bfa_ioc *ioc,
enum bfi_ioc_state fwstate)
{
writel(fwstate, ioc->ioc_regs.alt_ioc_fwstate);
}
static enum bfi_ioc_state
bfa_ioc_ct_get_alt_ioc_fwstate(struct bfa_ioc *ioc)
{
return (enum bfi_ioc_state)readl(ioc->ioc_regs.alt_ioc_fwstate);
}
static enum bfa_status
bfa_ioc_ct_pll_init(void __iomem *rb, enum bfi_asic_mode asic_mode)
{
u32 pll_sclk, pll_fclk, r32;
bool fcmode = (asic_mode == BFI_ASIC_MODE_FC);
pll_sclk = __APP_PLL_SCLK_LRESETN | __APP_PLL_SCLK_ENARST |
__APP_PLL_SCLK_RSEL200500 | __APP_PLL_SCLK_P0_1(3U) |
__APP_PLL_SCLK_JITLMT0_1(3U) |
__APP_PLL_SCLK_CNTLMT0_1(1U);
pll_fclk = __APP_PLL_LCLK_LRESETN | __APP_PLL_LCLK_ENARST |
__APP_PLL_LCLK_RSEL200500 | __APP_PLL_LCLK_P0_1(3U) |
__APP_PLL_LCLK_JITLMT0_1(3U) |
__APP_PLL_LCLK_CNTLMT0_1(1U);
if (fcmode) {
writel(0, (rb + OP_MODE));
writel(__APP_EMS_CMLCKSEL |
__APP_EMS_REFCKBUFEN2 |
__APP_EMS_CHANNEL_SEL,
(rb + ETH_MAC_SER_REG));
} else {
writel(__GLOBAL_FCOE_MODE, (rb + OP_MODE));
writel(__APP_EMS_REFCKBUFEN1,
(rb + ETH_MAC_SER_REG));
}
writel(BFI_IOC_UNINIT, (rb + BFA_IOC0_STATE_REG));
writel(BFI_IOC_UNINIT, (rb + BFA_IOC1_STATE_REG));
writel(0xffffffffU, (rb + HOSTFN0_INT_MSK));
writel(0xffffffffU, (rb + HOSTFN1_INT_MSK));
writel(0xffffffffU, (rb + HOSTFN0_INT_STATUS));
writel(0xffffffffU, (rb + HOSTFN1_INT_STATUS));
writel(0xffffffffU, (rb + HOSTFN0_INT_MSK));
writel(0xffffffffU, (rb + HOSTFN1_INT_MSK));
writel(pll_sclk |
__APP_PLL_SCLK_LOGIC_SOFT_RESET,
rb + APP_PLL_SCLK_CTL_REG);
writel(pll_fclk |
__APP_PLL_LCLK_LOGIC_SOFT_RESET,
rb + APP_PLL_LCLK_CTL_REG);
writel(pll_sclk |
__APP_PLL_SCLK_LOGIC_SOFT_RESET | __APP_PLL_SCLK_ENABLE,
rb + APP_PLL_SCLK_CTL_REG);
writel(pll_fclk |
__APP_PLL_LCLK_LOGIC_SOFT_RESET | __APP_PLL_LCLK_ENABLE,
rb + APP_PLL_LCLK_CTL_REG);
readl(rb + HOSTFN0_INT_MSK);
udelay(2000);
writel(0xffffffffU, (rb + HOSTFN0_INT_STATUS));
writel(0xffffffffU, (rb + HOSTFN1_INT_STATUS));
writel(pll_sclk |
__APP_PLL_SCLK_ENABLE,
rb + APP_PLL_SCLK_CTL_REG);
writel(pll_fclk |
__APP_PLL_LCLK_ENABLE,
rb + APP_PLL_LCLK_CTL_REG);
if (!fcmode) {
writel(__PMM_1T_RESET_P, (rb + PMM_1T_RESET_REG_P0));
writel(__PMM_1T_RESET_P, (rb + PMM_1T_RESET_REG_P1));
}
r32 = readl(rb + PSS_CTL_REG);
r32 &= ~__PSS_LMEM_RESET;
writel(r32, (rb + PSS_CTL_REG));
udelay(1000);
if (!fcmode) {
writel(0, (rb + PMM_1T_RESET_REG_P0));
writel(0, (rb + PMM_1T_RESET_REG_P1));
}
writel(__EDRAM_BISTR_START, (rb + MBIST_CTL_REG));
udelay(1000);
r32 = readl(rb + MBIST_STAT_REG);
writel(0, (rb + MBIST_CTL_REG));
return BFA_STATUS_OK;
}
static void
bfa_ioc_ct2_sclk_init(void __iomem *rb)
{
u32 r32;
/*
* put s_clk PLL and PLL FSM in reset
*/
r32 = readl(rb + CT2_APP_PLL_SCLK_CTL_REG);
r32 &= ~(__APP_PLL_SCLK_ENABLE | __APP_PLL_SCLK_LRESETN);
r32 |= (__APP_PLL_SCLK_ENARST | __APP_PLL_SCLK_BYPASS |
__APP_PLL_SCLK_LOGIC_SOFT_RESET);
writel(r32, (rb + CT2_APP_PLL_SCLK_CTL_REG));
/*
* Ignore mode and program for the max clock (which is FC16)
* Firmware/NFC will do the PLL init appropriately
*/
r32 = readl(rb + CT2_APP_PLL_SCLK_CTL_REG);
r32 &= ~(__APP_PLL_SCLK_REFCLK_SEL | __APP_PLL_SCLK_CLK_DIV2);
writel(r32, (rb + CT2_APP_PLL_SCLK_CTL_REG));
/*
* while doing PLL init dont clock gate ethernet subsystem
*/
r32 = readl(rb + CT2_CHIP_MISC_PRG);
writel(r32 | __ETH_CLK_ENABLE_PORT0,
rb + CT2_CHIP_MISC_PRG);
r32 = readl(rb + CT2_PCIE_MISC_REG);
writel(r32 | __ETH_CLK_ENABLE_PORT1,
rb + CT2_PCIE_MISC_REG);
/*
* set sclk value
*/
r32 = readl(rb + CT2_APP_PLL_SCLK_CTL_REG);
r32 &= (__P_SCLK_PLL_LOCK | __APP_PLL_SCLK_REFCLK_SEL |
__APP_PLL_SCLK_CLK_DIV2);
writel(r32 | 0x1061731b, rb + CT2_APP_PLL_SCLK_CTL_REG);
/*
* poll for s_clk lock or delay 1ms
*/
udelay(1000);
/*
* Dont do clock gating for ethernet subsystem, firmware/NFC will
* do this appropriately
*/
}
static void
bfa_ioc_ct2_lclk_init(void __iomem *rb)
{
u32 r32;
/*
* put l_clk PLL and PLL FSM in reset
*/
r32 = readl(rb + CT2_APP_PLL_LCLK_CTL_REG);
r32 &= ~(__APP_PLL_LCLK_ENABLE | __APP_PLL_LCLK_LRESETN);
r32 |= (__APP_PLL_LCLK_ENARST | __APP_PLL_LCLK_BYPASS |
__APP_PLL_LCLK_LOGIC_SOFT_RESET);
writel(r32, rb + CT2_APP_PLL_LCLK_CTL_REG);
/*
* set LPU speed (set for FC16 which will work for other modes)
*/
r32 = readl(rb + CT2_CHIP_MISC_PRG);
writel(r32, (rb + CT2_CHIP_MISC_PRG));
/*
* set LPU half speed (set for FC16 which will work for other modes)
*/
r32 = readl(rb + CT2_APP_PLL_LCLK_CTL_REG);
writel(r32, rb + CT2_APP_PLL_LCLK_CTL_REG);
/*
* set lclk for mode (set for FC16)
*/
r32 = readl(rb + CT2_APP_PLL_LCLK_CTL_REG);
r32 &= (__P_LCLK_PLL_LOCK | __APP_LPUCLK_HALFSPEED);
r32 |= 0x20c1731b;
writel(r32, (rb + CT2_APP_PLL_LCLK_CTL_REG));
/*
* poll for s_clk lock or delay 1ms
*/
udelay(1000);
}
static void
bfa_ioc_ct2_mem_init(void __iomem *rb)
{
u32 r32;
r32 = readl(rb + PSS_CTL_REG);
r32 &= ~__PSS_LMEM_RESET;
writel(r32, rb + PSS_CTL_REG);
udelay(1000);
writel(__EDRAM_BISTR_START, rb + CT2_MBIST_CTL_REG);
udelay(1000);
writel(0, rb + CT2_MBIST_CTL_REG);
}
static void
bfa_ioc_ct2_mac_reset(void __iomem *rb)
{
volatile u32 r32;
bfa_ioc_ct2_sclk_init(rb);
bfa_ioc_ct2_lclk_init(rb);
/*
* release soft reset on s_clk & l_clk
*/
r32 = readl(rb + CT2_APP_PLL_SCLK_CTL_REG);
writel(r32 & ~__APP_PLL_SCLK_LOGIC_SOFT_RESET,
rb + CT2_APP_PLL_SCLK_CTL_REG);
/*
* release soft reset on s_clk & l_clk
*/
r32 = readl(rb + CT2_APP_PLL_LCLK_CTL_REG);
writel(r32 & ~__APP_PLL_LCLK_LOGIC_SOFT_RESET,
rb + CT2_APP_PLL_LCLK_CTL_REG);
/* put port0, port1 MAC & AHB in reset */
writel(__CSI_MAC_RESET | __CSI_MAC_AHB_RESET,
rb + CT2_CSI_MAC_CONTROL_REG(0));
writel(__CSI_MAC_RESET | __CSI_MAC_AHB_RESET,
rb + CT2_CSI_MAC_CONTROL_REG(1));
}
#define CT2_NFC_MAX_DELAY 1000
#define CT2_NFC_VER_VALID 0x143
#define BFA_IOC_PLL_POLL 1000000
static bool
bfa_ioc_ct2_nfc_halted(void __iomem *rb)
{
volatile u32 r32;
r32 = readl(rb + CT2_NFC_CSR_SET_REG);
if (r32 & __NFC_CONTROLLER_HALTED)
return true;
return false;
}
static void
bfa_ioc_ct2_nfc_resume(void __iomem *rb)
{
volatile u32 r32;
int i;
writel(__HALT_NFC_CONTROLLER, rb + CT2_NFC_CSR_CLR_REG);
for (i = 0; i < CT2_NFC_MAX_DELAY; i++) {
r32 = readl(rb + CT2_NFC_CSR_SET_REG);
if (!(r32 & __NFC_CONTROLLER_HALTED))
return;
udelay(1000);
}
BUG_ON(1);
}
static enum bfa_status
bfa_ioc_ct2_pll_init(void __iomem *rb, enum bfi_asic_mode asic_mode)
{
volatile u32 wgn, r32;
u32 nfc_ver, i;
wgn = readl(rb + CT2_WGN_STATUS);
nfc_ver = readl(rb + CT2_RSC_GPR15_REG);
if (wgn == (__A2T_AHB_LOAD | __WGN_READY) &&
nfc_ver >= CT2_NFC_VER_VALID) {
if (bfa_ioc_ct2_nfc_halted(rb))
bfa_ioc_ct2_nfc_resume(rb);
writel(__RESET_AND_START_SCLK_LCLK_PLLS,
rb + CT2_CSI_FW_CTL_SET_REG);
for (i = 0; i < BFA_IOC_PLL_POLL; i++) {
r32 = readl(rb + CT2_APP_PLL_LCLK_CTL_REG);
if (r32 & __RESET_AND_START_SCLK_LCLK_PLLS)
break;
}
BUG_ON(!(r32 & __RESET_AND_START_SCLK_LCLK_PLLS));
for (i = 0; i < BFA_IOC_PLL_POLL; i++) {
r32 = readl(rb + CT2_APP_PLL_LCLK_CTL_REG);
if (!(r32 & __RESET_AND_START_SCLK_LCLK_PLLS))
break;
}
BUG_ON(r32 & __RESET_AND_START_SCLK_LCLK_PLLS);
udelay(1000);
r32 = readl(rb + CT2_CSI_FW_CTL_REG);
BUG_ON(r32 & __RESET_AND_START_SCLK_LCLK_PLLS);
} else {
writel(__HALT_NFC_CONTROLLER, (rb + CT2_NFC_CSR_SET_REG));
for (i = 0; i < CT2_NFC_MAX_DELAY; i++) {
r32 = readl(rb + CT2_NFC_CSR_SET_REG);
if (r32 & __NFC_CONTROLLER_HALTED)
break;
udelay(1000);
}
bfa_ioc_ct2_mac_reset(rb);
bfa_ioc_ct2_sclk_init(rb);
bfa_ioc_ct2_lclk_init(rb);
/* release soft reset on s_clk & l_clk */
r32 = readl(rb + CT2_APP_PLL_SCLK_CTL_REG);
writel(r32 & ~__APP_PLL_SCLK_LOGIC_SOFT_RESET,
rb + CT2_APP_PLL_SCLK_CTL_REG);
r32 = readl(rb + CT2_APP_PLL_LCLK_CTL_REG);
writel(r32 & ~__APP_PLL_LCLK_LOGIC_SOFT_RESET,
rb + CT2_APP_PLL_LCLK_CTL_REG);
}
/* Announce flash device presence, if flash was corrupted. */
if (wgn == (__WGN_READY | __GLBL_PF_VF_CFG_RDY)) {
r32 = readl(rb + PSS_GPIO_OUT_REG);
writel(r32 & ~1, rb + PSS_GPIO_OUT_REG);
r32 = readl(rb + PSS_GPIO_OE_REG);
writel(r32 | 1, rb + PSS_GPIO_OE_REG);
}
/*
* Mask the interrupts and clear any
* pending interrupts left by BIOS/EFI
*/
writel(1, rb + CT2_LPU0_HOSTFN_MBOX0_MSK);
writel(1, rb + CT2_LPU1_HOSTFN_MBOX0_MSK);
/* For first time initialization, no need to clear interrupts */
r32 = readl(rb + HOST_SEM5_REG);
if (r32 & 0x1) {
r32 = readl(rb + CT2_LPU0_HOSTFN_CMD_STAT);
if (r32 == 1) {
writel(1, rb + CT2_LPU0_HOSTFN_CMD_STAT);
readl(rb + CT2_LPU0_HOSTFN_CMD_STAT);
}
r32 = readl(rb + CT2_LPU1_HOSTFN_CMD_STAT);
if (r32 == 1) {
writel(1, rb + CT2_LPU1_HOSTFN_CMD_STAT);
readl(rb + CT2_LPU1_HOSTFN_CMD_STAT);
}
}
bfa_ioc_ct2_mem_init(rb);
writel(BFI_IOC_UNINIT, rb + CT2_BFA_IOC0_STATE_REG);
writel(BFI_IOC_UNINIT, rb + CT2_BFA_IOC1_STATE_REG);
return BFA_STATUS_OK;
}
|
linux-master
|
drivers/net/ethernet/brocade/bna/bfa_ioc_ct.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Linux network driver for QLogic BR-series Converged Network Adapter.
*/
/*
* Copyright (c) 2005-2014 Brocade Communications Systems, Inc.
* Copyright (c) 2014-2015 QLogic Corporation
* All rights reserved
* www.qlogic.com
*/
#include "bfa_cee.h"
#include "bfi_cna.h"
#include "bfa_ioc.h"
static void bfa_cee_format_lldp_cfg(struct bfa_cee_lldp_cfg *lldp_cfg);
static void bfa_cee_format_cee_cfg(void *buffer);
static void
bfa_cee_format_cee_cfg(void *buffer)
{
struct bfa_cee_attr *cee_cfg = buffer;
bfa_cee_format_lldp_cfg(&cee_cfg->lldp_remote);
}
static void
bfa_cee_stats_swap(struct bfa_cee_stats *stats)
{
u32 *buffer = (u32 *)stats;
int i;
for (i = 0; i < (sizeof(struct bfa_cee_stats) / sizeof(u32));
i++) {
buffer[i] = ntohl(buffer[i]);
}
}
static void
bfa_cee_format_lldp_cfg(struct bfa_cee_lldp_cfg *lldp_cfg)
{
lldp_cfg->time_to_live =
ntohs(lldp_cfg->time_to_live);
lldp_cfg->enabled_system_cap =
ntohs(lldp_cfg->enabled_system_cap);
}
/**
* bfa_cee_attr_meminfo - Returns the size of the DMA memory needed by CEE attributes
*/
static u32
bfa_cee_attr_meminfo(void)
{
return roundup(sizeof(struct bfa_cee_attr), BFA_DMA_ALIGN_SZ);
}
/**
* bfa_cee_stats_meminfo - Returns the size of the DMA memory needed by CEE stats
*/
static u32
bfa_cee_stats_meminfo(void)
{
return roundup(sizeof(struct bfa_cee_stats), BFA_DMA_ALIGN_SZ);
}
/**
* bfa_cee_get_attr_isr - CEE ISR for get-attributes responses from f/w
*
* @cee: Pointer to the CEE module
* @status: Return status from the f/w
*/
static void
bfa_cee_get_attr_isr(struct bfa_cee *cee, enum bfa_status status)
{
cee->get_attr_status = status;
if (status == BFA_STATUS_OK) {
memcpy(cee->attr, cee->attr_dma.kva,
sizeof(struct bfa_cee_attr));
bfa_cee_format_cee_cfg(cee->attr);
}
cee->get_attr_pending = false;
if (cee->cbfn.get_attr_cbfn)
cee->cbfn.get_attr_cbfn(cee->cbfn.get_attr_cbarg, status);
}
/**
* bfa_cee_get_stats_isr - CEE ISR for get-stats responses from f/w
*
* @cee: Pointer to the CEE module
* @status: Return status from the f/w
*/
static void
bfa_cee_get_stats_isr(struct bfa_cee *cee, enum bfa_status status)
{
cee->get_stats_status = status;
if (status == BFA_STATUS_OK) {
memcpy(cee->stats, cee->stats_dma.kva,
sizeof(struct bfa_cee_stats));
bfa_cee_stats_swap(cee->stats);
}
cee->get_stats_pending = false;
if (cee->cbfn.get_stats_cbfn)
cee->cbfn.get_stats_cbfn(cee->cbfn.get_stats_cbarg, status);
}
/**
* bfa_cee_reset_stats_isr - CEE ISR for reset-stats responses from f/w
*
* @cee: Input Pointer to the CEE module
* @status: Return status from the f/w
*/
static void
bfa_cee_reset_stats_isr(struct bfa_cee *cee, enum bfa_status status)
{
cee->reset_stats_status = status;
cee->reset_stats_pending = false;
if (cee->cbfn.reset_stats_cbfn)
cee->cbfn.reset_stats_cbfn(cee->cbfn.reset_stats_cbarg, status);
}
/**
* bfa_nw_cee_meminfo - Returns the size of the DMA memory needed by CEE module
*/
u32
bfa_nw_cee_meminfo(void)
{
return bfa_cee_attr_meminfo() + bfa_cee_stats_meminfo();
}
/**
* bfa_nw_cee_mem_claim - Initialized CEE DMA Memory
*
* @cee: CEE module pointer
* @dma_kva: Kernel Virtual Address of CEE DMA Memory
* @dma_pa: Physical Address of CEE DMA Memory
*/
void
bfa_nw_cee_mem_claim(struct bfa_cee *cee, u8 *dma_kva, u64 dma_pa)
{
cee->attr_dma.kva = dma_kva;
cee->attr_dma.pa = dma_pa;
cee->stats_dma.kva = dma_kva + bfa_cee_attr_meminfo();
cee->stats_dma.pa = dma_pa + bfa_cee_attr_meminfo();
cee->attr = (struct bfa_cee_attr *) dma_kva;
cee->stats = (struct bfa_cee_stats *)
(dma_kva + bfa_cee_attr_meminfo());
}
/**
* bfa_nw_cee_get_attr - Send the request to the f/w to fetch CEE attributes.
*
* @cee: Pointer to the CEE module data structure.
* @attr: attribute requested
* @cbfn: function pointer
* @cbarg: function pointer arguments
*
* Return: status
*/
enum bfa_status
bfa_nw_cee_get_attr(struct bfa_cee *cee, struct bfa_cee_attr *attr,
bfa_cee_get_attr_cbfn_t cbfn, void *cbarg)
{
struct bfi_cee_get_req *cmd;
BUG_ON(!((cee != NULL) && (cee->ioc != NULL)));
if (!bfa_nw_ioc_is_operational(cee->ioc))
return BFA_STATUS_IOC_FAILURE;
if (cee->get_attr_pending)
return BFA_STATUS_DEVBUSY;
cee->get_attr_pending = true;
cmd = (struct bfi_cee_get_req *) cee->get_cfg_mb.msg;
cee->attr = attr;
cee->cbfn.get_attr_cbfn = cbfn;
cee->cbfn.get_attr_cbarg = cbarg;
bfi_h2i_set(cmd->mh, BFI_MC_CEE, BFI_CEE_H2I_GET_CFG_REQ,
bfa_ioc_portid(cee->ioc));
bfa_dma_be_addr_set(cmd->dma_addr, cee->attr_dma.pa);
bfa_nw_ioc_mbox_queue(cee->ioc, &cee->get_cfg_mb, NULL, NULL);
return BFA_STATUS_OK;
}
/**
* bfa_cee_isr - Handles Mail-box interrupts for CEE module.
* @cbarg: argument passed containing pointer to the CEE module data structure.
* @m: message pointer
*/
static void
bfa_cee_isr(void *cbarg, struct bfi_mbmsg *m)
{
union bfi_cee_i2h_msg_u *msg;
struct bfi_cee_get_rsp *get_rsp;
struct bfa_cee *cee = (struct bfa_cee *) cbarg;
msg = (union bfi_cee_i2h_msg_u *) m;
get_rsp = (struct bfi_cee_get_rsp *) m;
switch (msg->mh.msg_id) {
case BFI_CEE_I2H_GET_CFG_RSP:
bfa_cee_get_attr_isr(cee, get_rsp->cmd_status);
break;
case BFI_CEE_I2H_GET_STATS_RSP:
bfa_cee_get_stats_isr(cee, get_rsp->cmd_status);
break;
case BFI_CEE_I2H_RESET_STATS_RSP:
bfa_cee_reset_stats_isr(cee, get_rsp->cmd_status);
break;
default:
BUG_ON(1);
}
}
/**
* bfa_cee_notify - CEE module heart-beat failure handler.
*
* @arg: argument passed containing pointer to the CEE module data structure.
* @event: IOC event type
*/
static void
bfa_cee_notify(void *arg, enum bfa_ioc_event event)
{
struct bfa_cee *cee;
cee = (struct bfa_cee *) arg;
switch (event) {
case BFA_IOC_E_DISABLED:
case BFA_IOC_E_FAILED:
if (cee->get_attr_pending) {
cee->get_attr_status = BFA_STATUS_FAILED;
cee->get_attr_pending = false;
if (cee->cbfn.get_attr_cbfn) {
cee->cbfn.get_attr_cbfn(
cee->cbfn.get_attr_cbarg,
BFA_STATUS_FAILED);
}
}
if (cee->get_stats_pending) {
cee->get_stats_status = BFA_STATUS_FAILED;
cee->get_stats_pending = false;
if (cee->cbfn.get_stats_cbfn) {
cee->cbfn.get_stats_cbfn(
cee->cbfn.get_stats_cbarg,
BFA_STATUS_FAILED);
}
}
if (cee->reset_stats_pending) {
cee->reset_stats_status = BFA_STATUS_FAILED;
cee->reset_stats_pending = false;
if (cee->cbfn.reset_stats_cbfn) {
cee->cbfn.reset_stats_cbfn(
cee->cbfn.reset_stats_cbarg,
BFA_STATUS_FAILED);
}
}
break;
default:
break;
}
}
/**
* bfa_nw_cee_attach - CEE module-attach API
*
* @cee: Pointer to the CEE module data structure
* @ioc: Pointer to the ioc module data structure
* @dev: Pointer to the device driver module data structure.
* The device driver specific mbox ISR functions have
* this pointer as one of the parameters.
*/
void
bfa_nw_cee_attach(struct bfa_cee *cee, struct bfa_ioc *ioc,
void *dev)
{
BUG_ON(!(cee != NULL));
cee->dev = dev;
cee->ioc = ioc;
bfa_nw_ioc_mbox_regisr(cee->ioc, BFI_MC_CEE, bfa_cee_isr, cee);
bfa_ioc_notify_init(&cee->ioc_notify, bfa_cee_notify, cee);
bfa_nw_ioc_notify_register(cee->ioc, &cee->ioc_notify);
}
|
linux-master
|
drivers/net/ethernet/brocade/bna/bfa_cee.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Linux network driver for QLogic BR-series Converged Network Adapter.
*/
/*
* Copyright (c) 2005-2014 Brocade Communications Systems, Inc.
* Copyright (c) 2014-2015 QLogic Corporation
* All rights reserved
* www.qlogic.com
*/
#include "bfa_ioc.h"
#include "bfi_reg.h"
#include "bfa_defs.h"
/* IOC local definitions */
/* Asic specific macros : see bfa_hw_cb.c and bfa_hw_ct.c for details. */
#define bfa_ioc_firmware_lock(__ioc) \
((__ioc)->ioc_hwif->ioc_firmware_lock(__ioc))
#define bfa_ioc_firmware_unlock(__ioc) \
((__ioc)->ioc_hwif->ioc_firmware_unlock(__ioc))
#define bfa_ioc_reg_init(__ioc) ((__ioc)->ioc_hwif->ioc_reg_init(__ioc))
#define bfa_ioc_map_port(__ioc) ((__ioc)->ioc_hwif->ioc_map_port(__ioc))
#define bfa_ioc_notify_fail(__ioc) \
((__ioc)->ioc_hwif->ioc_notify_fail(__ioc))
#define bfa_ioc_sync_start(__ioc) \
((__ioc)->ioc_hwif->ioc_sync_start(__ioc))
#define bfa_ioc_sync_join(__ioc) \
((__ioc)->ioc_hwif->ioc_sync_join(__ioc))
#define bfa_ioc_sync_leave(__ioc) \
((__ioc)->ioc_hwif->ioc_sync_leave(__ioc))
#define bfa_ioc_sync_ack(__ioc) \
((__ioc)->ioc_hwif->ioc_sync_ack(__ioc))
#define bfa_ioc_sync_complete(__ioc) \
((__ioc)->ioc_hwif->ioc_sync_complete(__ioc))
#define bfa_ioc_set_cur_ioc_fwstate(__ioc, __fwstate) \
((__ioc)->ioc_hwif->ioc_set_fwstate(__ioc, __fwstate))
#define bfa_ioc_get_cur_ioc_fwstate(__ioc) \
((__ioc)->ioc_hwif->ioc_get_fwstate(__ioc))
#define bfa_ioc_set_alt_ioc_fwstate(__ioc, __fwstate) \
((__ioc)->ioc_hwif->ioc_set_alt_fwstate(__ioc, __fwstate))
static bool bfa_nw_auto_recover = true;
/*
* forward declarations
*/
static void bfa_ioc_hw_sem_init(struct bfa_ioc *ioc);
static void bfa_ioc_hw_sem_get(struct bfa_ioc *ioc);
static void bfa_ioc_hw_sem_get_cancel(struct bfa_ioc *ioc);
static void bfa_ioc_hwinit(struct bfa_ioc *ioc, bool force);
static void bfa_ioc_poll_fwinit(struct bfa_ioc *ioc);
static void bfa_ioc_send_enable(struct bfa_ioc *ioc);
static void bfa_ioc_send_disable(struct bfa_ioc *ioc);
static void bfa_ioc_send_getattr(struct bfa_ioc *ioc);
static void bfa_ioc_hb_monitor(struct bfa_ioc *ioc);
static void bfa_ioc_hb_stop(struct bfa_ioc *ioc);
static void bfa_ioc_reset(struct bfa_ioc *ioc, bool force);
static void bfa_ioc_mbox_poll(struct bfa_ioc *ioc);
static void bfa_ioc_mbox_flush(struct bfa_ioc *ioc);
static void bfa_ioc_recover(struct bfa_ioc *ioc);
static void bfa_ioc_event_notify(struct bfa_ioc *, enum bfa_ioc_event);
static void bfa_ioc_disable_comp(struct bfa_ioc *ioc);
static void bfa_ioc_lpu_stop(struct bfa_ioc *ioc);
static void bfa_nw_ioc_debug_save_ftrc(struct bfa_ioc *ioc);
static void bfa_ioc_fail_notify(struct bfa_ioc *ioc);
static void bfa_ioc_pf_enabled(struct bfa_ioc *ioc);
static void bfa_ioc_pf_disabled(struct bfa_ioc *ioc);
static void bfa_ioc_pf_failed(struct bfa_ioc *ioc);
static void bfa_ioc_pf_hwfailed(struct bfa_ioc *ioc);
static void bfa_ioc_pf_fwmismatch(struct bfa_ioc *ioc);
static enum bfa_status bfa_ioc_boot(struct bfa_ioc *ioc,
enum bfi_fwboot_type boot_type, u32 boot_param);
static u32 bfa_ioc_smem_pgnum(struct bfa_ioc *ioc, u32 fmaddr);
static void bfa_ioc_get_adapter_serial_num(struct bfa_ioc *ioc,
char *serial_num);
static void bfa_ioc_get_adapter_fw_ver(struct bfa_ioc *ioc,
char *fw_ver);
static void bfa_ioc_get_pci_chip_rev(struct bfa_ioc *ioc,
char *chip_rev);
static void bfa_ioc_get_adapter_optrom_ver(struct bfa_ioc *ioc,
char *optrom_ver);
static void bfa_ioc_get_adapter_manufacturer(struct bfa_ioc *ioc,
char *manufacturer);
static void bfa_ioc_get_adapter_model(struct bfa_ioc *ioc, char *model);
static u64 bfa_ioc_get_pwwn(struct bfa_ioc *ioc);
/* IOC state machine definitions/declarations */
enum ioc_event {
IOC_E_RESET = 1, /*!< IOC reset request */
IOC_E_ENABLE = 2, /*!< IOC enable request */
IOC_E_DISABLE = 3, /*!< IOC disable request */
IOC_E_DETACH = 4, /*!< driver detach cleanup */
IOC_E_ENABLED = 5, /*!< f/w enabled */
IOC_E_FWRSP_GETATTR = 6, /*!< IOC get attribute response */
IOC_E_DISABLED = 7, /*!< f/w disabled */
IOC_E_PFFAILED = 8, /*!< failure notice by iocpf sm */
IOC_E_HBFAIL = 9, /*!< heartbeat failure */
IOC_E_HWERROR = 10, /*!< hardware error interrupt */
IOC_E_TIMEOUT = 11, /*!< timeout */
IOC_E_HWFAILED = 12, /*!< PCI mapping failure notice */
};
bfa_fsm_state_decl(bfa_ioc, uninit, struct bfa_ioc, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, reset, struct bfa_ioc, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, enabling, struct bfa_ioc, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, getattr, struct bfa_ioc, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, op, struct bfa_ioc, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, fail_retry, struct bfa_ioc, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, fail, struct bfa_ioc, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, disabling, struct bfa_ioc, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, disabled, struct bfa_ioc, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, hwfail, struct bfa_ioc, enum ioc_event);
static struct ioc_sm_table_s ioc_sm_table[] = {
{BFA_SM(bfa_ioc_sm_uninit), BFA_IOC_UNINIT},
{BFA_SM(bfa_ioc_sm_reset), BFA_IOC_RESET},
{BFA_SM(bfa_ioc_sm_enabling), BFA_IOC_ENABLING},
{BFA_SM(bfa_ioc_sm_getattr), BFA_IOC_GETATTR},
{BFA_SM(bfa_ioc_sm_op), BFA_IOC_OPERATIONAL},
{BFA_SM(bfa_ioc_sm_fail_retry), BFA_IOC_INITFAIL},
{BFA_SM(bfa_ioc_sm_fail), BFA_IOC_FAIL},
{BFA_SM(bfa_ioc_sm_disabling), BFA_IOC_DISABLING},
{BFA_SM(bfa_ioc_sm_disabled), BFA_IOC_DISABLED},
{BFA_SM(bfa_ioc_sm_hwfail), BFA_IOC_HWFAIL},
};
/*
* Forward declareations for iocpf state machine
*/
static void bfa_iocpf_enable(struct bfa_ioc *ioc);
static void bfa_iocpf_disable(struct bfa_ioc *ioc);
static void bfa_iocpf_fail(struct bfa_ioc *ioc);
static void bfa_iocpf_initfail(struct bfa_ioc *ioc);
static void bfa_iocpf_getattrfail(struct bfa_ioc *ioc);
static void bfa_iocpf_stop(struct bfa_ioc *ioc);
/* IOCPF state machine events */
enum iocpf_event {
IOCPF_E_ENABLE = 1, /*!< IOCPF enable request */
IOCPF_E_DISABLE = 2, /*!< IOCPF disable request */
IOCPF_E_STOP = 3, /*!< stop on driver detach */
IOCPF_E_FWREADY = 4, /*!< f/w initialization done */
IOCPF_E_FWRSP_ENABLE = 5, /*!< enable f/w response */
IOCPF_E_FWRSP_DISABLE = 6, /*!< disable f/w response */
IOCPF_E_FAIL = 7, /*!< failure notice by ioc sm */
IOCPF_E_INITFAIL = 8, /*!< init fail notice by ioc sm */
IOCPF_E_GETATTRFAIL = 9, /*!< init fail notice by ioc sm */
IOCPF_E_SEMLOCKED = 10, /*!< h/w semaphore is locked */
IOCPF_E_TIMEOUT = 11, /*!< f/w response timeout */
IOCPF_E_SEM_ERROR = 12, /*!< h/w sem mapping error */
};
/* IOCPF states */
enum bfa_iocpf_state {
BFA_IOCPF_RESET = 1, /*!< IOC is in reset state */
BFA_IOCPF_SEMWAIT = 2, /*!< Waiting for IOC h/w semaphore */
BFA_IOCPF_HWINIT = 3, /*!< IOC h/w is being initialized */
BFA_IOCPF_READY = 4, /*!< IOCPF is initialized */
BFA_IOCPF_INITFAIL = 5, /*!< IOCPF failed */
BFA_IOCPF_FAIL = 6, /*!< IOCPF failed */
BFA_IOCPF_DISABLING = 7, /*!< IOCPF is being disabled */
BFA_IOCPF_DISABLED = 8, /*!< IOCPF is disabled */
BFA_IOCPF_FWMISMATCH = 9, /*!< IOC f/w different from drivers */
};
bfa_fsm_state_decl(bfa_iocpf, reset, struct bfa_iocpf, enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, fwcheck, struct bfa_iocpf, enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, mismatch, struct bfa_iocpf, enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, semwait, struct bfa_iocpf, enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, hwinit, struct bfa_iocpf, enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, enabling, struct bfa_iocpf, enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, ready, struct bfa_iocpf, enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, initfail_sync, struct bfa_iocpf,
enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, initfail, struct bfa_iocpf, enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, fail_sync, struct bfa_iocpf, enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, fail, struct bfa_iocpf, enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, disabling, struct bfa_iocpf, enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, disabling_sync, struct bfa_iocpf,
enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, disabled, struct bfa_iocpf, enum iocpf_event);
static struct iocpf_sm_table_s iocpf_sm_table[] = {
{BFA_SM(bfa_iocpf_sm_reset), BFA_IOCPF_RESET},
{BFA_SM(bfa_iocpf_sm_fwcheck), BFA_IOCPF_FWMISMATCH},
{BFA_SM(bfa_iocpf_sm_mismatch), BFA_IOCPF_FWMISMATCH},
{BFA_SM(bfa_iocpf_sm_semwait), BFA_IOCPF_SEMWAIT},
{BFA_SM(bfa_iocpf_sm_hwinit), BFA_IOCPF_HWINIT},
{BFA_SM(bfa_iocpf_sm_enabling), BFA_IOCPF_HWINIT},
{BFA_SM(bfa_iocpf_sm_ready), BFA_IOCPF_READY},
{BFA_SM(bfa_iocpf_sm_initfail_sync), BFA_IOCPF_INITFAIL},
{BFA_SM(bfa_iocpf_sm_initfail), BFA_IOCPF_INITFAIL},
{BFA_SM(bfa_iocpf_sm_fail_sync), BFA_IOCPF_FAIL},
{BFA_SM(bfa_iocpf_sm_fail), BFA_IOCPF_FAIL},
{BFA_SM(bfa_iocpf_sm_disabling), BFA_IOCPF_DISABLING},
{BFA_SM(bfa_iocpf_sm_disabling_sync), BFA_IOCPF_DISABLING},
{BFA_SM(bfa_iocpf_sm_disabled), BFA_IOCPF_DISABLED},
};
/* IOC State Machine */
/* Beginning state. IOC uninit state. */
static void
bfa_ioc_sm_uninit_entry(struct bfa_ioc *ioc)
{
}
/* IOC is in uninit state. */
static void
bfa_ioc_sm_uninit(struct bfa_ioc *ioc, enum ioc_event event)
{
switch (event) {
case IOC_E_RESET:
bfa_fsm_set_state(ioc, bfa_ioc_sm_reset);
break;
default:
bfa_sm_fault(event);
}
}
/* Reset entry actions -- initialize state machine */
static void
bfa_ioc_sm_reset_entry(struct bfa_ioc *ioc)
{
bfa_fsm_set_state(&ioc->iocpf, bfa_iocpf_sm_reset);
}
/* IOC is in reset state. */
static void
bfa_ioc_sm_reset(struct bfa_ioc *ioc, enum ioc_event event)
{
switch (event) {
case IOC_E_ENABLE:
bfa_fsm_set_state(ioc, bfa_ioc_sm_enabling);
break;
case IOC_E_DISABLE:
bfa_ioc_disable_comp(ioc);
break;
case IOC_E_DETACH:
bfa_fsm_set_state(ioc, bfa_ioc_sm_uninit);
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_ioc_sm_enabling_entry(struct bfa_ioc *ioc)
{
bfa_iocpf_enable(ioc);
}
/* Host IOC function is being enabled, awaiting response from firmware.
* Semaphore is acquired.
*/
static void
bfa_ioc_sm_enabling(struct bfa_ioc *ioc, enum ioc_event event)
{
switch (event) {
case IOC_E_ENABLED:
bfa_fsm_set_state(ioc, bfa_ioc_sm_getattr);
break;
case IOC_E_PFFAILED:
fallthrough;
case IOC_E_HWERROR:
ioc->cbfn->enable_cbfn(ioc->bfa, BFA_STATUS_IOC_FAILURE);
bfa_fsm_set_state(ioc, bfa_ioc_sm_fail);
if (event != IOC_E_PFFAILED)
bfa_iocpf_initfail(ioc);
break;
case IOC_E_HWFAILED:
ioc->cbfn->enable_cbfn(ioc->bfa, BFA_STATUS_IOC_FAILURE);
bfa_fsm_set_state(ioc, bfa_ioc_sm_hwfail);
break;
case IOC_E_DISABLE:
bfa_fsm_set_state(ioc, bfa_ioc_sm_disabling);
break;
case IOC_E_DETACH:
bfa_fsm_set_state(ioc, bfa_ioc_sm_uninit);
bfa_iocpf_stop(ioc);
break;
case IOC_E_ENABLE:
break;
default:
bfa_sm_fault(event);
}
}
/* Semaphore should be acquired for version check. */
static void
bfa_ioc_sm_getattr_entry(struct bfa_ioc *ioc)
{
mod_timer(&ioc->ioc_timer, jiffies +
msecs_to_jiffies(BFA_IOC_TOV));
bfa_ioc_send_getattr(ioc);
}
/* IOC configuration in progress. Timer is active. */
static void
bfa_ioc_sm_getattr(struct bfa_ioc *ioc, enum ioc_event event)
{
switch (event) {
case IOC_E_FWRSP_GETATTR:
del_timer(&ioc->ioc_timer);
bfa_fsm_set_state(ioc, bfa_ioc_sm_op);
break;
case IOC_E_PFFAILED:
case IOC_E_HWERROR:
del_timer(&ioc->ioc_timer);
fallthrough;
case IOC_E_TIMEOUT:
ioc->cbfn->enable_cbfn(ioc->bfa, BFA_STATUS_IOC_FAILURE);
bfa_fsm_set_state(ioc, bfa_ioc_sm_fail);
if (event != IOC_E_PFFAILED)
bfa_iocpf_getattrfail(ioc);
break;
case IOC_E_DISABLE:
del_timer(&ioc->ioc_timer);
bfa_fsm_set_state(ioc, bfa_ioc_sm_disabling);
break;
case IOC_E_ENABLE:
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_ioc_sm_op_entry(struct bfa_ioc *ioc)
{
ioc->cbfn->enable_cbfn(ioc->bfa, BFA_STATUS_OK);
bfa_ioc_event_notify(ioc, BFA_IOC_E_ENABLED);
bfa_ioc_hb_monitor(ioc);
}
static void
bfa_ioc_sm_op(struct bfa_ioc *ioc, enum ioc_event event)
{
switch (event) {
case IOC_E_ENABLE:
break;
case IOC_E_DISABLE:
bfa_ioc_hb_stop(ioc);
bfa_fsm_set_state(ioc, bfa_ioc_sm_disabling);
break;
case IOC_E_PFFAILED:
case IOC_E_HWERROR:
bfa_ioc_hb_stop(ioc);
fallthrough;
case IOC_E_HBFAIL:
if (ioc->iocpf.auto_recover)
bfa_fsm_set_state(ioc, bfa_ioc_sm_fail_retry);
else
bfa_fsm_set_state(ioc, bfa_ioc_sm_fail);
bfa_ioc_fail_notify(ioc);
if (event != IOC_E_PFFAILED)
bfa_iocpf_fail(ioc);
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_ioc_sm_disabling_entry(struct bfa_ioc *ioc)
{
bfa_iocpf_disable(ioc);
}
/* IOC is being disabled */
static void
bfa_ioc_sm_disabling(struct bfa_ioc *ioc, enum ioc_event event)
{
switch (event) {
case IOC_E_DISABLED:
bfa_fsm_set_state(ioc, bfa_ioc_sm_disabled);
break;
case IOC_E_HWERROR:
/*
* No state change. Will move to disabled state
* after iocpf sm completes failure processing and
* moves to disabled state.
*/
bfa_iocpf_fail(ioc);
break;
case IOC_E_HWFAILED:
bfa_fsm_set_state(ioc, bfa_ioc_sm_hwfail);
bfa_ioc_disable_comp(ioc);
break;
default:
bfa_sm_fault(event);
}
}
/* IOC disable completion entry. */
static void
bfa_ioc_sm_disabled_entry(struct bfa_ioc *ioc)
{
bfa_ioc_disable_comp(ioc);
}
static void
bfa_ioc_sm_disabled(struct bfa_ioc *ioc, enum ioc_event event)
{
switch (event) {
case IOC_E_ENABLE:
bfa_fsm_set_state(ioc, bfa_ioc_sm_enabling);
break;
case IOC_E_DISABLE:
ioc->cbfn->disable_cbfn(ioc->bfa);
break;
case IOC_E_DETACH:
bfa_fsm_set_state(ioc, bfa_ioc_sm_uninit);
bfa_iocpf_stop(ioc);
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_ioc_sm_fail_retry_entry(struct bfa_ioc *ioc)
{
}
/* Hardware initialization retry. */
static void
bfa_ioc_sm_fail_retry(struct bfa_ioc *ioc, enum ioc_event event)
{
switch (event) {
case IOC_E_ENABLED:
bfa_fsm_set_state(ioc, bfa_ioc_sm_getattr);
break;
case IOC_E_PFFAILED:
case IOC_E_HWERROR:
/**
* Initialization retry failed.
*/
ioc->cbfn->enable_cbfn(ioc->bfa, BFA_STATUS_IOC_FAILURE);
bfa_fsm_set_state(ioc, bfa_ioc_sm_fail);
if (event != IOC_E_PFFAILED)
bfa_iocpf_initfail(ioc);
break;
case IOC_E_HWFAILED:
ioc->cbfn->enable_cbfn(ioc->bfa, BFA_STATUS_IOC_FAILURE);
bfa_fsm_set_state(ioc, bfa_ioc_sm_hwfail);
break;
case IOC_E_ENABLE:
break;
case IOC_E_DISABLE:
bfa_fsm_set_state(ioc, bfa_ioc_sm_disabling);
break;
case IOC_E_DETACH:
bfa_fsm_set_state(ioc, bfa_ioc_sm_uninit);
bfa_iocpf_stop(ioc);
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_ioc_sm_fail_entry(struct bfa_ioc *ioc)
{
}
/* IOC failure. */
static void
bfa_ioc_sm_fail(struct bfa_ioc *ioc, enum ioc_event event)
{
switch (event) {
case IOC_E_ENABLE:
ioc->cbfn->enable_cbfn(ioc->bfa, BFA_STATUS_IOC_FAILURE);
break;
case IOC_E_DISABLE:
bfa_fsm_set_state(ioc, bfa_ioc_sm_disabling);
break;
case IOC_E_DETACH:
bfa_fsm_set_state(ioc, bfa_ioc_sm_uninit);
bfa_iocpf_stop(ioc);
break;
case IOC_E_HWERROR:
/* HB failure notification, ignore. */
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_ioc_sm_hwfail_entry(struct bfa_ioc *ioc)
{
}
/* IOC failure. */
static void
bfa_ioc_sm_hwfail(struct bfa_ioc *ioc, enum ioc_event event)
{
switch (event) {
case IOC_E_ENABLE:
ioc->cbfn->enable_cbfn(ioc->bfa, BFA_STATUS_IOC_FAILURE);
break;
case IOC_E_DISABLE:
ioc->cbfn->disable_cbfn(ioc->bfa);
break;
case IOC_E_DETACH:
bfa_fsm_set_state(ioc, bfa_ioc_sm_uninit);
break;
default:
bfa_sm_fault(event);
}
}
/* IOCPF State Machine */
/* Reset entry actions -- initialize state machine */
static void
bfa_iocpf_sm_reset_entry(struct bfa_iocpf *iocpf)
{
iocpf->fw_mismatch_notified = false;
iocpf->auto_recover = bfa_nw_auto_recover;
}
/* Beginning state. IOC is in reset state. */
static void
bfa_iocpf_sm_reset(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
switch (event) {
case IOCPF_E_ENABLE:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_fwcheck);
break;
case IOCPF_E_STOP:
break;
default:
bfa_sm_fault(event);
}
}
/* Semaphore should be acquired for version check. */
static void
bfa_iocpf_sm_fwcheck_entry(struct bfa_iocpf *iocpf)
{
bfa_ioc_hw_sem_init(iocpf->ioc);
bfa_ioc_hw_sem_get(iocpf->ioc);
}
/* Awaiting h/w semaphore to continue with version check. */
static void
bfa_iocpf_sm_fwcheck(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
struct bfa_ioc *ioc = iocpf->ioc;
switch (event) {
case IOCPF_E_SEMLOCKED:
if (bfa_ioc_firmware_lock(ioc)) {
if (bfa_ioc_sync_start(ioc)) {
bfa_ioc_sync_join(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_hwinit);
} else {
bfa_ioc_firmware_unlock(ioc);
bfa_nw_ioc_hw_sem_release(ioc);
mod_timer(&ioc->sem_timer, jiffies +
msecs_to_jiffies(BFA_IOC_HWSEM_TOV));
}
} else {
bfa_nw_ioc_hw_sem_release(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_mismatch);
}
break;
case IOCPF_E_SEM_ERROR:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_fail);
bfa_ioc_pf_hwfailed(ioc);
break;
case IOCPF_E_DISABLE:
bfa_ioc_hw_sem_get_cancel(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_reset);
bfa_ioc_pf_disabled(ioc);
break;
case IOCPF_E_STOP:
bfa_ioc_hw_sem_get_cancel(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_reset);
break;
default:
bfa_sm_fault(event);
}
}
/* Notify enable completion callback */
static void
bfa_iocpf_sm_mismatch_entry(struct bfa_iocpf *iocpf)
{
/* Call only the first time sm enters fwmismatch state. */
if (!iocpf->fw_mismatch_notified)
bfa_ioc_pf_fwmismatch(iocpf->ioc);
iocpf->fw_mismatch_notified = true;
mod_timer(&(iocpf->ioc)->iocpf_timer, jiffies +
msecs_to_jiffies(BFA_IOC_TOV));
}
/* Awaiting firmware version match. */
static void
bfa_iocpf_sm_mismatch(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
struct bfa_ioc *ioc = iocpf->ioc;
switch (event) {
case IOCPF_E_TIMEOUT:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_fwcheck);
break;
case IOCPF_E_DISABLE:
del_timer(&ioc->iocpf_timer);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_reset);
bfa_ioc_pf_disabled(ioc);
break;
case IOCPF_E_STOP:
del_timer(&ioc->iocpf_timer);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_reset);
break;
default:
bfa_sm_fault(event);
}
}
/* Request for semaphore. */
static void
bfa_iocpf_sm_semwait_entry(struct bfa_iocpf *iocpf)
{
bfa_ioc_hw_sem_get(iocpf->ioc);
}
/* Awaiting semaphore for h/w initialzation. */
static void
bfa_iocpf_sm_semwait(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
struct bfa_ioc *ioc = iocpf->ioc;
switch (event) {
case IOCPF_E_SEMLOCKED:
if (bfa_ioc_sync_complete(ioc)) {
bfa_ioc_sync_join(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_hwinit);
} else {
bfa_nw_ioc_hw_sem_release(ioc);
mod_timer(&ioc->sem_timer, jiffies +
msecs_to_jiffies(BFA_IOC_HWSEM_TOV));
}
break;
case IOCPF_E_SEM_ERROR:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_fail);
bfa_ioc_pf_hwfailed(ioc);
break;
case IOCPF_E_DISABLE:
bfa_ioc_hw_sem_get_cancel(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_disabling_sync);
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_iocpf_sm_hwinit_entry(struct bfa_iocpf *iocpf)
{
iocpf->poll_time = 0;
bfa_ioc_reset(iocpf->ioc, false);
}
/* Hardware is being initialized. Interrupts are enabled.
* Holding hardware semaphore lock.
*/
static void
bfa_iocpf_sm_hwinit(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
struct bfa_ioc *ioc = iocpf->ioc;
switch (event) {
case IOCPF_E_FWREADY:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_enabling);
break;
case IOCPF_E_TIMEOUT:
bfa_nw_ioc_hw_sem_release(ioc);
bfa_ioc_pf_failed(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_initfail_sync);
break;
case IOCPF_E_DISABLE:
del_timer(&ioc->iocpf_timer);
bfa_ioc_sync_leave(ioc);
bfa_nw_ioc_hw_sem_release(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_disabled);
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_iocpf_sm_enabling_entry(struct bfa_iocpf *iocpf)
{
mod_timer(&(iocpf->ioc)->iocpf_timer, jiffies +
msecs_to_jiffies(BFA_IOC_TOV));
/**
* Enable Interrupts before sending fw IOC ENABLE cmd.
*/
iocpf->ioc->cbfn->reset_cbfn(iocpf->ioc->bfa);
bfa_ioc_send_enable(iocpf->ioc);
}
/* Host IOC function is being enabled, awaiting response from firmware.
* Semaphore is acquired.
*/
static void
bfa_iocpf_sm_enabling(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
struct bfa_ioc *ioc = iocpf->ioc;
switch (event) {
case IOCPF_E_FWRSP_ENABLE:
del_timer(&ioc->iocpf_timer);
bfa_nw_ioc_hw_sem_release(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_ready);
break;
case IOCPF_E_INITFAIL:
del_timer(&ioc->iocpf_timer);
fallthrough;
case IOCPF_E_TIMEOUT:
bfa_nw_ioc_hw_sem_release(ioc);
if (event == IOCPF_E_TIMEOUT)
bfa_ioc_pf_failed(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_initfail_sync);
break;
case IOCPF_E_DISABLE:
del_timer(&ioc->iocpf_timer);
bfa_nw_ioc_hw_sem_release(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_disabling);
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_iocpf_sm_ready_entry(struct bfa_iocpf *iocpf)
{
bfa_ioc_pf_enabled(iocpf->ioc);
}
static void
bfa_iocpf_sm_ready(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
switch (event) {
case IOCPF_E_DISABLE:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_disabling);
break;
case IOCPF_E_GETATTRFAIL:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_initfail_sync);
break;
case IOCPF_E_FAIL:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_fail_sync);
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_iocpf_sm_disabling_entry(struct bfa_iocpf *iocpf)
{
mod_timer(&(iocpf->ioc)->iocpf_timer, jiffies +
msecs_to_jiffies(BFA_IOC_TOV));
bfa_ioc_send_disable(iocpf->ioc);
}
/* IOC is being disabled */
static void
bfa_iocpf_sm_disabling(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
struct bfa_ioc *ioc = iocpf->ioc;
switch (event) {
case IOCPF_E_FWRSP_DISABLE:
del_timer(&ioc->iocpf_timer);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_disabling_sync);
break;
case IOCPF_E_FAIL:
del_timer(&ioc->iocpf_timer);
fallthrough;
case IOCPF_E_TIMEOUT:
bfa_ioc_set_cur_ioc_fwstate(ioc, BFI_IOC_FAIL);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_disabling_sync);
break;
case IOCPF_E_FWRSP_ENABLE:
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_iocpf_sm_disabling_sync_entry(struct bfa_iocpf *iocpf)
{
bfa_ioc_hw_sem_get(iocpf->ioc);
}
/* IOC hb ack request is being removed. */
static void
bfa_iocpf_sm_disabling_sync(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
struct bfa_ioc *ioc = iocpf->ioc;
switch (event) {
case IOCPF_E_SEMLOCKED:
bfa_ioc_sync_leave(ioc);
bfa_nw_ioc_hw_sem_release(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_disabled);
break;
case IOCPF_E_SEM_ERROR:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_fail);
bfa_ioc_pf_hwfailed(ioc);
break;
case IOCPF_E_FAIL:
break;
default:
bfa_sm_fault(event);
}
}
/* IOC disable completion entry. */
static void
bfa_iocpf_sm_disabled_entry(struct bfa_iocpf *iocpf)
{
bfa_ioc_mbox_flush(iocpf->ioc);
bfa_ioc_pf_disabled(iocpf->ioc);
}
static void
bfa_iocpf_sm_disabled(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
struct bfa_ioc *ioc = iocpf->ioc;
switch (event) {
case IOCPF_E_ENABLE:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_semwait);
break;
case IOCPF_E_STOP:
bfa_ioc_firmware_unlock(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_reset);
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_iocpf_sm_initfail_sync_entry(struct bfa_iocpf *iocpf)
{
bfa_nw_ioc_debug_save_ftrc(iocpf->ioc);
bfa_ioc_hw_sem_get(iocpf->ioc);
}
/* Hardware initialization failed. */
static void
bfa_iocpf_sm_initfail_sync(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
struct bfa_ioc *ioc = iocpf->ioc;
switch (event) {
case IOCPF_E_SEMLOCKED:
bfa_ioc_notify_fail(ioc);
bfa_ioc_sync_leave(ioc);
bfa_ioc_set_cur_ioc_fwstate(ioc, BFI_IOC_FAIL);
bfa_nw_ioc_hw_sem_release(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_initfail);
break;
case IOCPF_E_SEM_ERROR:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_fail);
bfa_ioc_pf_hwfailed(ioc);
break;
case IOCPF_E_DISABLE:
bfa_ioc_hw_sem_get_cancel(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_disabling_sync);
break;
case IOCPF_E_STOP:
bfa_ioc_hw_sem_get_cancel(ioc);
bfa_ioc_firmware_unlock(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_reset);
break;
case IOCPF_E_FAIL:
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_iocpf_sm_initfail_entry(struct bfa_iocpf *iocpf)
{
}
/* Hardware initialization failed. */
static void
bfa_iocpf_sm_initfail(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
struct bfa_ioc *ioc = iocpf->ioc;
switch (event) {
case IOCPF_E_DISABLE:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_disabled);
break;
case IOCPF_E_STOP:
bfa_ioc_firmware_unlock(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_reset);
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_iocpf_sm_fail_sync_entry(struct bfa_iocpf *iocpf)
{
/**
* Mark IOC as failed in hardware and stop firmware.
*/
bfa_ioc_lpu_stop(iocpf->ioc);
/**
* Flush any queued up mailbox requests.
*/
bfa_ioc_mbox_flush(iocpf->ioc);
bfa_ioc_hw_sem_get(iocpf->ioc);
}
/* IOC is in failed state. */
static void
bfa_iocpf_sm_fail_sync(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
struct bfa_ioc *ioc = iocpf->ioc;
switch (event) {
case IOCPF_E_SEMLOCKED:
bfa_ioc_sync_ack(ioc);
bfa_ioc_notify_fail(ioc);
if (!iocpf->auto_recover) {
bfa_ioc_sync_leave(ioc);
bfa_ioc_set_cur_ioc_fwstate(ioc, BFI_IOC_FAIL);
bfa_nw_ioc_hw_sem_release(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_fail);
} else {
if (bfa_ioc_sync_complete(ioc))
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_hwinit);
else {
bfa_nw_ioc_hw_sem_release(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_semwait);
}
}
break;
case IOCPF_E_SEM_ERROR:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_fail);
bfa_ioc_pf_hwfailed(ioc);
break;
case IOCPF_E_DISABLE:
bfa_ioc_hw_sem_get_cancel(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_disabling_sync);
break;
case IOCPF_E_FAIL:
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_iocpf_sm_fail_entry(struct bfa_iocpf *iocpf)
{
}
/* IOC is in failed state. */
static void
bfa_iocpf_sm_fail(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
switch (event) {
case IOCPF_E_DISABLE:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_disabled);
break;
default:
bfa_sm_fault(event);
}
}
/* BFA IOC private functions */
/* Notify common modules registered for notification. */
static void
bfa_ioc_event_notify(struct bfa_ioc *ioc, enum bfa_ioc_event event)
{
struct bfa_ioc_notify *notify;
list_for_each_entry(notify, &ioc->notify_q, qe)
notify->cbfn(notify->cbarg, event);
}
static void
bfa_ioc_disable_comp(struct bfa_ioc *ioc)
{
ioc->cbfn->disable_cbfn(ioc->bfa);
bfa_ioc_event_notify(ioc, BFA_IOC_E_DISABLED);
}
bool
bfa_nw_ioc_sem_get(void __iomem *sem_reg)
{
u32 r32;
int cnt = 0;
#define BFA_SEM_SPINCNT 3000
r32 = readl(sem_reg);
while ((r32 & 1) && (cnt < BFA_SEM_SPINCNT)) {
cnt++;
udelay(2);
r32 = readl(sem_reg);
}
if (!(r32 & 1))
return true;
return false;
}
void
bfa_nw_ioc_sem_release(void __iomem *sem_reg)
{
readl(sem_reg);
writel(1, sem_reg);
}
/* Clear fwver hdr */
static void
bfa_ioc_fwver_clear(struct bfa_ioc *ioc)
{
u32 pgnum, loff = 0;
int i;
pgnum = PSS_SMEM_PGNUM(ioc->ioc_regs.smem_pg0, loff);
writel(pgnum, ioc->ioc_regs.host_page_num_fn);
for (i = 0; i < (sizeof(struct bfi_ioc_image_hdr) / sizeof(u32)); i++) {
writel(0, ioc->ioc_regs.smem_page_start + loff);
loff += sizeof(u32);
}
}
static void
bfa_ioc_hw_sem_init(struct bfa_ioc *ioc)
{
struct bfi_ioc_image_hdr fwhdr;
u32 fwstate, r32;
/* Spin on init semaphore to serialize. */
r32 = readl(ioc->ioc_regs.ioc_init_sem_reg);
while (r32 & 0x1) {
udelay(20);
r32 = readl(ioc->ioc_regs.ioc_init_sem_reg);
}
fwstate = bfa_ioc_get_cur_ioc_fwstate(ioc);
if (fwstate == BFI_IOC_UNINIT) {
writel(1, ioc->ioc_regs.ioc_init_sem_reg);
return;
}
bfa_nw_ioc_fwver_get(ioc, &fwhdr);
if (swab32(fwhdr.exec) == BFI_FWBOOT_TYPE_NORMAL) {
writel(1, ioc->ioc_regs.ioc_init_sem_reg);
return;
}
bfa_ioc_fwver_clear(ioc);
bfa_ioc_set_cur_ioc_fwstate(ioc, BFI_IOC_UNINIT);
bfa_ioc_set_alt_ioc_fwstate(ioc, BFI_IOC_UNINIT);
/*
* Try to lock and then unlock the semaphore.
*/
readl(ioc->ioc_regs.ioc_sem_reg);
writel(1, ioc->ioc_regs.ioc_sem_reg);
/* Unlock init semaphore */
writel(1, ioc->ioc_regs.ioc_init_sem_reg);
}
static void
bfa_ioc_hw_sem_get(struct bfa_ioc *ioc)
{
u32 r32;
/**
* First read to the semaphore register will return 0, subsequent reads
* will return 1. Semaphore is released by writing 1 to the register
*/
r32 = readl(ioc->ioc_regs.ioc_sem_reg);
if (r32 == ~0) {
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_SEM_ERROR);
return;
}
if (!(r32 & 1)) {
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_SEMLOCKED);
return;
}
mod_timer(&ioc->sem_timer, jiffies +
msecs_to_jiffies(BFA_IOC_HWSEM_TOV));
}
void
bfa_nw_ioc_hw_sem_release(struct bfa_ioc *ioc)
{
writel(1, ioc->ioc_regs.ioc_sem_reg);
}
static void
bfa_ioc_hw_sem_get_cancel(struct bfa_ioc *ioc)
{
del_timer(&ioc->sem_timer);
}
/* Initialize LPU local memory (aka secondary memory / SRAM) */
static void
bfa_ioc_lmem_init(struct bfa_ioc *ioc)
{
u32 pss_ctl;
int i;
#define PSS_LMEM_INIT_TIME 10000
pss_ctl = readl(ioc->ioc_regs.pss_ctl_reg);
pss_ctl &= ~__PSS_LMEM_RESET;
pss_ctl |= __PSS_LMEM_INIT_EN;
/*
* i2c workaround 12.5khz clock
*/
pss_ctl |= __PSS_I2C_CLK_DIV(3UL);
writel(pss_ctl, ioc->ioc_regs.pss_ctl_reg);
/**
* wait for memory initialization to be complete
*/
i = 0;
do {
pss_ctl = readl(ioc->ioc_regs.pss_ctl_reg);
i++;
} while (!(pss_ctl & __PSS_LMEM_INIT_DONE) && (i < PSS_LMEM_INIT_TIME));
/**
* If memory initialization is not successful, IOC timeout will catch
* such failures.
*/
BUG_ON(!(pss_ctl & __PSS_LMEM_INIT_DONE));
pss_ctl &= ~(__PSS_LMEM_INIT_DONE | __PSS_LMEM_INIT_EN);
writel(pss_ctl, ioc->ioc_regs.pss_ctl_reg);
}
static void
bfa_ioc_lpu_start(struct bfa_ioc *ioc)
{
u32 pss_ctl;
/**
* Take processor out of reset.
*/
pss_ctl = readl(ioc->ioc_regs.pss_ctl_reg);
pss_ctl &= ~__PSS_LPU0_RESET;
writel(pss_ctl, ioc->ioc_regs.pss_ctl_reg);
}
static void
bfa_ioc_lpu_stop(struct bfa_ioc *ioc)
{
u32 pss_ctl;
/**
* Put processors in reset.
*/
pss_ctl = readl(ioc->ioc_regs.pss_ctl_reg);
pss_ctl |= (__PSS_LPU0_RESET | __PSS_LPU1_RESET);
writel(pss_ctl, ioc->ioc_regs.pss_ctl_reg);
}
/* Get driver and firmware versions. */
void
bfa_nw_ioc_fwver_get(struct bfa_ioc *ioc, struct bfi_ioc_image_hdr *fwhdr)
{
u32 pgnum;
u32 loff = 0;
int i;
u32 *fwsig = (u32 *) fwhdr;
pgnum = bfa_ioc_smem_pgnum(ioc, loff);
writel(pgnum, ioc->ioc_regs.host_page_num_fn);
for (i = 0; i < (sizeof(struct bfi_ioc_image_hdr) / sizeof(u32));
i++) {
fwsig[i] =
swab32(readl(loff + ioc->ioc_regs.smem_page_start));
loff += sizeof(u32);
}
}
static bool
bfa_ioc_fwver_md5_check(struct bfi_ioc_image_hdr *fwhdr_1,
struct bfi_ioc_image_hdr *fwhdr_2)
{
int i;
for (i = 0; i < BFI_IOC_MD5SUM_SZ; i++) {
if (fwhdr_1->md5sum[i] != fwhdr_2->md5sum[i])
return false;
}
return true;
}
/* Returns TRUE if major minor and maintenance are same.
* If patch version are same, check for MD5 Checksum to be same.
*/
static bool
bfa_ioc_fw_ver_compatible(struct bfi_ioc_image_hdr *drv_fwhdr,
struct bfi_ioc_image_hdr *fwhdr_to_cmp)
{
if (drv_fwhdr->signature != fwhdr_to_cmp->signature)
return false;
if (drv_fwhdr->fwver.major != fwhdr_to_cmp->fwver.major)
return false;
if (drv_fwhdr->fwver.minor != fwhdr_to_cmp->fwver.minor)
return false;
if (drv_fwhdr->fwver.maint != fwhdr_to_cmp->fwver.maint)
return false;
if (drv_fwhdr->fwver.patch == fwhdr_to_cmp->fwver.patch &&
drv_fwhdr->fwver.phase == fwhdr_to_cmp->fwver.phase &&
drv_fwhdr->fwver.build == fwhdr_to_cmp->fwver.build)
return bfa_ioc_fwver_md5_check(drv_fwhdr, fwhdr_to_cmp);
return true;
}
static bool
bfa_ioc_flash_fwver_valid(struct bfi_ioc_image_hdr *flash_fwhdr)
{
if (flash_fwhdr->fwver.major == 0 || flash_fwhdr->fwver.major == 0xFF)
return false;
return true;
}
static bool
fwhdr_is_ga(struct bfi_ioc_image_hdr *fwhdr)
{
if (fwhdr->fwver.phase == 0 &&
fwhdr->fwver.build == 0)
return false;
return true;
}
/* Returns TRUE if both are compatible and patch of fwhdr_to_cmp is better. */
static enum bfi_ioc_img_ver_cmp
bfa_ioc_fw_ver_patch_cmp(struct bfi_ioc_image_hdr *base_fwhdr,
struct bfi_ioc_image_hdr *fwhdr_to_cmp)
{
if (!bfa_ioc_fw_ver_compatible(base_fwhdr, fwhdr_to_cmp))
return BFI_IOC_IMG_VER_INCOMP;
if (fwhdr_to_cmp->fwver.patch > base_fwhdr->fwver.patch)
return BFI_IOC_IMG_VER_BETTER;
else if (fwhdr_to_cmp->fwver.patch < base_fwhdr->fwver.patch)
return BFI_IOC_IMG_VER_OLD;
/* GA takes priority over internal builds of the same patch stream.
* At this point major minor maint and patch numbers are same.
*/
if (fwhdr_is_ga(base_fwhdr))
if (fwhdr_is_ga(fwhdr_to_cmp))
return BFI_IOC_IMG_VER_SAME;
else
return BFI_IOC_IMG_VER_OLD;
else
if (fwhdr_is_ga(fwhdr_to_cmp))
return BFI_IOC_IMG_VER_BETTER;
if (fwhdr_to_cmp->fwver.phase > base_fwhdr->fwver.phase)
return BFI_IOC_IMG_VER_BETTER;
else if (fwhdr_to_cmp->fwver.phase < base_fwhdr->fwver.phase)
return BFI_IOC_IMG_VER_OLD;
if (fwhdr_to_cmp->fwver.build > base_fwhdr->fwver.build)
return BFI_IOC_IMG_VER_BETTER;
else if (fwhdr_to_cmp->fwver.build < base_fwhdr->fwver.build)
return BFI_IOC_IMG_VER_OLD;
/* All Version Numbers are equal.
* Md5 check to be done as a part of compatibility check.
*/
return BFI_IOC_IMG_VER_SAME;
}
/* register definitions */
#define FLI_CMD_REG 0x0001d000
#define FLI_WRDATA_REG 0x0001d00c
#define FLI_RDDATA_REG 0x0001d010
#define FLI_ADDR_REG 0x0001d004
#define FLI_DEV_STATUS_REG 0x0001d014
#define BFA_FLASH_FIFO_SIZE 128 /* fifo size */
#define BFA_FLASH_CHECK_MAX 10000 /* max # of status check */
#define BFA_FLASH_BLOCKING_OP_MAX 1000000 /* max # of blocking op check */
#define BFA_FLASH_WIP_MASK 0x01 /* write in progress bit mask */
#define NFC_STATE_RUNNING 0x20000001
#define NFC_STATE_PAUSED 0x00004560
#define NFC_VER_VALID 0x147
enum bfa_flash_cmd {
BFA_FLASH_FAST_READ = 0x0b, /* fast read */
BFA_FLASH_WRITE_ENABLE = 0x06, /* write enable */
BFA_FLASH_SECTOR_ERASE = 0xd8, /* sector erase */
BFA_FLASH_WRITE = 0x02, /* write */
BFA_FLASH_READ_STATUS = 0x05, /* read status */
};
/* hardware error definition */
enum bfa_flash_err {
BFA_FLASH_NOT_PRESENT = -1, /*!< flash not present */
BFA_FLASH_UNINIT = -2, /*!< flash not initialized */
BFA_FLASH_BAD = -3, /*!< flash bad */
BFA_FLASH_BUSY = -4, /*!< flash busy */
BFA_FLASH_ERR_CMD_ACT = -5, /*!< command active never cleared */
BFA_FLASH_ERR_FIFO_CNT = -6, /*!< fifo count never cleared */
BFA_FLASH_ERR_WIP = -7, /*!< write-in-progress never cleared */
BFA_FLASH_ERR_TIMEOUT = -8, /*!< fli timeout */
BFA_FLASH_ERR_LEN = -9, /*!< invalid length */
};
/* flash command register data structure */
union bfa_flash_cmd_reg {
struct {
#ifdef __BIG_ENDIAN
u32 act:1;
u32 rsv:1;
u32 write_cnt:9;
u32 read_cnt:9;
u32 addr_cnt:4;
u32 cmd:8;
#else
u32 cmd:8;
u32 addr_cnt:4;
u32 read_cnt:9;
u32 write_cnt:9;
u32 rsv:1;
u32 act:1;
#endif
} r;
u32 i;
};
/* flash device status register data structure */
union bfa_flash_dev_status_reg {
struct {
#ifdef __BIG_ENDIAN
u32 rsv:21;
u32 fifo_cnt:6;
u32 busy:1;
u32 init_status:1;
u32 present:1;
u32 bad:1;
u32 good:1;
#else
u32 good:1;
u32 bad:1;
u32 present:1;
u32 init_status:1;
u32 busy:1;
u32 fifo_cnt:6;
u32 rsv:21;
#endif
} r;
u32 i;
};
/* flash address register data structure */
union bfa_flash_addr_reg {
struct {
#ifdef __BIG_ENDIAN
u32 addr:24;
u32 dummy:8;
#else
u32 dummy:8;
u32 addr:24;
#endif
} r;
u32 i;
};
/* Flash raw private functions */
static void
bfa_flash_set_cmd(void __iomem *pci_bar, u8 wr_cnt,
u8 rd_cnt, u8 ad_cnt, u8 op)
{
union bfa_flash_cmd_reg cmd;
cmd.i = 0;
cmd.r.act = 1;
cmd.r.write_cnt = wr_cnt;
cmd.r.read_cnt = rd_cnt;
cmd.r.addr_cnt = ad_cnt;
cmd.r.cmd = op;
writel(cmd.i, (pci_bar + FLI_CMD_REG));
}
static void
bfa_flash_set_addr(void __iomem *pci_bar, u32 address)
{
union bfa_flash_addr_reg addr;
addr.r.addr = address & 0x00ffffff;
addr.r.dummy = 0;
writel(addr.i, (pci_bar + FLI_ADDR_REG));
}
static int
bfa_flash_cmd_act_check(void __iomem *pci_bar)
{
union bfa_flash_cmd_reg cmd;
cmd.i = readl(pci_bar + FLI_CMD_REG);
if (cmd.r.act)
return BFA_FLASH_ERR_CMD_ACT;
return 0;
}
/* Flush FLI data fifo. */
static int
bfa_flash_fifo_flush(void __iomem *pci_bar)
{
u32 i;
union bfa_flash_dev_status_reg dev_status;
dev_status.i = readl(pci_bar + FLI_DEV_STATUS_REG);
if (!dev_status.r.fifo_cnt)
return 0;
/* fifo counter in terms of words */
for (i = 0; i < dev_status.r.fifo_cnt; i++)
readl(pci_bar + FLI_RDDATA_REG);
/* Check the device status. It may take some time. */
for (i = 0; i < BFA_FLASH_CHECK_MAX; i++) {
dev_status.i = readl(pci_bar + FLI_DEV_STATUS_REG);
if (!dev_status.r.fifo_cnt)
break;
}
if (dev_status.r.fifo_cnt)
return BFA_FLASH_ERR_FIFO_CNT;
return 0;
}
/* Read flash status. */
static int
bfa_flash_status_read(void __iomem *pci_bar)
{
union bfa_flash_dev_status_reg dev_status;
int status;
u32 ret_status;
int i;
status = bfa_flash_fifo_flush(pci_bar);
if (status < 0)
return status;
bfa_flash_set_cmd(pci_bar, 0, 4, 0, BFA_FLASH_READ_STATUS);
for (i = 0; i < BFA_FLASH_CHECK_MAX; i++) {
status = bfa_flash_cmd_act_check(pci_bar);
if (!status)
break;
}
if (status)
return status;
dev_status.i = readl(pci_bar + FLI_DEV_STATUS_REG);
if (!dev_status.r.fifo_cnt)
return BFA_FLASH_BUSY;
ret_status = readl(pci_bar + FLI_RDDATA_REG);
ret_status >>= 24;
status = bfa_flash_fifo_flush(pci_bar);
if (status < 0)
return status;
return ret_status;
}
/* Start flash read operation. */
static int
bfa_flash_read_start(void __iomem *pci_bar, u32 offset, u32 len,
char *buf)
{
int status;
/* len must be mutiple of 4 and not exceeding fifo size */
if (len == 0 || len > BFA_FLASH_FIFO_SIZE || (len & 0x03) != 0)
return BFA_FLASH_ERR_LEN;
/* check status */
status = bfa_flash_status_read(pci_bar);
if (status == BFA_FLASH_BUSY)
status = bfa_flash_status_read(pci_bar);
if (status < 0)
return status;
/* check if write-in-progress bit is cleared */
if (status & BFA_FLASH_WIP_MASK)
return BFA_FLASH_ERR_WIP;
bfa_flash_set_addr(pci_bar, offset);
bfa_flash_set_cmd(pci_bar, 0, (u8)len, 4, BFA_FLASH_FAST_READ);
return 0;
}
/* Check flash read operation. */
static u32
bfa_flash_read_check(void __iomem *pci_bar)
{
if (bfa_flash_cmd_act_check(pci_bar))
return 1;
return 0;
}
/* End flash read operation. */
static void
bfa_flash_read_end(void __iomem *pci_bar, u32 len, char *buf)
{
u32 i;
/* read data fifo up to 32 words */
for (i = 0; i < len; i += 4) {
u32 w = readl(pci_bar + FLI_RDDATA_REG);
*((u32 *)(buf + i)) = swab32(w);
}
bfa_flash_fifo_flush(pci_bar);
}
/* Perform flash raw read. */
#define FLASH_BLOCKING_OP_MAX 500
#define FLASH_SEM_LOCK_REG 0x18820
static int
bfa_raw_sem_get(void __iomem *bar)
{
int locked;
locked = readl(bar + FLASH_SEM_LOCK_REG);
return !locked;
}
static enum bfa_status
bfa_flash_sem_get(void __iomem *bar)
{
u32 n = FLASH_BLOCKING_OP_MAX;
while (!bfa_raw_sem_get(bar)) {
if (--n <= 0)
return BFA_STATUS_BADFLASH;
mdelay(10);
}
return BFA_STATUS_OK;
}
static void
bfa_flash_sem_put(void __iomem *bar)
{
writel(0, (bar + FLASH_SEM_LOCK_REG));
}
static enum bfa_status
bfa_flash_raw_read(void __iomem *pci_bar, u32 offset, char *buf,
u32 len)
{
u32 n;
int status;
u32 off, l, s, residue, fifo_sz;
residue = len;
off = 0;
fifo_sz = BFA_FLASH_FIFO_SIZE;
status = bfa_flash_sem_get(pci_bar);
if (status != BFA_STATUS_OK)
return status;
while (residue) {
s = offset + off;
n = s / fifo_sz;
l = (n + 1) * fifo_sz - s;
if (l > residue)
l = residue;
status = bfa_flash_read_start(pci_bar, offset + off, l,
&buf[off]);
if (status < 0) {
bfa_flash_sem_put(pci_bar);
return BFA_STATUS_FAILED;
}
n = BFA_FLASH_BLOCKING_OP_MAX;
while (bfa_flash_read_check(pci_bar)) {
if (--n <= 0) {
bfa_flash_sem_put(pci_bar);
return BFA_STATUS_FAILED;
}
}
bfa_flash_read_end(pci_bar, l, &buf[off]);
residue -= l;
off += l;
}
bfa_flash_sem_put(pci_bar);
return BFA_STATUS_OK;
}
#define BFA_FLASH_PART_FWIMG_ADDR 0x100000 /* fw image address */
static enum bfa_status
bfa_nw_ioc_flash_img_get_chnk(struct bfa_ioc *ioc, u32 off,
u32 *fwimg)
{
return bfa_flash_raw_read(ioc->pcidev.pci_bar_kva,
BFA_FLASH_PART_FWIMG_ADDR + (off * sizeof(u32)),
(char *)fwimg, BFI_FLASH_CHUNK_SZ);
}
static enum bfi_ioc_img_ver_cmp
bfa_ioc_flash_fwver_cmp(struct bfa_ioc *ioc,
struct bfi_ioc_image_hdr *base_fwhdr)
{
struct bfi_ioc_image_hdr *flash_fwhdr;
enum bfa_status status;
u32 fwimg[BFI_FLASH_CHUNK_SZ_WORDS];
status = bfa_nw_ioc_flash_img_get_chnk(ioc, 0, fwimg);
if (status != BFA_STATUS_OK)
return BFI_IOC_IMG_VER_INCOMP;
flash_fwhdr = (struct bfi_ioc_image_hdr *)fwimg;
if (bfa_ioc_flash_fwver_valid(flash_fwhdr))
return bfa_ioc_fw_ver_patch_cmp(base_fwhdr, flash_fwhdr);
else
return BFI_IOC_IMG_VER_INCOMP;
}
/*
* Returns TRUE if driver is willing to work with current smem f/w version.
*/
bool
bfa_nw_ioc_fwver_cmp(struct bfa_ioc *ioc, struct bfi_ioc_image_hdr *fwhdr)
{
struct bfi_ioc_image_hdr *drv_fwhdr;
enum bfi_ioc_img_ver_cmp smem_flash_cmp, drv_smem_cmp;
drv_fwhdr = (struct bfi_ioc_image_hdr *)
bfa_cb_image_get_chunk(bfa_ioc_asic_gen(ioc), 0);
/* If smem is incompatible or old, driver should not work with it. */
drv_smem_cmp = bfa_ioc_fw_ver_patch_cmp(drv_fwhdr, fwhdr);
if (drv_smem_cmp == BFI_IOC_IMG_VER_INCOMP ||
drv_smem_cmp == BFI_IOC_IMG_VER_OLD) {
return false;
}
/* IF Flash has a better F/W than smem do not work with smem.
* If smem f/w == flash f/w, as smem f/w not old | incmp, work with it.
* If Flash is old or incomp work with smem iff smem f/w == drv f/w.
*/
smem_flash_cmp = bfa_ioc_flash_fwver_cmp(ioc, fwhdr);
if (smem_flash_cmp == BFI_IOC_IMG_VER_BETTER)
return false;
else if (smem_flash_cmp == BFI_IOC_IMG_VER_SAME)
return true;
else
return (drv_smem_cmp == BFI_IOC_IMG_VER_SAME) ?
true : false;
}
/* Return true if current running version is valid. Firmware signature and
* execution context (driver/bios) must match.
*/
static bool
bfa_ioc_fwver_valid(struct bfa_ioc *ioc, u32 boot_env)
{
struct bfi_ioc_image_hdr fwhdr;
bfa_nw_ioc_fwver_get(ioc, &fwhdr);
if (swab32(fwhdr.bootenv) != boot_env)
return false;
return bfa_nw_ioc_fwver_cmp(ioc, &fwhdr);
}
/* Conditionally flush any pending message from firmware at start. */
static void
bfa_ioc_msgflush(struct bfa_ioc *ioc)
{
u32 r32;
r32 = readl(ioc->ioc_regs.lpu_mbox_cmd);
if (r32)
writel(1, ioc->ioc_regs.lpu_mbox_cmd);
}
static void
bfa_ioc_hwinit(struct bfa_ioc *ioc, bool force)
{
enum bfi_ioc_state ioc_fwstate;
bool fwvalid;
u32 boot_env;
ioc_fwstate = bfa_ioc_get_cur_ioc_fwstate(ioc);
if (force)
ioc_fwstate = BFI_IOC_UNINIT;
boot_env = BFI_FWBOOT_ENV_OS;
/**
* check if firmware is valid
*/
fwvalid = (ioc_fwstate == BFI_IOC_UNINIT) ?
false : bfa_ioc_fwver_valid(ioc, boot_env);
if (!fwvalid) {
if (bfa_ioc_boot(ioc, BFI_FWBOOT_TYPE_NORMAL, boot_env) ==
BFA_STATUS_OK)
bfa_ioc_poll_fwinit(ioc);
return;
}
/**
* If hardware initialization is in progress (initialized by other IOC),
* just wait for an initialization completion interrupt.
*/
if (ioc_fwstate == BFI_IOC_INITING) {
bfa_ioc_poll_fwinit(ioc);
return;
}
/**
* If IOC function is disabled and firmware version is same,
* just re-enable IOC.
*/
if (ioc_fwstate == BFI_IOC_DISABLED || ioc_fwstate == BFI_IOC_OP) {
/**
* When using MSI-X any pending firmware ready event should
* be flushed. Otherwise MSI-X interrupts are not delivered.
*/
bfa_ioc_msgflush(ioc);
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_FWREADY);
return;
}
/**
* Initialize the h/w for any other states.
*/
if (bfa_ioc_boot(ioc, BFI_FWBOOT_TYPE_NORMAL, boot_env) ==
BFA_STATUS_OK)
bfa_ioc_poll_fwinit(ioc);
}
void
bfa_nw_ioc_timeout(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(ioc, IOC_E_TIMEOUT);
}
static void
bfa_ioc_mbox_send(struct bfa_ioc *ioc, void *ioc_msg, int len)
{
u32 *msgp = (u32 *) ioc_msg;
u32 i;
BUG_ON(!(len <= BFI_IOC_MSGLEN_MAX));
/*
* first write msg to mailbox registers
*/
for (i = 0; i < len / sizeof(u32); i++)
writel(cpu_to_le32(msgp[i]),
ioc->ioc_regs.hfn_mbox + i * sizeof(u32));
for (; i < BFI_IOC_MSGLEN_MAX / sizeof(u32); i++)
writel(0, ioc->ioc_regs.hfn_mbox + i * sizeof(u32));
/*
* write 1 to mailbox CMD to trigger LPU event
*/
writel(1, ioc->ioc_regs.hfn_mbox_cmd);
(void) readl(ioc->ioc_regs.hfn_mbox_cmd);
}
static void
bfa_ioc_send_enable(struct bfa_ioc *ioc)
{
struct bfi_ioc_ctrl_req enable_req;
bfi_h2i_set(enable_req.mh, BFI_MC_IOC, BFI_IOC_H2I_ENABLE_REQ,
bfa_ioc_portid(ioc));
enable_req.clscode = htons(ioc->clscode);
enable_req.rsvd = htons(0);
/* overflow in 2106 */
enable_req.tv_sec = ntohl(ktime_get_real_seconds());
bfa_ioc_mbox_send(ioc, &enable_req, sizeof(struct bfi_ioc_ctrl_req));
}
static void
bfa_ioc_send_disable(struct bfa_ioc *ioc)
{
struct bfi_ioc_ctrl_req disable_req;
bfi_h2i_set(disable_req.mh, BFI_MC_IOC, BFI_IOC_H2I_DISABLE_REQ,
bfa_ioc_portid(ioc));
disable_req.clscode = htons(ioc->clscode);
disable_req.rsvd = htons(0);
/* overflow in 2106 */
disable_req.tv_sec = ntohl(ktime_get_real_seconds());
bfa_ioc_mbox_send(ioc, &disable_req, sizeof(struct bfi_ioc_ctrl_req));
}
static void
bfa_ioc_send_getattr(struct bfa_ioc *ioc)
{
struct bfi_ioc_getattr_req attr_req;
bfi_h2i_set(attr_req.mh, BFI_MC_IOC, BFI_IOC_H2I_GETATTR_REQ,
bfa_ioc_portid(ioc));
bfa_dma_be_addr_set(attr_req.attr_addr, ioc->attr_dma.pa);
bfa_ioc_mbox_send(ioc, &attr_req, sizeof(attr_req));
}
void
bfa_nw_ioc_hb_check(struct bfa_ioc *ioc)
{
u32 hb_count;
hb_count = readl(ioc->ioc_regs.heartbeat);
if (ioc->hb_count == hb_count) {
bfa_ioc_recover(ioc);
return;
} else {
ioc->hb_count = hb_count;
}
bfa_ioc_mbox_poll(ioc);
mod_timer(&ioc->hb_timer, jiffies +
msecs_to_jiffies(BFA_IOC_HB_TOV));
}
static void
bfa_ioc_hb_monitor(struct bfa_ioc *ioc)
{
ioc->hb_count = readl(ioc->ioc_regs.heartbeat);
mod_timer(&ioc->hb_timer, jiffies +
msecs_to_jiffies(BFA_IOC_HB_TOV));
}
static void
bfa_ioc_hb_stop(struct bfa_ioc *ioc)
{
del_timer(&ioc->hb_timer);
}
/* Initiate a full firmware download. */
static enum bfa_status
bfa_ioc_download_fw(struct bfa_ioc *ioc, u32 boot_type,
u32 boot_env)
{
u32 *fwimg;
u32 pgnum;
u32 loff = 0;
u32 chunkno = 0;
u32 i;
u32 asicmode;
u32 fwimg_size;
u32 fwimg_buf[BFI_FLASH_CHUNK_SZ_WORDS];
enum bfa_status status;
if (boot_env == BFI_FWBOOT_ENV_OS &&
boot_type == BFI_FWBOOT_TYPE_FLASH) {
fwimg_size = BFI_FLASH_IMAGE_SZ/sizeof(u32);
status = bfa_nw_ioc_flash_img_get_chnk(ioc,
BFA_IOC_FLASH_CHUNK_ADDR(chunkno), fwimg_buf);
if (status != BFA_STATUS_OK)
return status;
fwimg = fwimg_buf;
} else {
fwimg_size = bfa_cb_image_get_size(bfa_ioc_asic_gen(ioc));
fwimg = bfa_cb_image_get_chunk(bfa_ioc_asic_gen(ioc),
BFA_IOC_FLASH_CHUNK_ADDR(chunkno));
}
pgnum = bfa_ioc_smem_pgnum(ioc, loff);
writel(pgnum, ioc->ioc_regs.host_page_num_fn);
for (i = 0; i < fwimg_size; i++) {
if (BFA_IOC_FLASH_CHUNK_NO(i) != chunkno) {
chunkno = BFA_IOC_FLASH_CHUNK_NO(i);
if (boot_env == BFI_FWBOOT_ENV_OS &&
boot_type == BFI_FWBOOT_TYPE_FLASH) {
status = bfa_nw_ioc_flash_img_get_chnk(ioc,
BFA_IOC_FLASH_CHUNK_ADDR(chunkno),
fwimg_buf);
if (status != BFA_STATUS_OK)
return status;
fwimg = fwimg_buf;
} else {
fwimg = bfa_cb_image_get_chunk(
bfa_ioc_asic_gen(ioc),
BFA_IOC_FLASH_CHUNK_ADDR(chunkno));
}
}
/**
* write smem
*/
writel(swab32(fwimg[BFA_IOC_FLASH_OFFSET_IN_CHUNK(i)]),
ioc->ioc_regs.smem_page_start + loff);
loff += sizeof(u32);
/**
* handle page offset wrap around
*/
loff = PSS_SMEM_PGOFF(loff);
if (loff == 0) {
pgnum++;
writel(pgnum,
ioc->ioc_regs.host_page_num_fn);
}
}
writel(bfa_ioc_smem_pgnum(ioc, 0),
ioc->ioc_regs.host_page_num_fn);
/*
* Set boot type, env and device mode at the end.
*/
if (boot_env == BFI_FWBOOT_ENV_OS &&
boot_type == BFI_FWBOOT_TYPE_FLASH) {
boot_type = BFI_FWBOOT_TYPE_NORMAL;
}
asicmode = BFI_FWBOOT_DEVMODE(ioc->asic_gen, ioc->asic_mode,
ioc->port0_mode, ioc->port1_mode);
writel(asicmode, ((ioc->ioc_regs.smem_page_start)
+ BFI_FWBOOT_DEVMODE_OFF));
writel(boot_type, ((ioc->ioc_regs.smem_page_start)
+ (BFI_FWBOOT_TYPE_OFF)));
writel(boot_env, ((ioc->ioc_regs.smem_page_start)
+ (BFI_FWBOOT_ENV_OFF)));
return BFA_STATUS_OK;
}
static void
bfa_ioc_reset(struct bfa_ioc *ioc, bool force)
{
bfa_ioc_hwinit(ioc, force);
}
/* BFA ioc enable reply by firmware */
static void
bfa_ioc_enable_reply(struct bfa_ioc *ioc, enum bfa_mode port_mode,
u8 cap_bm)
{
struct bfa_iocpf *iocpf = &ioc->iocpf;
ioc->port_mode = ioc->port_mode_cfg = port_mode;
ioc->ad_cap_bm = cap_bm;
bfa_fsm_send_event(iocpf, IOCPF_E_FWRSP_ENABLE);
}
/* Update BFA configuration from firmware configuration. */
static void
bfa_ioc_getattr_reply(struct bfa_ioc *ioc)
{
struct bfi_ioc_attr *attr = ioc->attr;
attr->adapter_prop = ntohl(attr->adapter_prop);
attr->card_type = ntohl(attr->card_type);
attr->maxfrsize = ntohs(attr->maxfrsize);
bfa_fsm_send_event(ioc, IOC_E_FWRSP_GETATTR);
}
/* Attach time initialization of mbox logic. */
static void
bfa_ioc_mbox_attach(struct bfa_ioc *ioc)
{
struct bfa_ioc_mbox_mod *mod = &ioc->mbox_mod;
int mc;
INIT_LIST_HEAD(&mod->cmd_q);
for (mc = 0; mc < BFI_MC_MAX; mc++) {
mod->mbhdlr[mc].cbfn = NULL;
mod->mbhdlr[mc].cbarg = ioc->bfa;
}
}
/* Mbox poll timer -- restarts any pending mailbox requests. */
static void
bfa_ioc_mbox_poll(struct bfa_ioc *ioc)
{
struct bfa_ioc_mbox_mod *mod = &ioc->mbox_mod;
struct bfa_mbox_cmd *cmd;
bfa_mbox_cmd_cbfn_t cbfn;
void *cbarg;
u32 stat;
/**
* If no command pending, do nothing
*/
if (list_empty(&mod->cmd_q))
return;
/**
* If previous command is not yet fetched by firmware, do nothing
*/
stat = readl(ioc->ioc_regs.hfn_mbox_cmd);
if (stat)
return;
/**
* Enqueue command to firmware.
*/
cmd = list_first_entry(&mod->cmd_q, struct bfa_mbox_cmd, qe);
list_del(&cmd->qe);
bfa_ioc_mbox_send(ioc, cmd->msg, sizeof(cmd->msg));
/**
* Give a callback to the client, indicating that the command is sent
*/
if (cmd->cbfn) {
cbfn = cmd->cbfn;
cbarg = cmd->cbarg;
cmd->cbfn = NULL;
cbfn(cbarg);
}
}
/* Cleanup any pending requests. */
static void
bfa_ioc_mbox_flush(struct bfa_ioc *ioc)
{
struct bfa_ioc_mbox_mod *mod = &ioc->mbox_mod;
struct bfa_mbox_cmd *cmd;
while (!list_empty(&mod->cmd_q)) {
cmd = list_first_entry(&mod->cmd_q, struct bfa_mbox_cmd, qe);
list_del(&cmd->qe);
}
}
/**
* bfa_nw_ioc_smem_read - Read data from SMEM to host through PCI memmap
*
* @ioc: memory for IOC
* @tbuf: app memory to store data from smem
* @soff: smem offset
* @sz: size of smem in bytes
*/
static int
bfa_nw_ioc_smem_read(struct bfa_ioc *ioc, void *tbuf, u32 soff, u32 sz)
{
u32 pgnum, loff, r32;
int i, len;
u32 *buf = tbuf;
pgnum = PSS_SMEM_PGNUM(ioc->ioc_regs.smem_pg0, soff);
loff = PSS_SMEM_PGOFF(soff);
/*
* Hold semaphore to serialize pll init and fwtrc.
*/
if (!bfa_nw_ioc_sem_get(ioc->ioc_regs.ioc_init_sem_reg))
return 1;
writel(pgnum, ioc->ioc_regs.host_page_num_fn);
len = sz/sizeof(u32);
for (i = 0; i < len; i++) {
r32 = swab32(readl(loff + ioc->ioc_regs.smem_page_start));
buf[i] = be32_to_cpu(r32);
loff += sizeof(u32);
/**
* handle page offset wrap around
*/
loff = PSS_SMEM_PGOFF(loff);
if (loff == 0) {
pgnum++;
writel(pgnum, ioc->ioc_regs.host_page_num_fn);
}
}
writel(PSS_SMEM_PGNUM(ioc->ioc_regs.smem_pg0, 0),
ioc->ioc_regs.host_page_num_fn);
/*
* release semaphore
*/
readl(ioc->ioc_regs.ioc_init_sem_reg);
writel(1, ioc->ioc_regs.ioc_init_sem_reg);
return 0;
}
/* Retrieve saved firmware trace from a prior IOC failure. */
int
bfa_nw_ioc_debug_fwtrc(struct bfa_ioc *ioc, void *trcdata, int *trclen)
{
u32 loff = BFI_IOC_TRC_OFF + BNA_DBG_FWTRC_LEN * ioc->port_id;
int tlen, status = 0;
tlen = *trclen;
if (tlen > BNA_DBG_FWTRC_LEN)
tlen = BNA_DBG_FWTRC_LEN;
status = bfa_nw_ioc_smem_read(ioc, trcdata, loff, tlen);
*trclen = tlen;
return status;
}
/* Save firmware trace if configured. */
static void
bfa_nw_ioc_debug_save_ftrc(struct bfa_ioc *ioc)
{
int tlen;
if (ioc->dbg_fwsave_once) {
ioc->dbg_fwsave_once = false;
if (ioc->dbg_fwsave_len) {
tlen = ioc->dbg_fwsave_len;
bfa_nw_ioc_debug_fwtrc(ioc, ioc->dbg_fwsave, &tlen);
}
}
}
/* Retrieve saved firmware trace from a prior IOC failure. */
int
bfa_nw_ioc_debug_fwsave(struct bfa_ioc *ioc, void *trcdata, int *trclen)
{
int tlen;
if (ioc->dbg_fwsave_len == 0)
return BFA_STATUS_ENOFSAVE;
tlen = *trclen;
if (tlen > ioc->dbg_fwsave_len)
tlen = ioc->dbg_fwsave_len;
memcpy(trcdata, ioc->dbg_fwsave, tlen);
*trclen = tlen;
return BFA_STATUS_OK;
}
static void
bfa_ioc_fail_notify(struct bfa_ioc *ioc)
{
/**
* Notify driver and common modules registered for notification.
*/
ioc->cbfn->hbfail_cbfn(ioc->bfa);
bfa_ioc_event_notify(ioc, BFA_IOC_E_FAILED);
bfa_nw_ioc_debug_save_ftrc(ioc);
}
/* IOCPF to IOC interface */
static void
bfa_ioc_pf_enabled(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(ioc, IOC_E_ENABLED);
}
static void
bfa_ioc_pf_disabled(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(ioc, IOC_E_DISABLED);
}
static void
bfa_ioc_pf_failed(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(ioc, IOC_E_PFFAILED);
}
static void
bfa_ioc_pf_hwfailed(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(ioc, IOC_E_HWFAILED);
}
static void
bfa_ioc_pf_fwmismatch(struct bfa_ioc *ioc)
{
/**
* Provide enable completion callback and AEN notification.
*/
ioc->cbfn->enable_cbfn(ioc->bfa, BFA_STATUS_IOC_FAILURE);
}
/* IOC public */
static enum bfa_status
bfa_ioc_pll_init(struct bfa_ioc *ioc)
{
/*
* Hold semaphore so that nobody can access the chip during init.
*/
bfa_nw_ioc_sem_get(ioc->ioc_regs.ioc_init_sem_reg);
bfa_ioc_pll_init_asic(ioc);
ioc->pllinit = true;
/* Initialize LMEM */
bfa_ioc_lmem_init(ioc);
/*
* release semaphore.
*/
bfa_nw_ioc_sem_release(ioc->ioc_regs.ioc_init_sem_reg);
return BFA_STATUS_OK;
}
/* Interface used by diag module to do firmware boot with memory test
* as the entry vector.
*/
static enum bfa_status
bfa_ioc_boot(struct bfa_ioc *ioc, enum bfi_fwboot_type boot_type,
u32 boot_env)
{
struct bfi_ioc_image_hdr *drv_fwhdr;
enum bfa_status status;
bfa_ioc_stats(ioc, ioc_boots);
if (bfa_ioc_pll_init(ioc) != BFA_STATUS_OK)
return BFA_STATUS_FAILED;
if (boot_env == BFI_FWBOOT_ENV_OS &&
boot_type == BFI_FWBOOT_TYPE_NORMAL) {
drv_fwhdr = (struct bfi_ioc_image_hdr *)
bfa_cb_image_get_chunk(bfa_ioc_asic_gen(ioc), 0);
/* Work with Flash iff flash f/w is better than driver f/w.
* Otherwise push drivers firmware.
*/
if (bfa_ioc_flash_fwver_cmp(ioc, drv_fwhdr) ==
BFI_IOC_IMG_VER_BETTER)
boot_type = BFI_FWBOOT_TYPE_FLASH;
}
/**
* Initialize IOC state of all functions on a chip reset.
*/
if (boot_type == BFI_FWBOOT_TYPE_MEMTEST) {
bfa_ioc_set_cur_ioc_fwstate(ioc, BFI_IOC_MEMTEST);
bfa_ioc_set_alt_ioc_fwstate(ioc, BFI_IOC_MEMTEST);
} else {
bfa_ioc_set_cur_ioc_fwstate(ioc, BFI_IOC_INITING);
bfa_ioc_set_alt_ioc_fwstate(ioc, BFI_IOC_INITING);
}
bfa_ioc_msgflush(ioc);
status = bfa_ioc_download_fw(ioc, boot_type, boot_env);
if (status == BFA_STATUS_OK)
bfa_ioc_lpu_start(ioc);
else
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_TIMEOUT);
return status;
}
/* Enable/disable IOC failure auto recovery. */
void
bfa_nw_ioc_auto_recover(bool auto_recover)
{
bfa_nw_auto_recover = auto_recover;
}
static bool
bfa_ioc_msgget(struct bfa_ioc *ioc, void *mbmsg)
{
u32 *msgp = mbmsg;
u32 r32;
int i;
r32 = readl(ioc->ioc_regs.lpu_mbox_cmd);
if ((r32 & 1) == 0)
return false;
/**
* read the MBOX msg
*/
for (i = 0; i < (sizeof(union bfi_ioc_i2h_msg_u) / sizeof(u32));
i++) {
r32 = readl(ioc->ioc_regs.lpu_mbox +
i * sizeof(u32));
msgp[i] = htonl(r32);
}
/**
* turn off mailbox interrupt by clearing mailbox status
*/
writel(1, ioc->ioc_regs.lpu_mbox_cmd);
readl(ioc->ioc_regs.lpu_mbox_cmd);
return true;
}
static void
bfa_ioc_isr(struct bfa_ioc *ioc, struct bfi_mbmsg *m)
{
union bfi_ioc_i2h_msg_u *msg;
struct bfa_iocpf *iocpf = &ioc->iocpf;
msg = (union bfi_ioc_i2h_msg_u *) m;
bfa_ioc_stats(ioc, ioc_isrs);
switch (msg->mh.msg_id) {
case BFI_IOC_I2H_HBEAT:
break;
case BFI_IOC_I2H_ENABLE_REPLY:
bfa_ioc_enable_reply(ioc,
(enum bfa_mode)msg->fw_event.port_mode,
msg->fw_event.cap_bm);
break;
case BFI_IOC_I2H_DISABLE_REPLY:
bfa_fsm_send_event(iocpf, IOCPF_E_FWRSP_DISABLE);
break;
case BFI_IOC_I2H_GETATTR_REPLY:
bfa_ioc_getattr_reply(ioc);
break;
default:
BUG_ON(1);
}
}
/**
* bfa_nw_ioc_attach - IOC attach time initialization and setup.
*
* @ioc: memory for IOC
* @bfa: driver instance structure
* @cbfn: callback function
*/
void
bfa_nw_ioc_attach(struct bfa_ioc *ioc, void *bfa, struct bfa_ioc_cbfn *cbfn)
{
ioc->bfa = bfa;
ioc->cbfn = cbfn;
ioc->fcmode = false;
ioc->pllinit = false;
ioc->dbg_fwsave_once = true;
ioc->iocpf.ioc = ioc;
bfa_ioc_mbox_attach(ioc);
INIT_LIST_HEAD(&ioc->notify_q);
bfa_fsm_set_state(ioc, bfa_ioc_sm_uninit);
bfa_fsm_send_event(ioc, IOC_E_RESET);
}
/* Driver detach time IOC cleanup. */
void
bfa_nw_ioc_detach(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(ioc, IOC_E_DETACH);
/* Done with detach, empty the notify_q. */
INIT_LIST_HEAD(&ioc->notify_q);
}
/**
* bfa_nw_ioc_pci_init - Setup IOC PCI properties.
*
* @ioc: memory for IOC
* @pcidev: PCI device information for this IOC
* @clscode: class code
*/
void
bfa_nw_ioc_pci_init(struct bfa_ioc *ioc, struct bfa_pcidev *pcidev,
enum bfi_pcifn_class clscode)
{
ioc->clscode = clscode;
ioc->pcidev = *pcidev;
/**
* Initialize IOC and device personality
*/
ioc->port0_mode = ioc->port1_mode = BFI_PORT_MODE_FC;
ioc->asic_mode = BFI_ASIC_MODE_FC;
switch (pcidev->device_id) {
case PCI_DEVICE_ID_BROCADE_CT:
ioc->asic_gen = BFI_ASIC_GEN_CT;
ioc->port0_mode = ioc->port1_mode = BFI_PORT_MODE_ETH;
ioc->asic_mode = BFI_ASIC_MODE_ETH;
ioc->port_mode = ioc->port_mode_cfg = BFA_MODE_CNA;
ioc->ad_cap_bm = BFA_CM_CNA;
break;
case BFA_PCI_DEVICE_ID_CT2:
ioc->asic_gen = BFI_ASIC_GEN_CT2;
if (clscode == BFI_PCIFN_CLASS_FC &&
pcidev->ssid == BFA_PCI_CT2_SSID_FC) {
ioc->asic_mode = BFI_ASIC_MODE_FC16;
ioc->fcmode = true;
ioc->port_mode = ioc->port_mode_cfg = BFA_MODE_HBA;
ioc->ad_cap_bm = BFA_CM_HBA;
} else {
ioc->port0_mode = ioc->port1_mode = BFI_PORT_MODE_ETH;
ioc->asic_mode = BFI_ASIC_MODE_ETH;
if (pcidev->ssid == BFA_PCI_CT2_SSID_FCoE) {
ioc->port_mode =
ioc->port_mode_cfg = BFA_MODE_CNA;
ioc->ad_cap_bm = BFA_CM_CNA;
} else {
ioc->port_mode =
ioc->port_mode_cfg = BFA_MODE_NIC;
ioc->ad_cap_bm = BFA_CM_NIC;
}
}
break;
default:
BUG_ON(1);
}
/**
* Set asic specific interfaces.
*/
if (ioc->asic_gen == BFI_ASIC_GEN_CT)
bfa_nw_ioc_set_ct_hwif(ioc);
else {
WARN_ON(ioc->asic_gen != BFI_ASIC_GEN_CT2);
bfa_nw_ioc_set_ct2_hwif(ioc);
bfa_nw_ioc_ct2_poweron(ioc);
}
bfa_ioc_map_port(ioc);
bfa_ioc_reg_init(ioc);
}
/**
* bfa_nw_ioc_mem_claim - Initialize IOC dma memory
*
* @ioc: memory for IOC
* @dm_kva: kernel virtual address of IOC dma memory
* @dm_pa: physical address of IOC dma memory
*/
void
bfa_nw_ioc_mem_claim(struct bfa_ioc *ioc, u8 *dm_kva, u64 dm_pa)
{
/**
* dma memory for firmware attribute
*/
ioc->attr_dma.kva = dm_kva;
ioc->attr_dma.pa = dm_pa;
ioc->attr = (struct bfi_ioc_attr *) dm_kva;
}
/* Return size of dma memory required. */
u32
bfa_nw_ioc_meminfo(void)
{
return roundup(sizeof(struct bfi_ioc_attr), BFA_DMA_ALIGN_SZ);
}
void
bfa_nw_ioc_enable(struct bfa_ioc *ioc)
{
bfa_ioc_stats(ioc, ioc_enables);
ioc->dbg_fwsave_once = true;
bfa_fsm_send_event(ioc, IOC_E_ENABLE);
}
void
bfa_nw_ioc_disable(struct bfa_ioc *ioc)
{
bfa_ioc_stats(ioc, ioc_disables);
bfa_fsm_send_event(ioc, IOC_E_DISABLE);
}
/* Initialize memory for saving firmware trace. */
void
bfa_nw_ioc_debug_memclaim(struct bfa_ioc *ioc, void *dbg_fwsave)
{
ioc->dbg_fwsave = dbg_fwsave;
ioc->dbg_fwsave_len = ioc->iocpf.auto_recover ? BNA_DBG_FWTRC_LEN : 0;
}
static u32
bfa_ioc_smem_pgnum(struct bfa_ioc *ioc, u32 fmaddr)
{
return PSS_SMEM_PGNUM(ioc->ioc_regs.smem_pg0, fmaddr);
}
/* Register mailbox message handler function, to be called by common modules */
void
bfa_nw_ioc_mbox_regisr(struct bfa_ioc *ioc, enum bfi_mclass mc,
bfa_ioc_mbox_mcfunc_t cbfn, void *cbarg)
{
struct bfa_ioc_mbox_mod *mod = &ioc->mbox_mod;
mod->mbhdlr[mc].cbfn = cbfn;
mod->mbhdlr[mc].cbarg = cbarg;
}
/**
* bfa_nw_ioc_mbox_queue - Queue a mailbox command request to firmware.
*
* @ioc: IOC instance
* @cmd: Mailbox command
* @cbfn: callback function
* @cbarg: arguments to callback
*
* Waits if mailbox is busy. Responsibility of caller to serialize
*/
bool
bfa_nw_ioc_mbox_queue(struct bfa_ioc *ioc, struct bfa_mbox_cmd *cmd,
bfa_mbox_cmd_cbfn_t cbfn, void *cbarg)
{
struct bfa_ioc_mbox_mod *mod = &ioc->mbox_mod;
u32 stat;
cmd->cbfn = cbfn;
cmd->cbarg = cbarg;
/**
* If a previous command is pending, queue new command
*/
if (!list_empty(&mod->cmd_q)) {
list_add_tail(&cmd->qe, &mod->cmd_q);
return true;
}
/**
* If mailbox is busy, queue command for poll timer
*/
stat = readl(ioc->ioc_regs.hfn_mbox_cmd);
if (stat) {
list_add_tail(&cmd->qe, &mod->cmd_q);
return true;
}
/**
* mailbox is free -- queue command to firmware
*/
bfa_ioc_mbox_send(ioc, cmd->msg, sizeof(cmd->msg));
return false;
}
/* Handle mailbox interrupts */
void
bfa_nw_ioc_mbox_isr(struct bfa_ioc *ioc)
{
struct bfa_ioc_mbox_mod *mod = &ioc->mbox_mod;
struct bfi_mbmsg m;
int mc;
if (bfa_ioc_msgget(ioc, &m)) {
/**
* Treat IOC message class as special.
*/
mc = m.mh.msg_class;
if (mc == BFI_MC_IOC) {
bfa_ioc_isr(ioc, &m);
return;
}
if ((mc >= BFI_MC_MAX) || (mod->mbhdlr[mc].cbfn == NULL))
return;
mod->mbhdlr[mc].cbfn(mod->mbhdlr[mc].cbarg, &m);
}
bfa_ioc_lpu_read_stat(ioc);
/**
* Try to send pending mailbox commands
*/
bfa_ioc_mbox_poll(ioc);
}
void
bfa_nw_ioc_error_isr(struct bfa_ioc *ioc)
{
bfa_ioc_stats(ioc, ioc_hbfails);
bfa_ioc_stats_hb_count(ioc, ioc->hb_count);
bfa_fsm_send_event(ioc, IOC_E_HWERROR);
}
/* return true if IOC is disabled */
bool
bfa_nw_ioc_is_disabled(struct bfa_ioc *ioc)
{
return bfa_fsm_cmp_state(ioc, bfa_ioc_sm_disabling) ||
bfa_fsm_cmp_state(ioc, bfa_ioc_sm_disabled);
}
/* return true if IOC is operational */
bool
bfa_nw_ioc_is_operational(struct bfa_ioc *ioc)
{
return bfa_fsm_cmp_state(ioc, bfa_ioc_sm_op);
}
/* Add to IOC heartbeat failure notification queue. To be used by common
* modules such as cee, port, diag.
*/
void
bfa_nw_ioc_notify_register(struct bfa_ioc *ioc,
struct bfa_ioc_notify *notify)
{
list_add_tail(¬ify->qe, &ioc->notify_q);
}
#define BFA_MFG_NAME "QLogic"
static void
bfa_ioc_get_adapter_attr(struct bfa_ioc *ioc,
struct bfa_adapter_attr *ad_attr)
{
struct bfi_ioc_attr *ioc_attr;
ioc_attr = ioc->attr;
bfa_ioc_get_adapter_serial_num(ioc, ad_attr->serial_num);
bfa_ioc_get_adapter_fw_ver(ioc, ad_attr->fw_ver);
bfa_ioc_get_adapter_optrom_ver(ioc, ad_attr->optrom_ver);
bfa_ioc_get_adapter_manufacturer(ioc, ad_attr->manufacturer);
memcpy(&ad_attr->vpd, &ioc_attr->vpd,
sizeof(struct bfa_mfg_vpd));
ad_attr->nports = bfa_ioc_get_nports(ioc);
ad_attr->max_speed = bfa_ioc_speed_sup(ioc);
bfa_ioc_get_adapter_model(ioc, ad_attr->model);
/* For now, model descr uses same model string */
bfa_ioc_get_adapter_model(ioc, ad_attr->model_descr);
ad_attr->card_type = ioc_attr->card_type;
ad_attr->is_mezz = bfa_mfg_is_mezz(ioc_attr->card_type);
if (BFI_ADAPTER_IS_SPECIAL(ioc_attr->adapter_prop))
ad_attr->prototype = 1;
else
ad_attr->prototype = 0;
ad_attr->pwwn = bfa_ioc_get_pwwn(ioc);
bfa_nw_ioc_get_mac(ioc, ad_attr->mac);
ad_attr->pcie_gen = ioc_attr->pcie_gen;
ad_attr->pcie_lanes = ioc_attr->pcie_lanes;
ad_attr->pcie_lanes_orig = ioc_attr->pcie_lanes_orig;
ad_attr->asic_rev = ioc_attr->asic_rev;
bfa_ioc_get_pci_chip_rev(ioc, ad_attr->hw_ver);
}
static enum bfa_ioc_type
bfa_ioc_get_type(struct bfa_ioc *ioc)
{
if (ioc->clscode == BFI_PCIFN_CLASS_ETH)
return BFA_IOC_TYPE_LL;
BUG_ON(!(ioc->clscode == BFI_PCIFN_CLASS_FC));
return (ioc->attr->port_mode == BFI_PORT_MODE_FC)
? BFA_IOC_TYPE_FC : BFA_IOC_TYPE_FCoE;
}
static void
bfa_ioc_get_adapter_serial_num(struct bfa_ioc *ioc, char *serial_num)
{
memcpy(serial_num,
(void *)ioc->attr->brcd_serialnum,
BFA_ADAPTER_SERIAL_NUM_LEN);
}
static void
bfa_ioc_get_adapter_fw_ver(struct bfa_ioc *ioc, char *fw_ver)
{
memcpy(fw_ver, ioc->attr->fw_version, BFA_VERSION_LEN);
}
static void
bfa_ioc_get_pci_chip_rev(struct bfa_ioc *ioc, char *chip_rev)
{
BUG_ON(!(chip_rev));
memset(chip_rev, 0, BFA_IOC_CHIP_REV_LEN);
chip_rev[0] = 'R';
chip_rev[1] = 'e';
chip_rev[2] = 'v';
chip_rev[3] = '-';
chip_rev[4] = ioc->attr->asic_rev;
chip_rev[5] = '\0';
}
static void
bfa_ioc_get_adapter_optrom_ver(struct bfa_ioc *ioc, char *optrom_ver)
{
memcpy(optrom_ver, ioc->attr->optrom_version,
BFA_VERSION_LEN);
}
static void
bfa_ioc_get_adapter_manufacturer(struct bfa_ioc *ioc, char *manufacturer)
{
strncpy(manufacturer, BFA_MFG_NAME, BFA_ADAPTER_MFG_NAME_LEN);
}
static void
bfa_ioc_get_adapter_model(struct bfa_ioc *ioc, char *model)
{
struct bfi_ioc_attr *ioc_attr;
BUG_ON(!(model));
memset(model, 0, BFA_ADAPTER_MODEL_NAME_LEN);
ioc_attr = ioc->attr;
snprintf(model, BFA_ADAPTER_MODEL_NAME_LEN, "%s-%u",
BFA_MFG_NAME, ioc_attr->card_type);
}
static enum bfa_ioc_state
bfa_ioc_get_state(struct bfa_ioc *ioc)
{
enum bfa_iocpf_state iocpf_st;
enum bfa_ioc_state ioc_st = ioc_sm_to_state(ioc_sm_table, ioc->fsm);
if (ioc_st == BFA_IOC_ENABLING ||
ioc_st == BFA_IOC_FAIL || ioc_st == BFA_IOC_INITFAIL) {
iocpf_st = iocpf_sm_to_state(iocpf_sm_table, ioc->iocpf.fsm);
switch (iocpf_st) {
case BFA_IOCPF_SEMWAIT:
ioc_st = BFA_IOC_SEMWAIT;
break;
case BFA_IOCPF_HWINIT:
ioc_st = BFA_IOC_HWINIT;
break;
case BFA_IOCPF_FWMISMATCH:
ioc_st = BFA_IOC_FWMISMATCH;
break;
case BFA_IOCPF_FAIL:
ioc_st = BFA_IOC_FAIL;
break;
case BFA_IOCPF_INITFAIL:
ioc_st = BFA_IOC_INITFAIL;
break;
default:
break;
}
}
return ioc_st;
}
void
bfa_nw_ioc_get_attr(struct bfa_ioc *ioc, struct bfa_ioc_attr *ioc_attr)
{
memset((void *)ioc_attr, 0, sizeof(struct bfa_ioc_attr));
ioc_attr->state = bfa_ioc_get_state(ioc);
ioc_attr->port_id = bfa_ioc_portid(ioc);
ioc_attr->port_mode = ioc->port_mode;
ioc_attr->port_mode_cfg = ioc->port_mode_cfg;
ioc_attr->cap_bm = ioc->ad_cap_bm;
ioc_attr->ioc_type = bfa_ioc_get_type(ioc);
bfa_ioc_get_adapter_attr(ioc, &ioc_attr->adapter_attr);
ioc_attr->pci_attr.device_id = bfa_ioc_devid(ioc);
ioc_attr->pci_attr.pcifn = bfa_ioc_pcifn(ioc);
ioc_attr->def_fn = bfa_ioc_is_default(ioc);
bfa_ioc_get_pci_chip_rev(ioc, ioc_attr->pci_attr.chip_rev);
}
/* WWN public */
static u64
bfa_ioc_get_pwwn(struct bfa_ioc *ioc)
{
return ioc->attr->pwwn;
}
void
bfa_nw_ioc_get_mac(struct bfa_ioc *ioc, u8 *mac)
{
ether_addr_copy(mac, ioc->attr->mac);
}
/* Firmware failure detected. Start recovery actions. */
static void
bfa_ioc_recover(struct bfa_ioc *ioc)
{
pr_crit("Heart Beat of IOC has failed\n");
bfa_ioc_stats(ioc, ioc_hbfails);
bfa_ioc_stats_hb_count(ioc, ioc->hb_count);
bfa_fsm_send_event(ioc, IOC_E_HBFAIL);
}
/* BFA IOC PF private functions */
static void
bfa_iocpf_enable(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_ENABLE);
}
static void
bfa_iocpf_disable(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_DISABLE);
}
static void
bfa_iocpf_fail(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_FAIL);
}
static void
bfa_iocpf_initfail(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_INITFAIL);
}
static void
bfa_iocpf_getattrfail(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_GETATTRFAIL);
}
static void
bfa_iocpf_stop(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_STOP);
}
void
bfa_nw_iocpf_timeout(struct bfa_ioc *ioc)
{
enum bfa_iocpf_state iocpf_st;
iocpf_st = iocpf_sm_to_state(iocpf_sm_table, ioc->iocpf.fsm);
if (iocpf_st == BFA_IOCPF_HWINIT)
bfa_ioc_poll_fwinit(ioc);
else
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_TIMEOUT);
}
void
bfa_nw_iocpf_sem_timeout(struct bfa_ioc *ioc)
{
bfa_ioc_hw_sem_get(ioc);
}
static void
bfa_ioc_poll_fwinit(struct bfa_ioc *ioc)
{
u32 fwstate = bfa_ioc_get_cur_ioc_fwstate(ioc);
if (fwstate == BFI_IOC_DISABLED) {
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_FWREADY);
return;
}
if (ioc->iocpf.poll_time >= BFA_IOC_TOV) {
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_TIMEOUT);
} else {
ioc->iocpf.poll_time += BFA_IOC_POLL_TOV;
mod_timer(&ioc->iocpf_timer, jiffies +
msecs_to_jiffies(BFA_IOC_POLL_TOV));
}
}
/*
* Flash module specific
*/
/*
* FLASH DMA buffer should be big enough to hold both MFG block and
* asic block(64k) at the same time and also should be 2k aligned to
* avoid write segement to cross sector boundary.
*/
#define BFA_FLASH_SEG_SZ 2048
#define BFA_FLASH_DMA_BUF_SZ \
roundup(0x010000 + sizeof(struct bfa_mfg_block), BFA_FLASH_SEG_SZ)
static void
bfa_flash_cb(struct bfa_flash *flash)
{
flash->op_busy = 0;
if (flash->cbfn)
flash->cbfn(flash->cbarg, flash->status);
}
static void
bfa_flash_notify(void *cbarg, enum bfa_ioc_event event)
{
struct bfa_flash *flash = cbarg;
switch (event) {
case BFA_IOC_E_DISABLED:
case BFA_IOC_E_FAILED:
if (flash->op_busy) {
flash->status = BFA_STATUS_IOC_FAILURE;
flash->cbfn(flash->cbarg, flash->status);
flash->op_busy = 0;
}
break;
default:
break;
}
}
/*
* Send flash write request.
*/
static void
bfa_flash_write_send(struct bfa_flash *flash)
{
struct bfi_flash_write_req *msg =
(struct bfi_flash_write_req *) flash->mb.msg;
u32 len;
msg->type = be32_to_cpu(flash->type);
msg->instance = flash->instance;
msg->offset = be32_to_cpu(flash->addr_off + flash->offset);
len = (flash->residue < BFA_FLASH_DMA_BUF_SZ) ?
flash->residue : BFA_FLASH_DMA_BUF_SZ;
msg->length = be32_to_cpu(len);
/* indicate if it's the last msg of the whole write operation */
msg->last = (len == flash->residue) ? 1 : 0;
bfi_h2i_set(msg->mh, BFI_MC_FLASH, BFI_FLASH_H2I_WRITE_REQ,
bfa_ioc_portid(flash->ioc));
bfa_alen_set(&msg->alen, len, flash->dbuf_pa);
memcpy(flash->dbuf_kva, flash->ubuf + flash->offset, len);
bfa_nw_ioc_mbox_queue(flash->ioc, &flash->mb, NULL, NULL);
flash->residue -= len;
flash->offset += len;
}
/**
* bfa_flash_read_send - Send flash read request.
*
* @cbarg: callback argument
*/
static void
bfa_flash_read_send(void *cbarg)
{
struct bfa_flash *flash = cbarg;
struct bfi_flash_read_req *msg =
(struct bfi_flash_read_req *) flash->mb.msg;
u32 len;
msg->type = be32_to_cpu(flash->type);
msg->instance = flash->instance;
msg->offset = be32_to_cpu(flash->addr_off + flash->offset);
len = (flash->residue < BFA_FLASH_DMA_BUF_SZ) ?
flash->residue : BFA_FLASH_DMA_BUF_SZ;
msg->length = be32_to_cpu(len);
bfi_h2i_set(msg->mh, BFI_MC_FLASH, BFI_FLASH_H2I_READ_REQ,
bfa_ioc_portid(flash->ioc));
bfa_alen_set(&msg->alen, len, flash->dbuf_pa);
bfa_nw_ioc_mbox_queue(flash->ioc, &flash->mb, NULL, NULL);
}
/**
* bfa_flash_intr - Process flash response messages upon receiving interrupts.
*
* @flasharg: flash structure
* @msg: message structure
*/
static void
bfa_flash_intr(void *flasharg, struct bfi_mbmsg *msg)
{
struct bfa_flash *flash = flasharg;
u32 status;
union {
struct bfi_flash_query_rsp *query;
struct bfi_flash_write_rsp *write;
struct bfi_flash_read_rsp *read;
struct bfi_mbmsg *msg;
} m;
m.msg = msg;
/* receiving response after ioc failure */
if (!flash->op_busy && msg->mh.msg_id != BFI_FLASH_I2H_EVENT)
return;
switch (msg->mh.msg_id) {
case BFI_FLASH_I2H_QUERY_RSP:
status = be32_to_cpu(m.query->status);
if (status == BFA_STATUS_OK) {
u32 i;
struct bfa_flash_attr *attr, *f;
attr = (struct bfa_flash_attr *) flash->ubuf;
f = (struct bfa_flash_attr *) flash->dbuf_kva;
attr->status = be32_to_cpu(f->status);
attr->npart = be32_to_cpu(f->npart);
for (i = 0; i < attr->npart; i++) {
attr->part[i].part_type =
be32_to_cpu(f->part[i].part_type);
attr->part[i].part_instance =
be32_to_cpu(f->part[i].part_instance);
attr->part[i].part_off =
be32_to_cpu(f->part[i].part_off);
attr->part[i].part_size =
be32_to_cpu(f->part[i].part_size);
attr->part[i].part_len =
be32_to_cpu(f->part[i].part_len);
attr->part[i].part_status =
be32_to_cpu(f->part[i].part_status);
}
}
flash->status = status;
bfa_flash_cb(flash);
break;
case BFI_FLASH_I2H_WRITE_RSP:
status = be32_to_cpu(m.write->status);
if (status != BFA_STATUS_OK || flash->residue == 0) {
flash->status = status;
bfa_flash_cb(flash);
} else
bfa_flash_write_send(flash);
break;
case BFI_FLASH_I2H_READ_RSP:
status = be32_to_cpu(m.read->status);
if (status != BFA_STATUS_OK) {
flash->status = status;
bfa_flash_cb(flash);
} else {
u32 len = be32_to_cpu(m.read->length);
memcpy(flash->ubuf + flash->offset,
flash->dbuf_kva, len);
flash->residue -= len;
flash->offset += len;
if (flash->residue == 0) {
flash->status = status;
bfa_flash_cb(flash);
} else
bfa_flash_read_send(flash);
}
break;
case BFI_FLASH_I2H_BOOT_VER_RSP:
case BFI_FLASH_I2H_EVENT:
break;
default:
WARN_ON(1);
}
}
/*
* Flash memory info API.
*/
u32
bfa_nw_flash_meminfo(void)
{
return roundup(BFA_FLASH_DMA_BUF_SZ, BFA_DMA_ALIGN_SZ);
}
/**
* bfa_nw_flash_attach - Flash attach API.
*
* @flash: flash structure
* @ioc: ioc structure
* @dev: device structure
*/
void
bfa_nw_flash_attach(struct bfa_flash *flash, struct bfa_ioc *ioc, void *dev)
{
flash->ioc = ioc;
flash->cbfn = NULL;
flash->cbarg = NULL;
flash->op_busy = 0;
bfa_nw_ioc_mbox_regisr(flash->ioc, BFI_MC_FLASH, bfa_flash_intr, flash);
bfa_ioc_notify_init(&flash->ioc_notify, bfa_flash_notify, flash);
list_add_tail(&flash->ioc_notify.qe, &flash->ioc->notify_q);
}
/**
* bfa_nw_flash_memclaim - Claim memory for flash
*
* @flash: flash structure
* @dm_kva: pointer to virtual memory address
* @dm_pa: physical memory address
*/
void
bfa_nw_flash_memclaim(struct bfa_flash *flash, u8 *dm_kva, u64 dm_pa)
{
flash->dbuf_kva = dm_kva;
flash->dbuf_pa = dm_pa;
memset(flash->dbuf_kva, 0, BFA_FLASH_DMA_BUF_SZ);
dm_kva += roundup(BFA_FLASH_DMA_BUF_SZ, BFA_DMA_ALIGN_SZ);
dm_pa += roundup(BFA_FLASH_DMA_BUF_SZ, BFA_DMA_ALIGN_SZ);
}
/**
* bfa_nw_flash_get_attr - Get flash attribute.
*
* @flash: flash structure
* @attr: flash attribute structure
* @cbfn: callback function
* @cbarg: callback argument
*
* Return status.
*/
enum bfa_status
bfa_nw_flash_get_attr(struct bfa_flash *flash, struct bfa_flash_attr *attr,
bfa_cb_flash cbfn, void *cbarg)
{
struct bfi_flash_query_req *msg =
(struct bfi_flash_query_req *) flash->mb.msg;
if (!bfa_nw_ioc_is_operational(flash->ioc))
return BFA_STATUS_IOC_NON_OP;
if (flash->op_busy)
return BFA_STATUS_DEVBUSY;
flash->op_busy = 1;
flash->cbfn = cbfn;
flash->cbarg = cbarg;
flash->ubuf = (u8 *) attr;
bfi_h2i_set(msg->mh, BFI_MC_FLASH, BFI_FLASH_H2I_QUERY_REQ,
bfa_ioc_portid(flash->ioc));
bfa_alen_set(&msg->alen, sizeof(struct bfa_flash_attr), flash->dbuf_pa);
bfa_nw_ioc_mbox_queue(flash->ioc, &flash->mb, NULL, NULL);
return BFA_STATUS_OK;
}
/**
* bfa_nw_flash_update_part - Update flash partition.
*
* @flash: flash structure
* @type: flash partition type
* @instance: flash partition instance
* @buf: update data buffer
* @len: data buffer length
* @offset: offset relative to the partition starting address
* @cbfn: callback function
* @cbarg: callback argument
*
* Return status.
*/
enum bfa_status
bfa_nw_flash_update_part(struct bfa_flash *flash, u32 type, u8 instance,
void *buf, u32 len, u32 offset,
bfa_cb_flash cbfn, void *cbarg)
{
if (!bfa_nw_ioc_is_operational(flash->ioc))
return BFA_STATUS_IOC_NON_OP;
/*
* 'len' must be in word (4-byte) boundary
*/
if (!len || (len & 0x03))
return BFA_STATUS_FLASH_BAD_LEN;
if (type == BFA_FLASH_PART_MFG)
return BFA_STATUS_EINVAL;
if (flash->op_busy)
return BFA_STATUS_DEVBUSY;
flash->op_busy = 1;
flash->cbfn = cbfn;
flash->cbarg = cbarg;
flash->type = type;
flash->instance = instance;
flash->residue = len;
flash->offset = 0;
flash->addr_off = offset;
flash->ubuf = buf;
bfa_flash_write_send(flash);
return BFA_STATUS_OK;
}
/**
* bfa_nw_flash_read_part - Read flash partition.
*
* @flash: flash structure
* @type: flash partition type
* @instance: flash partition instance
* @buf: read data buffer
* @len: data buffer length
* @offset: offset relative to the partition starting address
* @cbfn: callback function
* @cbarg: callback argument
*
* Return status.
*/
enum bfa_status
bfa_nw_flash_read_part(struct bfa_flash *flash, u32 type, u8 instance,
void *buf, u32 len, u32 offset,
bfa_cb_flash cbfn, void *cbarg)
{
if (!bfa_nw_ioc_is_operational(flash->ioc))
return BFA_STATUS_IOC_NON_OP;
/*
* 'len' must be in word (4-byte) boundary
*/
if (!len || (len & 0x03))
return BFA_STATUS_FLASH_BAD_LEN;
if (flash->op_busy)
return BFA_STATUS_DEVBUSY;
flash->op_busy = 1;
flash->cbfn = cbfn;
flash->cbarg = cbarg;
flash->type = type;
flash->instance = instance;
flash->residue = len;
flash->offset = 0;
flash->addr_off = offset;
flash->ubuf = buf;
bfa_flash_read_send(flash);
return BFA_STATUS_OK;
}
|
linux-master
|
drivers/net/ethernet/brocade/bna/bfa_ioc.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Linux network driver for QLogic BR-series Converged Network Adapter.
*/
/*
* Copyright (c) 2005-2014 Brocade Communications Systems, Inc.
* Copyright (c) 2014-2015 QLogic Corporation
* All rights reserved
* www.qlogic.com
*/
#include "bna.h"
static inline int
ethport_can_be_up(struct bna_ethport *ethport)
{
int ready = 0;
if (ethport->bna->enet.type == BNA_ENET_T_REGULAR)
ready = ((ethport->flags & BNA_ETHPORT_F_ADMIN_UP) &&
(ethport->flags & BNA_ETHPORT_F_RX_STARTED) &&
(ethport->flags & BNA_ETHPORT_F_PORT_ENABLED));
else
ready = ((ethport->flags & BNA_ETHPORT_F_ADMIN_UP) &&
(ethport->flags & BNA_ETHPORT_F_RX_STARTED) &&
!(ethport->flags & BNA_ETHPORT_F_PORT_ENABLED));
return ready;
}
#define ethport_is_up ethport_can_be_up
enum bna_ethport_event {
ETHPORT_E_START = 1,
ETHPORT_E_STOP = 2,
ETHPORT_E_FAIL = 3,
ETHPORT_E_UP = 4,
ETHPORT_E_DOWN = 5,
ETHPORT_E_FWRESP_UP_OK = 6,
ETHPORT_E_FWRESP_DOWN = 7,
ETHPORT_E_FWRESP_UP_FAIL = 8,
};
enum bna_enet_event {
ENET_E_START = 1,
ENET_E_STOP = 2,
ENET_E_FAIL = 3,
ENET_E_PAUSE_CFG = 4,
ENET_E_MTU_CFG = 5,
ENET_E_FWRESP_PAUSE = 6,
ENET_E_CHLD_STOPPED = 7,
};
enum bna_ioceth_event {
IOCETH_E_ENABLE = 1,
IOCETH_E_DISABLE = 2,
IOCETH_E_IOC_RESET = 3,
IOCETH_E_IOC_FAILED = 4,
IOCETH_E_IOC_READY = 5,
IOCETH_E_ENET_ATTR_RESP = 6,
IOCETH_E_ENET_STOPPED = 7,
IOCETH_E_IOC_DISABLED = 8,
};
#define bna_stats_copy(_name, _type) \
do { \
count = sizeof(struct bfi_enet_stats_ ## _type) / sizeof(u64); \
stats_src = (u64 *)&bna->stats.hw_stats_kva->_name ## _stats; \
stats_dst = (u64 *)&bna->stats.hw_stats._name ## _stats; \
for (i = 0; i < count; i++) \
stats_dst[i] = be64_to_cpu(stats_src[i]); \
} while (0) \
/*
* FW response handlers
*/
static void
bna_bfi_ethport_enable_aen(struct bna_ethport *ethport,
struct bfi_msgq_mhdr *msghdr)
{
ethport->flags |= BNA_ETHPORT_F_PORT_ENABLED;
if (ethport_can_be_up(ethport))
bfa_fsm_send_event(ethport, ETHPORT_E_UP);
}
static void
bna_bfi_ethport_disable_aen(struct bna_ethport *ethport,
struct bfi_msgq_mhdr *msghdr)
{
int ethport_up = ethport_is_up(ethport);
ethport->flags &= ~BNA_ETHPORT_F_PORT_ENABLED;
if (ethport_up)
bfa_fsm_send_event(ethport, ETHPORT_E_DOWN);
}
static void
bna_bfi_ethport_admin_rsp(struct bna_ethport *ethport,
struct bfi_msgq_mhdr *msghdr)
{
struct bfi_enet_enable_req *admin_req =
ðport->bfi_enet_cmd.admin_req;
struct bfi_enet_rsp *rsp =
container_of(msghdr, struct bfi_enet_rsp, mh);
switch (admin_req->enable) {
case BNA_STATUS_T_ENABLED:
if (rsp->error == BFI_ENET_CMD_OK)
bfa_fsm_send_event(ethport, ETHPORT_E_FWRESP_UP_OK);
else {
ethport->flags &= ~BNA_ETHPORT_F_PORT_ENABLED;
bfa_fsm_send_event(ethport, ETHPORT_E_FWRESP_UP_FAIL);
}
break;
case BNA_STATUS_T_DISABLED:
bfa_fsm_send_event(ethport, ETHPORT_E_FWRESP_DOWN);
ethport->link_status = BNA_LINK_DOWN;
ethport->link_cbfn(ethport->bna->bnad, BNA_LINK_DOWN);
break;
}
}
static void
bna_bfi_ethport_lpbk_rsp(struct bna_ethport *ethport,
struct bfi_msgq_mhdr *msghdr)
{
struct bfi_enet_diag_lb_req *diag_lb_req =
ðport->bfi_enet_cmd.lpbk_req;
struct bfi_enet_rsp *rsp =
container_of(msghdr, struct bfi_enet_rsp, mh);
switch (diag_lb_req->enable) {
case BNA_STATUS_T_ENABLED:
if (rsp->error == BFI_ENET_CMD_OK)
bfa_fsm_send_event(ethport, ETHPORT_E_FWRESP_UP_OK);
else {
ethport->flags &= ~BNA_ETHPORT_F_ADMIN_UP;
bfa_fsm_send_event(ethport, ETHPORT_E_FWRESP_UP_FAIL);
}
break;
case BNA_STATUS_T_DISABLED:
bfa_fsm_send_event(ethport, ETHPORT_E_FWRESP_DOWN);
break;
}
}
static void
bna_bfi_pause_set_rsp(struct bna_enet *enet, struct bfi_msgq_mhdr *msghdr)
{
bfa_fsm_send_event(enet, ENET_E_FWRESP_PAUSE);
}
static void
bna_bfi_attr_get_rsp(struct bna_ioceth *ioceth,
struct bfi_msgq_mhdr *msghdr)
{
struct bfi_enet_attr_rsp *rsp =
container_of(msghdr, struct bfi_enet_attr_rsp, mh);
/**
* Store only if not set earlier, since BNAD can override the HW
* attributes
*/
if (!ioceth->attr.fw_query_complete) {
ioceth->attr.num_txq = ntohl(rsp->max_cfg);
ioceth->attr.num_rxp = ntohl(rsp->max_cfg);
ioceth->attr.num_ucmac = ntohl(rsp->max_ucmac);
ioceth->attr.num_mcmac = BFI_ENET_MAX_MCAM;
ioceth->attr.max_rit_size = ntohl(rsp->rit_size);
ioceth->attr.fw_query_complete = true;
}
bfa_fsm_send_event(ioceth, IOCETH_E_ENET_ATTR_RESP);
}
static void
bna_bfi_stats_get_rsp(struct bna *bna, struct bfi_msgq_mhdr *msghdr)
{
struct bfi_enet_stats_req *stats_req = &bna->stats_mod.stats_get;
u64 *stats_src;
u64 *stats_dst;
u32 tx_enet_mask = ntohl(stats_req->tx_enet_mask);
u32 rx_enet_mask = ntohl(stats_req->rx_enet_mask);
int count;
int i;
bna_stats_copy(mac, mac);
bna_stats_copy(bpc, bpc);
bna_stats_copy(rad, rad);
bna_stats_copy(rlb, rad);
bna_stats_copy(fc_rx, fc_rx);
bna_stats_copy(fc_tx, fc_tx);
stats_src = (u64 *)&(bna->stats.hw_stats_kva->rxf_stats[0]);
/* Copy Rxf stats to SW area, scatter them while copying */
for (i = 0; i < BFI_ENET_CFG_MAX; i++) {
stats_dst = (u64 *)&(bna->stats.hw_stats.rxf_stats[i]);
memset(stats_dst, 0, sizeof(struct bfi_enet_stats_rxf));
if (rx_enet_mask & BIT(i)) {
int k;
count = sizeof(struct bfi_enet_stats_rxf) /
sizeof(u64);
for (k = 0; k < count; k++) {
stats_dst[k] = be64_to_cpu(*stats_src);
stats_src++;
}
}
}
/* Copy Txf stats to SW area, scatter them while copying */
for (i = 0; i < BFI_ENET_CFG_MAX; i++) {
stats_dst = (u64 *)&(bna->stats.hw_stats.txf_stats[i]);
memset(stats_dst, 0, sizeof(struct bfi_enet_stats_txf));
if (tx_enet_mask & BIT(i)) {
int k;
count = sizeof(struct bfi_enet_stats_txf) /
sizeof(u64);
for (k = 0; k < count; k++) {
stats_dst[k] = be64_to_cpu(*stats_src);
stats_src++;
}
}
}
bna->stats_mod.stats_get_busy = false;
bnad_cb_stats_get(bna->bnad, BNA_CB_SUCCESS, &bna->stats);
}
static void
bna_bfi_ethport_linkup_aen(struct bna_ethport *ethport,
struct bfi_msgq_mhdr *msghdr)
{
ethport->link_status = BNA_LINK_UP;
/* Dispatch events */
ethport->link_cbfn(ethport->bna->bnad, ethport->link_status);
}
static void
bna_bfi_ethport_linkdown_aen(struct bna_ethport *ethport,
struct bfi_msgq_mhdr *msghdr)
{
ethport->link_status = BNA_LINK_DOWN;
/* Dispatch events */
ethport->link_cbfn(ethport->bna->bnad, BNA_LINK_DOWN);
}
static void
bna_err_handler(struct bna *bna, u32 intr_status)
{
if (BNA_IS_HALT_INTR(bna, intr_status))
bna_halt_clear(bna);
bfa_nw_ioc_error_isr(&bna->ioceth.ioc);
}
void
bna_mbox_handler(struct bna *bna, u32 intr_status)
{
if (BNA_IS_ERR_INTR(bna, intr_status)) {
bna_err_handler(bna, intr_status);
return;
}
if (BNA_IS_MBOX_INTR(bna, intr_status))
bfa_nw_ioc_mbox_isr(&bna->ioceth.ioc);
}
static void
bna_msgq_rsp_handler(void *arg, struct bfi_msgq_mhdr *msghdr)
{
struct bna *bna = (struct bna *)arg;
struct bna_tx *tx;
struct bna_rx *rx;
switch (msghdr->msg_id) {
case BFI_ENET_I2H_RX_CFG_SET_RSP:
bna_rx_from_rid(bna, msghdr->enet_id, rx);
if (rx)
bna_bfi_rx_enet_start_rsp(rx, msghdr);
break;
case BFI_ENET_I2H_RX_CFG_CLR_RSP:
bna_rx_from_rid(bna, msghdr->enet_id, rx);
if (rx)
bna_bfi_rx_enet_stop_rsp(rx, msghdr);
break;
case BFI_ENET_I2H_RIT_CFG_RSP:
case BFI_ENET_I2H_RSS_CFG_RSP:
case BFI_ENET_I2H_RSS_ENABLE_RSP:
case BFI_ENET_I2H_RX_PROMISCUOUS_RSP:
case BFI_ENET_I2H_RX_DEFAULT_RSP:
case BFI_ENET_I2H_MAC_UCAST_CLR_RSP:
case BFI_ENET_I2H_MAC_UCAST_ADD_RSP:
case BFI_ENET_I2H_MAC_UCAST_DEL_RSP:
case BFI_ENET_I2H_MAC_MCAST_DEL_RSP:
case BFI_ENET_I2H_MAC_MCAST_FILTER_RSP:
case BFI_ENET_I2H_RX_VLAN_SET_RSP:
case BFI_ENET_I2H_RX_VLAN_STRIP_ENABLE_RSP:
bna_rx_from_rid(bna, msghdr->enet_id, rx);
if (rx)
bna_bfi_rxf_cfg_rsp(&rx->rxf, msghdr);
break;
case BFI_ENET_I2H_MAC_UCAST_SET_RSP:
bna_rx_from_rid(bna, msghdr->enet_id, rx);
if (rx)
bna_bfi_rxf_ucast_set_rsp(&rx->rxf, msghdr);
break;
case BFI_ENET_I2H_MAC_MCAST_ADD_RSP:
bna_rx_from_rid(bna, msghdr->enet_id, rx);
if (rx)
bna_bfi_rxf_mcast_add_rsp(&rx->rxf, msghdr);
break;
case BFI_ENET_I2H_TX_CFG_SET_RSP:
bna_tx_from_rid(bna, msghdr->enet_id, tx);
if (tx)
bna_bfi_tx_enet_start_rsp(tx, msghdr);
break;
case BFI_ENET_I2H_TX_CFG_CLR_RSP:
bna_tx_from_rid(bna, msghdr->enet_id, tx);
if (tx)
bna_bfi_tx_enet_stop_rsp(tx, msghdr);
break;
case BFI_ENET_I2H_PORT_ADMIN_RSP:
bna_bfi_ethport_admin_rsp(&bna->ethport, msghdr);
break;
case BFI_ENET_I2H_DIAG_LOOPBACK_RSP:
bna_bfi_ethport_lpbk_rsp(&bna->ethport, msghdr);
break;
case BFI_ENET_I2H_SET_PAUSE_RSP:
bna_bfi_pause_set_rsp(&bna->enet, msghdr);
break;
case BFI_ENET_I2H_GET_ATTR_RSP:
bna_bfi_attr_get_rsp(&bna->ioceth, msghdr);
break;
case BFI_ENET_I2H_STATS_GET_RSP:
bna_bfi_stats_get_rsp(bna, msghdr);
break;
case BFI_ENET_I2H_STATS_CLR_RSP:
/* No-op */
break;
case BFI_ENET_I2H_LINK_UP_AEN:
bna_bfi_ethport_linkup_aen(&bna->ethport, msghdr);
break;
case BFI_ENET_I2H_LINK_DOWN_AEN:
bna_bfi_ethport_linkdown_aen(&bna->ethport, msghdr);
break;
case BFI_ENET_I2H_PORT_ENABLE_AEN:
bna_bfi_ethport_enable_aen(&bna->ethport, msghdr);
break;
case BFI_ENET_I2H_PORT_DISABLE_AEN:
bna_bfi_ethport_disable_aen(&bna->ethport, msghdr);
break;
case BFI_ENET_I2H_BW_UPDATE_AEN:
bna_bfi_bw_update_aen(&bna->tx_mod);
break;
default:
break;
}
}
/* ETHPORT */
#define call_ethport_stop_cbfn(_ethport) \
do { \
if ((_ethport)->stop_cbfn) { \
void (*cbfn)(struct bna_enet *); \
cbfn = (_ethport)->stop_cbfn; \
(_ethport)->stop_cbfn = NULL; \
cbfn(&(_ethport)->bna->enet); \
} \
} while (0)
#define call_ethport_adminup_cbfn(ethport, status) \
do { \
if ((ethport)->adminup_cbfn) { \
void (*cbfn)(struct bnad *, enum bna_cb_status); \
cbfn = (ethport)->adminup_cbfn; \
(ethport)->adminup_cbfn = NULL; \
cbfn((ethport)->bna->bnad, status); \
} \
} while (0)
static void
bna_bfi_ethport_admin_up(struct bna_ethport *ethport)
{
struct bfi_enet_enable_req *admin_up_req =
ðport->bfi_enet_cmd.admin_req;
bfi_msgq_mhdr_set(admin_up_req->mh, BFI_MC_ENET,
BFI_ENET_H2I_PORT_ADMIN_UP_REQ, 0, 0);
admin_up_req->mh.num_entries = htons(
bfi_msgq_num_cmd_entries(sizeof(struct bfi_enet_enable_req)));
admin_up_req->enable = BNA_STATUS_T_ENABLED;
bfa_msgq_cmd_set(ðport->msgq_cmd, NULL, NULL,
sizeof(struct bfi_enet_enable_req), &admin_up_req->mh);
bfa_msgq_cmd_post(ðport->bna->msgq, ðport->msgq_cmd);
}
static void
bna_bfi_ethport_admin_down(struct bna_ethport *ethport)
{
struct bfi_enet_enable_req *admin_down_req =
ðport->bfi_enet_cmd.admin_req;
bfi_msgq_mhdr_set(admin_down_req->mh, BFI_MC_ENET,
BFI_ENET_H2I_PORT_ADMIN_UP_REQ, 0, 0);
admin_down_req->mh.num_entries = htons(
bfi_msgq_num_cmd_entries(sizeof(struct bfi_enet_enable_req)));
admin_down_req->enable = BNA_STATUS_T_DISABLED;
bfa_msgq_cmd_set(ðport->msgq_cmd, NULL, NULL,
sizeof(struct bfi_enet_enable_req), &admin_down_req->mh);
bfa_msgq_cmd_post(ðport->bna->msgq, ðport->msgq_cmd);
}
static void
bna_bfi_ethport_lpbk_up(struct bna_ethport *ethport)
{
struct bfi_enet_diag_lb_req *lpbk_up_req =
ðport->bfi_enet_cmd.lpbk_req;
bfi_msgq_mhdr_set(lpbk_up_req->mh, BFI_MC_ENET,
BFI_ENET_H2I_DIAG_LOOPBACK_REQ, 0, 0);
lpbk_up_req->mh.num_entries = htons(
bfi_msgq_num_cmd_entries(sizeof(struct bfi_enet_diag_lb_req)));
lpbk_up_req->mode = (ethport->bna->enet.type ==
BNA_ENET_T_LOOPBACK_INTERNAL) ?
BFI_ENET_DIAG_LB_OPMODE_EXT :
BFI_ENET_DIAG_LB_OPMODE_CBL;
lpbk_up_req->enable = BNA_STATUS_T_ENABLED;
bfa_msgq_cmd_set(ðport->msgq_cmd, NULL, NULL,
sizeof(struct bfi_enet_diag_lb_req), &lpbk_up_req->mh);
bfa_msgq_cmd_post(ðport->bna->msgq, ðport->msgq_cmd);
}
static void
bna_bfi_ethport_lpbk_down(struct bna_ethport *ethport)
{
struct bfi_enet_diag_lb_req *lpbk_down_req =
ðport->bfi_enet_cmd.lpbk_req;
bfi_msgq_mhdr_set(lpbk_down_req->mh, BFI_MC_ENET,
BFI_ENET_H2I_DIAG_LOOPBACK_REQ, 0, 0);
lpbk_down_req->mh.num_entries = htons(
bfi_msgq_num_cmd_entries(sizeof(struct bfi_enet_diag_lb_req)));
lpbk_down_req->enable = BNA_STATUS_T_DISABLED;
bfa_msgq_cmd_set(ðport->msgq_cmd, NULL, NULL,
sizeof(struct bfi_enet_diag_lb_req), &lpbk_down_req->mh);
bfa_msgq_cmd_post(ðport->bna->msgq, ðport->msgq_cmd);
}
static void
bna_bfi_ethport_up(struct bna_ethport *ethport)
{
if (ethport->bna->enet.type == BNA_ENET_T_REGULAR)
bna_bfi_ethport_admin_up(ethport);
else
bna_bfi_ethport_lpbk_up(ethport);
}
static void
bna_bfi_ethport_down(struct bna_ethport *ethport)
{
if (ethport->bna->enet.type == BNA_ENET_T_REGULAR)
bna_bfi_ethport_admin_down(ethport);
else
bna_bfi_ethport_lpbk_down(ethport);
}
bfa_fsm_state_decl(bna_ethport, stopped, struct bna_ethport,
enum bna_ethport_event);
bfa_fsm_state_decl(bna_ethport, down, struct bna_ethport,
enum bna_ethport_event);
bfa_fsm_state_decl(bna_ethport, up_resp_wait, struct bna_ethport,
enum bna_ethport_event);
bfa_fsm_state_decl(bna_ethport, down_resp_wait, struct bna_ethport,
enum bna_ethport_event);
bfa_fsm_state_decl(bna_ethport, up, struct bna_ethport,
enum bna_ethport_event);
bfa_fsm_state_decl(bna_ethport, last_resp_wait, struct bna_ethport,
enum bna_ethport_event);
static void
bna_ethport_sm_stopped_entry(struct bna_ethport *ethport)
{
call_ethport_stop_cbfn(ethport);
}
static void
bna_ethport_sm_stopped(struct bna_ethport *ethport,
enum bna_ethport_event event)
{
switch (event) {
case ETHPORT_E_START:
bfa_fsm_set_state(ethport, bna_ethport_sm_down);
break;
case ETHPORT_E_STOP:
call_ethport_stop_cbfn(ethport);
break;
case ETHPORT_E_FAIL:
/* No-op */
break;
case ETHPORT_E_DOWN:
/* This event is received due to Rx objects failing */
/* No-op */
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_ethport_sm_down_entry(struct bna_ethport *ethport)
{
}
static void
bna_ethport_sm_down(struct bna_ethport *ethport,
enum bna_ethport_event event)
{
switch (event) {
case ETHPORT_E_STOP:
bfa_fsm_set_state(ethport, bna_ethport_sm_stopped);
break;
case ETHPORT_E_FAIL:
bfa_fsm_set_state(ethport, bna_ethport_sm_stopped);
break;
case ETHPORT_E_UP:
bfa_fsm_set_state(ethport, bna_ethport_sm_up_resp_wait);
bna_bfi_ethport_up(ethport);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_ethport_sm_up_resp_wait_entry(struct bna_ethport *ethport)
{
}
static void
bna_ethport_sm_up_resp_wait(struct bna_ethport *ethport,
enum bna_ethport_event event)
{
switch (event) {
case ETHPORT_E_STOP:
bfa_fsm_set_state(ethport, bna_ethport_sm_last_resp_wait);
break;
case ETHPORT_E_FAIL:
call_ethport_adminup_cbfn(ethport, BNA_CB_FAIL);
bfa_fsm_set_state(ethport, bna_ethport_sm_stopped);
break;
case ETHPORT_E_DOWN:
call_ethport_adminup_cbfn(ethport, BNA_CB_INTERRUPT);
bfa_fsm_set_state(ethport, bna_ethport_sm_down_resp_wait);
break;
case ETHPORT_E_FWRESP_UP_OK:
call_ethport_adminup_cbfn(ethport, BNA_CB_SUCCESS);
bfa_fsm_set_state(ethport, bna_ethport_sm_up);
break;
case ETHPORT_E_FWRESP_UP_FAIL:
call_ethport_adminup_cbfn(ethport, BNA_CB_FAIL);
bfa_fsm_set_state(ethport, bna_ethport_sm_down);
break;
case ETHPORT_E_FWRESP_DOWN:
/* down_resp_wait -> up_resp_wait transition on ETHPORT_E_UP */
bna_bfi_ethport_up(ethport);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_ethport_sm_down_resp_wait_entry(struct bna_ethport *ethport)
{
/**
* NOTE: Do not call bna_bfi_ethport_down() here. That will over step
* mbox due to up_resp_wait -> down_resp_wait transition on event
* ETHPORT_E_DOWN
*/
}
static void
bna_ethport_sm_down_resp_wait(struct bna_ethport *ethport,
enum bna_ethport_event event)
{
switch (event) {
case ETHPORT_E_STOP:
bfa_fsm_set_state(ethport, bna_ethport_sm_last_resp_wait);
break;
case ETHPORT_E_FAIL:
bfa_fsm_set_state(ethport, bna_ethport_sm_stopped);
break;
case ETHPORT_E_UP:
bfa_fsm_set_state(ethport, bna_ethport_sm_up_resp_wait);
break;
case ETHPORT_E_FWRESP_UP_OK:
/* up_resp_wait->down_resp_wait transition on ETHPORT_E_DOWN */
bna_bfi_ethport_down(ethport);
break;
case ETHPORT_E_FWRESP_UP_FAIL:
case ETHPORT_E_FWRESP_DOWN:
bfa_fsm_set_state(ethport, bna_ethport_sm_down);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_ethport_sm_up_entry(struct bna_ethport *ethport)
{
}
static void
bna_ethport_sm_up(struct bna_ethport *ethport,
enum bna_ethport_event event)
{
switch (event) {
case ETHPORT_E_STOP:
bfa_fsm_set_state(ethport, bna_ethport_sm_last_resp_wait);
bna_bfi_ethport_down(ethport);
break;
case ETHPORT_E_FAIL:
bfa_fsm_set_state(ethport, bna_ethport_sm_stopped);
break;
case ETHPORT_E_DOWN:
bfa_fsm_set_state(ethport, bna_ethport_sm_down_resp_wait);
bna_bfi_ethport_down(ethport);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_ethport_sm_last_resp_wait_entry(struct bna_ethport *ethport)
{
}
static void
bna_ethport_sm_last_resp_wait(struct bna_ethport *ethport,
enum bna_ethport_event event)
{
switch (event) {
case ETHPORT_E_FAIL:
bfa_fsm_set_state(ethport, bna_ethport_sm_stopped);
break;
case ETHPORT_E_DOWN:
/**
* This event is received due to Rx objects stopping in
* parallel to ethport
*/
/* No-op */
break;
case ETHPORT_E_FWRESP_UP_OK:
/* up_resp_wait->last_resp_wait transition on ETHPORT_T_STOP */
bna_bfi_ethport_down(ethport);
break;
case ETHPORT_E_FWRESP_UP_FAIL:
case ETHPORT_E_FWRESP_DOWN:
bfa_fsm_set_state(ethport, bna_ethport_sm_stopped);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_ethport_init(struct bna_ethport *ethport, struct bna *bna)
{
ethport->flags |= (BNA_ETHPORT_F_ADMIN_UP | BNA_ETHPORT_F_PORT_ENABLED);
ethport->bna = bna;
ethport->link_status = BNA_LINK_DOWN;
ethport->link_cbfn = bnad_cb_ethport_link_status;
ethport->rx_started_count = 0;
ethport->stop_cbfn = NULL;
ethport->adminup_cbfn = NULL;
bfa_fsm_set_state(ethport, bna_ethport_sm_stopped);
}
static void
bna_ethport_uninit(struct bna_ethport *ethport)
{
ethport->flags &= ~BNA_ETHPORT_F_ADMIN_UP;
ethport->flags &= ~BNA_ETHPORT_F_PORT_ENABLED;
ethport->bna = NULL;
}
static void
bna_ethport_start(struct bna_ethport *ethport)
{
bfa_fsm_send_event(ethport, ETHPORT_E_START);
}
static void
bna_enet_cb_ethport_stopped(struct bna_enet *enet)
{
bfa_wc_down(&enet->chld_stop_wc);
}
static void
bna_ethport_stop(struct bna_ethport *ethport)
{
ethport->stop_cbfn = bna_enet_cb_ethport_stopped;
bfa_fsm_send_event(ethport, ETHPORT_E_STOP);
}
static void
bna_ethport_fail(struct bna_ethport *ethport)
{
/* Reset the physical port status to enabled */
ethport->flags |= BNA_ETHPORT_F_PORT_ENABLED;
if (ethport->link_status != BNA_LINK_DOWN) {
ethport->link_status = BNA_LINK_DOWN;
ethport->link_cbfn(ethport->bna->bnad, BNA_LINK_DOWN);
}
bfa_fsm_send_event(ethport, ETHPORT_E_FAIL);
}
/* Should be called only when ethport is disabled */
void
bna_ethport_cb_rx_started(struct bna_ethport *ethport)
{
ethport->rx_started_count++;
if (ethport->rx_started_count == 1) {
ethport->flags |= BNA_ETHPORT_F_RX_STARTED;
if (ethport_can_be_up(ethport))
bfa_fsm_send_event(ethport, ETHPORT_E_UP);
}
}
void
bna_ethport_cb_rx_stopped(struct bna_ethport *ethport)
{
int ethport_up = ethport_is_up(ethport);
ethport->rx_started_count--;
if (ethport->rx_started_count == 0) {
ethport->flags &= ~BNA_ETHPORT_F_RX_STARTED;
if (ethport_up)
bfa_fsm_send_event(ethport, ETHPORT_E_DOWN);
}
}
/* ENET */
#define bna_enet_chld_start(enet) \
do { \
enum bna_tx_type tx_type = \
((enet)->type == BNA_ENET_T_REGULAR) ? \
BNA_TX_T_REGULAR : BNA_TX_T_LOOPBACK; \
enum bna_rx_type rx_type = \
((enet)->type == BNA_ENET_T_REGULAR) ? \
BNA_RX_T_REGULAR : BNA_RX_T_LOOPBACK; \
bna_ethport_start(&(enet)->bna->ethport); \
bna_tx_mod_start(&(enet)->bna->tx_mod, tx_type); \
bna_rx_mod_start(&(enet)->bna->rx_mod, rx_type); \
} while (0)
#define bna_enet_chld_stop(enet) \
do { \
enum bna_tx_type tx_type = \
((enet)->type == BNA_ENET_T_REGULAR) ? \
BNA_TX_T_REGULAR : BNA_TX_T_LOOPBACK; \
enum bna_rx_type rx_type = \
((enet)->type == BNA_ENET_T_REGULAR) ? \
BNA_RX_T_REGULAR : BNA_RX_T_LOOPBACK; \
bfa_wc_init(&(enet)->chld_stop_wc, bna_enet_cb_chld_stopped, (enet));\
bfa_wc_up(&(enet)->chld_stop_wc); \
bna_ethport_stop(&(enet)->bna->ethport); \
bfa_wc_up(&(enet)->chld_stop_wc); \
bna_tx_mod_stop(&(enet)->bna->tx_mod, tx_type); \
bfa_wc_up(&(enet)->chld_stop_wc); \
bna_rx_mod_stop(&(enet)->bna->rx_mod, rx_type); \
bfa_wc_wait(&(enet)->chld_stop_wc); \
} while (0)
#define bna_enet_chld_fail(enet) \
do { \
bna_ethport_fail(&(enet)->bna->ethport); \
bna_tx_mod_fail(&(enet)->bna->tx_mod); \
bna_rx_mod_fail(&(enet)->bna->rx_mod); \
} while (0)
#define bna_enet_rx_start(enet) \
do { \
enum bna_rx_type rx_type = \
((enet)->type == BNA_ENET_T_REGULAR) ? \
BNA_RX_T_REGULAR : BNA_RX_T_LOOPBACK; \
bna_rx_mod_start(&(enet)->bna->rx_mod, rx_type); \
} while (0)
#define bna_enet_rx_stop(enet) \
do { \
enum bna_rx_type rx_type = \
((enet)->type == BNA_ENET_T_REGULAR) ? \
BNA_RX_T_REGULAR : BNA_RX_T_LOOPBACK; \
bfa_wc_init(&(enet)->chld_stop_wc, bna_enet_cb_chld_stopped, (enet));\
bfa_wc_up(&(enet)->chld_stop_wc); \
bna_rx_mod_stop(&(enet)->bna->rx_mod, rx_type); \
bfa_wc_wait(&(enet)->chld_stop_wc); \
} while (0)
#define call_enet_stop_cbfn(enet) \
do { \
if ((enet)->stop_cbfn) { \
void (*cbfn)(void *); \
void *cbarg; \
cbfn = (enet)->stop_cbfn; \
cbarg = (enet)->stop_cbarg; \
(enet)->stop_cbfn = NULL; \
(enet)->stop_cbarg = NULL; \
cbfn(cbarg); \
} \
} while (0)
#define call_enet_mtu_cbfn(enet) \
do { \
if ((enet)->mtu_cbfn) { \
void (*cbfn)(struct bnad *); \
cbfn = (enet)->mtu_cbfn; \
(enet)->mtu_cbfn = NULL; \
cbfn((enet)->bna->bnad); \
} \
} while (0)
static void bna_enet_cb_chld_stopped(void *arg);
static void bna_bfi_pause_set(struct bna_enet *enet);
bfa_fsm_state_decl(bna_enet, stopped, struct bna_enet,
enum bna_enet_event);
bfa_fsm_state_decl(bna_enet, pause_init_wait, struct bna_enet,
enum bna_enet_event);
bfa_fsm_state_decl(bna_enet, last_resp_wait, struct bna_enet,
enum bna_enet_event);
bfa_fsm_state_decl(bna_enet, started, struct bna_enet,
enum bna_enet_event);
bfa_fsm_state_decl(bna_enet, cfg_wait, struct bna_enet,
enum bna_enet_event);
bfa_fsm_state_decl(bna_enet, cfg_stop_wait, struct bna_enet,
enum bna_enet_event);
bfa_fsm_state_decl(bna_enet, chld_stop_wait, struct bna_enet,
enum bna_enet_event);
static void
bna_enet_sm_stopped_entry(struct bna_enet *enet)
{
call_enet_mtu_cbfn(enet);
call_enet_stop_cbfn(enet);
}
static void
bna_enet_sm_stopped(struct bna_enet *enet, enum bna_enet_event event)
{
switch (event) {
case ENET_E_START:
bfa_fsm_set_state(enet, bna_enet_sm_pause_init_wait);
break;
case ENET_E_STOP:
call_enet_stop_cbfn(enet);
break;
case ENET_E_FAIL:
/* No-op */
break;
case ENET_E_PAUSE_CFG:
break;
case ENET_E_MTU_CFG:
call_enet_mtu_cbfn(enet);
break;
case ENET_E_CHLD_STOPPED:
/**
* This event is received due to Ethport, Tx and Rx objects
* failing
*/
/* No-op */
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_enet_sm_pause_init_wait_entry(struct bna_enet *enet)
{
bna_bfi_pause_set(enet);
}
static void
bna_enet_sm_pause_init_wait(struct bna_enet *enet,
enum bna_enet_event event)
{
switch (event) {
case ENET_E_STOP:
enet->flags &= ~BNA_ENET_F_PAUSE_CHANGED;
bfa_fsm_set_state(enet, bna_enet_sm_last_resp_wait);
break;
case ENET_E_FAIL:
enet->flags &= ~BNA_ENET_F_PAUSE_CHANGED;
bfa_fsm_set_state(enet, bna_enet_sm_stopped);
break;
case ENET_E_PAUSE_CFG:
enet->flags |= BNA_ENET_F_PAUSE_CHANGED;
break;
case ENET_E_MTU_CFG:
/* No-op */
break;
case ENET_E_FWRESP_PAUSE:
if (enet->flags & BNA_ENET_F_PAUSE_CHANGED) {
enet->flags &= ~BNA_ENET_F_PAUSE_CHANGED;
bna_bfi_pause_set(enet);
} else {
bfa_fsm_set_state(enet, bna_enet_sm_started);
bna_enet_chld_start(enet);
}
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_enet_sm_last_resp_wait_entry(struct bna_enet *enet)
{
enet->flags &= ~BNA_ENET_F_PAUSE_CHANGED;
}
static void
bna_enet_sm_last_resp_wait(struct bna_enet *enet,
enum bna_enet_event event)
{
switch (event) {
case ENET_E_FAIL:
case ENET_E_FWRESP_PAUSE:
bfa_fsm_set_state(enet, bna_enet_sm_stopped);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_enet_sm_started_entry(struct bna_enet *enet)
{
/**
* NOTE: Do not call bna_enet_chld_start() here, since it will be
* inadvertently called during cfg_wait->started transition as well
*/
call_enet_mtu_cbfn(enet);
}
static void
bna_enet_sm_started(struct bna_enet *enet,
enum bna_enet_event event)
{
switch (event) {
case ENET_E_STOP:
bfa_fsm_set_state(enet, bna_enet_sm_chld_stop_wait);
break;
case ENET_E_FAIL:
bfa_fsm_set_state(enet, bna_enet_sm_stopped);
bna_enet_chld_fail(enet);
break;
case ENET_E_PAUSE_CFG:
bfa_fsm_set_state(enet, bna_enet_sm_cfg_wait);
bna_bfi_pause_set(enet);
break;
case ENET_E_MTU_CFG:
bfa_fsm_set_state(enet, bna_enet_sm_cfg_wait);
bna_enet_rx_stop(enet);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_enet_sm_cfg_wait_entry(struct bna_enet *enet)
{
}
static void
bna_enet_sm_cfg_wait(struct bna_enet *enet,
enum bna_enet_event event)
{
switch (event) {
case ENET_E_STOP:
enet->flags &= ~BNA_ENET_F_PAUSE_CHANGED;
enet->flags &= ~BNA_ENET_F_MTU_CHANGED;
bfa_fsm_set_state(enet, bna_enet_sm_cfg_stop_wait);
break;
case ENET_E_FAIL:
enet->flags &= ~BNA_ENET_F_PAUSE_CHANGED;
enet->flags &= ~BNA_ENET_F_MTU_CHANGED;
bfa_fsm_set_state(enet, bna_enet_sm_stopped);
bna_enet_chld_fail(enet);
break;
case ENET_E_PAUSE_CFG:
enet->flags |= BNA_ENET_F_PAUSE_CHANGED;
break;
case ENET_E_MTU_CFG:
enet->flags |= BNA_ENET_F_MTU_CHANGED;
break;
case ENET_E_CHLD_STOPPED:
bna_enet_rx_start(enet);
fallthrough;
case ENET_E_FWRESP_PAUSE:
if (enet->flags & BNA_ENET_F_PAUSE_CHANGED) {
enet->flags &= ~BNA_ENET_F_PAUSE_CHANGED;
bna_bfi_pause_set(enet);
} else if (enet->flags & BNA_ENET_F_MTU_CHANGED) {
enet->flags &= ~BNA_ENET_F_MTU_CHANGED;
bna_enet_rx_stop(enet);
} else {
bfa_fsm_set_state(enet, bna_enet_sm_started);
}
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_enet_sm_cfg_stop_wait_entry(struct bna_enet *enet)
{
enet->flags &= ~BNA_ENET_F_PAUSE_CHANGED;
enet->flags &= ~BNA_ENET_F_MTU_CHANGED;
}
static void
bna_enet_sm_cfg_stop_wait(struct bna_enet *enet,
enum bna_enet_event event)
{
switch (event) {
case ENET_E_FAIL:
bfa_fsm_set_state(enet, bna_enet_sm_stopped);
bna_enet_chld_fail(enet);
break;
case ENET_E_FWRESP_PAUSE:
case ENET_E_CHLD_STOPPED:
bfa_fsm_set_state(enet, bna_enet_sm_chld_stop_wait);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_enet_sm_chld_stop_wait_entry(struct bna_enet *enet)
{
bna_enet_chld_stop(enet);
}
static void
bna_enet_sm_chld_stop_wait(struct bna_enet *enet,
enum bna_enet_event event)
{
switch (event) {
case ENET_E_FAIL:
bfa_fsm_set_state(enet, bna_enet_sm_stopped);
bna_enet_chld_fail(enet);
break;
case ENET_E_CHLD_STOPPED:
bfa_fsm_set_state(enet, bna_enet_sm_stopped);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_bfi_pause_set(struct bna_enet *enet)
{
struct bfi_enet_set_pause_req *pause_req = &enet->pause_req;
bfi_msgq_mhdr_set(pause_req->mh, BFI_MC_ENET,
BFI_ENET_H2I_SET_PAUSE_REQ, 0, 0);
pause_req->mh.num_entries = htons(
bfi_msgq_num_cmd_entries(sizeof(struct bfi_enet_set_pause_req)));
pause_req->tx_pause = enet->pause_config.tx_pause;
pause_req->rx_pause = enet->pause_config.rx_pause;
bfa_msgq_cmd_set(&enet->msgq_cmd, NULL, NULL,
sizeof(struct bfi_enet_set_pause_req), &pause_req->mh);
bfa_msgq_cmd_post(&enet->bna->msgq, &enet->msgq_cmd);
}
static void
bna_enet_cb_chld_stopped(void *arg)
{
struct bna_enet *enet = (struct bna_enet *)arg;
bfa_fsm_send_event(enet, ENET_E_CHLD_STOPPED);
}
static void
bna_enet_init(struct bna_enet *enet, struct bna *bna)
{
enet->bna = bna;
enet->flags = 0;
enet->mtu = 0;
enet->type = BNA_ENET_T_REGULAR;
enet->stop_cbfn = NULL;
enet->stop_cbarg = NULL;
enet->mtu_cbfn = NULL;
bfa_fsm_set_state(enet, bna_enet_sm_stopped);
}
static void
bna_enet_uninit(struct bna_enet *enet)
{
enet->flags = 0;
enet->bna = NULL;
}
static void
bna_enet_start(struct bna_enet *enet)
{
enet->flags |= BNA_ENET_F_IOCETH_READY;
if (enet->flags & BNA_ENET_F_ENABLED)
bfa_fsm_send_event(enet, ENET_E_START);
}
static void
bna_ioceth_cb_enet_stopped(void *arg)
{
struct bna_ioceth *ioceth = (struct bna_ioceth *)arg;
bfa_fsm_send_event(ioceth, IOCETH_E_ENET_STOPPED);
}
static void
bna_enet_stop(struct bna_enet *enet)
{
enet->stop_cbfn = bna_ioceth_cb_enet_stopped;
enet->stop_cbarg = &enet->bna->ioceth;
enet->flags &= ~BNA_ENET_F_IOCETH_READY;
bfa_fsm_send_event(enet, ENET_E_STOP);
}
static void
bna_enet_fail(struct bna_enet *enet)
{
enet->flags &= ~BNA_ENET_F_IOCETH_READY;
bfa_fsm_send_event(enet, ENET_E_FAIL);
}
void
bna_enet_cb_tx_stopped(struct bna_enet *enet)
{
bfa_wc_down(&enet->chld_stop_wc);
}
void
bna_enet_cb_rx_stopped(struct bna_enet *enet)
{
bfa_wc_down(&enet->chld_stop_wc);
}
int
bna_enet_mtu_get(struct bna_enet *enet)
{
return enet->mtu;
}
void
bna_enet_enable(struct bna_enet *enet)
{
if (enet->fsm != bna_enet_sm_stopped)
return;
enet->flags |= BNA_ENET_F_ENABLED;
if (enet->flags & BNA_ENET_F_IOCETH_READY)
bfa_fsm_send_event(enet, ENET_E_START);
}
void
bna_enet_disable(struct bna_enet *enet, enum bna_cleanup_type type,
void (*cbfn)(void *))
{
if (type == BNA_SOFT_CLEANUP) {
(*cbfn)(enet->bna->bnad);
return;
}
enet->stop_cbfn = cbfn;
enet->stop_cbarg = enet->bna->bnad;
enet->flags &= ~BNA_ENET_F_ENABLED;
bfa_fsm_send_event(enet, ENET_E_STOP);
}
void
bna_enet_pause_config(struct bna_enet *enet,
struct bna_pause_config *pause_config)
{
enet->pause_config = *pause_config;
bfa_fsm_send_event(enet, ENET_E_PAUSE_CFG);
}
void
bna_enet_mtu_set(struct bna_enet *enet, int mtu,
void (*cbfn)(struct bnad *))
{
enet->mtu = mtu;
enet->mtu_cbfn = cbfn;
bfa_fsm_send_event(enet, ENET_E_MTU_CFG);
}
void
bna_enet_perm_mac_get(struct bna_enet *enet, u8 *mac)
{
bfa_nw_ioc_get_mac(&enet->bna->ioceth.ioc, mac);
}
/* IOCETH */
#define enable_mbox_intr(_ioceth) \
do { \
u32 intr_status; \
bna_intr_status_get((_ioceth)->bna, intr_status); \
bnad_cb_mbox_intr_enable((_ioceth)->bna->bnad); \
bna_mbox_intr_enable((_ioceth)->bna); \
} while (0)
#define disable_mbox_intr(_ioceth) \
do { \
bna_mbox_intr_disable((_ioceth)->bna); \
bnad_cb_mbox_intr_disable((_ioceth)->bna->bnad); \
} while (0)
#define call_ioceth_stop_cbfn(_ioceth) \
do { \
if ((_ioceth)->stop_cbfn) { \
void (*cbfn)(struct bnad *); \
struct bnad *cbarg; \
cbfn = (_ioceth)->stop_cbfn; \
cbarg = (_ioceth)->stop_cbarg; \
(_ioceth)->stop_cbfn = NULL; \
(_ioceth)->stop_cbarg = NULL; \
cbfn(cbarg); \
} \
} while (0)
#define bna_stats_mod_uninit(_stats_mod) \
do { \
} while (0)
#define bna_stats_mod_start(_stats_mod) \
do { \
(_stats_mod)->ioc_ready = true; \
} while (0)
#define bna_stats_mod_stop(_stats_mod) \
do { \
(_stats_mod)->ioc_ready = false; \
} while (0)
#define bna_stats_mod_fail(_stats_mod) \
do { \
(_stats_mod)->ioc_ready = false; \
(_stats_mod)->stats_get_busy = false; \
(_stats_mod)->stats_clr_busy = false; \
} while (0)
static void bna_bfi_attr_get(struct bna_ioceth *ioceth);
bfa_fsm_state_decl(bna_ioceth, stopped, struct bna_ioceth,
enum bna_ioceth_event);
bfa_fsm_state_decl(bna_ioceth, ioc_ready_wait, struct bna_ioceth,
enum bna_ioceth_event);
bfa_fsm_state_decl(bna_ioceth, enet_attr_wait, struct bna_ioceth,
enum bna_ioceth_event);
bfa_fsm_state_decl(bna_ioceth, ready, struct bna_ioceth,
enum bna_ioceth_event);
bfa_fsm_state_decl(bna_ioceth, last_resp_wait, struct bna_ioceth,
enum bna_ioceth_event);
bfa_fsm_state_decl(bna_ioceth, enet_stop_wait, struct bna_ioceth,
enum bna_ioceth_event);
bfa_fsm_state_decl(bna_ioceth, ioc_disable_wait, struct bna_ioceth,
enum bna_ioceth_event);
bfa_fsm_state_decl(bna_ioceth, failed, struct bna_ioceth,
enum bna_ioceth_event);
static void
bna_ioceth_sm_stopped_entry(struct bna_ioceth *ioceth)
{
call_ioceth_stop_cbfn(ioceth);
}
static void
bna_ioceth_sm_stopped(struct bna_ioceth *ioceth,
enum bna_ioceth_event event)
{
switch (event) {
case IOCETH_E_ENABLE:
bfa_fsm_set_state(ioceth, bna_ioceth_sm_ioc_ready_wait);
bfa_nw_ioc_enable(&ioceth->ioc);
break;
case IOCETH_E_DISABLE:
bfa_fsm_set_state(ioceth, bna_ioceth_sm_stopped);
break;
case IOCETH_E_IOC_RESET:
enable_mbox_intr(ioceth);
break;
case IOCETH_E_IOC_FAILED:
disable_mbox_intr(ioceth);
bfa_fsm_set_state(ioceth, bna_ioceth_sm_failed);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_ioceth_sm_ioc_ready_wait_entry(struct bna_ioceth *ioceth)
{
/**
* Do not call bfa_nw_ioc_enable() here. It must be called in the
* previous state due to failed -> ioc_ready_wait transition.
*/
}
static void
bna_ioceth_sm_ioc_ready_wait(struct bna_ioceth *ioceth,
enum bna_ioceth_event event)
{
switch (event) {
case IOCETH_E_DISABLE:
bfa_fsm_set_state(ioceth, bna_ioceth_sm_ioc_disable_wait);
bfa_nw_ioc_disable(&ioceth->ioc);
break;
case IOCETH_E_IOC_RESET:
enable_mbox_intr(ioceth);
break;
case IOCETH_E_IOC_FAILED:
disable_mbox_intr(ioceth);
bfa_fsm_set_state(ioceth, bna_ioceth_sm_failed);
break;
case IOCETH_E_IOC_READY:
bfa_fsm_set_state(ioceth, bna_ioceth_sm_enet_attr_wait);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_ioceth_sm_enet_attr_wait_entry(struct bna_ioceth *ioceth)
{
bna_bfi_attr_get(ioceth);
}
static void
bna_ioceth_sm_enet_attr_wait(struct bna_ioceth *ioceth,
enum bna_ioceth_event event)
{
switch (event) {
case IOCETH_E_DISABLE:
bfa_fsm_set_state(ioceth, bna_ioceth_sm_last_resp_wait);
break;
case IOCETH_E_IOC_FAILED:
disable_mbox_intr(ioceth);
bfa_fsm_set_state(ioceth, bna_ioceth_sm_failed);
break;
case IOCETH_E_ENET_ATTR_RESP:
bfa_fsm_set_state(ioceth, bna_ioceth_sm_ready);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_ioceth_sm_ready_entry(struct bna_ioceth *ioceth)
{
bna_enet_start(&ioceth->bna->enet);
bna_stats_mod_start(&ioceth->bna->stats_mod);
bnad_cb_ioceth_ready(ioceth->bna->bnad);
}
static void
bna_ioceth_sm_ready(struct bna_ioceth *ioceth, enum bna_ioceth_event event)
{
switch (event) {
case IOCETH_E_DISABLE:
bfa_fsm_set_state(ioceth, bna_ioceth_sm_enet_stop_wait);
break;
case IOCETH_E_IOC_FAILED:
disable_mbox_intr(ioceth);
bna_enet_fail(&ioceth->bna->enet);
bna_stats_mod_fail(&ioceth->bna->stats_mod);
bfa_fsm_set_state(ioceth, bna_ioceth_sm_failed);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_ioceth_sm_last_resp_wait_entry(struct bna_ioceth *ioceth)
{
}
static void
bna_ioceth_sm_last_resp_wait(struct bna_ioceth *ioceth,
enum bna_ioceth_event event)
{
switch (event) {
case IOCETH_E_IOC_FAILED:
bfa_fsm_set_state(ioceth, bna_ioceth_sm_ioc_disable_wait);
disable_mbox_intr(ioceth);
bfa_nw_ioc_disable(&ioceth->ioc);
break;
case IOCETH_E_ENET_ATTR_RESP:
bfa_fsm_set_state(ioceth, bna_ioceth_sm_ioc_disable_wait);
bfa_nw_ioc_disable(&ioceth->ioc);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_ioceth_sm_enet_stop_wait_entry(struct bna_ioceth *ioceth)
{
bna_stats_mod_stop(&ioceth->bna->stats_mod);
bna_enet_stop(&ioceth->bna->enet);
}
static void
bna_ioceth_sm_enet_stop_wait(struct bna_ioceth *ioceth,
enum bna_ioceth_event event)
{
switch (event) {
case IOCETH_E_IOC_FAILED:
bfa_fsm_set_state(ioceth, bna_ioceth_sm_ioc_disable_wait);
disable_mbox_intr(ioceth);
bna_enet_fail(&ioceth->bna->enet);
bna_stats_mod_fail(&ioceth->bna->stats_mod);
bfa_nw_ioc_disable(&ioceth->ioc);
break;
case IOCETH_E_ENET_STOPPED:
bfa_fsm_set_state(ioceth, bna_ioceth_sm_ioc_disable_wait);
bfa_nw_ioc_disable(&ioceth->ioc);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_ioceth_sm_ioc_disable_wait_entry(struct bna_ioceth *ioceth)
{
}
static void
bna_ioceth_sm_ioc_disable_wait(struct bna_ioceth *ioceth,
enum bna_ioceth_event event)
{
switch (event) {
case IOCETH_E_IOC_DISABLED:
disable_mbox_intr(ioceth);
bfa_fsm_set_state(ioceth, bna_ioceth_sm_stopped);
break;
case IOCETH_E_ENET_STOPPED:
/* This event is received due to enet failing */
/* No-op */
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_ioceth_sm_failed_entry(struct bna_ioceth *ioceth)
{
bnad_cb_ioceth_failed(ioceth->bna->bnad);
}
static void
bna_ioceth_sm_failed(struct bna_ioceth *ioceth,
enum bna_ioceth_event event)
{
switch (event) {
case IOCETH_E_DISABLE:
bfa_fsm_set_state(ioceth, bna_ioceth_sm_ioc_disable_wait);
bfa_nw_ioc_disable(&ioceth->ioc);
break;
case IOCETH_E_IOC_RESET:
enable_mbox_intr(ioceth);
bfa_fsm_set_state(ioceth, bna_ioceth_sm_ioc_ready_wait);
break;
case IOCETH_E_IOC_FAILED:
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_bfi_attr_get(struct bna_ioceth *ioceth)
{
struct bfi_enet_attr_req *attr_req = &ioceth->attr_req;
bfi_msgq_mhdr_set(attr_req->mh, BFI_MC_ENET,
BFI_ENET_H2I_GET_ATTR_REQ, 0, 0);
attr_req->mh.num_entries = htons(
bfi_msgq_num_cmd_entries(sizeof(struct bfi_enet_attr_req)));
bfa_msgq_cmd_set(&ioceth->msgq_cmd, NULL, NULL,
sizeof(struct bfi_enet_attr_req), &attr_req->mh);
bfa_msgq_cmd_post(&ioceth->bna->msgq, &ioceth->msgq_cmd);
}
/* IOC callback functions */
static void
bna_cb_ioceth_enable(void *arg, enum bfa_status error)
{
struct bna_ioceth *ioceth = (struct bna_ioceth *)arg;
if (error)
bfa_fsm_send_event(ioceth, IOCETH_E_IOC_FAILED);
else
bfa_fsm_send_event(ioceth, IOCETH_E_IOC_READY);
}
static void
bna_cb_ioceth_disable(void *arg)
{
struct bna_ioceth *ioceth = (struct bna_ioceth *)arg;
bfa_fsm_send_event(ioceth, IOCETH_E_IOC_DISABLED);
}
static void
bna_cb_ioceth_hbfail(void *arg)
{
struct bna_ioceth *ioceth = (struct bna_ioceth *)arg;
bfa_fsm_send_event(ioceth, IOCETH_E_IOC_FAILED);
}
static void
bna_cb_ioceth_reset(void *arg)
{
struct bna_ioceth *ioceth = (struct bna_ioceth *)arg;
bfa_fsm_send_event(ioceth, IOCETH_E_IOC_RESET);
}
static struct bfa_ioc_cbfn bna_ioceth_cbfn = {
.enable_cbfn = bna_cb_ioceth_enable,
.disable_cbfn = bna_cb_ioceth_disable,
.hbfail_cbfn = bna_cb_ioceth_hbfail,
.reset_cbfn = bna_cb_ioceth_reset
};
static void bna_attr_init(struct bna_ioceth *ioceth)
{
ioceth->attr.num_txq = BFI_ENET_DEF_TXQ;
ioceth->attr.num_rxp = BFI_ENET_DEF_RXP;
ioceth->attr.num_ucmac = BFI_ENET_DEF_UCAM;
ioceth->attr.num_mcmac = BFI_ENET_MAX_MCAM;
ioceth->attr.max_rit_size = BFI_ENET_DEF_RITSZ;
ioceth->attr.fw_query_complete = false;
}
static void
bna_ioceth_init(struct bna_ioceth *ioceth, struct bna *bna,
struct bna_res_info *res_info)
{
u64 dma;
u8 *kva;
ioceth->bna = bna;
/**
* Attach IOC and claim:
* 1. DMA memory for IOC attributes
* 2. Kernel memory for FW trace
*/
bfa_nw_ioc_attach(&ioceth->ioc, ioceth, &bna_ioceth_cbfn);
bfa_nw_ioc_pci_init(&ioceth->ioc, &bna->pcidev, BFI_PCIFN_CLASS_ETH);
BNA_GET_DMA_ADDR(
&res_info[BNA_RES_MEM_T_ATTR].res_u.mem_info.mdl[0].dma, dma);
kva = res_info[BNA_RES_MEM_T_ATTR].res_u.mem_info.mdl[0].kva;
bfa_nw_ioc_mem_claim(&ioceth->ioc, kva, dma);
kva = res_info[BNA_RES_MEM_T_FWTRC].res_u.mem_info.mdl[0].kva;
bfa_nw_ioc_debug_memclaim(&ioceth->ioc, kva);
/**
* Attach common modules (Diag, SFP, CEE, Port) and claim respective
* DMA memory.
*/
BNA_GET_DMA_ADDR(
&res_info[BNA_RES_MEM_T_COM].res_u.mem_info.mdl[0].dma, dma);
kva = res_info[BNA_RES_MEM_T_COM].res_u.mem_info.mdl[0].kva;
bfa_nw_cee_attach(&bna->cee, &ioceth->ioc, bna);
bfa_nw_cee_mem_claim(&bna->cee, kva, dma);
kva += bfa_nw_cee_meminfo();
dma += bfa_nw_cee_meminfo();
bfa_nw_flash_attach(&bna->flash, &ioceth->ioc, bna);
bfa_nw_flash_memclaim(&bna->flash, kva, dma);
kva += bfa_nw_flash_meminfo();
dma += bfa_nw_flash_meminfo();
bfa_msgq_attach(&bna->msgq, &ioceth->ioc);
bfa_msgq_memclaim(&bna->msgq, kva, dma);
bfa_msgq_regisr(&bna->msgq, BFI_MC_ENET, bna_msgq_rsp_handler, bna);
kva += bfa_msgq_meminfo();
dma += bfa_msgq_meminfo();
ioceth->stop_cbfn = NULL;
ioceth->stop_cbarg = NULL;
bna_attr_init(ioceth);
bfa_fsm_set_state(ioceth, bna_ioceth_sm_stopped);
}
static void
bna_ioceth_uninit(struct bna_ioceth *ioceth)
{
bfa_nw_ioc_detach(&ioceth->ioc);
ioceth->bna = NULL;
}
void
bna_ioceth_enable(struct bna_ioceth *ioceth)
{
if (ioceth->fsm == bna_ioceth_sm_ready) {
bnad_cb_ioceth_ready(ioceth->bna->bnad);
return;
}
if (ioceth->fsm == bna_ioceth_sm_stopped)
bfa_fsm_send_event(ioceth, IOCETH_E_ENABLE);
}
void
bna_ioceth_disable(struct bna_ioceth *ioceth, enum bna_cleanup_type type)
{
if (type == BNA_SOFT_CLEANUP) {
bnad_cb_ioceth_disabled(ioceth->bna->bnad);
return;
}
ioceth->stop_cbfn = bnad_cb_ioceth_disabled;
ioceth->stop_cbarg = ioceth->bna->bnad;
bfa_fsm_send_event(ioceth, IOCETH_E_DISABLE);
}
static void
bna_ucam_mod_init(struct bna_ucam_mod *ucam_mod, struct bna *bna,
struct bna_res_info *res_info)
{
int i;
ucam_mod->ucmac = (struct bna_mac *)
res_info[BNA_MOD_RES_MEM_T_UCMAC_ARRAY].res_u.mem_info.mdl[0].kva;
INIT_LIST_HEAD(&ucam_mod->free_q);
for (i = 0; i < bna->ioceth.attr.num_ucmac; i++)
list_add_tail(&ucam_mod->ucmac[i].qe, &ucam_mod->free_q);
/* A separate queue to allow synchronous setting of a list of MACs */
INIT_LIST_HEAD(&ucam_mod->del_q);
for (; i < (bna->ioceth.attr.num_ucmac * 2); i++)
list_add_tail(&ucam_mod->ucmac[i].qe, &ucam_mod->del_q);
ucam_mod->bna = bna;
}
static void
bna_ucam_mod_uninit(struct bna_ucam_mod *ucam_mod)
{
ucam_mod->bna = NULL;
}
static void
bna_mcam_mod_init(struct bna_mcam_mod *mcam_mod, struct bna *bna,
struct bna_res_info *res_info)
{
int i;
mcam_mod->mcmac = (struct bna_mac *)
res_info[BNA_MOD_RES_MEM_T_MCMAC_ARRAY].res_u.mem_info.mdl[0].kva;
INIT_LIST_HEAD(&mcam_mod->free_q);
for (i = 0; i < bna->ioceth.attr.num_mcmac; i++)
list_add_tail(&mcam_mod->mcmac[i].qe, &mcam_mod->free_q);
mcam_mod->mchandle = (struct bna_mcam_handle *)
res_info[BNA_MOD_RES_MEM_T_MCHANDLE_ARRAY].res_u.mem_info.mdl[0].kva;
INIT_LIST_HEAD(&mcam_mod->free_handle_q);
for (i = 0; i < bna->ioceth.attr.num_mcmac; i++)
list_add_tail(&mcam_mod->mchandle[i].qe,
&mcam_mod->free_handle_q);
/* A separate queue to allow synchronous setting of a list of MACs */
INIT_LIST_HEAD(&mcam_mod->del_q);
for (; i < (bna->ioceth.attr.num_mcmac * 2); i++)
list_add_tail(&mcam_mod->mcmac[i].qe, &mcam_mod->del_q);
mcam_mod->bna = bna;
}
static void
bna_mcam_mod_uninit(struct bna_mcam_mod *mcam_mod)
{
mcam_mod->bna = NULL;
}
static void
bna_bfi_stats_get(struct bna *bna)
{
struct bfi_enet_stats_req *stats_req = &bna->stats_mod.stats_get;
bna->stats_mod.stats_get_busy = true;
bfi_msgq_mhdr_set(stats_req->mh, BFI_MC_ENET,
BFI_ENET_H2I_STATS_GET_REQ, 0, 0);
stats_req->mh.num_entries = htons(
bfi_msgq_num_cmd_entries(sizeof(struct bfi_enet_stats_req)));
stats_req->stats_mask = htons(BFI_ENET_STATS_ALL);
stats_req->tx_enet_mask = htonl(bna->tx_mod.rid_mask);
stats_req->rx_enet_mask = htonl(bna->rx_mod.rid_mask);
stats_req->host_buffer.a32.addr_hi = bna->stats.hw_stats_dma.msb;
stats_req->host_buffer.a32.addr_lo = bna->stats.hw_stats_dma.lsb;
bfa_msgq_cmd_set(&bna->stats_mod.stats_get_cmd, NULL, NULL,
sizeof(struct bfi_enet_stats_req), &stats_req->mh);
bfa_msgq_cmd_post(&bna->msgq, &bna->stats_mod.stats_get_cmd);
}
void
bna_res_req(struct bna_res_info *res_info)
{
/* DMA memory for COMMON_MODULE */
res_info[BNA_RES_MEM_T_COM].res_type = BNA_RES_T_MEM;
res_info[BNA_RES_MEM_T_COM].res_u.mem_info.mem_type = BNA_MEM_T_DMA;
res_info[BNA_RES_MEM_T_COM].res_u.mem_info.num = 1;
res_info[BNA_RES_MEM_T_COM].res_u.mem_info.len = ALIGN(
(bfa_nw_cee_meminfo() +
bfa_nw_flash_meminfo() +
bfa_msgq_meminfo()), PAGE_SIZE);
/* DMA memory for retrieving IOC attributes */
res_info[BNA_RES_MEM_T_ATTR].res_type = BNA_RES_T_MEM;
res_info[BNA_RES_MEM_T_ATTR].res_u.mem_info.mem_type = BNA_MEM_T_DMA;
res_info[BNA_RES_MEM_T_ATTR].res_u.mem_info.num = 1;
res_info[BNA_RES_MEM_T_ATTR].res_u.mem_info.len =
ALIGN(bfa_nw_ioc_meminfo(), PAGE_SIZE);
/* Virtual memory for retreiving fw_trc */
res_info[BNA_RES_MEM_T_FWTRC].res_type = BNA_RES_T_MEM;
res_info[BNA_RES_MEM_T_FWTRC].res_u.mem_info.mem_type = BNA_MEM_T_KVA;
res_info[BNA_RES_MEM_T_FWTRC].res_u.mem_info.num = 1;
res_info[BNA_RES_MEM_T_FWTRC].res_u.mem_info.len = BNA_DBG_FWTRC_LEN;
/* DMA memory for retreiving stats */
res_info[BNA_RES_MEM_T_STATS].res_type = BNA_RES_T_MEM;
res_info[BNA_RES_MEM_T_STATS].res_u.mem_info.mem_type = BNA_MEM_T_DMA;
res_info[BNA_RES_MEM_T_STATS].res_u.mem_info.num = 1;
res_info[BNA_RES_MEM_T_STATS].res_u.mem_info.len =
ALIGN(sizeof(struct bfi_enet_stats),
PAGE_SIZE);
}
void
bna_mod_res_req(struct bna *bna, struct bna_res_info *res_info)
{
struct bna_attr *attr = &bna->ioceth.attr;
/* Virtual memory for Tx objects - stored by Tx module */
res_info[BNA_MOD_RES_MEM_T_TX_ARRAY].res_type = BNA_RES_T_MEM;
res_info[BNA_MOD_RES_MEM_T_TX_ARRAY].res_u.mem_info.mem_type =
BNA_MEM_T_KVA;
res_info[BNA_MOD_RES_MEM_T_TX_ARRAY].res_u.mem_info.num = 1;
res_info[BNA_MOD_RES_MEM_T_TX_ARRAY].res_u.mem_info.len =
attr->num_txq * sizeof(struct bna_tx);
/* Virtual memory for TxQ - stored by Tx module */
res_info[BNA_MOD_RES_MEM_T_TXQ_ARRAY].res_type = BNA_RES_T_MEM;
res_info[BNA_MOD_RES_MEM_T_TXQ_ARRAY].res_u.mem_info.mem_type =
BNA_MEM_T_KVA;
res_info[BNA_MOD_RES_MEM_T_TXQ_ARRAY].res_u.mem_info.num = 1;
res_info[BNA_MOD_RES_MEM_T_TXQ_ARRAY].res_u.mem_info.len =
attr->num_txq * sizeof(struct bna_txq);
/* Virtual memory for Rx objects - stored by Rx module */
res_info[BNA_MOD_RES_MEM_T_RX_ARRAY].res_type = BNA_RES_T_MEM;
res_info[BNA_MOD_RES_MEM_T_RX_ARRAY].res_u.mem_info.mem_type =
BNA_MEM_T_KVA;
res_info[BNA_MOD_RES_MEM_T_RX_ARRAY].res_u.mem_info.num = 1;
res_info[BNA_MOD_RES_MEM_T_RX_ARRAY].res_u.mem_info.len =
attr->num_rxp * sizeof(struct bna_rx);
/* Virtual memory for RxPath - stored by Rx module */
res_info[BNA_MOD_RES_MEM_T_RXP_ARRAY].res_type = BNA_RES_T_MEM;
res_info[BNA_MOD_RES_MEM_T_RXP_ARRAY].res_u.mem_info.mem_type =
BNA_MEM_T_KVA;
res_info[BNA_MOD_RES_MEM_T_RXP_ARRAY].res_u.mem_info.num = 1;
res_info[BNA_MOD_RES_MEM_T_RXP_ARRAY].res_u.mem_info.len =
attr->num_rxp * sizeof(struct bna_rxp);
/* Virtual memory for RxQ - stored by Rx module */
res_info[BNA_MOD_RES_MEM_T_RXQ_ARRAY].res_type = BNA_RES_T_MEM;
res_info[BNA_MOD_RES_MEM_T_RXQ_ARRAY].res_u.mem_info.mem_type =
BNA_MEM_T_KVA;
res_info[BNA_MOD_RES_MEM_T_RXQ_ARRAY].res_u.mem_info.num = 1;
res_info[BNA_MOD_RES_MEM_T_RXQ_ARRAY].res_u.mem_info.len =
(attr->num_rxp * 2) * sizeof(struct bna_rxq);
/* Virtual memory for Unicast MAC address - stored by ucam module */
res_info[BNA_MOD_RES_MEM_T_UCMAC_ARRAY].res_type = BNA_RES_T_MEM;
res_info[BNA_MOD_RES_MEM_T_UCMAC_ARRAY].res_u.mem_info.mem_type =
BNA_MEM_T_KVA;
res_info[BNA_MOD_RES_MEM_T_UCMAC_ARRAY].res_u.mem_info.num = 1;
res_info[BNA_MOD_RES_MEM_T_UCMAC_ARRAY].res_u.mem_info.len =
(attr->num_ucmac * 2) * sizeof(struct bna_mac);
/* Virtual memory for Multicast MAC address - stored by mcam module */
res_info[BNA_MOD_RES_MEM_T_MCMAC_ARRAY].res_type = BNA_RES_T_MEM;
res_info[BNA_MOD_RES_MEM_T_MCMAC_ARRAY].res_u.mem_info.mem_type =
BNA_MEM_T_KVA;
res_info[BNA_MOD_RES_MEM_T_MCMAC_ARRAY].res_u.mem_info.num = 1;
res_info[BNA_MOD_RES_MEM_T_MCMAC_ARRAY].res_u.mem_info.len =
(attr->num_mcmac * 2) * sizeof(struct bna_mac);
/* Virtual memory for Multicast handle - stored by mcam module */
res_info[BNA_MOD_RES_MEM_T_MCHANDLE_ARRAY].res_type = BNA_RES_T_MEM;
res_info[BNA_MOD_RES_MEM_T_MCHANDLE_ARRAY].res_u.mem_info.mem_type =
BNA_MEM_T_KVA;
res_info[BNA_MOD_RES_MEM_T_MCHANDLE_ARRAY].res_u.mem_info.num = 1;
res_info[BNA_MOD_RES_MEM_T_MCHANDLE_ARRAY].res_u.mem_info.len =
attr->num_mcmac * sizeof(struct bna_mcam_handle);
}
void
bna_init(struct bna *bna, struct bnad *bnad,
struct bfa_pcidev *pcidev, struct bna_res_info *res_info)
{
bna->bnad = bnad;
bna->pcidev = *pcidev;
bna->stats.hw_stats_kva = (struct bfi_enet_stats *)
res_info[BNA_RES_MEM_T_STATS].res_u.mem_info.mdl[0].kva;
bna->stats.hw_stats_dma.msb =
res_info[BNA_RES_MEM_T_STATS].res_u.mem_info.mdl[0].dma.msb;
bna->stats.hw_stats_dma.lsb =
res_info[BNA_RES_MEM_T_STATS].res_u.mem_info.mdl[0].dma.lsb;
bna_reg_addr_init(bna, &bna->pcidev);
/* Also initializes diag, cee, sfp, phy_port, msgq */
bna_ioceth_init(&bna->ioceth, bna, res_info);
bna_enet_init(&bna->enet, bna);
bna_ethport_init(&bna->ethport, bna);
}
void
bna_mod_init(struct bna *bna, struct bna_res_info *res_info)
{
bna_tx_mod_init(&bna->tx_mod, bna, res_info);
bna_rx_mod_init(&bna->rx_mod, bna, res_info);
bna_ucam_mod_init(&bna->ucam_mod, bna, res_info);
bna_mcam_mod_init(&bna->mcam_mod, bna, res_info);
bna->default_mode_rid = BFI_INVALID_RID;
bna->promisc_rid = BFI_INVALID_RID;
bna->mod_flags |= BNA_MOD_F_INIT_DONE;
}
void
bna_uninit(struct bna *bna)
{
if (bna->mod_flags & BNA_MOD_F_INIT_DONE) {
bna_mcam_mod_uninit(&bna->mcam_mod);
bna_ucam_mod_uninit(&bna->ucam_mod);
bna_rx_mod_uninit(&bna->rx_mod);
bna_tx_mod_uninit(&bna->tx_mod);
bna->mod_flags &= ~BNA_MOD_F_INIT_DONE;
}
bna_stats_mod_uninit(&bna->stats_mod);
bna_ethport_uninit(&bna->ethport);
bna_enet_uninit(&bna->enet);
bna_ioceth_uninit(&bna->ioceth);
bna->bnad = NULL;
}
int
bna_num_txq_set(struct bna *bna, int num_txq)
{
if (bna->ioceth.attr.fw_query_complete &&
(num_txq <= bna->ioceth.attr.num_txq)) {
bna->ioceth.attr.num_txq = num_txq;
return BNA_CB_SUCCESS;
}
return BNA_CB_FAIL;
}
int
bna_num_rxp_set(struct bna *bna, int num_rxp)
{
if (bna->ioceth.attr.fw_query_complete &&
(num_rxp <= bna->ioceth.attr.num_rxp)) {
bna->ioceth.attr.num_rxp = num_rxp;
return BNA_CB_SUCCESS;
}
return BNA_CB_FAIL;
}
struct bna_mac *
bna_cam_mod_mac_get(struct list_head *head)
{
struct bna_mac *mac;
mac = list_first_entry_or_null(head, struct bna_mac, qe);
if (mac)
list_del(&mac->qe);
return mac;
}
struct bna_mcam_handle *
bna_mcam_mod_handle_get(struct bna_mcam_mod *mcam_mod)
{
struct bna_mcam_handle *handle;
handle = list_first_entry_or_null(&mcam_mod->free_handle_q,
struct bna_mcam_handle, qe);
if (handle)
list_del(&handle->qe);
return handle;
}
void
bna_mcam_mod_handle_put(struct bna_mcam_mod *mcam_mod,
struct bna_mcam_handle *handle)
{
list_add_tail(&handle->qe, &mcam_mod->free_handle_q);
}
void
bna_hw_stats_get(struct bna *bna)
{
if (!bna->stats_mod.ioc_ready) {
bnad_cb_stats_get(bna->bnad, BNA_CB_FAIL, &bna->stats);
return;
}
if (bna->stats_mod.stats_get_busy) {
bnad_cb_stats_get(bna->bnad, BNA_CB_BUSY, &bna->stats);
return;
}
bna_bfi_stats_get(bna);
}
|
linux-master
|
drivers/net/ethernet/brocade/bna/bna_enet.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Linux network driver for QLogic BR-series Converged Network Adapter.
*/
/*
* Copyright (c) 2005-2014 Brocade Communications Systems, Inc.
* Copyright (c) 2014-2015 QLogic Corporation
* All rights reserved
* www.qlogic.com
*/
/* MSGQ module source file. */
#include "bfi.h"
#include "bfa_msgq.h"
#include "bfa_ioc.h"
#define call_cmdq_ent_cbfn(_cmdq_ent, _status) \
{ \
bfa_msgq_cmdcbfn_t cbfn; \
void *cbarg; \
cbfn = (_cmdq_ent)->cbfn; \
cbarg = (_cmdq_ent)->cbarg; \
(_cmdq_ent)->cbfn = NULL; \
(_cmdq_ent)->cbarg = NULL; \
if (cbfn) { \
cbfn(cbarg, (_status)); \
} \
}
static void bfa_msgq_cmdq_dbell(struct bfa_msgq_cmdq *cmdq);
static void bfa_msgq_cmdq_copy_rsp(struct bfa_msgq_cmdq *cmdq);
enum cmdq_event {
CMDQ_E_START = 1,
CMDQ_E_STOP = 2,
CMDQ_E_FAIL = 3,
CMDQ_E_POST = 4,
CMDQ_E_INIT_RESP = 5,
CMDQ_E_DB_READY = 6,
};
bfa_fsm_state_decl(cmdq, stopped, struct bfa_msgq_cmdq, enum cmdq_event);
bfa_fsm_state_decl(cmdq, init_wait, struct bfa_msgq_cmdq, enum cmdq_event);
bfa_fsm_state_decl(cmdq, ready, struct bfa_msgq_cmdq, enum cmdq_event);
bfa_fsm_state_decl(cmdq, dbell_wait, struct bfa_msgq_cmdq,
enum cmdq_event);
static void
cmdq_sm_stopped_entry(struct bfa_msgq_cmdq *cmdq)
{
struct bfa_msgq_cmd_entry *cmdq_ent;
cmdq->producer_index = 0;
cmdq->consumer_index = 0;
cmdq->flags = 0;
cmdq->token = 0;
cmdq->offset = 0;
cmdq->bytes_to_copy = 0;
while (!list_empty(&cmdq->pending_q)) {
cmdq_ent = list_first_entry(&cmdq->pending_q,
struct bfa_msgq_cmd_entry, qe);
list_del(&cmdq_ent->qe);
call_cmdq_ent_cbfn(cmdq_ent, BFA_STATUS_FAILED);
}
}
static void
cmdq_sm_stopped(struct bfa_msgq_cmdq *cmdq, enum cmdq_event event)
{
switch (event) {
case CMDQ_E_START:
bfa_fsm_set_state(cmdq, cmdq_sm_init_wait);
break;
case CMDQ_E_STOP:
case CMDQ_E_FAIL:
/* No-op */
break;
case CMDQ_E_POST:
cmdq->flags |= BFA_MSGQ_CMDQ_F_DB_UPDATE;
break;
default:
bfa_sm_fault(event);
}
}
static void
cmdq_sm_init_wait_entry(struct bfa_msgq_cmdq *cmdq)
{
bfa_wc_down(&cmdq->msgq->init_wc);
}
static void
cmdq_sm_init_wait(struct bfa_msgq_cmdq *cmdq, enum cmdq_event event)
{
switch (event) {
case CMDQ_E_STOP:
case CMDQ_E_FAIL:
bfa_fsm_set_state(cmdq, cmdq_sm_stopped);
break;
case CMDQ_E_POST:
cmdq->flags |= BFA_MSGQ_CMDQ_F_DB_UPDATE;
break;
case CMDQ_E_INIT_RESP:
if (cmdq->flags & BFA_MSGQ_CMDQ_F_DB_UPDATE) {
cmdq->flags &= ~BFA_MSGQ_CMDQ_F_DB_UPDATE;
bfa_fsm_set_state(cmdq, cmdq_sm_dbell_wait);
} else
bfa_fsm_set_state(cmdq, cmdq_sm_ready);
break;
default:
bfa_sm_fault(event);
}
}
static void
cmdq_sm_ready_entry(struct bfa_msgq_cmdq *cmdq)
{
}
static void
cmdq_sm_ready(struct bfa_msgq_cmdq *cmdq, enum cmdq_event event)
{
switch (event) {
case CMDQ_E_STOP:
case CMDQ_E_FAIL:
bfa_fsm_set_state(cmdq, cmdq_sm_stopped);
break;
case CMDQ_E_POST:
bfa_fsm_set_state(cmdq, cmdq_sm_dbell_wait);
break;
default:
bfa_sm_fault(event);
}
}
static void
cmdq_sm_dbell_wait_entry(struct bfa_msgq_cmdq *cmdq)
{
bfa_msgq_cmdq_dbell(cmdq);
}
static void
cmdq_sm_dbell_wait(struct bfa_msgq_cmdq *cmdq, enum cmdq_event event)
{
switch (event) {
case CMDQ_E_STOP:
case CMDQ_E_FAIL:
bfa_fsm_set_state(cmdq, cmdq_sm_stopped);
break;
case CMDQ_E_POST:
cmdq->flags |= BFA_MSGQ_CMDQ_F_DB_UPDATE;
break;
case CMDQ_E_DB_READY:
if (cmdq->flags & BFA_MSGQ_CMDQ_F_DB_UPDATE) {
cmdq->flags &= ~BFA_MSGQ_CMDQ_F_DB_UPDATE;
bfa_fsm_set_state(cmdq, cmdq_sm_dbell_wait);
} else
bfa_fsm_set_state(cmdq, cmdq_sm_ready);
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_msgq_cmdq_dbell_ready(void *arg)
{
struct bfa_msgq_cmdq *cmdq = (struct bfa_msgq_cmdq *)arg;
bfa_fsm_send_event(cmdq, CMDQ_E_DB_READY);
}
static void
bfa_msgq_cmdq_dbell(struct bfa_msgq_cmdq *cmdq)
{
struct bfi_msgq_h2i_db *dbell =
(struct bfi_msgq_h2i_db *)(&cmdq->dbell_mb.msg[0]);
memset(dbell, 0, sizeof(struct bfi_msgq_h2i_db));
bfi_h2i_set(dbell->mh, BFI_MC_MSGQ, BFI_MSGQ_H2I_DOORBELL_PI, 0);
dbell->mh.mtag.i2htok = 0;
dbell->idx.cmdq_pi = htons(cmdq->producer_index);
if (!bfa_nw_ioc_mbox_queue(cmdq->msgq->ioc, &cmdq->dbell_mb,
bfa_msgq_cmdq_dbell_ready, cmdq)) {
bfa_msgq_cmdq_dbell_ready(cmdq);
}
}
static void
__cmd_copy(struct bfa_msgq_cmdq *cmdq, struct bfa_msgq_cmd_entry *cmd)
{
size_t len = cmd->msg_size;
size_t to_copy;
u8 *src, *dst;
src = (u8 *)cmd->msg_hdr;
dst = (u8 *)cmdq->addr.kva;
dst += (cmdq->producer_index * BFI_MSGQ_CMD_ENTRY_SIZE);
while (len) {
to_copy = (len < BFI_MSGQ_CMD_ENTRY_SIZE) ?
len : BFI_MSGQ_CMD_ENTRY_SIZE;
memcpy(dst, src, to_copy);
len -= to_copy;
src += BFI_MSGQ_CMD_ENTRY_SIZE;
BFA_MSGQ_INDX_ADD(cmdq->producer_index, 1, cmdq->depth);
dst = (u8 *)cmdq->addr.kva;
dst += (cmdq->producer_index * BFI_MSGQ_CMD_ENTRY_SIZE);
}
}
static void
bfa_msgq_cmdq_ci_update(struct bfa_msgq_cmdq *cmdq, struct bfi_mbmsg *mb)
{
struct bfi_msgq_i2h_db *dbell = (struct bfi_msgq_i2h_db *)mb;
struct bfa_msgq_cmd_entry *cmd;
int posted = 0;
cmdq->consumer_index = ntohs(dbell->idx.cmdq_ci);
/* Walk through pending list to see if the command can be posted */
while (!list_empty(&cmdq->pending_q)) {
cmd = list_first_entry(&cmdq->pending_q,
struct bfa_msgq_cmd_entry, qe);
if (ntohs(cmd->msg_hdr->num_entries) <=
BFA_MSGQ_FREE_CNT(cmdq)) {
list_del(&cmd->qe);
__cmd_copy(cmdq, cmd);
posted = 1;
call_cmdq_ent_cbfn(cmd, BFA_STATUS_OK);
} else {
break;
}
}
if (posted)
bfa_fsm_send_event(cmdq, CMDQ_E_POST);
}
static void
bfa_msgq_cmdq_copy_next(void *arg)
{
struct bfa_msgq_cmdq *cmdq = (struct bfa_msgq_cmdq *)arg;
if (cmdq->bytes_to_copy)
bfa_msgq_cmdq_copy_rsp(cmdq);
}
static void
bfa_msgq_cmdq_copy_req(struct bfa_msgq_cmdq *cmdq, struct bfi_mbmsg *mb)
{
struct bfi_msgq_i2h_cmdq_copy_req *req =
(struct bfi_msgq_i2h_cmdq_copy_req *)mb;
cmdq->token = 0;
cmdq->offset = ntohs(req->offset);
cmdq->bytes_to_copy = ntohs(req->len);
bfa_msgq_cmdq_copy_rsp(cmdq);
}
static void
bfa_msgq_cmdq_copy_rsp(struct bfa_msgq_cmdq *cmdq)
{
struct bfi_msgq_h2i_cmdq_copy_rsp *rsp =
(struct bfi_msgq_h2i_cmdq_copy_rsp *)&cmdq->copy_mb.msg[0];
int copied;
u8 *addr = (u8 *)cmdq->addr.kva;
memset(rsp, 0, sizeof(struct bfi_msgq_h2i_cmdq_copy_rsp));
bfi_h2i_set(rsp->mh, BFI_MC_MSGQ, BFI_MSGQ_H2I_CMDQ_COPY_RSP, 0);
rsp->mh.mtag.i2htok = htons(cmdq->token);
copied = (cmdq->bytes_to_copy >= BFI_CMD_COPY_SZ) ? BFI_CMD_COPY_SZ :
cmdq->bytes_to_copy;
addr += cmdq->offset;
memcpy(rsp->data, addr, copied);
cmdq->token++;
cmdq->offset += copied;
cmdq->bytes_to_copy -= copied;
if (!bfa_nw_ioc_mbox_queue(cmdq->msgq->ioc, &cmdq->copy_mb,
bfa_msgq_cmdq_copy_next, cmdq)) {
bfa_msgq_cmdq_copy_next(cmdq);
}
}
static void
bfa_msgq_cmdq_attach(struct bfa_msgq_cmdq *cmdq, struct bfa_msgq *msgq)
{
cmdq->depth = BFA_MSGQ_CMDQ_NUM_ENTRY;
INIT_LIST_HEAD(&cmdq->pending_q);
cmdq->msgq = msgq;
bfa_fsm_set_state(cmdq, cmdq_sm_stopped);
}
static void bfa_msgq_rspq_dbell(struct bfa_msgq_rspq *rspq);
enum rspq_event {
RSPQ_E_START = 1,
RSPQ_E_STOP = 2,
RSPQ_E_FAIL = 3,
RSPQ_E_RESP = 4,
RSPQ_E_INIT_RESP = 5,
RSPQ_E_DB_READY = 6,
};
bfa_fsm_state_decl(rspq, stopped, struct bfa_msgq_rspq, enum rspq_event);
bfa_fsm_state_decl(rspq, init_wait, struct bfa_msgq_rspq,
enum rspq_event);
bfa_fsm_state_decl(rspq, ready, struct bfa_msgq_rspq, enum rspq_event);
bfa_fsm_state_decl(rspq, dbell_wait, struct bfa_msgq_rspq,
enum rspq_event);
static void
rspq_sm_stopped_entry(struct bfa_msgq_rspq *rspq)
{
rspq->producer_index = 0;
rspq->consumer_index = 0;
rspq->flags = 0;
}
static void
rspq_sm_stopped(struct bfa_msgq_rspq *rspq, enum rspq_event event)
{
switch (event) {
case RSPQ_E_START:
bfa_fsm_set_state(rspq, rspq_sm_init_wait);
break;
case RSPQ_E_STOP:
case RSPQ_E_FAIL:
/* No-op */
break;
default:
bfa_sm_fault(event);
}
}
static void
rspq_sm_init_wait_entry(struct bfa_msgq_rspq *rspq)
{
bfa_wc_down(&rspq->msgq->init_wc);
}
static void
rspq_sm_init_wait(struct bfa_msgq_rspq *rspq, enum rspq_event event)
{
switch (event) {
case RSPQ_E_FAIL:
case RSPQ_E_STOP:
bfa_fsm_set_state(rspq, rspq_sm_stopped);
break;
case RSPQ_E_INIT_RESP:
bfa_fsm_set_state(rspq, rspq_sm_ready);
break;
default:
bfa_sm_fault(event);
}
}
static void
rspq_sm_ready_entry(struct bfa_msgq_rspq *rspq)
{
}
static void
rspq_sm_ready(struct bfa_msgq_rspq *rspq, enum rspq_event event)
{
switch (event) {
case RSPQ_E_STOP:
case RSPQ_E_FAIL:
bfa_fsm_set_state(rspq, rspq_sm_stopped);
break;
case RSPQ_E_RESP:
bfa_fsm_set_state(rspq, rspq_sm_dbell_wait);
break;
default:
bfa_sm_fault(event);
}
}
static void
rspq_sm_dbell_wait_entry(struct bfa_msgq_rspq *rspq)
{
if (!bfa_nw_ioc_is_disabled(rspq->msgq->ioc))
bfa_msgq_rspq_dbell(rspq);
}
static void
rspq_sm_dbell_wait(struct bfa_msgq_rspq *rspq, enum rspq_event event)
{
switch (event) {
case RSPQ_E_STOP:
case RSPQ_E_FAIL:
bfa_fsm_set_state(rspq, rspq_sm_stopped);
break;
case RSPQ_E_RESP:
rspq->flags |= BFA_MSGQ_RSPQ_F_DB_UPDATE;
break;
case RSPQ_E_DB_READY:
if (rspq->flags & BFA_MSGQ_RSPQ_F_DB_UPDATE) {
rspq->flags &= ~BFA_MSGQ_RSPQ_F_DB_UPDATE;
bfa_fsm_set_state(rspq, rspq_sm_dbell_wait);
} else
bfa_fsm_set_state(rspq, rspq_sm_ready);
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_msgq_rspq_dbell_ready(void *arg)
{
struct bfa_msgq_rspq *rspq = (struct bfa_msgq_rspq *)arg;
bfa_fsm_send_event(rspq, RSPQ_E_DB_READY);
}
static void
bfa_msgq_rspq_dbell(struct bfa_msgq_rspq *rspq)
{
struct bfi_msgq_h2i_db *dbell =
(struct bfi_msgq_h2i_db *)(&rspq->dbell_mb.msg[0]);
memset(dbell, 0, sizeof(struct bfi_msgq_h2i_db));
bfi_h2i_set(dbell->mh, BFI_MC_MSGQ, BFI_MSGQ_H2I_DOORBELL_CI, 0);
dbell->mh.mtag.i2htok = 0;
dbell->idx.rspq_ci = htons(rspq->consumer_index);
if (!bfa_nw_ioc_mbox_queue(rspq->msgq->ioc, &rspq->dbell_mb,
bfa_msgq_rspq_dbell_ready, rspq)) {
bfa_msgq_rspq_dbell_ready(rspq);
}
}
static void
bfa_msgq_rspq_pi_update(struct bfa_msgq_rspq *rspq, struct bfi_mbmsg *mb)
{
struct bfi_msgq_i2h_db *dbell = (struct bfi_msgq_i2h_db *)mb;
struct bfi_msgq_mhdr *msghdr;
int num_entries;
int mc;
u8 *rspq_qe;
rspq->producer_index = ntohs(dbell->idx.rspq_pi);
while (rspq->consumer_index != rspq->producer_index) {
rspq_qe = (u8 *)rspq->addr.kva;
rspq_qe += (rspq->consumer_index * BFI_MSGQ_RSP_ENTRY_SIZE);
msghdr = (struct bfi_msgq_mhdr *)rspq_qe;
mc = msghdr->msg_class;
num_entries = ntohs(msghdr->num_entries);
if ((mc >= BFI_MC_MAX) || (rspq->rsphdlr[mc].cbfn == NULL))
break;
(rspq->rsphdlr[mc].cbfn)(rspq->rsphdlr[mc].cbarg, msghdr);
BFA_MSGQ_INDX_ADD(rspq->consumer_index, num_entries,
rspq->depth);
}
bfa_fsm_send_event(rspq, RSPQ_E_RESP);
}
static void
bfa_msgq_rspq_attach(struct bfa_msgq_rspq *rspq, struct bfa_msgq *msgq)
{
rspq->depth = BFA_MSGQ_RSPQ_NUM_ENTRY;
rspq->msgq = msgq;
bfa_fsm_set_state(rspq, rspq_sm_stopped);
}
static void
bfa_msgq_init_rsp(struct bfa_msgq *msgq,
struct bfi_mbmsg *mb)
{
bfa_fsm_send_event(&msgq->cmdq, CMDQ_E_INIT_RESP);
bfa_fsm_send_event(&msgq->rspq, RSPQ_E_INIT_RESP);
}
static void
bfa_msgq_init(void *arg)
{
struct bfa_msgq *msgq = (struct bfa_msgq *)arg;
struct bfi_msgq_cfg_req *msgq_cfg =
(struct bfi_msgq_cfg_req *)&msgq->init_mb.msg[0];
memset(msgq_cfg, 0, sizeof(struct bfi_msgq_cfg_req));
bfi_h2i_set(msgq_cfg->mh, BFI_MC_MSGQ, BFI_MSGQ_H2I_INIT_REQ, 0);
msgq_cfg->mh.mtag.i2htok = 0;
bfa_dma_be_addr_set(msgq_cfg->cmdq.addr, msgq->cmdq.addr.pa);
msgq_cfg->cmdq.q_depth = htons(msgq->cmdq.depth);
bfa_dma_be_addr_set(msgq_cfg->rspq.addr, msgq->rspq.addr.pa);
msgq_cfg->rspq.q_depth = htons(msgq->rspq.depth);
bfa_nw_ioc_mbox_queue(msgq->ioc, &msgq->init_mb, NULL, NULL);
}
static void
bfa_msgq_isr(void *cbarg, struct bfi_mbmsg *msg)
{
struct bfa_msgq *msgq = (struct bfa_msgq *)cbarg;
switch (msg->mh.msg_id) {
case BFI_MSGQ_I2H_INIT_RSP:
bfa_msgq_init_rsp(msgq, msg);
break;
case BFI_MSGQ_I2H_DOORBELL_PI:
bfa_msgq_rspq_pi_update(&msgq->rspq, msg);
break;
case BFI_MSGQ_I2H_DOORBELL_CI:
bfa_msgq_cmdq_ci_update(&msgq->cmdq, msg);
break;
case BFI_MSGQ_I2H_CMDQ_COPY_REQ:
bfa_msgq_cmdq_copy_req(&msgq->cmdq, msg);
break;
default:
BUG_ON(1);
}
}
static void
bfa_msgq_notify(void *cbarg, enum bfa_ioc_event event)
{
struct bfa_msgq *msgq = (struct bfa_msgq *)cbarg;
switch (event) {
case BFA_IOC_E_ENABLED:
bfa_wc_init(&msgq->init_wc, bfa_msgq_init, msgq);
bfa_wc_up(&msgq->init_wc);
bfa_fsm_send_event(&msgq->cmdq, CMDQ_E_START);
bfa_wc_up(&msgq->init_wc);
bfa_fsm_send_event(&msgq->rspq, RSPQ_E_START);
bfa_wc_wait(&msgq->init_wc);
break;
case BFA_IOC_E_DISABLED:
bfa_fsm_send_event(&msgq->cmdq, CMDQ_E_STOP);
bfa_fsm_send_event(&msgq->rspq, RSPQ_E_STOP);
break;
case BFA_IOC_E_FAILED:
bfa_fsm_send_event(&msgq->cmdq, CMDQ_E_FAIL);
bfa_fsm_send_event(&msgq->rspq, RSPQ_E_FAIL);
break;
default:
break;
}
}
u32
bfa_msgq_meminfo(void)
{
return roundup(BFA_MSGQ_CMDQ_SIZE, BFA_DMA_ALIGN_SZ) +
roundup(BFA_MSGQ_RSPQ_SIZE, BFA_DMA_ALIGN_SZ);
}
void
bfa_msgq_memclaim(struct bfa_msgq *msgq, u8 *kva, u64 pa)
{
msgq->cmdq.addr.kva = kva;
msgq->cmdq.addr.pa = pa;
kva += roundup(BFA_MSGQ_CMDQ_SIZE, BFA_DMA_ALIGN_SZ);
pa += roundup(BFA_MSGQ_CMDQ_SIZE, BFA_DMA_ALIGN_SZ);
msgq->rspq.addr.kva = kva;
msgq->rspq.addr.pa = pa;
}
void
bfa_msgq_attach(struct bfa_msgq *msgq, struct bfa_ioc *ioc)
{
msgq->ioc = ioc;
bfa_msgq_cmdq_attach(&msgq->cmdq, msgq);
bfa_msgq_rspq_attach(&msgq->rspq, msgq);
bfa_nw_ioc_mbox_regisr(msgq->ioc, BFI_MC_MSGQ, bfa_msgq_isr, msgq);
bfa_ioc_notify_init(&msgq->ioc_notify, bfa_msgq_notify, msgq);
bfa_nw_ioc_notify_register(msgq->ioc, &msgq->ioc_notify);
}
void
bfa_msgq_regisr(struct bfa_msgq *msgq, enum bfi_mclass mc,
bfa_msgq_mcfunc_t cbfn, void *cbarg)
{
msgq->rspq.rsphdlr[mc].cbfn = cbfn;
msgq->rspq.rsphdlr[mc].cbarg = cbarg;
}
void
bfa_msgq_cmd_post(struct bfa_msgq *msgq, struct bfa_msgq_cmd_entry *cmd)
{
if (ntohs(cmd->msg_hdr->num_entries) <=
BFA_MSGQ_FREE_CNT(&msgq->cmdq)) {
__cmd_copy(&msgq->cmdq, cmd);
call_cmdq_ent_cbfn(cmd, BFA_STATUS_OK);
bfa_fsm_send_event(&msgq->cmdq, CMDQ_E_POST);
} else {
list_add_tail(&cmd->qe, &msgq->cmdq.pending_q);
}
}
void
bfa_msgq_rsp_copy(struct bfa_msgq *msgq, u8 *buf, size_t buf_len)
{
struct bfa_msgq_rspq *rspq = &msgq->rspq;
size_t len = buf_len;
size_t to_copy;
int ci;
u8 *src, *dst;
ci = rspq->consumer_index;
src = (u8 *)rspq->addr.kva;
src += (ci * BFI_MSGQ_RSP_ENTRY_SIZE);
dst = buf;
while (len) {
to_copy = (len < BFI_MSGQ_RSP_ENTRY_SIZE) ?
len : BFI_MSGQ_RSP_ENTRY_SIZE;
memcpy(dst, src, to_copy);
len -= to_copy;
dst += BFI_MSGQ_RSP_ENTRY_SIZE;
BFA_MSGQ_INDX_ADD(ci, 1, rspq->depth);
src = (u8 *)rspq->addr.kva;
src += (ci * BFI_MSGQ_RSP_ENTRY_SIZE);
}
}
|
linux-master
|
drivers/net/ethernet/brocade/bna/bfa_msgq.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Linux network driver for QLogic BR-series Converged Network Adapter.
*/
/*
* Copyright (c) 2005-2014 Brocade Communications Systems, Inc.
* Copyright (c) 2014-2015 QLogic Corporation
* All rights reserved
* www.qlogic.com
*/
#include "cna.h"
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <linux/ethtool.h>
#include <linux/rtnetlink.h>
#include "bna.h"
#include "bnad.h"
#define BNAD_NUM_TXF_COUNTERS 12
#define BNAD_NUM_RXF_COUNTERS 10
#define BNAD_NUM_CQ_COUNTERS (3 + 5)
#define BNAD_NUM_RXQ_COUNTERS 7
#define BNAD_NUM_TXQ_COUNTERS 5
static const char *bnad_net_stats_strings[] = {
"rx_packets",
"tx_packets",
"rx_bytes",
"tx_bytes",
"rx_errors",
"tx_errors",
"rx_dropped",
"tx_dropped",
"multicast",
"collisions",
"rx_length_errors",
"rx_crc_errors",
"rx_frame_errors",
"tx_fifo_errors",
"netif_queue_stop",
"netif_queue_wakeup",
"netif_queue_stopped",
"tso4",
"tso6",
"tso_err",
"tcpcsum_offload",
"udpcsum_offload",
"csum_help",
"tx_skb_too_short",
"tx_skb_stopping",
"tx_skb_max_vectors",
"tx_skb_mss_too_long",
"tx_skb_tso_too_short",
"tx_skb_tso_prepare",
"tx_skb_non_tso_too_long",
"tx_skb_tcp_hdr",
"tx_skb_udp_hdr",
"tx_skb_csum_err",
"tx_skb_headlen_too_long",
"tx_skb_headlen_zero",
"tx_skb_frag_zero",
"tx_skb_len_mismatch",
"tx_skb_map_failed",
"hw_stats_updates",
"netif_rx_dropped",
"link_toggle",
"cee_toggle",
"rxp_info_alloc_failed",
"mbox_intr_disabled",
"mbox_intr_enabled",
"tx_unmap_q_alloc_failed",
"rx_unmap_q_alloc_failed",
"rxbuf_alloc_failed",
"rxbuf_map_failed",
"mac_stats_clr_cnt",
"mac_frame_64",
"mac_frame_65_127",
"mac_frame_128_255",
"mac_frame_256_511",
"mac_frame_512_1023",
"mac_frame_1024_1518",
"mac_frame_1518_1522",
"mac_rx_bytes",
"mac_rx_packets",
"mac_rx_fcs_error",
"mac_rx_multicast",
"mac_rx_broadcast",
"mac_rx_control_frames",
"mac_rx_pause",
"mac_rx_unknown_opcode",
"mac_rx_alignment_error",
"mac_rx_frame_length_error",
"mac_rx_code_error",
"mac_rx_carrier_sense_error",
"mac_rx_undersize",
"mac_rx_oversize",
"mac_rx_fragments",
"mac_rx_jabber",
"mac_rx_drop",
"mac_tx_bytes",
"mac_tx_packets",
"mac_tx_multicast",
"mac_tx_broadcast",
"mac_tx_pause",
"mac_tx_deferral",
"mac_tx_excessive_deferral",
"mac_tx_single_collision",
"mac_tx_multiple_collision",
"mac_tx_late_collision",
"mac_tx_excessive_collision",
"mac_tx_total_collision",
"mac_tx_pause_honored",
"mac_tx_drop",
"mac_tx_jabber",
"mac_tx_fcs_error",
"mac_tx_control_frame",
"mac_tx_oversize",
"mac_tx_undersize",
"mac_tx_fragments",
"bpc_tx_pause_0",
"bpc_tx_pause_1",
"bpc_tx_pause_2",
"bpc_tx_pause_3",
"bpc_tx_pause_4",
"bpc_tx_pause_5",
"bpc_tx_pause_6",
"bpc_tx_pause_7",
"bpc_tx_zero_pause_0",
"bpc_tx_zero_pause_1",
"bpc_tx_zero_pause_2",
"bpc_tx_zero_pause_3",
"bpc_tx_zero_pause_4",
"bpc_tx_zero_pause_5",
"bpc_tx_zero_pause_6",
"bpc_tx_zero_pause_7",
"bpc_tx_first_pause_0",
"bpc_tx_first_pause_1",
"bpc_tx_first_pause_2",
"bpc_tx_first_pause_3",
"bpc_tx_first_pause_4",
"bpc_tx_first_pause_5",
"bpc_tx_first_pause_6",
"bpc_tx_first_pause_7",
"bpc_rx_pause_0",
"bpc_rx_pause_1",
"bpc_rx_pause_2",
"bpc_rx_pause_3",
"bpc_rx_pause_4",
"bpc_rx_pause_5",
"bpc_rx_pause_6",
"bpc_rx_pause_7",
"bpc_rx_zero_pause_0",
"bpc_rx_zero_pause_1",
"bpc_rx_zero_pause_2",
"bpc_rx_zero_pause_3",
"bpc_rx_zero_pause_4",
"bpc_rx_zero_pause_5",
"bpc_rx_zero_pause_6",
"bpc_rx_zero_pause_7",
"bpc_rx_first_pause_0",
"bpc_rx_first_pause_1",
"bpc_rx_first_pause_2",
"bpc_rx_first_pause_3",
"bpc_rx_first_pause_4",
"bpc_rx_first_pause_5",
"bpc_rx_first_pause_6",
"bpc_rx_first_pause_7",
"rad_rx_frames",
"rad_rx_octets",
"rad_rx_vlan_frames",
"rad_rx_ucast",
"rad_rx_ucast_octets",
"rad_rx_ucast_vlan",
"rad_rx_mcast",
"rad_rx_mcast_octets",
"rad_rx_mcast_vlan",
"rad_rx_bcast",
"rad_rx_bcast_octets",
"rad_rx_bcast_vlan",
"rad_rx_drops",
"rlb_rad_rx_frames",
"rlb_rad_rx_octets",
"rlb_rad_rx_vlan_frames",
"rlb_rad_rx_ucast",
"rlb_rad_rx_ucast_octets",
"rlb_rad_rx_ucast_vlan",
"rlb_rad_rx_mcast",
"rlb_rad_rx_mcast_octets",
"rlb_rad_rx_mcast_vlan",
"rlb_rad_rx_bcast",
"rlb_rad_rx_bcast_octets",
"rlb_rad_rx_bcast_vlan",
"rlb_rad_rx_drops",
"fc_rx_ucast_octets",
"fc_rx_ucast",
"fc_rx_ucast_vlan",
"fc_rx_mcast_octets",
"fc_rx_mcast",
"fc_rx_mcast_vlan",
"fc_rx_bcast_octets",
"fc_rx_bcast",
"fc_rx_bcast_vlan",
"fc_tx_ucast_octets",
"fc_tx_ucast",
"fc_tx_ucast_vlan",
"fc_tx_mcast_octets",
"fc_tx_mcast",
"fc_tx_mcast_vlan",
"fc_tx_bcast_octets",
"fc_tx_bcast",
"fc_tx_bcast_vlan",
"fc_tx_parity_errors",
"fc_tx_timeout",
"fc_tx_fid_parity_errors",
};
#define BNAD_ETHTOOL_STATS_NUM ARRAY_SIZE(bnad_net_stats_strings)
static int
bnad_get_link_ksettings(struct net_device *netdev,
struct ethtool_link_ksettings *cmd)
{
ethtool_link_ksettings_zero_link_mode(cmd, supported);
ethtool_link_ksettings_zero_link_mode(cmd, advertising);
ethtool_link_ksettings_add_link_mode(cmd, supported, 10000baseCR_Full);
ethtool_link_ksettings_add_link_mode(cmd, supported, 10000baseSR_Full);
ethtool_link_ksettings_add_link_mode(cmd, supported, 10000baseLR_Full);
ethtool_link_ksettings_add_link_mode(cmd, advertising, 10000baseCR_Full);
ethtool_link_ksettings_add_link_mode(cmd, advertising, 10000baseSR_Full);
ethtool_link_ksettings_add_link_mode(cmd, advertising, 10000baseLR_Full);
cmd->base.autoneg = AUTONEG_DISABLE;
ethtool_link_ksettings_add_link_mode(cmd, supported, FIBRE);
ethtool_link_ksettings_add_link_mode(cmd, advertising, FIBRE);
cmd->base.port = PORT_FIBRE;
cmd->base.phy_address = 0;
if (netif_carrier_ok(netdev)) {
cmd->base.speed = SPEED_10000;
cmd->base.duplex = DUPLEX_FULL;
} else {
cmd->base.speed = SPEED_UNKNOWN;
cmd->base.duplex = DUPLEX_UNKNOWN;
}
return 0;
}
static int
bnad_set_link_ksettings(struct net_device *netdev,
const struct ethtool_link_ksettings *cmd)
{
/* 10G full duplex setting supported only */
if (cmd->base.autoneg == AUTONEG_ENABLE)
return -EOPNOTSUPP;
if ((cmd->base.speed == SPEED_10000) &&
(cmd->base.duplex == DUPLEX_FULL))
return 0;
return -EOPNOTSUPP;
}
static void
bnad_get_drvinfo(struct net_device *netdev, struct ethtool_drvinfo *drvinfo)
{
struct bnad *bnad = netdev_priv(netdev);
struct bfa_ioc_attr *ioc_attr;
unsigned long flags;
strscpy(drvinfo->driver, BNAD_NAME, sizeof(drvinfo->driver));
ioc_attr = kzalloc(sizeof(*ioc_attr), GFP_KERNEL);
if (ioc_attr) {
spin_lock_irqsave(&bnad->bna_lock, flags);
bfa_nw_ioc_get_attr(&bnad->bna.ioceth.ioc, ioc_attr);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
strscpy(drvinfo->fw_version, ioc_attr->adapter_attr.fw_ver,
sizeof(drvinfo->fw_version));
kfree(ioc_attr);
}
strscpy(drvinfo->bus_info, pci_name(bnad->pcidev),
sizeof(drvinfo->bus_info));
}
static void
bnad_get_wol(struct net_device *netdev, struct ethtool_wolinfo *wolinfo)
{
wolinfo->supported = 0;
wolinfo->wolopts = 0;
}
static int bnad_get_coalesce(struct net_device *netdev,
struct ethtool_coalesce *coalesce,
struct kernel_ethtool_coalesce *kernel_coal,
struct netlink_ext_ack *extack)
{
struct bnad *bnad = netdev_priv(netdev);
unsigned long flags;
/* Lock rqd. to access bnad->bna_lock */
spin_lock_irqsave(&bnad->bna_lock, flags);
coalesce->use_adaptive_rx_coalesce =
(bnad->cfg_flags & BNAD_CF_DIM_ENABLED) ? true : false;
spin_unlock_irqrestore(&bnad->bna_lock, flags);
coalesce->rx_coalesce_usecs = bnad->rx_coalescing_timeo *
BFI_COALESCING_TIMER_UNIT;
coalesce->tx_coalesce_usecs = bnad->tx_coalescing_timeo *
BFI_COALESCING_TIMER_UNIT;
coalesce->tx_max_coalesced_frames = BFI_TX_INTERPKT_COUNT;
return 0;
}
static int bnad_set_coalesce(struct net_device *netdev,
struct ethtool_coalesce *coalesce,
struct kernel_ethtool_coalesce *kernel_coal,
struct netlink_ext_ack *extack)
{
struct bnad *bnad = netdev_priv(netdev);
unsigned long flags;
int to_del = 0;
if (coalesce->rx_coalesce_usecs == 0 ||
coalesce->rx_coalesce_usecs >
BFI_MAX_COALESCING_TIMEO * BFI_COALESCING_TIMER_UNIT)
return -EINVAL;
if (coalesce->tx_coalesce_usecs == 0 ||
coalesce->tx_coalesce_usecs >
BFI_MAX_COALESCING_TIMEO * BFI_COALESCING_TIMER_UNIT)
return -EINVAL;
mutex_lock(&bnad->conf_mutex);
/*
* Do not need to store rx_coalesce_usecs here
* Every time DIM is disabled, we can get it from the
* stack.
*/
spin_lock_irqsave(&bnad->bna_lock, flags);
if (coalesce->use_adaptive_rx_coalesce) {
if (!(bnad->cfg_flags & BNAD_CF_DIM_ENABLED)) {
bnad->cfg_flags |= BNAD_CF_DIM_ENABLED;
bnad_dim_timer_start(bnad);
}
} else {
if (bnad->cfg_flags & BNAD_CF_DIM_ENABLED) {
bnad->cfg_flags &= ~BNAD_CF_DIM_ENABLED;
if (bnad->cfg_flags & BNAD_CF_DIM_ENABLED &&
test_bit(BNAD_RF_DIM_TIMER_RUNNING,
&bnad->run_flags)) {
clear_bit(BNAD_RF_DIM_TIMER_RUNNING,
&bnad->run_flags);
to_del = 1;
}
spin_unlock_irqrestore(&bnad->bna_lock, flags);
if (to_del)
del_timer_sync(&bnad->dim_timer);
spin_lock_irqsave(&bnad->bna_lock, flags);
bnad_rx_coalescing_timeo_set(bnad);
}
}
if (bnad->tx_coalescing_timeo != coalesce->tx_coalesce_usecs /
BFI_COALESCING_TIMER_UNIT) {
bnad->tx_coalescing_timeo = coalesce->tx_coalesce_usecs /
BFI_COALESCING_TIMER_UNIT;
bnad_tx_coalescing_timeo_set(bnad);
}
if (bnad->rx_coalescing_timeo != coalesce->rx_coalesce_usecs /
BFI_COALESCING_TIMER_UNIT) {
bnad->rx_coalescing_timeo = coalesce->rx_coalesce_usecs /
BFI_COALESCING_TIMER_UNIT;
if (!(bnad->cfg_flags & BNAD_CF_DIM_ENABLED))
bnad_rx_coalescing_timeo_set(bnad);
}
/* Add Tx Inter-pkt DMA count? */
spin_unlock_irqrestore(&bnad->bna_lock, flags);
mutex_unlock(&bnad->conf_mutex);
return 0;
}
static void
bnad_get_ringparam(struct net_device *netdev,
struct ethtool_ringparam *ringparam,
struct kernel_ethtool_ringparam *kernel_ringparam,
struct netlink_ext_ack *extack)
{
struct bnad *bnad = netdev_priv(netdev);
ringparam->rx_max_pending = BNAD_MAX_RXQ_DEPTH;
ringparam->tx_max_pending = BNAD_MAX_TXQ_DEPTH;
ringparam->rx_pending = bnad->rxq_depth;
ringparam->tx_pending = bnad->txq_depth;
}
static int
bnad_set_ringparam(struct net_device *netdev,
struct ethtool_ringparam *ringparam,
struct kernel_ethtool_ringparam *kernel_ringparam,
struct netlink_ext_ack *extack)
{
int i, current_err, err = 0;
struct bnad *bnad = netdev_priv(netdev);
unsigned long flags;
mutex_lock(&bnad->conf_mutex);
if (ringparam->rx_pending == bnad->rxq_depth &&
ringparam->tx_pending == bnad->txq_depth) {
mutex_unlock(&bnad->conf_mutex);
return 0;
}
if (ringparam->rx_pending < BNAD_MIN_Q_DEPTH ||
ringparam->rx_pending > BNAD_MAX_RXQ_DEPTH ||
!is_power_of_2(ringparam->rx_pending)) {
mutex_unlock(&bnad->conf_mutex);
return -EINVAL;
}
if (ringparam->tx_pending < BNAD_MIN_Q_DEPTH ||
ringparam->tx_pending > BNAD_MAX_TXQ_DEPTH ||
!is_power_of_2(ringparam->tx_pending)) {
mutex_unlock(&bnad->conf_mutex);
return -EINVAL;
}
if (ringparam->rx_pending != bnad->rxq_depth) {
bnad->rxq_depth = ringparam->rx_pending;
if (!netif_running(netdev)) {
mutex_unlock(&bnad->conf_mutex);
return 0;
}
for (i = 0; i < bnad->num_rx; i++) {
if (!bnad->rx_info[i].rx)
continue;
bnad_destroy_rx(bnad, i);
current_err = bnad_setup_rx(bnad, i);
if (current_err && !err)
err = current_err;
}
if (!err && bnad->rx_info[0].rx) {
/* restore rx configuration */
bnad_restore_vlans(bnad, 0);
bnad_enable_default_bcast(bnad);
spin_lock_irqsave(&bnad->bna_lock, flags);
bnad_mac_addr_set_locked(bnad, netdev->dev_addr);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
bnad->cfg_flags &= ~(BNAD_CF_ALLMULTI |
BNAD_CF_PROMISC);
bnad_set_rx_mode(netdev);
}
}
if (ringparam->tx_pending != bnad->txq_depth) {
bnad->txq_depth = ringparam->tx_pending;
if (!netif_running(netdev)) {
mutex_unlock(&bnad->conf_mutex);
return 0;
}
for (i = 0; i < bnad->num_tx; i++) {
if (!bnad->tx_info[i].tx)
continue;
bnad_destroy_tx(bnad, i);
current_err = bnad_setup_tx(bnad, i);
if (current_err && !err)
err = current_err;
}
}
mutex_unlock(&bnad->conf_mutex);
return err;
}
static void
bnad_get_pauseparam(struct net_device *netdev,
struct ethtool_pauseparam *pauseparam)
{
struct bnad *bnad = netdev_priv(netdev);
pauseparam->autoneg = 0;
pauseparam->rx_pause = bnad->bna.enet.pause_config.rx_pause;
pauseparam->tx_pause = bnad->bna.enet.pause_config.tx_pause;
}
static int
bnad_set_pauseparam(struct net_device *netdev,
struct ethtool_pauseparam *pauseparam)
{
struct bnad *bnad = netdev_priv(netdev);
struct bna_pause_config pause_config;
unsigned long flags;
if (pauseparam->autoneg == AUTONEG_ENABLE)
return -EINVAL;
mutex_lock(&bnad->conf_mutex);
if (pauseparam->rx_pause != bnad->bna.enet.pause_config.rx_pause ||
pauseparam->tx_pause != bnad->bna.enet.pause_config.tx_pause) {
pause_config.rx_pause = pauseparam->rx_pause;
pause_config.tx_pause = pauseparam->tx_pause;
spin_lock_irqsave(&bnad->bna_lock, flags);
bna_enet_pause_config(&bnad->bna.enet, &pause_config);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
}
mutex_unlock(&bnad->conf_mutex);
return 0;
}
static void bnad_get_txf_strings(u8 **string, int f_num)
{
ethtool_sprintf(string, "txf%d_ucast_octets", f_num);
ethtool_sprintf(string, "txf%d_ucast", f_num);
ethtool_sprintf(string, "txf%d_ucast_vlan", f_num);
ethtool_sprintf(string, "txf%d_mcast_octets", f_num);
ethtool_sprintf(string, "txf%d_mcast", f_num);
ethtool_sprintf(string, "txf%d_mcast_vlan", f_num);
ethtool_sprintf(string, "txf%d_bcast_octets", f_num);
ethtool_sprintf(string, "txf%d_bcast", f_num);
ethtool_sprintf(string, "txf%d_bcast_vlan", f_num);
ethtool_sprintf(string, "txf%d_errors", f_num);
ethtool_sprintf(string, "txf%d_filter_vlan", f_num);
ethtool_sprintf(string, "txf%d_filter_mac_sa", f_num);
}
static void bnad_get_rxf_strings(u8 **string, int f_num)
{
ethtool_sprintf(string, "rxf%d_ucast_octets", f_num);
ethtool_sprintf(string, "rxf%d_ucast", f_num);
ethtool_sprintf(string, "rxf%d_ucast_vlan", f_num);
ethtool_sprintf(string, "rxf%d_mcast_octets", f_num);
ethtool_sprintf(string, "rxf%d_mcast", f_num);
ethtool_sprintf(string, "rxf%d_mcast_vlan", f_num);
ethtool_sprintf(string, "rxf%d_bcast_octets", f_num);
ethtool_sprintf(string, "rxf%d_bcast", f_num);
ethtool_sprintf(string, "rxf%d_bcast_vlan", f_num);
ethtool_sprintf(string, "rxf%d_frame_drops", f_num);
}
static void bnad_get_cq_strings(u8 **string, int q_num)
{
ethtool_sprintf(string, "cq%d_producer_index", q_num);
ethtool_sprintf(string, "cq%d_consumer_index", q_num);
ethtool_sprintf(string, "cq%d_hw_producer_index", q_num);
ethtool_sprintf(string, "cq%d_intr", q_num);
ethtool_sprintf(string, "cq%d_poll", q_num);
ethtool_sprintf(string, "cq%d_schedule", q_num);
ethtool_sprintf(string, "cq%d_keep_poll", q_num);
ethtool_sprintf(string, "cq%d_complete", q_num);
}
static void bnad_get_rxq_strings(u8 **string, int q_num)
{
ethtool_sprintf(string, "rxq%d_packets", q_num);
ethtool_sprintf(string, "rxq%d_bytes", q_num);
ethtool_sprintf(string, "rxq%d_packets_with_error", q_num);
ethtool_sprintf(string, "rxq%d_allocbuf_failed", q_num);
ethtool_sprintf(string, "rxq%d_mapbuf_failed", q_num);
ethtool_sprintf(string, "rxq%d_producer_index", q_num);
ethtool_sprintf(string, "rxq%d_consumer_index", q_num);
}
static void bnad_get_txq_strings(u8 **string, int q_num)
{
ethtool_sprintf(string, "txq%d_packets", q_num);
ethtool_sprintf(string, "txq%d_bytes", q_num);
ethtool_sprintf(string, "txq%d_producer_index", q_num);
ethtool_sprintf(string, "txq%d_consumer_index", q_num);
ethtool_sprintf(string, "txq%d_hw_consumer_index", q_num);
}
static void
bnad_get_strings(struct net_device *netdev, u32 stringset, u8 *string)
{
struct bnad *bnad = netdev_priv(netdev);
int i, j, q_num;
u32 bmap;
if (stringset != ETH_SS_STATS)
return;
mutex_lock(&bnad->conf_mutex);
for (i = 0; i < BNAD_ETHTOOL_STATS_NUM; i++) {
BUG_ON(!(strlen(bnad_net_stats_strings[i]) < ETH_GSTRING_LEN));
ethtool_sprintf(&string, bnad_net_stats_strings[i]);
}
bmap = bna_tx_rid_mask(&bnad->bna);
for (i = 0; bmap; i++) {
if (bmap & 1)
bnad_get_txf_strings(&string, i);
bmap >>= 1;
}
bmap = bna_rx_rid_mask(&bnad->bna);
for (i = 0; bmap; i++, bmap >>= 1) {
if (bmap & 1)
bnad_get_rxf_strings(&string, i);
bmap >>= 1;
}
q_num = 0;
for (i = 0; i < bnad->num_rx; i++) {
if (!bnad->rx_info[i].rx)
continue;
for (j = 0; j < bnad->num_rxp_per_rx; j++)
bnad_get_cq_strings(&string, q_num++);
}
q_num = 0;
for (i = 0; i < bnad->num_rx; i++) {
if (!bnad->rx_info[i].rx)
continue;
for (j = 0; j < bnad->num_rxp_per_rx; j++) {
bnad_get_rxq_strings(&string, q_num++);
if (bnad->rx_info[i].rx_ctrl[j].ccb &&
bnad->rx_info[i].rx_ctrl[j].ccb->rcb[1] &&
bnad->rx_info[i].rx_ctrl[j].ccb->rcb[1]->rxq)
bnad_get_rxq_strings(&string, q_num++);
}
}
q_num = 0;
for (i = 0; i < bnad->num_tx; i++) {
if (!bnad->tx_info[i].tx)
continue;
for (j = 0; j < bnad->num_txq_per_tx; j++)
bnad_get_txq_strings(&string, q_num++);
}
mutex_unlock(&bnad->conf_mutex);
}
static int
bnad_get_stats_count_locked(struct net_device *netdev)
{
struct bnad *bnad = netdev_priv(netdev);
int i, j, count = 0, rxf_active_num = 0, txf_active_num = 0;
u32 bmap;
bmap = bna_tx_rid_mask(&bnad->bna);
for (i = 0; bmap; i++) {
if (bmap & 1)
txf_active_num++;
bmap >>= 1;
}
bmap = bna_rx_rid_mask(&bnad->bna);
for (i = 0; bmap; i++) {
if (bmap & 1)
rxf_active_num++;
bmap >>= 1;
}
count = BNAD_ETHTOOL_STATS_NUM +
txf_active_num * BNAD_NUM_TXF_COUNTERS +
rxf_active_num * BNAD_NUM_RXF_COUNTERS;
for (i = 0; i < bnad->num_rx; i++) {
if (!bnad->rx_info[i].rx)
continue;
count += bnad->num_rxp_per_rx * BNAD_NUM_CQ_COUNTERS;
count += bnad->num_rxp_per_rx * BNAD_NUM_RXQ_COUNTERS;
for (j = 0; j < bnad->num_rxp_per_rx; j++)
if (bnad->rx_info[i].rx_ctrl[j].ccb &&
bnad->rx_info[i].rx_ctrl[j].ccb->rcb[1] &&
bnad->rx_info[i].rx_ctrl[j].ccb->rcb[1]->rxq)
count += BNAD_NUM_RXQ_COUNTERS;
}
for (i = 0; i < bnad->num_tx; i++) {
if (!bnad->tx_info[i].tx)
continue;
count += bnad->num_txq_per_tx * BNAD_NUM_TXQ_COUNTERS;
}
return count;
}
static int
bnad_per_q_stats_fill(struct bnad *bnad, u64 *buf, int bi)
{
int i, j;
struct bna_rcb *rcb = NULL;
struct bna_tcb *tcb = NULL;
for (i = 0; i < bnad->num_rx; i++) {
if (!bnad->rx_info[i].rx)
continue;
for (j = 0; j < bnad->num_rxp_per_rx; j++)
if (bnad->rx_info[i].rx_ctrl[j].ccb &&
bnad->rx_info[i].rx_ctrl[j].ccb->rcb[0] &&
bnad->rx_info[i].rx_ctrl[j].ccb->rcb[0]->rxq) {
buf[bi++] = bnad->rx_info[i].rx_ctrl[j].
ccb->producer_index;
buf[bi++] = 0; /* ccb->consumer_index */
buf[bi++] = *(bnad->rx_info[i].rx_ctrl[j].
ccb->hw_producer_index);
buf[bi++] = bnad->rx_info[i].
rx_ctrl[j].rx_intr_ctr;
buf[bi++] = bnad->rx_info[i].
rx_ctrl[j].rx_poll_ctr;
buf[bi++] = bnad->rx_info[i].
rx_ctrl[j].rx_schedule;
buf[bi++] = bnad->rx_info[i].
rx_ctrl[j].rx_keep_poll;
buf[bi++] = bnad->rx_info[i].
rx_ctrl[j].rx_complete;
}
}
for (i = 0; i < bnad->num_rx; i++) {
if (!bnad->rx_info[i].rx)
continue;
for (j = 0; j < bnad->num_rxp_per_rx; j++)
if (bnad->rx_info[i].rx_ctrl[j].ccb) {
if (bnad->rx_info[i].rx_ctrl[j].ccb->rcb[0] &&
bnad->rx_info[i].rx_ctrl[j].ccb->
rcb[0]->rxq) {
rcb = bnad->rx_info[i].rx_ctrl[j].
ccb->rcb[0];
buf[bi++] = rcb->rxq->rx_packets;
buf[bi++] = rcb->rxq->rx_bytes;
buf[bi++] = rcb->rxq->
rx_packets_with_error;
buf[bi++] = rcb->rxq->
rxbuf_alloc_failed;
buf[bi++] = rcb->rxq->rxbuf_map_failed;
buf[bi++] = rcb->producer_index;
buf[bi++] = rcb->consumer_index;
}
if (bnad->rx_info[i].rx_ctrl[j].ccb->rcb[1] &&
bnad->rx_info[i].rx_ctrl[j].ccb->
rcb[1]->rxq) {
rcb = bnad->rx_info[i].rx_ctrl[j].
ccb->rcb[1];
buf[bi++] = rcb->rxq->rx_packets;
buf[bi++] = rcb->rxq->rx_bytes;
buf[bi++] = rcb->rxq->
rx_packets_with_error;
buf[bi++] = rcb->rxq->
rxbuf_alloc_failed;
buf[bi++] = rcb->rxq->rxbuf_map_failed;
buf[bi++] = rcb->producer_index;
buf[bi++] = rcb->consumer_index;
}
}
}
for (i = 0; i < bnad->num_tx; i++) {
if (!bnad->tx_info[i].tx)
continue;
for (j = 0; j < bnad->num_txq_per_tx; j++)
if (bnad->tx_info[i].tcb[j] &&
bnad->tx_info[i].tcb[j]->txq) {
tcb = bnad->tx_info[i].tcb[j];
buf[bi++] = tcb->txq->tx_packets;
buf[bi++] = tcb->txq->tx_bytes;
buf[bi++] = tcb->producer_index;
buf[bi++] = tcb->consumer_index;
buf[bi++] = *(tcb->hw_consumer_index);
}
}
return bi;
}
static void
bnad_get_ethtool_stats(struct net_device *netdev, struct ethtool_stats *stats,
u64 *buf)
{
struct bnad *bnad = netdev_priv(netdev);
int i, j, bi = 0;
unsigned long flags;
struct rtnl_link_stats64 net_stats64;
u64 *stats64;
u32 bmap;
mutex_lock(&bnad->conf_mutex);
if (bnad_get_stats_count_locked(netdev) != stats->n_stats) {
mutex_unlock(&bnad->conf_mutex);
return;
}
/*
* Used bna_lock to sync reads from bna_stats, which is written
* under the same lock
*/
spin_lock_irqsave(&bnad->bna_lock, flags);
memset(&net_stats64, 0, sizeof(net_stats64));
bnad_netdev_qstats_fill(bnad, &net_stats64);
bnad_netdev_hwstats_fill(bnad, &net_stats64);
buf[bi++] = net_stats64.rx_packets;
buf[bi++] = net_stats64.tx_packets;
buf[bi++] = net_stats64.rx_bytes;
buf[bi++] = net_stats64.tx_bytes;
buf[bi++] = net_stats64.rx_errors;
buf[bi++] = net_stats64.tx_errors;
buf[bi++] = net_stats64.rx_dropped;
buf[bi++] = net_stats64.tx_dropped;
buf[bi++] = net_stats64.multicast;
buf[bi++] = net_stats64.collisions;
buf[bi++] = net_stats64.rx_length_errors;
buf[bi++] = net_stats64.rx_crc_errors;
buf[bi++] = net_stats64.rx_frame_errors;
buf[bi++] = net_stats64.tx_fifo_errors;
/* Get netif_queue_stopped from stack */
bnad->stats.drv_stats.netif_queue_stopped = netif_queue_stopped(netdev);
/* Fill driver stats into ethtool buffers */
stats64 = (u64 *)&bnad->stats.drv_stats;
for (i = 0; i < sizeof(struct bnad_drv_stats) / sizeof(u64); i++)
buf[bi++] = stats64[i];
/* Fill hardware stats excluding the rxf/txf into ethtool bufs */
stats64 = (u64 *) &bnad->stats.bna_stats->hw_stats;
for (i = 0;
i < offsetof(struct bfi_enet_stats, rxf_stats[0]) /
sizeof(u64);
i++)
buf[bi++] = stats64[i];
/* Fill txf stats into ethtool buffers */
bmap = bna_tx_rid_mask(&bnad->bna);
for (i = 0; bmap; i++) {
if (bmap & 1) {
stats64 = (u64 *)&bnad->stats.bna_stats->
hw_stats.txf_stats[i];
for (j = 0; j < sizeof(struct bfi_enet_stats_txf) /
sizeof(u64); j++)
buf[bi++] = stats64[j];
}
bmap >>= 1;
}
/* Fill rxf stats into ethtool buffers */
bmap = bna_rx_rid_mask(&bnad->bna);
for (i = 0; bmap; i++) {
if (bmap & 1) {
stats64 = (u64 *)&bnad->stats.bna_stats->
hw_stats.rxf_stats[i];
for (j = 0; j < sizeof(struct bfi_enet_stats_rxf) /
sizeof(u64); j++)
buf[bi++] = stats64[j];
}
bmap >>= 1;
}
/* Fill per Q stats into ethtool buffers */
bi = bnad_per_q_stats_fill(bnad, buf, bi);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
mutex_unlock(&bnad->conf_mutex);
}
static int
bnad_get_sset_count(struct net_device *netdev, int sset)
{
switch (sset) {
case ETH_SS_STATS:
return bnad_get_stats_count_locked(netdev);
default:
return -EOPNOTSUPP;
}
}
static u32
bnad_get_flash_partition_by_offset(struct bnad *bnad, u32 offset,
u32 *base_offset)
{
struct bfa_flash_attr *flash_attr;
struct bnad_iocmd_comp fcomp;
u32 i, flash_part = 0, ret;
unsigned long flags = 0;
flash_attr = kzalloc(sizeof(struct bfa_flash_attr), GFP_KERNEL);
if (!flash_attr)
return 0;
fcomp.bnad = bnad;
fcomp.comp_status = 0;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bnad->bna_lock, flags);
ret = bfa_nw_flash_get_attr(&bnad->bna.flash, flash_attr,
bnad_cb_completion, &fcomp);
if (ret != BFA_STATUS_OK) {
spin_unlock_irqrestore(&bnad->bna_lock, flags);
kfree(flash_attr);
return 0;
}
spin_unlock_irqrestore(&bnad->bna_lock, flags);
wait_for_completion(&fcomp.comp);
ret = fcomp.comp_status;
/* Check for the flash type & base offset value */
if (ret == BFA_STATUS_OK) {
for (i = 0; i < flash_attr->npart; i++) {
if (offset >= flash_attr->part[i].part_off &&
offset < (flash_attr->part[i].part_off +
flash_attr->part[i].part_size)) {
flash_part = flash_attr->part[i].part_type;
*base_offset = flash_attr->part[i].part_off;
break;
}
}
}
kfree(flash_attr);
return flash_part;
}
static int
bnad_get_eeprom_len(struct net_device *netdev)
{
return BFA_TOTAL_FLASH_SIZE;
}
static int
bnad_get_eeprom(struct net_device *netdev, struct ethtool_eeprom *eeprom,
u8 *bytes)
{
struct bnad *bnad = netdev_priv(netdev);
struct bnad_iocmd_comp fcomp;
u32 flash_part = 0, base_offset = 0;
unsigned long flags = 0;
int ret = 0;
/* Fill the magic value */
eeprom->magic = bnad->pcidev->vendor | (bnad->pcidev->device << 16);
/* Query the flash partition based on the offset */
flash_part = bnad_get_flash_partition_by_offset(bnad,
eeprom->offset, &base_offset);
if (flash_part == 0)
return -EFAULT;
fcomp.bnad = bnad;
fcomp.comp_status = 0;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bnad->bna_lock, flags);
ret = bfa_nw_flash_read_part(&bnad->bna.flash, flash_part,
bnad->id, bytes, eeprom->len,
eeprom->offset - base_offset,
bnad_cb_completion, &fcomp);
if (ret != BFA_STATUS_OK) {
spin_unlock_irqrestore(&bnad->bna_lock, flags);
goto done;
}
spin_unlock_irqrestore(&bnad->bna_lock, flags);
wait_for_completion(&fcomp.comp);
ret = fcomp.comp_status;
done:
return ret;
}
static int
bnad_set_eeprom(struct net_device *netdev, struct ethtool_eeprom *eeprom,
u8 *bytes)
{
struct bnad *bnad = netdev_priv(netdev);
struct bnad_iocmd_comp fcomp;
u32 flash_part = 0, base_offset = 0;
unsigned long flags = 0;
int ret = 0;
/* Check if the flash update request is valid */
if (eeprom->magic != (bnad->pcidev->vendor |
(bnad->pcidev->device << 16)))
return -EINVAL;
/* Query the flash partition based on the offset */
flash_part = bnad_get_flash_partition_by_offset(bnad,
eeprom->offset, &base_offset);
if (flash_part == 0)
return -EFAULT;
fcomp.bnad = bnad;
fcomp.comp_status = 0;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bnad->bna_lock, flags);
ret = bfa_nw_flash_update_part(&bnad->bna.flash, flash_part,
bnad->id, bytes, eeprom->len,
eeprom->offset - base_offset,
bnad_cb_completion, &fcomp);
if (ret != BFA_STATUS_OK) {
spin_unlock_irqrestore(&bnad->bna_lock, flags);
goto done;
}
spin_unlock_irqrestore(&bnad->bna_lock, flags);
wait_for_completion(&fcomp.comp);
ret = fcomp.comp_status;
done:
return ret;
}
static int
bnad_flash_device(struct net_device *netdev, struct ethtool_flash *eflash)
{
struct bnad *bnad = netdev_priv(netdev);
struct bnad_iocmd_comp fcomp;
const struct firmware *fw;
int ret = 0;
ret = request_firmware(&fw, eflash->data, &bnad->pcidev->dev);
if (ret) {
netdev_err(netdev, "can't load firmware %s\n", eflash->data);
goto out;
}
fcomp.bnad = bnad;
fcomp.comp_status = 0;
init_completion(&fcomp.comp);
spin_lock_irq(&bnad->bna_lock);
ret = bfa_nw_flash_update_part(&bnad->bna.flash, BFA_FLASH_PART_FWIMG,
bnad->id, (u8 *)fw->data, fw->size, 0,
bnad_cb_completion, &fcomp);
if (ret != BFA_STATUS_OK) {
netdev_warn(netdev, "flash update failed with err=%d\n", ret);
ret = -EIO;
spin_unlock_irq(&bnad->bna_lock);
goto out;
}
spin_unlock_irq(&bnad->bna_lock);
wait_for_completion(&fcomp.comp);
if (fcomp.comp_status != BFA_STATUS_OK) {
ret = -EIO;
netdev_warn(netdev,
"firmware image update failed with err=%d\n",
fcomp.comp_status);
}
out:
release_firmware(fw);
return ret;
}
static const struct ethtool_ops bnad_ethtool_ops = {
.supported_coalesce_params = ETHTOOL_COALESCE_USECS |
ETHTOOL_COALESCE_TX_MAX_FRAMES |
ETHTOOL_COALESCE_USE_ADAPTIVE_RX,
.get_drvinfo = bnad_get_drvinfo,
.get_wol = bnad_get_wol,
.get_link = ethtool_op_get_link,
.get_coalesce = bnad_get_coalesce,
.set_coalesce = bnad_set_coalesce,
.get_ringparam = bnad_get_ringparam,
.set_ringparam = bnad_set_ringparam,
.get_pauseparam = bnad_get_pauseparam,
.set_pauseparam = bnad_set_pauseparam,
.get_strings = bnad_get_strings,
.get_ethtool_stats = bnad_get_ethtool_stats,
.get_sset_count = bnad_get_sset_count,
.get_eeprom_len = bnad_get_eeprom_len,
.get_eeprom = bnad_get_eeprom,
.set_eeprom = bnad_set_eeprom,
.flash_device = bnad_flash_device,
.get_ts_info = ethtool_op_get_ts_info,
.get_link_ksettings = bnad_get_link_ksettings,
.set_link_ksettings = bnad_set_link_ksettings,
};
void
bnad_set_ethtool_ops(struct net_device *netdev)
{
netdev->ethtool_ops = &bnad_ethtool_ops;
}
|
linux-master
|
drivers/net/ethernet/brocade/bna/bnad_ethtool.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Linux network driver for QLogic BR-series Converged Network Adapter.
*/
/*
* Copyright (c) 2005-2014 Brocade Communications Systems, Inc.
* Copyright (c) 2014-2015 QLogic Corporation
* All rights reserved
* www.qlogic.com
*/
#include <linux/debugfs.h>
#include <linux/module.h>
#include "bnad.h"
/*
* BNA debufs interface
*
* To access the interface, debugfs file system should be mounted
* if not already mounted using:
* mount -t debugfs none /sys/kernel/debug
*
* BNA Hierarchy:
* - bna/pci_dev:<pci_name>
* where the pci_name corresponds to the one under /sys/bus/pci/drivers/bna
*
* Debugging service available per pci_dev:
* fwtrc: To collect current firmware trace.
* fwsave: To collect last saved fw trace as a result of firmware crash.
* regwr: To write one word to chip register
* regrd: To read one or more words from chip register.
*/
struct bnad_debug_info {
char *debug_buffer;
void *i_private;
int buffer_len;
};
static int
bnad_debugfs_open_fwtrc(struct inode *inode, struct file *file)
{
struct bnad *bnad = inode->i_private;
struct bnad_debug_info *fw_debug;
unsigned long flags;
int rc;
fw_debug = kzalloc(sizeof(struct bnad_debug_info), GFP_KERNEL);
if (!fw_debug)
return -ENOMEM;
fw_debug->buffer_len = BNA_DBG_FWTRC_LEN;
fw_debug->debug_buffer = kzalloc(fw_debug->buffer_len, GFP_KERNEL);
if (!fw_debug->debug_buffer) {
kfree(fw_debug);
fw_debug = NULL;
return -ENOMEM;
}
spin_lock_irqsave(&bnad->bna_lock, flags);
rc = bfa_nw_ioc_debug_fwtrc(&bnad->bna.ioceth.ioc,
fw_debug->debug_buffer,
&fw_debug->buffer_len);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
if (rc != BFA_STATUS_OK) {
kfree(fw_debug->debug_buffer);
fw_debug->debug_buffer = NULL;
kfree(fw_debug);
fw_debug = NULL;
netdev_warn(bnad->netdev, "failed to collect fwtrc\n");
return -ENOMEM;
}
file->private_data = fw_debug;
return 0;
}
static int
bnad_debugfs_open_fwsave(struct inode *inode, struct file *file)
{
struct bnad *bnad = inode->i_private;
struct bnad_debug_info *fw_debug;
unsigned long flags;
int rc;
fw_debug = kzalloc(sizeof(struct bnad_debug_info), GFP_KERNEL);
if (!fw_debug)
return -ENOMEM;
fw_debug->buffer_len = BNA_DBG_FWTRC_LEN;
fw_debug->debug_buffer = kzalloc(fw_debug->buffer_len, GFP_KERNEL);
if (!fw_debug->debug_buffer) {
kfree(fw_debug);
fw_debug = NULL;
return -ENOMEM;
}
spin_lock_irqsave(&bnad->bna_lock, flags);
rc = bfa_nw_ioc_debug_fwsave(&bnad->bna.ioceth.ioc,
fw_debug->debug_buffer,
&fw_debug->buffer_len);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
if (rc != BFA_STATUS_OK && rc != BFA_STATUS_ENOFSAVE) {
kfree(fw_debug->debug_buffer);
fw_debug->debug_buffer = NULL;
kfree(fw_debug);
fw_debug = NULL;
netdev_warn(bnad->netdev, "failed to collect fwsave\n");
return -ENOMEM;
}
file->private_data = fw_debug;
return 0;
}
static int
bnad_debugfs_open_reg(struct inode *inode, struct file *file)
{
struct bnad_debug_info *reg_debug;
reg_debug = kzalloc(sizeof(struct bnad_debug_info), GFP_KERNEL);
if (!reg_debug)
return -ENOMEM;
reg_debug->i_private = inode->i_private;
file->private_data = reg_debug;
return 0;
}
static int
bnad_get_debug_drvinfo(struct bnad *bnad, void *buffer, u32 len)
{
struct bnad_drvinfo *drvinfo = (struct bnad_drvinfo *) buffer;
struct bnad_iocmd_comp fcomp;
unsigned long flags = 0;
int ret = BFA_STATUS_FAILED;
/* Get IOC info */
spin_lock_irqsave(&bnad->bna_lock, flags);
bfa_nw_ioc_get_attr(&bnad->bna.ioceth.ioc, &drvinfo->ioc_attr);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
/* Retrieve CEE related info */
fcomp.bnad = bnad;
fcomp.comp_status = 0;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bnad->bna_lock, flags);
ret = bfa_nw_cee_get_attr(&bnad->bna.cee, &drvinfo->cee_attr,
bnad_cb_completion, &fcomp);
if (ret != BFA_STATUS_OK) {
spin_unlock_irqrestore(&bnad->bna_lock, flags);
goto out;
}
spin_unlock_irqrestore(&bnad->bna_lock, flags);
wait_for_completion(&fcomp.comp);
drvinfo->cee_status = fcomp.comp_status;
/* Retrieve flash partition info */
fcomp.comp_status = 0;
reinit_completion(&fcomp.comp);
spin_lock_irqsave(&bnad->bna_lock, flags);
ret = bfa_nw_flash_get_attr(&bnad->bna.flash, &drvinfo->flash_attr,
bnad_cb_completion, &fcomp);
if (ret != BFA_STATUS_OK) {
spin_unlock_irqrestore(&bnad->bna_lock, flags);
goto out;
}
spin_unlock_irqrestore(&bnad->bna_lock, flags);
wait_for_completion(&fcomp.comp);
drvinfo->flash_status = fcomp.comp_status;
out:
return ret;
}
static int
bnad_debugfs_open_drvinfo(struct inode *inode, struct file *file)
{
struct bnad *bnad = inode->i_private;
struct bnad_debug_info *drv_info;
int rc;
drv_info = kzalloc(sizeof(struct bnad_debug_info), GFP_KERNEL);
if (!drv_info)
return -ENOMEM;
drv_info->buffer_len = sizeof(struct bnad_drvinfo);
drv_info->debug_buffer = kzalloc(drv_info->buffer_len, GFP_KERNEL);
if (!drv_info->debug_buffer) {
kfree(drv_info);
drv_info = NULL;
return -ENOMEM;
}
mutex_lock(&bnad->conf_mutex);
rc = bnad_get_debug_drvinfo(bnad, drv_info->debug_buffer,
drv_info->buffer_len);
mutex_unlock(&bnad->conf_mutex);
if (rc != BFA_STATUS_OK) {
kfree(drv_info->debug_buffer);
drv_info->debug_buffer = NULL;
kfree(drv_info);
drv_info = NULL;
netdev_warn(bnad->netdev, "failed to collect drvinfo\n");
return -ENOMEM;
}
file->private_data = drv_info;
return 0;
}
/* Changes the current file position */
static loff_t
bnad_debugfs_lseek(struct file *file, loff_t offset, int orig)
{
struct bnad_debug_info *debug = file->private_data;
if (!debug)
return -EINVAL;
return fixed_size_llseek(file, offset, orig, debug->buffer_len);
}
static ssize_t
bnad_debugfs_read(struct file *file, char __user *buf,
size_t nbytes, loff_t *pos)
{
struct bnad_debug_info *debug = file->private_data;
if (!debug || !debug->debug_buffer)
return 0;
return simple_read_from_buffer(buf, nbytes, pos,
debug->debug_buffer, debug->buffer_len);
}
#define BFA_REG_CT_ADDRSZ (0x40000)
#define BFA_REG_CB_ADDRSZ (0x20000)
#define BFA_REG_ADDRSZ(__ioc) \
((u32)(bfa_asic_id_ctc(bfa_ioc_devid(__ioc)) ? \
BFA_REG_CT_ADDRSZ : BFA_REG_CB_ADDRSZ))
#define BFA_REG_ADDRMSK(__ioc) (BFA_REG_ADDRSZ(__ioc) - 1)
/*
* Function to check if the register offset passed is valid.
*/
static int
bna_reg_offset_check(struct bfa_ioc *ioc, u32 offset, u32 len)
{
u8 area;
/* check [16:15] */
area = (offset >> 15) & 0x7;
if (area == 0) {
/* PCIe core register */
if (offset + (len << 2) > 0x8000) /* 8k dwords or 32KB */
return BFA_STATUS_EINVAL;
} else if (area == 0x1) {
/* CB 32 KB memory page */
if (offset + (len << 2) > 0x10000) /* 8k dwords or 32KB */
return BFA_STATUS_EINVAL;
} else {
/* CB register space 64KB */
if (offset + (len << 2) > BFA_REG_ADDRMSK(ioc))
return BFA_STATUS_EINVAL;
}
return BFA_STATUS_OK;
}
static ssize_t
bnad_debugfs_read_regrd(struct file *file, char __user *buf,
size_t nbytes, loff_t *pos)
{
struct bnad_debug_info *regrd_debug = file->private_data;
struct bnad *bnad = (struct bnad *)regrd_debug->i_private;
ssize_t rc;
if (!bnad->regdata)
return 0;
rc = simple_read_from_buffer(buf, nbytes, pos,
bnad->regdata, bnad->reglen);
if ((*pos + nbytes) >= bnad->reglen) {
kfree(bnad->regdata);
bnad->regdata = NULL;
bnad->reglen = 0;
}
return rc;
}
static ssize_t
bnad_debugfs_write_regrd(struct file *file, const char __user *buf,
size_t nbytes, loff_t *ppos)
{
struct bnad_debug_info *regrd_debug = file->private_data;
struct bnad *bnad = (struct bnad *)regrd_debug->i_private;
struct bfa_ioc *ioc = &bnad->bna.ioceth.ioc;
int rc, i;
u32 addr, len;
u32 *regbuf;
void __iomem *rb, *reg_addr;
unsigned long flags;
void *kern_buf;
/* Copy the user space buf */
kern_buf = memdup_user(buf, nbytes);
if (IS_ERR(kern_buf))
return PTR_ERR(kern_buf);
rc = sscanf(kern_buf, "%x:%x", &addr, &len);
if (rc < 2 || len > UINT_MAX >> 2) {
netdev_warn(bnad->netdev, "failed to read user buffer\n");
kfree(kern_buf);
return -EINVAL;
}
kfree(kern_buf);
kfree(bnad->regdata);
bnad->reglen = 0;
bnad->regdata = kzalloc(len << 2, GFP_KERNEL);
if (!bnad->regdata)
return -ENOMEM;
bnad->reglen = len << 2;
rb = bfa_ioc_bar0(ioc);
addr &= BFA_REG_ADDRMSK(ioc);
/* offset and len sanity check */
rc = bna_reg_offset_check(ioc, addr, len);
if (rc) {
netdev_warn(bnad->netdev, "failed reg offset check\n");
kfree(bnad->regdata);
bnad->regdata = NULL;
bnad->reglen = 0;
return -EINVAL;
}
reg_addr = rb + addr;
regbuf = (u32 *)bnad->regdata;
spin_lock_irqsave(&bnad->bna_lock, flags);
for (i = 0; i < len; i++) {
*regbuf = readl(reg_addr);
regbuf++;
reg_addr += sizeof(u32);
}
spin_unlock_irqrestore(&bnad->bna_lock, flags);
return nbytes;
}
static ssize_t
bnad_debugfs_write_regwr(struct file *file, const char __user *buf,
size_t nbytes, loff_t *ppos)
{
struct bnad_debug_info *debug = file->private_data;
struct bnad *bnad = (struct bnad *)debug->i_private;
struct bfa_ioc *ioc = &bnad->bna.ioceth.ioc;
int rc;
u32 addr, val;
void __iomem *reg_addr;
unsigned long flags;
void *kern_buf;
/* Copy the user space buf */
kern_buf = memdup_user(buf, nbytes);
if (IS_ERR(kern_buf))
return PTR_ERR(kern_buf);
rc = sscanf(kern_buf, "%x:%x", &addr, &val);
if (rc < 2) {
netdev_warn(bnad->netdev, "failed to read user buffer\n");
kfree(kern_buf);
return -EINVAL;
}
kfree(kern_buf);
addr &= BFA_REG_ADDRMSK(ioc); /* offset only 17 bit and word align */
/* offset and len sanity check */
rc = bna_reg_offset_check(ioc, addr, 1);
if (rc) {
netdev_warn(bnad->netdev, "failed reg offset check\n");
return -EINVAL;
}
reg_addr = (bfa_ioc_bar0(ioc)) + addr;
spin_lock_irqsave(&bnad->bna_lock, flags);
writel(val, reg_addr);
spin_unlock_irqrestore(&bnad->bna_lock, flags);
return nbytes;
}
static int
bnad_debugfs_release(struct inode *inode, struct file *file)
{
struct bnad_debug_info *debug = file->private_data;
if (!debug)
return 0;
file->private_data = NULL;
kfree(debug);
return 0;
}
static int
bnad_debugfs_buffer_release(struct inode *inode, struct file *file)
{
struct bnad_debug_info *debug = file->private_data;
if (!debug)
return 0;
kfree(debug->debug_buffer);
file->private_data = NULL;
kfree(debug);
debug = NULL;
return 0;
}
static const struct file_operations bnad_debugfs_op_fwtrc = {
.owner = THIS_MODULE,
.open = bnad_debugfs_open_fwtrc,
.llseek = bnad_debugfs_lseek,
.read = bnad_debugfs_read,
.release = bnad_debugfs_buffer_release,
};
static const struct file_operations bnad_debugfs_op_fwsave = {
.owner = THIS_MODULE,
.open = bnad_debugfs_open_fwsave,
.llseek = bnad_debugfs_lseek,
.read = bnad_debugfs_read,
.release = bnad_debugfs_buffer_release,
};
static const struct file_operations bnad_debugfs_op_regrd = {
.owner = THIS_MODULE,
.open = bnad_debugfs_open_reg,
.llseek = bnad_debugfs_lseek,
.read = bnad_debugfs_read_regrd,
.write = bnad_debugfs_write_regrd,
.release = bnad_debugfs_release,
};
static const struct file_operations bnad_debugfs_op_regwr = {
.owner = THIS_MODULE,
.open = bnad_debugfs_open_reg,
.llseek = bnad_debugfs_lseek,
.write = bnad_debugfs_write_regwr,
.release = bnad_debugfs_release,
};
static const struct file_operations bnad_debugfs_op_drvinfo = {
.owner = THIS_MODULE,
.open = bnad_debugfs_open_drvinfo,
.llseek = bnad_debugfs_lseek,
.read = bnad_debugfs_read,
.release = bnad_debugfs_buffer_release,
};
struct bnad_debugfs_entry {
const char *name;
umode_t mode;
const struct file_operations *fops;
};
static const struct bnad_debugfs_entry bnad_debugfs_files[] = {
{ "fwtrc", S_IFREG | 0444, &bnad_debugfs_op_fwtrc, },
{ "fwsave", S_IFREG | 0444, &bnad_debugfs_op_fwsave, },
{ "regrd", S_IFREG | 0644, &bnad_debugfs_op_regrd, },
{ "regwr", S_IFREG | 0200, &bnad_debugfs_op_regwr, },
{ "drvinfo", S_IFREG | 0444, &bnad_debugfs_op_drvinfo, },
};
static struct dentry *bna_debugfs_root;
static atomic_t bna_debugfs_port_count;
/* Initialize debugfs interface for BNA */
void
bnad_debugfs_init(struct bnad *bnad)
{
const struct bnad_debugfs_entry *file;
char name[64];
int i;
/* Setup the BNA debugfs root directory*/
if (!bna_debugfs_root) {
bna_debugfs_root = debugfs_create_dir("bna", NULL);
atomic_set(&bna_debugfs_port_count, 0);
if (!bna_debugfs_root) {
netdev_warn(bnad->netdev,
"debugfs root dir creation failed\n");
return;
}
}
/* Setup the pci_dev debugfs directory for the port */
snprintf(name, sizeof(name), "pci_dev:%s", pci_name(bnad->pcidev));
if (!bnad->port_debugfs_root) {
bnad->port_debugfs_root =
debugfs_create_dir(name, bna_debugfs_root);
atomic_inc(&bna_debugfs_port_count);
for (i = 0; i < ARRAY_SIZE(bnad_debugfs_files); i++) {
file = &bnad_debugfs_files[i];
bnad->bnad_dentry_files[i] =
debugfs_create_file(file->name,
file->mode,
bnad->port_debugfs_root,
bnad,
file->fops);
if (!bnad->bnad_dentry_files[i]) {
netdev_warn(bnad->netdev,
"create %s entry failed\n",
file->name);
return;
}
}
}
}
/* Uninitialize debugfs interface for BNA */
void
bnad_debugfs_uninit(struct bnad *bnad)
{
int i;
for (i = 0; i < ARRAY_SIZE(bnad_debugfs_files); i++) {
if (bnad->bnad_dentry_files[i]) {
debugfs_remove(bnad->bnad_dentry_files[i]);
bnad->bnad_dentry_files[i] = NULL;
}
}
/* Remove the pci_dev debugfs directory for the port */
if (bnad->port_debugfs_root) {
debugfs_remove(bnad->port_debugfs_root);
bnad->port_debugfs_root = NULL;
atomic_dec(&bna_debugfs_port_count);
}
/* Remove the BNA debugfs root directory */
if (atomic_read(&bna_debugfs_port_count) == 0) {
debugfs_remove(bna_debugfs_root);
bna_debugfs_root = NULL;
}
}
|
linux-master
|
drivers/net/ethernet/brocade/bna/bnad_debugfs.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Linux network driver for QLogic BR-series Converged Network Adapter.
*/
/*
* Copyright (c) 2005-2014 Brocade Communications Systems, Inc.
* Copyright (c) 2014-2015 QLogic Corporation
* All rights reserved
* www.qlogic.com
*/
#include "bna.h"
#include "bfi.h"
/* IB */
static void
bna_ib_coalescing_timeo_set(struct bna_ib *ib, u8 coalescing_timeo)
{
ib->coalescing_timeo = coalescing_timeo;
ib->door_bell.doorbell_ack = BNA_DOORBELL_IB_INT_ACK(
(u32)ib->coalescing_timeo, 0);
}
/* RXF */
#define bna_rxf_vlan_cfg_soft_reset(rxf) \
do { \
(rxf)->vlan_pending_bitmask = (u8)BFI_VLAN_BMASK_ALL; \
(rxf)->vlan_strip_pending = true; \
} while (0)
#define bna_rxf_rss_cfg_soft_reset(rxf) \
do { \
if ((rxf)->rss_status == BNA_STATUS_T_ENABLED) \
(rxf)->rss_pending = (BNA_RSS_F_RIT_PENDING | \
BNA_RSS_F_CFG_PENDING | \
BNA_RSS_F_STATUS_PENDING); \
} while (0)
static int bna_rxf_cfg_apply(struct bna_rxf *rxf);
static void bna_rxf_cfg_reset(struct bna_rxf *rxf);
static int bna_rxf_ucast_cfg_apply(struct bna_rxf *rxf);
static int bna_rxf_promisc_cfg_apply(struct bna_rxf *rxf);
static int bna_rxf_allmulti_cfg_apply(struct bna_rxf *rxf);
static int bna_rxf_vlan_strip_cfg_apply(struct bna_rxf *rxf);
static int bna_rxf_ucast_cfg_reset(struct bna_rxf *rxf,
enum bna_cleanup_type cleanup);
static int bna_rxf_promisc_cfg_reset(struct bna_rxf *rxf,
enum bna_cleanup_type cleanup);
static int bna_rxf_allmulti_cfg_reset(struct bna_rxf *rxf,
enum bna_cleanup_type cleanup);
bfa_fsm_state_decl(bna_rxf, stopped, struct bna_rxf,
enum bna_rxf_event);
bfa_fsm_state_decl(bna_rxf, cfg_wait, struct bna_rxf,
enum bna_rxf_event);
bfa_fsm_state_decl(bna_rxf, started, struct bna_rxf,
enum bna_rxf_event);
bfa_fsm_state_decl(bna_rxf, last_resp_wait, struct bna_rxf,
enum bna_rxf_event);
static void
bna_rxf_sm_stopped_entry(struct bna_rxf *rxf)
{
call_rxf_stop_cbfn(rxf);
}
static void
bna_rxf_sm_stopped(struct bna_rxf *rxf, enum bna_rxf_event event)
{
switch (event) {
case RXF_E_START:
bfa_fsm_set_state(rxf, bna_rxf_sm_cfg_wait);
break;
case RXF_E_STOP:
call_rxf_stop_cbfn(rxf);
break;
case RXF_E_FAIL:
/* No-op */
break;
case RXF_E_CONFIG:
call_rxf_cam_fltr_cbfn(rxf);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_rxf_sm_cfg_wait_entry(struct bna_rxf *rxf)
{
if (!bna_rxf_cfg_apply(rxf)) {
/* No more pending config updates */
bfa_fsm_set_state(rxf, bna_rxf_sm_started);
}
}
static void
bna_rxf_sm_cfg_wait(struct bna_rxf *rxf, enum bna_rxf_event event)
{
switch (event) {
case RXF_E_STOP:
bfa_fsm_set_state(rxf, bna_rxf_sm_last_resp_wait);
break;
case RXF_E_FAIL:
bna_rxf_cfg_reset(rxf);
call_rxf_start_cbfn(rxf);
call_rxf_cam_fltr_cbfn(rxf);
bfa_fsm_set_state(rxf, bna_rxf_sm_stopped);
break;
case RXF_E_CONFIG:
/* No-op */
break;
case RXF_E_FW_RESP:
if (!bna_rxf_cfg_apply(rxf)) {
/* No more pending config updates */
bfa_fsm_set_state(rxf, bna_rxf_sm_started);
}
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_rxf_sm_started_entry(struct bna_rxf *rxf)
{
call_rxf_start_cbfn(rxf);
call_rxf_cam_fltr_cbfn(rxf);
}
static void
bna_rxf_sm_started(struct bna_rxf *rxf, enum bna_rxf_event event)
{
switch (event) {
case RXF_E_STOP:
case RXF_E_FAIL:
bna_rxf_cfg_reset(rxf);
bfa_fsm_set_state(rxf, bna_rxf_sm_stopped);
break;
case RXF_E_CONFIG:
bfa_fsm_set_state(rxf, bna_rxf_sm_cfg_wait);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_rxf_sm_last_resp_wait_entry(struct bna_rxf *rxf)
{
}
static void
bna_rxf_sm_last_resp_wait(struct bna_rxf *rxf, enum bna_rxf_event event)
{
switch (event) {
case RXF_E_FAIL:
case RXF_E_FW_RESP:
bna_rxf_cfg_reset(rxf);
bfa_fsm_set_state(rxf, bna_rxf_sm_stopped);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_bfi_ucast_req(struct bna_rxf *rxf, struct bna_mac *mac,
enum bfi_enet_h2i_msgs req_type)
{
struct bfi_enet_ucast_req *req = &rxf->bfi_enet_cmd.ucast_req;
bfi_msgq_mhdr_set(req->mh, BFI_MC_ENET, req_type, 0, rxf->rx->rid);
req->mh.num_entries = htons(
bfi_msgq_num_cmd_entries(sizeof(struct bfi_enet_ucast_req)));
ether_addr_copy(req->mac_addr, mac->addr);
bfa_msgq_cmd_set(&rxf->msgq_cmd, NULL, NULL,
sizeof(struct bfi_enet_ucast_req), &req->mh);
bfa_msgq_cmd_post(&rxf->rx->bna->msgq, &rxf->msgq_cmd);
}
static void
bna_bfi_mcast_add_req(struct bna_rxf *rxf, struct bna_mac *mac)
{
struct bfi_enet_mcast_add_req *req =
&rxf->bfi_enet_cmd.mcast_add_req;
bfi_msgq_mhdr_set(req->mh, BFI_MC_ENET, BFI_ENET_H2I_MAC_MCAST_ADD_REQ,
0, rxf->rx->rid);
req->mh.num_entries = htons(
bfi_msgq_num_cmd_entries(sizeof(struct bfi_enet_mcast_add_req)));
ether_addr_copy(req->mac_addr, mac->addr);
bfa_msgq_cmd_set(&rxf->msgq_cmd, NULL, NULL,
sizeof(struct bfi_enet_mcast_add_req), &req->mh);
bfa_msgq_cmd_post(&rxf->rx->bna->msgq, &rxf->msgq_cmd);
}
static void
bna_bfi_mcast_del_req(struct bna_rxf *rxf, u16 handle)
{
struct bfi_enet_mcast_del_req *req =
&rxf->bfi_enet_cmd.mcast_del_req;
bfi_msgq_mhdr_set(req->mh, BFI_MC_ENET, BFI_ENET_H2I_MAC_MCAST_DEL_REQ,
0, rxf->rx->rid);
req->mh.num_entries = htons(
bfi_msgq_num_cmd_entries(sizeof(struct bfi_enet_mcast_del_req)));
req->handle = htons(handle);
bfa_msgq_cmd_set(&rxf->msgq_cmd, NULL, NULL,
sizeof(struct bfi_enet_mcast_del_req), &req->mh);
bfa_msgq_cmd_post(&rxf->rx->bna->msgq, &rxf->msgq_cmd);
}
static void
bna_bfi_mcast_filter_req(struct bna_rxf *rxf, enum bna_status status)
{
struct bfi_enet_enable_req *req = &rxf->bfi_enet_cmd.req;
bfi_msgq_mhdr_set(req->mh, BFI_MC_ENET,
BFI_ENET_H2I_MAC_MCAST_FILTER_REQ, 0, rxf->rx->rid);
req->mh.num_entries = htons(
bfi_msgq_num_cmd_entries(sizeof(struct bfi_enet_enable_req)));
req->enable = status;
bfa_msgq_cmd_set(&rxf->msgq_cmd, NULL, NULL,
sizeof(struct bfi_enet_enable_req), &req->mh);
bfa_msgq_cmd_post(&rxf->rx->bna->msgq, &rxf->msgq_cmd);
}
static void
bna_bfi_rx_promisc_req(struct bna_rxf *rxf, enum bna_status status)
{
struct bfi_enet_enable_req *req = &rxf->bfi_enet_cmd.req;
bfi_msgq_mhdr_set(req->mh, BFI_MC_ENET,
BFI_ENET_H2I_RX_PROMISCUOUS_REQ, 0, rxf->rx->rid);
req->mh.num_entries = htons(
bfi_msgq_num_cmd_entries(sizeof(struct bfi_enet_enable_req)));
req->enable = status;
bfa_msgq_cmd_set(&rxf->msgq_cmd, NULL, NULL,
sizeof(struct bfi_enet_enable_req), &req->mh);
bfa_msgq_cmd_post(&rxf->rx->bna->msgq, &rxf->msgq_cmd);
}
static void
bna_bfi_rx_vlan_filter_set(struct bna_rxf *rxf, u8 block_idx)
{
struct bfi_enet_rx_vlan_req *req = &rxf->bfi_enet_cmd.vlan_req;
int i;
int j;
bfi_msgq_mhdr_set(req->mh, BFI_MC_ENET,
BFI_ENET_H2I_RX_VLAN_SET_REQ, 0, rxf->rx->rid);
req->mh.num_entries = htons(
bfi_msgq_num_cmd_entries(sizeof(struct bfi_enet_rx_vlan_req)));
req->block_idx = block_idx;
for (i = 0; i < (BFI_ENET_VLAN_BLOCK_SIZE / 32); i++) {
j = (block_idx * (BFI_ENET_VLAN_BLOCK_SIZE / 32)) + i;
if (rxf->vlan_filter_status == BNA_STATUS_T_ENABLED)
req->bit_mask[i] =
htonl(rxf->vlan_filter_table[j]);
else
req->bit_mask[i] = 0xFFFFFFFF;
}
bfa_msgq_cmd_set(&rxf->msgq_cmd, NULL, NULL,
sizeof(struct bfi_enet_rx_vlan_req), &req->mh);
bfa_msgq_cmd_post(&rxf->rx->bna->msgq, &rxf->msgq_cmd);
}
static void
bna_bfi_vlan_strip_enable(struct bna_rxf *rxf)
{
struct bfi_enet_enable_req *req = &rxf->bfi_enet_cmd.req;
bfi_msgq_mhdr_set(req->mh, BFI_MC_ENET,
BFI_ENET_H2I_RX_VLAN_STRIP_ENABLE_REQ, 0, rxf->rx->rid);
req->mh.num_entries = htons(
bfi_msgq_num_cmd_entries(sizeof(struct bfi_enet_enable_req)));
req->enable = rxf->vlan_strip_status;
bfa_msgq_cmd_set(&rxf->msgq_cmd, NULL, NULL,
sizeof(struct bfi_enet_enable_req), &req->mh);
bfa_msgq_cmd_post(&rxf->rx->bna->msgq, &rxf->msgq_cmd);
}
static void
bna_bfi_rit_cfg(struct bna_rxf *rxf)
{
struct bfi_enet_rit_req *req = &rxf->bfi_enet_cmd.rit_req;
bfi_msgq_mhdr_set(req->mh, BFI_MC_ENET,
BFI_ENET_H2I_RIT_CFG_REQ, 0, rxf->rx->rid);
req->mh.num_entries = htons(
bfi_msgq_num_cmd_entries(sizeof(struct bfi_enet_rit_req)));
req->size = htons(rxf->rit_size);
memcpy(&req->table[0], rxf->rit, rxf->rit_size);
bfa_msgq_cmd_set(&rxf->msgq_cmd, NULL, NULL,
sizeof(struct bfi_enet_rit_req), &req->mh);
bfa_msgq_cmd_post(&rxf->rx->bna->msgq, &rxf->msgq_cmd);
}
static void
bna_bfi_rss_cfg(struct bna_rxf *rxf)
{
struct bfi_enet_rss_cfg_req *req = &rxf->bfi_enet_cmd.rss_req;
int i;
bfi_msgq_mhdr_set(req->mh, BFI_MC_ENET,
BFI_ENET_H2I_RSS_CFG_REQ, 0, rxf->rx->rid);
req->mh.num_entries = htons(
bfi_msgq_num_cmd_entries(sizeof(struct bfi_enet_rss_cfg_req)));
req->cfg.type = rxf->rss_cfg.hash_type;
req->cfg.mask = rxf->rss_cfg.hash_mask;
for (i = 0; i < BFI_ENET_RSS_KEY_LEN; i++)
req->cfg.key[i] =
htonl(rxf->rss_cfg.toeplitz_hash_key[i]);
bfa_msgq_cmd_set(&rxf->msgq_cmd, NULL, NULL,
sizeof(struct bfi_enet_rss_cfg_req), &req->mh);
bfa_msgq_cmd_post(&rxf->rx->bna->msgq, &rxf->msgq_cmd);
}
static void
bna_bfi_rss_enable(struct bna_rxf *rxf)
{
struct bfi_enet_enable_req *req = &rxf->bfi_enet_cmd.req;
bfi_msgq_mhdr_set(req->mh, BFI_MC_ENET,
BFI_ENET_H2I_RSS_ENABLE_REQ, 0, rxf->rx->rid);
req->mh.num_entries = htons(
bfi_msgq_num_cmd_entries(sizeof(struct bfi_enet_enable_req)));
req->enable = rxf->rss_status;
bfa_msgq_cmd_set(&rxf->msgq_cmd, NULL, NULL,
sizeof(struct bfi_enet_enable_req), &req->mh);
bfa_msgq_cmd_post(&rxf->rx->bna->msgq, &rxf->msgq_cmd);
}
/* This function gets the multicast MAC that has already been added to CAM */
static struct bna_mac *
bna_rxf_mcmac_get(struct bna_rxf *rxf, const u8 *mac_addr)
{
struct bna_mac *mac;
list_for_each_entry(mac, &rxf->mcast_active_q, qe)
if (ether_addr_equal(mac->addr, mac_addr))
return mac;
list_for_each_entry(mac, &rxf->mcast_pending_del_q, qe)
if (ether_addr_equal(mac->addr, mac_addr))
return mac;
return NULL;
}
static struct bna_mcam_handle *
bna_rxf_mchandle_get(struct bna_rxf *rxf, int handle)
{
struct bna_mcam_handle *mchandle;
list_for_each_entry(mchandle, &rxf->mcast_handle_q, qe)
if (mchandle->handle == handle)
return mchandle;
return NULL;
}
static void
bna_rxf_mchandle_attach(struct bna_rxf *rxf, u8 *mac_addr, int handle)
{
struct bna_mac *mcmac;
struct bna_mcam_handle *mchandle;
mcmac = bna_rxf_mcmac_get(rxf, mac_addr);
mchandle = bna_rxf_mchandle_get(rxf, handle);
if (mchandle == NULL) {
mchandle = bna_mcam_mod_handle_get(&rxf->rx->bna->mcam_mod);
mchandle->handle = handle;
mchandle->refcnt = 0;
list_add_tail(&mchandle->qe, &rxf->mcast_handle_q);
}
mchandle->refcnt++;
mcmac->handle = mchandle;
}
static int
bna_rxf_mcast_del(struct bna_rxf *rxf, struct bna_mac *mac,
enum bna_cleanup_type cleanup)
{
struct bna_mcam_handle *mchandle;
int ret = 0;
mchandle = mac->handle;
if (mchandle == NULL)
return ret;
mchandle->refcnt--;
if (mchandle->refcnt == 0) {
if (cleanup == BNA_HARD_CLEANUP) {
bna_bfi_mcast_del_req(rxf, mchandle->handle);
ret = 1;
}
list_del(&mchandle->qe);
bna_mcam_mod_handle_put(&rxf->rx->bna->mcam_mod, mchandle);
}
mac->handle = NULL;
return ret;
}
static int
bna_rxf_mcast_cfg_apply(struct bna_rxf *rxf)
{
struct bna_mac *mac = NULL;
int ret;
/* First delete multicast entries to maintain the count */
while (!list_empty(&rxf->mcast_pending_del_q)) {
mac = list_first_entry(&rxf->mcast_pending_del_q,
struct bna_mac, qe);
ret = bna_rxf_mcast_del(rxf, mac, BNA_HARD_CLEANUP);
list_move_tail(&mac->qe, bna_mcam_mod_del_q(rxf->rx->bna));
if (ret)
return ret;
}
/* Add multicast entries */
if (!list_empty(&rxf->mcast_pending_add_q)) {
mac = list_first_entry(&rxf->mcast_pending_add_q,
struct bna_mac, qe);
list_move_tail(&mac->qe, &rxf->mcast_active_q);
bna_bfi_mcast_add_req(rxf, mac);
return 1;
}
return 0;
}
static int
bna_rxf_vlan_cfg_apply(struct bna_rxf *rxf)
{
u8 vlan_pending_bitmask;
int block_idx = 0;
if (rxf->vlan_pending_bitmask) {
vlan_pending_bitmask = rxf->vlan_pending_bitmask;
while (!(vlan_pending_bitmask & 0x1)) {
block_idx++;
vlan_pending_bitmask >>= 1;
}
rxf->vlan_pending_bitmask &= ~BIT(block_idx);
bna_bfi_rx_vlan_filter_set(rxf, block_idx);
return 1;
}
return 0;
}
static int
bna_rxf_mcast_cfg_reset(struct bna_rxf *rxf, enum bna_cleanup_type cleanup)
{
struct bna_mac *mac;
int ret;
/* Throw away delete pending mcast entries */
while (!list_empty(&rxf->mcast_pending_del_q)) {
mac = list_first_entry(&rxf->mcast_pending_del_q,
struct bna_mac, qe);
ret = bna_rxf_mcast_del(rxf, mac, cleanup);
list_move_tail(&mac->qe, bna_mcam_mod_del_q(rxf->rx->bna));
if (ret)
return ret;
}
/* Move active mcast entries to pending_add_q */
while (!list_empty(&rxf->mcast_active_q)) {
mac = list_first_entry(&rxf->mcast_active_q,
struct bna_mac, qe);
list_move_tail(&mac->qe, &rxf->mcast_pending_add_q);
if (bna_rxf_mcast_del(rxf, mac, cleanup))
return 1;
}
return 0;
}
static int
bna_rxf_rss_cfg_apply(struct bna_rxf *rxf)
{
if (rxf->rss_pending) {
if (rxf->rss_pending & BNA_RSS_F_RIT_PENDING) {
rxf->rss_pending &= ~BNA_RSS_F_RIT_PENDING;
bna_bfi_rit_cfg(rxf);
return 1;
}
if (rxf->rss_pending & BNA_RSS_F_CFG_PENDING) {
rxf->rss_pending &= ~BNA_RSS_F_CFG_PENDING;
bna_bfi_rss_cfg(rxf);
return 1;
}
if (rxf->rss_pending & BNA_RSS_F_STATUS_PENDING) {
rxf->rss_pending &= ~BNA_RSS_F_STATUS_PENDING;
bna_bfi_rss_enable(rxf);
return 1;
}
}
return 0;
}
static int
bna_rxf_cfg_apply(struct bna_rxf *rxf)
{
if (bna_rxf_ucast_cfg_apply(rxf))
return 1;
if (bna_rxf_mcast_cfg_apply(rxf))
return 1;
if (bna_rxf_promisc_cfg_apply(rxf))
return 1;
if (bna_rxf_allmulti_cfg_apply(rxf))
return 1;
if (bna_rxf_vlan_cfg_apply(rxf))
return 1;
if (bna_rxf_vlan_strip_cfg_apply(rxf))
return 1;
if (bna_rxf_rss_cfg_apply(rxf))
return 1;
return 0;
}
static void
bna_rxf_cfg_reset(struct bna_rxf *rxf)
{
bna_rxf_ucast_cfg_reset(rxf, BNA_SOFT_CLEANUP);
bna_rxf_mcast_cfg_reset(rxf, BNA_SOFT_CLEANUP);
bna_rxf_promisc_cfg_reset(rxf, BNA_SOFT_CLEANUP);
bna_rxf_allmulti_cfg_reset(rxf, BNA_SOFT_CLEANUP);
bna_rxf_vlan_cfg_soft_reset(rxf);
bna_rxf_rss_cfg_soft_reset(rxf);
}
static void
bna_rit_init(struct bna_rxf *rxf, int rit_size)
{
struct bna_rx *rx = rxf->rx;
struct bna_rxp *rxp;
int offset = 0;
rxf->rit_size = rit_size;
list_for_each_entry(rxp, &rx->rxp_q, qe) {
rxf->rit[offset] = rxp->cq.ccb->id;
offset++;
}
}
void
bna_bfi_rxf_cfg_rsp(struct bna_rxf *rxf, struct bfi_msgq_mhdr *msghdr)
{
bfa_fsm_send_event(rxf, RXF_E_FW_RESP);
}
void
bna_bfi_rxf_ucast_set_rsp(struct bna_rxf *rxf,
struct bfi_msgq_mhdr *msghdr)
{
struct bfi_enet_rsp *rsp =
container_of(msghdr, struct bfi_enet_rsp, mh);
if (rsp->error) {
/* Clear ucast from cache */
rxf->ucast_active_set = 0;
}
bfa_fsm_send_event(rxf, RXF_E_FW_RESP);
}
void
bna_bfi_rxf_mcast_add_rsp(struct bna_rxf *rxf,
struct bfi_msgq_mhdr *msghdr)
{
struct bfi_enet_mcast_add_req *req =
&rxf->bfi_enet_cmd.mcast_add_req;
struct bfi_enet_mcast_add_rsp *rsp =
container_of(msghdr, struct bfi_enet_mcast_add_rsp, mh);
bna_rxf_mchandle_attach(rxf, (u8 *)&req->mac_addr,
ntohs(rsp->handle));
bfa_fsm_send_event(rxf, RXF_E_FW_RESP);
}
static void
bna_rxf_init(struct bna_rxf *rxf,
struct bna_rx *rx,
struct bna_rx_config *q_config,
struct bna_res_info *res_info)
{
rxf->rx = rx;
INIT_LIST_HEAD(&rxf->ucast_pending_add_q);
INIT_LIST_HEAD(&rxf->ucast_pending_del_q);
rxf->ucast_pending_set = 0;
rxf->ucast_active_set = 0;
INIT_LIST_HEAD(&rxf->ucast_active_q);
rxf->ucast_pending_mac = NULL;
INIT_LIST_HEAD(&rxf->mcast_pending_add_q);
INIT_LIST_HEAD(&rxf->mcast_pending_del_q);
INIT_LIST_HEAD(&rxf->mcast_active_q);
INIT_LIST_HEAD(&rxf->mcast_handle_q);
rxf->rit = (u8 *)
res_info[BNA_RX_RES_MEM_T_RIT].res_u.mem_info.mdl[0].kva;
bna_rit_init(rxf, q_config->num_paths);
rxf->rss_status = q_config->rss_status;
if (rxf->rss_status == BNA_STATUS_T_ENABLED) {
rxf->rss_cfg = q_config->rss_config;
rxf->rss_pending |= BNA_RSS_F_CFG_PENDING;
rxf->rss_pending |= BNA_RSS_F_RIT_PENDING;
rxf->rss_pending |= BNA_RSS_F_STATUS_PENDING;
}
rxf->vlan_filter_status = BNA_STATUS_T_DISABLED;
memset(rxf->vlan_filter_table, 0,
(sizeof(u32) * (BFI_ENET_VLAN_ID_MAX / 32)));
rxf->vlan_filter_table[0] |= 1; /* for pure priority tagged frames */
rxf->vlan_pending_bitmask = (u8)BFI_VLAN_BMASK_ALL;
rxf->vlan_strip_status = q_config->vlan_strip_status;
bfa_fsm_set_state(rxf, bna_rxf_sm_stopped);
}
static void
bna_rxf_uninit(struct bna_rxf *rxf)
{
struct bna_mac *mac;
rxf->ucast_pending_set = 0;
rxf->ucast_active_set = 0;
while (!list_empty(&rxf->ucast_pending_add_q)) {
mac = list_first_entry(&rxf->ucast_pending_add_q,
struct bna_mac, qe);
list_move_tail(&mac->qe, bna_ucam_mod_free_q(rxf->rx->bna));
}
if (rxf->ucast_pending_mac) {
list_add_tail(&rxf->ucast_pending_mac->qe,
bna_ucam_mod_free_q(rxf->rx->bna));
rxf->ucast_pending_mac = NULL;
}
while (!list_empty(&rxf->mcast_pending_add_q)) {
mac = list_first_entry(&rxf->mcast_pending_add_q,
struct bna_mac, qe);
list_move_tail(&mac->qe, bna_mcam_mod_free_q(rxf->rx->bna));
}
rxf->rxmode_pending = 0;
rxf->rxmode_pending_bitmask = 0;
if (rxf->rx->bna->promisc_rid == rxf->rx->rid)
rxf->rx->bna->promisc_rid = BFI_INVALID_RID;
if (rxf->rx->bna->default_mode_rid == rxf->rx->rid)
rxf->rx->bna->default_mode_rid = BFI_INVALID_RID;
rxf->rss_pending = 0;
rxf->vlan_strip_pending = false;
rxf->rx = NULL;
}
static void
bna_rx_cb_rxf_started(struct bna_rx *rx)
{
bfa_fsm_send_event(rx, RX_E_RXF_STARTED);
}
static void
bna_rxf_start(struct bna_rxf *rxf)
{
rxf->start_cbfn = bna_rx_cb_rxf_started;
rxf->start_cbarg = rxf->rx;
bfa_fsm_send_event(rxf, RXF_E_START);
}
static void
bna_rx_cb_rxf_stopped(struct bna_rx *rx)
{
bfa_fsm_send_event(rx, RX_E_RXF_STOPPED);
}
static void
bna_rxf_stop(struct bna_rxf *rxf)
{
rxf->stop_cbfn = bna_rx_cb_rxf_stopped;
rxf->stop_cbarg = rxf->rx;
bfa_fsm_send_event(rxf, RXF_E_STOP);
}
static void
bna_rxf_fail(struct bna_rxf *rxf)
{
bfa_fsm_send_event(rxf, RXF_E_FAIL);
}
enum bna_cb_status
bna_rx_ucast_set(struct bna_rx *rx, const u8 *ucmac)
{
struct bna_rxf *rxf = &rx->rxf;
if (rxf->ucast_pending_mac == NULL) {
rxf->ucast_pending_mac =
bna_cam_mod_mac_get(bna_ucam_mod_free_q(rxf->rx->bna));
if (rxf->ucast_pending_mac == NULL)
return BNA_CB_UCAST_CAM_FULL;
}
ether_addr_copy(rxf->ucast_pending_mac->addr, ucmac);
rxf->ucast_pending_set = 1;
rxf->cam_fltr_cbfn = NULL;
rxf->cam_fltr_cbarg = rx->bna->bnad;
bfa_fsm_send_event(rxf, RXF_E_CONFIG);
return BNA_CB_SUCCESS;
}
enum bna_cb_status
bna_rx_mcast_add(struct bna_rx *rx, const u8 *addr,
void (*cbfn)(struct bnad *, struct bna_rx *))
{
struct bna_rxf *rxf = &rx->rxf;
struct bna_mac *mac;
/* Check if already added or pending addition */
if (bna_mac_find(&rxf->mcast_active_q, addr) ||
bna_mac_find(&rxf->mcast_pending_add_q, addr)) {
if (cbfn)
cbfn(rx->bna->bnad, rx);
return BNA_CB_SUCCESS;
}
mac = bna_cam_mod_mac_get(bna_mcam_mod_free_q(rxf->rx->bna));
if (mac == NULL)
return BNA_CB_MCAST_LIST_FULL;
ether_addr_copy(mac->addr, addr);
list_add_tail(&mac->qe, &rxf->mcast_pending_add_q);
rxf->cam_fltr_cbfn = cbfn;
rxf->cam_fltr_cbarg = rx->bna->bnad;
bfa_fsm_send_event(rxf, RXF_E_CONFIG);
return BNA_CB_SUCCESS;
}
enum bna_cb_status
bna_rx_ucast_listset(struct bna_rx *rx, int count, const u8 *uclist)
{
struct bna_ucam_mod *ucam_mod = &rx->bna->ucam_mod;
struct bna_rxf *rxf = &rx->rxf;
struct list_head list_head;
const u8 *mcaddr;
struct bna_mac *mac, *del_mac;
int i;
/* Purge the pending_add_q */
while (!list_empty(&rxf->ucast_pending_add_q)) {
mac = list_first_entry(&rxf->ucast_pending_add_q,
struct bna_mac, qe);
list_move_tail(&mac->qe, &ucam_mod->free_q);
}
/* Schedule active_q entries for deletion */
while (!list_empty(&rxf->ucast_active_q)) {
mac = list_first_entry(&rxf->ucast_active_q,
struct bna_mac, qe);
del_mac = bna_cam_mod_mac_get(&ucam_mod->del_q);
ether_addr_copy(del_mac->addr, mac->addr);
del_mac->handle = mac->handle;
list_add_tail(&del_mac->qe, &rxf->ucast_pending_del_q);
list_move_tail(&mac->qe, &ucam_mod->free_q);
}
/* Allocate nodes */
INIT_LIST_HEAD(&list_head);
for (i = 0, mcaddr = uclist; i < count; i++) {
mac = bna_cam_mod_mac_get(&ucam_mod->free_q);
if (mac == NULL)
goto err_return;
ether_addr_copy(mac->addr, mcaddr);
list_add_tail(&mac->qe, &list_head);
mcaddr += ETH_ALEN;
}
/* Add the new entries */
while (!list_empty(&list_head)) {
mac = list_first_entry(&list_head, struct bna_mac, qe);
list_move_tail(&mac->qe, &rxf->ucast_pending_add_q);
}
bfa_fsm_send_event(rxf, RXF_E_CONFIG);
return BNA_CB_SUCCESS;
err_return:
while (!list_empty(&list_head)) {
mac = list_first_entry(&list_head, struct bna_mac, qe);
list_move_tail(&mac->qe, &ucam_mod->free_q);
}
return BNA_CB_UCAST_CAM_FULL;
}
enum bna_cb_status
bna_rx_mcast_listset(struct bna_rx *rx, int count, const u8 *mclist)
{
struct bna_mcam_mod *mcam_mod = &rx->bna->mcam_mod;
struct bna_rxf *rxf = &rx->rxf;
struct list_head list_head;
const u8 *mcaddr;
struct bna_mac *mac, *del_mac;
int i;
/* Purge the pending_add_q */
while (!list_empty(&rxf->mcast_pending_add_q)) {
mac = list_first_entry(&rxf->mcast_pending_add_q,
struct bna_mac, qe);
list_move_tail(&mac->qe, &mcam_mod->free_q);
}
/* Schedule active_q entries for deletion */
while (!list_empty(&rxf->mcast_active_q)) {
mac = list_first_entry(&rxf->mcast_active_q,
struct bna_mac, qe);
del_mac = bna_cam_mod_mac_get(&mcam_mod->del_q);
ether_addr_copy(del_mac->addr, mac->addr);
del_mac->handle = mac->handle;
list_add_tail(&del_mac->qe, &rxf->mcast_pending_del_q);
mac->handle = NULL;
list_move_tail(&mac->qe, &mcam_mod->free_q);
}
/* Allocate nodes */
INIT_LIST_HEAD(&list_head);
for (i = 0, mcaddr = mclist; i < count; i++) {
mac = bna_cam_mod_mac_get(&mcam_mod->free_q);
if (mac == NULL)
goto err_return;
ether_addr_copy(mac->addr, mcaddr);
list_add_tail(&mac->qe, &list_head);
mcaddr += ETH_ALEN;
}
/* Add the new entries */
while (!list_empty(&list_head)) {
mac = list_first_entry(&list_head, struct bna_mac, qe);
list_move_tail(&mac->qe, &rxf->mcast_pending_add_q);
}
bfa_fsm_send_event(rxf, RXF_E_CONFIG);
return BNA_CB_SUCCESS;
err_return:
while (!list_empty(&list_head)) {
mac = list_first_entry(&list_head, struct bna_mac, qe);
list_move_tail(&mac->qe, &mcam_mod->free_q);
}
return BNA_CB_MCAST_LIST_FULL;
}
void
bna_rx_mcast_delall(struct bna_rx *rx)
{
struct bna_rxf *rxf = &rx->rxf;
struct bna_mac *mac, *del_mac;
int need_hw_config = 0;
/* Purge all entries from pending_add_q */
while (!list_empty(&rxf->mcast_pending_add_q)) {
mac = list_first_entry(&rxf->mcast_pending_add_q,
struct bna_mac, qe);
list_move_tail(&mac->qe, bna_mcam_mod_free_q(rxf->rx->bna));
}
/* Schedule all entries in active_q for deletion */
while (!list_empty(&rxf->mcast_active_q)) {
mac = list_first_entry(&rxf->mcast_active_q,
struct bna_mac, qe);
list_del(&mac->qe);
del_mac = bna_cam_mod_mac_get(bna_mcam_mod_del_q(rxf->rx->bna));
memcpy(del_mac, mac, sizeof(*del_mac));
list_add_tail(&del_mac->qe, &rxf->mcast_pending_del_q);
mac->handle = NULL;
list_add_tail(&mac->qe, bna_mcam_mod_free_q(rxf->rx->bna));
need_hw_config = 1;
}
if (need_hw_config)
bfa_fsm_send_event(rxf, RXF_E_CONFIG);
}
void
bna_rx_vlan_add(struct bna_rx *rx, int vlan_id)
{
struct bna_rxf *rxf = &rx->rxf;
int index = (vlan_id >> BFI_VLAN_WORD_SHIFT);
int bit = BIT(vlan_id & BFI_VLAN_WORD_MASK);
int group_id = (vlan_id >> BFI_VLAN_BLOCK_SHIFT);
rxf->vlan_filter_table[index] |= bit;
if (rxf->vlan_filter_status == BNA_STATUS_T_ENABLED) {
rxf->vlan_pending_bitmask |= BIT(group_id);
bfa_fsm_send_event(rxf, RXF_E_CONFIG);
}
}
void
bna_rx_vlan_del(struct bna_rx *rx, int vlan_id)
{
struct bna_rxf *rxf = &rx->rxf;
int index = (vlan_id >> BFI_VLAN_WORD_SHIFT);
int bit = BIT(vlan_id & BFI_VLAN_WORD_MASK);
int group_id = (vlan_id >> BFI_VLAN_BLOCK_SHIFT);
rxf->vlan_filter_table[index] &= ~bit;
if (rxf->vlan_filter_status == BNA_STATUS_T_ENABLED) {
rxf->vlan_pending_bitmask |= BIT(group_id);
bfa_fsm_send_event(rxf, RXF_E_CONFIG);
}
}
static int
bna_rxf_ucast_cfg_apply(struct bna_rxf *rxf)
{
struct bna_mac *mac = NULL;
/* Delete MAC addresses previousely added */
if (!list_empty(&rxf->ucast_pending_del_q)) {
mac = list_first_entry(&rxf->ucast_pending_del_q,
struct bna_mac, qe);
bna_bfi_ucast_req(rxf, mac, BFI_ENET_H2I_MAC_UCAST_DEL_REQ);
list_move_tail(&mac->qe, bna_ucam_mod_del_q(rxf->rx->bna));
return 1;
}
/* Set default unicast MAC */
if (rxf->ucast_pending_set) {
rxf->ucast_pending_set = 0;
ether_addr_copy(rxf->ucast_active_mac.addr,
rxf->ucast_pending_mac->addr);
rxf->ucast_active_set = 1;
bna_bfi_ucast_req(rxf, &rxf->ucast_active_mac,
BFI_ENET_H2I_MAC_UCAST_SET_REQ);
return 1;
}
/* Add additional MAC entries */
if (!list_empty(&rxf->ucast_pending_add_q)) {
mac = list_first_entry(&rxf->ucast_pending_add_q,
struct bna_mac, qe);
list_move_tail(&mac->qe, &rxf->ucast_active_q);
bna_bfi_ucast_req(rxf, mac, BFI_ENET_H2I_MAC_UCAST_ADD_REQ);
return 1;
}
return 0;
}
static int
bna_rxf_ucast_cfg_reset(struct bna_rxf *rxf, enum bna_cleanup_type cleanup)
{
struct bna_mac *mac;
/* Throw away delete pending ucast entries */
while (!list_empty(&rxf->ucast_pending_del_q)) {
mac = list_first_entry(&rxf->ucast_pending_del_q,
struct bna_mac, qe);
if (cleanup == BNA_SOFT_CLEANUP)
list_move_tail(&mac->qe,
bna_ucam_mod_del_q(rxf->rx->bna));
else {
bna_bfi_ucast_req(rxf, mac,
BFI_ENET_H2I_MAC_UCAST_DEL_REQ);
list_move_tail(&mac->qe,
bna_ucam_mod_del_q(rxf->rx->bna));
return 1;
}
}
/* Move active ucast entries to pending_add_q */
while (!list_empty(&rxf->ucast_active_q)) {
mac = list_first_entry(&rxf->ucast_active_q,
struct bna_mac, qe);
list_move_tail(&mac->qe, &rxf->ucast_pending_add_q);
if (cleanup == BNA_HARD_CLEANUP) {
bna_bfi_ucast_req(rxf, mac,
BFI_ENET_H2I_MAC_UCAST_DEL_REQ);
return 1;
}
}
if (rxf->ucast_active_set) {
rxf->ucast_pending_set = 1;
rxf->ucast_active_set = 0;
if (cleanup == BNA_HARD_CLEANUP) {
bna_bfi_ucast_req(rxf, &rxf->ucast_active_mac,
BFI_ENET_H2I_MAC_UCAST_CLR_REQ);
return 1;
}
}
return 0;
}
static int
bna_rxf_promisc_cfg_apply(struct bna_rxf *rxf)
{
struct bna *bna = rxf->rx->bna;
/* Enable/disable promiscuous mode */
if (is_promisc_enable(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask)) {
/* move promisc configuration from pending -> active */
promisc_inactive(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask);
rxf->rxmode_active |= BNA_RXMODE_PROMISC;
bna_bfi_rx_promisc_req(rxf, BNA_STATUS_T_ENABLED);
return 1;
} else if (is_promisc_disable(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask)) {
/* move promisc configuration from pending -> active */
promisc_inactive(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask);
rxf->rxmode_active &= ~BNA_RXMODE_PROMISC;
bna->promisc_rid = BFI_INVALID_RID;
bna_bfi_rx_promisc_req(rxf, BNA_STATUS_T_DISABLED);
return 1;
}
return 0;
}
static int
bna_rxf_promisc_cfg_reset(struct bna_rxf *rxf, enum bna_cleanup_type cleanup)
{
struct bna *bna = rxf->rx->bna;
/* Clear pending promisc mode disable */
if (is_promisc_disable(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask)) {
promisc_inactive(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask);
rxf->rxmode_active &= ~BNA_RXMODE_PROMISC;
bna->promisc_rid = BFI_INVALID_RID;
if (cleanup == BNA_HARD_CLEANUP) {
bna_bfi_rx_promisc_req(rxf, BNA_STATUS_T_DISABLED);
return 1;
}
}
/* Move promisc mode config from active -> pending */
if (rxf->rxmode_active & BNA_RXMODE_PROMISC) {
promisc_enable(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask);
rxf->rxmode_active &= ~BNA_RXMODE_PROMISC;
if (cleanup == BNA_HARD_CLEANUP) {
bna_bfi_rx_promisc_req(rxf, BNA_STATUS_T_DISABLED);
return 1;
}
}
return 0;
}
static int
bna_rxf_allmulti_cfg_apply(struct bna_rxf *rxf)
{
/* Enable/disable allmulti mode */
if (is_allmulti_enable(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask)) {
/* move allmulti configuration from pending -> active */
allmulti_inactive(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask);
rxf->rxmode_active |= BNA_RXMODE_ALLMULTI;
bna_bfi_mcast_filter_req(rxf, BNA_STATUS_T_DISABLED);
return 1;
} else if (is_allmulti_disable(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask)) {
/* move allmulti configuration from pending -> active */
allmulti_inactive(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask);
rxf->rxmode_active &= ~BNA_RXMODE_ALLMULTI;
bna_bfi_mcast_filter_req(rxf, BNA_STATUS_T_ENABLED);
return 1;
}
return 0;
}
static int
bna_rxf_allmulti_cfg_reset(struct bna_rxf *rxf, enum bna_cleanup_type cleanup)
{
/* Clear pending allmulti mode disable */
if (is_allmulti_disable(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask)) {
allmulti_inactive(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask);
rxf->rxmode_active &= ~BNA_RXMODE_ALLMULTI;
if (cleanup == BNA_HARD_CLEANUP) {
bna_bfi_mcast_filter_req(rxf, BNA_STATUS_T_ENABLED);
return 1;
}
}
/* Move allmulti mode config from active -> pending */
if (rxf->rxmode_active & BNA_RXMODE_ALLMULTI) {
allmulti_enable(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask);
rxf->rxmode_active &= ~BNA_RXMODE_ALLMULTI;
if (cleanup == BNA_HARD_CLEANUP) {
bna_bfi_mcast_filter_req(rxf, BNA_STATUS_T_ENABLED);
return 1;
}
}
return 0;
}
static int
bna_rxf_promisc_enable(struct bna_rxf *rxf)
{
struct bna *bna = rxf->rx->bna;
int ret = 0;
if (is_promisc_enable(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask) ||
(rxf->rxmode_active & BNA_RXMODE_PROMISC)) {
/* Do nothing if pending enable or already enabled */
} else if (is_promisc_disable(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask)) {
/* Turn off pending disable command */
promisc_inactive(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask);
} else {
/* Schedule enable */
promisc_enable(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask);
bna->promisc_rid = rxf->rx->rid;
ret = 1;
}
return ret;
}
static int
bna_rxf_promisc_disable(struct bna_rxf *rxf)
{
struct bna *bna = rxf->rx->bna;
int ret = 0;
if (is_promisc_disable(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask) ||
(!(rxf->rxmode_active & BNA_RXMODE_PROMISC))) {
/* Do nothing if pending disable or already disabled */
} else if (is_promisc_enable(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask)) {
/* Turn off pending enable command */
promisc_inactive(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask);
bna->promisc_rid = BFI_INVALID_RID;
} else if (rxf->rxmode_active & BNA_RXMODE_PROMISC) {
/* Schedule disable */
promisc_disable(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask);
ret = 1;
}
return ret;
}
static int
bna_rxf_allmulti_enable(struct bna_rxf *rxf)
{
int ret = 0;
if (is_allmulti_enable(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask) ||
(rxf->rxmode_active & BNA_RXMODE_ALLMULTI)) {
/* Do nothing if pending enable or already enabled */
} else if (is_allmulti_disable(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask)) {
/* Turn off pending disable command */
allmulti_inactive(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask);
} else {
/* Schedule enable */
allmulti_enable(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask);
ret = 1;
}
return ret;
}
static int
bna_rxf_allmulti_disable(struct bna_rxf *rxf)
{
int ret = 0;
if (is_allmulti_disable(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask) ||
(!(rxf->rxmode_active & BNA_RXMODE_ALLMULTI))) {
/* Do nothing if pending disable or already disabled */
} else if (is_allmulti_enable(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask)) {
/* Turn off pending enable command */
allmulti_inactive(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask);
} else if (rxf->rxmode_active & BNA_RXMODE_ALLMULTI) {
/* Schedule disable */
allmulti_disable(rxf->rxmode_pending,
rxf->rxmode_pending_bitmask);
ret = 1;
}
return ret;
}
static int
bna_rxf_vlan_strip_cfg_apply(struct bna_rxf *rxf)
{
if (rxf->vlan_strip_pending) {
rxf->vlan_strip_pending = false;
bna_bfi_vlan_strip_enable(rxf);
return 1;
}
return 0;
}
/* RX */
#define BNA_GET_RXQS(qcfg) (((qcfg)->rxp_type == BNA_RXP_SINGLE) ? \
(qcfg)->num_paths : ((qcfg)->num_paths * 2))
#define SIZE_TO_PAGES(size) (((size) >> PAGE_SHIFT) + ((((size) &\
(PAGE_SIZE - 1)) + (PAGE_SIZE - 1)) >> PAGE_SHIFT))
#define call_rx_stop_cbfn(rx) \
do { \
if ((rx)->stop_cbfn) { \
void (*cbfn)(void *, struct bna_rx *); \
void *cbarg; \
cbfn = (rx)->stop_cbfn; \
cbarg = (rx)->stop_cbarg; \
(rx)->stop_cbfn = NULL; \
(rx)->stop_cbarg = NULL; \
cbfn(cbarg, rx); \
} \
} while (0)
#define call_rx_stall_cbfn(rx) \
do { \
if ((rx)->rx_stall_cbfn) \
(rx)->rx_stall_cbfn((rx)->bna->bnad, (rx)); \
} while (0)
#define bfi_enet_datapath_q_init(bfi_q, bna_qpt) \
do { \
struct bna_dma_addr cur_q_addr = \
*((struct bna_dma_addr *)((bna_qpt)->kv_qpt_ptr)); \
(bfi_q)->pg_tbl.a32.addr_lo = (bna_qpt)->hw_qpt_ptr.lsb; \
(bfi_q)->pg_tbl.a32.addr_hi = (bna_qpt)->hw_qpt_ptr.msb; \
(bfi_q)->first_entry.a32.addr_lo = cur_q_addr.lsb; \
(bfi_q)->first_entry.a32.addr_hi = cur_q_addr.msb; \
(bfi_q)->pages = htons((u16)(bna_qpt)->page_count); \
(bfi_q)->page_sz = htons((u16)(bna_qpt)->page_size);\
} while (0)
static void bna_bfi_rx_enet_start(struct bna_rx *rx);
static void bna_rx_enet_stop(struct bna_rx *rx);
static void bna_rx_mod_cb_rx_stopped(void *arg, struct bna_rx *rx);
bfa_fsm_state_decl(bna_rx, stopped,
struct bna_rx, enum bna_rx_event);
bfa_fsm_state_decl(bna_rx, start_wait,
struct bna_rx, enum bna_rx_event);
bfa_fsm_state_decl(bna_rx, start_stop_wait,
struct bna_rx, enum bna_rx_event);
bfa_fsm_state_decl(bna_rx, rxf_start_wait,
struct bna_rx, enum bna_rx_event);
bfa_fsm_state_decl(bna_rx, started,
struct bna_rx, enum bna_rx_event);
bfa_fsm_state_decl(bna_rx, rxf_stop_wait,
struct bna_rx, enum bna_rx_event);
bfa_fsm_state_decl(bna_rx, stop_wait,
struct bna_rx, enum bna_rx_event);
bfa_fsm_state_decl(bna_rx, cleanup_wait,
struct bna_rx, enum bna_rx_event);
bfa_fsm_state_decl(bna_rx, failed,
struct bna_rx, enum bna_rx_event);
bfa_fsm_state_decl(bna_rx, quiesce_wait,
struct bna_rx, enum bna_rx_event);
static void bna_rx_sm_stopped_entry(struct bna_rx *rx)
{
call_rx_stop_cbfn(rx);
}
static void bna_rx_sm_stopped(struct bna_rx *rx,
enum bna_rx_event event)
{
switch (event) {
case RX_E_START:
bfa_fsm_set_state(rx, bna_rx_sm_start_wait);
break;
case RX_E_STOP:
call_rx_stop_cbfn(rx);
break;
case RX_E_FAIL:
/* no-op */
break;
default:
bfa_sm_fault(event);
break;
}
}
static void bna_rx_sm_start_wait_entry(struct bna_rx *rx)
{
bna_bfi_rx_enet_start(rx);
}
static void
bna_rx_sm_stop_wait_entry(struct bna_rx *rx)
{
}
static void
bna_rx_sm_stop_wait(struct bna_rx *rx, enum bna_rx_event event)
{
switch (event) {
case RX_E_FAIL:
case RX_E_STOPPED:
bfa_fsm_set_state(rx, bna_rx_sm_cleanup_wait);
rx->rx_cleanup_cbfn(rx->bna->bnad, rx);
break;
case RX_E_STARTED:
bna_rx_enet_stop(rx);
break;
default:
bfa_sm_fault(event);
break;
}
}
static void bna_rx_sm_start_wait(struct bna_rx *rx,
enum bna_rx_event event)
{
switch (event) {
case RX_E_STOP:
bfa_fsm_set_state(rx, bna_rx_sm_start_stop_wait);
break;
case RX_E_FAIL:
bfa_fsm_set_state(rx, bna_rx_sm_stopped);
break;
case RX_E_STARTED:
bfa_fsm_set_state(rx, bna_rx_sm_rxf_start_wait);
break;
default:
bfa_sm_fault(event);
break;
}
}
static void bna_rx_sm_rxf_start_wait_entry(struct bna_rx *rx)
{
rx->rx_post_cbfn(rx->bna->bnad, rx);
bna_rxf_start(&rx->rxf);
}
static void
bna_rx_sm_rxf_stop_wait_entry(struct bna_rx *rx)
{
}
static void
bna_rx_sm_rxf_stop_wait(struct bna_rx *rx, enum bna_rx_event event)
{
switch (event) {
case RX_E_FAIL:
bfa_fsm_set_state(rx, bna_rx_sm_cleanup_wait);
bna_rxf_fail(&rx->rxf);
call_rx_stall_cbfn(rx);
rx->rx_cleanup_cbfn(rx->bna->bnad, rx);
break;
case RX_E_RXF_STARTED:
bna_rxf_stop(&rx->rxf);
break;
case RX_E_RXF_STOPPED:
bfa_fsm_set_state(rx, bna_rx_sm_stop_wait);
call_rx_stall_cbfn(rx);
bna_rx_enet_stop(rx);
break;
default:
bfa_sm_fault(event);
break;
}
}
static void
bna_rx_sm_start_stop_wait_entry(struct bna_rx *rx)
{
}
static void
bna_rx_sm_start_stop_wait(struct bna_rx *rx, enum bna_rx_event event)
{
switch (event) {
case RX_E_FAIL:
case RX_E_STOPPED:
bfa_fsm_set_state(rx, bna_rx_sm_stopped);
break;
case RX_E_STARTED:
bna_rx_enet_stop(rx);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_rx_sm_started_entry(struct bna_rx *rx)
{
struct bna_rxp *rxp;
int is_regular = (rx->type == BNA_RX_T_REGULAR);
/* Start IB */
list_for_each_entry(rxp, &rx->rxp_q, qe)
bna_ib_start(rx->bna, &rxp->cq.ib, is_regular);
bna_ethport_cb_rx_started(&rx->bna->ethport);
}
static void
bna_rx_sm_started(struct bna_rx *rx, enum bna_rx_event event)
{
switch (event) {
case RX_E_STOP:
bfa_fsm_set_state(rx, bna_rx_sm_rxf_stop_wait);
bna_ethport_cb_rx_stopped(&rx->bna->ethport);
bna_rxf_stop(&rx->rxf);
break;
case RX_E_FAIL:
bfa_fsm_set_state(rx, bna_rx_sm_failed);
bna_ethport_cb_rx_stopped(&rx->bna->ethport);
bna_rxf_fail(&rx->rxf);
call_rx_stall_cbfn(rx);
rx->rx_cleanup_cbfn(rx->bna->bnad, rx);
break;
default:
bfa_sm_fault(event);
break;
}
}
static void bna_rx_sm_rxf_start_wait(struct bna_rx *rx,
enum bna_rx_event event)
{
switch (event) {
case RX_E_STOP:
bfa_fsm_set_state(rx, bna_rx_sm_rxf_stop_wait);
break;
case RX_E_FAIL:
bfa_fsm_set_state(rx, bna_rx_sm_failed);
bna_rxf_fail(&rx->rxf);
call_rx_stall_cbfn(rx);
rx->rx_cleanup_cbfn(rx->bna->bnad, rx);
break;
case RX_E_RXF_STARTED:
bfa_fsm_set_state(rx, bna_rx_sm_started);
break;
default:
bfa_sm_fault(event);
break;
}
}
static void
bna_rx_sm_cleanup_wait_entry(struct bna_rx *rx)
{
}
static void
bna_rx_sm_cleanup_wait(struct bna_rx *rx, enum bna_rx_event event)
{
switch (event) {
case RX_E_FAIL:
case RX_E_RXF_STOPPED:
/* No-op */
break;
case RX_E_CLEANUP_DONE:
bfa_fsm_set_state(rx, bna_rx_sm_stopped);
break;
default:
bfa_sm_fault(event);
break;
}
}
static void
bna_rx_sm_failed_entry(struct bna_rx *rx)
{
}
static void
bna_rx_sm_failed(struct bna_rx *rx, enum bna_rx_event event)
{
switch (event) {
case RX_E_START:
bfa_fsm_set_state(rx, bna_rx_sm_quiesce_wait);
break;
case RX_E_STOP:
bfa_fsm_set_state(rx, bna_rx_sm_cleanup_wait);
break;
case RX_E_FAIL:
case RX_E_RXF_STARTED:
case RX_E_RXF_STOPPED:
/* No-op */
break;
case RX_E_CLEANUP_DONE:
bfa_fsm_set_state(rx, bna_rx_sm_stopped);
break;
default:
bfa_sm_fault(event);
break;
} }
static void
bna_rx_sm_quiesce_wait_entry(struct bna_rx *rx)
{
}
static void
bna_rx_sm_quiesce_wait(struct bna_rx *rx, enum bna_rx_event event)
{
switch (event) {
case RX_E_STOP:
bfa_fsm_set_state(rx, bna_rx_sm_cleanup_wait);
break;
case RX_E_FAIL:
bfa_fsm_set_state(rx, bna_rx_sm_failed);
break;
case RX_E_CLEANUP_DONE:
bfa_fsm_set_state(rx, bna_rx_sm_start_wait);
break;
default:
bfa_sm_fault(event);
break;
}
}
static void
bna_bfi_rx_enet_start(struct bna_rx *rx)
{
struct bfi_enet_rx_cfg_req *cfg_req = &rx->bfi_enet_cmd.cfg_req;
struct bna_rxp *rxp = NULL;
struct bna_rxq *q0 = NULL, *q1 = NULL;
int i;
bfi_msgq_mhdr_set(cfg_req->mh, BFI_MC_ENET,
BFI_ENET_H2I_RX_CFG_SET_REQ, 0, rx->rid);
cfg_req->mh.num_entries = htons(
bfi_msgq_num_cmd_entries(sizeof(struct bfi_enet_rx_cfg_req)));
cfg_req->rx_cfg.frame_size = bna_enet_mtu_get(&rx->bna->enet);
cfg_req->num_queue_sets = rx->num_paths;
for (i = 0; i < rx->num_paths; i++) {
rxp = rxp ? list_next_entry(rxp, qe)
: list_first_entry(&rx->rxp_q, struct bna_rxp, qe);
GET_RXQS(rxp, q0, q1);
switch (rxp->type) {
case BNA_RXP_SLR:
case BNA_RXP_HDS:
/* Small RxQ */
bfi_enet_datapath_q_init(&cfg_req->q_cfg[i].qs.q,
&q1->qpt);
cfg_req->q_cfg[i].qs.rx_buffer_size =
htons((u16)q1->buffer_size);
fallthrough;
case BNA_RXP_SINGLE:
/* Large/Single RxQ */
bfi_enet_datapath_q_init(&cfg_req->q_cfg[i].ql.q,
&q0->qpt);
if (q0->multi_buffer)
/* multi-buffer is enabled by allocating
* a new rx with new set of resources.
* q0->buffer_size should be initialized to
* fragment size.
*/
cfg_req->rx_cfg.multi_buffer =
BNA_STATUS_T_ENABLED;
else
q0->buffer_size =
bna_enet_mtu_get(&rx->bna->enet);
cfg_req->q_cfg[i].ql.rx_buffer_size =
htons((u16)q0->buffer_size);
break;
default:
BUG_ON(1);
}
bfi_enet_datapath_q_init(&cfg_req->q_cfg[i].cq.q,
&rxp->cq.qpt);
cfg_req->q_cfg[i].ib.index_addr.a32.addr_lo =
rxp->cq.ib.ib_seg_host_addr.lsb;
cfg_req->q_cfg[i].ib.index_addr.a32.addr_hi =
rxp->cq.ib.ib_seg_host_addr.msb;
cfg_req->q_cfg[i].ib.intr.msix_index =
htons((u16)rxp->cq.ib.intr_vector);
}
cfg_req->ib_cfg.int_pkt_dma = BNA_STATUS_T_DISABLED;
cfg_req->ib_cfg.int_enabled = BNA_STATUS_T_ENABLED;
cfg_req->ib_cfg.int_pkt_enabled = BNA_STATUS_T_DISABLED;
cfg_req->ib_cfg.continuous_coalescing = BNA_STATUS_T_DISABLED;
cfg_req->ib_cfg.msix = (rxp->cq.ib.intr_type == BNA_INTR_T_MSIX)
? BNA_STATUS_T_ENABLED :
BNA_STATUS_T_DISABLED;
cfg_req->ib_cfg.coalescing_timeout =
htonl((u32)rxp->cq.ib.coalescing_timeo);
cfg_req->ib_cfg.inter_pkt_timeout =
htonl((u32)rxp->cq.ib.interpkt_timeo);
cfg_req->ib_cfg.inter_pkt_count = (u8)rxp->cq.ib.interpkt_count;
switch (rxp->type) {
case BNA_RXP_SLR:
cfg_req->rx_cfg.rxq_type = BFI_ENET_RXQ_LARGE_SMALL;
break;
case BNA_RXP_HDS:
cfg_req->rx_cfg.rxq_type = BFI_ENET_RXQ_HDS;
cfg_req->rx_cfg.hds.type = rx->hds_cfg.hdr_type;
cfg_req->rx_cfg.hds.force_offset = rx->hds_cfg.forced_offset;
cfg_req->rx_cfg.hds.max_header_size = rx->hds_cfg.forced_offset;
break;
case BNA_RXP_SINGLE:
cfg_req->rx_cfg.rxq_type = BFI_ENET_RXQ_SINGLE;
break;
default:
BUG_ON(1);
}
cfg_req->rx_cfg.strip_vlan = rx->rxf.vlan_strip_status;
bfa_msgq_cmd_set(&rx->msgq_cmd, NULL, NULL,
sizeof(struct bfi_enet_rx_cfg_req), &cfg_req->mh);
bfa_msgq_cmd_post(&rx->bna->msgq, &rx->msgq_cmd);
}
static void
bna_bfi_rx_enet_stop(struct bna_rx *rx)
{
struct bfi_enet_req *req = &rx->bfi_enet_cmd.req;
bfi_msgq_mhdr_set(req->mh, BFI_MC_ENET,
BFI_ENET_H2I_RX_CFG_CLR_REQ, 0, rx->rid);
req->mh.num_entries = htons(
bfi_msgq_num_cmd_entries(sizeof(struct bfi_enet_req)));
bfa_msgq_cmd_set(&rx->msgq_cmd, NULL, NULL, sizeof(struct bfi_enet_req),
&req->mh);
bfa_msgq_cmd_post(&rx->bna->msgq, &rx->msgq_cmd);
}
static void
bna_rx_enet_stop(struct bna_rx *rx)
{
struct bna_rxp *rxp;
/* Stop IB */
list_for_each_entry(rxp, &rx->rxp_q, qe)
bna_ib_stop(rx->bna, &rxp->cq.ib);
bna_bfi_rx_enet_stop(rx);
}
static int
bna_rx_res_check(struct bna_rx_mod *rx_mod, struct bna_rx_config *rx_cfg)
{
if ((rx_mod->rx_free_count == 0) ||
(rx_mod->rxp_free_count == 0) ||
(rx_mod->rxq_free_count == 0))
return 0;
if (rx_cfg->rxp_type == BNA_RXP_SINGLE) {
if ((rx_mod->rxp_free_count < rx_cfg->num_paths) ||
(rx_mod->rxq_free_count < rx_cfg->num_paths))
return 0;
} else {
if ((rx_mod->rxp_free_count < rx_cfg->num_paths) ||
(rx_mod->rxq_free_count < (2 * rx_cfg->num_paths)))
return 0;
}
return 1;
}
static struct bna_rxq *
bna_rxq_get(struct bna_rx_mod *rx_mod)
{
struct bna_rxq *rxq = NULL;
rxq = list_first_entry(&rx_mod->rxq_free_q, struct bna_rxq, qe);
list_del(&rxq->qe);
rx_mod->rxq_free_count--;
return rxq;
}
static void
bna_rxq_put(struct bna_rx_mod *rx_mod, struct bna_rxq *rxq)
{
list_add_tail(&rxq->qe, &rx_mod->rxq_free_q);
rx_mod->rxq_free_count++;
}
static struct bna_rxp *
bna_rxp_get(struct bna_rx_mod *rx_mod)
{
struct bna_rxp *rxp = NULL;
rxp = list_first_entry(&rx_mod->rxp_free_q, struct bna_rxp, qe);
list_del(&rxp->qe);
rx_mod->rxp_free_count--;
return rxp;
}
static void
bna_rxp_put(struct bna_rx_mod *rx_mod, struct bna_rxp *rxp)
{
list_add_tail(&rxp->qe, &rx_mod->rxp_free_q);
rx_mod->rxp_free_count++;
}
static struct bna_rx *
bna_rx_get(struct bna_rx_mod *rx_mod, enum bna_rx_type type)
{
struct bna_rx *rx = NULL;
BUG_ON(list_empty(&rx_mod->rx_free_q));
if (type == BNA_RX_T_REGULAR)
rx = list_first_entry(&rx_mod->rx_free_q, struct bna_rx, qe);
else
rx = list_last_entry(&rx_mod->rx_free_q, struct bna_rx, qe);
rx_mod->rx_free_count--;
list_move_tail(&rx->qe, &rx_mod->rx_active_q);
rx->type = type;
return rx;
}
static void
bna_rx_put(struct bna_rx_mod *rx_mod, struct bna_rx *rx)
{
struct list_head *qe;
list_for_each_prev(qe, &rx_mod->rx_free_q)
if (((struct bna_rx *)qe)->rid < rx->rid)
break;
list_add(&rx->qe, qe);
rx_mod->rx_free_count++;
}
static void
bna_rxp_add_rxqs(struct bna_rxp *rxp, struct bna_rxq *q0,
struct bna_rxq *q1)
{
switch (rxp->type) {
case BNA_RXP_SINGLE:
rxp->rxq.single.only = q0;
rxp->rxq.single.reserved = NULL;
break;
case BNA_RXP_SLR:
rxp->rxq.slr.large = q0;
rxp->rxq.slr.small = q1;
break;
case BNA_RXP_HDS:
rxp->rxq.hds.data = q0;
rxp->rxq.hds.hdr = q1;
break;
default:
break;
}
}
static void
bna_rxq_qpt_setup(struct bna_rxq *rxq,
struct bna_rxp *rxp,
u32 page_count,
u32 page_size,
struct bna_mem_descr *qpt_mem,
struct bna_mem_descr *swqpt_mem,
struct bna_mem_descr *page_mem)
{
u8 *kva;
u64 dma;
struct bna_dma_addr bna_dma;
int i;
rxq->qpt.hw_qpt_ptr.lsb = qpt_mem->dma.lsb;
rxq->qpt.hw_qpt_ptr.msb = qpt_mem->dma.msb;
rxq->qpt.kv_qpt_ptr = qpt_mem->kva;
rxq->qpt.page_count = page_count;
rxq->qpt.page_size = page_size;
rxq->rcb->sw_qpt = (void **) swqpt_mem->kva;
rxq->rcb->sw_q = page_mem->kva;
kva = page_mem->kva;
BNA_GET_DMA_ADDR(&page_mem->dma, dma);
for (i = 0; i < rxq->qpt.page_count; i++) {
rxq->rcb->sw_qpt[i] = kva;
kva += PAGE_SIZE;
BNA_SET_DMA_ADDR(dma, &bna_dma);
((struct bna_dma_addr *)rxq->qpt.kv_qpt_ptr)[i].lsb =
bna_dma.lsb;
((struct bna_dma_addr *)rxq->qpt.kv_qpt_ptr)[i].msb =
bna_dma.msb;
dma += PAGE_SIZE;
}
}
static void
bna_rxp_cqpt_setup(struct bna_rxp *rxp,
u32 page_count,
u32 page_size,
struct bna_mem_descr *qpt_mem,
struct bna_mem_descr *swqpt_mem,
struct bna_mem_descr *page_mem)
{
u8 *kva;
u64 dma;
struct bna_dma_addr bna_dma;
int i;
rxp->cq.qpt.hw_qpt_ptr.lsb = qpt_mem->dma.lsb;
rxp->cq.qpt.hw_qpt_ptr.msb = qpt_mem->dma.msb;
rxp->cq.qpt.kv_qpt_ptr = qpt_mem->kva;
rxp->cq.qpt.page_count = page_count;
rxp->cq.qpt.page_size = page_size;
rxp->cq.ccb->sw_qpt = (void **) swqpt_mem->kva;
rxp->cq.ccb->sw_q = page_mem->kva;
kva = page_mem->kva;
BNA_GET_DMA_ADDR(&page_mem->dma, dma);
for (i = 0; i < rxp->cq.qpt.page_count; i++) {
rxp->cq.ccb->sw_qpt[i] = kva;
kva += PAGE_SIZE;
BNA_SET_DMA_ADDR(dma, &bna_dma);
((struct bna_dma_addr *)rxp->cq.qpt.kv_qpt_ptr)[i].lsb =
bna_dma.lsb;
((struct bna_dma_addr *)rxp->cq.qpt.kv_qpt_ptr)[i].msb =
bna_dma.msb;
dma += PAGE_SIZE;
}
}
static void
bna_rx_mod_cb_rx_stopped(void *arg, struct bna_rx *rx)
{
struct bna_rx_mod *rx_mod = (struct bna_rx_mod *)arg;
bfa_wc_down(&rx_mod->rx_stop_wc);
}
static void
bna_rx_mod_cb_rx_stopped_all(void *arg)
{
struct bna_rx_mod *rx_mod = (struct bna_rx_mod *)arg;
if (rx_mod->stop_cbfn)
rx_mod->stop_cbfn(&rx_mod->bna->enet);
rx_mod->stop_cbfn = NULL;
}
static void
bna_rx_start(struct bna_rx *rx)
{
rx->rx_flags |= BNA_RX_F_ENET_STARTED;
if (rx->rx_flags & BNA_RX_F_ENABLED)
bfa_fsm_send_event(rx, RX_E_START);
}
static void
bna_rx_stop(struct bna_rx *rx)
{
rx->rx_flags &= ~BNA_RX_F_ENET_STARTED;
if (rx->fsm == bna_rx_sm_stopped)
bna_rx_mod_cb_rx_stopped(&rx->bna->rx_mod, rx);
else {
rx->stop_cbfn = bna_rx_mod_cb_rx_stopped;
rx->stop_cbarg = &rx->bna->rx_mod;
bfa_fsm_send_event(rx, RX_E_STOP);
}
}
static void
bna_rx_fail(struct bna_rx *rx)
{
/* Indicate Enet is not enabled, and failed */
rx->rx_flags &= ~BNA_RX_F_ENET_STARTED;
bfa_fsm_send_event(rx, RX_E_FAIL);
}
void
bna_rx_mod_start(struct bna_rx_mod *rx_mod, enum bna_rx_type type)
{
struct bna_rx *rx;
rx_mod->flags |= BNA_RX_MOD_F_ENET_STARTED;
if (type == BNA_RX_T_LOOPBACK)
rx_mod->flags |= BNA_RX_MOD_F_ENET_LOOPBACK;
list_for_each_entry(rx, &rx_mod->rx_active_q, qe)
if (rx->type == type)
bna_rx_start(rx);
}
void
bna_rx_mod_stop(struct bna_rx_mod *rx_mod, enum bna_rx_type type)
{
struct bna_rx *rx;
rx_mod->flags &= ~BNA_RX_MOD_F_ENET_STARTED;
rx_mod->flags &= ~BNA_RX_MOD_F_ENET_LOOPBACK;
rx_mod->stop_cbfn = bna_enet_cb_rx_stopped;
bfa_wc_init(&rx_mod->rx_stop_wc, bna_rx_mod_cb_rx_stopped_all, rx_mod);
list_for_each_entry(rx, &rx_mod->rx_active_q, qe)
if (rx->type == type) {
bfa_wc_up(&rx_mod->rx_stop_wc);
bna_rx_stop(rx);
}
bfa_wc_wait(&rx_mod->rx_stop_wc);
}
void
bna_rx_mod_fail(struct bna_rx_mod *rx_mod)
{
struct bna_rx *rx;
rx_mod->flags &= ~BNA_RX_MOD_F_ENET_STARTED;
rx_mod->flags &= ~BNA_RX_MOD_F_ENET_LOOPBACK;
list_for_each_entry(rx, &rx_mod->rx_active_q, qe)
bna_rx_fail(rx);
}
void bna_rx_mod_init(struct bna_rx_mod *rx_mod, struct bna *bna,
struct bna_res_info *res_info)
{
int index;
struct bna_rx *rx_ptr;
struct bna_rxp *rxp_ptr;
struct bna_rxq *rxq_ptr;
rx_mod->bna = bna;
rx_mod->flags = 0;
rx_mod->rx = (struct bna_rx *)
res_info[BNA_MOD_RES_MEM_T_RX_ARRAY].res_u.mem_info.mdl[0].kva;
rx_mod->rxp = (struct bna_rxp *)
res_info[BNA_MOD_RES_MEM_T_RXP_ARRAY].res_u.mem_info.mdl[0].kva;
rx_mod->rxq = (struct bna_rxq *)
res_info[BNA_MOD_RES_MEM_T_RXQ_ARRAY].res_u.mem_info.mdl[0].kva;
/* Initialize the queues */
INIT_LIST_HEAD(&rx_mod->rx_free_q);
rx_mod->rx_free_count = 0;
INIT_LIST_HEAD(&rx_mod->rxq_free_q);
rx_mod->rxq_free_count = 0;
INIT_LIST_HEAD(&rx_mod->rxp_free_q);
rx_mod->rxp_free_count = 0;
INIT_LIST_HEAD(&rx_mod->rx_active_q);
/* Build RX queues */
for (index = 0; index < bna->ioceth.attr.num_rxp; index++) {
rx_ptr = &rx_mod->rx[index];
INIT_LIST_HEAD(&rx_ptr->rxp_q);
rx_ptr->bna = NULL;
rx_ptr->rid = index;
rx_ptr->stop_cbfn = NULL;
rx_ptr->stop_cbarg = NULL;
list_add_tail(&rx_ptr->qe, &rx_mod->rx_free_q);
rx_mod->rx_free_count++;
}
/* build RX-path queue */
for (index = 0; index < bna->ioceth.attr.num_rxp; index++) {
rxp_ptr = &rx_mod->rxp[index];
list_add_tail(&rxp_ptr->qe, &rx_mod->rxp_free_q);
rx_mod->rxp_free_count++;
}
/* build RXQ queue */
for (index = 0; index < (bna->ioceth.attr.num_rxp * 2); index++) {
rxq_ptr = &rx_mod->rxq[index];
list_add_tail(&rxq_ptr->qe, &rx_mod->rxq_free_q);
rx_mod->rxq_free_count++;
}
}
void
bna_rx_mod_uninit(struct bna_rx_mod *rx_mod)
{
rx_mod->bna = NULL;
}
void
bna_bfi_rx_enet_start_rsp(struct bna_rx *rx, struct bfi_msgq_mhdr *msghdr)
{
struct bfi_enet_rx_cfg_rsp *cfg_rsp = &rx->bfi_enet_cmd.cfg_rsp;
struct bna_rxp *rxp = NULL;
struct bna_rxq *q0 = NULL, *q1 = NULL;
int i;
bfa_msgq_rsp_copy(&rx->bna->msgq, (u8 *)cfg_rsp,
sizeof(struct bfi_enet_rx_cfg_rsp));
rx->hw_id = cfg_rsp->hw_id;
for (i = 0, rxp = list_first_entry(&rx->rxp_q, struct bna_rxp, qe);
i < rx->num_paths; i++, rxp = list_next_entry(rxp, qe)) {
GET_RXQS(rxp, q0, q1);
/* Setup doorbells */
rxp->cq.ccb->i_dbell->doorbell_addr =
rx->bna->pcidev.pci_bar_kva
+ ntohl(cfg_rsp->q_handles[i].i_dbell);
rxp->hw_id = cfg_rsp->q_handles[i].hw_cqid;
q0->rcb->q_dbell =
rx->bna->pcidev.pci_bar_kva
+ ntohl(cfg_rsp->q_handles[i].ql_dbell);
q0->hw_id = cfg_rsp->q_handles[i].hw_lqid;
if (q1) {
q1->rcb->q_dbell =
rx->bna->pcidev.pci_bar_kva
+ ntohl(cfg_rsp->q_handles[i].qs_dbell);
q1->hw_id = cfg_rsp->q_handles[i].hw_sqid;
}
/* Initialize producer/consumer indexes */
(*rxp->cq.ccb->hw_producer_index) = 0;
rxp->cq.ccb->producer_index = 0;
q0->rcb->producer_index = q0->rcb->consumer_index = 0;
if (q1)
q1->rcb->producer_index = q1->rcb->consumer_index = 0;
}
bfa_fsm_send_event(rx, RX_E_STARTED);
}
void
bna_bfi_rx_enet_stop_rsp(struct bna_rx *rx, struct bfi_msgq_mhdr *msghdr)
{
bfa_fsm_send_event(rx, RX_E_STOPPED);
}
void
bna_rx_res_req(struct bna_rx_config *q_cfg, struct bna_res_info *res_info)
{
u32 cq_size, hq_size, dq_size;
u32 cpage_count, hpage_count, dpage_count;
struct bna_mem_info *mem_info;
u32 cq_depth;
u32 hq_depth;
u32 dq_depth;
dq_depth = q_cfg->q0_depth;
hq_depth = ((q_cfg->rxp_type == BNA_RXP_SINGLE) ? 0 : q_cfg->q1_depth);
cq_depth = roundup_pow_of_two(dq_depth + hq_depth);
cq_size = cq_depth * BFI_CQ_WI_SIZE;
cq_size = ALIGN(cq_size, PAGE_SIZE);
cpage_count = SIZE_TO_PAGES(cq_size);
dq_depth = roundup_pow_of_two(dq_depth);
dq_size = dq_depth * BFI_RXQ_WI_SIZE;
dq_size = ALIGN(dq_size, PAGE_SIZE);
dpage_count = SIZE_TO_PAGES(dq_size);
if (BNA_RXP_SINGLE != q_cfg->rxp_type) {
hq_depth = roundup_pow_of_two(hq_depth);
hq_size = hq_depth * BFI_RXQ_WI_SIZE;
hq_size = ALIGN(hq_size, PAGE_SIZE);
hpage_count = SIZE_TO_PAGES(hq_size);
} else
hpage_count = 0;
res_info[BNA_RX_RES_MEM_T_CCB].res_type = BNA_RES_T_MEM;
mem_info = &res_info[BNA_RX_RES_MEM_T_CCB].res_u.mem_info;
mem_info->mem_type = BNA_MEM_T_KVA;
mem_info->len = sizeof(struct bna_ccb);
mem_info->num = q_cfg->num_paths;
res_info[BNA_RX_RES_MEM_T_RCB].res_type = BNA_RES_T_MEM;
mem_info = &res_info[BNA_RX_RES_MEM_T_RCB].res_u.mem_info;
mem_info->mem_type = BNA_MEM_T_KVA;
mem_info->len = sizeof(struct bna_rcb);
mem_info->num = BNA_GET_RXQS(q_cfg);
res_info[BNA_RX_RES_MEM_T_CQPT].res_type = BNA_RES_T_MEM;
mem_info = &res_info[BNA_RX_RES_MEM_T_CQPT].res_u.mem_info;
mem_info->mem_type = BNA_MEM_T_DMA;
mem_info->len = cpage_count * sizeof(struct bna_dma_addr);
mem_info->num = q_cfg->num_paths;
res_info[BNA_RX_RES_MEM_T_CSWQPT].res_type = BNA_RES_T_MEM;
mem_info = &res_info[BNA_RX_RES_MEM_T_CSWQPT].res_u.mem_info;
mem_info->mem_type = BNA_MEM_T_KVA;
mem_info->len = cpage_count * sizeof(void *);
mem_info->num = q_cfg->num_paths;
res_info[BNA_RX_RES_MEM_T_CQPT_PAGE].res_type = BNA_RES_T_MEM;
mem_info = &res_info[BNA_RX_RES_MEM_T_CQPT_PAGE].res_u.mem_info;
mem_info->mem_type = BNA_MEM_T_DMA;
mem_info->len = PAGE_SIZE * cpage_count;
mem_info->num = q_cfg->num_paths;
res_info[BNA_RX_RES_MEM_T_DQPT].res_type = BNA_RES_T_MEM;
mem_info = &res_info[BNA_RX_RES_MEM_T_DQPT].res_u.mem_info;
mem_info->mem_type = BNA_MEM_T_DMA;
mem_info->len = dpage_count * sizeof(struct bna_dma_addr);
mem_info->num = q_cfg->num_paths;
res_info[BNA_RX_RES_MEM_T_DSWQPT].res_type = BNA_RES_T_MEM;
mem_info = &res_info[BNA_RX_RES_MEM_T_DSWQPT].res_u.mem_info;
mem_info->mem_type = BNA_MEM_T_KVA;
mem_info->len = dpage_count * sizeof(void *);
mem_info->num = q_cfg->num_paths;
res_info[BNA_RX_RES_MEM_T_DPAGE].res_type = BNA_RES_T_MEM;
mem_info = &res_info[BNA_RX_RES_MEM_T_DPAGE].res_u.mem_info;
mem_info->mem_type = BNA_MEM_T_DMA;
mem_info->len = PAGE_SIZE * dpage_count;
mem_info->num = q_cfg->num_paths;
res_info[BNA_RX_RES_MEM_T_HQPT].res_type = BNA_RES_T_MEM;
mem_info = &res_info[BNA_RX_RES_MEM_T_HQPT].res_u.mem_info;
mem_info->mem_type = BNA_MEM_T_DMA;
mem_info->len = hpage_count * sizeof(struct bna_dma_addr);
mem_info->num = (hpage_count ? q_cfg->num_paths : 0);
res_info[BNA_RX_RES_MEM_T_HSWQPT].res_type = BNA_RES_T_MEM;
mem_info = &res_info[BNA_RX_RES_MEM_T_HSWQPT].res_u.mem_info;
mem_info->mem_type = BNA_MEM_T_KVA;
mem_info->len = hpage_count * sizeof(void *);
mem_info->num = (hpage_count ? q_cfg->num_paths : 0);
res_info[BNA_RX_RES_MEM_T_HPAGE].res_type = BNA_RES_T_MEM;
mem_info = &res_info[BNA_RX_RES_MEM_T_HPAGE].res_u.mem_info;
mem_info->mem_type = BNA_MEM_T_DMA;
mem_info->len = PAGE_SIZE * hpage_count;
mem_info->num = (hpage_count ? q_cfg->num_paths : 0);
res_info[BNA_RX_RES_MEM_T_IBIDX].res_type = BNA_RES_T_MEM;
mem_info = &res_info[BNA_RX_RES_MEM_T_IBIDX].res_u.mem_info;
mem_info->mem_type = BNA_MEM_T_DMA;
mem_info->len = BFI_IBIDX_SIZE;
mem_info->num = q_cfg->num_paths;
res_info[BNA_RX_RES_MEM_T_RIT].res_type = BNA_RES_T_MEM;
mem_info = &res_info[BNA_RX_RES_MEM_T_RIT].res_u.mem_info;
mem_info->mem_type = BNA_MEM_T_KVA;
mem_info->len = BFI_ENET_RSS_RIT_MAX;
mem_info->num = 1;
res_info[BNA_RX_RES_T_INTR].res_type = BNA_RES_T_INTR;
res_info[BNA_RX_RES_T_INTR].res_u.intr_info.intr_type = BNA_INTR_T_MSIX;
res_info[BNA_RX_RES_T_INTR].res_u.intr_info.num = q_cfg->num_paths;
}
struct bna_rx *
bna_rx_create(struct bna *bna, struct bnad *bnad,
struct bna_rx_config *rx_cfg,
const struct bna_rx_event_cbfn *rx_cbfn,
struct bna_res_info *res_info,
void *priv)
{
struct bna_rx_mod *rx_mod = &bna->rx_mod;
struct bna_rx *rx;
struct bna_rxp *rxp;
struct bna_rxq *q0;
struct bna_rxq *q1;
struct bna_intr_info *intr_info;
struct bna_mem_descr *hqunmap_mem;
struct bna_mem_descr *dqunmap_mem;
struct bna_mem_descr *ccb_mem;
struct bna_mem_descr *rcb_mem;
struct bna_mem_descr *cqpt_mem;
struct bna_mem_descr *cswqpt_mem;
struct bna_mem_descr *cpage_mem;
struct bna_mem_descr *hqpt_mem;
struct bna_mem_descr *dqpt_mem;
struct bna_mem_descr *hsqpt_mem;
struct bna_mem_descr *dsqpt_mem;
struct bna_mem_descr *hpage_mem;
struct bna_mem_descr *dpage_mem;
u32 dpage_count, hpage_count;
u32 hq_idx, dq_idx, rcb_idx;
u32 cq_depth, i;
u32 page_count;
if (!bna_rx_res_check(rx_mod, rx_cfg))
return NULL;
intr_info = &res_info[BNA_RX_RES_T_INTR].res_u.intr_info;
ccb_mem = &res_info[BNA_RX_RES_MEM_T_CCB].res_u.mem_info.mdl[0];
rcb_mem = &res_info[BNA_RX_RES_MEM_T_RCB].res_u.mem_info.mdl[0];
dqunmap_mem = &res_info[BNA_RX_RES_MEM_T_UNMAPDQ].res_u.mem_info.mdl[0];
hqunmap_mem = &res_info[BNA_RX_RES_MEM_T_UNMAPHQ].res_u.mem_info.mdl[0];
cqpt_mem = &res_info[BNA_RX_RES_MEM_T_CQPT].res_u.mem_info.mdl[0];
cswqpt_mem = &res_info[BNA_RX_RES_MEM_T_CSWQPT].res_u.mem_info.mdl[0];
cpage_mem = &res_info[BNA_RX_RES_MEM_T_CQPT_PAGE].res_u.mem_info.mdl[0];
hqpt_mem = &res_info[BNA_RX_RES_MEM_T_HQPT].res_u.mem_info.mdl[0];
dqpt_mem = &res_info[BNA_RX_RES_MEM_T_DQPT].res_u.mem_info.mdl[0];
hsqpt_mem = &res_info[BNA_RX_RES_MEM_T_HSWQPT].res_u.mem_info.mdl[0];
dsqpt_mem = &res_info[BNA_RX_RES_MEM_T_DSWQPT].res_u.mem_info.mdl[0];
hpage_mem = &res_info[BNA_RX_RES_MEM_T_HPAGE].res_u.mem_info.mdl[0];
dpage_mem = &res_info[BNA_RX_RES_MEM_T_DPAGE].res_u.mem_info.mdl[0];
page_count = res_info[BNA_RX_RES_MEM_T_CQPT_PAGE].res_u.mem_info.len /
PAGE_SIZE;
dpage_count = res_info[BNA_RX_RES_MEM_T_DPAGE].res_u.mem_info.len /
PAGE_SIZE;
hpage_count = res_info[BNA_RX_RES_MEM_T_HPAGE].res_u.mem_info.len /
PAGE_SIZE;
rx = bna_rx_get(rx_mod, rx_cfg->rx_type);
rx->bna = bna;
rx->rx_flags = 0;
INIT_LIST_HEAD(&rx->rxp_q);
rx->stop_cbfn = NULL;
rx->stop_cbarg = NULL;
rx->priv = priv;
rx->rcb_setup_cbfn = rx_cbfn->rcb_setup_cbfn;
rx->rcb_destroy_cbfn = rx_cbfn->rcb_destroy_cbfn;
rx->ccb_setup_cbfn = rx_cbfn->ccb_setup_cbfn;
rx->ccb_destroy_cbfn = rx_cbfn->ccb_destroy_cbfn;
rx->rx_stall_cbfn = rx_cbfn->rx_stall_cbfn;
/* Following callbacks are mandatory */
rx->rx_cleanup_cbfn = rx_cbfn->rx_cleanup_cbfn;
rx->rx_post_cbfn = rx_cbfn->rx_post_cbfn;
if (rx->bna->rx_mod.flags & BNA_RX_MOD_F_ENET_STARTED) {
switch (rx->type) {
case BNA_RX_T_REGULAR:
if (!(rx->bna->rx_mod.flags &
BNA_RX_MOD_F_ENET_LOOPBACK))
rx->rx_flags |= BNA_RX_F_ENET_STARTED;
break;
case BNA_RX_T_LOOPBACK:
if (rx->bna->rx_mod.flags & BNA_RX_MOD_F_ENET_LOOPBACK)
rx->rx_flags |= BNA_RX_F_ENET_STARTED;
break;
}
}
rx->num_paths = rx_cfg->num_paths;
for (i = 0, hq_idx = 0, dq_idx = 0, rcb_idx = 0;
i < rx->num_paths; i++) {
rxp = bna_rxp_get(rx_mod);
list_add_tail(&rxp->qe, &rx->rxp_q);
rxp->type = rx_cfg->rxp_type;
rxp->rx = rx;
rxp->cq.rx = rx;
q0 = bna_rxq_get(rx_mod);
if (BNA_RXP_SINGLE == rx_cfg->rxp_type)
q1 = NULL;
else
q1 = bna_rxq_get(rx_mod);
if (1 == intr_info->num)
rxp->vector = intr_info->idl[0].vector;
else
rxp->vector = intr_info->idl[i].vector;
/* Setup IB */
rxp->cq.ib.ib_seg_host_addr.lsb =
res_info[BNA_RX_RES_MEM_T_IBIDX].res_u.mem_info.mdl[i].dma.lsb;
rxp->cq.ib.ib_seg_host_addr.msb =
res_info[BNA_RX_RES_MEM_T_IBIDX].res_u.mem_info.mdl[i].dma.msb;
rxp->cq.ib.ib_seg_host_addr_kva =
res_info[BNA_RX_RES_MEM_T_IBIDX].res_u.mem_info.mdl[i].kva;
rxp->cq.ib.intr_type = intr_info->intr_type;
if (intr_info->intr_type == BNA_INTR_T_MSIX)
rxp->cq.ib.intr_vector = rxp->vector;
else
rxp->cq.ib.intr_vector = BIT(rxp->vector);
rxp->cq.ib.coalescing_timeo = rx_cfg->coalescing_timeo;
rxp->cq.ib.interpkt_count = BFI_RX_INTERPKT_COUNT;
rxp->cq.ib.interpkt_timeo = BFI_RX_INTERPKT_TIMEO;
bna_rxp_add_rxqs(rxp, q0, q1);
/* Setup large Q */
q0->rx = rx;
q0->rxp = rxp;
q0->rcb = (struct bna_rcb *) rcb_mem[rcb_idx].kva;
q0->rcb->unmap_q = (void *)dqunmap_mem[dq_idx].kva;
rcb_idx++; dq_idx++;
q0->rcb->q_depth = rx_cfg->q0_depth;
q0->q_depth = rx_cfg->q0_depth;
q0->multi_buffer = rx_cfg->q0_multi_buf;
q0->buffer_size = rx_cfg->q0_buf_size;
q0->num_vecs = rx_cfg->q0_num_vecs;
q0->rcb->rxq = q0;
q0->rcb->bnad = bna->bnad;
q0->rcb->id = 0;
q0->rx_packets = q0->rx_bytes = 0;
q0->rx_packets_with_error = q0->rxbuf_alloc_failed = 0;
q0->rxbuf_map_failed = 0;
bna_rxq_qpt_setup(q0, rxp, dpage_count, PAGE_SIZE,
&dqpt_mem[i], &dsqpt_mem[i], &dpage_mem[i]);
if (rx->rcb_setup_cbfn)
rx->rcb_setup_cbfn(bnad, q0->rcb);
/* Setup small Q */
if (q1) {
q1->rx = rx;
q1->rxp = rxp;
q1->rcb = (struct bna_rcb *) rcb_mem[rcb_idx].kva;
q1->rcb->unmap_q = (void *)hqunmap_mem[hq_idx].kva;
rcb_idx++; hq_idx++;
q1->rcb->q_depth = rx_cfg->q1_depth;
q1->q_depth = rx_cfg->q1_depth;
q1->multi_buffer = BNA_STATUS_T_DISABLED;
q1->num_vecs = 1;
q1->rcb->rxq = q1;
q1->rcb->bnad = bna->bnad;
q1->rcb->id = 1;
q1->buffer_size = (rx_cfg->rxp_type == BNA_RXP_HDS) ?
rx_cfg->hds_config.forced_offset
: rx_cfg->q1_buf_size;
q1->rx_packets = q1->rx_bytes = 0;
q1->rx_packets_with_error = q1->rxbuf_alloc_failed = 0;
q1->rxbuf_map_failed = 0;
bna_rxq_qpt_setup(q1, rxp, hpage_count, PAGE_SIZE,
&hqpt_mem[i], &hsqpt_mem[i],
&hpage_mem[i]);
if (rx->rcb_setup_cbfn)
rx->rcb_setup_cbfn(bnad, q1->rcb);
}
/* Setup CQ */
rxp->cq.ccb = (struct bna_ccb *) ccb_mem[i].kva;
cq_depth = rx_cfg->q0_depth +
((rx_cfg->rxp_type == BNA_RXP_SINGLE) ?
0 : rx_cfg->q1_depth);
/* if multi-buffer is enabled sum of q0_depth
* and q1_depth need not be a power of 2
*/
cq_depth = roundup_pow_of_two(cq_depth);
rxp->cq.ccb->q_depth = cq_depth;
rxp->cq.ccb->cq = &rxp->cq;
rxp->cq.ccb->rcb[0] = q0->rcb;
q0->rcb->ccb = rxp->cq.ccb;
if (q1) {
rxp->cq.ccb->rcb[1] = q1->rcb;
q1->rcb->ccb = rxp->cq.ccb;
}
rxp->cq.ccb->hw_producer_index =
(u32 *)rxp->cq.ib.ib_seg_host_addr_kva;
rxp->cq.ccb->i_dbell = &rxp->cq.ib.door_bell;
rxp->cq.ccb->intr_type = rxp->cq.ib.intr_type;
rxp->cq.ccb->intr_vector = rxp->cq.ib.intr_vector;
rxp->cq.ccb->rx_coalescing_timeo =
rxp->cq.ib.coalescing_timeo;
rxp->cq.ccb->pkt_rate.small_pkt_cnt = 0;
rxp->cq.ccb->pkt_rate.large_pkt_cnt = 0;
rxp->cq.ccb->bnad = bna->bnad;
rxp->cq.ccb->id = i;
bna_rxp_cqpt_setup(rxp, page_count, PAGE_SIZE,
&cqpt_mem[i], &cswqpt_mem[i], &cpage_mem[i]);
if (rx->ccb_setup_cbfn)
rx->ccb_setup_cbfn(bnad, rxp->cq.ccb);
}
rx->hds_cfg = rx_cfg->hds_config;
bna_rxf_init(&rx->rxf, rx, rx_cfg, res_info);
bfa_fsm_set_state(rx, bna_rx_sm_stopped);
rx_mod->rid_mask |= BIT(rx->rid);
return rx;
}
void
bna_rx_destroy(struct bna_rx *rx)
{
struct bna_rx_mod *rx_mod = &rx->bna->rx_mod;
struct bna_rxq *q0 = NULL;
struct bna_rxq *q1 = NULL;
struct bna_rxp *rxp;
struct list_head *qe;
bna_rxf_uninit(&rx->rxf);
while (!list_empty(&rx->rxp_q)) {
rxp = list_first_entry(&rx->rxp_q, struct bna_rxp, qe);
list_del(&rxp->qe);
GET_RXQS(rxp, q0, q1);
if (rx->rcb_destroy_cbfn)
rx->rcb_destroy_cbfn(rx->bna->bnad, q0->rcb);
q0->rcb = NULL;
q0->rxp = NULL;
q0->rx = NULL;
bna_rxq_put(rx_mod, q0);
if (q1) {
if (rx->rcb_destroy_cbfn)
rx->rcb_destroy_cbfn(rx->bna->bnad, q1->rcb);
q1->rcb = NULL;
q1->rxp = NULL;
q1->rx = NULL;
bna_rxq_put(rx_mod, q1);
}
rxp->rxq.slr.large = NULL;
rxp->rxq.slr.small = NULL;
if (rx->ccb_destroy_cbfn)
rx->ccb_destroy_cbfn(rx->bna->bnad, rxp->cq.ccb);
rxp->cq.ccb = NULL;
rxp->rx = NULL;
bna_rxp_put(rx_mod, rxp);
}
list_for_each(qe, &rx_mod->rx_active_q)
if (qe == &rx->qe) {
list_del(&rx->qe);
break;
}
rx_mod->rid_mask &= ~BIT(rx->rid);
rx->bna = NULL;
rx->priv = NULL;
bna_rx_put(rx_mod, rx);
}
void
bna_rx_enable(struct bna_rx *rx)
{
if (rx->fsm != bna_rx_sm_stopped)
return;
rx->rx_flags |= BNA_RX_F_ENABLED;
if (rx->rx_flags & BNA_RX_F_ENET_STARTED)
bfa_fsm_send_event(rx, RX_E_START);
}
void
bna_rx_disable(struct bna_rx *rx, enum bna_cleanup_type type,
void (*cbfn)(void *, struct bna_rx *))
{
if (type == BNA_SOFT_CLEANUP) {
/* h/w should not be accessed. Treat we're stopped */
(*cbfn)(rx->bna->bnad, rx);
} else {
rx->stop_cbfn = cbfn;
rx->stop_cbarg = rx->bna->bnad;
rx->rx_flags &= ~BNA_RX_F_ENABLED;
bfa_fsm_send_event(rx, RX_E_STOP);
}
}
void
bna_rx_cleanup_complete(struct bna_rx *rx)
{
bfa_fsm_send_event(rx, RX_E_CLEANUP_DONE);
}
void
bna_rx_vlan_strip_enable(struct bna_rx *rx)
{
struct bna_rxf *rxf = &rx->rxf;
if (rxf->vlan_strip_status == BNA_STATUS_T_DISABLED) {
rxf->vlan_strip_status = BNA_STATUS_T_ENABLED;
rxf->vlan_strip_pending = true;
bfa_fsm_send_event(rxf, RXF_E_CONFIG);
}
}
void
bna_rx_vlan_strip_disable(struct bna_rx *rx)
{
struct bna_rxf *rxf = &rx->rxf;
if (rxf->vlan_strip_status != BNA_STATUS_T_DISABLED) {
rxf->vlan_strip_status = BNA_STATUS_T_DISABLED;
rxf->vlan_strip_pending = true;
bfa_fsm_send_event(rxf, RXF_E_CONFIG);
}
}
enum bna_cb_status
bna_rx_mode_set(struct bna_rx *rx, enum bna_rxmode new_mode,
enum bna_rxmode bitmask)
{
struct bna_rxf *rxf = &rx->rxf;
int need_hw_config = 0;
/* Error checks */
if (is_promisc_enable(new_mode, bitmask)) {
/* If promisc mode is already enabled elsewhere in the system */
if ((rx->bna->promisc_rid != BFI_INVALID_RID) &&
(rx->bna->promisc_rid != rxf->rx->rid))
goto err_return;
/* If default mode is already enabled in the system */
if (rx->bna->default_mode_rid != BFI_INVALID_RID)
goto err_return;
/* Trying to enable promiscuous and default mode together */
if (is_default_enable(new_mode, bitmask))
goto err_return;
}
if (is_default_enable(new_mode, bitmask)) {
/* If default mode is already enabled elsewhere in the system */
if ((rx->bna->default_mode_rid != BFI_INVALID_RID) &&
(rx->bna->default_mode_rid != rxf->rx->rid)) {
goto err_return;
}
/* If promiscuous mode is already enabled in the system */
if (rx->bna->promisc_rid != BFI_INVALID_RID)
goto err_return;
}
/* Process the commands */
if (is_promisc_enable(new_mode, bitmask)) {
if (bna_rxf_promisc_enable(rxf))
need_hw_config = 1;
} else if (is_promisc_disable(new_mode, bitmask)) {
if (bna_rxf_promisc_disable(rxf))
need_hw_config = 1;
}
if (is_allmulti_enable(new_mode, bitmask)) {
if (bna_rxf_allmulti_enable(rxf))
need_hw_config = 1;
} else if (is_allmulti_disable(new_mode, bitmask)) {
if (bna_rxf_allmulti_disable(rxf))
need_hw_config = 1;
}
/* Trigger h/w if needed */
if (need_hw_config) {
rxf->cam_fltr_cbfn = NULL;
rxf->cam_fltr_cbarg = rx->bna->bnad;
bfa_fsm_send_event(rxf, RXF_E_CONFIG);
}
return BNA_CB_SUCCESS;
err_return:
return BNA_CB_FAIL;
}
void
bna_rx_vlanfilter_enable(struct bna_rx *rx)
{
struct bna_rxf *rxf = &rx->rxf;
if (rxf->vlan_filter_status == BNA_STATUS_T_DISABLED) {
rxf->vlan_filter_status = BNA_STATUS_T_ENABLED;
rxf->vlan_pending_bitmask = (u8)BFI_VLAN_BMASK_ALL;
bfa_fsm_send_event(rxf, RXF_E_CONFIG);
}
}
void
bna_rx_coalescing_timeo_set(struct bna_rx *rx, int coalescing_timeo)
{
struct bna_rxp *rxp;
list_for_each_entry(rxp, &rx->rxp_q, qe) {
rxp->cq.ccb->rx_coalescing_timeo = coalescing_timeo;
bna_ib_coalescing_timeo_set(&rxp->cq.ib, coalescing_timeo);
}
}
void
bna_rx_dim_reconfig(struct bna *bna, const u32 vector[][BNA_BIAS_T_MAX])
{
int i, j;
for (i = 0; i < BNA_LOAD_T_MAX; i++)
for (j = 0; j < BNA_BIAS_T_MAX; j++)
bna->rx_mod.dim_vector[i][j] = vector[i][j];
}
void
bna_rx_dim_update(struct bna_ccb *ccb)
{
struct bna *bna = ccb->cq->rx->bna;
u32 load, bias;
u32 pkt_rt, small_rt, large_rt;
u8 coalescing_timeo;
if ((ccb->pkt_rate.small_pkt_cnt == 0) &&
(ccb->pkt_rate.large_pkt_cnt == 0))
return;
/* Arrive at preconfigured coalescing timeo value based on pkt rate */
small_rt = ccb->pkt_rate.small_pkt_cnt;
large_rt = ccb->pkt_rate.large_pkt_cnt;
pkt_rt = small_rt + large_rt;
if (pkt_rt < BNA_PKT_RATE_10K)
load = BNA_LOAD_T_LOW_4;
else if (pkt_rt < BNA_PKT_RATE_20K)
load = BNA_LOAD_T_LOW_3;
else if (pkt_rt < BNA_PKT_RATE_30K)
load = BNA_LOAD_T_LOW_2;
else if (pkt_rt < BNA_PKT_RATE_40K)
load = BNA_LOAD_T_LOW_1;
else if (pkt_rt < BNA_PKT_RATE_50K)
load = BNA_LOAD_T_HIGH_1;
else if (pkt_rt < BNA_PKT_RATE_60K)
load = BNA_LOAD_T_HIGH_2;
else if (pkt_rt < BNA_PKT_RATE_80K)
load = BNA_LOAD_T_HIGH_3;
else
load = BNA_LOAD_T_HIGH_4;
if (small_rt > (large_rt << 1))
bias = 0;
else
bias = 1;
ccb->pkt_rate.small_pkt_cnt = 0;
ccb->pkt_rate.large_pkt_cnt = 0;
coalescing_timeo = bna->rx_mod.dim_vector[load][bias];
ccb->rx_coalescing_timeo = coalescing_timeo;
/* Set it to IB */
bna_ib_coalescing_timeo_set(&ccb->cq->ib, coalescing_timeo);
}
const u32 bna_napi_dim_vector[BNA_LOAD_T_MAX][BNA_BIAS_T_MAX] = {
{12, 12},
{6, 10},
{5, 10},
{4, 8},
{3, 6},
{3, 6},
{2, 4},
{1, 2},
};
/* TX */
#define call_tx_stop_cbfn(tx) \
do { \
if ((tx)->stop_cbfn) { \
void (*cbfn)(void *, struct bna_tx *); \
void *cbarg; \
cbfn = (tx)->stop_cbfn; \
cbarg = (tx)->stop_cbarg; \
(tx)->stop_cbfn = NULL; \
(tx)->stop_cbarg = NULL; \
cbfn(cbarg, (tx)); \
} \
} while (0)
static void bna_tx_mod_cb_tx_stopped(void *tx_mod, struct bna_tx *tx);
static void bna_bfi_tx_enet_start(struct bna_tx *tx);
static void bna_tx_enet_stop(struct bna_tx *tx);
enum bna_tx_event {
TX_E_START = 1,
TX_E_STOP = 2,
TX_E_FAIL = 3,
TX_E_STARTED = 4,
TX_E_STOPPED = 5,
TX_E_CLEANUP_DONE = 7,
TX_E_BW_UPDATE = 8,
};
bfa_fsm_state_decl(bna_tx, stopped, struct bna_tx, enum bna_tx_event);
bfa_fsm_state_decl(bna_tx, start_wait, struct bna_tx, enum bna_tx_event);
bfa_fsm_state_decl(bna_tx, started, struct bna_tx, enum bna_tx_event);
bfa_fsm_state_decl(bna_tx, stop_wait, struct bna_tx, enum bna_tx_event);
bfa_fsm_state_decl(bna_tx, cleanup_wait, struct bna_tx,
enum bna_tx_event);
bfa_fsm_state_decl(bna_tx, prio_stop_wait, struct bna_tx,
enum bna_tx_event);
bfa_fsm_state_decl(bna_tx, prio_cleanup_wait, struct bna_tx,
enum bna_tx_event);
bfa_fsm_state_decl(bna_tx, failed, struct bna_tx, enum bna_tx_event);
bfa_fsm_state_decl(bna_tx, quiesce_wait, struct bna_tx,
enum bna_tx_event);
static void
bna_tx_sm_stopped_entry(struct bna_tx *tx)
{
call_tx_stop_cbfn(tx);
}
static void
bna_tx_sm_stopped(struct bna_tx *tx, enum bna_tx_event event)
{
switch (event) {
case TX_E_START:
bfa_fsm_set_state(tx, bna_tx_sm_start_wait);
break;
case TX_E_STOP:
call_tx_stop_cbfn(tx);
break;
case TX_E_FAIL:
/* No-op */
break;
case TX_E_BW_UPDATE:
/* No-op */
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_tx_sm_start_wait_entry(struct bna_tx *tx)
{
bna_bfi_tx_enet_start(tx);
}
static void
bna_tx_sm_start_wait(struct bna_tx *tx, enum bna_tx_event event)
{
switch (event) {
case TX_E_STOP:
tx->flags &= ~BNA_TX_F_BW_UPDATED;
bfa_fsm_set_state(tx, bna_tx_sm_stop_wait);
break;
case TX_E_FAIL:
tx->flags &= ~BNA_TX_F_BW_UPDATED;
bfa_fsm_set_state(tx, bna_tx_sm_stopped);
break;
case TX_E_STARTED:
if (tx->flags & BNA_TX_F_BW_UPDATED) {
tx->flags &= ~BNA_TX_F_BW_UPDATED;
bfa_fsm_set_state(tx, bna_tx_sm_prio_stop_wait);
} else
bfa_fsm_set_state(tx, bna_tx_sm_started);
break;
case TX_E_BW_UPDATE:
tx->flags |= BNA_TX_F_BW_UPDATED;
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_tx_sm_started_entry(struct bna_tx *tx)
{
struct bna_txq *txq;
int is_regular = (tx->type == BNA_TX_T_REGULAR);
list_for_each_entry(txq, &tx->txq_q, qe) {
txq->tcb->priority = txq->priority;
/* Start IB */
bna_ib_start(tx->bna, &txq->ib, is_regular);
}
tx->tx_resume_cbfn(tx->bna->bnad, tx);
}
static void
bna_tx_sm_started(struct bna_tx *tx, enum bna_tx_event event)
{
switch (event) {
case TX_E_STOP:
bfa_fsm_set_state(tx, bna_tx_sm_stop_wait);
tx->tx_stall_cbfn(tx->bna->bnad, tx);
bna_tx_enet_stop(tx);
break;
case TX_E_FAIL:
bfa_fsm_set_state(tx, bna_tx_sm_failed);
tx->tx_stall_cbfn(tx->bna->bnad, tx);
tx->tx_cleanup_cbfn(tx->bna->bnad, tx);
break;
case TX_E_BW_UPDATE:
bfa_fsm_set_state(tx, bna_tx_sm_prio_stop_wait);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_tx_sm_stop_wait_entry(struct bna_tx *tx)
{
}
static void
bna_tx_sm_stop_wait(struct bna_tx *tx, enum bna_tx_event event)
{
switch (event) {
case TX_E_FAIL:
case TX_E_STOPPED:
bfa_fsm_set_state(tx, bna_tx_sm_cleanup_wait);
tx->tx_cleanup_cbfn(tx->bna->bnad, tx);
break;
case TX_E_STARTED:
/**
* We are here due to start_wait -> stop_wait transition on
* TX_E_STOP event
*/
bna_tx_enet_stop(tx);
break;
case TX_E_BW_UPDATE:
/* No-op */
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_tx_sm_cleanup_wait_entry(struct bna_tx *tx)
{
}
static void
bna_tx_sm_cleanup_wait(struct bna_tx *tx, enum bna_tx_event event)
{
switch (event) {
case TX_E_FAIL:
case TX_E_BW_UPDATE:
/* No-op */
break;
case TX_E_CLEANUP_DONE:
bfa_fsm_set_state(tx, bna_tx_sm_stopped);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_tx_sm_prio_stop_wait_entry(struct bna_tx *tx)
{
tx->tx_stall_cbfn(tx->bna->bnad, tx);
bna_tx_enet_stop(tx);
}
static void
bna_tx_sm_prio_stop_wait(struct bna_tx *tx, enum bna_tx_event event)
{
switch (event) {
case TX_E_STOP:
bfa_fsm_set_state(tx, bna_tx_sm_stop_wait);
break;
case TX_E_FAIL:
bfa_fsm_set_state(tx, bna_tx_sm_failed);
tx->tx_cleanup_cbfn(tx->bna->bnad, tx);
break;
case TX_E_STOPPED:
bfa_fsm_set_state(tx, bna_tx_sm_prio_cleanup_wait);
break;
case TX_E_BW_UPDATE:
/* No-op */
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_tx_sm_prio_cleanup_wait_entry(struct bna_tx *tx)
{
tx->tx_cleanup_cbfn(tx->bna->bnad, tx);
}
static void
bna_tx_sm_prio_cleanup_wait(struct bna_tx *tx, enum bna_tx_event event)
{
switch (event) {
case TX_E_STOP:
bfa_fsm_set_state(tx, bna_tx_sm_cleanup_wait);
break;
case TX_E_FAIL:
bfa_fsm_set_state(tx, bna_tx_sm_failed);
break;
case TX_E_BW_UPDATE:
/* No-op */
break;
case TX_E_CLEANUP_DONE:
bfa_fsm_set_state(tx, bna_tx_sm_start_wait);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_tx_sm_failed_entry(struct bna_tx *tx)
{
}
static void
bna_tx_sm_failed(struct bna_tx *tx, enum bna_tx_event event)
{
switch (event) {
case TX_E_START:
bfa_fsm_set_state(tx, bna_tx_sm_quiesce_wait);
break;
case TX_E_STOP:
bfa_fsm_set_state(tx, bna_tx_sm_cleanup_wait);
break;
case TX_E_FAIL:
/* No-op */
break;
case TX_E_CLEANUP_DONE:
bfa_fsm_set_state(tx, bna_tx_sm_stopped);
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_tx_sm_quiesce_wait_entry(struct bna_tx *tx)
{
}
static void
bna_tx_sm_quiesce_wait(struct bna_tx *tx, enum bna_tx_event event)
{
switch (event) {
case TX_E_STOP:
bfa_fsm_set_state(tx, bna_tx_sm_cleanup_wait);
break;
case TX_E_FAIL:
bfa_fsm_set_state(tx, bna_tx_sm_failed);
break;
case TX_E_CLEANUP_DONE:
bfa_fsm_set_state(tx, bna_tx_sm_start_wait);
break;
case TX_E_BW_UPDATE:
/* No-op */
break;
default:
bfa_sm_fault(event);
}
}
static void
bna_bfi_tx_enet_start(struct bna_tx *tx)
{
struct bfi_enet_tx_cfg_req *cfg_req = &tx->bfi_enet_cmd.cfg_req;
struct bna_txq *txq = NULL;
int i;
bfi_msgq_mhdr_set(cfg_req->mh, BFI_MC_ENET,
BFI_ENET_H2I_TX_CFG_SET_REQ, 0, tx->rid);
cfg_req->mh.num_entries = htons(
bfi_msgq_num_cmd_entries(sizeof(struct bfi_enet_tx_cfg_req)));
cfg_req->num_queues = tx->num_txq;
for (i = 0; i < tx->num_txq; i++) {
txq = txq ? list_next_entry(txq, qe)
: list_first_entry(&tx->txq_q, struct bna_txq, qe);
bfi_enet_datapath_q_init(&cfg_req->q_cfg[i].q.q, &txq->qpt);
cfg_req->q_cfg[i].q.priority = txq->priority;
cfg_req->q_cfg[i].ib.index_addr.a32.addr_lo =
txq->ib.ib_seg_host_addr.lsb;
cfg_req->q_cfg[i].ib.index_addr.a32.addr_hi =
txq->ib.ib_seg_host_addr.msb;
cfg_req->q_cfg[i].ib.intr.msix_index =
htons((u16)txq->ib.intr_vector);
}
cfg_req->ib_cfg.int_pkt_dma = BNA_STATUS_T_ENABLED;
cfg_req->ib_cfg.int_enabled = BNA_STATUS_T_ENABLED;
cfg_req->ib_cfg.int_pkt_enabled = BNA_STATUS_T_DISABLED;
cfg_req->ib_cfg.continuous_coalescing = BNA_STATUS_T_ENABLED;
cfg_req->ib_cfg.msix = (txq->ib.intr_type == BNA_INTR_T_MSIX)
? BNA_STATUS_T_ENABLED : BNA_STATUS_T_DISABLED;
cfg_req->ib_cfg.coalescing_timeout =
htonl((u32)txq->ib.coalescing_timeo);
cfg_req->ib_cfg.inter_pkt_timeout =
htonl((u32)txq->ib.interpkt_timeo);
cfg_req->ib_cfg.inter_pkt_count = (u8)txq->ib.interpkt_count;
cfg_req->tx_cfg.vlan_mode = BFI_ENET_TX_VLAN_WI;
cfg_req->tx_cfg.vlan_id = htons((u16)tx->txf_vlan_id);
cfg_req->tx_cfg.admit_tagged_frame = BNA_STATUS_T_ENABLED;
cfg_req->tx_cfg.apply_vlan_filter = BNA_STATUS_T_DISABLED;
bfa_msgq_cmd_set(&tx->msgq_cmd, NULL, NULL,
sizeof(struct bfi_enet_tx_cfg_req), &cfg_req->mh);
bfa_msgq_cmd_post(&tx->bna->msgq, &tx->msgq_cmd);
}
static void
bna_bfi_tx_enet_stop(struct bna_tx *tx)
{
struct bfi_enet_req *req = &tx->bfi_enet_cmd.req;
bfi_msgq_mhdr_set(req->mh, BFI_MC_ENET,
BFI_ENET_H2I_TX_CFG_CLR_REQ, 0, tx->rid);
req->mh.num_entries = htons(
bfi_msgq_num_cmd_entries(sizeof(struct bfi_enet_req)));
bfa_msgq_cmd_set(&tx->msgq_cmd, NULL, NULL, sizeof(struct bfi_enet_req),
&req->mh);
bfa_msgq_cmd_post(&tx->bna->msgq, &tx->msgq_cmd);
}
static void
bna_tx_enet_stop(struct bna_tx *tx)
{
struct bna_txq *txq;
/* Stop IB */
list_for_each_entry(txq, &tx->txq_q, qe)
bna_ib_stop(tx->bna, &txq->ib);
bna_bfi_tx_enet_stop(tx);
}
static void
bna_txq_qpt_setup(struct bna_txq *txq, int page_count, int page_size,
struct bna_mem_descr *qpt_mem,
struct bna_mem_descr *swqpt_mem,
struct bna_mem_descr *page_mem)
{
u8 *kva;
u64 dma;
struct bna_dma_addr bna_dma;
int i;
txq->qpt.hw_qpt_ptr.lsb = qpt_mem->dma.lsb;
txq->qpt.hw_qpt_ptr.msb = qpt_mem->dma.msb;
txq->qpt.kv_qpt_ptr = qpt_mem->kva;
txq->qpt.page_count = page_count;
txq->qpt.page_size = page_size;
txq->tcb->sw_qpt = (void **) swqpt_mem->kva;
txq->tcb->sw_q = page_mem->kva;
kva = page_mem->kva;
BNA_GET_DMA_ADDR(&page_mem->dma, dma);
for (i = 0; i < page_count; i++) {
txq->tcb->sw_qpt[i] = kva;
kva += PAGE_SIZE;
BNA_SET_DMA_ADDR(dma, &bna_dma);
((struct bna_dma_addr *)txq->qpt.kv_qpt_ptr)[i].lsb =
bna_dma.lsb;
((struct bna_dma_addr *)txq->qpt.kv_qpt_ptr)[i].msb =
bna_dma.msb;
dma += PAGE_SIZE;
}
}
static struct bna_tx *
bna_tx_get(struct bna_tx_mod *tx_mod, enum bna_tx_type type)
{
struct bna_tx *tx = NULL;
if (list_empty(&tx_mod->tx_free_q))
return NULL;
if (type == BNA_TX_T_REGULAR)
tx = list_first_entry(&tx_mod->tx_free_q, struct bna_tx, qe);
else
tx = list_last_entry(&tx_mod->tx_free_q, struct bna_tx, qe);
list_del(&tx->qe);
tx->type = type;
return tx;
}
static void
bna_tx_free(struct bna_tx *tx)
{
struct bna_tx_mod *tx_mod = &tx->bna->tx_mod;
struct bna_txq *txq;
struct list_head *qe;
while (!list_empty(&tx->txq_q)) {
txq = list_first_entry(&tx->txq_q, struct bna_txq, qe);
txq->tcb = NULL;
txq->tx = NULL;
list_move_tail(&txq->qe, &tx_mod->txq_free_q);
}
list_for_each(qe, &tx_mod->tx_active_q) {
if (qe == &tx->qe) {
list_del(&tx->qe);
break;
}
}
tx->bna = NULL;
tx->priv = NULL;
list_for_each_prev(qe, &tx_mod->tx_free_q)
if (((struct bna_tx *)qe)->rid < tx->rid)
break;
list_add(&tx->qe, qe);
}
static void
bna_tx_start(struct bna_tx *tx)
{
tx->flags |= BNA_TX_F_ENET_STARTED;
if (tx->flags & BNA_TX_F_ENABLED)
bfa_fsm_send_event(tx, TX_E_START);
}
static void
bna_tx_stop(struct bna_tx *tx)
{
tx->stop_cbfn = bna_tx_mod_cb_tx_stopped;
tx->stop_cbarg = &tx->bna->tx_mod;
tx->flags &= ~BNA_TX_F_ENET_STARTED;
bfa_fsm_send_event(tx, TX_E_STOP);
}
static void
bna_tx_fail(struct bna_tx *tx)
{
tx->flags &= ~BNA_TX_F_ENET_STARTED;
bfa_fsm_send_event(tx, TX_E_FAIL);
}
void
bna_bfi_tx_enet_start_rsp(struct bna_tx *tx, struct bfi_msgq_mhdr *msghdr)
{
struct bfi_enet_tx_cfg_rsp *cfg_rsp = &tx->bfi_enet_cmd.cfg_rsp;
struct bna_txq *txq = NULL;
int i;
bfa_msgq_rsp_copy(&tx->bna->msgq, (u8 *)cfg_rsp,
sizeof(struct bfi_enet_tx_cfg_rsp));
tx->hw_id = cfg_rsp->hw_id;
for (i = 0, txq = list_first_entry(&tx->txq_q, struct bna_txq, qe);
i < tx->num_txq; i++, txq = list_next_entry(txq, qe)) {
/* Setup doorbells */
txq->tcb->i_dbell->doorbell_addr =
tx->bna->pcidev.pci_bar_kva
+ ntohl(cfg_rsp->q_handles[i].i_dbell);
txq->tcb->q_dbell =
tx->bna->pcidev.pci_bar_kva
+ ntohl(cfg_rsp->q_handles[i].q_dbell);
txq->hw_id = cfg_rsp->q_handles[i].hw_qid;
/* Initialize producer/consumer indexes */
(*txq->tcb->hw_consumer_index) = 0;
txq->tcb->producer_index = txq->tcb->consumer_index = 0;
}
bfa_fsm_send_event(tx, TX_E_STARTED);
}
void
bna_bfi_tx_enet_stop_rsp(struct bna_tx *tx, struct bfi_msgq_mhdr *msghdr)
{
bfa_fsm_send_event(tx, TX_E_STOPPED);
}
void
bna_bfi_bw_update_aen(struct bna_tx_mod *tx_mod)
{
struct bna_tx *tx;
list_for_each_entry(tx, &tx_mod->tx_active_q, qe)
bfa_fsm_send_event(tx, TX_E_BW_UPDATE);
}
void
bna_tx_res_req(int num_txq, int txq_depth, struct bna_res_info *res_info)
{
u32 q_size;
u32 page_count;
struct bna_mem_info *mem_info;
res_info[BNA_TX_RES_MEM_T_TCB].res_type = BNA_RES_T_MEM;
mem_info = &res_info[BNA_TX_RES_MEM_T_TCB].res_u.mem_info;
mem_info->mem_type = BNA_MEM_T_KVA;
mem_info->len = sizeof(struct bna_tcb);
mem_info->num = num_txq;
q_size = txq_depth * BFI_TXQ_WI_SIZE;
q_size = ALIGN(q_size, PAGE_SIZE);
page_count = q_size >> PAGE_SHIFT;
res_info[BNA_TX_RES_MEM_T_QPT].res_type = BNA_RES_T_MEM;
mem_info = &res_info[BNA_TX_RES_MEM_T_QPT].res_u.mem_info;
mem_info->mem_type = BNA_MEM_T_DMA;
mem_info->len = page_count * sizeof(struct bna_dma_addr);
mem_info->num = num_txq;
res_info[BNA_TX_RES_MEM_T_SWQPT].res_type = BNA_RES_T_MEM;
mem_info = &res_info[BNA_TX_RES_MEM_T_SWQPT].res_u.mem_info;
mem_info->mem_type = BNA_MEM_T_KVA;
mem_info->len = page_count * sizeof(void *);
mem_info->num = num_txq;
res_info[BNA_TX_RES_MEM_T_PAGE].res_type = BNA_RES_T_MEM;
mem_info = &res_info[BNA_TX_RES_MEM_T_PAGE].res_u.mem_info;
mem_info->mem_type = BNA_MEM_T_DMA;
mem_info->len = PAGE_SIZE * page_count;
mem_info->num = num_txq;
res_info[BNA_TX_RES_MEM_T_IBIDX].res_type = BNA_RES_T_MEM;
mem_info = &res_info[BNA_TX_RES_MEM_T_IBIDX].res_u.mem_info;
mem_info->mem_type = BNA_MEM_T_DMA;
mem_info->len = BFI_IBIDX_SIZE;
mem_info->num = num_txq;
res_info[BNA_TX_RES_INTR_T_TXCMPL].res_type = BNA_RES_T_INTR;
res_info[BNA_TX_RES_INTR_T_TXCMPL].res_u.intr_info.intr_type =
BNA_INTR_T_MSIX;
res_info[BNA_TX_RES_INTR_T_TXCMPL].res_u.intr_info.num = num_txq;
}
struct bna_tx *
bna_tx_create(struct bna *bna, struct bnad *bnad,
struct bna_tx_config *tx_cfg,
const struct bna_tx_event_cbfn *tx_cbfn,
struct bna_res_info *res_info, void *priv)
{
struct bna_intr_info *intr_info;
struct bna_tx_mod *tx_mod = &bna->tx_mod;
struct bna_tx *tx;
struct bna_txq *txq;
int page_count;
int i;
intr_info = &res_info[BNA_TX_RES_INTR_T_TXCMPL].res_u.intr_info;
page_count = (res_info[BNA_TX_RES_MEM_T_PAGE].res_u.mem_info.len) /
PAGE_SIZE;
/**
* Get resources
*/
if ((intr_info->num != 1) && (intr_info->num != tx_cfg->num_txq))
return NULL;
/* Tx */
tx = bna_tx_get(tx_mod, tx_cfg->tx_type);
if (!tx)
return NULL;
tx->bna = bna;
tx->priv = priv;
/* TxQs */
INIT_LIST_HEAD(&tx->txq_q);
for (i = 0; i < tx_cfg->num_txq; i++) {
if (list_empty(&tx_mod->txq_free_q))
goto err_return;
txq = list_first_entry(&tx_mod->txq_free_q, struct bna_txq, qe);
list_move_tail(&txq->qe, &tx->txq_q);
txq->tx = tx;
}
/*
* Initialize
*/
/* Tx */
tx->tcb_setup_cbfn = tx_cbfn->tcb_setup_cbfn;
tx->tcb_destroy_cbfn = tx_cbfn->tcb_destroy_cbfn;
/* Following callbacks are mandatory */
tx->tx_stall_cbfn = tx_cbfn->tx_stall_cbfn;
tx->tx_resume_cbfn = tx_cbfn->tx_resume_cbfn;
tx->tx_cleanup_cbfn = tx_cbfn->tx_cleanup_cbfn;
list_add_tail(&tx->qe, &tx_mod->tx_active_q);
tx->num_txq = tx_cfg->num_txq;
tx->flags = 0;
if (tx->bna->tx_mod.flags & BNA_TX_MOD_F_ENET_STARTED) {
switch (tx->type) {
case BNA_TX_T_REGULAR:
if (!(tx->bna->tx_mod.flags &
BNA_TX_MOD_F_ENET_LOOPBACK))
tx->flags |= BNA_TX_F_ENET_STARTED;
break;
case BNA_TX_T_LOOPBACK:
if (tx->bna->tx_mod.flags & BNA_TX_MOD_F_ENET_LOOPBACK)
tx->flags |= BNA_TX_F_ENET_STARTED;
break;
}
}
/* TxQ */
i = 0;
list_for_each_entry(txq, &tx->txq_q, qe) {
txq->tcb = (struct bna_tcb *)
res_info[BNA_TX_RES_MEM_T_TCB].res_u.mem_info.mdl[i].kva;
txq->tx_packets = 0;
txq->tx_bytes = 0;
/* IB */
txq->ib.ib_seg_host_addr.lsb =
res_info[BNA_TX_RES_MEM_T_IBIDX].res_u.mem_info.mdl[i].dma.lsb;
txq->ib.ib_seg_host_addr.msb =
res_info[BNA_TX_RES_MEM_T_IBIDX].res_u.mem_info.mdl[i].dma.msb;
txq->ib.ib_seg_host_addr_kva =
res_info[BNA_TX_RES_MEM_T_IBIDX].res_u.mem_info.mdl[i].kva;
txq->ib.intr_type = intr_info->intr_type;
txq->ib.intr_vector = (intr_info->num == 1) ?
intr_info->idl[0].vector :
intr_info->idl[i].vector;
if (intr_info->intr_type == BNA_INTR_T_INTX)
txq->ib.intr_vector = BIT(txq->ib.intr_vector);
txq->ib.coalescing_timeo = tx_cfg->coalescing_timeo;
txq->ib.interpkt_timeo = BFI_TX_INTERPKT_TIMEO;
txq->ib.interpkt_count = BFI_TX_INTERPKT_COUNT;
/* TCB */
txq->tcb->q_depth = tx_cfg->txq_depth;
txq->tcb->unmap_q = (void *)
res_info[BNA_TX_RES_MEM_T_UNMAPQ].res_u.mem_info.mdl[i].kva;
txq->tcb->hw_consumer_index =
(u32 *)txq->ib.ib_seg_host_addr_kva;
txq->tcb->i_dbell = &txq->ib.door_bell;
txq->tcb->intr_type = txq->ib.intr_type;
txq->tcb->intr_vector = txq->ib.intr_vector;
txq->tcb->txq = txq;
txq->tcb->bnad = bnad;
txq->tcb->id = i;
/* QPT, SWQPT, Pages */
bna_txq_qpt_setup(txq, page_count, PAGE_SIZE,
&res_info[BNA_TX_RES_MEM_T_QPT].res_u.mem_info.mdl[i],
&res_info[BNA_TX_RES_MEM_T_SWQPT].res_u.mem_info.mdl[i],
&res_info[BNA_TX_RES_MEM_T_PAGE].
res_u.mem_info.mdl[i]);
/* Callback to bnad for setting up TCB */
if (tx->tcb_setup_cbfn)
(tx->tcb_setup_cbfn)(bna->bnad, txq->tcb);
if (tx_cfg->num_txq == BFI_TX_MAX_PRIO)
txq->priority = txq->tcb->id;
else
txq->priority = tx_mod->default_prio;
i++;
}
tx->txf_vlan_id = 0;
bfa_fsm_set_state(tx, bna_tx_sm_stopped);
tx_mod->rid_mask |= BIT(tx->rid);
return tx;
err_return:
bna_tx_free(tx);
return NULL;
}
void
bna_tx_destroy(struct bna_tx *tx)
{
struct bna_txq *txq;
list_for_each_entry(txq, &tx->txq_q, qe)
if (tx->tcb_destroy_cbfn)
(tx->tcb_destroy_cbfn)(tx->bna->bnad, txq->tcb);
tx->bna->tx_mod.rid_mask &= ~BIT(tx->rid);
bna_tx_free(tx);
}
void
bna_tx_enable(struct bna_tx *tx)
{
if (tx->fsm != bna_tx_sm_stopped)
return;
tx->flags |= BNA_TX_F_ENABLED;
if (tx->flags & BNA_TX_F_ENET_STARTED)
bfa_fsm_send_event(tx, TX_E_START);
}
void
bna_tx_disable(struct bna_tx *tx, enum bna_cleanup_type type,
void (*cbfn)(void *, struct bna_tx *))
{
if (type == BNA_SOFT_CLEANUP) {
(*cbfn)(tx->bna->bnad, tx);
return;
}
tx->stop_cbfn = cbfn;
tx->stop_cbarg = tx->bna->bnad;
tx->flags &= ~BNA_TX_F_ENABLED;
bfa_fsm_send_event(tx, TX_E_STOP);
}
void
bna_tx_cleanup_complete(struct bna_tx *tx)
{
bfa_fsm_send_event(tx, TX_E_CLEANUP_DONE);
}
static void
bna_tx_mod_cb_tx_stopped(void *arg, struct bna_tx *tx)
{
struct bna_tx_mod *tx_mod = (struct bna_tx_mod *)arg;
bfa_wc_down(&tx_mod->tx_stop_wc);
}
static void
bna_tx_mod_cb_tx_stopped_all(void *arg)
{
struct bna_tx_mod *tx_mod = (struct bna_tx_mod *)arg;
if (tx_mod->stop_cbfn)
tx_mod->stop_cbfn(&tx_mod->bna->enet);
tx_mod->stop_cbfn = NULL;
}
void
bna_tx_mod_init(struct bna_tx_mod *tx_mod, struct bna *bna,
struct bna_res_info *res_info)
{
int i;
tx_mod->bna = bna;
tx_mod->flags = 0;
tx_mod->tx = (struct bna_tx *)
res_info[BNA_MOD_RES_MEM_T_TX_ARRAY].res_u.mem_info.mdl[0].kva;
tx_mod->txq = (struct bna_txq *)
res_info[BNA_MOD_RES_MEM_T_TXQ_ARRAY].res_u.mem_info.mdl[0].kva;
INIT_LIST_HEAD(&tx_mod->tx_free_q);
INIT_LIST_HEAD(&tx_mod->tx_active_q);
INIT_LIST_HEAD(&tx_mod->txq_free_q);
for (i = 0; i < bna->ioceth.attr.num_txq; i++) {
tx_mod->tx[i].rid = i;
list_add_tail(&tx_mod->tx[i].qe, &tx_mod->tx_free_q);
list_add_tail(&tx_mod->txq[i].qe, &tx_mod->txq_free_q);
}
tx_mod->prio_map = BFI_TX_PRIO_MAP_ALL;
tx_mod->default_prio = 0;
tx_mod->iscsi_over_cee = BNA_STATUS_T_DISABLED;
tx_mod->iscsi_prio = -1;
}
void
bna_tx_mod_uninit(struct bna_tx_mod *tx_mod)
{
tx_mod->bna = NULL;
}
void
bna_tx_mod_start(struct bna_tx_mod *tx_mod, enum bna_tx_type type)
{
struct bna_tx *tx;
tx_mod->flags |= BNA_TX_MOD_F_ENET_STARTED;
if (type == BNA_TX_T_LOOPBACK)
tx_mod->flags |= BNA_TX_MOD_F_ENET_LOOPBACK;
list_for_each_entry(tx, &tx_mod->tx_active_q, qe)
if (tx->type == type)
bna_tx_start(tx);
}
void
bna_tx_mod_stop(struct bna_tx_mod *tx_mod, enum bna_tx_type type)
{
struct bna_tx *tx;
tx_mod->flags &= ~BNA_TX_MOD_F_ENET_STARTED;
tx_mod->flags &= ~BNA_TX_MOD_F_ENET_LOOPBACK;
tx_mod->stop_cbfn = bna_enet_cb_tx_stopped;
bfa_wc_init(&tx_mod->tx_stop_wc, bna_tx_mod_cb_tx_stopped_all, tx_mod);
list_for_each_entry(tx, &tx_mod->tx_active_q, qe)
if (tx->type == type) {
bfa_wc_up(&tx_mod->tx_stop_wc);
bna_tx_stop(tx);
}
bfa_wc_wait(&tx_mod->tx_stop_wc);
}
void
bna_tx_mod_fail(struct bna_tx_mod *tx_mod)
{
struct bna_tx *tx;
tx_mod->flags &= ~BNA_TX_MOD_F_ENET_STARTED;
tx_mod->flags &= ~BNA_TX_MOD_F_ENET_LOOPBACK;
list_for_each_entry(tx, &tx_mod->tx_active_q, qe)
bna_tx_fail(tx);
}
void
bna_tx_coalescing_timeo_set(struct bna_tx *tx, int coalescing_timeo)
{
struct bna_txq *txq;
list_for_each_entry(txq, &tx->txq_q, qe)
bna_ib_coalescing_timeo_set(&txq->ib, coalescing_timeo);
}
|
linux-master
|
drivers/net/ethernet/brocade/bna/bna_tx_rx.c
|
// SPDX-License-Identifier: (GPL-2.0 OR MIT)
/* Google virtual Ethernet (gve) driver
*
* Copyright (C) 2015-2021 Google, Inc.
*/
#include <linux/ethtool.h>
#include <linux/rtnetlink.h>
#include "gve.h"
#include "gve_adminq.h"
#include "gve_dqo.h"
static void gve_get_drvinfo(struct net_device *netdev,
struct ethtool_drvinfo *info)
{
struct gve_priv *priv = netdev_priv(netdev);
strscpy(info->driver, gve_driver_name, sizeof(info->driver));
strscpy(info->version, gve_version_str, sizeof(info->version));
strscpy(info->bus_info, pci_name(priv->pdev), sizeof(info->bus_info));
}
static void gve_set_msglevel(struct net_device *netdev, u32 value)
{
struct gve_priv *priv = netdev_priv(netdev);
priv->msg_enable = value;
}
static u32 gve_get_msglevel(struct net_device *netdev)
{
struct gve_priv *priv = netdev_priv(netdev);
return priv->msg_enable;
}
/* For the following stats column string names, make sure the order
* matches how it is filled in the code. For xdp_aborted, xdp_drop,
* xdp_pass, xdp_tx, xdp_redirect, make sure it also matches the order
* as declared in enum xdp_action inside file uapi/linux/bpf.h .
*/
static const char gve_gstrings_main_stats[][ETH_GSTRING_LEN] = {
"rx_packets", "tx_packets", "rx_bytes", "tx_bytes",
"rx_dropped", "tx_dropped", "tx_timeouts",
"rx_skb_alloc_fail", "rx_buf_alloc_fail", "rx_desc_err_dropped_pkt",
"interface_up_cnt", "interface_down_cnt", "reset_cnt",
"page_alloc_fail", "dma_mapping_error", "stats_report_trigger_cnt",
};
static const char gve_gstrings_rx_stats[][ETH_GSTRING_LEN] = {
"rx_posted_desc[%u]", "rx_completed_desc[%u]", "rx_consumed_desc[%u]", "rx_bytes[%u]",
"rx_cont_packet_cnt[%u]", "rx_frag_flip_cnt[%u]", "rx_frag_copy_cnt[%u]",
"rx_frag_alloc_cnt[%u]",
"rx_dropped_pkt[%u]", "rx_copybreak_pkt[%u]", "rx_copied_pkt[%u]",
"rx_queue_drop_cnt[%u]", "rx_no_buffers_posted[%u]",
"rx_drops_packet_over_mru[%u]", "rx_drops_invalid_checksum[%u]",
"rx_xdp_aborted[%u]", "rx_xdp_drop[%u]", "rx_xdp_pass[%u]",
"rx_xdp_tx[%u]", "rx_xdp_redirect[%u]",
"rx_xdp_tx_errors[%u]", "rx_xdp_redirect_errors[%u]", "rx_xdp_alloc_fails[%u]",
};
static const char gve_gstrings_tx_stats[][ETH_GSTRING_LEN] = {
"tx_posted_desc[%u]", "tx_completed_desc[%u]", "tx_consumed_desc[%u]", "tx_bytes[%u]",
"tx_wake[%u]", "tx_stop[%u]", "tx_event_counter[%u]",
"tx_dma_mapping_error[%u]", "tx_xsk_wakeup[%u]",
"tx_xsk_done[%u]", "tx_xsk_sent[%u]", "tx_xdp_xmit[%u]", "tx_xdp_xmit_errors[%u]"
};
static const char gve_gstrings_adminq_stats[][ETH_GSTRING_LEN] = {
"adminq_prod_cnt", "adminq_cmd_fail", "adminq_timeouts",
"adminq_describe_device_cnt", "adminq_cfg_device_resources_cnt",
"adminq_register_page_list_cnt", "adminq_unregister_page_list_cnt",
"adminq_create_tx_queue_cnt", "adminq_create_rx_queue_cnt",
"adminq_destroy_tx_queue_cnt", "adminq_destroy_rx_queue_cnt",
"adminq_dcfg_device_resources_cnt", "adminq_set_driver_parameter_cnt",
"adminq_report_stats_cnt", "adminq_report_link_speed_cnt"
};
static const char gve_gstrings_priv_flags[][ETH_GSTRING_LEN] = {
"report-stats",
};
#define GVE_MAIN_STATS_LEN ARRAY_SIZE(gve_gstrings_main_stats)
#define GVE_ADMINQ_STATS_LEN ARRAY_SIZE(gve_gstrings_adminq_stats)
#define NUM_GVE_TX_CNTS ARRAY_SIZE(gve_gstrings_tx_stats)
#define NUM_GVE_RX_CNTS ARRAY_SIZE(gve_gstrings_rx_stats)
#define GVE_PRIV_FLAGS_STR_LEN ARRAY_SIZE(gve_gstrings_priv_flags)
static void gve_get_strings(struct net_device *netdev, u32 stringset, u8 *data)
{
struct gve_priv *priv = netdev_priv(netdev);
char *s = (char *)data;
int num_tx_queues;
int i, j;
num_tx_queues = gve_num_tx_queues(priv);
switch (stringset) {
case ETH_SS_STATS:
memcpy(s, *gve_gstrings_main_stats,
sizeof(gve_gstrings_main_stats));
s += sizeof(gve_gstrings_main_stats);
for (i = 0; i < priv->rx_cfg.num_queues; i++) {
for (j = 0; j < NUM_GVE_RX_CNTS; j++) {
snprintf(s, ETH_GSTRING_LEN,
gve_gstrings_rx_stats[j], i);
s += ETH_GSTRING_LEN;
}
}
for (i = 0; i < num_tx_queues; i++) {
for (j = 0; j < NUM_GVE_TX_CNTS; j++) {
snprintf(s, ETH_GSTRING_LEN,
gve_gstrings_tx_stats[j], i);
s += ETH_GSTRING_LEN;
}
}
memcpy(s, *gve_gstrings_adminq_stats,
sizeof(gve_gstrings_adminq_stats));
s += sizeof(gve_gstrings_adminq_stats);
break;
case ETH_SS_PRIV_FLAGS:
memcpy(s, *gve_gstrings_priv_flags,
sizeof(gve_gstrings_priv_flags));
s += sizeof(gve_gstrings_priv_flags);
break;
default:
break;
}
}
static int gve_get_sset_count(struct net_device *netdev, int sset)
{
struct gve_priv *priv = netdev_priv(netdev);
int num_tx_queues;
num_tx_queues = gve_num_tx_queues(priv);
switch (sset) {
case ETH_SS_STATS:
return GVE_MAIN_STATS_LEN + GVE_ADMINQ_STATS_LEN +
(priv->rx_cfg.num_queues * NUM_GVE_RX_CNTS) +
(num_tx_queues * NUM_GVE_TX_CNTS);
case ETH_SS_PRIV_FLAGS:
return GVE_PRIV_FLAGS_STR_LEN;
default:
return -EOPNOTSUPP;
}
}
static void
gve_get_ethtool_stats(struct net_device *netdev,
struct ethtool_stats *stats, u64 *data)
{
u64 tmp_rx_pkts, tmp_rx_bytes, tmp_rx_skb_alloc_fail,
tmp_rx_buf_alloc_fail, tmp_rx_desc_err_dropped_pkt,
tmp_tx_pkts, tmp_tx_bytes;
u64 rx_buf_alloc_fail, rx_desc_err_dropped_pkt, rx_pkts,
rx_skb_alloc_fail, rx_bytes, tx_pkts, tx_bytes, tx_dropped;
int stats_idx, base_stats_idx, max_stats_idx;
struct stats *report_stats;
int *rx_qid_to_stats_idx;
int *tx_qid_to_stats_idx;
struct gve_priv *priv;
bool skip_nic_stats;
unsigned int start;
int num_tx_queues;
int ring;
int i, j;
ASSERT_RTNL();
priv = netdev_priv(netdev);
num_tx_queues = gve_num_tx_queues(priv);
report_stats = priv->stats_report->stats;
rx_qid_to_stats_idx = kmalloc_array(priv->rx_cfg.num_queues,
sizeof(int), GFP_KERNEL);
if (!rx_qid_to_stats_idx)
return;
tx_qid_to_stats_idx = kmalloc_array(num_tx_queues,
sizeof(int), GFP_KERNEL);
if (!tx_qid_to_stats_idx) {
kfree(rx_qid_to_stats_idx);
return;
}
for (rx_pkts = 0, rx_bytes = 0, rx_skb_alloc_fail = 0,
rx_buf_alloc_fail = 0, rx_desc_err_dropped_pkt = 0, ring = 0;
ring < priv->rx_cfg.num_queues; ring++) {
if (priv->rx) {
do {
struct gve_rx_ring *rx = &priv->rx[ring];
start =
u64_stats_fetch_begin(&priv->rx[ring].statss);
tmp_rx_pkts = rx->rpackets;
tmp_rx_bytes = rx->rbytes;
tmp_rx_skb_alloc_fail = rx->rx_skb_alloc_fail;
tmp_rx_buf_alloc_fail = rx->rx_buf_alloc_fail;
tmp_rx_desc_err_dropped_pkt =
rx->rx_desc_err_dropped_pkt;
} while (u64_stats_fetch_retry(&priv->rx[ring].statss,
start));
rx_pkts += tmp_rx_pkts;
rx_bytes += tmp_rx_bytes;
rx_skb_alloc_fail += tmp_rx_skb_alloc_fail;
rx_buf_alloc_fail += tmp_rx_buf_alloc_fail;
rx_desc_err_dropped_pkt += tmp_rx_desc_err_dropped_pkt;
}
}
for (tx_pkts = 0, tx_bytes = 0, tx_dropped = 0, ring = 0;
ring < num_tx_queues; ring++) {
if (priv->tx) {
do {
start =
u64_stats_fetch_begin(&priv->tx[ring].statss);
tmp_tx_pkts = priv->tx[ring].pkt_done;
tmp_tx_bytes = priv->tx[ring].bytes_done;
} while (u64_stats_fetch_retry(&priv->tx[ring].statss,
start));
tx_pkts += tmp_tx_pkts;
tx_bytes += tmp_tx_bytes;
tx_dropped += priv->tx[ring].dropped_pkt;
}
}
i = 0;
data[i++] = rx_pkts;
data[i++] = tx_pkts;
data[i++] = rx_bytes;
data[i++] = tx_bytes;
/* total rx dropped packets */
data[i++] = rx_skb_alloc_fail + rx_buf_alloc_fail +
rx_desc_err_dropped_pkt;
data[i++] = tx_dropped;
data[i++] = priv->tx_timeo_cnt;
data[i++] = rx_skb_alloc_fail;
data[i++] = rx_buf_alloc_fail;
data[i++] = rx_desc_err_dropped_pkt;
data[i++] = priv->interface_up_cnt;
data[i++] = priv->interface_down_cnt;
data[i++] = priv->reset_cnt;
data[i++] = priv->page_alloc_fail;
data[i++] = priv->dma_mapping_error;
data[i++] = priv->stats_report_trigger_cnt;
i = GVE_MAIN_STATS_LEN;
/* For rx cross-reporting stats, start from nic rx stats in report */
base_stats_idx = GVE_TX_STATS_REPORT_NUM * num_tx_queues +
GVE_RX_STATS_REPORT_NUM * priv->rx_cfg.num_queues;
max_stats_idx = NIC_RX_STATS_REPORT_NUM * priv->rx_cfg.num_queues +
base_stats_idx;
/* Preprocess the stats report for rx, map queue id to start index */
skip_nic_stats = false;
for (stats_idx = base_stats_idx; stats_idx < max_stats_idx;
stats_idx += NIC_RX_STATS_REPORT_NUM) {
u32 stat_name = be32_to_cpu(report_stats[stats_idx].stat_name);
u32 queue_id = be32_to_cpu(report_stats[stats_idx].queue_id);
if (stat_name == 0) {
/* no stats written by NIC yet */
skip_nic_stats = true;
break;
}
rx_qid_to_stats_idx[queue_id] = stats_idx;
}
/* walk RX rings */
if (priv->rx) {
for (ring = 0; ring < priv->rx_cfg.num_queues; ring++) {
struct gve_rx_ring *rx = &priv->rx[ring];
data[i++] = rx->fill_cnt;
data[i++] = rx->cnt;
data[i++] = rx->fill_cnt - rx->cnt;
do {
start =
u64_stats_fetch_begin(&priv->rx[ring].statss);
tmp_rx_bytes = rx->rbytes;
tmp_rx_skb_alloc_fail = rx->rx_skb_alloc_fail;
tmp_rx_buf_alloc_fail = rx->rx_buf_alloc_fail;
tmp_rx_desc_err_dropped_pkt =
rx->rx_desc_err_dropped_pkt;
} while (u64_stats_fetch_retry(&priv->rx[ring].statss,
start));
data[i++] = tmp_rx_bytes;
data[i++] = rx->rx_cont_packet_cnt;
data[i++] = rx->rx_frag_flip_cnt;
data[i++] = rx->rx_frag_copy_cnt;
data[i++] = rx->rx_frag_alloc_cnt;
/* rx dropped packets */
data[i++] = tmp_rx_skb_alloc_fail +
tmp_rx_buf_alloc_fail +
tmp_rx_desc_err_dropped_pkt;
data[i++] = rx->rx_copybreak_pkt;
data[i++] = rx->rx_copied_pkt;
/* stats from NIC */
if (skip_nic_stats) {
/* skip NIC rx stats */
i += NIC_RX_STATS_REPORT_NUM;
} else {
stats_idx = rx_qid_to_stats_idx[ring];
for (j = 0; j < NIC_RX_STATS_REPORT_NUM; j++) {
u64 value =
be64_to_cpu(report_stats[stats_idx + j].value);
data[i++] = value;
}
}
/* XDP rx counters */
do {
start = u64_stats_fetch_begin(&priv->rx[ring].statss);
for (j = 0; j < GVE_XDP_ACTIONS; j++)
data[i + j] = rx->xdp_actions[j];
data[i + j++] = rx->xdp_tx_errors;
data[i + j++] = rx->xdp_redirect_errors;
data[i + j++] = rx->xdp_alloc_fails;
} while (u64_stats_fetch_retry(&priv->rx[ring].statss,
start));
i += GVE_XDP_ACTIONS + 3; /* XDP rx counters */
}
} else {
i += priv->rx_cfg.num_queues * NUM_GVE_RX_CNTS;
}
/* For tx cross-reporting stats, start from nic tx stats in report */
base_stats_idx = max_stats_idx;
max_stats_idx = NIC_TX_STATS_REPORT_NUM * num_tx_queues +
max_stats_idx;
/* Preprocess the stats report for tx, map queue id to start index */
skip_nic_stats = false;
for (stats_idx = base_stats_idx; stats_idx < max_stats_idx;
stats_idx += NIC_TX_STATS_REPORT_NUM) {
u32 stat_name = be32_to_cpu(report_stats[stats_idx].stat_name);
u32 queue_id = be32_to_cpu(report_stats[stats_idx].queue_id);
if (stat_name == 0) {
/* no stats written by NIC yet */
skip_nic_stats = true;
break;
}
tx_qid_to_stats_idx[queue_id] = stats_idx;
}
/* walk TX rings */
if (priv->tx) {
for (ring = 0; ring < num_tx_queues; ring++) {
struct gve_tx_ring *tx = &priv->tx[ring];
if (gve_is_gqi(priv)) {
data[i++] = tx->req;
data[i++] = tx->done;
data[i++] = tx->req - tx->done;
} else {
/* DQO doesn't currently support
* posted/completed descriptor counts;
*/
data[i++] = 0;
data[i++] = 0;
data[i++] = tx->dqo_tx.tail - tx->dqo_tx.head;
}
do {
start =
u64_stats_fetch_begin(&priv->tx[ring].statss);
tmp_tx_bytes = tx->bytes_done;
} while (u64_stats_fetch_retry(&priv->tx[ring].statss,
start));
data[i++] = tmp_tx_bytes;
data[i++] = tx->wake_queue;
data[i++] = tx->stop_queue;
data[i++] = gve_tx_load_event_counter(priv, tx);
data[i++] = tx->dma_mapping_error;
/* stats from NIC */
if (skip_nic_stats) {
/* skip NIC tx stats */
i += NIC_TX_STATS_REPORT_NUM;
} else {
stats_idx = tx_qid_to_stats_idx[ring];
for (j = 0; j < NIC_TX_STATS_REPORT_NUM; j++) {
u64 value =
be64_to_cpu(report_stats[stats_idx + j].value);
data[i++] = value;
}
}
/* XDP xsk counters */
data[i++] = tx->xdp_xsk_wakeup;
data[i++] = tx->xdp_xsk_done;
do {
start = u64_stats_fetch_begin(&priv->tx[ring].statss);
data[i] = tx->xdp_xsk_sent;
data[i + 1] = tx->xdp_xmit;
data[i + 2] = tx->xdp_xmit_errors;
} while (u64_stats_fetch_retry(&priv->tx[ring].statss,
start));
i += 3; /* XDP tx counters */
}
} else {
i += num_tx_queues * NUM_GVE_TX_CNTS;
}
kfree(rx_qid_to_stats_idx);
kfree(tx_qid_to_stats_idx);
/* AQ Stats */
data[i++] = priv->adminq_prod_cnt;
data[i++] = priv->adminq_cmd_fail;
data[i++] = priv->adminq_timeouts;
data[i++] = priv->adminq_describe_device_cnt;
data[i++] = priv->adminq_cfg_device_resources_cnt;
data[i++] = priv->adminq_register_page_list_cnt;
data[i++] = priv->adminq_unregister_page_list_cnt;
data[i++] = priv->adminq_create_tx_queue_cnt;
data[i++] = priv->adminq_create_rx_queue_cnt;
data[i++] = priv->adminq_destroy_tx_queue_cnt;
data[i++] = priv->adminq_destroy_rx_queue_cnt;
data[i++] = priv->adminq_dcfg_device_resources_cnt;
data[i++] = priv->adminq_set_driver_parameter_cnt;
data[i++] = priv->adminq_report_stats_cnt;
data[i++] = priv->adminq_report_link_speed_cnt;
}
static void gve_get_channels(struct net_device *netdev,
struct ethtool_channels *cmd)
{
struct gve_priv *priv = netdev_priv(netdev);
cmd->max_rx = priv->rx_cfg.max_queues;
cmd->max_tx = priv->tx_cfg.max_queues;
cmd->max_other = 0;
cmd->max_combined = 0;
cmd->rx_count = priv->rx_cfg.num_queues;
cmd->tx_count = priv->tx_cfg.num_queues;
cmd->other_count = 0;
cmd->combined_count = 0;
}
static int gve_set_channels(struct net_device *netdev,
struct ethtool_channels *cmd)
{
struct gve_priv *priv = netdev_priv(netdev);
struct gve_queue_config new_tx_cfg = priv->tx_cfg;
struct gve_queue_config new_rx_cfg = priv->rx_cfg;
struct ethtool_channels old_settings;
int new_tx = cmd->tx_count;
int new_rx = cmd->rx_count;
gve_get_channels(netdev, &old_settings);
/* Changing combined is not allowed */
if (cmd->combined_count != old_settings.combined_count)
return -EINVAL;
if (!new_rx || !new_tx)
return -EINVAL;
if (priv->num_xdp_queues &&
(new_tx != new_rx || (2 * new_tx > priv->tx_cfg.max_queues))) {
dev_err(&priv->pdev->dev, "XDP load failed: The number of configured RX queues should be equal to the number of configured TX queues and the number of configured RX/TX queues should be less than or equal to half the maximum number of RX/TX queues");
return -EINVAL;
}
if (!netif_carrier_ok(netdev)) {
priv->tx_cfg.num_queues = new_tx;
priv->rx_cfg.num_queues = new_rx;
return 0;
}
new_tx_cfg.num_queues = new_tx;
new_rx_cfg.num_queues = new_rx;
return gve_adjust_queues(priv, new_rx_cfg, new_tx_cfg);
}
static void gve_get_ringparam(struct net_device *netdev,
struct ethtool_ringparam *cmd,
struct kernel_ethtool_ringparam *kernel_cmd,
struct netlink_ext_ack *extack)
{
struct gve_priv *priv = netdev_priv(netdev);
cmd->rx_max_pending = priv->rx_desc_cnt;
cmd->tx_max_pending = priv->tx_desc_cnt;
cmd->rx_pending = priv->rx_desc_cnt;
cmd->tx_pending = priv->tx_desc_cnt;
}
static int gve_user_reset(struct net_device *netdev, u32 *flags)
{
struct gve_priv *priv = netdev_priv(netdev);
if (*flags == ETH_RESET_ALL) {
*flags = 0;
return gve_reset(priv, true);
}
return -EOPNOTSUPP;
}
static int gve_get_tunable(struct net_device *netdev,
const struct ethtool_tunable *etuna, void *value)
{
struct gve_priv *priv = netdev_priv(netdev);
switch (etuna->id) {
case ETHTOOL_RX_COPYBREAK:
*(u32 *)value = priv->rx_copybreak;
return 0;
default:
return -EOPNOTSUPP;
}
}
static int gve_set_tunable(struct net_device *netdev,
const struct ethtool_tunable *etuna,
const void *value)
{
struct gve_priv *priv = netdev_priv(netdev);
u32 len;
switch (etuna->id) {
case ETHTOOL_RX_COPYBREAK:
{
u32 max_copybreak = gve_is_gqi(priv) ?
(PAGE_SIZE / 2) : priv->data_buffer_size_dqo;
len = *(u32 *)value;
if (len > max_copybreak)
return -EINVAL;
priv->rx_copybreak = len;
return 0;
}
default:
return -EOPNOTSUPP;
}
}
static u32 gve_get_priv_flags(struct net_device *netdev)
{
struct gve_priv *priv = netdev_priv(netdev);
u32 ret_flags = 0;
/* Only 1 flag exists currently: report-stats (BIT(O)), so set that flag. */
if (priv->ethtool_flags & BIT(0))
ret_flags |= BIT(0);
return ret_flags;
}
static int gve_set_priv_flags(struct net_device *netdev, u32 flags)
{
struct gve_priv *priv = netdev_priv(netdev);
u64 ori_flags, new_flags;
int num_tx_queues;
num_tx_queues = gve_num_tx_queues(priv);
ori_flags = READ_ONCE(priv->ethtool_flags);
new_flags = ori_flags;
/* Only one priv flag exists: report-stats (BIT(0))*/
if (flags & BIT(0))
new_flags |= BIT(0);
else
new_flags &= ~(BIT(0));
priv->ethtool_flags = new_flags;
/* start report-stats timer when user turns report stats on. */
if (flags & BIT(0)) {
mod_timer(&priv->stats_report_timer,
round_jiffies(jiffies +
msecs_to_jiffies(priv->stats_report_timer_period)));
}
/* Zero off gve stats when report-stats turned off and */
/* delete report stats timer. */
if (!(flags & BIT(0)) && (ori_flags & BIT(0))) {
int tx_stats_num = GVE_TX_STATS_REPORT_NUM *
num_tx_queues;
int rx_stats_num = GVE_RX_STATS_REPORT_NUM *
priv->rx_cfg.num_queues;
memset(priv->stats_report->stats, 0, (tx_stats_num + rx_stats_num) *
sizeof(struct stats));
del_timer_sync(&priv->stats_report_timer);
}
return 0;
}
static int gve_get_link_ksettings(struct net_device *netdev,
struct ethtool_link_ksettings *cmd)
{
struct gve_priv *priv = netdev_priv(netdev);
int err = 0;
if (priv->link_speed == 0)
err = gve_adminq_report_link_speed(priv);
cmd->base.speed = priv->link_speed;
cmd->base.duplex = DUPLEX_FULL;
return err;
}
static int gve_get_coalesce(struct net_device *netdev,
struct ethtool_coalesce *ec,
struct kernel_ethtool_coalesce *kernel_ec,
struct netlink_ext_ack *extack)
{
struct gve_priv *priv = netdev_priv(netdev);
if (gve_is_gqi(priv))
return -EOPNOTSUPP;
ec->tx_coalesce_usecs = priv->tx_coalesce_usecs;
ec->rx_coalesce_usecs = priv->rx_coalesce_usecs;
return 0;
}
static int gve_set_coalesce(struct net_device *netdev,
struct ethtool_coalesce *ec,
struct kernel_ethtool_coalesce *kernel_ec,
struct netlink_ext_ack *extack)
{
struct gve_priv *priv = netdev_priv(netdev);
u32 tx_usecs_orig = priv->tx_coalesce_usecs;
u32 rx_usecs_orig = priv->rx_coalesce_usecs;
int idx;
if (gve_is_gqi(priv))
return -EOPNOTSUPP;
if (ec->tx_coalesce_usecs > GVE_MAX_ITR_INTERVAL_DQO ||
ec->rx_coalesce_usecs > GVE_MAX_ITR_INTERVAL_DQO)
return -EINVAL;
priv->tx_coalesce_usecs = ec->tx_coalesce_usecs;
priv->rx_coalesce_usecs = ec->rx_coalesce_usecs;
if (tx_usecs_orig != priv->tx_coalesce_usecs) {
for (idx = 0; idx < priv->tx_cfg.num_queues; idx++) {
int ntfy_idx = gve_tx_idx_to_ntfy(priv, idx);
struct gve_notify_block *block = &priv->ntfy_blocks[ntfy_idx];
gve_set_itr_coalesce_usecs_dqo(priv, block,
priv->tx_coalesce_usecs);
}
}
if (rx_usecs_orig != priv->rx_coalesce_usecs) {
for (idx = 0; idx < priv->rx_cfg.num_queues; idx++) {
int ntfy_idx = gve_rx_idx_to_ntfy(priv, idx);
struct gve_notify_block *block = &priv->ntfy_blocks[ntfy_idx];
gve_set_itr_coalesce_usecs_dqo(priv, block,
priv->rx_coalesce_usecs);
}
}
return 0;
}
const struct ethtool_ops gve_ethtool_ops = {
.supported_coalesce_params = ETHTOOL_COALESCE_USECS,
.get_drvinfo = gve_get_drvinfo,
.get_strings = gve_get_strings,
.get_sset_count = gve_get_sset_count,
.get_ethtool_stats = gve_get_ethtool_stats,
.set_msglevel = gve_set_msglevel,
.get_msglevel = gve_get_msglevel,
.set_channels = gve_set_channels,
.get_channels = gve_get_channels,
.get_link = ethtool_op_get_link,
.get_coalesce = gve_get_coalesce,
.set_coalesce = gve_set_coalesce,
.get_ringparam = gve_get_ringparam,
.reset = gve_user_reset,
.get_tunable = gve_get_tunable,
.set_tunable = gve_set_tunable,
.get_priv_flags = gve_get_priv_flags,
.set_priv_flags = gve_set_priv_flags,
.get_link_ksettings = gve_get_link_ksettings
};
|
linux-master
|
drivers/net/ethernet/google/gve/gve_ethtool.c
|
// SPDX-License-Identifier: (GPL-2.0 OR MIT)
/* Google virtual Ethernet (gve) driver
*
* Copyright (C) 2015-2021 Google, Inc.
*/
#include <linux/etherdevice.h>
#include <linux/pci.h>
#include "gve.h"
#include "gve_adminq.h"
#include "gve_register.h"
#define GVE_MAX_ADMINQ_RELEASE_CHECK 500
#define GVE_ADMINQ_SLEEP_LEN 20
#define GVE_MAX_ADMINQ_EVENT_COUNTER_CHECK 100
#define GVE_DEVICE_OPTION_ERROR_FMT "%s option error:\n" \
"Expected: length=%d, feature_mask=%x.\n" \
"Actual: length=%d, feature_mask=%x.\n"
#define GVE_DEVICE_OPTION_TOO_BIG_FMT "Length of %s option larger than expected. Possible older version of guest driver.\n"
static
struct gve_device_option *gve_get_next_option(struct gve_device_descriptor *descriptor,
struct gve_device_option *option)
{
void *option_end, *descriptor_end;
option_end = (void *)(option + 1) + be16_to_cpu(option->option_length);
descriptor_end = (void *)descriptor + be16_to_cpu(descriptor->total_length);
return option_end > descriptor_end ? NULL : (struct gve_device_option *)option_end;
}
static
void gve_parse_device_option(struct gve_priv *priv,
struct gve_device_descriptor *device_descriptor,
struct gve_device_option *option,
struct gve_device_option_gqi_rda **dev_op_gqi_rda,
struct gve_device_option_gqi_qpl **dev_op_gqi_qpl,
struct gve_device_option_dqo_rda **dev_op_dqo_rda,
struct gve_device_option_jumbo_frames **dev_op_jumbo_frames,
struct gve_device_option_dqo_qpl **dev_op_dqo_qpl)
{
u32 req_feat_mask = be32_to_cpu(option->required_features_mask);
u16 option_length = be16_to_cpu(option->option_length);
u16 option_id = be16_to_cpu(option->option_id);
/* If the length or feature mask doesn't match, continue without
* enabling the feature.
*/
switch (option_id) {
case GVE_DEV_OPT_ID_GQI_RAW_ADDRESSING:
if (option_length != GVE_DEV_OPT_LEN_GQI_RAW_ADDRESSING ||
req_feat_mask != GVE_DEV_OPT_REQ_FEAT_MASK_GQI_RAW_ADDRESSING) {
dev_warn(&priv->pdev->dev, GVE_DEVICE_OPTION_ERROR_FMT,
"Raw Addressing",
GVE_DEV_OPT_LEN_GQI_RAW_ADDRESSING,
GVE_DEV_OPT_REQ_FEAT_MASK_GQI_RAW_ADDRESSING,
option_length, req_feat_mask);
break;
}
dev_info(&priv->pdev->dev,
"Gqi raw addressing device option enabled.\n");
priv->queue_format = GVE_GQI_RDA_FORMAT;
break;
case GVE_DEV_OPT_ID_GQI_RDA:
if (option_length < sizeof(**dev_op_gqi_rda) ||
req_feat_mask != GVE_DEV_OPT_REQ_FEAT_MASK_GQI_RDA) {
dev_warn(&priv->pdev->dev, GVE_DEVICE_OPTION_ERROR_FMT,
"GQI RDA", (int)sizeof(**dev_op_gqi_rda),
GVE_DEV_OPT_REQ_FEAT_MASK_GQI_RDA,
option_length, req_feat_mask);
break;
}
if (option_length > sizeof(**dev_op_gqi_rda)) {
dev_warn(&priv->pdev->dev,
GVE_DEVICE_OPTION_TOO_BIG_FMT, "GQI RDA");
}
*dev_op_gqi_rda = (void *)(option + 1);
break;
case GVE_DEV_OPT_ID_GQI_QPL:
if (option_length < sizeof(**dev_op_gqi_qpl) ||
req_feat_mask != GVE_DEV_OPT_REQ_FEAT_MASK_GQI_QPL) {
dev_warn(&priv->pdev->dev, GVE_DEVICE_OPTION_ERROR_FMT,
"GQI QPL", (int)sizeof(**dev_op_gqi_qpl),
GVE_DEV_OPT_REQ_FEAT_MASK_GQI_QPL,
option_length, req_feat_mask);
break;
}
if (option_length > sizeof(**dev_op_gqi_qpl)) {
dev_warn(&priv->pdev->dev,
GVE_DEVICE_OPTION_TOO_BIG_FMT, "GQI QPL");
}
*dev_op_gqi_qpl = (void *)(option + 1);
break;
case GVE_DEV_OPT_ID_DQO_RDA:
if (option_length < sizeof(**dev_op_dqo_rda) ||
req_feat_mask != GVE_DEV_OPT_REQ_FEAT_MASK_DQO_RDA) {
dev_warn(&priv->pdev->dev, GVE_DEVICE_OPTION_ERROR_FMT,
"DQO RDA", (int)sizeof(**dev_op_dqo_rda),
GVE_DEV_OPT_REQ_FEAT_MASK_DQO_RDA,
option_length, req_feat_mask);
break;
}
if (option_length > sizeof(**dev_op_dqo_rda)) {
dev_warn(&priv->pdev->dev,
GVE_DEVICE_OPTION_TOO_BIG_FMT, "DQO RDA");
}
*dev_op_dqo_rda = (void *)(option + 1);
break;
case GVE_DEV_OPT_ID_DQO_QPL:
if (option_length < sizeof(**dev_op_dqo_qpl) ||
req_feat_mask != GVE_DEV_OPT_REQ_FEAT_MASK_DQO_QPL) {
dev_warn(&priv->pdev->dev, GVE_DEVICE_OPTION_ERROR_FMT,
"DQO QPL", (int)sizeof(**dev_op_dqo_qpl),
GVE_DEV_OPT_REQ_FEAT_MASK_DQO_QPL,
option_length, req_feat_mask);
break;
}
if (option_length > sizeof(**dev_op_dqo_qpl)) {
dev_warn(&priv->pdev->dev,
GVE_DEVICE_OPTION_TOO_BIG_FMT, "DQO QPL");
}
*dev_op_dqo_qpl = (void *)(option + 1);
break;
case GVE_DEV_OPT_ID_JUMBO_FRAMES:
if (option_length < sizeof(**dev_op_jumbo_frames) ||
req_feat_mask != GVE_DEV_OPT_REQ_FEAT_MASK_JUMBO_FRAMES) {
dev_warn(&priv->pdev->dev, GVE_DEVICE_OPTION_ERROR_FMT,
"Jumbo Frames",
(int)sizeof(**dev_op_jumbo_frames),
GVE_DEV_OPT_REQ_FEAT_MASK_JUMBO_FRAMES,
option_length, req_feat_mask);
break;
}
if (option_length > sizeof(**dev_op_jumbo_frames)) {
dev_warn(&priv->pdev->dev,
GVE_DEVICE_OPTION_TOO_BIG_FMT,
"Jumbo Frames");
}
*dev_op_jumbo_frames = (void *)(option + 1);
break;
default:
/* If we don't recognize the option just continue
* without doing anything.
*/
dev_dbg(&priv->pdev->dev, "Unrecognized device option 0x%hx not enabled.\n",
option_id);
}
}
/* Process all device options for a given describe device call. */
static int
gve_process_device_options(struct gve_priv *priv,
struct gve_device_descriptor *descriptor,
struct gve_device_option_gqi_rda **dev_op_gqi_rda,
struct gve_device_option_gqi_qpl **dev_op_gqi_qpl,
struct gve_device_option_dqo_rda **dev_op_dqo_rda,
struct gve_device_option_jumbo_frames **dev_op_jumbo_frames,
struct gve_device_option_dqo_qpl **dev_op_dqo_qpl)
{
const int num_options = be16_to_cpu(descriptor->num_device_options);
struct gve_device_option *dev_opt;
int i;
/* The options struct directly follows the device descriptor. */
dev_opt = (void *)(descriptor + 1);
for (i = 0; i < num_options; i++) {
struct gve_device_option *next_opt;
next_opt = gve_get_next_option(descriptor, dev_opt);
if (!next_opt) {
dev_err(&priv->dev->dev,
"options exceed device_descriptor's total length.\n");
return -EINVAL;
}
gve_parse_device_option(priv, descriptor, dev_opt,
dev_op_gqi_rda, dev_op_gqi_qpl,
dev_op_dqo_rda, dev_op_jumbo_frames,
dev_op_dqo_qpl);
dev_opt = next_opt;
}
return 0;
}
int gve_adminq_alloc(struct device *dev, struct gve_priv *priv)
{
priv->adminq = dma_alloc_coherent(dev, PAGE_SIZE,
&priv->adminq_bus_addr, GFP_KERNEL);
if (unlikely(!priv->adminq))
return -ENOMEM;
priv->adminq_mask = (PAGE_SIZE / sizeof(union gve_adminq_command)) - 1;
priv->adminq_prod_cnt = 0;
priv->adminq_cmd_fail = 0;
priv->adminq_timeouts = 0;
priv->adminq_describe_device_cnt = 0;
priv->adminq_cfg_device_resources_cnt = 0;
priv->adminq_register_page_list_cnt = 0;
priv->adminq_unregister_page_list_cnt = 0;
priv->adminq_create_tx_queue_cnt = 0;
priv->adminq_create_rx_queue_cnt = 0;
priv->adminq_destroy_tx_queue_cnt = 0;
priv->adminq_destroy_rx_queue_cnt = 0;
priv->adminq_dcfg_device_resources_cnt = 0;
priv->adminq_set_driver_parameter_cnt = 0;
priv->adminq_report_stats_cnt = 0;
priv->adminq_report_link_speed_cnt = 0;
priv->adminq_get_ptype_map_cnt = 0;
/* Setup Admin queue with the device */
iowrite32be(priv->adminq_bus_addr / PAGE_SIZE,
&priv->reg_bar0->adminq_pfn);
gve_set_admin_queue_ok(priv);
return 0;
}
void gve_adminq_release(struct gve_priv *priv)
{
int i = 0;
/* Tell the device the adminq is leaving */
iowrite32be(0x0, &priv->reg_bar0->adminq_pfn);
while (ioread32be(&priv->reg_bar0->adminq_pfn)) {
/* If this is reached the device is unrecoverable and still
* holding memory. Continue looping to avoid memory corruption,
* but WARN so it is visible what is going on.
*/
if (i == GVE_MAX_ADMINQ_RELEASE_CHECK)
WARN(1, "Unrecoverable platform error!");
i++;
msleep(GVE_ADMINQ_SLEEP_LEN);
}
gve_clear_device_rings_ok(priv);
gve_clear_device_resources_ok(priv);
gve_clear_admin_queue_ok(priv);
}
void gve_adminq_free(struct device *dev, struct gve_priv *priv)
{
if (!gve_get_admin_queue_ok(priv))
return;
gve_adminq_release(priv);
dma_free_coherent(dev, PAGE_SIZE, priv->adminq, priv->adminq_bus_addr);
gve_clear_admin_queue_ok(priv);
}
static void gve_adminq_kick_cmd(struct gve_priv *priv, u32 prod_cnt)
{
iowrite32be(prod_cnt, &priv->reg_bar0->adminq_doorbell);
}
static bool gve_adminq_wait_for_cmd(struct gve_priv *priv, u32 prod_cnt)
{
int i;
for (i = 0; i < GVE_MAX_ADMINQ_EVENT_COUNTER_CHECK; i++) {
if (ioread32be(&priv->reg_bar0->adminq_event_counter)
== prod_cnt)
return true;
msleep(GVE_ADMINQ_SLEEP_LEN);
}
return false;
}
static int gve_adminq_parse_err(struct gve_priv *priv, u32 status)
{
if (status != GVE_ADMINQ_COMMAND_PASSED &&
status != GVE_ADMINQ_COMMAND_UNSET) {
dev_err(&priv->pdev->dev, "AQ command failed with status %d\n", status);
priv->adminq_cmd_fail++;
}
switch (status) {
case GVE_ADMINQ_COMMAND_PASSED:
return 0;
case GVE_ADMINQ_COMMAND_UNSET:
dev_err(&priv->pdev->dev, "parse_aq_err: err and status both unset, this should not be possible.\n");
return -EINVAL;
case GVE_ADMINQ_COMMAND_ERROR_ABORTED:
case GVE_ADMINQ_COMMAND_ERROR_CANCELLED:
case GVE_ADMINQ_COMMAND_ERROR_DATALOSS:
case GVE_ADMINQ_COMMAND_ERROR_FAILED_PRECONDITION:
case GVE_ADMINQ_COMMAND_ERROR_UNAVAILABLE:
return -EAGAIN;
case GVE_ADMINQ_COMMAND_ERROR_ALREADY_EXISTS:
case GVE_ADMINQ_COMMAND_ERROR_INTERNAL_ERROR:
case GVE_ADMINQ_COMMAND_ERROR_INVALID_ARGUMENT:
case GVE_ADMINQ_COMMAND_ERROR_NOT_FOUND:
case GVE_ADMINQ_COMMAND_ERROR_OUT_OF_RANGE:
case GVE_ADMINQ_COMMAND_ERROR_UNKNOWN_ERROR:
return -EINVAL;
case GVE_ADMINQ_COMMAND_ERROR_DEADLINE_EXCEEDED:
return -ETIME;
case GVE_ADMINQ_COMMAND_ERROR_PERMISSION_DENIED:
case GVE_ADMINQ_COMMAND_ERROR_UNAUTHENTICATED:
return -EACCES;
case GVE_ADMINQ_COMMAND_ERROR_RESOURCE_EXHAUSTED:
return -ENOMEM;
case GVE_ADMINQ_COMMAND_ERROR_UNIMPLEMENTED:
return -EOPNOTSUPP;
default:
dev_err(&priv->pdev->dev, "parse_aq_err: unknown status code %d\n", status);
return -EINVAL;
}
}
/* Flushes all AQ commands currently queued and waits for them to complete.
* If there are failures, it will return the first error.
*/
static int gve_adminq_kick_and_wait(struct gve_priv *priv)
{
int tail, head;
int i;
tail = ioread32be(&priv->reg_bar0->adminq_event_counter);
head = priv->adminq_prod_cnt;
gve_adminq_kick_cmd(priv, head);
if (!gve_adminq_wait_for_cmd(priv, head)) {
dev_err(&priv->pdev->dev, "AQ commands timed out, need to reset AQ\n");
priv->adminq_timeouts++;
return -ENOTRECOVERABLE;
}
for (i = tail; i < head; i++) {
union gve_adminq_command *cmd;
u32 status, err;
cmd = &priv->adminq[i & priv->adminq_mask];
status = be32_to_cpu(READ_ONCE(cmd->status));
err = gve_adminq_parse_err(priv, status);
if (err)
// Return the first error if we failed.
return err;
}
return 0;
}
/* This function is not threadsafe - the caller is responsible for any
* necessary locks.
*/
static int gve_adminq_issue_cmd(struct gve_priv *priv,
union gve_adminq_command *cmd_orig)
{
union gve_adminq_command *cmd;
u32 opcode;
u32 tail;
tail = ioread32be(&priv->reg_bar0->adminq_event_counter);
// Check if next command will overflow the buffer.
if (((priv->adminq_prod_cnt + 1) & priv->adminq_mask) ==
(tail & priv->adminq_mask)) {
int err;
// Flush existing commands to make room.
err = gve_adminq_kick_and_wait(priv);
if (err)
return err;
// Retry.
tail = ioread32be(&priv->reg_bar0->adminq_event_counter);
if (((priv->adminq_prod_cnt + 1) & priv->adminq_mask) ==
(tail & priv->adminq_mask)) {
// This should never happen. We just flushed the
// command queue so there should be enough space.
return -ENOMEM;
}
}
cmd = &priv->adminq[priv->adminq_prod_cnt & priv->adminq_mask];
priv->adminq_prod_cnt++;
memcpy(cmd, cmd_orig, sizeof(*cmd_orig));
opcode = be32_to_cpu(READ_ONCE(cmd->opcode));
switch (opcode) {
case GVE_ADMINQ_DESCRIBE_DEVICE:
priv->adminq_describe_device_cnt++;
break;
case GVE_ADMINQ_CONFIGURE_DEVICE_RESOURCES:
priv->adminq_cfg_device_resources_cnt++;
break;
case GVE_ADMINQ_REGISTER_PAGE_LIST:
priv->adminq_register_page_list_cnt++;
break;
case GVE_ADMINQ_UNREGISTER_PAGE_LIST:
priv->adminq_unregister_page_list_cnt++;
break;
case GVE_ADMINQ_CREATE_TX_QUEUE:
priv->adminq_create_tx_queue_cnt++;
break;
case GVE_ADMINQ_CREATE_RX_QUEUE:
priv->adminq_create_rx_queue_cnt++;
break;
case GVE_ADMINQ_DESTROY_TX_QUEUE:
priv->adminq_destroy_tx_queue_cnt++;
break;
case GVE_ADMINQ_DESTROY_RX_QUEUE:
priv->adminq_destroy_rx_queue_cnt++;
break;
case GVE_ADMINQ_DECONFIGURE_DEVICE_RESOURCES:
priv->adminq_dcfg_device_resources_cnt++;
break;
case GVE_ADMINQ_SET_DRIVER_PARAMETER:
priv->adminq_set_driver_parameter_cnt++;
break;
case GVE_ADMINQ_REPORT_STATS:
priv->adminq_report_stats_cnt++;
break;
case GVE_ADMINQ_REPORT_LINK_SPEED:
priv->adminq_report_link_speed_cnt++;
break;
case GVE_ADMINQ_GET_PTYPE_MAP:
priv->adminq_get_ptype_map_cnt++;
break;
case GVE_ADMINQ_VERIFY_DRIVER_COMPATIBILITY:
priv->adminq_verify_driver_compatibility_cnt++;
break;
default:
dev_err(&priv->pdev->dev, "unknown AQ command opcode %d\n", opcode);
}
return 0;
}
/* This function is not threadsafe - the caller is responsible for any
* necessary locks.
* The caller is also responsible for making sure there are no commands
* waiting to be executed.
*/
static int gve_adminq_execute_cmd(struct gve_priv *priv,
union gve_adminq_command *cmd_orig)
{
u32 tail, head;
int err;
tail = ioread32be(&priv->reg_bar0->adminq_event_counter);
head = priv->adminq_prod_cnt;
if (tail != head)
// This is not a valid path
return -EINVAL;
err = gve_adminq_issue_cmd(priv, cmd_orig);
if (err)
return err;
return gve_adminq_kick_and_wait(priv);
}
/* The device specifies that the management vector can either be the first irq
* or the last irq. ntfy_blk_msix_base_idx indicates the first irq assigned to
* the ntfy blks. It if is 0 then the management vector is last, if it is 1 then
* the management vector is first.
*
* gve arranges the msix vectors so that the management vector is last.
*/
#define GVE_NTFY_BLK_BASE_MSIX_IDX 0
int gve_adminq_configure_device_resources(struct gve_priv *priv,
dma_addr_t counter_array_bus_addr,
u32 num_counters,
dma_addr_t db_array_bus_addr,
u32 num_ntfy_blks)
{
union gve_adminq_command cmd;
memset(&cmd, 0, sizeof(cmd));
cmd.opcode = cpu_to_be32(GVE_ADMINQ_CONFIGURE_DEVICE_RESOURCES);
cmd.configure_device_resources =
(struct gve_adminq_configure_device_resources) {
.counter_array = cpu_to_be64(counter_array_bus_addr),
.num_counters = cpu_to_be32(num_counters),
.irq_db_addr = cpu_to_be64(db_array_bus_addr),
.num_irq_dbs = cpu_to_be32(num_ntfy_blks),
.irq_db_stride = cpu_to_be32(sizeof(*priv->irq_db_indices)),
.ntfy_blk_msix_base_idx =
cpu_to_be32(GVE_NTFY_BLK_BASE_MSIX_IDX),
.queue_format = priv->queue_format,
};
return gve_adminq_execute_cmd(priv, &cmd);
}
int gve_adminq_deconfigure_device_resources(struct gve_priv *priv)
{
union gve_adminq_command cmd;
memset(&cmd, 0, sizeof(cmd));
cmd.opcode = cpu_to_be32(GVE_ADMINQ_DECONFIGURE_DEVICE_RESOURCES);
return gve_adminq_execute_cmd(priv, &cmd);
}
static int gve_adminq_create_tx_queue(struct gve_priv *priv, u32 queue_index)
{
struct gve_tx_ring *tx = &priv->tx[queue_index];
union gve_adminq_command cmd;
memset(&cmd, 0, sizeof(cmd));
cmd.opcode = cpu_to_be32(GVE_ADMINQ_CREATE_TX_QUEUE);
cmd.create_tx_queue = (struct gve_adminq_create_tx_queue) {
.queue_id = cpu_to_be32(queue_index),
.queue_resources_addr =
cpu_to_be64(tx->q_resources_bus),
.tx_ring_addr = cpu_to_be64(tx->bus),
.ntfy_id = cpu_to_be32(tx->ntfy_id),
};
if (gve_is_gqi(priv)) {
u32 qpl_id = priv->queue_format == GVE_GQI_RDA_FORMAT ?
GVE_RAW_ADDRESSING_QPL_ID : tx->tx_fifo.qpl->id;
cmd.create_tx_queue.queue_page_list_id = cpu_to_be32(qpl_id);
} else {
u16 comp_ring_size;
u32 qpl_id = 0;
if (priv->queue_format == GVE_DQO_RDA_FORMAT) {
qpl_id = GVE_RAW_ADDRESSING_QPL_ID;
comp_ring_size =
priv->options_dqo_rda.tx_comp_ring_entries;
} else {
qpl_id = tx->dqo.qpl->id;
comp_ring_size = priv->tx_desc_cnt;
}
cmd.create_tx_queue.queue_page_list_id = cpu_to_be32(qpl_id);
cmd.create_tx_queue.tx_ring_size =
cpu_to_be16(priv->tx_desc_cnt);
cmd.create_tx_queue.tx_comp_ring_addr =
cpu_to_be64(tx->complq_bus_dqo);
cmd.create_tx_queue.tx_comp_ring_size =
cpu_to_be16(comp_ring_size);
}
return gve_adminq_issue_cmd(priv, &cmd);
}
int gve_adminq_create_tx_queues(struct gve_priv *priv, u32 start_id, u32 num_queues)
{
int err;
int i;
for (i = start_id; i < start_id + num_queues; i++) {
err = gve_adminq_create_tx_queue(priv, i);
if (err)
return err;
}
return gve_adminq_kick_and_wait(priv);
}
static int gve_adminq_create_rx_queue(struct gve_priv *priv, u32 queue_index)
{
struct gve_rx_ring *rx = &priv->rx[queue_index];
union gve_adminq_command cmd;
memset(&cmd, 0, sizeof(cmd));
cmd.opcode = cpu_to_be32(GVE_ADMINQ_CREATE_RX_QUEUE);
cmd.create_rx_queue = (struct gve_adminq_create_rx_queue) {
.queue_id = cpu_to_be32(queue_index),
.ntfy_id = cpu_to_be32(rx->ntfy_id),
.queue_resources_addr = cpu_to_be64(rx->q_resources_bus),
};
if (gve_is_gqi(priv)) {
u32 qpl_id = priv->queue_format == GVE_GQI_RDA_FORMAT ?
GVE_RAW_ADDRESSING_QPL_ID : rx->data.qpl->id;
cmd.create_rx_queue.rx_desc_ring_addr =
cpu_to_be64(rx->desc.bus),
cmd.create_rx_queue.rx_data_ring_addr =
cpu_to_be64(rx->data.data_bus),
cmd.create_rx_queue.index = cpu_to_be32(queue_index);
cmd.create_rx_queue.queue_page_list_id = cpu_to_be32(qpl_id);
cmd.create_rx_queue.packet_buffer_size = cpu_to_be16(rx->packet_buffer_size);
} else {
u16 rx_buff_ring_entries;
u32 qpl_id = 0;
if (priv->queue_format == GVE_DQO_RDA_FORMAT) {
qpl_id = GVE_RAW_ADDRESSING_QPL_ID;
rx_buff_ring_entries =
priv->options_dqo_rda.rx_buff_ring_entries;
} else {
qpl_id = rx->dqo.qpl->id;
rx_buff_ring_entries = priv->rx_desc_cnt;
}
cmd.create_rx_queue.queue_page_list_id = cpu_to_be32(qpl_id);
cmd.create_rx_queue.rx_ring_size =
cpu_to_be16(priv->rx_desc_cnt);
cmd.create_rx_queue.rx_desc_ring_addr =
cpu_to_be64(rx->dqo.complq.bus);
cmd.create_rx_queue.rx_data_ring_addr =
cpu_to_be64(rx->dqo.bufq.bus);
cmd.create_rx_queue.packet_buffer_size =
cpu_to_be16(priv->data_buffer_size_dqo);
cmd.create_rx_queue.rx_buff_ring_size =
cpu_to_be16(rx_buff_ring_entries);
cmd.create_rx_queue.enable_rsc =
!!(priv->dev->features & NETIF_F_LRO);
}
return gve_adminq_issue_cmd(priv, &cmd);
}
int gve_adminq_create_rx_queues(struct gve_priv *priv, u32 num_queues)
{
int err;
int i;
for (i = 0; i < num_queues; i++) {
err = gve_adminq_create_rx_queue(priv, i);
if (err)
return err;
}
return gve_adminq_kick_and_wait(priv);
}
static int gve_adminq_destroy_tx_queue(struct gve_priv *priv, u32 queue_index)
{
union gve_adminq_command cmd;
int err;
memset(&cmd, 0, sizeof(cmd));
cmd.opcode = cpu_to_be32(GVE_ADMINQ_DESTROY_TX_QUEUE);
cmd.destroy_tx_queue = (struct gve_adminq_destroy_tx_queue) {
.queue_id = cpu_to_be32(queue_index),
};
err = gve_adminq_issue_cmd(priv, &cmd);
if (err)
return err;
return 0;
}
int gve_adminq_destroy_tx_queues(struct gve_priv *priv, u32 start_id, u32 num_queues)
{
int err;
int i;
for (i = start_id; i < start_id + num_queues; i++) {
err = gve_adminq_destroy_tx_queue(priv, i);
if (err)
return err;
}
return gve_adminq_kick_and_wait(priv);
}
static int gve_adminq_destroy_rx_queue(struct gve_priv *priv, u32 queue_index)
{
union gve_adminq_command cmd;
int err;
memset(&cmd, 0, sizeof(cmd));
cmd.opcode = cpu_to_be32(GVE_ADMINQ_DESTROY_RX_QUEUE);
cmd.destroy_rx_queue = (struct gve_adminq_destroy_rx_queue) {
.queue_id = cpu_to_be32(queue_index),
};
err = gve_adminq_issue_cmd(priv, &cmd);
if (err)
return err;
return 0;
}
int gve_adminq_destroy_rx_queues(struct gve_priv *priv, u32 num_queues)
{
int err;
int i;
for (i = 0; i < num_queues; i++) {
err = gve_adminq_destroy_rx_queue(priv, i);
if (err)
return err;
}
return gve_adminq_kick_and_wait(priv);
}
static int gve_set_desc_cnt(struct gve_priv *priv,
struct gve_device_descriptor *descriptor)
{
priv->tx_desc_cnt = be16_to_cpu(descriptor->tx_queue_entries);
if (priv->tx_desc_cnt * sizeof(priv->tx->desc[0]) < PAGE_SIZE) {
dev_err(&priv->pdev->dev, "Tx desc count %d too low\n",
priv->tx_desc_cnt);
return -EINVAL;
}
priv->rx_desc_cnt = be16_to_cpu(descriptor->rx_queue_entries);
if (priv->rx_desc_cnt * sizeof(priv->rx->desc.desc_ring[0])
< PAGE_SIZE) {
dev_err(&priv->pdev->dev, "Rx desc count %d too low\n",
priv->rx_desc_cnt);
return -EINVAL;
}
return 0;
}
static int
gve_set_desc_cnt_dqo(struct gve_priv *priv,
const struct gve_device_descriptor *descriptor,
const struct gve_device_option_dqo_rda *dev_op_dqo_rda)
{
priv->tx_desc_cnt = be16_to_cpu(descriptor->tx_queue_entries);
priv->rx_desc_cnt = be16_to_cpu(descriptor->rx_queue_entries);
if (priv->queue_format == GVE_DQO_QPL_FORMAT)
return 0;
priv->options_dqo_rda.tx_comp_ring_entries =
be16_to_cpu(dev_op_dqo_rda->tx_comp_ring_entries);
priv->options_dqo_rda.rx_buff_ring_entries =
be16_to_cpu(dev_op_dqo_rda->rx_buff_ring_entries);
return 0;
}
static void gve_enable_supported_features(struct gve_priv *priv,
u32 supported_features_mask,
const struct gve_device_option_jumbo_frames
*dev_op_jumbo_frames,
const struct gve_device_option_dqo_qpl
*dev_op_dqo_qpl)
{
/* Before control reaches this point, the page-size-capped max MTU from
* the gve_device_descriptor field has already been stored in
* priv->dev->max_mtu. We overwrite it with the true max MTU below.
*/
if (dev_op_jumbo_frames &&
(supported_features_mask & GVE_SUP_JUMBO_FRAMES_MASK)) {
dev_info(&priv->pdev->dev,
"JUMBO FRAMES device option enabled.\n");
priv->dev->max_mtu = be16_to_cpu(dev_op_jumbo_frames->max_mtu);
}
/* Override pages for qpl for DQO-QPL */
if (dev_op_dqo_qpl) {
priv->tx_pages_per_qpl =
be16_to_cpu(dev_op_dqo_qpl->tx_pages_per_qpl);
priv->rx_pages_per_qpl =
be16_to_cpu(dev_op_dqo_qpl->rx_pages_per_qpl);
if (priv->tx_pages_per_qpl == 0)
priv->tx_pages_per_qpl = DQO_QPL_DEFAULT_TX_PAGES;
if (priv->rx_pages_per_qpl == 0)
priv->rx_pages_per_qpl = DQO_QPL_DEFAULT_RX_PAGES;
}
}
int gve_adminq_describe_device(struct gve_priv *priv)
{
struct gve_device_option_jumbo_frames *dev_op_jumbo_frames = NULL;
struct gve_device_option_gqi_rda *dev_op_gqi_rda = NULL;
struct gve_device_option_gqi_qpl *dev_op_gqi_qpl = NULL;
struct gve_device_option_dqo_rda *dev_op_dqo_rda = NULL;
struct gve_device_option_dqo_qpl *dev_op_dqo_qpl = NULL;
struct gve_device_descriptor *descriptor;
u32 supported_features_mask = 0;
union gve_adminq_command cmd;
dma_addr_t descriptor_bus;
int err = 0;
u8 *mac;
u16 mtu;
memset(&cmd, 0, sizeof(cmd));
descriptor = dma_alloc_coherent(&priv->pdev->dev, PAGE_SIZE,
&descriptor_bus, GFP_KERNEL);
if (!descriptor)
return -ENOMEM;
cmd.opcode = cpu_to_be32(GVE_ADMINQ_DESCRIBE_DEVICE);
cmd.describe_device.device_descriptor_addr =
cpu_to_be64(descriptor_bus);
cmd.describe_device.device_descriptor_version =
cpu_to_be32(GVE_ADMINQ_DEVICE_DESCRIPTOR_VERSION);
cmd.describe_device.available_length = cpu_to_be32(PAGE_SIZE);
err = gve_adminq_execute_cmd(priv, &cmd);
if (err)
goto free_device_descriptor;
err = gve_process_device_options(priv, descriptor, &dev_op_gqi_rda,
&dev_op_gqi_qpl, &dev_op_dqo_rda,
&dev_op_jumbo_frames,
&dev_op_dqo_qpl);
if (err)
goto free_device_descriptor;
/* If the GQI_RAW_ADDRESSING option is not enabled and the queue format
* is not set to GqiRda, choose the queue format in a priority order:
* DqoRda, DqoQpl, GqiRda, GqiQpl. Use GqiQpl as default.
*/
if (dev_op_dqo_rda) {
priv->queue_format = GVE_DQO_RDA_FORMAT;
dev_info(&priv->pdev->dev,
"Driver is running with DQO RDA queue format.\n");
supported_features_mask =
be32_to_cpu(dev_op_dqo_rda->supported_features_mask);
} else if (dev_op_dqo_qpl) {
priv->queue_format = GVE_DQO_QPL_FORMAT;
supported_features_mask =
be32_to_cpu(dev_op_dqo_qpl->supported_features_mask);
} else if (dev_op_gqi_rda) {
priv->queue_format = GVE_GQI_RDA_FORMAT;
dev_info(&priv->pdev->dev,
"Driver is running with GQI RDA queue format.\n");
supported_features_mask =
be32_to_cpu(dev_op_gqi_rda->supported_features_mask);
} else if (priv->queue_format == GVE_GQI_RDA_FORMAT) {
dev_info(&priv->pdev->dev,
"Driver is running with GQI RDA queue format.\n");
} else {
priv->queue_format = GVE_GQI_QPL_FORMAT;
if (dev_op_gqi_qpl)
supported_features_mask =
be32_to_cpu(dev_op_gqi_qpl->supported_features_mask);
dev_info(&priv->pdev->dev,
"Driver is running with GQI QPL queue format.\n");
}
if (gve_is_gqi(priv)) {
err = gve_set_desc_cnt(priv, descriptor);
} else {
/* DQO supports LRO. */
priv->dev->hw_features |= NETIF_F_LRO;
err = gve_set_desc_cnt_dqo(priv, descriptor, dev_op_dqo_rda);
}
if (err)
goto free_device_descriptor;
priv->max_registered_pages =
be64_to_cpu(descriptor->max_registered_pages);
mtu = be16_to_cpu(descriptor->mtu);
if (mtu < ETH_MIN_MTU) {
dev_err(&priv->pdev->dev, "MTU %d below minimum MTU\n", mtu);
err = -EINVAL;
goto free_device_descriptor;
}
priv->dev->max_mtu = mtu;
priv->num_event_counters = be16_to_cpu(descriptor->counters);
eth_hw_addr_set(priv->dev, descriptor->mac);
mac = descriptor->mac;
dev_info(&priv->pdev->dev, "MAC addr: %pM\n", mac);
priv->tx_pages_per_qpl = be16_to_cpu(descriptor->tx_pages_per_qpl);
priv->rx_data_slot_cnt = be16_to_cpu(descriptor->rx_pages_per_qpl);
if (gve_is_gqi(priv) && priv->rx_data_slot_cnt < priv->rx_desc_cnt) {
dev_err(&priv->pdev->dev, "rx_data_slot_cnt cannot be smaller than rx_desc_cnt, setting rx_desc_cnt down to %d.\n",
priv->rx_data_slot_cnt);
priv->rx_desc_cnt = priv->rx_data_slot_cnt;
}
priv->default_num_queues = be16_to_cpu(descriptor->default_num_queues);
gve_enable_supported_features(priv, supported_features_mask,
dev_op_jumbo_frames, dev_op_dqo_qpl);
free_device_descriptor:
dma_free_coherent(&priv->pdev->dev, PAGE_SIZE, descriptor,
descriptor_bus);
return err;
}
int gve_adminq_register_page_list(struct gve_priv *priv,
struct gve_queue_page_list *qpl)
{
struct device *hdev = &priv->pdev->dev;
u32 num_entries = qpl->num_entries;
u32 size = num_entries * sizeof(qpl->page_buses[0]);
union gve_adminq_command cmd;
dma_addr_t page_list_bus;
__be64 *page_list;
int err;
int i;
memset(&cmd, 0, sizeof(cmd));
page_list = dma_alloc_coherent(hdev, size, &page_list_bus, GFP_KERNEL);
if (!page_list)
return -ENOMEM;
for (i = 0; i < num_entries; i++)
page_list[i] = cpu_to_be64(qpl->page_buses[i]);
cmd.opcode = cpu_to_be32(GVE_ADMINQ_REGISTER_PAGE_LIST);
cmd.reg_page_list = (struct gve_adminq_register_page_list) {
.page_list_id = cpu_to_be32(qpl->id),
.num_pages = cpu_to_be32(num_entries),
.page_address_list_addr = cpu_to_be64(page_list_bus),
};
err = gve_adminq_execute_cmd(priv, &cmd);
dma_free_coherent(hdev, size, page_list, page_list_bus);
return err;
}
int gve_adminq_unregister_page_list(struct gve_priv *priv, u32 page_list_id)
{
union gve_adminq_command cmd;
memset(&cmd, 0, sizeof(cmd));
cmd.opcode = cpu_to_be32(GVE_ADMINQ_UNREGISTER_PAGE_LIST);
cmd.unreg_page_list = (struct gve_adminq_unregister_page_list) {
.page_list_id = cpu_to_be32(page_list_id),
};
return gve_adminq_execute_cmd(priv, &cmd);
}
int gve_adminq_set_mtu(struct gve_priv *priv, u64 mtu)
{
union gve_adminq_command cmd;
memset(&cmd, 0, sizeof(cmd));
cmd.opcode = cpu_to_be32(GVE_ADMINQ_SET_DRIVER_PARAMETER);
cmd.set_driver_param = (struct gve_adminq_set_driver_parameter) {
.parameter_type = cpu_to_be32(GVE_SET_PARAM_MTU),
.parameter_value = cpu_to_be64(mtu),
};
return gve_adminq_execute_cmd(priv, &cmd);
}
int gve_adminq_report_stats(struct gve_priv *priv, u64 stats_report_len,
dma_addr_t stats_report_addr, u64 interval)
{
union gve_adminq_command cmd;
memset(&cmd, 0, sizeof(cmd));
cmd.opcode = cpu_to_be32(GVE_ADMINQ_REPORT_STATS);
cmd.report_stats = (struct gve_adminq_report_stats) {
.stats_report_len = cpu_to_be64(stats_report_len),
.stats_report_addr = cpu_to_be64(stats_report_addr),
.interval = cpu_to_be64(interval),
};
return gve_adminq_execute_cmd(priv, &cmd);
}
int gve_adminq_verify_driver_compatibility(struct gve_priv *priv,
u64 driver_info_len,
dma_addr_t driver_info_addr)
{
union gve_adminq_command cmd;
memset(&cmd, 0, sizeof(cmd));
cmd.opcode = cpu_to_be32(GVE_ADMINQ_VERIFY_DRIVER_COMPATIBILITY);
cmd.verify_driver_compatibility = (struct gve_adminq_verify_driver_compatibility) {
.driver_info_len = cpu_to_be64(driver_info_len),
.driver_info_addr = cpu_to_be64(driver_info_addr),
};
return gve_adminq_execute_cmd(priv, &cmd);
}
int gve_adminq_report_link_speed(struct gve_priv *priv)
{
union gve_adminq_command gvnic_cmd;
dma_addr_t link_speed_region_bus;
__be64 *link_speed_region;
int err;
link_speed_region =
dma_alloc_coherent(&priv->pdev->dev, sizeof(*link_speed_region),
&link_speed_region_bus, GFP_KERNEL);
if (!link_speed_region)
return -ENOMEM;
memset(&gvnic_cmd, 0, sizeof(gvnic_cmd));
gvnic_cmd.opcode = cpu_to_be32(GVE_ADMINQ_REPORT_LINK_SPEED);
gvnic_cmd.report_link_speed.link_speed_address =
cpu_to_be64(link_speed_region_bus);
err = gve_adminq_execute_cmd(priv, &gvnic_cmd);
priv->link_speed = be64_to_cpu(*link_speed_region);
dma_free_coherent(&priv->pdev->dev, sizeof(*link_speed_region), link_speed_region,
link_speed_region_bus);
return err;
}
int gve_adminq_get_ptype_map_dqo(struct gve_priv *priv,
struct gve_ptype_lut *ptype_lut)
{
struct gve_ptype_map *ptype_map;
union gve_adminq_command cmd;
dma_addr_t ptype_map_bus;
int err = 0;
int i;
memset(&cmd, 0, sizeof(cmd));
ptype_map = dma_alloc_coherent(&priv->pdev->dev, sizeof(*ptype_map),
&ptype_map_bus, GFP_KERNEL);
if (!ptype_map)
return -ENOMEM;
cmd.opcode = cpu_to_be32(GVE_ADMINQ_GET_PTYPE_MAP);
cmd.get_ptype_map = (struct gve_adminq_get_ptype_map) {
.ptype_map_len = cpu_to_be64(sizeof(*ptype_map)),
.ptype_map_addr = cpu_to_be64(ptype_map_bus),
};
err = gve_adminq_execute_cmd(priv, &cmd);
if (err)
goto err;
/* Populate ptype_lut. */
for (i = 0; i < GVE_NUM_PTYPES; i++) {
ptype_lut->ptypes[i].l3_type =
ptype_map->ptypes[i].l3_type;
ptype_lut->ptypes[i].l4_type =
ptype_map->ptypes[i].l4_type;
}
err:
dma_free_coherent(&priv->pdev->dev, sizeof(*ptype_map), ptype_map,
ptype_map_bus);
return err;
}
|
linux-master
|
drivers/net/ethernet/google/gve/gve_adminq.c
|
// SPDX-License-Identifier: (GPL-2.0 OR MIT)
/* Google virtual Ethernet (gve) driver
*
* Copyright (C) 2015-2021 Google, Inc.
*/
#include "gve.h"
#include "gve_adminq.h"
#include "gve_utils.h"
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/vmalloc.h>
#include <linux/skbuff.h>
#include <net/xdp_sock_drv.h>
static inline void gve_tx_put_doorbell(struct gve_priv *priv,
struct gve_queue_resources *q_resources,
u32 val)
{
iowrite32be(val, &priv->db_bar2[be32_to_cpu(q_resources->db_index)]);
}
void gve_xdp_tx_flush(struct gve_priv *priv, u32 xdp_qid)
{
u32 tx_qid = gve_xdp_tx_queue_id(priv, xdp_qid);
struct gve_tx_ring *tx = &priv->tx[tx_qid];
gve_tx_put_doorbell(priv, tx->q_resources, tx->req);
}
/* gvnic can only transmit from a Registered Segment.
* We copy skb payloads into the registered segment before writing Tx
* descriptors and ringing the Tx doorbell.
*
* gve_tx_fifo_* manages the Registered Segment as a FIFO - clients must
* free allocations in the order they were allocated.
*/
static int gve_tx_fifo_init(struct gve_priv *priv, struct gve_tx_fifo *fifo)
{
fifo->base = vmap(fifo->qpl->pages, fifo->qpl->num_entries, VM_MAP,
PAGE_KERNEL);
if (unlikely(!fifo->base)) {
netif_err(priv, drv, priv->dev, "Failed to vmap fifo, qpl_id = %d\n",
fifo->qpl->id);
return -ENOMEM;
}
fifo->size = fifo->qpl->num_entries * PAGE_SIZE;
atomic_set(&fifo->available, fifo->size);
fifo->head = 0;
return 0;
}
static void gve_tx_fifo_release(struct gve_priv *priv, struct gve_tx_fifo *fifo)
{
WARN(atomic_read(&fifo->available) != fifo->size,
"Releasing non-empty fifo");
vunmap(fifo->base);
}
static int gve_tx_fifo_pad_alloc_one_frag(struct gve_tx_fifo *fifo,
size_t bytes)
{
return (fifo->head + bytes < fifo->size) ? 0 : fifo->size - fifo->head;
}
static bool gve_tx_fifo_can_alloc(struct gve_tx_fifo *fifo, size_t bytes)
{
return (atomic_read(&fifo->available) <= bytes) ? false : true;
}
/* gve_tx_alloc_fifo - Allocate fragment(s) from Tx FIFO
* @fifo: FIFO to allocate from
* @bytes: Allocation size
* @iov: Scatter-gather elements to fill with allocation fragment base/len
*
* Returns number of valid elements in iov[] or negative on error.
*
* Allocations from a given FIFO must be externally synchronized but concurrent
* allocation and frees are allowed.
*/
static int gve_tx_alloc_fifo(struct gve_tx_fifo *fifo, size_t bytes,
struct gve_tx_iovec iov[2])
{
size_t overflow, padding;
u32 aligned_head;
int nfrags = 0;
if (!bytes)
return 0;
/* This check happens before we know how much padding is needed to
* align to a cacheline boundary for the payload, but that is fine,
* because the FIFO head always start aligned, and the FIFO's boundaries
* are aligned, so if there is space for the data, there is space for
* the padding to the next alignment.
*/
WARN(!gve_tx_fifo_can_alloc(fifo, bytes),
"Reached %s when there's not enough space in the fifo", __func__);
nfrags++;
iov[0].iov_offset = fifo->head;
iov[0].iov_len = bytes;
fifo->head += bytes;
if (fifo->head > fifo->size) {
/* If the allocation did not fit in the tail fragment of the
* FIFO, also use the head fragment.
*/
nfrags++;
overflow = fifo->head - fifo->size;
iov[0].iov_len -= overflow;
iov[1].iov_offset = 0; /* Start of fifo*/
iov[1].iov_len = overflow;
fifo->head = overflow;
}
/* Re-align to a cacheline boundary */
aligned_head = L1_CACHE_ALIGN(fifo->head);
padding = aligned_head - fifo->head;
iov[nfrags - 1].iov_padding = padding;
atomic_sub(bytes + padding, &fifo->available);
fifo->head = aligned_head;
if (fifo->head == fifo->size)
fifo->head = 0;
return nfrags;
}
/* gve_tx_free_fifo - Return space to Tx FIFO
* @fifo: FIFO to return fragments to
* @bytes: Bytes to free
*/
static void gve_tx_free_fifo(struct gve_tx_fifo *fifo, size_t bytes)
{
atomic_add(bytes, &fifo->available);
}
static size_t gve_tx_clear_buffer_state(struct gve_tx_buffer_state *info)
{
size_t space_freed = 0;
int i;
for (i = 0; i < ARRAY_SIZE(info->iov); i++) {
space_freed += info->iov[i].iov_len + info->iov[i].iov_padding;
info->iov[i].iov_len = 0;
info->iov[i].iov_padding = 0;
}
return space_freed;
}
static int gve_clean_xdp_done(struct gve_priv *priv, struct gve_tx_ring *tx,
u32 to_do)
{
struct gve_tx_buffer_state *info;
u32 clean_end = tx->done + to_do;
u64 pkts = 0, bytes = 0;
size_t space_freed = 0;
u32 xsk_complete = 0;
u32 idx;
for (; tx->done < clean_end; tx->done++) {
idx = tx->done & tx->mask;
info = &tx->info[idx];
if (unlikely(!info->xdp.size))
continue;
bytes += info->xdp.size;
pkts++;
xsk_complete += info->xdp.is_xsk;
info->xdp.size = 0;
if (info->xdp_frame) {
xdp_return_frame(info->xdp_frame);
info->xdp_frame = NULL;
}
space_freed += gve_tx_clear_buffer_state(info);
}
gve_tx_free_fifo(&tx->tx_fifo, space_freed);
if (xsk_complete > 0 && tx->xsk_pool)
xsk_tx_completed(tx->xsk_pool, xsk_complete);
u64_stats_update_begin(&tx->statss);
tx->bytes_done += bytes;
tx->pkt_done += pkts;
u64_stats_update_end(&tx->statss);
return pkts;
}
static int gve_clean_tx_done(struct gve_priv *priv, struct gve_tx_ring *tx,
u32 to_do, bool try_to_wake);
static void gve_tx_free_ring(struct gve_priv *priv, int idx)
{
struct gve_tx_ring *tx = &priv->tx[idx];
struct device *hdev = &priv->pdev->dev;
size_t bytes;
u32 slots;
gve_tx_remove_from_block(priv, idx);
slots = tx->mask + 1;
if (tx->q_num < priv->tx_cfg.num_queues) {
gve_clean_tx_done(priv, tx, priv->tx_desc_cnt, false);
netdev_tx_reset_queue(tx->netdev_txq);
} else {
gve_clean_xdp_done(priv, tx, priv->tx_desc_cnt);
}
dma_free_coherent(hdev, sizeof(*tx->q_resources),
tx->q_resources, tx->q_resources_bus);
tx->q_resources = NULL;
if (!tx->raw_addressing) {
gve_tx_fifo_release(priv, &tx->tx_fifo);
gve_unassign_qpl(priv, tx->tx_fifo.qpl->id);
tx->tx_fifo.qpl = NULL;
}
bytes = sizeof(*tx->desc) * slots;
dma_free_coherent(hdev, bytes, tx->desc, tx->bus);
tx->desc = NULL;
vfree(tx->info);
tx->info = NULL;
netif_dbg(priv, drv, priv->dev, "freed tx queue %d\n", idx);
}
static int gve_tx_alloc_ring(struct gve_priv *priv, int idx)
{
struct gve_tx_ring *tx = &priv->tx[idx];
struct device *hdev = &priv->pdev->dev;
u32 slots = priv->tx_desc_cnt;
size_t bytes;
/* Make sure everything is zeroed to start */
memset(tx, 0, sizeof(*tx));
spin_lock_init(&tx->clean_lock);
spin_lock_init(&tx->xdp_lock);
tx->q_num = idx;
tx->mask = slots - 1;
/* alloc metadata */
tx->info = vcalloc(slots, sizeof(*tx->info));
if (!tx->info)
return -ENOMEM;
/* alloc tx queue */
bytes = sizeof(*tx->desc) * slots;
tx->desc = dma_alloc_coherent(hdev, bytes, &tx->bus, GFP_KERNEL);
if (!tx->desc)
goto abort_with_info;
tx->raw_addressing = priv->queue_format == GVE_GQI_RDA_FORMAT;
tx->dev = &priv->pdev->dev;
if (!tx->raw_addressing) {
tx->tx_fifo.qpl = gve_assign_tx_qpl(priv, idx);
if (!tx->tx_fifo.qpl)
goto abort_with_desc;
/* map Tx FIFO */
if (gve_tx_fifo_init(priv, &tx->tx_fifo))
goto abort_with_qpl;
}
tx->q_resources =
dma_alloc_coherent(hdev,
sizeof(*tx->q_resources),
&tx->q_resources_bus,
GFP_KERNEL);
if (!tx->q_resources)
goto abort_with_fifo;
netif_dbg(priv, drv, priv->dev, "tx[%d]->bus=%lx\n", idx,
(unsigned long)tx->bus);
if (idx < priv->tx_cfg.num_queues)
tx->netdev_txq = netdev_get_tx_queue(priv->dev, idx);
gve_tx_add_to_block(priv, idx);
return 0;
abort_with_fifo:
if (!tx->raw_addressing)
gve_tx_fifo_release(priv, &tx->tx_fifo);
abort_with_qpl:
if (!tx->raw_addressing)
gve_unassign_qpl(priv, tx->tx_fifo.qpl->id);
abort_with_desc:
dma_free_coherent(hdev, bytes, tx->desc, tx->bus);
tx->desc = NULL;
abort_with_info:
vfree(tx->info);
tx->info = NULL;
return -ENOMEM;
}
int gve_tx_alloc_rings(struct gve_priv *priv, int start_id, int num_rings)
{
int err = 0;
int i;
for (i = start_id; i < start_id + num_rings; i++) {
err = gve_tx_alloc_ring(priv, i);
if (err) {
netif_err(priv, drv, priv->dev,
"Failed to alloc tx ring=%d: err=%d\n",
i, err);
break;
}
}
/* Unallocate if there was an error */
if (err) {
int j;
for (j = start_id; j < i; j++)
gve_tx_free_ring(priv, j);
}
return err;
}
void gve_tx_free_rings_gqi(struct gve_priv *priv, int start_id, int num_rings)
{
int i;
for (i = start_id; i < start_id + num_rings; i++)
gve_tx_free_ring(priv, i);
}
/* gve_tx_avail - Calculates the number of slots available in the ring
* @tx: tx ring to check
*
* Returns the number of slots available
*
* The capacity of the queue is mask + 1. We don't need to reserve an entry.
**/
static inline u32 gve_tx_avail(struct gve_tx_ring *tx)
{
return tx->mask + 1 - (tx->req - tx->done);
}
static inline int gve_skb_fifo_bytes_required(struct gve_tx_ring *tx,
struct sk_buff *skb)
{
int pad_bytes, align_hdr_pad;
int bytes;
int hlen;
hlen = skb_is_gso(skb) ? skb_checksum_start_offset(skb) + tcp_hdrlen(skb) :
min_t(int, GVE_GQ_TX_MIN_PKT_DESC_BYTES, skb->len);
pad_bytes = gve_tx_fifo_pad_alloc_one_frag(&tx->tx_fifo,
hlen);
/* We need to take into account the header alignment padding. */
align_hdr_pad = L1_CACHE_ALIGN(hlen) - hlen;
bytes = align_hdr_pad + pad_bytes + skb->len;
return bytes;
}
/* The most descriptors we could need is MAX_SKB_FRAGS + 4 :
* 1 for each skb frag
* 1 for the skb linear portion
* 1 for when tcp hdr needs to be in separate descriptor
* 1 if the payload wraps to the beginning of the FIFO
* 1 for metadata descriptor
*/
#define MAX_TX_DESC_NEEDED (MAX_SKB_FRAGS + 4)
static void gve_tx_unmap_buf(struct device *dev, struct gve_tx_buffer_state *info)
{
if (info->skb) {
dma_unmap_single(dev, dma_unmap_addr(info, dma),
dma_unmap_len(info, len),
DMA_TO_DEVICE);
dma_unmap_len_set(info, len, 0);
} else {
dma_unmap_page(dev, dma_unmap_addr(info, dma),
dma_unmap_len(info, len),
DMA_TO_DEVICE);
dma_unmap_len_set(info, len, 0);
}
}
/* Check if sufficient resources (descriptor ring space, FIFO space) are
* available to transmit the given number of bytes.
*/
static inline bool gve_can_tx(struct gve_tx_ring *tx, int bytes_required)
{
bool can_alloc = true;
if (!tx->raw_addressing)
can_alloc = gve_tx_fifo_can_alloc(&tx->tx_fifo, bytes_required);
return (gve_tx_avail(tx) >= MAX_TX_DESC_NEEDED && can_alloc);
}
static_assert(NAPI_POLL_WEIGHT >= MAX_TX_DESC_NEEDED);
/* Stops the queue if the skb cannot be transmitted. */
static int gve_maybe_stop_tx(struct gve_priv *priv, struct gve_tx_ring *tx,
struct sk_buff *skb)
{
int bytes_required = 0;
u32 nic_done;
u32 to_do;
int ret;
if (!tx->raw_addressing)
bytes_required = gve_skb_fifo_bytes_required(tx, skb);
if (likely(gve_can_tx(tx, bytes_required)))
return 0;
ret = -EBUSY;
spin_lock(&tx->clean_lock);
nic_done = gve_tx_load_event_counter(priv, tx);
to_do = nic_done - tx->done;
/* Only try to clean if there is hope for TX */
if (to_do + gve_tx_avail(tx) >= MAX_TX_DESC_NEEDED) {
if (to_do > 0) {
to_do = min_t(u32, to_do, NAPI_POLL_WEIGHT);
gve_clean_tx_done(priv, tx, to_do, false);
}
if (likely(gve_can_tx(tx, bytes_required)))
ret = 0;
}
if (ret) {
/* No space, so stop the queue */
tx->stop_queue++;
netif_tx_stop_queue(tx->netdev_txq);
}
spin_unlock(&tx->clean_lock);
return ret;
}
static void gve_tx_fill_pkt_desc(union gve_tx_desc *pkt_desc,
u16 csum_offset, u8 ip_summed, bool is_gso,
int l4_hdr_offset, u32 desc_cnt,
u16 hlen, u64 addr, u16 pkt_len)
{
/* l4_hdr_offset and csum_offset are in units of 16-bit words */
if (is_gso) {
pkt_desc->pkt.type_flags = GVE_TXD_TSO | GVE_TXF_L4CSUM;
pkt_desc->pkt.l4_csum_offset = csum_offset >> 1;
pkt_desc->pkt.l4_hdr_offset = l4_hdr_offset >> 1;
} else if (likely(ip_summed == CHECKSUM_PARTIAL)) {
pkt_desc->pkt.type_flags = GVE_TXD_STD | GVE_TXF_L4CSUM;
pkt_desc->pkt.l4_csum_offset = csum_offset >> 1;
pkt_desc->pkt.l4_hdr_offset = l4_hdr_offset >> 1;
} else {
pkt_desc->pkt.type_flags = GVE_TXD_STD;
pkt_desc->pkt.l4_csum_offset = 0;
pkt_desc->pkt.l4_hdr_offset = 0;
}
pkt_desc->pkt.desc_cnt = desc_cnt;
pkt_desc->pkt.len = cpu_to_be16(pkt_len);
pkt_desc->pkt.seg_len = cpu_to_be16(hlen);
pkt_desc->pkt.seg_addr = cpu_to_be64(addr);
}
static void gve_tx_fill_mtd_desc(union gve_tx_desc *mtd_desc,
struct sk_buff *skb)
{
BUILD_BUG_ON(sizeof(mtd_desc->mtd) != sizeof(mtd_desc->pkt));
mtd_desc->mtd.type_flags = GVE_TXD_MTD | GVE_MTD_SUBTYPE_PATH;
mtd_desc->mtd.path_state = GVE_MTD_PATH_STATE_DEFAULT |
GVE_MTD_PATH_HASH_L4;
mtd_desc->mtd.path_hash = cpu_to_be32(skb->hash);
mtd_desc->mtd.reserved0 = 0;
mtd_desc->mtd.reserved1 = 0;
}
static void gve_tx_fill_seg_desc(union gve_tx_desc *seg_desc,
u16 l3_offset, u16 gso_size,
bool is_gso_v6, bool is_gso,
u16 len, u64 addr)
{
seg_desc->seg.type_flags = GVE_TXD_SEG;
if (is_gso) {
if (is_gso_v6)
seg_desc->seg.type_flags |= GVE_TXSF_IPV6;
seg_desc->seg.l3_offset = l3_offset >> 1;
seg_desc->seg.mss = cpu_to_be16(gso_size);
}
seg_desc->seg.seg_len = cpu_to_be16(len);
seg_desc->seg.seg_addr = cpu_to_be64(addr);
}
static void gve_dma_sync_for_device(struct device *dev, dma_addr_t *page_buses,
u64 iov_offset, u64 iov_len)
{
u64 last_page = (iov_offset + iov_len - 1) / PAGE_SIZE;
u64 first_page = iov_offset / PAGE_SIZE;
u64 page;
for (page = first_page; page <= last_page; page++)
dma_sync_single_for_device(dev, page_buses[page], PAGE_SIZE, DMA_TO_DEVICE);
}
static int gve_tx_add_skb_copy(struct gve_priv *priv, struct gve_tx_ring *tx, struct sk_buff *skb)
{
int pad_bytes, hlen, hdr_nfrags, payload_nfrags, l4_hdr_offset;
union gve_tx_desc *pkt_desc, *seg_desc;
struct gve_tx_buffer_state *info;
int mtd_desc_nr = !!skb->l4_hash;
bool is_gso = skb_is_gso(skb);
u32 idx = tx->req & tx->mask;
int payload_iov = 2;
int copy_offset;
u32 next_idx;
int i;
info = &tx->info[idx];
pkt_desc = &tx->desc[idx];
l4_hdr_offset = skb_checksum_start_offset(skb);
/* If the skb is gso, then we want the tcp header alone in the first segment
* otherwise we want the minimum required by the gVNIC spec.
*/
hlen = is_gso ? l4_hdr_offset + tcp_hdrlen(skb) :
min_t(int, GVE_GQ_TX_MIN_PKT_DESC_BYTES, skb->len);
info->skb = skb;
/* We don't want to split the header, so if necessary, pad to the end
* of the fifo and then put the header at the beginning of the fifo.
*/
pad_bytes = gve_tx_fifo_pad_alloc_one_frag(&tx->tx_fifo, hlen);
hdr_nfrags = gve_tx_alloc_fifo(&tx->tx_fifo, hlen + pad_bytes,
&info->iov[0]);
WARN(!hdr_nfrags, "hdr_nfrags should never be 0!");
payload_nfrags = gve_tx_alloc_fifo(&tx->tx_fifo, skb->len - hlen,
&info->iov[payload_iov]);
gve_tx_fill_pkt_desc(pkt_desc, skb->csum_offset, skb->ip_summed,
is_gso, l4_hdr_offset,
1 + mtd_desc_nr + payload_nfrags, hlen,
info->iov[hdr_nfrags - 1].iov_offset, skb->len);
skb_copy_bits(skb, 0,
tx->tx_fifo.base + info->iov[hdr_nfrags - 1].iov_offset,
hlen);
gve_dma_sync_for_device(&priv->pdev->dev, tx->tx_fifo.qpl->page_buses,
info->iov[hdr_nfrags - 1].iov_offset,
info->iov[hdr_nfrags - 1].iov_len);
copy_offset = hlen;
if (mtd_desc_nr) {
next_idx = (tx->req + 1) & tx->mask;
gve_tx_fill_mtd_desc(&tx->desc[next_idx], skb);
}
for (i = payload_iov; i < payload_nfrags + payload_iov; i++) {
next_idx = (tx->req + 1 + mtd_desc_nr + i - payload_iov) & tx->mask;
seg_desc = &tx->desc[next_idx];
gve_tx_fill_seg_desc(seg_desc, skb_network_offset(skb),
skb_shinfo(skb)->gso_size,
skb_is_gso_v6(skb), is_gso,
info->iov[i].iov_len,
info->iov[i].iov_offset);
skb_copy_bits(skb, copy_offset,
tx->tx_fifo.base + info->iov[i].iov_offset,
info->iov[i].iov_len);
gve_dma_sync_for_device(&priv->pdev->dev, tx->tx_fifo.qpl->page_buses,
info->iov[i].iov_offset,
info->iov[i].iov_len);
copy_offset += info->iov[i].iov_len;
}
return 1 + mtd_desc_nr + payload_nfrags;
}
static int gve_tx_add_skb_no_copy(struct gve_priv *priv, struct gve_tx_ring *tx,
struct sk_buff *skb)
{
const struct skb_shared_info *shinfo = skb_shinfo(skb);
int hlen, num_descriptors, l4_hdr_offset;
union gve_tx_desc *pkt_desc, *mtd_desc, *seg_desc;
struct gve_tx_buffer_state *info;
int mtd_desc_nr = !!skb->l4_hash;
bool is_gso = skb_is_gso(skb);
u32 idx = tx->req & tx->mask;
u64 addr;
u32 len;
int i;
info = &tx->info[idx];
pkt_desc = &tx->desc[idx];
l4_hdr_offset = skb_checksum_start_offset(skb);
/* If the skb is gso, then we want only up to the tcp header in the first segment
* to efficiently replicate on each segment otherwise we want the linear portion
* of the skb (which will contain the checksum because skb->csum_start and
* skb->csum_offset are given relative to skb->head) in the first segment.
*/
hlen = is_gso ? l4_hdr_offset + tcp_hdrlen(skb) : skb_headlen(skb);
len = skb_headlen(skb);
info->skb = skb;
addr = dma_map_single(tx->dev, skb->data, len, DMA_TO_DEVICE);
if (unlikely(dma_mapping_error(tx->dev, addr))) {
tx->dma_mapping_error++;
goto drop;
}
dma_unmap_len_set(info, len, len);
dma_unmap_addr_set(info, dma, addr);
num_descriptors = 1 + shinfo->nr_frags;
if (hlen < len)
num_descriptors++;
if (mtd_desc_nr)
num_descriptors++;
gve_tx_fill_pkt_desc(pkt_desc, skb->csum_offset, skb->ip_summed,
is_gso, l4_hdr_offset,
num_descriptors, hlen, addr, skb->len);
if (mtd_desc_nr) {
idx = (idx + 1) & tx->mask;
mtd_desc = &tx->desc[idx];
gve_tx_fill_mtd_desc(mtd_desc, skb);
}
if (hlen < len) {
/* For gso the rest of the linear portion of the skb needs to
* be in its own descriptor.
*/
len -= hlen;
addr += hlen;
idx = (idx + 1) & tx->mask;
seg_desc = &tx->desc[idx];
gve_tx_fill_seg_desc(seg_desc, skb_network_offset(skb),
skb_shinfo(skb)->gso_size,
skb_is_gso_v6(skb), is_gso, len, addr);
}
for (i = 0; i < shinfo->nr_frags; i++) {
const skb_frag_t *frag = &shinfo->frags[i];
idx = (idx + 1) & tx->mask;
seg_desc = &tx->desc[idx];
len = skb_frag_size(frag);
addr = skb_frag_dma_map(tx->dev, frag, 0, len, DMA_TO_DEVICE);
if (unlikely(dma_mapping_error(tx->dev, addr))) {
tx->dma_mapping_error++;
goto unmap_drop;
}
tx->info[idx].skb = NULL;
dma_unmap_len_set(&tx->info[idx], len, len);
dma_unmap_addr_set(&tx->info[idx], dma, addr);
gve_tx_fill_seg_desc(seg_desc, skb_network_offset(skb),
skb_shinfo(skb)->gso_size,
skb_is_gso_v6(skb), is_gso, len, addr);
}
return num_descriptors;
unmap_drop:
i += num_descriptors - shinfo->nr_frags;
while (i--) {
/* Skip metadata descriptor, if set */
if (i == 1 && mtd_desc_nr == 1)
continue;
idx--;
gve_tx_unmap_buf(tx->dev, &tx->info[idx & tx->mask]);
}
drop:
tx->dropped_pkt++;
return 0;
}
netdev_tx_t gve_tx(struct sk_buff *skb, struct net_device *dev)
{
struct gve_priv *priv = netdev_priv(dev);
struct gve_tx_ring *tx;
int nsegs;
WARN(skb_get_queue_mapping(skb) >= priv->tx_cfg.num_queues,
"skb queue index out of range");
tx = &priv->tx[skb_get_queue_mapping(skb)];
if (unlikely(gve_maybe_stop_tx(priv, tx, skb))) {
/* We need to ring the txq doorbell -- we have stopped the Tx
* queue for want of resources, but prior calls to gve_tx()
* may have added descriptors without ringing the doorbell.
*/
gve_tx_put_doorbell(priv, tx->q_resources, tx->req);
return NETDEV_TX_BUSY;
}
if (tx->raw_addressing)
nsegs = gve_tx_add_skb_no_copy(priv, tx, skb);
else
nsegs = gve_tx_add_skb_copy(priv, tx, skb);
/* If the packet is getting sent, we need to update the skb */
if (nsegs) {
netdev_tx_sent_queue(tx->netdev_txq, skb->len);
skb_tx_timestamp(skb);
tx->req += nsegs;
} else {
dev_kfree_skb_any(skb);
}
if (!netif_xmit_stopped(tx->netdev_txq) && netdev_xmit_more())
return NETDEV_TX_OK;
/* Give packets to NIC. Even if this packet failed to send the doorbell
* might need to be rung because of xmit_more.
*/
gve_tx_put_doorbell(priv, tx->q_resources, tx->req);
return NETDEV_TX_OK;
}
static int gve_tx_fill_xdp(struct gve_priv *priv, struct gve_tx_ring *tx,
void *data, int len, void *frame_p, bool is_xsk)
{
int pad, nfrags, ndescs, iovi, offset;
struct gve_tx_buffer_state *info;
u32 reqi = tx->req;
pad = gve_tx_fifo_pad_alloc_one_frag(&tx->tx_fifo, len);
if (pad >= GVE_GQ_TX_MIN_PKT_DESC_BYTES)
pad = 0;
info = &tx->info[reqi & tx->mask];
info->xdp_frame = frame_p;
info->xdp.size = len;
info->xdp.is_xsk = is_xsk;
nfrags = gve_tx_alloc_fifo(&tx->tx_fifo, pad + len,
&info->iov[0]);
iovi = pad > 0;
ndescs = nfrags - iovi;
offset = 0;
while (iovi < nfrags) {
if (!offset)
gve_tx_fill_pkt_desc(&tx->desc[reqi & tx->mask], 0,
CHECKSUM_NONE, false, 0, ndescs,
info->iov[iovi].iov_len,
info->iov[iovi].iov_offset, len);
else
gve_tx_fill_seg_desc(&tx->desc[reqi & tx->mask],
0, 0, false, false,
info->iov[iovi].iov_len,
info->iov[iovi].iov_offset);
memcpy(tx->tx_fifo.base + info->iov[iovi].iov_offset,
data + offset, info->iov[iovi].iov_len);
gve_dma_sync_for_device(&priv->pdev->dev,
tx->tx_fifo.qpl->page_buses,
info->iov[iovi].iov_offset,
info->iov[iovi].iov_len);
offset += info->iov[iovi].iov_len;
iovi++;
reqi++;
}
return ndescs;
}
int gve_xdp_xmit(struct net_device *dev, int n, struct xdp_frame **frames,
u32 flags)
{
struct gve_priv *priv = netdev_priv(dev);
struct gve_tx_ring *tx;
int i, err = 0, qid;
if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK))
return -EINVAL;
qid = gve_xdp_tx_queue_id(priv,
smp_processor_id() % priv->num_xdp_queues);
tx = &priv->tx[qid];
spin_lock(&tx->xdp_lock);
for (i = 0; i < n; i++) {
err = gve_xdp_xmit_one(priv, tx, frames[i]->data,
frames[i]->len, frames[i]);
if (err)
break;
}
if (flags & XDP_XMIT_FLUSH)
gve_tx_put_doorbell(priv, tx->q_resources, tx->req);
spin_unlock(&tx->xdp_lock);
u64_stats_update_begin(&tx->statss);
tx->xdp_xmit += n;
tx->xdp_xmit_errors += n - i;
u64_stats_update_end(&tx->statss);
return i ? i : err;
}
int gve_xdp_xmit_one(struct gve_priv *priv, struct gve_tx_ring *tx,
void *data, int len, void *frame_p)
{
int nsegs;
if (!gve_can_tx(tx, len + GVE_GQ_TX_MIN_PKT_DESC_BYTES - 1))
return -EBUSY;
nsegs = gve_tx_fill_xdp(priv, tx, data, len, frame_p, false);
tx->req += nsegs;
return 0;
}
#define GVE_TX_START_THRESH PAGE_SIZE
static int gve_clean_tx_done(struct gve_priv *priv, struct gve_tx_ring *tx,
u32 to_do, bool try_to_wake)
{
struct gve_tx_buffer_state *info;
u64 pkts = 0, bytes = 0;
size_t space_freed = 0;
struct sk_buff *skb;
u32 idx;
int j;
for (j = 0; j < to_do; j++) {
idx = tx->done & tx->mask;
netif_info(priv, tx_done, priv->dev,
"[%d] %s: idx=%d (req=%u done=%u)\n",
tx->q_num, __func__, idx, tx->req, tx->done);
info = &tx->info[idx];
skb = info->skb;
/* Unmap the buffer */
if (tx->raw_addressing)
gve_tx_unmap_buf(tx->dev, info);
tx->done++;
/* Mark as free */
if (skb) {
info->skb = NULL;
bytes += skb->len;
pkts++;
dev_consume_skb_any(skb);
if (tx->raw_addressing)
continue;
space_freed += gve_tx_clear_buffer_state(info);
}
}
if (!tx->raw_addressing)
gve_tx_free_fifo(&tx->tx_fifo, space_freed);
u64_stats_update_begin(&tx->statss);
tx->bytes_done += bytes;
tx->pkt_done += pkts;
u64_stats_update_end(&tx->statss);
netdev_tx_completed_queue(tx->netdev_txq, pkts, bytes);
/* start the queue if we've stopped it */
#ifndef CONFIG_BQL
/* Make sure that the doorbells are synced */
smp_mb();
#endif
if (try_to_wake && netif_tx_queue_stopped(tx->netdev_txq) &&
likely(gve_can_tx(tx, GVE_TX_START_THRESH))) {
tx->wake_queue++;
netif_tx_wake_queue(tx->netdev_txq);
}
return pkts;
}
u32 gve_tx_load_event_counter(struct gve_priv *priv,
struct gve_tx_ring *tx)
{
u32 counter_index = be32_to_cpu(tx->q_resources->counter_index);
__be32 counter = READ_ONCE(priv->counter_array[counter_index]);
return be32_to_cpu(counter);
}
static int gve_xsk_tx(struct gve_priv *priv, struct gve_tx_ring *tx,
int budget)
{
struct xdp_desc desc;
int sent = 0, nsegs;
void *data;
spin_lock(&tx->xdp_lock);
while (sent < budget) {
if (!gve_can_tx(tx, GVE_TX_START_THRESH))
goto out;
if (!xsk_tx_peek_desc(tx->xsk_pool, &desc)) {
tx->xdp_xsk_done = tx->xdp_xsk_wakeup;
goto out;
}
data = xsk_buff_raw_get_data(tx->xsk_pool, desc.addr);
nsegs = gve_tx_fill_xdp(priv, tx, data, desc.len, NULL, true);
tx->req += nsegs;
sent++;
}
out:
if (sent > 0) {
gve_tx_put_doorbell(priv, tx->q_resources, tx->req);
xsk_tx_release(tx->xsk_pool);
}
spin_unlock(&tx->xdp_lock);
return sent;
}
bool gve_xdp_poll(struct gve_notify_block *block, int budget)
{
struct gve_priv *priv = block->priv;
struct gve_tx_ring *tx = block->tx;
u32 nic_done;
bool repoll;
u32 to_do;
/* If budget is 0, do all the work */
if (budget == 0)
budget = INT_MAX;
/* Find out how much work there is to be done */
nic_done = gve_tx_load_event_counter(priv, tx);
to_do = min_t(u32, (nic_done - tx->done), budget);
gve_clean_xdp_done(priv, tx, to_do);
repoll = nic_done != tx->done;
if (tx->xsk_pool) {
int sent = gve_xsk_tx(priv, tx, budget);
u64_stats_update_begin(&tx->statss);
tx->xdp_xsk_sent += sent;
u64_stats_update_end(&tx->statss);
repoll |= (sent == budget);
if (xsk_uses_need_wakeup(tx->xsk_pool))
xsk_set_tx_need_wakeup(tx->xsk_pool);
}
/* If we still have work we want to repoll */
return repoll;
}
bool gve_tx_poll(struct gve_notify_block *block, int budget)
{
struct gve_priv *priv = block->priv;
struct gve_tx_ring *tx = block->tx;
u32 nic_done;
u32 to_do;
/* If budget is 0, do all the work */
if (budget == 0)
budget = INT_MAX;
/* In TX path, it may try to clean completed pkts in order to xmit,
* to avoid cleaning conflict, use spin_lock(), it yields better
* concurrency between xmit/clean than netif's lock.
*/
spin_lock(&tx->clean_lock);
/* Find out how much work there is to be done */
nic_done = gve_tx_load_event_counter(priv, tx);
to_do = min_t(u32, (nic_done - tx->done), budget);
gve_clean_tx_done(priv, tx, to_do, true);
spin_unlock(&tx->clean_lock);
/* If we still have work we want to repoll */
return nic_done != tx->done;
}
bool gve_tx_clean_pending(struct gve_priv *priv, struct gve_tx_ring *tx)
{
u32 nic_done = gve_tx_load_event_counter(priv, tx);
return nic_done != tx->done;
}
|
linux-master
|
drivers/net/ethernet/google/gve/gve_tx.c
|
// SPDX-License-Identifier: (GPL-2.0 OR MIT)
/* Google virtual Ethernet (gve) driver
*
* Copyright (C) 2015-2021 Google, Inc.
*/
#include "gve.h"
#include "gve_adminq.h"
#include "gve_utils.h"
#include <linux/etherdevice.h>
#include <linux/filter.h>
#include <net/xdp.h>
#include <net/xdp_sock_drv.h>
static void gve_rx_free_buffer(struct device *dev,
struct gve_rx_slot_page_info *page_info,
union gve_rx_data_slot *data_slot)
{
dma_addr_t dma = (dma_addr_t)(be64_to_cpu(data_slot->addr) &
GVE_DATA_SLOT_ADDR_PAGE_MASK);
page_ref_sub(page_info->page, page_info->pagecnt_bias - 1);
gve_free_page(dev, page_info->page, dma, DMA_FROM_DEVICE);
}
static void gve_rx_unfill_pages(struct gve_priv *priv, struct gve_rx_ring *rx)
{
u32 slots = rx->mask + 1;
int i;
if (rx->data.raw_addressing) {
for (i = 0; i < slots; i++)
gve_rx_free_buffer(&priv->pdev->dev, &rx->data.page_info[i],
&rx->data.data_ring[i]);
} else {
for (i = 0; i < slots; i++)
page_ref_sub(rx->data.page_info[i].page,
rx->data.page_info[i].pagecnt_bias - 1);
gve_unassign_qpl(priv, rx->data.qpl->id);
rx->data.qpl = NULL;
for (i = 0; i < rx->qpl_copy_pool_mask + 1; i++) {
page_ref_sub(rx->qpl_copy_pool[i].page,
rx->qpl_copy_pool[i].pagecnt_bias - 1);
put_page(rx->qpl_copy_pool[i].page);
}
}
kvfree(rx->data.page_info);
rx->data.page_info = NULL;
}
static void gve_rx_free_ring(struct gve_priv *priv, int idx)
{
struct gve_rx_ring *rx = &priv->rx[idx];
struct device *dev = &priv->pdev->dev;
u32 slots = rx->mask + 1;
size_t bytes;
gve_rx_remove_from_block(priv, idx);
bytes = sizeof(struct gve_rx_desc) * priv->rx_desc_cnt;
dma_free_coherent(dev, bytes, rx->desc.desc_ring, rx->desc.bus);
rx->desc.desc_ring = NULL;
dma_free_coherent(dev, sizeof(*rx->q_resources),
rx->q_resources, rx->q_resources_bus);
rx->q_resources = NULL;
gve_rx_unfill_pages(priv, rx);
bytes = sizeof(*rx->data.data_ring) * slots;
dma_free_coherent(dev, bytes, rx->data.data_ring,
rx->data.data_bus);
rx->data.data_ring = NULL;
kvfree(rx->qpl_copy_pool);
rx->qpl_copy_pool = NULL;
netif_dbg(priv, drv, priv->dev, "freed rx ring %d\n", idx);
}
static void gve_setup_rx_buffer(struct gve_rx_slot_page_info *page_info,
dma_addr_t addr, struct page *page, __be64 *slot_addr)
{
page_info->page = page;
page_info->page_offset = 0;
page_info->page_address = page_address(page);
*slot_addr = cpu_to_be64(addr);
/* The page already has 1 ref */
page_ref_add(page, INT_MAX - 1);
page_info->pagecnt_bias = INT_MAX;
}
static int gve_rx_alloc_buffer(struct gve_priv *priv, struct device *dev,
struct gve_rx_slot_page_info *page_info,
union gve_rx_data_slot *data_slot)
{
struct page *page;
dma_addr_t dma;
int err;
err = gve_alloc_page(priv, dev, &page, &dma, DMA_FROM_DEVICE,
GFP_ATOMIC);
if (err)
return err;
gve_setup_rx_buffer(page_info, dma, page, &data_slot->addr);
return 0;
}
static int gve_prefill_rx_pages(struct gve_rx_ring *rx)
{
struct gve_priv *priv = rx->gve;
u32 slots;
int err;
int i;
int j;
/* Allocate one page per Rx queue slot. Each page is split into two
* packet buffers, when possible we "page flip" between the two.
*/
slots = rx->mask + 1;
rx->data.page_info = kvzalloc(slots *
sizeof(*rx->data.page_info), GFP_KERNEL);
if (!rx->data.page_info)
return -ENOMEM;
if (!rx->data.raw_addressing) {
rx->data.qpl = gve_assign_rx_qpl(priv, rx->q_num);
if (!rx->data.qpl) {
kvfree(rx->data.page_info);
rx->data.page_info = NULL;
return -ENOMEM;
}
}
for (i = 0; i < slots; i++) {
if (!rx->data.raw_addressing) {
struct page *page = rx->data.qpl->pages[i];
dma_addr_t addr = i * PAGE_SIZE;
gve_setup_rx_buffer(&rx->data.page_info[i], addr, page,
&rx->data.data_ring[i].qpl_offset);
continue;
}
err = gve_rx_alloc_buffer(priv, &priv->pdev->dev, &rx->data.page_info[i],
&rx->data.data_ring[i]);
if (err)
goto alloc_err;
}
if (!rx->data.raw_addressing) {
for (j = 0; j < rx->qpl_copy_pool_mask + 1; j++) {
struct page *page = alloc_page(GFP_KERNEL);
if (!page) {
err = -ENOMEM;
goto alloc_err_qpl;
}
rx->qpl_copy_pool[j].page = page;
rx->qpl_copy_pool[j].page_offset = 0;
rx->qpl_copy_pool[j].page_address = page_address(page);
/* The page already has 1 ref. */
page_ref_add(page, INT_MAX - 1);
rx->qpl_copy_pool[j].pagecnt_bias = INT_MAX;
}
}
return slots;
alloc_err_qpl:
while (j--) {
page_ref_sub(rx->qpl_copy_pool[j].page,
rx->qpl_copy_pool[j].pagecnt_bias - 1);
put_page(rx->qpl_copy_pool[j].page);
}
alloc_err:
while (i--)
gve_rx_free_buffer(&priv->pdev->dev,
&rx->data.page_info[i],
&rx->data.data_ring[i]);
return err;
}
static void gve_rx_ctx_clear(struct gve_rx_ctx *ctx)
{
ctx->skb_head = NULL;
ctx->skb_tail = NULL;
ctx->total_size = 0;
ctx->frag_cnt = 0;
ctx->drop_pkt = false;
}
static int gve_rx_alloc_ring(struct gve_priv *priv, int idx)
{
struct gve_rx_ring *rx = &priv->rx[idx];
struct device *hdev = &priv->pdev->dev;
u32 slots, npages;
int filled_pages;
size_t bytes;
int err;
netif_dbg(priv, drv, priv->dev, "allocating rx ring\n");
/* Make sure everything is zeroed to start with */
memset(rx, 0, sizeof(*rx));
rx->gve = priv;
rx->q_num = idx;
slots = priv->rx_data_slot_cnt;
rx->mask = slots - 1;
rx->data.raw_addressing = priv->queue_format == GVE_GQI_RDA_FORMAT;
/* alloc rx data ring */
bytes = sizeof(*rx->data.data_ring) * slots;
rx->data.data_ring = dma_alloc_coherent(hdev, bytes,
&rx->data.data_bus,
GFP_KERNEL);
if (!rx->data.data_ring)
return -ENOMEM;
rx->qpl_copy_pool_mask = min_t(u32, U32_MAX, slots * 2) - 1;
rx->qpl_copy_pool_head = 0;
rx->qpl_copy_pool = kvcalloc(rx->qpl_copy_pool_mask + 1,
sizeof(rx->qpl_copy_pool[0]),
GFP_KERNEL);
if (!rx->qpl_copy_pool) {
err = -ENOMEM;
goto abort_with_slots;
}
filled_pages = gve_prefill_rx_pages(rx);
if (filled_pages < 0) {
err = -ENOMEM;
goto abort_with_copy_pool;
}
rx->fill_cnt = filled_pages;
/* Ensure data ring slots (packet buffers) are visible. */
dma_wmb();
/* Alloc gve_queue_resources */
rx->q_resources =
dma_alloc_coherent(hdev,
sizeof(*rx->q_resources),
&rx->q_resources_bus,
GFP_KERNEL);
if (!rx->q_resources) {
err = -ENOMEM;
goto abort_filled;
}
netif_dbg(priv, drv, priv->dev, "rx[%d]->data.data_bus=%lx\n", idx,
(unsigned long)rx->data.data_bus);
/* alloc rx desc ring */
bytes = sizeof(struct gve_rx_desc) * priv->rx_desc_cnt;
npages = bytes / PAGE_SIZE;
if (npages * PAGE_SIZE != bytes) {
err = -EIO;
goto abort_with_q_resources;
}
rx->desc.desc_ring = dma_alloc_coherent(hdev, bytes, &rx->desc.bus,
GFP_KERNEL);
if (!rx->desc.desc_ring) {
err = -ENOMEM;
goto abort_with_q_resources;
}
rx->cnt = 0;
rx->db_threshold = priv->rx_desc_cnt / 2;
rx->desc.seqno = 1;
/* Allocating half-page buffers allows page-flipping which is faster
* than copying or allocating new pages.
*/
rx->packet_buffer_size = PAGE_SIZE / 2;
gve_rx_ctx_clear(&rx->ctx);
gve_rx_add_to_block(priv, idx);
return 0;
abort_with_q_resources:
dma_free_coherent(hdev, sizeof(*rx->q_resources),
rx->q_resources, rx->q_resources_bus);
rx->q_resources = NULL;
abort_filled:
gve_rx_unfill_pages(priv, rx);
abort_with_copy_pool:
kvfree(rx->qpl_copy_pool);
rx->qpl_copy_pool = NULL;
abort_with_slots:
bytes = sizeof(*rx->data.data_ring) * slots;
dma_free_coherent(hdev, bytes, rx->data.data_ring, rx->data.data_bus);
rx->data.data_ring = NULL;
return err;
}
int gve_rx_alloc_rings(struct gve_priv *priv)
{
int err = 0;
int i;
for (i = 0; i < priv->rx_cfg.num_queues; i++) {
err = gve_rx_alloc_ring(priv, i);
if (err) {
netif_err(priv, drv, priv->dev,
"Failed to alloc rx ring=%d: err=%d\n",
i, err);
break;
}
}
/* Unallocate if there was an error */
if (err) {
int j;
for (j = 0; j < i; j++)
gve_rx_free_ring(priv, j);
}
return err;
}
void gve_rx_free_rings_gqi(struct gve_priv *priv)
{
int i;
for (i = 0; i < priv->rx_cfg.num_queues; i++)
gve_rx_free_ring(priv, i);
}
void gve_rx_write_doorbell(struct gve_priv *priv, struct gve_rx_ring *rx)
{
u32 db_idx = be32_to_cpu(rx->q_resources->db_index);
iowrite32be(rx->fill_cnt, &priv->db_bar2[db_idx]);
}
static enum pkt_hash_types gve_rss_type(__be16 pkt_flags)
{
if (likely(pkt_flags & (GVE_RXF_TCP | GVE_RXF_UDP)))
return PKT_HASH_TYPE_L4;
if (pkt_flags & (GVE_RXF_IPV4 | GVE_RXF_IPV6))
return PKT_HASH_TYPE_L3;
return PKT_HASH_TYPE_L2;
}
static struct sk_buff *gve_rx_add_frags(struct napi_struct *napi,
struct gve_rx_slot_page_info *page_info,
u16 packet_buffer_size, u16 len,
struct gve_rx_ctx *ctx)
{
u32 offset = page_info->page_offset + page_info->pad;
struct sk_buff *skb = ctx->skb_tail;
int num_frags = 0;
if (!skb) {
skb = napi_get_frags(napi);
if (unlikely(!skb))
return NULL;
ctx->skb_head = skb;
ctx->skb_tail = skb;
} else {
num_frags = skb_shinfo(ctx->skb_tail)->nr_frags;
if (num_frags == MAX_SKB_FRAGS) {
skb = napi_alloc_skb(napi, 0);
if (!skb)
return NULL;
// We will never chain more than two SKBs: 2 * 16 * 2k > 64k
// which is why we do not need to chain by using skb->next
skb_shinfo(ctx->skb_tail)->frag_list = skb;
ctx->skb_tail = skb;
num_frags = 0;
}
}
if (skb != ctx->skb_head) {
ctx->skb_head->len += len;
ctx->skb_head->data_len += len;
ctx->skb_head->truesize += packet_buffer_size;
}
skb_add_rx_frag(skb, num_frags, page_info->page,
offset, len, packet_buffer_size);
return ctx->skb_head;
}
static void gve_rx_flip_buff(struct gve_rx_slot_page_info *page_info, __be64 *slot_addr)
{
const __be64 offset = cpu_to_be64(PAGE_SIZE / 2);
/* "flip" to other packet buffer on this page */
page_info->page_offset ^= PAGE_SIZE / 2;
*(slot_addr) ^= offset;
}
static int gve_rx_can_recycle_buffer(struct gve_rx_slot_page_info *page_info)
{
int pagecount = page_count(page_info->page);
/* This page is not being used by any SKBs - reuse */
if (pagecount == page_info->pagecnt_bias)
return 1;
/* This page is still being used by an SKB - we can't reuse */
else if (pagecount > page_info->pagecnt_bias)
return 0;
WARN(pagecount < page_info->pagecnt_bias,
"Pagecount should never be less than the bias.");
return -1;
}
static struct sk_buff *
gve_rx_raw_addressing(struct device *dev, struct net_device *netdev,
struct gve_rx_slot_page_info *page_info, u16 len,
struct napi_struct *napi,
union gve_rx_data_slot *data_slot,
u16 packet_buffer_size, struct gve_rx_ctx *ctx)
{
struct sk_buff *skb = gve_rx_add_frags(napi, page_info, packet_buffer_size, len, ctx);
if (!skb)
return NULL;
/* Optimistically stop the kernel from freeing the page.
* We will check again in refill to determine if we need to alloc a
* new page.
*/
gve_dec_pagecnt_bias(page_info);
return skb;
}
static struct sk_buff *gve_rx_copy_to_pool(struct gve_rx_ring *rx,
struct gve_rx_slot_page_info *page_info,
u16 len, struct napi_struct *napi)
{
u32 pool_idx = rx->qpl_copy_pool_head & rx->qpl_copy_pool_mask;
void *src = page_info->page_address + page_info->page_offset;
struct gve_rx_slot_page_info *copy_page_info;
struct gve_rx_ctx *ctx = &rx->ctx;
bool alloc_page = false;
struct sk_buff *skb;
void *dst;
copy_page_info = &rx->qpl_copy_pool[pool_idx];
if (!copy_page_info->can_flip) {
int recycle = gve_rx_can_recycle_buffer(copy_page_info);
if (unlikely(recycle < 0)) {
gve_schedule_reset(rx->gve);
return NULL;
}
alloc_page = !recycle;
}
if (alloc_page) {
struct gve_rx_slot_page_info alloc_page_info;
struct page *page;
/* The least recently used page turned out to be
* still in use by the kernel. Ignoring it and moving
* on alleviates head-of-line blocking.
*/
rx->qpl_copy_pool_head++;
page = alloc_page(GFP_ATOMIC);
if (!page)
return NULL;
alloc_page_info.page = page;
alloc_page_info.page_offset = 0;
alloc_page_info.page_address = page_address(page);
alloc_page_info.pad = page_info->pad;
memcpy(alloc_page_info.page_address, src, page_info->pad + len);
skb = gve_rx_add_frags(napi, &alloc_page_info,
rx->packet_buffer_size,
len, ctx);
u64_stats_update_begin(&rx->statss);
rx->rx_frag_copy_cnt++;
rx->rx_frag_alloc_cnt++;
u64_stats_update_end(&rx->statss);
return skb;
}
dst = copy_page_info->page_address + copy_page_info->page_offset;
memcpy(dst, src, page_info->pad + len);
copy_page_info->pad = page_info->pad;
skb = gve_rx_add_frags(napi, copy_page_info,
rx->packet_buffer_size, len, ctx);
if (unlikely(!skb))
return NULL;
gve_dec_pagecnt_bias(copy_page_info);
copy_page_info->page_offset += rx->packet_buffer_size;
copy_page_info->page_offset &= (PAGE_SIZE - 1);
if (copy_page_info->can_flip) {
/* We have used both halves of this copy page, it
* is time for it to go to the back of the queue.
*/
copy_page_info->can_flip = false;
rx->qpl_copy_pool_head++;
prefetch(rx->qpl_copy_pool[rx->qpl_copy_pool_head & rx->qpl_copy_pool_mask].page);
} else {
copy_page_info->can_flip = true;
}
u64_stats_update_begin(&rx->statss);
rx->rx_frag_copy_cnt++;
u64_stats_update_end(&rx->statss);
return skb;
}
static struct sk_buff *
gve_rx_qpl(struct device *dev, struct net_device *netdev,
struct gve_rx_ring *rx, struct gve_rx_slot_page_info *page_info,
u16 len, struct napi_struct *napi,
union gve_rx_data_slot *data_slot)
{
struct gve_rx_ctx *ctx = &rx->ctx;
struct sk_buff *skb;
/* if raw_addressing mode is not enabled gvnic can only receive into
* registered segments. If the buffer can't be recycled, our only
* choice is to copy the data out of it so that we can return it to the
* device.
*/
if (page_info->can_flip) {
skb = gve_rx_add_frags(napi, page_info, rx->packet_buffer_size, len, ctx);
/* No point in recycling if we didn't get the skb */
if (skb) {
/* Make sure that the page isn't freed. */
gve_dec_pagecnt_bias(page_info);
gve_rx_flip_buff(page_info, &data_slot->qpl_offset);
}
} else {
skb = gve_rx_copy_to_pool(rx, page_info, len, napi);
}
return skb;
}
static struct sk_buff *gve_rx_skb(struct gve_priv *priv, struct gve_rx_ring *rx,
struct gve_rx_slot_page_info *page_info, struct napi_struct *napi,
u16 len, union gve_rx_data_slot *data_slot,
bool is_only_frag)
{
struct net_device *netdev = priv->dev;
struct gve_rx_ctx *ctx = &rx->ctx;
struct sk_buff *skb = NULL;
if (len <= priv->rx_copybreak && is_only_frag) {
/* Just copy small packets */
skb = gve_rx_copy(netdev, napi, page_info, len);
if (skb) {
u64_stats_update_begin(&rx->statss);
rx->rx_copied_pkt++;
rx->rx_frag_copy_cnt++;
rx->rx_copybreak_pkt++;
u64_stats_update_end(&rx->statss);
}
} else {
int recycle = gve_rx_can_recycle_buffer(page_info);
if (unlikely(recycle < 0)) {
gve_schedule_reset(priv);
return NULL;
}
page_info->can_flip = recycle;
if (page_info->can_flip) {
u64_stats_update_begin(&rx->statss);
rx->rx_frag_flip_cnt++;
u64_stats_update_end(&rx->statss);
}
if (rx->data.raw_addressing) {
skb = gve_rx_raw_addressing(&priv->pdev->dev, netdev,
page_info, len, napi,
data_slot,
rx->packet_buffer_size, ctx);
} else {
skb = gve_rx_qpl(&priv->pdev->dev, netdev, rx,
page_info, len, napi, data_slot);
}
}
return skb;
}
static int gve_xsk_pool_redirect(struct net_device *dev,
struct gve_rx_ring *rx,
void *data, int len,
struct bpf_prog *xdp_prog)
{
struct xdp_buff *xdp;
int err;
if (rx->xsk_pool->frame_len < len)
return -E2BIG;
xdp = xsk_buff_alloc(rx->xsk_pool);
if (!xdp) {
u64_stats_update_begin(&rx->statss);
rx->xdp_alloc_fails++;
u64_stats_update_end(&rx->statss);
return -ENOMEM;
}
xdp->data_end = xdp->data + len;
memcpy(xdp->data, data, len);
err = xdp_do_redirect(dev, xdp, xdp_prog);
if (err)
xsk_buff_free(xdp);
return err;
}
static int gve_xdp_redirect(struct net_device *dev, struct gve_rx_ring *rx,
struct xdp_buff *orig, struct bpf_prog *xdp_prog)
{
int total_len, len = orig->data_end - orig->data;
int headroom = XDP_PACKET_HEADROOM;
struct xdp_buff new;
void *frame;
int err;
if (rx->xsk_pool)
return gve_xsk_pool_redirect(dev, rx, orig->data,
len, xdp_prog);
total_len = headroom + SKB_DATA_ALIGN(len) +
SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
frame = page_frag_alloc(&rx->page_cache, total_len, GFP_ATOMIC);
if (!frame) {
u64_stats_update_begin(&rx->statss);
rx->xdp_alloc_fails++;
u64_stats_update_end(&rx->statss);
return -ENOMEM;
}
xdp_init_buff(&new, total_len, &rx->xdp_rxq);
xdp_prepare_buff(&new, frame, headroom, len, false);
memcpy(new.data, orig->data, len);
err = xdp_do_redirect(dev, &new, xdp_prog);
if (err)
page_frag_free(frame);
return err;
}
static void gve_xdp_done(struct gve_priv *priv, struct gve_rx_ring *rx,
struct xdp_buff *xdp, struct bpf_prog *xprog,
int xdp_act)
{
struct gve_tx_ring *tx;
int tx_qid;
int err;
switch (xdp_act) {
case XDP_ABORTED:
case XDP_DROP:
default:
break;
case XDP_TX:
tx_qid = gve_xdp_tx_queue_id(priv, rx->q_num);
tx = &priv->tx[tx_qid];
spin_lock(&tx->xdp_lock);
err = gve_xdp_xmit_one(priv, tx, xdp->data,
xdp->data_end - xdp->data, NULL);
spin_unlock(&tx->xdp_lock);
if (unlikely(err)) {
u64_stats_update_begin(&rx->statss);
rx->xdp_tx_errors++;
u64_stats_update_end(&rx->statss);
}
break;
case XDP_REDIRECT:
err = gve_xdp_redirect(priv->dev, rx, xdp, xprog);
if (unlikely(err)) {
u64_stats_update_begin(&rx->statss);
rx->xdp_redirect_errors++;
u64_stats_update_end(&rx->statss);
}
break;
}
u64_stats_update_begin(&rx->statss);
if ((u32)xdp_act < GVE_XDP_ACTIONS)
rx->xdp_actions[xdp_act]++;
u64_stats_update_end(&rx->statss);
}
#define GVE_PKTCONT_BIT_IS_SET(x) (GVE_RXF_PKT_CONT & (x))
static void gve_rx(struct gve_rx_ring *rx, netdev_features_t feat,
struct gve_rx_desc *desc, u32 idx,
struct gve_rx_cnts *cnts)
{
bool is_last_frag = !GVE_PKTCONT_BIT_IS_SET(desc->flags_seq);
struct gve_rx_slot_page_info *page_info;
u16 frag_size = be16_to_cpu(desc->len);
struct gve_rx_ctx *ctx = &rx->ctx;
union gve_rx_data_slot *data_slot;
struct gve_priv *priv = rx->gve;
struct sk_buff *skb = NULL;
struct bpf_prog *xprog;
struct xdp_buff xdp;
dma_addr_t page_bus;
void *va;
u16 len = frag_size;
struct napi_struct *napi = &priv->ntfy_blocks[rx->ntfy_id].napi;
bool is_first_frag = ctx->frag_cnt == 0;
bool is_only_frag = is_first_frag && is_last_frag;
if (unlikely(ctx->drop_pkt))
goto finish_frag;
if (desc->flags_seq & GVE_RXF_ERR) {
ctx->drop_pkt = true;
cnts->desc_err_pkt_cnt++;
napi_free_frags(napi);
goto finish_frag;
}
if (unlikely(frag_size > rx->packet_buffer_size)) {
netdev_warn(priv->dev, "Unexpected frag size %d, can't exceed %d, scheduling reset",
frag_size, rx->packet_buffer_size);
ctx->drop_pkt = true;
napi_free_frags(napi);
gve_schedule_reset(rx->gve);
goto finish_frag;
}
/* Prefetch two packet buffers ahead, we will need it soon. */
page_info = &rx->data.page_info[(idx + 2) & rx->mask];
va = page_info->page_address + page_info->page_offset;
prefetch(page_info->page); /* Kernel page struct. */
prefetch(va); /* Packet header. */
prefetch(va + 64); /* Next cacheline too. */
page_info = &rx->data.page_info[idx];
data_slot = &rx->data.data_ring[idx];
page_bus = (rx->data.raw_addressing) ?
be64_to_cpu(data_slot->addr) - page_info->page_offset :
rx->data.qpl->page_buses[idx];
dma_sync_single_for_cpu(&priv->pdev->dev, page_bus,
PAGE_SIZE, DMA_FROM_DEVICE);
page_info->pad = is_first_frag ? GVE_RX_PAD : 0;
len -= page_info->pad;
frag_size -= page_info->pad;
xprog = READ_ONCE(priv->xdp_prog);
if (xprog && is_only_frag) {
void *old_data;
int xdp_act;
xdp_init_buff(&xdp, rx->packet_buffer_size, &rx->xdp_rxq);
xdp_prepare_buff(&xdp, page_info->page_address +
page_info->page_offset, GVE_RX_PAD,
len, false);
old_data = xdp.data;
xdp_act = bpf_prog_run_xdp(xprog, &xdp);
if (xdp_act != XDP_PASS) {
gve_xdp_done(priv, rx, &xdp, xprog, xdp_act);
ctx->total_size += frag_size;
goto finish_ok_pkt;
}
page_info->pad += xdp.data - old_data;
len = xdp.data_end - xdp.data;
u64_stats_update_begin(&rx->statss);
rx->xdp_actions[XDP_PASS]++;
u64_stats_update_end(&rx->statss);
}
skb = gve_rx_skb(priv, rx, page_info, napi, len,
data_slot, is_only_frag);
if (!skb) {
u64_stats_update_begin(&rx->statss);
rx->rx_skb_alloc_fail++;
u64_stats_update_end(&rx->statss);
napi_free_frags(napi);
ctx->drop_pkt = true;
goto finish_frag;
}
ctx->total_size += frag_size;
if (is_first_frag) {
if (likely(feat & NETIF_F_RXCSUM)) {
/* NIC passes up the partial sum */
if (desc->csum)
skb->ip_summed = CHECKSUM_COMPLETE;
else
skb->ip_summed = CHECKSUM_NONE;
skb->csum = csum_unfold(desc->csum);
}
/* parse flags & pass relevant info up */
if (likely(feat & NETIF_F_RXHASH) &&
gve_needs_rss(desc->flags_seq))
skb_set_hash(skb, be32_to_cpu(desc->rss_hash),
gve_rss_type(desc->flags_seq));
}
if (is_last_frag) {
skb_record_rx_queue(skb, rx->q_num);
if (skb_is_nonlinear(skb))
napi_gro_frags(napi);
else
napi_gro_receive(napi, skb);
goto finish_ok_pkt;
}
goto finish_frag;
finish_ok_pkt:
cnts->ok_pkt_bytes += ctx->total_size;
cnts->ok_pkt_cnt++;
finish_frag:
ctx->frag_cnt++;
if (is_last_frag) {
cnts->total_pkt_cnt++;
cnts->cont_pkt_cnt += (ctx->frag_cnt > 1);
gve_rx_ctx_clear(ctx);
}
}
bool gve_rx_work_pending(struct gve_rx_ring *rx)
{
struct gve_rx_desc *desc;
__be16 flags_seq;
u32 next_idx;
next_idx = rx->cnt & rx->mask;
desc = rx->desc.desc_ring + next_idx;
flags_seq = desc->flags_seq;
return (GVE_SEQNO(flags_seq) == rx->desc.seqno);
}
static bool gve_rx_refill_buffers(struct gve_priv *priv, struct gve_rx_ring *rx)
{
int refill_target = rx->mask + 1;
u32 fill_cnt = rx->fill_cnt;
while (fill_cnt - rx->cnt < refill_target) {
struct gve_rx_slot_page_info *page_info;
u32 idx = fill_cnt & rx->mask;
page_info = &rx->data.page_info[idx];
if (page_info->can_flip) {
/* The other half of the page is free because it was
* free when we processed the descriptor. Flip to it.
*/
union gve_rx_data_slot *data_slot =
&rx->data.data_ring[idx];
gve_rx_flip_buff(page_info, &data_slot->addr);
page_info->can_flip = 0;
} else {
/* It is possible that the networking stack has already
* finished processing all outstanding packets in the buffer
* and it can be reused.
* Flipping is unnecessary here - if the networking stack still
* owns half the page it is impossible to tell which half. Either
* the whole page is free or it needs to be replaced.
*/
int recycle = gve_rx_can_recycle_buffer(page_info);
if (recycle < 0) {
if (!rx->data.raw_addressing)
gve_schedule_reset(priv);
return false;
}
if (!recycle) {
/* We can't reuse the buffer - alloc a new one*/
union gve_rx_data_slot *data_slot =
&rx->data.data_ring[idx];
struct device *dev = &priv->pdev->dev;
gve_rx_free_buffer(dev, page_info, data_slot);
page_info->page = NULL;
if (gve_rx_alloc_buffer(priv, dev, page_info,
data_slot)) {
u64_stats_update_begin(&rx->statss);
rx->rx_buf_alloc_fail++;
u64_stats_update_end(&rx->statss);
break;
}
}
}
fill_cnt++;
}
rx->fill_cnt = fill_cnt;
return true;
}
static int gve_clean_rx_done(struct gve_rx_ring *rx, int budget,
netdev_features_t feat)
{
u64 xdp_redirects = rx->xdp_actions[XDP_REDIRECT];
u64 xdp_txs = rx->xdp_actions[XDP_TX];
struct gve_rx_ctx *ctx = &rx->ctx;
struct gve_priv *priv = rx->gve;
struct gve_rx_cnts cnts = {0};
struct gve_rx_desc *next_desc;
u32 idx = rx->cnt & rx->mask;
u32 work_done = 0;
struct gve_rx_desc *desc = &rx->desc.desc_ring[idx];
// Exceed budget only if (and till) the inflight packet is consumed.
while ((GVE_SEQNO(desc->flags_seq) == rx->desc.seqno) &&
(work_done < budget || ctx->frag_cnt)) {
next_desc = &rx->desc.desc_ring[(idx + 1) & rx->mask];
prefetch(next_desc);
gve_rx(rx, feat, desc, idx, &cnts);
rx->cnt++;
idx = rx->cnt & rx->mask;
desc = &rx->desc.desc_ring[idx];
rx->desc.seqno = gve_next_seqno(rx->desc.seqno);
work_done++;
}
// The device will only send whole packets.
if (unlikely(ctx->frag_cnt)) {
struct napi_struct *napi = &priv->ntfy_blocks[rx->ntfy_id].napi;
napi_free_frags(napi);
gve_rx_ctx_clear(&rx->ctx);
netdev_warn(priv->dev, "Unexpected seq number %d with incomplete packet, expected %d, scheduling reset",
GVE_SEQNO(desc->flags_seq), rx->desc.seqno);
gve_schedule_reset(rx->gve);
}
if (!work_done && rx->fill_cnt - rx->cnt > rx->db_threshold)
return 0;
if (work_done) {
u64_stats_update_begin(&rx->statss);
rx->rpackets += cnts.ok_pkt_cnt;
rx->rbytes += cnts.ok_pkt_bytes;
rx->rx_cont_packet_cnt += cnts.cont_pkt_cnt;
rx->rx_desc_err_dropped_pkt += cnts.desc_err_pkt_cnt;
u64_stats_update_end(&rx->statss);
}
if (xdp_txs != rx->xdp_actions[XDP_TX])
gve_xdp_tx_flush(priv, rx->q_num);
if (xdp_redirects != rx->xdp_actions[XDP_REDIRECT])
xdp_do_flush();
/* restock ring slots */
if (!rx->data.raw_addressing) {
/* In QPL mode buffs are refilled as the desc are processed */
rx->fill_cnt += work_done;
} else if (rx->fill_cnt - rx->cnt <= rx->db_threshold) {
/* In raw addressing mode buffs are only refilled if the avail
* falls below a threshold.
*/
if (!gve_rx_refill_buffers(priv, rx))
return 0;
/* If we were not able to completely refill buffers, we'll want
* to schedule this queue for work again to refill buffers.
*/
if (rx->fill_cnt - rx->cnt <= rx->db_threshold) {
gve_rx_write_doorbell(priv, rx);
return budget;
}
}
gve_rx_write_doorbell(priv, rx);
return cnts.total_pkt_cnt;
}
int gve_rx_poll(struct gve_notify_block *block, int budget)
{
struct gve_rx_ring *rx = block->rx;
netdev_features_t feat;
int work_done = 0;
feat = block->napi.dev->features;
/* If budget is 0, do all the work */
if (budget == 0)
budget = INT_MAX;
if (budget > 0)
work_done = gve_clean_rx_done(rx, budget, feat);
return work_done;
}
|
linux-master
|
drivers/net/ethernet/google/gve/gve_rx.c
|
// SPDX-License-Identifier: (GPL-2.0 OR MIT)
/* Google virtual Ethernet (gve) driver
*
* Copyright (C) 2015-2021 Google, Inc.
*/
#include <linux/bpf.h>
#include <linux/cpumask.h>
#include <linux/etherdevice.h>
#include <linux/filter.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/sched.h>
#include <linux/timer.h>
#include <linux/workqueue.h>
#include <linux/utsname.h>
#include <linux/version.h>
#include <net/sch_generic.h>
#include <net/xdp_sock_drv.h>
#include "gve.h"
#include "gve_dqo.h"
#include "gve_adminq.h"
#include "gve_register.h"
#define GVE_DEFAULT_RX_COPYBREAK (256)
#define DEFAULT_MSG_LEVEL (NETIF_MSG_DRV | NETIF_MSG_LINK)
#define GVE_VERSION "1.0.0"
#define GVE_VERSION_PREFIX "GVE-"
// Minimum amount of time between queue kicks in msec (10 seconds)
#define MIN_TX_TIMEOUT_GAP (1000 * 10)
char gve_driver_name[] = "gve";
const char gve_version_str[] = GVE_VERSION;
static const char gve_version_prefix[] = GVE_VERSION_PREFIX;
static int gve_verify_driver_compatibility(struct gve_priv *priv)
{
int err;
struct gve_driver_info *driver_info;
dma_addr_t driver_info_bus;
driver_info = dma_alloc_coherent(&priv->pdev->dev,
sizeof(struct gve_driver_info),
&driver_info_bus, GFP_KERNEL);
if (!driver_info)
return -ENOMEM;
*driver_info = (struct gve_driver_info) {
.os_type = 1, /* Linux */
.os_version_major = cpu_to_be32(LINUX_VERSION_MAJOR),
.os_version_minor = cpu_to_be32(LINUX_VERSION_SUBLEVEL),
.os_version_sub = cpu_to_be32(LINUX_VERSION_PATCHLEVEL),
.driver_capability_flags = {
cpu_to_be64(GVE_DRIVER_CAPABILITY_FLAGS1),
cpu_to_be64(GVE_DRIVER_CAPABILITY_FLAGS2),
cpu_to_be64(GVE_DRIVER_CAPABILITY_FLAGS3),
cpu_to_be64(GVE_DRIVER_CAPABILITY_FLAGS4),
},
};
strscpy(driver_info->os_version_str1, utsname()->release,
sizeof(driver_info->os_version_str1));
strscpy(driver_info->os_version_str2, utsname()->version,
sizeof(driver_info->os_version_str2));
err = gve_adminq_verify_driver_compatibility(priv,
sizeof(struct gve_driver_info),
driver_info_bus);
/* It's ok if the device doesn't support this */
if (err == -EOPNOTSUPP)
err = 0;
dma_free_coherent(&priv->pdev->dev,
sizeof(struct gve_driver_info),
driver_info, driver_info_bus);
return err;
}
static netdev_tx_t gve_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct gve_priv *priv = netdev_priv(dev);
if (gve_is_gqi(priv))
return gve_tx(skb, dev);
else
return gve_tx_dqo(skb, dev);
}
static void gve_get_stats(struct net_device *dev, struct rtnl_link_stats64 *s)
{
struct gve_priv *priv = netdev_priv(dev);
unsigned int start;
u64 packets, bytes;
int num_tx_queues;
int ring;
num_tx_queues = gve_num_tx_queues(priv);
if (priv->rx) {
for (ring = 0; ring < priv->rx_cfg.num_queues; ring++) {
do {
start =
u64_stats_fetch_begin(&priv->rx[ring].statss);
packets = priv->rx[ring].rpackets;
bytes = priv->rx[ring].rbytes;
} while (u64_stats_fetch_retry(&priv->rx[ring].statss,
start));
s->rx_packets += packets;
s->rx_bytes += bytes;
}
}
if (priv->tx) {
for (ring = 0; ring < num_tx_queues; ring++) {
do {
start =
u64_stats_fetch_begin(&priv->tx[ring].statss);
packets = priv->tx[ring].pkt_done;
bytes = priv->tx[ring].bytes_done;
} while (u64_stats_fetch_retry(&priv->tx[ring].statss,
start));
s->tx_packets += packets;
s->tx_bytes += bytes;
}
}
}
static int gve_alloc_counter_array(struct gve_priv *priv)
{
priv->counter_array =
dma_alloc_coherent(&priv->pdev->dev,
priv->num_event_counters *
sizeof(*priv->counter_array),
&priv->counter_array_bus, GFP_KERNEL);
if (!priv->counter_array)
return -ENOMEM;
return 0;
}
static void gve_free_counter_array(struct gve_priv *priv)
{
if (!priv->counter_array)
return;
dma_free_coherent(&priv->pdev->dev,
priv->num_event_counters *
sizeof(*priv->counter_array),
priv->counter_array, priv->counter_array_bus);
priv->counter_array = NULL;
}
/* NIC requests to report stats */
static void gve_stats_report_task(struct work_struct *work)
{
struct gve_priv *priv = container_of(work, struct gve_priv,
stats_report_task);
if (gve_get_do_report_stats(priv)) {
gve_handle_report_stats(priv);
gve_clear_do_report_stats(priv);
}
}
static void gve_stats_report_schedule(struct gve_priv *priv)
{
if (!gve_get_probe_in_progress(priv) &&
!gve_get_reset_in_progress(priv)) {
gve_set_do_report_stats(priv);
queue_work(priv->gve_wq, &priv->stats_report_task);
}
}
static void gve_stats_report_timer(struct timer_list *t)
{
struct gve_priv *priv = from_timer(priv, t, stats_report_timer);
mod_timer(&priv->stats_report_timer,
round_jiffies(jiffies +
msecs_to_jiffies(priv->stats_report_timer_period)));
gve_stats_report_schedule(priv);
}
static int gve_alloc_stats_report(struct gve_priv *priv)
{
int tx_stats_num, rx_stats_num;
tx_stats_num = (GVE_TX_STATS_REPORT_NUM + NIC_TX_STATS_REPORT_NUM) *
gve_num_tx_queues(priv);
rx_stats_num = (GVE_RX_STATS_REPORT_NUM + NIC_RX_STATS_REPORT_NUM) *
priv->rx_cfg.num_queues;
priv->stats_report_len = struct_size(priv->stats_report, stats,
tx_stats_num + rx_stats_num);
priv->stats_report =
dma_alloc_coherent(&priv->pdev->dev, priv->stats_report_len,
&priv->stats_report_bus, GFP_KERNEL);
if (!priv->stats_report)
return -ENOMEM;
/* Set up timer for the report-stats task */
timer_setup(&priv->stats_report_timer, gve_stats_report_timer, 0);
priv->stats_report_timer_period = GVE_STATS_REPORT_TIMER_PERIOD;
return 0;
}
static void gve_free_stats_report(struct gve_priv *priv)
{
if (!priv->stats_report)
return;
del_timer_sync(&priv->stats_report_timer);
dma_free_coherent(&priv->pdev->dev, priv->stats_report_len,
priv->stats_report, priv->stats_report_bus);
priv->stats_report = NULL;
}
static irqreturn_t gve_mgmnt_intr(int irq, void *arg)
{
struct gve_priv *priv = arg;
queue_work(priv->gve_wq, &priv->service_task);
return IRQ_HANDLED;
}
static irqreturn_t gve_intr(int irq, void *arg)
{
struct gve_notify_block *block = arg;
struct gve_priv *priv = block->priv;
iowrite32be(GVE_IRQ_MASK, gve_irq_doorbell(priv, block));
napi_schedule_irqoff(&block->napi);
return IRQ_HANDLED;
}
static irqreturn_t gve_intr_dqo(int irq, void *arg)
{
struct gve_notify_block *block = arg;
/* Interrupts are automatically masked */
napi_schedule_irqoff(&block->napi);
return IRQ_HANDLED;
}
static int gve_napi_poll(struct napi_struct *napi, int budget)
{
struct gve_notify_block *block;
__be32 __iomem *irq_doorbell;
bool reschedule = false;
struct gve_priv *priv;
int work_done = 0;
block = container_of(napi, struct gve_notify_block, napi);
priv = block->priv;
if (block->tx) {
if (block->tx->q_num < priv->tx_cfg.num_queues)
reschedule |= gve_tx_poll(block, budget);
else
reschedule |= gve_xdp_poll(block, budget);
}
if (block->rx) {
work_done = gve_rx_poll(block, budget);
reschedule |= work_done == budget;
}
if (reschedule)
return budget;
/* Complete processing - don't unmask irq if busy polling is enabled */
if (likely(napi_complete_done(napi, work_done))) {
irq_doorbell = gve_irq_doorbell(priv, block);
iowrite32be(GVE_IRQ_ACK | GVE_IRQ_EVENT, irq_doorbell);
/* Ensure IRQ ACK is visible before we check pending work.
* If queue had issued updates, it would be truly visible.
*/
mb();
if (block->tx)
reschedule |= gve_tx_clean_pending(priv, block->tx);
if (block->rx)
reschedule |= gve_rx_work_pending(block->rx);
if (reschedule && napi_reschedule(napi))
iowrite32be(GVE_IRQ_MASK, irq_doorbell);
}
return work_done;
}
static int gve_napi_poll_dqo(struct napi_struct *napi, int budget)
{
struct gve_notify_block *block =
container_of(napi, struct gve_notify_block, napi);
struct gve_priv *priv = block->priv;
bool reschedule = false;
int work_done = 0;
if (block->tx)
reschedule |= gve_tx_poll_dqo(block, /*do_clean=*/true);
if (block->rx) {
work_done = gve_rx_poll_dqo(block, budget);
reschedule |= work_done == budget;
}
if (reschedule)
return budget;
if (likely(napi_complete_done(napi, work_done))) {
/* Enable interrupts again.
*
* We don't need to repoll afterwards because HW supports the
* PCI MSI-X PBA feature.
*
* Another interrupt would be triggered if a new event came in
* since the last one.
*/
gve_write_irq_doorbell_dqo(priv, block,
GVE_ITR_NO_UPDATE_DQO | GVE_ITR_ENABLE_BIT_DQO);
}
return work_done;
}
static int gve_alloc_notify_blocks(struct gve_priv *priv)
{
int num_vecs_requested = priv->num_ntfy_blks + 1;
unsigned int active_cpus;
int vecs_enabled;
int i, j;
int err;
priv->msix_vectors = kvcalloc(num_vecs_requested,
sizeof(*priv->msix_vectors), GFP_KERNEL);
if (!priv->msix_vectors)
return -ENOMEM;
for (i = 0; i < num_vecs_requested; i++)
priv->msix_vectors[i].entry = i;
vecs_enabled = pci_enable_msix_range(priv->pdev, priv->msix_vectors,
GVE_MIN_MSIX, num_vecs_requested);
if (vecs_enabled < 0) {
dev_err(&priv->pdev->dev, "Could not enable min msix %d/%d\n",
GVE_MIN_MSIX, vecs_enabled);
err = vecs_enabled;
goto abort_with_msix_vectors;
}
if (vecs_enabled != num_vecs_requested) {
int new_num_ntfy_blks = (vecs_enabled - 1) & ~0x1;
int vecs_per_type = new_num_ntfy_blks / 2;
int vecs_left = new_num_ntfy_blks % 2;
priv->num_ntfy_blks = new_num_ntfy_blks;
priv->mgmt_msix_idx = priv->num_ntfy_blks;
priv->tx_cfg.max_queues = min_t(int, priv->tx_cfg.max_queues,
vecs_per_type);
priv->rx_cfg.max_queues = min_t(int, priv->rx_cfg.max_queues,
vecs_per_type + vecs_left);
dev_err(&priv->pdev->dev,
"Could not enable desired msix, only enabled %d, adjusting tx max queues to %d, and rx max queues to %d\n",
vecs_enabled, priv->tx_cfg.max_queues,
priv->rx_cfg.max_queues);
if (priv->tx_cfg.num_queues > priv->tx_cfg.max_queues)
priv->tx_cfg.num_queues = priv->tx_cfg.max_queues;
if (priv->rx_cfg.num_queues > priv->rx_cfg.max_queues)
priv->rx_cfg.num_queues = priv->rx_cfg.max_queues;
}
/* Half the notification blocks go to TX and half to RX */
active_cpus = min_t(int, priv->num_ntfy_blks / 2, num_online_cpus());
/* Setup Management Vector - the last vector */
snprintf(priv->mgmt_msix_name, sizeof(priv->mgmt_msix_name), "gve-mgmnt@pci:%s",
pci_name(priv->pdev));
err = request_irq(priv->msix_vectors[priv->mgmt_msix_idx].vector,
gve_mgmnt_intr, 0, priv->mgmt_msix_name, priv);
if (err) {
dev_err(&priv->pdev->dev, "Did not receive management vector.\n");
goto abort_with_msix_enabled;
}
priv->irq_db_indices =
dma_alloc_coherent(&priv->pdev->dev,
priv->num_ntfy_blks *
sizeof(*priv->irq_db_indices),
&priv->irq_db_indices_bus, GFP_KERNEL);
if (!priv->irq_db_indices) {
err = -ENOMEM;
goto abort_with_mgmt_vector;
}
priv->ntfy_blocks = kvzalloc(priv->num_ntfy_blks *
sizeof(*priv->ntfy_blocks), GFP_KERNEL);
if (!priv->ntfy_blocks) {
err = -ENOMEM;
goto abort_with_irq_db_indices;
}
/* Setup the other blocks - the first n-1 vectors */
for (i = 0; i < priv->num_ntfy_blks; i++) {
struct gve_notify_block *block = &priv->ntfy_blocks[i];
int msix_idx = i;
snprintf(block->name, sizeof(block->name), "gve-ntfy-blk%d@pci:%s",
i, pci_name(priv->pdev));
block->priv = priv;
err = request_irq(priv->msix_vectors[msix_idx].vector,
gve_is_gqi(priv) ? gve_intr : gve_intr_dqo,
0, block->name, block);
if (err) {
dev_err(&priv->pdev->dev,
"Failed to receive msix vector %d\n", i);
goto abort_with_some_ntfy_blocks;
}
irq_set_affinity_hint(priv->msix_vectors[msix_idx].vector,
get_cpu_mask(i % active_cpus));
block->irq_db_index = &priv->irq_db_indices[i].index;
}
return 0;
abort_with_some_ntfy_blocks:
for (j = 0; j < i; j++) {
struct gve_notify_block *block = &priv->ntfy_blocks[j];
int msix_idx = j;
irq_set_affinity_hint(priv->msix_vectors[msix_idx].vector,
NULL);
free_irq(priv->msix_vectors[msix_idx].vector, block);
}
kvfree(priv->ntfy_blocks);
priv->ntfy_blocks = NULL;
abort_with_irq_db_indices:
dma_free_coherent(&priv->pdev->dev, priv->num_ntfy_blks *
sizeof(*priv->irq_db_indices),
priv->irq_db_indices, priv->irq_db_indices_bus);
priv->irq_db_indices = NULL;
abort_with_mgmt_vector:
free_irq(priv->msix_vectors[priv->mgmt_msix_idx].vector, priv);
abort_with_msix_enabled:
pci_disable_msix(priv->pdev);
abort_with_msix_vectors:
kvfree(priv->msix_vectors);
priv->msix_vectors = NULL;
return err;
}
static void gve_free_notify_blocks(struct gve_priv *priv)
{
int i;
if (!priv->msix_vectors)
return;
/* Free the irqs */
for (i = 0; i < priv->num_ntfy_blks; i++) {
struct gve_notify_block *block = &priv->ntfy_blocks[i];
int msix_idx = i;
irq_set_affinity_hint(priv->msix_vectors[msix_idx].vector,
NULL);
free_irq(priv->msix_vectors[msix_idx].vector, block);
}
free_irq(priv->msix_vectors[priv->mgmt_msix_idx].vector, priv);
kvfree(priv->ntfy_blocks);
priv->ntfy_blocks = NULL;
dma_free_coherent(&priv->pdev->dev, priv->num_ntfy_blks *
sizeof(*priv->irq_db_indices),
priv->irq_db_indices, priv->irq_db_indices_bus);
priv->irq_db_indices = NULL;
pci_disable_msix(priv->pdev);
kvfree(priv->msix_vectors);
priv->msix_vectors = NULL;
}
static int gve_setup_device_resources(struct gve_priv *priv)
{
int err;
err = gve_alloc_counter_array(priv);
if (err)
return err;
err = gve_alloc_notify_blocks(priv);
if (err)
goto abort_with_counter;
err = gve_alloc_stats_report(priv);
if (err)
goto abort_with_ntfy_blocks;
err = gve_adminq_configure_device_resources(priv,
priv->counter_array_bus,
priv->num_event_counters,
priv->irq_db_indices_bus,
priv->num_ntfy_blks);
if (unlikely(err)) {
dev_err(&priv->pdev->dev,
"could not setup device_resources: err=%d\n", err);
err = -ENXIO;
goto abort_with_stats_report;
}
if (!gve_is_gqi(priv)) {
priv->ptype_lut_dqo = kvzalloc(sizeof(*priv->ptype_lut_dqo),
GFP_KERNEL);
if (!priv->ptype_lut_dqo) {
err = -ENOMEM;
goto abort_with_stats_report;
}
err = gve_adminq_get_ptype_map_dqo(priv, priv->ptype_lut_dqo);
if (err) {
dev_err(&priv->pdev->dev,
"Failed to get ptype map: err=%d\n", err);
goto abort_with_ptype_lut;
}
}
err = gve_adminq_report_stats(priv, priv->stats_report_len,
priv->stats_report_bus,
GVE_STATS_REPORT_TIMER_PERIOD);
if (err)
dev_err(&priv->pdev->dev,
"Failed to report stats: err=%d\n", err);
gve_set_device_resources_ok(priv);
return 0;
abort_with_ptype_lut:
kvfree(priv->ptype_lut_dqo);
priv->ptype_lut_dqo = NULL;
abort_with_stats_report:
gve_free_stats_report(priv);
abort_with_ntfy_blocks:
gve_free_notify_blocks(priv);
abort_with_counter:
gve_free_counter_array(priv);
return err;
}
static void gve_trigger_reset(struct gve_priv *priv);
static void gve_teardown_device_resources(struct gve_priv *priv)
{
int err;
/* Tell device its resources are being freed */
if (gve_get_device_resources_ok(priv)) {
/* detach the stats report */
err = gve_adminq_report_stats(priv, 0, 0x0, GVE_STATS_REPORT_TIMER_PERIOD);
if (err) {
dev_err(&priv->pdev->dev,
"Failed to detach stats report: err=%d\n", err);
gve_trigger_reset(priv);
}
err = gve_adminq_deconfigure_device_resources(priv);
if (err) {
dev_err(&priv->pdev->dev,
"Could not deconfigure device resources: err=%d\n",
err);
gve_trigger_reset(priv);
}
}
kvfree(priv->ptype_lut_dqo);
priv->ptype_lut_dqo = NULL;
gve_free_counter_array(priv);
gve_free_notify_blocks(priv);
gve_free_stats_report(priv);
gve_clear_device_resources_ok(priv);
}
static void gve_add_napi(struct gve_priv *priv, int ntfy_idx,
int (*gve_poll)(struct napi_struct *, int))
{
struct gve_notify_block *block = &priv->ntfy_blocks[ntfy_idx];
netif_napi_add(priv->dev, &block->napi, gve_poll);
}
static void gve_remove_napi(struct gve_priv *priv, int ntfy_idx)
{
struct gve_notify_block *block = &priv->ntfy_blocks[ntfy_idx];
netif_napi_del(&block->napi);
}
static int gve_register_xdp_qpls(struct gve_priv *priv)
{
int start_id;
int err;
int i;
start_id = gve_tx_qpl_id(priv, gve_xdp_tx_start_queue_id(priv));
for (i = start_id; i < start_id + gve_num_xdp_qpls(priv); i++) {
err = gve_adminq_register_page_list(priv, &priv->qpls[i]);
if (err) {
netif_err(priv, drv, priv->dev,
"failed to register queue page list %d\n",
priv->qpls[i].id);
/* This failure will trigger a reset - no need to clean
* up
*/
return err;
}
}
return 0;
}
static int gve_register_qpls(struct gve_priv *priv)
{
int start_id;
int err;
int i;
start_id = gve_tx_start_qpl_id(priv);
for (i = start_id; i < start_id + gve_num_tx_qpls(priv); i++) {
err = gve_adminq_register_page_list(priv, &priv->qpls[i]);
if (err) {
netif_err(priv, drv, priv->dev,
"failed to register queue page list %d\n",
priv->qpls[i].id);
/* This failure will trigger a reset - no need to clean
* up
*/
return err;
}
}
start_id = gve_rx_start_qpl_id(priv);
for (i = start_id; i < start_id + gve_num_rx_qpls(priv); i++) {
err = gve_adminq_register_page_list(priv, &priv->qpls[i]);
if (err) {
netif_err(priv, drv, priv->dev,
"failed to register queue page list %d\n",
priv->qpls[i].id);
/* This failure will trigger a reset - no need to clean
* up
*/
return err;
}
}
return 0;
}
static int gve_unregister_xdp_qpls(struct gve_priv *priv)
{
int start_id;
int err;
int i;
start_id = gve_tx_qpl_id(priv, gve_xdp_tx_start_queue_id(priv));
for (i = start_id; i < start_id + gve_num_xdp_qpls(priv); i++) {
err = gve_adminq_unregister_page_list(priv, priv->qpls[i].id);
/* This failure will trigger a reset - no need to clean up */
if (err) {
netif_err(priv, drv, priv->dev,
"Failed to unregister queue page list %d\n",
priv->qpls[i].id);
return err;
}
}
return 0;
}
static int gve_unregister_qpls(struct gve_priv *priv)
{
int start_id;
int err;
int i;
start_id = gve_tx_start_qpl_id(priv);
for (i = start_id; i < start_id + gve_num_tx_qpls(priv); i++) {
err = gve_adminq_unregister_page_list(priv, priv->qpls[i].id);
/* This failure will trigger a reset - no need to clean up */
if (err) {
netif_err(priv, drv, priv->dev,
"Failed to unregister queue page list %d\n",
priv->qpls[i].id);
return err;
}
}
start_id = gve_rx_start_qpl_id(priv);
for (i = start_id; i < start_id + gve_num_rx_qpls(priv); i++) {
err = gve_adminq_unregister_page_list(priv, priv->qpls[i].id);
/* This failure will trigger a reset - no need to clean up */
if (err) {
netif_err(priv, drv, priv->dev,
"Failed to unregister queue page list %d\n",
priv->qpls[i].id);
return err;
}
}
return 0;
}
static int gve_create_xdp_rings(struct gve_priv *priv)
{
int err;
err = gve_adminq_create_tx_queues(priv,
gve_xdp_tx_start_queue_id(priv),
priv->num_xdp_queues);
if (err) {
netif_err(priv, drv, priv->dev, "failed to create %d XDP tx queues\n",
priv->num_xdp_queues);
/* This failure will trigger a reset - no need to clean
* up
*/
return err;
}
netif_dbg(priv, drv, priv->dev, "created %d XDP tx queues\n",
priv->num_xdp_queues);
return 0;
}
static int gve_create_rings(struct gve_priv *priv)
{
int num_tx_queues = gve_num_tx_queues(priv);
int err;
int i;
err = gve_adminq_create_tx_queues(priv, 0, num_tx_queues);
if (err) {
netif_err(priv, drv, priv->dev, "failed to create %d tx queues\n",
num_tx_queues);
/* This failure will trigger a reset - no need to clean
* up
*/
return err;
}
netif_dbg(priv, drv, priv->dev, "created %d tx queues\n",
num_tx_queues);
err = gve_adminq_create_rx_queues(priv, priv->rx_cfg.num_queues);
if (err) {
netif_err(priv, drv, priv->dev, "failed to create %d rx queues\n",
priv->rx_cfg.num_queues);
/* This failure will trigger a reset - no need to clean
* up
*/
return err;
}
netif_dbg(priv, drv, priv->dev, "created %d rx queues\n",
priv->rx_cfg.num_queues);
if (gve_is_gqi(priv)) {
/* Rx data ring has been prefilled with packet buffers at queue
* allocation time.
*
* Write the doorbell to provide descriptor slots and packet
* buffers to the NIC.
*/
for (i = 0; i < priv->rx_cfg.num_queues; i++)
gve_rx_write_doorbell(priv, &priv->rx[i]);
} else {
for (i = 0; i < priv->rx_cfg.num_queues; i++) {
/* Post buffers and ring doorbell. */
gve_rx_post_buffers_dqo(&priv->rx[i]);
}
}
return 0;
}
static void add_napi_init_xdp_sync_stats(struct gve_priv *priv,
int (*napi_poll)(struct napi_struct *napi,
int budget))
{
int start_id = gve_xdp_tx_start_queue_id(priv);
int i;
/* Add xdp tx napi & init sync stats*/
for (i = start_id; i < start_id + priv->num_xdp_queues; i++) {
int ntfy_idx = gve_tx_idx_to_ntfy(priv, i);
u64_stats_init(&priv->tx[i].statss);
priv->tx[i].ntfy_id = ntfy_idx;
gve_add_napi(priv, ntfy_idx, napi_poll);
}
}
static void add_napi_init_sync_stats(struct gve_priv *priv,
int (*napi_poll)(struct napi_struct *napi,
int budget))
{
int i;
/* Add tx napi & init sync stats*/
for (i = 0; i < gve_num_tx_queues(priv); i++) {
int ntfy_idx = gve_tx_idx_to_ntfy(priv, i);
u64_stats_init(&priv->tx[i].statss);
priv->tx[i].ntfy_id = ntfy_idx;
gve_add_napi(priv, ntfy_idx, napi_poll);
}
/* Add rx napi & init sync stats*/
for (i = 0; i < priv->rx_cfg.num_queues; i++) {
int ntfy_idx = gve_rx_idx_to_ntfy(priv, i);
u64_stats_init(&priv->rx[i].statss);
priv->rx[i].ntfy_id = ntfy_idx;
gve_add_napi(priv, ntfy_idx, napi_poll);
}
}
static void gve_tx_free_rings(struct gve_priv *priv, int start_id, int num_rings)
{
if (gve_is_gqi(priv)) {
gve_tx_free_rings_gqi(priv, start_id, num_rings);
} else {
gve_tx_free_rings_dqo(priv);
}
}
static int gve_alloc_xdp_rings(struct gve_priv *priv)
{
int start_id;
int err = 0;
if (!priv->num_xdp_queues)
return 0;
start_id = gve_xdp_tx_start_queue_id(priv);
err = gve_tx_alloc_rings(priv, start_id, priv->num_xdp_queues);
if (err)
return err;
add_napi_init_xdp_sync_stats(priv, gve_napi_poll);
return 0;
}
static int gve_alloc_rings(struct gve_priv *priv)
{
int err;
/* Setup tx rings */
priv->tx = kvcalloc(priv->tx_cfg.max_queues, sizeof(*priv->tx),
GFP_KERNEL);
if (!priv->tx)
return -ENOMEM;
if (gve_is_gqi(priv))
err = gve_tx_alloc_rings(priv, 0, gve_num_tx_queues(priv));
else
err = gve_tx_alloc_rings_dqo(priv);
if (err)
goto free_tx;
/* Setup rx rings */
priv->rx = kvcalloc(priv->rx_cfg.max_queues, sizeof(*priv->rx),
GFP_KERNEL);
if (!priv->rx) {
err = -ENOMEM;
goto free_tx_queue;
}
if (gve_is_gqi(priv))
err = gve_rx_alloc_rings(priv);
else
err = gve_rx_alloc_rings_dqo(priv);
if (err)
goto free_rx;
if (gve_is_gqi(priv))
add_napi_init_sync_stats(priv, gve_napi_poll);
else
add_napi_init_sync_stats(priv, gve_napi_poll_dqo);
return 0;
free_rx:
kvfree(priv->rx);
priv->rx = NULL;
free_tx_queue:
gve_tx_free_rings(priv, 0, gve_num_tx_queues(priv));
free_tx:
kvfree(priv->tx);
priv->tx = NULL;
return err;
}
static int gve_destroy_xdp_rings(struct gve_priv *priv)
{
int start_id;
int err;
start_id = gve_xdp_tx_start_queue_id(priv);
err = gve_adminq_destroy_tx_queues(priv,
start_id,
priv->num_xdp_queues);
if (err) {
netif_err(priv, drv, priv->dev,
"failed to destroy XDP queues\n");
/* This failure will trigger a reset - no need to clean up */
return err;
}
netif_dbg(priv, drv, priv->dev, "destroyed XDP queues\n");
return 0;
}
static int gve_destroy_rings(struct gve_priv *priv)
{
int num_tx_queues = gve_num_tx_queues(priv);
int err;
err = gve_adminq_destroy_tx_queues(priv, 0, num_tx_queues);
if (err) {
netif_err(priv, drv, priv->dev,
"failed to destroy tx queues\n");
/* This failure will trigger a reset - no need to clean up */
return err;
}
netif_dbg(priv, drv, priv->dev, "destroyed tx queues\n");
err = gve_adminq_destroy_rx_queues(priv, priv->rx_cfg.num_queues);
if (err) {
netif_err(priv, drv, priv->dev,
"failed to destroy rx queues\n");
/* This failure will trigger a reset - no need to clean up */
return err;
}
netif_dbg(priv, drv, priv->dev, "destroyed rx queues\n");
return 0;
}
static void gve_rx_free_rings(struct gve_priv *priv)
{
if (gve_is_gqi(priv))
gve_rx_free_rings_gqi(priv);
else
gve_rx_free_rings_dqo(priv);
}
static void gve_free_xdp_rings(struct gve_priv *priv)
{
int ntfy_idx, start_id;
int i;
start_id = gve_xdp_tx_start_queue_id(priv);
if (priv->tx) {
for (i = start_id; i < start_id + priv->num_xdp_queues; i++) {
ntfy_idx = gve_tx_idx_to_ntfy(priv, i);
gve_remove_napi(priv, ntfy_idx);
}
gve_tx_free_rings(priv, start_id, priv->num_xdp_queues);
}
}
static void gve_free_rings(struct gve_priv *priv)
{
int num_tx_queues = gve_num_tx_queues(priv);
int ntfy_idx;
int i;
if (priv->tx) {
for (i = 0; i < num_tx_queues; i++) {
ntfy_idx = gve_tx_idx_to_ntfy(priv, i);
gve_remove_napi(priv, ntfy_idx);
}
gve_tx_free_rings(priv, 0, num_tx_queues);
kvfree(priv->tx);
priv->tx = NULL;
}
if (priv->rx) {
for (i = 0; i < priv->rx_cfg.num_queues; i++) {
ntfy_idx = gve_rx_idx_to_ntfy(priv, i);
gve_remove_napi(priv, ntfy_idx);
}
gve_rx_free_rings(priv);
kvfree(priv->rx);
priv->rx = NULL;
}
}
int gve_alloc_page(struct gve_priv *priv, struct device *dev,
struct page **page, dma_addr_t *dma,
enum dma_data_direction dir, gfp_t gfp_flags)
{
*page = alloc_page(gfp_flags);
if (!*page) {
priv->page_alloc_fail++;
return -ENOMEM;
}
*dma = dma_map_page(dev, *page, 0, PAGE_SIZE, dir);
if (dma_mapping_error(dev, *dma)) {
priv->dma_mapping_error++;
put_page(*page);
return -ENOMEM;
}
return 0;
}
static int gve_alloc_queue_page_list(struct gve_priv *priv, u32 id,
int pages)
{
struct gve_queue_page_list *qpl = &priv->qpls[id];
int err;
int i;
if (pages + priv->num_registered_pages > priv->max_registered_pages) {
netif_err(priv, drv, priv->dev,
"Reached max number of registered pages %llu > %llu\n",
pages + priv->num_registered_pages,
priv->max_registered_pages);
return -EINVAL;
}
qpl->id = id;
qpl->num_entries = 0;
qpl->pages = kvcalloc(pages, sizeof(*qpl->pages), GFP_KERNEL);
/* caller handles clean up */
if (!qpl->pages)
return -ENOMEM;
qpl->page_buses = kvcalloc(pages, sizeof(*qpl->page_buses), GFP_KERNEL);
/* caller handles clean up */
if (!qpl->page_buses)
return -ENOMEM;
for (i = 0; i < pages; i++) {
err = gve_alloc_page(priv, &priv->pdev->dev, &qpl->pages[i],
&qpl->page_buses[i],
gve_qpl_dma_dir(priv, id), GFP_KERNEL);
/* caller handles clean up */
if (err)
return -ENOMEM;
qpl->num_entries++;
}
priv->num_registered_pages += pages;
return 0;
}
void gve_free_page(struct device *dev, struct page *page, dma_addr_t dma,
enum dma_data_direction dir)
{
if (!dma_mapping_error(dev, dma))
dma_unmap_page(dev, dma, PAGE_SIZE, dir);
if (page)
put_page(page);
}
static void gve_free_queue_page_list(struct gve_priv *priv, u32 id)
{
struct gve_queue_page_list *qpl = &priv->qpls[id];
int i;
if (!qpl->pages)
return;
if (!qpl->page_buses)
goto free_pages;
for (i = 0; i < qpl->num_entries; i++)
gve_free_page(&priv->pdev->dev, qpl->pages[i],
qpl->page_buses[i], gve_qpl_dma_dir(priv, id));
kvfree(qpl->page_buses);
qpl->page_buses = NULL;
free_pages:
kvfree(qpl->pages);
qpl->pages = NULL;
priv->num_registered_pages -= qpl->num_entries;
}
static int gve_alloc_xdp_qpls(struct gve_priv *priv)
{
int start_id;
int i, j;
int err;
start_id = gve_tx_qpl_id(priv, gve_xdp_tx_start_queue_id(priv));
for (i = start_id; i < start_id + gve_num_xdp_qpls(priv); i++) {
err = gve_alloc_queue_page_list(priv, i,
priv->tx_pages_per_qpl);
if (err)
goto free_qpls;
}
return 0;
free_qpls:
for (j = start_id; j <= i; j++)
gve_free_queue_page_list(priv, j);
return err;
}
static int gve_alloc_qpls(struct gve_priv *priv)
{
int max_queues = priv->tx_cfg.max_queues + priv->rx_cfg.max_queues;
int page_count;
int start_id;
int i, j;
int err;
if (!gve_is_qpl(priv))
return 0;
priv->qpls = kvcalloc(max_queues, sizeof(*priv->qpls), GFP_KERNEL);
if (!priv->qpls)
return -ENOMEM;
start_id = gve_tx_start_qpl_id(priv);
page_count = priv->tx_pages_per_qpl;
for (i = start_id; i < start_id + gve_num_tx_qpls(priv); i++) {
err = gve_alloc_queue_page_list(priv, i,
page_count);
if (err)
goto free_qpls;
}
start_id = gve_rx_start_qpl_id(priv);
/* For GQI_QPL number of pages allocated have 1:1 relationship with
* number of descriptors. For DQO, number of pages required are
* more than descriptors (because of out of order completions).
*/
page_count = priv->queue_format == GVE_GQI_QPL_FORMAT ?
priv->rx_data_slot_cnt : priv->rx_pages_per_qpl;
for (i = start_id; i < start_id + gve_num_rx_qpls(priv); i++) {
err = gve_alloc_queue_page_list(priv, i,
page_count);
if (err)
goto free_qpls;
}
priv->qpl_cfg.qpl_map_size = BITS_TO_LONGS(max_queues) *
sizeof(unsigned long) * BITS_PER_BYTE;
priv->qpl_cfg.qpl_id_map = kvcalloc(BITS_TO_LONGS(max_queues),
sizeof(unsigned long), GFP_KERNEL);
if (!priv->qpl_cfg.qpl_id_map) {
err = -ENOMEM;
goto free_qpls;
}
return 0;
free_qpls:
for (j = 0; j <= i; j++)
gve_free_queue_page_list(priv, j);
kvfree(priv->qpls);
priv->qpls = NULL;
return err;
}
static void gve_free_xdp_qpls(struct gve_priv *priv)
{
int start_id;
int i;
start_id = gve_tx_qpl_id(priv, gve_xdp_tx_start_queue_id(priv));
for (i = start_id; i < start_id + gve_num_xdp_qpls(priv); i++)
gve_free_queue_page_list(priv, i);
}
static void gve_free_qpls(struct gve_priv *priv)
{
int max_queues = priv->tx_cfg.max_queues + priv->rx_cfg.max_queues;
int i;
if (!priv->qpls)
return;
kvfree(priv->qpl_cfg.qpl_id_map);
priv->qpl_cfg.qpl_id_map = NULL;
for (i = 0; i < max_queues; i++)
gve_free_queue_page_list(priv, i);
kvfree(priv->qpls);
priv->qpls = NULL;
}
/* Use this to schedule a reset when the device is capable of continuing
* to handle other requests in its current state. If it is not, do a reset
* in thread instead.
*/
void gve_schedule_reset(struct gve_priv *priv)
{
gve_set_do_reset(priv);
queue_work(priv->gve_wq, &priv->service_task);
}
static void gve_reset_and_teardown(struct gve_priv *priv, bool was_up);
static int gve_reset_recovery(struct gve_priv *priv, bool was_up);
static void gve_turndown(struct gve_priv *priv);
static void gve_turnup(struct gve_priv *priv);
static int gve_reg_xdp_info(struct gve_priv *priv, struct net_device *dev)
{
struct napi_struct *napi;
struct gve_rx_ring *rx;
int err = 0;
int i, j;
u32 tx_qid;
if (!priv->num_xdp_queues)
return 0;
for (i = 0; i < priv->rx_cfg.num_queues; i++) {
rx = &priv->rx[i];
napi = &priv->ntfy_blocks[rx->ntfy_id].napi;
err = xdp_rxq_info_reg(&rx->xdp_rxq, dev, i,
napi->napi_id);
if (err)
goto err;
err = xdp_rxq_info_reg_mem_model(&rx->xdp_rxq,
MEM_TYPE_PAGE_SHARED, NULL);
if (err)
goto err;
rx->xsk_pool = xsk_get_pool_from_qid(dev, i);
if (rx->xsk_pool) {
err = xdp_rxq_info_reg(&rx->xsk_rxq, dev, i,
napi->napi_id);
if (err)
goto err;
err = xdp_rxq_info_reg_mem_model(&rx->xsk_rxq,
MEM_TYPE_XSK_BUFF_POOL, NULL);
if (err)
goto err;
xsk_pool_set_rxq_info(rx->xsk_pool,
&rx->xsk_rxq);
}
}
for (i = 0; i < priv->num_xdp_queues; i++) {
tx_qid = gve_xdp_tx_queue_id(priv, i);
priv->tx[tx_qid].xsk_pool = xsk_get_pool_from_qid(dev, i);
}
return 0;
err:
for (j = i; j >= 0; j--) {
rx = &priv->rx[j];
if (xdp_rxq_info_is_reg(&rx->xdp_rxq))
xdp_rxq_info_unreg(&rx->xdp_rxq);
if (xdp_rxq_info_is_reg(&rx->xsk_rxq))
xdp_rxq_info_unreg(&rx->xsk_rxq);
}
return err;
}
static void gve_unreg_xdp_info(struct gve_priv *priv)
{
int i, tx_qid;
if (!priv->num_xdp_queues)
return;
for (i = 0; i < priv->rx_cfg.num_queues; i++) {
struct gve_rx_ring *rx = &priv->rx[i];
xdp_rxq_info_unreg(&rx->xdp_rxq);
if (rx->xsk_pool) {
xdp_rxq_info_unreg(&rx->xsk_rxq);
rx->xsk_pool = NULL;
}
}
for (i = 0; i < priv->num_xdp_queues; i++) {
tx_qid = gve_xdp_tx_queue_id(priv, i);
priv->tx[tx_qid].xsk_pool = NULL;
}
}
static void gve_drain_page_cache(struct gve_priv *priv)
{
struct page_frag_cache *nc;
int i;
for (i = 0; i < priv->rx_cfg.num_queues; i++) {
nc = &priv->rx[i].page_cache;
if (nc->va) {
__page_frag_cache_drain(virt_to_page(nc->va),
nc->pagecnt_bias);
nc->va = NULL;
}
}
}
static int gve_open(struct net_device *dev)
{
struct gve_priv *priv = netdev_priv(dev);
int err;
if (priv->xdp_prog)
priv->num_xdp_queues = priv->rx_cfg.num_queues;
else
priv->num_xdp_queues = 0;
err = gve_alloc_qpls(priv);
if (err)
return err;
err = gve_alloc_rings(priv);
if (err)
goto free_qpls;
err = netif_set_real_num_tx_queues(dev, priv->tx_cfg.num_queues);
if (err)
goto free_rings;
err = netif_set_real_num_rx_queues(dev, priv->rx_cfg.num_queues);
if (err)
goto free_rings;
err = gve_reg_xdp_info(priv, dev);
if (err)
goto free_rings;
err = gve_register_qpls(priv);
if (err)
goto reset;
if (!gve_is_gqi(priv)) {
/* Hard code this for now. This may be tuned in the future for
* performance.
*/
priv->data_buffer_size_dqo = GVE_RX_BUFFER_SIZE_DQO;
}
err = gve_create_rings(priv);
if (err)
goto reset;
gve_set_device_rings_ok(priv);
if (gve_get_report_stats(priv))
mod_timer(&priv->stats_report_timer,
round_jiffies(jiffies +
msecs_to_jiffies(priv->stats_report_timer_period)));
gve_turnup(priv);
queue_work(priv->gve_wq, &priv->service_task);
priv->interface_up_cnt++;
return 0;
free_rings:
gve_free_rings(priv);
free_qpls:
gve_free_qpls(priv);
return err;
reset:
/* This must have been called from a reset due to the rtnl lock
* so just return at this point.
*/
if (gve_get_reset_in_progress(priv))
return err;
/* Otherwise reset before returning */
gve_reset_and_teardown(priv, true);
/* if this fails there is nothing we can do so just ignore the return */
gve_reset_recovery(priv, false);
/* return the original error */
return err;
}
static int gve_close(struct net_device *dev)
{
struct gve_priv *priv = netdev_priv(dev);
int err;
netif_carrier_off(dev);
if (gve_get_device_rings_ok(priv)) {
gve_turndown(priv);
gve_drain_page_cache(priv);
err = gve_destroy_rings(priv);
if (err)
goto err;
err = gve_unregister_qpls(priv);
if (err)
goto err;
gve_clear_device_rings_ok(priv);
}
del_timer_sync(&priv->stats_report_timer);
gve_unreg_xdp_info(priv);
gve_free_rings(priv);
gve_free_qpls(priv);
priv->interface_down_cnt++;
return 0;
err:
/* This must have been called from a reset due to the rtnl lock
* so just return at this point.
*/
if (gve_get_reset_in_progress(priv))
return err;
/* Otherwise reset before returning */
gve_reset_and_teardown(priv, true);
return gve_reset_recovery(priv, false);
}
static int gve_remove_xdp_queues(struct gve_priv *priv)
{
int err;
err = gve_destroy_xdp_rings(priv);
if (err)
return err;
err = gve_unregister_xdp_qpls(priv);
if (err)
return err;
gve_unreg_xdp_info(priv);
gve_free_xdp_rings(priv);
gve_free_xdp_qpls(priv);
priv->num_xdp_queues = 0;
return 0;
}
static int gve_add_xdp_queues(struct gve_priv *priv)
{
int err;
priv->num_xdp_queues = priv->tx_cfg.num_queues;
err = gve_alloc_xdp_qpls(priv);
if (err)
goto err;
err = gve_alloc_xdp_rings(priv);
if (err)
goto free_xdp_qpls;
err = gve_reg_xdp_info(priv, priv->dev);
if (err)
goto free_xdp_rings;
err = gve_register_xdp_qpls(priv);
if (err)
goto free_xdp_rings;
err = gve_create_xdp_rings(priv);
if (err)
goto free_xdp_rings;
return 0;
free_xdp_rings:
gve_free_xdp_rings(priv);
free_xdp_qpls:
gve_free_xdp_qpls(priv);
err:
priv->num_xdp_queues = 0;
return err;
}
static void gve_handle_link_status(struct gve_priv *priv, bool link_status)
{
if (!gve_get_napi_enabled(priv))
return;
if (link_status == netif_carrier_ok(priv->dev))
return;
if (link_status) {
netdev_info(priv->dev, "Device link is up.\n");
netif_carrier_on(priv->dev);
} else {
netdev_info(priv->dev, "Device link is down.\n");
netif_carrier_off(priv->dev);
}
}
static int gve_set_xdp(struct gve_priv *priv, struct bpf_prog *prog,
struct netlink_ext_ack *extack)
{
struct bpf_prog *old_prog;
int err = 0;
u32 status;
old_prog = READ_ONCE(priv->xdp_prog);
if (!netif_carrier_ok(priv->dev)) {
WRITE_ONCE(priv->xdp_prog, prog);
if (old_prog)
bpf_prog_put(old_prog);
return 0;
}
gve_turndown(priv);
if (!old_prog && prog) {
// Allocate XDP TX queues if an XDP program is
// being installed
err = gve_add_xdp_queues(priv);
if (err)
goto out;
} else if (old_prog && !prog) {
// Remove XDP TX queues if an XDP program is
// being uninstalled
err = gve_remove_xdp_queues(priv);
if (err)
goto out;
}
WRITE_ONCE(priv->xdp_prog, prog);
if (old_prog)
bpf_prog_put(old_prog);
out:
gve_turnup(priv);
status = ioread32be(&priv->reg_bar0->device_status);
gve_handle_link_status(priv, GVE_DEVICE_STATUS_LINK_STATUS_MASK & status);
return err;
}
static int gve_xsk_pool_enable(struct net_device *dev,
struct xsk_buff_pool *pool,
u16 qid)
{
struct gve_priv *priv = netdev_priv(dev);
struct napi_struct *napi;
struct gve_rx_ring *rx;
int tx_qid;
int err;
if (qid >= priv->rx_cfg.num_queues) {
dev_err(&priv->pdev->dev, "xsk pool invalid qid %d", qid);
return -EINVAL;
}
if (xsk_pool_get_rx_frame_size(pool) <
priv->dev->max_mtu + sizeof(struct ethhdr)) {
dev_err(&priv->pdev->dev, "xsk pool frame_len too small");
return -EINVAL;
}
err = xsk_pool_dma_map(pool, &priv->pdev->dev,
DMA_ATTR_SKIP_CPU_SYNC | DMA_ATTR_WEAK_ORDERING);
if (err)
return err;
/* If XDP prog is not installed, return */
if (!priv->xdp_prog)
return 0;
rx = &priv->rx[qid];
napi = &priv->ntfy_blocks[rx->ntfy_id].napi;
err = xdp_rxq_info_reg(&rx->xsk_rxq, dev, qid, napi->napi_id);
if (err)
goto err;
err = xdp_rxq_info_reg_mem_model(&rx->xsk_rxq,
MEM_TYPE_XSK_BUFF_POOL, NULL);
if (err)
goto err;
xsk_pool_set_rxq_info(pool, &rx->xsk_rxq);
rx->xsk_pool = pool;
tx_qid = gve_xdp_tx_queue_id(priv, qid);
priv->tx[tx_qid].xsk_pool = pool;
return 0;
err:
if (xdp_rxq_info_is_reg(&rx->xsk_rxq))
xdp_rxq_info_unreg(&rx->xsk_rxq);
xsk_pool_dma_unmap(pool,
DMA_ATTR_SKIP_CPU_SYNC | DMA_ATTR_WEAK_ORDERING);
return err;
}
static int gve_xsk_pool_disable(struct net_device *dev,
u16 qid)
{
struct gve_priv *priv = netdev_priv(dev);
struct napi_struct *napi_rx;
struct napi_struct *napi_tx;
struct xsk_buff_pool *pool;
int tx_qid;
pool = xsk_get_pool_from_qid(dev, qid);
if (!pool)
return -EINVAL;
if (qid >= priv->rx_cfg.num_queues)
return -EINVAL;
/* If XDP prog is not installed, unmap DMA and return */
if (!priv->xdp_prog)
goto done;
tx_qid = gve_xdp_tx_queue_id(priv, qid);
if (!netif_running(dev)) {
priv->rx[qid].xsk_pool = NULL;
xdp_rxq_info_unreg(&priv->rx[qid].xsk_rxq);
priv->tx[tx_qid].xsk_pool = NULL;
goto done;
}
napi_rx = &priv->ntfy_blocks[priv->rx[qid].ntfy_id].napi;
napi_disable(napi_rx); /* make sure current rx poll is done */
napi_tx = &priv->ntfy_blocks[priv->tx[tx_qid].ntfy_id].napi;
napi_disable(napi_tx); /* make sure current tx poll is done */
priv->rx[qid].xsk_pool = NULL;
xdp_rxq_info_unreg(&priv->rx[qid].xsk_rxq);
priv->tx[tx_qid].xsk_pool = NULL;
smp_mb(); /* Make sure it is visible to the workers on datapath */
napi_enable(napi_rx);
if (gve_rx_work_pending(&priv->rx[qid]))
napi_schedule(napi_rx);
napi_enable(napi_tx);
if (gve_tx_clean_pending(priv, &priv->tx[tx_qid]))
napi_schedule(napi_tx);
done:
xsk_pool_dma_unmap(pool,
DMA_ATTR_SKIP_CPU_SYNC | DMA_ATTR_WEAK_ORDERING);
return 0;
}
static int gve_xsk_wakeup(struct net_device *dev, u32 queue_id, u32 flags)
{
struct gve_priv *priv = netdev_priv(dev);
int tx_queue_id = gve_xdp_tx_queue_id(priv, queue_id);
if (queue_id >= priv->rx_cfg.num_queues || !priv->xdp_prog)
return -EINVAL;
if (flags & XDP_WAKEUP_TX) {
struct gve_tx_ring *tx = &priv->tx[tx_queue_id];
struct napi_struct *napi =
&priv->ntfy_blocks[tx->ntfy_id].napi;
if (!napi_if_scheduled_mark_missed(napi)) {
/* Call local_bh_enable to trigger SoftIRQ processing */
local_bh_disable();
napi_schedule(napi);
local_bh_enable();
}
tx->xdp_xsk_wakeup++;
}
return 0;
}
static int verify_xdp_configuration(struct net_device *dev)
{
struct gve_priv *priv = netdev_priv(dev);
if (dev->features & NETIF_F_LRO) {
netdev_warn(dev, "XDP is not supported when LRO is on.\n");
return -EOPNOTSUPP;
}
if (priv->queue_format != GVE_GQI_QPL_FORMAT) {
netdev_warn(dev, "XDP is not supported in mode %d.\n",
priv->queue_format);
return -EOPNOTSUPP;
}
if (dev->mtu > (PAGE_SIZE / 2) - sizeof(struct ethhdr) - GVE_RX_PAD) {
netdev_warn(dev, "XDP is not supported for mtu %d.\n",
dev->mtu);
return -EOPNOTSUPP;
}
if (priv->rx_cfg.num_queues != priv->tx_cfg.num_queues ||
(2 * priv->tx_cfg.num_queues > priv->tx_cfg.max_queues)) {
netdev_warn(dev, "XDP load failed: The number of configured RX queues %d should be equal to the number of configured TX queues %d and the number of configured RX/TX queues should be less than or equal to half the maximum number of RX/TX queues %d",
priv->rx_cfg.num_queues,
priv->tx_cfg.num_queues,
priv->tx_cfg.max_queues);
return -EINVAL;
}
return 0;
}
static int gve_xdp(struct net_device *dev, struct netdev_bpf *xdp)
{
struct gve_priv *priv = netdev_priv(dev);
int err;
err = verify_xdp_configuration(dev);
if (err)
return err;
switch (xdp->command) {
case XDP_SETUP_PROG:
return gve_set_xdp(priv, xdp->prog, xdp->extack);
case XDP_SETUP_XSK_POOL:
if (xdp->xsk.pool)
return gve_xsk_pool_enable(dev, xdp->xsk.pool, xdp->xsk.queue_id);
else
return gve_xsk_pool_disable(dev, xdp->xsk.queue_id);
default:
return -EINVAL;
}
}
int gve_adjust_queues(struct gve_priv *priv,
struct gve_queue_config new_rx_config,
struct gve_queue_config new_tx_config)
{
int err;
if (netif_carrier_ok(priv->dev)) {
/* To make this process as simple as possible we teardown the
* device, set the new configuration, and then bring the device
* up again.
*/
err = gve_close(priv->dev);
/* we have already tried to reset in close,
* just fail at this point
*/
if (err)
return err;
priv->tx_cfg = new_tx_config;
priv->rx_cfg = new_rx_config;
err = gve_open(priv->dev);
if (err)
goto err;
return 0;
}
/* Set the config for the next up. */
priv->tx_cfg = new_tx_config;
priv->rx_cfg = new_rx_config;
return 0;
err:
netif_err(priv, drv, priv->dev,
"Adjust queues failed! !!! DISABLING ALL QUEUES !!!\n");
gve_turndown(priv);
return err;
}
static void gve_turndown(struct gve_priv *priv)
{
int idx;
if (netif_carrier_ok(priv->dev))
netif_carrier_off(priv->dev);
if (!gve_get_napi_enabled(priv))
return;
/* Disable napi to prevent more work from coming in */
for (idx = 0; idx < gve_num_tx_queues(priv); idx++) {
int ntfy_idx = gve_tx_idx_to_ntfy(priv, idx);
struct gve_notify_block *block = &priv->ntfy_blocks[ntfy_idx];
napi_disable(&block->napi);
}
for (idx = 0; idx < priv->rx_cfg.num_queues; idx++) {
int ntfy_idx = gve_rx_idx_to_ntfy(priv, idx);
struct gve_notify_block *block = &priv->ntfy_blocks[ntfy_idx];
napi_disable(&block->napi);
}
/* Stop tx queues */
netif_tx_disable(priv->dev);
gve_clear_napi_enabled(priv);
gve_clear_report_stats(priv);
}
static void gve_turnup(struct gve_priv *priv)
{
int idx;
/* Start the tx queues */
netif_tx_start_all_queues(priv->dev);
/* Enable napi and unmask interrupts for all queues */
for (idx = 0; idx < gve_num_tx_queues(priv); idx++) {
int ntfy_idx = gve_tx_idx_to_ntfy(priv, idx);
struct gve_notify_block *block = &priv->ntfy_blocks[ntfy_idx];
napi_enable(&block->napi);
if (gve_is_gqi(priv)) {
iowrite32be(0, gve_irq_doorbell(priv, block));
} else {
gve_set_itr_coalesce_usecs_dqo(priv, block,
priv->tx_coalesce_usecs);
}
}
for (idx = 0; idx < priv->rx_cfg.num_queues; idx++) {
int ntfy_idx = gve_rx_idx_to_ntfy(priv, idx);
struct gve_notify_block *block = &priv->ntfy_blocks[ntfy_idx];
napi_enable(&block->napi);
if (gve_is_gqi(priv)) {
iowrite32be(0, gve_irq_doorbell(priv, block));
} else {
gve_set_itr_coalesce_usecs_dqo(priv, block,
priv->rx_coalesce_usecs);
}
}
gve_set_napi_enabled(priv);
}
static void gve_tx_timeout(struct net_device *dev, unsigned int txqueue)
{
struct gve_notify_block *block;
struct gve_tx_ring *tx = NULL;
struct gve_priv *priv;
u32 last_nic_done;
u32 current_time;
u32 ntfy_idx;
netdev_info(dev, "Timeout on tx queue, %d", txqueue);
priv = netdev_priv(dev);
if (txqueue > priv->tx_cfg.num_queues)
goto reset;
ntfy_idx = gve_tx_idx_to_ntfy(priv, txqueue);
if (ntfy_idx >= priv->num_ntfy_blks)
goto reset;
block = &priv->ntfy_blocks[ntfy_idx];
tx = block->tx;
current_time = jiffies_to_msecs(jiffies);
if (tx->last_kick_msec + MIN_TX_TIMEOUT_GAP > current_time)
goto reset;
/* Check to see if there are missed completions, which will allow us to
* kick the queue.
*/
last_nic_done = gve_tx_load_event_counter(priv, tx);
if (last_nic_done - tx->done) {
netdev_info(dev, "Kicking queue %d", txqueue);
iowrite32be(GVE_IRQ_MASK, gve_irq_doorbell(priv, block));
napi_schedule(&block->napi);
tx->last_kick_msec = current_time;
goto out;
} // Else reset.
reset:
gve_schedule_reset(priv);
out:
if (tx)
tx->queue_timeout++;
priv->tx_timeo_cnt++;
}
static int gve_set_features(struct net_device *netdev,
netdev_features_t features)
{
const netdev_features_t orig_features = netdev->features;
struct gve_priv *priv = netdev_priv(netdev);
int err;
if ((netdev->features & NETIF_F_LRO) != (features & NETIF_F_LRO)) {
netdev->features ^= NETIF_F_LRO;
if (netif_carrier_ok(netdev)) {
/* To make this process as simple as possible we
* teardown the device, set the new configuration,
* and then bring the device up again.
*/
err = gve_close(netdev);
/* We have already tried to reset in close, just fail
* at this point.
*/
if (err)
goto err;
err = gve_open(netdev);
if (err)
goto err;
}
}
return 0;
err:
/* Reverts the change on error. */
netdev->features = orig_features;
netif_err(priv, drv, netdev,
"Set features failed! !!! DISABLING ALL QUEUES !!!\n");
return err;
}
static const struct net_device_ops gve_netdev_ops = {
.ndo_start_xmit = gve_start_xmit,
.ndo_open = gve_open,
.ndo_stop = gve_close,
.ndo_get_stats64 = gve_get_stats,
.ndo_tx_timeout = gve_tx_timeout,
.ndo_set_features = gve_set_features,
.ndo_bpf = gve_xdp,
.ndo_xdp_xmit = gve_xdp_xmit,
.ndo_xsk_wakeup = gve_xsk_wakeup,
};
static void gve_handle_status(struct gve_priv *priv, u32 status)
{
if (GVE_DEVICE_STATUS_RESET_MASK & status) {
dev_info(&priv->pdev->dev, "Device requested reset.\n");
gve_set_do_reset(priv);
}
if (GVE_DEVICE_STATUS_REPORT_STATS_MASK & status) {
priv->stats_report_trigger_cnt++;
gve_set_do_report_stats(priv);
}
}
static void gve_handle_reset(struct gve_priv *priv)
{
/* A service task will be scheduled at the end of probe to catch any
* resets that need to happen, and we don't want to reset until
* probe is done.
*/
if (gve_get_probe_in_progress(priv))
return;
if (gve_get_do_reset(priv)) {
rtnl_lock();
gve_reset(priv, false);
rtnl_unlock();
}
}
void gve_handle_report_stats(struct gve_priv *priv)
{
struct stats *stats = priv->stats_report->stats;
int idx, stats_idx = 0;
unsigned int start = 0;
u64 tx_bytes;
if (!gve_get_report_stats(priv))
return;
be64_add_cpu(&priv->stats_report->written_count, 1);
/* tx stats */
if (priv->tx) {
for (idx = 0; idx < gve_num_tx_queues(priv); idx++) {
u32 last_completion = 0;
u32 tx_frames = 0;
/* DQO doesn't currently support these metrics. */
if (gve_is_gqi(priv)) {
last_completion = priv->tx[idx].done;
tx_frames = priv->tx[idx].req;
}
do {
start = u64_stats_fetch_begin(&priv->tx[idx].statss);
tx_bytes = priv->tx[idx].bytes_done;
} while (u64_stats_fetch_retry(&priv->tx[idx].statss, start));
stats[stats_idx++] = (struct stats) {
.stat_name = cpu_to_be32(TX_WAKE_CNT),
.value = cpu_to_be64(priv->tx[idx].wake_queue),
.queue_id = cpu_to_be32(idx),
};
stats[stats_idx++] = (struct stats) {
.stat_name = cpu_to_be32(TX_STOP_CNT),
.value = cpu_to_be64(priv->tx[idx].stop_queue),
.queue_id = cpu_to_be32(idx),
};
stats[stats_idx++] = (struct stats) {
.stat_name = cpu_to_be32(TX_FRAMES_SENT),
.value = cpu_to_be64(tx_frames),
.queue_id = cpu_to_be32(idx),
};
stats[stats_idx++] = (struct stats) {
.stat_name = cpu_to_be32(TX_BYTES_SENT),
.value = cpu_to_be64(tx_bytes),
.queue_id = cpu_to_be32(idx),
};
stats[stats_idx++] = (struct stats) {
.stat_name = cpu_to_be32(TX_LAST_COMPLETION_PROCESSED),
.value = cpu_to_be64(last_completion),
.queue_id = cpu_to_be32(idx),
};
stats[stats_idx++] = (struct stats) {
.stat_name = cpu_to_be32(TX_TIMEOUT_CNT),
.value = cpu_to_be64(priv->tx[idx].queue_timeout),
.queue_id = cpu_to_be32(idx),
};
}
}
/* rx stats */
if (priv->rx) {
for (idx = 0; idx < priv->rx_cfg.num_queues; idx++) {
stats[stats_idx++] = (struct stats) {
.stat_name = cpu_to_be32(RX_NEXT_EXPECTED_SEQUENCE),
.value = cpu_to_be64(priv->rx[idx].desc.seqno),
.queue_id = cpu_to_be32(idx),
};
stats[stats_idx++] = (struct stats) {
.stat_name = cpu_to_be32(RX_BUFFERS_POSTED),
.value = cpu_to_be64(priv->rx[0].fill_cnt),
.queue_id = cpu_to_be32(idx),
};
}
}
}
/* Handle NIC status register changes, reset requests and report stats */
static void gve_service_task(struct work_struct *work)
{
struct gve_priv *priv = container_of(work, struct gve_priv,
service_task);
u32 status = ioread32be(&priv->reg_bar0->device_status);
gve_handle_status(priv, status);
gve_handle_reset(priv);
gve_handle_link_status(priv, GVE_DEVICE_STATUS_LINK_STATUS_MASK & status);
}
static void gve_set_netdev_xdp_features(struct gve_priv *priv)
{
if (priv->queue_format == GVE_GQI_QPL_FORMAT) {
priv->dev->xdp_features = NETDEV_XDP_ACT_BASIC;
priv->dev->xdp_features |= NETDEV_XDP_ACT_REDIRECT;
priv->dev->xdp_features |= NETDEV_XDP_ACT_NDO_XMIT;
priv->dev->xdp_features |= NETDEV_XDP_ACT_XSK_ZEROCOPY;
} else {
priv->dev->xdp_features = 0;
}
}
static int gve_init_priv(struct gve_priv *priv, bool skip_describe_device)
{
int num_ntfy;
int err;
/* Set up the adminq */
err = gve_adminq_alloc(&priv->pdev->dev, priv);
if (err) {
dev_err(&priv->pdev->dev,
"Failed to alloc admin queue: err=%d\n", err);
return err;
}
err = gve_verify_driver_compatibility(priv);
if (err) {
dev_err(&priv->pdev->dev,
"Could not verify driver compatibility: err=%d\n", err);
goto err;
}
if (skip_describe_device)
goto setup_device;
priv->queue_format = GVE_QUEUE_FORMAT_UNSPECIFIED;
/* Get the initial information we need from the device */
err = gve_adminq_describe_device(priv);
if (err) {
dev_err(&priv->pdev->dev,
"Could not get device information: err=%d\n", err);
goto err;
}
priv->dev->mtu = priv->dev->max_mtu;
num_ntfy = pci_msix_vec_count(priv->pdev);
if (num_ntfy <= 0) {
dev_err(&priv->pdev->dev,
"could not count MSI-x vectors: err=%d\n", num_ntfy);
err = num_ntfy;
goto err;
} else if (num_ntfy < GVE_MIN_MSIX) {
dev_err(&priv->pdev->dev, "gve needs at least %d MSI-x vectors, but only has %d\n",
GVE_MIN_MSIX, num_ntfy);
err = -EINVAL;
goto err;
}
/* Big TCP is only supported on DQ*/
if (!gve_is_gqi(priv))
netif_set_tso_max_size(priv->dev, GVE_DQO_TX_MAX);
priv->num_registered_pages = 0;
priv->rx_copybreak = GVE_DEFAULT_RX_COPYBREAK;
/* gvnic has one Notification Block per MSI-x vector, except for the
* management vector
*/
priv->num_ntfy_blks = (num_ntfy - 1) & ~0x1;
priv->mgmt_msix_idx = priv->num_ntfy_blks;
priv->tx_cfg.max_queues =
min_t(int, priv->tx_cfg.max_queues, priv->num_ntfy_blks / 2);
priv->rx_cfg.max_queues =
min_t(int, priv->rx_cfg.max_queues, priv->num_ntfy_blks / 2);
priv->tx_cfg.num_queues = priv->tx_cfg.max_queues;
priv->rx_cfg.num_queues = priv->rx_cfg.max_queues;
if (priv->default_num_queues > 0) {
priv->tx_cfg.num_queues = min_t(int, priv->default_num_queues,
priv->tx_cfg.num_queues);
priv->rx_cfg.num_queues = min_t(int, priv->default_num_queues,
priv->rx_cfg.num_queues);
}
dev_info(&priv->pdev->dev, "TX queues %d, RX queues %d\n",
priv->tx_cfg.num_queues, priv->rx_cfg.num_queues);
dev_info(&priv->pdev->dev, "Max TX queues %d, Max RX queues %d\n",
priv->tx_cfg.max_queues, priv->rx_cfg.max_queues);
if (!gve_is_gqi(priv)) {
priv->tx_coalesce_usecs = GVE_TX_IRQ_RATELIMIT_US_DQO;
priv->rx_coalesce_usecs = GVE_RX_IRQ_RATELIMIT_US_DQO;
}
setup_device:
gve_set_netdev_xdp_features(priv);
err = gve_setup_device_resources(priv);
if (!err)
return 0;
err:
gve_adminq_free(&priv->pdev->dev, priv);
return err;
}
static void gve_teardown_priv_resources(struct gve_priv *priv)
{
gve_teardown_device_resources(priv);
gve_adminq_free(&priv->pdev->dev, priv);
}
static void gve_trigger_reset(struct gve_priv *priv)
{
/* Reset the device by releasing the AQ */
gve_adminq_release(priv);
}
static void gve_reset_and_teardown(struct gve_priv *priv, bool was_up)
{
gve_trigger_reset(priv);
/* With the reset having already happened, close cannot fail */
if (was_up)
gve_close(priv->dev);
gve_teardown_priv_resources(priv);
}
static int gve_reset_recovery(struct gve_priv *priv, bool was_up)
{
int err;
err = gve_init_priv(priv, true);
if (err)
goto err;
if (was_up) {
err = gve_open(priv->dev);
if (err)
goto err;
}
return 0;
err:
dev_err(&priv->pdev->dev, "Reset failed! !!! DISABLING ALL QUEUES !!!\n");
gve_turndown(priv);
return err;
}
int gve_reset(struct gve_priv *priv, bool attempt_teardown)
{
bool was_up = netif_carrier_ok(priv->dev);
int err;
dev_info(&priv->pdev->dev, "Performing reset\n");
gve_clear_do_reset(priv);
gve_set_reset_in_progress(priv);
/* If we aren't attempting to teardown normally, just go turndown and
* reset right away.
*/
if (!attempt_teardown) {
gve_turndown(priv);
gve_reset_and_teardown(priv, was_up);
} else {
/* Otherwise attempt to close normally */
if (was_up) {
err = gve_close(priv->dev);
/* If that fails reset as we did above */
if (err)
gve_reset_and_teardown(priv, was_up);
}
/* Clean up any remaining resources */
gve_teardown_priv_resources(priv);
}
/* Set it all back up */
err = gve_reset_recovery(priv, was_up);
gve_clear_reset_in_progress(priv);
priv->reset_cnt++;
priv->interface_up_cnt = 0;
priv->interface_down_cnt = 0;
priv->stats_report_trigger_cnt = 0;
return err;
}
static void gve_write_version(u8 __iomem *driver_version_register)
{
const char *c = gve_version_prefix;
while (*c) {
writeb(*c, driver_version_register);
c++;
}
c = gve_version_str;
while (*c) {
writeb(*c, driver_version_register);
c++;
}
writeb('\n', driver_version_register);
}
static int gve_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
int max_tx_queues, max_rx_queues;
struct net_device *dev;
__be32 __iomem *db_bar;
struct gve_registers __iomem *reg_bar;
struct gve_priv *priv;
int err;
err = pci_enable_device(pdev);
if (err)
return err;
err = pci_request_regions(pdev, gve_driver_name);
if (err)
goto abort_with_enabled;
pci_set_master(pdev);
err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
if (err) {
dev_err(&pdev->dev, "Failed to set dma mask: err=%d\n", err);
goto abort_with_pci_region;
}
reg_bar = pci_iomap(pdev, GVE_REGISTER_BAR, 0);
if (!reg_bar) {
dev_err(&pdev->dev, "Failed to map pci bar!\n");
err = -ENOMEM;
goto abort_with_pci_region;
}
db_bar = pci_iomap(pdev, GVE_DOORBELL_BAR, 0);
if (!db_bar) {
dev_err(&pdev->dev, "Failed to map doorbell bar!\n");
err = -ENOMEM;
goto abort_with_reg_bar;
}
gve_write_version(®_bar->driver_version);
/* Get max queues to alloc etherdev */
max_tx_queues = ioread32be(®_bar->max_tx_queues);
max_rx_queues = ioread32be(®_bar->max_rx_queues);
/* Alloc and setup the netdev and priv */
dev = alloc_etherdev_mqs(sizeof(*priv), max_tx_queues, max_rx_queues);
if (!dev) {
dev_err(&pdev->dev, "could not allocate netdev\n");
err = -ENOMEM;
goto abort_with_db_bar;
}
SET_NETDEV_DEV(dev, &pdev->dev);
pci_set_drvdata(pdev, dev);
dev->ethtool_ops = &gve_ethtool_ops;
dev->netdev_ops = &gve_netdev_ops;
/* Set default and supported features.
*
* Features might be set in other locations as well (such as
* `gve_adminq_describe_device`).
*/
dev->hw_features = NETIF_F_HIGHDMA;
dev->hw_features |= NETIF_F_SG;
dev->hw_features |= NETIF_F_HW_CSUM;
dev->hw_features |= NETIF_F_TSO;
dev->hw_features |= NETIF_F_TSO6;
dev->hw_features |= NETIF_F_TSO_ECN;
dev->hw_features |= NETIF_F_RXCSUM;
dev->hw_features |= NETIF_F_RXHASH;
dev->features = dev->hw_features;
dev->watchdog_timeo = 5 * HZ;
dev->min_mtu = ETH_MIN_MTU;
netif_carrier_off(dev);
priv = netdev_priv(dev);
priv->dev = dev;
priv->pdev = pdev;
priv->msg_enable = DEFAULT_MSG_LEVEL;
priv->reg_bar0 = reg_bar;
priv->db_bar2 = db_bar;
priv->service_task_flags = 0x0;
priv->state_flags = 0x0;
priv->ethtool_flags = 0x0;
gve_set_probe_in_progress(priv);
priv->gve_wq = alloc_ordered_workqueue("gve", 0);
if (!priv->gve_wq) {
dev_err(&pdev->dev, "Could not allocate workqueue");
err = -ENOMEM;
goto abort_with_netdev;
}
INIT_WORK(&priv->service_task, gve_service_task);
INIT_WORK(&priv->stats_report_task, gve_stats_report_task);
priv->tx_cfg.max_queues = max_tx_queues;
priv->rx_cfg.max_queues = max_rx_queues;
err = gve_init_priv(priv, false);
if (err)
goto abort_with_wq;
err = register_netdev(dev);
if (err)
goto abort_with_gve_init;
dev_info(&pdev->dev, "GVE version %s\n", gve_version_str);
dev_info(&pdev->dev, "GVE queue format %d\n", (int)priv->queue_format);
gve_clear_probe_in_progress(priv);
queue_work(priv->gve_wq, &priv->service_task);
return 0;
abort_with_gve_init:
gve_teardown_priv_resources(priv);
abort_with_wq:
destroy_workqueue(priv->gve_wq);
abort_with_netdev:
free_netdev(dev);
abort_with_db_bar:
pci_iounmap(pdev, db_bar);
abort_with_reg_bar:
pci_iounmap(pdev, reg_bar);
abort_with_pci_region:
pci_release_regions(pdev);
abort_with_enabled:
pci_disable_device(pdev);
return err;
}
static void gve_remove(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct gve_priv *priv = netdev_priv(netdev);
__be32 __iomem *db_bar = priv->db_bar2;
void __iomem *reg_bar = priv->reg_bar0;
unregister_netdev(netdev);
gve_teardown_priv_resources(priv);
destroy_workqueue(priv->gve_wq);
free_netdev(netdev);
pci_iounmap(pdev, db_bar);
pci_iounmap(pdev, reg_bar);
pci_release_regions(pdev);
pci_disable_device(pdev);
}
static void gve_shutdown(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct gve_priv *priv = netdev_priv(netdev);
bool was_up = netif_carrier_ok(priv->dev);
rtnl_lock();
if (was_up && gve_close(priv->dev)) {
/* If the dev was up, attempt to close, if close fails, reset */
gve_reset_and_teardown(priv, was_up);
} else {
/* If the dev wasn't up or close worked, finish tearing down */
gve_teardown_priv_resources(priv);
}
rtnl_unlock();
}
#ifdef CONFIG_PM
static int gve_suspend(struct pci_dev *pdev, pm_message_t state)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct gve_priv *priv = netdev_priv(netdev);
bool was_up = netif_carrier_ok(priv->dev);
priv->suspend_cnt++;
rtnl_lock();
if (was_up && gve_close(priv->dev)) {
/* If the dev was up, attempt to close, if close fails, reset */
gve_reset_and_teardown(priv, was_up);
} else {
/* If the dev wasn't up or close worked, finish tearing down */
gve_teardown_priv_resources(priv);
}
priv->up_before_suspend = was_up;
rtnl_unlock();
return 0;
}
static int gve_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct gve_priv *priv = netdev_priv(netdev);
int err;
priv->resume_cnt++;
rtnl_lock();
err = gve_reset_recovery(priv, priv->up_before_suspend);
rtnl_unlock();
return err;
}
#endif /* CONFIG_PM */
static const struct pci_device_id gve_id_table[] = {
{ PCI_DEVICE(PCI_VENDOR_ID_GOOGLE, PCI_DEV_ID_GVNIC) },
{ }
};
static struct pci_driver gve_driver = {
.name = gve_driver_name,
.id_table = gve_id_table,
.probe = gve_probe,
.remove = gve_remove,
.shutdown = gve_shutdown,
#ifdef CONFIG_PM
.suspend = gve_suspend,
.resume = gve_resume,
#endif
};
module_pci_driver(gve_driver);
MODULE_DEVICE_TABLE(pci, gve_id_table);
MODULE_AUTHOR("Google, Inc.");
MODULE_DESCRIPTION("Google Virtual NIC Driver");
MODULE_LICENSE("Dual MIT/GPL");
MODULE_VERSION(GVE_VERSION);
|
linux-master
|
drivers/net/ethernet/google/gve/gve_main.c
|
// SPDX-License-Identifier: (GPL-2.0 OR MIT)
/* Google virtual Ethernet (gve) driver
*
* Copyright (C) 2015-2021 Google, Inc.
*/
#include "gve.h"
#include "gve_adminq.h"
#include "gve_utils.h"
void gve_tx_remove_from_block(struct gve_priv *priv, int queue_idx)
{
struct gve_notify_block *block =
&priv->ntfy_blocks[gve_tx_idx_to_ntfy(priv, queue_idx)];
block->tx = NULL;
}
void gve_tx_add_to_block(struct gve_priv *priv, int queue_idx)
{
unsigned int active_cpus = min_t(int, priv->num_ntfy_blks / 2,
num_online_cpus());
int ntfy_idx = gve_tx_idx_to_ntfy(priv, queue_idx);
struct gve_notify_block *block = &priv->ntfy_blocks[ntfy_idx];
struct gve_tx_ring *tx = &priv->tx[queue_idx];
block->tx = tx;
tx->ntfy_id = ntfy_idx;
netif_set_xps_queue(priv->dev, get_cpu_mask(ntfy_idx % active_cpus),
queue_idx);
}
void gve_rx_remove_from_block(struct gve_priv *priv, int queue_idx)
{
struct gve_notify_block *block =
&priv->ntfy_blocks[gve_rx_idx_to_ntfy(priv, queue_idx)];
block->rx = NULL;
}
void gve_rx_add_to_block(struct gve_priv *priv, int queue_idx)
{
u32 ntfy_idx = gve_rx_idx_to_ntfy(priv, queue_idx);
struct gve_notify_block *block = &priv->ntfy_blocks[ntfy_idx];
struct gve_rx_ring *rx = &priv->rx[queue_idx];
block->rx = rx;
rx->ntfy_id = ntfy_idx;
}
struct sk_buff *gve_rx_copy(struct net_device *dev, struct napi_struct *napi,
struct gve_rx_slot_page_info *page_info, u16 len)
{
void *va = page_info->page_address + page_info->page_offset +
page_info->pad;
struct sk_buff *skb;
skb = napi_alloc_skb(napi, len);
if (unlikely(!skb))
return NULL;
__skb_put(skb, len);
skb_copy_to_linear_data_offset(skb, 0, va, len);
skb->protocol = eth_type_trans(skb, dev);
return skb;
}
void gve_dec_pagecnt_bias(struct gve_rx_slot_page_info *page_info)
{
page_info->pagecnt_bias--;
if (page_info->pagecnt_bias == 0) {
int pagecount = page_count(page_info->page);
/* If we have run out of bias - set it back up to INT_MAX
* minus the existing refs.
*/
page_info->pagecnt_bias = INT_MAX - pagecount;
/* Set pagecount back up to max. */
page_ref_add(page_info->page, INT_MAX - pagecount);
}
}
|
linux-master
|
drivers/net/ethernet/google/gve/gve_utils.c
|
// SPDX-License-Identifier: (GPL-2.0 OR MIT)
/* Google virtual Ethernet (gve) driver
*
* Copyright (C) 2015-2021 Google, Inc.
*/
#include "gve.h"
#include "gve_dqo.h"
#include "gve_adminq.h"
#include "gve_utils.h"
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <net/ip6_checksum.h>
#include <net/ipv6.h>
#include <net/tcp.h>
static int gve_buf_ref_cnt(struct gve_rx_buf_state_dqo *bs)
{
return page_count(bs->page_info.page) - bs->page_info.pagecnt_bias;
}
static void gve_free_page_dqo(struct gve_priv *priv,
struct gve_rx_buf_state_dqo *bs,
bool free_page)
{
page_ref_sub(bs->page_info.page, bs->page_info.pagecnt_bias - 1);
if (free_page)
gve_free_page(&priv->pdev->dev, bs->page_info.page, bs->addr,
DMA_FROM_DEVICE);
bs->page_info.page = NULL;
}
static struct gve_rx_buf_state_dqo *gve_alloc_buf_state(struct gve_rx_ring *rx)
{
struct gve_rx_buf_state_dqo *buf_state;
s16 buffer_id;
buffer_id = rx->dqo.free_buf_states;
if (unlikely(buffer_id == -1))
return NULL;
buf_state = &rx->dqo.buf_states[buffer_id];
/* Remove buf_state from free list */
rx->dqo.free_buf_states = buf_state->next;
/* Point buf_state to itself to mark it as allocated */
buf_state->next = buffer_id;
return buf_state;
}
static bool gve_buf_state_is_allocated(struct gve_rx_ring *rx,
struct gve_rx_buf_state_dqo *buf_state)
{
s16 buffer_id = buf_state - rx->dqo.buf_states;
return buf_state->next == buffer_id;
}
static void gve_free_buf_state(struct gve_rx_ring *rx,
struct gve_rx_buf_state_dqo *buf_state)
{
s16 buffer_id = buf_state - rx->dqo.buf_states;
buf_state->next = rx->dqo.free_buf_states;
rx->dqo.free_buf_states = buffer_id;
}
static struct gve_rx_buf_state_dqo *
gve_dequeue_buf_state(struct gve_rx_ring *rx, struct gve_index_list *list)
{
struct gve_rx_buf_state_dqo *buf_state;
s16 buffer_id;
buffer_id = list->head;
if (unlikely(buffer_id == -1))
return NULL;
buf_state = &rx->dqo.buf_states[buffer_id];
/* Remove buf_state from list */
list->head = buf_state->next;
if (buf_state->next == -1)
list->tail = -1;
/* Point buf_state to itself to mark it as allocated */
buf_state->next = buffer_id;
return buf_state;
}
static void gve_enqueue_buf_state(struct gve_rx_ring *rx,
struct gve_index_list *list,
struct gve_rx_buf_state_dqo *buf_state)
{
s16 buffer_id = buf_state - rx->dqo.buf_states;
buf_state->next = -1;
if (list->head == -1) {
list->head = buffer_id;
list->tail = buffer_id;
} else {
int tail = list->tail;
rx->dqo.buf_states[tail].next = buffer_id;
list->tail = buffer_id;
}
}
static struct gve_rx_buf_state_dqo *
gve_get_recycled_buf_state(struct gve_rx_ring *rx)
{
struct gve_rx_buf_state_dqo *buf_state;
int i;
/* Recycled buf states are immediately usable. */
buf_state = gve_dequeue_buf_state(rx, &rx->dqo.recycled_buf_states);
if (likely(buf_state))
return buf_state;
if (unlikely(rx->dqo.used_buf_states.head == -1))
return NULL;
/* Used buf states are only usable when ref count reaches 0, which means
* no SKBs refer to them.
*
* Search a limited number before giving up.
*/
for (i = 0; i < 5; i++) {
buf_state = gve_dequeue_buf_state(rx, &rx->dqo.used_buf_states);
if (gve_buf_ref_cnt(buf_state) == 0) {
rx->dqo.used_buf_states_cnt--;
return buf_state;
}
gve_enqueue_buf_state(rx, &rx->dqo.used_buf_states, buf_state);
}
/* For QPL, we cannot allocate any new buffers and must
* wait for the existing ones to be available.
*/
if (rx->dqo.qpl)
return NULL;
/* If there are no free buf states discard an entry from
* `used_buf_states` so it can be used.
*/
if (unlikely(rx->dqo.free_buf_states == -1)) {
buf_state = gve_dequeue_buf_state(rx, &rx->dqo.used_buf_states);
if (gve_buf_ref_cnt(buf_state) == 0)
return buf_state;
gve_free_page_dqo(rx->gve, buf_state, true);
gve_free_buf_state(rx, buf_state);
}
return NULL;
}
static int gve_alloc_page_dqo(struct gve_rx_ring *rx,
struct gve_rx_buf_state_dqo *buf_state)
{
struct gve_priv *priv = rx->gve;
u32 idx;
if (!rx->dqo.qpl) {
int err;
err = gve_alloc_page(priv, &priv->pdev->dev,
&buf_state->page_info.page,
&buf_state->addr,
DMA_FROM_DEVICE, GFP_ATOMIC);
if (err)
return err;
} else {
idx = rx->dqo.next_qpl_page_idx;
if (idx >= priv->rx_pages_per_qpl) {
net_err_ratelimited("%s: Out of QPL pages\n",
priv->dev->name);
return -ENOMEM;
}
buf_state->page_info.page = rx->dqo.qpl->pages[idx];
buf_state->addr = rx->dqo.qpl->page_buses[idx];
rx->dqo.next_qpl_page_idx++;
}
buf_state->page_info.page_offset = 0;
buf_state->page_info.page_address =
page_address(buf_state->page_info.page);
buf_state->last_single_ref_offset = 0;
/* The page already has 1 ref. */
page_ref_add(buf_state->page_info.page, INT_MAX - 1);
buf_state->page_info.pagecnt_bias = INT_MAX;
return 0;
}
static void gve_rx_free_ring_dqo(struct gve_priv *priv, int idx)
{
struct gve_rx_ring *rx = &priv->rx[idx];
struct device *hdev = &priv->pdev->dev;
size_t completion_queue_slots;
size_t buffer_queue_slots;
size_t size;
int i;
completion_queue_slots = rx->dqo.complq.mask + 1;
buffer_queue_slots = rx->dqo.bufq.mask + 1;
gve_rx_remove_from_block(priv, idx);
if (rx->q_resources) {
dma_free_coherent(hdev, sizeof(*rx->q_resources),
rx->q_resources, rx->q_resources_bus);
rx->q_resources = NULL;
}
for (i = 0; i < rx->dqo.num_buf_states; i++) {
struct gve_rx_buf_state_dqo *bs = &rx->dqo.buf_states[i];
/* Only free page for RDA. QPL pages are freed in gve_main. */
if (bs->page_info.page)
gve_free_page_dqo(priv, bs, !rx->dqo.qpl);
}
if (rx->dqo.qpl) {
gve_unassign_qpl(priv, rx->dqo.qpl->id);
rx->dqo.qpl = NULL;
}
if (rx->dqo.bufq.desc_ring) {
size = sizeof(rx->dqo.bufq.desc_ring[0]) * buffer_queue_slots;
dma_free_coherent(hdev, size, rx->dqo.bufq.desc_ring,
rx->dqo.bufq.bus);
rx->dqo.bufq.desc_ring = NULL;
}
if (rx->dqo.complq.desc_ring) {
size = sizeof(rx->dqo.complq.desc_ring[0]) *
completion_queue_slots;
dma_free_coherent(hdev, size, rx->dqo.complq.desc_ring,
rx->dqo.complq.bus);
rx->dqo.complq.desc_ring = NULL;
}
kvfree(rx->dqo.buf_states);
rx->dqo.buf_states = NULL;
netif_dbg(priv, drv, priv->dev, "freed rx ring %d\n", idx);
}
static int gve_rx_alloc_ring_dqo(struct gve_priv *priv, int idx)
{
struct gve_rx_ring *rx = &priv->rx[idx];
struct device *hdev = &priv->pdev->dev;
size_t size;
int i;
const u32 buffer_queue_slots =
priv->queue_format == GVE_DQO_RDA_FORMAT ?
priv->options_dqo_rda.rx_buff_ring_entries : priv->rx_desc_cnt;
const u32 completion_queue_slots = priv->rx_desc_cnt;
netif_dbg(priv, drv, priv->dev, "allocating rx ring DQO\n");
memset(rx, 0, sizeof(*rx));
rx->gve = priv;
rx->q_num = idx;
rx->dqo.bufq.mask = buffer_queue_slots - 1;
rx->dqo.complq.num_free_slots = completion_queue_slots;
rx->dqo.complq.mask = completion_queue_slots - 1;
rx->ctx.skb_head = NULL;
rx->ctx.skb_tail = NULL;
rx->dqo.num_buf_states = priv->queue_format == GVE_DQO_RDA_FORMAT ?
min_t(s16, S16_MAX, buffer_queue_slots * 4) :
priv->rx_pages_per_qpl;
rx->dqo.buf_states = kvcalloc(rx->dqo.num_buf_states,
sizeof(rx->dqo.buf_states[0]),
GFP_KERNEL);
if (!rx->dqo.buf_states)
return -ENOMEM;
/* Set up linked list of buffer IDs */
for (i = 0; i < rx->dqo.num_buf_states - 1; i++)
rx->dqo.buf_states[i].next = i + 1;
rx->dqo.buf_states[rx->dqo.num_buf_states - 1].next = -1;
rx->dqo.recycled_buf_states.head = -1;
rx->dqo.recycled_buf_states.tail = -1;
rx->dqo.used_buf_states.head = -1;
rx->dqo.used_buf_states.tail = -1;
/* Allocate RX completion queue */
size = sizeof(rx->dqo.complq.desc_ring[0]) *
completion_queue_slots;
rx->dqo.complq.desc_ring =
dma_alloc_coherent(hdev, size, &rx->dqo.complq.bus, GFP_KERNEL);
if (!rx->dqo.complq.desc_ring)
goto err;
/* Allocate RX buffer queue */
size = sizeof(rx->dqo.bufq.desc_ring[0]) * buffer_queue_slots;
rx->dqo.bufq.desc_ring =
dma_alloc_coherent(hdev, size, &rx->dqo.bufq.bus, GFP_KERNEL);
if (!rx->dqo.bufq.desc_ring)
goto err;
if (priv->queue_format != GVE_DQO_RDA_FORMAT) {
rx->dqo.qpl = gve_assign_rx_qpl(priv, rx->q_num);
if (!rx->dqo.qpl)
goto err;
rx->dqo.next_qpl_page_idx = 0;
}
rx->q_resources = dma_alloc_coherent(hdev, sizeof(*rx->q_resources),
&rx->q_resources_bus, GFP_KERNEL);
if (!rx->q_resources)
goto err;
gve_rx_add_to_block(priv, idx);
return 0;
err:
gve_rx_free_ring_dqo(priv, idx);
return -ENOMEM;
}
void gve_rx_write_doorbell_dqo(const struct gve_priv *priv, int queue_idx)
{
const struct gve_rx_ring *rx = &priv->rx[queue_idx];
u64 index = be32_to_cpu(rx->q_resources->db_index);
iowrite32(rx->dqo.bufq.tail, &priv->db_bar2[index]);
}
int gve_rx_alloc_rings_dqo(struct gve_priv *priv)
{
int err = 0;
int i;
for (i = 0; i < priv->rx_cfg.num_queues; i++) {
err = gve_rx_alloc_ring_dqo(priv, i);
if (err) {
netif_err(priv, drv, priv->dev,
"Failed to alloc rx ring=%d: err=%d\n",
i, err);
goto err;
}
}
return 0;
err:
for (i--; i >= 0; i--)
gve_rx_free_ring_dqo(priv, i);
return err;
}
void gve_rx_free_rings_dqo(struct gve_priv *priv)
{
int i;
for (i = 0; i < priv->rx_cfg.num_queues; i++)
gve_rx_free_ring_dqo(priv, i);
}
void gve_rx_post_buffers_dqo(struct gve_rx_ring *rx)
{
struct gve_rx_compl_queue_dqo *complq = &rx->dqo.complq;
struct gve_rx_buf_queue_dqo *bufq = &rx->dqo.bufq;
struct gve_priv *priv = rx->gve;
u32 num_avail_slots;
u32 num_full_slots;
u32 num_posted = 0;
num_full_slots = (bufq->tail - bufq->head) & bufq->mask;
num_avail_slots = bufq->mask - num_full_slots;
num_avail_slots = min_t(u32, num_avail_slots, complq->num_free_slots);
while (num_posted < num_avail_slots) {
struct gve_rx_desc_dqo *desc = &bufq->desc_ring[bufq->tail];
struct gve_rx_buf_state_dqo *buf_state;
buf_state = gve_get_recycled_buf_state(rx);
if (unlikely(!buf_state)) {
buf_state = gve_alloc_buf_state(rx);
if (unlikely(!buf_state))
break;
if (unlikely(gve_alloc_page_dqo(rx, buf_state))) {
u64_stats_update_begin(&rx->statss);
rx->rx_buf_alloc_fail++;
u64_stats_update_end(&rx->statss);
gve_free_buf_state(rx, buf_state);
break;
}
}
desc->buf_id = cpu_to_le16(buf_state - rx->dqo.buf_states);
desc->buf_addr = cpu_to_le64(buf_state->addr +
buf_state->page_info.page_offset);
bufq->tail = (bufq->tail + 1) & bufq->mask;
complq->num_free_slots--;
num_posted++;
if ((bufq->tail & (GVE_RX_BUF_THRESH_DQO - 1)) == 0)
gve_rx_write_doorbell_dqo(priv, rx->q_num);
}
rx->fill_cnt += num_posted;
}
static void gve_try_recycle_buf(struct gve_priv *priv, struct gve_rx_ring *rx,
struct gve_rx_buf_state_dqo *buf_state)
{
const int data_buffer_size = priv->data_buffer_size_dqo;
int pagecount;
/* Can't reuse if we only fit one buffer per page */
if (data_buffer_size * 2 > PAGE_SIZE)
goto mark_used;
pagecount = gve_buf_ref_cnt(buf_state);
/* Record the offset when we have a single remaining reference.
*
* When this happens, we know all of the other offsets of the page are
* usable.
*/
if (pagecount == 1) {
buf_state->last_single_ref_offset =
buf_state->page_info.page_offset;
}
/* Use the next buffer sized chunk in the page. */
buf_state->page_info.page_offset += data_buffer_size;
buf_state->page_info.page_offset &= (PAGE_SIZE - 1);
/* If we wrap around to the same offset without ever dropping to 1
* reference, then we don't know if this offset was ever freed.
*/
if (buf_state->page_info.page_offset ==
buf_state->last_single_ref_offset) {
goto mark_used;
}
gve_enqueue_buf_state(rx, &rx->dqo.recycled_buf_states, buf_state);
return;
mark_used:
gve_enqueue_buf_state(rx, &rx->dqo.used_buf_states, buf_state);
rx->dqo.used_buf_states_cnt++;
}
static void gve_rx_skb_csum(struct sk_buff *skb,
const struct gve_rx_compl_desc_dqo *desc,
struct gve_ptype ptype)
{
skb->ip_summed = CHECKSUM_NONE;
/* HW did not identify and process L3 and L4 headers. */
if (unlikely(!desc->l3_l4_processed))
return;
if (ptype.l3_type == GVE_L3_TYPE_IPV4) {
if (unlikely(desc->csum_ip_err || desc->csum_external_ip_err))
return;
} else if (ptype.l3_type == GVE_L3_TYPE_IPV6) {
/* Checksum should be skipped if this flag is set. */
if (unlikely(desc->ipv6_ex_add))
return;
}
if (unlikely(desc->csum_l4_err))
return;
switch (ptype.l4_type) {
case GVE_L4_TYPE_TCP:
case GVE_L4_TYPE_UDP:
case GVE_L4_TYPE_ICMP:
case GVE_L4_TYPE_SCTP:
skb->ip_summed = CHECKSUM_UNNECESSARY;
break;
default:
break;
}
}
static void gve_rx_skb_hash(struct sk_buff *skb,
const struct gve_rx_compl_desc_dqo *compl_desc,
struct gve_ptype ptype)
{
enum pkt_hash_types hash_type = PKT_HASH_TYPE_L2;
if (ptype.l4_type != GVE_L4_TYPE_UNKNOWN)
hash_type = PKT_HASH_TYPE_L4;
else if (ptype.l3_type != GVE_L3_TYPE_UNKNOWN)
hash_type = PKT_HASH_TYPE_L3;
skb_set_hash(skb, le32_to_cpu(compl_desc->hash), hash_type);
}
static void gve_rx_free_skb(struct gve_rx_ring *rx)
{
if (!rx->ctx.skb_head)
return;
dev_kfree_skb_any(rx->ctx.skb_head);
rx->ctx.skb_head = NULL;
rx->ctx.skb_tail = NULL;
}
static bool gve_rx_should_trigger_copy_ondemand(struct gve_rx_ring *rx)
{
if (!rx->dqo.qpl)
return false;
if (rx->dqo.used_buf_states_cnt <
(rx->dqo.num_buf_states -
GVE_DQO_QPL_ONDEMAND_ALLOC_THRESHOLD))
return false;
return true;
}
static int gve_rx_copy_ondemand(struct gve_rx_ring *rx,
struct gve_rx_buf_state_dqo *buf_state,
u16 buf_len)
{
struct page *page = alloc_page(GFP_ATOMIC);
int num_frags;
if (!page)
return -ENOMEM;
memcpy(page_address(page),
buf_state->page_info.page_address +
buf_state->page_info.page_offset,
buf_len);
num_frags = skb_shinfo(rx->ctx.skb_tail)->nr_frags;
skb_add_rx_frag(rx->ctx.skb_tail, num_frags, page,
0, buf_len, PAGE_SIZE);
u64_stats_update_begin(&rx->statss);
rx->rx_frag_alloc_cnt++;
u64_stats_update_end(&rx->statss);
/* Return unused buffer. */
gve_enqueue_buf_state(rx, &rx->dqo.recycled_buf_states, buf_state);
return 0;
}
/* Chains multi skbs for single rx packet.
* Returns 0 if buffer is appended, -1 otherwise.
*/
static int gve_rx_append_frags(struct napi_struct *napi,
struct gve_rx_buf_state_dqo *buf_state,
u16 buf_len, struct gve_rx_ring *rx,
struct gve_priv *priv)
{
int num_frags = skb_shinfo(rx->ctx.skb_tail)->nr_frags;
if (unlikely(num_frags == MAX_SKB_FRAGS)) {
struct sk_buff *skb;
skb = napi_alloc_skb(napi, 0);
if (!skb)
return -1;
if (rx->ctx.skb_tail == rx->ctx.skb_head)
skb_shinfo(rx->ctx.skb_head)->frag_list = skb;
else
rx->ctx.skb_tail->next = skb;
rx->ctx.skb_tail = skb;
num_frags = 0;
}
if (rx->ctx.skb_tail != rx->ctx.skb_head) {
rx->ctx.skb_head->len += buf_len;
rx->ctx.skb_head->data_len += buf_len;
rx->ctx.skb_head->truesize += priv->data_buffer_size_dqo;
}
/* Trigger ondemand page allocation if we are running low on buffers */
if (gve_rx_should_trigger_copy_ondemand(rx))
return gve_rx_copy_ondemand(rx, buf_state, buf_len);
skb_add_rx_frag(rx->ctx.skb_tail, num_frags,
buf_state->page_info.page,
buf_state->page_info.page_offset,
buf_len, priv->data_buffer_size_dqo);
gve_dec_pagecnt_bias(&buf_state->page_info);
/* Advances buffer page-offset if page is partially used.
* Marks buffer as used if page is full.
*/
gve_try_recycle_buf(priv, rx, buf_state);
return 0;
}
/* Returns 0 if descriptor is completed successfully.
* Returns -EINVAL if descriptor is invalid.
* Returns -ENOMEM if data cannot be copied to skb.
*/
static int gve_rx_dqo(struct napi_struct *napi, struct gve_rx_ring *rx,
const struct gve_rx_compl_desc_dqo *compl_desc,
int queue_idx)
{
const u16 buffer_id = le16_to_cpu(compl_desc->buf_id);
const bool eop = compl_desc->end_of_packet != 0;
struct gve_rx_buf_state_dqo *buf_state;
struct gve_priv *priv = rx->gve;
u16 buf_len;
if (unlikely(buffer_id >= rx->dqo.num_buf_states)) {
net_err_ratelimited("%s: Invalid RX buffer_id=%u\n",
priv->dev->name, buffer_id);
return -EINVAL;
}
buf_state = &rx->dqo.buf_states[buffer_id];
if (unlikely(!gve_buf_state_is_allocated(rx, buf_state))) {
net_err_ratelimited("%s: RX buffer_id is not allocated: %u\n",
priv->dev->name, buffer_id);
return -EINVAL;
}
if (unlikely(compl_desc->rx_error)) {
gve_enqueue_buf_state(rx, &rx->dqo.recycled_buf_states,
buf_state);
return -EINVAL;
}
buf_len = compl_desc->packet_len;
/* Page might have not been used for awhile and was likely last written
* by a different thread.
*/
prefetch(buf_state->page_info.page);
/* Sync the portion of dma buffer for CPU to read. */
dma_sync_single_range_for_cpu(&priv->pdev->dev, buf_state->addr,
buf_state->page_info.page_offset,
buf_len, DMA_FROM_DEVICE);
/* Append to current skb if one exists. */
if (rx->ctx.skb_head) {
if (unlikely(gve_rx_append_frags(napi, buf_state, buf_len, rx,
priv)) != 0) {
goto error;
}
return 0;
}
if (eop && buf_len <= priv->rx_copybreak) {
rx->ctx.skb_head = gve_rx_copy(priv->dev, napi,
&buf_state->page_info, buf_len);
if (unlikely(!rx->ctx.skb_head))
goto error;
rx->ctx.skb_tail = rx->ctx.skb_head;
u64_stats_update_begin(&rx->statss);
rx->rx_copied_pkt++;
rx->rx_copybreak_pkt++;
u64_stats_update_end(&rx->statss);
gve_enqueue_buf_state(rx, &rx->dqo.recycled_buf_states,
buf_state);
return 0;
}
rx->ctx.skb_head = napi_get_frags(napi);
if (unlikely(!rx->ctx.skb_head))
goto error;
rx->ctx.skb_tail = rx->ctx.skb_head;
if (gve_rx_should_trigger_copy_ondemand(rx)) {
if (gve_rx_copy_ondemand(rx, buf_state, buf_len) < 0)
goto error;
return 0;
}
skb_add_rx_frag(rx->ctx.skb_head, 0, buf_state->page_info.page,
buf_state->page_info.page_offset, buf_len,
priv->data_buffer_size_dqo);
gve_dec_pagecnt_bias(&buf_state->page_info);
gve_try_recycle_buf(priv, rx, buf_state);
return 0;
error:
gve_enqueue_buf_state(rx, &rx->dqo.recycled_buf_states, buf_state);
return -ENOMEM;
}
static int gve_rx_complete_rsc(struct sk_buff *skb,
const struct gve_rx_compl_desc_dqo *desc,
struct gve_ptype ptype)
{
struct skb_shared_info *shinfo = skb_shinfo(skb);
/* Only TCP is supported right now. */
if (ptype.l4_type != GVE_L4_TYPE_TCP)
return -EINVAL;
switch (ptype.l3_type) {
case GVE_L3_TYPE_IPV4:
shinfo->gso_type = SKB_GSO_TCPV4;
break;
case GVE_L3_TYPE_IPV6:
shinfo->gso_type = SKB_GSO_TCPV6;
break;
default:
return -EINVAL;
}
shinfo->gso_size = le16_to_cpu(desc->rsc_seg_len);
return 0;
}
/* Returns 0 if skb is completed successfully, -1 otherwise. */
static int gve_rx_complete_skb(struct gve_rx_ring *rx, struct napi_struct *napi,
const struct gve_rx_compl_desc_dqo *desc,
netdev_features_t feat)
{
struct gve_ptype ptype =
rx->gve->ptype_lut_dqo->ptypes[desc->packet_type];
int err;
skb_record_rx_queue(rx->ctx.skb_head, rx->q_num);
if (feat & NETIF_F_RXHASH)
gve_rx_skb_hash(rx->ctx.skb_head, desc, ptype);
if (feat & NETIF_F_RXCSUM)
gve_rx_skb_csum(rx->ctx.skb_head, desc, ptype);
/* RSC packets must set gso_size otherwise the TCP stack will complain
* that packets are larger than MTU.
*/
if (desc->rsc) {
err = gve_rx_complete_rsc(rx->ctx.skb_head, desc, ptype);
if (err < 0)
return err;
}
if (skb_headlen(rx->ctx.skb_head) == 0)
napi_gro_frags(napi);
else
napi_gro_receive(napi, rx->ctx.skb_head);
return 0;
}
int gve_rx_poll_dqo(struct gve_notify_block *block, int budget)
{
struct napi_struct *napi = &block->napi;
netdev_features_t feat = napi->dev->features;
struct gve_rx_ring *rx = block->rx;
struct gve_rx_compl_queue_dqo *complq = &rx->dqo.complq;
u32 work_done = 0;
u64 bytes = 0;
int err;
while (work_done < budget) {
struct gve_rx_compl_desc_dqo *compl_desc =
&complq->desc_ring[complq->head];
u32 pkt_bytes;
/* No more new packets */
if (compl_desc->generation == complq->cur_gen_bit)
break;
/* Prefetch the next two descriptors. */
prefetch(&complq->desc_ring[(complq->head + 1) & complq->mask]);
prefetch(&complq->desc_ring[(complq->head + 2) & complq->mask]);
/* Do not read data until we own the descriptor */
dma_rmb();
err = gve_rx_dqo(napi, rx, compl_desc, rx->q_num);
if (err < 0) {
gve_rx_free_skb(rx);
u64_stats_update_begin(&rx->statss);
if (err == -ENOMEM)
rx->rx_skb_alloc_fail++;
else if (err == -EINVAL)
rx->rx_desc_err_dropped_pkt++;
u64_stats_update_end(&rx->statss);
}
complq->head = (complq->head + 1) & complq->mask;
complq->num_free_slots++;
/* When the ring wraps, the generation bit is flipped. */
complq->cur_gen_bit ^= (complq->head == 0);
/* Receiving a completion means we have space to post another
* buffer on the buffer queue.
*/
{
struct gve_rx_buf_queue_dqo *bufq = &rx->dqo.bufq;
bufq->head = (bufq->head + 1) & bufq->mask;
}
/* Free running counter of completed descriptors */
rx->cnt++;
if (!rx->ctx.skb_head)
continue;
if (!compl_desc->end_of_packet)
continue;
work_done++;
pkt_bytes = rx->ctx.skb_head->len;
/* The ethernet header (first ETH_HLEN bytes) is snipped off
* by eth_type_trans.
*/
if (skb_headlen(rx->ctx.skb_head))
pkt_bytes += ETH_HLEN;
/* gve_rx_complete_skb() will consume skb if successful */
if (gve_rx_complete_skb(rx, napi, compl_desc, feat) != 0) {
gve_rx_free_skb(rx);
u64_stats_update_begin(&rx->statss);
rx->rx_desc_err_dropped_pkt++;
u64_stats_update_end(&rx->statss);
continue;
}
bytes += pkt_bytes;
rx->ctx.skb_head = NULL;
rx->ctx.skb_tail = NULL;
}
gve_rx_post_buffers_dqo(rx);
u64_stats_update_begin(&rx->statss);
rx->rpackets += work_done;
rx->rbytes += bytes;
u64_stats_update_end(&rx->statss);
return work_done;
}
|
linux-master
|
drivers/net/ethernet/google/gve/gve_rx_dqo.c
|
// SPDX-License-Identifier: (GPL-2.0 OR MIT)
/* Google virtual Ethernet (gve) driver
*
* Copyright (C) 2015-2021 Google, Inc.
*/
#include "gve.h"
#include "gve_adminq.h"
#include "gve_utils.h"
#include "gve_dqo.h"
#include <net/ip.h>
#include <linux/tcp.h>
#include <linux/slab.h>
#include <linux/skbuff.h>
/* Returns true if tx_bufs are available. */
static bool gve_has_free_tx_qpl_bufs(struct gve_tx_ring *tx, int count)
{
int num_avail;
if (!tx->dqo.qpl)
return true;
num_avail = tx->dqo.num_tx_qpl_bufs -
(tx->dqo_tx.alloc_tx_qpl_buf_cnt -
tx->dqo_tx.free_tx_qpl_buf_cnt);
if (count <= num_avail)
return true;
/* Update cached value from dqo_compl. */
tx->dqo_tx.free_tx_qpl_buf_cnt =
atomic_read_acquire(&tx->dqo_compl.free_tx_qpl_buf_cnt);
num_avail = tx->dqo.num_tx_qpl_bufs -
(tx->dqo_tx.alloc_tx_qpl_buf_cnt -
tx->dqo_tx.free_tx_qpl_buf_cnt);
return count <= num_avail;
}
static s16
gve_alloc_tx_qpl_buf(struct gve_tx_ring *tx)
{
s16 index;
index = tx->dqo_tx.free_tx_qpl_buf_head;
/* No TX buffers available, try to steal the list from the
* completion handler.
*/
if (unlikely(index == -1)) {
tx->dqo_tx.free_tx_qpl_buf_head =
atomic_xchg(&tx->dqo_compl.free_tx_qpl_buf_head, -1);
index = tx->dqo_tx.free_tx_qpl_buf_head;
if (unlikely(index == -1))
return index;
}
/* Remove TX buf from free list */
tx->dqo_tx.free_tx_qpl_buf_head = tx->dqo.tx_qpl_buf_next[index];
return index;
}
static void
gve_free_tx_qpl_bufs(struct gve_tx_ring *tx,
struct gve_tx_pending_packet_dqo *pkt)
{
s16 index;
int i;
if (!pkt->num_bufs)
return;
index = pkt->tx_qpl_buf_ids[0];
/* Create a linked list of buffers to be added to the free list */
for (i = 1; i < pkt->num_bufs; i++) {
tx->dqo.tx_qpl_buf_next[index] = pkt->tx_qpl_buf_ids[i];
index = pkt->tx_qpl_buf_ids[i];
}
while (true) {
s16 old_head = atomic_read_acquire(&tx->dqo_compl.free_tx_qpl_buf_head);
tx->dqo.tx_qpl_buf_next[index] = old_head;
if (atomic_cmpxchg(&tx->dqo_compl.free_tx_qpl_buf_head,
old_head,
pkt->tx_qpl_buf_ids[0]) == old_head) {
break;
}
}
atomic_add(pkt->num_bufs, &tx->dqo_compl.free_tx_qpl_buf_cnt);
pkt->num_bufs = 0;
}
/* Returns true if a gve_tx_pending_packet_dqo object is available. */
static bool gve_has_pending_packet(struct gve_tx_ring *tx)
{
/* Check TX path's list. */
if (tx->dqo_tx.free_pending_packets != -1)
return true;
/* Check completion handler's list. */
if (atomic_read_acquire(&tx->dqo_compl.free_pending_packets) != -1)
return true;
return false;
}
static struct gve_tx_pending_packet_dqo *
gve_alloc_pending_packet(struct gve_tx_ring *tx)
{
struct gve_tx_pending_packet_dqo *pending_packet;
s16 index;
index = tx->dqo_tx.free_pending_packets;
/* No pending_packets available, try to steal the list from the
* completion handler.
*/
if (unlikely(index == -1)) {
tx->dqo_tx.free_pending_packets =
atomic_xchg(&tx->dqo_compl.free_pending_packets, -1);
index = tx->dqo_tx.free_pending_packets;
if (unlikely(index == -1))
return NULL;
}
pending_packet = &tx->dqo.pending_packets[index];
/* Remove pending_packet from free list */
tx->dqo_tx.free_pending_packets = pending_packet->next;
pending_packet->state = GVE_PACKET_STATE_PENDING_DATA_COMPL;
return pending_packet;
}
static void
gve_free_pending_packet(struct gve_tx_ring *tx,
struct gve_tx_pending_packet_dqo *pending_packet)
{
s16 index = pending_packet - tx->dqo.pending_packets;
pending_packet->state = GVE_PACKET_STATE_UNALLOCATED;
while (true) {
s16 old_head = atomic_read_acquire(&tx->dqo_compl.free_pending_packets);
pending_packet->next = old_head;
if (atomic_cmpxchg(&tx->dqo_compl.free_pending_packets,
old_head, index) == old_head) {
break;
}
}
}
/* gve_tx_free_desc - Cleans up all pending tx requests and buffers.
*/
static void gve_tx_clean_pending_packets(struct gve_tx_ring *tx)
{
int i;
for (i = 0; i < tx->dqo.num_pending_packets; i++) {
struct gve_tx_pending_packet_dqo *cur_state =
&tx->dqo.pending_packets[i];
int j;
for (j = 0; j < cur_state->num_bufs; j++) {
if (j == 0) {
dma_unmap_single(tx->dev,
dma_unmap_addr(cur_state, dma[j]),
dma_unmap_len(cur_state, len[j]),
DMA_TO_DEVICE);
} else {
dma_unmap_page(tx->dev,
dma_unmap_addr(cur_state, dma[j]),
dma_unmap_len(cur_state, len[j]),
DMA_TO_DEVICE);
}
}
if (cur_state->skb) {
dev_consume_skb_any(cur_state->skb);
cur_state->skb = NULL;
}
}
}
static void gve_tx_free_ring_dqo(struct gve_priv *priv, int idx)
{
struct gve_tx_ring *tx = &priv->tx[idx];
struct device *hdev = &priv->pdev->dev;
size_t bytes;
gve_tx_remove_from_block(priv, idx);
if (tx->q_resources) {
dma_free_coherent(hdev, sizeof(*tx->q_resources),
tx->q_resources, tx->q_resources_bus);
tx->q_resources = NULL;
}
if (tx->dqo.compl_ring) {
bytes = sizeof(tx->dqo.compl_ring[0]) *
(tx->dqo.complq_mask + 1);
dma_free_coherent(hdev, bytes, tx->dqo.compl_ring,
tx->complq_bus_dqo);
tx->dqo.compl_ring = NULL;
}
if (tx->dqo.tx_ring) {
bytes = sizeof(tx->dqo.tx_ring[0]) * (tx->mask + 1);
dma_free_coherent(hdev, bytes, tx->dqo.tx_ring, tx->bus);
tx->dqo.tx_ring = NULL;
}
kvfree(tx->dqo.pending_packets);
tx->dqo.pending_packets = NULL;
kvfree(tx->dqo.tx_qpl_buf_next);
tx->dqo.tx_qpl_buf_next = NULL;
if (tx->dqo.qpl) {
gve_unassign_qpl(priv, tx->dqo.qpl->id);
tx->dqo.qpl = NULL;
}
netif_dbg(priv, drv, priv->dev, "freed tx queue %d\n", idx);
}
static int gve_tx_qpl_buf_init(struct gve_tx_ring *tx)
{
int num_tx_qpl_bufs = GVE_TX_BUFS_PER_PAGE_DQO *
tx->dqo.qpl->num_entries;
int i;
tx->dqo.tx_qpl_buf_next = kvcalloc(num_tx_qpl_bufs,
sizeof(tx->dqo.tx_qpl_buf_next[0]),
GFP_KERNEL);
if (!tx->dqo.tx_qpl_buf_next)
return -ENOMEM;
tx->dqo.num_tx_qpl_bufs = num_tx_qpl_bufs;
/* Generate free TX buf list */
for (i = 0; i < num_tx_qpl_bufs - 1; i++)
tx->dqo.tx_qpl_buf_next[i] = i + 1;
tx->dqo.tx_qpl_buf_next[num_tx_qpl_bufs - 1] = -1;
atomic_set_release(&tx->dqo_compl.free_tx_qpl_buf_head, -1);
return 0;
}
static int gve_tx_alloc_ring_dqo(struct gve_priv *priv, int idx)
{
struct gve_tx_ring *tx = &priv->tx[idx];
struct device *hdev = &priv->pdev->dev;
int num_pending_packets;
size_t bytes;
int i;
memset(tx, 0, sizeof(*tx));
tx->q_num = idx;
tx->dev = &priv->pdev->dev;
tx->netdev_txq = netdev_get_tx_queue(priv->dev, idx);
atomic_set_release(&tx->dqo_compl.hw_tx_head, 0);
/* Queue sizes must be a power of 2 */
tx->mask = priv->tx_desc_cnt - 1;
tx->dqo.complq_mask = priv->queue_format == GVE_DQO_RDA_FORMAT ?
priv->options_dqo_rda.tx_comp_ring_entries - 1 :
tx->mask;
/* The max number of pending packets determines the maximum number of
* descriptors which maybe written to the completion queue.
*
* We must set the number small enough to make sure we never overrun the
* completion queue.
*/
num_pending_packets = tx->dqo.complq_mask + 1;
/* Reserve space for descriptor completions, which will be reported at
* most every GVE_TX_MIN_RE_INTERVAL packets.
*/
num_pending_packets -=
(tx->dqo.complq_mask + 1) / GVE_TX_MIN_RE_INTERVAL;
/* Each packet may have at most 2 buffer completions if it receives both
* a miss and reinjection completion.
*/
num_pending_packets /= 2;
tx->dqo.num_pending_packets = min_t(int, num_pending_packets, S16_MAX);
tx->dqo.pending_packets = kvcalloc(tx->dqo.num_pending_packets,
sizeof(tx->dqo.pending_packets[0]),
GFP_KERNEL);
if (!tx->dqo.pending_packets)
goto err;
/* Set up linked list of pending packets */
for (i = 0; i < tx->dqo.num_pending_packets - 1; i++)
tx->dqo.pending_packets[i].next = i + 1;
tx->dqo.pending_packets[tx->dqo.num_pending_packets - 1].next = -1;
atomic_set_release(&tx->dqo_compl.free_pending_packets, -1);
tx->dqo_compl.miss_completions.head = -1;
tx->dqo_compl.miss_completions.tail = -1;
tx->dqo_compl.timed_out_completions.head = -1;
tx->dqo_compl.timed_out_completions.tail = -1;
bytes = sizeof(tx->dqo.tx_ring[0]) * (tx->mask + 1);
tx->dqo.tx_ring = dma_alloc_coherent(hdev, bytes, &tx->bus, GFP_KERNEL);
if (!tx->dqo.tx_ring)
goto err;
bytes = sizeof(tx->dqo.compl_ring[0]) * (tx->dqo.complq_mask + 1);
tx->dqo.compl_ring = dma_alloc_coherent(hdev, bytes,
&tx->complq_bus_dqo,
GFP_KERNEL);
if (!tx->dqo.compl_ring)
goto err;
tx->q_resources = dma_alloc_coherent(hdev, sizeof(*tx->q_resources),
&tx->q_resources_bus, GFP_KERNEL);
if (!tx->q_resources)
goto err;
if (gve_is_qpl(priv)) {
tx->dqo.qpl = gve_assign_tx_qpl(priv, idx);
if (!tx->dqo.qpl)
goto err;
if (gve_tx_qpl_buf_init(tx))
goto err;
}
gve_tx_add_to_block(priv, idx);
return 0;
err:
gve_tx_free_ring_dqo(priv, idx);
return -ENOMEM;
}
int gve_tx_alloc_rings_dqo(struct gve_priv *priv)
{
int err = 0;
int i;
for (i = 0; i < priv->tx_cfg.num_queues; i++) {
err = gve_tx_alloc_ring_dqo(priv, i);
if (err) {
netif_err(priv, drv, priv->dev,
"Failed to alloc tx ring=%d: err=%d\n",
i, err);
goto err;
}
}
return 0;
err:
for (i--; i >= 0; i--)
gve_tx_free_ring_dqo(priv, i);
return err;
}
void gve_tx_free_rings_dqo(struct gve_priv *priv)
{
int i;
for (i = 0; i < priv->tx_cfg.num_queues; i++) {
struct gve_tx_ring *tx = &priv->tx[i];
gve_clean_tx_done_dqo(priv, tx, /*napi=*/NULL);
netdev_tx_reset_queue(tx->netdev_txq);
gve_tx_clean_pending_packets(tx);
gve_tx_free_ring_dqo(priv, i);
}
}
/* Returns the number of slots available in the ring */
static u32 num_avail_tx_slots(const struct gve_tx_ring *tx)
{
u32 num_used = (tx->dqo_tx.tail - tx->dqo_tx.head) & tx->mask;
return tx->mask - num_used;
}
static bool gve_has_avail_slots_tx_dqo(struct gve_tx_ring *tx,
int desc_count, int buf_count)
{
return gve_has_pending_packet(tx) &&
num_avail_tx_slots(tx) >= desc_count &&
gve_has_free_tx_qpl_bufs(tx, buf_count);
}
/* Stops the queue if available descriptors is less than 'count'.
* Return: 0 if stop is not required.
*/
static int gve_maybe_stop_tx_dqo(struct gve_tx_ring *tx,
int desc_count, int buf_count)
{
if (likely(gve_has_avail_slots_tx_dqo(tx, desc_count, buf_count)))
return 0;
/* Update cached TX head pointer */
tx->dqo_tx.head = atomic_read_acquire(&tx->dqo_compl.hw_tx_head);
if (likely(gve_has_avail_slots_tx_dqo(tx, desc_count, buf_count)))
return 0;
/* No space, so stop the queue */
tx->stop_queue++;
netif_tx_stop_queue(tx->netdev_txq);
/* Sync with restarting queue in `gve_tx_poll_dqo()` */
mb();
/* After stopping queue, check if we can transmit again in order to
* avoid TOCTOU bug.
*/
tx->dqo_tx.head = atomic_read_acquire(&tx->dqo_compl.hw_tx_head);
if (likely(!gve_has_avail_slots_tx_dqo(tx, desc_count, buf_count)))
return -EBUSY;
netif_tx_start_queue(tx->netdev_txq);
tx->wake_queue++;
return 0;
}
static void gve_extract_tx_metadata_dqo(const struct sk_buff *skb,
struct gve_tx_metadata_dqo *metadata)
{
memset(metadata, 0, sizeof(*metadata));
metadata->version = GVE_TX_METADATA_VERSION_DQO;
if (skb->l4_hash) {
u16 path_hash = skb->hash ^ (skb->hash >> 16);
path_hash &= (1 << 15) - 1;
if (unlikely(path_hash == 0))
path_hash = ~path_hash;
metadata->path_hash = path_hash;
}
}
static void gve_tx_fill_pkt_desc_dqo(struct gve_tx_ring *tx, u32 *desc_idx,
struct sk_buff *skb, u32 len, u64 addr,
s16 compl_tag, bool eop, bool is_gso)
{
const bool checksum_offload_en = skb->ip_summed == CHECKSUM_PARTIAL;
while (len > 0) {
struct gve_tx_pkt_desc_dqo *desc =
&tx->dqo.tx_ring[*desc_idx].pkt;
u32 cur_len = min_t(u32, len, GVE_TX_MAX_BUF_SIZE_DQO);
bool cur_eop = eop && cur_len == len;
*desc = (struct gve_tx_pkt_desc_dqo){
.buf_addr = cpu_to_le64(addr),
.dtype = GVE_TX_PKT_DESC_DTYPE_DQO,
.end_of_packet = cur_eop,
.checksum_offload_enable = checksum_offload_en,
.compl_tag = cpu_to_le16(compl_tag),
.buf_size = cur_len,
};
addr += cur_len;
len -= cur_len;
*desc_idx = (*desc_idx + 1) & tx->mask;
}
}
/* Validates and prepares `skb` for TSO.
*
* Returns header length, or < 0 if invalid.
*/
static int gve_prep_tso(struct sk_buff *skb)
{
struct tcphdr *tcp;
int header_len;
u32 paylen;
int err;
/* Note: HW requires MSS (gso_size) to be <= 9728 and the total length
* of the TSO to be <= 262143.
*
* However, we don't validate these because:
* - Hypervisor enforces a limit of 9K MTU
* - Kernel will not produce a TSO larger than 64k
*/
if (unlikely(skb_shinfo(skb)->gso_size < GVE_TX_MIN_TSO_MSS_DQO))
return -1;
/* Needed because we will modify header. */
err = skb_cow_head(skb, 0);
if (err < 0)
return err;
tcp = tcp_hdr(skb);
/* Remove payload length from checksum. */
paylen = skb->len - skb_transport_offset(skb);
switch (skb_shinfo(skb)->gso_type) {
case SKB_GSO_TCPV4:
case SKB_GSO_TCPV6:
csum_replace_by_diff(&tcp->check,
(__force __wsum)htonl(paylen));
/* Compute length of segmentation header. */
header_len = skb_tcp_all_headers(skb);
break;
default:
return -EINVAL;
}
if (unlikely(header_len > GVE_TX_MAX_HDR_SIZE_DQO))
return -EINVAL;
return header_len;
}
static void gve_tx_fill_tso_ctx_desc(struct gve_tx_tso_context_desc_dqo *desc,
const struct sk_buff *skb,
const struct gve_tx_metadata_dqo *metadata,
int header_len)
{
*desc = (struct gve_tx_tso_context_desc_dqo){
.header_len = header_len,
.cmd_dtype = {
.dtype = GVE_TX_TSO_CTX_DESC_DTYPE_DQO,
.tso = 1,
},
.flex0 = metadata->bytes[0],
.flex5 = metadata->bytes[5],
.flex6 = metadata->bytes[6],
.flex7 = metadata->bytes[7],
.flex8 = metadata->bytes[8],
.flex9 = metadata->bytes[9],
.flex10 = metadata->bytes[10],
.flex11 = metadata->bytes[11],
};
desc->tso_total_len = skb->len - header_len;
desc->mss = skb_shinfo(skb)->gso_size;
}
static void
gve_tx_fill_general_ctx_desc(struct gve_tx_general_context_desc_dqo *desc,
const struct gve_tx_metadata_dqo *metadata)
{
*desc = (struct gve_tx_general_context_desc_dqo){
.flex0 = metadata->bytes[0],
.flex1 = metadata->bytes[1],
.flex2 = metadata->bytes[2],
.flex3 = metadata->bytes[3],
.flex4 = metadata->bytes[4],
.flex5 = metadata->bytes[5],
.flex6 = metadata->bytes[6],
.flex7 = metadata->bytes[7],
.flex8 = metadata->bytes[8],
.flex9 = metadata->bytes[9],
.flex10 = metadata->bytes[10],
.flex11 = metadata->bytes[11],
.cmd_dtype = {.dtype = GVE_TX_GENERAL_CTX_DESC_DTYPE_DQO},
};
}
static int gve_tx_add_skb_no_copy_dqo(struct gve_tx_ring *tx,
struct sk_buff *skb,
struct gve_tx_pending_packet_dqo *pkt,
s16 completion_tag,
u32 *desc_idx,
bool is_gso)
{
const struct skb_shared_info *shinfo = skb_shinfo(skb);
int i;
/* Note: HW requires that the size of a non-TSO packet be within the
* range of [17, 9728].
*
* We don't double check because
* - We limited `netdev->min_mtu` to ETH_MIN_MTU.
* - Hypervisor won't allow MTU larger than 9216.
*/
pkt->num_bufs = 0;
/* Map the linear portion of skb */
{
u32 len = skb_headlen(skb);
dma_addr_t addr;
addr = dma_map_single(tx->dev, skb->data, len, DMA_TO_DEVICE);
if (unlikely(dma_mapping_error(tx->dev, addr)))
goto err;
dma_unmap_len_set(pkt, len[pkt->num_bufs], len);
dma_unmap_addr_set(pkt, dma[pkt->num_bufs], addr);
++pkt->num_bufs;
gve_tx_fill_pkt_desc_dqo(tx, desc_idx, skb, len, addr,
completion_tag,
/*eop=*/shinfo->nr_frags == 0, is_gso);
}
for (i = 0; i < shinfo->nr_frags; i++) {
const skb_frag_t *frag = &shinfo->frags[i];
bool is_eop = i == (shinfo->nr_frags - 1);
u32 len = skb_frag_size(frag);
dma_addr_t addr;
addr = skb_frag_dma_map(tx->dev, frag, 0, len, DMA_TO_DEVICE);
if (unlikely(dma_mapping_error(tx->dev, addr)))
goto err;
dma_unmap_len_set(pkt, len[pkt->num_bufs], len);
dma_unmap_addr_set(pkt, dma[pkt->num_bufs], addr);
++pkt->num_bufs;
gve_tx_fill_pkt_desc_dqo(tx, desc_idx, skb, len, addr,
completion_tag, is_eop, is_gso);
}
return 0;
err:
for (i = 0; i < pkt->num_bufs; i++) {
if (i == 0) {
dma_unmap_single(tx->dev,
dma_unmap_addr(pkt, dma[i]),
dma_unmap_len(pkt, len[i]),
DMA_TO_DEVICE);
} else {
dma_unmap_page(tx->dev,
dma_unmap_addr(pkt, dma[i]),
dma_unmap_len(pkt, len[i]),
DMA_TO_DEVICE);
}
}
pkt->num_bufs = 0;
return -1;
}
/* Tx buffer i corresponds to
* qpl_page_id = i / GVE_TX_BUFS_PER_PAGE_DQO
* qpl_page_offset = (i % GVE_TX_BUFS_PER_PAGE_DQO) * GVE_TX_BUF_SIZE_DQO
*/
static void gve_tx_buf_get_addr(struct gve_tx_ring *tx,
s16 index,
void **va, dma_addr_t *dma_addr)
{
int page_id = index >> (PAGE_SHIFT - GVE_TX_BUF_SHIFT_DQO);
int offset = (index & (GVE_TX_BUFS_PER_PAGE_DQO - 1)) << GVE_TX_BUF_SHIFT_DQO;
*va = page_address(tx->dqo.qpl->pages[page_id]) + offset;
*dma_addr = tx->dqo.qpl->page_buses[page_id] + offset;
}
static int gve_tx_add_skb_copy_dqo(struct gve_tx_ring *tx,
struct sk_buff *skb,
struct gve_tx_pending_packet_dqo *pkt,
s16 completion_tag,
u32 *desc_idx,
bool is_gso)
{
u32 copy_offset = 0;
dma_addr_t dma_addr;
u32 copy_len;
s16 index;
void *va;
/* Break the packet into buffer size chunks */
pkt->num_bufs = 0;
while (copy_offset < skb->len) {
index = gve_alloc_tx_qpl_buf(tx);
if (unlikely(index == -1))
goto err;
gve_tx_buf_get_addr(tx, index, &va, &dma_addr);
copy_len = min_t(u32, GVE_TX_BUF_SIZE_DQO,
skb->len - copy_offset);
skb_copy_bits(skb, copy_offset, va, copy_len);
copy_offset += copy_len;
dma_sync_single_for_device(tx->dev, dma_addr,
copy_len, DMA_TO_DEVICE);
gve_tx_fill_pkt_desc_dqo(tx, desc_idx, skb,
copy_len,
dma_addr,
completion_tag,
copy_offset == skb->len,
is_gso);
pkt->tx_qpl_buf_ids[pkt->num_bufs] = index;
++tx->dqo_tx.alloc_tx_qpl_buf_cnt;
++pkt->num_bufs;
}
return 0;
err:
/* Should not be here if gve_has_free_tx_qpl_bufs() check is correct */
gve_free_tx_qpl_bufs(tx, pkt);
return -ENOMEM;
}
/* Returns 0 on success, or < 0 on error.
*
* Before this function is called, the caller must ensure
* gve_has_pending_packet(tx) returns true.
*/
static int gve_tx_add_skb_dqo(struct gve_tx_ring *tx,
struct sk_buff *skb)
{
const bool is_gso = skb_is_gso(skb);
u32 desc_idx = tx->dqo_tx.tail;
struct gve_tx_pending_packet_dqo *pkt;
struct gve_tx_metadata_dqo metadata;
s16 completion_tag;
pkt = gve_alloc_pending_packet(tx);
pkt->skb = skb;
completion_tag = pkt - tx->dqo.pending_packets;
gve_extract_tx_metadata_dqo(skb, &metadata);
if (is_gso) {
int header_len = gve_prep_tso(skb);
if (unlikely(header_len < 0))
goto err;
gve_tx_fill_tso_ctx_desc(&tx->dqo.tx_ring[desc_idx].tso_ctx,
skb, &metadata, header_len);
desc_idx = (desc_idx + 1) & tx->mask;
}
gve_tx_fill_general_ctx_desc(&tx->dqo.tx_ring[desc_idx].general_ctx,
&metadata);
desc_idx = (desc_idx + 1) & tx->mask;
if (tx->dqo.qpl) {
if (gve_tx_add_skb_copy_dqo(tx, skb, pkt,
completion_tag,
&desc_idx, is_gso))
goto err;
} else {
if (gve_tx_add_skb_no_copy_dqo(tx, skb, pkt,
completion_tag,
&desc_idx, is_gso))
goto err;
}
tx->dqo_tx.posted_packet_desc_cnt += pkt->num_bufs;
/* Commit the changes to our state */
tx->dqo_tx.tail = desc_idx;
/* Request a descriptor completion on the last descriptor of the
* packet if we are allowed to by the HW enforced interval.
*/
{
u32 last_desc_idx = (desc_idx - 1) & tx->mask;
u32 last_report_event_interval =
(last_desc_idx - tx->dqo_tx.last_re_idx) & tx->mask;
if (unlikely(last_report_event_interval >=
GVE_TX_MIN_RE_INTERVAL)) {
tx->dqo.tx_ring[last_desc_idx].pkt.report_event = true;
tx->dqo_tx.last_re_idx = last_desc_idx;
}
}
return 0;
err:
pkt->skb = NULL;
gve_free_pending_packet(tx, pkt);
return -1;
}
static int gve_num_descs_per_buf(size_t size)
{
return DIV_ROUND_UP(size, GVE_TX_MAX_BUF_SIZE_DQO);
}
static int gve_num_buffer_descs_needed(const struct sk_buff *skb)
{
const struct skb_shared_info *shinfo = skb_shinfo(skb);
int num_descs;
int i;
num_descs = gve_num_descs_per_buf(skb_headlen(skb));
for (i = 0; i < shinfo->nr_frags; i++) {
unsigned int frag_size = skb_frag_size(&shinfo->frags[i]);
num_descs += gve_num_descs_per_buf(frag_size);
}
return num_descs;
}
/* Returns true if HW is capable of sending TSO represented by `skb`.
*
* Each segment must not span more than GVE_TX_MAX_DATA_DESCS buffers.
* - The header is counted as one buffer for every single segment.
* - A buffer which is split between two segments is counted for both.
* - If a buffer contains both header and payload, it is counted as two buffers.
*/
static bool gve_can_send_tso(const struct sk_buff *skb)
{
const int max_bufs_per_seg = GVE_TX_MAX_DATA_DESCS - 1;
const struct skb_shared_info *shinfo = skb_shinfo(skb);
const int header_len = skb_tcp_all_headers(skb);
const int gso_size = shinfo->gso_size;
int cur_seg_num_bufs;
int cur_seg_size;
int i;
cur_seg_size = skb_headlen(skb) - header_len;
cur_seg_num_bufs = cur_seg_size > 0;
for (i = 0; i < shinfo->nr_frags; i++) {
if (cur_seg_size >= gso_size) {
cur_seg_size %= gso_size;
cur_seg_num_bufs = cur_seg_size > 0;
}
if (unlikely(++cur_seg_num_bufs > max_bufs_per_seg))
return false;
cur_seg_size += skb_frag_size(&shinfo->frags[i]);
}
return true;
}
/* Attempt to transmit specified SKB.
*
* Returns 0 if the SKB was transmitted or dropped.
* Returns -1 if there is not currently enough space to transmit the SKB.
*/
static int gve_try_tx_skb(struct gve_priv *priv, struct gve_tx_ring *tx,
struct sk_buff *skb)
{
int num_buffer_descs;
int total_num_descs;
if (tx->dqo.qpl) {
if (skb_is_gso(skb))
if (unlikely(ipv6_hopopt_jumbo_remove(skb)))
goto drop;
/* We do not need to verify the number of buffers used per
* packet or per segment in case of TSO as with 2K size buffers
* none of the TX packet rules would be violated.
*
* gve_can_send_tso() checks that each TCP segment of gso_size is
* not distributed over more than 9 SKB frags..
*/
num_buffer_descs = DIV_ROUND_UP(skb->len, GVE_TX_BUF_SIZE_DQO);
} else {
if (skb_is_gso(skb)) {
/* If TSO doesn't meet HW requirements, attempt to linearize the
* packet.
*/
if (unlikely(!gve_can_send_tso(skb) &&
skb_linearize(skb) < 0)) {
net_err_ratelimited("%s: Failed to transmit TSO packet\n",
priv->dev->name);
goto drop;
}
if (unlikely(ipv6_hopopt_jumbo_remove(skb)))
goto drop;
num_buffer_descs = gve_num_buffer_descs_needed(skb);
} else {
num_buffer_descs = gve_num_buffer_descs_needed(skb);
if (unlikely(num_buffer_descs > GVE_TX_MAX_DATA_DESCS)) {
if (unlikely(skb_linearize(skb) < 0))
goto drop;
num_buffer_descs = 1;
}
}
}
/* Metadata + (optional TSO) + data descriptors. */
total_num_descs = 1 + skb_is_gso(skb) + num_buffer_descs;
if (unlikely(gve_maybe_stop_tx_dqo(tx, total_num_descs +
GVE_TX_MIN_DESC_PREVENT_CACHE_OVERLAP,
num_buffer_descs))) {
return -1;
}
if (unlikely(gve_tx_add_skb_dqo(tx, skb) < 0))
goto drop;
netdev_tx_sent_queue(tx->netdev_txq, skb->len);
skb_tx_timestamp(skb);
return 0;
drop:
tx->dropped_pkt++;
dev_kfree_skb_any(skb);
return 0;
}
/* Transmit a given skb and ring the doorbell. */
netdev_tx_t gve_tx_dqo(struct sk_buff *skb, struct net_device *dev)
{
struct gve_priv *priv = netdev_priv(dev);
struct gve_tx_ring *tx;
tx = &priv->tx[skb_get_queue_mapping(skb)];
if (unlikely(gve_try_tx_skb(priv, tx, skb) < 0)) {
/* We need to ring the txq doorbell -- we have stopped the Tx
* queue for want of resources, but prior calls to gve_tx()
* may have added descriptors without ringing the doorbell.
*/
gve_tx_put_doorbell_dqo(priv, tx->q_resources, tx->dqo_tx.tail);
return NETDEV_TX_BUSY;
}
if (!netif_xmit_stopped(tx->netdev_txq) && netdev_xmit_more())
return NETDEV_TX_OK;
gve_tx_put_doorbell_dqo(priv, tx->q_resources, tx->dqo_tx.tail);
return NETDEV_TX_OK;
}
static void add_to_list(struct gve_tx_ring *tx, struct gve_index_list *list,
struct gve_tx_pending_packet_dqo *pending_packet)
{
s16 old_tail, index;
index = pending_packet - tx->dqo.pending_packets;
old_tail = list->tail;
list->tail = index;
if (old_tail == -1)
list->head = index;
else
tx->dqo.pending_packets[old_tail].next = index;
pending_packet->next = -1;
pending_packet->prev = old_tail;
}
static void remove_from_list(struct gve_tx_ring *tx,
struct gve_index_list *list,
struct gve_tx_pending_packet_dqo *pkt)
{
s16 prev_index, next_index;
prev_index = pkt->prev;
next_index = pkt->next;
if (prev_index == -1) {
/* Node is head */
list->head = next_index;
} else {
tx->dqo.pending_packets[prev_index].next = next_index;
}
if (next_index == -1) {
/* Node is tail */
list->tail = prev_index;
} else {
tx->dqo.pending_packets[next_index].prev = prev_index;
}
}
static void gve_unmap_packet(struct device *dev,
struct gve_tx_pending_packet_dqo *pkt)
{
int i;
/* SKB linear portion is guaranteed to be mapped */
dma_unmap_single(dev, dma_unmap_addr(pkt, dma[0]),
dma_unmap_len(pkt, len[0]), DMA_TO_DEVICE);
for (i = 1; i < pkt->num_bufs; i++) {
dma_unmap_page(dev, dma_unmap_addr(pkt, dma[i]),
dma_unmap_len(pkt, len[i]), DMA_TO_DEVICE);
}
pkt->num_bufs = 0;
}
/* Completion types and expected behavior:
* No Miss compl + Packet compl = Packet completed normally.
* Miss compl + Re-inject compl = Packet completed normally.
* No Miss compl + Re-inject compl = Skipped i.e. packet not completed.
* Miss compl + Packet compl = Skipped i.e. packet not completed.
*/
static void gve_handle_packet_completion(struct gve_priv *priv,
struct gve_tx_ring *tx, bool is_napi,
u16 compl_tag, u64 *bytes, u64 *pkts,
bool is_reinjection)
{
struct gve_tx_pending_packet_dqo *pending_packet;
if (unlikely(compl_tag >= tx->dqo.num_pending_packets)) {
net_err_ratelimited("%s: Invalid TX completion tag: %d\n",
priv->dev->name, (int)compl_tag);
return;
}
pending_packet = &tx->dqo.pending_packets[compl_tag];
if (unlikely(is_reinjection)) {
if (unlikely(pending_packet->state ==
GVE_PACKET_STATE_TIMED_OUT_COMPL)) {
net_err_ratelimited("%s: Re-injection completion: %d received after timeout.\n",
priv->dev->name, (int)compl_tag);
/* Packet was already completed as a result of timeout,
* so just remove from list and free pending packet.
*/
remove_from_list(tx,
&tx->dqo_compl.timed_out_completions,
pending_packet);
gve_free_pending_packet(tx, pending_packet);
return;
}
if (unlikely(pending_packet->state !=
GVE_PACKET_STATE_PENDING_REINJECT_COMPL)) {
/* No outstanding miss completion but packet allocated
* implies packet receives a re-injection completion
* without a prior miss completion. Return without
* completing the packet.
*/
net_err_ratelimited("%s: Re-injection completion received without corresponding miss completion: %d\n",
priv->dev->name, (int)compl_tag);
return;
}
remove_from_list(tx, &tx->dqo_compl.miss_completions,
pending_packet);
} else {
/* Packet is allocated but not a pending data completion. */
if (unlikely(pending_packet->state !=
GVE_PACKET_STATE_PENDING_DATA_COMPL)) {
net_err_ratelimited("%s: No pending data completion: %d\n",
priv->dev->name, (int)compl_tag);
return;
}
}
tx->dqo_tx.completed_packet_desc_cnt += pending_packet->num_bufs;
if (tx->dqo.qpl)
gve_free_tx_qpl_bufs(tx, pending_packet);
else
gve_unmap_packet(tx->dev, pending_packet);
*bytes += pending_packet->skb->len;
(*pkts)++;
napi_consume_skb(pending_packet->skb, is_napi);
pending_packet->skb = NULL;
gve_free_pending_packet(tx, pending_packet);
}
static void gve_handle_miss_completion(struct gve_priv *priv,
struct gve_tx_ring *tx, u16 compl_tag,
u64 *bytes, u64 *pkts)
{
struct gve_tx_pending_packet_dqo *pending_packet;
if (unlikely(compl_tag >= tx->dqo.num_pending_packets)) {
net_err_ratelimited("%s: Invalid TX completion tag: %d\n",
priv->dev->name, (int)compl_tag);
return;
}
pending_packet = &tx->dqo.pending_packets[compl_tag];
if (unlikely(pending_packet->state !=
GVE_PACKET_STATE_PENDING_DATA_COMPL)) {
net_err_ratelimited("%s: Unexpected packet state: %d for completion tag : %d\n",
priv->dev->name, (int)pending_packet->state,
(int)compl_tag);
return;
}
pending_packet->state = GVE_PACKET_STATE_PENDING_REINJECT_COMPL;
/* jiffies can wraparound but time comparisons can handle overflows. */
pending_packet->timeout_jiffies =
jiffies +
msecs_to_jiffies(GVE_REINJECT_COMPL_TIMEOUT *
MSEC_PER_SEC);
add_to_list(tx, &tx->dqo_compl.miss_completions, pending_packet);
*bytes += pending_packet->skb->len;
(*pkts)++;
}
static void remove_miss_completions(struct gve_priv *priv,
struct gve_tx_ring *tx)
{
struct gve_tx_pending_packet_dqo *pending_packet;
s16 next_index;
next_index = tx->dqo_compl.miss_completions.head;
while (next_index != -1) {
pending_packet = &tx->dqo.pending_packets[next_index];
next_index = pending_packet->next;
/* Break early because packets should timeout in order. */
if (time_is_after_jiffies(pending_packet->timeout_jiffies))
break;
remove_from_list(tx, &tx->dqo_compl.miss_completions,
pending_packet);
/* Unmap/free TX buffers and free skb but do not unallocate packet i.e.
* the completion tag is not freed to ensure that the driver
* can take appropriate action if a corresponding valid
* completion is received later.
*/
if (tx->dqo.qpl)
gve_free_tx_qpl_bufs(tx, pending_packet);
else
gve_unmap_packet(tx->dev, pending_packet);
/* This indicates the packet was dropped. */
dev_kfree_skb_any(pending_packet->skb);
pending_packet->skb = NULL;
tx->dropped_pkt++;
net_err_ratelimited("%s: No reinjection completion was received for: %d.\n",
priv->dev->name,
(int)(pending_packet - tx->dqo.pending_packets));
pending_packet->state = GVE_PACKET_STATE_TIMED_OUT_COMPL;
pending_packet->timeout_jiffies =
jiffies +
msecs_to_jiffies(GVE_DEALLOCATE_COMPL_TIMEOUT *
MSEC_PER_SEC);
/* Maintain pending packet in another list so the packet can be
* unallocated at a later time.
*/
add_to_list(tx, &tx->dqo_compl.timed_out_completions,
pending_packet);
}
}
static void remove_timed_out_completions(struct gve_priv *priv,
struct gve_tx_ring *tx)
{
struct gve_tx_pending_packet_dqo *pending_packet;
s16 next_index;
next_index = tx->dqo_compl.timed_out_completions.head;
while (next_index != -1) {
pending_packet = &tx->dqo.pending_packets[next_index];
next_index = pending_packet->next;
/* Break early because packets should timeout in order. */
if (time_is_after_jiffies(pending_packet->timeout_jiffies))
break;
remove_from_list(tx, &tx->dqo_compl.timed_out_completions,
pending_packet);
gve_free_pending_packet(tx, pending_packet);
}
}
int gve_clean_tx_done_dqo(struct gve_priv *priv, struct gve_tx_ring *tx,
struct napi_struct *napi)
{
u64 reinject_compl_bytes = 0;
u64 reinject_compl_pkts = 0;
int num_descs_cleaned = 0;
u64 miss_compl_bytes = 0;
u64 miss_compl_pkts = 0;
u64 pkt_compl_bytes = 0;
u64 pkt_compl_pkts = 0;
/* Limit in order to avoid blocking for too long */
while (!napi || pkt_compl_pkts < napi->weight) {
struct gve_tx_compl_desc *compl_desc =
&tx->dqo.compl_ring[tx->dqo_compl.head];
u16 type;
if (compl_desc->generation == tx->dqo_compl.cur_gen_bit)
break;
/* Prefetch the next descriptor. */
prefetch(&tx->dqo.compl_ring[(tx->dqo_compl.head + 1) &
tx->dqo.complq_mask]);
/* Do not read data until we own the descriptor */
dma_rmb();
type = compl_desc->type;
if (type == GVE_COMPL_TYPE_DQO_DESC) {
/* This is the last descriptor fetched by HW plus one */
u16 tx_head = le16_to_cpu(compl_desc->tx_head);
atomic_set_release(&tx->dqo_compl.hw_tx_head, tx_head);
} else if (type == GVE_COMPL_TYPE_DQO_PKT) {
u16 compl_tag = le16_to_cpu(compl_desc->completion_tag);
if (compl_tag & GVE_ALT_MISS_COMPL_BIT) {
compl_tag &= ~GVE_ALT_MISS_COMPL_BIT;
gve_handle_miss_completion(priv, tx, compl_tag,
&miss_compl_bytes,
&miss_compl_pkts);
} else {
gve_handle_packet_completion(priv, tx, !!napi,
compl_tag,
&pkt_compl_bytes,
&pkt_compl_pkts,
false);
}
} else if (type == GVE_COMPL_TYPE_DQO_MISS) {
u16 compl_tag = le16_to_cpu(compl_desc->completion_tag);
gve_handle_miss_completion(priv, tx, compl_tag,
&miss_compl_bytes,
&miss_compl_pkts);
} else if (type == GVE_COMPL_TYPE_DQO_REINJECTION) {
u16 compl_tag = le16_to_cpu(compl_desc->completion_tag);
gve_handle_packet_completion(priv, tx, !!napi,
compl_tag,
&reinject_compl_bytes,
&reinject_compl_pkts,
true);
}
tx->dqo_compl.head =
(tx->dqo_compl.head + 1) & tx->dqo.complq_mask;
/* Flip the generation bit when we wrap around */
tx->dqo_compl.cur_gen_bit ^= tx->dqo_compl.head == 0;
num_descs_cleaned++;
}
netdev_tx_completed_queue(tx->netdev_txq,
pkt_compl_pkts + miss_compl_pkts,
pkt_compl_bytes + miss_compl_bytes);
remove_miss_completions(priv, tx);
remove_timed_out_completions(priv, tx);
u64_stats_update_begin(&tx->statss);
tx->bytes_done += pkt_compl_bytes + reinject_compl_bytes;
tx->pkt_done += pkt_compl_pkts + reinject_compl_pkts;
u64_stats_update_end(&tx->statss);
return num_descs_cleaned;
}
bool gve_tx_poll_dqo(struct gve_notify_block *block, bool do_clean)
{
struct gve_tx_compl_desc *compl_desc;
struct gve_tx_ring *tx = block->tx;
struct gve_priv *priv = block->priv;
if (do_clean) {
int num_descs_cleaned = gve_clean_tx_done_dqo(priv, tx,
&block->napi);
/* Sync with queue being stopped in `gve_maybe_stop_tx_dqo()` */
mb();
if (netif_tx_queue_stopped(tx->netdev_txq) &&
num_descs_cleaned > 0) {
tx->wake_queue++;
netif_tx_wake_queue(tx->netdev_txq);
}
}
/* Return true if we still have work. */
compl_desc = &tx->dqo.compl_ring[tx->dqo_compl.head];
return compl_desc->generation != tx->dqo_compl.cur_gen_bit;
}
|
linux-master
|
drivers/net/ethernet/google/gve/gve_tx_dqo.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright(c) 2015 EZchip Technologies.
*/
#include <linux/module.h>
#include <linux/etherdevice.h>
#include <linux/interrupt.h>
#include <linux/mod_devicetable.h>
#include <linux/of_net.h>
#include <linux/platform_device.h>
#include "nps_enet.h"
#define DRV_NAME "nps_mgt_enet"
static inline bool nps_enet_is_tx_pending(struct nps_enet_priv *priv)
{
u32 tx_ctrl_value = nps_enet_reg_get(priv, NPS_ENET_REG_TX_CTL);
u32 tx_ctrl_ct = (tx_ctrl_value & TX_CTL_CT_MASK) >> TX_CTL_CT_SHIFT;
return (!tx_ctrl_ct && priv->tx_skb);
}
static void nps_enet_clean_rx_fifo(struct net_device *ndev, u32 frame_len)
{
struct nps_enet_priv *priv = netdev_priv(ndev);
u32 i, len = DIV_ROUND_UP(frame_len, sizeof(u32));
/* Empty Rx FIFO buffer by reading all words */
for (i = 0; i < len; i++)
nps_enet_reg_get(priv, NPS_ENET_REG_RX_BUF);
}
static void nps_enet_read_rx_fifo(struct net_device *ndev,
unsigned char *dst, u32 length)
{
struct nps_enet_priv *priv = netdev_priv(ndev);
s32 i, last = length & (sizeof(u32) - 1);
u32 *reg = (u32 *)dst, len = length / sizeof(u32);
bool dst_is_aligned = IS_ALIGNED((unsigned long)dst, sizeof(u32));
/* In case dst is not aligned we need an intermediate buffer */
if (dst_is_aligned) {
ioread32_rep(priv->regs_base + NPS_ENET_REG_RX_BUF, reg, len);
reg += len;
} else { /* !dst_is_aligned */
for (i = 0; i < len; i++, reg++) {
u32 buf = nps_enet_reg_get(priv, NPS_ENET_REG_RX_BUF);
put_unaligned_be32(buf, reg);
}
}
/* copy last bytes (if any) */
if (last) {
u32 buf;
ioread32_rep(priv->regs_base + NPS_ENET_REG_RX_BUF, &buf, 1);
memcpy((u8 *)reg, &buf, last);
}
}
static u32 nps_enet_rx_handler(struct net_device *ndev)
{
u32 frame_len, err = 0;
u32 work_done = 0;
struct nps_enet_priv *priv = netdev_priv(ndev);
struct sk_buff *skb;
u32 rx_ctrl_value = nps_enet_reg_get(priv, NPS_ENET_REG_RX_CTL);
u32 rx_ctrl_cr = (rx_ctrl_value & RX_CTL_CR_MASK) >> RX_CTL_CR_SHIFT;
u32 rx_ctrl_er = (rx_ctrl_value & RX_CTL_ER_MASK) >> RX_CTL_ER_SHIFT;
u32 rx_ctrl_crc = (rx_ctrl_value & RX_CTL_CRC_MASK) >> RX_CTL_CRC_SHIFT;
frame_len = (rx_ctrl_value & RX_CTL_NR_MASK) >> RX_CTL_NR_SHIFT;
/* Check if we got RX */
if (!rx_ctrl_cr)
return work_done;
/* If we got here there is a work for us */
work_done++;
/* Check Rx error */
if (rx_ctrl_er) {
ndev->stats.rx_errors++;
err = 1;
}
/* Check Rx CRC error */
if (rx_ctrl_crc) {
ndev->stats.rx_crc_errors++;
ndev->stats.rx_dropped++;
err = 1;
}
/* Check Frame length Min 64b */
if (unlikely(frame_len < ETH_ZLEN)) {
ndev->stats.rx_length_errors++;
ndev->stats.rx_dropped++;
err = 1;
}
if (err)
goto rx_irq_clean;
/* Skb allocation */
skb = netdev_alloc_skb_ip_align(ndev, frame_len);
if (unlikely(!skb)) {
ndev->stats.rx_errors++;
ndev->stats.rx_dropped++;
goto rx_irq_clean;
}
/* Copy frame from Rx fifo into the skb */
nps_enet_read_rx_fifo(ndev, skb->data, frame_len);
skb_put(skb, frame_len);
skb->protocol = eth_type_trans(skb, ndev);
skb->ip_summed = CHECKSUM_UNNECESSARY;
ndev->stats.rx_packets++;
ndev->stats.rx_bytes += frame_len;
netif_receive_skb(skb);
goto rx_irq_frame_done;
rx_irq_clean:
/* Clean Rx fifo */
nps_enet_clean_rx_fifo(ndev, frame_len);
rx_irq_frame_done:
/* Ack Rx ctrl register */
nps_enet_reg_set(priv, NPS_ENET_REG_RX_CTL, 0);
return work_done;
}
static void nps_enet_tx_handler(struct net_device *ndev)
{
struct nps_enet_priv *priv = netdev_priv(ndev);
u32 tx_ctrl_value = nps_enet_reg_get(priv, NPS_ENET_REG_TX_CTL);
u32 tx_ctrl_et = (tx_ctrl_value & TX_CTL_ET_MASK) >> TX_CTL_ET_SHIFT;
u32 tx_ctrl_nt = (tx_ctrl_value & TX_CTL_NT_MASK) >> TX_CTL_NT_SHIFT;
/* Check if we got TX */
if (!nps_enet_is_tx_pending(priv))
return;
/* Ack Tx ctrl register */
nps_enet_reg_set(priv, NPS_ENET_REG_TX_CTL, 0);
/* Check Tx transmit error */
if (unlikely(tx_ctrl_et)) {
ndev->stats.tx_errors++;
} else {
ndev->stats.tx_packets++;
ndev->stats.tx_bytes += tx_ctrl_nt;
}
dev_kfree_skb(priv->tx_skb);
priv->tx_skb = NULL;
if (netif_queue_stopped(ndev))
netif_wake_queue(ndev);
}
/**
* nps_enet_poll - NAPI poll handler.
* @napi: Pointer to napi_struct structure.
* @budget: How many frames to process on one call.
*
* returns: Number of processed frames
*/
static int nps_enet_poll(struct napi_struct *napi, int budget)
{
struct net_device *ndev = napi->dev;
struct nps_enet_priv *priv = netdev_priv(ndev);
u32 work_done;
nps_enet_tx_handler(ndev);
work_done = nps_enet_rx_handler(ndev);
if ((work_done < budget) && napi_complete_done(napi, work_done)) {
u32 buf_int_enable_value = 0;
/* set tx_done and rx_rdy bits */
buf_int_enable_value |= NPS_ENET_ENABLE << RX_RDY_SHIFT;
buf_int_enable_value |= NPS_ENET_ENABLE << TX_DONE_SHIFT;
nps_enet_reg_set(priv, NPS_ENET_REG_BUF_INT_ENABLE,
buf_int_enable_value);
/* in case we will get a tx interrupt while interrupts
* are masked, we will lose it since the tx is edge interrupt.
* specifically, while executing the code section above,
* between nps_enet_tx_handler and the interrupts enable, all
* tx requests will be stuck until we will get an rx interrupt.
* the two code lines below will solve this situation by
* re-adding ourselves to the poll list.
*/
if (nps_enet_is_tx_pending(priv)) {
nps_enet_reg_set(priv, NPS_ENET_REG_BUF_INT_ENABLE, 0);
napi_reschedule(napi);
}
}
return work_done;
}
/**
* nps_enet_irq_handler - Global interrupt handler for ENET.
* @irq: irq number.
* @dev_instance: device instance.
*
* returns: IRQ_HANDLED for all cases.
*
* EZchip ENET has 2 interrupt causes, and depending on bits raised in
* CTRL registers we may tell what is a reason for interrupt to fire up.
* We got one for RX and the other for TX (completion).
*/
static irqreturn_t nps_enet_irq_handler(s32 irq, void *dev_instance)
{
struct net_device *ndev = dev_instance;
struct nps_enet_priv *priv = netdev_priv(ndev);
u32 rx_ctrl_value = nps_enet_reg_get(priv, NPS_ENET_REG_RX_CTL);
u32 rx_ctrl_cr = (rx_ctrl_value & RX_CTL_CR_MASK) >> RX_CTL_CR_SHIFT;
if (nps_enet_is_tx_pending(priv) || rx_ctrl_cr)
if (likely(napi_schedule_prep(&priv->napi))) {
nps_enet_reg_set(priv, NPS_ENET_REG_BUF_INT_ENABLE, 0);
__napi_schedule(&priv->napi);
}
return IRQ_HANDLED;
}
static void nps_enet_set_hw_mac_address(struct net_device *ndev)
{
struct nps_enet_priv *priv = netdev_priv(ndev);
u32 ge_mac_cfg_1_value = 0;
u32 *ge_mac_cfg_2_value = &priv->ge_mac_cfg_2_value;
/* set MAC address in HW */
ge_mac_cfg_1_value |= ndev->dev_addr[0] << CFG_1_OCTET_0_SHIFT;
ge_mac_cfg_1_value |= ndev->dev_addr[1] << CFG_1_OCTET_1_SHIFT;
ge_mac_cfg_1_value |= ndev->dev_addr[2] << CFG_1_OCTET_2_SHIFT;
ge_mac_cfg_1_value |= ndev->dev_addr[3] << CFG_1_OCTET_3_SHIFT;
*ge_mac_cfg_2_value = (*ge_mac_cfg_2_value & ~CFG_2_OCTET_4_MASK)
| ndev->dev_addr[4] << CFG_2_OCTET_4_SHIFT;
*ge_mac_cfg_2_value = (*ge_mac_cfg_2_value & ~CFG_2_OCTET_5_MASK)
| ndev->dev_addr[5] << CFG_2_OCTET_5_SHIFT;
nps_enet_reg_set(priv, NPS_ENET_REG_GE_MAC_CFG_1,
ge_mac_cfg_1_value);
nps_enet_reg_set(priv, NPS_ENET_REG_GE_MAC_CFG_2,
*ge_mac_cfg_2_value);
}
/**
* nps_enet_hw_reset - Reset the network device.
* @ndev: Pointer to the network device.
*
* This function reset the PCS and TX fifo.
* The programming model is to set the relevant reset bits
* wait for some time for this to propagate and then unset
* the reset bits. This way we ensure that reset procedure
* is done successfully by device.
*/
static void nps_enet_hw_reset(struct net_device *ndev)
{
struct nps_enet_priv *priv = netdev_priv(ndev);
u32 ge_rst_value = 0, phase_fifo_ctl_value = 0;
/* Pcs reset sequence*/
ge_rst_value |= NPS_ENET_ENABLE << RST_GMAC_0_SHIFT;
nps_enet_reg_set(priv, NPS_ENET_REG_GE_RST, ge_rst_value);
usleep_range(10, 20);
ge_rst_value = 0;
nps_enet_reg_set(priv, NPS_ENET_REG_GE_RST, ge_rst_value);
/* Tx fifo reset sequence */
phase_fifo_ctl_value |= NPS_ENET_ENABLE << PHASE_FIFO_CTL_RST_SHIFT;
phase_fifo_ctl_value |= NPS_ENET_ENABLE << PHASE_FIFO_CTL_INIT_SHIFT;
nps_enet_reg_set(priv, NPS_ENET_REG_PHASE_FIFO_CTL,
phase_fifo_ctl_value);
usleep_range(10, 20);
phase_fifo_ctl_value = 0;
nps_enet_reg_set(priv, NPS_ENET_REG_PHASE_FIFO_CTL,
phase_fifo_ctl_value);
}
static void nps_enet_hw_enable_control(struct net_device *ndev)
{
struct nps_enet_priv *priv = netdev_priv(ndev);
u32 ge_mac_cfg_0_value = 0, buf_int_enable_value = 0;
u32 *ge_mac_cfg_2_value = &priv->ge_mac_cfg_2_value;
u32 *ge_mac_cfg_3_value = &priv->ge_mac_cfg_3_value;
s32 max_frame_length;
/* Enable Rx and Tx statistics */
*ge_mac_cfg_2_value = (*ge_mac_cfg_2_value & ~CFG_2_STAT_EN_MASK)
| NPS_ENET_GE_MAC_CFG_2_STAT_EN << CFG_2_STAT_EN_SHIFT;
/* Discard packets with different MAC address */
*ge_mac_cfg_2_value = (*ge_mac_cfg_2_value & ~CFG_2_DISK_DA_MASK)
| NPS_ENET_ENABLE << CFG_2_DISK_DA_SHIFT;
/* Discard multicast packets */
*ge_mac_cfg_2_value = (*ge_mac_cfg_2_value & ~CFG_2_DISK_MC_MASK)
| NPS_ENET_ENABLE << CFG_2_DISK_MC_SHIFT;
nps_enet_reg_set(priv, NPS_ENET_REG_GE_MAC_CFG_2,
*ge_mac_cfg_2_value);
/* Discard Packets bigger than max frame length */
max_frame_length = ETH_HLEN + ndev->mtu + ETH_FCS_LEN;
if (max_frame_length <= NPS_ENET_MAX_FRAME_LENGTH) {
*ge_mac_cfg_3_value =
(*ge_mac_cfg_3_value & ~CFG_3_MAX_LEN_MASK)
| max_frame_length << CFG_3_MAX_LEN_SHIFT;
}
/* Enable interrupts */
buf_int_enable_value |= NPS_ENET_ENABLE << RX_RDY_SHIFT;
buf_int_enable_value |= NPS_ENET_ENABLE << TX_DONE_SHIFT;
nps_enet_reg_set(priv, NPS_ENET_REG_BUF_INT_ENABLE,
buf_int_enable_value);
/* Write device MAC address to HW */
nps_enet_set_hw_mac_address(ndev);
/* Rx and Tx HW features */
ge_mac_cfg_0_value |= NPS_ENET_ENABLE << CFG_0_TX_PAD_EN_SHIFT;
ge_mac_cfg_0_value |= NPS_ENET_ENABLE << CFG_0_TX_CRC_EN_SHIFT;
ge_mac_cfg_0_value |= NPS_ENET_ENABLE << CFG_0_RX_CRC_STRIP_SHIFT;
/* IFG configuration */
ge_mac_cfg_0_value |=
NPS_ENET_GE_MAC_CFG_0_RX_IFG << CFG_0_RX_IFG_SHIFT;
ge_mac_cfg_0_value |=
NPS_ENET_GE_MAC_CFG_0_TX_IFG << CFG_0_TX_IFG_SHIFT;
/* preamble configuration */
ge_mac_cfg_0_value |= NPS_ENET_ENABLE << CFG_0_RX_PR_CHECK_EN_SHIFT;
ge_mac_cfg_0_value |=
NPS_ENET_GE_MAC_CFG_0_TX_PR_LEN << CFG_0_TX_PR_LEN_SHIFT;
/* enable flow control frames */
ge_mac_cfg_0_value |= NPS_ENET_ENABLE << CFG_0_TX_FC_EN_SHIFT;
ge_mac_cfg_0_value |= NPS_ENET_ENABLE << CFG_0_RX_FC_EN_SHIFT;
ge_mac_cfg_0_value |=
NPS_ENET_GE_MAC_CFG_0_TX_FC_RETR << CFG_0_TX_FC_RETR_SHIFT;
*ge_mac_cfg_3_value = (*ge_mac_cfg_3_value & ~CFG_3_CF_DROP_MASK)
| NPS_ENET_ENABLE << CFG_3_CF_DROP_SHIFT;
/* Enable Rx and Tx */
ge_mac_cfg_0_value |= NPS_ENET_ENABLE << CFG_0_RX_EN_SHIFT;
ge_mac_cfg_0_value |= NPS_ENET_ENABLE << CFG_0_TX_EN_SHIFT;
nps_enet_reg_set(priv, NPS_ENET_REG_GE_MAC_CFG_3,
*ge_mac_cfg_3_value);
nps_enet_reg_set(priv, NPS_ENET_REG_GE_MAC_CFG_0,
ge_mac_cfg_0_value);
}
static void nps_enet_hw_disable_control(struct net_device *ndev)
{
struct nps_enet_priv *priv = netdev_priv(ndev);
/* Disable interrupts */
nps_enet_reg_set(priv, NPS_ENET_REG_BUF_INT_ENABLE, 0);
/* Disable Rx and Tx */
nps_enet_reg_set(priv, NPS_ENET_REG_GE_MAC_CFG_0, 0);
}
static void nps_enet_send_frame(struct net_device *ndev,
struct sk_buff *skb)
{
struct nps_enet_priv *priv = netdev_priv(ndev);
u32 tx_ctrl_value = 0;
short length = skb->len;
u32 i, len = DIV_ROUND_UP(length, sizeof(u32));
u32 *src = (void *)skb->data;
bool src_is_aligned = IS_ALIGNED((unsigned long)src, sizeof(u32));
/* In case src is not aligned we need an intermediate buffer */
if (src_is_aligned)
iowrite32_rep(priv->regs_base + NPS_ENET_REG_TX_BUF, src, len);
else /* !src_is_aligned */
for (i = 0; i < len; i++, src++)
nps_enet_reg_set(priv, NPS_ENET_REG_TX_BUF,
get_unaligned_be32(src));
/* Write the length of the Frame */
tx_ctrl_value |= length << TX_CTL_NT_SHIFT;
tx_ctrl_value |= NPS_ENET_ENABLE << TX_CTL_CT_SHIFT;
/* Send Frame */
nps_enet_reg_set(priv, NPS_ENET_REG_TX_CTL, tx_ctrl_value);
}
/**
* nps_enet_set_mac_address - Set the MAC address for this device.
* @ndev: Pointer to net_device structure.
* @p: 6 byte Address to be written as MAC address.
*
* This function copies the HW address from the sockaddr structure to the
* net_device structure and updates the address in HW.
*
* returns: -EBUSY if the net device is busy or 0 if the address is set
* successfully.
*/
static s32 nps_enet_set_mac_address(struct net_device *ndev, void *p)
{
struct sockaddr *addr = p;
s32 res;
if (netif_running(ndev))
return -EBUSY;
res = eth_mac_addr(ndev, p);
if (!res) {
eth_hw_addr_set(ndev, addr->sa_data);
nps_enet_set_hw_mac_address(ndev);
}
return res;
}
/**
* nps_enet_set_rx_mode - Change the receive filtering mode.
* @ndev: Pointer to the network device.
*
* This function enables/disables promiscuous mode
*/
static void nps_enet_set_rx_mode(struct net_device *ndev)
{
struct nps_enet_priv *priv = netdev_priv(ndev);
u32 ge_mac_cfg_2_value = priv->ge_mac_cfg_2_value;
if (ndev->flags & IFF_PROMISC) {
ge_mac_cfg_2_value = (ge_mac_cfg_2_value & ~CFG_2_DISK_DA_MASK)
| NPS_ENET_DISABLE << CFG_2_DISK_DA_SHIFT;
ge_mac_cfg_2_value = (ge_mac_cfg_2_value & ~CFG_2_DISK_MC_MASK)
| NPS_ENET_DISABLE << CFG_2_DISK_MC_SHIFT;
} else {
ge_mac_cfg_2_value = (ge_mac_cfg_2_value & ~CFG_2_DISK_DA_MASK)
| NPS_ENET_ENABLE << CFG_2_DISK_DA_SHIFT;
ge_mac_cfg_2_value = (ge_mac_cfg_2_value & ~CFG_2_DISK_MC_MASK)
| NPS_ENET_ENABLE << CFG_2_DISK_MC_SHIFT;
}
nps_enet_reg_set(priv, NPS_ENET_REG_GE_MAC_CFG_2, ge_mac_cfg_2_value);
}
/**
* nps_enet_open - Open the network device.
* @ndev: Pointer to the network device.
*
* returns: 0, on success or non-zero error value on failure.
*
* This function sets the MAC address, requests and enables an IRQ
* for the ENET device and starts the Tx queue.
*/
static s32 nps_enet_open(struct net_device *ndev)
{
struct nps_enet_priv *priv = netdev_priv(ndev);
s32 err;
/* Reset private variables */
priv->tx_skb = NULL;
priv->ge_mac_cfg_2_value = 0;
priv->ge_mac_cfg_3_value = 0;
/* ge_mac_cfg_3 default values */
priv->ge_mac_cfg_3_value |=
NPS_ENET_GE_MAC_CFG_3_RX_IFG_TH << CFG_3_RX_IFG_TH_SHIFT;
priv->ge_mac_cfg_3_value |=
NPS_ENET_GE_MAC_CFG_3_MAX_LEN << CFG_3_MAX_LEN_SHIFT;
/* Disable HW device */
nps_enet_hw_disable_control(ndev);
/* irq Rx allocation */
err = request_irq(priv->irq, nps_enet_irq_handler,
0, "enet-rx-tx", ndev);
if (err)
return err;
napi_enable(&priv->napi);
/* Enable HW device */
nps_enet_hw_reset(ndev);
nps_enet_hw_enable_control(ndev);
netif_start_queue(ndev);
return 0;
}
/**
* nps_enet_stop - Close the network device.
* @ndev: Pointer to the network device.
*
* This function stops the Tx queue, disables interrupts for the ENET device.
*/
static s32 nps_enet_stop(struct net_device *ndev)
{
struct nps_enet_priv *priv = netdev_priv(ndev);
napi_disable(&priv->napi);
netif_stop_queue(ndev);
nps_enet_hw_disable_control(ndev);
free_irq(priv->irq, ndev);
return 0;
}
/**
* nps_enet_start_xmit - Starts the data transmission.
* @skb: sk_buff pointer that contains data to be Transmitted.
* @ndev: Pointer to net_device structure.
*
* returns: NETDEV_TX_OK, on success
* NETDEV_TX_BUSY, if any of the descriptors are not free.
*
* This function is invoked from upper layers to initiate transmission.
*/
static netdev_tx_t nps_enet_start_xmit(struct sk_buff *skb,
struct net_device *ndev)
{
struct nps_enet_priv *priv = netdev_priv(ndev);
/* This driver handles one frame at a time */
netif_stop_queue(ndev);
priv->tx_skb = skb;
/* make sure tx_skb is actually written to the memory
* before the HW is informed and the IRQ is fired.
*/
wmb();
nps_enet_send_frame(ndev, skb);
return NETDEV_TX_OK;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void nps_enet_poll_controller(struct net_device *ndev)
{
disable_irq(ndev->irq);
nps_enet_irq_handler(ndev->irq, ndev);
enable_irq(ndev->irq);
}
#endif
static const struct net_device_ops nps_netdev_ops = {
.ndo_open = nps_enet_open,
.ndo_stop = nps_enet_stop,
.ndo_start_xmit = nps_enet_start_xmit,
.ndo_set_mac_address = nps_enet_set_mac_address,
.ndo_set_rx_mode = nps_enet_set_rx_mode,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = nps_enet_poll_controller,
#endif
};
static s32 nps_enet_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct net_device *ndev;
struct nps_enet_priv *priv;
s32 err = 0;
if (!dev->of_node)
return -ENODEV;
ndev = alloc_etherdev(sizeof(struct nps_enet_priv));
if (!ndev)
return -ENOMEM;
platform_set_drvdata(pdev, ndev);
SET_NETDEV_DEV(ndev, dev);
priv = netdev_priv(ndev);
/* The EZ NET specific entries in the device structure. */
ndev->netdev_ops = &nps_netdev_ops;
ndev->watchdog_timeo = (400 * HZ / 1000);
/* FIXME :: no multicast support yet */
ndev->flags &= ~IFF_MULTICAST;
priv->regs_base = devm_platform_ioremap_resource(pdev, 0);
if (IS_ERR(priv->regs_base)) {
err = PTR_ERR(priv->regs_base);
goto out_netdev;
}
dev_dbg(dev, "Registers base address is 0x%p\n", priv->regs_base);
/* set kernel MAC address to dev */
err = of_get_ethdev_address(dev->of_node, ndev);
if (err)
eth_hw_addr_random(ndev);
/* Get IRQ number */
priv->irq = platform_get_irq(pdev, 0);
if (priv->irq < 0) {
err = -ENODEV;
goto out_netdev;
}
netif_napi_add_weight(ndev, &priv->napi, nps_enet_poll,
NPS_ENET_NAPI_POLL_WEIGHT);
/* Register the driver. Should be the last thing in probe */
err = register_netdev(ndev);
if (err) {
dev_err(dev, "Failed to register ndev for %s, err = 0x%08x\n",
ndev->name, (s32)err);
goto out_netif_api;
}
dev_info(dev, "(rx/tx=%d)\n", priv->irq);
return 0;
out_netif_api:
netif_napi_del(&priv->napi);
out_netdev:
free_netdev(ndev);
return err;
}
static s32 nps_enet_remove(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct nps_enet_priv *priv = netdev_priv(ndev);
unregister_netdev(ndev);
netif_napi_del(&priv->napi);
free_netdev(ndev);
return 0;
}
static const struct of_device_id nps_enet_dt_ids[] = {
{ .compatible = "ezchip,nps-mgt-enet" },
{ /* Sentinel */ }
};
MODULE_DEVICE_TABLE(of, nps_enet_dt_ids);
static struct platform_driver nps_enet_driver = {
.probe = nps_enet_probe,
.remove = nps_enet_remove,
.driver = {
.name = DRV_NAME,
.of_match_table = nps_enet_dt_ids,
},
};
module_platform_driver(nps_enet_driver);
MODULE_AUTHOR("EZchip Semiconductor");
MODULE_LICENSE("GPL v2");
|
linux-master
|
drivers/net/ethernet/ezchip/nps_enet.c
|
// SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
/* Copyright (c) 2021, Microsoft Corporation. */
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/utsname.h>
#include <linux/version.h>
#include <net/mana/mana.h>
static u32 mana_gd_r32(struct gdma_context *g, u64 offset)
{
return readl(g->bar0_va + offset);
}
static u64 mana_gd_r64(struct gdma_context *g, u64 offset)
{
return readq(g->bar0_va + offset);
}
static void mana_gd_init_pf_regs(struct pci_dev *pdev)
{
struct gdma_context *gc = pci_get_drvdata(pdev);
void __iomem *sriov_base_va;
u64 sriov_base_off;
gc->db_page_size = mana_gd_r32(gc, GDMA_PF_REG_DB_PAGE_SIZE) & 0xFFFF;
gc->db_page_base = gc->bar0_va +
mana_gd_r64(gc, GDMA_PF_REG_DB_PAGE_OFF);
sriov_base_off = mana_gd_r64(gc, GDMA_SRIOV_REG_CFG_BASE_OFF);
sriov_base_va = gc->bar0_va + sriov_base_off;
gc->shm_base = sriov_base_va +
mana_gd_r64(gc, sriov_base_off + GDMA_PF_REG_SHM_OFF);
}
static void mana_gd_init_vf_regs(struct pci_dev *pdev)
{
struct gdma_context *gc = pci_get_drvdata(pdev);
gc->db_page_size = mana_gd_r32(gc, GDMA_REG_DB_PAGE_SIZE) & 0xFFFF;
gc->db_page_base = gc->bar0_va +
mana_gd_r64(gc, GDMA_REG_DB_PAGE_OFFSET);
gc->phys_db_page_base = gc->bar0_pa +
mana_gd_r64(gc, GDMA_REG_DB_PAGE_OFFSET);
gc->shm_base = gc->bar0_va + mana_gd_r64(gc, GDMA_REG_SHM_OFFSET);
}
static void mana_gd_init_registers(struct pci_dev *pdev)
{
struct gdma_context *gc = pci_get_drvdata(pdev);
if (gc->is_pf)
mana_gd_init_pf_regs(pdev);
else
mana_gd_init_vf_regs(pdev);
}
static int mana_gd_query_max_resources(struct pci_dev *pdev)
{
struct gdma_context *gc = pci_get_drvdata(pdev);
struct gdma_query_max_resources_resp resp = {};
struct gdma_general_req req = {};
int err;
mana_gd_init_req_hdr(&req.hdr, GDMA_QUERY_MAX_RESOURCES,
sizeof(req), sizeof(resp));
err = mana_gd_send_request(gc, sizeof(req), &req, sizeof(resp), &resp);
if (err || resp.hdr.status) {
dev_err(gc->dev, "Failed to query resource info: %d, 0x%x\n",
err, resp.hdr.status);
return err ? err : -EPROTO;
}
if (gc->num_msix_usable > resp.max_msix)
gc->num_msix_usable = resp.max_msix;
if (gc->num_msix_usable <= 1)
return -ENOSPC;
gc->max_num_queues = num_online_cpus();
if (gc->max_num_queues > MANA_MAX_NUM_QUEUES)
gc->max_num_queues = MANA_MAX_NUM_QUEUES;
if (gc->max_num_queues > resp.max_eq)
gc->max_num_queues = resp.max_eq;
if (gc->max_num_queues > resp.max_cq)
gc->max_num_queues = resp.max_cq;
if (gc->max_num_queues > resp.max_sq)
gc->max_num_queues = resp.max_sq;
if (gc->max_num_queues > resp.max_rq)
gc->max_num_queues = resp.max_rq;
/* The Hardware Channel (HWC) used 1 MSI-X */
if (gc->max_num_queues > gc->num_msix_usable - 1)
gc->max_num_queues = gc->num_msix_usable - 1;
return 0;
}
static int mana_gd_query_hwc_timeout(struct pci_dev *pdev, u32 *timeout_val)
{
struct gdma_context *gc = pci_get_drvdata(pdev);
struct gdma_query_hwc_timeout_resp resp = {};
struct gdma_query_hwc_timeout_req req = {};
int err;
mana_gd_init_req_hdr(&req.hdr, GDMA_QUERY_HWC_TIMEOUT,
sizeof(req), sizeof(resp));
req.timeout_ms = *timeout_val;
err = mana_gd_send_request(gc, sizeof(req), &req, sizeof(resp), &resp);
if (err || resp.hdr.status)
return err ? err : -EPROTO;
*timeout_val = resp.timeout_ms;
return 0;
}
static int mana_gd_detect_devices(struct pci_dev *pdev)
{
struct gdma_context *gc = pci_get_drvdata(pdev);
struct gdma_list_devices_resp resp = {};
struct gdma_general_req req = {};
struct gdma_dev_id dev;
u32 i, max_num_devs;
u16 dev_type;
int err;
mana_gd_init_req_hdr(&req.hdr, GDMA_LIST_DEVICES, sizeof(req),
sizeof(resp));
err = mana_gd_send_request(gc, sizeof(req), &req, sizeof(resp), &resp);
if (err || resp.hdr.status) {
dev_err(gc->dev, "Failed to detect devices: %d, 0x%x\n", err,
resp.hdr.status);
return err ? err : -EPROTO;
}
max_num_devs = min_t(u32, MAX_NUM_GDMA_DEVICES, resp.num_of_devs);
for (i = 0; i < max_num_devs; i++) {
dev = resp.devs[i];
dev_type = dev.type;
/* HWC is already detected in mana_hwc_create_channel(). */
if (dev_type == GDMA_DEVICE_HWC)
continue;
if (dev_type == GDMA_DEVICE_MANA) {
gc->mana.gdma_context = gc;
gc->mana.dev_id = dev;
}
}
return gc->mana.dev_id.type == 0 ? -ENODEV : 0;
}
int mana_gd_send_request(struct gdma_context *gc, u32 req_len, const void *req,
u32 resp_len, void *resp)
{
struct hw_channel_context *hwc = gc->hwc.driver_data;
return mana_hwc_send_request(hwc, req_len, req, resp_len, resp);
}
EXPORT_SYMBOL_NS(mana_gd_send_request, NET_MANA);
int mana_gd_alloc_memory(struct gdma_context *gc, unsigned int length,
struct gdma_mem_info *gmi)
{
dma_addr_t dma_handle;
void *buf;
if (length < PAGE_SIZE || !is_power_of_2(length))
return -EINVAL;
gmi->dev = gc->dev;
buf = dma_alloc_coherent(gmi->dev, length, &dma_handle, GFP_KERNEL);
if (!buf)
return -ENOMEM;
gmi->dma_handle = dma_handle;
gmi->virt_addr = buf;
gmi->length = length;
return 0;
}
void mana_gd_free_memory(struct gdma_mem_info *gmi)
{
dma_free_coherent(gmi->dev, gmi->length, gmi->virt_addr,
gmi->dma_handle);
}
static int mana_gd_create_hw_eq(struct gdma_context *gc,
struct gdma_queue *queue)
{
struct gdma_create_queue_resp resp = {};
struct gdma_create_queue_req req = {};
int err;
if (queue->type != GDMA_EQ)
return -EINVAL;
mana_gd_init_req_hdr(&req.hdr, GDMA_CREATE_QUEUE,
sizeof(req), sizeof(resp));
req.hdr.dev_id = queue->gdma_dev->dev_id;
req.type = queue->type;
req.pdid = queue->gdma_dev->pdid;
req.doolbell_id = queue->gdma_dev->doorbell;
req.gdma_region = queue->mem_info.dma_region_handle;
req.queue_size = queue->queue_size;
req.log2_throttle_limit = queue->eq.log2_throttle_limit;
req.eq_pci_msix_index = queue->eq.msix_index;
err = mana_gd_send_request(gc, sizeof(req), &req, sizeof(resp), &resp);
if (err || resp.hdr.status) {
dev_err(gc->dev, "Failed to create queue: %d, 0x%x\n", err,
resp.hdr.status);
return err ? err : -EPROTO;
}
queue->id = resp.queue_index;
queue->eq.disable_needed = true;
queue->mem_info.dma_region_handle = GDMA_INVALID_DMA_REGION;
return 0;
}
static int mana_gd_disable_queue(struct gdma_queue *queue)
{
struct gdma_context *gc = queue->gdma_dev->gdma_context;
struct gdma_disable_queue_req req = {};
struct gdma_general_resp resp = {};
int err;
WARN_ON(queue->type != GDMA_EQ);
mana_gd_init_req_hdr(&req.hdr, GDMA_DISABLE_QUEUE,
sizeof(req), sizeof(resp));
req.hdr.dev_id = queue->gdma_dev->dev_id;
req.type = queue->type;
req.queue_index = queue->id;
req.alloc_res_id_on_creation = 1;
err = mana_gd_send_request(gc, sizeof(req), &req, sizeof(resp), &resp);
if (err || resp.hdr.status) {
dev_err(gc->dev, "Failed to disable queue: %d, 0x%x\n", err,
resp.hdr.status);
return err ? err : -EPROTO;
}
return 0;
}
#define DOORBELL_OFFSET_SQ 0x0
#define DOORBELL_OFFSET_RQ 0x400
#define DOORBELL_OFFSET_CQ 0x800
#define DOORBELL_OFFSET_EQ 0xFF8
static void mana_gd_ring_doorbell(struct gdma_context *gc, u32 db_index,
enum gdma_queue_type q_type, u32 qid,
u32 tail_ptr, u8 num_req)
{
void __iomem *addr = gc->db_page_base + gc->db_page_size * db_index;
union gdma_doorbell_entry e = {};
switch (q_type) {
case GDMA_EQ:
e.eq.id = qid;
e.eq.tail_ptr = tail_ptr;
e.eq.arm = num_req;
addr += DOORBELL_OFFSET_EQ;
break;
case GDMA_CQ:
e.cq.id = qid;
e.cq.tail_ptr = tail_ptr;
e.cq.arm = num_req;
addr += DOORBELL_OFFSET_CQ;
break;
case GDMA_RQ:
e.rq.id = qid;
e.rq.tail_ptr = tail_ptr;
e.rq.wqe_cnt = num_req;
addr += DOORBELL_OFFSET_RQ;
break;
case GDMA_SQ:
e.sq.id = qid;
e.sq.tail_ptr = tail_ptr;
addr += DOORBELL_OFFSET_SQ;
break;
default:
WARN_ON(1);
return;
}
/* Ensure all writes are done before ring doorbell */
wmb();
writeq(e.as_uint64, addr);
}
void mana_gd_wq_ring_doorbell(struct gdma_context *gc, struct gdma_queue *queue)
{
/* Hardware Spec specifies that software client should set 0 for
* wqe_cnt for Receive Queues. This value is not used in Send Queues.
*/
mana_gd_ring_doorbell(gc, queue->gdma_dev->doorbell, queue->type,
queue->id, queue->head * GDMA_WQE_BU_SIZE, 0);
}
void mana_gd_ring_cq(struct gdma_queue *cq, u8 arm_bit)
{
struct gdma_context *gc = cq->gdma_dev->gdma_context;
u32 num_cqe = cq->queue_size / GDMA_CQE_SIZE;
u32 head = cq->head % (num_cqe << GDMA_CQE_OWNER_BITS);
mana_gd_ring_doorbell(gc, cq->gdma_dev->doorbell, cq->type, cq->id,
head, arm_bit);
}
static void mana_gd_process_eqe(struct gdma_queue *eq)
{
u32 head = eq->head % (eq->queue_size / GDMA_EQE_SIZE);
struct gdma_context *gc = eq->gdma_dev->gdma_context;
struct gdma_eqe *eq_eqe_ptr = eq->queue_mem_ptr;
union gdma_eqe_info eqe_info;
enum gdma_eqe_type type;
struct gdma_event event;
struct gdma_queue *cq;
struct gdma_eqe *eqe;
u32 cq_id;
eqe = &eq_eqe_ptr[head];
eqe_info.as_uint32 = eqe->eqe_info;
type = eqe_info.type;
switch (type) {
case GDMA_EQE_COMPLETION:
cq_id = eqe->details[0] & 0xFFFFFF;
if (WARN_ON_ONCE(cq_id >= gc->max_num_cqs))
break;
cq = gc->cq_table[cq_id];
if (WARN_ON_ONCE(!cq || cq->type != GDMA_CQ || cq->id != cq_id))
break;
if (cq->cq.callback)
cq->cq.callback(cq->cq.context, cq);
break;
case GDMA_EQE_TEST_EVENT:
gc->test_event_eq_id = eq->id;
complete(&gc->eq_test_event);
break;
case GDMA_EQE_HWC_INIT_EQ_ID_DB:
case GDMA_EQE_HWC_INIT_DATA:
case GDMA_EQE_HWC_INIT_DONE:
if (!eq->eq.callback)
break;
event.type = type;
memcpy(&event.details, &eqe->details, GDMA_EVENT_DATA_SIZE);
eq->eq.callback(eq->eq.context, eq, &event);
break;
default:
break;
}
}
static void mana_gd_process_eq_events(void *arg)
{
u32 owner_bits, new_bits, old_bits;
union gdma_eqe_info eqe_info;
struct gdma_eqe *eq_eqe_ptr;
struct gdma_queue *eq = arg;
struct gdma_context *gc;
struct gdma_eqe *eqe;
u32 head, num_eqe;
int i;
gc = eq->gdma_dev->gdma_context;
num_eqe = eq->queue_size / GDMA_EQE_SIZE;
eq_eqe_ptr = eq->queue_mem_ptr;
/* Process up to 5 EQEs at a time, and update the HW head. */
for (i = 0; i < 5; i++) {
eqe = &eq_eqe_ptr[eq->head % num_eqe];
eqe_info.as_uint32 = eqe->eqe_info;
owner_bits = eqe_info.owner_bits;
old_bits = (eq->head / num_eqe - 1) & GDMA_EQE_OWNER_MASK;
/* No more entries */
if (owner_bits == old_bits)
break;
new_bits = (eq->head / num_eqe) & GDMA_EQE_OWNER_MASK;
if (owner_bits != new_bits) {
dev_err(gc->dev, "EQ %d: overflow detected\n", eq->id);
break;
}
/* Per GDMA spec, rmb is necessary after checking owner_bits, before
* reading eqe.
*/
rmb();
mana_gd_process_eqe(eq);
eq->head++;
}
head = eq->head % (num_eqe << GDMA_EQE_OWNER_BITS);
mana_gd_ring_doorbell(gc, eq->gdma_dev->doorbell, eq->type, eq->id,
head, SET_ARM_BIT);
}
static int mana_gd_register_irq(struct gdma_queue *queue,
const struct gdma_queue_spec *spec)
{
struct gdma_dev *gd = queue->gdma_dev;
struct gdma_irq_context *gic;
struct gdma_context *gc;
struct gdma_resource *r;
unsigned int msi_index;
unsigned long flags;
struct device *dev;
int err = 0;
gc = gd->gdma_context;
r = &gc->msix_resource;
dev = gc->dev;
spin_lock_irqsave(&r->lock, flags);
msi_index = find_first_zero_bit(r->map, r->size);
if (msi_index >= r->size || msi_index >= gc->num_msix_usable) {
err = -ENOSPC;
} else {
bitmap_set(r->map, msi_index, 1);
queue->eq.msix_index = msi_index;
}
spin_unlock_irqrestore(&r->lock, flags);
if (err) {
dev_err(dev, "Register IRQ err:%d, msi:%u rsize:%u, nMSI:%u",
err, msi_index, r->size, gc->num_msix_usable);
return err;
}
gic = &gc->irq_contexts[msi_index];
WARN_ON(gic->handler || gic->arg);
gic->arg = queue;
gic->handler = mana_gd_process_eq_events;
return 0;
}
static void mana_gd_deregiser_irq(struct gdma_queue *queue)
{
struct gdma_dev *gd = queue->gdma_dev;
struct gdma_irq_context *gic;
struct gdma_context *gc;
struct gdma_resource *r;
unsigned int msix_index;
unsigned long flags;
gc = gd->gdma_context;
r = &gc->msix_resource;
/* At most num_online_cpus() + 1 interrupts are used. */
msix_index = queue->eq.msix_index;
if (WARN_ON(msix_index >= gc->num_msix_usable))
return;
gic = &gc->irq_contexts[msix_index];
gic->handler = NULL;
gic->arg = NULL;
spin_lock_irqsave(&r->lock, flags);
bitmap_clear(r->map, msix_index, 1);
spin_unlock_irqrestore(&r->lock, flags);
queue->eq.msix_index = INVALID_PCI_MSIX_INDEX;
}
int mana_gd_test_eq(struct gdma_context *gc, struct gdma_queue *eq)
{
struct gdma_generate_test_event_req req = {};
struct gdma_general_resp resp = {};
struct device *dev = gc->dev;
int err;
mutex_lock(&gc->eq_test_event_mutex);
init_completion(&gc->eq_test_event);
gc->test_event_eq_id = INVALID_QUEUE_ID;
mana_gd_init_req_hdr(&req.hdr, GDMA_GENERATE_TEST_EQE,
sizeof(req), sizeof(resp));
req.hdr.dev_id = eq->gdma_dev->dev_id;
req.queue_index = eq->id;
err = mana_gd_send_request(gc, sizeof(req), &req, sizeof(resp), &resp);
if (err) {
dev_err(dev, "test_eq failed: %d\n", err);
goto out;
}
err = -EPROTO;
if (resp.hdr.status) {
dev_err(dev, "test_eq failed: 0x%x\n", resp.hdr.status);
goto out;
}
if (!wait_for_completion_timeout(&gc->eq_test_event, 30 * HZ)) {
dev_err(dev, "test_eq timed out on queue %d\n", eq->id);
goto out;
}
if (eq->id != gc->test_event_eq_id) {
dev_err(dev, "test_eq got an event on wrong queue %d (%d)\n",
gc->test_event_eq_id, eq->id);
goto out;
}
err = 0;
out:
mutex_unlock(&gc->eq_test_event_mutex);
return err;
}
static void mana_gd_destroy_eq(struct gdma_context *gc, bool flush_evenets,
struct gdma_queue *queue)
{
int err;
if (flush_evenets) {
err = mana_gd_test_eq(gc, queue);
if (err)
dev_warn(gc->dev, "Failed to flush EQ: %d\n", err);
}
mana_gd_deregiser_irq(queue);
if (queue->eq.disable_needed)
mana_gd_disable_queue(queue);
}
static int mana_gd_create_eq(struct gdma_dev *gd,
const struct gdma_queue_spec *spec,
bool create_hwq, struct gdma_queue *queue)
{
struct gdma_context *gc = gd->gdma_context;
struct device *dev = gc->dev;
u32 log2_num_entries;
int err;
queue->eq.msix_index = INVALID_PCI_MSIX_INDEX;
log2_num_entries = ilog2(queue->queue_size / GDMA_EQE_SIZE);
if (spec->eq.log2_throttle_limit > log2_num_entries) {
dev_err(dev, "EQ throttling limit (%lu) > maximum EQE (%u)\n",
spec->eq.log2_throttle_limit, log2_num_entries);
return -EINVAL;
}
err = mana_gd_register_irq(queue, spec);
if (err) {
dev_err(dev, "Failed to register irq: %d\n", err);
return err;
}
queue->eq.callback = spec->eq.callback;
queue->eq.context = spec->eq.context;
queue->head |= INITIALIZED_OWNER_BIT(log2_num_entries);
queue->eq.log2_throttle_limit = spec->eq.log2_throttle_limit ?: 1;
if (create_hwq) {
err = mana_gd_create_hw_eq(gc, queue);
if (err)
goto out;
err = mana_gd_test_eq(gc, queue);
if (err)
goto out;
}
return 0;
out:
dev_err(dev, "Failed to create EQ: %d\n", err);
mana_gd_destroy_eq(gc, false, queue);
return err;
}
static void mana_gd_create_cq(const struct gdma_queue_spec *spec,
struct gdma_queue *queue)
{
u32 log2_num_entries = ilog2(spec->queue_size / GDMA_CQE_SIZE);
queue->head |= INITIALIZED_OWNER_BIT(log2_num_entries);
queue->cq.parent = spec->cq.parent_eq;
queue->cq.context = spec->cq.context;
queue->cq.callback = spec->cq.callback;
}
static void mana_gd_destroy_cq(struct gdma_context *gc,
struct gdma_queue *queue)
{
u32 id = queue->id;
if (id >= gc->max_num_cqs)
return;
if (!gc->cq_table[id])
return;
gc->cq_table[id] = NULL;
}
int mana_gd_create_hwc_queue(struct gdma_dev *gd,
const struct gdma_queue_spec *spec,
struct gdma_queue **queue_ptr)
{
struct gdma_context *gc = gd->gdma_context;
struct gdma_mem_info *gmi;
struct gdma_queue *queue;
int err;
queue = kzalloc(sizeof(*queue), GFP_KERNEL);
if (!queue)
return -ENOMEM;
gmi = &queue->mem_info;
err = mana_gd_alloc_memory(gc, spec->queue_size, gmi);
if (err)
goto free_q;
queue->head = 0;
queue->tail = 0;
queue->queue_mem_ptr = gmi->virt_addr;
queue->queue_size = spec->queue_size;
queue->monitor_avl_buf = spec->monitor_avl_buf;
queue->type = spec->type;
queue->gdma_dev = gd;
if (spec->type == GDMA_EQ)
err = mana_gd_create_eq(gd, spec, false, queue);
else if (spec->type == GDMA_CQ)
mana_gd_create_cq(spec, queue);
if (err)
goto out;
*queue_ptr = queue;
return 0;
out:
mana_gd_free_memory(gmi);
free_q:
kfree(queue);
return err;
}
int mana_gd_destroy_dma_region(struct gdma_context *gc, u64 dma_region_handle)
{
struct gdma_destroy_dma_region_req req = {};
struct gdma_general_resp resp = {};
int err;
if (dma_region_handle == GDMA_INVALID_DMA_REGION)
return 0;
mana_gd_init_req_hdr(&req.hdr, GDMA_DESTROY_DMA_REGION, sizeof(req),
sizeof(resp));
req.dma_region_handle = dma_region_handle;
err = mana_gd_send_request(gc, sizeof(req), &req, sizeof(resp), &resp);
if (err || resp.hdr.status) {
dev_err(gc->dev, "Failed to destroy DMA region: %d, 0x%x\n",
err, resp.hdr.status);
return -EPROTO;
}
return 0;
}
EXPORT_SYMBOL_NS(mana_gd_destroy_dma_region, NET_MANA);
static int mana_gd_create_dma_region(struct gdma_dev *gd,
struct gdma_mem_info *gmi)
{
unsigned int num_page = gmi->length / PAGE_SIZE;
struct gdma_create_dma_region_req *req = NULL;
struct gdma_create_dma_region_resp resp = {};
struct gdma_context *gc = gd->gdma_context;
struct hw_channel_context *hwc;
u32 length = gmi->length;
size_t req_msg_size;
int err;
int i;
if (length < PAGE_SIZE || !is_power_of_2(length))
return -EINVAL;
if (offset_in_page(gmi->virt_addr) != 0)
return -EINVAL;
hwc = gc->hwc.driver_data;
req_msg_size = struct_size(req, page_addr_list, num_page);
if (req_msg_size > hwc->max_req_msg_size)
return -EINVAL;
req = kzalloc(req_msg_size, GFP_KERNEL);
if (!req)
return -ENOMEM;
mana_gd_init_req_hdr(&req->hdr, GDMA_CREATE_DMA_REGION,
req_msg_size, sizeof(resp));
req->length = length;
req->offset_in_page = 0;
req->gdma_page_type = GDMA_PAGE_TYPE_4K;
req->page_count = num_page;
req->page_addr_list_len = num_page;
for (i = 0; i < num_page; i++)
req->page_addr_list[i] = gmi->dma_handle + i * PAGE_SIZE;
err = mana_gd_send_request(gc, req_msg_size, req, sizeof(resp), &resp);
if (err)
goto out;
if (resp.hdr.status ||
resp.dma_region_handle == GDMA_INVALID_DMA_REGION) {
dev_err(gc->dev, "Failed to create DMA region: 0x%x\n",
resp.hdr.status);
err = -EPROTO;
goto out;
}
gmi->dma_region_handle = resp.dma_region_handle;
out:
kfree(req);
return err;
}
int mana_gd_create_mana_eq(struct gdma_dev *gd,
const struct gdma_queue_spec *spec,
struct gdma_queue **queue_ptr)
{
struct gdma_context *gc = gd->gdma_context;
struct gdma_mem_info *gmi;
struct gdma_queue *queue;
int err;
if (spec->type != GDMA_EQ)
return -EINVAL;
queue = kzalloc(sizeof(*queue), GFP_KERNEL);
if (!queue)
return -ENOMEM;
gmi = &queue->mem_info;
err = mana_gd_alloc_memory(gc, spec->queue_size, gmi);
if (err)
goto free_q;
err = mana_gd_create_dma_region(gd, gmi);
if (err)
goto out;
queue->head = 0;
queue->tail = 0;
queue->queue_mem_ptr = gmi->virt_addr;
queue->queue_size = spec->queue_size;
queue->monitor_avl_buf = spec->monitor_avl_buf;
queue->type = spec->type;
queue->gdma_dev = gd;
err = mana_gd_create_eq(gd, spec, true, queue);
if (err)
goto out;
*queue_ptr = queue;
return 0;
out:
mana_gd_free_memory(gmi);
free_q:
kfree(queue);
return err;
}
int mana_gd_create_mana_wq_cq(struct gdma_dev *gd,
const struct gdma_queue_spec *spec,
struct gdma_queue **queue_ptr)
{
struct gdma_context *gc = gd->gdma_context;
struct gdma_mem_info *gmi;
struct gdma_queue *queue;
int err;
if (spec->type != GDMA_CQ && spec->type != GDMA_SQ &&
spec->type != GDMA_RQ)
return -EINVAL;
queue = kzalloc(sizeof(*queue), GFP_KERNEL);
if (!queue)
return -ENOMEM;
gmi = &queue->mem_info;
err = mana_gd_alloc_memory(gc, spec->queue_size, gmi);
if (err)
goto free_q;
err = mana_gd_create_dma_region(gd, gmi);
if (err)
goto out;
queue->head = 0;
queue->tail = 0;
queue->queue_mem_ptr = gmi->virt_addr;
queue->queue_size = spec->queue_size;
queue->monitor_avl_buf = spec->monitor_avl_buf;
queue->type = spec->type;
queue->gdma_dev = gd;
if (spec->type == GDMA_CQ)
mana_gd_create_cq(spec, queue);
*queue_ptr = queue;
return 0;
out:
mana_gd_free_memory(gmi);
free_q:
kfree(queue);
return err;
}
void mana_gd_destroy_queue(struct gdma_context *gc, struct gdma_queue *queue)
{
struct gdma_mem_info *gmi = &queue->mem_info;
switch (queue->type) {
case GDMA_EQ:
mana_gd_destroy_eq(gc, queue->eq.disable_needed, queue);
break;
case GDMA_CQ:
mana_gd_destroy_cq(gc, queue);
break;
case GDMA_RQ:
break;
case GDMA_SQ:
break;
default:
dev_err(gc->dev, "Can't destroy unknown queue: type=%d\n",
queue->type);
return;
}
mana_gd_destroy_dma_region(gc, gmi->dma_region_handle);
mana_gd_free_memory(gmi);
kfree(queue);
}
int mana_gd_verify_vf_version(struct pci_dev *pdev)
{
struct gdma_context *gc = pci_get_drvdata(pdev);
struct gdma_verify_ver_resp resp = {};
struct gdma_verify_ver_req req = {};
struct hw_channel_context *hwc;
int err;
hwc = gc->hwc.driver_data;
mana_gd_init_req_hdr(&req.hdr, GDMA_VERIFY_VF_DRIVER_VERSION,
sizeof(req), sizeof(resp));
req.protocol_ver_min = GDMA_PROTOCOL_FIRST;
req.protocol_ver_max = GDMA_PROTOCOL_LAST;
req.gd_drv_cap_flags1 = GDMA_DRV_CAP_FLAGS1;
req.gd_drv_cap_flags2 = GDMA_DRV_CAP_FLAGS2;
req.gd_drv_cap_flags3 = GDMA_DRV_CAP_FLAGS3;
req.gd_drv_cap_flags4 = GDMA_DRV_CAP_FLAGS4;
req.drv_ver = 0; /* Unused*/
req.os_type = 0x10; /* Linux */
req.os_ver_major = LINUX_VERSION_MAJOR;
req.os_ver_minor = LINUX_VERSION_PATCHLEVEL;
req.os_ver_build = LINUX_VERSION_SUBLEVEL;
strscpy(req.os_ver_str1, utsname()->sysname, sizeof(req.os_ver_str1));
strscpy(req.os_ver_str2, utsname()->release, sizeof(req.os_ver_str2));
strscpy(req.os_ver_str3, utsname()->version, sizeof(req.os_ver_str3));
err = mana_gd_send_request(gc, sizeof(req), &req, sizeof(resp), &resp);
if (err || resp.hdr.status) {
dev_err(gc->dev, "VfVerifyVersionOutput: %d, status=0x%x\n",
err, resp.hdr.status);
return err ? err : -EPROTO;
}
if (resp.pf_cap_flags1 & GDMA_DRV_CAP_FLAG_1_HWC_TIMEOUT_RECONFIG) {
err = mana_gd_query_hwc_timeout(pdev, &hwc->hwc_timeout);
if (err) {
dev_err(gc->dev, "Failed to set the hwc timeout %d\n", err);
return err;
}
dev_dbg(gc->dev, "set the hwc timeout to %u\n", hwc->hwc_timeout);
}
return 0;
}
int mana_gd_register_device(struct gdma_dev *gd)
{
struct gdma_context *gc = gd->gdma_context;
struct gdma_register_device_resp resp = {};
struct gdma_general_req req = {};
int err;
gd->pdid = INVALID_PDID;
gd->doorbell = INVALID_DOORBELL;
gd->gpa_mkey = INVALID_MEM_KEY;
mana_gd_init_req_hdr(&req.hdr, GDMA_REGISTER_DEVICE, sizeof(req),
sizeof(resp));
req.hdr.dev_id = gd->dev_id;
err = mana_gd_send_request(gc, sizeof(req), &req, sizeof(resp), &resp);
if (err || resp.hdr.status) {
dev_err(gc->dev, "gdma_register_device_resp failed: %d, 0x%x\n",
err, resp.hdr.status);
return err ? err : -EPROTO;
}
gd->pdid = resp.pdid;
gd->gpa_mkey = resp.gpa_mkey;
gd->doorbell = resp.db_id;
return 0;
}
int mana_gd_deregister_device(struct gdma_dev *gd)
{
struct gdma_context *gc = gd->gdma_context;
struct gdma_general_resp resp = {};
struct gdma_general_req req = {};
int err;
if (gd->pdid == INVALID_PDID)
return -EINVAL;
mana_gd_init_req_hdr(&req.hdr, GDMA_DEREGISTER_DEVICE, sizeof(req),
sizeof(resp));
req.hdr.dev_id = gd->dev_id;
err = mana_gd_send_request(gc, sizeof(req), &req, sizeof(resp), &resp);
if (err || resp.hdr.status) {
dev_err(gc->dev, "Failed to deregister device: %d, 0x%x\n",
err, resp.hdr.status);
if (!err)
err = -EPROTO;
}
gd->pdid = INVALID_PDID;
gd->doorbell = INVALID_DOORBELL;
gd->gpa_mkey = INVALID_MEM_KEY;
return err;
}
u32 mana_gd_wq_avail_space(struct gdma_queue *wq)
{
u32 used_space = (wq->head - wq->tail) * GDMA_WQE_BU_SIZE;
u32 wq_size = wq->queue_size;
WARN_ON_ONCE(used_space > wq_size);
return wq_size - used_space;
}
u8 *mana_gd_get_wqe_ptr(const struct gdma_queue *wq, u32 wqe_offset)
{
u32 offset = (wqe_offset * GDMA_WQE_BU_SIZE) & (wq->queue_size - 1);
WARN_ON_ONCE((offset + GDMA_WQE_BU_SIZE) > wq->queue_size);
return wq->queue_mem_ptr + offset;
}
static u32 mana_gd_write_client_oob(const struct gdma_wqe_request *wqe_req,
enum gdma_queue_type q_type,
u32 client_oob_size, u32 sgl_data_size,
u8 *wqe_ptr)
{
bool oob_in_sgl = !!(wqe_req->flags & GDMA_WR_OOB_IN_SGL);
bool pad_data = !!(wqe_req->flags & GDMA_WR_PAD_BY_SGE0);
struct gdma_wqe *header = (struct gdma_wqe *)wqe_ptr;
u8 *ptr;
memset(header, 0, sizeof(struct gdma_wqe));
header->num_sge = wqe_req->num_sge;
header->inline_oob_size_div4 = client_oob_size / sizeof(u32);
if (oob_in_sgl) {
WARN_ON_ONCE(!pad_data || wqe_req->num_sge < 2);
header->client_oob_in_sgl = 1;
if (pad_data)
header->last_vbytes = wqe_req->sgl[0].size;
}
if (q_type == GDMA_SQ)
header->client_data_unit = wqe_req->client_data_unit;
/* The size of gdma_wqe + client_oob_size must be less than or equal
* to one Basic Unit (i.e. 32 bytes), so the pointer can't go beyond
* the queue memory buffer boundary.
*/
ptr = wqe_ptr + sizeof(header);
if (wqe_req->inline_oob_data && wqe_req->inline_oob_size > 0) {
memcpy(ptr, wqe_req->inline_oob_data, wqe_req->inline_oob_size);
if (client_oob_size > wqe_req->inline_oob_size)
memset(ptr + wqe_req->inline_oob_size, 0,
client_oob_size - wqe_req->inline_oob_size);
}
return sizeof(header) + client_oob_size;
}
static void mana_gd_write_sgl(struct gdma_queue *wq, u8 *wqe_ptr,
const struct gdma_wqe_request *wqe_req)
{
u32 sgl_size = sizeof(struct gdma_sge) * wqe_req->num_sge;
const u8 *address = (u8 *)wqe_req->sgl;
u8 *base_ptr, *end_ptr;
u32 size_to_end;
base_ptr = wq->queue_mem_ptr;
end_ptr = base_ptr + wq->queue_size;
size_to_end = (u32)(end_ptr - wqe_ptr);
if (size_to_end < sgl_size) {
memcpy(wqe_ptr, address, size_to_end);
wqe_ptr = base_ptr;
address += size_to_end;
sgl_size -= size_to_end;
}
memcpy(wqe_ptr, address, sgl_size);
}
int mana_gd_post_work_request(struct gdma_queue *wq,
const struct gdma_wqe_request *wqe_req,
struct gdma_posted_wqe_info *wqe_info)
{
u32 client_oob_size = wqe_req->inline_oob_size;
struct gdma_context *gc;
u32 sgl_data_size;
u32 max_wqe_size;
u32 wqe_size;
u8 *wqe_ptr;
if (wqe_req->num_sge == 0)
return -EINVAL;
if (wq->type == GDMA_RQ) {
if (client_oob_size != 0)
return -EINVAL;
client_oob_size = INLINE_OOB_SMALL_SIZE;
max_wqe_size = GDMA_MAX_RQE_SIZE;
} else {
if (client_oob_size != INLINE_OOB_SMALL_SIZE &&
client_oob_size != INLINE_OOB_LARGE_SIZE)
return -EINVAL;
max_wqe_size = GDMA_MAX_SQE_SIZE;
}
sgl_data_size = sizeof(struct gdma_sge) * wqe_req->num_sge;
wqe_size = ALIGN(sizeof(struct gdma_wqe) + client_oob_size +
sgl_data_size, GDMA_WQE_BU_SIZE);
if (wqe_size > max_wqe_size)
return -EINVAL;
if (wq->monitor_avl_buf && wqe_size > mana_gd_wq_avail_space(wq)) {
gc = wq->gdma_dev->gdma_context;
dev_err(gc->dev, "unsuccessful flow control!\n");
return -ENOSPC;
}
if (wqe_info)
wqe_info->wqe_size_in_bu = wqe_size / GDMA_WQE_BU_SIZE;
wqe_ptr = mana_gd_get_wqe_ptr(wq, wq->head);
wqe_ptr += mana_gd_write_client_oob(wqe_req, wq->type, client_oob_size,
sgl_data_size, wqe_ptr);
if (wqe_ptr >= (u8 *)wq->queue_mem_ptr + wq->queue_size)
wqe_ptr -= wq->queue_size;
mana_gd_write_sgl(wq, wqe_ptr, wqe_req);
wq->head += wqe_size / GDMA_WQE_BU_SIZE;
return 0;
}
int mana_gd_post_and_ring(struct gdma_queue *queue,
const struct gdma_wqe_request *wqe_req,
struct gdma_posted_wqe_info *wqe_info)
{
struct gdma_context *gc = queue->gdma_dev->gdma_context;
int err;
err = mana_gd_post_work_request(queue, wqe_req, wqe_info);
if (err)
return err;
mana_gd_wq_ring_doorbell(gc, queue);
return 0;
}
static int mana_gd_read_cqe(struct gdma_queue *cq, struct gdma_comp *comp)
{
unsigned int num_cqe = cq->queue_size / sizeof(struct gdma_cqe);
struct gdma_cqe *cq_cqe = cq->queue_mem_ptr;
u32 owner_bits, new_bits, old_bits;
struct gdma_cqe *cqe;
cqe = &cq_cqe[cq->head % num_cqe];
owner_bits = cqe->cqe_info.owner_bits;
old_bits = (cq->head / num_cqe - 1) & GDMA_CQE_OWNER_MASK;
/* Return 0 if no more entries. */
if (owner_bits == old_bits)
return 0;
new_bits = (cq->head / num_cqe) & GDMA_CQE_OWNER_MASK;
/* Return -1 if overflow detected. */
if (WARN_ON_ONCE(owner_bits != new_bits))
return -1;
/* Per GDMA spec, rmb is necessary after checking owner_bits, before
* reading completion info
*/
rmb();
comp->wq_num = cqe->cqe_info.wq_num;
comp->is_sq = cqe->cqe_info.is_sq;
memcpy(comp->cqe_data, cqe->cqe_data, GDMA_COMP_DATA_SIZE);
return 1;
}
int mana_gd_poll_cq(struct gdma_queue *cq, struct gdma_comp *comp, int num_cqe)
{
int cqe_idx;
int ret;
for (cqe_idx = 0; cqe_idx < num_cqe; cqe_idx++) {
ret = mana_gd_read_cqe(cq, &comp[cqe_idx]);
if (ret < 0) {
cq->head -= cqe_idx;
return ret;
}
if (ret == 0)
break;
cq->head++;
}
return cqe_idx;
}
static irqreturn_t mana_gd_intr(int irq, void *arg)
{
struct gdma_irq_context *gic = arg;
if (gic->handler)
gic->handler(gic->arg);
return IRQ_HANDLED;
}
int mana_gd_alloc_res_map(u32 res_avail, struct gdma_resource *r)
{
r->map = bitmap_zalloc(res_avail, GFP_KERNEL);
if (!r->map)
return -ENOMEM;
r->size = res_avail;
spin_lock_init(&r->lock);
return 0;
}
void mana_gd_free_res_map(struct gdma_resource *r)
{
bitmap_free(r->map);
r->map = NULL;
r->size = 0;
}
static int mana_gd_setup_irqs(struct pci_dev *pdev)
{
unsigned int max_queues_per_port = num_online_cpus();
struct gdma_context *gc = pci_get_drvdata(pdev);
struct gdma_irq_context *gic;
unsigned int max_irqs, cpu;
int nvec, irq;
int err, i = 0, j;
if (max_queues_per_port > MANA_MAX_NUM_QUEUES)
max_queues_per_port = MANA_MAX_NUM_QUEUES;
/* Need 1 interrupt for the Hardware communication Channel (HWC) */
max_irqs = max_queues_per_port + 1;
nvec = pci_alloc_irq_vectors(pdev, 2, max_irqs, PCI_IRQ_MSIX);
if (nvec < 0)
return nvec;
gc->irq_contexts = kcalloc(nvec, sizeof(struct gdma_irq_context),
GFP_KERNEL);
if (!gc->irq_contexts) {
err = -ENOMEM;
goto free_irq_vector;
}
for (i = 0; i < nvec; i++) {
gic = &gc->irq_contexts[i];
gic->handler = NULL;
gic->arg = NULL;
if (!i)
snprintf(gic->name, MANA_IRQ_NAME_SZ, "mana_hwc@pci:%s",
pci_name(pdev));
else
snprintf(gic->name, MANA_IRQ_NAME_SZ, "mana_q%d@pci:%s",
i - 1, pci_name(pdev));
irq = pci_irq_vector(pdev, i);
if (irq < 0) {
err = irq;
goto free_irq;
}
err = request_irq(irq, mana_gd_intr, 0, gic->name, gic);
if (err)
goto free_irq;
cpu = cpumask_local_spread(i, gc->numa_node);
irq_set_affinity_and_hint(irq, cpumask_of(cpu));
}
err = mana_gd_alloc_res_map(nvec, &gc->msix_resource);
if (err)
goto free_irq;
gc->max_num_msix = nvec;
gc->num_msix_usable = nvec;
return 0;
free_irq:
for (j = i - 1; j >= 0; j--) {
irq = pci_irq_vector(pdev, j);
gic = &gc->irq_contexts[j];
irq_update_affinity_hint(irq, NULL);
free_irq(irq, gic);
}
kfree(gc->irq_contexts);
gc->irq_contexts = NULL;
free_irq_vector:
pci_free_irq_vectors(pdev);
return err;
}
static void mana_gd_remove_irqs(struct pci_dev *pdev)
{
struct gdma_context *gc = pci_get_drvdata(pdev);
struct gdma_irq_context *gic;
int irq, i;
if (gc->max_num_msix < 1)
return;
mana_gd_free_res_map(&gc->msix_resource);
for (i = 0; i < gc->max_num_msix; i++) {
irq = pci_irq_vector(pdev, i);
if (irq < 0)
continue;
gic = &gc->irq_contexts[i];
/* Need to clear the hint before free_irq */
irq_update_affinity_hint(irq, NULL);
free_irq(irq, gic);
}
pci_free_irq_vectors(pdev);
gc->max_num_msix = 0;
gc->num_msix_usable = 0;
kfree(gc->irq_contexts);
gc->irq_contexts = NULL;
}
static int mana_gd_setup(struct pci_dev *pdev)
{
struct gdma_context *gc = pci_get_drvdata(pdev);
int err;
mana_gd_init_registers(pdev);
mana_smc_init(&gc->shm_channel, gc->dev, gc->shm_base);
err = mana_gd_setup_irqs(pdev);
if (err)
return err;
err = mana_hwc_create_channel(gc);
if (err)
goto remove_irq;
err = mana_gd_verify_vf_version(pdev);
if (err)
goto destroy_hwc;
err = mana_gd_query_max_resources(pdev);
if (err)
goto destroy_hwc;
err = mana_gd_detect_devices(pdev);
if (err)
goto destroy_hwc;
return 0;
destroy_hwc:
mana_hwc_destroy_channel(gc);
remove_irq:
mana_gd_remove_irqs(pdev);
return err;
}
static void mana_gd_cleanup(struct pci_dev *pdev)
{
struct gdma_context *gc = pci_get_drvdata(pdev);
mana_hwc_destroy_channel(gc);
mana_gd_remove_irqs(pdev);
}
static bool mana_is_pf(unsigned short dev_id)
{
return dev_id == MANA_PF_DEVICE_ID;
}
static int mana_gd_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
struct gdma_context *gc;
void __iomem *bar0_va;
int bar = 0;
int err;
/* Each port has 2 CQs, each CQ has at most 1 EQE at a time */
BUILD_BUG_ON(2 * MAX_PORTS_IN_MANA_DEV * GDMA_EQE_SIZE > EQ_SIZE);
err = pci_enable_device(pdev);
if (err)
return -ENXIO;
pci_set_master(pdev);
err = pci_request_regions(pdev, "mana");
if (err)
goto disable_dev;
err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
if (err)
goto release_region;
err = dma_set_max_seg_size(&pdev->dev, UINT_MAX);
if (err) {
dev_err(&pdev->dev, "Failed to set dma device segment size\n");
goto release_region;
}
err = -ENOMEM;
gc = vzalloc(sizeof(*gc));
if (!gc)
goto release_region;
mutex_init(&gc->eq_test_event_mutex);
pci_set_drvdata(pdev, gc);
gc->bar0_pa = pci_resource_start(pdev, 0);
bar0_va = pci_iomap(pdev, bar, 0);
if (!bar0_va)
goto free_gc;
gc->numa_node = dev_to_node(&pdev->dev);
gc->is_pf = mana_is_pf(pdev->device);
gc->bar0_va = bar0_va;
gc->dev = &pdev->dev;
err = mana_gd_setup(pdev);
if (err)
goto unmap_bar;
err = mana_probe(&gc->mana, false);
if (err)
goto cleanup_gd;
return 0;
cleanup_gd:
mana_gd_cleanup(pdev);
unmap_bar:
pci_iounmap(pdev, bar0_va);
free_gc:
pci_set_drvdata(pdev, NULL);
vfree(gc);
release_region:
pci_release_regions(pdev);
disable_dev:
pci_disable_device(pdev);
dev_err(&pdev->dev, "gdma probe failed: err = %d\n", err);
return err;
}
static void mana_gd_remove(struct pci_dev *pdev)
{
struct gdma_context *gc = pci_get_drvdata(pdev);
mana_remove(&gc->mana, false);
mana_gd_cleanup(pdev);
pci_iounmap(pdev, gc->bar0_va);
vfree(gc);
pci_release_regions(pdev);
pci_disable_device(pdev);
}
/* The 'state' parameter is not used. */
static int mana_gd_suspend(struct pci_dev *pdev, pm_message_t state)
{
struct gdma_context *gc = pci_get_drvdata(pdev);
mana_remove(&gc->mana, true);
mana_gd_cleanup(pdev);
return 0;
}
/* In case the NIC hardware stops working, the suspend and resume callbacks will
* fail -- if this happens, it's safer to just report an error than try to undo
* what has been done.
*/
static int mana_gd_resume(struct pci_dev *pdev)
{
struct gdma_context *gc = pci_get_drvdata(pdev);
int err;
err = mana_gd_setup(pdev);
if (err)
return err;
err = mana_probe(&gc->mana, true);
if (err)
return err;
return 0;
}
/* Quiesce the device for kexec. This is also called upon reboot/shutdown. */
static void mana_gd_shutdown(struct pci_dev *pdev)
{
struct gdma_context *gc = pci_get_drvdata(pdev);
dev_info(&pdev->dev, "Shutdown was called\n");
mana_remove(&gc->mana, true);
mana_gd_cleanup(pdev);
pci_disable_device(pdev);
}
static const struct pci_device_id mana_id_table[] = {
{ PCI_DEVICE(PCI_VENDOR_ID_MICROSOFT, MANA_PF_DEVICE_ID) },
{ PCI_DEVICE(PCI_VENDOR_ID_MICROSOFT, MANA_VF_DEVICE_ID) },
{ }
};
static struct pci_driver mana_driver = {
.name = "mana",
.id_table = mana_id_table,
.probe = mana_gd_probe,
.remove = mana_gd_remove,
.suspend = mana_gd_suspend,
.resume = mana_gd_resume,
.shutdown = mana_gd_shutdown,
};
module_pci_driver(mana_driver);
MODULE_DEVICE_TABLE(pci, mana_id_table);
MODULE_LICENSE("Dual BSD/GPL");
MODULE_DESCRIPTION("Microsoft Azure Network Adapter driver");
|
linux-master
|
drivers/net/ethernet/microsoft/mana/gdma_main.c
|
// SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
/* Copyright (c) 2021, Microsoft Corporation. */
#include <uapi/linux/bpf.h>
#include <linux/inetdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/filter.h>
#include <linux/mm.h>
#include <linux/pci.h>
#include <net/checksum.h>
#include <net/ip6_checksum.h>
#include <net/page_pool/helpers.h>
#include <net/xdp.h>
#include <net/mana/mana.h>
#include <net/mana/mana_auxiliary.h>
static DEFINE_IDA(mana_adev_ida);
static int mana_adev_idx_alloc(void)
{
return ida_alloc(&mana_adev_ida, GFP_KERNEL);
}
static void mana_adev_idx_free(int idx)
{
ida_free(&mana_adev_ida, idx);
}
/* Microsoft Azure Network Adapter (MANA) functions */
static int mana_open(struct net_device *ndev)
{
struct mana_port_context *apc = netdev_priv(ndev);
int err;
err = mana_alloc_queues(ndev);
if (err)
return err;
apc->port_is_up = true;
/* Ensure port state updated before txq state */
smp_wmb();
netif_carrier_on(ndev);
netif_tx_wake_all_queues(ndev);
return 0;
}
static int mana_close(struct net_device *ndev)
{
struct mana_port_context *apc = netdev_priv(ndev);
if (!apc->port_is_up)
return 0;
return mana_detach(ndev, true);
}
static bool mana_can_tx(struct gdma_queue *wq)
{
return mana_gd_wq_avail_space(wq) >= MAX_TX_WQE_SIZE;
}
static unsigned int mana_checksum_info(struct sk_buff *skb)
{
if (skb->protocol == htons(ETH_P_IP)) {
struct iphdr *ip = ip_hdr(skb);
if (ip->protocol == IPPROTO_TCP)
return IPPROTO_TCP;
if (ip->protocol == IPPROTO_UDP)
return IPPROTO_UDP;
} else if (skb->protocol == htons(ETH_P_IPV6)) {
struct ipv6hdr *ip6 = ipv6_hdr(skb);
if (ip6->nexthdr == IPPROTO_TCP)
return IPPROTO_TCP;
if (ip6->nexthdr == IPPROTO_UDP)
return IPPROTO_UDP;
}
/* No csum offloading */
return 0;
}
static int mana_map_skb(struct sk_buff *skb, struct mana_port_context *apc,
struct mana_tx_package *tp)
{
struct mana_skb_head *ash = (struct mana_skb_head *)skb->head;
struct gdma_dev *gd = apc->ac->gdma_dev;
struct gdma_context *gc;
struct device *dev;
skb_frag_t *frag;
dma_addr_t da;
int i;
gc = gd->gdma_context;
dev = gc->dev;
da = dma_map_single(dev, skb->data, skb_headlen(skb), DMA_TO_DEVICE);
if (dma_mapping_error(dev, da))
return -ENOMEM;
ash->dma_handle[0] = da;
ash->size[0] = skb_headlen(skb);
tp->wqe_req.sgl[0].address = ash->dma_handle[0];
tp->wqe_req.sgl[0].mem_key = gd->gpa_mkey;
tp->wqe_req.sgl[0].size = ash->size[0];
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
frag = &skb_shinfo(skb)->frags[i];
da = skb_frag_dma_map(dev, frag, 0, skb_frag_size(frag),
DMA_TO_DEVICE);
if (dma_mapping_error(dev, da))
goto frag_err;
ash->dma_handle[i + 1] = da;
ash->size[i + 1] = skb_frag_size(frag);
tp->wqe_req.sgl[i + 1].address = ash->dma_handle[i + 1];
tp->wqe_req.sgl[i + 1].mem_key = gd->gpa_mkey;
tp->wqe_req.sgl[i + 1].size = ash->size[i + 1];
}
return 0;
frag_err:
for (i = i - 1; i >= 0; i--)
dma_unmap_page(dev, ash->dma_handle[i + 1], ash->size[i + 1],
DMA_TO_DEVICE);
dma_unmap_single(dev, ash->dma_handle[0], ash->size[0], DMA_TO_DEVICE);
return -ENOMEM;
}
netdev_tx_t mana_start_xmit(struct sk_buff *skb, struct net_device *ndev)
{
enum mana_tx_pkt_format pkt_fmt = MANA_SHORT_PKT_FMT;
struct mana_port_context *apc = netdev_priv(ndev);
u16 txq_idx = skb_get_queue_mapping(skb);
struct gdma_dev *gd = apc->ac->gdma_dev;
bool ipv4 = false, ipv6 = false;
struct mana_tx_package pkg = {};
struct netdev_queue *net_txq;
struct mana_stats_tx *tx_stats;
struct gdma_queue *gdma_sq;
unsigned int csum_type;
struct mana_txq *txq;
struct mana_cq *cq;
int err, len;
u16 ihs;
if (unlikely(!apc->port_is_up))
goto tx_drop;
if (skb_cow_head(skb, MANA_HEADROOM))
goto tx_drop_count;
txq = &apc->tx_qp[txq_idx].txq;
gdma_sq = txq->gdma_sq;
cq = &apc->tx_qp[txq_idx].tx_cq;
tx_stats = &txq->stats;
pkg.tx_oob.s_oob.vcq_num = cq->gdma_id;
pkg.tx_oob.s_oob.vsq_frame = txq->vsq_frame;
if (txq->vp_offset > MANA_SHORT_VPORT_OFFSET_MAX) {
pkg.tx_oob.l_oob.long_vp_offset = txq->vp_offset;
pkt_fmt = MANA_LONG_PKT_FMT;
} else {
pkg.tx_oob.s_oob.short_vp_offset = txq->vp_offset;
}
if (skb_vlan_tag_present(skb)) {
pkt_fmt = MANA_LONG_PKT_FMT;
pkg.tx_oob.l_oob.inject_vlan_pri_tag = 1;
pkg.tx_oob.l_oob.pcp = skb_vlan_tag_get_prio(skb);
pkg.tx_oob.l_oob.dei = skb_vlan_tag_get_cfi(skb);
pkg.tx_oob.l_oob.vlan_id = skb_vlan_tag_get_id(skb);
}
pkg.tx_oob.s_oob.pkt_fmt = pkt_fmt;
if (pkt_fmt == MANA_SHORT_PKT_FMT) {
pkg.wqe_req.inline_oob_size = sizeof(struct mana_tx_short_oob);
u64_stats_update_begin(&tx_stats->syncp);
tx_stats->short_pkt_fmt++;
u64_stats_update_end(&tx_stats->syncp);
} else {
pkg.wqe_req.inline_oob_size = sizeof(struct mana_tx_oob);
u64_stats_update_begin(&tx_stats->syncp);
tx_stats->long_pkt_fmt++;
u64_stats_update_end(&tx_stats->syncp);
}
pkg.wqe_req.inline_oob_data = &pkg.tx_oob;
pkg.wqe_req.flags = 0;
pkg.wqe_req.client_data_unit = 0;
pkg.wqe_req.num_sge = 1 + skb_shinfo(skb)->nr_frags;
WARN_ON_ONCE(pkg.wqe_req.num_sge > MAX_TX_WQE_SGL_ENTRIES);
if (pkg.wqe_req.num_sge <= ARRAY_SIZE(pkg.sgl_array)) {
pkg.wqe_req.sgl = pkg.sgl_array;
} else {
pkg.sgl_ptr = kmalloc_array(pkg.wqe_req.num_sge,
sizeof(struct gdma_sge),
GFP_ATOMIC);
if (!pkg.sgl_ptr)
goto tx_drop_count;
pkg.wqe_req.sgl = pkg.sgl_ptr;
}
if (skb->protocol == htons(ETH_P_IP))
ipv4 = true;
else if (skb->protocol == htons(ETH_P_IPV6))
ipv6 = true;
if (skb_is_gso(skb)) {
pkg.tx_oob.s_oob.is_outer_ipv4 = ipv4;
pkg.tx_oob.s_oob.is_outer_ipv6 = ipv6;
pkg.tx_oob.s_oob.comp_iphdr_csum = 1;
pkg.tx_oob.s_oob.comp_tcp_csum = 1;
pkg.tx_oob.s_oob.trans_off = skb_transport_offset(skb);
pkg.wqe_req.client_data_unit = skb_shinfo(skb)->gso_size;
pkg.wqe_req.flags = GDMA_WR_OOB_IN_SGL | GDMA_WR_PAD_BY_SGE0;
if (ipv4) {
ip_hdr(skb)->tot_len = 0;
ip_hdr(skb)->check = 0;
tcp_hdr(skb)->check =
~csum_tcpudp_magic(ip_hdr(skb)->saddr,
ip_hdr(skb)->daddr, 0,
IPPROTO_TCP, 0);
} else {
ipv6_hdr(skb)->payload_len = 0;
tcp_hdr(skb)->check =
~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
&ipv6_hdr(skb)->daddr, 0,
IPPROTO_TCP, 0);
}
if (skb->encapsulation) {
ihs = skb_inner_tcp_all_headers(skb);
u64_stats_update_begin(&tx_stats->syncp);
tx_stats->tso_inner_packets++;
tx_stats->tso_inner_bytes += skb->len - ihs;
u64_stats_update_end(&tx_stats->syncp);
} else {
if (skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) {
ihs = skb_transport_offset(skb) + sizeof(struct udphdr);
} else {
ihs = skb_tcp_all_headers(skb);
if (ipv6_has_hopopt_jumbo(skb))
ihs -= sizeof(struct hop_jumbo_hdr);
}
u64_stats_update_begin(&tx_stats->syncp);
tx_stats->tso_packets++;
tx_stats->tso_bytes += skb->len - ihs;
u64_stats_update_end(&tx_stats->syncp);
}
} else if (skb->ip_summed == CHECKSUM_PARTIAL) {
csum_type = mana_checksum_info(skb);
u64_stats_update_begin(&tx_stats->syncp);
tx_stats->csum_partial++;
u64_stats_update_end(&tx_stats->syncp);
if (csum_type == IPPROTO_TCP) {
pkg.tx_oob.s_oob.is_outer_ipv4 = ipv4;
pkg.tx_oob.s_oob.is_outer_ipv6 = ipv6;
pkg.tx_oob.s_oob.comp_tcp_csum = 1;
pkg.tx_oob.s_oob.trans_off = skb_transport_offset(skb);
} else if (csum_type == IPPROTO_UDP) {
pkg.tx_oob.s_oob.is_outer_ipv4 = ipv4;
pkg.tx_oob.s_oob.is_outer_ipv6 = ipv6;
pkg.tx_oob.s_oob.comp_udp_csum = 1;
} else {
/* Can't do offload of this type of checksum */
if (skb_checksum_help(skb))
goto free_sgl_ptr;
}
}
if (mana_map_skb(skb, apc, &pkg)) {
u64_stats_update_begin(&tx_stats->syncp);
tx_stats->mana_map_err++;
u64_stats_update_end(&tx_stats->syncp);
goto free_sgl_ptr;
}
skb_queue_tail(&txq->pending_skbs, skb);
len = skb->len;
net_txq = netdev_get_tx_queue(ndev, txq_idx);
err = mana_gd_post_work_request(gdma_sq, &pkg.wqe_req,
(struct gdma_posted_wqe_info *)skb->cb);
if (!mana_can_tx(gdma_sq)) {
netif_tx_stop_queue(net_txq);
apc->eth_stats.stop_queue++;
}
if (err) {
(void)skb_dequeue_tail(&txq->pending_skbs);
netdev_warn(ndev, "Failed to post TX OOB: %d\n", err);
err = NETDEV_TX_BUSY;
goto tx_busy;
}
err = NETDEV_TX_OK;
atomic_inc(&txq->pending_sends);
mana_gd_wq_ring_doorbell(gd->gdma_context, gdma_sq);
/* skb may be freed after mana_gd_post_work_request. Do not use it. */
skb = NULL;
tx_stats = &txq->stats;
u64_stats_update_begin(&tx_stats->syncp);
tx_stats->packets++;
tx_stats->bytes += len;
u64_stats_update_end(&tx_stats->syncp);
tx_busy:
if (netif_tx_queue_stopped(net_txq) && mana_can_tx(gdma_sq)) {
netif_tx_wake_queue(net_txq);
apc->eth_stats.wake_queue++;
}
kfree(pkg.sgl_ptr);
return err;
free_sgl_ptr:
kfree(pkg.sgl_ptr);
tx_drop_count:
ndev->stats.tx_dropped++;
tx_drop:
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
static void mana_get_stats64(struct net_device *ndev,
struct rtnl_link_stats64 *st)
{
struct mana_port_context *apc = netdev_priv(ndev);
unsigned int num_queues = apc->num_queues;
struct mana_stats_rx *rx_stats;
struct mana_stats_tx *tx_stats;
unsigned int start;
u64 packets, bytes;
int q;
if (!apc->port_is_up)
return;
netdev_stats_to_stats64(st, &ndev->stats);
for (q = 0; q < num_queues; q++) {
rx_stats = &apc->rxqs[q]->stats;
do {
start = u64_stats_fetch_begin(&rx_stats->syncp);
packets = rx_stats->packets;
bytes = rx_stats->bytes;
} while (u64_stats_fetch_retry(&rx_stats->syncp, start));
st->rx_packets += packets;
st->rx_bytes += bytes;
}
for (q = 0; q < num_queues; q++) {
tx_stats = &apc->tx_qp[q].txq.stats;
do {
start = u64_stats_fetch_begin(&tx_stats->syncp);
packets = tx_stats->packets;
bytes = tx_stats->bytes;
} while (u64_stats_fetch_retry(&tx_stats->syncp, start));
st->tx_packets += packets;
st->tx_bytes += bytes;
}
}
static int mana_get_tx_queue(struct net_device *ndev, struct sk_buff *skb,
int old_q)
{
struct mana_port_context *apc = netdev_priv(ndev);
u32 hash = skb_get_hash(skb);
struct sock *sk = skb->sk;
int txq;
txq = apc->indir_table[hash & MANA_INDIRECT_TABLE_MASK];
if (txq != old_q && sk && sk_fullsock(sk) &&
rcu_access_pointer(sk->sk_dst_cache))
sk_tx_queue_set(sk, txq);
return txq;
}
static u16 mana_select_queue(struct net_device *ndev, struct sk_buff *skb,
struct net_device *sb_dev)
{
int txq;
if (ndev->real_num_tx_queues == 1)
return 0;
txq = sk_tx_queue_get(skb->sk);
if (txq < 0 || skb->ooo_okay || txq >= ndev->real_num_tx_queues) {
if (skb_rx_queue_recorded(skb))
txq = skb_get_rx_queue(skb);
else
txq = mana_get_tx_queue(ndev, skb, txq);
}
return txq;
}
/* Release pre-allocated RX buffers */
static void mana_pre_dealloc_rxbufs(struct mana_port_context *mpc)
{
struct device *dev;
int i;
dev = mpc->ac->gdma_dev->gdma_context->dev;
if (!mpc->rxbufs_pre)
goto out1;
if (!mpc->das_pre)
goto out2;
while (mpc->rxbpre_total) {
i = --mpc->rxbpre_total;
dma_unmap_single(dev, mpc->das_pre[i], mpc->rxbpre_datasize,
DMA_FROM_DEVICE);
put_page(virt_to_head_page(mpc->rxbufs_pre[i]));
}
kfree(mpc->das_pre);
mpc->das_pre = NULL;
out2:
kfree(mpc->rxbufs_pre);
mpc->rxbufs_pre = NULL;
out1:
mpc->rxbpre_datasize = 0;
mpc->rxbpre_alloc_size = 0;
mpc->rxbpre_headroom = 0;
}
/* Get a buffer from the pre-allocated RX buffers */
static void *mana_get_rxbuf_pre(struct mana_rxq *rxq, dma_addr_t *da)
{
struct net_device *ndev = rxq->ndev;
struct mana_port_context *mpc;
void *va;
mpc = netdev_priv(ndev);
if (!mpc->rxbufs_pre || !mpc->das_pre || !mpc->rxbpre_total) {
netdev_err(ndev, "No RX pre-allocated bufs\n");
return NULL;
}
/* Check sizes to catch unexpected coding error */
if (mpc->rxbpre_datasize != rxq->datasize) {
netdev_err(ndev, "rxbpre_datasize mismatch: %u: %u\n",
mpc->rxbpre_datasize, rxq->datasize);
return NULL;
}
if (mpc->rxbpre_alloc_size != rxq->alloc_size) {
netdev_err(ndev, "rxbpre_alloc_size mismatch: %u: %u\n",
mpc->rxbpre_alloc_size, rxq->alloc_size);
return NULL;
}
if (mpc->rxbpre_headroom != rxq->headroom) {
netdev_err(ndev, "rxbpre_headroom mismatch: %u: %u\n",
mpc->rxbpre_headroom, rxq->headroom);
return NULL;
}
mpc->rxbpre_total--;
*da = mpc->das_pre[mpc->rxbpre_total];
va = mpc->rxbufs_pre[mpc->rxbpre_total];
mpc->rxbufs_pre[mpc->rxbpre_total] = NULL;
/* Deallocate the array after all buffers are gone */
if (!mpc->rxbpre_total)
mana_pre_dealloc_rxbufs(mpc);
return va;
}
/* Get RX buffer's data size, alloc size, XDP headroom based on MTU */
static void mana_get_rxbuf_cfg(int mtu, u32 *datasize, u32 *alloc_size,
u32 *headroom)
{
if (mtu > MANA_XDP_MTU_MAX)
*headroom = 0; /* no support for XDP */
else
*headroom = XDP_PACKET_HEADROOM;
*alloc_size = mtu + MANA_RXBUF_PAD + *headroom;
*datasize = ALIGN(mtu + ETH_HLEN, MANA_RX_DATA_ALIGN);
}
static int mana_pre_alloc_rxbufs(struct mana_port_context *mpc, int new_mtu)
{
struct device *dev;
struct page *page;
dma_addr_t da;
int num_rxb;
void *va;
int i;
mana_get_rxbuf_cfg(new_mtu, &mpc->rxbpre_datasize,
&mpc->rxbpre_alloc_size, &mpc->rxbpre_headroom);
dev = mpc->ac->gdma_dev->gdma_context->dev;
num_rxb = mpc->num_queues * RX_BUFFERS_PER_QUEUE;
WARN(mpc->rxbufs_pre, "mana rxbufs_pre exists\n");
mpc->rxbufs_pre = kmalloc_array(num_rxb, sizeof(void *), GFP_KERNEL);
if (!mpc->rxbufs_pre)
goto error;
mpc->das_pre = kmalloc_array(num_rxb, sizeof(dma_addr_t), GFP_KERNEL);
if (!mpc->das_pre)
goto error;
mpc->rxbpre_total = 0;
for (i = 0; i < num_rxb; i++) {
if (mpc->rxbpre_alloc_size > PAGE_SIZE) {
va = netdev_alloc_frag(mpc->rxbpre_alloc_size);
if (!va)
goto error;
page = virt_to_head_page(va);
/* Check if the frag falls back to single page */
if (compound_order(page) <
get_order(mpc->rxbpre_alloc_size)) {
put_page(page);
goto error;
}
} else {
page = dev_alloc_page();
if (!page)
goto error;
va = page_to_virt(page);
}
da = dma_map_single(dev, va + mpc->rxbpre_headroom,
mpc->rxbpre_datasize, DMA_FROM_DEVICE);
if (dma_mapping_error(dev, da)) {
put_page(virt_to_head_page(va));
goto error;
}
mpc->rxbufs_pre[i] = va;
mpc->das_pre[i] = da;
mpc->rxbpre_total = i + 1;
}
return 0;
error:
mana_pre_dealloc_rxbufs(mpc);
return -ENOMEM;
}
static int mana_change_mtu(struct net_device *ndev, int new_mtu)
{
struct mana_port_context *mpc = netdev_priv(ndev);
unsigned int old_mtu = ndev->mtu;
int err;
/* Pre-allocate buffers to prevent failure in mana_attach later */
err = mana_pre_alloc_rxbufs(mpc, new_mtu);
if (err) {
netdev_err(ndev, "Insufficient memory for new MTU\n");
return err;
}
err = mana_detach(ndev, false);
if (err) {
netdev_err(ndev, "mana_detach failed: %d\n", err);
goto out;
}
ndev->mtu = new_mtu;
err = mana_attach(ndev);
if (err) {
netdev_err(ndev, "mana_attach failed: %d\n", err);
ndev->mtu = old_mtu;
}
out:
mana_pre_dealloc_rxbufs(mpc);
return err;
}
static const struct net_device_ops mana_devops = {
.ndo_open = mana_open,
.ndo_stop = mana_close,
.ndo_select_queue = mana_select_queue,
.ndo_start_xmit = mana_start_xmit,
.ndo_validate_addr = eth_validate_addr,
.ndo_get_stats64 = mana_get_stats64,
.ndo_bpf = mana_bpf,
.ndo_xdp_xmit = mana_xdp_xmit,
.ndo_change_mtu = mana_change_mtu,
};
static void mana_cleanup_port_context(struct mana_port_context *apc)
{
kfree(apc->rxqs);
apc->rxqs = NULL;
}
static int mana_init_port_context(struct mana_port_context *apc)
{
apc->rxqs = kcalloc(apc->num_queues, sizeof(struct mana_rxq *),
GFP_KERNEL);
return !apc->rxqs ? -ENOMEM : 0;
}
static int mana_send_request(struct mana_context *ac, void *in_buf,
u32 in_len, void *out_buf, u32 out_len)
{
struct gdma_context *gc = ac->gdma_dev->gdma_context;
struct gdma_resp_hdr *resp = out_buf;
struct gdma_req_hdr *req = in_buf;
struct device *dev = gc->dev;
static atomic_t activity_id;
int err;
req->dev_id = gc->mana.dev_id;
req->activity_id = atomic_inc_return(&activity_id);
err = mana_gd_send_request(gc, in_len, in_buf, out_len,
out_buf);
if (err || resp->status) {
dev_err(dev, "Failed to send mana message: %d, 0x%x\n",
err, resp->status);
return err ? err : -EPROTO;
}
if (req->dev_id.as_uint32 != resp->dev_id.as_uint32 ||
req->activity_id != resp->activity_id) {
dev_err(dev, "Unexpected mana message response: %x,%x,%x,%x\n",
req->dev_id.as_uint32, resp->dev_id.as_uint32,
req->activity_id, resp->activity_id);
return -EPROTO;
}
return 0;
}
static int mana_verify_resp_hdr(const struct gdma_resp_hdr *resp_hdr,
const enum mana_command_code expected_code,
const u32 min_size)
{
if (resp_hdr->response.msg_type != expected_code)
return -EPROTO;
if (resp_hdr->response.msg_version < GDMA_MESSAGE_V1)
return -EPROTO;
if (resp_hdr->response.msg_size < min_size)
return -EPROTO;
return 0;
}
static int mana_pf_register_hw_vport(struct mana_port_context *apc)
{
struct mana_register_hw_vport_resp resp = {};
struct mana_register_hw_vport_req req = {};
int err;
mana_gd_init_req_hdr(&req.hdr, MANA_REGISTER_HW_PORT,
sizeof(req), sizeof(resp));
req.attached_gfid = 1;
req.is_pf_default_vport = 1;
req.allow_all_ether_types = 1;
err = mana_send_request(apc->ac, &req, sizeof(req), &resp,
sizeof(resp));
if (err) {
netdev_err(apc->ndev, "Failed to register hw vPort: %d\n", err);
return err;
}
err = mana_verify_resp_hdr(&resp.hdr, MANA_REGISTER_HW_PORT,
sizeof(resp));
if (err || resp.hdr.status) {
netdev_err(apc->ndev, "Failed to register hw vPort: %d, 0x%x\n",
err, resp.hdr.status);
return err ? err : -EPROTO;
}
apc->port_handle = resp.hw_vport_handle;
return 0;
}
static void mana_pf_deregister_hw_vport(struct mana_port_context *apc)
{
struct mana_deregister_hw_vport_resp resp = {};
struct mana_deregister_hw_vport_req req = {};
int err;
mana_gd_init_req_hdr(&req.hdr, MANA_DEREGISTER_HW_PORT,
sizeof(req), sizeof(resp));
req.hw_vport_handle = apc->port_handle;
err = mana_send_request(apc->ac, &req, sizeof(req), &resp,
sizeof(resp));
if (err) {
netdev_err(apc->ndev, "Failed to unregister hw vPort: %d\n",
err);
return;
}
err = mana_verify_resp_hdr(&resp.hdr, MANA_DEREGISTER_HW_PORT,
sizeof(resp));
if (err || resp.hdr.status)
netdev_err(apc->ndev,
"Failed to deregister hw vPort: %d, 0x%x\n",
err, resp.hdr.status);
}
static int mana_pf_register_filter(struct mana_port_context *apc)
{
struct mana_register_filter_resp resp = {};
struct mana_register_filter_req req = {};
int err;
mana_gd_init_req_hdr(&req.hdr, MANA_REGISTER_FILTER,
sizeof(req), sizeof(resp));
req.vport = apc->port_handle;
memcpy(req.mac_addr, apc->mac_addr, ETH_ALEN);
err = mana_send_request(apc->ac, &req, sizeof(req), &resp,
sizeof(resp));
if (err) {
netdev_err(apc->ndev, "Failed to register filter: %d\n", err);
return err;
}
err = mana_verify_resp_hdr(&resp.hdr, MANA_REGISTER_FILTER,
sizeof(resp));
if (err || resp.hdr.status) {
netdev_err(apc->ndev, "Failed to register filter: %d, 0x%x\n",
err, resp.hdr.status);
return err ? err : -EPROTO;
}
apc->pf_filter_handle = resp.filter_handle;
return 0;
}
static void mana_pf_deregister_filter(struct mana_port_context *apc)
{
struct mana_deregister_filter_resp resp = {};
struct mana_deregister_filter_req req = {};
int err;
mana_gd_init_req_hdr(&req.hdr, MANA_DEREGISTER_FILTER,
sizeof(req), sizeof(resp));
req.filter_handle = apc->pf_filter_handle;
err = mana_send_request(apc->ac, &req, sizeof(req), &resp,
sizeof(resp));
if (err) {
netdev_err(apc->ndev, "Failed to unregister filter: %d\n",
err);
return;
}
err = mana_verify_resp_hdr(&resp.hdr, MANA_DEREGISTER_FILTER,
sizeof(resp));
if (err || resp.hdr.status)
netdev_err(apc->ndev,
"Failed to deregister filter: %d, 0x%x\n",
err, resp.hdr.status);
}
static int mana_query_device_cfg(struct mana_context *ac, u32 proto_major_ver,
u32 proto_minor_ver, u32 proto_micro_ver,
u16 *max_num_vports)
{
struct gdma_context *gc = ac->gdma_dev->gdma_context;
struct mana_query_device_cfg_resp resp = {};
struct mana_query_device_cfg_req req = {};
struct device *dev = gc->dev;
int err = 0;
mana_gd_init_req_hdr(&req.hdr, MANA_QUERY_DEV_CONFIG,
sizeof(req), sizeof(resp));
req.hdr.resp.msg_version = GDMA_MESSAGE_V2;
req.proto_major_ver = proto_major_ver;
req.proto_minor_ver = proto_minor_ver;
req.proto_micro_ver = proto_micro_ver;
err = mana_send_request(ac, &req, sizeof(req), &resp, sizeof(resp));
if (err) {
dev_err(dev, "Failed to query config: %d", err);
return err;
}
err = mana_verify_resp_hdr(&resp.hdr, MANA_QUERY_DEV_CONFIG,
sizeof(resp));
if (err || resp.hdr.status) {
dev_err(dev, "Invalid query result: %d, 0x%x\n", err,
resp.hdr.status);
if (!err)
err = -EPROTO;
return err;
}
*max_num_vports = resp.max_num_vports;
if (resp.hdr.response.msg_version == GDMA_MESSAGE_V2)
gc->adapter_mtu = resp.adapter_mtu;
else
gc->adapter_mtu = ETH_FRAME_LEN;
return 0;
}
static int mana_query_vport_cfg(struct mana_port_context *apc, u32 vport_index,
u32 *max_sq, u32 *max_rq, u32 *num_indir_entry)
{
struct mana_query_vport_cfg_resp resp = {};
struct mana_query_vport_cfg_req req = {};
int err;
mana_gd_init_req_hdr(&req.hdr, MANA_QUERY_VPORT_CONFIG,
sizeof(req), sizeof(resp));
req.vport_index = vport_index;
err = mana_send_request(apc->ac, &req, sizeof(req), &resp,
sizeof(resp));
if (err)
return err;
err = mana_verify_resp_hdr(&resp.hdr, MANA_QUERY_VPORT_CONFIG,
sizeof(resp));
if (err)
return err;
if (resp.hdr.status)
return -EPROTO;
*max_sq = resp.max_num_sq;
*max_rq = resp.max_num_rq;
*num_indir_entry = resp.num_indirection_ent;
apc->port_handle = resp.vport;
ether_addr_copy(apc->mac_addr, resp.mac_addr);
return 0;
}
void mana_uncfg_vport(struct mana_port_context *apc)
{
mutex_lock(&apc->vport_mutex);
apc->vport_use_count--;
WARN_ON(apc->vport_use_count < 0);
mutex_unlock(&apc->vport_mutex);
}
EXPORT_SYMBOL_NS(mana_uncfg_vport, NET_MANA);
int mana_cfg_vport(struct mana_port_context *apc, u32 protection_dom_id,
u32 doorbell_pg_id)
{
struct mana_config_vport_resp resp = {};
struct mana_config_vport_req req = {};
int err;
/* This function is used to program the Ethernet port in the hardware
* table. It can be called from the Ethernet driver or the RDMA driver.
*
* For Ethernet usage, the hardware supports only one active user on a
* physical port. The driver checks on the port usage before programming
* the hardware when creating the RAW QP (RDMA driver) or exposing the
* device to kernel NET layer (Ethernet driver).
*
* Because the RDMA driver doesn't know in advance which QP type the
* user will create, it exposes the device with all its ports. The user
* may not be able to create RAW QP on a port if this port is already
* in used by the Ethernet driver from the kernel.
*
* This physical port limitation only applies to the RAW QP. For RC QP,
* the hardware doesn't have this limitation. The user can create RC
* QPs on a physical port up to the hardware limits independent of the
* Ethernet usage on the same port.
*/
mutex_lock(&apc->vport_mutex);
if (apc->vport_use_count > 0) {
mutex_unlock(&apc->vport_mutex);
return -EBUSY;
}
apc->vport_use_count++;
mutex_unlock(&apc->vport_mutex);
mana_gd_init_req_hdr(&req.hdr, MANA_CONFIG_VPORT_TX,
sizeof(req), sizeof(resp));
req.vport = apc->port_handle;
req.pdid = protection_dom_id;
req.doorbell_pageid = doorbell_pg_id;
err = mana_send_request(apc->ac, &req, sizeof(req), &resp,
sizeof(resp));
if (err) {
netdev_err(apc->ndev, "Failed to configure vPort: %d\n", err);
goto out;
}
err = mana_verify_resp_hdr(&resp.hdr, MANA_CONFIG_VPORT_TX,
sizeof(resp));
if (err || resp.hdr.status) {
netdev_err(apc->ndev, "Failed to configure vPort: %d, 0x%x\n",
err, resp.hdr.status);
if (!err)
err = -EPROTO;
goto out;
}
apc->tx_shortform_allowed = resp.short_form_allowed;
apc->tx_vp_offset = resp.tx_vport_offset;
netdev_info(apc->ndev, "Configured vPort %llu PD %u DB %u\n",
apc->port_handle, protection_dom_id, doorbell_pg_id);
out:
if (err)
mana_uncfg_vport(apc);
return err;
}
EXPORT_SYMBOL_NS(mana_cfg_vport, NET_MANA);
static int mana_cfg_vport_steering(struct mana_port_context *apc,
enum TRI_STATE rx,
bool update_default_rxobj, bool update_key,
bool update_tab)
{
u16 num_entries = MANA_INDIRECT_TABLE_SIZE;
struct mana_cfg_rx_steer_req_v2 *req;
struct mana_cfg_rx_steer_resp resp = {};
struct net_device *ndev = apc->ndev;
mana_handle_t *req_indir_tab;
u32 req_buf_size;
int err;
req_buf_size = sizeof(*req) + sizeof(mana_handle_t) * num_entries;
req = kzalloc(req_buf_size, GFP_KERNEL);
if (!req)
return -ENOMEM;
mana_gd_init_req_hdr(&req->hdr, MANA_CONFIG_VPORT_RX, req_buf_size,
sizeof(resp));
req->hdr.req.msg_version = GDMA_MESSAGE_V2;
req->vport = apc->port_handle;
req->num_indir_entries = num_entries;
req->indir_tab_offset = sizeof(*req);
req->rx_enable = rx;
req->rss_enable = apc->rss_state;
req->update_default_rxobj = update_default_rxobj;
req->update_hashkey = update_key;
req->update_indir_tab = update_tab;
req->default_rxobj = apc->default_rxobj;
req->cqe_coalescing_enable = 0;
if (update_key)
memcpy(&req->hashkey, apc->hashkey, MANA_HASH_KEY_SIZE);
if (update_tab) {
req_indir_tab = (mana_handle_t *)(req + 1);
memcpy(req_indir_tab, apc->rxobj_table,
req->num_indir_entries * sizeof(mana_handle_t));
}
err = mana_send_request(apc->ac, req, req_buf_size, &resp,
sizeof(resp));
if (err) {
netdev_err(ndev, "Failed to configure vPort RX: %d\n", err);
goto out;
}
err = mana_verify_resp_hdr(&resp.hdr, MANA_CONFIG_VPORT_RX,
sizeof(resp));
if (err) {
netdev_err(ndev, "vPort RX configuration failed: %d\n", err);
goto out;
}
if (resp.hdr.status) {
netdev_err(ndev, "vPort RX configuration failed: 0x%x\n",
resp.hdr.status);
err = -EPROTO;
}
netdev_info(ndev, "Configured steering vPort %llu entries %u\n",
apc->port_handle, num_entries);
out:
kfree(req);
return err;
}
int mana_create_wq_obj(struct mana_port_context *apc,
mana_handle_t vport,
u32 wq_type, struct mana_obj_spec *wq_spec,
struct mana_obj_spec *cq_spec,
mana_handle_t *wq_obj)
{
struct mana_create_wqobj_resp resp = {};
struct mana_create_wqobj_req req = {};
struct net_device *ndev = apc->ndev;
int err;
mana_gd_init_req_hdr(&req.hdr, MANA_CREATE_WQ_OBJ,
sizeof(req), sizeof(resp));
req.vport = vport;
req.wq_type = wq_type;
req.wq_gdma_region = wq_spec->gdma_region;
req.cq_gdma_region = cq_spec->gdma_region;
req.wq_size = wq_spec->queue_size;
req.cq_size = cq_spec->queue_size;
req.cq_moderation_ctx_id = cq_spec->modr_ctx_id;
req.cq_parent_qid = cq_spec->attached_eq;
err = mana_send_request(apc->ac, &req, sizeof(req), &resp,
sizeof(resp));
if (err) {
netdev_err(ndev, "Failed to create WQ object: %d\n", err);
goto out;
}
err = mana_verify_resp_hdr(&resp.hdr, MANA_CREATE_WQ_OBJ,
sizeof(resp));
if (err || resp.hdr.status) {
netdev_err(ndev, "Failed to create WQ object: %d, 0x%x\n", err,
resp.hdr.status);
if (!err)
err = -EPROTO;
goto out;
}
if (resp.wq_obj == INVALID_MANA_HANDLE) {
netdev_err(ndev, "Got an invalid WQ object handle\n");
err = -EPROTO;
goto out;
}
*wq_obj = resp.wq_obj;
wq_spec->queue_index = resp.wq_id;
cq_spec->queue_index = resp.cq_id;
return 0;
out:
return err;
}
EXPORT_SYMBOL_NS(mana_create_wq_obj, NET_MANA);
void mana_destroy_wq_obj(struct mana_port_context *apc, u32 wq_type,
mana_handle_t wq_obj)
{
struct mana_destroy_wqobj_resp resp = {};
struct mana_destroy_wqobj_req req = {};
struct net_device *ndev = apc->ndev;
int err;
mana_gd_init_req_hdr(&req.hdr, MANA_DESTROY_WQ_OBJ,
sizeof(req), sizeof(resp));
req.wq_type = wq_type;
req.wq_obj_handle = wq_obj;
err = mana_send_request(apc->ac, &req, sizeof(req), &resp,
sizeof(resp));
if (err) {
netdev_err(ndev, "Failed to destroy WQ object: %d\n", err);
return;
}
err = mana_verify_resp_hdr(&resp.hdr, MANA_DESTROY_WQ_OBJ,
sizeof(resp));
if (err || resp.hdr.status)
netdev_err(ndev, "Failed to destroy WQ object: %d, 0x%x\n", err,
resp.hdr.status);
}
EXPORT_SYMBOL_NS(mana_destroy_wq_obj, NET_MANA);
static void mana_destroy_eq(struct mana_context *ac)
{
struct gdma_context *gc = ac->gdma_dev->gdma_context;
struct gdma_queue *eq;
int i;
if (!ac->eqs)
return;
for (i = 0; i < gc->max_num_queues; i++) {
eq = ac->eqs[i].eq;
if (!eq)
continue;
mana_gd_destroy_queue(gc, eq);
}
kfree(ac->eqs);
ac->eqs = NULL;
}
static int mana_create_eq(struct mana_context *ac)
{
struct gdma_dev *gd = ac->gdma_dev;
struct gdma_context *gc = gd->gdma_context;
struct gdma_queue_spec spec = {};
int err;
int i;
ac->eqs = kcalloc(gc->max_num_queues, sizeof(struct mana_eq),
GFP_KERNEL);
if (!ac->eqs)
return -ENOMEM;
spec.type = GDMA_EQ;
spec.monitor_avl_buf = false;
spec.queue_size = EQ_SIZE;
spec.eq.callback = NULL;
spec.eq.context = ac->eqs;
spec.eq.log2_throttle_limit = LOG2_EQ_THROTTLE;
for (i = 0; i < gc->max_num_queues; i++) {
err = mana_gd_create_mana_eq(gd, &spec, &ac->eqs[i].eq);
if (err)
goto out;
}
return 0;
out:
mana_destroy_eq(ac);
return err;
}
static int mana_fence_rq(struct mana_port_context *apc, struct mana_rxq *rxq)
{
struct mana_fence_rq_resp resp = {};
struct mana_fence_rq_req req = {};
int err;
init_completion(&rxq->fence_event);
mana_gd_init_req_hdr(&req.hdr, MANA_FENCE_RQ,
sizeof(req), sizeof(resp));
req.wq_obj_handle = rxq->rxobj;
err = mana_send_request(apc->ac, &req, sizeof(req), &resp,
sizeof(resp));
if (err) {
netdev_err(apc->ndev, "Failed to fence RQ %u: %d\n",
rxq->rxq_idx, err);
return err;
}
err = mana_verify_resp_hdr(&resp.hdr, MANA_FENCE_RQ, sizeof(resp));
if (err || resp.hdr.status) {
netdev_err(apc->ndev, "Failed to fence RQ %u: %d, 0x%x\n",
rxq->rxq_idx, err, resp.hdr.status);
if (!err)
err = -EPROTO;
return err;
}
if (wait_for_completion_timeout(&rxq->fence_event, 10 * HZ) == 0) {
netdev_err(apc->ndev, "Failed to fence RQ %u: timed out\n",
rxq->rxq_idx);
return -ETIMEDOUT;
}
return 0;
}
static void mana_fence_rqs(struct mana_port_context *apc)
{
unsigned int rxq_idx;
struct mana_rxq *rxq;
int err;
for (rxq_idx = 0; rxq_idx < apc->num_queues; rxq_idx++) {
rxq = apc->rxqs[rxq_idx];
err = mana_fence_rq(apc, rxq);
/* In case of any error, use sleep instead. */
if (err)
msleep(100);
}
}
static int mana_move_wq_tail(struct gdma_queue *wq, u32 num_units)
{
u32 used_space_old;
u32 used_space_new;
used_space_old = wq->head - wq->tail;
used_space_new = wq->head - (wq->tail + num_units);
if (WARN_ON_ONCE(used_space_new > used_space_old))
return -ERANGE;
wq->tail += num_units;
return 0;
}
static void mana_unmap_skb(struct sk_buff *skb, struct mana_port_context *apc)
{
struct mana_skb_head *ash = (struct mana_skb_head *)skb->head;
struct gdma_context *gc = apc->ac->gdma_dev->gdma_context;
struct device *dev = gc->dev;
int i;
dma_unmap_single(dev, ash->dma_handle[0], ash->size[0], DMA_TO_DEVICE);
for (i = 1; i < skb_shinfo(skb)->nr_frags + 1; i++)
dma_unmap_page(dev, ash->dma_handle[i], ash->size[i],
DMA_TO_DEVICE);
}
static void mana_poll_tx_cq(struct mana_cq *cq)
{
struct gdma_comp *completions = cq->gdma_comp_buf;
struct gdma_posted_wqe_info *wqe_info;
unsigned int pkt_transmitted = 0;
unsigned int wqe_unit_cnt = 0;
struct mana_txq *txq = cq->txq;
struct mana_port_context *apc;
struct netdev_queue *net_txq;
struct gdma_queue *gdma_wq;
unsigned int avail_space;
struct net_device *ndev;
struct sk_buff *skb;
bool txq_stopped;
int comp_read;
int i;
ndev = txq->ndev;
apc = netdev_priv(ndev);
comp_read = mana_gd_poll_cq(cq->gdma_cq, completions,
CQE_POLLING_BUFFER);
if (comp_read < 1)
return;
for (i = 0; i < comp_read; i++) {
struct mana_tx_comp_oob *cqe_oob;
if (WARN_ON_ONCE(!completions[i].is_sq))
return;
cqe_oob = (struct mana_tx_comp_oob *)completions[i].cqe_data;
if (WARN_ON_ONCE(cqe_oob->cqe_hdr.client_type !=
MANA_CQE_COMPLETION))
return;
switch (cqe_oob->cqe_hdr.cqe_type) {
case CQE_TX_OKAY:
break;
case CQE_TX_SA_DROP:
case CQE_TX_MTU_DROP:
case CQE_TX_INVALID_OOB:
case CQE_TX_INVALID_ETH_TYPE:
case CQE_TX_HDR_PROCESSING_ERROR:
case CQE_TX_VF_DISABLED:
case CQE_TX_VPORT_IDX_OUT_OF_RANGE:
case CQE_TX_VPORT_DISABLED:
case CQE_TX_VLAN_TAGGING_VIOLATION:
WARN_ONCE(1, "TX: CQE error %d: ignored.\n",
cqe_oob->cqe_hdr.cqe_type);
apc->eth_stats.tx_cqe_err++;
break;
default:
/* If the CQE type is unexpected, log an error, assert,
* and go through the error path.
*/
WARN_ONCE(1, "TX: Unexpected CQE type %d: HW BUG?\n",
cqe_oob->cqe_hdr.cqe_type);
apc->eth_stats.tx_cqe_unknown_type++;
return;
}
if (WARN_ON_ONCE(txq->gdma_txq_id != completions[i].wq_num))
return;
skb = skb_dequeue(&txq->pending_skbs);
if (WARN_ON_ONCE(!skb))
return;
wqe_info = (struct gdma_posted_wqe_info *)skb->cb;
wqe_unit_cnt += wqe_info->wqe_size_in_bu;
mana_unmap_skb(skb, apc);
napi_consume_skb(skb, cq->budget);
pkt_transmitted++;
}
if (WARN_ON_ONCE(wqe_unit_cnt == 0))
return;
mana_move_wq_tail(txq->gdma_sq, wqe_unit_cnt);
gdma_wq = txq->gdma_sq;
avail_space = mana_gd_wq_avail_space(gdma_wq);
/* Ensure tail updated before checking q stop */
smp_mb();
net_txq = txq->net_txq;
txq_stopped = netif_tx_queue_stopped(net_txq);
/* Ensure checking txq_stopped before apc->port_is_up. */
smp_rmb();
if (txq_stopped && apc->port_is_up && avail_space >= MAX_TX_WQE_SIZE) {
netif_tx_wake_queue(net_txq);
apc->eth_stats.wake_queue++;
}
if (atomic_sub_return(pkt_transmitted, &txq->pending_sends) < 0)
WARN_ON_ONCE(1);
cq->work_done = pkt_transmitted;
}
static void mana_post_pkt_rxq(struct mana_rxq *rxq)
{
struct mana_recv_buf_oob *recv_buf_oob;
u32 curr_index;
int err;
curr_index = rxq->buf_index++;
if (rxq->buf_index == rxq->num_rx_buf)
rxq->buf_index = 0;
recv_buf_oob = &rxq->rx_oobs[curr_index];
err = mana_gd_post_work_request(rxq->gdma_rq, &recv_buf_oob->wqe_req,
&recv_buf_oob->wqe_inf);
if (WARN_ON_ONCE(err))
return;
WARN_ON_ONCE(recv_buf_oob->wqe_inf.wqe_size_in_bu != 1);
}
static struct sk_buff *mana_build_skb(struct mana_rxq *rxq, void *buf_va,
uint pkt_len, struct xdp_buff *xdp)
{
struct sk_buff *skb = napi_build_skb(buf_va, rxq->alloc_size);
if (!skb)
return NULL;
if (xdp->data_hard_start) {
skb_reserve(skb, xdp->data - xdp->data_hard_start);
skb_put(skb, xdp->data_end - xdp->data);
return skb;
}
skb_reserve(skb, rxq->headroom);
skb_put(skb, pkt_len);
return skb;
}
static void mana_rx_skb(void *buf_va, bool from_pool,
struct mana_rxcomp_oob *cqe, struct mana_rxq *rxq)
{
struct mana_stats_rx *rx_stats = &rxq->stats;
struct net_device *ndev = rxq->ndev;
uint pkt_len = cqe->ppi[0].pkt_len;
u16 rxq_idx = rxq->rxq_idx;
struct napi_struct *napi;
struct xdp_buff xdp = {};
struct sk_buff *skb;
u32 hash_value;
u32 act;
rxq->rx_cq.work_done++;
napi = &rxq->rx_cq.napi;
if (!buf_va) {
++ndev->stats.rx_dropped;
return;
}
act = mana_run_xdp(ndev, rxq, &xdp, buf_va, pkt_len);
if (act == XDP_REDIRECT && !rxq->xdp_rc)
return;
if (act != XDP_PASS && act != XDP_TX)
goto drop_xdp;
skb = mana_build_skb(rxq, buf_va, pkt_len, &xdp);
if (!skb)
goto drop;
if (from_pool)
skb_mark_for_recycle(skb);
skb->dev = napi->dev;
skb->protocol = eth_type_trans(skb, ndev);
skb_checksum_none_assert(skb);
skb_record_rx_queue(skb, rxq_idx);
if ((ndev->features & NETIF_F_RXCSUM) && cqe->rx_iphdr_csum_succeed) {
if (cqe->rx_tcp_csum_succeed || cqe->rx_udp_csum_succeed)
skb->ip_summed = CHECKSUM_UNNECESSARY;
}
if (cqe->rx_hashtype != 0 && (ndev->features & NETIF_F_RXHASH)) {
hash_value = cqe->ppi[0].pkt_hash;
if (cqe->rx_hashtype & MANA_HASH_L4)
skb_set_hash(skb, hash_value, PKT_HASH_TYPE_L4);
else
skb_set_hash(skb, hash_value, PKT_HASH_TYPE_L3);
}
if (cqe->rx_vlantag_present) {
u16 vlan_tci = cqe->rx_vlan_id;
__vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vlan_tci);
}
u64_stats_update_begin(&rx_stats->syncp);
rx_stats->packets++;
rx_stats->bytes += pkt_len;
if (act == XDP_TX)
rx_stats->xdp_tx++;
u64_stats_update_end(&rx_stats->syncp);
if (act == XDP_TX) {
skb_set_queue_mapping(skb, rxq_idx);
mana_xdp_tx(skb, ndev);
return;
}
napi_gro_receive(napi, skb);
return;
drop_xdp:
u64_stats_update_begin(&rx_stats->syncp);
rx_stats->xdp_drop++;
u64_stats_update_end(&rx_stats->syncp);
drop:
if (from_pool) {
page_pool_recycle_direct(rxq->page_pool,
virt_to_head_page(buf_va));
} else {
WARN_ON_ONCE(rxq->xdp_save_va);
/* Save for reuse */
rxq->xdp_save_va = buf_va;
}
++ndev->stats.rx_dropped;
return;
}
static void *mana_get_rxfrag(struct mana_rxq *rxq, struct device *dev,
dma_addr_t *da, bool *from_pool, bool is_napi)
{
struct page *page;
void *va;
*from_pool = false;
/* Reuse XDP dropped page if available */
if (rxq->xdp_save_va) {
va = rxq->xdp_save_va;
rxq->xdp_save_va = NULL;
} else if (rxq->alloc_size > PAGE_SIZE) {
if (is_napi)
va = napi_alloc_frag(rxq->alloc_size);
else
va = netdev_alloc_frag(rxq->alloc_size);
if (!va)
return NULL;
page = virt_to_head_page(va);
/* Check if the frag falls back to single page */
if (compound_order(page) < get_order(rxq->alloc_size)) {
put_page(page);
return NULL;
}
} else {
page = page_pool_dev_alloc_pages(rxq->page_pool);
if (!page)
return NULL;
*from_pool = true;
va = page_to_virt(page);
}
*da = dma_map_single(dev, va + rxq->headroom, rxq->datasize,
DMA_FROM_DEVICE);
if (dma_mapping_error(dev, *da)) {
if (*from_pool)
page_pool_put_full_page(rxq->page_pool, page, false);
else
put_page(virt_to_head_page(va));
return NULL;
}
return va;
}
/* Allocate frag for rx buffer, and save the old buf */
static void mana_refill_rx_oob(struct device *dev, struct mana_rxq *rxq,
struct mana_recv_buf_oob *rxoob, void **old_buf,
bool *old_fp)
{
bool from_pool;
dma_addr_t da;
void *va;
va = mana_get_rxfrag(rxq, dev, &da, &from_pool, true);
if (!va)
return;
dma_unmap_single(dev, rxoob->sgl[0].address, rxq->datasize,
DMA_FROM_DEVICE);
*old_buf = rxoob->buf_va;
*old_fp = rxoob->from_pool;
rxoob->buf_va = va;
rxoob->sgl[0].address = da;
rxoob->from_pool = from_pool;
}
static void mana_process_rx_cqe(struct mana_rxq *rxq, struct mana_cq *cq,
struct gdma_comp *cqe)
{
struct mana_rxcomp_oob *oob = (struct mana_rxcomp_oob *)cqe->cqe_data;
struct gdma_context *gc = rxq->gdma_rq->gdma_dev->gdma_context;
struct net_device *ndev = rxq->ndev;
struct mana_recv_buf_oob *rxbuf_oob;
struct mana_port_context *apc;
struct device *dev = gc->dev;
void *old_buf = NULL;
u32 curr, pktlen;
bool old_fp;
apc = netdev_priv(ndev);
switch (oob->cqe_hdr.cqe_type) {
case CQE_RX_OKAY:
break;
case CQE_RX_TRUNCATED:
++ndev->stats.rx_dropped;
rxbuf_oob = &rxq->rx_oobs[rxq->buf_index];
netdev_warn_once(ndev, "Dropped a truncated packet\n");
goto drop;
case CQE_RX_COALESCED_4:
netdev_err(ndev, "RX coalescing is unsupported\n");
apc->eth_stats.rx_coalesced_err++;
return;
case CQE_RX_OBJECT_FENCE:
complete(&rxq->fence_event);
return;
default:
netdev_err(ndev, "Unknown RX CQE type = %d\n",
oob->cqe_hdr.cqe_type);
apc->eth_stats.rx_cqe_unknown_type++;
return;
}
pktlen = oob->ppi[0].pkt_len;
if (pktlen == 0) {
/* data packets should never have packetlength of zero */
netdev_err(ndev, "RX pkt len=0, rq=%u, cq=%u, rxobj=0x%llx\n",
rxq->gdma_id, cq->gdma_id, rxq->rxobj);
return;
}
curr = rxq->buf_index;
rxbuf_oob = &rxq->rx_oobs[curr];
WARN_ON_ONCE(rxbuf_oob->wqe_inf.wqe_size_in_bu != 1);
mana_refill_rx_oob(dev, rxq, rxbuf_oob, &old_buf, &old_fp);
/* Unsuccessful refill will have old_buf == NULL.
* In this case, mana_rx_skb() will drop the packet.
*/
mana_rx_skb(old_buf, old_fp, oob, rxq);
drop:
mana_move_wq_tail(rxq->gdma_rq, rxbuf_oob->wqe_inf.wqe_size_in_bu);
mana_post_pkt_rxq(rxq);
}
static void mana_poll_rx_cq(struct mana_cq *cq)
{
struct gdma_comp *comp = cq->gdma_comp_buf;
struct mana_rxq *rxq = cq->rxq;
int comp_read, i;
comp_read = mana_gd_poll_cq(cq->gdma_cq, comp, CQE_POLLING_BUFFER);
WARN_ON_ONCE(comp_read > CQE_POLLING_BUFFER);
rxq->xdp_flush = false;
for (i = 0; i < comp_read; i++) {
if (WARN_ON_ONCE(comp[i].is_sq))
return;
/* verify recv cqe references the right rxq */
if (WARN_ON_ONCE(comp[i].wq_num != cq->rxq->gdma_id))
return;
mana_process_rx_cqe(rxq, cq, &comp[i]);
}
if (comp_read > 0) {
struct gdma_context *gc = rxq->gdma_rq->gdma_dev->gdma_context;
mana_gd_wq_ring_doorbell(gc, rxq->gdma_rq);
}
if (rxq->xdp_flush)
xdp_do_flush();
}
static int mana_cq_handler(void *context, struct gdma_queue *gdma_queue)
{
struct mana_cq *cq = context;
u8 arm_bit;
int w;
WARN_ON_ONCE(cq->gdma_cq != gdma_queue);
if (cq->type == MANA_CQ_TYPE_RX)
mana_poll_rx_cq(cq);
else
mana_poll_tx_cq(cq);
w = cq->work_done;
if (w < cq->budget &&
napi_complete_done(&cq->napi, w)) {
arm_bit = SET_ARM_BIT;
} else {
arm_bit = 0;
}
mana_gd_ring_cq(gdma_queue, arm_bit);
return w;
}
static int mana_poll(struct napi_struct *napi, int budget)
{
struct mana_cq *cq = container_of(napi, struct mana_cq, napi);
int w;
cq->work_done = 0;
cq->budget = budget;
w = mana_cq_handler(cq, cq->gdma_cq);
return min(w, budget);
}
static void mana_schedule_napi(void *context, struct gdma_queue *gdma_queue)
{
struct mana_cq *cq = context;
napi_schedule_irqoff(&cq->napi);
}
static void mana_deinit_cq(struct mana_port_context *apc, struct mana_cq *cq)
{
struct gdma_dev *gd = apc->ac->gdma_dev;
if (!cq->gdma_cq)
return;
mana_gd_destroy_queue(gd->gdma_context, cq->gdma_cq);
}
static void mana_deinit_txq(struct mana_port_context *apc, struct mana_txq *txq)
{
struct gdma_dev *gd = apc->ac->gdma_dev;
if (!txq->gdma_sq)
return;
mana_gd_destroy_queue(gd->gdma_context, txq->gdma_sq);
}
static void mana_destroy_txq(struct mana_port_context *apc)
{
struct napi_struct *napi;
int i;
if (!apc->tx_qp)
return;
for (i = 0; i < apc->num_queues; i++) {
napi = &apc->tx_qp[i].tx_cq.napi;
napi_synchronize(napi);
napi_disable(napi);
netif_napi_del(napi);
mana_destroy_wq_obj(apc, GDMA_SQ, apc->tx_qp[i].tx_object);
mana_deinit_cq(apc, &apc->tx_qp[i].tx_cq);
mana_deinit_txq(apc, &apc->tx_qp[i].txq);
}
kfree(apc->tx_qp);
apc->tx_qp = NULL;
}
static int mana_create_txq(struct mana_port_context *apc,
struct net_device *net)
{
struct mana_context *ac = apc->ac;
struct gdma_dev *gd = ac->gdma_dev;
struct mana_obj_spec wq_spec;
struct mana_obj_spec cq_spec;
struct gdma_queue_spec spec;
struct gdma_context *gc;
struct mana_txq *txq;
struct mana_cq *cq;
u32 txq_size;
u32 cq_size;
int err;
int i;
apc->tx_qp = kcalloc(apc->num_queues, sizeof(struct mana_tx_qp),
GFP_KERNEL);
if (!apc->tx_qp)
return -ENOMEM;
/* The minimum size of the WQE is 32 bytes, hence
* MAX_SEND_BUFFERS_PER_QUEUE represents the maximum number of WQEs
* the SQ can store. This value is then used to size other queues
* to prevent overflow.
*/
txq_size = MAX_SEND_BUFFERS_PER_QUEUE * 32;
BUILD_BUG_ON(!PAGE_ALIGNED(txq_size));
cq_size = MAX_SEND_BUFFERS_PER_QUEUE * COMP_ENTRY_SIZE;
cq_size = PAGE_ALIGN(cq_size);
gc = gd->gdma_context;
for (i = 0; i < apc->num_queues; i++) {
apc->tx_qp[i].tx_object = INVALID_MANA_HANDLE;
/* Create SQ */
txq = &apc->tx_qp[i].txq;
u64_stats_init(&txq->stats.syncp);
txq->ndev = net;
txq->net_txq = netdev_get_tx_queue(net, i);
txq->vp_offset = apc->tx_vp_offset;
skb_queue_head_init(&txq->pending_skbs);
memset(&spec, 0, sizeof(spec));
spec.type = GDMA_SQ;
spec.monitor_avl_buf = true;
spec.queue_size = txq_size;
err = mana_gd_create_mana_wq_cq(gd, &spec, &txq->gdma_sq);
if (err)
goto out;
/* Create SQ's CQ */
cq = &apc->tx_qp[i].tx_cq;
cq->type = MANA_CQ_TYPE_TX;
cq->txq = txq;
memset(&spec, 0, sizeof(spec));
spec.type = GDMA_CQ;
spec.monitor_avl_buf = false;
spec.queue_size = cq_size;
spec.cq.callback = mana_schedule_napi;
spec.cq.parent_eq = ac->eqs[i].eq;
spec.cq.context = cq;
err = mana_gd_create_mana_wq_cq(gd, &spec, &cq->gdma_cq);
if (err)
goto out;
memset(&wq_spec, 0, sizeof(wq_spec));
memset(&cq_spec, 0, sizeof(cq_spec));
wq_spec.gdma_region = txq->gdma_sq->mem_info.dma_region_handle;
wq_spec.queue_size = txq->gdma_sq->queue_size;
cq_spec.gdma_region = cq->gdma_cq->mem_info.dma_region_handle;
cq_spec.queue_size = cq->gdma_cq->queue_size;
cq_spec.modr_ctx_id = 0;
cq_spec.attached_eq = cq->gdma_cq->cq.parent->id;
err = mana_create_wq_obj(apc, apc->port_handle, GDMA_SQ,
&wq_spec, &cq_spec,
&apc->tx_qp[i].tx_object);
if (err)
goto out;
txq->gdma_sq->id = wq_spec.queue_index;
cq->gdma_cq->id = cq_spec.queue_index;
txq->gdma_sq->mem_info.dma_region_handle =
GDMA_INVALID_DMA_REGION;
cq->gdma_cq->mem_info.dma_region_handle =
GDMA_INVALID_DMA_REGION;
txq->gdma_txq_id = txq->gdma_sq->id;
cq->gdma_id = cq->gdma_cq->id;
if (WARN_ON(cq->gdma_id >= gc->max_num_cqs)) {
err = -EINVAL;
goto out;
}
gc->cq_table[cq->gdma_id] = cq->gdma_cq;
netif_napi_add_tx(net, &cq->napi, mana_poll);
napi_enable(&cq->napi);
mana_gd_ring_cq(cq->gdma_cq, SET_ARM_BIT);
}
return 0;
out:
mana_destroy_txq(apc);
return err;
}
static void mana_destroy_rxq(struct mana_port_context *apc,
struct mana_rxq *rxq, bool validate_state)
{
struct gdma_context *gc = apc->ac->gdma_dev->gdma_context;
struct mana_recv_buf_oob *rx_oob;
struct device *dev = gc->dev;
struct napi_struct *napi;
struct page *page;
int i;
if (!rxq)
return;
napi = &rxq->rx_cq.napi;
if (validate_state)
napi_synchronize(napi);
napi_disable(napi);
xdp_rxq_info_unreg(&rxq->xdp_rxq);
netif_napi_del(napi);
mana_destroy_wq_obj(apc, GDMA_RQ, rxq->rxobj);
mana_deinit_cq(apc, &rxq->rx_cq);
if (rxq->xdp_save_va)
put_page(virt_to_head_page(rxq->xdp_save_va));
for (i = 0; i < rxq->num_rx_buf; i++) {
rx_oob = &rxq->rx_oobs[i];
if (!rx_oob->buf_va)
continue;
dma_unmap_single(dev, rx_oob->sgl[0].address,
rx_oob->sgl[0].size, DMA_FROM_DEVICE);
page = virt_to_head_page(rx_oob->buf_va);
if (rx_oob->from_pool)
page_pool_put_full_page(rxq->page_pool, page, false);
else
put_page(page);
rx_oob->buf_va = NULL;
}
page_pool_destroy(rxq->page_pool);
if (rxq->gdma_rq)
mana_gd_destroy_queue(gc, rxq->gdma_rq);
kfree(rxq);
}
static int mana_fill_rx_oob(struct mana_recv_buf_oob *rx_oob, u32 mem_key,
struct mana_rxq *rxq, struct device *dev)
{
struct mana_port_context *mpc = netdev_priv(rxq->ndev);
bool from_pool = false;
dma_addr_t da;
void *va;
if (mpc->rxbufs_pre)
va = mana_get_rxbuf_pre(rxq, &da);
else
va = mana_get_rxfrag(rxq, dev, &da, &from_pool, false);
if (!va)
return -ENOMEM;
rx_oob->buf_va = va;
rx_oob->from_pool = from_pool;
rx_oob->sgl[0].address = da;
rx_oob->sgl[0].size = rxq->datasize;
rx_oob->sgl[0].mem_key = mem_key;
return 0;
}
#define MANA_WQE_HEADER_SIZE 16
#define MANA_WQE_SGE_SIZE 16
static int mana_alloc_rx_wqe(struct mana_port_context *apc,
struct mana_rxq *rxq, u32 *rxq_size, u32 *cq_size)
{
struct gdma_context *gc = apc->ac->gdma_dev->gdma_context;
struct mana_recv_buf_oob *rx_oob;
struct device *dev = gc->dev;
u32 buf_idx;
int ret;
WARN_ON(rxq->datasize == 0);
*rxq_size = 0;
*cq_size = 0;
for (buf_idx = 0; buf_idx < rxq->num_rx_buf; buf_idx++) {
rx_oob = &rxq->rx_oobs[buf_idx];
memset(rx_oob, 0, sizeof(*rx_oob));
rx_oob->num_sge = 1;
ret = mana_fill_rx_oob(rx_oob, apc->ac->gdma_dev->gpa_mkey, rxq,
dev);
if (ret)
return ret;
rx_oob->wqe_req.sgl = rx_oob->sgl;
rx_oob->wqe_req.num_sge = rx_oob->num_sge;
rx_oob->wqe_req.inline_oob_size = 0;
rx_oob->wqe_req.inline_oob_data = NULL;
rx_oob->wqe_req.flags = 0;
rx_oob->wqe_req.client_data_unit = 0;
*rxq_size += ALIGN(MANA_WQE_HEADER_SIZE +
MANA_WQE_SGE_SIZE * rx_oob->num_sge, 32);
*cq_size += COMP_ENTRY_SIZE;
}
return 0;
}
static int mana_push_wqe(struct mana_rxq *rxq)
{
struct mana_recv_buf_oob *rx_oob;
u32 buf_idx;
int err;
for (buf_idx = 0; buf_idx < rxq->num_rx_buf; buf_idx++) {
rx_oob = &rxq->rx_oobs[buf_idx];
err = mana_gd_post_and_ring(rxq->gdma_rq, &rx_oob->wqe_req,
&rx_oob->wqe_inf);
if (err)
return -ENOSPC;
}
return 0;
}
static int mana_create_page_pool(struct mana_rxq *rxq, struct gdma_context *gc)
{
struct page_pool_params pprm = {};
int ret;
pprm.pool_size = RX_BUFFERS_PER_QUEUE;
pprm.nid = gc->numa_node;
pprm.napi = &rxq->rx_cq.napi;
rxq->page_pool = page_pool_create(&pprm);
if (IS_ERR(rxq->page_pool)) {
ret = PTR_ERR(rxq->page_pool);
rxq->page_pool = NULL;
return ret;
}
return 0;
}
static struct mana_rxq *mana_create_rxq(struct mana_port_context *apc,
u32 rxq_idx, struct mana_eq *eq,
struct net_device *ndev)
{
struct gdma_dev *gd = apc->ac->gdma_dev;
struct mana_obj_spec wq_spec;
struct mana_obj_spec cq_spec;
struct gdma_queue_spec spec;
struct mana_cq *cq = NULL;
struct gdma_context *gc;
u32 cq_size, rq_size;
struct mana_rxq *rxq;
int err;
gc = gd->gdma_context;
rxq = kzalloc(struct_size(rxq, rx_oobs, RX_BUFFERS_PER_QUEUE),
GFP_KERNEL);
if (!rxq)
return NULL;
rxq->ndev = ndev;
rxq->num_rx_buf = RX_BUFFERS_PER_QUEUE;
rxq->rxq_idx = rxq_idx;
rxq->rxobj = INVALID_MANA_HANDLE;
mana_get_rxbuf_cfg(ndev->mtu, &rxq->datasize, &rxq->alloc_size,
&rxq->headroom);
/* Create page pool for RX queue */
err = mana_create_page_pool(rxq, gc);
if (err) {
netdev_err(ndev, "Create page pool err:%d\n", err);
goto out;
}
err = mana_alloc_rx_wqe(apc, rxq, &rq_size, &cq_size);
if (err)
goto out;
rq_size = PAGE_ALIGN(rq_size);
cq_size = PAGE_ALIGN(cq_size);
/* Create RQ */
memset(&spec, 0, sizeof(spec));
spec.type = GDMA_RQ;
spec.monitor_avl_buf = true;
spec.queue_size = rq_size;
err = mana_gd_create_mana_wq_cq(gd, &spec, &rxq->gdma_rq);
if (err)
goto out;
/* Create RQ's CQ */
cq = &rxq->rx_cq;
cq->type = MANA_CQ_TYPE_RX;
cq->rxq = rxq;
memset(&spec, 0, sizeof(spec));
spec.type = GDMA_CQ;
spec.monitor_avl_buf = false;
spec.queue_size = cq_size;
spec.cq.callback = mana_schedule_napi;
spec.cq.parent_eq = eq->eq;
spec.cq.context = cq;
err = mana_gd_create_mana_wq_cq(gd, &spec, &cq->gdma_cq);
if (err)
goto out;
memset(&wq_spec, 0, sizeof(wq_spec));
memset(&cq_spec, 0, sizeof(cq_spec));
wq_spec.gdma_region = rxq->gdma_rq->mem_info.dma_region_handle;
wq_spec.queue_size = rxq->gdma_rq->queue_size;
cq_spec.gdma_region = cq->gdma_cq->mem_info.dma_region_handle;
cq_spec.queue_size = cq->gdma_cq->queue_size;
cq_spec.modr_ctx_id = 0;
cq_spec.attached_eq = cq->gdma_cq->cq.parent->id;
err = mana_create_wq_obj(apc, apc->port_handle, GDMA_RQ,
&wq_spec, &cq_spec, &rxq->rxobj);
if (err)
goto out;
rxq->gdma_rq->id = wq_spec.queue_index;
cq->gdma_cq->id = cq_spec.queue_index;
rxq->gdma_rq->mem_info.dma_region_handle = GDMA_INVALID_DMA_REGION;
cq->gdma_cq->mem_info.dma_region_handle = GDMA_INVALID_DMA_REGION;
rxq->gdma_id = rxq->gdma_rq->id;
cq->gdma_id = cq->gdma_cq->id;
err = mana_push_wqe(rxq);
if (err)
goto out;
if (WARN_ON(cq->gdma_id >= gc->max_num_cqs)) {
err = -EINVAL;
goto out;
}
gc->cq_table[cq->gdma_id] = cq->gdma_cq;
netif_napi_add_weight(ndev, &cq->napi, mana_poll, 1);
WARN_ON(xdp_rxq_info_reg(&rxq->xdp_rxq, ndev, rxq_idx,
cq->napi.napi_id));
WARN_ON(xdp_rxq_info_reg_mem_model(&rxq->xdp_rxq, MEM_TYPE_PAGE_POOL,
rxq->page_pool));
napi_enable(&cq->napi);
mana_gd_ring_cq(cq->gdma_cq, SET_ARM_BIT);
out:
if (!err)
return rxq;
netdev_err(ndev, "Failed to create RXQ: err = %d\n", err);
mana_destroy_rxq(apc, rxq, false);
if (cq)
mana_deinit_cq(apc, cq);
return NULL;
}
static int mana_add_rx_queues(struct mana_port_context *apc,
struct net_device *ndev)
{
struct mana_context *ac = apc->ac;
struct mana_rxq *rxq;
int err = 0;
int i;
for (i = 0; i < apc->num_queues; i++) {
rxq = mana_create_rxq(apc, i, &ac->eqs[i], ndev);
if (!rxq) {
err = -ENOMEM;
goto out;
}
u64_stats_init(&rxq->stats.syncp);
apc->rxqs[i] = rxq;
}
apc->default_rxobj = apc->rxqs[0]->rxobj;
out:
return err;
}
static void mana_destroy_vport(struct mana_port_context *apc)
{
struct gdma_dev *gd = apc->ac->gdma_dev;
struct mana_rxq *rxq;
u32 rxq_idx;
for (rxq_idx = 0; rxq_idx < apc->num_queues; rxq_idx++) {
rxq = apc->rxqs[rxq_idx];
if (!rxq)
continue;
mana_destroy_rxq(apc, rxq, true);
apc->rxqs[rxq_idx] = NULL;
}
mana_destroy_txq(apc);
mana_uncfg_vport(apc);
if (gd->gdma_context->is_pf)
mana_pf_deregister_hw_vport(apc);
}
static int mana_create_vport(struct mana_port_context *apc,
struct net_device *net)
{
struct gdma_dev *gd = apc->ac->gdma_dev;
int err;
apc->default_rxobj = INVALID_MANA_HANDLE;
if (gd->gdma_context->is_pf) {
err = mana_pf_register_hw_vport(apc);
if (err)
return err;
}
err = mana_cfg_vport(apc, gd->pdid, gd->doorbell);
if (err)
return err;
return mana_create_txq(apc, net);
}
static void mana_rss_table_init(struct mana_port_context *apc)
{
int i;
for (i = 0; i < MANA_INDIRECT_TABLE_SIZE; i++)
apc->indir_table[i] =
ethtool_rxfh_indir_default(i, apc->num_queues);
}
int mana_config_rss(struct mana_port_context *apc, enum TRI_STATE rx,
bool update_hash, bool update_tab)
{
u32 queue_idx;
int err;
int i;
if (update_tab) {
for (i = 0; i < MANA_INDIRECT_TABLE_SIZE; i++) {
queue_idx = apc->indir_table[i];
apc->rxobj_table[i] = apc->rxqs[queue_idx]->rxobj;
}
}
err = mana_cfg_vport_steering(apc, rx, true, update_hash, update_tab);
if (err)
return err;
mana_fence_rqs(apc);
return 0;
}
void mana_query_gf_stats(struct mana_port_context *apc)
{
struct mana_query_gf_stat_resp resp = {};
struct mana_query_gf_stat_req req = {};
struct net_device *ndev = apc->ndev;
int err;
mana_gd_init_req_hdr(&req.hdr, MANA_QUERY_GF_STAT,
sizeof(req), sizeof(resp));
req.req_stats = STATISTICS_FLAGS_HC_TX_BYTES |
STATISTICS_FLAGS_HC_TX_UCAST_PACKETS |
STATISTICS_FLAGS_HC_TX_UCAST_BYTES |
STATISTICS_FLAGS_HC_TX_MCAST_PACKETS |
STATISTICS_FLAGS_HC_TX_MCAST_BYTES |
STATISTICS_FLAGS_HC_TX_BCAST_PACKETS |
STATISTICS_FLAGS_HC_TX_BCAST_BYTES;
err = mana_send_request(apc->ac, &req, sizeof(req), &resp,
sizeof(resp));
if (err) {
netdev_err(ndev, "Failed to query GF stats: %d\n", err);
return;
}
err = mana_verify_resp_hdr(&resp.hdr, MANA_QUERY_GF_STAT,
sizeof(resp));
if (err || resp.hdr.status) {
netdev_err(ndev, "Failed to query GF stats: %d, 0x%x\n", err,
resp.hdr.status);
return;
}
apc->eth_stats.hc_tx_bytes = resp.hc_tx_bytes;
apc->eth_stats.hc_tx_ucast_pkts = resp.hc_tx_ucast_pkts;
apc->eth_stats.hc_tx_ucast_bytes = resp.hc_tx_ucast_bytes;
apc->eth_stats.hc_tx_bcast_pkts = resp.hc_tx_bcast_pkts;
apc->eth_stats.hc_tx_bcast_bytes = resp.hc_tx_bcast_bytes;
apc->eth_stats.hc_tx_mcast_pkts = resp.hc_tx_mcast_pkts;
apc->eth_stats.hc_tx_mcast_bytes = resp.hc_tx_mcast_bytes;
}
static int mana_init_port(struct net_device *ndev)
{
struct mana_port_context *apc = netdev_priv(ndev);
u32 max_txq, max_rxq, max_queues;
int port_idx = apc->port_idx;
u32 num_indirect_entries;
int err;
err = mana_init_port_context(apc);
if (err)
return err;
err = mana_query_vport_cfg(apc, port_idx, &max_txq, &max_rxq,
&num_indirect_entries);
if (err) {
netdev_err(ndev, "Failed to query info for vPort %d\n",
port_idx);
goto reset_apc;
}
max_queues = min_t(u32, max_txq, max_rxq);
if (apc->max_queues > max_queues)
apc->max_queues = max_queues;
if (apc->num_queues > apc->max_queues)
apc->num_queues = apc->max_queues;
eth_hw_addr_set(ndev, apc->mac_addr);
return 0;
reset_apc:
kfree(apc->rxqs);
apc->rxqs = NULL;
return err;
}
int mana_alloc_queues(struct net_device *ndev)
{
struct mana_port_context *apc = netdev_priv(ndev);
struct gdma_dev *gd = apc->ac->gdma_dev;
int err;
err = mana_create_vport(apc, ndev);
if (err)
return err;
err = netif_set_real_num_tx_queues(ndev, apc->num_queues);
if (err)
goto destroy_vport;
err = mana_add_rx_queues(apc, ndev);
if (err)
goto destroy_vport;
apc->rss_state = apc->num_queues > 1 ? TRI_STATE_TRUE : TRI_STATE_FALSE;
err = netif_set_real_num_rx_queues(ndev, apc->num_queues);
if (err)
goto destroy_vport;
mana_rss_table_init(apc);
err = mana_config_rss(apc, TRI_STATE_TRUE, true, true);
if (err)
goto destroy_vport;
if (gd->gdma_context->is_pf) {
err = mana_pf_register_filter(apc);
if (err)
goto destroy_vport;
}
mana_chn_setxdp(apc, mana_xdp_get(apc));
return 0;
destroy_vport:
mana_destroy_vport(apc);
return err;
}
int mana_attach(struct net_device *ndev)
{
struct mana_port_context *apc = netdev_priv(ndev);
int err;
ASSERT_RTNL();
err = mana_init_port(ndev);
if (err)
return err;
if (apc->port_st_save) {
err = mana_alloc_queues(ndev);
if (err) {
mana_cleanup_port_context(apc);
return err;
}
}
apc->port_is_up = apc->port_st_save;
/* Ensure port state updated before txq state */
smp_wmb();
if (apc->port_is_up)
netif_carrier_on(ndev);
netif_device_attach(ndev);
return 0;
}
static int mana_dealloc_queues(struct net_device *ndev)
{
struct mana_port_context *apc = netdev_priv(ndev);
unsigned long timeout = jiffies + 120 * HZ;
struct gdma_dev *gd = apc->ac->gdma_dev;
struct mana_txq *txq;
struct sk_buff *skb;
int i, err;
u32 tsleep;
if (apc->port_is_up)
return -EINVAL;
mana_chn_setxdp(apc, NULL);
if (gd->gdma_context->is_pf)
mana_pf_deregister_filter(apc);
/* No packet can be transmitted now since apc->port_is_up is false.
* There is still a tiny chance that mana_poll_tx_cq() can re-enable
* a txq because it may not timely see apc->port_is_up being cleared
* to false, but it doesn't matter since mana_start_xmit() drops any
* new packets due to apc->port_is_up being false.
*
* Drain all the in-flight TX packets.
* A timeout of 120 seconds for all the queues is used.
* This will break the while loop when h/w is not responding.
* This value of 120 has been decided here considering max
* number of queues.
*/
for (i = 0; i < apc->num_queues; i++) {
txq = &apc->tx_qp[i].txq;
tsleep = 1000;
while (atomic_read(&txq->pending_sends) > 0 &&
time_before(jiffies, timeout)) {
usleep_range(tsleep, tsleep + 1000);
tsleep <<= 1;
}
if (atomic_read(&txq->pending_sends)) {
err = pcie_flr(to_pci_dev(gd->gdma_context->dev));
if (err) {
netdev_err(ndev, "flr failed %d with %d pkts pending in txq %u\n",
err, atomic_read(&txq->pending_sends),
txq->gdma_txq_id);
}
break;
}
}
for (i = 0; i < apc->num_queues; i++) {
txq = &apc->tx_qp[i].txq;
while ((skb = skb_dequeue(&txq->pending_skbs))) {
mana_unmap_skb(skb, apc);
dev_kfree_skb_any(skb);
}
atomic_set(&txq->pending_sends, 0);
}
/* We're 100% sure the queues can no longer be woken up, because
* we're sure now mana_poll_tx_cq() can't be running.
*/
apc->rss_state = TRI_STATE_FALSE;
err = mana_config_rss(apc, TRI_STATE_FALSE, false, false);
if (err) {
netdev_err(ndev, "Failed to disable vPort: %d\n", err);
return err;
}
mana_destroy_vport(apc);
return 0;
}
int mana_detach(struct net_device *ndev, bool from_close)
{
struct mana_port_context *apc = netdev_priv(ndev);
int err;
ASSERT_RTNL();
apc->port_st_save = apc->port_is_up;
apc->port_is_up = false;
/* Ensure port state updated before txq state */
smp_wmb();
netif_tx_disable(ndev);
netif_carrier_off(ndev);
if (apc->port_st_save) {
err = mana_dealloc_queues(ndev);
if (err)
return err;
}
if (!from_close) {
netif_device_detach(ndev);
mana_cleanup_port_context(apc);
}
return 0;
}
static int mana_probe_port(struct mana_context *ac, int port_idx,
struct net_device **ndev_storage)
{
struct gdma_context *gc = ac->gdma_dev->gdma_context;
struct mana_port_context *apc;
struct net_device *ndev;
int err;
ndev = alloc_etherdev_mq(sizeof(struct mana_port_context),
gc->max_num_queues);
if (!ndev)
return -ENOMEM;
*ndev_storage = ndev;
apc = netdev_priv(ndev);
apc->ac = ac;
apc->ndev = ndev;
apc->max_queues = gc->max_num_queues;
apc->num_queues = gc->max_num_queues;
apc->port_handle = INVALID_MANA_HANDLE;
apc->pf_filter_handle = INVALID_MANA_HANDLE;
apc->port_idx = port_idx;
mutex_init(&apc->vport_mutex);
apc->vport_use_count = 0;
ndev->netdev_ops = &mana_devops;
ndev->ethtool_ops = &mana_ethtool_ops;
ndev->mtu = ETH_DATA_LEN;
ndev->max_mtu = gc->adapter_mtu - ETH_HLEN;
ndev->min_mtu = ETH_MIN_MTU;
ndev->needed_headroom = MANA_HEADROOM;
ndev->dev_port = port_idx;
SET_NETDEV_DEV(ndev, gc->dev);
netif_carrier_off(ndev);
netdev_rss_key_fill(apc->hashkey, MANA_HASH_KEY_SIZE);
err = mana_init_port(ndev);
if (err)
goto free_net;
netdev_lockdep_set_classes(ndev);
ndev->hw_features = NETIF_F_SG | NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM;
ndev->hw_features |= NETIF_F_RXCSUM;
ndev->hw_features |= NETIF_F_TSO | NETIF_F_TSO6;
ndev->hw_features |= NETIF_F_RXHASH;
ndev->features = ndev->hw_features | NETIF_F_HW_VLAN_CTAG_TX |
NETIF_F_HW_VLAN_CTAG_RX;
ndev->vlan_features = ndev->features;
ndev->xdp_features = NETDEV_XDP_ACT_BASIC | NETDEV_XDP_ACT_REDIRECT |
NETDEV_XDP_ACT_NDO_XMIT;
err = register_netdev(ndev);
if (err) {
netdev_err(ndev, "Unable to register netdev.\n");
goto reset_apc;
}
return 0;
reset_apc:
kfree(apc->rxqs);
apc->rxqs = NULL;
free_net:
*ndev_storage = NULL;
netdev_err(ndev, "Failed to probe vPort %d: %d\n", port_idx, err);
free_netdev(ndev);
return err;
}
static void adev_release(struct device *dev)
{
struct mana_adev *madev = container_of(dev, struct mana_adev, adev.dev);
kfree(madev);
}
static void remove_adev(struct gdma_dev *gd)
{
struct auxiliary_device *adev = gd->adev;
int id = adev->id;
auxiliary_device_delete(adev);
auxiliary_device_uninit(adev);
mana_adev_idx_free(id);
gd->adev = NULL;
}
static int add_adev(struct gdma_dev *gd)
{
struct auxiliary_device *adev;
struct mana_adev *madev;
int ret;
madev = kzalloc(sizeof(*madev), GFP_KERNEL);
if (!madev)
return -ENOMEM;
adev = &madev->adev;
ret = mana_adev_idx_alloc();
if (ret < 0)
goto idx_fail;
adev->id = ret;
adev->name = "rdma";
adev->dev.parent = gd->gdma_context->dev;
adev->dev.release = adev_release;
madev->mdev = gd;
ret = auxiliary_device_init(adev);
if (ret)
goto init_fail;
ret = auxiliary_device_add(adev);
if (ret)
goto add_fail;
gd->adev = adev;
return 0;
add_fail:
auxiliary_device_uninit(adev);
init_fail:
mana_adev_idx_free(adev->id);
idx_fail:
kfree(madev);
return ret;
}
int mana_probe(struct gdma_dev *gd, bool resuming)
{
struct gdma_context *gc = gd->gdma_context;
struct mana_context *ac = gd->driver_data;
struct device *dev = gc->dev;
u16 num_ports = 0;
int err;
int i;
dev_info(dev,
"Microsoft Azure Network Adapter protocol version: %d.%d.%d\n",
MANA_MAJOR_VERSION, MANA_MINOR_VERSION, MANA_MICRO_VERSION);
err = mana_gd_register_device(gd);
if (err)
return err;
if (!resuming) {
ac = kzalloc(sizeof(*ac), GFP_KERNEL);
if (!ac)
return -ENOMEM;
ac->gdma_dev = gd;
gd->driver_data = ac;
}
err = mana_create_eq(ac);
if (err)
goto out;
err = mana_query_device_cfg(ac, MANA_MAJOR_VERSION, MANA_MINOR_VERSION,
MANA_MICRO_VERSION, &num_ports);
if (err)
goto out;
if (!resuming) {
ac->num_ports = num_ports;
} else {
if (ac->num_ports != num_ports) {
dev_err(dev, "The number of vPorts changed: %d->%d\n",
ac->num_ports, num_ports);
err = -EPROTO;
goto out;
}
}
if (ac->num_ports == 0)
dev_err(dev, "Failed to detect any vPort\n");
if (ac->num_ports > MAX_PORTS_IN_MANA_DEV)
ac->num_ports = MAX_PORTS_IN_MANA_DEV;
if (!resuming) {
for (i = 0; i < ac->num_ports; i++) {
err = mana_probe_port(ac, i, &ac->ports[i]);
if (err)
break;
}
} else {
for (i = 0; i < ac->num_ports; i++) {
rtnl_lock();
err = mana_attach(ac->ports[i]);
rtnl_unlock();
if (err)
break;
}
}
err = add_adev(gd);
out:
if (err)
mana_remove(gd, false);
return err;
}
void mana_remove(struct gdma_dev *gd, bool suspending)
{
struct gdma_context *gc = gd->gdma_context;
struct mana_context *ac = gd->driver_data;
struct device *dev = gc->dev;
struct net_device *ndev;
int err;
int i;
/* adev currently doesn't support suspending, always remove it */
if (gd->adev)
remove_adev(gd);
for (i = 0; i < ac->num_ports; i++) {
ndev = ac->ports[i];
if (!ndev) {
if (i == 0)
dev_err(dev, "No net device to remove\n");
goto out;
}
/* All cleanup actions should stay after rtnl_lock(), otherwise
* other functions may access partially cleaned up data.
*/
rtnl_lock();
err = mana_detach(ndev, false);
if (err)
netdev_err(ndev, "Failed to detach vPort %d: %d\n",
i, err);
if (suspending) {
/* No need to unregister the ndev. */
rtnl_unlock();
continue;
}
unregister_netdevice(ndev);
rtnl_unlock();
free_netdev(ndev);
}
mana_destroy_eq(ac);
out:
mana_gd_deregister_device(gd);
if (suspending)
return;
gd->driver_data = NULL;
gd->gdma_context = NULL;
kfree(ac);
}
|
linux-master
|
drivers/net/ethernet/microsoft/mana/mana_en.c
|
// SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
/* Copyright (c) 2021, Microsoft Corporation. */
#include <linux/inetdevice.h>
#include <linux/etherdevice.h>
#include <linux/mm.h>
#include <linux/bpf.h>
#include <linux/bpf_trace.h>
#include <net/xdp.h>
#include <net/mana/mana.h>
void mana_xdp_tx(struct sk_buff *skb, struct net_device *ndev)
{
u16 txq_idx = skb_get_queue_mapping(skb);
struct netdev_queue *ndevtxq;
int rc;
__skb_push(skb, ETH_HLEN);
ndevtxq = netdev_get_tx_queue(ndev, txq_idx);
__netif_tx_lock(ndevtxq, smp_processor_id());
rc = mana_start_xmit(skb, ndev);
__netif_tx_unlock(ndevtxq);
if (dev_xmit_complete(rc))
return;
dev_kfree_skb_any(skb);
ndev->stats.tx_dropped++;
}
static int mana_xdp_xmit_fm(struct net_device *ndev, struct xdp_frame *frame,
u16 q_idx)
{
struct sk_buff *skb;
skb = xdp_build_skb_from_frame(frame, ndev);
if (unlikely(!skb))
return -ENOMEM;
skb_set_queue_mapping(skb, q_idx);
mana_xdp_tx(skb, ndev);
return 0;
}
int mana_xdp_xmit(struct net_device *ndev, int n, struct xdp_frame **frames,
u32 flags)
{
struct mana_port_context *apc = netdev_priv(ndev);
struct mana_stats_tx *tx_stats;
int i, count = 0;
u16 q_idx;
if (unlikely(!apc->port_is_up))
return 0;
q_idx = smp_processor_id() % ndev->real_num_tx_queues;
for (i = 0; i < n; i++) {
if (mana_xdp_xmit_fm(ndev, frames[i], q_idx))
break;
count++;
}
tx_stats = &apc->tx_qp[q_idx].txq.stats;
u64_stats_update_begin(&tx_stats->syncp);
tx_stats->xdp_xmit += count;
u64_stats_update_end(&tx_stats->syncp);
return count;
}
u32 mana_run_xdp(struct net_device *ndev, struct mana_rxq *rxq,
struct xdp_buff *xdp, void *buf_va, uint pkt_len)
{
struct mana_stats_rx *rx_stats;
struct bpf_prog *prog;
u32 act = XDP_PASS;
rcu_read_lock();
prog = rcu_dereference(rxq->bpf_prog);
if (!prog)
goto out;
xdp_init_buff(xdp, PAGE_SIZE, &rxq->xdp_rxq);
xdp_prepare_buff(xdp, buf_va, XDP_PACKET_HEADROOM, pkt_len, false);
act = bpf_prog_run_xdp(prog, xdp);
rx_stats = &rxq->stats;
switch (act) {
case XDP_PASS:
case XDP_TX:
case XDP_DROP:
break;
case XDP_REDIRECT:
rxq->xdp_rc = xdp_do_redirect(ndev, xdp, prog);
if (!rxq->xdp_rc) {
rxq->xdp_flush = true;
u64_stats_update_begin(&rx_stats->syncp);
rx_stats->packets++;
rx_stats->bytes += pkt_len;
rx_stats->xdp_redirect++;
u64_stats_update_end(&rx_stats->syncp);
break;
}
fallthrough;
case XDP_ABORTED:
trace_xdp_exception(ndev, prog, act);
break;
default:
bpf_warn_invalid_xdp_action(ndev, prog, act);
}
out:
rcu_read_unlock();
return act;
}
struct bpf_prog *mana_xdp_get(struct mana_port_context *apc)
{
ASSERT_RTNL();
return apc->bpf_prog;
}
static struct bpf_prog *mana_chn_xdp_get(struct mana_port_context *apc)
{
return rtnl_dereference(apc->rxqs[0]->bpf_prog);
}
/* Set xdp program on channels */
void mana_chn_setxdp(struct mana_port_context *apc, struct bpf_prog *prog)
{
struct bpf_prog *old_prog = mana_chn_xdp_get(apc);
unsigned int num_queues = apc->num_queues;
int i;
ASSERT_RTNL();
if (old_prog == prog)
return;
if (prog)
bpf_prog_add(prog, num_queues);
for (i = 0; i < num_queues; i++)
rcu_assign_pointer(apc->rxqs[i]->bpf_prog, prog);
if (old_prog)
for (i = 0; i < num_queues; i++)
bpf_prog_put(old_prog);
}
static int mana_xdp_set(struct net_device *ndev, struct bpf_prog *prog,
struct netlink_ext_ack *extack)
{
struct mana_port_context *apc = netdev_priv(ndev);
struct bpf_prog *old_prog;
struct gdma_context *gc;
gc = apc->ac->gdma_dev->gdma_context;
old_prog = mana_xdp_get(apc);
if (!old_prog && !prog)
return 0;
if (prog && ndev->mtu > MANA_XDP_MTU_MAX) {
netdev_err(ndev, "XDP: mtu:%u too large, mtu_max:%lu\n",
ndev->mtu, MANA_XDP_MTU_MAX);
NL_SET_ERR_MSG_MOD(extack, "XDP: mtu too large");
return -EOPNOTSUPP;
}
/* One refcnt of the prog is hold by the caller already, so
* don't increase refcnt for this one.
*/
apc->bpf_prog = prog;
if (old_prog)
bpf_prog_put(old_prog);
if (apc->port_is_up)
mana_chn_setxdp(apc, prog);
if (prog)
ndev->max_mtu = MANA_XDP_MTU_MAX;
else
ndev->max_mtu = gc->adapter_mtu - ETH_HLEN;
return 0;
}
int mana_bpf(struct net_device *ndev, struct netdev_bpf *bpf)
{
struct netlink_ext_ack *extack = bpf->extack;
int ret;
switch (bpf->command) {
case XDP_SETUP_PROG:
return mana_xdp_set(ndev, bpf->prog, extack);
default:
return -EOPNOTSUPP;
}
return ret;
}
|
linux-master
|
drivers/net/ethernet/microsoft/mana/mana_bpf.c
|
// SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
/* Copyright (c) 2021, Microsoft Corporation. */
#include <linux/inetdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <net/mana/mana.h>
static const struct {
char name[ETH_GSTRING_LEN];
u16 offset;
} mana_eth_stats[] = {
{"stop_queue", offsetof(struct mana_ethtool_stats, stop_queue)},
{"wake_queue", offsetof(struct mana_ethtool_stats, wake_queue)},
{"hc_tx_bytes", offsetof(struct mana_ethtool_stats, hc_tx_bytes)},
{"hc_tx_ucast_pkts", offsetof(struct mana_ethtool_stats,
hc_tx_ucast_pkts)},
{"hc_tx_ucast_bytes", offsetof(struct mana_ethtool_stats,
hc_tx_ucast_bytes)},
{"hc_tx_bcast_pkts", offsetof(struct mana_ethtool_stats,
hc_tx_bcast_pkts)},
{"hc_tx_bcast_bytes", offsetof(struct mana_ethtool_stats,
hc_tx_bcast_bytes)},
{"hc_tx_mcast_pkts", offsetof(struct mana_ethtool_stats,
hc_tx_mcast_pkts)},
{"hc_tx_mcast_bytes", offsetof(struct mana_ethtool_stats,
hc_tx_mcast_bytes)},
{"tx_cq_err", offsetof(struct mana_ethtool_stats, tx_cqe_err)},
{"tx_cqe_unknown_type", offsetof(struct mana_ethtool_stats,
tx_cqe_unknown_type)},
{"rx_coalesced_err", offsetof(struct mana_ethtool_stats,
rx_coalesced_err)},
{"rx_cqe_unknown_type", offsetof(struct mana_ethtool_stats,
rx_cqe_unknown_type)},
};
static int mana_get_sset_count(struct net_device *ndev, int stringset)
{
struct mana_port_context *apc = netdev_priv(ndev);
unsigned int num_queues = apc->num_queues;
if (stringset != ETH_SS_STATS)
return -EINVAL;
return ARRAY_SIZE(mana_eth_stats) + num_queues *
(MANA_STATS_RX_COUNT + MANA_STATS_TX_COUNT);
}
static void mana_get_strings(struct net_device *ndev, u32 stringset, u8 *data)
{
struct mana_port_context *apc = netdev_priv(ndev);
unsigned int num_queues = apc->num_queues;
u8 *p = data;
int i;
if (stringset != ETH_SS_STATS)
return;
for (i = 0; i < ARRAY_SIZE(mana_eth_stats); i++) {
memcpy(p, mana_eth_stats[i].name, ETH_GSTRING_LEN);
p += ETH_GSTRING_LEN;
}
for (i = 0; i < num_queues; i++) {
sprintf(p, "rx_%d_packets", i);
p += ETH_GSTRING_LEN;
sprintf(p, "rx_%d_bytes", i);
p += ETH_GSTRING_LEN;
sprintf(p, "rx_%d_xdp_drop", i);
p += ETH_GSTRING_LEN;
sprintf(p, "rx_%d_xdp_tx", i);
p += ETH_GSTRING_LEN;
sprintf(p, "rx_%d_xdp_redirect", i);
p += ETH_GSTRING_LEN;
}
for (i = 0; i < num_queues; i++) {
sprintf(p, "tx_%d_packets", i);
p += ETH_GSTRING_LEN;
sprintf(p, "tx_%d_bytes", i);
p += ETH_GSTRING_LEN;
sprintf(p, "tx_%d_xdp_xmit", i);
p += ETH_GSTRING_LEN;
sprintf(p, "tx_%d_tso_packets", i);
p += ETH_GSTRING_LEN;
sprintf(p, "tx_%d_tso_bytes", i);
p += ETH_GSTRING_LEN;
sprintf(p, "tx_%d_tso_inner_packets", i);
p += ETH_GSTRING_LEN;
sprintf(p, "tx_%d_tso_inner_bytes", i);
p += ETH_GSTRING_LEN;
sprintf(p, "tx_%d_long_pkt_fmt", i);
p += ETH_GSTRING_LEN;
sprintf(p, "tx_%d_short_pkt_fmt", i);
p += ETH_GSTRING_LEN;
sprintf(p, "tx_%d_csum_partial", i);
p += ETH_GSTRING_LEN;
sprintf(p, "tx_%d_mana_map_err", i);
p += ETH_GSTRING_LEN;
}
}
static void mana_get_ethtool_stats(struct net_device *ndev,
struct ethtool_stats *e_stats, u64 *data)
{
struct mana_port_context *apc = netdev_priv(ndev);
unsigned int num_queues = apc->num_queues;
void *eth_stats = &apc->eth_stats;
struct mana_stats_rx *rx_stats;
struct mana_stats_tx *tx_stats;
unsigned int start;
u64 packets, bytes;
u64 xdp_redirect;
u64 xdp_xmit;
u64 xdp_drop;
u64 xdp_tx;
u64 tso_packets;
u64 tso_bytes;
u64 tso_inner_packets;
u64 tso_inner_bytes;
u64 long_pkt_fmt;
u64 short_pkt_fmt;
u64 csum_partial;
u64 mana_map_err;
int q, i = 0;
if (!apc->port_is_up)
return;
/* we call mana function to update stats from GDMA */
mana_query_gf_stats(apc);
for (q = 0; q < ARRAY_SIZE(mana_eth_stats); q++)
data[i++] = *(u64 *)(eth_stats + mana_eth_stats[q].offset);
for (q = 0; q < num_queues; q++) {
rx_stats = &apc->rxqs[q]->stats;
do {
start = u64_stats_fetch_begin(&rx_stats->syncp);
packets = rx_stats->packets;
bytes = rx_stats->bytes;
xdp_drop = rx_stats->xdp_drop;
xdp_tx = rx_stats->xdp_tx;
xdp_redirect = rx_stats->xdp_redirect;
} while (u64_stats_fetch_retry(&rx_stats->syncp, start));
data[i++] = packets;
data[i++] = bytes;
data[i++] = xdp_drop;
data[i++] = xdp_tx;
data[i++] = xdp_redirect;
}
for (q = 0; q < num_queues; q++) {
tx_stats = &apc->tx_qp[q].txq.stats;
do {
start = u64_stats_fetch_begin(&tx_stats->syncp);
packets = tx_stats->packets;
bytes = tx_stats->bytes;
xdp_xmit = tx_stats->xdp_xmit;
tso_packets = tx_stats->tso_packets;
tso_bytes = tx_stats->tso_bytes;
tso_inner_packets = tx_stats->tso_inner_packets;
tso_inner_bytes = tx_stats->tso_inner_bytes;
long_pkt_fmt = tx_stats->long_pkt_fmt;
short_pkt_fmt = tx_stats->short_pkt_fmt;
csum_partial = tx_stats->csum_partial;
mana_map_err = tx_stats->mana_map_err;
} while (u64_stats_fetch_retry(&tx_stats->syncp, start));
data[i++] = packets;
data[i++] = bytes;
data[i++] = xdp_xmit;
data[i++] = tso_packets;
data[i++] = tso_bytes;
data[i++] = tso_inner_packets;
data[i++] = tso_inner_bytes;
data[i++] = long_pkt_fmt;
data[i++] = short_pkt_fmt;
data[i++] = csum_partial;
data[i++] = mana_map_err;
}
}
static int mana_get_rxnfc(struct net_device *ndev, struct ethtool_rxnfc *cmd,
u32 *rules)
{
struct mana_port_context *apc = netdev_priv(ndev);
switch (cmd->cmd) {
case ETHTOOL_GRXRINGS:
cmd->data = apc->num_queues;
return 0;
}
return -EOPNOTSUPP;
}
static u32 mana_get_rxfh_key_size(struct net_device *ndev)
{
return MANA_HASH_KEY_SIZE;
}
static u32 mana_rss_indir_size(struct net_device *ndev)
{
return MANA_INDIRECT_TABLE_SIZE;
}
static int mana_get_rxfh(struct net_device *ndev, u32 *indir, u8 *key,
u8 *hfunc)
{
struct mana_port_context *apc = netdev_priv(ndev);
int i;
if (hfunc)
*hfunc = ETH_RSS_HASH_TOP; /* Toeplitz */
if (indir) {
for (i = 0; i < MANA_INDIRECT_TABLE_SIZE; i++)
indir[i] = apc->indir_table[i];
}
if (key)
memcpy(key, apc->hashkey, MANA_HASH_KEY_SIZE);
return 0;
}
static int mana_set_rxfh(struct net_device *ndev, const u32 *indir,
const u8 *key, const u8 hfunc)
{
struct mana_port_context *apc = netdev_priv(ndev);
bool update_hash = false, update_table = false;
u32 save_table[MANA_INDIRECT_TABLE_SIZE];
u8 save_key[MANA_HASH_KEY_SIZE];
int i, err;
if (!apc->port_is_up)
return -EOPNOTSUPP;
if (hfunc != ETH_RSS_HASH_NO_CHANGE && hfunc != ETH_RSS_HASH_TOP)
return -EOPNOTSUPP;
if (indir) {
for (i = 0; i < MANA_INDIRECT_TABLE_SIZE; i++)
if (indir[i] >= apc->num_queues)
return -EINVAL;
update_table = true;
for (i = 0; i < MANA_INDIRECT_TABLE_SIZE; i++) {
save_table[i] = apc->indir_table[i];
apc->indir_table[i] = indir[i];
}
}
if (key) {
update_hash = true;
memcpy(save_key, apc->hashkey, MANA_HASH_KEY_SIZE);
memcpy(apc->hashkey, key, MANA_HASH_KEY_SIZE);
}
err = mana_config_rss(apc, TRI_STATE_TRUE, update_hash, update_table);
if (err) { /* recover to original values */
if (update_table) {
for (i = 0; i < MANA_INDIRECT_TABLE_SIZE; i++)
apc->indir_table[i] = save_table[i];
}
if (update_hash)
memcpy(apc->hashkey, save_key, MANA_HASH_KEY_SIZE);
mana_config_rss(apc, TRI_STATE_TRUE, update_hash, update_table);
}
return err;
}
static void mana_get_channels(struct net_device *ndev,
struct ethtool_channels *channel)
{
struct mana_port_context *apc = netdev_priv(ndev);
channel->max_combined = apc->max_queues;
channel->combined_count = apc->num_queues;
}
static int mana_set_channels(struct net_device *ndev,
struct ethtool_channels *channels)
{
struct mana_port_context *apc = netdev_priv(ndev);
unsigned int new_count = channels->combined_count;
unsigned int old_count = apc->num_queues;
int err, err2;
err = mana_detach(ndev, false);
if (err) {
netdev_err(ndev, "mana_detach failed: %d\n", err);
return err;
}
apc->num_queues = new_count;
err = mana_attach(ndev);
if (!err)
return 0;
netdev_err(ndev, "mana_attach failed: %d\n", err);
/* Try to roll it back to the old configuration. */
apc->num_queues = old_count;
err2 = mana_attach(ndev);
if (err2)
netdev_err(ndev, "mana re-attach failed: %d\n", err2);
return err;
}
const struct ethtool_ops mana_ethtool_ops = {
.get_ethtool_stats = mana_get_ethtool_stats,
.get_sset_count = mana_get_sset_count,
.get_strings = mana_get_strings,
.get_rxnfc = mana_get_rxnfc,
.get_rxfh_key_size = mana_get_rxfh_key_size,
.get_rxfh_indir_size = mana_rss_indir_size,
.get_rxfh = mana_get_rxfh,
.set_rxfh = mana_set_rxfh,
.get_channels = mana_get_channels,
.set_channels = mana_set_channels,
};
|
linux-master
|
drivers/net/ethernet/microsoft/mana/mana_ethtool.c
|
// SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
/* Copyright (c) 2021, Microsoft Corporation. */
#include <net/mana/gdma.h>
#include <net/mana/hw_channel.h>
static int mana_hwc_get_msg_index(struct hw_channel_context *hwc, u16 *msg_id)
{
struct gdma_resource *r = &hwc->inflight_msg_res;
unsigned long flags;
u32 index;
down(&hwc->sema);
spin_lock_irqsave(&r->lock, flags);
index = find_first_zero_bit(hwc->inflight_msg_res.map,
hwc->inflight_msg_res.size);
bitmap_set(hwc->inflight_msg_res.map, index, 1);
spin_unlock_irqrestore(&r->lock, flags);
*msg_id = index;
return 0;
}
static void mana_hwc_put_msg_index(struct hw_channel_context *hwc, u16 msg_id)
{
struct gdma_resource *r = &hwc->inflight_msg_res;
unsigned long flags;
spin_lock_irqsave(&r->lock, flags);
bitmap_clear(hwc->inflight_msg_res.map, msg_id, 1);
spin_unlock_irqrestore(&r->lock, flags);
up(&hwc->sema);
}
static int mana_hwc_verify_resp_msg(const struct hwc_caller_ctx *caller_ctx,
const struct gdma_resp_hdr *resp_msg,
u32 resp_len)
{
if (resp_len < sizeof(*resp_msg))
return -EPROTO;
if (resp_len > caller_ctx->output_buflen)
return -EPROTO;
return 0;
}
static void mana_hwc_handle_resp(struct hw_channel_context *hwc, u32 resp_len,
const struct gdma_resp_hdr *resp_msg)
{
struct hwc_caller_ctx *ctx;
int err;
if (!test_bit(resp_msg->response.hwc_msg_id,
hwc->inflight_msg_res.map)) {
dev_err(hwc->dev, "hwc_rx: invalid msg_id = %u\n",
resp_msg->response.hwc_msg_id);
return;
}
ctx = hwc->caller_ctx + resp_msg->response.hwc_msg_id;
err = mana_hwc_verify_resp_msg(ctx, resp_msg, resp_len);
if (err)
goto out;
ctx->status_code = resp_msg->status;
memcpy(ctx->output_buf, resp_msg, resp_len);
out:
ctx->error = err;
complete(&ctx->comp_event);
}
static int mana_hwc_post_rx_wqe(const struct hwc_wq *hwc_rxq,
struct hwc_work_request *req)
{
struct device *dev = hwc_rxq->hwc->dev;
struct gdma_sge *sge;
int err;
sge = &req->sge;
sge->address = (u64)req->buf_sge_addr;
sge->mem_key = hwc_rxq->msg_buf->gpa_mkey;
sge->size = req->buf_len;
memset(&req->wqe_req, 0, sizeof(struct gdma_wqe_request));
req->wqe_req.sgl = sge;
req->wqe_req.num_sge = 1;
req->wqe_req.client_data_unit = 0;
err = mana_gd_post_and_ring(hwc_rxq->gdma_wq, &req->wqe_req, NULL);
if (err)
dev_err(dev, "Failed to post WQE on HWC RQ: %d\n", err);
return err;
}
static void mana_hwc_init_event_handler(void *ctx, struct gdma_queue *q_self,
struct gdma_event *event)
{
struct hw_channel_context *hwc = ctx;
struct gdma_dev *gd = hwc->gdma_dev;
union hwc_init_type_data type_data;
union hwc_init_eq_id_db eq_db;
u32 type, val;
switch (event->type) {
case GDMA_EQE_HWC_INIT_EQ_ID_DB:
eq_db.as_uint32 = event->details[0];
hwc->cq->gdma_eq->id = eq_db.eq_id;
gd->doorbell = eq_db.doorbell;
break;
case GDMA_EQE_HWC_INIT_DATA:
type_data.as_uint32 = event->details[0];
type = type_data.type;
val = type_data.value;
switch (type) {
case HWC_INIT_DATA_CQID:
hwc->cq->gdma_cq->id = val;
break;
case HWC_INIT_DATA_RQID:
hwc->rxq->gdma_wq->id = val;
break;
case HWC_INIT_DATA_SQID:
hwc->txq->gdma_wq->id = val;
break;
case HWC_INIT_DATA_QUEUE_DEPTH:
hwc->hwc_init_q_depth_max = (u16)val;
break;
case HWC_INIT_DATA_MAX_REQUEST:
hwc->hwc_init_max_req_msg_size = val;
break;
case HWC_INIT_DATA_MAX_RESPONSE:
hwc->hwc_init_max_resp_msg_size = val;
break;
case HWC_INIT_DATA_MAX_NUM_CQS:
gd->gdma_context->max_num_cqs = val;
break;
case HWC_INIT_DATA_PDID:
hwc->gdma_dev->pdid = val;
break;
case HWC_INIT_DATA_GPA_MKEY:
hwc->rxq->msg_buf->gpa_mkey = val;
hwc->txq->msg_buf->gpa_mkey = val;
break;
case HWC_INIT_DATA_PF_DEST_RQ_ID:
hwc->pf_dest_vrq_id = val;
break;
case HWC_INIT_DATA_PF_DEST_CQ_ID:
hwc->pf_dest_vrcq_id = val;
break;
}
break;
case GDMA_EQE_HWC_INIT_DONE:
complete(&hwc->hwc_init_eqe_comp);
break;
case GDMA_EQE_HWC_SOC_RECONFIG_DATA:
type_data.as_uint32 = event->details[0];
type = type_data.type;
val = type_data.value;
switch (type) {
case HWC_DATA_CFG_HWC_TIMEOUT:
hwc->hwc_timeout = val;
break;
default:
dev_warn(hwc->dev, "Received unknown reconfig type %u\n", type);
break;
}
break;
default:
dev_warn(hwc->dev, "Received unknown gdma event %u\n", event->type);
/* Ignore unknown events, which should never happen. */
break;
}
}
static void mana_hwc_rx_event_handler(void *ctx, u32 gdma_rxq_id,
const struct hwc_rx_oob *rx_oob)
{
struct hw_channel_context *hwc = ctx;
struct hwc_wq *hwc_rxq = hwc->rxq;
struct hwc_work_request *rx_req;
struct gdma_resp_hdr *resp;
struct gdma_wqe *dma_oob;
struct gdma_queue *rq;
struct gdma_sge *sge;
u64 rq_base_addr;
u64 rx_req_idx;
u8 *wqe;
if (WARN_ON_ONCE(hwc_rxq->gdma_wq->id != gdma_rxq_id))
return;
rq = hwc_rxq->gdma_wq;
wqe = mana_gd_get_wqe_ptr(rq, rx_oob->wqe_offset / GDMA_WQE_BU_SIZE);
dma_oob = (struct gdma_wqe *)wqe;
sge = (struct gdma_sge *)(wqe + 8 + dma_oob->inline_oob_size_div4 * 4);
/* Select the RX work request for virtual address and for reposting. */
rq_base_addr = hwc_rxq->msg_buf->mem_info.dma_handle;
rx_req_idx = (sge->address - rq_base_addr) / hwc->max_req_msg_size;
rx_req = &hwc_rxq->msg_buf->reqs[rx_req_idx];
resp = (struct gdma_resp_hdr *)rx_req->buf_va;
if (resp->response.hwc_msg_id >= hwc->num_inflight_msg) {
dev_err(hwc->dev, "HWC RX: wrong msg_id=%u\n",
resp->response.hwc_msg_id);
return;
}
mana_hwc_handle_resp(hwc, rx_oob->tx_oob_data_size, resp);
/* Do no longer use 'resp', because the buffer is posted to the HW
* in the below mana_hwc_post_rx_wqe().
*/
resp = NULL;
mana_hwc_post_rx_wqe(hwc_rxq, rx_req);
}
static void mana_hwc_tx_event_handler(void *ctx, u32 gdma_txq_id,
const struct hwc_rx_oob *rx_oob)
{
struct hw_channel_context *hwc = ctx;
struct hwc_wq *hwc_txq = hwc->txq;
WARN_ON_ONCE(!hwc_txq || hwc_txq->gdma_wq->id != gdma_txq_id);
}
static int mana_hwc_create_gdma_wq(struct hw_channel_context *hwc,
enum gdma_queue_type type, u64 queue_size,
struct gdma_queue **queue)
{
struct gdma_queue_spec spec = {};
if (type != GDMA_SQ && type != GDMA_RQ)
return -EINVAL;
spec.type = type;
spec.monitor_avl_buf = false;
spec.queue_size = queue_size;
return mana_gd_create_hwc_queue(hwc->gdma_dev, &spec, queue);
}
static int mana_hwc_create_gdma_cq(struct hw_channel_context *hwc,
u64 queue_size,
void *ctx, gdma_cq_callback *cb,
struct gdma_queue *parent_eq,
struct gdma_queue **queue)
{
struct gdma_queue_spec spec = {};
spec.type = GDMA_CQ;
spec.monitor_avl_buf = false;
spec.queue_size = queue_size;
spec.cq.context = ctx;
spec.cq.callback = cb;
spec.cq.parent_eq = parent_eq;
return mana_gd_create_hwc_queue(hwc->gdma_dev, &spec, queue);
}
static int mana_hwc_create_gdma_eq(struct hw_channel_context *hwc,
u64 queue_size,
void *ctx, gdma_eq_callback *cb,
struct gdma_queue **queue)
{
struct gdma_queue_spec spec = {};
spec.type = GDMA_EQ;
spec.monitor_avl_buf = false;
spec.queue_size = queue_size;
spec.eq.context = ctx;
spec.eq.callback = cb;
spec.eq.log2_throttle_limit = DEFAULT_LOG2_THROTTLING_FOR_ERROR_EQ;
return mana_gd_create_hwc_queue(hwc->gdma_dev, &spec, queue);
}
static void mana_hwc_comp_event(void *ctx, struct gdma_queue *q_self)
{
struct hwc_rx_oob comp_data = {};
struct gdma_comp *completions;
struct hwc_cq *hwc_cq = ctx;
int comp_read, i;
WARN_ON_ONCE(hwc_cq->gdma_cq != q_self);
completions = hwc_cq->comp_buf;
comp_read = mana_gd_poll_cq(q_self, completions, hwc_cq->queue_depth);
WARN_ON_ONCE(comp_read <= 0 || comp_read > hwc_cq->queue_depth);
for (i = 0; i < comp_read; ++i) {
comp_data = *(struct hwc_rx_oob *)completions[i].cqe_data;
if (completions[i].is_sq)
hwc_cq->tx_event_handler(hwc_cq->tx_event_ctx,
completions[i].wq_num,
&comp_data);
else
hwc_cq->rx_event_handler(hwc_cq->rx_event_ctx,
completions[i].wq_num,
&comp_data);
}
mana_gd_ring_cq(q_self, SET_ARM_BIT);
}
static void mana_hwc_destroy_cq(struct gdma_context *gc, struct hwc_cq *hwc_cq)
{
kfree(hwc_cq->comp_buf);
if (hwc_cq->gdma_cq)
mana_gd_destroy_queue(gc, hwc_cq->gdma_cq);
if (hwc_cq->gdma_eq)
mana_gd_destroy_queue(gc, hwc_cq->gdma_eq);
kfree(hwc_cq);
}
static int mana_hwc_create_cq(struct hw_channel_context *hwc, u16 q_depth,
gdma_eq_callback *callback, void *ctx,
hwc_rx_event_handler_t *rx_ev_hdlr,
void *rx_ev_ctx,
hwc_tx_event_handler_t *tx_ev_hdlr,
void *tx_ev_ctx, struct hwc_cq **hwc_cq_ptr)
{
struct gdma_queue *eq, *cq;
struct gdma_comp *comp_buf;
struct hwc_cq *hwc_cq;
u32 eq_size, cq_size;
int err;
eq_size = roundup_pow_of_two(GDMA_EQE_SIZE * q_depth);
if (eq_size < MINIMUM_SUPPORTED_PAGE_SIZE)
eq_size = MINIMUM_SUPPORTED_PAGE_SIZE;
cq_size = roundup_pow_of_two(GDMA_CQE_SIZE * q_depth);
if (cq_size < MINIMUM_SUPPORTED_PAGE_SIZE)
cq_size = MINIMUM_SUPPORTED_PAGE_SIZE;
hwc_cq = kzalloc(sizeof(*hwc_cq), GFP_KERNEL);
if (!hwc_cq)
return -ENOMEM;
err = mana_hwc_create_gdma_eq(hwc, eq_size, ctx, callback, &eq);
if (err) {
dev_err(hwc->dev, "Failed to create HWC EQ for RQ: %d\n", err);
goto out;
}
hwc_cq->gdma_eq = eq;
err = mana_hwc_create_gdma_cq(hwc, cq_size, hwc_cq, mana_hwc_comp_event,
eq, &cq);
if (err) {
dev_err(hwc->dev, "Failed to create HWC CQ for RQ: %d\n", err);
goto out;
}
hwc_cq->gdma_cq = cq;
comp_buf = kcalloc(q_depth, sizeof(*comp_buf), GFP_KERNEL);
if (!comp_buf) {
err = -ENOMEM;
goto out;
}
hwc_cq->hwc = hwc;
hwc_cq->comp_buf = comp_buf;
hwc_cq->queue_depth = q_depth;
hwc_cq->rx_event_handler = rx_ev_hdlr;
hwc_cq->rx_event_ctx = rx_ev_ctx;
hwc_cq->tx_event_handler = tx_ev_hdlr;
hwc_cq->tx_event_ctx = tx_ev_ctx;
*hwc_cq_ptr = hwc_cq;
return 0;
out:
mana_hwc_destroy_cq(hwc->gdma_dev->gdma_context, hwc_cq);
return err;
}
static int mana_hwc_alloc_dma_buf(struct hw_channel_context *hwc, u16 q_depth,
u32 max_msg_size,
struct hwc_dma_buf **dma_buf_ptr)
{
struct gdma_context *gc = hwc->gdma_dev->gdma_context;
struct hwc_work_request *hwc_wr;
struct hwc_dma_buf *dma_buf;
struct gdma_mem_info *gmi;
void *virt_addr;
u32 buf_size;
u8 *base_pa;
int err;
u16 i;
dma_buf = kzalloc(struct_size(dma_buf, reqs, q_depth), GFP_KERNEL);
if (!dma_buf)
return -ENOMEM;
dma_buf->num_reqs = q_depth;
buf_size = PAGE_ALIGN(q_depth * max_msg_size);
gmi = &dma_buf->mem_info;
err = mana_gd_alloc_memory(gc, buf_size, gmi);
if (err) {
dev_err(hwc->dev, "Failed to allocate DMA buffer: %d\n", err);
goto out;
}
virt_addr = dma_buf->mem_info.virt_addr;
base_pa = (u8 *)dma_buf->mem_info.dma_handle;
for (i = 0; i < q_depth; i++) {
hwc_wr = &dma_buf->reqs[i];
hwc_wr->buf_va = virt_addr + i * max_msg_size;
hwc_wr->buf_sge_addr = base_pa + i * max_msg_size;
hwc_wr->buf_len = max_msg_size;
}
*dma_buf_ptr = dma_buf;
return 0;
out:
kfree(dma_buf);
return err;
}
static void mana_hwc_dealloc_dma_buf(struct hw_channel_context *hwc,
struct hwc_dma_buf *dma_buf)
{
if (!dma_buf)
return;
mana_gd_free_memory(&dma_buf->mem_info);
kfree(dma_buf);
}
static void mana_hwc_destroy_wq(struct hw_channel_context *hwc,
struct hwc_wq *hwc_wq)
{
mana_hwc_dealloc_dma_buf(hwc, hwc_wq->msg_buf);
if (hwc_wq->gdma_wq)
mana_gd_destroy_queue(hwc->gdma_dev->gdma_context,
hwc_wq->gdma_wq);
kfree(hwc_wq);
}
static int mana_hwc_create_wq(struct hw_channel_context *hwc,
enum gdma_queue_type q_type, u16 q_depth,
u32 max_msg_size, struct hwc_cq *hwc_cq,
struct hwc_wq **hwc_wq_ptr)
{
struct gdma_queue *queue;
struct hwc_wq *hwc_wq;
u32 queue_size;
int err;
WARN_ON(q_type != GDMA_SQ && q_type != GDMA_RQ);
if (q_type == GDMA_RQ)
queue_size = roundup_pow_of_two(GDMA_MAX_RQE_SIZE * q_depth);
else
queue_size = roundup_pow_of_two(GDMA_MAX_SQE_SIZE * q_depth);
if (queue_size < MINIMUM_SUPPORTED_PAGE_SIZE)
queue_size = MINIMUM_SUPPORTED_PAGE_SIZE;
hwc_wq = kzalloc(sizeof(*hwc_wq), GFP_KERNEL);
if (!hwc_wq)
return -ENOMEM;
err = mana_hwc_create_gdma_wq(hwc, q_type, queue_size, &queue);
if (err)
goto out;
hwc_wq->hwc = hwc;
hwc_wq->gdma_wq = queue;
hwc_wq->queue_depth = q_depth;
hwc_wq->hwc_cq = hwc_cq;
err = mana_hwc_alloc_dma_buf(hwc, q_depth, max_msg_size,
&hwc_wq->msg_buf);
if (err)
goto out;
*hwc_wq_ptr = hwc_wq;
return 0;
out:
if (err)
mana_hwc_destroy_wq(hwc, hwc_wq);
return err;
}
static int mana_hwc_post_tx_wqe(const struct hwc_wq *hwc_txq,
struct hwc_work_request *req,
u32 dest_virt_rq_id, u32 dest_virt_rcq_id,
bool dest_pf)
{
struct device *dev = hwc_txq->hwc->dev;
struct hwc_tx_oob *tx_oob;
struct gdma_sge *sge;
int err;
if (req->msg_size == 0 || req->msg_size > req->buf_len) {
dev_err(dev, "wrong msg_size: %u, buf_len: %u\n",
req->msg_size, req->buf_len);
return -EINVAL;
}
tx_oob = &req->tx_oob;
tx_oob->vrq_id = dest_virt_rq_id;
tx_oob->dest_vfid = 0;
tx_oob->vrcq_id = dest_virt_rcq_id;
tx_oob->vscq_id = hwc_txq->hwc_cq->gdma_cq->id;
tx_oob->loopback = false;
tx_oob->lso_override = false;
tx_oob->dest_pf = dest_pf;
tx_oob->vsq_id = hwc_txq->gdma_wq->id;
sge = &req->sge;
sge->address = (u64)req->buf_sge_addr;
sge->mem_key = hwc_txq->msg_buf->gpa_mkey;
sge->size = req->msg_size;
memset(&req->wqe_req, 0, sizeof(struct gdma_wqe_request));
req->wqe_req.sgl = sge;
req->wqe_req.num_sge = 1;
req->wqe_req.inline_oob_size = sizeof(struct hwc_tx_oob);
req->wqe_req.inline_oob_data = tx_oob;
req->wqe_req.client_data_unit = 0;
err = mana_gd_post_and_ring(hwc_txq->gdma_wq, &req->wqe_req, NULL);
if (err)
dev_err(dev, "Failed to post WQE on HWC SQ: %d\n", err);
return err;
}
static int mana_hwc_init_inflight_msg(struct hw_channel_context *hwc,
u16 num_msg)
{
int err;
sema_init(&hwc->sema, num_msg);
err = mana_gd_alloc_res_map(num_msg, &hwc->inflight_msg_res);
if (err)
dev_err(hwc->dev, "Failed to init inflight_msg_res: %d\n", err);
return err;
}
static int mana_hwc_test_channel(struct hw_channel_context *hwc, u16 q_depth,
u32 max_req_msg_size, u32 max_resp_msg_size)
{
struct gdma_context *gc = hwc->gdma_dev->gdma_context;
struct hwc_wq *hwc_rxq = hwc->rxq;
struct hwc_work_request *req;
struct hwc_caller_ctx *ctx;
int err;
int i;
/* Post all WQEs on the RQ */
for (i = 0; i < q_depth; i++) {
req = &hwc_rxq->msg_buf->reqs[i];
err = mana_hwc_post_rx_wqe(hwc_rxq, req);
if (err)
return err;
}
ctx = kcalloc(q_depth, sizeof(*ctx), GFP_KERNEL);
if (!ctx)
return -ENOMEM;
for (i = 0; i < q_depth; ++i)
init_completion(&ctx[i].comp_event);
hwc->caller_ctx = ctx;
return mana_gd_test_eq(gc, hwc->cq->gdma_eq);
}
static int mana_hwc_establish_channel(struct gdma_context *gc, u16 *q_depth,
u32 *max_req_msg_size,
u32 *max_resp_msg_size)
{
struct hw_channel_context *hwc = gc->hwc.driver_data;
struct gdma_queue *rq = hwc->rxq->gdma_wq;
struct gdma_queue *sq = hwc->txq->gdma_wq;
struct gdma_queue *eq = hwc->cq->gdma_eq;
struct gdma_queue *cq = hwc->cq->gdma_cq;
int err;
init_completion(&hwc->hwc_init_eqe_comp);
err = mana_smc_setup_hwc(&gc->shm_channel, false,
eq->mem_info.dma_handle,
cq->mem_info.dma_handle,
rq->mem_info.dma_handle,
sq->mem_info.dma_handle,
eq->eq.msix_index);
if (err)
return err;
if (!wait_for_completion_timeout(&hwc->hwc_init_eqe_comp, 60 * HZ))
return -ETIMEDOUT;
*q_depth = hwc->hwc_init_q_depth_max;
*max_req_msg_size = hwc->hwc_init_max_req_msg_size;
*max_resp_msg_size = hwc->hwc_init_max_resp_msg_size;
/* Both were set in mana_hwc_init_event_handler(). */
if (WARN_ON(cq->id >= gc->max_num_cqs))
return -EPROTO;
gc->cq_table = vcalloc(gc->max_num_cqs, sizeof(struct gdma_queue *));
if (!gc->cq_table)
return -ENOMEM;
gc->cq_table[cq->id] = cq;
return 0;
}
static int mana_hwc_init_queues(struct hw_channel_context *hwc, u16 q_depth,
u32 max_req_msg_size, u32 max_resp_msg_size)
{
int err;
err = mana_hwc_init_inflight_msg(hwc, q_depth);
if (err)
return err;
/* CQ is shared by SQ and RQ, so CQ's queue depth is the sum of SQ
* queue depth and RQ queue depth.
*/
err = mana_hwc_create_cq(hwc, q_depth * 2,
mana_hwc_init_event_handler, hwc,
mana_hwc_rx_event_handler, hwc,
mana_hwc_tx_event_handler, hwc, &hwc->cq);
if (err) {
dev_err(hwc->dev, "Failed to create HWC CQ: %d\n", err);
goto out;
}
err = mana_hwc_create_wq(hwc, GDMA_RQ, q_depth, max_req_msg_size,
hwc->cq, &hwc->rxq);
if (err) {
dev_err(hwc->dev, "Failed to create HWC RQ: %d\n", err);
goto out;
}
err = mana_hwc_create_wq(hwc, GDMA_SQ, q_depth, max_resp_msg_size,
hwc->cq, &hwc->txq);
if (err) {
dev_err(hwc->dev, "Failed to create HWC SQ: %d\n", err);
goto out;
}
hwc->num_inflight_msg = q_depth;
hwc->max_req_msg_size = max_req_msg_size;
return 0;
out:
/* mana_hwc_create_channel() will do the cleanup.*/
return err;
}
int mana_hwc_create_channel(struct gdma_context *gc)
{
u32 max_req_msg_size, max_resp_msg_size;
struct gdma_dev *gd = &gc->hwc;
struct hw_channel_context *hwc;
u16 q_depth_max;
int err;
hwc = kzalloc(sizeof(*hwc), GFP_KERNEL);
if (!hwc)
return -ENOMEM;
gd->gdma_context = gc;
gd->driver_data = hwc;
hwc->gdma_dev = gd;
hwc->dev = gc->dev;
hwc->hwc_timeout = HW_CHANNEL_WAIT_RESOURCE_TIMEOUT_MS;
/* HWC's instance number is always 0. */
gd->dev_id.as_uint32 = 0;
gd->dev_id.type = GDMA_DEVICE_HWC;
gd->pdid = INVALID_PDID;
gd->doorbell = INVALID_DOORBELL;
/* mana_hwc_init_queues() only creates the required data structures,
* and doesn't touch the HWC device.
*/
err = mana_hwc_init_queues(hwc, HW_CHANNEL_VF_BOOTSTRAP_QUEUE_DEPTH,
HW_CHANNEL_MAX_REQUEST_SIZE,
HW_CHANNEL_MAX_RESPONSE_SIZE);
if (err) {
dev_err(hwc->dev, "Failed to initialize HWC: %d\n", err);
goto out;
}
err = mana_hwc_establish_channel(gc, &q_depth_max, &max_req_msg_size,
&max_resp_msg_size);
if (err) {
dev_err(hwc->dev, "Failed to establish HWC: %d\n", err);
goto out;
}
err = mana_hwc_test_channel(gc->hwc.driver_data,
HW_CHANNEL_VF_BOOTSTRAP_QUEUE_DEPTH,
max_req_msg_size, max_resp_msg_size);
if (err) {
dev_err(hwc->dev, "Failed to test HWC: %d\n", err);
goto out;
}
return 0;
out:
mana_hwc_destroy_channel(gc);
return err;
}
void mana_hwc_destroy_channel(struct gdma_context *gc)
{
struct hw_channel_context *hwc = gc->hwc.driver_data;
if (!hwc)
return;
/* gc->max_num_cqs is set in mana_hwc_init_event_handler(). If it's
* non-zero, the HWC worked and we should tear down the HWC here.
*/
if (gc->max_num_cqs > 0) {
mana_smc_teardown_hwc(&gc->shm_channel, false);
gc->max_num_cqs = 0;
}
kfree(hwc->caller_ctx);
hwc->caller_ctx = NULL;
if (hwc->txq)
mana_hwc_destroy_wq(hwc, hwc->txq);
if (hwc->rxq)
mana_hwc_destroy_wq(hwc, hwc->rxq);
if (hwc->cq)
mana_hwc_destroy_cq(hwc->gdma_dev->gdma_context, hwc->cq);
mana_gd_free_res_map(&hwc->inflight_msg_res);
hwc->num_inflight_msg = 0;
hwc->gdma_dev->doorbell = INVALID_DOORBELL;
hwc->gdma_dev->pdid = INVALID_PDID;
hwc->hwc_timeout = 0;
kfree(hwc);
gc->hwc.driver_data = NULL;
gc->hwc.gdma_context = NULL;
vfree(gc->cq_table);
gc->cq_table = NULL;
}
int mana_hwc_send_request(struct hw_channel_context *hwc, u32 req_len,
const void *req, u32 resp_len, void *resp)
{
struct gdma_context *gc = hwc->gdma_dev->gdma_context;
struct hwc_work_request *tx_wr;
struct hwc_wq *txq = hwc->txq;
struct gdma_req_hdr *req_msg;
struct hwc_caller_ctx *ctx;
u32 dest_vrcq = 0;
u32 dest_vrq = 0;
u16 msg_id;
int err;
mana_hwc_get_msg_index(hwc, &msg_id);
tx_wr = &txq->msg_buf->reqs[msg_id];
if (req_len > tx_wr->buf_len) {
dev_err(hwc->dev, "HWC: req msg size: %d > %d\n", req_len,
tx_wr->buf_len);
err = -EINVAL;
goto out;
}
ctx = hwc->caller_ctx + msg_id;
ctx->output_buf = resp;
ctx->output_buflen = resp_len;
req_msg = (struct gdma_req_hdr *)tx_wr->buf_va;
if (req)
memcpy(req_msg, req, req_len);
req_msg->req.hwc_msg_id = msg_id;
tx_wr->msg_size = req_len;
if (gc->is_pf) {
dest_vrq = hwc->pf_dest_vrq_id;
dest_vrcq = hwc->pf_dest_vrcq_id;
}
err = mana_hwc_post_tx_wqe(txq, tx_wr, dest_vrq, dest_vrcq, false);
if (err) {
dev_err(hwc->dev, "HWC: Failed to post send WQE: %d\n", err);
goto out;
}
if (!wait_for_completion_timeout(&ctx->comp_event,
(msecs_to_jiffies(hwc->hwc_timeout) * HZ))) {
dev_err(hwc->dev, "HWC: Request timed out!\n");
err = -ETIMEDOUT;
goto out;
}
if (ctx->error) {
err = ctx->error;
goto out;
}
if (ctx->status_code && ctx->status_code != GDMA_STATUS_MORE_ENTRIES) {
dev_err(hwc->dev, "HWC: Failed hw_channel req: 0x%x\n",
ctx->status_code);
err = -EPROTO;
goto out;
}
out:
mana_hwc_put_msg_index(hwc, msg_id);
return err;
}
|
linux-master
|
drivers/net/ethernet/microsoft/mana/hw_channel.c
|
// SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
/* Copyright (c) 2021, Microsoft Corporation. */
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/io.h>
#include <linux/mm.h>
#include <net/mana/shm_channel.h>
#define PAGE_FRAME_L48_WIDTH_BYTES 6
#define PAGE_FRAME_L48_WIDTH_BITS (PAGE_FRAME_L48_WIDTH_BYTES * 8)
#define PAGE_FRAME_L48_MASK 0x0000FFFFFFFFFFFF
#define PAGE_FRAME_H4_WIDTH_BITS 4
#define VECTOR_MASK 0xFFFF
#define SHMEM_VF_RESET_STATE ((u32)-1)
#define SMC_MSG_TYPE_ESTABLISH_HWC 1
#define SMC_MSG_TYPE_ESTABLISH_HWC_VERSION 0
#define SMC_MSG_TYPE_DESTROY_HWC 2
#define SMC_MSG_TYPE_DESTROY_HWC_VERSION 0
#define SMC_MSG_DIRECTION_REQUEST 0
#define SMC_MSG_DIRECTION_RESPONSE 1
/* Structures labeled with "HW DATA" are exchanged with the hardware. All of
* them are naturally aligned and hence don't need __packed.
*/
/* Shared memory channel protocol header
*
* msg_type: set on request and response; response matches request.
* msg_version: newer PF writes back older response (matching request)
* older PF acts on latest version known and sets that version in result
* (less than request).
* direction: 0 for request, VF->PF; 1 for response, PF->VF.
* status: 0 on request,
* operation result on response (success = 0, failure = 1 or greater).
* reset_vf: If set on either establish or destroy request, indicates perform
* FLR before/after the operation.
* owner_is_pf: 1 indicates PF owned, 0 indicates VF owned.
*/
union smc_proto_hdr {
u32 as_uint32;
struct {
u8 msg_type : 3;
u8 msg_version : 3;
u8 reserved_1 : 1;
u8 direction : 1;
u8 status;
u8 reserved_2;
u8 reset_vf : 1;
u8 reserved_3 : 6;
u8 owner_is_pf : 1;
};
}; /* HW DATA */
#define SMC_APERTURE_BITS 256
#define SMC_BASIC_UNIT (sizeof(u32))
#define SMC_APERTURE_DWORDS (SMC_APERTURE_BITS / (SMC_BASIC_UNIT * 8))
#define SMC_LAST_DWORD (SMC_APERTURE_DWORDS - 1)
static int mana_smc_poll_register(void __iomem *base, bool reset)
{
void __iomem *ptr = base + SMC_LAST_DWORD * SMC_BASIC_UNIT;
u32 last_dword;
int i;
/* Poll the hardware for the ownership bit. This should be pretty fast,
* but let's do it in a loop just in case the hardware or the PF
* driver are temporarily busy.
*/
for (i = 0; i < 20 * 1000; i++) {
last_dword = readl(ptr);
/* shmem reads as 0xFFFFFFFF in the reset case */
if (reset && last_dword == SHMEM_VF_RESET_STATE)
return 0;
/* If bit_31 is set, the PF currently owns the SMC. */
if (!(last_dword & BIT(31)))
return 0;
usleep_range(1000, 2000);
}
return -ETIMEDOUT;
}
static int mana_smc_read_response(struct shm_channel *sc, u32 msg_type,
u32 msg_version, bool reset_vf)
{
void __iomem *base = sc->base;
union smc_proto_hdr hdr;
int err;
/* Wait for PF to respond. */
err = mana_smc_poll_register(base, reset_vf);
if (err)
return err;
hdr.as_uint32 = readl(base + SMC_LAST_DWORD * SMC_BASIC_UNIT);
if (reset_vf && hdr.as_uint32 == SHMEM_VF_RESET_STATE)
return 0;
/* Validate protocol fields from the PF driver */
if (hdr.msg_type != msg_type || hdr.msg_version > msg_version ||
hdr.direction != SMC_MSG_DIRECTION_RESPONSE) {
dev_err(sc->dev, "Wrong SMC response 0x%x, type=%d, ver=%d\n",
hdr.as_uint32, msg_type, msg_version);
return -EPROTO;
}
/* Validate the operation result */
if (hdr.status != 0) {
dev_err(sc->dev, "SMC operation failed: 0x%x\n", hdr.status);
return -EPROTO;
}
return 0;
}
void mana_smc_init(struct shm_channel *sc, struct device *dev,
void __iomem *base)
{
sc->dev = dev;
sc->base = base;
}
int mana_smc_setup_hwc(struct shm_channel *sc, bool reset_vf, u64 eq_addr,
u64 cq_addr, u64 rq_addr, u64 sq_addr,
u32 eq_msix_index)
{
union smc_proto_hdr *hdr;
u16 all_addr_h4bits = 0;
u16 frame_addr_seq = 0;
u64 frame_addr = 0;
u8 shm_buf[32];
u64 *shmem;
u32 *dword;
u8 *ptr;
int err;
int i;
/* Ensure VF already has possession of shared memory */
err = mana_smc_poll_register(sc->base, false);
if (err) {
dev_err(sc->dev, "Timeout when setting up HWC: %d\n", err);
return err;
}
if (!PAGE_ALIGNED(eq_addr) || !PAGE_ALIGNED(cq_addr) ||
!PAGE_ALIGNED(rq_addr) || !PAGE_ALIGNED(sq_addr))
return -EINVAL;
if ((eq_msix_index & VECTOR_MASK) != eq_msix_index)
return -EINVAL;
/* Scheme for packing four addresses and extra info into 256 bits.
*
* Addresses must be page frame aligned, so only frame address bits
* are transferred.
*
* 52-bit frame addresses are split into the lower 48 bits and upper
* 4 bits. Lower 48 bits of 4 address are written sequentially from
* the start of the 256-bit shared memory region followed by 16 bits
* containing the upper 4 bits of the 4 addresses in sequence.
*
* A 16 bit EQ vector number fills out the next-to-last 32-bit dword.
*
* The final 32-bit dword is used for protocol control information as
* defined in smc_proto_hdr.
*/
memset(shm_buf, 0, sizeof(shm_buf));
ptr = shm_buf;
/* EQ addr: low 48 bits of frame address */
shmem = (u64 *)ptr;
frame_addr = PHYS_PFN(eq_addr);
*shmem = frame_addr & PAGE_FRAME_L48_MASK;
all_addr_h4bits |= (frame_addr >> PAGE_FRAME_L48_WIDTH_BITS) <<
(frame_addr_seq++ * PAGE_FRAME_H4_WIDTH_BITS);
ptr += PAGE_FRAME_L48_WIDTH_BYTES;
/* CQ addr: low 48 bits of frame address */
shmem = (u64 *)ptr;
frame_addr = PHYS_PFN(cq_addr);
*shmem = frame_addr & PAGE_FRAME_L48_MASK;
all_addr_h4bits |= (frame_addr >> PAGE_FRAME_L48_WIDTH_BITS) <<
(frame_addr_seq++ * PAGE_FRAME_H4_WIDTH_BITS);
ptr += PAGE_FRAME_L48_WIDTH_BYTES;
/* RQ addr: low 48 bits of frame address */
shmem = (u64 *)ptr;
frame_addr = PHYS_PFN(rq_addr);
*shmem = frame_addr & PAGE_FRAME_L48_MASK;
all_addr_h4bits |= (frame_addr >> PAGE_FRAME_L48_WIDTH_BITS) <<
(frame_addr_seq++ * PAGE_FRAME_H4_WIDTH_BITS);
ptr += PAGE_FRAME_L48_WIDTH_BYTES;
/* SQ addr: low 48 bits of frame address */
shmem = (u64 *)ptr;
frame_addr = PHYS_PFN(sq_addr);
*shmem = frame_addr & PAGE_FRAME_L48_MASK;
all_addr_h4bits |= (frame_addr >> PAGE_FRAME_L48_WIDTH_BITS) <<
(frame_addr_seq++ * PAGE_FRAME_H4_WIDTH_BITS);
ptr += PAGE_FRAME_L48_WIDTH_BYTES;
/* High 4 bits of the four frame addresses */
*((u16 *)ptr) = all_addr_h4bits;
ptr += sizeof(u16);
/* EQ MSIX vector number */
*((u16 *)ptr) = (u16)eq_msix_index;
ptr += sizeof(u16);
/* 32-bit protocol header in final dword */
*((u32 *)ptr) = 0;
hdr = (union smc_proto_hdr *)ptr;
hdr->msg_type = SMC_MSG_TYPE_ESTABLISH_HWC;
hdr->msg_version = SMC_MSG_TYPE_ESTABLISH_HWC_VERSION;
hdr->direction = SMC_MSG_DIRECTION_REQUEST;
hdr->reset_vf = reset_vf;
/* Write 256-message buffer to shared memory (final 32-bit write
* triggers HW to set possession bit to PF).
*/
dword = (u32 *)shm_buf;
for (i = 0; i < SMC_APERTURE_DWORDS; i++)
writel(*dword++, sc->base + i * SMC_BASIC_UNIT);
/* Read shmem response (polling for VF possession) and validate.
* For setup, waiting for response on shared memory is not strictly
* necessary, since wait occurs later for results to appear in EQE's.
*/
err = mana_smc_read_response(sc, SMC_MSG_TYPE_ESTABLISH_HWC,
SMC_MSG_TYPE_ESTABLISH_HWC_VERSION,
reset_vf);
if (err) {
dev_err(sc->dev, "Error when setting up HWC: %d\n", err);
return err;
}
return 0;
}
int mana_smc_teardown_hwc(struct shm_channel *sc, bool reset_vf)
{
union smc_proto_hdr hdr = {};
int err;
/* Ensure already has possession of shared memory */
err = mana_smc_poll_register(sc->base, false);
if (err) {
dev_err(sc->dev, "Timeout when tearing down HWC\n");
return err;
}
/* Set up protocol header for HWC destroy message */
hdr.msg_type = SMC_MSG_TYPE_DESTROY_HWC;
hdr.msg_version = SMC_MSG_TYPE_DESTROY_HWC_VERSION;
hdr.direction = SMC_MSG_DIRECTION_REQUEST;
hdr.reset_vf = reset_vf;
/* Write message in high 32 bits of 256-bit shared memory, causing HW
* to set possession bit to PF.
*/
writel(hdr.as_uint32, sc->base + SMC_LAST_DWORD * SMC_BASIC_UNIT);
/* Read shmem response (polling for VF possession) and validate.
* For teardown, waiting for response is required to ensure hardware
* invalidates MST entries before software frees memory.
*/
err = mana_smc_read_response(sc, SMC_MSG_TYPE_DESTROY_HWC,
SMC_MSG_TYPE_DESTROY_HWC_VERSION,
reset_vf);
if (err) {
dev_err(sc->dev, "Error when tearing down HWC: %d\n", err);
return err;
}
return 0;
}
|
linux-master
|
drivers/net/ethernet/microsoft/mana/shm_channel.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2018 Solarflare Communications Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include "net_driver.h"
#include <linux/module.h>
#include <linux/filter.h>
#include "efx_channels.h"
#include "efx.h"
#include "efx_common.h"
#include "tx_common.h"
#include "rx_common.h"
#include "nic.h"
#include "sriov.h"
#include "workarounds.h"
/* This is the first interrupt mode to try out of:
* 0 => MSI-X
* 1 => MSI
* 2 => legacy
*/
unsigned int efx_interrupt_mode = EFX_INT_MODE_MSIX;
/* This is the requested number of CPUs to use for Receive-Side Scaling (RSS),
* i.e. the number of CPUs among which we may distribute simultaneous
* interrupt handling.
*
* Cards without MSI-X will only target one CPU via legacy or MSI interrupt.
* The default (0) means to assign an interrupt to each core.
*/
unsigned int rss_cpus;
static unsigned int irq_adapt_low_thresh = 8000;
module_param(irq_adapt_low_thresh, uint, 0644);
MODULE_PARM_DESC(irq_adapt_low_thresh,
"Threshold score for reducing IRQ moderation");
static unsigned int irq_adapt_high_thresh = 16000;
module_param(irq_adapt_high_thresh, uint, 0644);
MODULE_PARM_DESC(irq_adapt_high_thresh,
"Threshold score for increasing IRQ moderation");
static const struct efx_channel_type efx_default_channel_type;
/*************
* INTERRUPTS
*************/
static unsigned int count_online_cores(struct efx_nic *efx, bool local_node)
{
cpumask_var_t filter_mask;
unsigned int count;
int cpu;
if (unlikely(!zalloc_cpumask_var(&filter_mask, GFP_KERNEL))) {
netif_warn(efx, probe, efx->net_dev,
"RSS disabled due to allocation failure\n");
return 1;
}
cpumask_copy(filter_mask, cpu_online_mask);
if (local_node)
cpumask_and(filter_mask, filter_mask,
cpumask_of_pcibus(efx->pci_dev->bus));
count = 0;
for_each_cpu(cpu, filter_mask) {
++count;
cpumask_andnot(filter_mask, filter_mask, topology_sibling_cpumask(cpu));
}
free_cpumask_var(filter_mask);
return count;
}
static unsigned int efx_wanted_parallelism(struct efx_nic *efx)
{
unsigned int count;
if (rss_cpus) {
count = rss_cpus;
} else {
count = count_online_cores(efx, true);
/* If no online CPUs in local node, fallback to any online CPUs */
if (count == 0)
count = count_online_cores(efx, false);
}
if (count > EFX_MAX_RX_QUEUES) {
netif_cond_dbg(efx, probe, efx->net_dev, !rss_cpus, warn,
"Reducing number of rx queues from %u to %u.\n",
count, EFX_MAX_RX_QUEUES);
count = EFX_MAX_RX_QUEUES;
}
/* If RSS is requested for the PF *and* VFs then we can't write RSS
* table entries that are inaccessible to VFs
*/
#ifdef CONFIG_SFC_SRIOV
if (efx->type->sriov_wanted) {
if (efx->type->sriov_wanted(efx) && efx_vf_size(efx) > 1 &&
count > efx_vf_size(efx)) {
netif_warn(efx, probe, efx->net_dev,
"Reducing number of RSS channels from %u to %u for "
"VF support. Increase vf-msix-limit to use more "
"channels on the PF.\n",
count, efx_vf_size(efx));
count = efx_vf_size(efx);
}
}
#endif
return count;
}
static int efx_allocate_msix_channels(struct efx_nic *efx,
unsigned int max_channels,
unsigned int extra_channels,
unsigned int parallelism)
{
unsigned int n_channels = parallelism;
int vec_count;
int tx_per_ev;
int n_xdp_tx;
int n_xdp_ev;
if (efx_separate_tx_channels)
n_channels *= 2;
n_channels += extra_channels;
/* To allow XDP transmit to happen from arbitrary NAPI contexts
* we allocate a TX queue per CPU. We share event queues across
* multiple tx queues, assuming tx and ev queues are both
* maximum size.
*/
tx_per_ev = EFX_MAX_EVQ_SIZE / EFX_TXQ_MAX_ENT(efx);
tx_per_ev = min(tx_per_ev, EFX_MAX_TXQ_PER_CHANNEL);
n_xdp_tx = num_possible_cpus();
n_xdp_ev = DIV_ROUND_UP(n_xdp_tx, tx_per_ev);
vec_count = pci_msix_vec_count(efx->pci_dev);
if (vec_count < 0)
return vec_count;
max_channels = min_t(unsigned int, vec_count, max_channels);
/* Check resources.
* We need a channel per event queue, plus a VI per tx queue.
* This may be more pessimistic than it needs to be.
*/
if (n_channels >= max_channels) {
efx->xdp_txq_queues_mode = EFX_XDP_TX_QUEUES_BORROWED;
netif_warn(efx, drv, efx->net_dev,
"Insufficient resources for %d XDP event queues (%d other channels, max %d)\n",
n_xdp_ev, n_channels, max_channels);
netif_warn(efx, drv, efx->net_dev,
"XDP_TX and XDP_REDIRECT might decrease device's performance\n");
} else if (n_channels + n_xdp_tx > efx->max_vis) {
efx->xdp_txq_queues_mode = EFX_XDP_TX_QUEUES_BORROWED;
netif_warn(efx, drv, efx->net_dev,
"Insufficient resources for %d XDP TX queues (%d other channels, max VIs %d)\n",
n_xdp_tx, n_channels, efx->max_vis);
netif_warn(efx, drv, efx->net_dev,
"XDP_TX and XDP_REDIRECT might decrease device's performance\n");
} else if (n_channels + n_xdp_ev > max_channels) {
efx->xdp_txq_queues_mode = EFX_XDP_TX_QUEUES_SHARED;
netif_warn(efx, drv, efx->net_dev,
"Insufficient resources for %d XDP event queues (%d other channels, max %d)\n",
n_xdp_ev, n_channels, max_channels);
n_xdp_ev = max_channels - n_channels;
netif_warn(efx, drv, efx->net_dev,
"XDP_TX and XDP_REDIRECT will work with reduced performance (%d cpus/tx_queue)\n",
DIV_ROUND_UP(n_xdp_tx, tx_per_ev * n_xdp_ev));
} else {
efx->xdp_txq_queues_mode = EFX_XDP_TX_QUEUES_DEDICATED;
}
if (efx->xdp_txq_queues_mode != EFX_XDP_TX_QUEUES_BORROWED) {
efx->n_xdp_channels = n_xdp_ev;
efx->xdp_tx_per_channel = tx_per_ev;
efx->xdp_tx_queue_count = n_xdp_tx;
n_channels += n_xdp_ev;
netif_dbg(efx, drv, efx->net_dev,
"Allocating %d TX and %d event queues for XDP\n",
n_xdp_ev * tx_per_ev, n_xdp_ev);
} else {
efx->n_xdp_channels = 0;
efx->xdp_tx_per_channel = 0;
efx->xdp_tx_queue_count = n_xdp_tx;
}
if (vec_count < n_channels) {
netif_err(efx, drv, efx->net_dev,
"WARNING: Insufficient MSI-X vectors available (%d < %u).\n",
vec_count, n_channels);
netif_err(efx, drv, efx->net_dev,
"WARNING: Performance may be reduced.\n");
n_channels = vec_count;
}
n_channels = min(n_channels, max_channels);
efx->n_channels = n_channels;
/* Ignore XDP tx channels when creating rx channels. */
n_channels -= efx->n_xdp_channels;
if (efx_separate_tx_channels) {
efx->n_tx_channels =
min(max(n_channels / 2, 1U),
efx->max_tx_channels);
efx->tx_channel_offset =
n_channels - efx->n_tx_channels;
efx->n_rx_channels =
max(n_channels -
efx->n_tx_channels, 1U);
} else {
efx->n_tx_channels = min(n_channels, efx->max_tx_channels);
efx->tx_channel_offset = 0;
efx->n_rx_channels = n_channels;
}
efx->n_rx_channels = min(efx->n_rx_channels, parallelism);
efx->n_tx_channels = min(efx->n_tx_channels, parallelism);
efx->xdp_channel_offset = n_channels;
netif_dbg(efx, drv, efx->net_dev,
"Allocating %u RX channels\n",
efx->n_rx_channels);
return efx->n_channels;
}
/* Probe the number and type of interrupts we are able to obtain, and
* the resulting numbers of channels and RX queues.
*/
int efx_probe_interrupts(struct efx_nic *efx)
{
unsigned int extra_channels = 0;
unsigned int rss_spread;
unsigned int i, j;
int rc;
for (i = 0; i < EFX_MAX_EXTRA_CHANNELS; i++)
if (efx->extra_channel_type[i])
++extra_channels;
if (efx->interrupt_mode == EFX_INT_MODE_MSIX) {
unsigned int parallelism = efx_wanted_parallelism(efx);
struct msix_entry xentries[EFX_MAX_CHANNELS];
unsigned int n_channels;
rc = efx_allocate_msix_channels(efx, efx->max_channels,
extra_channels, parallelism);
if (rc >= 0) {
n_channels = rc;
for (i = 0; i < n_channels; i++)
xentries[i].entry = i;
rc = pci_enable_msix_range(efx->pci_dev, xentries, 1,
n_channels);
}
if (rc < 0) {
/* Fall back to single channel MSI */
netif_err(efx, drv, efx->net_dev,
"could not enable MSI-X\n");
if (efx->type->min_interrupt_mode >= EFX_INT_MODE_MSI)
efx->interrupt_mode = EFX_INT_MODE_MSI;
else
return rc;
} else if (rc < n_channels) {
netif_err(efx, drv, efx->net_dev,
"WARNING: Insufficient MSI-X vectors"
" available (%d < %u).\n", rc, n_channels);
netif_err(efx, drv, efx->net_dev,
"WARNING: Performance may be reduced.\n");
n_channels = rc;
}
if (rc > 0) {
for (i = 0; i < efx->n_channels; i++)
efx_get_channel(efx, i)->irq =
xentries[i].vector;
}
}
/* Try single interrupt MSI */
if (efx->interrupt_mode == EFX_INT_MODE_MSI) {
efx->n_channels = 1;
efx->n_rx_channels = 1;
efx->n_tx_channels = 1;
efx->tx_channel_offset = 0;
efx->n_xdp_channels = 0;
efx->xdp_channel_offset = efx->n_channels;
efx->xdp_txq_queues_mode = EFX_XDP_TX_QUEUES_BORROWED;
rc = pci_enable_msi(efx->pci_dev);
if (rc == 0) {
efx_get_channel(efx, 0)->irq = efx->pci_dev->irq;
} else {
netif_err(efx, drv, efx->net_dev,
"could not enable MSI\n");
if (efx->type->min_interrupt_mode >= EFX_INT_MODE_LEGACY)
efx->interrupt_mode = EFX_INT_MODE_LEGACY;
else
return rc;
}
}
/* Assume legacy interrupts */
if (efx->interrupt_mode == EFX_INT_MODE_LEGACY) {
efx->n_channels = 1 + (efx_separate_tx_channels ? 1 : 0);
efx->n_rx_channels = 1;
efx->n_tx_channels = 1;
efx->tx_channel_offset = efx_separate_tx_channels ? 1 : 0;
efx->n_xdp_channels = 0;
efx->xdp_channel_offset = efx->n_channels;
efx->xdp_txq_queues_mode = EFX_XDP_TX_QUEUES_BORROWED;
efx->legacy_irq = efx->pci_dev->irq;
}
/* Assign extra channels if possible, before XDP channels */
efx->n_extra_tx_channels = 0;
j = efx->xdp_channel_offset;
for (i = 0; i < EFX_MAX_EXTRA_CHANNELS; i++) {
if (!efx->extra_channel_type[i])
continue;
if (j <= efx->tx_channel_offset + efx->n_tx_channels) {
efx->extra_channel_type[i]->handle_no_channel(efx);
} else {
--j;
efx_get_channel(efx, j)->type =
efx->extra_channel_type[i];
if (efx_channel_has_tx_queues(efx_get_channel(efx, j)))
efx->n_extra_tx_channels++;
}
}
rss_spread = efx->n_rx_channels;
/* RSS might be usable on VFs even if it is disabled on the PF */
#ifdef CONFIG_SFC_SRIOV
if (efx->type->sriov_wanted) {
efx->rss_spread = ((rss_spread > 1 ||
!efx->type->sriov_wanted(efx)) ?
rss_spread : efx_vf_size(efx));
return 0;
}
#endif
efx->rss_spread = rss_spread;
return 0;
}
#if defined(CONFIG_SMP)
void efx_set_interrupt_affinity(struct efx_nic *efx)
{
const struct cpumask *numa_mask = cpumask_of_pcibus(efx->pci_dev->bus);
struct efx_channel *channel;
unsigned int cpu;
/* If no online CPUs in local node, fallback to any online CPU */
if (cpumask_first_and(cpu_online_mask, numa_mask) >= nr_cpu_ids)
numa_mask = cpu_online_mask;
cpu = -1;
efx_for_each_channel(channel, efx) {
cpu = cpumask_next_and(cpu, cpu_online_mask, numa_mask);
if (cpu >= nr_cpu_ids)
cpu = cpumask_first_and(cpu_online_mask, numa_mask);
irq_set_affinity_hint(channel->irq, cpumask_of(cpu));
}
}
void efx_clear_interrupt_affinity(struct efx_nic *efx)
{
struct efx_channel *channel;
efx_for_each_channel(channel, efx)
irq_set_affinity_hint(channel->irq, NULL);
}
#else
void
efx_set_interrupt_affinity(struct efx_nic *efx __attribute__ ((unused)))
{
}
void
efx_clear_interrupt_affinity(struct efx_nic *efx __attribute__ ((unused)))
{
}
#endif /* CONFIG_SMP */
void efx_remove_interrupts(struct efx_nic *efx)
{
struct efx_channel *channel;
/* Remove MSI/MSI-X interrupts */
efx_for_each_channel(channel, efx)
channel->irq = 0;
pci_disable_msi(efx->pci_dev);
pci_disable_msix(efx->pci_dev);
/* Remove legacy interrupt */
efx->legacy_irq = 0;
}
/***************
* EVENT QUEUES
***************/
/* Create event queue
* Event queue memory allocations are done only once. If the channel
* is reset, the memory buffer will be reused; this guards against
* errors during channel reset and also simplifies interrupt handling.
*/
int efx_probe_eventq(struct efx_channel *channel)
{
struct efx_nic *efx = channel->efx;
unsigned long entries;
netif_dbg(efx, probe, efx->net_dev,
"chan %d create event queue\n", channel->channel);
/* Build an event queue with room for one event per tx and rx buffer,
* plus some extra for link state events and MCDI completions.
*/
entries = roundup_pow_of_two(efx->rxq_entries + efx->txq_entries + 128);
EFX_WARN_ON_PARANOID(entries > EFX_MAX_EVQ_SIZE);
channel->eventq_mask = max(entries, EFX_MIN_EVQ_SIZE) - 1;
return efx_nic_probe_eventq(channel);
}
/* Prepare channel's event queue */
int efx_init_eventq(struct efx_channel *channel)
{
struct efx_nic *efx = channel->efx;
int rc;
EFX_WARN_ON_PARANOID(channel->eventq_init);
netif_dbg(efx, drv, efx->net_dev,
"chan %d init event queue\n", channel->channel);
rc = efx_nic_init_eventq(channel);
if (rc == 0) {
efx->type->push_irq_moderation(channel);
channel->eventq_read_ptr = 0;
channel->eventq_init = true;
}
return rc;
}
/* Enable event queue processing and NAPI */
void efx_start_eventq(struct efx_channel *channel)
{
netif_dbg(channel->efx, ifup, channel->efx->net_dev,
"chan %d start event queue\n", channel->channel);
/* Make sure the NAPI handler sees the enabled flag set */
channel->enabled = true;
smp_wmb();
napi_enable(&channel->napi_str);
efx_nic_eventq_read_ack(channel);
}
/* Disable event queue processing and NAPI */
void efx_stop_eventq(struct efx_channel *channel)
{
if (!channel->enabled)
return;
napi_disable(&channel->napi_str);
channel->enabled = false;
}
void efx_fini_eventq(struct efx_channel *channel)
{
if (!channel->eventq_init)
return;
netif_dbg(channel->efx, drv, channel->efx->net_dev,
"chan %d fini event queue\n", channel->channel);
efx_nic_fini_eventq(channel);
channel->eventq_init = false;
}
void efx_remove_eventq(struct efx_channel *channel)
{
netif_dbg(channel->efx, drv, channel->efx->net_dev,
"chan %d remove event queue\n", channel->channel);
efx_nic_remove_eventq(channel);
}
/**************************************************************************
*
* Channel handling
*
*************************************************************************/
#ifdef CONFIG_RFS_ACCEL
static void efx_filter_rfs_expire(struct work_struct *data)
{
struct delayed_work *dwork = to_delayed_work(data);
struct efx_channel *channel;
unsigned int time, quota;
channel = container_of(dwork, struct efx_channel, filter_work);
time = jiffies - channel->rfs_last_expiry;
quota = channel->rfs_filter_count * time / (30 * HZ);
if (quota >= 20 && __efx_filter_rfs_expire(channel, min(channel->rfs_filter_count, quota)))
channel->rfs_last_expiry += time;
/* Ensure we do more work eventually even if NAPI poll is not happening */
schedule_delayed_work(dwork, 30 * HZ);
}
#endif
/* Allocate and initialise a channel structure. */
static struct efx_channel *efx_alloc_channel(struct efx_nic *efx, int i)
{
struct efx_rx_queue *rx_queue;
struct efx_tx_queue *tx_queue;
struct efx_channel *channel;
int j;
channel = kzalloc(sizeof(*channel), GFP_KERNEL);
if (!channel)
return NULL;
channel->efx = efx;
channel->channel = i;
channel->type = &efx_default_channel_type;
for (j = 0; j < EFX_MAX_TXQ_PER_CHANNEL; j++) {
tx_queue = &channel->tx_queue[j];
tx_queue->efx = efx;
tx_queue->queue = -1;
tx_queue->label = j;
tx_queue->channel = channel;
}
#ifdef CONFIG_RFS_ACCEL
INIT_DELAYED_WORK(&channel->filter_work, efx_filter_rfs_expire);
#endif
rx_queue = &channel->rx_queue;
rx_queue->efx = efx;
timer_setup(&rx_queue->slow_fill, efx_rx_slow_fill, 0);
return channel;
}
int efx_init_channels(struct efx_nic *efx)
{
unsigned int i;
for (i = 0; i < EFX_MAX_CHANNELS; i++) {
efx->channel[i] = efx_alloc_channel(efx, i);
if (!efx->channel[i])
return -ENOMEM;
efx->msi_context[i].efx = efx;
efx->msi_context[i].index = i;
}
/* Higher numbered interrupt modes are less capable! */
efx->interrupt_mode = min(efx->type->min_interrupt_mode,
efx_interrupt_mode);
efx->max_channels = EFX_MAX_CHANNELS;
efx->max_tx_channels = EFX_MAX_CHANNELS;
return 0;
}
void efx_fini_channels(struct efx_nic *efx)
{
unsigned int i;
for (i = 0; i < EFX_MAX_CHANNELS; i++)
if (efx->channel[i]) {
kfree(efx->channel[i]);
efx->channel[i] = NULL;
}
}
/* Allocate and initialise a channel structure, copying parameters
* (but not resources) from an old channel structure.
*/
struct efx_channel *efx_copy_channel(const struct efx_channel *old_channel)
{
struct efx_rx_queue *rx_queue;
struct efx_tx_queue *tx_queue;
struct efx_channel *channel;
int j;
channel = kmalloc(sizeof(*channel), GFP_KERNEL);
if (!channel)
return NULL;
*channel = *old_channel;
channel->napi_dev = NULL;
INIT_HLIST_NODE(&channel->napi_str.napi_hash_node);
channel->napi_str.napi_id = 0;
channel->napi_str.state = 0;
memset(&channel->eventq, 0, sizeof(channel->eventq));
for (j = 0; j < EFX_MAX_TXQ_PER_CHANNEL; j++) {
tx_queue = &channel->tx_queue[j];
if (tx_queue->channel)
tx_queue->channel = channel;
tx_queue->buffer = NULL;
tx_queue->cb_page = NULL;
memset(&tx_queue->txd, 0, sizeof(tx_queue->txd));
}
rx_queue = &channel->rx_queue;
rx_queue->buffer = NULL;
memset(&rx_queue->rxd, 0, sizeof(rx_queue->rxd));
timer_setup(&rx_queue->slow_fill, efx_rx_slow_fill, 0);
#ifdef CONFIG_RFS_ACCEL
INIT_DELAYED_WORK(&channel->filter_work, efx_filter_rfs_expire);
#endif
return channel;
}
static int efx_probe_channel(struct efx_channel *channel)
{
struct efx_tx_queue *tx_queue;
struct efx_rx_queue *rx_queue;
int rc;
netif_dbg(channel->efx, probe, channel->efx->net_dev,
"creating channel %d\n", channel->channel);
rc = channel->type->pre_probe(channel);
if (rc)
goto fail;
rc = efx_probe_eventq(channel);
if (rc)
goto fail;
efx_for_each_channel_tx_queue(tx_queue, channel) {
rc = efx_probe_tx_queue(tx_queue);
if (rc)
goto fail;
}
efx_for_each_channel_rx_queue(rx_queue, channel) {
rc = efx_probe_rx_queue(rx_queue);
if (rc)
goto fail;
}
channel->rx_list = NULL;
return 0;
fail:
efx_remove_channel(channel);
return rc;
}
static void efx_get_channel_name(struct efx_channel *channel, char *buf,
size_t len)
{
struct efx_nic *efx = channel->efx;
const char *type;
int number;
number = channel->channel;
if (number >= efx->xdp_channel_offset &&
!WARN_ON_ONCE(!efx->n_xdp_channels)) {
type = "-xdp";
number -= efx->xdp_channel_offset;
} else if (efx->tx_channel_offset == 0) {
type = "";
} else if (number < efx->tx_channel_offset) {
type = "-rx";
} else {
type = "-tx";
number -= efx->tx_channel_offset;
}
snprintf(buf, len, "%s%s-%d", efx->name, type, number);
}
void efx_set_channel_names(struct efx_nic *efx)
{
struct efx_channel *channel;
efx_for_each_channel(channel, efx)
channel->type->get_name(channel,
efx->msi_context[channel->channel].name,
sizeof(efx->msi_context[0].name));
}
int efx_probe_channels(struct efx_nic *efx)
{
struct efx_channel *channel;
int rc;
/* Probe channels in reverse, so that any 'extra' channels
* use the start of the buffer table. This allows the traffic
* channels to be resized without moving them or wasting the
* entries before them.
*/
efx_for_each_channel_rev(channel, efx) {
rc = efx_probe_channel(channel);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"failed to create channel %d\n",
channel->channel);
goto fail;
}
}
efx_set_channel_names(efx);
return 0;
fail:
efx_remove_channels(efx);
return rc;
}
void efx_remove_channel(struct efx_channel *channel)
{
struct efx_tx_queue *tx_queue;
struct efx_rx_queue *rx_queue;
netif_dbg(channel->efx, drv, channel->efx->net_dev,
"destroy chan %d\n", channel->channel);
efx_for_each_channel_rx_queue(rx_queue, channel)
efx_remove_rx_queue(rx_queue);
efx_for_each_channel_tx_queue(tx_queue, channel)
efx_remove_tx_queue(tx_queue);
efx_remove_eventq(channel);
channel->type->post_remove(channel);
}
void efx_remove_channels(struct efx_nic *efx)
{
struct efx_channel *channel;
efx_for_each_channel(channel, efx)
efx_remove_channel(channel);
kfree(efx->xdp_tx_queues);
}
static int efx_set_xdp_tx_queue(struct efx_nic *efx, int xdp_queue_number,
struct efx_tx_queue *tx_queue)
{
if (xdp_queue_number >= efx->xdp_tx_queue_count)
return -EINVAL;
netif_dbg(efx, drv, efx->net_dev,
"Channel %u TXQ %u is XDP %u, HW %u\n",
tx_queue->channel->channel, tx_queue->label,
xdp_queue_number, tx_queue->queue);
efx->xdp_tx_queues[xdp_queue_number] = tx_queue;
return 0;
}
static void efx_set_xdp_channels(struct efx_nic *efx)
{
struct efx_tx_queue *tx_queue;
struct efx_channel *channel;
unsigned int next_queue = 0;
int xdp_queue_number = 0;
int rc;
/* We need to mark which channels really have RX and TX
* queues, and adjust the TX queue numbers if we have separate
* RX-only and TX-only channels.
*/
efx_for_each_channel(channel, efx) {
if (channel->channel < efx->tx_channel_offset)
continue;
if (efx_channel_is_xdp_tx(channel)) {
efx_for_each_channel_tx_queue(tx_queue, channel) {
tx_queue->queue = next_queue++;
rc = efx_set_xdp_tx_queue(efx, xdp_queue_number,
tx_queue);
if (rc == 0)
xdp_queue_number++;
}
} else {
efx_for_each_channel_tx_queue(tx_queue, channel) {
tx_queue->queue = next_queue++;
netif_dbg(efx, drv, efx->net_dev,
"Channel %u TXQ %u is HW %u\n",
channel->channel, tx_queue->label,
tx_queue->queue);
}
/* If XDP is borrowing queues from net stack, it must
* use the queue with no csum offload, which is the
* first one of the channel
* (note: tx_queue_by_type is not initialized yet)
*/
if (efx->xdp_txq_queues_mode ==
EFX_XDP_TX_QUEUES_BORROWED) {
tx_queue = &channel->tx_queue[0];
rc = efx_set_xdp_tx_queue(efx, xdp_queue_number,
tx_queue);
if (rc == 0)
xdp_queue_number++;
}
}
}
WARN_ON(efx->xdp_txq_queues_mode == EFX_XDP_TX_QUEUES_DEDICATED &&
xdp_queue_number != efx->xdp_tx_queue_count);
WARN_ON(efx->xdp_txq_queues_mode != EFX_XDP_TX_QUEUES_DEDICATED &&
xdp_queue_number > efx->xdp_tx_queue_count);
/* If we have more CPUs than assigned XDP TX queues, assign the already
* existing queues to the exceeding CPUs
*/
next_queue = 0;
while (xdp_queue_number < efx->xdp_tx_queue_count) {
tx_queue = efx->xdp_tx_queues[next_queue++];
rc = efx_set_xdp_tx_queue(efx, xdp_queue_number, tx_queue);
if (rc == 0)
xdp_queue_number++;
}
}
int efx_realloc_channels(struct efx_nic *efx, u32 rxq_entries, u32 txq_entries)
{
struct efx_channel *other_channel[EFX_MAX_CHANNELS], *channel,
*ptp_channel = efx_ptp_channel(efx);
struct efx_ptp_data *ptp_data = efx->ptp_data;
u32 old_rxq_entries, old_txq_entries;
unsigned int i;
int rc, rc2;
rc = efx_check_disabled(efx);
if (rc)
return rc;
efx_device_detach_sync(efx);
efx_stop_all(efx);
efx_soft_disable_interrupts(efx);
/* Clone channels (where possible) */
memset(other_channel, 0, sizeof(other_channel));
for (i = 0; i < efx->n_channels; i++) {
channel = efx->channel[i];
if (channel->type->copy)
channel = channel->type->copy(channel);
if (!channel) {
rc = -ENOMEM;
goto out;
}
other_channel[i] = channel;
}
/* Swap entry counts and channel pointers */
old_rxq_entries = efx->rxq_entries;
old_txq_entries = efx->txq_entries;
efx->rxq_entries = rxq_entries;
efx->txq_entries = txq_entries;
for (i = 0; i < efx->n_channels; i++)
swap(efx->channel[i], other_channel[i]);
for (i = 0; i < efx->n_channels; i++) {
channel = efx->channel[i];
if (!channel->type->copy)
continue;
rc = efx_probe_channel(channel);
if (rc)
goto rollback;
efx_init_napi_channel(efx->channel[i]);
}
efx_set_xdp_channels(efx);
out:
efx->ptp_data = NULL;
/* Destroy unused channel structures */
for (i = 0; i < efx->n_channels; i++) {
channel = other_channel[i];
if (channel && channel->type->copy) {
efx_fini_napi_channel(channel);
efx_remove_channel(channel);
kfree(channel);
}
}
efx->ptp_data = ptp_data;
rc2 = efx_soft_enable_interrupts(efx);
if (rc2) {
rc = rc ? rc : rc2;
netif_err(efx, drv, efx->net_dev,
"unable to restart interrupts on channel reallocation\n");
efx_schedule_reset(efx, RESET_TYPE_DISABLE);
} else {
efx_start_all(efx);
efx_device_attach_if_not_resetting(efx);
}
return rc;
rollback:
/* Swap back */
efx->rxq_entries = old_rxq_entries;
efx->txq_entries = old_txq_entries;
for (i = 0; i < efx->n_channels; i++)
swap(efx->channel[i], other_channel[i]);
efx_ptp_update_channel(efx, ptp_channel);
goto out;
}
int efx_set_channels(struct efx_nic *efx)
{
struct efx_channel *channel;
int rc;
if (efx->xdp_tx_queue_count) {
EFX_WARN_ON_PARANOID(efx->xdp_tx_queues);
/* Allocate array for XDP TX queue lookup. */
efx->xdp_tx_queues = kcalloc(efx->xdp_tx_queue_count,
sizeof(*efx->xdp_tx_queues),
GFP_KERNEL);
if (!efx->xdp_tx_queues)
return -ENOMEM;
}
efx_for_each_channel(channel, efx) {
if (channel->channel < efx->n_rx_channels)
channel->rx_queue.core_index = channel->channel;
else
channel->rx_queue.core_index = -1;
}
efx_set_xdp_channels(efx);
rc = netif_set_real_num_tx_queues(efx->net_dev, efx->n_tx_channels);
if (rc)
return rc;
return netif_set_real_num_rx_queues(efx->net_dev, efx->n_rx_channels);
}
static bool efx_default_channel_want_txqs(struct efx_channel *channel)
{
return channel->channel - channel->efx->tx_channel_offset <
channel->efx->n_tx_channels;
}
/*************
* START/STOP
*************/
int efx_soft_enable_interrupts(struct efx_nic *efx)
{
struct efx_channel *channel, *end_channel;
int rc;
BUG_ON(efx->state == STATE_DISABLED);
efx->irq_soft_enabled = true;
smp_wmb();
efx_for_each_channel(channel, efx) {
if (!channel->type->keep_eventq) {
rc = efx_init_eventq(channel);
if (rc)
goto fail;
}
efx_start_eventq(channel);
}
efx_mcdi_mode_event(efx);
return 0;
fail:
end_channel = channel;
efx_for_each_channel(channel, efx) {
if (channel == end_channel)
break;
efx_stop_eventq(channel);
if (!channel->type->keep_eventq)
efx_fini_eventq(channel);
}
return rc;
}
void efx_soft_disable_interrupts(struct efx_nic *efx)
{
struct efx_channel *channel;
if (efx->state == STATE_DISABLED)
return;
efx_mcdi_mode_poll(efx);
efx->irq_soft_enabled = false;
smp_wmb();
if (efx->legacy_irq)
synchronize_irq(efx->legacy_irq);
efx_for_each_channel(channel, efx) {
if (channel->irq)
synchronize_irq(channel->irq);
efx_stop_eventq(channel);
if (!channel->type->keep_eventq)
efx_fini_eventq(channel);
}
/* Flush the asynchronous MCDI request queue */
efx_mcdi_flush_async(efx);
}
int efx_enable_interrupts(struct efx_nic *efx)
{
struct efx_channel *channel, *end_channel;
int rc;
/* TODO: Is this really a bug? */
BUG_ON(efx->state == STATE_DISABLED);
if (efx->eeh_disabled_legacy_irq) {
enable_irq(efx->legacy_irq);
efx->eeh_disabled_legacy_irq = false;
}
efx->type->irq_enable_master(efx);
efx_for_each_channel(channel, efx) {
if (channel->type->keep_eventq) {
rc = efx_init_eventq(channel);
if (rc)
goto fail;
}
}
rc = efx_soft_enable_interrupts(efx);
if (rc)
goto fail;
return 0;
fail:
end_channel = channel;
efx_for_each_channel(channel, efx) {
if (channel == end_channel)
break;
if (channel->type->keep_eventq)
efx_fini_eventq(channel);
}
efx->type->irq_disable_non_ev(efx);
return rc;
}
void efx_disable_interrupts(struct efx_nic *efx)
{
struct efx_channel *channel;
efx_soft_disable_interrupts(efx);
efx_for_each_channel(channel, efx) {
if (channel->type->keep_eventq)
efx_fini_eventq(channel);
}
efx->type->irq_disable_non_ev(efx);
}
void efx_start_channels(struct efx_nic *efx)
{
struct efx_tx_queue *tx_queue;
struct efx_rx_queue *rx_queue;
struct efx_channel *channel;
efx_for_each_channel_rev(channel, efx) {
if (channel->type->start)
channel->type->start(channel);
efx_for_each_channel_tx_queue(tx_queue, channel) {
efx_init_tx_queue(tx_queue);
atomic_inc(&efx->active_queues);
}
efx_for_each_channel_rx_queue(rx_queue, channel) {
efx_init_rx_queue(rx_queue);
atomic_inc(&efx->active_queues);
efx_stop_eventq(channel);
efx_fast_push_rx_descriptors(rx_queue, false);
efx_start_eventq(channel);
}
WARN_ON(channel->rx_pkt_n_frags);
}
}
void efx_stop_channels(struct efx_nic *efx)
{
struct efx_tx_queue *tx_queue;
struct efx_rx_queue *rx_queue;
struct efx_channel *channel;
int rc = 0;
/* Stop special channels and RX refill.
* The channel's stop has to be called first, since it might wait
* for a sentinel RX to indicate the channel has fully drained.
*/
efx_for_each_channel(channel, efx) {
if (channel->type->stop)
channel->type->stop(channel);
efx_for_each_channel_rx_queue(rx_queue, channel)
rx_queue->refill_enabled = false;
}
efx_for_each_channel(channel, efx) {
/* RX packet processing is pipelined, so wait for the
* NAPI handler to complete. At least event queue 0
* might be kept active by non-data events, so don't
* use napi_synchronize() but actually disable NAPI
* temporarily.
*/
if (efx_channel_has_rx_queue(channel)) {
efx_stop_eventq(channel);
efx_start_eventq(channel);
}
}
if (efx->type->fini_dmaq)
rc = efx->type->fini_dmaq(efx);
if (rc) {
netif_err(efx, drv, efx->net_dev, "failed to flush queues\n");
} else {
netif_dbg(efx, drv, efx->net_dev,
"successfully flushed all queues\n");
}
efx_for_each_channel(channel, efx) {
efx_for_each_channel_rx_queue(rx_queue, channel)
efx_fini_rx_queue(rx_queue);
efx_for_each_channel_tx_queue(tx_queue, channel)
efx_fini_tx_queue(tx_queue);
}
}
/**************************************************************************
*
* NAPI interface
*
*************************************************************************/
/* Process channel's event queue
*
* This function is responsible for processing the event queue of a
* single channel. The caller must guarantee that this function will
* never be concurrently called more than once on the same channel,
* though different channels may be being processed concurrently.
*/
static int efx_process_channel(struct efx_channel *channel, int budget)
{
struct efx_tx_queue *tx_queue;
struct list_head rx_list;
int spent;
if (unlikely(!channel->enabled))
return 0;
/* Prepare the batch receive list */
EFX_WARN_ON_PARANOID(channel->rx_list != NULL);
INIT_LIST_HEAD(&rx_list);
channel->rx_list = &rx_list;
efx_for_each_channel_tx_queue(tx_queue, channel) {
tx_queue->pkts_compl = 0;
tx_queue->bytes_compl = 0;
}
spent = efx_nic_process_eventq(channel, budget);
if (spent && efx_channel_has_rx_queue(channel)) {
struct efx_rx_queue *rx_queue =
efx_channel_get_rx_queue(channel);
efx_rx_flush_packet(channel);
efx_fast_push_rx_descriptors(rx_queue, true);
}
/* Update BQL */
efx_for_each_channel_tx_queue(tx_queue, channel) {
if (tx_queue->bytes_compl) {
netdev_tx_completed_queue(tx_queue->core_txq,
tx_queue->pkts_compl,
tx_queue->bytes_compl);
}
}
/* Receive any packets we queued up */
netif_receive_skb_list(channel->rx_list);
channel->rx_list = NULL;
return spent;
}
static void efx_update_irq_mod(struct efx_nic *efx, struct efx_channel *channel)
{
int step = efx->irq_mod_step_us;
if (channel->irq_mod_score < irq_adapt_low_thresh) {
if (channel->irq_moderation_us > step) {
channel->irq_moderation_us -= step;
efx->type->push_irq_moderation(channel);
}
} else if (channel->irq_mod_score > irq_adapt_high_thresh) {
if (channel->irq_moderation_us <
efx->irq_rx_moderation_us) {
channel->irq_moderation_us += step;
efx->type->push_irq_moderation(channel);
}
}
channel->irq_count = 0;
channel->irq_mod_score = 0;
}
/* NAPI poll handler
*
* NAPI guarantees serialisation of polls of the same device, which
* provides the guarantee required by efx_process_channel().
*/
static int efx_poll(struct napi_struct *napi, int budget)
{
struct efx_channel *channel =
container_of(napi, struct efx_channel, napi_str);
struct efx_nic *efx = channel->efx;
#ifdef CONFIG_RFS_ACCEL
unsigned int time;
#endif
int spent;
netif_vdbg(efx, intr, efx->net_dev,
"channel %d NAPI poll executing on CPU %d\n",
channel->channel, raw_smp_processor_id());
spent = efx_process_channel(channel, budget);
xdp_do_flush_map();
if (spent < budget) {
if (efx_channel_has_rx_queue(channel) &&
efx->irq_rx_adaptive &&
unlikely(++channel->irq_count == 1000)) {
efx_update_irq_mod(efx, channel);
}
#ifdef CONFIG_RFS_ACCEL
/* Perhaps expire some ARFS filters */
time = jiffies - channel->rfs_last_expiry;
/* Would our quota be >= 20? */
if (channel->rfs_filter_count * time >= 600 * HZ)
mod_delayed_work(system_wq, &channel->filter_work, 0);
#endif
/* There is no race here; although napi_disable() will
* only wait for napi_complete(), this isn't a problem
* since efx_nic_eventq_read_ack() will have no effect if
* interrupts have already been disabled.
*/
if (napi_complete_done(napi, spent))
efx_nic_eventq_read_ack(channel);
}
return spent;
}
void efx_init_napi_channel(struct efx_channel *channel)
{
struct efx_nic *efx = channel->efx;
channel->napi_dev = efx->net_dev;
netif_napi_add(channel->napi_dev, &channel->napi_str, efx_poll);
}
void efx_init_napi(struct efx_nic *efx)
{
struct efx_channel *channel;
efx_for_each_channel(channel, efx)
efx_init_napi_channel(channel);
}
void efx_fini_napi_channel(struct efx_channel *channel)
{
if (channel->napi_dev)
netif_napi_del(&channel->napi_str);
channel->napi_dev = NULL;
}
void efx_fini_napi(struct efx_nic *efx)
{
struct efx_channel *channel;
efx_for_each_channel(channel, efx)
efx_fini_napi_channel(channel);
}
/***************
* Housekeeping
***************/
static int efx_channel_dummy_op_int(struct efx_channel *channel)
{
return 0;
}
void efx_channel_dummy_op_void(struct efx_channel *channel)
{
}
static const struct efx_channel_type efx_default_channel_type = {
.pre_probe = efx_channel_dummy_op_int,
.post_remove = efx_channel_dummy_op_void,
.get_name = efx_get_channel_name,
.copy = efx_copy_channel,
.want_txqs = efx_default_channel_want_txqs,
.keep_eventq = false,
.want_pio = true,
};
|
linux-master
|
drivers/net/ethernet/sfc/efx_channels.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2019 Solarflare Communications Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include <linux/module.h>
#include <linux/netdevice.h>
#include "net_driver.h"
#include "mcdi.h"
#include "nic.h"
#include "selftest.h"
#include "rx_common.h"
#include "ethtool_common.h"
#include "mcdi_port_common.h"
struct efx_sw_stat_desc {
const char *name;
enum {
EFX_ETHTOOL_STAT_SOURCE_nic,
EFX_ETHTOOL_STAT_SOURCE_channel,
EFX_ETHTOOL_STAT_SOURCE_tx_queue
} source;
unsigned int offset;
u64 (*get_stat)(void *field); /* Reader function */
};
/* Initialiser for a struct efx_sw_stat_desc with type-checking */
#define EFX_ETHTOOL_STAT(stat_name, source_name, field, field_type, \
get_stat_function) { \
.name = #stat_name, \
.source = EFX_ETHTOOL_STAT_SOURCE_##source_name, \
.offset = ((((field_type *) 0) == \
&((struct efx_##source_name *)0)->field) ? \
offsetof(struct efx_##source_name, field) : \
offsetof(struct efx_##source_name, field)), \
.get_stat = get_stat_function, \
}
static u64 efx_get_uint_stat(void *field)
{
return *(unsigned int *)field;
}
static u64 efx_get_atomic_stat(void *field)
{
return atomic_read((atomic_t *) field);
}
#define EFX_ETHTOOL_ATOMIC_NIC_ERROR_STAT(field) \
EFX_ETHTOOL_STAT(field, nic, field, \
atomic_t, efx_get_atomic_stat)
#define EFX_ETHTOOL_UINT_CHANNEL_STAT(field) \
EFX_ETHTOOL_STAT(field, channel, n_##field, \
unsigned int, efx_get_uint_stat)
#define EFX_ETHTOOL_UINT_CHANNEL_STAT_NO_N(field) \
EFX_ETHTOOL_STAT(field, channel, field, \
unsigned int, efx_get_uint_stat)
#define EFX_ETHTOOL_UINT_TXQ_STAT(field) \
EFX_ETHTOOL_STAT(tx_##field, tx_queue, field, \
unsigned int, efx_get_uint_stat)
static const struct efx_sw_stat_desc efx_sw_stat_desc[] = {
EFX_ETHTOOL_UINT_TXQ_STAT(merge_events),
EFX_ETHTOOL_UINT_TXQ_STAT(tso_bursts),
EFX_ETHTOOL_UINT_TXQ_STAT(tso_long_headers),
EFX_ETHTOOL_UINT_TXQ_STAT(tso_packets),
EFX_ETHTOOL_UINT_TXQ_STAT(tso_fallbacks),
EFX_ETHTOOL_UINT_TXQ_STAT(pushes),
EFX_ETHTOOL_UINT_TXQ_STAT(pio_packets),
EFX_ETHTOOL_UINT_TXQ_STAT(cb_packets),
EFX_ETHTOOL_ATOMIC_NIC_ERROR_STAT(rx_reset),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_tobe_disc),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_ip_hdr_chksum_err),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_tcp_udp_chksum_err),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_inner_ip_hdr_chksum_err),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_inner_tcp_udp_chksum_err),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_outer_ip_hdr_chksum_err),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_outer_tcp_udp_chksum_err),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_eth_crc_err),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_mcast_mismatch),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_frm_trunc),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_merge_events),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_merge_packets),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_xdp_drops),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_xdp_bad_drops),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_xdp_tx),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_xdp_redirect),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_mport_bad),
#ifdef CONFIG_RFS_ACCEL
EFX_ETHTOOL_UINT_CHANNEL_STAT_NO_N(rfs_filter_count),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rfs_succeeded),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rfs_failed),
#endif
};
#define EFX_ETHTOOL_SW_STAT_COUNT ARRAY_SIZE(efx_sw_stat_desc)
void efx_ethtool_get_drvinfo(struct net_device *net_dev,
struct ethtool_drvinfo *info)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
strscpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
efx_mcdi_print_fwver(efx, info->fw_version,
sizeof(info->fw_version));
strscpy(info->bus_info, pci_name(efx->pci_dev), sizeof(info->bus_info));
}
u32 efx_ethtool_get_msglevel(struct net_device *net_dev)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
return efx->msg_enable;
}
void efx_ethtool_set_msglevel(struct net_device *net_dev, u32 msg_enable)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
efx->msg_enable = msg_enable;
}
void efx_ethtool_self_test(struct net_device *net_dev,
struct ethtool_test *test, u64 *data)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
struct efx_self_tests *efx_tests;
bool already_up;
int rc = -ENOMEM;
efx_tests = kzalloc(sizeof(*efx_tests), GFP_KERNEL);
if (!efx_tests)
goto fail;
if (!efx_net_active(efx->state)) {
rc = -EBUSY;
goto out;
}
netif_info(efx, drv, efx->net_dev, "starting %sline testing\n",
(test->flags & ETH_TEST_FL_OFFLINE) ? "off" : "on");
/* We need rx buffers and interrupts. */
already_up = (efx->net_dev->flags & IFF_UP);
if (!already_up) {
rc = dev_open(efx->net_dev, NULL);
if (rc) {
netif_err(efx, drv, efx->net_dev,
"failed opening device.\n");
goto out;
}
}
rc = efx_selftest(efx, efx_tests, test->flags);
if (!already_up)
dev_close(efx->net_dev);
netif_info(efx, drv, efx->net_dev, "%s %sline self-tests\n",
rc == 0 ? "passed" : "failed",
(test->flags & ETH_TEST_FL_OFFLINE) ? "off" : "on");
out:
efx_ethtool_fill_self_tests(efx, efx_tests, NULL, data);
kfree(efx_tests);
fail:
if (rc)
test->flags |= ETH_TEST_FL_FAILED;
}
void efx_ethtool_get_pauseparam(struct net_device *net_dev,
struct ethtool_pauseparam *pause)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
pause->rx_pause = !!(efx->wanted_fc & EFX_FC_RX);
pause->tx_pause = !!(efx->wanted_fc & EFX_FC_TX);
pause->autoneg = !!(efx->wanted_fc & EFX_FC_AUTO);
}
int efx_ethtool_set_pauseparam(struct net_device *net_dev,
struct ethtool_pauseparam *pause)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
u8 wanted_fc, old_fc;
u32 old_adv;
int rc = 0;
mutex_lock(&efx->mac_lock);
wanted_fc = ((pause->rx_pause ? EFX_FC_RX : 0) |
(pause->tx_pause ? EFX_FC_TX : 0) |
(pause->autoneg ? EFX_FC_AUTO : 0));
if ((wanted_fc & EFX_FC_TX) && !(wanted_fc & EFX_FC_RX)) {
netif_dbg(efx, drv, efx->net_dev,
"Flow control unsupported: tx ON rx OFF\n");
rc = -EINVAL;
goto out;
}
if ((wanted_fc & EFX_FC_AUTO) && !efx->link_advertising[0]) {
netif_dbg(efx, drv, efx->net_dev,
"Autonegotiation is disabled\n");
rc = -EINVAL;
goto out;
}
/* Hook for Falcon bug 11482 workaround */
if (efx->type->prepare_enable_fc_tx &&
(wanted_fc & EFX_FC_TX) && !(efx->wanted_fc & EFX_FC_TX))
efx->type->prepare_enable_fc_tx(efx);
old_adv = efx->link_advertising[0];
old_fc = efx->wanted_fc;
efx_link_set_wanted_fc(efx, wanted_fc);
if (efx->link_advertising[0] != old_adv ||
(efx->wanted_fc ^ old_fc) & EFX_FC_AUTO) {
rc = efx_mcdi_port_reconfigure(efx);
if (rc) {
netif_err(efx, drv, efx->net_dev,
"Unable to advertise requested flow "
"control setting\n");
goto out;
}
}
/* Reconfigure the MAC. The PHY *may* generate a link state change event
* if the user just changed the advertised capabilities, but there's no
* harm doing this twice */
efx_mac_reconfigure(efx, false);
out:
mutex_unlock(&efx->mac_lock);
return rc;
}
/**
* efx_fill_test - fill in an individual self-test entry
* @test_index: Index of the test
* @strings: Ethtool strings, or %NULL
* @data: Ethtool test results, or %NULL
* @test: Pointer to test result (used only if data != %NULL)
* @unit_format: Unit name format (e.g. "chan\%d")
* @unit_id: Unit id (e.g. 0 for "chan0")
* @test_format: Test name format (e.g. "loopback.\%s.tx.sent")
* @test_id: Test id (e.g. "PHYXS" for "loopback.PHYXS.tx_sent")
*
* Fill in an individual self-test entry.
*/
static void efx_fill_test(unsigned int test_index, u8 *strings, u64 *data,
int *test, const char *unit_format, int unit_id,
const char *test_format, const char *test_id)
{
char unit_str[ETH_GSTRING_LEN], test_str[ETH_GSTRING_LEN];
/* Fill data value, if applicable */
if (data)
data[test_index] = *test;
/* Fill string, if applicable */
if (strings) {
if (strchr(unit_format, '%'))
snprintf(unit_str, sizeof(unit_str),
unit_format, unit_id);
else
strcpy(unit_str, unit_format);
snprintf(test_str, sizeof(test_str), test_format, test_id);
snprintf(strings + test_index * ETH_GSTRING_LEN,
ETH_GSTRING_LEN,
"%-6s %-24s", unit_str, test_str);
}
}
#define EFX_CHANNEL_NAME(_channel) "chan%d", _channel->channel
#define EFX_TX_QUEUE_NAME(_tx_queue) "txq%d", _tx_queue->label
#define EFX_LOOPBACK_NAME(_mode, _counter) \
"loopback.%s." _counter, STRING_TABLE_LOOKUP(_mode, efx_loopback_mode)
/**
* efx_fill_loopback_test - fill in a block of loopback self-test entries
* @efx: Efx NIC
* @lb_tests: Efx loopback self-test results structure
* @mode: Loopback test mode
* @test_index: Starting index of the test
* @strings: Ethtool strings, or %NULL
* @data: Ethtool test results, or %NULL
*
* Fill in a block of loopback self-test entries. Return new test
* index.
*/
static int efx_fill_loopback_test(struct efx_nic *efx,
struct efx_loopback_self_tests *lb_tests,
enum efx_loopback_mode mode,
unsigned int test_index,
u8 *strings, u64 *data)
{
struct efx_channel *channel =
efx_get_channel(efx, efx->tx_channel_offset);
struct efx_tx_queue *tx_queue;
efx_for_each_channel_tx_queue(tx_queue, channel) {
efx_fill_test(test_index++, strings, data,
&lb_tests->tx_sent[tx_queue->label],
EFX_TX_QUEUE_NAME(tx_queue),
EFX_LOOPBACK_NAME(mode, "tx_sent"));
efx_fill_test(test_index++, strings, data,
&lb_tests->tx_done[tx_queue->label],
EFX_TX_QUEUE_NAME(tx_queue),
EFX_LOOPBACK_NAME(mode, "tx_done"));
}
efx_fill_test(test_index++, strings, data,
&lb_tests->rx_good,
"rx", 0,
EFX_LOOPBACK_NAME(mode, "rx_good"));
efx_fill_test(test_index++, strings, data,
&lb_tests->rx_bad,
"rx", 0,
EFX_LOOPBACK_NAME(mode, "rx_bad"));
return test_index;
}
/**
* efx_ethtool_fill_self_tests - get self-test details
* @efx: Efx NIC
* @tests: Efx self-test results structure, or %NULL
* @strings: Ethtool strings, or %NULL
* @data: Ethtool test results, or %NULL
*
* Get self-test number of strings, strings, and/or test results.
* Return number of strings (== number of test results).
*
* The reason for merging these three functions is to make sure that
* they can never be inconsistent.
*/
int efx_ethtool_fill_self_tests(struct efx_nic *efx,
struct efx_self_tests *tests,
u8 *strings, u64 *data)
{
struct efx_channel *channel;
unsigned int n = 0, i;
enum efx_loopback_mode mode;
efx_fill_test(n++, strings, data, &tests->phy_alive,
"phy", 0, "alive", NULL);
efx_fill_test(n++, strings, data, &tests->nvram,
"core", 0, "nvram", NULL);
efx_fill_test(n++, strings, data, &tests->interrupt,
"core", 0, "interrupt", NULL);
/* Event queues */
efx_for_each_channel(channel, efx) {
efx_fill_test(n++, strings, data,
&tests->eventq_dma[channel->channel],
EFX_CHANNEL_NAME(channel),
"eventq.dma", NULL);
efx_fill_test(n++, strings, data,
&tests->eventq_int[channel->channel],
EFX_CHANNEL_NAME(channel),
"eventq.int", NULL);
}
efx_fill_test(n++, strings, data, &tests->memory,
"core", 0, "memory", NULL);
efx_fill_test(n++, strings, data, &tests->registers,
"core", 0, "registers", NULL);
for (i = 0; true; ++i) {
const char *name;
EFX_WARN_ON_PARANOID(i >= EFX_MAX_PHY_TESTS);
name = efx_mcdi_phy_test_name(efx, i);
if (name == NULL)
break;
efx_fill_test(n++, strings, data, &tests->phy_ext[i], "phy", 0, name, NULL);
}
/* Loopback tests */
for (mode = LOOPBACK_NONE; mode <= LOOPBACK_TEST_MAX; mode++) {
if (!(efx->loopback_modes & (1 << mode)))
continue;
n = efx_fill_loopback_test(efx,
&tests->loopback[mode], mode, n,
strings, data);
}
return n;
}
static size_t efx_describe_per_queue_stats(struct efx_nic *efx, u8 *strings)
{
size_t n_stats = 0;
struct efx_channel *channel;
efx_for_each_channel(channel, efx) {
if (efx_channel_has_tx_queues(channel)) {
n_stats++;
if (strings != NULL) {
snprintf(strings, ETH_GSTRING_LEN,
"tx-%u.tx_packets",
channel->tx_queue[0].queue /
EFX_MAX_TXQ_PER_CHANNEL);
strings += ETH_GSTRING_LEN;
}
}
}
efx_for_each_channel(channel, efx) {
if (efx_channel_has_rx_queue(channel)) {
n_stats++;
if (strings != NULL) {
snprintf(strings, ETH_GSTRING_LEN,
"rx-%d.rx_packets", channel->channel);
strings += ETH_GSTRING_LEN;
}
}
}
if (efx->xdp_tx_queue_count && efx->xdp_tx_queues) {
unsigned short xdp;
for (xdp = 0; xdp < efx->xdp_tx_queue_count; xdp++) {
n_stats++;
if (strings) {
snprintf(strings, ETH_GSTRING_LEN,
"tx-xdp-cpu-%hu.tx_packets", xdp);
strings += ETH_GSTRING_LEN;
}
}
}
return n_stats;
}
int efx_ethtool_get_sset_count(struct net_device *net_dev, int string_set)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
switch (string_set) {
case ETH_SS_STATS:
return efx->type->describe_stats(efx, NULL) +
EFX_ETHTOOL_SW_STAT_COUNT +
efx_describe_per_queue_stats(efx, NULL) +
efx_ptp_describe_stats(efx, NULL);
case ETH_SS_TEST:
return efx_ethtool_fill_self_tests(efx, NULL, NULL, NULL);
default:
return -EINVAL;
}
}
void efx_ethtool_get_strings(struct net_device *net_dev,
u32 string_set, u8 *strings)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
int i;
switch (string_set) {
case ETH_SS_STATS:
strings += (efx->type->describe_stats(efx, strings) *
ETH_GSTRING_LEN);
for (i = 0; i < EFX_ETHTOOL_SW_STAT_COUNT; i++)
strscpy(strings + i * ETH_GSTRING_LEN,
efx_sw_stat_desc[i].name, ETH_GSTRING_LEN);
strings += EFX_ETHTOOL_SW_STAT_COUNT * ETH_GSTRING_LEN;
strings += (efx_describe_per_queue_stats(efx, strings) *
ETH_GSTRING_LEN);
efx_ptp_describe_stats(efx, strings);
break;
case ETH_SS_TEST:
efx_ethtool_fill_self_tests(efx, NULL, strings, NULL);
break;
default:
/* No other string sets */
break;
}
}
void efx_ethtool_get_stats(struct net_device *net_dev,
struct ethtool_stats *stats,
u64 *data)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
const struct efx_sw_stat_desc *stat;
struct efx_channel *channel;
struct efx_tx_queue *tx_queue;
struct efx_rx_queue *rx_queue;
int i;
spin_lock_bh(&efx->stats_lock);
/* Get NIC statistics */
data += efx->type->update_stats(efx, data, NULL);
/* Get software statistics */
for (i = 0; i < EFX_ETHTOOL_SW_STAT_COUNT; i++) {
stat = &efx_sw_stat_desc[i];
switch (stat->source) {
case EFX_ETHTOOL_STAT_SOURCE_nic:
data[i] = stat->get_stat((void *)efx + stat->offset);
break;
case EFX_ETHTOOL_STAT_SOURCE_channel:
data[i] = 0;
efx_for_each_channel(channel, efx)
data[i] += stat->get_stat((void *)channel +
stat->offset);
break;
case EFX_ETHTOOL_STAT_SOURCE_tx_queue:
data[i] = 0;
efx_for_each_channel(channel, efx) {
efx_for_each_channel_tx_queue(tx_queue, channel)
data[i] +=
stat->get_stat((void *)tx_queue
+ stat->offset);
}
break;
}
}
data += EFX_ETHTOOL_SW_STAT_COUNT;
spin_unlock_bh(&efx->stats_lock);
efx_for_each_channel(channel, efx) {
if (efx_channel_has_tx_queues(channel)) {
*data = 0;
efx_for_each_channel_tx_queue(tx_queue, channel) {
*data += tx_queue->tx_packets;
}
data++;
}
}
efx_for_each_channel(channel, efx) {
if (efx_channel_has_rx_queue(channel)) {
*data = 0;
efx_for_each_channel_rx_queue(rx_queue, channel) {
*data += rx_queue->rx_packets;
}
data++;
}
}
if (efx->xdp_tx_queue_count && efx->xdp_tx_queues) {
int xdp;
for (xdp = 0; xdp < efx->xdp_tx_queue_count; xdp++) {
data[0] = efx->xdp_tx_queues[xdp]->tx_packets;
data++;
}
}
efx_ptp_update_stats(efx, data);
}
/* This must be called with rtnl_lock held. */
int efx_ethtool_get_link_ksettings(struct net_device *net_dev,
struct ethtool_link_ksettings *cmd)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
struct efx_link_state *link_state = &efx->link_state;
mutex_lock(&efx->mac_lock);
efx_mcdi_phy_get_link_ksettings(efx, cmd);
mutex_unlock(&efx->mac_lock);
/* Both MACs support pause frames (bidirectional and respond-only) */
ethtool_link_ksettings_add_link_mode(cmd, supported, Pause);
ethtool_link_ksettings_add_link_mode(cmd, supported, Asym_Pause);
if (LOOPBACK_INTERNAL(efx)) {
cmd->base.speed = link_state->speed;
cmd->base.duplex = link_state->fd ? DUPLEX_FULL : DUPLEX_HALF;
}
return 0;
}
/* This must be called with rtnl_lock held. */
int efx_ethtool_set_link_ksettings(struct net_device *net_dev,
const struct ethtool_link_ksettings *cmd)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
int rc;
/* GMAC does not support 1000Mbps HD */
if ((cmd->base.speed == SPEED_1000) &&
(cmd->base.duplex != DUPLEX_FULL)) {
netif_dbg(efx, drv, efx->net_dev,
"rejecting unsupported 1000Mbps HD setting\n");
return -EINVAL;
}
mutex_lock(&efx->mac_lock);
rc = efx_mcdi_phy_set_link_ksettings(efx, cmd);
mutex_unlock(&efx->mac_lock);
return rc;
}
int efx_ethtool_get_fecparam(struct net_device *net_dev,
struct ethtool_fecparam *fecparam)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
int rc;
mutex_lock(&efx->mac_lock);
rc = efx_mcdi_phy_get_fecparam(efx, fecparam);
mutex_unlock(&efx->mac_lock);
return rc;
}
int efx_ethtool_set_fecparam(struct net_device *net_dev,
struct ethtool_fecparam *fecparam)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
int rc;
mutex_lock(&efx->mac_lock);
rc = efx_mcdi_phy_set_fecparam(efx, fecparam);
mutex_unlock(&efx->mac_lock);
return rc;
}
/* MAC address mask including only I/G bit */
static const u8 mac_addr_ig_mask[ETH_ALEN] __aligned(2) = {0x01, 0, 0, 0, 0, 0};
#define IP4_ADDR_FULL_MASK ((__force __be32)~0)
#define IP_PROTO_FULL_MASK 0xFF
#define PORT_FULL_MASK ((__force __be16)~0)
#define ETHER_TYPE_FULL_MASK ((__force __be16)~0)
static inline void ip6_fill_mask(__be32 *mask)
{
mask[0] = mask[1] = mask[2] = mask[3] = ~(__be32)0;
}
static int efx_ethtool_get_class_rule(struct efx_nic *efx,
struct ethtool_rx_flow_spec *rule,
u32 *rss_context)
{
struct ethtool_tcpip4_spec *ip_entry = &rule->h_u.tcp_ip4_spec;
struct ethtool_tcpip4_spec *ip_mask = &rule->m_u.tcp_ip4_spec;
struct ethtool_usrip4_spec *uip_entry = &rule->h_u.usr_ip4_spec;
struct ethtool_usrip4_spec *uip_mask = &rule->m_u.usr_ip4_spec;
struct ethtool_tcpip6_spec *ip6_entry = &rule->h_u.tcp_ip6_spec;
struct ethtool_tcpip6_spec *ip6_mask = &rule->m_u.tcp_ip6_spec;
struct ethtool_usrip6_spec *uip6_entry = &rule->h_u.usr_ip6_spec;
struct ethtool_usrip6_spec *uip6_mask = &rule->m_u.usr_ip6_spec;
struct ethhdr *mac_entry = &rule->h_u.ether_spec;
struct ethhdr *mac_mask = &rule->m_u.ether_spec;
struct efx_filter_spec spec;
int rc;
rc = efx_filter_get_filter_safe(efx, EFX_FILTER_PRI_MANUAL,
rule->location, &spec);
if (rc)
return rc;
if (spec.dmaq_id == EFX_FILTER_RX_DMAQ_ID_DROP)
rule->ring_cookie = RX_CLS_FLOW_DISC;
else
rule->ring_cookie = spec.dmaq_id;
if ((spec.match_flags & EFX_FILTER_MATCH_ETHER_TYPE) &&
spec.ether_type == htons(ETH_P_IP) &&
(spec.match_flags & EFX_FILTER_MATCH_IP_PROTO) &&
(spec.ip_proto == IPPROTO_TCP || spec.ip_proto == IPPROTO_UDP) &&
!(spec.match_flags &
~(EFX_FILTER_MATCH_ETHER_TYPE | EFX_FILTER_MATCH_OUTER_VID |
EFX_FILTER_MATCH_LOC_HOST | EFX_FILTER_MATCH_REM_HOST |
EFX_FILTER_MATCH_IP_PROTO |
EFX_FILTER_MATCH_LOC_PORT | EFX_FILTER_MATCH_REM_PORT))) {
rule->flow_type = ((spec.ip_proto == IPPROTO_TCP) ?
TCP_V4_FLOW : UDP_V4_FLOW);
if (spec.match_flags & EFX_FILTER_MATCH_LOC_HOST) {
ip_entry->ip4dst = spec.loc_host[0];
ip_mask->ip4dst = IP4_ADDR_FULL_MASK;
}
if (spec.match_flags & EFX_FILTER_MATCH_REM_HOST) {
ip_entry->ip4src = spec.rem_host[0];
ip_mask->ip4src = IP4_ADDR_FULL_MASK;
}
if (spec.match_flags & EFX_FILTER_MATCH_LOC_PORT) {
ip_entry->pdst = spec.loc_port;
ip_mask->pdst = PORT_FULL_MASK;
}
if (spec.match_flags & EFX_FILTER_MATCH_REM_PORT) {
ip_entry->psrc = spec.rem_port;
ip_mask->psrc = PORT_FULL_MASK;
}
} else if ((spec.match_flags & EFX_FILTER_MATCH_ETHER_TYPE) &&
spec.ether_type == htons(ETH_P_IPV6) &&
(spec.match_flags & EFX_FILTER_MATCH_IP_PROTO) &&
(spec.ip_proto == IPPROTO_TCP || spec.ip_proto == IPPROTO_UDP) &&
!(spec.match_flags &
~(EFX_FILTER_MATCH_ETHER_TYPE | EFX_FILTER_MATCH_OUTER_VID |
EFX_FILTER_MATCH_LOC_HOST | EFX_FILTER_MATCH_REM_HOST |
EFX_FILTER_MATCH_IP_PROTO |
EFX_FILTER_MATCH_LOC_PORT | EFX_FILTER_MATCH_REM_PORT))) {
rule->flow_type = ((spec.ip_proto == IPPROTO_TCP) ?
TCP_V6_FLOW : UDP_V6_FLOW);
if (spec.match_flags & EFX_FILTER_MATCH_LOC_HOST) {
memcpy(ip6_entry->ip6dst, spec.loc_host,
sizeof(ip6_entry->ip6dst));
ip6_fill_mask(ip6_mask->ip6dst);
}
if (spec.match_flags & EFX_FILTER_MATCH_REM_HOST) {
memcpy(ip6_entry->ip6src, spec.rem_host,
sizeof(ip6_entry->ip6src));
ip6_fill_mask(ip6_mask->ip6src);
}
if (spec.match_flags & EFX_FILTER_MATCH_LOC_PORT) {
ip6_entry->pdst = spec.loc_port;
ip6_mask->pdst = PORT_FULL_MASK;
}
if (spec.match_flags & EFX_FILTER_MATCH_REM_PORT) {
ip6_entry->psrc = spec.rem_port;
ip6_mask->psrc = PORT_FULL_MASK;
}
} else if (!(spec.match_flags &
~(EFX_FILTER_MATCH_LOC_MAC | EFX_FILTER_MATCH_LOC_MAC_IG |
EFX_FILTER_MATCH_REM_MAC | EFX_FILTER_MATCH_ETHER_TYPE |
EFX_FILTER_MATCH_OUTER_VID))) {
rule->flow_type = ETHER_FLOW;
if (spec.match_flags &
(EFX_FILTER_MATCH_LOC_MAC | EFX_FILTER_MATCH_LOC_MAC_IG)) {
ether_addr_copy(mac_entry->h_dest, spec.loc_mac);
if (spec.match_flags & EFX_FILTER_MATCH_LOC_MAC)
eth_broadcast_addr(mac_mask->h_dest);
else
ether_addr_copy(mac_mask->h_dest,
mac_addr_ig_mask);
}
if (spec.match_flags & EFX_FILTER_MATCH_REM_MAC) {
ether_addr_copy(mac_entry->h_source, spec.rem_mac);
eth_broadcast_addr(mac_mask->h_source);
}
if (spec.match_flags & EFX_FILTER_MATCH_ETHER_TYPE) {
mac_entry->h_proto = spec.ether_type;
mac_mask->h_proto = ETHER_TYPE_FULL_MASK;
}
} else if (spec.match_flags & EFX_FILTER_MATCH_ETHER_TYPE &&
spec.ether_type == htons(ETH_P_IP) &&
!(spec.match_flags &
~(EFX_FILTER_MATCH_ETHER_TYPE | EFX_FILTER_MATCH_OUTER_VID |
EFX_FILTER_MATCH_LOC_HOST | EFX_FILTER_MATCH_REM_HOST |
EFX_FILTER_MATCH_IP_PROTO))) {
rule->flow_type = IPV4_USER_FLOW;
uip_entry->ip_ver = ETH_RX_NFC_IP4;
if (spec.match_flags & EFX_FILTER_MATCH_IP_PROTO) {
uip_mask->proto = IP_PROTO_FULL_MASK;
uip_entry->proto = spec.ip_proto;
}
if (spec.match_flags & EFX_FILTER_MATCH_LOC_HOST) {
uip_entry->ip4dst = spec.loc_host[0];
uip_mask->ip4dst = IP4_ADDR_FULL_MASK;
}
if (spec.match_flags & EFX_FILTER_MATCH_REM_HOST) {
uip_entry->ip4src = spec.rem_host[0];
uip_mask->ip4src = IP4_ADDR_FULL_MASK;
}
} else if (spec.match_flags & EFX_FILTER_MATCH_ETHER_TYPE &&
spec.ether_type == htons(ETH_P_IPV6) &&
!(spec.match_flags &
~(EFX_FILTER_MATCH_ETHER_TYPE | EFX_FILTER_MATCH_OUTER_VID |
EFX_FILTER_MATCH_LOC_HOST | EFX_FILTER_MATCH_REM_HOST |
EFX_FILTER_MATCH_IP_PROTO))) {
rule->flow_type = IPV6_USER_FLOW;
if (spec.match_flags & EFX_FILTER_MATCH_IP_PROTO) {
uip6_mask->l4_proto = IP_PROTO_FULL_MASK;
uip6_entry->l4_proto = spec.ip_proto;
}
if (spec.match_flags & EFX_FILTER_MATCH_LOC_HOST) {
memcpy(uip6_entry->ip6dst, spec.loc_host,
sizeof(uip6_entry->ip6dst));
ip6_fill_mask(uip6_mask->ip6dst);
}
if (spec.match_flags & EFX_FILTER_MATCH_REM_HOST) {
memcpy(uip6_entry->ip6src, spec.rem_host,
sizeof(uip6_entry->ip6src));
ip6_fill_mask(uip6_mask->ip6src);
}
} else {
/* The above should handle all filters that we insert */
WARN_ON(1);
return -EINVAL;
}
if (spec.match_flags & EFX_FILTER_MATCH_OUTER_VID) {
rule->flow_type |= FLOW_EXT;
rule->h_ext.vlan_tci = spec.outer_vid;
rule->m_ext.vlan_tci = htons(0xfff);
}
if (spec.flags & EFX_FILTER_FLAG_RX_RSS) {
rule->flow_type |= FLOW_RSS;
*rss_context = spec.rss_context;
}
return rc;
}
int efx_ethtool_get_rxnfc(struct net_device *net_dev,
struct ethtool_rxnfc *info, u32 *rule_locs)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
u32 rss_context = 0;
s32 rc = 0;
switch (info->cmd) {
case ETHTOOL_GRXRINGS:
info->data = efx->n_rx_channels;
return 0;
case ETHTOOL_GRXFH: {
struct efx_rss_context *ctx = &efx->rss_context;
__u64 data;
mutex_lock(&efx->rss_lock);
if (info->flow_type & FLOW_RSS && info->rss_context) {
ctx = efx_find_rss_context_entry(efx, info->rss_context);
if (!ctx) {
rc = -ENOENT;
goto out_unlock;
}
}
data = 0;
if (!efx_rss_active(ctx)) /* No RSS */
goto out_setdata_unlock;
switch (info->flow_type & ~FLOW_RSS) {
case UDP_V4_FLOW:
case UDP_V6_FLOW:
if (ctx->rx_hash_udp_4tuple)
data = (RXH_L4_B_0_1 | RXH_L4_B_2_3 |
RXH_IP_SRC | RXH_IP_DST);
else
data = RXH_IP_SRC | RXH_IP_DST;
break;
case TCP_V4_FLOW:
case TCP_V6_FLOW:
data = (RXH_L4_B_0_1 | RXH_L4_B_2_3 |
RXH_IP_SRC | RXH_IP_DST);
break;
case SCTP_V4_FLOW:
case SCTP_V6_FLOW:
case AH_ESP_V4_FLOW:
case AH_ESP_V6_FLOW:
case IPV4_FLOW:
case IPV6_FLOW:
data = RXH_IP_SRC | RXH_IP_DST;
break;
default:
break;
}
out_setdata_unlock:
info->data = data;
out_unlock:
mutex_unlock(&efx->rss_lock);
return rc;
}
case ETHTOOL_GRXCLSRLCNT:
info->data = efx_filter_get_rx_id_limit(efx);
if (info->data == 0)
return -EOPNOTSUPP;
info->data |= RX_CLS_LOC_SPECIAL;
info->rule_cnt =
efx_filter_count_rx_used(efx, EFX_FILTER_PRI_MANUAL);
return 0;
case ETHTOOL_GRXCLSRULE:
if (efx_filter_get_rx_id_limit(efx) == 0)
return -EOPNOTSUPP;
rc = efx_ethtool_get_class_rule(efx, &info->fs, &rss_context);
if (rc < 0)
return rc;
if (info->fs.flow_type & FLOW_RSS)
info->rss_context = rss_context;
return 0;
case ETHTOOL_GRXCLSRLALL:
info->data = efx_filter_get_rx_id_limit(efx);
if (info->data == 0)
return -EOPNOTSUPP;
rc = efx_filter_get_rx_ids(efx, EFX_FILTER_PRI_MANUAL,
rule_locs, info->rule_cnt);
if (rc < 0)
return rc;
info->rule_cnt = rc;
return 0;
default:
return -EOPNOTSUPP;
}
}
static inline bool ip6_mask_is_full(__be32 mask[4])
{
return !~(mask[0] & mask[1] & mask[2] & mask[3]);
}
static inline bool ip6_mask_is_empty(__be32 mask[4])
{
return !(mask[0] | mask[1] | mask[2] | mask[3]);
}
static int efx_ethtool_set_class_rule(struct efx_nic *efx,
struct ethtool_rx_flow_spec *rule,
u32 rss_context)
{
struct ethtool_tcpip4_spec *ip_entry = &rule->h_u.tcp_ip4_spec;
struct ethtool_tcpip4_spec *ip_mask = &rule->m_u.tcp_ip4_spec;
struct ethtool_usrip4_spec *uip_entry = &rule->h_u.usr_ip4_spec;
struct ethtool_usrip4_spec *uip_mask = &rule->m_u.usr_ip4_spec;
struct ethtool_tcpip6_spec *ip6_entry = &rule->h_u.tcp_ip6_spec;
struct ethtool_tcpip6_spec *ip6_mask = &rule->m_u.tcp_ip6_spec;
struct ethtool_usrip6_spec *uip6_entry = &rule->h_u.usr_ip6_spec;
struct ethtool_usrip6_spec *uip6_mask = &rule->m_u.usr_ip6_spec;
u32 flow_type = rule->flow_type & ~(FLOW_EXT | FLOW_RSS);
struct ethhdr *mac_entry = &rule->h_u.ether_spec;
struct ethhdr *mac_mask = &rule->m_u.ether_spec;
enum efx_filter_flags flags = 0;
struct efx_filter_spec spec;
int rc;
/* Check that user wants us to choose the location */
if (rule->location != RX_CLS_LOC_ANY)
return -EINVAL;
/* Range-check ring_cookie */
if (rule->ring_cookie >= efx->n_rx_channels &&
rule->ring_cookie != RX_CLS_FLOW_DISC)
return -EINVAL;
/* Check for unsupported extensions */
if ((rule->flow_type & FLOW_EXT) &&
(rule->m_ext.vlan_etype || rule->m_ext.data[0] ||
rule->m_ext.data[1]))
return -EINVAL;
if (efx->rx_scatter)
flags |= EFX_FILTER_FLAG_RX_SCATTER;
if (rule->flow_type & FLOW_RSS)
flags |= EFX_FILTER_FLAG_RX_RSS;
efx_filter_init_rx(&spec, EFX_FILTER_PRI_MANUAL, flags,
(rule->ring_cookie == RX_CLS_FLOW_DISC) ?
EFX_FILTER_RX_DMAQ_ID_DROP : rule->ring_cookie);
if (rule->flow_type & FLOW_RSS)
spec.rss_context = rss_context;
switch (flow_type) {
case TCP_V4_FLOW:
case UDP_V4_FLOW:
spec.match_flags = (EFX_FILTER_MATCH_ETHER_TYPE |
EFX_FILTER_MATCH_IP_PROTO);
spec.ether_type = htons(ETH_P_IP);
spec.ip_proto = flow_type == TCP_V4_FLOW ? IPPROTO_TCP
: IPPROTO_UDP;
if (ip_mask->ip4dst) {
if (ip_mask->ip4dst != IP4_ADDR_FULL_MASK)
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_LOC_HOST;
spec.loc_host[0] = ip_entry->ip4dst;
}
if (ip_mask->ip4src) {
if (ip_mask->ip4src != IP4_ADDR_FULL_MASK)
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_REM_HOST;
spec.rem_host[0] = ip_entry->ip4src;
}
if (ip_mask->pdst) {
if (ip_mask->pdst != PORT_FULL_MASK)
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_LOC_PORT;
spec.loc_port = ip_entry->pdst;
}
if (ip_mask->psrc) {
if (ip_mask->psrc != PORT_FULL_MASK)
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_REM_PORT;
spec.rem_port = ip_entry->psrc;
}
if (ip_mask->tos)
return -EINVAL;
break;
case TCP_V6_FLOW:
case UDP_V6_FLOW:
spec.match_flags = (EFX_FILTER_MATCH_ETHER_TYPE |
EFX_FILTER_MATCH_IP_PROTO);
spec.ether_type = htons(ETH_P_IPV6);
spec.ip_proto = flow_type == TCP_V6_FLOW ? IPPROTO_TCP
: IPPROTO_UDP;
if (!ip6_mask_is_empty(ip6_mask->ip6dst)) {
if (!ip6_mask_is_full(ip6_mask->ip6dst))
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_LOC_HOST;
memcpy(spec.loc_host, ip6_entry->ip6dst, sizeof(spec.loc_host));
}
if (!ip6_mask_is_empty(ip6_mask->ip6src)) {
if (!ip6_mask_is_full(ip6_mask->ip6src))
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_REM_HOST;
memcpy(spec.rem_host, ip6_entry->ip6src, sizeof(spec.rem_host));
}
if (ip6_mask->pdst) {
if (ip6_mask->pdst != PORT_FULL_MASK)
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_LOC_PORT;
spec.loc_port = ip6_entry->pdst;
}
if (ip6_mask->psrc) {
if (ip6_mask->psrc != PORT_FULL_MASK)
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_REM_PORT;
spec.rem_port = ip6_entry->psrc;
}
if (ip6_mask->tclass)
return -EINVAL;
break;
case IPV4_USER_FLOW:
if (uip_mask->l4_4_bytes || uip_mask->tos || uip_mask->ip_ver ||
uip_entry->ip_ver != ETH_RX_NFC_IP4)
return -EINVAL;
spec.match_flags = EFX_FILTER_MATCH_ETHER_TYPE;
spec.ether_type = htons(ETH_P_IP);
if (uip_mask->ip4dst) {
if (uip_mask->ip4dst != IP4_ADDR_FULL_MASK)
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_LOC_HOST;
spec.loc_host[0] = uip_entry->ip4dst;
}
if (uip_mask->ip4src) {
if (uip_mask->ip4src != IP4_ADDR_FULL_MASK)
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_REM_HOST;
spec.rem_host[0] = uip_entry->ip4src;
}
if (uip_mask->proto) {
if (uip_mask->proto != IP_PROTO_FULL_MASK)
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_IP_PROTO;
spec.ip_proto = uip_entry->proto;
}
break;
case IPV6_USER_FLOW:
if (uip6_mask->l4_4_bytes || uip6_mask->tclass)
return -EINVAL;
spec.match_flags = EFX_FILTER_MATCH_ETHER_TYPE;
spec.ether_type = htons(ETH_P_IPV6);
if (!ip6_mask_is_empty(uip6_mask->ip6dst)) {
if (!ip6_mask_is_full(uip6_mask->ip6dst))
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_LOC_HOST;
memcpy(spec.loc_host, uip6_entry->ip6dst, sizeof(spec.loc_host));
}
if (!ip6_mask_is_empty(uip6_mask->ip6src)) {
if (!ip6_mask_is_full(uip6_mask->ip6src))
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_REM_HOST;
memcpy(spec.rem_host, uip6_entry->ip6src, sizeof(spec.rem_host));
}
if (uip6_mask->l4_proto) {
if (uip6_mask->l4_proto != IP_PROTO_FULL_MASK)
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_IP_PROTO;
spec.ip_proto = uip6_entry->l4_proto;
}
break;
case ETHER_FLOW:
if (!is_zero_ether_addr(mac_mask->h_dest)) {
if (ether_addr_equal(mac_mask->h_dest,
mac_addr_ig_mask))
spec.match_flags |= EFX_FILTER_MATCH_LOC_MAC_IG;
else if (is_broadcast_ether_addr(mac_mask->h_dest))
spec.match_flags |= EFX_FILTER_MATCH_LOC_MAC;
else
return -EINVAL;
ether_addr_copy(spec.loc_mac, mac_entry->h_dest);
}
if (!is_zero_ether_addr(mac_mask->h_source)) {
if (!is_broadcast_ether_addr(mac_mask->h_source))
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_REM_MAC;
ether_addr_copy(spec.rem_mac, mac_entry->h_source);
}
if (mac_mask->h_proto) {
if (mac_mask->h_proto != ETHER_TYPE_FULL_MASK)
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_ETHER_TYPE;
spec.ether_type = mac_entry->h_proto;
}
break;
default:
return -EINVAL;
}
if ((rule->flow_type & FLOW_EXT) && rule->m_ext.vlan_tci) {
if (rule->m_ext.vlan_tci != htons(0xfff))
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_OUTER_VID;
spec.outer_vid = rule->h_ext.vlan_tci;
}
rc = efx_filter_insert_filter(efx, &spec, true);
if (rc < 0)
return rc;
rule->location = rc;
return 0;
}
int efx_ethtool_set_rxnfc(struct net_device *net_dev,
struct ethtool_rxnfc *info)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
if (efx_filter_get_rx_id_limit(efx) == 0)
return -EOPNOTSUPP;
switch (info->cmd) {
case ETHTOOL_SRXCLSRLINS:
return efx_ethtool_set_class_rule(efx, &info->fs,
info->rss_context);
case ETHTOOL_SRXCLSRLDEL:
return efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_MANUAL,
info->fs.location);
default:
return -EOPNOTSUPP;
}
}
u32 efx_ethtool_get_rxfh_indir_size(struct net_device *net_dev)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
if (efx->n_rx_channels == 1)
return 0;
return ARRAY_SIZE(efx->rss_context.rx_indir_table);
}
u32 efx_ethtool_get_rxfh_key_size(struct net_device *net_dev)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
return efx->type->rx_hash_key_size;
}
int efx_ethtool_get_rxfh(struct net_device *net_dev, u32 *indir, u8 *key,
u8 *hfunc)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
int rc;
rc = efx->type->rx_pull_rss_config(efx);
if (rc)
return rc;
if (hfunc)
*hfunc = ETH_RSS_HASH_TOP;
if (indir)
memcpy(indir, efx->rss_context.rx_indir_table,
sizeof(efx->rss_context.rx_indir_table));
if (key)
memcpy(key, efx->rss_context.rx_hash_key,
efx->type->rx_hash_key_size);
return 0;
}
int efx_ethtool_set_rxfh(struct net_device *net_dev, const u32 *indir,
const u8 *key, const u8 hfunc)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
/* Hash function is Toeplitz, cannot be changed */
if (hfunc != ETH_RSS_HASH_NO_CHANGE && hfunc != ETH_RSS_HASH_TOP)
return -EOPNOTSUPP;
if (!indir && !key)
return 0;
if (!key)
key = efx->rss_context.rx_hash_key;
if (!indir)
indir = efx->rss_context.rx_indir_table;
return efx->type->rx_push_rss_config(efx, true, indir, key);
}
int efx_ethtool_get_rxfh_context(struct net_device *net_dev, u32 *indir,
u8 *key, u8 *hfunc, u32 rss_context)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
struct efx_rss_context *ctx;
int rc = 0;
if (!efx->type->rx_pull_rss_context_config)
return -EOPNOTSUPP;
mutex_lock(&efx->rss_lock);
ctx = efx_find_rss_context_entry(efx, rss_context);
if (!ctx) {
rc = -ENOENT;
goto out_unlock;
}
rc = efx->type->rx_pull_rss_context_config(efx, ctx);
if (rc)
goto out_unlock;
if (hfunc)
*hfunc = ETH_RSS_HASH_TOP;
if (indir)
memcpy(indir, ctx->rx_indir_table, sizeof(ctx->rx_indir_table));
if (key)
memcpy(key, ctx->rx_hash_key, efx->type->rx_hash_key_size);
out_unlock:
mutex_unlock(&efx->rss_lock);
return rc;
}
int efx_ethtool_set_rxfh_context(struct net_device *net_dev,
const u32 *indir, const u8 *key,
const u8 hfunc, u32 *rss_context,
bool delete)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
struct efx_rss_context *ctx;
bool allocated = false;
int rc;
if (!efx->type->rx_push_rss_context_config)
return -EOPNOTSUPP;
/* Hash function is Toeplitz, cannot be changed */
if (hfunc != ETH_RSS_HASH_NO_CHANGE && hfunc != ETH_RSS_HASH_TOP)
return -EOPNOTSUPP;
mutex_lock(&efx->rss_lock);
if (*rss_context == ETH_RXFH_CONTEXT_ALLOC) {
if (delete) {
/* alloc + delete == Nothing to do */
rc = -EINVAL;
goto out_unlock;
}
ctx = efx_alloc_rss_context_entry(efx);
if (!ctx) {
rc = -ENOMEM;
goto out_unlock;
}
ctx->context_id = EFX_MCDI_RSS_CONTEXT_INVALID;
/* Initialise indir table and key to defaults */
efx_set_default_rx_indir_table(efx, ctx);
netdev_rss_key_fill(ctx->rx_hash_key, sizeof(ctx->rx_hash_key));
allocated = true;
} else {
ctx = efx_find_rss_context_entry(efx, *rss_context);
if (!ctx) {
rc = -ENOENT;
goto out_unlock;
}
}
if (delete) {
/* delete this context */
rc = efx->type->rx_push_rss_context_config(efx, ctx, NULL, NULL);
if (!rc)
efx_free_rss_context_entry(ctx);
goto out_unlock;
}
if (!key)
key = ctx->rx_hash_key;
if (!indir)
indir = ctx->rx_indir_table;
rc = efx->type->rx_push_rss_context_config(efx, ctx, indir, key);
if (rc && allocated)
efx_free_rss_context_entry(ctx);
else
*rss_context = ctx->user_id;
out_unlock:
mutex_unlock(&efx->rss_lock);
return rc;
}
int efx_ethtool_reset(struct net_device *net_dev, u32 *flags)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
int rc;
rc = efx->type->map_reset_flags(flags);
if (rc < 0)
return rc;
return efx_reset(efx, rc);
}
int efx_ethtool_get_module_eeprom(struct net_device *net_dev,
struct ethtool_eeprom *ee,
u8 *data)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
int ret;
mutex_lock(&efx->mac_lock);
ret = efx_mcdi_phy_get_module_eeprom(efx, ee, data);
mutex_unlock(&efx->mac_lock);
return ret;
}
int efx_ethtool_get_module_info(struct net_device *net_dev,
struct ethtool_modinfo *modinfo)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
int ret;
mutex_lock(&efx->mac_lock);
ret = efx_mcdi_phy_get_module_info(efx, modinfo);
mutex_unlock(&efx->mac_lock);
return ret;
}
|
linux-master
|
drivers/net/ethernet/sfc/ethtool_common.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2018 Solarflare Communications Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include "mcdi_port_common.h"
#include "efx_common.h"
#include "nic.h"
int efx_mcdi_get_phy_cfg(struct efx_nic *efx, struct efx_mcdi_phy_data *cfg)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_PHY_CFG_OUT_LEN);
size_t outlen;
int rc;
BUILD_BUG_ON(MC_CMD_GET_PHY_CFG_IN_LEN != 0);
BUILD_BUG_ON(MC_CMD_GET_PHY_CFG_OUT_NAME_LEN != sizeof(cfg->name));
rc = efx_mcdi_rpc(efx, MC_CMD_GET_PHY_CFG, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_GET_PHY_CFG_OUT_LEN) {
rc = -EIO;
goto fail;
}
cfg->flags = MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_FLAGS);
cfg->type = MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_TYPE);
cfg->supported_cap =
MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_SUPPORTED_CAP);
cfg->channel = MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_CHANNEL);
cfg->port = MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_PRT);
cfg->stats_mask = MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_STATS_MASK);
memcpy(cfg->name, MCDI_PTR(outbuf, GET_PHY_CFG_OUT_NAME),
sizeof(cfg->name));
cfg->media = MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_MEDIA_TYPE);
cfg->mmd_mask = MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_MMD_MASK);
memcpy(cfg->revision, MCDI_PTR(outbuf, GET_PHY_CFG_OUT_REVISION),
sizeof(cfg->revision));
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
void efx_link_set_advertising(struct efx_nic *efx,
const unsigned long *advertising)
{
memcpy(efx->link_advertising, advertising,
sizeof(__ETHTOOL_DECLARE_LINK_MODE_MASK()));
efx->link_advertising[0] |= ADVERTISED_Autoneg;
if (advertising[0] & ADVERTISED_Pause)
efx->wanted_fc |= (EFX_FC_TX | EFX_FC_RX);
else
efx->wanted_fc &= ~(EFX_FC_TX | EFX_FC_RX);
if (advertising[0] & ADVERTISED_Asym_Pause)
efx->wanted_fc ^= EFX_FC_TX;
}
int efx_mcdi_set_link(struct efx_nic *efx, u32 capabilities,
u32 flags, u32 loopback_mode, u32 loopback_speed)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_SET_LINK_IN_LEN);
BUILD_BUG_ON(MC_CMD_SET_LINK_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, SET_LINK_IN_CAP, capabilities);
MCDI_SET_DWORD(inbuf, SET_LINK_IN_FLAGS, flags);
MCDI_SET_DWORD(inbuf, SET_LINK_IN_LOOPBACK_MODE, loopback_mode);
MCDI_SET_DWORD(inbuf, SET_LINK_IN_LOOPBACK_SPEED, loopback_speed);
return efx_mcdi_rpc(efx, MC_CMD_SET_LINK, inbuf, sizeof(inbuf),
NULL, 0, NULL);
}
int efx_mcdi_loopback_modes(struct efx_nic *efx, u64 *loopback_modes)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_LOOPBACK_MODES_OUT_LEN);
size_t outlen;
int rc;
rc = efx_mcdi_rpc(efx, MC_CMD_GET_LOOPBACK_MODES, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < (MC_CMD_GET_LOOPBACK_MODES_OUT_SUGGESTED_OFST +
MC_CMD_GET_LOOPBACK_MODES_OUT_SUGGESTED_LEN)) {
rc = -EIO;
goto fail;
}
*loopback_modes = MCDI_QWORD(outbuf, GET_LOOPBACK_MODES_OUT_SUGGESTED);
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
void mcdi_to_ethtool_linkset(u32 media, u32 cap, unsigned long *linkset)
{
#define SET_BIT(name) __set_bit(ETHTOOL_LINK_MODE_ ## name ## _BIT, \
linkset)
bitmap_zero(linkset, __ETHTOOL_LINK_MODE_MASK_NBITS);
switch (media) {
case MC_CMD_MEDIA_KX4:
SET_BIT(Backplane);
if (cap & (1 << MC_CMD_PHY_CAP_1000FDX_LBN))
SET_BIT(1000baseKX_Full);
if (cap & (1 << MC_CMD_PHY_CAP_10000FDX_LBN))
SET_BIT(10000baseKX4_Full);
if (cap & (1 << MC_CMD_PHY_CAP_40000FDX_LBN))
SET_BIT(40000baseKR4_Full);
break;
case MC_CMD_MEDIA_XFP:
case MC_CMD_MEDIA_SFP_PLUS:
case MC_CMD_MEDIA_QSFP_PLUS:
SET_BIT(FIBRE);
if (cap & (1 << MC_CMD_PHY_CAP_1000FDX_LBN)) {
SET_BIT(1000baseT_Full);
SET_BIT(1000baseX_Full);
}
if (cap & (1 << MC_CMD_PHY_CAP_10000FDX_LBN)) {
SET_BIT(10000baseCR_Full);
SET_BIT(10000baseLR_Full);
SET_BIT(10000baseSR_Full);
}
if (cap & (1 << MC_CMD_PHY_CAP_40000FDX_LBN)) {
SET_BIT(40000baseCR4_Full);
SET_BIT(40000baseSR4_Full);
}
if (cap & (1 << MC_CMD_PHY_CAP_100000FDX_LBN)) {
SET_BIT(100000baseCR4_Full);
SET_BIT(100000baseSR4_Full);
}
if (cap & (1 << MC_CMD_PHY_CAP_25000FDX_LBN)) {
SET_BIT(25000baseCR_Full);
SET_BIT(25000baseSR_Full);
}
if (cap & (1 << MC_CMD_PHY_CAP_50000FDX_LBN))
SET_BIT(50000baseCR2_Full);
break;
case MC_CMD_MEDIA_BASE_T:
SET_BIT(TP);
if (cap & (1 << MC_CMD_PHY_CAP_10HDX_LBN))
SET_BIT(10baseT_Half);
if (cap & (1 << MC_CMD_PHY_CAP_10FDX_LBN))
SET_BIT(10baseT_Full);
if (cap & (1 << MC_CMD_PHY_CAP_100HDX_LBN))
SET_BIT(100baseT_Half);
if (cap & (1 << MC_CMD_PHY_CAP_100FDX_LBN))
SET_BIT(100baseT_Full);
if (cap & (1 << MC_CMD_PHY_CAP_1000HDX_LBN))
SET_BIT(1000baseT_Half);
if (cap & (1 << MC_CMD_PHY_CAP_1000FDX_LBN))
SET_BIT(1000baseT_Full);
if (cap & (1 << MC_CMD_PHY_CAP_10000FDX_LBN))
SET_BIT(10000baseT_Full);
break;
}
if (cap & (1 << MC_CMD_PHY_CAP_PAUSE_LBN))
SET_BIT(Pause);
if (cap & (1 << MC_CMD_PHY_CAP_ASYM_LBN))
SET_BIT(Asym_Pause);
if (cap & (1 << MC_CMD_PHY_CAP_AN_LBN))
SET_BIT(Autoneg);
#undef SET_BIT
}
u32 ethtool_linkset_to_mcdi_cap(const unsigned long *linkset)
{
u32 result = 0;
#define TEST_BIT(name) test_bit(ETHTOOL_LINK_MODE_ ## name ## _BIT, \
linkset)
if (TEST_BIT(10baseT_Half))
result |= (1 << MC_CMD_PHY_CAP_10HDX_LBN);
if (TEST_BIT(10baseT_Full))
result |= (1 << MC_CMD_PHY_CAP_10FDX_LBN);
if (TEST_BIT(100baseT_Half))
result |= (1 << MC_CMD_PHY_CAP_100HDX_LBN);
if (TEST_BIT(100baseT_Full))
result |= (1 << MC_CMD_PHY_CAP_100FDX_LBN);
if (TEST_BIT(1000baseT_Half))
result |= (1 << MC_CMD_PHY_CAP_1000HDX_LBN);
if (TEST_BIT(1000baseT_Full) || TEST_BIT(1000baseKX_Full) ||
TEST_BIT(1000baseX_Full))
result |= (1 << MC_CMD_PHY_CAP_1000FDX_LBN);
if (TEST_BIT(10000baseT_Full) || TEST_BIT(10000baseKX4_Full) ||
TEST_BIT(10000baseCR_Full) || TEST_BIT(10000baseLR_Full) ||
TEST_BIT(10000baseSR_Full))
result |= (1 << MC_CMD_PHY_CAP_10000FDX_LBN);
if (TEST_BIT(40000baseCR4_Full) || TEST_BIT(40000baseKR4_Full) ||
TEST_BIT(40000baseSR4_Full))
result |= (1 << MC_CMD_PHY_CAP_40000FDX_LBN);
if (TEST_BIT(100000baseCR4_Full) || TEST_BIT(100000baseSR4_Full))
result |= (1 << MC_CMD_PHY_CAP_100000FDX_LBN);
if (TEST_BIT(25000baseCR_Full) || TEST_BIT(25000baseSR_Full))
result |= (1 << MC_CMD_PHY_CAP_25000FDX_LBN);
if (TEST_BIT(50000baseCR2_Full))
result |= (1 << MC_CMD_PHY_CAP_50000FDX_LBN);
if (TEST_BIT(Pause))
result |= (1 << MC_CMD_PHY_CAP_PAUSE_LBN);
if (TEST_BIT(Asym_Pause))
result |= (1 << MC_CMD_PHY_CAP_ASYM_LBN);
if (TEST_BIT(Autoneg))
result |= (1 << MC_CMD_PHY_CAP_AN_LBN);
#undef TEST_BIT
return result;
}
u32 efx_get_mcdi_phy_flags(struct efx_nic *efx)
{
struct efx_mcdi_phy_data *phy_cfg = efx->phy_data;
enum efx_phy_mode mode, supported;
u32 flags;
/* TODO: Advertise the capabilities supported by this PHY */
supported = 0;
if (phy_cfg->flags & (1 << MC_CMD_GET_PHY_CFG_OUT_TXDIS_LBN))
supported |= PHY_MODE_TX_DISABLED;
if (phy_cfg->flags & (1 << MC_CMD_GET_PHY_CFG_OUT_LOWPOWER_LBN))
supported |= PHY_MODE_LOW_POWER;
if (phy_cfg->flags & (1 << MC_CMD_GET_PHY_CFG_OUT_POWEROFF_LBN))
supported |= PHY_MODE_OFF;
mode = efx->phy_mode & supported;
flags = 0;
if (mode & PHY_MODE_TX_DISABLED)
flags |= (1 << MC_CMD_SET_LINK_IN_TXDIS_LBN);
if (mode & PHY_MODE_LOW_POWER)
flags |= (1 << MC_CMD_SET_LINK_IN_LOWPOWER_LBN);
if (mode & PHY_MODE_OFF)
flags |= (1 << MC_CMD_SET_LINK_IN_POWEROFF_LBN);
return flags;
}
u8 mcdi_to_ethtool_media(u32 media)
{
switch (media) {
case MC_CMD_MEDIA_XAUI:
case MC_CMD_MEDIA_CX4:
case MC_CMD_MEDIA_KX4:
return PORT_OTHER;
case MC_CMD_MEDIA_XFP:
case MC_CMD_MEDIA_SFP_PLUS:
case MC_CMD_MEDIA_QSFP_PLUS:
return PORT_FIBRE;
case MC_CMD_MEDIA_BASE_T:
return PORT_TP;
default:
return PORT_OTHER;
}
}
void efx_mcdi_phy_decode_link(struct efx_nic *efx,
struct efx_link_state *link_state,
u32 speed, u32 flags, u32 fcntl)
{
switch (fcntl) {
case MC_CMD_FCNTL_AUTO:
WARN_ON(1); /* This is not a link mode */
link_state->fc = EFX_FC_AUTO | EFX_FC_TX | EFX_FC_RX;
break;
case MC_CMD_FCNTL_BIDIR:
link_state->fc = EFX_FC_TX | EFX_FC_RX;
break;
case MC_CMD_FCNTL_RESPOND:
link_state->fc = EFX_FC_RX;
break;
default:
WARN_ON(1);
fallthrough;
case MC_CMD_FCNTL_OFF:
link_state->fc = 0;
break;
}
link_state->up = !!(flags & (1 << MC_CMD_GET_LINK_OUT_LINK_UP_LBN));
link_state->fd = !!(flags & (1 << MC_CMD_GET_LINK_OUT_FULL_DUPLEX_LBN));
link_state->speed = speed;
}
/* The semantics of the ethtool FEC mode bitmask are not well defined,
* particularly the meaning of combinations of bits. Which means we get to
* define our own semantics, as follows:
* OFF overrides any other bits, and means "disable all FEC" (with the
* exception of 25G KR4/CR4, where it is not possible to reject it if AN
* partner requests it).
* AUTO on its own means use cable requirements and link partner autoneg with
* fw-default preferences for the cable type.
* AUTO and either RS or BASER means use the specified FEC type if cable and
* link partner support it, otherwise autoneg/fw-default.
* RS or BASER alone means use the specified FEC type if cable and link partner
* support it and either requests it, otherwise no FEC.
* Both RS and BASER (whether AUTO or not) means use FEC if cable and link
* partner support it, preferring RS to BASER.
*/
u32 ethtool_fec_caps_to_mcdi(u32 supported_cap, u32 ethtool_cap)
{
u32 ret = 0;
if (ethtool_cap & ETHTOOL_FEC_OFF)
return 0;
if (ethtool_cap & ETHTOOL_FEC_AUTO)
ret |= ((1 << MC_CMD_PHY_CAP_BASER_FEC_LBN) |
(1 << MC_CMD_PHY_CAP_25G_BASER_FEC_LBN) |
(1 << MC_CMD_PHY_CAP_RS_FEC_LBN)) & supported_cap;
if (ethtool_cap & ETHTOOL_FEC_RS &&
supported_cap & (1 << MC_CMD_PHY_CAP_RS_FEC_LBN))
ret |= (1 << MC_CMD_PHY_CAP_RS_FEC_LBN) |
(1 << MC_CMD_PHY_CAP_RS_FEC_REQUESTED_LBN);
if (ethtool_cap & ETHTOOL_FEC_BASER) {
if (supported_cap & (1 << MC_CMD_PHY_CAP_BASER_FEC_LBN))
ret |= (1 << MC_CMD_PHY_CAP_BASER_FEC_LBN) |
(1 << MC_CMD_PHY_CAP_BASER_FEC_REQUESTED_LBN);
if (supported_cap & (1 << MC_CMD_PHY_CAP_25G_BASER_FEC_LBN))
ret |= (1 << MC_CMD_PHY_CAP_25G_BASER_FEC_LBN) |
(1 << MC_CMD_PHY_CAP_25G_BASER_FEC_REQUESTED_LBN);
}
return ret;
}
/* Invert ethtool_fec_caps_to_mcdi. There are two combinations that function
* can never produce, (baser xor rs) and neither req; the implementation below
* maps both of those to AUTO. This should never matter, and it's not clear
* what a better mapping would be anyway.
*/
u32 mcdi_fec_caps_to_ethtool(u32 caps, bool is_25g)
{
bool rs = caps & (1 << MC_CMD_PHY_CAP_RS_FEC_LBN),
rs_req = caps & (1 << MC_CMD_PHY_CAP_RS_FEC_REQUESTED_LBN),
baser = is_25g ? caps & (1 << MC_CMD_PHY_CAP_25G_BASER_FEC_LBN)
: caps & (1 << MC_CMD_PHY_CAP_BASER_FEC_LBN),
baser_req = is_25g ? caps & (1 << MC_CMD_PHY_CAP_25G_BASER_FEC_REQUESTED_LBN)
: caps & (1 << MC_CMD_PHY_CAP_BASER_FEC_REQUESTED_LBN);
if (!baser && !rs)
return ETHTOOL_FEC_OFF;
return (rs_req ? ETHTOOL_FEC_RS : 0) |
(baser_req ? ETHTOOL_FEC_BASER : 0) |
(baser == baser_req && rs == rs_req ? 0 : ETHTOOL_FEC_AUTO);
}
/* Verify that the forced flow control settings (!EFX_FC_AUTO) are
* supported by the link partner. Warn the user if this isn't the case
*/
void efx_mcdi_phy_check_fcntl(struct efx_nic *efx, u32 lpa)
{
struct efx_mcdi_phy_data *phy_cfg = efx->phy_data;
u32 rmtadv;
/* The link partner capabilities are only relevant if the
* link supports flow control autonegotiation
*/
if (~phy_cfg->supported_cap & (1 << MC_CMD_PHY_CAP_AN_LBN))
return;
/* If flow control autoneg is supported and enabled, then fine */
if (efx->wanted_fc & EFX_FC_AUTO)
return;
rmtadv = 0;
if (lpa & (1 << MC_CMD_PHY_CAP_PAUSE_LBN))
rmtadv |= ADVERTISED_Pause;
if (lpa & (1 << MC_CMD_PHY_CAP_ASYM_LBN))
rmtadv |= ADVERTISED_Asym_Pause;
if ((efx->wanted_fc & EFX_FC_TX) && rmtadv == ADVERTISED_Asym_Pause)
netif_err(efx, link, efx->net_dev,
"warning: link partner doesn't support pause frames");
}
bool efx_mcdi_phy_poll(struct efx_nic *efx)
{
struct efx_link_state old_state = efx->link_state;
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_LINK_OUT_LEN);
int rc;
WARN_ON(!mutex_is_locked(&efx->mac_lock));
BUILD_BUG_ON(MC_CMD_GET_LINK_IN_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_GET_LINK, NULL, 0,
outbuf, sizeof(outbuf), NULL);
if (rc)
efx->link_state.up = false;
else
efx_mcdi_phy_decode_link(
efx, &efx->link_state,
MCDI_DWORD(outbuf, GET_LINK_OUT_LINK_SPEED),
MCDI_DWORD(outbuf, GET_LINK_OUT_FLAGS),
MCDI_DWORD(outbuf, GET_LINK_OUT_FCNTL));
return !efx_link_state_equal(&efx->link_state, &old_state);
}
int efx_mcdi_phy_probe(struct efx_nic *efx)
{
struct efx_mcdi_phy_data *phy_data;
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_LINK_OUT_LEN);
u32 caps;
int rc;
/* Initialise and populate phy_data */
phy_data = kzalloc(sizeof(*phy_data), GFP_KERNEL);
if (phy_data == NULL)
return -ENOMEM;
rc = efx_mcdi_get_phy_cfg(efx, phy_data);
if (rc != 0)
goto fail;
/* Read initial link advertisement */
BUILD_BUG_ON(MC_CMD_GET_LINK_IN_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_GET_LINK, NULL, 0,
outbuf, sizeof(outbuf), NULL);
if (rc)
goto fail;
/* Fill out nic state */
efx->phy_data = phy_data;
efx->phy_type = phy_data->type;
efx->mdio_bus = phy_data->channel;
efx->mdio.prtad = phy_data->port;
efx->mdio.mmds = phy_data->mmd_mask & ~(1 << MC_CMD_MMD_CLAUSE22);
efx->mdio.mode_support = 0;
if (phy_data->mmd_mask & (1 << MC_CMD_MMD_CLAUSE22))
efx->mdio.mode_support |= MDIO_SUPPORTS_C22;
if (phy_data->mmd_mask & ~(1 << MC_CMD_MMD_CLAUSE22))
efx->mdio.mode_support |= MDIO_SUPPORTS_C45 | MDIO_EMULATE_C22;
caps = MCDI_DWORD(outbuf, GET_LINK_OUT_CAP);
if (caps & (1 << MC_CMD_PHY_CAP_AN_LBN))
mcdi_to_ethtool_linkset(phy_data->media, caps,
efx->link_advertising);
else
phy_data->forced_cap = caps;
/* Assert that we can map efx -> mcdi loopback modes */
BUILD_BUG_ON(LOOPBACK_NONE != MC_CMD_LOOPBACK_NONE);
BUILD_BUG_ON(LOOPBACK_DATA != MC_CMD_LOOPBACK_DATA);
BUILD_BUG_ON(LOOPBACK_GMAC != MC_CMD_LOOPBACK_GMAC);
BUILD_BUG_ON(LOOPBACK_XGMII != MC_CMD_LOOPBACK_XGMII);
BUILD_BUG_ON(LOOPBACK_XGXS != MC_CMD_LOOPBACK_XGXS);
BUILD_BUG_ON(LOOPBACK_XAUI != MC_CMD_LOOPBACK_XAUI);
BUILD_BUG_ON(LOOPBACK_GMII != MC_CMD_LOOPBACK_GMII);
BUILD_BUG_ON(LOOPBACK_SGMII != MC_CMD_LOOPBACK_SGMII);
BUILD_BUG_ON(LOOPBACK_XGBR != MC_CMD_LOOPBACK_XGBR);
BUILD_BUG_ON(LOOPBACK_XFI != MC_CMD_LOOPBACK_XFI);
BUILD_BUG_ON(LOOPBACK_XAUI_FAR != MC_CMD_LOOPBACK_XAUI_FAR);
BUILD_BUG_ON(LOOPBACK_GMII_FAR != MC_CMD_LOOPBACK_GMII_FAR);
BUILD_BUG_ON(LOOPBACK_SGMII_FAR != MC_CMD_LOOPBACK_SGMII_FAR);
BUILD_BUG_ON(LOOPBACK_XFI_FAR != MC_CMD_LOOPBACK_XFI_FAR);
BUILD_BUG_ON(LOOPBACK_GPHY != MC_CMD_LOOPBACK_GPHY);
BUILD_BUG_ON(LOOPBACK_PHYXS != MC_CMD_LOOPBACK_PHYXS);
BUILD_BUG_ON(LOOPBACK_PCS != MC_CMD_LOOPBACK_PCS);
BUILD_BUG_ON(LOOPBACK_PMAPMD != MC_CMD_LOOPBACK_PMAPMD);
BUILD_BUG_ON(LOOPBACK_XPORT != MC_CMD_LOOPBACK_XPORT);
BUILD_BUG_ON(LOOPBACK_XGMII_WS != MC_CMD_LOOPBACK_XGMII_WS);
BUILD_BUG_ON(LOOPBACK_XAUI_WS != MC_CMD_LOOPBACK_XAUI_WS);
BUILD_BUG_ON(LOOPBACK_XAUI_WS_FAR != MC_CMD_LOOPBACK_XAUI_WS_FAR);
BUILD_BUG_ON(LOOPBACK_XAUI_WS_NEAR != MC_CMD_LOOPBACK_XAUI_WS_NEAR);
BUILD_BUG_ON(LOOPBACK_GMII_WS != MC_CMD_LOOPBACK_GMII_WS);
BUILD_BUG_ON(LOOPBACK_XFI_WS != MC_CMD_LOOPBACK_XFI_WS);
BUILD_BUG_ON(LOOPBACK_XFI_WS_FAR != MC_CMD_LOOPBACK_XFI_WS_FAR);
BUILD_BUG_ON(LOOPBACK_PHYXS_WS != MC_CMD_LOOPBACK_PHYXS_WS);
rc = efx_mcdi_loopback_modes(efx, &efx->loopback_modes);
if (rc != 0)
goto fail;
/* The MC indicates that LOOPBACK_NONE is a valid loopback mode,
* but by convention we don't
*/
efx->loopback_modes &= ~(1 << LOOPBACK_NONE);
/* Set the initial link mode */
efx_mcdi_phy_decode_link(efx, &efx->link_state,
MCDI_DWORD(outbuf, GET_LINK_OUT_LINK_SPEED),
MCDI_DWORD(outbuf, GET_LINK_OUT_FLAGS),
MCDI_DWORD(outbuf, GET_LINK_OUT_FCNTL));
/* Record the initial FEC configuration (or nearest approximation
* representable in the ethtool configuration space)
*/
efx->fec_config = mcdi_fec_caps_to_ethtool(caps,
efx->link_state.speed == 25000 ||
efx->link_state.speed == 50000);
/* Default to Autonegotiated flow control if the PHY supports it */
efx->wanted_fc = EFX_FC_RX | EFX_FC_TX;
if (phy_data->supported_cap & (1 << MC_CMD_PHY_CAP_AN_LBN))
efx->wanted_fc |= EFX_FC_AUTO;
efx_link_set_wanted_fc(efx, efx->wanted_fc);
return 0;
fail:
kfree(phy_data);
return rc;
}
void efx_mcdi_phy_remove(struct efx_nic *efx)
{
struct efx_mcdi_phy_data *phy_data = efx->phy_data;
efx->phy_data = NULL;
kfree(phy_data);
}
void efx_mcdi_phy_get_link_ksettings(struct efx_nic *efx, struct ethtool_link_ksettings *cmd)
{
struct efx_mcdi_phy_data *phy_cfg = efx->phy_data;
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_LINK_OUT_LEN);
int rc;
cmd->base.speed = efx->link_state.speed;
cmd->base.duplex = efx->link_state.fd;
cmd->base.port = mcdi_to_ethtool_media(phy_cfg->media);
cmd->base.phy_address = phy_cfg->port;
cmd->base.autoneg = !!(efx->link_advertising[0] & ADVERTISED_Autoneg);
cmd->base.mdio_support = (efx->mdio.mode_support &
(MDIO_SUPPORTS_C45 | MDIO_SUPPORTS_C22));
mcdi_to_ethtool_linkset(phy_cfg->media, phy_cfg->supported_cap,
cmd->link_modes.supported);
memcpy(cmd->link_modes.advertising, efx->link_advertising,
sizeof(__ETHTOOL_DECLARE_LINK_MODE_MASK()));
BUILD_BUG_ON(MC_CMD_GET_LINK_IN_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_GET_LINK, NULL, 0,
outbuf, sizeof(outbuf), NULL);
if (rc)
return;
mcdi_to_ethtool_linkset(phy_cfg->media,
MCDI_DWORD(outbuf, GET_LINK_OUT_LP_CAP),
cmd->link_modes.lp_advertising);
}
int efx_mcdi_phy_set_link_ksettings(struct efx_nic *efx, const struct ethtool_link_ksettings *cmd)
{
struct efx_mcdi_phy_data *phy_cfg = efx->phy_data;
u32 caps;
int rc;
if (cmd->base.autoneg) {
caps = (ethtool_linkset_to_mcdi_cap(cmd->link_modes.advertising) |
1 << MC_CMD_PHY_CAP_AN_LBN);
} else if (cmd->base.duplex) {
switch (cmd->base.speed) {
case 10: caps = 1 << MC_CMD_PHY_CAP_10FDX_LBN; break;
case 100: caps = 1 << MC_CMD_PHY_CAP_100FDX_LBN; break;
case 1000: caps = 1 << MC_CMD_PHY_CAP_1000FDX_LBN; break;
case 10000: caps = 1 << MC_CMD_PHY_CAP_10000FDX_LBN; break;
case 40000: caps = 1 << MC_CMD_PHY_CAP_40000FDX_LBN; break;
case 100000: caps = 1 << MC_CMD_PHY_CAP_100000FDX_LBN; break;
case 25000: caps = 1 << MC_CMD_PHY_CAP_25000FDX_LBN; break;
case 50000: caps = 1 << MC_CMD_PHY_CAP_50000FDX_LBN; break;
default: return -EINVAL;
}
} else {
switch (cmd->base.speed) {
case 10: caps = 1 << MC_CMD_PHY_CAP_10HDX_LBN; break;
case 100: caps = 1 << MC_CMD_PHY_CAP_100HDX_LBN; break;
case 1000: caps = 1 << MC_CMD_PHY_CAP_1000HDX_LBN; break;
default: return -EINVAL;
}
}
caps |= ethtool_fec_caps_to_mcdi(phy_cfg->supported_cap, efx->fec_config);
rc = efx_mcdi_set_link(efx, caps, efx_get_mcdi_phy_flags(efx),
efx->loopback_mode, 0);
if (rc)
return rc;
if (cmd->base.autoneg) {
efx_link_set_advertising(efx, cmd->link_modes.advertising);
phy_cfg->forced_cap = 0;
} else {
efx_link_clear_advertising(efx);
phy_cfg->forced_cap = caps;
}
return 0;
}
int efx_mcdi_phy_get_fecparam(struct efx_nic *efx, struct ethtool_fecparam *fec)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_LINK_OUT_V2_LEN);
u32 caps, active, speed; /* MCDI format */
bool is_25g = false;
size_t outlen;
int rc;
BUILD_BUG_ON(MC_CMD_GET_LINK_IN_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_GET_LINK, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < MC_CMD_GET_LINK_OUT_V2_LEN)
return -EOPNOTSUPP;
/* behaviour for 25G/50G links depends on 25G BASER bit */
speed = MCDI_DWORD(outbuf, GET_LINK_OUT_V2_LINK_SPEED);
is_25g = speed == 25000 || speed == 50000;
caps = MCDI_DWORD(outbuf, GET_LINK_OUT_V2_CAP);
fec->fec = mcdi_fec_caps_to_ethtool(caps, is_25g);
/* BASER is never supported on 100G */
if (speed == 100000)
fec->fec &= ~ETHTOOL_FEC_BASER;
active = MCDI_DWORD(outbuf, GET_LINK_OUT_V2_FEC_TYPE);
switch (active) {
case MC_CMD_FEC_NONE:
fec->active_fec = ETHTOOL_FEC_OFF;
break;
case MC_CMD_FEC_BASER:
fec->active_fec = ETHTOOL_FEC_BASER;
break;
case MC_CMD_FEC_RS:
fec->active_fec = ETHTOOL_FEC_RS;
break;
default:
netif_warn(efx, hw, efx->net_dev,
"Firmware reports unrecognised FEC_TYPE %u\n",
active);
/* We don't know what firmware has picked. AUTO is as good a
* "can't happen" value as any other.
*/
fec->active_fec = ETHTOOL_FEC_AUTO;
break;
}
return 0;
}
/* Basic validation to ensure that the caps we are going to attempt to set are
* in fact supported by the adapter. Note that 'no FEC' is always supported.
*/
static int ethtool_fec_supported(u32 supported_cap, u32 ethtool_cap)
{
if (ethtool_cap & ETHTOOL_FEC_OFF)
return 0;
if (ethtool_cap &&
!ethtool_fec_caps_to_mcdi(supported_cap, ethtool_cap))
return -EINVAL;
return 0;
}
int efx_mcdi_phy_set_fecparam(struct efx_nic *efx, const struct ethtool_fecparam *fec)
{
struct efx_mcdi_phy_data *phy_cfg = efx->phy_data;
u32 caps;
int rc;
rc = ethtool_fec_supported(phy_cfg->supported_cap, fec->fec);
if (rc)
return rc;
/* Work out what efx_mcdi_phy_set_link_ksettings() would produce from
* saved advertising bits
*/
if (test_bit(ETHTOOL_LINK_MODE_Autoneg_BIT, efx->link_advertising))
caps = (ethtool_linkset_to_mcdi_cap(efx->link_advertising) |
1 << MC_CMD_PHY_CAP_AN_LBN);
else
caps = phy_cfg->forced_cap;
caps |= ethtool_fec_caps_to_mcdi(phy_cfg->supported_cap, fec->fec);
rc = efx_mcdi_set_link(efx, caps, efx_get_mcdi_phy_flags(efx),
efx->loopback_mode, 0);
if (rc)
return rc;
/* Record the new FEC setting for subsequent set_link calls */
efx->fec_config = fec->fec;
return 0;
}
int efx_mcdi_phy_test_alive(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_PHY_STATE_OUT_LEN);
size_t outlen;
int rc;
BUILD_BUG_ON(MC_CMD_GET_PHY_STATE_IN_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_GET_PHY_STATE, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < MC_CMD_GET_PHY_STATE_OUT_LEN)
return -EIO;
if (MCDI_DWORD(outbuf, GET_PHY_STATE_OUT_STATE) != MC_CMD_PHY_STATE_OK)
return -EINVAL;
return 0;
}
int efx_mcdi_port_reconfigure(struct efx_nic *efx)
{
struct efx_mcdi_phy_data *phy_cfg = efx->phy_data;
u32 caps = (efx->link_advertising[0] ?
ethtool_linkset_to_mcdi_cap(efx->link_advertising) :
phy_cfg->forced_cap);
caps |= ethtool_fec_caps_to_mcdi(phy_cfg->supported_cap, efx->fec_config);
return efx_mcdi_set_link(efx, caps, efx_get_mcdi_phy_flags(efx),
efx->loopback_mode, 0);
}
static const char *const mcdi_sft9001_cable_diag_names[] = {
"cable.pairA.length",
"cable.pairB.length",
"cable.pairC.length",
"cable.pairD.length",
"cable.pairA.status",
"cable.pairB.status",
"cable.pairC.status",
"cable.pairD.status",
};
static int efx_mcdi_bist(struct efx_nic *efx, unsigned int bist_mode,
int *results)
{
unsigned int retry, i, count = 0;
size_t outlen;
u32 status;
MCDI_DECLARE_BUF(inbuf, MC_CMD_START_BIST_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_POLL_BIST_OUT_SFT9001_LEN);
u8 *ptr;
int rc;
BUILD_BUG_ON(MC_CMD_START_BIST_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, START_BIST_IN_TYPE, bist_mode);
rc = efx_mcdi_rpc(efx, MC_CMD_START_BIST,
inbuf, MC_CMD_START_BIST_IN_LEN, NULL, 0, NULL);
if (rc)
goto out;
/* Wait up to 10s for BIST to finish */
for (retry = 0; retry < 100; ++retry) {
BUILD_BUG_ON(MC_CMD_POLL_BIST_IN_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_POLL_BIST, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto out;
status = MCDI_DWORD(outbuf, POLL_BIST_OUT_RESULT);
if (status != MC_CMD_POLL_BIST_RUNNING)
goto finished;
msleep(100);
}
rc = -ETIMEDOUT;
goto out;
finished:
results[count++] = (status == MC_CMD_POLL_BIST_PASSED) ? 1 : -1;
/* SFT9001 specific cable diagnostics output */
if (efx->phy_type == PHY_TYPE_SFT9001B &&
(bist_mode == MC_CMD_PHY_BIST_CABLE_SHORT ||
bist_mode == MC_CMD_PHY_BIST_CABLE_LONG)) {
ptr = MCDI_PTR(outbuf, POLL_BIST_OUT_SFT9001_CABLE_LENGTH_A);
if (status == MC_CMD_POLL_BIST_PASSED &&
outlen >= MC_CMD_POLL_BIST_OUT_SFT9001_LEN) {
for (i = 0; i < 8; i++) {
results[count + i] =
EFX_DWORD_FIELD(((efx_dword_t *)ptr)[i],
EFX_DWORD_0);
}
}
count += 8;
}
rc = count;
out:
return rc;
}
int efx_mcdi_phy_run_tests(struct efx_nic *efx, int *results, unsigned int flags)
{
struct efx_mcdi_phy_data *phy_cfg = efx->phy_data;
u32 mode;
int rc;
if (phy_cfg->flags & (1 << MC_CMD_GET_PHY_CFG_OUT_BIST_LBN)) {
rc = efx_mcdi_bist(efx, MC_CMD_PHY_BIST, results);
if (rc < 0)
return rc;
results += rc;
}
/* If we support both LONG and SHORT, then run each in response to
* break or not. Otherwise, run the one we support
*/
mode = 0;
if (phy_cfg->flags & (1 << MC_CMD_GET_PHY_CFG_OUT_BIST_CABLE_SHORT_LBN)) {
if ((flags & ETH_TEST_FL_OFFLINE) &&
(phy_cfg->flags &
(1 << MC_CMD_GET_PHY_CFG_OUT_BIST_CABLE_LONG_LBN)))
mode = MC_CMD_PHY_BIST_CABLE_LONG;
else
mode = MC_CMD_PHY_BIST_CABLE_SHORT;
} else if (phy_cfg->flags &
(1 << MC_CMD_GET_PHY_CFG_OUT_BIST_CABLE_LONG_LBN))
mode = MC_CMD_PHY_BIST_CABLE_LONG;
if (mode != 0) {
rc = efx_mcdi_bist(efx, mode, results);
if (rc < 0)
return rc;
results += rc;
}
return 0;
}
const char *efx_mcdi_phy_test_name(struct efx_nic *efx, unsigned int index)
{
struct efx_mcdi_phy_data *phy_cfg = efx->phy_data;
if (phy_cfg->flags & (1 << MC_CMD_GET_PHY_CFG_OUT_BIST_LBN)) {
if (index == 0)
return "bist";
--index;
}
if (phy_cfg->flags & ((1 << MC_CMD_GET_PHY_CFG_OUT_BIST_CABLE_SHORT_LBN) |
(1 << MC_CMD_GET_PHY_CFG_OUT_BIST_CABLE_LONG_LBN))) {
if (index == 0)
return "cable";
--index;
if (efx->phy_type == PHY_TYPE_SFT9001B) {
if (index < ARRAY_SIZE(mcdi_sft9001_cable_diag_names))
return mcdi_sft9001_cable_diag_names[index];
index -= ARRAY_SIZE(mcdi_sft9001_cable_diag_names);
}
}
return NULL;
}
#define SFP_PAGE_SIZE 128
#define SFF_DIAG_TYPE_OFFSET 92
#define SFF_DIAG_ADDR_CHANGE BIT(2)
#define SFF_8079_NUM_PAGES 2
#define SFF_8472_NUM_PAGES 4
#define SFF_8436_NUM_PAGES 5
#define SFF_DMT_LEVEL_OFFSET 94
/** efx_mcdi_phy_get_module_eeprom_page() - Get a single page of module eeprom
* @efx: NIC context
* @page: EEPROM page number
* @data: Destination data pointer
* @offset: Offset in page to copy from in to data
* @space: Space available in data
*
* Return:
* >=0 - amount of data copied
* <0 - error
*/
static int efx_mcdi_phy_get_module_eeprom_page(struct efx_nic *efx,
unsigned int page,
u8 *data, ssize_t offset,
ssize_t space)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_PHY_MEDIA_INFO_OUT_LENMAX);
MCDI_DECLARE_BUF(inbuf, MC_CMD_GET_PHY_MEDIA_INFO_IN_LEN);
unsigned int payload_len;
unsigned int to_copy;
size_t outlen;
int rc;
if (offset > SFP_PAGE_SIZE)
return -EINVAL;
to_copy = min(space, SFP_PAGE_SIZE - offset);
MCDI_SET_DWORD(inbuf, GET_PHY_MEDIA_INFO_IN_PAGE, page);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_GET_PHY_MEDIA_INFO,
inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf),
&outlen);
if (rc)
return rc;
if (outlen < (MC_CMD_GET_PHY_MEDIA_INFO_OUT_DATA_OFST +
SFP_PAGE_SIZE))
return -EIO;
payload_len = MCDI_DWORD(outbuf, GET_PHY_MEDIA_INFO_OUT_DATALEN);
if (payload_len != SFP_PAGE_SIZE)
return -EIO;
memcpy(data, MCDI_PTR(outbuf, GET_PHY_MEDIA_INFO_OUT_DATA) + offset,
to_copy);
return to_copy;
}
static int efx_mcdi_phy_get_module_eeprom_byte(struct efx_nic *efx,
unsigned int page,
u8 byte)
{
u8 data;
int rc;
rc = efx_mcdi_phy_get_module_eeprom_page(efx, page, &data, byte, 1);
if (rc == 1)
return data;
return rc;
}
static int efx_mcdi_phy_diag_type(struct efx_nic *efx)
{
/* Page zero of the EEPROM includes the diagnostic type at byte 92. */
return efx_mcdi_phy_get_module_eeprom_byte(efx, 0,
SFF_DIAG_TYPE_OFFSET);
}
static int efx_mcdi_phy_sff_8472_level(struct efx_nic *efx)
{
/* Page zero of the EEPROM includes the DMT level at byte 94. */
return efx_mcdi_phy_get_module_eeprom_byte(efx, 0,
SFF_DMT_LEVEL_OFFSET);
}
static u32 efx_mcdi_phy_module_type(struct efx_nic *efx)
{
struct efx_mcdi_phy_data *phy_data = efx->phy_data;
if (phy_data->media != MC_CMD_MEDIA_QSFP_PLUS)
return phy_data->media;
/* A QSFP+ NIC may actually have an SFP+ module attached.
* The ID is page 0, byte 0.
* QSFP28 is of type SFF_8636, however, this is treated
* the same by ethtool, so we can also treat them the same.
*/
switch (efx_mcdi_phy_get_module_eeprom_byte(efx, 0, 0)) {
case 0x3: /* SFP */
return MC_CMD_MEDIA_SFP_PLUS;
case 0xc: /* QSFP */
case 0xd: /* QSFP+ */
case 0x11: /* QSFP28 */
return MC_CMD_MEDIA_QSFP_PLUS;
default:
return 0;
}
}
int efx_mcdi_phy_get_module_eeprom(struct efx_nic *efx, struct ethtool_eeprom *ee, u8 *data)
{
int rc;
ssize_t space_remaining = ee->len;
unsigned int page_off;
bool ignore_missing;
int num_pages;
int page;
switch (efx_mcdi_phy_module_type(efx)) {
case MC_CMD_MEDIA_SFP_PLUS:
num_pages = efx_mcdi_phy_sff_8472_level(efx) > 0 ?
SFF_8472_NUM_PAGES : SFF_8079_NUM_PAGES;
page = 0;
ignore_missing = false;
break;
case MC_CMD_MEDIA_QSFP_PLUS:
num_pages = SFF_8436_NUM_PAGES;
page = -1; /* We obtain the lower page by asking for -1. */
ignore_missing = true; /* Ignore missing pages after page 0. */
break;
default:
return -EOPNOTSUPP;
}
page_off = ee->offset % SFP_PAGE_SIZE;
page += ee->offset / SFP_PAGE_SIZE;
while (space_remaining && (page < num_pages)) {
rc = efx_mcdi_phy_get_module_eeprom_page(efx, page,
data, page_off,
space_remaining);
if (rc > 0) {
space_remaining -= rc;
data += rc;
page_off = 0;
page++;
} else if (rc == 0) {
space_remaining = 0;
} else if (ignore_missing && (page > 0)) {
int intended_size = SFP_PAGE_SIZE - page_off;
space_remaining -= intended_size;
if (space_remaining < 0) {
space_remaining = 0;
} else {
memset(data, 0, intended_size);
data += intended_size;
page_off = 0;
page++;
rc = 0;
}
} else {
return rc;
}
}
return 0;
}
int efx_mcdi_phy_get_module_info(struct efx_nic *efx, struct ethtool_modinfo *modinfo)
{
int sff_8472_level;
int diag_type;
switch (efx_mcdi_phy_module_type(efx)) {
case MC_CMD_MEDIA_SFP_PLUS:
sff_8472_level = efx_mcdi_phy_sff_8472_level(efx);
/* If we can't read the diagnostics level we have none. */
if (sff_8472_level < 0)
return -EOPNOTSUPP;
/* Check if this module requires the (unsupported) address
* change operation.
*/
diag_type = efx_mcdi_phy_diag_type(efx);
if (sff_8472_level == 0 ||
(diag_type & SFF_DIAG_ADDR_CHANGE)) {
modinfo->type = ETH_MODULE_SFF_8079;
modinfo->eeprom_len = ETH_MODULE_SFF_8079_LEN;
} else {
modinfo->type = ETH_MODULE_SFF_8472;
modinfo->eeprom_len = ETH_MODULE_SFF_8472_LEN;
}
break;
case MC_CMD_MEDIA_QSFP_PLUS:
modinfo->type = ETH_MODULE_SFF_8436;
modinfo->eeprom_len = ETH_MODULE_SFF_8436_MAX_LEN;
break;
default:
return -EOPNOTSUPP;
}
return 0;
}
static unsigned int efx_calc_mac_mtu(struct efx_nic *efx)
{
return EFX_MAX_FRAME_LEN(efx->net_dev->mtu);
}
int efx_mcdi_set_mac(struct efx_nic *efx)
{
u32 fcntl;
MCDI_DECLARE_BUF(cmdbytes, MC_CMD_SET_MAC_IN_LEN);
BUILD_BUG_ON(MC_CMD_SET_MAC_OUT_LEN != 0);
/* This has no effect on EF10 */
ether_addr_copy(MCDI_PTR(cmdbytes, SET_MAC_IN_ADDR),
efx->net_dev->dev_addr);
MCDI_SET_DWORD(cmdbytes, SET_MAC_IN_MTU, efx_calc_mac_mtu(efx));
MCDI_SET_DWORD(cmdbytes, SET_MAC_IN_DRAIN, 0);
MCDI_POPULATE_DWORD_1(cmdbytes, SET_MAC_IN_FLAGS,
SET_MAC_IN_FLAG_INCLUDE_FCS,
!!(efx->net_dev->features & NETIF_F_RXFCS));
switch (efx->wanted_fc) {
case EFX_FC_RX | EFX_FC_TX:
fcntl = MC_CMD_FCNTL_BIDIR;
break;
case EFX_FC_RX:
fcntl = MC_CMD_FCNTL_RESPOND;
break;
default:
fcntl = MC_CMD_FCNTL_OFF;
break;
}
if (efx->wanted_fc & EFX_FC_AUTO)
fcntl = MC_CMD_FCNTL_AUTO;
if (efx->fc_disable)
fcntl = MC_CMD_FCNTL_OFF;
MCDI_SET_DWORD(cmdbytes, SET_MAC_IN_FCNTL, fcntl);
return efx_mcdi_rpc(efx, MC_CMD_SET_MAC, cmdbytes, sizeof(cmdbytes),
NULL, 0, NULL);
}
int efx_mcdi_set_mtu(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_SET_MAC_EXT_IN_LEN);
BUILD_BUG_ON(MC_CMD_SET_MAC_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, SET_MAC_EXT_IN_MTU, efx_calc_mac_mtu(efx));
MCDI_POPULATE_DWORD_1(inbuf, SET_MAC_EXT_IN_CONTROL,
SET_MAC_EXT_IN_CFG_MTU, 1);
return efx_mcdi_rpc(efx, MC_CMD_SET_MAC, inbuf, sizeof(inbuf),
NULL, 0, NULL);
}
enum efx_stats_action {
EFX_STATS_ENABLE,
EFX_STATS_DISABLE,
EFX_STATS_PULL,
};
static int efx_mcdi_mac_stats(struct efx_nic *efx,
enum efx_stats_action action, int clear)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAC_STATS_IN_LEN);
int rc;
int change = action == EFX_STATS_PULL ? 0 : 1;
int enable = action == EFX_STATS_ENABLE ? 1 : 0;
int period = action == EFX_STATS_ENABLE ? 1000 : 0;
dma_addr_t dma_addr = efx->stats_buffer.dma_addr;
u32 dma_len = action != EFX_STATS_DISABLE ?
efx->num_mac_stats * sizeof(u64) : 0;
BUILD_BUG_ON(MC_CMD_MAC_STATS_OUT_DMA_LEN != 0);
MCDI_SET_QWORD(inbuf, MAC_STATS_IN_DMA_ADDR, dma_addr);
MCDI_POPULATE_DWORD_7(inbuf, MAC_STATS_IN_CMD,
MAC_STATS_IN_DMA, !!enable,
MAC_STATS_IN_CLEAR, clear,
MAC_STATS_IN_PERIODIC_CHANGE, change,
MAC_STATS_IN_PERIODIC_ENABLE, enable,
MAC_STATS_IN_PERIODIC_CLEAR, 0,
MAC_STATS_IN_PERIODIC_NOEVENT, 1,
MAC_STATS_IN_PERIOD_MS, period);
MCDI_SET_DWORD(inbuf, MAC_STATS_IN_DMA_LEN, dma_len);
if (efx_nic_rev(efx) >= EFX_REV_HUNT_A0)
MCDI_SET_DWORD(inbuf, MAC_STATS_IN_PORT_ID, efx->vport_id);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_MAC_STATS, inbuf, sizeof(inbuf),
NULL, 0, NULL);
/* Expect ENOENT if DMA queues have not been set up */
if (rc && (rc != -ENOENT || atomic_read(&efx->active_queues)))
efx_mcdi_display_error(efx, MC_CMD_MAC_STATS, sizeof(inbuf),
NULL, 0, rc);
return rc;
}
void efx_mcdi_mac_start_stats(struct efx_nic *efx)
{
__le64 *dma_stats = efx->stats_buffer.addr;
dma_stats[efx->num_mac_stats - 1] = EFX_MC_STATS_GENERATION_INVALID;
efx_mcdi_mac_stats(efx, EFX_STATS_ENABLE, 0);
}
void efx_mcdi_mac_stop_stats(struct efx_nic *efx)
{
efx_mcdi_mac_stats(efx, EFX_STATS_DISABLE, 0);
}
#define EFX_MAC_STATS_WAIT_US 100
#define EFX_MAC_STATS_WAIT_ATTEMPTS 10
void efx_mcdi_mac_pull_stats(struct efx_nic *efx)
{
__le64 *dma_stats = efx->stats_buffer.addr;
int attempts = EFX_MAC_STATS_WAIT_ATTEMPTS;
dma_stats[efx->num_mac_stats - 1] = EFX_MC_STATS_GENERATION_INVALID;
efx_mcdi_mac_stats(efx, EFX_STATS_PULL, 0);
while (dma_stats[efx->num_mac_stats - 1] ==
EFX_MC_STATS_GENERATION_INVALID &&
attempts-- != 0)
udelay(EFX_MAC_STATS_WAIT_US);
}
int efx_mcdi_mac_init_stats(struct efx_nic *efx)
{
int rc;
if (!efx->num_mac_stats)
return 0;
/* Allocate buffer for stats */
rc = efx_nic_alloc_buffer(efx, &efx->stats_buffer,
efx->num_mac_stats * sizeof(u64), GFP_KERNEL);
if (rc) {
netif_warn(efx, probe, efx->net_dev,
"failed to allocate DMA buffer: %d\n", rc);
return rc;
}
netif_dbg(efx, probe, efx->net_dev,
"stats buffer at %llx (virt %p phys %llx)\n",
(u64) efx->stats_buffer.dma_addr,
efx->stats_buffer.addr,
(u64) virt_to_phys(efx->stats_buffer.addr));
return 0;
}
void efx_mcdi_mac_fini_stats(struct efx_nic *efx)
{
efx_nic_free_buffer(efx, &efx->stats_buffer);
}
/* Get physical port number (EF10 only; on Siena it is same as PF number) */
int efx_mcdi_port_get_number(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_PORT_ASSIGNMENT_OUT_LEN);
int rc;
rc = efx_mcdi_rpc(efx, MC_CMD_GET_PORT_ASSIGNMENT, NULL, 0,
outbuf, sizeof(outbuf), NULL);
if (rc)
return rc;
return MCDI_DWORD(outbuf, GET_PORT_ASSIGNMENT_OUT_PORT);
}
static unsigned int efx_mcdi_event_link_speed[] = {
[MCDI_EVENT_LINKCHANGE_SPEED_100M] = 100,
[MCDI_EVENT_LINKCHANGE_SPEED_1G] = 1000,
[MCDI_EVENT_LINKCHANGE_SPEED_10G] = 10000,
[MCDI_EVENT_LINKCHANGE_SPEED_40G] = 40000,
[MCDI_EVENT_LINKCHANGE_SPEED_25G] = 25000,
[MCDI_EVENT_LINKCHANGE_SPEED_50G] = 50000,
[MCDI_EVENT_LINKCHANGE_SPEED_100G] = 100000,
};
void efx_mcdi_process_link_change(struct efx_nic *efx, efx_qword_t *ev)
{
u32 flags, fcntl, speed, lpa;
speed = EFX_QWORD_FIELD(*ev, MCDI_EVENT_LINKCHANGE_SPEED);
EFX_WARN_ON_PARANOID(speed >= ARRAY_SIZE(efx_mcdi_event_link_speed));
speed = efx_mcdi_event_link_speed[speed];
flags = EFX_QWORD_FIELD(*ev, MCDI_EVENT_LINKCHANGE_LINK_FLAGS);
fcntl = EFX_QWORD_FIELD(*ev, MCDI_EVENT_LINKCHANGE_FCNTL);
lpa = EFX_QWORD_FIELD(*ev, MCDI_EVENT_LINKCHANGE_LP_CAP);
/* efx->link_state is only modified by efx_mcdi_phy_get_link(),
* which is only run after flushing the event queues. Therefore, it
* is safe to modify the link state outside of the mac_lock here.
*/
efx_mcdi_phy_decode_link(efx, &efx->link_state, speed, flags, fcntl);
efx_mcdi_phy_check_fcntl(efx, lpa);
efx_link_status_changed(efx);
}
|
linux-master
|
drivers/net/ethernet/sfc/mcdi_port_common.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2005-2019 Solarflare Communications Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include "net_driver.h"
#include "ef100_rx.h"
#include "rx_common.h"
#include "efx.h"
#include "nic_common.h"
#include "mcdi_functions.h"
#include "ef100_regs.h"
#include "ef100_nic.h"
#include "io.h"
/* Get the value of a field in the RX prefix */
#define PREFIX_OFFSET_W(_f) (ESF_GZ_RX_PREFIX_ ## _f ## _LBN / 32)
#define PREFIX_OFFSET_B(_f) (ESF_GZ_RX_PREFIX_ ## _f ## _LBN % 32)
#define PREFIX_WIDTH_MASK(_f) ((1ULL << ESF_GZ_RX_PREFIX_ ## _f ## _WIDTH) - 1)
#define PREFIX_WORD(_p, _f) le32_to_cpu((__force __le32)(_p)[PREFIX_OFFSET_W(_f)])
#define PREFIX_FIELD(_p, _f) ((PREFIX_WORD(_p, _f) >> PREFIX_OFFSET_B(_f)) & \
PREFIX_WIDTH_MASK(_f))
#define ESF_GZ_RX_PREFIX_NT_OR_INNER_L3_CLASS_LBN \
(ESF_GZ_RX_PREFIX_CLASS_LBN + ESF_GZ_RX_PREFIX_HCLASS_NT_OR_INNER_L3_CLASS_LBN)
#define ESF_GZ_RX_PREFIX_NT_OR_INNER_L3_CLASS_WIDTH \
ESF_GZ_RX_PREFIX_HCLASS_NT_OR_INNER_L3_CLASS_WIDTH
bool ef100_rx_buf_hash_valid(const u8 *prefix)
{
return PREFIX_FIELD(prefix, RSS_HASH_VALID);
}
static bool ef100_has_fcs_error(struct efx_channel *channel, u32 *prefix)
{
u16 rxclass;
u8 l2status;
rxclass = le16_to_cpu((__force __le16)PREFIX_FIELD(prefix, CLASS));
l2status = PREFIX_FIELD(&rxclass, HCLASS_L2_STATUS);
if (likely(l2status == ESE_GZ_RH_HCLASS_L2_STATUS_OK))
/* Everything is ok */
return false;
if (l2status == ESE_GZ_RH_HCLASS_L2_STATUS_FCS_ERR)
channel->n_rx_eth_crc_err++;
return true;
}
void __ef100_rx_packet(struct efx_channel *channel)
{
struct efx_rx_queue *rx_queue = efx_channel_get_rx_queue(channel);
struct efx_rx_buffer *rx_buf = efx_rx_buffer(rx_queue,
channel->rx_pkt_index);
struct efx_nic *efx = channel->efx;
struct ef100_nic_data *nic_data;
u8 *eh = efx_rx_buf_va(rx_buf);
__wsum csum = 0;
u16 ing_port;
u32 *prefix;
prefix = (u32 *)(eh - ESE_GZ_RX_PKT_PREFIX_LEN);
if (channel->type->receive_raw) {
u32 mark = PREFIX_FIELD(prefix, USER_MARK);
if (channel->type->receive_raw(rx_queue, mark))
return; /* packet was consumed */
}
if (ef100_has_fcs_error(channel, prefix) &&
unlikely(!(efx->net_dev->features & NETIF_F_RXALL)))
goto out;
rx_buf->len = le16_to_cpu((__force __le16)PREFIX_FIELD(prefix, LENGTH));
if (rx_buf->len <= sizeof(struct ethhdr)) {
if (net_ratelimit())
netif_err(channel->efx, rx_err, channel->efx->net_dev,
"RX packet too small (%d)\n", rx_buf->len);
++channel->n_rx_frm_trunc;
goto out;
}
ing_port = le16_to_cpu((__force __le16) PREFIX_FIELD(prefix, INGRESS_MPORT));
nic_data = efx->nic_data;
if (nic_data->have_mport && ing_port != nic_data->base_mport) {
#ifdef CONFIG_SFC_SRIOV
struct efx_rep *efv;
rcu_read_lock();
efv = efx_ef100_find_rep_by_mport(efx, ing_port);
if (efv) {
if (efv->net_dev->flags & IFF_UP)
efx_ef100_rep_rx_packet(efv, rx_buf);
rcu_read_unlock();
/* Representor Rx doesn't care about PF Rx buffer
* ownership, it just makes a copy. So, we are done
* with the Rx buffer from PF point of view and should
* free it.
*/
goto free_rx_buffer;
}
rcu_read_unlock();
#endif
if (net_ratelimit())
netif_warn(efx, drv, efx->net_dev,
"Unrecognised ing_port %04x (base %04x), dropping\n",
ing_port, nic_data->base_mport);
channel->n_rx_mport_bad++;
goto free_rx_buffer;
}
if (likely(efx->net_dev->features & NETIF_F_RXCSUM)) {
if (PREFIX_FIELD(prefix, NT_OR_INNER_L3_CLASS) == 1) {
++channel->n_rx_ip_hdr_chksum_err;
} else {
u16 sum = be16_to_cpu((__force __be16)PREFIX_FIELD(prefix, CSUM_FRAME));
csum = (__force __wsum) sum;
}
}
if (channel->type->receive_skb) {
/* no support for special channels yet, so just discard */
WARN_ON_ONCE(1);
goto free_rx_buffer;
}
efx_rx_packet_gro(channel, rx_buf, channel->rx_pkt_n_frags, eh, csum);
goto out;
free_rx_buffer:
efx_free_rx_buffers(rx_queue, rx_buf, 1);
out:
channel->rx_pkt_n_frags = 0;
}
static void ef100_rx_packet(struct efx_rx_queue *rx_queue, unsigned int index)
{
struct efx_rx_buffer *rx_buf = efx_rx_buffer(rx_queue, index);
struct efx_channel *channel = efx_rx_queue_channel(rx_queue);
struct efx_nic *efx = rx_queue->efx;
++rx_queue->rx_packets;
netif_vdbg(efx, rx_status, efx->net_dev,
"RX queue %d received id %x\n",
efx_rx_queue_index(rx_queue), index);
efx_sync_rx_buffer(efx, rx_buf, efx->rx_dma_len);
prefetch(efx_rx_buf_va(rx_buf));
rx_buf->page_offset += efx->rx_prefix_size;
efx_recycle_rx_pages(channel, rx_buf, 1);
efx_rx_flush_packet(channel);
channel->rx_pkt_n_frags = 1;
channel->rx_pkt_index = index;
}
void efx_ef100_ev_rx(struct efx_channel *channel, const efx_qword_t *p_event)
{
struct efx_rx_queue *rx_queue = efx_channel_get_rx_queue(channel);
unsigned int n_packets =
EFX_QWORD_FIELD(*p_event, ESF_GZ_EV_RXPKTS_NUM_PKT);
int i;
WARN_ON_ONCE(!n_packets);
if (n_packets > 1)
++channel->n_rx_merge_events;
channel->irq_mod_score += 2 * n_packets;
for (i = 0; i < n_packets; ++i) {
ef100_rx_packet(rx_queue,
rx_queue->removed_count & rx_queue->ptr_mask);
++rx_queue->removed_count;
}
}
void ef100_rx_write(struct efx_rx_queue *rx_queue)
{
unsigned int notified_count = rx_queue->notified_count;
struct efx_rx_buffer *rx_buf;
unsigned int idx;
efx_qword_t *rxd;
efx_dword_t rxdb;
while (notified_count != rx_queue->added_count) {
idx = notified_count & rx_queue->ptr_mask;
rx_buf = efx_rx_buffer(rx_queue, idx);
rxd = efx_rx_desc(rx_queue, idx);
EFX_POPULATE_QWORD_1(*rxd, ESF_GZ_RX_BUF_ADDR, rx_buf->dma_addr);
++notified_count;
}
if (notified_count == rx_queue->notified_count)
return;
wmb();
EFX_POPULATE_DWORD_1(rxdb, ERF_GZ_RX_RING_PIDX,
rx_queue->added_count & rx_queue->ptr_mask);
efx_writed_page(rx_queue->efx, &rxdb,
ER_GZ_RX_RING_DOORBELL, efx_rx_queue_index(rx_queue));
if (rx_queue->grant_credits)
wmb();
rx_queue->notified_count = notified_count;
if (rx_queue->grant_credits)
schedule_work(&rx_queue->grant_work);
}
|
linux-master
|
drivers/net/ethernet/sfc/ef100_rx.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2005-2006 Fen Systems Ltd.
* Copyright 2005-2013 Solarflare Communications Inc.
*/
#include <linux/filter.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/delay.h>
#include <linux/notifier.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/in.h>
#include <linux/ethtool.h>
#include <linux/topology.h>
#include <linux/gfp.h>
#include <linux/interrupt.h>
#include "net_driver.h"
#include <net/gre.h>
#include <net/udp_tunnel.h>
#include "efx.h"
#include "efx_common.h"
#include "efx_channels.h"
#include "ef100.h"
#include "rx_common.h"
#include "tx_common.h"
#include "nic.h"
#include "io.h"
#include "selftest.h"
#include "sriov.h"
#include "efx_devlink.h"
#include "mcdi_port_common.h"
#include "mcdi_pcol.h"
#include "workarounds.h"
/**************************************************************************
*
* Configurable values
*
*************************************************************************/
module_param_named(interrupt_mode, efx_interrupt_mode, uint, 0444);
MODULE_PARM_DESC(interrupt_mode,
"Interrupt mode (0=>MSIX 1=>MSI 2=>legacy)");
module_param(rss_cpus, uint, 0444);
MODULE_PARM_DESC(rss_cpus, "Number of CPUs to use for Receive-Side Scaling");
/*
* Use separate channels for TX and RX events
*
* Set this to 1 to use separate channels for TX and RX. It allows us
* to control interrupt affinity separately for TX and RX.
*
* This is only used in MSI-X interrupt mode
*/
bool efx_separate_tx_channels;
module_param(efx_separate_tx_channels, bool, 0444);
MODULE_PARM_DESC(efx_separate_tx_channels,
"Use separate channels for TX and RX");
/* Initial interrupt moderation settings. They can be modified after
* module load with ethtool.
*
* The default for RX should strike a balance between increasing the
* round-trip latency and reducing overhead.
*/
static unsigned int rx_irq_mod_usec = 60;
/* Initial interrupt moderation settings. They can be modified after
* module load with ethtool.
*
* This default is chosen to ensure that a 10G link does not go idle
* while a TX queue is stopped after it has become full. A queue is
* restarted when it drops below half full. The time this takes (assuming
* worst case 3 descriptors per packet and 1024 descriptors) is
* 512 / 3 * 1.2 = 205 usec.
*/
static unsigned int tx_irq_mod_usec = 150;
static bool phy_flash_cfg;
module_param(phy_flash_cfg, bool, 0644);
MODULE_PARM_DESC(phy_flash_cfg, "Set PHYs into reflash mode initially");
static unsigned debug = (NETIF_MSG_DRV | NETIF_MSG_PROBE |
NETIF_MSG_LINK | NETIF_MSG_IFDOWN |
NETIF_MSG_IFUP | NETIF_MSG_RX_ERR |
NETIF_MSG_TX_ERR | NETIF_MSG_HW);
module_param(debug, uint, 0);
MODULE_PARM_DESC(debug, "Bitmapped debugging message enable value");
/**************************************************************************
*
* Utility functions and prototypes
*
*************************************************************************/
static void efx_remove_port(struct efx_nic *efx);
static int efx_xdp_setup_prog(struct efx_nic *efx, struct bpf_prog *prog);
static int efx_xdp(struct net_device *dev, struct netdev_bpf *xdp);
static int efx_xdp_xmit(struct net_device *dev, int n, struct xdp_frame **xdpfs,
u32 flags);
/**************************************************************************
*
* Port handling
*
**************************************************************************/
static void efx_fini_port(struct efx_nic *efx);
static int efx_probe_port(struct efx_nic *efx)
{
int rc;
netif_dbg(efx, probe, efx->net_dev, "create port\n");
if (phy_flash_cfg)
efx->phy_mode = PHY_MODE_SPECIAL;
/* Connect up MAC/PHY operations table */
rc = efx->type->probe_port(efx);
if (rc)
return rc;
/* Initialise MAC address to permanent address */
eth_hw_addr_set(efx->net_dev, efx->net_dev->perm_addr);
return 0;
}
static int efx_init_port(struct efx_nic *efx)
{
int rc;
netif_dbg(efx, drv, efx->net_dev, "init port\n");
mutex_lock(&efx->mac_lock);
efx->port_initialized = true;
/* Ensure the PHY advertises the correct flow control settings */
rc = efx_mcdi_port_reconfigure(efx);
if (rc && rc != -EPERM)
goto fail;
mutex_unlock(&efx->mac_lock);
return 0;
fail:
mutex_unlock(&efx->mac_lock);
return rc;
}
static void efx_fini_port(struct efx_nic *efx)
{
netif_dbg(efx, drv, efx->net_dev, "shut down port\n");
if (!efx->port_initialized)
return;
efx->port_initialized = false;
efx->link_state.up = false;
efx_link_status_changed(efx);
}
static void efx_remove_port(struct efx_nic *efx)
{
netif_dbg(efx, drv, efx->net_dev, "destroying port\n");
efx->type->remove_port(efx);
}
/**************************************************************************
*
* NIC handling
*
**************************************************************************/
static LIST_HEAD(efx_primary_list);
static LIST_HEAD(efx_unassociated_list);
static bool efx_same_controller(struct efx_nic *left, struct efx_nic *right)
{
return left->type == right->type &&
left->vpd_sn && right->vpd_sn &&
!strcmp(left->vpd_sn, right->vpd_sn);
}
static void efx_associate(struct efx_nic *efx)
{
struct efx_nic *other, *next;
if (efx->primary == efx) {
/* Adding primary function; look for secondaries */
netif_dbg(efx, probe, efx->net_dev, "adding to primary list\n");
list_add_tail(&efx->node, &efx_primary_list);
list_for_each_entry_safe(other, next, &efx_unassociated_list,
node) {
if (efx_same_controller(efx, other)) {
list_del(&other->node);
netif_dbg(other, probe, other->net_dev,
"moving to secondary list of %s %s\n",
pci_name(efx->pci_dev),
efx->net_dev->name);
list_add_tail(&other->node,
&efx->secondary_list);
other->primary = efx;
}
}
} else {
/* Adding secondary function; look for primary */
list_for_each_entry(other, &efx_primary_list, node) {
if (efx_same_controller(efx, other)) {
netif_dbg(efx, probe, efx->net_dev,
"adding to secondary list of %s %s\n",
pci_name(other->pci_dev),
other->net_dev->name);
list_add_tail(&efx->node,
&other->secondary_list);
efx->primary = other;
return;
}
}
netif_dbg(efx, probe, efx->net_dev,
"adding to unassociated list\n");
list_add_tail(&efx->node, &efx_unassociated_list);
}
}
static void efx_dissociate(struct efx_nic *efx)
{
struct efx_nic *other, *next;
list_del(&efx->node);
efx->primary = NULL;
list_for_each_entry_safe(other, next, &efx->secondary_list, node) {
list_del(&other->node);
netif_dbg(other, probe, other->net_dev,
"moving to unassociated list\n");
list_add_tail(&other->node, &efx_unassociated_list);
other->primary = NULL;
}
}
static int efx_probe_nic(struct efx_nic *efx)
{
int rc;
netif_dbg(efx, probe, efx->net_dev, "creating NIC\n");
/* Carry out hardware-type specific initialisation */
rc = efx->type->probe(efx);
if (rc)
return rc;
do {
if (!efx->max_channels || !efx->max_tx_channels) {
netif_err(efx, drv, efx->net_dev,
"Insufficient resources to allocate"
" any channels\n");
rc = -ENOSPC;
goto fail1;
}
/* Determine the number of channels and queues by trying
* to hook in MSI-X interrupts.
*/
rc = efx_probe_interrupts(efx);
if (rc)
goto fail1;
rc = efx_set_channels(efx);
if (rc)
goto fail1;
/* dimension_resources can fail with EAGAIN */
rc = efx->type->dimension_resources(efx);
if (rc != 0 && rc != -EAGAIN)
goto fail2;
if (rc == -EAGAIN)
/* try again with new max_channels */
efx_remove_interrupts(efx);
} while (rc == -EAGAIN);
if (efx->n_channels > 1)
netdev_rss_key_fill(efx->rss_context.rx_hash_key,
sizeof(efx->rss_context.rx_hash_key));
efx_set_default_rx_indir_table(efx, &efx->rss_context);
/* Initialise the interrupt moderation settings */
efx->irq_mod_step_us = DIV_ROUND_UP(efx->timer_quantum_ns, 1000);
efx_init_irq_moderation(efx, tx_irq_mod_usec, rx_irq_mod_usec, true,
true);
return 0;
fail2:
efx_remove_interrupts(efx);
fail1:
efx->type->remove(efx);
return rc;
}
static void efx_remove_nic(struct efx_nic *efx)
{
netif_dbg(efx, drv, efx->net_dev, "destroying NIC\n");
efx_remove_interrupts(efx);
efx->type->remove(efx);
}
/**************************************************************************
*
* NIC startup/shutdown
*
*************************************************************************/
static int efx_probe_all(struct efx_nic *efx)
{
int rc;
rc = efx_probe_nic(efx);
if (rc) {
netif_err(efx, probe, efx->net_dev, "failed to create NIC\n");
goto fail1;
}
rc = efx_probe_port(efx);
if (rc) {
netif_err(efx, probe, efx->net_dev, "failed to create port\n");
goto fail2;
}
BUILD_BUG_ON(EFX_DEFAULT_DMAQ_SIZE < EFX_RXQ_MIN_ENT);
if (WARN_ON(EFX_DEFAULT_DMAQ_SIZE < EFX_TXQ_MIN_ENT(efx))) {
rc = -EINVAL;
goto fail3;
}
#ifdef CONFIG_SFC_SRIOV
rc = efx->type->vswitching_probe(efx);
if (rc) /* not fatal; the PF will still work fine */
netif_warn(efx, probe, efx->net_dev,
"failed to setup vswitching rc=%d;"
" VFs may not function\n", rc);
#endif
rc = efx_probe_filters(efx);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"failed to create filter tables\n");
goto fail4;
}
rc = efx_probe_channels(efx);
if (rc)
goto fail5;
efx->state = STATE_NET_DOWN;
return 0;
fail5:
efx_remove_filters(efx);
fail4:
#ifdef CONFIG_SFC_SRIOV
efx->type->vswitching_remove(efx);
#endif
fail3:
efx_remove_port(efx);
fail2:
efx_remove_nic(efx);
fail1:
return rc;
}
static void efx_remove_all(struct efx_nic *efx)
{
rtnl_lock();
efx_xdp_setup_prog(efx, NULL);
rtnl_unlock();
efx_remove_channels(efx);
efx_remove_filters(efx);
#ifdef CONFIG_SFC_SRIOV
efx->type->vswitching_remove(efx);
#endif
efx_remove_port(efx);
efx_remove_nic(efx);
}
/**************************************************************************
*
* Interrupt moderation
*
**************************************************************************/
unsigned int efx_usecs_to_ticks(struct efx_nic *efx, unsigned int usecs)
{
if (usecs == 0)
return 0;
if (usecs * 1000 < efx->timer_quantum_ns)
return 1; /* never round down to 0 */
return usecs * 1000 / efx->timer_quantum_ns;
}
unsigned int efx_ticks_to_usecs(struct efx_nic *efx, unsigned int ticks)
{
/* We must round up when converting ticks to microseconds
* because we round down when converting the other way.
*/
return DIV_ROUND_UP(ticks * efx->timer_quantum_ns, 1000);
}
/* Set interrupt moderation parameters */
int efx_init_irq_moderation(struct efx_nic *efx, unsigned int tx_usecs,
unsigned int rx_usecs, bool rx_adaptive,
bool rx_may_override_tx)
{
struct efx_channel *channel;
unsigned int timer_max_us;
EFX_ASSERT_RESET_SERIALISED(efx);
timer_max_us = efx->timer_max_ns / 1000;
if (tx_usecs > timer_max_us || rx_usecs > timer_max_us)
return -EINVAL;
if (tx_usecs != rx_usecs && efx->tx_channel_offset == 0 &&
!rx_may_override_tx) {
netif_err(efx, drv, efx->net_dev, "Channels are shared. "
"RX and TX IRQ moderation must be equal\n");
return -EINVAL;
}
efx->irq_rx_adaptive = rx_adaptive;
efx->irq_rx_moderation_us = rx_usecs;
efx_for_each_channel(channel, efx) {
if (efx_channel_has_rx_queue(channel))
channel->irq_moderation_us = rx_usecs;
else if (efx_channel_has_tx_queues(channel))
channel->irq_moderation_us = tx_usecs;
else if (efx_channel_is_xdp_tx(channel))
channel->irq_moderation_us = tx_usecs;
}
return 0;
}
void efx_get_irq_moderation(struct efx_nic *efx, unsigned int *tx_usecs,
unsigned int *rx_usecs, bool *rx_adaptive)
{
*rx_adaptive = efx->irq_rx_adaptive;
*rx_usecs = efx->irq_rx_moderation_us;
/* If channels are shared between RX and TX, so is IRQ
* moderation. Otherwise, IRQ moderation is the same for all
* TX channels and is not adaptive.
*/
if (efx->tx_channel_offset == 0) {
*tx_usecs = *rx_usecs;
} else {
struct efx_channel *tx_channel;
tx_channel = efx->channel[efx->tx_channel_offset];
*tx_usecs = tx_channel->irq_moderation_us;
}
}
/**************************************************************************
*
* ioctls
*
*************************************************************************/
/* Net device ioctl
* Context: process, rtnl_lock() held.
*/
static int efx_ioctl(struct net_device *net_dev, struct ifreq *ifr, int cmd)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
struct mii_ioctl_data *data = if_mii(ifr);
if (cmd == SIOCSHWTSTAMP)
return efx_ptp_set_ts_config(efx, ifr);
if (cmd == SIOCGHWTSTAMP)
return efx_ptp_get_ts_config(efx, ifr);
/* Convert phy_id from older PRTAD/DEVAD format */
if ((cmd == SIOCGMIIREG || cmd == SIOCSMIIREG) &&
(data->phy_id & 0xfc00) == 0x0400)
data->phy_id ^= MDIO_PHY_ID_C45 | 0x0400;
return mdio_mii_ioctl(&efx->mdio, data, cmd);
}
/**************************************************************************
*
* Kernel net device interface
*
*************************************************************************/
/* Context: process, rtnl_lock() held. */
int efx_net_open(struct net_device *net_dev)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
int rc;
netif_dbg(efx, ifup, efx->net_dev, "opening device on CPU %d\n",
raw_smp_processor_id());
rc = efx_check_disabled(efx);
if (rc)
return rc;
if (efx->phy_mode & PHY_MODE_SPECIAL)
return -EBUSY;
if (efx_mcdi_poll_reboot(efx) && efx_reset(efx, RESET_TYPE_ALL))
return -EIO;
/* Notify the kernel of the link state polled during driver load,
* before the monitor starts running */
efx_link_status_changed(efx);
efx_start_all(efx);
if (efx->state == STATE_DISABLED || efx->reset_pending)
netif_device_detach(efx->net_dev);
else
efx->state = STATE_NET_UP;
return 0;
}
/* Context: process, rtnl_lock() held.
* Note that the kernel will ignore our return code; this method
* should really be a void.
*/
int efx_net_stop(struct net_device *net_dev)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
netif_dbg(efx, ifdown, efx->net_dev, "closing on CPU %d\n",
raw_smp_processor_id());
/* Stop the device and flush all the channels */
efx_stop_all(efx);
return 0;
}
static int efx_vlan_rx_add_vid(struct net_device *net_dev, __be16 proto, u16 vid)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
if (efx->type->vlan_rx_add_vid)
return efx->type->vlan_rx_add_vid(efx, proto, vid);
else
return -EOPNOTSUPP;
}
static int efx_vlan_rx_kill_vid(struct net_device *net_dev, __be16 proto, u16 vid)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
if (efx->type->vlan_rx_kill_vid)
return efx->type->vlan_rx_kill_vid(efx, proto, vid);
else
return -EOPNOTSUPP;
}
static const struct net_device_ops efx_netdev_ops = {
.ndo_open = efx_net_open,
.ndo_stop = efx_net_stop,
.ndo_get_stats64 = efx_net_stats,
.ndo_tx_timeout = efx_watchdog,
.ndo_start_xmit = efx_hard_start_xmit,
.ndo_validate_addr = eth_validate_addr,
.ndo_eth_ioctl = efx_ioctl,
.ndo_change_mtu = efx_change_mtu,
.ndo_set_mac_address = efx_set_mac_address,
.ndo_set_rx_mode = efx_set_rx_mode,
.ndo_set_features = efx_set_features,
.ndo_features_check = efx_features_check,
.ndo_vlan_rx_add_vid = efx_vlan_rx_add_vid,
.ndo_vlan_rx_kill_vid = efx_vlan_rx_kill_vid,
#ifdef CONFIG_SFC_SRIOV
.ndo_set_vf_mac = efx_sriov_set_vf_mac,
.ndo_set_vf_vlan = efx_sriov_set_vf_vlan,
.ndo_set_vf_spoofchk = efx_sriov_set_vf_spoofchk,
.ndo_get_vf_config = efx_sriov_get_vf_config,
.ndo_set_vf_link_state = efx_sriov_set_vf_link_state,
#endif
.ndo_get_phys_port_id = efx_get_phys_port_id,
.ndo_get_phys_port_name = efx_get_phys_port_name,
#ifdef CONFIG_RFS_ACCEL
.ndo_rx_flow_steer = efx_filter_rfs,
#endif
.ndo_xdp_xmit = efx_xdp_xmit,
.ndo_bpf = efx_xdp
};
static int efx_xdp_setup_prog(struct efx_nic *efx, struct bpf_prog *prog)
{
struct bpf_prog *old_prog;
if (efx->xdp_rxq_info_failed) {
netif_err(efx, drv, efx->net_dev,
"Unable to bind XDP program due to previous failure of rxq_info\n");
return -EINVAL;
}
if (prog && efx->net_dev->mtu > efx_xdp_max_mtu(efx)) {
netif_err(efx, drv, efx->net_dev,
"Unable to configure XDP with MTU of %d (max: %d)\n",
efx->net_dev->mtu, efx_xdp_max_mtu(efx));
return -EINVAL;
}
old_prog = rtnl_dereference(efx->xdp_prog);
rcu_assign_pointer(efx->xdp_prog, prog);
/* Release the reference that was originally passed by the caller. */
if (old_prog)
bpf_prog_put(old_prog);
return 0;
}
/* Context: process, rtnl_lock() held. */
static int efx_xdp(struct net_device *dev, struct netdev_bpf *xdp)
{
struct efx_nic *efx = efx_netdev_priv(dev);
switch (xdp->command) {
case XDP_SETUP_PROG:
return efx_xdp_setup_prog(efx, xdp->prog);
default:
return -EINVAL;
}
}
static int efx_xdp_xmit(struct net_device *dev, int n, struct xdp_frame **xdpfs,
u32 flags)
{
struct efx_nic *efx = efx_netdev_priv(dev);
if (!netif_running(dev))
return -EINVAL;
return efx_xdp_tx_buffers(efx, n, xdpfs, flags & XDP_XMIT_FLUSH);
}
static void efx_update_name(struct efx_nic *efx)
{
strcpy(efx->name, efx->net_dev->name);
efx_mtd_rename(efx);
efx_set_channel_names(efx);
}
static int efx_netdev_event(struct notifier_block *this,
unsigned long event, void *ptr)
{
struct net_device *net_dev = netdev_notifier_info_to_dev(ptr);
if ((net_dev->netdev_ops == &efx_netdev_ops) &&
event == NETDEV_CHANGENAME)
efx_update_name(efx_netdev_priv(net_dev));
return NOTIFY_DONE;
}
static struct notifier_block efx_netdev_notifier = {
.notifier_call = efx_netdev_event,
};
static ssize_t phy_type_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct efx_nic *efx = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", efx->phy_type);
}
static DEVICE_ATTR_RO(phy_type);
static int efx_register_netdev(struct efx_nic *efx)
{
struct net_device *net_dev = efx->net_dev;
struct efx_channel *channel;
int rc;
net_dev->watchdog_timeo = 5 * HZ;
net_dev->irq = efx->pci_dev->irq;
net_dev->netdev_ops = &efx_netdev_ops;
if (efx_nic_rev(efx) >= EFX_REV_HUNT_A0)
net_dev->priv_flags |= IFF_UNICAST_FLT;
net_dev->ethtool_ops = &efx_ethtool_ops;
netif_set_tso_max_segs(net_dev, EFX_TSO_MAX_SEGS);
net_dev->min_mtu = EFX_MIN_MTU;
net_dev->max_mtu = EFX_MAX_MTU;
rtnl_lock();
/* Enable resets to be scheduled and check whether any were
* already requested. If so, the NIC is probably hosed so we
* abort.
*/
if (efx->reset_pending) {
pci_err(efx->pci_dev, "aborting probe due to scheduled reset\n");
rc = -EIO;
goto fail_locked;
}
rc = dev_alloc_name(net_dev, net_dev->name);
if (rc < 0)
goto fail_locked;
efx_update_name(efx);
/* Always start with carrier off; PHY events will detect the link */
netif_carrier_off(net_dev);
rc = register_netdevice(net_dev);
if (rc)
goto fail_locked;
efx_for_each_channel(channel, efx) {
struct efx_tx_queue *tx_queue;
efx_for_each_channel_tx_queue(tx_queue, channel)
efx_init_tx_queue_core_txq(tx_queue);
}
efx_associate(efx);
efx->state = STATE_NET_DOWN;
rtnl_unlock();
rc = device_create_file(&efx->pci_dev->dev, &dev_attr_phy_type);
if (rc) {
netif_err(efx, drv, efx->net_dev,
"failed to init net dev attributes\n");
goto fail_registered;
}
efx_init_mcdi_logging(efx);
return 0;
fail_registered:
rtnl_lock();
efx_dissociate(efx);
unregister_netdevice(net_dev);
fail_locked:
efx->state = STATE_UNINIT;
rtnl_unlock();
netif_err(efx, drv, efx->net_dev, "could not register net dev\n");
return rc;
}
static void efx_unregister_netdev(struct efx_nic *efx)
{
if (!efx->net_dev)
return;
if (WARN_ON(efx_netdev_priv(efx->net_dev) != efx))
return;
if (efx_dev_registered(efx)) {
strscpy(efx->name, pci_name(efx->pci_dev), sizeof(efx->name));
efx_fini_mcdi_logging(efx);
device_remove_file(&efx->pci_dev->dev, &dev_attr_phy_type);
unregister_netdev(efx->net_dev);
}
}
/**************************************************************************
*
* List of NICs we support
*
**************************************************************************/
/* PCI device ID table */
static const struct pci_device_id efx_pci_table[] = {
{PCI_DEVICE(PCI_VENDOR_ID_SOLARFLARE, 0x0903), /* SFC9120 PF */
.driver_data = (unsigned long) &efx_hunt_a0_nic_type},
{PCI_DEVICE(PCI_VENDOR_ID_SOLARFLARE, 0x1903), /* SFC9120 VF */
.driver_data = (unsigned long) &efx_hunt_a0_vf_nic_type},
{PCI_DEVICE(PCI_VENDOR_ID_SOLARFLARE, 0x0923), /* SFC9140 PF */
.driver_data = (unsigned long) &efx_hunt_a0_nic_type},
{PCI_DEVICE(PCI_VENDOR_ID_SOLARFLARE, 0x1923), /* SFC9140 VF */
.driver_data = (unsigned long) &efx_hunt_a0_vf_nic_type},
{PCI_DEVICE(PCI_VENDOR_ID_SOLARFLARE, 0x0a03), /* SFC9220 PF */
.driver_data = (unsigned long) &efx_hunt_a0_nic_type},
{PCI_DEVICE(PCI_VENDOR_ID_SOLARFLARE, 0x1a03), /* SFC9220 VF */
.driver_data = (unsigned long) &efx_hunt_a0_vf_nic_type},
{PCI_DEVICE(PCI_VENDOR_ID_SOLARFLARE, 0x0b03), /* SFC9250 PF */
.driver_data = (unsigned long) &efx_hunt_a0_nic_type},
{PCI_DEVICE(PCI_VENDOR_ID_SOLARFLARE, 0x1b03), /* SFC9250 VF */
.driver_data = (unsigned long) &efx_hunt_a0_vf_nic_type},
{0} /* end of list */
};
/**************************************************************************
*
* Data housekeeping
*
**************************************************************************/
void efx_update_sw_stats(struct efx_nic *efx, u64 *stats)
{
u64 n_rx_nodesc_trunc = 0;
struct efx_channel *channel;
efx_for_each_channel(channel, efx)
n_rx_nodesc_trunc += channel->n_rx_nodesc_trunc;
stats[GENERIC_STAT_rx_nodesc_trunc] = n_rx_nodesc_trunc;
stats[GENERIC_STAT_rx_noskb_drops] = atomic_read(&efx->n_rx_noskb_drops);
}
/**************************************************************************
*
* PCI interface
*
**************************************************************************/
/* Main body of final NIC shutdown code
* This is called only at module unload (or hotplug removal).
*/
static void efx_pci_remove_main(struct efx_nic *efx)
{
/* Flush reset_work. It can no longer be scheduled since we
* are not READY.
*/
WARN_ON(efx_net_active(efx->state));
efx_flush_reset_workqueue(efx);
efx_disable_interrupts(efx);
efx_clear_interrupt_affinity(efx);
efx_nic_fini_interrupt(efx);
efx_fini_port(efx);
efx->type->fini(efx);
efx_fini_napi(efx);
efx_remove_all(efx);
}
/* Final NIC shutdown
* This is called only at module unload (or hotplug removal). A PF can call
* this on its VFs to ensure they are unbound first.
*/
static void efx_pci_remove(struct pci_dev *pci_dev)
{
struct efx_probe_data *probe_data;
struct efx_nic *efx;
efx = pci_get_drvdata(pci_dev);
if (!efx)
return;
/* Mark the NIC as fini, then stop the interface */
rtnl_lock();
efx_dissociate(efx);
dev_close(efx->net_dev);
efx_disable_interrupts(efx);
efx->state = STATE_UNINIT;
rtnl_unlock();
if (efx->type->sriov_fini)
efx->type->sriov_fini(efx);
efx_fini_devlink_lock(efx);
efx_unregister_netdev(efx);
efx_mtd_remove(efx);
efx_pci_remove_main(efx);
efx_fini_io(efx);
pci_dbg(efx->pci_dev, "shutdown successful\n");
efx_fini_devlink_and_unlock(efx);
efx_fini_struct(efx);
free_netdev(efx->net_dev);
probe_data = container_of(efx, struct efx_probe_data, efx);
kfree(probe_data);
};
/* NIC VPD information
* Called during probe to display the part number of the
* installed NIC.
*/
static void efx_probe_vpd_strings(struct efx_nic *efx)
{
struct pci_dev *dev = efx->pci_dev;
unsigned int vpd_size, kw_len;
u8 *vpd_data;
int start;
vpd_data = pci_vpd_alloc(dev, &vpd_size);
if (IS_ERR(vpd_data)) {
pci_warn(dev, "Unable to read VPD\n");
return;
}
start = pci_vpd_find_ro_info_keyword(vpd_data, vpd_size,
PCI_VPD_RO_KEYWORD_PARTNO, &kw_len);
if (start < 0)
pci_err(dev, "Part number not found or incomplete\n");
else
pci_info(dev, "Part Number : %.*s\n", kw_len, vpd_data + start);
start = pci_vpd_find_ro_info_keyword(vpd_data, vpd_size,
PCI_VPD_RO_KEYWORD_SERIALNO, &kw_len);
if (start < 0)
pci_err(dev, "Serial number not found or incomplete\n");
else
efx->vpd_sn = kmemdup_nul(vpd_data + start, kw_len, GFP_KERNEL);
kfree(vpd_data);
}
/* Main body of NIC initialisation
* This is called at module load (or hotplug insertion, theoretically).
*/
static int efx_pci_probe_main(struct efx_nic *efx)
{
int rc;
/* Do start-of-day initialisation */
rc = efx_probe_all(efx);
if (rc)
goto fail1;
efx_init_napi(efx);
down_write(&efx->filter_sem);
rc = efx->type->init(efx);
up_write(&efx->filter_sem);
if (rc) {
pci_err(efx->pci_dev, "failed to initialise NIC\n");
goto fail3;
}
rc = efx_init_port(efx);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"failed to initialise port\n");
goto fail4;
}
rc = efx_nic_init_interrupt(efx);
if (rc)
goto fail5;
efx_set_interrupt_affinity(efx);
rc = efx_enable_interrupts(efx);
if (rc)
goto fail6;
return 0;
fail6:
efx_clear_interrupt_affinity(efx);
efx_nic_fini_interrupt(efx);
fail5:
efx_fini_port(efx);
fail4:
efx->type->fini(efx);
fail3:
efx_fini_napi(efx);
efx_remove_all(efx);
fail1:
return rc;
}
static int efx_pci_probe_post_io(struct efx_nic *efx)
{
struct net_device *net_dev = efx->net_dev;
int rc = efx_pci_probe_main(efx);
if (rc)
return rc;
if (efx->type->sriov_init) {
rc = efx->type->sriov_init(efx);
if (rc)
pci_err(efx->pci_dev, "SR-IOV can't be enabled rc %d\n",
rc);
}
/* Determine netdevice features */
net_dev->features |= efx->type->offload_features;
/* Add TSO features */
if (efx->type->tso_versions && efx->type->tso_versions(efx))
net_dev->features |= NETIF_F_TSO | NETIF_F_TSO6;
/* Mask for features that also apply to VLAN devices */
net_dev->vlan_features |= (NETIF_F_HW_CSUM | NETIF_F_SG |
NETIF_F_HIGHDMA | NETIF_F_ALL_TSO |
NETIF_F_RXCSUM);
/* Determine user configurable features */
net_dev->hw_features |= net_dev->features & ~efx->fixed_features;
/* Disable receiving frames with bad FCS, by default. */
net_dev->features &= ~NETIF_F_RXALL;
/* Disable VLAN filtering by default. It may be enforced if
* the feature is fixed (i.e. VLAN filters are required to
* receive VLAN tagged packets due to vPort restrictions).
*/
net_dev->features &= ~NETIF_F_HW_VLAN_CTAG_FILTER;
net_dev->features |= efx->fixed_features;
net_dev->xdp_features = NETDEV_XDP_ACT_BASIC |
NETDEV_XDP_ACT_REDIRECT |
NETDEV_XDP_ACT_NDO_XMIT;
/* devlink creation, registration and lock */
rc = efx_probe_devlink_and_lock(efx);
if (rc)
pci_err(efx->pci_dev, "devlink registration failed");
rc = efx_register_netdev(efx);
efx_probe_devlink_unlock(efx);
if (!rc)
return 0;
efx_pci_remove_main(efx);
return rc;
}
/* NIC initialisation
*
* This is called at module load (or hotplug insertion,
* theoretically). It sets up PCI mappings, resets the NIC,
* sets up and registers the network devices with the kernel and hooks
* the interrupt service routine. It does not prepare the device for
* transmission; this is left to the first time one of the network
* interfaces is brought up (i.e. efx_net_open).
*/
static int efx_pci_probe(struct pci_dev *pci_dev,
const struct pci_device_id *entry)
{
struct efx_probe_data *probe_data, **probe_ptr;
struct net_device *net_dev;
struct efx_nic *efx;
int rc;
/* Allocate probe data and struct efx_nic */
probe_data = kzalloc(sizeof(*probe_data), GFP_KERNEL);
if (!probe_data)
return -ENOMEM;
probe_data->pci_dev = pci_dev;
efx = &probe_data->efx;
/* Allocate and initialise a struct net_device */
net_dev = alloc_etherdev_mq(sizeof(probe_data), EFX_MAX_CORE_TX_QUEUES);
if (!net_dev) {
rc = -ENOMEM;
goto fail0;
}
probe_ptr = netdev_priv(net_dev);
*probe_ptr = probe_data;
efx->net_dev = net_dev;
efx->type = (const struct efx_nic_type *) entry->driver_data;
efx->fixed_features |= NETIF_F_HIGHDMA;
pci_set_drvdata(pci_dev, efx);
SET_NETDEV_DEV(net_dev, &pci_dev->dev);
rc = efx_init_struct(efx, pci_dev);
if (rc)
goto fail1;
efx->mdio.dev = net_dev;
pci_info(pci_dev, "Solarflare NIC detected\n");
if (!efx->type->is_vf)
efx_probe_vpd_strings(efx);
/* Set up basic I/O (BAR mappings etc) */
rc = efx_init_io(efx, efx->type->mem_bar(efx), efx->type->max_dma_mask,
efx->type->mem_map_size(efx));
if (rc)
goto fail2;
rc = efx_pci_probe_post_io(efx);
if (rc) {
/* On failure, retry once immediately.
* If we aborted probe due to a scheduled reset, dismiss it.
*/
efx->reset_pending = 0;
rc = efx_pci_probe_post_io(efx);
if (rc) {
/* On another failure, retry once more
* after a 50-305ms delay.
*/
unsigned char r;
get_random_bytes(&r, 1);
msleep((unsigned int)r + 50);
efx->reset_pending = 0;
rc = efx_pci_probe_post_io(efx);
}
}
if (rc)
goto fail3;
netif_dbg(efx, probe, efx->net_dev, "initialisation successful\n");
/* Try to create MTDs, but allow this to fail */
rtnl_lock();
rc = efx_mtd_probe(efx);
rtnl_unlock();
if (rc && rc != -EPERM)
netif_warn(efx, probe, efx->net_dev,
"failed to create MTDs (%d)\n", rc);
if (efx->type->udp_tnl_push_ports)
efx->type->udp_tnl_push_ports(efx);
return 0;
fail3:
efx_fini_io(efx);
fail2:
efx_fini_struct(efx);
fail1:
WARN_ON(rc > 0);
netif_dbg(efx, drv, efx->net_dev, "initialisation failed. rc=%d\n", rc);
free_netdev(net_dev);
fail0:
kfree(probe_data);
return rc;
}
/* efx_pci_sriov_configure returns the actual number of Virtual Functions
* enabled on success
*/
#ifdef CONFIG_SFC_SRIOV
static int efx_pci_sriov_configure(struct pci_dev *dev, int num_vfs)
{
int rc;
struct efx_nic *efx = pci_get_drvdata(dev);
if (efx->type->sriov_configure) {
rc = efx->type->sriov_configure(efx, num_vfs);
if (rc)
return rc;
else
return num_vfs;
} else
return -EOPNOTSUPP;
}
#endif
static int efx_pm_freeze(struct device *dev)
{
struct efx_nic *efx = dev_get_drvdata(dev);
rtnl_lock();
if (efx_net_active(efx->state)) {
efx_device_detach_sync(efx);
efx_stop_all(efx);
efx_disable_interrupts(efx);
efx->state = efx_freeze(efx->state);
}
rtnl_unlock();
return 0;
}
static void efx_pci_shutdown(struct pci_dev *pci_dev)
{
struct efx_nic *efx = pci_get_drvdata(pci_dev);
if (!efx)
return;
efx_pm_freeze(&pci_dev->dev);
pci_disable_device(pci_dev);
}
static int efx_pm_thaw(struct device *dev)
{
int rc;
struct efx_nic *efx = dev_get_drvdata(dev);
rtnl_lock();
if (efx_frozen(efx->state)) {
rc = efx_enable_interrupts(efx);
if (rc)
goto fail;
mutex_lock(&efx->mac_lock);
efx_mcdi_port_reconfigure(efx);
mutex_unlock(&efx->mac_lock);
efx_start_all(efx);
efx_device_attach_if_not_resetting(efx);
efx->state = efx_thaw(efx->state);
efx->type->resume_wol(efx);
}
rtnl_unlock();
/* Reschedule any quenched resets scheduled during efx_pm_freeze() */
efx_queue_reset_work(efx);
return 0;
fail:
rtnl_unlock();
return rc;
}
static int efx_pm_poweroff(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct efx_nic *efx = pci_get_drvdata(pci_dev);
efx->type->fini(efx);
efx->reset_pending = 0;
pci_save_state(pci_dev);
return pci_set_power_state(pci_dev, PCI_D3hot);
}
/* Used for both resume and restore */
static int efx_pm_resume(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct efx_nic *efx = pci_get_drvdata(pci_dev);
int rc;
rc = pci_set_power_state(pci_dev, PCI_D0);
if (rc)
return rc;
pci_restore_state(pci_dev);
rc = pci_enable_device(pci_dev);
if (rc)
return rc;
pci_set_master(efx->pci_dev);
rc = efx->type->reset(efx, RESET_TYPE_ALL);
if (rc)
return rc;
down_write(&efx->filter_sem);
rc = efx->type->init(efx);
up_write(&efx->filter_sem);
if (rc)
return rc;
rc = efx_pm_thaw(dev);
return rc;
}
static int efx_pm_suspend(struct device *dev)
{
int rc;
efx_pm_freeze(dev);
rc = efx_pm_poweroff(dev);
if (rc)
efx_pm_resume(dev);
return rc;
}
static const struct dev_pm_ops efx_pm_ops = {
.suspend = efx_pm_suspend,
.resume = efx_pm_resume,
.freeze = efx_pm_freeze,
.thaw = efx_pm_thaw,
.poweroff = efx_pm_poweroff,
.restore = efx_pm_resume,
};
static struct pci_driver efx_pci_driver = {
.name = KBUILD_MODNAME,
.id_table = efx_pci_table,
.probe = efx_pci_probe,
.remove = efx_pci_remove,
.driver.pm = &efx_pm_ops,
.shutdown = efx_pci_shutdown,
.err_handler = &efx_err_handlers,
#ifdef CONFIG_SFC_SRIOV
.sriov_configure = efx_pci_sriov_configure,
#endif
};
/**************************************************************************
*
* Kernel module interface
*
*************************************************************************/
static int __init efx_init_module(void)
{
int rc;
printk(KERN_INFO "Solarflare NET driver\n");
rc = register_netdevice_notifier(&efx_netdev_notifier);
if (rc)
goto err_notifier;
rc = efx_create_reset_workqueue();
if (rc)
goto err_reset;
rc = pci_register_driver(&efx_pci_driver);
if (rc < 0)
goto err_pci;
rc = pci_register_driver(&ef100_pci_driver);
if (rc < 0)
goto err_pci_ef100;
return 0;
err_pci_ef100:
pci_unregister_driver(&efx_pci_driver);
err_pci:
efx_destroy_reset_workqueue();
err_reset:
unregister_netdevice_notifier(&efx_netdev_notifier);
err_notifier:
return rc;
}
static void __exit efx_exit_module(void)
{
printk(KERN_INFO "Solarflare NET driver unloading\n");
pci_unregister_driver(&ef100_pci_driver);
pci_unregister_driver(&efx_pci_driver);
efx_destroy_reset_workqueue();
unregister_netdevice_notifier(&efx_netdev_notifier);
}
module_init(efx_init_module);
module_exit(efx_exit_module);
MODULE_AUTHOR("Solarflare Communications and "
"Michael Brown <[email protected]>");
MODULE_DESCRIPTION("Solarflare network driver");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, efx_pci_table);
|
linux-master
|
drivers/net/ethernet/sfc/efx.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2022 Xilinx Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include "tc_bindings.h"
#include "tc.h"
#include "tc_encap_actions.h"
struct efx_tc_block_binding {
struct list_head list;
struct efx_nic *efx;
struct efx_rep *efv;
struct net_device *otherdev; /* may actually be us */
struct flow_block *block;
};
static struct efx_tc_block_binding *efx_tc_find_binding(struct efx_nic *efx,
struct net_device *otherdev)
{
struct efx_tc_block_binding *binding;
ASSERT_RTNL();
list_for_each_entry(binding, &efx->tc->block_list, list)
if (binding->otherdev == otherdev)
return binding;
return NULL;
}
static int efx_tc_block_cb(enum tc_setup_type type, void *type_data,
void *cb_priv)
{
struct efx_tc_block_binding *binding = cb_priv;
struct flow_cls_offload *tcf = type_data;
switch (type) {
case TC_SETUP_CLSFLOWER:
return efx_tc_flower(binding->efx, binding->otherdev,
tcf, binding->efv);
default:
return -EOPNOTSUPP;
}
}
void efx_tc_block_unbind(void *cb_priv)
{
struct efx_tc_block_binding *binding = cb_priv;
list_del(&binding->list);
kfree(binding);
}
static struct efx_tc_block_binding *efx_tc_create_binding(
struct efx_nic *efx, struct efx_rep *efv,
struct net_device *otherdev, struct flow_block *block)
{
struct efx_tc_block_binding *binding = kmalloc(sizeof(*binding), GFP_KERNEL);
if (!binding)
return ERR_PTR(-ENOMEM);
binding->efx = efx;
binding->efv = efv;
binding->otherdev = otherdev;
binding->block = block;
list_add(&binding->list, &efx->tc->block_list);
return binding;
}
int efx_tc_setup_block(struct net_device *net_dev, struct efx_nic *efx,
struct flow_block_offload *tcb, struct efx_rep *efv)
{
struct efx_tc_block_binding *binding;
struct flow_block_cb *block_cb;
int rc;
if (tcb->binder_type != FLOW_BLOCK_BINDER_TYPE_CLSACT_INGRESS)
return -EOPNOTSUPP;
if (WARN_ON(!efx->tc))
return -ENETDOWN;
switch (tcb->command) {
case FLOW_BLOCK_BIND:
binding = efx_tc_create_binding(efx, efv, net_dev, tcb->block);
if (IS_ERR(binding))
return PTR_ERR(binding);
block_cb = flow_block_cb_alloc(efx_tc_block_cb, binding,
binding, efx_tc_block_unbind);
rc = PTR_ERR_OR_ZERO(block_cb);
netif_dbg(efx, drv, efx->net_dev,
"bind %sdirect block for device %s, rc %d\n",
net_dev == efx->net_dev ? "" :
efv ? "semi" : "in",
net_dev ? net_dev->name : NULL, rc);
if (rc) {
list_del(&binding->list);
kfree(binding);
} else {
flow_block_cb_add(block_cb, tcb);
}
return rc;
case FLOW_BLOCK_UNBIND:
binding = efx_tc_find_binding(efx, net_dev);
if (binding) {
block_cb = flow_block_cb_lookup(tcb->block,
efx_tc_block_cb,
binding);
if (block_cb) {
flow_block_cb_remove(block_cb, tcb);
netif_dbg(efx, drv, efx->net_dev,
"unbound %sdirect block for device %s\n",
net_dev == efx->net_dev ? "" :
binding->efv ? "semi" : "in",
net_dev ? net_dev->name : NULL);
return 0;
}
}
/* If we're in driver teardown, then we expect to have
* already unbound all our blocks (we did it early while
* we still had MCDI to remove the filters), so getting
* unbind callbacks now isn't a problem.
*/
netif_cond_dbg(efx, drv, efx->net_dev,
!efx->tc->up, warn,
"%sdirect block unbind for device %s, was never bound\n",
net_dev == efx->net_dev ? "" : "in",
net_dev ? net_dev->name : NULL);
return -ENOENT;
default:
return -EOPNOTSUPP;
}
}
int efx_tc_indr_setup_cb(struct net_device *net_dev, struct Qdisc *sch,
void *cb_priv, enum tc_setup_type type,
void *type_data, void *data,
void (*cleanup)(struct flow_block_cb *block_cb))
{
struct flow_block_offload *tcb = type_data;
struct efx_tc_block_binding *binding;
struct flow_block_cb *block_cb;
struct efx_nic *efx = cb_priv;
bool is_ovs_int_port;
int rc;
if (!net_dev)
return -EOPNOTSUPP;
if (tcb->binder_type != FLOW_BLOCK_BINDER_TYPE_CLSACT_INGRESS &&
tcb->binder_type != FLOW_BLOCK_BINDER_TYPE_CLSACT_EGRESS)
return -EOPNOTSUPP;
is_ovs_int_port = netif_is_ovs_master(net_dev);
if (tcb->binder_type == FLOW_BLOCK_BINDER_TYPE_CLSACT_EGRESS &&
!is_ovs_int_port)
return -EOPNOTSUPP;
if (is_ovs_int_port)
return -EOPNOTSUPP;
switch (type) {
case TC_SETUP_BLOCK:
switch (tcb->command) {
case FLOW_BLOCK_BIND:
binding = efx_tc_create_binding(efx, NULL, net_dev, tcb->block);
if (IS_ERR(binding))
return PTR_ERR(binding);
block_cb = flow_indr_block_cb_alloc(efx_tc_block_cb, binding,
binding, efx_tc_block_unbind,
tcb, net_dev, sch, data, binding,
cleanup);
rc = PTR_ERR_OR_ZERO(block_cb);
netif_dbg(efx, drv, efx->net_dev,
"bind indr block for device %s, rc %d\n",
net_dev ? net_dev->name : NULL, rc);
if (rc) {
list_del(&binding->list);
kfree(binding);
} else {
flow_block_cb_add(block_cb, tcb);
}
return rc;
case FLOW_BLOCK_UNBIND:
binding = efx_tc_find_binding(efx, net_dev);
if (!binding)
return -ENOENT;
block_cb = flow_block_cb_lookup(tcb->block,
efx_tc_block_cb,
binding);
if (!block_cb)
return -ENOENT;
flow_indr_block_cb_remove(block_cb, tcb);
netif_dbg(efx, drv, efx->net_dev,
"unbind indr block for device %s\n",
net_dev ? net_dev->name : NULL);
return 0;
default:
return -EOPNOTSUPP;
}
default:
return -EOPNOTSUPP;
}
}
/* .ndo_setup_tc implementation
* Entry point for flower block and filter management.
*/
int efx_tc_setup(struct net_device *net_dev, enum tc_setup_type type,
void *type_data)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
if (efx->type->is_vf)
return -EOPNOTSUPP;
if (!efx->tc)
return -EOPNOTSUPP;
if (type == TC_SETUP_CLSFLOWER)
return efx_tc_flower(efx, net_dev, type_data, NULL);
if (type == TC_SETUP_BLOCK)
return efx_tc_setup_block(net_dev, efx, type_data, NULL);
return -EOPNOTSUPP;
}
int efx_tc_netdev_event(struct efx_nic *efx, unsigned long event,
struct net_device *net_dev)
{
if (efx->type->is_vf)
return NOTIFY_DONE;
if (event == NETDEV_UNREGISTER)
efx_tc_unregister_egdev(efx, net_dev);
return NOTIFY_OK;
}
|
linux-master
|
drivers/net/ethernet/sfc/tc_bindings.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2011-2013 Solarflare Communications Inc.
*/
#include <linux/bitops.h>
#include <linux/slab.h>
#include <linux/hwmon.h>
#include <linux/stat.h>
#include "net_driver.h"
#include "mcdi.h"
#include "mcdi_pcol.h"
#include "nic.h"
enum efx_hwmon_type {
EFX_HWMON_UNKNOWN,
EFX_HWMON_TEMP, /* temperature */
EFX_HWMON_COOL, /* cooling device, probably a heatsink */
EFX_HWMON_IN, /* voltage */
EFX_HWMON_CURR, /* current */
EFX_HWMON_POWER, /* power */
EFX_HWMON_TYPES_COUNT
};
static const char *const efx_hwmon_unit[EFX_HWMON_TYPES_COUNT] = {
[EFX_HWMON_TEMP] = " degC",
[EFX_HWMON_COOL] = " rpm", /* though nonsense for a heatsink */
[EFX_HWMON_IN] = " mV",
[EFX_HWMON_CURR] = " mA",
[EFX_HWMON_POWER] = " W",
};
static const struct {
const char *label;
enum efx_hwmon_type hwmon_type;
int port;
} efx_mcdi_sensor_type[] = {
#define SENSOR(name, label, hwmon_type, port) \
[MC_CMD_SENSOR_##name] = { label, EFX_HWMON_ ## hwmon_type, port }
SENSOR(CONTROLLER_TEMP, "Controller board temp.", TEMP, -1),
SENSOR(PHY_COMMON_TEMP, "PHY temp.", TEMP, -1),
SENSOR(CONTROLLER_COOLING, "Controller heat sink", COOL, -1),
SENSOR(PHY0_TEMP, "PHY temp.", TEMP, 0),
SENSOR(PHY0_COOLING, "PHY heat sink", COOL, 0),
SENSOR(PHY1_TEMP, "PHY temp.", TEMP, 1),
SENSOR(PHY1_COOLING, "PHY heat sink", COOL, 1),
SENSOR(IN_1V0, "1.0V supply", IN, -1),
SENSOR(IN_1V2, "1.2V supply", IN, -1),
SENSOR(IN_1V8, "1.8V supply", IN, -1),
SENSOR(IN_2V5, "2.5V supply", IN, -1),
SENSOR(IN_3V3, "3.3V supply", IN, -1),
SENSOR(IN_12V0, "12.0V supply", IN, -1),
SENSOR(IN_1V2A, "1.2V analogue supply", IN, -1),
SENSOR(IN_VREF, "Ref. voltage", IN, -1),
SENSOR(OUT_VAOE, "AOE FPGA supply", IN, -1),
SENSOR(AOE_TEMP, "AOE FPGA temp.", TEMP, -1),
SENSOR(PSU_AOE_TEMP, "AOE regulator temp.", TEMP, -1),
SENSOR(PSU_TEMP, "Controller regulator temp.",
TEMP, -1),
SENSOR(FAN_0, "Fan 0", COOL, -1),
SENSOR(FAN_1, "Fan 1", COOL, -1),
SENSOR(FAN_2, "Fan 2", COOL, -1),
SENSOR(FAN_3, "Fan 3", COOL, -1),
SENSOR(FAN_4, "Fan 4", COOL, -1),
SENSOR(IN_VAOE, "AOE input supply", IN, -1),
SENSOR(OUT_IAOE, "AOE output current", CURR, -1),
SENSOR(IN_IAOE, "AOE input current", CURR, -1),
SENSOR(NIC_POWER, "Board power use", POWER, -1),
SENSOR(IN_0V9, "0.9V supply", IN, -1),
SENSOR(IN_I0V9, "0.9V supply current", CURR, -1),
SENSOR(IN_I1V2, "1.2V supply current", CURR, -1),
SENSOR(IN_0V9_ADC, "0.9V supply (ext. ADC)", IN, -1),
SENSOR(CONTROLLER_2_TEMP, "Controller board temp. 2", TEMP, -1),
SENSOR(VREG_INTERNAL_TEMP, "Regulator die temp.", TEMP, -1),
SENSOR(VREG_0V9_TEMP, "0.9V regulator temp.", TEMP, -1),
SENSOR(VREG_1V2_TEMP, "1.2V regulator temp.", TEMP, -1),
SENSOR(CONTROLLER_VPTAT,
"Controller PTAT voltage (int. ADC)", IN, -1),
SENSOR(CONTROLLER_INTERNAL_TEMP,
"Controller die temp. (int. ADC)", TEMP, -1),
SENSOR(CONTROLLER_VPTAT_EXTADC,
"Controller PTAT voltage (ext. ADC)", IN, -1),
SENSOR(CONTROLLER_INTERNAL_TEMP_EXTADC,
"Controller die temp. (ext. ADC)", TEMP, -1),
SENSOR(AMBIENT_TEMP, "Ambient temp.", TEMP, -1),
SENSOR(AIRFLOW, "Air flow raw", IN, -1),
SENSOR(VDD08D_VSS08D_CSR, "0.9V die (int. ADC)", IN, -1),
SENSOR(VDD08D_VSS08D_CSR_EXTADC, "0.9V die (ext. ADC)", IN, -1),
SENSOR(HOTPOINT_TEMP, "Controller board temp. (hotpoint)", TEMP, -1),
#undef SENSOR
};
static const char *const sensor_status_names[] = {
[MC_CMD_SENSOR_STATE_OK] = "OK",
[MC_CMD_SENSOR_STATE_WARNING] = "Warning",
[MC_CMD_SENSOR_STATE_FATAL] = "Fatal",
[MC_CMD_SENSOR_STATE_BROKEN] = "Device failure",
[MC_CMD_SENSOR_STATE_NO_READING] = "No reading",
};
void efx_mcdi_sensor_event(struct efx_nic *efx, efx_qword_t *ev)
{
unsigned int type, state, value;
enum efx_hwmon_type hwmon_type = EFX_HWMON_UNKNOWN;
const char *name = NULL, *state_txt, *unit;
type = EFX_QWORD_FIELD(*ev, MCDI_EVENT_SENSOREVT_MONITOR);
state = EFX_QWORD_FIELD(*ev, MCDI_EVENT_SENSOREVT_STATE);
value = EFX_QWORD_FIELD(*ev, MCDI_EVENT_SENSOREVT_VALUE);
/* Deal gracefully with the board having more drivers than we
* know about, but do not expect new sensor states. */
if (type < ARRAY_SIZE(efx_mcdi_sensor_type)) {
name = efx_mcdi_sensor_type[type].label;
hwmon_type = efx_mcdi_sensor_type[type].hwmon_type;
}
if (!name)
name = "No sensor name available";
EFX_WARN_ON_PARANOID(state >= ARRAY_SIZE(sensor_status_names));
state_txt = sensor_status_names[state];
EFX_WARN_ON_PARANOID(hwmon_type >= EFX_HWMON_TYPES_COUNT);
unit = efx_hwmon_unit[hwmon_type];
if (!unit)
unit = "";
netif_err(efx, hw, efx->net_dev,
"Sensor %d (%s) reports condition '%s' for value %d%s\n",
type, name, state_txt, value, unit);
}
#ifdef CONFIG_SFC_MCDI_MON
struct efx_mcdi_mon_attribute {
struct device_attribute dev_attr;
unsigned int index;
unsigned int type;
enum efx_hwmon_type hwmon_type;
unsigned int limit_value;
char name[12];
};
static int efx_mcdi_mon_update(struct efx_nic *efx)
{
struct efx_mcdi_mon *hwmon = efx_mcdi_mon(efx);
MCDI_DECLARE_BUF(inbuf, MC_CMD_READ_SENSORS_EXT_IN_LEN);
int rc;
MCDI_SET_QWORD(inbuf, READ_SENSORS_EXT_IN_DMA_ADDR,
hwmon->dma_buf.dma_addr);
MCDI_SET_DWORD(inbuf, READ_SENSORS_EXT_IN_LENGTH, hwmon->dma_buf.len);
rc = efx_mcdi_rpc(efx, MC_CMD_READ_SENSORS,
inbuf, sizeof(inbuf), NULL, 0, NULL);
if (rc == 0)
hwmon->last_update = jiffies;
return rc;
}
static int efx_mcdi_mon_get_entry(struct device *dev, unsigned int index,
efx_dword_t *entry)
{
struct efx_nic *efx = dev_get_drvdata(dev->parent);
struct efx_mcdi_mon *hwmon = efx_mcdi_mon(efx);
int rc;
BUILD_BUG_ON(MC_CMD_READ_SENSORS_OUT_LEN != 0);
mutex_lock(&hwmon->update_lock);
/* Use cached value if last update was < 1 s ago */
if (time_before(jiffies, hwmon->last_update + HZ))
rc = 0;
else
rc = efx_mcdi_mon_update(efx);
/* Copy out the requested entry */
*entry = ((efx_dword_t *)hwmon->dma_buf.addr)[index];
mutex_unlock(&hwmon->update_lock);
return rc;
}
static ssize_t efx_mcdi_mon_show_value(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct efx_mcdi_mon_attribute *mon_attr =
container_of(attr, struct efx_mcdi_mon_attribute, dev_attr);
efx_dword_t entry;
unsigned int value, state;
int rc;
rc = efx_mcdi_mon_get_entry(dev, mon_attr->index, &entry);
if (rc)
return rc;
state = EFX_DWORD_FIELD(entry, MC_CMD_SENSOR_VALUE_ENTRY_TYPEDEF_STATE);
if (state == MC_CMD_SENSOR_STATE_NO_READING)
return -EBUSY;
value = EFX_DWORD_FIELD(entry, MC_CMD_SENSOR_VALUE_ENTRY_TYPEDEF_VALUE);
switch (mon_attr->hwmon_type) {
case EFX_HWMON_TEMP:
/* Convert temperature from degrees to milli-degrees Celsius */
value *= 1000;
break;
case EFX_HWMON_POWER:
/* Convert power from watts to microwatts */
value *= 1000000;
break;
default:
/* No conversion needed */
break;
}
return sprintf(buf, "%u\n", value);
}
static ssize_t efx_mcdi_mon_show_limit(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct efx_mcdi_mon_attribute *mon_attr =
container_of(attr, struct efx_mcdi_mon_attribute, dev_attr);
unsigned int value;
value = mon_attr->limit_value;
switch (mon_attr->hwmon_type) {
case EFX_HWMON_TEMP:
/* Convert temperature from degrees to milli-degrees Celsius */
value *= 1000;
break;
case EFX_HWMON_POWER:
/* Convert power from watts to microwatts */
value *= 1000000;
break;
default:
/* No conversion needed */
break;
}
return sprintf(buf, "%u\n", value);
}
static ssize_t efx_mcdi_mon_show_alarm(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct efx_mcdi_mon_attribute *mon_attr =
container_of(attr, struct efx_mcdi_mon_attribute, dev_attr);
efx_dword_t entry;
int state;
int rc;
rc = efx_mcdi_mon_get_entry(dev, mon_attr->index, &entry);
if (rc)
return rc;
state = EFX_DWORD_FIELD(entry, MC_CMD_SENSOR_VALUE_ENTRY_TYPEDEF_STATE);
return sprintf(buf, "%d\n", state != MC_CMD_SENSOR_STATE_OK);
}
static ssize_t efx_mcdi_mon_show_label(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct efx_mcdi_mon_attribute *mon_attr =
container_of(attr, struct efx_mcdi_mon_attribute, dev_attr);
return sprintf(buf, "%s\n",
efx_mcdi_sensor_type[mon_attr->type].label);
}
static void
efx_mcdi_mon_add_attr(struct efx_nic *efx, const char *name,
ssize_t (*reader)(struct device *,
struct device_attribute *, char *),
unsigned int index, unsigned int type,
unsigned int limit_value)
{
struct efx_mcdi_mon *hwmon = efx_mcdi_mon(efx);
struct efx_mcdi_mon_attribute *attr = &hwmon->attrs[hwmon->n_attrs];
strscpy(attr->name, name, sizeof(attr->name));
attr->index = index;
attr->type = type;
if (type < ARRAY_SIZE(efx_mcdi_sensor_type))
attr->hwmon_type = efx_mcdi_sensor_type[type].hwmon_type;
else
attr->hwmon_type = EFX_HWMON_UNKNOWN;
attr->limit_value = limit_value;
sysfs_attr_init(&attr->dev_attr.attr);
attr->dev_attr.attr.name = attr->name;
attr->dev_attr.attr.mode = 0444;
attr->dev_attr.show = reader;
hwmon->group.attrs[hwmon->n_attrs++] = &attr->dev_attr.attr;
}
int efx_mcdi_mon_probe(struct efx_nic *efx)
{
unsigned int n_temp = 0, n_cool = 0, n_in = 0, n_curr = 0, n_power = 0;
struct efx_mcdi_mon *hwmon = efx_mcdi_mon(efx);
MCDI_DECLARE_BUF(inbuf, MC_CMD_SENSOR_INFO_EXT_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_SENSOR_INFO_OUT_LENMAX);
unsigned int n_pages, n_sensors, n_attrs, page;
size_t outlen;
char name[12];
u32 mask;
int rc, i, j, type;
/* Find out how many sensors are present */
n_sensors = 0;
page = 0;
do {
MCDI_SET_DWORD(inbuf, SENSOR_INFO_EXT_IN_PAGE, page);
rc = efx_mcdi_rpc(efx, MC_CMD_SENSOR_INFO, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < MC_CMD_SENSOR_INFO_OUT_LENMIN)
return -EIO;
mask = MCDI_DWORD(outbuf, SENSOR_INFO_OUT_MASK);
n_sensors += hweight32(mask & ~(1 << MC_CMD_SENSOR_PAGE0_NEXT));
++page;
} while (mask & (1 << MC_CMD_SENSOR_PAGE0_NEXT));
n_pages = page;
/* Don't create a device if there are none */
if (n_sensors == 0)
return 0;
rc = efx_nic_alloc_buffer(
efx, &hwmon->dma_buf,
n_sensors * MC_CMD_SENSOR_VALUE_ENTRY_TYPEDEF_LEN,
GFP_KERNEL);
if (rc)
return rc;
mutex_init(&hwmon->update_lock);
efx_mcdi_mon_update(efx);
/* Allocate space for the maximum possible number of
* attributes for this set of sensors:
* value, min, max, crit, alarm and label for each sensor.
*/
n_attrs = 6 * n_sensors;
hwmon->attrs = kcalloc(n_attrs, sizeof(*hwmon->attrs), GFP_KERNEL);
if (!hwmon->attrs) {
rc = -ENOMEM;
goto fail;
}
hwmon->group.attrs = kcalloc(n_attrs + 1, sizeof(struct attribute *),
GFP_KERNEL);
if (!hwmon->group.attrs) {
rc = -ENOMEM;
goto fail;
}
for (i = 0, j = -1, type = -1; ; i++) {
enum efx_hwmon_type hwmon_type;
const char *hwmon_prefix;
unsigned hwmon_index;
u16 min1, max1, min2, max2;
/* Find next sensor type or exit if there is none */
do {
type++;
if ((type % 32) == 0) {
page = type / 32;
j = -1;
if (page == n_pages)
goto hwmon_register;
MCDI_SET_DWORD(inbuf, SENSOR_INFO_EXT_IN_PAGE,
page);
rc = efx_mcdi_rpc(efx, MC_CMD_SENSOR_INFO,
inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf),
&outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_SENSOR_INFO_OUT_LENMIN) {
rc = -EIO;
goto fail;
}
mask = (MCDI_DWORD(outbuf,
SENSOR_INFO_OUT_MASK) &
~(1 << MC_CMD_SENSOR_PAGE0_NEXT));
/* Check again for short response */
if (outlen <
MC_CMD_SENSOR_INFO_OUT_LEN(hweight32(mask))) {
rc = -EIO;
goto fail;
}
}
} while (!(mask & (1 << type % 32)));
j++;
if (type < ARRAY_SIZE(efx_mcdi_sensor_type)) {
hwmon_type = efx_mcdi_sensor_type[type].hwmon_type;
/* Skip sensors specific to a different port */
if (hwmon_type != EFX_HWMON_UNKNOWN &&
efx_mcdi_sensor_type[type].port >= 0 &&
efx_mcdi_sensor_type[type].port !=
efx_port_num(efx))
continue;
} else {
hwmon_type = EFX_HWMON_UNKNOWN;
}
switch (hwmon_type) {
case EFX_HWMON_TEMP:
hwmon_prefix = "temp";
hwmon_index = ++n_temp; /* 1-based */
break;
case EFX_HWMON_COOL:
/* This is likely to be a heatsink, but there
* is no convention for representing cooling
* devices other than fans.
*/
hwmon_prefix = "fan";
hwmon_index = ++n_cool; /* 1-based */
break;
default:
hwmon_prefix = "in";
hwmon_index = n_in++; /* 0-based */
break;
case EFX_HWMON_CURR:
hwmon_prefix = "curr";
hwmon_index = ++n_curr; /* 1-based */
break;
case EFX_HWMON_POWER:
hwmon_prefix = "power";
hwmon_index = ++n_power; /* 1-based */
break;
}
min1 = MCDI_ARRAY_FIELD(outbuf, SENSOR_ENTRY,
SENSOR_INFO_ENTRY, j, MIN1);
max1 = MCDI_ARRAY_FIELD(outbuf, SENSOR_ENTRY,
SENSOR_INFO_ENTRY, j, MAX1);
min2 = MCDI_ARRAY_FIELD(outbuf, SENSOR_ENTRY,
SENSOR_INFO_ENTRY, j, MIN2);
max2 = MCDI_ARRAY_FIELD(outbuf, SENSOR_ENTRY,
SENSOR_INFO_ENTRY, j, MAX2);
if (min1 != max1) {
snprintf(name, sizeof(name), "%s%u_input",
hwmon_prefix, hwmon_index);
efx_mcdi_mon_add_attr(
efx, name, efx_mcdi_mon_show_value, i, type, 0);
if (hwmon_type != EFX_HWMON_POWER) {
snprintf(name, sizeof(name), "%s%u_min",
hwmon_prefix, hwmon_index);
efx_mcdi_mon_add_attr(
efx, name, efx_mcdi_mon_show_limit,
i, type, min1);
}
snprintf(name, sizeof(name), "%s%u_max",
hwmon_prefix, hwmon_index);
efx_mcdi_mon_add_attr(
efx, name, efx_mcdi_mon_show_limit,
i, type, max1);
if (min2 != max2) {
/* Assume max2 is critical value.
* But we have no good way to expose min2.
*/
snprintf(name, sizeof(name), "%s%u_crit",
hwmon_prefix, hwmon_index);
efx_mcdi_mon_add_attr(
efx, name, efx_mcdi_mon_show_limit,
i, type, max2);
}
}
snprintf(name, sizeof(name), "%s%u_alarm",
hwmon_prefix, hwmon_index);
efx_mcdi_mon_add_attr(
efx, name, efx_mcdi_mon_show_alarm, i, type, 0);
if (type < ARRAY_SIZE(efx_mcdi_sensor_type) &&
efx_mcdi_sensor_type[type].label) {
snprintf(name, sizeof(name), "%s%u_label",
hwmon_prefix, hwmon_index);
efx_mcdi_mon_add_attr(
efx, name, efx_mcdi_mon_show_label, i, type, 0);
}
}
hwmon_register:
hwmon->groups[0] = &hwmon->group;
hwmon->device = hwmon_device_register_with_groups(&efx->pci_dev->dev,
KBUILD_MODNAME, NULL,
hwmon->groups);
if (IS_ERR(hwmon->device)) {
rc = PTR_ERR(hwmon->device);
goto fail;
}
return 0;
fail:
efx_mcdi_mon_remove(efx);
return rc;
}
void efx_mcdi_mon_remove(struct efx_nic *efx)
{
struct efx_mcdi_mon *hwmon = efx_mcdi_mon(efx);
if (hwmon->device)
hwmon_device_unregister(hwmon->device);
kfree(hwmon->attrs);
kfree(hwmon->group.attrs);
efx_nic_free_buffer(efx, &hwmon->dma_buf);
}
#endif /* CONFIG_SFC_MCDI_MON */
|
linux-master
|
drivers/net/ethernet/sfc/mcdi_mon.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2018 Solarflare Communications Inc.
* Copyright 2019-2020 Xilinx Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include <linux/module.h>
#include <linux/netdevice.h>
#include "net_driver.h"
#include "efx.h"
#include "mcdi_port_common.h"
#include "ethtool_common.h"
#include "ef100_ethtool.h"
#include "mcdi_functions.h"
/* This is the maximum number of descriptor rings supported by the QDMA */
#define EFX_EF100_MAX_DMAQ_SIZE 16384UL
static void
ef100_ethtool_get_ringparam(struct net_device *net_dev,
struct ethtool_ringparam *ring,
struct kernel_ethtool_ringparam *kernel_ring,
struct netlink_ext_ack *extack)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
ring->rx_max_pending = EFX_EF100_MAX_DMAQ_SIZE;
ring->tx_max_pending = EFX_EF100_MAX_DMAQ_SIZE;
ring->rx_pending = efx->rxq_entries;
ring->tx_pending = efx->txq_entries;
}
/* Ethtool options available
*/
const struct ethtool_ops ef100_ethtool_ops = {
.get_drvinfo = efx_ethtool_get_drvinfo,
.get_msglevel = efx_ethtool_get_msglevel,
.set_msglevel = efx_ethtool_set_msglevel,
.get_pauseparam = efx_ethtool_get_pauseparam,
.set_pauseparam = efx_ethtool_set_pauseparam,
.get_sset_count = efx_ethtool_get_sset_count,
.self_test = efx_ethtool_self_test,
.get_strings = efx_ethtool_get_strings,
.get_link_ksettings = efx_ethtool_get_link_ksettings,
.set_link_ksettings = efx_ethtool_set_link_ksettings,
.get_link = ethtool_op_get_link,
.get_ringparam = ef100_ethtool_get_ringparam,
.get_fecparam = efx_ethtool_get_fecparam,
.set_fecparam = efx_ethtool_set_fecparam,
.get_ethtool_stats = efx_ethtool_get_stats,
.get_rxnfc = efx_ethtool_get_rxnfc,
.set_rxnfc = efx_ethtool_set_rxnfc,
.reset = efx_ethtool_reset,
.get_rxfh_indir_size = efx_ethtool_get_rxfh_indir_size,
.get_rxfh_key_size = efx_ethtool_get_rxfh_key_size,
.get_rxfh = efx_ethtool_get_rxfh,
.set_rxfh = efx_ethtool_set_rxfh,
.get_rxfh_context = efx_ethtool_get_rxfh_context,
.set_rxfh_context = efx_ethtool_set_rxfh_context,
.get_module_info = efx_ethtool_get_module_info,
.get_module_eeprom = efx_ethtool_get_module_eeprom,
};
|
linux-master
|
drivers/net/ethernet/sfc/ef100_ethtool.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2005-2006 Fen Systems Ltd.
* Copyright 2005-2013 Solarflare Communications Inc.
*/
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/slab.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include <linux/prefetch.h>
#include <linux/moduleparam.h>
#include <linux/iommu.h>
#include <net/ip.h>
#include <net/checksum.h>
#include <net/xdp.h>
#include <linux/bpf_trace.h>
#include "net_driver.h"
#include "efx.h"
#include "rx_common.h"
#include "filter.h"
#include "nic.h"
#include "selftest.h"
#include "workarounds.h"
/* Preferred number of descriptors to fill at once */
#define EFX_RX_PREFERRED_BATCH 8U
/* Maximum rx prefix used by any architecture. */
#define EFX_MAX_RX_PREFIX_SIZE 16
/* Size of buffer allocated for skb header area. */
#define EFX_SKB_HEADERS 128u
/* Each packet can consume up to ceil(max_frame_len / buffer_size) buffers */
#define EFX_RX_MAX_FRAGS DIV_ROUND_UP(EFX_MAX_FRAME_LEN(EFX_MAX_MTU), \
EFX_RX_USR_BUF_SIZE)
static void efx_rx_packet__check_len(struct efx_rx_queue *rx_queue,
struct efx_rx_buffer *rx_buf,
int len)
{
struct efx_nic *efx = rx_queue->efx;
unsigned max_len = rx_buf->len - efx->type->rx_buffer_padding;
if (likely(len <= max_len))
return;
/* The packet must be discarded, but this is only a fatal error
* if the caller indicated it was
*/
rx_buf->flags |= EFX_RX_PKT_DISCARD;
if (net_ratelimit())
netif_err(efx, rx_err, efx->net_dev,
"RX queue %d overlength RX event (%#x > %#x)\n",
efx_rx_queue_index(rx_queue), len, max_len);
efx_rx_queue_channel(rx_queue)->n_rx_overlength++;
}
/* Allocate and construct an SKB around page fragments */
static struct sk_buff *efx_rx_mk_skb(struct efx_channel *channel,
struct efx_rx_buffer *rx_buf,
unsigned int n_frags,
u8 *eh, int hdr_len)
{
struct efx_nic *efx = channel->efx;
struct sk_buff *skb;
/* Allocate an SKB to store the headers */
skb = netdev_alloc_skb(efx->net_dev,
efx->rx_ip_align + efx->rx_prefix_size +
hdr_len);
if (unlikely(skb == NULL)) {
atomic_inc(&efx->n_rx_noskb_drops);
return NULL;
}
EFX_WARN_ON_ONCE_PARANOID(rx_buf->len < hdr_len);
memcpy(skb->data + efx->rx_ip_align, eh - efx->rx_prefix_size,
efx->rx_prefix_size + hdr_len);
skb_reserve(skb, efx->rx_ip_align + efx->rx_prefix_size);
__skb_put(skb, hdr_len);
/* Append the remaining page(s) onto the frag list */
if (rx_buf->len > hdr_len) {
rx_buf->page_offset += hdr_len;
rx_buf->len -= hdr_len;
for (;;) {
skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags,
rx_buf->page, rx_buf->page_offset,
rx_buf->len, efx->rx_buffer_truesize);
rx_buf->page = NULL;
if (skb_shinfo(skb)->nr_frags == n_frags)
break;
rx_buf = efx_rx_buf_next(&channel->rx_queue, rx_buf);
}
} else {
__free_pages(rx_buf->page, efx->rx_buffer_order);
rx_buf->page = NULL;
n_frags = 0;
}
/* Move past the ethernet header */
skb->protocol = eth_type_trans(skb, efx->net_dev);
skb_mark_napi_id(skb, &channel->napi_str);
return skb;
}
void efx_rx_packet(struct efx_rx_queue *rx_queue, unsigned int index,
unsigned int n_frags, unsigned int len, u16 flags)
{
struct efx_nic *efx = rx_queue->efx;
struct efx_channel *channel = efx_rx_queue_channel(rx_queue);
struct efx_rx_buffer *rx_buf;
rx_queue->rx_packets++;
rx_buf = efx_rx_buffer(rx_queue, index);
rx_buf->flags |= flags;
/* Validate the number of fragments and completed length */
if (n_frags == 1) {
if (!(flags & EFX_RX_PKT_PREFIX_LEN))
efx_rx_packet__check_len(rx_queue, rx_buf, len);
} else if (unlikely(n_frags > EFX_RX_MAX_FRAGS) ||
unlikely(len <= (n_frags - 1) * efx->rx_dma_len) ||
unlikely(len > n_frags * efx->rx_dma_len) ||
unlikely(!efx->rx_scatter)) {
/* If this isn't an explicit discard request, either
* the hardware or the driver is broken.
*/
WARN_ON(!(len == 0 && rx_buf->flags & EFX_RX_PKT_DISCARD));
rx_buf->flags |= EFX_RX_PKT_DISCARD;
}
netif_vdbg(efx, rx_status, efx->net_dev,
"RX queue %d received ids %x-%x len %d %s%s\n",
efx_rx_queue_index(rx_queue), index,
(index + n_frags - 1) & rx_queue->ptr_mask, len,
(rx_buf->flags & EFX_RX_PKT_CSUMMED) ? " [SUMMED]" : "",
(rx_buf->flags & EFX_RX_PKT_DISCARD) ? " [DISCARD]" : "");
/* Discard packet, if instructed to do so. Process the
* previous receive first.
*/
if (unlikely(rx_buf->flags & EFX_RX_PKT_DISCARD)) {
efx_rx_flush_packet(channel);
efx_discard_rx_packet(channel, rx_buf, n_frags);
return;
}
if (n_frags == 1 && !(flags & EFX_RX_PKT_PREFIX_LEN))
rx_buf->len = len;
/* Release and/or sync the DMA mapping - assumes all RX buffers
* consumed in-order per RX queue.
*/
efx_sync_rx_buffer(efx, rx_buf, rx_buf->len);
/* Prefetch nice and early so data will (hopefully) be in cache by
* the time we look at it.
*/
prefetch(efx_rx_buf_va(rx_buf));
rx_buf->page_offset += efx->rx_prefix_size;
rx_buf->len -= efx->rx_prefix_size;
if (n_frags > 1) {
/* Release/sync DMA mapping for additional fragments.
* Fix length for last fragment.
*/
unsigned int tail_frags = n_frags - 1;
for (;;) {
rx_buf = efx_rx_buf_next(rx_queue, rx_buf);
if (--tail_frags == 0)
break;
efx_sync_rx_buffer(efx, rx_buf, efx->rx_dma_len);
}
rx_buf->len = len - (n_frags - 1) * efx->rx_dma_len;
efx_sync_rx_buffer(efx, rx_buf, rx_buf->len);
}
/* All fragments have been DMA-synced, so recycle pages. */
rx_buf = efx_rx_buffer(rx_queue, index);
efx_recycle_rx_pages(channel, rx_buf, n_frags);
/* Pipeline receives so that we give time for packet headers to be
* prefetched into cache.
*/
efx_rx_flush_packet(channel);
channel->rx_pkt_n_frags = n_frags;
channel->rx_pkt_index = index;
}
static void efx_rx_deliver(struct efx_channel *channel, u8 *eh,
struct efx_rx_buffer *rx_buf,
unsigned int n_frags)
{
struct sk_buff *skb;
u16 hdr_len = min_t(u16, rx_buf->len, EFX_SKB_HEADERS);
skb = efx_rx_mk_skb(channel, rx_buf, n_frags, eh, hdr_len);
if (unlikely(skb == NULL)) {
struct efx_rx_queue *rx_queue;
rx_queue = efx_channel_get_rx_queue(channel);
efx_free_rx_buffers(rx_queue, rx_buf, n_frags);
return;
}
skb_record_rx_queue(skb, channel->rx_queue.core_index);
/* Set the SKB flags */
skb_checksum_none_assert(skb);
if (likely(rx_buf->flags & EFX_RX_PKT_CSUMMED)) {
skb->ip_summed = CHECKSUM_UNNECESSARY;
skb->csum_level = !!(rx_buf->flags & EFX_RX_PKT_CSUM_LEVEL);
}
efx_rx_skb_attach_timestamp(channel, skb);
if (channel->type->receive_skb)
if (channel->type->receive_skb(channel, skb))
return;
/* Pass the packet up */
if (channel->rx_list != NULL)
/* Add to list, will pass up later */
list_add_tail(&skb->list, channel->rx_list);
else
/* No list, so pass it up now */
netif_receive_skb(skb);
}
/** efx_do_xdp: perform XDP processing on a received packet
*
* Returns true if packet should still be delivered.
*/
static bool efx_do_xdp(struct efx_nic *efx, struct efx_channel *channel,
struct efx_rx_buffer *rx_buf, u8 **ehp)
{
u8 rx_prefix[EFX_MAX_RX_PREFIX_SIZE];
struct efx_rx_queue *rx_queue;
struct bpf_prog *xdp_prog;
struct xdp_frame *xdpf;
struct xdp_buff xdp;
u32 xdp_act;
s16 offset;
int err;
xdp_prog = rcu_dereference_bh(efx->xdp_prog);
if (!xdp_prog)
return true;
rx_queue = efx_channel_get_rx_queue(channel);
if (unlikely(channel->rx_pkt_n_frags > 1)) {
/* We can't do XDP on fragmented packets - drop. */
efx_free_rx_buffers(rx_queue, rx_buf,
channel->rx_pkt_n_frags);
if (net_ratelimit())
netif_err(efx, rx_err, efx->net_dev,
"XDP is not possible with multiple receive fragments (%d)\n",
channel->rx_pkt_n_frags);
channel->n_rx_xdp_bad_drops++;
return false;
}
dma_sync_single_for_cpu(&efx->pci_dev->dev, rx_buf->dma_addr,
rx_buf->len, DMA_FROM_DEVICE);
/* Save the rx prefix. */
EFX_WARN_ON_PARANOID(efx->rx_prefix_size > EFX_MAX_RX_PREFIX_SIZE);
memcpy(rx_prefix, *ehp - efx->rx_prefix_size,
efx->rx_prefix_size);
xdp_init_buff(&xdp, efx->rx_page_buf_step, &rx_queue->xdp_rxq_info);
/* No support yet for XDP metadata */
xdp_prepare_buff(&xdp, *ehp - EFX_XDP_HEADROOM, EFX_XDP_HEADROOM,
rx_buf->len, false);
xdp_act = bpf_prog_run_xdp(xdp_prog, &xdp);
offset = (u8 *)xdp.data - *ehp;
switch (xdp_act) {
case XDP_PASS:
/* Fix up rx prefix. */
if (offset) {
*ehp += offset;
rx_buf->page_offset += offset;
rx_buf->len -= offset;
memcpy(*ehp - efx->rx_prefix_size, rx_prefix,
efx->rx_prefix_size);
}
break;
case XDP_TX:
/* Buffer ownership passes to tx on success. */
xdpf = xdp_convert_buff_to_frame(&xdp);
err = efx_xdp_tx_buffers(efx, 1, &xdpf, true);
if (unlikely(err != 1)) {
efx_free_rx_buffers(rx_queue, rx_buf, 1);
if (net_ratelimit())
netif_err(efx, rx_err, efx->net_dev,
"XDP TX failed (%d)\n", err);
channel->n_rx_xdp_bad_drops++;
trace_xdp_exception(efx->net_dev, xdp_prog, xdp_act);
} else {
channel->n_rx_xdp_tx++;
}
break;
case XDP_REDIRECT:
err = xdp_do_redirect(efx->net_dev, &xdp, xdp_prog);
if (unlikely(err)) {
efx_free_rx_buffers(rx_queue, rx_buf, 1);
if (net_ratelimit())
netif_err(efx, rx_err, efx->net_dev,
"XDP redirect failed (%d)\n", err);
channel->n_rx_xdp_bad_drops++;
trace_xdp_exception(efx->net_dev, xdp_prog, xdp_act);
} else {
channel->n_rx_xdp_redirect++;
}
break;
default:
bpf_warn_invalid_xdp_action(efx->net_dev, xdp_prog, xdp_act);
efx_free_rx_buffers(rx_queue, rx_buf, 1);
channel->n_rx_xdp_bad_drops++;
trace_xdp_exception(efx->net_dev, xdp_prog, xdp_act);
break;
case XDP_ABORTED:
trace_xdp_exception(efx->net_dev, xdp_prog, xdp_act);
fallthrough;
case XDP_DROP:
efx_free_rx_buffers(rx_queue, rx_buf, 1);
channel->n_rx_xdp_drops++;
break;
}
return xdp_act == XDP_PASS;
}
/* Handle a received packet. Second half: Touches packet payload. */
void __efx_rx_packet(struct efx_channel *channel)
{
struct efx_rx_queue *rx_queue = efx_channel_get_rx_queue(channel);
struct efx_nic *efx = channel->efx;
struct efx_rx_buffer *rx_buf =
efx_rx_buffer(rx_queue, channel->rx_pkt_index);
u8 *eh = efx_rx_buf_va(rx_buf);
/* Read length from the prefix if necessary. This already
* excludes the length of the prefix itself.
*/
if (rx_buf->flags & EFX_RX_PKT_PREFIX_LEN) {
rx_buf->len = le16_to_cpup((__le16 *)
(eh + efx->rx_packet_len_offset));
/* A known issue may prevent this being filled in;
* if that happens, just drop the packet.
* Must do that in the driver since passing a zero-length
* packet up to the stack may cause a crash.
*/
if (unlikely(!rx_buf->len)) {
efx_free_rx_buffers(rx_queue, rx_buf,
channel->rx_pkt_n_frags);
channel->n_rx_frm_trunc++;
goto out;
}
}
/* If we're in loopback test, then pass the packet directly to the
* loopback layer, and free the rx_buf here
*/
if (unlikely(efx->loopback_selftest)) {
efx_loopback_rx_packet(efx, eh, rx_buf->len);
efx_free_rx_buffers(rx_queue, rx_buf,
channel->rx_pkt_n_frags);
goto out;
}
if (!efx_do_xdp(efx, channel, rx_buf, &eh))
goto out;
if (unlikely(!(efx->net_dev->features & NETIF_F_RXCSUM)))
rx_buf->flags &= ~EFX_RX_PKT_CSUMMED;
if ((rx_buf->flags & EFX_RX_PKT_TCP) && !channel->type->receive_skb)
efx_rx_packet_gro(channel, rx_buf, channel->rx_pkt_n_frags, eh, 0);
else
efx_rx_deliver(channel, eh, rx_buf, channel->rx_pkt_n_frags);
out:
channel->rx_pkt_n_frags = 0;
}
|
linux-master
|
drivers/net/ethernet/sfc/rx.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2022 Advanced Micro Devices, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include "tc_counters.h"
#include "tc_encap_actions.h"
#include "mae_counter_format.h"
#include "mae.h"
#include "rx_common.h"
/* Counter-management hashtables */
static const struct rhashtable_params efx_tc_counter_id_ht_params = {
.key_len = offsetof(struct efx_tc_counter_index, linkage),
.key_offset = 0,
.head_offset = offsetof(struct efx_tc_counter_index, linkage),
};
static const struct rhashtable_params efx_tc_counter_ht_params = {
.key_len = offsetof(struct efx_tc_counter, linkage),
.key_offset = 0,
.head_offset = offsetof(struct efx_tc_counter, linkage),
};
static void efx_tc_counter_free(void *ptr, void *__unused)
{
struct efx_tc_counter *cnt = ptr;
WARN_ON(!list_empty(&cnt->users));
/* We'd like to synchronize_rcu() here, but unfortunately we aren't
* removing the element from the hashtable (it's not clear that's a
* safe thing to do in an rhashtable_free_and_destroy free_fn), so
* threads could still be obtaining new pointers to *cnt if they can
* race against this function at all.
*/
flush_work(&cnt->work);
EFX_WARN_ON_PARANOID(spin_is_locked(&cnt->lock));
kfree(cnt);
}
static void efx_tc_counter_id_free(void *ptr, void *__unused)
{
struct efx_tc_counter_index *ctr = ptr;
WARN_ON(refcount_read(&ctr->ref));
kfree(ctr);
}
int efx_tc_init_counters(struct efx_nic *efx)
{
int rc;
rc = rhashtable_init(&efx->tc->counter_id_ht, &efx_tc_counter_id_ht_params);
if (rc < 0)
goto fail_counter_id_ht;
rc = rhashtable_init(&efx->tc->counter_ht, &efx_tc_counter_ht_params);
if (rc < 0)
goto fail_counter_ht;
return 0;
fail_counter_ht:
rhashtable_destroy(&efx->tc->counter_id_ht);
fail_counter_id_ht:
return rc;
}
/* Only call this in init failure teardown.
* Normal exit should fini instead as there may be entries in the table.
*/
void efx_tc_destroy_counters(struct efx_nic *efx)
{
rhashtable_destroy(&efx->tc->counter_ht);
rhashtable_destroy(&efx->tc->counter_id_ht);
}
void efx_tc_fini_counters(struct efx_nic *efx)
{
rhashtable_free_and_destroy(&efx->tc->counter_id_ht, efx_tc_counter_id_free, NULL);
rhashtable_free_and_destroy(&efx->tc->counter_ht, efx_tc_counter_free, NULL);
}
static void efx_tc_counter_work(struct work_struct *work)
{
struct efx_tc_counter *cnt = container_of(work, struct efx_tc_counter, work);
struct efx_tc_encap_action *encap;
struct efx_tc_action_set *act;
unsigned long touched;
struct neighbour *n;
spin_lock_bh(&cnt->lock);
touched = READ_ONCE(cnt->touched);
list_for_each_entry(act, &cnt->users, count_user) {
encap = act->encap_md;
if (!encap)
continue;
if (!encap->neigh) /* can't happen */
continue;
if (time_after_eq(encap->neigh->used, touched))
continue;
encap->neigh->used = touched;
/* We have passed traffic using this ARP entry, so
* indicate to the ARP cache that it's still active
*/
if (encap->neigh->dst_ip)
n = neigh_lookup(&arp_tbl, &encap->neigh->dst_ip,
encap->neigh->egdev);
else
#if IS_ENABLED(CONFIG_IPV6)
n = neigh_lookup(ipv6_stub->nd_tbl,
&encap->neigh->dst_ip6,
encap->neigh->egdev);
#else
n = NULL;
#endif
if (!n)
continue;
neigh_event_send(n, NULL);
neigh_release(n);
}
spin_unlock_bh(&cnt->lock);
}
/* Counter allocation */
struct efx_tc_counter *efx_tc_flower_allocate_counter(struct efx_nic *efx,
int type)
{
struct efx_tc_counter *cnt;
int rc, rc2;
cnt = kzalloc(sizeof(*cnt), GFP_USER);
if (!cnt)
return ERR_PTR(-ENOMEM);
spin_lock_init(&cnt->lock);
INIT_WORK(&cnt->work, efx_tc_counter_work);
cnt->touched = jiffies;
cnt->type = type;
rc = efx_mae_allocate_counter(efx, cnt);
if (rc)
goto fail1;
INIT_LIST_HEAD(&cnt->users);
rc = rhashtable_insert_fast(&efx->tc->counter_ht, &cnt->linkage,
efx_tc_counter_ht_params);
if (rc)
goto fail2;
return cnt;
fail2:
/* If we get here, it implies that we couldn't insert into the table,
* which in turn probably means that the fw_id was already taken.
* In that case, it's unclear whether we really 'own' the fw_id; but
* the firmware seemed to think we did, so it's proper to free it.
*/
rc2 = efx_mae_free_counter(efx, cnt);
if (rc2)
netif_warn(efx, hw, efx->net_dev,
"Failed to free MAE counter %u, rc %d\n",
cnt->fw_id, rc2);
fail1:
kfree(cnt);
return ERR_PTR(rc > 0 ? -EIO : rc);
}
void efx_tc_flower_release_counter(struct efx_nic *efx,
struct efx_tc_counter *cnt)
{
int rc;
rhashtable_remove_fast(&efx->tc->counter_ht, &cnt->linkage,
efx_tc_counter_ht_params);
rc = efx_mae_free_counter(efx, cnt);
if (rc)
netif_warn(efx, hw, efx->net_dev,
"Failed to free MAE counter %u, rc %d\n",
cnt->fw_id, rc);
WARN_ON(!list_empty(&cnt->users));
/* This doesn't protect counter updates coming in arbitrarily long
* after we deleted the counter. The RCU just ensures that we won't
* free the counter while another thread has a pointer to it.
* Ensuring we don't update the wrong counter if the ID gets re-used
* is handled by the generation count.
*/
synchronize_rcu();
flush_work(&cnt->work);
EFX_WARN_ON_PARANOID(spin_is_locked(&cnt->lock));
kfree(cnt);
}
static struct efx_tc_counter *efx_tc_flower_find_counter_by_fw_id(
struct efx_nic *efx, int type, u32 fw_id)
{
struct efx_tc_counter key = {};
key.fw_id = fw_id;
key.type = type;
return rhashtable_lookup_fast(&efx->tc->counter_ht, &key,
efx_tc_counter_ht_params);
}
/* TC cookie to counter mapping */
void efx_tc_flower_put_counter_index(struct efx_nic *efx,
struct efx_tc_counter_index *ctr)
{
if (!refcount_dec_and_test(&ctr->ref))
return; /* still in use */
rhashtable_remove_fast(&efx->tc->counter_id_ht, &ctr->linkage,
efx_tc_counter_id_ht_params);
efx_tc_flower_release_counter(efx, ctr->cnt);
kfree(ctr);
}
struct efx_tc_counter_index *efx_tc_flower_get_counter_index(
struct efx_nic *efx, unsigned long cookie,
enum efx_tc_counter_type type)
{
struct efx_tc_counter_index *ctr, *old;
struct efx_tc_counter *cnt;
ctr = kzalloc(sizeof(*ctr), GFP_USER);
if (!ctr)
return ERR_PTR(-ENOMEM);
ctr->cookie = cookie;
old = rhashtable_lookup_get_insert_fast(&efx->tc->counter_id_ht,
&ctr->linkage,
efx_tc_counter_id_ht_params);
if (old) {
/* don't need our new entry */
kfree(ctr);
if (IS_ERR(old)) /* oh dear, it's actually an error */
return ERR_CAST(old);
if (!refcount_inc_not_zero(&old->ref))
return ERR_PTR(-EAGAIN);
/* existing entry found */
ctr = old;
} else {
cnt = efx_tc_flower_allocate_counter(efx, type);
if (IS_ERR(cnt)) {
rhashtable_remove_fast(&efx->tc->counter_id_ht,
&ctr->linkage,
efx_tc_counter_id_ht_params);
kfree(ctr);
return (void *)cnt; /* it's an ERR_PTR */
}
ctr->cnt = cnt;
refcount_set(&ctr->ref, 1);
}
return ctr;
}
struct efx_tc_counter_index *efx_tc_flower_find_counter_index(
struct efx_nic *efx, unsigned long cookie)
{
struct efx_tc_counter_index key = {};
key.cookie = cookie;
return rhashtable_lookup_fast(&efx->tc->counter_id_ht, &key,
efx_tc_counter_id_ht_params);
}
/* TC Channel. Counter updates are delivered on this channel's RXQ. */
static void efx_tc_handle_no_channel(struct efx_nic *efx)
{
netif_warn(efx, drv, efx->net_dev,
"MAE counters require MSI-X and 1 additional interrupt vector.\n");
}
static int efx_tc_probe_channel(struct efx_channel *channel)
{
struct efx_rx_queue *rx_queue = &channel->rx_queue;
channel->irq_moderation_us = 0;
rx_queue->core_index = 0;
INIT_WORK(&rx_queue->grant_work, efx_mae_counters_grant_credits);
return 0;
}
static int efx_tc_start_channel(struct efx_channel *channel)
{
struct efx_rx_queue *rx_queue = efx_channel_get_rx_queue(channel);
struct efx_nic *efx = channel->efx;
return efx_mae_start_counters(efx, rx_queue);
}
static void efx_tc_stop_channel(struct efx_channel *channel)
{
struct efx_rx_queue *rx_queue = efx_channel_get_rx_queue(channel);
struct efx_nic *efx = channel->efx;
int rc;
rc = efx_mae_stop_counters(efx, rx_queue);
if (rc)
netif_warn(efx, drv, efx->net_dev,
"Failed to stop MAE counters streaming, rc=%d.\n",
rc);
rx_queue->grant_credits = false;
flush_work(&rx_queue->grant_work);
}
static void efx_tc_remove_channel(struct efx_channel *channel)
{
}
static void efx_tc_get_channel_name(struct efx_channel *channel,
char *buf, size_t len)
{
snprintf(buf, len, "%s-mae", channel->efx->name);
}
static void efx_tc_counter_update(struct efx_nic *efx,
enum efx_tc_counter_type counter_type,
u32 counter_idx, u64 packets, u64 bytes,
u32 mark)
{
struct efx_tc_counter *cnt;
rcu_read_lock(); /* Protect against deletion of 'cnt' */
cnt = efx_tc_flower_find_counter_by_fw_id(efx, counter_type, counter_idx);
if (!cnt) {
/* This can legitimately happen when a counter is removed,
* with updates for the counter still in-flight; however this
* should be an infrequent occurrence.
*/
if (net_ratelimit())
netif_dbg(efx, drv, efx->net_dev,
"Got update for unwanted MAE counter %u type %u\n",
counter_idx, counter_type);
goto out;
}
spin_lock_bh(&cnt->lock);
if ((s32)mark - (s32)cnt->gen < 0) {
/* This counter update packet is from before the counter was
* allocated; thus it must be for a previous counter with
* the same ID that has since been freed, and it should be
* ignored.
*/
} else {
/* Update latest seen generation count. This ensures that
* even a long-lived counter won't start getting ignored if
* the generation count wraps around, unless it somehow
* manages to go 1<<31 generations without an update.
*/
cnt->gen = mark;
/* update counter values */
cnt->packets += packets;
cnt->bytes += bytes;
cnt->touched = jiffies;
}
spin_unlock_bh(&cnt->lock);
schedule_work(&cnt->work);
out:
rcu_read_unlock();
}
static void efx_tc_rx_version_1(struct efx_nic *efx, const u8 *data, u32 mark)
{
u16 n_counters, i;
/* Header format:
* + | 0 | 1 | 2 | 3 |
* 0 |version | reserved |
* 4 | seq_index | n_counters |
*/
n_counters = le16_to_cpu(*(const __le16 *)(data + 6));
/* Counter update entry format:
* | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | a | b | c | d | e | f |
* | counter_idx | packet_count | byte_count |
*/
for (i = 0; i < n_counters; i++) {
const void *entry = data + 8 + 16 * i;
u64 packet_count, byte_count;
u32 counter_idx;
counter_idx = le32_to_cpu(*(const __le32 *)entry);
packet_count = le32_to_cpu(*(const __le32 *)(entry + 4)) |
((u64)le16_to_cpu(*(const __le16 *)(entry + 8)) << 32);
byte_count = le16_to_cpu(*(const __le16 *)(entry + 10)) |
((u64)le32_to_cpu(*(const __le32 *)(entry + 12)) << 16);
efx_tc_counter_update(efx, EFX_TC_COUNTER_TYPE_AR, counter_idx,
packet_count, byte_count, mark);
}
}
#define TCV2_HDR_PTR(pkt, field) \
((void)BUILD_BUG_ON_ZERO(ERF_SC_PACKETISER_HEADER_##field##_LBN & 7), \
(pkt) + ERF_SC_PACKETISER_HEADER_##field##_LBN / 8)
#define TCV2_HDR_BYTE(pkt, field) \
((void)BUILD_BUG_ON_ZERO(ERF_SC_PACKETISER_HEADER_##field##_WIDTH != 8),\
*TCV2_HDR_PTR(pkt, field))
#define TCV2_HDR_WORD(pkt, field) \
((void)BUILD_BUG_ON_ZERO(ERF_SC_PACKETISER_HEADER_##field##_WIDTH != 16),\
(void)BUILD_BUG_ON_ZERO(ERF_SC_PACKETISER_HEADER_##field##_LBN & 15), \
*(__force const __le16 *)TCV2_HDR_PTR(pkt, field))
#define TCV2_PKT_PTR(pkt, poff, i, field) \
((void)BUILD_BUG_ON_ZERO(ERF_SC_PACKETISER_PAYLOAD_##field##_LBN & 7), \
(pkt) + ERF_SC_PACKETISER_PAYLOAD_##field##_LBN/8 + poff + \
i * ER_RX_SL_PACKETISER_PAYLOAD_WORD_SIZE)
/* Read a little-endian 48-bit field with 16-bit alignment */
static u64 efx_tc_read48(const __le16 *field)
{
u64 out = 0;
int i;
for (i = 0; i < 3; i++)
out |= (u64)le16_to_cpu(field[i]) << (i * 16);
return out;
}
static enum efx_tc_counter_type efx_tc_rx_version_2(struct efx_nic *efx,
const u8 *data, u32 mark)
{
u8 payload_offset, header_offset, ident;
enum efx_tc_counter_type type;
u16 n_counters, i;
ident = TCV2_HDR_BYTE(data, IDENTIFIER);
switch (ident) {
case ERF_SC_PACKETISER_HEADER_IDENTIFIER_AR:
type = EFX_TC_COUNTER_TYPE_AR;
break;
case ERF_SC_PACKETISER_HEADER_IDENTIFIER_CT:
type = EFX_TC_COUNTER_TYPE_CT;
break;
case ERF_SC_PACKETISER_HEADER_IDENTIFIER_OR:
type = EFX_TC_COUNTER_TYPE_OR;
break;
default:
if (net_ratelimit())
netif_err(efx, drv, efx->net_dev,
"ignored v2 MAE counter packet (bad identifier %u"
"), counters may be inaccurate\n", ident);
return EFX_TC_COUNTER_TYPE_MAX;
}
header_offset = TCV2_HDR_BYTE(data, HEADER_OFFSET);
/* mae_counter_format.h implies that this offset is fixed, since it
* carries on with SOP-based LBNs for the fields in this header
*/
if (header_offset != ERF_SC_PACKETISER_HEADER_HEADER_OFFSET_DEFAULT) {
if (net_ratelimit())
netif_err(efx, drv, efx->net_dev,
"choked on v2 MAE counter packet (bad header_offset %u"
"), counters may be inaccurate\n", header_offset);
return EFX_TC_COUNTER_TYPE_MAX;
}
payload_offset = TCV2_HDR_BYTE(data, PAYLOAD_OFFSET);
n_counters = le16_to_cpu(TCV2_HDR_WORD(data, COUNT));
for (i = 0; i < n_counters; i++) {
const void *counter_idx_p, *packet_count_p, *byte_count_p;
u64 packet_count, byte_count;
u32 counter_idx;
/* 24-bit field with 32-bit alignment */
counter_idx_p = TCV2_PKT_PTR(data, payload_offset, i, COUNTER_INDEX);
BUILD_BUG_ON(ERF_SC_PACKETISER_PAYLOAD_COUNTER_INDEX_WIDTH != 24);
BUILD_BUG_ON(ERF_SC_PACKETISER_PAYLOAD_COUNTER_INDEX_LBN & 31);
counter_idx = le32_to_cpu(*(const __le32 *)counter_idx_p) & 0xffffff;
/* 48-bit field with 16-bit alignment */
packet_count_p = TCV2_PKT_PTR(data, payload_offset, i, PACKET_COUNT);
BUILD_BUG_ON(ERF_SC_PACKETISER_PAYLOAD_PACKET_COUNT_WIDTH != 48);
BUILD_BUG_ON(ERF_SC_PACKETISER_PAYLOAD_PACKET_COUNT_LBN & 15);
packet_count = efx_tc_read48((const __le16 *)packet_count_p);
/* 48-bit field with 16-bit alignment */
byte_count_p = TCV2_PKT_PTR(data, payload_offset, i, BYTE_COUNT);
BUILD_BUG_ON(ERF_SC_PACKETISER_PAYLOAD_BYTE_COUNT_WIDTH != 48);
BUILD_BUG_ON(ERF_SC_PACKETISER_PAYLOAD_BYTE_COUNT_LBN & 15);
byte_count = efx_tc_read48((const __le16 *)byte_count_p);
if (type == EFX_TC_COUNTER_TYPE_CT) {
/* CT counters are 1-bit saturating counters to update
* the lastuse time in CT stats. A received CT counter
* should have packet counter to 0 and only LSB bit on
* in byte counter.
*/
if (packet_count || byte_count != 1)
netdev_warn_once(efx->net_dev,
"CT counter with inconsistent state (%llu, %llu)\n",
packet_count, byte_count);
/* Do not increment the driver's byte counter */
byte_count = 0;
}
efx_tc_counter_update(efx, type, counter_idx, packet_count,
byte_count, mark);
}
return type;
}
/* We always swallow the packet, whether successful or not, since it's not
* a network packet and shouldn't ever be forwarded to the stack.
* @mark is the generation count for counter allocations.
*/
static bool efx_tc_rx(struct efx_rx_queue *rx_queue, u32 mark)
{
struct efx_channel *channel = efx_rx_queue_channel(rx_queue);
struct efx_rx_buffer *rx_buf = efx_rx_buffer(rx_queue,
channel->rx_pkt_index);
const u8 *data = efx_rx_buf_va(rx_buf);
struct efx_nic *efx = rx_queue->efx;
enum efx_tc_counter_type type;
u8 version;
/* version is always first byte of packet */
version = *data;
switch (version) {
case 1:
type = EFX_TC_COUNTER_TYPE_AR;
efx_tc_rx_version_1(efx, data, mark);
break;
case ERF_SC_PACKETISER_HEADER_VERSION_VALUE: // 2
type = efx_tc_rx_version_2(efx, data, mark);
break;
default:
if (net_ratelimit())
netif_err(efx, drv, efx->net_dev,
"choked on MAE counter packet (bad version %u"
"); counters may be inaccurate\n",
version);
goto out;
}
if (type < EFX_TC_COUNTER_TYPE_MAX) {
/* Update seen_gen unconditionally, to avoid a missed wakeup if
* we race with efx_mae_stop_counters().
*/
efx->tc->seen_gen[type] = mark;
if (efx->tc->flush_counters &&
(s32)(efx->tc->flush_gen[type] - mark) <= 0)
wake_up(&efx->tc->flush_wq);
}
out:
efx_free_rx_buffers(rx_queue, rx_buf, 1);
channel->rx_pkt_n_frags = 0;
return true;
}
const struct efx_channel_type efx_tc_channel_type = {
.handle_no_channel = efx_tc_handle_no_channel,
.pre_probe = efx_tc_probe_channel,
.start = efx_tc_start_channel,
.stop = efx_tc_stop_channel,
.post_remove = efx_tc_remove_channel,
.get_name = efx_tc_get_channel_name,
.receive_raw = efx_tc_rx,
.keep_eventq = true,
};
|
linux-master
|
drivers/net/ethernet/sfc/tc_counters.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2018 Solarflare Communications Inc.
* Copyright 2019-2020 Xilinx Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include "net_driver.h"
#include "mcdi_port_common.h"
#include "mcdi_functions.h"
#include "efx_common.h"
#include "efx_channels.h"
#include "tx_common.h"
#include "ef100_netdev.h"
#include "ef100_ethtool.h"
#include "nic_common.h"
#include "ef100_nic.h"
#include "ef100_tx.h"
#include "ef100_regs.h"
#include "mcdi_filters.h"
#include "rx_common.h"
#include "ef100_sriov.h"
#include "tc_bindings.h"
#include "tc_encap_actions.h"
#include "efx_devlink.h"
static void ef100_update_name(struct efx_nic *efx)
{
strcpy(efx->name, efx->net_dev->name);
}
static int ef100_alloc_vis(struct efx_nic *efx, unsigned int *allocated_vis)
{
/* EF100 uses a single TXQ per channel, as all checksum offloading
* is configured in the TX descriptor, and there is no TX Pacer for
* HIGHPRI queues.
*/
unsigned int tx_vis = efx->n_tx_channels + efx->n_extra_tx_channels;
unsigned int rx_vis = efx->n_rx_channels;
unsigned int min_vis, max_vis;
int rc;
EFX_WARN_ON_PARANOID(efx->tx_queues_per_channel != 1);
tx_vis += efx->n_xdp_channels * efx->xdp_tx_per_channel;
max_vis = max(rx_vis, tx_vis);
/* We require at least a single complete TX channel worth of queues. */
min_vis = efx->tx_queues_per_channel;
rc = efx_mcdi_alloc_vis(efx, min_vis, max_vis,
NULL, allocated_vis);
/* We retry allocating VIs by reallocating channels when we have not
* been able to allocate the maximum VIs.
*/
if (!rc && *allocated_vis < max_vis)
rc = -EAGAIN;
return rc;
}
static int ef100_remap_bar(struct efx_nic *efx, int max_vis)
{
unsigned int uc_mem_map_size;
void __iomem *membase;
efx->max_vis = max_vis;
uc_mem_map_size = PAGE_ALIGN(max_vis * efx->vi_stride);
/* Extend the original UC mapping of the memory BAR */
membase = ioremap(efx->membase_phys, uc_mem_map_size);
if (!membase) {
netif_err(efx, probe, efx->net_dev,
"could not extend memory BAR to %x\n",
uc_mem_map_size);
return -ENOMEM;
}
iounmap(efx->membase);
efx->membase = membase;
return 0;
}
/* Context: process, rtnl_lock() held.
* Note that the kernel will ignore our return code; this method
* should really be a void.
*/
static int ef100_net_stop(struct net_device *net_dev)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
netif_dbg(efx, ifdown, efx->net_dev, "closing on CPU %d\n",
raw_smp_processor_id());
efx_detach_reps(efx);
netif_stop_queue(net_dev);
efx_stop_all(efx);
efx_mcdi_mac_fini_stats(efx);
efx_disable_interrupts(efx);
efx_clear_interrupt_affinity(efx);
efx_nic_fini_interrupt(efx);
efx_remove_filters(efx);
efx_fini_napi(efx);
efx_remove_channels(efx);
efx_mcdi_free_vis(efx);
efx_remove_interrupts(efx);
efx->state = STATE_NET_DOWN;
return 0;
}
/* Context: process, rtnl_lock() held. */
static int ef100_net_open(struct net_device *net_dev)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
unsigned int allocated_vis;
int rc;
ef100_update_name(efx);
netif_dbg(efx, ifup, net_dev, "opening device on CPU %d\n",
raw_smp_processor_id());
rc = efx_check_disabled(efx);
if (rc)
goto fail;
rc = efx_probe_interrupts(efx);
if (rc)
goto fail;
rc = efx_set_channels(efx);
if (rc)
goto fail;
rc = efx_mcdi_free_vis(efx);
if (rc)
goto fail;
rc = ef100_alloc_vis(efx, &allocated_vis);
if (rc && rc != -EAGAIN)
goto fail;
/* Try one more time but with the maximum number of channels
* equal to the allocated VIs, which would more likely succeed.
*/
if (rc == -EAGAIN) {
rc = efx_mcdi_free_vis(efx);
if (rc)
goto fail;
efx_remove_interrupts(efx);
efx->max_channels = allocated_vis;
rc = efx_probe_interrupts(efx);
if (rc)
goto fail;
rc = efx_set_channels(efx);
if (rc)
goto fail;
rc = ef100_alloc_vis(efx, &allocated_vis);
if (rc && rc != -EAGAIN)
goto fail;
/* It should be very unlikely that we failed here again, but in
* such a case we return ENOSPC.
*/
if (rc == -EAGAIN) {
rc = -ENOSPC;
goto fail;
}
}
rc = efx_probe_channels(efx);
if (rc)
return rc;
rc = ef100_remap_bar(efx, allocated_vis);
if (rc)
goto fail;
efx_init_napi(efx);
rc = efx_probe_filters(efx);
if (rc)
goto fail;
rc = efx_nic_init_interrupt(efx);
if (rc)
goto fail;
efx_set_interrupt_affinity(efx);
rc = efx_enable_interrupts(efx);
if (rc)
goto fail;
/* in case the MC rebooted while we were stopped, consume the change
* to the warm reboot count
*/
(void) efx_mcdi_poll_reboot(efx);
rc = efx_mcdi_mac_init_stats(efx);
if (rc)
goto fail;
efx_start_all(efx);
/* Link state detection is normally event-driven; we have
* to poll now because we could have missed a change
*/
mutex_lock(&efx->mac_lock);
if (efx_mcdi_phy_poll(efx))
efx_link_status_changed(efx);
mutex_unlock(&efx->mac_lock);
efx->state = STATE_NET_UP;
if (netif_running(efx->net_dev))
efx_attach_reps(efx);
return 0;
fail:
ef100_net_stop(net_dev);
return rc;
}
/* Initiate a packet transmission. We use one channel per CPU
* (sharing when we have more CPUs than channels).
*
* Context: non-blocking.
* Note that returning anything other than NETDEV_TX_OK will cause the
* OS to free the skb.
*/
static netdev_tx_t ef100_hard_start_xmit(struct sk_buff *skb,
struct net_device *net_dev)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
return __ef100_hard_start_xmit(skb, efx, net_dev, NULL);
}
netdev_tx_t __ef100_hard_start_xmit(struct sk_buff *skb,
struct efx_nic *efx,
struct net_device *net_dev,
struct efx_rep *efv)
{
struct efx_tx_queue *tx_queue;
struct efx_channel *channel;
int rc;
channel = efx_get_tx_channel(efx, skb_get_queue_mapping(skb));
netif_vdbg(efx, tx_queued, efx->net_dev,
"%s len %d data %d channel %d\n", __func__,
skb->len, skb->data_len, channel->channel);
if (!efx->n_channels || !efx->n_tx_channels || !channel) {
netif_stop_queue(net_dev);
dev_kfree_skb_any(skb);
goto err;
}
tx_queue = &channel->tx_queue[0];
rc = __ef100_enqueue_skb(tx_queue, skb, efv);
if (rc == 0)
return NETDEV_TX_OK;
err:
net_dev->stats.tx_dropped++;
return NETDEV_TX_OK;
}
static const struct net_device_ops ef100_netdev_ops = {
.ndo_open = ef100_net_open,
.ndo_stop = ef100_net_stop,
.ndo_start_xmit = ef100_hard_start_xmit,
.ndo_tx_timeout = efx_watchdog,
.ndo_get_stats64 = efx_net_stats,
.ndo_change_mtu = efx_change_mtu,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = efx_set_mac_address,
.ndo_set_rx_mode = efx_set_rx_mode, /* Lookout */
.ndo_set_features = efx_set_features,
.ndo_get_phys_port_id = efx_get_phys_port_id,
.ndo_get_phys_port_name = efx_get_phys_port_name,
#ifdef CONFIG_RFS_ACCEL
.ndo_rx_flow_steer = efx_filter_rfs,
#endif
#ifdef CONFIG_SFC_SRIOV
.ndo_setup_tc = efx_tc_setup,
#endif
};
/* Netdev registration
*/
int ef100_netdev_event(struct notifier_block *this,
unsigned long event, void *ptr)
{
struct efx_nic *efx = container_of(this, struct efx_nic, netdev_notifier);
struct net_device *net_dev = netdev_notifier_info_to_dev(ptr);
struct ef100_nic_data *nic_data = efx->nic_data;
int err;
if (efx->net_dev == net_dev &&
(event == NETDEV_CHANGENAME || event == NETDEV_REGISTER))
ef100_update_name(efx);
if (!nic_data->grp_mae)
return NOTIFY_DONE;
err = efx_tc_netdev_event(efx, event, net_dev);
if (err & NOTIFY_STOP_MASK)
return err;
return NOTIFY_DONE;
}
static int ef100_netevent_event(struct notifier_block *this,
unsigned long event, void *ptr)
{
struct efx_nic *efx = container_of(this, struct efx_nic, netevent_notifier);
struct ef100_nic_data *nic_data = efx->nic_data;
int err;
if (!nic_data->grp_mae)
return NOTIFY_DONE;
err = efx_tc_netevent_event(efx, event, ptr);
if (err & NOTIFY_STOP_MASK)
return err;
return NOTIFY_DONE;
};
static int ef100_register_netdev(struct efx_nic *efx)
{
struct net_device *net_dev = efx->net_dev;
int rc;
net_dev->watchdog_timeo = 5 * HZ;
net_dev->irq = efx->pci_dev->irq;
net_dev->netdev_ops = &ef100_netdev_ops;
net_dev->min_mtu = EFX_MIN_MTU;
net_dev->max_mtu = EFX_MAX_MTU;
net_dev->ethtool_ops = &ef100_ethtool_ops;
rtnl_lock();
rc = dev_alloc_name(net_dev, net_dev->name);
if (rc < 0)
goto fail_locked;
ef100_update_name(efx);
rc = register_netdevice(net_dev);
if (rc)
goto fail_locked;
/* Always start with carrier off; PHY events will detect the link */
netif_carrier_off(net_dev);
efx->state = STATE_NET_DOWN;
rtnl_unlock();
efx_init_mcdi_logging(efx);
return 0;
fail_locked:
rtnl_unlock();
netif_err(efx, drv, efx->net_dev, "could not register net dev\n");
return rc;
}
static void ef100_unregister_netdev(struct efx_nic *efx)
{
if (efx_dev_registered(efx)) {
efx_fini_mcdi_logging(efx);
efx->state = STATE_PROBED;
unregister_netdev(efx->net_dev);
}
}
void ef100_remove_netdev(struct efx_probe_data *probe_data)
{
struct efx_nic *efx = &probe_data->efx;
if (!efx->net_dev)
return;
rtnl_lock();
dev_close(efx->net_dev);
rtnl_unlock();
unregister_netdevice_notifier(&efx->netdev_notifier);
unregister_netevent_notifier(&efx->netevent_notifier);
#if defined(CONFIG_SFC_SRIOV)
if (!efx->type->is_vf)
efx_ef100_pci_sriov_disable(efx, true);
#endif
efx_fini_devlink_lock(efx);
ef100_unregister_netdev(efx);
#ifdef CONFIG_SFC_SRIOV
ef100_pf_unset_devlink_port(efx);
efx_fini_tc(efx);
#endif
down_write(&efx->filter_sem);
efx_mcdi_filter_table_remove(efx);
up_write(&efx->filter_sem);
efx_fini_channels(efx);
kfree(efx->phy_data);
efx->phy_data = NULL;
efx_fini_devlink_and_unlock(efx);
free_netdev(efx->net_dev);
efx->net_dev = NULL;
efx->state = STATE_PROBED;
}
int ef100_probe_netdev(struct efx_probe_data *probe_data)
{
struct efx_nic *efx = &probe_data->efx;
struct efx_probe_data **probe_ptr;
struct ef100_nic_data *nic_data;
struct net_device *net_dev;
int rc;
if (efx->mcdi->fn_flags &
(1 << MC_CMD_DRV_ATTACH_EXT_OUT_FLAG_NO_ACTIVE_PORT)) {
pci_info(efx->pci_dev, "No network port on this PCI function");
return 0;
}
/* Allocate and initialise a struct net_device */
net_dev = alloc_etherdev_mq(sizeof(probe_data), EFX_MAX_CORE_TX_QUEUES);
if (!net_dev)
return -ENOMEM;
probe_ptr = netdev_priv(net_dev);
*probe_ptr = probe_data;
efx->net_dev = net_dev;
SET_NETDEV_DEV(net_dev, &efx->pci_dev->dev);
/* enable all supported features except rx-fcs and rx-all */
net_dev->features |= efx->type->offload_features &
~(NETIF_F_RXFCS | NETIF_F_RXALL);
net_dev->hw_features |= efx->type->offload_features;
net_dev->hw_enc_features |= efx->type->offload_features;
net_dev->vlan_features |= NETIF_F_HW_CSUM | NETIF_F_SG |
NETIF_F_HIGHDMA | NETIF_F_ALL_TSO;
netif_set_tso_max_segs(net_dev,
ESE_EF100_DP_GZ_TSO_MAX_HDR_NUM_SEGS_DEFAULT);
efx->mdio.dev = net_dev;
rc = efx_ef100_init_datapath_caps(efx);
if (rc < 0)
goto fail;
rc = ef100_phy_probe(efx);
if (rc)
goto fail;
rc = efx_init_channels(efx);
if (rc)
goto fail;
down_write(&efx->filter_sem);
rc = ef100_filter_table_probe(efx);
up_write(&efx->filter_sem);
if (rc)
goto fail;
netdev_rss_key_fill(efx->rss_context.rx_hash_key,
sizeof(efx->rss_context.rx_hash_key));
/* Don't fail init if RSS setup doesn't work. */
efx_mcdi_push_default_indir_table(efx, efx->n_rx_channels);
nic_data = efx->nic_data;
rc = ef100_get_mac_address(efx, net_dev->perm_addr, CLIENT_HANDLE_SELF,
efx->type->is_vf);
if (rc)
return rc;
/* Assign MAC address */
eth_hw_addr_set(net_dev, net_dev->perm_addr);
ether_addr_copy(nic_data->port_id, net_dev->perm_addr);
/* devlink creation, registration and lock */
rc = efx_probe_devlink_and_lock(efx);
if (rc)
pci_info(efx->pci_dev, "devlink registration failed");
rc = ef100_register_netdev(efx);
if (rc)
goto fail;
if (!efx->type->is_vf) {
rc = ef100_probe_netdev_pf(efx);
if (rc)
goto fail;
#ifdef CONFIG_SFC_SRIOV
ef100_pf_set_devlink_port(efx);
#endif
}
efx->netdev_notifier.notifier_call = ef100_netdev_event;
rc = register_netdevice_notifier(&efx->netdev_notifier);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"Failed to register netdevice notifier, rc=%d\n", rc);
goto fail;
}
efx->netevent_notifier.notifier_call = ef100_netevent_event;
rc = register_netevent_notifier(&efx->netevent_notifier);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"Failed to register netevent notifier, rc=%d\n", rc);
goto fail;
}
efx_probe_devlink_unlock(efx);
return rc;
fail:
#ifdef CONFIG_SFC_SRIOV
/* remove devlink port if does exist */
ef100_pf_unset_devlink_port(efx);
#endif
efx_probe_devlink_unlock(efx);
return rc;
}
|
linux-master
|
drivers/net/ethernet/sfc/ef100_netdev.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2023, Advanced Micro Devices, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include "tc_conntrack.h"
#include "tc.h"
#include "mae.h"
static int efx_tc_flow_block(enum tc_setup_type type, void *type_data,
void *cb_priv);
static const struct rhashtable_params efx_tc_ct_zone_ht_params = {
.key_len = offsetof(struct efx_tc_ct_zone, linkage),
.key_offset = 0,
.head_offset = offsetof(struct efx_tc_ct_zone, linkage),
};
static const struct rhashtable_params efx_tc_ct_ht_params = {
.key_len = offsetof(struct efx_tc_ct_entry, linkage),
.key_offset = 0,
.head_offset = offsetof(struct efx_tc_ct_entry, linkage),
};
static void efx_tc_ct_zone_free(void *ptr, void *arg)
{
struct efx_tc_ct_zone *zone = ptr;
struct efx_nic *efx = zone->efx;
netif_err(efx, drv, efx->net_dev,
"tc ct_zone %u still present at teardown, removing\n",
zone->zone);
nf_flow_table_offload_del_cb(zone->nf_ft, efx_tc_flow_block, zone);
kfree(zone);
}
static void efx_tc_ct_free(void *ptr, void *arg)
{
struct efx_tc_ct_entry *conn = ptr;
struct efx_nic *efx = arg;
netif_err(efx, drv, efx->net_dev,
"tc ct_entry %lx still present at teardown\n",
conn->cookie);
/* We can release the counter, but we can't remove the CT itself
* from hardware because the table meta is already gone.
*/
efx_tc_flower_release_counter(efx, conn->cnt);
kfree(conn);
}
int efx_tc_init_conntrack(struct efx_nic *efx)
{
int rc;
rc = rhashtable_init(&efx->tc->ct_zone_ht, &efx_tc_ct_zone_ht_params);
if (rc < 0)
goto fail_ct_zone_ht;
rc = rhashtable_init(&efx->tc->ct_ht, &efx_tc_ct_ht_params);
if (rc < 0)
goto fail_ct_ht;
return 0;
fail_ct_ht:
rhashtable_destroy(&efx->tc->ct_zone_ht);
fail_ct_zone_ht:
return rc;
}
/* Only call this in init failure teardown.
* Normal exit should fini instead as there may be entries in the table.
*/
void efx_tc_destroy_conntrack(struct efx_nic *efx)
{
rhashtable_destroy(&efx->tc->ct_ht);
rhashtable_destroy(&efx->tc->ct_zone_ht);
}
void efx_tc_fini_conntrack(struct efx_nic *efx)
{
rhashtable_free_and_destroy(&efx->tc->ct_zone_ht, efx_tc_ct_zone_free, NULL);
rhashtable_free_and_destroy(&efx->tc->ct_ht, efx_tc_ct_free, efx);
}
#define EFX_NF_TCP_FLAG(flg) cpu_to_be16(be32_to_cpu(TCP_FLAG_##flg) >> 16)
static int efx_tc_ct_parse_match(struct efx_nic *efx, struct flow_rule *fr,
struct efx_tc_ct_entry *conn)
{
struct flow_dissector *dissector = fr->match.dissector;
unsigned char ipv = 0;
bool tcp = false;
if (flow_rule_match_key(fr, FLOW_DISSECTOR_KEY_CONTROL)) {
struct flow_match_control fm;
flow_rule_match_control(fr, &fm);
if (IS_ALL_ONES(fm.mask->addr_type))
switch (fm.key->addr_type) {
case FLOW_DISSECTOR_KEY_IPV4_ADDRS:
ipv = 4;
break;
case FLOW_DISSECTOR_KEY_IPV6_ADDRS:
ipv = 6;
break;
default:
break;
}
}
if (!ipv) {
netif_dbg(efx, drv, efx->net_dev,
"Conntrack missing ipv specification\n");
return -EOPNOTSUPP;
}
if (dissector->used_keys &
~(BIT_ULL(FLOW_DISSECTOR_KEY_CONTROL) |
BIT_ULL(FLOW_DISSECTOR_KEY_BASIC) |
BIT_ULL(FLOW_DISSECTOR_KEY_IPV4_ADDRS) |
BIT_ULL(FLOW_DISSECTOR_KEY_IPV6_ADDRS) |
BIT_ULL(FLOW_DISSECTOR_KEY_PORTS) |
BIT_ULL(FLOW_DISSECTOR_KEY_TCP) |
BIT_ULL(FLOW_DISSECTOR_KEY_META))) {
netif_dbg(efx, drv, efx->net_dev,
"Unsupported conntrack keys %#llx\n",
dissector->used_keys);
return -EOPNOTSUPP;
}
if (flow_rule_match_key(fr, FLOW_DISSECTOR_KEY_BASIC)) {
struct flow_match_basic fm;
flow_rule_match_basic(fr, &fm);
if (!IS_ALL_ONES(fm.mask->n_proto)) {
netif_dbg(efx, drv, efx->net_dev,
"Conntrack eth_proto is not exact-match; mask %04x\n",
ntohs(fm.mask->n_proto));
return -EOPNOTSUPP;
}
conn->eth_proto = fm.key->n_proto;
if (conn->eth_proto != (ipv == 4 ? htons(ETH_P_IP)
: htons(ETH_P_IPV6))) {
netif_dbg(efx, drv, efx->net_dev,
"Conntrack eth_proto is not IPv%u, is %04x\n",
ipv, ntohs(conn->eth_proto));
return -EOPNOTSUPP;
}
if (!IS_ALL_ONES(fm.mask->ip_proto)) {
netif_dbg(efx, drv, efx->net_dev,
"Conntrack ip_proto is not exact-match; mask %02x\n",
fm.mask->ip_proto);
return -EOPNOTSUPP;
}
conn->ip_proto = fm.key->ip_proto;
switch (conn->ip_proto) {
case IPPROTO_TCP:
tcp = true;
break;
case IPPROTO_UDP:
break;
default:
netif_dbg(efx, drv, efx->net_dev,
"Conntrack ip_proto not TCP or UDP, is %02x\n",
conn->ip_proto);
return -EOPNOTSUPP;
}
} else {
netif_dbg(efx, drv, efx->net_dev,
"Conntrack missing eth_proto, ip_proto\n");
return -EOPNOTSUPP;
}
if (ipv == 4 && flow_rule_match_key(fr, FLOW_DISSECTOR_KEY_IPV4_ADDRS)) {
struct flow_match_ipv4_addrs fm;
flow_rule_match_ipv4_addrs(fr, &fm);
if (!IS_ALL_ONES(fm.mask->src)) {
netif_dbg(efx, drv, efx->net_dev,
"Conntrack ipv4.src is not exact-match; mask %08x\n",
ntohl(fm.mask->src));
return -EOPNOTSUPP;
}
conn->src_ip = fm.key->src;
if (!IS_ALL_ONES(fm.mask->dst)) {
netif_dbg(efx, drv, efx->net_dev,
"Conntrack ipv4.dst is not exact-match; mask %08x\n",
ntohl(fm.mask->dst));
return -EOPNOTSUPP;
}
conn->dst_ip = fm.key->dst;
} else if (ipv == 6 && flow_rule_match_key(fr, FLOW_DISSECTOR_KEY_IPV6_ADDRS)) {
struct flow_match_ipv6_addrs fm;
flow_rule_match_ipv6_addrs(fr, &fm);
if (!efx_ipv6_addr_all_ones(&fm.mask->src)) {
netif_dbg(efx, drv, efx->net_dev,
"Conntrack ipv6.src is not exact-match; mask %pI6\n",
&fm.mask->src);
return -EOPNOTSUPP;
}
conn->src_ip6 = fm.key->src;
if (!efx_ipv6_addr_all_ones(&fm.mask->dst)) {
netif_dbg(efx, drv, efx->net_dev,
"Conntrack ipv6.dst is not exact-match; mask %pI6\n",
&fm.mask->dst);
return -EOPNOTSUPP;
}
conn->dst_ip6 = fm.key->dst;
} else {
netif_dbg(efx, drv, efx->net_dev,
"Conntrack missing IPv%u addrs\n", ipv);
return -EOPNOTSUPP;
}
if (flow_rule_match_key(fr, FLOW_DISSECTOR_KEY_PORTS)) {
struct flow_match_ports fm;
flow_rule_match_ports(fr, &fm);
if (!IS_ALL_ONES(fm.mask->src)) {
netif_dbg(efx, drv, efx->net_dev,
"Conntrack ports.src is not exact-match; mask %04x\n",
ntohs(fm.mask->src));
return -EOPNOTSUPP;
}
conn->l4_sport = fm.key->src;
if (!IS_ALL_ONES(fm.mask->dst)) {
netif_dbg(efx, drv, efx->net_dev,
"Conntrack ports.dst is not exact-match; mask %04x\n",
ntohs(fm.mask->dst));
return -EOPNOTSUPP;
}
conn->l4_dport = fm.key->dst;
} else {
netif_dbg(efx, drv, efx->net_dev, "Conntrack missing L4 ports\n");
return -EOPNOTSUPP;
}
if (flow_rule_match_key(fr, FLOW_DISSECTOR_KEY_TCP)) {
__be16 tcp_interesting_flags;
struct flow_match_tcp fm;
if (!tcp) {
netif_dbg(efx, drv, efx->net_dev,
"Conntrack matching on TCP keys but ipproto is not tcp\n");
return -EOPNOTSUPP;
}
flow_rule_match_tcp(fr, &fm);
tcp_interesting_flags = EFX_NF_TCP_FLAG(SYN) |
EFX_NF_TCP_FLAG(RST) |
EFX_NF_TCP_FLAG(FIN);
/* If any of the tcp_interesting_flags is set, we always
* inhibit CT lookup in LHS (so SW can update CT table).
*/
if (fm.key->flags & tcp_interesting_flags) {
netif_dbg(efx, drv, efx->net_dev,
"Unsupported conntrack tcp.flags %04x/%04x\n",
ntohs(fm.key->flags), ntohs(fm.mask->flags));
return -EOPNOTSUPP;
}
/* Other TCP flags cannot be filtered at CT */
if (fm.mask->flags & ~tcp_interesting_flags) {
netif_dbg(efx, drv, efx->net_dev,
"Unsupported conntrack tcp.flags %04x/%04x\n",
ntohs(fm.key->flags), ntohs(fm.mask->flags));
return -EOPNOTSUPP;
}
}
return 0;
}
static int efx_tc_ct_replace(struct efx_tc_ct_zone *ct_zone,
struct flow_cls_offload *tc)
{
struct flow_rule *fr = flow_cls_offload_flow_rule(tc);
struct efx_tc_ct_entry *conn, *old;
struct efx_nic *efx = ct_zone->efx;
const struct flow_action_entry *fa;
struct efx_tc_counter *cnt;
int rc, i;
if (WARN_ON(!efx->tc))
return -ENETDOWN;
if (WARN_ON(!efx->tc->up))
return -ENETDOWN;
conn = kzalloc(sizeof(*conn), GFP_USER);
if (!conn)
return -ENOMEM;
conn->cookie = tc->cookie;
old = rhashtable_lookup_get_insert_fast(&efx->tc->ct_ht,
&conn->linkage,
efx_tc_ct_ht_params);
if (IS_ERR(old)) {
rc = PTR_ERR(old);
goto release;
} else if (old) {
netif_dbg(efx, drv, efx->net_dev,
"Already offloaded conntrack (cookie %lx)\n", tc->cookie);
rc = -EEXIST;
goto release;
}
/* Parse match */
conn->zone = ct_zone;
rc = efx_tc_ct_parse_match(efx, fr, conn);
if (rc)
goto release;
/* Parse actions */
flow_action_for_each(i, fa, &fr->action) {
switch (fa->id) {
case FLOW_ACTION_CT_METADATA:
conn->mark = fa->ct_metadata.mark;
if (memchr_inv(fa->ct_metadata.labels, 0, sizeof(fa->ct_metadata.labels))) {
netif_dbg(efx, drv, efx->net_dev,
"Setting CT label not supported\n");
rc = -EOPNOTSUPP;
goto release;
}
break;
default:
netif_dbg(efx, drv, efx->net_dev,
"Unhandled action %u for conntrack\n", fa->id);
rc = -EOPNOTSUPP;
goto release;
}
}
/* fill in defaults for unmangled values */
conn->nat_ip = conn->dnat ? conn->dst_ip : conn->src_ip;
conn->l4_natport = conn->dnat ? conn->l4_dport : conn->l4_sport;
cnt = efx_tc_flower_allocate_counter(efx, EFX_TC_COUNTER_TYPE_CT);
if (IS_ERR(cnt)) {
rc = PTR_ERR(cnt);
goto release;
}
conn->cnt = cnt;
rc = efx_mae_insert_ct(efx, conn);
if (rc) {
netif_dbg(efx, drv, efx->net_dev,
"Failed to insert conntrack, %d\n", rc);
goto release;
}
mutex_lock(&ct_zone->mutex);
list_add_tail(&conn->list, &ct_zone->cts);
mutex_unlock(&ct_zone->mutex);
return 0;
release:
if (conn->cnt)
efx_tc_flower_release_counter(efx, conn->cnt);
if (!old)
rhashtable_remove_fast(&efx->tc->ct_ht, &conn->linkage,
efx_tc_ct_ht_params);
kfree(conn);
return rc;
}
/* Caller must follow with efx_tc_ct_remove_finish() after RCU grace period! */
static void efx_tc_ct_remove(struct efx_nic *efx, struct efx_tc_ct_entry *conn)
{
int rc;
/* Remove it from HW */
rc = efx_mae_remove_ct(efx, conn);
/* Delete it from SW */
rhashtable_remove_fast(&efx->tc->ct_ht, &conn->linkage,
efx_tc_ct_ht_params);
if (rc) {
netif_err(efx, drv, efx->net_dev,
"Failed to remove conntrack %lx from hw, rc %d\n",
conn->cookie, rc);
} else {
netif_dbg(efx, drv, efx->net_dev, "Removed conntrack %lx\n",
conn->cookie);
}
}
static void efx_tc_ct_remove_finish(struct efx_nic *efx, struct efx_tc_ct_entry *conn)
{
/* Remove related CT counter. This is delayed after the conn object we
* are working with has been successfully removed. This protects the
* counter from being used-after-free inside efx_tc_ct_stats.
*/
efx_tc_flower_release_counter(efx, conn->cnt);
kfree(conn);
}
static int efx_tc_ct_destroy(struct efx_tc_ct_zone *ct_zone,
struct flow_cls_offload *tc)
{
struct efx_nic *efx = ct_zone->efx;
struct efx_tc_ct_entry *conn;
conn = rhashtable_lookup_fast(&efx->tc->ct_ht, &tc->cookie,
efx_tc_ct_ht_params);
if (!conn) {
netif_warn(efx, drv, efx->net_dev,
"Conntrack %lx not found to remove\n", tc->cookie);
return -ENOENT;
}
mutex_lock(&ct_zone->mutex);
list_del(&conn->list);
efx_tc_ct_remove(efx, conn);
mutex_unlock(&ct_zone->mutex);
synchronize_rcu();
efx_tc_ct_remove_finish(efx, conn);
return 0;
}
static int efx_tc_ct_stats(struct efx_tc_ct_zone *ct_zone,
struct flow_cls_offload *tc)
{
struct efx_nic *efx = ct_zone->efx;
struct efx_tc_ct_entry *conn;
struct efx_tc_counter *cnt;
rcu_read_lock();
conn = rhashtable_lookup_fast(&efx->tc->ct_ht, &tc->cookie,
efx_tc_ct_ht_params);
if (!conn) {
netif_warn(efx, drv, efx->net_dev,
"Conntrack %lx not found for stats\n", tc->cookie);
rcu_read_unlock();
return -ENOENT;
}
cnt = conn->cnt;
spin_lock_bh(&cnt->lock);
/* Report only last use */
flow_stats_update(&tc->stats, 0, 0, 0, cnt->touched,
FLOW_ACTION_HW_STATS_DELAYED);
spin_unlock_bh(&cnt->lock);
rcu_read_unlock();
return 0;
}
static int efx_tc_flow_block(enum tc_setup_type type, void *type_data,
void *cb_priv)
{
struct flow_cls_offload *tcb = type_data;
struct efx_tc_ct_zone *ct_zone = cb_priv;
if (type != TC_SETUP_CLSFLOWER)
return -EOPNOTSUPP;
switch (tcb->command) {
case FLOW_CLS_REPLACE:
return efx_tc_ct_replace(ct_zone, tcb);
case FLOW_CLS_DESTROY:
return efx_tc_ct_destroy(ct_zone, tcb);
case FLOW_CLS_STATS:
return efx_tc_ct_stats(ct_zone, tcb);
default:
break;
}
return -EOPNOTSUPP;
}
struct efx_tc_ct_zone *efx_tc_ct_register_zone(struct efx_nic *efx, u16 zone,
struct nf_flowtable *ct_ft)
{
struct efx_tc_ct_zone *ct_zone, *old;
int rc;
ct_zone = kzalloc(sizeof(*ct_zone), GFP_USER);
if (!ct_zone)
return ERR_PTR(-ENOMEM);
ct_zone->zone = zone;
old = rhashtable_lookup_get_insert_fast(&efx->tc->ct_zone_ht,
&ct_zone->linkage,
efx_tc_ct_zone_ht_params);
if (old) {
/* don't need our new entry */
kfree(ct_zone);
if (IS_ERR(old)) /* oh dear, it's actually an error */
return ERR_CAST(old);
if (!refcount_inc_not_zero(&old->ref))
return ERR_PTR(-EAGAIN);
/* existing entry found */
WARN_ON_ONCE(old->nf_ft != ct_ft);
netif_dbg(efx, drv, efx->net_dev,
"Found existing ct_zone for %u\n", zone);
return old;
}
ct_zone->nf_ft = ct_ft;
ct_zone->efx = efx;
INIT_LIST_HEAD(&ct_zone->cts);
mutex_init(&ct_zone->mutex);
rc = nf_flow_table_offload_add_cb(ct_ft, efx_tc_flow_block, ct_zone);
netif_dbg(efx, drv, efx->net_dev, "Adding new ct_zone for %u, rc %d\n",
zone, rc);
if (rc < 0)
goto fail;
refcount_set(&ct_zone->ref, 1);
return ct_zone;
fail:
rhashtable_remove_fast(&efx->tc->ct_zone_ht, &ct_zone->linkage,
efx_tc_ct_zone_ht_params);
kfree(ct_zone);
return ERR_PTR(rc);
}
void efx_tc_ct_unregister_zone(struct efx_nic *efx,
struct efx_tc_ct_zone *ct_zone)
{
struct efx_tc_ct_entry *conn, *next;
if (!refcount_dec_and_test(&ct_zone->ref))
return; /* still in use */
nf_flow_table_offload_del_cb(ct_zone->nf_ft, efx_tc_flow_block, ct_zone);
rhashtable_remove_fast(&efx->tc->ct_zone_ht, &ct_zone->linkage,
efx_tc_ct_zone_ht_params);
mutex_lock(&ct_zone->mutex);
list_for_each_entry(conn, &ct_zone->cts, list)
efx_tc_ct_remove(efx, conn);
synchronize_rcu();
/* need to use _safe because efx_tc_ct_remove_finish() frees conn */
list_for_each_entry_safe(conn, next, &ct_zone->cts, list)
efx_tc_ct_remove_finish(efx, conn);
mutex_unlock(&ct_zone->mutex);
mutex_destroy(&ct_zone->mutex);
netif_dbg(efx, drv, efx->net_dev, "Removed ct_zone for %u\n",
ct_zone->zone);
kfree(ct_zone);
}
|
linux-master
|
drivers/net/ethernet/sfc/tc_conntrack.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2005-2018 Solarflare Communications Inc.
* Copyright 2019-2022 Xilinx Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include "net_driver.h"
#include <linux/module.h>
#include "efx_common.h"
#include "efx_channels.h"
#include "io.h"
#include "ef100_nic.h"
#include "ef100_netdev.h"
#include "ef100_sriov.h"
#include "ef100_regs.h"
#include "ef100.h"
#define EFX_EF100_PCI_DEFAULT_BAR 2
/* Number of bytes at start of vendor specified extended capability that indicate
* that the capability is vendor specified. i.e. offset from value returned by
* pci_find_next_ext_capability() to beginning of vendor specified capability
* header.
*/
#define PCI_EXT_CAP_HDR_LENGTH 4
/* Expected size of a Xilinx continuation address table entry. */
#define ESE_GZ_CFGBAR_CONT_CAP_MIN_LENGTH 16
struct ef100_func_ctl_window {
bool valid;
unsigned int bar;
u64 offset;
};
static int ef100_pci_walk_xilinx_table(struct efx_nic *efx, u64 offset,
struct ef100_func_ctl_window *result);
/* Number of bytes to offset when reading bit position x with dword accessors. */
#define ROUND_DOWN_TO_DWORD(x) (((x) & (~31)) >> 3)
#define EXTRACT_BITS(x, lbn, width) \
(((x) >> ((lbn) & 31)) & ((1ull << (width)) - 1))
static u32 _ef100_pci_get_bar_bits_with_width(struct efx_nic *efx,
int structure_start,
int lbn, int width)
{
efx_dword_t dword;
efx_readd(efx, &dword, structure_start + ROUND_DOWN_TO_DWORD(lbn));
return EXTRACT_BITS(le32_to_cpu(dword.u32[0]), lbn, width);
}
#define ef100_pci_get_bar_bits(efx, entry_location, bitdef) \
_ef100_pci_get_bar_bits_with_width(efx, entry_location, \
ESF_GZ_CFGBAR_ ## bitdef ## _LBN, \
ESF_GZ_CFGBAR_ ## bitdef ## _WIDTH)
static int ef100_pci_parse_ef100_entry(struct efx_nic *efx, int entry_location,
struct ef100_func_ctl_window *result)
{
u64 offset = ef100_pci_get_bar_bits(efx, entry_location, EF100_FUNC_CTL_WIN_OFF) <<
ESE_GZ_EF100_FUNC_CTL_WIN_OFF_SHIFT;
u32 bar = ef100_pci_get_bar_bits(efx, entry_location, EF100_BAR);
netif_dbg(efx, probe, efx->net_dev,
"Found EF100 function control window bar=%d offset=0x%llx\n",
bar, offset);
if (result->valid) {
netif_err(efx, probe, efx->net_dev,
"Duplicated EF100 table entry.\n");
return -EINVAL;
}
if (bar == ESE_GZ_CFGBAR_EF100_BAR_NUM_EXPANSION_ROM ||
bar == ESE_GZ_CFGBAR_EF100_BAR_NUM_INVALID) {
netif_err(efx, probe, efx->net_dev,
"Bad BAR value of %d in Xilinx capabilities EF100 entry.\n",
bar);
return -EINVAL;
}
result->bar = bar;
result->offset = offset;
result->valid = true;
return 0;
}
static bool ef100_pci_does_bar_overflow(struct efx_nic *efx, int bar,
u64 next_entry)
{
return next_entry + ESE_GZ_CFGBAR_ENTRY_HEADER_SIZE >
pci_resource_len(efx->pci_dev, bar);
}
/* Parse a Xilinx capabilities table entry describing a continuation to a new
* sub-table.
*/
static int ef100_pci_parse_continue_entry(struct efx_nic *efx, int entry_location,
struct ef100_func_ctl_window *result)
{
unsigned int previous_bar;
efx_oword_t entry;
u64 offset;
int rc = 0;
u32 bar;
efx_reado(efx, &entry, entry_location);
bar = EFX_OWORD_FIELD32(entry, ESF_GZ_CFGBAR_CONT_CAP_BAR);
offset = EFX_OWORD_FIELD64(entry, ESF_GZ_CFGBAR_CONT_CAP_OFFSET) <<
ESE_GZ_CONT_CAP_OFFSET_BYTES_SHIFT;
previous_bar = efx->mem_bar;
if (bar == ESE_GZ_VSEC_BAR_NUM_EXPANSION_ROM ||
bar == ESE_GZ_VSEC_BAR_NUM_INVALID) {
netif_err(efx, probe, efx->net_dev,
"Bad BAR value of %d in Xilinx capabilities sub-table.\n",
bar);
return -EINVAL;
}
if (bar != previous_bar) {
efx_fini_io(efx);
if (ef100_pci_does_bar_overflow(efx, bar, offset)) {
netif_err(efx, probe, efx->net_dev,
"Xilinx table will overrun BAR[%d] offset=0x%llx\n",
bar, offset);
return -EINVAL;
}
/* Temporarily map new BAR. */
rc = efx_init_io(efx, bar,
(dma_addr_t)DMA_BIT_MASK(ESF_GZ_TX_SEND_ADDR_WIDTH),
pci_resource_len(efx->pci_dev, bar));
if (rc) {
netif_err(efx, probe, efx->net_dev,
"Mapping new BAR for Xilinx table failed, rc=%d\n", rc);
return rc;
}
}
rc = ef100_pci_walk_xilinx_table(efx, offset, result);
if (rc)
return rc;
if (bar != previous_bar) {
efx_fini_io(efx);
/* Put old BAR back. */
rc = efx_init_io(efx, previous_bar,
(dma_addr_t)DMA_BIT_MASK(ESF_GZ_TX_SEND_ADDR_WIDTH),
pci_resource_len(efx->pci_dev, previous_bar));
if (rc) {
netif_err(efx, probe, efx->net_dev,
"Putting old BAR back failed, rc=%d\n", rc);
return rc;
}
}
return 0;
}
/* Iterate over the Xilinx capabilities table in the currently mapped BAR and
* call ef100_pci_parse_ef100_entry() on any EF100 entries and
* ef100_pci_parse_continue_entry() on any table continuations.
*/
static int ef100_pci_walk_xilinx_table(struct efx_nic *efx, u64 offset,
struct ef100_func_ctl_window *result)
{
u64 current_entry = offset;
int rc = 0;
while (true) {
u32 id = ef100_pci_get_bar_bits(efx, current_entry, ENTRY_FORMAT);
u32 last = ef100_pci_get_bar_bits(efx, current_entry, ENTRY_LAST);
u32 rev = ef100_pci_get_bar_bits(efx, current_entry, ENTRY_REV);
u32 entry_size;
if (id == ESE_GZ_CFGBAR_ENTRY_LAST)
return 0;
entry_size = ef100_pci_get_bar_bits(efx, current_entry, ENTRY_SIZE);
netif_dbg(efx, probe, efx->net_dev,
"Seen Xilinx table entry 0x%x size 0x%x at 0x%llx in BAR[%d]\n",
id, entry_size, current_entry, efx->mem_bar);
if (entry_size < sizeof(u32) * 2) {
netif_err(efx, probe, efx->net_dev,
"Xilinx table entry too short len=0x%x\n", entry_size);
return -EINVAL;
}
switch (id) {
case ESE_GZ_CFGBAR_ENTRY_EF100:
if (rev != ESE_GZ_CFGBAR_ENTRY_REV_EF100 ||
entry_size < ESE_GZ_CFGBAR_ENTRY_SIZE_EF100) {
netif_err(efx, probe, efx->net_dev,
"Bad length or rev for EF100 entry in Xilinx capabilities table. entry_size=%d rev=%d.\n",
entry_size, rev);
return -EINVAL;
}
rc = ef100_pci_parse_ef100_entry(efx, current_entry,
result);
if (rc)
return rc;
break;
case ESE_GZ_CFGBAR_ENTRY_CONT_CAP_ADDR:
if (rev != 0 || entry_size < ESE_GZ_CFGBAR_CONT_CAP_MIN_LENGTH) {
netif_err(efx, probe, efx->net_dev,
"Bad length or rev for continue entry in Xilinx capabilities table. entry_size=%d rev=%d.\n",
entry_size, rev);
return -EINVAL;
}
rc = ef100_pci_parse_continue_entry(efx, current_entry, result);
if (rc)
return rc;
break;
default:
/* Ignore unknown table entries. */
break;
}
if (last)
return 0;
current_entry += entry_size;
if (ef100_pci_does_bar_overflow(efx, efx->mem_bar, current_entry)) {
netif_err(efx, probe, efx->net_dev,
"Xilinx table overrun at position=0x%llx.\n",
current_entry);
return -EINVAL;
}
}
}
static int _ef100_pci_get_config_bits_with_width(struct efx_nic *efx,
int structure_start, int lbn,
int width, u32 *result)
{
int rc, pos = structure_start + ROUND_DOWN_TO_DWORD(lbn);
u32 temp;
rc = pci_read_config_dword(efx->pci_dev, pos, &temp);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"Failed to read PCI config dword at %d\n",
pos);
return rc;
}
*result = EXTRACT_BITS(temp, lbn, width);
return 0;
}
#define ef100_pci_get_config_bits(efx, entry_location, bitdef, result) \
_ef100_pci_get_config_bits_with_width(efx, entry_location, \
ESF_GZ_VSEC_ ## bitdef ## _LBN, \
ESF_GZ_VSEC_ ## bitdef ## _WIDTH, result)
/* Call ef100_pci_walk_xilinx_table() for the Xilinx capabilities table pointed
* to by this PCI_EXT_CAP_ID_VNDR.
*/
static int ef100_pci_parse_xilinx_cap(struct efx_nic *efx, int vndr_cap,
bool has_offset_hi,
struct ef100_func_ctl_window *result)
{
u32 offset_high = 0;
u32 offset_lo = 0;
u64 offset = 0;
u32 bar = 0;
int rc = 0;
rc = ef100_pci_get_config_bits(efx, vndr_cap, TBL_BAR, &bar);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"Failed to read ESF_GZ_VSEC_TBL_BAR, rc=%d\n",
rc);
return rc;
}
if (bar == ESE_GZ_CFGBAR_CONT_CAP_BAR_NUM_EXPANSION_ROM ||
bar == ESE_GZ_CFGBAR_CONT_CAP_BAR_NUM_INVALID) {
netif_err(efx, probe, efx->net_dev,
"Bad BAR value of %d in Xilinx capabilities sub-table.\n",
bar);
return -EINVAL;
}
rc = ef100_pci_get_config_bits(efx, vndr_cap, TBL_OFF_LO, &offset_lo);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"Failed to read ESF_GZ_VSEC_TBL_OFF_LO, rc=%d\n",
rc);
return rc;
}
/* Get optional extension to 64bit offset. */
if (has_offset_hi) {
rc = ef100_pci_get_config_bits(efx, vndr_cap, TBL_OFF_HI, &offset_high);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"Failed to read ESF_GZ_VSEC_TBL_OFF_HI, rc=%d\n",
rc);
return rc;
}
}
offset = (((u64)offset_lo) << ESE_GZ_VSEC_TBL_OFF_LO_BYTES_SHIFT) |
(((u64)offset_high) << ESE_GZ_VSEC_TBL_OFF_HI_BYTES_SHIFT);
if (offset > pci_resource_len(efx->pci_dev, bar) - sizeof(u32) * 2) {
netif_err(efx, probe, efx->net_dev,
"Xilinx table will overrun BAR[%d] offset=0x%llx\n",
bar, offset);
return -EINVAL;
}
/* Temporarily map BAR. */
rc = efx_init_io(efx, bar,
(dma_addr_t)DMA_BIT_MASK(ESF_GZ_TX_SEND_ADDR_WIDTH),
pci_resource_len(efx->pci_dev, bar));
if (rc) {
netif_err(efx, probe, efx->net_dev,
"efx_init_io failed, rc=%d\n", rc);
return rc;
}
rc = ef100_pci_walk_xilinx_table(efx, offset, result);
/* Unmap temporarily mapped BAR. */
efx_fini_io(efx);
return rc;
}
/* Call ef100_pci_parse_ef100_entry() for each Xilinx PCI_EXT_CAP_ID_VNDR
* capability.
*/
static int ef100_pci_find_func_ctrl_window(struct efx_nic *efx,
struct ef100_func_ctl_window *result)
{
int num_xilinx_caps = 0;
int cap = 0;
result->valid = false;
while ((cap = pci_find_next_ext_capability(efx->pci_dev, cap, PCI_EXT_CAP_ID_VNDR)) != 0) {
int vndr_cap = cap + PCI_EXT_CAP_HDR_LENGTH;
u32 vsec_ver = 0;
u32 vsec_len = 0;
u32 vsec_id = 0;
int rc = 0;
num_xilinx_caps++;
rc = ef100_pci_get_config_bits(efx, vndr_cap, ID, &vsec_id);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"Failed to read ESF_GZ_VSEC_ID, rc=%d\n",
rc);
return rc;
}
rc = ef100_pci_get_config_bits(efx, vndr_cap, VER, &vsec_ver);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"Failed to read ESF_GZ_VSEC_VER, rc=%d\n",
rc);
return rc;
}
/* Get length of whole capability - i.e. starting at cap */
rc = ef100_pci_get_config_bits(efx, vndr_cap, LEN, &vsec_len);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"Failed to read ESF_GZ_VSEC_LEN, rc=%d\n",
rc);
return rc;
}
if (vsec_id == ESE_GZ_XILINX_VSEC_ID &&
vsec_ver == ESE_GZ_VSEC_VER_XIL_CFGBAR &&
vsec_len >= ESE_GZ_VSEC_LEN_MIN) {
bool has_offset_hi = (vsec_len >= ESE_GZ_VSEC_LEN_HIGH_OFFT);
rc = ef100_pci_parse_xilinx_cap(efx, vndr_cap,
has_offset_hi, result);
if (rc)
return rc;
}
}
if (num_xilinx_caps && !result->valid) {
netif_err(efx, probe, efx->net_dev,
"Seen %d Xilinx tables, but no EF100 entry.\n",
num_xilinx_caps);
return -EINVAL;
}
return 0;
}
/* Final NIC shutdown
* This is called only at module unload (or hotplug removal). A PF can call
* this on its VFs to ensure they are unbound first.
*/
static void ef100_pci_remove(struct pci_dev *pci_dev)
{
struct efx_nic *efx = pci_get_drvdata(pci_dev);
struct efx_probe_data *probe_data;
if (!efx)
return;
probe_data = container_of(efx, struct efx_probe_data, efx);
ef100_remove_netdev(probe_data);
#ifdef CONFIG_SFC_SRIOV
efx_fini_struct_tc(efx);
#endif
ef100_remove(efx);
efx_fini_io(efx);
pci_dbg(pci_dev, "shutdown successful\n");
pci_set_drvdata(pci_dev, NULL);
efx_fini_struct(efx);
kfree(probe_data);
};
static int ef100_pci_probe(struct pci_dev *pci_dev,
const struct pci_device_id *entry)
{
struct ef100_func_ctl_window fcw = { 0 };
struct efx_probe_data *probe_data;
struct efx_nic *efx;
int rc;
/* Allocate probe data and struct efx_nic */
probe_data = kzalloc(sizeof(*probe_data), GFP_KERNEL);
if (!probe_data)
return -ENOMEM;
probe_data->pci_dev = pci_dev;
efx = &probe_data->efx;
efx->type = (const struct efx_nic_type *)entry->driver_data;
efx->pci_dev = pci_dev;
pci_set_drvdata(pci_dev, efx);
rc = efx_init_struct(efx, pci_dev);
if (rc)
goto fail;
efx->vi_stride = EF100_DEFAULT_VI_STRIDE;
pci_info(pci_dev, "Solarflare EF100 NIC detected\n");
rc = ef100_pci_find_func_ctrl_window(efx, &fcw);
if (rc) {
pci_err(pci_dev,
"Error looking for ef100 function control window, rc=%d\n",
rc);
goto fail;
}
if (!fcw.valid) {
/* Extended capability not found - use defaults. */
fcw.bar = EFX_EF100_PCI_DEFAULT_BAR;
fcw.offset = 0;
fcw.valid = true;
}
if (fcw.offset > pci_resource_len(efx->pci_dev, fcw.bar) - ESE_GZ_FCW_LEN) {
pci_err(pci_dev, "Func control window overruns BAR\n");
rc = -EIO;
goto fail;
}
/* Set up basic I/O (BAR mappings etc) */
rc = efx_init_io(efx, fcw.bar,
(dma_addr_t)DMA_BIT_MASK(ESF_GZ_TX_SEND_ADDR_WIDTH),
pci_resource_len(efx->pci_dev, fcw.bar));
if (rc)
goto fail;
efx->reg_base = fcw.offset;
rc = efx->type->probe(efx);
if (rc)
goto fail;
efx->state = STATE_PROBED;
rc = ef100_probe_netdev(probe_data);
if (rc)
goto fail;
pci_dbg(pci_dev, "initialisation successful\n");
return 0;
fail:
ef100_pci_remove(pci_dev);
return rc;
}
#ifdef CONFIG_SFC_SRIOV
static int ef100_pci_sriov_configure(struct pci_dev *dev, int num_vfs)
{
struct efx_nic *efx = pci_get_drvdata(dev);
int rc;
if (efx->type->sriov_configure) {
rc = efx->type->sriov_configure(efx, num_vfs);
if (rc)
return rc;
else
return num_vfs;
}
return -ENOENT;
}
#endif
/* PCI device ID table */
static const struct pci_device_id ef100_pci_table[] = {
{PCI_DEVICE(PCI_VENDOR_ID_XILINX, 0x0100), /* Riverhead PF */
.driver_data = (unsigned long) &ef100_pf_nic_type },
{PCI_DEVICE(PCI_VENDOR_ID_XILINX, 0x1100), /* Riverhead VF */
.driver_data = (unsigned long) &ef100_vf_nic_type },
{0} /* end of list */
};
struct pci_driver ef100_pci_driver = {
.name = "sfc_ef100",
.id_table = ef100_pci_table,
.probe = ef100_pci_probe,
.remove = ef100_pci_remove,
#ifdef CONFIG_SFC_SRIOV
.sriov_configure = ef100_pci_sriov_configure,
#endif
.err_handler = &efx_err_handlers,
};
MODULE_DEVICE_TABLE(pci, ef100_pci_table);
|
linux-master
|
drivers/net/ethernet/sfc/ef100.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for AMD network controllers and boards
* Copyright (C) 2023, Advanced Micro Devices, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include "net_driver.h"
#include "ef100_nic.h"
#include "efx_devlink.h"
#include <linux/rtc.h>
#include "mcdi.h"
#include "mcdi_functions.h"
#include "mcdi_pcol.h"
#ifdef CONFIG_SFC_SRIOV
#include "mae.h"
#include "ef100_rep.h"
#endif
struct efx_devlink {
struct efx_nic *efx;
};
#ifdef CONFIG_SFC_SRIOV
static int efx_devlink_port_addr_get(struct devlink_port *port, u8 *hw_addr,
int *hw_addr_len,
struct netlink_ext_ack *extack)
{
struct efx_devlink *devlink = devlink_priv(port->devlink);
struct mae_mport_desc *mport_desc;
efx_qword_t pciefn;
u32 client_id;
int rc = 0;
mport_desc = container_of(port, struct mae_mport_desc, dl_port);
if (!ef100_mport_on_local_intf(devlink->efx, mport_desc)) {
rc = -EINVAL;
NL_SET_ERR_MSG_FMT(extack,
"Port not on local interface (mport: %u)",
mport_desc->mport_id);
goto out;
}
if (ef100_mport_is_vf(mport_desc))
EFX_POPULATE_QWORD_3(pciefn,
PCIE_FUNCTION_PF, PCIE_FUNCTION_PF_NULL,
PCIE_FUNCTION_VF, mport_desc->vf_idx,
PCIE_FUNCTION_INTF, PCIE_INTERFACE_CALLER);
else
EFX_POPULATE_QWORD_3(pciefn,
PCIE_FUNCTION_PF, mport_desc->pf_idx,
PCIE_FUNCTION_VF, PCIE_FUNCTION_VF_NULL,
PCIE_FUNCTION_INTF, PCIE_INTERFACE_CALLER);
rc = efx_ef100_lookup_client_id(devlink->efx, pciefn, &client_id);
if (rc) {
NL_SET_ERR_MSG_FMT(extack,
"No internal client_ID for port (mport: %u)",
mport_desc->mport_id);
goto out;
}
rc = ef100_get_mac_address(devlink->efx, hw_addr, client_id, true);
if (rc != 0)
NL_SET_ERR_MSG_FMT(extack,
"No available MAC for port (mport: %u)",
mport_desc->mport_id);
out:
*hw_addr_len = ETH_ALEN;
return rc;
}
static int efx_devlink_port_addr_set(struct devlink_port *port,
const u8 *hw_addr, int hw_addr_len,
struct netlink_ext_ack *extack)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_SET_CLIENT_MAC_ADDRESSES_IN_LEN(1));
struct efx_devlink *devlink = devlink_priv(port->devlink);
struct mae_mport_desc *mport_desc;
efx_qword_t pciefn;
u32 client_id;
int rc;
mport_desc = container_of(port, struct mae_mport_desc, dl_port);
if (!ef100_mport_is_vf(mport_desc)) {
NL_SET_ERR_MSG_FMT(extack,
"port mac change not allowed (mport: %u)",
mport_desc->mport_id);
return -EPERM;
}
EFX_POPULATE_QWORD_3(pciefn,
PCIE_FUNCTION_PF, PCIE_FUNCTION_PF_NULL,
PCIE_FUNCTION_VF, mport_desc->vf_idx,
PCIE_FUNCTION_INTF, PCIE_INTERFACE_CALLER);
rc = efx_ef100_lookup_client_id(devlink->efx, pciefn, &client_id);
if (rc) {
NL_SET_ERR_MSG_FMT(extack,
"No internal client_ID for port (mport: %u)",
mport_desc->mport_id);
return rc;
}
MCDI_SET_DWORD(inbuf, SET_CLIENT_MAC_ADDRESSES_IN_CLIENT_HANDLE,
client_id);
ether_addr_copy(MCDI_PTR(inbuf, SET_CLIENT_MAC_ADDRESSES_IN_MAC_ADDRS),
hw_addr);
rc = efx_mcdi_rpc(devlink->efx, MC_CMD_SET_CLIENT_MAC_ADDRESSES, inbuf,
sizeof(inbuf), NULL, 0, NULL);
if (rc)
NL_SET_ERR_MSG_FMT(extack,
"sfc MC_CMD_SET_CLIENT_MAC_ADDRESSES mcdi error (mport: %u)",
mport_desc->mport_id);
return rc;
}
static const struct devlink_port_ops sfc_devlink_port_ops = {
.port_fn_hw_addr_get = efx_devlink_port_addr_get,
.port_fn_hw_addr_set = efx_devlink_port_addr_set,
};
static void efx_devlink_del_port(struct devlink_port *dl_port)
{
if (!dl_port)
return;
devl_port_unregister(dl_port);
}
static int efx_devlink_add_port(struct efx_nic *efx,
struct mae_mport_desc *mport)
{
bool external = false;
if (!ef100_mport_on_local_intf(efx, mport))
external = true;
switch (mport->mport_type) {
case MAE_MPORT_DESC_MPORT_TYPE_VNIC:
if (mport->vf_idx != MAE_MPORT_DESC_VF_IDX_NULL)
devlink_port_attrs_pci_vf_set(&mport->dl_port, 0, mport->pf_idx,
mport->vf_idx,
external);
else
devlink_port_attrs_pci_pf_set(&mport->dl_port, 0, mport->pf_idx,
external);
break;
default:
/* MAE_MPORT_DESC_MPORT_ALIAS and UNDEFINED */
return 0;
}
mport->dl_port.index = mport->mport_id;
return devl_port_register_with_ops(efx->devlink, &mport->dl_port,
mport->mport_id,
&sfc_devlink_port_ops);
}
#endif
static int efx_devlink_info_nvram_partition(struct efx_nic *efx,
struct devlink_info_req *req,
unsigned int partition_type,
const char *version_name)
{
char buf[EFX_MAX_VERSION_INFO_LEN];
u16 version[4];
int rc;
rc = efx_mcdi_nvram_metadata(efx, partition_type, NULL, version, NULL,
0);
/* If the partition does not exist, that is not an error. */
if (rc == -ENOENT)
return 0;
if (rc) {
netif_err(efx, drv, efx->net_dev, "mcdi nvram %s: failed (rc=%d)\n",
version_name, rc);
return rc;
}
snprintf(buf, EFX_MAX_VERSION_INFO_LEN, "%u.%u.%u.%u", version[0],
version[1], version[2], version[3]);
devlink_info_version_stored_put(req, version_name, buf);
return 0;
}
static int efx_devlink_info_stored_versions(struct efx_nic *efx,
struct devlink_info_req *req)
{
int err;
/* We do not care here about the specific error but just if an error
* happened. The specific error will be reported inside the call
* through system messages, and if any error happened in any call
* below, we report it through extack.
*/
err = efx_devlink_info_nvram_partition(efx, req,
NVRAM_PARTITION_TYPE_BUNDLE,
DEVLINK_INFO_VERSION_GENERIC_FW_BUNDLE_ID);
err |= efx_devlink_info_nvram_partition(efx, req,
NVRAM_PARTITION_TYPE_MC_FIRMWARE,
DEVLINK_INFO_VERSION_GENERIC_FW_MGMT);
err |= efx_devlink_info_nvram_partition(efx, req,
NVRAM_PARTITION_TYPE_SUC_FIRMWARE,
EFX_DEVLINK_INFO_VERSION_FW_MGMT_SUC);
err |= efx_devlink_info_nvram_partition(efx, req,
NVRAM_PARTITION_TYPE_EXPANSION_ROM,
EFX_DEVLINK_INFO_VERSION_FW_EXPROM);
err |= efx_devlink_info_nvram_partition(efx, req,
NVRAM_PARTITION_TYPE_EXPANSION_UEFI,
EFX_DEVLINK_INFO_VERSION_FW_UEFI);
return err;
}
#define EFX_VER_FLAG(_f) \
(MC_CMD_GET_VERSION_V5_OUT_ ## _f ## _PRESENT_LBN)
static void efx_devlink_info_running_v2(struct efx_nic *efx,
struct devlink_info_req *req,
unsigned int flags, efx_dword_t *outbuf)
{
char buf[EFX_MAX_VERSION_INFO_LEN];
union {
const __le32 *dwords;
const __le16 *words;
const char *str;
} ver;
struct rtc_time build_date;
unsigned int build_id;
size_t offset;
__maybe_unused u64 tstamp;
if (flags & BIT(EFX_VER_FLAG(BOARD_EXT_INFO))) {
snprintf(buf, EFX_MAX_VERSION_INFO_LEN, "%s",
MCDI_PTR(outbuf, GET_VERSION_V2_OUT_BOARD_NAME));
devlink_info_version_fixed_put(req,
DEVLINK_INFO_VERSION_GENERIC_BOARD_ID,
buf);
/* Favour full board version if present (in V5 or later) */
if (~flags & BIT(EFX_VER_FLAG(BOARD_VERSION))) {
snprintf(buf, EFX_MAX_VERSION_INFO_LEN, "%u",
MCDI_DWORD(outbuf,
GET_VERSION_V2_OUT_BOARD_REVISION));
devlink_info_version_fixed_put(req,
DEVLINK_INFO_VERSION_GENERIC_BOARD_REV,
buf);
}
ver.str = MCDI_PTR(outbuf, GET_VERSION_V2_OUT_BOARD_SERIAL);
if (ver.str[0])
devlink_info_board_serial_number_put(req, ver.str);
}
if (flags & BIT(EFX_VER_FLAG(FPGA_EXT_INFO))) {
ver.dwords = (__le32 *)MCDI_PTR(outbuf,
GET_VERSION_V2_OUT_FPGA_VERSION);
offset = snprintf(buf, EFX_MAX_VERSION_INFO_LEN, "%u_%c%u",
le32_to_cpu(ver.dwords[0]),
'A' + le32_to_cpu(ver.dwords[1]),
le32_to_cpu(ver.dwords[2]));
ver.str = MCDI_PTR(outbuf, GET_VERSION_V2_OUT_FPGA_EXTRA);
if (ver.str[0])
snprintf(&buf[offset], EFX_MAX_VERSION_INFO_LEN - offset,
" (%s)", ver.str);
devlink_info_version_running_put(req,
EFX_DEVLINK_INFO_VERSION_FPGA_REV,
buf);
}
if (flags & BIT(EFX_VER_FLAG(CMC_EXT_INFO))) {
ver.dwords = (__le32 *)MCDI_PTR(outbuf,
GET_VERSION_V2_OUT_CMCFW_VERSION);
offset = snprintf(buf, EFX_MAX_VERSION_INFO_LEN, "%u.%u.%u.%u",
le32_to_cpu(ver.dwords[0]),
le32_to_cpu(ver.dwords[1]),
le32_to_cpu(ver.dwords[2]),
le32_to_cpu(ver.dwords[3]));
#ifdef CONFIG_RTC_LIB
tstamp = MCDI_QWORD(outbuf,
GET_VERSION_V2_OUT_CMCFW_BUILD_DATE);
if (tstamp) {
rtc_time64_to_tm(tstamp, &build_date);
snprintf(&buf[offset], EFX_MAX_VERSION_INFO_LEN - offset,
" (%ptRd)", &build_date);
}
#endif
devlink_info_version_running_put(req,
EFX_DEVLINK_INFO_VERSION_FW_MGMT_CMC,
buf);
}
ver.words = (__le16 *)MCDI_PTR(outbuf, GET_VERSION_V2_OUT_VERSION);
offset = snprintf(buf, EFX_MAX_VERSION_INFO_LEN, "%u.%u.%u.%u",
le16_to_cpu(ver.words[0]), le16_to_cpu(ver.words[1]),
le16_to_cpu(ver.words[2]), le16_to_cpu(ver.words[3]));
if (flags & BIT(EFX_VER_FLAG(MCFW_EXT_INFO))) {
build_id = MCDI_DWORD(outbuf, GET_VERSION_V2_OUT_MCFW_BUILD_ID);
snprintf(&buf[offset], EFX_MAX_VERSION_INFO_LEN - offset,
" (%x) %s", build_id,
MCDI_PTR(outbuf, GET_VERSION_V2_OUT_MCFW_BUILD_NAME));
}
devlink_info_version_running_put(req,
DEVLINK_INFO_VERSION_GENERIC_FW_MGMT,
buf);
if (flags & BIT(EFX_VER_FLAG(SUCFW_EXT_INFO))) {
ver.dwords = (__le32 *)MCDI_PTR(outbuf,
GET_VERSION_V2_OUT_SUCFW_VERSION);
#ifdef CONFIG_RTC_LIB
tstamp = MCDI_QWORD(outbuf,
GET_VERSION_V2_OUT_SUCFW_BUILD_DATE);
rtc_time64_to_tm(tstamp, &build_date);
#else
memset(&build_date, 0, sizeof(build_date));
#endif
build_id = MCDI_DWORD(outbuf, GET_VERSION_V2_OUT_SUCFW_CHIP_ID);
snprintf(buf, EFX_MAX_VERSION_INFO_LEN,
"%u.%u.%u.%u type %x (%ptRd)",
le32_to_cpu(ver.dwords[0]), le32_to_cpu(ver.dwords[1]),
le32_to_cpu(ver.dwords[2]), le32_to_cpu(ver.dwords[3]),
build_id, &build_date);
devlink_info_version_running_put(req,
EFX_DEVLINK_INFO_VERSION_FW_MGMT_SUC,
buf);
}
}
static void efx_devlink_info_running_v3(struct efx_nic *efx,
struct devlink_info_req *req,
unsigned int flags, efx_dword_t *outbuf)
{
char buf[EFX_MAX_VERSION_INFO_LEN];
union {
const __le32 *dwords;
const __le16 *words;
const char *str;
} ver;
if (flags & BIT(EFX_VER_FLAG(DATAPATH_HW_VERSION))) {
ver.dwords = (__le32 *)MCDI_PTR(outbuf,
GET_VERSION_V3_OUT_DATAPATH_HW_VERSION);
snprintf(buf, EFX_MAX_VERSION_INFO_LEN, "%u.%u.%u",
le32_to_cpu(ver.dwords[0]), le32_to_cpu(ver.dwords[1]),
le32_to_cpu(ver.dwords[2]));
devlink_info_version_running_put(req,
EFX_DEVLINK_INFO_VERSION_DATAPATH_HW,
buf);
}
if (flags & BIT(EFX_VER_FLAG(DATAPATH_FW_VERSION))) {
ver.dwords = (__le32 *)MCDI_PTR(outbuf,
GET_VERSION_V3_OUT_DATAPATH_FW_VERSION);
snprintf(buf, EFX_MAX_VERSION_INFO_LEN, "%u.%u.%u",
le32_to_cpu(ver.dwords[0]), le32_to_cpu(ver.dwords[1]),
le32_to_cpu(ver.dwords[2]));
devlink_info_version_running_put(req,
EFX_DEVLINK_INFO_VERSION_DATAPATH_FW,
buf);
}
}
static void efx_devlink_info_running_v4(struct efx_nic *efx,
struct devlink_info_req *req,
unsigned int flags, efx_dword_t *outbuf)
{
char buf[EFX_MAX_VERSION_INFO_LEN];
union {
const __le32 *dwords;
const __le16 *words;
const char *str;
} ver;
if (flags & BIT(EFX_VER_FLAG(SOC_BOOT_VERSION))) {
ver.dwords = (__le32 *)MCDI_PTR(outbuf,
GET_VERSION_V4_OUT_SOC_BOOT_VERSION);
snprintf(buf, EFX_MAX_VERSION_INFO_LEN, "%u.%u.%u.%u",
le32_to_cpu(ver.dwords[0]), le32_to_cpu(ver.dwords[1]),
le32_to_cpu(ver.dwords[2]),
le32_to_cpu(ver.dwords[3]));
devlink_info_version_running_put(req,
EFX_DEVLINK_INFO_VERSION_SOC_BOOT,
buf);
}
if (flags & BIT(EFX_VER_FLAG(SOC_UBOOT_VERSION))) {
ver.dwords = (__le32 *)MCDI_PTR(outbuf,
GET_VERSION_V4_OUT_SOC_UBOOT_VERSION);
snprintf(buf, EFX_MAX_VERSION_INFO_LEN, "%u.%u.%u.%u",
le32_to_cpu(ver.dwords[0]), le32_to_cpu(ver.dwords[1]),
le32_to_cpu(ver.dwords[2]),
le32_to_cpu(ver.dwords[3]));
devlink_info_version_running_put(req,
EFX_DEVLINK_INFO_VERSION_SOC_UBOOT,
buf);
}
if (flags & BIT(EFX_VER_FLAG(SOC_MAIN_ROOTFS_VERSION))) {
ver.dwords = (__le32 *)MCDI_PTR(outbuf,
GET_VERSION_V4_OUT_SOC_MAIN_ROOTFS_VERSION);
snprintf(buf, EFX_MAX_VERSION_INFO_LEN, "%u.%u.%u.%u",
le32_to_cpu(ver.dwords[0]), le32_to_cpu(ver.dwords[1]),
le32_to_cpu(ver.dwords[2]),
le32_to_cpu(ver.dwords[3]));
devlink_info_version_running_put(req,
EFX_DEVLINK_INFO_VERSION_SOC_MAIN,
buf);
}
if (flags & BIT(EFX_VER_FLAG(SOC_RECOVERY_BUILDROOT_VERSION))) {
ver.dwords = (__le32 *)MCDI_PTR(outbuf,
GET_VERSION_V4_OUT_SOC_RECOVERY_BUILDROOT_VERSION);
snprintf(buf, EFX_MAX_VERSION_INFO_LEN, "%u.%u.%u.%u",
le32_to_cpu(ver.dwords[0]), le32_to_cpu(ver.dwords[1]),
le32_to_cpu(ver.dwords[2]),
le32_to_cpu(ver.dwords[3]));
devlink_info_version_running_put(req,
EFX_DEVLINK_INFO_VERSION_SOC_RECOVERY,
buf);
}
if (flags & BIT(EFX_VER_FLAG(SUCFW_VERSION)) &&
~flags & BIT(EFX_VER_FLAG(SUCFW_EXT_INFO))) {
ver.dwords = (__le32 *)MCDI_PTR(outbuf,
GET_VERSION_V4_OUT_SUCFW_VERSION);
snprintf(buf, EFX_MAX_VERSION_INFO_LEN, "%u.%u.%u.%u",
le32_to_cpu(ver.dwords[0]), le32_to_cpu(ver.dwords[1]),
le32_to_cpu(ver.dwords[2]),
le32_to_cpu(ver.dwords[3]));
devlink_info_version_running_put(req,
EFX_DEVLINK_INFO_VERSION_FW_MGMT_SUC,
buf);
}
}
static void efx_devlink_info_running_v5(struct efx_nic *efx,
struct devlink_info_req *req,
unsigned int flags, efx_dword_t *outbuf)
{
char buf[EFX_MAX_VERSION_INFO_LEN];
union {
const __le32 *dwords;
const __le16 *words;
const char *str;
} ver;
if (flags & BIT(EFX_VER_FLAG(BOARD_VERSION))) {
ver.dwords = (__le32 *)MCDI_PTR(outbuf,
GET_VERSION_V5_OUT_BOARD_VERSION);
snprintf(buf, EFX_MAX_VERSION_INFO_LEN, "%u.%u.%u.%u",
le32_to_cpu(ver.dwords[0]), le32_to_cpu(ver.dwords[1]),
le32_to_cpu(ver.dwords[2]),
le32_to_cpu(ver.dwords[3]));
devlink_info_version_running_put(req,
DEVLINK_INFO_VERSION_GENERIC_BOARD_REV,
buf);
}
if (flags & BIT(EFX_VER_FLAG(BUNDLE_VERSION))) {
ver.dwords = (__le32 *)MCDI_PTR(outbuf,
GET_VERSION_V5_OUT_BUNDLE_VERSION);
snprintf(buf, EFX_MAX_VERSION_INFO_LEN, "%u.%u.%u.%u",
le32_to_cpu(ver.dwords[0]), le32_to_cpu(ver.dwords[1]),
le32_to_cpu(ver.dwords[2]),
le32_to_cpu(ver.dwords[3]));
devlink_info_version_running_put(req,
DEVLINK_INFO_VERSION_GENERIC_FW_BUNDLE_ID,
buf);
}
}
static int efx_devlink_info_running_versions(struct efx_nic *efx,
struct devlink_info_req *req)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_VERSION_V5_OUT_LEN);
MCDI_DECLARE_BUF(inbuf, MC_CMD_GET_VERSION_EXT_IN_LEN);
char buf[EFX_MAX_VERSION_INFO_LEN];
union {
const __le32 *dwords;
const __le16 *words;
const char *str;
} ver;
size_t outlength;
unsigned int flags;
int rc;
rc = efx_mcdi_rpc(efx, MC_CMD_GET_VERSION, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlength);
if (rc || outlength < MC_CMD_GET_VERSION_OUT_LEN) {
netif_err(efx, drv, efx->net_dev,
"mcdi MC_CMD_GET_VERSION failed\n");
return rc;
}
/* Handle previous output */
if (outlength < MC_CMD_GET_VERSION_V2_OUT_LEN) {
ver.words = (__le16 *)MCDI_PTR(outbuf,
GET_VERSION_EXT_OUT_VERSION);
snprintf(buf, EFX_MAX_VERSION_INFO_LEN, "%u.%u.%u.%u",
le16_to_cpu(ver.words[0]),
le16_to_cpu(ver.words[1]),
le16_to_cpu(ver.words[2]),
le16_to_cpu(ver.words[3]));
devlink_info_version_running_put(req,
DEVLINK_INFO_VERSION_GENERIC_FW_MGMT,
buf);
return 0;
}
/* Handle V2 additions */
flags = MCDI_DWORD(outbuf, GET_VERSION_V2_OUT_FLAGS);
efx_devlink_info_running_v2(efx, req, flags, outbuf);
if (outlength < MC_CMD_GET_VERSION_V3_OUT_LEN)
return 0;
/* Handle V3 additions */
efx_devlink_info_running_v3(efx, req, flags, outbuf);
if (outlength < MC_CMD_GET_VERSION_V4_OUT_LEN)
return 0;
/* Handle V4 additions */
efx_devlink_info_running_v4(efx, req, flags, outbuf);
if (outlength < MC_CMD_GET_VERSION_V5_OUT_LEN)
return 0;
/* Handle V5 additions */
efx_devlink_info_running_v5(efx, req, flags, outbuf);
return 0;
}
#define EFX_MAX_SERIALNUM_LEN (ETH_ALEN * 2 + 1)
static int efx_devlink_info_board_cfg(struct efx_nic *efx,
struct devlink_info_req *req)
{
char sn[EFX_MAX_SERIALNUM_LEN];
u8 mac_address[ETH_ALEN];
int rc;
rc = efx_mcdi_get_board_cfg(efx, (u8 *)mac_address, NULL, NULL);
if (!rc) {
snprintf(sn, EFX_MAX_SERIALNUM_LEN, "%pm", mac_address);
devlink_info_serial_number_put(req, sn);
}
return rc;
}
static int efx_devlink_info_get(struct devlink *devlink,
struct devlink_info_req *req,
struct netlink_ext_ack *extack)
{
struct efx_devlink *devlink_private = devlink_priv(devlink);
struct efx_nic *efx = devlink_private->efx;
int err;
/* Several different MCDI commands are used. We report if errors
* happened through extack. Specific error information via system
* messages inside the calls.
*/
err = efx_devlink_info_board_cfg(efx, req);
err |= efx_devlink_info_stored_versions(efx, req);
err |= efx_devlink_info_running_versions(efx, req);
if (err)
NL_SET_ERR_MSG_MOD(extack, "Errors when getting device info. Check system messages");
return 0;
}
static const struct devlink_ops sfc_devlink_ops = {
.info_get = efx_devlink_info_get,
};
#ifdef CONFIG_SFC_SRIOV
static struct devlink_port *ef100_set_devlink_port(struct efx_nic *efx, u32 idx)
{
struct mae_mport_desc *mport;
u32 id;
int rc;
if (!efx->mae)
return NULL;
if (efx_mae_lookup_mport(efx, idx, &id)) {
/* This should not happen. */
if (idx == MAE_MPORT_DESC_VF_IDX_NULL)
pci_warn_once(efx->pci_dev, "No mport ID found for PF.\n");
else
pci_warn_once(efx->pci_dev, "No mport ID found for VF %u.\n",
idx);
return NULL;
}
mport = efx_mae_get_mport(efx, id);
if (!mport) {
/* This should not happen. */
if (idx == MAE_MPORT_DESC_VF_IDX_NULL)
pci_warn_once(efx->pci_dev, "No mport found for PF.\n");
else
pci_warn_once(efx->pci_dev, "No mport found for VF %u.\n",
idx);
return NULL;
}
rc = efx_devlink_add_port(efx, mport);
if (rc) {
if (idx == MAE_MPORT_DESC_VF_IDX_NULL)
pci_warn(efx->pci_dev,
"devlink port creation for PF failed.\n");
else
pci_warn(efx->pci_dev,
"devlink_port creation for VF %u failed.\n",
idx);
return NULL;
}
return &mport->dl_port;
}
void ef100_rep_set_devlink_port(struct efx_rep *efv)
{
efv->dl_port = ef100_set_devlink_port(efv->parent, efv->idx);
}
void ef100_pf_set_devlink_port(struct efx_nic *efx)
{
efx->dl_port = ef100_set_devlink_port(efx, MAE_MPORT_DESC_VF_IDX_NULL);
}
void ef100_rep_unset_devlink_port(struct efx_rep *efv)
{
efx_devlink_del_port(efv->dl_port);
}
void ef100_pf_unset_devlink_port(struct efx_nic *efx)
{
efx_devlink_del_port(efx->dl_port);
}
#endif
void efx_fini_devlink_lock(struct efx_nic *efx)
{
if (efx->devlink)
devl_lock(efx->devlink);
}
void efx_fini_devlink_and_unlock(struct efx_nic *efx)
{
if (efx->devlink) {
devl_unregister(efx->devlink);
devl_unlock(efx->devlink);
devlink_free(efx->devlink);
efx->devlink = NULL;
}
}
int efx_probe_devlink_and_lock(struct efx_nic *efx)
{
struct efx_devlink *devlink_private;
if (efx->type->is_vf)
return 0;
efx->devlink = devlink_alloc(&sfc_devlink_ops,
sizeof(struct efx_devlink),
&efx->pci_dev->dev);
if (!efx->devlink)
return -ENOMEM;
devl_lock(efx->devlink);
devlink_private = devlink_priv(efx->devlink);
devlink_private->efx = efx;
devl_register(efx->devlink);
return 0;
}
void efx_probe_devlink_unlock(struct efx_nic *efx)
{
if (!efx->devlink)
return;
devl_unlock(efx->devlink);
}
|
linux-master
|
drivers/net/ethernet/sfc/efx_devlink.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2018 Solarflare Communications Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include "net_driver.h"
#include "efx.h"
#include "nic_common.h"
#include "tx_common.h"
#include <net/gso.h>
static unsigned int efx_tx_cb_page_count(struct efx_tx_queue *tx_queue)
{
return DIV_ROUND_UP(tx_queue->ptr_mask + 1,
PAGE_SIZE >> EFX_TX_CB_ORDER);
}
int efx_probe_tx_queue(struct efx_tx_queue *tx_queue)
{
struct efx_nic *efx = tx_queue->efx;
unsigned int entries;
int rc;
/* Create the smallest power-of-two aligned ring */
entries = max(roundup_pow_of_two(efx->txq_entries), EFX_MIN_DMAQ_SIZE);
EFX_WARN_ON_PARANOID(entries > EFX_MAX_DMAQ_SIZE);
tx_queue->ptr_mask = entries - 1;
netif_dbg(efx, probe, efx->net_dev,
"creating TX queue %d size %#x mask %#x\n",
tx_queue->queue, efx->txq_entries, tx_queue->ptr_mask);
/* Allocate software ring */
tx_queue->buffer = kcalloc(entries, sizeof(*tx_queue->buffer),
GFP_KERNEL);
if (!tx_queue->buffer)
return -ENOMEM;
tx_queue->cb_page = kcalloc(efx_tx_cb_page_count(tx_queue),
sizeof(tx_queue->cb_page[0]), GFP_KERNEL);
if (!tx_queue->cb_page) {
rc = -ENOMEM;
goto fail1;
}
/* Allocate hardware ring, determine TXQ type */
rc = efx_nic_probe_tx(tx_queue);
if (rc)
goto fail2;
tx_queue->channel->tx_queue_by_type[tx_queue->type] = tx_queue;
return 0;
fail2:
kfree(tx_queue->cb_page);
tx_queue->cb_page = NULL;
fail1:
kfree(tx_queue->buffer);
tx_queue->buffer = NULL;
return rc;
}
void efx_init_tx_queue(struct efx_tx_queue *tx_queue)
{
struct efx_nic *efx = tx_queue->efx;
netif_dbg(efx, drv, efx->net_dev,
"initialising TX queue %d\n", tx_queue->queue);
tx_queue->insert_count = 0;
tx_queue->notify_count = 0;
tx_queue->write_count = 0;
tx_queue->packet_write_count = 0;
tx_queue->old_write_count = 0;
tx_queue->read_count = 0;
tx_queue->old_read_count = 0;
tx_queue->empty_read_count = 0 | EFX_EMPTY_COUNT_VALID;
tx_queue->xmit_pending = false;
tx_queue->timestamping = (efx_ptp_use_mac_tx_timestamps(efx) &&
tx_queue->channel == efx_ptp_channel(efx));
tx_queue->completed_timestamp_major = 0;
tx_queue->completed_timestamp_minor = 0;
tx_queue->xdp_tx = efx_channel_is_xdp_tx(tx_queue->channel);
tx_queue->tso_version = 0;
/* Set up TX descriptor ring */
efx_nic_init_tx(tx_queue);
tx_queue->initialised = true;
}
void efx_fini_tx_queue(struct efx_tx_queue *tx_queue)
{
struct efx_tx_buffer *buffer;
netif_dbg(tx_queue->efx, drv, tx_queue->efx->net_dev,
"shutting down TX queue %d\n", tx_queue->queue);
tx_queue->initialised = false;
if (!tx_queue->buffer)
return;
/* Free any buffers left in the ring */
while (tx_queue->read_count != tx_queue->write_count) {
unsigned int pkts_compl = 0, bytes_compl = 0;
unsigned int efv_pkts_compl = 0;
buffer = &tx_queue->buffer[tx_queue->read_count & tx_queue->ptr_mask];
efx_dequeue_buffer(tx_queue, buffer, &pkts_compl, &bytes_compl,
&efv_pkts_compl);
++tx_queue->read_count;
}
tx_queue->xmit_pending = false;
netdev_tx_reset_queue(tx_queue->core_txq);
}
void efx_remove_tx_queue(struct efx_tx_queue *tx_queue)
{
int i;
if (!tx_queue->buffer)
return;
netif_dbg(tx_queue->efx, drv, tx_queue->efx->net_dev,
"destroying TX queue %d\n", tx_queue->queue);
efx_nic_remove_tx(tx_queue);
if (tx_queue->cb_page) {
for (i = 0; i < efx_tx_cb_page_count(tx_queue); i++)
efx_nic_free_buffer(tx_queue->efx,
&tx_queue->cb_page[i]);
kfree(tx_queue->cb_page);
tx_queue->cb_page = NULL;
}
kfree(tx_queue->buffer);
tx_queue->buffer = NULL;
tx_queue->channel->tx_queue_by_type[tx_queue->type] = NULL;
}
void efx_dequeue_buffer(struct efx_tx_queue *tx_queue,
struct efx_tx_buffer *buffer,
unsigned int *pkts_compl,
unsigned int *bytes_compl,
unsigned int *efv_pkts_compl)
{
if (buffer->unmap_len) {
struct device *dma_dev = &tx_queue->efx->pci_dev->dev;
dma_addr_t unmap_addr = buffer->dma_addr - buffer->dma_offset;
if (buffer->flags & EFX_TX_BUF_MAP_SINGLE)
dma_unmap_single(dma_dev, unmap_addr, buffer->unmap_len,
DMA_TO_DEVICE);
else
dma_unmap_page(dma_dev, unmap_addr, buffer->unmap_len,
DMA_TO_DEVICE);
buffer->unmap_len = 0;
}
if (buffer->flags & EFX_TX_BUF_SKB) {
struct sk_buff *skb = (struct sk_buff *)buffer->skb;
if (unlikely(buffer->flags & EFX_TX_BUF_EFV)) {
EFX_WARN_ON_PARANOID(!efv_pkts_compl);
(*efv_pkts_compl)++;
} else {
EFX_WARN_ON_PARANOID(!pkts_compl || !bytes_compl);
(*pkts_compl)++;
(*bytes_compl) += skb->len;
}
if (tx_queue->timestamping &&
(tx_queue->completed_timestamp_major ||
tx_queue->completed_timestamp_minor)) {
struct skb_shared_hwtstamps hwtstamp;
hwtstamp.hwtstamp =
efx_ptp_nic_to_kernel_time(tx_queue);
skb_tstamp_tx(skb, &hwtstamp);
tx_queue->completed_timestamp_major = 0;
tx_queue->completed_timestamp_minor = 0;
}
dev_consume_skb_any((struct sk_buff *)buffer->skb);
netif_vdbg(tx_queue->efx, tx_done, tx_queue->efx->net_dev,
"TX queue %d transmission id %x complete\n",
tx_queue->queue, tx_queue->read_count);
} else if (buffer->flags & EFX_TX_BUF_XDP) {
xdp_return_frame_rx_napi(buffer->xdpf);
}
buffer->len = 0;
buffer->flags = 0;
}
/* Remove packets from the TX queue
*
* This removes packets from the TX queue, up to and including the
* specified index.
*/
static void efx_dequeue_buffers(struct efx_tx_queue *tx_queue,
unsigned int index,
unsigned int *pkts_compl,
unsigned int *bytes_compl,
unsigned int *efv_pkts_compl)
{
struct efx_nic *efx = tx_queue->efx;
unsigned int stop_index, read_ptr;
stop_index = (index + 1) & tx_queue->ptr_mask;
read_ptr = tx_queue->read_count & tx_queue->ptr_mask;
while (read_ptr != stop_index) {
struct efx_tx_buffer *buffer = &tx_queue->buffer[read_ptr];
if (!efx_tx_buffer_in_use(buffer)) {
netif_err(efx, tx_err, efx->net_dev,
"TX queue %d spurious TX completion id %d\n",
tx_queue->queue, read_ptr);
efx_schedule_reset(efx, RESET_TYPE_TX_SKIP);
return;
}
efx_dequeue_buffer(tx_queue, buffer, pkts_compl, bytes_compl,
efv_pkts_compl);
++tx_queue->read_count;
read_ptr = tx_queue->read_count & tx_queue->ptr_mask;
}
}
void efx_xmit_done_check_empty(struct efx_tx_queue *tx_queue)
{
if ((int)(tx_queue->read_count - tx_queue->old_write_count) >= 0) {
tx_queue->old_write_count = READ_ONCE(tx_queue->write_count);
if (tx_queue->read_count == tx_queue->old_write_count) {
/* Ensure that read_count is flushed. */
smp_mb();
tx_queue->empty_read_count =
tx_queue->read_count | EFX_EMPTY_COUNT_VALID;
}
}
}
int efx_xmit_done(struct efx_tx_queue *tx_queue, unsigned int index)
{
unsigned int fill_level, pkts_compl = 0, bytes_compl = 0;
unsigned int efv_pkts_compl = 0;
struct efx_nic *efx = tx_queue->efx;
EFX_WARN_ON_ONCE_PARANOID(index > tx_queue->ptr_mask);
efx_dequeue_buffers(tx_queue, index, &pkts_compl, &bytes_compl,
&efv_pkts_compl);
tx_queue->pkts_compl += pkts_compl;
tx_queue->bytes_compl += bytes_compl;
if (pkts_compl + efv_pkts_compl > 1)
++tx_queue->merge_events;
/* See if we need to restart the netif queue. This memory
* barrier ensures that we write read_count (inside
* efx_dequeue_buffers()) before reading the queue status.
*/
smp_mb();
if (unlikely(netif_tx_queue_stopped(tx_queue->core_txq)) &&
likely(efx->port_enabled) &&
likely(netif_device_present(efx->net_dev))) {
fill_level = efx_channel_tx_fill_level(tx_queue->channel);
if (fill_level <= efx->txq_wake_thresh)
netif_tx_wake_queue(tx_queue->core_txq);
}
efx_xmit_done_check_empty(tx_queue);
return pkts_compl + efv_pkts_compl;
}
/* Remove buffers put into a tx_queue for the current packet.
* None of the buffers must have an skb attached.
*/
void efx_enqueue_unwind(struct efx_tx_queue *tx_queue,
unsigned int insert_count)
{
unsigned int efv_pkts_compl = 0;
struct efx_tx_buffer *buffer;
unsigned int bytes_compl = 0;
unsigned int pkts_compl = 0;
/* Work backwards until we hit the original insert pointer value */
while (tx_queue->insert_count != insert_count) {
--tx_queue->insert_count;
buffer = __efx_tx_queue_get_insert_buffer(tx_queue);
efx_dequeue_buffer(tx_queue, buffer, &pkts_compl, &bytes_compl,
&efv_pkts_compl);
}
}
struct efx_tx_buffer *efx_tx_map_chunk(struct efx_tx_queue *tx_queue,
dma_addr_t dma_addr, size_t len)
{
const struct efx_nic_type *nic_type = tx_queue->efx->type;
struct efx_tx_buffer *buffer;
unsigned int dma_len;
/* Map the fragment taking account of NIC-dependent DMA limits. */
do {
buffer = efx_tx_queue_get_insert_buffer(tx_queue);
if (nic_type->tx_limit_len)
dma_len = nic_type->tx_limit_len(tx_queue, dma_addr, len);
else
dma_len = len;
buffer->len = dma_len;
buffer->dma_addr = dma_addr;
buffer->flags = EFX_TX_BUF_CONT;
len -= dma_len;
dma_addr += dma_len;
++tx_queue->insert_count;
} while (len);
return buffer;
}
int efx_tx_tso_header_length(struct sk_buff *skb)
{
size_t header_len;
if (skb->encapsulation)
header_len = skb_inner_transport_header(skb) -
skb->data +
(inner_tcp_hdr(skb)->doff << 2u);
else
header_len = skb_transport_header(skb) - skb->data +
(tcp_hdr(skb)->doff << 2u);
return header_len;
}
/* Map all data from an SKB for DMA and create descriptors on the queue. */
int efx_tx_map_data(struct efx_tx_queue *tx_queue, struct sk_buff *skb,
unsigned int segment_count)
{
struct efx_nic *efx = tx_queue->efx;
struct device *dma_dev = &efx->pci_dev->dev;
unsigned int frag_index, nr_frags;
dma_addr_t dma_addr, unmap_addr;
unsigned short dma_flags;
size_t len, unmap_len;
nr_frags = skb_shinfo(skb)->nr_frags;
frag_index = 0;
/* Map header data. */
len = skb_headlen(skb);
dma_addr = dma_map_single(dma_dev, skb->data, len, DMA_TO_DEVICE);
dma_flags = EFX_TX_BUF_MAP_SINGLE;
unmap_len = len;
unmap_addr = dma_addr;
if (unlikely(dma_mapping_error(dma_dev, dma_addr)))
return -EIO;
if (segment_count) {
/* For TSO we need to put the header in to a separate
* descriptor. Map this separately if necessary.
*/
size_t header_len = efx_tx_tso_header_length(skb);
if (header_len != len) {
tx_queue->tso_long_headers++;
efx_tx_map_chunk(tx_queue, dma_addr, header_len);
len -= header_len;
dma_addr += header_len;
}
}
/* Add descriptors for each fragment. */
do {
struct efx_tx_buffer *buffer;
skb_frag_t *fragment;
buffer = efx_tx_map_chunk(tx_queue, dma_addr, len);
/* The final descriptor for a fragment is responsible for
* unmapping the whole fragment.
*/
buffer->flags = EFX_TX_BUF_CONT | dma_flags;
buffer->unmap_len = unmap_len;
buffer->dma_offset = buffer->dma_addr - unmap_addr;
if (frag_index >= nr_frags) {
/* Store SKB details with the final buffer for
* the completion.
*/
buffer->skb = skb;
buffer->flags = EFX_TX_BUF_SKB | dma_flags;
return 0;
}
/* Move on to the next fragment. */
fragment = &skb_shinfo(skb)->frags[frag_index++];
len = skb_frag_size(fragment);
dma_addr = skb_frag_dma_map(dma_dev, fragment, 0, len,
DMA_TO_DEVICE);
dma_flags = 0;
unmap_len = len;
unmap_addr = dma_addr;
if (unlikely(dma_mapping_error(dma_dev, dma_addr)))
return -EIO;
} while (1);
}
unsigned int efx_tx_max_skb_descs(struct efx_nic *efx)
{
/* Header and payload descriptor for each output segment, plus
* one for every input fragment boundary within a segment
*/
unsigned int max_descs = EFX_TSO_MAX_SEGS * 2 + MAX_SKB_FRAGS;
/* Possibly one more per segment for option descriptors */
if (efx_nic_rev(efx) >= EFX_REV_HUNT_A0)
max_descs += EFX_TSO_MAX_SEGS;
/* Possibly more for PCIe page boundaries within input fragments */
if (PAGE_SIZE > EFX_PAGE_SIZE)
max_descs += max_t(unsigned int, MAX_SKB_FRAGS,
DIV_ROUND_UP(GSO_LEGACY_MAX_SIZE,
EFX_PAGE_SIZE));
return max_descs;
}
/*
* Fallback to software TSO.
*
* This is used if we are unable to send a GSO packet through hardware TSO.
* This should only ever happen due to per-queue restrictions - unsupported
* packets should first be filtered by the feature flags.
*
* Returns 0 on success, error code otherwise.
*/
int efx_tx_tso_fallback(struct efx_tx_queue *tx_queue, struct sk_buff *skb)
{
struct sk_buff *segments, *next;
segments = skb_gso_segment(skb, 0);
if (IS_ERR(segments))
return PTR_ERR(segments);
dev_consume_skb_any(skb);
skb_list_walk_safe(segments, skb, next) {
skb_mark_not_on_list(skb);
efx_enqueue_skb(tx_queue, skb);
}
return 0;
}
|
linux-master
|
drivers/net/ethernet/sfc/tx_common.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2009-2013 Solarflare Communications Inc.
*/
/*
* Driver for PHY related operations via MCDI.
*/
#include <linux/slab.h>
#include "efx.h"
#include "mcdi_port.h"
#include "mcdi.h"
#include "mcdi_pcol.h"
#include "nic.h"
#include "selftest.h"
#include "mcdi_port_common.h"
static int efx_mcdi_mdio_read(struct net_device *net_dev,
int prtad, int devad, u16 addr)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
MCDI_DECLARE_BUF(inbuf, MC_CMD_MDIO_READ_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_MDIO_READ_OUT_LEN);
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, MDIO_READ_IN_BUS, efx->mdio_bus);
MCDI_SET_DWORD(inbuf, MDIO_READ_IN_PRTAD, prtad);
MCDI_SET_DWORD(inbuf, MDIO_READ_IN_DEVAD, devad);
MCDI_SET_DWORD(inbuf, MDIO_READ_IN_ADDR, addr);
rc = efx_mcdi_rpc(efx, MC_CMD_MDIO_READ, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (MCDI_DWORD(outbuf, MDIO_READ_OUT_STATUS) !=
MC_CMD_MDIO_STATUS_GOOD)
return -EIO;
return (u16)MCDI_DWORD(outbuf, MDIO_READ_OUT_VALUE);
}
static int efx_mcdi_mdio_write(struct net_device *net_dev,
int prtad, int devad, u16 addr, u16 value)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
MCDI_DECLARE_BUF(inbuf, MC_CMD_MDIO_WRITE_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_MDIO_WRITE_OUT_LEN);
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, MDIO_WRITE_IN_BUS, efx->mdio_bus);
MCDI_SET_DWORD(inbuf, MDIO_WRITE_IN_PRTAD, prtad);
MCDI_SET_DWORD(inbuf, MDIO_WRITE_IN_DEVAD, devad);
MCDI_SET_DWORD(inbuf, MDIO_WRITE_IN_ADDR, addr);
MCDI_SET_DWORD(inbuf, MDIO_WRITE_IN_VALUE, value);
rc = efx_mcdi_rpc(efx, MC_CMD_MDIO_WRITE, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (MCDI_DWORD(outbuf, MDIO_WRITE_OUT_STATUS) !=
MC_CMD_MDIO_STATUS_GOOD)
return -EIO;
return 0;
}
u32 efx_mcdi_phy_get_caps(struct efx_nic *efx)
{
struct efx_mcdi_phy_data *phy_data = efx->phy_data;
return phy_data->supported_cap;
}
bool efx_mcdi_mac_check_fault(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_LINK_OUT_LEN);
size_t outlength;
int rc;
BUILD_BUG_ON(MC_CMD_GET_LINK_IN_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_GET_LINK, NULL, 0,
outbuf, sizeof(outbuf), &outlength);
if (rc)
return true;
return MCDI_DWORD(outbuf, GET_LINK_OUT_MAC_FAULT) != 0;
}
int efx_mcdi_port_probe(struct efx_nic *efx)
{
int rc;
/* Set up MDIO structure for PHY */
efx->mdio.mode_support = MDIO_SUPPORTS_C45 | MDIO_EMULATE_C22;
efx->mdio.mdio_read = efx_mcdi_mdio_read;
efx->mdio.mdio_write = efx_mcdi_mdio_write;
/* Fill out MDIO structure, loopback modes, and initial link state */
rc = efx_mcdi_phy_probe(efx);
if (rc != 0)
return rc;
return efx_mcdi_mac_init_stats(efx);
}
void efx_mcdi_port_remove(struct efx_nic *efx)
{
efx_mcdi_phy_remove(efx);
efx_mcdi_mac_fini_stats(efx);
}
|
linux-master
|
drivers/net/ethernet/sfc/mcdi_port.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2019 Solarflare Communications Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include "net_driver.h"
#include "efx.h"
#include "nic.h"
#include "mcdi_functions.h"
#include "mcdi.h"
#include "mcdi_pcol.h"
int efx_mcdi_free_vis(struct efx_nic *efx)
{
MCDI_DECLARE_BUF_ERR(outbuf);
size_t outlen;
int rc = efx_mcdi_rpc_quiet(efx, MC_CMD_FREE_VIS, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
/* -EALREADY means nothing to free, so ignore */
if (rc == -EALREADY)
rc = 0;
if (rc)
efx_mcdi_display_error(efx, MC_CMD_FREE_VIS, 0, outbuf, outlen,
rc);
return rc;
}
int efx_mcdi_alloc_vis(struct efx_nic *efx, unsigned int min_vis,
unsigned int max_vis, unsigned int *vi_base,
unsigned int *allocated_vis)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_ALLOC_VIS_OUT_LEN);
MCDI_DECLARE_BUF(inbuf, MC_CMD_ALLOC_VIS_IN_LEN);
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, ALLOC_VIS_IN_MIN_VI_COUNT, min_vis);
MCDI_SET_DWORD(inbuf, ALLOC_VIS_IN_MAX_VI_COUNT, max_vis);
rc = efx_mcdi_rpc(efx, MC_CMD_ALLOC_VIS, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc != 0)
return rc;
if (outlen < MC_CMD_ALLOC_VIS_OUT_LEN)
return -EIO;
netif_dbg(efx, drv, efx->net_dev, "base VI is A0x%03x\n",
MCDI_DWORD(outbuf, ALLOC_VIS_OUT_VI_BASE));
if (vi_base)
*vi_base = MCDI_DWORD(outbuf, ALLOC_VIS_OUT_VI_BASE);
if (allocated_vis)
*allocated_vis = MCDI_DWORD(outbuf, ALLOC_VIS_OUT_VI_COUNT);
return 0;
}
int efx_mcdi_ev_probe(struct efx_channel *channel)
{
return efx_nic_alloc_buffer(channel->efx, &channel->eventq,
(channel->eventq_mask + 1) *
sizeof(efx_qword_t),
GFP_KERNEL);
}
int efx_mcdi_ev_init(struct efx_channel *channel, bool v1_cut_thru, bool v2)
{
MCDI_DECLARE_BUF(inbuf,
MC_CMD_INIT_EVQ_V2_IN_LEN(EFX_MAX_EVQ_SIZE * 8 /
EFX_BUF_SIZE));
MCDI_DECLARE_BUF(outbuf, MC_CMD_INIT_EVQ_V2_OUT_LEN);
size_t entries = channel->eventq.len / EFX_BUF_SIZE;
struct efx_nic *efx = channel->efx;
size_t inlen, outlen;
dma_addr_t dma_addr;
int rc, i;
/* Fill event queue with all ones (i.e. empty events) */
memset(channel->eventq.addr, 0xff, channel->eventq.len);
MCDI_SET_DWORD(inbuf, INIT_EVQ_IN_SIZE, channel->eventq_mask + 1);
MCDI_SET_DWORD(inbuf, INIT_EVQ_IN_INSTANCE, channel->channel);
/* INIT_EVQ expects index in vector table, not absolute */
MCDI_SET_DWORD(inbuf, INIT_EVQ_IN_IRQ_NUM, channel->channel);
MCDI_SET_DWORD(inbuf, INIT_EVQ_IN_TMR_MODE,
MC_CMD_INIT_EVQ_IN_TMR_MODE_DIS);
MCDI_SET_DWORD(inbuf, INIT_EVQ_IN_TMR_LOAD, 0);
MCDI_SET_DWORD(inbuf, INIT_EVQ_IN_TMR_RELOAD, 0);
MCDI_SET_DWORD(inbuf, INIT_EVQ_IN_COUNT_MODE,
MC_CMD_INIT_EVQ_IN_COUNT_MODE_DIS);
MCDI_SET_DWORD(inbuf, INIT_EVQ_IN_COUNT_THRSHLD, 0);
if (v2) {
/* Use the new generic approach to specifying event queue
* configuration, requesting lower latency or higher throughput.
* The options that actually get used appear in the output.
*/
MCDI_POPULATE_DWORD_2(inbuf, INIT_EVQ_V2_IN_FLAGS,
INIT_EVQ_V2_IN_FLAG_INTERRUPTING, 1,
INIT_EVQ_V2_IN_FLAG_TYPE,
MC_CMD_INIT_EVQ_V2_IN_FLAG_TYPE_AUTO);
} else {
MCDI_POPULATE_DWORD_4(inbuf, INIT_EVQ_IN_FLAGS,
INIT_EVQ_IN_FLAG_INTERRUPTING, 1,
INIT_EVQ_IN_FLAG_RX_MERGE, 1,
INIT_EVQ_IN_FLAG_TX_MERGE, 1,
INIT_EVQ_IN_FLAG_CUT_THRU, v1_cut_thru);
}
dma_addr = channel->eventq.dma_addr;
for (i = 0; i < entries; ++i) {
MCDI_SET_ARRAY_QWORD(inbuf, INIT_EVQ_IN_DMA_ADDR, i, dma_addr);
dma_addr += EFX_BUF_SIZE;
}
inlen = MC_CMD_INIT_EVQ_IN_LEN(entries);
rc = efx_mcdi_rpc(efx, MC_CMD_INIT_EVQ, inbuf, inlen,
outbuf, sizeof(outbuf), &outlen);
if (outlen >= MC_CMD_INIT_EVQ_V2_OUT_LEN)
netif_dbg(efx, drv, efx->net_dev,
"Channel %d using event queue flags %08x\n",
channel->channel,
MCDI_DWORD(outbuf, INIT_EVQ_V2_OUT_FLAGS));
return rc;
}
void efx_mcdi_ev_remove(struct efx_channel *channel)
{
efx_nic_free_buffer(channel->efx, &channel->eventq);
}
void efx_mcdi_ev_fini(struct efx_channel *channel)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_FINI_EVQ_IN_LEN);
MCDI_DECLARE_BUF_ERR(outbuf);
struct efx_nic *efx = channel->efx;
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, FINI_EVQ_IN_INSTANCE, channel->channel);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_FINI_EVQ, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc && rc != -EALREADY)
goto fail;
return;
fail:
efx_mcdi_display_error(efx, MC_CMD_FINI_EVQ, MC_CMD_FINI_EVQ_IN_LEN,
outbuf, outlen, rc);
}
int efx_mcdi_tx_init(struct efx_tx_queue *tx_queue)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_INIT_TXQ_IN_LEN(EFX_MAX_DMAQ_SIZE * 8 /
EFX_BUF_SIZE));
bool csum_offload = tx_queue->type & EFX_TXQ_TYPE_OUTER_CSUM;
bool inner_csum = tx_queue->type & EFX_TXQ_TYPE_INNER_CSUM;
size_t entries = tx_queue->txd.len / EFX_BUF_SIZE;
struct efx_channel *channel = tx_queue->channel;
struct efx_nic *efx = tx_queue->efx;
dma_addr_t dma_addr;
size_t inlen;
int rc, i;
BUILD_BUG_ON(MC_CMD_INIT_TXQ_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, INIT_TXQ_IN_SIZE, tx_queue->ptr_mask + 1);
MCDI_SET_DWORD(inbuf, INIT_TXQ_IN_TARGET_EVQ, channel->channel);
MCDI_SET_DWORD(inbuf, INIT_TXQ_IN_LABEL, tx_queue->label);
MCDI_SET_DWORD(inbuf, INIT_TXQ_IN_INSTANCE, tx_queue->queue);
MCDI_SET_DWORD(inbuf, INIT_TXQ_IN_OWNER_ID, 0);
MCDI_SET_DWORD(inbuf, INIT_TXQ_IN_PORT_ID, efx->vport_id);
dma_addr = tx_queue->txd.dma_addr;
netif_dbg(efx, hw, efx->net_dev, "pushing TXQ %d. %zu entries (%llx)\n",
tx_queue->queue, entries, (u64)dma_addr);
for (i = 0; i < entries; ++i) {
MCDI_SET_ARRAY_QWORD(inbuf, INIT_TXQ_IN_DMA_ADDR, i, dma_addr);
dma_addr += EFX_BUF_SIZE;
}
inlen = MC_CMD_INIT_TXQ_IN_LEN(entries);
do {
bool tso_v2 = tx_queue->tso_version == 2;
/* TSOv2 implies IP header checksum offload for TSO frames,
* so we can safely disable IP header checksum offload for
* everything else. If we don't have TSOv2, then we have to
* enable IP header checksum offload, which is strictly
* incorrect but better than breaking TSO.
*/
MCDI_POPULATE_DWORD_6(inbuf, INIT_TXQ_IN_FLAGS,
/* This flag was removed from mcdi_pcol.h for
* the non-_EXT version of INIT_TXQ. However,
* firmware still honours it.
*/
INIT_TXQ_EXT_IN_FLAG_TSOV2_EN, tso_v2,
INIT_TXQ_IN_FLAG_IP_CSUM_DIS, !(csum_offload && tso_v2),
INIT_TXQ_IN_FLAG_TCP_CSUM_DIS, !csum_offload,
INIT_TXQ_EXT_IN_FLAG_TIMESTAMP, tx_queue->timestamping,
INIT_TXQ_IN_FLAG_INNER_IP_CSUM_EN, inner_csum && !tso_v2,
INIT_TXQ_IN_FLAG_INNER_TCP_CSUM_EN, inner_csum);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_INIT_TXQ, inbuf, inlen,
NULL, 0, NULL);
if (rc == -ENOSPC && tso_v2) {
/* Retry without TSOv2 if we're short on contexts. */
tx_queue->tso_version = 0;
netif_warn(efx, probe, efx->net_dev,
"TSOv2 context not available to segment in "
"hardware. TCP performance may be reduced.\n"
);
} else if (rc) {
efx_mcdi_display_error(efx, MC_CMD_INIT_TXQ,
MC_CMD_INIT_TXQ_EXT_IN_LEN,
NULL, 0, rc);
goto fail;
}
} while (rc);
return 0;
fail:
return rc;
}
void efx_mcdi_tx_remove(struct efx_tx_queue *tx_queue)
{
efx_nic_free_buffer(tx_queue->efx, &tx_queue->txd);
}
void efx_mcdi_tx_fini(struct efx_tx_queue *tx_queue)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_FINI_TXQ_IN_LEN);
MCDI_DECLARE_BUF_ERR(outbuf);
struct efx_nic *efx = tx_queue->efx;
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, FINI_TXQ_IN_INSTANCE,
tx_queue->queue);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_FINI_TXQ, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc && rc != -EALREADY)
goto fail;
return;
fail:
efx_mcdi_display_error(efx, MC_CMD_FINI_TXQ, MC_CMD_FINI_TXQ_IN_LEN,
outbuf, outlen, rc);
}
int efx_mcdi_rx_probe(struct efx_rx_queue *rx_queue)
{
return efx_nic_alloc_buffer(rx_queue->efx, &rx_queue->rxd,
(rx_queue->ptr_mask + 1) *
sizeof(efx_qword_t),
GFP_KERNEL);
}
void efx_mcdi_rx_init(struct efx_rx_queue *rx_queue)
{
struct efx_channel *channel = efx_rx_queue_channel(rx_queue);
size_t entries = rx_queue->rxd.len / EFX_BUF_SIZE;
MCDI_DECLARE_BUF(inbuf, MC_CMD_INIT_RXQ_V4_IN_LEN);
struct efx_nic *efx = rx_queue->efx;
unsigned int buffer_size;
dma_addr_t dma_addr;
int rc;
int i;
BUILD_BUG_ON(MC_CMD_INIT_RXQ_OUT_LEN != 0);
rx_queue->scatter_n = 0;
rx_queue->scatter_len = 0;
if (efx->type->revision == EFX_REV_EF100)
buffer_size = efx->rx_page_buf_step;
else
buffer_size = 0;
MCDI_SET_DWORD(inbuf, INIT_RXQ_IN_SIZE, rx_queue->ptr_mask + 1);
MCDI_SET_DWORD(inbuf, INIT_RXQ_IN_TARGET_EVQ, channel->channel);
MCDI_SET_DWORD(inbuf, INIT_RXQ_IN_LABEL, efx_rx_queue_index(rx_queue));
MCDI_SET_DWORD(inbuf, INIT_RXQ_IN_INSTANCE,
efx_rx_queue_index(rx_queue));
MCDI_POPULATE_DWORD_2(inbuf, INIT_RXQ_IN_FLAGS,
INIT_RXQ_IN_FLAG_PREFIX, 1,
INIT_RXQ_IN_FLAG_TIMESTAMP, 1);
MCDI_SET_DWORD(inbuf, INIT_RXQ_IN_OWNER_ID, 0);
MCDI_SET_DWORD(inbuf, INIT_RXQ_IN_PORT_ID, efx->vport_id);
MCDI_SET_DWORD(inbuf, INIT_RXQ_V4_IN_BUFFER_SIZE_BYTES, buffer_size);
dma_addr = rx_queue->rxd.dma_addr;
netif_dbg(efx, hw, efx->net_dev, "pushing RXQ %d. %zu entries (%llx)\n",
efx_rx_queue_index(rx_queue), entries, (u64)dma_addr);
for (i = 0; i < entries; ++i) {
MCDI_SET_ARRAY_QWORD(inbuf, INIT_RXQ_IN_DMA_ADDR, i, dma_addr);
dma_addr += EFX_BUF_SIZE;
}
rc = efx_mcdi_rpc(efx, MC_CMD_INIT_RXQ, inbuf, sizeof(inbuf),
NULL, 0, NULL);
if (rc)
netdev_WARN(efx->net_dev, "failed to initialise RXQ %d\n",
efx_rx_queue_index(rx_queue));
}
void efx_mcdi_rx_remove(struct efx_rx_queue *rx_queue)
{
efx_nic_free_buffer(rx_queue->efx, &rx_queue->rxd);
}
void efx_mcdi_rx_fini(struct efx_rx_queue *rx_queue)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_FINI_RXQ_IN_LEN);
MCDI_DECLARE_BUF_ERR(outbuf);
struct efx_nic *efx = rx_queue->efx;
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, FINI_RXQ_IN_INSTANCE,
efx_rx_queue_index(rx_queue));
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_FINI_RXQ, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc && rc != -EALREADY)
goto fail;
return;
fail:
efx_mcdi_display_error(efx, MC_CMD_FINI_RXQ, MC_CMD_FINI_RXQ_IN_LEN,
outbuf, outlen, rc);
}
int efx_fini_dmaq(struct efx_nic *efx)
{
struct efx_tx_queue *tx_queue;
struct efx_rx_queue *rx_queue;
struct efx_channel *channel;
int pending;
/* If the MC has just rebooted, the TX/RX queues will have already been
* torn down, but efx->active_queues needs to be set to zero.
*/
if (efx->must_realloc_vis) {
atomic_set(&efx->active_queues, 0);
return 0;
}
/* Do not attempt to write to the NIC during EEH recovery */
if (efx->state != STATE_RECOVERY) {
efx_for_each_channel(channel, efx) {
efx_for_each_channel_rx_queue(rx_queue, channel)
efx_mcdi_rx_fini(rx_queue);
efx_for_each_channel_tx_queue(tx_queue, channel)
efx_mcdi_tx_fini(tx_queue);
}
wait_event_timeout(efx->flush_wq,
atomic_read(&efx->active_queues) == 0,
msecs_to_jiffies(EFX_MAX_FLUSH_TIME));
pending = atomic_read(&efx->active_queues);
if (pending) {
netif_err(efx, hw, efx->net_dev, "failed to flush %d queues\n",
pending);
return -ETIMEDOUT;
}
}
return 0;
}
int efx_mcdi_window_mode_to_stride(struct efx_nic *efx, u8 vi_window_mode)
{
switch (vi_window_mode) {
case MC_CMD_GET_CAPABILITIES_V3_OUT_VI_WINDOW_MODE_8K:
efx->vi_stride = 8192;
break;
case MC_CMD_GET_CAPABILITIES_V3_OUT_VI_WINDOW_MODE_16K:
efx->vi_stride = 16384;
break;
case MC_CMD_GET_CAPABILITIES_V3_OUT_VI_WINDOW_MODE_64K:
efx->vi_stride = 65536;
break;
default:
netif_err(efx, probe, efx->net_dev,
"Unrecognised VI window mode %d\n",
vi_window_mode);
return -EIO;
}
netif_dbg(efx, probe, efx->net_dev, "vi_stride = %u\n",
efx->vi_stride);
return 0;
}
int efx_get_pf_index(struct efx_nic *efx, unsigned int *pf_index)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_FUNCTION_INFO_OUT_LEN);
size_t outlen;
int rc;
rc = efx_mcdi_rpc(efx, MC_CMD_GET_FUNCTION_INFO, NULL, 0, outbuf,
sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < sizeof(outbuf))
return -EIO;
*pf_index = MCDI_DWORD(outbuf, GET_FUNCTION_INFO_OUT_PF);
return 0;
}
|
linux-master
|
drivers/net/ethernet/sfc/mcdi_functions.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2008-2013 Solarflare Communications Inc.
*/
#include <linux/delay.h>
#include <linux/moduleparam.h>
#include <linux/atomic.h>
#include "net_driver.h"
#include "nic.h"
#include "io.h"
#include "mcdi_pcol.h"
/**************************************************************************
*
* Management-Controller-to-Driver Interface
*
**************************************************************************
*/
#define MCDI_RPC_TIMEOUT (10 * HZ)
/* A reboot/assertion causes the MCDI status word to be set after the
* command word is set or a REBOOT event is sent. If we notice a reboot
* via these mechanisms then wait 250ms for the status word to be set.
*/
#define MCDI_STATUS_DELAY_US 100
#define MCDI_STATUS_DELAY_COUNT 2500
#define MCDI_STATUS_SLEEP_MS \
(MCDI_STATUS_DELAY_US * MCDI_STATUS_DELAY_COUNT / 1000)
#define SEQ_MASK \
EFX_MASK32(EFX_WIDTH(MCDI_HEADER_SEQ))
struct efx_mcdi_async_param {
struct list_head list;
unsigned int cmd;
size_t inlen;
size_t outlen;
bool quiet;
efx_mcdi_async_completer *complete;
unsigned long cookie;
/* followed by request/response buffer */
};
static void efx_mcdi_timeout_async(struct timer_list *t);
static int efx_mcdi_drv_attach(struct efx_nic *efx, bool driver_operating,
bool *was_attached_out);
static bool efx_mcdi_poll_once(struct efx_nic *efx);
static void efx_mcdi_abandon(struct efx_nic *efx);
#ifdef CONFIG_SFC_MCDI_LOGGING
static bool mcdi_logging_default;
module_param(mcdi_logging_default, bool, 0644);
MODULE_PARM_DESC(mcdi_logging_default,
"Enable MCDI logging on newly-probed functions");
#endif
int efx_mcdi_init(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi;
bool already_attached;
int rc = -ENOMEM;
efx->mcdi = kzalloc(sizeof(*efx->mcdi), GFP_KERNEL);
if (!efx->mcdi)
goto fail;
mcdi = efx_mcdi(efx);
mcdi->efx = efx;
#ifdef CONFIG_SFC_MCDI_LOGGING
/* consuming code assumes buffer is page-sized */
mcdi->logging_buffer = (char *)__get_free_page(GFP_KERNEL);
if (!mcdi->logging_buffer)
goto fail1;
mcdi->logging_enabled = mcdi_logging_default;
#endif
init_waitqueue_head(&mcdi->wq);
init_waitqueue_head(&mcdi->proxy_rx_wq);
spin_lock_init(&mcdi->iface_lock);
mcdi->state = MCDI_STATE_QUIESCENT;
mcdi->mode = MCDI_MODE_POLL;
spin_lock_init(&mcdi->async_lock);
INIT_LIST_HEAD(&mcdi->async_list);
timer_setup(&mcdi->async_timer, efx_mcdi_timeout_async, 0);
(void) efx_mcdi_poll_reboot(efx);
mcdi->new_epoch = true;
/* Recover from a failed assertion before probing */
rc = efx_mcdi_handle_assertion(efx);
if (rc)
goto fail2;
/* Let the MC (and BMC, if this is a LOM) know that the driver
* is loaded. We should do this before we reset the NIC.
*/
rc = efx_mcdi_drv_attach(efx, true, &already_attached);
if (rc) {
pci_err(efx->pci_dev, "Unable to register driver with MCPU\n");
goto fail2;
}
if (already_attached)
/* Not a fatal error */
pci_err(efx->pci_dev, "Host already registered with MCPU\n");
if (efx->mcdi->fn_flags &
(1 << MC_CMD_DRV_ATTACH_EXT_OUT_FLAG_PRIMARY))
efx->primary = efx;
return 0;
fail2:
#ifdef CONFIG_SFC_MCDI_LOGGING
free_page((unsigned long)mcdi->logging_buffer);
fail1:
#endif
kfree(efx->mcdi);
efx->mcdi = NULL;
fail:
return rc;
}
void efx_mcdi_detach(struct efx_nic *efx)
{
if (!efx->mcdi)
return;
BUG_ON(efx->mcdi->iface.state != MCDI_STATE_QUIESCENT);
/* Relinquish the device (back to the BMC, if this is a LOM) */
efx_mcdi_drv_attach(efx, false, NULL);
}
void efx_mcdi_fini(struct efx_nic *efx)
{
if (!efx->mcdi)
return;
#ifdef CONFIG_SFC_MCDI_LOGGING
free_page((unsigned long)efx->mcdi->iface.logging_buffer);
#endif
kfree(efx->mcdi);
}
static void efx_mcdi_send_request(struct efx_nic *efx, unsigned cmd,
const efx_dword_t *inbuf, size_t inlen)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
#ifdef CONFIG_SFC_MCDI_LOGGING
char *buf = mcdi->logging_buffer; /* page-sized */
#endif
efx_dword_t hdr[2];
size_t hdr_len;
u32 xflags, seqno;
BUG_ON(mcdi->state == MCDI_STATE_QUIESCENT);
/* Serialise with efx_mcdi_ev_cpl() and efx_mcdi_ev_death() */
spin_lock_bh(&mcdi->iface_lock);
++mcdi->seqno;
seqno = mcdi->seqno & SEQ_MASK;
spin_unlock_bh(&mcdi->iface_lock);
xflags = 0;
if (mcdi->mode == MCDI_MODE_EVENTS)
xflags |= MCDI_HEADER_XFLAGS_EVREQ;
if (efx->type->mcdi_max_ver == 1) {
/* MCDI v1 */
EFX_POPULATE_DWORD_7(hdr[0],
MCDI_HEADER_RESPONSE, 0,
MCDI_HEADER_RESYNC, 1,
MCDI_HEADER_CODE, cmd,
MCDI_HEADER_DATALEN, inlen,
MCDI_HEADER_SEQ, seqno,
MCDI_HEADER_XFLAGS, xflags,
MCDI_HEADER_NOT_EPOCH, !mcdi->new_epoch);
hdr_len = 4;
} else {
/* MCDI v2 */
BUG_ON(inlen > MCDI_CTL_SDU_LEN_MAX_V2);
EFX_POPULATE_DWORD_7(hdr[0],
MCDI_HEADER_RESPONSE, 0,
MCDI_HEADER_RESYNC, 1,
MCDI_HEADER_CODE, MC_CMD_V2_EXTN,
MCDI_HEADER_DATALEN, 0,
MCDI_HEADER_SEQ, seqno,
MCDI_HEADER_XFLAGS, xflags,
MCDI_HEADER_NOT_EPOCH, !mcdi->new_epoch);
EFX_POPULATE_DWORD_2(hdr[1],
MC_CMD_V2_EXTN_IN_EXTENDED_CMD, cmd,
MC_CMD_V2_EXTN_IN_ACTUAL_LEN, inlen);
hdr_len = 8;
}
#ifdef CONFIG_SFC_MCDI_LOGGING
if (mcdi->logging_enabled && !WARN_ON_ONCE(!buf)) {
int bytes = 0;
int i;
/* Lengths should always be a whole number of dwords, so scream
* if they're not.
*/
WARN_ON_ONCE(hdr_len % 4);
WARN_ON_ONCE(inlen % 4);
/* We own the logging buffer, as only one MCDI can be in
* progress on a NIC at any one time. So no need for locking.
*/
for (i = 0; i < hdr_len / 4 && bytes < PAGE_SIZE; i++)
bytes += scnprintf(buf + bytes, PAGE_SIZE - bytes,
" %08x",
le32_to_cpu(hdr[i].u32[0]));
for (i = 0; i < inlen / 4 && bytes < PAGE_SIZE; i++)
bytes += scnprintf(buf + bytes, PAGE_SIZE - bytes,
" %08x",
le32_to_cpu(inbuf[i].u32[0]));
netif_info(efx, hw, efx->net_dev, "MCDI RPC REQ:%s\n", buf);
}
#endif
efx->type->mcdi_request(efx, hdr, hdr_len, inbuf, inlen);
mcdi->new_epoch = false;
}
static int efx_mcdi_errno(unsigned int mcdi_err)
{
switch (mcdi_err) {
case 0:
return 0;
#define TRANSLATE_ERROR(name) \
case MC_CMD_ERR_ ## name: \
return -name;
TRANSLATE_ERROR(EPERM);
TRANSLATE_ERROR(ENOENT);
TRANSLATE_ERROR(EINTR);
TRANSLATE_ERROR(EAGAIN);
TRANSLATE_ERROR(EACCES);
TRANSLATE_ERROR(EBUSY);
TRANSLATE_ERROR(EINVAL);
TRANSLATE_ERROR(EDEADLK);
TRANSLATE_ERROR(ENOSYS);
TRANSLATE_ERROR(ETIME);
TRANSLATE_ERROR(EALREADY);
TRANSLATE_ERROR(ENOSPC);
#undef TRANSLATE_ERROR
case MC_CMD_ERR_ENOTSUP:
return -EOPNOTSUPP;
case MC_CMD_ERR_ALLOC_FAIL:
return -ENOBUFS;
case MC_CMD_ERR_MAC_EXIST:
return -EADDRINUSE;
default:
return -EPROTO;
}
}
static void efx_mcdi_read_response_header(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
unsigned int respseq, respcmd, error;
#ifdef CONFIG_SFC_MCDI_LOGGING
char *buf = mcdi->logging_buffer; /* page-sized */
#endif
efx_dword_t hdr;
efx->type->mcdi_read_response(efx, &hdr, 0, 4);
respseq = EFX_DWORD_FIELD(hdr, MCDI_HEADER_SEQ);
respcmd = EFX_DWORD_FIELD(hdr, MCDI_HEADER_CODE);
error = EFX_DWORD_FIELD(hdr, MCDI_HEADER_ERROR);
if (respcmd != MC_CMD_V2_EXTN) {
mcdi->resp_hdr_len = 4;
mcdi->resp_data_len = EFX_DWORD_FIELD(hdr, MCDI_HEADER_DATALEN);
} else {
efx->type->mcdi_read_response(efx, &hdr, 4, 4);
mcdi->resp_hdr_len = 8;
mcdi->resp_data_len =
EFX_DWORD_FIELD(hdr, MC_CMD_V2_EXTN_IN_ACTUAL_LEN);
}
#ifdef CONFIG_SFC_MCDI_LOGGING
if (mcdi->logging_enabled && !WARN_ON_ONCE(!buf)) {
size_t hdr_len, data_len;
int bytes = 0;
int i;
WARN_ON_ONCE(mcdi->resp_hdr_len % 4);
hdr_len = mcdi->resp_hdr_len / 4;
/* MCDI_DECLARE_BUF ensures that underlying buffer is padded
* to dword size, and the MCDI buffer is always dword size
*/
data_len = DIV_ROUND_UP(mcdi->resp_data_len, 4);
/* We own the logging buffer, as only one MCDI can be in
* progress on a NIC at any one time. So no need for locking.
*/
for (i = 0; i < hdr_len && bytes < PAGE_SIZE; i++) {
efx->type->mcdi_read_response(efx, &hdr, (i * 4), 4);
bytes += scnprintf(buf + bytes, PAGE_SIZE - bytes,
" %08x", le32_to_cpu(hdr.u32[0]));
}
for (i = 0; i < data_len && bytes < PAGE_SIZE; i++) {
efx->type->mcdi_read_response(efx, &hdr,
mcdi->resp_hdr_len + (i * 4), 4);
bytes += scnprintf(buf + bytes, PAGE_SIZE - bytes,
" %08x", le32_to_cpu(hdr.u32[0]));
}
netif_info(efx, hw, efx->net_dev, "MCDI RPC RESP:%s\n", buf);
}
#endif
mcdi->resprc_raw = 0;
if (error && mcdi->resp_data_len == 0) {
netif_err(efx, hw, efx->net_dev, "MC rebooted\n");
mcdi->resprc = -EIO;
} else if ((respseq ^ mcdi->seqno) & SEQ_MASK) {
netif_err(efx, hw, efx->net_dev,
"MC response mismatch tx seq 0x%x rx seq 0x%x\n",
respseq, mcdi->seqno);
mcdi->resprc = -EIO;
} else if (error) {
efx->type->mcdi_read_response(efx, &hdr, mcdi->resp_hdr_len, 4);
mcdi->resprc_raw = EFX_DWORD_FIELD(hdr, EFX_DWORD_0);
mcdi->resprc = efx_mcdi_errno(mcdi->resprc_raw);
} else {
mcdi->resprc = 0;
}
}
static bool efx_mcdi_poll_once(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
rmb();
if (!efx->type->mcdi_poll_response(efx))
return false;
spin_lock_bh(&mcdi->iface_lock);
efx_mcdi_read_response_header(efx);
spin_unlock_bh(&mcdi->iface_lock);
return true;
}
static int efx_mcdi_poll(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
unsigned long time, finish;
unsigned int spins;
int rc;
/* Check for a reboot atomically with respect to efx_mcdi_copyout() */
rc = efx_mcdi_poll_reboot(efx);
if (rc) {
spin_lock_bh(&mcdi->iface_lock);
mcdi->resprc = rc;
mcdi->resp_hdr_len = 0;
mcdi->resp_data_len = 0;
spin_unlock_bh(&mcdi->iface_lock);
return 0;
}
/* Poll for completion. Poll quickly (once a us) for the 1st jiffy,
* because generally mcdi responses are fast. After that, back off
* and poll once a jiffy (approximately)
*/
spins = USER_TICK_USEC;
finish = jiffies + MCDI_RPC_TIMEOUT;
while (1) {
if (spins != 0) {
--spins;
udelay(1);
} else {
schedule_timeout_uninterruptible(1);
}
time = jiffies;
if (efx_mcdi_poll_once(efx))
break;
if (time_after(time, finish))
return -ETIMEDOUT;
}
/* Return rc=0 like wait_event_timeout() */
return 0;
}
/* Test and clear MC-rebooted flag for this port/function; reset
* software state as necessary.
*/
int efx_mcdi_poll_reboot(struct efx_nic *efx)
{
if (!efx->mcdi)
return 0;
return efx->type->mcdi_poll_reboot(efx);
}
static bool efx_mcdi_acquire_async(struct efx_mcdi_iface *mcdi)
{
return cmpxchg(&mcdi->state,
MCDI_STATE_QUIESCENT, MCDI_STATE_RUNNING_ASYNC) ==
MCDI_STATE_QUIESCENT;
}
static void efx_mcdi_acquire_sync(struct efx_mcdi_iface *mcdi)
{
/* Wait until the interface becomes QUIESCENT and we win the race
* to mark it RUNNING_SYNC.
*/
wait_event(mcdi->wq,
cmpxchg(&mcdi->state,
MCDI_STATE_QUIESCENT, MCDI_STATE_RUNNING_SYNC) ==
MCDI_STATE_QUIESCENT);
}
static int efx_mcdi_await_completion(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
if (wait_event_timeout(mcdi->wq, mcdi->state == MCDI_STATE_COMPLETED,
MCDI_RPC_TIMEOUT) == 0)
return -ETIMEDOUT;
/* Check if efx_mcdi_set_mode() switched us back to polled completions.
* In which case, poll for completions directly. If efx_mcdi_ev_cpl()
* completed the request first, then we'll just end up completing the
* request again, which is safe.
*
* We need an smp_rmb() to synchronise with efx_mcdi_mode_poll(), which
* wait_event_timeout() implicitly provides.
*/
if (mcdi->mode == MCDI_MODE_POLL)
return efx_mcdi_poll(efx);
return 0;
}
/* If the interface is RUNNING_SYNC, switch to COMPLETED and wake the
* requester. Return whether this was done. Does not take any locks.
*/
static bool efx_mcdi_complete_sync(struct efx_mcdi_iface *mcdi)
{
if (cmpxchg(&mcdi->state,
MCDI_STATE_RUNNING_SYNC, MCDI_STATE_COMPLETED) ==
MCDI_STATE_RUNNING_SYNC) {
wake_up(&mcdi->wq);
return true;
}
return false;
}
static void efx_mcdi_release(struct efx_mcdi_iface *mcdi)
{
if (mcdi->mode == MCDI_MODE_EVENTS) {
struct efx_mcdi_async_param *async;
struct efx_nic *efx = mcdi->efx;
/* Process the asynchronous request queue */
spin_lock_bh(&mcdi->async_lock);
async = list_first_entry_or_null(
&mcdi->async_list, struct efx_mcdi_async_param, list);
if (async) {
mcdi->state = MCDI_STATE_RUNNING_ASYNC;
efx_mcdi_send_request(efx, async->cmd,
(const efx_dword_t *)(async + 1),
async->inlen);
mod_timer(&mcdi->async_timer,
jiffies + MCDI_RPC_TIMEOUT);
}
spin_unlock_bh(&mcdi->async_lock);
if (async)
return;
}
mcdi->state = MCDI_STATE_QUIESCENT;
wake_up(&mcdi->wq);
}
/* If the interface is RUNNING_ASYNC, switch to COMPLETED, call the
* asynchronous completion function, and release the interface.
* Return whether this was done. Must be called in bh-disabled
* context. Will take iface_lock and async_lock.
*/
static bool efx_mcdi_complete_async(struct efx_mcdi_iface *mcdi, bool timeout)
{
struct efx_nic *efx = mcdi->efx;
struct efx_mcdi_async_param *async;
size_t hdr_len, data_len, err_len;
efx_dword_t *outbuf;
MCDI_DECLARE_BUF_ERR(errbuf);
int rc;
if (cmpxchg(&mcdi->state,
MCDI_STATE_RUNNING_ASYNC, MCDI_STATE_COMPLETED) !=
MCDI_STATE_RUNNING_ASYNC)
return false;
spin_lock(&mcdi->iface_lock);
if (timeout) {
/* Ensure that if the completion event arrives later,
* the seqno check in efx_mcdi_ev_cpl() will fail
*/
++mcdi->seqno;
++mcdi->credits;
rc = -ETIMEDOUT;
hdr_len = 0;
data_len = 0;
} else {
rc = mcdi->resprc;
hdr_len = mcdi->resp_hdr_len;
data_len = mcdi->resp_data_len;
}
spin_unlock(&mcdi->iface_lock);
/* Stop the timer. In case the timer function is running, we
* must wait for it to return so that there is no possibility
* of it aborting the next request.
*/
if (!timeout)
del_timer_sync(&mcdi->async_timer);
spin_lock(&mcdi->async_lock);
async = list_first_entry(&mcdi->async_list,
struct efx_mcdi_async_param, list);
list_del(&async->list);
spin_unlock(&mcdi->async_lock);
outbuf = (efx_dword_t *)(async + 1);
efx->type->mcdi_read_response(efx, outbuf, hdr_len,
min(async->outlen, data_len));
if (!timeout && rc && !async->quiet) {
err_len = min(sizeof(errbuf), data_len);
efx->type->mcdi_read_response(efx, errbuf, hdr_len,
sizeof(errbuf));
efx_mcdi_display_error(efx, async->cmd, async->inlen, errbuf,
err_len, rc);
}
if (async->complete)
async->complete(efx, async->cookie, rc, outbuf,
min(async->outlen, data_len));
kfree(async);
efx_mcdi_release(mcdi);
return true;
}
static void efx_mcdi_ev_cpl(struct efx_nic *efx, unsigned int seqno,
unsigned int datalen, unsigned int mcdi_err)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
bool wake = false;
spin_lock(&mcdi->iface_lock);
if ((seqno ^ mcdi->seqno) & SEQ_MASK) {
if (mcdi->credits)
/* The request has been cancelled */
--mcdi->credits;
else
netif_err(efx, hw, efx->net_dev,
"MC response mismatch tx seq 0x%x rx "
"seq 0x%x\n", seqno, mcdi->seqno);
} else {
if (efx->type->mcdi_max_ver >= 2) {
/* MCDI v2 responses don't fit in an event */
efx_mcdi_read_response_header(efx);
} else {
mcdi->resprc = efx_mcdi_errno(mcdi_err);
mcdi->resp_hdr_len = 4;
mcdi->resp_data_len = datalen;
}
wake = true;
}
spin_unlock(&mcdi->iface_lock);
if (wake) {
if (!efx_mcdi_complete_async(mcdi, false))
(void) efx_mcdi_complete_sync(mcdi);
/* If the interface isn't RUNNING_ASYNC or
* RUNNING_SYNC then we've received a duplicate
* completion after we've already transitioned back to
* QUIESCENT. [A subsequent invocation would increment
* seqno, so would have failed the seqno check].
*/
}
}
static void efx_mcdi_timeout_async(struct timer_list *t)
{
struct efx_mcdi_iface *mcdi = from_timer(mcdi, t, async_timer);
efx_mcdi_complete_async(mcdi, true);
}
static int
efx_mcdi_check_supported(struct efx_nic *efx, unsigned int cmd, size_t inlen)
{
if (efx->type->mcdi_max_ver < 0 ||
(efx->type->mcdi_max_ver < 2 &&
cmd > MC_CMD_CMD_SPACE_ESCAPE_7))
return -EINVAL;
if (inlen > MCDI_CTL_SDU_LEN_MAX_V2 ||
(efx->type->mcdi_max_ver < 2 &&
inlen > MCDI_CTL_SDU_LEN_MAX_V1))
return -EMSGSIZE;
return 0;
}
static bool efx_mcdi_get_proxy_handle(struct efx_nic *efx,
size_t hdr_len, size_t data_len,
u32 *proxy_handle)
{
MCDI_DECLARE_BUF_ERR(testbuf);
const size_t buflen = sizeof(testbuf);
if (!proxy_handle || data_len < buflen)
return false;
efx->type->mcdi_read_response(efx, testbuf, hdr_len, buflen);
if (MCDI_DWORD(testbuf, ERR_CODE) == MC_CMD_ERR_PROXY_PENDING) {
*proxy_handle = MCDI_DWORD(testbuf, ERR_PROXY_PENDING_HANDLE);
return true;
}
return false;
}
static int _efx_mcdi_rpc_finish(struct efx_nic *efx, unsigned int cmd,
size_t inlen,
efx_dword_t *outbuf, size_t outlen,
size_t *outlen_actual, bool quiet,
u32 *proxy_handle, int *raw_rc)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
MCDI_DECLARE_BUF_ERR(errbuf);
int rc;
if (mcdi->mode == MCDI_MODE_POLL)
rc = efx_mcdi_poll(efx);
else
rc = efx_mcdi_await_completion(efx);
if (rc != 0) {
netif_err(efx, hw, efx->net_dev,
"MC command 0x%x inlen %d mode %d timed out\n",
cmd, (int)inlen, mcdi->mode);
if (mcdi->mode == MCDI_MODE_EVENTS && efx_mcdi_poll_once(efx)) {
netif_err(efx, hw, efx->net_dev,
"MCDI request was completed without an event\n");
rc = 0;
}
efx_mcdi_abandon(efx);
/* Close the race with efx_mcdi_ev_cpl() executing just too late
* and completing a request we've just cancelled, by ensuring
* that the seqno check therein fails.
*/
spin_lock_bh(&mcdi->iface_lock);
++mcdi->seqno;
++mcdi->credits;
spin_unlock_bh(&mcdi->iface_lock);
}
if (proxy_handle)
*proxy_handle = 0;
if (rc != 0) {
if (outlen_actual)
*outlen_actual = 0;
} else {
size_t hdr_len, data_len, err_len;
/* At the very least we need a memory barrier here to ensure
* we pick up changes from efx_mcdi_ev_cpl(). Protect against
* a spurious efx_mcdi_ev_cpl() running concurrently by
* acquiring the iface_lock. */
spin_lock_bh(&mcdi->iface_lock);
rc = mcdi->resprc;
if (raw_rc)
*raw_rc = mcdi->resprc_raw;
hdr_len = mcdi->resp_hdr_len;
data_len = mcdi->resp_data_len;
err_len = min(sizeof(errbuf), data_len);
spin_unlock_bh(&mcdi->iface_lock);
BUG_ON(rc > 0);
efx->type->mcdi_read_response(efx, outbuf, hdr_len,
min(outlen, data_len));
if (outlen_actual)
*outlen_actual = data_len;
efx->type->mcdi_read_response(efx, errbuf, hdr_len, err_len);
if (cmd == MC_CMD_REBOOT && rc == -EIO) {
/* Don't reset if MC_CMD_REBOOT returns EIO */
} else if (rc == -EIO || rc == -EINTR) {
netif_err(efx, hw, efx->net_dev, "MC reboot detected\n");
netif_dbg(efx, hw, efx->net_dev, "MC rebooted during command %d rc %d\n",
cmd, -rc);
if (efx->type->mcdi_reboot_detected)
efx->type->mcdi_reboot_detected(efx);
efx_schedule_reset(efx, RESET_TYPE_MC_FAILURE);
} else if (proxy_handle && (rc == -EPROTO) &&
efx_mcdi_get_proxy_handle(efx, hdr_len, data_len,
proxy_handle)) {
mcdi->proxy_rx_status = 0;
mcdi->proxy_rx_handle = 0;
mcdi->state = MCDI_STATE_PROXY_WAIT;
} else if (rc && !quiet) {
efx_mcdi_display_error(efx, cmd, inlen, errbuf, err_len,
rc);
}
if (rc == -EIO || rc == -EINTR) {
msleep(MCDI_STATUS_SLEEP_MS);
efx_mcdi_poll_reboot(efx);
mcdi->new_epoch = true;
}
}
if (!proxy_handle || !*proxy_handle)
efx_mcdi_release(mcdi);
return rc;
}
static void efx_mcdi_proxy_abort(struct efx_mcdi_iface *mcdi)
{
if (mcdi->state == MCDI_STATE_PROXY_WAIT) {
/* Interrupt the proxy wait. */
mcdi->proxy_rx_status = -EINTR;
wake_up(&mcdi->proxy_rx_wq);
}
}
static void efx_mcdi_ev_proxy_response(struct efx_nic *efx,
u32 handle, int status)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
WARN_ON(mcdi->state != MCDI_STATE_PROXY_WAIT);
mcdi->proxy_rx_status = efx_mcdi_errno(status);
/* Ensure the status is written before we update the handle, since the
* latter is used to check if we've finished.
*/
wmb();
mcdi->proxy_rx_handle = handle;
wake_up(&mcdi->proxy_rx_wq);
}
static int efx_mcdi_proxy_wait(struct efx_nic *efx, u32 handle, bool quiet)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
int rc;
/* Wait for a proxy event, or timeout. */
rc = wait_event_timeout(mcdi->proxy_rx_wq,
mcdi->proxy_rx_handle != 0 ||
mcdi->proxy_rx_status == -EINTR,
MCDI_RPC_TIMEOUT);
if (rc <= 0) {
netif_dbg(efx, hw, efx->net_dev,
"MCDI proxy timeout %d\n", handle);
return -ETIMEDOUT;
} else if (mcdi->proxy_rx_handle != handle) {
netif_warn(efx, hw, efx->net_dev,
"MCDI proxy unexpected handle %d (expected %d)\n",
mcdi->proxy_rx_handle, handle);
return -EINVAL;
}
return mcdi->proxy_rx_status;
}
static int _efx_mcdi_rpc(struct efx_nic *efx, unsigned int cmd,
const efx_dword_t *inbuf, size_t inlen,
efx_dword_t *outbuf, size_t outlen,
size_t *outlen_actual, bool quiet, int *raw_rc)
{
u32 proxy_handle = 0; /* Zero is an invalid proxy handle. */
int rc;
if (inbuf && inlen && (inbuf == outbuf)) {
/* The input buffer can't be aliased with the output. */
WARN_ON(1);
return -EINVAL;
}
rc = efx_mcdi_rpc_start(efx, cmd, inbuf, inlen);
if (rc)
return rc;
rc = _efx_mcdi_rpc_finish(efx, cmd, inlen, outbuf, outlen,
outlen_actual, quiet, &proxy_handle, raw_rc);
if (proxy_handle) {
/* Handle proxy authorisation. This allows approval of MCDI
* operations to be delegated to the admin function, allowing
* fine control over (eg) multicast subscriptions.
*/
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
netif_dbg(efx, hw, efx->net_dev,
"MCDI waiting for proxy auth %d\n",
proxy_handle);
rc = efx_mcdi_proxy_wait(efx, proxy_handle, quiet);
if (rc == 0) {
netif_dbg(efx, hw, efx->net_dev,
"MCDI proxy retry %d\n", proxy_handle);
/* We now retry the original request. */
mcdi->state = MCDI_STATE_RUNNING_SYNC;
efx_mcdi_send_request(efx, cmd, inbuf, inlen);
rc = _efx_mcdi_rpc_finish(efx, cmd, inlen,
outbuf, outlen, outlen_actual,
quiet, NULL, raw_rc);
} else {
netif_cond_dbg(efx, hw, efx->net_dev, rc == -EPERM, err,
"MC command 0x%x failed after proxy auth rc=%d\n",
cmd, rc);
if (rc == -EINTR || rc == -EIO)
efx_schedule_reset(efx, RESET_TYPE_MC_FAILURE);
efx_mcdi_release(mcdi);
}
}
return rc;
}
static int _efx_mcdi_rpc_evb_retry(struct efx_nic *efx, unsigned cmd,
const efx_dword_t *inbuf, size_t inlen,
efx_dword_t *outbuf, size_t outlen,
size_t *outlen_actual, bool quiet)
{
int raw_rc = 0;
int rc;
rc = _efx_mcdi_rpc(efx, cmd, inbuf, inlen,
outbuf, outlen, outlen_actual, true, &raw_rc);
if ((rc == -EPROTO) && (raw_rc == MC_CMD_ERR_NO_EVB_PORT) &&
efx->type->is_vf) {
/* If the EVB port isn't available within a VF this may
* mean the PF is still bringing the switch up. We should
* retry our request shortly.
*/
unsigned long abort_time = jiffies + MCDI_RPC_TIMEOUT;
unsigned int delay_us = 10000;
netif_dbg(efx, hw, efx->net_dev,
"%s: NO_EVB_PORT; will retry request\n",
__func__);
do {
usleep_range(delay_us, delay_us + 10000);
rc = _efx_mcdi_rpc(efx, cmd, inbuf, inlen,
outbuf, outlen, outlen_actual,
true, &raw_rc);
if (delay_us < 100000)
delay_us <<= 1;
} while ((rc == -EPROTO) &&
(raw_rc == MC_CMD_ERR_NO_EVB_PORT) &&
time_before(jiffies, abort_time));
}
if (rc && !quiet && !(cmd == MC_CMD_REBOOT && rc == -EIO))
efx_mcdi_display_error(efx, cmd, inlen,
outbuf, outlen, rc);
return rc;
}
/**
* efx_mcdi_rpc - Issue an MCDI command and wait for completion
* @efx: NIC through which to issue the command
* @cmd: Command type number
* @inbuf: Command parameters
* @inlen: Length of command parameters, in bytes. Must be a multiple
* of 4 and no greater than %MCDI_CTL_SDU_LEN_MAX_V1.
* @outbuf: Response buffer. May be %NULL if @outlen is 0.
* @outlen: Length of response buffer, in bytes. If the actual
* response is longer than @outlen & ~3, it will be truncated
* to that length.
* @outlen_actual: Pointer through which to return the actual response
* length. May be %NULL if this is not needed.
*
* This function may sleep and therefore must be called in an appropriate
* context.
*
* Return: A negative error code, or zero if successful. The error
* code may come from the MCDI response or may indicate a failure
* to communicate with the MC. In the former case, the response
* will still be copied to @outbuf and *@outlen_actual will be
* set accordingly. In the latter case, *@outlen_actual will be
* set to zero.
*/
int efx_mcdi_rpc(struct efx_nic *efx, unsigned cmd,
const efx_dword_t *inbuf, size_t inlen,
efx_dword_t *outbuf, size_t outlen,
size_t *outlen_actual)
{
return _efx_mcdi_rpc_evb_retry(efx, cmd, inbuf, inlen, outbuf, outlen,
outlen_actual, false);
}
/* Normally, on receiving an error code in the MCDI response,
* efx_mcdi_rpc will log an error message containing (among other
* things) the raw error code, by means of efx_mcdi_display_error.
* This _quiet version suppresses that; if the caller wishes to log
* the error conditionally on the return code, it should call this
* function and is then responsible for calling efx_mcdi_display_error
* as needed.
*/
int efx_mcdi_rpc_quiet(struct efx_nic *efx, unsigned cmd,
const efx_dword_t *inbuf, size_t inlen,
efx_dword_t *outbuf, size_t outlen,
size_t *outlen_actual)
{
return _efx_mcdi_rpc_evb_retry(efx, cmd, inbuf, inlen, outbuf, outlen,
outlen_actual, true);
}
int efx_mcdi_rpc_start(struct efx_nic *efx, unsigned cmd,
const efx_dword_t *inbuf, size_t inlen)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
int rc;
rc = efx_mcdi_check_supported(efx, cmd, inlen);
if (rc)
return rc;
if (efx->mc_bist_for_other_fn)
return -ENETDOWN;
if (mcdi->mode == MCDI_MODE_FAIL)
return -ENETDOWN;
efx_mcdi_acquire_sync(mcdi);
efx_mcdi_send_request(efx, cmd, inbuf, inlen);
return 0;
}
static int _efx_mcdi_rpc_async(struct efx_nic *efx, unsigned int cmd,
const efx_dword_t *inbuf, size_t inlen,
size_t outlen,
efx_mcdi_async_completer *complete,
unsigned long cookie, bool quiet)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
struct efx_mcdi_async_param *async;
int rc;
rc = efx_mcdi_check_supported(efx, cmd, inlen);
if (rc)
return rc;
if (efx->mc_bist_for_other_fn)
return -ENETDOWN;
async = kmalloc(sizeof(*async) + ALIGN(max(inlen, outlen), 4),
GFP_ATOMIC);
if (!async)
return -ENOMEM;
async->cmd = cmd;
async->inlen = inlen;
async->outlen = outlen;
async->quiet = quiet;
async->complete = complete;
async->cookie = cookie;
memcpy(async + 1, inbuf, inlen);
spin_lock_bh(&mcdi->async_lock);
if (mcdi->mode == MCDI_MODE_EVENTS) {
list_add_tail(&async->list, &mcdi->async_list);
/* If this is at the front of the queue, try to start it
* immediately
*/
if (mcdi->async_list.next == &async->list &&
efx_mcdi_acquire_async(mcdi)) {
efx_mcdi_send_request(efx, cmd, inbuf, inlen);
mod_timer(&mcdi->async_timer,
jiffies + MCDI_RPC_TIMEOUT);
}
} else {
kfree(async);
rc = -ENETDOWN;
}
spin_unlock_bh(&mcdi->async_lock);
return rc;
}
/**
* efx_mcdi_rpc_async - Schedule an MCDI command to run asynchronously
* @efx: NIC through which to issue the command
* @cmd: Command type number
* @inbuf: Command parameters
* @inlen: Length of command parameters, in bytes
* @outlen: Length to allocate for response buffer, in bytes
* @complete: Function to be called on completion or cancellation.
* @cookie: Arbitrary value to be passed to @complete.
*
* This function does not sleep and therefore may be called in atomic
* context. It will fail if event queues are disabled or if MCDI
* event completions have been disabled due to an error.
*
* If it succeeds, the @complete function will be called exactly once
* in atomic context, when one of the following occurs:
* (a) the completion event is received (in NAPI context)
* (b) event queues are disabled (in the process that disables them)
* (c) the request times-out (in timer context)
*/
int
efx_mcdi_rpc_async(struct efx_nic *efx, unsigned int cmd,
const efx_dword_t *inbuf, size_t inlen, size_t outlen,
efx_mcdi_async_completer *complete, unsigned long cookie)
{
return _efx_mcdi_rpc_async(efx, cmd, inbuf, inlen, outlen, complete,
cookie, false);
}
int efx_mcdi_rpc_async_quiet(struct efx_nic *efx, unsigned int cmd,
const efx_dword_t *inbuf, size_t inlen,
size_t outlen, efx_mcdi_async_completer *complete,
unsigned long cookie)
{
return _efx_mcdi_rpc_async(efx, cmd, inbuf, inlen, outlen, complete,
cookie, true);
}
int efx_mcdi_rpc_finish(struct efx_nic *efx, unsigned cmd, size_t inlen,
efx_dword_t *outbuf, size_t outlen,
size_t *outlen_actual)
{
return _efx_mcdi_rpc_finish(efx, cmd, inlen, outbuf, outlen,
outlen_actual, false, NULL, NULL);
}
int efx_mcdi_rpc_finish_quiet(struct efx_nic *efx, unsigned cmd, size_t inlen,
efx_dword_t *outbuf, size_t outlen,
size_t *outlen_actual)
{
return _efx_mcdi_rpc_finish(efx, cmd, inlen, outbuf, outlen,
outlen_actual, true, NULL, NULL);
}
void efx_mcdi_display_error(struct efx_nic *efx, unsigned cmd,
size_t inlen, efx_dword_t *outbuf,
size_t outlen, int rc)
{
int code = 0, err_arg = 0;
if (outlen >= MC_CMD_ERR_CODE_OFST + 4)
code = MCDI_DWORD(outbuf, ERR_CODE);
if (outlen >= MC_CMD_ERR_ARG_OFST + 4)
err_arg = MCDI_DWORD(outbuf, ERR_ARG);
netif_cond_dbg(efx, hw, efx->net_dev, rc == -EPERM, err,
"MC command 0x%x inlen %zu failed rc=%d (raw=%d) arg=%d\n",
cmd, inlen, rc, code, err_arg);
}
/* Switch to polled MCDI completions. This can be called in various
* error conditions with various locks held, so it must be lockless.
* Caller is responsible for flushing asynchronous requests later.
*/
void efx_mcdi_mode_poll(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi;
if (!efx->mcdi)
return;
mcdi = efx_mcdi(efx);
/* If already in polling mode, nothing to do.
* If in fail-fast state, don't switch to polled completion.
* FLR recovery will do that later.
*/
if (mcdi->mode == MCDI_MODE_POLL || mcdi->mode == MCDI_MODE_FAIL)
return;
/* We can switch from event completion to polled completion, because
* mcdi requests are always completed in shared memory. We do this by
* switching the mode to POLL'd then completing the request.
* efx_mcdi_await_completion() will then call efx_mcdi_poll().
*
* We need an smp_wmb() to synchronise with efx_mcdi_await_completion(),
* which efx_mcdi_complete_sync() provides for us.
*/
mcdi->mode = MCDI_MODE_POLL;
efx_mcdi_complete_sync(mcdi);
}
/* Flush any running or queued asynchronous requests, after event processing
* is stopped
*/
void efx_mcdi_flush_async(struct efx_nic *efx)
{
struct efx_mcdi_async_param *async, *next;
struct efx_mcdi_iface *mcdi;
if (!efx->mcdi)
return;
mcdi = efx_mcdi(efx);
/* We must be in poll or fail mode so no more requests can be queued */
BUG_ON(mcdi->mode == MCDI_MODE_EVENTS);
del_timer_sync(&mcdi->async_timer);
/* If a request is still running, make sure we give the MC
* time to complete it so that the response won't overwrite our
* next request.
*/
if (mcdi->state == MCDI_STATE_RUNNING_ASYNC) {
efx_mcdi_poll(efx);
mcdi->state = MCDI_STATE_QUIESCENT;
}
/* Nothing else will access the async list now, so it is safe
* to walk it without holding async_lock. If we hold it while
* calling a completer then lockdep may warn that we have
* acquired locks in the wrong order.
*/
list_for_each_entry_safe(async, next, &mcdi->async_list, list) {
if (async->complete)
async->complete(efx, async->cookie, -ENETDOWN, NULL, 0);
list_del(&async->list);
kfree(async);
}
}
void efx_mcdi_mode_event(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi;
if (!efx->mcdi)
return;
mcdi = efx_mcdi(efx);
/* If already in event completion mode, nothing to do.
* If in fail-fast state, don't switch to event completion. FLR
* recovery will do that later.
*/
if (mcdi->mode == MCDI_MODE_EVENTS || mcdi->mode == MCDI_MODE_FAIL)
return;
/* We can't switch from polled to event completion in the middle of a
* request, because the completion method is specified in the request.
* So acquire the interface to serialise the requestors. We don't need
* to acquire the iface_lock to change the mode here, but we do need a
* write memory barrier ensure that efx_mcdi_rpc() sees it, which
* efx_mcdi_acquire() provides.
*/
efx_mcdi_acquire_sync(mcdi);
mcdi->mode = MCDI_MODE_EVENTS;
efx_mcdi_release(mcdi);
}
static void efx_mcdi_ev_death(struct efx_nic *efx, int rc)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
/* If there is an outstanding MCDI request, it has been terminated
* either by a BADASSERT or REBOOT event. If the mcdi interface is
* in polled mode, then do nothing because the MC reboot handler will
* set the header correctly. However, if the mcdi interface is waiting
* for a CMDDONE event it won't receive it [and since all MCDI events
* are sent to the same queue, we can't be racing with
* efx_mcdi_ev_cpl()]
*
* If there is an outstanding asynchronous request, we can't
* complete it now (efx_mcdi_complete() would deadlock). The
* reset process will take care of this.
*
* There's a race here with efx_mcdi_send_request(), because
* we might receive a REBOOT event *before* the request has
* been copied out. In polled mode (during startup) this is
* irrelevant, because efx_mcdi_complete_sync() is ignored. In
* event mode, this condition is just an edge-case of
* receiving a REBOOT event after posting the MCDI
* request. Did the mc reboot before or after the copyout? The
* best we can do always is just return failure.
*
* If there is an outstanding proxy response expected it is not going
* to arrive. We should thus abort it.
*/
spin_lock(&mcdi->iface_lock);
efx_mcdi_proxy_abort(mcdi);
if (efx_mcdi_complete_sync(mcdi)) {
if (mcdi->mode == MCDI_MODE_EVENTS) {
mcdi->resprc = rc;
mcdi->resp_hdr_len = 0;
mcdi->resp_data_len = 0;
++mcdi->credits;
}
} else {
int count;
/* Consume the status word since efx_mcdi_rpc_finish() won't */
for (count = 0; count < MCDI_STATUS_DELAY_COUNT; ++count) {
rc = efx_mcdi_poll_reboot(efx);
if (rc)
break;
udelay(MCDI_STATUS_DELAY_US);
}
/* On EF10, a CODE_MC_REBOOT event can be received without the
* reboot detection in efx_mcdi_poll_reboot() being triggered.
* If zero was returned from the final call to
* efx_mcdi_poll_reboot(), the MC reboot wasn't noticed but the
* MC has definitely rebooted so prepare for the reset.
*/
if (!rc && efx->type->mcdi_reboot_detected)
efx->type->mcdi_reboot_detected(efx);
mcdi->new_epoch = true;
/* Nobody was waiting for an MCDI request, so trigger a reset */
efx_schedule_reset(efx, RESET_TYPE_MC_FAILURE);
}
spin_unlock(&mcdi->iface_lock);
}
/* The MC is going down in to BIST mode. set the BIST flag to block
* new MCDI, cancel any outstanding MCDI and schedule a BIST-type reset
* (which doesn't actually execute a reset, it waits for the controlling
* function to reset it).
*/
static void efx_mcdi_ev_bist(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
spin_lock(&mcdi->iface_lock);
efx->mc_bist_for_other_fn = true;
efx_mcdi_proxy_abort(mcdi);
if (efx_mcdi_complete_sync(mcdi)) {
if (mcdi->mode == MCDI_MODE_EVENTS) {
mcdi->resprc = -EIO;
mcdi->resp_hdr_len = 0;
mcdi->resp_data_len = 0;
++mcdi->credits;
}
}
mcdi->new_epoch = true;
efx_schedule_reset(efx, RESET_TYPE_MC_BIST);
spin_unlock(&mcdi->iface_lock);
}
/* MCDI timeouts seen, so make all MCDI calls fail-fast and issue an FLR to try
* to recover.
*/
static void efx_mcdi_abandon(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
if (xchg(&mcdi->mode, MCDI_MODE_FAIL) == MCDI_MODE_FAIL)
return; /* it had already been done */
netif_dbg(efx, hw, efx->net_dev, "MCDI is timing out; trying to recover\n");
efx_schedule_reset(efx, RESET_TYPE_MCDI_TIMEOUT);
}
static void efx_handle_drain_event(struct efx_nic *efx)
{
if (atomic_dec_and_test(&efx->active_queues))
wake_up(&efx->flush_wq);
WARN_ON(atomic_read(&efx->active_queues) < 0);
}
/* Called from efx_farch_ev_process and efx_ef10_ev_process for MCDI events */
void efx_mcdi_process_event(struct efx_channel *channel,
efx_qword_t *event)
{
struct efx_nic *efx = channel->efx;
int code = EFX_QWORD_FIELD(*event, MCDI_EVENT_CODE);
u32 data = EFX_QWORD_FIELD(*event, MCDI_EVENT_DATA);
switch (code) {
case MCDI_EVENT_CODE_BADSSERT:
netif_err(efx, hw, efx->net_dev,
"MC watchdog or assertion failure at 0x%x\n", data);
efx_mcdi_ev_death(efx, -EINTR);
break;
case MCDI_EVENT_CODE_PMNOTICE:
netif_info(efx, wol, efx->net_dev, "MCDI PM event.\n");
break;
case MCDI_EVENT_CODE_CMDDONE:
efx_mcdi_ev_cpl(efx,
MCDI_EVENT_FIELD(*event, CMDDONE_SEQ),
MCDI_EVENT_FIELD(*event, CMDDONE_DATALEN),
MCDI_EVENT_FIELD(*event, CMDDONE_ERRNO));
break;
case MCDI_EVENT_CODE_LINKCHANGE:
efx_mcdi_process_link_change(efx, event);
break;
case MCDI_EVENT_CODE_SENSOREVT:
efx_sensor_event(efx, event);
break;
case MCDI_EVENT_CODE_SCHEDERR:
netif_dbg(efx, hw, efx->net_dev,
"MC Scheduler alert (0x%x)\n", data);
break;
case MCDI_EVENT_CODE_REBOOT:
case MCDI_EVENT_CODE_MC_REBOOT:
netif_info(efx, hw, efx->net_dev, "MC Reboot\n");
efx_mcdi_ev_death(efx, -EIO);
break;
case MCDI_EVENT_CODE_MC_BIST:
netif_info(efx, hw, efx->net_dev, "MC entered BIST mode\n");
efx_mcdi_ev_bist(efx);
break;
case MCDI_EVENT_CODE_MAC_STATS_DMA:
/* MAC stats are gather lazily. We can ignore this. */
break;
case MCDI_EVENT_CODE_PTP_FAULT:
case MCDI_EVENT_CODE_PTP_PPS:
efx_ptp_event(efx, event);
break;
case MCDI_EVENT_CODE_PTP_TIME:
efx_time_sync_event(channel, event);
break;
case MCDI_EVENT_CODE_TX_FLUSH:
case MCDI_EVENT_CODE_RX_FLUSH:
/* Two flush events will be sent: one to the same event
* queue as completions, and one to event queue 0.
* In the latter case the {RX,TX}_FLUSH_TO_DRIVER
* flag will be set, and we should ignore the event
* because we want to wait for all completions.
*/
BUILD_BUG_ON(MCDI_EVENT_TX_FLUSH_TO_DRIVER_LBN !=
MCDI_EVENT_RX_FLUSH_TO_DRIVER_LBN);
if (!MCDI_EVENT_FIELD(*event, TX_FLUSH_TO_DRIVER))
efx_handle_drain_event(efx);
break;
case MCDI_EVENT_CODE_TX_ERR:
case MCDI_EVENT_CODE_RX_ERR:
netif_err(efx, hw, efx->net_dev,
"%s DMA error (event: "EFX_QWORD_FMT")\n",
code == MCDI_EVENT_CODE_TX_ERR ? "TX" : "RX",
EFX_QWORD_VAL(*event));
efx_schedule_reset(efx, RESET_TYPE_DMA_ERROR);
break;
case MCDI_EVENT_CODE_PROXY_RESPONSE:
efx_mcdi_ev_proxy_response(efx,
MCDI_EVENT_FIELD(*event, PROXY_RESPONSE_HANDLE),
MCDI_EVENT_FIELD(*event, PROXY_RESPONSE_RC));
break;
default:
netif_err(efx, hw, efx->net_dev,
"Unknown MCDI event " EFX_QWORD_FMT "\n",
EFX_QWORD_VAL(*event));
}
}
/**************************************************************************
*
* Specific request functions
*
**************************************************************************
*/
void efx_mcdi_print_fwver(struct efx_nic *efx, char *buf, size_t len)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_VERSION_OUT_LEN);
size_t outlength;
const __le16 *ver_words;
size_t offset;
int rc;
BUILD_BUG_ON(MC_CMD_GET_VERSION_IN_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_GET_VERSION, NULL, 0,
outbuf, sizeof(outbuf), &outlength);
if (rc)
goto fail;
if (outlength < MC_CMD_GET_VERSION_OUT_LEN) {
rc = -EIO;
goto fail;
}
ver_words = (__le16 *)MCDI_PTR(outbuf, GET_VERSION_OUT_VERSION);
offset = scnprintf(buf, len, "%u.%u.%u.%u",
le16_to_cpu(ver_words[0]),
le16_to_cpu(ver_words[1]),
le16_to_cpu(ver_words[2]),
le16_to_cpu(ver_words[3]));
if (efx->type->print_additional_fwver)
offset += efx->type->print_additional_fwver(efx, buf + offset,
len - offset);
/* It's theoretically possible for the string to exceed 31
* characters, though in practice the first three version
* components are short enough that this doesn't happen.
*/
if (WARN_ON(offset >= len))
buf[0] = 0;
return;
fail:
pci_err(efx->pci_dev, "%s: failed rc=%d\n", __func__, rc);
buf[0] = 0;
}
static int efx_mcdi_drv_attach(struct efx_nic *efx, bool driver_operating,
bool *was_attached)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_DRV_ATTACH_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_DRV_ATTACH_EXT_OUT_LEN);
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, DRV_ATTACH_IN_NEW_STATE,
driver_operating ? 1 : 0);
MCDI_SET_DWORD(inbuf, DRV_ATTACH_IN_UPDATE, 1);
MCDI_SET_DWORD(inbuf, DRV_ATTACH_IN_FIRMWARE_ID, MC_CMD_FW_LOW_LATENCY);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_DRV_ATTACH, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
/* If we're not the primary PF, trying to ATTACH with a FIRMWARE_ID
* specified will fail with EPERM, and we have to tell the MC we don't
* care what firmware we get.
*/
if (rc == -EPERM) {
pci_dbg(efx->pci_dev,
"%s with fw-variant setting failed EPERM, trying without it\n",
__func__);
MCDI_SET_DWORD(inbuf, DRV_ATTACH_IN_FIRMWARE_ID,
MC_CMD_FW_DONT_CARE);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_DRV_ATTACH, inbuf,
sizeof(inbuf), outbuf, sizeof(outbuf),
&outlen);
}
if (rc) {
efx_mcdi_display_error(efx, MC_CMD_DRV_ATTACH, sizeof(inbuf),
outbuf, outlen, rc);
goto fail;
}
if (outlen < MC_CMD_DRV_ATTACH_OUT_LEN) {
rc = -EIO;
goto fail;
}
if (driver_operating) {
if (outlen >= MC_CMD_DRV_ATTACH_EXT_OUT_LEN) {
efx->mcdi->fn_flags =
MCDI_DWORD(outbuf,
DRV_ATTACH_EXT_OUT_FUNC_FLAGS);
} else {
/* Synthesise flags for Siena */
efx->mcdi->fn_flags =
1 << MC_CMD_DRV_ATTACH_EXT_OUT_FLAG_LINKCTRL |
1 << MC_CMD_DRV_ATTACH_EXT_OUT_FLAG_TRUSTED |
(efx_port_num(efx) == 0) <<
MC_CMD_DRV_ATTACH_EXT_OUT_FLAG_PRIMARY;
}
}
/* We currently assume we have control of the external link
* and are completely trusted by firmware. Abort probing
* if that's not true for this function.
*/
if (was_attached != NULL)
*was_attached = MCDI_DWORD(outbuf, DRV_ATTACH_OUT_OLD_STATE);
return 0;
fail:
pci_err(efx->pci_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_get_board_cfg(struct efx_nic *efx, u8 *mac_address,
u16 *fw_subtype_list, u32 *capabilities)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_BOARD_CFG_OUT_LENMAX);
size_t outlen, i;
int port_num = efx_port_num(efx);
int rc;
BUILD_BUG_ON(MC_CMD_GET_BOARD_CFG_IN_LEN != 0);
/* we need __aligned(2) for ether_addr_copy */
BUILD_BUG_ON(MC_CMD_GET_BOARD_CFG_OUT_MAC_ADDR_BASE_PORT0_OFST & 1);
BUILD_BUG_ON(MC_CMD_GET_BOARD_CFG_OUT_MAC_ADDR_BASE_PORT1_OFST & 1);
rc = efx_mcdi_rpc(efx, MC_CMD_GET_BOARD_CFG, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_GET_BOARD_CFG_OUT_LENMIN) {
rc = -EIO;
goto fail;
}
if (mac_address)
ether_addr_copy(mac_address,
port_num ?
MCDI_PTR(outbuf, GET_BOARD_CFG_OUT_MAC_ADDR_BASE_PORT1) :
MCDI_PTR(outbuf, GET_BOARD_CFG_OUT_MAC_ADDR_BASE_PORT0));
if (fw_subtype_list) {
for (i = 0;
i < MCDI_VAR_ARRAY_LEN(outlen,
GET_BOARD_CFG_OUT_FW_SUBTYPE_LIST);
i++)
fw_subtype_list[i] = MCDI_ARRAY_WORD(
outbuf, GET_BOARD_CFG_OUT_FW_SUBTYPE_LIST, i);
for (; i < MC_CMD_GET_BOARD_CFG_OUT_FW_SUBTYPE_LIST_MAXNUM; i++)
fw_subtype_list[i] = 0;
}
if (capabilities) {
if (port_num)
*capabilities = MCDI_DWORD(outbuf,
GET_BOARD_CFG_OUT_CAPABILITIES_PORT1);
else
*capabilities = MCDI_DWORD(outbuf,
GET_BOARD_CFG_OUT_CAPABILITIES_PORT0);
}
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d len=%d\n",
__func__, rc, (int)outlen);
return rc;
}
int efx_mcdi_log_ctrl(struct efx_nic *efx, bool evq, bool uart, u32 dest_evq)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_LOG_CTRL_IN_LEN);
u32 dest = 0;
int rc;
if (uart)
dest |= MC_CMD_LOG_CTRL_IN_LOG_DEST_UART;
if (evq)
dest |= MC_CMD_LOG_CTRL_IN_LOG_DEST_EVQ;
MCDI_SET_DWORD(inbuf, LOG_CTRL_IN_LOG_DEST, dest);
MCDI_SET_DWORD(inbuf, LOG_CTRL_IN_LOG_DEST_EVQ, dest_evq);
BUILD_BUG_ON(MC_CMD_LOG_CTRL_OUT_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_LOG_CTRL, inbuf, sizeof(inbuf),
NULL, 0, NULL);
return rc;
}
int efx_mcdi_nvram_types(struct efx_nic *efx, u32 *nvram_types_out)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_NVRAM_TYPES_OUT_LEN);
size_t outlen;
int rc;
BUILD_BUG_ON(MC_CMD_NVRAM_TYPES_IN_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_TYPES, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_NVRAM_TYPES_OUT_LEN) {
rc = -EIO;
goto fail;
}
*nvram_types_out = MCDI_DWORD(outbuf, NVRAM_TYPES_OUT_TYPES);
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n",
__func__, rc);
return rc;
}
/* This function finds types using the new NVRAM_PARTITIONS mcdi. */
static int efx_new_mcdi_nvram_types(struct efx_nic *efx, u32 *number,
u32 *nvram_types)
{
efx_dword_t *outbuf = kzalloc(MC_CMD_NVRAM_PARTITIONS_OUT_LENMAX_MCDI2,
GFP_KERNEL);
size_t outlen;
int rc;
if (!outbuf)
return -ENOMEM;
BUILD_BUG_ON(MC_CMD_NVRAM_PARTITIONS_IN_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_PARTITIONS, NULL, 0,
outbuf, MC_CMD_NVRAM_PARTITIONS_OUT_LENMAX_MCDI2, &outlen);
if (rc)
goto fail;
*number = MCDI_DWORD(outbuf, NVRAM_PARTITIONS_OUT_NUM_PARTITIONS);
memcpy(nvram_types, MCDI_PTR(outbuf, NVRAM_PARTITIONS_OUT_TYPE_ID),
*number * sizeof(u32));
fail:
kfree(outbuf);
return rc;
}
int efx_mcdi_nvram_info(struct efx_nic *efx, unsigned int type,
size_t *size_out, size_t *erase_size_out,
bool *protected_out)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_NVRAM_INFO_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_NVRAM_INFO_OUT_LEN);
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_INFO_IN_TYPE, type);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_INFO, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_NVRAM_INFO_OUT_LEN) {
rc = -EIO;
goto fail;
}
*size_out = MCDI_DWORD(outbuf, NVRAM_INFO_OUT_SIZE);
*erase_size_out = MCDI_DWORD(outbuf, NVRAM_INFO_OUT_ERASESIZE);
*protected_out = !!(MCDI_DWORD(outbuf, NVRAM_INFO_OUT_FLAGS) &
(1 << MC_CMD_NVRAM_INFO_OUT_PROTECTED_LBN));
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
static int efx_mcdi_nvram_test(struct efx_nic *efx, unsigned int type)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_NVRAM_TEST_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_NVRAM_TEST_OUT_LEN);
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_TEST_IN_TYPE, type);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_TEST, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), NULL);
if (rc)
return rc;
switch (MCDI_DWORD(outbuf, NVRAM_TEST_OUT_RESULT)) {
case MC_CMD_NVRAM_TEST_PASS:
case MC_CMD_NVRAM_TEST_NOTSUPP:
return 0;
default:
return -EIO;
}
}
/* This function tests nvram partitions using the new mcdi partition lookup scheme */
int efx_new_mcdi_nvram_test_all(struct efx_nic *efx)
{
u32 *nvram_types = kzalloc(MC_CMD_NVRAM_PARTITIONS_OUT_LENMAX_MCDI2,
GFP_KERNEL);
unsigned int number;
int rc, i;
if (!nvram_types)
return -ENOMEM;
rc = efx_new_mcdi_nvram_types(efx, &number, nvram_types);
if (rc)
goto fail;
/* Require at least one check */
rc = -EAGAIN;
for (i = 0; i < number; i++) {
if (nvram_types[i] == NVRAM_PARTITION_TYPE_PARTITION_MAP ||
nvram_types[i] == NVRAM_PARTITION_TYPE_DYNAMIC_CONFIG)
continue;
rc = efx_mcdi_nvram_test(efx, nvram_types[i]);
if (rc)
goto fail;
}
fail:
kfree(nvram_types);
return rc;
}
int efx_mcdi_nvram_test_all(struct efx_nic *efx)
{
u32 nvram_types;
unsigned int type;
int rc;
rc = efx_mcdi_nvram_types(efx, &nvram_types);
if (rc)
goto fail1;
type = 0;
while (nvram_types != 0) {
if (nvram_types & 1) {
rc = efx_mcdi_nvram_test(efx, type);
if (rc)
goto fail2;
}
type++;
nvram_types >>= 1;
}
return 0;
fail2:
netif_err(efx, hw, efx->net_dev, "%s: failed type=%u\n",
__func__, type);
fail1:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
/* Returns 1 if an assertion was read, 0 if no assertion had fired,
* negative on error.
*/
static int efx_mcdi_read_assertion(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_GET_ASSERTS_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_ASSERTS_OUT_LEN);
unsigned int flags, index;
const char *reason;
size_t outlen;
int retry;
int rc;
/* Attempt to read any stored assertion state before we reboot
* the mcfw out of the assertion handler. Retry twice, once
* because a boot-time assertion might cause this command to fail
* with EINTR. And once again because GET_ASSERTS can race with
* MC_CMD_REBOOT running on the other port. */
retry = 2;
do {
MCDI_SET_DWORD(inbuf, GET_ASSERTS_IN_CLEAR, 1);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_GET_ASSERTS,
inbuf, MC_CMD_GET_ASSERTS_IN_LEN,
outbuf, sizeof(outbuf), &outlen);
if (rc == -EPERM)
return 0;
} while ((rc == -EINTR || rc == -EIO) && retry-- > 0);
if (rc) {
efx_mcdi_display_error(efx, MC_CMD_GET_ASSERTS,
MC_CMD_GET_ASSERTS_IN_LEN, outbuf,
outlen, rc);
return rc;
}
if (outlen < MC_CMD_GET_ASSERTS_OUT_LEN)
return -EIO;
/* Print out any recorded assertion state */
flags = MCDI_DWORD(outbuf, GET_ASSERTS_OUT_GLOBAL_FLAGS);
if (flags == MC_CMD_GET_ASSERTS_FLAGS_NO_FAILS)
return 0;
reason = (flags == MC_CMD_GET_ASSERTS_FLAGS_SYS_FAIL)
? "system-level assertion"
: (flags == MC_CMD_GET_ASSERTS_FLAGS_THR_FAIL)
? "thread-level assertion"
: (flags == MC_CMD_GET_ASSERTS_FLAGS_WDOG_FIRED)
? "watchdog reset"
: "unknown assertion";
netif_err(efx, hw, efx->net_dev,
"MCPU %s at PC = 0x%.8x in thread 0x%.8x\n", reason,
MCDI_DWORD(outbuf, GET_ASSERTS_OUT_SAVED_PC_OFFS),
MCDI_DWORD(outbuf, GET_ASSERTS_OUT_THREAD_OFFS));
/* Print out the registers */
for (index = 0;
index < MC_CMD_GET_ASSERTS_OUT_GP_REGS_OFFS_NUM;
index++)
netif_err(efx, hw, efx->net_dev, "R%.2d (?): 0x%.8x\n",
1 + index,
MCDI_ARRAY_DWORD(outbuf, GET_ASSERTS_OUT_GP_REGS_OFFS,
index));
return 1;
}
static int efx_mcdi_exit_assertion(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_REBOOT_IN_LEN);
int rc;
/* If the MC is running debug firmware, it might now be
* waiting for a debugger to attach, but we just want it to
* reboot. We set a flag that makes the command a no-op if it
* has already done so.
* The MCDI will thus return either 0 or -EIO.
*/
BUILD_BUG_ON(MC_CMD_REBOOT_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, REBOOT_IN_FLAGS,
MC_CMD_REBOOT_FLAGS_AFTER_ASSERTION);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_REBOOT, inbuf, MC_CMD_REBOOT_IN_LEN,
NULL, 0, NULL);
if (rc == -EIO)
rc = 0;
if (rc)
efx_mcdi_display_error(efx, MC_CMD_REBOOT, MC_CMD_REBOOT_IN_LEN,
NULL, 0, rc);
return rc;
}
int efx_mcdi_handle_assertion(struct efx_nic *efx)
{
int rc;
rc = efx_mcdi_read_assertion(efx);
if (rc <= 0)
return rc;
return efx_mcdi_exit_assertion(efx);
}
int efx_mcdi_set_id_led(struct efx_nic *efx, enum efx_led_mode mode)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_SET_ID_LED_IN_LEN);
BUILD_BUG_ON(EFX_LED_OFF != MC_CMD_LED_OFF);
BUILD_BUG_ON(EFX_LED_ON != MC_CMD_LED_ON);
BUILD_BUG_ON(EFX_LED_DEFAULT != MC_CMD_LED_DEFAULT);
BUILD_BUG_ON(MC_CMD_SET_ID_LED_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, SET_ID_LED_IN_STATE, mode);
return efx_mcdi_rpc(efx, MC_CMD_SET_ID_LED, inbuf, sizeof(inbuf), NULL, 0, NULL);
}
static int efx_mcdi_reset_func(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_ENTITY_RESET_IN_LEN);
int rc;
BUILD_BUG_ON(MC_CMD_ENTITY_RESET_OUT_LEN != 0);
MCDI_POPULATE_DWORD_1(inbuf, ENTITY_RESET_IN_FLAG,
ENTITY_RESET_IN_FUNCTION_RESOURCE_RESET, 1);
rc = efx_mcdi_rpc(efx, MC_CMD_ENTITY_RESET, inbuf, sizeof(inbuf),
NULL, 0, NULL);
return rc;
}
static int efx_mcdi_reset_mc(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_REBOOT_IN_LEN);
int rc;
BUILD_BUG_ON(MC_CMD_REBOOT_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, REBOOT_IN_FLAGS, 0);
rc = efx_mcdi_rpc(efx, MC_CMD_REBOOT, inbuf, sizeof(inbuf),
NULL, 0, NULL);
/* White is black, and up is down */
if (rc == -EIO)
return 0;
if (rc == 0)
rc = -EIO;
return rc;
}
enum reset_type efx_mcdi_map_reset_reason(enum reset_type reason)
{
return RESET_TYPE_RECOVER_OR_ALL;
}
int efx_mcdi_reset(struct efx_nic *efx, enum reset_type method)
{
int rc;
/* If MCDI is down, we can't handle_assertion */
if (method == RESET_TYPE_MCDI_TIMEOUT) {
rc = pci_reset_function(efx->pci_dev);
if (rc)
return rc;
/* Re-enable polled MCDI completion */
if (efx->mcdi) {
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
mcdi->mode = MCDI_MODE_POLL;
}
return 0;
}
/* Recover from a failed assertion pre-reset */
rc = efx_mcdi_handle_assertion(efx);
if (rc)
return rc;
if (method == RESET_TYPE_DATAPATH)
return 0;
else if (method == RESET_TYPE_WORLD)
return efx_mcdi_reset_mc(efx);
else
return efx_mcdi_reset_func(efx);
}
static int efx_mcdi_wol_filter_set(struct efx_nic *efx, u32 type,
const u8 *mac, int *id_out)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_WOL_FILTER_SET_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_WOL_FILTER_SET_OUT_LEN);
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, WOL_FILTER_SET_IN_WOL_TYPE, type);
MCDI_SET_DWORD(inbuf, WOL_FILTER_SET_IN_FILTER_MODE,
MC_CMD_FILTER_MODE_SIMPLE);
ether_addr_copy(MCDI_PTR(inbuf, WOL_FILTER_SET_IN_MAGIC_MAC), mac);
rc = efx_mcdi_rpc(efx, MC_CMD_WOL_FILTER_SET, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_WOL_FILTER_SET_OUT_LEN) {
rc = -EIO;
goto fail;
}
*id_out = (int)MCDI_DWORD(outbuf, WOL_FILTER_SET_OUT_FILTER_ID);
return 0;
fail:
*id_out = -1;
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int
efx_mcdi_wol_filter_set_magic(struct efx_nic *efx, const u8 *mac, int *id_out)
{
return efx_mcdi_wol_filter_set(efx, MC_CMD_WOL_TYPE_MAGIC, mac, id_out);
}
int efx_mcdi_wol_filter_get_magic(struct efx_nic *efx, int *id_out)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_WOL_FILTER_GET_OUT_LEN);
size_t outlen;
int rc;
rc = efx_mcdi_rpc(efx, MC_CMD_WOL_FILTER_GET, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_WOL_FILTER_GET_OUT_LEN) {
rc = -EIO;
goto fail;
}
*id_out = (int)MCDI_DWORD(outbuf, WOL_FILTER_GET_OUT_FILTER_ID);
return 0;
fail:
*id_out = -1;
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_wol_filter_remove(struct efx_nic *efx, int id)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_WOL_FILTER_REMOVE_IN_LEN);
int rc;
MCDI_SET_DWORD(inbuf, WOL_FILTER_REMOVE_IN_FILTER_ID, (u32)id);
rc = efx_mcdi_rpc(efx, MC_CMD_WOL_FILTER_REMOVE, inbuf, sizeof(inbuf),
NULL, 0, NULL);
return rc;
}
int efx_mcdi_flush_rxqs(struct efx_nic *efx)
{
struct efx_channel *channel;
struct efx_rx_queue *rx_queue;
MCDI_DECLARE_BUF(inbuf,
MC_CMD_FLUSH_RX_QUEUES_IN_LEN(EFX_MAX_CHANNELS));
int rc, count;
BUILD_BUG_ON(EFX_MAX_CHANNELS >
MC_CMD_FLUSH_RX_QUEUES_IN_QID_OFST_MAXNUM);
count = 0;
efx_for_each_channel(channel, efx) {
efx_for_each_channel_rx_queue(rx_queue, channel) {
if (rx_queue->flush_pending) {
rx_queue->flush_pending = false;
atomic_dec(&efx->rxq_flush_pending);
MCDI_SET_ARRAY_DWORD(
inbuf, FLUSH_RX_QUEUES_IN_QID_OFST,
count, efx_rx_queue_index(rx_queue));
count++;
}
}
}
rc = efx_mcdi_rpc(efx, MC_CMD_FLUSH_RX_QUEUES, inbuf,
MC_CMD_FLUSH_RX_QUEUES_IN_LEN(count), NULL, 0, NULL);
WARN_ON(rc < 0);
return rc;
}
int efx_mcdi_wol_filter_reset(struct efx_nic *efx)
{
int rc;
rc = efx_mcdi_rpc(efx, MC_CMD_WOL_FILTER_RESET, NULL, 0, NULL, 0, NULL);
return rc;
}
int efx_mcdi_set_workaround(struct efx_nic *efx, u32 type, bool enabled,
unsigned int *flags)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_WORKAROUND_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_WORKAROUND_EXT_OUT_LEN);
size_t outlen;
int rc;
BUILD_BUG_ON(MC_CMD_WORKAROUND_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, WORKAROUND_IN_TYPE, type);
MCDI_SET_DWORD(inbuf, WORKAROUND_IN_ENABLED, enabled);
rc = efx_mcdi_rpc(efx, MC_CMD_WORKAROUND, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (!flags)
return 0;
if (outlen >= MC_CMD_WORKAROUND_EXT_OUT_LEN)
*flags = MCDI_DWORD(outbuf, WORKAROUND_EXT_OUT_FLAGS);
else
*flags = 0;
return 0;
}
int efx_mcdi_get_workarounds(struct efx_nic *efx, unsigned int *impl_out,
unsigned int *enabled_out)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_WORKAROUNDS_OUT_LEN);
size_t outlen;
int rc;
rc = efx_mcdi_rpc(efx, MC_CMD_GET_WORKAROUNDS, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_GET_WORKAROUNDS_OUT_LEN) {
rc = -EIO;
goto fail;
}
if (impl_out)
*impl_out = MCDI_DWORD(outbuf, GET_WORKAROUNDS_OUT_IMPLEMENTED);
if (enabled_out)
*enabled_out = MCDI_DWORD(outbuf, GET_WORKAROUNDS_OUT_ENABLED);
return 0;
fail:
/* Older firmware lacks GET_WORKAROUNDS and this isn't especially
* terrifying. The call site will have to deal with it though.
*/
netif_cond_dbg(efx, hw, efx->net_dev, rc == -ENOSYS, err,
"%s: failed rc=%d\n", __func__, rc);
return rc;
}
/* Failure to read a privilege mask is never fatal, because we can always
* carry on as though we didn't have the privilege we were interested in.
* So use efx_mcdi_rpc_quiet().
*/
int efx_mcdi_get_privilege_mask(struct efx_nic *efx, u32 *mask)
{
MCDI_DECLARE_BUF(fi_outbuf, MC_CMD_GET_FUNCTION_INFO_OUT_LEN);
MCDI_DECLARE_BUF(pm_inbuf, MC_CMD_PRIVILEGE_MASK_IN_LEN);
MCDI_DECLARE_BUF(pm_outbuf, MC_CMD_PRIVILEGE_MASK_OUT_LEN);
size_t outlen;
u16 pf, vf;
int rc;
if (!efx || !mask)
return -EINVAL;
/* Get our function number */
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_GET_FUNCTION_INFO, NULL, 0,
fi_outbuf, MC_CMD_GET_FUNCTION_INFO_OUT_LEN,
&outlen);
if (rc != 0)
return rc;
if (outlen < MC_CMD_GET_FUNCTION_INFO_OUT_LEN)
return -EIO;
pf = MCDI_DWORD(fi_outbuf, GET_FUNCTION_INFO_OUT_PF);
vf = MCDI_DWORD(fi_outbuf, GET_FUNCTION_INFO_OUT_VF);
MCDI_POPULATE_DWORD_2(pm_inbuf, PRIVILEGE_MASK_IN_FUNCTION,
PRIVILEGE_MASK_IN_FUNCTION_PF, pf,
PRIVILEGE_MASK_IN_FUNCTION_VF, vf);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_PRIVILEGE_MASK,
pm_inbuf, sizeof(pm_inbuf),
pm_outbuf, sizeof(pm_outbuf), &outlen);
if (rc != 0)
return rc;
if (outlen < MC_CMD_PRIVILEGE_MASK_OUT_LEN)
return -EIO;
*mask = MCDI_DWORD(pm_outbuf, PRIVILEGE_MASK_OUT_OLD_MASK);
return 0;
}
int efx_mcdi_nvram_metadata(struct efx_nic *efx, unsigned int type,
u32 *subtype, u16 version[4], char *desc,
size_t descsize)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_NVRAM_METADATA_IN_LEN);
efx_dword_t *outbuf;
size_t outlen;
u32 flags;
int rc;
outbuf = kzalloc(MC_CMD_NVRAM_METADATA_OUT_LENMAX_MCDI2, GFP_KERNEL);
if (!outbuf)
return -ENOMEM;
MCDI_SET_DWORD(inbuf, NVRAM_METADATA_IN_TYPE, type);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_NVRAM_METADATA, inbuf,
sizeof(inbuf), outbuf,
MC_CMD_NVRAM_METADATA_OUT_LENMAX_MCDI2,
&outlen);
if (rc)
goto out_free;
if (outlen < MC_CMD_NVRAM_METADATA_OUT_LENMIN) {
rc = -EIO;
goto out_free;
}
flags = MCDI_DWORD(outbuf, NVRAM_METADATA_OUT_FLAGS);
if (desc && descsize > 0) {
if (flags & BIT(MC_CMD_NVRAM_METADATA_OUT_DESCRIPTION_VALID_LBN)) {
if (descsize <=
MC_CMD_NVRAM_METADATA_OUT_DESCRIPTION_NUM(outlen)) {
rc = -E2BIG;
goto out_free;
}
strncpy(desc,
MCDI_PTR(outbuf, NVRAM_METADATA_OUT_DESCRIPTION),
MC_CMD_NVRAM_METADATA_OUT_DESCRIPTION_NUM(outlen));
desc[MC_CMD_NVRAM_METADATA_OUT_DESCRIPTION_NUM(outlen)] = '\0';
} else {
desc[0] = '\0';
}
}
if (subtype) {
if (flags & BIT(MC_CMD_NVRAM_METADATA_OUT_SUBTYPE_VALID_LBN))
*subtype = MCDI_DWORD(outbuf, NVRAM_METADATA_OUT_SUBTYPE);
else
*subtype = 0;
}
if (version) {
if (flags & BIT(MC_CMD_NVRAM_METADATA_OUT_VERSION_VALID_LBN)) {
version[0] = MCDI_WORD(outbuf, NVRAM_METADATA_OUT_VERSION_W);
version[1] = MCDI_WORD(outbuf, NVRAM_METADATA_OUT_VERSION_X);
version[2] = MCDI_WORD(outbuf, NVRAM_METADATA_OUT_VERSION_Y);
version[3] = MCDI_WORD(outbuf, NVRAM_METADATA_OUT_VERSION_Z);
} else {
version[0] = 0;
version[1] = 0;
version[2] = 0;
version[3] = 0;
}
}
out_free:
kfree(outbuf);
return rc;
}
#ifdef CONFIG_SFC_MTD
#define EFX_MCDI_NVRAM_LEN_MAX 128
static int efx_mcdi_nvram_update_start(struct efx_nic *efx, unsigned int type)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_NVRAM_UPDATE_START_V2_IN_LEN);
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_UPDATE_START_IN_TYPE, type);
MCDI_POPULATE_DWORD_1(inbuf, NVRAM_UPDATE_START_V2_IN_FLAGS,
NVRAM_UPDATE_START_V2_IN_FLAG_REPORT_VERIFY_RESULT,
1);
BUILD_BUG_ON(MC_CMD_NVRAM_UPDATE_START_OUT_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_UPDATE_START, inbuf, sizeof(inbuf),
NULL, 0, NULL);
return rc;
}
static int efx_mcdi_nvram_read(struct efx_nic *efx, unsigned int type,
loff_t offset, u8 *buffer, size_t length)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_NVRAM_READ_IN_V2_LEN);
MCDI_DECLARE_BUF(outbuf,
MC_CMD_NVRAM_READ_OUT_LEN(EFX_MCDI_NVRAM_LEN_MAX));
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_READ_IN_TYPE, type);
MCDI_SET_DWORD(inbuf, NVRAM_READ_IN_OFFSET, offset);
MCDI_SET_DWORD(inbuf, NVRAM_READ_IN_LENGTH, length);
MCDI_SET_DWORD(inbuf, NVRAM_READ_IN_V2_MODE,
MC_CMD_NVRAM_READ_IN_V2_DEFAULT);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_READ, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
memcpy(buffer, MCDI_PTR(outbuf, NVRAM_READ_OUT_READ_BUFFER), length);
return 0;
}
static int efx_mcdi_nvram_write(struct efx_nic *efx, unsigned int type,
loff_t offset, const u8 *buffer, size_t length)
{
MCDI_DECLARE_BUF(inbuf,
MC_CMD_NVRAM_WRITE_IN_LEN(EFX_MCDI_NVRAM_LEN_MAX));
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_WRITE_IN_TYPE, type);
MCDI_SET_DWORD(inbuf, NVRAM_WRITE_IN_OFFSET, offset);
MCDI_SET_DWORD(inbuf, NVRAM_WRITE_IN_LENGTH, length);
memcpy(MCDI_PTR(inbuf, NVRAM_WRITE_IN_WRITE_BUFFER), buffer, length);
BUILD_BUG_ON(MC_CMD_NVRAM_WRITE_OUT_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_WRITE, inbuf,
ALIGN(MC_CMD_NVRAM_WRITE_IN_LEN(length), 4),
NULL, 0, NULL);
return rc;
}
static int efx_mcdi_nvram_erase(struct efx_nic *efx, unsigned int type,
loff_t offset, size_t length)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_NVRAM_ERASE_IN_LEN);
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_ERASE_IN_TYPE, type);
MCDI_SET_DWORD(inbuf, NVRAM_ERASE_IN_OFFSET, offset);
MCDI_SET_DWORD(inbuf, NVRAM_ERASE_IN_LENGTH, length);
BUILD_BUG_ON(MC_CMD_NVRAM_ERASE_OUT_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_ERASE, inbuf, sizeof(inbuf),
NULL, 0, NULL);
return rc;
}
static int efx_mcdi_nvram_update_finish(struct efx_nic *efx, unsigned int type)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_NVRAM_UPDATE_FINISH_V2_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_NVRAM_UPDATE_FINISH_V2_OUT_LEN);
size_t outlen;
int rc, rc2;
MCDI_SET_DWORD(inbuf, NVRAM_UPDATE_FINISH_IN_TYPE, type);
/* Always set this flag. Old firmware ignores it */
MCDI_POPULATE_DWORD_1(inbuf, NVRAM_UPDATE_FINISH_V2_IN_FLAGS,
NVRAM_UPDATE_FINISH_V2_IN_FLAG_REPORT_VERIFY_RESULT,
1);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_UPDATE_FINISH, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (!rc && outlen >= MC_CMD_NVRAM_UPDATE_FINISH_V2_OUT_LEN) {
rc2 = MCDI_DWORD(outbuf, NVRAM_UPDATE_FINISH_V2_OUT_RESULT_CODE);
if (rc2 != MC_CMD_NVRAM_VERIFY_RC_SUCCESS)
netif_err(efx, drv, efx->net_dev,
"NVRAM update failed verification with code 0x%x\n",
rc2);
switch (rc2) {
case MC_CMD_NVRAM_VERIFY_RC_SUCCESS:
break;
case MC_CMD_NVRAM_VERIFY_RC_CMS_CHECK_FAILED:
case MC_CMD_NVRAM_VERIFY_RC_MESSAGE_DIGEST_CHECK_FAILED:
case MC_CMD_NVRAM_VERIFY_RC_SIGNATURE_CHECK_FAILED:
case MC_CMD_NVRAM_VERIFY_RC_TRUSTED_APPROVERS_CHECK_FAILED:
case MC_CMD_NVRAM_VERIFY_RC_SIGNATURE_CHAIN_CHECK_FAILED:
rc = -EIO;
break;
case MC_CMD_NVRAM_VERIFY_RC_INVALID_CMS_FORMAT:
case MC_CMD_NVRAM_VERIFY_RC_BAD_MESSAGE_DIGEST:
rc = -EINVAL;
break;
case MC_CMD_NVRAM_VERIFY_RC_NO_VALID_SIGNATURES:
case MC_CMD_NVRAM_VERIFY_RC_NO_TRUSTED_APPROVERS:
case MC_CMD_NVRAM_VERIFY_RC_NO_SIGNATURE_MATCH:
rc = -EPERM;
break;
default:
netif_err(efx, drv, efx->net_dev,
"Unknown response to NVRAM_UPDATE_FINISH\n");
rc = -EIO;
}
}
return rc;
}
int efx_mcdi_mtd_read(struct mtd_info *mtd, loff_t start,
size_t len, size_t *retlen, u8 *buffer)
{
struct efx_mcdi_mtd_partition *part = to_efx_mcdi_mtd_partition(mtd);
struct efx_nic *efx = mtd->priv;
loff_t offset = start;
loff_t end = min_t(loff_t, start + len, mtd->size);
size_t chunk;
int rc = 0;
while (offset < end) {
chunk = min_t(size_t, end - offset, EFX_MCDI_NVRAM_LEN_MAX);
rc = efx_mcdi_nvram_read(efx, part->nvram_type, offset,
buffer, chunk);
if (rc)
goto out;
offset += chunk;
buffer += chunk;
}
out:
*retlen = offset - start;
return rc;
}
int efx_mcdi_mtd_erase(struct mtd_info *mtd, loff_t start, size_t len)
{
struct efx_mcdi_mtd_partition *part = to_efx_mcdi_mtd_partition(mtd);
struct efx_nic *efx = mtd->priv;
loff_t offset = start & ~((loff_t)(mtd->erasesize - 1));
loff_t end = min_t(loff_t, start + len, mtd->size);
size_t chunk = part->common.mtd.erasesize;
int rc = 0;
if (!part->updating) {
rc = efx_mcdi_nvram_update_start(efx, part->nvram_type);
if (rc)
goto out;
part->updating = true;
}
/* The MCDI interface can in fact do multiple erase blocks at once;
* but erasing may be slow, so we make multiple calls here to avoid
* tripping the MCDI RPC timeout. */
while (offset < end) {
rc = efx_mcdi_nvram_erase(efx, part->nvram_type, offset,
chunk);
if (rc)
goto out;
offset += chunk;
}
out:
return rc;
}
int efx_mcdi_mtd_write(struct mtd_info *mtd, loff_t start,
size_t len, size_t *retlen, const u8 *buffer)
{
struct efx_mcdi_mtd_partition *part = to_efx_mcdi_mtd_partition(mtd);
struct efx_nic *efx = mtd->priv;
loff_t offset = start;
loff_t end = min_t(loff_t, start + len, mtd->size);
size_t chunk;
int rc = 0;
if (!part->updating) {
rc = efx_mcdi_nvram_update_start(efx, part->nvram_type);
if (rc)
goto out;
part->updating = true;
}
while (offset < end) {
chunk = min_t(size_t, end - offset, EFX_MCDI_NVRAM_LEN_MAX);
rc = efx_mcdi_nvram_write(efx, part->nvram_type, offset,
buffer, chunk);
if (rc)
goto out;
offset += chunk;
buffer += chunk;
}
out:
*retlen = offset - start;
return rc;
}
int efx_mcdi_mtd_sync(struct mtd_info *mtd)
{
struct efx_mcdi_mtd_partition *part = to_efx_mcdi_mtd_partition(mtd);
struct efx_nic *efx = mtd->priv;
int rc = 0;
if (part->updating) {
part->updating = false;
rc = efx_mcdi_nvram_update_finish(efx, part->nvram_type);
}
return rc;
}
void efx_mcdi_mtd_rename(struct efx_mtd_partition *part)
{
struct efx_mcdi_mtd_partition *mcdi_part =
container_of(part, struct efx_mcdi_mtd_partition, common);
struct efx_nic *efx = part->mtd.priv;
snprintf(part->name, sizeof(part->name), "%s %s:%02x",
efx->name, part->type_name, mcdi_part->fw_subtype);
}
#endif /* CONFIG_SFC_MTD */
|
linux-master
|
drivers/net/ethernet/sfc/mcdi.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2018 Solarflare Communications Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include "net_driver.h"
#include <linux/module.h>
#include <linux/iommu.h>
#include "efx.h"
#include "nic.h"
#include "rx_common.h"
/* This is the percentage fill level below which new RX descriptors
* will be added to the RX descriptor ring.
*/
static unsigned int rx_refill_threshold;
module_param(rx_refill_threshold, uint, 0444);
MODULE_PARM_DESC(rx_refill_threshold,
"RX descriptor ring refill threshold (%)");
/* RX maximum head room required.
*
* This must be at least 1 to prevent overflow, plus one packet-worth
* to allow pipelined receives.
*/
#define EFX_RXD_HEAD_ROOM (1 + EFX_RX_MAX_FRAGS)
/* Check the RX page recycle ring for a page that can be reused. */
static struct page *efx_reuse_page(struct efx_rx_queue *rx_queue)
{
struct efx_nic *efx = rx_queue->efx;
struct efx_rx_page_state *state;
unsigned int index;
struct page *page;
if (unlikely(!rx_queue->page_ring))
return NULL;
index = rx_queue->page_remove & rx_queue->page_ptr_mask;
page = rx_queue->page_ring[index];
if (page == NULL)
return NULL;
rx_queue->page_ring[index] = NULL;
/* page_remove cannot exceed page_add. */
if (rx_queue->page_remove != rx_queue->page_add)
++rx_queue->page_remove;
/* If page_count is 1 then we hold the only reference to this page. */
if (page_count(page) == 1) {
++rx_queue->page_recycle_count;
return page;
} else {
state = page_address(page);
dma_unmap_page(&efx->pci_dev->dev, state->dma_addr,
PAGE_SIZE << efx->rx_buffer_order,
DMA_FROM_DEVICE);
put_page(page);
++rx_queue->page_recycle_failed;
}
return NULL;
}
/* Attempt to recycle the page if there is an RX recycle ring; the page can
* only be added if this is the final RX buffer, to prevent pages being used in
* the descriptor ring and appearing in the recycle ring simultaneously.
*/
static void efx_recycle_rx_page(struct efx_channel *channel,
struct efx_rx_buffer *rx_buf)
{
struct efx_rx_queue *rx_queue = efx_channel_get_rx_queue(channel);
struct efx_nic *efx = rx_queue->efx;
struct page *page = rx_buf->page;
unsigned int index;
/* Only recycle the page after processing the final buffer. */
if (!(rx_buf->flags & EFX_RX_BUF_LAST_IN_PAGE))
return;
index = rx_queue->page_add & rx_queue->page_ptr_mask;
if (rx_queue->page_ring[index] == NULL) {
unsigned int read_index = rx_queue->page_remove &
rx_queue->page_ptr_mask;
/* The next slot in the recycle ring is available, but
* increment page_remove if the read pointer currently
* points here.
*/
if (read_index == index)
++rx_queue->page_remove;
rx_queue->page_ring[index] = page;
++rx_queue->page_add;
return;
}
++rx_queue->page_recycle_full;
efx_unmap_rx_buffer(efx, rx_buf);
put_page(rx_buf->page);
}
/* Recycle the pages that are used by buffers that have just been received. */
void efx_recycle_rx_pages(struct efx_channel *channel,
struct efx_rx_buffer *rx_buf,
unsigned int n_frags)
{
struct efx_rx_queue *rx_queue = efx_channel_get_rx_queue(channel);
if (unlikely(!rx_queue->page_ring))
return;
do {
efx_recycle_rx_page(channel, rx_buf);
rx_buf = efx_rx_buf_next(rx_queue, rx_buf);
} while (--n_frags);
}
void efx_discard_rx_packet(struct efx_channel *channel,
struct efx_rx_buffer *rx_buf,
unsigned int n_frags)
{
struct efx_rx_queue *rx_queue = efx_channel_get_rx_queue(channel);
efx_recycle_rx_pages(channel, rx_buf, n_frags);
efx_free_rx_buffers(rx_queue, rx_buf, n_frags);
}
static void efx_init_rx_recycle_ring(struct efx_rx_queue *rx_queue)
{
unsigned int bufs_in_recycle_ring, page_ring_size;
struct efx_nic *efx = rx_queue->efx;
bufs_in_recycle_ring = efx_rx_recycle_ring_size(efx);
page_ring_size = roundup_pow_of_two(bufs_in_recycle_ring /
efx->rx_bufs_per_page);
rx_queue->page_ring = kcalloc(page_ring_size,
sizeof(*rx_queue->page_ring), GFP_KERNEL);
if (!rx_queue->page_ring)
rx_queue->page_ptr_mask = 0;
else
rx_queue->page_ptr_mask = page_ring_size - 1;
}
static void efx_fini_rx_recycle_ring(struct efx_rx_queue *rx_queue)
{
struct efx_nic *efx = rx_queue->efx;
int i;
if (unlikely(!rx_queue->page_ring))
return;
/* Unmap and release the pages in the recycle ring. Remove the ring. */
for (i = 0; i <= rx_queue->page_ptr_mask; i++) {
struct page *page = rx_queue->page_ring[i];
struct efx_rx_page_state *state;
if (page == NULL)
continue;
state = page_address(page);
dma_unmap_page(&efx->pci_dev->dev, state->dma_addr,
PAGE_SIZE << efx->rx_buffer_order,
DMA_FROM_DEVICE);
put_page(page);
}
kfree(rx_queue->page_ring);
rx_queue->page_ring = NULL;
}
static void efx_fini_rx_buffer(struct efx_rx_queue *rx_queue,
struct efx_rx_buffer *rx_buf)
{
/* Release the page reference we hold for the buffer. */
if (rx_buf->page)
put_page(rx_buf->page);
/* If this is the last buffer in a page, unmap and free it. */
if (rx_buf->flags & EFX_RX_BUF_LAST_IN_PAGE) {
efx_unmap_rx_buffer(rx_queue->efx, rx_buf);
efx_free_rx_buffers(rx_queue, rx_buf, 1);
}
rx_buf->page = NULL;
}
int efx_probe_rx_queue(struct efx_rx_queue *rx_queue)
{
struct efx_nic *efx = rx_queue->efx;
unsigned int entries;
int rc;
/* Create the smallest power-of-two aligned ring */
entries = max(roundup_pow_of_two(efx->rxq_entries), EFX_MIN_DMAQ_SIZE);
EFX_WARN_ON_PARANOID(entries > EFX_MAX_DMAQ_SIZE);
rx_queue->ptr_mask = entries - 1;
netif_dbg(efx, probe, efx->net_dev,
"creating RX queue %d size %#x mask %#x\n",
efx_rx_queue_index(rx_queue), efx->rxq_entries,
rx_queue->ptr_mask);
/* Allocate RX buffers */
rx_queue->buffer = kcalloc(entries, sizeof(*rx_queue->buffer),
GFP_KERNEL);
if (!rx_queue->buffer)
return -ENOMEM;
rc = efx_nic_probe_rx(rx_queue);
if (rc) {
kfree(rx_queue->buffer);
rx_queue->buffer = NULL;
}
return rc;
}
void efx_init_rx_queue(struct efx_rx_queue *rx_queue)
{
unsigned int max_fill, trigger, max_trigger;
struct efx_nic *efx = rx_queue->efx;
int rc = 0;
netif_dbg(rx_queue->efx, drv, rx_queue->efx->net_dev,
"initialising RX queue %d\n", efx_rx_queue_index(rx_queue));
/* Initialise ptr fields */
rx_queue->added_count = 0;
rx_queue->notified_count = 0;
rx_queue->granted_count = 0;
rx_queue->removed_count = 0;
rx_queue->min_fill = -1U;
efx_init_rx_recycle_ring(rx_queue);
rx_queue->page_remove = 0;
rx_queue->page_add = rx_queue->page_ptr_mask + 1;
rx_queue->page_recycle_count = 0;
rx_queue->page_recycle_failed = 0;
rx_queue->page_recycle_full = 0;
/* Initialise limit fields */
max_fill = efx->rxq_entries - EFX_RXD_HEAD_ROOM;
max_trigger =
max_fill - efx->rx_pages_per_batch * efx->rx_bufs_per_page;
if (rx_refill_threshold != 0) {
trigger = max_fill * min(rx_refill_threshold, 100U) / 100U;
if (trigger > max_trigger)
trigger = max_trigger;
} else {
trigger = max_trigger;
}
rx_queue->max_fill = max_fill;
rx_queue->fast_fill_trigger = trigger;
rx_queue->refill_enabled = true;
/* Initialise XDP queue information */
rc = xdp_rxq_info_reg(&rx_queue->xdp_rxq_info, efx->net_dev,
rx_queue->core_index, 0);
if (rc) {
netif_err(efx, rx_err, efx->net_dev,
"Failure to initialise XDP queue information rc=%d\n",
rc);
efx->xdp_rxq_info_failed = true;
} else {
rx_queue->xdp_rxq_info_valid = true;
}
/* Set up RX descriptor ring */
efx_nic_init_rx(rx_queue);
}
void efx_fini_rx_queue(struct efx_rx_queue *rx_queue)
{
struct efx_rx_buffer *rx_buf;
int i;
netif_dbg(rx_queue->efx, drv, rx_queue->efx->net_dev,
"shutting down RX queue %d\n", efx_rx_queue_index(rx_queue));
del_timer_sync(&rx_queue->slow_fill);
if (rx_queue->grant_credits)
flush_work(&rx_queue->grant_work);
/* Release RX buffers from the current read ptr to the write ptr */
if (rx_queue->buffer) {
for (i = rx_queue->removed_count; i < rx_queue->added_count;
i++) {
unsigned int index = i & rx_queue->ptr_mask;
rx_buf = efx_rx_buffer(rx_queue, index);
efx_fini_rx_buffer(rx_queue, rx_buf);
}
}
efx_fini_rx_recycle_ring(rx_queue);
if (rx_queue->xdp_rxq_info_valid)
xdp_rxq_info_unreg(&rx_queue->xdp_rxq_info);
rx_queue->xdp_rxq_info_valid = false;
}
void efx_remove_rx_queue(struct efx_rx_queue *rx_queue)
{
netif_dbg(rx_queue->efx, drv, rx_queue->efx->net_dev,
"destroying RX queue %d\n", efx_rx_queue_index(rx_queue));
efx_nic_remove_rx(rx_queue);
kfree(rx_queue->buffer);
rx_queue->buffer = NULL;
}
/* Unmap a DMA-mapped page. This function is only called for the final RX
* buffer in a page.
*/
void efx_unmap_rx_buffer(struct efx_nic *efx,
struct efx_rx_buffer *rx_buf)
{
struct page *page = rx_buf->page;
if (page) {
struct efx_rx_page_state *state = page_address(page);
dma_unmap_page(&efx->pci_dev->dev,
state->dma_addr,
PAGE_SIZE << efx->rx_buffer_order,
DMA_FROM_DEVICE);
}
}
void efx_free_rx_buffers(struct efx_rx_queue *rx_queue,
struct efx_rx_buffer *rx_buf,
unsigned int num_bufs)
{
do {
if (rx_buf->page) {
put_page(rx_buf->page);
rx_buf->page = NULL;
}
rx_buf = efx_rx_buf_next(rx_queue, rx_buf);
} while (--num_bufs);
}
void efx_rx_slow_fill(struct timer_list *t)
{
struct efx_rx_queue *rx_queue = from_timer(rx_queue, t, slow_fill);
/* Post an event to cause NAPI to run and refill the queue */
efx_nic_generate_fill_event(rx_queue);
++rx_queue->slow_fill_count;
}
void efx_schedule_slow_fill(struct efx_rx_queue *rx_queue)
{
mod_timer(&rx_queue->slow_fill, jiffies + msecs_to_jiffies(10));
}
/* efx_init_rx_buffers - create EFX_RX_BATCH page-based RX buffers
*
* @rx_queue: Efx RX queue
*
* This allocates a batch of pages, maps them for DMA, and populates
* struct efx_rx_buffers for each one. Return a negative error code or
* 0 on success. If a single page can be used for multiple buffers,
* then the page will either be inserted fully, or not at all.
*/
static int efx_init_rx_buffers(struct efx_rx_queue *rx_queue, bool atomic)
{
unsigned int page_offset, index, count;
struct efx_nic *efx = rx_queue->efx;
struct efx_rx_page_state *state;
struct efx_rx_buffer *rx_buf;
dma_addr_t dma_addr;
struct page *page;
count = 0;
do {
page = efx_reuse_page(rx_queue);
if (page == NULL) {
page = alloc_pages(__GFP_COMP |
(atomic ? GFP_ATOMIC : GFP_KERNEL),
efx->rx_buffer_order);
if (unlikely(page == NULL))
return -ENOMEM;
dma_addr =
dma_map_page(&efx->pci_dev->dev, page, 0,
PAGE_SIZE << efx->rx_buffer_order,
DMA_FROM_DEVICE);
if (unlikely(dma_mapping_error(&efx->pci_dev->dev,
dma_addr))) {
__free_pages(page, efx->rx_buffer_order);
return -EIO;
}
state = page_address(page);
state->dma_addr = dma_addr;
} else {
state = page_address(page);
dma_addr = state->dma_addr;
}
dma_addr += sizeof(struct efx_rx_page_state);
page_offset = sizeof(struct efx_rx_page_state);
do {
index = rx_queue->added_count & rx_queue->ptr_mask;
rx_buf = efx_rx_buffer(rx_queue, index);
rx_buf->dma_addr = dma_addr + efx->rx_ip_align +
EFX_XDP_HEADROOM;
rx_buf->page = page;
rx_buf->page_offset = page_offset + efx->rx_ip_align +
EFX_XDP_HEADROOM;
rx_buf->len = efx->rx_dma_len;
rx_buf->flags = 0;
++rx_queue->added_count;
get_page(page);
dma_addr += efx->rx_page_buf_step;
page_offset += efx->rx_page_buf_step;
} while (page_offset + efx->rx_page_buf_step <= PAGE_SIZE);
rx_buf->flags = EFX_RX_BUF_LAST_IN_PAGE;
} while (++count < efx->rx_pages_per_batch);
return 0;
}
void efx_rx_config_page_split(struct efx_nic *efx)
{
efx->rx_page_buf_step = ALIGN(efx->rx_dma_len + efx->rx_ip_align +
EFX_XDP_HEADROOM + EFX_XDP_TAILROOM,
EFX_RX_BUF_ALIGNMENT);
efx->rx_bufs_per_page = efx->rx_buffer_order ? 1 :
((PAGE_SIZE - sizeof(struct efx_rx_page_state)) /
efx->rx_page_buf_step);
efx->rx_buffer_truesize = (PAGE_SIZE << efx->rx_buffer_order) /
efx->rx_bufs_per_page;
efx->rx_pages_per_batch = DIV_ROUND_UP(EFX_RX_PREFERRED_BATCH,
efx->rx_bufs_per_page);
}
/* efx_fast_push_rx_descriptors - push new RX descriptors quickly
* @rx_queue: RX descriptor queue
*
* This will aim to fill the RX descriptor queue up to
* @rx_queue->@max_fill. If there is insufficient atomic
* memory to do so, a slow fill will be scheduled.
*
* The caller must provide serialisation (none is used here). In practise,
* this means this function must run from the NAPI handler, or be called
* when NAPI is disabled.
*/
void efx_fast_push_rx_descriptors(struct efx_rx_queue *rx_queue, bool atomic)
{
struct efx_nic *efx = rx_queue->efx;
unsigned int fill_level, batch_size;
int space, rc = 0;
if (!rx_queue->refill_enabled)
return;
/* Calculate current fill level, and exit if we don't need to fill */
fill_level = (rx_queue->added_count - rx_queue->removed_count);
EFX_WARN_ON_ONCE_PARANOID(fill_level > rx_queue->efx->rxq_entries);
if (fill_level >= rx_queue->fast_fill_trigger)
goto out;
/* Record minimum fill level */
if (unlikely(fill_level < rx_queue->min_fill)) {
if (fill_level)
rx_queue->min_fill = fill_level;
}
batch_size = efx->rx_pages_per_batch * efx->rx_bufs_per_page;
space = rx_queue->max_fill - fill_level;
EFX_WARN_ON_ONCE_PARANOID(space < batch_size);
netif_vdbg(rx_queue->efx, rx_status, rx_queue->efx->net_dev,
"RX queue %d fast-filling descriptor ring from"
" level %d to level %d\n",
efx_rx_queue_index(rx_queue), fill_level,
rx_queue->max_fill);
do {
rc = efx_init_rx_buffers(rx_queue, atomic);
if (unlikely(rc)) {
/* Ensure that we don't leave the rx queue empty */
efx_schedule_slow_fill(rx_queue);
goto out;
}
} while ((space -= batch_size) >= batch_size);
netif_vdbg(rx_queue->efx, rx_status, rx_queue->efx->net_dev,
"RX queue %d fast-filled descriptor ring "
"to level %d\n", efx_rx_queue_index(rx_queue),
rx_queue->added_count - rx_queue->removed_count);
out:
if (rx_queue->notified_count != rx_queue->added_count)
efx_nic_notify_rx_desc(rx_queue);
}
/* Pass a received packet up through GRO. GRO can handle pages
* regardless of checksum state and skbs with a good checksum.
*/
void
efx_rx_packet_gro(struct efx_channel *channel, struct efx_rx_buffer *rx_buf,
unsigned int n_frags, u8 *eh, __wsum csum)
{
struct napi_struct *napi = &channel->napi_str;
struct efx_nic *efx = channel->efx;
struct sk_buff *skb;
skb = napi_get_frags(napi);
if (unlikely(!skb)) {
struct efx_rx_queue *rx_queue;
rx_queue = efx_channel_get_rx_queue(channel);
efx_free_rx_buffers(rx_queue, rx_buf, n_frags);
return;
}
if (efx->net_dev->features & NETIF_F_RXHASH &&
efx_rx_buf_hash_valid(efx, eh))
skb_set_hash(skb, efx_rx_buf_hash(efx, eh),
PKT_HASH_TYPE_L3);
if (csum) {
skb->csum = csum;
skb->ip_summed = CHECKSUM_COMPLETE;
} else {
skb->ip_summed = ((rx_buf->flags & EFX_RX_PKT_CSUMMED) ?
CHECKSUM_UNNECESSARY : CHECKSUM_NONE);
}
skb->csum_level = !!(rx_buf->flags & EFX_RX_PKT_CSUM_LEVEL);
for (;;) {
skb_fill_page_desc(skb, skb_shinfo(skb)->nr_frags,
rx_buf->page, rx_buf->page_offset,
rx_buf->len);
rx_buf->page = NULL;
skb->len += rx_buf->len;
if (skb_shinfo(skb)->nr_frags == n_frags)
break;
rx_buf = efx_rx_buf_next(&channel->rx_queue, rx_buf);
}
skb->data_len = skb->len;
skb->truesize += n_frags * efx->rx_buffer_truesize;
skb_record_rx_queue(skb, channel->rx_queue.core_index);
napi_gro_frags(napi);
}
/* RSS contexts. We're using linked lists and crappy O(n) algorithms, because
* (a) this is an infrequent control-plane operation and (b) n is small (max 64)
*/
struct efx_rss_context *efx_alloc_rss_context_entry(struct efx_nic *efx)
{
struct list_head *head = &efx->rss_context.list;
struct efx_rss_context *ctx, *new;
u32 id = 1; /* Don't use zero, that refers to the master RSS context */
WARN_ON(!mutex_is_locked(&efx->rss_lock));
/* Search for first gap in the numbering */
list_for_each_entry(ctx, head, list) {
if (ctx->user_id != id)
break;
id++;
/* Check for wrap. If this happens, we have nearly 2^32
* allocated RSS contexts, which seems unlikely.
*/
if (WARN_ON_ONCE(!id))
return NULL;
}
/* Create the new entry */
new = kmalloc(sizeof(*new), GFP_KERNEL);
if (!new)
return NULL;
new->context_id = EFX_MCDI_RSS_CONTEXT_INVALID;
new->rx_hash_udp_4tuple = false;
/* Insert the new entry into the gap */
new->user_id = id;
list_add_tail(&new->list, &ctx->list);
return new;
}
struct efx_rss_context *efx_find_rss_context_entry(struct efx_nic *efx, u32 id)
{
struct list_head *head = &efx->rss_context.list;
struct efx_rss_context *ctx;
WARN_ON(!mutex_is_locked(&efx->rss_lock));
list_for_each_entry(ctx, head, list)
if (ctx->user_id == id)
return ctx;
return NULL;
}
void efx_free_rss_context_entry(struct efx_rss_context *ctx)
{
list_del(&ctx->list);
kfree(ctx);
}
void efx_set_default_rx_indir_table(struct efx_nic *efx,
struct efx_rss_context *ctx)
{
size_t i;
for (i = 0; i < ARRAY_SIZE(ctx->rx_indir_table); i++)
ctx->rx_indir_table[i] =
ethtool_rxfh_indir_default(i, efx->rss_spread);
}
/**
* efx_filter_is_mc_recipient - test whether spec is a multicast recipient
* @spec: Specification to test
*
* Return: %true if the specification is a non-drop RX filter that
* matches a local MAC address I/G bit value of 1 or matches a local
* IPv4 or IPv6 address value in the respective multicast address
* range. Otherwise %false.
*/
bool efx_filter_is_mc_recipient(const struct efx_filter_spec *spec)
{
if (!(spec->flags & EFX_FILTER_FLAG_RX) ||
spec->dmaq_id == EFX_FILTER_RX_DMAQ_ID_DROP)
return false;
if (spec->match_flags &
(EFX_FILTER_MATCH_LOC_MAC | EFX_FILTER_MATCH_LOC_MAC_IG) &&
is_multicast_ether_addr(spec->loc_mac))
return true;
if ((spec->match_flags &
(EFX_FILTER_MATCH_ETHER_TYPE | EFX_FILTER_MATCH_LOC_HOST)) ==
(EFX_FILTER_MATCH_ETHER_TYPE | EFX_FILTER_MATCH_LOC_HOST)) {
if (spec->ether_type == htons(ETH_P_IP) &&
ipv4_is_multicast(spec->loc_host[0]))
return true;
if (spec->ether_type == htons(ETH_P_IPV6) &&
((const u8 *)spec->loc_host)[0] == 0xff)
return true;
}
return false;
}
bool efx_filter_spec_equal(const struct efx_filter_spec *left,
const struct efx_filter_spec *right)
{
if ((left->match_flags ^ right->match_flags) |
((left->flags ^ right->flags) &
(EFX_FILTER_FLAG_RX | EFX_FILTER_FLAG_TX)))
return false;
return memcmp(&left->vport_id, &right->vport_id,
sizeof(struct efx_filter_spec) -
offsetof(struct efx_filter_spec, vport_id)) == 0;
}
u32 efx_filter_spec_hash(const struct efx_filter_spec *spec)
{
BUILD_BUG_ON(offsetof(struct efx_filter_spec, vport_id) & 3);
return jhash2((const u32 *)&spec->vport_id,
(sizeof(struct efx_filter_spec) -
offsetof(struct efx_filter_spec, vport_id)) / 4,
0);
}
#ifdef CONFIG_RFS_ACCEL
bool efx_rps_check_rule(struct efx_arfs_rule *rule, unsigned int filter_idx,
bool *force)
{
if (rule->filter_id == EFX_ARFS_FILTER_ID_PENDING) {
/* ARFS is currently updating this entry, leave it */
return false;
}
if (rule->filter_id == EFX_ARFS_FILTER_ID_ERROR) {
/* ARFS tried and failed to update this, so it's probably out
* of date. Remove the filter and the ARFS rule entry.
*/
rule->filter_id = EFX_ARFS_FILTER_ID_REMOVING;
*force = true;
return true;
} else if (WARN_ON(rule->filter_id != filter_idx)) { /* can't happen */
/* ARFS has moved on, so old filter is not needed. Since we did
* not mark the rule with EFX_ARFS_FILTER_ID_REMOVING, it will
* not be removed by efx_rps_hash_del() subsequently.
*/
*force = true;
return true;
}
/* Remove it iff ARFS wants to. */
return true;
}
static
struct hlist_head *efx_rps_hash_bucket(struct efx_nic *efx,
const struct efx_filter_spec *spec)
{
u32 hash = efx_filter_spec_hash(spec);
lockdep_assert_held(&efx->rps_hash_lock);
if (!efx->rps_hash_table)
return NULL;
return &efx->rps_hash_table[hash % EFX_ARFS_HASH_TABLE_SIZE];
}
struct efx_arfs_rule *efx_rps_hash_find(struct efx_nic *efx,
const struct efx_filter_spec *spec)
{
struct efx_arfs_rule *rule;
struct hlist_head *head;
struct hlist_node *node;
head = efx_rps_hash_bucket(efx, spec);
if (!head)
return NULL;
hlist_for_each(node, head) {
rule = container_of(node, struct efx_arfs_rule, node);
if (efx_filter_spec_equal(spec, &rule->spec))
return rule;
}
return NULL;
}
struct efx_arfs_rule *efx_rps_hash_add(struct efx_nic *efx,
const struct efx_filter_spec *spec,
bool *new)
{
struct efx_arfs_rule *rule;
struct hlist_head *head;
struct hlist_node *node;
head = efx_rps_hash_bucket(efx, spec);
if (!head)
return NULL;
hlist_for_each(node, head) {
rule = container_of(node, struct efx_arfs_rule, node);
if (efx_filter_spec_equal(spec, &rule->spec)) {
*new = false;
return rule;
}
}
rule = kmalloc(sizeof(*rule), GFP_ATOMIC);
*new = true;
if (rule) {
memcpy(&rule->spec, spec, sizeof(rule->spec));
hlist_add_head(&rule->node, head);
}
return rule;
}
void efx_rps_hash_del(struct efx_nic *efx, const struct efx_filter_spec *spec)
{
struct efx_arfs_rule *rule;
struct hlist_head *head;
struct hlist_node *node;
head = efx_rps_hash_bucket(efx, spec);
if (WARN_ON(!head))
return;
hlist_for_each(node, head) {
rule = container_of(node, struct efx_arfs_rule, node);
if (efx_filter_spec_equal(spec, &rule->spec)) {
/* Someone already reused the entry. We know that if
* this check doesn't fire (i.e. filter_id == REMOVING)
* then the REMOVING mark was put there by our caller,
* because caller is holding a lock on filter table and
* only holders of that lock set REMOVING.
*/
if (rule->filter_id != EFX_ARFS_FILTER_ID_REMOVING)
return;
hlist_del(node);
kfree(rule);
return;
}
}
/* We didn't find it. */
WARN_ON(1);
}
#endif
int efx_probe_filters(struct efx_nic *efx)
{
int rc;
mutex_lock(&efx->mac_lock);
rc = efx->type->filter_table_probe(efx);
if (rc)
goto out_unlock;
#ifdef CONFIG_RFS_ACCEL
if (efx->type->offload_features & NETIF_F_NTUPLE) {
struct efx_channel *channel;
int i, success = 1;
efx_for_each_channel(channel, efx) {
channel->rps_flow_id =
kcalloc(efx->type->max_rx_ip_filters,
sizeof(*channel->rps_flow_id),
GFP_KERNEL);
if (!channel->rps_flow_id)
success = 0;
else
for (i = 0;
i < efx->type->max_rx_ip_filters;
++i)
channel->rps_flow_id[i] =
RPS_FLOW_ID_INVALID;
channel->rfs_expire_index = 0;
channel->rfs_filter_count = 0;
}
if (!success) {
efx_for_each_channel(channel, efx)
kfree(channel->rps_flow_id);
efx->type->filter_table_remove(efx);
rc = -ENOMEM;
goto out_unlock;
}
}
#endif
out_unlock:
mutex_unlock(&efx->mac_lock);
return rc;
}
void efx_remove_filters(struct efx_nic *efx)
{
#ifdef CONFIG_RFS_ACCEL
struct efx_channel *channel;
efx_for_each_channel(channel, efx) {
cancel_delayed_work_sync(&channel->filter_work);
kfree(channel->rps_flow_id);
channel->rps_flow_id = NULL;
}
#endif
efx->type->filter_table_remove(efx);
}
#ifdef CONFIG_RFS_ACCEL
static void efx_filter_rfs_work(struct work_struct *data)
{
struct efx_async_filter_insertion *req = container_of(data, struct efx_async_filter_insertion,
work);
struct efx_nic *efx = efx_netdev_priv(req->net_dev);
struct efx_channel *channel = efx_get_channel(efx, req->rxq_index);
int slot_idx = req - efx->rps_slot;
struct efx_arfs_rule *rule;
u16 arfs_id = 0;
int rc;
rc = efx->type->filter_insert(efx, &req->spec, true);
if (rc >= 0)
/* Discard 'priority' part of EF10+ filter ID (mcdi_filters) */
rc %= efx->type->max_rx_ip_filters;
if (efx->rps_hash_table) {
spin_lock_bh(&efx->rps_hash_lock);
rule = efx_rps_hash_find(efx, &req->spec);
/* The rule might have already gone, if someone else's request
* for the same spec was already worked and then expired before
* we got around to our work. In that case we have nothing
* tying us to an arfs_id, meaning that as soon as the filter
* is considered for expiry it will be removed.
*/
if (rule) {
if (rc < 0)
rule->filter_id = EFX_ARFS_FILTER_ID_ERROR;
else
rule->filter_id = rc;
arfs_id = rule->arfs_id;
}
spin_unlock_bh(&efx->rps_hash_lock);
}
if (rc >= 0) {
/* Remember this so we can check whether to expire the filter
* later.
*/
mutex_lock(&efx->rps_mutex);
if (channel->rps_flow_id[rc] == RPS_FLOW_ID_INVALID)
channel->rfs_filter_count++;
channel->rps_flow_id[rc] = req->flow_id;
mutex_unlock(&efx->rps_mutex);
if (req->spec.ether_type == htons(ETH_P_IP))
netif_info(efx, rx_status, efx->net_dev,
"steering %s %pI4:%u:%pI4:%u to queue %u [flow %u filter %d id %u]\n",
(req->spec.ip_proto == IPPROTO_TCP) ? "TCP" : "UDP",
req->spec.rem_host, ntohs(req->spec.rem_port),
req->spec.loc_host, ntohs(req->spec.loc_port),
req->rxq_index, req->flow_id, rc, arfs_id);
else
netif_info(efx, rx_status, efx->net_dev,
"steering %s [%pI6]:%u:[%pI6]:%u to queue %u [flow %u filter %d id %u]\n",
(req->spec.ip_proto == IPPROTO_TCP) ? "TCP" : "UDP",
req->spec.rem_host, ntohs(req->spec.rem_port),
req->spec.loc_host, ntohs(req->spec.loc_port),
req->rxq_index, req->flow_id, rc, arfs_id);
channel->n_rfs_succeeded++;
} else {
if (req->spec.ether_type == htons(ETH_P_IP))
netif_dbg(efx, rx_status, efx->net_dev,
"failed to steer %s %pI4:%u:%pI4:%u to queue %u [flow %u rc %d id %u]\n",
(req->spec.ip_proto == IPPROTO_TCP) ? "TCP" : "UDP",
req->spec.rem_host, ntohs(req->spec.rem_port),
req->spec.loc_host, ntohs(req->spec.loc_port),
req->rxq_index, req->flow_id, rc, arfs_id);
else
netif_dbg(efx, rx_status, efx->net_dev,
"failed to steer %s [%pI6]:%u:[%pI6]:%u to queue %u [flow %u rc %d id %u]\n",
(req->spec.ip_proto == IPPROTO_TCP) ? "TCP" : "UDP",
req->spec.rem_host, ntohs(req->spec.rem_port),
req->spec.loc_host, ntohs(req->spec.loc_port),
req->rxq_index, req->flow_id, rc, arfs_id);
channel->n_rfs_failed++;
/* We're overloading the NIC's filter tables, so let's do a
* chunk of extra expiry work.
*/
__efx_filter_rfs_expire(channel, min(channel->rfs_filter_count,
100u));
}
/* Release references */
clear_bit(slot_idx, &efx->rps_slot_map);
dev_put(req->net_dev);
}
int efx_filter_rfs(struct net_device *net_dev, const struct sk_buff *skb,
u16 rxq_index, u32 flow_id)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
struct efx_async_filter_insertion *req;
struct efx_arfs_rule *rule;
struct flow_keys fk;
int slot_idx;
bool new;
int rc;
/* find a free slot */
for (slot_idx = 0; slot_idx < EFX_RPS_MAX_IN_FLIGHT; slot_idx++)
if (!test_and_set_bit(slot_idx, &efx->rps_slot_map))
break;
if (slot_idx >= EFX_RPS_MAX_IN_FLIGHT)
return -EBUSY;
if (flow_id == RPS_FLOW_ID_INVALID) {
rc = -EINVAL;
goto out_clear;
}
if (!skb_flow_dissect_flow_keys(skb, &fk, 0)) {
rc = -EPROTONOSUPPORT;
goto out_clear;
}
if (fk.basic.n_proto != htons(ETH_P_IP) && fk.basic.n_proto != htons(ETH_P_IPV6)) {
rc = -EPROTONOSUPPORT;
goto out_clear;
}
if (fk.control.flags & FLOW_DIS_IS_FRAGMENT) {
rc = -EPROTONOSUPPORT;
goto out_clear;
}
req = efx->rps_slot + slot_idx;
efx_filter_init_rx(&req->spec, EFX_FILTER_PRI_HINT,
efx->rx_scatter ? EFX_FILTER_FLAG_RX_SCATTER : 0,
rxq_index);
req->spec.match_flags =
EFX_FILTER_MATCH_ETHER_TYPE | EFX_FILTER_MATCH_IP_PROTO |
EFX_FILTER_MATCH_LOC_HOST | EFX_FILTER_MATCH_LOC_PORT |
EFX_FILTER_MATCH_REM_HOST | EFX_FILTER_MATCH_REM_PORT;
req->spec.ether_type = fk.basic.n_proto;
req->spec.ip_proto = fk.basic.ip_proto;
if (fk.basic.n_proto == htons(ETH_P_IP)) {
req->spec.rem_host[0] = fk.addrs.v4addrs.src;
req->spec.loc_host[0] = fk.addrs.v4addrs.dst;
} else {
memcpy(req->spec.rem_host, &fk.addrs.v6addrs.src,
sizeof(struct in6_addr));
memcpy(req->spec.loc_host, &fk.addrs.v6addrs.dst,
sizeof(struct in6_addr));
}
req->spec.rem_port = fk.ports.src;
req->spec.loc_port = fk.ports.dst;
if (efx->rps_hash_table) {
/* Add it to ARFS hash table */
spin_lock(&efx->rps_hash_lock);
rule = efx_rps_hash_add(efx, &req->spec, &new);
if (!rule) {
rc = -ENOMEM;
goto out_unlock;
}
if (new)
rule->arfs_id = efx->rps_next_id++ % RPS_NO_FILTER;
rc = rule->arfs_id;
/* Skip if existing or pending filter already does the right thing */
if (!new && rule->rxq_index == rxq_index &&
rule->filter_id >= EFX_ARFS_FILTER_ID_PENDING)
goto out_unlock;
rule->rxq_index = rxq_index;
rule->filter_id = EFX_ARFS_FILTER_ID_PENDING;
spin_unlock(&efx->rps_hash_lock);
} else {
/* Without an ARFS hash table, we just use arfs_id 0 for all
* filters. This means if multiple flows hash to the same
* flow_id, all but the most recently touched will be eligible
* for expiry.
*/
rc = 0;
}
/* Queue the request */
dev_hold(req->net_dev = net_dev);
INIT_WORK(&req->work, efx_filter_rfs_work);
req->rxq_index = rxq_index;
req->flow_id = flow_id;
schedule_work(&req->work);
return rc;
out_unlock:
spin_unlock(&efx->rps_hash_lock);
out_clear:
clear_bit(slot_idx, &efx->rps_slot_map);
return rc;
}
bool __efx_filter_rfs_expire(struct efx_channel *channel, unsigned int quota)
{
bool (*expire_one)(struct efx_nic *efx, u32 flow_id, unsigned int index);
struct efx_nic *efx = channel->efx;
unsigned int index, size, start;
u32 flow_id;
if (!mutex_trylock(&efx->rps_mutex))
return false;
expire_one = efx->type->filter_rfs_expire_one;
index = channel->rfs_expire_index;
start = index;
size = efx->type->max_rx_ip_filters;
while (quota) {
flow_id = channel->rps_flow_id[index];
if (flow_id != RPS_FLOW_ID_INVALID) {
quota--;
if (expire_one(efx, flow_id, index)) {
netif_info(efx, rx_status, efx->net_dev,
"expired filter %d [channel %u flow %u]\n",
index, channel->channel, flow_id);
channel->rps_flow_id[index] = RPS_FLOW_ID_INVALID;
channel->rfs_filter_count--;
}
}
if (++index == size)
index = 0;
/* If we were called with a quota that exceeds the total number
* of filters in the table (which shouldn't happen, but could
* if two callers race), ensure that we don't loop forever -
* stop when we've examined every row of the table.
*/
if (index == start)
break;
}
channel->rfs_expire_index = index;
mutex_unlock(&efx->rps_mutex);
return true;
}
#endif /* CONFIG_RFS_ACCEL */
|
linux-master
|
drivers/net/ethernet/sfc/rx_common.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2019 Solarflare Communications Inc.
* Copyright 2020-2022 Xilinx Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include <linux/rhashtable.h>
#include "ef100_rep.h"
#include "ef100_netdev.h"
#include "ef100_nic.h"
#include "mae.h"
#include "rx_common.h"
#include "tc_bindings.h"
#include "efx_devlink.h"
#define EFX_EF100_REP_DRIVER "efx_ef100_rep"
#define EFX_REP_DEFAULT_PSEUDO_RING_SIZE 64
static int efx_ef100_rep_poll(struct napi_struct *napi, int weight);
static int efx_ef100_rep_init_struct(struct efx_nic *efx, struct efx_rep *efv,
unsigned int i)
{
efv->parent = efx;
efv->idx = i;
INIT_LIST_HEAD(&efv->list);
efv->dflt.fw_id = MC_CMD_MAE_ACTION_RULE_INSERT_OUT_ACTION_RULE_ID_NULL;
INIT_LIST_HEAD(&efv->dflt.acts.list);
INIT_LIST_HEAD(&efv->rx_list);
spin_lock_init(&efv->rx_lock);
efv->msg_enable = NETIF_MSG_DRV | NETIF_MSG_PROBE |
NETIF_MSG_LINK | NETIF_MSG_IFDOWN |
NETIF_MSG_IFUP | NETIF_MSG_RX_ERR |
NETIF_MSG_TX_ERR | NETIF_MSG_HW;
return 0;
}
static int efx_ef100_rep_open(struct net_device *net_dev)
{
struct efx_rep *efv = netdev_priv(net_dev);
netif_napi_add(net_dev, &efv->napi, efx_ef100_rep_poll);
napi_enable(&efv->napi);
return 0;
}
static int efx_ef100_rep_close(struct net_device *net_dev)
{
struct efx_rep *efv = netdev_priv(net_dev);
napi_disable(&efv->napi);
netif_napi_del(&efv->napi);
return 0;
}
static netdev_tx_t efx_ef100_rep_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct efx_rep *efv = netdev_priv(dev);
struct efx_nic *efx = efv->parent;
netdev_tx_t rc;
/* __ef100_hard_start_xmit() will always return success even in the
* case of TX drops, where it will increment efx's tx_dropped. The
* efv stats really only count attempted TX, not success/failure.
*/
atomic64_inc(&efv->stats.tx_packets);
atomic64_add(skb->len, &efv->stats.tx_bytes);
netif_tx_lock(efx->net_dev);
rc = __ef100_hard_start_xmit(skb, efx, dev, efv);
netif_tx_unlock(efx->net_dev);
return rc;
}
static int efx_ef100_rep_get_port_parent_id(struct net_device *dev,
struct netdev_phys_item_id *ppid)
{
struct efx_rep *efv = netdev_priv(dev);
struct efx_nic *efx = efv->parent;
struct ef100_nic_data *nic_data;
nic_data = efx->nic_data;
/* nic_data->port_id is a u8[] */
ppid->id_len = sizeof(nic_data->port_id);
memcpy(ppid->id, nic_data->port_id, sizeof(nic_data->port_id));
return 0;
}
static int efx_ef100_rep_get_phys_port_name(struct net_device *dev,
char *buf, size_t len)
{
struct efx_rep *efv = netdev_priv(dev);
struct efx_nic *efx = efv->parent;
struct ef100_nic_data *nic_data;
int ret;
nic_data = efx->nic_data;
ret = snprintf(buf, len, "p%upf%uvf%u", efx->port_num,
nic_data->pf_index, efv->idx);
if (ret >= len)
return -EOPNOTSUPP;
return 0;
}
static int efx_ef100_rep_setup_tc(struct net_device *net_dev,
enum tc_setup_type type, void *type_data)
{
struct efx_rep *efv = netdev_priv(net_dev);
struct efx_nic *efx = efv->parent;
if (type == TC_SETUP_CLSFLOWER)
return efx_tc_flower(efx, net_dev, type_data, efv);
if (type == TC_SETUP_BLOCK)
return efx_tc_setup_block(net_dev, efx, type_data, efv);
return -EOPNOTSUPP;
}
static void efx_ef100_rep_get_stats64(struct net_device *dev,
struct rtnl_link_stats64 *stats)
{
struct efx_rep *efv = netdev_priv(dev);
stats->rx_packets = atomic64_read(&efv->stats.rx_packets);
stats->tx_packets = atomic64_read(&efv->stats.tx_packets);
stats->rx_bytes = atomic64_read(&efv->stats.rx_bytes);
stats->tx_bytes = atomic64_read(&efv->stats.tx_bytes);
stats->rx_dropped = atomic64_read(&efv->stats.rx_dropped);
stats->tx_errors = atomic64_read(&efv->stats.tx_errors);
}
const struct net_device_ops efx_ef100_rep_netdev_ops = {
.ndo_open = efx_ef100_rep_open,
.ndo_stop = efx_ef100_rep_close,
.ndo_start_xmit = efx_ef100_rep_xmit,
.ndo_get_port_parent_id = efx_ef100_rep_get_port_parent_id,
.ndo_get_phys_port_name = efx_ef100_rep_get_phys_port_name,
.ndo_get_stats64 = efx_ef100_rep_get_stats64,
.ndo_setup_tc = efx_ef100_rep_setup_tc,
};
static void efx_ef100_rep_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *drvinfo)
{
strscpy(drvinfo->driver, EFX_EF100_REP_DRIVER, sizeof(drvinfo->driver));
}
static u32 efx_ef100_rep_ethtool_get_msglevel(struct net_device *net_dev)
{
struct efx_rep *efv = netdev_priv(net_dev);
return efv->msg_enable;
}
static void efx_ef100_rep_ethtool_set_msglevel(struct net_device *net_dev,
u32 msg_enable)
{
struct efx_rep *efv = netdev_priv(net_dev);
efv->msg_enable = msg_enable;
}
static void efx_ef100_rep_ethtool_get_ringparam(struct net_device *net_dev,
struct ethtool_ringparam *ring,
struct kernel_ethtool_ringparam *kring,
struct netlink_ext_ack *ext_ack)
{
struct efx_rep *efv = netdev_priv(net_dev);
ring->rx_max_pending = U32_MAX;
ring->rx_pending = efv->rx_pring_size;
}
static int efx_ef100_rep_ethtool_set_ringparam(struct net_device *net_dev,
struct ethtool_ringparam *ring,
struct kernel_ethtool_ringparam *kring,
struct netlink_ext_ack *ext_ack)
{
struct efx_rep *efv = netdev_priv(net_dev);
if (ring->rx_mini_pending || ring->rx_jumbo_pending || ring->tx_pending)
return -EINVAL;
efv->rx_pring_size = ring->rx_pending;
return 0;
}
static const struct ethtool_ops efx_ef100_rep_ethtool_ops = {
.get_drvinfo = efx_ef100_rep_get_drvinfo,
.get_msglevel = efx_ef100_rep_ethtool_get_msglevel,
.set_msglevel = efx_ef100_rep_ethtool_set_msglevel,
.get_ringparam = efx_ef100_rep_ethtool_get_ringparam,
.set_ringparam = efx_ef100_rep_ethtool_set_ringparam,
};
static struct efx_rep *efx_ef100_rep_create_netdev(struct efx_nic *efx,
unsigned int i)
{
struct net_device *net_dev;
struct efx_rep *efv;
int rc;
net_dev = alloc_etherdev_mq(sizeof(*efv), 1);
if (!net_dev)
return ERR_PTR(-ENOMEM);
efv = netdev_priv(net_dev);
rc = efx_ef100_rep_init_struct(efx, efv, i);
if (rc)
goto fail1;
efv->net_dev = net_dev;
rtnl_lock();
spin_lock_bh(&efx->vf_reps_lock);
list_add_tail(&efv->list, &efx->vf_reps);
spin_unlock_bh(&efx->vf_reps_lock);
if (netif_running(efx->net_dev) && efx->state == STATE_NET_UP) {
netif_device_attach(net_dev);
netif_carrier_on(net_dev);
} else {
netif_carrier_off(net_dev);
netif_tx_stop_all_queues(net_dev);
}
rtnl_unlock();
net_dev->netdev_ops = &efx_ef100_rep_netdev_ops;
net_dev->ethtool_ops = &efx_ef100_rep_ethtool_ops;
net_dev->min_mtu = EFX_MIN_MTU;
net_dev->max_mtu = EFX_MAX_MTU;
net_dev->features |= NETIF_F_LLTX;
net_dev->hw_features |= NETIF_F_LLTX;
return efv;
fail1:
free_netdev(net_dev);
return ERR_PTR(rc);
}
static int efx_ef100_configure_rep(struct efx_rep *efv)
{
struct efx_nic *efx = efv->parent;
int rc;
efv->rx_pring_size = EFX_REP_DEFAULT_PSEUDO_RING_SIZE;
/* Look up actual mport ID */
rc = efx_mae_lookup_mport(efx, efv->idx, &efv->mport);
if (rc)
return rc;
pci_dbg(efx->pci_dev, "VF %u has mport ID %#x\n", efv->idx, efv->mport);
/* mport label should fit in 16 bits */
WARN_ON(efv->mport >> 16);
return efx_tc_configure_default_rule_rep(efv);
}
static void efx_ef100_deconfigure_rep(struct efx_rep *efv)
{
struct efx_nic *efx = efv->parent;
efx_tc_deconfigure_default_rule(efx, &efv->dflt);
}
static void efx_ef100_rep_destroy_netdev(struct efx_rep *efv)
{
struct efx_nic *efx = efv->parent;
rtnl_lock();
spin_lock_bh(&efx->vf_reps_lock);
list_del(&efv->list);
spin_unlock_bh(&efx->vf_reps_lock);
rtnl_unlock();
synchronize_rcu();
free_netdev(efv->net_dev);
}
int efx_ef100_vfrep_create(struct efx_nic *efx, unsigned int i)
{
struct efx_rep *efv;
int rc;
efv = efx_ef100_rep_create_netdev(efx, i);
if (IS_ERR(efv)) {
rc = PTR_ERR(efv);
pci_err(efx->pci_dev,
"Failed to create representor for VF %d, rc %d\n", i,
rc);
return rc;
}
rc = efx_ef100_configure_rep(efv);
if (rc) {
pci_err(efx->pci_dev,
"Failed to configure representor for VF %d, rc %d\n",
i, rc);
goto fail1;
}
ef100_rep_set_devlink_port(efv);
rc = register_netdev(efv->net_dev);
if (rc) {
pci_err(efx->pci_dev,
"Failed to register representor for VF %d, rc %d\n",
i, rc);
goto fail2;
}
pci_dbg(efx->pci_dev, "Representor for VF %d is %s\n", i,
efv->net_dev->name);
return 0;
fail2:
ef100_rep_unset_devlink_port(efv);
efx_ef100_deconfigure_rep(efv);
fail1:
efx_ef100_rep_destroy_netdev(efv);
return rc;
}
void efx_ef100_vfrep_destroy(struct efx_nic *efx, struct efx_rep *efv)
{
struct net_device *rep_dev;
rep_dev = efv->net_dev;
if (!rep_dev)
return;
netif_dbg(efx, drv, rep_dev, "Removing VF representor\n");
unregister_netdev(rep_dev);
ef100_rep_unset_devlink_port(efv);
efx_ef100_deconfigure_rep(efv);
efx_ef100_rep_destroy_netdev(efv);
}
void efx_ef100_fini_vfreps(struct efx_nic *efx)
{
struct ef100_nic_data *nic_data = efx->nic_data;
struct efx_rep *efv, *next;
if (!nic_data->grp_mae)
return;
list_for_each_entry_safe(efv, next, &efx->vf_reps, list)
efx_ef100_vfrep_destroy(efx, efv);
}
static bool ef100_mport_is_pcie_vnic(struct mae_mport_desc *mport_desc)
{
return mport_desc->mport_type == MAE_MPORT_DESC_MPORT_TYPE_VNIC &&
mport_desc->vnic_client_type == MAE_MPORT_DESC_VNIC_CLIENT_TYPE_FUNCTION;
}
bool ef100_mport_on_local_intf(struct efx_nic *efx,
struct mae_mport_desc *mport_desc)
{
struct ef100_nic_data *nic_data = efx->nic_data;
bool pcie_func;
pcie_func = ef100_mport_is_pcie_vnic(mport_desc);
return nic_data->have_local_intf && pcie_func &&
mport_desc->interface_idx == nic_data->local_mae_intf;
}
bool ef100_mport_is_vf(struct mae_mport_desc *mport_desc)
{
bool pcie_func;
pcie_func = ef100_mport_is_pcie_vnic(mport_desc);
return pcie_func && (mport_desc->vf_idx != MAE_MPORT_DESC_VF_IDX_NULL);
}
void efx_ef100_init_reps(struct efx_nic *efx)
{
struct ef100_nic_data *nic_data = efx->nic_data;
int rc;
nic_data->have_local_intf = false;
rc = efx_mae_enumerate_mports(efx);
if (rc)
pci_warn(efx->pci_dev,
"Could not enumerate mports (rc=%d), are we admin?",
rc);
}
void efx_ef100_fini_reps(struct efx_nic *efx)
{
struct efx_mae *mae = efx->mae;
rhashtable_free_and_destroy(&mae->mports_ht, efx_mae_remove_mport,
NULL);
}
static int efx_ef100_rep_poll(struct napi_struct *napi, int weight)
{
struct efx_rep *efv = container_of(napi, struct efx_rep, napi);
unsigned int read_index;
struct list_head head;
struct sk_buff *skb;
bool need_resched;
int spent = 0;
INIT_LIST_HEAD(&head);
/* Grab up to 'weight' pending SKBs */
spin_lock_bh(&efv->rx_lock);
read_index = efv->write_index;
while (spent < weight && !list_empty(&efv->rx_list)) {
skb = list_first_entry(&efv->rx_list, struct sk_buff, list);
list_del(&skb->list);
list_add_tail(&skb->list, &head);
spent++;
}
spin_unlock_bh(&efv->rx_lock);
/* Receive them */
netif_receive_skb_list(&head);
if (spent < weight)
if (napi_complete_done(napi, spent)) {
spin_lock_bh(&efv->rx_lock);
efv->read_index = read_index;
/* If write_index advanced while we were doing the
* RX, then storing our read_index won't re-prime the
* fake-interrupt. In that case, we need to schedule
* NAPI again to consume the additional packet(s).
*/
need_resched = efv->write_index != read_index;
spin_unlock_bh(&efv->rx_lock);
if (need_resched)
napi_schedule(&efv->napi);
}
return spent;
}
void efx_ef100_rep_rx_packet(struct efx_rep *efv, struct efx_rx_buffer *rx_buf)
{
u8 *eh = efx_rx_buf_va(rx_buf);
struct sk_buff *skb;
bool primed;
/* Don't allow too many queued SKBs to build up, as they consume
* GFP_ATOMIC memory. If we overrun, just start dropping.
*/
if (efv->write_index - READ_ONCE(efv->read_index) > efv->rx_pring_size) {
atomic64_inc(&efv->stats.rx_dropped);
if (net_ratelimit())
netif_dbg(efv->parent, rx_err, efv->net_dev,
"nodesc-dropped packet of length %u\n",
rx_buf->len);
return;
}
skb = netdev_alloc_skb(efv->net_dev, rx_buf->len);
if (!skb) {
atomic64_inc(&efv->stats.rx_dropped);
if (net_ratelimit())
netif_dbg(efv->parent, rx_err, efv->net_dev,
"noskb-dropped packet of length %u\n",
rx_buf->len);
return;
}
memcpy(skb->data, eh, rx_buf->len);
__skb_put(skb, rx_buf->len);
skb_record_rx_queue(skb, 0); /* rep is single-queue */
/* Move past the ethernet header */
skb->protocol = eth_type_trans(skb, efv->net_dev);
skb_checksum_none_assert(skb);
atomic64_inc(&efv->stats.rx_packets);
atomic64_add(rx_buf->len, &efv->stats.rx_bytes);
/* Add it to the rx list */
spin_lock_bh(&efv->rx_lock);
primed = efv->read_index == efv->write_index;
list_add_tail(&skb->list, &efv->rx_list);
efv->write_index++;
spin_unlock_bh(&efv->rx_lock);
/* Trigger rx work */
if (primed)
napi_schedule(&efv->napi);
}
struct efx_rep *efx_ef100_find_rep_by_mport(struct efx_nic *efx, u16 mport)
{
struct efx_rep *efv, *out = NULL;
/* spinlock guards against list mutation while we're walking it;
* but caller must also hold rcu_read_lock() to ensure the netdev
* isn't freed after we drop the spinlock.
*/
spin_lock_bh(&efx->vf_reps_lock);
list_for_each_entry(efv, &efx->vf_reps, list)
if (efv->mport == mport) {
out = efv;
break;
}
spin_unlock_bh(&efx->vf_reps_lock);
return out;
}
|
linux-master
|
drivers/net/ethernet/sfc/ef100_rep.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2023, Advanced Micro Devices, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include "tc_encap_actions.h"
#include "tc.h"
#include "mae.h"
#include <net/vxlan.h>
#include <net/geneve.h>
#include <net/netevent.h>
#include <net/arp.h>
static const struct rhashtable_params efx_neigh_ht_params = {
.key_len = offsetof(struct efx_neigh_binder, ha),
.key_offset = 0,
.head_offset = offsetof(struct efx_neigh_binder, linkage),
};
static const struct rhashtable_params efx_tc_encap_ht_params = {
.key_len = offsetofend(struct efx_tc_encap_action, key),
.key_offset = 0,
.head_offset = offsetof(struct efx_tc_encap_action, linkage),
};
static void efx_tc_encap_free(void *ptr, void *__unused)
{
struct efx_tc_encap_action *enc = ptr;
WARN_ON(refcount_read(&enc->ref));
kfree(enc);
}
static void efx_neigh_free(void *ptr, void *__unused)
{
struct efx_neigh_binder *neigh = ptr;
WARN_ON(refcount_read(&neigh->ref));
WARN_ON(!list_empty(&neigh->users));
put_net_track(neigh->net, &neigh->ns_tracker);
netdev_put(neigh->egdev, &neigh->dev_tracker);
kfree(neigh);
}
int efx_tc_init_encap_actions(struct efx_nic *efx)
{
int rc;
rc = rhashtable_init(&efx->tc->neigh_ht, &efx_neigh_ht_params);
if (rc < 0)
goto fail_neigh_ht;
rc = rhashtable_init(&efx->tc->encap_ht, &efx_tc_encap_ht_params);
if (rc < 0)
goto fail_encap_ht;
return 0;
fail_encap_ht:
rhashtable_destroy(&efx->tc->neigh_ht);
fail_neigh_ht:
return rc;
}
/* Only call this in init failure teardown.
* Normal exit should fini instead as there may be entries in the table.
*/
void efx_tc_destroy_encap_actions(struct efx_nic *efx)
{
rhashtable_destroy(&efx->tc->encap_ht);
rhashtable_destroy(&efx->tc->neigh_ht);
}
void efx_tc_fini_encap_actions(struct efx_nic *efx)
{
rhashtable_free_and_destroy(&efx->tc->encap_ht, efx_tc_encap_free, NULL);
rhashtable_free_and_destroy(&efx->tc->neigh_ht, efx_neigh_free, NULL);
}
static void efx_neigh_update(struct work_struct *work);
static int efx_bind_neigh(struct efx_nic *efx,
struct efx_tc_encap_action *encap, struct net *net,
struct netlink_ext_ack *extack)
{
struct efx_neigh_binder *neigh, *old;
struct flowi6 flow6 = {};
struct flowi4 flow4 = {};
int rc;
/* GCC stupidly thinks that only values explicitly listed in the enum
* definition can _possibly_ be sensible case values, so without this
* cast it complains about the IPv6 versions.
*/
switch ((int)encap->type) {
case EFX_ENCAP_TYPE_VXLAN:
case EFX_ENCAP_TYPE_GENEVE:
flow4.flowi4_proto = IPPROTO_UDP;
flow4.fl4_dport = encap->key.tp_dst;
flow4.flowi4_tos = encap->key.tos;
flow4.daddr = encap->key.u.ipv4.dst;
flow4.saddr = encap->key.u.ipv4.src;
break;
case EFX_ENCAP_TYPE_VXLAN | EFX_ENCAP_FLAG_IPV6:
case EFX_ENCAP_TYPE_GENEVE | EFX_ENCAP_FLAG_IPV6:
flow6.flowi6_proto = IPPROTO_UDP;
flow6.fl6_dport = encap->key.tp_dst;
flow6.flowlabel = ip6_make_flowinfo(encap->key.tos,
encap->key.label);
flow6.daddr = encap->key.u.ipv6.dst;
flow6.saddr = encap->key.u.ipv6.src;
break;
default:
NL_SET_ERR_MSG_FMT_MOD(extack, "Unsupported encap type %d",
(int)encap->type);
return -EOPNOTSUPP;
}
neigh = kzalloc(sizeof(*neigh), GFP_KERNEL_ACCOUNT);
if (!neigh)
return -ENOMEM;
neigh->net = get_net_track(net, &neigh->ns_tracker, GFP_KERNEL_ACCOUNT);
neigh->dst_ip = flow4.daddr;
neigh->dst_ip6 = flow6.daddr;
old = rhashtable_lookup_get_insert_fast(&efx->tc->neigh_ht,
&neigh->linkage,
efx_neigh_ht_params);
if (old) {
/* don't need our new entry */
put_net_track(neigh->net, &neigh->ns_tracker);
kfree(neigh);
if (IS_ERR(old)) /* oh dear, it's actually an error */
return PTR_ERR(old);
if (!refcount_inc_not_zero(&old->ref))
return -EAGAIN;
/* existing entry found, ref taken */
neigh = old;
} else {
/* New entry. We need to initiate a lookup */
struct neighbour *n;
struct rtable *rt;
if (encap->type & EFX_ENCAP_FLAG_IPV6) {
#if IS_ENABLED(CONFIG_IPV6)
struct dst_entry *dst;
dst = ipv6_stub->ipv6_dst_lookup_flow(net, NULL, &flow6,
NULL);
rc = PTR_ERR_OR_ZERO(dst);
if (rc) {
NL_SET_ERR_MSG_MOD(extack, "Failed to lookup route for IPv6 encap");
goto out_free;
}
neigh->egdev = dst->dev;
netdev_hold(neigh->egdev, &neigh->dev_tracker,
GFP_KERNEL_ACCOUNT);
neigh->ttl = ip6_dst_hoplimit(dst);
n = dst_neigh_lookup(dst, &flow6.daddr);
dst_release(dst);
#else
/* We shouldn't ever get here, because if IPv6 isn't
* enabled how did someone create an IPv6 tunnel_key?
*/
rc = -EOPNOTSUPP;
NL_SET_ERR_MSG_MOD(extack, "No IPv6 support (neigh bind)");
goto out_free;
#endif
} else {
rt = ip_route_output_key(net, &flow4);
if (IS_ERR_OR_NULL(rt)) {
rc = PTR_ERR_OR_ZERO(rt);
if (!rc)
rc = -EIO;
NL_SET_ERR_MSG_MOD(extack, "Failed to lookup route for encap");
goto out_free;
}
neigh->egdev = rt->dst.dev;
netdev_hold(neigh->egdev, &neigh->dev_tracker,
GFP_KERNEL_ACCOUNT);
neigh->ttl = ip4_dst_hoplimit(&rt->dst);
n = dst_neigh_lookup(&rt->dst, &flow4.daddr);
ip_rt_put(rt);
}
if (!n) {
rc = -ENETUNREACH;
NL_SET_ERR_MSG_MOD(extack, "Failed to lookup neighbour for encap");
netdev_put(neigh->egdev, &neigh->dev_tracker);
goto out_free;
}
refcount_set(&neigh->ref, 1);
INIT_LIST_HEAD(&neigh->users);
read_lock_bh(&n->lock);
ether_addr_copy(neigh->ha, n->ha);
neigh->n_valid = n->nud_state & NUD_VALID;
read_unlock_bh(&n->lock);
rwlock_init(&neigh->lock);
INIT_WORK(&neigh->work, efx_neigh_update);
neigh->efx = efx;
neigh->used = jiffies;
if (!neigh->n_valid)
/* Prod ARP to find us a neighbour */
neigh_event_send(n, NULL);
neigh_release(n);
}
/* Add us to this neigh */
encap->neigh = neigh;
list_add_tail(&encap->list, &neigh->users);
return 0;
out_free:
/* cleanup common to several error paths */
rhashtable_remove_fast(&efx->tc->neigh_ht, &neigh->linkage,
efx_neigh_ht_params);
synchronize_rcu();
put_net_track(net, &neigh->ns_tracker);
kfree(neigh);
return rc;
}
static void efx_free_neigh(struct efx_neigh_binder *neigh)
{
struct efx_nic *efx = neigh->efx;
rhashtable_remove_fast(&efx->tc->neigh_ht, &neigh->linkage,
efx_neigh_ht_params);
synchronize_rcu();
netdev_put(neigh->egdev, &neigh->dev_tracker);
put_net_track(neigh->net, &neigh->ns_tracker);
kfree(neigh);
}
static void efx_release_neigh(struct efx_nic *efx,
struct efx_tc_encap_action *encap)
{
struct efx_neigh_binder *neigh = encap->neigh;
if (!neigh)
return;
list_del(&encap->list);
encap->neigh = NULL;
if (!refcount_dec_and_test(&neigh->ref))
return; /* still in use */
efx_free_neigh(neigh);
}
static void efx_gen_tun_header_eth(struct efx_tc_encap_action *encap, u16 proto)
{
struct efx_neigh_binder *neigh = encap->neigh;
struct ethhdr *eth;
encap->encap_hdr_len = sizeof(*eth);
eth = (struct ethhdr *)encap->encap_hdr;
if (encap->neigh->n_valid)
ether_addr_copy(eth->h_dest, neigh->ha);
else
eth_zero_addr(eth->h_dest);
ether_addr_copy(eth->h_source, neigh->egdev->dev_addr);
eth->h_proto = htons(proto);
}
static void efx_gen_tun_header_ipv4(struct efx_tc_encap_action *encap, u8 ipproto, u8 len)
{
struct efx_neigh_binder *neigh = encap->neigh;
struct ip_tunnel_key *key = &encap->key;
struct iphdr *ip;
ip = (struct iphdr *)(encap->encap_hdr + encap->encap_hdr_len);
encap->encap_hdr_len += sizeof(*ip);
ip->daddr = key->u.ipv4.dst;
ip->saddr = key->u.ipv4.src;
ip->ttl = neigh->ttl;
ip->protocol = ipproto;
ip->version = 0x4;
ip->ihl = 0x5;
ip->tot_len = cpu_to_be16(ip->ihl * 4 + len);
ip_send_check(ip);
}
#ifdef CONFIG_IPV6
static void efx_gen_tun_header_ipv6(struct efx_tc_encap_action *encap, u8 ipproto, u8 len)
{
struct efx_neigh_binder *neigh = encap->neigh;
struct ip_tunnel_key *key = &encap->key;
struct ipv6hdr *ip;
ip = (struct ipv6hdr *)(encap->encap_hdr + encap->encap_hdr_len);
encap->encap_hdr_len += sizeof(*ip);
ip6_flow_hdr(ip, key->tos, key->label);
ip->daddr = key->u.ipv6.dst;
ip->saddr = key->u.ipv6.src;
ip->hop_limit = neigh->ttl;
ip->nexthdr = ipproto;
ip->version = 0x6;
ip->payload_len = cpu_to_be16(len);
}
#endif
static void efx_gen_tun_header_udp(struct efx_tc_encap_action *encap, u8 len)
{
struct ip_tunnel_key *key = &encap->key;
struct udphdr *udp;
udp = (struct udphdr *)(encap->encap_hdr + encap->encap_hdr_len);
encap->encap_hdr_len += sizeof(*udp);
udp->dest = key->tp_dst;
udp->len = cpu_to_be16(sizeof(*udp) + len);
}
static void efx_gen_tun_header_vxlan(struct efx_tc_encap_action *encap)
{
struct ip_tunnel_key *key = &encap->key;
struct vxlanhdr *vxlan;
vxlan = (struct vxlanhdr *)(encap->encap_hdr + encap->encap_hdr_len);
encap->encap_hdr_len += sizeof(*vxlan);
vxlan->vx_flags = VXLAN_HF_VNI;
vxlan->vx_vni = vxlan_vni_field(tunnel_id_to_key32(key->tun_id));
}
static void efx_gen_tun_header_geneve(struct efx_tc_encap_action *encap)
{
struct ip_tunnel_key *key = &encap->key;
struct genevehdr *geneve;
u32 vni;
geneve = (struct genevehdr *)(encap->encap_hdr + encap->encap_hdr_len);
encap->encap_hdr_len += sizeof(*geneve);
geneve->proto_type = htons(ETH_P_TEB);
/* convert tun_id to host-endian so we can use host arithmetic to
* extract individual bytes.
*/
vni = ntohl(tunnel_id_to_key32(key->tun_id));
geneve->vni[0] = vni >> 16;
geneve->vni[1] = vni >> 8;
geneve->vni[2] = vni;
}
#define vxlan_header_l4_len (sizeof(struct udphdr) + sizeof(struct vxlanhdr))
#define vxlan4_header_len (sizeof(struct ethhdr) + sizeof(struct iphdr) + vxlan_header_l4_len)
static void efx_gen_vxlan_header_ipv4(struct efx_tc_encap_action *encap)
{
BUILD_BUG_ON(sizeof(encap->encap_hdr) < vxlan4_header_len);
efx_gen_tun_header_eth(encap, ETH_P_IP);
efx_gen_tun_header_ipv4(encap, IPPROTO_UDP, vxlan_header_l4_len);
efx_gen_tun_header_udp(encap, sizeof(struct vxlanhdr));
efx_gen_tun_header_vxlan(encap);
}
#define geneve_header_l4_len (sizeof(struct udphdr) + sizeof(struct genevehdr))
#define geneve4_header_len (sizeof(struct ethhdr) + sizeof(struct iphdr) + geneve_header_l4_len)
static void efx_gen_geneve_header_ipv4(struct efx_tc_encap_action *encap)
{
BUILD_BUG_ON(sizeof(encap->encap_hdr) < geneve4_header_len);
efx_gen_tun_header_eth(encap, ETH_P_IP);
efx_gen_tun_header_ipv4(encap, IPPROTO_UDP, geneve_header_l4_len);
efx_gen_tun_header_udp(encap, sizeof(struct genevehdr));
efx_gen_tun_header_geneve(encap);
}
#ifdef CONFIG_IPV6
#define vxlan6_header_len (sizeof(struct ethhdr) + sizeof(struct ipv6hdr) + vxlan_header_l4_len)
static void efx_gen_vxlan_header_ipv6(struct efx_tc_encap_action *encap)
{
BUILD_BUG_ON(sizeof(encap->encap_hdr) < vxlan6_header_len);
efx_gen_tun_header_eth(encap, ETH_P_IPV6);
efx_gen_tun_header_ipv6(encap, IPPROTO_UDP, vxlan_header_l4_len);
efx_gen_tun_header_udp(encap, sizeof(struct vxlanhdr));
efx_gen_tun_header_vxlan(encap);
}
#define geneve6_header_len (sizeof(struct ethhdr) + sizeof(struct ipv6hdr) + geneve_header_l4_len)
static void efx_gen_geneve_header_ipv6(struct efx_tc_encap_action *encap)
{
BUILD_BUG_ON(sizeof(encap->encap_hdr) < geneve6_header_len);
efx_gen_tun_header_eth(encap, ETH_P_IPV6);
efx_gen_tun_header_ipv6(encap, IPPROTO_UDP, geneve_header_l4_len);
efx_gen_tun_header_udp(encap, sizeof(struct genevehdr));
efx_gen_tun_header_geneve(encap);
}
#endif
static void efx_gen_encap_header(struct efx_nic *efx,
struct efx_tc_encap_action *encap)
{
encap->n_valid = encap->neigh->n_valid;
/* GCC stupidly thinks that only values explicitly listed in the enum
* definition can _possibly_ be sensible case values, so without this
* cast it complains about the IPv6 versions.
*/
switch ((int)encap->type) {
case EFX_ENCAP_TYPE_VXLAN:
efx_gen_vxlan_header_ipv4(encap);
break;
case EFX_ENCAP_TYPE_GENEVE:
efx_gen_geneve_header_ipv4(encap);
break;
#ifdef CONFIG_IPV6
case EFX_ENCAP_TYPE_VXLAN | EFX_ENCAP_FLAG_IPV6:
efx_gen_vxlan_header_ipv6(encap);
break;
case EFX_ENCAP_TYPE_GENEVE | EFX_ENCAP_FLAG_IPV6:
efx_gen_geneve_header_ipv6(encap);
break;
#endif
default:
/* unhandled encap type, can't happen */
if (net_ratelimit())
netif_err(efx, drv, efx->net_dev,
"Bogus encap type %d, can't generate\n",
encap->type);
/* Use fallback action. */
encap->n_valid = false;
break;
}
}
static void efx_tc_update_encap(struct efx_nic *efx,
struct efx_tc_encap_action *encap)
{
struct efx_tc_action_set_list *acts, *fallback;
struct efx_tc_flow_rule *rule;
struct efx_tc_action_set *act;
int rc;
if (encap->n_valid) {
/* Make sure no rules are using this encap while we change it */
list_for_each_entry(act, &encap->users, encap_user) {
acts = act->user;
if (WARN_ON(!acts)) /* can't happen */
continue;
rule = container_of(acts, struct efx_tc_flow_rule, acts);
if (rule->fallback)
fallback = rule->fallback;
else /* fallback fallback: deliver to PF */
fallback = &efx->tc->facts.pf;
rc = efx_mae_update_rule(efx, fallback->fw_id,
rule->fw_id);
if (rc)
netif_err(efx, drv, efx->net_dev,
"Failed to update (f) rule %08x rc %d\n",
rule->fw_id, rc);
else
netif_dbg(efx, drv, efx->net_dev, "Updated (f) rule %08x\n",
rule->fw_id);
}
}
/* Make sure we don't leak arbitrary bytes on the wire;
* set an all-0s ethernet header. A successful call to
* efx_gen_encap_header() will overwrite this.
*/
memset(encap->encap_hdr, 0, sizeof(encap->encap_hdr));
encap->encap_hdr_len = ETH_HLEN;
if (encap->neigh) {
read_lock_bh(&encap->neigh->lock);
efx_gen_encap_header(efx, encap);
read_unlock_bh(&encap->neigh->lock);
} else {
encap->n_valid = false;
}
rc = efx_mae_update_encap_md(efx, encap);
if (rc) {
netif_err(efx, drv, efx->net_dev,
"Failed to update encap hdr %08x rc %d\n",
encap->fw_id, rc);
return;
}
netif_dbg(efx, drv, efx->net_dev, "Updated encap hdr %08x\n",
encap->fw_id);
if (!encap->n_valid)
return;
/* Update rule users: use the action if they are now ready */
list_for_each_entry(act, &encap->users, encap_user) {
acts = act->user;
if (WARN_ON(!acts)) /* can't happen */
continue;
rule = container_of(acts, struct efx_tc_flow_rule, acts);
if (!efx_tc_check_ready(efx, rule))
continue;
rc = efx_mae_update_rule(efx, acts->fw_id, rule->fw_id);
if (rc)
netif_err(efx, drv, efx->net_dev,
"Failed to update rule %08x rc %d\n",
rule->fw_id, rc);
else
netif_dbg(efx, drv, efx->net_dev, "Updated rule %08x\n",
rule->fw_id);
}
}
static void efx_neigh_update(struct work_struct *work)
{
struct efx_neigh_binder *neigh = container_of(work, struct efx_neigh_binder, work);
struct efx_tc_encap_action *encap;
struct efx_nic *efx = neigh->efx;
mutex_lock(&efx->tc->mutex);
list_for_each_entry(encap, &neigh->users, list)
efx_tc_update_encap(neigh->efx, encap);
/* release ref taken in efx_neigh_event() */
if (refcount_dec_and_test(&neigh->ref))
efx_free_neigh(neigh);
mutex_unlock(&efx->tc->mutex);
}
static int efx_neigh_event(struct efx_nic *efx, struct neighbour *n)
{
struct efx_neigh_binder keys = {NULL}, *neigh;
bool n_valid, ipv6 = false;
char ha[ETH_ALEN];
size_t keysize;
if (WARN_ON(!efx->tc))
return NOTIFY_DONE;
if (n->tbl == &arp_tbl) {
keysize = sizeof(keys.dst_ip);
#if IS_ENABLED(CONFIG_IPV6)
} else if (n->tbl == ipv6_stub->nd_tbl) {
ipv6 = true;
keysize = sizeof(keys.dst_ip6);
#endif
} else {
return NOTIFY_DONE;
}
if (!n->parms) {
netif_warn(efx, drv, efx->net_dev, "neigh_event with no parms!\n");
return NOTIFY_DONE;
}
keys.net = read_pnet(&n->parms->net);
if (n->tbl->key_len != keysize) {
netif_warn(efx, drv, efx->net_dev, "neigh_event with bad key_len %u\n",
n->tbl->key_len);
return NOTIFY_DONE;
}
read_lock_bh(&n->lock); /* Get a consistent view */
memcpy(ha, n->ha, ETH_ALEN);
n_valid = (n->nud_state & NUD_VALID) && !n->dead;
read_unlock_bh(&n->lock);
if (ipv6)
memcpy(&keys.dst_ip6, n->primary_key, n->tbl->key_len);
else
memcpy(&keys.dst_ip, n->primary_key, n->tbl->key_len);
rcu_read_lock();
neigh = rhashtable_lookup_fast(&efx->tc->neigh_ht, &keys,
efx_neigh_ht_params);
if (!neigh || neigh->dying)
/* We're not interested in this neighbour */
goto done;
write_lock_bh(&neigh->lock);
if (n_valid == neigh->n_valid && !memcmp(ha, neigh->ha, ETH_ALEN)) {
write_unlock_bh(&neigh->lock);
/* Nothing has changed; no work to do */
goto done;
}
neigh->n_valid = n_valid;
memcpy(neigh->ha, ha, ETH_ALEN);
write_unlock_bh(&neigh->lock);
if (refcount_inc_not_zero(&neigh->ref)) {
rcu_read_unlock();
if (!schedule_work(&neigh->work))
/* failed to schedule, release the ref we just took */
if (refcount_dec_and_test(&neigh->ref))
efx_free_neigh(neigh);
} else {
done:
rcu_read_unlock();
}
return NOTIFY_DONE;
}
bool efx_tc_check_ready(struct efx_nic *efx, struct efx_tc_flow_rule *rule)
{
struct efx_tc_action_set *act;
/* Encap actions can only be offloaded if they have valid
* neighbour info for the outer Ethernet header.
*/
list_for_each_entry(act, &rule->acts.list, list)
if (act->encap_md && !act->encap_md->n_valid)
return false;
return true;
}
struct efx_tc_encap_action *efx_tc_flower_create_encap_md(
struct efx_nic *efx, const struct ip_tunnel_info *info,
struct net_device *egdev, struct netlink_ext_ack *extack)
{
enum efx_encap_type type = efx_tc_indr_netdev_type(egdev);
struct efx_tc_encap_action *encap, *old;
struct efx_rep *to_efv;
s64 rc;
if (type == EFX_ENCAP_TYPE_NONE) {
/* dest is not an encap device */
NL_SET_ERR_MSG_MOD(extack, "Not a (supported) tunnel device but tunnel_key is set");
return ERR_PTR(-EOPNOTSUPP);
}
rc = efx_mae_check_encap_type_supported(efx, type);
if (rc < 0) {
NL_SET_ERR_MSG_MOD(extack, "Firmware reports no support for this tunnel type");
return ERR_PTR(rc);
}
/* No support yet for Geneve options */
if (info->options_len) {
NL_SET_ERR_MSG_MOD(extack, "Unsupported tunnel options");
return ERR_PTR(-EOPNOTSUPP);
}
switch (info->mode) {
case IP_TUNNEL_INFO_TX:
break;
case IP_TUNNEL_INFO_TX | IP_TUNNEL_INFO_IPV6:
type |= EFX_ENCAP_FLAG_IPV6;
break;
default:
NL_SET_ERR_MSG_FMT_MOD(extack, "Unsupported tunnel mode %u",
info->mode);
return ERR_PTR(-EOPNOTSUPP);
}
encap = kzalloc(sizeof(*encap), GFP_KERNEL_ACCOUNT);
if (!encap)
return ERR_PTR(-ENOMEM);
encap->type = type;
encap->key = info->key;
INIT_LIST_HEAD(&encap->users);
old = rhashtable_lookup_get_insert_fast(&efx->tc->encap_ht,
&encap->linkage,
efx_tc_encap_ht_params);
if (old) {
/* don't need our new entry */
kfree(encap);
if (IS_ERR(old)) /* oh dear, it's actually an error */
return ERR_CAST(old);
if (!refcount_inc_not_zero(&old->ref))
return ERR_PTR(-EAGAIN);
/* existing entry found, ref taken */
return old;
}
rc = efx_bind_neigh(efx, encap, dev_net(egdev), extack);
if (rc < 0)
goto out_remove;
to_efv = efx_tc_flower_lookup_efv(efx, encap->neigh->egdev);
if (IS_ERR(to_efv)) {
/* neigh->egdev isn't ours */
NL_SET_ERR_MSG_MOD(extack, "Tunnel egress device not on switch");
rc = PTR_ERR(to_efv);
goto out_release;
}
rc = efx_tc_flower_external_mport(efx, to_efv);
if (rc < 0) {
NL_SET_ERR_MSG_MOD(extack, "Failed to identify tunnel egress m-port");
goto out_release;
}
encap->dest_mport = rc;
read_lock_bh(&encap->neigh->lock);
efx_gen_encap_header(efx, encap);
read_unlock_bh(&encap->neigh->lock);
rc = efx_mae_allocate_encap_md(efx, encap);
if (rc < 0) {
NL_SET_ERR_MSG_MOD(extack, "Failed to write tunnel header to hw");
goto out_release;
}
/* ref and return */
refcount_set(&encap->ref, 1);
return encap;
out_release:
efx_release_neigh(efx, encap);
out_remove:
rhashtable_remove_fast(&efx->tc->encap_ht, &encap->linkage,
efx_tc_encap_ht_params);
kfree(encap);
return ERR_PTR(rc);
}
void efx_tc_flower_release_encap_md(struct efx_nic *efx,
struct efx_tc_encap_action *encap)
{
if (!refcount_dec_and_test(&encap->ref))
return; /* still in use */
efx_release_neigh(efx, encap);
rhashtable_remove_fast(&efx->tc->encap_ht, &encap->linkage,
efx_tc_encap_ht_params);
efx_mae_free_encap_md(efx, encap);
kfree(encap);
}
static void efx_tc_remove_neigh_users(struct efx_nic *efx, struct efx_neigh_binder *neigh)
{
struct efx_tc_encap_action *encap, *next;
list_for_each_entry_safe(encap, next, &neigh->users, list) {
/* Should cause neigh usage count to fall to zero, freeing it */
efx_release_neigh(efx, encap);
/* The encap has lost its neigh, so it's now unready */
efx_tc_update_encap(efx, encap);
}
}
void efx_tc_unregister_egdev(struct efx_nic *efx, struct net_device *net_dev)
{
struct efx_neigh_binder *neigh;
struct rhashtable_iter walk;
mutex_lock(&efx->tc->mutex);
rhashtable_walk_enter(&efx->tc->neigh_ht, &walk);
rhashtable_walk_start(&walk);
while ((neigh = rhashtable_walk_next(&walk)) != NULL) {
if (IS_ERR(neigh))
continue;
if (neigh->egdev != net_dev)
continue;
neigh->dying = true;
rhashtable_walk_stop(&walk);
synchronize_rcu(); /* Make sure any updates see dying flag */
efx_tc_remove_neigh_users(efx, neigh); /* might sleep */
rhashtable_walk_start(&walk);
}
rhashtable_walk_stop(&walk);
rhashtable_walk_exit(&walk);
mutex_unlock(&efx->tc->mutex);
}
int efx_tc_netevent_event(struct efx_nic *efx, unsigned long event,
void *ptr)
{
if (efx->type->is_vf)
return NOTIFY_DONE;
switch (event) {
case NETEVENT_NEIGH_UPDATE:
return efx_neigh_event(efx, ptr);
default:
return NOTIFY_DONE;
}
}
|
linux-master
|
drivers/net/ethernet/sfc/tc_encap_actions.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2012-2013 Solarflare Communications Inc.
*/
#include "net_driver.h"
#include "rx_common.h"
#include "tx_common.h"
#include "ef10_regs.h"
#include "io.h"
#include "mcdi.h"
#include "mcdi_pcol.h"
#include "mcdi_port.h"
#include "mcdi_port_common.h"
#include "mcdi_functions.h"
#include "nic.h"
#include "mcdi_filters.h"
#include "workarounds.h"
#include "selftest.h"
#include "ef10_sriov.h"
#include <linux/in.h>
#include <linux/jhash.h>
#include <linux/wait.h>
#include <linux/workqueue.h>
#include <net/udp_tunnel.h>
/* Hardware control for EF10 architecture including 'Huntington'. */
#define EFX_EF10_DRVGEN_EV 7
enum {
EFX_EF10_TEST = 1,
EFX_EF10_REFILL,
};
/* VLAN list entry */
struct efx_ef10_vlan {
struct list_head list;
u16 vid;
};
static int efx_ef10_set_udp_tnl_ports(struct efx_nic *efx, bool unloading);
static const struct udp_tunnel_nic_info efx_ef10_udp_tunnels;
static int efx_ef10_get_warm_boot_count(struct efx_nic *efx)
{
efx_dword_t reg;
efx_readd(efx, ®, ER_DZ_BIU_MC_SFT_STATUS);
return EFX_DWORD_FIELD(reg, EFX_WORD_1) == 0xb007 ?
EFX_DWORD_FIELD(reg, EFX_WORD_0) : -EIO;
}
/* On all EF10s up to and including SFC9220 (Medford1), all PFs use BAR 0 for
* I/O space and BAR 2(&3) for memory. On SFC9250 (Medford2), there is no I/O
* bar; PFs use BAR 0/1 for memory.
*/
static unsigned int efx_ef10_pf_mem_bar(struct efx_nic *efx)
{
switch (efx->pci_dev->device) {
case 0x0b03: /* SFC9250 PF */
return 0;
default:
return 2;
}
}
/* All VFs use BAR 0/1 for memory */
static unsigned int efx_ef10_vf_mem_bar(struct efx_nic *efx)
{
return 0;
}
static unsigned int efx_ef10_mem_map_size(struct efx_nic *efx)
{
int bar;
bar = efx->type->mem_bar(efx);
return resource_size(&efx->pci_dev->resource[bar]);
}
static bool efx_ef10_is_vf(struct efx_nic *efx)
{
return efx->type->is_vf;
}
#ifdef CONFIG_SFC_SRIOV
static int efx_ef10_get_vf_index(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_FUNCTION_INFO_OUT_LEN);
struct efx_ef10_nic_data *nic_data = efx->nic_data;
size_t outlen;
int rc;
rc = efx_mcdi_rpc(efx, MC_CMD_GET_FUNCTION_INFO, NULL, 0, outbuf,
sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < sizeof(outbuf))
return -EIO;
nic_data->vf_index = MCDI_DWORD(outbuf, GET_FUNCTION_INFO_OUT_VF);
return 0;
}
#endif
static int efx_ef10_init_datapath_caps(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_CAPABILITIES_V4_OUT_LEN);
struct efx_ef10_nic_data *nic_data = efx->nic_data;
size_t outlen;
int rc;
BUILD_BUG_ON(MC_CMD_GET_CAPABILITIES_IN_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_GET_CAPABILITIES, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < MC_CMD_GET_CAPABILITIES_OUT_LEN) {
netif_err(efx, drv, efx->net_dev,
"unable to read datapath firmware capabilities\n");
return -EIO;
}
nic_data->datapath_caps =
MCDI_DWORD(outbuf, GET_CAPABILITIES_OUT_FLAGS1);
if (outlen >= MC_CMD_GET_CAPABILITIES_V2_OUT_LEN) {
nic_data->datapath_caps2 = MCDI_DWORD(outbuf,
GET_CAPABILITIES_V2_OUT_FLAGS2);
nic_data->piobuf_size = MCDI_WORD(outbuf,
GET_CAPABILITIES_V2_OUT_SIZE_PIO_BUFF);
} else {
nic_data->datapath_caps2 = 0;
nic_data->piobuf_size = ER_DZ_TX_PIOBUF_SIZE;
}
/* record the DPCPU firmware IDs to determine VEB vswitching support.
*/
nic_data->rx_dpcpu_fw_id =
MCDI_WORD(outbuf, GET_CAPABILITIES_OUT_RX_DPCPU_FW_ID);
nic_data->tx_dpcpu_fw_id =
MCDI_WORD(outbuf, GET_CAPABILITIES_OUT_TX_DPCPU_FW_ID);
if (!(nic_data->datapath_caps &
(1 << MC_CMD_GET_CAPABILITIES_OUT_RX_PREFIX_LEN_14_LBN))) {
netif_err(efx, probe, efx->net_dev,
"current firmware does not support an RX prefix\n");
return -ENODEV;
}
if (outlen >= MC_CMD_GET_CAPABILITIES_V3_OUT_LEN) {
u8 vi_window_mode = MCDI_BYTE(outbuf,
GET_CAPABILITIES_V3_OUT_VI_WINDOW_MODE);
rc = efx_mcdi_window_mode_to_stride(efx, vi_window_mode);
if (rc)
return rc;
} else {
/* keep default VI stride */
netif_dbg(efx, probe, efx->net_dev,
"firmware did not report VI window mode, assuming vi_stride = %u\n",
efx->vi_stride);
}
if (outlen >= MC_CMD_GET_CAPABILITIES_V4_OUT_LEN) {
efx->num_mac_stats = MCDI_WORD(outbuf,
GET_CAPABILITIES_V4_OUT_MAC_STATS_NUM_STATS);
netif_dbg(efx, probe, efx->net_dev,
"firmware reports num_mac_stats = %u\n",
efx->num_mac_stats);
} else {
/* leave num_mac_stats as the default value, MC_CMD_MAC_NSTATS */
netif_dbg(efx, probe, efx->net_dev,
"firmware did not report num_mac_stats, assuming %u\n",
efx->num_mac_stats);
}
return 0;
}
static void efx_ef10_read_licensed_features(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_LICENSING_V3_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_LICENSING_V3_OUT_LEN);
struct efx_ef10_nic_data *nic_data = efx->nic_data;
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, LICENSING_V3_IN_OP,
MC_CMD_LICENSING_V3_IN_OP_REPORT_LICENSE);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_LICENSING_V3, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc || (outlen < MC_CMD_LICENSING_V3_OUT_LEN))
return;
nic_data->licensed_features = MCDI_QWORD(outbuf,
LICENSING_V3_OUT_LICENSED_FEATURES);
}
static int efx_ef10_get_sysclk_freq(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_CLOCK_OUT_LEN);
int rc;
rc = efx_mcdi_rpc(efx, MC_CMD_GET_CLOCK, NULL, 0,
outbuf, sizeof(outbuf), NULL);
if (rc)
return rc;
rc = MCDI_DWORD(outbuf, GET_CLOCK_OUT_SYS_FREQ);
return rc > 0 ? rc : -ERANGE;
}
static int efx_ef10_get_timer_workarounds(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
unsigned int implemented;
unsigned int enabled;
int rc;
nic_data->workaround_35388 = false;
nic_data->workaround_61265 = false;
rc = efx_mcdi_get_workarounds(efx, &implemented, &enabled);
if (rc == -ENOSYS) {
/* Firmware without GET_WORKAROUNDS - not a problem. */
rc = 0;
} else if (rc == 0) {
/* Bug61265 workaround is always enabled if implemented. */
if (enabled & MC_CMD_GET_WORKAROUNDS_OUT_BUG61265)
nic_data->workaround_61265 = true;
if (enabled & MC_CMD_GET_WORKAROUNDS_OUT_BUG35388) {
nic_data->workaround_35388 = true;
} else if (implemented & MC_CMD_GET_WORKAROUNDS_OUT_BUG35388) {
/* Workaround is implemented but not enabled.
* Try to enable it.
*/
rc = efx_mcdi_set_workaround(efx,
MC_CMD_WORKAROUND_BUG35388,
true, NULL);
if (rc == 0)
nic_data->workaround_35388 = true;
/* If we failed to set the workaround just carry on. */
rc = 0;
}
}
netif_dbg(efx, probe, efx->net_dev,
"workaround for bug 35388 is %sabled\n",
nic_data->workaround_35388 ? "en" : "dis");
netif_dbg(efx, probe, efx->net_dev,
"workaround for bug 61265 is %sabled\n",
nic_data->workaround_61265 ? "en" : "dis");
return rc;
}
static void efx_ef10_process_timer_config(struct efx_nic *efx,
const efx_dword_t *data)
{
unsigned int max_count;
if (EFX_EF10_WORKAROUND_61265(efx)) {
efx->timer_quantum_ns = MCDI_DWORD(data,
GET_EVQ_TMR_PROPERTIES_OUT_MCDI_TMR_STEP_NS);
efx->timer_max_ns = MCDI_DWORD(data,
GET_EVQ_TMR_PROPERTIES_OUT_MCDI_TMR_MAX_NS);
} else if (EFX_EF10_WORKAROUND_35388(efx)) {
efx->timer_quantum_ns = MCDI_DWORD(data,
GET_EVQ_TMR_PROPERTIES_OUT_BUG35388_TMR_NS_PER_COUNT);
max_count = MCDI_DWORD(data,
GET_EVQ_TMR_PROPERTIES_OUT_BUG35388_TMR_MAX_COUNT);
efx->timer_max_ns = max_count * efx->timer_quantum_ns;
} else {
efx->timer_quantum_ns = MCDI_DWORD(data,
GET_EVQ_TMR_PROPERTIES_OUT_TMR_REG_NS_PER_COUNT);
max_count = MCDI_DWORD(data,
GET_EVQ_TMR_PROPERTIES_OUT_TMR_REG_MAX_COUNT);
efx->timer_max_ns = max_count * efx->timer_quantum_ns;
}
netif_dbg(efx, probe, efx->net_dev,
"got timer properties from MC: quantum %u ns; max %u ns\n",
efx->timer_quantum_ns, efx->timer_max_ns);
}
static int efx_ef10_get_timer_config(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_EVQ_TMR_PROPERTIES_OUT_LEN);
int rc;
rc = efx_ef10_get_timer_workarounds(efx);
if (rc)
return rc;
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_GET_EVQ_TMR_PROPERTIES, NULL, 0,
outbuf, sizeof(outbuf), NULL);
if (rc == 0) {
efx_ef10_process_timer_config(efx, outbuf);
} else if (rc == -ENOSYS || rc == -EPERM) {
/* Not available - fall back to Huntington defaults. */
unsigned int quantum;
rc = efx_ef10_get_sysclk_freq(efx);
if (rc < 0)
return rc;
quantum = 1536000 / rc; /* 1536 cycles */
efx->timer_quantum_ns = quantum;
efx->timer_max_ns = efx->type->timer_period_max * quantum;
rc = 0;
} else {
efx_mcdi_display_error(efx, MC_CMD_GET_EVQ_TMR_PROPERTIES,
MC_CMD_GET_EVQ_TMR_PROPERTIES_OUT_LEN,
NULL, 0, rc);
}
return rc;
}
static int efx_ef10_get_mac_address_pf(struct efx_nic *efx, u8 *mac_address)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_MAC_ADDRESSES_OUT_LEN);
size_t outlen;
int rc;
BUILD_BUG_ON(MC_CMD_GET_MAC_ADDRESSES_IN_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_GET_MAC_ADDRESSES, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < MC_CMD_GET_MAC_ADDRESSES_OUT_LEN)
return -EIO;
ether_addr_copy(mac_address,
MCDI_PTR(outbuf, GET_MAC_ADDRESSES_OUT_MAC_ADDR_BASE));
return 0;
}
static int efx_ef10_get_mac_address_vf(struct efx_nic *efx, u8 *mac_address)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_VPORT_GET_MAC_ADDRESSES_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_VPORT_GET_MAC_ADDRESSES_OUT_LENMAX);
size_t outlen;
int num_addrs, rc;
MCDI_SET_DWORD(inbuf, VPORT_GET_MAC_ADDRESSES_IN_VPORT_ID,
EVB_PORT_ID_ASSIGNED);
rc = efx_mcdi_rpc(efx, MC_CMD_VPORT_GET_MAC_ADDRESSES, inbuf,
sizeof(inbuf), outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < MC_CMD_VPORT_GET_MAC_ADDRESSES_OUT_LENMIN)
return -EIO;
num_addrs = MCDI_DWORD(outbuf,
VPORT_GET_MAC_ADDRESSES_OUT_MACADDR_COUNT);
WARN_ON(num_addrs != 1);
ether_addr_copy(mac_address,
MCDI_PTR(outbuf, VPORT_GET_MAC_ADDRESSES_OUT_MACADDR));
return 0;
}
static ssize_t link_control_flag_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct efx_nic *efx = dev_get_drvdata(dev);
return sprintf(buf, "%d\n",
((efx->mcdi->fn_flags) &
(1 << MC_CMD_DRV_ATTACH_EXT_OUT_FLAG_LINKCTRL))
? 1 : 0);
}
static ssize_t primary_flag_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct efx_nic *efx = dev_get_drvdata(dev);
return sprintf(buf, "%d\n",
((efx->mcdi->fn_flags) &
(1 << MC_CMD_DRV_ATTACH_EXT_OUT_FLAG_PRIMARY))
? 1 : 0);
}
static struct efx_ef10_vlan *efx_ef10_find_vlan(struct efx_nic *efx, u16 vid)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
struct efx_ef10_vlan *vlan;
WARN_ON(!mutex_is_locked(&nic_data->vlan_lock));
list_for_each_entry(vlan, &nic_data->vlan_list, list) {
if (vlan->vid == vid)
return vlan;
}
return NULL;
}
static int efx_ef10_add_vlan(struct efx_nic *efx, u16 vid)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
struct efx_ef10_vlan *vlan;
int rc;
mutex_lock(&nic_data->vlan_lock);
vlan = efx_ef10_find_vlan(efx, vid);
if (vlan) {
/* We add VID 0 on init. 8021q adds it on module init
* for all interfaces with VLAN filtring feature.
*/
if (vid == 0)
goto done_unlock;
netif_warn(efx, drv, efx->net_dev,
"VLAN %u already added\n", vid);
rc = -EALREADY;
goto fail_exist;
}
rc = -ENOMEM;
vlan = kzalloc(sizeof(*vlan), GFP_KERNEL);
if (!vlan)
goto fail_alloc;
vlan->vid = vid;
list_add_tail(&vlan->list, &nic_data->vlan_list);
if (efx->filter_state) {
mutex_lock(&efx->mac_lock);
down_write(&efx->filter_sem);
rc = efx_mcdi_filter_add_vlan(efx, vlan->vid);
up_write(&efx->filter_sem);
mutex_unlock(&efx->mac_lock);
if (rc)
goto fail_filter_add_vlan;
}
done_unlock:
mutex_unlock(&nic_data->vlan_lock);
return 0;
fail_filter_add_vlan:
list_del(&vlan->list);
kfree(vlan);
fail_alloc:
fail_exist:
mutex_unlock(&nic_data->vlan_lock);
return rc;
}
static void efx_ef10_del_vlan_internal(struct efx_nic *efx,
struct efx_ef10_vlan *vlan)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
WARN_ON(!mutex_is_locked(&nic_data->vlan_lock));
if (efx->filter_state) {
down_write(&efx->filter_sem);
efx_mcdi_filter_del_vlan(efx, vlan->vid);
up_write(&efx->filter_sem);
}
list_del(&vlan->list);
kfree(vlan);
}
static int efx_ef10_del_vlan(struct efx_nic *efx, u16 vid)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
struct efx_ef10_vlan *vlan;
int rc = 0;
/* 8021q removes VID 0 on module unload for all interfaces
* with VLAN filtering feature. We need to keep it to receive
* untagged traffic.
*/
if (vid == 0)
return 0;
mutex_lock(&nic_data->vlan_lock);
vlan = efx_ef10_find_vlan(efx, vid);
if (!vlan) {
netif_err(efx, drv, efx->net_dev,
"VLAN %u to be deleted not found\n", vid);
rc = -ENOENT;
} else {
efx_ef10_del_vlan_internal(efx, vlan);
}
mutex_unlock(&nic_data->vlan_lock);
return rc;
}
static void efx_ef10_cleanup_vlans(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
struct efx_ef10_vlan *vlan, *next_vlan;
mutex_lock(&nic_data->vlan_lock);
list_for_each_entry_safe(vlan, next_vlan, &nic_data->vlan_list, list)
efx_ef10_del_vlan_internal(efx, vlan);
mutex_unlock(&nic_data->vlan_lock);
}
static DEVICE_ATTR_RO(link_control_flag);
static DEVICE_ATTR_RO(primary_flag);
static int efx_ef10_probe(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data;
int i, rc;
nic_data = kzalloc(sizeof(*nic_data), GFP_KERNEL);
if (!nic_data)
return -ENOMEM;
efx->nic_data = nic_data;
/* we assume later that we can copy from this buffer in dwords */
BUILD_BUG_ON(MCDI_CTL_SDU_LEN_MAX_V2 % 4);
rc = efx_nic_alloc_buffer(efx, &nic_data->mcdi_buf,
8 + MCDI_CTL_SDU_LEN_MAX_V2, GFP_KERNEL);
if (rc)
goto fail1;
/* Get the MC's warm boot count. In case it's rebooting right
* now, be prepared to retry.
*/
i = 0;
for (;;) {
rc = efx_ef10_get_warm_boot_count(efx);
if (rc >= 0)
break;
if (++i == 5)
goto fail2;
ssleep(1);
}
nic_data->warm_boot_count = rc;
/* In case we're recovering from a crash (kexec), we want to
* cancel any outstanding request by the previous user of this
* function. We send a special message using the least
* significant bits of the 'high' (doorbell) register.
*/
_efx_writed(efx, cpu_to_le32(1), ER_DZ_MC_DB_HWRD);
rc = efx_mcdi_init(efx);
if (rc)
goto fail2;
mutex_init(&nic_data->udp_tunnels_lock);
for (i = 0; i < ARRAY_SIZE(nic_data->udp_tunnels); ++i)
nic_data->udp_tunnels[i].type =
TUNNEL_ENCAP_UDP_PORT_ENTRY_INVALID;
/* Reset (most) configuration for this function */
rc = efx_mcdi_reset(efx, RESET_TYPE_ALL);
if (rc)
goto fail3;
/* Enable event logging */
rc = efx_mcdi_log_ctrl(efx, true, false, 0);
if (rc)
goto fail3;
rc = device_create_file(&efx->pci_dev->dev,
&dev_attr_link_control_flag);
if (rc)
goto fail3;
rc = device_create_file(&efx->pci_dev->dev, &dev_attr_primary_flag);
if (rc)
goto fail4;
rc = efx_get_pf_index(efx, &nic_data->pf_index);
if (rc)
goto fail5;
rc = efx_ef10_init_datapath_caps(efx);
if (rc < 0)
goto fail5;
efx_ef10_read_licensed_features(efx);
/* We can have one VI for each vi_stride-byte region.
* However, until we use TX option descriptors we need up to four
* TX queues per channel for different checksumming combinations.
*/
if (nic_data->datapath_caps &
(1 << MC_CMD_GET_CAPABILITIES_OUT_VXLAN_NVGRE_LBN))
efx->tx_queues_per_channel = 4;
else
efx->tx_queues_per_channel = 2;
efx->max_vis = efx_ef10_mem_map_size(efx) / efx->vi_stride;
if (!efx->max_vis) {
netif_err(efx, drv, efx->net_dev, "error determining max VIs\n");
rc = -EIO;
goto fail5;
}
efx->max_channels = min_t(unsigned int, EFX_MAX_CHANNELS,
efx->max_vis / efx->tx_queues_per_channel);
efx->max_tx_channels = efx->max_channels;
if (WARN_ON(efx->max_channels == 0)) {
rc = -EIO;
goto fail5;
}
efx->rx_packet_len_offset =
ES_DZ_RX_PREFIX_PKTLEN_OFST - ES_DZ_RX_PREFIX_SIZE;
if (nic_data->datapath_caps &
(1 << MC_CMD_GET_CAPABILITIES_OUT_RX_INCLUDE_FCS_LBN))
efx->net_dev->hw_features |= NETIF_F_RXFCS;
rc = efx_mcdi_port_get_number(efx);
if (rc < 0)
goto fail5;
efx->port_num = rc;
rc = efx->type->get_mac_address(efx, efx->net_dev->perm_addr);
if (rc)
goto fail5;
rc = efx_ef10_get_timer_config(efx);
if (rc < 0)
goto fail5;
rc = efx_mcdi_mon_probe(efx);
if (rc && rc != -EPERM)
goto fail5;
efx_ptp_defer_probe_with_channel(efx);
#ifdef CONFIG_SFC_SRIOV
if ((efx->pci_dev->physfn) && (!efx->pci_dev->is_physfn)) {
struct pci_dev *pci_dev_pf = efx->pci_dev->physfn;
struct efx_nic *efx_pf = pci_get_drvdata(pci_dev_pf);
efx_pf->type->get_mac_address(efx_pf, nic_data->port_id);
} else
#endif
ether_addr_copy(nic_data->port_id, efx->net_dev->perm_addr);
INIT_LIST_HEAD(&nic_data->vlan_list);
mutex_init(&nic_data->vlan_lock);
/* Add unspecified VID to support VLAN filtering being disabled */
rc = efx_ef10_add_vlan(efx, EFX_FILTER_VID_UNSPEC);
if (rc)
goto fail_add_vid_unspec;
/* If VLAN filtering is enabled, we need VID 0 to get untagged
* traffic. It is added automatically if 8021q module is loaded,
* but we can't rely on it since module may be not loaded.
*/
rc = efx_ef10_add_vlan(efx, 0);
if (rc)
goto fail_add_vid_0;
if (nic_data->datapath_caps &
(1 << MC_CMD_GET_CAPABILITIES_OUT_VXLAN_NVGRE_LBN) &&
efx->mcdi->fn_flags &
(1 << MC_CMD_DRV_ATTACH_EXT_OUT_FLAG_TRUSTED))
efx->net_dev->udp_tunnel_nic_info = &efx_ef10_udp_tunnels;
return 0;
fail_add_vid_0:
efx_ef10_cleanup_vlans(efx);
fail_add_vid_unspec:
mutex_destroy(&nic_data->vlan_lock);
efx_ptp_remove(efx);
efx_mcdi_mon_remove(efx);
fail5:
device_remove_file(&efx->pci_dev->dev, &dev_attr_primary_flag);
fail4:
device_remove_file(&efx->pci_dev->dev, &dev_attr_link_control_flag);
fail3:
efx_mcdi_detach(efx);
mutex_lock(&nic_data->udp_tunnels_lock);
memset(nic_data->udp_tunnels, 0, sizeof(nic_data->udp_tunnels));
(void)efx_ef10_set_udp_tnl_ports(efx, true);
mutex_unlock(&nic_data->udp_tunnels_lock);
mutex_destroy(&nic_data->udp_tunnels_lock);
efx_mcdi_fini(efx);
fail2:
efx_nic_free_buffer(efx, &nic_data->mcdi_buf);
fail1:
kfree(nic_data);
efx->nic_data = NULL;
return rc;
}
#ifdef EFX_USE_PIO
static void efx_ef10_free_piobufs(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
MCDI_DECLARE_BUF(inbuf, MC_CMD_FREE_PIOBUF_IN_LEN);
unsigned int i;
int rc;
BUILD_BUG_ON(MC_CMD_FREE_PIOBUF_OUT_LEN != 0);
for (i = 0; i < nic_data->n_piobufs; i++) {
MCDI_SET_DWORD(inbuf, FREE_PIOBUF_IN_PIOBUF_HANDLE,
nic_data->piobuf_handle[i]);
rc = efx_mcdi_rpc(efx, MC_CMD_FREE_PIOBUF, inbuf, sizeof(inbuf),
NULL, 0, NULL);
WARN_ON(rc);
}
nic_data->n_piobufs = 0;
}
static int efx_ef10_alloc_piobufs(struct efx_nic *efx, unsigned int n)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
MCDI_DECLARE_BUF(outbuf, MC_CMD_ALLOC_PIOBUF_OUT_LEN);
unsigned int i;
size_t outlen;
int rc = 0;
BUILD_BUG_ON(MC_CMD_ALLOC_PIOBUF_IN_LEN != 0);
for (i = 0; i < n; i++) {
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_ALLOC_PIOBUF, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc) {
/* Don't display the MC error if we didn't have space
* for a VF.
*/
if (!(efx_ef10_is_vf(efx) && rc == -ENOSPC))
efx_mcdi_display_error(efx, MC_CMD_ALLOC_PIOBUF,
0, outbuf, outlen, rc);
break;
}
if (outlen < MC_CMD_ALLOC_PIOBUF_OUT_LEN) {
rc = -EIO;
break;
}
nic_data->piobuf_handle[i] =
MCDI_DWORD(outbuf, ALLOC_PIOBUF_OUT_PIOBUF_HANDLE);
netif_dbg(efx, probe, efx->net_dev,
"allocated PIO buffer %u handle %x\n", i,
nic_data->piobuf_handle[i]);
}
nic_data->n_piobufs = i;
if (rc)
efx_ef10_free_piobufs(efx);
return rc;
}
static int efx_ef10_link_piobufs(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
MCDI_DECLARE_BUF(inbuf, MC_CMD_LINK_PIOBUF_IN_LEN);
struct efx_channel *channel;
struct efx_tx_queue *tx_queue;
unsigned int offset, index;
int rc;
BUILD_BUG_ON(MC_CMD_LINK_PIOBUF_OUT_LEN != 0);
BUILD_BUG_ON(MC_CMD_UNLINK_PIOBUF_OUT_LEN != 0);
/* Link a buffer to each VI in the write-combining mapping */
for (index = 0; index < nic_data->n_piobufs; ++index) {
MCDI_SET_DWORD(inbuf, LINK_PIOBUF_IN_PIOBUF_HANDLE,
nic_data->piobuf_handle[index]);
MCDI_SET_DWORD(inbuf, LINK_PIOBUF_IN_TXQ_INSTANCE,
nic_data->pio_write_vi_base + index);
rc = efx_mcdi_rpc(efx, MC_CMD_LINK_PIOBUF,
inbuf, MC_CMD_LINK_PIOBUF_IN_LEN,
NULL, 0, NULL);
if (rc) {
netif_err(efx, drv, efx->net_dev,
"failed to link VI %u to PIO buffer %u (%d)\n",
nic_data->pio_write_vi_base + index, index,
rc);
goto fail;
}
netif_dbg(efx, probe, efx->net_dev,
"linked VI %u to PIO buffer %u\n",
nic_data->pio_write_vi_base + index, index);
}
/* Link a buffer to each TX queue */
efx_for_each_channel(channel, efx) {
/* Extra channels, even those with TXQs (PTP), do not require
* PIO resources.
*/
if (!channel->type->want_pio ||
channel->channel >= efx->xdp_channel_offset)
continue;
efx_for_each_channel_tx_queue(tx_queue, channel) {
/* We assign the PIO buffers to queues in
* reverse order to allow for the following
* special case.
*/
offset = ((efx->tx_channel_offset + efx->n_tx_channels -
tx_queue->channel->channel - 1) *
efx_piobuf_size);
index = offset / nic_data->piobuf_size;
offset = offset % nic_data->piobuf_size;
/* When the host page size is 4K, the first
* host page in the WC mapping may be within
* the same VI page as the last TX queue. We
* can only link one buffer to each VI.
*/
if (tx_queue->queue == nic_data->pio_write_vi_base) {
BUG_ON(index != 0);
rc = 0;
} else {
MCDI_SET_DWORD(inbuf,
LINK_PIOBUF_IN_PIOBUF_HANDLE,
nic_data->piobuf_handle[index]);
MCDI_SET_DWORD(inbuf,
LINK_PIOBUF_IN_TXQ_INSTANCE,
tx_queue->queue);
rc = efx_mcdi_rpc(efx, MC_CMD_LINK_PIOBUF,
inbuf, MC_CMD_LINK_PIOBUF_IN_LEN,
NULL, 0, NULL);
}
if (rc) {
/* This is non-fatal; the TX path just
* won't use PIO for this queue
*/
netif_err(efx, drv, efx->net_dev,
"failed to link VI %u to PIO buffer %u (%d)\n",
tx_queue->queue, index, rc);
tx_queue->piobuf = NULL;
} else {
tx_queue->piobuf =
nic_data->pio_write_base +
index * efx->vi_stride + offset;
tx_queue->piobuf_offset = offset;
netif_dbg(efx, probe, efx->net_dev,
"linked VI %u to PIO buffer %u offset %x addr %p\n",
tx_queue->queue, index,
tx_queue->piobuf_offset,
tx_queue->piobuf);
}
}
}
return 0;
fail:
/* inbuf was defined for MC_CMD_LINK_PIOBUF. We can use the same
* buffer for MC_CMD_UNLINK_PIOBUF because it's shorter.
*/
BUILD_BUG_ON(MC_CMD_LINK_PIOBUF_IN_LEN < MC_CMD_UNLINK_PIOBUF_IN_LEN);
while (index--) {
MCDI_SET_DWORD(inbuf, UNLINK_PIOBUF_IN_TXQ_INSTANCE,
nic_data->pio_write_vi_base + index);
efx_mcdi_rpc(efx, MC_CMD_UNLINK_PIOBUF,
inbuf, MC_CMD_UNLINK_PIOBUF_IN_LEN,
NULL, 0, NULL);
}
return rc;
}
static void efx_ef10_forget_old_piobufs(struct efx_nic *efx)
{
struct efx_channel *channel;
struct efx_tx_queue *tx_queue;
/* All our existing PIO buffers went away */
efx_for_each_channel(channel, efx)
efx_for_each_channel_tx_queue(tx_queue, channel)
tx_queue->piobuf = NULL;
}
#else /* !EFX_USE_PIO */
static int efx_ef10_alloc_piobufs(struct efx_nic *efx, unsigned int n)
{
return n == 0 ? 0 : -ENOBUFS;
}
static int efx_ef10_link_piobufs(struct efx_nic *efx)
{
return 0;
}
static void efx_ef10_free_piobufs(struct efx_nic *efx)
{
}
static void efx_ef10_forget_old_piobufs(struct efx_nic *efx)
{
}
#endif /* EFX_USE_PIO */
static void efx_ef10_remove(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
int rc;
#ifdef CONFIG_SFC_SRIOV
struct efx_ef10_nic_data *nic_data_pf;
struct pci_dev *pci_dev_pf;
struct efx_nic *efx_pf;
struct ef10_vf *vf;
if (efx->pci_dev->is_virtfn) {
pci_dev_pf = efx->pci_dev->physfn;
if (pci_dev_pf) {
efx_pf = pci_get_drvdata(pci_dev_pf);
nic_data_pf = efx_pf->nic_data;
vf = nic_data_pf->vf + nic_data->vf_index;
vf->efx = NULL;
} else
netif_info(efx, drv, efx->net_dev,
"Could not get the PF id from VF\n");
}
#endif
efx_ef10_cleanup_vlans(efx);
mutex_destroy(&nic_data->vlan_lock);
efx_ptp_remove(efx);
efx_mcdi_mon_remove(efx);
efx_mcdi_rx_free_indir_table(efx);
if (nic_data->wc_membase)
iounmap(nic_data->wc_membase);
rc = efx_mcdi_free_vis(efx);
WARN_ON(rc != 0);
if (!nic_data->must_restore_piobufs)
efx_ef10_free_piobufs(efx);
device_remove_file(&efx->pci_dev->dev, &dev_attr_primary_flag);
device_remove_file(&efx->pci_dev->dev, &dev_attr_link_control_flag);
efx_mcdi_detach(efx);
memset(nic_data->udp_tunnels, 0, sizeof(nic_data->udp_tunnels));
mutex_lock(&nic_data->udp_tunnels_lock);
(void)efx_ef10_set_udp_tnl_ports(efx, true);
mutex_unlock(&nic_data->udp_tunnels_lock);
mutex_destroy(&nic_data->udp_tunnels_lock);
efx_mcdi_fini(efx);
efx_nic_free_buffer(efx, &nic_data->mcdi_buf);
kfree(nic_data);
}
static int efx_ef10_probe_pf(struct efx_nic *efx)
{
return efx_ef10_probe(efx);
}
int efx_ef10_vadaptor_query(struct efx_nic *efx, unsigned int port_id,
u32 *port_flags, u32 *vadaptor_flags,
unsigned int *vlan_tags)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
MCDI_DECLARE_BUF(inbuf, MC_CMD_VADAPTOR_QUERY_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_VADAPTOR_QUERY_OUT_LEN);
size_t outlen;
int rc;
if (nic_data->datapath_caps &
(1 << MC_CMD_GET_CAPABILITIES_OUT_VADAPTOR_QUERY_LBN)) {
MCDI_SET_DWORD(inbuf, VADAPTOR_QUERY_IN_UPSTREAM_PORT_ID,
port_id);
rc = efx_mcdi_rpc(efx, MC_CMD_VADAPTOR_QUERY, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < sizeof(outbuf)) {
rc = -EIO;
return rc;
}
}
if (port_flags)
*port_flags = MCDI_DWORD(outbuf, VADAPTOR_QUERY_OUT_PORT_FLAGS);
if (vadaptor_flags)
*vadaptor_flags =
MCDI_DWORD(outbuf, VADAPTOR_QUERY_OUT_VADAPTOR_FLAGS);
if (vlan_tags)
*vlan_tags =
MCDI_DWORD(outbuf,
VADAPTOR_QUERY_OUT_NUM_AVAILABLE_VLAN_TAGS);
return 0;
}
int efx_ef10_vadaptor_alloc(struct efx_nic *efx, unsigned int port_id)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_VADAPTOR_ALLOC_IN_LEN);
MCDI_SET_DWORD(inbuf, VADAPTOR_ALLOC_IN_UPSTREAM_PORT_ID, port_id);
return efx_mcdi_rpc(efx, MC_CMD_VADAPTOR_ALLOC, inbuf, sizeof(inbuf),
NULL, 0, NULL);
}
int efx_ef10_vadaptor_free(struct efx_nic *efx, unsigned int port_id)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_VADAPTOR_FREE_IN_LEN);
MCDI_SET_DWORD(inbuf, VADAPTOR_FREE_IN_UPSTREAM_PORT_ID, port_id);
return efx_mcdi_rpc(efx, MC_CMD_VADAPTOR_FREE, inbuf, sizeof(inbuf),
NULL, 0, NULL);
}
int efx_ef10_vport_add_mac(struct efx_nic *efx,
unsigned int port_id, const u8 *mac)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_VPORT_ADD_MAC_ADDRESS_IN_LEN);
MCDI_SET_DWORD(inbuf, VPORT_ADD_MAC_ADDRESS_IN_VPORT_ID, port_id);
ether_addr_copy(MCDI_PTR(inbuf, VPORT_ADD_MAC_ADDRESS_IN_MACADDR), mac);
return efx_mcdi_rpc(efx, MC_CMD_VPORT_ADD_MAC_ADDRESS, inbuf,
sizeof(inbuf), NULL, 0, NULL);
}
int efx_ef10_vport_del_mac(struct efx_nic *efx,
unsigned int port_id, const u8 *mac)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_VPORT_DEL_MAC_ADDRESS_IN_LEN);
MCDI_SET_DWORD(inbuf, VPORT_DEL_MAC_ADDRESS_IN_VPORT_ID, port_id);
ether_addr_copy(MCDI_PTR(inbuf, VPORT_DEL_MAC_ADDRESS_IN_MACADDR), mac);
return efx_mcdi_rpc(efx, MC_CMD_VPORT_DEL_MAC_ADDRESS, inbuf,
sizeof(inbuf), NULL, 0, NULL);
}
#ifdef CONFIG_SFC_SRIOV
static int efx_ef10_probe_vf(struct efx_nic *efx)
{
int rc;
struct pci_dev *pci_dev_pf;
/* If the parent PF has no VF data structure, it doesn't know about this
* VF so fail probe. The VF needs to be re-created. This can happen
* if the PF driver was unloaded while any VF was assigned to a guest
* (using Xen, only).
*/
pci_dev_pf = efx->pci_dev->physfn;
if (pci_dev_pf) {
struct efx_nic *efx_pf = pci_get_drvdata(pci_dev_pf);
struct efx_ef10_nic_data *nic_data_pf = efx_pf->nic_data;
if (!nic_data_pf->vf) {
netif_info(efx, drv, efx->net_dev,
"The VF cannot link to its parent PF; "
"please destroy and re-create the VF\n");
return -EBUSY;
}
}
rc = efx_ef10_probe(efx);
if (rc)
return rc;
rc = efx_ef10_get_vf_index(efx);
if (rc)
goto fail;
if (efx->pci_dev->is_virtfn) {
if (efx->pci_dev->physfn) {
struct efx_nic *efx_pf =
pci_get_drvdata(efx->pci_dev->physfn);
struct efx_ef10_nic_data *nic_data_p = efx_pf->nic_data;
struct efx_ef10_nic_data *nic_data = efx->nic_data;
nic_data_p->vf[nic_data->vf_index].efx = efx;
nic_data_p->vf[nic_data->vf_index].pci_dev =
efx->pci_dev;
} else
netif_info(efx, drv, efx->net_dev,
"Could not get the PF id from VF\n");
}
return 0;
fail:
efx_ef10_remove(efx);
return rc;
}
#else
static int efx_ef10_probe_vf(struct efx_nic *efx __attribute__ ((unused)))
{
return 0;
}
#endif
static int efx_ef10_alloc_vis(struct efx_nic *efx,
unsigned int min_vis, unsigned int max_vis)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
return efx_mcdi_alloc_vis(efx, min_vis, max_vis, &nic_data->vi_base,
&nic_data->n_allocated_vis);
}
/* Note that the failure path of this function does not free
* resources, as this will be done by efx_ef10_remove().
*/
static int efx_ef10_dimension_resources(struct efx_nic *efx)
{
unsigned int min_vis = max_t(unsigned int, efx->tx_queues_per_channel,
efx_separate_tx_channels ? 2 : 1);
unsigned int channel_vis, pio_write_vi_base, max_vis;
struct efx_ef10_nic_data *nic_data = efx->nic_data;
unsigned int uc_mem_map_size, wc_mem_map_size;
void __iomem *membase;
int rc;
channel_vis = max(efx->n_channels,
((efx->n_tx_channels + efx->n_extra_tx_channels) *
efx->tx_queues_per_channel) +
efx->n_xdp_channels * efx->xdp_tx_per_channel);
if (efx->max_vis && efx->max_vis < channel_vis) {
netif_dbg(efx, drv, efx->net_dev,
"Reducing channel VIs from %u to %u\n",
channel_vis, efx->max_vis);
channel_vis = efx->max_vis;
}
#ifdef EFX_USE_PIO
/* Try to allocate PIO buffers if wanted and if the full
* number of PIO buffers would be sufficient to allocate one
* copy-buffer per TX channel. Failure is non-fatal, as there
* are only a small number of PIO buffers shared between all
* functions of the controller.
*/
if (efx_piobuf_size != 0 &&
nic_data->piobuf_size / efx_piobuf_size * EF10_TX_PIOBUF_COUNT >=
efx->n_tx_channels) {
unsigned int n_piobufs =
DIV_ROUND_UP(efx->n_tx_channels,
nic_data->piobuf_size / efx_piobuf_size);
rc = efx_ef10_alloc_piobufs(efx, n_piobufs);
if (rc == -ENOSPC)
netif_dbg(efx, probe, efx->net_dev,
"out of PIO buffers; cannot allocate more\n");
else if (rc == -EPERM)
netif_dbg(efx, probe, efx->net_dev,
"not permitted to allocate PIO buffers\n");
else if (rc)
netif_err(efx, probe, efx->net_dev,
"failed to allocate PIO buffers (%d)\n", rc);
else
netif_dbg(efx, probe, efx->net_dev,
"allocated %u PIO buffers\n", n_piobufs);
}
#else
nic_data->n_piobufs = 0;
#endif
/* PIO buffers should be mapped with write-combining enabled,
* and we want to make single UC and WC mappings rather than
* several of each (in fact that's the only option if host
* page size is >4K). So we may allocate some extra VIs just
* for writing PIO buffers through.
*
* The UC mapping contains (channel_vis - 1) complete VIs and the
* first 4K of the next VI. Then the WC mapping begins with
* the remainder of this last VI.
*/
uc_mem_map_size = PAGE_ALIGN((channel_vis - 1) * efx->vi_stride +
ER_DZ_TX_PIOBUF);
if (nic_data->n_piobufs) {
/* pio_write_vi_base rounds down to give the number of complete
* VIs inside the UC mapping.
*/
pio_write_vi_base = uc_mem_map_size / efx->vi_stride;
wc_mem_map_size = (PAGE_ALIGN((pio_write_vi_base +
nic_data->n_piobufs) *
efx->vi_stride) -
uc_mem_map_size);
max_vis = pio_write_vi_base + nic_data->n_piobufs;
} else {
pio_write_vi_base = 0;
wc_mem_map_size = 0;
max_vis = channel_vis;
}
/* In case the last attached driver failed to free VIs, do it now */
rc = efx_mcdi_free_vis(efx);
if (rc != 0)
return rc;
rc = efx_ef10_alloc_vis(efx, min_vis, max_vis);
if (rc != 0)
return rc;
if (nic_data->n_allocated_vis < channel_vis) {
netif_info(efx, drv, efx->net_dev,
"Could not allocate enough VIs to satisfy RSS"
" requirements. Performance may not be optimal.\n");
/* We didn't get the VIs to populate our channels.
* We could keep what we got but then we'd have more
* interrupts than we need.
* Instead calculate new max_channels and restart
*/
efx->max_channels = nic_data->n_allocated_vis;
efx->max_tx_channels =
nic_data->n_allocated_vis / efx->tx_queues_per_channel;
efx_mcdi_free_vis(efx);
return -EAGAIN;
}
/* If we didn't get enough VIs to map all the PIO buffers, free the
* PIO buffers
*/
if (nic_data->n_piobufs &&
nic_data->n_allocated_vis <
pio_write_vi_base + nic_data->n_piobufs) {
netif_dbg(efx, probe, efx->net_dev,
"%u VIs are not sufficient to map %u PIO buffers\n",
nic_data->n_allocated_vis, nic_data->n_piobufs);
efx_ef10_free_piobufs(efx);
}
/* Shrink the original UC mapping of the memory BAR */
membase = ioremap(efx->membase_phys, uc_mem_map_size);
if (!membase) {
netif_err(efx, probe, efx->net_dev,
"could not shrink memory BAR to %x\n",
uc_mem_map_size);
return -ENOMEM;
}
iounmap(efx->membase);
efx->membase = membase;
/* Set up the WC mapping if needed */
if (wc_mem_map_size) {
nic_data->wc_membase = ioremap_wc(efx->membase_phys +
uc_mem_map_size,
wc_mem_map_size);
if (!nic_data->wc_membase) {
netif_err(efx, probe, efx->net_dev,
"could not allocate WC mapping of size %x\n",
wc_mem_map_size);
return -ENOMEM;
}
nic_data->pio_write_vi_base = pio_write_vi_base;
nic_data->pio_write_base =
nic_data->wc_membase +
(pio_write_vi_base * efx->vi_stride + ER_DZ_TX_PIOBUF -
uc_mem_map_size);
rc = efx_ef10_link_piobufs(efx);
if (rc)
efx_ef10_free_piobufs(efx);
}
netif_dbg(efx, probe, efx->net_dev,
"memory BAR at %pa (virtual %p+%x UC, %p+%x WC)\n",
&efx->membase_phys, efx->membase, uc_mem_map_size,
nic_data->wc_membase, wc_mem_map_size);
return 0;
}
static void efx_ef10_fini_nic(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
spin_lock_bh(&efx->stats_lock);
kfree(nic_data->mc_stats);
nic_data->mc_stats = NULL;
spin_unlock_bh(&efx->stats_lock);
}
static int efx_ef10_init_nic(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
struct net_device *net_dev = efx->net_dev;
netdev_features_t tun_feats, tso_feats;
int rc;
if (nic_data->must_check_datapath_caps) {
rc = efx_ef10_init_datapath_caps(efx);
if (rc)
return rc;
nic_data->must_check_datapath_caps = false;
}
if (efx->must_realloc_vis) {
/* We cannot let the number of VIs change now */
rc = efx_ef10_alloc_vis(efx, nic_data->n_allocated_vis,
nic_data->n_allocated_vis);
if (rc)
return rc;
efx->must_realloc_vis = false;
}
nic_data->mc_stats = kmalloc(efx->num_mac_stats * sizeof(__le64),
GFP_KERNEL);
if (!nic_data->mc_stats)
return -ENOMEM;
if (nic_data->must_restore_piobufs && nic_data->n_piobufs) {
rc = efx_ef10_alloc_piobufs(efx, nic_data->n_piobufs);
if (rc == 0) {
rc = efx_ef10_link_piobufs(efx);
if (rc)
efx_ef10_free_piobufs(efx);
}
/* Log an error on failure, but this is non-fatal.
* Permission errors are less important - we've presumably
* had the PIO buffer licence removed.
*/
if (rc == -EPERM)
netif_dbg(efx, drv, efx->net_dev,
"not permitted to restore PIO buffers\n");
else if (rc)
netif_err(efx, drv, efx->net_dev,
"failed to restore PIO buffers (%d)\n", rc);
nic_data->must_restore_piobufs = false;
}
/* encap features might change during reset if fw variant changed */
if (efx_has_cap(efx, VXLAN_NVGRE) && !efx_ef10_is_vf(efx))
net_dev->hw_enc_features |= NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM;
else
net_dev->hw_enc_features &= ~(NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM);
tun_feats = NETIF_F_GSO_UDP_TUNNEL | NETIF_F_GSO_GRE |
NETIF_F_GSO_UDP_TUNNEL_CSUM | NETIF_F_GSO_GRE_CSUM;
tso_feats = NETIF_F_TSO | NETIF_F_TSO6;
if (efx_has_cap(efx, TX_TSO_V2_ENCAP)) {
/* If this is first nic_init, or if it is a reset and a new fw
* variant has added new features, enable them by default.
* If the features are not new, maintain their current value.
*/
if (!(net_dev->hw_features & tun_feats))
net_dev->features |= tun_feats;
net_dev->hw_enc_features |= tun_feats | tso_feats;
net_dev->hw_features |= tun_feats;
} else {
net_dev->hw_enc_features &= ~(tun_feats | tso_feats);
net_dev->hw_features &= ~tun_feats;
net_dev->features &= ~tun_feats;
}
/* don't fail init if RSS setup doesn't work */
rc = efx->type->rx_push_rss_config(efx, false,
efx->rss_context.rx_indir_table, NULL);
return 0;
}
static void efx_ef10_table_reset_mc_allocations(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
#ifdef CONFIG_SFC_SRIOV
unsigned int i;
#endif
/* All our allocations have been reset */
efx->must_realloc_vis = true;
efx_mcdi_filter_table_reset_mc_allocations(efx);
nic_data->must_restore_piobufs = true;
efx_ef10_forget_old_piobufs(efx);
efx->rss_context.context_id = EFX_MCDI_RSS_CONTEXT_INVALID;
/* Driver-created vswitches and vports must be re-created */
nic_data->must_probe_vswitching = true;
efx->vport_id = EVB_PORT_ID_ASSIGNED;
#ifdef CONFIG_SFC_SRIOV
if (nic_data->vf)
for (i = 0; i < efx->vf_count; i++)
nic_data->vf[i].vport_id = 0;
#endif
}
static enum reset_type efx_ef10_map_reset_reason(enum reset_type reason)
{
if (reason == RESET_TYPE_MC_FAILURE)
return RESET_TYPE_DATAPATH;
return efx_mcdi_map_reset_reason(reason);
}
static int efx_ef10_map_reset_flags(u32 *flags)
{
enum {
EF10_RESET_PORT = ((ETH_RESET_MAC | ETH_RESET_PHY) <<
ETH_RESET_SHARED_SHIFT),
EF10_RESET_MC = ((ETH_RESET_DMA | ETH_RESET_FILTER |
ETH_RESET_OFFLOAD | ETH_RESET_MAC |
ETH_RESET_PHY | ETH_RESET_MGMT) <<
ETH_RESET_SHARED_SHIFT)
};
/* We assume for now that our PCI function is permitted to
* reset everything.
*/
if ((*flags & EF10_RESET_MC) == EF10_RESET_MC) {
*flags &= ~EF10_RESET_MC;
return RESET_TYPE_WORLD;
}
if ((*flags & EF10_RESET_PORT) == EF10_RESET_PORT) {
*flags &= ~EF10_RESET_PORT;
return RESET_TYPE_ALL;
}
/* no invisible reset implemented */
return -EINVAL;
}
static int efx_ef10_reset(struct efx_nic *efx, enum reset_type reset_type)
{
int rc = efx_mcdi_reset(efx, reset_type);
/* Unprivileged functions return -EPERM, but need to return success
* here so that the datapath is brought back up.
*/
if (reset_type == RESET_TYPE_WORLD && rc == -EPERM)
rc = 0;
/* If it was a port reset, trigger reallocation of MC resources.
* Note that on an MC reset nothing needs to be done now because we'll
* detect the MC reset later and handle it then.
* For an FLR, we never get an MC reset event, but the MC has reset all
* resources assigned to us, so we have to trigger reallocation now.
*/
if ((reset_type == RESET_TYPE_ALL ||
reset_type == RESET_TYPE_MCDI_TIMEOUT) && !rc)
efx_ef10_table_reset_mc_allocations(efx);
return rc;
}
#define EF10_DMA_STAT(ext_name, mcdi_name) \
[EF10_STAT_ ## ext_name] = \
{ #ext_name, 64, 8 * MC_CMD_MAC_ ## mcdi_name }
#define EF10_DMA_INVIS_STAT(int_name, mcdi_name) \
[EF10_STAT_ ## int_name] = \
{ NULL, 64, 8 * MC_CMD_MAC_ ## mcdi_name }
#define EF10_OTHER_STAT(ext_name) \
[EF10_STAT_ ## ext_name] = { #ext_name, 0, 0 }
static const struct efx_hw_stat_desc efx_ef10_stat_desc[EF10_STAT_COUNT] = {
EF10_DMA_STAT(port_tx_bytes, TX_BYTES),
EF10_DMA_STAT(port_tx_packets, TX_PKTS),
EF10_DMA_STAT(port_tx_pause, TX_PAUSE_PKTS),
EF10_DMA_STAT(port_tx_control, TX_CONTROL_PKTS),
EF10_DMA_STAT(port_tx_unicast, TX_UNICAST_PKTS),
EF10_DMA_STAT(port_tx_multicast, TX_MULTICAST_PKTS),
EF10_DMA_STAT(port_tx_broadcast, TX_BROADCAST_PKTS),
EF10_DMA_STAT(port_tx_lt64, TX_LT64_PKTS),
EF10_DMA_STAT(port_tx_64, TX_64_PKTS),
EF10_DMA_STAT(port_tx_65_to_127, TX_65_TO_127_PKTS),
EF10_DMA_STAT(port_tx_128_to_255, TX_128_TO_255_PKTS),
EF10_DMA_STAT(port_tx_256_to_511, TX_256_TO_511_PKTS),
EF10_DMA_STAT(port_tx_512_to_1023, TX_512_TO_1023_PKTS),
EF10_DMA_STAT(port_tx_1024_to_15xx, TX_1024_TO_15XX_PKTS),
EF10_DMA_STAT(port_tx_15xx_to_jumbo, TX_15XX_TO_JUMBO_PKTS),
EF10_DMA_STAT(port_rx_bytes, RX_BYTES),
EF10_DMA_INVIS_STAT(port_rx_bytes_minus_good_bytes, RX_BAD_BYTES),
EF10_OTHER_STAT(port_rx_good_bytes),
EF10_OTHER_STAT(port_rx_bad_bytes),
EF10_DMA_STAT(port_rx_packets, RX_PKTS),
EF10_DMA_STAT(port_rx_good, RX_GOOD_PKTS),
EF10_DMA_STAT(port_rx_bad, RX_BAD_FCS_PKTS),
EF10_DMA_STAT(port_rx_pause, RX_PAUSE_PKTS),
EF10_DMA_STAT(port_rx_control, RX_CONTROL_PKTS),
EF10_DMA_STAT(port_rx_unicast, RX_UNICAST_PKTS),
EF10_DMA_STAT(port_rx_multicast, RX_MULTICAST_PKTS),
EF10_DMA_STAT(port_rx_broadcast, RX_BROADCAST_PKTS),
EF10_DMA_STAT(port_rx_lt64, RX_UNDERSIZE_PKTS),
EF10_DMA_STAT(port_rx_64, RX_64_PKTS),
EF10_DMA_STAT(port_rx_65_to_127, RX_65_TO_127_PKTS),
EF10_DMA_STAT(port_rx_128_to_255, RX_128_TO_255_PKTS),
EF10_DMA_STAT(port_rx_256_to_511, RX_256_TO_511_PKTS),
EF10_DMA_STAT(port_rx_512_to_1023, RX_512_TO_1023_PKTS),
EF10_DMA_STAT(port_rx_1024_to_15xx, RX_1024_TO_15XX_PKTS),
EF10_DMA_STAT(port_rx_15xx_to_jumbo, RX_15XX_TO_JUMBO_PKTS),
EF10_DMA_STAT(port_rx_gtjumbo, RX_GTJUMBO_PKTS),
EF10_DMA_STAT(port_rx_bad_gtjumbo, RX_JABBER_PKTS),
EF10_DMA_STAT(port_rx_overflow, RX_OVERFLOW_PKTS),
EF10_DMA_STAT(port_rx_align_error, RX_ALIGN_ERROR_PKTS),
EF10_DMA_STAT(port_rx_length_error, RX_LENGTH_ERROR_PKTS),
EF10_DMA_STAT(port_rx_nodesc_drops, RX_NODESC_DROPS),
EFX_GENERIC_SW_STAT(rx_nodesc_trunc),
EFX_GENERIC_SW_STAT(rx_noskb_drops),
EF10_DMA_STAT(port_rx_pm_trunc_bb_overflow, PM_TRUNC_BB_OVERFLOW),
EF10_DMA_STAT(port_rx_pm_discard_bb_overflow, PM_DISCARD_BB_OVERFLOW),
EF10_DMA_STAT(port_rx_pm_trunc_vfifo_full, PM_TRUNC_VFIFO_FULL),
EF10_DMA_STAT(port_rx_pm_discard_vfifo_full, PM_DISCARD_VFIFO_FULL),
EF10_DMA_STAT(port_rx_pm_trunc_qbb, PM_TRUNC_QBB),
EF10_DMA_STAT(port_rx_pm_discard_qbb, PM_DISCARD_QBB),
EF10_DMA_STAT(port_rx_pm_discard_mapping, PM_DISCARD_MAPPING),
EF10_DMA_STAT(port_rx_dp_q_disabled_packets, RXDP_Q_DISABLED_PKTS),
EF10_DMA_STAT(port_rx_dp_di_dropped_packets, RXDP_DI_DROPPED_PKTS),
EF10_DMA_STAT(port_rx_dp_streaming_packets, RXDP_STREAMING_PKTS),
EF10_DMA_STAT(port_rx_dp_hlb_fetch, RXDP_HLB_FETCH_CONDITIONS),
EF10_DMA_STAT(port_rx_dp_hlb_wait, RXDP_HLB_WAIT_CONDITIONS),
EF10_DMA_STAT(rx_unicast, VADAPTER_RX_UNICAST_PACKETS),
EF10_DMA_STAT(rx_unicast_bytes, VADAPTER_RX_UNICAST_BYTES),
EF10_DMA_STAT(rx_multicast, VADAPTER_RX_MULTICAST_PACKETS),
EF10_DMA_STAT(rx_multicast_bytes, VADAPTER_RX_MULTICAST_BYTES),
EF10_DMA_STAT(rx_broadcast, VADAPTER_RX_BROADCAST_PACKETS),
EF10_DMA_STAT(rx_broadcast_bytes, VADAPTER_RX_BROADCAST_BYTES),
EF10_DMA_STAT(rx_bad, VADAPTER_RX_BAD_PACKETS),
EF10_DMA_STAT(rx_bad_bytes, VADAPTER_RX_BAD_BYTES),
EF10_DMA_STAT(rx_overflow, VADAPTER_RX_OVERFLOW),
EF10_DMA_STAT(tx_unicast, VADAPTER_TX_UNICAST_PACKETS),
EF10_DMA_STAT(tx_unicast_bytes, VADAPTER_TX_UNICAST_BYTES),
EF10_DMA_STAT(tx_multicast, VADAPTER_TX_MULTICAST_PACKETS),
EF10_DMA_STAT(tx_multicast_bytes, VADAPTER_TX_MULTICAST_BYTES),
EF10_DMA_STAT(tx_broadcast, VADAPTER_TX_BROADCAST_PACKETS),
EF10_DMA_STAT(tx_broadcast_bytes, VADAPTER_TX_BROADCAST_BYTES),
EF10_DMA_STAT(tx_bad, VADAPTER_TX_BAD_PACKETS),
EF10_DMA_STAT(tx_bad_bytes, VADAPTER_TX_BAD_BYTES),
EF10_DMA_STAT(tx_overflow, VADAPTER_TX_OVERFLOW),
EF10_DMA_STAT(fec_uncorrected_errors, FEC_UNCORRECTED_ERRORS),
EF10_DMA_STAT(fec_corrected_errors, FEC_CORRECTED_ERRORS),
EF10_DMA_STAT(fec_corrected_symbols_lane0, FEC_CORRECTED_SYMBOLS_LANE0),
EF10_DMA_STAT(fec_corrected_symbols_lane1, FEC_CORRECTED_SYMBOLS_LANE1),
EF10_DMA_STAT(fec_corrected_symbols_lane2, FEC_CORRECTED_SYMBOLS_LANE2),
EF10_DMA_STAT(fec_corrected_symbols_lane3, FEC_CORRECTED_SYMBOLS_LANE3),
EF10_DMA_STAT(ctpio_vi_busy_fallback, CTPIO_VI_BUSY_FALLBACK),
EF10_DMA_STAT(ctpio_long_write_success, CTPIO_LONG_WRITE_SUCCESS),
EF10_DMA_STAT(ctpio_missing_dbell_fail, CTPIO_MISSING_DBELL_FAIL),
EF10_DMA_STAT(ctpio_overflow_fail, CTPIO_OVERFLOW_FAIL),
EF10_DMA_STAT(ctpio_underflow_fail, CTPIO_UNDERFLOW_FAIL),
EF10_DMA_STAT(ctpio_timeout_fail, CTPIO_TIMEOUT_FAIL),
EF10_DMA_STAT(ctpio_noncontig_wr_fail, CTPIO_NONCONTIG_WR_FAIL),
EF10_DMA_STAT(ctpio_frm_clobber_fail, CTPIO_FRM_CLOBBER_FAIL),
EF10_DMA_STAT(ctpio_invalid_wr_fail, CTPIO_INVALID_WR_FAIL),
EF10_DMA_STAT(ctpio_vi_clobber_fallback, CTPIO_VI_CLOBBER_FALLBACK),
EF10_DMA_STAT(ctpio_unqualified_fallback, CTPIO_UNQUALIFIED_FALLBACK),
EF10_DMA_STAT(ctpio_runt_fallback, CTPIO_RUNT_FALLBACK),
EF10_DMA_STAT(ctpio_success, CTPIO_SUCCESS),
EF10_DMA_STAT(ctpio_fallback, CTPIO_FALLBACK),
EF10_DMA_STAT(ctpio_poison, CTPIO_POISON),
EF10_DMA_STAT(ctpio_erase, CTPIO_ERASE),
};
#define HUNT_COMMON_STAT_MASK ((1ULL << EF10_STAT_port_tx_bytes) | \
(1ULL << EF10_STAT_port_tx_packets) | \
(1ULL << EF10_STAT_port_tx_pause) | \
(1ULL << EF10_STAT_port_tx_unicast) | \
(1ULL << EF10_STAT_port_tx_multicast) | \
(1ULL << EF10_STAT_port_tx_broadcast) | \
(1ULL << EF10_STAT_port_rx_bytes) | \
(1ULL << \
EF10_STAT_port_rx_bytes_minus_good_bytes) | \
(1ULL << EF10_STAT_port_rx_good_bytes) | \
(1ULL << EF10_STAT_port_rx_bad_bytes) | \
(1ULL << EF10_STAT_port_rx_packets) | \
(1ULL << EF10_STAT_port_rx_good) | \
(1ULL << EF10_STAT_port_rx_bad) | \
(1ULL << EF10_STAT_port_rx_pause) | \
(1ULL << EF10_STAT_port_rx_control) | \
(1ULL << EF10_STAT_port_rx_unicast) | \
(1ULL << EF10_STAT_port_rx_multicast) | \
(1ULL << EF10_STAT_port_rx_broadcast) | \
(1ULL << EF10_STAT_port_rx_lt64) | \
(1ULL << EF10_STAT_port_rx_64) | \
(1ULL << EF10_STAT_port_rx_65_to_127) | \
(1ULL << EF10_STAT_port_rx_128_to_255) | \
(1ULL << EF10_STAT_port_rx_256_to_511) | \
(1ULL << EF10_STAT_port_rx_512_to_1023) |\
(1ULL << EF10_STAT_port_rx_1024_to_15xx) |\
(1ULL << EF10_STAT_port_rx_15xx_to_jumbo) |\
(1ULL << EF10_STAT_port_rx_gtjumbo) | \
(1ULL << EF10_STAT_port_rx_bad_gtjumbo) |\
(1ULL << EF10_STAT_port_rx_overflow) | \
(1ULL << EF10_STAT_port_rx_nodesc_drops) |\
(1ULL << GENERIC_STAT_rx_nodesc_trunc) | \
(1ULL << GENERIC_STAT_rx_noskb_drops))
/* On 7000 series NICs, these statistics are only provided by the 10G MAC.
* For a 10G/40G switchable port we do not expose these because they might
* not include all the packets they should.
* On 8000 series NICs these statistics are always provided.
*/
#define HUNT_10G_ONLY_STAT_MASK ((1ULL << EF10_STAT_port_tx_control) | \
(1ULL << EF10_STAT_port_tx_lt64) | \
(1ULL << EF10_STAT_port_tx_64) | \
(1ULL << EF10_STAT_port_tx_65_to_127) |\
(1ULL << EF10_STAT_port_tx_128_to_255) |\
(1ULL << EF10_STAT_port_tx_256_to_511) |\
(1ULL << EF10_STAT_port_tx_512_to_1023) |\
(1ULL << EF10_STAT_port_tx_1024_to_15xx) |\
(1ULL << EF10_STAT_port_tx_15xx_to_jumbo))
/* These statistics are only provided by the 40G MAC. For a 10G/40G
* switchable port we do expose these because the errors will otherwise
* be silent.
*/
#define HUNT_40G_EXTRA_STAT_MASK ((1ULL << EF10_STAT_port_rx_align_error) |\
(1ULL << EF10_STAT_port_rx_length_error))
/* These statistics are only provided if the firmware supports the
* capability PM_AND_RXDP_COUNTERS.
*/
#define HUNT_PM_AND_RXDP_STAT_MASK ( \
(1ULL << EF10_STAT_port_rx_pm_trunc_bb_overflow) | \
(1ULL << EF10_STAT_port_rx_pm_discard_bb_overflow) | \
(1ULL << EF10_STAT_port_rx_pm_trunc_vfifo_full) | \
(1ULL << EF10_STAT_port_rx_pm_discard_vfifo_full) | \
(1ULL << EF10_STAT_port_rx_pm_trunc_qbb) | \
(1ULL << EF10_STAT_port_rx_pm_discard_qbb) | \
(1ULL << EF10_STAT_port_rx_pm_discard_mapping) | \
(1ULL << EF10_STAT_port_rx_dp_q_disabled_packets) | \
(1ULL << EF10_STAT_port_rx_dp_di_dropped_packets) | \
(1ULL << EF10_STAT_port_rx_dp_streaming_packets) | \
(1ULL << EF10_STAT_port_rx_dp_hlb_fetch) | \
(1ULL << EF10_STAT_port_rx_dp_hlb_wait))
/* These statistics are only provided if the NIC supports MC_CMD_MAC_STATS_V2,
* indicated by returning a value >= MC_CMD_MAC_NSTATS_V2 in
* MC_CMD_GET_CAPABILITIES_V4_OUT_MAC_STATS_NUM_STATS.
* These bits are in the second u64 of the raw mask.
*/
#define EF10_FEC_STAT_MASK ( \
(1ULL << (EF10_STAT_fec_uncorrected_errors - 64)) | \
(1ULL << (EF10_STAT_fec_corrected_errors - 64)) | \
(1ULL << (EF10_STAT_fec_corrected_symbols_lane0 - 64)) | \
(1ULL << (EF10_STAT_fec_corrected_symbols_lane1 - 64)) | \
(1ULL << (EF10_STAT_fec_corrected_symbols_lane2 - 64)) | \
(1ULL << (EF10_STAT_fec_corrected_symbols_lane3 - 64)))
/* These statistics are only provided if the NIC supports MC_CMD_MAC_STATS_V3,
* indicated by returning a value >= MC_CMD_MAC_NSTATS_V3 in
* MC_CMD_GET_CAPABILITIES_V4_OUT_MAC_STATS_NUM_STATS.
* These bits are in the second u64 of the raw mask.
*/
#define EF10_CTPIO_STAT_MASK ( \
(1ULL << (EF10_STAT_ctpio_vi_busy_fallback - 64)) | \
(1ULL << (EF10_STAT_ctpio_long_write_success - 64)) | \
(1ULL << (EF10_STAT_ctpio_missing_dbell_fail - 64)) | \
(1ULL << (EF10_STAT_ctpio_overflow_fail - 64)) | \
(1ULL << (EF10_STAT_ctpio_underflow_fail - 64)) | \
(1ULL << (EF10_STAT_ctpio_timeout_fail - 64)) | \
(1ULL << (EF10_STAT_ctpio_noncontig_wr_fail - 64)) | \
(1ULL << (EF10_STAT_ctpio_frm_clobber_fail - 64)) | \
(1ULL << (EF10_STAT_ctpio_invalid_wr_fail - 64)) | \
(1ULL << (EF10_STAT_ctpio_vi_clobber_fallback - 64)) | \
(1ULL << (EF10_STAT_ctpio_unqualified_fallback - 64)) | \
(1ULL << (EF10_STAT_ctpio_runt_fallback - 64)) | \
(1ULL << (EF10_STAT_ctpio_success - 64)) | \
(1ULL << (EF10_STAT_ctpio_fallback - 64)) | \
(1ULL << (EF10_STAT_ctpio_poison - 64)) | \
(1ULL << (EF10_STAT_ctpio_erase - 64)))
static u64 efx_ef10_raw_stat_mask(struct efx_nic *efx)
{
u64 raw_mask = HUNT_COMMON_STAT_MASK;
u32 port_caps = efx_mcdi_phy_get_caps(efx);
struct efx_ef10_nic_data *nic_data = efx->nic_data;
if (!(efx->mcdi->fn_flags &
1 << MC_CMD_DRV_ATTACH_EXT_OUT_FLAG_LINKCTRL))
return 0;
if (port_caps & (1 << MC_CMD_PHY_CAP_40000FDX_LBN)) {
raw_mask |= HUNT_40G_EXTRA_STAT_MASK;
/* 8000 series have everything even at 40G */
if (nic_data->datapath_caps2 &
(1 << MC_CMD_GET_CAPABILITIES_V2_OUT_MAC_STATS_40G_TX_SIZE_BINS_LBN))
raw_mask |= HUNT_10G_ONLY_STAT_MASK;
} else {
raw_mask |= HUNT_10G_ONLY_STAT_MASK;
}
if (nic_data->datapath_caps &
(1 << MC_CMD_GET_CAPABILITIES_OUT_PM_AND_RXDP_COUNTERS_LBN))
raw_mask |= HUNT_PM_AND_RXDP_STAT_MASK;
return raw_mask;
}
static void efx_ef10_get_stat_mask(struct efx_nic *efx, unsigned long *mask)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
u64 raw_mask[2];
raw_mask[0] = efx_ef10_raw_stat_mask(efx);
/* Only show vadaptor stats when EVB capability is present */
if (nic_data->datapath_caps &
(1 << MC_CMD_GET_CAPABILITIES_OUT_EVB_LBN)) {
raw_mask[0] |= ~((1ULL << EF10_STAT_rx_unicast) - 1);
raw_mask[1] = (1ULL << (EF10_STAT_V1_COUNT - 64)) - 1;
} else {
raw_mask[1] = 0;
}
/* Only show FEC stats when NIC supports MC_CMD_MAC_STATS_V2 */
if (efx->num_mac_stats >= MC_CMD_MAC_NSTATS_V2)
raw_mask[1] |= EF10_FEC_STAT_MASK;
/* CTPIO stats appear in V3. Only show them on devices that actually
* support CTPIO. Although this driver doesn't use CTPIO others might,
* and we may be reporting the stats for the underlying port.
*/
if (efx->num_mac_stats >= MC_CMD_MAC_NSTATS_V3 &&
(nic_data->datapath_caps2 &
(1 << MC_CMD_GET_CAPABILITIES_V4_OUT_CTPIO_LBN)))
raw_mask[1] |= EF10_CTPIO_STAT_MASK;
#if BITS_PER_LONG == 64
BUILD_BUG_ON(BITS_TO_LONGS(EF10_STAT_COUNT) != 2);
mask[0] = raw_mask[0];
mask[1] = raw_mask[1];
#else
BUILD_BUG_ON(BITS_TO_LONGS(EF10_STAT_COUNT) != 3);
mask[0] = raw_mask[0] & 0xffffffff;
mask[1] = raw_mask[0] >> 32;
mask[2] = raw_mask[1] & 0xffffffff;
#endif
}
static size_t efx_ef10_describe_stats(struct efx_nic *efx, u8 *names)
{
DECLARE_BITMAP(mask, EF10_STAT_COUNT);
efx_ef10_get_stat_mask(efx, mask);
return efx_nic_describe_stats(efx_ef10_stat_desc, EF10_STAT_COUNT,
mask, names);
}
static void efx_ef10_get_fec_stats(struct efx_nic *efx,
struct ethtool_fec_stats *fec_stats)
{
DECLARE_BITMAP(mask, EF10_STAT_COUNT);
struct efx_ef10_nic_data *nic_data = efx->nic_data;
u64 *stats = nic_data->stats;
efx_ef10_get_stat_mask(efx, mask);
if (test_bit(EF10_STAT_fec_corrected_errors, mask))
fec_stats->corrected_blocks.total =
stats[EF10_STAT_fec_corrected_errors];
if (test_bit(EF10_STAT_fec_uncorrected_errors, mask))
fec_stats->uncorrectable_blocks.total =
stats[EF10_STAT_fec_uncorrected_errors];
}
static size_t efx_ef10_update_stats_common(struct efx_nic *efx, u64 *full_stats,
struct rtnl_link_stats64 *core_stats)
{
DECLARE_BITMAP(mask, EF10_STAT_COUNT);
struct efx_ef10_nic_data *nic_data = efx->nic_data;
u64 *stats = nic_data->stats;
size_t stats_count = 0, index;
efx_ef10_get_stat_mask(efx, mask);
if (full_stats) {
for_each_set_bit(index, mask, EF10_STAT_COUNT) {
if (efx_ef10_stat_desc[index].name) {
*full_stats++ = stats[index];
++stats_count;
}
}
}
if (!core_stats)
return stats_count;
if (nic_data->datapath_caps &
1 << MC_CMD_GET_CAPABILITIES_OUT_EVB_LBN) {
/* Use vadaptor stats. */
core_stats->rx_packets = stats[EF10_STAT_rx_unicast] +
stats[EF10_STAT_rx_multicast] +
stats[EF10_STAT_rx_broadcast];
core_stats->tx_packets = stats[EF10_STAT_tx_unicast] +
stats[EF10_STAT_tx_multicast] +
stats[EF10_STAT_tx_broadcast];
core_stats->rx_bytes = stats[EF10_STAT_rx_unicast_bytes] +
stats[EF10_STAT_rx_multicast_bytes] +
stats[EF10_STAT_rx_broadcast_bytes];
core_stats->tx_bytes = stats[EF10_STAT_tx_unicast_bytes] +
stats[EF10_STAT_tx_multicast_bytes] +
stats[EF10_STAT_tx_broadcast_bytes];
core_stats->rx_dropped = stats[GENERIC_STAT_rx_nodesc_trunc] +
stats[GENERIC_STAT_rx_noskb_drops];
core_stats->multicast = stats[EF10_STAT_rx_multicast];
core_stats->rx_crc_errors = stats[EF10_STAT_rx_bad];
core_stats->rx_fifo_errors = stats[EF10_STAT_rx_overflow];
core_stats->rx_errors = core_stats->rx_crc_errors;
core_stats->tx_errors = stats[EF10_STAT_tx_bad];
} else {
/* Use port stats. */
core_stats->rx_packets = stats[EF10_STAT_port_rx_packets];
core_stats->tx_packets = stats[EF10_STAT_port_tx_packets];
core_stats->rx_bytes = stats[EF10_STAT_port_rx_bytes];
core_stats->tx_bytes = stats[EF10_STAT_port_tx_bytes];
core_stats->rx_dropped = stats[EF10_STAT_port_rx_nodesc_drops] +
stats[GENERIC_STAT_rx_nodesc_trunc] +
stats[GENERIC_STAT_rx_noskb_drops];
core_stats->multicast = stats[EF10_STAT_port_rx_multicast];
core_stats->rx_length_errors =
stats[EF10_STAT_port_rx_gtjumbo] +
stats[EF10_STAT_port_rx_length_error];
core_stats->rx_crc_errors = stats[EF10_STAT_port_rx_bad];
core_stats->rx_frame_errors =
stats[EF10_STAT_port_rx_align_error];
core_stats->rx_fifo_errors = stats[EF10_STAT_port_rx_overflow];
core_stats->rx_errors = (core_stats->rx_length_errors +
core_stats->rx_crc_errors +
core_stats->rx_frame_errors);
}
return stats_count;
}
static size_t efx_ef10_update_stats_pf(struct efx_nic *efx, u64 *full_stats,
struct rtnl_link_stats64 *core_stats)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
DECLARE_BITMAP(mask, EF10_STAT_COUNT);
u64 *stats = nic_data->stats;
efx_ef10_get_stat_mask(efx, mask);
/* If NIC was fini'd (probably resetting), then we can't read
* updated stats right now.
*/
if (nic_data->mc_stats) {
efx_nic_copy_stats(efx, nic_data->mc_stats);
efx_nic_update_stats(efx_ef10_stat_desc, EF10_STAT_COUNT,
mask, stats, nic_data->mc_stats, false);
}
/* Update derived statistics */
efx_nic_fix_nodesc_drop_stat(efx,
&stats[EF10_STAT_port_rx_nodesc_drops]);
/* MC Firmware reads RX_BYTES and RX_GOOD_BYTES from the MAC.
* It then calculates RX_BAD_BYTES and DMAs it to us with RX_BYTES.
* We report these as port_rx_ stats. We are not given RX_GOOD_BYTES.
* Here we calculate port_rx_good_bytes.
*/
stats[EF10_STAT_port_rx_good_bytes] =
stats[EF10_STAT_port_rx_bytes] -
stats[EF10_STAT_port_rx_bytes_minus_good_bytes];
/* The asynchronous reads used to calculate RX_BAD_BYTES in
* MC Firmware are done such that we should not see an increase in
* RX_BAD_BYTES when a good packet has arrived. Unfortunately this
* does mean that the stat can decrease at times. Here we do not
* update the stat unless it has increased or has gone to zero
* (In the case of the NIC rebooting).
* Please see Bug 33781 for a discussion of why things work this way.
*/
efx_update_diff_stat(&stats[EF10_STAT_port_rx_bad_bytes],
stats[EF10_STAT_port_rx_bytes_minus_good_bytes]);
efx_update_sw_stats(efx, stats);
return efx_ef10_update_stats_common(efx, full_stats, core_stats);
}
static int efx_ef10_try_update_nic_stats_vf(struct efx_nic *efx)
__must_hold(&efx->stats_lock)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAC_STATS_IN_LEN);
struct efx_ef10_nic_data *nic_data = efx->nic_data;
DECLARE_BITMAP(mask, EF10_STAT_COUNT);
__le64 generation_start, generation_end;
u64 *stats = nic_data->stats;
u32 dma_len = efx->num_mac_stats * sizeof(u64);
struct efx_buffer stats_buf;
__le64 *dma_stats;
int rc;
spin_unlock_bh(&efx->stats_lock);
efx_ef10_get_stat_mask(efx, mask);
rc = efx_nic_alloc_buffer(efx, &stats_buf, dma_len, GFP_KERNEL);
if (rc) {
spin_lock_bh(&efx->stats_lock);
return rc;
}
dma_stats = stats_buf.addr;
dma_stats[efx->num_mac_stats - 1] = EFX_MC_STATS_GENERATION_INVALID;
MCDI_SET_QWORD(inbuf, MAC_STATS_IN_DMA_ADDR, stats_buf.dma_addr);
MCDI_POPULATE_DWORD_1(inbuf, MAC_STATS_IN_CMD,
MAC_STATS_IN_DMA, 1);
MCDI_SET_DWORD(inbuf, MAC_STATS_IN_DMA_LEN, dma_len);
MCDI_SET_DWORD(inbuf, MAC_STATS_IN_PORT_ID, EVB_PORT_ID_ASSIGNED);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_MAC_STATS, inbuf, sizeof(inbuf),
NULL, 0, NULL);
spin_lock_bh(&efx->stats_lock);
if (rc) {
/* Expect ENOENT if DMA queues have not been set up */
if (rc != -ENOENT || atomic_read(&efx->active_queues))
efx_mcdi_display_error(efx, MC_CMD_MAC_STATS,
sizeof(inbuf), NULL, 0, rc);
goto out;
}
generation_end = dma_stats[efx->num_mac_stats - 1];
if (generation_end == EFX_MC_STATS_GENERATION_INVALID) {
WARN_ON_ONCE(1);
goto out;
}
rmb();
efx_nic_update_stats(efx_ef10_stat_desc, EF10_STAT_COUNT, mask,
stats, stats_buf.addr, false);
rmb();
generation_start = dma_stats[MC_CMD_MAC_GENERATION_START];
if (generation_end != generation_start) {
rc = -EAGAIN;
goto out;
}
efx_update_sw_stats(efx, stats);
out:
/* releasing a DMA coherent buffer with BH disabled can panic */
spin_unlock_bh(&efx->stats_lock);
efx_nic_free_buffer(efx, &stats_buf);
spin_lock_bh(&efx->stats_lock);
return rc;
}
static size_t efx_ef10_update_stats_vf(struct efx_nic *efx, u64 *full_stats,
struct rtnl_link_stats64 *core_stats)
{
if (efx_ef10_try_update_nic_stats_vf(efx))
return 0;
return efx_ef10_update_stats_common(efx, full_stats, core_stats);
}
static size_t efx_ef10_update_stats_atomic_vf(struct efx_nic *efx, u64 *full_stats,
struct rtnl_link_stats64 *core_stats)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
/* In atomic context, cannot update HW stats. Just update the
* software stats and return so the caller can continue.
*/
efx_update_sw_stats(efx, nic_data->stats);
return efx_ef10_update_stats_common(efx, full_stats, core_stats);
}
static void efx_ef10_push_irq_moderation(struct efx_channel *channel)
{
struct efx_nic *efx = channel->efx;
unsigned int mode, usecs;
efx_dword_t timer_cmd;
if (channel->irq_moderation_us) {
mode = 3;
usecs = channel->irq_moderation_us;
} else {
mode = 0;
usecs = 0;
}
if (EFX_EF10_WORKAROUND_61265(efx)) {
MCDI_DECLARE_BUF(inbuf, MC_CMD_SET_EVQ_TMR_IN_LEN);
unsigned int ns = usecs * 1000;
MCDI_SET_DWORD(inbuf, SET_EVQ_TMR_IN_INSTANCE,
channel->channel);
MCDI_SET_DWORD(inbuf, SET_EVQ_TMR_IN_TMR_LOAD_REQ_NS, ns);
MCDI_SET_DWORD(inbuf, SET_EVQ_TMR_IN_TMR_RELOAD_REQ_NS, ns);
MCDI_SET_DWORD(inbuf, SET_EVQ_TMR_IN_TMR_MODE, mode);
efx_mcdi_rpc_async(efx, MC_CMD_SET_EVQ_TMR,
inbuf, sizeof(inbuf), 0, NULL, 0);
} else if (EFX_EF10_WORKAROUND_35388(efx)) {
unsigned int ticks = efx_usecs_to_ticks(efx, usecs);
EFX_POPULATE_DWORD_3(timer_cmd, ERF_DD_EVQ_IND_TIMER_FLAGS,
EFE_DD_EVQ_IND_TIMER_FLAGS,
ERF_DD_EVQ_IND_TIMER_MODE, mode,
ERF_DD_EVQ_IND_TIMER_VAL, ticks);
efx_writed_page(efx, &timer_cmd, ER_DD_EVQ_INDIRECT,
channel->channel);
} else {
unsigned int ticks = efx_usecs_to_ticks(efx, usecs);
EFX_POPULATE_DWORD_3(timer_cmd, ERF_DZ_TC_TIMER_MODE, mode,
ERF_DZ_TC_TIMER_VAL, ticks,
ERF_FZ_TC_TMR_REL_VAL, ticks);
efx_writed_page(efx, &timer_cmd, ER_DZ_EVQ_TMR,
channel->channel);
}
}
static void efx_ef10_get_wol_vf(struct efx_nic *efx,
struct ethtool_wolinfo *wol) {}
static int efx_ef10_set_wol_vf(struct efx_nic *efx, u32 type)
{
return -EOPNOTSUPP;
}
static void efx_ef10_get_wol(struct efx_nic *efx, struct ethtool_wolinfo *wol)
{
wol->supported = 0;
wol->wolopts = 0;
memset(&wol->sopass, 0, sizeof(wol->sopass));
}
static int efx_ef10_set_wol(struct efx_nic *efx, u32 type)
{
if (type != 0)
return -EINVAL;
return 0;
}
static void efx_ef10_mcdi_request(struct efx_nic *efx,
const efx_dword_t *hdr, size_t hdr_len,
const efx_dword_t *sdu, size_t sdu_len)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
u8 *pdu = nic_data->mcdi_buf.addr;
memcpy(pdu, hdr, hdr_len);
memcpy(pdu + hdr_len, sdu, sdu_len);
wmb();
/* The hardware provides 'low' and 'high' (doorbell) registers
* for passing the 64-bit address of an MCDI request to
* firmware. However the dwords are swapped by firmware. The
* least significant bits of the doorbell are then 0 for all
* MCDI requests due to alignment.
*/
_efx_writed(efx, cpu_to_le32((u64)nic_data->mcdi_buf.dma_addr >> 32),
ER_DZ_MC_DB_LWRD);
_efx_writed(efx, cpu_to_le32((u32)nic_data->mcdi_buf.dma_addr),
ER_DZ_MC_DB_HWRD);
}
static bool efx_ef10_mcdi_poll_response(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
const efx_dword_t hdr = *(const efx_dword_t *)nic_data->mcdi_buf.addr;
rmb();
return EFX_DWORD_FIELD(hdr, MCDI_HEADER_RESPONSE);
}
static void
efx_ef10_mcdi_read_response(struct efx_nic *efx, efx_dword_t *outbuf,
size_t offset, size_t outlen)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
const u8 *pdu = nic_data->mcdi_buf.addr;
memcpy(outbuf, pdu + offset, outlen);
}
static void efx_ef10_mcdi_reboot_detected(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
/* All our allocations have been reset */
efx_ef10_table_reset_mc_allocations(efx);
/* The datapath firmware might have been changed */
nic_data->must_check_datapath_caps = true;
/* MAC statistics have been cleared on the NIC; clear the local
* statistic that we update with efx_update_diff_stat().
*/
nic_data->stats[EF10_STAT_port_rx_bad_bytes] = 0;
}
static int efx_ef10_mcdi_poll_reboot(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
int rc;
rc = efx_ef10_get_warm_boot_count(efx);
if (rc < 0) {
/* The firmware is presumably in the process of
* rebooting. However, we are supposed to report each
* reboot just once, so we must only do that once we
* can read and store the updated warm boot count.
*/
return 0;
}
if (rc == nic_data->warm_boot_count)
return 0;
nic_data->warm_boot_count = rc;
efx_ef10_mcdi_reboot_detected(efx);
return -EIO;
}
/* Handle an MSI interrupt
*
* Handle an MSI hardware interrupt. This routine schedules event
* queue processing. No interrupt acknowledgement cycle is necessary.
* Also, we never need to check that the interrupt is for us, since
* MSI interrupts cannot be shared.
*/
static irqreturn_t efx_ef10_msi_interrupt(int irq, void *dev_id)
{
struct efx_msi_context *context = dev_id;
struct efx_nic *efx = context->efx;
netif_vdbg(efx, intr, efx->net_dev,
"IRQ %d on CPU %d\n", irq, raw_smp_processor_id());
if (likely(READ_ONCE(efx->irq_soft_enabled))) {
/* Note test interrupts */
if (context->index == efx->irq_level)
efx->last_irq_cpu = raw_smp_processor_id();
/* Schedule processing of the channel */
efx_schedule_channel_irq(efx->channel[context->index]);
}
return IRQ_HANDLED;
}
static irqreturn_t efx_ef10_legacy_interrupt(int irq, void *dev_id)
{
struct efx_nic *efx = dev_id;
bool soft_enabled = READ_ONCE(efx->irq_soft_enabled);
struct efx_channel *channel;
efx_dword_t reg;
u32 queues;
/* Read the ISR which also ACKs the interrupts */
efx_readd(efx, ®, ER_DZ_BIU_INT_ISR);
queues = EFX_DWORD_FIELD(reg, ERF_DZ_ISR_REG);
if (queues == 0)
return IRQ_NONE;
if (likely(soft_enabled)) {
/* Note test interrupts */
if (queues & (1U << efx->irq_level))
efx->last_irq_cpu = raw_smp_processor_id();
efx_for_each_channel(channel, efx) {
if (queues & 1)
efx_schedule_channel_irq(channel);
queues >>= 1;
}
}
netif_vdbg(efx, intr, efx->net_dev,
"IRQ %d on CPU %d status " EFX_DWORD_FMT "\n",
irq, raw_smp_processor_id(), EFX_DWORD_VAL(reg));
return IRQ_HANDLED;
}
static int efx_ef10_irq_test_generate(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_TRIGGER_INTERRUPT_IN_LEN);
if (efx_mcdi_set_workaround(efx, MC_CMD_WORKAROUND_BUG41750, true,
NULL) == 0)
return -ENOTSUPP;
BUILD_BUG_ON(MC_CMD_TRIGGER_INTERRUPT_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, TRIGGER_INTERRUPT_IN_INTR_LEVEL, efx->irq_level);
return efx_mcdi_rpc(efx, MC_CMD_TRIGGER_INTERRUPT,
inbuf, sizeof(inbuf), NULL, 0, NULL);
}
static int efx_ef10_tx_probe(struct efx_tx_queue *tx_queue)
{
/* low two bits of label are what we want for type */
BUILD_BUG_ON((EFX_TXQ_TYPE_OUTER_CSUM | EFX_TXQ_TYPE_INNER_CSUM) != 3);
tx_queue->type = tx_queue->label & 3;
return efx_nic_alloc_buffer(tx_queue->efx, &tx_queue->txd,
(tx_queue->ptr_mask + 1) *
sizeof(efx_qword_t),
GFP_KERNEL);
}
/* This writes to the TX_DESC_WPTR and also pushes data */
static inline void efx_ef10_push_tx_desc(struct efx_tx_queue *tx_queue,
const efx_qword_t *txd)
{
unsigned int write_ptr;
efx_oword_t reg;
write_ptr = tx_queue->write_count & tx_queue->ptr_mask;
EFX_POPULATE_OWORD_1(reg, ERF_DZ_TX_DESC_WPTR, write_ptr);
reg.qword[0] = *txd;
efx_writeo_page(tx_queue->efx, ®,
ER_DZ_TX_DESC_UPD, tx_queue->queue);
}
/* Add Firmware-Assisted TSO v2 option descriptors to a queue.
*/
int efx_ef10_tx_tso_desc(struct efx_tx_queue *tx_queue, struct sk_buff *skb,
bool *data_mapped)
{
struct efx_tx_buffer *buffer;
u16 inner_ipv4_id = 0;
u16 outer_ipv4_id = 0;
struct tcphdr *tcp;
struct iphdr *ip;
u16 ip_tot_len;
u32 seqnum;
u32 mss;
EFX_WARN_ON_ONCE_PARANOID(tx_queue->tso_version != 2);
mss = skb_shinfo(skb)->gso_size;
if (unlikely(mss < 4)) {
WARN_ONCE(1, "MSS of %u is too small for TSO v2\n", mss);
return -EINVAL;
}
if (skb->encapsulation) {
if (!tx_queue->tso_encap)
return -EINVAL;
ip = ip_hdr(skb);
if (ip->version == 4)
outer_ipv4_id = ntohs(ip->id);
ip = inner_ip_hdr(skb);
tcp = inner_tcp_hdr(skb);
} else {
ip = ip_hdr(skb);
tcp = tcp_hdr(skb);
}
/* 8000-series EF10 hardware requires that IP Total Length be
* greater than or equal to the value it will have in each segment
* (which is at most mss + 208 + TCP header length), but also less
* than (0x10000 - inner_network_header). Otherwise the TCP
* checksum calculation will be broken for encapsulated packets.
* We fill in ip->tot_len with 0xff30, which should satisfy the
* first requirement unless the MSS is ridiculously large (which
* should be impossible as the driver max MTU is 9216); it is
* guaranteed to satisfy the second as we only attempt TSO if
* inner_network_header <= 208.
*/
ip_tot_len = 0x10000 - EFX_TSO2_MAX_HDRLEN;
EFX_WARN_ON_ONCE_PARANOID(mss + EFX_TSO2_MAX_HDRLEN +
(tcp->doff << 2u) > ip_tot_len);
if (ip->version == 4) {
ip->tot_len = htons(ip_tot_len);
ip->check = 0;
inner_ipv4_id = ntohs(ip->id);
} else {
((struct ipv6hdr *)ip)->payload_len = htons(ip_tot_len);
}
seqnum = ntohl(tcp->seq);
buffer = efx_tx_queue_get_insert_buffer(tx_queue);
buffer->flags = EFX_TX_BUF_OPTION;
buffer->len = 0;
buffer->unmap_len = 0;
EFX_POPULATE_QWORD_5(buffer->option,
ESF_DZ_TX_DESC_IS_OPT, 1,
ESF_DZ_TX_OPTION_TYPE, ESE_DZ_TX_OPTION_DESC_TSO,
ESF_DZ_TX_TSO_OPTION_TYPE,
ESE_DZ_TX_TSO_OPTION_DESC_FATSO2A,
ESF_DZ_TX_TSO_IP_ID, inner_ipv4_id,
ESF_DZ_TX_TSO_TCP_SEQNO, seqnum
);
++tx_queue->insert_count;
buffer = efx_tx_queue_get_insert_buffer(tx_queue);
buffer->flags = EFX_TX_BUF_OPTION;
buffer->len = 0;
buffer->unmap_len = 0;
EFX_POPULATE_QWORD_5(buffer->option,
ESF_DZ_TX_DESC_IS_OPT, 1,
ESF_DZ_TX_OPTION_TYPE, ESE_DZ_TX_OPTION_DESC_TSO,
ESF_DZ_TX_TSO_OPTION_TYPE,
ESE_DZ_TX_TSO_OPTION_DESC_FATSO2B,
ESF_DZ_TX_TSO_OUTER_IPID, outer_ipv4_id,
ESF_DZ_TX_TSO_TCP_MSS, mss
);
++tx_queue->insert_count;
return 0;
}
static u32 efx_ef10_tso_versions(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
u32 tso_versions = 0;
if (nic_data->datapath_caps &
(1 << MC_CMD_GET_CAPABILITIES_OUT_TX_TSO_LBN))
tso_versions |= BIT(1);
if (nic_data->datapath_caps2 &
(1 << MC_CMD_GET_CAPABILITIES_V2_OUT_TX_TSO_V2_LBN))
tso_versions |= BIT(2);
return tso_versions;
}
static void efx_ef10_tx_init(struct efx_tx_queue *tx_queue)
{
bool csum_offload = tx_queue->type & EFX_TXQ_TYPE_OUTER_CSUM;
bool inner_csum = tx_queue->type & EFX_TXQ_TYPE_INNER_CSUM;
struct efx_channel *channel = tx_queue->channel;
struct efx_nic *efx = tx_queue->efx;
struct efx_ef10_nic_data *nic_data;
efx_qword_t *txd;
int rc;
nic_data = efx->nic_data;
/* Only attempt to enable TX timestamping if we have the license for it,
* otherwise TXQ init will fail
*/
if (!(nic_data->licensed_features &
(1 << LICENSED_V3_FEATURES_TX_TIMESTAMPS_LBN))) {
tx_queue->timestamping = false;
/* Disable sync events on this channel. */
if (efx->type->ptp_set_ts_sync_events)
efx->type->ptp_set_ts_sync_events(efx, false, false);
}
/* TSOv2 is a limited resource that can only be configured on a limited
* number of queues. TSO without checksum offload is not really a thing,
* so we only enable it for those queues.
* TSOv2 cannot be used with Hardware timestamping, and is never needed
* for XDP tx.
*/
if (efx_has_cap(efx, TX_TSO_V2)) {
if ((csum_offload || inner_csum) &&
!tx_queue->timestamping && !tx_queue->xdp_tx) {
tx_queue->tso_version = 2;
netif_dbg(efx, hw, efx->net_dev, "Using TSOv2 for channel %u\n",
channel->channel);
}
} else if (efx_has_cap(efx, TX_TSO)) {
tx_queue->tso_version = 1;
}
rc = efx_mcdi_tx_init(tx_queue);
if (rc)
goto fail;
/* A previous user of this TX queue might have set us up the
* bomb by writing a descriptor to the TX push collector but
* not the doorbell. (Each collector belongs to a port, not a
* queue or function, so cannot easily be reset.) We must
* attempt to push a no-op descriptor in its place.
*/
tx_queue->buffer[0].flags = EFX_TX_BUF_OPTION;
tx_queue->insert_count = 1;
txd = efx_tx_desc(tx_queue, 0);
EFX_POPULATE_QWORD_7(*txd,
ESF_DZ_TX_DESC_IS_OPT, true,
ESF_DZ_TX_OPTION_TYPE,
ESE_DZ_TX_OPTION_DESC_CRC_CSUM,
ESF_DZ_TX_OPTION_UDP_TCP_CSUM, csum_offload,
ESF_DZ_TX_OPTION_IP_CSUM, csum_offload && tx_queue->tso_version != 2,
ESF_DZ_TX_OPTION_INNER_UDP_TCP_CSUM, inner_csum,
ESF_DZ_TX_OPTION_INNER_IP_CSUM, inner_csum && tx_queue->tso_version != 2,
ESF_DZ_TX_TIMESTAMP, tx_queue->timestamping);
tx_queue->write_count = 1;
if (tx_queue->tso_version == 2 && efx_has_cap(efx, TX_TSO_V2_ENCAP))
tx_queue->tso_encap = true;
wmb();
efx_ef10_push_tx_desc(tx_queue, txd);
return;
fail:
netdev_WARN(efx->net_dev, "failed to initialise TXQ %d\n",
tx_queue->queue);
}
/* This writes to the TX_DESC_WPTR; write pointer for TX descriptor ring */
static inline void efx_ef10_notify_tx_desc(struct efx_tx_queue *tx_queue)
{
unsigned int write_ptr;
efx_dword_t reg;
write_ptr = tx_queue->write_count & tx_queue->ptr_mask;
EFX_POPULATE_DWORD_1(reg, ERF_DZ_TX_DESC_WPTR_DWORD, write_ptr);
efx_writed_page(tx_queue->efx, ®,
ER_DZ_TX_DESC_UPD_DWORD, tx_queue->queue);
}
#define EFX_EF10_MAX_TX_DESCRIPTOR_LEN 0x3fff
static unsigned int efx_ef10_tx_limit_len(struct efx_tx_queue *tx_queue,
dma_addr_t dma_addr, unsigned int len)
{
if (len > EFX_EF10_MAX_TX_DESCRIPTOR_LEN) {
/* If we need to break across multiple descriptors we should
* stop at a page boundary. This assumes the length limit is
* greater than the page size.
*/
dma_addr_t end = dma_addr + EFX_EF10_MAX_TX_DESCRIPTOR_LEN;
BUILD_BUG_ON(EFX_EF10_MAX_TX_DESCRIPTOR_LEN < EFX_PAGE_SIZE);
len = (end & (~(EFX_PAGE_SIZE - 1))) - dma_addr;
}
return len;
}
static void efx_ef10_tx_write(struct efx_tx_queue *tx_queue)
{
unsigned int old_write_count = tx_queue->write_count;
struct efx_tx_buffer *buffer;
unsigned int write_ptr;
efx_qword_t *txd;
tx_queue->xmit_pending = false;
if (unlikely(tx_queue->write_count == tx_queue->insert_count))
return;
do {
write_ptr = tx_queue->write_count & tx_queue->ptr_mask;
buffer = &tx_queue->buffer[write_ptr];
txd = efx_tx_desc(tx_queue, write_ptr);
++tx_queue->write_count;
/* Create TX descriptor ring entry */
if (buffer->flags & EFX_TX_BUF_OPTION) {
*txd = buffer->option;
if (EFX_QWORD_FIELD(*txd, ESF_DZ_TX_OPTION_TYPE) == 1)
/* PIO descriptor */
tx_queue->packet_write_count = tx_queue->write_count;
} else {
tx_queue->packet_write_count = tx_queue->write_count;
BUILD_BUG_ON(EFX_TX_BUF_CONT != 1);
EFX_POPULATE_QWORD_3(
*txd,
ESF_DZ_TX_KER_CONT,
buffer->flags & EFX_TX_BUF_CONT,
ESF_DZ_TX_KER_BYTE_CNT, buffer->len,
ESF_DZ_TX_KER_BUF_ADDR, buffer->dma_addr);
}
} while (tx_queue->write_count != tx_queue->insert_count);
wmb(); /* Ensure descriptors are written before they are fetched */
if (efx_nic_may_push_tx_desc(tx_queue, old_write_count)) {
txd = efx_tx_desc(tx_queue,
old_write_count & tx_queue->ptr_mask);
efx_ef10_push_tx_desc(tx_queue, txd);
++tx_queue->pushes;
} else {
efx_ef10_notify_tx_desc(tx_queue);
}
}
static int efx_ef10_probe_multicast_chaining(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
unsigned int enabled, implemented;
bool want_workaround_26807;
int rc;
rc = efx_mcdi_get_workarounds(efx, &implemented, &enabled);
if (rc == -ENOSYS) {
/* GET_WORKAROUNDS was implemented before this workaround,
* thus it must be unavailable in this firmware.
*/
nic_data->workaround_26807 = false;
return 0;
}
if (rc)
return rc;
want_workaround_26807 =
implemented & MC_CMD_GET_WORKAROUNDS_OUT_BUG26807;
nic_data->workaround_26807 =
!!(enabled & MC_CMD_GET_WORKAROUNDS_OUT_BUG26807);
if (want_workaround_26807 && !nic_data->workaround_26807) {
unsigned int flags;
rc = efx_mcdi_set_workaround(efx,
MC_CMD_WORKAROUND_BUG26807,
true, &flags);
if (!rc) {
if (flags &
1 << MC_CMD_WORKAROUND_EXT_OUT_FLR_DONE_LBN) {
netif_info(efx, drv, efx->net_dev,
"other functions on NIC have been reset\n");
/* With MCFW v4.6.x and earlier, the
* boot count will have incremented,
* so re-read the warm_boot_count
* value now to ensure this function
* doesn't think it has changed next
* time it checks.
*/
rc = efx_ef10_get_warm_boot_count(efx);
if (rc >= 0) {
nic_data->warm_boot_count = rc;
rc = 0;
}
}
nic_data->workaround_26807 = true;
} else if (rc == -EPERM) {
rc = 0;
}
}
return rc;
}
static int efx_ef10_filter_table_probe(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
int rc = efx_ef10_probe_multicast_chaining(efx);
struct efx_mcdi_filter_vlan *vlan;
if (rc)
return rc;
down_write(&efx->filter_sem);
rc = efx_mcdi_filter_table_probe(efx, nic_data->workaround_26807);
if (rc)
goto out_unlock;
list_for_each_entry(vlan, &nic_data->vlan_list, list) {
rc = efx_mcdi_filter_add_vlan(efx, vlan->vid);
if (rc)
goto fail_add_vlan;
}
goto out_unlock;
fail_add_vlan:
efx_mcdi_filter_table_remove(efx);
out_unlock:
up_write(&efx->filter_sem);
return rc;
}
static void efx_ef10_filter_table_remove(struct efx_nic *efx)
{
down_write(&efx->filter_sem);
efx_mcdi_filter_table_remove(efx);
up_write(&efx->filter_sem);
}
/* This creates an entry in the RX descriptor queue */
static inline void
efx_ef10_build_rx_desc(struct efx_rx_queue *rx_queue, unsigned int index)
{
struct efx_rx_buffer *rx_buf;
efx_qword_t *rxd;
rxd = efx_rx_desc(rx_queue, index);
rx_buf = efx_rx_buffer(rx_queue, index);
EFX_POPULATE_QWORD_2(*rxd,
ESF_DZ_RX_KER_BYTE_CNT, rx_buf->len,
ESF_DZ_RX_KER_BUF_ADDR, rx_buf->dma_addr);
}
static void efx_ef10_rx_write(struct efx_rx_queue *rx_queue)
{
struct efx_nic *efx = rx_queue->efx;
unsigned int write_count;
efx_dword_t reg;
/* Firmware requires that RX_DESC_WPTR be a multiple of 8 */
write_count = rx_queue->added_count & ~7;
if (rx_queue->notified_count == write_count)
return;
do
efx_ef10_build_rx_desc(
rx_queue,
rx_queue->notified_count & rx_queue->ptr_mask);
while (++rx_queue->notified_count != write_count);
wmb();
EFX_POPULATE_DWORD_1(reg, ERF_DZ_RX_DESC_WPTR,
write_count & rx_queue->ptr_mask);
efx_writed_page(efx, ®, ER_DZ_RX_DESC_UPD,
efx_rx_queue_index(rx_queue));
}
static efx_mcdi_async_completer efx_ef10_rx_defer_refill_complete;
static void efx_ef10_rx_defer_refill(struct efx_rx_queue *rx_queue)
{
struct efx_channel *channel = efx_rx_queue_channel(rx_queue);
MCDI_DECLARE_BUF(inbuf, MC_CMD_DRIVER_EVENT_IN_LEN);
efx_qword_t event;
EFX_POPULATE_QWORD_2(event,
ESF_DZ_EV_CODE, EFX_EF10_DRVGEN_EV,
ESF_DZ_EV_DATA, EFX_EF10_REFILL);
MCDI_SET_DWORD(inbuf, DRIVER_EVENT_IN_EVQ, channel->channel);
/* MCDI_SET_QWORD is not appropriate here since EFX_POPULATE_* has
* already swapped the data to little-endian order.
*/
memcpy(MCDI_PTR(inbuf, DRIVER_EVENT_IN_DATA), &event.u64[0],
sizeof(efx_qword_t));
efx_mcdi_rpc_async(channel->efx, MC_CMD_DRIVER_EVENT,
inbuf, sizeof(inbuf), 0,
efx_ef10_rx_defer_refill_complete, 0);
}
static void
efx_ef10_rx_defer_refill_complete(struct efx_nic *efx, unsigned long cookie,
int rc, efx_dword_t *outbuf,
size_t outlen_actual)
{
/* nothing to do */
}
static int efx_ef10_ev_init(struct efx_channel *channel)
{
struct efx_nic *efx = channel->efx;
struct efx_ef10_nic_data *nic_data;
bool use_v2, cut_thru;
nic_data = efx->nic_data;
use_v2 = nic_data->datapath_caps2 &
1 << MC_CMD_GET_CAPABILITIES_V2_OUT_INIT_EVQ_V2_LBN;
cut_thru = !(nic_data->datapath_caps &
1 << MC_CMD_GET_CAPABILITIES_OUT_RX_BATCHING_LBN);
return efx_mcdi_ev_init(channel, cut_thru, use_v2);
}
static void efx_ef10_handle_rx_wrong_queue(struct efx_rx_queue *rx_queue,
unsigned int rx_queue_label)
{
struct efx_nic *efx = rx_queue->efx;
netif_info(efx, hw, efx->net_dev,
"rx event arrived on queue %d labeled as queue %u\n",
efx_rx_queue_index(rx_queue), rx_queue_label);
efx_schedule_reset(efx, RESET_TYPE_DISABLE);
}
static void
efx_ef10_handle_rx_bad_lbits(struct efx_rx_queue *rx_queue,
unsigned int actual, unsigned int expected)
{
unsigned int dropped = (actual - expected) & rx_queue->ptr_mask;
struct efx_nic *efx = rx_queue->efx;
netif_info(efx, hw, efx->net_dev,
"dropped %d events (index=%d expected=%d)\n",
dropped, actual, expected);
efx_schedule_reset(efx, RESET_TYPE_DISABLE);
}
/* partially received RX was aborted. clean up. */
static void efx_ef10_handle_rx_abort(struct efx_rx_queue *rx_queue)
{
unsigned int rx_desc_ptr;
netif_dbg(rx_queue->efx, hw, rx_queue->efx->net_dev,
"scattered RX aborted (dropping %u buffers)\n",
rx_queue->scatter_n);
rx_desc_ptr = rx_queue->removed_count & rx_queue->ptr_mask;
efx_rx_packet(rx_queue, rx_desc_ptr, rx_queue->scatter_n,
0, EFX_RX_PKT_DISCARD);
rx_queue->removed_count += rx_queue->scatter_n;
rx_queue->scatter_n = 0;
rx_queue->scatter_len = 0;
++efx_rx_queue_channel(rx_queue)->n_rx_nodesc_trunc;
}
static u16 efx_ef10_handle_rx_event_errors(struct efx_channel *channel,
unsigned int n_packets,
unsigned int rx_encap_hdr,
unsigned int rx_l3_class,
unsigned int rx_l4_class,
const efx_qword_t *event)
{
struct efx_nic *efx = channel->efx;
bool handled = false;
if (EFX_QWORD_FIELD(*event, ESF_DZ_RX_ECRC_ERR)) {
if (!(efx->net_dev->features & NETIF_F_RXALL)) {
if (!efx->loopback_selftest)
channel->n_rx_eth_crc_err += n_packets;
return EFX_RX_PKT_DISCARD;
}
handled = true;
}
if (EFX_QWORD_FIELD(*event, ESF_DZ_RX_IPCKSUM_ERR)) {
if (unlikely(rx_encap_hdr != ESE_EZ_ENCAP_HDR_VXLAN &&
rx_l3_class != ESE_DZ_L3_CLASS_IP4 &&
rx_l3_class != ESE_DZ_L3_CLASS_IP4_FRAG &&
rx_l3_class != ESE_DZ_L3_CLASS_IP6 &&
rx_l3_class != ESE_DZ_L3_CLASS_IP6_FRAG))
netdev_WARN(efx->net_dev,
"invalid class for RX_IPCKSUM_ERR: event="
EFX_QWORD_FMT "\n",
EFX_QWORD_VAL(*event));
if (!efx->loopback_selftest)
*(rx_encap_hdr ?
&channel->n_rx_outer_ip_hdr_chksum_err :
&channel->n_rx_ip_hdr_chksum_err) += n_packets;
return 0;
}
if (EFX_QWORD_FIELD(*event, ESF_DZ_RX_TCPUDP_CKSUM_ERR)) {
if (unlikely(rx_encap_hdr != ESE_EZ_ENCAP_HDR_VXLAN &&
((rx_l3_class != ESE_DZ_L3_CLASS_IP4 &&
rx_l3_class != ESE_DZ_L3_CLASS_IP6) ||
(rx_l4_class != ESE_FZ_L4_CLASS_TCP &&
rx_l4_class != ESE_FZ_L4_CLASS_UDP))))
netdev_WARN(efx->net_dev,
"invalid class for RX_TCPUDP_CKSUM_ERR: event="
EFX_QWORD_FMT "\n",
EFX_QWORD_VAL(*event));
if (!efx->loopback_selftest)
*(rx_encap_hdr ?
&channel->n_rx_outer_tcp_udp_chksum_err :
&channel->n_rx_tcp_udp_chksum_err) += n_packets;
return 0;
}
if (EFX_QWORD_FIELD(*event, ESF_EZ_RX_IP_INNER_CHKSUM_ERR)) {
if (unlikely(!rx_encap_hdr))
netdev_WARN(efx->net_dev,
"invalid encapsulation type for RX_IP_INNER_CHKSUM_ERR: event="
EFX_QWORD_FMT "\n",
EFX_QWORD_VAL(*event));
else if (unlikely(rx_l3_class != ESE_DZ_L3_CLASS_IP4 &&
rx_l3_class != ESE_DZ_L3_CLASS_IP4_FRAG &&
rx_l3_class != ESE_DZ_L3_CLASS_IP6 &&
rx_l3_class != ESE_DZ_L3_CLASS_IP6_FRAG))
netdev_WARN(efx->net_dev,
"invalid class for RX_IP_INNER_CHKSUM_ERR: event="
EFX_QWORD_FMT "\n",
EFX_QWORD_VAL(*event));
if (!efx->loopback_selftest)
channel->n_rx_inner_ip_hdr_chksum_err += n_packets;
return 0;
}
if (EFX_QWORD_FIELD(*event, ESF_EZ_RX_TCP_UDP_INNER_CHKSUM_ERR)) {
if (unlikely(!rx_encap_hdr))
netdev_WARN(efx->net_dev,
"invalid encapsulation type for RX_TCP_UDP_INNER_CHKSUM_ERR: event="
EFX_QWORD_FMT "\n",
EFX_QWORD_VAL(*event));
else if (unlikely((rx_l3_class != ESE_DZ_L3_CLASS_IP4 &&
rx_l3_class != ESE_DZ_L3_CLASS_IP6) ||
(rx_l4_class != ESE_FZ_L4_CLASS_TCP &&
rx_l4_class != ESE_FZ_L4_CLASS_UDP)))
netdev_WARN(efx->net_dev,
"invalid class for RX_TCP_UDP_INNER_CHKSUM_ERR: event="
EFX_QWORD_FMT "\n",
EFX_QWORD_VAL(*event));
if (!efx->loopback_selftest)
channel->n_rx_inner_tcp_udp_chksum_err += n_packets;
return 0;
}
WARN_ON(!handled); /* No error bits were recognised */
return 0;
}
static int efx_ef10_handle_rx_event(struct efx_channel *channel,
const efx_qword_t *event)
{
unsigned int rx_bytes, next_ptr_lbits, rx_queue_label;
unsigned int rx_l3_class, rx_l4_class, rx_encap_hdr;
unsigned int n_descs, n_packets, i;
struct efx_nic *efx = channel->efx;
struct efx_ef10_nic_data *nic_data = efx->nic_data;
struct efx_rx_queue *rx_queue;
efx_qword_t errors;
bool rx_cont;
u16 flags = 0;
if (unlikely(READ_ONCE(efx->reset_pending)))
return 0;
/* Basic packet information */
rx_bytes = EFX_QWORD_FIELD(*event, ESF_DZ_RX_BYTES);
next_ptr_lbits = EFX_QWORD_FIELD(*event, ESF_DZ_RX_DSC_PTR_LBITS);
rx_queue_label = EFX_QWORD_FIELD(*event, ESF_DZ_RX_QLABEL);
rx_l3_class = EFX_QWORD_FIELD(*event, ESF_DZ_RX_L3_CLASS);
rx_l4_class = EFX_QWORD_FIELD(*event, ESF_FZ_RX_L4_CLASS);
rx_cont = EFX_QWORD_FIELD(*event, ESF_DZ_RX_CONT);
rx_encap_hdr =
nic_data->datapath_caps &
(1 << MC_CMD_GET_CAPABILITIES_OUT_VXLAN_NVGRE_LBN) ?
EFX_QWORD_FIELD(*event, ESF_EZ_RX_ENCAP_HDR) :
ESE_EZ_ENCAP_HDR_NONE;
if (EFX_QWORD_FIELD(*event, ESF_DZ_RX_DROP_EVENT))
netdev_WARN(efx->net_dev, "saw RX_DROP_EVENT: event="
EFX_QWORD_FMT "\n",
EFX_QWORD_VAL(*event));
rx_queue = efx_channel_get_rx_queue(channel);
if (unlikely(rx_queue_label != efx_rx_queue_index(rx_queue)))
efx_ef10_handle_rx_wrong_queue(rx_queue, rx_queue_label);
n_descs = ((next_ptr_lbits - rx_queue->removed_count) &
((1 << ESF_DZ_RX_DSC_PTR_LBITS_WIDTH) - 1));
if (n_descs != rx_queue->scatter_n + 1) {
struct efx_ef10_nic_data *nic_data = efx->nic_data;
/* detect rx abort */
if (unlikely(n_descs == rx_queue->scatter_n)) {
if (rx_queue->scatter_n == 0 || rx_bytes != 0)
netdev_WARN(efx->net_dev,
"invalid RX abort: scatter_n=%u event="
EFX_QWORD_FMT "\n",
rx_queue->scatter_n,
EFX_QWORD_VAL(*event));
efx_ef10_handle_rx_abort(rx_queue);
return 0;
}
/* Check that RX completion merging is valid, i.e.
* the current firmware supports it and this is a
* non-scattered packet.
*/
if (!(nic_data->datapath_caps &
(1 << MC_CMD_GET_CAPABILITIES_OUT_RX_BATCHING_LBN)) ||
rx_queue->scatter_n != 0 || rx_cont) {
efx_ef10_handle_rx_bad_lbits(
rx_queue, next_ptr_lbits,
(rx_queue->removed_count +
rx_queue->scatter_n + 1) &
((1 << ESF_DZ_RX_DSC_PTR_LBITS_WIDTH) - 1));
return 0;
}
/* Merged completion for multiple non-scattered packets */
rx_queue->scatter_n = 1;
rx_queue->scatter_len = 0;
n_packets = n_descs;
++channel->n_rx_merge_events;
channel->n_rx_merge_packets += n_packets;
flags |= EFX_RX_PKT_PREFIX_LEN;
} else {
++rx_queue->scatter_n;
rx_queue->scatter_len += rx_bytes;
if (rx_cont)
return 0;
n_packets = 1;
}
EFX_POPULATE_QWORD_5(errors, ESF_DZ_RX_ECRC_ERR, 1,
ESF_DZ_RX_IPCKSUM_ERR, 1,
ESF_DZ_RX_TCPUDP_CKSUM_ERR, 1,
ESF_EZ_RX_IP_INNER_CHKSUM_ERR, 1,
ESF_EZ_RX_TCP_UDP_INNER_CHKSUM_ERR, 1);
EFX_AND_QWORD(errors, *event, errors);
if (unlikely(!EFX_QWORD_IS_ZERO(errors))) {
flags |= efx_ef10_handle_rx_event_errors(channel, n_packets,
rx_encap_hdr,
rx_l3_class, rx_l4_class,
event);
} else {
bool tcpudp = rx_l4_class == ESE_FZ_L4_CLASS_TCP ||
rx_l4_class == ESE_FZ_L4_CLASS_UDP;
switch (rx_encap_hdr) {
case ESE_EZ_ENCAP_HDR_VXLAN: /* VxLAN or GENEVE */
flags |= EFX_RX_PKT_CSUMMED; /* outer UDP csum */
if (tcpudp)
flags |= EFX_RX_PKT_CSUM_LEVEL; /* inner L4 */
break;
case ESE_EZ_ENCAP_HDR_GRE:
case ESE_EZ_ENCAP_HDR_NONE:
if (tcpudp)
flags |= EFX_RX_PKT_CSUMMED;
break;
default:
netdev_WARN(efx->net_dev,
"unknown encapsulation type: event="
EFX_QWORD_FMT "\n",
EFX_QWORD_VAL(*event));
}
}
if (rx_l4_class == ESE_FZ_L4_CLASS_TCP)
flags |= EFX_RX_PKT_TCP;
channel->irq_mod_score += 2 * n_packets;
/* Handle received packet(s) */
for (i = 0; i < n_packets; i++) {
efx_rx_packet(rx_queue,
rx_queue->removed_count & rx_queue->ptr_mask,
rx_queue->scatter_n, rx_queue->scatter_len,
flags);
rx_queue->removed_count += rx_queue->scatter_n;
}
rx_queue->scatter_n = 0;
rx_queue->scatter_len = 0;
return n_packets;
}
static u32 efx_ef10_extract_event_ts(efx_qword_t *event)
{
u32 tstamp;
tstamp = EFX_QWORD_FIELD(*event, TX_TIMESTAMP_EVENT_TSTAMP_DATA_HI);
tstamp <<= 16;
tstamp |= EFX_QWORD_FIELD(*event, TX_TIMESTAMP_EVENT_TSTAMP_DATA_LO);
return tstamp;
}
static int
efx_ef10_handle_tx_event(struct efx_channel *channel, efx_qword_t *event)
{
struct efx_nic *efx = channel->efx;
struct efx_tx_queue *tx_queue;
unsigned int tx_ev_desc_ptr;
unsigned int tx_ev_q_label;
unsigned int tx_ev_type;
int work_done;
u64 ts_part;
if (unlikely(READ_ONCE(efx->reset_pending)))
return 0;
if (unlikely(EFX_QWORD_FIELD(*event, ESF_DZ_TX_DROP_EVENT)))
return 0;
/* Get the transmit queue */
tx_ev_q_label = EFX_QWORD_FIELD(*event, ESF_DZ_TX_QLABEL);
tx_queue = channel->tx_queue + (tx_ev_q_label % EFX_MAX_TXQ_PER_CHANNEL);
if (!tx_queue->timestamping) {
/* Transmit completion */
tx_ev_desc_ptr = EFX_QWORD_FIELD(*event, ESF_DZ_TX_DESCR_INDX);
return efx_xmit_done(tx_queue, tx_ev_desc_ptr & tx_queue->ptr_mask);
}
/* Transmit timestamps are only available for 8XXX series. They result
* in up to three events per packet. These occur in order, and are:
* - the normal completion event (may be omitted)
* - the low part of the timestamp
* - the high part of the timestamp
*
* It's possible for multiple completion events to appear before the
* corresponding timestamps. So we can for example get:
* COMP N
* COMP N+1
* TS_LO N
* TS_HI N
* TS_LO N+1
* TS_HI N+1
*
* In addition it's also possible for the adjacent completions to be
* merged, so we may not see COMP N above. As such, the completion
* events are not very useful here.
*
* Each part of the timestamp is itself split across two 16 bit
* fields in the event.
*/
tx_ev_type = EFX_QWORD_FIELD(*event, ESF_EZ_TX_SOFT1);
work_done = 0;
switch (tx_ev_type) {
case TX_TIMESTAMP_EVENT_TX_EV_COMPLETION:
/* Ignore this event - see above. */
break;
case TX_TIMESTAMP_EVENT_TX_EV_TSTAMP_LO:
ts_part = efx_ef10_extract_event_ts(event);
tx_queue->completed_timestamp_minor = ts_part;
break;
case TX_TIMESTAMP_EVENT_TX_EV_TSTAMP_HI:
ts_part = efx_ef10_extract_event_ts(event);
tx_queue->completed_timestamp_major = ts_part;
efx_xmit_done_single(tx_queue);
work_done = 1;
break;
default:
netif_err(efx, hw, efx->net_dev,
"channel %d unknown tx event type %d (data "
EFX_QWORD_FMT ")\n",
channel->channel, tx_ev_type,
EFX_QWORD_VAL(*event));
break;
}
return work_done;
}
static void
efx_ef10_handle_driver_event(struct efx_channel *channel, efx_qword_t *event)
{
struct efx_nic *efx = channel->efx;
int subcode;
subcode = EFX_QWORD_FIELD(*event, ESF_DZ_DRV_SUB_CODE);
switch (subcode) {
case ESE_DZ_DRV_TIMER_EV:
case ESE_DZ_DRV_WAKE_UP_EV:
break;
case ESE_DZ_DRV_START_UP_EV:
/* event queue init complete. ok. */
break;
default:
netif_err(efx, hw, efx->net_dev,
"channel %d unknown driver event type %d"
" (data " EFX_QWORD_FMT ")\n",
channel->channel, subcode,
EFX_QWORD_VAL(*event));
}
}
static void efx_ef10_handle_driver_generated_event(struct efx_channel *channel,
efx_qword_t *event)
{
struct efx_nic *efx = channel->efx;
u32 subcode;
subcode = EFX_QWORD_FIELD(*event, EFX_DWORD_0);
switch (subcode) {
case EFX_EF10_TEST:
channel->event_test_cpu = raw_smp_processor_id();
break;
case EFX_EF10_REFILL:
/* The queue must be empty, so we won't receive any rx
* events, so efx_process_channel() won't refill the
* queue. Refill it here
*/
efx_fast_push_rx_descriptors(&channel->rx_queue, true);
break;
default:
netif_err(efx, hw, efx->net_dev,
"channel %d unknown driver event type %u"
" (data " EFX_QWORD_FMT ")\n",
channel->channel, (unsigned) subcode,
EFX_QWORD_VAL(*event));
}
}
#define EFX_NAPI_MAX_TX 512
static int efx_ef10_ev_process(struct efx_channel *channel, int quota)
{
struct efx_nic *efx = channel->efx;
efx_qword_t event, *p_event;
unsigned int read_ptr;
int spent_tx = 0;
int spent = 0;
int ev_code;
if (quota <= 0)
return spent;
read_ptr = channel->eventq_read_ptr;
for (;;) {
p_event = efx_event(channel, read_ptr);
event = *p_event;
if (!efx_event_present(&event))
break;
EFX_SET_QWORD(*p_event);
++read_ptr;
ev_code = EFX_QWORD_FIELD(event, ESF_DZ_EV_CODE);
netif_vdbg(efx, drv, efx->net_dev,
"processing event on %d " EFX_QWORD_FMT "\n",
channel->channel, EFX_QWORD_VAL(event));
switch (ev_code) {
case ESE_DZ_EV_CODE_MCDI_EV:
efx_mcdi_process_event(channel, &event);
break;
case ESE_DZ_EV_CODE_RX_EV:
spent += efx_ef10_handle_rx_event(channel, &event);
if (spent >= quota) {
/* XXX can we split a merged event to
* avoid going over-quota?
*/
spent = quota;
goto out;
}
break;
case ESE_DZ_EV_CODE_TX_EV:
spent_tx += efx_ef10_handle_tx_event(channel, &event);
if (spent_tx >= EFX_NAPI_MAX_TX) {
spent = quota;
goto out;
}
break;
case ESE_DZ_EV_CODE_DRIVER_EV:
efx_ef10_handle_driver_event(channel, &event);
if (++spent == quota)
goto out;
break;
case EFX_EF10_DRVGEN_EV:
efx_ef10_handle_driver_generated_event(channel, &event);
break;
default:
netif_err(efx, hw, efx->net_dev,
"channel %d unknown event type %d"
" (data " EFX_QWORD_FMT ")\n",
channel->channel, ev_code,
EFX_QWORD_VAL(event));
}
}
out:
channel->eventq_read_ptr = read_ptr;
return spent;
}
static void efx_ef10_ev_read_ack(struct efx_channel *channel)
{
struct efx_nic *efx = channel->efx;
efx_dword_t rptr;
if (EFX_EF10_WORKAROUND_35388(efx)) {
BUILD_BUG_ON(EFX_MIN_EVQ_SIZE <
(1 << ERF_DD_EVQ_IND_RPTR_WIDTH));
BUILD_BUG_ON(EFX_MAX_EVQ_SIZE >
(1 << 2 * ERF_DD_EVQ_IND_RPTR_WIDTH));
EFX_POPULATE_DWORD_2(rptr, ERF_DD_EVQ_IND_RPTR_FLAGS,
EFE_DD_EVQ_IND_RPTR_FLAGS_HIGH,
ERF_DD_EVQ_IND_RPTR,
(channel->eventq_read_ptr &
channel->eventq_mask) >>
ERF_DD_EVQ_IND_RPTR_WIDTH);
efx_writed_page(efx, &rptr, ER_DD_EVQ_INDIRECT,
channel->channel);
EFX_POPULATE_DWORD_2(rptr, ERF_DD_EVQ_IND_RPTR_FLAGS,
EFE_DD_EVQ_IND_RPTR_FLAGS_LOW,
ERF_DD_EVQ_IND_RPTR,
channel->eventq_read_ptr &
((1 << ERF_DD_EVQ_IND_RPTR_WIDTH) - 1));
efx_writed_page(efx, &rptr, ER_DD_EVQ_INDIRECT,
channel->channel);
} else {
EFX_POPULATE_DWORD_1(rptr, ERF_DZ_EVQ_RPTR,
channel->eventq_read_ptr &
channel->eventq_mask);
efx_writed_page(efx, &rptr, ER_DZ_EVQ_RPTR, channel->channel);
}
}
static void efx_ef10_ev_test_generate(struct efx_channel *channel)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_DRIVER_EVENT_IN_LEN);
struct efx_nic *efx = channel->efx;
efx_qword_t event;
int rc;
EFX_POPULATE_QWORD_2(event,
ESF_DZ_EV_CODE, EFX_EF10_DRVGEN_EV,
ESF_DZ_EV_DATA, EFX_EF10_TEST);
MCDI_SET_DWORD(inbuf, DRIVER_EVENT_IN_EVQ, channel->channel);
/* MCDI_SET_QWORD is not appropriate here since EFX_POPULATE_* has
* already swapped the data to little-endian order.
*/
memcpy(MCDI_PTR(inbuf, DRIVER_EVENT_IN_DATA), &event.u64[0],
sizeof(efx_qword_t));
rc = efx_mcdi_rpc(efx, MC_CMD_DRIVER_EVENT, inbuf, sizeof(inbuf),
NULL, 0, NULL);
if (rc != 0)
goto fail;
return;
fail:
WARN_ON(true);
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
}
static void efx_ef10_prepare_flr(struct efx_nic *efx)
{
atomic_set(&efx->active_queues, 0);
}
static int efx_ef10_vport_set_mac_address(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
u8 mac_old[ETH_ALEN];
int rc, rc2;
/* Only reconfigure a PF-created vport */
if (is_zero_ether_addr(nic_data->vport_mac))
return 0;
efx_device_detach_sync(efx);
efx_net_stop(efx->net_dev);
efx_ef10_filter_table_remove(efx);
rc = efx_ef10_vadaptor_free(efx, efx->vport_id);
if (rc)
goto restore_filters;
ether_addr_copy(mac_old, nic_data->vport_mac);
rc = efx_ef10_vport_del_mac(efx, efx->vport_id,
nic_data->vport_mac);
if (rc)
goto restore_vadaptor;
rc = efx_ef10_vport_add_mac(efx, efx->vport_id,
efx->net_dev->dev_addr);
if (!rc) {
ether_addr_copy(nic_data->vport_mac, efx->net_dev->dev_addr);
} else {
rc2 = efx_ef10_vport_add_mac(efx, efx->vport_id, mac_old);
if (rc2) {
/* Failed to add original MAC, so clear vport_mac */
eth_zero_addr(nic_data->vport_mac);
goto reset_nic;
}
}
restore_vadaptor:
rc2 = efx_ef10_vadaptor_alloc(efx, efx->vport_id);
if (rc2)
goto reset_nic;
restore_filters:
rc2 = efx_ef10_filter_table_probe(efx);
if (rc2)
goto reset_nic;
rc2 = efx_net_open(efx->net_dev);
if (rc2)
goto reset_nic;
efx_device_attach_if_not_resetting(efx);
return rc;
reset_nic:
netif_err(efx, drv, efx->net_dev,
"Failed to restore when changing MAC address - scheduling reset\n");
efx_schedule_reset(efx, RESET_TYPE_DATAPATH);
return rc ? rc : rc2;
}
static int efx_ef10_set_mac_address(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_VADAPTOR_SET_MAC_IN_LEN);
bool was_enabled = efx->port_enabled;
int rc;
#ifdef CONFIG_SFC_SRIOV
/* If this function is a VF and we have access to the parent PF,
* then use the PF control path to attempt to change the VF MAC address.
*/
if (efx->pci_dev->is_virtfn && efx->pci_dev->physfn) {
struct efx_nic *efx_pf = pci_get_drvdata(efx->pci_dev->physfn);
struct efx_ef10_nic_data *nic_data = efx->nic_data;
u8 mac[ETH_ALEN];
/* net_dev->dev_addr can be zeroed by efx_net_stop in
* efx_ef10_sriov_set_vf_mac, so pass in a copy.
*/
ether_addr_copy(mac, efx->net_dev->dev_addr);
rc = efx_ef10_sriov_set_vf_mac(efx_pf, nic_data->vf_index, mac);
if (!rc)
return 0;
netif_dbg(efx, drv, efx->net_dev,
"Updating VF mac via PF failed (%d), setting directly\n",
rc);
}
#endif
efx_device_detach_sync(efx);
efx_net_stop(efx->net_dev);
mutex_lock(&efx->mac_lock);
efx_ef10_filter_table_remove(efx);
ether_addr_copy(MCDI_PTR(inbuf, VADAPTOR_SET_MAC_IN_MACADDR),
efx->net_dev->dev_addr);
MCDI_SET_DWORD(inbuf, VADAPTOR_SET_MAC_IN_UPSTREAM_PORT_ID,
efx->vport_id);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_VADAPTOR_SET_MAC, inbuf,
sizeof(inbuf), NULL, 0, NULL);
efx_ef10_filter_table_probe(efx);
mutex_unlock(&efx->mac_lock);
if (was_enabled)
efx_net_open(efx->net_dev);
efx_device_attach_if_not_resetting(efx);
if (rc == -EPERM) {
netif_err(efx, drv, efx->net_dev,
"Cannot change MAC address; use sfboot to enable"
" mac-spoofing on this interface\n");
} else if (rc == -ENOSYS && !efx_ef10_is_vf(efx)) {
/* If the active MCFW does not support MC_CMD_VADAPTOR_SET_MAC
* fall-back to the method of changing the MAC address on the
* vport. This only applies to PFs because such versions of
* MCFW do not support VFs.
*/
rc = efx_ef10_vport_set_mac_address(efx);
} else if (rc) {
efx_mcdi_display_error(efx, MC_CMD_VADAPTOR_SET_MAC,
sizeof(inbuf), NULL, 0, rc);
}
return rc;
}
static int efx_ef10_mac_reconfigure(struct efx_nic *efx, bool mtu_only)
{
WARN_ON(!mutex_is_locked(&efx->mac_lock));
efx_mcdi_filter_sync_rx_mode(efx);
if (mtu_only && efx_has_cap(efx, SET_MAC_ENHANCED))
return efx_mcdi_set_mtu(efx);
return efx_mcdi_set_mac(efx);
}
static int efx_ef10_start_bist(struct efx_nic *efx, u32 bist_type)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_START_BIST_IN_LEN);
MCDI_SET_DWORD(inbuf, START_BIST_IN_TYPE, bist_type);
return efx_mcdi_rpc(efx, MC_CMD_START_BIST, inbuf, sizeof(inbuf),
NULL, 0, NULL);
}
/* MC BISTs follow a different poll mechanism to phy BISTs.
* The BIST is done in the poll handler on the MC, and the MCDI command
* will block until the BIST is done.
*/
static int efx_ef10_poll_bist(struct efx_nic *efx)
{
int rc;
MCDI_DECLARE_BUF(outbuf, MC_CMD_POLL_BIST_OUT_LEN);
size_t outlen;
u32 result;
rc = efx_mcdi_rpc(efx, MC_CMD_POLL_BIST, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc != 0)
return rc;
if (outlen < MC_CMD_POLL_BIST_OUT_LEN)
return -EIO;
result = MCDI_DWORD(outbuf, POLL_BIST_OUT_RESULT);
switch (result) {
case MC_CMD_POLL_BIST_PASSED:
netif_dbg(efx, hw, efx->net_dev, "BIST passed.\n");
return 0;
case MC_CMD_POLL_BIST_TIMEOUT:
netif_err(efx, hw, efx->net_dev, "BIST timed out\n");
return -EIO;
case MC_CMD_POLL_BIST_FAILED:
netif_err(efx, hw, efx->net_dev, "BIST failed.\n");
return -EIO;
default:
netif_err(efx, hw, efx->net_dev,
"BIST returned unknown result %u", result);
return -EIO;
}
}
static int efx_ef10_run_bist(struct efx_nic *efx, u32 bist_type)
{
int rc;
netif_dbg(efx, drv, efx->net_dev, "starting BIST type %u\n", bist_type);
rc = efx_ef10_start_bist(efx, bist_type);
if (rc != 0)
return rc;
return efx_ef10_poll_bist(efx);
}
static int
efx_ef10_test_chip(struct efx_nic *efx, struct efx_self_tests *tests)
{
int rc, rc2;
efx_reset_down(efx, RESET_TYPE_WORLD);
rc = efx_mcdi_rpc(efx, MC_CMD_ENABLE_OFFLINE_BIST,
NULL, 0, NULL, 0, NULL);
if (rc != 0)
goto out;
tests->memory = efx_ef10_run_bist(efx, MC_CMD_MC_MEM_BIST) ? -1 : 1;
tests->registers = efx_ef10_run_bist(efx, MC_CMD_REG_BIST) ? -1 : 1;
rc = efx_mcdi_reset(efx, RESET_TYPE_WORLD);
out:
if (rc == -EPERM)
rc = 0;
rc2 = efx_reset_up(efx, RESET_TYPE_WORLD, rc == 0);
return rc ? rc : rc2;
}
#ifdef CONFIG_SFC_MTD
struct efx_ef10_nvram_type_info {
u16 type, type_mask;
u8 port;
const char *name;
};
static const struct efx_ef10_nvram_type_info efx_ef10_nvram_types[] = {
{ NVRAM_PARTITION_TYPE_MC_FIRMWARE, 0, 0, "sfc_mcfw" },
{ NVRAM_PARTITION_TYPE_MC_FIRMWARE_BACKUP, 0, 0, "sfc_mcfw_backup" },
{ NVRAM_PARTITION_TYPE_EXPANSION_ROM, 0, 0, "sfc_exp_rom" },
{ NVRAM_PARTITION_TYPE_STATIC_CONFIG, 0, 0, "sfc_static_cfg" },
{ NVRAM_PARTITION_TYPE_DYNAMIC_CONFIG, 0, 0, "sfc_dynamic_cfg" },
{ NVRAM_PARTITION_TYPE_EXPROM_CONFIG_PORT0, 0, 0, "sfc_exp_rom_cfg" },
{ NVRAM_PARTITION_TYPE_EXPROM_CONFIG_PORT1, 0, 1, "sfc_exp_rom_cfg" },
{ NVRAM_PARTITION_TYPE_EXPROM_CONFIG_PORT2, 0, 2, "sfc_exp_rom_cfg" },
{ NVRAM_PARTITION_TYPE_EXPROM_CONFIG_PORT3, 0, 3, "sfc_exp_rom_cfg" },
{ NVRAM_PARTITION_TYPE_LICENSE, 0, 0, "sfc_license" },
{ NVRAM_PARTITION_TYPE_PHY_MIN, 0xff, 0, "sfc_phy_fw" },
{ NVRAM_PARTITION_TYPE_MUM_FIRMWARE, 0, 0, "sfc_mumfw" },
{ NVRAM_PARTITION_TYPE_EXPANSION_UEFI, 0, 0, "sfc_uefi" },
{ NVRAM_PARTITION_TYPE_DYNCONFIG_DEFAULTS, 0, 0, "sfc_dynamic_cfg_dflt" },
{ NVRAM_PARTITION_TYPE_ROMCONFIG_DEFAULTS, 0, 0, "sfc_exp_rom_cfg_dflt" },
{ NVRAM_PARTITION_TYPE_STATUS, 0, 0, "sfc_status" },
{ NVRAM_PARTITION_TYPE_BUNDLE, 0, 0, "sfc_bundle" },
{ NVRAM_PARTITION_TYPE_BUNDLE_METADATA, 0, 0, "sfc_bundle_metadata" },
};
#define EF10_NVRAM_PARTITION_COUNT ARRAY_SIZE(efx_ef10_nvram_types)
static int efx_ef10_mtd_probe_partition(struct efx_nic *efx,
struct efx_mcdi_mtd_partition *part,
unsigned int type,
unsigned long *found)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_NVRAM_METADATA_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_NVRAM_METADATA_OUT_LENMAX);
const struct efx_ef10_nvram_type_info *info;
size_t size, erase_size, outlen;
int type_idx = 0;
bool protected;
int rc;
for (type_idx = 0; ; type_idx++) {
if (type_idx == EF10_NVRAM_PARTITION_COUNT)
return -ENODEV;
info = efx_ef10_nvram_types + type_idx;
if ((type & ~info->type_mask) == info->type)
break;
}
if (info->port != efx_port_num(efx))
return -ENODEV;
rc = efx_mcdi_nvram_info(efx, type, &size, &erase_size, &protected);
if (rc)
return rc;
if (protected &&
(type != NVRAM_PARTITION_TYPE_DYNCONFIG_DEFAULTS &&
type != NVRAM_PARTITION_TYPE_ROMCONFIG_DEFAULTS))
/* Hide protected partitions that don't provide defaults. */
return -ENODEV;
if (protected)
/* Protected partitions are read only. */
erase_size = 0;
/* If we've already exposed a partition of this type, hide this
* duplicate. All operations on MTDs are keyed by the type anyway,
* so we can't act on the duplicate.
*/
if (__test_and_set_bit(type_idx, found))
return -EEXIST;
part->nvram_type = type;
MCDI_SET_DWORD(inbuf, NVRAM_METADATA_IN_TYPE, type);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_METADATA, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < MC_CMD_NVRAM_METADATA_OUT_LENMIN)
return -EIO;
if (MCDI_DWORD(outbuf, NVRAM_METADATA_OUT_FLAGS) &
(1 << MC_CMD_NVRAM_METADATA_OUT_SUBTYPE_VALID_LBN))
part->fw_subtype = MCDI_DWORD(outbuf,
NVRAM_METADATA_OUT_SUBTYPE);
part->common.dev_type_name = "EF10 NVRAM manager";
part->common.type_name = info->name;
part->common.mtd.type = MTD_NORFLASH;
part->common.mtd.flags = MTD_CAP_NORFLASH;
part->common.mtd.size = size;
part->common.mtd.erasesize = erase_size;
/* sfc_status is read-only */
if (!erase_size)
part->common.mtd.flags |= MTD_NO_ERASE;
return 0;
}
static int efx_ef10_mtd_probe(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_NVRAM_PARTITIONS_OUT_LENMAX);
DECLARE_BITMAP(found, EF10_NVRAM_PARTITION_COUNT) = { 0 };
struct efx_mcdi_mtd_partition *parts;
size_t outlen, n_parts_total, i, n_parts;
unsigned int type;
int rc;
ASSERT_RTNL();
BUILD_BUG_ON(MC_CMD_NVRAM_PARTITIONS_IN_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_PARTITIONS, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < MC_CMD_NVRAM_PARTITIONS_OUT_LENMIN)
return -EIO;
n_parts_total = MCDI_DWORD(outbuf, NVRAM_PARTITIONS_OUT_NUM_PARTITIONS);
if (n_parts_total >
MCDI_VAR_ARRAY_LEN(outlen, NVRAM_PARTITIONS_OUT_TYPE_ID))
return -EIO;
parts = kcalloc(n_parts_total, sizeof(*parts), GFP_KERNEL);
if (!parts)
return -ENOMEM;
n_parts = 0;
for (i = 0; i < n_parts_total; i++) {
type = MCDI_ARRAY_DWORD(outbuf, NVRAM_PARTITIONS_OUT_TYPE_ID,
i);
rc = efx_ef10_mtd_probe_partition(efx, &parts[n_parts], type,
found);
if (rc == -EEXIST || rc == -ENODEV)
continue;
if (rc)
goto fail;
n_parts++;
}
if (!n_parts) {
kfree(parts);
return 0;
}
rc = efx_mtd_add(efx, &parts[0].common, n_parts, sizeof(*parts));
fail:
if (rc)
kfree(parts);
return rc;
}
#endif /* CONFIG_SFC_MTD */
static void efx_ef10_ptp_write_host_time(struct efx_nic *efx, u32 host_time)
{
_efx_writed(efx, cpu_to_le32(host_time), ER_DZ_MC_DB_LWRD);
}
static void efx_ef10_ptp_write_host_time_vf(struct efx_nic *efx,
u32 host_time) {}
static int efx_ef10_rx_enable_timestamping(struct efx_channel *channel,
bool temp)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_TIME_EVENT_SUBSCRIBE_LEN);
int rc;
if (channel->sync_events_state == SYNC_EVENTS_REQUESTED ||
channel->sync_events_state == SYNC_EVENTS_VALID ||
(temp && channel->sync_events_state == SYNC_EVENTS_DISABLED))
return 0;
channel->sync_events_state = SYNC_EVENTS_REQUESTED;
MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_TIME_EVENT_SUBSCRIBE);
MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
MCDI_SET_DWORD(inbuf, PTP_IN_TIME_EVENT_SUBSCRIBE_QUEUE,
channel->channel);
rc = efx_mcdi_rpc(channel->efx, MC_CMD_PTP,
inbuf, sizeof(inbuf), NULL, 0, NULL);
if (rc != 0)
channel->sync_events_state = temp ? SYNC_EVENTS_QUIESCENT :
SYNC_EVENTS_DISABLED;
return rc;
}
static int efx_ef10_rx_disable_timestamping(struct efx_channel *channel,
bool temp)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_TIME_EVENT_UNSUBSCRIBE_LEN);
int rc;
if (channel->sync_events_state == SYNC_EVENTS_DISABLED ||
(temp && channel->sync_events_state == SYNC_EVENTS_QUIESCENT))
return 0;
if (channel->sync_events_state == SYNC_EVENTS_QUIESCENT) {
channel->sync_events_state = SYNC_EVENTS_DISABLED;
return 0;
}
channel->sync_events_state = temp ? SYNC_EVENTS_QUIESCENT :
SYNC_EVENTS_DISABLED;
MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_TIME_EVENT_UNSUBSCRIBE);
MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
MCDI_SET_DWORD(inbuf, PTP_IN_TIME_EVENT_UNSUBSCRIBE_CONTROL,
MC_CMD_PTP_IN_TIME_EVENT_UNSUBSCRIBE_SINGLE);
MCDI_SET_DWORD(inbuf, PTP_IN_TIME_EVENT_UNSUBSCRIBE_QUEUE,
channel->channel);
rc = efx_mcdi_rpc(channel->efx, MC_CMD_PTP,
inbuf, sizeof(inbuf), NULL, 0, NULL);
return rc;
}
static int efx_ef10_ptp_set_ts_sync_events(struct efx_nic *efx, bool en,
bool temp)
{
int (*set)(struct efx_channel *channel, bool temp);
struct efx_channel *channel;
set = en ?
efx_ef10_rx_enable_timestamping :
efx_ef10_rx_disable_timestamping;
channel = efx_ptp_channel(efx);
if (channel) {
int rc = set(channel, temp);
if (en && rc != 0) {
efx_ef10_ptp_set_ts_sync_events(efx, false, temp);
return rc;
}
}
return 0;
}
static int efx_ef10_ptp_set_ts_config_vf(struct efx_nic *efx,
struct hwtstamp_config *init)
{
return -EOPNOTSUPP;
}
static int efx_ef10_ptp_set_ts_config(struct efx_nic *efx,
struct hwtstamp_config *init)
{
int rc;
switch (init->rx_filter) {
case HWTSTAMP_FILTER_NONE:
efx_ef10_ptp_set_ts_sync_events(efx, false, false);
/* if TX timestamping is still requested then leave PTP on */
return efx_ptp_change_mode(efx,
init->tx_type != HWTSTAMP_TX_OFF, 0);
case HWTSTAMP_FILTER_ALL:
case HWTSTAMP_FILTER_PTP_V1_L4_EVENT:
case HWTSTAMP_FILTER_PTP_V1_L4_SYNC:
case HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ:
case HWTSTAMP_FILTER_PTP_V2_L4_EVENT:
case HWTSTAMP_FILTER_PTP_V2_L4_SYNC:
case HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ:
case HWTSTAMP_FILTER_PTP_V2_L2_EVENT:
case HWTSTAMP_FILTER_PTP_V2_L2_SYNC:
case HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ:
case HWTSTAMP_FILTER_PTP_V2_EVENT:
case HWTSTAMP_FILTER_PTP_V2_SYNC:
case HWTSTAMP_FILTER_PTP_V2_DELAY_REQ:
case HWTSTAMP_FILTER_NTP_ALL:
init->rx_filter = HWTSTAMP_FILTER_ALL;
rc = efx_ptp_change_mode(efx, true, 0);
if (!rc)
rc = efx_ef10_ptp_set_ts_sync_events(efx, true, false);
if (rc)
efx_ptp_change_mode(efx, false, 0);
return rc;
default:
return -ERANGE;
}
}
static int efx_ef10_get_phys_port_id(struct efx_nic *efx,
struct netdev_phys_item_id *ppid)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
if (!is_valid_ether_addr(nic_data->port_id))
return -EOPNOTSUPP;
ppid->id_len = ETH_ALEN;
memcpy(ppid->id, nic_data->port_id, ppid->id_len);
return 0;
}
static int efx_ef10_vlan_rx_add_vid(struct efx_nic *efx, __be16 proto, u16 vid)
{
if (proto != htons(ETH_P_8021Q))
return -EINVAL;
return efx_ef10_add_vlan(efx, vid);
}
static int efx_ef10_vlan_rx_kill_vid(struct efx_nic *efx, __be16 proto, u16 vid)
{
if (proto != htons(ETH_P_8021Q))
return -EINVAL;
return efx_ef10_del_vlan(efx, vid);
}
/* We rely on the MCDI wiping out our TX rings if it made any changes to the
* ports table, ensuring that any TSO descriptors that were made on a now-
* removed tunnel port will be blown away and won't break things when we try
* to transmit them using the new ports table.
*/
static int efx_ef10_set_udp_tnl_ports(struct efx_nic *efx, bool unloading)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
MCDI_DECLARE_BUF(inbuf, MC_CMD_SET_TUNNEL_ENCAP_UDP_PORTS_IN_LENMAX);
MCDI_DECLARE_BUF(outbuf, MC_CMD_SET_TUNNEL_ENCAP_UDP_PORTS_OUT_LEN);
bool will_reset = false;
size_t num_entries = 0;
size_t inlen, outlen;
size_t i;
int rc;
efx_dword_t flags_and_num_entries;
WARN_ON(!mutex_is_locked(&nic_data->udp_tunnels_lock));
nic_data->udp_tunnels_dirty = false;
if (!(nic_data->datapath_caps &
(1 << MC_CMD_GET_CAPABILITIES_OUT_VXLAN_NVGRE_LBN))) {
efx_device_attach_if_not_resetting(efx);
return 0;
}
BUILD_BUG_ON(ARRAY_SIZE(nic_data->udp_tunnels) >
MC_CMD_SET_TUNNEL_ENCAP_UDP_PORTS_IN_ENTRIES_MAXNUM);
for (i = 0; i < ARRAY_SIZE(nic_data->udp_tunnels); ++i) {
if (nic_data->udp_tunnels[i].type !=
TUNNEL_ENCAP_UDP_PORT_ENTRY_INVALID) {
efx_dword_t entry;
EFX_POPULATE_DWORD_2(entry,
TUNNEL_ENCAP_UDP_PORT_ENTRY_UDP_PORT,
ntohs(nic_data->udp_tunnels[i].port),
TUNNEL_ENCAP_UDP_PORT_ENTRY_PROTOCOL,
nic_data->udp_tunnels[i].type);
*_MCDI_ARRAY_DWORD(inbuf,
SET_TUNNEL_ENCAP_UDP_PORTS_IN_ENTRIES,
num_entries++) = entry;
}
}
BUILD_BUG_ON((MC_CMD_SET_TUNNEL_ENCAP_UDP_PORTS_IN_NUM_ENTRIES_OFST -
MC_CMD_SET_TUNNEL_ENCAP_UDP_PORTS_IN_FLAGS_OFST) * 8 !=
EFX_WORD_1_LBN);
BUILD_BUG_ON(MC_CMD_SET_TUNNEL_ENCAP_UDP_PORTS_IN_NUM_ENTRIES_LEN * 8 !=
EFX_WORD_1_WIDTH);
EFX_POPULATE_DWORD_2(flags_and_num_entries,
MC_CMD_SET_TUNNEL_ENCAP_UDP_PORTS_IN_UNLOADING,
!!unloading,
EFX_WORD_1, num_entries);
*_MCDI_DWORD(inbuf, SET_TUNNEL_ENCAP_UDP_PORTS_IN_FLAGS) =
flags_and_num_entries;
inlen = MC_CMD_SET_TUNNEL_ENCAP_UDP_PORTS_IN_LEN(num_entries);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_SET_TUNNEL_ENCAP_UDP_PORTS,
inbuf, inlen, outbuf, sizeof(outbuf), &outlen);
if (rc == -EIO) {
/* Most likely the MC rebooted due to another function also
* setting its tunnel port list. Mark the tunnel port list as
* dirty, so it will be pushed upon coming up from the reboot.
*/
nic_data->udp_tunnels_dirty = true;
return 0;
}
if (rc) {
/* expected not available on unprivileged functions */
if (rc != -EPERM)
netif_warn(efx, drv, efx->net_dev,
"Unable to set UDP tunnel ports; rc=%d.\n", rc);
} else if (MCDI_DWORD(outbuf, SET_TUNNEL_ENCAP_UDP_PORTS_OUT_FLAGS) &
(1 << MC_CMD_SET_TUNNEL_ENCAP_UDP_PORTS_OUT_RESETTING_LBN)) {
netif_info(efx, drv, efx->net_dev,
"Rebooting MC due to UDP tunnel port list change\n");
will_reset = true;
if (unloading)
/* Delay for the MC reset to complete. This will make
* unloading other functions a bit smoother. This is a
* race, but the other unload will work whichever way
* it goes, this just avoids an unnecessary error
* message.
*/
msleep(100);
}
if (!will_reset && !unloading) {
/* The caller will have detached, relying on the MC reset to
* trigger a re-attach. Since there won't be an MC reset, we
* have to do the attach ourselves.
*/
efx_device_attach_if_not_resetting(efx);
}
return rc;
}
static int efx_ef10_udp_tnl_push_ports(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
int rc = 0;
mutex_lock(&nic_data->udp_tunnels_lock);
if (nic_data->udp_tunnels_dirty) {
/* Make sure all TX are stopped while we modify the table, else
* we might race against an efx_features_check().
*/
efx_device_detach_sync(efx);
rc = efx_ef10_set_udp_tnl_ports(efx, false);
}
mutex_unlock(&nic_data->udp_tunnels_lock);
return rc;
}
static int efx_ef10_udp_tnl_set_port(struct net_device *dev,
unsigned int table, unsigned int entry,
struct udp_tunnel_info *ti)
{
struct efx_nic *efx = efx_netdev_priv(dev);
struct efx_ef10_nic_data *nic_data;
int efx_tunnel_type, rc;
if (ti->type == UDP_TUNNEL_TYPE_VXLAN)
efx_tunnel_type = TUNNEL_ENCAP_UDP_PORT_ENTRY_VXLAN;
else
efx_tunnel_type = TUNNEL_ENCAP_UDP_PORT_ENTRY_GENEVE;
nic_data = efx->nic_data;
if (!(nic_data->datapath_caps &
(1 << MC_CMD_GET_CAPABILITIES_OUT_VXLAN_NVGRE_LBN)))
return -EOPNOTSUPP;
mutex_lock(&nic_data->udp_tunnels_lock);
/* Make sure all TX are stopped while we add to the table, else we
* might race against an efx_features_check().
*/
efx_device_detach_sync(efx);
nic_data->udp_tunnels[entry].type = efx_tunnel_type;
nic_data->udp_tunnels[entry].port = ti->port;
rc = efx_ef10_set_udp_tnl_ports(efx, false);
mutex_unlock(&nic_data->udp_tunnels_lock);
return rc;
}
/* Called under the TX lock with the TX queue running, hence no-one can be
* in the middle of updating the UDP tunnels table. However, they could
* have tried and failed the MCDI, in which case they'll have set the dirty
* flag before dropping their locks.
*/
static bool efx_ef10_udp_tnl_has_port(struct efx_nic *efx, __be16 port)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
size_t i;
if (!(nic_data->datapath_caps &
(1 << MC_CMD_GET_CAPABILITIES_OUT_VXLAN_NVGRE_LBN)))
return false;
if (nic_data->udp_tunnels_dirty)
/* SW table may not match HW state, so just assume we can't
* use any UDP tunnel offloads.
*/
return false;
for (i = 0; i < ARRAY_SIZE(nic_data->udp_tunnels); ++i)
if (nic_data->udp_tunnels[i].type !=
TUNNEL_ENCAP_UDP_PORT_ENTRY_INVALID &&
nic_data->udp_tunnels[i].port == port)
return true;
return false;
}
static int efx_ef10_udp_tnl_unset_port(struct net_device *dev,
unsigned int table, unsigned int entry,
struct udp_tunnel_info *ti)
{
struct efx_nic *efx = efx_netdev_priv(dev);
struct efx_ef10_nic_data *nic_data;
int rc;
nic_data = efx->nic_data;
mutex_lock(&nic_data->udp_tunnels_lock);
/* Make sure all TX are stopped while we remove from the table, else we
* might race against an efx_features_check().
*/
efx_device_detach_sync(efx);
nic_data->udp_tunnels[entry].type = TUNNEL_ENCAP_UDP_PORT_ENTRY_INVALID;
nic_data->udp_tunnels[entry].port = 0;
rc = efx_ef10_set_udp_tnl_ports(efx, false);
mutex_unlock(&nic_data->udp_tunnels_lock);
return rc;
}
static const struct udp_tunnel_nic_info efx_ef10_udp_tunnels = {
.set_port = efx_ef10_udp_tnl_set_port,
.unset_port = efx_ef10_udp_tnl_unset_port,
.flags = UDP_TUNNEL_NIC_INFO_MAY_SLEEP,
.tables = {
{
.n_entries = 16,
.tunnel_types = UDP_TUNNEL_TYPE_VXLAN |
UDP_TUNNEL_TYPE_GENEVE,
},
},
};
/* EF10 may have multiple datapath firmware variants within a
* single version. Report which variants are running.
*/
static size_t efx_ef10_print_additional_fwver(struct efx_nic *efx, char *buf,
size_t len)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
return scnprintf(buf, len, " rx%x tx%x",
nic_data->rx_dpcpu_fw_id,
nic_data->tx_dpcpu_fw_id);
}
static unsigned int ef10_check_caps(const struct efx_nic *efx,
u8 flag,
u32 offset)
{
const struct efx_ef10_nic_data *nic_data = efx->nic_data;
switch (offset) {
case(MC_CMD_GET_CAPABILITIES_V4_OUT_FLAGS1_OFST):
return nic_data->datapath_caps & BIT_ULL(flag);
case(MC_CMD_GET_CAPABILITIES_V4_OUT_FLAGS2_OFST):
return nic_data->datapath_caps2 & BIT_ULL(flag);
default:
return 0;
}
}
static unsigned int efx_ef10_recycle_ring_size(const struct efx_nic *efx)
{
unsigned int ret = EFX_RECYCLE_RING_SIZE_10G;
/* There is no difference between PFs and VFs. The side is based on
* the maximum link speed of a given NIC.
*/
switch (efx->pci_dev->device & 0xfff) {
case 0x0903: /* Farmingdale can do up to 10G */
break;
case 0x0923: /* Greenport can do up to 40G */
case 0x0a03: /* Medford can do up to 40G */
ret *= 4;
break;
default: /* Medford2 can do up to 100G */
ret *= 10;
}
if (IS_ENABLED(CONFIG_PPC64))
ret *= 4;
return ret;
}
#define EF10_OFFLOAD_FEATURES \
(NETIF_F_IP_CSUM | \
NETIF_F_HW_VLAN_CTAG_FILTER | \
NETIF_F_IPV6_CSUM | \
NETIF_F_RXHASH | \
NETIF_F_NTUPLE | \
NETIF_F_SG | \
NETIF_F_RXCSUM | \
NETIF_F_RXALL)
const struct efx_nic_type efx_hunt_a0_vf_nic_type = {
.is_vf = true,
.mem_bar = efx_ef10_vf_mem_bar,
.mem_map_size = efx_ef10_mem_map_size,
.probe = efx_ef10_probe_vf,
.remove = efx_ef10_remove,
.dimension_resources = efx_ef10_dimension_resources,
.init = efx_ef10_init_nic,
.fini = efx_ef10_fini_nic,
.map_reset_reason = efx_ef10_map_reset_reason,
.map_reset_flags = efx_ef10_map_reset_flags,
.reset = efx_ef10_reset,
.probe_port = efx_mcdi_port_probe,
.remove_port = efx_mcdi_port_remove,
.fini_dmaq = efx_fini_dmaq,
.prepare_flr = efx_ef10_prepare_flr,
.finish_flr = efx_port_dummy_op_void,
.describe_stats = efx_ef10_describe_stats,
.update_stats = efx_ef10_update_stats_vf,
.update_stats_atomic = efx_ef10_update_stats_atomic_vf,
.start_stats = efx_port_dummy_op_void,
.pull_stats = efx_port_dummy_op_void,
.stop_stats = efx_port_dummy_op_void,
.push_irq_moderation = efx_ef10_push_irq_moderation,
.reconfigure_mac = efx_ef10_mac_reconfigure,
.check_mac_fault = efx_mcdi_mac_check_fault,
.reconfigure_port = efx_mcdi_port_reconfigure,
.get_wol = efx_ef10_get_wol_vf,
.set_wol = efx_ef10_set_wol_vf,
.resume_wol = efx_port_dummy_op_void,
.mcdi_request = efx_ef10_mcdi_request,
.mcdi_poll_response = efx_ef10_mcdi_poll_response,
.mcdi_read_response = efx_ef10_mcdi_read_response,
.mcdi_poll_reboot = efx_ef10_mcdi_poll_reboot,
.mcdi_reboot_detected = efx_ef10_mcdi_reboot_detected,
.irq_enable_master = efx_port_dummy_op_void,
.irq_test_generate = efx_ef10_irq_test_generate,
.irq_disable_non_ev = efx_port_dummy_op_void,
.irq_handle_msi = efx_ef10_msi_interrupt,
.irq_handle_legacy = efx_ef10_legacy_interrupt,
.tx_probe = efx_ef10_tx_probe,
.tx_init = efx_ef10_tx_init,
.tx_remove = efx_mcdi_tx_remove,
.tx_write = efx_ef10_tx_write,
.tx_limit_len = efx_ef10_tx_limit_len,
.tx_enqueue = __efx_enqueue_skb,
.rx_push_rss_config = efx_mcdi_vf_rx_push_rss_config,
.rx_pull_rss_config = efx_mcdi_rx_pull_rss_config,
.rx_probe = efx_mcdi_rx_probe,
.rx_init = efx_mcdi_rx_init,
.rx_remove = efx_mcdi_rx_remove,
.rx_write = efx_ef10_rx_write,
.rx_defer_refill = efx_ef10_rx_defer_refill,
.rx_packet = __efx_rx_packet,
.ev_probe = efx_mcdi_ev_probe,
.ev_init = efx_ef10_ev_init,
.ev_fini = efx_mcdi_ev_fini,
.ev_remove = efx_mcdi_ev_remove,
.ev_process = efx_ef10_ev_process,
.ev_read_ack = efx_ef10_ev_read_ack,
.ev_test_generate = efx_ef10_ev_test_generate,
.filter_table_probe = efx_ef10_filter_table_probe,
.filter_table_restore = efx_mcdi_filter_table_restore,
.filter_table_remove = efx_ef10_filter_table_remove,
.filter_update_rx_scatter = efx_mcdi_update_rx_scatter,
.filter_insert = efx_mcdi_filter_insert,
.filter_remove_safe = efx_mcdi_filter_remove_safe,
.filter_get_safe = efx_mcdi_filter_get_safe,
.filter_clear_rx = efx_mcdi_filter_clear_rx,
.filter_count_rx_used = efx_mcdi_filter_count_rx_used,
.filter_get_rx_id_limit = efx_mcdi_filter_get_rx_id_limit,
.filter_get_rx_ids = efx_mcdi_filter_get_rx_ids,
#ifdef CONFIG_RFS_ACCEL
.filter_rfs_expire_one = efx_mcdi_filter_rfs_expire_one,
#endif
#ifdef CONFIG_SFC_MTD
.mtd_probe = efx_port_dummy_op_int,
#endif
.ptp_write_host_time = efx_ef10_ptp_write_host_time_vf,
.ptp_set_ts_config = efx_ef10_ptp_set_ts_config_vf,
.vlan_rx_add_vid = efx_ef10_vlan_rx_add_vid,
.vlan_rx_kill_vid = efx_ef10_vlan_rx_kill_vid,
#ifdef CONFIG_SFC_SRIOV
.vswitching_probe = efx_ef10_vswitching_probe_vf,
.vswitching_restore = efx_ef10_vswitching_restore_vf,
.vswitching_remove = efx_ef10_vswitching_remove_vf,
#endif
.get_mac_address = efx_ef10_get_mac_address_vf,
.set_mac_address = efx_ef10_set_mac_address,
.get_phys_port_id = efx_ef10_get_phys_port_id,
.revision = EFX_REV_HUNT_A0,
.max_dma_mask = DMA_BIT_MASK(ESF_DZ_TX_KER_BUF_ADDR_WIDTH),
.rx_prefix_size = ES_DZ_RX_PREFIX_SIZE,
.rx_hash_offset = ES_DZ_RX_PREFIX_HASH_OFST,
.rx_ts_offset = ES_DZ_RX_PREFIX_TSTAMP_OFST,
.can_rx_scatter = true,
.always_rx_scatter = true,
.min_interrupt_mode = EFX_INT_MODE_MSIX,
.timer_period_max = 1 << ERF_DD_EVQ_IND_TIMER_VAL_WIDTH,
.offload_features = EF10_OFFLOAD_FEATURES,
.mcdi_max_ver = 2,
.max_rx_ip_filters = EFX_MCDI_FILTER_TBL_ROWS,
.hwtstamp_filters = 1 << HWTSTAMP_FILTER_NONE |
1 << HWTSTAMP_FILTER_ALL,
.rx_hash_key_size = 40,
.check_caps = ef10_check_caps,
.print_additional_fwver = efx_ef10_print_additional_fwver,
.sensor_event = efx_mcdi_sensor_event,
.rx_recycle_ring_size = efx_ef10_recycle_ring_size,
};
const struct efx_nic_type efx_hunt_a0_nic_type = {
.is_vf = false,
.mem_bar = efx_ef10_pf_mem_bar,
.mem_map_size = efx_ef10_mem_map_size,
.probe = efx_ef10_probe_pf,
.remove = efx_ef10_remove,
.dimension_resources = efx_ef10_dimension_resources,
.init = efx_ef10_init_nic,
.fini = efx_ef10_fini_nic,
.map_reset_reason = efx_ef10_map_reset_reason,
.map_reset_flags = efx_ef10_map_reset_flags,
.reset = efx_ef10_reset,
.probe_port = efx_mcdi_port_probe,
.remove_port = efx_mcdi_port_remove,
.fini_dmaq = efx_fini_dmaq,
.prepare_flr = efx_ef10_prepare_flr,
.finish_flr = efx_port_dummy_op_void,
.describe_stats = efx_ef10_describe_stats,
.update_stats = efx_ef10_update_stats_pf,
.start_stats = efx_mcdi_mac_start_stats,
.pull_stats = efx_mcdi_mac_pull_stats,
.stop_stats = efx_mcdi_mac_stop_stats,
.push_irq_moderation = efx_ef10_push_irq_moderation,
.reconfigure_mac = efx_ef10_mac_reconfigure,
.check_mac_fault = efx_mcdi_mac_check_fault,
.reconfigure_port = efx_mcdi_port_reconfigure,
.get_wol = efx_ef10_get_wol,
.set_wol = efx_ef10_set_wol,
.resume_wol = efx_port_dummy_op_void,
.get_fec_stats = efx_ef10_get_fec_stats,
.test_chip = efx_ef10_test_chip,
.test_nvram = efx_mcdi_nvram_test_all,
.mcdi_request = efx_ef10_mcdi_request,
.mcdi_poll_response = efx_ef10_mcdi_poll_response,
.mcdi_read_response = efx_ef10_mcdi_read_response,
.mcdi_poll_reboot = efx_ef10_mcdi_poll_reboot,
.mcdi_reboot_detected = efx_ef10_mcdi_reboot_detected,
.irq_enable_master = efx_port_dummy_op_void,
.irq_test_generate = efx_ef10_irq_test_generate,
.irq_disable_non_ev = efx_port_dummy_op_void,
.irq_handle_msi = efx_ef10_msi_interrupt,
.irq_handle_legacy = efx_ef10_legacy_interrupt,
.tx_probe = efx_ef10_tx_probe,
.tx_init = efx_ef10_tx_init,
.tx_remove = efx_mcdi_tx_remove,
.tx_write = efx_ef10_tx_write,
.tx_limit_len = efx_ef10_tx_limit_len,
.tx_enqueue = __efx_enqueue_skb,
.rx_push_rss_config = efx_mcdi_pf_rx_push_rss_config,
.rx_pull_rss_config = efx_mcdi_rx_pull_rss_config,
.rx_push_rss_context_config = efx_mcdi_rx_push_rss_context_config,
.rx_pull_rss_context_config = efx_mcdi_rx_pull_rss_context_config,
.rx_restore_rss_contexts = efx_mcdi_rx_restore_rss_contexts,
.rx_probe = efx_mcdi_rx_probe,
.rx_init = efx_mcdi_rx_init,
.rx_remove = efx_mcdi_rx_remove,
.rx_write = efx_ef10_rx_write,
.rx_defer_refill = efx_ef10_rx_defer_refill,
.rx_packet = __efx_rx_packet,
.ev_probe = efx_mcdi_ev_probe,
.ev_init = efx_ef10_ev_init,
.ev_fini = efx_mcdi_ev_fini,
.ev_remove = efx_mcdi_ev_remove,
.ev_process = efx_ef10_ev_process,
.ev_read_ack = efx_ef10_ev_read_ack,
.ev_test_generate = efx_ef10_ev_test_generate,
.filter_table_probe = efx_ef10_filter_table_probe,
.filter_table_restore = efx_mcdi_filter_table_restore,
.filter_table_remove = efx_ef10_filter_table_remove,
.filter_update_rx_scatter = efx_mcdi_update_rx_scatter,
.filter_insert = efx_mcdi_filter_insert,
.filter_remove_safe = efx_mcdi_filter_remove_safe,
.filter_get_safe = efx_mcdi_filter_get_safe,
.filter_clear_rx = efx_mcdi_filter_clear_rx,
.filter_count_rx_used = efx_mcdi_filter_count_rx_used,
.filter_get_rx_id_limit = efx_mcdi_filter_get_rx_id_limit,
.filter_get_rx_ids = efx_mcdi_filter_get_rx_ids,
#ifdef CONFIG_RFS_ACCEL
.filter_rfs_expire_one = efx_mcdi_filter_rfs_expire_one,
#endif
#ifdef CONFIG_SFC_MTD
.mtd_probe = efx_ef10_mtd_probe,
.mtd_rename = efx_mcdi_mtd_rename,
.mtd_read = efx_mcdi_mtd_read,
.mtd_erase = efx_mcdi_mtd_erase,
.mtd_write = efx_mcdi_mtd_write,
.mtd_sync = efx_mcdi_mtd_sync,
#endif
.ptp_write_host_time = efx_ef10_ptp_write_host_time,
.ptp_set_ts_sync_events = efx_ef10_ptp_set_ts_sync_events,
.ptp_set_ts_config = efx_ef10_ptp_set_ts_config,
.vlan_rx_add_vid = efx_ef10_vlan_rx_add_vid,
.vlan_rx_kill_vid = efx_ef10_vlan_rx_kill_vid,
.udp_tnl_push_ports = efx_ef10_udp_tnl_push_ports,
.udp_tnl_has_port = efx_ef10_udp_tnl_has_port,
#ifdef CONFIG_SFC_SRIOV
.sriov_configure = efx_ef10_sriov_configure,
.sriov_init = efx_ef10_sriov_init,
.sriov_fini = efx_ef10_sriov_fini,
.sriov_wanted = efx_ef10_sriov_wanted,
.sriov_set_vf_mac = efx_ef10_sriov_set_vf_mac,
.sriov_set_vf_vlan = efx_ef10_sriov_set_vf_vlan,
.sriov_set_vf_spoofchk = efx_ef10_sriov_set_vf_spoofchk,
.sriov_get_vf_config = efx_ef10_sriov_get_vf_config,
.sriov_set_vf_link_state = efx_ef10_sriov_set_vf_link_state,
.vswitching_probe = efx_ef10_vswitching_probe_pf,
.vswitching_restore = efx_ef10_vswitching_restore_pf,
.vswitching_remove = efx_ef10_vswitching_remove_pf,
#endif
.get_mac_address = efx_ef10_get_mac_address_pf,
.set_mac_address = efx_ef10_set_mac_address,
.tso_versions = efx_ef10_tso_versions,
.get_phys_port_id = efx_ef10_get_phys_port_id,
.revision = EFX_REV_HUNT_A0,
.max_dma_mask = DMA_BIT_MASK(ESF_DZ_TX_KER_BUF_ADDR_WIDTH),
.rx_prefix_size = ES_DZ_RX_PREFIX_SIZE,
.rx_hash_offset = ES_DZ_RX_PREFIX_HASH_OFST,
.rx_ts_offset = ES_DZ_RX_PREFIX_TSTAMP_OFST,
.can_rx_scatter = true,
.always_rx_scatter = true,
.option_descriptors = true,
.min_interrupt_mode = EFX_INT_MODE_LEGACY,
.timer_period_max = 1 << ERF_DD_EVQ_IND_TIMER_VAL_WIDTH,
.offload_features = EF10_OFFLOAD_FEATURES,
.mcdi_max_ver = 2,
.max_rx_ip_filters = EFX_MCDI_FILTER_TBL_ROWS,
.hwtstamp_filters = 1 << HWTSTAMP_FILTER_NONE |
1 << HWTSTAMP_FILTER_ALL,
.rx_hash_key_size = 40,
.check_caps = ef10_check_caps,
.print_additional_fwver = efx_ef10_print_additional_fwver,
.sensor_event = efx_mcdi_sensor_event,
.rx_recycle_ring_size = efx_ef10_recycle_ring_size,
};
|
linux-master
|
drivers/net/ethernet/sfc/ef10.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2005-2006 Fen Systems Ltd.
* Copyright 2006-2013 Solarflare Communications Inc.
*/
#include <linux/netdevice.h>
#include <linux/ethtool.h>
#include <linux/rtnetlink.h>
#include <linux/in.h>
#include "net_driver.h"
#include "workarounds.h"
#include "selftest.h"
#include "efx.h"
#include "efx_channels.h"
#include "rx_common.h"
#include "tx_common.h"
#include "ethtool_common.h"
#include "filter.h"
#include "nic.h"
#define EFX_ETHTOOL_EEPROM_MAGIC 0xEFAB
/**************************************************************************
*
* Ethtool operations
*
**************************************************************************
*/
/* Identify device by flashing LEDs */
static int efx_ethtool_phys_id(struct net_device *net_dev,
enum ethtool_phys_id_state state)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
enum efx_led_mode mode = EFX_LED_DEFAULT;
switch (state) {
case ETHTOOL_ID_ON:
mode = EFX_LED_ON;
break;
case ETHTOOL_ID_OFF:
mode = EFX_LED_OFF;
break;
case ETHTOOL_ID_INACTIVE:
mode = EFX_LED_DEFAULT;
break;
case ETHTOOL_ID_ACTIVE:
return 1; /* cycle on/off once per second */
}
return efx_mcdi_set_id_led(efx, mode);
}
static int efx_ethtool_get_regs_len(struct net_device *net_dev)
{
return efx_nic_get_regs_len(efx_netdev_priv(net_dev));
}
static void efx_ethtool_get_regs(struct net_device *net_dev,
struct ethtool_regs *regs, void *buf)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
regs->version = efx->type->revision;
efx_nic_get_regs(efx, buf);
}
/*
* Each channel has a single IRQ and moderation timer, started by any
* completion (or other event). Unless the module parameter
* separate_tx_channels is set, IRQs and moderation are therefore
* shared between RX and TX completions. In this case, when RX IRQ
* moderation is explicitly changed then TX IRQ moderation is
* automatically changed too, but otherwise we fail if the two values
* are requested to be different.
*
* The hardware does not support a limit on the number of completions
* before an IRQ, so we do not use the max_frames fields. We should
* report and require that max_frames == (usecs != 0), but this would
* invalidate existing user documentation.
*
* The hardware does not have distinct settings for interrupt
* moderation while the previous IRQ is being handled, so we should
* not use the 'irq' fields. However, an earlier developer
* misunderstood the meaning of the 'irq' fields and the driver did
* not support the standard fields. To avoid invalidating existing
* user documentation, we report and accept changes through either the
* standard or 'irq' fields. If both are changed at the same time, we
* prefer the standard field.
*
* We implement adaptive IRQ moderation, but use a different algorithm
* from that assumed in the definition of struct ethtool_coalesce.
* Therefore we do not use any of the adaptive moderation parameters
* in it.
*/
static int efx_ethtool_get_coalesce(struct net_device *net_dev,
struct ethtool_coalesce *coalesce,
struct kernel_ethtool_coalesce *kernel_coal,
struct netlink_ext_ack *extack)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
unsigned int tx_usecs, rx_usecs;
bool rx_adaptive;
efx_get_irq_moderation(efx, &tx_usecs, &rx_usecs, &rx_adaptive);
coalesce->tx_coalesce_usecs = tx_usecs;
coalesce->tx_coalesce_usecs_irq = tx_usecs;
coalesce->rx_coalesce_usecs = rx_usecs;
coalesce->rx_coalesce_usecs_irq = rx_usecs;
coalesce->use_adaptive_rx_coalesce = rx_adaptive;
return 0;
}
static int efx_ethtool_set_coalesce(struct net_device *net_dev,
struct ethtool_coalesce *coalesce,
struct kernel_ethtool_coalesce *kernel_coal,
struct netlink_ext_ack *extack)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
struct efx_channel *channel;
unsigned int tx_usecs, rx_usecs;
bool adaptive, rx_may_override_tx;
int rc;
efx_get_irq_moderation(efx, &tx_usecs, &rx_usecs, &adaptive);
if (coalesce->rx_coalesce_usecs != rx_usecs)
rx_usecs = coalesce->rx_coalesce_usecs;
else
rx_usecs = coalesce->rx_coalesce_usecs_irq;
adaptive = coalesce->use_adaptive_rx_coalesce;
/* If channels are shared, TX IRQ moderation can be quietly
* overridden unless it is changed from its old value.
*/
rx_may_override_tx = (coalesce->tx_coalesce_usecs == tx_usecs &&
coalesce->tx_coalesce_usecs_irq == tx_usecs);
if (coalesce->tx_coalesce_usecs != tx_usecs)
tx_usecs = coalesce->tx_coalesce_usecs;
else
tx_usecs = coalesce->tx_coalesce_usecs_irq;
rc = efx_init_irq_moderation(efx, tx_usecs, rx_usecs, adaptive,
rx_may_override_tx);
if (rc != 0)
return rc;
efx_for_each_channel(channel, efx)
efx->type->push_irq_moderation(channel);
return 0;
}
static void
efx_ethtool_get_ringparam(struct net_device *net_dev,
struct ethtool_ringparam *ring,
struct kernel_ethtool_ringparam *kernel_ring,
struct netlink_ext_ack *extack)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
ring->rx_max_pending = EFX_MAX_DMAQ_SIZE;
ring->tx_max_pending = EFX_TXQ_MAX_ENT(efx);
ring->rx_pending = efx->rxq_entries;
ring->tx_pending = efx->txq_entries;
}
static int
efx_ethtool_set_ringparam(struct net_device *net_dev,
struct ethtool_ringparam *ring,
struct kernel_ethtool_ringparam *kernel_ring,
struct netlink_ext_ack *extack)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
u32 txq_entries;
if (ring->rx_mini_pending || ring->rx_jumbo_pending ||
ring->rx_pending > EFX_MAX_DMAQ_SIZE ||
ring->tx_pending > EFX_TXQ_MAX_ENT(efx))
return -EINVAL;
if (ring->rx_pending < EFX_RXQ_MIN_ENT) {
netif_err(efx, drv, efx->net_dev,
"RX queues cannot be smaller than %u\n",
EFX_RXQ_MIN_ENT);
return -EINVAL;
}
txq_entries = max(ring->tx_pending, EFX_TXQ_MIN_ENT(efx));
if (txq_entries != ring->tx_pending)
netif_warn(efx, drv, efx->net_dev,
"increasing TX queue size to minimum of %u\n",
txq_entries);
return efx_realloc_channels(efx, ring->rx_pending, txq_entries);
}
static void efx_ethtool_get_wol(struct net_device *net_dev,
struct ethtool_wolinfo *wol)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
return efx->type->get_wol(efx, wol);
}
static int efx_ethtool_set_wol(struct net_device *net_dev,
struct ethtool_wolinfo *wol)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
return efx->type->set_wol(efx, wol->wolopts);
}
static void efx_ethtool_get_fec_stats(struct net_device *net_dev,
struct ethtool_fec_stats *fec_stats)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
if (efx->type->get_fec_stats)
efx->type->get_fec_stats(efx, fec_stats);
}
static int efx_ethtool_get_ts_info(struct net_device *net_dev,
struct ethtool_ts_info *ts_info)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
/* Software capabilities */
ts_info->so_timestamping = (SOF_TIMESTAMPING_RX_SOFTWARE |
SOF_TIMESTAMPING_SOFTWARE);
ts_info->phc_index = -1;
efx_ptp_get_ts_info(efx, ts_info);
return 0;
}
const struct ethtool_ops efx_ethtool_ops = {
.supported_coalesce_params = ETHTOOL_COALESCE_USECS |
ETHTOOL_COALESCE_USECS_IRQ |
ETHTOOL_COALESCE_USE_ADAPTIVE_RX,
.get_drvinfo = efx_ethtool_get_drvinfo,
.get_regs_len = efx_ethtool_get_regs_len,
.get_regs = efx_ethtool_get_regs,
.get_msglevel = efx_ethtool_get_msglevel,
.set_msglevel = efx_ethtool_set_msglevel,
.get_link = ethtool_op_get_link,
.get_coalesce = efx_ethtool_get_coalesce,
.set_coalesce = efx_ethtool_set_coalesce,
.get_ringparam = efx_ethtool_get_ringparam,
.set_ringparam = efx_ethtool_set_ringparam,
.get_pauseparam = efx_ethtool_get_pauseparam,
.set_pauseparam = efx_ethtool_set_pauseparam,
.get_sset_count = efx_ethtool_get_sset_count,
.self_test = efx_ethtool_self_test,
.get_strings = efx_ethtool_get_strings,
.set_phys_id = efx_ethtool_phys_id,
.get_ethtool_stats = efx_ethtool_get_stats,
.get_wol = efx_ethtool_get_wol,
.set_wol = efx_ethtool_set_wol,
.reset = efx_ethtool_reset,
.get_rxnfc = efx_ethtool_get_rxnfc,
.set_rxnfc = efx_ethtool_set_rxnfc,
.get_rxfh_indir_size = efx_ethtool_get_rxfh_indir_size,
.get_rxfh_key_size = efx_ethtool_get_rxfh_key_size,
.get_rxfh = efx_ethtool_get_rxfh,
.set_rxfh = efx_ethtool_set_rxfh,
.get_rxfh_context = efx_ethtool_get_rxfh_context,
.set_rxfh_context = efx_ethtool_set_rxfh_context,
.get_ts_info = efx_ethtool_get_ts_info,
.get_module_info = efx_ethtool_get_module_info,
.get_module_eeprom = efx_ethtool_get_module_eeprom,
.get_link_ksettings = efx_ethtool_get_link_ksettings,
.set_link_ksettings = efx_ethtool_set_link_ksettings,
.get_fec_stats = efx_ethtool_get_fec_stats,
.get_fecparam = efx_ethtool_get_fecparam,
.set_fecparam = efx_ethtool_set_fecparam,
};
|
linux-master
|
drivers/net/ethernet/sfc/ethtool.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2019 Solarflare Communications Inc.
* Copyright 2020-2022 Xilinx Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include <net/pkt_cls.h>
#include <net/vxlan.h>
#include <net/geneve.h>
#include <net/tc_act/tc_ct.h>
#include "tc.h"
#include "tc_bindings.h"
#include "tc_encap_actions.h"
#include "tc_conntrack.h"
#include "mae.h"
#include "ef100_rep.h"
#include "efx.h"
enum efx_encap_type efx_tc_indr_netdev_type(struct net_device *net_dev)
{
if (netif_is_vxlan(net_dev))
return EFX_ENCAP_TYPE_VXLAN;
if (netif_is_geneve(net_dev))
return EFX_ENCAP_TYPE_GENEVE;
return EFX_ENCAP_TYPE_NONE;
}
#define EFX_TC_HDR_TYPE_TTL_MASK ((u32)0xff)
/* Hoplimit is stored in the most significant byte in the pedit ipv6 header action */
#define EFX_TC_HDR_TYPE_HLIMIT_MASK ~((u32)0xff000000)
#define EFX_EFV_PF NULL
/* Look up the representor information (efv) for a device.
* May return NULL for the PF (us), or an error pointer for a device that
* isn't supported as a TC offload endpoint
*/
struct efx_rep *efx_tc_flower_lookup_efv(struct efx_nic *efx,
struct net_device *dev)
{
struct efx_rep *efv;
if (!dev)
return ERR_PTR(-EOPNOTSUPP);
/* Is it us (the PF)? */
if (dev == efx->net_dev)
return EFX_EFV_PF;
/* Is it an efx vfrep at all? */
if (dev->netdev_ops != &efx_ef100_rep_netdev_ops)
return ERR_PTR(-EOPNOTSUPP);
/* Is it ours? We don't support TC rules that include another
* EF100's netdevices (not even on another port of the same NIC).
*/
efv = netdev_priv(dev);
if (efv->parent != efx)
return ERR_PTR(-EOPNOTSUPP);
return efv;
}
/* Convert a driver-internal vport ID into an internal device (PF or VF) */
static s64 efx_tc_flower_internal_mport(struct efx_nic *efx, struct efx_rep *efv)
{
u32 mport;
if (IS_ERR(efv))
return PTR_ERR(efv);
if (!efv) /* device is PF (us) */
efx_mae_mport_uplink(efx, &mport);
else /* device is repr */
efx_mae_mport_mport(efx, efv->mport, &mport);
return mport;
}
/* Convert a driver-internal vport ID into an external device (wire or VF) */
s64 efx_tc_flower_external_mport(struct efx_nic *efx, struct efx_rep *efv)
{
u32 mport;
if (IS_ERR(efv))
return PTR_ERR(efv);
if (!efv) /* device is PF (us) */
efx_mae_mport_wire(efx, &mport);
else /* device is repr */
efx_mae_mport_mport(efx, efv->mport, &mport);
return mport;
}
static const struct rhashtable_params efx_tc_mac_ht_params = {
.key_len = offsetofend(struct efx_tc_mac_pedit_action, h_addr),
.key_offset = 0,
.head_offset = offsetof(struct efx_tc_mac_pedit_action, linkage),
};
static const struct rhashtable_params efx_tc_encap_match_ht_params = {
.key_len = offsetof(struct efx_tc_encap_match, linkage),
.key_offset = 0,
.head_offset = offsetof(struct efx_tc_encap_match, linkage),
};
static const struct rhashtable_params efx_tc_match_action_ht_params = {
.key_len = sizeof(unsigned long),
.key_offset = offsetof(struct efx_tc_flow_rule, cookie),
.head_offset = offsetof(struct efx_tc_flow_rule, linkage),
};
static const struct rhashtable_params efx_tc_lhs_rule_ht_params = {
.key_len = sizeof(unsigned long),
.key_offset = offsetof(struct efx_tc_lhs_rule, cookie),
.head_offset = offsetof(struct efx_tc_lhs_rule, linkage),
};
static const struct rhashtable_params efx_tc_recirc_ht_params = {
.key_len = offsetof(struct efx_tc_recirc_id, linkage),
.key_offset = 0,
.head_offset = offsetof(struct efx_tc_recirc_id, linkage),
};
static struct efx_tc_mac_pedit_action *efx_tc_flower_get_mac(struct efx_nic *efx,
unsigned char h_addr[ETH_ALEN],
struct netlink_ext_ack *extack)
{
struct efx_tc_mac_pedit_action *ped, *old;
int rc;
ped = kzalloc(sizeof(*ped), GFP_USER);
if (!ped)
return ERR_PTR(-ENOMEM);
memcpy(ped->h_addr, h_addr, ETH_ALEN);
old = rhashtable_lookup_get_insert_fast(&efx->tc->mac_ht,
&ped->linkage,
efx_tc_mac_ht_params);
if (old) {
/* don't need our new entry */
kfree(ped);
if (IS_ERR(old)) /* oh dear, it's actually an error */
return ERR_CAST(old);
if (!refcount_inc_not_zero(&old->ref))
return ERR_PTR(-EAGAIN);
/* existing entry found, ref taken */
return old;
}
rc = efx_mae_allocate_pedit_mac(efx, ped);
if (rc < 0) {
NL_SET_ERR_MSG_MOD(extack, "Failed to store pedit MAC address in hw");
goto out_remove;
}
/* ref and return */
refcount_set(&ped->ref, 1);
return ped;
out_remove:
rhashtable_remove_fast(&efx->tc->mac_ht, &ped->linkage,
efx_tc_mac_ht_params);
kfree(ped);
return ERR_PTR(rc);
}
static void efx_tc_flower_put_mac(struct efx_nic *efx,
struct efx_tc_mac_pedit_action *ped)
{
if (!refcount_dec_and_test(&ped->ref))
return; /* still in use */
rhashtable_remove_fast(&efx->tc->mac_ht, &ped->linkage,
efx_tc_mac_ht_params);
efx_mae_free_pedit_mac(efx, ped);
kfree(ped);
}
static void efx_tc_free_action_set(struct efx_nic *efx,
struct efx_tc_action_set *act, bool in_hw)
{
/* Failure paths calling this on the 'cursor' action set in_hw=false,
* because if the alloc had succeeded we'd've put it in acts.list and
* not still have it in act.
*/
if (in_hw) {
efx_mae_free_action_set(efx, act->fw_id);
/* in_hw is true iff we are on an acts.list; make sure to
* remove ourselves from that list before we are freed.
*/
list_del(&act->list);
}
if (act->count) {
spin_lock_bh(&act->count->cnt->lock);
if (!list_empty(&act->count_user))
list_del(&act->count_user);
spin_unlock_bh(&act->count->cnt->lock);
efx_tc_flower_put_counter_index(efx, act->count);
}
if (act->encap_md) {
list_del(&act->encap_user);
efx_tc_flower_release_encap_md(efx, act->encap_md);
}
if (act->src_mac)
efx_tc_flower_put_mac(efx, act->src_mac);
if (act->dst_mac)
efx_tc_flower_put_mac(efx, act->dst_mac);
kfree(act);
}
static void efx_tc_free_action_set_list(struct efx_nic *efx,
struct efx_tc_action_set_list *acts,
bool in_hw)
{
struct efx_tc_action_set *act, *next;
/* Failure paths set in_hw=false, because usually the acts didn't get
* to efx_mae_alloc_action_set_list(); if they did, the failure tree
* has a separate efx_mae_free_action_set_list() before calling us.
*/
if (in_hw)
efx_mae_free_action_set_list(efx, acts);
/* Any act that's on the list will be in_hw even if the list isn't */
list_for_each_entry_safe(act, next, &acts->list, list)
efx_tc_free_action_set(efx, act, true);
/* Don't kfree, as acts is embedded inside a struct efx_tc_flow_rule */
}
/* Boilerplate for the simple 'copy a field' cases */
#define _MAP_KEY_AND_MASK(_name, _type, _tcget, _tcfield, _field) \
if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_##_name)) { \
struct flow_match_##_type fm; \
\
flow_rule_match_##_tcget(rule, &fm); \
match->value._field = fm.key->_tcfield; \
match->mask._field = fm.mask->_tcfield; \
}
#define MAP_KEY_AND_MASK(_name, _type, _tcfield, _field) \
_MAP_KEY_AND_MASK(_name, _type, _type, _tcfield, _field)
#define MAP_ENC_KEY_AND_MASK(_name, _type, _tcget, _tcfield, _field) \
_MAP_KEY_AND_MASK(ENC_##_name, _type, _tcget, _tcfield, _field)
static int efx_tc_flower_parse_match(struct efx_nic *efx,
struct flow_rule *rule,
struct efx_tc_match *match,
struct netlink_ext_ack *extack)
{
struct flow_dissector *dissector = rule->match.dissector;
unsigned char ipv = 0;
/* Owing to internal TC infelicities, the IPV6_ADDRS key might be set
* even on IPv4 filters; so rather than relying on dissector->used_keys
* we check the addr_type in the CONTROL key. If we don't find it (or
* it's masked, which should never happen), we treat both IPV4_ADDRS
* and IPV6_ADDRS as absent.
*/
if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_CONTROL)) {
struct flow_match_control fm;
flow_rule_match_control(rule, &fm);
if (IS_ALL_ONES(fm.mask->addr_type))
switch (fm.key->addr_type) {
case FLOW_DISSECTOR_KEY_IPV4_ADDRS:
ipv = 4;
break;
case FLOW_DISSECTOR_KEY_IPV6_ADDRS:
ipv = 6;
break;
default:
break;
}
if (fm.mask->flags & FLOW_DIS_IS_FRAGMENT) {
match->value.ip_frag = fm.key->flags & FLOW_DIS_IS_FRAGMENT;
match->mask.ip_frag = true;
}
if (fm.mask->flags & FLOW_DIS_FIRST_FRAG) {
match->value.ip_firstfrag = fm.key->flags & FLOW_DIS_FIRST_FRAG;
match->mask.ip_firstfrag = true;
}
if (fm.mask->flags & ~(FLOW_DIS_IS_FRAGMENT | FLOW_DIS_FIRST_FRAG)) {
NL_SET_ERR_MSG_FMT_MOD(extack, "Unsupported match on control.flags %#x",
fm.mask->flags);
return -EOPNOTSUPP;
}
}
if (dissector->used_keys &
~(BIT_ULL(FLOW_DISSECTOR_KEY_CONTROL) |
BIT_ULL(FLOW_DISSECTOR_KEY_BASIC) |
BIT_ULL(FLOW_DISSECTOR_KEY_ETH_ADDRS) |
BIT_ULL(FLOW_DISSECTOR_KEY_VLAN) |
BIT_ULL(FLOW_DISSECTOR_KEY_CVLAN) |
BIT_ULL(FLOW_DISSECTOR_KEY_IPV4_ADDRS) |
BIT_ULL(FLOW_DISSECTOR_KEY_IPV6_ADDRS) |
BIT_ULL(FLOW_DISSECTOR_KEY_PORTS) |
BIT_ULL(FLOW_DISSECTOR_KEY_ENC_KEYID) |
BIT_ULL(FLOW_DISSECTOR_KEY_ENC_IPV4_ADDRS) |
BIT_ULL(FLOW_DISSECTOR_KEY_ENC_IPV6_ADDRS) |
BIT_ULL(FLOW_DISSECTOR_KEY_ENC_IP) |
BIT_ULL(FLOW_DISSECTOR_KEY_ENC_PORTS) |
BIT_ULL(FLOW_DISSECTOR_KEY_ENC_CONTROL) |
BIT_ULL(FLOW_DISSECTOR_KEY_CT) |
BIT_ULL(FLOW_DISSECTOR_KEY_TCP) |
BIT_ULL(FLOW_DISSECTOR_KEY_IP))) {
NL_SET_ERR_MSG_FMT_MOD(extack, "Unsupported flower keys %#llx",
dissector->used_keys);
return -EOPNOTSUPP;
}
MAP_KEY_AND_MASK(BASIC, basic, n_proto, eth_proto);
/* Make sure we're IP if any L3/L4 keys used. */
if (!IS_ALL_ONES(match->mask.eth_proto) ||
!(match->value.eth_proto == htons(ETH_P_IP) ||
match->value.eth_proto == htons(ETH_P_IPV6)))
if (dissector->used_keys &
(BIT_ULL(FLOW_DISSECTOR_KEY_IPV4_ADDRS) |
BIT_ULL(FLOW_DISSECTOR_KEY_IPV6_ADDRS) |
BIT_ULL(FLOW_DISSECTOR_KEY_PORTS) |
BIT_ULL(FLOW_DISSECTOR_KEY_IP) |
BIT_ULL(FLOW_DISSECTOR_KEY_TCP))) {
NL_SET_ERR_MSG_FMT_MOD(extack,
"L3/L4 flower keys %#llx require protocol ipv[46]",
dissector->used_keys);
return -EINVAL;
}
if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_VLAN)) {
struct flow_match_vlan fm;
flow_rule_match_vlan(rule, &fm);
if (fm.mask->vlan_id || fm.mask->vlan_priority || fm.mask->vlan_tpid) {
match->value.vlan_proto[0] = fm.key->vlan_tpid;
match->mask.vlan_proto[0] = fm.mask->vlan_tpid;
match->value.vlan_tci[0] = cpu_to_be16(fm.key->vlan_priority << 13 |
fm.key->vlan_id);
match->mask.vlan_tci[0] = cpu_to_be16(fm.mask->vlan_priority << 13 |
fm.mask->vlan_id);
}
}
if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_CVLAN)) {
struct flow_match_vlan fm;
flow_rule_match_cvlan(rule, &fm);
if (fm.mask->vlan_id || fm.mask->vlan_priority || fm.mask->vlan_tpid) {
match->value.vlan_proto[1] = fm.key->vlan_tpid;
match->mask.vlan_proto[1] = fm.mask->vlan_tpid;
match->value.vlan_tci[1] = cpu_to_be16(fm.key->vlan_priority << 13 |
fm.key->vlan_id);
match->mask.vlan_tci[1] = cpu_to_be16(fm.mask->vlan_priority << 13 |
fm.mask->vlan_id);
}
}
if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ETH_ADDRS)) {
struct flow_match_eth_addrs fm;
flow_rule_match_eth_addrs(rule, &fm);
ether_addr_copy(match->value.eth_saddr, fm.key->src);
ether_addr_copy(match->value.eth_daddr, fm.key->dst);
ether_addr_copy(match->mask.eth_saddr, fm.mask->src);
ether_addr_copy(match->mask.eth_daddr, fm.mask->dst);
}
MAP_KEY_AND_MASK(BASIC, basic, ip_proto, ip_proto);
/* Make sure we're TCP/UDP if any L4 keys used. */
if ((match->value.ip_proto != IPPROTO_UDP &&
match->value.ip_proto != IPPROTO_TCP) || !IS_ALL_ONES(match->mask.ip_proto))
if (dissector->used_keys &
(BIT_ULL(FLOW_DISSECTOR_KEY_PORTS) |
BIT_ULL(FLOW_DISSECTOR_KEY_TCP))) {
NL_SET_ERR_MSG_FMT_MOD(extack,
"L4 flower keys %#llx require ipproto udp or tcp",
dissector->used_keys);
return -EINVAL;
}
MAP_KEY_AND_MASK(IP, ip, tos, ip_tos);
MAP_KEY_AND_MASK(IP, ip, ttl, ip_ttl);
if (ipv == 4) {
MAP_KEY_AND_MASK(IPV4_ADDRS, ipv4_addrs, src, src_ip);
MAP_KEY_AND_MASK(IPV4_ADDRS, ipv4_addrs, dst, dst_ip);
}
#ifdef CONFIG_IPV6
else if (ipv == 6) {
MAP_KEY_AND_MASK(IPV6_ADDRS, ipv6_addrs, src, src_ip6);
MAP_KEY_AND_MASK(IPV6_ADDRS, ipv6_addrs, dst, dst_ip6);
}
#endif
MAP_KEY_AND_MASK(PORTS, ports, src, l4_sport);
MAP_KEY_AND_MASK(PORTS, ports, dst, l4_dport);
MAP_KEY_AND_MASK(TCP, tcp, flags, tcp_flags);
if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ENC_CONTROL)) {
struct flow_match_control fm;
flow_rule_match_enc_control(rule, &fm);
if (fm.mask->flags) {
NL_SET_ERR_MSG_FMT_MOD(extack, "Unsupported match on enc_control.flags %#x",
fm.mask->flags);
return -EOPNOTSUPP;
}
if (!IS_ALL_ONES(fm.mask->addr_type)) {
NL_SET_ERR_MSG_FMT_MOD(extack, "Unsupported enc addr_type mask %u (key %u)",
fm.mask->addr_type,
fm.key->addr_type);
return -EOPNOTSUPP;
}
switch (fm.key->addr_type) {
case FLOW_DISSECTOR_KEY_IPV4_ADDRS:
MAP_ENC_KEY_AND_MASK(IPV4_ADDRS, ipv4_addrs, enc_ipv4_addrs,
src, enc_src_ip);
MAP_ENC_KEY_AND_MASK(IPV4_ADDRS, ipv4_addrs, enc_ipv4_addrs,
dst, enc_dst_ip);
break;
#ifdef CONFIG_IPV6
case FLOW_DISSECTOR_KEY_IPV6_ADDRS:
MAP_ENC_KEY_AND_MASK(IPV6_ADDRS, ipv6_addrs, enc_ipv6_addrs,
src, enc_src_ip6);
MAP_ENC_KEY_AND_MASK(IPV6_ADDRS, ipv6_addrs, enc_ipv6_addrs,
dst, enc_dst_ip6);
break;
#endif
default:
NL_SET_ERR_MSG_FMT_MOD(extack,
"Unsupported enc addr_type %u (supported are IPv4, IPv6)",
fm.key->addr_type);
return -EOPNOTSUPP;
}
MAP_ENC_KEY_AND_MASK(IP, ip, enc_ip, tos, enc_ip_tos);
MAP_ENC_KEY_AND_MASK(IP, ip, enc_ip, ttl, enc_ip_ttl);
MAP_ENC_KEY_AND_MASK(PORTS, ports, enc_ports, src, enc_sport);
MAP_ENC_KEY_AND_MASK(PORTS, ports, enc_ports, dst, enc_dport);
MAP_ENC_KEY_AND_MASK(KEYID, enc_keyid, enc_keyid, keyid, enc_keyid);
} else if (dissector->used_keys &
(BIT_ULL(FLOW_DISSECTOR_KEY_ENC_KEYID) |
BIT_ULL(FLOW_DISSECTOR_KEY_ENC_IPV4_ADDRS) |
BIT_ULL(FLOW_DISSECTOR_KEY_ENC_IPV6_ADDRS) |
BIT_ULL(FLOW_DISSECTOR_KEY_ENC_IP) |
BIT_ULL(FLOW_DISSECTOR_KEY_ENC_PORTS))) {
NL_SET_ERR_MSG_FMT_MOD(extack,
"Flower enc keys require enc_control (keys: %#llx)",
dissector->used_keys);
return -EOPNOTSUPP;
}
if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_CT)) {
struct flow_match_ct fm;
flow_rule_match_ct(rule, &fm);
match->value.ct_state_trk = !!(fm.key->ct_state & TCA_FLOWER_KEY_CT_FLAGS_TRACKED);
match->mask.ct_state_trk = !!(fm.mask->ct_state & TCA_FLOWER_KEY_CT_FLAGS_TRACKED);
match->value.ct_state_est = !!(fm.key->ct_state & TCA_FLOWER_KEY_CT_FLAGS_ESTABLISHED);
match->mask.ct_state_est = !!(fm.mask->ct_state & TCA_FLOWER_KEY_CT_FLAGS_ESTABLISHED);
if (fm.mask->ct_state & ~(TCA_FLOWER_KEY_CT_FLAGS_TRACKED |
TCA_FLOWER_KEY_CT_FLAGS_ESTABLISHED)) {
NL_SET_ERR_MSG_FMT_MOD(extack,
"Unsupported ct_state match %#x",
fm.mask->ct_state);
return -EOPNOTSUPP;
}
match->value.ct_mark = fm.key->ct_mark;
match->mask.ct_mark = fm.mask->ct_mark;
match->value.ct_zone = fm.key->ct_zone;
match->mask.ct_zone = fm.mask->ct_zone;
if (memchr_inv(fm.mask->ct_labels, 0, sizeof(fm.mask->ct_labels))) {
NL_SET_ERR_MSG_MOD(extack, "Matching on ct_label not supported");
return -EOPNOTSUPP;
}
}
return 0;
}
static void efx_tc_flower_release_encap_match(struct efx_nic *efx,
struct efx_tc_encap_match *encap)
{
int rc;
if (!refcount_dec_and_test(&encap->ref))
return; /* still in use */
if (encap->type == EFX_TC_EM_DIRECT) {
rc = efx_mae_unregister_encap_match(efx, encap);
if (rc)
/* Display message but carry on and remove entry from our
* SW tables, because there's not much we can do about it.
*/
netif_err(efx, drv, efx->net_dev,
"Failed to release encap match %#x, rc %d\n",
encap->fw_id, rc);
}
rhashtable_remove_fast(&efx->tc->encap_match_ht, &encap->linkage,
efx_tc_encap_match_ht_params);
if (encap->pseudo)
efx_tc_flower_release_encap_match(efx, encap->pseudo);
kfree(encap);
}
static int efx_tc_flower_record_encap_match(struct efx_nic *efx,
struct efx_tc_match *match,
enum efx_encap_type type,
enum efx_tc_em_pseudo_type em_type,
u8 child_ip_tos_mask,
__be16 child_udp_sport_mask,
struct netlink_ext_ack *extack)
{
struct efx_tc_encap_match *encap, *old, *pseudo = NULL;
bool ipv6 = false;
int rc;
/* We require that the socket-defining fields (IP addrs and UDP dest
* port) are present and exact-match. Other fields may only be used
* if the field-set (and any masks) are the same for all encap
* matches on the same <sip,dip,dport> tuple; this is enforced by
* pseudo encap matches.
*/
if (match->mask.enc_dst_ip | match->mask.enc_src_ip) {
if (!IS_ALL_ONES(match->mask.enc_dst_ip)) {
NL_SET_ERR_MSG_MOD(extack,
"Egress encap match is not exact on dst IP address");
return -EOPNOTSUPP;
}
if (!IS_ALL_ONES(match->mask.enc_src_ip)) {
NL_SET_ERR_MSG_MOD(extack,
"Egress encap match is not exact on src IP address");
return -EOPNOTSUPP;
}
#ifdef CONFIG_IPV6
if (!ipv6_addr_any(&match->mask.enc_dst_ip6) ||
!ipv6_addr_any(&match->mask.enc_src_ip6)) {
NL_SET_ERR_MSG_MOD(extack,
"Egress encap match on both IPv4 and IPv6, don't understand");
return -EOPNOTSUPP;
}
} else {
ipv6 = true;
if (!efx_ipv6_addr_all_ones(&match->mask.enc_dst_ip6)) {
NL_SET_ERR_MSG_MOD(extack,
"Egress encap match is not exact on dst IP address");
return -EOPNOTSUPP;
}
if (!efx_ipv6_addr_all_ones(&match->mask.enc_src_ip6)) {
NL_SET_ERR_MSG_MOD(extack,
"Egress encap match is not exact on src IP address");
return -EOPNOTSUPP;
}
#endif
}
if (!IS_ALL_ONES(match->mask.enc_dport)) {
NL_SET_ERR_MSG_MOD(extack, "Egress encap match is not exact on dst UDP port");
return -EOPNOTSUPP;
}
if (match->mask.enc_sport || match->mask.enc_ip_tos) {
struct efx_tc_match pmatch = *match;
if (em_type == EFX_TC_EM_PSEUDO_MASK) { /* can't happen */
NL_SET_ERR_MSG_MOD(extack, "Bad recursion in egress encap match handler");
return -EOPNOTSUPP;
}
pmatch.value.enc_ip_tos = 0;
pmatch.mask.enc_ip_tos = 0;
pmatch.value.enc_sport = 0;
pmatch.mask.enc_sport = 0;
rc = efx_tc_flower_record_encap_match(efx, &pmatch, type,
EFX_TC_EM_PSEUDO_MASK,
match->mask.enc_ip_tos,
match->mask.enc_sport,
extack);
if (rc)
return rc;
pseudo = pmatch.encap;
}
if (match->mask.enc_ip_ttl) {
NL_SET_ERR_MSG_MOD(extack, "Egress encap match on IP TTL not supported");
rc = -EOPNOTSUPP;
goto fail_pseudo;
}
rc = efx_mae_check_encap_match_caps(efx, ipv6, match->mask.enc_ip_tos,
match->mask.enc_sport, extack);
if (rc)
goto fail_pseudo;
encap = kzalloc(sizeof(*encap), GFP_USER);
if (!encap) {
rc = -ENOMEM;
goto fail_pseudo;
}
encap->src_ip = match->value.enc_src_ip;
encap->dst_ip = match->value.enc_dst_ip;
#ifdef CONFIG_IPV6
encap->src_ip6 = match->value.enc_src_ip6;
encap->dst_ip6 = match->value.enc_dst_ip6;
#endif
encap->udp_dport = match->value.enc_dport;
encap->tun_type = type;
encap->ip_tos = match->value.enc_ip_tos;
encap->ip_tos_mask = match->mask.enc_ip_tos;
encap->child_ip_tos_mask = child_ip_tos_mask;
encap->udp_sport = match->value.enc_sport;
encap->udp_sport_mask = match->mask.enc_sport;
encap->child_udp_sport_mask = child_udp_sport_mask;
encap->type = em_type;
encap->pseudo = pseudo;
old = rhashtable_lookup_get_insert_fast(&efx->tc->encap_match_ht,
&encap->linkage,
efx_tc_encap_match_ht_params);
if (old) {
/* don't need our new entry */
kfree(encap);
if (pseudo) /* don't need our new pseudo either */
efx_tc_flower_release_encap_match(efx, pseudo);
if (IS_ERR(old)) /* oh dear, it's actually an error */
return PTR_ERR(old);
/* check old and new em_types are compatible */
switch (old->type) {
case EFX_TC_EM_DIRECT:
/* old EM is in hardware, so mustn't overlap with a
* pseudo, but may be shared with another direct EM
*/
if (em_type == EFX_TC_EM_DIRECT)
break;
NL_SET_ERR_MSG_MOD(extack, "Pseudo encap match conflicts with existing direct entry");
return -EEXIST;
case EFX_TC_EM_PSEUDO_MASK:
/* old EM is protecting a ToS- or src port-qualified
* filter, so may only be shared with another pseudo
* for the same ToS and src port masks.
*/
if (em_type != EFX_TC_EM_PSEUDO_MASK) {
NL_SET_ERR_MSG_FMT_MOD(extack,
"%s encap match conflicts with existing pseudo(MASK) entry",
em_type ? "Pseudo" : "Direct");
return -EEXIST;
}
if (child_ip_tos_mask != old->child_ip_tos_mask) {
NL_SET_ERR_MSG_FMT_MOD(extack,
"Pseudo encap match for TOS mask %#04x conflicts with existing pseudo(MASK) entry for TOS mask %#04x",
child_ip_tos_mask,
old->child_ip_tos_mask);
return -EEXIST;
}
if (child_udp_sport_mask != old->child_udp_sport_mask) {
NL_SET_ERR_MSG_FMT_MOD(extack,
"Pseudo encap match for UDP src port mask %#x conflicts with existing pseudo(MASK) entry for mask %#x",
child_udp_sport_mask,
old->child_udp_sport_mask);
return -EEXIST;
}
break;
default: /* Unrecognised pseudo-type. Just say no */
NL_SET_ERR_MSG_FMT_MOD(extack,
"%s encap match conflicts with existing pseudo(%d) entry",
em_type ? "Pseudo" : "Direct",
old->type);
return -EEXIST;
}
/* check old and new tun_types are compatible */
if (old->tun_type != type) {
NL_SET_ERR_MSG_FMT_MOD(extack,
"Egress encap match with conflicting tun_type %u != %u",
old->tun_type, type);
return -EEXIST;
}
if (!refcount_inc_not_zero(&old->ref))
return -EAGAIN;
/* existing entry found */
encap = old;
} else {
if (em_type == EFX_TC_EM_DIRECT) {
rc = efx_mae_register_encap_match(efx, encap);
if (rc) {
NL_SET_ERR_MSG_MOD(extack, "Failed to record egress encap match in HW");
goto fail;
}
}
refcount_set(&encap->ref, 1);
}
match->encap = encap;
return 0;
fail:
rhashtable_remove_fast(&efx->tc->encap_match_ht, &encap->linkage,
efx_tc_encap_match_ht_params);
kfree(encap);
fail_pseudo:
if (pseudo)
efx_tc_flower_release_encap_match(efx, pseudo);
return rc;
}
static struct efx_tc_recirc_id *efx_tc_get_recirc_id(struct efx_nic *efx,
u32 chain_index,
struct net_device *net_dev)
{
struct efx_tc_recirc_id *rid, *old;
int rc;
rid = kzalloc(sizeof(*rid), GFP_USER);
if (!rid)
return ERR_PTR(-ENOMEM);
rid->chain_index = chain_index;
/* We don't take a reference here, because it's implied - if there's
* a rule on the net_dev that's been offloaded to us, then the net_dev
* can't go away until the rule has been deoffloaded.
*/
rid->net_dev = net_dev;
old = rhashtable_lookup_get_insert_fast(&efx->tc->recirc_ht,
&rid->linkage,
efx_tc_recirc_ht_params);
if (old) {
/* don't need our new entry */
kfree(rid);
if (IS_ERR(old)) /* oh dear, it's actually an error */
return ERR_CAST(old);
if (!refcount_inc_not_zero(&old->ref))
return ERR_PTR(-EAGAIN);
/* existing entry found */
rid = old;
} else {
rc = ida_alloc_range(&efx->tc->recirc_ida, 1, U8_MAX, GFP_USER);
if (rc < 0) {
rhashtable_remove_fast(&efx->tc->recirc_ht,
&rid->linkage,
efx_tc_recirc_ht_params);
kfree(rid);
return ERR_PTR(rc);
}
rid->fw_id = rc;
refcount_set(&rid->ref, 1);
}
return rid;
}
static void efx_tc_put_recirc_id(struct efx_nic *efx, struct efx_tc_recirc_id *rid)
{
if (!refcount_dec_and_test(&rid->ref))
return; /* still in use */
rhashtable_remove_fast(&efx->tc->recirc_ht, &rid->linkage,
efx_tc_recirc_ht_params);
ida_free(&efx->tc->recirc_ida, rid->fw_id);
kfree(rid);
}
static void efx_tc_delete_rule(struct efx_nic *efx, struct efx_tc_flow_rule *rule)
{
efx_mae_delete_rule(efx, rule->fw_id);
/* Release entries in subsidiary tables */
efx_tc_free_action_set_list(efx, &rule->acts, true);
if (rule->match.rid)
efx_tc_put_recirc_id(efx, rule->match.rid);
if (rule->match.encap)
efx_tc_flower_release_encap_match(efx, rule->match.encap);
rule->fw_id = MC_CMD_MAE_ACTION_RULE_INSERT_OUT_ACTION_RULE_ID_NULL;
}
static const char *efx_tc_encap_type_name(enum efx_encap_type typ)
{
switch (typ) {
case EFX_ENCAP_TYPE_NONE:
return "none";
case EFX_ENCAP_TYPE_VXLAN:
return "vxlan";
case EFX_ENCAP_TYPE_GENEVE:
return "geneve";
default:
pr_warn_once("Unknown efx_encap_type %d encountered\n", typ);
return "unknown";
}
}
/* For details of action order constraints refer to SF-123102-TC-1§12.6.1 */
enum efx_tc_action_order {
EFX_TC_AO_DECAP,
EFX_TC_AO_DEC_TTL,
EFX_TC_AO_PEDIT_MAC_ADDRS,
EFX_TC_AO_VLAN_POP,
EFX_TC_AO_VLAN_PUSH,
EFX_TC_AO_COUNT,
EFX_TC_AO_ENCAP,
EFX_TC_AO_DELIVER
};
/* Determine whether we can add @new action without violating order */
static bool efx_tc_flower_action_order_ok(const struct efx_tc_action_set *act,
enum efx_tc_action_order new)
{
switch (new) {
case EFX_TC_AO_DECAP:
if (act->decap)
return false;
/* PEDIT_MAC_ADDRS must not happen before DECAP, though it
* can wait until much later
*/
if (act->dst_mac || act->src_mac)
return false;
/* Decrementing ttl must not happen before DECAP */
if (act->do_ttl_dec)
return false;
fallthrough;
case EFX_TC_AO_VLAN_POP:
if (act->vlan_pop >= 2)
return false;
/* If we've already pushed a VLAN, we can't then pop it;
* the hardware would instead try to pop an existing VLAN
* before pushing the new one.
*/
if (act->vlan_push)
return false;
fallthrough;
case EFX_TC_AO_VLAN_PUSH:
if (act->vlan_push >= 2)
return false;
fallthrough;
case EFX_TC_AO_COUNT:
if (act->count)
return false;
fallthrough;
case EFX_TC_AO_PEDIT_MAC_ADDRS:
case EFX_TC_AO_ENCAP:
if (act->encap_md)
return false;
fallthrough;
case EFX_TC_AO_DELIVER:
return !act->deliver;
case EFX_TC_AO_DEC_TTL:
if (act->encap_md)
return false;
return !act->do_ttl_dec;
default:
/* Bad caller. Whatever they wanted to do, say they can't. */
WARN_ON_ONCE(1);
return false;
}
}
/**
* DOC: TC conntrack sequences
*
* The MAE hardware can handle at most two rounds of action rule matching,
* consequently we support conntrack through the notion of a "left-hand side
* rule". This is a rule which typically contains only the actions "ct" and
* "goto chain N", and corresponds to one or more "right-hand side rules" in
* chain N, which typically match on +trk+est, and may perform ct(nat) actions.
* RHS rules go in the Action Rule table as normal but with a nonzero recirc_id
* (the hardware equivalent of chain_index), while LHS rules may go in either
* the Action Rule or the Outer Rule table, the latter being preferred for
* performance reasons, and set both DO_CT and a recirc_id in their response.
*
* Besides the RHS rules, there are often also similar rules matching on
* +trk+new which perform the ct(commit) action. These are not offloaded.
*/
static bool efx_tc_rule_is_lhs_rule(struct flow_rule *fr,
struct efx_tc_match *match)
{
const struct flow_action_entry *fa;
int i;
flow_action_for_each(i, fa, &fr->action) {
switch (fa->id) {
case FLOW_ACTION_GOTO:
return true;
case FLOW_ACTION_CT:
/* If rule is -trk, or doesn't mention trk at all, then
* a CT action implies a conntrack lookup (hence it's an
* LHS rule). If rule is +trk, then a CT action could
* just be ct(nat) or even ct(commit) (though the latter
* can't be offloaded).
*/
if (!match->mask.ct_state_trk || !match->value.ct_state_trk)
return true;
break;
default:
break;
}
}
return false;
}
static int efx_tc_flower_handle_lhs_actions(struct efx_nic *efx,
struct flow_cls_offload *tc,
struct flow_rule *fr,
struct net_device *net_dev,
struct efx_tc_lhs_rule *rule)
{
struct netlink_ext_ack *extack = tc->common.extack;
struct efx_tc_lhs_action *act = &rule->lhs_act;
const struct flow_action_entry *fa;
bool pipe = true;
int i;
flow_action_for_each(i, fa, &fr->action) {
struct efx_tc_ct_zone *ct_zone;
struct efx_tc_recirc_id *rid;
if (!pipe) {
/* more actions after a non-pipe action */
NL_SET_ERR_MSG_MOD(extack, "Action follows non-pipe action");
return -EINVAL;
}
switch (fa->id) {
case FLOW_ACTION_GOTO:
if (!fa->chain_index) {
NL_SET_ERR_MSG_MOD(extack, "Can't goto chain 0, no looping in hw");
return -EOPNOTSUPP;
}
rid = efx_tc_get_recirc_id(efx, fa->chain_index,
net_dev);
if (IS_ERR(rid)) {
NL_SET_ERR_MSG_MOD(extack, "Failed to allocate a hardware recirculation ID for this chain_index");
return PTR_ERR(rid);
}
act->rid = rid;
if (fa->hw_stats) {
struct efx_tc_counter_index *cnt;
if (!(fa->hw_stats & FLOW_ACTION_HW_STATS_DELAYED)) {
NL_SET_ERR_MSG_FMT_MOD(extack,
"hw_stats_type %u not supported (only 'delayed')",
fa->hw_stats);
return -EOPNOTSUPP;
}
cnt = efx_tc_flower_get_counter_index(efx, tc->cookie,
EFX_TC_COUNTER_TYPE_OR);
if (IS_ERR(cnt)) {
NL_SET_ERR_MSG_MOD(extack, "Failed to obtain a counter");
return PTR_ERR(cnt);
}
WARN_ON(act->count); /* can't happen */
act->count = cnt;
}
pipe = false;
break;
case FLOW_ACTION_CT:
if (act->zone) {
NL_SET_ERR_MSG_MOD(extack, "Can't offload multiple ct actions");
return -EOPNOTSUPP;
}
if (fa->ct.action & (TCA_CT_ACT_COMMIT |
TCA_CT_ACT_FORCE)) {
NL_SET_ERR_MSG_MOD(extack, "Can't offload ct commit/force");
return -EOPNOTSUPP;
}
if (fa->ct.action & TCA_CT_ACT_CLEAR) {
NL_SET_ERR_MSG_MOD(extack, "Can't clear ct in LHS rule");
return -EOPNOTSUPP;
}
if (fa->ct.action & (TCA_CT_ACT_NAT |
TCA_CT_ACT_NAT_SRC |
TCA_CT_ACT_NAT_DST)) {
NL_SET_ERR_MSG_MOD(extack, "Can't perform NAT in LHS rule - packet isn't conntracked yet");
return -EOPNOTSUPP;
}
if (fa->ct.action) {
NL_SET_ERR_MSG_FMT_MOD(extack, "Unhandled ct.action %u for LHS rule\n",
fa->ct.action);
return -EOPNOTSUPP;
}
ct_zone = efx_tc_ct_register_zone(efx, fa->ct.zone,
fa->ct.flow_table);
if (IS_ERR(ct_zone)) {
NL_SET_ERR_MSG_MOD(extack, "Failed to register for CT updates");
return PTR_ERR(ct_zone);
}
act->zone = ct_zone;
break;
default:
NL_SET_ERR_MSG_FMT_MOD(extack, "Unhandled action %u for LHS rule\n",
fa->id);
return -EOPNOTSUPP;
}
}
if (pipe) {
NL_SET_ERR_MSG_MOD(extack, "Missing goto chain in LHS rule");
return -EOPNOTSUPP;
}
return 0;
}
static void efx_tc_flower_release_lhs_actions(struct efx_nic *efx,
struct efx_tc_lhs_action *act)
{
if (act->rid)
efx_tc_put_recirc_id(efx, act->rid);
if (act->zone)
efx_tc_ct_unregister_zone(efx, act->zone);
if (act->count)
efx_tc_flower_put_counter_index(efx, act->count);
}
/**
* struct efx_tc_mangler_state - accumulates 32-bit pedits into fields
*
* @dst_mac_32: dst_mac[0:3] has been populated
* @dst_mac_16: dst_mac[4:5] has been populated
* @src_mac_16: src_mac[0:1] has been populated
* @src_mac_32: src_mac[2:5] has been populated
* @dst_mac: h_dest field of ethhdr
* @src_mac: h_source field of ethhdr
*
* Since FLOW_ACTION_MANGLE comes in 32-bit chunks that do not
* necessarily equate to whole fields of the packet header, this
* structure is used to hold the cumulative effect of the partial
* field pedits that have been processed so far.
*/
struct efx_tc_mangler_state {
u8 dst_mac_32:1; /* eth->h_dest[0:3] */
u8 dst_mac_16:1; /* eth->h_dest[4:5] */
u8 src_mac_16:1; /* eth->h_source[0:1] */
u8 src_mac_32:1; /* eth->h_source[2:5] */
unsigned char dst_mac[ETH_ALEN];
unsigned char src_mac[ETH_ALEN];
};
/** efx_tc_complete_mac_mangle() - pull complete field pedits out of @mung
* @efx: NIC we're installing a flow rule on
* @act: action set (cursor) to update
* @mung: accumulated partial mangles
* @extack: netlink extended ack for reporting errors
*
* Check @mung to find any combinations of partial mangles that can be
* combined into a complete packet field edit, add that edit to @act,
* and consume the partial mangles from @mung.
*/
static int efx_tc_complete_mac_mangle(struct efx_nic *efx,
struct efx_tc_action_set *act,
struct efx_tc_mangler_state *mung,
struct netlink_ext_ack *extack)
{
struct efx_tc_mac_pedit_action *ped;
if (mung->dst_mac_32 && mung->dst_mac_16) {
ped = efx_tc_flower_get_mac(efx, mung->dst_mac, extack);
if (IS_ERR(ped))
return PTR_ERR(ped);
/* Check that we have not already populated dst_mac */
if (act->dst_mac)
efx_tc_flower_put_mac(efx, act->dst_mac);
act->dst_mac = ped;
/* consume the incomplete state */
mung->dst_mac_32 = 0;
mung->dst_mac_16 = 0;
}
if (mung->src_mac_16 && mung->src_mac_32) {
ped = efx_tc_flower_get_mac(efx, mung->src_mac, extack);
if (IS_ERR(ped))
return PTR_ERR(ped);
/* Check that we have not already populated src_mac */
if (act->src_mac)
efx_tc_flower_put_mac(efx, act->src_mac);
act->src_mac = ped;
/* consume the incomplete state */
mung->src_mac_32 = 0;
mung->src_mac_16 = 0;
}
return 0;
}
static int efx_tc_pedit_add(struct efx_nic *efx, struct efx_tc_action_set *act,
const struct flow_action_entry *fa,
struct netlink_ext_ack *extack)
{
switch (fa->mangle.htype) {
case FLOW_ACT_MANGLE_HDR_TYPE_IP4:
switch (fa->mangle.offset) {
case offsetof(struct iphdr, ttl):
/* check that pedit applies to ttl only */
if (fa->mangle.mask != ~EFX_TC_HDR_TYPE_TTL_MASK)
break;
/* Adding 0xff is equivalent to decrementing the ttl.
* Other added values are not supported.
*/
if ((fa->mangle.val & EFX_TC_HDR_TYPE_TTL_MASK) != U8_MAX)
break;
/* check that we do not decrement ttl twice */
if (!efx_tc_flower_action_order_ok(act,
EFX_TC_AO_DEC_TTL)) {
NL_SET_ERR_MSG_MOD(extack, "Unsupported: multiple dec ttl");
return -EOPNOTSUPP;
}
act->do_ttl_dec = 1;
return 0;
default:
break;
}
break;
case FLOW_ACT_MANGLE_HDR_TYPE_IP6:
switch (fa->mangle.offset) {
case round_down(offsetof(struct ipv6hdr, hop_limit), 4):
/* check that pedit applies to hoplimit only */
if (fa->mangle.mask != EFX_TC_HDR_TYPE_HLIMIT_MASK)
break;
/* Adding 0xff is equivalent to decrementing the hoplimit.
* Other added values are not supported.
*/
if ((fa->mangle.val >> 24) != U8_MAX)
break;
/* check that we do not decrement hoplimit twice */
if (!efx_tc_flower_action_order_ok(act,
EFX_TC_AO_DEC_TTL)) {
NL_SET_ERR_MSG_MOD(extack, "Unsupported: multiple dec ttl");
return -EOPNOTSUPP;
}
act->do_ttl_dec = 1;
return 0;
default:
break;
}
break;
default:
break;
}
NL_SET_ERR_MSG_FMT_MOD(extack,
"Unsupported: ttl add action type %x %x %x/%x",
fa->mangle.htype, fa->mangle.offset,
fa->mangle.val, fa->mangle.mask);
return -EOPNOTSUPP;
}
/**
* efx_tc_mangle() - handle a single 32-bit (or less) pedit
* @efx: NIC we're installing a flow rule on
* @act: action set (cursor) to update
* @fa: FLOW_ACTION_MANGLE action metadata
* @mung: accumulator for partial mangles
* @extack: netlink extended ack for reporting errors
* @match: original match used along with the mangle action
*
* Identify the fields written by a FLOW_ACTION_MANGLE, and record
* the partial mangle state in @mung. If this mangle completes an
* earlier partial mangle, consume and apply to @act by calling
* efx_tc_complete_mac_mangle().
*/
static int efx_tc_mangle(struct efx_nic *efx, struct efx_tc_action_set *act,
const struct flow_action_entry *fa,
struct efx_tc_mangler_state *mung,
struct netlink_ext_ack *extack,
struct efx_tc_match *match)
{
__le32 mac32;
__le16 mac16;
u8 tr_ttl;
switch (fa->mangle.htype) {
case FLOW_ACT_MANGLE_HDR_TYPE_ETH:
BUILD_BUG_ON(offsetof(struct ethhdr, h_dest) != 0);
BUILD_BUG_ON(offsetof(struct ethhdr, h_source) != 6);
if (!efx_tc_flower_action_order_ok(act, EFX_TC_AO_PEDIT_MAC_ADDRS)) {
NL_SET_ERR_MSG_MOD(extack,
"Pedit mangle mac action violates action order");
return -EOPNOTSUPP;
}
switch (fa->mangle.offset) {
case 0:
if (fa->mangle.mask) {
NL_SET_ERR_MSG_FMT_MOD(extack,
"Unsupported: mask (%#x) of eth.dst32 mangle",
fa->mangle.mask);
return -EOPNOTSUPP;
}
/* Ethernet address is little-endian */
mac32 = cpu_to_le32(fa->mangle.val);
memcpy(mung->dst_mac, &mac32, sizeof(mac32));
mung->dst_mac_32 = 1;
return efx_tc_complete_mac_mangle(efx, act, mung, extack);
case 4:
if (fa->mangle.mask == 0xffff) {
mac16 = cpu_to_le16(fa->mangle.val >> 16);
memcpy(mung->src_mac, &mac16, sizeof(mac16));
mung->src_mac_16 = 1;
} else if (fa->mangle.mask == 0xffff0000) {
mac16 = cpu_to_le16((u16)fa->mangle.val);
memcpy(mung->dst_mac + 4, &mac16, sizeof(mac16));
mung->dst_mac_16 = 1;
} else {
NL_SET_ERR_MSG_FMT_MOD(extack,
"Unsupported: mask (%#x) of eth+4 mangle is not high or low 16b",
fa->mangle.mask);
return -EOPNOTSUPP;
}
return efx_tc_complete_mac_mangle(efx, act, mung, extack);
case 8:
if (fa->mangle.mask) {
NL_SET_ERR_MSG_FMT_MOD(extack,
"Unsupported: mask (%#x) of eth.src32 mangle",
fa->mangle.mask);
return -EOPNOTSUPP;
}
mac32 = cpu_to_le32(fa->mangle.val);
memcpy(mung->src_mac + 2, &mac32, sizeof(mac32));
mung->src_mac_32 = 1;
return efx_tc_complete_mac_mangle(efx, act, mung, extack);
default:
NL_SET_ERR_MSG_FMT_MOD(extack, "Unsupported: mangle eth+%u %x/%x",
fa->mangle.offset, fa->mangle.val, fa->mangle.mask);
return -EOPNOTSUPP;
}
break;
case FLOW_ACT_MANGLE_HDR_TYPE_IP4:
switch (fa->mangle.offset) {
case offsetof(struct iphdr, ttl):
/* we currently only support pedit IP4 when it applies
* to TTL and then only when it can be achieved with a
* decrement ttl action
*/
/* check that pedit applies to ttl only */
if (fa->mangle.mask != ~EFX_TC_HDR_TYPE_TTL_MASK) {
NL_SET_ERR_MSG_FMT_MOD(extack,
"Unsupported: mask (%#x) out of range, only support mangle action on ipv4.ttl",
fa->mangle.mask);
return -EOPNOTSUPP;
}
/* we can only convert to a dec ttl when we have an
* exact match on the ttl field
*/
if (match->mask.ip_ttl != U8_MAX) {
NL_SET_ERR_MSG_FMT_MOD(extack,
"Unsupported: only support mangle ipv4.ttl when we have an exact match on ttl, mask used for match (%#x)",
match->mask.ip_ttl);
return -EOPNOTSUPP;
}
/* check that we don't try to decrement 0, which equates
* to setting the ttl to 0xff
*/
if (match->value.ip_ttl == 0) {
NL_SET_ERR_MSG_MOD(extack,
"Unsupported: we cannot decrement ttl past 0");
return -EOPNOTSUPP;
}
/* check that we do not decrement ttl twice */
if (!efx_tc_flower_action_order_ok(act,
EFX_TC_AO_DEC_TTL)) {
NL_SET_ERR_MSG_MOD(extack,
"Unsupported: multiple dec ttl");
return -EOPNOTSUPP;
}
/* check pedit can be achieved with decrement action */
tr_ttl = match->value.ip_ttl - 1;
if ((fa->mangle.val & EFX_TC_HDR_TYPE_TTL_MASK) == tr_ttl) {
act->do_ttl_dec = 1;
return 0;
}
fallthrough;
default:
NL_SET_ERR_MSG_FMT_MOD(extack,
"Unsupported: only support mangle on the ttl field (offset is %u)",
fa->mangle.offset);
return -EOPNOTSUPP;
}
break;
case FLOW_ACT_MANGLE_HDR_TYPE_IP6:
switch (fa->mangle.offset) {
case round_down(offsetof(struct ipv6hdr, hop_limit), 4):
/* we currently only support pedit IP6 when it applies
* to the hoplimit and then only when it can be achieved
* with a decrement hoplimit action
*/
/* check that pedit applies to ttl only */
if (fa->mangle.mask != EFX_TC_HDR_TYPE_HLIMIT_MASK) {
NL_SET_ERR_MSG_FMT_MOD(extack,
"Unsupported: mask (%#x) out of range, only support mangle action on ipv6.hop_limit",
fa->mangle.mask);
return -EOPNOTSUPP;
}
/* we can only convert to a dec ttl when we have an
* exact match on the ttl field
*/
if (match->mask.ip_ttl != U8_MAX) {
NL_SET_ERR_MSG_FMT_MOD(extack,
"Unsupported: only support mangle ipv6.hop_limit when we have an exact match on ttl, mask used for match (%#x)",
match->mask.ip_ttl);
return -EOPNOTSUPP;
}
/* check that we don't try to decrement 0, which equates
* to setting the ttl to 0xff
*/
if (match->value.ip_ttl == 0) {
NL_SET_ERR_MSG_MOD(extack,
"Unsupported: we cannot decrement hop_limit past 0");
return -EOPNOTSUPP;
}
/* check that we do not decrement hoplimit twice */
if (!efx_tc_flower_action_order_ok(act,
EFX_TC_AO_DEC_TTL)) {
NL_SET_ERR_MSG_MOD(extack,
"Unsupported: multiple dec ttl");
return -EOPNOTSUPP;
}
/* check pedit can be achieved with decrement action */
tr_ttl = match->value.ip_ttl - 1;
if ((fa->mangle.val >> 24) == tr_ttl) {
act->do_ttl_dec = 1;
return 0;
}
fallthrough;
default:
NL_SET_ERR_MSG_FMT_MOD(extack,
"Unsupported: only support mangle on the hop_limit field");
return -EOPNOTSUPP;
}
default:
NL_SET_ERR_MSG_FMT_MOD(extack, "Unhandled mangle htype %u for action rule",
fa->mangle.htype);
return -EOPNOTSUPP;
}
return 0;
}
/**
* efx_tc_incomplete_mangle() - check for leftover partial pedits
* @mung: accumulator for partial mangles
* @extack: netlink extended ack for reporting errors
*
* Since the MAE can only overwrite whole fields, any partial
* field mangle left over on reaching packet delivery (mirred or
* end of TC actions) cannot be offloaded. Check for any such
* and reject them with -%EOPNOTSUPP.
*/
static int efx_tc_incomplete_mangle(struct efx_tc_mangler_state *mung,
struct netlink_ext_ack *extack)
{
if (mung->dst_mac_32 || mung->dst_mac_16) {
NL_SET_ERR_MSG_MOD(extack, "Incomplete pedit of destination MAC address");
return -EOPNOTSUPP;
}
if (mung->src_mac_16 || mung->src_mac_32) {
NL_SET_ERR_MSG_MOD(extack, "Incomplete pedit of source MAC address");
return -EOPNOTSUPP;
}
return 0;
}
static int efx_tc_flower_replace_foreign(struct efx_nic *efx,
struct net_device *net_dev,
struct flow_cls_offload *tc)
{
struct flow_rule *fr = flow_cls_offload_flow_rule(tc);
struct netlink_ext_ack *extack = tc->common.extack;
struct efx_tc_flow_rule *rule = NULL, *old = NULL;
struct efx_tc_action_set *act = NULL;
bool found = false, uplinked = false;
const struct flow_action_entry *fa;
struct efx_tc_match match;
struct efx_rep *to_efv;
s64 rc;
int i;
/* Parse match */
memset(&match, 0, sizeof(match));
rc = efx_tc_flower_parse_match(efx, fr, &match, NULL);
if (rc)
return rc;
/* The rule as given to us doesn't specify a source netdevice.
* But, determining whether packets from a VF should match it is
* complicated, so leave those to the software slowpath: qualify
* the filter with source m-port == wire.
*/
rc = efx_tc_flower_external_mport(efx, EFX_EFV_PF);
if (rc < 0) {
NL_SET_ERR_MSG_MOD(extack, "Failed to identify ingress m-port for foreign filter");
return rc;
}
match.value.ingress_port = rc;
match.mask.ingress_port = ~0;
if (tc->common.chain_index) {
struct efx_tc_recirc_id *rid;
rid = efx_tc_get_recirc_id(efx, tc->common.chain_index, net_dev);
if (IS_ERR(rid)) {
NL_SET_ERR_MSG_FMT_MOD(extack,
"Failed to allocate a hardware recirculation ID for chain_index %u",
tc->common.chain_index);
return PTR_ERR(rid);
}
match.rid = rid;
match.value.recirc_id = rid->fw_id;
}
match.mask.recirc_id = 0xff;
/* AR table can't match on DO_CT (+trk). But a commonly used pattern is
* +trk+est, which is strictly implied by +est, so rewrite it to that.
*/
if (match.mask.ct_state_trk && match.value.ct_state_trk &&
match.mask.ct_state_est && match.value.ct_state_est)
match.mask.ct_state_trk = 0;
/* Thanks to CT_TCP_FLAGS_INHIBIT, packets with interesting flags could
* match +trk-est (CT_HIT=0) despite being on an established connection.
* So make -est imply -tcp_syn_fin_rst match to ensure these packets
* still hit the software path.
*/
if (match.mask.ct_state_est && !match.value.ct_state_est) {
if (match.value.tcp_syn_fin_rst) {
/* Can't offload this combination */
rc = -EOPNOTSUPP;
goto release;
}
match.mask.tcp_syn_fin_rst = true;
}
flow_action_for_each(i, fa, &fr->action) {
switch (fa->id) {
case FLOW_ACTION_REDIRECT:
case FLOW_ACTION_MIRRED: /* mirred means mirror here */
to_efv = efx_tc_flower_lookup_efv(efx, fa->dev);
if (IS_ERR(to_efv))
continue;
found = true;
break;
default:
break;
}
}
if (!found) { /* We don't care. */
netif_dbg(efx, drv, efx->net_dev,
"Ignoring foreign filter that doesn't egdev us\n");
rc = -EOPNOTSUPP;
goto release;
}
rc = efx_mae_match_check_caps(efx, &match.mask, NULL);
if (rc)
goto release;
if (efx_tc_match_is_encap(&match.mask)) {
enum efx_encap_type type;
type = efx_tc_indr_netdev_type(net_dev);
if (type == EFX_ENCAP_TYPE_NONE) {
NL_SET_ERR_MSG_MOD(extack,
"Egress encap match on unsupported tunnel device");
rc = -EOPNOTSUPP;
goto release;
}
rc = efx_mae_check_encap_type_supported(efx, type);
if (rc) {
NL_SET_ERR_MSG_FMT_MOD(extack,
"Firmware reports no support for %s encap match",
efx_tc_encap_type_name(type));
goto release;
}
rc = efx_tc_flower_record_encap_match(efx, &match, type,
EFX_TC_EM_DIRECT, 0, 0,
extack);
if (rc)
goto release;
} else {
/* This is not a tunnel decap rule, ignore it */
netif_dbg(efx, drv, efx->net_dev,
"Ignoring foreign filter without encap match\n");
rc = -EOPNOTSUPP;
goto release;
}
rule = kzalloc(sizeof(*rule), GFP_USER);
if (!rule) {
rc = -ENOMEM;
goto release;
}
INIT_LIST_HEAD(&rule->acts.list);
rule->cookie = tc->cookie;
old = rhashtable_lookup_get_insert_fast(&efx->tc->match_action_ht,
&rule->linkage,
efx_tc_match_action_ht_params);
if (IS_ERR(old)) {
rc = PTR_ERR(old);
goto release;
} else if (old) {
netif_dbg(efx, drv, efx->net_dev,
"Ignoring already-offloaded rule (cookie %lx)\n",
tc->cookie);
rc = -EEXIST;
goto release;
}
act = kzalloc(sizeof(*act), GFP_USER);
if (!act) {
rc = -ENOMEM;
goto release;
}
/* Parse actions. For foreign rules we only support decap & redirect.
* See corresponding code in efx_tc_flower_replace() for theory of
* operation & how 'act' cursor is used.
*/
flow_action_for_each(i, fa, &fr->action) {
struct efx_tc_action_set save;
switch (fa->id) {
case FLOW_ACTION_REDIRECT:
case FLOW_ACTION_MIRRED:
/* See corresponding code in efx_tc_flower_replace() for
* long explanations of what's going on here.
*/
save = *act;
if (fa->hw_stats) {
struct efx_tc_counter_index *ctr;
if (!(fa->hw_stats & FLOW_ACTION_HW_STATS_DELAYED)) {
NL_SET_ERR_MSG_FMT_MOD(extack,
"hw_stats_type %u not supported (only 'delayed')",
fa->hw_stats);
rc = -EOPNOTSUPP;
goto release;
}
if (!efx_tc_flower_action_order_ok(act, EFX_TC_AO_COUNT)) {
rc = -EOPNOTSUPP;
goto release;
}
ctr = efx_tc_flower_get_counter_index(efx,
tc->cookie,
EFX_TC_COUNTER_TYPE_AR);
if (IS_ERR(ctr)) {
rc = PTR_ERR(ctr);
NL_SET_ERR_MSG_MOD(extack, "Failed to obtain a counter");
goto release;
}
act->count = ctr;
INIT_LIST_HEAD(&act->count_user);
}
if (!efx_tc_flower_action_order_ok(act, EFX_TC_AO_DELIVER)) {
/* can't happen */
rc = -EOPNOTSUPP;
NL_SET_ERR_MSG_MOD(extack,
"Deliver action violates action order (can't happen)");
goto release;
}
to_efv = efx_tc_flower_lookup_efv(efx, fa->dev);
/* PF implies egdev is us, in which case we really
* want to deliver to the uplink (because this is an
* ingress filter). If we don't recognise the egdev
* at all, then we'd better trap so SW can handle it.
*/
if (IS_ERR(to_efv))
to_efv = EFX_EFV_PF;
if (to_efv == EFX_EFV_PF) {
if (uplinked)
break;
uplinked = true;
}
rc = efx_tc_flower_internal_mport(efx, to_efv);
if (rc < 0) {
NL_SET_ERR_MSG_MOD(extack, "Failed to identify egress m-port");
goto release;
}
act->dest_mport = rc;
act->deliver = 1;
rc = efx_mae_alloc_action_set(efx, act);
if (rc) {
NL_SET_ERR_MSG_MOD(extack,
"Failed to write action set to hw (mirred)");
goto release;
}
list_add_tail(&act->list, &rule->acts.list);
act = NULL;
if (fa->id == FLOW_ACTION_REDIRECT)
break; /* end of the line */
/* Mirror, so continue on with saved act */
act = kzalloc(sizeof(*act), GFP_USER);
if (!act) {
rc = -ENOMEM;
goto release;
}
*act = save;
break;
case FLOW_ACTION_TUNNEL_DECAP:
if (!efx_tc_flower_action_order_ok(act, EFX_TC_AO_DECAP)) {
rc = -EINVAL;
NL_SET_ERR_MSG_MOD(extack, "Decap action violates action order");
goto release;
}
act->decap = 1;
/* If we previously delivered/trapped to uplink, now
* that we've decapped we'll want another copy if we
* try to deliver/trap to uplink again.
*/
uplinked = false;
break;
default:
NL_SET_ERR_MSG_FMT_MOD(extack, "Unhandled action %u",
fa->id);
rc = -EOPNOTSUPP;
goto release;
}
}
if (act) {
if (!uplinked) {
/* Not shot/redirected, so deliver to default dest (which is
* the uplink, as this is an ingress filter)
*/
efx_mae_mport_uplink(efx, &act->dest_mport);
act->deliver = 1;
}
rc = efx_mae_alloc_action_set(efx, act);
if (rc) {
NL_SET_ERR_MSG_MOD(extack, "Failed to write action set to hw (deliver)");
goto release;
}
list_add_tail(&act->list, &rule->acts.list);
act = NULL; /* Prevent double-free in error path */
}
rule->match = match;
netif_dbg(efx, drv, efx->net_dev,
"Successfully parsed foreign filter (cookie %lx)\n",
tc->cookie);
rc = efx_mae_alloc_action_set_list(efx, &rule->acts);
if (rc) {
NL_SET_ERR_MSG_MOD(extack, "Failed to write action set list to hw");
goto release;
}
rc = efx_mae_insert_rule(efx, &rule->match, EFX_TC_PRIO_TC,
rule->acts.fw_id, &rule->fw_id);
if (rc) {
NL_SET_ERR_MSG_MOD(extack, "Failed to insert rule in hw");
goto release_acts;
}
return 0;
release_acts:
efx_mae_free_action_set_list(efx, &rule->acts);
release:
/* We failed to insert the rule, so free up any entries we created in
* subsidiary tables.
*/
if (match.rid)
efx_tc_put_recirc_id(efx, match.rid);
if (act)
efx_tc_free_action_set(efx, act, false);
if (rule) {
if (!old)
rhashtable_remove_fast(&efx->tc->match_action_ht,
&rule->linkage,
efx_tc_match_action_ht_params);
efx_tc_free_action_set_list(efx, &rule->acts, false);
}
kfree(rule);
if (match.encap)
efx_tc_flower_release_encap_match(efx, match.encap);
return rc;
}
static int efx_tc_flower_replace_lhs(struct efx_nic *efx,
struct flow_cls_offload *tc,
struct flow_rule *fr,
struct efx_tc_match *match,
struct efx_rep *efv,
struct net_device *net_dev)
{
struct netlink_ext_ack *extack = tc->common.extack;
struct efx_tc_lhs_rule *rule, *old;
int rc;
if (tc->common.chain_index) {
NL_SET_ERR_MSG_MOD(extack, "LHS rule only allowed in chain 0");
return -EOPNOTSUPP;
}
if (match->mask.ct_state_trk && match->value.ct_state_trk) {
NL_SET_ERR_MSG_MOD(extack, "LHS rule can never match +trk");
return -EOPNOTSUPP;
}
/* LHS rules are always -trk, so we don't need to match on that */
match->mask.ct_state_trk = 0;
match->value.ct_state_trk = 0;
rc = efx_mae_match_check_caps_lhs(efx, &match->mask, extack);
if (rc)
return rc;
rule = kzalloc(sizeof(*rule), GFP_USER);
if (!rule)
return -ENOMEM;
rule->cookie = tc->cookie;
old = rhashtable_lookup_get_insert_fast(&efx->tc->lhs_rule_ht,
&rule->linkage,
efx_tc_lhs_rule_ht_params);
if (IS_ERR(old)) {
rc = PTR_ERR(old);
goto release;
} else if (old) {
netif_dbg(efx, drv, efx->net_dev,
"Already offloaded rule (cookie %lx)\n", tc->cookie);
rc = -EEXIST;
NL_SET_ERR_MSG_MOD(extack, "Rule already offloaded");
goto release;
}
/* Parse actions */
/* See note in efx_tc_flower_replace() regarding passed net_dev
* (used for efx_tc_get_recirc_id()).
*/
rc = efx_tc_flower_handle_lhs_actions(efx, tc, fr, efx->net_dev, rule);
if (rc)
goto release;
rule->match = *match;
rc = efx_mae_insert_lhs_rule(efx, rule, EFX_TC_PRIO_TC);
if (rc) {
NL_SET_ERR_MSG_MOD(extack, "Failed to insert rule in hw");
goto release;
}
netif_dbg(efx, drv, efx->net_dev,
"Successfully parsed lhs rule (cookie %lx)\n",
tc->cookie);
return 0;
release:
efx_tc_flower_release_lhs_actions(efx, &rule->lhs_act);
if (!old)
rhashtable_remove_fast(&efx->tc->lhs_rule_ht, &rule->linkage,
efx_tc_lhs_rule_ht_params);
kfree(rule);
return rc;
}
static int efx_tc_flower_replace(struct efx_nic *efx,
struct net_device *net_dev,
struct flow_cls_offload *tc,
struct efx_rep *efv)
{
struct flow_rule *fr = flow_cls_offload_flow_rule(tc);
struct netlink_ext_ack *extack = tc->common.extack;
const struct ip_tunnel_info *encap_info = NULL;
struct efx_tc_flow_rule *rule = NULL, *old;
struct efx_tc_mangler_state mung = {};
struct efx_tc_action_set *act = NULL;
const struct flow_action_entry *fa;
struct efx_rep *from_efv, *to_efv;
struct efx_tc_match match;
u32 acts_id;
s64 rc;
int i;
if (!tc_can_offload_extack(efx->net_dev, extack))
return -EOPNOTSUPP;
if (WARN_ON(!efx->tc))
return -ENETDOWN;
if (WARN_ON(!efx->tc->up))
return -ENETDOWN;
from_efv = efx_tc_flower_lookup_efv(efx, net_dev);
if (IS_ERR(from_efv)) {
/* Not from our PF or representors, so probably a tunnel dev */
return efx_tc_flower_replace_foreign(efx, net_dev, tc);
}
if (efv != from_efv) {
/* can't happen */
NL_SET_ERR_MSG_FMT_MOD(extack, "for %s efv is %snull but from_efv is %snull (can't happen)",
netdev_name(net_dev), efv ? "non-" : "",
from_efv ? "non-" : "");
return -EINVAL;
}
/* Parse match */
memset(&match, 0, sizeof(match));
rc = efx_tc_flower_external_mport(efx, from_efv);
if (rc < 0) {
NL_SET_ERR_MSG_MOD(extack, "Failed to identify ingress m-port");
return rc;
}
match.value.ingress_port = rc;
match.mask.ingress_port = ~0;
rc = efx_tc_flower_parse_match(efx, fr, &match, extack);
if (rc)
return rc;
if (efx_tc_match_is_encap(&match.mask)) {
NL_SET_ERR_MSG_MOD(extack, "Ingress enc_key matches not supported");
return -EOPNOTSUPP;
}
if (efx_tc_rule_is_lhs_rule(fr, &match))
return efx_tc_flower_replace_lhs(efx, tc, fr, &match, efv,
net_dev);
/* chain_index 0 is always recirc_id 0 (and does not appear in recirc_ht).
* Conveniently, match.rid == NULL and match.value.recirc_id == 0 owing
* to the initial memset(), so we don't need to do anything in that case.
*/
if (tc->common.chain_index) {
struct efx_tc_recirc_id *rid;
/* Note regarding passed net_dev:
* VFreps and PF can share chain namespace, as they have
* distinct ingress_mports. So we don't need to burn an
* extra recirc_id if both use the same chain_index.
* (Strictly speaking, we could give each VFrep its own
* recirc_id namespace that doesn't take IDs away from the
* PF, but that would require a bunch of additional IDAs -
* one for each representor - and that's not likely to be
* the main cause of recirc_id exhaustion anyway.)
*/
rid = efx_tc_get_recirc_id(efx, tc->common.chain_index,
efx->net_dev);
if (IS_ERR(rid)) {
NL_SET_ERR_MSG_FMT_MOD(extack,
"Failed to allocate a hardware recirculation ID for chain_index %u",
tc->common.chain_index);
return PTR_ERR(rid);
}
match.rid = rid;
match.value.recirc_id = rid->fw_id;
}
match.mask.recirc_id = 0xff;
/* AR table can't match on DO_CT (+trk). But a commonly used pattern is
* +trk+est, which is strictly implied by +est, so rewrite it to that.
*/
if (match.mask.ct_state_trk && match.value.ct_state_trk &&
match.mask.ct_state_est && match.value.ct_state_est)
match.mask.ct_state_trk = 0;
/* Thanks to CT_TCP_FLAGS_INHIBIT, packets with interesting flags could
* match +trk-est (CT_HIT=0) despite being on an established connection.
* So make -est imply -tcp_syn_fin_rst match to ensure these packets
* still hit the software path.
*/
if (match.mask.ct_state_est && !match.value.ct_state_est) {
if (match.value.tcp_syn_fin_rst) {
/* Can't offload this combination */
rc = -EOPNOTSUPP;
goto release;
}
match.mask.tcp_syn_fin_rst = true;
}
rc = efx_mae_match_check_caps(efx, &match.mask, extack);
if (rc)
goto release;
rule = kzalloc(sizeof(*rule), GFP_USER);
if (!rule) {
rc = -ENOMEM;
goto release;
}
INIT_LIST_HEAD(&rule->acts.list);
rule->cookie = tc->cookie;
old = rhashtable_lookup_get_insert_fast(&efx->tc->match_action_ht,
&rule->linkage,
efx_tc_match_action_ht_params);
if (IS_ERR(old)) {
rc = PTR_ERR(old);
goto release;
} else if (old) {
netif_dbg(efx, drv, efx->net_dev,
"Already offloaded rule (cookie %lx)\n", tc->cookie);
NL_SET_ERR_MSG_MOD(extack, "Rule already offloaded");
rc = -EEXIST;
goto release;
}
/* Parse actions */
act = kzalloc(sizeof(*act), GFP_USER);
if (!act) {
rc = -ENOMEM;
goto release;
}
/**
* DOC: TC action translation
*
* Actions in TC are sequential and cumulative, with delivery actions
* potentially anywhere in the order. The EF100 MAE, however, takes
* an 'action set list' consisting of 'action sets', each of which is
* applied to the _original_ packet, and consists of a set of optional
* actions in a fixed order with delivery at the end.
* To translate between these two models, we maintain a 'cursor', @act,
* which describes the cumulative effect of all the packet-mutating
* actions encountered so far; on handling a delivery (mirred or drop)
* action, once the action-set has been inserted into hardware, we
* append @act to the action-set list (@rule->acts); if this is a pipe
* action (mirred mirror) we then allocate a new @act with a copy of
* the cursor state _before_ the delivery action, otherwise we set @act
* to %NULL.
* This ensures that every allocated action-set is either attached to
* @rule->acts or pointed to by @act (and never both), and that only
* those action-sets in @rule->acts exist in hardware. Consequently,
* in the failure path, @act only needs to be freed in memory, whereas
* for @rule->acts we remove each action-set from hardware before
* freeing it (efx_tc_free_action_set_list()), even if the action-set
* list itself is not in hardware.
*/
flow_action_for_each(i, fa, &fr->action) {
struct efx_tc_action_set save;
u16 tci;
if (!act) {
/* more actions after a non-pipe action */
NL_SET_ERR_MSG_MOD(extack, "Action follows non-pipe action");
rc = -EINVAL;
goto release;
}
if ((fa->id == FLOW_ACTION_REDIRECT ||
fa->id == FLOW_ACTION_MIRRED ||
fa->id == FLOW_ACTION_DROP) && fa->hw_stats) {
struct efx_tc_counter_index *ctr;
/* Currently the only actions that want stats are
* mirred and gact (ok, shot, trap, goto-chain), which
* means we want stats just before delivery. Also,
* note that tunnel_key set shouldn't change the length
* — it's only the subsequent mirred that does that,
* and the stats are taken _before_ the mirred action
* happens.
*/
if (!efx_tc_flower_action_order_ok(act, EFX_TC_AO_COUNT)) {
/* All supported actions that count either steal
* (gact shot, mirred redirect) or clone act
* (mirred mirror), so we should never get two
* count actions on one action_set.
*/
NL_SET_ERR_MSG_MOD(extack, "Count-action conflict (can't happen)");
rc = -EOPNOTSUPP;
goto release;
}
if (!(fa->hw_stats & FLOW_ACTION_HW_STATS_DELAYED)) {
NL_SET_ERR_MSG_FMT_MOD(extack, "hw_stats_type %u not supported (only 'delayed')",
fa->hw_stats);
rc = -EOPNOTSUPP;
goto release;
}
ctr = efx_tc_flower_get_counter_index(efx, tc->cookie,
EFX_TC_COUNTER_TYPE_AR);
if (IS_ERR(ctr)) {
rc = PTR_ERR(ctr);
NL_SET_ERR_MSG_MOD(extack, "Failed to obtain a counter");
goto release;
}
act->count = ctr;
INIT_LIST_HEAD(&act->count_user);
}
switch (fa->id) {
case FLOW_ACTION_DROP:
rc = efx_mae_alloc_action_set(efx, act);
if (rc) {
NL_SET_ERR_MSG_MOD(extack, "Failed to write action set to hw (drop)");
goto release;
}
list_add_tail(&act->list, &rule->acts.list);
act = NULL; /* end of the line */
break;
case FLOW_ACTION_REDIRECT:
case FLOW_ACTION_MIRRED:
save = *act;
if (encap_info) {
struct efx_tc_encap_action *encap;
if (!efx_tc_flower_action_order_ok(act,
EFX_TC_AO_ENCAP)) {
rc = -EOPNOTSUPP;
NL_SET_ERR_MSG_MOD(extack, "Encap action violates action order");
goto release;
}
encap = efx_tc_flower_create_encap_md(
efx, encap_info, fa->dev, extack);
if (IS_ERR_OR_NULL(encap)) {
rc = PTR_ERR(encap);
if (!rc)
rc = -EIO; /* arbitrary */
goto release;
}
act->encap_md = encap;
list_add_tail(&act->encap_user, &encap->users);
act->dest_mport = encap->dest_mport;
act->deliver = 1;
if (act->count && !WARN_ON(!act->count->cnt)) {
/* This counter is used by an encap
* action, which needs a reference back
* so it can prod neighbouring whenever
* traffic is seen.
*/
spin_lock_bh(&act->count->cnt->lock);
list_add_tail(&act->count_user,
&act->count->cnt->users);
spin_unlock_bh(&act->count->cnt->lock);
}
rc = efx_mae_alloc_action_set(efx, act);
if (rc) {
NL_SET_ERR_MSG_MOD(extack, "Failed to write action set to hw (encap)");
goto release;
}
list_add_tail(&act->list, &rule->acts.list);
act->user = &rule->acts;
act = NULL;
if (fa->id == FLOW_ACTION_REDIRECT)
break; /* end of the line */
/* Mirror, so continue on with saved act */
save.count = NULL;
act = kzalloc(sizeof(*act), GFP_USER);
if (!act) {
rc = -ENOMEM;
goto release;
}
*act = save;
break;
}
if (!efx_tc_flower_action_order_ok(act, EFX_TC_AO_DELIVER)) {
/* can't happen */
rc = -EOPNOTSUPP;
NL_SET_ERR_MSG_MOD(extack, "Deliver action violates action order (can't happen)");
goto release;
}
to_efv = efx_tc_flower_lookup_efv(efx, fa->dev);
if (IS_ERR(to_efv)) {
NL_SET_ERR_MSG_MOD(extack, "Mirred egress device not on switch");
rc = PTR_ERR(to_efv);
goto release;
}
rc = efx_tc_flower_external_mport(efx, to_efv);
if (rc < 0) {
NL_SET_ERR_MSG_MOD(extack, "Failed to identify egress m-port");
goto release;
}
act->dest_mport = rc;
act->deliver = 1;
rc = efx_mae_alloc_action_set(efx, act);
if (rc) {
NL_SET_ERR_MSG_MOD(extack, "Failed to write action set to hw (mirred)");
goto release;
}
list_add_tail(&act->list, &rule->acts.list);
act = NULL;
if (fa->id == FLOW_ACTION_REDIRECT)
break; /* end of the line */
/* Mirror, so continue on with saved act */
save.count = NULL;
act = kzalloc(sizeof(*act), GFP_USER);
if (!act) {
rc = -ENOMEM;
goto release;
}
*act = save;
break;
case FLOW_ACTION_VLAN_POP:
if (act->vlan_push) {
act->vlan_push--;
} else if (efx_tc_flower_action_order_ok(act, EFX_TC_AO_VLAN_POP)) {
act->vlan_pop++;
} else {
NL_SET_ERR_MSG_MOD(extack,
"More than two VLAN pops, or action order violated");
rc = -EINVAL;
goto release;
}
break;
case FLOW_ACTION_VLAN_PUSH:
if (!efx_tc_flower_action_order_ok(act, EFX_TC_AO_VLAN_PUSH)) {
rc = -EINVAL;
NL_SET_ERR_MSG_MOD(extack,
"More than two VLAN pushes, or action order violated");
goto release;
}
tci = fa->vlan.vid & VLAN_VID_MASK;
tci |= fa->vlan.prio << VLAN_PRIO_SHIFT;
act->vlan_tci[act->vlan_push] = cpu_to_be16(tci);
act->vlan_proto[act->vlan_push] = fa->vlan.proto;
act->vlan_push++;
break;
case FLOW_ACTION_ADD:
rc = efx_tc_pedit_add(efx, act, fa, extack);
if (rc < 0)
goto release;
break;
case FLOW_ACTION_MANGLE:
rc = efx_tc_mangle(efx, act, fa, &mung, extack, &match);
if (rc < 0)
goto release;
break;
case FLOW_ACTION_TUNNEL_ENCAP:
if (encap_info) {
/* Can't specify encap multiple times.
* If you want to overwrite an existing
* encap_info, use an intervening
* FLOW_ACTION_TUNNEL_DECAP to clear it.
*/
NL_SET_ERR_MSG_MOD(extack, "Tunnel key set when already set");
rc = -EINVAL;
goto release;
}
if (!fa->tunnel) {
NL_SET_ERR_MSG_MOD(extack, "Tunnel key set is missing key");
rc = -EOPNOTSUPP;
goto release;
}
encap_info = fa->tunnel;
break;
case FLOW_ACTION_TUNNEL_DECAP:
if (encap_info) {
encap_info = NULL;
break;
}
/* Since we don't support enc_key matches on ingress
* (and if we did there'd be no tunnel-device to give
* us a type), we can't offload a decap that's not
* just undoing a previous encap action.
*/
NL_SET_ERR_MSG_MOD(extack, "Cannot offload tunnel decap action without tunnel device");
rc = -EOPNOTSUPP;
goto release;
default:
NL_SET_ERR_MSG_FMT_MOD(extack, "Unhandled action %u",
fa->id);
rc = -EOPNOTSUPP;
goto release;
}
}
rc = efx_tc_incomplete_mangle(&mung, extack);
if (rc < 0)
goto release;
if (act) {
/* Not shot/redirected, so deliver to default dest */
if (from_efv == EFX_EFV_PF)
/* Rule applies to traffic from the wire,
* and default dest is thus the PF
*/
efx_mae_mport_uplink(efx, &act->dest_mport);
else
/* Representor, so rule applies to traffic from
* representee, and default dest is thus the rep.
* All reps use the same mport for delivery
*/
efx_mae_mport_mport(efx, efx->tc->reps_mport_id,
&act->dest_mport);
act->deliver = 1;
rc = efx_mae_alloc_action_set(efx, act);
if (rc) {
NL_SET_ERR_MSG_MOD(extack, "Failed to write action set to hw (deliver)");
goto release;
}
list_add_tail(&act->list, &rule->acts.list);
act = NULL; /* Prevent double-free in error path */
}
netif_dbg(efx, drv, efx->net_dev,
"Successfully parsed filter (cookie %lx)\n",
tc->cookie);
rule->match = match;
rc = efx_mae_alloc_action_set_list(efx, &rule->acts);
if (rc) {
NL_SET_ERR_MSG_MOD(extack, "Failed to write action set list to hw");
goto release;
}
if (from_efv == EFX_EFV_PF)
/* PF netdev, so rule applies to traffic from wire */
rule->fallback = &efx->tc->facts.pf;
else
/* repdev, so rule applies to traffic from representee */
rule->fallback = &efx->tc->facts.reps;
if (!efx_tc_check_ready(efx, rule)) {
netif_dbg(efx, drv, efx->net_dev, "action not ready for hw\n");
acts_id = rule->fallback->fw_id;
} else {
netif_dbg(efx, drv, efx->net_dev, "ready for hw\n");
acts_id = rule->acts.fw_id;
}
rc = efx_mae_insert_rule(efx, &rule->match, EFX_TC_PRIO_TC,
acts_id, &rule->fw_id);
if (rc) {
NL_SET_ERR_MSG_MOD(extack, "Failed to insert rule in hw");
goto release_acts;
}
return 0;
release_acts:
efx_mae_free_action_set_list(efx, &rule->acts);
release:
/* We failed to insert the rule, so free up any entries we created in
* subsidiary tables.
*/
if (match.rid)
efx_tc_put_recirc_id(efx, match.rid);
if (act)
efx_tc_free_action_set(efx, act, false);
if (rule) {
if (!old)
rhashtable_remove_fast(&efx->tc->match_action_ht,
&rule->linkage,
efx_tc_match_action_ht_params);
efx_tc_free_action_set_list(efx, &rule->acts, false);
}
kfree(rule);
return rc;
}
static int efx_tc_flower_destroy(struct efx_nic *efx,
struct net_device *net_dev,
struct flow_cls_offload *tc)
{
struct netlink_ext_ack *extack = tc->common.extack;
struct efx_tc_lhs_rule *lhs_rule;
struct efx_tc_flow_rule *rule;
lhs_rule = rhashtable_lookup_fast(&efx->tc->lhs_rule_ht, &tc->cookie,
efx_tc_lhs_rule_ht_params);
if (lhs_rule) {
/* Remove it from HW */
efx_mae_remove_lhs_rule(efx, lhs_rule);
/* Delete it from SW */
efx_tc_flower_release_lhs_actions(efx, &lhs_rule->lhs_act);
rhashtable_remove_fast(&efx->tc->lhs_rule_ht, &lhs_rule->linkage,
efx_tc_lhs_rule_ht_params);
if (lhs_rule->match.encap)
efx_tc_flower_release_encap_match(efx, lhs_rule->match.encap);
netif_dbg(efx, drv, efx->net_dev, "Removed (lhs) filter %lx\n",
lhs_rule->cookie);
kfree(lhs_rule);
return 0;
}
rule = rhashtable_lookup_fast(&efx->tc->match_action_ht, &tc->cookie,
efx_tc_match_action_ht_params);
if (!rule) {
/* Only log a message if we're the ingress device. Otherwise
* it's a foreign filter and we might just not have been
* interested (e.g. we might not have been the egress device
* either).
*/
if (!IS_ERR(efx_tc_flower_lookup_efv(efx, net_dev)))
netif_warn(efx, drv, efx->net_dev,
"Filter %lx not found to remove\n", tc->cookie);
NL_SET_ERR_MSG_MOD(extack, "Flow cookie not found in offloaded rules");
return -ENOENT;
}
/* Remove it from HW */
efx_tc_delete_rule(efx, rule);
/* Delete it from SW */
rhashtable_remove_fast(&efx->tc->match_action_ht, &rule->linkage,
efx_tc_match_action_ht_params);
netif_dbg(efx, drv, efx->net_dev, "Removed filter %lx\n", rule->cookie);
kfree(rule);
return 0;
}
static int efx_tc_flower_stats(struct efx_nic *efx, struct net_device *net_dev,
struct flow_cls_offload *tc)
{
struct netlink_ext_ack *extack = tc->common.extack;
struct efx_tc_counter_index *ctr;
struct efx_tc_counter *cnt;
u64 packets, bytes;
ctr = efx_tc_flower_find_counter_index(efx, tc->cookie);
if (!ctr) {
/* See comment in efx_tc_flower_destroy() */
if (!IS_ERR(efx_tc_flower_lookup_efv(efx, net_dev)))
if (net_ratelimit())
netif_warn(efx, drv, efx->net_dev,
"Filter %lx not found for stats\n",
tc->cookie);
NL_SET_ERR_MSG_MOD(extack, "Flow cookie not found in offloaded rules");
return -ENOENT;
}
if (WARN_ON(!ctr->cnt)) /* can't happen */
return -EIO;
cnt = ctr->cnt;
spin_lock_bh(&cnt->lock);
/* Report only new pkts/bytes since last time TC asked */
packets = cnt->packets;
bytes = cnt->bytes;
flow_stats_update(&tc->stats, bytes - cnt->old_bytes,
packets - cnt->old_packets, 0, cnt->touched,
FLOW_ACTION_HW_STATS_DELAYED);
cnt->old_packets = packets;
cnt->old_bytes = bytes;
spin_unlock_bh(&cnt->lock);
return 0;
}
int efx_tc_flower(struct efx_nic *efx, struct net_device *net_dev,
struct flow_cls_offload *tc, struct efx_rep *efv)
{
int rc;
if (!efx->tc)
return -EOPNOTSUPP;
mutex_lock(&efx->tc->mutex);
switch (tc->command) {
case FLOW_CLS_REPLACE:
rc = efx_tc_flower_replace(efx, net_dev, tc, efv);
break;
case FLOW_CLS_DESTROY:
rc = efx_tc_flower_destroy(efx, net_dev, tc);
break;
case FLOW_CLS_STATS:
rc = efx_tc_flower_stats(efx, net_dev, tc);
break;
default:
rc = -EOPNOTSUPP;
break;
}
mutex_unlock(&efx->tc->mutex);
return rc;
}
static int efx_tc_configure_default_rule(struct efx_nic *efx, u32 ing_port,
u32 eg_port, struct efx_tc_flow_rule *rule)
{
struct efx_tc_action_set_list *acts = &rule->acts;
struct efx_tc_match *match = &rule->match;
struct efx_tc_action_set *act;
int rc;
match->value.ingress_port = ing_port;
match->mask.ingress_port = ~0;
act = kzalloc(sizeof(*act), GFP_KERNEL);
if (!act)
return -ENOMEM;
act->deliver = 1;
act->dest_mport = eg_port;
rc = efx_mae_alloc_action_set(efx, act);
if (rc)
goto fail1;
EFX_WARN_ON_PARANOID(!list_empty(&acts->list));
list_add_tail(&act->list, &acts->list);
rc = efx_mae_alloc_action_set_list(efx, acts);
if (rc)
goto fail2;
rc = efx_mae_insert_rule(efx, match, EFX_TC_PRIO_DFLT,
acts->fw_id, &rule->fw_id);
if (rc)
goto fail3;
return 0;
fail3:
efx_mae_free_action_set_list(efx, acts);
fail2:
list_del(&act->list);
efx_mae_free_action_set(efx, act->fw_id);
fail1:
kfree(act);
return rc;
}
static int efx_tc_configure_default_rule_pf(struct efx_nic *efx)
{
struct efx_tc_flow_rule *rule = &efx->tc->dflt.pf;
u32 ing_port, eg_port;
efx_mae_mport_uplink(efx, &ing_port);
efx_mae_mport_wire(efx, &eg_port);
return efx_tc_configure_default_rule(efx, ing_port, eg_port, rule);
}
static int efx_tc_configure_default_rule_wire(struct efx_nic *efx)
{
struct efx_tc_flow_rule *rule = &efx->tc->dflt.wire;
u32 ing_port, eg_port;
efx_mae_mport_wire(efx, &ing_port);
efx_mae_mport_uplink(efx, &eg_port);
return efx_tc_configure_default_rule(efx, ing_port, eg_port, rule);
}
int efx_tc_configure_default_rule_rep(struct efx_rep *efv)
{
struct efx_tc_flow_rule *rule = &efv->dflt;
struct efx_nic *efx = efv->parent;
u32 ing_port, eg_port;
efx_mae_mport_mport(efx, efv->mport, &ing_port);
efx_mae_mport_mport(efx, efx->tc->reps_mport_id, &eg_port);
return efx_tc_configure_default_rule(efx, ing_port, eg_port, rule);
}
void efx_tc_deconfigure_default_rule(struct efx_nic *efx,
struct efx_tc_flow_rule *rule)
{
if (rule->fw_id != MC_CMD_MAE_ACTION_RULE_INSERT_OUT_ACTION_RULE_ID_NULL)
efx_tc_delete_rule(efx, rule);
rule->fw_id = MC_CMD_MAE_ACTION_RULE_INSERT_OUT_ACTION_RULE_ID_NULL;
}
static int efx_tc_configure_fallback_acts(struct efx_nic *efx, u32 eg_port,
struct efx_tc_action_set_list *acts)
{
struct efx_tc_action_set *act;
int rc;
act = kzalloc(sizeof(*act), GFP_KERNEL);
if (!act)
return -ENOMEM;
act->deliver = 1;
act->dest_mport = eg_port;
rc = efx_mae_alloc_action_set(efx, act);
if (rc)
goto fail1;
EFX_WARN_ON_PARANOID(!list_empty(&acts->list));
list_add_tail(&act->list, &acts->list);
rc = efx_mae_alloc_action_set_list(efx, acts);
if (rc)
goto fail2;
return 0;
fail2:
list_del(&act->list);
efx_mae_free_action_set(efx, act->fw_id);
fail1:
kfree(act);
return rc;
}
static int efx_tc_configure_fallback_acts_pf(struct efx_nic *efx)
{
struct efx_tc_action_set_list *acts = &efx->tc->facts.pf;
u32 eg_port;
efx_mae_mport_uplink(efx, &eg_port);
return efx_tc_configure_fallback_acts(efx, eg_port, acts);
}
static int efx_tc_configure_fallback_acts_reps(struct efx_nic *efx)
{
struct efx_tc_action_set_list *acts = &efx->tc->facts.reps;
u32 eg_port;
efx_mae_mport_mport(efx, efx->tc->reps_mport_id, &eg_port);
return efx_tc_configure_fallback_acts(efx, eg_port, acts);
}
static void efx_tc_deconfigure_fallback_acts(struct efx_nic *efx,
struct efx_tc_action_set_list *acts)
{
efx_tc_free_action_set_list(efx, acts, true);
}
static int efx_tc_configure_rep_mport(struct efx_nic *efx)
{
u32 rep_mport_label;
int rc;
rc = efx_mae_allocate_mport(efx, &efx->tc->reps_mport_id, &rep_mport_label);
if (rc)
return rc;
pci_dbg(efx->pci_dev, "created rep mport 0x%08x (0x%04x)\n",
efx->tc->reps_mport_id, rep_mport_label);
/* Use mport *selector* as vport ID */
efx_mae_mport_mport(efx, efx->tc->reps_mport_id,
&efx->tc->reps_mport_vport_id);
return 0;
}
static void efx_tc_deconfigure_rep_mport(struct efx_nic *efx)
{
efx_mae_free_mport(efx, efx->tc->reps_mport_id);
efx->tc->reps_mport_id = MAE_MPORT_SELECTOR_NULL;
}
int efx_tc_insert_rep_filters(struct efx_nic *efx)
{
struct efx_filter_spec promisc, allmulti;
int rc;
if (efx->type->is_vf)
return 0;
if (!efx->tc)
return 0;
efx_filter_init_rx(&promisc, EFX_FILTER_PRI_REQUIRED, 0, 0);
efx_filter_set_uc_def(&promisc);
efx_filter_set_vport_id(&promisc, efx->tc->reps_mport_vport_id);
rc = efx_filter_insert_filter(efx, &promisc, false);
if (rc < 0)
return rc;
efx->tc->reps_filter_uc = rc;
efx_filter_init_rx(&allmulti, EFX_FILTER_PRI_REQUIRED, 0, 0);
efx_filter_set_mc_def(&allmulti);
efx_filter_set_vport_id(&allmulti, efx->tc->reps_mport_vport_id);
rc = efx_filter_insert_filter(efx, &allmulti, false);
if (rc < 0)
return rc;
efx->tc->reps_filter_mc = rc;
return 0;
}
void efx_tc_remove_rep_filters(struct efx_nic *efx)
{
if (efx->type->is_vf)
return;
if (!efx->tc)
return;
if (efx->tc->reps_filter_mc >= 0)
efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED, efx->tc->reps_filter_mc);
efx->tc->reps_filter_mc = -1;
if (efx->tc->reps_filter_uc >= 0)
efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED, efx->tc->reps_filter_uc);
efx->tc->reps_filter_uc = -1;
}
int efx_init_tc(struct efx_nic *efx)
{
int rc;
rc = efx_mae_get_caps(efx, efx->tc->caps);
if (rc)
return rc;
if (efx->tc->caps->match_field_count > MAE_NUM_FIELDS)
/* Firmware supports some match fields the driver doesn't know
* about. Not fatal, unless any of those fields are required
* (MAE_FIELD_SUPPORTED_MATCH_ALWAYS) but if so we don't know.
*/
netif_warn(efx, probe, efx->net_dev,
"FW reports additional match fields %u\n",
efx->tc->caps->match_field_count);
if (efx->tc->caps->action_prios < EFX_TC_PRIO__NUM) {
netif_err(efx, probe, efx->net_dev,
"Too few action prios supported (have %u, need %u)\n",
efx->tc->caps->action_prios, EFX_TC_PRIO__NUM);
return -EIO;
}
rc = efx_tc_configure_default_rule_pf(efx);
if (rc)
return rc;
rc = efx_tc_configure_default_rule_wire(efx);
if (rc)
return rc;
rc = efx_tc_configure_rep_mport(efx);
if (rc)
return rc;
rc = efx_tc_configure_fallback_acts_pf(efx);
if (rc)
return rc;
rc = efx_tc_configure_fallback_acts_reps(efx);
if (rc)
return rc;
rc = efx_mae_get_tables(efx);
if (rc)
return rc;
rc = flow_indr_dev_register(efx_tc_indr_setup_cb, efx);
if (rc)
goto out_free;
efx->tc->up = true;
return 0;
out_free:
efx_mae_free_tables(efx);
return rc;
}
void efx_fini_tc(struct efx_nic *efx)
{
/* We can get called even if efx_init_struct_tc() failed */
if (!efx->tc)
return;
if (efx->tc->up)
flow_indr_dev_unregister(efx_tc_indr_setup_cb, efx, efx_tc_block_unbind);
efx_tc_deconfigure_rep_mport(efx);
efx_tc_deconfigure_default_rule(efx, &efx->tc->dflt.pf);
efx_tc_deconfigure_default_rule(efx, &efx->tc->dflt.wire);
efx_tc_deconfigure_fallback_acts(efx, &efx->tc->facts.pf);
efx_tc_deconfigure_fallback_acts(efx, &efx->tc->facts.reps);
efx->tc->up = false;
efx_mae_free_tables(efx);
}
/* At teardown time, all TC filter rules (and thus all resources they created)
* should already have been removed. If we find any in our hashtables, make a
* cursory attempt to clean up the software side.
*/
static void efx_tc_encap_match_free(void *ptr, void *__unused)
{
struct efx_tc_encap_match *encap = ptr;
WARN_ON(refcount_read(&encap->ref));
kfree(encap);
}
static void efx_tc_recirc_free(void *ptr, void *arg)
{
struct efx_tc_recirc_id *rid = ptr;
struct efx_nic *efx = arg;
WARN_ON(refcount_read(&rid->ref));
ida_free(&efx->tc->recirc_ida, rid->fw_id);
kfree(rid);
}
static void efx_tc_lhs_free(void *ptr, void *arg)
{
struct efx_tc_lhs_rule *rule = ptr;
struct efx_nic *efx = arg;
netif_err(efx, drv, efx->net_dev,
"tc lhs_rule %lx still present at teardown, removing\n",
rule->cookie);
if (rule->lhs_act.zone)
efx_tc_ct_unregister_zone(efx, rule->lhs_act.zone);
if (rule->lhs_act.count)
efx_tc_flower_put_counter_index(efx, rule->lhs_act.count);
efx_mae_remove_lhs_rule(efx, rule);
kfree(rule);
}
static void efx_tc_mac_free(void *ptr, void *__unused)
{
struct efx_tc_mac_pedit_action *ped = ptr;
WARN_ON(refcount_read(&ped->ref));
kfree(ped);
}
static void efx_tc_flow_free(void *ptr, void *arg)
{
struct efx_tc_flow_rule *rule = ptr;
struct efx_nic *efx = arg;
netif_err(efx, drv, efx->net_dev,
"tc rule %lx still present at teardown, removing\n",
rule->cookie);
/* Also releases entries in subsidiary tables */
efx_tc_delete_rule(efx, rule);
kfree(rule);
}
int efx_init_struct_tc(struct efx_nic *efx)
{
int rc;
if (efx->type->is_vf)
return 0;
efx->tc = kzalloc(sizeof(*efx->tc), GFP_KERNEL);
if (!efx->tc)
return -ENOMEM;
efx->tc->caps = kzalloc(sizeof(struct mae_caps), GFP_KERNEL);
if (!efx->tc->caps) {
rc = -ENOMEM;
goto fail_alloc_caps;
}
INIT_LIST_HEAD(&efx->tc->block_list);
mutex_init(&efx->tc->mutex);
init_waitqueue_head(&efx->tc->flush_wq);
rc = efx_tc_init_encap_actions(efx);
if (rc < 0)
goto fail_encap_actions;
rc = efx_tc_init_counters(efx);
if (rc < 0)
goto fail_counters;
rc = rhashtable_init(&efx->tc->mac_ht, &efx_tc_mac_ht_params);
if (rc < 0)
goto fail_mac_ht;
rc = rhashtable_init(&efx->tc->encap_match_ht, &efx_tc_encap_match_ht_params);
if (rc < 0)
goto fail_encap_match_ht;
rc = rhashtable_init(&efx->tc->match_action_ht, &efx_tc_match_action_ht_params);
if (rc < 0)
goto fail_match_action_ht;
rc = rhashtable_init(&efx->tc->lhs_rule_ht, &efx_tc_lhs_rule_ht_params);
if (rc < 0)
goto fail_lhs_rule_ht;
rc = efx_tc_init_conntrack(efx);
if (rc < 0)
goto fail_conntrack;
rc = rhashtable_init(&efx->tc->recirc_ht, &efx_tc_recirc_ht_params);
if (rc < 0)
goto fail_recirc_ht;
ida_init(&efx->tc->recirc_ida);
efx->tc->reps_filter_uc = -1;
efx->tc->reps_filter_mc = -1;
INIT_LIST_HEAD(&efx->tc->dflt.pf.acts.list);
efx->tc->dflt.pf.fw_id = MC_CMD_MAE_ACTION_RULE_INSERT_OUT_ACTION_RULE_ID_NULL;
INIT_LIST_HEAD(&efx->tc->dflt.wire.acts.list);
efx->tc->dflt.wire.fw_id = MC_CMD_MAE_ACTION_RULE_INSERT_OUT_ACTION_RULE_ID_NULL;
INIT_LIST_HEAD(&efx->tc->facts.pf.list);
efx->tc->facts.pf.fw_id = MC_CMD_MAE_ACTION_SET_ALLOC_OUT_ACTION_SET_ID_NULL;
INIT_LIST_HEAD(&efx->tc->facts.reps.list);
efx->tc->facts.reps.fw_id = MC_CMD_MAE_ACTION_SET_ALLOC_OUT_ACTION_SET_ID_NULL;
efx->extra_channel_type[EFX_EXTRA_CHANNEL_TC] = &efx_tc_channel_type;
return 0;
fail_recirc_ht:
efx_tc_destroy_conntrack(efx);
fail_conntrack:
rhashtable_destroy(&efx->tc->lhs_rule_ht);
fail_lhs_rule_ht:
rhashtable_destroy(&efx->tc->match_action_ht);
fail_match_action_ht:
rhashtable_destroy(&efx->tc->encap_match_ht);
fail_encap_match_ht:
rhashtable_destroy(&efx->tc->mac_ht);
fail_mac_ht:
efx_tc_destroy_counters(efx);
fail_counters:
efx_tc_destroy_encap_actions(efx);
fail_encap_actions:
mutex_destroy(&efx->tc->mutex);
kfree(efx->tc->caps);
fail_alloc_caps:
kfree(efx->tc);
efx->tc = NULL;
return rc;
}
void efx_fini_struct_tc(struct efx_nic *efx)
{
if (!efx->tc)
return;
mutex_lock(&efx->tc->mutex);
EFX_WARN_ON_PARANOID(efx->tc->dflt.pf.fw_id !=
MC_CMD_MAE_ACTION_RULE_INSERT_OUT_ACTION_RULE_ID_NULL);
EFX_WARN_ON_PARANOID(efx->tc->dflt.wire.fw_id !=
MC_CMD_MAE_ACTION_RULE_INSERT_OUT_ACTION_RULE_ID_NULL);
EFX_WARN_ON_PARANOID(efx->tc->facts.pf.fw_id !=
MC_CMD_MAE_ACTION_SET_LIST_ALLOC_OUT_ACTION_SET_LIST_ID_NULL);
EFX_WARN_ON_PARANOID(efx->tc->facts.reps.fw_id !=
MC_CMD_MAE_ACTION_SET_LIST_ALLOC_OUT_ACTION_SET_LIST_ID_NULL);
rhashtable_free_and_destroy(&efx->tc->lhs_rule_ht, efx_tc_lhs_free, efx);
rhashtable_free_and_destroy(&efx->tc->match_action_ht, efx_tc_flow_free,
efx);
rhashtable_free_and_destroy(&efx->tc->encap_match_ht,
efx_tc_encap_match_free, NULL);
efx_tc_fini_conntrack(efx);
rhashtable_free_and_destroy(&efx->tc->recirc_ht, efx_tc_recirc_free, efx);
WARN_ON(!ida_is_empty(&efx->tc->recirc_ida));
ida_destroy(&efx->tc->recirc_ida);
rhashtable_free_and_destroy(&efx->tc->mac_ht, efx_tc_mac_free, NULL);
efx_tc_fini_counters(efx);
efx_tc_fini_encap_actions(efx);
mutex_unlock(&efx->tc->mutex);
mutex_destroy(&efx->tc->mutex);
kfree(efx->tc->caps);
kfree(efx->tc);
efx->tc = NULL;
}
|
linux-master
|
drivers/net/ethernet/sfc/tc.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2005-2006 Fen Systems Ltd.
* Copyright 2006-2013 Solarflare Communications Inc.
*/
#include <linux/module.h>
#include <linux/mtd/mtd.h>
#include <linux/slab.h>
#include <linux/rtnetlink.h>
#include "net_driver.h"
#include "efx.h"
#define to_efx_mtd_partition(mtd) \
container_of(mtd, struct efx_mtd_partition, mtd)
/* MTD interface */
static int efx_mtd_erase(struct mtd_info *mtd, struct erase_info *erase)
{
struct efx_nic *efx = mtd->priv;
return efx->type->mtd_erase(mtd, erase->addr, erase->len);
}
static void efx_mtd_sync(struct mtd_info *mtd)
{
struct efx_mtd_partition *part = to_efx_mtd_partition(mtd);
struct efx_nic *efx = mtd->priv;
int rc;
rc = efx->type->mtd_sync(mtd);
if (rc)
pr_err("%s: %s sync failed (%d)\n",
part->name, part->dev_type_name, rc);
}
static void efx_mtd_remove_partition(struct efx_mtd_partition *part)
{
int rc;
for (;;) {
rc = mtd_device_unregister(&part->mtd);
if (rc != -EBUSY)
break;
ssleep(1);
}
WARN_ON(rc);
list_del(&part->node);
}
int efx_mtd_add(struct efx_nic *efx, struct efx_mtd_partition *parts,
size_t n_parts, size_t sizeof_part)
{
struct efx_mtd_partition *part;
size_t i;
for (i = 0; i < n_parts; i++) {
part = (struct efx_mtd_partition *)((char *)parts +
i * sizeof_part);
part->mtd.writesize = 1;
if (!(part->mtd.flags & MTD_NO_ERASE))
part->mtd.flags |= MTD_WRITEABLE;
part->mtd.owner = THIS_MODULE;
part->mtd.priv = efx;
part->mtd.name = part->name;
part->mtd._erase = efx_mtd_erase;
part->mtd._read = efx->type->mtd_read;
part->mtd._write = efx->type->mtd_write;
part->mtd._sync = efx_mtd_sync;
efx->type->mtd_rename(part);
if (mtd_device_register(&part->mtd, NULL, 0))
goto fail;
/* Add to list in order - efx_mtd_remove() depends on this */
list_add_tail(&part->node, &efx->mtd_list);
}
return 0;
fail:
while (i--) {
part = (struct efx_mtd_partition *)((char *)parts +
i * sizeof_part);
efx_mtd_remove_partition(part);
}
/* Failure is unlikely here, but probably means we're out of memory */
return -ENOMEM;
}
void efx_mtd_remove(struct efx_nic *efx)
{
struct efx_mtd_partition *parts, *part, *next;
WARN_ON(efx_dev_registered(efx));
if (list_empty(&efx->mtd_list))
return;
parts = list_first_entry(&efx->mtd_list, struct efx_mtd_partition,
node);
list_for_each_entry_safe(part, next, &efx->mtd_list, node)
efx_mtd_remove_partition(part);
kfree(parts);
}
void efx_mtd_rename(struct efx_nic *efx)
{
struct efx_mtd_partition *part;
ASSERT_RTNL();
list_for_each_entry(part, &efx->mtd_list, node)
efx->type->mtd_rename(part);
}
|
linux-master
|
drivers/net/ethernet/sfc/mtd.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2005-2006 Fen Systems Ltd.
* Copyright 2006-2012 Solarflare Communications Inc.
*/
#include <linux/netdevice.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/kernel_stat.h>
#include <linux/pci.h>
#include <linux/ethtool.h>
#include <linux/ip.h>
#include <linux/in.h>
#include <linux/udp.h>
#include <linux/rtnetlink.h>
#include <linux/slab.h>
#include "net_driver.h"
#include "efx.h"
#include "efx_common.h"
#include "efx_channels.h"
#include "nic.h"
#include "mcdi_port_common.h"
#include "selftest.h"
#include "workarounds.h"
/* IRQ latency can be enormous because:
* - All IRQs may be disabled on a CPU for a *long* time by e.g. a
* slow serial console or an old IDE driver doing error recovery
* - The PREEMPT_RT patches mostly deal with this, but also allow a
* tasklet or normal task to be given higher priority than our IRQ
* threads
* Try to avoid blaming the hardware for this.
*/
#define IRQ_TIMEOUT HZ
/*
* Loopback test packet structure
*
* The self-test should stress every RSS vector.
*/
struct efx_loopback_payload {
char pad[2]; /* Ensures ip is 4-byte aligned */
struct_group_attr(packet, __packed,
struct ethhdr header;
struct iphdr ip;
struct udphdr udp;
__be16 iteration;
char msg[64];
);
} __packed __aligned(4);
#define EFX_LOOPBACK_PAYLOAD_LEN \
sizeof_field(struct efx_loopback_payload, packet)
/* Loopback test source MAC address */
static const u8 payload_source[ETH_ALEN] __aligned(2) = {
0x00, 0x0f, 0x53, 0x1b, 0x1b, 0x1b,
};
static const char payload_msg[] =
"Hello world! This is an Efx loopback test in progress!";
/* Interrupt mode names */
static const unsigned int efx_interrupt_mode_max = EFX_INT_MODE_MAX;
static const char *const efx_interrupt_mode_names[] = {
[EFX_INT_MODE_MSIX] = "MSI-X",
[EFX_INT_MODE_MSI] = "MSI",
[EFX_INT_MODE_LEGACY] = "legacy",
};
#define INT_MODE(efx) \
STRING_TABLE_LOOKUP(efx->interrupt_mode, efx_interrupt_mode)
/**
* struct efx_loopback_state - persistent state during a loopback selftest
* @flush: Drop all packets in efx_loopback_rx_packet
* @packet_count: Number of packets being used in this test
* @skbs: An array of skbs transmitted
* @offload_csum: Checksums are being offloaded
* @rx_good: RX good packet count
* @rx_bad: RX bad packet count
* @payload: Payload used in tests
*/
struct efx_loopback_state {
bool flush;
int packet_count;
struct sk_buff **skbs;
bool offload_csum;
atomic_t rx_good;
atomic_t rx_bad;
struct efx_loopback_payload payload;
};
/* How long to wait for all the packets to arrive (in ms) */
#define LOOPBACK_TIMEOUT_MS 1000
/**************************************************************************
*
* MII, NVRAM and register tests
*
**************************************************************************/
static int efx_test_phy_alive(struct efx_nic *efx, struct efx_self_tests *tests)
{
int rc = 0;
rc = efx_mcdi_phy_test_alive(efx);
tests->phy_alive = rc ? -1 : 1;
return rc;
}
static int efx_test_nvram(struct efx_nic *efx, struct efx_self_tests *tests)
{
int rc = 0;
if (efx->type->test_nvram) {
rc = efx->type->test_nvram(efx);
if (rc == -EPERM)
rc = 0;
else
tests->nvram = rc ? -1 : 1;
}
return rc;
}
/**************************************************************************
*
* Interrupt and event queue testing
*
**************************************************************************/
/* Test generation and receipt of interrupts */
static int efx_test_interrupts(struct efx_nic *efx,
struct efx_self_tests *tests)
{
unsigned long timeout, wait;
int cpu;
int rc;
netif_dbg(efx, drv, efx->net_dev, "testing interrupts\n");
tests->interrupt = -1;
rc = efx_nic_irq_test_start(efx);
if (rc == -ENOTSUPP) {
netif_dbg(efx, drv, efx->net_dev,
"direct interrupt testing not supported\n");
tests->interrupt = 0;
return 0;
}
timeout = jiffies + IRQ_TIMEOUT;
wait = 1;
/* Wait for arrival of test interrupt. */
netif_dbg(efx, drv, efx->net_dev, "waiting for test interrupt\n");
do {
schedule_timeout_uninterruptible(wait);
cpu = efx_nic_irq_test_irq_cpu(efx);
if (cpu >= 0)
goto success;
wait *= 2;
} while (time_before(jiffies, timeout));
netif_err(efx, drv, efx->net_dev, "timed out waiting for interrupt\n");
return -ETIMEDOUT;
success:
netif_dbg(efx, drv, efx->net_dev, "%s test interrupt seen on CPU%d\n",
INT_MODE(efx), cpu);
tests->interrupt = 1;
return 0;
}
/* Test generation and receipt of interrupting events */
static int efx_test_eventq_irq(struct efx_nic *efx,
struct efx_self_tests *tests)
{
struct efx_channel *channel;
unsigned int read_ptr[EFX_MAX_CHANNELS];
unsigned long napi_ran = 0, dma_pend = 0, int_pend = 0;
unsigned long timeout, wait;
BUILD_BUG_ON(EFX_MAX_CHANNELS > BITS_PER_LONG);
efx_for_each_channel(channel, efx) {
read_ptr[channel->channel] = channel->eventq_read_ptr;
set_bit(channel->channel, &dma_pend);
set_bit(channel->channel, &int_pend);
efx_nic_event_test_start(channel);
}
timeout = jiffies + IRQ_TIMEOUT;
wait = 1;
/* Wait for arrival of interrupts. NAPI processing may or may
* not complete in time, but we can cope in any case.
*/
do {
schedule_timeout_uninterruptible(wait);
efx_for_each_channel(channel, efx) {
efx_stop_eventq(channel);
if (channel->eventq_read_ptr !=
read_ptr[channel->channel]) {
set_bit(channel->channel, &napi_ran);
clear_bit(channel->channel, &dma_pend);
clear_bit(channel->channel, &int_pend);
} else {
if (efx_nic_event_present(channel))
clear_bit(channel->channel, &dma_pend);
if (efx_nic_event_test_irq_cpu(channel) >= 0)
clear_bit(channel->channel, &int_pend);
}
efx_start_eventq(channel);
}
wait *= 2;
} while ((dma_pend || int_pend) && time_before(jiffies, timeout));
efx_for_each_channel(channel, efx) {
bool dma_seen = !test_bit(channel->channel, &dma_pend);
bool int_seen = !test_bit(channel->channel, &int_pend);
tests->eventq_dma[channel->channel] = dma_seen ? 1 : -1;
tests->eventq_int[channel->channel] = int_seen ? 1 : -1;
if (dma_seen && int_seen) {
netif_dbg(efx, drv, efx->net_dev,
"channel %d event queue passed (with%s NAPI)\n",
channel->channel,
test_bit(channel->channel, &napi_ran) ?
"" : "out");
} else {
/* Report failure and whether either interrupt or DMA
* worked
*/
netif_err(efx, drv, efx->net_dev,
"channel %d timed out waiting for event queue\n",
channel->channel);
if (int_seen)
netif_err(efx, drv, efx->net_dev,
"channel %d saw interrupt "
"during event queue test\n",
channel->channel);
if (dma_seen)
netif_err(efx, drv, efx->net_dev,
"channel %d event was generated, but "
"failed to trigger an interrupt\n",
channel->channel);
}
}
return (dma_pend || int_pend) ? -ETIMEDOUT : 0;
}
static int efx_test_phy(struct efx_nic *efx, struct efx_self_tests *tests,
unsigned flags)
{
int rc;
mutex_lock(&efx->mac_lock);
rc = efx_mcdi_phy_run_tests(efx, tests->phy_ext, flags);
mutex_unlock(&efx->mac_lock);
if (rc == -EPERM)
rc = 0;
else
netif_info(efx, drv, efx->net_dev,
"%s phy selftest\n", rc ? "Failed" : "Passed");
return rc;
}
/**************************************************************************
*
* Loopback testing
* NB Only one loopback test can be executing concurrently.
*
**************************************************************************/
/* Loopback test RX callback
* This is called for each received packet during loopback testing.
*/
void efx_loopback_rx_packet(struct efx_nic *efx,
const char *buf_ptr, int pkt_len)
{
struct efx_loopback_state *state = efx->loopback_selftest;
struct efx_loopback_payload received;
struct efx_loopback_payload *payload;
BUG_ON(!buf_ptr);
/* If we are just flushing, then drop the packet */
if ((state == NULL) || state->flush)
return;
payload = &state->payload;
memcpy(&received.packet, buf_ptr,
min_t(int, pkt_len, EFX_LOOPBACK_PAYLOAD_LEN));
received.ip.saddr = payload->ip.saddr;
if (state->offload_csum)
received.ip.check = payload->ip.check;
/* Check that header exists */
if (pkt_len < sizeof(received.header)) {
netif_err(efx, drv, efx->net_dev,
"saw runt RX packet (length %d) in %s loopback "
"test\n", pkt_len, LOOPBACK_MODE(efx));
goto err;
}
/* Check that the ethernet header exists */
if (memcmp(&received.header, &payload->header, ETH_HLEN) != 0) {
netif_err(efx, drv, efx->net_dev,
"saw non-loopback RX packet in %s loopback test\n",
LOOPBACK_MODE(efx));
goto err;
}
/* Check packet length */
if (pkt_len != EFX_LOOPBACK_PAYLOAD_LEN) {
netif_err(efx, drv, efx->net_dev,
"saw incorrect RX packet length %d (wanted %d) in "
"%s loopback test\n", pkt_len,
(int)EFX_LOOPBACK_PAYLOAD_LEN, LOOPBACK_MODE(efx));
goto err;
}
/* Check that IP header matches */
if (memcmp(&received.ip, &payload->ip, sizeof(payload->ip)) != 0) {
netif_err(efx, drv, efx->net_dev,
"saw corrupted IP header in %s loopback test\n",
LOOPBACK_MODE(efx));
goto err;
}
/* Check that msg and padding matches */
if (memcmp(&received.msg, &payload->msg, sizeof(received.msg)) != 0) {
netif_err(efx, drv, efx->net_dev,
"saw corrupted RX packet in %s loopback test\n",
LOOPBACK_MODE(efx));
goto err;
}
/* Check that iteration matches */
if (received.iteration != payload->iteration) {
netif_err(efx, drv, efx->net_dev,
"saw RX packet from iteration %d (wanted %d) in "
"%s loopback test\n", ntohs(received.iteration),
ntohs(payload->iteration), LOOPBACK_MODE(efx));
goto err;
}
/* Increase correct RX count */
netif_vdbg(efx, drv, efx->net_dev,
"got loopback RX in %s loopback test\n", LOOPBACK_MODE(efx));
atomic_inc(&state->rx_good);
return;
err:
#ifdef DEBUG
if (atomic_read(&state->rx_bad) == 0) {
netif_err(efx, drv, efx->net_dev, "received packet:\n");
print_hex_dump(KERN_ERR, "", DUMP_PREFIX_OFFSET, 0x10, 1,
buf_ptr, pkt_len, 0);
netif_err(efx, drv, efx->net_dev, "expected packet:\n");
print_hex_dump(KERN_ERR, "", DUMP_PREFIX_OFFSET, 0x10, 1,
&state->payload.packet, EFX_LOOPBACK_PAYLOAD_LEN,
0);
}
#endif
atomic_inc(&state->rx_bad);
}
/* Initialise an efx_selftest_state for a new iteration */
static void efx_iterate_state(struct efx_nic *efx)
{
struct efx_loopback_state *state = efx->loopback_selftest;
struct net_device *net_dev = efx->net_dev;
struct efx_loopback_payload *payload = &state->payload;
/* Initialise the layerII header */
ether_addr_copy((u8 *)&payload->header.h_dest, net_dev->dev_addr);
ether_addr_copy((u8 *)&payload->header.h_source, payload_source);
payload->header.h_proto = htons(ETH_P_IP);
/* saddr set later and used as incrementing count */
payload->ip.daddr = htonl(INADDR_LOOPBACK);
payload->ip.ihl = 5;
payload->ip.check = (__force __sum16) htons(0xdead);
payload->ip.tot_len = htons(sizeof(*payload) -
offsetof(struct efx_loopback_payload, ip));
payload->ip.version = IPVERSION;
payload->ip.protocol = IPPROTO_UDP;
/* Initialise udp header */
payload->udp.source = 0;
payload->udp.len = htons(sizeof(*payload) -
offsetof(struct efx_loopback_payload, udp));
payload->udp.check = 0; /* checksum ignored */
/* Fill out payload */
payload->iteration = htons(ntohs(payload->iteration) + 1);
memcpy(&payload->msg, payload_msg, sizeof(payload_msg));
/* Fill out remaining state members */
atomic_set(&state->rx_good, 0);
atomic_set(&state->rx_bad, 0);
smp_wmb();
}
static int efx_begin_loopback(struct efx_tx_queue *tx_queue)
{
struct efx_nic *efx = tx_queue->efx;
struct efx_loopback_state *state = efx->loopback_selftest;
struct efx_loopback_payload *payload;
struct sk_buff *skb;
int i;
netdev_tx_t rc;
/* Transmit N copies of buffer */
for (i = 0; i < state->packet_count; i++) {
/* Allocate an skb, holding an extra reference for
* transmit completion counting */
skb = alloc_skb(sizeof(state->payload), GFP_KERNEL);
if (!skb)
return -ENOMEM;
state->skbs[i] = skb;
skb_get(skb);
/* Copy the payload in, incrementing the source address to
* exercise the rss vectors */
payload = skb_put(skb, sizeof(state->payload));
memcpy(payload, &state->payload, sizeof(state->payload));
payload->ip.saddr = htonl(INADDR_LOOPBACK | (i << 2));
/* Strip off the leading padding */
skb_pull(skb, offsetof(struct efx_loopback_payload, header));
/* Strip off the trailing padding */
skb_trim(skb, EFX_LOOPBACK_PAYLOAD_LEN);
/* Ensure everything we've written is visible to the
* interrupt handler. */
smp_wmb();
netif_tx_lock_bh(efx->net_dev);
rc = efx_enqueue_skb(tx_queue, skb);
netif_tx_unlock_bh(efx->net_dev);
if (rc != NETDEV_TX_OK) {
netif_err(efx, drv, efx->net_dev,
"TX queue %d could not transmit packet %d of "
"%d in %s loopback test\n", tx_queue->label,
i + 1, state->packet_count,
LOOPBACK_MODE(efx));
/* Defer cleaning up the other skbs for the caller */
kfree_skb(skb);
return -EPIPE;
}
}
return 0;
}
static int efx_poll_loopback(struct efx_nic *efx)
{
struct efx_loopback_state *state = efx->loopback_selftest;
return atomic_read(&state->rx_good) == state->packet_count;
}
static int efx_end_loopback(struct efx_tx_queue *tx_queue,
struct efx_loopback_self_tests *lb_tests)
{
struct efx_nic *efx = tx_queue->efx;
struct efx_loopback_state *state = efx->loopback_selftest;
struct sk_buff *skb;
int tx_done = 0, rx_good, rx_bad;
int i, rc = 0;
netif_tx_lock_bh(efx->net_dev);
/* Count the number of tx completions, and decrement the refcnt. Any
* skbs not already completed will be free'd when the queue is flushed */
for (i = 0; i < state->packet_count; i++) {
skb = state->skbs[i];
if (skb && !skb_shared(skb))
++tx_done;
dev_kfree_skb(skb);
}
netif_tx_unlock_bh(efx->net_dev);
/* Check TX completion and received packet counts */
rx_good = atomic_read(&state->rx_good);
rx_bad = atomic_read(&state->rx_bad);
if (tx_done != state->packet_count) {
/* Don't free the skbs; they will be picked up on TX
* overflow or channel teardown.
*/
netif_err(efx, drv, efx->net_dev,
"TX queue %d saw only %d out of an expected %d "
"TX completion events in %s loopback test\n",
tx_queue->label, tx_done, state->packet_count,
LOOPBACK_MODE(efx));
rc = -ETIMEDOUT;
/* Allow to fall through so we see the RX errors as well */
}
/* We may always be up to a flush away from our desired packet total */
if (rx_good != state->packet_count) {
netif_dbg(efx, drv, efx->net_dev,
"TX queue %d saw only %d out of an expected %d "
"received packets in %s loopback test\n",
tx_queue->label, rx_good, state->packet_count,
LOOPBACK_MODE(efx));
rc = -ETIMEDOUT;
/* Fall through */
}
/* Update loopback test structure */
lb_tests->tx_sent[tx_queue->label] += state->packet_count;
lb_tests->tx_done[tx_queue->label] += tx_done;
lb_tests->rx_good += rx_good;
lb_tests->rx_bad += rx_bad;
return rc;
}
static int
efx_test_loopback(struct efx_tx_queue *tx_queue,
struct efx_loopback_self_tests *lb_tests)
{
struct efx_nic *efx = tx_queue->efx;
struct efx_loopback_state *state = efx->loopback_selftest;
int i, begin_rc, end_rc;
for (i = 0; i < 3; i++) {
/* Determine how many packets to send */
state->packet_count = efx->txq_entries / 3;
state->packet_count = min(1 << (i << 2), state->packet_count);
state->skbs = kcalloc(state->packet_count,
sizeof(state->skbs[0]), GFP_KERNEL);
if (!state->skbs)
return -ENOMEM;
state->flush = false;
netif_dbg(efx, drv, efx->net_dev,
"TX queue %d (hw %d) testing %s loopback with %d packets\n",
tx_queue->label, tx_queue->queue, LOOPBACK_MODE(efx),
state->packet_count);
efx_iterate_state(efx);
begin_rc = efx_begin_loopback(tx_queue);
/* This will normally complete very quickly, but be
* prepared to wait much longer. */
msleep(1);
if (!efx_poll_loopback(efx)) {
msleep(LOOPBACK_TIMEOUT_MS);
efx_poll_loopback(efx);
}
end_rc = efx_end_loopback(tx_queue, lb_tests);
kfree(state->skbs);
if (begin_rc || end_rc) {
/* Wait a while to ensure there are no packets
* floating around after a failure. */
schedule_timeout_uninterruptible(HZ / 10);
return begin_rc ? begin_rc : end_rc;
}
}
netif_dbg(efx, drv, efx->net_dev,
"TX queue %d passed %s loopback test with a burst length "
"of %d packets\n", tx_queue->label, LOOPBACK_MODE(efx),
state->packet_count);
return 0;
}
static int efx_wait_for_link(struct efx_nic *efx)
{
struct efx_link_state *link_state = &efx->link_state;
int count, link_up_count = 0;
bool link_up;
for (count = 0; count < 40; count++) {
schedule_timeout_uninterruptible(HZ / 10);
if (efx->type->monitor != NULL) {
mutex_lock(&efx->mac_lock);
efx->type->monitor(efx);
mutex_unlock(&efx->mac_lock);
}
mutex_lock(&efx->mac_lock);
link_up = link_state->up;
if (link_up)
link_up = !efx->type->check_mac_fault(efx);
mutex_unlock(&efx->mac_lock);
if (link_up) {
if (++link_up_count == 2)
return 0;
} else {
link_up_count = 0;
}
}
return -ETIMEDOUT;
}
static int efx_test_loopbacks(struct efx_nic *efx, struct efx_self_tests *tests,
unsigned int loopback_modes)
{
enum efx_loopback_mode mode;
struct efx_loopback_state *state;
struct efx_channel *channel =
efx_get_channel(efx, efx->tx_channel_offset);
struct efx_tx_queue *tx_queue;
int rc = 0;
/* Set the port loopback_selftest member. From this point on
* all received packets will be dropped. Mark the state as
* "flushing" so all inflight packets are dropped */
state = kzalloc(sizeof(*state), GFP_KERNEL);
if (state == NULL)
return -ENOMEM;
BUG_ON(efx->loopback_selftest);
state->flush = true;
efx->loopback_selftest = state;
/* Test all supported loopback modes */
for (mode = LOOPBACK_NONE; mode <= LOOPBACK_TEST_MAX; mode++) {
if (!(loopback_modes & (1 << mode)))
continue;
/* Move the port into the specified loopback mode. */
state->flush = true;
mutex_lock(&efx->mac_lock);
efx->loopback_mode = mode;
rc = __efx_reconfigure_port(efx);
mutex_unlock(&efx->mac_lock);
if (rc) {
netif_err(efx, drv, efx->net_dev,
"unable to move into %s loopback\n",
LOOPBACK_MODE(efx));
goto out;
}
rc = efx_wait_for_link(efx);
if (rc) {
netif_err(efx, drv, efx->net_dev,
"loopback %s never came up\n",
LOOPBACK_MODE(efx));
goto out;
}
/* Test all enabled types of TX queue */
efx_for_each_channel_tx_queue(tx_queue, channel) {
state->offload_csum = (tx_queue->type &
EFX_TXQ_TYPE_OUTER_CSUM);
rc = efx_test_loopback(tx_queue,
&tests->loopback[mode]);
if (rc)
goto out;
}
}
out:
/* Remove the flush. The caller will remove the loopback setting */
state->flush = true;
efx->loopback_selftest = NULL;
wmb();
kfree(state);
if (rc == -EPERM)
rc = 0;
return rc;
}
/**************************************************************************
*
* Entry point
*
*************************************************************************/
int efx_selftest(struct efx_nic *efx, struct efx_self_tests *tests,
unsigned flags)
{
enum efx_loopback_mode loopback_mode = efx->loopback_mode;
int phy_mode = efx->phy_mode;
int rc_test = 0, rc_reset, rc;
efx_selftest_async_cancel(efx);
/* Online (i.e. non-disruptive) testing
* This checks interrupt generation, event delivery and PHY presence. */
rc = efx_test_phy_alive(efx, tests);
if (rc && !rc_test)
rc_test = rc;
rc = efx_test_nvram(efx, tests);
if (rc && !rc_test)
rc_test = rc;
rc = efx_test_interrupts(efx, tests);
if (rc && !rc_test)
rc_test = rc;
rc = efx_test_eventq_irq(efx, tests);
if (rc && !rc_test)
rc_test = rc;
if (rc_test)
return rc_test;
if (!(flags & ETH_TEST_FL_OFFLINE))
return efx_test_phy(efx, tests, flags);
/* Offline (i.e. disruptive) testing
* This checks MAC and PHY loopback on the specified port. */
/* Detach the device so the kernel doesn't transmit during the
* loopback test and the watchdog timeout doesn't fire.
*/
efx_device_detach_sync(efx);
if (efx->type->test_chip) {
rc_reset = efx->type->test_chip(efx, tests);
if (rc_reset) {
netif_err(efx, hw, efx->net_dev,
"Unable to recover from chip test\n");
efx_schedule_reset(efx, RESET_TYPE_DISABLE);
return rc_reset;
}
if ((tests->memory < 0 || tests->registers < 0) && !rc_test)
rc_test = -EIO;
}
/* Ensure that the phy is powered and out of loopback
* for the bist and loopback tests */
mutex_lock(&efx->mac_lock);
efx->phy_mode &= ~PHY_MODE_LOW_POWER;
efx->loopback_mode = LOOPBACK_NONE;
__efx_reconfigure_port(efx);
mutex_unlock(&efx->mac_lock);
rc = efx_test_phy(efx, tests, flags);
if (rc && !rc_test)
rc_test = rc;
rc = efx_test_loopbacks(efx, tests, efx->loopback_modes);
if (rc && !rc_test)
rc_test = rc;
/* restore the PHY to the previous state */
mutex_lock(&efx->mac_lock);
efx->phy_mode = phy_mode;
efx->loopback_mode = loopback_mode;
__efx_reconfigure_port(efx);
mutex_unlock(&efx->mac_lock);
efx_device_attach_if_not_resetting(efx);
return rc_test;
}
void efx_selftest_async_start(struct efx_nic *efx)
{
struct efx_channel *channel;
efx_for_each_channel(channel, efx)
efx_nic_event_test_start(channel);
schedule_delayed_work(&efx->selftest_work, IRQ_TIMEOUT);
}
void efx_selftest_async_cancel(struct efx_nic *efx)
{
cancel_delayed_work_sync(&efx->selftest_work);
}
static void efx_selftest_async_work(struct work_struct *data)
{
struct efx_nic *efx = container_of(data, struct efx_nic,
selftest_work.work);
struct efx_channel *channel;
int cpu;
efx_for_each_channel(channel, efx) {
cpu = efx_nic_event_test_irq_cpu(channel);
if (cpu < 0)
netif_err(efx, ifup, efx->net_dev,
"channel %d failed to trigger an interrupt\n",
channel->channel);
else
netif_dbg(efx, ifup, efx->net_dev,
"channel %d triggered interrupt on CPU %d\n",
channel->channel, cpu);
}
}
void efx_selftest_async_init(struct efx_nic *efx)
{
INIT_DELAYED_WORK(&efx->selftest_work, efx_selftest_async_work);
}
|
linux-master
|
drivers/net/ethernet/sfc/selftest.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2005-2006 Fen Systems Ltd.
* Copyright 2006-2013 Solarflare Communications Inc.
*/
#include <linux/bitops.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/module.h>
#include <linux/seq_file.h>
#include <linux/cpu_rmap.h>
#include "net_driver.h"
#include "bitfield.h"
#include "efx.h"
#include "nic.h"
#include "ef10_regs.h"
#include "io.h"
#include "workarounds.h"
#include "mcdi_pcol.h"
/**************************************************************************
*
* Generic buffer handling
* These buffers are used for interrupt status, MAC stats, etc.
*
**************************************************************************/
int efx_nic_alloc_buffer(struct efx_nic *efx, struct efx_buffer *buffer,
unsigned int len, gfp_t gfp_flags)
{
buffer->addr = dma_alloc_coherent(&efx->pci_dev->dev, len,
&buffer->dma_addr, gfp_flags);
if (!buffer->addr)
return -ENOMEM;
buffer->len = len;
return 0;
}
void efx_nic_free_buffer(struct efx_nic *efx, struct efx_buffer *buffer)
{
if (buffer->addr) {
dma_free_coherent(&efx->pci_dev->dev, buffer->len,
buffer->addr, buffer->dma_addr);
buffer->addr = NULL;
}
}
/* Check whether an event is present in the eventq at the current
* read pointer. Only useful for self-test.
*/
bool efx_nic_event_present(struct efx_channel *channel)
{
return efx_event_present(efx_event(channel, channel->eventq_read_ptr));
}
void efx_nic_event_test_start(struct efx_channel *channel)
{
channel->event_test_cpu = -1;
smp_wmb();
channel->efx->type->ev_test_generate(channel);
}
int efx_nic_irq_test_start(struct efx_nic *efx)
{
efx->last_irq_cpu = -1;
smp_wmb();
return efx->type->irq_test_generate(efx);
}
/* Hook interrupt handler(s)
* Try MSI and then legacy interrupts.
*/
int efx_nic_init_interrupt(struct efx_nic *efx)
{
struct efx_channel *channel;
unsigned int n_irqs;
int rc;
if (!EFX_INT_MODE_USE_MSI(efx)) {
rc = request_irq(efx->legacy_irq,
efx->type->irq_handle_legacy, IRQF_SHARED,
efx->name, efx);
if (rc) {
netif_err(efx, drv, efx->net_dev,
"failed to hook legacy IRQ %d\n",
efx->pci_dev->irq);
goto fail1;
}
efx->irqs_hooked = true;
return 0;
}
#ifdef CONFIG_RFS_ACCEL
if (efx->interrupt_mode == EFX_INT_MODE_MSIX) {
efx->net_dev->rx_cpu_rmap =
alloc_irq_cpu_rmap(efx->n_rx_channels);
if (!efx->net_dev->rx_cpu_rmap) {
rc = -ENOMEM;
goto fail1;
}
}
#endif
/* Hook MSI or MSI-X interrupt */
n_irqs = 0;
efx_for_each_channel(channel, efx) {
rc = request_irq(channel->irq, efx->type->irq_handle_msi,
IRQF_PROBE_SHARED, /* Not shared */
efx->msi_context[channel->channel].name,
&efx->msi_context[channel->channel]);
if (rc) {
netif_err(efx, drv, efx->net_dev,
"failed to hook IRQ %d\n", channel->irq);
goto fail2;
}
++n_irqs;
#ifdef CONFIG_RFS_ACCEL
if (efx->interrupt_mode == EFX_INT_MODE_MSIX &&
channel->channel < efx->n_rx_channels) {
rc = irq_cpu_rmap_add(efx->net_dev->rx_cpu_rmap,
channel->irq);
if (rc)
goto fail2;
}
#endif
}
efx->irqs_hooked = true;
return 0;
fail2:
#ifdef CONFIG_RFS_ACCEL
free_irq_cpu_rmap(efx->net_dev->rx_cpu_rmap);
efx->net_dev->rx_cpu_rmap = NULL;
#endif
efx_for_each_channel(channel, efx) {
if (n_irqs-- == 0)
break;
free_irq(channel->irq, &efx->msi_context[channel->channel]);
}
fail1:
return rc;
}
void efx_nic_fini_interrupt(struct efx_nic *efx)
{
struct efx_channel *channel;
#ifdef CONFIG_RFS_ACCEL
free_irq_cpu_rmap(efx->net_dev->rx_cpu_rmap);
efx->net_dev->rx_cpu_rmap = NULL;
#endif
if (!efx->irqs_hooked)
return;
if (EFX_INT_MODE_USE_MSI(efx)) {
/* Disable MSI/MSI-X interrupts */
efx_for_each_channel(channel, efx)
free_irq(channel->irq,
&efx->msi_context[channel->channel]);
} else {
/* Disable legacy interrupt */
free_irq(efx->legacy_irq, efx);
}
efx->irqs_hooked = false;
}
/* Register dump */
#define REGISTER_REVISION_ED 4
#define REGISTER_REVISION_EZ 4 /* latest EF10 revision */
struct efx_nic_reg {
u32 offset:24;
u32 min_revision:3, max_revision:3;
};
#define REGISTER(name, arch, min_rev, max_rev) { \
arch ## R_ ## min_rev ## max_rev ## _ ## name, \
REGISTER_REVISION_ ## arch ## min_rev, \
REGISTER_REVISION_ ## arch ## max_rev \
}
#define REGISTER_DZ(name) REGISTER(name, E, D, Z)
static const struct efx_nic_reg efx_nic_regs[] = {
/* XX_PRBS_CTL, XX_PRBS_CHK and XX_PRBS_ERR are not used */
/* XX_CORE_STAT is partly RC */
REGISTER_DZ(BIU_HW_REV_ID),
REGISTER_DZ(MC_DB_LWRD),
REGISTER_DZ(MC_DB_HWRD),
};
struct efx_nic_reg_table {
u32 offset:24;
u32 min_revision:3, max_revision:3;
u32 step:6, rows:21;
};
#define REGISTER_TABLE_DIMENSIONS(_, offset, arch, min_rev, max_rev, step, rows) { \
offset, \
REGISTER_REVISION_ ## arch ## min_rev, \
REGISTER_REVISION_ ## arch ## max_rev, \
step, rows \
}
#define REGISTER_TABLE(name, arch, min_rev, max_rev) \
REGISTER_TABLE_DIMENSIONS( \
name, arch ## R_ ## min_rev ## max_rev ## _ ## name, \
arch, min_rev, max_rev, \
arch ## R_ ## min_rev ## max_rev ## _ ## name ## _STEP, \
arch ## R_ ## min_rev ## max_rev ## _ ## name ## _ROWS)
#define REGISTER_TABLE_DZ(name) REGISTER_TABLE(name, E, D, Z)
static const struct efx_nic_reg_table efx_nic_reg_tables[] = {
REGISTER_TABLE_DZ(BIU_MC_SFT_STATUS),
};
size_t efx_nic_get_regs_len(struct efx_nic *efx)
{
const struct efx_nic_reg *reg;
const struct efx_nic_reg_table *table;
size_t len = 0;
for (reg = efx_nic_regs;
reg < efx_nic_regs + ARRAY_SIZE(efx_nic_regs);
reg++)
if (efx->type->revision >= reg->min_revision &&
efx->type->revision <= reg->max_revision)
len += sizeof(efx_oword_t);
for (table = efx_nic_reg_tables;
table < efx_nic_reg_tables + ARRAY_SIZE(efx_nic_reg_tables);
table++)
if (efx->type->revision >= table->min_revision &&
efx->type->revision <= table->max_revision)
len += table->rows * min_t(size_t, table->step, 16);
return len;
}
void efx_nic_get_regs(struct efx_nic *efx, void *buf)
{
const struct efx_nic_reg *reg;
const struct efx_nic_reg_table *table;
for (reg = efx_nic_regs;
reg < efx_nic_regs + ARRAY_SIZE(efx_nic_regs);
reg++) {
if (efx->type->revision >= reg->min_revision &&
efx->type->revision <= reg->max_revision) {
efx_reado(efx, (efx_oword_t *)buf, reg->offset);
buf += sizeof(efx_oword_t);
}
}
for (table = efx_nic_reg_tables;
table < efx_nic_reg_tables + ARRAY_SIZE(efx_nic_reg_tables);
table++) {
size_t size, i;
if (!(efx->type->revision >= table->min_revision &&
efx->type->revision <= table->max_revision))
continue;
size = min_t(size_t, table->step, 16);
for (i = 0; i < table->rows; i++) {
switch (table->step) {
case 4: /* 32-bit SRAM */
efx_readd(efx, buf, table->offset + 4 * i);
break;
case 16: /* 128-bit-readable register */
efx_reado_table(efx, buf, table->offset, i);
break;
case 32: /* 128-bit register, interleaved */
efx_reado_table(efx, buf, table->offset, 2 * i);
break;
default:
WARN_ON(1);
return;
}
buf += size;
}
}
}
/**
* efx_nic_describe_stats - Describe supported statistics for ethtool
* @desc: Array of &struct efx_hw_stat_desc describing the statistics
* @count: Length of the @desc array
* @mask: Bitmask of which elements of @desc are enabled
* @names: Buffer to copy names to, or %NULL. The names are copied
* starting at intervals of %ETH_GSTRING_LEN bytes.
*
* Returns the number of visible statistics, i.e. the number of set
* bits in the first @count bits of @mask for which a name is defined.
*/
size_t efx_nic_describe_stats(const struct efx_hw_stat_desc *desc, size_t count,
const unsigned long *mask, u8 *names)
{
size_t visible = 0;
size_t index;
for_each_set_bit(index, mask, count) {
if (desc[index].name) {
if (names) {
strscpy(names, desc[index].name,
ETH_GSTRING_LEN);
names += ETH_GSTRING_LEN;
}
++visible;
}
}
return visible;
}
/**
* efx_nic_copy_stats - Copy stats from the DMA buffer in to an
* intermediate buffer. This is used to get a consistent
* set of stats while the DMA buffer can be written at any time
* by the NIC.
* @efx: The associated NIC.
* @dest: Destination buffer. Must be the same size as the DMA buffer.
*/
int efx_nic_copy_stats(struct efx_nic *efx, __le64 *dest)
{
__le64 *dma_stats = efx->stats_buffer.addr;
__le64 generation_start, generation_end;
int rc = 0, retry;
if (!dest)
return 0;
if (!dma_stats)
goto return_zeroes;
/* If we're unlucky enough to read statistics during the DMA, wait
* up to 10ms for it to finish (typically takes <500us)
*/
for (retry = 0; retry < 100; ++retry) {
generation_end = dma_stats[efx->num_mac_stats - 1];
if (generation_end == EFX_MC_STATS_GENERATION_INVALID)
goto return_zeroes;
rmb();
memcpy(dest, dma_stats, efx->num_mac_stats * sizeof(__le64));
rmb();
generation_start = dma_stats[MC_CMD_MAC_GENERATION_START];
if (generation_end == generation_start)
return 0; /* return good data */
udelay(100);
}
rc = -EIO;
return_zeroes:
memset(dest, 0, efx->num_mac_stats * sizeof(u64));
return rc;
}
/**
* efx_nic_update_stats - Convert statistics DMA buffer to array of u64
* @desc: Array of &struct efx_hw_stat_desc describing the DMA buffer
* layout. DMA widths of 0, 16, 32 and 64 are supported; where
* the width is specified as 0 the corresponding element of
* @stats is not updated.
* @count: Length of the @desc array
* @mask: Bitmask of which elements of @desc are enabled
* @stats: Buffer to update with the converted statistics. The length
* of this array must be at least @count.
* @dma_buf: DMA buffer containing hardware statistics
* @accumulate: If set, the converted values will be added rather than
* directly stored to the corresponding elements of @stats
*/
void efx_nic_update_stats(const struct efx_hw_stat_desc *desc, size_t count,
const unsigned long *mask,
u64 *stats, const void *dma_buf, bool accumulate)
{
size_t index;
for_each_set_bit(index, mask, count) {
if (desc[index].dma_width) {
const void *addr = dma_buf + desc[index].offset;
u64 val;
switch (desc[index].dma_width) {
case 16:
val = le16_to_cpup((__le16 *)addr);
break;
case 32:
val = le32_to_cpup((__le32 *)addr);
break;
case 64:
val = le64_to_cpup((__le64 *)addr);
break;
default:
WARN_ON(1);
val = 0;
break;
}
if (accumulate)
stats[index] += val;
else
stats[index] = val;
}
}
}
void efx_nic_fix_nodesc_drop_stat(struct efx_nic *efx, u64 *rx_nodesc_drops)
{
/* if down, or this is the first update after coming up */
if (!(efx->net_dev->flags & IFF_UP) || !efx->rx_nodesc_drops_prev_state)
efx->rx_nodesc_drops_while_down +=
*rx_nodesc_drops - efx->rx_nodesc_drops_total;
efx->rx_nodesc_drops_total = *rx_nodesc_drops;
efx->rx_nodesc_drops_prev_state = !!(efx->net_dev->flags & IFF_UP);
*rx_nodesc_drops -= efx->rx_nodesc_drops_while_down;
}
|
linux-master
|
drivers/net/ethernet/sfc/nic.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2011-2013 Solarflare Communications Inc.
*/
/* Theory of operation:
*
* PTP support is assisted by firmware running on the MC, which provides
* the hardware timestamping capabilities. Both transmitted and received
* PTP event packets are queued onto internal queues for subsequent processing;
* this is because the MC operations are relatively long and would block
* block NAPI/interrupt operation.
*
* Receive event processing:
* The event contains the packet's UUID and sequence number, together
* with the hardware timestamp. The PTP receive packet queue is searched
* for this UUID/sequence number and, if found, put on a pending queue.
* Packets not matching are delivered without timestamps (MCDI events will
* always arrive after the actual packet).
* It is important for the operation of the PTP protocol that the ordering
* of packets between the event and general port is maintained.
*
* Work queue processing:
* If work waiting, synchronise host/hardware time
*
* Transmit: send packet through MC, which returns the transmission time
* that is converted to an appropriate timestamp.
*
* Receive: the packet's reception time is converted to an appropriate
* timestamp.
*/
#include <linux/ip.h>
#include <linux/udp.h>
#include <linux/time.h>
#include <linux/errno.h>
#include <linux/ktime.h>
#include <linux/module.h>
#include <linux/pps_kernel.h>
#include <linux/ptp_clock_kernel.h>
#include "net_driver.h"
#include "efx.h"
#include "mcdi.h"
#include "mcdi_pcol.h"
#include "io.h"
#include "tx.h"
#include "nic.h" /* indirectly includes ptp.h */
#include "efx_channels.h"
/* Maximum number of events expected to make up a PTP event */
#define MAX_EVENT_FRAGS 3
/* Maximum delay, ms, to begin synchronisation */
#define MAX_SYNCHRONISE_WAIT_MS 2
/* How long, at most, to spend synchronising */
#define SYNCHRONISE_PERIOD_NS 250000
/* How often to update the shared memory time */
#define SYNCHRONISATION_GRANULARITY_NS 200
/* Minimum permitted length of a (corrected) synchronisation time */
#define DEFAULT_MIN_SYNCHRONISATION_NS 120
/* Maximum permitted length of a (corrected) synchronisation time */
#define MAX_SYNCHRONISATION_NS 1000
/* How many (MC) receive events that can be queued */
#define MAX_RECEIVE_EVENTS 8
/* Length of (modified) moving average. */
#define AVERAGE_LENGTH 16
/* How long an unmatched event or packet can be held */
#define PKT_EVENT_LIFETIME_MS 10
/* How long unused unicast filters can be held */
#define UCAST_FILTER_EXPIRY_JIFFIES msecs_to_jiffies(30000)
/* Offsets into PTP packet for identification. These offsets are from the
* start of the IP header, not the MAC header. Note that neither PTP V1 nor
* PTP V2 permit the use of IPV4 options.
*/
#define PTP_DPORT_OFFSET 22
#define PTP_V1_VERSION_LENGTH 2
#define PTP_V1_VERSION_OFFSET 28
#define PTP_V1_SEQUENCE_LENGTH 2
#define PTP_V1_SEQUENCE_OFFSET 58
/* The minimum length of a PTP V1 packet for offsets, etc. to be valid:
* includes IP header.
*/
#define PTP_V1_MIN_LENGTH 64
#define PTP_V2_VERSION_LENGTH 1
#define PTP_V2_VERSION_OFFSET 29
#define PTP_V2_SEQUENCE_LENGTH 2
#define PTP_V2_SEQUENCE_OFFSET 58
/* The minimum length of a PTP V2 packet for offsets, etc. to be valid:
* includes IP header.
*/
#define PTP_V2_MIN_LENGTH 63
#define PTP_MIN_LENGTH 63
#define PTP_ADDR_IPV4 0xe0000181 /* 224.0.1.129 */
#define PTP_ADDR_IPV6 {0xff, 0x0e, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
0, 0x01, 0x81} /* ff0e::181 */
#define PTP_EVENT_PORT 319
#define PTP_GENERAL_PORT 320
#define PTP_ADDR_ETHER {0x01, 0x1b, 0x19, 0, 0, 0} /* 01-1B-19-00-00-00 */
/* Annoyingly the format of the version numbers are different between
* versions 1 and 2 so it isn't possible to simply look for 1 or 2.
*/
#define PTP_VERSION_V1 1
#define PTP_VERSION_V2 2
#define PTP_VERSION_V2_MASK 0x0f
enum ptp_packet_state {
PTP_PACKET_STATE_UNMATCHED = 0,
PTP_PACKET_STATE_MATCHED,
PTP_PACKET_STATE_TIMED_OUT,
PTP_PACKET_STATE_MATCH_UNWANTED
};
/* NIC synchronised with single word of time only comprising
* partial seconds and full nanoseconds: 10^9 ~ 2^30 so 2 bits for seconds.
*/
#define MC_NANOSECOND_BITS 30
#define MC_NANOSECOND_MASK ((1 << MC_NANOSECOND_BITS) - 1)
#define MC_SECOND_MASK ((1 << (32 - MC_NANOSECOND_BITS)) - 1)
/* Maximum parts-per-billion adjustment that is acceptable */
#define MAX_PPB 1000000
/* Precalculate scale word to avoid long long division at runtime */
/* This is equivalent to 2^66 / 10^9. */
#define PPB_SCALE_WORD ((1LL << (57)) / 1953125LL)
/* How much to shift down after scaling to convert to FP40 */
#define PPB_SHIFT_FP40 26
/* ... and FP44. */
#define PPB_SHIFT_FP44 22
#define PTP_SYNC_ATTEMPTS 4
/**
* struct efx_ptp_match - Matching structure, stored in sk_buff's cb area.
* @expiry: Time after which the packet should be delivered irrespective of
* event arrival.
* @state: The state of the packet - whether it is ready for processing or
* whether that is of no interest.
*/
struct efx_ptp_match {
unsigned long expiry;
enum ptp_packet_state state;
};
/**
* struct efx_ptp_event_rx - A PTP receive event (from MC)
* @link: list of events
* @seq0: First part of (PTP) UUID
* @seq1: Second part of (PTP) UUID and sequence number
* @hwtimestamp: Event timestamp
* @expiry: Time which the packet arrived
*/
struct efx_ptp_event_rx {
struct list_head link;
u32 seq0;
u32 seq1;
ktime_t hwtimestamp;
unsigned long expiry;
};
/**
* struct efx_ptp_timeset - Synchronisation between host and MC
* @host_start: Host time immediately before hardware timestamp taken
* @major: Hardware timestamp, major
* @minor: Hardware timestamp, minor
* @host_end: Host time immediately after hardware timestamp taken
* @wait: Number of NIC clock ticks between hardware timestamp being read and
* host end time being seen
* @window: Difference of host_end and host_start
* @valid: Whether this timeset is valid
*/
struct efx_ptp_timeset {
u32 host_start;
u32 major;
u32 minor;
u32 host_end;
u32 wait;
u32 window; /* Derived: end - start, allowing for wrap */
};
/**
* struct efx_ptp_rxfilter - Filter for PTP packets
* @list: Node of the list where the filter is added
* @ether_type: Network protocol of the filter (ETHER_P_IP / ETHER_P_IPV6)
* @loc_port: UDP port of the filter (PTP_EVENT_PORT / PTP_GENERAL_PORT)
* @loc_host: IPv4/v6 address of the filter
* @expiry: time when the filter expires, in jiffies
* @handle: Handle ID for the MCDI filters table
*/
struct efx_ptp_rxfilter {
struct list_head list;
__be16 ether_type;
__be16 loc_port;
__be32 loc_host[4];
unsigned long expiry;
int handle;
};
/**
* struct efx_ptp_data - Precision Time Protocol (PTP) state
* @efx: The NIC context
* @channel: The PTP channel (for Medford and Medford2)
* @rxq: Receive SKB queue (awaiting timestamps)
* @txq: Transmit SKB queue
* @workwq: Work queue for processing pending PTP operations
* @work: Work task
* @cleanup_work: Work task for periodic cleanup
* @reset_required: A serious error has occurred and the PTP task needs to be
* reset (disable, enable).
* @rxfilters_mcast: Receive filters for multicast PTP packets
* @rxfilters_ucast: Receive filters for unicast PTP packets
* @config: Current timestamp configuration
* @enabled: PTP operation enabled
* @mode: Mode in which PTP operating (PTP version)
* @ns_to_nic_time: Function to convert from scalar nanoseconds to NIC time
* @nic_to_kernel_time: Function to convert from NIC to kernel time
* @nic_time: contains time details
* @nic_time.minor_max: Wrap point for NIC minor times
* @nic_time.sync_event_diff_min: Minimum acceptable difference between time
* in packet prefix and last MCDI time sync event i.e. how much earlier than
* the last sync event time a packet timestamp can be.
* @nic_time.sync_event_diff_max: Maximum acceptable difference between time
* in packet prefix and last MCDI time sync event i.e. how much later than
* the last sync event time a packet timestamp can be.
* @nic_time.sync_event_minor_shift: Shift required to make minor time from
* field in MCDI time sync event.
* @min_synchronisation_ns: Minimum acceptable corrected sync window
* @capabilities: Capabilities flags from the NIC
* @ts_corrections: contains corrections details
* @ts_corrections.ptp_tx: Required driver correction of PTP packet transmit
* timestamps
* @ts_corrections.ptp_rx: Required driver correction of PTP packet receive
* timestamps
* @ts_corrections.pps_out: PPS output error (information only)
* @ts_corrections.pps_in: Required driver correction of PPS input timestamps
* @ts_corrections.general_tx: Required driver correction of general packet
* transmit timestamps
* @ts_corrections.general_rx: Required driver correction of general packet
* receive timestamps
* @evt_frags: Partly assembled PTP events
* @evt_frag_idx: Current fragment number
* @evt_code: Last event code
* @start: Address at which MC indicates ready for synchronisation
* @host_time_pps: Host time at last PPS
* @adjfreq_ppb_shift: Shift required to convert scaled parts-per-billion
* frequency adjustment into a fixed point fractional nanosecond format.
* @current_adjfreq: Current ppb adjustment.
* @phc_clock: Pointer to registered phc device (if primary function)
* @phc_clock_info: Registration structure for phc device
* @pps_work: pps work task for handling pps events
* @pps_workwq: pps work queue
* @nic_ts_enabled: Flag indicating if NIC generated TS events are handled
* @txbuf: Buffer for use when transmitting (PTP) packets to MC (avoids
* allocations in main data path).
* @good_syncs: Number of successful synchronisations.
* @fast_syncs: Number of synchronisations requiring short delay
* @bad_syncs: Number of failed synchronisations.
* @sync_timeouts: Number of synchronisation timeouts
* @no_time_syncs: Number of synchronisations with no good times.
* @invalid_sync_windows: Number of sync windows with bad durations.
* @undersize_sync_windows: Number of corrected sync windows that are too small
* @oversize_sync_windows: Number of corrected sync windows that are too large
* @rx_no_timestamp: Number of packets received without a timestamp.
* @timeset: Last set of synchronisation statistics.
* @xmit_skb: Transmit SKB function.
*/
struct efx_ptp_data {
struct efx_nic *efx;
struct efx_channel *channel;
struct sk_buff_head rxq;
struct sk_buff_head txq;
struct workqueue_struct *workwq;
struct work_struct work;
struct delayed_work cleanup_work;
bool reset_required;
struct list_head rxfilters_mcast;
struct list_head rxfilters_ucast;
struct hwtstamp_config config;
bool enabled;
unsigned int mode;
void (*ns_to_nic_time)(s64 ns, u32 *nic_major, u32 *nic_minor);
ktime_t (*nic_to_kernel_time)(u32 nic_major, u32 nic_minor,
s32 correction);
struct {
u32 minor_max;
u32 sync_event_diff_min;
u32 sync_event_diff_max;
unsigned int sync_event_minor_shift;
} nic_time;
unsigned int min_synchronisation_ns;
unsigned int capabilities;
struct {
s32 ptp_tx;
s32 ptp_rx;
s32 pps_out;
s32 pps_in;
s32 general_tx;
s32 general_rx;
} ts_corrections;
efx_qword_t evt_frags[MAX_EVENT_FRAGS];
int evt_frag_idx;
int evt_code;
struct efx_buffer start;
struct pps_event_time host_time_pps;
unsigned int adjfreq_ppb_shift;
s64 current_adjfreq;
struct ptp_clock *phc_clock;
struct ptp_clock_info phc_clock_info;
struct work_struct pps_work;
struct workqueue_struct *pps_workwq;
bool nic_ts_enabled;
efx_dword_t txbuf[MCDI_TX_BUF_LEN(MC_CMD_PTP_IN_TRANSMIT_LENMAX)];
unsigned int good_syncs;
unsigned int fast_syncs;
unsigned int bad_syncs;
unsigned int sync_timeouts;
unsigned int no_time_syncs;
unsigned int invalid_sync_windows;
unsigned int undersize_sync_windows;
unsigned int oversize_sync_windows;
unsigned int rx_no_timestamp;
struct efx_ptp_timeset
timeset[MC_CMD_PTP_OUT_SYNCHRONIZE_TIMESET_MAXNUM];
void (*xmit_skb)(struct efx_nic *efx, struct sk_buff *skb);
};
static int efx_phc_adjfine(struct ptp_clock_info *ptp, long scaled_ppm);
static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta);
static int efx_phc_gettime(struct ptp_clock_info *ptp, struct timespec64 *ts);
static int efx_phc_settime(struct ptp_clock_info *ptp,
const struct timespec64 *e_ts);
static int efx_phc_enable(struct ptp_clock_info *ptp,
struct ptp_clock_request *request, int on);
static int efx_ptp_insert_unicast_filter(struct efx_nic *efx,
struct sk_buff *skb);
bool efx_ptp_use_mac_tx_timestamps(struct efx_nic *efx)
{
return efx_has_cap(efx, TX_MAC_TIMESTAMPING);
}
/* PTP 'extra' channel is still a traffic channel, but we only create TX queues
* if PTP uses MAC TX timestamps, not if PTP uses the MC directly to transmit.
*/
static bool efx_ptp_want_txqs(struct efx_channel *channel)
{
return efx_ptp_use_mac_tx_timestamps(channel->efx);
}
#define PTP_SW_STAT(ext_name, field_name) \
{ #ext_name, 0, offsetof(struct efx_ptp_data, field_name) }
#define PTP_MC_STAT(ext_name, mcdi_name) \
{ #ext_name, 32, MC_CMD_PTP_OUT_STATUS_STATS_ ## mcdi_name ## _OFST }
static const struct efx_hw_stat_desc efx_ptp_stat_desc[] = {
PTP_SW_STAT(ptp_good_syncs, good_syncs),
PTP_SW_STAT(ptp_fast_syncs, fast_syncs),
PTP_SW_STAT(ptp_bad_syncs, bad_syncs),
PTP_SW_STAT(ptp_sync_timeouts, sync_timeouts),
PTP_SW_STAT(ptp_no_time_syncs, no_time_syncs),
PTP_SW_STAT(ptp_invalid_sync_windows, invalid_sync_windows),
PTP_SW_STAT(ptp_undersize_sync_windows, undersize_sync_windows),
PTP_SW_STAT(ptp_oversize_sync_windows, oversize_sync_windows),
PTP_SW_STAT(ptp_rx_no_timestamp, rx_no_timestamp),
PTP_MC_STAT(ptp_tx_timestamp_packets, TX),
PTP_MC_STAT(ptp_rx_timestamp_packets, RX),
PTP_MC_STAT(ptp_timestamp_packets, TS),
PTP_MC_STAT(ptp_filter_matches, FM),
PTP_MC_STAT(ptp_non_filter_matches, NFM),
};
#define PTP_STAT_COUNT ARRAY_SIZE(efx_ptp_stat_desc)
static const unsigned long efx_ptp_stat_mask[] = {
[0 ... BITS_TO_LONGS(PTP_STAT_COUNT) - 1] = ~0UL,
};
size_t efx_ptp_describe_stats(struct efx_nic *efx, u8 *strings)
{
if (!efx->ptp_data)
return 0;
return efx_nic_describe_stats(efx_ptp_stat_desc, PTP_STAT_COUNT,
efx_ptp_stat_mask, strings);
}
size_t efx_ptp_update_stats(struct efx_nic *efx, u64 *stats)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_STATUS_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_PTP_OUT_STATUS_LEN);
size_t i;
int rc;
if (!efx->ptp_data)
return 0;
/* Copy software statistics */
for (i = 0; i < PTP_STAT_COUNT; i++) {
if (efx_ptp_stat_desc[i].dma_width)
continue;
stats[i] = *(unsigned int *)((char *)efx->ptp_data +
efx_ptp_stat_desc[i].offset);
}
/* Fetch MC statistics. We *must* fill in all statistics or
* risk leaking kernel memory to userland, so if the MCDI
* request fails we pretend we got zeroes.
*/
MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_STATUS);
MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
rc = efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), NULL);
if (rc)
memset(outbuf, 0, sizeof(outbuf));
efx_nic_update_stats(efx_ptp_stat_desc, PTP_STAT_COUNT,
efx_ptp_stat_mask,
stats, _MCDI_PTR(outbuf, 0), false);
return PTP_STAT_COUNT;
}
/* To convert from s27 format to ns we multiply then divide by a power of 2.
* For the conversion from ns to s27, the operation is also converted to a
* multiply and shift.
*/
#define S27_TO_NS_SHIFT (27)
#define NS_TO_S27_MULT (((1ULL << 63) + NSEC_PER_SEC / 2) / NSEC_PER_SEC)
#define NS_TO_S27_SHIFT (63 - S27_TO_NS_SHIFT)
#define S27_MINOR_MAX (1 << S27_TO_NS_SHIFT)
/* For Huntington platforms NIC time is in seconds and fractions of a second
* where the minor register only uses 27 bits in units of 2^-27s.
*/
static void efx_ptp_ns_to_s27(s64 ns, u32 *nic_major, u32 *nic_minor)
{
struct timespec64 ts = ns_to_timespec64(ns);
u32 maj = (u32)ts.tv_sec;
u32 min = (u32)(((u64)ts.tv_nsec * NS_TO_S27_MULT +
(1ULL << (NS_TO_S27_SHIFT - 1))) >> NS_TO_S27_SHIFT);
/* The conversion can result in the minor value exceeding the maximum.
* In this case, round up to the next second.
*/
if (min >= S27_MINOR_MAX) {
min -= S27_MINOR_MAX;
maj++;
}
*nic_major = maj;
*nic_minor = min;
}
static inline ktime_t efx_ptp_s27_to_ktime(u32 nic_major, u32 nic_minor)
{
u32 ns = (u32)(((u64)nic_minor * NSEC_PER_SEC +
(1ULL << (S27_TO_NS_SHIFT - 1))) >> S27_TO_NS_SHIFT);
return ktime_set(nic_major, ns);
}
static ktime_t efx_ptp_s27_to_ktime_correction(u32 nic_major, u32 nic_minor,
s32 correction)
{
/* Apply the correction and deal with carry */
nic_minor += correction;
if ((s32)nic_minor < 0) {
nic_minor += S27_MINOR_MAX;
nic_major--;
} else if (nic_minor >= S27_MINOR_MAX) {
nic_minor -= S27_MINOR_MAX;
nic_major++;
}
return efx_ptp_s27_to_ktime(nic_major, nic_minor);
}
/* For Medford2 platforms the time is in seconds and quarter nanoseconds. */
static void efx_ptp_ns_to_s_qns(s64 ns, u32 *nic_major, u32 *nic_minor)
{
struct timespec64 ts = ns_to_timespec64(ns);
*nic_major = (u32)ts.tv_sec;
*nic_minor = ts.tv_nsec * 4;
}
static ktime_t efx_ptp_s_qns_to_ktime_correction(u32 nic_major, u32 nic_minor,
s32 correction)
{
ktime_t kt;
nic_minor = DIV_ROUND_CLOSEST(nic_minor, 4);
correction = DIV_ROUND_CLOSEST(correction, 4);
kt = ktime_set(nic_major, nic_minor);
if (correction >= 0)
kt = ktime_add_ns(kt, (u64)correction);
else
kt = ktime_sub_ns(kt, (u64)-correction);
return kt;
}
struct efx_channel *efx_ptp_channel(struct efx_nic *efx)
{
return efx->ptp_data ? efx->ptp_data->channel : NULL;
}
void efx_ptp_update_channel(struct efx_nic *efx, struct efx_channel *channel)
{
if (efx->ptp_data)
efx->ptp_data->channel = channel;
}
static u32 last_sync_timestamp_major(struct efx_nic *efx)
{
struct efx_channel *channel = efx_ptp_channel(efx);
u32 major = 0;
if (channel)
major = channel->sync_timestamp_major;
return major;
}
/* The 8000 series and later can provide the time from the MAC, which is only
* 48 bits long and provides meta-information in the top 2 bits.
*/
static ktime_t
efx_ptp_mac_nic_to_ktime_correction(struct efx_nic *efx,
struct efx_ptp_data *ptp,
u32 nic_major, u32 nic_minor,
s32 correction)
{
u32 sync_timestamp;
ktime_t kt = { 0 };
s16 delta;
if (!(nic_major & 0x80000000)) {
WARN_ON_ONCE(nic_major >> 16);
/* Medford provides 48 bits of timestamp, so we must get the top
* 16 bits from the timesync event state.
*
* We only have the lower 16 bits of the time now, but we do
* have a full resolution timestamp at some point in past. As
* long as the difference between the (real) now and the sync
* is less than 2^15, then we can reconstruct the difference
* between those two numbers using only the lower 16 bits of
* each.
*
* Put another way
*
* a - b = ((a mod k) - b) mod k
*
* when -k/2 < (a-b) < k/2. In our case k is 2^16. We know
* (a mod k) and b, so can calculate the delta, a - b.
*
*/
sync_timestamp = last_sync_timestamp_major(efx);
/* Because delta is s16 this does an implicit mask down to
* 16 bits which is what we need, assuming
* MEDFORD_TX_SECS_EVENT_BITS is 16. delta is signed so that
* we can deal with the (unlikely) case of sync timestamps
* arriving from the future.
*/
delta = nic_major - sync_timestamp;
/* Recover the fully specified time now, by applying the offset
* to the (fully specified) sync time.
*/
nic_major = sync_timestamp + delta;
kt = ptp->nic_to_kernel_time(nic_major, nic_minor,
correction);
}
return kt;
}
ktime_t efx_ptp_nic_to_kernel_time(struct efx_tx_queue *tx_queue)
{
struct efx_nic *efx = tx_queue->efx;
struct efx_ptp_data *ptp = efx->ptp_data;
ktime_t kt;
if (efx_ptp_use_mac_tx_timestamps(efx))
kt = efx_ptp_mac_nic_to_ktime_correction(efx, ptp,
tx_queue->completed_timestamp_major,
tx_queue->completed_timestamp_minor,
ptp->ts_corrections.general_tx);
else
kt = ptp->nic_to_kernel_time(
tx_queue->completed_timestamp_major,
tx_queue->completed_timestamp_minor,
ptp->ts_corrections.general_tx);
return kt;
}
/* Get PTP attributes and set up time conversions */
static int efx_ptp_get_attributes(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_GET_ATTRIBUTES_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_PTP_OUT_GET_ATTRIBUTES_LEN);
struct efx_ptp_data *ptp = efx->ptp_data;
int rc;
u32 fmt;
size_t out_len;
/* Get the PTP attributes. If the NIC doesn't support the operation we
* use the default format for compatibility with older NICs i.e.
* seconds and nanoseconds.
*/
MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_GET_ATTRIBUTES);
MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &out_len);
if (rc == 0) {
fmt = MCDI_DWORD(outbuf, PTP_OUT_GET_ATTRIBUTES_TIME_FORMAT);
} else if (rc == -EINVAL) {
fmt = MC_CMD_PTP_OUT_GET_ATTRIBUTES_SECONDS_NANOSECONDS;
} else if (rc == -EPERM) {
pci_info(efx->pci_dev, "no PTP support\n");
return rc;
} else {
efx_mcdi_display_error(efx, MC_CMD_PTP, sizeof(inbuf),
outbuf, sizeof(outbuf), rc);
return rc;
}
switch (fmt) {
case MC_CMD_PTP_OUT_GET_ATTRIBUTES_SECONDS_27FRACTION:
ptp->ns_to_nic_time = efx_ptp_ns_to_s27;
ptp->nic_to_kernel_time = efx_ptp_s27_to_ktime_correction;
ptp->nic_time.minor_max = 1 << 27;
ptp->nic_time.sync_event_minor_shift = 19;
break;
case MC_CMD_PTP_OUT_GET_ATTRIBUTES_SECONDS_QTR_NANOSECONDS:
ptp->ns_to_nic_time = efx_ptp_ns_to_s_qns;
ptp->nic_to_kernel_time = efx_ptp_s_qns_to_ktime_correction;
ptp->nic_time.minor_max = 4000000000UL;
ptp->nic_time.sync_event_minor_shift = 24;
break;
default:
return -ERANGE;
}
/* Precalculate acceptable difference between the minor time in the
* packet prefix and the last MCDI time sync event. We expect the
* packet prefix timestamp to be after of sync event by up to one
* sync event interval (0.25s) but we allow it to exceed this by a
* fuzz factor of (0.1s)
*/
ptp->nic_time.sync_event_diff_min = ptp->nic_time.minor_max
- (ptp->nic_time.minor_max / 10);
ptp->nic_time.sync_event_diff_max = (ptp->nic_time.minor_max / 4)
+ (ptp->nic_time.minor_max / 10);
/* MC_CMD_PTP_OP_GET_ATTRIBUTES has been extended twice from an older
* operation MC_CMD_PTP_OP_GET_TIME_FORMAT. The function now may return
* a value to use for the minimum acceptable corrected synchronization
* window and may return further capabilities.
* If we have the extra information store it. For older firmware that
* does not implement the extended command use the default value.
*/
if (rc == 0 &&
out_len >= MC_CMD_PTP_OUT_GET_ATTRIBUTES_CAPABILITIES_OFST)
ptp->min_synchronisation_ns =
MCDI_DWORD(outbuf,
PTP_OUT_GET_ATTRIBUTES_SYNC_WINDOW_MIN);
else
ptp->min_synchronisation_ns = DEFAULT_MIN_SYNCHRONISATION_NS;
if (rc == 0 &&
out_len >= MC_CMD_PTP_OUT_GET_ATTRIBUTES_LEN)
ptp->capabilities = MCDI_DWORD(outbuf,
PTP_OUT_GET_ATTRIBUTES_CAPABILITIES);
else
ptp->capabilities = 0;
/* Set up the shift for conversion between frequency
* adjustments in parts-per-billion and the fixed-point
* fractional ns format that the adapter uses.
*/
if (ptp->capabilities & (1 << MC_CMD_PTP_OUT_GET_ATTRIBUTES_FP44_FREQ_ADJ_LBN))
ptp->adjfreq_ppb_shift = PPB_SHIFT_FP44;
else
ptp->adjfreq_ppb_shift = PPB_SHIFT_FP40;
return 0;
}
/* Get PTP timestamp corrections */
static int efx_ptp_get_timestamp_corrections(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_GET_TIMESTAMP_CORRECTIONS_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_PTP_OUT_GET_TIMESTAMP_CORRECTIONS_V2_LEN);
int rc;
size_t out_len;
/* Get the timestamp corrections from the NIC. If this operation is
* not supported (older NICs) then no correction is required.
*/
MCDI_SET_DWORD(inbuf, PTP_IN_OP,
MC_CMD_PTP_OP_GET_TIMESTAMP_CORRECTIONS);
MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &out_len);
if (rc == 0) {
efx->ptp_data->ts_corrections.ptp_tx = MCDI_DWORD(outbuf,
PTP_OUT_GET_TIMESTAMP_CORRECTIONS_TRANSMIT);
efx->ptp_data->ts_corrections.ptp_rx = MCDI_DWORD(outbuf,
PTP_OUT_GET_TIMESTAMP_CORRECTIONS_RECEIVE);
efx->ptp_data->ts_corrections.pps_out = MCDI_DWORD(outbuf,
PTP_OUT_GET_TIMESTAMP_CORRECTIONS_PPS_OUT);
efx->ptp_data->ts_corrections.pps_in = MCDI_DWORD(outbuf,
PTP_OUT_GET_TIMESTAMP_CORRECTIONS_PPS_IN);
if (out_len >= MC_CMD_PTP_OUT_GET_TIMESTAMP_CORRECTIONS_V2_LEN) {
efx->ptp_data->ts_corrections.general_tx = MCDI_DWORD(
outbuf,
PTP_OUT_GET_TIMESTAMP_CORRECTIONS_V2_GENERAL_TX);
efx->ptp_data->ts_corrections.general_rx = MCDI_DWORD(
outbuf,
PTP_OUT_GET_TIMESTAMP_CORRECTIONS_V2_GENERAL_RX);
} else {
efx->ptp_data->ts_corrections.general_tx =
efx->ptp_data->ts_corrections.ptp_tx;
efx->ptp_data->ts_corrections.general_rx =
efx->ptp_data->ts_corrections.ptp_rx;
}
} else if (rc == -EINVAL) {
efx->ptp_data->ts_corrections.ptp_tx = 0;
efx->ptp_data->ts_corrections.ptp_rx = 0;
efx->ptp_data->ts_corrections.pps_out = 0;
efx->ptp_data->ts_corrections.pps_in = 0;
efx->ptp_data->ts_corrections.general_tx = 0;
efx->ptp_data->ts_corrections.general_rx = 0;
} else {
efx_mcdi_display_error(efx, MC_CMD_PTP, sizeof(inbuf), outbuf,
sizeof(outbuf), rc);
return rc;
}
return 0;
}
/* Enable MCDI PTP support. */
static int efx_ptp_enable(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_ENABLE_LEN);
MCDI_DECLARE_BUF_ERR(outbuf);
int rc;
MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_ENABLE);
MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
MCDI_SET_DWORD(inbuf, PTP_IN_ENABLE_QUEUE,
efx->ptp_data->channel ?
efx->ptp_data->channel->channel : 0);
MCDI_SET_DWORD(inbuf, PTP_IN_ENABLE_MODE, efx->ptp_data->mode);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), NULL);
rc = (rc == -EALREADY) ? 0 : rc;
if (rc)
efx_mcdi_display_error(efx, MC_CMD_PTP,
MC_CMD_PTP_IN_ENABLE_LEN,
outbuf, sizeof(outbuf), rc);
return rc;
}
/* Disable MCDI PTP support.
*
* Note that this function should never rely on the presence of ptp_data -
* may be called before that exists.
*/
static int efx_ptp_disable(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_DISABLE_LEN);
MCDI_DECLARE_BUF_ERR(outbuf);
int rc;
MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_DISABLE);
MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), NULL);
rc = (rc == -EALREADY) ? 0 : rc;
/* If we get ENOSYS, the NIC doesn't support PTP, and thus this function
* should only have been called during probe.
*/
if (rc == -ENOSYS || rc == -EPERM)
pci_info(efx->pci_dev, "no PTP support\n");
else if (rc)
efx_mcdi_display_error(efx, MC_CMD_PTP,
MC_CMD_PTP_IN_DISABLE_LEN,
outbuf, sizeof(outbuf), rc);
return rc;
}
static void efx_ptp_deliver_rx_queue(struct sk_buff_head *q)
{
struct sk_buff *skb;
while ((skb = skb_dequeue(q))) {
local_bh_disable();
netif_receive_skb(skb);
local_bh_enable();
}
}
static void efx_ptp_handle_no_channel(struct efx_nic *efx)
{
netif_err(efx, drv, efx->net_dev,
"ERROR: PTP requires MSI-X and 1 additional interrupt"
"vector. PTP disabled\n");
}
/* Repeatedly send the host time to the MC which will capture the hardware
* time.
*/
static void efx_ptp_send_times(struct efx_nic *efx,
struct pps_event_time *last_time)
{
struct pps_event_time now;
struct timespec64 limit;
struct efx_ptp_data *ptp = efx->ptp_data;
int *mc_running = ptp->start.addr;
pps_get_ts(&now);
limit = now.ts_real;
timespec64_add_ns(&limit, SYNCHRONISE_PERIOD_NS);
/* Write host time for specified period or until MC is done */
while ((timespec64_compare(&now.ts_real, &limit) < 0) &&
READ_ONCE(*mc_running)) {
struct timespec64 update_time;
unsigned int host_time;
/* Don't update continuously to avoid saturating the PCIe bus */
update_time = now.ts_real;
timespec64_add_ns(&update_time, SYNCHRONISATION_GRANULARITY_NS);
do {
pps_get_ts(&now);
} while ((timespec64_compare(&now.ts_real, &update_time) < 0) &&
READ_ONCE(*mc_running));
/* Synchronise NIC with single word of time only */
host_time = (now.ts_real.tv_sec << MC_NANOSECOND_BITS |
now.ts_real.tv_nsec);
/* Update host time in NIC memory */
efx->type->ptp_write_host_time(efx, host_time);
}
*last_time = now;
}
/* Read a timeset from the MC's results and partial process. */
static void efx_ptp_read_timeset(MCDI_DECLARE_STRUCT_PTR(data),
struct efx_ptp_timeset *timeset)
{
unsigned start_ns, end_ns;
timeset->host_start = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_HOSTSTART);
timeset->major = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_MAJOR);
timeset->minor = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_MINOR);
timeset->host_end = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_HOSTEND),
timeset->wait = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_WAITNS);
/* Ignore seconds */
start_ns = timeset->host_start & MC_NANOSECOND_MASK;
end_ns = timeset->host_end & MC_NANOSECOND_MASK;
/* Allow for rollover */
if (end_ns < start_ns)
end_ns += NSEC_PER_SEC;
/* Determine duration of operation */
timeset->window = end_ns - start_ns;
}
/* Process times received from MC.
*
* Extract times from returned results, and establish the minimum value
* seen. The minimum value represents the "best" possible time and events
* too much greater than this are rejected - the machine is, perhaps, too
* busy. A number of readings are taken so that, hopefully, at least one good
* synchronisation will be seen in the results.
*/
static int
efx_ptp_process_times(struct efx_nic *efx, MCDI_DECLARE_STRUCT_PTR(synch_buf),
size_t response_length,
const struct pps_event_time *last_time)
{
unsigned number_readings =
MCDI_VAR_ARRAY_LEN(response_length,
PTP_OUT_SYNCHRONIZE_TIMESET);
unsigned i;
unsigned ngood = 0;
unsigned last_good = 0;
struct efx_ptp_data *ptp = efx->ptp_data;
u32 last_sec;
u32 start_sec;
struct timespec64 delta;
ktime_t mc_time;
if (number_readings == 0)
return -EAGAIN;
/* Read the set of results and find the last good host-MC
* synchronization result. The MC times when it finishes reading the
* host time so the corrected window time should be fairly constant
* for a given platform. Increment stats for any results that appear
* to be erroneous.
*/
for (i = 0; i < number_readings; i++) {
s32 window, corrected;
struct timespec64 wait;
efx_ptp_read_timeset(
MCDI_ARRAY_STRUCT_PTR(synch_buf,
PTP_OUT_SYNCHRONIZE_TIMESET, i),
&ptp->timeset[i]);
wait = ktime_to_timespec64(
ptp->nic_to_kernel_time(0, ptp->timeset[i].wait, 0));
window = ptp->timeset[i].window;
corrected = window - wait.tv_nsec;
/* We expect the uncorrected synchronization window to be at
* least as large as the interval between host start and end
* times. If it is smaller than this then this is mostly likely
* to be a consequence of the host's time being adjusted.
* Check that the corrected sync window is in a reasonable
* range. If it is out of range it is likely to be because an
* interrupt or other delay occurred between reading the system
* time and writing it to MC memory.
*/
if (window < SYNCHRONISATION_GRANULARITY_NS) {
++ptp->invalid_sync_windows;
} else if (corrected >= MAX_SYNCHRONISATION_NS) {
++ptp->oversize_sync_windows;
} else if (corrected < ptp->min_synchronisation_ns) {
++ptp->undersize_sync_windows;
} else {
ngood++;
last_good = i;
}
}
if (ngood == 0) {
netif_warn(efx, drv, efx->net_dev,
"PTP no suitable synchronisations\n");
return -EAGAIN;
}
/* Calculate delay from last good sync (host time) to last_time.
* It is possible that the seconds rolled over between taking
* the start reading and the last value written by the host. The
* timescales are such that a gap of more than one second is never
* expected. delta is *not* normalised.
*/
start_sec = ptp->timeset[last_good].host_start >> MC_NANOSECOND_BITS;
last_sec = last_time->ts_real.tv_sec & MC_SECOND_MASK;
if (start_sec != last_sec &&
((start_sec + 1) & MC_SECOND_MASK) != last_sec) {
netif_warn(efx, hw, efx->net_dev,
"PTP bad synchronisation seconds\n");
return -EAGAIN;
}
delta.tv_sec = (last_sec - start_sec) & 1;
delta.tv_nsec =
last_time->ts_real.tv_nsec -
(ptp->timeset[last_good].host_start & MC_NANOSECOND_MASK);
/* Convert the NIC time at last good sync into kernel time.
* No correction is required - this time is the output of a
* firmware process.
*/
mc_time = ptp->nic_to_kernel_time(ptp->timeset[last_good].major,
ptp->timeset[last_good].minor, 0);
/* Calculate delay from NIC top of second to last_time */
delta.tv_nsec += ktime_to_timespec64(mc_time).tv_nsec;
/* Set PPS timestamp to match NIC top of second */
ptp->host_time_pps = *last_time;
pps_sub_ts(&ptp->host_time_pps, delta);
return 0;
}
/* Synchronize times between the host and the MC */
static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings)
{
struct efx_ptp_data *ptp = efx->ptp_data;
MCDI_DECLARE_BUF(synch_buf, MC_CMD_PTP_OUT_SYNCHRONIZE_LENMAX);
size_t response_length;
int rc;
unsigned long timeout;
struct pps_event_time last_time = {};
unsigned int loops = 0;
int *start = ptp->start.addr;
MCDI_SET_DWORD(synch_buf, PTP_IN_OP, MC_CMD_PTP_OP_SYNCHRONIZE);
MCDI_SET_DWORD(synch_buf, PTP_IN_PERIPH_ID, 0);
MCDI_SET_DWORD(synch_buf, PTP_IN_SYNCHRONIZE_NUMTIMESETS,
num_readings);
MCDI_SET_QWORD(synch_buf, PTP_IN_SYNCHRONIZE_START_ADDR,
ptp->start.dma_addr);
/* Clear flag that signals MC ready */
WRITE_ONCE(*start, 0);
rc = efx_mcdi_rpc_start(efx, MC_CMD_PTP, synch_buf,
MC_CMD_PTP_IN_SYNCHRONIZE_LEN);
EFX_WARN_ON_ONCE_PARANOID(rc);
/* Wait for start from MCDI (or timeout) */
timeout = jiffies + msecs_to_jiffies(MAX_SYNCHRONISE_WAIT_MS);
while (!READ_ONCE(*start) && (time_before(jiffies, timeout))) {
udelay(20); /* Usually start MCDI execution quickly */
loops++;
}
if (loops <= 1)
++ptp->fast_syncs;
if (!time_before(jiffies, timeout))
++ptp->sync_timeouts;
if (READ_ONCE(*start))
efx_ptp_send_times(efx, &last_time);
/* Collect results */
rc = efx_mcdi_rpc_finish(efx, MC_CMD_PTP,
MC_CMD_PTP_IN_SYNCHRONIZE_LEN,
synch_buf, sizeof(synch_buf),
&response_length);
if (rc == 0) {
rc = efx_ptp_process_times(efx, synch_buf, response_length,
&last_time);
if (rc == 0)
++ptp->good_syncs;
else
++ptp->no_time_syncs;
}
/* Increment the bad syncs counter if the synchronize fails, whatever
* the reason.
*/
if (rc != 0)
++ptp->bad_syncs;
return rc;
}
/* Transmit a PTP packet via the dedicated hardware timestamped queue. */
static void efx_ptp_xmit_skb_queue(struct efx_nic *efx, struct sk_buff *skb)
{
struct efx_ptp_data *ptp_data = efx->ptp_data;
u8 type = efx_tx_csum_type_skb(skb);
struct efx_tx_queue *tx_queue;
tx_queue = efx_channel_get_tx_queue(ptp_data->channel, type);
if (tx_queue && tx_queue->timestamping) {
skb_get(skb);
/* This code invokes normal driver TX code which is always
* protected from softirqs when called from generic TX code,
* which in turn disables preemption. Look at __dev_queue_xmit
* which uses rcu_read_lock_bh disabling preemption for RCU
* plus disabling softirqs. We do not need RCU reader
* protection here.
*
* Although it is theoretically safe for current PTP TX/RX code
* running without disabling softirqs, there are three good
* reasond for doing so:
*
* 1) The code invoked is mainly implemented for non-PTP
* packets and it is always executed with softirqs
* disabled.
* 2) This being a single PTP packet, better to not
* interrupt its processing by softirqs which can lead
* to high latencies.
* 3) netdev_xmit_more checks preemption is disabled and
* triggers a BUG_ON if not.
*/
local_bh_disable();
efx_enqueue_skb(tx_queue, skb);
local_bh_enable();
/* We need to add the filters after enqueuing the packet.
* Otherwise, there's high latency in sending back the
* timestamp, causing ptp4l timeouts
*/
efx_ptp_insert_unicast_filter(efx, skb);
dev_consume_skb_any(skb);
} else {
WARN_ONCE(1, "PTP channel has no timestamped tx queue\n");
dev_kfree_skb_any(skb);
}
}
/* Transmit a PTP packet, via the MCDI interface, to the wire. */
static void efx_ptp_xmit_skb_mc(struct efx_nic *efx, struct sk_buff *skb)
{
MCDI_DECLARE_BUF(txtime, MC_CMD_PTP_OUT_TRANSMIT_LEN);
struct efx_ptp_data *ptp_data = efx->ptp_data;
struct skb_shared_hwtstamps timestamps;
size_t len;
int rc;
MCDI_SET_DWORD(ptp_data->txbuf, PTP_IN_OP, MC_CMD_PTP_OP_TRANSMIT);
MCDI_SET_DWORD(ptp_data->txbuf, PTP_IN_PERIPH_ID, 0);
MCDI_SET_DWORD(ptp_data->txbuf, PTP_IN_TRANSMIT_LENGTH, skb->len);
if (skb_shinfo(skb)->nr_frags != 0) {
rc = skb_linearize(skb);
if (rc != 0)
goto fail;
}
if (skb->ip_summed == CHECKSUM_PARTIAL) {
rc = skb_checksum_help(skb);
if (rc != 0)
goto fail;
}
skb_copy_from_linear_data(skb,
MCDI_PTR(ptp_data->txbuf,
PTP_IN_TRANSMIT_PACKET),
skb->len);
rc = efx_mcdi_rpc(efx, MC_CMD_PTP,
ptp_data->txbuf, MC_CMD_PTP_IN_TRANSMIT_LEN(skb->len),
txtime, sizeof(txtime), &len);
if (rc != 0)
goto fail;
memset(×tamps, 0, sizeof(timestamps));
timestamps.hwtstamp = ptp_data->nic_to_kernel_time(
MCDI_DWORD(txtime, PTP_OUT_TRANSMIT_MAJOR),
MCDI_DWORD(txtime, PTP_OUT_TRANSMIT_MINOR),
ptp_data->ts_corrections.ptp_tx);
skb_tstamp_tx(skb, ×tamps);
/* Add the filters after sending back the timestamp to avoid delaying it
* or ptp4l may timeout.
*/
efx_ptp_insert_unicast_filter(efx, skb);
fail:
dev_kfree_skb_any(skb);
return;
}
/* Process any queued receive events and corresponding packets
*
* q is returned with all the packets that are ready for delivery.
*/
static void efx_ptp_process_events(struct efx_nic *efx, struct sk_buff_head *q)
{
struct efx_ptp_data *ptp = efx->ptp_data;
struct sk_buff *skb;
while ((skb = skb_dequeue(&ptp->rxq))) {
struct efx_ptp_match *match;
match = (struct efx_ptp_match *)skb->cb;
if (match->state == PTP_PACKET_STATE_MATCH_UNWANTED) {
__skb_queue_tail(q, skb);
} else if (time_after(jiffies, match->expiry)) {
match->state = PTP_PACKET_STATE_TIMED_OUT;
++ptp->rx_no_timestamp;
__skb_queue_tail(q, skb);
} else {
/* Replace unprocessed entry and stop */
skb_queue_head(&ptp->rxq, skb);
break;
}
}
}
/* Complete processing of a received packet */
static inline void efx_ptp_process_rx(struct efx_nic *efx, struct sk_buff *skb)
{
local_bh_disable();
netif_receive_skb(skb);
local_bh_enable();
}
static struct efx_ptp_rxfilter *
efx_ptp_find_filter(struct list_head *filter_list, struct efx_filter_spec *spec)
{
struct efx_ptp_rxfilter *rxfilter;
list_for_each_entry(rxfilter, filter_list, list) {
if (rxfilter->ether_type == spec->ether_type &&
rxfilter->loc_port == spec->loc_port &&
!memcmp(rxfilter->loc_host, spec->loc_host, sizeof(spec->loc_host)))
return rxfilter;
}
return NULL;
}
static void efx_ptp_remove_one_filter(struct efx_nic *efx,
struct efx_ptp_rxfilter *rxfilter)
{
efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
rxfilter->handle);
list_del(&rxfilter->list);
kfree(rxfilter);
}
static void efx_ptp_remove_filters(struct efx_nic *efx,
struct list_head *filter_list)
{
struct efx_ptp_rxfilter *rxfilter, *tmp;
list_for_each_entry_safe(rxfilter, tmp, filter_list, list)
efx_ptp_remove_one_filter(efx, rxfilter);
}
static void efx_ptp_init_filter(struct efx_nic *efx,
struct efx_filter_spec *rxfilter)
{
struct efx_channel *channel = efx->ptp_data->channel;
struct efx_rx_queue *queue = efx_channel_get_rx_queue(channel);
efx_filter_init_rx(rxfilter, EFX_FILTER_PRI_REQUIRED, 0,
efx_rx_queue_index(queue));
}
static int efx_ptp_insert_filter(struct efx_nic *efx,
struct list_head *filter_list,
struct efx_filter_spec *spec,
unsigned long expiry)
{
struct efx_ptp_data *ptp = efx->ptp_data;
struct efx_ptp_rxfilter *rxfilter;
int rc;
rxfilter = efx_ptp_find_filter(filter_list, spec);
if (rxfilter) {
rxfilter->expiry = expiry;
return 0;
}
rxfilter = kzalloc(sizeof(*rxfilter), GFP_KERNEL);
if (!rxfilter)
return -ENOMEM;
rc = efx_filter_insert_filter(efx, spec, true);
if (rc < 0)
goto fail;
rxfilter->handle = rc;
rxfilter->ether_type = spec->ether_type;
rxfilter->loc_port = spec->loc_port;
memcpy(rxfilter->loc_host, spec->loc_host, sizeof(spec->loc_host));
rxfilter->expiry = expiry;
list_add(&rxfilter->list, filter_list);
queue_delayed_work(ptp->workwq, &ptp->cleanup_work,
UCAST_FILTER_EXPIRY_JIFFIES + 1);
return 0;
fail:
kfree(rxfilter);
return rc;
}
static int efx_ptp_insert_ipv4_filter(struct efx_nic *efx,
struct list_head *filter_list,
__be32 addr, u16 port,
unsigned long expiry)
{
struct efx_filter_spec spec;
efx_ptp_init_filter(efx, &spec);
efx_filter_set_ipv4_local(&spec, IPPROTO_UDP, addr, htons(port));
return efx_ptp_insert_filter(efx, filter_list, &spec, expiry);
}
static int efx_ptp_insert_ipv6_filter(struct efx_nic *efx,
struct list_head *filter_list,
struct in6_addr *addr, u16 port,
unsigned long expiry)
{
struct efx_filter_spec spec;
efx_ptp_init_filter(efx, &spec);
efx_filter_set_ipv6_local(&spec, IPPROTO_UDP, addr, htons(port));
return efx_ptp_insert_filter(efx, filter_list, &spec, expiry);
}
static int efx_ptp_insert_eth_multicast_filter(struct efx_nic *efx)
{
struct efx_ptp_data *ptp = efx->ptp_data;
const u8 addr[ETH_ALEN] = PTP_ADDR_ETHER;
struct efx_filter_spec spec;
efx_ptp_init_filter(efx, &spec);
efx_filter_set_eth_local(&spec, EFX_FILTER_VID_UNSPEC, addr);
spec.match_flags |= EFX_FILTER_MATCH_ETHER_TYPE;
spec.ether_type = htons(ETH_P_1588);
return efx_ptp_insert_filter(efx, &ptp->rxfilters_mcast, &spec, 0);
}
static int efx_ptp_insert_multicast_filters(struct efx_nic *efx)
{
struct efx_ptp_data *ptp = efx->ptp_data;
int rc;
if (!ptp->channel || !list_empty(&ptp->rxfilters_mcast))
return 0;
/* Must filter on both event and general ports to ensure
* that there is no packet re-ordering.
*/
rc = efx_ptp_insert_ipv4_filter(efx, &ptp->rxfilters_mcast,
htonl(PTP_ADDR_IPV4), PTP_EVENT_PORT,
0);
if (rc < 0)
goto fail;
rc = efx_ptp_insert_ipv4_filter(efx, &ptp->rxfilters_mcast,
htonl(PTP_ADDR_IPV4), PTP_GENERAL_PORT,
0);
if (rc < 0)
goto fail;
/* if the NIC supports hw timestamps by the MAC, we can support
* PTP over IPv6 and Ethernet
*/
if (efx_ptp_use_mac_tx_timestamps(efx)) {
struct in6_addr ipv6_addr = {{PTP_ADDR_IPV6}};
rc = efx_ptp_insert_ipv6_filter(efx, &ptp->rxfilters_mcast,
&ipv6_addr, PTP_EVENT_PORT, 0);
if (rc < 0)
goto fail;
rc = efx_ptp_insert_ipv6_filter(efx, &ptp->rxfilters_mcast,
&ipv6_addr, PTP_GENERAL_PORT, 0);
if (rc < 0)
goto fail;
rc = efx_ptp_insert_eth_multicast_filter(efx);
/* Not all firmware variants support this filter */
if (rc < 0 && rc != -EPROTONOSUPPORT)
goto fail;
}
return 0;
fail:
efx_ptp_remove_filters(efx, &ptp->rxfilters_mcast);
return rc;
}
static bool efx_ptp_valid_unicast_event_pkt(struct sk_buff *skb)
{
if (skb->protocol == htons(ETH_P_IP)) {
return ip_hdr(skb)->daddr != htonl(PTP_ADDR_IPV4) &&
ip_hdr(skb)->protocol == IPPROTO_UDP &&
udp_hdr(skb)->source == htons(PTP_EVENT_PORT);
} else if (skb->protocol == htons(ETH_P_IPV6)) {
struct in6_addr mcast_addr = {{PTP_ADDR_IPV6}};
return !ipv6_addr_equal(&ipv6_hdr(skb)->daddr, &mcast_addr) &&
ipv6_hdr(skb)->nexthdr == IPPROTO_UDP &&
udp_hdr(skb)->source == htons(PTP_EVENT_PORT);
}
return false;
}
static int efx_ptp_insert_unicast_filter(struct efx_nic *efx,
struct sk_buff *skb)
{
struct efx_ptp_data *ptp = efx->ptp_data;
unsigned long expiry;
int rc;
if (!efx_ptp_valid_unicast_event_pkt(skb))
return -EINVAL;
expiry = jiffies + UCAST_FILTER_EXPIRY_JIFFIES;
if (skb->protocol == htons(ETH_P_IP)) {
__be32 addr = ip_hdr(skb)->saddr;
rc = efx_ptp_insert_ipv4_filter(efx, &ptp->rxfilters_ucast,
addr, PTP_EVENT_PORT, expiry);
if (rc < 0)
goto out;
rc = efx_ptp_insert_ipv4_filter(efx, &ptp->rxfilters_ucast,
addr, PTP_GENERAL_PORT, expiry);
} else if (efx_ptp_use_mac_tx_timestamps(efx)) {
/* IPv6 PTP only supported by devices with MAC hw timestamp */
struct in6_addr *addr = &ipv6_hdr(skb)->saddr;
rc = efx_ptp_insert_ipv6_filter(efx, &ptp->rxfilters_ucast,
addr, PTP_EVENT_PORT, expiry);
if (rc < 0)
goto out;
rc = efx_ptp_insert_ipv6_filter(efx, &ptp->rxfilters_ucast,
addr, PTP_GENERAL_PORT, expiry);
} else {
return -EOPNOTSUPP;
}
out:
return rc;
}
static int efx_ptp_start(struct efx_nic *efx)
{
struct efx_ptp_data *ptp = efx->ptp_data;
int rc;
ptp->reset_required = false;
rc = efx_ptp_insert_multicast_filters(efx);
if (rc)
return rc;
rc = efx_ptp_enable(efx);
if (rc != 0)
goto fail;
ptp->evt_frag_idx = 0;
ptp->current_adjfreq = 0;
return 0;
fail:
efx_ptp_remove_filters(efx, &ptp->rxfilters_mcast);
return rc;
}
static int efx_ptp_stop(struct efx_nic *efx)
{
struct efx_ptp_data *ptp = efx->ptp_data;
int rc;
if (ptp == NULL)
return 0;
rc = efx_ptp_disable(efx);
efx_ptp_remove_filters(efx, &ptp->rxfilters_mcast);
efx_ptp_remove_filters(efx, &ptp->rxfilters_ucast);
/* Make sure RX packets are really delivered */
efx_ptp_deliver_rx_queue(&efx->ptp_data->rxq);
skb_queue_purge(&efx->ptp_data->txq);
return rc;
}
static int efx_ptp_restart(struct efx_nic *efx)
{
if (efx->ptp_data && efx->ptp_data->enabled)
return efx_ptp_start(efx);
return 0;
}
static void efx_ptp_pps_worker(struct work_struct *work)
{
struct efx_ptp_data *ptp =
container_of(work, struct efx_ptp_data, pps_work);
struct efx_nic *efx = ptp->efx;
struct ptp_clock_event ptp_evt;
if (efx_ptp_synchronize(efx, PTP_SYNC_ATTEMPTS))
return;
ptp_evt.type = PTP_CLOCK_PPSUSR;
ptp_evt.pps_times = ptp->host_time_pps;
ptp_clock_event(ptp->phc_clock, &ptp_evt);
}
static void efx_ptp_worker(struct work_struct *work)
{
struct efx_ptp_data *ptp_data =
container_of(work, struct efx_ptp_data, work);
struct efx_nic *efx = ptp_data->efx;
struct sk_buff *skb;
struct sk_buff_head tempq;
if (ptp_data->reset_required) {
efx_ptp_stop(efx);
efx_ptp_start(efx);
return;
}
__skb_queue_head_init(&tempq);
efx_ptp_process_events(efx, &tempq);
while ((skb = skb_dequeue(&ptp_data->txq)))
ptp_data->xmit_skb(efx, skb);
while ((skb = __skb_dequeue(&tempq)))
efx_ptp_process_rx(efx, skb);
}
static void efx_ptp_cleanup_worker(struct work_struct *work)
{
struct efx_ptp_data *ptp =
container_of(work, struct efx_ptp_data, cleanup_work.work);
struct efx_ptp_rxfilter *rxfilter, *tmp;
list_for_each_entry_safe(rxfilter, tmp, &ptp->rxfilters_ucast, list) {
if (time_is_before_jiffies(rxfilter->expiry))
efx_ptp_remove_one_filter(ptp->efx, rxfilter);
}
if (!list_empty(&ptp->rxfilters_ucast)) {
queue_delayed_work(ptp->workwq, &ptp->cleanup_work,
UCAST_FILTER_EXPIRY_JIFFIES + 1);
}
}
static const struct ptp_clock_info efx_phc_clock_info = {
.owner = THIS_MODULE,
.name = "sfc",
.max_adj = MAX_PPB,
.n_alarm = 0,
.n_ext_ts = 0,
.n_per_out = 0,
.n_pins = 0,
.pps = 1,
.adjfine = efx_phc_adjfine,
.adjtime = efx_phc_adjtime,
.gettime64 = efx_phc_gettime,
.settime64 = efx_phc_settime,
.enable = efx_phc_enable,
};
/* Initialise PTP state. */
int efx_ptp_probe(struct efx_nic *efx, struct efx_channel *channel)
{
struct efx_ptp_data *ptp;
int rc = 0;
if (efx->ptp_data) {
efx->ptp_data->channel = channel;
return 0;
}
ptp = kzalloc(sizeof(struct efx_ptp_data), GFP_KERNEL);
efx->ptp_data = ptp;
if (!efx->ptp_data)
return -ENOMEM;
ptp->efx = efx;
ptp->channel = channel;
rc = efx_nic_alloc_buffer(efx, &ptp->start, sizeof(int), GFP_KERNEL);
if (rc != 0)
goto fail1;
skb_queue_head_init(&ptp->rxq);
skb_queue_head_init(&ptp->txq);
ptp->workwq = create_singlethread_workqueue("sfc_ptp");
if (!ptp->workwq) {
rc = -ENOMEM;
goto fail2;
}
if (efx_ptp_use_mac_tx_timestamps(efx)) {
ptp->xmit_skb = efx_ptp_xmit_skb_queue;
/* Request sync events on this channel. */
channel->sync_events_state = SYNC_EVENTS_QUIESCENT;
} else {
ptp->xmit_skb = efx_ptp_xmit_skb_mc;
}
INIT_WORK(&ptp->work, efx_ptp_worker);
INIT_DELAYED_WORK(&ptp->cleanup_work, efx_ptp_cleanup_worker);
ptp->config.flags = 0;
ptp->config.tx_type = HWTSTAMP_TX_OFF;
ptp->config.rx_filter = HWTSTAMP_FILTER_NONE;
INIT_LIST_HEAD(&ptp->rxfilters_mcast);
INIT_LIST_HEAD(&ptp->rxfilters_ucast);
/* Get the NIC PTP attributes and set up time conversions */
rc = efx_ptp_get_attributes(efx);
if (rc < 0)
goto fail3;
/* Get the timestamp corrections */
rc = efx_ptp_get_timestamp_corrections(efx);
if (rc < 0)
goto fail3;
if (efx->mcdi->fn_flags &
(1 << MC_CMD_DRV_ATTACH_EXT_OUT_FLAG_PRIMARY)) {
ptp->phc_clock_info = efx_phc_clock_info;
ptp->phc_clock = ptp_clock_register(&ptp->phc_clock_info,
&efx->pci_dev->dev);
if (IS_ERR(ptp->phc_clock)) {
rc = PTR_ERR(ptp->phc_clock);
goto fail3;
} else if (ptp->phc_clock) {
INIT_WORK(&ptp->pps_work, efx_ptp_pps_worker);
ptp->pps_workwq = create_singlethread_workqueue("sfc_pps");
if (!ptp->pps_workwq) {
rc = -ENOMEM;
goto fail4;
}
}
}
ptp->nic_ts_enabled = false;
return 0;
fail4:
ptp_clock_unregister(efx->ptp_data->phc_clock);
fail3:
destroy_workqueue(efx->ptp_data->workwq);
fail2:
efx_nic_free_buffer(efx, &ptp->start);
fail1:
kfree(efx->ptp_data);
efx->ptp_data = NULL;
return rc;
}
/* Initialise PTP channel.
*
* Setting core_index to zero causes the queue to be initialised and doesn't
* overlap with 'rxq0' because ptp.c doesn't use skb_record_rx_queue.
*/
static int efx_ptp_probe_channel(struct efx_channel *channel)
{
struct efx_nic *efx = channel->efx;
int rc;
channel->irq_moderation_us = 0;
channel->rx_queue.core_index = 0;
rc = efx_ptp_probe(efx, channel);
/* Failure to probe PTP is not fatal; this channel will just not be
* used for anything.
* In the case of EPERM, efx_ptp_probe will print its own message (in
* efx_ptp_get_attributes()), so we don't need to.
*/
if (rc && rc != -EPERM)
netif_warn(efx, drv, efx->net_dev,
"Failed to probe PTP, rc=%d\n", rc);
return 0;
}
void efx_ptp_remove(struct efx_nic *efx)
{
if (!efx->ptp_data)
return;
(void)efx_ptp_disable(efx);
cancel_work_sync(&efx->ptp_data->work);
cancel_delayed_work_sync(&efx->ptp_data->cleanup_work);
if (efx->ptp_data->pps_workwq)
cancel_work_sync(&efx->ptp_data->pps_work);
skb_queue_purge(&efx->ptp_data->rxq);
skb_queue_purge(&efx->ptp_data->txq);
if (efx->ptp_data->phc_clock) {
destroy_workqueue(efx->ptp_data->pps_workwq);
ptp_clock_unregister(efx->ptp_data->phc_clock);
}
destroy_workqueue(efx->ptp_data->workwq);
efx_nic_free_buffer(efx, &efx->ptp_data->start);
kfree(efx->ptp_data);
efx->ptp_data = NULL;
}
static void efx_ptp_remove_channel(struct efx_channel *channel)
{
efx_ptp_remove(channel->efx);
}
static void efx_ptp_get_channel_name(struct efx_channel *channel,
char *buf, size_t len)
{
snprintf(buf, len, "%s-ptp", channel->efx->name);
}
/* Determine whether this packet should be processed by the PTP module
* or transmitted conventionally.
*/
bool efx_ptp_is_ptp_tx(struct efx_nic *efx, struct sk_buff *skb)
{
return efx->ptp_data &&
efx->ptp_data->enabled &&
skb->len >= PTP_MIN_LENGTH &&
skb->len <= MC_CMD_PTP_IN_TRANSMIT_PACKET_MAXNUM &&
likely(skb->protocol == htons(ETH_P_IP)) &&
skb_transport_header_was_set(skb) &&
skb_network_header_len(skb) >= sizeof(struct iphdr) &&
ip_hdr(skb)->protocol == IPPROTO_UDP &&
skb_headlen(skb) >=
skb_transport_offset(skb) + sizeof(struct udphdr) &&
udp_hdr(skb)->dest == htons(PTP_EVENT_PORT);
}
/* Receive a PTP packet. Packets are queued until the arrival of
* the receive timestamp from the MC - this will probably occur after the
* packet arrival because of the processing in the MC.
*/
static bool efx_ptp_rx(struct efx_channel *channel, struct sk_buff *skb)
{
struct efx_nic *efx = channel->efx;
struct efx_ptp_data *ptp = efx->ptp_data;
struct efx_ptp_match *match = (struct efx_ptp_match *)skb->cb;
unsigned int version;
u8 *data;
match->expiry = jiffies + msecs_to_jiffies(PKT_EVENT_LIFETIME_MS);
/* Correct version? */
if (ptp->mode == MC_CMD_PTP_MODE_V1) {
if (!pskb_may_pull(skb, PTP_V1_MIN_LENGTH)) {
return false;
}
data = skb->data;
version = ntohs(*(__be16 *)&data[PTP_V1_VERSION_OFFSET]);
if (version != PTP_VERSION_V1) {
return false;
}
} else {
if (!pskb_may_pull(skb, PTP_V2_MIN_LENGTH)) {
return false;
}
data = skb->data;
version = data[PTP_V2_VERSION_OFFSET];
if ((version & PTP_VERSION_V2_MASK) != PTP_VERSION_V2) {
return false;
}
}
/* Does this packet require timestamping? */
if (ntohs(*(__be16 *)&data[PTP_DPORT_OFFSET]) == PTP_EVENT_PORT) {
match->state = PTP_PACKET_STATE_UNMATCHED;
/* We expect the sequence number to be in the same position in
* the packet for PTP V1 and V2
*/
BUILD_BUG_ON(PTP_V1_SEQUENCE_OFFSET != PTP_V2_SEQUENCE_OFFSET);
BUILD_BUG_ON(PTP_V1_SEQUENCE_LENGTH != PTP_V2_SEQUENCE_LENGTH);
} else {
match->state = PTP_PACKET_STATE_MATCH_UNWANTED;
}
skb_queue_tail(&ptp->rxq, skb);
queue_work(ptp->workwq, &ptp->work);
return true;
}
/* Transmit a PTP packet. This has to be transmitted by the MC
* itself, through an MCDI call. MCDI calls aren't permitted
* in the transmit path so defer the actual transmission to a suitable worker.
*/
int efx_ptp_tx(struct efx_nic *efx, struct sk_buff *skb)
{
struct efx_ptp_data *ptp = efx->ptp_data;
skb_queue_tail(&ptp->txq, skb);
if ((udp_hdr(skb)->dest == htons(PTP_EVENT_PORT)) &&
(skb->len <= MC_CMD_PTP_IN_TRANSMIT_PACKET_MAXNUM))
efx_xmit_hwtstamp_pending(skb);
queue_work(ptp->workwq, &ptp->work);
return NETDEV_TX_OK;
}
int efx_ptp_get_mode(struct efx_nic *efx)
{
return efx->ptp_data->mode;
}
int efx_ptp_change_mode(struct efx_nic *efx, bool enable_wanted,
unsigned int new_mode)
{
if ((enable_wanted != efx->ptp_data->enabled) ||
(enable_wanted && (efx->ptp_data->mode != new_mode))) {
int rc = 0;
if (enable_wanted) {
/* Change of mode requires disable */
if (efx->ptp_data->enabled &&
(efx->ptp_data->mode != new_mode)) {
efx->ptp_data->enabled = false;
rc = efx_ptp_stop(efx);
if (rc != 0)
return rc;
}
/* Set new operating mode and establish
* baseline synchronisation, which must
* succeed.
*/
efx->ptp_data->mode = new_mode;
if (netif_running(efx->net_dev))
rc = efx_ptp_start(efx);
if (rc == 0) {
rc = efx_ptp_synchronize(efx,
PTP_SYNC_ATTEMPTS * 2);
if (rc != 0)
efx_ptp_stop(efx);
}
} else {
rc = efx_ptp_stop(efx);
}
if (rc != 0)
return rc;
efx->ptp_data->enabled = enable_wanted;
}
return 0;
}
static int efx_ptp_ts_init(struct efx_nic *efx, struct hwtstamp_config *init)
{
int rc;
if ((init->tx_type != HWTSTAMP_TX_OFF) &&
(init->tx_type != HWTSTAMP_TX_ON))
return -ERANGE;
rc = efx->type->ptp_set_ts_config(efx, init);
if (rc)
return rc;
efx->ptp_data->config = *init;
return 0;
}
void efx_ptp_get_ts_info(struct efx_nic *efx, struct ethtool_ts_info *ts_info)
{
struct efx_ptp_data *ptp = efx->ptp_data;
struct efx_nic *primary = efx->primary;
ASSERT_RTNL();
if (!ptp)
return;
ts_info->so_timestamping |= (SOF_TIMESTAMPING_TX_HARDWARE |
SOF_TIMESTAMPING_RX_HARDWARE |
SOF_TIMESTAMPING_RAW_HARDWARE);
/* Check licensed features. If we don't have the license for TX
* timestamps, the NIC will not support them.
*/
if (efx_ptp_use_mac_tx_timestamps(efx)) {
struct efx_ef10_nic_data *nic_data = efx->nic_data;
if (!(nic_data->licensed_features &
(1 << LICENSED_V3_FEATURES_TX_TIMESTAMPS_LBN)))
ts_info->so_timestamping &=
~SOF_TIMESTAMPING_TX_HARDWARE;
}
if (primary && primary->ptp_data && primary->ptp_data->phc_clock)
ts_info->phc_index =
ptp_clock_index(primary->ptp_data->phc_clock);
ts_info->tx_types = 1 << HWTSTAMP_TX_OFF | 1 << HWTSTAMP_TX_ON;
ts_info->rx_filters = ptp->efx->type->hwtstamp_filters;
}
int efx_ptp_set_ts_config(struct efx_nic *efx, struct ifreq *ifr)
{
struct hwtstamp_config config;
int rc;
/* Not a PTP enabled port */
if (!efx->ptp_data)
return -EOPNOTSUPP;
if (copy_from_user(&config, ifr->ifr_data, sizeof(config)))
return -EFAULT;
rc = efx_ptp_ts_init(efx, &config);
if (rc != 0)
return rc;
return copy_to_user(ifr->ifr_data, &config, sizeof(config))
? -EFAULT : 0;
}
int efx_ptp_get_ts_config(struct efx_nic *efx, struct ifreq *ifr)
{
if (!efx->ptp_data)
return -EOPNOTSUPP;
return copy_to_user(ifr->ifr_data, &efx->ptp_data->config,
sizeof(efx->ptp_data->config)) ? -EFAULT : 0;
}
static void ptp_event_failure(struct efx_nic *efx, int expected_frag_len)
{
struct efx_ptp_data *ptp = efx->ptp_data;
netif_err(efx, hw, efx->net_dev,
"PTP unexpected event length: got %d expected %d\n",
ptp->evt_frag_idx, expected_frag_len);
ptp->reset_required = true;
queue_work(ptp->workwq, &ptp->work);
}
static void ptp_event_fault(struct efx_nic *efx, struct efx_ptp_data *ptp)
{
int code = EFX_QWORD_FIELD(ptp->evt_frags[0], MCDI_EVENT_DATA);
if (ptp->evt_frag_idx != 1) {
ptp_event_failure(efx, 1);
return;
}
netif_err(efx, hw, efx->net_dev, "PTP error %d\n", code);
}
static void ptp_event_pps(struct efx_nic *efx, struct efx_ptp_data *ptp)
{
if (ptp->nic_ts_enabled)
queue_work(ptp->pps_workwq, &ptp->pps_work);
}
void efx_ptp_event(struct efx_nic *efx, efx_qword_t *ev)
{
struct efx_ptp_data *ptp = efx->ptp_data;
int code = EFX_QWORD_FIELD(*ev, MCDI_EVENT_CODE);
if (!ptp) {
if (!efx->ptp_warned) {
netif_warn(efx, drv, efx->net_dev,
"Received PTP event but PTP not set up\n");
efx->ptp_warned = true;
}
return;
}
if (!ptp->enabled)
return;
if (ptp->evt_frag_idx == 0) {
ptp->evt_code = code;
} else if (ptp->evt_code != code) {
netif_err(efx, hw, efx->net_dev,
"PTP out of sequence event %d\n", code);
ptp->evt_frag_idx = 0;
}
ptp->evt_frags[ptp->evt_frag_idx++] = *ev;
if (!MCDI_EVENT_FIELD(*ev, CONT)) {
/* Process resulting event */
switch (code) {
case MCDI_EVENT_CODE_PTP_FAULT:
ptp_event_fault(efx, ptp);
break;
case MCDI_EVENT_CODE_PTP_PPS:
ptp_event_pps(efx, ptp);
break;
default:
netif_err(efx, hw, efx->net_dev,
"PTP unknown event %d\n", code);
break;
}
ptp->evt_frag_idx = 0;
} else if (MAX_EVENT_FRAGS == ptp->evt_frag_idx) {
netif_err(efx, hw, efx->net_dev,
"PTP too many event fragments\n");
ptp->evt_frag_idx = 0;
}
}
void efx_time_sync_event(struct efx_channel *channel, efx_qword_t *ev)
{
struct efx_nic *efx = channel->efx;
struct efx_ptp_data *ptp = efx->ptp_data;
/* When extracting the sync timestamp minor value, we should discard
* the least significant two bits. These are not required in order
* to reconstruct full-range timestamps and they are optionally used
* to report status depending on the options supplied when subscribing
* for sync events.
*/
channel->sync_timestamp_major = MCDI_EVENT_FIELD(*ev, PTP_TIME_MAJOR);
channel->sync_timestamp_minor =
(MCDI_EVENT_FIELD(*ev, PTP_TIME_MINOR_MS_8BITS) & 0xFC)
<< ptp->nic_time.sync_event_minor_shift;
/* if sync events have been disabled then we want to silently ignore
* this event, so throw away result.
*/
(void) cmpxchg(&channel->sync_events_state, SYNC_EVENTS_REQUESTED,
SYNC_EVENTS_VALID);
}
static inline u32 efx_rx_buf_timestamp_minor(struct efx_nic *efx, const u8 *eh)
{
#if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
return __le32_to_cpup((const __le32 *)(eh + efx->rx_packet_ts_offset));
#else
const u8 *data = eh + efx->rx_packet_ts_offset;
return (u32)data[0] |
(u32)data[1] << 8 |
(u32)data[2] << 16 |
(u32)data[3] << 24;
#endif
}
void __efx_rx_skb_attach_timestamp(struct efx_channel *channel,
struct sk_buff *skb)
{
struct efx_nic *efx = channel->efx;
struct efx_ptp_data *ptp = efx->ptp_data;
u32 pkt_timestamp_major, pkt_timestamp_minor;
u32 diff, carry;
struct skb_shared_hwtstamps *timestamps;
if (channel->sync_events_state != SYNC_EVENTS_VALID)
return;
pkt_timestamp_minor = efx_rx_buf_timestamp_minor(efx, skb_mac_header(skb));
/* get the difference between the packet and sync timestamps,
* modulo one second
*/
diff = pkt_timestamp_minor - channel->sync_timestamp_minor;
if (pkt_timestamp_minor < channel->sync_timestamp_minor)
diff += ptp->nic_time.minor_max;
/* do we roll over a second boundary and need to carry the one? */
carry = (channel->sync_timestamp_minor >= ptp->nic_time.minor_max - diff) ?
1 : 0;
if (diff <= ptp->nic_time.sync_event_diff_max) {
/* packet is ahead of the sync event by a quarter of a second or
* less (allowing for fuzz)
*/
pkt_timestamp_major = channel->sync_timestamp_major + carry;
} else if (diff >= ptp->nic_time.sync_event_diff_min) {
/* packet is behind the sync event but within the fuzz factor.
* This means the RX packet and sync event crossed as they were
* placed on the event queue, which can sometimes happen.
*/
pkt_timestamp_major = channel->sync_timestamp_major - 1 + carry;
} else {
/* it's outside tolerance in both directions. this might be
* indicative of us missing sync events for some reason, so
* we'll call it an error rather than risk giving a bogus
* timestamp.
*/
netif_vdbg(efx, drv, efx->net_dev,
"packet timestamp %x too far from sync event %x:%x\n",
pkt_timestamp_minor, channel->sync_timestamp_major,
channel->sync_timestamp_minor);
return;
}
/* attach the timestamps to the skb */
timestamps = skb_hwtstamps(skb);
timestamps->hwtstamp =
ptp->nic_to_kernel_time(pkt_timestamp_major,
pkt_timestamp_minor,
ptp->ts_corrections.general_rx);
}
static int efx_phc_adjfine(struct ptp_clock_info *ptp, long scaled_ppm)
{
struct efx_ptp_data *ptp_data = container_of(ptp,
struct efx_ptp_data,
phc_clock_info);
s32 delta = scaled_ppm_to_ppb(scaled_ppm);
struct efx_nic *efx = ptp_data->efx;
MCDI_DECLARE_BUF(inadj, MC_CMD_PTP_IN_ADJUST_LEN);
s64 adjustment_ns;
int rc;
if (delta > MAX_PPB)
delta = MAX_PPB;
else if (delta < -MAX_PPB)
delta = -MAX_PPB;
/* Convert ppb to fixed point ns taking care to round correctly. */
adjustment_ns = ((s64)delta * PPB_SCALE_WORD +
(1 << (ptp_data->adjfreq_ppb_shift - 1))) >>
ptp_data->adjfreq_ppb_shift;
MCDI_SET_DWORD(inadj, PTP_IN_OP, MC_CMD_PTP_OP_ADJUST);
MCDI_SET_DWORD(inadj, PTP_IN_PERIPH_ID, 0);
MCDI_SET_QWORD(inadj, PTP_IN_ADJUST_FREQ, adjustment_ns);
MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_SECONDS, 0);
MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_NANOSECONDS, 0);
rc = efx_mcdi_rpc(efx, MC_CMD_PTP, inadj, sizeof(inadj),
NULL, 0, NULL);
if (rc != 0)
return rc;
ptp_data->current_adjfreq = adjustment_ns;
return 0;
}
static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta)
{
u32 nic_major, nic_minor;
struct efx_ptp_data *ptp_data = container_of(ptp,
struct efx_ptp_data,
phc_clock_info);
struct efx_nic *efx = ptp_data->efx;
MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_ADJUST_LEN);
efx->ptp_data->ns_to_nic_time(delta, &nic_major, &nic_minor);
MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_ADJUST);
MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
MCDI_SET_QWORD(inbuf, PTP_IN_ADJUST_FREQ, ptp_data->current_adjfreq);
MCDI_SET_DWORD(inbuf, PTP_IN_ADJUST_MAJOR, nic_major);
MCDI_SET_DWORD(inbuf, PTP_IN_ADJUST_MINOR, nic_minor);
return efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
NULL, 0, NULL);
}
static int efx_phc_gettime(struct ptp_clock_info *ptp, struct timespec64 *ts)
{
struct efx_ptp_data *ptp_data = container_of(ptp,
struct efx_ptp_data,
phc_clock_info);
struct efx_nic *efx = ptp_data->efx;
MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_READ_NIC_TIME_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_PTP_OUT_READ_NIC_TIME_LEN);
int rc;
ktime_t kt;
MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_READ_NIC_TIME);
MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
rc = efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), NULL);
if (rc != 0)
return rc;
kt = ptp_data->nic_to_kernel_time(
MCDI_DWORD(outbuf, PTP_OUT_READ_NIC_TIME_MAJOR),
MCDI_DWORD(outbuf, PTP_OUT_READ_NIC_TIME_MINOR), 0);
*ts = ktime_to_timespec64(kt);
return 0;
}
static int efx_phc_settime(struct ptp_clock_info *ptp,
const struct timespec64 *e_ts)
{
/* Get the current NIC time, efx_phc_gettime.
* Subtract from the desired time to get the offset
* call efx_phc_adjtime with the offset
*/
int rc;
struct timespec64 time_now;
struct timespec64 delta;
rc = efx_phc_gettime(ptp, &time_now);
if (rc != 0)
return rc;
delta = timespec64_sub(*e_ts, time_now);
rc = efx_phc_adjtime(ptp, timespec64_to_ns(&delta));
if (rc != 0)
return rc;
return 0;
}
static int efx_phc_enable(struct ptp_clock_info *ptp,
struct ptp_clock_request *request,
int enable)
{
struct efx_ptp_data *ptp_data = container_of(ptp,
struct efx_ptp_data,
phc_clock_info);
if (request->type != PTP_CLK_REQ_PPS)
return -EOPNOTSUPP;
ptp_data->nic_ts_enabled = !!enable;
return 0;
}
static const struct efx_channel_type efx_ptp_channel_type = {
.handle_no_channel = efx_ptp_handle_no_channel,
.pre_probe = efx_ptp_probe_channel,
.post_remove = efx_ptp_remove_channel,
.get_name = efx_ptp_get_channel_name,
.copy = efx_copy_channel,
.receive_skb = efx_ptp_rx,
.want_txqs = efx_ptp_want_txqs,
.keep_eventq = false,
};
void efx_ptp_defer_probe_with_channel(struct efx_nic *efx)
{
/* Check whether PTP is implemented on this NIC. The DISABLE
* operation will succeed if and only if it is implemented.
*/
if (efx_ptp_disable(efx) == 0)
efx->extra_channel_type[EFX_EXTRA_CHANNEL_PTP] =
&efx_ptp_channel_type;
}
void efx_ptp_start_datapath(struct efx_nic *efx)
{
if (efx_ptp_restart(efx))
netif_err(efx, drv, efx->net_dev, "Failed to restart PTP.\n");
/* re-enable timestamping if it was previously enabled */
if (efx->type->ptp_set_ts_sync_events)
efx->type->ptp_set_ts_sync_events(efx, true, true);
}
void efx_ptp_stop_datapath(struct efx_nic *efx)
{
/* temporarily disable timestamping */
if (efx->type->ptp_set_ts_sync_events)
efx->type->ptp_set_ts_sync_events(efx, false, true);
efx_ptp_stop(efx);
}
|
linux-master
|
drivers/net/ethernet/sfc/ptp.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2019 Solarflare Communications Inc.
* Copyright 2020-2022 Xilinx Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include "ef100_sriov.h"
#include "ef100_nic.h"
#include "ef100_rep.h"
static int efx_ef100_pci_sriov_enable(struct efx_nic *efx, int num_vfs)
{
struct ef100_nic_data *nic_data = efx->nic_data;
struct pci_dev *dev = efx->pci_dev;
struct efx_rep *efv, *next;
int rc, i;
efx->vf_count = num_vfs;
rc = pci_enable_sriov(dev, num_vfs);
if (rc)
goto fail1;
if (!nic_data->grp_mae)
return 0;
for (i = 0; i < num_vfs; i++) {
rc = efx_ef100_vfrep_create(efx, i);
if (rc)
goto fail2;
}
return 0;
fail2:
list_for_each_entry_safe(efv, next, &efx->vf_reps, list)
efx_ef100_vfrep_destroy(efx, efv);
pci_disable_sriov(dev);
fail1:
netif_err(efx, probe, efx->net_dev, "Failed to enable SRIOV VFs\n");
efx->vf_count = 0;
return rc;
}
int efx_ef100_pci_sriov_disable(struct efx_nic *efx, bool force)
{
struct pci_dev *dev = efx->pci_dev;
unsigned int vfs_assigned;
vfs_assigned = pci_vfs_assigned(dev);
if (vfs_assigned && !force) {
netif_info(efx, drv, efx->net_dev, "VFs are assigned to guests; "
"please detach them before disabling SR-IOV\n");
return -EBUSY;
}
efx_ef100_fini_vfreps(efx);
if (!vfs_assigned)
pci_disable_sriov(dev);
return 0;
}
int efx_ef100_sriov_configure(struct efx_nic *efx, int num_vfs)
{
if (num_vfs == 0)
return efx_ef100_pci_sriov_disable(efx, false);
else
return efx_ef100_pci_sriov_enable(efx, num_vfs);
}
|
linux-master
|
drivers/net/ethernet/sfc/ef100_sriov.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2019 Solarflare Communications Inc.
* Copyright 2020-2022 Xilinx Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include <linux/rhashtable.h>
#include "ef100_nic.h"
#include "mae.h"
#include "mcdi.h"
#include "mcdi_pcol.h"
#include "mcdi_pcol_mae.h"
#include "tc_encap_actions.h"
#include "tc_conntrack.h"
int efx_mae_allocate_mport(struct efx_nic *efx, u32 *id, u32 *label)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_MAE_MPORT_ALLOC_ALIAS_OUT_LEN);
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_MPORT_ALLOC_ALIAS_IN_LEN);
size_t outlen;
int rc;
if (WARN_ON_ONCE(!id))
return -EINVAL;
if (WARN_ON_ONCE(!label))
return -EINVAL;
MCDI_SET_DWORD(inbuf, MAE_MPORT_ALLOC_ALIAS_IN_TYPE,
MC_CMD_MAE_MPORT_ALLOC_ALIAS_IN_MPORT_TYPE_ALIAS);
MCDI_SET_DWORD(inbuf, MAE_MPORT_ALLOC_ALIAS_IN_DELIVER_MPORT,
MAE_MPORT_SELECTOR_ASSIGNED);
rc = efx_mcdi_rpc(efx, MC_CMD_MAE_MPORT_ALLOC, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < sizeof(outbuf))
return -EIO;
*id = MCDI_DWORD(outbuf, MAE_MPORT_ALLOC_ALIAS_OUT_MPORT_ID);
*label = MCDI_DWORD(outbuf, MAE_MPORT_ALLOC_ALIAS_OUT_LABEL);
return 0;
}
int efx_mae_free_mport(struct efx_nic *efx, u32 id)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_MPORT_FREE_IN_LEN);
BUILD_BUG_ON(MC_CMD_MAE_MPORT_FREE_OUT_LEN);
MCDI_SET_DWORD(inbuf, MAE_MPORT_FREE_IN_MPORT_ID, id);
return efx_mcdi_rpc(efx, MC_CMD_MAE_MPORT_FREE, inbuf, sizeof(inbuf),
NULL, 0, NULL);
}
void efx_mae_mport_wire(struct efx_nic *efx, u32 *out)
{
efx_dword_t mport;
EFX_POPULATE_DWORD_2(mport,
MAE_MPORT_SELECTOR_TYPE, MAE_MPORT_SELECTOR_TYPE_PPORT,
MAE_MPORT_SELECTOR_PPORT_ID, efx->port_num);
*out = EFX_DWORD_VAL(mport);
}
void efx_mae_mport_uplink(struct efx_nic *efx __always_unused, u32 *out)
{
efx_dword_t mport;
EFX_POPULATE_DWORD_3(mport,
MAE_MPORT_SELECTOR_TYPE, MAE_MPORT_SELECTOR_TYPE_FUNC,
MAE_MPORT_SELECTOR_FUNC_PF_ID, MAE_MPORT_SELECTOR_FUNC_PF_ID_CALLER,
MAE_MPORT_SELECTOR_FUNC_VF_ID, MAE_MPORT_SELECTOR_FUNC_VF_ID_NULL);
*out = EFX_DWORD_VAL(mport);
}
void efx_mae_mport_vf(struct efx_nic *efx __always_unused, u32 vf_id, u32 *out)
{
efx_dword_t mport;
EFX_POPULATE_DWORD_3(mport,
MAE_MPORT_SELECTOR_TYPE, MAE_MPORT_SELECTOR_TYPE_FUNC,
MAE_MPORT_SELECTOR_FUNC_PF_ID, MAE_MPORT_SELECTOR_FUNC_PF_ID_CALLER,
MAE_MPORT_SELECTOR_FUNC_VF_ID, vf_id);
*out = EFX_DWORD_VAL(mport);
}
/* Constructs an mport selector from an mport ID, because they're not the same */
void efx_mae_mport_mport(struct efx_nic *efx __always_unused, u32 mport_id, u32 *out)
{
efx_dword_t mport;
EFX_POPULATE_DWORD_2(mport,
MAE_MPORT_SELECTOR_TYPE, MAE_MPORT_SELECTOR_TYPE_MPORT_ID,
MAE_MPORT_SELECTOR_MPORT_ID, mport_id);
*out = EFX_DWORD_VAL(mport);
}
/* id is really only 24 bits wide */
int efx_mae_fw_lookup_mport(struct efx_nic *efx, u32 selector, u32 *id)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_MAE_MPORT_LOOKUP_OUT_LEN);
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_MPORT_LOOKUP_IN_LEN);
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, MAE_MPORT_LOOKUP_IN_MPORT_SELECTOR, selector);
rc = efx_mcdi_rpc(efx, MC_CMD_MAE_MPORT_LOOKUP, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < sizeof(outbuf))
return -EIO;
*id = MCDI_DWORD(outbuf, MAE_MPORT_LOOKUP_OUT_MPORT_ID);
return 0;
}
int efx_mae_start_counters(struct efx_nic *efx, struct efx_rx_queue *rx_queue)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_COUNTERS_STREAM_START_V2_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_MAE_COUNTERS_STREAM_START_OUT_LEN);
u32 out_flags;
size_t outlen;
int rc;
MCDI_SET_WORD(inbuf, MAE_COUNTERS_STREAM_START_V2_IN_QID,
efx_rx_queue_index(rx_queue));
MCDI_SET_WORD(inbuf, MAE_COUNTERS_STREAM_START_V2_IN_PACKET_SIZE,
efx->net_dev->mtu);
MCDI_SET_DWORD(inbuf, MAE_COUNTERS_STREAM_START_V2_IN_COUNTER_TYPES_MASK,
BIT(MAE_COUNTER_TYPE_AR) | BIT(MAE_COUNTER_TYPE_CT) |
BIT(MAE_COUNTER_TYPE_OR));
rc = efx_mcdi_rpc(efx, MC_CMD_MAE_COUNTERS_STREAM_START,
inbuf, sizeof(inbuf), outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < sizeof(outbuf))
return -EIO;
out_flags = MCDI_DWORD(outbuf, MAE_COUNTERS_STREAM_START_OUT_FLAGS);
if (out_flags & BIT(MC_CMD_MAE_COUNTERS_STREAM_START_OUT_USES_CREDITS_OFST)) {
netif_dbg(efx, drv, efx->net_dev,
"MAE counter stream uses credits\n");
rx_queue->grant_credits = true;
out_flags &= ~BIT(MC_CMD_MAE_COUNTERS_STREAM_START_OUT_USES_CREDITS_OFST);
}
if (out_flags) {
netif_err(efx, drv, efx->net_dev,
"MAE counter stream start: unrecognised flags %x\n",
out_flags);
goto out_stop;
}
return 0;
out_stop:
efx_mae_stop_counters(efx, rx_queue);
return -EOPNOTSUPP;
}
static bool efx_mae_counters_flushed(u32 *flush_gen, u32 *seen_gen)
{
int i;
for (i = 0; i < EFX_TC_COUNTER_TYPE_MAX; i++)
if ((s32)(flush_gen[i] - seen_gen[i]) > 0)
return false;
return true;
}
int efx_mae_stop_counters(struct efx_nic *efx, struct efx_rx_queue *rx_queue)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_MAE_COUNTERS_STREAM_STOP_V2_OUT_LENMAX);
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_COUNTERS_STREAM_STOP_IN_LEN);
size_t outlen;
int rc, i;
MCDI_SET_WORD(inbuf, MAE_COUNTERS_STREAM_STOP_IN_QID,
efx_rx_queue_index(rx_queue));
rc = efx_mcdi_rpc(efx, MC_CMD_MAE_COUNTERS_STREAM_STOP,
inbuf, sizeof(inbuf), outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
netif_dbg(efx, drv, efx->net_dev, "Draining counters:\n");
/* Only process received generation counts */
for (i = 0; (i < (outlen / 4)) && (i < EFX_TC_COUNTER_TYPE_MAX); i++) {
efx->tc->flush_gen[i] = MCDI_ARRAY_DWORD(outbuf,
MAE_COUNTERS_STREAM_STOP_V2_OUT_GENERATION_COUNT,
i);
netif_dbg(efx, drv, efx->net_dev,
"\ttype %u, awaiting gen %u\n", i,
efx->tc->flush_gen[i]);
}
efx->tc->flush_counters = true;
/* Drain can take up to 2 seconds owing to FWRIVERHD-2884; whatever
* timeout we use, that delay is added to unload on nonresponsive
* hardware, so 2500ms seems like a reasonable compromise.
*/
if (!wait_event_timeout(efx->tc->flush_wq,
efx_mae_counters_flushed(efx->tc->flush_gen,
efx->tc->seen_gen),
msecs_to_jiffies(2500)))
netif_warn(efx, drv, efx->net_dev,
"Failed to drain counters RXQ, FW may be unhappy\n");
efx->tc->flush_counters = false;
return rc;
}
void efx_mae_counters_grant_credits(struct work_struct *work)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_COUNTERS_STREAM_GIVE_CREDITS_IN_LEN);
struct efx_rx_queue *rx_queue = container_of(work, struct efx_rx_queue,
grant_work);
struct efx_nic *efx = rx_queue->efx;
unsigned int credits;
BUILD_BUG_ON(MC_CMD_MAE_COUNTERS_STREAM_GIVE_CREDITS_OUT_LEN);
credits = READ_ONCE(rx_queue->notified_count) - rx_queue->granted_count;
MCDI_SET_DWORD(inbuf, MAE_COUNTERS_STREAM_GIVE_CREDITS_IN_NUM_CREDITS,
credits);
if (!efx_mcdi_rpc(efx, MC_CMD_MAE_COUNTERS_STREAM_GIVE_CREDITS,
inbuf, sizeof(inbuf), NULL, 0, NULL))
rx_queue->granted_count += credits;
}
static int efx_mae_table_get_desc(struct efx_nic *efx,
struct efx_tc_table_desc *desc,
u32 table_id)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_TABLE_DESCRIPTOR_OUT_LEN(16));
MCDI_DECLARE_BUF(inbuf, MC_CMD_TABLE_DESCRIPTOR_IN_LEN);
unsigned int offset = 0, i;
size_t outlen;
int rc;
memset(desc, 0, sizeof(*desc));
MCDI_SET_DWORD(inbuf, TABLE_DESCRIPTOR_IN_TABLE_ID, table_id);
more:
MCDI_SET_DWORD(inbuf, TABLE_DESCRIPTOR_IN_FIRST_FIELDS_INDEX, offset);
rc = efx_mcdi_rpc(efx, MC_CMD_TABLE_DESCRIPTOR, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_TABLE_DESCRIPTOR_OUT_LEN(1)) {
rc = -EIO;
goto fail;
}
if (!offset) { /* first iteration: get metadata */
desc->type = MCDI_WORD(outbuf, TABLE_DESCRIPTOR_OUT_TYPE);
desc->key_width = MCDI_WORD(outbuf, TABLE_DESCRIPTOR_OUT_KEY_WIDTH);
desc->resp_width = MCDI_WORD(outbuf, TABLE_DESCRIPTOR_OUT_RESP_WIDTH);
desc->n_keys = MCDI_WORD(outbuf, TABLE_DESCRIPTOR_OUT_N_KEY_FIELDS);
desc->n_resps = MCDI_WORD(outbuf, TABLE_DESCRIPTOR_OUT_N_RESP_FIELDS);
desc->n_prios = MCDI_WORD(outbuf, TABLE_DESCRIPTOR_OUT_N_PRIORITIES);
desc->flags = MCDI_BYTE(outbuf, TABLE_DESCRIPTOR_OUT_FLAGS);
rc = -EOPNOTSUPP;
if (desc->flags)
goto fail;
desc->scheme = MCDI_BYTE(outbuf, TABLE_DESCRIPTOR_OUT_SCHEME);
if (desc->scheme)
goto fail;
rc = -ENOMEM;
desc->keys = kcalloc(desc->n_keys,
sizeof(struct efx_tc_table_field_fmt),
GFP_KERNEL);
if (!desc->keys)
goto fail;
desc->resps = kcalloc(desc->n_resps,
sizeof(struct efx_tc_table_field_fmt),
GFP_KERNEL);
if (!desc->resps)
goto fail;
}
/* FW could have returned more than the 16 field_descrs we
* made room for in our outbuf
*/
outlen = min(outlen, sizeof(outbuf));
for (i = 0; i + offset < desc->n_keys + desc->n_resps; i++) {
struct efx_tc_table_field_fmt *field;
MCDI_DECLARE_STRUCT_PTR(fdesc);
if (outlen < MC_CMD_TABLE_DESCRIPTOR_OUT_LEN(i + 1)) {
offset += i;
goto more;
}
if (i + offset < desc->n_keys)
field = desc->keys + i + offset;
else
field = desc->resps + (i + offset - desc->n_keys);
fdesc = MCDI_ARRAY_STRUCT_PTR(outbuf,
TABLE_DESCRIPTOR_OUT_FIELDS, i);
field->field_id = MCDI_STRUCT_WORD(fdesc,
TABLE_FIELD_DESCR_FIELD_ID);
field->lbn = MCDI_STRUCT_WORD(fdesc, TABLE_FIELD_DESCR_LBN);
field->width = MCDI_STRUCT_WORD(fdesc, TABLE_FIELD_DESCR_WIDTH);
field->masking = MCDI_STRUCT_BYTE(fdesc, TABLE_FIELD_DESCR_MASK_TYPE);
field->scheme = MCDI_STRUCT_BYTE(fdesc, TABLE_FIELD_DESCR_SCHEME);
}
return 0;
fail:
kfree(desc->keys);
kfree(desc->resps);
return rc;
}
static int efx_mae_table_hook_find(u16 n_fields,
struct efx_tc_table_field_fmt *fields,
u16 field_id)
{
unsigned int i;
for (i = 0; i < n_fields; i++) {
if (fields[i].field_id == field_id)
return i;
}
return -EPROTO;
}
#define TABLE_FIND_KEY(_desc, _id) \
efx_mae_table_hook_find((_desc)->n_keys, (_desc)->keys, _id)
#define TABLE_FIND_RESP(_desc, _id) \
efx_mae_table_hook_find((_desc)->n_resps, (_desc)->resps, _id)
#define TABLE_HOOK_KEY(_meta, _name, _mcdi_name) ({ \
int _rc = TABLE_FIND_KEY(&_meta->desc, TABLE_FIELD_ID_##_mcdi_name); \
\
if (_rc > U8_MAX) \
_rc = -EOPNOTSUPP; \
if (_rc >= 0) { \
_meta->keys._name##_idx = _rc; \
_rc = 0; \
} \
_rc; \
})
#define TABLE_HOOK_RESP(_meta, _name, _mcdi_name) ({ \
int _rc = TABLE_FIND_RESP(&_meta->desc, TABLE_FIELD_ID_##_mcdi_name); \
\
if (_rc > U8_MAX) \
_rc = -EOPNOTSUPP; \
if (_rc >= 0) { \
_meta->resps._name##_idx = _rc; \
_rc = 0; \
} \
_rc; \
})
static int efx_mae_table_hook_ct(struct efx_nic *efx,
struct efx_tc_table_ct *meta_ct)
{
int rc;
rc = TABLE_HOOK_KEY(meta_ct, eth_proto, ETHER_TYPE);
if (rc)
return rc;
rc = TABLE_HOOK_KEY(meta_ct, ip_proto, IP_PROTO);
if (rc)
return rc;
rc = TABLE_HOOK_KEY(meta_ct, src_ip, SRC_IP);
if (rc)
return rc;
rc = TABLE_HOOK_KEY(meta_ct, dst_ip, DST_IP);
if (rc)
return rc;
rc = TABLE_HOOK_KEY(meta_ct, l4_sport, SRC_PORT);
if (rc)
return rc;
rc = TABLE_HOOK_KEY(meta_ct, l4_dport, DST_PORT);
if (rc)
return rc;
rc = TABLE_HOOK_KEY(meta_ct, zone, DOMAIN);
if (rc)
return rc;
rc = TABLE_HOOK_RESP(meta_ct, dnat, NAT_DIR);
if (rc)
return rc;
rc = TABLE_HOOK_RESP(meta_ct, nat_ip, NAT_IP);
if (rc)
return rc;
rc = TABLE_HOOK_RESP(meta_ct, l4_natport, NAT_PORT);
if (rc)
return rc;
rc = TABLE_HOOK_RESP(meta_ct, mark, CT_MARK);
if (rc)
return rc;
rc = TABLE_HOOK_RESP(meta_ct, counter_id, COUNTER_ID);
if (rc)
return rc;
meta_ct->hooked = true;
return 0;
}
static void efx_mae_table_free_desc(struct efx_tc_table_desc *desc)
{
kfree(desc->keys);
kfree(desc->resps);
memset(desc, 0, sizeof(*desc));
}
static bool efx_mae_check_table_exists(struct efx_nic *efx, u32 tbl_req)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_TABLE_LIST_OUT_LEN(16));
MCDI_DECLARE_BUF(inbuf, MC_CMD_TABLE_LIST_IN_LEN);
u32 tbl_id, tbl_total, tbl_cnt, pos = 0;
size_t outlen, msg_max;
bool ct_tbl = false;
int rc, idx;
msg_max = sizeof(outbuf);
efx->tc->meta_ct.hooked = false;
more:
memset(outbuf, 0, sizeof(*outbuf));
MCDI_SET_DWORD(inbuf, TABLE_LIST_IN_FIRST_TABLE_ID_INDEX, pos);
rc = efx_mcdi_rpc(efx, MC_CMD_TABLE_LIST, inbuf, sizeof(inbuf), outbuf,
msg_max, &outlen);
if (rc)
return false;
if (outlen < MC_CMD_TABLE_LIST_OUT_LEN(1))
return false;
tbl_total = MCDI_DWORD(outbuf, TABLE_LIST_OUT_N_TABLES);
tbl_cnt = MC_CMD_TABLE_LIST_OUT_TABLE_ID_NUM(min(outlen, msg_max));
for (idx = 0; idx < tbl_cnt; idx++) {
tbl_id = MCDI_ARRAY_DWORD(outbuf, TABLE_LIST_OUT_TABLE_ID, idx);
if (tbl_id == tbl_req) {
ct_tbl = true;
break;
}
}
pos += tbl_cnt;
if (!ct_tbl && pos < tbl_total)
goto more;
return ct_tbl;
}
int efx_mae_get_tables(struct efx_nic *efx)
{
int rc;
efx->tc->meta_ct.hooked = false;
if (efx_mae_check_table_exists(efx, TABLE_ID_CONNTRACK_TABLE)) {
rc = efx_mae_table_get_desc(efx, &efx->tc->meta_ct.desc,
TABLE_ID_CONNTRACK_TABLE);
if (rc) {
pci_info(efx->pci_dev,
"FW does not support conntrack desc rc %d\n",
rc);
return 0;
}
rc = efx_mae_table_hook_ct(efx, &efx->tc->meta_ct);
if (rc) {
pci_info(efx->pci_dev,
"FW does not support conntrack hook rc %d\n",
rc);
return 0;
}
} else {
pci_info(efx->pci_dev,
"FW does not support conntrack table\n");
}
return 0;
}
void efx_mae_free_tables(struct efx_nic *efx)
{
efx_mae_table_free_desc(&efx->tc->meta_ct.desc);
efx->tc->meta_ct.hooked = false;
}
static int efx_mae_get_basic_caps(struct efx_nic *efx, struct mae_caps *caps)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_MAE_GET_CAPS_OUT_LEN);
size_t outlen;
int rc;
BUILD_BUG_ON(MC_CMD_MAE_GET_CAPS_IN_LEN);
rc = efx_mcdi_rpc(efx, MC_CMD_MAE_GET_CAPS, NULL, 0, outbuf,
sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < sizeof(outbuf))
return -EIO;
caps->match_field_count = MCDI_DWORD(outbuf, MAE_GET_CAPS_OUT_MATCH_FIELD_COUNT);
caps->encap_types = MCDI_DWORD(outbuf, MAE_GET_CAPS_OUT_ENCAP_TYPES_SUPPORTED);
caps->action_prios = MCDI_DWORD(outbuf, MAE_GET_CAPS_OUT_ACTION_PRIOS);
return 0;
}
static int efx_mae_get_rule_fields(struct efx_nic *efx, u32 cmd,
u8 *field_support)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_MAE_GET_AR_CAPS_OUT_LEN(MAE_NUM_FIELDS));
MCDI_DECLARE_STRUCT_PTR(caps);
unsigned int count;
size_t outlen;
int rc, i;
/* AR and OR caps MCDIs have identical layout, so we are using the
* same code for both.
*/
BUILD_BUG_ON(MC_CMD_MAE_GET_AR_CAPS_OUT_LEN(MAE_NUM_FIELDS) <
MC_CMD_MAE_GET_OR_CAPS_OUT_LEN(MAE_NUM_FIELDS));
BUILD_BUG_ON(MC_CMD_MAE_GET_AR_CAPS_IN_LEN);
BUILD_BUG_ON(MC_CMD_MAE_GET_OR_CAPS_IN_LEN);
rc = efx_mcdi_rpc(efx, cmd, NULL, 0, outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
BUILD_BUG_ON(MC_CMD_MAE_GET_AR_CAPS_OUT_COUNT_OFST !=
MC_CMD_MAE_GET_OR_CAPS_OUT_COUNT_OFST);
count = MCDI_DWORD(outbuf, MAE_GET_AR_CAPS_OUT_COUNT);
memset(field_support, MAE_FIELD_UNSUPPORTED, MAE_NUM_FIELDS);
BUILD_BUG_ON(MC_CMD_MAE_GET_AR_CAPS_OUT_FIELD_FLAGS_OFST !=
MC_CMD_MAE_GET_OR_CAPS_OUT_FIELD_FLAGS_OFST);
caps = _MCDI_DWORD(outbuf, MAE_GET_AR_CAPS_OUT_FIELD_FLAGS);
/* We're only interested in the support status enum, not any other
* flags, so just extract that from each entry.
*/
for (i = 0; i < count; i++)
if (i * sizeof(*outbuf) + MC_CMD_MAE_GET_AR_CAPS_OUT_FIELD_FLAGS_OFST < outlen)
field_support[i] = EFX_DWORD_FIELD(caps[i], MAE_FIELD_FLAGS_SUPPORT_STATUS);
return 0;
}
int efx_mae_get_caps(struct efx_nic *efx, struct mae_caps *caps)
{
int rc;
rc = efx_mae_get_basic_caps(efx, caps);
if (rc)
return rc;
rc = efx_mae_get_rule_fields(efx, MC_CMD_MAE_GET_AR_CAPS,
caps->action_rule_fields);
if (rc)
return rc;
return efx_mae_get_rule_fields(efx, MC_CMD_MAE_GET_OR_CAPS,
caps->outer_rule_fields);
}
/* Bit twiddling:
* Prefix: 1...110...0
* ~: 0...001...1
* + 1: 0...010...0 is power of two
* so (~x) & ((~x) + 1) == 0. Converse holds also.
*/
#define is_prefix_byte(_x) !(((_x) ^ 0xff) & (((_x) ^ 0xff) + 1))
enum mask_type { MASK_ONES, MASK_ZEROES, MASK_PREFIX, MASK_OTHER };
static const char *mask_type_name(enum mask_type typ)
{
switch (typ) {
case MASK_ONES:
return "all-1s";
case MASK_ZEROES:
return "all-0s";
case MASK_PREFIX:
return "prefix";
case MASK_OTHER:
return "arbitrary";
default: /* can't happen */
return "unknown";
}
}
/* Checks a (big-endian) bytestring is a bit prefix */
static enum mask_type classify_mask(const u8 *mask, size_t len)
{
bool zeroes = true; /* All bits seen so far are zeroes */
bool ones = true; /* All bits seen so far are ones */
bool prefix = true; /* Valid prefix so far */
size_t i;
for (i = 0; i < len; i++) {
if (ones) {
if (!is_prefix_byte(mask[i]))
prefix = false;
} else if (mask[i]) {
prefix = false;
}
if (mask[i] != 0xff)
ones = false;
if (mask[i])
zeroes = false;
}
if (ones)
return MASK_ONES;
if (zeroes)
return MASK_ZEROES;
if (prefix)
return MASK_PREFIX;
return MASK_OTHER;
}
static int efx_mae_match_check_cap_typ(u8 support, enum mask_type typ)
{
switch (support) {
case MAE_FIELD_UNSUPPORTED:
case MAE_FIELD_SUPPORTED_MATCH_NEVER:
if (typ == MASK_ZEROES)
return 0;
return -EOPNOTSUPP;
case MAE_FIELD_SUPPORTED_MATCH_OPTIONAL:
if (typ == MASK_ZEROES)
return 0;
fallthrough;
case MAE_FIELD_SUPPORTED_MATCH_ALWAYS:
if (typ == MASK_ONES)
return 0;
return -EINVAL;
case MAE_FIELD_SUPPORTED_MATCH_PREFIX:
if (typ == MASK_OTHER)
return -EOPNOTSUPP;
return 0;
case MAE_FIELD_SUPPORTED_MATCH_MASK:
return 0;
default:
return -EIO;
}
}
/* Validate field mask against hardware capabilities. Captures caller's 'rc' */
#define CHECK(_mcdi, _field) ({ \
enum mask_type typ = classify_mask((const u8 *)&mask->_field, \
sizeof(mask->_field)); \
\
rc = efx_mae_match_check_cap_typ(supported_fields[MAE_FIELD_ ## _mcdi],\
typ); \
if (rc) \
NL_SET_ERR_MSG_FMT_MOD(extack, \
"No support for %s mask in field %s", \
mask_type_name(typ), #_field); \
rc; \
})
/* Booleans need special handling */
#define CHECK_BIT(_mcdi, _field) ({ \
enum mask_type typ = mask->_field ? MASK_ONES : MASK_ZEROES; \
\
rc = efx_mae_match_check_cap_typ(supported_fields[MAE_FIELD_ ## _mcdi],\
typ); \
if (rc) \
NL_SET_ERR_MSG_FMT_MOD(extack, \
"No support for %s mask in field %s", \
mask_type_name(typ), #_field); \
rc; \
})
int efx_mae_match_check_caps(struct efx_nic *efx,
const struct efx_tc_match_fields *mask,
struct netlink_ext_ack *extack)
{
const u8 *supported_fields = efx->tc->caps->action_rule_fields;
__be32 ingress_port = cpu_to_be32(mask->ingress_port);
enum mask_type ingress_port_mask_type;
int rc;
/* Check for _PREFIX assumes big-endian, so we need to convert */
ingress_port_mask_type = classify_mask((const u8 *)&ingress_port,
sizeof(ingress_port));
rc = efx_mae_match_check_cap_typ(supported_fields[MAE_FIELD_INGRESS_PORT],
ingress_port_mask_type);
if (rc) {
NL_SET_ERR_MSG_FMT_MOD(extack, "No support for %s mask in field ingress_port",
mask_type_name(ingress_port_mask_type));
return rc;
}
if (CHECK(ETHER_TYPE, eth_proto) ||
CHECK(VLAN0_TCI, vlan_tci[0]) ||
CHECK(VLAN0_PROTO, vlan_proto[0]) ||
CHECK(VLAN1_TCI, vlan_tci[1]) ||
CHECK(VLAN1_PROTO, vlan_proto[1]) ||
CHECK(ETH_SADDR, eth_saddr) ||
CHECK(ETH_DADDR, eth_daddr) ||
CHECK(IP_PROTO, ip_proto) ||
CHECK(IP_TOS, ip_tos) ||
CHECK(IP_TTL, ip_ttl) ||
CHECK(SRC_IP4, src_ip) ||
CHECK(DST_IP4, dst_ip) ||
#ifdef CONFIG_IPV6
CHECK(SRC_IP6, src_ip6) ||
CHECK(DST_IP6, dst_ip6) ||
#endif
CHECK(L4_SPORT, l4_sport) ||
CHECK(L4_DPORT, l4_dport) ||
CHECK(TCP_FLAGS, tcp_flags) ||
CHECK_BIT(TCP_SYN_FIN_RST, tcp_syn_fin_rst) ||
CHECK_BIT(IS_IP_FRAG, ip_frag) ||
CHECK_BIT(IP_FIRST_FRAG, ip_firstfrag) ||
CHECK_BIT(DO_CT, ct_state_trk) ||
CHECK_BIT(CT_HIT, ct_state_est) ||
CHECK(CT_MARK, ct_mark) ||
CHECK(CT_DOMAIN, ct_zone) ||
CHECK(RECIRC_ID, recirc_id))
return rc;
/* Matches on outer fields are done in a separate hardware table,
* the Outer Rule table. Thus the Action Rule merely does an
* exact match on Outer Rule ID if any outer field matches are
* present. The exception is the VNI/VSID (enc_keyid), which is
* available to the Action Rule match iff the Outer Rule matched
* (and thus identified the encap protocol to use to extract it).
*/
if (efx_tc_match_is_encap(mask)) {
rc = efx_mae_match_check_cap_typ(
supported_fields[MAE_FIELD_OUTER_RULE_ID],
MASK_ONES);
if (rc) {
NL_SET_ERR_MSG_MOD(extack, "No support for encap rule ID matches");
return rc;
}
if (CHECK(ENC_VNET_ID, enc_keyid))
return rc;
} else if (mask->enc_keyid) {
NL_SET_ERR_MSG_MOD(extack, "Match on enc_keyid requires other encap fields");
return -EINVAL;
}
return 0;
}
/* Checks for match fields not supported in LHS Outer Rules */
#define UNSUPPORTED(_field) ({ \
enum mask_type typ = classify_mask((const u8 *)&mask->_field, \
sizeof(mask->_field)); \
\
if (typ != MASK_ZEROES) { \
NL_SET_ERR_MSG_MOD(extack, "Unsupported match field " #_field);\
rc = -EOPNOTSUPP; \
} \
rc; \
})
#define UNSUPPORTED_BIT(_field) ({ \
if (mask->_field) { \
NL_SET_ERR_MSG_MOD(extack, "Unsupported match field " #_field);\
rc = -EOPNOTSUPP; \
} \
rc; \
})
/* LHS rules are (normally) inserted in the Outer Rule table, which means
* they use ENC_ fields in hardware to match regular (not enc_) fields from
* &struct efx_tc_match_fields.
*/
int efx_mae_match_check_caps_lhs(struct efx_nic *efx,
const struct efx_tc_match_fields *mask,
struct netlink_ext_ack *extack)
{
const u8 *supported_fields = efx->tc->caps->outer_rule_fields;
__be32 ingress_port = cpu_to_be32(mask->ingress_port);
enum mask_type ingress_port_mask_type;
int rc;
/* Check for _PREFIX assumes big-endian, so we need to convert */
ingress_port_mask_type = classify_mask((const u8 *)&ingress_port,
sizeof(ingress_port));
rc = efx_mae_match_check_cap_typ(supported_fields[MAE_FIELD_INGRESS_PORT],
ingress_port_mask_type);
if (rc) {
NL_SET_ERR_MSG_FMT_MOD(extack, "No support for %s mask in field %s\n",
mask_type_name(ingress_port_mask_type),
"ingress_port");
return rc;
}
if (CHECK(ENC_ETHER_TYPE, eth_proto) ||
CHECK(ENC_VLAN0_TCI, vlan_tci[0]) ||
CHECK(ENC_VLAN0_PROTO, vlan_proto[0]) ||
CHECK(ENC_VLAN1_TCI, vlan_tci[1]) ||
CHECK(ENC_VLAN1_PROTO, vlan_proto[1]) ||
CHECK(ENC_ETH_SADDR, eth_saddr) ||
CHECK(ENC_ETH_DADDR, eth_daddr) ||
CHECK(ENC_IP_PROTO, ip_proto) ||
CHECK(ENC_IP_TOS, ip_tos) ||
CHECK(ENC_IP_TTL, ip_ttl) ||
CHECK_BIT(ENC_IP_FRAG, ip_frag) ||
UNSUPPORTED_BIT(ip_firstfrag) ||
CHECK(ENC_SRC_IP4, src_ip) ||
CHECK(ENC_DST_IP4, dst_ip) ||
#ifdef CONFIG_IPV6
CHECK(ENC_SRC_IP6, src_ip6) ||
CHECK(ENC_DST_IP6, dst_ip6) ||
#endif
CHECK(ENC_L4_SPORT, l4_sport) ||
CHECK(ENC_L4_DPORT, l4_dport) ||
UNSUPPORTED(tcp_flags) ||
CHECK_BIT(TCP_SYN_FIN_RST, tcp_syn_fin_rst))
return rc;
if (efx_tc_match_is_encap(mask)) {
/* can't happen; disallowed for local rules, translated
* for foreign rules.
*/
NL_SET_ERR_MSG_MOD(extack, "Unexpected encap match in LHS rule");
return -EOPNOTSUPP;
}
if (UNSUPPORTED(enc_keyid) ||
/* Can't filter on conntrack in LHS rules */
UNSUPPORTED_BIT(ct_state_trk) ||
UNSUPPORTED_BIT(ct_state_est) ||
UNSUPPORTED(ct_mark) ||
UNSUPPORTED(recirc_id))
return rc;
return 0;
}
#undef UNSUPPORTED
#undef CHECK_BIT
#undef CHECK
#define CHECK(_mcdi) ({ \
rc = efx_mae_match_check_cap_typ(supported_fields[MAE_FIELD_ ## _mcdi],\
MASK_ONES); \
if (rc) \
NL_SET_ERR_MSG_FMT_MOD(extack, \
"No support for field %s", #_mcdi); \
rc; \
})
/* Checks that the fields needed for encap-rule matches are supported by the
* MAE. All the fields are exact-match, except possibly ENC_IP_TOS.
*/
int efx_mae_check_encap_match_caps(struct efx_nic *efx, bool ipv6,
u8 ip_tos_mask, __be16 udp_sport_mask,
struct netlink_ext_ack *extack)
{
u8 *supported_fields = efx->tc->caps->outer_rule_fields;
enum mask_type typ;
int rc;
if (CHECK(ENC_ETHER_TYPE))
return rc;
if (ipv6) {
if (CHECK(ENC_SRC_IP6) ||
CHECK(ENC_DST_IP6))
return rc;
} else {
if (CHECK(ENC_SRC_IP4) ||
CHECK(ENC_DST_IP4))
return rc;
}
if (CHECK(ENC_L4_DPORT) ||
CHECK(ENC_IP_PROTO))
return rc;
typ = classify_mask((const u8 *)&udp_sport_mask, sizeof(udp_sport_mask));
rc = efx_mae_match_check_cap_typ(supported_fields[MAE_FIELD_ENC_L4_SPORT],
typ);
if (rc) {
NL_SET_ERR_MSG_FMT_MOD(extack, "No support for %s mask in field %s",
mask_type_name(typ), "enc_src_port");
return rc;
}
typ = classify_mask(&ip_tos_mask, sizeof(ip_tos_mask));
rc = efx_mae_match_check_cap_typ(supported_fields[MAE_FIELD_ENC_IP_TOS],
typ);
if (rc) {
NL_SET_ERR_MSG_FMT_MOD(extack, "No support for %s mask in field %s",
mask_type_name(typ), "enc_ip_tos");
return rc;
}
return 0;
}
#undef CHECK
int efx_mae_check_encap_type_supported(struct efx_nic *efx, enum efx_encap_type typ)
{
unsigned int bit;
switch (typ & EFX_ENCAP_TYPES_MASK) {
case EFX_ENCAP_TYPE_VXLAN:
bit = MC_CMD_MAE_GET_CAPS_OUT_ENCAP_TYPE_VXLAN_LBN;
break;
case EFX_ENCAP_TYPE_GENEVE:
bit = MC_CMD_MAE_GET_CAPS_OUT_ENCAP_TYPE_GENEVE_LBN;
break;
default:
return -EOPNOTSUPP;
}
if (efx->tc->caps->encap_types & BIT(bit))
return 0;
return -EOPNOTSUPP;
}
int efx_mae_allocate_counter(struct efx_nic *efx, struct efx_tc_counter *cnt)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_MAE_COUNTER_ALLOC_OUT_LEN(1));
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_COUNTER_ALLOC_V2_IN_LEN);
size_t outlen;
int rc;
if (!cnt)
return -EINVAL;
MCDI_SET_DWORD(inbuf, MAE_COUNTER_ALLOC_V2_IN_REQUESTED_COUNT, 1);
MCDI_SET_DWORD(inbuf, MAE_COUNTER_ALLOC_V2_IN_COUNTER_TYPE, cnt->type);
rc = efx_mcdi_rpc(efx, MC_CMD_MAE_COUNTER_ALLOC, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
/* pcol says this can't happen, since count is 1 */
if (outlen < sizeof(outbuf))
return -EIO;
cnt->fw_id = MCDI_DWORD(outbuf, MAE_COUNTER_ALLOC_OUT_COUNTER_ID);
cnt->gen = MCDI_DWORD(outbuf, MAE_COUNTER_ALLOC_OUT_GENERATION_COUNT);
return 0;
}
int efx_mae_free_counter(struct efx_nic *efx, struct efx_tc_counter *cnt)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_MAE_COUNTER_FREE_OUT_LEN(1));
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_COUNTER_FREE_V2_IN_LEN);
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, MAE_COUNTER_FREE_V2_IN_COUNTER_ID_COUNT, 1);
MCDI_SET_DWORD(inbuf, MAE_COUNTER_FREE_V2_IN_FREE_COUNTER_ID, cnt->fw_id);
MCDI_SET_DWORD(inbuf, MAE_COUNTER_FREE_V2_IN_COUNTER_TYPE, cnt->type);
rc = efx_mcdi_rpc(efx, MC_CMD_MAE_COUNTER_FREE, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
/* pcol says this can't happen, since count is 1 */
if (outlen < sizeof(outbuf))
return -EIO;
/* FW freed a different ID than we asked for, should also never happen.
* Warn because it means we've now got a different idea to the FW of
* what counters exist, which could cause mayhem later.
*/
if (WARN_ON(MCDI_DWORD(outbuf, MAE_COUNTER_FREE_OUT_FREED_COUNTER_ID) !=
cnt->fw_id))
return -EIO;
return 0;
}
static int efx_mae_encap_type_to_mae_type(enum efx_encap_type type)
{
switch (type & EFX_ENCAP_TYPES_MASK) {
case EFX_ENCAP_TYPE_NONE:
return MAE_MCDI_ENCAP_TYPE_NONE;
case EFX_ENCAP_TYPE_VXLAN:
return MAE_MCDI_ENCAP_TYPE_VXLAN;
case EFX_ENCAP_TYPE_GENEVE:
return MAE_MCDI_ENCAP_TYPE_GENEVE;
default:
return -EOPNOTSUPP;
}
}
int efx_mae_allocate_encap_md(struct efx_nic *efx,
struct efx_tc_encap_action *encap)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_ENCAP_HEADER_ALLOC_IN_LEN(EFX_TC_MAX_ENCAP_HDR));
MCDI_DECLARE_BUF(outbuf, MC_CMD_MAE_ENCAP_HEADER_ALLOC_OUT_LEN);
size_t inlen, outlen;
int rc;
rc = efx_mae_encap_type_to_mae_type(encap->type);
if (rc < 0)
return rc;
MCDI_SET_DWORD(inbuf, MAE_ENCAP_HEADER_ALLOC_IN_ENCAP_TYPE, rc);
inlen = MC_CMD_MAE_ENCAP_HEADER_ALLOC_IN_LEN(encap->encap_hdr_len);
if (WARN_ON(inlen > sizeof(inbuf))) /* can't happen */
return -EINVAL;
memcpy(MCDI_PTR(inbuf, MAE_ENCAP_HEADER_ALLOC_IN_HDR_DATA),
encap->encap_hdr,
encap->encap_hdr_len);
rc = efx_mcdi_rpc(efx, MC_CMD_MAE_ENCAP_HEADER_ALLOC, inbuf,
inlen, outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < sizeof(outbuf))
return -EIO;
encap->fw_id = MCDI_DWORD(outbuf, MAE_ENCAP_HEADER_ALLOC_OUT_ENCAP_HEADER_ID);
return 0;
}
int efx_mae_update_encap_md(struct efx_nic *efx,
struct efx_tc_encap_action *encap)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_ENCAP_HEADER_UPDATE_IN_LEN(EFX_TC_MAX_ENCAP_HDR));
size_t inlen;
int rc;
rc = efx_mae_encap_type_to_mae_type(encap->type);
if (rc < 0)
return rc;
MCDI_SET_DWORD(inbuf, MAE_ENCAP_HEADER_UPDATE_IN_ENCAP_TYPE, rc);
MCDI_SET_DWORD(inbuf, MAE_ENCAP_HEADER_UPDATE_IN_EH_ID,
encap->fw_id);
inlen = MC_CMD_MAE_ENCAP_HEADER_UPDATE_IN_LEN(encap->encap_hdr_len);
if (WARN_ON(inlen > sizeof(inbuf))) /* can't happen */
return -EINVAL;
memcpy(MCDI_PTR(inbuf, MAE_ENCAP_HEADER_UPDATE_IN_HDR_DATA),
encap->encap_hdr,
encap->encap_hdr_len);
BUILD_BUG_ON(MC_CMD_MAE_ENCAP_HEADER_UPDATE_OUT_LEN != 0);
return efx_mcdi_rpc(efx, MC_CMD_MAE_ENCAP_HEADER_UPDATE, inbuf,
inlen, NULL, 0, NULL);
}
int efx_mae_free_encap_md(struct efx_nic *efx,
struct efx_tc_encap_action *encap)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_MAE_ENCAP_HEADER_FREE_OUT_LEN(1));
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_ENCAP_HEADER_FREE_IN_LEN(1));
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, MAE_ENCAP_HEADER_FREE_IN_EH_ID, encap->fw_id);
rc = efx_mcdi_rpc(efx, MC_CMD_MAE_ENCAP_HEADER_FREE, inbuf,
sizeof(inbuf), outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < sizeof(outbuf))
return -EIO;
/* FW freed a different ID than we asked for, should also never happen.
* Warn because it means we've now got a different idea to the FW of
* what encap_mds exist, which could cause mayhem later.
*/
if (WARN_ON(MCDI_DWORD(outbuf, MAE_ENCAP_HEADER_FREE_OUT_FREED_EH_ID) != encap->fw_id))
return -EIO;
/* We're probably about to free @encap, but let's just make sure its
* fw_id is blatted so that it won't look valid if it leaks out.
*/
encap->fw_id = MC_CMD_MAE_ENCAP_HEADER_ALLOC_OUT_ENCAP_HEADER_ID_NULL;
return 0;
}
int efx_mae_lookup_mport(struct efx_nic *efx, u32 vf_idx, u32 *id)
{
struct ef100_nic_data *nic_data = efx->nic_data;
struct efx_mae *mae = efx->mae;
struct rhashtable_iter walk;
struct mae_mport_desc *m;
int rc = -ENOENT;
rhashtable_walk_enter(&mae->mports_ht, &walk);
rhashtable_walk_start(&walk);
while ((m = rhashtable_walk_next(&walk)) != NULL) {
if (m->mport_type == MAE_MPORT_DESC_MPORT_TYPE_VNIC &&
m->interface_idx == nic_data->local_mae_intf &&
m->pf_idx == 0 &&
m->vf_idx == vf_idx) {
*id = m->mport_id;
rc = 0;
break;
}
}
rhashtable_walk_stop(&walk);
rhashtable_walk_exit(&walk);
return rc;
}
static bool efx_mae_asl_id(u32 id)
{
return !!(id & BIT(31));
}
/* mport handling */
static const struct rhashtable_params efx_mae_mports_ht_params = {
.key_len = sizeof(u32),
.key_offset = offsetof(struct mae_mport_desc, mport_id),
.head_offset = offsetof(struct mae_mport_desc, linkage),
};
struct mae_mport_desc *efx_mae_get_mport(struct efx_nic *efx, u32 mport_id)
{
return rhashtable_lookup_fast(&efx->mae->mports_ht, &mport_id,
efx_mae_mports_ht_params);
}
static int efx_mae_add_mport(struct efx_nic *efx, struct mae_mport_desc *desc)
{
struct efx_mae *mae = efx->mae;
int rc;
rc = rhashtable_insert_fast(&mae->mports_ht, &desc->linkage,
efx_mae_mports_ht_params);
if (rc) {
pci_err(efx->pci_dev, "Failed to insert MPORT %08x, rc %d\n",
desc->mport_id, rc);
kfree(desc);
return rc;
}
return rc;
}
void efx_mae_remove_mport(void *desc, void *arg)
{
struct mae_mport_desc *mport = desc;
synchronize_rcu();
kfree(mport);
}
static int efx_mae_process_mport(struct efx_nic *efx,
struct mae_mport_desc *desc)
{
struct ef100_nic_data *nic_data = efx->nic_data;
struct mae_mport_desc *mport;
mport = efx_mae_get_mport(efx, desc->mport_id);
if (!IS_ERR_OR_NULL(mport)) {
netif_err(efx, drv, efx->net_dev,
"mport with id %u does exist!!!\n", desc->mport_id);
return -EEXIST;
}
if (nic_data->have_own_mport &&
desc->mport_id == nic_data->own_mport) {
WARN_ON(desc->mport_type != MAE_MPORT_DESC_MPORT_TYPE_VNIC);
WARN_ON(desc->vnic_client_type !=
MAE_MPORT_DESC_VNIC_CLIENT_TYPE_FUNCTION);
nic_data->local_mae_intf = desc->interface_idx;
nic_data->have_local_intf = true;
pci_dbg(efx->pci_dev, "MAE interface_idx is %u\n",
nic_data->local_mae_intf);
}
return efx_mae_add_mport(efx, desc);
}
#define MCDI_MPORT_JOURNAL_LEN \
ALIGN(MC_CMD_MAE_MPORT_READ_JOURNAL_OUT_LENMAX_MCDI2, 4)
int efx_mae_enumerate_mports(struct efx_nic *efx)
{
efx_dword_t *outbuf = kzalloc(MCDI_MPORT_JOURNAL_LEN, GFP_KERNEL);
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_MPORT_READ_JOURNAL_IN_LEN);
MCDI_DECLARE_STRUCT_PTR(desc);
size_t outlen, stride, count;
int rc = 0, i;
if (!outbuf)
return -ENOMEM;
do {
rc = efx_mcdi_rpc(efx, MC_CMD_MAE_MPORT_READ_JOURNAL, inbuf,
sizeof(inbuf), outbuf,
MCDI_MPORT_JOURNAL_LEN, &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_MAE_MPORT_READ_JOURNAL_OUT_MPORT_DESC_DATA_OFST) {
rc = -EIO;
goto fail;
}
count = MCDI_DWORD(outbuf, MAE_MPORT_READ_JOURNAL_OUT_MPORT_DESC_COUNT);
if (!count)
continue; /* not break; we want to look at MORE flag */
stride = MCDI_DWORD(outbuf, MAE_MPORT_READ_JOURNAL_OUT_SIZEOF_MPORT_DESC);
if (stride < MAE_MPORT_DESC_LEN) {
rc = -EIO;
goto fail;
}
if (outlen < MC_CMD_MAE_MPORT_READ_JOURNAL_OUT_LEN(count * stride)) {
rc = -EIO;
goto fail;
}
for (i = 0; i < count; i++) {
struct mae_mport_desc *d;
d = kzalloc(sizeof(*d), GFP_KERNEL);
if (!d) {
rc = -ENOMEM;
goto fail;
}
desc = (efx_dword_t *)
_MCDI_PTR(outbuf, MC_CMD_MAE_MPORT_READ_JOURNAL_OUT_MPORT_DESC_DATA_OFST +
i * stride);
d->mport_id = MCDI_STRUCT_DWORD(desc, MAE_MPORT_DESC_MPORT_ID);
d->flags = MCDI_STRUCT_DWORD(desc, MAE_MPORT_DESC_FLAGS);
d->caller_flags = MCDI_STRUCT_DWORD(desc,
MAE_MPORT_DESC_CALLER_FLAGS);
d->mport_type = MCDI_STRUCT_DWORD(desc,
MAE_MPORT_DESC_MPORT_TYPE);
switch (d->mport_type) {
case MAE_MPORT_DESC_MPORT_TYPE_NET_PORT:
d->port_idx = MCDI_STRUCT_DWORD(desc,
MAE_MPORT_DESC_NET_PORT_IDX);
break;
case MAE_MPORT_DESC_MPORT_TYPE_ALIAS:
d->alias_mport_id = MCDI_STRUCT_DWORD(desc,
MAE_MPORT_DESC_ALIAS_DELIVER_MPORT_ID);
break;
case MAE_MPORT_DESC_MPORT_TYPE_VNIC:
d->vnic_client_type = MCDI_STRUCT_DWORD(desc,
MAE_MPORT_DESC_VNIC_CLIENT_TYPE);
d->interface_idx = MCDI_STRUCT_DWORD(desc,
MAE_MPORT_DESC_VNIC_FUNCTION_INTERFACE);
d->pf_idx = MCDI_STRUCT_WORD(desc,
MAE_MPORT_DESC_VNIC_FUNCTION_PF_IDX);
d->vf_idx = MCDI_STRUCT_WORD(desc,
MAE_MPORT_DESC_VNIC_FUNCTION_VF_IDX);
break;
default:
/* Unknown mport_type, just accept it */
break;
}
rc = efx_mae_process_mport(efx, d);
/* Any failure will be due to memory allocation faiure,
* so there is no point to try subsequent entries.
*/
if (rc)
goto fail;
}
} while (MCDI_FIELD(outbuf, MAE_MPORT_READ_JOURNAL_OUT, MORE) &&
!WARN_ON(!count));
fail:
kfree(outbuf);
return rc;
}
/**
* efx_mae_allocate_pedit_mac() - allocate pedit MAC address in HW.
* @efx: NIC we're installing a pedit MAC address on
* @ped: pedit MAC action to be installed
*
* Attempts to install @ped in HW and populates its id with an index of this
* entry in the firmware MAC address table on success.
*
* Return: negative value on error, 0 in success.
*/
int efx_mae_allocate_pedit_mac(struct efx_nic *efx,
struct efx_tc_mac_pedit_action *ped)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_MAE_MAC_ADDR_ALLOC_OUT_LEN);
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_MAC_ADDR_ALLOC_IN_LEN);
size_t outlen;
int rc;
BUILD_BUG_ON(MC_CMD_MAE_MAC_ADDR_ALLOC_IN_MAC_ADDR_LEN !=
sizeof(ped->h_addr));
memcpy(MCDI_PTR(inbuf, MAE_MAC_ADDR_ALLOC_IN_MAC_ADDR), ped->h_addr,
sizeof(ped->h_addr));
rc = efx_mcdi_rpc(efx, MC_CMD_MAE_MAC_ADDR_ALLOC, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < sizeof(outbuf))
return -EIO;
ped->fw_id = MCDI_DWORD(outbuf, MAE_MAC_ADDR_ALLOC_OUT_MAC_ID);
return 0;
}
/**
* efx_mae_free_pedit_mac() - free pedit MAC address in HW.
* @efx: NIC we're installing a pedit MAC address on
* @ped: pedit MAC action that needs to be freed
*
* Frees @ped in HW, check that firmware did not free a different one and clears
* the id (which denotes the index of the entry in the MAC address table).
*/
void efx_mae_free_pedit_mac(struct efx_nic *efx,
struct efx_tc_mac_pedit_action *ped)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_MAE_MAC_ADDR_FREE_OUT_LEN(1));
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_MAC_ADDR_FREE_IN_LEN(1));
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, MAE_MAC_ADDR_FREE_IN_MAC_ID, ped->fw_id);
rc = efx_mcdi_rpc(efx, MC_CMD_MAE_MAC_ADDR_FREE, inbuf,
sizeof(inbuf), outbuf, sizeof(outbuf), &outlen);
if (rc || outlen < sizeof(outbuf))
return;
/* FW freed a different ID than we asked for, should also never happen.
* Warn because it means we've now got a different idea to the FW of
* what MAC addresses exist, which could cause mayhem later.
*/
if (WARN_ON(MCDI_DWORD(outbuf, MAE_MAC_ADDR_FREE_OUT_FREED_MAC_ID) != ped->fw_id))
return;
/* We're probably about to free @ped, but let's just make sure its
* fw_id is blatted so that it won't look valid if it leaks out.
*/
ped->fw_id = MC_CMD_MAE_MAC_ADDR_ALLOC_OUT_MAC_ID_NULL;
}
int efx_mae_alloc_action_set(struct efx_nic *efx, struct efx_tc_action_set *act)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_MAE_ACTION_SET_ALLOC_OUT_LEN);
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_ACTION_SET_ALLOC_IN_LEN);
size_t outlen;
int rc;
MCDI_POPULATE_DWORD_4(inbuf, MAE_ACTION_SET_ALLOC_IN_FLAGS,
MAE_ACTION_SET_ALLOC_IN_VLAN_PUSH, act->vlan_push,
MAE_ACTION_SET_ALLOC_IN_VLAN_POP, act->vlan_pop,
MAE_ACTION_SET_ALLOC_IN_DECAP, act->decap,
MAE_ACTION_SET_ALLOC_IN_DO_DECR_IP_TTL,
act->do_ttl_dec);
if (act->src_mac)
MCDI_SET_DWORD(inbuf, MAE_ACTION_SET_ALLOC_IN_SRC_MAC_ID,
act->src_mac->fw_id);
else
MCDI_SET_DWORD(inbuf, MAE_ACTION_SET_ALLOC_IN_SRC_MAC_ID,
MC_CMD_MAE_MAC_ADDR_ALLOC_OUT_MAC_ID_NULL);
if (act->dst_mac)
MCDI_SET_DWORD(inbuf, MAE_ACTION_SET_ALLOC_IN_DST_MAC_ID,
act->dst_mac->fw_id);
else
MCDI_SET_DWORD(inbuf, MAE_ACTION_SET_ALLOC_IN_DST_MAC_ID,
MC_CMD_MAE_MAC_ADDR_ALLOC_OUT_MAC_ID_NULL);
if (act->count && !WARN_ON(!act->count->cnt))
MCDI_SET_DWORD(inbuf, MAE_ACTION_SET_ALLOC_IN_COUNTER_ID,
act->count->cnt->fw_id);
else
MCDI_SET_DWORD(inbuf, MAE_ACTION_SET_ALLOC_IN_COUNTER_ID,
MC_CMD_MAE_COUNTER_ALLOC_OUT_COUNTER_ID_NULL);
MCDI_SET_DWORD(inbuf, MAE_ACTION_SET_ALLOC_IN_COUNTER_LIST_ID,
MC_CMD_MAE_COUNTER_LIST_ALLOC_OUT_COUNTER_LIST_ID_NULL);
if (act->vlan_push) {
MCDI_SET_WORD_BE(inbuf, MAE_ACTION_SET_ALLOC_IN_VLAN0_TCI_BE,
act->vlan_tci[0]);
MCDI_SET_WORD_BE(inbuf, MAE_ACTION_SET_ALLOC_IN_VLAN0_PROTO_BE,
act->vlan_proto[0]);
}
if (act->vlan_push >= 2) {
MCDI_SET_WORD_BE(inbuf, MAE_ACTION_SET_ALLOC_IN_VLAN1_TCI_BE,
act->vlan_tci[1]);
MCDI_SET_WORD_BE(inbuf, MAE_ACTION_SET_ALLOC_IN_VLAN1_PROTO_BE,
act->vlan_proto[1]);
}
if (act->encap_md)
MCDI_SET_DWORD(inbuf, MAE_ACTION_SET_ALLOC_IN_ENCAP_HEADER_ID,
act->encap_md->fw_id);
else
MCDI_SET_DWORD(inbuf, MAE_ACTION_SET_ALLOC_IN_ENCAP_HEADER_ID,
MC_CMD_MAE_ENCAP_HEADER_ALLOC_OUT_ENCAP_HEADER_ID_NULL);
if (act->deliver)
MCDI_SET_DWORD(inbuf, MAE_ACTION_SET_ALLOC_IN_DELIVER,
act->dest_mport);
BUILD_BUG_ON(MAE_MPORT_SELECTOR_NULL);
rc = efx_mcdi_rpc(efx, MC_CMD_MAE_ACTION_SET_ALLOC, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < sizeof(outbuf))
return -EIO;
act->fw_id = MCDI_DWORD(outbuf, MAE_ACTION_SET_ALLOC_OUT_AS_ID);
/* We rely on the high bit of AS IDs always being clear.
* The firmware API guarantees this, but let's check it ourselves.
*/
if (WARN_ON_ONCE(efx_mae_asl_id(act->fw_id))) {
efx_mae_free_action_set(efx, act->fw_id);
return -EIO;
}
return 0;
}
int efx_mae_free_action_set(struct efx_nic *efx, u32 fw_id)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_MAE_ACTION_SET_FREE_OUT_LEN(1));
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_ACTION_SET_FREE_IN_LEN(1));
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, MAE_ACTION_SET_FREE_IN_AS_ID, fw_id);
rc = efx_mcdi_rpc(efx, MC_CMD_MAE_ACTION_SET_FREE, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < sizeof(outbuf))
return -EIO;
/* FW freed a different ID than we asked for, should never happen.
* Warn because it means we've now got a different idea to the FW of
* what action-sets exist, which could cause mayhem later.
*/
if (WARN_ON(MCDI_DWORD(outbuf, MAE_ACTION_SET_FREE_OUT_FREED_AS_ID) != fw_id))
return -EIO;
return 0;
}
int efx_mae_alloc_action_set_list(struct efx_nic *efx,
struct efx_tc_action_set_list *acts)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_MAE_ACTION_SET_LIST_ALLOC_OUT_LEN);
struct efx_tc_action_set *act;
size_t inlen, outlen, i = 0;
efx_dword_t *inbuf;
int rc;
list_for_each_entry(act, &acts->list, list)
i++;
if (i == 0)
return -EINVAL;
if (i == 1) {
/* Don't wrap an ASL around a single AS, just use the AS_ID
* directly. ASLs are a more limited resource.
*/
act = list_first_entry(&acts->list, struct efx_tc_action_set, list);
acts->fw_id = act->fw_id;
return 0;
}
if (i > MC_CMD_MAE_ACTION_SET_LIST_ALLOC_IN_AS_IDS_MAXNUM_MCDI2)
return -EOPNOTSUPP; /* Too many actions */
inlen = MC_CMD_MAE_ACTION_SET_LIST_ALLOC_IN_LEN(i);
inbuf = kzalloc(inlen, GFP_KERNEL);
if (!inbuf)
return -ENOMEM;
i = 0;
list_for_each_entry(act, &acts->list, list) {
MCDI_SET_ARRAY_DWORD(inbuf, MAE_ACTION_SET_LIST_ALLOC_IN_AS_IDS,
i, act->fw_id);
i++;
}
MCDI_SET_DWORD(inbuf, MAE_ACTION_SET_LIST_ALLOC_IN_COUNT, i);
rc = efx_mcdi_rpc(efx, MC_CMD_MAE_ACTION_SET_LIST_ALLOC, inbuf, inlen,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto out_free;
if (outlen < sizeof(outbuf)) {
rc = -EIO;
goto out_free;
}
acts->fw_id = MCDI_DWORD(outbuf, MAE_ACTION_SET_LIST_ALLOC_OUT_ASL_ID);
/* We rely on the high bit of ASL IDs always being set.
* The firmware API guarantees this, but let's check it ourselves.
*/
if (WARN_ON_ONCE(!efx_mae_asl_id(acts->fw_id))) {
efx_mae_free_action_set_list(efx, acts);
rc = -EIO;
}
out_free:
kfree(inbuf);
return rc;
}
int efx_mae_free_action_set_list(struct efx_nic *efx,
struct efx_tc_action_set_list *acts)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_MAE_ACTION_SET_LIST_FREE_OUT_LEN(1));
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_ACTION_SET_LIST_FREE_IN_LEN(1));
size_t outlen;
int rc;
/* If this is just an AS_ID with no ASL wrapper, then there is
* nothing for us to free. (The AS will be freed later.)
*/
if (efx_mae_asl_id(acts->fw_id)) {
MCDI_SET_DWORD(inbuf, MAE_ACTION_SET_LIST_FREE_IN_ASL_ID,
acts->fw_id);
rc = efx_mcdi_rpc(efx, MC_CMD_MAE_ACTION_SET_LIST_FREE, inbuf,
sizeof(inbuf), outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < sizeof(outbuf))
return -EIO;
/* FW freed a different ID than we asked for, should never happen.
* Warn because it means we've now got a different idea to the FW of
* what action-set-lists exist, which could cause mayhem later.
*/
if (WARN_ON(MCDI_DWORD(outbuf, MAE_ACTION_SET_LIST_FREE_OUT_FREED_ASL_ID) != acts->fw_id))
return -EIO;
}
/* We're probably about to free @acts, but let's just make sure its
* fw_id is blatted so that it won't look valid if it leaks out.
*/
acts->fw_id = MC_CMD_MAE_ACTION_SET_LIST_ALLOC_OUT_ACTION_SET_LIST_ID_NULL;
return 0;
}
int efx_mae_register_encap_match(struct efx_nic *efx,
struct efx_tc_encap_match *encap)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_OUTER_RULE_INSERT_IN_LEN(MAE_ENC_FIELD_PAIRS_LEN));
MCDI_DECLARE_BUF(outbuf, MC_CMD_MAE_OUTER_RULE_INSERT_OUT_LEN);
MCDI_DECLARE_STRUCT_PTR(match_crit);
size_t outlen;
int rc;
rc = efx_mae_encap_type_to_mae_type(encap->tun_type);
if (rc < 0)
return rc;
match_crit = _MCDI_DWORD(inbuf, MAE_OUTER_RULE_INSERT_IN_FIELD_MATCH_CRITERIA);
/* The struct contains IP src and dst, and udp dport.
* So we actually need to filter on IP src and dst, L4 dport, and
* ipproto == udp.
*/
MCDI_SET_DWORD(inbuf, MAE_OUTER_RULE_INSERT_IN_ENCAP_TYPE, rc);
#ifdef CONFIG_IPV6
if (encap->src_ip | encap->dst_ip) {
#endif
MCDI_STRUCT_SET_DWORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_SRC_IP4_BE,
encap->src_ip);
MCDI_STRUCT_SET_DWORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_SRC_IP4_BE_MASK,
~(__be32)0);
MCDI_STRUCT_SET_DWORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_DST_IP4_BE,
encap->dst_ip);
MCDI_STRUCT_SET_DWORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_DST_IP4_BE_MASK,
~(__be32)0);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_ETHER_TYPE_BE,
htons(ETH_P_IP));
#ifdef CONFIG_IPV6
} else {
memcpy(MCDI_STRUCT_PTR(match_crit, MAE_ENC_FIELD_PAIRS_ENC_SRC_IP6_BE),
&encap->src_ip6, sizeof(encap->src_ip6));
memset(MCDI_STRUCT_PTR(match_crit, MAE_ENC_FIELD_PAIRS_ENC_SRC_IP6_BE_MASK),
0xff, sizeof(encap->src_ip6));
memcpy(MCDI_STRUCT_PTR(match_crit, MAE_ENC_FIELD_PAIRS_ENC_DST_IP6_BE),
&encap->dst_ip6, sizeof(encap->dst_ip6));
memset(MCDI_STRUCT_PTR(match_crit, MAE_ENC_FIELD_PAIRS_ENC_DST_IP6_BE_MASK),
0xff, sizeof(encap->dst_ip6));
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_ETHER_TYPE_BE,
htons(ETH_P_IPV6));
}
#endif
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_ETHER_TYPE_BE_MASK,
~(__be16)0);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_L4_DPORT_BE,
encap->udp_dport);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_L4_DPORT_BE_MASK,
~(__be16)0);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_L4_DPORT_BE,
encap->udp_sport);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_L4_DPORT_BE_MASK,
encap->udp_sport_mask);
MCDI_STRUCT_SET_BYTE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_IP_PROTO, IPPROTO_UDP);
MCDI_STRUCT_SET_BYTE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_IP_PROTO_MASK, ~0);
MCDI_STRUCT_SET_BYTE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_IP_TOS,
encap->ip_tos);
MCDI_STRUCT_SET_BYTE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_IP_TOS_MASK,
encap->ip_tos_mask);
rc = efx_mcdi_rpc(efx, MC_CMD_MAE_OUTER_RULE_INSERT, inbuf,
sizeof(inbuf), outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < sizeof(outbuf))
return -EIO;
encap->fw_id = MCDI_DWORD(outbuf, MAE_OUTER_RULE_INSERT_OUT_OR_ID);
return 0;
}
int efx_mae_unregister_encap_match(struct efx_nic *efx,
struct efx_tc_encap_match *encap)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_MAE_OUTER_RULE_REMOVE_OUT_LEN(1));
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_OUTER_RULE_REMOVE_IN_LEN(1));
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, MAE_OUTER_RULE_REMOVE_IN_OR_ID, encap->fw_id);
rc = efx_mcdi_rpc(efx, MC_CMD_MAE_OUTER_RULE_REMOVE, inbuf,
sizeof(inbuf), outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < sizeof(outbuf))
return -EIO;
/* FW freed a different ID than we asked for, should also never happen.
* Warn because it means we've now got a different idea to the FW of
* what encap_mds exist, which could cause mayhem later.
*/
if (WARN_ON(MCDI_DWORD(outbuf, MAE_OUTER_RULE_REMOVE_OUT_REMOVED_OR_ID) != encap->fw_id))
return -EIO;
/* We're probably about to free @encap, but let's just make sure its
* fw_id is blatted so that it won't look valid if it leaks out.
*/
encap->fw_id = MC_CMD_MAE_OUTER_RULE_INSERT_OUT_OUTER_RULE_ID_NULL;
return 0;
}
static int efx_mae_populate_lhs_match_criteria(MCDI_DECLARE_STRUCT_PTR(match_crit),
const struct efx_tc_match *match)
{
if (match->mask.ingress_port) {
if (~match->mask.ingress_port)
return -EOPNOTSUPP;
MCDI_STRUCT_SET_DWORD(match_crit,
MAE_ENC_FIELD_PAIRS_INGRESS_MPORT_SELECTOR,
match->value.ingress_port);
}
MCDI_STRUCT_SET_DWORD(match_crit, MAE_ENC_FIELD_PAIRS_INGRESS_MPORT_SELECTOR_MASK,
match->mask.ingress_port);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_ETHER_TYPE_BE,
match->value.eth_proto);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_ETHER_TYPE_BE_MASK,
match->mask.eth_proto);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_VLAN0_TCI_BE,
match->value.vlan_tci[0]);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_VLAN0_TCI_BE_MASK,
match->mask.vlan_tci[0]);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_VLAN0_PROTO_BE,
match->value.vlan_proto[0]);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_VLAN0_PROTO_BE_MASK,
match->mask.vlan_proto[0]);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_VLAN1_TCI_BE,
match->value.vlan_tci[1]);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_VLAN1_TCI_BE_MASK,
match->mask.vlan_tci[1]);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_VLAN1_PROTO_BE,
match->value.vlan_proto[1]);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_VLAN1_PROTO_BE_MASK,
match->mask.vlan_proto[1]);
memcpy(MCDI_STRUCT_PTR(match_crit, MAE_ENC_FIELD_PAIRS_ENC_ETH_SADDR_BE),
match->value.eth_saddr, ETH_ALEN);
memcpy(MCDI_STRUCT_PTR(match_crit, MAE_ENC_FIELD_PAIRS_ENC_ETH_SADDR_BE_MASK),
match->mask.eth_saddr, ETH_ALEN);
memcpy(MCDI_STRUCT_PTR(match_crit, MAE_ENC_FIELD_PAIRS_ENC_ETH_DADDR_BE),
match->value.eth_daddr, ETH_ALEN);
memcpy(MCDI_STRUCT_PTR(match_crit, MAE_ENC_FIELD_PAIRS_ENC_ETH_DADDR_BE_MASK),
match->mask.eth_daddr, ETH_ALEN);
MCDI_STRUCT_SET_BYTE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_IP_PROTO,
match->value.ip_proto);
MCDI_STRUCT_SET_BYTE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_IP_PROTO_MASK,
match->mask.ip_proto);
MCDI_STRUCT_SET_BYTE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_IP_TOS,
match->value.ip_tos);
MCDI_STRUCT_SET_BYTE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_IP_TOS_MASK,
match->mask.ip_tos);
MCDI_STRUCT_SET_BYTE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_IP_TTL,
match->value.ip_ttl);
MCDI_STRUCT_SET_BYTE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_IP_TTL_MASK,
match->mask.ip_ttl);
MCDI_STRUCT_POPULATE_BYTE_1(match_crit,
MAE_ENC_FIELD_PAIRS_ENC_VLAN_FLAGS,
MAE_ENC_FIELD_PAIRS_ENC_IP_FRAG,
match->value.ip_frag);
MCDI_STRUCT_POPULATE_BYTE_1(match_crit,
MAE_ENC_FIELD_PAIRS_ENC_VLAN_FLAGS_MASK,
MAE_ENC_FIELD_PAIRS_ENC_IP_FRAG_MASK,
match->mask.ip_frag);
MCDI_STRUCT_SET_DWORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_SRC_IP4_BE,
match->value.src_ip);
MCDI_STRUCT_SET_DWORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_SRC_IP4_BE_MASK,
match->mask.src_ip);
MCDI_STRUCT_SET_DWORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_DST_IP4_BE,
match->value.dst_ip);
MCDI_STRUCT_SET_DWORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_DST_IP4_BE_MASK,
match->mask.dst_ip);
#ifdef CONFIG_IPV6
memcpy(MCDI_STRUCT_PTR(match_crit, MAE_ENC_FIELD_PAIRS_ENC_SRC_IP6_BE),
&match->value.src_ip6, sizeof(struct in6_addr));
memcpy(MCDI_STRUCT_PTR(match_crit, MAE_ENC_FIELD_PAIRS_ENC_SRC_IP6_BE_MASK),
&match->mask.src_ip6, sizeof(struct in6_addr));
memcpy(MCDI_STRUCT_PTR(match_crit, MAE_ENC_FIELD_PAIRS_ENC_DST_IP6_BE),
&match->value.dst_ip6, sizeof(struct in6_addr));
memcpy(MCDI_STRUCT_PTR(match_crit, MAE_ENC_FIELD_PAIRS_ENC_DST_IP6_BE_MASK),
&match->mask.dst_ip6, sizeof(struct in6_addr));
#endif
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_L4_SPORT_BE,
match->value.l4_sport);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_L4_SPORT_BE_MASK,
match->mask.l4_sport);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_L4_DPORT_BE,
match->value.l4_dport);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_ENC_FIELD_PAIRS_ENC_L4_DPORT_BE_MASK,
match->mask.l4_dport);
/* No enc-keys in LHS rules. Caps check should have caught this; any
* enc-keys from an fLHS should have been translated to regular keys
* and any EM should be a pseudo (we're an OR so can't have a direct
* EM with another OR).
*/
if (WARN_ON_ONCE(match->encap && !match->encap->type))
return -EOPNOTSUPP;
if (WARN_ON_ONCE(match->mask.enc_src_ip))
return -EOPNOTSUPP;
if (WARN_ON_ONCE(match->mask.enc_dst_ip))
return -EOPNOTSUPP;
#ifdef CONFIG_IPV6
if (WARN_ON_ONCE(!ipv6_addr_any(&match->mask.enc_src_ip6)))
return -EOPNOTSUPP;
if (WARN_ON_ONCE(!ipv6_addr_any(&match->mask.enc_dst_ip6)))
return -EOPNOTSUPP;
#endif
if (WARN_ON_ONCE(match->mask.enc_ip_tos))
return -EOPNOTSUPP;
if (WARN_ON_ONCE(match->mask.enc_ip_ttl))
return -EOPNOTSUPP;
if (WARN_ON_ONCE(match->mask.enc_sport))
return -EOPNOTSUPP;
if (WARN_ON_ONCE(match->mask.enc_dport))
return -EOPNOTSUPP;
if (WARN_ON_ONCE(match->mask.enc_keyid))
return -EOPNOTSUPP;
return 0;
}
static int efx_mae_insert_lhs_outer_rule(struct efx_nic *efx,
struct efx_tc_lhs_rule *rule, u32 prio)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_OUTER_RULE_INSERT_IN_LEN(MAE_ENC_FIELD_PAIRS_LEN));
MCDI_DECLARE_BUF(outbuf, MC_CMD_MAE_OUTER_RULE_INSERT_OUT_LEN);
MCDI_DECLARE_STRUCT_PTR(match_crit);
const struct efx_tc_lhs_action *act;
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, MAE_OUTER_RULE_INSERT_IN_PRIO, prio);
/* match */
match_crit = _MCDI_DWORD(inbuf, MAE_OUTER_RULE_INSERT_IN_FIELD_MATCH_CRITERIA);
rc = efx_mae_populate_lhs_match_criteria(match_crit, &rule->match);
if (rc)
return rc;
/* action */
act = &rule->lhs_act;
MCDI_SET_DWORD(inbuf, MAE_OUTER_RULE_INSERT_IN_ENCAP_TYPE,
MAE_MCDI_ENCAP_TYPE_NONE);
/* We always inhibit CT lookup on TCP_INTERESTING_FLAGS, since the
* SW path needs to process the packet to update the conntrack tables
* on connection establishment (SYN) or termination (FIN, RST).
*/
MCDI_POPULATE_DWORD_6(inbuf, MAE_OUTER_RULE_INSERT_IN_LOOKUP_CONTROL,
MAE_OUTER_RULE_INSERT_IN_DO_CT, !!act->zone,
MAE_OUTER_RULE_INSERT_IN_CT_TCP_FLAGS_INHIBIT, 1,
MAE_OUTER_RULE_INSERT_IN_CT_DOMAIN,
act->zone ? act->zone->zone : 0,
MAE_OUTER_RULE_INSERT_IN_CT_VNI_MODE,
MAE_CT_VNI_MODE_ZERO,
MAE_OUTER_RULE_INSERT_IN_DO_COUNT, !!act->count,
MAE_OUTER_RULE_INSERT_IN_RECIRC_ID,
act->rid ? act->rid->fw_id : 0);
if (act->count)
MCDI_SET_DWORD(inbuf, MAE_OUTER_RULE_INSERT_IN_COUNTER_ID,
act->count->cnt->fw_id);
rc = efx_mcdi_rpc(efx, MC_CMD_MAE_OUTER_RULE_INSERT, inbuf,
sizeof(inbuf), outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < sizeof(outbuf))
return -EIO;
rule->fw_id = MCDI_DWORD(outbuf, MAE_OUTER_RULE_INSERT_OUT_OR_ID);
return 0;
}
int efx_mae_insert_lhs_rule(struct efx_nic *efx, struct efx_tc_lhs_rule *rule,
u32 prio)
{
return efx_mae_insert_lhs_outer_rule(efx, rule, prio);
}
static int efx_mae_remove_lhs_outer_rule(struct efx_nic *efx,
struct efx_tc_lhs_rule *rule)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_MAE_OUTER_RULE_REMOVE_OUT_LEN(1));
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_OUTER_RULE_REMOVE_IN_LEN(1));
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, MAE_OUTER_RULE_REMOVE_IN_OR_ID, rule->fw_id);
rc = efx_mcdi_rpc(efx, MC_CMD_MAE_OUTER_RULE_REMOVE, inbuf,
sizeof(inbuf), outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < sizeof(outbuf))
return -EIO;
/* FW freed a different ID than we asked for, should also never happen.
* Warn because it means we've now got a different idea to the FW of
* what encap_mds exist, which could cause mayhem later.
*/
if (WARN_ON(MCDI_DWORD(outbuf, MAE_OUTER_RULE_REMOVE_OUT_REMOVED_OR_ID) != rule->fw_id))
return -EIO;
/* We're probably about to free @rule, but let's just make sure its
* fw_id is blatted so that it won't look valid if it leaks out.
*/
rule->fw_id = MC_CMD_MAE_OUTER_RULE_INSERT_OUT_OUTER_RULE_ID_NULL;
return 0;
}
int efx_mae_remove_lhs_rule(struct efx_nic *efx, struct efx_tc_lhs_rule *rule)
{
return efx_mae_remove_lhs_outer_rule(efx, rule);
}
/* Populating is done by taking each byte of @value in turn and storing
* it in the appropriate bits of @row. @value must be big-endian; we
* convert it to little-endianness as we go.
*/
static int efx_mae_table_populate(struct efx_tc_table_field_fmt field,
__le32 *row, size_t row_bits,
void *value, size_t value_size)
{
unsigned int i;
/* For now only scheme 0 is supported for any field, so we check here
* (rather than, say, in calling code, which knows the semantics and
* could in principle encode for other schemes).
*/
if (field.scheme)
return -EOPNOTSUPP;
if (DIV_ROUND_UP(field.width, 8) != value_size)
return -EINVAL;
if (field.lbn + field.width > row_bits)
return -EINVAL;
for (i = 0; i < value_size; i++) {
unsigned int bn = field.lbn + i * 8;
unsigned int wn = bn / 32;
u64 v;
v = ((u8 *)value)[value_size - i - 1];
v <<= (bn % 32);
row[wn] |= cpu_to_le32(v & 0xffffffff);
if (wn * 32 < row_bits)
row[wn + 1] |= cpu_to_le32(v >> 32);
}
return 0;
}
static int efx_mae_table_populate_bool(struct efx_tc_table_field_fmt field,
__le32 *row, size_t row_bits, bool value)
{
u8 v = value ? 1 : 0;
if (field.width != 1)
return -EINVAL;
return efx_mae_table_populate(field, row, row_bits, &v, 1);
}
static int efx_mae_table_populate_ipv4(struct efx_tc_table_field_fmt field,
__le32 *row, size_t row_bits, __be32 value)
{
/* IPv4 is placed in the first 4 bytes of an IPv6-sized field */
struct in6_addr v = {};
if (field.width != 128)
return -EINVAL;
v.s6_addr32[0] = value;
return efx_mae_table_populate(field, row, row_bits, &v, sizeof(v));
}
static int efx_mae_table_populate_u24(struct efx_tc_table_field_fmt field,
__le32 *row, size_t row_bits, u32 value)
{
__be32 v = cpu_to_be32(value);
/* We adjust value_size here since just 3 bytes will be copied, and
* the pointer to the value is set discarding the first byte which is
* the most significant byte for a big-endian 4-bytes value.
*/
return efx_mae_table_populate(field, row, row_bits, ((void *)&v) + 1,
sizeof(v) - 1);
}
#define _TABLE_POPULATE(dst, dw, _field, _value) ({ \
typeof(_value) _v = _value; \
\
(_field.width == sizeof(_value) * 8) ? \
efx_mae_table_populate(_field, dst, dw, &_v, \
sizeof(_v)) : -EINVAL; \
})
#define TABLE_POPULATE_KEY_IPV4(dst, _table, _field, _value) \
efx_mae_table_populate_ipv4(efx->tc->meta_##_table.desc.keys \
[efx->tc->meta_##_table.keys._field##_idx],\
dst, efx->tc->meta_##_table.desc.key_width,\
_value)
#define TABLE_POPULATE_KEY(dst, _table, _field, _value) \
_TABLE_POPULATE(dst, efx->tc->meta_##_table.desc.key_width, \
efx->tc->meta_##_table.desc.keys \
[efx->tc->meta_##_table.keys._field##_idx], \
_value)
#define TABLE_POPULATE_RESP_BOOL(dst, _table, _field, _value) \
efx_mae_table_populate_bool(efx->tc->meta_##_table.desc.resps \
[efx->tc->meta_##_table.resps._field##_idx],\
dst, efx->tc->meta_##_table.desc.resp_width,\
_value)
#define TABLE_POPULATE_RESP(dst, _table, _field, _value) \
_TABLE_POPULATE(dst, efx->tc->meta_##_table.desc.resp_width, \
efx->tc->meta_##_table.desc.resps \
[efx->tc->meta_##_table.resps._field##_idx], \
_value)
#define TABLE_POPULATE_RESP_U24(dst, _table, _field, _value) \
efx_mae_table_populate_u24(efx->tc->meta_##_table.desc.resps \
[efx->tc->meta_##_table.resps._field##_idx],\
dst, efx->tc->meta_##_table.desc.resp_width,\
_value)
static int efx_mae_populate_ct_key(struct efx_nic *efx, __le32 *key, size_t kw,
struct efx_tc_ct_entry *conn)
{
bool ipv6 = conn->eth_proto == htons(ETH_P_IPV6);
int rc;
rc = TABLE_POPULATE_KEY(key, ct, eth_proto, conn->eth_proto);
if (rc)
return rc;
rc = TABLE_POPULATE_KEY(key, ct, ip_proto, conn->ip_proto);
if (rc)
return rc;
if (ipv6)
rc = TABLE_POPULATE_KEY(key, ct, src_ip, conn->src_ip6);
else
rc = TABLE_POPULATE_KEY_IPV4(key, ct, src_ip, conn->src_ip);
if (rc)
return rc;
if (ipv6)
rc = TABLE_POPULATE_KEY(key, ct, dst_ip, conn->dst_ip6);
else
rc = TABLE_POPULATE_KEY_IPV4(key, ct, dst_ip, conn->dst_ip);
if (rc)
return rc;
rc = TABLE_POPULATE_KEY(key, ct, l4_sport, conn->l4_sport);
if (rc)
return rc;
rc = TABLE_POPULATE_KEY(key, ct, l4_dport, conn->l4_dport);
if (rc)
return rc;
return TABLE_POPULATE_KEY(key, ct, zone, cpu_to_be16(conn->zone->zone));
}
int efx_mae_insert_ct(struct efx_nic *efx, struct efx_tc_ct_entry *conn)
{
bool ipv6 = conn->eth_proto == htons(ETH_P_IPV6);
__le32 *key = NULL, *resp = NULL;
size_t inlen, kw, rw;
efx_dword_t *inbuf;
int rc = -ENOMEM;
/* Check table access is supported */
if (!efx->tc->meta_ct.hooked)
return -EOPNOTSUPP;
/* key/resp widths are in bits; convert to dwords for IN_LEN */
kw = DIV_ROUND_UP(efx->tc->meta_ct.desc.key_width, 32);
rw = DIV_ROUND_UP(efx->tc->meta_ct.desc.resp_width, 32);
BUILD_BUG_ON(sizeof(__le32) != MC_CMD_TABLE_INSERT_IN_DATA_LEN);
inlen = MC_CMD_TABLE_INSERT_IN_LEN(kw + rw);
if (inlen > MC_CMD_TABLE_INSERT_IN_LENMAX_MCDI2)
return -E2BIG;
inbuf = kzalloc(inlen, GFP_KERNEL);
if (!inbuf)
return -ENOMEM;
key = kcalloc(kw, sizeof(__le32), GFP_KERNEL);
if (!key)
goto out_free;
resp = kcalloc(rw, sizeof(__le32), GFP_KERNEL);
if (!resp)
goto out_free;
rc = efx_mae_populate_ct_key(efx, key, kw, conn);
if (rc)
goto out_free;
rc = TABLE_POPULATE_RESP_BOOL(resp, ct, dnat, conn->dnat);
if (rc)
goto out_free;
/* No support in hw for IPv6 NAT; field is only 32 bits */
if (!ipv6)
rc = TABLE_POPULATE_RESP(resp, ct, nat_ip, conn->nat_ip);
if (rc)
goto out_free;
rc = TABLE_POPULATE_RESP(resp, ct, l4_natport, conn->l4_natport);
if (rc)
goto out_free;
rc = TABLE_POPULATE_RESP(resp, ct, mark, cpu_to_be32(conn->mark));
if (rc)
goto out_free;
rc = TABLE_POPULATE_RESP_U24(resp, ct, counter_id, conn->cnt->fw_id);
if (rc)
goto out_free;
MCDI_SET_DWORD(inbuf, TABLE_INSERT_IN_TABLE_ID, TABLE_ID_CONNTRACK_TABLE);
MCDI_SET_WORD(inbuf, TABLE_INSERT_IN_KEY_WIDTH,
efx->tc->meta_ct.desc.key_width);
/* MASK_WIDTH is zero as CT is a BCAM */
MCDI_SET_WORD(inbuf, TABLE_INSERT_IN_RESP_WIDTH,
efx->tc->meta_ct.desc.resp_width);
memcpy(MCDI_PTR(inbuf, TABLE_INSERT_IN_DATA), key, kw * sizeof(__le32));
memcpy(MCDI_PTR(inbuf, TABLE_INSERT_IN_DATA) + kw * sizeof(__le32),
resp, rw * sizeof(__le32));
BUILD_BUG_ON(MC_CMD_TABLE_INSERT_OUT_LEN);
rc = efx_mcdi_rpc(efx, MC_CMD_TABLE_INSERT, inbuf, inlen, NULL, 0, NULL);
out_free:
kfree(resp);
kfree(key);
kfree(inbuf);
return rc;
}
int efx_mae_remove_ct(struct efx_nic *efx, struct efx_tc_ct_entry *conn)
{
__le32 *key = NULL;
efx_dword_t *inbuf;
size_t inlen, kw;
int rc = -ENOMEM;
/* Check table access is supported */
if (!efx->tc->meta_ct.hooked)
return -EOPNOTSUPP;
/* key width is in bits; convert to dwords for IN_LEN */
kw = DIV_ROUND_UP(efx->tc->meta_ct.desc.key_width, 32);
BUILD_BUG_ON(sizeof(__le32) != MC_CMD_TABLE_DELETE_IN_DATA_LEN);
inlen = MC_CMD_TABLE_DELETE_IN_LEN(kw);
if (inlen > MC_CMD_TABLE_DELETE_IN_LENMAX_MCDI2)
return -E2BIG;
inbuf = kzalloc(inlen, GFP_KERNEL);
if (!inbuf)
return -ENOMEM;
key = kcalloc(kw, sizeof(__le32), GFP_KERNEL);
if (!key)
goto out_free;
rc = efx_mae_populate_ct_key(efx, key, kw, conn);
if (rc)
goto out_free;
MCDI_SET_DWORD(inbuf, TABLE_DELETE_IN_TABLE_ID, TABLE_ID_CONNTRACK_TABLE);
MCDI_SET_WORD(inbuf, TABLE_DELETE_IN_KEY_WIDTH,
efx->tc->meta_ct.desc.key_width);
/* MASK_WIDTH is zero as CT is a BCAM */
/* RESP_WIDTH is zero for DELETE */
memcpy(MCDI_PTR(inbuf, TABLE_DELETE_IN_DATA), key, kw * sizeof(__le32));
BUILD_BUG_ON(MC_CMD_TABLE_DELETE_OUT_LEN);
rc = efx_mcdi_rpc(efx, MC_CMD_TABLE_DELETE, inbuf, inlen, NULL, 0, NULL);
out_free:
kfree(key);
kfree(inbuf);
return rc;
}
static int efx_mae_populate_match_criteria(MCDI_DECLARE_STRUCT_PTR(match_crit),
const struct efx_tc_match *match)
{
if (match->mask.ingress_port) {
if (~match->mask.ingress_port)
return -EOPNOTSUPP;
MCDI_STRUCT_SET_DWORD(match_crit,
MAE_FIELD_MASK_VALUE_PAIRS_V2_INGRESS_MPORT_SELECTOR,
match->value.ingress_port);
}
MCDI_STRUCT_SET_DWORD(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_INGRESS_MPORT_SELECTOR_MASK,
match->mask.ingress_port);
EFX_POPULATE_DWORD_5(*_MCDI_STRUCT_DWORD(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_FLAGS),
MAE_FIELD_MASK_VALUE_PAIRS_V2_DO_CT,
match->value.ct_state_trk,
MAE_FIELD_MASK_VALUE_PAIRS_V2_CT_HIT,
match->value.ct_state_est,
MAE_FIELD_MASK_VALUE_PAIRS_V2_IS_IP_FRAG,
match->value.ip_frag,
MAE_FIELD_MASK_VALUE_PAIRS_V2_IP_FIRST_FRAG,
match->value.ip_firstfrag,
MAE_FIELD_MASK_VALUE_PAIRS_V2_TCP_SYN_FIN_RST,
match->value.tcp_syn_fin_rst);
EFX_POPULATE_DWORD_5(*_MCDI_STRUCT_DWORD(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_FLAGS_MASK),
MAE_FIELD_MASK_VALUE_PAIRS_V2_DO_CT,
match->mask.ct_state_trk,
MAE_FIELD_MASK_VALUE_PAIRS_V2_CT_HIT,
match->mask.ct_state_est,
MAE_FIELD_MASK_VALUE_PAIRS_V2_IS_IP_FRAG,
match->mask.ip_frag,
MAE_FIELD_MASK_VALUE_PAIRS_V2_IP_FIRST_FRAG,
match->mask.ip_firstfrag,
MAE_FIELD_MASK_VALUE_PAIRS_V2_TCP_SYN_FIN_RST,
match->mask.tcp_syn_fin_rst);
MCDI_STRUCT_SET_BYTE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_RECIRC_ID,
match->value.recirc_id);
MCDI_STRUCT_SET_BYTE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_RECIRC_ID_MASK,
match->mask.recirc_id);
MCDI_STRUCT_SET_DWORD(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_CT_MARK,
match->value.ct_mark);
MCDI_STRUCT_SET_DWORD(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_CT_MARK_MASK,
match->mask.ct_mark);
MCDI_STRUCT_SET_WORD(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_CT_DOMAIN,
match->value.ct_zone);
MCDI_STRUCT_SET_WORD(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_CT_DOMAIN_MASK,
match->mask.ct_zone);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_ETHER_TYPE_BE,
match->value.eth_proto);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_ETHER_TYPE_BE_MASK,
match->mask.eth_proto);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_VLAN0_TCI_BE,
match->value.vlan_tci[0]);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_VLAN0_TCI_BE_MASK,
match->mask.vlan_tci[0]);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_VLAN0_PROTO_BE,
match->value.vlan_proto[0]);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_VLAN0_PROTO_BE_MASK,
match->mask.vlan_proto[0]);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_VLAN1_TCI_BE,
match->value.vlan_tci[1]);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_VLAN1_TCI_BE_MASK,
match->mask.vlan_tci[1]);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_VLAN1_PROTO_BE,
match->value.vlan_proto[1]);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_VLAN1_PROTO_BE_MASK,
match->mask.vlan_proto[1]);
memcpy(MCDI_STRUCT_PTR(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_ETH_SADDR_BE),
match->value.eth_saddr, ETH_ALEN);
memcpy(MCDI_STRUCT_PTR(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_ETH_SADDR_BE_MASK),
match->mask.eth_saddr, ETH_ALEN);
memcpy(MCDI_STRUCT_PTR(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_ETH_DADDR_BE),
match->value.eth_daddr, ETH_ALEN);
memcpy(MCDI_STRUCT_PTR(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_ETH_DADDR_BE_MASK),
match->mask.eth_daddr, ETH_ALEN);
MCDI_STRUCT_SET_BYTE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_IP_PROTO,
match->value.ip_proto);
MCDI_STRUCT_SET_BYTE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_IP_PROTO_MASK,
match->mask.ip_proto);
MCDI_STRUCT_SET_BYTE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_IP_TOS,
match->value.ip_tos);
MCDI_STRUCT_SET_BYTE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_IP_TOS_MASK,
match->mask.ip_tos);
MCDI_STRUCT_SET_BYTE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_IP_TTL,
match->value.ip_ttl);
MCDI_STRUCT_SET_BYTE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_IP_TTL_MASK,
match->mask.ip_ttl);
MCDI_STRUCT_SET_DWORD_BE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_SRC_IP4_BE,
match->value.src_ip);
MCDI_STRUCT_SET_DWORD_BE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_SRC_IP4_BE_MASK,
match->mask.src_ip);
MCDI_STRUCT_SET_DWORD_BE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_DST_IP4_BE,
match->value.dst_ip);
MCDI_STRUCT_SET_DWORD_BE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_DST_IP4_BE_MASK,
match->mask.dst_ip);
#ifdef CONFIG_IPV6
memcpy(MCDI_STRUCT_PTR(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_SRC_IP6_BE),
&match->value.src_ip6, sizeof(struct in6_addr));
memcpy(MCDI_STRUCT_PTR(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_SRC_IP6_BE_MASK),
&match->mask.src_ip6, sizeof(struct in6_addr));
memcpy(MCDI_STRUCT_PTR(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_DST_IP6_BE),
&match->value.dst_ip6, sizeof(struct in6_addr));
memcpy(MCDI_STRUCT_PTR(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_DST_IP6_BE_MASK),
&match->mask.dst_ip6, sizeof(struct in6_addr));
#endif
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_L4_SPORT_BE,
match->value.l4_sport);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_L4_SPORT_BE_MASK,
match->mask.l4_sport);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_L4_DPORT_BE,
match->value.l4_dport);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_L4_DPORT_BE_MASK,
match->mask.l4_dport);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_TCP_FLAGS_BE,
match->value.tcp_flags);
MCDI_STRUCT_SET_WORD_BE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_TCP_FLAGS_BE_MASK,
match->mask.tcp_flags);
/* enc-keys are handled indirectly, through encap_match ID */
if (match->encap) {
MCDI_STRUCT_SET_DWORD(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_OUTER_RULE_ID,
match->encap->fw_id);
MCDI_STRUCT_SET_DWORD(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_OUTER_RULE_ID_MASK,
U32_MAX);
/* enc_keyid (VNI/VSID) is not part of the encap_match */
MCDI_STRUCT_SET_DWORD_BE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_ENC_VNET_ID_BE,
match->value.enc_keyid);
MCDI_STRUCT_SET_DWORD_BE(match_crit, MAE_FIELD_MASK_VALUE_PAIRS_V2_ENC_VNET_ID_BE_MASK,
match->mask.enc_keyid);
} else if (WARN_ON_ONCE(match->mask.enc_src_ip) ||
WARN_ON_ONCE(match->mask.enc_dst_ip) ||
WARN_ON_ONCE(!ipv6_addr_any(&match->mask.enc_src_ip6)) ||
WARN_ON_ONCE(!ipv6_addr_any(&match->mask.enc_dst_ip6)) ||
WARN_ON_ONCE(match->mask.enc_ip_tos) ||
WARN_ON_ONCE(match->mask.enc_ip_ttl) ||
WARN_ON_ONCE(match->mask.enc_sport) ||
WARN_ON_ONCE(match->mask.enc_dport) ||
WARN_ON_ONCE(match->mask.enc_keyid)) {
/* No enc-keys should appear in a rule without an encap_match */
return -EOPNOTSUPP;
}
return 0;
}
int efx_mae_insert_rule(struct efx_nic *efx, const struct efx_tc_match *match,
u32 prio, u32 acts_id, u32 *id)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_ACTION_RULE_INSERT_IN_LEN(MAE_FIELD_MASK_VALUE_PAIRS_V2_LEN));
MCDI_DECLARE_BUF(outbuf, MC_CMD_MAE_ACTION_RULE_INSERT_OUT_LEN);
MCDI_DECLARE_STRUCT_PTR(match_crit);
MCDI_DECLARE_STRUCT_PTR(response);
size_t outlen;
int rc;
if (!id)
return -EINVAL;
match_crit = _MCDI_DWORD(inbuf, MAE_ACTION_RULE_INSERT_IN_MATCH_CRITERIA);
response = _MCDI_DWORD(inbuf, MAE_ACTION_RULE_INSERT_IN_RESPONSE);
if (efx_mae_asl_id(acts_id)) {
MCDI_STRUCT_SET_DWORD(response, MAE_ACTION_RULE_RESPONSE_ASL_ID, acts_id);
MCDI_STRUCT_SET_DWORD(response, MAE_ACTION_RULE_RESPONSE_AS_ID,
MC_CMD_MAE_ACTION_SET_ALLOC_OUT_ACTION_SET_ID_NULL);
} else {
/* We only had one AS, so we didn't wrap it in an ASL */
MCDI_STRUCT_SET_DWORD(response, MAE_ACTION_RULE_RESPONSE_ASL_ID,
MC_CMD_MAE_ACTION_SET_LIST_ALLOC_OUT_ACTION_SET_LIST_ID_NULL);
MCDI_STRUCT_SET_DWORD(response, MAE_ACTION_RULE_RESPONSE_AS_ID, acts_id);
}
MCDI_SET_DWORD(inbuf, MAE_ACTION_RULE_INSERT_IN_PRIO, prio);
rc = efx_mae_populate_match_criteria(match_crit, match);
if (rc)
return rc;
rc = efx_mcdi_rpc(efx, MC_CMD_MAE_ACTION_RULE_INSERT, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < sizeof(outbuf))
return -EIO;
*id = MCDI_DWORD(outbuf, MAE_ACTION_RULE_INSERT_OUT_AR_ID);
return 0;
}
int efx_mae_update_rule(struct efx_nic *efx, u32 acts_id, u32 id)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_ACTION_RULE_UPDATE_IN_LEN);
MCDI_DECLARE_STRUCT_PTR(response);
BUILD_BUG_ON(MC_CMD_MAE_ACTION_RULE_UPDATE_OUT_LEN);
response = _MCDI_DWORD(inbuf, MAE_ACTION_RULE_UPDATE_IN_RESPONSE);
MCDI_SET_DWORD(inbuf, MAE_ACTION_RULE_UPDATE_IN_AR_ID, id);
if (efx_mae_asl_id(acts_id)) {
MCDI_STRUCT_SET_DWORD(response, MAE_ACTION_RULE_RESPONSE_ASL_ID, acts_id);
MCDI_STRUCT_SET_DWORD(response, MAE_ACTION_RULE_RESPONSE_AS_ID,
MC_CMD_MAE_ACTION_SET_ALLOC_OUT_ACTION_SET_ID_NULL);
} else {
/* We only had one AS, so we didn't wrap it in an ASL */
MCDI_STRUCT_SET_DWORD(response, MAE_ACTION_RULE_RESPONSE_ASL_ID,
MC_CMD_MAE_ACTION_SET_LIST_ALLOC_OUT_ACTION_SET_LIST_ID_NULL);
MCDI_STRUCT_SET_DWORD(response, MAE_ACTION_RULE_RESPONSE_AS_ID, acts_id);
}
return efx_mcdi_rpc(efx, MC_CMD_MAE_ACTION_RULE_UPDATE, inbuf, sizeof(inbuf),
NULL, 0, NULL);
}
int efx_mae_delete_rule(struct efx_nic *efx, u32 id)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_MAE_ACTION_RULE_DELETE_OUT_LEN(1));
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAE_ACTION_RULE_DELETE_IN_LEN(1));
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, MAE_ACTION_RULE_DELETE_IN_AR_ID, id);
rc = efx_mcdi_rpc(efx, MC_CMD_MAE_ACTION_RULE_DELETE, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < sizeof(outbuf))
return -EIO;
/* FW freed a different ID than we asked for, should also never happen.
* Warn because it means we've now got a different idea to the FW of
* what rules exist, which could cause mayhem later.
*/
if (WARN_ON(MCDI_DWORD(outbuf, MAE_ACTION_RULE_DELETE_OUT_DELETED_AR_ID) != id))
return -EIO;
return 0;
}
int efx_init_mae(struct efx_nic *efx)
{
struct ef100_nic_data *nic_data = efx->nic_data;
struct efx_mae *mae;
int rc;
if (!nic_data->have_mport)
return -EINVAL;
mae = kmalloc(sizeof(*mae), GFP_KERNEL);
if (!mae)
return -ENOMEM;
rc = rhashtable_init(&mae->mports_ht, &efx_mae_mports_ht_params);
if (rc < 0) {
kfree(mae);
return rc;
}
efx->mae = mae;
mae->efx = efx;
return 0;
}
void efx_fini_mae(struct efx_nic *efx)
{
struct efx_mae *mae = efx->mae;
kfree(mae);
efx->mae = NULL;
}
|
linux-master
|
drivers/net/ethernet/sfc/mae.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2018 Solarflare Communications Inc.
* Copyright 2019-2020 Xilinx Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include <net/ip6_checksum.h>
#include "net_driver.h"
#include "tx_common.h"
#include "nic_common.h"
#include "mcdi_functions.h"
#include "ef100_regs.h"
#include "io.h"
#include "ef100_tx.h"
#include "ef100_nic.h"
int ef100_tx_probe(struct efx_tx_queue *tx_queue)
{
/* Allocate an extra descriptor for the QMDA status completion entry */
return efx_nic_alloc_buffer(tx_queue->efx, &tx_queue->txd,
(tx_queue->ptr_mask + 2) *
sizeof(efx_oword_t),
GFP_KERNEL);
}
void ef100_tx_init(struct efx_tx_queue *tx_queue)
{
/* must be the inverse of lookup in efx_get_tx_channel */
tx_queue->core_txq =
netdev_get_tx_queue(tx_queue->efx->net_dev,
tx_queue->channel->channel -
tx_queue->efx->tx_channel_offset);
/* This value is purely documentational; as EF100 never passes through
* the switch statement in tx.c:__efx_enqueue_skb(), that switch does
* not handle case 3. EF100's TSOv3 descriptors are generated by
* ef100_make_tso_desc().
* Meanwhile, all efx_mcdi_tx_init() cares about is that it's not 2.
*/
tx_queue->tso_version = 3;
if (efx_mcdi_tx_init(tx_queue))
netdev_WARN(tx_queue->efx->net_dev,
"failed to initialise TXQ %d\n", tx_queue->queue);
}
static bool ef100_tx_can_tso(struct efx_tx_queue *tx_queue, struct sk_buff *skb)
{
struct efx_nic *efx = tx_queue->efx;
struct ef100_nic_data *nic_data;
struct efx_tx_buffer *buffer;
size_t header_len;
u32 mss;
nic_data = efx->nic_data;
if (!skb_is_gso_tcp(skb))
return false;
if (!(efx->net_dev->features & NETIF_F_TSO))
return false;
mss = skb_shinfo(skb)->gso_size;
if (unlikely(mss < 4)) {
WARN_ONCE(1, "MSS of %u is too small for TSO\n", mss);
return false;
}
header_len = efx_tx_tso_header_length(skb);
if (header_len > nic_data->tso_max_hdr_len)
return false;
if (skb_shinfo(skb)->gso_segs > nic_data->tso_max_payload_num_segs) {
/* net_dev->gso_max_segs should've caught this */
WARN_ON_ONCE(1);
return false;
}
if (skb->data_len / mss > nic_data->tso_max_frames)
return false;
/* net_dev->gso_max_size should've caught this */
if (WARN_ON_ONCE(skb->data_len > nic_data->tso_max_payload_len))
return false;
/* Reserve an empty buffer for the TSO V3 descriptor.
* Convey the length of the header since we already know it.
*/
buffer = efx_tx_queue_get_insert_buffer(tx_queue);
buffer->flags = EFX_TX_BUF_TSO_V3 | EFX_TX_BUF_CONT;
buffer->len = header_len;
buffer->unmap_len = 0;
buffer->skb = skb;
++tx_queue->insert_count;
return true;
}
static efx_oword_t *ef100_tx_desc(struct efx_tx_queue *tx_queue, unsigned int index)
{
if (likely(tx_queue->txd.addr))
return ((efx_oword_t *)tx_queue->txd.addr) + index;
else
return NULL;
}
static void ef100_notify_tx_desc(struct efx_tx_queue *tx_queue)
{
unsigned int write_ptr;
efx_dword_t reg;
tx_queue->xmit_pending = false;
if (unlikely(tx_queue->notify_count == tx_queue->write_count))
return;
write_ptr = tx_queue->write_count & tx_queue->ptr_mask;
/* The write pointer goes into the high word */
EFX_POPULATE_DWORD_1(reg, ERF_GZ_TX_RING_PIDX, write_ptr);
efx_writed_page(tx_queue->efx, ®,
ER_GZ_TX_RING_DOORBELL, tx_queue->queue);
tx_queue->notify_count = tx_queue->write_count;
}
static void ef100_tx_push_buffers(struct efx_tx_queue *tx_queue)
{
ef100_notify_tx_desc(tx_queue);
++tx_queue->pushes;
}
static void ef100_set_tx_csum_partial(const struct sk_buff *skb,
struct efx_tx_buffer *buffer, efx_oword_t *txd)
{
efx_oword_t csum;
int csum_start;
if (!skb || skb->ip_summed != CHECKSUM_PARTIAL)
return;
/* skb->csum_start has the offset from head, but we need the offset
* from data.
*/
csum_start = skb_checksum_start_offset(skb);
EFX_POPULATE_OWORD_3(csum,
ESF_GZ_TX_SEND_CSO_PARTIAL_EN, 1,
ESF_GZ_TX_SEND_CSO_PARTIAL_START_W,
csum_start >> 1,
ESF_GZ_TX_SEND_CSO_PARTIAL_CSUM_W,
skb->csum_offset >> 1);
EFX_OR_OWORD(*txd, *txd, csum);
}
static void ef100_set_tx_hw_vlan(const struct sk_buff *skb, efx_oword_t *txd)
{
u16 vlan_tci = skb_vlan_tag_get(skb);
efx_oword_t vlan;
EFX_POPULATE_OWORD_2(vlan,
ESF_GZ_TX_SEND_VLAN_INSERT_EN, 1,
ESF_GZ_TX_SEND_VLAN_INSERT_TCI, vlan_tci);
EFX_OR_OWORD(*txd, *txd, vlan);
}
static void ef100_make_send_desc(struct efx_nic *efx,
const struct sk_buff *skb,
struct efx_tx_buffer *buffer, efx_oword_t *txd,
unsigned int segment_count)
{
/* TX send descriptor */
EFX_POPULATE_OWORD_3(*txd,
ESF_GZ_TX_SEND_NUM_SEGS, segment_count,
ESF_GZ_TX_SEND_LEN, buffer->len,
ESF_GZ_TX_SEND_ADDR, buffer->dma_addr);
if (likely(efx->net_dev->features & NETIF_F_HW_CSUM))
ef100_set_tx_csum_partial(skb, buffer, txd);
if (efx->net_dev->features & NETIF_F_HW_VLAN_CTAG_TX &&
skb && skb_vlan_tag_present(skb))
ef100_set_tx_hw_vlan(skb, txd);
}
static void ef100_make_tso_desc(struct efx_nic *efx,
const struct sk_buff *skb,
struct efx_tx_buffer *buffer, efx_oword_t *txd,
unsigned int segment_count)
{
bool gso_partial = skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL;
unsigned int len, ip_offset, tcp_offset, payload_segs;
u32 mangleid = ESE_GZ_TX_DESC_IP4_ID_INC_MOD16;
unsigned int outer_ip_offset, outer_l4_offset;
u16 vlan_tci = skb_vlan_tag_get(skb);
u32 mss = skb_shinfo(skb)->gso_size;
bool encap = skb->encapsulation;
bool udp_encap = false;
u16 vlan_enable = 0;
struct tcphdr *tcp;
bool outer_csum;
u32 paylen;
if (skb_shinfo(skb)->gso_type & SKB_GSO_TCP_FIXEDID)
mangleid = ESE_GZ_TX_DESC_IP4_ID_NO_OP;
if (efx->net_dev->features & NETIF_F_HW_VLAN_CTAG_TX)
vlan_enable = skb_vlan_tag_present(skb);
len = skb->len - buffer->len;
/* We use 1 for the TSO descriptor and 1 for the header */
payload_segs = segment_count - 2;
if (encap) {
outer_ip_offset = skb_network_offset(skb);
outer_l4_offset = skb_transport_offset(skb);
ip_offset = skb_inner_network_offset(skb);
tcp_offset = skb_inner_transport_offset(skb);
if (skb_shinfo(skb)->gso_type &
(SKB_GSO_UDP_TUNNEL | SKB_GSO_UDP_TUNNEL_CSUM))
udp_encap = true;
} else {
ip_offset = skb_network_offset(skb);
tcp_offset = skb_transport_offset(skb);
outer_ip_offset = outer_l4_offset = 0;
}
outer_csum = skb_shinfo(skb)->gso_type & SKB_GSO_UDP_TUNNEL_CSUM;
/* subtract TCP payload length from inner checksum */
tcp = (void *)skb->data + tcp_offset;
paylen = skb->len - tcp_offset;
csum_replace_by_diff(&tcp->check, (__force __wsum)htonl(paylen));
EFX_POPULATE_OWORD_19(*txd,
ESF_GZ_TX_DESC_TYPE, ESE_GZ_TX_DESC_TYPE_TSO,
ESF_GZ_TX_TSO_MSS, mss,
ESF_GZ_TX_TSO_HDR_NUM_SEGS, 1,
ESF_GZ_TX_TSO_PAYLOAD_NUM_SEGS, payload_segs,
ESF_GZ_TX_TSO_HDR_LEN_W, buffer->len >> 1,
ESF_GZ_TX_TSO_PAYLOAD_LEN, len,
ESF_GZ_TX_TSO_CSO_OUTER_L4, outer_csum,
ESF_GZ_TX_TSO_CSO_INNER_L4, 1,
ESF_GZ_TX_TSO_INNER_L3_OFF_W, ip_offset >> 1,
ESF_GZ_TX_TSO_INNER_L4_OFF_W, tcp_offset >> 1,
ESF_GZ_TX_TSO_ED_INNER_IP4_ID, mangleid,
ESF_GZ_TX_TSO_ED_INNER_IP_LEN, 1,
ESF_GZ_TX_TSO_OUTER_L3_OFF_W, outer_ip_offset >> 1,
ESF_GZ_TX_TSO_OUTER_L4_OFF_W, outer_l4_offset >> 1,
ESF_GZ_TX_TSO_ED_OUTER_UDP_LEN, udp_encap && !gso_partial,
ESF_GZ_TX_TSO_ED_OUTER_IP_LEN, encap && !gso_partial,
ESF_GZ_TX_TSO_ED_OUTER_IP4_ID, encap ? mangleid :
ESE_GZ_TX_DESC_IP4_ID_NO_OP,
ESF_GZ_TX_TSO_VLAN_INSERT_EN, vlan_enable,
ESF_GZ_TX_TSO_VLAN_INSERT_TCI, vlan_tci
);
}
static void ef100_tx_make_descriptors(struct efx_tx_queue *tx_queue,
const struct sk_buff *skb,
unsigned int segment_count,
struct efx_rep *efv)
{
unsigned int old_write_count = tx_queue->write_count;
unsigned int new_write_count = old_write_count;
struct efx_tx_buffer *buffer;
unsigned int next_desc_type;
unsigned int write_ptr;
efx_oword_t *txd;
unsigned int nr_descs = tx_queue->insert_count - old_write_count;
if (unlikely(nr_descs == 0))
return;
if (segment_count)
next_desc_type = ESE_GZ_TX_DESC_TYPE_TSO;
else
next_desc_type = ESE_GZ_TX_DESC_TYPE_SEND;
if (unlikely(efv)) {
/* Create TX override descriptor */
write_ptr = new_write_count & tx_queue->ptr_mask;
txd = ef100_tx_desc(tx_queue, write_ptr);
++new_write_count;
tx_queue->packet_write_count = new_write_count;
EFX_POPULATE_OWORD_3(*txd,
ESF_GZ_TX_DESC_TYPE, ESE_GZ_TX_DESC_TYPE_PREFIX,
ESF_GZ_TX_PREFIX_EGRESS_MPORT, efv->mport,
ESF_GZ_TX_PREFIX_EGRESS_MPORT_EN, 1);
nr_descs--;
}
/* if it's a raw write (such as XDP) then always SEND single frames */
if (!skb)
nr_descs = 1;
do {
write_ptr = new_write_count & tx_queue->ptr_mask;
buffer = &tx_queue->buffer[write_ptr];
txd = ef100_tx_desc(tx_queue, write_ptr);
++new_write_count;
/* Create TX descriptor ring entry */
tx_queue->packet_write_count = new_write_count;
switch (next_desc_type) {
case ESE_GZ_TX_DESC_TYPE_SEND:
ef100_make_send_desc(tx_queue->efx, skb,
buffer, txd, nr_descs);
break;
case ESE_GZ_TX_DESC_TYPE_TSO:
/* TX TSO descriptor */
WARN_ON_ONCE(!(buffer->flags & EFX_TX_BUF_TSO_V3));
ef100_make_tso_desc(tx_queue->efx, skb,
buffer, txd, nr_descs);
break;
default:
/* TX segment descriptor */
EFX_POPULATE_OWORD_3(*txd,
ESF_GZ_TX_DESC_TYPE, ESE_GZ_TX_DESC_TYPE_SEG,
ESF_GZ_TX_SEG_LEN, buffer->len,
ESF_GZ_TX_SEG_ADDR, buffer->dma_addr);
}
/* if it's a raw write (such as XDP) then always SEND */
next_desc_type = skb ? ESE_GZ_TX_DESC_TYPE_SEG :
ESE_GZ_TX_DESC_TYPE_SEND;
/* mark as an EFV buffer if applicable */
if (unlikely(efv))
buffer->flags |= EFX_TX_BUF_EFV;
} while (new_write_count != tx_queue->insert_count);
wmb(); /* Ensure descriptors are written before they are fetched */
tx_queue->write_count = new_write_count;
/* The write_count above must be updated before reading
* channel->holdoff_doorbell to avoid a race with the
* completion path, so ensure these operations are not
* re-ordered. This also flushes the update of write_count
* back into the cache.
*/
smp_mb();
}
void ef100_tx_write(struct efx_tx_queue *tx_queue)
{
ef100_tx_make_descriptors(tx_queue, NULL, 0, NULL);
ef100_tx_push_buffers(tx_queue);
}
int ef100_ev_tx(struct efx_channel *channel, const efx_qword_t *p_event)
{
unsigned int tx_done =
EFX_QWORD_FIELD(*p_event, ESF_GZ_EV_TXCMPL_NUM_DESC);
unsigned int qlabel =
EFX_QWORD_FIELD(*p_event, ESF_GZ_EV_TXCMPL_Q_LABEL);
struct efx_tx_queue *tx_queue =
efx_channel_get_tx_queue(channel, qlabel);
unsigned int tx_index = (tx_queue->read_count + tx_done - 1) &
tx_queue->ptr_mask;
return efx_xmit_done(tx_queue, tx_index);
}
/* Add a socket buffer to a TX queue
*
* You must hold netif_tx_lock() to call this function.
*
* Returns 0 on success, error code otherwise. In case of an error this
* function will free the SKB.
*/
netdev_tx_t ef100_enqueue_skb(struct efx_tx_queue *tx_queue,
struct sk_buff *skb)
{
return __ef100_enqueue_skb(tx_queue, skb, NULL);
}
int __ef100_enqueue_skb(struct efx_tx_queue *tx_queue, struct sk_buff *skb,
struct efx_rep *efv)
{
unsigned int old_insert_count = tx_queue->insert_count;
struct efx_nic *efx = tx_queue->efx;
bool xmit_more = netdev_xmit_more();
unsigned int fill_level;
unsigned int segments;
int rc;
if (!tx_queue->buffer || !tx_queue->ptr_mask) {
netif_stop_queue(efx->net_dev);
dev_kfree_skb_any(skb);
return -ENODEV;
}
segments = skb_is_gso(skb) ? skb_shinfo(skb)->gso_segs : 0;
if (segments == 1)
segments = 0; /* Don't use TSO/GSO for a single segment. */
if (segments && !ef100_tx_can_tso(tx_queue, skb)) {
rc = efx_tx_tso_fallback(tx_queue, skb);
tx_queue->tso_fallbacks++;
if (rc)
goto err;
else
return 0;
}
if (unlikely(efv)) {
struct efx_tx_buffer *buffer = __efx_tx_queue_get_insert_buffer(tx_queue);
/* Drop representor packets if the queue is stopped.
* We currently don't assert backoff to representors so this is
* to make sure representor traffic can't starve the main
* net device.
* And, of course, if there are no TX descriptors left.
*/
if (netif_tx_queue_stopped(tx_queue->core_txq) ||
unlikely(efx_tx_buffer_in_use(buffer))) {
atomic64_inc(&efv->stats.tx_errors);
rc = -ENOSPC;
goto err;
}
/* Also drop representor traffic if it could cause us to
* stop the queue. If we assert backoff and we haven't
* received traffic on the main net device recently then the
* TX watchdog can go off erroneously.
*/
fill_level = efx_channel_tx_old_fill_level(tx_queue->channel);
fill_level += efx_tx_max_skb_descs(efx);
if (fill_level > efx->txq_stop_thresh) {
struct efx_tx_queue *txq2;
/* Refresh cached fill level and re-check */
efx_for_each_channel_tx_queue(txq2, tx_queue->channel)
txq2->old_read_count = READ_ONCE(txq2->read_count);
fill_level = efx_channel_tx_old_fill_level(tx_queue->channel);
fill_level += efx_tx_max_skb_descs(efx);
if (fill_level > efx->txq_stop_thresh) {
atomic64_inc(&efv->stats.tx_errors);
rc = -ENOSPC;
goto err;
}
}
buffer->flags = EFX_TX_BUF_OPTION | EFX_TX_BUF_EFV;
tx_queue->insert_count++;
}
/* Map for DMA and create descriptors */
rc = efx_tx_map_data(tx_queue, skb, segments);
if (rc)
goto err;
ef100_tx_make_descriptors(tx_queue, skb, segments, efv);
fill_level = efx_channel_tx_old_fill_level(tx_queue->channel);
if (fill_level > efx->txq_stop_thresh) {
struct efx_tx_queue *txq2;
/* Because of checks above, representor traffic should
* not be able to stop the queue.
*/
WARN_ON(efv);
netif_tx_stop_queue(tx_queue->core_txq);
/* Re-read after a memory barrier in case we've raced with
* the completion path. Otherwise there's a danger we'll never
* restart the queue if all completions have just happened.
*/
smp_mb();
efx_for_each_channel_tx_queue(txq2, tx_queue->channel)
txq2->old_read_count = READ_ONCE(txq2->read_count);
fill_level = efx_channel_tx_old_fill_level(tx_queue->channel);
if (fill_level < efx->txq_stop_thresh)
netif_tx_start_queue(tx_queue->core_txq);
}
tx_queue->xmit_pending = true;
/* If xmit_more then we don't need to push the doorbell, unless there
* are 256 descriptors already queued in which case we have to push to
* ensure we never push more than 256 at once.
*
* Always push for representor traffic, and don't account it to parent
* PF netdevice's BQL.
*/
if (unlikely(efv) ||
__netdev_tx_sent_queue(tx_queue->core_txq, skb->len, xmit_more) ||
tx_queue->write_count - tx_queue->notify_count > 255)
ef100_tx_push_buffers(tx_queue);
if (segments) {
tx_queue->tso_bursts++;
tx_queue->tso_packets += segments;
tx_queue->tx_packets += segments;
} else {
tx_queue->tx_packets++;
}
return 0;
err:
efx_enqueue_unwind(tx_queue, old_insert_count);
if (!IS_ERR_OR_NULL(skb))
dev_kfree_skb_any(skb);
/* If we're not expecting another transmit and we had something to push
* on this queue then we need to push here to get the previous packets
* out. We only enter this branch from before the xmit_more handling
* above, so xmit_pending still refers to the old state.
*/
if (tx_queue->xmit_pending && !xmit_more)
ef100_tx_push_buffers(tx_queue);
return rc;
}
|
linux-master
|
drivers/net/ethernet/sfc/ef100_tx.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2014-2015 Solarflare Communications Inc.
*/
#include <linux/module.h>
#include "net_driver.h"
#include "nic.h"
#include "sriov.h"
int efx_sriov_set_vf_mac(struct net_device *net_dev, int vf_i, u8 *mac)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
if (efx->type->sriov_set_vf_mac)
return efx->type->sriov_set_vf_mac(efx, vf_i, mac);
else
return -EOPNOTSUPP;
}
int efx_sriov_set_vf_vlan(struct net_device *net_dev, int vf_i, u16 vlan,
u8 qos, __be16 vlan_proto)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
if (efx->type->sriov_set_vf_vlan) {
if ((vlan & ~VLAN_VID_MASK) ||
(qos & ~(VLAN_PRIO_MASK >> VLAN_PRIO_SHIFT)))
return -EINVAL;
if (vlan_proto != htons(ETH_P_8021Q))
return -EPROTONOSUPPORT;
return efx->type->sriov_set_vf_vlan(efx, vf_i, vlan, qos);
} else {
return -EOPNOTSUPP;
}
}
int efx_sriov_set_vf_spoofchk(struct net_device *net_dev, int vf_i,
bool spoofchk)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
if (efx->type->sriov_set_vf_spoofchk)
return efx->type->sriov_set_vf_spoofchk(efx, vf_i, spoofchk);
else
return -EOPNOTSUPP;
}
int efx_sriov_get_vf_config(struct net_device *net_dev, int vf_i,
struct ifla_vf_info *ivi)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
if (efx->type->sriov_get_vf_config)
return efx->type->sriov_get_vf_config(efx, vf_i, ivi);
else
return -EOPNOTSUPP;
}
int efx_sriov_set_vf_link_state(struct net_device *net_dev, int vf_i,
int link_state)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
if (efx->type->sriov_set_vf_link_state)
return efx->type->sriov_set_vf_link_state(efx, vf_i,
link_state);
else
return -EOPNOTSUPP;
}
|
linux-master
|
drivers/net/ethernet/sfc/sriov.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2018 Solarflare Communications Inc.
* Copyright 2019-2022 Xilinx Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include "ef100_nic.h"
#include "efx_common.h"
#include "efx_channels.h"
#include "io.h"
#include "selftest.h"
#include "ef100_regs.h"
#include "mcdi.h"
#include "mcdi_pcol.h"
#include "mcdi_port_common.h"
#include "mcdi_functions.h"
#include "mcdi_filters.h"
#include "ef100_rx.h"
#include "ef100_tx.h"
#include "ef100_sriov.h"
#include "ef100_netdev.h"
#include "tc.h"
#include "mae.h"
#include "rx_common.h"
#define EF100_MAX_VIS 4096
#define EF100_NUM_MCDI_BUFFERS 1
#define MCDI_BUF_LEN (8 + MCDI_CTL_SDU_LEN_MAX)
#define EF100_RESET_PORT ((ETH_RESET_MAC | ETH_RESET_PHY) << ETH_RESET_SHARED_SHIFT)
/* MCDI
*/
static u8 *ef100_mcdi_buf(struct efx_nic *efx, u8 bufid, dma_addr_t *dma_addr)
{
struct ef100_nic_data *nic_data = efx->nic_data;
if (dma_addr)
*dma_addr = nic_data->mcdi_buf.dma_addr +
bufid * ALIGN(MCDI_BUF_LEN, 256);
return nic_data->mcdi_buf.addr + bufid * ALIGN(MCDI_BUF_LEN, 256);
}
static int ef100_get_warm_boot_count(struct efx_nic *efx)
{
efx_dword_t reg;
efx_readd(efx, ®, efx_reg(efx, ER_GZ_MC_SFT_STATUS));
if (EFX_DWORD_FIELD(reg, EFX_DWORD_0) == 0xffffffff) {
netif_err(efx, hw, efx->net_dev, "Hardware unavailable\n");
efx->state = STATE_DISABLED;
return -ENETDOWN;
} else {
return EFX_DWORD_FIELD(reg, EFX_WORD_1) == 0xb007 ?
EFX_DWORD_FIELD(reg, EFX_WORD_0) : -EIO;
}
}
static void ef100_mcdi_request(struct efx_nic *efx,
const efx_dword_t *hdr, size_t hdr_len,
const efx_dword_t *sdu, size_t sdu_len)
{
dma_addr_t dma_addr;
u8 *pdu = ef100_mcdi_buf(efx, 0, &dma_addr);
memcpy(pdu, hdr, hdr_len);
memcpy(pdu + hdr_len, sdu, sdu_len);
wmb();
/* The hardware provides 'low' and 'high' (doorbell) registers
* for passing the 64-bit address of an MCDI request to
* firmware. However the dwords are swapped by firmware. The
* least significant bits of the doorbell are then 0 for all
* MCDI requests due to alignment.
*/
_efx_writed(efx, cpu_to_le32((u64)dma_addr >> 32), efx_reg(efx, ER_GZ_MC_DB_LWRD));
_efx_writed(efx, cpu_to_le32((u32)dma_addr), efx_reg(efx, ER_GZ_MC_DB_HWRD));
}
static bool ef100_mcdi_poll_response(struct efx_nic *efx)
{
const efx_dword_t hdr =
*(const efx_dword_t *)(ef100_mcdi_buf(efx, 0, NULL));
rmb();
return EFX_DWORD_FIELD(hdr, MCDI_HEADER_RESPONSE);
}
static void ef100_mcdi_read_response(struct efx_nic *efx,
efx_dword_t *outbuf, size_t offset,
size_t outlen)
{
const u8 *pdu = ef100_mcdi_buf(efx, 0, NULL);
memcpy(outbuf, pdu + offset, outlen);
}
static int ef100_mcdi_poll_reboot(struct efx_nic *efx)
{
struct ef100_nic_data *nic_data = efx->nic_data;
int rc;
rc = ef100_get_warm_boot_count(efx);
if (rc < 0) {
/* The firmware is presumably in the process of
* rebooting. However, we are supposed to report each
* reboot just once, so we must only do that once we
* can read and store the updated warm boot count.
*/
return 0;
}
if (rc == nic_data->warm_boot_count)
return 0;
nic_data->warm_boot_count = rc;
return -EIO;
}
static void ef100_mcdi_reboot_detected(struct efx_nic *efx)
{
}
/* MCDI calls
*/
int ef100_get_mac_address(struct efx_nic *efx, u8 *mac_address,
int client_handle, bool empty_ok)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_CLIENT_MAC_ADDRESSES_OUT_LEN(1));
MCDI_DECLARE_BUF(inbuf, MC_CMD_GET_CLIENT_MAC_ADDRESSES_IN_LEN);
size_t outlen;
int rc;
BUILD_BUG_ON(MC_CMD_GET_MAC_ADDRESSES_IN_LEN != 0);
MCDI_SET_DWORD(inbuf, GET_CLIENT_MAC_ADDRESSES_IN_CLIENT_HANDLE,
client_handle);
rc = efx_mcdi_rpc(efx, MC_CMD_GET_CLIENT_MAC_ADDRESSES, inbuf,
sizeof(inbuf), outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen >= MC_CMD_GET_CLIENT_MAC_ADDRESSES_OUT_LEN(1)) {
ether_addr_copy(mac_address,
MCDI_PTR(outbuf, GET_CLIENT_MAC_ADDRESSES_OUT_MAC_ADDRS));
} else if (empty_ok) {
pci_warn(efx->pci_dev,
"No MAC address provisioned for client ID %#x.\n",
client_handle);
eth_zero_addr(mac_address);
} else {
return -ENOENT;
}
return 0;
}
int efx_ef100_init_datapath_caps(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_CAPABILITIES_V7_OUT_LEN);
struct ef100_nic_data *nic_data = efx->nic_data;
u8 vi_window_mode;
size_t outlen;
int rc;
BUILD_BUG_ON(MC_CMD_GET_CAPABILITIES_IN_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_GET_CAPABILITIES, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < MC_CMD_GET_CAPABILITIES_V4_OUT_LEN) {
netif_err(efx, drv, efx->net_dev,
"unable to read datapath firmware capabilities\n");
return -EIO;
}
nic_data->datapath_caps = MCDI_DWORD(outbuf,
GET_CAPABILITIES_OUT_FLAGS1);
nic_data->datapath_caps2 = MCDI_DWORD(outbuf,
GET_CAPABILITIES_V2_OUT_FLAGS2);
if (outlen < MC_CMD_GET_CAPABILITIES_V7_OUT_LEN)
nic_data->datapath_caps3 = 0;
else
nic_data->datapath_caps3 = MCDI_DWORD(outbuf,
GET_CAPABILITIES_V7_OUT_FLAGS3);
vi_window_mode = MCDI_BYTE(outbuf,
GET_CAPABILITIES_V3_OUT_VI_WINDOW_MODE);
rc = efx_mcdi_window_mode_to_stride(efx, vi_window_mode);
if (rc)
return rc;
if (efx_ef100_has_cap(nic_data->datapath_caps2, TX_TSO_V3)) {
struct net_device *net_dev = efx->net_dev;
netdev_features_t tso = NETIF_F_TSO | NETIF_F_TSO6 | NETIF_F_GSO_PARTIAL |
NETIF_F_GSO_UDP_TUNNEL | NETIF_F_GSO_UDP_TUNNEL_CSUM |
NETIF_F_GSO_GRE | NETIF_F_GSO_GRE_CSUM;
net_dev->features |= tso;
net_dev->hw_features |= tso;
net_dev->hw_enc_features |= tso;
/* EF100 HW can only offload outer checksums if they are UDP,
* so for GRE_CSUM we have to use GSO_PARTIAL.
*/
net_dev->gso_partial_features |= NETIF_F_GSO_GRE_CSUM;
}
efx->num_mac_stats = MCDI_WORD(outbuf,
GET_CAPABILITIES_V4_OUT_MAC_STATS_NUM_STATS);
netif_dbg(efx, probe, efx->net_dev,
"firmware reports num_mac_stats = %u\n",
efx->num_mac_stats);
return 0;
}
/* Event handling
*/
static int ef100_ev_probe(struct efx_channel *channel)
{
/* Allocate an extra descriptor for the QMDA status completion entry */
return efx_nic_alloc_buffer(channel->efx, &channel->eventq,
(channel->eventq_mask + 2) *
sizeof(efx_qword_t),
GFP_KERNEL);
}
static int ef100_ev_init(struct efx_channel *channel)
{
struct ef100_nic_data *nic_data = channel->efx->nic_data;
/* initial phase is 0 */
clear_bit(channel->channel, nic_data->evq_phases);
return efx_mcdi_ev_init(channel, false, false);
}
static void ef100_ev_read_ack(struct efx_channel *channel)
{
efx_dword_t evq_prime;
EFX_POPULATE_DWORD_2(evq_prime,
ERF_GZ_EVQ_ID, channel->channel,
ERF_GZ_IDX, channel->eventq_read_ptr &
channel->eventq_mask);
efx_writed(channel->efx, &evq_prime,
efx_reg(channel->efx, ER_GZ_EVQ_INT_PRIME));
}
#define EFX_NAPI_MAX_TX 512
static int ef100_ev_process(struct efx_channel *channel, int quota)
{
struct efx_nic *efx = channel->efx;
struct ef100_nic_data *nic_data;
bool evq_phase, old_evq_phase;
unsigned int read_ptr;
efx_qword_t *p_event;
int spent_tx = 0;
int spent = 0;
bool ev_phase;
int ev_type;
if (unlikely(!channel->enabled))
return 0;
nic_data = efx->nic_data;
evq_phase = test_bit(channel->channel, nic_data->evq_phases);
old_evq_phase = evq_phase;
read_ptr = channel->eventq_read_ptr;
BUILD_BUG_ON(ESF_GZ_EV_RXPKTS_PHASE_LBN != ESF_GZ_EV_TXCMPL_PHASE_LBN);
while (spent < quota) {
p_event = efx_event(channel, read_ptr);
ev_phase = !!EFX_QWORD_FIELD(*p_event, ESF_GZ_EV_RXPKTS_PHASE);
if (ev_phase != evq_phase)
break;
netif_vdbg(efx, drv, efx->net_dev,
"processing event on %d " EFX_QWORD_FMT "\n",
channel->channel, EFX_QWORD_VAL(*p_event));
ev_type = EFX_QWORD_FIELD(*p_event, ESF_GZ_E_TYPE);
switch (ev_type) {
case ESE_GZ_EF100_EV_RX_PKTS:
efx_ef100_ev_rx(channel, p_event);
++spent;
break;
case ESE_GZ_EF100_EV_MCDI:
efx_mcdi_process_event(channel, p_event);
break;
case ESE_GZ_EF100_EV_TX_COMPLETION:
spent_tx += ef100_ev_tx(channel, p_event);
if (spent_tx >= EFX_NAPI_MAX_TX)
spent = quota;
break;
case ESE_GZ_EF100_EV_DRIVER:
netif_info(efx, drv, efx->net_dev,
"Driver initiated event " EFX_QWORD_FMT "\n",
EFX_QWORD_VAL(*p_event));
break;
default:
netif_info(efx, drv, efx->net_dev,
"Unhandled event " EFX_QWORD_FMT "\n",
EFX_QWORD_VAL(*p_event));
}
++read_ptr;
if ((read_ptr & channel->eventq_mask) == 0)
evq_phase = !evq_phase;
}
channel->eventq_read_ptr = read_ptr;
if (evq_phase != old_evq_phase)
change_bit(channel->channel, nic_data->evq_phases);
return spent;
}
static irqreturn_t ef100_msi_interrupt(int irq, void *dev_id)
{
struct efx_msi_context *context = dev_id;
struct efx_nic *efx = context->efx;
netif_vdbg(efx, intr, efx->net_dev,
"IRQ %d on CPU %d\n", irq, raw_smp_processor_id());
if (likely(READ_ONCE(efx->irq_soft_enabled))) {
/* Note test interrupts */
if (context->index == efx->irq_level)
efx->last_irq_cpu = raw_smp_processor_id();
/* Schedule processing of the channel */
efx_schedule_channel_irq(efx->channel[context->index]);
}
return IRQ_HANDLED;
}
int ef100_phy_probe(struct efx_nic *efx)
{
struct efx_mcdi_phy_data *phy_data;
int rc;
/* Probe for the PHY */
efx->phy_data = kzalloc(sizeof(struct efx_mcdi_phy_data), GFP_KERNEL);
if (!efx->phy_data)
return -ENOMEM;
rc = efx_mcdi_get_phy_cfg(efx, efx->phy_data);
if (rc)
return rc;
/* Populate driver and ethtool settings */
phy_data = efx->phy_data;
mcdi_to_ethtool_linkset(phy_data->media, phy_data->supported_cap,
efx->link_advertising);
efx->fec_config = mcdi_fec_caps_to_ethtool(phy_data->supported_cap,
false);
/* Default to Autonegotiated flow control if the PHY supports it */
efx->wanted_fc = EFX_FC_RX | EFX_FC_TX;
if (phy_data->supported_cap & (1 << MC_CMD_PHY_CAP_AN_LBN))
efx->wanted_fc |= EFX_FC_AUTO;
efx_link_set_wanted_fc(efx, efx->wanted_fc);
/* Push settings to the PHY. Failure is not fatal, the user can try to
* fix it using ethtool.
*/
rc = efx_mcdi_port_reconfigure(efx);
if (rc && rc != -EPERM)
netif_warn(efx, drv, efx->net_dev,
"could not initialise PHY settings\n");
return 0;
}
int ef100_filter_table_probe(struct efx_nic *efx)
{
return efx_mcdi_filter_table_probe(efx, true);
}
static int ef100_filter_table_up(struct efx_nic *efx)
{
int rc;
down_write(&efx->filter_sem);
rc = efx_mcdi_filter_add_vlan(efx, EFX_FILTER_VID_UNSPEC);
if (rc)
goto fail_unspec;
rc = efx_mcdi_filter_add_vlan(efx, 0);
if (rc)
goto fail_vlan0;
/* Drop the lock: we've finished altering table existence, and
* filter insertion will need to take the lock for read.
*/
up_write(&efx->filter_sem);
if (IS_ENABLED(CONFIG_SFC_SRIOV))
rc = efx_tc_insert_rep_filters(efx);
/* Rep filter failure is nonfatal */
if (rc)
netif_warn(efx, drv, efx->net_dev,
"Failed to insert representor filters, rc %d\n",
rc);
return 0;
fail_vlan0:
efx_mcdi_filter_del_vlan(efx, EFX_FILTER_VID_UNSPEC);
fail_unspec:
efx_mcdi_filter_table_down(efx);
up_write(&efx->filter_sem);
return rc;
}
static void ef100_filter_table_down(struct efx_nic *efx)
{
if (IS_ENABLED(CONFIG_SFC_SRIOV))
efx_tc_remove_rep_filters(efx);
down_write(&efx->filter_sem);
efx_mcdi_filter_del_vlan(efx, 0);
efx_mcdi_filter_del_vlan(efx, EFX_FILTER_VID_UNSPEC);
efx_mcdi_filter_table_down(efx);
up_write(&efx->filter_sem);
}
/* Other
*/
static int ef100_reconfigure_mac(struct efx_nic *efx, bool mtu_only)
{
WARN_ON(!mutex_is_locked(&efx->mac_lock));
efx_mcdi_filter_sync_rx_mode(efx);
if (mtu_only && efx_has_cap(efx, SET_MAC_ENHANCED))
return efx_mcdi_set_mtu(efx);
return efx_mcdi_set_mac(efx);
}
static enum reset_type ef100_map_reset_reason(enum reset_type reason)
{
if (reason == RESET_TYPE_TX_WATCHDOG)
return reason;
return RESET_TYPE_DISABLE;
}
static int ef100_map_reset_flags(u32 *flags)
{
/* Only perform a RESET_TYPE_ALL because we don't support MC_REBOOTs */
if ((*flags & EF100_RESET_PORT)) {
*flags &= ~EF100_RESET_PORT;
return RESET_TYPE_ALL;
}
if (*flags & ETH_RESET_MGMT) {
*flags &= ~ETH_RESET_MGMT;
return RESET_TYPE_DISABLE;
}
return -EINVAL;
}
static int ef100_reset(struct efx_nic *efx, enum reset_type reset_type)
{
int rc;
dev_close(efx->net_dev);
if (reset_type == RESET_TYPE_TX_WATCHDOG) {
netif_device_attach(efx->net_dev);
__clear_bit(reset_type, &efx->reset_pending);
rc = dev_open(efx->net_dev, NULL);
} else if (reset_type == RESET_TYPE_ALL) {
rc = efx_mcdi_reset(efx, reset_type);
if (rc)
return rc;
netif_device_attach(efx->net_dev);
rc = dev_open(efx->net_dev, NULL);
} else {
rc = 1; /* Leave the device closed */
}
return rc;
}
static void ef100_common_stat_mask(unsigned long *mask)
{
__set_bit(EF100_STAT_port_rx_packets, mask);
__set_bit(EF100_STAT_port_tx_packets, mask);
__set_bit(EF100_STAT_port_rx_bytes, mask);
__set_bit(EF100_STAT_port_tx_bytes, mask);
__set_bit(EF100_STAT_port_rx_multicast, mask);
__set_bit(EF100_STAT_port_rx_bad, mask);
__set_bit(EF100_STAT_port_rx_align_error, mask);
__set_bit(EF100_STAT_port_rx_overflow, mask);
}
static void ef100_ethtool_stat_mask(unsigned long *mask)
{
__set_bit(EF100_STAT_port_tx_pause, mask);
__set_bit(EF100_STAT_port_tx_unicast, mask);
__set_bit(EF100_STAT_port_tx_multicast, mask);
__set_bit(EF100_STAT_port_tx_broadcast, mask);
__set_bit(EF100_STAT_port_tx_lt64, mask);
__set_bit(EF100_STAT_port_tx_64, mask);
__set_bit(EF100_STAT_port_tx_65_to_127, mask);
__set_bit(EF100_STAT_port_tx_128_to_255, mask);
__set_bit(EF100_STAT_port_tx_256_to_511, mask);
__set_bit(EF100_STAT_port_tx_512_to_1023, mask);
__set_bit(EF100_STAT_port_tx_1024_to_15xx, mask);
__set_bit(EF100_STAT_port_tx_15xx_to_jumbo, mask);
__set_bit(EF100_STAT_port_rx_good, mask);
__set_bit(EF100_STAT_port_rx_pause, mask);
__set_bit(EF100_STAT_port_rx_unicast, mask);
__set_bit(EF100_STAT_port_rx_broadcast, mask);
__set_bit(EF100_STAT_port_rx_lt64, mask);
__set_bit(EF100_STAT_port_rx_64, mask);
__set_bit(EF100_STAT_port_rx_65_to_127, mask);
__set_bit(EF100_STAT_port_rx_128_to_255, mask);
__set_bit(EF100_STAT_port_rx_256_to_511, mask);
__set_bit(EF100_STAT_port_rx_512_to_1023, mask);
__set_bit(EF100_STAT_port_rx_1024_to_15xx, mask);
__set_bit(EF100_STAT_port_rx_15xx_to_jumbo, mask);
__set_bit(EF100_STAT_port_rx_gtjumbo, mask);
__set_bit(EF100_STAT_port_rx_bad_gtjumbo, mask);
__set_bit(EF100_STAT_port_rx_length_error, mask);
__set_bit(EF100_STAT_port_rx_nodesc_drops, mask);
__set_bit(GENERIC_STAT_rx_nodesc_trunc, mask);
__set_bit(GENERIC_STAT_rx_noskb_drops, mask);
}
#define EF100_DMA_STAT(ext_name, mcdi_name) \
[EF100_STAT_ ## ext_name] = \
{ #ext_name, 64, 8 * MC_CMD_MAC_ ## mcdi_name }
static const struct efx_hw_stat_desc ef100_stat_desc[EF100_STAT_COUNT] = {
EF100_DMA_STAT(port_tx_bytes, TX_BYTES),
EF100_DMA_STAT(port_tx_packets, TX_PKTS),
EF100_DMA_STAT(port_tx_pause, TX_PAUSE_PKTS),
EF100_DMA_STAT(port_tx_unicast, TX_UNICAST_PKTS),
EF100_DMA_STAT(port_tx_multicast, TX_MULTICAST_PKTS),
EF100_DMA_STAT(port_tx_broadcast, TX_BROADCAST_PKTS),
EF100_DMA_STAT(port_tx_lt64, TX_LT64_PKTS),
EF100_DMA_STAT(port_tx_64, TX_64_PKTS),
EF100_DMA_STAT(port_tx_65_to_127, TX_65_TO_127_PKTS),
EF100_DMA_STAT(port_tx_128_to_255, TX_128_TO_255_PKTS),
EF100_DMA_STAT(port_tx_256_to_511, TX_256_TO_511_PKTS),
EF100_DMA_STAT(port_tx_512_to_1023, TX_512_TO_1023_PKTS),
EF100_DMA_STAT(port_tx_1024_to_15xx, TX_1024_TO_15XX_PKTS),
EF100_DMA_STAT(port_tx_15xx_to_jumbo, TX_15XX_TO_JUMBO_PKTS),
EF100_DMA_STAT(port_rx_bytes, RX_BYTES),
EF100_DMA_STAT(port_rx_packets, RX_PKTS),
EF100_DMA_STAT(port_rx_good, RX_GOOD_PKTS),
EF100_DMA_STAT(port_rx_bad, RX_BAD_FCS_PKTS),
EF100_DMA_STAT(port_rx_pause, RX_PAUSE_PKTS),
EF100_DMA_STAT(port_rx_unicast, RX_UNICAST_PKTS),
EF100_DMA_STAT(port_rx_multicast, RX_MULTICAST_PKTS),
EF100_DMA_STAT(port_rx_broadcast, RX_BROADCAST_PKTS),
EF100_DMA_STAT(port_rx_lt64, RX_UNDERSIZE_PKTS),
EF100_DMA_STAT(port_rx_64, RX_64_PKTS),
EF100_DMA_STAT(port_rx_65_to_127, RX_65_TO_127_PKTS),
EF100_DMA_STAT(port_rx_128_to_255, RX_128_TO_255_PKTS),
EF100_DMA_STAT(port_rx_256_to_511, RX_256_TO_511_PKTS),
EF100_DMA_STAT(port_rx_512_to_1023, RX_512_TO_1023_PKTS),
EF100_DMA_STAT(port_rx_1024_to_15xx, RX_1024_TO_15XX_PKTS),
EF100_DMA_STAT(port_rx_15xx_to_jumbo, RX_15XX_TO_JUMBO_PKTS),
EF100_DMA_STAT(port_rx_gtjumbo, RX_GTJUMBO_PKTS),
EF100_DMA_STAT(port_rx_bad_gtjumbo, RX_JABBER_PKTS),
EF100_DMA_STAT(port_rx_align_error, RX_ALIGN_ERROR_PKTS),
EF100_DMA_STAT(port_rx_length_error, RX_LENGTH_ERROR_PKTS),
EF100_DMA_STAT(port_rx_overflow, RX_OVERFLOW_PKTS),
EF100_DMA_STAT(port_rx_nodesc_drops, RX_NODESC_DROPS),
EFX_GENERIC_SW_STAT(rx_nodesc_trunc),
EFX_GENERIC_SW_STAT(rx_noskb_drops),
};
static size_t ef100_describe_stats(struct efx_nic *efx, u8 *names)
{
DECLARE_BITMAP(mask, EF100_STAT_COUNT) = {};
ef100_ethtool_stat_mask(mask);
return efx_nic_describe_stats(ef100_stat_desc, EF100_STAT_COUNT,
mask, names);
}
static size_t ef100_update_stats_common(struct efx_nic *efx, u64 *full_stats,
struct rtnl_link_stats64 *core_stats)
{
struct ef100_nic_data *nic_data = efx->nic_data;
DECLARE_BITMAP(mask, EF100_STAT_COUNT) = {};
size_t stats_count = 0, index;
u64 *stats = nic_data->stats;
ef100_ethtool_stat_mask(mask);
if (full_stats) {
for_each_set_bit(index, mask, EF100_STAT_COUNT) {
if (ef100_stat_desc[index].name) {
*full_stats++ = stats[index];
++stats_count;
}
}
}
if (!core_stats)
return stats_count;
core_stats->rx_packets = stats[EF100_STAT_port_rx_packets];
core_stats->tx_packets = stats[EF100_STAT_port_tx_packets];
core_stats->rx_bytes = stats[EF100_STAT_port_rx_bytes];
core_stats->tx_bytes = stats[EF100_STAT_port_tx_bytes];
core_stats->rx_dropped = stats[EF100_STAT_port_rx_nodesc_drops] +
stats[GENERIC_STAT_rx_nodesc_trunc] +
stats[GENERIC_STAT_rx_noskb_drops];
core_stats->multicast = stats[EF100_STAT_port_rx_multicast];
core_stats->rx_length_errors =
stats[EF100_STAT_port_rx_gtjumbo] +
stats[EF100_STAT_port_rx_length_error];
core_stats->rx_crc_errors = stats[EF100_STAT_port_rx_bad];
core_stats->rx_frame_errors =
stats[EF100_STAT_port_rx_align_error];
core_stats->rx_fifo_errors = stats[EF100_STAT_port_rx_overflow];
core_stats->rx_errors = (core_stats->rx_length_errors +
core_stats->rx_crc_errors +
core_stats->rx_frame_errors);
return stats_count;
}
static size_t ef100_update_stats(struct efx_nic *efx,
u64 *full_stats,
struct rtnl_link_stats64 *core_stats)
{
__le64 *mc_stats = kmalloc(array_size(efx->num_mac_stats, sizeof(__le64)), GFP_ATOMIC);
struct ef100_nic_data *nic_data = efx->nic_data;
DECLARE_BITMAP(mask, EF100_STAT_COUNT) = {};
u64 *stats = nic_data->stats;
ef100_common_stat_mask(mask);
ef100_ethtool_stat_mask(mask);
if (!mc_stats)
return 0;
efx_nic_copy_stats(efx, mc_stats);
efx_nic_update_stats(ef100_stat_desc, EF100_STAT_COUNT, mask,
stats, mc_stats, false);
kfree(mc_stats);
return ef100_update_stats_common(efx, full_stats, core_stats);
}
static int efx_ef100_get_phys_port_id(struct efx_nic *efx,
struct netdev_phys_item_id *ppid)
{
struct ef100_nic_data *nic_data = efx->nic_data;
if (!is_valid_ether_addr(nic_data->port_id))
return -EOPNOTSUPP;
ppid->id_len = ETH_ALEN;
memcpy(ppid->id, nic_data->port_id, ppid->id_len);
return 0;
}
static int efx_ef100_irq_test_generate(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_TRIGGER_INTERRUPT_IN_LEN);
BUILD_BUG_ON(MC_CMD_TRIGGER_INTERRUPT_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, TRIGGER_INTERRUPT_IN_INTR_LEVEL, efx->irq_level);
return efx_mcdi_rpc_quiet(efx, MC_CMD_TRIGGER_INTERRUPT,
inbuf, sizeof(inbuf), NULL, 0, NULL);
}
#define EFX_EF100_TEST 1
static void efx_ef100_ev_test_generate(struct efx_channel *channel)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_DRIVER_EVENT_IN_LEN);
struct efx_nic *efx = channel->efx;
efx_qword_t event;
int rc;
EFX_POPULATE_QWORD_2(event,
ESF_GZ_E_TYPE, ESE_GZ_EF100_EV_DRIVER,
ESF_GZ_DRIVER_DATA, EFX_EF100_TEST);
MCDI_SET_DWORD(inbuf, DRIVER_EVENT_IN_EVQ, channel->channel);
/* MCDI_SET_QWORD is not appropriate here since EFX_POPULATE_* has
* already swapped the data to little-endian order.
*/
memcpy(MCDI_PTR(inbuf, DRIVER_EVENT_IN_DATA), &event.u64[0],
sizeof(efx_qword_t));
rc = efx_mcdi_rpc(efx, MC_CMD_DRIVER_EVENT, inbuf, sizeof(inbuf),
NULL, 0, NULL);
if (rc && (rc != -ENETDOWN))
goto fail;
return;
fail:
WARN_ON(true);
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
}
static unsigned int ef100_check_caps(const struct efx_nic *efx,
u8 flag, u32 offset)
{
const struct ef100_nic_data *nic_data = efx->nic_data;
switch (offset) {
case MC_CMD_GET_CAPABILITIES_V8_OUT_FLAGS1_OFST:
return nic_data->datapath_caps & BIT_ULL(flag);
case MC_CMD_GET_CAPABILITIES_V8_OUT_FLAGS2_OFST:
return nic_data->datapath_caps2 & BIT_ULL(flag);
case MC_CMD_GET_CAPABILITIES_V8_OUT_FLAGS3_OFST:
return nic_data->datapath_caps3 & BIT_ULL(flag);
default:
return 0;
}
}
static unsigned int efx_ef100_recycle_ring_size(const struct efx_nic *efx)
{
/* Maximum link speed for Riverhead is 100G */
return 10 * EFX_RECYCLE_RING_SIZE_10G;
}
static int efx_ef100_get_base_mport(struct efx_nic *efx)
{
struct ef100_nic_data *nic_data = efx->nic_data;
u32 selector, id;
int rc;
/* Construct mport selector for "physical network port" */
efx_mae_mport_wire(efx, &selector);
/* Look up actual mport ID */
rc = efx_mae_fw_lookup_mport(efx, selector, &id);
if (rc)
return rc;
/* The ID should always fit in 16 bits, because that's how wide the
* corresponding fields in the RX prefix & TX override descriptor are
*/
if (id >> 16)
netif_warn(efx, probe, efx->net_dev, "Bad base m-port id %#x\n",
id);
nic_data->base_mport = id;
nic_data->have_mport = true;
/* Construct mport selector for "calling PF" */
efx_mae_mport_uplink(efx, &selector);
/* Look up actual mport ID */
rc = efx_mae_fw_lookup_mport(efx, selector, &id);
if (rc)
return rc;
if (id >> 16)
netif_warn(efx, probe, efx->net_dev, "Bad own m-port id %#x\n",
id);
nic_data->own_mport = id;
nic_data->have_own_mport = true;
return 0;
}
static int compare_versions(const char *a, const char *b)
{
int a_major, a_minor, a_point, a_patch;
int b_major, b_minor, b_point, b_patch;
int a_matched, b_matched;
a_matched = sscanf(a, "%d.%d.%d.%d", &a_major, &a_minor, &a_point, &a_patch);
b_matched = sscanf(b, "%d.%d.%d.%d", &b_major, &b_minor, &b_point, &b_patch);
if (a_matched == 4 && b_matched != 4)
return +1;
if (a_matched != 4 && b_matched == 4)
return -1;
if (a_matched != 4 && b_matched != 4)
return 0;
if (a_major != b_major)
return a_major - b_major;
if (a_minor != b_minor)
return a_minor - b_minor;
if (a_point != b_point)
return a_point - b_point;
return a_patch - b_patch;
}
enum ef100_tlv_state_machine {
EF100_TLV_TYPE,
EF100_TLV_TYPE_CONT,
EF100_TLV_LENGTH,
EF100_TLV_VALUE
};
struct ef100_tlv_state {
enum ef100_tlv_state_machine state;
u64 value;
u32 value_offset;
u16 type;
u8 len;
};
static int ef100_tlv_feed(struct ef100_tlv_state *state, u8 byte)
{
switch (state->state) {
case EF100_TLV_TYPE:
state->type = byte & 0x7f;
state->state = (byte & 0x80) ? EF100_TLV_TYPE_CONT
: EF100_TLV_LENGTH;
/* Clear ready to read in a new entry */
state->value = 0;
state->value_offset = 0;
return 0;
case EF100_TLV_TYPE_CONT:
state->type |= byte << 7;
state->state = EF100_TLV_LENGTH;
return 0;
case EF100_TLV_LENGTH:
state->len = byte;
/* We only handle TLVs that fit in a u64 */
if (state->len > sizeof(state->value))
return -EOPNOTSUPP;
/* len may be zero, implying a value of zero */
state->state = state->len ? EF100_TLV_VALUE : EF100_TLV_TYPE;
return 0;
case EF100_TLV_VALUE:
state->value |= ((u64)byte) << (state->value_offset * 8);
state->value_offset++;
if (state->value_offset >= state->len)
state->state = EF100_TLV_TYPE;
return 0;
default: /* state machine error, can't happen */
WARN_ON_ONCE(1);
return -EIO;
}
}
static int ef100_process_design_param(struct efx_nic *efx,
const struct ef100_tlv_state *reader)
{
struct ef100_nic_data *nic_data = efx->nic_data;
switch (reader->type) {
case ESE_EF100_DP_GZ_PAD: /* padding, skip it */
return 0;
case ESE_EF100_DP_GZ_PARTIAL_TSTAMP_SUB_NANO_BITS:
/* Driver doesn't support timestamping yet, so we don't care */
return 0;
case ESE_EF100_DP_GZ_EVQ_UNSOL_CREDIT_SEQ_BITS:
/* Driver doesn't support unsolicited-event credits yet, so
* we don't care
*/
return 0;
case ESE_EF100_DP_GZ_NMMU_GROUP_SIZE:
/* Driver doesn't manage the NMMU (so we don't care) */
return 0;
case ESE_EF100_DP_GZ_RX_L4_CSUM_PROTOCOLS:
/* Driver uses CHECKSUM_COMPLETE, so we don't care about
* protocol checksum validation
*/
return 0;
case ESE_EF100_DP_GZ_TSO_MAX_HDR_LEN:
nic_data->tso_max_hdr_len = min_t(u64, reader->value, 0xffff);
return 0;
case ESE_EF100_DP_GZ_TSO_MAX_HDR_NUM_SEGS:
/* We always put HDR_NUM_SEGS=1 in our TSO descriptors */
if (!reader->value) {
netif_err(efx, probe, efx->net_dev,
"TSO_MAX_HDR_NUM_SEGS < 1\n");
return -EOPNOTSUPP;
}
return 0;
case ESE_EF100_DP_GZ_RXQ_SIZE_GRANULARITY:
case ESE_EF100_DP_GZ_TXQ_SIZE_GRANULARITY:
/* Our TXQ and RXQ sizes are always power-of-two and thus divisible by
* EFX_MIN_DMAQ_SIZE, so we just need to check that
* EFX_MIN_DMAQ_SIZE is divisible by GRANULARITY.
* This is very unlikely to fail.
*/
if (!reader->value || reader->value > EFX_MIN_DMAQ_SIZE ||
EFX_MIN_DMAQ_SIZE % (u32)reader->value) {
netif_err(efx, probe, efx->net_dev,
"%s size granularity is %llu, can't guarantee safety\n",
reader->type == ESE_EF100_DP_GZ_RXQ_SIZE_GRANULARITY ? "RXQ" : "TXQ",
reader->value);
return -EOPNOTSUPP;
}
return 0;
case ESE_EF100_DP_GZ_TSO_MAX_PAYLOAD_LEN:
nic_data->tso_max_payload_len = min_t(u64, reader->value,
GSO_LEGACY_MAX_SIZE);
netif_set_tso_max_size(efx->net_dev,
nic_data->tso_max_payload_len);
return 0;
case ESE_EF100_DP_GZ_TSO_MAX_PAYLOAD_NUM_SEGS:
nic_data->tso_max_payload_num_segs = min_t(u64, reader->value, 0xffff);
netif_set_tso_max_segs(efx->net_dev,
nic_data->tso_max_payload_num_segs);
return 0;
case ESE_EF100_DP_GZ_TSO_MAX_NUM_FRAMES:
nic_data->tso_max_frames = min_t(u64, reader->value, 0xffff);
return 0;
case ESE_EF100_DP_GZ_COMPAT:
if (reader->value) {
netif_err(efx, probe, efx->net_dev,
"DP_COMPAT has unknown bits %#llx, driver not compatible with this hw\n",
reader->value);
return -EOPNOTSUPP;
}
return 0;
case ESE_EF100_DP_GZ_MEM2MEM_MAX_LEN:
/* Driver doesn't use mem2mem transfers */
return 0;
case ESE_EF100_DP_GZ_EVQ_TIMER_TICK_NANOS:
/* Driver doesn't currently use EVQ_TIMER */
return 0;
case ESE_EF100_DP_GZ_NMMU_PAGE_SIZES:
/* Driver doesn't manage the NMMU (so we don't care) */
return 0;
case ESE_EF100_DP_GZ_VI_STRIDES:
/* We never try to set the VI stride, and we don't rely on
* being able to find VIs past VI 0 until after we've learned
* the current stride from MC_CMD_GET_CAPABILITIES.
* So the value of this shouldn't matter.
*/
if (reader->value != ESE_EF100_DP_GZ_VI_STRIDES_DEFAULT)
netif_dbg(efx, probe, efx->net_dev,
"NIC has other than default VI_STRIDES (mask "
"%#llx), early probing might use wrong one\n",
reader->value);
return 0;
case ESE_EF100_DP_GZ_RX_MAX_RUNT:
/* Driver doesn't look at L2_STATUS:LEN_ERR bit, so we don't
* care whether it indicates runt or overlength for any given
* packet, so we don't care about this parameter.
*/
return 0;
default:
/* Host interface says "Drivers should ignore design parameters
* that they do not recognise."
*/
netif_dbg(efx, probe, efx->net_dev,
"Ignoring unrecognised design parameter %u\n",
reader->type);
return 0;
}
}
static int ef100_check_design_params(struct efx_nic *efx)
{
struct ef100_tlv_state reader = {};
u32 total_len, offset = 0;
efx_dword_t reg;
int rc = 0, i;
u32 data;
efx_readd(efx, ®, ER_GZ_PARAMS_TLV_LEN);
total_len = EFX_DWORD_FIELD(reg, EFX_DWORD_0);
pci_dbg(efx->pci_dev, "%u bytes of design parameters\n", total_len);
while (offset < total_len) {
efx_readd(efx, ®, ER_GZ_PARAMS_TLV + offset);
data = EFX_DWORD_FIELD(reg, EFX_DWORD_0);
for (i = 0; i < sizeof(data); i++) {
rc = ef100_tlv_feed(&reader, data);
/* Got a complete value? */
if (!rc && reader.state == EF100_TLV_TYPE)
rc = ef100_process_design_param(efx, &reader);
if (rc)
goto out;
data >>= 8;
offset++;
}
}
/* Check we didn't end halfway through a TLV entry, which could either
* mean that the TLV stream is truncated or just that it's corrupted
* and our state machine is out of sync.
*/
if (reader.state != EF100_TLV_TYPE) {
if (reader.state == EF100_TLV_TYPE_CONT)
netif_err(efx, probe, efx->net_dev,
"truncated design parameter (incomplete type %u)\n",
reader.type);
else
netif_err(efx, probe, efx->net_dev,
"truncated design parameter %u\n",
reader.type);
rc = -EIO;
}
out:
return rc;
}
/* NIC probe and remove
*/
static int ef100_probe_main(struct efx_nic *efx)
{
unsigned int bar_size = resource_size(&efx->pci_dev->resource[efx->mem_bar]);
struct ef100_nic_data *nic_data;
char fw_version[32];
u32 priv_mask = 0;
int i, rc;
if (WARN_ON(bar_size == 0))
return -EIO;
nic_data = kzalloc(sizeof(*nic_data), GFP_KERNEL);
if (!nic_data)
return -ENOMEM;
efx->nic_data = nic_data;
nic_data->efx = efx;
efx->max_vis = EF100_MAX_VIS;
/* Populate design-parameter defaults */
nic_data->tso_max_hdr_len = ESE_EF100_DP_GZ_TSO_MAX_HDR_LEN_DEFAULT;
nic_data->tso_max_frames = ESE_EF100_DP_GZ_TSO_MAX_NUM_FRAMES_DEFAULT;
nic_data->tso_max_payload_num_segs = ESE_EF100_DP_GZ_TSO_MAX_PAYLOAD_NUM_SEGS_DEFAULT;
nic_data->tso_max_payload_len = ESE_EF100_DP_GZ_TSO_MAX_PAYLOAD_LEN_DEFAULT;
/* Read design parameters */
rc = ef100_check_design_params(efx);
if (rc) {
pci_err(efx->pci_dev, "Unsupported design parameters\n");
goto fail;
}
/* we assume later that we can copy from this buffer in dwords */
BUILD_BUG_ON(MCDI_CTL_SDU_LEN_MAX_V2 % 4);
/* MCDI buffers must be 256 byte aligned. */
rc = efx_nic_alloc_buffer(efx, &nic_data->mcdi_buf, MCDI_BUF_LEN,
GFP_KERNEL);
if (rc)
goto fail;
/* Get the MC's warm boot count. In case it's rebooting right
* now, be prepared to retry.
*/
i = 0;
for (;;) {
rc = ef100_get_warm_boot_count(efx);
if (rc >= 0)
break;
if (++i == 5)
goto fail;
ssleep(1);
}
nic_data->warm_boot_count = rc;
/* In case we're recovering from a crash (kexec), we want to
* cancel any outstanding request by the previous user of this
* function. We send a special message using the least
* significant bits of the 'high' (doorbell) register.
*/
_efx_writed(efx, cpu_to_le32(1), efx_reg(efx, ER_GZ_MC_DB_HWRD));
/* Post-IO section. */
rc = efx_mcdi_init(efx);
if (rc)
goto fail;
/* Reset (most) configuration for this function */
rc = efx_mcdi_reset(efx, RESET_TYPE_ALL);
if (rc)
goto fail;
/* Enable event logging */
rc = efx_mcdi_log_ctrl(efx, true, false, 0);
if (rc)
goto fail;
rc = efx_get_pf_index(efx, &nic_data->pf_index);
if (rc)
goto fail;
rc = efx_mcdi_port_get_number(efx);
if (rc < 0)
goto fail;
efx->port_num = rc;
efx_mcdi_print_fwver(efx, fw_version, sizeof(fw_version));
pci_dbg(efx->pci_dev, "Firmware version %s\n", fw_version);
rc = efx_mcdi_get_privilege_mask(efx, &priv_mask);
if (rc) /* non-fatal, and priv_mask will still be 0 */
pci_info(efx->pci_dev,
"Failed to get privilege mask from FW, rc %d\n", rc);
nic_data->grp_mae = !!(priv_mask & MC_CMD_PRIVILEGE_MASK_IN_GRP_MAE);
if (compare_versions(fw_version, "1.1.0.1000") < 0) {
pci_info(efx->pci_dev, "Firmware uses old event descriptors\n");
rc = -EINVAL;
goto fail;
}
if (efx_has_cap(efx, UNSOL_EV_CREDIT_SUPPORTED)) {
pci_info(efx->pci_dev, "Firmware uses unsolicited-event credits\n");
rc = -EINVAL;
goto fail;
}
return 0;
fail:
return rc;
}
/* MCDI commands are related to the same device issuing them. This function
* allows to do an MCDI command on behalf of another device, mainly PFs setting
* things for VFs.
*/
int efx_ef100_lookup_client_id(struct efx_nic *efx, efx_qword_t pciefn, u32 *id)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_CLIENT_HANDLE_OUT_LEN);
MCDI_DECLARE_BUF(inbuf, MC_CMD_GET_CLIENT_HANDLE_IN_LEN);
u64 pciefn_flat = le64_to_cpu(pciefn.u64[0]);
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, GET_CLIENT_HANDLE_IN_TYPE,
MC_CMD_GET_CLIENT_HANDLE_IN_TYPE_FUNC);
MCDI_SET_QWORD(inbuf, GET_CLIENT_HANDLE_IN_FUNC,
pciefn_flat);
rc = efx_mcdi_rpc(efx, MC_CMD_GET_CLIENT_HANDLE, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < sizeof(outbuf))
return -EIO;
*id = MCDI_DWORD(outbuf, GET_CLIENT_HANDLE_OUT_HANDLE);
return 0;
}
int ef100_probe_netdev_pf(struct efx_nic *efx)
{
struct ef100_nic_data *nic_data = efx->nic_data;
struct net_device *net_dev = efx->net_dev;
int rc;
if (!IS_ENABLED(CONFIG_SFC_SRIOV) || !nic_data->grp_mae)
return 0;
rc = efx_init_struct_tc(efx);
if (rc)
return rc;
rc = efx_ef100_get_base_mport(efx);
if (rc) {
netif_warn(efx, probe, net_dev,
"Failed to probe base mport rc %d; representors will not function\n",
rc);
}
rc = efx_init_mae(efx);
if (rc)
netif_warn(efx, probe, net_dev,
"Failed to init MAE rc %d; representors will not function\n",
rc);
else
efx_ef100_init_reps(efx);
rc = efx_init_tc(efx);
if (rc) {
/* Either we don't have an MAE at all (i.e. legacy v-switching),
* or we do but we failed to probe it. In the latter case, we
* may not have set up default rules, in which case we won't be
* able to pass any traffic. However, we don't fail the probe,
* because the user might need to use the netdevice to apply
* configuration changes to fix whatever's wrong with the MAE.
*/
netif_warn(efx, probe, net_dev, "Failed to probe MAE rc %d\n",
rc);
} else {
net_dev->features |= NETIF_F_HW_TC;
efx->fixed_features |= NETIF_F_HW_TC;
}
return 0;
}
int ef100_probe_vf(struct efx_nic *efx)
{
return ef100_probe_main(efx);
}
void ef100_remove(struct efx_nic *efx)
{
struct ef100_nic_data *nic_data = efx->nic_data;
if (IS_ENABLED(CONFIG_SFC_SRIOV) && efx->mae) {
efx_ef100_fini_reps(efx);
efx_fini_mae(efx);
}
efx_mcdi_detach(efx);
efx_mcdi_fini(efx);
if (nic_data)
efx_nic_free_buffer(efx, &nic_data->mcdi_buf);
kfree(nic_data);
efx->nic_data = NULL;
}
/* NIC level access functions
*/
#define EF100_OFFLOAD_FEATURES (NETIF_F_HW_CSUM | NETIF_F_RXCSUM | \
NETIF_F_HIGHDMA | NETIF_F_SG | NETIF_F_FRAGLIST | NETIF_F_NTUPLE | \
NETIF_F_RXHASH | NETIF_F_RXFCS | NETIF_F_TSO_ECN | NETIF_F_RXALL | \
NETIF_F_HW_VLAN_CTAG_TX)
const struct efx_nic_type ef100_pf_nic_type = {
.revision = EFX_REV_EF100,
.is_vf = false,
.probe = ef100_probe_main,
.offload_features = EF100_OFFLOAD_FEATURES,
.mcdi_max_ver = 2,
.mcdi_request = ef100_mcdi_request,
.mcdi_poll_response = ef100_mcdi_poll_response,
.mcdi_read_response = ef100_mcdi_read_response,
.mcdi_poll_reboot = ef100_mcdi_poll_reboot,
.mcdi_reboot_detected = ef100_mcdi_reboot_detected,
.irq_enable_master = efx_port_dummy_op_void,
.irq_test_generate = efx_ef100_irq_test_generate,
.irq_disable_non_ev = efx_port_dummy_op_void,
.push_irq_moderation = efx_channel_dummy_op_void,
.min_interrupt_mode = EFX_INT_MODE_MSIX,
.map_reset_reason = ef100_map_reset_reason,
.map_reset_flags = ef100_map_reset_flags,
.reset = ef100_reset,
.check_caps = ef100_check_caps,
.ev_probe = ef100_ev_probe,
.ev_init = ef100_ev_init,
.ev_fini = efx_mcdi_ev_fini,
.ev_remove = efx_mcdi_ev_remove,
.irq_handle_msi = ef100_msi_interrupt,
.ev_process = ef100_ev_process,
.ev_read_ack = ef100_ev_read_ack,
.ev_test_generate = efx_ef100_ev_test_generate,
.tx_probe = ef100_tx_probe,
.tx_init = ef100_tx_init,
.tx_write = ef100_tx_write,
.tx_enqueue = ef100_enqueue_skb,
.rx_probe = efx_mcdi_rx_probe,
.rx_init = efx_mcdi_rx_init,
.rx_remove = efx_mcdi_rx_remove,
.rx_write = ef100_rx_write,
.rx_packet = __ef100_rx_packet,
.rx_buf_hash_valid = ef100_rx_buf_hash_valid,
.fini_dmaq = efx_fini_dmaq,
.max_rx_ip_filters = EFX_MCDI_FILTER_TBL_ROWS,
.filter_table_probe = ef100_filter_table_up,
.filter_table_restore = efx_mcdi_filter_table_restore,
.filter_table_remove = ef100_filter_table_down,
.filter_insert = efx_mcdi_filter_insert,
.filter_remove_safe = efx_mcdi_filter_remove_safe,
.filter_get_safe = efx_mcdi_filter_get_safe,
.filter_clear_rx = efx_mcdi_filter_clear_rx,
.filter_count_rx_used = efx_mcdi_filter_count_rx_used,
.filter_get_rx_id_limit = efx_mcdi_filter_get_rx_id_limit,
.filter_get_rx_ids = efx_mcdi_filter_get_rx_ids,
#ifdef CONFIG_RFS_ACCEL
.filter_rfs_expire_one = efx_mcdi_filter_rfs_expire_one,
#endif
.get_phys_port_id = efx_ef100_get_phys_port_id,
.rx_prefix_size = ESE_GZ_RX_PKT_PREFIX_LEN,
.rx_hash_offset = ESF_GZ_RX_PREFIX_RSS_HASH_LBN / 8,
.rx_ts_offset = ESF_GZ_RX_PREFIX_PARTIAL_TSTAMP_LBN / 8,
.rx_hash_key_size = 40,
.rx_pull_rss_config = efx_mcdi_rx_pull_rss_config,
.rx_push_rss_config = efx_mcdi_pf_rx_push_rss_config,
.rx_push_rss_context_config = efx_mcdi_rx_push_rss_context_config,
.rx_pull_rss_context_config = efx_mcdi_rx_pull_rss_context_config,
.rx_restore_rss_contexts = efx_mcdi_rx_restore_rss_contexts,
.rx_recycle_ring_size = efx_ef100_recycle_ring_size,
.reconfigure_mac = ef100_reconfigure_mac,
.reconfigure_port = efx_mcdi_port_reconfigure,
.test_nvram = efx_new_mcdi_nvram_test_all,
.describe_stats = ef100_describe_stats,
.start_stats = efx_mcdi_mac_start_stats,
.update_stats = ef100_update_stats,
.pull_stats = efx_mcdi_mac_pull_stats,
.stop_stats = efx_mcdi_mac_stop_stats,
.sriov_configure = IS_ENABLED(CONFIG_SFC_SRIOV) ?
efx_ef100_sriov_configure : NULL,
/* Per-type bar/size configuration not used on ef100. Location of
* registers is defined by extended capabilities.
*/
.mem_bar = NULL,
.mem_map_size = NULL,
};
const struct efx_nic_type ef100_vf_nic_type = {
.revision = EFX_REV_EF100,
.is_vf = true,
.probe = ef100_probe_vf,
.offload_features = EF100_OFFLOAD_FEATURES,
.mcdi_max_ver = 2,
.mcdi_request = ef100_mcdi_request,
.mcdi_poll_response = ef100_mcdi_poll_response,
.mcdi_read_response = ef100_mcdi_read_response,
.mcdi_poll_reboot = ef100_mcdi_poll_reboot,
.mcdi_reboot_detected = ef100_mcdi_reboot_detected,
.irq_enable_master = efx_port_dummy_op_void,
.irq_test_generate = efx_ef100_irq_test_generate,
.irq_disable_non_ev = efx_port_dummy_op_void,
.push_irq_moderation = efx_channel_dummy_op_void,
.min_interrupt_mode = EFX_INT_MODE_MSIX,
.map_reset_reason = ef100_map_reset_reason,
.map_reset_flags = ef100_map_reset_flags,
.reset = ef100_reset,
.check_caps = ef100_check_caps,
.ev_probe = ef100_ev_probe,
.ev_init = ef100_ev_init,
.ev_fini = efx_mcdi_ev_fini,
.ev_remove = efx_mcdi_ev_remove,
.irq_handle_msi = ef100_msi_interrupt,
.ev_process = ef100_ev_process,
.ev_read_ack = ef100_ev_read_ack,
.ev_test_generate = efx_ef100_ev_test_generate,
.tx_probe = ef100_tx_probe,
.tx_init = ef100_tx_init,
.tx_write = ef100_tx_write,
.tx_enqueue = ef100_enqueue_skb,
.rx_probe = efx_mcdi_rx_probe,
.rx_init = efx_mcdi_rx_init,
.rx_remove = efx_mcdi_rx_remove,
.rx_write = ef100_rx_write,
.rx_packet = __ef100_rx_packet,
.rx_buf_hash_valid = ef100_rx_buf_hash_valid,
.fini_dmaq = efx_fini_dmaq,
.max_rx_ip_filters = EFX_MCDI_FILTER_TBL_ROWS,
.filter_table_probe = ef100_filter_table_up,
.filter_table_restore = efx_mcdi_filter_table_restore,
.filter_table_remove = ef100_filter_table_down,
.filter_insert = efx_mcdi_filter_insert,
.filter_remove_safe = efx_mcdi_filter_remove_safe,
.filter_get_safe = efx_mcdi_filter_get_safe,
.filter_clear_rx = efx_mcdi_filter_clear_rx,
.filter_count_rx_used = efx_mcdi_filter_count_rx_used,
.filter_get_rx_id_limit = efx_mcdi_filter_get_rx_id_limit,
.filter_get_rx_ids = efx_mcdi_filter_get_rx_ids,
#ifdef CONFIG_RFS_ACCEL
.filter_rfs_expire_one = efx_mcdi_filter_rfs_expire_one,
#endif
.rx_prefix_size = ESE_GZ_RX_PKT_PREFIX_LEN,
.rx_hash_offset = ESF_GZ_RX_PREFIX_RSS_HASH_LBN / 8,
.rx_ts_offset = ESF_GZ_RX_PREFIX_PARTIAL_TSTAMP_LBN / 8,
.rx_hash_key_size = 40,
.rx_pull_rss_config = efx_mcdi_rx_pull_rss_config,
.rx_push_rss_config = efx_mcdi_pf_rx_push_rss_config,
.rx_restore_rss_contexts = efx_mcdi_rx_restore_rss_contexts,
.rx_recycle_ring_size = efx_ef100_recycle_ring_size,
.reconfigure_mac = ef100_reconfigure_mac,
.test_nvram = efx_new_mcdi_nvram_test_all,
.describe_stats = ef100_describe_stats,
.start_stats = efx_mcdi_mac_start_stats,
.update_stats = ef100_update_stats,
.pull_stats = efx_mcdi_mac_pull_stats,
.stop_stats = efx_mcdi_mac_stop_stats,
.mem_bar = NULL,
.mem_map_size = NULL,
};
|
linux-master
|
drivers/net/ethernet/sfc/ef100_nic.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2018 Solarflare Communications Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include "net_driver.h"
#include <linux/filter.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <net/gre.h>
#include "efx_common.h"
#include "efx_channels.h"
#include "efx.h"
#include "mcdi.h"
#include "selftest.h"
#include "rx_common.h"
#include "tx_common.h"
#include "nic.h"
#include "mcdi_port_common.h"
#include "io.h"
#include "mcdi_pcol.h"
#include "ef100_rep.h"
static unsigned int debug = (NETIF_MSG_DRV | NETIF_MSG_PROBE |
NETIF_MSG_LINK | NETIF_MSG_IFDOWN |
NETIF_MSG_IFUP | NETIF_MSG_RX_ERR |
NETIF_MSG_TX_ERR | NETIF_MSG_HW);
module_param(debug, uint, 0);
MODULE_PARM_DESC(debug, "Bitmapped debugging message enable value");
/* This is the time (in jiffies) between invocations of the hardware
* monitor.
*/
static unsigned int efx_monitor_interval = 1 * HZ;
/* How often and how many times to poll for a reset while waiting for a
* BIST that another function started to complete.
*/
#define BIST_WAIT_DELAY_MS 100
#define BIST_WAIT_DELAY_COUNT 100
/* Default stats update time */
#define STATS_PERIOD_MS_DEFAULT 1000
static const unsigned int efx_reset_type_max = RESET_TYPE_MAX;
static const char *const efx_reset_type_names[] = {
[RESET_TYPE_INVISIBLE] = "INVISIBLE",
[RESET_TYPE_ALL] = "ALL",
[RESET_TYPE_RECOVER_OR_ALL] = "RECOVER_OR_ALL",
[RESET_TYPE_WORLD] = "WORLD",
[RESET_TYPE_RECOVER_OR_DISABLE] = "RECOVER_OR_DISABLE",
[RESET_TYPE_DATAPATH] = "DATAPATH",
[RESET_TYPE_MC_BIST] = "MC_BIST",
[RESET_TYPE_DISABLE] = "DISABLE",
[RESET_TYPE_TX_WATCHDOG] = "TX_WATCHDOG",
[RESET_TYPE_INT_ERROR] = "INT_ERROR",
[RESET_TYPE_DMA_ERROR] = "DMA_ERROR",
[RESET_TYPE_TX_SKIP] = "TX_SKIP",
[RESET_TYPE_MC_FAILURE] = "MC_FAILURE",
[RESET_TYPE_MCDI_TIMEOUT] = "MCDI_TIMEOUT (FLR)",
};
#define RESET_TYPE(type) \
STRING_TABLE_LOOKUP(type, efx_reset_type)
/* Loopback mode names (see LOOPBACK_MODE()) */
const unsigned int efx_loopback_mode_max = LOOPBACK_MAX;
const char *const efx_loopback_mode_names[] = {
[LOOPBACK_NONE] = "NONE",
[LOOPBACK_DATA] = "DATAPATH",
[LOOPBACK_GMAC] = "GMAC",
[LOOPBACK_XGMII] = "XGMII",
[LOOPBACK_XGXS] = "XGXS",
[LOOPBACK_XAUI] = "XAUI",
[LOOPBACK_GMII] = "GMII",
[LOOPBACK_SGMII] = "SGMII",
[LOOPBACK_XGBR] = "XGBR",
[LOOPBACK_XFI] = "XFI",
[LOOPBACK_XAUI_FAR] = "XAUI_FAR",
[LOOPBACK_GMII_FAR] = "GMII_FAR",
[LOOPBACK_SGMII_FAR] = "SGMII_FAR",
[LOOPBACK_XFI_FAR] = "XFI_FAR",
[LOOPBACK_GPHY] = "GPHY",
[LOOPBACK_PHYXS] = "PHYXS",
[LOOPBACK_PCS] = "PCS",
[LOOPBACK_PMAPMD] = "PMA/PMD",
[LOOPBACK_XPORT] = "XPORT",
[LOOPBACK_XGMII_WS] = "XGMII_WS",
[LOOPBACK_XAUI_WS] = "XAUI_WS",
[LOOPBACK_XAUI_WS_FAR] = "XAUI_WS_FAR",
[LOOPBACK_XAUI_WS_NEAR] = "XAUI_WS_NEAR",
[LOOPBACK_GMII_WS] = "GMII_WS",
[LOOPBACK_XFI_WS] = "XFI_WS",
[LOOPBACK_XFI_WS_FAR] = "XFI_WS_FAR",
[LOOPBACK_PHYXS_WS] = "PHYXS_WS",
};
/* Reset workqueue. If any NIC has a hardware failure then a reset will be
* queued onto this work queue. This is not a per-nic work queue, because
* efx_reset_work() acquires the rtnl lock, so resets are naturally serialised.
*/
static struct workqueue_struct *reset_workqueue;
int efx_create_reset_workqueue(void)
{
reset_workqueue = create_singlethread_workqueue("sfc_reset");
if (!reset_workqueue) {
printk(KERN_ERR "Failed to create reset workqueue\n");
return -ENOMEM;
}
return 0;
}
void efx_queue_reset_work(struct efx_nic *efx)
{
queue_work(reset_workqueue, &efx->reset_work);
}
void efx_flush_reset_workqueue(struct efx_nic *efx)
{
cancel_work_sync(&efx->reset_work);
}
void efx_destroy_reset_workqueue(void)
{
if (reset_workqueue) {
destroy_workqueue(reset_workqueue);
reset_workqueue = NULL;
}
}
/* We assume that efx->type->reconfigure_mac will always try to sync RX
* filters and therefore needs to read-lock the filter table against freeing
*/
void efx_mac_reconfigure(struct efx_nic *efx, bool mtu_only)
{
if (efx->type->reconfigure_mac) {
down_read(&efx->filter_sem);
efx->type->reconfigure_mac(efx, mtu_only);
up_read(&efx->filter_sem);
}
}
/* Asynchronous work item for changing MAC promiscuity and multicast
* hash. Avoid a drain/rx_ingress enable by reconfiguring the current
* MAC directly.
*/
static void efx_mac_work(struct work_struct *data)
{
struct efx_nic *efx = container_of(data, struct efx_nic, mac_work);
mutex_lock(&efx->mac_lock);
if (efx->port_enabled)
efx_mac_reconfigure(efx, false);
mutex_unlock(&efx->mac_lock);
}
int efx_set_mac_address(struct net_device *net_dev, void *data)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
struct sockaddr *addr = data;
u8 *new_addr = addr->sa_data;
u8 old_addr[6];
int rc;
if (!is_valid_ether_addr(new_addr)) {
netif_err(efx, drv, efx->net_dev,
"invalid ethernet MAC address requested: %pM\n",
new_addr);
return -EADDRNOTAVAIL;
}
/* save old address */
ether_addr_copy(old_addr, net_dev->dev_addr);
eth_hw_addr_set(net_dev, new_addr);
if (efx->type->set_mac_address) {
rc = efx->type->set_mac_address(efx);
if (rc) {
eth_hw_addr_set(net_dev, old_addr);
return rc;
}
}
/* Reconfigure the MAC */
mutex_lock(&efx->mac_lock);
efx_mac_reconfigure(efx, false);
mutex_unlock(&efx->mac_lock);
return 0;
}
/* Context: netif_addr_lock held, BHs disabled. */
void efx_set_rx_mode(struct net_device *net_dev)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
if (efx->port_enabled)
queue_work(efx->workqueue, &efx->mac_work);
/* Otherwise efx_start_port() will do this */
}
int efx_set_features(struct net_device *net_dev, netdev_features_t data)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
int rc;
/* If disabling RX n-tuple filtering, clear existing filters */
if (net_dev->features & ~data & NETIF_F_NTUPLE) {
rc = efx->type->filter_clear_rx(efx, EFX_FILTER_PRI_MANUAL);
if (rc)
return rc;
}
/* If Rx VLAN filter is changed, update filters via mac_reconfigure.
* If rx-fcs is changed, mac_reconfigure updates that too.
*/
if ((net_dev->features ^ data) & (NETIF_F_HW_VLAN_CTAG_FILTER |
NETIF_F_RXFCS)) {
/* efx_set_rx_mode() will schedule MAC work to update filters
* when a new features are finally set in net_dev.
*/
efx_set_rx_mode(net_dev);
}
return 0;
}
/* This ensures that the kernel is kept informed (via
* netif_carrier_on/off) of the link status, and also maintains the
* link status's stop on the port's TX queue.
*/
void efx_link_status_changed(struct efx_nic *efx)
{
struct efx_link_state *link_state = &efx->link_state;
/* SFC Bug 5356: A net_dev notifier is registered, so we must ensure
* that no events are triggered between unregister_netdev() and the
* driver unloading. A more general condition is that NETDEV_CHANGE
* can only be generated between NETDEV_UP and NETDEV_DOWN
*/
if (!netif_running(efx->net_dev))
return;
if (link_state->up != netif_carrier_ok(efx->net_dev)) {
efx->n_link_state_changes++;
if (link_state->up)
netif_carrier_on(efx->net_dev);
else
netif_carrier_off(efx->net_dev);
}
/* Status message for kernel log */
if (link_state->up)
netif_info(efx, link, efx->net_dev,
"link up at %uMbps %s-duplex (MTU %d)\n",
link_state->speed, link_state->fd ? "full" : "half",
efx->net_dev->mtu);
else
netif_info(efx, link, efx->net_dev, "link down\n");
}
unsigned int efx_xdp_max_mtu(struct efx_nic *efx)
{
/* The maximum MTU that we can fit in a single page, allowing for
* framing, overhead and XDP headroom + tailroom.
*/
int overhead = EFX_MAX_FRAME_LEN(0) + sizeof(struct efx_rx_page_state) +
efx->rx_prefix_size + efx->type->rx_buffer_padding +
efx->rx_ip_align + EFX_XDP_HEADROOM + EFX_XDP_TAILROOM;
return PAGE_SIZE - overhead;
}
/* Context: process, rtnl_lock() held. */
int efx_change_mtu(struct net_device *net_dev, int new_mtu)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
int rc;
rc = efx_check_disabled(efx);
if (rc)
return rc;
if (rtnl_dereference(efx->xdp_prog) &&
new_mtu > efx_xdp_max_mtu(efx)) {
netif_err(efx, drv, efx->net_dev,
"Requested MTU of %d too big for XDP (max: %d)\n",
new_mtu, efx_xdp_max_mtu(efx));
return -EINVAL;
}
netif_dbg(efx, drv, efx->net_dev, "changing MTU to %d\n", new_mtu);
efx_device_detach_sync(efx);
efx_stop_all(efx);
mutex_lock(&efx->mac_lock);
net_dev->mtu = new_mtu;
efx_mac_reconfigure(efx, true);
mutex_unlock(&efx->mac_lock);
efx_start_all(efx);
efx_device_attach_if_not_resetting(efx);
return 0;
}
/**************************************************************************
*
* Hardware monitor
*
**************************************************************************/
/* Run periodically off the general workqueue */
static void efx_monitor(struct work_struct *data)
{
struct efx_nic *efx = container_of(data, struct efx_nic,
monitor_work.work);
netif_vdbg(efx, timer, efx->net_dev,
"hardware monitor executing on CPU %d\n",
raw_smp_processor_id());
BUG_ON(efx->type->monitor == NULL);
/* If the mac_lock is already held then it is likely a port
* reconfiguration is already in place, which will likely do
* most of the work of monitor() anyway.
*/
if (mutex_trylock(&efx->mac_lock)) {
if (efx->port_enabled && efx->type->monitor)
efx->type->monitor(efx);
mutex_unlock(&efx->mac_lock);
}
efx_start_monitor(efx);
}
void efx_start_monitor(struct efx_nic *efx)
{
if (efx->type->monitor)
queue_delayed_work(efx->workqueue, &efx->monitor_work,
efx_monitor_interval);
}
/**************************************************************************
*
* Event queue processing
*
*************************************************************************/
/* Channels are shutdown and reinitialised whilst the NIC is running
* to propagate configuration changes (mtu, checksum offload), or
* to clear hardware error conditions
*/
static void efx_start_datapath(struct efx_nic *efx)
{
netdev_features_t old_features = efx->net_dev->features;
bool old_rx_scatter = efx->rx_scatter;
size_t rx_buf_len;
/* Calculate the rx buffer allocation parameters required to
* support the current MTU, including padding for header
* alignment and overruns.
*/
efx->rx_dma_len = (efx->rx_prefix_size +
EFX_MAX_FRAME_LEN(efx->net_dev->mtu) +
efx->type->rx_buffer_padding);
rx_buf_len = (sizeof(struct efx_rx_page_state) + EFX_XDP_HEADROOM +
efx->rx_ip_align + efx->rx_dma_len + EFX_XDP_TAILROOM);
if (rx_buf_len <= PAGE_SIZE) {
efx->rx_scatter = efx->type->always_rx_scatter;
efx->rx_buffer_order = 0;
} else if (efx->type->can_rx_scatter) {
BUILD_BUG_ON(EFX_RX_USR_BUF_SIZE % L1_CACHE_BYTES);
BUILD_BUG_ON(sizeof(struct efx_rx_page_state) +
2 * ALIGN(NET_IP_ALIGN + EFX_RX_USR_BUF_SIZE,
EFX_RX_BUF_ALIGNMENT) >
PAGE_SIZE);
efx->rx_scatter = true;
efx->rx_dma_len = EFX_RX_USR_BUF_SIZE;
efx->rx_buffer_order = 0;
} else {
efx->rx_scatter = false;
efx->rx_buffer_order = get_order(rx_buf_len);
}
efx_rx_config_page_split(efx);
if (efx->rx_buffer_order)
netif_dbg(efx, drv, efx->net_dev,
"RX buf len=%u; page order=%u batch=%u\n",
efx->rx_dma_len, efx->rx_buffer_order,
efx->rx_pages_per_batch);
else
netif_dbg(efx, drv, efx->net_dev,
"RX buf len=%u step=%u bpp=%u; page batch=%u\n",
efx->rx_dma_len, efx->rx_page_buf_step,
efx->rx_bufs_per_page, efx->rx_pages_per_batch);
/* Restore previously fixed features in hw_features and remove
* features which are fixed now
*/
efx->net_dev->hw_features |= efx->net_dev->features;
efx->net_dev->hw_features &= ~efx->fixed_features;
efx->net_dev->features |= efx->fixed_features;
if (efx->net_dev->features != old_features)
netdev_features_change(efx->net_dev);
/* RX filters may also have scatter-enabled flags */
if ((efx->rx_scatter != old_rx_scatter) &&
efx->type->filter_update_rx_scatter)
efx->type->filter_update_rx_scatter(efx);
/* We must keep at least one descriptor in a TX ring empty.
* We could avoid this when the queue size does not exactly
* match the hardware ring size, but it's not that important.
* Therefore we stop the queue when one more skb might fill
* the ring completely. We wake it when half way back to
* empty.
*/
efx->txq_stop_thresh = efx->txq_entries - efx_tx_max_skb_descs(efx);
efx->txq_wake_thresh = efx->txq_stop_thresh / 2;
/* Initialise the channels */
efx_start_channels(efx);
efx_ptp_start_datapath(efx);
if (netif_device_present(efx->net_dev))
netif_tx_wake_all_queues(efx->net_dev);
}
static void efx_stop_datapath(struct efx_nic *efx)
{
EFX_ASSERT_RESET_SERIALISED(efx);
BUG_ON(efx->port_enabled);
efx_ptp_stop_datapath(efx);
efx_stop_channels(efx);
}
/**************************************************************************
*
* Port handling
*
**************************************************************************/
/* Equivalent to efx_link_set_advertising with all-zeroes, except does not
* force the Autoneg bit on.
*/
void efx_link_clear_advertising(struct efx_nic *efx)
{
bitmap_zero(efx->link_advertising, __ETHTOOL_LINK_MODE_MASK_NBITS);
efx->wanted_fc &= ~(EFX_FC_TX | EFX_FC_RX);
}
void efx_link_set_wanted_fc(struct efx_nic *efx, u8 wanted_fc)
{
efx->wanted_fc = wanted_fc;
if (efx->link_advertising[0]) {
if (wanted_fc & EFX_FC_RX)
efx->link_advertising[0] |= (ADVERTISED_Pause |
ADVERTISED_Asym_Pause);
else
efx->link_advertising[0] &= ~(ADVERTISED_Pause |
ADVERTISED_Asym_Pause);
if (wanted_fc & EFX_FC_TX)
efx->link_advertising[0] ^= ADVERTISED_Asym_Pause;
}
}
static void efx_start_port(struct efx_nic *efx)
{
netif_dbg(efx, ifup, efx->net_dev, "start port\n");
BUG_ON(efx->port_enabled);
mutex_lock(&efx->mac_lock);
efx->port_enabled = true;
/* Ensure MAC ingress/egress is enabled */
efx_mac_reconfigure(efx, false);
mutex_unlock(&efx->mac_lock);
}
/* Cancel work for MAC reconfiguration, periodic hardware monitoring
* and the async self-test, wait for them to finish and prevent them
* being scheduled again. This doesn't cover online resets, which
* should only be cancelled when removing the device.
*/
static void efx_stop_port(struct efx_nic *efx)
{
netif_dbg(efx, ifdown, efx->net_dev, "stop port\n");
EFX_ASSERT_RESET_SERIALISED(efx);
mutex_lock(&efx->mac_lock);
efx->port_enabled = false;
mutex_unlock(&efx->mac_lock);
/* Serialise against efx_set_multicast_list() */
netif_addr_lock_bh(efx->net_dev);
netif_addr_unlock_bh(efx->net_dev);
cancel_delayed_work_sync(&efx->monitor_work);
efx_selftest_async_cancel(efx);
cancel_work_sync(&efx->mac_work);
}
/* If the interface is supposed to be running but is not, start
* the hardware and software data path, regular activity for the port
* (MAC statistics, link polling, etc.) and schedule the port to be
* reconfigured. Interrupts must already be enabled. This function
* is safe to call multiple times, so long as the NIC is not disabled.
* Requires the RTNL lock.
*/
void efx_start_all(struct efx_nic *efx)
{
EFX_ASSERT_RESET_SERIALISED(efx);
BUG_ON(efx->state == STATE_DISABLED);
/* Check that it is appropriate to restart the interface. All
* of these flags are safe to read under just the rtnl lock
*/
if (efx->port_enabled || !netif_running(efx->net_dev) ||
efx->reset_pending)
return;
efx_start_port(efx);
efx_start_datapath(efx);
/* Start the hardware monitor if there is one */
efx_start_monitor(efx);
efx_selftest_async_start(efx);
/* Link state detection is normally event-driven; we have
* to poll now because we could have missed a change
*/
mutex_lock(&efx->mac_lock);
if (efx_mcdi_phy_poll(efx))
efx_link_status_changed(efx);
mutex_unlock(&efx->mac_lock);
if (efx->type->start_stats) {
efx->type->start_stats(efx);
efx->type->pull_stats(efx);
spin_lock_bh(&efx->stats_lock);
efx->type->update_stats(efx, NULL, NULL);
spin_unlock_bh(&efx->stats_lock);
}
}
/* Quiesce the hardware and software data path, and regular activity
* for the port without bringing the link down. Safe to call multiple
* times with the NIC in almost any state, but interrupts should be
* enabled. Requires the RTNL lock.
*/
void efx_stop_all(struct efx_nic *efx)
{
EFX_ASSERT_RESET_SERIALISED(efx);
/* port_enabled can be read safely under the rtnl lock */
if (!efx->port_enabled)
return;
if (efx->type->update_stats) {
/* update stats before we go down so we can accurately count
* rx_nodesc_drops
*/
efx->type->pull_stats(efx);
spin_lock_bh(&efx->stats_lock);
efx->type->update_stats(efx, NULL, NULL);
spin_unlock_bh(&efx->stats_lock);
efx->type->stop_stats(efx);
}
efx_stop_port(efx);
/* Stop the kernel transmit interface. This is only valid if
* the device is stopped or detached; otherwise the watchdog
* may fire immediately.
*/
WARN_ON(netif_running(efx->net_dev) &&
netif_device_present(efx->net_dev));
netif_tx_disable(efx->net_dev);
efx_stop_datapath(efx);
}
/* Context: process, dev_base_lock or RTNL held, non-blocking. */
void efx_net_stats(struct net_device *net_dev, struct rtnl_link_stats64 *stats)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
spin_lock_bh(&efx->stats_lock);
efx_nic_update_stats_atomic(efx, NULL, stats);
spin_unlock_bh(&efx->stats_lock);
}
/* Push loopback/power/transmit disable settings to the PHY, and reconfigure
* the MAC appropriately. All other PHY configuration changes are pushed
* through phy_op->set_settings(), and pushed asynchronously to the MAC
* through efx_monitor().
*
* Callers must hold the mac_lock
*/
int __efx_reconfigure_port(struct efx_nic *efx)
{
enum efx_phy_mode phy_mode;
int rc = 0;
WARN_ON(!mutex_is_locked(&efx->mac_lock));
/* Disable PHY transmit in mac level loopbacks */
phy_mode = efx->phy_mode;
if (LOOPBACK_INTERNAL(efx))
efx->phy_mode |= PHY_MODE_TX_DISABLED;
else
efx->phy_mode &= ~PHY_MODE_TX_DISABLED;
if (efx->type->reconfigure_port)
rc = efx->type->reconfigure_port(efx);
if (rc)
efx->phy_mode = phy_mode;
return rc;
}
/* Reinitialise the MAC to pick up new PHY settings, even if the port is
* disabled.
*/
int efx_reconfigure_port(struct efx_nic *efx)
{
int rc;
EFX_ASSERT_RESET_SERIALISED(efx);
mutex_lock(&efx->mac_lock);
rc = __efx_reconfigure_port(efx);
mutex_unlock(&efx->mac_lock);
return rc;
}
/**************************************************************************
*
* Device reset and suspend
*
**************************************************************************/
static void efx_wait_for_bist_end(struct efx_nic *efx)
{
int i;
for (i = 0; i < BIST_WAIT_DELAY_COUNT; ++i) {
if (efx_mcdi_poll_reboot(efx))
goto out;
msleep(BIST_WAIT_DELAY_MS);
}
netif_err(efx, drv, efx->net_dev, "Warning: No MC reboot after BIST mode\n");
out:
/* Either way unset the BIST flag. If we found no reboot we probably
* won't recover, but we should try.
*/
efx->mc_bist_for_other_fn = false;
}
/* Try recovery mechanisms.
* For now only EEH is supported.
* Returns 0 if the recovery mechanisms are unsuccessful.
* Returns a non-zero value otherwise.
*/
int efx_try_recovery(struct efx_nic *efx)
{
#ifdef CONFIG_EEH
/* A PCI error can occur and not be seen by EEH because nothing
* happens on the PCI bus. In this case the driver may fail and
* schedule a 'recover or reset', leading to this recovery handler.
* Manually call the eeh failure check function.
*/
struct eeh_dev *eehdev = pci_dev_to_eeh_dev(efx->pci_dev);
if (eeh_dev_check_failure(eehdev)) {
/* The EEH mechanisms will handle the error and reset the
* device if necessary.
*/
return 1;
}
#endif
return 0;
}
/* Tears down the entire software state and most of the hardware state
* before reset.
*/
void efx_reset_down(struct efx_nic *efx, enum reset_type method)
{
EFX_ASSERT_RESET_SERIALISED(efx);
if (method == RESET_TYPE_MCDI_TIMEOUT)
efx->type->prepare_flr(efx);
efx_stop_all(efx);
efx_disable_interrupts(efx);
mutex_lock(&efx->mac_lock);
down_write(&efx->filter_sem);
mutex_lock(&efx->rss_lock);
efx->type->fini(efx);
}
/* Context: netif_tx_lock held, BHs disabled. */
void efx_watchdog(struct net_device *net_dev, unsigned int txqueue)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
netif_err(efx, tx_err, efx->net_dev,
"TX stuck with port_enabled=%d: resetting channels\n",
efx->port_enabled);
efx_schedule_reset(efx, RESET_TYPE_TX_WATCHDOG);
}
/* This function will always ensure that the locks acquired in
* efx_reset_down() are released. A failure return code indicates
* that we were unable to reinitialise the hardware, and the
* driver should be disabled. If ok is false, then the rx and tx
* engines are not restarted, pending a RESET_DISABLE.
*/
int efx_reset_up(struct efx_nic *efx, enum reset_type method, bool ok)
{
int rc;
EFX_ASSERT_RESET_SERIALISED(efx);
if (method == RESET_TYPE_MCDI_TIMEOUT)
efx->type->finish_flr(efx);
/* Ensure that SRAM is initialised even if we're disabling the device */
rc = efx->type->init(efx);
if (rc) {
netif_err(efx, drv, efx->net_dev, "failed to initialise NIC\n");
goto fail;
}
if (!ok)
goto fail;
if (efx->port_initialized && method != RESET_TYPE_INVISIBLE &&
method != RESET_TYPE_DATAPATH) {
rc = efx_mcdi_port_reconfigure(efx);
if (rc && rc != -EPERM)
netif_err(efx, drv, efx->net_dev,
"could not restore PHY settings\n");
}
rc = efx_enable_interrupts(efx);
if (rc)
goto fail;
#ifdef CONFIG_SFC_SRIOV
rc = efx->type->vswitching_restore(efx);
if (rc) /* not fatal; the PF will still work fine */
netif_warn(efx, probe, efx->net_dev,
"failed to restore vswitching rc=%d;"
" VFs may not function\n", rc);
#endif
if (efx->type->rx_restore_rss_contexts)
efx->type->rx_restore_rss_contexts(efx);
mutex_unlock(&efx->rss_lock);
efx->type->filter_table_restore(efx);
up_write(&efx->filter_sem);
mutex_unlock(&efx->mac_lock);
efx_start_all(efx);
if (efx->type->udp_tnl_push_ports)
efx->type->udp_tnl_push_ports(efx);
return 0;
fail:
efx->port_initialized = false;
mutex_unlock(&efx->rss_lock);
up_write(&efx->filter_sem);
mutex_unlock(&efx->mac_lock);
return rc;
}
/* Reset the NIC using the specified method. Note that the reset may
* fail, in which case the card will be left in an unusable state.
*
* Caller must hold the rtnl_lock.
*/
int efx_reset(struct efx_nic *efx, enum reset_type method)
{
int rc, rc2 = 0;
bool disabled;
netif_info(efx, drv, efx->net_dev, "resetting (%s)\n",
RESET_TYPE(method));
efx_device_detach_sync(efx);
/* efx_reset_down() grabs locks that prevent recovery on EF100.
* EF100 reset is handled in the efx_nic_type callback below.
*/
if (efx_nic_rev(efx) != EFX_REV_EF100)
efx_reset_down(efx, method);
rc = efx->type->reset(efx, method);
if (rc) {
netif_err(efx, drv, efx->net_dev, "failed to reset hardware\n");
goto out;
}
/* Clear flags for the scopes we covered. We assume the NIC and
* driver are now quiescent so that there is no race here.
*/
if (method < RESET_TYPE_MAX_METHOD)
efx->reset_pending &= -(1 << (method + 1));
else /* it doesn't fit into the well-ordered scope hierarchy */
__clear_bit(method, &efx->reset_pending);
/* Reinitialise bus-mastering, which may have been turned off before
* the reset was scheduled. This is still appropriate, even in the
* RESET_TYPE_DISABLE since this driver generally assumes the hardware
* can respond to requests.
*/
pci_set_master(efx->pci_dev);
out:
/* Leave device stopped if necessary */
disabled = rc ||
method == RESET_TYPE_DISABLE ||
method == RESET_TYPE_RECOVER_OR_DISABLE;
if (efx_nic_rev(efx) != EFX_REV_EF100)
rc2 = efx_reset_up(efx, method, !disabled);
if (rc2) {
disabled = true;
if (!rc)
rc = rc2;
}
if (disabled) {
dev_close(efx->net_dev);
netif_err(efx, drv, efx->net_dev, "has been disabled\n");
efx->state = STATE_DISABLED;
} else {
netif_dbg(efx, drv, efx->net_dev, "reset complete\n");
efx_device_attach_if_not_resetting(efx);
}
return rc;
}
/* The worker thread exists so that code that cannot sleep can
* schedule a reset for later.
*/
static void efx_reset_work(struct work_struct *data)
{
struct efx_nic *efx = container_of(data, struct efx_nic, reset_work);
unsigned long pending;
enum reset_type method;
pending = READ_ONCE(efx->reset_pending);
method = fls(pending) - 1;
if (method == RESET_TYPE_MC_BIST)
efx_wait_for_bist_end(efx);
if ((method == RESET_TYPE_RECOVER_OR_DISABLE ||
method == RESET_TYPE_RECOVER_OR_ALL) &&
efx_try_recovery(efx))
return;
if (!pending)
return;
rtnl_lock();
/* We checked the state in efx_schedule_reset() but it may
* have changed by now. Now that we have the RTNL lock,
* it cannot change again.
*/
if (efx_net_active(efx->state))
(void)efx_reset(efx, method);
rtnl_unlock();
}
void efx_schedule_reset(struct efx_nic *efx, enum reset_type type)
{
enum reset_type method;
if (efx_recovering(efx->state)) {
netif_dbg(efx, drv, efx->net_dev,
"recovering: skip scheduling %s reset\n",
RESET_TYPE(type));
return;
}
switch (type) {
case RESET_TYPE_INVISIBLE:
case RESET_TYPE_ALL:
case RESET_TYPE_RECOVER_OR_ALL:
case RESET_TYPE_WORLD:
case RESET_TYPE_DISABLE:
case RESET_TYPE_RECOVER_OR_DISABLE:
case RESET_TYPE_DATAPATH:
case RESET_TYPE_MC_BIST:
case RESET_TYPE_MCDI_TIMEOUT:
method = type;
netif_dbg(efx, drv, efx->net_dev, "scheduling %s reset\n",
RESET_TYPE(method));
break;
default:
method = efx->type->map_reset_reason(type);
netif_dbg(efx, drv, efx->net_dev,
"scheduling %s reset for %s\n",
RESET_TYPE(method), RESET_TYPE(type));
break;
}
set_bit(method, &efx->reset_pending);
smp_mb(); /* ensure we change reset_pending before checking state */
/* If we're not READY then just leave the flags set as the cue
* to abort probing or reschedule the reset later.
*/
if (!efx_net_active(READ_ONCE(efx->state)))
return;
/* efx_process_channel() will no longer read events once a
* reset is scheduled. So switch back to poll'd MCDI completions.
*/
efx_mcdi_mode_poll(efx);
efx_queue_reset_work(efx);
}
/**************************************************************************
*
* Dummy NIC operations
*
* Can be used for some unimplemented operations
* Needed so all function pointers are valid and do not have to be tested
* before use
*
**************************************************************************/
int efx_port_dummy_op_int(struct efx_nic *efx)
{
return 0;
}
void efx_port_dummy_op_void(struct efx_nic *efx) {}
/**************************************************************************
*
* Data housekeeping
*
**************************************************************************/
/* This zeroes out and then fills in the invariants in a struct
* efx_nic (including all sub-structures).
*/
int efx_init_struct(struct efx_nic *efx, struct pci_dev *pci_dev)
{
int rc = -ENOMEM;
/* Initialise common structures */
INIT_LIST_HEAD(&efx->node);
INIT_LIST_HEAD(&efx->secondary_list);
spin_lock_init(&efx->biu_lock);
#ifdef CONFIG_SFC_MTD
INIT_LIST_HEAD(&efx->mtd_list);
#endif
INIT_WORK(&efx->reset_work, efx_reset_work);
INIT_DELAYED_WORK(&efx->monitor_work, efx_monitor);
efx_selftest_async_init(efx);
efx->pci_dev = pci_dev;
efx->msg_enable = debug;
efx->state = STATE_UNINIT;
strscpy(efx->name, pci_name(pci_dev), sizeof(efx->name));
efx->rx_prefix_size = efx->type->rx_prefix_size;
efx->rx_ip_align =
NET_IP_ALIGN ? (efx->rx_prefix_size + NET_IP_ALIGN) % 4 : 0;
efx->rx_packet_hash_offset =
efx->type->rx_hash_offset - efx->type->rx_prefix_size;
efx->rx_packet_ts_offset =
efx->type->rx_ts_offset - efx->type->rx_prefix_size;
INIT_LIST_HEAD(&efx->rss_context.list);
efx->rss_context.context_id = EFX_MCDI_RSS_CONTEXT_INVALID;
mutex_init(&efx->rss_lock);
efx->vport_id = EVB_PORT_ID_ASSIGNED;
spin_lock_init(&efx->stats_lock);
efx->vi_stride = EFX_DEFAULT_VI_STRIDE;
efx->num_mac_stats = MC_CMD_MAC_NSTATS;
BUILD_BUG_ON(MC_CMD_MAC_NSTATS - 1 != MC_CMD_MAC_GENERATION_END);
mutex_init(&efx->mac_lock);
init_rwsem(&efx->filter_sem);
#ifdef CONFIG_RFS_ACCEL
mutex_init(&efx->rps_mutex);
spin_lock_init(&efx->rps_hash_lock);
/* Failure to allocate is not fatal, but may degrade ARFS performance */
efx->rps_hash_table = kcalloc(EFX_ARFS_HASH_TABLE_SIZE,
sizeof(*efx->rps_hash_table), GFP_KERNEL);
#endif
spin_lock_init(&efx->vf_reps_lock);
INIT_LIST_HEAD(&efx->vf_reps);
INIT_WORK(&efx->mac_work, efx_mac_work);
init_waitqueue_head(&efx->flush_wq);
efx->tx_queues_per_channel = 1;
efx->rxq_entries = EFX_DEFAULT_DMAQ_SIZE;
efx->txq_entries = EFX_DEFAULT_DMAQ_SIZE;
efx->mem_bar = UINT_MAX;
rc = efx_init_channels(efx);
if (rc)
goto fail;
/* Would be good to use the net_dev name, but we're too early */
snprintf(efx->workqueue_name, sizeof(efx->workqueue_name), "sfc%s",
pci_name(pci_dev));
efx->workqueue = create_singlethread_workqueue(efx->workqueue_name);
if (!efx->workqueue) {
rc = -ENOMEM;
goto fail;
}
return 0;
fail:
efx_fini_struct(efx);
return rc;
}
void efx_fini_struct(struct efx_nic *efx)
{
#ifdef CONFIG_RFS_ACCEL
kfree(efx->rps_hash_table);
#endif
efx_fini_channels(efx);
kfree(efx->vpd_sn);
if (efx->workqueue) {
destroy_workqueue(efx->workqueue);
efx->workqueue = NULL;
}
}
/* This configures the PCI device to enable I/O and DMA. */
int efx_init_io(struct efx_nic *efx, int bar, dma_addr_t dma_mask,
unsigned int mem_map_size)
{
struct pci_dev *pci_dev = efx->pci_dev;
int rc;
efx->mem_bar = UINT_MAX;
pci_dbg(pci_dev, "initialising I/O bar=%d\n", bar);
rc = pci_enable_device(pci_dev);
if (rc) {
pci_err(pci_dev, "failed to enable PCI device\n");
goto fail1;
}
pci_set_master(pci_dev);
rc = dma_set_mask_and_coherent(&pci_dev->dev, dma_mask);
if (rc) {
pci_err(efx->pci_dev, "could not find a suitable DMA mask\n");
goto fail2;
}
pci_dbg(efx->pci_dev, "using DMA mask %llx\n", (unsigned long long)dma_mask);
efx->membase_phys = pci_resource_start(efx->pci_dev, bar);
if (!efx->membase_phys) {
pci_err(efx->pci_dev,
"ERROR: No BAR%d mapping from the BIOS. Try pci=realloc on the kernel command line\n",
bar);
rc = -ENODEV;
goto fail3;
}
rc = pci_request_region(pci_dev, bar, "sfc");
if (rc) {
pci_err(efx->pci_dev,
"request for memory BAR[%d] failed\n", bar);
rc = -EIO;
goto fail3;
}
efx->mem_bar = bar;
efx->membase = ioremap(efx->membase_phys, mem_map_size);
if (!efx->membase) {
pci_err(efx->pci_dev,
"could not map memory BAR[%d] at %llx+%x\n", bar,
(unsigned long long)efx->membase_phys, mem_map_size);
rc = -ENOMEM;
goto fail4;
}
pci_dbg(efx->pci_dev,
"memory BAR[%d] at %llx+%x (virtual %p)\n", bar,
(unsigned long long)efx->membase_phys, mem_map_size,
efx->membase);
return 0;
fail4:
pci_release_region(efx->pci_dev, bar);
fail3:
efx->membase_phys = 0;
fail2:
pci_disable_device(efx->pci_dev);
fail1:
return rc;
}
void efx_fini_io(struct efx_nic *efx)
{
pci_dbg(efx->pci_dev, "shutting down I/O\n");
if (efx->membase) {
iounmap(efx->membase);
efx->membase = NULL;
}
if (efx->membase_phys) {
pci_release_region(efx->pci_dev, efx->mem_bar);
efx->membase_phys = 0;
efx->mem_bar = UINT_MAX;
}
/* Don't disable bus-mastering if VFs are assigned */
if (!pci_vfs_assigned(efx->pci_dev))
pci_disable_device(efx->pci_dev);
}
#ifdef CONFIG_SFC_MCDI_LOGGING
static ssize_t mcdi_logging_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct efx_nic *efx = dev_get_drvdata(dev);
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
return sysfs_emit(buf, "%d\n", mcdi->logging_enabled);
}
static ssize_t mcdi_logging_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct efx_nic *efx = dev_get_drvdata(dev);
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
bool enable = count > 0 && *buf != '0';
mcdi->logging_enabled = enable;
return count;
}
static DEVICE_ATTR_RW(mcdi_logging);
void efx_init_mcdi_logging(struct efx_nic *efx)
{
int rc = device_create_file(&efx->pci_dev->dev, &dev_attr_mcdi_logging);
if (rc) {
netif_warn(efx, drv, efx->net_dev,
"failed to init net dev attributes\n");
}
}
void efx_fini_mcdi_logging(struct efx_nic *efx)
{
device_remove_file(&efx->pci_dev->dev, &dev_attr_mcdi_logging);
}
#endif
/* A PCI error affecting this device was detected.
* At this point MMIO and DMA may be disabled.
* Stop the software path and request a slot reset.
*/
static pci_ers_result_t efx_io_error_detected(struct pci_dev *pdev,
pci_channel_state_t state)
{
pci_ers_result_t status = PCI_ERS_RESULT_RECOVERED;
struct efx_nic *efx = pci_get_drvdata(pdev);
if (state == pci_channel_io_perm_failure)
return PCI_ERS_RESULT_DISCONNECT;
rtnl_lock();
if (efx->state != STATE_DISABLED) {
efx->state = efx_recover(efx->state);
efx->reset_pending = 0;
efx_device_detach_sync(efx);
if (efx_net_active(efx->state)) {
efx_stop_all(efx);
efx_disable_interrupts(efx);
}
status = PCI_ERS_RESULT_NEED_RESET;
} else {
/* If the interface is disabled we don't want to do anything
* with it.
*/
status = PCI_ERS_RESULT_RECOVERED;
}
rtnl_unlock();
pci_disable_device(pdev);
return status;
}
/* Fake a successful reset, which will be performed later in efx_io_resume. */
static pci_ers_result_t efx_io_slot_reset(struct pci_dev *pdev)
{
struct efx_nic *efx = pci_get_drvdata(pdev);
pci_ers_result_t status = PCI_ERS_RESULT_RECOVERED;
if (pci_enable_device(pdev)) {
netif_err(efx, hw, efx->net_dev,
"Cannot re-enable PCI device after reset.\n");
status = PCI_ERS_RESULT_DISCONNECT;
}
return status;
}
/* Perform the actual reset and resume I/O operations. */
static void efx_io_resume(struct pci_dev *pdev)
{
struct efx_nic *efx = pci_get_drvdata(pdev);
int rc;
rtnl_lock();
if (efx->state == STATE_DISABLED)
goto out;
rc = efx_reset(efx, RESET_TYPE_ALL);
if (rc) {
netif_err(efx, hw, efx->net_dev,
"efx_reset failed after PCI error (%d)\n", rc);
} else {
efx->state = efx_recovered(efx->state);
netif_dbg(efx, hw, efx->net_dev,
"Done resetting and resuming IO after PCI error.\n");
}
out:
rtnl_unlock();
}
/* For simplicity and reliability, we always require a slot reset and try to
* reset the hardware when a pci error affecting the device is detected.
* We leave both the link_reset and mmio_enabled callback unimplemented:
* with our request for slot reset the mmio_enabled callback will never be
* called, and the link_reset callback is not used by AER or EEH mechanisms.
*/
const struct pci_error_handlers efx_err_handlers = {
.error_detected = efx_io_error_detected,
.slot_reset = efx_io_slot_reset,
.resume = efx_io_resume,
};
/* Determine whether the NIC will be able to handle TX offloads for a given
* encapsulated packet.
*/
static bool efx_can_encap_offloads(struct efx_nic *efx, struct sk_buff *skb)
{
struct gre_base_hdr *greh;
__be16 dst_port;
u8 ipproto;
/* Does the NIC support encap offloads?
* If not, we should never get here, because we shouldn't have
* advertised encap offload feature flags in the first place.
*/
if (WARN_ON_ONCE(!efx->type->udp_tnl_has_port))
return false;
/* Determine encapsulation protocol in use */
switch (skb->protocol) {
case htons(ETH_P_IP):
ipproto = ip_hdr(skb)->protocol;
break;
case htons(ETH_P_IPV6):
/* If there are extension headers, this will cause us to
* think we can't offload something that we maybe could have.
*/
ipproto = ipv6_hdr(skb)->nexthdr;
break;
default:
/* Not IP, so can't offload it */
return false;
}
switch (ipproto) {
case IPPROTO_GRE:
/* We support NVGRE but not IP over GRE or random gretaps.
* Specifically, the NIC will accept GRE as encapsulated if
* the inner protocol is Ethernet, but only handle it
* correctly if the GRE header is 8 bytes long. Moreover,
* it will not update the Checksum or Sequence Number fields
* if they are present. (The Routing Present flag,
* GRE_ROUTING, cannot be set else the header would be more
* than 8 bytes long; so we don't have to worry about it.)
*/
if (skb->inner_protocol_type != ENCAP_TYPE_ETHER)
return false;
if (ntohs(skb->inner_protocol) != ETH_P_TEB)
return false;
if (skb_inner_mac_header(skb) - skb_transport_header(skb) != 8)
return false;
greh = (struct gre_base_hdr *)skb_transport_header(skb);
return !(greh->flags & (GRE_CSUM | GRE_SEQ));
case IPPROTO_UDP:
/* If the port is registered for a UDP tunnel, we assume the
* packet is for that tunnel, and the NIC will handle it as
* such. If not, the NIC won't know what to do with it.
*/
dst_port = udp_hdr(skb)->dest;
return efx->type->udp_tnl_has_port(efx, dst_port);
default:
return false;
}
}
netdev_features_t efx_features_check(struct sk_buff *skb, struct net_device *dev,
netdev_features_t features)
{
struct efx_nic *efx = efx_netdev_priv(dev);
if (skb->encapsulation) {
if (features & NETIF_F_GSO_MASK)
/* Hardware can only do TSO with at most 208 bytes
* of headers.
*/
if (skb_inner_transport_offset(skb) >
EFX_TSO2_MAX_HDRLEN)
features &= ~(NETIF_F_GSO_MASK);
if (features & (NETIF_F_GSO_MASK | NETIF_F_CSUM_MASK))
if (!efx_can_encap_offloads(efx, skb))
features &= ~(NETIF_F_GSO_MASK |
NETIF_F_CSUM_MASK);
}
return features;
}
int efx_get_phys_port_id(struct net_device *net_dev,
struct netdev_phys_item_id *ppid)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
if (efx->type->get_phys_port_id)
return efx->type->get_phys_port_id(efx, ppid);
else
return -EOPNOTSUPP;
}
int efx_get_phys_port_name(struct net_device *net_dev, char *name, size_t len)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
if (snprintf(name, len, "p%u", efx->port_num) >= len)
return -EINVAL;
return 0;
}
void efx_detach_reps(struct efx_nic *efx)
{
struct net_device *rep_dev;
struct efx_rep *efv;
ASSERT_RTNL();
netif_dbg(efx, drv, efx->net_dev, "Detaching VF representors\n");
list_for_each_entry(efv, &efx->vf_reps, list) {
rep_dev = efv->net_dev;
if (!rep_dev)
continue;
netif_carrier_off(rep_dev);
/* See efx_device_detach_sync() */
netif_tx_lock_bh(rep_dev);
netif_tx_stop_all_queues(rep_dev);
netif_tx_unlock_bh(rep_dev);
}
}
void efx_attach_reps(struct efx_nic *efx)
{
struct net_device *rep_dev;
struct efx_rep *efv;
ASSERT_RTNL();
netif_dbg(efx, drv, efx->net_dev, "Attaching VF representors\n");
list_for_each_entry(efv, &efx->vf_reps, list) {
rep_dev = efv->net_dev;
if (!rep_dev)
continue;
netif_tx_wake_all_queues(rep_dev);
netif_carrier_on(rep_dev);
}
}
|
linux-master
|
drivers/net/ethernet/sfc/efx_common.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2015 Solarflare Communications Inc.
*/
#include <linux/etherdevice.h>
#include <linux/pci.h>
#include <linux/module.h>
#include "net_driver.h"
#include "ef10_sriov.h"
#include "efx.h"
#include "nic.h"
#include "mcdi_pcol.h"
static int efx_ef10_evb_port_assign(struct efx_nic *efx, unsigned int port_id,
unsigned int vf_fn)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_EVB_PORT_ASSIGN_IN_LEN);
struct efx_ef10_nic_data *nic_data = efx->nic_data;
MCDI_SET_DWORD(inbuf, EVB_PORT_ASSIGN_IN_PORT_ID, port_id);
MCDI_POPULATE_DWORD_2(inbuf, EVB_PORT_ASSIGN_IN_FUNCTION,
EVB_PORT_ASSIGN_IN_PF, nic_data->pf_index,
EVB_PORT_ASSIGN_IN_VF, vf_fn);
return efx_mcdi_rpc(efx, MC_CMD_EVB_PORT_ASSIGN, inbuf, sizeof(inbuf),
NULL, 0, NULL);
}
static int efx_ef10_vswitch_alloc(struct efx_nic *efx, unsigned int port_id,
unsigned int vswitch_type)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_VSWITCH_ALLOC_IN_LEN);
int rc;
MCDI_SET_DWORD(inbuf, VSWITCH_ALLOC_IN_UPSTREAM_PORT_ID, port_id);
MCDI_SET_DWORD(inbuf, VSWITCH_ALLOC_IN_TYPE, vswitch_type);
MCDI_SET_DWORD(inbuf, VSWITCH_ALLOC_IN_NUM_VLAN_TAGS, 2);
MCDI_POPULATE_DWORD_1(inbuf, VSWITCH_ALLOC_IN_FLAGS,
VSWITCH_ALLOC_IN_FLAG_AUTO_PORT, 0);
/* Quietly try to allocate 2 VLAN tags */
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_VSWITCH_ALLOC, inbuf, sizeof(inbuf),
NULL, 0, NULL);
/* If 2 VLAN tags is too many, revert to trying with 1 VLAN tags */
if (rc == -EPROTO) {
MCDI_SET_DWORD(inbuf, VSWITCH_ALLOC_IN_NUM_VLAN_TAGS, 1);
rc = efx_mcdi_rpc(efx, MC_CMD_VSWITCH_ALLOC, inbuf,
sizeof(inbuf), NULL, 0, NULL);
} else if (rc) {
efx_mcdi_display_error(efx, MC_CMD_VSWITCH_ALLOC,
MC_CMD_VSWITCH_ALLOC_IN_LEN,
NULL, 0, rc);
}
return rc;
}
static int efx_ef10_vswitch_free(struct efx_nic *efx, unsigned int port_id)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_VSWITCH_FREE_IN_LEN);
MCDI_SET_DWORD(inbuf, VSWITCH_FREE_IN_UPSTREAM_PORT_ID, port_id);
return efx_mcdi_rpc(efx, MC_CMD_VSWITCH_FREE, inbuf, sizeof(inbuf),
NULL, 0, NULL);
}
static int efx_ef10_vport_alloc(struct efx_nic *efx,
unsigned int port_id_in,
unsigned int vport_type,
u16 vlan,
unsigned int *port_id_out)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_VPORT_ALLOC_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_VPORT_ALLOC_OUT_LEN);
size_t outlen;
int rc;
EFX_WARN_ON_PARANOID(!port_id_out);
MCDI_SET_DWORD(inbuf, VPORT_ALLOC_IN_UPSTREAM_PORT_ID, port_id_in);
MCDI_SET_DWORD(inbuf, VPORT_ALLOC_IN_TYPE, vport_type);
MCDI_SET_DWORD(inbuf, VPORT_ALLOC_IN_NUM_VLAN_TAGS,
(vlan != EFX_EF10_NO_VLAN));
MCDI_POPULATE_DWORD_1(inbuf, VPORT_ALLOC_IN_FLAGS,
VPORT_ALLOC_IN_FLAG_AUTO_PORT, 0);
if (vlan != EFX_EF10_NO_VLAN)
MCDI_POPULATE_DWORD_1(inbuf, VPORT_ALLOC_IN_VLAN_TAGS,
VPORT_ALLOC_IN_VLAN_TAG_0, vlan);
rc = efx_mcdi_rpc(efx, MC_CMD_VPORT_ALLOC, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < MC_CMD_VPORT_ALLOC_OUT_LEN)
return -EIO;
*port_id_out = MCDI_DWORD(outbuf, VPORT_ALLOC_OUT_VPORT_ID);
return 0;
}
static int efx_ef10_vport_free(struct efx_nic *efx, unsigned int port_id)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_VPORT_FREE_IN_LEN);
MCDI_SET_DWORD(inbuf, VPORT_FREE_IN_VPORT_ID, port_id);
return efx_mcdi_rpc(efx, MC_CMD_VPORT_FREE, inbuf, sizeof(inbuf),
NULL, 0, NULL);
}
static void efx_ef10_sriov_free_vf_vports(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
int i;
if (!nic_data->vf)
return;
for (i = 0; i < efx->vf_count; i++) {
struct ef10_vf *vf = nic_data->vf + i;
/* If VF is assigned, do not free the vport */
if (vf->pci_dev && pci_is_dev_assigned(vf->pci_dev))
continue;
if (vf->vport_assigned) {
efx_ef10_evb_port_assign(efx, EVB_PORT_ID_NULL, i);
vf->vport_assigned = 0;
}
if (!is_zero_ether_addr(vf->mac)) {
efx_ef10_vport_del_mac(efx, vf->vport_id, vf->mac);
eth_zero_addr(vf->mac);
}
if (vf->vport_id) {
efx_ef10_vport_free(efx, vf->vport_id);
vf->vport_id = 0;
}
vf->efx = NULL;
}
}
static void efx_ef10_sriov_free_vf_vswitching(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
efx_ef10_sriov_free_vf_vports(efx);
kfree(nic_data->vf);
nic_data->vf = NULL;
}
static int efx_ef10_sriov_assign_vf_vport(struct efx_nic *efx,
unsigned int vf_i)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
struct ef10_vf *vf = nic_data->vf + vf_i;
int rc;
if (WARN_ON_ONCE(!nic_data->vf))
return -EOPNOTSUPP;
rc = efx_ef10_vport_alloc(efx, EVB_PORT_ID_ASSIGNED,
MC_CMD_VPORT_ALLOC_IN_VPORT_TYPE_NORMAL,
vf->vlan, &vf->vport_id);
if (rc)
return rc;
rc = efx_ef10_vport_add_mac(efx, vf->vport_id, vf->mac);
if (rc) {
eth_zero_addr(vf->mac);
return rc;
}
rc = efx_ef10_evb_port_assign(efx, vf->vport_id, vf_i);
if (rc)
return rc;
vf->vport_assigned = 1;
return 0;
}
static int efx_ef10_sriov_alloc_vf_vswitching(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
unsigned int i;
int rc;
nic_data->vf = kcalloc(efx->vf_count, sizeof(struct ef10_vf),
GFP_KERNEL);
if (!nic_data->vf)
return -ENOMEM;
for (i = 0; i < efx->vf_count; i++) {
eth_random_addr(nic_data->vf[i].mac);
nic_data->vf[i].efx = NULL;
nic_data->vf[i].vlan = EFX_EF10_NO_VLAN;
rc = efx_ef10_sriov_assign_vf_vport(efx, i);
if (rc)
goto fail;
}
return 0;
fail:
efx_ef10_sriov_free_vf_vswitching(efx);
return rc;
}
static int efx_ef10_sriov_restore_vf_vswitching(struct efx_nic *efx)
{
unsigned int i;
int rc;
for (i = 0; i < efx->vf_count; i++) {
rc = efx_ef10_sriov_assign_vf_vport(efx, i);
if (rc)
goto fail;
}
return 0;
fail:
efx_ef10_sriov_free_vf_vswitching(efx);
return rc;
}
static int efx_ef10_vadaptor_alloc_set_features(struct efx_nic *efx)
{
u32 port_flags;
int rc;
rc = efx_ef10_vadaptor_alloc(efx, efx->vport_id);
if (rc)
goto fail_vadaptor_alloc;
rc = efx_ef10_vadaptor_query(efx, efx->vport_id,
&port_flags, NULL, NULL);
if (rc)
goto fail_vadaptor_query;
if (port_flags &
(1 << MC_CMD_VPORT_ALLOC_IN_FLAG_VLAN_RESTRICT_LBN))
efx->fixed_features |= NETIF_F_HW_VLAN_CTAG_FILTER;
else
efx->fixed_features &= ~NETIF_F_HW_VLAN_CTAG_FILTER;
return 0;
fail_vadaptor_query:
efx_ef10_vadaptor_free(efx, EVB_PORT_ID_ASSIGNED);
fail_vadaptor_alloc:
return rc;
}
/* On top of the default firmware vswitch setup, create a VEB vswitch and
* expansion vport for use by this function.
*/
int efx_ef10_vswitching_probe_pf(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
struct net_device *net_dev = efx->net_dev;
int rc;
if (pci_sriov_get_totalvfs(efx->pci_dev) <= 0) {
/* vswitch not needed as we have no VFs */
efx_ef10_vadaptor_alloc_set_features(efx);
return 0;
}
rc = efx_ef10_vswitch_alloc(efx, EVB_PORT_ID_ASSIGNED,
MC_CMD_VSWITCH_ALLOC_IN_VSWITCH_TYPE_VEB);
if (rc)
goto fail1;
rc = efx_ef10_vport_alloc(efx, EVB_PORT_ID_ASSIGNED,
MC_CMD_VPORT_ALLOC_IN_VPORT_TYPE_NORMAL,
EFX_EF10_NO_VLAN, &efx->vport_id);
if (rc)
goto fail2;
rc = efx_ef10_vport_add_mac(efx, efx->vport_id, net_dev->dev_addr);
if (rc)
goto fail3;
ether_addr_copy(nic_data->vport_mac, net_dev->dev_addr);
rc = efx_ef10_vadaptor_alloc_set_features(efx);
if (rc)
goto fail4;
return 0;
fail4:
efx_ef10_vport_del_mac(efx, efx->vport_id, nic_data->vport_mac);
eth_zero_addr(nic_data->vport_mac);
fail3:
efx_ef10_vport_free(efx, efx->vport_id);
efx->vport_id = EVB_PORT_ID_ASSIGNED;
fail2:
efx_ef10_vswitch_free(efx, EVB_PORT_ID_ASSIGNED);
fail1:
return rc;
}
int efx_ef10_vswitching_probe_vf(struct efx_nic *efx)
{
return efx_ef10_vadaptor_alloc_set_features(efx);
}
int efx_ef10_vswitching_restore_pf(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
int rc;
if (!nic_data->must_probe_vswitching)
return 0;
rc = efx_ef10_vswitching_probe_pf(efx);
if (rc)
goto fail;
rc = efx_ef10_sriov_restore_vf_vswitching(efx);
if (rc)
goto fail;
nic_data->must_probe_vswitching = false;
fail:
return rc;
}
int efx_ef10_vswitching_restore_vf(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
int rc;
if (!nic_data->must_probe_vswitching)
return 0;
rc = efx_ef10_vadaptor_free(efx, EVB_PORT_ID_ASSIGNED);
if (rc)
return rc;
nic_data->must_probe_vswitching = false;
return 0;
}
void efx_ef10_vswitching_remove_pf(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
efx_ef10_sriov_free_vf_vswitching(efx);
efx_ef10_vadaptor_free(efx, efx->vport_id);
if (efx->vport_id == EVB_PORT_ID_ASSIGNED)
return; /* No vswitch was ever created */
if (!is_zero_ether_addr(nic_data->vport_mac)) {
efx_ef10_vport_del_mac(efx, efx->vport_id,
efx->net_dev->dev_addr);
eth_zero_addr(nic_data->vport_mac);
}
efx_ef10_vport_free(efx, efx->vport_id);
efx->vport_id = EVB_PORT_ID_ASSIGNED;
/* Only free the vswitch if no VFs are assigned */
if (!pci_vfs_assigned(efx->pci_dev))
efx_ef10_vswitch_free(efx, efx->vport_id);
}
void efx_ef10_vswitching_remove_vf(struct efx_nic *efx)
{
efx_ef10_vadaptor_free(efx, EVB_PORT_ID_ASSIGNED);
}
static int efx_ef10_pci_sriov_enable(struct efx_nic *efx, int num_vfs)
{
int rc = 0;
struct pci_dev *dev = efx->pci_dev;
efx->vf_count = num_vfs;
rc = efx_ef10_sriov_alloc_vf_vswitching(efx);
if (rc)
goto fail1;
rc = pci_enable_sriov(dev, num_vfs);
if (rc)
goto fail2;
return 0;
fail2:
efx_ef10_sriov_free_vf_vswitching(efx);
fail1:
efx->vf_count = 0;
netif_err(efx, probe, efx->net_dev,
"Failed to enable SRIOV VFs\n");
return rc;
}
/* Disable SRIOV and remove VFs
* If some VFs are attached to a guest (using Xen, only) nothing is
* done if force=false, and vports are freed if force=true (for the non
* attachedc ones, only) but SRIOV is not disabled and VFs are not
* removed in either case.
*/
static int efx_ef10_pci_sriov_disable(struct efx_nic *efx, bool force)
{
struct pci_dev *dev = efx->pci_dev;
struct efx_ef10_nic_data *nic_data = efx->nic_data;
unsigned int vfs_assigned = pci_vfs_assigned(dev);
int i, rc = 0;
if (vfs_assigned && !force) {
netif_info(efx, drv, efx->net_dev, "VFs are assigned to guests; "
"please detach them before disabling SR-IOV\n");
return -EBUSY;
}
if (!vfs_assigned) {
for (i = 0; i < efx->vf_count; i++)
nic_data->vf[i].pci_dev = NULL;
pci_disable_sriov(dev);
} else {
rc = -EBUSY;
}
efx_ef10_sriov_free_vf_vswitching(efx);
efx->vf_count = 0;
return rc;
}
int efx_ef10_sriov_configure(struct efx_nic *efx, int num_vfs)
{
if (num_vfs == 0)
return efx_ef10_pci_sriov_disable(efx, false);
else
return efx_ef10_pci_sriov_enable(efx, num_vfs);
}
int efx_ef10_sriov_init(struct efx_nic *efx)
{
return 0;
}
void efx_ef10_sriov_fini(struct efx_nic *efx)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
int rc;
if (!nic_data->vf) {
/* Remove any un-assigned orphaned VFs. This can happen if the PF driver
* was unloaded while any VF was assigned to a guest (using Xen, only).
*/
if (pci_num_vf(efx->pci_dev) && !pci_vfs_assigned(efx->pci_dev))
pci_disable_sriov(efx->pci_dev);
return;
}
/* Disable SRIOV and remove any VFs in the host */
rc = efx_ef10_pci_sriov_disable(efx, true);
if (rc)
netif_dbg(efx, drv, efx->net_dev,
"Disabling SRIOV was not successful rc=%d\n", rc);
else
netif_dbg(efx, drv, efx->net_dev, "SRIOV disabled\n");
}
static int efx_ef10_vport_del_vf_mac(struct efx_nic *efx, unsigned int port_id,
u8 *mac)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_VPORT_DEL_MAC_ADDRESS_IN_LEN);
MCDI_DECLARE_BUF_ERR(outbuf);
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, VPORT_DEL_MAC_ADDRESS_IN_VPORT_ID, port_id);
ether_addr_copy(MCDI_PTR(inbuf, VPORT_DEL_MAC_ADDRESS_IN_MACADDR), mac);
rc = efx_mcdi_rpc(efx, MC_CMD_VPORT_DEL_MAC_ADDRESS, inbuf,
sizeof(inbuf), outbuf, sizeof(outbuf), &outlen);
return rc;
}
int efx_ef10_sriov_set_vf_mac(struct efx_nic *efx, int vf_i, const u8 *mac)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
struct ef10_vf *vf;
int rc;
if (!nic_data->vf)
return -EOPNOTSUPP;
if (vf_i >= efx->vf_count)
return -EINVAL;
vf = nic_data->vf + vf_i;
if (vf->efx) {
efx_device_detach_sync(vf->efx);
efx_net_stop(vf->efx->net_dev);
vf->efx->type->filter_table_remove(vf->efx);
rc = efx_ef10_vadaptor_free(vf->efx, EVB_PORT_ID_ASSIGNED);
if (rc)
return rc;
}
rc = efx_ef10_evb_port_assign(efx, EVB_PORT_ID_NULL, vf_i);
if (rc)
return rc;
if (!is_zero_ether_addr(vf->mac)) {
rc = efx_ef10_vport_del_vf_mac(efx, vf->vport_id, vf->mac);
if (rc)
return rc;
}
if (!is_zero_ether_addr(mac)) {
rc = efx_ef10_vport_add_mac(efx, vf->vport_id, mac);
if (rc)
goto fail;
if (vf->efx)
eth_hw_addr_set(vf->efx->net_dev, mac);
}
ether_addr_copy(vf->mac, mac);
rc = efx_ef10_evb_port_assign(efx, vf->vport_id, vf_i);
if (rc)
goto fail;
if (vf->efx) {
/* VF cannot use the vport_id that the PF created */
rc = efx_ef10_vadaptor_alloc(vf->efx, EVB_PORT_ID_ASSIGNED);
if (rc)
return rc;
vf->efx->type->filter_table_probe(vf->efx);
efx_net_open(vf->efx->net_dev);
efx_device_attach_if_not_resetting(vf->efx);
}
return 0;
fail:
eth_zero_addr(vf->mac);
return rc;
}
int efx_ef10_sriov_set_vf_vlan(struct efx_nic *efx, int vf_i, u16 vlan,
u8 qos)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
struct ef10_vf *vf;
u16 new_vlan;
int rc = 0, rc2 = 0;
if (vf_i >= efx->vf_count)
return -EINVAL;
if (qos != 0)
return -EINVAL;
vf = nic_data->vf + vf_i;
new_vlan = (vlan == 0) ? EFX_EF10_NO_VLAN : vlan;
if (new_vlan == vf->vlan)
return 0;
if (vf->efx) {
efx_device_detach_sync(vf->efx);
efx_net_stop(vf->efx->net_dev);
mutex_lock(&vf->efx->mac_lock);
vf->efx->type->filter_table_remove(vf->efx);
rc = efx_ef10_vadaptor_free(vf->efx, EVB_PORT_ID_ASSIGNED);
if (rc)
goto restore_filters;
}
if (vf->vport_assigned) {
rc = efx_ef10_evb_port_assign(efx, EVB_PORT_ID_NULL, vf_i);
if (rc) {
netif_warn(efx, drv, efx->net_dev,
"Failed to change vlan on VF %d.\n", vf_i);
netif_warn(efx, drv, efx->net_dev,
"This is likely because the VF is bound to a driver in a VM.\n");
netif_warn(efx, drv, efx->net_dev,
"Please unload the driver in the VM.\n");
goto restore_vadaptor;
}
vf->vport_assigned = 0;
}
if (!is_zero_ether_addr(vf->mac)) {
rc = efx_ef10_vport_del_mac(efx, vf->vport_id, vf->mac);
if (rc)
goto restore_evb_port;
}
if (vf->vport_id) {
rc = efx_ef10_vport_free(efx, vf->vport_id);
if (rc)
goto restore_mac;
vf->vport_id = 0;
}
/* Do the actual vlan change */
vf->vlan = new_vlan;
/* Restore everything in reverse order */
rc = efx_ef10_vport_alloc(efx, EVB_PORT_ID_ASSIGNED,
MC_CMD_VPORT_ALLOC_IN_VPORT_TYPE_NORMAL,
vf->vlan, &vf->vport_id);
if (rc)
goto reset_nic_up_write;
restore_mac:
if (!is_zero_ether_addr(vf->mac)) {
rc2 = efx_ef10_vport_add_mac(efx, vf->vport_id, vf->mac);
if (rc2) {
eth_zero_addr(vf->mac);
goto reset_nic_up_write;
}
}
restore_evb_port:
rc2 = efx_ef10_evb_port_assign(efx, vf->vport_id, vf_i);
if (rc2)
goto reset_nic_up_write;
else
vf->vport_assigned = 1;
restore_vadaptor:
if (vf->efx) {
rc2 = efx_ef10_vadaptor_alloc(vf->efx, EVB_PORT_ID_ASSIGNED);
if (rc2)
goto reset_nic_up_write;
}
restore_filters:
if (vf->efx) {
rc2 = vf->efx->type->filter_table_probe(vf->efx);
if (rc2)
goto reset_nic_up_write;
mutex_unlock(&vf->efx->mac_lock);
rc2 = efx_net_open(vf->efx->net_dev);
if (rc2)
goto reset_nic;
efx_device_attach_if_not_resetting(vf->efx);
}
return rc;
reset_nic_up_write:
if (vf->efx)
mutex_unlock(&vf->efx->mac_lock);
reset_nic:
if (vf->efx) {
netif_err(efx, drv, efx->net_dev,
"Failed to restore VF - scheduling reset.\n");
efx_schedule_reset(vf->efx, RESET_TYPE_DATAPATH);
} else {
netif_err(efx, drv, efx->net_dev,
"Failed to restore the VF and cannot reset the VF "
"- VF is not functional.\n");
netif_err(efx, drv, efx->net_dev,
"Please reload the driver attached to the VF.\n");
}
return rc ? rc : rc2;
}
static int efx_ef10_sriov_set_privilege_mask(struct efx_nic *efx, int vf_i,
u32 mask, u32 value)
{
MCDI_DECLARE_BUF(pm_outbuf, MC_CMD_PRIVILEGE_MASK_OUT_LEN);
MCDI_DECLARE_BUF(pm_inbuf, MC_CMD_PRIVILEGE_MASK_IN_LEN);
struct efx_ef10_nic_data *nic_data = efx->nic_data;
u32 old_mask, new_mask;
size_t outlen;
int rc;
EFX_WARN_ON_PARANOID((value & ~mask) != 0);
/* Get privilege mask */
MCDI_POPULATE_DWORD_2(pm_inbuf, PRIVILEGE_MASK_IN_FUNCTION,
PRIVILEGE_MASK_IN_FUNCTION_PF, nic_data->pf_index,
PRIVILEGE_MASK_IN_FUNCTION_VF, vf_i);
rc = efx_mcdi_rpc(efx, MC_CMD_PRIVILEGE_MASK,
pm_inbuf, sizeof(pm_inbuf),
pm_outbuf, sizeof(pm_outbuf), &outlen);
if (rc != 0)
return rc;
if (outlen != MC_CMD_PRIVILEGE_MASK_OUT_LEN)
return -EIO;
old_mask = MCDI_DWORD(pm_outbuf, PRIVILEGE_MASK_OUT_OLD_MASK);
new_mask = old_mask & ~mask;
new_mask |= value;
if (new_mask == old_mask)
return 0;
new_mask |= MC_CMD_PRIVILEGE_MASK_IN_DO_CHANGE;
/* Set privilege mask */
MCDI_SET_DWORD(pm_inbuf, PRIVILEGE_MASK_IN_NEW_MASK, new_mask);
rc = efx_mcdi_rpc(efx, MC_CMD_PRIVILEGE_MASK,
pm_inbuf, sizeof(pm_inbuf),
pm_outbuf, sizeof(pm_outbuf), &outlen);
if (rc != 0)
return rc;
if (outlen != MC_CMD_PRIVILEGE_MASK_OUT_LEN)
return -EIO;
return 0;
}
int efx_ef10_sriov_set_vf_spoofchk(struct efx_nic *efx, int vf_i, bool spoofchk)
{
struct efx_ef10_nic_data *nic_data = efx->nic_data;
/* Can't enable spoofchk if firmware doesn't support it. */
if (!(nic_data->datapath_caps &
BIT(MC_CMD_GET_CAPABILITIES_OUT_TX_MAC_SECURITY_FILTERING_LBN)) &&
spoofchk)
return -EOPNOTSUPP;
return efx_ef10_sriov_set_privilege_mask(efx, vf_i,
MC_CMD_PRIVILEGE_MASK_IN_GRP_MAC_SPOOFING_TX,
spoofchk ? 0 : MC_CMD_PRIVILEGE_MASK_IN_GRP_MAC_SPOOFING_TX);
}
int efx_ef10_sriov_set_vf_link_state(struct efx_nic *efx, int vf_i,
int link_state)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_LINK_STATE_MODE_IN_LEN);
struct efx_ef10_nic_data *nic_data = efx->nic_data;
BUILD_BUG_ON(IFLA_VF_LINK_STATE_AUTO !=
MC_CMD_LINK_STATE_MODE_IN_LINK_STATE_AUTO);
BUILD_BUG_ON(IFLA_VF_LINK_STATE_ENABLE !=
MC_CMD_LINK_STATE_MODE_IN_LINK_STATE_UP);
BUILD_BUG_ON(IFLA_VF_LINK_STATE_DISABLE !=
MC_CMD_LINK_STATE_MODE_IN_LINK_STATE_DOWN);
MCDI_POPULATE_DWORD_2(inbuf, LINK_STATE_MODE_IN_FUNCTION,
LINK_STATE_MODE_IN_FUNCTION_PF,
nic_data->pf_index,
LINK_STATE_MODE_IN_FUNCTION_VF, vf_i);
MCDI_SET_DWORD(inbuf, LINK_STATE_MODE_IN_NEW_MODE, link_state);
return efx_mcdi_rpc(efx, MC_CMD_LINK_STATE_MODE, inbuf, sizeof(inbuf),
NULL, 0, NULL); /* don't care what old mode was */
}
int efx_ef10_sriov_get_vf_config(struct efx_nic *efx, int vf_i,
struct ifla_vf_info *ivf)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_LINK_STATE_MODE_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_LINK_STATE_MODE_OUT_LEN);
struct efx_ef10_nic_data *nic_data = efx->nic_data;
struct ef10_vf *vf;
size_t outlen;
int rc;
if (vf_i >= efx->vf_count)
return -EINVAL;
if (!nic_data->vf)
return -EOPNOTSUPP;
vf = nic_data->vf + vf_i;
ivf->vf = vf_i;
ivf->min_tx_rate = 0;
ivf->max_tx_rate = 0;
ether_addr_copy(ivf->mac, vf->mac);
ivf->vlan = (vf->vlan == EFX_EF10_NO_VLAN) ? 0 : vf->vlan;
ivf->qos = 0;
MCDI_POPULATE_DWORD_2(inbuf, LINK_STATE_MODE_IN_FUNCTION,
LINK_STATE_MODE_IN_FUNCTION_PF,
nic_data->pf_index,
LINK_STATE_MODE_IN_FUNCTION_VF, vf_i);
MCDI_SET_DWORD(inbuf, LINK_STATE_MODE_IN_NEW_MODE,
MC_CMD_LINK_STATE_MODE_IN_DO_NOT_CHANGE);
rc = efx_mcdi_rpc(efx, MC_CMD_LINK_STATE_MODE, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < MC_CMD_LINK_STATE_MODE_OUT_LEN)
return -EIO;
ivf->linkstate = MCDI_DWORD(outbuf, LINK_STATE_MODE_OUT_OLD_MODE);
return 0;
}
|
linux-master
|
drivers/net/ethernet/sfc/ef10_sriov.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2005-2006 Fen Systems Ltd.
* Copyright 2005-2013 Solarflare Communications Inc.
*/
#include <linux/pci.h>
#include <linux/tcp.h>
#include <linux/ip.h>
#include <linux/in.h>
#include <linux/ipv6.h>
#include <linux/slab.h>
#include <net/ipv6.h>
#include <linux/if_ether.h>
#include <linux/highmem.h>
#include <linux/cache.h>
#include "net_driver.h"
#include "efx.h"
#include "io.h"
#include "nic.h"
#include "tx.h"
#include "tx_common.h"
#include "workarounds.h"
#include "ef10_regs.h"
#ifdef EFX_USE_PIO
#define EFX_PIOBUF_SIZE_DEF ALIGN(256, L1_CACHE_BYTES)
unsigned int efx_piobuf_size __read_mostly = EFX_PIOBUF_SIZE_DEF;
#endif /* EFX_USE_PIO */
static inline u8 *efx_tx_get_copy_buffer(struct efx_tx_queue *tx_queue,
struct efx_tx_buffer *buffer)
{
unsigned int index = efx_tx_queue_get_insert_index(tx_queue);
struct efx_buffer *page_buf =
&tx_queue->cb_page[index >> (PAGE_SHIFT - EFX_TX_CB_ORDER)];
unsigned int offset =
((index << EFX_TX_CB_ORDER) + NET_IP_ALIGN) & (PAGE_SIZE - 1);
if (unlikely(!page_buf->addr) &&
efx_nic_alloc_buffer(tx_queue->efx, page_buf, PAGE_SIZE,
GFP_ATOMIC))
return NULL;
buffer->dma_addr = page_buf->dma_addr + offset;
buffer->unmap_len = 0;
return (u8 *)page_buf->addr + offset;
}
u8 *efx_tx_get_copy_buffer_limited(struct efx_tx_queue *tx_queue,
struct efx_tx_buffer *buffer, size_t len)
{
if (len > EFX_TX_CB_SIZE)
return NULL;
return efx_tx_get_copy_buffer(tx_queue, buffer);
}
static void efx_tx_maybe_stop_queue(struct efx_tx_queue *txq1)
{
/* We need to consider all queues that the net core sees as one */
struct efx_nic *efx = txq1->efx;
struct efx_tx_queue *txq2;
unsigned int fill_level;
fill_level = efx_channel_tx_old_fill_level(txq1->channel);
if (likely(fill_level < efx->txq_stop_thresh))
return;
/* We used the stale old_read_count above, which gives us a
* pessimistic estimate of the fill level (which may even
* validly be >= efx->txq_entries). Now try again using
* read_count (more likely to be a cache miss).
*
* If we read read_count and then conditionally stop the
* queue, it is possible for the completion path to race with
* us and complete all outstanding descriptors in the middle,
* after which there will be no more completions to wake it.
* Therefore we stop the queue first, then read read_count
* (with a memory barrier to ensure the ordering), then
* restart the queue if the fill level turns out to be low
* enough.
*/
netif_tx_stop_queue(txq1->core_txq);
smp_mb();
efx_for_each_channel_tx_queue(txq2, txq1->channel)
txq2->old_read_count = READ_ONCE(txq2->read_count);
fill_level = efx_channel_tx_old_fill_level(txq1->channel);
EFX_WARN_ON_ONCE_PARANOID(fill_level >= efx->txq_entries);
if (likely(fill_level < efx->txq_stop_thresh)) {
smp_mb();
if (likely(!efx->loopback_selftest))
netif_tx_start_queue(txq1->core_txq);
}
}
static int efx_enqueue_skb_copy(struct efx_tx_queue *tx_queue,
struct sk_buff *skb)
{
unsigned int copy_len = skb->len;
struct efx_tx_buffer *buffer;
u8 *copy_buffer;
int rc;
EFX_WARN_ON_ONCE_PARANOID(copy_len > EFX_TX_CB_SIZE);
buffer = efx_tx_queue_get_insert_buffer(tx_queue);
copy_buffer = efx_tx_get_copy_buffer(tx_queue, buffer);
if (unlikely(!copy_buffer))
return -ENOMEM;
rc = skb_copy_bits(skb, 0, copy_buffer, copy_len);
EFX_WARN_ON_PARANOID(rc);
buffer->len = copy_len;
buffer->skb = skb;
buffer->flags = EFX_TX_BUF_SKB;
++tx_queue->insert_count;
return rc;
}
#ifdef EFX_USE_PIO
struct efx_short_copy_buffer {
int used;
u8 buf[L1_CACHE_BYTES];
};
/* Copy to PIO, respecting that writes to PIO buffers must be dword aligned.
* Advances piobuf pointer. Leaves additional data in the copy buffer.
*/
static void efx_memcpy_toio_aligned(struct efx_nic *efx, u8 __iomem **piobuf,
u8 *data, int len,
struct efx_short_copy_buffer *copy_buf)
{
int block_len = len & ~(sizeof(copy_buf->buf) - 1);
__iowrite64_copy(*piobuf, data, block_len >> 3);
*piobuf += block_len;
len -= block_len;
if (len) {
data += block_len;
BUG_ON(copy_buf->used);
BUG_ON(len > sizeof(copy_buf->buf));
memcpy(copy_buf->buf, data, len);
copy_buf->used = len;
}
}
/* Copy to PIO, respecting dword alignment, popping data from copy buffer first.
* Advances piobuf pointer. Leaves additional data in the copy buffer.
*/
static void efx_memcpy_toio_aligned_cb(struct efx_nic *efx, u8 __iomem **piobuf,
u8 *data, int len,
struct efx_short_copy_buffer *copy_buf)
{
if (copy_buf->used) {
/* if the copy buffer is partially full, fill it up and write */
int copy_to_buf =
min_t(int, sizeof(copy_buf->buf) - copy_buf->used, len);
memcpy(copy_buf->buf + copy_buf->used, data, copy_to_buf);
copy_buf->used += copy_to_buf;
/* if we didn't fill it up then we're done for now */
if (copy_buf->used < sizeof(copy_buf->buf))
return;
__iowrite64_copy(*piobuf, copy_buf->buf,
sizeof(copy_buf->buf) >> 3);
*piobuf += sizeof(copy_buf->buf);
data += copy_to_buf;
len -= copy_to_buf;
copy_buf->used = 0;
}
efx_memcpy_toio_aligned(efx, piobuf, data, len, copy_buf);
}
static void efx_flush_copy_buffer(struct efx_nic *efx, u8 __iomem *piobuf,
struct efx_short_copy_buffer *copy_buf)
{
/* if there's anything in it, write the whole buffer, including junk */
if (copy_buf->used)
__iowrite64_copy(piobuf, copy_buf->buf,
sizeof(copy_buf->buf) >> 3);
}
/* Traverse skb structure and copy fragments in to PIO buffer.
* Advances piobuf pointer.
*/
static void efx_skb_copy_bits_to_pio(struct efx_nic *efx, struct sk_buff *skb,
u8 __iomem **piobuf,
struct efx_short_copy_buffer *copy_buf)
{
int i;
efx_memcpy_toio_aligned(efx, piobuf, skb->data, skb_headlen(skb),
copy_buf);
for (i = 0; i < skb_shinfo(skb)->nr_frags; ++i) {
skb_frag_t *f = &skb_shinfo(skb)->frags[i];
u8 *vaddr;
vaddr = kmap_local_page(skb_frag_page(f));
efx_memcpy_toio_aligned_cb(efx, piobuf, vaddr + skb_frag_off(f),
skb_frag_size(f), copy_buf);
kunmap_local(vaddr);
}
EFX_WARN_ON_ONCE_PARANOID(skb_shinfo(skb)->frag_list);
}
static int efx_enqueue_skb_pio(struct efx_tx_queue *tx_queue,
struct sk_buff *skb)
{
struct efx_tx_buffer *buffer =
efx_tx_queue_get_insert_buffer(tx_queue);
u8 __iomem *piobuf = tx_queue->piobuf;
/* Copy to PIO buffer. Ensure the writes are padded to the end
* of a cache line, as this is required for write-combining to be
* effective on at least x86.
*/
if (skb_shinfo(skb)->nr_frags) {
/* The size of the copy buffer will ensure all writes
* are the size of a cache line.
*/
struct efx_short_copy_buffer copy_buf;
copy_buf.used = 0;
efx_skb_copy_bits_to_pio(tx_queue->efx, skb,
&piobuf, ©_buf);
efx_flush_copy_buffer(tx_queue->efx, piobuf, ©_buf);
} else {
/* Pad the write to the size of a cache line.
* We can do this because we know the skb_shared_info struct is
* after the source, and the destination buffer is big enough.
*/
BUILD_BUG_ON(L1_CACHE_BYTES >
SKB_DATA_ALIGN(sizeof(struct skb_shared_info)));
__iowrite64_copy(tx_queue->piobuf, skb->data,
ALIGN(skb->len, L1_CACHE_BYTES) >> 3);
}
buffer->skb = skb;
buffer->flags = EFX_TX_BUF_SKB | EFX_TX_BUF_OPTION;
EFX_POPULATE_QWORD_5(buffer->option,
ESF_DZ_TX_DESC_IS_OPT, 1,
ESF_DZ_TX_OPTION_TYPE, ESE_DZ_TX_OPTION_DESC_PIO,
ESF_DZ_TX_PIO_CONT, 0,
ESF_DZ_TX_PIO_BYTE_CNT, skb->len,
ESF_DZ_TX_PIO_BUF_ADDR,
tx_queue->piobuf_offset);
++tx_queue->insert_count;
return 0;
}
/* Decide whether we can use TX PIO, ie. write packet data directly into
* a buffer on the device. This can reduce latency at the expense of
* throughput, so we only do this if both hardware and software TX rings
* are empty, including all queues for the channel. This also ensures that
* only one packet at a time can be using the PIO buffer. If the xmit_more
* flag is set then we don't use this - there'll be another packet along
* shortly and we want to hold off the doorbell.
*/
static bool efx_tx_may_pio(struct efx_tx_queue *tx_queue)
{
struct efx_channel *channel = tx_queue->channel;
if (!tx_queue->piobuf)
return false;
EFX_WARN_ON_ONCE_PARANOID(!channel->efx->type->option_descriptors);
efx_for_each_channel_tx_queue(tx_queue, channel)
if (!efx_nic_tx_is_empty(tx_queue, tx_queue->packet_write_count))
return false;
return true;
}
#endif /* EFX_USE_PIO */
/* Send any pending traffic for a channel. xmit_more is shared across all
* queues for a channel, so we must check all of them.
*/
static void efx_tx_send_pending(struct efx_channel *channel)
{
struct efx_tx_queue *q;
efx_for_each_channel_tx_queue(q, channel) {
if (q->xmit_pending)
efx_nic_push_buffers(q);
}
}
/*
* Add a socket buffer to a TX queue
*
* This maps all fragments of a socket buffer for DMA and adds them to
* the TX queue. The queue's insert pointer will be incremented by
* the number of fragments in the socket buffer.
*
* If any DMA mapping fails, any mapped fragments will be unmapped,
* the queue's insert pointer will be restored to its original value.
*
* This function is split out from efx_hard_start_xmit to allow the
* loopback test to direct packets via specific TX queues.
*
* Returns NETDEV_TX_OK.
* You must hold netif_tx_lock() to call this function.
*/
netdev_tx_t __efx_enqueue_skb(struct efx_tx_queue *tx_queue, struct sk_buff *skb)
{
unsigned int old_insert_count = tx_queue->insert_count;
bool xmit_more = netdev_xmit_more();
bool data_mapped = false;
unsigned int segments;
unsigned int skb_len;
int rc;
skb_len = skb->len;
segments = skb_is_gso(skb) ? skb_shinfo(skb)->gso_segs : 0;
if (segments == 1)
segments = 0; /* Don't use TSO for a single segment. */
/* Handle TSO first - it's *possible* (although unlikely) that we might
* be passed a packet to segment that's smaller than the copybreak/PIO
* size limit.
*/
if (segments) {
switch (tx_queue->tso_version) {
case 1:
rc = efx_enqueue_skb_tso(tx_queue, skb, &data_mapped);
break;
case 2:
rc = efx_ef10_tx_tso_desc(tx_queue, skb, &data_mapped);
break;
case 0: /* No TSO on this queue, SW fallback needed */
default:
rc = -EINVAL;
break;
}
if (rc == -EINVAL) {
rc = efx_tx_tso_fallback(tx_queue, skb);
tx_queue->tso_fallbacks++;
if (rc == 0)
return 0;
}
if (rc)
goto err;
#ifdef EFX_USE_PIO
} else if (skb_len <= efx_piobuf_size && !xmit_more &&
efx_tx_may_pio(tx_queue)) {
/* Use PIO for short packets with an empty queue. */
if (efx_enqueue_skb_pio(tx_queue, skb))
goto err;
tx_queue->pio_packets++;
data_mapped = true;
#endif
} else if (skb->data_len && skb_len <= EFX_TX_CB_SIZE) {
/* Pad short packets or coalesce short fragmented packets. */
if (efx_enqueue_skb_copy(tx_queue, skb))
goto err;
tx_queue->cb_packets++;
data_mapped = true;
}
/* Map for DMA and create descriptors if we haven't done so already. */
if (!data_mapped && (efx_tx_map_data(tx_queue, skb, segments)))
goto err;
efx_tx_maybe_stop_queue(tx_queue);
tx_queue->xmit_pending = true;
/* Pass off to hardware */
if (__netdev_tx_sent_queue(tx_queue->core_txq, skb_len, xmit_more))
efx_tx_send_pending(tx_queue->channel);
if (segments) {
tx_queue->tso_bursts++;
tx_queue->tso_packets += segments;
tx_queue->tx_packets += segments;
} else {
tx_queue->tx_packets++;
}
return NETDEV_TX_OK;
err:
efx_enqueue_unwind(tx_queue, old_insert_count);
dev_kfree_skb_any(skb);
/* If we're not expecting another transmit and we had something to push
* on this queue or a partner queue then we need to push here to get the
* previous packets out.
*/
if (!xmit_more)
efx_tx_send_pending(tx_queue->channel);
return NETDEV_TX_OK;
}
/* Transmit a packet from an XDP buffer
*
* Returns number of packets sent on success, error code otherwise.
* Runs in NAPI context, either in our poll (for XDP TX) or a different NIC
* (for XDP redirect).
*/
int efx_xdp_tx_buffers(struct efx_nic *efx, int n, struct xdp_frame **xdpfs,
bool flush)
{
struct efx_tx_buffer *tx_buffer;
struct efx_tx_queue *tx_queue;
struct xdp_frame *xdpf;
dma_addr_t dma_addr;
unsigned int len;
int space;
int cpu;
int i = 0;
if (unlikely(n && !xdpfs))
return -EINVAL;
if (unlikely(!n))
return 0;
cpu = raw_smp_processor_id();
if (unlikely(cpu >= efx->xdp_tx_queue_count))
return -EINVAL;
tx_queue = efx->xdp_tx_queues[cpu];
if (unlikely(!tx_queue))
return -EINVAL;
if (!tx_queue->initialised)
return -EINVAL;
if (efx->xdp_txq_queues_mode != EFX_XDP_TX_QUEUES_DEDICATED)
HARD_TX_LOCK(efx->net_dev, tx_queue->core_txq, cpu);
/* If we're borrowing net stack queues we have to handle stop-restart
* or we might block the queue and it will be considered as frozen
*/
if (efx->xdp_txq_queues_mode == EFX_XDP_TX_QUEUES_BORROWED) {
if (netif_tx_queue_stopped(tx_queue->core_txq))
goto unlock;
efx_tx_maybe_stop_queue(tx_queue);
}
/* Check for available space. We should never need multiple
* descriptors per frame.
*/
space = efx->txq_entries +
tx_queue->read_count - tx_queue->insert_count;
for (i = 0; i < n; i++) {
xdpf = xdpfs[i];
if (i >= space)
break;
/* We'll want a descriptor for this tx. */
prefetchw(__efx_tx_queue_get_insert_buffer(tx_queue));
len = xdpf->len;
/* Map for DMA. */
dma_addr = dma_map_single(&efx->pci_dev->dev,
xdpf->data, len,
DMA_TO_DEVICE);
if (dma_mapping_error(&efx->pci_dev->dev, dma_addr))
break;
/* Create descriptor and set up for unmapping DMA. */
tx_buffer = efx_tx_map_chunk(tx_queue, dma_addr, len);
tx_buffer->xdpf = xdpf;
tx_buffer->flags = EFX_TX_BUF_XDP |
EFX_TX_BUF_MAP_SINGLE;
tx_buffer->dma_offset = 0;
tx_buffer->unmap_len = len;
tx_queue->tx_packets++;
}
/* Pass mapped frames to hardware. */
if (flush && i > 0)
efx_nic_push_buffers(tx_queue);
unlock:
if (efx->xdp_txq_queues_mode != EFX_XDP_TX_QUEUES_DEDICATED)
HARD_TX_UNLOCK(efx->net_dev, tx_queue->core_txq);
return i == 0 ? -EIO : i;
}
/* Initiate a packet transmission. We use one channel per CPU
* (sharing when we have more CPUs than channels).
*
* Context: non-blocking.
* Should always return NETDEV_TX_OK and consume the skb.
*/
netdev_tx_t efx_hard_start_xmit(struct sk_buff *skb,
struct net_device *net_dev)
{
struct efx_nic *efx = efx_netdev_priv(net_dev);
struct efx_tx_queue *tx_queue;
unsigned index, type;
EFX_WARN_ON_PARANOID(!netif_device_present(net_dev));
index = skb_get_queue_mapping(skb);
type = efx_tx_csum_type_skb(skb);
/* PTP "event" packet */
if (unlikely(efx_xmit_with_hwtstamp(skb)) &&
((efx_ptp_use_mac_tx_timestamps(efx) && efx->ptp_data) ||
unlikely(efx_ptp_is_ptp_tx(efx, skb)))) {
/* There may be existing transmits on the channel that are
* waiting for this packet to trigger the doorbell write.
* We need to send the packets at this point.
*/
efx_tx_send_pending(efx_get_tx_channel(efx, index));
return efx_ptp_tx(efx, skb);
}
tx_queue = efx_get_tx_queue(efx, index, type);
if (WARN_ON_ONCE(!tx_queue)) {
/* We don't have a TXQ of the right type.
* This should never happen, as we don't advertise offload
* features unless we can support them.
*/
dev_kfree_skb_any(skb);
/* If we're not expecting another transmit and we had something to push
* on this queue or a partner queue then we need to push here to get the
* previous packets out.
*/
if (!netdev_xmit_more())
efx_tx_send_pending(efx_get_tx_channel(efx, index));
return NETDEV_TX_OK;
}
return __efx_enqueue_skb(tx_queue, skb);
}
void efx_xmit_done_single(struct efx_tx_queue *tx_queue)
{
unsigned int pkts_compl = 0, bytes_compl = 0;
unsigned int efv_pkts_compl = 0;
unsigned int read_ptr;
bool finished = false;
read_ptr = tx_queue->read_count & tx_queue->ptr_mask;
while (!finished) {
struct efx_tx_buffer *buffer = &tx_queue->buffer[read_ptr];
if (!efx_tx_buffer_in_use(buffer)) {
struct efx_nic *efx = tx_queue->efx;
netif_err(efx, hw, efx->net_dev,
"TX queue %d spurious single TX completion\n",
tx_queue->queue);
efx_schedule_reset(efx, RESET_TYPE_TX_SKIP);
return;
}
/* Need to check the flag before dequeueing. */
if (buffer->flags & EFX_TX_BUF_SKB)
finished = true;
efx_dequeue_buffer(tx_queue, buffer, &pkts_compl, &bytes_compl,
&efv_pkts_compl);
++tx_queue->read_count;
read_ptr = tx_queue->read_count & tx_queue->ptr_mask;
}
tx_queue->pkts_compl += pkts_compl;
tx_queue->bytes_compl += bytes_compl;
EFX_WARN_ON_PARANOID(pkts_compl + efv_pkts_compl != 1);
efx_xmit_done_check_empty(tx_queue);
}
void efx_init_tx_queue_core_txq(struct efx_tx_queue *tx_queue)
{
struct efx_nic *efx = tx_queue->efx;
/* Must be inverse of queue lookup in efx_hard_start_xmit() */
tx_queue->core_txq =
netdev_get_tx_queue(efx->net_dev,
tx_queue->channel->channel);
}
|
linux-master
|
drivers/net/ethernet/sfc/tx.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2005-2006 Fen Systems Ltd.
* Copyright 2005-2015 Solarflare Communications Inc.
*/
#include <linux/pci.h>
#include <linux/tcp.h>
#include <linux/ip.h>
#include <linux/in.h>
#include <linux/ipv6.h>
#include <linux/slab.h>
#include <net/ipv6.h>
#include <linux/if_ether.h>
#include <linux/highmem.h>
#include <linux/moduleparam.h>
#include <linux/cache.h>
#include "net_driver.h"
#include "efx.h"
#include "io.h"
#include "nic.h"
#include "tx.h"
#include "workarounds.h"
#include "ef10_regs.h"
/* Efx legacy TCP segmentation acceleration.
*
* Utilises firmware support to go faster than GSO (but not as fast as TSOv2).
*
* Requires TX checksum offload support.
*/
#define PTR_DIFF(p1, p2) ((u8 *)(p1) - (u8 *)(p2))
/**
* struct tso_state - TSO state for an SKB
* @out_len: Remaining length in current segment
* @seqnum: Current sequence number
* @ipv4_id: Current IPv4 ID, host endian
* @packet_space: Remaining space in current packet
* @dma_addr: DMA address of current position
* @in_len: Remaining length in current SKB fragment
* @unmap_len: Length of SKB fragment
* @unmap_addr: DMA address of SKB fragment
* @protocol: Network protocol (after any VLAN header)
* @ip_off: Offset of IP header
* @tcp_off: Offset of TCP header
* @header_len: Number of bytes of header
* @ip_base_len: IPv4 tot_len or IPv6 payload_len, before TCP payload
* @header_dma_addr: Header DMA address
* @header_unmap_len: Header DMA mapped length
*
* The state used during segmentation. It is put into this data structure
* just to make it easy to pass into inline functions.
*/
struct tso_state {
/* Output position */
unsigned int out_len;
unsigned int seqnum;
u16 ipv4_id;
unsigned int packet_space;
/* Input position */
dma_addr_t dma_addr;
unsigned int in_len;
unsigned int unmap_len;
dma_addr_t unmap_addr;
__be16 protocol;
unsigned int ip_off;
unsigned int tcp_off;
unsigned int header_len;
unsigned int ip_base_len;
dma_addr_t header_dma_addr;
unsigned int header_unmap_len;
};
static inline void prefetch_ptr(struct efx_tx_queue *tx_queue)
{
unsigned int insert_ptr = efx_tx_queue_get_insert_index(tx_queue);
char *ptr;
ptr = (char *) (tx_queue->buffer + insert_ptr);
prefetch(ptr);
prefetch(ptr + 0x80);
ptr = (char *)(((efx_qword_t *)tx_queue->txd.addr) + insert_ptr);
prefetch(ptr);
prefetch(ptr + 0x80);
}
/**
* efx_tx_queue_insert - push descriptors onto the TX queue
* @tx_queue: Efx TX queue
* @dma_addr: DMA address of fragment
* @len: Length of fragment
* @final_buffer: The final buffer inserted into the queue
*
* Push descriptors onto the TX queue.
*/
static void efx_tx_queue_insert(struct efx_tx_queue *tx_queue,
dma_addr_t dma_addr, unsigned int len,
struct efx_tx_buffer **final_buffer)
{
struct efx_tx_buffer *buffer;
unsigned int dma_len;
EFX_WARN_ON_ONCE_PARANOID(len <= 0);
while (1) {
buffer = efx_tx_queue_get_insert_buffer(tx_queue);
++tx_queue->insert_count;
EFX_WARN_ON_ONCE_PARANOID(tx_queue->insert_count -
tx_queue->read_count >=
tx_queue->efx->txq_entries);
buffer->dma_addr = dma_addr;
dma_len = tx_queue->efx->type->tx_limit_len(tx_queue,
dma_addr, len);
/* If there's space for everything this is our last buffer. */
if (dma_len >= len)
break;
buffer->len = dma_len;
buffer->flags = EFX_TX_BUF_CONT;
dma_addr += dma_len;
len -= dma_len;
}
EFX_WARN_ON_ONCE_PARANOID(!len);
buffer->len = len;
*final_buffer = buffer;
}
/*
* Verify that our various assumptions about sk_buffs and the conditions
* under which TSO will be attempted hold true. Return the protocol number.
*/
static __be16 efx_tso_check_protocol(struct sk_buff *skb)
{
__be16 protocol = skb->protocol;
EFX_WARN_ON_ONCE_PARANOID(((struct ethhdr *)skb->data)->h_proto !=
protocol);
if (protocol == htons(ETH_P_8021Q)) {
struct vlan_ethhdr *veh = skb_vlan_eth_hdr(skb);
protocol = veh->h_vlan_encapsulated_proto;
}
if (protocol == htons(ETH_P_IP)) {
EFX_WARN_ON_ONCE_PARANOID(ip_hdr(skb)->protocol != IPPROTO_TCP);
} else {
EFX_WARN_ON_ONCE_PARANOID(protocol != htons(ETH_P_IPV6));
EFX_WARN_ON_ONCE_PARANOID(ipv6_hdr(skb)->nexthdr != NEXTHDR_TCP);
}
EFX_WARN_ON_ONCE_PARANOID((PTR_DIFF(tcp_hdr(skb), skb->data) +
(tcp_hdr(skb)->doff << 2u)) >
skb_headlen(skb));
return protocol;
}
/* Parse the SKB header and initialise state. */
static int tso_start(struct tso_state *st, struct efx_nic *efx,
struct efx_tx_queue *tx_queue,
const struct sk_buff *skb)
{
struct device *dma_dev = &efx->pci_dev->dev;
unsigned int header_len, in_len;
dma_addr_t dma_addr;
st->ip_off = skb_network_header(skb) - skb->data;
st->tcp_off = skb_transport_header(skb) - skb->data;
header_len = st->tcp_off + (tcp_hdr(skb)->doff << 2u);
in_len = skb_headlen(skb) - header_len;
st->header_len = header_len;
st->in_len = in_len;
if (st->protocol == htons(ETH_P_IP)) {
st->ip_base_len = st->header_len - st->ip_off;
st->ipv4_id = ntohs(ip_hdr(skb)->id);
} else {
st->ip_base_len = st->header_len - st->tcp_off;
st->ipv4_id = 0;
}
st->seqnum = ntohl(tcp_hdr(skb)->seq);
EFX_WARN_ON_ONCE_PARANOID(tcp_hdr(skb)->urg);
EFX_WARN_ON_ONCE_PARANOID(tcp_hdr(skb)->syn);
EFX_WARN_ON_ONCE_PARANOID(tcp_hdr(skb)->rst);
st->out_len = skb->len - header_len;
dma_addr = dma_map_single(dma_dev, skb->data,
skb_headlen(skb), DMA_TO_DEVICE);
st->header_dma_addr = dma_addr;
st->header_unmap_len = skb_headlen(skb);
st->dma_addr = dma_addr + header_len;
st->unmap_len = 0;
return unlikely(dma_mapping_error(dma_dev, dma_addr)) ? -ENOMEM : 0;
}
static int tso_get_fragment(struct tso_state *st, struct efx_nic *efx,
skb_frag_t *frag)
{
st->unmap_addr = skb_frag_dma_map(&efx->pci_dev->dev, frag, 0,
skb_frag_size(frag), DMA_TO_DEVICE);
if (likely(!dma_mapping_error(&efx->pci_dev->dev, st->unmap_addr))) {
st->unmap_len = skb_frag_size(frag);
st->in_len = skb_frag_size(frag);
st->dma_addr = st->unmap_addr;
return 0;
}
return -ENOMEM;
}
/**
* tso_fill_packet_with_fragment - form descriptors for the current fragment
* @tx_queue: Efx TX queue
* @skb: Socket buffer
* @st: TSO state
*
* Form descriptors for the current fragment, until we reach the end
* of fragment or end-of-packet.
*/
static void tso_fill_packet_with_fragment(struct efx_tx_queue *tx_queue,
const struct sk_buff *skb,
struct tso_state *st)
{
struct efx_tx_buffer *buffer;
int n;
if (st->in_len == 0)
return;
if (st->packet_space == 0)
return;
EFX_WARN_ON_ONCE_PARANOID(st->in_len <= 0);
EFX_WARN_ON_ONCE_PARANOID(st->packet_space <= 0);
n = min(st->in_len, st->packet_space);
st->packet_space -= n;
st->out_len -= n;
st->in_len -= n;
efx_tx_queue_insert(tx_queue, st->dma_addr, n, &buffer);
if (st->out_len == 0) {
/* Transfer ownership of the skb */
buffer->skb = skb;
buffer->flags = EFX_TX_BUF_SKB;
} else if (st->packet_space != 0) {
buffer->flags = EFX_TX_BUF_CONT;
}
if (st->in_len == 0) {
/* Transfer ownership of the DMA mapping */
buffer->unmap_len = st->unmap_len;
buffer->dma_offset = buffer->unmap_len - buffer->len;
st->unmap_len = 0;
}
st->dma_addr += n;
}
#define TCP_FLAGS_OFFSET 13
/**
* tso_start_new_packet - generate a new header and prepare for the new packet
* @tx_queue: Efx TX queue
* @skb: Socket buffer
* @st: TSO state
*
* Generate a new header and prepare for the new packet. Return 0 on
* success, or -%ENOMEM if failed to alloc header, or other negative error.
*/
static int tso_start_new_packet(struct efx_tx_queue *tx_queue,
const struct sk_buff *skb,
struct tso_state *st)
{
struct efx_tx_buffer *buffer =
efx_tx_queue_get_insert_buffer(tx_queue);
bool is_last = st->out_len <= skb_shinfo(skb)->gso_size;
u8 tcp_flags_mask, tcp_flags;
if (!is_last) {
st->packet_space = skb_shinfo(skb)->gso_size;
tcp_flags_mask = 0x09; /* mask out FIN and PSH */
} else {
st->packet_space = st->out_len;
tcp_flags_mask = 0x00;
}
if (WARN_ON(!st->header_unmap_len))
return -EINVAL;
/* Send the original headers with a TSO option descriptor
* in front
*/
tcp_flags = ((u8 *)tcp_hdr(skb))[TCP_FLAGS_OFFSET] & ~tcp_flags_mask;
buffer->flags = EFX_TX_BUF_OPTION;
buffer->len = 0;
buffer->unmap_len = 0;
EFX_POPULATE_QWORD_5(buffer->option,
ESF_DZ_TX_DESC_IS_OPT, 1,
ESF_DZ_TX_OPTION_TYPE,
ESE_DZ_TX_OPTION_DESC_TSO,
ESF_DZ_TX_TSO_TCP_FLAGS, tcp_flags,
ESF_DZ_TX_TSO_IP_ID, st->ipv4_id,
ESF_DZ_TX_TSO_TCP_SEQNO, st->seqnum);
++tx_queue->insert_count;
/* We mapped the headers in tso_start(). Unmap them
* when the last segment is completed.
*/
buffer = efx_tx_queue_get_insert_buffer(tx_queue);
buffer->dma_addr = st->header_dma_addr;
buffer->len = st->header_len;
if (is_last) {
buffer->flags = EFX_TX_BUF_CONT | EFX_TX_BUF_MAP_SINGLE;
buffer->unmap_len = st->header_unmap_len;
buffer->dma_offset = 0;
/* Ensure we only unmap them once in case of a
* later DMA mapping error and rollback
*/
st->header_unmap_len = 0;
} else {
buffer->flags = EFX_TX_BUF_CONT;
buffer->unmap_len = 0;
}
++tx_queue->insert_count;
st->seqnum += skb_shinfo(skb)->gso_size;
/* Linux leaves suitable gaps in the IP ID space for us to fill. */
++st->ipv4_id;
return 0;
}
/**
* efx_enqueue_skb_tso - segment and transmit a TSO socket buffer
* @tx_queue: Efx TX queue
* @skb: Socket buffer
* @data_mapped: Did we map the data? Always set to true
* by this on success.
*
* Context: You must hold netif_tx_lock() to call this function.
*
* Add socket buffer @skb to @tx_queue, doing TSO or return != 0 if
* @skb was not enqueued. @skb is consumed unless return value is
* %EINVAL.
*/
int efx_enqueue_skb_tso(struct efx_tx_queue *tx_queue,
struct sk_buff *skb,
bool *data_mapped)
{
struct efx_nic *efx = tx_queue->efx;
int frag_i, rc;
struct tso_state state;
if (tx_queue->tso_version != 1)
return -EINVAL;
prefetch(skb->data);
/* Find the packet protocol and sanity-check it */
state.protocol = efx_tso_check_protocol(skb);
EFX_WARN_ON_ONCE_PARANOID(tx_queue->write_count != tx_queue->insert_count);
rc = tso_start(&state, efx, tx_queue, skb);
if (rc)
goto fail;
if (likely(state.in_len == 0)) {
/* Grab the first payload fragment. */
EFX_WARN_ON_ONCE_PARANOID(skb_shinfo(skb)->nr_frags < 1);
frag_i = 0;
rc = tso_get_fragment(&state, efx,
skb_shinfo(skb)->frags + frag_i);
if (rc)
goto fail;
} else {
/* Payload starts in the header area. */
frag_i = -1;
}
rc = tso_start_new_packet(tx_queue, skb, &state);
if (rc)
goto fail;
prefetch_ptr(tx_queue);
while (1) {
tso_fill_packet_with_fragment(tx_queue, skb, &state);
/* Move onto the next fragment? */
if (state.in_len == 0) {
if (++frag_i >= skb_shinfo(skb)->nr_frags)
/* End of payload reached. */
break;
rc = tso_get_fragment(&state, efx,
skb_shinfo(skb)->frags + frag_i);
if (rc)
goto fail;
}
/* Start at new packet? */
if (state.packet_space == 0) {
rc = tso_start_new_packet(tx_queue, skb, &state);
if (rc)
goto fail;
}
}
*data_mapped = true;
return 0;
fail:
if (rc == -ENOMEM)
netif_err(efx, tx_err, efx->net_dev,
"Out of memory for TSO headers, or DMA mapping error\n");
else
netif_err(efx, tx_err, efx->net_dev, "TSO failed, rc = %d\n", rc);
/* Free the DMA mapping we were in the process of writing out */
if (state.unmap_len) {
dma_unmap_page(&efx->pci_dev->dev, state.unmap_addr,
state.unmap_len, DMA_TO_DEVICE);
}
/* Free the header DMA mapping */
if (state.header_unmap_len)
dma_unmap_single(&efx->pci_dev->dev, state.header_dma_addr,
state.header_unmap_len, DMA_TO_DEVICE);
return rc;
}
|
linux-master
|
drivers/net/ethernet/sfc/tx_tso.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2005-2018 Solarflare Communications Inc.
* Copyright 2019-2020 Xilinx Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include "mcdi_filters.h"
#include "mcdi.h"
#include "nic.h"
#include "rx_common.h"
/* The maximum size of a shared RSS context */
/* TODO: this should really be from the mcdi protocol export */
#define EFX_EF10_MAX_SHARED_RSS_CONTEXT_SIZE 64UL
#define EFX_EF10_FILTER_ID_INVALID 0xffff
/* An arbitrary search limit for the software hash table */
#define EFX_EF10_FILTER_SEARCH_LIMIT 200
static struct efx_filter_spec *
efx_mcdi_filter_entry_spec(const struct efx_mcdi_filter_table *table,
unsigned int filter_idx)
{
return (struct efx_filter_spec *)(table->entry[filter_idx].spec &
~EFX_EF10_FILTER_FLAGS);
}
static unsigned int
efx_mcdi_filter_entry_flags(const struct efx_mcdi_filter_table *table,
unsigned int filter_idx)
{
return table->entry[filter_idx].spec & EFX_EF10_FILTER_FLAGS;
}
static u32 efx_mcdi_filter_get_unsafe_id(u32 filter_id)
{
WARN_ON_ONCE(filter_id == EFX_EF10_FILTER_ID_INVALID);
return filter_id & (EFX_MCDI_FILTER_TBL_ROWS - 1);
}
static unsigned int efx_mcdi_filter_get_unsafe_pri(u32 filter_id)
{
return filter_id / (EFX_MCDI_FILTER_TBL_ROWS * 2);
}
static u32 efx_mcdi_filter_make_filter_id(unsigned int pri, u16 idx)
{
return pri * EFX_MCDI_FILTER_TBL_ROWS * 2 + idx;
}
/*
* Decide whether a filter should be exclusive or else should allow
* delivery to additional recipients. Currently we decide that
* filters for specific local unicast MAC and IP addresses are
* exclusive.
*/
static bool efx_mcdi_filter_is_exclusive(const struct efx_filter_spec *spec)
{
if (spec->match_flags & EFX_FILTER_MATCH_LOC_MAC &&
!is_multicast_ether_addr(spec->loc_mac))
return true;
if ((spec->match_flags &
(EFX_FILTER_MATCH_ETHER_TYPE | EFX_FILTER_MATCH_LOC_HOST)) ==
(EFX_FILTER_MATCH_ETHER_TYPE | EFX_FILTER_MATCH_LOC_HOST)) {
if (spec->ether_type == htons(ETH_P_IP) &&
!ipv4_is_multicast(spec->loc_host[0]))
return true;
if (spec->ether_type == htons(ETH_P_IPV6) &&
((const u8 *)spec->loc_host)[0] != 0xff)
return true;
}
return false;
}
static void
efx_mcdi_filter_set_entry(struct efx_mcdi_filter_table *table,
unsigned int filter_idx,
const struct efx_filter_spec *spec,
unsigned int flags)
{
table->entry[filter_idx].spec = (unsigned long)spec | flags;
}
static void
efx_mcdi_filter_push_prep_set_match_fields(struct efx_nic *efx,
const struct efx_filter_spec *spec,
efx_dword_t *inbuf)
{
enum efx_encap_type encap_type = efx_filter_get_encap_type(spec);
u32 match_fields = 0, uc_match, mc_match;
MCDI_SET_DWORD(inbuf, FILTER_OP_IN_OP,
efx_mcdi_filter_is_exclusive(spec) ?
MC_CMD_FILTER_OP_IN_OP_INSERT :
MC_CMD_FILTER_OP_IN_OP_SUBSCRIBE);
/*
* Convert match flags and values. Unlike almost
* everything else in MCDI, these fields are in
* network byte order.
*/
#define COPY_VALUE(value, mcdi_field) \
do { \
match_fields |= \
1 << MC_CMD_FILTER_OP_IN_MATCH_ ## \
mcdi_field ## _LBN; \
BUILD_BUG_ON( \
MC_CMD_FILTER_OP_IN_ ## mcdi_field ## _LEN < \
sizeof(value)); \
memcpy(MCDI_PTR(inbuf, FILTER_OP_IN_ ## mcdi_field), \
&value, sizeof(value)); \
} while (0)
#define COPY_FIELD(gen_flag, gen_field, mcdi_field) \
if (spec->match_flags & EFX_FILTER_MATCH_ ## gen_flag) { \
COPY_VALUE(spec->gen_field, mcdi_field); \
}
/*
* Handle encap filters first. They will always be mismatch
* (unknown UC or MC) filters
*/
if (encap_type) {
/*
* ether_type and outer_ip_proto need to be variables
* because COPY_VALUE wants to memcpy them
*/
__be16 ether_type =
htons(encap_type & EFX_ENCAP_FLAG_IPV6 ?
ETH_P_IPV6 : ETH_P_IP);
u8 vni_type = MC_CMD_FILTER_OP_EXT_IN_VNI_TYPE_GENEVE;
u8 outer_ip_proto;
switch (encap_type & EFX_ENCAP_TYPES_MASK) {
case EFX_ENCAP_TYPE_VXLAN:
vni_type = MC_CMD_FILTER_OP_EXT_IN_VNI_TYPE_VXLAN;
fallthrough;
case EFX_ENCAP_TYPE_GENEVE:
COPY_VALUE(ether_type, ETHER_TYPE);
outer_ip_proto = IPPROTO_UDP;
COPY_VALUE(outer_ip_proto, IP_PROTO);
/*
* We always need to set the type field, even
* though we're not matching on the TNI.
*/
MCDI_POPULATE_DWORD_1(inbuf,
FILTER_OP_EXT_IN_VNI_OR_VSID,
FILTER_OP_EXT_IN_VNI_TYPE,
vni_type);
break;
case EFX_ENCAP_TYPE_NVGRE:
COPY_VALUE(ether_type, ETHER_TYPE);
outer_ip_proto = IPPROTO_GRE;
COPY_VALUE(outer_ip_proto, IP_PROTO);
break;
default:
WARN_ON(1);
}
uc_match = MC_CMD_FILTER_OP_EXT_IN_MATCH_IFRM_UNKNOWN_UCAST_DST_LBN;
mc_match = MC_CMD_FILTER_OP_EXT_IN_MATCH_IFRM_UNKNOWN_MCAST_DST_LBN;
} else {
uc_match = MC_CMD_FILTER_OP_EXT_IN_MATCH_UNKNOWN_UCAST_DST_LBN;
mc_match = MC_CMD_FILTER_OP_EXT_IN_MATCH_UNKNOWN_MCAST_DST_LBN;
}
if (spec->match_flags & EFX_FILTER_MATCH_LOC_MAC_IG)
match_fields |=
is_multicast_ether_addr(spec->loc_mac) ?
1 << mc_match :
1 << uc_match;
COPY_FIELD(REM_HOST, rem_host, SRC_IP);
COPY_FIELD(LOC_HOST, loc_host, DST_IP);
COPY_FIELD(REM_MAC, rem_mac, SRC_MAC);
COPY_FIELD(REM_PORT, rem_port, SRC_PORT);
COPY_FIELD(LOC_MAC, loc_mac, DST_MAC);
COPY_FIELD(LOC_PORT, loc_port, DST_PORT);
COPY_FIELD(ETHER_TYPE, ether_type, ETHER_TYPE);
COPY_FIELD(INNER_VID, inner_vid, INNER_VLAN);
COPY_FIELD(OUTER_VID, outer_vid, OUTER_VLAN);
COPY_FIELD(IP_PROTO, ip_proto, IP_PROTO);
#undef COPY_FIELD
#undef COPY_VALUE
MCDI_SET_DWORD(inbuf, FILTER_OP_IN_MATCH_FIELDS,
match_fields);
}
static void efx_mcdi_filter_push_prep(struct efx_nic *efx,
const struct efx_filter_spec *spec,
efx_dword_t *inbuf, u64 handle,
struct efx_rss_context *ctx,
bool replacing)
{
u32 flags = spec->flags;
memset(inbuf, 0, MC_CMD_FILTER_OP_EXT_IN_LEN);
/* If RSS filter, caller better have given us an RSS context */
if (flags & EFX_FILTER_FLAG_RX_RSS) {
/*
* We don't have the ability to return an error, so we'll just
* log a warning and disable RSS for the filter.
*/
if (WARN_ON_ONCE(!ctx))
flags &= ~EFX_FILTER_FLAG_RX_RSS;
else if (WARN_ON_ONCE(ctx->context_id == EFX_MCDI_RSS_CONTEXT_INVALID))
flags &= ~EFX_FILTER_FLAG_RX_RSS;
}
if (replacing) {
MCDI_SET_DWORD(inbuf, FILTER_OP_IN_OP,
MC_CMD_FILTER_OP_IN_OP_REPLACE);
MCDI_SET_QWORD(inbuf, FILTER_OP_IN_HANDLE, handle);
} else {
efx_mcdi_filter_push_prep_set_match_fields(efx, spec, inbuf);
}
if (flags & EFX_FILTER_FLAG_VPORT_ID)
MCDI_SET_DWORD(inbuf, FILTER_OP_IN_PORT_ID, spec->vport_id);
else
MCDI_SET_DWORD(inbuf, FILTER_OP_IN_PORT_ID, efx->vport_id);
MCDI_SET_DWORD(inbuf, FILTER_OP_IN_RX_DEST,
spec->dmaq_id == EFX_FILTER_RX_DMAQ_ID_DROP ?
MC_CMD_FILTER_OP_IN_RX_DEST_DROP :
MC_CMD_FILTER_OP_IN_RX_DEST_HOST);
MCDI_SET_DWORD(inbuf, FILTER_OP_IN_TX_DOMAIN, 0);
MCDI_SET_DWORD(inbuf, FILTER_OP_IN_TX_DEST,
MC_CMD_FILTER_OP_IN_TX_DEST_DEFAULT);
MCDI_SET_DWORD(inbuf, FILTER_OP_IN_RX_QUEUE,
spec->dmaq_id == EFX_FILTER_RX_DMAQ_ID_DROP ?
0 : spec->dmaq_id);
MCDI_SET_DWORD(inbuf, FILTER_OP_IN_RX_MODE,
(flags & EFX_FILTER_FLAG_RX_RSS) ?
MC_CMD_FILTER_OP_IN_RX_MODE_RSS :
MC_CMD_FILTER_OP_IN_RX_MODE_SIMPLE);
if (flags & EFX_FILTER_FLAG_RX_RSS)
MCDI_SET_DWORD(inbuf, FILTER_OP_IN_RX_CONTEXT, ctx->context_id);
}
static int efx_mcdi_filter_push(struct efx_nic *efx,
const struct efx_filter_spec *spec, u64 *handle,
struct efx_rss_context *ctx, bool replacing)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_FILTER_OP_EXT_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_FILTER_OP_EXT_OUT_LEN);
size_t outlen;
int rc;
efx_mcdi_filter_push_prep(efx, spec, inbuf, *handle, ctx, replacing);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_FILTER_OP, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc && spec->priority != EFX_FILTER_PRI_HINT)
efx_mcdi_display_error(efx, MC_CMD_FILTER_OP, sizeof(inbuf),
outbuf, outlen, rc);
if (rc == 0)
*handle = MCDI_QWORD(outbuf, FILTER_OP_OUT_HANDLE);
if (rc == -ENOSPC)
rc = -EBUSY; /* to match efx_farch_filter_insert() */
return rc;
}
static u32 efx_mcdi_filter_mcdi_flags_from_spec(const struct efx_filter_spec *spec)
{
enum efx_encap_type encap_type = efx_filter_get_encap_type(spec);
unsigned int match_flags = spec->match_flags;
unsigned int uc_match, mc_match;
u32 mcdi_flags = 0;
#define MAP_FILTER_TO_MCDI_FLAG(gen_flag, mcdi_field, encap) { \
unsigned int old_match_flags = match_flags; \
match_flags &= ~EFX_FILTER_MATCH_ ## gen_flag; \
if (match_flags != old_match_flags) \
mcdi_flags |= \
(1 << ((encap) ? \
MC_CMD_FILTER_OP_EXT_IN_MATCH_IFRM_ ## \
mcdi_field ## _LBN : \
MC_CMD_FILTER_OP_EXT_IN_MATCH_ ##\
mcdi_field ## _LBN)); \
}
/* inner or outer based on encap type */
MAP_FILTER_TO_MCDI_FLAG(REM_HOST, SRC_IP, encap_type);
MAP_FILTER_TO_MCDI_FLAG(LOC_HOST, DST_IP, encap_type);
MAP_FILTER_TO_MCDI_FLAG(REM_MAC, SRC_MAC, encap_type);
MAP_FILTER_TO_MCDI_FLAG(REM_PORT, SRC_PORT, encap_type);
MAP_FILTER_TO_MCDI_FLAG(LOC_MAC, DST_MAC, encap_type);
MAP_FILTER_TO_MCDI_FLAG(LOC_PORT, DST_PORT, encap_type);
MAP_FILTER_TO_MCDI_FLAG(ETHER_TYPE, ETHER_TYPE, encap_type);
MAP_FILTER_TO_MCDI_FLAG(IP_PROTO, IP_PROTO, encap_type);
/* always outer */
MAP_FILTER_TO_MCDI_FLAG(INNER_VID, INNER_VLAN, false);
MAP_FILTER_TO_MCDI_FLAG(OUTER_VID, OUTER_VLAN, false);
#undef MAP_FILTER_TO_MCDI_FLAG
/* special handling for encap type, and mismatch */
if (encap_type) {
match_flags &= ~EFX_FILTER_MATCH_ENCAP_TYPE;
mcdi_flags |=
(1 << MC_CMD_FILTER_OP_EXT_IN_MATCH_ETHER_TYPE_LBN);
mcdi_flags |= (1 << MC_CMD_FILTER_OP_EXT_IN_MATCH_IP_PROTO_LBN);
uc_match = MC_CMD_FILTER_OP_EXT_IN_MATCH_IFRM_UNKNOWN_UCAST_DST_LBN;
mc_match = MC_CMD_FILTER_OP_EXT_IN_MATCH_IFRM_UNKNOWN_MCAST_DST_LBN;
} else {
uc_match = MC_CMD_FILTER_OP_EXT_IN_MATCH_UNKNOWN_UCAST_DST_LBN;
mc_match = MC_CMD_FILTER_OP_EXT_IN_MATCH_UNKNOWN_MCAST_DST_LBN;
}
if (match_flags & EFX_FILTER_MATCH_LOC_MAC_IG) {
match_flags &= ~EFX_FILTER_MATCH_LOC_MAC_IG;
mcdi_flags |=
is_multicast_ether_addr(spec->loc_mac) ?
1 << mc_match :
1 << uc_match;
}
/* Did we map them all? */
WARN_ON_ONCE(match_flags);
return mcdi_flags;
}
static int efx_mcdi_filter_pri(struct efx_mcdi_filter_table *table,
const struct efx_filter_spec *spec)
{
u32 mcdi_flags = efx_mcdi_filter_mcdi_flags_from_spec(spec);
unsigned int match_pri;
for (match_pri = 0;
match_pri < table->rx_match_count;
match_pri++)
if (table->rx_match_mcdi_flags[match_pri] == mcdi_flags)
return match_pri;
return -EPROTONOSUPPORT;
}
static s32 efx_mcdi_filter_insert_locked(struct efx_nic *efx,
struct efx_filter_spec *spec,
bool replace_equal)
{
DECLARE_BITMAP(mc_rem_map, EFX_EF10_FILTER_SEARCH_LIMIT);
struct efx_mcdi_filter_table *table;
struct efx_filter_spec *saved_spec;
struct efx_rss_context *ctx = NULL;
unsigned int match_pri, hash;
unsigned int priv_flags;
bool rss_locked = false;
bool replacing = false;
unsigned int depth, i;
int ins_index = -1;
DEFINE_WAIT(wait);
bool is_mc_recip;
s32 rc;
WARN_ON(!rwsem_is_locked(&efx->filter_sem));
table = efx->filter_state;
down_write(&table->lock);
/* For now, only support RX filters */
if ((spec->flags & (EFX_FILTER_FLAG_RX | EFX_FILTER_FLAG_TX)) !=
EFX_FILTER_FLAG_RX) {
rc = -EINVAL;
goto out_unlock;
}
rc = efx_mcdi_filter_pri(table, spec);
if (rc < 0)
goto out_unlock;
match_pri = rc;
hash = efx_filter_spec_hash(spec);
is_mc_recip = efx_filter_is_mc_recipient(spec);
if (is_mc_recip)
bitmap_zero(mc_rem_map, EFX_EF10_FILTER_SEARCH_LIMIT);
if (spec->flags & EFX_FILTER_FLAG_RX_RSS) {
mutex_lock(&efx->rss_lock);
rss_locked = true;
if (spec->rss_context)
ctx = efx_find_rss_context_entry(efx, spec->rss_context);
else
ctx = &efx->rss_context;
if (!ctx) {
rc = -ENOENT;
goto out_unlock;
}
if (ctx->context_id == EFX_MCDI_RSS_CONTEXT_INVALID) {
rc = -EOPNOTSUPP;
goto out_unlock;
}
}
/* Find any existing filters with the same match tuple or
* else a free slot to insert at.
*/
for (depth = 1; depth < EFX_EF10_FILTER_SEARCH_LIMIT; depth++) {
i = (hash + depth) & (EFX_MCDI_FILTER_TBL_ROWS - 1);
saved_spec = efx_mcdi_filter_entry_spec(table, i);
if (!saved_spec) {
if (ins_index < 0)
ins_index = i;
} else if (efx_filter_spec_equal(spec, saved_spec)) {
if (spec->priority < saved_spec->priority &&
spec->priority != EFX_FILTER_PRI_AUTO) {
rc = -EPERM;
goto out_unlock;
}
if (!is_mc_recip) {
/* This is the only one */
if (spec->priority ==
saved_spec->priority &&
!replace_equal) {
rc = -EEXIST;
goto out_unlock;
}
ins_index = i;
break;
} else if (spec->priority >
saved_spec->priority ||
(spec->priority ==
saved_spec->priority &&
replace_equal)) {
if (ins_index < 0)
ins_index = i;
else
__set_bit(depth, mc_rem_map);
}
}
}
/* Once we reach the maximum search depth, use the first suitable
* slot, or return -EBUSY if there was none
*/
if (ins_index < 0) {
rc = -EBUSY;
goto out_unlock;
}
/* Create a software table entry if necessary. */
saved_spec = efx_mcdi_filter_entry_spec(table, ins_index);
if (saved_spec) {
if (spec->priority == EFX_FILTER_PRI_AUTO &&
saved_spec->priority >= EFX_FILTER_PRI_AUTO) {
/* Just make sure it won't be removed */
if (saved_spec->priority > EFX_FILTER_PRI_AUTO)
saved_spec->flags |= EFX_FILTER_FLAG_RX_OVER_AUTO;
table->entry[ins_index].spec &=
~EFX_EF10_FILTER_FLAG_AUTO_OLD;
rc = ins_index;
goto out_unlock;
}
replacing = true;
priv_flags = efx_mcdi_filter_entry_flags(table, ins_index);
} else {
saved_spec = kmalloc(sizeof(*spec), GFP_ATOMIC);
if (!saved_spec) {
rc = -ENOMEM;
goto out_unlock;
}
*saved_spec = *spec;
priv_flags = 0;
}
efx_mcdi_filter_set_entry(table, ins_index, saved_spec, priv_flags);
/* Actually insert the filter on the HW */
rc = efx_mcdi_filter_push(efx, spec, &table->entry[ins_index].handle,
ctx, replacing);
if (rc == -EINVAL && efx->must_realloc_vis)
/* The MC rebooted under us, causing it to reject our filter
* insertion as pointing to an invalid VI (spec->dmaq_id).
*/
rc = -EAGAIN;
/* Finalise the software table entry */
if (rc == 0) {
if (replacing) {
/* Update the fields that may differ */
if (saved_spec->priority == EFX_FILTER_PRI_AUTO)
saved_spec->flags |=
EFX_FILTER_FLAG_RX_OVER_AUTO;
saved_spec->priority = spec->priority;
saved_spec->flags &= EFX_FILTER_FLAG_RX_OVER_AUTO;
saved_spec->flags |= spec->flags;
saved_spec->rss_context = spec->rss_context;
saved_spec->dmaq_id = spec->dmaq_id;
saved_spec->vport_id = spec->vport_id;
}
} else if (!replacing) {
kfree(saved_spec);
saved_spec = NULL;
} else {
/* We failed to replace, so the old filter is still present.
* Roll back the software table to reflect this. In fact the
* efx_mcdi_filter_set_entry() call below will do the right
* thing, so nothing extra is needed here.
*/
}
efx_mcdi_filter_set_entry(table, ins_index, saved_spec, priv_flags);
/* Remove and finalise entries for lower-priority multicast
* recipients
*/
if (is_mc_recip) {
MCDI_DECLARE_BUF(inbuf, MC_CMD_FILTER_OP_EXT_IN_LEN);
unsigned int depth, i;
memset(inbuf, 0, sizeof(inbuf));
for (depth = 0; depth < EFX_EF10_FILTER_SEARCH_LIMIT; depth++) {
if (!test_bit(depth, mc_rem_map))
continue;
i = (hash + depth) & (EFX_MCDI_FILTER_TBL_ROWS - 1);
saved_spec = efx_mcdi_filter_entry_spec(table, i);
priv_flags = efx_mcdi_filter_entry_flags(table, i);
if (rc == 0) {
MCDI_SET_DWORD(inbuf, FILTER_OP_IN_OP,
MC_CMD_FILTER_OP_IN_OP_UNSUBSCRIBE);
MCDI_SET_QWORD(inbuf, FILTER_OP_IN_HANDLE,
table->entry[i].handle);
rc = efx_mcdi_rpc(efx, MC_CMD_FILTER_OP,
inbuf, sizeof(inbuf),
NULL, 0, NULL);
}
if (rc == 0) {
kfree(saved_spec);
saved_spec = NULL;
priv_flags = 0;
}
efx_mcdi_filter_set_entry(table, i, saved_spec,
priv_flags);
}
}
/* If successful, return the inserted filter ID */
if (rc == 0)
rc = efx_mcdi_filter_make_filter_id(match_pri, ins_index);
out_unlock:
if (rss_locked)
mutex_unlock(&efx->rss_lock);
up_write(&table->lock);
return rc;
}
s32 efx_mcdi_filter_insert(struct efx_nic *efx, struct efx_filter_spec *spec,
bool replace_equal)
{
s32 ret;
down_read(&efx->filter_sem);
ret = efx_mcdi_filter_insert_locked(efx, spec, replace_equal);
up_read(&efx->filter_sem);
return ret;
}
/*
* Remove a filter.
* If !by_index, remove by ID
* If by_index, remove by index
* Filter ID may come from userland and must be range-checked.
* Caller must hold efx->filter_sem for read, and efx->filter_state->lock
* for write.
*/
static int efx_mcdi_filter_remove_internal(struct efx_nic *efx,
unsigned int priority_mask,
u32 filter_id, bool by_index)
{
unsigned int filter_idx = efx_mcdi_filter_get_unsafe_id(filter_id);
struct efx_mcdi_filter_table *table = efx->filter_state;
MCDI_DECLARE_BUF(inbuf,
MC_CMD_FILTER_OP_IN_HANDLE_OFST +
MC_CMD_FILTER_OP_IN_HANDLE_LEN);
struct efx_filter_spec *spec;
DEFINE_WAIT(wait);
int rc;
spec = efx_mcdi_filter_entry_spec(table, filter_idx);
if (!spec ||
(!by_index &&
efx_mcdi_filter_pri(table, spec) !=
efx_mcdi_filter_get_unsafe_pri(filter_id)))
return -ENOENT;
if (spec->flags & EFX_FILTER_FLAG_RX_OVER_AUTO &&
priority_mask == (1U << EFX_FILTER_PRI_AUTO)) {
/* Just remove flags */
spec->flags &= ~EFX_FILTER_FLAG_RX_OVER_AUTO;
table->entry[filter_idx].spec &= ~EFX_EF10_FILTER_FLAG_AUTO_OLD;
return 0;
}
if (!(priority_mask & (1U << spec->priority)))
return -ENOENT;
if (spec->flags & EFX_FILTER_FLAG_RX_OVER_AUTO) {
/* Reset to an automatic filter */
struct efx_filter_spec new_spec = *spec;
new_spec.priority = EFX_FILTER_PRI_AUTO;
new_spec.flags = (EFX_FILTER_FLAG_RX |
(efx_rss_active(&efx->rss_context) ?
EFX_FILTER_FLAG_RX_RSS : 0));
new_spec.dmaq_id = 0;
new_spec.rss_context = 0;
rc = efx_mcdi_filter_push(efx, &new_spec,
&table->entry[filter_idx].handle,
&efx->rss_context,
true);
if (rc == 0)
*spec = new_spec;
} else {
/* Really remove the filter */
MCDI_SET_DWORD(inbuf, FILTER_OP_IN_OP,
efx_mcdi_filter_is_exclusive(spec) ?
MC_CMD_FILTER_OP_IN_OP_REMOVE :
MC_CMD_FILTER_OP_IN_OP_UNSUBSCRIBE);
MCDI_SET_QWORD(inbuf, FILTER_OP_IN_HANDLE,
table->entry[filter_idx].handle);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_FILTER_OP,
inbuf, sizeof(inbuf), NULL, 0, NULL);
if ((rc == 0) || (rc == -ENOENT)) {
/* Filter removed OK or didn't actually exist */
kfree(spec);
efx_mcdi_filter_set_entry(table, filter_idx, NULL, 0);
} else {
efx_mcdi_display_error(efx, MC_CMD_FILTER_OP,
MC_CMD_FILTER_OP_EXT_IN_LEN,
NULL, 0, rc);
}
}
return rc;
}
/* Remove filters that weren't renewed. */
static void efx_mcdi_filter_remove_old(struct efx_nic *efx)
{
struct efx_mcdi_filter_table *table = efx->filter_state;
int remove_failed = 0;
int remove_noent = 0;
int rc;
int i;
down_write(&table->lock);
for (i = 0; i < EFX_MCDI_FILTER_TBL_ROWS; i++) {
if (READ_ONCE(table->entry[i].spec) &
EFX_EF10_FILTER_FLAG_AUTO_OLD) {
rc = efx_mcdi_filter_remove_internal(efx,
1U << EFX_FILTER_PRI_AUTO, i, true);
if (rc == -ENOENT)
remove_noent++;
else if (rc)
remove_failed++;
}
}
up_write(&table->lock);
if (remove_failed)
netif_info(efx, drv, efx->net_dev,
"%s: failed to remove %d filters\n",
__func__, remove_failed);
if (remove_noent)
netif_info(efx, drv, efx->net_dev,
"%s: failed to remove %d non-existent filters\n",
__func__, remove_noent);
}
int efx_mcdi_filter_remove_safe(struct efx_nic *efx,
enum efx_filter_priority priority,
u32 filter_id)
{
struct efx_mcdi_filter_table *table;
int rc;
down_read(&efx->filter_sem);
table = efx->filter_state;
down_write(&table->lock);
rc = efx_mcdi_filter_remove_internal(efx, 1U << priority, filter_id,
false);
up_write(&table->lock);
up_read(&efx->filter_sem);
return rc;
}
/* Caller must hold efx->filter_sem for read */
static void efx_mcdi_filter_remove_unsafe(struct efx_nic *efx,
enum efx_filter_priority priority,
u32 filter_id)
{
struct efx_mcdi_filter_table *table = efx->filter_state;
if (filter_id == EFX_EF10_FILTER_ID_INVALID)
return;
down_write(&table->lock);
efx_mcdi_filter_remove_internal(efx, 1U << priority, filter_id,
true);
up_write(&table->lock);
}
int efx_mcdi_filter_get_safe(struct efx_nic *efx,
enum efx_filter_priority priority,
u32 filter_id, struct efx_filter_spec *spec)
{
unsigned int filter_idx = efx_mcdi_filter_get_unsafe_id(filter_id);
const struct efx_filter_spec *saved_spec;
struct efx_mcdi_filter_table *table;
int rc;
down_read(&efx->filter_sem);
table = efx->filter_state;
down_read(&table->lock);
saved_spec = efx_mcdi_filter_entry_spec(table, filter_idx);
if (saved_spec && saved_spec->priority == priority &&
efx_mcdi_filter_pri(table, saved_spec) ==
efx_mcdi_filter_get_unsafe_pri(filter_id)) {
*spec = *saved_spec;
rc = 0;
} else {
rc = -ENOENT;
}
up_read(&table->lock);
up_read(&efx->filter_sem);
return rc;
}
static int efx_mcdi_filter_insert_addr_list(struct efx_nic *efx,
struct efx_mcdi_filter_vlan *vlan,
bool multicast, bool rollback)
{
struct efx_mcdi_filter_table *table = efx->filter_state;
struct efx_mcdi_dev_addr *addr_list;
enum efx_filter_flags filter_flags;
struct efx_filter_spec spec;
u8 baddr[ETH_ALEN];
unsigned int i, j;
int addr_count;
u16 *ids;
int rc;
if (multicast) {
addr_list = table->dev_mc_list;
addr_count = table->dev_mc_count;
ids = vlan->mc;
} else {
addr_list = table->dev_uc_list;
addr_count = table->dev_uc_count;
ids = vlan->uc;
}
filter_flags = efx_rss_active(&efx->rss_context) ? EFX_FILTER_FLAG_RX_RSS : 0;
/* Insert/renew filters */
for (i = 0; i < addr_count; i++) {
EFX_WARN_ON_PARANOID(ids[i] != EFX_EF10_FILTER_ID_INVALID);
efx_filter_init_rx(&spec, EFX_FILTER_PRI_AUTO, filter_flags, 0);
efx_filter_set_eth_local(&spec, vlan->vid, addr_list[i].addr);
rc = efx_mcdi_filter_insert_locked(efx, &spec, true);
if (rc < 0) {
if (rollback) {
netif_info(efx, drv, efx->net_dev,
"efx_mcdi_filter_insert failed rc=%d\n",
rc);
/* Fall back to promiscuous */
for (j = 0; j < i; j++) {
efx_mcdi_filter_remove_unsafe(
efx, EFX_FILTER_PRI_AUTO,
ids[j]);
ids[j] = EFX_EF10_FILTER_ID_INVALID;
}
return rc;
} else {
/* keep invalid ID, and carry on */
}
} else {
ids[i] = efx_mcdi_filter_get_unsafe_id(rc);
}
}
if (multicast && rollback) {
/* Also need an Ethernet broadcast filter */
EFX_WARN_ON_PARANOID(vlan->default_filters[EFX_EF10_BCAST] !=
EFX_EF10_FILTER_ID_INVALID);
efx_filter_init_rx(&spec, EFX_FILTER_PRI_AUTO, filter_flags, 0);
eth_broadcast_addr(baddr);
efx_filter_set_eth_local(&spec, vlan->vid, baddr);
rc = efx_mcdi_filter_insert_locked(efx, &spec, true);
if (rc < 0) {
netif_warn(efx, drv, efx->net_dev,
"Broadcast filter insert failed rc=%d\n", rc);
/* Fall back to promiscuous */
for (j = 0; j < i; j++) {
efx_mcdi_filter_remove_unsafe(
efx, EFX_FILTER_PRI_AUTO,
ids[j]);
ids[j] = EFX_EF10_FILTER_ID_INVALID;
}
return rc;
} else {
vlan->default_filters[EFX_EF10_BCAST] =
efx_mcdi_filter_get_unsafe_id(rc);
}
}
return 0;
}
static int efx_mcdi_filter_insert_def(struct efx_nic *efx,
struct efx_mcdi_filter_vlan *vlan,
enum efx_encap_type encap_type,
bool multicast, bool rollback)
{
struct efx_mcdi_filter_table *table = efx->filter_state;
enum efx_filter_flags filter_flags;
struct efx_filter_spec spec;
u8 baddr[ETH_ALEN];
int rc;
u16 *id;
filter_flags = efx_rss_active(&efx->rss_context) ? EFX_FILTER_FLAG_RX_RSS : 0;
efx_filter_init_rx(&spec, EFX_FILTER_PRI_AUTO, filter_flags, 0);
if (multicast)
efx_filter_set_mc_def(&spec);
else
efx_filter_set_uc_def(&spec);
if (encap_type) {
if (efx_has_cap(efx, VXLAN_NVGRE))
efx_filter_set_encap_type(&spec, encap_type);
else
/*
* don't insert encap filters on non-supporting
* platforms. ID will be left as INVALID.
*/
return 0;
}
if (vlan->vid != EFX_FILTER_VID_UNSPEC)
efx_filter_set_eth_local(&spec, vlan->vid, NULL);
rc = efx_mcdi_filter_insert_locked(efx, &spec, true);
if (rc < 0) {
const char *um = multicast ? "Multicast" : "Unicast";
const char *encap_name = "";
const char *encap_ipv = "";
if ((encap_type & EFX_ENCAP_TYPES_MASK) ==
EFX_ENCAP_TYPE_VXLAN)
encap_name = "VXLAN ";
else if ((encap_type & EFX_ENCAP_TYPES_MASK) ==
EFX_ENCAP_TYPE_NVGRE)
encap_name = "NVGRE ";
else if ((encap_type & EFX_ENCAP_TYPES_MASK) ==
EFX_ENCAP_TYPE_GENEVE)
encap_name = "GENEVE ";
if (encap_type & EFX_ENCAP_FLAG_IPV6)
encap_ipv = "IPv6 ";
else if (encap_type)
encap_ipv = "IPv4 ";
/*
* unprivileged functions can't insert mismatch filters
* for encapsulated or unicast traffic, so downgrade
* those warnings to debug.
*/
netif_cond_dbg(efx, drv, efx->net_dev,
rc == -EPERM && (encap_type || !multicast), warn,
"%s%s%s mismatch filter insert failed rc=%d\n",
encap_name, encap_ipv, um, rc);
} else if (multicast) {
/* mapping from encap types to default filter IDs (multicast) */
static enum efx_mcdi_filter_default_filters map[] = {
[EFX_ENCAP_TYPE_NONE] = EFX_EF10_MCDEF,
[EFX_ENCAP_TYPE_VXLAN] = EFX_EF10_VXLAN4_MCDEF,
[EFX_ENCAP_TYPE_NVGRE] = EFX_EF10_NVGRE4_MCDEF,
[EFX_ENCAP_TYPE_GENEVE] = EFX_EF10_GENEVE4_MCDEF,
[EFX_ENCAP_TYPE_VXLAN | EFX_ENCAP_FLAG_IPV6] =
EFX_EF10_VXLAN6_MCDEF,
[EFX_ENCAP_TYPE_NVGRE | EFX_ENCAP_FLAG_IPV6] =
EFX_EF10_NVGRE6_MCDEF,
[EFX_ENCAP_TYPE_GENEVE | EFX_ENCAP_FLAG_IPV6] =
EFX_EF10_GENEVE6_MCDEF,
};
/* quick bounds check (BCAST result impossible) */
BUILD_BUG_ON(EFX_EF10_BCAST != 0);
if (encap_type >= ARRAY_SIZE(map) || map[encap_type] == 0) {
WARN_ON(1);
return -EINVAL;
}
/* then follow map */
id = &vlan->default_filters[map[encap_type]];
EFX_WARN_ON_PARANOID(*id != EFX_EF10_FILTER_ID_INVALID);
*id = efx_mcdi_filter_get_unsafe_id(rc);
if (!table->mc_chaining && !encap_type) {
/* Also need an Ethernet broadcast filter */
efx_filter_init_rx(&spec, EFX_FILTER_PRI_AUTO,
filter_flags, 0);
eth_broadcast_addr(baddr);
efx_filter_set_eth_local(&spec, vlan->vid, baddr);
rc = efx_mcdi_filter_insert_locked(efx, &spec, true);
if (rc < 0) {
netif_warn(efx, drv, efx->net_dev,
"Broadcast filter insert failed rc=%d\n",
rc);
if (rollback) {
/* Roll back the mc_def filter */
efx_mcdi_filter_remove_unsafe(
efx, EFX_FILTER_PRI_AUTO,
*id);
*id = EFX_EF10_FILTER_ID_INVALID;
return rc;
}
} else {
EFX_WARN_ON_PARANOID(
vlan->default_filters[EFX_EF10_BCAST] !=
EFX_EF10_FILTER_ID_INVALID);
vlan->default_filters[EFX_EF10_BCAST] =
efx_mcdi_filter_get_unsafe_id(rc);
}
}
rc = 0;
} else {
/* mapping from encap types to default filter IDs (unicast) */
static enum efx_mcdi_filter_default_filters map[] = {
[EFX_ENCAP_TYPE_NONE] = EFX_EF10_UCDEF,
[EFX_ENCAP_TYPE_VXLAN] = EFX_EF10_VXLAN4_UCDEF,
[EFX_ENCAP_TYPE_NVGRE] = EFX_EF10_NVGRE4_UCDEF,
[EFX_ENCAP_TYPE_GENEVE] = EFX_EF10_GENEVE4_UCDEF,
[EFX_ENCAP_TYPE_VXLAN | EFX_ENCAP_FLAG_IPV6] =
EFX_EF10_VXLAN6_UCDEF,
[EFX_ENCAP_TYPE_NVGRE | EFX_ENCAP_FLAG_IPV6] =
EFX_EF10_NVGRE6_UCDEF,
[EFX_ENCAP_TYPE_GENEVE | EFX_ENCAP_FLAG_IPV6] =
EFX_EF10_GENEVE6_UCDEF,
};
/* quick bounds check (BCAST result impossible) */
BUILD_BUG_ON(EFX_EF10_BCAST != 0);
if (encap_type >= ARRAY_SIZE(map) || map[encap_type] == 0) {
WARN_ON(1);
return -EINVAL;
}
/* then follow map */
id = &vlan->default_filters[map[encap_type]];
EFX_WARN_ON_PARANOID(*id != EFX_EF10_FILTER_ID_INVALID);
*id = rc;
rc = 0;
}
return rc;
}
/*
* Caller must hold efx->filter_sem for read if race against
* efx_mcdi_filter_table_remove() is possible
*/
static void efx_mcdi_filter_vlan_sync_rx_mode(struct efx_nic *efx,
struct efx_mcdi_filter_vlan *vlan)
{
struct efx_mcdi_filter_table *table = efx->filter_state;
/*
* Do not install unspecified VID if VLAN filtering is enabled.
* Do not install all specified VIDs if VLAN filtering is disabled.
*/
if ((vlan->vid == EFX_FILTER_VID_UNSPEC) == table->vlan_filter)
return;
/* Insert/renew unicast filters */
if (table->uc_promisc) {
efx_mcdi_filter_insert_def(efx, vlan, EFX_ENCAP_TYPE_NONE,
false, false);
efx_mcdi_filter_insert_addr_list(efx, vlan, false, false);
} else {
/*
* If any of the filters failed to insert, fall back to
* promiscuous mode - add in the uc_def filter. But keep
* our individual unicast filters.
*/
if (efx_mcdi_filter_insert_addr_list(efx, vlan, false, false))
efx_mcdi_filter_insert_def(efx, vlan,
EFX_ENCAP_TYPE_NONE,
false, false);
}
efx_mcdi_filter_insert_def(efx, vlan, EFX_ENCAP_TYPE_VXLAN,
false, false);
efx_mcdi_filter_insert_def(efx, vlan, EFX_ENCAP_TYPE_VXLAN |
EFX_ENCAP_FLAG_IPV6,
false, false);
efx_mcdi_filter_insert_def(efx, vlan, EFX_ENCAP_TYPE_NVGRE,
false, false);
efx_mcdi_filter_insert_def(efx, vlan, EFX_ENCAP_TYPE_NVGRE |
EFX_ENCAP_FLAG_IPV6,
false, false);
efx_mcdi_filter_insert_def(efx, vlan, EFX_ENCAP_TYPE_GENEVE,
false, false);
efx_mcdi_filter_insert_def(efx, vlan, EFX_ENCAP_TYPE_GENEVE |
EFX_ENCAP_FLAG_IPV6,
false, false);
/*
* Insert/renew multicast filters
*
* If changing promiscuous state with cascaded multicast filters, remove
* old filters first, so that packets are dropped rather than duplicated
*/
if (table->mc_chaining && table->mc_promisc_last != table->mc_promisc)
efx_mcdi_filter_remove_old(efx);
if (table->mc_promisc) {
if (table->mc_chaining) {
/*
* If we failed to insert promiscuous filters, rollback
* and fall back to individual multicast filters
*/
if (efx_mcdi_filter_insert_def(efx, vlan,
EFX_ENCAP_TYPE_NONE,
true, true)) {
/* Changing promisc state, so remove old filters */
efx_mcdi_filter_remove_old(efx);
efx_mcdi_filter_insert_addr_list(efx, vlan,
true, false);
}
} else {
/*
* If we failed to insert promiscuous filters, don't
* rollback. Regardless, also insert the mc_list,
* unless it's incomplete due to overflow
*/
efx_mcdi_filter_insert_def(efx, vlan,
EFX_ENCAP_TYPE_NONE,
true, false);
if (!table->mc_overflow)
efx_mcdi_filter_insert_addr_list(efx, vlan,
true, false);
}
} else {
/*
* If any filters failed to insert, rollback and fall back to
* promiscuous mode - mc_def filter and maybe broadcast. If
* that fails, roll back again and insert as many of our
* individual multicast filters as we can.
*/
if (efx_mcdi_filter_insert_addr_list(efx, vlan, true, true)) {
/* Changing promisc state, so remove old filters */
if (table->mc_chaining)
efx_mcdi_filter_remove_old(efx);
if (efx_mcdi_filter_insert_def(efx, vlan,
EFX_ENCAP_TYPE_NONE,
true, true))
efx_mcdi_filter_insert_addr_list(efx, vlan,
true, false);
}
}
efx_mcdi_filter_insert_def(efx, vlan, EFX_ENCAP_TYPE_VXLAN,
true, false);
efx_mcdi_filter_insert_def(efx, vlan, EFX_ENCAP_TYPE_VXLAN |
EFX_ENCAP_FLAG_IPV6,
true, false);
efx_mcdi_filter_insert_def(efx, vlan, EFX_ENCAP_TYPE_NVGRE,
true, false);
efx_mcdi_filter_insert_def(efx, vlan, EFX_ENCAP_TYPE_NVGRE |
EFX_ENCAP_FLAG_IPV6,
true, false);
efx_mcdi_filter_insert_def(efx, vlan, EFX_ENCAP_TYPE_GENEVE,
true, false);
efx_mcdi_filter_insert_def(efx, vlan, EFX_ENCAP_TYPE_GENEVE |
EFX_ENCAP_FLAG_IPV6,
true, false);
}
int efx_mcdi_filter_clear_rx(struct efx_nic *efx,
enum efx_filter_priority priority)
{
struct efx_mcdi_filter_table *table;
unsigned int priority_mask;
unsigned int i;
int rc;
priority_mask = (((1U << (priority + 1)) - 1) &
~(1U << EFX_FILTER_PRI_AUTO));
down_read(&efx->filter_sem);
table = efx->filter_state;
down_write(&table->lock);
for (i = 0; i < EFX_MCDI_FILTER_TBL_ROWS; i++) {
rc = efx_mcdi_filter_remove_internal(efx, priority_mask,
i, true);
if (rc && rc != -ENOENT)
break;
rc = 0;
}
up_write(&table->lock);
up_read(&efx->filter_sem);
return rc;
}
u32 efx_mcdi_filter_count_rx_used(struct efx_nic *efx,
enum efx_filter_priority priority)
{
struct efx_mcdi_filter_table *table;
unsigned int filter_idx;
s32 count = 0;
down_read(&efx->filter_sem);
table = efx->filter_state;
down_read(&table->lock);
for (filter_idx = 0; filter_idx < EFX_MCDI_FILTER_TBL_ROWS; filter_idx++) {
if (table->entry[filter_idx].spec &&
efx_mcdi_filter_entry_spec(table, filter_idx)->priority ==
priority)
++count;
}
up_read(&table->lock);
up_read(&efx->filter_sem);
return count;
}
u32 efx_mcdi_filter_get_rx_id_limit(struct efx_nic *efx)
{
struct efx_mcdi_filter_table *table = efx->filter_state;
return table->rx_match_count * EFX_MCDI_FILTER_TBL_ROWS * 2;
}
s32 efx_mcdi_filter_get_rx_ids(struct efx_nic *efx,
enum efx_filter_priority priority,
u32 *buf, u32 size)
{
struct efx_mcdi_filter_table *table;
struct efx_filter_spec *spec;
unsigned int filter_idx;
s32 count = 0;
down_read(&efx->filter_sem);
table = efx->filter_state;
down_read(&table->lock);
for (filter_idx = 0; filter_idx < EFX_MCDI_FILTER_TBL_ROWS; filter_idx++) {
spec = efx_mcdi_filter_entry_spec(table, filter_idx);
if (spec && spec->priority == priority) {
if (count == size) {
count = -EMSGSIZE;
break;
}
buf[count++] =
efx_mcdi_filter_make_filter_id(
efx_mcdi_filter_pri(table, spec),
filter_idx);
}
}
up_read(&table->lock);
up_read(&efx->filter_sem);
return count;
}
static int efx_mcdi_filter_match_flags_from_mcdi(bool encap, u32 mcdi_flags)
{
int match_flags = 0;
#define MAP_FLAG(gen_flag, mcdi_field) do { \
u32 old_mcdi_flags = mcdi_flags; \
mcdi_flags &= ~(1 << MC_CMD_FILTER_OP_EXT_IN_MATCH_ ## \
mcdi_field ## _LBN); \
if (mcdi_flags != old_mcdi_flags) \
match_flags |= EFX_FILTER_MATCH_ ## gen_flag; \
} while (0)
if (encap) {
/* encap filters must specify encap type */
match_flags |= EFX_FILTER_MATCH_ENCAP_TYPE;
/* and imply ethertype and ip proto */
mcdi_flags &=
~(1 << MC_CMD_FILTER_OP_EXT_IN_MATCH_IP_PROTO_LBN);
mcdi_flags &=
~(1 << MC_CMD_FILTER_OP_EXT_IN_MATCH_ETHER_TYPE_LBN);
/* VLAN tags refer to the outer packet */
MAP_FLAG(INNER_VID, INNER_VLAN);
MAP_FLAG(OUTER_VID, OUTER_VLAN);
/* everything else refers to the inner packet */
MAP_FLAG(LOC_MAC_IG, IFRM_UNKNOWN_UCAST_DST);
MAP_FLAG(LOC_MAC_IG, IFRM_UNKNOWN_MCAST_DST);
MAP_FLAG(REM_HOST, IFRM_SRC_IP);
MAP_FLAG(LOC_HOST, IFRM_DST_IP);
MAP_FLAG(REM_MAC, IFRM_SRC_MAC);
MAP_FLAG(REM_PORT, IFRM_SRC_PORT);
MAP_FLAG(LOC_MAC, IFRM_DST_MAC);
MAP_FLAG(LOC_PORT, IFRM_DST_PORT);
MAP_FLAG(ETHER_TYPE, IFRM_ETHER_TYPE);
MAP_FLAG(IP_PROTO, IFRM_IP_PROTO);
} else {
MAP_FLAG(LOC_MAC_IG, UNKNOWN_UCAST_DST);
MAP_FLAG(LOC_MAC_IG, UNKNOWN_MCAST_DST);
MAP_FLAG(REM_HOST, SRC_IP);
MAP_FLAG(LOC_HOST, DST_IP);
MAP_FLAG(REM_MAC, SRC_MAC);
MAP_FLAG(REM_PORT, SRC_PORT);
MAP_FLAG(LOC_MAC, DST_MAC);
MAP_FLAG(LOC_PORT, DST_PORT);
MAP_FLAG(ETHER_TYPE, ETHER_TYPE);
MAP_FLAG(INNER_VID, INNER_VLAN);
MAP_FLAG(OUTER_VID, OUTER_VLAN);
MAP_FLAG(IP_PROTO, IP_PROTO);
}
#undef MAP_FLAG
/* Did we map them all? */
if (mcdi_flags)
return -EINVAL;
return match_flags;
}
bool efx_mcdi_filter_match_supported(struct efx_mcdi_filter_table *table,
bool encap,
enum efx_filter_match_flags match_flags)
{
unsigned int match_pri;
int mf;
for (match_pri = 0;
match_pri < table->rx_match_count;
match_pri++) {
mf = efx_mcdi_filter_match_flags_from_mcdi(encap,
table->rx_match_mcdi_flags[match_pri]);
if (mf == match_flags)
return true;
}
return false;
}
static int
efx_mcdi_filter_table_probe_matches(struct efx_nic *efx,
struct efx_mcdi_filter_table *table,
bool encap)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_GET_PARSER_DISP_INFO_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_PARSER_DISP_INFO_OUT_LENMAX);
unsigned int pd_match_pri, pd_match_count;
size_t outlen;
int rc;
/* Find out which RX filter types are supported, and their priorities */
MCDI_SET_DWORD(inbuf, GET_PARSER_DISP_INFO_IN_OP,
encap ?
MC_CMD_GET_PARSER_DISP_INFO_IN_OP_GET_SUPPORTED_ENCAP_RX_MATCHES :
MC_CMD_GET_PARSER_DISP_INFO_IN_OP_GET_SUPPORTED_RX_MATCHES);
rc = efx_mcdi_rpc(efx, MC_CMD_GET_PARSER_DISP_INFO,
inbuf, sizeof(inbuf), outbuf, sizeof(outbuf),
&outlen);
if (rc)
return rc;
pd_match_count = MCDI_VAR_ARRAY_LEN(
outlen, GET_PARSER_DISP_INFO_OUT_SUPPORTED_MATCHES);
for (pd_match_pri = 0; pd_match_pri < pd_match_count; pd_match_pri++) {
u32 mcdi_flags =
MCDI_ARRAY_DWORD(
outbuf,
GET_PARSER_DISP_INFO_OUT_SUPPORTED_MATCHES,
pd_match_pri);
rc = efx_mcdi_filter_match_flags_from_mcdi(encap, mcdi_flags);
if (rc < 0) {
netif_dbg(efx, probe, efx->net_dev,
"%s: fw flags %#x pri %u not supported in driver\n",
__func__, mcdi_flags, pd_match_pri);
} else {
netif_dbg(efx, probe, efx->net_dev,
"%s: fw flags %#x pri %u supported as driver flags %#x pri %u\n",
__func__, mcdi_flags, pd_match_pri,
rc, table->rx_match_count);
table->rx_match_mcdi_flags[table->rx_match_count] = mcdi_flags;
table->rx_match_count++;
}
}
return 0;
}
int efx_mcdi_filter_table_probe(struct efx_nic *efx, bool multicast_chaining)
{
struct net_device *net_dev = efx->net_dev;
struct efx_mcdi_filter_table *table;
int rc;
if (!efx_rwsem_assert_write_locked(&efx->filter_sem))
return -EINVAL;
if (efx->filter_state) /* already probed */
return 0;
table = kzalloc(sizeof(*table), GFP_KERNEL);
if (!table)
return -ENOMEM;
table->mc_chaining = multicast_chaining;
table->rx_match_count = 0;
rc = efx_mcdi_filter_table_probe_matches(efx, table, false);
if (rc)
goto fail;
if (efx_has_cap(efx, VXLAN_NVGRE))
rc = efx_mcdi_filter_table_probe_matches(efx, table, true);
if (rc)
goto fail;
if ((efx_supported_features(efx) & NETIF_F_HW_VLAN_CTAG_FILTER) &&
!(efx_mcdi_filter_match_supported(table, false,
(EFX_FILTER_MATCH_OUTER_VID | EFX_FILTER_MATCH_LOC_MAC)) &&
efx_mcdi_filter_match_supported(table, false,
(EFX_FILTER_MATCH_OUTER_VID | EFX_FILTER_MATCH_LOC_MAC_IG)))) {
netif_info(efx, probe, net_dev,
"VLAN filters are not supported in this firmware variant\n");
net_dev->features &= ~NETIF_F_HW_VLAN_CTAG_FILTER;
efx->fixed_features &= ~NETIF_F_HW_VLAN_CTAG_FILTER;
net_dev->hw_features &= ~NETIF_F_HW_VLAN_CTAG_FILTER;
}
table->entry = vzalloc(array_size(EFX_MCDI_FILTER_TBL_ROWS,
sizeof(*table->entry)));
if (!table->entry) {
rc = -ENOMEM;
goto fail;
}
table->mc_promisc_last = false;
table->vlan_filter =
!!(efx->net_dev->features & NETIF_F_HW_VLAN_CTAG_FILTER);
INIT_LIST_HEAD(&table->vlan_list);
init_rwsem(&table->lock);
efx->filter_state = table;
return 0;
fail:
kfree(table);
return rc;
}
void efx_mcdi_filter_table_reset_mc_allocations(struct efx_nic *efx)
{
struct efx_mcdi_filter_table *table = efx->filter_state;
if (table) {
table->must_restore_filters = true;
table->must_restore_rss_contexts = true;
}
}
/*
* Caller must hold efx->filter_sem for read if race against
* efx_mcdi_filter_table_remove() is possible
*/
void efx_mcdi_filter_table_restore(struct efx_nic *efx)
{
struct efx_mcdi_filter_table *table = efx->filter_state;
unsigned int invalid_filters = 0, failed = 0;
struct efx_mcdi_filter_vlan *vlan;
struct efx_filter_spec *spec;
struct efx_rss_context *ctx;
unsigned int filter_idx;
u32 mcdi_flags;
int match_pri;
int rc, i;
WARN_ON(!rwsem_is_locked(&efx->filter_sem));
if (!table || !table->must_restore_filters)
return;
down_write(&table->lock);
mutex_lock(&efx->rss_lock);
for (filter_idx = 0; filter_idx < EFX_MCDI_FILTER_TBL_ROWS; filter_idx++) {
spec = efx_mcdi_filter_entry_spec(table, filter_idx);
if (!spec)
continue;
mcdi_flags = efx_mcdi_filter_mcdi_flags_from_spec(spec);
match_pri = 0;
while (match_pri < table->rx_match_count &&
table->rx_match_mcdi_flags[match_pri] != mcdi_flags)
++match_pri;
if (match_pri >= table->rx_match_count) {
invalid_filters++;
goto not_restored;
}
if (spec->rss_context)
ctx = efx_find_rss_context_entry(efx, spec->rss_context);
else
ctx = &efx->rss_context;
if (spec->flags & EFX_FILTER_FLAG_RX_RSS) {
if (!ctx) {
netif_warn(efx, drv, efx->net_dev,
"Warning: unable to restore a filter with nonexistent RSS context %u.\n",
spec->rss_context);
invalid_filters++;
goto not_restored;
}
if (ctx->context_id == EFX_MCDI_RSS_CONTEXT_INVALID) {
netif_warn(efx, drv, efx->net_dev,
"Warning: unable to restore a filter with RSS context %u as it was not created.\n",
spec->rss_context);
invalid_filters++;
goto not_restored;
}
}
rc = efx_mcdi_filter_push(efx, spec,
&table->entry[filter_idx].handle,
ctx, false);
if (rc)
failed++;
if (rc) {
not_restored:
list_for_each_entry(vlan, &table->vlan_list, list)
for (i = 0; i < EFX_EF10_NUM_DEFAULT_FILTERS; ++i)
if (vlan->default_filters[i] == filter_idx)
vlan->default_filters[i] =
EFX_EF10_FILTER_ID_INVALID;
kfree(spec);
efx_mcdi_filter_set_entry(table, filter_idx, NULL, 0);
}
}
mutex_unlock(&efx->rss_lock);
up_write(&table->lock);
/*
* This can happen validly if the MC's capabilities have changed, so
* is not an error.
*/
if (invalid_filters)
netif_dbg(efx, drv, efx->net_dev,
"Did not restore %u filters that are now unsupported.\n",
invalid_filters);
if (failed)
netif_err(efx, hw, efx->net_dev,
"unable to restore %u filters\n", failed);
else
table->must_restore_filters = false;
}
void efx_mcdi_filter_table_down(struct efx_nic *efx)
{
struct efx_mcdi_filter_table *table = efx->filter_state;
MCDI_DECLARE_BUF(inbuf, MC_CMD_FILTER_OP_EXT_IN_LEN);
struct efx_filter_spec *spec;
unsigned int filter_idx;
int rc;
if (!table)
return;
efx_mcdi_filter_cleanup_vlans(efx);
for (filter_idx = 0; filter_idx < EFX_MCDI_FILTER_TBL_ROWS; filter_idx++) {
spec = efx_mcdi_filter_entry_spec(table, filter_idx);
if (!spec)
continue;
MCDI_SET_DWORD(inbuf, FILTER_OP_IN_OP,
efx_mcdi_filter_is_exclusive(spec) ?
MC_CMD_FILTER_OP_IN_OP_REMOVE :
MC_CMD_FILTER_OP_IN_OP_UNSUBSCRIBE);
MCDI_SET_QWORD(inbuf, FILTER_OP_IN_HANDLE,
table->entry[filter_idx].handle);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_FILTER_OP, inbuf,
sizeof(inbuf), NULL, 0, NULL);
if (rc)
netif_info(efx, drv, efx->net_dev,
"%s: filter %04x remove failed\n",
__func__, filter_idx);
kfree(spec);
}
}
void efx_mcdi_filter_table_remove(struct efx_nic *efx)
{
struct efx_mcdi_filter_table *table = efx->filter_state;
efx_mcdi_filter_table_down(efx);
efx->filter_state = NULL;
/*
* If we were called without locking, then it's not safe to free
* the table as others might be using it. So we just WARN, leak
* the memory, and potentially get an inconsistent filter table
* state.
* This should never actually happen.
*/
if (!efx_rwsem_assert_write_locked(&efx->filter_sem))
return;
if (!table)
return;
vfree(table->entry);
kfree(table);
}
static void efx_mcdi_filter_mark_one_old(struct efx_nic *efx, uint16_t *id)
{
struct efx_mcdi_filter_table *table = efx->filter_state;
unsigned int filter_idx;
efx_rwsem_assert_write_locked(&table->lock);
if (*id != EFX_EF10_FILTER_ID_INVALID) {
filter_idx = efx_mcdi_filter_get_unsafe_id(*id);
if (!table->entry[filter_idx].spec)
netif_dbg(efx, drv, efx->net_dev,
"marked null spec old %04x:%04x\n", *id,
filter_idx);
table->entry[filter_idx].spec |= EFX_EF10_FILTER_FLAG_AUTO_OLD;
*id = EFX_EF10_FILTER_ID_INVALID;
}
}
/* Mark old per-VLAN filters that may need to be removed */
static void _efx_mcdi_filter_vlan_mark_old(struct efx_nic *efx,
struct efx_mcdi_filter_vlan *vlan)
{
struct efx_mcdi_filter_table *table = efx->filter_state;
unsigned int i;
for (i = 0; i < table->dev_uc_count; i++)
efx_mcdi_filter_mark_one_old(efx, &vlan->uc[i]);
for (i = 0; i < table->dev_mc_count; i++)
efx_mcdi_filter_mark_one_old(efx, &vlan->mc[i]);
for (i = 0; i < EFX_EF10_NUM_DEFAULT_FILTERS; i++)
efx_mcdi_filter_mark_one_old(efx, &vlan->default_filters[i]);
}
/*
* Mark old filters that may need to be removed.
* Caller must hold efx->filter_sem for read if race against
* efx_mcdi_filter_table_remove() is possible
*/
static void efx_mcdi_filter_mark_old(struct efx_nic *efx)
{
struct efx_mcdi_filter_table *table = efx->filter_state;
struct efx_mcdi_filter_vlan *vlan;
down_write(&table->lock);
list_for_each_entry(vlan, &table->vlan_list, list)
_efx_mcdi_filter_vlan_mark_old(efx, vlan);
up_write(&table->lock);
}
int efx_mcdi_filter_add_vlan(struct efx_nic *efx, u16 vid)
{
struct efx_mcdi_filter_table *table = efx->filter_state;
struct efx_mcdi_filter_vlan *vlan;
unsigned int i;
if (!efx_rwsem_assert_write_locked(&efx->filter_sem))
return -EINVAL;
vlan = efx_mcdi_filter_find_vlan(efx, vid);
if (WARN_ON(vlan)) {
netif_err(efx, drv, efx->net_dev,
"VLAN %u already added\n", vid);
return -EALREADY;
}
vlan = kzalloc(sizeof(*vlan), GFP_KERNEL);
if (!vlan)
return -ENOMEM;
vlan->vid = vid;
for (i = 0; i < ARRAY_SIZE(vlan->uc); i++)
vlan->uc[i] = EFX_EF10_FILTER_ID_INVALID;
for (i = 0; i < ARRAY_SIZE(vlan->mc); i++)
vlan->mc[i] = EFX_EF10_FILTER_ID_INVALID;
for (i = 0; i < EFX_EF10_NUM_DEFAULT_FILTERS; i++)
vlan->default_filters[i] = EFX_EF10_FILTER_ID_INVALID;
list_add_tail(&vlan->list, &table->vlan_list);
if (efx_dev_registered(efx))
efx_mcdi_filter_vlan_sync_rx_mode(efx, vlan);
return 0;
}
static void efx_mcdi_filter_del_vlan_internal(struct efx_nic *efx,
struct efx_mcdi_filter_vlan *vlan)
{
unsigned int i;
/* See comment in efx_mcdi_filter_table_remove() */
if (!efx_rwsem_assert_write_locked(&efx->filter_sem))
return;
list_del(&vlan->list);
for (i = 0; i < ARRAY_SIZE(vlan->uc); i++)
efx_mcdi_filter_remove_unsafe(efx, EFX_FILTER_PRI_AUTO,
vlan->uc[i]);
for (i = 0; i < ARRAY_SIZE(vlan->mc); i++)
efx_mcdi_filter_remove_unsafe(efx, EFX_FILTER_PRI_AUTO,
vlan->mc[i]);
for (i = 0; i < EFX_EF10_NUM_DEFAULT_FILTERS; i++)
if (vlan->default_filters[i] != EFX_EF10_FILTER_ID_INVALID)
efx_mcdi_filter_remove_unsafe(efx, EFX_FILTER_PRI_AUTO,
vlan->default_filters[i]);
kfree(vlan);
}
void efx_mcdi_filter_del_vlan(struct efx_nic *efx, u16 vid)
{
struct efx_mcdi_filter_vlan *vlan;
/* See comment in efx_mcdi_filter_table_remove() */
if (!efx_rwsem_assert_write_locked(&efx->filter_sem))
return;
vlan = efx_mcdi_filter_find_vlan(efx, vid);
if (!vlan) {
netif_err(efx, drv, efx->net_dev,
"VLAN %u not found in filter state\n", vid);
return;
}
efx_mcdi_filter_del_vlan_internal(efx, vlan);
}
struct efx_mcdi_filter_vlan *efx_mcdi_filter_find_vlan(struct efx_nic *efx,
u16 vid)
{
struct efx_mcdi_filter_table *table = efx->filter_state;
struct efx_mcdi_filter_vlan *vlan;
WARN_ON(!rwsem_is_locked(&efx->filter_sem));
list_for_each_entry(vlan, &table->vlan_list, list) {
if (vlan->vid == vid)
return vlan;
}
return NULL;
}
void efx_mcdi_filter_cleanup_vlans(struct efx_nic *efx)
{
struct efx_mcdi_filter_table *table = efx->filter_state;
struct efx_mcdi_filter_vlan *vlan, *next_vlan;
/* See comment in efx_mcdi_filter_table_remove() */
if (!efx_rwsem_assert_write_locked(&efx->filter_sem))
return;
if (!table)
return;
list_for_each_entry_safe(vlan, next_vlan, &table->vlan_list, list)
efx_mcdi_filter_del_vlan_internal(efx, vlan);
}
static void efx_mcdi_filter_uc_addr_list(struct efx_nic *efx)
{
struct efx_mcdi_filter_table *table = efx->filter_state;
struct net_device *net_dev = efx->net_dev;
struct netdev_hw_addr *uc;
unsigned int i;
table->uc_promisc = !!(net_dev->flags & IFF_PROMISC);
ether_addr_copy(table->dev_uc_list[0].addr, net_dev->dev_addr);
i = 1;
netdev_for_each_uc_addr(uc, net_dev) {
if (i >= EFX_EF10_FILTER_DEV_UC_MAX) {
table->uc_promisc = true;
break;
}
ether_addr_copy(table->dev_uc_list[i].addr, uc->addr);
i++;
}
table->dev_uc_count = i;
}
static void efx_mcdi_filter_mc_addr_list(struct efx_nic *efx)
{
struct efx_mcdi_filter_table *table = efx->filter_state;
struct net_device *net_dev = efx->net_dev;
struct netdev_hw_addr *mc;
unsigned int i;
table->mc_overflow = false;
table->mc_promisc = !!(net_dev->flags & (IFF_PROMISC | IFF_ALLMULTI));
i = 0;
netdev_for_each_mc_addr(mc, net_dev) {
if (i >= EFX_EF10_FILTER_DEV_MC_MAX) {
table->mc_promisc = true;
table->mc_overflow = true;
break;
}
ether_addr_copy(table->dev_mc_list[i].addr, mc->addr);
i++;
}
table->dev_mc_count = i;
}
/*
* Caller must hold efx->filter_sem for read if race against
* efx_mcdi_filter_table_remove() is possible
*/
void efx_mcdi_filter_sync_rx_mode(struct efx_nic *efx)
{
struct efx_mcdi_filter_table *table = efx->filter_state;
struct net_device *net_dev = efx->net_dev;
struct efx_mcdi_filter_vlan *vlan;
bool vlan_filter;
if (!efx_dev_registered(efx))
return;
if (!table)
return;
efx_mcdi_filter_mark_old(efx);
/*
* Copy/convert the address lists; add the primary station
* address and broadcast address
*/
netif_addr_lock_bh(net_dev);
efx_mcdi_filter_uc_addr_list(efx);
efx_mcdi_filter_mc_addr_list(efx);
netif_addr_unlock_bh(net_dev);
/*
* If VLAN filtering changes, all old filters are finally removed.
* Do it in advance to avoid conflicts for unicast untagged and
* VLAN 0 tagged filters.
*/
vlan_filter = !!(net_dev->features & NETIF_F_HW_VLAN_CTAG_FILTER);
if (table->vlan_filter != vlan_filter) {
table->vlan_filter = vlan_filter;
efx_mcdi_filter_remove_old(efx);
}
list_for_each_entry(vlan, &table->vlan_list, list)
efx_mcdi_filter_vlan_sync_rx_mode(efx, vlan);
efx_mcdi_filter_remove_old(efx);
table->mc_promisc_last = table->mc_promisc;
}
#ifdef CONFIG_RFS_ACCEL
bool efx_mcdi_filter_rfs_expire_one(struct efx_nic *efx, u32 flow_id,
unsigned int filter_idx)
{
struct efx_filter_spec *spec, saved_spec;
struct efx_mcdi_filter_table *table;
struct efx_arfs_rule *rule = NULL;
bool ret = true, force = false;
u16 arfs_id;
down_read(&efx->filter_sem);
table = efx->filter_state;
down_write(&table->lock);
spec = efx_mcdi_filter_entry_spec(table, filter_idx);
if (!spec || spec->priority != EFX_FILTER_PRI_HINT)
goto out_unlock;
spin_lock_bh(&efx->rps_hash_lock);
if (!efx->rps_hash_table) {
/* In the absence of the table, we always return 0 to ARFS. */
arfs_id = 0;
} else {
rule = efx_rps_hash_find(efx, spec);
if (!rule)
/* ARFS table doesn't know of this filter, so remove it */
goto expire;
arfs_id = rule->arfs_id;
ret = efx_rps_check_rule(rule, filter_idx, &force);
if (force)
goto expire;
if (!ret) {
spin_unlock_bh(&efx->rps_hash_lock);
goto out_unlock;
}
}
if (!rps_may_expire_flow(efx->net_dev, spec->dmaq_id, flow_id, arfs_id))
ret = false;
else if (rule)
rule->filter_id = EFX_ARFS_FILTER_ID_REMOVING;
expire:
saved_spec = *spec; /* remove operation will kfree spec */
spin_unlock_bh(&efx->rps_hash_lock);
/*
* At this point (since we dropped the lock), another thread might queue
* up a fresh insertion request (but the actual insertion will be held
* up by our possession of the filter table lock). In that case, it
* will set rule->filter_id to EFX_ARFS_FILTER_ID_PENDING, meaning that
* the rule is not removed by efx_rps_hash_del() below.
*/
if (ret)
ret = efx_mcdi_filter_remove_internal(efx, 1U << spec->priority,
filter_idx, true) == 0;
/*
* While we can't safely dereference rule (we dropped the lock), we can
* still test it for NULL.
*/
if (ret && rule) {
/* Expiring, so remove entry from ARFS table */
spin_lock_bh(&efx->rps_hash_lock);
efx_rps_hash_del(efx, &saved_spec);
spin_unlock_bh(&efx->rps_hash_lock);
}
out_unlock:
up_write(&table->lock);
up_read(&efx->filter_sem);
return ret;
}
#endif /* CONFIG_RFS_ACCEL */
#define RSS_MODE_HASH_ADDRS (1 << RSS_MODE_HASH_SRC_ADDR_LBN |\
1 << RSS_MODE_HASH_DST_ADDR_LBN)
#define RSS_MODE_HASH_PORTS (1 << RSS_MODE_HASH_SRC_PORT_LBN |\
1 << RSS_MODE_HASH_DST_PORT_LBN)
#define RSS_CONTEXT_FLAGS_DEFAULT (1 << MC_CMD_RSS_CONTEXT_GET_FLAGS_OUT_TOEPLITZ_IPV4_EN_LBN |\
1 << MC_CMD_RSS_CONTEXT_GET_FLAGS_OUT_TOEPLITZ_TCPV4_EN_LBN |\
1 << MC_CMD_RSS_CONTEXT_GET_FLAGS_OUT_TOEPLITZ_IPV6_EN_LBN |\
1 << MC_CMD_RSS_CONTEXT_GET_FLAGS_OUT_TOEPLITZ_TCPV6_EN_LBN |\
(RSS_MODE_HASH_ADDRS | RSS_MODE_HASH_PORTS) << MC_CMD_RSS_CONTEXT_GET_FLAGS_OUT_TCP_IPV4_RSS_MODE_LBN |\
RSS_MODE_HASH_ADDRS << MC_CMD_RSS_CONTEXT_GET_FLAGS_OUT_UDP_IPV4_RSS_MODE_LBN |\
RSS_MODE_HASH_ADDRS << MC_CMD_RSS_CONTEXT_GET_FLAGS_OUT_OTHER_IPV4_RSS_MODE_LBN |\
(RSS_MODE_HASH_ADDRS | RSS_MODE_HASH_PORTS) << MC_CMD_RSS_CONTEXT_GET_FLAGS_OUT_TCP_IPV6_RSS_MODE_LBN |\
RSS_MODE_HASH_ADDRS << MC_CMD_RSS_CONTEXT_GET_FLAGS_OUT_UDP_IPV6_RSS_MODE_LBN |\
RSS_MODE_HASH_ADDRS << MC_CMD_RSS_CONTEXT_GET_FLAGS_OUT_OTHER_IPV6_RSS_MODE_LBN)
int efx_mcdi_get_rss_context_flags(struct efx_nic *efx, u32 context, u32 *flags)
{
/*
* Firmware had a bug (sfc bug 61952) where it would not actually
* fill in the flags field in the response to MC_CMD_RSS_CONTEXT_GET_FLAGS.
* This meant that it would always contain whatever was previously
* in the MCDI buffer. Fortunately, all firmware versions with
* this bug have the same default flags value for a newly-allocated
* RSS context, and the only time we want to get the flags is just
* after allocating. Moreover, the response has a 32-bit hole
* where the context ID would be in the request, so we can use an
* overlength buffer in the request and pre-fill the flags field
* with what we believe the default to be. Thus if the firmware
* has the bug, it will leave our pre-filled value in the flags
* field of the response, and we will get the right answer.
*
* However, this does mean that this function should NOT be used if
* the RSS context flags might not be their defaults - it is ONLY
* reliably correct for a newly-allocated RSS context.
*/
MCDI_DECLARE_BUF(inbuf, MC_CMD_RSS_CONTEXT_GET_FLAGS_OUT_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_RSS_CONTEXT_GET_FLAGS_OUT_LEN);
size_t outlen;
int rc;
/* Check we have a hole for the context ID */
BUILD_BUG_ON(MC_CMD_RSS_CONTEXT_GET_FLAGS_IN_LEN != MC_CMD_RSS_CONTEXT_GET_FLAGS_OUT_FLAGS_OFST);
MCDI_SET_DWORD(inbuf, RSS_CONTEXT_GET_FLAGS_IN_RSS_CONTEXT_ID, context);
MCDI_SET_DWORD(inbuf, RSS_CONTEXT_GET_FLAGS_OUT_FLAGS,
RSS_CONTEXT_FLAGS_DEFAULT);
rc = efx_mcdi_rpc(efx, MC_CMD_RSS_CONTEXT_GET_FLAGS, inbuf,
sizeof(inbuf), outbuf, sizeof(outbuf), &outlen);
if (rc == 0) {
if (outlen < MC_CMD_RSS_CONTEXT_GET_FLAGS_OUT_LEN)
rc = -EIO;
else
*flags = MCDI_DWORD(outbuf, RSS_CONTEXT_GET_FLAGS_OUT_FLAGS);
}
return rc;
}
/*
* Attempt to enable 4-tuple UDP hashing on the specified RSS context.
* If we fail, we just leave the RSS context at its default hash settings,
* which is safe but may slightly reduce performance.
* Defaults are 4-tuple for TCP and 2-tuple for UDP and other-IP, so we
* just need to set the UDP ports flags (for both IP versions).
*/
void efx_mcdi_set_rss_context_flags(struct efx_nic *efx,
struct efx_rss_context *ctx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_RSS_CONTEXT_SET_FLAGS_IN_LEN);
u32 flags;
BUILD_BUG_ON(MC_CMD_RSS_CONTEXT_SET_FLAGS_OUT_LEN != 0);
if (efx_mcdi_get_rss_context_flags(efx, ctx->context_id, &flags) != 0)
return;
MCDI_SET_DWORD(inbuf, RSS_CONTEXT_SET_FLAGS_IN_RSS_CONTEXT_ID,
ctx->context_id);
flags |= RSS_MODE_HASH_PORTS << MC_CMD_RSS_CONTEXT_GET_FLAGS_OUT_UDP_IPV4_RSS_MODE_LBN;
flags |= RSS_MODE_HASH_PORTS << MC_CMD_RSS_CONTEXT_GET_FLAGS_OUT_UDP_IPV6_RSS_MODE_LBN;
MCDI_SET_DWORD(inbuf, RSS_CONTEXT_SET_FLAGS_IN_FLAGS, flags);
if (!efx_mcdi_rpc(efx, MC_CMD_RSS_CONTEXT_SET_FLAGS, inbuf, sizeof(inbuf),
NULL, 0, NULL))
/* Succeeded, so UDP 4-tuple is now enabled */
ctx->rx_hash_udp_4tuple = true;
}
static int efx_mcdi_filter_alloc_rss_context(struct efx_nic *efx, bool exclusive,
struct efx_rss_context *ctx,
unsigned *context_size)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_RSS_CONTEXT_ALLOC_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_RSS_CONTEXT_ALLOC_OUT_LEN);
size_t outlen;
int rc;
u32 alloc_type = exclusive ?
MC_CMD_RSS_CONTEXT_ALLOC_IN_TYPE_EXCLUSIVE :
MC_CMD_RSS_CONTEXT_ALLOC_IN_TYPE_SHARED;
unsigned rss_spread = exclusive ?
efx->rss_spread :
min(rounddown_pow_of_two(efx->rss_spread),
EFX_EF10_MAX_SHARED_RSS_CONTEXT_SIZE);
if (!exclusive && rss_spread == 1) {
ctx->context_id = EFX_MCDI_RSS_CONTEXT_INVALID;
if (context_size)
*context_size = 1;
return 0;
}
if (efx_has_cap(efx, RX_RSS_LIMITED))
return -EOPNOTSUPP;
MCDI_SET_DWORD(inbuf, RSS_CONTEXT_ALLOC_IN_UPSTREAM_PORT_ID,
efx->vport_id);
MCDI_SET_DWORD(inbuf, RSS_CONTEXT_ALLOC_IN_TYPE, alloc_type);
MCDI_SET_DWORD(inbuf, RSS_CONTEXT_ALLOC_IN_NUM_QUEUES, rss_spread);
rc = efx_mcdi_rpc(efx, MC_CMD_RSS_CONTEXT_ALLOC, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc != 0)
return rc;
if (outlen < MC_CMD_RSS_CONTEXT_ALLOC_OUT_LEN)
return -EIO;
ctx->context_id = MCDI_DWORD(outbuf, RSS_CONTEXT_ALLOC_OUT_RSS_CONTEXT_ID);
if (context_size)
*context_size = rss_spread;
if (efx_has_cap(efx, ADDITIONAL_RSS_MODES))
efx_mcdi_set_rss_context_flags(efx, ctx);
return 0;
}
static int efx_mcdi_filter_free_rss_context(struct efx_nic *efx, u32 context)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_RSS_CONTEXT_FREE_IN_LEN);
MCDI_SET_DWORD(inbuf, RSS_CONTEXT_FREE_IN_RSS_CONTEXT_ID,
context);
return efx_mcdi_rpc(efx, MC_CMD_RSS_CONTEXT_FREE, inbuf, sizeof(inbuf),
NULL, 0, NULL);
}
static int efx_mcdi_filter_populate_rss_table(struct efx_nic *efx, u32 context,
const u32 *rx_indir_table, const u8 *key)
{
MCDI_DECLARE_BUF(tablebuf, MC_CMD_RSS_CONTEXT_SET_TABLE_IN_LEN);
MCDI_DECLARE_BUF(keybuf, MC_CMD_RSS_CONTEXT_SET_KEY_IN_LEN);
int i, rc;
MCDI_SET_DWORD(tablebuf, RSS_CONTEXT_SET_TABLE_IN_RSS_CONTEXT_ID,
context);
BUILD_BUG_ON(ARRAY_SIZE(efx->rss_context.rx_indir_table) !=
MC_CMD_RSS_CONTEXT_SET_TABLE_IN_INDIRECTION_TABLE_LEN);
/* This iterates over the length of efx->rss_context.rx_indir_table, but
* copies bytes from rx_indir_table. That's because the latter is a
* pointer rather than an array, but should have the same length.
* The efx->rss_context.rx_hash_key loop below is similar.
*/
for (i = 0; i < ARRAY_SIZE(efx->rss_context.rx_indir_table); ++i)
MCDI_PTR(tablebuf,
RSS_CONTEXT_SET_TABLE_IN_INDIRECTION_TABLE)[i] =
(u8) rx_indir_table[i];
rc = efx_mcdi_rpc(efx, MC_CMD_RSS_CONTEXT_SET_TABLE, tablebuf,
sizeof(tablebuf), NULL, 0, NULL);
if (rc != 0)
return rc;
MCDI_SET_DWORD(keybuf, RSS_CONTEXT_SET_KEY_IN_RSS_CONTEXT_ID,
context);
BUILD_BUG_ON(ARRAY_SIZE(efx->rss_context.rx_hash_key) !=
MC_CMD_RSS_CONTEXT_SET_KEY_IN_TOEPLITZ_KEY_LEN);
for (i = 0; i < ARRAY_SIZE(efx->rss_context.rx_hash_key); ++i)
MCDI_PTR(keybuf, RSS_CONTEXT_SET_KEY_IN_TOEPLITZ_KEY)[i] = key[i];
return efx_mcdi_rpc(efx, MC_CMD_RSS_CONTEXT_SET_KEY, keybuf,
sizeof(keybuf), NULL, 0, NULL);
}
void efx_mcdi_rx_free_indir_table(struct efx_nic *efx)
{
int rc;
if (efx->rss_context.context_id != EFX_MCDI_RSS_CONTEXT_INVALID) {
rc = efx_mcdi_filter_free_rss_context(efx, efx->rss_context.context_id);
WARN_ON(rc != 0);
}
efx->rss_context.context_id = EFX_MCDI_RSS_CONTEXT_INVALID;
}
static int efx_mcdi_filter_rx_push_shared_rss_config(struct efx_nic *efx,
unsigned *context_size)
{
struct efx_mcdi_filter_table *table = efx->filter_state;
int rc = efx_mcdi_filter_alloc_rss_context(efx, false, &efx->rss_context,
context_size);
if (rc != 0)
return rc;
table->rx_rss_context_exclusive = false;
efx_set_default_rx_indir_table(efx, &efx->rss_context);
return 0;
}
static int efx_mcdi_filter_rx_push_exclusive_rss_config(struct efx_nic *efx,
const u32 *rx_indir_table,
const u8 *key)
{
struct efx_mcdi_filter_table *table = efx->filter_state;
u32 old_rx_rss_context = efx->rss_context.context_id;
int rc;
if (efx->rss_context.context_id == EFX_MCDI_RSS_CONTEXT_INVALID ||
!table->rx_rss_context_exclusive) {
rc = efx_mcdi_filter_alloc_rss_context(efx, true, &efx->rss_context,
NULL);
if (rc == -EOPNOTSUPP)
return rc;
else if (rc != 0)
goto fail1;
}
rc = efx_mcdi_filter_populate_rss_table(efx, efx->rss_context.context_id,
rx_indir_table, key);
if (rc != 0)
goto fail2;
if (efx->rss_context.context_id != old_rx_rss_context &&
old_rx_rss_context != EFX_MCDI_RSS_CONTEXT_INVALID)
WARN_ON(efx_mcdi_filter_free_rss_context(efx, old_rx_rss_context) != 0);
table->rx_rss_context_exclusive = true;
if (rx_indir_table != efx->rss_context.rx_indir_table)
memcpy(efx->rss_context.rx_indir_table, rx_indir_table,
sizeof(efx->rss_context.rx_indir_table));
if (key != efx->rss_context.rx_hash_key)
memcpy(efx->rss_context.rx_hash_key, key,
efx->type->rx_hash_key_size);
return 0;
fail2:
if (old_rx_rss_context != efx->rss_context.context_id) {
WARN_ON(efx_mcdi_filter_free_rss_context(efx, efx->rss_context.context_id) != 0);
efx->rss_context.context_id = old_rx_rss_context;
}
fail1:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_rx_push_rss_context_config(struct efx_nic *efx,
struct efx_rss_context *ctx,
const u32 *rx_indir_table,
const u8 *key)
{
int rc;
WARN_ON(!mutex_is_locked(&efx->rss_lock));
if (ctx->context_id == EFX_MCDI_RSS_CONTEXT_INVALID) {
rc = efx_mcdi_filter_alloc_rss_context(efx, true, ctx, NULL);
if (rc)
return rc;
}
if (!rx_indir_table) /* Delete this context */
return efx_mcdi_filter_free_rss_context(efx, ctx->context_id);
rc = efx_mcdi_filter_populate_rss_table(efx, ctx->context_id,
rx_indir_table, key);
if (rc)
return rc;
memcpy(ctx->rx_indir_table, rx_indir_table,
sizeof(efx->rss_context.rx_indir_table));
memcpy(ctx->rx_hash_key, key, efx->type->rx_hash_key_size);
return 0;
}
int efx_mcdi_rx_pull_rss_context_config(struct efx_nic *efx,
struct efx_rss_context *ctx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_RSS_CONTEXT_GET_TABLE_IN_LEN);
MCDI_DECLARE_BUF(tablebuf, MC_CMD_RSS_CONTEXT_GET_TABLE_OUT_LEN);
MCDI_DECLARE_BUF(keybuf, MC_CMD_RSS_CONTEXT_GET_KEY_OUT_LEN);
size_t outlen;
int rc, i;
WARN_ON(!mutex_is_locked(&efx->rss_lock));
BUILD_BUG_ON(MC_CMD_RSS_CONTEXT_GET_TABLE_IN_LEN !=
MC_CMD_RSS_CONTEXT_GET_KEY_IN_LEN);
if (ctx->context_id == EFX_MCDI_RSS_CONTEXT_INVALID)
return -ENOENT;
MCDI_SET_DWORD(inbuf, RSS_CONTEXT_GET_TABLE_IN_RSS_CONTEXT_ID,
ctx->context_id);
BUILD_BUG_ON(ARRAY_SIZE(ctx->rx_indir_table) !=
MC_CMD_RSS_CONTEXT_GET_TABLE_OUT_INDIRECTION_TABLE_LEN);
rc = efx_mcdi_rpc(efx, MC_CMD_RSS_CONTEXT_GET_TABLE, inbuf, sizeof(inbuf),
tablebuf, sizeof(tablebuf), &outlen);
if (rc != 0)
return rc;
if (WARN_ON(outlen != MC_CMD_RSS_CONTEXT_GET_TABLE_OUT_LEN))
return -EIO;
for (i = 0; i < ARRAY_SIZE(ctx->rx_indir_table); i++)
ctx->rx_indir_table[i] = MCDI_PTR(tablebuf,
RSS_CONTEXT_GET_TABLE_OUT_INDIRECTION_TABLE)[i];
MCDI_SET_DWORD(inbuf, RSS_CONTEXT_GET_KEY_IN_RSS_CONTEXT_ID,
ctx->context_id);
BUILD_BUG_ON(ARRAY_SIZE(ctx->rx_hash_key) !=
MC_CMD_RSS_CONTEXT_SET_KEY_IN_TOEPLITZ_KEY_LEN);
rc = efx_mcdi_rpc(efx, MC_CMD_RSS_CONTEXT_GET_KEY, inbuf, sizeof(inbuf),
keybuf, sizeof(keybuf), &outlen);
if (rc != 0)
return rc;
if (WARN_ON(outlen != MC_CMD_RSS_CONTEXT_GET_KEY_OUT_LEN))
return -EIO;
for (i = 0; i < ARRAY_SIZE(ctx->rx_hash_key); ++i)
ctx->rx_hash_key[i] = MCDI_PTR(
keybuf, RSS_CONTEXT_GET_KEY_OUT_TOEPLITZ_KEY)[i];
return 0;
}
int efx_mcdi_rx_pull_rss_config(struct efx_nic *efx)
{
int rc;
mutex_lock(&efx->rss_lock);
rc = efx_mcdi_rx_pull_rss_context_config(efx, &efx->rss_context);
mutex_unlock(&efx->rss_lock);
return rc;
}
void efx_mcdi_rx_restore_rss_contexts(struct efx_nic *efx)
{
struct efx_mcdi_filter_table *table = efx->filter_state;
struct efx_rss_context *ctx;
int rc;
WARN_ON(!mutex_is_locked(&efx->rss_lock));
if (!table->must_restore_rss_contexts)
return;
list_for_each_entry(ctx, &efx->rss_context.list, list) {
/* previous NIC RSS context is gone */
ctx->context_id = EFX_MCDI_RSS_CONTEXT_INVALID;
/* so try to allocate a new one */
rc = efx_mcdi_rx_push_rss_context_config(efx, ctx,
ctx->rx_indir_table,
ctx->rx_hash_key);
if (rc)
netif_warn(efx, probe, efx->net_dev,
"failed to restore RSS context %u, rc=%d"
"; RSS filters may fail to be applied\n",
ctx->user_id, rc);
}
table->must_restore_rss_contexts = false;
}
int efx_mcdi_pf_rx_push_rss_config(struct efx_nic *efx, bool user,
const u32 *rx_indir_table,
const u8 *key)
{
int rc;
if (efx->rss_spread == 1)
return 0;
if (!key)
key = efx->rss_context.rx_hash_key;
rc = efx_mcdi_filter_rx_push_exclusive_rss_config(efx, rx_indir_table, key);
if (rc == -ENOBUFS && !user) {
unsigned context_size;
bool mismatch = false;
size_t i;
for (i = 0;
i < ARRAY_SIZE(efx->rss_context.rx_indir_table) && !mismatch;
i++)
mismatch = rx_indir_table[i] !=
ethtool_rxfh_indir_default(i, efx->rss_spread);
rc = efx_mcdi_filter_rx_push_shared_rss_config(efx, &context_size);
if (rc == 0) {
if (context_size != efx->rss_spread)
netif_warn(efx, probe, efx->net_dev,
"Could not allocate an exclusive RSS"
" context; allocated a shared one of"
" different size."
" Wanted %u, got %u.\n",
efx->rss_spread, context_size);
else if (mismatch)
netif_warn(efx, probe, efx->net_dev,
"Could not allocate an exclusive RSS"
" context; allocated a shared one but"
" could not apply custom"
" indirection.\n");
else
netif_info(efx, probe, efx->net_dev,
"Could not allocate an exclusive RSS"
" context; allocated a shared one.\n");
}
}
return rc;
}
int efx_mcdi_vf_rx_push_rss_config(struct efx_nic *efx, bool user,
const u32 *rx_indir_table
__attribute__ ((unused)),
const u8 *key
__attribute__ ((unused)))
{
if (user)
return -EOPNOTSUPP;
if (efx->rss_context.context_id != EFX_MCDI_RSS_CONTEXT_INVALID)
return 0;
return efx_mcdi_filter_rx_push_shared_rss_config(efx, NULL);
}
int efx_mcdi_push_default_indir_table(struct efx_nic *efx,
unsigned int rss_spread)
{
int rc = 0;
if (efx->rss_spread == rss_spread)
return 0;
efx->rss_spread = rss_spread;
if (!efx->filter_state)
return 0;
efx_mcdi_rx_free_indir_table(efx);
if (rss_spread > 1) {
efx_set_default_rx_indir_table(efx, &efx->rss_context);
rc = efx->type->rx_push_rss_config(efx, false,
efx->rss_context.rx_indir_table, NULL);
}
return rc;
}
|
linux-master
|
drivers/net/ethernet/sfc/mcdi_filters.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2018 Solarflare Communications Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include "net_driver.h"
#include <linux/module.h>
#include <linux/filter.h>
#include "efx_channels.h"
#include "efx.h"
#include "efx_common.h"
#include "tx_common.h"
#include "rx_common.h"
#include "nic.h"
#include "sriov.h"
#include "workarounds.h"
/* This is the first interrupt mode to try out of:
* 0 => MSI-X
* 1 => MSI
* 2 => legacy
*/
unsigned int efx_siena_interrupt_mode = EFX_INT_MODE_MSIX;
/* This is the requested number of CPUs to use for Receive-Side Scaling (RSS),
* i.e. the number of CPUs among which we may distribute simultaneous
* interrupt handling.
*
* Cards without MSI-X will only target one CPU via legacy or MSI interrupt.
* The default (0) means to assign an interrupt to each core.
*/
unsigned int efx_siena_rss_cpus;
static unsigned int irq_adapt_low_thresh = 8000;
module_param(irq_adapt_low_thresh, uint, 0644);
MODULE_PARM_DESC(irq_adapt_low_thresh,
"Threshold score for reducing IRQ moderation");
static unsigned int irq_adapt_high_thresh = 16000;
module_param(irq_adapt_high_thresh, uint, 0644);
MODULE_PARM_DESC(irq_adapt_high_thresh,
"Threshold score for increasing IRQ moderation");
static const struct efx_channel_type efx_default_channel_type;
/*************
* INTERRUPTS
*************/
static unsigned int count_online_cores(struct efx_nic *efx, bool local_node)
{
cpumask_var_t filter_mask;
unsigned int count;
int cpu;
if (unlikely(!zalloc_cpumask_var(&filter_mask, GFP_KERNEL))) {
netif_warn(efx, probe, efx->net_dev,
"RSS disabled due to allocation failure\n");
return 1;
}
cpumask_copy(filter_mask, cpu_online_mask);
if (local_node)
cpumask_and(filter_mask, filter_mask,
cpumask_of_pcibus(efx->pci_dev->bus));
count = 0;
for_each_cpu(cpu, filter_mask) {
++count;
cpumask_andnot(filter_mask, filter_mask, topology_sibling_cpumask(cpu));
}
free_cpumask_var(filter_mask);
return count;
}
static unsigned int efx_wanted_parallelism(struct efx_nic *efx)
{
unsigned int count;
if (efx_siena_rss_cpus) {
count = efx_siena_rss_cpus;
} else {
count = count_online_cores(efx, true);
/* If no online CPUs in local node, fallback to any online CPUs */
if (count == 0)
count = count_online_cores(efx, false);
}
if (count > EFX_MAX_RX_QUEUES) {
netif_cond_dbg(efx, probe, efx->net_dev, !efx_siena_rss_cpus,
warn,
"Reducing number of rx queues from %u to %u.\n",
count, EFX_MAX_RX_QUEUES);
count = EFX_MAX_RX_QUEUES;
}
/* If RSS is requested for the PF *and* VFs then we can't write RSS
* table entries that are inaccessible to VFs
*/
#ifdef CONFIG_SFC_SIENA_SRIOV
if (efx->type->sriov_wanted) {
if (efx->type->sriov_wanted(efx) && efx_vf_size(efx) > 1 &&
count > efx_vf_size(efx)) {
netif_warn(efx, probe, efx->net_dev,
"Reducing number of RSS channels from %u to %u for "
"VF support. Increase vf-msix-limit to use more "
"channels on the PF.\n",
count, efx_vf_size(efx));
count = efx_vf_size(efx);
}
}
#endif
return count;
}
static int efx_allocate_msix_channels(struct efx_nic *efx,
unsigned int max_channels,
unsigned int extra_channels,
unsigned int parallelism)
{
unsigned int n_channels = parallelism;
int vec_count;
int tx_per_ev;
int n_xdp_tx;
int n_xdp_ev;
if (efx_siena_separate_tx_channels)
n_channels *= 2;
n_channels += extra_channels;
/* To allow XDP transmit to happen from arbitrary NAPI contexts
* we allocate a TX queue per CPU. We share event queues across
* multiple tx queues, assuming tx and ev queues are both
* maximum size.
*/
tx_per_ev = EFX_MAX_EVQ_SIZE / EFX_TXQ_MAX_ENT(efx);
tx_per_ev = min(tx_per_ev, EFX_MAX_TXQ_PER_CHANNEL);
n_xdp_tx = num_possible_cpus();
n_xdp_ev = DIV_ROUND_UP(n_xdp_tx, tx_per_ev);
vec_count = pci_msix_vec_count(efx->pci_dev);
if (vec_count < 0)
return vec_count;
max_channels = min_t(unsigned int, vec_count, max_channels);
/* Check resources.
* We need a channel per event queue, plus a VI per tx queue.
* This may be more pessimistic than it needs to be.
*/
if (n_channels >= max_channels) {
efx->xdp_txq_queues_mode = EFX_XDP_TX_QUEUES_BORROWED;
netif_warn(efx, drv, efx->net_dev,
"Insufficient resources for %d XDP event queues (%d other channels, max %d)\n",
n_xdp_ev, n_channels, max_channels);
netif_warn(efx, drv, efx->net_dev,
"XDP_TX and XDP_REDIRECT might decrease device's performance\n");
} else if (n_channels + n_xdp_tx > efx->max_vis) {
efx->xdp_txq_queues_mode = EFX_XDP_TX_QUEUES_BORROWED;
netif_warn(efx, drv, efx->net_dev,
"Insufficient resources for %d XDP TX queues (%d other channels, max VIs %d)\n",
n_xdp_tx, n_channels, efx->max_vis);
netif_warn(efx, drv, efx->net_dev,
"XDP_TX and XDP_REDIRECT might decrease device's performance\n");
} else if (n_channels + n_xdp_ev > max_channels) {
efx->xdp_txq_queues_mode = EFX_XDP_TX_QUEUES_SHARED;
netif_warn(efx, drv, efx->net_dev,
"Insufficient resources for %d XDP event queues (%d other channels, max %d)\n",
n_xdp_ev, n_channels, max_channels);
n_xdp_ev = max_channels - n_channels;
netif_warn(efx, drv, efx->net_dev,
"XDP_TX and XDP_REDIRECT will work with reduced performance (%d cpus/tx_queue)\n",
DIV_ROUND_UP(n_xdp_tx, tx_per_ev * n_xdp_ev));
} else {
efx->xdp_txq_queues_mode = EFX_XDP_TX_QUEUES_DEDICATED;
}
if (efx->xdp_txq_queues_mode != EFX_XDP_TX_QUEUES_BORROWED) {
efx->n_xdp_channels = n_xdp_ev;
efx->xdp_tx_per_channel = tx_per_ev;
efx->xdp_tx_queue_count = n_xdp_tx;
n_channels += n_xdp_ev;
netif_dbg(efx, drv, efx->net_dev,
"Allocating %d TX and %d event queues for XDP\n",
n_xdp_ev * tx_per_ev, n_xdp_ev);
} else {
efx->n_xdp_channels = 0;
efx->xdp_tx_per_channel = 0;
efx->xdp_tx_queue_count = n_xdp_tx;
}
if (vec_count < n_channels) {
netif_err(efx, drv, efx->net_dev,
"WARNING: Insufficient MSI-X vectors available (%d < %u).\n",
vec_count, n_channels);
netif_err(efx, drv, efx->net_dev,
"WARNING: Performance may be reduced.\n");
n_channels = vec_count;
}
n_channels = min(n_channels, max_channels);
efx->n_channels = n_channels;
/* Ignore XDP tx channels when creating rx channels. */
n_channels -= efx->n_xdp_channels;
if (efx_siena_separate_tx_channels) {
efx->n_tx_channels =
min(max(n_channels / 2, 1U),
efx->max_tx_channels);
efx->tx_channel_offset =
n_channels - efx->n_tx_channels;
efx->n_rx_channels =
max(n_channels -
efx->n_tx_channels, 1U);
} else {
efx->n_tx_channels = min(n_channels, efx->max_tx_channels);
efx->tx_channel_offset = 0;
efx->n_rx_channels = n_channels;
}
efx->n_rx_channels = min(efx->n_rx_channels, parallelism);
efx->n_tx_channels = min(efx->n_tx_channels, parallelism);
efx->xdp_channel_offset = n_channels;
netif_dbg(efx, drv, efx->net_dev,
"Allocating %u RX channels\n",
efx->n_rx_channels);
return efx->n_channels;
}
/* Probe the number and type of interrupts we are able to obtain, and
* the resulting numbers of channels and RX queues.
*/
int efx_siena_probe_interrupts(struct efx_nic *efx)
{
unsigned int extra_channels = 0;
unsigned int rss_spread;
unsigned int i, j;
int rc;
for (i = 0; i < EFX_MAX_EXTRA_CHANNELS; i++)
if (efx->extra_channel_type[i])
++extra_channels;
if (efx->interrupt_mode == EFX_INT_MODE_MSIX) {
unsigned int parallelism = efx_wanted_parallelism(efx);
struct msix_entry xentries[EFX_MAX_CHANNELS];
unsigned int n_channels;
rc = efx_allocate_msix_channels(efx, efx->max_channels,
extra_channels, parallelism);
if (rc >= 0) {
n_channels = rc;
for (i = 0; i < n_channels; i++)
xentries[i].entry = i;
rc = pci_enable_msix_range(efx->pci_dev, xentries, 1,
n_channels);
}
if (rc < 0) {
/* Fall back to single channel MSI */
netif_err(efx, drv, efx->net_dev,
"could not enable MSI-X\n");
if (efx->type->min_interrupt_mode >= EFX_INT_MODE_MSI)
efx->interrupt_mode = EFX_INT_MODE_MSI;
else
return rc;
} else if (rc < n_channels) {
netif_err(efx, drv, efx->net_dev,
"WARNING: Insufficient MSI-X vectors"
" available (%d < %u).\n", rc, n_channels);
netif_err(efx, drv, efx->net_dev,
"WARNING: Performance may be reduced.\n");
n_channels = rc;
}
if (rc > 0) {
for (i = 0; i < efx->n_channels; i++)
efx_get_channel(efx, i)->irq =
xentries[i].vector;
}
}
/* Try single interrupt MSI */
if (efx->interrupt_mode == EFX_INT_MODE_MSI) {
efx->n_channels = 1;
efx->n_rx_channels = 1;
efx->n_tx_channels = 1;
efx->tx_channel_offset = 0;
efx->n_xdp_channels = 0;
efx->xdp_channel_offset = efx->n_channels;
efx->xdp_txq_queues_mode = EFX_XDP_TX_QUEUES_BORROWED;
rc = pci_enable_msi(efx->pci_dev);
if (rc == 0) {
efx_get_channel(efx, 0)->irq = efx->pci_dev->irq;
} else {
netif_err(efx, drv, efx->net_dev,
"could not enable MSI\n");
if (efx->type->min_interrupt_mode >= EFX_INT_MODE_LEGACY)
efx->interrupt_mode = EFX_INT_MODE_LEGACY;
else
return rc;
}
}
/* Assume legacy interrupts */
if (efx->interrupt_mode == EFX_INT_MODE_LEGACY) {
efx->n_channels = 1 + (efx_siena_separate_tx_channels ? 1 : 0);
efx->n_rx_channels = 1;
efx->n_tx_channels = 1;
efx->tx_channel_offset = efx_siena_separate_tx_channels ? 1 : 0;
efx->n_xdp_channels = 0;
efx->xdp_channel_offset = efx->n_channels;
efx->xdp_txq_queues_mode = EFX_XDP_TX_QUEUES_BORROWED;
efx->legacy_irq = efx->pci_dev->irq;
}
/* Assign extra channels if possible, before XDP channels */
efx->n_extra_tx_channels = 0;
j = efx->xdp_channel_offset;
for (i = 0; i < EFX_MAX_EXTRA_CHANNELS; i++) {
if (!efx->extra_channel_type[i])
continue;
if (j <= efx->tx_channel_offset + efx->n_tx_channels) {
efx->extra_channel_type[i]->handle_no_channel(efx);
} else {
--j;
efx_get_channel(efx, j)->type =
efx->extra_channel_type[i];
if (efx_channel_has_tx_queues(efx_get_channel(efx, j)))
efx->n_extra_tx_channels++;
}
}
rss_spread = efx->n_rx_channels;
/* RSS might be usable on VFs even if it is disabled on the PF */
#ifdef CONFIG_SFC_SIENA_SRIOV
if (efx->type->sriov_wanted) {
efx->rss_spread = ((rss_spread > 1 ||
!efx->type->sriov_wanted(efx)) ?
rss_spread : efx_vf_size(efx));
return 0;
}
#endif
efx->rss_spread = rss_spread;
return 0;
}
#if defined(CONFIG_SMP)
void efx_siena_set_interrupt_affinity(struct efx_nic *efx)
{
const struct cpumask *numa_mask = cpumask_of_pcibus(efx->pci_dev->bus);
struct efx_channel *channel;
unsigned int cpu;
/* If no online CPUs in local node, fallback to any online CPU */
if (cpumask_first_and(cpu_online_mask, numa_mask) >= nr_cpu_ids)
numa_mask = cpu_online_mask;
cpu = -1;
efx_for_each_channel(channel, efx) {
cpu = cpumask_next_and(cpu, cpu_online_mask, numa_mask);
if (cpu >= nr_cpu_ids)
cpu = cpumask_first_and(cpu_online_mask, numa_mask);
irq_set_affinity_hint(channel->irq, cpumask_of(cpu));
}
}
void efx_siena_clear_interrupt_affinity(struct efx_nic *efx)
{
struct efx_channel *channel;
efx_for_each_channel(channel, efx)
irq_set_affinity_hint(channel->irq, NULL);
}
#else
void
efx_siena_set_interrupt_affinity(struct efx_nic *efx __always_unused)
{
}
void
efx_siena_clear_interrupt_affinity(struct efx_nic *efx __always_unused)
{
}
#endif /* CONFIG_SMP */
void efx_siena_remove_interrupts(struct efx_nic *efx)
{
struct efx_channel *channel;
/* Remove MSI/MSI-X interrupts */
efx_for_each_channel(channel, efx)
channel->irq = 0;
pci_disable_msi(efx->pci_dev);
pci_disable_msix(efx->pci_dev);
/* Remove legacy interrupt */
efx->legacy_irq = 0;
}
/***************
* EVENT QUEUES
***************/
/* Create event queue
* Event queue memory allocations are done only once. If the channel
* is reset, the memory buffer will be reused; this guards against
* errors during channel reset and also simplifies interrupt handling.
*/
static int efx_probe_eventq(struct efx_channel *channel)
{
struct efx_nic *efx = channel->efx;
unsigned long entries;
netif_dbg(efx, probe, efx->net_dev,
"chan %d create event queue\n", channel->channel);
/* Build an event queue with room for one event per tx and rx buffer,
* plus some extra for link state events and MCDI completions.
*/
entries = roundup_pow_of_two(efx->rxq_entries + efx->txq_entries + 128);
EFX_WARN_ON_PARANOID(entries > EFX_MAX_EVQ_SIZE);
channel->eventq_mask = max(entries, EFX_MIN_EVQ_SIZE) - 1;
return efx_nic_probe_eventq(channel);
}
/* Prepare channel's event queue */
static int efx_init_eventq(struct efx_channel *channel)
{
struct efx_nic *efx = channel->efx;
int rc;
EFX_WARN_ON_PARANOID(channel->eventq_init);
netif_dbg(efx, drv, efx->net_dev,
"chan %d init event queue\n", channel->channel);
rc = efx_nic_init_eventq(channel);
if (rc == 0) {
efx->type->push_irq_moderation(channel);
channel->eventq_read_ptr = 0;
channel->eventq_init = true;
}
return rc;
}
/* Enable event queue processing and NAPI */
void efx_siena_start_eventq(struct efx_channel *channel)
{
netif_dbg(channel->efx, ifup, channel->efx->net_dev,
"chan %d start event queue\n", channel->channel);
/* Make sure the NAPI handler sees the enabled flag set */
channel->enabled = true;
smp_wmb();
napi_enable(&channel->napi_str);
efx_nic_eventq_read_ack(channel);
}
/* Disable event queue processing and NAPI */
void efx_siena_stop_eventq(struct efx_channel *channel)
{
if (!channel->enabled)
return;
napi_disable(&channel->napi_str);
channel->enabled = false;
}
static void efx_fini_eventq(struct efx_channel *channel)
{
if (!channel->eventq_init)
return;
netif_dbg(channel->efx, drv, channel->efx->net_dev,
"chan %d fini event queue\n", channel->channel);
efx_nic_fini_eventq(channel);
channel->eventq_init = false;
}
static void efx_remove_eventq(struct efx_channel *channel)
{
netif_dbg(channel->efx, drv, channel->efx->net_dev,
"chan %d remove event queue\n", channel->channel);
efx_nic_remove_eventq(channel);
}
/**************************************************************************
*
* Channel handling
*
*************************************************************************/
#ifdef CONFIG_RFS_ACCEL
static void efx_filter_rfs_expire(struct work_struct *data)
{
struct delayed_work *dwork = to_delayed_work(data);
struct efx_channel *channel;
unsigned int time, quota;
channel = container_of(dwork, struct efx_channel, filter_work);
time = jiffies - channel->rfs_last_expiry;
quota = channel->rfs_filter_count * time / (30 * HZ);
if (quota >= 20 && __efx_siena_filter_rfs_expire(channel,
min(channel->rfs_filter_count, quota)))
channel->rfs_last_expiry += time;
/* Ensure we do more work eventually even if NAPI poll is not happening */
schedule_delayed_work(dwork, 30 * HZ);
}
#endif
/* Allocate and initialise a channel structure. */
static struct efx_channel *efx_alloc_channel(struct efx_nic *efx, int i)
{
struct efx_rx_queue *rx_queue;
struct efx_tx_queue *tx_queue;
struct efx_channel *channel;
int j;
channel = kzalloc(sizeof(*channel), GFP_KERNEL);
if (!channel)
return NULL;
channel->efx = efx;
channel->channel = i;
channel->type = &efx_default_channel_type;
for (j = 0; j < EFX_MAX_TXQ_PER_CHANNEL; j++) {
tx_queue = &channel->tx_queue[j];
tx_queue->efx = efx;
tx_queue->queue = -1;
tx_queue->label = j;
tx_queue->channel = channel;
}
#ifdef CONFIG_RFS_ACCEL
INIT_DELAYED_WORK(&channel->filter_work, efx_filter_rfs_expire);
#endif
rx_queue = &channel->rx_queue;
rx_queue->efx = efx;
timer_setup(&rx_queue->slow_fill, efx_siena_rx_slow_fill, 0);
return channel;
}
int efx_siena_init_channels(struct efx_nic *efx)
{
unsigned int i;
for (i = 0; i < EFX_MAX_CHANNELS; i++) {
efx->channel[i] = efx_alloc_channel(efx, i);
if (!efx->channel[i])
return -ENOMEM;
efx->msi_context[i].efx = efx;
efx->msi_context[i].index = i;
}
/* Higher numbered interrupt modes are less capable! */
efx->interrupt_mode = min(efx->type->min_interrupt_mode,
efx_siena_interrupt_mode);
efx->max_channels = EFX_MAX_CHANNELS;
efx->max_tx_channels = EFX_MAX_CHANNELS;
return 0;
}
void efx_siena_fini_channels(struct efx_nic *efx)
{
unsigned int i;
for (i = 0; i < EFX_MAX_CHANNELS; i++)
if (efx->channel[i]) {
kfree(efx->channel[i]);
efx->channel[i] = NULL;
}
}
/* Allocate and initialise a channel structure, copying parameters
* (but not resources) from an old channel structure.
*/
static
struct efx_channel *efx_copy_channel(const struct efx_channel *old_channel)
{
struct efx_rx_queue *rx_queue;
struct efx_tx_queue *tx_queue;
struct efx_channel *channel;
int j;
channel = kmalloc(sizeof(*channel), GFP_KERNEL);
if (!channel)
return NULL;
*channel = *old_channel;
channel->napi_dev = NULL;
INIT_HLIST_NODE(&channel->napi_str.napi_hash_node);
channel->napi_str.napi_id = 0;
channel->napi_str.state = 0;
memset(&channel->eventq, 0, sizeof(channel->eventq));
for (j = 0; j < EFX_MAX_TXQ_PER_CHANNEL; j++) {
tx_queue = &channel->tx_queue[j];
if (tx_queue->channel)
tx_queue->channel = channel;
tx_queue->buffer = NULL;
tx_queue->cb_page = NULL;
memset(&tx_queue->txd, 0, sizeof(tx_queue->txd));
}
rx_queue = &channel->rx_queue;
rx_queue->buffer = NULL;
memset(&rx_queue->rxd, 0, sizeof(rx_queue->rxd));
timer_setup(&rx_queue->slow_fill, efx_siena_rx_slow_fill, 0);
#ifdef CONFIG_RFS_ACCEL
INIT_DELAYED_WORK(&channel->filter_work, efx_filter_rfs_expire);
#endif
return channel;
}
static int efx_probe_channel(struct efx_channel *channel)
{
struct efx_tx_queue *tx_queue;
struct efx_rx_queue *rx_queue;
int rc;
netif_dbg(channel->efx, probe, channel->efx->net_dev,
"creating channel %d\n", channel->channel);
rc = channel->type->pre_probe(channel);
if (rc)
goto fail;
rc = efx_probe_eventq(channel);
if (rc)
goto fail;
efx_for_each_channel_tx_queue(tx_queue, channel) {
rc = efx_siena_probe_tx_queue(tx_queue);
if (rc)
goto fail;
}
efx_for_each_channel_rx_queue(rx_queue, channel) {
rc = efx_siena_probe_rx_queue(rx_queue);
if (rc)
goto fail;
}
channel->rx_list = NULL;
return 0;
fail:
efx_siena_remove_channel(channel);
return rc;
}
static void efx_get_channel_name(struct efx_channel *channel, char *buf,
size_t len)
{
struct efx_nic *efx = channel->efx;
const char *type;
int number;
number = channel->channel;
if (number >= efx->xdp_channel_offset &&
!WARN_ON_ONCE(!efx->n_xdp_channels)) {
type = "-xdp";
number -= efx->xdp_channel_offset;
} else if (efx->tx_channel_offset == 0) {
type = "";
} else if (number < efx->tx_channel_offset) {
type = "-rx";
} else {
type = "-tx";
number -= efx->tx_channel_offset;
}
snprintf(buf, len, "%s%s-%d", efx->name, type, number);
}
void efx_siena_set_channel_names(struct efx_nic *efx)
{
struct efx_channel *channel;
efx_for_each_channel(channel, efx)
channel->type->get_name(channel,
efx->msi_context[channel->channel].name,
sizeof(efx->msi_context[0].name));
}
int efx_siena_probe_channels(struct efx_nic *efx)
{
struct efx_channel *channel;
int rc;
/* Restart special buffer allocation */
efx->next_buffer_table = 0;
/* Probe channels in reverse, so that any 'extra' channels
* use the start of the buffer table. This allows the traffic
* channels to be resized without moving them or wasting the
* entries before them.
*/
efx_for_each_channel_rev(channel, efx) {
rc = efx_probe_channel(channel);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"failed to create channel %d\n",
channel->channel);
goto fail;
}
}
efx_siena_set_channel_names(efx);
return 0;
fail:
efx_siena_remove_channels(efx);
return rc;
}
void efx_siena_remove_channel(struct efx_channel *channel)
{
struct efx_tx_queue *tx_queue;
struct efx_rx_queue *rx_queue;
netif_dbg(channel->efx, drv, channel->efx->net_dev,
"destroy chan %d\n", channel->channel);
efx_for_each_channel_rx_queue(rx_queue, channel)
efx_siena_remove_rx_queue(rx_queue);
efx_for_each_channel_tx_queue(tx_queue, channel)
efx_siena_remove_tx_queue(tx_queue);
efx_remove_eventq(channel);
channel->type->post_remove(channel);
}
void efx_siena_remove_channels(struct efx_nic *efx)
{
struct efx_channel *channel;
efx_for_each_channel(channel, efx)
efx_siena_remove_channel(channel);
kfree(efx->xdp_tx_queues);
}
static int efx_set_xdp_tx_queue(struct efx_nic *efx, int xdp_queue_number,
struct efx_tx_queue *tx_queue)
{
if (xdp_queue_number >= efx->xdp_tx_queue_count)
return -EINVAL;
netif_dbg(efx, drv, efx->net_dev,
"Channel %u TXQ %u is XDP %u, HW %u\n",
tx_queue->channel->channel, tx_queue->label,
xdp_queue_number, tx_queue->queue);
efx->xdp_tx_queues[xdp_queue_number] = tx_queue;
return 0;
}
static void efx_set_xdp_channels(struct efx_nic *efx)
{
struct efx_tx_queue *tx_queue;
struct efx_channel *channel;
unsigned int next_queue = 0;
int xdp_queue_number = 0;
int rc;
/* We need to mark which channels really have RX and TX
* queues, and adjust the TX queue numbers if we have separate
* RX-only and TX-only channels.
*/
efx_for_each_channel(channel, efx) {
if (channel->channel < efx->tx_channel_offset)
continue;
if (efx_channel_is_xdp_tx(channel)) {
efx_for_each_channel_tx_queue(tx_queue, channel) {
tx_queue->queue = next_queue++;
rc = efx_set_xdp_tx_queue(efx, xdp_queue_number,
tx_queue);
if (rc == 0)
xdp_queue_number++;
}
} else {
efx_for_each_channel_tx_queue(tx_queue, channel) {
tx_queue->queue = next_queue++;
netif_dbg(efx, drv, efx->net_dev,
"Channel %u TXQ %u is HW %u\n",
channel->channel, tx_queue->label,
tx_queue->queue);
}
/* If XDP is borrowing queues from net stack, it must
* use the queue with no csum offload, which is the
* first one of the channel
* (note: tx_queue_by_type is not initialized yet)
*/
if (efx->xdp_txq_queues_mode ==
EFX_XDP_TX_QUEUES_BORROWED) {
tx_queue = &channel->tx_queue[0];
rc = efx_set_xdp_tx_queue(efx, xdp_queue_number,
tx_queue);
if (rc == 0)
xdp_queue_number++;
}
}
}
WARN_ON(efx->xdp_txq_queues_mode == EFX_XDP_TX_QUEUES_DEDICATED &&
xdp_queue_number != efx->xdp_tx_queue_count);
WARN_ON(efx->xdp_txq_queues_mode != EFX_XDP_TX_QUEUES_DEDICATED &&
xdp_queue_number > efx->xdp_tx_queue_count);
/* If we have more CPUs than assigned XDP TX queues, assign the already
* existing queues to the exceeding CPUs
*/
next_queue = 0;
while (xdp_queue_number < efx->xdp_tx_queue_count) {
tx_queue = efx->xdp_tx_queues[next_queue++];
rc = efx_set_xdp_tx_queue(efx, xdp_queue_number, tx_queue);
if (rc == 0)
xdp_queue_number++;
}
}
static int efx_soft_enable_interrupts(struct efx_nic *efx);
static void efx_soft_disable_interrupts(struct efx_nic *efx);
static void efx_init_napi_channel(struct efx_channel *channel);
static void efx_fini_napi_channel(struct efx_channel *channel);
int efx_siena_realloc_channels(struct efx_nic *efx, u32 rxq_entries,
u32 txq_entries)
{
struct efx_channel *other_channel[EFX_MAX_CHANNELS], *channel;
unsigned int i, next_buffer_table = 0;
u32 old_rxq_entries, old_txq_entries;
int rc, rc2;
rc = efx_check_disabled(efx);
if (rc)
return rc;
/* Not all channels should be reallocated. We must avoid
* reallocating their buffer table entries.
*/
efx_for_each_channel(channel, efx) {
struct efx_rx_queue *rx_queue;
struct efx_tx_queue *tx_queue;
if (channel->type->copy)
continue;
next_buffer_table = max(next_buffer_table,
channel->eventq.index +
channel->eventq.entries);
efx_for_each_channel_rx_queue(rx_queue, channel)
next_buffer_table = max(next_buffer_table,
rx_queue->rxd.index +
rx_queue->rxd.entries);
efx_for_each_channel_tx_queue(tx_queue, channel)
next_buffer_table = max(next_buffer_table,
tx_queue->txd.index +
tx_queue->txd.entries);
}
efx_device_detach_sync(efx);
efx_siena_stop_all(efx);
efx_soft_disable_interrupts(efx);
/* Clone channels (where possible) */
memset(other_channel, 0, sizeof(other_channel));
for (i = 0; i < efx->n_channels; i++) {
channel = efx->channel[i];
if (channel->type->copy)
channel = channel->type->copy(channel);
if (!channel) {
rc = -ENOMEM;
goto out;
}
other_channel[i] = channel;
}
/* Swap entry counts and channel pointers */
old_rxq_entries = efx->rxq_entries;
old_txq_entries = efx->txq_entries;
efx->rxq_entries = rxq_entries;
efx->txq_entries = txq_entries;
for (i = 0; i < efx->n_channels; i++)
swap(efx->channel[i], other_channel[i]);
/* Restart buffer table allocation */
efx->next_buffer_table = next_buffer_table;
for (i = 0; i < efx->n_channels; i++) {
channel = efx->channel[i];
if (!channel->type->copy)
continue;
rc = efx_probe_channel(channel);
if (rc)
goto rollback;
efx_init_napi_channel(efx->channel[i]);
}
efx_set_xdp_channels(efx);
out:
/* Destroy unused channel structures */
for (i = 0; i < efx->n_channels; i++) {
channel = other_channel[i];
if (channel && channel->type->copy) {
efx_fini_napi_channel(channel);
efx_siena_remove_channel(channel);
kfree(channel);
}
}
rc2 = efx_soft_enable_interrupts(efx);
if (rc2) {
rc = rc ? rc : rc2;
netif_err(efx, drv, efx->net_dev,
"unable to restart interrupts on channel reallocation\n");
efx_siena_schedule_reset(efx, RESET_TYPE_DISABLE);
} else {
efx_siena_start_all(efx);
efx_device_attach_if_not_resetting(efx);
}
return rc;
rollback:
/* Swap back */
efx->rxq_entries = old_rxq_entries;
efx->txq_entries = old_txq_entries;
for (i = 0; i < efx->n_channels; i++)
swap(efx->channel[i], other_channel[i]);
goto out;
}
int efx_siena_set_channels(struct efx_nic *efx)
{
struct efx_channel *channel;
int rc;
if (efx->xdp_tx_queue_count) {
EFX_WARN_ON_PARANOID(efx->xdp_tx_queues);
/* Allocate array for XDP TX queue lookup. */
efx->xdp_tx_queues = kcalloc(efx->xdp_tx_queue_count,
sizeof(*efx->xdp_tx_queues),
GFP_KERNEL);
if (!efx->xdp_tx_queues)
return -ENOMEM;
}
efx_for_each_channel(channel, efx) {
if (channel->channel < efx->n_rx_channels)
channel->rx_queue.core_index = channel->channel;
else
channel->rx_queue.core_index = -1;
}
efx_set_xdp_channels(efx);
rc = netif_set_real_num_tx_queues(efx->net_dev, efx->n_tx_channels);
if (rc)
return rc;
return netif_set_real_num_rx_queues(efx->net_dev, efx->n_rx_channels);
}
static bool efx_default_channel_want_txqs(struct efx_channel *channel)
{
return channel->channel - channel->efx->tx_channel_offset <
channel->efx->n_tx_channels;
}
/*************
* START/STOP
*************/
static int efx_soft_enable_interrupts(struct efx_nic *efx)
{
struct efx_channel *channel, *end_channel;
int rc;
BUG_ON(efx->state == STATE_DISABLED);
efx->irq_soft_enabled = true;
smp_wmb();
efx_for_each_channel(channel, efx) {
if (!channel->type->keep_eventq) {
rc = efx_init_eventq(channel);
if (rc)
goto fail;
}
efx_siena_start_eventq(channel);
}
efx_siena_mcdi_mode_event(efx);
return 0;
fail:
end_channel = channel;
efx_for_each_channel(channel, efx) {
if (channel == end_channel)
break;
efx_siena_stop_eventq(channel);
if (!channel->type->keep_eventq)
efx_fini_eventq(channel);
}
return rc;
}
static void efx_soft_disable_interrupts(struct efx_nic *efx)
{
struct efx_channel *channel;
if (efx->state == STATE_DISABLED)
return;
efx_siena_mcdi_mode_poll(efx);
efx->irq_soft_enabled = false;
smp_wmb();
if (efx->legacy_irq)
synchronize_irq(efx->legacy_irq);
efx_for_each_channel(channel, efx) {
if (channel->irq)
synchronize_irq(channel->irq);
efx_siena_stop_eventq(channel);
if (!channel->type->keep_eventq)
efx_fini_eventq(channel);
}
/* Flush the asynchronous MCDI request queue */
efx_siena_mcdi_flush_async(efx);
}
int efx_siena_enable_interrupts(struct efx_nic *efx)
{
struct efx_channel *channel, *end_channel;
int rc;
/* TODO: Is this really a bug? */
BUG_ON(efx->state == STATE_DISABLED);
if (efx->eeh_disabled_legacy_irq) {
enable_irq(efx->legacy_irq);
efx->eeh_disabled_legacy_irq = false;
}
efx->type->irq_enable_master(efx);
efx_for_each_channel(channel, efx) {
if (channel->type->keep_eventq) {
rc = efx_init_eventq(channel);
if (rc)
goto fail;
}
}
rc = efx_soft_enable_interrupts(efx);
if (rc)
goto fail;
return 0;
fail:
end_channel = channel;
efx_for_each_channel(channel, efx) {
if (channel == end_channel)
break;
if (channel->type->keep_eventq)
efx_fini_eventq(channel);
}
efx->type->irq_disable_non_ev(efx);
return rc;
}
void efx_siena_disable_interrupts(struct efx_nic *efx)
{
struct efx_channel *channel;
efx_soft_disable_interrupts(efx);
efx_for_each_channel(channel, efx) {
if (channel->type->keep_eventq)
efx_fini_eventq(channel);
}
efx->type->irq_disable_non_ev(efx);
}
void efx_siena_start_channels(struct efx_nic *efx)
{
struct efx_tx_queue *tx_queue;
struct efx_rx_queue *rx_queue;
struct efx_channel *channel;
efx_for_each_channel_rev(channel, efx) {
efx_for_each_channel_tx_queue(tx_queue, channel) {
efx_siena_init_tx_queue(tx_queue);
atomic_inc(&efx->active_queues);
}
efx_for_each_channel_rx_queue(rx_queue, channel) {
efx_siena_init_rx_queue(rx_queue);
atomic_inc(&efx->active_queues);
efx_siena_stop_eventq(channel);
efx_siena_fast_push_rx_descriptors(rx_queue, false);
efx_siena_start_eventq(channel);
}
WARN_ON(channel->rx_pkt_n_frags);
}
}
void efx_siena_stop_channels(struct efx_nic *efx)
{
struct efx_tx_queue *tx_queue;
struct efx_rx_queue *rx_queue;
struct efx_channel *channel;
int rc = 0;
/* Stop RX refill */
efx_for_each_channel(channel, efx) {
efx_for_each_channel_rx_queue(rx_queue, channel)
rx_queue->refill_enabled = false;
}
efx_for_each_channel(channel, efx) {
/* RX packet processing is pipelined, so wait for the
* NAPI handler to complete. At least event queue 0
* might be kept active by non-data events, so don't
* use napi_synchronize() but actually disable NAPI
* temporarily.
*/
if (efx_channel_has_rx_queue(channel)) {
efx_siena_stop_eventq(channel);
efx_siena_start_eventq(channel);
}
}
if (efx->type->fini_dmaq)
rc = efx->type->fini_dmaq(efx);
if (rc) {
netif_err(efx, drv, efx->net_dev, "failed to flush queues\n");
} else {
netif_dbg(efx, drv, efx->net_dev,
"successfully flushed all queues\n");
}
efx_for_each_channel(channel, efx) {
efx_for_each_channel_rx_queue(rx_queue, channel)
efx_siena_fini_rx_queue(rx_queue);
efx_for_each_channel_tx_queue(tx_queue, channel)
efx_siena_fini_tx_queue(tx_queue);
}
}
/**************************************************************************
*
* NAPI interface
*
*************************************************************************/
/* Process channel's event queue
*
* This function is responsible for processing the event queue of a
* single channel. The caller must guarantee that this function will
* never be concurrently called more than once on the same channel,
* though different channels may be being processed concurrently.
*/
static int efx_process_channel(struct efx_channel *channel, int budget)
{
struct efx_tx_queue *tx_queue;
struct list_head rx_list;
int spent;
if (unlikely(!channel->enabled))
return 0;
/* Prepare the batch receive list */
EFX_WARN_ON_PARANOID(channel->rx_list != NULL);
INIT_LIST_HEAD(&rx_list);
channel->rx_list = &rx_list;
efx_for_each_channel_tx_queue(tx_queue, channel) {
tx_queue->pkts_compl = 0;
tx_queue->bytes_compl = 0;
}
spent = efx_nic_process_eventq(channel, budget);
if (spent && efx_channel_has_rx_queue(channel)) {
struct efx_rx_queue *rx_queue =
efx_channel_get_rx_queue(channel);
efx_rx_flush_packet(channel);
efx_siena_fast_push_rx_descriptors(rx_queue, true);
}
/* Update BQL */
efx_for_each_channel_tx_queue(tx_queue, channel) {
if (tx_queue->bytes_compl) {
netdev_tx_completed_queue(tx_queue->core_txq,
tx_queue->pkts_compl,
tx_queue->bytes_compl);
}
}
/* Receive any packets we queued up */
netif_receive_skb_list(channel->rx_list);
channel->rx_list = NULL;
return spent;
}
static void efx_update_irq_mod(struct efx_nic *efx, struct efx_channel *channel)
{
int step = efx->irq_mod_step_us;
if (channel->irq_mod_score < irq_adapt_low_thresh) {
if (channel->irq_moderation_us > step) {
channel->irq_moderation_us -= step;
efx->type->push_irq_moderation(channel);
}
} else if (channel->irq_mod_score > irq_adapt_high_thresh) {
if (channel->irq_moderation_us <
efx->irq_rx_moderation_us) {
channel->irq_moderation_us += step;
efx->type->push_irq_moderation(channel);
}
}
channel->irq_count = 0;
channel->irq_mod_score = 0;
}
/* NAPI poll handler
*
* NAPI guarantees serialisation of polls of the same device, which
* provides the guarantee required by efx_process_channel().
*/
static int efx_poll(struct napi_struct *napi, int budget)
{
struct efx_channel *channel =
container_of(napi, struct efx_channel, napi_str);
struct efx_nic *efx = channel->efx;
#ifdef CONFIG_RFS_ACCEL
unsigned int time;
#endif
int spent;
netif_vdbg(efx, intr, efx->net_dev,
"channel %d NAPI poll executing on CPU %d\n",
channel->channel, raw_smp_processor_id());
spent = efx_process_channel(channel, budget);
xdp_do_flush_map();
if (spent < budget) {
if (efx_channel_has_rx_queue(channel) &&
efx->irq_rx_adaptive &&
unlikely(++channel->irq_count == 1000)) {
efx_update_irq_mod(efx, channel);
}
#ifdef CONFIG_RFS_ACCEL
/* Perhaps expire some ARFS filters */
time = jiffies - channel->rfs_last_expiry;
/* Would our quota be >= 20? */
if (channel->rfs_filter_count * time >= 600 * HZ)
mod_delayed_work(system_wq, &channel->filter_work, 0);
#endif
/* There is no race here; although napi_disable() will
* only wait for napi_complete(), this isn't a problem
* since efx_nic_eventq_read_ack() will have no effect if
* interrupts have already been disabled.
*/
if (napi_complete_done(napi, spent))
efx_nic_eventq_read_ack(channel);
}
return spent;
}
static void efx_init_napi_channel(struct efx_channel *channel)
{
struct efx_nic *efx = channel->efx;
channel->napi_dev = efx->net_dev;
netif_napi_add(channel->napi_dev, &channel->napi_str, efx_poll);
}
void efx_siena_init_napi(struct efx_nic *efx)
{
struct efx_channel *channel;
efx_for_each_channel(channel, efx)
efx_init_napi_channel(channel);
}
static void efx_fini_napi_channel(struct efx_channel *channel)
{
if (channel->napi_dev)
netif_napi_del(&channel->napi_str);
channel->napi_dev = NULL;
}
void efx_siena_fini_napi(struct efx_nic *efx)
{
struct efx_channel *channel;
efx_for_each_channel(channel, efx)
efx_fini_napi_channel(channel);
}
/***************
* Housekeeping
***************/
static int efx_channel_dummy_op_int(struct efx_channel *channel)
{
return 0;
}
void efx_siena_channel_dummy_op_void(struct efx_channel *channel)
{
}
static const struct efx_channel_type efx_default_channel_type = {
.pre_probe = efx_channel_dummy_op_int,
.post_remove = efx_siena_channel_dummy_op_void,
.get_name = efx_get_channel_name,
.copy = efx_copy_channel,
.want_txqs = efx_default_channel_want_txqs,
.keep_eventq = false,
.want_pio = true,
};
|
linux-master
|
drivers/net/ethernet/sfc/siena/efx_channels.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2019 Solarflare Communications Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include <linux/module.h>
#include <linux/netdevice.h>
#include "net_driver.h"
#include "mcdi.h"
#include "nic.h"
#include "selftest.h"
#include "rx_common.h"
#include "ethtool_common.h"
#include "mcdi_port_common.h"
struct efx_sw_stat_desc {
const char *name;
enum {
EFX_ETHTOOL_STAT_SOURCE_nic,
EFX_ETHTOOL_STAT_SOURCE_channel,
EFX_ETHTOOL_STAT_SOURCE_tx_queue
} source;
unsigned int offset;
u64 (*get_stat)(void *field); /* Reader function */
};
/* Initialiser for a struct efx_sw_stat_desc with type-checking */
#define EFX_ETHTOOL_STAT(stat_name, source_name, field, field_type, \
get_stat_function) { \
.name = #stat_name, \
.source = EFX_ETHTOOL_STAT_SOURCE_##source_name, \
.offset = ((((field_type *) 0) == \
&((struct efx_##source_name *)0)->field) ? \
offsetof(struct efx_##source_name, field) : \
offsetof(struct efx_##source_name, field)), \
.get_stat = get_stat_function, \
}
static u64 efx_get_uint_stat(void *field)
{
return *(unsigned int *)field;
}
static u64 efx_get_atomic_stat(void *field)
{
return atomic_read((atomic_t *) field);
}
#define EFX_ETHTOOL_ATOMIC_NIC_ERROR_STAT(field) \
EFX_ETHTOOL_STAT(field, nic, field, \
atomic_t, efx_get_atomic_stat)
#define EFX_ETHTOOL_UINT_CHANNEL_STAT(field) \
EFX_ETHTOOL_STAT(field, channel, n_##field, \
unsigned int, efx_get_uint_stat)
#define EFX_ETHTOOL_UINT_CHANNEL_STAT_NO_N(field) \
EFX_ETHTOOL_STAT(field, channel, field, \
unsigned int, efx_get_uint_stat)
#define EFX_ETHTOOL_UINT_TXQ_STAT(field) \
EFX_ETHTOOL_STAT(tx_##field, tx_queue, field, \
unsigned int, efx_get_uint_stat)
static const struct efx_sw_stat_desc efx_sw_stat_desc[] = {
EFX_ETHTOOL_UINT_TXQ_STAT(merge_events),
EFX_ETHTOOL_UINT_TXQ_STAT(tso_bursts),
EFX_ETHTOOL_UINT_TXQ_STAT(tso_long_headers),
EFX_ETHTOOL_UINT_TXQ_STAT(tso_packets),
EFX_ETHTOOL_UINT_TXQ_STAT(tso_fallbacks),
EFX_ETHTOOL_UINT_TXQ_STAT(pushes),
EFX_ETHTOOL_UINT_TXQ_STAT(pio_packets),
EFX_ETHTOOL_UINT_TXQ_STAT(cb_packets),
EFX_ETHTOOL_ATOMIC_NIC_ERROR_STAT(rx_reset),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_tobe_disc),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_ip_hdr_chksum_err),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_tcp_udp_chksum_err),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_inner_ip_hdr_chksum_err),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_inner_tcp_udp_chksum_err),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_outer_ip_hdr_chksum_err),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_outer_tcp_udp_chksum_err),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_eth_crc_err),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_mcast_mismatch),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_frm_trunc),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_merge_events),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_merge_packets),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_xdp_drops),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_xdp_bad_drops),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_xdp_tx),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rx_xdp_redirect),
#ifdef CONFIG_RFS_ACCEL
EFX_ETHTOOL_UINT_CHANNEL_STAT_NO_N(rfs_filter_count),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rfs_succeeded),
EFX_ETHTOOL_UINT_CHANNEL_STAT(rfs_failed),
#endif
};
#define EFX_ETHTOOL_SW_STAT_COUNT ARRAY_SIZE(efx_sw_stat_desc)
void efx_siena_ethtool_get_drvinfo(struct net_device *net_dev,
struct ethtool_drvinfo *info)
{
struct efx_nic *efx = netdev_priv(net_dev);
strscpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
efx_siena_mcdi_print_fwver(efx, info->fw_version,
sizeof(info->fw_version));
strscpy(info->bus_info, pci_name(efx->pci_dev), sizeof(info->bus_info));
}
u32 efx_siena_ethtool_get_msglevel(struct net_device *net_dev)
{
struct efx_nic *efx = netdev_priv(net_dev);
return efx->msg_enable;
}
void efx_siena_ethtool_set_msglevel(struct net_device *net_dev, u32 msg_enable)
{
struct efx_nic *efx = netdev_priv(net_dev);
efx->msg_enable = msg_enable;
}
void efx_siena_ethtool_get_pauseparam(struct net_device *net_dev,
struct ethtool_pauseparam *pause)
{
struct efx_nic *efx = netdev_priv(net_dev);
pause->rx_pause = !!(efx->wanted_fc & EFX_FC_RX);
pause->tx_pause = !!(efx->wanted_fc & EFX_FC_TX);
pause->autoneg = !!(efx->wanted_fc & EFX_FC_AUTO);
}
int efx_siena_ethtool_set_pauseparam(struct net_device *net_dev,
struct ethtool_pauseparam *pause)
{
struct efx_nic *efx = netdev_priv(net_dev);
u8 wanted_fc, old_fc;
u32 old_adv;
int rc = 0;
mutex_lock(&efx->mac_lock);
wanted_fc = ((pause->rx_pause ? EFX_FC_RX : 0) |
(pause->tx_pause ? EFX_FC_TX : 0) |
(pause->autoneg ? EFX_FC_AUTO : 0));
if ((wanted_fc & EFX_FC_TX) && !(wanted_fc & EFX_FC_RX)) {
netif_dbg(efx, drv, efx->net_dev,
"Flow control unsupported: tx ON rx OFF\n");
rc = -EINVAL;
goto out;
}
if ((wanted_fc & EFX_FC_AUTO) && !efx->link_advertising[0]) {
netif_dbg(efx, drv, efx->net_dev,
"Autonegotiation is disabled\n");
rc = -EINVAL;
goto out;
}
/* Hook for Falcon bug 11482 workaround */
if (efx->type->prepare_enable_fc_tx &&
(wanted_fc & EFX_FC_TX) && !(efx->wanted_fc & EFX_FC_TX))
efx->type->prepare_enable_fc_tx(efx);
old_adv = efx->link_advertising[0];
old_fc = efx->wanted_fc;
efx_siena_link_set_wanted_fc(efx, wanted_fc);
if (efx->link_advertising[0] != old_adv ||
(efx->wanted_fc ^ old_fc) & EFX_FC_AUTO) {
rc = efx_siena_mcdi_port_reconfigure(efx);
if (rc) {
netif_err(efx, drv, efx->net_dev,
"Unable to advertise requested flow "
"control setting\n");
goto out;
}
}
/* Reconfigure the MAC. The PHY *may* generate a link state change event
* if the user just changed the advertised capabilities, but there's no
* harm doing this twice */
efx_siena_mac_reconfigure(efx, false);
out:
mutex_unlock(&efx->mac_lock);
return rc;
}
/**
* efx_fill_test - fill in an individual self-test entry
* @test_index: Index of the test
* @strings: Ethtool strings, or %NULL
* @data: Ethtool test results, or %NULL
* @test: Pointer to test result (used only if data != %NULL)
* @unit_format: Unit name format (e.g. "chan\%d")
* @unit_id: Unit id (e.g. 0 for "chan0")
* @test_format: Test name format (e.g. "loopback.\%s.tx.sent")
* @test_id: Test id (e.g. "PHYXS" for "loopback.PHYXS.tx_sent")
*
* Fill in an individual self-test entry.
*/
static void efx_fill_test(unsigned int test_index, u8 *strings, u64 *data,
int *test, const char *unit_format, int unit_id,
const char *test_format, const char *test_id)
{
char unit_str[ETH_GSTRING_LEN], test_str[ETH_GSTRING_LEN];
/* Fill data value, if applicable */
if (data)
data[test_index] = *test;
/* Fill string, if applicable */
if (strings) {
if (strchr(unit_format, '%'))
snprintf(unit_str, sizeof(unit_str),
unit_format, unit_id);
else
strcpy(unit_str, unit_format);
snprintf(test_str, sizeof(test_str), test_format, test_id);
snprintf(strings + test_index * ETH_GSTRING_LEN,
ETH_GSTRING_LEN,
"%-6s %-24s", unit_str, test_str);
}
}
#define EFX_CHANNEL_NAME(_channel) "chan%d", _channel->channel
#define EFX_TX_QUEUE_NAME(_tx_queue) "txq%d", _tx_queue->label
#define EFX_LOOPBACK_NAME(_mode, _counter) \
"loopback.%s." _counter, STRING_TABLE_LOOKUP(_mode, efx_siena_loopback_mode)
/**
* efx_fill_loopback_test - fill in a block of loopback self-test entries
* @efx: Efx NIC
* @lb_tests: Efx loopback self-test results structure
* @mode: Loopback test mode
* @test_index: Starting index of the test
* @strings: Ethtool strings, or %NULL
* @data: Ethtool test results, or %NULL
*
* Fill in a block of loopback self-test entries. Return new test
* index.
*/
static int efx_fill_loopback_test(struct efx_nic *efx,
struct efx_loopback_self_tests *lb_tests,
enum efx_loopback_mode mode,
unsigned int test_index,
u8 *strings, u64 *data)
{
struct efx_channel *channel =
efx_get_channel(efx, efx->tx_channel_offset);
struct efx_tx_queue *tx_queue;
efx_for_each_channel_tx_queue(tx_queue, channel) {
efx_fill_test(test_index++, strings, data,
&lb_tests->tx_sent[tx_queue->label],
EFX_TX_QUEUE_NAME(tx_queue),
EFX_LOOPBACK_NAME(mode, "tx_sent"));
efx_fill_test(test_index++, strings, data,
&lb_tests->tx_done[tx_queue->label],
EFX_TX_QUEUE_NAME(tx_queue),
EFX_LOOPBACK_NAME(mode, "tx_done"));
}
efx_fill_test(test_index++, strings, data,
&lb_tests->rx_good,
"rx", 0,
EFX_LOOPBACK_NAME(mode, "rx_good"));
efx_fill_test(test_index++, strings, data,
&lb_tests->rx_bad,
"rx", 0,
EFX_LOOPBACK_NAME(mode, "rx_bad"));
return test_index;
}
/**
* efx_ethtool_fill_self_tests - get self-test details
* @efx: Efx NIC
* @tests: Efx self-test results structure, or %NULL
* @strings: Ethtool strings, or %NULL
* @data: Ethtool test results, or %NULL
*
* Get self-test number of strings, strings, and/or test results.
* Return number of strings (== number of test results).
*
* The reason for merging these three functions is to make sure that
* they can never be inconsistent.
*/
static int efx_ethtool_fill_self_tests(struct efx_nic *efx,
struct efx_self_tests *tests,
u8 *strings, u64 *data)
{
struct efx_channel *channel;
unsigned int n = 0, i;
enum efx_loopback_mode mode;
efx_fill_test(n++, strings, data, &tests->phy_alive,
"phy", 0, "alive", NULL);
efx_fill_test(n++, strings, data, &tests->nvram,
"core", 0, "nvram", NULL);
efx_fill_test(n++, strings, data, &tests->interrupt,
"core", 0, "interrupt", NULL);
/* Event queues */
efx_for_each_channel(channel, efx) {
efx_fill_test(n++, strings, data,
&tests->eventq_dma[channel->channel],
EFX_CHANNEL_NAME(channel),
"eventq.dma", NULL);
efx_fill_test(n++, strings, data,
&tests->eventq_int[channel->channel],
EFX_CHANNEL_NAME(channel),
"eventq.int", NULL);
}
efx_fill_test(n++, strings, data, &tests->memory,
"core", 0, "memory", NULL);
efx_fill_test(n++, strings, data, &tests->registers,
"core", 0, "registers", NULL);
for (i = 0; true; ++i) {
const char *name;
EFX_WARN_ON_PARANOID(i >= EFX_MAX_PHY_TESTS);
name = efx_siena_mcdi_phy_test_name(efx, i);
if (name == NULL)
break;
efx_fill_test(n++, strings, data, &tests->phy_ext[i], "phy", 0, name, NULL);
}
/* Loopback tests */
for (mode = LOOPBACK_NONE; mode <= LOOPBACK_TEST_MAX; mode++) {
if (!(efx->loopback_modes & (1 << mode)))
continue;
n = efx_fill_loopback_test(efx,
&tests->loopback[mode], mode, n,
strings, data);
}
return n;
}
void efx_siena_ethtool_self_test(struct net_device *net_dev,
struct ethtool_test *test, u64 *data)
{
struct efx_nic *efx = netdev_priv(net_dev);
struct efx_self_tests *efx_tests;
bool already_up;
int rc = -ENOMEM;
efx_tests = kzalloc(sizeof(*efx_tests), GFP_KERNEL);
if (!efx_tests)
goto fail;
if (efx->state != STATE_READY) {
rc = -EBUSY;
goto out;
}
netif_info(efx, drv, efx->net_dev, "starting %sline testing\n",
(test->flags & ETH_TEST_FL_OFFLINE) ? "off" : "on");
/* We need rx buffers and interrupts. */
already_up = (efx->net_dev->flags & IFF_UP);
if (!already_up) {
rc = dev_open(efx->net_dev, NULL);
if (rc) {
netif_err(efx, drv, efx->net_dev,
"failed opening device.\n");
goto out;
}
}
rc = efx_siena_selftest(efx, efx_tests, test->flags);
if (!already_up)
dev_close(efx->net_dev);
netif_info(efx, drv, efx->net_dev, "%s %sline self-tests\n",
rc == 0 ? "passed" : "failed",
(test->flags & ETH_TEST_FL_OFFLINE) ? "off" : "on");
out:
efx_ethtool_fill_self_tests(efx, efx_tests, NULL, data);
kfree(efx_tests);
fail:
if (rc)
test->flags |= ETH_TEST_FL_FAILED;
}
static size_t efx_describe_per_queue_stats(struct efx_nic *efx, u8 *strings)
{
size_t n_stats = 0;
struct efx_channel *channel;
efx_for_each_channel(channel, efx) {
if (efx_channel_has_tx_queues(channel)) {
n_stats++;
if (strings != NULL) {
snprintf(strings, ETH_GSTRING_LEN,
"tx-%u.tx_packets",
channel->tx_queue[0].queue /
EFX_MAX_TXQ_PER_CHANNEL);
strings += ETH_GSTRING_LEN;
}
}
}
efx_for_each_channel(channel, efx) {
if (efx_channel_has_rx_queue(channel)) {
n_stats++;
if (strings != NULL) {
snprintf(strings, ETH_GSTRING_LEN,
"rx-%d.rx_packets", channel->channel);
strings += ETH_GSTRING_LEN;
}
}
}
if (efx->xdp_tx_queue_count && efx->xdp_tx_queues) {
unsigned short xdp;
for (xdp = 0; xdp < efx->xdp_tx_queue_count; xdp++) {
n_stats++;
if (strings) {
snprintf(strings, ETH_GSTRING_LEN,
"tx-xdp-cpu-%hu.tx_packets", xdp);
strings += ETH_GSTRING_LEN;
}
}
}
return n_stats;
}
int efx_siena_ethtool_get_sset_count(struct net_device *net_dev, int string_set)
{
struct efx_nic *efx = netdev_priv(net_dev);
switch (string_set) {
case ETH_SS_STATS:
return efx->type->describe_stats(efx, NULL) +
EFX_ETHTOOL_SW_STAT_COUNT +
efx_describe_per_queue_stats(efx, NULL) +
efx_siena_ptp_describe_stats(efx, NULL);
case ETH_SS_TEST:
return efx_ethtool_fill_self_tests(efx, NULL, NULL, NULL);
default:
return -EINVAL;
}
}
void efx_siena_ethtool_get_strings(struct net_device *net_dev,
u32 string_set, u8 *strings)
{
struct efx_nic *efx = netdev_priv(net_dev);
int i;
switch (string_set) {
case ETH_SS_STATS:
strings += (efx->type->describe_stats(efx, strings) *
ETH_GSTRING_LEN);
for (i = 0; i < EFX_ETHTOOL_SW_STAT_COUNT; i++)
strscpy(strings + i * ETH_GSTRING_LEN,
efx_sw_stat_desc[i].name, ETH_GSTRING_LEN);
strings += EFX_ETHTOOL_SW_STAT_COUNT * ETH_GSTRING_LEN;
strings += (efx_describe_per_queue_stats(efx, strings) *
ETH_GSTRING_LEN);
efx_siena_ptp_describe_stats(efx, strings);
break;
case ETH_SS_TEST:
efx_ethtool_fill_self_tests(efx, NULL, strings, NULL);
break;
default:
/* No other string sets */
break;
}
}
void efx_siena_ethtool_get_stats(struct net_device *net_dev,
struct ethtool_stats *stats,
u64 *data)
{
struct efx_nic *efx = netdev_priv(net_dev);
const struct efx_sw_stat_desc *stat;
struct efx_channel *channel;
struct efx_tx_queue *tx_queue;
struct efx_rx_queue *rx_queue;
int i;
spin_lock_bh(&efx->stats_lock);
/* Get NIC statistics */
data += efx->type->update_stats(efx, data, NULL);
/* Get software statistics */
for (i = 0; i < EFX_ETHTOOL_SW_STAT_COUNT; i++) {
stat = &efx_sw_stat_desc[i];
switch (stat->source) {
case EFX_ETHTOOL_STAT_SOURCE_nic:
data[i] = stat->get_stat((void *)efx + stat->offset);
break;
case EFX_ETHTOOL_STAT_SOURCE_channel:
data[i] = 0;
efx_for_each_channel(channel, efx)
data[i] += stat->get_stat((void *)channel +
stat->offset);
break;
case EFX_ETHTOOL_STAT_SOURCE_tx_queue:
data[i] = 0;
efx_for_each_channel(channel, efx) {
efx_for_each_channel_tx_queue(tx_queue, channel)
data[i] +=
stat->get_stat((void *)tx_queue
+ stat->offset);
}
break;
}
}
data += EFX_ETHTOOL_SW_STAT_COUNT;
spin_unlock_bh(&efx->stats_lock);
efx_for_each_channel(channel, efx) {
if (efx_channel_has_tx_queues(channel)) {
*data = 0;
efx_for_each_channel_tx_queue(tx_queue, channel) {
*data += tx_queue->tx_packets;
}
data++;
}
}
efx_for_each_channel(channel, efx) {
if (efx_channel_has_rx_queue(channel)) {
*data = 0;
efx_for_each_channel_rx_queue(rx_queue, channel) {
*data += rx_queue->rx_packets;
}
data++;
}
}
if (efx->xdp_tx_queue_count && efx->xdp_tx_queues) {
int xdp;
for (xdp = 0; xdp < efx->xdp_tx_queue_count; xdp++) {
data[0] = efx->xdp_tx_queues[xdp]->tx_packets;
data++;
}
}
efx_siena_ptp_update_stats(efx, data);
}
/* This must be called with rtnl_lock held. */
int efx_siena_ethtool_get_link_ksettings(struct net_device *net_dev,
struct ethtool_link_ksettings *cmd)
{
struct efx_nic *efx = netdev_priv(net_dev);
struct efx_link_state *link_state = &efx->link_state;
mutex_lock(&efx->mac_lock);
efx_siena_mcdi_phy_get_link_ksettings(efx, cmd);
mutex_unlock(&efx->mac_lock);
/* Both MACs support pause frames (bidirectional and respond-only) */
ethtool_link_ksettings_add_link_mode(cmd, supported, Pause);
ethtool_link_ksettings_add_link_mode(cmd, supported, Asym_Pause);
if (LOOPBACK_INTERNAL(efx)) {
cmd->base.speed = link_state->speed;
cmd->base.duplex = link_state->fd ? DUPLEX_FULL : DUPLEX_HALF;
}
return 0;
}
/* This must be called with rtnl_lock held. */
int
efx_siena_ethtool_set_link_ksettings(struct net_device *net_dev,
const struct ethtool_link_ksettings *cmd)
{
struct efx_nic *efx = netdev_priv(net_dev);
int rc;
/* GMAC does not support 1000Mbps HD */
if ((cmd->base.speed == SPEED_1000) &&
(cmd->base.duplex != DUPLEX_FULL)) {
netif_dbg(efx, drv, efx->net_dev,
"rejecting unsupported 1000Mbps HD setting\n");
return -EINVAL;
}
mutex_lock(&efx->mac_lock);
rc = efx_siena_mcdi_phy_set_link_ksettings(efx, cmd);
mutex_unlock(&efx->mac_lock);
return rc;
}
int efx_siena_ethtool_get_fecparam(struct net_device *net_dev,
struct ethtool_fecparam *fecparam)
{
struct efx_nic *efx = netdev_priv(net_dev);
int rc;
mutex_lock(&efx->mac_lock);
rc = efx_siena_mcdi_phy_get_fecparam(efx, fecparam);
mutex_unlock(&efx->mac_lock);
return rc;
}
int efx_siena_ethtool_set_fecparam(struct net_device *net_dev,
struct ethtool_fecparam *fecparam)
{
struct efx_nic *efx = netdev_priv(net_dev);
int rc;
mutex_lock(&efx->mac_lock);
rc = efx_siena_mcdi_phy_set_fecparam(efx, fecparam);
mutex_unlock(&efx->mac_lock);
return rc;
}
/* MAC address mask including only I/G bit */
static const u8 mac_addr_ig_mask[ETH_ALEN] __aligned(2) = {0x01, 0, 0, 0, 0, 0};
#define IP4_ADDR_FULL_MASK ((__force __be32)~0)
#define IP_PROTO_FULL_MASK 0xFF
#define PORT_FULL_MASK ((__force __be16)~0)
#define ETHER_TYPE_FULL_MASK ((__force __be16)~0)
static inline void ip6_fill_mask(__be32 *mask)
{
mask[0] = mask[1] = mask[2] = mask[3] = ~(__be32)0;
}
static int efx_ethtool_get_class_rule(struct efx_nic *efx,
struct ethtool_rx_flow_spec *rule,
u32 *rss_context)
{
struct ethtool_tcpip4_spec *ip_entry = &rule->h_u.tcp_ip4_spec;
struct ethtool_tcpip4_spec *ip_mask = &rule->m_u.tcp_ip4_spec;
struct ethtool_usrip4_spec *uip_entry = &rule->h_u.usr_ip4_spec;
struct ethtool_usrip4_spec *uip_mask = &rule->m_u.usr_ip4_spec;
struct ethtool_tcpip6_spec *ip6_entry = &rule->h_u.tcp_ip6_spec;
struct ethtool_tcpip6_spec *ip6_mask = &rule->m_u.tcp_ip6_spec;
struct ethtool_usrip6_spec *uip6_entry = &rule->h_u.usr_ip6_spec;
struct ethtool_usrip6_spec *uip6_mask = &rule->m_u.usr_ip6_spec;
struct ethhdr *mac_entry = &rule->h_u.ether_spec;
struct ethhdr *mac_mask = &rule->m_u.ether_spec;
struct efx_filter_spec spec;
int rc;
rc = efx_filter_get_filter_safe(efx, EFX_FILTER_PRI_MANUAL,
rule->location, &spec);
if (rc)
return rc;
if (spec.dmaq_id == EFX_FILTER_RX_DMAQ_ID_DROP)
rule->ring_cookie = RX_CLS_FLOW_DISC;
else
rule->ring_cookie = spec.dmaq_id;
if ((spec.match_flags & EFX_FILTER_MATCH_ETHER_TYPE) &&
spec.ether_type == htons(ETH_P_IP) &&
(spec.match_flags & EFX_FILTER_MATCH_IP_PROTO) &&
(spec.ip_proto == IPPROTO_TCP || spec.ip_proto == IPPROTO_UDP) &&
!(spec.match_flags &
~(EFX_FILTER_MATCH_ETHER_TYPE | EFX_FILTER_MATCH_OUTER_VID |
EFX_FILTER_MATCH_LOC_HOST | EFX_FILTER_MATCH_REM_HOST |
EFX_FILTER_MATCH_IP_PROTO |
EFX_FILTER_MATCH_LOC_PORT | EFX_FILTER_MATCH_REM_PORT))) {
rule->flow_type = ((spec.ip_proto == IPPROTO_TCP) ?
TCP_V4_FLOW : UDP_V4_FLOW);
if (spec.match_flags & EFX_FILTER_MATCH_LOC_HOST) {
ip_entry->ip4dst = spec.loc_host[0];
ip_mask->ip4dst = IP4_ADDR_FULL_MASK;
}
if (spec.match_flags & EFX_FILTER_MATCH_REM_HOST) {
ip_entry->ip4src = spec.rem_host[0];
ip_mask->ip4src = IP4_ADDR_FULL_MASK;
}
if (spec.match_flags & EFX_FILTER_MATCH_LOC_PORT) {
ip_entry->pdst = spec.loc_port;
ip_mask->pdst = PORT_FULL_MASK;
}
if (spec.match_flags & EFX_FILTER_MATCH_REM_PORT) {
ip_entry->psrc = spec.rem_port;
ip_mask->psrc = PORT_FULL_MASK;
}
} else if ((spec.match_flags & EFX_FILTER_MATCH_ETHER_TYPE) &&
spec.ether_type == htons(ETH_P_IPV6) &&
(spec.match_flags & EFX_FILTER_MATCH_IP_PROTO) &&
(spec.ip_proto == IPPROTO_TCP || spec.ip_proto == IPPROTO_UDP) &&
!(spec.match_flags &
~(EFX_FILTER_MATCH_ETHER_TYPE | EFX_FILTER_MATCH_OUTER_VID |
EFX_FILTER_MATCH_LOC_HOST | EFX_FILTER_MATCH_REM_HOST |
EFX_FILTER_MATCH_IP_PROTO |
EFX_FILTER_MATCH_LOC_PORT | EFX_FILTER_MATCH_REM_PORT))) {
rule->flow_type = ((spec.ip_proto == IPPROTO_TCP) ?
TCP_V6_FLOW : UDP_V6_FLOW);
if (spec.match_flags & EFX_FILTER_MATCH_LOC_HOST) {
memcpy(ip6_entry->ip6dst, spec.loc_host,
sizeof(ip6_entry->ip6dst));
ip6_fill_mask(ip6_mask->ip6dst);
}
if (spec.match_flags & EFX_FILTER_MATCH_REM_HOST) {
memcpy(ip6_entry->ip6src, spec.rem_host,
sizeof(ip6_entry->ip6src));
ip6_fill_mask(ip6_mask->ip6src);
}
if (spec.match_flags & EFX_FILTER_MATCH_LOC_PORT) {
ip6_entry->pdst = spec.loc_port;
ip6_mask->pdst = PORT_FULL_MASK;
}
if (spec.match_flags & EFX_FILTER_MATCH_REM_PORT) {
ip6_entry->psrc = spec.rem_port;
ip6_mask->psrc = PORT_FULL_MASK;
}
} else if (!(spec.match_flags &
~(EFX_FILTER_MATCH_LOC_MAC | EFX_FILTER_MATCH_LOC_MAC_IG |
EFX_FILTER_MATCH_REM_MAC | EFX_FILTER_MATCH_ETHER_TYPE |
EFX_FILTER_MATCH_OUTER_VID))) {
rule->flow_type = ETHER_FLOW;
if (spec.match_flags &
(EFX_FILTER_MATCH_LOC_MAC | EFX_FILTER_MATCH_LOC_MAC_IG)) {
ether_addr_copy(mac_entry->h_dest, spec.loc_mac);
if (spec.match_flags & EFX_FILTER_MATCH_LOC_MAC)
eth_broadcast_addr(mac_mask->h_dest);
else
ether_addr_copy(mac_mask->h_dest,
mac_addr_ig_mask);
}
if (spec.match_flags & EFX_FILTER_MATCH_REM_MAC) {
ether_addr_copy(mac_entry->h_source, spec.rem_mac);
eth_broadcast_addr(mac_mask->h_source);
}
if (spec.match_flags & EFX_FILTER_MATCH_ETHER_TYPE) {
mac_entry->h_proto = spec.ether_type;
mac_mask->h_proto = ETHER_TYPE_FULL_MASK;
}
} else if (spec.match_flags & EFX_FILTER_MATCH_ETHER_TYPE &&
spec.ether_type == htons(ETH_P_IP) &&
!(spec.match_flags &
~(EFX_FILTER_MATCH_ETHER_TYPE | EFX_FILTER_MATCH_OUTER_VID |
EFX_FILTER_MATCH_LOC_HOST | EFX_FILTER_MATCH_REM_HOST |
EFX_FILTER_MATCH_IP_PROTO))) {
rule->flow_type = IPV4_USER_FLOW;
uip_entry->ip_ver = ETH_RX_NFC_IP4;
if (spec.match_flags & EFX_FILTER_MATCH_IP_PROTO) {
uip_mask->proto = IP_PROTO_FULL_MASK;
uip_entry->proto = spec.ip_proto;
}
if (spec.match_flags & EFX_FILTER_MATCH_LOC_HOST) {
uip_entry->ip4dst = spec.loc_host[0];
uip_mask->ip4dst = IP4_ADDR_FULL_MASK;
}
if (spec.match_flags & EFX_FILTER_MATCH_REM_HOST) {
uip_entry->ip4src = spec.rem_host[0];
uip_mask->ip4src = IP4_ADDR_FULL_MASK;
}
} else if (spec.match_flags & EFX_FILTER_MATCH_ETHER_TYPE &&
spec.ether_type == htons(ETH_P_IPV6) &&
!(spec.match_flags &
~(EFX_FILTER_MATCH_ETHER_TYPE | EFX_FILTER_MATCH_OUTER_VID |
EFX_FILTER_MATCH_LOC_HOST | EFX_FILTER_MATCH_REM_HOST |
EFX_FILTER_MATCH_IP_PROTO))) {
rule->flow_type = IPV6_USER_FLOW;
if (spec.match_flags & EFX_FILTER_MATCH_IP_PROTO) {
uip6_mask->l4_proto = IP_PROTO_FULL_MASK;
uip6_entry->l4_proto = spec.ip_proto;
}
if (spec.match_flags & EFX_FILTER_MATCH_LOC_HOST) {
memcpy(uip6_entry->ip6dst, spec.loc_host,
sizeof(uip6_entry->ip6dst));
ip6_fill_mask(uip6_mask->ip6dst);
}
if (spec.match_flags & EFX_FILTER_MATCH_REM_HOST) {
memcpy(uip6_entry->ip6src, spec.rem_host,
sizeof(uip6_entry->ip6src));
ip6_fill_mask(uip6_mask->ip6src);
}
} else {
/* The above should handle all filters that we insert */
WARN_ON(1);
return -EINVAL;
}
if (spec.match_flags & EFX_FILTER_MATCH_OUTER_VID) {
rule->flow_type |= FLOW_EXT;
rule->h_ext.vlan_tci = spec.outer_vid;
rule->m_ext.vlan_tci = htons(0xfff);
}
if (spec.flags & EFX_FILTER_FLAG_RX_RSS) {
rule->flow_type |= FLOW_RSS;
*rss_context = spec.rss_context;
}
return rc;
}
int efx_siena_ethtool_get_rxnfc(struct net_device *net_dev,
struct ethtool_rxnfc *info, u32 *rule_locs)
{
struct efx_nic *efx = netdev_priv(net_dev);
u32 rss_context = 0;
s32 rc = 0;
switch (info->cmd) {
case ETHTOOL_GRXRINGS:
info->data = efx->n_rx_channels;
return 0;
case ETHTOOL_GRXFH: {
struct efx_rss_context *ctx = &efx->rss_context;
__u64 data;
mutex_lock(&efx->rss_lock);
if (info->flow_type & FLOW_RSS && info->rss_context) {
ctx = efx_siena_find_rss_context_entry(efx,
info->rss_context);
if (!ctx) {
rc = -ENOENT;
goto out_unlock;
}
}
data = 0;
if (!efx_rss_active(ctx)) /* No RSS */
goto out_setdata_unlock;
switch (info->flow_type & ~FLOW_RSS) {
case UDP_V4_FLOW:
case UDP_V6_FLOW:
if (ctx->rx_hash_udp_4tuple)
data = (RXH_L4_B_0_1 | RXH_L4_B_2_3 |
RXH_IP_SRC | RXH_IP_DST);
else
data = RXH_IP_SRC | RXH_IP_DST;
break;
case TCP_V4_FLOW:
case TCP_V6_FLOW:
data = (RXH_L4_B_0_1 | RXH_L4_B_2_3 |
RXH_IP_SRC | RXH_IP_DST);
break;
case SCTP_V4_FLOW:
case SCTP_V6_FLOW:
case AH_ESP_V4_FLOW:
case AH_ESP_V6_FLOW:
case IPV4_FLOW:
case IPV6_FLOW:
data = RXH_IP_SRC | RXH_IP_DST;
break;
default:
break;
}
out_setdata_unlock:
info->data = data;
out_unlock:
mutex_unlock(&efx->rss_lock);
return rc;
}
case ETHTOOL_GRXCLSRLCNT:
info->data = efx_filter_get_rx_id_limit(efx);
if (info->data == 0)
return -EOPNOTSUPP;
info->data |= RX_CLS_LOC_SPECIAL;
info->rule_cnt =
efx_filter_count_rx_used(efx, EFX_FILTER_PRI_MANUAL);
return 0;
case ETHTOOL_GRXCLSRULE:
if (efx_filter_get_rx_id_limit(efx) == 0)
return -EOPNOTSUPP;
rc = efx_ethtool_get_class_rule(efx, &info->fs, &rss_context);
if (rc < 0)
return rc;
if (info->fs.flow_type & FLOW_RSS)
info->rss_context = rss_context;
return 0;
case ETHTOOL_GRXCLSRLALL:
info->data = efx_filter_get_rx_id_limit(efx);
if (info->data == 0)
return -EOPNOTSUPP;
rc = efx_filter_get_rx_ids(efx, EFX_FILTER_PRI_MANUAL,
rule_locs, info->rule_cnt);
if (rc < 0)
return rc;
info->rule_cnt = rc;
return 0;
default:
return -EOPNOTSUPP;
}
}
static inline bool ip6_mask_is_full(__be32 mask[4])
{
return !~(mask[0] & mask[1] & mask[2] & mask[3]);
}
static inline bool ip6_mask_is_empty(__be32 mask[4])
{
return !(mask[0] | mask[1] | mask[2] | mask[3]);
}
static int efx_ethtool_set_class_rule(struct efx_nic *efx,
struct ethtool_rx_flow_spec *rule,
u32 rss_context)
{
struct ethtool_tcpip4_spec *ip_entry = &rule->h_u.tcp_ip4_spec;
struct ethtool_tcpip4_spec *ip_mask = &rule->m_u.tcp_ip4_spec;
struct ethtool_usrip4_spec *uip_entry = &rule->h_u.usr_ip4_spec;
struct ethtool_usrip4_spec *uip_mask = &rule->m_u.usr_ip4_spec;
struct ethtool_tcpip6_spec *ip6_entry = &rule->h_u.tcp_ip6_spec;
struct ethtool_tcpip6_spec *ip6_mask = &rule->m_u.tcp_ip6_spec;
struct ethtool_usrip6_spec *uip6_entry = &rule->h_u.usr_ip6_spec;
struct ethtool_usrip6_spec *uip6_mask = &rule->m_u.usr_ip6_spec;
u32 flow_type = rule->flow_type & ~(FLOW_EXT | FLOW_RSS);
struct ethhdr *mac_entry = &rule->h_u.ether_spec;
struct ethhdr *mac_mask = &rule->m_u.ether_spec;
enum efx_filter_flags flags = 0;
struct efx_filter_spec spec;
int rc;
/* Check that user wants us to choose the location */
if (rule->location != RX_CLS_LOC_ANY)
return -EINVAL;
/* Range-check ring_cookie */
if (rule->ring_cookie >= efx->n_rx_channels &&
rule->ring_cookie != RX_CLS_FLOW_DISC)
return -EINVAL;
/* Check for unsupported extensions */
if ((rule->flow_type & FLOW_EXT) &&
(rule->m_ext.vlan_etype || rule->m_ext.data[0] ||
rule->m_ext.data[1]))
return -EINVAL;
if (efx->rx_scatter)
flags |= EFX_FILTER_FLAG_RX_SCATTER;
if (rule->flow_type & FLOW_RSS)
flags |= EFX_FILTER_FLAG_RX_RSS;
efx_filter_init_rx(&spec, EFX_FILTER_PRI_MANUAL, flags,
(rule->ring_cookie == RX_CLS_FLOW_DISC) ?
EFX_FILTER_RX_DMAQ_ID_DROP : rule->ring_cookie);
if (rule->flow_type & FLOW_RSS)
spec.rss_context = rss_context;
switch (flow_type) {
case TCP_V4_FLOW:
case UDP_V4_FLOW:
spec.match_flags = (EFX_FILTER_MATCH_ETHER_TYPE |
EFX_FILTER_MATCH_IP_PROTO);
spec.ether_type = htons(ETH_P_IP);
spec.ip_proto = flow_type == TCP_V4_FLOW ? IPPROTO_TCP
: IPPROTO_UDP;
if (ip_mask->ip4dst) {
if (ip_mask->ip4dst != IP4_ADDR_FULL_MASK)
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_LOC_HOST;
spec.loc_host[0] = ip_entry->ip4dst;
}
if (ip_mask->ip4src) {
if (ip_mask->ip4src != IP4_ADDR_FULL_MASK)
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_REM_HOST;
spec.rem_host[0] = ip_entry->ip4src;
}
if (ip_mask->pdst) {
if (ip_mask->pdst != PORT_FULL_MASK)
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_LOC_PORT;
spec.loc_port = ip_entry->pdst;
}
if (ip_mask->psrc) {
if (ip_mask->psrc != PORT_FULL_MASK)
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_REM_PORT;
spec.rem_port = ip_entry->psrc;
}
if (ip_mask->tos)
return -EINVAL;
break;
case TCP_V6_FLOW:
case UDP_V6_FLOW:
spec.match_flags = (EFX_FILTER_MATCH_ETHER_TYPE |
EFX_FILTER_MATCH_IP_PROTO);
spec.ether_type = htons(ETH_P_IPV6);
spec.ip_proto = flow_type == TCP_V6_FLOW ? IPPROTO_TCP
: IPPROTO_UDP;
if (!ip6_mask_is_empty(ip6_mask->ip6dst)) {
if (!ip6_mask_is_full(ip6_mask->ip6dst))
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_LOC_HOST;
memcpy(spec.loc_host, ip6_entry->ip6dst, sizeof(spec.loc_host));
}
if (!ip6_mask_is_empty(ip6_mask->ip6src)) {
if (!ip6_mask_is_full(ip6_mask->ip6src))
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_REM_HOST;
memcpy(spec.rem_host, ip6_entry->ip6src, sizeof(spec.rem_host));
}
if (ip6_mask->pdst) {
if (ip6_mask->pdst != PORT_FULL_MASK)
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_LOC_PORT;
spec.loc_port = ip6_entry->pdst;
}
if (ip6_mask->psrc) {
if (ip6_mask->psrc != PORT_FULL_MASK)
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_REM_PORT;
spec.rem_port = ip6_entry->psrc;
}
if (ip6_mask->tclass)
return -EINVAL;
break;
case IPV4_USER_FLOW:
if (uip_mask->l4_4_bytes || uip_mask->tos || uip_mask->ip_ver ||
uip_entry->ip_ver != ETH_RX_NFC_IP4)
return -EINVAL;
spec.match_flags = EFX_FILTER_MATCH_ETHER_TYPE;
spec.ether_type = htons(ETH_P_IP);
if (uip_mask->ip4dst) {
if (uip_mask->ip4dst != IP4_ADDR_FULL_MASK)
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_LOC_HOST;
spec.loc_host[0] = uip_entry->ip4dst;
}
if (uip_mask->ip4src) {
if (uip_mask->ip4src != IP4_ADDR_FULL_MASK)
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_REM_HOST;
spec.rem_host[0] = uip_entry->ip4src;
}
if (uip_mask->proto) {
if (uip_mask->proto != IP_PROTO_FULL_MASK)
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_IP_PROTO;
spec.ip_proto = uip_entry->proto;
}
break;
case IPV6_USER_FLOW:
if (uip6_mask->l4_4_bytes || uip6_mask->tclass)
return -EINVAL;
spec.match_flags = EFX_FILTER_MATCH_ETHER_TYPE;
spec.ether_type = htons(ETH_P_IPV6);
if (!ip6_mask_is_empty(uip6_mask->ip6dst)) {
if (!ip6_mask_is_full(uip6_mask->ip6dst))
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_LOC_HOST;
memcpy(spec.loc_host, uip6_entry->ip6dst, sizeof(spec.loc_host));
}
if (!ip6_mask_is_empty(uip6_mask->ip6src)) {
if (!ip6_mask_is_full(uip6_mask->ip6src))
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_REM_HOST;
memcpy(spec.rem_host, uip6_entry->ip6src, sizeof(spec.rem_host));
}
if (uip6_mask->l4_proto) {
if (uip6_mask->l4_proto != IP_PROTO_FULL_MASK)
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_IP_PROTO;
spec.ip_proto = uip6_entry->l4_proto;
}
break;
case ETHER_FLOW:
if (!is_zero_ether_addr(mac_mask->h_dest)) {
if (ether_addr_equal(mac_mask->h_dest,
mac_addr_ig_mask))
spec.match_flags |= EFX_FILTER_MATCH_LOC_MAC_IG;
else if (is_broadcast_ether_addr(mac_mask->h_dest))
spec.match_flags |= EFX_FILTER_MATCH_LOC_MAC;
else
return -EINVAL;
ether_addr_copy(spec.loc_mac, mac_entry->h_dest);
}
if (!is_zero_ether_addr(mac_mask->h_source)) {
if (!is_broadcast_ether_addr(mac_mask->h_source))
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_REM_MAC;
ether_addr_copy(spec.rem_mac, mac_entry->h_source);
}
if (mac_mask->h_proto) {
if (mac_mask->h_proto != ETHER_TYPE_FULL_MASK)
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_ETHER_TYPE;
spec.ether_type = mac_entry->h_proto;
}
break;
default:
return -EINVAL;
}
if ((rule->flow_type & FLOW_EXT) && rule->m_ext.vlan_tci) {
if (rule->m_ext.vlan_tci != htons(0xfff))
return -EINVAL;
spec.match_flags |= EFX_FILTER_MATCH_OUTER_VID;
spec.outer_vid = rule->h_ext.vlan_tci;
}
rc = efx_filter_insert_filter(efx, &spec, true);
if (rc < 0)
return rc;
rule->location = rc;
return 0;
}
int efx_siena_ethtool_set_rxnfc(struct net_device *net_dev,
struct ethtool_rxnfc *info)
{
struct efx_nic *efx = netdev_priv(net_dev);
if (efx_filter_get_rx_id_limit(efx) == 0)
return -EOPNOTSUPP;
switch (info->cmd) {
case ETHTOOL_SRXCLSRLINS:
return efx_ethtool_set_class_rule(efx, &info->fs,
info->rss_context);
case ETHTOOL_SRXCLSRLDEL:
return efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_MANUAL,
info->fs.location);
default:
return -EOPNOTSUPP;
}
}
u32 efx_siena_ethtool_get_rxfh_indir_size(struct net_device *net_dev)
{
struct efx_nic *efx = netdev_priv(net_dev);
if (efx->n_rx_channels == 1)
return 0;
return ARRAY_SIZE(efx->rss_context.rx_indir_table);
}
u32 efx_siena_ethtool_get_rxfh_key_size(struct net_device *net_dev)
{
struct efx_nic *efx = netdev_priv(net_dev);
return efx->type->rx_hash_key_size;
}
int efx_siena_ethtool_get_rxfh(struct net_device *net_dev, u32 *indir, u8 *key,
u8 *hfunc)
{
struct efx_nic *efx = netdev_priv(net_dev);
int rc;
rc = efx->type->rx_pull_rss_config(efx);
if (rc)
return rc;
if (hfunc)
*hfunc = ETH_RSS_HASH_TOP;
if (indir)
memcpy(indir, efx->rss_context.rx_indir_table,
sizeof(efx->rss_context.rx_indir_table));
if (key)
memcpy(key, efx->rss_context.rx_hash_key,
efx->type->rx_hash_key_size);
return 0;
}
int efx_siena_ethtool_set_rxfh(struct net_device *net_dev, const u32 *indir,
const u8 *key, const u8 hfunc)
{
struct efx_nic *efx = netdev_priv(net_dev);
/* Hash function is Toeplitz, cannot be changed */
if (hfunc != ETH_RSS_HASH_NO_CHANGE && hfunc != ETH_RSS_HASH_TOP)
return -EOPNOTSUPP;
if (!indir && !key)
return 0;
if (!key)
key = efx->rss_context.rx_hash_key;
if (!indir)
indir = efx->rss_context.rx_indir_table;
return efx->type->rx_push_rss_config(efx, true, indir, key);
}
int efx_siena_ethtool_get_rxfh_context(struct net_device *net_dev, u32 *indir,
u8 *key, u8 *hfunc, u32 rss_context)
{
struct efx_nic *efx = netdev_priv(net_dev);
struct efx_rss_context *ctx;
int rc = 0;
if (!efx->type->rx_pull_rss_context_config)
return -EOPNOTSUPP;
mutex_lock(&efx->rss_lock);
ctx = efx_siena_find_rss_context_entry(efx, rss_context);
if (!ctx) {
rc = -ENOENT;
goto out_unlock;
}
rc = efx->type->rx_pull_rss_context_config(efx, ctx);
if (rc)
goto out_unlock;
if (hfunc)
*hfunc = ETH_RSS_HASH_TOP;
if (indir)
memcpy(indir, ctx->rx_indir_table, sizeof(ctx->rx_indir_table));
if (key)
memcpy(key, ctx->rx_hash_key, efx->type->rx_hash_key_size);
out_unlock:
mutex_unlock(&efx->rss_lock);
return rc;
}
int efx_siena_ethtool_set_rxfh_context(struct net_device *net_dev,
const u32 *indir, const u8 *key,
const u8 hfunc, u32 *rss_context,
bool delete)
{
struct efx_nic *efx = netdev_priv(net_dev);
struct efx_rss_context *ctx;
bool allocated = false;
int rc;
if (!efx->type->rx_push_rss_context_config)
return -EOPNOTSUPP;
/* Hash function is Toeplitz, cannot be changed */
if (hfunc != ETH_RSS_HASH_NO_CHANGE && hfunc != ETH_RSS_HASH_TOP)
return -EOPNOTSUPP;
mutex_lock(&efx->rss_lock);
if (*rss_context == ETH_RXFH_CONTEXT_ALLOC) {
if (delete) {
/* alloc + delete == Nothing to do */
rc = -EINVAL;
goto out_unlock;
}
ctx = efx_siena_alloc_rss_context_entry(efx);
if (!ctx) {
rc = -ENOMEM;
goto out_unlock;
}
ctx->context_id = EFX_MCDI_RSS_CONTEXT_INVALID;
/* Initialise indir table and key to defaults */
efx_siena_set_default_rx_indir_table(efx, ctx);
netdev_rss_key_fill(ctx->rx_hash_key, sizeof(ctx->rx_hash_key));
allocated = true;
} else {
ctx = efx_siena_find_rss_context_entry(efx, *rss_context);
if (!ctx) {
rc = -ENOENT;
goto out_unlock;
}
}
if (delete) {
/* delete this context */
rc = efx->type->rx_push_rss_context_config(efx, ctx, NULL, NULL);
if (!rc)
efx_siena_free_rss_context_entry(ctx);
goto out_unlock;
}
if (!key)
key = ctx->rx_hash_key;
if (!indir)
indir = ctx->rx_indir_table;
rc = efx->type->rx_push_rss_context_config(efx, ctx, indir, key);
if (rc && allocated)
efx_siena_free_rss_context_entry(ctx);
else
*rss_context = ctx->user_id;
out_unlock:
mutex_unlock(&efx->rss_lock);
return rc;
}
int efx_siena_ethtool_reset(struct net_device *net_dev, u32 *flags)
{
struct efx_nic *efx = netdev_priv(net_dev);
int rc;
rc = efx->type->map_reset_flags(flags);
if (rc < 0)
return rc;
return efx_siena_reset(efx, rc);
}
int efx_siena_ethtool_get_module_eeprom(struct net_device *net_dev,
struct ethtool_eeprom *ee,
u8 *data)
{
struct efx_nic *efx = netdev_priv(net_dev);
int ret;
mutex_lock(&efx->mac_lock);
ret = efx_siena_mcdi_phy_get_module_eeprom(efx, ee, data);
mutex_unlock(&efx->mac_lock);
return ret;
}
int efx_siena_ethtool_get_module_info(struct net_device *net_dev,
struct ethtool_modinfo *modinfo)
{
struct efx_nic *efx = netdev_priv(net_dev);
int ret;
mutex_lock(&efx->mac_lock);
ret = efx_siena_mcdi_phy_get_module_info(efx, modinfo);
mutex_unlock(&efx->mac_lock);
return ret;
}
|
linux-master
|
drivers/net/ethernet/sfc/siena/ethtool_common.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2018 Solarflare Communications Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include "mcdi_port_common.h"
#include "efx_common.h"
#include "nic.h"
static int efx_mcdi_get_phy_cfg(struct efx_nic *efx,
struct efx_mcdi_phy_data *cfg)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_PHY_CFG_OUT_LEN);
size_t outlen;
int rc;
BUILD_BUG_ON(MC_CMD_GET_PHY_CFG_IN_LEN != 0);
BUILD_BUG_ON(MC_CMD_GET_PHY_CFG_OUT_NAME_LEN != sizeof(cfg->name));
rc = efx_siena_mcdi_rpc(efx, MC_CMD_GET_PHY_CFG, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_GET_PHY_CFG_OUT_LEN) {
rc = -EIO;
goto fail;
}
cfg->flags = MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_FLAGS);
cfg->type = MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_TYPE);
cfg->supported_cap =
MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_SUPPORTED_CAP);
cfg->channel = MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_CHANNEL);
cfg->port = MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_PRT);
cfg->stats_mask = MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_STATS_MASK);
memcpy(cfg->name, MCDI_PTR(outbuf, GET_PHY_CFG_OUT_NAME),
sizeof(cfg->name));
cfg->media = MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_MEDIA_TYPE);
cfg->mmd_mask = MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_MMD_MASK);
memcpy(cfg->revision, MCDI_PTR(outbuf, GET_PHY_CFG_OUT_REVISION),
sizeof(cfg->revision));
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
void efx_siena_link_set_advertising(struct efx_nic *efx,
const unsigned long *advertising)
{
memcpy(efx->link_advertising, advertising,
sizeof(__ETHTOOL_DECLARE_LINK_MODE_MASK()));
efx->link_advertising[0] |= ADVERTISED_Autoneg;
if (advertising[0] & ADVERTISED_Pause)
efx->wanted_fc |= (EFX_FC_TX | EFX_FC_RX);
else
efx->wanted_fc &= ~(EFX_FC_TX | EFX_FC_RX);
if (advertising[0] & ADVERTISED_Asym_Pause)
efx->wanted_fc ^= EFX_FC_TX;
}
static int efx_mcdi_set_link(struct efx_nic *efx, u32 capabilities,
u32 flags, u32 loopback_mode, u32 loopback_speed)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_SET_LINK_IN_LEN);
BUILD_BUG_ON(MC_CMD_SET_LINK_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, SET_LINK_IN_CAP, capabilities);
MCDI_SET_DWORD(inbuf, SET_LINK_IN_FLAGS, flags);
MCDI_SET_DWORD(inbuf, SET_LINK_IN_LOOPBACK_MODE, loopback_mode);
MCDI_SET_DWORD(inbuf, SET_LINK_IN_LOOPBACK_SPEED, loopback_speed);
return efx_siena_mcdi_rpc(efx, MC_CMD_SET_LINK, inbuf, sizeof(inbuf),
NULL, 0, NULL);
}
static int efx_mcdi_loopback_modes(struct efx_nic *efx, u64 *loopback_modes)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_LOOPBACK_MODES_OUT_LEN);
size_t outlen;
int rc;
rc = efx_siena_mcdi_rpc(efx, MC_CMD_GET_LOOPBACK_MODES, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < (MC_CMD_GET_LOOPBACK_MODES_OUT_SUGGESTED_OFST +
MC_CMD_GET_LOOPBACK_MODES_OUT_SUGGESTED_LEN)) {
rc = -EIO;
goto fail;
}
*loopback_modes = MCDI_QWORD(outbuf, GET_LOOPBACK_MODES_OUT_SUGGESTED);
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
static void mcdi_to_ethtool_linkset(u32 media, u32 cap, unsigned long *linkset)
{
#define SET_BIT(name) __set_bit(ETHTOOL_LINK_MODE_ ## name ## _BIT, \
linkset)
bitmap_zero(linkset, __ETHTOOL_LINK_MODE_MASK_NBITS);
switch (media) {
case MC_CMD_MEDIA_KX4:
SET_BIT(Backplane);
if (cap & (1 << MC_CMD_PHY_CAP_1000FDX_LBN))
SET_BIT(1000baseKX_Full);
if (cap & (1 << MC_CMD_PHY_CAP_10000FDX_LBN))
SET_BIT(10000baseKX4_Full);
if (cap & (1 << MC_CMD_PHY_CAP_40000FDX_LBN))
SET_BIT(40000baseKR4_Full);
break;
case MC_CMD_MEDIA_XFP:
case MC_CMD_MEDIA_SFP_PLUS:
case MC_CMD_MEDIA_QSFP_PLUS:
SET_BIT(FIBRE);
if (cap & (1 << MC_CMD_PHY_CAP_1000FDX_LBN)) {
SET_BIT(1000baseT_Full);
SET_BIT(1000baseX_Full);
}
if (cap & (1 << MC_CMD_PHY_CAP_10000FDX_LBN)) {
SET_BIT(10000baseCR_Full);
SET_BIT(10000baseLR_Full);
SET_BIT(10000baseSR_Full);
}
if (cap & (1 << MC_CMD_PHY_CAP_40000FDX_LBN)) {
SET_BIT(40000baseCR4_Full);
SET_BIT(40000baseSR4_Full);
}
if (cap & (1 << MC_CMD_PHY_CAP_100000FDX_LBN)) {
SET_BIT(100000baseCR4_Full);
SET_BIT(100000baseSR4_Full);
}
if (cap & (1 << MC_CMD_PHY_CAP_25000FDX_LBN)) {
SET_BIT(25000baseCR_Full);
SET_BIT(25000baseSR_Full);
}
if (cap & (1 << MC_CMD_PHY_CAP_50000FDX_LBN))
SET_BIT(50000baseCR2_Full);
break;
case MC_CMD_MEDIA_BASE_T:
SET_BIT(TP);
if (cap & (1 << MC_CMD_PHY_CAP_10HDX_LBN))
SET_BIT(10baseT_Half);
if (cap & (1 << MC_CMD_PHY_CAP_10FDX_LBN))
SET_BIT(10baseT_Full);
if (cap & (1 << MC_CMD_PHY_CAP_100HDX_LBN))
SET_BIT(100baseT_Half);
if (cap & (1 << MC_CMD_PHY_CAP_100FDX_LBN))
SET_BIT(100baseT_Full);
if (cap & (1 << MC_CMD_PHY_CAP_1000HDX_LBN))
SET_BIT(1000baseT_Half);
if (cap & (1 << MC_CMD_PHY_CAP_1000FDX_LBN))
SET_BIT(1000baseT_Full);
if (cap & (1 << MC_CMD_PHY_CAP_10000FDX_LBN))
SET_BIT(10000baseT_Full);
break;
}
if (cap & (1 << MC_CMD_PHY_CAP_PAUSE_LBN))
SET_BIT(Pause);
if (cap & (1 << MC_CMD_PHY_CAP_ASYM_LBN))
SET_BIT(Asym_Pause);
if (cap & (1 << MC_CMD_PHY_CAP_AN_LBN))
SET_BIT(Autoneg);
#undef SET_BIT
}
static u32 ethtool_linkset_to_mcdi_cap(const unsigned long *linkset)
{
u32 result = 0;
#define TEST_BIT(name) test_bit(ETHTOOL_LINK_MODE_ ## name ## _BIT, \
linkset)
if (TEST_BIT(10baseT_Half))
result |= (1 << MC_CMD_PHY_CAP_10HDX_LBN);
if (TEST_BIT(10baseT_Full))
result |= (1 << MC_CMD_PHY_CAP_10FDX_LBN);
if (TEST_BIT(100baseT_Half))
result |= (1 << MC_CMD_PHY_CAP_100HDX_LBN);
if (TEST_BIT(100baseT_Full))
result |= (1 << MC_CMD_PHY_CAP_100FDX_LBN);
if (TEST_BIT(1000baseT_Half))
result |= (1 << MC_CMD_PHY_CAP_1000HDX_LBN);
if (TEST_BIT(1000baseT_Full) || TEST_BIT(1000baseKX_Full) ||
TEST_BIT(1000baseX_Full))
result |= (1 << MC_CMD_PHY_CAP_1000FDX_LBN);
if (TEST_BIT(10000baseT_Full) || TEST_BIT(10000baseKX4_Full) ||
TEST_BIT(10000baseCR_Full) || TEST_BIT(10000baseLR_Full) ||
TEST_BIT(10000baseSR_Full))
result |= (1 << MC_CMD_PHY_CAP_10000FDX_LBN);
if (TEST_BIT(40000baseCR4_Full) || TEST_BIT(40000baseKR4_Full) ||
TEST_BIT(40000baseSR4_Full))
result |= (1 << MC_CMD_PHY_CAP_40000FDX_LBN);
if (TEST_BIT(100000baseCR4_Full) || TEST_BIT(100000baseSR4_Full))
result |= (1 << MC_CMD_PHY_CAP_100000FDX_LBN);
if (TEST_BIT(25000baseCR_Full) || TEST_BIT(25000baseSR_Full))
result |= (1 << MC_CMD_PHY_CAP_25000FDX_LBN);
if (TEST_BIT(50000baseCR2_Full))
result |= (1 << MC_CMD_PHY_CAP_50000FDX_LBN);
if (TEST_BIT(Pause))
result |= (1 << MC_CMD_PHY_CAP_PAUSE_LBN);
if (TEST_BIT(Asym_Pause))
result |= (1 << MC_CMD_PHY_CAP_ASYM_LBN);
if (TEST_BIT(Autoneg))
result |= (1 << MC_CMD_PHY_CAP_AN_LBN);
#undef TEST_BIT
return result;
}
static u32 efx_get_mcdi_phy_flags(struct efx_nic *efx)
{
struct efx_mcdi_phy_data *phy_cfg = efx->phy_data;
enum efx_phy_mode mode, supported;
u32 flags;
/* TODO: Advertise the capabilities supported by this PHY */
supported = 0;
if (phy_cfg->flags & (1 << MC_CMD_GET_PHY_CFG_OUT_TXDIS_LBN))
supported |= PHY_MODE_TX_DISABLED;
if (phy_cfg->flags & (1 << MC_CMD_GET_PHY_CFG_OUT_LOWPOWER_LBN))
supported |= PHY_MODE_LOW_POWER;
if (phy_cfg->flags & (1 << MC_CMD_GET_PHY_CFG_OUT_POWEROFF_LBN))
supported |= PHY_MODE_OFF;
mode = efx->phy_mode & supported;
flags = 0;
if (mode & PHY_MODE_TX_DISABLED)
flags |= (1 << MC_CMD_SET_LINK_IN_TXDIS_LBN);
if (mode & PHY_MODE_LOW_POWER)
flags |= (1 << MC_CMD_SET_LINK_IN_LOWPOWER_LBN);
if (mode & PHY_MODE_OFF)
flags |= (1 << MC_CMD_SET_LINK_IN_POWEROFF_LBN);
return flags;
}
static u8 mcdi_to_ethtool_media(u32 media)
{
switch (media) {
case MC_CMD_MEDIA_XAUI:
case MC_CMD_MEDIA_CX4:
case MC_CMD_MEDIA_KX4:
return PORT_OTHER;
case MC_CMD_MEDIA_XFP:
case MC_CMD_MEDIA_SFP_PLUS:
case MC_CMD_MEDIA_QSFP_PLUS:
return PORT_FIBRE;
case MC_CMD_MEDIA_BASE_T:
return PORT_TP;
default:
return PORT_OTHER;
}
}
static void efx_mcdi_phy_decode_link(struct efx_nic *efx,
struct efx_link_state *link_state,
u32 speed, u32 flags, u32 fcntl)
{
switch (fcntl) {
case MC_CMD_FCNTL_AUTO:
WARN_ON(1); /* This is not a link mode */
link_state->fc = EFX_FC_AUTO | EFX_FC_TX | EFX_FC_RX;
break;
case MC_CMD_FCNTL_BIDIR:
link_state->fc = EFX_FC_TX | EFX_FC_RX;
break;
case MC_CMD_FCNTL_RESPOND:
link_state->fc = EFX_FC_RX;
break;
default:
WARN_ON(1);
fallthrough;
case MC_CMD_FCNTL_OFF:
link_state->fc = 0;
break;
}
link_state->up = !!(flags & (1 << MC_CMD_GET_LINK_OUT_LINK_UP_LBN));
link_state->fd = !!(flags & (1 << MC_CMD_GET_LINK_OUT_FULL_DUPLEX_LBN));
link_state->speed = speed;
}
/* The semantics of the ethtool FEC mode bitmask are not well defined,
* particularly the meaning of combinations of bits. Which means we get to
* define our own semantics, as follows:
* OFF overrides any other bits, and means "disable all FEC" (with the
* exception of 25G KR4/CR4, where it is not possible to reject it if AN
* partner requests it).
* AUTO on its own means use cable requirements and link partner autoneg with
* fw-default preferences for the cable type.
* AUTO and either RS or BASER means use the specified FEC type if cable and
* link partner support it, otherwise autoneg/fw-default.
* RS or BASER alone means use the specified FEC type if cable and link partner
* support it and either requests it, otherwise no FEC.
* Both RS and BASER (whether AUTO or not) means use FEC if cable and link
* partner support it, preferring RS to BASER.
*/
static u32 ethtool_fec_caps_to_mcdi(u32 supported_cap, u32 ethtool_cap)
{
u32 ret = 0;
if (ethtool_cap & ETHTOOL_FEC_OFF)
return 0;
if (ethtool_cap & ETHTOOL_FEC_AUTO)
ret |= ((1 << MC_CMD_PHY_CAP_BASER_FEC_LBN) |
(1 << MC_CMD_PHY_CAP_25G_BASER_FEC_LBN) |
(1 << MC_CMD_PHY_CAP_RS_FEC_LBN)) & supported_cap;
if (ethtool_cap & ETHTOOL_FEC_RS &&
supported_cap & (1 << MC_CMD_PHY_CAP_RS_FEC_LBN))
ret |= (1 << MC_CMD_PHY_CAP_RS_FEC_LBN) |
(1 << MC_CMD_PHY_CAP_RS_FEC_REQUESTED_LBN);
if (ethtool_cap & ETHTOOL_FEC_BASER) {
if (supported_cap & (1 << MC_CMD_PHY_CAP_BASER_FEC_LBN))
ret |= (1 << MC_CMD_PHY_CAP_BASER_FEC_LBN) |
(1 << MC_CMD_PHY_CAP_BASER_FEC_REQUESTED_LBN);
if (supported_cap & (1 << MC_CMD_PHY_CAP_25G_BASER_FEC_LBN))
ret |= (1 << MC_CMD_PHY_CAP_25G_BASER_FEC_LBN) |
(1 << MC_CMD_PHY_CAP_25G_BASER_FEC_REQUESTED_LBN);
}
return ret;
}
/* Invert ethtool_fec_caps_to_mcdi. There are two combinations that function
* can never produce, (baser xor rs) and neither req; the implementation below
* maps both of those to AUTO. This should never matter, and it's not clear
* what a better mapping would be anyway.
*/
static u32 mcdi_fec_caps_to_ethtool(u32 caps, bool is_25g)
{
bool rs = caps & (1 << MC_CMD_PHY_CAP_RS_FEC_LBN),
rs_req = caps & (1 << MC_CMD_PHY_CAP_RS_FEC_REQUESTED_LBN),
baser = is_25g ? caps & (1 << MC_CMD_PHY_CAP_25G_BASER_FEC_LBN)
: caps & (1 << MC_CMD_PHY_CAP_BASER_FEC_LBN),
baser_req = is_25g ? caps & (1 << MC_CMD_PHY_CAP_25G_BASER_FEC_REQUESTED_LBN)
: caps & (1 << MC_CMD_PHY_CAP_BASER_FEC_REQUESTED_LBN);
if (!baser && !rs)
return ETHTOOL_FEC_OFF;
return (rs_req ? ETHTOOL_FEC_RS : 0) |
(baser_req ? ETHTOOL_FEC_BASER : 0) |
(baser == baser_req && rs == rs_req ? 0 : ETHTOOL_FEC_AUTO);
}
/* Verify that the forced flow control settings (!EFX_FC_AUTO) are
* supported by the link partner. Warn the user if this isn't the case
*/
static void efx_mcdi_phy_check_fcntl(struct efx_nic *efx, u32 lpa)
{
struct efx_mcdi_phy_data *phy_cfg = efx->phy_data;
u32 rmtadv;
/* The link partner capabilities are only relevant if the
* link supports flow control autonegotiation
*/
if (~phy_cfg->supported_cap & (1 << MC_CMD_PHY_CAP_AN_LBN))
return;
/* If flow control autoneg is supported and enabled, then fine */
if (efx->wanted_fc & EFX_FC_AUTO)
return;
rmtadv = 0;
if (lpa & (1 << MC_CMD_PHY_CAP_PAUSE_LBN))
rmtadv |= ADVERTISED_Pause;
if (lpa & (1 << MC_CMD_PHY_CAP_ASYM_LBN))
rmtadv |= ADVERTISED_Asym_Pause;
if ((efx->wanted_fc & EFX_FC_TX) && rmtadv == ADVERTISED_Asym_Pause)
netif_err(efx, link, efx->net_dev,
"warning: link partner doesn't support pause frames");
}
bool efx_siena_mcdi_phy_poll(struct efx_nic *efx)
{
struct efx_link_state old_state = efx->link_state;
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_LINK_OUT_LEN);
int rc;
WARN_ON(!mutex_is_locked(&efx->mac_lock));
BUILD_BUG_ON(MC_CMD_GET_LINK_IN_LEN != 0);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_GET_LINK, NULL, 0,
outbuf, sizeof(outbuf), NULL);
if (rc)
efx->link_state.up = false;
else
efx_mcdi_phy_decode_link(
efx, &efx->link_state,
MCDI_DWORD(outbuf, GET_LINK_OUT_LINK_SPEED),
MCDI_DWORD(outbuf, GET_LINK_OUT_FLAGS),
MCDI_DWORD(outbuf, GET_LINK_OUT_FCNTL));
return !efx_link_state_equal(&efx->link_state, &old_state);
}
int efx_siena_mcdi_phy_probe(struct efx_nic *efx)
{
struct efx_mcdi_phy_data *phy_data;
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_LINK_OUT_LEN);
u32 caps;
int rc;
/* Initialise and populate phy_data */
phy_data = kzalloc(sizeof(*phy_data), GFP_KERNEL);
if (phy_data == NULL)
return -ENOMEM;
rc = efx_mcdi_get_phy_cfg(efx, phy_data);
if (rc != 0)
goto fail;
/* Read initial link advertisement */
BUILD_BUG_ON(MC_CMD_GET_LINK_IN_LEN != 0);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_GET_LINK, NULL, 0,
outbuf, sizeof(outbuf), NULL);
if (rc)
goto fail;
/* Fill out nic state */
efx->phy_data = phy_data;
efx->phy_type = phy_data->type;
efx->mdio_bus = phy_data->channel;
efx->mdio.prtad = phy_data->port;
efx->mdio.mmds = phy_data->mmd_mask & ~(1 << MC_CMD_MMD_CLAUSE22);
efx->mdio.mode_support = 0;
if (phy_data->mmd_mask & (1 << MC_CMD_MMD_CLAUSE22))
efx->mdio.mode_support |= MDIO_SUPPORTS_C22;
if (phy_data->mmd_mask & ~(1 << MC_CMD_MMD_CLAUSE22))
efx->mdio.mode_support |= MDIO_SUPPORTS_C45 | MDIO_EMULATE_C22;
caps = MCDI_DWORD(outbuf, GET_LINK_OUT_CAP);
if (caps & (1 << MC_CMD_PHY_CAP_AN_LBN))
mcdi_to_ethtool_linkset(phy_data->media, caps,
efx->link_advertising);
else
phy_data->forced_cap = caps;
/* Assert that we can map efx -> mcdi loopback modes */
BUILD_BUG_ON(LOOPBACK_NONE != MC_CMD_LOOPBACK_NONE);
BUILD_BUG_ON(LOOPBACK_DATA != MC_CMD_LOOPBACK_DATA);
BUILD_BUG_ON(LOOPBACK_GMAC != MC_CMD_LOOPBACK_GMAC);
BUILD_BUG_ON(LOOPBACK_XGMII != MC_CMD_LOOPBACK_XGMII);
BUILD_BUG_ON(LOOPBACK_XGXS != MC_CMD_LOOPBACK_XGXS);
BUILD_BUG_ON(LOOPBACK_XAUI != MC_CMD_LOOPBACK_XAUI);
BUILD_BUG_ON(LOOPBACK_GMII != MC_CMD_LOOPBACK_GMII);
BUILD_BUG_ON(LOOPBACK_SGMII != MC_CMD_LOOPBACK_SGMII);
BUILD_BUG_ON(LOOPBACK_XGBR != MC_CMD_LOOPBACK_XGBR);
BUILD_BUG_ON(LOOPBACK_XFI != MC_CMD_LOOPBACK_XFI);
BUILD_BUG_ON(LOOPBACK_XAUI_FAR != MC_CMD_LOOPBACK_XAUI_FAR);
BUILD_BUG_ON(LOOPBACK_GMII_FAR != MC_CMD_LOOPBACK_GMII_FAR);
BUILD_BUG_ON(LOOPBACK_SGMII_FAR != MC_CMD_LOOPBACK_SGMII_FAR);
BUILD_BUG_ON(LOOPBACK_XFI_FAR != MC_CMD_LOOPBACK_XFI_FAR);
BUILD_BUG_ON(LOOPBACK_GPHY != MC_CMD_LOOPBACK_GPHY);
BUILD_BUG_ON(LOOPBACK_PHYXS != MC_CMD_LOOPBACK_PHYXS);
BUILD_BUG_ON(LOOPBACK_PCS != MC_CMD_LOOPBACK_PCS);
BUILD_BUG_ON(LOOPBACK_PMAPMD != MC_CMD_LOOPBACK_PMAPMD);
BUILD_BUG_ON(LOOPBACK_XPORT != MC_CMD_LOOPBACK_XPORT);
BUILD_BUG_ON(LOOPBACK_XGMII_WS != MC_CMD_LOOPBACK_XGMII_WS);
BUILD_BUG_ON(LOOPBACK_XAUI_WS != MC_CMD_LOOPBACK_XAUI_WS);
BUILD_BUG_ON(LOOPBACK_XAUI_WS_FAR != MC_CMD_LOOPBACK_XAUI_WS_FAR);
BUILD_BUG_ON(LOOPBACK_XAUI_WS_NEAR != MC_CMD_LOOPBACK_XAUI_WS_NEAR);
BUILD_BUG_ON(LOOPBACK_GMII_WS != MC_CMD_LOOPBACK_GMII_WS);
BUILD_BUG_ON(LOOPBACK_XFI_WS != MC_CMD_LOOPBACK_XFI_WS);
BUILD_BUG_ON(LOOPBACK_XFI_WS_FAR != MC_CMD_LOOPBACK_XFI_WS_FAR);
BUILD_BUG_ON(LOOPBACK_PHYXS_WS != MC_CMD_LOOPBACK_PHYXS_WS);
rc = efx_mcdi_loopback_modes(efx, &efx->loopback_modes);
if (rc != 0)
goto fail;
/* The MC indicates that LOOPBACK_NONE is a valid loopback mode,
* but by convention we don't
*/
efx->loopback_modes &= ~(1 << LOOPBACK_NONE);
/* Set the initial link mode */
efx_mcdi_phy_decode_link(efx, &efx->link_state,
MCDI_DWORD(outbuf, GET_LINK_OUT_LINK_SPEED),
MCDI_DWORD(outbuf, GET_LINK_OUT_FLAGS),
MCDI_DWORD(outbuf, GET_LINK_OUT_FCNTL));
/* Record the initial FEC configuration (or nearest approximation
* representable in the ethtool configuration space)
*/
efx->fec_config = mcdi_fec_caps_to_ethtool(caps,
efx->link_state.speed == 25000 ||
efx->link_state.speed == 50000);
/* Default to Autonegotiated flow control if the PHY supports it */
efx->wanted_fc = EFX_FC_RX | EFX_FC_TX;
if (phy_data->supported_cap & (1 << MC_CMD_PHY_CAP_AN_LBN))
efx->wanted_fc |= EFX_FC_AUTO;
efx_siena_link_set_wanted_fc(efx, efx->wanted_fc);
return 0;
fail:
kfree(phy_data);
return rc;
}
void efx_siena_mcdi_phy_remove(struct efx_nic *efx)
{
struct efx_mcdi_phy_data *phy_data = efx->phy_data;
efx->phy_data = NULL;
kfree(phy_data);
}
void efx_siena_mcdi_phy_get_link_ksettings(struct efx_nic *efx,
struct ethtool_link_ksettings *cmd)
{
struct efx_mcdi_phy_data *phy_cfg = efx->phy_data;
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_LINK_OUT_LEN);
int rc;
cmd->base.speed = efx->link_state.speed;
cmd->base.duplex = efx->link_state.fd;
cmd->base.port = mcdi_to_ethtool_media(phy_cfg->media);
cmd->base.phy_address = phy_cfg->port;
cmd->base.autoneg = !!(efx->link_advertising[0] & ADVERTISED_Autoneg);
cmd->base.mdio_support = (efx->mdio.mode_support &
(MDIO_SUPPORTS_C45 | MDIO_SUPPORTS_C22));
mcdi_to_ethtool_linkset(phy_cfg->media, phy_cfg->supported_cap,
cmd->link_modes.supported);
memcpy(cmd->link_modes.advertising, efx->link_advertising,
sizeof(__ETHTOOL_DECLARE_LINK_MODE_MASK()));
BUILD_BUG_ON(MC_CMD_GET_LINK_IN_LEN != 0);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_GET_LINK, NULL, 0,
outbuf, sizeof(outbuf), NULL);
if (rc)
return;
mcdi_to_ethtool_linkset(phy_cfg->media,
MCDI_DWORD(outbuf, GET_LINK_OUT_LP_CAP),
cmd->link_modes.lp_advertising);
}
int
efx_siena_mcdi_phy_set_link_ksettings(struct efx_nic *efx,
const struct ethtool_link_ksettings *cmd)
{
struct efx_mcdi_phy_data *phy_cfg = efx->phy_data;
u32 caps;
int rc;
if (cmd->base.autoneg) {
caps = (ethtool_linkset_to_mcdi_cap(cmd->link_modes.advertising) |
1 << MC_CMD_PHY_CAP_AN_LBN);
} else if (cmd->base.duplex) {
switch (cmd->base.speed) {
case 10: caps = 1 << MC_CMD_PHY_CAP_10FDX_LBN; break;
case 100: caps = 1 << MC_CMD_PHY_CAP_100FDX_LBN; break;
case 1000: caps = 1 << MC_CMD_PHY_CAP_1000FDX_LBN; break;
case 10000: caps = 1 << MC_CMD_PHY_CAP_10000FDX_LBN; break;
case 40000: caps = 1 << MC_CMD_PHY_CAP_40000FDX_LBN; break;
case 100000: caps = 1 << MC_CMD_PHY_CAP_100000FDX_LBN; break;
case 25000: caps = 1 << MC_CMD_PHY_CAP_25000FDX_LBN; break;
case 50000: caps = 1 << MC_CMD_PHY_CAP_50000FDX_LBN; break;
default: return -EINVAL;
}
} else {
switch (cmd->base.speed) {
case 10: caps = 1 << MC_CMD_PHY_CAP_10HDX_LBN; break;
case 100: caps = 1 << MC_CMD_PHY_CAP_100HDX_LBN; break;
case 1000: caps = 1 << MC_CMD_PHY_CAP_1000HDX_LBN; break;
default: return -EINVAL;
}
}
caps |= ethtool_fec_caps_to_mcdi(phy_cfg->supported_cap, efx->fec_config);
rc = efx_mcdi_set_link(efx, caps, efx_get_mcdi_phy_flags(efx),
efx->loopback_mode, 0);
if (rc)
return rc;
if (cmd->base.autoneg) {
efx_siena_link_set_advertising(efx, cmd->link_modes.advertising);
phy_cfg->forced_cap = 0;
} else {
efx_siena_link_clear_advertising(efx);
phy_cfg->forced_cap = caps;
}
return 0;
}
int efx_siena_mcdi_phy_get_fecparam(struct efx_nic *efx,
struct ethtool_fecparam *fec)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_LINK_OUT_V2_LEN);
u32 caps, active, speed; /* MCDI format */
bool is_25g = false;
size_t outlen;
int rc;
BUILD_BUG_ON(MC_CMD_GET_LINK_IN_LEN != 0);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_GET_LINK, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < MC_CMD_GET_LINK_OUT_V2_LEN)
return -EOPNOTSUPP;
/* behaviour for 25G/50G links depends on 25G BASER bit */
speed = MCDI_DWORD(outbuf, GET_LINK_OUT_V2_LINK_SPEED);
is_25g = speed == 25000 || speed == 50000;
caps = MCDI_DWORD(outbuf, GET_LINK_OUT_V2_CAP);
fec->fec = mcdi_fec_caps_to_ethtool(caps, is_25g);
/* BASER is never supported on 100G */
if (speed == 100000)
fec->fec &= ~ETHTOOL_FEC_BASER;
active = MCDI_DWORD(outbuf, GET_LINK_OUT_V2_FEC_TYPE);
switch (active) {
case MC_CMD_FEC_NONE:
fec->active_fec = ETHTOOL_FEC_OFF;
break;
case MC_CMD_FEC_BASER:
fec->active_fec = ETHTOOL_FEC_BASER;
break;
case MC_CMD_FEC_RS:
fec->active_fec = ETHTOOL_FEC_RS;
break;
default:
netif_warn(efx, hw, efx->net_dev,
"Firmware reports unrecognised FEC_TYPE %u\n",
active);
/* We don't know what firmware has picked. AUTO is as good a
* "can't happen" value as any other.
*/
fec->active_fec = ETHTOOL_FEC_AUTO;
break;
}
return 0;
}
/* Basic validation to ensure that the caps we are going to attempt to set are
* in fact supported by the adapter. Note that 'no FEC' is always supported.
*/
static int ethtool_fec_supported(u32 supported_cap, u32 ethtool_cap)
{
if (ethtool_cap & ETHTOOL_FEC_OFF)
return 0;
if (ethtool_cap &&
!ethtool_fec_caps_to_mcdi(supported_cap, ethtool_cap))
return -EINVAL;
return 0;
}
int efx_siena_mcdi_phy_set_fecparam(struct efx_nic *efx,
const struct ethtool_fecparam *fec)
{
struct efx_mcdi_phy_data *phy_cfg = efx->phy_data;
u32 caps;
int rc;
rc = ethtool_fec_supported(phy_cfg->supported_cap, fec->fec);
if (rc)
return rc;
/* Work out what efx_siena_mcdi_phy_set_link_ksettings() would produce from
* saved advertising bits
*/
if (test_bit(ETHTOOL_LINK_MODE_Autoneg_BIT, efx->link_advertising))
caps = (ethtool_linkset_to_mcdi_cap(efx->link_advertising) |
1 << MC_CMD_PHY_CAP_AN_LBN);
else
caps = phy_cfg->forced_cap;
caps |= ethtool_fec_caps_to_mcdi(phy_cfg->supported_cap, fec->fec);
rc = efx_mcdi_set_link(efx, caps, efx_get_mcdi_phy_flags(efx),
efx->loopback_mode, 0);
if (rc)
return rc;
/* Record the new FEC setting for subsequent set_link calls */
efx->fec_config = fec->fec;
return 0;
}
int efx_siena_mcdi_phy_test_alive(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_PHY_STATE_OUT_LEN);
size_t outlen;
int rc;
BUILD_BUG_ON(MC_CMD_GET_PHY_STATE_IN_LEN != 0);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_GET_PHY_STATE, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (outlen < MC_CMD_GET_PHY_STATE_OUT_LEN)
return -EIO;
if (MCDI_DWORD(outbuf, GET_PHY_STATE_OUT_STATE) != MC_CMD_PHY_STATE_OK)
return -EINVAL;
return 0;
}
int efx_siena_mcdi_port_reconfigure(struct efx_nic *efx)
{
struct efx_mcdi_phy_data *phy_cfg = efx->phy_data;
u32 caps = (efx->link_advertising[0] ?
ethtool_linkset_to_mcdi_cap(efx->link_advertising) :
phy_cfg->forced_cap);
caps |= ethtool_fec_caps_to_mcdi(phy_cfg->supported_cap, efx->fec_config);
return efx_mcdi_set_link(efx, caps, efx_get_mcdi_phy_flags(efx),
efx->loopback_mode, 0);
}
static const char *const mcdi_sft9001_cable_diag_names[] = {
"cable.pairA.length",
"cable.pairB.length",
"cable.pairC.length",
"cable.pairD.length",
"cable.pairA.status",
"cable.pairB.status",
"cable.pairC.status",
"cable.pairD.status",
};
static int efx_mcdi_bist(struct efx_nic *efx, unsigned int bist_mode,
int *results)
{
unsigned int retry, i, count = 0;
size_t outlen;
u32 status;
MCDI_DECLARE_BUF(inbuf, MC_CMD_START_BIST_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_POLL_BIST_OUT_SFT9001_LEN);
u8 *ptr;
int rc;
BUILD_BUG_ON(MC_CMD_START_BIST_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, START_BIST_IN_TYPE, bist_mode);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_START_BIST, inbuf,
MC_CMD_START_BIST_IN_LEN, NULL, 0, NULL);
if (rc)
goto out;
/* Wait up to 10s for BIST to finish */
for (retry = 0; retry < 100; ++retry) {
BUILD_BUG_ON(MC_CMD_POLL_BIST_IN_LEN != 0);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_POLL_BIST, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto out;
status = MCDI_DWORD(outbuf, POLL_BIST_OUT_RESULT);
if (status != MC_CMD_POLL_BIST_RUNNING)
goto finished;
msleep(100);
}
rc = -ETIMEDOUT;
goto out;
finished:
results[count++] = (status == MC_CMD_POLL_BIST_PASSED) ? 1 : -1;
/* SFT9001 specific cable diagnostics output */
if (efx->phy_type == PHY_TYPE_SFT9001B &&
(bist_mode == MC_CMD_PHY_BIST_CABLE_SHORT ||
bist_mode == MC_CMD_PHY_BIST_CABLE_LONG)) {
ptr = MCDI_PTR(outbuf, POLL_BIST_OUT_SFT9001_CABLE_LENGTH_A);
if (status == MC_CMD_POLL_BIST_PASSED &&
outlen >= MC_CMD_POLL_BIST_OUT_SFT9001_LEN) {
for (i = 0; i < 8; i++) {
results[count + i] =
EFX_DWORD_FIELD(((efx_dword_t *)ptr)[i],
EFX_DWORD_0);
}
}
count += 8;
}
rc = count;
out:
return rc;
}
int efx_siena_mcdi_phy_run_tests(struct efx_nic *efx, int *results,
unsigned int flags)
{
struct efx_mcdi_phy_data *phy_cfg = efx->phy_data;
u32 mode;
int rc;
if (phy_cfg->flags & (1 << MC_CMD_GET_PHY_CFG_OUT_BIST_LBN)) {
rc = efx_mcdi_bist(efx, MC_CMD_PHY_BIST, results);
if (rc < 0)
return rc;
results += rc;
}
/* If we support both LONG and SHORT, then run each in response to
* break or not. Otherwise, run the one we support
*/
mode = 0;
if (phy_cfg->flags & (1 << MC_CMD_GET_PHY_CFG_OUT_BIST_CABLE_SHORT_LBN)) {
if ((flags & ETH_TEST_FL_OFFLINE) &&
(phy_cfg->flags &
(1 << MC_CMD_GET_PHY_CFG_OUT_BIST_CABLE_LONG_LBN)))
mode = MC_CMD_PHY_BIST_CABLE_LONG;
else
mode = MC_CMD_PHY_BIST_CABLE_SHORT;
} else if (phy_cfg->flags &
(1 << MC_CMD_GET_PHY_CFG_OUT_BIST_CABLE_LONG_LBN))
mode = MC_CMD_PHY_BIST_CABLE_LONG;
if (mode != 0) {
rc = efx_mcdi_bist(efx, mode, results);
if (rc < 0)
return rc;
results += rc;
}
return 0;
}
const char *efx_siena_mcdi_phy_test_name(struct efx_nic *efx,
unsigned int index)
{
struct efx_mcdi_phy_data *phy_cfg = efx->phy_data;
if (phy_cfg->flags & (1 << MC_CMD_GET_PHY_CFG_OUT_BIST_LBN)) {
if (index == 0)
return "bist";
--index;
}
if (phy_cfg->flags & ((1 << MC_CMD_GET_PHY_CFG_OUT_BIST_CABLE_SHORT_LBN) |
(1 << MC_CMD_GET_PHY_CFG_OUT_BIST_CABLE_LONG_LBN))) {
if (index == 0)
return "cable";
--index;
if (efx->phy_type == PHY_TYPE_SFT9001B) {
if (index < ARRAY_SIZE(mcdi_sft9001_cable_diag_names))
return mcdi_sft9001_cable_diag_names[index];
index -= ARRAY_SIZE(mcdi_sft9001_cable_diag_names);
}
}
return NULL;
}
#define SFP_PAGE_SIZE 128
#define SFF_DIAG_TYPE_OFFSET 92
#define SFF_DIAG_ADDR_CHANGE BIT(2)
#define SFF_8079_NUM_PAGES 2
#define SFF_8472_NUM_PAGES 4
#define SFF_8436_NUM_PAGES 5
#define SFF_DMT_LEVEL_OFFSET 94
/** efx_mcdi_phy_get_module_eeprom_page() - Get a single page of module eeprom
* @efx: NIC context
* @page: EEPROM page number
* @data: Destination data pointer
* @offset: Offset in page to copy from in to data
* @space: Space available in data
*
* Return:
* >=0 - amount of data copied
* <0 - error
*/
static int efx_mcdi_phy_get_module_eeprom_page(struct efx_nic *efx,
unsigned int page,
u8 *data, ssize_t offset,
ssize_t space)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_PHY_MEDIA_INFO_OUT_LENMAX);
MCDI_DECLARE_BUF(inbuf, MC_CMD_GET_PHY_MEDIA_INFO_IN_LEN);
unsigned int payload_len;
unsigned int to_copy;
size_t outlen;
int rc;
if (offset > SFP_PAGE_SIZE)
return -EINVAL;
to_copy = min(space, SFP_PAGE_SIZE - offset);
MCDI_SET_DWORD(inbuf, GET_PHY_MEDIA_INFO_IN_PAGE, page);
rc = efx_siena_mcdi_rpc_quiet(efx, MC_CMD_GET_PHY_MEDIA_INFO,
inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf),
&outlen);
if (rc)
return rc;
if (outlen < (MC_CMD_GET_PHY_MEDIA_INFO_OUT_DATA_OFST +
SFP_PAGE_SIZE))
return -EIO;
payload_len = MCDI_DWORD(outbuf, GET_PHY_MEDIA_INFO_OUT_DATALEN);
if (payload_len != SFP_PAGE_SIZE)
return -EIO;
memcpy(data, MCDI_PTR(outbuf, GET_PHY_MEDIA_INFO_OUT_DATA) + offset,
to_copy);
return to_copy;
}
static int efx_mcdi_phy_get_module_eeprom_byte(struct efx_nic *efx,
unsigned int page,
u8 byte)
{
u8 data;
int rc;
rc = efx_mcdi_phy_get_module_eeprom_page(efx, page, &data, byte, 1);
if (rc == 1)
return data;
return rc;
}
static int efx_mcdi_phy_diag_type(struct efx_nic *efx)
{
/* Page zero of the EEPROM includes the diagnostic type at byte 92. */
return efx_mcdi_phy_get_module_eeprom_byte(efx, 0,
SFF_DIAG_TYPE_OFFSET);
}
static int efx_mcdi_phy_sff_8472_level(struct efx_nic *efx)
{
/* Page zero of the EEPROM includes the DMT level at byte 94. */
return efx_mcdi_phy_get_module_eeprom_byte(efx, 0,
SFF_DMT_LEVEL_OFFSET);
}
static u32 efx_mcdi_phy_module_type(struct efx_nic *efx)
{
struct efx_mcdi_phy_data *phy_data = efx->phy_data;
if (phy_data->media != MC_CMD_MEDIA_QSFP_PLUS)
return phy_data->media;
/* A QSFP+ NIC may actually have an SFP+ module attached.
* The ID is page 0, byte 0.
*/
switch (efx_mcdi_phy_get_module_eeprom_byte(efx, 0, 0)) {
case 0x3:
return MC_CMD_MEDIA_SFP_PLUS;
case 0xc:
case 0xd:
return MC_CMD_MEDIA_QSFP_PLUS;
default:
return 0;
}
}
int efx_siena_mcdi_phy_get_module_eeprom(struct efx_nic *efx,
struct ethtool_eeprom *ee, u8 *data)
{
int rc;
ssize_t space_remaining = ee->len;
unsigned int page_off;
bool ignore_missing;
int num_pages;
int page;
switch (efx_mcdi_phy_module_type(efx)) {
case MC_CMD_MEDIA_SFP_PLUS:
num_pages = efx_mcdi_phy_sff_8472_level(efx) > 0 ?
SFF_8472_NUM_PAGES : SFF_8079_NUM_PAGES;
page = 0;
ignore_missing = false;
break;
case MC_CMD_MEDIA_QSFP_PLUS:
num_pages = SFF_8436_NUM_PAGES;
page = -1; /* We obtain the lower page by asking for -1. */
ignore_missing = true; /* Ignore missing pages after page 0. */
break;
default:
return -EOPNOTSUPP;
}
page_off = ee->offset % SFP_PAGE_SIZE;
page += ee->offset / SFP_PAGE_SIZE;
while (space_remaining && (page < num_pages)) {
rc = efx_mcdi_phy_get_module_eeprom_page(efx, page,
data, page_off,
space_remaining);
if (rc > 0) {
space_remaining -= rc;
data += rc;
page_off = 0;
page++;
} else if (rc == 0) {
space_remaining = 0;
} else if (ignore_missing && (page > 0)) {
int intended_size = SFP_PAGE_SIZE - page_off;
space_remaining -= intended_size;
if (space_remaining < 0) {
space_remaining = 0;
} else {
memset(data, 0, intended_size);
data += intended_size;
page_off = 0;
page++;
rc = 0;
}
} else {
return rc;
}
}
return 0;
}
int efx_siena_mcdi_phy_get_module_info(struct efx_nic *efx, struct ethtool_modinfo *modinfo)
{
int sff_8472_level;
int diag_type;
switch (efx_mcdi_phy_module_type(efx)) {
case MC_CMD_MEDIA_SFP_PLUS:
sff_8472_level = efx_mcdi_phy_sff_8472_level(efx);
/* If we can't read the diagnostics level we have none. */
if (sff_8472_level < 0)
return -EOPNOTSUPP;
/* Check if this module requires the (unsupported) address
* change operation.
*/
diag_type = efx_mcdi_phy_diag_type(efx);
if (sff_8472_level == 0 ||
(diag_type & SFF_DIAG_ADDR_CHANGE)) {
modinfo->type = ETH_MODULE_SFF_8079;
modinfo->eeprom_len = ETH_MODULE_SFF_8079_LEN;
} else {
modinfo->type = ETH_MODULE_SFF_8472;
modinfo->eeprom_len = ETH_MODULE_SFF_8472_LEN;
}
break;
case MC_CMD_MEDIA_QSFP_PLUS:
modinfo->type = ETH_MODULE_SFF_8436;
modinfo->eeprom_len = ETH_MODULE_SFF_8436_LEN;
break;
default:
return -EOPNOTSUPP;
}
return 0;
}
static unsigned int efx_calc_mac_mtu(struct efx_nic *efx)
{
return EFX_MAX_FRAME_LEN(efx->net_dev->mtu);
}
int efx_siena_mcdi_set_mac(struct efx_nic *efx)
{
u32 fcntl;
MCDI_DECLARE_BUF(cmdbytes, MC_CMD_SET_MAC_IN_LEN);
BUILD_BUG_ON(MC_CMD_SET_MAC_OUT_LEN != 0);
/* This has no effect on EF10 */
ether_addr_copy(MCDI_PTR(cmdbytes, SET_MAC_IN_ADDR),
efx->net_dev->dev_addr);
MCDI_SET_DWORD(cmdbytes, SET_MAC_IN_MTU, efx_calc_mac_mtu(efx));
MCDI_SET_DWORD(cmdbytes, SET_MAC_IN_DRAIN, 0);
/* Set simple MAC filter for Siena */
MCDI_POPULATE_DWORD_1(cmdbytes, SET_MAC_IN_REJECT,
SET_MAC_IN_REJECT_UNCST, efx->unicast_filter);
MCDI_POPULATE_DWORD_1(cmdbytes, SET_MAC_IN_FLAGS,
SET_MAC_IN_FLAG_INCLUDE_FCS,
!!(efx->net_dev->features & NETIF_F_RXFCS));
switch (efx->wanted_fc) {
case EFX_FC_RX | EFX_FC_TX:
fcntl = MC_CMD_FCNTL_BIDIR;
break;
case EFX_FC_RX:
fcntl = MC_CMD_FCNTL_RESPOND;
break;
default:
fcntl = MC_CMD_FCNTL_OFF;
break;
}
if (efx->wanted_fc & EFX_FC_AUTO)
fcntl = MC_CMD_FCNTL_AUTO;
if (efx->fc_disable)
fcntl = MC_CMD_FCNTL_OFF;
MCDI_SET_DWORD(cmdbytes, SET_MAC_IN_FCNTL, fcntl);
return efx_siena_mcdi_rpc(efx, MC_CMD_SET_MAC, cmdbytes,
sizeof(cmdbytes), NULL, 0, NULL);
}
enum efx_stats_action {
EFX_STATS_ENABLE,
EFX_STATS_DISABLE,
EFX_STATS_PULL,
};
static int efx_mcdi_mac_stats(struct efx_nic *efx,
enum efx_stats_action action, int clear)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_MAC_STATS_IN_LEN);
int rc;
int change = action == EFX_STATS_PULL ? 0 : 1;
int enable = action == EFX_STATS_ENABLE ? 1 : 0;
int period = action == EFX_STATS_ENABLE ? 1000 : 0;
dma_addr_t dma_addr = efx->stats_buffer.dma_addr;
u32 dma_len = action != EFX_STATS_DISABLE ?
efx->num_mac_stats * sizeof(u64) : 0;
BUILD_BUG_ON(MC_CMD_MAC_STATS_OUT_DMA_LEN != 0);
MCDI_SET_QWORD(inbuf, MAC_STATS_IN_DMA_ADDR, dma_addr);
MCDI_POPULATE_DWORD_7(inbuf, MAC_STATS_IN_CMD,
MAC_STATS_IN_DMA, !!enable,
MAC_STATS_IN_CLEAR, clear,
MAC_STATS_IN_PERIODIC_CHANGE, change,
MAC_STATS_IN_PERIODIC_ENABLE, enable,
MAC_STATS_IN_PERIODIC_CLEAR, 0,
MAC_STATS_IN_PERIODIC_NOEVENT, 1,
MAC_STATS_IN_PERIOD_MS, period);
MCDI_SET_DWORD(inbuf, MAC_STATS_IN_DMA_LEN, dma_len);
if (efx_nic_rev(efx) >= EFX_REV_HUNT_A0)
MCDI_SET_DWORD(inbuf, MAC_STATS_IN_PORT_ID, efx->vport_id);
rc = efx_siena_mcdi_rpc_quiet(efx, MC_CMD_MAC_STATS, inbuf,
sizeof(inbuf), NULL, 0, NULL);
/* Expect ENOENT if DMA queues have not been set up */
if (rc && (rc != -ENOENT || atomic_read(&efx->active_queues)))
efx_siena_mcdi_display_error(efx, MC_CMD_MAC_STATS,
sizeof(inbuf), NULL, 0, rc);
return rc;
}
void efx_siena_mcdi_mac_start_stats(struct efx_nic *efx)
{
__le64 *dma_stats = efx->stats_buffer.addr;
dma_stats[efx->num_mac_stats - 1] = EFX_MC_STATS_GENERATION_INVALID;
efx_mcdi_mac_stats(efx, EFX_STATS_ENABLE, 0);
}
void efx_siena_mcdi_mac_stop_stats(struct efx_nic *efx)
{
efx_mcdi_mac_stats(efx, EFX_STATS_DISABLE, 0);
}
#define EFX_MAC_STATS_WAIT_US 100
#define EFX_MAC_STATS_WAIT_ATTEMPTS 10
void efx_siena_mcdi_mac_pull_stats(struct efx_nic *efx)
{
__le64 *dma_stats = efx->stats_buffer.addr;
int attempts = EFX_MAC_STATS_WAIT_ATTEMPTS;
dma_stats[efx->num_mac_stats - 1] = EFX_MC_STATS_GENERATION_INVALID;
efx_mcdi_mac_stats(efx, EFX_STATS_PULL, 0);
while (dma_stats[efx->num_mac_stats - 1] ==
EFX_MC_STATS_GENERATION_INVALID &&
attempts-- != 0)
udelay(EFX_MAC_STATS_WAIT_US);
}
int efx_siena_mcdi_mac_init_stats(struct efx_nic *efx)
{
int rc;
if (!efx->num_mac_stats)
return 0;
/* Allocate buffer for stats */
rc = efx_siena_alloc_buffer(efx, &efx->stats_buffer,
efx->num_mac_stats * sizeof(u64),
GFP_KERNEL);
if (rc) {
netif_warn(efx, probe, efx->net_dev,
"failed to allocate DMA buffer: %d\n", rc);
return rc;
}
netif_dbg(efx, probe, efx->net_dev,
"stats buffer at %llx (virt %p phys %llx)\n",
(u64) efx->stats_buffer.dma_addr,
efx->stats_buffer.addr,
(u64) virt_to_phys(efx->stats_buffer.addr));
return 0;
}
void efx_siena_mcdi_mac_fini_stats(struct efx_nic *efx)
{
efx_siena_free_buffer(efx, &efx->stats_buffer);
}
static unsigned int efx_mcdi_event_link_speed[] = {
[MCDI_EVENT_LINKCHANGE_SPEED_100M] = 100,
[MCDI_EVENT_LINKCHANGE_SPEED_1G] = 1000,
[MCDI_EVENT_LINKCHANGE_SPEED_10G] = 10000,
[MCDI_EVENT_LINKCHANGE_SPEED_40G] = 40000,
[MCDI_EVENT_LINKCHANGE_SPEED_25G] = 25000,
[MCDI_EVENT_LINKCHANGE_SPEED_50G] = 50000,
[MCDI_EVENT_LINKCHANGE_SPEED_100G] = 100000,
};
void efx_siena_mcdi_process_link_change(struct efx_nic *efx, efx_qword_t *ev)
{
u32 flags, fcntl, speed, lpa;
speed = EFX_QWORD_FIELD(*ev, MCDI_EVENT_LINKCHANGE_SPEED);
EFX_WARN_ON_PARANOID(speed >= ARRAY_SIZE(efx_mcdi_event_link_speed));
speed = efx_mcdi_event_link_speed[speed];
flags = EFX_QWORD_FIELD(*ev, MCDI_EVENT_LINKCHANGE_LINK_FLAGS);
fcntl = EFX_QWORD_FIELD(*ev, MCDI_EVENT_LINKCHANGE_FCNTL);
lpa = EFX_QWORD_FIELD(*ev, MCDI_EVENT_LINKCHANGE_LP_CAP);
/* efx->link_state is only modified by efx_mcdi_phy_get_link(),
* which is only run after flushing the event queues. Therefore, it
* is safe to modify the link state outside of the mac_lock here.
*/
efx_mcdi_phy_decode_link(efx, &efx->link_state, speed, flags, fcntl);
efx_mcdi_phy_check_fcntl(efx, lpa);
efx_siena_link_status_changed(efx);
}
|
linux-master
|
drivers/net/ethernet/sfc/siena/mcdi_port_common.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2005-2006 Fen Systems Ltd.
* Copyright 2005-2013 Solarflare Communications Inc.
*/
#include <linux/filter.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/delay.h>
#include <linux/notifier.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/in.h>
#include <linux/ethtool.h>
#include <linux/topology.h>
#include <linux/gfp.h>
#include <linux/interrupt.h>
#include "net_driver.h"
#include <net/gre.h>
#include <net/udp_tunnel.h>
#include "efx.h"
#include "efx_common.h"
#include "efx_channels.h"
#include "rx_common.h"
#include "tx_common.h"
#include "nic.h"
#include "io.h"
#include "selftest.h"
#include "sriov.h"
#ifdef CONFIG_SFC_SIENA_SRIOV
#include "siena_sriov.h"
#endif
#include "mcdi_port_common.h"
#include "mcdi_pcol.h"
#include "workarounds.h"
/**************************************************************************
*
* Configurable values
*
*************************************************************************/
module_param_named(interrupt_mode, efx_siena_interrupt_mode, uint, 0444);
MODULE_PARM_DESC(interrupt_mode,
"Interrupt mode (0=>MSIX 1=>MSI 2=>legacy)");
module_param_named(rss_cpus, efx_siena_rss_cpus, uint, 0444);
MODULE_PARM_DESC(rss_cpus, "Number of CPUs to use for Receive-Side Scaling");
/*
* Use separate channels for TX and RX events
*
* Set this to 1 to use separate channels for TX and RX. It allows us
* to control interrupt affinity separately for TX and RX.
*
* This is only used in MSI-X interrupt mode
*/
bool efx_siena_separate_tx_channels;
module_param_named(efx_separate_tx_channels, efx_siena_separate_tx_channels,
bool, 0444);
MODULE_PARM_DESC(efx_separate_tx_channels,
"Use separate channels for TX and RX");
/* Initial interrupt moderation settings. They can be modified after
* module load with ethtool.
*
* The default for RX should strike a balance between increasing the
* round-trip latency and reducing overhead.
*/
static unsigned int rx_irq_mod_usec = 60;
/* Initial interrupt moderation settings. They can be modified after
* module load with ethtool.
*
* This default is chosen to ensure that a 10G link does not go idle
* while a TX queue is stopped after it has become full. A queue is
* restarted when it drops below half full. The time this takes (assuming
* worst case 3 descriptors per packet and 1024 descriptors) is
* 512 / 3 * 1.2 = 205 usec.
*/
static unsigned int tx_irq_mod_usec = 150;
static bool phy_flash_cfg;
module_param(phy_flash_cfg, bool, 0644);
MODULE_PARM_DESC(phy_flash_cfg, "Set PHYs into reflash mode initially");
static unsigned debug = (NETIF_MSG_DRV | NETIF_MSG_PROBE |
NETIF_MSG_LINK | NETIF_MSG_IFDOWN |
NETIF_MSG_IFUP | NETIF_MSG_RX_ERR |
NETIF_MSG_TX_ERR | NETIF_MSG_HW);
module_param(debug, uint, 0);
MODULE_PARM_DESC(debug, "Bitmapped debugging message enable value");
/**************************************************************************
*
* Utility functions and prototypes
*
*************************************************************************/
static void efx_remove_port(struct efx_nic *efx);
static int efx_xdp_setup_prog(struct efx_nic *efx, struct bpf_prog *prog);
static int efx_xdp(struct net_device *dev, struct netdev_bpf *xdp);
static int efx_xdp_xmit(struct net_device *dev, int n, struct xdp_frame **xdpfs,
u32 flags);
#define EFX_ASSERT_RESET_SERIALISED(efx) \
do { \
if ((efx->state == STATE_READY) || \
(efx->state == STATE_RECOVERY) || \
(efx->state == STATE_DISABLED)) \
ASSERT_RTNL(); \
} while (0)
/**************************************************************************
*
* Port handling
*
**************************************************************************/
static void efx_fini_port(struct efx_nic *efx);
static int efx_probe_port(struct efx_nic *efx)
{
int rc;
netif_dbg(efx, probe, efx->net_dev, "create port\n");
if (phy_flash_cfg)
efx->phy_mode = PHY_MODE_SPECIAL;
/* Connect up MAC/PHY operations table */
rc = efx->type->probe_port(efx);
if (rc)
return rc;
/* Initialise MAC address to permanent address */
eth_hw_addr_set(efx->net_dev, efx->net_dev->perm_addr);
return 0;
}
static int efx_init_port(struct efx_nic *efx)
{
int rc;
netif_dbg(efx, drv, efx->net_dev, "init port\n");
mutex_lock(&efx->mac_lock);
efx->port_initialized = true;
/* Ensure the PHY advertises the correct flow control settings */
rc = efx_siena_mcdi_port_reconfigure(efx);
if (rc && rc != -EPERM)
goto fail;
mutex_unlock(&efx->mac_lock);
return 0;
fail:
mutex_unlock(&efx->mac_lock);
return rc;
}
static void efx_fini_port(struct efx_nic *efx)
{
netif_dbg(efx, drv, efx->net_dev, "shut down port\n");
if (!efx->port_initialized)
return;
efx->port_initialized = false;
efx->link_state.up = false;
efx_siena_link_status_changed(efx);
}
static void efx_remove_port(struct efx_nic *efx)
{
netif_dbg(efx, drv, efx->net_dev, "destroying port\n");
efx->type->remove_port(efx);
}
/**************************************************************************
*
* NIC handling
*
**************************************************************************/
static LIST_HEAD(efx_primary_list);
static LIST_HEAD(efx_unassociated_list);
static bool efx_same_controller(struct efx_nic *left, struct efx_nic *right)
{
return left->type == right->type &&
left->vpd_sn && right->vpd_sn &&
!strcmp(left->vpd_sn, right->vpd_sn);
}
static void efx_associate(struct efx_nic *efx)
{
struct efx_nic *other, *next;
if (efx->primary == efx) {
/* Adding primary function; look for secondaries */
netif_dbg(efx, probe, efx->net_dev, "adding to primary list\n");
list_add_tail(&efx->node, &efx_primary_list);
list_for_each_entry_safe(other, next, &efx_unassociated_list,
node) {
if (efx_same_controller(efx, other)) {
list_del(&other->node);
netif_dbg(other, probe, other->net_dev,
"moving to secondary list of %s %s\n",
pci_name(efx->pci_dev),
efx->net_dev->name);
list_add_tail(&other->node,
&efx->secondary_list);
other->primary = efx;
}
}
} else {
/* Adding secondary function; look for primary */
list_for_each_entry(other, &efx_primary_list, node) {
if (efx_same_controller(efx, other)) {
netif_dbg(efx, probe, efx->net_dev,
"adding to secondary list of %s %s\n",
pci_name(other->pci_dev),
other->net_dev->name);
list_add_tail(&efx->node,
&other->secondary_list);
efx->primary = other;
return;
}
}
netif_dbg(efx, probe, efx->net_dev,
"adding to unassociated list\n");
list_add_tail(&efx->node, &efx_unassociated_list);
}
}
static void efx_dissociate(struct efx_nic *efx)
{
struct efx_nic *other, *next;
list_del(&efx->node);
efx->primary = NULL;
list_for_each_entry_safe(other, next, &efx->secondary_list, node) {
list_del(&other->node);
netif_dbg(other, probe, other->net_dev,
"moving to unassociated list\n");
list_add_tail(&other->node, &efx_unassociated_list);
other->primary = NULL;
}
}
static int efx_probe_nic(struct efx_nic *efx)
{
int rc;
netif_dbg(efx, probe, efx->net_dev, "creating NIC\n");
/* Carry out hardware-type specific initialisation */
rc = efx->type->probe(efx);
if (rc)
return rc;
do {
if (!efx->max_channels || !efx->max_tx_channels) {
netif_err(efx, drv, efx->net_dev,
"Insufficient resources to allocate"
" any channels\n");
rc = -ENOSPC;
goto fail1;
}
/* Determine the number of channels and queues by trying
* to hook in MSI-X interrupts.
*/
rc = efx_siena_probe_interrupts(efx);
if (rc)
goto fail1;
rc = efx_siena_set_channels(efx);
if (rc)
goto fail1;
/* dimension_resources can fail with EAGAIN */
rc = efx->type->dimension_resources(efx);
if (rc != 0 && rc != -EAGAIN)
goto fail2;
if (rc == -EAGAIN)
/* try again with new max_channels */
efx_siena_remove_interrupts(efx);
} while (rc == -EAGAIN);
if (efx->n_channels > 1)
netdev_rss_key_fill(efx->rss_context.rx_hash_key,
sizeof(efx->rss_context.rx_hash_key));
efx_siena_set_default_rx_indir_table(efx, &efx->rss_context);
/* Initialise the interrupt moderation settings */
efx->irq_mod_step_us = DIV_ROUND_UP(efx->timer_quantum_ns, 1000);
efx_siena_init_irq_moderation(efx, tx_irq_mod_usec, rx_irq_mod_usec,
true, true);
return 0;
fail2:
efx_siena_remove_interrupts(efx);
fail1:
efx->type->remove(efx);
return rc;
}
static void efx_remove_nic(struct efx_nic *efx)
{
netif_dbg(efx, drv, efx->net_dev, "destroying NIC\n");
efx_siena_remove_interrupts(efx);
efx->type->remove(efx);
}
/**************************************************************************
*
* NIC startup/shutdown
*
*************************************************************************/
static int efx_probe_all(struct efx_nic *efx)
{
int rc;
rc = efx_probe_nic(efx);
if (rc) {
netif_err(efx, probe, efx->net_dev, "failed to create NIC\n");
goto fail1;
}
rc = efx_probe_port(efx);
if (rc) {
netif_err(efx, probe, efx->net_dev, "failed to create port\n");
goto fail2;
}
BUILD_BUG_ON(EFX_DEFAULT_DMAQ_SIZE < EFX_RXQ_MIN_ENT);
if (WARN_ON(EFX_DEFAULT_DMAQ_SIZE < EFX_TXQ_MIN_ENT(efx))) {
rc = -EINVAL;
goto fail3;
}
#ifdef CONFIG_SFC_SIENA_SRIOV
rc = efx->type->vswitching_probe(efx);
if (rc) /* not fatal; the PF will still work fine */
netif_warn(efx, probe, efx->net_dev,
"failed to setup vswitching rc=%d;"
" VFs may not function\n", rc);
#endif
rc = efx_siena_probe_filters(efx);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"failed to create filter tables\n");
goto fail4;
}
rc = efx_siena_probe_channels(efx);
if (rc)
goto fail5;
return 0;
fail5:
efx_siena_remove_filters(efx);
fail4:
#ifdef CONFIG_SFC_SIENA_SRIOV
efx->type->vswitching_remove(efx);
#endif
fail3:
efx_remove_port(efx);
fail2:
efx_remove_nic(efx);
fail1:
return rc;
}
static void efx_remove_all(struct efx_nic *efx)
{
rtnl_lock();
efx_xdp_setup_prog(efx, NULL);
rtnl_unlock();
efx_siena_remove_channels(efx);
efx_siena_remove_filters(efx);
#ifdef CONFIG_SFC_SIENA_SRIOV
efx->type->vswitching_remove(efx);
#endif
efx_remove_port(efx);
efx_remove_nic(efx);
}
/**************************************************************************
*
* Interrupt moderation
*
**************************************************************************/
unsigned int efx_siena_usecs_to_ticks(struct efx_nic *efx, unsigned int usecs)
{
if (usecs == 0)
return 0;
if (usecs * 1000 < efx->timer_quantum_ns)
return 1; /* never round down to 0 */
return usecs * 1000 / efx->timer_quantum_ns;
}
/* Set interrupt moderation parameters */
int efx_siena_init_irq_moderation(struct efx_nic *efx, unsigned int tx_usecs,
unsigned int rx_usecs, bool rx_adaptive,
bool rx_may_override_tx)
{
struct efx_channel *channel;
unsigned int timer_max_us;
EFX_ASSERT_RESET_SERIALISED(efx);
timer_max_us = efx->timer_max_ns / 1000;
if (tx_usecs > timer_max_us || rx_usecs > timer_max_us)
return -EINVAL;
if (tx_usecs != rx_usecs && efx->tx_channel_offset == 0 &&
!rx_may_override_tx) {
netif_err(efx, drv, efx->net_dev, "Channels are shared. "
"RX and TX IRQ moderation must be equal\n");
return -EINVAL;
}
efx->irq_rx_adaptive = rx_adaptive;
efx->irq_rx_moderation_us = rx_usecs;
efx_for_each_channel(channel, efx) {
if (efx_channel_has_rx_queue(channel))
channel->irq_moderation_us = rx_usecs;
else if (efx_channel_has_tx_queues(channel))
channel->irq_moderation_us = tx_usecs;
else if (efx_channel_is_xdp_tx(channel))
channel->irq_moderation_us = tx_usecs;
}
return 0;
}
void efx_siena_get_irq_moderation(struct efx_nic *efx, unsigned int *tx_usecs,
unsigned int *rx_usecs, bool *rx_adaptive)
{
*rx_adaptive = efx->irq_rx_adaptive;
*rx_usecs = efx->irq_rx_moderation_us;
/* If channels are shared between RX and TX, so is IRQ
* moderation. Otherwise, IRQ moderation is the same for all
* TX channels and is not adaptive.
*/
if (efx->tx_channel_offset == 0) {
*tx_usecs = *rx_usecs;
} else {
struct efx_channel *tx_channel;
tx_channel = efx->channel[efx->tx_channel_offset];
*tx_usecs = tx_channel->irq_moderation_us;
}
}
/**************************************************************************
*
* ioctls
*
*************************************************************************/
/* Net device ioctl
* Context: process, rtnl_lock() held.
*/
static int efx_ioctl(struct net_device *net_dev, struct ifreq *ifr, int cmd)
{
struct efx_nic *efx = netdev_priv(net_dev);
struct mii_ioctl_data *data = if_mii(ifr);
if (cmd == SIOCSHWTSTAMP)
return efx_siena_ptp_set_ts_config(efx, ifr);
if (cmd == SIOCGHWTSTAMP)
return efx_siena_ptp_get_ts_config(efx, ifr);
/* Convert phy_id from older PRTAD/DEVAD format */
if ((cmd == SIOCGMIIREG || cmd == SIOCSMIIREG) &&
(data->phy_id & 0xfc00) == 0x0400)
data->phy_id ^= MDIO_PHY_ID_C45 | 0x0400;
return mdio_mii_ioctl(&efx->mdio, data, cmd);
}
/**************************************************************************
*
* Kernel net device interface
*
*************************************************************************/
/* Context: process, rtnl_lock() held. */
static int efx_net_open(struct net_device *net_dev)
{
struct efx_nic *efx = netdev_priv(net_dev);
int rc;
netif_dbg(efx, ifup, efx->net_dev, "opening device on CPU %d\n",
raw_smp_processor_id());
rc = efx_check_disabled(efx);
if (rc)
return rc;
if (efx->phy_mode & PHY_MODE_SPECIAL)
return -EBUSY;
if (efx_siena_mcdi_poll_reboot(efx) && efx_siena_reset(efx, RESET_TYPE_ALL))
return -EIO;
/* Notify the kernel of the link state polled during driver load,
* before the monitor starts running */
efx_siena_link_status_changed(efx);
efx_siena_start_all(efx);
if (efx->state == STATE_DISABLED || efx->reset_pending)
netif_device_detach(efx->net_dev);
efx_siena_selftest_async_start(efx);
return 0;
}
/* Context: process, rtnl_lock() held.
* Note that the kernel will ignore our return code; this method
* should really be a void.
*/
static int efx_net_stop(struct net_device *net_dev)
{
struct efx_nic *efx = netdev_priv(net_dev);
netif_dbg(efx, ifdown, efx->net_dev, "closing on CPU %d\n",
raw_smp_processor_id());
/* Stop the device and flush all the channels */
efx_siena_stop_all(efx);
return 0;
}
static int efx_vlan_rx_add_vid(struct net_device *net_dev, __be16 proto, u16 vid)
{
struct efx_nic *efx = netdev_priv(net_dev);
if (efx->type->vlan_rx_add_vid)
return efx->type->vlan_rx_add_vid(efx, proto, vid);
else
return -EOPNOTSUPP;
}
static int efx_vlan_rx_kill_vid(struct net_device *net_dev, __be16 proto, u16 vid)
{
struct efx_nic *efx = netdev_priv(net_dev);
if (efx->type->vlan_rx_kill_vid)
return efx->type->vlan_rx_kill_vid(efx, proto, vid);
else
return -EOPNOTSUPP;
}
static const struct net_device_ops efx_netdev_ops = {
.ndo_open = efx_net_open,
.ndo_stop = efx_net_stop,
.ndo_get_stats64 = efx_siena_net_stats,
.ndo_tx_timeout = efx_siena_watchdog,
.ndo_start_xmit = efx_siena_hard_start_xmit,
.ndo_validate_addr = eth_validate_addr,
.ndo_eth_ioctl = efx_ioctl,
.ndo_change_mtu = efx_siena_change_mtu,
.ndo_set_mac_address = efx_siena_set_mac_address,
.ndo_set_rx_mode = efx_siena_set_rx_mode,
.ndo_set_features = efx_siena_set_features,
.ndo_features_check = efx_siena_features_check,
.ndo_vlan_rx_add_vid = efx_vlan_rx_add_vid,
.ndo_vlan_rx_kill_vid = efx_vlan_rx_kill_vid,
#ifdef CONFIG_SFC_SIENA_SRIOV
.ndo_set_vf_mac = efx_sriov_set_vf_mac,
.ndo_set_vf_vlan = efx_sriov_set_vf_vlan,
.ndo_set_vf_spoofchk = efx_sriov_set_vf_spoofchk,
.ndo_get_vf_config = efx_sriov_get_vf_config,
.ndo_set_vf_link_state = efx_sriov_set_vf_link_state,
#endif
.ndo_get_phys_port_id = efx_siena_get_phys_port_id,
.ndo_get_phys_port_name = efx_siena_get_phys_port_name,
.ndo_setup_tc = efx_siena_setup_tc,
#ifdef CONFIG_RFS_ACCEL
.ndo_rx_flow_steer = efx_siena_filter_rfs,
#endif
.ndo_xdp_xmit = efx_xdp_xmit,
.ndo_bpf = efx_xdp
};
static int efx_xdp_setup_prog(struct efx_nic *efx, struct bpf_prog *prog)
{
struct bpf_prog *old_prog;
if (efx->xdp_rxq_info_failed) {
netif_err(efx, drv, efx->net_dev,
"Unable to bind XDP program due to previous failure of rxq_info\n");
return -EINVAL;
}
if (prog && efx->net_dev->mtu > efx_siena_xdp_max_mtu(efx)) {
netif_err(efx, drv, efx->net_dev,
"Unable to configure XDP with MTU of %d (max: %d)\n",
efx->net_dev->mtu, efx_siena_xdp_max_mtu(efx));
return -EINVAL;
}
old_prog = rtnl_dereference(efx->xdp_prog);
rcu_assign_pointer(efx->xdp_prog, prog);
/* Release the reference that was originally passed by the caller. */
if (old_prog)
bpf_prog_put(old_prog);
return 0;
}
/* Context: process, rtnl_lock() held. */
static int efx_xdp(struct net_device *dev, struct netdev_bpf *xdp)
{
struct efx_nic *efx = netdev_priv(dev);
switch (xdp->command) {
case XDP_SETUP_PROG:
return efx_xdp_setup_prog(efx, xdp->prog);
default:
return -EINVAL;
}
}
static int efx_xdp_xmit(struct net_device *dev, int n, struct xdp_frame **xdpfs,
u32 flags)
{
struct efx_nic *efx = netdev_priv(dev);
if (!netif_running(dev))
return -EINVAL;
return efx_siena_xdp_tx_buffers(efx, n, xdpfs, flags & XDP_XMIT_FLUSH);
}
static void efx_update_name(struct efx_nic *efx)
{
strcpy(efx->name, efx->net_dev->name);
efx_siena_mtd_rename(efx);
efx_siena_set_channel_names(efx);
}
static int efx_netdev_event(struct notifier_block *this,
unsigned long event, void *ptr)
{
struct net_device *net_dev = netdev_notifier_info_to_dev(ptr);
if ((net_dev->netdev_ops == &efx_netdev_ops) &&
event == NETDEV_CHANGENAME)
efx_update_name(netdev_priv(net_dev));
return NOTIFY_DONE;
}
static struct notifier_block efx_netdev_notifier = {
.notifier_call = efx_netdev_event,
};
static ssize_t phy_type_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct efx_nic *efx = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", efx->phy_type);
}
static DEVICE_ATTR_RO(phy_type);
static int efx_register_netdev(struct efx_nic *efx)
{
struct net_device *net_dev = efx->net_dev;
struct efx_channel *channel;
int rc;
net_dev->watchdog_timeo = 5 * HZ;
net_dev->irq = efx->pci_dev->irq;
net_dev->netdev_ops = &efx_netdev_ops;
if (efx_nic_rev(efx) >= EFX_REV_HUNT_A0)
net_dev->priv_flags |= IFF_UNICAST_FLT;
net_dev->ethtool_ops = &efx_siena_ethtool_ops;
netif_set_tso_max_segs(net_dev, EFX_TSO_MAX_SEGS);
net_dev->min_mtu = EFX_MIN_MTU;
net_dev->max_mtu = EFX_MAX_MTU;
rtnl_lock();
/* Enable resets to be scheduled and check whether any were
* already requested. If so, the NIC is probably hosed so we
* abort.
*/
efx->state = STATE_READY;
smp_mb(); /* ensure we change state before checking reset_pending */
if (efx->reset_pending) {
pci_err(efx->pci_dev, "aborting probe due to scheduled reset\n");
rc = -EIO;
goto fail_locked;
}
rc = dev_alloc_name(net_dev, net_dev->name);
if (rc < 0)
goto fail_locked;
efx_update_name(efx);
/* Always start with carrier off; PHY events will detect the link */
netif_carrier_off(net_dev);
rc = register_netdevice(net_dev);
if (rc)
goto fail_locked;
efx_for_each_channel(channel, efx) {
struct efx_tx_queue *tx_queue;
efx_for_each_channel_tx_queue(tx_queue, channel)
efx_siena_init_tx_queue_core_txq(tx_queue);
}
efx_associate(efx);
rtnl_unlock();
rc = device_create_file(&efx->pci_dev->dev, &dev_attr_phy_type);
if (rc) {
netif_err(efx, drv, efx->net_dev,
"failed to init net dev attributes\n");
goto fail_registered;
}
efx_siena_init_mcdi_logging(efx);
return 0;
fail_registered:
rtnl_lock();
efx_dissociate(efx);
unregister_netdevice(net_dev);
fail_locked:
efx->state = STATE_UNINIT;
rtnl_unlock();
netif_err(efx, drv, efx->net_dev, "could not register net dev\n");
return rc;
}
static void efx_unregister_netdev(struct efx_nic *efx)
{
if (!efx->net_dev)
return;
BUG_ON(netdev_priv(efx->net_dev) != efx);
if (efx_dev_registered(efx)) {
strscpy(efx->name, pci_name(efx->pci_dev), sizeof(efx->name));
efx_siena_fini_mcdi_logging(efx);
device_remove_file(&efx->pci_dev->dev, &dev_attr_phy_type);
unregister_netdev(efx->net_dev);
}
}
/**************************************************************************
*
* List of NICs we support
*
**************************************************************************/
/* PCI device ID table */
static const struct pci_device_id efx_pci_table[] = {
{PCI_DEVICE(PCI_VENDOR_ID_SOLARFLARE, 0x0803), /* SFC9020 */
.driver_data = (unsigned long)&siena_a0_nic_type},
{PCI_DEVICE(PCI_VENDOR_ID_SOLARFLARE, 0x0813), /* SFL9021 */
.driver_data = (unsigned long)&siena_a0_nic_type},
{0} /* end of list */
};
/**************************************************************************
*
* Data housekeeping
*
**************************************************************************/
void efx_siena_update_sw_stats(struct efx_nic *efx, u64 *stats)
{
u64 n_rx_nodesc_trunc = 0;
struct efx_channel *channel;
efx_for_each_channel(channel, efx)
n_rx_nodesc_trunc += channel->n_rx_nodesc_trunc;
stats[GENERIC_STAT_rx_nodesc_trunc] = n_rx_nodesc_trunc;
stats[GENERIC_STAT_rx_noskb_drops] = atomic_read(&efx->n_rx_noskb_drops);
}
/**************************************************************************
*
* PCI interface
*
**************************************************************************/
/* Main body of final NIC shutdown code
* This is called only at module unload (or hotplug removal).
*/
static void efx_pci_remove_main(struct efx_nic *efx)
{
/* Flush reset_work. It can no longer be scheduled since we
* are not READY.
*/
BUG_ON(efx->state == STATE_READY);
efx_siena_flush_reset_workqueue(efx);
efx_siena_disable_interrupts(efx);
efx_siena_clear_interrupt_affinity(efx);
efx_siena_fini_interrupt(efx);
efx_fini_port(efx);
efx->type->fini(efx);
efx_siena_fini_napi(efx);
efx_remove_all(efx);
}
/* Final NIC shutdown
* This is called only at module unload (or hotplug removal). A PF can call
* this on its VFs to ensure they are unbound first.
*/
static void efx_pci_remove(struct pci_dev *pci_dev)
{
struct efx_nic *efx;
efx = pci_get_drvdata(pci_dev);
if (!efx)
return;
/* Mark the NIC as fini, then stop the interface */
rtnl_lock();
efx_dissociate(efx);
dev_close(efx->net_dev);
efx_siena_disable_interrupts(efx);
efx->state = STATE_UNINIT;
rtnl_unlock();
if (efx->type->sriov_fini)
efx->type->sriov_fini(efx);
efx_unregister_netdev(efx);
efx_siena_mtd_remove(efx);
efx_pci_remove_main(efx);
efx_siena_fini_io(efx);
netif_dbg(efx, drv, efx->net_dev, "shutdown successful\n");
efx_siena_fini_struct(efx);
free_netdev(efx->net_dev);
};
/* NIC VPD information
* Called during probe to display the part number of the
* installed NIC.
*/
static void efx_probe_vpd_strings(struct efx_nic *efx)
{
struct pci_dev *dev = efx->pci_dev;
unsigned int vpd_size, kw_len;
u8 *vpd_data;
int start;
vpd_data = pci_vpd_alloc(dev, &vpd_size);
if (IS_ERR(vpd_data)) {
pci_warn(dev, "Unable to read VPD\n");
return;
}
start = pci_vpd_find_ro_info_keyword(vpd_data, vpd_size,
PCI_VPD_RO_KEYWORD_PARTNO, &kw_len);
if (start < 0)
pci_err(dev, "Part number not found or incomplete\n");
else
pci_info(dev, "Part Number : %.*s\n", kw_len, vpd_data + start);
start = pci_vpd_find_ro_info_keyword(vpd_data, vpd_size,
PCI_VPD_RO_KEYWORD_SERIALNO, &kw_len);
if (start < 0)
pci_err(dev, "Serial number not found or incomplete\n");
else
efx->vpd_sn = kmemdup_nul(vpd_data + start, kw_len, GFP_KERNEL);
kfree(vpd_data);
}
/* Main body of NIC initialisation
* This is called at module load (or hotplug insertion, theoretically).
*/
static int efx_pci_probe_main(struct efx_nic *efx)
{
int rc;
/* Do start-of-day initialisation */
rc = efx_probe_all(efx);
if (rc)
goto fail1;
efx_siena_init_napi(efx);
down_write(&efx->filter_sem);
rc = efx->type->init(efx);
up_write(&efx->filter_sem);
if (rc) {
pci_err(efx->pci_dev, "failed to initialise NIC\n");
goto fail3;
}
rc = efx_init_port(efx);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"failed to initialise port\n");
goto fail4;
}
rc = efx_siena_init_interrupt(efx);
if (rc)
goto fail5;
efx_siena_set_interrupt_affinity(efx);
rc = efx_siena_enable_interrupts(efx);
if (rc)
goto fail6;
return 0;
fail6:
efx_siena_clear_interrupt_affinity(efx);
efx_siena_fini_interrupt(efx);
fail5:
efx_fini_port(efx);
fail4:
efx->type->fini(efx);
fail3:
efx_siena_fini_napi(efx);
efx_remove_all(efx);
fail1:
return rc;
}
static int efx_pci_probe_post_io(struct efx_nic *efx)
{
struct net_device *net_dev = efx->net_dev;
int rc = efx_pci_probe_main(efx);
if (rc)
return rc;
if (efx->type->sriov_init) {
rc = efx->type->sriov_init(efx);
if (rc)
pci_err(efx->pci_dev, "SR-IOV can't be enabled rc %d\n",
rc);
}
/* Determine netdevice features */
net_dev->features |= (efx->type->offload_features | NETIF_F_SG |
NETIF_F_TSO | NETIF_F_RXCSUM | NETIF_F_RXALL);
if (efx->type->offload_features & (NETIF_F_IPV6_CSUM | NETIF_F_HW_CSUM))
net_dev->features |= NETIF_F_TSO6;
/* Check whether device supports TSO */
if (!efx->type->tso_versions || !efx->type->tso_versions(efx))
net_dev->features &= ~NETIF_F_ALL_TSO;
/* Mask for features that also apply to VLAN devices */
net_dev->vlan_features |= (NETIF_F_HW_CSUM | NETIF_F_SG |
NETIF_F_HIGHDMA | NETIF_F_ALL_TSO |
NETIF_F_RXCSUM);
net_dev->hw_features |= net_dev->features & ~efx->fixed_features;
/* Disable receiving frames with bad FCS, by default. */
net_dev->features &= ~NETIF_F_RXALL;
/* Disable VLAN filtering by default. It may be enforced if
* the feature is fixed (i.e. VLAN filters are required to
* receive VLAN tagged packets due to vPort restrictions).
*/
net_dev->features &= ~NETIF_F_HW_VLAN_CTAG_FILTER;
net_dev->features |= efx->fixed_features;
net_dev->xdp_features = NETDEV_XDP_ACT_BASIC |
NETDEV_XDP_ACT_REDIRECT |
NETDEV_XDP_ACT_NDO_XMIT;
rc = efx_register_netdev(efx);
if (!rc)
return 0;
efx_pci_remove_main(efx);
return rc;
}
/* NIC initialisation
*
* This is called at module load (or hotplug insertion,
* theoretically). It sets up PCI mappings, resets the NIC,
* sets up and registers the network devices with the kernel and hooks
* the interrupt service routine. It does not prepare the device for
* transmission; this is left to the first time one of the network
* interfaces is brought up (i.e. efx_net_open).
*/
static int efx_pci_probe(struct pci_dev *pci_dev,
const struct pci_device_id *entry)
{
struct net_device *net_dev;
struct efx_nic *efx;
int rc;
/* Allocate and initialise a struct net_device and struct efx_nic */
net_dev = alloc_etherdev_mqs(sizeof(*efx), EFX_MAX_CORE_TX_QUEUES,
EFX_MAX_RX_QUEUES);
if (!net_dev)
return -ENOMEM;
efx = netdev_priv(net_dev);
efx->type = (const struct efx_nic_type *) entry->driver_data;
efx->fixed_features |= NETIF_F_HIGHDMA;
pci_set_drvdata(pci_dev, efx);
SET_NETDEV_DEV(net_dev, &pci_dev->dev);
rc = efx_siena_init_struct(efx, pci_dev, net_dev);
if (rc)
goto fail1;
pci_info(pci_dev, "Solarflare NIC detected\n");
if (!efx->type->is_vf)
efx_probe_vpd_strings(efx);
/* Set up basic I/O (BAR mappings etc) */
rc = efx_siena_init_io(efx, efx->type->mem_bar(efx),
efx->type->max_dma_mask,
efx->type->mem_map_size(efx));
if (rc)
goto fail2;
rc = efx_pci_probe_post_io(efx);
if (rc) {
/* On failure, retry once immediately.
* If we aborted probe due to a scheduled reset, dismiss it.
*/
efx->reset_pending = 0;
rc = efx_pci_probe_post_io(efx);
if (rc) {
/* On another failure, retry once more
* after a 50-305ms delay.
*/
unsigned char r;
get_random_bytes(&r, 1);
msleep((unsigned int)r + 50);
efx->reset_pending = 0;
rc = efx_pci_probe_post_io(efx);
}
}
if (rc)
goto fail3;
netif_dbg(efx, probe, efx->net_dev, "initialisation successful\n");
/* Try to create MTDs, but allow this to fail */
rtnl_lock();
rc = efx_mtd_probe(efx);
rtnl_unlock();
if (rc && rc != -EPERM)
netif_warn(efx, probe, efx->net_dev,
"failed to create MTDs (%d)\n", rc);
if (efx->type->udp_tnl_push_ports)
efx->type->udp_tnl_push_ports(efx);
return 0;
fail3:
efx_siena_fini_io(efx);
fail2:
efx_siena_fini_struct(efx);
fail1:
WARN_ON(rc > 0);
netif_dbg(efx, drv, efx->net_dev, "initialisation failed. rc=%d\n", rc);
free_netdev(net_dev);
return rc;
}
/* efx_pci_sriov_configure returns the actual number of Virtual Functions
* enabled on success
*/
#ifdef CONFIG_SFC_SIENA_SRIOV
static int efx_pci_sriov_configure(struct pci_dev *dev, int num_vfs)
{
int rc;
struct efx_nic *efx = pci_get_drvdata(dev);
if (efx->type->sriov_configure) {
rc = efx->type->sriov_configure(efx, num_vfs);
if (rc)
return rc;
else
return num_vfs;
} else
return -EOPNOTSUPP;
}
#endif
static int efx_pm_freeze(struct device *dev)
{
struct efx_nic *efx = dev_get_drvdata(dev);
rtnl_lock();
if (efx->state != STATE_DISABLED) {
efx->state = STATE_UNINIT;
efx_device_detach_sync(efx);
efx_siena_stop_all(efx);
efx_siena_disable_interrupts(efx);
}
rtnl_unlock();
return 0;
}
static void efx_pci_shutdown(struct pci_dev *pci_dev)
{
struct efx_nic *efx = pci_get_drvdata(pci_dev);
if (!efx)
return;
efx_pm_freeze(&pci_dev->dev);
pci_disable_device(pci_dev);
}
static int efx_pm_thaw(struct device *dev)
{
int rc;
struct efx_nic *efx = dev_get_drvdata(dev);
rtnl_lock();
if (efx->state != STATE_DISABLED) {
rc = efx_siena_enable_interrupts(efx);
if (rc)
goto fail;
mutex_lock(&efx->mac_lock);
efx_siena_mcdi_port_reconfigure(efx);
mutex_unlock(&efx->mac_lock);
efx_siena_start_all(efx);
efx_device_attach_if_not_resetting(efx);
efx->state = STATE_READY;
efx->type->resume_wol(efx);
}
rtnl_unlock();
/* Reschedule any quenched resets scheduled during efx_pm_freeze() */
efx_siena_queue_reset_work(efx);
return 0;
fail:
rtnl_unlock();
return rc;
}
static int efx_pm_poweroff(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct efx_nic *efx = pci_get_drvdata(pci_dev);
efx->type->fini(efx);
efx->reset_pending = 0;
pci_save_state(pci_dev);
return pci_set_power_state(pci_dev, PCI_D3hot);
}
/* Used for both resume and restore */
static int efx_pm_resume(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct efx_nic *efx = pci_get_drvdata(pci_dev);
int rc;
rc = pci_set_power_state(pci_dev, PCI_D0);
if (rc)
return rc;
pci_restore_state(pci_dev);
rc = pci_enable_device(pci_dev);
if (rc)
return rc;
pci_set_master(efx->pci_dev);
rc = efx->type->reset(efx, RESET_TYPE_ALL);
if (rc)
return rc;
down_write(&efx->filter_sem);
rc = efx->type->init(efx);
up_write(&efx->filter_sem);
if (rc)
return rc;
rc = efx_pm_thaw(dev);
return rc;
}
static int efx_pm_suspend(struct device *dev)
{
int rc;
efx_pm_freeze(dev);
rc = efx_pm_poweroff(dev);
if (rc)
efx_pm_resume(dev);
return rc;
}
static const struct dev_pm_ops efx_pm_ops = {
.suspend = efx_pm_suspend,
.resume = efx_pm_resume,
.freeze = efx_pm_freeze,
.thaw = efx_pm_thaw,
.poweroff = efx_pm_poweroff,
.restore = efx_pm_resume,
};
static struct pci_driver efx_pci_driver = {
.name = KBUILD_MODNAME,
.id_table = efx_pci_table,
.probe = efx_pci_probe,
.remove = efx_pci_remove,
.driver.pm = &efx_pm_ops,
.shutdown = efx_pci_shutdown,
.err_handler = &efx_siena_err_handlers,
#ifdef CONFIG_SFC_SIENA_SRIOV
.sriov_configure = efx_pci_sriov_configure,
#endif
};
/**************************************************************************
*
* Kernel module interface
*
*************************************************************************/
static int __init efx_init_module(void)
{
int rc;
pr_info("Solarflare Siena driver\n");
rc = register_netdevice_notifier(&efx_netdev_notifier);
if (rc)
goto err_notifier;
#ifdef CONFIG_SFC_SIENA_SRIOV
rc = efx_init_sriov();
if (rc)
goto err_sriov;
#endif
rc = efx_siena_create_reset_workqueue();
if (rc)
goto err_reset;
rc = pci_register_driver(&efx_pci_driver);
if (rc < 0)
goto err_pci;
return 0;
err_pci:
efx_siena_destroy_reset_workqueue();
err_reset:
#ifdef CONFIG_SFC_SIENA_SRIOV
efx_fini_sriov();
err_sriov:
#endif
unregister_netdevice_notifier(&efx_netdev_notifier);
err_notifier:
return rc;
}
static void __exit efx_exit_module(void)
{
pr_info("Solarflare Siena driver unloading\n");
pci_unregister_driver(&efx_pci_driver);
efx_siena_destroy_reset_workqueue();
#ifdef CONFIG_SFC_SIENA_SRIOV
efx_fini_sriov();
#endif
unregister_netdevice_notifier(&efx_netdev_notifier);
}
module_init(efx_init_module);
module_exit(efx_exit_module);
MODULE_AUTHOR("Solarflare Communications and "
"Michael Brown <[email protected]>");
MODULE_DESCRIPTION("Solarflare Siena network driver");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, efx_pci_table);
|
linux-master
|
drivers/net/ethernet/sfc/siena/efx.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2011-2013 Solarflare Communications Inc.
*/
#include <linux/bitops.h>
#include <linux/slab.h>
#include <linux/hwmon.h>
#include <linux/stat.h>
#include "net_driver.h"
#include "mcdi.h"
#include "mcdi_pcol.h"
#include "nic.h"
enum efx_hwmon_type {
EFX_HWMON_UNKNOWN,
EFX_HWMON_TEMP, /* temperature */
EFX_HWMON_COOL, /* cooling device, probably a heatsink */
EFX_HWMON_IN, /* voltage */
EFX_HWMON_CURR, /* current */
EFX_HWMON_POWER, /* power */
EFX_HWMON_TYPES_COUNT
};
static const char *const efx_hwmon_unit[EFX_HWMON_TYPES_COUNT] = {
[EFX_HWMON_TEMP] = " degC",
[EFX_HWMON_COOL] = " rpm", /* though nonsense for a heatsink */
[EFX_HWMON_IN] = " mV",
[EFX_HWMON_CURR] = " mA",
[EFX_HWMON_POWER] = " W",
};
static const struct {
const char *label;
enum efx_hwmon_type hwmon_type;
int port;
} efx_mcdi_sensor_type[] = {
#define SENSOR(name, label, hwmon_type, port) \
[MC_CMD_SENSOR_##name] = { label, EFX_HWMON_ ## hwmon_type, port }
SENSOR(CONTROLLER_TEMP, "Controller board temp.", TEMP, -1),
SENSOR(PHY_COMMON_TEMP, "PHY temp.", TEMP, -1),
SENSOR(CONTROLLER_COOLING, "Controller heat sink", COOL, -1),
SENSOR(PHY0_TEMP, "PHY temp.", TEMP, 0),
SENSOR(PHY0_COOLING, "PHY heat sink", COOL, 0),
SENSOR(PHY1_TEMP, "PHY temp.", TEMP, 1),
SENSOR(PHY1_COOLING, "PHY heat sink", COOL, 1),
SENSOR(IN_1V0, "1.0V supply", IN, -1),
SENSOR(IN_1V2, "1.2V supply", IN, -1),
SENSOR(IN_1V8, "1.8V supply", IN, -1),
SENSOR(IN_2V5, "2.5V supply", IN, -1),
SENSOR(IN_3V3, "3.3V supply", IN, -1),
SENSOR(IN_12V0, "12.0V supply", IN, -1),
SENSOR(IN_1V2A, "1.2V analogue supply", IN, -1),
SENSOR(IN_VREF, "Ref. voltage", IN, -1),
SENSOR(OUT_VAOE, "AOE FPGA supply", IN, -1),
SENSOR(AOE_TEMP, "AOE FPGA temp.", TEMP, -1),
SENSOR(PSU_AOE_TEMP, "AOE regulator temp.", TEMP, -1),
SENSOR(PSU_TEMP, "Controller regulator temp.",
TEMP, -1),
SENSOR(FAN_0, "Fan 0", COOL, -1),
SENSOR(FAN_1, "Fan 1", COOL, -1),
SENSOR(FAN_2, "Fan 2", COOL, -1),
SENSOR(FAN_3, "Fan 3", COOL, -1),
SENSOR(FAN_4, "Fan 4", COOL, -1),
SENSOR(IN_VAOE, "AOE input supply", IN, -1),
SENSOR(OUT_IAOE, "AOE output current", CURR, -1),
SENSOR(IN_IAOE, "AOE input current", CURR, -1),
SENSOR(NIC_POWER, "Board power use", POWER, -1),
SENSOR(IN_0V9, "0.9V supply", IN, -1),
SENSOR(IN_I0V9, "0.9V supply current", CURR, -1),
SENSOR(IN_I1V2, "1.2V supply current", CURR, -1),
SENSOR(IN_0V9_ADC, "0.9V supply (ext. ADC)", IN, -1),
SENSOR(CONTROLLER_2_TEMP, "Controller board temp. 2", TEMP, -1),
SENSOR(VREG_INTERNAL_TEMP, "Regulator die temp.", TEMP, -1),
SENSOR(VREG_0V9_TEMP, "0.9V regulator temp.", TEMP, -1),
SENSOR(VREG_1V2_TEMP, "1.2V regulator temp.", TEMP, -1),
SENSOR(CONTROLLER_VPTAT,
"Controller PTAT voltage (int. ADC)", IN, -1),
SENSOR(CONTROLLER_INTERNAL_TEMP,
"Controller die temp. (int. ADC)", TEMP, -1),
SENSOR(CONTROLLER_VPTAT_EXTADC,
"Controller PTAT voltage (ext. ADC)", IN, -1),
SENSOR(CONTROLLER_INTERNAL_TEMP_EXTADC,
"Controller die temp. (ext. ADC)", TEMP, -1),
SENSOR(AMBIENT_TEMP, "Ambient temp.", TEMP, -1),
SENSOR(AIRFLOW, "Air flow raw", IN, -1),
SENSOR(VDD08D_VSS08D_CSR, "0.9V die (int. ADC)", IN, -1),
SENSOR(VDD08D_VSS08D_CSR_EXTADC, "0.9V die (ext. ADC)", IN, -1),
SENSOR(HOTPOINT_TEMP, "Controller board temp. (hotpoint)", TEMP, -1),
#undef SENSOR
};
static const char *const sensor_status_names[] = {
[MC_CMD_SENSOR_STATE_OK] = "OK",
[MC_CMD_SENSOR_STATE_WARNING] = "Warning",
[MC_CMD_SENSOR_STATE_FATAL] = "Fatal",
[MC_CMD_SENSOR_STATE_BROKEN] = "Device failure",
[MC_CMD_SENSOR_STATE_NO_READING] = "No reading",
};
void efx_siena_mcdi_sensor_event(struct efx_nic *efx, efx_qword_t *ev)
{
unsigned int type, state, value;
enum efx_hwmon_type hwmon_type = EFX_HWMON_UNKNOWN;
const char *name = NULL, *state_txt, *unit;
type = EFX_QWORD_FIELD(*ev, MCDI_EVENT_SENSOREVT_MONITOR);
state = EFX_QWORD_FIELD(*ev, MCDI_EVENT_SENSOREVT_STATE);
value = EFX_QWORD_FIELD(*ev, MCDI_EVENT_SENSOREVT_VALUE);
/* Deal gracefully with the board having more drivers than we
* know about, but do not expect new sensor states. */
if (type < ARRAY_SIZE(efx_mcdi_sensor_type)) {
name = efx_mcdi_sensor_type[type].label;
hwmon_type = efx_mcdi_sensor_type[type].hwmon_type;
}
if (!name)
name = "No sensor name available";
EFX_WARN_ON_PARANOID(state >= ARRAY_SIZE(sensor_status_names));
state_txt = sensor_status_names[state];
EFX_WARN_ON_PARANOID(hwmon_type >= EFX_HWMON_TYPES_COUNT);
unit = efx_hwmon_unit[hwmon_type];
if (!unit)
unit = "";
netif_err(efx, hw, efx->net_dev,
"Sensor %d (%s) reports condition '%s' for value %d%s\n",
type, name, state_txt, value, unit);
}
#ifdef CONFIG_SFC_SIENA_MCDI_MON
struct efx_mcdi_mon_attribute {
struct device_attribute dev_attr;
unsigned int index;
unsigned int type;
enum efx_hwmon_type hwmon_type;
unsigned int limit_value;
char name[12];
};
static int efx_mcdi_mon_update(struct efx_nic *efx)
{
struct efx_mcdi_mon *hwmon = efx_mcdi_mon(efx);
MCDI_DECLARE_BUF(inbuf, MC_CMD_READ_SENSORS_EXT_IN_LEN);
int rc;
MCDI_SET_QWORD(inbuf, READ_SENSORS_EXT_IN_DMA_ADDR,
hwmon->dma_buf.dma_addr);
MCDI_SET_DWORD(inbuf, READ_SENSORS_EXT_IN_LENGTH, hwmon->dma_buf.len);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_READ_SENSORS,
inbuf, sizeof(inbuf), NULL, 0, NULL);
if (rc == 0)
hwmon->last_update = jiffies;
return rc;
}
static int efx_mcdi_mon_get_entry(struct device *dev, unsigned int index,
efx_dword_t *entry)
{
struct efx_nic *efx = dev_get_drvdata(dev->parent);
struct efx_mcdi_mon *hwmon = efx_mcdi_mon(efx);
int rc;
BUILD_BUG_ON(MC_CMD_READ_SENSORS_OUT_LEN != 0);
mutex_lock(&hwmon->update_lock);
/* Use cached value if last update was < 1 s ago */
if (time_before(jiffies, hwmon->last_update + HZ))
rc = 0;
else
rc = efx_mcdi_mon_update(efx);
/* Copy out the requested entry */
*entry = ((efx_dword_t *)hwmon->dma_buf.addr)[index];
mutex_unlock(&hwmon->update_lock);
return rc;
}
static ssize_t efx_mcdi_mon_show_value(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct efx_mcdi_mon_attribute *mon_attr =
container_of(attr, struct efx_mcdi_mon_attribute, dev_attr);
efx_dword_t entry;
unsigned int value, state;
int rc;
rc = efx_mcdi_mon_get_entry(dev, mon_attr->index, &entry);
if (rc)
return rc;
state = EFX_DWORD_FIELD(entry, MC_CMD_SENSOR_VALUE_ENTRY_TYPEDEF_STATE);
if (state == MC_CMD_SENSOR_STATE_NO_READING)
return -EBUSY;
value = EFX_DWORD_FIELD(entry, MC_CMD_SENSOR_VALUE_ENTRY_TYPEDEF_VALUE);
switch (mon_attr->hwmon_type) {
case EFX_HWMON_TEMP:
/* Convert temperature from degrees to milli-degrees Celsius */
value *= 1000;
break;
case EFX_HWMON_POWER:
/* Convert power from watts to microwatts */
value *= 1000000;
break;
default:
/* No conversion needed */
break;
}
return sprintf(buf, "%u\n", value);
}
static ssize_t efx_mcdi_mon_show_limit(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct efx_mcdi_mon_attribute *mon_attr =
container_of(attr, struct efx_mcdi_mon_attribute, dev_attr);
unsigned int value;
value = mon_attr->limit_value;
switch (mon_attr->hwmon_type) {
case EFX_HWMON_TEMP:
/* Convert temperature from degrees to milli-degrees Celsius */
value *= 1000;
break;
case EFX_HWMON_POWER:
/* Convert power from watts to microwatts */
value *= 1000000;
break;
default:
/* No conversion needed */
break;
}
return sprintf(buf, "%u\n", value);
}
static ssize_t efx_mcdi_mon_show_alarm(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct efx_mcdi_mon_attribute *mon_attr =
container_of(attr, struct efx_mcdi_mon_attribute, dev_attr);
efx_dword_t entry;
int state;
int rc;
rc = efx_mcdi_mon_get_entry(dev, mon_attr->index, &entry);
if (rc)
return rc;
state = EFX_DWORD_FIELD(entry, MC_CMD_SENSOR_VALUE_ENTRY_TYPEDEF_STATE);
return sprintf(buf, "%d\n", state != MC_CMD_SENSOR_STATE_OK);
}
static ssize_t efx_mcdi_mon_show_label(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct efx_mcdi_mon_attribute *mon_attr =
container_of(attr, struct efx_mcdi_mon_attribute, dev_attr);
return sprintf(buf, "%s\n",
efx_mcdi_sensor_type[mon_attr->type].label);
}
static void
efx_mcdi_mon_add_attr(struct efx_nic *efx, const char *name,
ssize_t (*reader)(struct device *,
struct device_attribute *, char *),
unsigned int index, unsigned int type,
unsigned int limit_value)
{
struct efx_mcdi_mon *hwmon = efx_mcdi_mon(efx);
struct efx_mcdi_mon_attribute *attr = &hwmon->attrs[hwmon->n_attrs];
strscpy(attr->name, name, sizeof(attr->name));
attr->index = index;
attr->type = type;
if (type < ARRAY_SIZE(efx_mcdi_sensor_type))
attr->hwmon_type = efx_mcdi_sensor_type[type].hwmon_type;
else
attr->hwmon_type = EFX_HWMON_UNKNOWN;
attr->limit_value = limit_value;
sysfs_attr_init(&attr->dev_attr.attr);
attr->dev_attr.attr.name = attr->name;
attr->dev_attr.attr.mode = 0444;
attr->dev_attr.show = reader;
hwmon->group.attrs[hwmon->n_attrs++] = &attr->dev_attr.attr;
}
int efx_siena_mcdi_mon_probe(struct efx_nic *efx)
{
unsigned int n_temp = 0, n_cool = 0, n_in = 0, n_curr = 0, n_power = 0;
struct efx_mcdi_mon *hwmon = efx_mcdi_mon(efx);
MCDI_DECLARE_BUF(inbuf, MC_CMD_SENSOR_INFO_EXT_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_SENSOR_INFO_OUT_LENMAX);
unsigned int n_pages, n_sensors, n_attrs, page;
size_t outlen;
char name[12];
u32 mask;
int rc, i, j, type;
/* Find out how many sensors are present */
n_sensors = 0;
page = 0;
do {
MCDI_SET_DWORD(inbuf, SENSOR_INFO_EXT_IN_PAGE, page);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_SENSOR_INFO, inbuf,
sizeof(inbuf), outbuf, sizeof(outbuf),
&outlen);
if (rc)
return rc;
if (outlen < MC_CMD_SENSOR_INFO_OUT_LENMIN)
return -EIO;
mask = MCDI_DWORD(outbuf, SENSOR_INFO_OUT_MASK);
n_sensors += hweight32(mask & ~(1 << MC_CMD_SENSOR_PAGE0_NEXT));
++page;
} while (mask & (1 << MC_CMD_SENSOR_PAGE0_NEXT));
n_pages = page;
/* Don't create a device if there are none */
if (n_sensors == 0)
return 0;
rc = efx_siena_alloc_buffer(efx, &hwmon->dma_buf,
n_sensors * MC_CMD_SENSOR_VALUE_ENTRY_TYPEDEF_LEN,
GFP_KERNEL);
if (rc)
return rc;
mutex_init(&hwmon->update_lock);
efx_mcdi_mon_update(efx);
/* Allocate space for the maximum possible number of
* attributes for this set of sensors:
* value, min, max, crit, alarm and label for each sensor.
*/
n_attrs = 6 * n_sensors;
hwmon->attrs = kcalloc(n_attrs, sizeof(*hwmon->attrs), GFP_KERNEL);
if (!hwmon->attrs) {
rc = -ENOMEM;
goto fail;
}
hwmon->group.attrs = kcalloc(n_attrs + 1, sizeof(struct attribute *),
GFP_KERNEL);
if (!hwmon->group.attrs) {
rc = -ENOMEM;
goto fail;
}
for (i = 0, j = -1, type = -1; ; i++) {
enum efx_hwmon_type hwmon_type;
const char *hwmon_prefix;
unsigned hwmon_index;
u16 min1, max1, min2, max2;
/* Find next sensor type or exit if there is none */
do {
type++;
if ((type % 32) == 0) {
page = type / 32;
j = -1;
if (page == n_pages)
goto hwmon_register;
MCDI_SET_DWORD(inbuf, SENSOR_INFO_EXT_IN_PAGE,
page);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_SENSOR_INFO,
inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf),
&outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_SENSOR_INFO_OUT_LENMIN) {
rc = -EIO;
goto fail;
}
mask = (MCDI_DWORD(outbuf,
SENSOR_INFO_OUT_MASK) &
~(1 << MC_CMD_SENSOR_PAGE0_NEXT));
/* Check again for short response */
if (outlen <
MC_CMD_SENSOR_INFO_OUT_LEN(hweight32(mask))) {
rc = -EIO;
goto fail;
}
}
} while (!(mask & (1 << type % 32)));
j++;
if (type < ARRAY_SIZE(efx_mcdi_sensor_type)) {
hwmon_type = efx_mcdi_sensor_type[type].hwmon_type;
/* Skip sensors specific to a different port */
if (hwmon_type != EFX_HWMON_UNKNOWN &&
efx_mcdi_sensor_type[type].port >= 0 &&
efx_mcdi_sensor_type[type].port !=
efx_port_num(efx))
continue;
} else {
hwmon_type = EFX_HWMON_UNKNOWN;
}
switch (hwmon_type) {
case EFX_HWMON_TEMP:
hwmon_prefix = "temp";
hwmon_index = ++n_temp; /* 1-based */
break;
case EFX_HWMON_COOL:
/* This is likely to be a heatsink, but there
* is no convention for representing cooling
* devices other than fans.
*/
hwmon_prefix = "fan";
hwmon_index = ++n_cool; /* 1-based */
break;
default:
hwmon_prefix = "in";
hwmon_index = n_in++; /* 0-based */
break;
case EFX_HWMON_CURR:
hwmon_prefix = "curr";
hwmon_index = ++n_curr; /* 1-based */
break;
case EFX_HWMON_POWER:
hwmon_prefix = "power";
hwmon_index = ++n_power; /* 1-based */
break;
}
min1 = MCDI_ARRAY_FIELD(outbuf, SENSOR_ENTRY,
SENSOR_INFO_ENTRY, j, MIN1);
max1 = MCDI_ARRAY_FIELD(outbuf, SENSOR_ENTRY,
SENSOR_INFO_ENTRY, j, MAX1);
min2 = MCDI_ARRAY_FIELD(outbuf, SENSOR_ENTRY,
SENSOR_INFO_ENTRY, j, MIN2);
max2 = MCDI_ARRAY_FIELD(outbuf, SENSOR_ENTRY,
SENSOR_INFO_ENTRY, j, MAX2);
if (min1 != max1) {
snprintf(name, sizeof(name), "%s%u_input",
hwmon_prefix, hwmon_index);
efx_mcdi_mon_add_attr(
efx, name, efx_mcdi_mon_show_value, i, type, 0);
if (hwmon_type != EFX_HWMON_POWER) {
snprintf(name, sizeof(name), "%s%u_min",
hwmon_prefix, hwmon_index);
efx_mcdi_mon_add_attr(
efx, name, efx_mcdi_mon_show_limit,
i, type, min1);
}
snprintf(name, sizeof(name), "%s%u_max",
hwmon_prefix, hwmon_index);
efx_mcdi_mon_add_attr(
efx, name, efx_mcdi_mon_show_limit,
i, type, max1);
if (min2 != max2) {
/* Assume max2 is critical value.
* But we have no good way to expose min2.
*/
snprintf(name, sizeof(name), "%s%u_crit",
hwmon_prefix, hwmon_index);
efx_mcdi_mon_add_attr(
efx, name, efx_mcdi_mon_show_limit,
i, type, max2);
}
}
snprintf(name, sizeof(name), "%s%u_alarm",
hwmon_prefix, hwmon_index);
efx_mcdi_mon_add_attr(
efx, name, efx_mcdi_mon_show_alarm, i, type, 0);
if (type < ARRAY_SIZE(efx_mcdi_sensor_type) &&
efx_mcdi_sensor_type[type].label) {
snprintf(name, sizeof(name), "%s%u_label",
hwmon_prefix, hwmon_index);
efx_mcdi_mon_add_attr(
efx, name, efx_mcdi_mon_show_label, i, type, 0);
}
}
hwmon_register:
hwmon->groups[0] = &hwmon->group;
hwmon->device = hwmon_device_register_with_groups(&efx->pci_dev->dev,
KBUILD_MODNAME, NULL,
hwmon->groups);
if (IS_ERR(hwmon->device)) {
rc = PTR_ERR(hwmon->device);
goto fail;
}
return 0;
fail:
efx_siena_mcdi_mon_remove(efx);
return rc;
}
void efx_siena_mcdi_mon_remove(struct efx_nic *efx)
{
struct efx_mcdi_mon *hwmon = efx_mcdi_mon(efx);
if (hwmon->device)
hwmon_device_unregister(hwmon->device);
kfree(hwmon->attrs);
kfree(hwmon->group.attrs);
efx_siena_free_buffer(efx, &hwmon->dma_buf);
}
#endif /* CONFIG_SFC_SIENA_MCDI_MON */
|
linux-master
|
drivers/net/ethernet/sfc/siena/mcdi_mon.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2005-2006 Fen Systems Ltd.
* Copyright 2005-2013 Solarflare Communications Inc.
*/
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/slab.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include <linux/prefetch.h>
#include <linux/moduleparam.h>
#include <linux/iommu.h>
#include <net/ip.h>
#include <net/checksum.h>
#include <net/xdp.h>
#include <linux/bpf_trace.h>
#include "net_driver.h"
#include "efx.h"
#include "rx_common.h"
#include "filter.h"
#include "nic.h"
#include "selftest.h"
#include "workarounds.h"
/* Preferred number of descriptors to fill at once */
#define EFX_RX_PREFERRED_BATCH 8U
/* Maximum rx prefix used by any architecture. */
#define EFX_MAX_RX_PREFIX_SIZE 16
/* Size of buffer allocated for skb header area. */
#define EFX_SKB_HEADERS 128u
/* Each packet can consume up to ceil(max_frame_len / buffer_size) buffers */
#define EFX_RX_MAX_FRAGS DIV_ROUND_UP(EFX_MAX_FRAME_LEN(EFX_MAX_MTU), \
EFX_RX_USR_BUF_SIZE)
static void efx_rx_packet__check_len(struct efx_rx_queue *rx_queue,
struct efx_rx_buffer *rx_buf,
int len)
{
struct efx_nic *efx = rx_queue->efx;
unsigned max_len = rx_buf->len - efx->type->rx_buffer_padding;
if (likely(len <= max_len))
return;
/* The packet must be discarded, but this is only a fatal error
* if the caller indicated it was
*/
rx_buf->flags |= EFX_RX_PKT_DISCARD;
if (net_ratelimit())
netif_err(efx, rx_err, efx->net_dev,
"RX queue %d overlength RX event (%#x > %#x)\n",
efx_rx_queue_index(rx_queue), len, max_len);
efx_rx_queue_channel(rx_queue)->n_rx_overlength++;
}
/* Allocate and construct an SKB around page fragments */
static struct sk_buff *efx_rx_mk_skb(struct efx_channel *channel,
struct efx_rx_buffer *rx_buf,
unsigned int n_frags,
u8 *eh, int hdr_len)
{
struct efx_nic *efx = channel->efx;
struct sk_buff *skb;
/* Allocate an SKB to store the headers */
skb = netdev_alloc_skb(efx->net_dev,
efx->rx_ip_align + efx->rx_prefix_size +
hdr_len);
if (unlikely(skb == NULL)) {
atomic_inc(&efx->n_rx_noskb_drops);
return NULL;
}
EFX_WARN_ON_ONCE_PARANOID(rx_buf->len < hdr_len);
memcpy(skb->data + efx->rx_ip_align, eh - efx->rx_prefix_size,
efx->rx_prefix_size + hdr_len);
skb_reserve(skb, efx->rx_ip_align + efx->rx_prefix_size);
__skb_put(skb, hdr_len);
/* Append the remaining page(s) onto the frag list */
if (rx_buf->len > hdr_len) {
rx_buf->page_offset += hdr_len;
rx_buf->len -= hdr_len;
for (;;) {
skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags,
rx_buf->page, rx_buf->page_offset,
rx_buf->len, efx->rx_buffer_truesize);
rx_buf->page = NULL;
if (skb_shinfo(skb)->nr_frags == n_frags)
break;
rx_buf = efx_rx_buf_next(&channel->rx_queue, rx_buf);
}
} else {
__free_pages(rx_buf->page, efx->rx_buffer_order);
rx_buf->page = NULL;
n_frags = 0;
}
/* Move past the ethernet header */
skb->protocol = eth_type_trans(skb, efx->net_dev);
skb_mark_napi_id(skb, &channel->napi_str);
return skb;
}
void efx_siena_rx_packet(struct efx_rx_queue *rx_queue, unsigned int index,
unsigned int n_frags, unsigned int len, u16 flags)
{
struct efx_nic *efx = rx_queue->efx;
struct efx_channel *channel = efx_rx_queue_channel(rx_queue);
struct efx_rx_buffer *rx_buf;
rx_queue->rx_packets++;
rx_buf = efx_rx_buffer(rx_queue, index);
rx_buf->flags |= flags;
/* Validate the number of fragments and completed length */
if (n_frags == 1) {
if (!(flags & EFX_RX_PKT_PREFIX_LEN))
efx_rx_packet__check_len(rx_queue, rx_buf, len);
} else if (unlikely(n_frags > EFX_RX_MAX_FRAGS) ||
unlikely(len <= (n_frags - 1) * efx->rx_dma_len) ||
unlikely(len > n_frags * efx->rx_dma_len) ||
unlikely(!efx->rx_scatter)) {
/* If this isn't an explicit discard request, either
* the hardware or the driver is broken.
*/
WARN_ON(!(len == 0 && rx_buf->flags & EFX_RX_PKT_DISCARD));
rx_buf->flags |= EFX_RX_PKT_DISCARD;
}
netif_vdbg(efx, rx_status, efx->net_dev,
"RX queue %d received ids %x-%x len %d %s%s\n",
efx_rx_queue_index(rx_queue), index,
(index + n_frags - 1) & rx_queue->ptr_mask, len,
(rx_buf->flags & EFX_RX_PKT_CSUMMED) ? " [SUMMED]" : "",
(rx_buf->flags & EFX_RX_PKT_DISCARD) ? " [DISCARD]" : "");
/* Discard packet, if instructed to do so. Process the
* previous receive first.
*/
if (unlikely(rx_buf->flags & EFX_RX_PKT_DISCARD)) {
efx_rx_flush_packet(channel);
efx_siena_discard_rx_packet(channel, rx_buf, n_frags);
return;
}
if (n_frags == 1 && !(flags & EFX_RX_PKT_PREFIX_LEN))
rx_buf->len = len;
/* Release and/or sync the DMA mapping - assumes all RX buffers
* consumed in-order per RX queue.
*/
efx_sync_rx_buffer(efx, rx_buf, rx_buf->len);
/* Prefetch nice and early so data will (hopefully) be in cache by
* the time we look at it.
*/
prefetch(efx_rx_buf_va(rx_buf));
rx_buf->page_offset += efx->rx_prefix_size;
rx_buf->len -= efx->rx_prefix_size;
if (n_frags > 1) {
/* Release/sync DMA mapping for additional fragments.
* Fix length for last fragment.
*/
unsigned int tail_frags = n_frags - 1;
for (;;) {
rx_buf = efx_rx_buf_next(rx_queue, rx_buf);
if (--tail_frags == 0)
break;
efx_sync_rx_buffer(efx, rx_buf, efx->rx_dma_len);
}
rx_buf->len = len - (n_frags - 1) * efx->rx_dma_len;
efx_sync_rx_buffer(efx, rx_buf, rx_buf->len);
}
/* All fragments have been DMA-synced, so recycle pages. */
rx_buf = efx_rx_buffer(rx_queue, index);
efx_siena_recycle_rx_pages(channel, rx_buf, n_frags);
/* Pipeline receives so that we give time for packet headers to be
* prefetched into cache.
*/
efx_rx_flush_packet(channel);
channel->rx_pkt_n_frags = n_frags;
channel->rx_pkt_index = index;
}
static void efx_rx_deliver(struct efx_channel *channel, u8 *eh,
struct efx_rx_buffer *rx_buf,
unsigned int n_frags)
{
struct sk_buff *skb;
u16 hdr_len = min_t(u16, rx_buf->len, EFX_SKB_HEADERS);
skb = efx_rx_mk_skb(channel, rx_buf, n_frags, eh, hdr_len);
if (unlikely(skb == NULL)) {
struct efx_rx_queue *rx_queue;
rx_queue = efx_channel_get_rx_queue(channel);
efx_siena_free_rx_buffers(rx_queue, rx_buf, n_frags);
return;
}
skb_record_rx_queue(skb, channel->rx_queue.core_index);
/* Set the SKB flags */
skb_checksum_none_assert(skb);
if (likely(rx_buf->flags & EFX_RX_PKT_CSUMMED)) {
skb->ip_summed = CHECKSUM_UNNECESSARY;
skb->csum_level = !!(rx_buf->flags & EFX_RX_PKT_CSUM_LEVEL);
}
efx_rx_skb_attach_timestamp(channel, skb);
if (channel->type->receive_skb)
if (channel->type->receive_skb(channel, skb))
return;
/* Pass the packet up */
if (channel->rx_list != NULL)
/* Add to list, will pass up later */
list_add_tail(&skb->list, channel->rx_list);
else
/* No list, so pass it up now */
netif_receive_skb(skb);
}
/** efx_do_xdp: perform XDP processing on a received packet
*
* Returns true if packet should still be delivered.
*/
static bool efx_do_xdp(struct efx_nic *efx, struct efx_channel *channel,
struct efx_rx_buffer *rx_buf, u8 **ehp)
{
u8 rx_prefix[EFX_MAX_RX_PREFIX_SIZE];
struct efx_rx_queue *rx_queue;
struct bpf_prog *xdp_prog;
struct xdp_frame *xdpf;
struct xdp_buff xdp;
u32 xdp_act;
s16 offset;
int err;
xdp_prog = rcu_dereference_bh(efx->xdp_prog);
if (!xdp_prog)
return true;
rx_queue = efx_channel_get_rx_queue(channel);
if (unlikely(channel->rx_pkt_n_frags > 1)) {
/* We can't do XDP on fragmented packets - drop. */
efx_siena_free_rx_buffers(rx_queue, rx_buf,
channel->rx_pkt_n_frags);
if (net_ratelimit())
netif_err(efx, rx_err, efx->net_dev,
"XDP is not possible with multiple receive fragments (%d)\n",
channel->rx_pkt_n_frags);
channel->n_rx_xdp_bad_drops++;
return false;
}
dma_sync_single_for_cpu(&efx->pci_dev->dev, rx_buf->dma_addr,
rx_buf->len, DMA_FROM_DEVICE);
/* Save the rx prefix. */
EFX_WARN_ON_PARANOID(efx->rx_prefix_size > EFX_MAX_RX_PREFIX_SIZE);
memcpy(rx_prefix, *ehp - efx->rx_prefix_size,
efx->rx_prefix_size);
xdp_init_buff(&xdp, efx->rx_page_buf_step, &rx_queue->xdp_rxq_info);
/* No support yet for XDP metadata */
xdp_prepare_buff(&xdp, *ehp - EFX_XDP_HEADROOM, EFX_XDP_HEADROOM,
rx_buf->len, false);
xdp_act = bpf_prog_run_xdp(xdp_prog, &xdp);
offset = (u8 *)xdp.data - *ehp;
switch (xdp_act) {
case XDP_PASS:
/* Fix up rx prefix. */
if (offset) {
*ehp += offset;
rx_buf->page_offset += offset;
rx_buf->len -= offset;
memcpy(*ehp - efx->rx_prefix_size, rx_prefix,
efx->rx_prefix_size);
}
break;
case XDP_TX:
/* Buffer ownership passes to tx on success. */
xdpf = xdp_convert_buff_to_frame(&xdp);
err = efx_siena_xdp_tx_buffers(efx, 1, &xdpf, true);
if (unlikely(err != 1)) {
efx_siena_free_rx_buffers(rx_queue, rx_buf, 1);
if (net_ratelimit())
netif_err(efx, rx_err, efx->net_dev,
"XDP TX failed (%d)\n", err);
channel->n_rx_xdp_bad_drops++;
trace_xdp_exception(efx->net_dev, xdp_prog, xdp_act);
} else {
channel->n_rx_xdp_tx++;
}
break;
case XDP_REDIRECT:
err = xdp_do_redirect(efx->net_dev, &xdp, xdp_prog);
if (unlikely(err)) {
efx_siena_free_rx_buffers(rx_queue, rx_buf, 1);
if (net_ratelimit())
netif_err(efx, rx_err, efx->net_dev,
"XDP redirect failed (%d)\n", err);
channel->n_rx_xdp_bad_drops++;
trace_xdp_exception(efx->net_dev, xdp_prog, xdp_act);
} else {
channel->n_rx_xdp_redirect++;
}
break;
default:
bpf_warn_invalid_xdp_action(efx->net_dev, xdp_prog, xdp_act);
efx_siena_free_rx_buffers(rx_queue, rx_buf, 1);
channel->n_rx_xdp_bad_drops++;
trace_xdp_exception(efx->net_dev, xdp_prog, xdp_act);
break;
case XDP_ABORTED:
trace_xdp_exception(efx->net_dev, xdp_prog, xdp_act);
fallthrough;
case XDP_DROP:
efx_siena_free_rx_buffers(rx_queue, rx_buf, 1);
channel->n_rx_xdp_drops++;
break;
}
return xdp_act == XDP_PASS;
}
/* Handle a received packet. Second half: Touches packet payload. */
void __efx_siena_rx_packet(struct efx_channel *channel)
{
struct efx_nic *efx = channel->efx;
struct efx_rx_buffer *rx_buf =
efx_rx_buffer(&channel->rx_queue, channel->rx_pkt_index);
u8 *eh = efx_rx_buf_va(rx_buf);
/* Read length from the prefix if necessary. This already
* excludes the length of the prefix itself.
*/
if (rx_buf->flags & EFX_RX_PKT_PREFIX_LEN)
rx_buf->len = le16_to_cpup((__le16 *)
(eh + efx->rx_packet_len_offset));
/* If we're in loopback test, then pass the packet directly to the
* loopback layer, and free the rx_buf here
*/
if (unlikely(efx->loopback_selftest)) {
struct efx_rx_queue *rx_queue;
efx_siena_loopback_rx_packet(efx, eh, rx_buf->len);
rx_queue = efx_channel_get_rx_queue(channel);
efx_siena_free_rx_buffers(rx_queue, rx_buf,
channel->rx_pkt_n_frags);
goto out;
}
if (!efx_do_xdp(efx, channel, rx_buf, &eh))
goto out;
if (unlikely(!(efx->net_dev->features & NETIF_F_RXCSUM)))
rx_buf->flags &= ~EFX_RX_PKT_CSUMMED;
if ((rx_buf->flags & EFX_RX_PKT_TCP) && !channel->type->receive_skb)
efx_siena_rx_packet_gro(channel, rx_buf,
channel->rx_pkt_n_frags, eh, 0);
else
efx_rx_deliver(channel, eh, rx_buf, channel->rx_pkt_n_frags);
out:
channel->rx_pkt_n_frags = 0;
}
|
linux-master
|
drivers/net/ethernet/sfc/siena/rx.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2005-2006 Fen Systems Ltd.
* Copyright 2006-2013 Solarflare Communications Inc.
*/
#include <linux/bitops.h>
#include <linux/delay.h>
#include <linux/pci.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/random.h>
#include "net_driver.h"
#include "bitfield.h"
#include "efx.h"
#include "efx_common.h"
#include "nic.h"
#include "farch_regs.h"
#include "io.h"
#include "workarounds.h"
#include "mcdi.h"
#include "mcdi_pcol.h"
#include "mcdi_port.h"
#include "mcdi_port_common.h"
#include "selftest.h"
#include "siena_sriov.h"
#include "rx_common.h"
/* Hardware control for SFC9000 family including SFL9021 (aka Siena). */
static void siena_init_wol(struct efx_nic *efx);
static void siena_push_irq_moderation(struct efx_channel *channel)
{
struct efx_nic *efx = channel->efx;
efx_dword_t timer_cmd;
if (channel->irq_moderation_us) {
unsigned int ticks;
ticks = efx_siena_usecs_to_ticks(efx, channel->irq_moderation_us);
EFX_POPULATE_DWORD_2(timer_cmd,
FRF_CZ_TC_TIMER_MODE,
FFE_CZ_TIMER_MODE_INT_HLDOFF,
FRF_CZ_TC_TIMER_VAL,
ticks - 1);
} else {
EFX_POPULATE_DWORD_2(timer_cmd,
FRF_CZ_TC_TIMER_MODE,
FFE_CZ_TIMER_MODE_DIS,
FRF_CZ_TC_TIMER_VAL, 0);
}
efx_writed_page_locked(channel->efx, &timer_cmd, FR_BZ_TIMER_COMMAND_P0,
channel->channel);
}
void efx_siena_prepare_flush(struct efx_nic *efx)
{
if (efx->fc_disable++ == 0)
efx_siena_mcdi_set_mac(efx);
}
void siena_finish_flush(struct efx_nic *efx)
{
if (--efx->fc_disable == 0)
efx_siena_mcdi_set_mac(efx);
}
static const struct efx_farch_register_test siena_register_tests[] = {
{ FR_AZ_ADR_REGION,
EFX_OWORD32(0x0003FFFF, 0x0003FFFF, 0x0003FFFF, 0x0003FFFF) },
{ FR_CZ_USR_EV_CFG,
EFX_OWORD32(0x000103FF, 0x00000000, 0x00000000, 0x00000000) },
{ FR_AZ_RX_CFG,
EFX_OWORD32(0xFFFFFFFE, 0xFFFFFFFF, 0x0003FFFF, 0x00000000) },
{ FR_AZ_TX_CFG,
EFX_OWORD32(0x7FFF0037, 0xFFFF8000, 0xFFFFFFFF, 0x03FFFFFF) },
{ FR_AZ_TX_RESERVED,
EFX_OWORD32(0xFFFEFE80, 0x1FFFFFFF, 0x020000FE, 0x007FFFFF) },
{ FR_AZ_SRM_TX_DC_CFG,
EFX_OWORD32(0x001FFFFF, 0x00000000, 0x00000000, 0x00000000) },
{ FR_AZ_RX_DC_CFG,
EFX_OWORD32(0x00000003, 0x00000000, 0x00000000, 0x00000000) },
{ FR_AZ_RX_DC_PF_WM,
EFX_OWORD32(0x000003FF, 0x00000000, 0x00000000, 0x00000000) },
{ FR_BZ_DP_CTRL,
EFX_OWORD32(0x00000FFF, 0x00000000, 0x00000000, 0x00000000) },
{ FR_BZ_RX_RSS_TKEY,
EFX_OWORD32(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF) },
{ FR_CZ_RX_RSS_IPV6_REG1,
EFX_OWORD32(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF) },
{ FR_CZ_RX_RSS_IPV6_REG2,
EFX_OWORD32(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF) },
{ FR_CZ_RX_RSS_IPV6_REG3,
EFX_OWORD32(0xFFFFFFFF, 0xFFFFFFFF, 0x00000007, 0x00000000) },
};
static int siena_test_chip(struct efx_nic *efx, struct efx_self_tests *tests)
{
enum reset_type reset_method = RESET_TYPE_ALL;
int rc, rc2;
efx_siena_reset_down(efx, reset_method);
/* Reset the chip immediately so that it is completely
* quiescent regardless of what any VF driver does.
*/
rc = efx_siena_mcdi_reset(efx, reset_method);
if (rc)
goto out;
tests->registers =
efx_farch_test_registers(efx, siena_register_tests,
ARRAY_SIZE(siena_register_tests))
? -1 : 1;
rc = efx_siena_mcdi_reset(efx, reset_method);
out:
rc2 = efx_siena_reset_up(efx, reset_method, rc == 0);
return rc ? rc : rc2;
}
/**************************************************************************
*
* PTP
*
**************************************************************************
*/
static void siena_ptp_write_host_time(struct efx_nic *efx, u32 host_time)
{
_efx_writed(efx, cpu_to_le32(host_time),
FR_CZ_MC_TREG_SMEM + MC_SMEM_P0_PTP_TIME_OFST);
}
static int siena_ptp_set_ts_config(struct efx_nic *efx,
struct hwtstamp_config *init)
{
int rc;
switch (init->rx_filter) {
case HWTSTAMP_FILTER_NONE:
/* if TX timestamping is still requested then leave PTP on */
return efx_siena_ptp_change_mode(efx,
init->tx_type != HWTSTAMP_TX_OFF,
efx_siena_ptp_get_mode(efx));
case HWTSTAMP_FILTER_PTP_V1_L4_EVENT:
case HWTSTAMP_FILTER_PTP_V1_L4_SYNC:
case HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ:
init->rx_filter = HWTSTAMP_FILTER_PTP_V1_L4_EVENT;
return efx_siena_ptp_change_mode(efx, true, MC_CMD_PTP_MODE_V1);
case HWTSTAMP_FILTER_PTP_V2_L4_EVENT:
case HWTSTAMP_FILTER_PTP_V2_L4_SYNC:
case HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ:
init->rx_filter = HWTSTAMP_FILTER_PTP_V2_L4_EVENT;
rc = efx_siena_ptp_change_mode(efx, true,
MC_CMD_PTP_MODE_V2_ENHANCED);
/* bug 33070 - old versions of the firmware do not support the
* improved UUID filtering option. Similarly old versions of the
* application do not expect it to be enabled. If the firmware
* does not accept the enhanced mode, fall back to the standard
* PTP v2 UUID filtering. */
if (rc != 0)
rc = efx_siena_ptp_change_mode(efx, true,
MC_CMD_PTP_MODE_V2);
return rc;
default:
return -ERANGE;
}
}
/**************************************************************************
*
* Device reset
*
**************************************************************************
*/
static int siena_map_reset_flags(u32 *flags)
{
enum {
SIENA_RESET_PORT = (ETH_RESET_DMA | ETH_RESET_FILTER |
ETH_RESET_OFFLOAD | ETH_RESET_MAC |
ETH_RESET_PHY),
SIENA_RESET_MC = (SIENA_RESET_PORT |
ETH_RESET_MGMT << ETH_RESET_SHARED_SHIFT),
};
if ((*flags & SIENA_RESET_MC) == SIENA_RESET_MC) {
*flags &= ~SIENA_RESET_MC;
return RESET_TYPE_WORLD;
}
if ((*flags & SIENA_RESET_PORT) == SIENA_RESET_PORT) {
*flags &= ~SIENA_RESET_PORT;
return RESET_TYPE_ALL;
}
/* no invisible reset implemented */
return -EINVAL;
}
#ifdef CONFIG_EEH
/* When a PCI device is isolated from the bus, a subsequent MMIO read is
* required for the kernel EEH mechanisms to notice. As the Solarflare driver
* was written to minimise MMIO read (for latency) then a periodic call to check
* the EEH status of the device is required so that device recovery can happen
* in a timely fashion.
*/
static void siena_monitor(struct efx_nic *efx)
{
struct eeh_dev *eehdev = pci_dev_to_eeh_dev(efx->pci_dev);
eeh_dev_check_failure(eehdev);
}
#endif
static int siena_probe_nvconfig(struct efx_nic *efx)
{
u32 caps = 0;
int rc;
rc = efx_siena_mcdi_get_board_cfg(efx, efx->net_dev->perm_addr, NULL,
&caps);
efx->timer_quantum_ns =
(caps & (1 << MC_CMD_CAPABILITIES_TURBO_ACTIVE_LBN)) ?
3072 : 6144; /* 768 cycles */
efx->timer_max_ns = efx->type->timer_period_max *
efx->timer_quantum_ns;
return rc;
}
static int siena_dimension_resources(struct efx_nic *efx)
{
/* Each port has a small block of internal SRAM dedicated to
* the buffer table and descriptor caches. In theory we can
* map both blocks to one port, but we don't.
*/
efx_farch_dimension_resources(efx, FR_CZ_BUF_FULL_TBL_ROWS / 2);
return 0;
}
/* On all Falcon-architecture NICs, PFs use BAR 0 for I/O space and BAR 2(&3)
* for memory.
*/
static unsigned int siena_mem_bar(struct efx_nic *efx)
{
return 2;
}
static unsigned int siena_mem_map_size(struct efx_nic *efx)
{
return FR_CZ_MC_TREG_SMEM +
FR_CZ_MC_TREG_SMEM_STEP * FR_CZ_MC_TREG_SMEM_ROWS;
}
static int siena_probe_nic(struct efx_nic *efx)
{
struct siena_nic_data *nic_data;
efx_oword_t reg;
int rc;
/* Allocate storage for hardware specific data */
nic_data = kzalloc(sizeof(struct siena_nic_data), GFP_KERNEL);
if (!nic_data)
return -ENOMEM;
nic_data->efx = efx;
efx->nic_data = nic_data;
if (efx_farch_fpga_ver(efx) != 0) {
netif_err(efx, probe, efx->net_dev,
"Siena FPGA not supported\n");
rc = -ENODEV;
goto fail1;
}
efx->max_channels = EFX_MAX_CHANNELS;
efx->max_vis = EFX_MAX_CHANNELS;
efx->max_tx_channels = EFX_MAX_CHANNELS;
efx->tx_queues_per_channel = 4;
efx_reado(efx, ®, FR_AZ_CS_DEBUG);
efx->port_num = EFX_OWORD_FIELD(reg, FRF_CZ_CS_PORT_NUM) - 1;
rc = efx_siena_mcdi_init(efx);
if (rc)
goto fail1;
/* Now we can reset the NIC */
rc = efx_siena_mcdi_reset(efx, RESET_TYPE_ALL);
if (rc) {
netif_err(efx, probe, efx->net_dev, "failed to reset NIC\n");
goto fail3;
}
siena_init_wol(efx);
/* Allocate memory for INT_KER */
rc = efx_siena_alloc_buffer(efx, &efx->irq_status, sizeof(efx_oword_t),
GFP_KERNEL);
if (rc)
goto fail4;
BUG_ON(efx->irq_status.dma_addr & 0x0f);
netif_dbg(efx, probe, efx->net_dev,
"INT_KER at %llx (virt %p phys %llx)\n",
(unsigned long long)efx->irq_status.dma_addr,
efx->irq_status.addr,
(unsigned long long)virt_to_phys(efx->irq_status.addr));
/* Read in the non-volatile configuration */
rc = siena_probe_nvconfig(efx);
if (rc == -EINVAL) {
netif_err(efx, probe, efx->net_dev,
"NVRAM is invalid therefore using defaults\n");
efx->phy_type = PHY_TYPE_NONE;
efx->mdio.prtad = MDIO_PRTAD_NONE;
} else if (rc) {
goto fail5;
}
rc = efx_siena_mcdi_mon_probe(efx);
if (rc)
goto fail5;
#ifdef CONFIG_SFC_SIENA_SRIOV
efx_siena_sriov_probe(efx);
#endif
efx_siena_ptp_defer_probe_with_channel(efx);
return 0;
fail5:
efx_siena_free_buffer(efx, &efx->irq_status);
fail4:
fail3:
efx_siena_mcdi_detach(efx);
efx_siena_mcdi_fini(efx);
fail1:
kfree(efx->nic_data);
return rc;
}
static int siena_rx_pull_rss_config(struct efx_nic *efx)
{
efx_oword_t temp;
/* Read from IPv6 RSS key as that's longer (the IPv4 key is just the
* first 128 bits of the same key, assuming it's been set by
* siena_rx_push_rss_config, below)
*/
efx_reado(efx, &temp, FR_CZ_RX_RSS_IPV6_REG1);
memcpy(efx->rss_context.rx_hash_key, &temp, sizeof(temp));
efx_reado(efx, &temp, FR_CZ_RX_RSS_IPV6_REG2);
memcpy(efx->rss_context.rx_hash_key + sizeof(temp), &temp, sizeof(temp));
efx_reado(efx, &temp, FR_CZ_RX_RSS_IPV6_REG3);
memcpy(efx->rss_context.rx_hash_key + 2 * sizeof(temp), &temp,
FRF_CZ_RX_RSS_IPV6_TKEY_HI_WIDTH / 8);
efx_farch_rx_pull_indir_table(efx);
return 0;
}
static int siena_rx_push_rss_config(struct efx_nic *efx, bool user,
const u32 *rx_indir_table, const u8 *key)
{
efx_oword_t temp;
/* Set hash key for IPv4 */
if (key)
memcpy(efx->rss_context.rx_hash_key, key, sizeof(temp));
memcpy(&temp, efx->rss_context.rx_hash_key, sizeof(temp));
efx_writeo(efx, &temp, FR_BZ_RX_RSS_TKEY);
/* Enable IPv6 RSS */
BUILD_BUG_ON(sizeof(efx->rss_context.rx_hash_key) <
2 * sizeof(temp) + FRF_CZ_RX_RSS_IPV6_TKEY_HI_WIDTH / 8 ||
FRF_CZ_RX_RSS_IPV6_TKEY_HI_LBN != 0);
memcpy(&temp, efx->rss_context.rx_hash_key, sizeof(temp));
efx_writeo(efx, &temp, FR_CZ_RX_RSS_IPV6_REG1);
memcpy(&temp, efx->rss_context.rx_hash_key + sizeof(temp), sizeof(temp));
efx_writeo(efx, &temp, FR_CZ_RX_RSS_IPV6_REG2);
EFX_POPULATE_OWORD_2(temp, FRF_CZ_RX_RSS_IPV6_THASH_ENABLE, 1,
FRF_CZ_RX_RSS_IPV6_IP_THASH_ENABLE, 1);
memcpy(&temp, efx->rss_context.rx_hash_key + 2 * sizeof(temp),
FRF_CZ_RX_RSS_IPV6_TKEY_HI_WIDTH / 8);
efx_writeo(efx, &temp, FR_CZ_RX_RSS_IPV6_REG3);
memcpy(efx->rss_context.rx_indir_table, rx_indir_table,
sizeof(efx->rss_context.rx_indir_table));
efx_farch_rx_push_indir_table(efx);
return 0;
}
/* This call performs hardware-specific global initialisation, such as
* defining the descriptor cache sizes and number of RSS channels.
* It does not set up any buffers, descriptor rings or event queues.
*/
static int siena_init_nic(struct efx_nic *efx)
{
efx_oword_t temp;
int rc;
/* Recover from a failed assertion post-reset */
rc = efx_siena_mcdi_handle_assertion(efx);
if (rc)
return rc;
/* Squash TX of packets of 16 bytes or less */
efx_reado(efx, &temp, FR_AZ_TX_RESERVED);
EFX_SET_OWORD_FIELD(temp, FRF_BZ_TX_FLUSH_MIN_LEN_EN, 1);
efx_writeo(efx, &temp, FR_AZ_TX_RESERVED);
/* Do not enable TX_NO_EOP_DISC_EN, since it limits packets to 16
* descriptors (which is bad).
*/
efx_reado(efx, &temp, FR_AZ_TX_CFG);
EFX_SET_OWORD_FIELD(temp, FRF_AZ_TX_NO_EOP_DISC_EN, 0);
EFX_SET_OWORD_FIELD(temp, FRF_CZ_TX_FILTER_EN_BIT, 1);
efx_writeo(efx, &temp, FR_AZ_TX_CFG);
efx_reado(efx, &temp, FR_AZ_RX_CFG);
EFX_SET_OWORD_FIELD(temp, FRF_BZ_RX_DESC_PUSH_EN, 0);
EFX_SET_OWORD_FIELD(temp, FRF_BZ_RX_INGR_EN, 1);
/* Enable hash insertion. This is broken for the 'Falcon' hash
* if IPv6 hashing is also enabled, so also select Toeplitz
* TCP/IPv4 and IPv4 hashes. */
EFX_SET_OWORD_FIELD(temp, FRF_BZ_RX_HASH_INSRT_HDR, 1);
EFX_SET_OWORD_FIELD(temp, FRF_BZ_RX_HASH_ALG, 1);
EFX_SET_OWORD_FIELD(temp, FRF_BZ_RX_IP_HASH, 1);
EFX_SET_OWORD_FIELD(temp, FRF_BZ_RX_USR_BUF_SIZE,
EFX_RX_USR_BUF_SIZE >> 5);
efx_writeo(efx, &temp, FR_AZ_RX_CFG);
siena_rx_push_rss_config(efx, false, efx->rss_context.rx_indir_table, NULL);
efx->rss_context.context_id = 0; /* indicates RSS is active */
/* Enable event logging */
rc = efx_siena_mcdi_log_ctrl(efx, true, false, 0);
if (rc)
return rc;
/* Set destination of both TX and RX Flush events */
EFX_POPULATE_OWORD_1(temp, FRF_BZ_FLS_EVQ_ID, 0);
efx_writeo(efx, &temp, FR_BZ_DP_CTRL);
EFX_POPULATE_OWORD_1(temp, FRF_CZ_USREV_DIS, 1);
efx_writeo(efx, &temp, FR_CZ_USR_EV_CFG);
efx_farch_init_common(efx);
return 0;
}
static void siena_remove_nic(struct efx_nic *efx)
{
efx_siena_mcdi_mon_remove(efx);
efx_siena_free_buffer(efx, &efx->irq_status);
efx_siena_mcdi_reset(efx, RESET_TYPE_ALL);
efx_siena_mcdi_detach(efx);
efx_siena_mcdi_fini(efx);
/* Tear down the private nic state */
kfree(efx->nic_data);
efx->nic_data = NULL;
}
#define SIENA_DMA_STAT(ext_name, mcdi_name) \
[SIENA_STAT_ ## ext_name] = \
{ #ext_name, 64, 8 * MC_CMD_MAC_ ## mcdi_name }
#define SIENA_OTHER_STAT(ext_name) \
[SIENA_STAT_ ## ext_name] = { #ext_name, 0, 0 }
#define GENERIC_SW_STAT(ext_name) \
[GENERIC_STAT_ ## ext_name] = { #ext_name, 0, 0 }
static const struct efx_hw_stat_desc siena_stat_desc[SIENA_STAT_COUNT] = {
SIENA_DMA_STAT(tx_bytes, TX_BYTES),
SIENA_OTHER_STAT(tx_good_bytes),
SIENA_DMA_STAT(tx_bad_bytes, TX_BAD_BYTES),
SIENA_DMA_STAT(tx_packets, TX_PKTS),
SIENA_DMA_STAT(tx_bad, TX_BAD_FCS_PKTS),
SIENA_DMA_STAT(tx_pause, TX_PAUSE_PKTS),
SIENA_DMA_STAT(tx_control, TX_CONTROL_PKTS),
SIENA_DMA_STAT(tx_unicast, TX_UNICAST_PKTS),
SIENA_DMA_STAT(tx_multicast, TX_MULTICAST_PKTS),
SIENA_DMA_STAT(tx_broadcast, TX_BROADCAST_PKTS),
SIENA_DMA_STAT(tx_lt64, TX_LT64_PKTS),
SIENA_DMA_STAT(tx_64, TX_64_PKTS),
SIENA_DMA_STAT(tx_65_to_127, TX_65_TO_127_PKTS),
SIENA_DMA_STAT(tx_128_to_255, TX_128_TO_255_PKTS),
SIENA_DMA_STAT(tx_256_to_511, TX_256_TO_511_PKTS),
SIENA_DMA_STAT(tx_512_to_1023, TX_512_TO_1023_PKTS),
SIENA_DMA_STAT(tx_1024_to_15xx, TX_1024_TO_15XX_PKTS),
SIENA_DMA_STAT(tx_15xx_to_jumbo, TX_15XX_TO_JUMBO_PKTS),
SIENA_DMA_STAT(tx_gtjumbo, TX_GTJUMBO_PKTS),
SIENA_OTHER_STAT(tx_collision),
SIENA_DMA_STAT(tx_single_collision, TX_SINGLE_COLLISION_PKTS),
SIENA_DMA_STAT(tx_multiple_collision, TX_MULTIPLE_COLLISION_PKTS),
SIENA_DMA_STAT(tx_excessive_collision, TX_EXCESSIVE_COLLISION_PKTS),
SIENA_DMA_STAT(tx_deferred, TX_DEFERRED_PKTS),
SIENA_DMA_STAT(tx_late_collision, TX_LATE_COLLISION_PKTS),
SIENA_DMA_STAT(tx_excessive_deferred, TX_EXCESSIVE_DEFERRED_PKTS),
SIENA_DMA_STAT(tx_non_tcpudp, TX_NON_TCPUDP_PKTS),
SIENA_DMA_STAT(tx_mac_src_error, TX_MAC_SRC_ERR_PKTS),
SIENA_DMA_STAT(tx_ip_src_error, TX_IP_SRC_ERR_PKTS),
SIENA_DMA_STAT(rx_bytes, RX_BYTES),
SIENA_OTHER_STAT(rx_good_bytes),
SIENA_DMA_STAT(rx_bad_bytes, RX_BAD_BYTES),
SIENA_DMA_STAT(rx_packets, RX_PKTS),
SIENA_DMA_STAT(rx_good, RX_GOOD_PKTS),
SIENA_DMA_STAT(rx_bad, RX_BAD_FCS_PKTS),
SIENA_DMA_STAT(rx_pause, RX_PAUSE_PKTS),
SIENA_DMA_STAT(rx_control, RX_CONTROL_PKTS),
SIENA_DMA_STAT(rx_unicast, RX_UNICAST_PKTS),
SIENA_DMA_STAT(rx_multicast, RX_MULTICAST_PKTS),
SIENA_DMA_STAT(rx_broadcast, RX_BROADCAST_PKTS),
SIENA_DMA_STAT(rx_lt64, RX_UNDERSIZE_PKTS),
SIENA_DMA_STAT(rx_64, RX_64_PKTS),
SIENA_DMA_STAT(rx_65_to_127, RX_65_TO_127_PKTS),
SIENA_DMA_STAT(rx_128_to_255, RX_128_TO_255_PKTS),
SIENA_DMA_STAT(rx_256_to_511, RX_256_TO_511_PKTS),
SIENA_DMA_STAT(rx_512_to_1023, RX_512_TO_1023_PKTS),
SIENA_DMA_STAT(rx_1024_to_15xx, RX_1024_TO_15XX_PKTS),
SIENA_DMA_STAT(rx_15xx_to_jumbo, RX_15XX_TO_JUMBO_PKTS),
SIENA_DMA_STAT(rx_gtjumbo, RX_GTJUMBO_PKTS),
SIENA_DMA_STAT(rx_bad_gtjumbo, RX_JABBER_PKTS),
SIENA_DMA_STAT(rx_overflow, RX_OVERFLOW_PKTS),
SIENA_DMA_STAT(rx_false_carrier, RX_FALSE_CARRIER_PKTS),
SIENA_DMA_STAT(rx_symbol_error, RX_SYMBOL_ERROR_PKTS),
SIENA_DMA_STAT(rx_align_error, RX_ALIGN_ERROR_PKTS),
SIENA_DMA_STAT(rx_length_error, RX_LENGTH_ERROR_PKTS),
SIENA_DMA_STAT(rx_internal_error, RX_INTERNAL_ERROR_PKTS),
SIENA_DMA_STAT(rx_nodesc_drop_cnt, RX_NODESC_DROPS),
GENERIC_SW_STAT(rx_nodesc_trunc),
GENERIC_SW_STAT(rx_noskb_drops),
};
static const unsigned long siena_stat_mask[] = {
[0 ... BITS_TO_LONGS(SIENA_STAT_COUNT) - 1] = ~0UL,
};
static size_t siena_describe_nic_stats(struct efx_nic *efx, u8 *names)
{
return efx_siena_describe_stats(siena_stat_desc, SIENA_STAT_COUNT,
siena_stat_mask, names);
}
static int siena_try_update_nic_stats(struct efx_nic *efx)
{
struct siena_nic_data *nic_data = efx->nic_data;
u64 *stats = nic_data->stats;
__le64 *dma_stats;
__le64 generation_start, generation_end;
dma_stats = efx->stats_buffer.addr;
generation_end = dma_stats[efx->num_mac_stats - 1];
if (generation_end == EFX_MC_STATS_GENERATION_INVALID)
return 0;
rmb();
efx_siena_update_stats(siena_stat_desc, SIENA_STAT_COUNT, siena_stat_mask,
stats, efx->stats_buffer.addr, false);
rmb();
generation_start = dma_stats[MC_CMD_MAC_GENERATION_START];
if (generation_end != generation_start)
return -EAGAIN;
/* Update derived statistics */
efx_siena_fix_nodesc_drop_stat(efx,
&stats[SIENA_STAT_rx_nodesc_drop_cnt]);
efx_update_diff_stat(&stats[SIENA_STAT_tx_good_bytes],
stats[SIENA_STAT_tx_bytes] -
stats[SIENA_STAT_tx_bad_bytes]);
stats[SIENA_STAT_tx_collision] =
stats[SIENA_STAT_tx_single_collision] +
stats[SIENA_STAT_tx_multiple_collision] +
stats[SIENA_STAT_tx_excessive_collision] +
stats[SIENA_STAT_tx_late_collision];
efx_update_diff_stat(&stats[SIENA_STAT_rx_good_bytes],
stats[SIENA_STAT_rx_bytes] -
stats[SIENA_STAT_rx_bad_bytes]);
efx_siena_update_sw_stats(efx, stats);
return 0;
}
static size_t siena_update_nic_stats(struct efx_nic *efx, u64 *full_stats,
struct rtnl_link_stats64 *core_stats)
{
struct siena_nic_data *nic_data = efx->nic_data;
u64 *stats = nic_data->stats;
int retry;
/* If we're unlucky enough to read statistics wduring the DMA, wait
* up to 10ms for it to finish (typically takes <500us) */
for (retry = 0; retry < 100; ++retry) {
if (siena_try_update_nic_stats(efx) == 0)
break;
udelay(100);
}
if (full_stats)
memcpy(full_stats, stats, sizeof(u64) * SIENA_STAT_COUNT);
if (core_stats) {
core_stats->rx_packets = stats[SIENA_STAT_rx_packets];
core_stats->tx_packets = stats[SIENA_STAT_tx_packets];
core_stats->rx_bytes = stats[SIENA_STAT_rx_bytes];
core_stats->tx_bytes = stats[SIENA_STAT_tx_bytes];
core_stats->rx_dropped = stats[SIENA_STAT_rx_nodesc_drop_cnt] +
stats[GENERIC_STAT_rx_nodesc_trunc] +
stats[GENERIC_STAT_rx_noskb_drops];
core_stats->multicast = stats[SIENA_STAT_rx_multicast];
core_stats->collisions = stats[SIENA_STAT_tx_collision];
core_stats->rx_length_errors =
stats[SIENA_STAT_rx_gtjumbo] +
stats[SIENA_STAT_rx_length_error];
core_stats->rx_crc_errors = stats[SIENA_STAT_rx_bad];
core_stats->rx_frame_errors = stats[SIENA_STAT_rx_align_error];
core_stats->rx_fifo_errors = stats[SIENA_STAT_rx_overflow];
core_stats->tx_window_errors =
stats[SIENA_STAT_tx_late_collision];
core_stats->rx_errors = (core_stats->rx_length_errors +
core_stats->rx_crc_errors +
core_stats->rx_frame_errors +
stats[SIENA_STAT_rx_symbol_error]);
core_stats->tx_errors = (core_stats->tx_window_errors +
stats[SIENA_STAT_tx_bad]);
}
return SIENA_STAT_COUNT;
}
static int siena_mac_reconfigure(struct efx_nic *efx, bool mtu_only __always_unused)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_SET_MCAST_HASH_IN_LEN);
int rc;
BUILD_BUG_ON(MC_CMD_SET_MCAST_HASH_IN_LEN !=
MC_CMD_SET_MCAST_HASH_IN_HASH0_OFST +
sizeof(efx->multicast_hash));
efx_farch_filter_sync_rx_mode(efx);
WARN_ON(!mutex_is_locked(&efx->mac_lock));
rc = efx_siena_mcdi_set_mac(efx);
if (rc != 0)
return rc;
memcpy(MCDI_PTR(inbuf, SET_MCAST_HASH_IN_HASH0),
efx->multicast_hash.byte, sizeof(efx->multicast_hash));
return efx_siena_mcdi_rpc(efx, MC_CMD_SET_MCAST_HASH,
inbuf, sizeof(inbuf), NULL, 0, NULL);
}
/**************************************************************************
*
* Wake on LAN
*
**************************************************************************
*/
static void siena_get_wol(struct efx_nic *efx, struct ethtool_wolinfo *wol)
{
struct siena_nic_data *nic_data = efx->nic_data;
wol->supported = WAKE_MAGIC;
if (nic_data->wol_filter_id != -1)
wol->wolopts = WAKE_MAGIC;
else
wol->wolopts = 0;
memset(&wol->sopass, 0, sizeof(wol->sopass));
}
static int siena_set_wol(struct efx_nic *efx, u32 type)
{
struct siena_nic_data *nic_data = efx->nic_data;
int rc;
if (type & ~WAKE_MAGIC)
return -EINVAL;
if (type & WAKE_MAGIC) {
if (nic_data->wol_filter_id != -1)
efx_siena_mcdi_wol_filter_remove(efx,
nic_data->wol_filter_id);
rc = efx_siena_mcdi_wol_filter_set_magic(efx,
efx->net_dev->dev_addr,
&nic_data->wol_filter_id);
if (rc)
goto fail;
pci_wake_from_d3(efx->pci_dev, true);
} else {
rc = efx_siena_mcdi_wol_filter_reset(efx);
nic_data->wol_filter_id = -1;
pci_wake_from_d3(efx->pci_dev, false);
if (rc)
goto fail;
}
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s failed: type=%d rc=%d\n",
__func__, type, rc);
return rc;
}
static void siena_init_wol(struct efx_nic *efx)
{
struct siena_nic_data *nic_data = efx->nic_data;
int rc;
rc = efx_siena_mcdi_wol_filter_get_magic(efx, &nic_data->wol_filter_id);
if (rc != 0) {
/* If it failed, attempt to get into a synchronised
* state with MC by resetting any set WoL filters */
efx_siena_mcdi_wol_filter_reset(efx);
nic_data->wol_filter_id = -1;
} else if (nic_data->wol_filter_id != -1) {
pci_wake_from_d3(efx->pci_dev, true);
}
}
/**************************************************************************
*
* MCDI
*
**************************************************************************
*/
#define MCDI_PDU(efx) \
(efx_port_num(efx) ? MC_SMEM_P1_PDU_OFST : MC_SMEM_P0_PDU_OFST)
#define MCDI_DOORBELL(efx) \
(efx_port_num(efx) ? MC_SMEM_P1_DOORBELL_OFST : MC_SMEM_P0_DOORBELL_OFST)
#define MCDI_STATUS(efx) \
(efx_port_num(efx) ? MC_SMEM_P1_STATUS_OFST : MC_SMEM_P0_STATUS_OFST)
static void siena_mcdi_request(struct efx_nic *efx,
const efx_dword_t *hdr, size_t hdr_len,
const efx_dword_t *sdu, size_t sdu_len)
{
unsigned pdu = FR_CZ_MC_TREG_SMEM + MCDI_PDU(efx);
unsigned doorbell = FR_CZ_MC_TREG_SMEM + MCDI_DOORBELL(efx);
unsigned int i;
unsigned int inlen_dw = DIV_ROUND_UP(sdu_len, 4);
EFX_WARN_ON_PARANOID(hdr_len != 4);
efx_writed(efx, hdr, pdu);
for (i = 0; i < inlen_dw; i++)
efx_writed(efx, &sdu[i], pdu + hdr_len + 4 * i);
/* Ensure the request is written out before the doorbell */
wmb();
/* ring the doorbell with a distinctive value */
_efx_writed(efx, (__force __le32) 0x45789abc, doorbell);
}
static bool siena_mcdi_poll_response(struct efx_nic *efx)
{
unsigned int pdu = FR_CZ_MC_TREG_SMEM + MCDI_PDU(efx);
efx_dword_t hdr;
efx_readd(efx, &hdr, pdu);
/* All 1's indicates that shared memory is in reset (and is
* not a valid hdr). Wait for it to come out reset before
* completing the command
*/
return EFX_DWORD_FIELD(hdr, EFX_DWORD_0) != 0xffffffff &&
EFX_DWORD_FIELD(hdr, MCDI_HEADER_RESPONSE);
}
static void siena_mcdi_read_response(struct efx_nic *efx, efx_dword_t *outbuf,
size_t offset, size_t outlen)
{
unsigned int pdu = FR_CZ_MC_TREG_SMEM + MCDI_PDU(efx);
unsigned int outlen_dw = DIV_ROUND_UP(outlen, 4);
int i;
for (i = 0; i < outlen_dw; i++)
efx_readd(efx, &outbuf[i], pdu + offset + 4 * i);
}
static int siena_mcdi_poll_reboot(struct efx_nic *efx)
{
struct siena_nic_data *nic_data = efx->nic_data;
unsigned int addr = FR_CZ_MC_TREG_SMEM + MCDI_STATUS(efx);
efx_dword_t reg;
u32 value;
efx_readd(efx, ®, addr);
value = EFX_DWORD_FIELD(reg, EFX_DWORD_0);
if (value == 0)
return 0;
EFX_ZERO_DWORD(reg);
efx_writed(efx, ®, addr);
/* MAC statistics have been cleared on the NIC; clear the local
* copies that we update with efx_update_diff_stat().
*/
nic_data->stats[SIENA_STAT_tx_good_bytes] = 0;
nic_data->stats[SIENA_STAT_rx_good_bytes] = 0;
if (value == MC_STATUS_DWORD_ASSERT)
return -EINTR;
else
return -EIO;
}
/**************************************************************************
*
* MTD
*
**************************************************************************
*/
#ifdef CONFIG_SFC_SIENA_MTD
struct siena_nvram_type_info {
int port;
const char *name;
};
static const struct siena_nvram_type_info siena_nvram_types[] = {
[MC_CMD_NVRAM_TYPE_DISABLED_CALLISTO] = { 0, "sfc_dummy_phy" },
[MC_CMD_NVRAM_TYPE_MC_FW] = { 0, "sfc_mcfw" },
[MC_CMD_NVRAM_TYPE_MC_FW_BACKUP] = { 0, "sfc_mcfw_backup" },
[MC_CMD_NVRAM_TYPE_STATIC_CFG_PORT0] = { 0, "sfc_static_cfg" },
[MC_CMD_NVRAM_TYPE_STATIC_CFG_PORT1] = { 1, "sfc_static_cfg" },
[MC_CMD_NVRAM_TYPE_DYNAMIC_CFG_PORT0] = { 0, "sfc_dynamic_cfg" },
[MC_CMD_NVRAM_TYPE_DYNAMIC_CFG_PORT1] = { 1, "sfc_dynamic_cfg" },
[MC_CMD_NVRAM_TYPE_EXP_ROM] = { 0, "sfc_exp_rom" },
[MC_CMD_NVRAM_TYPE_EXP_ROM_CFG_PORT0] = { 0, "sfc_exp_rom_cfg" },
[MC_CMD_NVRAM_TYPE_EXP_ROM_CFG_PORT1] = { 1, "sfc_exp_rom_cfg" },
[MC_CMD_NVRAM_TYPE_PHY_PORT0] = { 0, "sfc_phy_fw" },
[MC_CMD_NVRAM_TYPE_PHY_PORT1] = { 1, "sfc_phy_fw" },
[MC_CMD_NVRAM_TYPE_FPGA] = { 0, "sfc_fpga" },
};
static int siena_mtd_probe_partition(struct efx_nic *efx,
struct efx_mcdi_mtd_partition *part,
unsigned int type)
{
const struct siena_nvram_type_info *info;
size_t size, erase_size;
bool protected;
int rc;
if (type >= ARRAY_SIZE(siena_nvram_types) ||
siena_nvram_types[type].name == NULL)
return -ENODEV;
info = &siena_nvram_types[type];
if (info->port != efx_port_num(efx))
return -ENODEV;
rc = efx_siena_mcdi_nvram_info(efx, type, &size, &erase_size,
&protected);
if (rc)
return rc;
if (protected)
return -ENODEV; /* hide it */
part->nvram_type = type;
part->common.dev_type_name = "Siena NVRAM manager";
part->common.type_name = info->name;
part->common.mtd.type = MTD_NORFLASH;
part->common.mtd.flags = MTD_CAP_NORFLASH;
part->common.mtd.size = size;
part->common.mtd.erasesize = erase_size;
return 0;
}
static int siena_mtd_get_fw_subtypes(struct efx_nic *efx,
struct efx_mcdi_mtd_partition *parts,
size_t n_parts)
{
uint16_t fw_subtype_list[
MC_CMD_GET_BOARD_CFG_OUT_FW_SUBTYPE_LIST_MAXNUM];
size_t i;
int rc;
rc = efx_siena_mcdi_get_board_cfg(efx, NULL, fw_subtype_list, NULL);
if (rc)
return rc;
for (i = 0; i < n_parts; i++)
parts[i].fw_subtype = fw_subtype_list[parts[i].nvram_type];
return 0;
}
static int siena_mtd_probe(struct efx_nic *efx)
{
struct efx_mcdi_mtd_partition *parts;
u32 nvram_types;
unsigned int type;
size_t n_parts;
int rc;
ASSERT_RTNL();
rc = efx_siena_mcdi_nvram_types(efx, &nvram_types);
if (rc)
return rc;
parts = kcalloc(hweight32(nvram_types), sizeof(*parts), GFP_KERNEL);
if (!parts)
return -ENOMEM;
type = 0;
n_parts = 0;
while (nvram_types != 0) {
if (nvram_types & 1) {
rc = siena_mtd_probe_partition(efx, &parts[n_parts],
type);
if (rc == 0)
n_parts++;
else if (rc != -ENODEV)
goto fail;
}
type++;
nvram_types >>= 1;
}
rc = siena_mtd_get_fw_subtypes(efx, parts, n_parts);
if (rc)
goto fail;
rc = efx_siena_mtd_add(efx, &parts[0].common, n_parts, sizeof(*parts));
fail:
if (rc)
kfree(parts);
return rc;
}
#endif /* CONFIG_SFC_SIENA_MTD */
static unsigned int siena_check_caps(const struct efx_nic *efx,
u8 flag, u32 offset)
{
/* Siena did not support MC_CMD_GET_CAPABILITIES */
return 0;
}
static unsigned int efx_siena_recycle_ring_size(const struct efx_nic *efx)
{
/* Maximum link speed is 10G */
return EFX_RECYCLE_RING_SIZE_10G;
}
/**************************************************************************
*
* Revision-dependent attributes used by efx.c and nic.c
*
**************************************************************************
*/
const struct efx_nic_type siena_a0_nic_type = {
.is_vf = false,
.mem_bar = siena_mem_bar,
.mem_map_size = siena_mem_map_size,
.probe = siena_probe_nic,
.remove = siena_remove_nic,
.init = siena_init_nic,
.dimension_resources = siena_dimension_resources,
.fini = efx_siena_port_dummy_op_void,
#ifdef CONFIG_EEH
.monitor = siena_monitor,
#else
.monitor = NULL,
#endif
.map_reset_reason = efx_siena_mcdi_map_reset_reason,
.map_reset_flags = siena_map_reset_flags,
.reset = efx_siena_mcdi_reset,
.probe_port = efx_siena_mcdi_port_probe,
.remove_port = efx_siena_mcdi_port_remove,
.fini_dmaq = efx_farch_fini_dmaq,
.prepare_flush = efx_siena_prepare_flush,
.finish_flush = siena_finish_flush,
.prepare_flr = efx_siena_port_dummy_op_void,
.finish_flr = efx_farch_finish_flr,
.describe_stats = siena_describe_nic_stats,
.update_stats = siena_update_nic_stats,
.start_stats = efx_siena_mcdi_mac_start_stats,
.pull_stats = efx_siena_mcdi_mac_pull_stats,
.stop_stats = efx_siena_mcdi_mac_stop_stats,
.push_irq_moderation = siena_push_irq_moderation,
.reconfigure_mac = siena_mac_reconfigure,
.check_mac_fault = efx_siena_mcdi_mac_check_fault,
.reconfigure_port = efx_siena_mcdi_port_reconfigure,
.get_wol = siena_get_wol,
.set_wol = siena_set_wol,
.resume_wol = siena_init_wol,
.test_chip = siena_test_chip,
.test_nvram = efx_siena_mcdi_nvram_test_all,
.mcdi_request = siena_mcdi_request,
.mcdi_poll_response = siena_mcdi_poll_response,
.mcdi_read_response = siena_mcdi_read_response,
.mcdi_poll_reboot = siena_mcdi_poll_reboot,
.irq_enable_master = efx_farch_irq_enable_master,
.irq_test_generate = efx_farch_irq_test_generate,
.irq_disable_non_ev = efx_farch_irq_disable_master,
.irq_handle_msi = efx_farch_msi_interrupt,
.irq_handle_legacy = efx_farch_legacy_interrupt,
.tx_probe = efx_farch_tx_probe,
.tx_init = efx_farch_tx_init,
.tx_remove = efx_farch_tx_remove,
.tx_write = efx_farch_tx_write,
.tx_limit_len = efx_farch_tx_limit_len,
.tx_enqueue = __efx_siena_enqueue_skb,
.rx_push_rss_config = siena_rx_push_rss_config,
.rx_pull_rss_config = siena_rx_pull_rss_config,
.rx_probe = efx_farch_rx_probe,
.rx_init = efx_farch_rx_init,
.rx_remove = efx_farch_rx_remove,
.rx_write = efx_farch_rx_write,
.rx_defer_refill = efx_farch_rx_defer_refill,
.rx_packet = __efx_siena_rx_packet,
.ev_probe = efx_farch_ev_probe,
.ev_init = efx_farch_ev_init,
.ev_fini = efx_farch_ev_fini,
.ev_remove = efx_farch_ev_remove,
.ev_process = efx_farch_ev_process,
.ev_read_ack = efx_farch_ev_read_ack,
.ev_test_generate = efx_farch_ev_test_generate,
.filter_table_probe = efx_farch_filter_table_probe,
.filter_table_restore = efx_farch_filter_table_restore,
.filter_table_remove = efx_farch_filter_table_remove,
.filter_update_rx_scatter = efx_farch_filter_update_rx_scatter,
.filter_insert = efx_farch_filter_insert,
.filter_remove_safe = efx_farch_filter_remove_safe,
.filter_get_safe = efx_farch_filter_get_safe,
.filter_clear_rx = efx_farch_filter_clear_rx,
.filter_count_rx_used = efx_farch_filter_count_rx_used,
.filter_get_rx_id_limit = efx_farch_filter_get_rx_id_limit,
.filter_get_rx_ids = efx_farch_filter_get_rx_ids,
#ifdef CONFIG_RFS_ACCEL
.filter_rfs_expire_one = efx_farch_filter_rfs_expire_one,
#endif
#ifdef CONFIG_SFC_SIENA_MTD
.mtd_probe = siena_mtd_probe,
.mtd_rename = efx_siena_mcdi_mtd_rename,
.mtd_read = efx_siena_mcdi_mtd_read,
.mtd_erase = efx_siena_mcdi_mtd_erase,
.mtd_write = efx_siena_mcdi_mtd_write,
.mtd_sync = efx_siena_mcdi_mtd_sync,
#endif
.ptp_write_host_time = siena_ptp_write_host_time,
.ptp_set_ts_config = siena_ptp_set_ts_config,
#ifdef CONFIG_SFC_SIENA_SRIOV
.sriov_configure = efx_siena_sriov_configure,
.sriov_init = efx_siena_sriov_init,
.sriov_fini = efx_siena_sriov_fini,
.sriov_wanted = efx_siena_sriov_wanted,
.sriov_reset = efx_siena_sriov_reset,
.sriov_flr = efx_siena_sriov_flr,
.sriov_set_vf_mac = efx_siena_sriov_set_vf_mac,
.sriov_set_vf_vlan = efx_siena_sriov_set_vf_vlan,
.sriov_set_vf_spoofchk = efx_siena_sriov_set_vf_spoofchk,
.sriov_get_vf_config = efx_siena_sriov_get_vf_config,
.vswitching_probe = efx_siena_port_dummy_op_int,
.vswitching_restore = efx_siena_port_dummy_op_int,
.vswitching_remove = efx_siena_port_dummy_op_void,
.set_mac_address = efx_siena_sriov_mac_address_changed,
#endif
.revision = EFX_REV_SIENA_A0,
.txd_ptr_tbl_base = FR_BZ_TX_DESC_PTR_TBL,
.rxd_ptr_tbl_base = FR_BZ_RX_DESC_PTR_TBL,
.buf_tbl_base = FR_BZ_BUF_FULL_TBL,
.evq_ptr_tbl_base = FR_BZ_EVQ_PTR_TBL,
.evq_rptr_tbl_base = FR_BZ_EVQ_RPTR,
.max_dma_mask = DMA_BIT_MASK(FSF_AZ_TX_KER_BUF_ADDR_WIDTH),
.rx_prefix_size = FS_BZ_RX_PREFIX_SIZE,
.rx_hash_offset = FS_BZ_RX_PREFIX_HASH_OFST,
.rx_buffer_padding = 0,
.can_rx_scatter = true,
.option_descriptors = false,
.min_interrupt_mode = EFX_INT_MODE_LEGACY,
.timer_period_max = 1 << FRF_CZ_TC_TIMER_VAL_WIDTH,
.offload_features = (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM |
NETIF_F_RXHASH | NETIF_F_NTUPLE),
.mcdi_max_ver = 1,
.max_rx_ip_filters = FR_BZ_RX_FILTER_TBL0_ROWS,
.hwtstamp_filters = (1 << HWTSTAMP_FILTER_NONE |
1 << HWTSTAMP_FILTER_PTP_V1_L4_EVENT |
1 << HWTSTAMP_FILTER_PTP_V2_L4_EVENT),
.rx_hash_key_size = 16,
.check_caps = siena_check_caps,
.sensor_event = efx_siena_mcdi_sensor_event,
.rx_recycle_ring_size = efx_siena_recycle_ring_size,
};
|
linux-master
|
drivers/net/ethernet/sfc/siena/siena.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2018 Solarflare Communications Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include "net_driver.h"
#include "efx.h"
#include "nic_common.h"
#include "tx_common.h"
#include <net/gso.h>
static unsigned int efx_tx_cb_page_count(struct efx_tx_queue *tx_queue)
{
return DIV_ROUND_UP(tx_queue->ptr_mask + 1,
PAGE_SIZE >> EFX_TX_CB_ORDER);
}
int efx_siena_probe_tx_queue(struct efx_tx_queue *tx_queue)
{
struct efx_nic *efx = tx_queue->efx;
unsigned int entries;
int rc;
/* Create the smallest power-of-two aligned ring */
entries = max(roundup_pow_of_two(efx->txq_entries), EFX_MIN_DMAQ_SIZE);
EFX_WARN_ON_PARANOID(entries > EFX_MAX_DMAQ_SIZE);
tx_queue->ptr_mask = entries - 1;
netif_dbg(efx, probe, efx->net_dev,
"creating TX queue %d size %#x mask %#x\n",
tx_queue->queue, efx->txq_entries, tx_queue->ptr_mask);
/* Allocate software ring */
tx_queue->buffer = kcalloc(entries, sizeof(*tx_queue->buffer),
GFP_KERNEL);
if (!tx_queue->buffer)
return -ENOMEM;
tx_queue->cb_page = kcalloc(efx_tx_cb_page_count(tx_queue),
sizeof(tx_queue->cb_page[0]), GFP_KERNEL);
if (!tx_queue->cb_page) {
rc = -ENOMEM;
goto fail1;
}
/* Allocate hardware ring, determine TXQ type */
rc = efx_nic_probe_tx(tx_queue);
if (rc)
goto fail2;
tx_queue->channel->tx_queue_by_type[tx_queue->type] = tx_queue;
return 0;
fail2:
kfree(tx_queue->cb_page);
tx_queue->cb_page = NULL;
fail1:
kfree(tx_queue->buffer);
tx_queue->buffer = NULL;
return rc;
}
void efx_siena_init_tx_queue(struct efx_tx_queue *tx_queue)
{
struct efx_nic *efx = tx_queue->efx;
netif_dbg(efx, drv, efx->net_dev,
"initialising TX queue %d\n", tx_queue->queue);
tx_queue->insert_count = 0;
tx_queue->notify_count = 0;
tx_queue->write_count = 0;
tx_queue->packet_write_count = 0;
tx_queue->old_write_count = 0;
tx_queue->read_count = 0;
tx_queue->old_read_count = 0;
tx_queue->empty_read_count = 0 | EFX_EMPTY_COUNT_VALID;
tx_queue->xmit_pending = false;
tx_queue->timestamping = (efx_siena_ptp_use_mac_tx_timestamps(efx) &&
tx_queue->channel == efx_siena_ptp_channel(efx));
tx_queue->completed_timestamp_major = 0;
tx_queue->completed_timestamp_minor = 0;
tx_queue->xdp_tx = efx_channel_is_xdp_tx(tx_queue->channel);
tx_queue->tso_version = 0;
/* Set up TX descriptor ring */
efx_nic_init_tx(tx_queue);
tx_queue->initialised = true;
}
void efx_siena_remove_tx_queue(struct efx_tx_queue *tx_queue)
{
int i;
if (!tx_queue->buffer)
return;
netif_dbg(tx_queue->efx, drv, tx_queue->efx->net_dev,
"destroying TX queue %d\n", tx_queue->queue);
efx_nic_remove_tx(tx_queue);
if (tx_queue->cb_page) {
for (i = 0; i < efx_tx_cb_page_count(tx_queue); i++)
efx_siena_free_buffer(tx_queue->efx,
&tx_queue->cb_page[i]);
kfree(tx_queue->cb_page);
tx_queue->cb_page = NULL;
}
kfree(tx_queue->buffer);
tx_queue->buffer = NULL;
tx_queue->channel->tx_queue_by_type[tx_queue->type] = NULL;
}
static void efx_dequeue_buffer(struct efx_tx_queue *tx_queue,
struct efx_tx_buffer *buffer,
unsigned int *pkts_compl,
unsigned int *bytes_compl)
{
if (buffer->unmap_len) {
struct device *dma_dev = &tx_queue->efx->pci_dev->dev;
dma_addr_t unmap_addr = buffer->dma_addr - buffer->dma_offset;
if (buffer->flags & EFX_TX_BUF_MAP_SINGLE)
dma_unmap_single(dma_dev, unmap_addr, buffer->unmap_len,
DMA_TO_DEVICE);
else
dma_unmap_page(dma_dev, unmap_addr, buffer->unmap_len,
DMA_TO_DEVICE);
buffer->unmap_len = 0;
}
if (buffer->flags & EFX_TX_BUF_SKB) {
struct sk_buff *skb = (struct sk_buff *)buffer->skb;
EFX_WARN_ON_PARANOID(!pkts_compl || !bytes_compl);
(*pkts_compl)++;
(*bytes_compl) += skb->len;
if (tx_queue->timestamping &&
(tx_queue->completed_timestamp_major ||
tx_queue->completed_timestamp_minor)) {
struct skb_shared_hwtstamps hwtstamp;
hwtstamp.hwtstamp =
efx_siena_ptp_nic_to_kernel_time(tx_queue);
skb_tstamp_tx(skb, &hwtstamp);
tx_queue->completed_timestamp_major = 0;
tx_queue->completed_timestamp_minor = 0;
}
dev_consume_skb_any((struct sk_buff *)buffer->skb);
netif_vdbg(tx_queue->efx, tx_done, tx_queue->efx->net_dev,
"TX queue %d transmission id %x complete\n",
tx_queue->queue, tx_queue->read_count);
} else if (buffer->flags & EFX_TX_BUF_XDP) {
xdp_return_frame_rx_napi(buffer->xdpf);
}
buffer->len = 0;
buffer->flags = 0;
}
void efx_siena_fini_tx_queue(struct efx_tx_queue *tx_queue)
{
struct efx_tx_buffer *buffer;
netif_dbg(tx_queue->efx, drv, tx_queue->efx->net_dev,
"shutting down TX queue %d\n", tx_queue->queue);
if (!tx_queue->buffer)
return;
/* Free any buffers left in the ring */
while (tx_queue->read_count != tx_queue->write_count) {
unsigned int pkts_compl = 0, bytes_compl = 0;
buffer = &tx_queue->buffer[tx_queue->read_count & tx_queue->ptr_mask];
efx_dequeue_buffer(tx_queue, buffer, &pkts_compl, &bytes_compl);
++tx_queue->read_count;
}
tx_queue->xmit_pending = false;
netdev_tx_reset_queue(tx_queue->core_txq);
}
/* Remove packets from the TX queue
*
* This removes packets from the TX queue, up to and including the
* specified index.
*/
static void efx_dequeue_buffers(struct efx_tx_queue *tx_queue,
unsigned int index,
unsigned int *pkts_compl,
unsigned int *bytes_compl)
{
struct efx_nic *efx = tx_queue->efx;
unsigned int stop_index, read_ptr;
stop_index = (index + 1) & tx_queue->ptr_mask;
read_ptr = tx_queue->read_count & tx_queue->ptr_mask;
while (read_ptr != stop_index) {
struct efx_tx_buffer *buffer = &tx_queue->buffer[read_ptr];
if (!efx_tx_buffer_in_use(buffer)) {
netif_err(efx, tx_err, efx->net_dev,
"TX queue %d spurious TX completion id %d\n",
tx_queue->queue, read_ptr);
efx_siena_schedule_reset(efx, RESET_TYPE_TX_SKIP);
return;
}
efx_dequeue_buffer(tx_queue, buffer, pkts_compl, bytes_compl);
++tx_queue->read_count;
read_ptr = tx_queue->read_count & tx_queue->ptr_mask;
}
}
void efx_siena_xmit_done_check_empty(struct efx_tx_queue *tx_queue)
{
if ((int)(tx_queue->read_count - tx_queue->old_write_count) >= 0) {
tx_queue->old_write_count = READ_ONCE(tx_queue->write_count);
if (tx_queue->read_count == tx_queue->old_write_count) {
/* Ensure that read_count is flushed. */
smp_mb();
tx_queue->empty_read_count =
tx_queue->read_count | EFX_EMPTY_COUNT_VALID;
}
}
}
void efx_siena_xmit_done(struct efx_tx_queue *tx_queue, unsigned int index)
{
unsigned int fill_level, pkts_compl = 0, bytes_compl = 0;
struct efx_nic *efx = tx_queue->efx;
EFX_WARN_ON_ONCE_PARANOID(index > tx_queue->ptr_mask);
efx_dequeue_buffers(tx_queue, index, &pkts_compl, &bytes_compl);
tx_queue->pkts_compl += pkts_compl;
tx_queue->bytes_compl += bytes_compl;
if (pkts_compl > 1)
++tx_queue->merge_events;
/* See if we need to restart the netif queue. This memory
* barrier ensures that we write read_count (inside
* efx_dequeue_buffers()) before reading the queue status.
*/
smp_mb();
if (unlikely(netif_tx_queue_stopped(tx_queue->core_txq)) &&
likely(efx->port_enabled) &&
likely(netif_device_present(efx->net_dev))) {
fill_level = efx_channel_tx_fill_level(tx_queue->channel);
if (fill_level <= efx->txq_wake_thresh)
netif_tx_wake_queue(tx_queue->core_txq);
}
efx_siena_xmit_done_check_empty(tx_queue);
}
/* Remove buffers put into a tx_queue for the current packet.
* None of the buffers must have an skb attached.
*/
void efx_siena_enqueue_unwind(struct efx_tx_queue *tx_queue,
unsigned int insert_count)
{
struct efx_tx_buffer *buffer;
unsigned int bytes_compl = 0;
unsigned int pkts_compl = 0;
/* Work backwards until we hit the original insert pointer value */
while (tx_queue->insert_count != insert_count) {
--tx_queue->insert_count;
buffer = __efx_tx_queue_get_insert_buffer(tx_queue);
efx_dequeue_buffer(tx_queue, buffer, &pkts_compl, &bytes_compl);
}
}
struct efx_tx_buffer *efx_siena_tx_map_chunk(struct efx_tx_queue *tx_queue,
dma_addr_t dma_addr, size_t len)
{
const struct efx_nic_type *nic_type = tx_queue->efx->type;
struct efx_tx_buffer *buffer;
unsigned int dma_len;
/* Map the fragment taking account of NIC-dependent DMA limits. */
do {
buffer = efx_tx_queue_get_insert_buffer(tx_queue);
if (nic_type->tx_limit_len)
dma_len = nic_type->tx_limit_len(tx_queue, dma_addr, len);
else
dma_len = len;
buffer->len = dma_len;
buffer->dma_addr = dma_addr;
buffer->flags = EFX_TX_BUF_CONT;
len -= dma_len;
dma_addr += dma_len;
++tx_queue->insert_count;
} while (len);
return buffer;
}
static int efx_tx_tso_header_length(struct sk_buff *skb)
{
size_t header_len;
if (skb->encapsulation)
header_len = skb_inner_transport_header(skb) -
skb->data +
(inner_tcp_hdr(skb)->doff << 2u);
else
header_len = skb_transport_header(skb) - skb->data +
(tcp_hdr(skb)->doff << 2u);
return header_len;
}
/* Map all data from an SKB for DMA and create descriptors on the queue. */
int efx_siena_tx_map_data(struct efx_tx_queue *tx_queue, struct sk_buff *skb,
unsigned int segment_count)
{
struct efx_nic *efx = tx_queue->efx;
struct device *dma_dev = &efx->pci_dev->dev;
unsigned int frag_index, nr_frags;
dma_addr_t dma_addr, unmap_addr;
unsigned short dma_flags;
size_t len, unmap_len;
nr_frags = skb_shinfo(skb)->nr_frags;
frag_index = 0;
/* Map header data. */
len = skb_headlen(skb);
dma_addr = dma_map_single(dma_dev, skb->data, len, DMA_TO_DEVICE);
dma_flags = EFX_TX_BUF_MAP_SINGLE;
unmap_len = len;
unmap_addr = dma_addr;
if (unlikely(dma_mapping_error(dma_dev, dma_addr)))
return -EIO;
if (segment_count) {
/* For TSO we need to put the header in to a separate
* descriptor. Map this separately if necessary.
*/
size_t header_len = efx_tx_tso_header_length(skb);
if (header_len != len) {
tx_queue->tso_long_headers++;
efx_siena_tx_map_chunk(tx_queue, dma_addr, header_len);
len -= header_len;
dma_addr += header_len;
}
}
/* Add descriptors for each fragment. */
do {
struct efx_tx_buffer *buffer;
skb_frag_t *fragment;
buffer = efx_siena_tx_map_chunk(tx_queue, dma_addr, len);
/* The final descriptor for a fragment is responsible for
* unmapping the whole fragment.
*/
buffer->flags = EFX_TX_BUF_CONT | dma_flags;
buffer->unmap_len = unmap_len;
buffer->dma_offset = buffer->dma_addr - unmap_addr;
if (frag_index >= nr_frags) {
/* Store SKB details with the final buffer for
* the completion.
*/
buffer->skb = skb;
buffer->flags = EFX_TX_BUF_SKB | dma_flags;
return 0;
}
/* Move on to the next fragment. */
fragment = &skb_shinfo(skb)->frags[frag_index++];
len = skb_frag_size(fragment);
dma_addr = skb_frag_dma_map(dma_dev, fragment, 0, len,
DMA_TO_DEVICE);
dma_flags = 0;
unmap_len = len;
unmap_addr = dma_addr;
if (unlikely(dma_mapping_error(dma_dev, dma_addr)))
return -EIO;
} while (1);
}
unsigned int efx_siena_tx_max_skb_descs(struct efx_nic *efx)
{
/* Header and payload descriptor for each output segment, plus
* one for every input fragment boundary within a segment
*/
unsigned int max_descs = EFX_TSO_MAX_SEGS * 2 + MAX_SKB_FRAGS;
/* Possibly one more per segment for option descriptors */
if (efx_nic_rev(efx) >= EFX_REV_HUNT_A0)
max_descs += EFX_TSO_MAX_SEGS;
/* Possibly more for PCIe page boundaries within input fragments */
if (PAGE_SIZE > EFX_PAGE_SIZE)
max_descs += max_t(unsigned int, MAX_SKB_FRAGS,
DIV_ROUND_UP(GSO_MAX_SIZE, EFX_PAGE_SIZE));
return max_descs;
}
/*
* Fallback to software TSO.
*
* This is used if we are unable to send a GSO packet through hardware TSO.
* This should only ever happen due to per-queue restrictions - unsupported
* packets should first be filtered by the feature flags.
*
* Returns 0 on success, error code otherwise.
*/
int efx_siena_tx_tso_fallback(struct efx_tx_queue *tx_queue,
struct sk_buff *skb)
{
struct sk_buff *segments, *next;
segments = skb_gso_segment(skb, 0);
if (IS_ERR(segments))
return PTR_ERR(segments);
dev_consume_skb_any(skb);
skb_list_walk_safe(segments, skb, next) {
skb_mark_not_on_list(skb);
efx_enqueue_skb(tx_queue, skb);
}
return 0;
}
|
linux-master
|
drivers/net/ethernet/sfc/siena/tx_common.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2010-2012 Solarflare Communications Inc.
*/
#include <linux/pci.h>
#include <linux/module.h>
#include "net_driver.h"
#include "efx.h"
#include "efx_channels.h"
#include "nic.h"
#include "io.h"
#include "mcdi.h"
#include "filter.h"
#include "mcdi_pcol.h"
#include "farch_regs.h"
#include "siena_sriov.h"
#include "vfdi.h"
/* Number of longs required to track all the VIs in a VF */
#define VI_MASK_LENGTH BITS_TO_LONGS(1 << EFX_VI_SCALE_MAX)
/* Maximum number of RX queues supported */
#define VF_MAX_RX_QUEUES 63
/**
* enum efx_vf_tx_filter_mode - TX MAC filtering behaviour
* @VF_TX_FILTER_OFF: Disabled
* @VF_TX_FILTER_AUTO: Enabled if MAC address assigned to VF and only
* 2 TX queues allowed per VF.
* @VF_TX_FILTER_ON: Enabled
*/
enum efx_vf_tx_filter_mode {
VF_TX_FILTER_OFF,
VF_TX_FILTER_AUTO,
VF_TX_FILTER_ON,
};
/**
* struct siena_vf - Back-end resource and protocol state for a PCI VF
* @efx: The Efx NIC owning this VF
* @pci_rid: The PCI requester ID for this VF
* @pci_name: The PCI name (formatted address) of this VF
* @index: Index of VF within its port and PF.
* @req: VFDI incoming request work item. Incoming USR_EV events are received
* by the NAPI handler, but must be handled by executing MCDI requests
* inside a work item.
* @req_addr: VFDI incoming request DMA address (in VF's PCI address space).
* @req_type: Expected next incoming (from VF) %VFDI_EV_TYPE member.
* @req_seqno: Expected next incoming (from VF) %VFDI_EV_SEQ member.
* @msg_seqno: Next %VFDI_EV_SEQ member to reply to VF. Protected by
* @status_lock
* @busy: VFDI request queued to be processed or being processed. Receiving
* a VFDI request when @busy is set is an error condition.
* @buf: Incoming VFDI requests are DMA from the VF into this buffer.
* @buftbl_base: Buffer table entries for this VF start at this index.
* @rx_filtering: Receive filtering has been requested by the VF driver.
* @rx_filter_flags: The flags sent in the %VFDI_OP_INSERT_FILTER request.
* @rx_filter_qid: VF relative qid for RX filter requested by VF.
* @rx_filter_id: Receive MAC filter ID. Only one filter per VF is supported.
* @tx_filter_mode: Transmit MAC filtering mode.
* @tx_filter_id: Transmit MAC filter ID.
* @addr: The MAC address and outer vlan tag of the VF.
* @status_addr: VF DMA address of page for &struct vfdi_status updates.
* @status_lock: Mutex protecting @msg_seqno, @status_addr, @addr,
* @peer_page_addrs and @peer_page_count from simultaneous
* updates by the VM and consumption by
* efx_siena_sriov_update_vf_addr()
* @peer_page_addrs: Pointer to an array of guest pages for local addresses.
* @peer_page_count: Number of entries in @peer_page_count.
* @evq0_addrs: Array of guest pages backing evq0.
* @evq0_count: Number of entries in @evq0_addrs.
* @flush_waitq: wait queue used by %VFDI_OP_FINI_ALL_QUEUES handler
* to wait for flush completions.
* @txq_lock: Mutex for TX queue allocation.
* @txq_mask: Mask of initialized transmit queues.
* @txq_count: Number of initialized transmit queues.
* @rxq_mask: Mask of initialized receive queues.
* @rxq_count: Number of initialized receive queues.
* @rxq_retry_mask: Mask or receive queues that need to be flushed again
* due to flush failure.
* @rxq_retry_count: Number of receive queues in @rxq_retry_mask.
* @reset_work: Work item to schedule a VF reset.
*/
struct siena_vf {
struct efx_nic *efx;
unsigned int pci_rid;
char pci_name[13]; /* dddd:bb:dd.f */
unsigned int index;
struct work_struct req;
u64 req_addr;
int req_type;
unsigned req_seqno;
unsigned msg_seqno;
bool busy;
struct efx_buffer buf;
unsigned buftbl_base;
bool rx_filtering;
enum efx_filter_flags rx_filter_flags;
unsigned rx_filter_qid;
int rx_filter_id;
enum efx_vf_tx_filter_mode tx_filter_mode;
int tx_filter_id;
struct vfdi_endpoint addr;
u64 status_addr;
struct mutex status_lock;
u64 *peer_page_addrs;
unsigned peer_page_count;
u64 evq0_addrs[EFX_MAX_VF_EVQ_SIZE * sizeof(efx_qword_t) /
EFX_BUF_SIZE];
unsigned evq0_count;
wait_queue_head_t flush_waitq;
struct mutex txq_lock;
unsigned long txq_mask[VI_MASK_LENGTH];
unsigned txq_count;
unsigned long rxq_mask[VI_MASK_LENGTH];
unsigned rxq_count;
unsigned long rxq_retry_mask[VI_MASK_LENGTH];
atomic_t rxq_retry_count;
struct work_struct reset_work;
};
struct efx_memcpy_req {
unsigned int from_rid;
void *from_buf;
u64 from_addr;
unsigned int to_rid;
u64 to_addr;
unsigned length;
};
/**
* struct efx_local_addr - A MAC address on the vswitch without a VF.
*
* Siena does not have a switch, so VFs can't transmit data to each
* other. Instead the VFs must be made aware of the local addresses
* on the vswitch, so that they can arrange for an alternative
* software datapath to be used.
*
* @link: List head for insertion into efx->local_addr_list.
* @addr: Ethernet address
*/
struct efx_local_addr {
struct list_head link;
u8 addr[ETH_ALEN];
};
/**
* struct efx_endpoint_page - Page of vfdi_endpoint structures
*
* @link: List head for insertion into efx->local_page_list.
* @ptr: Pointer to page.
* @addr: DMA address of page.
*/
struct efx_endpoint_page {
struct list_head link;
void *ptr;
dma_addr_t addr;
};
/* Buffer table entries are reserved txq0,rxq0,evq0,txq1,rxq1,evq1 */
#define EFX_BUFTBL_TXQ_BASE(_vf, _qid) \
((_vf)->buftbl_base + EFX_VF_BUFTBL_PER_VI * (_qid))
#define EFX_BUFTBL_RXQ_BASE(_vf, _qid) \
(EFX_BUFTBL_TXQ_BASE(_vf, _qid) + \
(EFX_MAX_DMAQ_SIZE * sizeof(efx_qword_t) / EFX_BUF_SIZE))
#define EFX_BUFTBL_EVQ_BASE(_vf, _qid) \
(EFX_BUFTBL_TXQ_BASE(_vf, _qid) + \
(2 * EFX_MAX_DMAQ_SIZE * sizeof(efx_qword_t) / EFX_BUF_SIZE))
#define EFX_FIELD_MASK(_field) \
((1 << _field ## _WIDTH) - 1)
/* VFs can only use this many transmit channels */
static unsigned int vf_max_tx_channels = 2;
module_param(vf_max_tx_channels, uint, 0444);
MODULE_PARM_DESC(vf_max_tx_channels,
"Limit the number of TX channels VFs can use");
static int max_vfs = -1;
module_param(max_vfs, int, 0444);
MODULE_PARM_DESC(max_vfs,
"Reduce the number of VFs initialized by the driver");
/* Workqueue used by VFDI communication. We can't use the global
* workqueue because it may be running the VF driver's probe()
* routine, which will be blocked there waiting for a VFDI response.
*/
static struct workqueue_struct *vfdi_workqueue;
static unsigned abs_index(struct siena_vf *vf, unsigned index)
{
return EFX_VI_BASE + vf->index * efx_vf_size(vf->efx) + index;
}
static int efx_siena_sriov_cmd(struct efx_nic *efx, bool enable,
unsigned *vi_scale_out, unsigned *vf_total_out)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_SRIOV_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_SRIOV_OUT_LEN);
unsigned vi_scale, vf_total;
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, SRIOV_IN_ENABLE, enable ? 1 : 0);
MCDI_SET_DWORD(inbuf, SRIOV_IN_VI_BASE, EFX_VI_BASE);
MCDI_SET_DWORD(inbuf, SRIOV_IN_VF_COUNT, efx->vf_count);
rc = efx_siena_mcdi_rpc_quiet(efx, MC_CMD_SRIOV, inbuf,
MC_CMD_SRIOV_IN_LEN, outbuf,
MC_CMD_SRIOV_OUT_LEN, &outlen);
if (rc)
return rc;
if (outlen < MC_CMD_SRIOV_OUT_LEN)
return -EIO;
vf_total = MCDI_DWORD(outbuf, SRIOV_OUT_VF_TOTAL);
vi_scale = MCDI_DWORD(outbuf, SRIOV_OUT_VI_SCALE);
if (vi_scale > EFX_VI_SCALE_MAX)
return -EOPNOTSUPP;
if (vi_scale_out)
*vi_scale_out = vi_scale;
if (vf_total_out)
*vf_total_out = vf_total;
return 0;
}
static void efx_siena_sriov_usrev(struct efx_nic *efx, bool enabled)
{
struct siena_nic_data *nic_data = efx->nic_data;
efx_oword_t reg;
EFX_POPULATE_OWORD_2(reg,
FRF_CZ_USREV_DIS, enabled ? 0 : 1,
FRF_CZ_DFLT_EVQ, nic_data->vfdi_channel->channel);
efx_writeo(efx, ®, FR_CZ_USR_EV_CFG);
}
static int efx_siena_sriov_memcpy(struct efx_nic *efx,
struct efx_memcpy_req *req,
unsigned int count)
{
MCDI_DECLARE_BUF(inbuf, MCDI_CTL_SDU_LEN_MAX_V1);
MCDI_DECLARE_STRUCT_PTR(record);
unsigned int index, used;
u64 from_addr;
u32 from_rid;
int rc;
mb(); /* Finish writing source/reading dest before DMA starts */
if (WARN_ON(count > MC_CMD_MEMCPY_IN_RECORD_MAXNUM))
return -ENOBUFS;
used = MC_CMD_MEMCPY_IN_LEN(count);
for (index = 0; index < count; index++) {
record = MCDI_ARRAY_STRUCT_PTR(inbuf, MEMCPY_IN_RECORD, index);
MCDI_SET_DWORD(record, MEMCPY_RECORD_TYPEDEF_NUM_RECORDS,
count);
MCDI_SET_DWORD(record, MEMCPY_RECORD_TYPEDEF_TO_RID,
req->to_rid);
MCDI_SET_QWORD(record, MEMCPY_RECORD_TYPEDEF_TO_ADDR,
req->to_addr);
if (req->from_buf == NULL) {
from_rid = req->from_rid;
from_addr = req->from_addr;
} else {
if (WARN_ON(used + req->length >
MCDI_CTL_SDU_LEN_MAX_V1)) {
rc = -ENOBUFS;
goto out;
}
from_rid = MC_CMD_MEMCPY_RECORD_TYPEDEF_RID_INLINE;
from_addr = used;
memcpy(_MCDI_PTR(inbuf, used), req->from_buf,
req->length);
used += req->length;
}
MCDI_SET_DWORD(record, MEMCPY_RECORD_TYPEDEF_FROM_RID, from_rid);
MCDI_SET_QWORD(record, MEMCPY_RECORD_TYPEDEF_FROM_ADDR,
from_addr);
MCDI_SET_DWORD(record, MEMCPY_RECORD_TYPEDEF_LENGTH,
req->length);
++req;
}
rc = efx_siena_mcdi_rpc(efx, MC_CMD_MEMCPY, inbuf, used, NULL, 0, NULL);
out:
mb(); /* Don't write source/read dest before DMA is complete */
return rc;
}
/* The TX filter is entirely controlled by this driver, and is modified
* underneath the feet of the VF
*/
static void efx_siena_sriov_reset_tx_filter(struct siena_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct efx_filter_spec filter;
u16 vlan;
int rc;
if (vf->tx_filter_id != -1) {
efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
vf->tx_filter_id);
netif_dbg(efx, hw, efx->net_dev, "Removed vf %s tx filter %d\n",
vf->pci_name, vf->tx_filter_id);
vf->tx_filter_id = -1;
}
if (is_zero_ether_addr(vf->addr.mac_addr))
return;
/* Turn on TX filtering automatically if not explicitly
* enabled or disabled.
*/
if (vf->tx_filter_mode == VF_TX_FILTER_AUTO && vf_max_tx_channels <= 2)
vf->tx_filter_mode = VF_TX_FILTER_ON;
vlan = ntohs(vf->addr.tci) & VLAN_VID_MASK;
efx_filter_init_tx(&filter, abs_index(vf, 0));
rc = efx_filter_set_eth_local(&filter,
vlan ? vlan : EFX_FILTER_VID_UNSPEC,
vf->addr.mac_addr);
BUG_ON(rc);
rc = efx_filter_insert_filter(efx, &filter, true);
if (rc < 0) {
netif_warn(efx, hw, efx->net_dev,
"Unable to migrate tx filter for vf %s\n",
vf->pci_name);
} else {
netif_dbg(efx, hw, efx->net_dev, "Inserted vf %s tx filter %d\n",
vf->pci_name, rc);
vf->tx_filter_id = rc;
}
}
/* The RX filter is managed here on behalf of the VF driver */
static void efx_siena_sriov_reset_rx_filter(struct siena_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct efx_filter_spec filter;
u16 vlan;
int rc;
if (vf->rx_filter_id != -1) {
efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
vf->rx_filter_id);
netif_dbg(efx, hw, efx->net_dev, "Removed vf %s rx filter %d\n",
vf->pci_name, vf->rx_filter_id);
vf->rx_filter_id = -1;
}
if (!vf->rx_filtering || is_zero_ether_addr(vf->addr.mac_addr))
return;
vlan = ntohs(vf->addr.tci) & VLAN_VID_MASK;
efx_filter_init_rx(&filter, EFX_FILTER_PRI_REQUIRED,
vf->rx_filter_flags,
abs_index(vf, vf->rx_filter_qid));
rc = efx_filter_set_eth_local(&filter,
vlan ? vlan : EFX_FILTER_VID_UNSPEC,
vf->addr.mac_addr);
BUG_ON(rc);
rc = efx_filter_insert_filter(efx, &filter, true);
if (rc < 0) {
netif_warn(efx, hw, efx->net_dev,
"Unable to insert rx filter for vf %s\n",
vf->pci_name);
} else {
netif_dbg(efx, hw, efx->net_dev, "Inserted vf %s rx filter %d\n",
vf->pci_name, rc);
vf->rx_filter_id = rc;
}
}
static void __efx_siena_sriov_update_vf_addr(struct siena_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct siena_nic_data *nic_data = efx->nic_data;
efx_siena_sriov_reset_tx_filter(vf);
efx_siena_sriov_reset_rx_filter(vf);
queue_work(vfdi_workqueue, &nic_data->peer_work);
}
/* Push the peer list to this VF. The caller must hold status_lock to interlock
* with VFDI requests, and they must be serialised against manipulation of
* local_page_list, either by acquiring local_lock or by running from
* efx_siena_sriov_peer_work()
*/
static void __efx_siena_sriov_push_vf_status(struct siena_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct siena_nic_data *nic_data = efx->nic_data;
struct vfdi_status *status = nic_data->vfdi_status.addr;
struct efx_memcpy_req copy[4];
struct efx_endpoint_page *epp;
unsigned int pos, count;
unsigned data_offset;
efx_qword_t event;
WARN_ON(!mutex_is_locked(&vf->status_lock));
WARN_ON(!vf->status_addr);
status->local = vf->addr;
status->generation_end = ++status->generation_start;
memset(copy, '\0', sizeof(copy));
/* Write generation_start */
copy[0].from_buf = &status->generation_start;
copy[0].to_rid = vf->pci_rid;
copy[0].to_addr = vf->status_addr + offsetof(struct vfdi_status,
generation_start);
copy[0].length = sizeof(status->generation_start);
/* DMA the rest of the structure (excluding the generations). This
* assumes that the non-generation portion of vfdi_status is in
* one chunk starting at the version member.
*/
data_offset = offsetof(struct vfdi_status, version);
copy[1].from_rid = efx->pci_dev->devfn;
copy[1].from_addr = nic_data->vfdi_status.dma_addr + data_offset;
copy[1].to_rid = vf->pci_rid;
copy[1].to_addr = vf->status_addr + data_offset;
copy[1].length = status->length - data_offset;
/* Copy the peer pages */
pos = 2;
count = 0;
list_for_each_entry(epp, &nic_data->local_page_list, link) {
if (count == vf->peer_page_count) {
/* The VF driver will know they need to provide more
* pages because peer_addr_count is too large.
*/
break;
}
copy[pos].from_buf = NULL;
copy[pos].from_rid = efx->pci_dev->devfn;
copy[pos].from_addr = epp->addr;
copy[pos].to_rid = vf->pci_rid;
copy[pos].to_addr = vf->peer_page_addrs[count];
copy[pos].length = EFX_PAGE_SIZE;
if (++pos == ARRAY_SIZE(copy)) {
efx_siena_sriov_memcpy(efx, copy, ARRAY_SIZE(copy));
pos = 0;
}
++count;
}
/* Write generation_end */
copy[pos].from_buf = &status->generation_end;
copy[pos].to_rid = vf->pci_rid;
copy[pos].to_addr = vf->status_addr + offsetof(struct vfdi_status,
generation_end);
copy[pos].length = sizeof(status->generation_end);
efx_siena_sriov_memcpy(efx, copy, pos + 1);
/* Notify the guest */
EFX_POPULATE_QWORD_3(event,
FSF_AZ_EV_CODE, FSE_CZ_EV_CODE_USER_EV,
VFDI_EV_SEQ, (vf->msg_seqno & 0xff),
VFDI_EV_TYPE, VFDI_EV_TYPE_STATUS);
++vf->msg_seqno;
efx_farch_generate_event(efx,
EFX_VI_BASE + vf->index * efx_vf_size(efx),
&event);
}
static void efx_siena_sriov_bufs(struct efx_nic *efx, unsigned offset,
u64 *addr, unsigned count)
{
efx_qword_t buf;
unsigned pos;
for (pos = 0; pos < count; ++pos) {
EFX_POPULATE_QWORD_3(buf,
FRF_AZ_BUF_ADR_REGION, 0,
FRF_AZ_BUF_ADR_FBUF,
addr ? addr[pos] >> 12 : 0,
FRF_AZ_BUF_OWNER_ID_FBUF, 0);
efx_sram_writeq(efx, efx->membase + FR_BZ_BUF_FULL_TBL,
&buf, offset + pos);
}
}
static bool bad_vf_index(struct efx_nic *efx, unsigned index)
{
return index >= efx_vf_size(efx);
}
static bool bad_buf_count(unsigned buf_count, unsigned max_entry_count)
{
unsigned max_buf_count = max_entry_count *
sizeof(efx_qword_t) / EFX_BUF_SIZE;
return ((buf_count & (buf_count - 1)) || buf_count > max_buf_count);
}
/* Check that VI specified by per-port index belongs to a VF.
* Optionally set VF index and VI index within the VF.
*/
static bool map_vi_index(struct efx_nic *efx, unsigned abs_index,
struct siena_vf **vf_out, unsigned *rel_index_out)
{
struct siena_nic_data *nic_data = efx->nic_data;
unsigned vf_i;
if (abs_index < EFX_VI_BASE)
return true;
vf_i = (abs_index - EFX_VI_BASE) / efx_vf_size(efx);
if (vf_i >= efx->vf_init_count)
return true;
if (vf_out)
*vf_out = nic_data->vf + vf_i;
if (rel_index_out)
*rel_index_out = abs_index % efx_vf_size(efx);
return false;
}
static int efx_vfdi_init_evq(struct siena_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct vfdi_req *req = vf->buf.addr;
unsigned vf_evq = req->u.init_evq.index;
unsigned buf_count = req->u.init_evq.buf_count;
unsigned abs_evq = abs_index(vf, vf_evq);
unsigned buftbl = EFX_BUFTBL_EVQ_BASE(vf, vf_evq);
efx_oword_t reg;
if (bad_vf_index(efx, vf_evq) ||
bad_buf_count(buf_count, EFX_MAX_VF_EVQ_SIZE)) {
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Invalid INIT_EVQ from %s: evq %d bufs %d\n",
vf->pci_name, vf_evq, buf_count);
return VFDI_RC_EINVAL;
}
efx_siena_sriov_bufs(efx, buftbl, req->u.init_evq.addr, buf_count);
EFX_POPULATE_OWORD_3(reg,
FRF_CZ_TIMER_Q_EN, 1,
FRF_CZ_HOST_NOTIFY_MODE, 0,
FRF_CZ_TIMER_MODE, FFE_CZ_TIMER_MODE_DIS);
efx_writeo_table(efx, ®, FR_BZ_TIMER_TBL, abs_evq);
EFX_POPULATE_OWORD_3(reg,
FRF_AZ_EVQ_EN, 1,
FRF_AZ_EVQ_SIZE, __ffs(buf_count),
FRF_AZ_EVQ_BUF_BASE_ID, buftbl);
efx_writeo_table(efx, ®, FR_BZ_EVQ_PTR_TBL, abs_evq);
if (vf_evq == 0) {
memcpy(vf->evq0_addrs, req->u.init_evq.addr,
buf_count * sizeof(u64));
vf->evq0_count = buf_count;
}
return VFDI_RC_SUCCESS;
}
static int efx_vfdi_init_rxq(struct siena_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct vfdi_req *req = vf->buf.addr;
unsigned vf_rxq = req->u.init_rxq.index;
unsigned vf_evq = req->u.init_rxq.evq;
unsigned buf_count = req->u.init_rxq.buf_count;
unsigned buftbl = EFX_BUFTBL_RXQ_BASE(vf, vf_rxq);
unsigned label;
efx_oword_t reg;
if (bad_vf_index(efx, vf_evq) || bad_vf_index(efx, vf_rxq) ||
vf_rxq >= VF_MAX_RX_QUEUES ||
bad_buf_count(buf_count, EFX_MAX_DMAQ_SIZE)) {
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Invalid INIT_RXQ from %s: rxq %d evq %d "
"buf_count %d\n", vf->pci_name, vf_rxq,
vf_evq, buf_count);
return VFDI_RC_EINVAL;
}
if (__test_and_set_bit(req->u.init_rxq.index, vf->rxq_mask))
++vf->rxq_count;
efx_siena_sriov_bufs(efx, buftbl, req->u.init_rxq.addr, buf_count);
label = req->u.init_rxq.label & EFX_FIELD_MASK(FRF_AZ_RX_DESCQ_LABEL);
EFX_POPULATE_OWORD_6(reg,
FRF_AZ_RX_DESCQ_BUF_BASE_ID, buftbl,
FRF_AZ_RX_DESCQ_EVQ_ID, abs_index(vf, vf_evq),
FRF_AZ_RX_DESCQ_LABEL, label,
FRF_AZ_RX_DESCQ_SIZE, __ffs(buf_count),
FRF_AZ_RX_DESCQ_JUMBO,
!!(req->u.init_rxq.flags &
VFDI_RXQ_FLAG_SCATTER_EN),
FRF_AZ_RX_DESCQ_EN, 1);
efx_writeo_table(efx, ®, FR_BZ_RX_DESC_PTR_TBL,
abs_index(vf, vf_rxq));
return VFDI_RC_SUCCESS;
}
static int efx_vfdi_init_txq(struct siena_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct vfdi_req *req = vf->buf.addr;
unsigned vf_txq = req->u.init_txq.index;
unsigned vf_evq = req->u.init_txq.evq;
unsigned buf_count = req->u.init_txq.buf_count;
unsigned buftbl = EFX_BUFTBL_TXQ_BASE(vf, vf_txq);
unsigned label, eth_filt_en;
efx_oword_t reg;
if (bad_vf_index(efx, vf_evq) || bad_vf_index(efx, vf_txq) ||
vf_txq >= vf_max_tx_channels ||
bad_buf_count(buf_count, EFX_MAX_DMAQ_SIZE)) {
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Invalid INIT_TXQ from %s: txq %d evq %d "
"buf_count %d\n", vf->pci_name, vf_txq,
vf_evq, buf_count);
return VFDI_RC_EINVAL;
}
mutex_lock(&vf->txq_lock);
if (__test_and_set_bit(req->u.init_txq.index, vf->txq_mask))
++vf->txq_count;
mutex_unlock(&vf->txq_lock);
efx_siena_sriov_bufs(efx, buftbl, req->u.init_txq.addr, buf_count);
eth_filt_en = vf->tx_filter_mode == VF_TX_FILTER_ON;
label = req->u.init_txq.label & EFX_FIELD_MASK(FRF_AZ_TX_DESCQ_LABEL);
EFX_POPULATE_OWORD_8(reg,
FRF_CZ_TX_DPT_Q_MASK_WIDTH, min(efx->vi_scale, 1U),
FRF_CZ_TX_DPT_ETH_FILT_EN, eth_filt_en,
FRF_AZ_TX_DESCQ_EN, 1,
FRF_AZ_TX_DESCQ_BUF_BASE_ID, buftbl,
FRF_AZ_TX_DESCQ_EVQ_ID, abs_index(vf, vf_evq),
FRF_AZ_TX_DESCQ_LABEL, label,
FRF_AZ_TX_DESCQ_SIZE, __ffs(buf_count),
FRF_BZ_TX_NON_IP_DROP_DIS, 1);
efx_writeo_table(efx, ®, FR_BZ_TX_DESC_PTR_TBL,
abs_index(vf, vf_txq));
return VFDI_RC_SUCCESS;
}
/* Returns true when efx_vfdi_fini_all_queues should wake */
static bool efx_vfdi_flush_wake(struct siena_vf *vf)
{
/* Ensure that all updates are visible to efx_vfdi_fini_all_queues() */
smp_mb();
return (!vf->txq_count && !vf->rxq_count) ||
atomic_read(&vf->rxq_retry_count);
}
static void efx_vfdi_flush_clear(struct siena_vf *vf)
{
memset(vf->txq_mask, 0, sizeof(vf->txq_mask));
vf->txq_count = 0;
memset(vf->rxq_mask, 0, sizeof(vf->rxq_mask));
vf->rxq_count = 0;
memset(vf->rxq_retry_mask, 0, sizeof(vf->rxq_retry_mask));
atomic_set(&vf->rxq_retry_count, 0);
}
static int efx_vfdi_fini_all_queues(struct siena_vf *vf)
{
struct efx_nic *efx = vf->efx;
efx_oword_t reg;
unsigned count = efx_vf_size(efx);
unsigned vf_offset = EFX_VI_BASE + vf->index * efx_vf_size(efx);
unsigned timeout = HZ;
unsigned index, rxqs_count;
MCDI_DECLARE_BUF(inbuf, MC_CMD_FLUSH_RX_QUEUES_IN_LENMAX);
int rc;
BUILD_BUG_ON(VF_MAX_RX_QUEUES >
MC_CMD_FLUSH_RX_QUEUES_IN_QID_OFST_MAXNUM);
rtnl_lock();
efx_siena_prepare_flush(efx);
rtnl_unlock();
/* Flush all the initialized queues */
rxqs_count = 0;
for (index = 0; index < count; ++index) {
if (test_bit(index, vf->txq_mask)) {
EFX_POPULATE_OWORD_2(reg,
FRF_AZ_TX_FLUSH_DESCQ_CMD, 1,
FRF_AZ_TX_FLUSH_DESCQ,
vf_offset + index);
efx_writeo(efx, ®, FR_AZ_TX_FLUSH_DESCQ);
}
if (test_bit(index, vf->rxq_mask)) {
MCDI_SET_ARRAY_DWORD(
inbuf, FLUSH_RX_QUEUES_IN_QID_OFST,
rxqs_count, vf_offset + index);
rxqs_count++;
}
}
atomic_set(&vf->rxq_retry_count, 0);
while (timeout && (vf->rxq_count || vf->txq_count)) {
rc = efx_siena_mcdi_rpc(efx, MC_CMD_FLUSH_RX_QUEUES, inbuf,
MC_CMD_FLUSH_RX_QUEUES_IN_LEN(rxqs_count),
NULL, 0, NULL);
WARN_ON(rc < 0);
timeout = wait_event_timeout(vf->flush_waitq,
efx_vfdi_flush_wake(vf),
timeout);
rxqs_count = 0;
for (index = 0; index < count; ++index) {
if (test_and_clear_bit(index, vf->rxq_retry_mask)) {
atomic_dec(&vf->rxq_retry_count);
MCDI_SET_ARRAY_DWORD(
inbuf, FLUSH_RX_QUEUES_IN_QID_OFST,
rxqs_count, vf_offset + index);
rxqs_count++;
}
}
}
rtnl_lock();
siena_finish_flush(efx);
rtnl_unlock();
/* Irrespective of success/failure, fini the queues */
EFX_ZERO_OWORD(reg);
for (index = 0; index < count; ++index) {
efx_writeo_table(efx, ®, FR_BZ_RX_DESC_PTR_TBL,
vf_offset + index);
efx_writeo_table(efx, ®, FR_BZ_TX_DESC_PTR_TBL,
vf_offset + index);
efx_writeo_table(efx, ®, FR_BZ_EVQ_PTR_TBL,
vf_offset + index);
efx_writeo_table(efx, ®, FR_BZ_TIMER_TBL,
vf_offset + index);
}
efx_siena_sriov_bufs(efx, vf->buftbl_base, NULL,
EFX_VF_BUFTBL_PER_VI * efx_vf_size(efx));
efx_vfdi_flush_clear(vf);
vf->evq0_count = 0;
return timeout ? 0 : VFDI_RC_ETIMEDOUT;
}
static int efx_vfdi_insert_filter(struct siena_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct siena_nic_data *nic_data = efx->nic_data;
struct vfdi_req *req = vf->buf.addr;
unsigned vf_rxq = req->u.mac_filter.rxq;
unsigned flags;
if (bad_vf_index(efx, vf_rxq) || vf->rx_filtering) {
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Invalid INSERT_FILTER from %s: rxq %d "
"flags 0x%x\n", vf->pci_name, vf_rxq,
req->u.mac_filter.flags);
return VFDI_RC_EINVAL;
}
flags = 0;
if (req->u.mac_filter.flags & VFDI_MAC_FILTER_FLAG_RSS)
flags |= EFX_FILTER_FLAG_RX_RSS;
if (req->u.mac_filter.flags & VFDI_MAC_FILTER_FLAG_SCATTER)
flags |= EFX_FILTER_FLAG_RX_SCATTER;
vf->rx_filter_flags = flags;
vf->rx_filter_qid = vf_rxq;
vf->rx_filtering = true;
efx_siena_sriov_reset_rx_filter(vf);
queue_work(vfdi_workqueue, &nic_data->peer_work);
return VFDI_RC_SUCCESS;
}
static int efx_vfdi_remove_all_filters(struct siena_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct siena_nic_data *nic_data = efx->nic_data;
vf->rx_filtering = false;
efx_siena_sriov_reset_rx_filter(vf);
queue_work(vfdi_workqueue, &nic_data->peer_work);
return VFDI_RC_SUCCESS;
}
static int efx_vfdi_set_status_page(struct siena_vf *vf)
{
struct efx_nic *efx = vf->efx;
struct siena_nic_data *nic_data = efx->nic_data;
struct vfdi_req *req = vf->buf.addr;
u64 page_count = req->u.set_status_page.peer_page_count;
u64 max_page_count =
(EFX_PAGE_SIZE -
offsetof(struct vfdi_req, u.set_status_page.peer_page_addr[0]))
/ sizeof(req->u.set_status_page.peer_page_addr[0]);
if (!req->u.set_status_page.dma_addr || page_count > max_page_count) {
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Invalid SET_STATUS_PAGE from %s\n",
vf->pci_name);
return VFDI_RC_EINVAL;
}
mutex_lock(&nic_data->local_lock);
mutex_lock(&vf->status_lock);
vf->status_addr = req->u.set_status_page.dma_addr;
kfree(vf->peer_page_addrs);
vf->peer_page_addrs = NULL;
vf->peer_page_count = 0;
if (page_count) {
vf->peer_page_addrs = kcalloc(page_count, sizeof(u64),
GFP_KERNEL);
if (vf->peer_page_addrs) {
memcpy(vf->peer_page_addrs,
req->u.set_status_page.peer_page_addr,
page_count * sizeof(u64));
vf->peer_page_count = page_count;
}
}
__efx_siena_sriov_push_vf_status(vf);
mutex_unlock(&vf->status_lock);
mutex_unlock(&nic_data->local_lock);
return VFDI_RC_SUCCESS;
}
static int efx_vfdi_clear_status_page(struct siena_vf *vf)
{
mutex_lock(&vf->status_lock);
vf->status_addr = 0;
mutex_unlock(&vf->status_lock);
return VFDI_RC_SUCCESS;
}
typedef int (*efx_vfdi_op_t)(struct siena_vf *vf);
static const efx_vfdi_op_t vfdi_ops[VFDI_OP_LIMIT] = {
[VFDI_OP_INIT_EVQ] = efx_vfdi_init_evq,
[VFDI_OP_INIT_TXQ] = efx_vfdi_init_txq,
[VFDI_OP_INIT_RXQ] = efx_vfdi_init_rxq,
[VFDI_OP_FINI_ALL_QUEUES] = efx_vfdi_fini_all_queues,
[VFDI_OP_INSERT_FILTER] = efx_vfdi_insert_filter,
[VFDI_OP_REMOVE_ALL_FILTERS] = efx_vfdi_remove_all_filters,
[VFDI_OP_SET_STATUS_PAGE] = efx_vfdi_set_status_page,
[VFDI_OP_CLEAR_STATUS_PAGE] = efx_vfdi_clear_status_page,
};
static void efx_siena_sriov_vfdi(struct work_struct *work)
{
struct siena_vf *vf = container_of(work, struct siena_vf, req);
struct efx_nic *efx = vf->efx;
struct vfdi_req *req = vf->buf.addr;
struct efx_memcpy_req copy[2];
int rc;
/* Copy this page into the local address space */
memset(copy, '\0', sizeof(copy));
copy[0].from_rid = vf->pci_rid;
copy[0].from_addr = vf->req_addr;
copy[0].to_rid = efx->pci_dev->devfn;
copy[0].to_addr = vf->buf.dma_addr;
copy[0].length = EFX_PAGE_SIZE;
rc = efx_siena_sriov_memcpy(efx, copy, 1);
if (rc) {
/* If we can't get the request, we can't reply to the caller */
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Unable to fetch VFDI request from %s rc %d\n",
vf->pci_name, -rc);
vf->busy = false;
return;
}
if (req->op < VFDI_OP_LIMIT && vfdi_ops[req->op] != NULL) {
rc = vfdi_ops[req->op](vf);
if (rc == 0) {
netif_dbg(efx, hw, efx->net_dev,
"vfdi request %d from %s ok\n",
req->op, vf->pci_name);
}
} else {
netif_dbg(efx, hw, efx->net_dev,
"ERROR: Unrecognised request %d from VF %s addr "
"%llx\n", req->op, vf->pci_name,
(unsigned long long)vf->req_addr);
rc = VFDI_RC_EOPNOTSUPP;
}
/* Allow subsequent VF requests */
vf->busy = false;
smp_wmb();
/* Respond to the request */
req->rc = rc;
req->op = VFDI_OP_RESPONSE;
memset(copy, '\0', sizeof(copy));
copy[0].from_buf = &req->rc;
copy[0].to_rid = vf->pci_rid;
copy[0].to_addr = vf->req_addr + offsetof(struct vfdi_req, rc);
copy[0].length = sizeof(req->rc);
copy[1].from_buf = &req->op;
copy[1].to_rid = vf->pci_rid;
copy[1].to_addr = vf->req_addr + offsetof(struct vfdi_req, op);
copy[1].length = sizeof(req->op);
(void)efx_siena_sriov_memcpy(efx, copy, ARRAY_SIZE(copy));
}
/* After a reset the event queues inside the guests no longer exist. Fill the
* event ring in guest memory with VFDI reset events, then (re-initialise) the
* event queue to raise an interrupt. The guest driver will then recover.
*/
static void efx_siena_sriov_reset_vf(struct siena_vf *vf,
struct efx_buffer *buffer)
{
struct efx_nic *efx = vf->efx;
struct efx_memcpy_req copy_req[4];
efx_qword_t event;
unsigned int pos, count, k, buftbl, abs_evq;
efx_oword_t reg;
efx_dword_t ptr;
int rc;
BUG_ON(buffer->len != EFX_PAGE_SIZE);
if (!vf->evq0_count)
return;
BUG_ON(vf->evq0_count & (vf->evq0_count - 1));
mutex_lock(&vf->status_lock);
EFX_POPULATE_QWORD_3(event,
FSF_AZ_EV_CODE, FSE_CZ_EV_CODE_USER_EV,
VFDI_EV_SEQ, vf->msg_seqno,
VFDI_EV_TYPE, VFDI_EV_TYPE_RESET);
vf->msg_seqno++;
for (pos = 0; pos < EFX_PAGE_SIZE; pos += sizeof(event))
memcpy(buffer->addr + pos, &event, sizeof(event));
for (pos = 0; pos < vf->evq0_count; pos += count) {
count = min_t(unsigned, vf->evq0_count - pos,
ARRAY_SIZE(copy_req));
for (k = 0; k < count; k++) {
copy_req[k].from_buf = NULL;
copy_req[k].from_rid = efx->pci_dev->devfn;
copy_req[k].from_addr = buffer->dma_addr;
copy_req[k].to_rid = vf->pci_rid;
copy_req[k].to_addr = vf->evq0_addrs[pos + k];
copy_req[k].length = EFX_PAGE_SIZE;
}
rc = efx_siena_sriov_memcpy(efx, copy_req, count);
if (rc) {
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Unable to notify %s of reset"
": %d\n", vf->pci_name, -rc);
break;
}
}
/* Reinitialise, arm and trigger evq0 */
abs_evq = abs_index(vf, 0);
buftbl = EFX_BUFTBL_EVQ_BASE(vf, 0);
efx_siena_sriov_bufs(efx, buftbl, vf->evq0_addrs, vf->evq0_count);
EFX_POPULATE_OWORD_3(reg,
FRF_CZ_TIMER_Q_EN, 1,
FRF_CZ_HOST_NOTIFY_MODE, 0,
FRF_CZ_TIMER_MODE, FFE_CZ_TIMER_MODE_DIS);
efx_writeo_table(efx, ®, FR_BZ_TIMER_TBL, abs_evq);
EFX_POPULATE_OWORD_3(reg,
FRF_AZ_EVQ_EN, 1,
FRF_AZ_EVQ_SIZE, __ffs(vf->evq0_count),
FRF_AZ_EVQ_BUF_BASE_ID, buftbl);
efx_writeo_table(efx, ®, FR_BZ_EVQ_PTR_TBL, abs_evq);
EFX_POPULATE_DWORD_1(ptr, FRF_AZ_EVQ_RPTR, 0);
efx_writed(efx, &ptr, FR_BZ_EVQ_RPTR + FR_BZ_EVQ_RPTR_STEP * abs_evq);
mutex_unlock(&vf->status_lock);
}
static void efx_siena_sriov_reset_vf_work(struct work_struct *work)
{
struct siena_vf *vf = container_of(work, struct siena_vf, req);
struct efx_nic *efx = vf->efx;
struct efx_buffer buf;
if (!efx_siena_alloc_buffer(efx, &buf, EFX_PAGE_SIZE, GFP_NOIO)) {
efx_siena_sriov_reset_vf(vf, &buf);
efx_siena_free_buffer(efx, &buf);
}
}
static void efx_siena_sriov_handle_no_channel(struct efx_nic *efx)
{
netif_err(efx, drv, efx->net_dev,
"ERROR: IOV requires MSI-X and 1 additional interrupt"
"vector. IOV disabled\n");
efx->vf_count = 0;
}
static int efx_siena_sriov_probe_channel(struct efx_channel *channel)
{
struct siena_nic_data *nic_data = channel->efx->nic_data;
nic_data->vfdi_channel = channel;
return 0;
}
static void
efx_siena_sriov_get_channel_name(struct efx_channel *channel,
char *buf, size_t len)
{
snprintf(buf, len, "%s-iov", channel->efx->name);
}
static const struct efx_channel_type efx_siena_sriov_channel_type = {
.handle_no_channel = efx_siena_sriov_handle_no_channel,
.pre_probe = efx_siena_sriov_probe_channel,
.post_remove = efx_siena_channel_dummy_op_void,
.get_name = efx_siena_sriov_get_channel_name,
/* no copy operation; channel must not be reallocated */
.keep_eventq = true,
};
void efx_siena_sriov_probe(struct efx_nic *efx)
{
unsigned count;
if (!max_vfs)
return;
if (efx_siena_sriov_cmd(efx, false, &efx->vi_scale, &count)) {
pci_info(efx->pci_dev, "no SR-IOV VFs probed\n");
return;
}
if (count > 0 && count > max_vfs)
count = max_vfs;
/* efx_nic_dimension_resources() will reduce vf_count as appopriate */
efx->vf_count = count;
efx->extra_channel_type[EFX_EXTRA_CHANNEL_IOV] = &efx_siena_sriov_channel_type;
}
/* Copy the list of individual addresses into the vfdi_status.peers
* array and auxiliary pages, protected by %local_lock. Drop that lock
* and then broadcast the address list to every VF.
*/
static void efx_siena_sriov_peer_work(struct work_struct *data)
{
struct siena_nic_data *nic_data = container_of(data,
struct siena_nic_data,
peer_work);
struct efx_nic *efx = nic_data->efx;
struct vfdi_status *vfdi_status = nic_data->vfdi_status.addr;
struct siena_vf *vf;
struct efx_local_addr *local_addr;
struct vfdi_endpoint *peer;
struct efx_endpoint_page *epp;
struct list_head pages;
unsigned int peer_space;
unsigned int peer_count;
unsigned int pos;
mutex_lock(&nic_data->local_lock);
/* Move the existing peer pages off %local_page_list */
INIT_LIST_HEAD(&pages);
list_splice_tail_init(&nic_data->local_page_list, &pages);
/* Populate the VF addresses starting from entry 1 (entry 0 is
* the PF address)
*/
peer = vfdi_status->peers + 1;
peer_space = ARRAY_SIZE(vfdi_status->peers) - 1;
peer_count = 1;
for (pos = 0; pos < efx->vf_count; ++pos) {
vf = nic_data->vf + pos;
mutex_lock(&vf->status_lock);
if (vf->rx_filtering && !is_zero_ether_addr(vf->addr.mac_addr)) {
*peer++ = vf->addr;
++peer_count;
--peer_space;
BUG_ON(peer_space == 0);
}
mutex_unlock(&vf->status_lock);
}
/* Fill the remaining addresses */
list_for_each_entry(local_addr, &nic_data->local_addr_list, link) {
ether_addr_copy(peer->mac_addr, local_addr->addr);
peer->tci = 0;
++peer;
++peer_count;
if (--peer_space == 0) {
if (list_empty(&pages)) {
epp = kmalloc(sizeof(*epp), GFP_KERNEL);
if (!epp)
break;
epp->ptr = dma_alloc_coherent(
&efx->pci_dev->dev, EFX_PAGE_SIZE,
&epp->addr, GFP_KERNEL);
if (!epp->ptr) {
kfree(epp);
break;
}
} else {
epp = list_first_entry(
&pages, struct efx_endpoint_page, link);
list_del(&epp->link);
}
list_add_tail(&epp->link, &nic_data->local_page_list);
peer = (struct vfdi_endpoint *)epp->ptr;
peer_space = EFX_PAGE_SIZE / sizeof(struct vfdi_endpoint);
}
}
vfdi_status->peer_count = peer_count;
mutex_unlock(&nic_data->local_lock);
/* Free any now unused endpoint pages */
while (!list_empty(&pages)) {
epp = list_first_entry(
&pages, struct efx_endpoint_page, link);
list_del(&epp->link);
dma_free_coherent(&efx->pci_dev->dev, EFX_PAGE_SIZE,
epp->ptr, epp->addr);
kfree(epp);
}
/* Finally, push the pages */
for (pos = 0; pos < efx->vf_count; ++pos) {
vf = nic_data->vf + pos;
mutex_lock(&vf->status_lock);
if (vf->status_addr)
__efx_siena_sriov_push_vf_status(vf);
mutex_unlock(&vf->status_lock);
}
}
static void efx_siena_sriov_free_local(struct efx_nic *efx)
{
struct siena_nic_data *nic_data = efx->nic_data;
struct efx_local_addr *local_addr;
struct efx_endpoint_page *epp;
while (!list_empty(&nic_data->local_addr_list)) {
local_addr = list_first_entry(&nic_data->local_addr_list,
struct efx_local_addr, link);
list_del(&local_addr->link);
kfree(local_addr);
}
while (!list_empty(&nic_data->local_page_list)) {
epp = list_first_entry(&nic_data->local_page_list,
struct efx_endpoint_page, link);
list_del(&epp->link);
dma_free_coherent(&efx->pci_dev->dev, EFX_PAGE_SIZE,
epp->ptr, epp->addr);
kfree(epp);
}
}
static int efx_siena_sriov_vf_alloc(struct efx_nic *efx)
{
unsigned index;
struct siena_vf *vf;
struct siena_nic_data *nic_data = efx->nic_data;
nic_data->vf = kcalloc(efx->vf_count, sizeof(*nic_data->vf),
GFP_KERNEL);
if (!nic_data->vf)
return -ENOMEM;
for (index = 0; index < efx->vf_count; ++index) {
vf = nic_data->vf + index;
vf->efx = efx;
vf->index = index;
vf->rx_filter_id = -1;
vf->tx_filter_mode = VF_TX_FILTER_AUTO;
vf->tx_filter_id = -1;
INIT_WORK(&vf->req, efx_siena_sriov_vfdi);
INIT_WORK(&vf->reset_work, efx_siena_sriov_reset_vf_work);
init_waitqueue_head(&vf->flush_waitq);
mutex_init(&vf->status_lock);
mutex_init(&vf->txq_lock);
}
return 0;
}
static void efx_siena_sriov_vfs_fini(struct efx_nic *efx)
{
struct siena_nic_data *nic_data = efx->nic_data;
struct siena_vf *vf;
unsigned int pos;
for (pos = 0; pos < efx->vf_count; ++pos) {
vf = nic_data->vf + pos;
efx_siena_free_buffer(efx, &vf->buf);
kfree(vf->peer_page_addrs);
vf->peer_page_addrs = NULL;
vf->peer_page_count = 0;
vf->evq0_count = 0;
}
}
static int efx_siena_sriov_vfs_init(struct efx_nic *efx)
{
struct pci_dev *pci_dev = efx->pci_dev;
struct siena_nic_data *nic_data = efx->nic_data;
unsigned index, devfn, sriov, buftbl_base;
u16 offset, stride;
struct siena_vf *vf;
int rc;
sriov = pci_find_ext_capability(pci_dev, PCI_EXT_CAP_ID_SRIOV);
if (!sriov)
return -ENOENT;
pci_read_config_word(pci_dev, sriov + PCI_SRIOV_VF_OFFSET, &offset);
pci_read_config_word(pci_dev, sriov + PCI_SRIOV_VF_STRIDE, &stride);
buftbl_base = nic_data->vf_buftbl_base;
devfn = pci_dev->devfn + offset;
for (index = 0; index < efx->vf_count; ++index) {
vf = nic_data->vf + index;
/* Reserve buffer entries */
vf->buftbl_base = buftbl_base;
buftbl_base += EFX_VF_BUFTBL_PER_VI * efx_vf_size(efx);
vf->pci_rid = devfn;
snprintf(vf->pci_name, sizeof(vf->pci_name),
"%04x:%02x:%02x.%d",
pci_domain_nr(pci_dev->bus), pci_dev->bus->number,
PCI_SLOT(devfn), PCI_FUNC(devfn));
rc = efx_siena_alloc_buffer(efx, &vf->buf, EFX_PAGE_SIZE,
GFP_KERNEL);
if (rc)
goto fail;
devfn += stride;
}
return 0;
fail:
efx_siena_sriov_vfs_fini(efx);
return rc;
}
int efx_siena_sriov_init(struct efx_nic *efx)
{
struct net_device *net_dev = efx->net_dev;
struct siena_nic_data *nic_data = efx->nic_data;
struct vfdi_status *vfdi_status;
int rc;
/* Ensure there's room for vf_channel */
BUILD_BUG_ON(EFX_MAX_CHANNELS + 1 >= EFX_VI_BASE);
/* Ensure that VI_BASE is aligned on VI_SCALE */
BUILD_BUG_ON(EFX_VI_BASE & ((1 << EFX_VI_SCALE_MAX) - 1));
if (efx->vf_count == 0)
return 0;
rc = efx_siena_sriov_cmd(efx, true, NULL, NULL);
if (rc)
goto fail_cmd;
rc = efx_siena_alloc_buffer(efx, &nic_data->vfdi_status,
sizeof(*vfdi_status), GFP_KERNEL);
if (rc)
goto fail_status;
vfdi_status = nic_data->vfdi_status.addr;
memset(vfdi_status, 0, sizeof(*vfdi_status));
vfdi_status->version = 1;
vfdi_status->length = sizeof(*vfdi_status);
vfdi_status->max_tx_channels = vf_max_tx_channels;
vfdi_status->vi_scale = efx->vi_scale;
vfdi_status->rss_rxq_count = efx->rss_spread;
vfdi_status->peer_count = 1 + efx->vf_count;
vfdi_status->timer_quantum_ns = efx->timer_quantum_ns;
rc = efx_siena_sriov_vf_alloc(efx);
if (rc)
goto fail_alloc;
mutex_init(&nic_data->local_lock);
INIT_WORK(&nic_data->peer_work, efx_siena_sriov_peer_work);
INIT_LIST_HEAD(&nic_data->local_addr_list);
INIT_LIST_HEAD(&nic_data->local_page_list);
rc = efx_siena_sriov_vfs_init(efx);
if (rc)
goto fail_vfs;
rtnl_lock();
ether_addr_copy(vfdi_status->peers[0].mac_addr, net_dev->dev_addr);
efx->vf_init_count = efx->vf_count;
rtnl_unlock();
efx_siena_sriov_usrev(efx, true);
/* At this point we must be ready to accept VFDI requests */
rc = pci_enable_sriov(efx->pci_dev, efx->vf_count);
if (rc)
goto fail_pci;
netif_info(efx, probe, net_dev,
"enabled SR-IOV for %d VFs, %d VI per VF\n",
efx->vf_count, efx_vf_size(efx));
return 0;
fail_pci:
efx_siena_sriov_usrev(efx, false);
rtnl_lock();
efx->vf_init_count = 0;
rtnl_unlock();
efx_siena_sriov_vfs_fini(efx);
fail_vfs:
cancel_work_sync(&nic_data->peer_work);
efx_siena_sriov_free_local(efx);
kfree(nic_data->vf);
fail_alloc:
efx_siena_free_buffer(efx, &nic_data->vfdi_status);
fail_status:
efx_siena_sriov_cmd(efx, false, NULL, NULL);
fail_cmd:
return rc;
}
void efx_siena_sriov_fini(struct efx_nic *efx)
{
struct siena_vf *vf;
unsigned int pos;
struct siena_nic_data *nic_data = efx->nic_data;
if (efx->vf_init_count == 0)
return;
/* Disable all interfaces to reconfiguration */
BUG_ON(nic_data->vfdi_channel->enabled);
efx_siena_sriov_usrev(efx, false);
rtnl_lock();
efx->vf_init_count = 0;
rtnl_unlock();
/* Flush all reconfiguration work */
for (pos = 0; pos < efx->vf_count; ++pos) {
vf = nic_data->vf + pos;
cancel_work_sync(&vf->req);
cancel_work_sync(&vf->reset_work);
}
cancel_work_sync(&nic_data->peer_work);
pci_disable_sriov(efx->pci_dev);
/* Tear down back-end state */
efx_siena_sriov_vfs_fini(efx);
efx_siena_sriov_free_local(efx);
kfree(nic_data->vf);
efx_siena_free_buffer(efx, &nic_data->vfdi_status);
efx_siena_sriov_cmd(efx, false, NULL, NULL);
}
void efx_siena_sriov_event(struct efx_channel *channel, efx_qword_t *event)
{
struct efx_nic *efx = channel->efx;
struct siena_vf *vf;
unsigned qid, seq, type, data;
qid = EFX_QWORD_FIELD(*event, FSF_CZ_USER_QID);
/* USR_EV_REG_VALUE is dword0, so access the VFDI_EV fields directly */
BUILD_BUG_ON(FSF_CZ_USER_EV_REG_VALUE_LBN != 0);
seq = EFX_QWORD_FIELD(*event, VFDI_EV_SEQ);
type = EFX_QWORD_FIELD(*event, VFDI_EV_TYPE);
data = EFX_QWORD_FIELD(*event, VFDI_EV_DATA);
netif_vdbg(efx, hw, efx->net_dev,
"USR_EV event from qid %d seq 0x%x type %d data 0x%x\n",
qid, seq, type, data);
if (map_vi_index(efx, qid, &vf, NULL))
return;
if (vf->busy)
goto error;
if (type == VFDI_EV_TYPE_REQ_WORD0) {
/* Resynchronise */
vf->req_type = VFDI_EV_TYPE_REQ_WORD0;
vf->req_seqno = seq + 1;
vf->req_addr = 0;
} else if (seq != (vf->req_seqno++ & 0xff) || type != vf->req_type)
goto error;
switch (vf->req_type) {
case VFDI_EV_TYPE_REQ_WORD0:
case VFDI_EV_TYPE_REQ_WORD1:
case VFDI_EV_TYPE_REQ_WORD2:
vf->req_addr |= (u64)data << (vf->req_type << 4);
++vf->req_type;
return;
case VFDI_EV_TYPE_REQ_WORD3:
vf->req_addr |= (u64)data << 48;
vf->req_type = VFDI_EV_TYPE_REQ_WORD0;
vf->busy = true;
queue_work(vfdi_workqueue, &vf->req);
return;
}
error:
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"ERROR: Screaming VFDI request from %s\n",
vf->pci_name);
/* Reset the request and sequence number */
vf->req_type = VFDI_EV_TYPE_REQ_WORD0;
vf->req_seqno = seq + 1;
}
void efx_siena_sriov_flr(struct efx_nic *efx, unsigned vf_i)
{
struct siena_nic_data *nic_data = efx->nic_data;
struct siena_vf *vf;
if (vf_i > efx->vf_init_count)
return;
vf = nic_data->vf + vf_i;
netif_info(efx, hw, efx->net_dev,
"FLR on VF %s\n", vf->pci_name);
vf->status_addr = 0;
efx_vfdi_remove_all_filters(vf);
efx_vfdi_flush_clear(vf);
vf->evq0_count = 0;
}
int efx_siena_sriov_mac_address_changed(struct efx_nic *efx)
{
struct siena_nic_data *nic_data = efx->nic_data;
struct vfdi_status *vfdi_status = nic_data->vfdi_status.addr;
if (!efx->vf_init_count)
return 0;
ether_addr_copy(vfdi_status->peers[0].mac_addr,
efx->net_dev->dev_addr);
queue_work(vfdi_workqueue, &nic_data->peer_work);
return 0;
}
void efx_siena_sriov_tx_flush_done(struct efx_nic *efx, efx_qword_t *event)
{
struct siena_vf *vf;
unsigned queue, qid;
queue = EFX_QWORD_FIELD(*event, FSF_AZ_DRIVER_EV_SUBDATA);
if (map_vi_index(efx, queue, &vf, &qid))
return;
/* Ignore flush completions triggered by an FLR */
if (!test_bit(qid, vf->txq_mask))
return;
__clear_bit(qid, vf->txq_mask);
--vf->txq_count;
if (efx_vfdi_flush_wake(vf))
wake_up(&vf->flush_waitq);
}
void efx_siena_sriov_rx_flush_done(struct efx_nic *efx, efx_qword_t *event)
{
struct siena_vf *vf;
unsigned ev_failed, queue, qid;
queue = EFX_QWORD_FIELD(*event, FSF_AZ_DRIVER_EV_RX_DESCQ_ID);
ev_failed = EFX_QWORD_FIELD(*event,
FSF_AZ_DRIVER_EV_RX_FLUSH_FAIL);
if (map_vi_index(efx, queue, &vf, &qid))
return;
if (!test_bit(qid, vf->rxq_mask))
return;
if (ev_failed) {
set_bit(qid, vf->rxq_retry_mask);
atomic_inc(&vf->rxq_retry_count);
} else {
__clear_bit(qid, vf->rxq_mask);
--vf->rxq_count;
}
if (efx_vfdi_flush_wake(vf))
wake_up(&vf->flush_waitq);
}
/* Called from napi. Schedule the reset work item */
void efx_siena_sriov_desc_fetch_err(struct efx_nic *efx, unsigned dmaq)
{
struct siena_vf *vf;
unsigned int rel;
if (map_vi_index(efx, dmaq, &vf, &rel))
return;
if (net_ratelimit())
netif_err(efx, hw, efx->net_dev,
"VF %d DMA Q %d reports descriptor fetch error.\n",
vf->index, rel);
queue_work(vfdi_workqueue, &vf->reset_work);
}
/* Reset all VFs */
void efx_siena_sriov_reset(struct efx_nic *efx)
{
struct siena_nic_data *nic_data = efx->nic_data;
unsigned int vf_i;
struct efx_buffer buf;
struct siena_vf *vf;
ASSERT_RTNL();
if (efx->vf_init_count == 0)
return;
efx_siena_sriov_usrev(efx, true);
(void)efx_siena_sriov_cmd(efx, true, NULL, NULL);
if (efx_siena_alloc_buffer(efx, &buf, EFX_PAGE_SIZE, GFP_NOIO))
return;
for (vf_i = 0; vf_i < efx->vf_init_count; ++vf_i) {
vf = nic_data->vf + vf_i;
efx_siena_sriov_reset_vf(vf, &buf);
}
efx_siena_free_buffer(efx, &buf);
}
int efx_init_sriov(void)
{
/* A single threaded workqueue is sufficient. efx_siena_sriov_vfdi() and
* efx_siena_sriov_peer_work() spend almost all their time sleeping for
* MCDI to complete anyway
*/
vfdi_workqueue = create_singlethread_workqueue("sfc_vfdi");
if (!vfdi_workqueue)
return -ENOMEM;
return 0;
}
void efx_fini_sriov(void)
{
destroy_workqueue(vfdi_workqueue);
}
int efx_siena_sriov_set_vf_mac(struct efx_nic *efx, int vf_i, const u8 *mac)
{
struct siena_nic_data *nic_data = efx->nic_data;
struct siena_vf *vf;
if (vf_i >= efx->vf_init_count)
return -EINVAL;
vf = nic_data->vf + vf_i;
mutex_lock(&vf->status_lock);
ether_addr_copy(vf->addr.mac_addr, mac);
__efx_siena_sriov_update_vf_addr(vf);
mutex_unlock(&vf->status_lock);
return 0;
}
int efx_siena_sriov_set_vf_vlan(struct efx_nic *efx, int vf_i,
u16 vlan, u8 qos)
{
struct siena_nic_data *nic_data = efx->nic_data;
struct siena_vf *vf;
u16 tci;
if (vf_i >= efx->vf_init_count)
return -EINVAL;
vf = nic_data->vf + vf_i;
mutex_lock(&vf->status_lock);
tci = (vlan & VLAN_VID_MASK) | ((qos & 0x7) << VLAN_PRIO_SHIFT);
vf->addr.tci = htons(tci);
__efx_siena_sriov_update_vf_addr(vf);
mutex_unlock(&vf->status_lock);
return 0;
}
int efx_siena_sriov_set_vf_spoofchk(struct efx_nic *efx, int vf_i,
bool spoofchk)
{
struct siena_nic_data *nic_data = efx->nic_data;
struct siena_vf *vf;
int rc;
if (vf_i >= efx->vf_init_count)
return -EINVAL;
vf = nic_data->vf + vf_i;
mutex_lock(&vf->txq_lock);
if (vf->txq_count == 0) {
vf->tx_filter_mode =
spoofchk ? VF_TX_FILTER_ON : VF_TX_FILTER_OFF;
rc = 0;
} else {
/* This cannot be changed while TX queues are running */
rc = -EBUSY;
}
mutex_unlock(&vf->txq_lock);
return rc;
}
int efx_siena_sriov_get_vf_config(struct efx_nic *efx, int vf_i,
struct ifla_vf_info *ivi)
{
struct siena_nic_data *nic_data = efx->nic_data;
struct siena_vf *vf;
u16 tci;
if (vf_i >= efx->vf_init_count)
return -EINVAL;
vf = nic_data->vf + vf_i;
ivi->vf = vf_i;
ether_addr_copy(ivi->mac, vf->addr.mac_addr);
ivi->max_tx_rate = 0;
ivi->min_tx_rate = 0;
tci = ntohs(vf->addr.tci);
ivi->vlan = tci & VLAN_VID_MASK;
ivi->qos = (tci >> VLAN_PRIO_SHIFT) & 0x7;
ivi->spoofchk = vf->tx_filter_mode == VF_TX_FILTER_ON;
return 0;
}
bool efx_siena_sriov_wanted(struct efx_nic *efx)
{
return efx->vf_count != 0;
}
int efx_siena_sriov_configure(struct efx_nic *efx, int num_vfs)
{
return 0;
}
|
linux-master
|
drivers/net/ethernet/sfc/siena/siena_sriov.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2009-2013 Solarflare Communications Inc.
*/
/*
* Driver for PHY related operations via MCDI.
*/
#include <linux/slab.h>
#include "efx.h"
#include "mcdi_port.h"
#include "mcdi.h"
#include "mcdi_pcol.h"
#include "nic.h"
#include "selftest.h"
#include "mcdi_port_common.h"
static int efx_mcdi_mdio_read(struct net_device *net_dev,
int prtad, int devad, u16 addr)
{
struct efx_nic *efx = netdev_priv(net_dev);
MCDI_DECLARE_BUF(inbuf, MC_CMD_MDIO_READ_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_MDIO_READ_OUT_LEN);
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, MDIO_READ_IN_BUS, efx->mdio_bus);
MCDI_SET_DWORD(inbuf, MDIO_READ_IN_PRTAD, prtad);
MCDI_SET_DWORD(inbuf, MDIO_READ_IN_DEVAD, devad);
MCDI_SET_DWORD(inbuf, MDIO_READ_IN_ADDR, addr);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_MDIO_READ, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (MCDI_DWORD(outbuf, MDIO_READ_OUT_STATUS) !=
MC_CMD_MDIO_STATUS_GOOD)
return -EIO;
return (u16)MCDI_DWORD(outbuf, MDIO_READ_OUT_VALUE);
}
static int efx_mcdi_mdio_write(struct net_device *net_dev,
int prtad, int devad, u16 addr, u16 value)
{
struct efx_nic *efx = netdev_priv(net_dev);
MCDI_DECLARE_BUF(inbuf, MC_CMD_MDIO_WRITE_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_MDIO_WRITE_OUT_LEN);
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, MDIO_WRITE_IN_BUS, efx->mdio_bus);
MCDI_SET_DWORD(inbuf, MDIO_WRITE_IN_PRTAD, prtad);
MCDI_SET_DWORD(inbuf, MDIO_WRITE_IN_DEVAD, devad);
MCDI_SET_DWORD(inbuf, MDIO_WRITE_IN_ADDR, addr);
MCDI_SET_DWORD(inbuf, MDIO_WRITE_IN_VALUE, value);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_MDIO_WRITE, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (MCDI_DWORD(outbuf, MDIO_WRITE_OUT_STATUS) !=
MC_CMD_MDIO_STATUS_GOOD)
return -EIO;
return 0;
}
bool efx_siena_mcdi_mac_check_fault(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_LINK_OUT_LEN);
size_t outlength;
int rc;
BUILD_BUG_ON(MC_CMD_GET_LINK_IN_LEN != 0);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_GET_LINK, NULL, 0,
outbuf, sizeof(outbuf), &outlength);
if (rc)
return true;
return MCDI_DWORD(outbuf, GET_LINK_OUT_MAC_FAULT) != 0;
}
int efx_siena_mcdi_port_probe(struct efx_nic *efx)
{
int rc;
/* Set up MDIO structure for PHY */
efx->mdio.mode_support = MDIO_SUPPORTS_C45 | MDIO_EMULATE_C22;
efx->mdio.mdio_read = efx_mcdi_mdio_read;
efx->mdio.mdio_write = efx_mcdi_mdio_write;
/* Fill out MDIO structure, loopback modes, and initial link state */
rc = efx_siena_mcdi_phy_probe(efx);
if (rc != 0)
return rc;
return efx_siena_mcdi_mac_init_stats(efx);
}
void efx_siena_mcdi_port_remove(struct efx_nic *efx)
{
efx_siena_mcdi_phy_remove(efx);
efx_siena_mcdi_mac_fini_stats(efx);
}
|
linux-master
|
drivers/net/ethernet/sfc/siena/mcdi_port.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2008-2013 Solarflare Communications Inc.
*/
#include <linux/delay.h>
#include <linux/moduleparam.h>
#include <linux/atomic.h>
#include "net_driver.h"
#include "nic.h"
#include "io.h"
#include "farch_regs.h"
#include "mcdi_pcol.h"
/**************************************************************************
*
* Management-Controller-to-Driver Interface
*
**************************************************************************
*/
#define MCDI_RPC_TIMEOUT (10 * HZ)
/* A reboot/assertion causes the MCDI status word to be set after the
* command word is set or a REBOOT event is sent. If we notice a reboot
* via these mechanisms then wait 250ms for the status word to be set.
*/
#define MCDI_STATUS_DELAY_US 100
#define MCDI_STATUS_DELAY_COUNT 2500
#define MCDI_STATUS_SLEEP_MS \
(MCDI_STATUS_DELAY_US * MCDI_STATUS_DELAY_COUNT / 1000)
#define SEQ_MASK \
EFX_MASK32(EFX_WIDTH(MCDI_HEADER_SEQ))
struct efx_mcdi_async_param {
struct list_head list;
unsigned int cmd;
size_t inlen;
size_t outlen;
bool quiet;
efx_mcdi_async_completer *complete;
unsigned long cookie;
/* followed by request/response buffer */
};
static void efx_mcdi_timeout_async(struct timer_list *t);
static int efx_mcdi_drv_attach(struct efx_nic *efx, bool driver_operating,
bool *was_attached_out);
static bool efx_mcdi_poll_once(struct efx_nic *efx);
static void efx_mcdi_abandon(struct efx_nic *efx);
#ifdef CONFIG_SFC_SIENA_MCDI_LOGGING
static bool efx_siena_mcdi_logging_default;
module_param_named(mcdi_logging_default, efx_siena_mcdi_logging_default,
bool, 0644);
MODULE_PARM_DESC(mcdi_logging_default,
"Enable MCDI logging on newly-probed functions");
#endif
int efx_siena_mcdi_init(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi;
bool already_attached;
int rc = -ENOMEM;
efx->mcdi = kzalloc(sizeof(*efx->mcdi), GFP_KERNEL);
if (!efx->mcdi)
goto fail;
mcdi = efx_mcdi(efx);
mcdi->efx = efx;
#ifdef CONFIG_SFC_SIENA_MCDI_LOGGING
/* consuming code assumes buffer is page-sized */
mcdi->logging_buffer = (char *)__get_free_page(GFP_KERNEL);
if (!mcdi->logging_buffer)
goto fail1;
mcdi->logging_enabled = efx_siena_mcdi_logging_default;
#endif
init_waitqueue_head(&mcdi->wq);
init_waitqueue_head(&mcdi->proxy_rx_wq);
spin_lock_init(&mcdi->iface_lock);
mcdi->state = MCDI_STATE_QUIESCENT;
mcdi->mode = MCDI_MODE_POLL;
spin_lock_init(&mcdi->async_lock);
INIT_LIST_HEAD(&mcdi->async_list);
timer_setup(&mcdi->async_timer, efx_mcdi_timeout_async, 0);
(void)efx_siena_mcdi_poll_reboot(efx);
mcdi->new_epoch = true;
/* Recover from a failed assertion before probing */
rc = efx_siena_mcdi_handle_assertion(efx);
if (rc)
goto fail2;
/* Let the MC (and BMC, if this is a LOM) know that the driver
* is loaded. We should do this before we reset the NIC.
*/
rc = efx_mcdi_drv_attach(efx, true, &already_attached);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"Unable to register driver with MCPU\n");
goto fail2;
}
if (already_attached)
/* Not a fatal error */
netif_err(efx, probe, efx->net_dev,
"Host already registered with MCPU\n");
if (efx->mcdi->fn_flags &
(1 << MC_CMD_DRV_ATTACH_EXT_OUT_FLAG_PRIMARY))
efx->primary = efx;
return 0;
fail2:
#ifdef CONFIG_SFC_SIENA_MCDI_LOGGING
free_page((unsigned long)mcdi->logging_buffer);
fail1:
#endif
kfree(efx->mcdi);
efx->mcdi = NULL;
fail:
return rc;
}
void efx_siena_mcdi_detach(struct efx_nic *efx)
{
if (!efx->mcdi)
return;
BUG_ON(efx->mcdi->iface.state != MCDI_STATE_QUIESCENT);
/* Relinquish the device (back to the BMC, if this is a LOM) */
efx_mcdi_drv_attach(efx, false, NULL);
}
void efx_siena_mcdi_fini(struct efx_nic *efx)
{
if (!efx->mcdi)
return;
#ifdef CONFIG_SFC_SIENA_MCDI_LOGGING
free_page((unsigned long)efx->mcdi->iface.logging_buffer);
#endif
kfree(efx->mcdi);
}
static void efx_mcdi_send_request(struct efx_nic *efx, unsigned cmd,
const efx_dword_t *inbuf, size_t inlen)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
#ifdef CONFIG_SFC_SIENA_MCDI_LOGGING
char *buf = mcdi->logging_buffer; /* page-sized */
#endif
efx_dword_t hdr[2];
size_t hdr_len;
u32 xflags, seqno;
BUG_ON(mcdi->state == MCDI_STATE_QUIESCENT);
/* Serialise with efx_mcdi_ev_cpl() and efx_mcdi_ev_death() */
spin_lock_bh(&mcdi->iface_lock);
++mcdi->seqno;
seqno = mcdi->seqno & SEQ_MASK;
spin_unlock_bh(&mcdi->iface_lock);
xflags = 0;
if (mcdi->mode == MCDI_MODE_EVENTS)
xflags |= MCDI_HEADER_XFLAGS_EVREQ;
if (efx->type->mcdi_max_ver == 1) {
/* MCDI v1 */
EFX_POPULATE_DWORD_7(hdr[0],
MCDI_HEADER_RESPONSE, 0,
MCDI_HEADER_RESYNC, 1,
MCDI_HEADER_CODE, cmd,
MCDI_HEADER_DATALEN, inlen,
MCDI_HEADER_SEQ, seqno,
MCDI_HEADER_XFLAGS, xflags,
MCDI_HEADER_NOT_EPOCH, !mcdi->new_epoch);
hdr_len = 4;
} else {
/* MCDI v2 */
BUG_ON(inlen > MCDI_CTL_SDU_LEN_MAX_V2);
EFX_POPULATE_DWORD_7(hdr[0],
MCDI_HEADER_RESPONSE, 0,
MCDI_HEADER_RESYNC, 1,
MCDI_HEADER_CODE, MC_CMD_V2_EXTN,
MCDI_HEADER_DATALEN, 0,
MCDI_HEADER_SEQ, seqno,
MCDI_HEADER_XFLAGS, xflags,
MCDI_HEADER_NOT_EPOCH, !mcdi->new_epoch);
EFX_POPULATE_DWORD_2(hdr[1],
MC_CMD_V2_EXTN_IN_EXTENDED_CMD, cmd,
MC_CMD_V2_EXTN_IN_ACTUAL_LEN, inlen);
hdr_len = 8;
}
#ifdef CONFIG_SFC_SIENA_MCDI_LOGGING
if (mcdi->logging_enabled && !WARN_ON_ONCE(!buf)) {
int bytes = 0;
int i;
/* Lengths should always be a whole number of dwords, so scream
* if they're not.
*/
WARN_ON_ONCE(hdr_len % 4);
WARN_ON_ONCE(inlen % 4);
/* We own the logging buffer, as only one MCDI can be in
* progress on a NIC at any one time. So no need for locking.
*/
for (i = 0; i < hdr_len / 4 && bytes < PAGE_SIZE; i++)
bytes += scnprintf(buf + bytes, PAGE_SIZE - bytes,
" %08x",
le32_to_cpu(hdr[i].u32[0]));
for (i = 0; i < inlen / 4 && bytes < PAGE_SIZE; i++)
bytes += scnprintf(buf + bytes, PAGE_SIZE - bytes,
" %08x",
le32_to_cpu(inbuf[i].u32[0]));
netif_info(efx, hw, efx->net_dev, "MCDI RPC REQ:%s\n", buf);
}
#endif
efx->type->mcdi_request(efx, hdr, hdr_len, inbuf, inlen);
mcdi->new_epoch = false;
}
static int efx_mcdi_errno(unsigned int mcdi_err)
{
switch (mcdi_err) {
case 0:
return 0;
#define TRANSLATE_ERROR(name) \
case MC_CMD_ERR_ ## name: \
return -name;
TRANSLATE_ERROR(EPERM);
TRANSLATE_ERROR(ENOENT);
TRANSLATE_ERROR(EINTR);
TRANSLATE_ERROR(EAGAIN);
TRANSLATE_ERROR(EACCES);
TRANSLATE_ERROR(EBUSY);
TRANSLATE_ERROR(EINVAL);
TRANSLATE_ERROR(EDEADLK);
TRANSLATE_ERROR(ENOSYS);
TRANSLATE_ERROR(ETIME);
TRANSLATE_ERROR(EALREADY);
TRANSLATE_ERROR(ENOSPC);
#undef TRANSLATE_ERROR
case MC_CMD_ERR_ENOTSUP:
return -EOPNOTSUPP;
case MC_CMD_ERR_ALLOC_FAIL:
return -ENOBUFS;
case MC_CMD_ERR_MAC_EXIST:
return -EADDRINUSE;
default:
return -EPROTO;
}
}
static void efx_mcdi_read_response_header(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
unsigned int respseq, respcmd, error;
#ifdef CONFIG_SFC_SIENA_MCDI_LOGGING
char *buf = mcdi->logging_buffer; /* page-sized */
#endif
efx_dword_t hdr;
efx->type->mcdi_read_response(efx, &hdr, 0, 4);
respseq = EFX_DWORD_FIELD(hdr, MCDI_HEADER_SEQ);
respcmd = EFX_DWORD_FIELD(hdr, MCDI_HEADER_CODE);
error = EFX_DWORD_FIELD(hdr, MCDI_HEADER_ERROR);
if (respcmd != MC_CMD_V2_EXTN) {
mcdi->resp_hdr_len = 4;
mcdi->resp_data_len = EFX_DWORD_FIELD(hdr, MCDI_HEADER_DATALEN);
} else {
efx->type->mcdi_read_response(efx, &hdr, 4, 4);
mcdi->resp_hdr_len = 8;
mcdi->resp_data_len =
EFX_DWORD_FIELD(hdr, MC_CMD_V2_EXTN_IN_ACTUAL_LEN);
}
#ifdef CONFIG_SFC_SIENA_MCDI_LOGGING
if (mcdi->logging_enabled && !WARN_ON_ONCE(!buf)) {
size_t hdr_len, data_len;
int bytes = 0;
int i;
WARN_ON_ONCE(mcdi->resp_hdr_len % 4);
hdr_len = mcdi->resp_hdr_len / 4;
/* MCDI_DECLARE_BUF ensures that underlying buffer is padded
* to dword size, and the MCDI buffer is always dword size
*/
data_len = DIV_ROUND_UP(mcdi->resp_data_len, 4);
/* We own the logging buffer, as only one MCDI can be in
* progress on a NIC at any one time. So no need for locking.
*/
for (i = 0; i < hdr_len && bytes < PAGE_SIZE; i++) {
efx->type->mcdi_read_response(efx, &hdr, (i * 4), 4);
bytes += scnprintf(buf + bytes, PAGE_SIZE - bytes,
" %08x", le32_to_cpu(hdr.u32[0]));
}
for (i = 0; i < data_len && bytes < PAGE_SIZE; i++) {
efx->type->mcdi_read_response(efx, &hdr,
mcdi->resp_hdr_len + (i * 4), 4);
bytes += scnprintf(buf + bytes, PAGE_SIZE - bytes,
" %08x", le32_to_cpu(hdr.u32[0]));
}
netif_info(efx, hw, efx->net_dev, "MCDI RPC RESP:%s\n", buf);
}
#endif
mcdi->resprc_raw = 0;
if (error && mcdi->resp_data_len == 0) {
netif_err(efx, hw, efx->net_dev, "MC rebooted\n");
mcdi->resprc = -EIO;
} else if ((respseq ^ mcdi->seqno) & SEQ_MASK) {
netif_err(efx, hw, efx->net_dev,
"MC response mismatch tx seq 0x%x rx seq 0x%x\n",
respseq, mcdi->seqno);
mcdi->resprc = -EIO;
} else if (error) {
efx->type->mcdi_read_response(efx, &hdr, mcdi->resp_hdr_len, 4);
mcdi->resprc_raw = EFX_DWORD_FIELD(hdr, EFX_DWORD_0);
mcdi->resprc = efx_mcdi_errno(mcdi->resprc_raw);
} else {
mcdi->resprc = 0;
}
}
static bool efx_mcdi_poll_once(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
rmb();
if (!efx->type->mcdi_poll_response(efx))
return false;
spin_lock_bh(&mcdi->iface_lock);
efx_mcdi_read_response_header(efx);
spin_unlock_bh(&mcdi->iface_lock);
return true;
}
static int efx_mcdi_poll(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
unsigned long time, finish;
unsigned int spins;
int rc;
/* Check for a reboot atomically with respect to efx_mcdi_copyout() */
rc = efx_siena_mcdi_poll_reboot(efx);
if (rc) {
spin_lock_bh(&mcdi->iface_lock);
mcdi->resprc = rc;
mcdi->resp_hdr_len = 0;
mcdi->resp_data_len = 0;
spin_unlock_bh(&mcdi->iface_lock);
return 0;
}
/* Poll for completion. Poll quickly (once a us) for the 1st jiffy,
* because generally mcdi responses are fast. After that, back off
* and poll once a jiffy (approximately)
*/
spins = USER_TICK_USEC;
finish = jiffies + MCDI_RPC_TIMEOUT;
while (1) {
if (spins != 0) {
--spins;
udelay(1);
} else {
schedule_timeout_uninterruptible(1);
}
time = jiffies;
if (efx_mcdi_poll_once(efx))
break;
if (time_after(time, finish))
return -ETIMEDOUT;
}
/* Return rc=0 like wait_event_timeout() */
return 0;
}
/* Test and clear MC-rebooted flag for this port/function; reset
* software state as necessary.
*/
int efx_siena_mcdi_poll_reboot(struct efx_nic *efx)
{
if (!efx->mcdi)
return 0;
return efx->type->mcdi_poll_reboot(efx);
}
static bool efx_mcdi_acquire_async(struct efx_mcdi_iface *mcdi)
{
return cmpxchg(&mcdi->state,
MCDI_STATE_QUIESCENT, MCDI_STATE_RUNNING_ASYNC) ==
MCDI_STATE_QUIESCENT;
}
static void efx_mcdi_acquire_sync(struct efx_mcdi_iface *mcdi)
{
/* Wait until the interface becomes QUIESCENT and we win the race
* to mark it RUNNING_SYNC.
*/
wait_event(mcdi->wq,
cmpxchg(&mcdi->state,
MCDI_STATE_QUIESCENT, MCDI_STATE_RUNNING_SYNC) ==
MCDI_STATE_QUIESCENT);
}
static int efx_mcdi_await_completion(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
if (wait_event_timeout(mcdi->wq, mcdi->state == MCDI_STATE_COMPLETED,
MCDI_RPC_TIMEOUT) == 0)
return -ETIMEDOUT;
/* Check if efx_mcdi_set_mode() switched us back to polled completions.
* In which case, poll for completions directly. If efx_mcdi_ev_cpl()
* completed the request first, then we'll just end up completing the
* request again, which is safe.
*
* We need an smp_rmb() to synchronise with efx_siena_mcdi_mode_poll(), which
* wait_event_timeout() implicitly provides.
*/
if (mcdi->mode == MCDI_MODE_POLL)
return efx_mcdi_poll(efx);
return 0;
}
/* If the interface is RUNNING_SYNC, switch to COMPLETED and wake the
* requester. Return whether this was done. Does not take any locks.
*/
static bool efx_mcdi_complete_sync(struct efx_mcdi_iface *mcdi)
{
if (cmpxchg(&mcdi->state,
MCDI_STATE_RUNNING_SYNC, MCDI_STATE_COMPLETED) ==
MCDI_STATE_RUNNING_SYNC) {
wake_up(&mcdi->wq);
return true;
}
return false;
}
static void efx_mcdi_release(struct efx_mcdi_iface *mcdi)
{
if (mcdi->mode == MCDI_MODE_EVENTS) {
struct efx_mcdi_async_param *async;
struct efx_nic *efx = mcdi->efx;
/* Process the asynchronous request queue */
spin_lock_bh(&mcdi->async_lock);
async = list_first_entry_or_null(
&mcdi->async_list, struct efx_mcdi_async_param, list);
if (async) {
mcdi->state = MCDI_STATE_RUNNING_ASYNC;
efx_mcdi_send_request(efx, async->cmd,
(const efx_dword_t *)(async + 1),
async->inlen);
mod_timer(&mcdi->async_timer,
jiffies + MCDI_RPC_TIMEOUT);
}
spin_unlock_bh(&mcdi->async_lock);
if (async)
return;
}
mcdi->state = MCDI_STATE_QUIESCENT;
wake_up(&mcdi->wq);
}
/* If the interface is RUNNING_ASYNC, switch to COMPLETED, call the
* asynchronous completion function, and release the interface.
* Return whether this was done. Must be called in bh-disabled
* context. Will take iface_lock and async_lock.
*/
static bool efx_mcdi_complete_async(struct efx_mcdi_iface *mcdi, bool timeout)
{
struct efx_nic *efx = mcdi->efx;
struct efx_mcdi_async_param *async;
size_t hdr_len, data_len, err_len;
efx_dword_t *outbuf;
MCDI_DECLARE_BUF_ERR(errbuf);
int rc;
if (cmpxchg(&mcdi->state,
MCDI_STATE_RUNNING_ASYNC, MCDI_STATE_COMPLETED) !=
MCDI_STATE_RUNNING_ASYNC)
return false;
spin_lock(&mcdi->iface_lock);
if (timeout) {
/* Ensure that if the completion event arrives later,
* the seqno check in efx_mcdi_ev_cpl() will fail
*/
++mcdi->seqno;
++mcdi->credits;
rc = -ETIMEDOUT;
hdr_len = 0;
data_len = 0;
} else {
rc = mcdi->resprc;
hdr_len = mcdi->resp_hdr_len;
data_len = mcdi->resp_data_len;
}
spin_unlock(&mcdi->iface_lock);
/* Stop the timer. In case the timer function is running, we
* must wait for it to return so that there is no possibility
* of it aborting the next request.
*/
if (!timeout)
del_timer_sync(&mcdi->async_timer);
spin_lock(&mcdi->async_lock);
async = list_first_entry(&mcdi->async_list,
struct efx_mcdi_async_param, list);
list_del(&async->list);
spin_unlock(&mcdi->async_lock);
outbuf = (efx_dword_t *)(async + 1);
efx->type->mcdi_read_response(efx, outbuf, hdr_len,
min(async->outlen, data_len));
if (!timeout && rc && !async->quiet) {
err_len = min(sizeof(errbuf), data_len);
efx->type->mcdi_read_response(efx, errbuf, hdr_len,
sizeof(errbuf));
efx_siena_mcdi_display_error(efx, async->cmd, async->inlen,
errbuf, err_len, rc);
}
if (async->complete)
async->complete(efx, async->cookie, rc, outbuf,
min(async->outlen, data_len));
kfree(async);
efx_mcdi_release(mcdi);
return true;
}
static void efx_mcdi_ev_cpl(struct efx_nic *efx, unsigned int seqno,
unsigned int datalen, unsigned int mcdi_err)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
bool wake = false;
spin_lock(&mcdi->iface_lock);
if ((seqno ^ mcdi->seqno) & SEQ_MASK) {
if (mcdi->credits)
/* The request has been cancelled */
--mcdi->credits;
else
netif_err(efx, hw, efx->net_dev,
"MC response mismatch tx seq 0x%x rx "
"seq 0x%x\n", seqno, mcdi->seqno);
} else {
if (efx->type->mcdi_max_ver >= 2) {
/* MCDI v2 responses don't fit in an event */
efx_mcdi_read_response_header(efx);
} else {
mcdi->resprc = efx_mcdi_errno(mcdi_err);
mcdi->resp_hdr_len = 4;
mcdi->resp_data_len = datalen;
}
wake = true;
}
spin_unlock(&mcdi->iface_lock);
if (wake) {
if (!efx_mcdi_complete_async(mcdi, false))
(void) efx_mcdi_complete_sync(mcdi);
/* If the interface isn't RUNNING_ASYNC or
* RUNNING_SYNC then we've received a duplicate
* completion after we've already transitioned back to
* QUIESCENT. [A subsequent invocation would increment
* seqno, so would have failed the seqno check].
*/
}
}
static void efx_mcdi_timeout_async(struct timer_list *t)
{
struct efx_mcdi_iface *mcdi = from_timer(mcdi, t, async_timer);
efx_mcdi_complete_async(mcdi, true);
}
static int
efx_mcdi_check_supported(struct efx_nic *efx, unsigned int cmd, size_t inlen)
{
if (efx->type->mcdi_max_ver < 0 ||
(efx->type->mcdi_max_ver < 2 &&
cmd > MC_CMD_CMD_SPACE_ESCAPE_7))
return -EINVAL;
if (inlen > MCDI_CTL_SDU_LEN_MAX_V2 ||
(efx->type->mcdi_max_ver < 2 &&
inlen > MCDI_CTL_SDU_LEN_MAX_V1))
return -EMSGSIZE;
return 0;
}
static bool efx_mcdi_get_proxy_handle(struct efx_nic *efx,
size_t hdr_len, size_t data_len,
u32 *proxy_handle)
{
MCDI_DECLARE_BUF_ERR(testbuf);
const size_t buflen = sizeof(testbuf);
if (!proxy_handle || data_len < buflen)
return false;
efx->type->mcdi_read_response(efx, testbuf, hdr_len, buflen);
if (MCDI_DWORD(testbuf, ERR_CODE) == MC_CMD_ERR_PROXY_PENDING) {
*proxy_handle = MCDI_DWORD(testbuf, ERR_PROXY_PENDING_HANDLE);
return true;
}
return false;
}
static int _efx_mcdi_rpc_finish(struct efx_nic *efx, unsigned int cmd,
size_t inlen,
efx_dword_t *outbuf, size_t outlen,
size_t *outlen_actual, bool quiet,
u32 *proxy_handle, int *raw_rc)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
MCDI_DECLARE_BUF_ERR(errbuf);
int rc;
if (mcdi->mode == MCDI_MODE_POLL)
rc = efx_mcdi_poll(efx);
else
rc = efx_mcdi_await_completion(efx);
if (rc != 0) {
netif_err(efx, hw, efx->net_dev,
"MC command 0x%x inlen %d mode %d timed out\n",
cmd, (int)inlen, mcdi->mode);
if (mcdi->mode == MCDI_MODE_EVENTS && efx_mcdi_poll_once(efx)) {
netif_err(efx, hw, efx->net_dev,
"MCDI request was completed without an event\n");
rc = 0;
}
efx_mcdi_abandon(efx);
/* Close the race with efx_mcdi_ev_cpl() executing just too late
* and completing a request we've just cancelled, by ensuring
* that the seqno check therein fails.
*/
spin_lock_bh(&mcdi->iface_lock);
++mcdi->seqno;
++mcdi->credits;
spin_unlock_bh(&mcdi->iface_lock);
}
if (proxy_handle)
*proxy_handle = 0;
if (rc != 0) {
if (outlen_actual)
*outlen_actual = 0;
} else {
size_t hdr_len, data_len, err_len;
/* At the very least we need a memory barrier here to ensure
* we pick up changes from efx_mcdi_ev_cpl(). Protect against
* a spurious efx_mcdi_ev_cpl() running concurrently by
* acquiring the iface_lock. */
spin_lock_bh(&mcdi->iface_lock);
rc = mcdi->resprc;
if (raw_rc)
*raw_rc = mcdi->resprc_raw;
hdr_len = mcdi->resp_hdr_len;
data_len = mcdi->resp_data_len;
err_len = min(sizeof(errbuf), data_len);
spin_unlock_bh(&mcdi->iface_lock);
BUG_ON(rc > 0);
efx->type->mcdi_read_response(efx, outbuf, hdr_len,
min(outlen, data_len));
if (outlen_actual)
*outlen_actual = data_len;
efx->type->mcdi_read_response(efx, errbuf, hdr_len, err_len);
if (cmd == MC_CMD_REBOOT && rc == -EIO) {
/* Don't reset if MC_CMD_REBOOT returns EIO */
} else if (rc == -EIO || rc == -EINTR) {
netif_err(efx, hw, efx->net_dev, "MC reboot detected\n");
netif_dbg(efx, hw, efx->net_dev, "MC rebooted during command %d rc %d\n",
cmd, -rc);
if (efx->type->mcdi_reboot_detected)
efx->type->mcdi_reboot_detected(efx);
efx_siena_schedule_reset(efx, RESET_TYPE_MC_FAILURE);
} else if (proxy_handle && (rc == -EPROTO) &&
efx_mcdi_get_proxy_handle(efx, hdr_len, data_len,
proxy_handle)) {
mcdi->proxy_rx_status = 0;
mcdi->proxy_rx_handle = 0;
mcdi->state = MCDI_STATE_PROXY_WAIT;
} else if (rc && !quiet) {
efx_siena_mcdi_display_error(efx, cmd, inlen, errbuf,
err_len, rc);
}
if (rc == -EIO || rc == -EINTR) {
msleep(MCDI_STATUS_SLEEP_MS);
efx_siena_mcdi_poll_reboot(efx);
mcdi->new_epoch = true;
}
}
if (!proxy_handle || !*proxy_handle)
efx_mcdi_release(mcdi);
return rc;
}
static void efx_mcdi_proxy_abort(struct efx_mcdi_iface *mcdi)
{
if (mcdi->state == MCDI_STATE_PROXY_WAIT) {
/* Interrupt the proxy wait. */
mcdi->proxy_rx_status = -EINTR;
wake_up(&mcdi->proxy_rx_wq);
}
}
static void efx_mcdi_ev_proxy_response(struct efx_nic *efx,
u32 handle, int status)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
WARN_ON(mcdi->state != MCDI_STATE_PROXY_WAIT);
mcdi->proxy_rx_status = efx_mcdi_errno(status);
/* Ensure the status is written before we update the handle, since the
* latter is used to check if we've finished.
*/
wmb();
mcdi->proxy_rx_handle = handle;
wake_up(&mcdi->proxy_rx_wq);
}
static int efx_mcdi_proxy_wait(struct efx_nic *efx, u32 handle, bool quiet)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
int rc;
/* Wait for a proxy event, or timeout. */
rc = wait_event_timeout(mcdi->proxy_rx_wq,
mcdi->proxy_rx_handle != 0 ||
mcdi->proxy_rx_status == -EINTR,
MCDI_RPC_TIMEOUT);
if (rc <= 0) {
netif_dbg(efx, hw, efx->net_dev,
"MCDI proxy timeout %d\n", handle);
return -ETIMEDOUT;
} else if (mcdi->proxy_rx_handle != handle) {
netif_warn(efx, hw, efx->net_dev,
"MCDI proxy unexpected handle %d (expected %d)\n",
mcdi->proxy_rx_handle, handle);
return -EINVAL;
}
return mcdi->proxy_rx_status;
}
static int _efx_mcdi_rpc(struct efx_nic *efx, unsigned int cmd,
const efx_dword_t *inbuf, size_t inlen,
efx_dword_t *outbuf, size_t outlen,
size_t *outlen_actual, bool quiet, int *raw_rc)
{
u32 proxy_handle = 0; /* Zero is an invalid proxy handle. */
int rc;
if (inbuf && inlen && (inbuf == outbuf)) {
/* The input buffer can't be aliased with the output. */
WARN_ON(1);
return -EINVAL;
}
rc = efx_siena_mcdi_rpc_start(efx, cmd, inbuf, inlen);
if (rc)
return rc;
rc = _efx_mcdi_rpc_finish(efx, cmd, inlen, outbuf, outlen,
outlen_actual, quiet, &proxy_handle, raw_rc);
if (proxy_handle) {
/* Handle proxy authorisation. This allows approval of MCDI
* operations to be delegated to the admin function, allowing
* fine control over (eg) multicast subscriptions.
*/
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
netif_dbg(efx, hw, efx->net_dev,
"MCDI waiting for proxy auth %d\n",
proxy_handle);
rc = efx_mcdi_proxy_wait(efx, proxy_handle, quiet);
if (rc == 0) {
netif_dbg(efx, hw, efx->net_dev,
"MCDI proxy retry %d\n", proxy_handle);
/* We now retry the original request. */
mcdi->state = MCDI_STATE_RUNNING_SYNC;
efx_mcdi_send_request(efx, cmd, inbuf, inlen);
rc = _efx_mcdi_rpc_finish(efx, cmd, inlen,
outbuf, outlen, outlen_actual,
quiet, NULL, raw_rc);
} else {
netif_cond_dbg(efx, hw, efx->net_dev, rc == -EPERM, err,
"MC command 0x%x failed after proxy auth rc=%d\n",
cmd, rc);
if (rc == -EINTR || rc == -EIO)
efx_siena_schedule_reset(efx, RESET_TYPE_MC_FAILURE);
efx_mcdi_release(mcdi);
}
}
return rc;
}
static int _efx_mcdi_rpc_evb_retry(struct efx_nic *efx, unsigned cmd,
const efx_dword_t *inbuf, size_t inlen,
efx_dword_t *outbuf, size_t outlen,
size_t *outlen_actual, bool quiet)
{
int raw_rc = 0;
int rc;
rc = _efx_mcdi_rpc(efx, cmd, inbuf, inlen,
outbuf, outlen, outlen_actual, true, &raw_rc);
if ((rc == -EPROTO) && (raw_rc == MC_CMD_ERR_NO_EVB_PORT) &&
efx->type->is_vf) {
/* If the EVB port isn't available within a VF this may
* mean the PF is still bringing the switch up. We should
* retry our request shortly.
*/
unsigned long abort_time = jiffies + MCDI_RPC_TIMEOUT;
unsigned int delay_us = 10000;
netif_dbg(efx, hw, efx->net_dev,
"%s: NO_EVB_PORT; will retry request\n",
__func__);
do {
usleep_range(delay_us, delay_us + 10000);
rc = _efx_mcdi_rpc(efx, cmd, inbuf, inlen,
outbuf, outlen, outlen_actual,
true, &raw_rc);
if (delay_us < 100000)
delay_us <<= 1;
} while ((rc == -EPROTO) &&
(raw_rc == MC_CMD_ERR_NO_EVB_PORT) &&
time_before(jiffies, abort_time));
}
if (rc && !quiet && !(cmd == MC_CMD_REBOOT && rc == -EIO))
efx_siena_mcdi_display_error(efx, cmd, inlen,
outbuf, outlen, rc);
return rc;
}
/**
* efx_siena_mcdi_rpc - Issue an MCDI command and wait for completion
* @efx: NIC through which to issue the command
* @cmd: Command type number
* @inbuf: Command parameters
* @inlen: Length of command parameters, in bytes. Must be a multiple
* of 4 and no greater than %MCDI_CTL_SDU_LEN_MAX_V1.
* @outbuf: Response buffer. May be %NULL if @outlen is 0.
* @outlen: Length of response buffer, in bytes. If the actual
* response is longer than @outlen & ~3, it will be truncated
* to that length.
* @outlen_actual: Pointer through which to return the actual response
* length. May be %NULL if this is not needed.
*
* This function may sleep and therefore must be called in an appropriate
* context.
*
* Return: A negative error code, or zero if successful. The error
* code may come from the MCDI response or may indicate a failure
* to communicate with the MC. In the former case, the response
* will still be copied to @outbuf and *@outlen_actual will be
* set accordingly. In the latter case, *@outlen_actual will be
* set to zero.
*/
int efx_siena_mcdi_rpc(struct efx_nic *efx, unsigned int cmd,
const efx_dword_t *inbuf, size_t inlen,
efx_dword_t *outbuf, size_t outlen,
size_t *outlen_actual)
{
return _efx_mcdi_rpc_evb_retry(efx, cmd, inbuf, inlen, outbuf, outlen,
outlen_actual, false);
}
/* Normally, on receiving an error code in the MCDI response,
* efx_siena_mcdi_rpc will log an error message containing (among other
* things) the raw error code, by means of efx_siena_mcdi_display_error.
* This _quiet version suppresses that; if the caller wishes to log
* the error conditionally on the return code, it should call this
* function and is then responsible for calling efx_siena_mcdi_display_error
* as needed.
*/
int efx_siena_mcdi_rpc_quiet(struct efx_nic *efx, unsigned int cmd,
const efx_dword_t *inbuf, size_t inlen,
efx_dword_t *outbuf, size_t outlen,
size_t *outlen_actual)
{
return _efx_mcdi_rpc_evb_retry(efx, cmd, inbuf, inlen, outbuf, outlen,
outlen_actual, true);
}
int efx_siena_mcdi_rpc_start(struct efx_nic *efx, unsigned int cmd,
const efx_dword_t *inbuf, size_t inlen)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
int rc;
rc = efx_mcdi_check_supported(efx, cmd, inlen);
if (rc)
return rc;
if (efx->mc_bist_for_other_fn)
return -ENETDOWN;
if (mcdi->mode == MCDI_MODE_FAIL)
return -ENETDOWN;
efx_mcdi_acquire_sync(mcdi);
efx_mcdi_send_request(efx, cmd, inbuf, inlen);
return 0;
}
static int _efx_mcdi_rpc_async(struct efx_nic *efx, unsigned int cmd,
const efx_dword_t *inbuf, size_t inlen,
size_t outlen,
efx_mcdi_async_completer *complete,
unsigned long cookie, bool quiet)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
struct efx_mcdi_async_param *async;
int rc;
rc = efx_mcdi_check_supported(efx, cmd, inlen);
if (rc)
return rc;
if (efx->mc_bist_for_other_fn)
return -ENETDOWN;
async = kmalloc(sizeof(*async) + ALIGN(max(inlen, outlen), 4),
GFP_ATOMIC);
if (!async)
return -ENOMEM;
async->cmd = cmd;
async->inlen = inlen;
async->outlen = outlen;
async->quiet = quiet;
async->complete = complete;
async->cookie = cookie;
memcpy(async + 1, inbuf, inlen);
spin_lock_bh(&mcdi->async_lock);
if (mcdi->mode == MCDI_MODE_EVENTS) {
list_add_tail(&async->list, &mcdi->async_list);
/* If this is at the front of the queue, try to start it
* immediately
*/
if (mcdi->async_list.next == &async->list &&
efx_mcdi_acquire_async(mcdi)) {
efx_mcdi_send_request(efx, cmd, inbuf, inlen);
mod_timer(&mcdi->async_timer,
jiffies + MCDI_RPC_TIMEOUT);
}
} else {
kfree(async);
rc = -ENETDOWN;
}
spin_unlock_bh(&mcdi->async_lock);
return rc;
}
/**
* efx_siena_mcdi_rpc_async - Schedule an MCDI command to run asynchronously
* @efx: NIC through which to issue the command
* @cmd: Command type number
* @inbuf: Command parameters
* @inlen: Length of command parameters, in bytes
* @outlen: Length to allocate for response buffer, in bytes
* @complete: Function to be called on completion or cancellation.
* @cookie: Arbitrary value to be passed to @complete.
*
* This function does not sleep and therefore may be called in atomic
* context. It will fail if event queues are disabled or if MCDI
* event completions have been disabled due to an error.
*
* If it succeeds, the @complete function will be called exactly once
* in atomic context, when one of the following occurs:
* (a) the completion event is received (in NAPI context)
* (b) event queues are disabled (in the process that disables them)
* (c) the request times-out (in timer context)
*/
int
efx_siena_mcdi_rpc_async(struct efx_nic *efx, unsigned int cmd,
const efx_dword_t *inbuf, size_t inlen, size_t outlen,
efx_mcdi_async_completer *complete,
unsigned long cookie)
{
return _efx_mcdi_rpc_async(efx, cmd, inbuf, inlen, outlen, complete,
cookie, false);
}
int efx_siena_mcdi_rpc_async_quiet(struct efx_nic *efx, unsigned int cmd,
const efx_dword_t *inbuf, size_t inlen,
size_t outlen,
efx_mcdi_async_completer *complete,
unsigned long cookie)
{
return _efx_mcdi_rpc_async(efx, cmd, inbuf, inlen, outlen, complete,
cookie, true);
}
int efx_siena_mcdi_rpc_finish(struct efx_nic *efx, unsigned int cmd,
size_t inlen, efx_dword_t *outbuf, size_t outlen,
size_t *outlen_actual)
{
return _efx_mcdi_rpc_finish(efx, cmd, inlen, outbuf, outlen,
outlen_actual, false, NULL, NULL);
}
int efx_siena_mcdi_rpc_finish_quiet(struct efx_nic *efx, unsigned int cmd,
size_t inlen, efx_dword_t *outbuf,
size_t outlen, size_t *outlen_actual)
{
return _efx_mcdi_rpc_finish(efx, cmd, inlen, outbuf, outlen,
outlen_actual, true, NULL, NULL);
}
void efx_siena_mcdi_display_error(struct efx_nic *efx, unsigned int cmd,
size_t inlen, efx_dword_t *outbuf,
size_t outlen, int rc)
{
int code = 0, err_arg = 0;
if (outlen >= MC_CMD_ERR_CODE_OFST + 4)
code = MCDI_DWORD(outbuf, ERR_CODE);
if (outlen >= MC_CMD_ERR_ARG_OFST + 4)
err_arg = MCDI_DWORD(outbuf, ERR_ARG);
netif_cond_dbg(efx, hw, efx->net_dev, rc == -EPERM, err,
"MC command 0x%x inlen %zu failed rc=%d (raw=%d) arg=%d\n",
cmd, inlen, rc, code, err_arg);
}
/* Switch to polled MCDI completions. This can be called in various
* error conditions with various locks held, so it must be lockless.
* Caller is responsible for flushing asynchronous requests later.
*/
void efx_siena_mcdi_mode_poll(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi;
if (!efx->mcdi)
return;
mcdi = efx_mcdi(efx);
/* If already in polling mode, nothing to do.
* If in fail-fast state, don't switch to polled completion.
* FLR recovery will do that later.
*/
if (mcdi->mode == MCDI_MODE_POLL || mcdi->mode == MCDI_MODE_FAIL)
return;
/* We can switch from event completion to polled completion, because
* mcdi requests are always completed in shared memory. We do this by
* switching the mode to POLL'd then completing the request.
* efx_mcdi_await_completion() will then call efx_mcdi_poll().
*
* We need an smp_wmb() to synchronise with efx_mcdi_await_completion(),
* which efx_mcdi_complete_sync() provides for us.
*/
mcdi->mode = MCDI_MODE_POLL;
efx_mcdi_complete_sync(mcdi);
}
/* Flush any running or queued asynchronous requests, after event processing
* is stopped
*/
void efx_siena_mcdi_flush_async(struct efx_nic *efx)
{
struct efx_mcdi_async_param *async, *next;
struct efx_mcdi_iface *mcdi;
if (!efx->mcdi)
return;
mcdi = efx_mcdi(efx);
/* We must be in poll or fail mode so no more requests can be queued */
BUG_ON(mcdi->mode == MCDI_MODE_EVENTS);
del_timer_sync(&mcdi->async_timer);
/* If a request is still running, make sure we give the MC
* time to complete it so that the response won't overwrite our
* next request.
*/
if (mcdi->state == MCDI_STATE_RUNNING_ASYNC) {
efx_mcdi_poll(efx);
mcdi->state = MCDI_STATE_QUIESCENT;
}
/* Nothing else will access the async list now, so it is safe
* to walk it without holding async_lock. If we hold it while
* calling a completer then lockdep may warn that we have
* acquired locks in the wrong order.
*/
list_for_each_entry_safe(async, next, &mcdi->async_list, list) {
if (async->complete)
async->complete(efx, async->cookie, -ENETDOWN, NULL, 0);
list_del(&async->list);
kfree(async);
}
}
void efx_siena_mcdi_mode_event(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi;
if (!efx->mcdi)
return;
mcdi = efx_mcdi(efx);
/* If already in event completion mode, nothing to do.
* If in fail-fast state, don't switch to event completion. FLR
* recovery will do that later.
*/
if (mcdi->mode == MCDI_MODE_EVENTS || mcdi->mode == MCDI_MODE_FAIL)
return;
/* We can't switch from polled to event completion in the middle of a
* request, because the completion method is specified in the request.
* So acquire the interface to serialise the requestors. We don't need
* to acquire the iface_lock to change the mode here, but we do need a
* write memory barrier ensure that efx_siena_mcdi_rpc() sees it, which
* efx_mcdi_acquire() provides.
*/
efx_mcdi_acquire_sync(mcdi);
mcdi->mode = MCDI_MODE_EVENTS;
efx_mcdi_release(mcdi);
}
static void efx_mcdi_ev_death(struct efx_nic *efx, int rc)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
/* If there is an outstanding MCDI request, it has been terminated
* either by a BADASSERT or REBOOT event. If the mcdi interface is
* in polled mode, then do nothing because the MC reboot handler will
* set the header correctly. However, if the mcdi interface is waiting
* for a CMDDONE event it won't receive it [and since all MCDI events
* are sent to the same queue, we can't be racing with
* efx_mcdi_ev_cpl()]
*
* If there is an outstanding asynchronous request, we can't
* complete it now (efx_mcdi_complete() would deadlock). The
* reset process will take care of this.
*
* There's a race here with efx_mcdi_send_request(), because
* we might receive a REBOOT event *before* the request has
* been copied out. In polled mode (during startup) this is
* irrelevant, because efx_mcdi_complete_sync() is ignored. In
* event mode, this condition is just an edge-case of
* receiving a REBOOT event after posting the MCDI
* request. Did the mc reboot before or after the copyout? The
* best we can do always is just return failure.
*
* If there is an outstanding proxy response expected it is not going
* to arrive. We should thus abort it.
*/
spin_lock(&mcdi->iface_lock);
efx_mcdi_proxy_abort(mcdi);
if (efx_mcdi_complete_sync(mcdi)) {
if (mcdi->mode == MCDI_MODE_EVENTS) {
mcdi->resprc = rc;
mcdi->resp_hdr_len = 0;
mcdi->resp_data_len = 0;
++mcdi->credits;
}
} else {
int count;
/* Consume the status word since efx_siena_mcdi_rpc_finish() won't */
for (count = 0; count < MCDI_STATUS_DELAY_COUNT; ++count) {
rc = efx_siena_mcdi_poll_reboot(efx);
if (rc)
break;
udelay(MCDI_STATUS_DELAY_US);
}
/* On EF10, a CODE_MC_REBOOT event can be received without the
* reboot detection in efx_siena_mcdi_poll_reboot() being triggered.
* If zero was returned from the final call to
* efx_siena_mcdi_poll_reboot(), the MC reboot wasn't noticed but the
* MC has definitely rebooted so prepare for the reset.
*/
if (!rc && efx->type->mcdi_reboot_detected)
efx->type->mcdi_reboot_detected(efx);
mcdi->new_epoch = true;
/* Nobody was waiting for an MCDI request, so trigger a reset */
efx_siena_schedule_reset(efx, RESET_TYPE_MC_FAILURE);
}
spin_unlock(&mcdi->iface_lock);
}
/* The MC is going down in to BIST mode. set the BIST flag to block
* new MCDI, cancel any outstanding MCDI and schedule a BIST-type reset
* (which doesn't actually execute a reset, it waits for the controlling
* function to reset it).
*/
static void efx_mcdi_ev_bist(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
spin_lock(&mcdi->iface_lock);
efx->mc_bist_for_other_fn = true;
efx_mcdi_proxy_abort(mcdi);
if (efx_mcdi_complete_sync(mcdi)) {
if (mcdi->mode == MCDI_MODE_EVENTS) {
mcdi->resprc = -EIO;
mcdi->resp_hdr_len = 0;
mcdi->resp_data_len = 0;
++mcdi->credits;
}
}
mcdi->new_epoch = true;
efx_siena_schedule_reset(efx, RESET_TYPE_MC_BIST);
spin_unlock(&mcdi->iface_lock);
}
/* MCDI timeouts seen, so make all MCDI calls fail-fast and issue an FLR to try
* to recover.
*/
static void efx_mcdi_abandon(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
if (xchg(&mcdi->mode, MCDI_MODE_FAIL) == MCDI_MODE_FAIL)
return; /* it had already been done */
netif_dbg(efx, hw, efx->net_dev, "MCDI is timing out; trying to recover\n");
efx_siena_schedule_reset(efx, RESET_TYPE_MCDI_TIMEOUT);
}
static void efx_handle_drain_event(struct efx_nic *efx)
{
if (atomic_dec_and_test(&efx->active_queues))
wake_up(&efx->flush_wq);
WARN_ON(atomic_read(&efx->active_queues) < 0);
}
/* Called from efx_farch_ev_process and efx_ef10_ev_process for MCDI events */
void efx_siena_mcdi_process_event(struct efx_channel *channel,
efx_qword_t *event)
{
struct efx_nic *efx = channel->efx;
int code = EFX_QWORD_FIELD(*event, MCDI_EVENT_CODE);
u32 data = EFX_QWORD_FIELD(*event, MCDI_EVENT_DATA);
switch (code) {
case MCDI_EVENT_CODE_BADSSERT:
netif_err(efx, hw, efx->net_dev,
"MC watchdog or assertion failure at 0x%x\n", data);
efx_mcdi_ev_death(efx, -EINTR);
break;
case MCDI_EVENT_CODE_PMNOTICE:
netif_info(efx, wol, efx->net_dev, "MCDI PM event.\n");
break;
case MCDI_EVENT_CODE_CMDDONE:
efx_mcdi_ev_cpl(efx,
MCDI_EVENT_FIELD(*event, CMDDONE_SEQ),
MCDI_EVENT_FIELD(*event, CMDDONE_DATALEN),
MCDI_EVENT_FIELD(*event, CMDDONE_ERRNO));
break;
case MCDI_EVENT_CODE_LINKCHANGE:
efx_siena_mcdi_process_link_change(efx, event);
break;
case MCDI_EVENT_CODE_SENSOREVT:
efx_sensor_event(efx, event);
break;
case MCDI_EVENT_CODE_SCHEDERR:
netif_dbg(efx, hw, efx->net_dev,
"MC Scheduler alert (0x%x)\n", data);
break;
case MCDI_EVENT_CODE_REBOOT:
case MCDI_EVENT_CODE_MC_REBOOT:
netif_info(efx, hw, efx->net_dev, "MC Reboot\n");
efx_mcdi_ev_death(efx, -EIO);
break;
case MCDI_EVENT_CODE_MC_BIST:
netif_info(efx, hw, efx->net_dev, "MC entered BIST mode\n");
efx_mcdi_ev_bist(efx);
break;
case MCDI_EVENT_CODE_MAC_STATS_DMA:
/* MAC stats are gather lazily. We can ignore this. */
break;
case MCDI_EVENT_CODE_FLR:
if (efx->type->sriov_flr)
efx->type->sriov_flr(efx,
MCDI_EVENT_FIELD(*event, FLR_VF));
break;
case MCDI_EVENT_CODE_PTP_RX:
case MCDI_EVENT_CODE_PTP_FAULT:
case MCDI_EVENT_CODE_PTP_PPS:
efx_siena_ptp_event(efx, event);
break;
case MCDI_EVENT_CODE_PTP_TIME:
efx_siena_time_sync_event(channel, event);
break;
case MCDI_EVENT_CODE_TX_FLUSH:
case MCDI_EVENT_CODE_RX_FLUSH:
/* Two flush events will be sent: one to the same event
* queue as completions, and one to event queue 0.
* In the latter case the {RX,TX}_FLUSH_TO_DRIVER
* flag will be set, and we should ignore the event
* because we want to wait for all completions.
*/
BUILD_BUG_ON(MCDI_EVENT_TX_FLUSH_TO_DRIVER_LBN !=
MCDI_EVENT_RX_FLUSH_TO_DRIVER_LBN);
if (!MCDI_EVENT_FIELD(*event, TX_FLUSH_TO_DRIVER))
efx_handle_drain_event(efx);
break;
case MCDI_EVENT_CODE_TX_ERR:
case MCDI_EVENT_CODE_RX_ERR:
netif_err(efx, hw, efx->net_dev,
"%s DMA error (event: "EFX_QWORD_FMT")\n",
code == MCDI_EVENT_CODE_TX_ERR ? "TX" : "RX",
EFX_QWORD_VAL(*event));
efx_siena_schedule_reset(efx, RESET_TYPE_DMA_ERROR);
break;
case MCDI_EVENT_CODE_PROXY_RESPONSE:
efx_mcdi_ev_proxy_response(efx,
MCDI_EVENT_FIELD(*event, PROXY_RESPONSE_HANDLE),
MCDI_EVENT_FIELD(*event, PROXY_RESPONSE_RC));
break;
default:
netif_err(efx, hw, efx->net_dev,
"Unknown MCDI event " EFX_QWORD_FMT "\n",
EFX_QWORD_VAL(*event));
}
}
/**************************************************************************
*
* Specific request functions
*
**************************************************************************
*/
void efx_siena_mcdi_print_fwver(struct efx_nic *efx, char *buf, size_t len)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_VERSION_OUT_LEN);
size_t outlength;
const __le16 *ver_words;
size_t offset;
int rc;
BUILD_BUG_ON(MC_CMD_GET_VERSION_IN_LEN != 0);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_GET_VERSION, NULL, 0,
outbuf, sizeof(outbuf), &outlength);
if (rc)
goto fail;
if (outlength < MC_CMD_GET_VERSION_OUT_LEN) {
rc = -EIO;
goto fail;
}
ver_words = (__le16 *)MCDI_PTR(outbuf, GET_VERSION_OUT_VERSION);
offset = scnprintf(buf, len, "%u.%u.%u.%u",
le16_to_cpu(ver_words[0]),
le16_to_cpu(ver_words[1]),
le16_to_cpu(ver_words[2]),
le16_to_cpu(ver_words[3]));
if (efx->type->print_additional_fwver)
offset += efx->type->print_additional_fwver(efx, buf + offset,
len - offset);
/* It's theoretically possible for the string to exceed 31
* characters, though in practice the first three version
* components are short enough that this doesn't happen.
*/
if (WARN_ON(offset >= len))
buf[0] = 0;
return;
fail:
netif_err(efx, probe, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
buf[0] = 0;
}
static int efx_mcdi_drv_attach(struct efx_nic *efx, bool driver_operating,
bool *was_attached)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_DRV_ATTACH_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_DRV_ATTACH_EXT_OUT_LEN);
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, DRV_ATTACH_IN_NEW_STATE,
driver_operating ? 1 : 0);
MCDI_SET_DWORD(inbuf, DRV_ATTACH_IN_UPDATE, 1);
MCDI_SET_DWORD(inbuf, DRV_ATTACH_IN_FIRMWARE_ID, MC_CMD_FW_LOW_LATENCY);
rc = efx_siena_mcdi_rpc_quiet(efx, MC_CMD_DRV_ATTACH, inbuf,
sizeof(inbuf), outbuf, sizeof(outbuf),
&outlen);
/* If we're not the primary PF, trying to ATTACH with a FIRMWARE_ID
* specified will fail with EPERM, and we have to tell the MC we don't
* care what firmware we get.
*/
if (rc == -EPERM) {
netif_dbg(efx, probe, efx->net_dev,
"efx_mcdi_drv_attach with fw-variant setting failed EPERM, trying without it\n");
MCDI_SET_DWORD(inbuf, DRV_ATTACH_IN_FIRMWARE_ID,
MC_CMD_FW_DONT_CARE);
rc = efx_siena_mcdi_rpc_quiet(efx, MC_CMD_DRV_ATTACH, inbuf,
sizeof(inbuf), outbuf,
sizeof(outbuf), &outlen);
}
if (rc) {
efx_siena_mcdi_display_error(efx, MC_CMD_DRV_ATTACH,
sizeof(inbuf), outbuf, outlen, rc);
goto fail;
}
if (outlen < MC_CMD_DRV_ATTACH_OUT_LEN) {
rc = -EIO;
goto fail;
}
if (driver_operating) {
if (outlen >= MC_CMD_DRV_ATTACH_EXT_OUT_LEN) {
efx->mcdi->fn_flags =
MCDI_DWORD(outbuf,
DRV_ATTACH_EXT_OUT_FUNC_FLAGS);
} else {
/* Synthesise flags for Siena */
efx->mcdi->fn_flags =
1 << MC_CMD_DRV_ATTACH_EXT_OUT_FLAG_LINKCTRL |
1 << MC_CMD_DRV_ATTACH_EXT_OUT_FLAG_TRUSTED |
(efx_port_num(efx) == 0) <<
MC_CMD_DRV_ATTACH_EXT_OUT_FLAG_PRIMARY;
}
}
/* We currently assume we have control of the external link
* and are completely trusted by firmware. Abort probing
* if that's not true for this function.
*/
if (was_attached != NULL)
*was_attached = MCDI_DWORD(outbuf, DRV_ATTACH_OUT_OLD_STATE);
return 0;
fail:
netif_err(efx, probe, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_siena_mcdi_get_board_cfg(struct efx_nic *efx, u8 *mac_address,
u16 *fw_subtype_list, u32 *capabilities)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_BOARD_CFG_OUT_LENMAX);
size_t outlen, i;
int port_num = efx_port_num(efx);
int rc;
BUILD_BUG_ON(MC_CMD_GET_BOARD_CFG_IN_LEN != 0);
/* we need __aligned(2) for ether_addr_copy */
BUILD_BUG_ON(MC_CMD_GET_BOARD_CFG_OUT_MAC_ADDR_BASE_PORT0_OFST & 1);
BUILD_BUG_ON(MC_CMD_GET_BOARD_CFG_OUT_MAC_ADDR_BASE_PORT1_OFST & 1);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_GET_BOARD_CFG, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_GET_BOARD_CFG_OUT_LENMIN) {
rc = -EIO;
goto fail;
}
if (mac_address)
ether_addr_copy(mac_address,
port_num ?
MCDI_PTR(outbuf, GET_BOARD_CFG_OUT_MAC_ADDR_BASE_PORT1) :
MCDI_PTR(outbuf, GET_BOARD_CFG_OUT_MAC_ADDR_BASE_PORT0));
if (fw_subtype_list) {
for (i = 0;
i < MCDI_VAR_ARRAY_LEN(outlen,
GET_BOARD_CFG_OUT_FW_SUBTYPE_LIST);
i++)
fw_subtype_list[i] = MCDI_ARRAY_WORD(
outbuf, GET_BOARD_CFG_OUT_FW_SUBTYPE_LIST, i);
for (; i < MC_CMD_GET_BOARD_CFG_OUT_FW_SUBTYPE_LIST_MAXNUM; i++)
fw_subtype_list[i] = 0;
}
if (capabilities) {
if (port_num)
*capabilities = MCDI_DWORD(outbuf,
GET_BOARD_CFG_OUT_CAPABILITIES_PORT1);
else
*capabilities = MCDI_DWORD(outbuf,
GET_BOARD_CFG_OUT_CAPABILITIES_PORT0);
}
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d len=%d\n",
__func__, rc, (int)outlen);
return rc;
}
int efx_siena_mcdi_log_ctrl(struct efx_nic *efx, bool evq, bool uart,
u32 dest_evq)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_LOG_CTRL_IN_LEN);
u32 dest = 0;
int rc;
if (uart)
dest |= MC_CMD_LOG_CTRL_IN_LOG_DEST_UART;
if (evq)
dest |= MC_CMD_LOG_CTRL_IN_LOG_DEST_EVQ;
MCDI_SET_DWORD(inbuf, LOG_CTRL_IN_LOG_DEST, dest);
MCDI_SET_DWORD(inbuf, LOG_CTRL_IN_LOG_DEST_EVQ, dest_evq);
BUILD_BUG_ON(MC_CMD_LOG_CTRL_OUT_LEN != 0);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_LOG_CTRL, inbuf, sizeof(inbuf),
NULL, 0, NULL);
return rc;
}
int efx_siena_mcdi_nvram_types(struct efx_nic *efx, u32 *nvram_types_out)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_NVRAM_TYPES_OUT_LEN);
size_t outlen;
int rc;
BUILD_BUG_ON(MC_CMD_NVRAM_TYPES_IN_LEN != 0);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_NVRAM_TYPES, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_NVRAM_TYPES_OUT_LEN) {
rc = -EIO;
goto fail;
}
*nvram_types_out = MCDI_DWORD(outbuf, NVRAM_TYPES_OUT_TYPES);
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n",
__func__, rc);
return rc;
}
int efx_siena_mcdi_nvram_info(struct efx_nic *efx, unsigned int type,
size_t *size_out, size_t *erase_size_out,
bool *protected_out)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_NVRAM_INFO_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_NVRAM_INFO_OUT_LEN);
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_INFO_IN_TYPE, type);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_NVRAM_INFO, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_NVRAM_INFO_OUT_LEN) {
rc = -EIO;
goto fail;
}
*size_out = MCDI_DWORD(outbuf, NVRAM_INFO_OUT_SIZE);
*erase_size_out = MCDI_DWORD(outbuf, NVRAM_INFO_OUT_ERASESIZE);
*protected_out = !!(MCDI_DWORD(outbuf, NVRAM_INFO_OUT_FLAGS) &
(1 << MC_CMD_NVRAM_INFO_OUT_PROTECTED_LBN));
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
static int efx_mcdi_nvram_test(struct efx_nic *efx, unsigned int type)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_NVRAM_TEST_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_NVRAM_TEST_OUT_LEN);
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_TEST_IN_TYPE, type);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_NVRAM_TEST, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), NULL);
if (rc)
return rc;
switch (MCDI_DWORD(outbuf, NVRAM_TEST_OUT_RESULT)) {
case MC_CMD_NVRAM_TEST_PASS:
case MC_CMD_NVRAM_TEST_NOTSUPP:
return 0;
default:
return -EIO;
}
}
int efx_siena_mcdi_nvram_test_all(struct efx_nic *efx)
{
u32 nvram_types;
unsigned int type;
int rc;
rc = efx_siena_mcdi_nvram_types(efx, &nvram_types);
if (rc)
goto fail1;
type = 0;
while (nvram_types != 0) {
if (nvram_types & 1) {
rc = efx_mcdi_nvram_test(efx, type);
if (rc)
goto fail2;
}
type++;
nvram_types >>= 1;
}
return 0;
fail2:
netif_err(efx, hw, efx->net_dev, "%s: failed type=%u\n",
__func__, type);
fail1:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
/* Returns 1 if an assertion was read, 0 if no assertion had fired,
* negative on error.
*/
static int efx_mcdi_read_assertion(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_GET_ASSERTS_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_ASSERTS_OUT_LEN);
unsigned int flags, index;
const char *reason;
size_t outlen;
int retry;
int rc;
/* Attempt to read any stored assertion state before we reboot
* the mcfw out of the assertion handler. Retry twice, once
* because a boot-time assertion might cause this command to fail
* with EINTR. And once again because GET_ASSERTS can race with
* MC_CMD_REBOOT running on the other port. */
retry = 2;
do {
MCDI_SET_DWORD(inbuf, GET_ASSERTS_IN_CLEAR, 1);
rc = efx_siena_mcdi_rpc_quiet(efx, MC_CMD_GET_ASSERTS,
inbuf, MC_CMD_GET_ASSERTS_IN_LEN,
outbuf, sizeof(outbuf), &outlen);
if (rc == -EPERM)
return 0;
} while ((rc == -EINTR || rc == -EIO) && retry-- > 0);
if (rc) {
efx_siena_mcdi_display_error(efx, MC_CMD_GET_ASSERTS,
MC_CMD_GET_ASSERTS_IN_LEN, outbuf,
outlen, rc);
return rc;
}
if (outlen < MC_CMD_GET_ASSERTS_OUT_LEN)
return -EIO;
/* Print out any recorded assertion state */
flags = MCDI_DWORD(outbuf, GET_ASSERTS_OUT_GLOBAL_FLAGS);
if (flags == MC_CMD_GET_ASSERTS_FLAGS_NO_FAILS)
return 0;
reason = (flags == MC_CMD_GET_ASSERTS_FLAGS_SYS_FAIL)
? "system-level assertion"
: (flags == MC_CMD_GET_ASSERTS_FLAGS_THR_FAIL)
? "thread-level assertion"
: (flags == MC_CMD_GET_ASSERTS_FLAGS_WDOG_FIRED)
? "watchdog reset"
: "unknown assertion";
netif_err(efx, hw, efx->net_dev,
"MCPU %s at PC = 0x%.8x in thread 0x%.8x\n", reason,
MCDI_DWORD(outbuf, GET_ASSERTS_OUT_SAVED_PC_OFFS),
MCDI_DWORD(outbuf, GET_ASSERTS_OUT_THREAD_OFFS));
/* Print out the registers */
for (index = 0;
index < MC_CMD_GET_ASSERTS_OUT_GP_REGS_OFFS_NUM;
index++)
netif_err(efx, hw, efx->net_dev, "R%.2d (?): 0x%.8x\n",
1 + index,
MCDI_ARRAY_DWORD(outbuf, GET_ASSERTS_OUT_GP_REGS_OFFS,
index));
return 1;
}
static int efx_mcdi_exit_assertion(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_REBOOT_IN_LEN);
int rc;
/* If the MC is running debug firmware, it might now be
* waiting for a debugger to attach, but we just want it to
* reboot. We set a flag that makes the command a no-op if it
* has already done so.
* The MCDI will thus return either 0 or -EIO.
*/
BUILD_BUG_ON(MC_CMD_REBOOT_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, REBOOT_IN_FLAGS,
MC_CMD_REBOOT_FLAGS_AFTER_ASSERTION);
rc = efx_siena_mcdi_rpc_quiet(efx, MC_CMD_REBOOT, inbuf,
MC_CMD_REBOOT_IN_LEN, NULL, 0, NULL);
if (rc == -EIO)
rc = 0;
if (rc)
efx_siena_mcdi_display_error(efx, MC_CMD_REBOOT,
MC_CMD_REBOOT_IN_LEN, NULL, 0, rc);
return rc;
}
int efx_siena_mcdi_handle_assertion(struct efx_nic *efx)
{
int rc;
rc = efx_mcdi_read_assertion(efx);
if (rc <= 0)
return rc;
return efx_mcdi_exit_assertion(efx);
}
int efx_siena_mcdi_set_id_led(struct efx_nic *efx, enum efx_led_mode mode)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_SET_ID_LED_IN_LEN);
BUILD_BUG_ON(EFX_LED_OFF != MC_CMD_LED_OFF);
BUILD_BUG_ON(EFX_LED_ON != MC_CMD_LED_ON);
BUILD_BUG_ON(EFX_LED_DEFAULT != MC_CMD_LED_DEFAULT);
BUILD_BUG_ON(MC_CMD_SET_ID_LED_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, SET_ID_LED_IN_STATE, mode);
return efx_siena_mcdi_rpc(efx, MC_CMD_SET_ID_LED, inbuf, sizeof(inbuf),
NULL, 0, NULL);
}
static int efx_mcdi_reset_func(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_ENTITY_RESET_IN_LEN);
int rc;
BUILD_BUG_ON(MC_CMD_ENTITY_RESET_OUT_LEN != 0);
MCDI_POPULATE_DWORD_1(inbuf, ENTITY_RESET_IN_FLAG,
ENTITY_RESET_IN_FUNCTION_RESOURCE_RESET, 1);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_ENTITY_RESET, inbuf, sizeof(inbuf),
NULL, 0, NULL);
return rc;
}
static int efx_mcdi_reset_mc(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_REBOOT_IN_LEN);
int rc;
BUILD_BUG_ON(MC_CMD_REBOOT_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, REBOOT_IN_FLAGS, 0);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_REBOOT, inbuf, sizeof(inbuf),
NULL, 0, NULL);
/* White is black, and up is down */
if (rc == -EIO)
return 0;
if (rc == 0)
rc = -EIO;
return rc;
}
enum reset_type efx_siena_mcdi_map_reset_reason(enum reset_type reason)
{
return RESET_TYPE_RECOVER_OR_ALL;
}
int efx_siena_mcdi_reset(struct efx_nic *efx, enum reset_type method)
{
int rc;
/* If MCDI is down, we can't handle_assertion */
if (method == RESET_TYPE_MCDI_TIMEOUT) {
rc = pci_reset_function(efx->pci_dev);
if (rc)
return rc;
/* Re-enable polled MCDI completion */
if (efx->mcdi) {
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
mcdi->mode = MCDI_MODE_POLL;
}
return 0;
}
/* Recover from a failed assertion pre-reset */
rc = efx_siena_mcdi_handle_assertion(efx);
if (rc)
return rc;
if (method == RESET_TYPE_DATAPATH)
return 0;
else if (method == RESET_TYPE_WORLD)
return efx_mcdi_reset_mc(efx);
else
return efx_mcdi_reset_func(efx);
}
static int efx_mcdi_wol_filter_set(struct efx_nic *efx, u32 type,
const u8 *mac, int *id_out)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_WOL_FILTER_SET_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_WOL_FILTER_SET_OUT_LEN);
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, WOL_FILTER_SET_IN_WOL_TYPE, type);
MCDI_SET_DWORD(inbuf, WOL_FILTER_SET_IN_FILTER_MODE,
MC_CMD_FILTER_MODE_SIMPLE);
ether_addr_copy(MCDI_PTR(inbuf, WOL_FILTER_SET_IN_MAGIC_MAC), mac);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_WOL_FILTER_SET, inbuf,
sizeof(inbuf), outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_WOL_FILTER_SET_OUT_LEN) {
rc = -EIO;
goto fail;
}
*id_out = (int)MCDI_DWORD(outbuf, WOL_FILTER_SET_OUT_FILTER_ID);
return 0;
fail:
*id_out = -1;
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_siena_mcdi_wol_filter_set_magic(struct efx_nic *efx, const u8 *mac,
int *id_out)
{
return efx_mcdi_wol_filter_set(efx, MC_CMD_WOL_TYPE_MAGIC, mac, id_out);
}
int efx_siena_mcdi_wol_filter_get_magic(struct efx_nic *efx, int *id_out)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_WOL_FILTER_GET_OUT_LEN);
size_t outlen;
int rc;
rc = efx_siena_mcdi_rpc(efx, MC_CMD_WOL_FILTER_GET, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_WOL_FILTER_GET_OUT_LEN) {
rc = -EIO;
goto fail;
}
*id_out = (int)MCDI_DWORD(outbuf, WOL_FILTER_GET_OUT_FILTER_ID);
return 0;
fail:
*id_out = -1;
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_siena_mcdi_wol_filter_remove(struct efx_nic *efx, int id)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_WOL_FILTER_REMOVE_IN_LEN);
int rc;
MCDI_SET_DWORD(inbuf, WOL_FILTER_REMOVE_IN_FILTER_ID, (u32)id);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_WOL_FILTER_REMOVE, inbuf,
sizeof(inbuf), NULL, 0, NULL);
return rc;
}
int efx_siena_mcdi_flush_rxqs(struct efx_nic *efx)
{
struct efx_channel *channel;
struct efx_rx_queue *rx_queue;
MCDI_DECLARE_BUF(inbuf,
MC_CMD_FLUSH_RX_QUEUES_IN_LEN(EFX_MAX_CHANNELS));
int rc, count;
BUILD_BUG_ON(EFX_MAX_CHANNELS >
MC_CMD_FLUSH_RX_QUEUES_IN_QID_OFST_MAXNUM);
count = 0;
efx_for_each_channel(channel, efx) {
efx_for_each_channel_rx_queue(rx_queue, channel) {
if (rx_queue->flush_pending) {
rx_queue->flush_pending = false;
atomic_dec(&efx->rxq_flush_pending);
MCDI_SET_ARRAY_DWORD(
inbuf, FLUSH_RX_QUEUES_IN_QID_OFST,
count, efx_rx_queue_index(rx_queue));
count++;
}
}
}
rc = efx_siena_mcdi_rpc(efx, MC_CMD_FLUSH_RX_QUEUES, inbuf,
MC_CMD_FLUSH_RX_QUEUES_IN_LEN(count),
NULL, 0, NULL);
WARN_ON(rc < 0);
return rc;
}
int efx_siena_mcdi_wol_filter_reset(struct efx_nic *efx)
{
int rc;
rc = efx_siena_mcdi_rpc(efx, MC_CMD_WOL_FILTER_RESET, NULL, 0,
NULL, 0, NULL);
return rc;
}
#ifdef CONFIG_SFC_SIENA_MTD
#define EFX_MCDI_NVRAM_LEN_MAX 128
static int efx_mcdi_nvram_update_start(struct efx_nic *efx, unsigned int type)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_NVRAM_UPDATE_START_V2_IN_LEN);
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_UPDATE_START_IN_TYPE, type);
MCDI_POPULATE_DWORD_1(inbuf, NVRAM_UPDATE_START_V2_IN_FLAGS,
NVRAM_UPDATE_START_V2_IN_FLAG_REPORT_VERIFY_RESULT,
1);
BUILD_BUG_ON(MC_CMD_NVRAM_UPDATE_START_OUT_LEN != 0);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_NVRAM_UPDATE_START, inbuf,
sizeof(inbuf), NULL, 0, NULL);
return rc;
}
static int efx_mcdi_nvram_read(struct efx_nic *efx, unsigned int type,
loff_t offset, u8 *buffer, size_t length)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_NVRAM_READ_IN_V2_LEN);
MCDI_DECLARE_BUF(outbuf,
MC_CMD_NVRAM_READ_OUT_LEN(EFX_MCDI_NVRAM_LEN_MAX));
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_READ_IN_TYPE, type);
MCDI_SET_DWORD(inbuf, NVRAM_READ_IN_OFFSET, offset);
MCDI_SET_DWORD(inbuf, NVRAM_READ_IN_LENGTH, length);
MCDI_SET_DWORD(inbuf, NVRAM_READ_IN_V2_MODE,
MC_CMD_NVRAM_READ_IN_V2_DEFAULT);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_NVRAM_READ, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
memcpy(buffer, MCDI_PTR(outbuf, NVRAM_READ_OUT_READ_BUFFER), length);
return 0;
}
static int efx_mcdi_nvram_write(struct efx_nic *efx, unsigned int type,
loff_t offset, const u8 *buffer, size_t length)
{
MCDI_DECLARE_BUF(inbuf,
MC_CMD_NVRAM_WRITE_IN_LEN(EFX_MCDI_NVRAM_LEN_MAX));
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_WRITE_IN_TYPE, type);
MCDI_SET_DWORD(inbuf, NVRAM_WRITE_IN_OFFSET, offset);
MCDI_SET_DWORD(inbuf, NVRAM_WRITE_IN_LENGTH, length);
memcpy(MCDI_PTR(inbuf, NVRAM_WRITE_IN_WRITE_BUFFER), buffer, length);
BUILD_BUG_ON(MC_CMD_NVRAM_WRITE_OUT_LEN != 0);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_NVRAM_WRITE, inbuf,
ALIGN(MC_CMD_NVRAM_WRITE_IN_LEN(length), 4),
NULL, 0, NULL);
return rc;
}
static int efx_mcdi_nvram_erase(struct efx_nic *efx, unsigned int type,
loff_t offset, size_t length)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_NVRAM_ERASE_IN_LEN);
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_ERASE_IN_TYPE, type);
MCDI_SET_DWORD(inbuf, NVRAM_ERASE_IN_OFFSET, offset);
MCDI_SET_DWORD(inbuf, NVRAM_ERASE_IN_LENGTH, length);
BUILD_BUG_ON(MC_CMD_NVRAM_ERASE_OUT_LEN != 0);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_NVRAM_ERASE, inbuf, sizeof(inbuf),
NULL, 0, NULL);
return rc;
}
static int efx_mcdi_nvram_update_finish(struct efx_nic *efx, unsigned int type)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_NVRAM_UPDATE_FINISH_V2_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_NVRAM_UPDATE_FINISH_V2_OUT_LEN);
size_t outlen;
int rc, rc2;
MCDI_SET_DWORD(inbuf, NVRAM_UPDATE_FINISH_IN_TYPE, type);
/* Always set this flag. Old firmware ignores it */
MCDI_POPULATE_DWORD_1(inbuf, NVRAM_UPDATE_FINISH_V2_IN_FLAGS,
NVRAM_UPDATE_FINISH_V2_IN_FLAG_REPORT_VERIFY_RESULT,
1);
rc = efx_siena_mcdi_rpc(efx, MC_CMD_NVRAM_UPDATE_FINISH, inbuf,
sizeof(inbuf), outbuf, sizeof(outbuf), &outlen);
if (!rc && outlen >= MC_CMD_NVRAM_UPDATE_FINISH_V2_OUT_LEN) {
rc2 = MCDI_DWORD(outbuf, NVRAM_UPDATE_FINISH_V2_OUT_RESULT_CODE);
if (rc2 != MC_CMD_NVRAM_VERIFY_RC_SUCCESS)
netif_err(efx, drv, efx->net_dev,
"NVRAM update failed verification with code 0x%x\n",
rc2);
switch (rc2) {
case MC_CMD_NVRAM_VERIFY_RC_SUCCESS:
break;
case MC_CMD_NVRAM_VERIFY_RC_CMS_CHECK_FAILED:
case MC_CMD_NVRAM_VERIFY_RC_MESSAGE_DIGEST_CHECK_FAILED:
case MC_CMD_NVRAM_VERIFY_RC_SIGNATURE_CHECK_FAILED:
case MC_CMD_NVRAM_VERIFY_RC_TRUSTED_APPROVERS_CHECK_FAILED:
case MC_CMD_NVRAM_VERIFY_RC_SIGNATURE_CHAIN_CHECK_FAILED:
rc = -EIO;
break;
case MC_CMD_NVRAM_VERIFY_RC_INVALID_CMS_FORMAT:
case MC_CMD_NVRAM_VERIFY_RC_BAD_MESSAGE_DIGEST:
rc = -EINVAL;
break;
case MC_CMD_NVRAM_VERIFY_RC_NO_VALID_SIGNATURES:
case MC_CMD_NVRAM_VERIFY_RC_NO_TRUSTED_APPROVERS:
case MC_CMD_NVRAM_VERIFY_RC_NO_SIGNATURE_MATCH:
rc = -EPERM;
break;
default:
netif_err(efx, drv, efx->net_dev,
"Unknown response to NVRAM_UPDATE_FINISH\n");
rc = -EIO;
}
}
return rc;
}
int efx_siena_mcdi_mtd_read(struct mtd_info *mtd, loff_t start,
size_t len, size_t *retlen, u8 *buffer)
{
struct efx_mcdi_mtd_partition *part = to_efx_mcdi_mtd_partition(mtd);
struct efx_nic *efx = mtd->priv;
loff_t offset = start;
loff_t end = min_t(loff_t, start + len, mtd->size);
size_t chunk;
int rc = 0;
while (offset < end) {
chunk = min_t(size_t, end - offset, EFX_MCDI_NVRAM_LEN_MAX);
rc = efx_mcdi_nvram_read(efx, part->nvram_type, offset,
buffer, chunk);
if (rc)
goto out;
offset += chunk;
buffer += chunk;
}
out:
*retlen = offset - start;
return rc;
}
int efx_siena_mcdi_mtd_erase(struct mtd_info *mtd, loff_t start, size_t len)
{
struct efx_mcdi_mtd_partition *part = to_efx_mcdi_mtd_partition(mtd);
struct efx_nic *efx = mtd->priv;
loff_t offset = start & ~((loff_t)(mtd->erasesize - 1));
loff_t end = min_t(loff_t, start + len, mtd->size);
size_t chunk = part->common.mtd.erasesize;
int rc = 0;
if (!part->updating) {
rc = efx_mcdi_nvram_update_start(efx, part->nvram_type);
if (rc)
goto out;
part->updating = true;
}
/* The MCDI interface can in fact do multiple erase blocks at once;
* but erasing may be slow, so we make multiple calls here to avoid
* tripping the MCDI RPC timeout. */
while (offset < end) {
rc = efx_mcdi_nvram_erase(efx, part->nvram_type, offset,
chunk);
if (rc)
goto out;
offset += chunk;
}
out:
return rc;
}
int efx_siena_mcdi_mtd_write(struct mtd_info *mtd, loff_t start,
size_t len, size_t *retlen, const u8 *buffer)
{
struct efx_mcdi_mtd_partition *part = to_efx_mcdi_mtd_partition(mtd);
struct efx_nic *efx = mtd->priv;
loff_t offset = start;
loff_t end = min_t(loff_t, start + len, mtd->size);
size_t chunk;
int rc = 0;
if (!part->updating) {
rc = efx_mcdi_nvram_update_start(efx, part->nvram_type);
if (rc)
goto out;
part->updating = true;
}
while (offset < end) {
chunk = min_t(size_t, end - offset, EFX_MCDI_NVRAM_LEN_MAX);
rc = efx_mcdi_nvram_write(efx, part->nvram_type, offset,
buffer, chunk);
if (rc)
goto out;
offset += chunk;
buffer += chunk;
}
out:
*retlen = offset - start;
return rc;
}
int efx_siena_mcdi_mtd_sync(struct mtd_info *mtd)
{
struct efx_mcdi_mtd_partition *part = to_efx_mcdi_mtd_partition(mtd);
struct efx_nic *efx = mtd->priv;
int rc = 0;
if (part->updating) {
part->updating = false;
rc = efx_mcdi_nvram_update_finish(efx, part->nvram_type);
}
return rc;
}
void efx_siena_mcdi_mtd_rename(struct efx_mtd_partition *part)
{
struct efx_mcdi_mtd_partition *mcdi_part =
container_of(part, struct efx_mcdi_mtd_partition, common);
struct efx_nic *efx = part->mtd.priv;
snprintf(part->name, sizeof(part->name), "%s %s:%02x",
efx->name, part->type_name, mcdi_part->fw_subtype);
}
#endif /* CONFIG_SFC_SIENA_MTD */
|
linux-master
|
drivers/net/ethernet/sfc/siena/mcdi.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2018 Solarflare Communications Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include "net_driver.h"
#include <linux/module.h>
#include <linux/iommu.h>
#include "efx.h"
#include "nic.h"
#include "rx_common.h"
/* This is the percentage fill level below which new RX descriptors
* will be added to the RX descriptor ring.
*/
static unsigned int rx_refill_threshold;
module_param(rx_refill_threshold, uint, 0444);
MODULE_PARM_DESC(rx_refill_threshold,
"RX descriptor ring refill threshold (%)");
/* RX maximum head room required.
*
* This must be at least 1 to prevent overflow, plus one packet-worth
* to allow pipelined receives.
*/
#define EFX_RXD_HEAD_ROOM (1 + EFX_RX_MAX_FRAGS)
static void efx_unmap_rx_buffer(struct efx_nic *efx,
struct efx_rx_buffer *rx_buf);
/* Check the RX page recycle ring for a page that can be reused. */
static struct page *efx_reuse_page(struct efx_rx_queue *rx_queue)
{
struct efx_nic *efx = rx_queue->efx;
struct efx_rx_page_state *state;
unsigned int index;
struct page *page;
if (unlikely(!rx_queue->page_ring))
return NULL;
index = rx_queue->page_remove & rx_queue->page_ptr_mask;
page = rx_queue->page_ring[index];
if (page == NULL)
return NULL;
rx_queue->page_ring[index] = NULL;
/* page_remove cannot exceed page_add. */
if (rx_queue->page_remove != rx_queue->page_add)
++rx_queue->page_remove;
/* If page_count is 1 then we hold the only reference to this page. */
if (page_count(page) == 1) {
++rx_queue->page_recycle_count;
return page;
} else {
state = page_address(page);
dma_unmap_page(&efx->pci_dev->dev, state->dma_addr,
PAGE_SIZE << efx->rx_buffer_order,
DMA_FROM_DEVICE);
put_page(page);
++rx_queue->page_recycle_failed;
}
return NULL;
}
/* Attempt to recycle the page if there is an RX recycle ring; the page can
* only be added if this is the final RX buffer, to prevent pages being used in
* the descriptor ring and appearing in the recycle ring simultaneously.
*/
static void efx_recycle_rx_page(struct efx_channel *channel,
struct efx_rx_buffer *rx_buf)
{
struct efx_rx_queue *rx_queue = efx_channel_get_rx_queue(channel);
struct efx_nic *efx = rx_queue->efx;
struct page *page = rx_buf->page;
unsigned int index;
/* Only recycle the page after processing the final buffer. */
if (!(rx_buf->flags & EFX_RX_BUF_LAST_IN_PAGE))
return;
index = rx_queue->page_add & rx_queue->page_ptr_mask;
if (rx_queue->page_ring[index] == NULL) {
unsigned int read_index = rx_queue->page_remove &
rx_queue->page_ptr_mask;
/* The next slot in the recycle ring is available, but
* increment page_remove if the read pointer currently
* points here.
*/
if (read_index == index)
++rx_queue->page_remove;
rx_queue->page_ring[index] = page;
++rx_queue->page_add;
return;
}
++rx_queue->page_recycle_full;
efx_unmap_rx_buffer(efx, rx_buf);
put_page(rx_buf->page);
}
/* Recycle the pages that are used by buffers that have just been received. */
void efx_siena_recycle_rx_pages(struct efx_channel *channel,
struct efx_rx_buffer *rx_buf,
unsigned int n_frags)
{
struct efx_rx_queue *rx_queue = efx_channel_get_rx_queue(channel);
if (unlikely(!rx_queue->page_ring))
return;
do {
efx_recycle_rx_page(channel, rx_buf);
rx_buf = efx_rx_buf_next(rx_queue, rx_buf);
} while (--n_frags);
}
void efx_siena_discard_rx_packet(struct efx_channel *channel,
struct efx_rx_buffer *rx_buf,
unsigned int n_frags)
{
struct efx_rx_queue *rx_queue = efx_channel_get_rx_queue(channel);
efx_siena_recycle_rx_pages(channel, rx_buf, n_frags);
efx_siena_free_rx_buffers(rx_queue, rx_buf, n_frags);
}
static void efx_init_rx_recycle_ring(struct efx_rx_queue *rx_queue)
{
unsigned int bufs_in_recycle_ring, page_ring_size;
struct efx_nic *efx = rx_queue->efx;
bufs_in_recycle_ring = efx_rx_recycle_ring_size(efx);
page_ring_size = roundup_pow_of_two(bufs_in_recycle_ring /
efx->rx_bufs_per_page);
rx_queue->page_ring = kcalloc(page_ring_size,
sizeof(*rx_queue->page_ring), GFP_KERNEL);
if (!rx_queue->page_ring)
rx_queue->page_ptr_mask = 0;
else
rx_queue->page_ptr_mask = page_ring_size - 1;
}
static void efx_fini_rx_recycle_ring(struct efx_rx_queue *rx_queue)
{
struct efx_nic *efx = rx_queue->efx;
int i;
if (unlikely(!rx_queue->page_ring))
return;
/* Unmap and release the pages in the recycle ring. Remove the ring. */
for (i = 0; i <= rx_queue->page_ptr_mask; i++) {
struct page *page = rx_queue->page_ring[i];
struct efx_rx_page_state *state;
if (page == NULL)
continue;
state = page_address(page);
dma_unmap_page(&efx->pci_dev->dev, state->dma_addr,
PAGE_SIZE << efx->rx_buffer_order,
DMA_FROM_DEVICE);
put_page(page);
}
kfree(rx_queue->page_ring);
rx_queue->page_ring = NULL;
}
static void efx_fini_rx_buffer(struct efx_rx_queue *rx_queue,
struct efx_rx_buffer *rx_buf)
{
/* Release the page reference we hold for the buffer. */
if (rx_buf->page)
put_page(rx_buf->page);
/* If this is the last buffer in a page, unmap and free it. */
if (rx_buf->flags & EFX_RX_BUF_LAST_IN_PAGE) {
efx_unmap_rx_buffer(rx_queue->efx, rx_buf);
efx_siena_free_rx_buffers(rx_queue, rx_buf, 1);
}
rx_buf->page = NULL;
}
int efx_siena_probe_rx_queue(struct efx_rx_queue *rx_queue)
{
struct efx_nic *efx = rx_queue->efx;
unsigned int entries;
int rc;
/* Create the smallest power-of-two aligned ring */
entries = max(roundup_pow_of_two(efx->rxq_entries), EFX_MIN_DMAQ_SIZE);
EFX_WARN_ON_PARANOID(entries > EFX_MAX_DMAQ_SIZE);
rx_queue->ptr_mask = entries - 1;
netif_dbg(efx, probe, efx->net_dev,
"creating RX queue %d size %#x mask %#x\n",
efx_rx_queue_index(rx_queue), efx->rxq_entries,
rx_queue->ptr_mask);
/* Allocate RX buffers */
rx_queue->buffer = kcalloc(entries, sizeof(*rx_queue->buffer),
GFP_KERNEL);
if (!rx_queue->buffer)
return -ENOMEM;
rc = efx_nic_probe_rx(rx_queue);
if (rc) {
kfree(rx_queue->buffer);
rx_queue->buffer = NULL;
}
return rc;
}
void efx_siena_init_rx_queue(struct efx_rx_queue *rx_queue)
{
unsigned int max_fill, trigger, max_trigger;
struct efx_nic *efx = rx_queue->efx;
int rc = 0;
netif_dbg(rx_queue->efx, drv, rx_queue->efx->net_dev,
"initialising RX queue %d\n", efx_rx_queue_index(rx_queue));
/* Initialise ptr fields */
rx_queue->added_count = 0;
rx_queue->notified_count = 0;
rx_queue->removed_count = 0;
rx_queue->min_fill = -1U;
efx_init_rx_recycle_ring(rx_queue);
rx_queue->page_remove = 0;
rx_queue->page_add = rx_queue->page_ptr_mask + 1;
rx_queue->page_recycle_count = 0;
rx_queue->page_recycle_failed = 0;
rx_queue->page_recycle_full = 0;
/* Initialise limit fields */
max_fill = efx->rxq_entries - EFX_RXD_HEAD_ROOM;
max_trigger =
max_fill - efx->rx_pages_per_batch * efx->rx_bufs_per_page;
if (rx_refill_threshold != 0) {
trigger = max_fill * min(rx_refill_threshold, 100U) / 100U;
if (trigger > max_trigger)
trigger = max_trigger;
} else {
trigger = max_trigger;
}
rx_queue->max_fill = max_fill;
rx_queue->fast_fill_trigger = trigger;
rx_queue->refill_enabled = true;
/* Initialise XDP queue information */
rc = xdp_rxq_info_reg(&rx_queue->xdp_rxq_info, efx->net_dev,
rx_queue->core_index, 0);
if (rc) {
netif_err(efx, rx_err, efx->net_dev,
"Failure to initialise XDP queue information rc=%d\n",
rc);
efx->xdp_rxq_info_failed = true;
} else {
rx_queue->xdp_rxq_info_valid = true;
}
/* Set up RX descriptor ring */
efx_nic_init_rx(rx_queue);
}
void efx_siena_fini_rx_queue(struct efx_rx_queue *rx_queue)
{
struct efx_rx_buffer *rx_buf;
int i;
netif_dbg(rx_queue->efx, drv, rx_queue->efx->net_dev,
"shutting down RX queue %d\n", efx_rx_queue_index(rx_queue));
del_timer_sync(&rx_queue->slow_fill);
/* Release RX buffers from the current read ptr to the write ptr */
if (rx_queue->buffer) {
for (i = rx_queue->removed_count; i < rx_queue->added_count;
i++) {
unsigned int index = i & rx_queue->ptr_mask;
rx_buf = efx_rx_buffer(rx_queue, index);
efx_fini_rx_buffer(rx_queue, rx_buf);
}
}
efx_fini_rx_recycle_ring(rx_queue);
if (rx_queue->xdp_rxq_info_valid)
xdp_rxq_info_unreg(&rx_queue->xdp_rxq_info);
rx_queue->xdp_rxq_info_valid = false;
}
void efx_siena_remove_rx_queue(struct efx_rx_queue *rx_queue)
{
netif_dbg(rx_queue->efx, drv, rx_queue->efx->net_dev,
"destroying RX queue %d\n", efx_rx_queue_index(rx_queue));
efx_nic_remove_rx(rx_queue);
kfree(rx_queue->buffer);
rx_queue->buffer = NULL;
}
/* Unmap a DMA-mapped page. This function is only called for the final RX
* buffer in a page.
*/
static void efx_unmap_rx_buffer(struct efx_nic *efx,
struct efx_rx_buffer *rx_buf)
{
struct page *page = rx_buf->page;
if (page) {
struct efx_rx_page_state *state = page_address(page);
dma_unmap_page(&efx->pci_dev->dev,
state->dma_addr,
PAGE_SIZE << efx->rx_buffer_order,
DMA_FROM_DEVICE);
}
}
void efx_siena_free_rx_buffers(struct efx_rx_queue *rx_queue,
struct efx_rx_buffer *rx_buf,
unsigned int num_bufs)
{
do {
if (rx_buf->page) {
put_page(rx_buf->page);
rx_buf->page = NULL;
}
rx_buf = efx_rx_buf_next(rx_queue, rx_buf);
} while (--num_bufs);
}
void efx_siena_rx_slow_fill(struct timer_list *t)
{
struct efx_rx_queue *rx_queue = from_timer(rx_queue, t, slow_fill);
/* Post an event to cause NAPI to run and refill the queue */
efx_nic_generate_fill_event(rx_queue);
++rx_queue->slow_fill_count;
}
static void efx_schedule_slow_fill(struct efx_rx_queue *rx_queue)
{
mod_timer(&rx_queue->slow_fill, jiffies + msecs_to_jiffies(10));
}
/* efx_init_rx_buffers - create EFX_RX_BATCH page-based RX buffers
*
* @rx_queue: Efx RX queue
*
* This allocates a batch of pages, maps them for DMA, and populates
* struct efx_rx_buffers for each one. Return a negative error code or
* 0 on success. If a single page can be used for multiple buffers,
* then the page will either be inserted fully, or not at all.
*/
static int efx_init_rx_buffers(struct efx_rx_queue *rx_queue, bool atomic)
{
unsigned int page_offset, index, count;
struct efx_nic *efx = rx_queue->efx;
struct efx_rx_page_state *state;
struct efx_rx_buffer *rx_buf;
dma_addr_t dma_addr;
struct page *page;
count = 0;
do {
page = efx_reuse_page(rx_queue);
if (page == NULL) {
page = alloc_pages(__GFP_COMP |
(atomic ? GFP_ATOMIC : GFP_KERNEL),
efx->rx_buffer_order);
if (unlikely(page == NULL))
return -ENOMEM;
dma_addr =
dma_map_page(&efx->pci_dev->dev, page, 0,
PAGE_SIZE << efx->rx_buffer_order,
DMA_FROM_DEVICE);
if (unlikely(dma_mapping_error(&efx->pci_dev->dev,
dma_addr))) {
__free_pages(page, efx->rx_buffer_order);
return -EIO;
}
state = page_address(page);
state->dma_addr = dma_addr;
} else {
state = page_address(page);
dma_addr = state->dma_addr;
}
dma_addr += sizeof(struct efx_rx_page_state);
page_offset = sizeof(struct efx_rx_page_state);
do {
index = rx_queue->added_count & rx_queue->ptr_mask;
rx_buf = efx_rx_buffer(rx_queue, index);
rx_buf->dma_addr = dma_addr + efx->rx_ip_align +
EFX_XDP_HEADROOM;
rx_buf->page = page;
rx_buf->page_offset = page_offset + efx->rx_ip_align +
EFX_XDP_HEADROOM;
rx_buf->len = efx->rx_dma_len;
rx_buf->flags = 0;
++rx_queue->added_count;
get_page(page);
dma_addr += efx->rx_page_buf_step;
page_offset += efx->rx_page_buf_step;
} while (page_offset + efx->rx_page_buf_step <= PAGE_SIZE);
rx_buf->flags = EFX_RX_BUF_LAST_IN_PAGE;
} while (++count < efx->rx_pages_per_batch);
return 0;
}
void efx_siena_rx_config_page_split(struct efx_nic *efx)
{
efx->rx_page_buf_step = ALIGN(efx->rx_dma_len + efx->rx_ip_align +
EFX_XDP_HEADROOM + EFX_XDP_TAILROOM,
EFX_RX_BUF_ALIGNMENT);
efx->rx_bufs_per_page = efx->rx_buffer_order ? 1 :
((PAGE_SIZE - sizeof(struct efx_rx_page_state)) /
efx->rx_page_buf_step);
efx->rx_buffer_truesize = (PAGE_SIZE << efx->rx_buffer_order) /
efx->rx_bufs_per_page;
efx->rx_pages_per_batch = DIV_ROUND_UP(EFX_RX_PREFERRED_BATCH,
efx->rx_bufs_per_page);
}
/* efx_siena_fast_push_rx_descriptors - push new RX descriptors quickly
* @rx_queue: RX descriptor queue
*
* This will aim to fill the RX descriptor queue up to
* @rx_queue->@max_fill. If there is insufficient atomic
* memory to do so, a slow fill will be scheduled.
*
* The caller must provide serialisation (none is used here). In practise,
* this means this function must run from the NAPI handler, or be called
* when NAPI is disabled.
*/
void efx_siena_fast_push_rx_descriptors(struct efx_rx_queue *rx_queue,
bool atomic)
{
struct efx_nic *efx = rx_queue->efx;
unsigned int fill_level, batch_size;
int space, rc = 0;
if (!rx_queue->refill_enabled)
return;
/* Calculate current fill level, and exit if we don't need to fill */
fill_level = (rx_queue->added_count - rx_queue->removed_count);
EFX_WARN_ON_ONCE_PARANOID(fill_level > rx_queue->efx->rxq_entries);
if (fill_level >= rx_queue->fast_fill_trigger)
goto out;
/* Record minimum fill level */
if (unlikely(fill_level < rx_queue->min_fill)) {
if (fill_level)
rx_queue->min_fill = fill_level;
}
batch_size = efx->rx_pages_per_batch * efx->rx_bufs_per_page;
space = rx_queue->max_fill - fill_level;
EFX_WARN_ON_ONCE_PARANOID(space < batch_size);
netif_vdbg(rx_queue->efx, rx_status, rx_queue->efx->net_dev,
"RX queue %d fast-filling descriptor ring from"
" level %d to level %d\n",
efx_rx_queue_index(rx_queue), fill_level,
rx_queue->max_fill);
do {
rc = efx_init_rx_buffers(rx_queue, atomic);
if (unlikely(rc)) {
/* Ensure that we don't leave the rx queue empty */
efx_schedule_slow_fill(rx_queue);
goto out;
}
} while ((space -= batch_size) >= batch_size);
netif_vdbg(rx_queue->efx, rx_status, rx_queue->efx->net_dev,
"RX queue %d fast-filled descriptor ring "
"to level %d\n", efx_rx_queue_index(rx_queue),
rx_queue->added_count - rx_queue->removed_count);
out:
if (rx_queue->notified_count != rx_queue->added_count)
efx_nic_notify_rx_desc(rx_queue);
}
/* Pass a received packet up through GRO. GRO can handle pages
* regardless of checksum state and skbs with a good checksum.
*/
void
efx_siena_rx_packet_gro(struct efx_channel *channel,
struct efx_rx_buffer *rx_buf,
unsigned int n_frags, u8 *eh, __wsum csum)
{
struct napi_struct *napi = &channel->napi_str;
struct efx_nic *efx = channel->efx;
struct sk_buff *skb;
skb = napi_get_frags(napi);
if (unlikely(!skb)) {
struct efx_rx_queue *rx_queue;
rx_queue = efx_channel_get_rx_queue(channel);
efx_siena_free_rx_buffers(rx_queue, rx_buf, n_frags);
return;
}
if (efx->net_dev->features & NETIF_F_RXHASH)
skb_set_hash(skb, efx_rx_buf_hash(efx, eh),
PKT_HASH_TYPE_L3);
if (csum) {
skb->csum = csum;
skb->ip_summed = CHECKSUM_COMPLETE;
} else {
skb->ip_summed = ((rx_buf->flags & EFX_RX_PKT_CSUMMED) ?
CHECKSUM_UNNECESSARY : CHECKSUM_NONE);
}
skb->csum_level = !!(rx_buf->flags & EFX_RX_PKT_CSUM_LEVEL);
for (;;) {
skb_fill_page_desc(skb, skb_shinfo(skb)->nr_frags,
rx_buf->page, rx_buf->page_offset,
rx_buf->len);
rx_buf->page = NULL;
skb->len += rx_buf->len;
if (skb_shinfo(skb)->nr_frags == n_frags)
break;
rx_buf = efx_rx_buf_next(&channel->rx_queue, rx_buf);
}
skb->data_len = skb->len;
skb->truesize += n_frags * efx->rx_buffer_truesize;
skb_record_rx_queue(skb, channel->rx_queue.core_index);
napi_gro_frags(napi);
}
/* RSS contexts. We're using linked lists and crappy O(n) algorithms, because
* (a) this is an infrequent control-plane operation and (b) n is small (max 64)
*/
struct efx_rss_context *efx_siena_alloc_rss_context_entry(struct efx_nic *efx)
{
struct list_head *head = &efx->rss_context.list;
struct efx_rss_context *ctx, *new;
u32 id = 1; /* Don't use zero, that refers to the master RSS context */
WARN_ON(!mutex_is_locked(&efx->rss_lock));
/* Search for first gap in the numbering */
list_for_each_entry(ctx, head, list) {
if (ctx->user_id != id)
break;
id++;
/* Check for wrap. If this happens, we have nearly 2^32
* allocated RSS contexts, which seems unlikely.
*/
if (WARN_ON_ONCE(!id))
return NULL;
}
/* Create the new entry */
new = kmalloc(sizeof(*new), GFP_KERNEL);
if (!new)
return NULL;
new->context_id = EFX_MCDI_RSS_CONTEXT_INVALID;
new->rx_hash_udp_4tuple = false;
/* Insert the new entry into the gap */
new->user_id = id;
list_add_tail(&new->list, &ctx->list);
return new;
}
struct efx_rss_context *efx_siena_find_rss_context_entry(struct efx_nic *efx,
u32 id)
{
struct list_head *head = &efx->rss_context.list;
struct efx_rss_context *ctx;
WARN_ON(!mutex_is_locked(&efx->rss_lock));
list_for_each_entry(ctx, head, list)
if (ctx->user_id == id)
return ctx;
return NULL;
}
void efx_siena_free_rss_context_entry(struct efx_rss_context *ctx)
{
list_del(&ctx->list);
kfree(ctx);
}
void efx_siena_set_default_rx_indir_table(struct efx_nic *efx,
struct efx_rss_context *ctx)
{
size_t i;
for (i = 0; i < ARRAY_SIZE(ctx->rx_indir_table); i++)
ctx->rx_indir_table[i] =
ethtool_rxfh_indir_default(i, efx->rss_spread);
}
/**
* efx_siena_filter_is_mc_recipient - test whether spec is a multicast recipient
* @spec: Specification to test
*
* Return: %true if the specification is a non-drop RX filter that
* matches a local MAC address I/G bit value of 1 or matches a local
* IPv4 or IPv6 address value in the respective multicast address
* range. Otherwise %false.
*/
bool efx_siena_filter_is_mc_recipient(const struct efx_filter_spec *spec)
{
if (!(spec->flags & EFX_FILTER_FLAG_RX) ||
spec->dmaq_id == EFX_FILTER_RX_DMAQ_ID_DROP)
return false;
if (spec->match_flags &
(EFX_FILTER_MATCH_LOC_MAC | EFX_FILTER_MATCH_LOC_MAC_IG) &&
is_multicast_ether_addr(spec->loc_mac))
return true;
if ((spec->match_flags &
(EFX_FILTER_MATCH_ETHER_TYPE | EFX_FILTER_MATCH_LOC_HOST)) ==
(EFX_FILTER_MATCH_ETHER_TYPE | EFX_FILTER_MATCH_LOC_HOST)) {
if (spec->ether_type == htons(ETH_P_IP) &&
ipv4_is_multicast(spec->loc_host[0]))
return true;
if (spec->ether_type == htons(ETH_P_IPV6) &&
((const u8 *)spec->loc_host)[0] == 0xff)
return true;
}
return false;
}
bool efx_siena_filter_spec_equal(const struct efx_filter_spec *left,
const struct efx_filter_spec *right)
{
if ((left->match_flags ^ right->match_flags) |
((left->flags ^ right->flags) &
(EFX_FILTER_FLAG_RX | EFX_FILTER_FLAG_TX)))
return false;
return memcmp(&left->outer_vid, &right->outer_vid,
sizeof(struct efx_filter_spec) -
offsetof(struct efx_filter_spec, outer_vid)) == 0;
}
u32 efx_siena_filter_spec_hash(const struct efx_filter_spec *spec)
{
BUILD_BUG_ON(offsetof(struct efx_filter_spec, outer_vid) & 3);
return jhash2((const u32 *)&spec->outer_vid,
(sizeof(struct efx_filter_spec) -
offsetof(struct efx_filter_spec, outer_vid)) / 4,
0);
}
#ifdef CONFIG_RFS_ACCEL
bool efx_siena_rps_check_rule(struct efx_arfs_rule *rule,
unsigned int filter_idx, bool *force)
{
if (rule->filter_id == EFX_ARFS_FILTER_ID_PENDING) {
/* ARFS is currently updating this entry, leave it */
return false;
}
if (rule->filter_id == EFX_ARFS_FILTER_ID_ERROR) {
/* ARFS tried and failed to update this, so it's probably out
* of date. Remove the filter and the ARFS rule entry.
*/
rule->filter_id = EFX_ARFS_FILTER_ID_REMOVING;
*force = true;
return true;
} else if (WARN_ON(rule->filter_id != filter_idx)) { /* can't happen */
/* ARFS has moved on, so old filter is not needed. Since we did
* not mark the rule with EFX_ARFS_FILTER_ID_REMOVING, it will
* not be removed by efx_siena_rps_hash_del() subsequently.
*/
*force = true;
return true;
}
/* Remove it iff ARFS wants to. */
return true;
}
static
struct hlist_head *efx_rps_hash_bucket(struct efx_nic *efx,
const struct efx_filter_spec *spec)
{
u32 hash = efx_siena_filter_spec_hash(spec);
lockdep_assert_held(&efx->rps_hash_lock);
if (!efx->rps_hash_table)
return NULL;
return &efx->rps_hash_table[hash % EFX_ARFS_HASH_TABLE_SIZE];
}
struct efx_arfs_rule *efx_siena_rps_hash_find(struct efx_nic *efx,
const struct efx_filter_spec *spec)
{
struct efx_arfs_rule *rule;
struct hlist_head *head;
struct hlist_node *node;
head = efx_rps_hash_bucket(efx, spec);
if (!head)
return NULL;
hlist_for_each(node, head) {
rule = container_of(node, struct efx_arfs_rule, node);
if (efx_siena_filter_spec_equal(spec, &rule->spec))
return rule;
}
return NULL;
}
static struct efx_arfs_rule *efx_rps_hash_add(struct efx_nic *efx,
const struct efx_filter_spec *spec,
bool *new)
{
struct efx_arfs_rule *rule;
struct hlist_head *head;
struct hlist_node *node;
head = efx_rps_hash_bucket(efx, spec);
if (!head)
return NULL;
hlist_for_each(node, head) {
rule = container_of(node, struct efx_arfs_rule, node);
if (efx_siena_filter_spec_equal(spec, &rule->spec)) {
*new = false;
return rule;
}
}
rule = kmalloc(sizeof(*rule), GFP_ATOMIC);
*new = true;
if (rule) {
memcpy(&rule->spec, spec, sizeof(rule->spec));
hlist_add_head(&rule->node, head);
}
return rule;
}
void efx_siena_rps_hash_del(struct efx_nic *efx,
const struct efx_filter_spec *spec)
{
struct efx_arfs_rule *rule;
struct hlist_head *head;
struct hlist_node *node;
head = efx_rps_hash_bucket(efx, spec);
if (WARN_ON(!head))
return;
hlist_for_each(node, head) {
rule = container_of(node, struct efx_arfs_rule, node);
if (efx_siena_filter_spec_equal(spec, &rule->spec)) {
/* Someone already reused the entry. We know that if
* this check doesn't fire (i.e. filter_id == REMOVING)
* then the REMOVING mark was put there by our caller,
* because caller is holding a lock on filter table and
* only holders of that lock set REMOVING.
*/
if (rule->filter_id != EFX_ARFS_FILTER_ID_REMOVING)
return;
hlist_del(node);
kfree(rule);
return;
}
}
/* We didn't find it. */
WARN_ON(1);
}
#endif
int efx_siena_probe_filters(struct efx_nic *efx)
{
int rc;
mutex_lock(&efx->mac_lock);
down_write(&efx->filter_sem);
rc = efx->type->filter_table_probe(efx);
if (rc)
goto out_unlock;
#ifdef CONFIG_RFS_ACCEL
if (efx->type->offload_features & NETIF_F_NTUPLE) {
struct efx_channel *channel;
int i, success = 1;
efx_for_each_channel(channel, efx) {
channel->rps_flow_id =
kcalloc(efx->type->max_rx_ip_filters,
sizeof(*channel->rps_flow_id),
GFP_KERNEL);
if (!channel->rps_flow_id)
success = 0;
else
for (i = 0;
i < efx->type->max_rx_ip_filters;
++i)
channel->rps_flow_id[i] =
RPS_FLOW_ID_INVALID;
channel->rfs_expire_index = 0;
channel->rfs_filter_count = 0;
}
if (!success) {
efx_for_each_channel(channel, efx)
kfree(channel->rps_flow_id);
efx->type->filter_table_remove(efx);
rc = -ENOMEM;
goto out_unlock;
}
}
#endif
out_unlock:
up_write(&efx->filter_sem);
mutex_unlock(&efx->mac_lock);
return rc;
}
void efx_siena_remove_filters(struct efx_nic *efx)
{
#ifdef CONFIG_RFS_ACCEL
struct efx_channel *channel;
efx_for_each_channel(channel, efx) {
cancel_delayed_work_sync(&channel->filter_work);
kfree(channel->rps_flow_id);
channel->rps_flow_id = NULL;
}
#endif
down_write(&efx->filter_sem);
efx->type->filter_table_remove(efx);
up_write(&efx->filter_sem);
}
#ifdef CONFIG_RFS_ACCEL
static void efx_filter_rfs_work(struct work_struct *data)
{
struct efx_async_filter_insertion *req = container_of(data, struct efx_async_filter_insertion,
work);
struct efx_nic *efx = netdev_priv(req->net_dev);
struct efx_channel *channel = efx_get_channel(efx, req->rxq_index);
int slot_idx = req - efx->rps_slot;
struct efx_arfs_rule *rule;
u16 arfs_id = 0;
int rc;
rc = efx->type->filter_insert(efx, &req->spec, true);
if (rc >= 0)
/* Discard 'priority' part of EF10+ filter ID (mcdi_filters) */
rc %= efx->type->max_rx_ip_filters;
if (efx->rps_hash_table) {
spin_lock_bh(&efx->rps_hash_lock);
rule = efx_siena_rps_hash_find(efx, &req->spec);
/* The rule might have already gone, if someone else's request
* for the same spec was already worked and then expired before
* we got around to our work. In that case we have nothing
* tying us to an arfs_id, meaning that as soon as the filter
* is considered for expiry it will be removed.
*/
if (rule) {
if (rc < 0)
rule->filter_id = EFX_ARFS_FILTER_ID_ERROR;
else
rule->filter_id = rc;
arfs_id = rule->arfs_id;
}
spin_unlock_bh(&efx->rps_hash_lock);
}
if (rc >= 0) {
/* Remember this so we can check whether to expire the filter
* later.
*/
mutex_lock(&efx->rps_mutex);
if (channel->rps_flow_id[rc] == RPS_FLOW_ID_INVALID)
channel->rfs_filter_count++;
channel->rps_flow_id[rc] = req->flow_id;
mutex_unlock(&efx->rps_mutex);
if (req->spec.ether_type == htons(ETH_P_IP))
netif_info(efx, rx_status, efx->net_dev,
"steering %s %pI4:%u:%pI4:%u to queue %u [flow %u filter %d id %u]\n",
(req->spec.ip_proto == IPPROTO_TCP) ? "TCP" : "UDP",
req->spec.rem_host, ntohs(req->spec.rem_port),
req->spec.loc_host, ntohs(req->spec.loc_port),
req->rxq_index, req->flow_id, rc, arfs_id);
else
netif_info(efx, rx_status, efx->net_dev,
"steering %s [%pI6]:%u:[%pI6]:%u to queue %u [flow %u filter %d id %u]\n",
(req->spec.ip_proto == IPPROTO_TCP) ? "TCP" : "UDP",
req->spec.rem_host, ntohs(req->spec.rem_port),
req->spec.loc_host, ntohs(req->spec.loc_port),
req->rxq_index, req->flow_id, rc, arfs_id);
channel->n_rfs_succeeded++;
} else {
if (req->spec.ether_type == htons(ETH_P_IP))
netif_dbg(efx, rx_status, efx->net_dev,
"failed to steer %s %pI4:%u:%pI4:%u to queue %u [flow %u rc %d id %u]\n",
(req->spec.ip_proto == IPPROTO_TCP) ? "TCP" : "UDP",
req->spec.rem_host, ntohs(req->spec.rem_port),
req->spec.loc_host, ntohs(req->spec.loc_port),
req->rxq_index, req->flow_id, rc, arfs_id);
else
netif_dbg(efx, rx_status, efx->net_dev,
"failed to steer %s [%pI6]:%u:[%pI6]:%u to queue %u [flow %u rc %d id %u]\n",
(req->spec.ip_proto == IPPROTO_TCP) ? "TCP" : "UDP",
req->spec.rem_host, ntohs(req->spec.rem_port),
req->spec.loc_host, ntohs(req->spec.loc_port),
req->rxq_index, req->flow_id, rc, arfs_id);
channel->n_rfs_failed++;
/* We're overloading the NIC's filter tables, so let's do a
* chunk of extra expiry work.
*/
__efx_siena_filter_rfs_expire(channel,
min(channel->rfs_filter_count,
100u));
}
/* Release references */
clear_bit(slot_idx, &efx->rps_slot_map);
dev_put(req->net_dev);
}
int efx_siena_filter_rfs(struct net_device *net_dev, const struct sk_buff *skb,
u16 rxq_index, u32 flow_id)
{
struct efx_nic *efx = netdev_priv(net_dev);
struct efx_async_filter_insertion *req;
struct efx_arfs_rule *rule;
struct flow_keys fk;
int slot_idx;
bool new;
int rc;
/* find a free slot */
for (slot_idx = 0; slot_idx < EFX_RPS_MAX_IN_FLIGHT; slot_idx++)
if (!test_and_set_bit(slot_idx, &efx->rps_slot_map))
break;
if (slot_idx >= EFX_RPS_MAX_IN_FLIGHT)
return -EBUSY;
if (flow_id == RPS_FLOW_ID_INVALID) {
rc = -EINVAL;
goto out_clear;
}
if (!skb_flow_dissect_flow_keys(skb, &fk, 0)) {
rc = -EPROTONOSUPPORT;
goto out_clear;
}
if (fk.basic.n_proto != htons(ETH_P_IP) && fk.basic.n_proto != htons(ETH_P_IPV6)) {
rc = -EPROTONOSUPPORT;
goto out_clear;
}
if (fk.control.flags & FLOW_DIS_IS_FRAGMENT) {
rc = -EPROTONOSUPPORT;
goto out_clear;
}
req = efx->rps_slot + slot_idx;
efx_filter_init_rx(&req->spec, EFX_FILTER_PRI_HINT,
efx->rx_scatter ? EFX_FILTER_FLAG_RX_SCATTER : 0,
rxq_index);
req->spec.match_flags =
EFX_FILTER_MATCH_ETHER_TYPE | EFX_FILTER_MATCH_IP_PROTO |
EFX_FILTER_MATCH_LOC_HOST | EFX_FILTER_MATCH_LOC_PORT |
EFX_FILTER_MATCH_REM_HOST | EFX_FILTER_MATCH_REM_PORT;
req->spec.ether_type = fk.basic.n_proto;
req->spec.ip_proto = fk.basic.ip_proto;
if (fk.basic.n_proto == htons(ETH_P_IP)) {
req->spec.rem_host[0] = fk.addrs.v4addrs.src;
req->spec.loc_host[0] = fk.addrs.v4addrs.dst;
} else {
memcpy(req->spec.rem_host, &fk.addrs.v6addrs.src,
sizeof(struct in6_addr));
memcpy(req->spec.loc_host, &fk.addrs.v6addrs.dst,
sizeof(struct in6_addr));
}
req->spec.rem_port = fk.ports.src;
req->spec.loc_port = fk.ports.dst;
if (efx->rps_hash_table) {
/* Add it to ARFS hash table */
spin_lock(&efx->rps_hash_lock);
rule = efx_rps_hash_add(efx, &req->spec, &new);
if (!rule) {
rc = -ENOMEM;
goto out_unlock;
}
if (new)
rule->arfs_id = efx->rps_next_id++ % RPS_NO_FILTER;
rc = rule->arfs_id;
/* Skip if existing or pending filter already does the right thing */
if (!new && rule->rxq_index == rxq_index &&
rule->filter_id >= EFX_ARFS_FILTER_ID_PENDING)
goto out_unlock;
rule->rxq_index = rxq_index;
rule->filter_id = EFX_ARFS_FILTER_ID_PENDING;
spin_unlock(&efx->rps_hash_lock);
} else {
/* Without an ARFS hash table, we just use arfs_id 0 for all
* filters. This means if multiple flows hash to the same
* flow_id, all but the most recently touched will be eligible
* for expiry.
*/
rc = 0;
}
/* Queue the request */
dev_hold(req->net_dev = net_dev);
INIT_WORK(&req->work, efx_filter_rfs_work);
req->rxq_index = rxq_index;
req->flow_id = flow_id;
schedule_work(&req->work);
return rc;
out_unlock:
spin_unlock(&efx->rps_hash_lock);
out_clear:
clear_bit(slot_idx, &efx->rps_slot_map);
return rc;
}
bool __efx_siena_filter_rfs_expire(struct efx_channel *channel,
unsigned int quota)
{
bool (*expire_one)(struct efx_nic *efx, u32 flow_id, unsigned int index);
struct efx_nic *efx = channel->efx;
unsigned int index, size, start;
u32 flow_id;
if (!mutex_trylock(&efx->rps_mutex))
return false;
expire_one = efx->type->filter_rfs_expire_one;
index = channel->rfs_expire_index;
start = index;
size = efx->type->max_rx_ip_filters;
while (quota) {
flow_id = channel->rps_flow_id[index];
if (flow_id != RPS_FLOW_ID_INVALID) {
quota--;
if (expire_one(efx, flow_id, index)) {
netif_info(efx, rx_status, efx->net_dev,
"expired filter %d [channel %u flow %u]\n",
index, channel->channel, flow_id);
channel->rps_flow_id[index] = RPS_FLOW_ID_INVALID;
channel->rfs_filter_count--;
}
}
if (++index == size)
index = 0;
/* If we were called with a quota that exceeds the total number
* of filters in the table (which shouldn't happen, but could
* if two callers race), ensure that we don't loop forever -
* stop when we've examined every row of the table.
*/
if (index == start)
break;
}
channel->rfs_expire_index = index;
mutex_unlock(&efx->rps_mutex);
return true;
}
#endif /* CONFIG_RFS_ACCEL */
|
linux-master
|
drivers/net/ethernet/sfc/siena/rx_common.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2005-2006 Fen Systems Ltd.
* Copyright 2006-2013 Solarflare Communications Inc.
*/
#include <linux/netdevice.h>
#include <linux/ethtool.h>
#include <linux/rtnetlink.h>
#include <linux/in.h>
#include "net_driver.h"
#include "workarounds.h"
#include "selftest.h"
#include "efx.h"
#include "efx_channels.h"
#include "rx_common.h"
#include "tx_common.h"
#include "ethtool_common.h"
#include "filter.h"
#include "nic.h"
#define EFX_ETHTOOL_EEPROM_MAGIC 0xEFAB
/**************************************************************************
*
* Ethtool operations
*
**************************************************************************
*/
/* Identify device by flashing LEDs */
static int efx_ethtool_phys_id(struct net_device *net_dev,
enum ethtool_phys_id_state state)
{
struct efx_nic *efx = netdev_priv(net_dev);
enum efx_led_mode mode = EFX_LED_DEFAULT;
switch (state) {
case ETHTOOL_ID_ON:
mode = EFX_LED_ON;
break;
case ETHTOOL_ID_OFF:
mode = EFX_LED_OFF;
break;
case ETHTOOL_ID_INACTIVE:
mode = EFX_LED_DEFAULT;
break;
case ETHTOOL_ID_ACTIVE:
return 1; /* cycle on/off once per second */
}
return efx_siena_mcdi_set_id_led(efx, mode);
}
static int efx_ethtool_get_regs_len(struct net_device *net_dev)
{
return efx_siena_get_regs_len(netdev_priv(net_dev));
}
static void efx_ethtool_get_regs(struct net_device *net_dev,
struct ethtool_regs *regs, void *buf)
{
struct efx_nic *efx = netdev_priv(net_dev);
regs->version = efx->type->revision;
efx_siena_get_regs(efx, buf);
}
/*
* Each channel has a single IRQ and moderation timer, started by any
* completion (or other event). Unless the module parameter
* separate_tx_channels is set, IRQs and moderation are therefore
* shared between RX and TX completions. In this case, when RX IRQ
* moderation is explicitly changed then TX IRQ moderation is
* automatically changed too, but otherwise we fail if the two values
* are requested to be different.
*
* The hardware does not support a limit on the number of completions
* before an IRQ, so we do not use the max_frames fields. We should
* report and require that max_frames == (usecs != 0), but this would
* invalidate existing user documentation.
*
* The hardware does not have distinct settings for interrupt
* moderation while the previous IRQ is being handled, so we should
* not use the 'irq' fields. However, an earlier developer
* misunderstood the meaning of the 'irq' fields and the driver did
* not support the standard fields. To avoid invalidating existing
* user documentation, we report and accept changes through either the
* standard or 'irq' fields. If both are changed at the same time, we
* prefer the standard field.
*
* We implement adaptive IRQ moderation, but use a different algorithm
* from that assumed in the definition of struct ethtool_coalesce.
* Therefore we do not use any of the adaptive moderation parameters
* in it.
*/
static int efx_ethtool_get_coalesce(struct net_device *net_dev,
struct ethtool_coalesce *coalesce,
struct kernel_ethtool_coalesce *kernel_coal,
struct netlink_ext_ack *extack)
{
struct efx_nic *efx = netdev_priv(net_dev);
unsigned int tx_usecs, rx_usecs;
bool rx_adaptive;
efx_siena_get_irq_moderation(efx, &tx_usecs, &rx_usecs, &rx_adaptive);
coalesce->tx_coalesce_usecs = tx_usecs;
coalesce->tx_coalesce_usecs_irq = tx_usecs;
coalesce->rx_coalesce_usecs = rx_usecs;
coalesce->rx_coalesce_usecs_irq = rx_usecs;
coalesce->use_adaptive_rx_coalesce = rx_adaptive;
return 0;
}
static int efx_ethtool_set_coalesce(struct net_device *net_dev,
struct ethtool_coalesce *coalesce,
struct kernel_ethtool_coalesce *kernel_coal,
struct netlink_ext_ack *extack)
{
struct efx_nic *efx = netdev_priv(net_dev);
struct efx_channel *channel;
unsigned int tx_usecs, rx_usecs;
bool adaptive, rx_may_override_tx;
int rc;
efx_siena_get_irq_moderation(efx, &tx_usecs, &rx_usecs, &adaptive);
if (coalesce->rx_coalesce_usecs != rx_usecs)
rx_usecs = coalesce->rx_coalesce_usecs;
else
rx_usecs = coalesce->rx_coalesce_usecs_irq;
adaptive = coalesce->use_adaptive_rx_coalesce;
/* If channels are shared, TX IRQ moderation can be quietly
* overridden unless it is changed from its old value.
*/
rx_may_override_tx = (coalesce->tx_coalesce_usecs == tx_usecs &&
coalesce->tx_coalesce_usecs_irq == tx_usecs);
if (coalesce->tx_coalesce_usecs != tx_usecs)
tx_usecs = coalesce->tx_coalesce_usecs;
else
tx_usecs = coalesce->tx_coalesce_usecs_irq;
rc = efx_siena_init_irq_moderation(efx, tx_usecs, rx_usecs, adaptive,
rx_may_override_tx);
if (rc != 0)
return rc;
efx_for_each_channel(channel, efx)
efx->type->push_irq_moderation(channel);
return 0;
}
static void
efx_ethtool_get_ringparam(struct net_device *net_dev,
struct ethtool_ringparam *ring,
struct kernel_ethtool_ringparam *kernel_ring,
struct netlink_ext_ack *extack)
{
struct efx_nic *efx = netdev_priv(net_dev);
ring->rx_max_pending = EFX_MAX_DMAQ_SIZE;
ring->tx_max_pending = EFX_TXQ_MAX_ENT(efx);
ring->rx_pending = efx->rxq_entries;
ring->tx_pending = efx->txq_entries;
}
static int
efx_ethtool_set_ringparam(struct net_device *net_dev,
struct ethtool_ringparam *ring,
struct kernel_ethtool_ringparam *kernel_ring,
struct netlink_ext_ack *extack)
{
struct efx_nic *efx = netdev_priv(net_dev);
u32 txq_entries;
if (ring->rx_mini_pending || ring->rx_jumbo_pending ||
ring->rx_pending > EFX_MAX_DMAQ_SIZE ||
ring->tx_pending > EFX_TXQ_MAX_ENT(efx))
return -EINVAL;
if (ring->rx_pending < EFX_RXQ_MIN_ENT) {
netif_err(efx, drv, efx->net_dev,
"RX queues cannot be smaller than %u\n",
EFX_RXQ_MIN_ENT);
return -EINVAL;
}
txq_entries = max(ring->tx_pending, EFX_TXQ_MIN_ENT(efx));
if (txq_entries != ring->tx_pending)
netif_warn(efx, drv, efx->net_dev,
"increasing TX queue size to minimum of %u\n",
txq_entries);
return efx_siena_realloc_channels(efx, ring->rx_pending, txq_entries);
}
static void efx_ethtool_get_wol(struct net_device *net_dev,
struct ethtool_wolinfo *wol)
{
struct efx_nic *efx = netdev_priv(net_dev);
return efx->type->get_wol(efx, wol);
}
static int efx_ethtool_set_wol(struct net_device *net_dev,
struct ethtool_wolinfo *wol)
{
struct efx_nic *efx = netdev_priv(net_dev);
return efx->type->set_wol(efx, wol->wolopts);
}
static void efx_ethtool_get_fec_stats(struct net_device *net_dev,
struct ethtool_fec_stats *fec_stats)
{
struct efx_nic *efx = netdev_priv(net_dev);
if (efx->type->get_fec_stats)
efx->type->get_fec_stats(efx, fec_stats);
}
static int efx_ethtool_get_ts_info(struct net_device *net_dev,
struct ethtool_ts_info *ts_info)
{
struct efx_nic *efx = netdev_priv(net_dev);
/* Software capabilities */
ts_info->so_timestamping = (SOF_TIMESTAMPING_RX_SOFTWARE |
SOF_TIMESTAMPING_SOFTWARE);
ts_info->phc_index = -1;
efx_siena_ptp_get_ts_info(efx, ts_info);
return 0;
}
const struct ethtool_ops efx_siena_ethtool_ops = {
.supported_coalesce_params = ETHTOOL_COALESCE_USECS |
ETHTOOL_COALESCE_USECS_IRQ |
ETHTOOL_COALESCE_USE_ADAPTIVE_RX,
.get_drvinfo = efx_siena_ethtool_get_drvinfo,
.get_regs_len = efx_ethtool_get_regs_len,
.get_regs = efx_ethtool_get_regs,
.get_msglevel = efx_siena_ethtool_get_msglevel,
.set_msglevel = efx_siena_ethtool_set_msglevel,
.get_link = ethtool_op_get_link,
.get_coalesce = efx_ethtool_get_coalesce,
.set_coalesce = efx_ethtool_set_coalesce,
.get_ringparam = efx_ethtool_get_ringparam,
.set_ringparam = efx_ethtool_set_ringparam,
.get_pauseparam = efx_siena_ethtool_get_pauseparam,
.set_pauseparam = efx_siena_ethtool_set_pauseparam,
.get_sset_count = efx_siena_ethtool_get_sset_count,
.self_test = efx_siena_ethtool_self_test,
.get_strings = efx_siena_ethtool_get_strings,
.set_phys_id = efx_ethtool_phys_id,
.get_ethtool_stats = efx_siena_ethtool_get_stats,
.get_wol = efx_ethtool_get_wol,
.set_wol = efx_ethtool_set_wol,
.reset = efx_siena_ethtool_reset,
.get_rxnfc = efx_siena_ethtool_get_rxnfc,
.set_rxnfc = efx_siena_ethtool_set_rxnfc,
.get_rxfh_indir_size = efx_siena_ethtool_get_rxfh_indir_size,
.get_rxfh_key_size = efx_siena_ethtool_get_rxfh_key_size,
.get_rxfh = efx_siena_ethtool_get_rxfh,
.set_rxfh = efx_siena_ethtool_set_rxfh,
.get_rxfh_context = efx_siena_ethtool_get_rxfh_context,
.set_rxfh_context = efx_siena_ethtool_set_rxfh_context,
.get_ts_info = efx_ethtool_get_ts_info,
.get_module_info = efx_siena_ethtool_get_module_info,
.get_module_eeprom = efx_siena_ethtool_get_module_eeprom,
.get_link_ksettings = efx_siena_ethtool_get_link_ksettings,
.set_link_ksettings = efx_siena_ethtool_set_link_ksettings,
.get_fec_stats = efx_ethtool_get_fec_stats,
.get_fecparam = efx_siena_ethtool_get_fecparam,
.set_fecparam = efx_siena_ethtool_set_fecparam,
};
|
linux-master
|
drivers/net/ethernet/sfc/siena/ethtool.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2005-2006 Fen Systems Ltd.
* Copyright 2006-2013 Solarflare Communications Inc.
*/
#include <linux/module.h>
#include <linux/mtd/mtd.h>
#include <linux/slab.h>
#include <linux/rtnetlink.h>
#include "net_driver.h"
#include "efx.h"
#define to_efx_mtd_partition(mtd) \
container_of(mtd, struct efx_mtd_partition, mtd)
/* MTD interface */
static int efx_mtd_erase(struct mtd_info *mtd, struct erase_info *erase)
{
struct efx_nic *efx = mtd->priv;
return efx->type->mtd_erase(mtd, erase->addr, erase->len);
}
static void efx_mtd_sync(struct mtd_info *mtd)
{
struct efx_mtd_partition *part = to_efx_mtd_partition(mtd);
struct efx_nic *efx = mtd->priv;
int rc;
rc = efx->type->mtd_sync(mtd);
if (rc)
pr_err("%s: %s sync failed (%d)\n",
part->name, part->dev_type_name, rc);
}
static void efx_siena_mtd_remove_partition(struct efx_mtd_partition *part)
{
int rc;
for (;;) {
rc = mtd_device_unregister(&part->mtd);
if (rc != -EBUSY)
break;
ssleep(1);
}
WARN_ON(rc);
list_del(&part->node);
}
int efx_siena_mtd_add(struct efx_nic *efx, struct efx_mtd_partition *parts,
size_t n_parts, size_t sizeof_part)
{
struct efx_mtd_partition *part;
size_t i;
for (i = 0; i < n_parts; i++) {
part = (struct efx_mtd_partition *)((char *)parts +
i * sizeof_part);
part->mtd.writesize = 1;
if (!(part->mtd.flags & MTD_NO_ERASE))
part->mtd.flags |= MTD_WRITEABLE;
part->mtd.owner = THIS_MODULE;
part->mtd.priv = efx;
part->mtd.name = part->name;
part->mtd._erase = efx_mtd_erase;
part->mtd._read = efx->type->mtd_read;
part->mtd._write = efx->type->mtd_write;
part->mtd._sync = efx_mtd_sync;
efx->type->mtd_rename(part);
if (mtd_device_register(&part->mtd, NULL, 0))
goto fail;
/* Add to list in order - efx_siena_mtd_remove() depends on this */
list_add_tail(&part->node, &efx->mtd_list);
}
return 0;
fail:
while (i--) {
part = (struct efx_mtd_partition *)((char *)parts +
i * sizeof_part);
efx_siena_mtd_remove_partition(part);
}
/* Failure is unlikely here, but probably means we're out of memory */
return -ENOMEM;
}
void efx_siena_mtd_remove(struct efx_nic *efx)
{
struct efx_mtd_partition *parts, *part, *next;
WARN_ON(efx_dev_registered(efx));
if (list_empty(&efx->mtd_list))
return;
parts = list_first_entry(&efx->mtd_list, struct efx_mtd_partition,
node);
list_for_each_entry_safe(part, next, &efx->mtd_list, node)
efx_siena_mtd_remove_partition(part);
kfree(parts);
}
void efx_siena_mtd_rename(struct efx_nic *efx)
{
struct efx_mtd_partition *part;
ASSERT_RTNL();
list_for_each_entry(part, &efx->mtd_list, node)
efx->type->mtd_rename(part);
}
|
linux-master
|
drivers/net/ethernet/sfc/siena/mtd.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2005-2006 Fen Systems Ltd.
* Copyright 2006-2013 Solarflare Communications Inc.
*/
#include <linux/bitops.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/module.h>
#include <linux/seq_file.h>
#include <linux/crc32.h>
#include "net_driver.h"
#include "bitfield.h"
#include "efx.h"
#include "rx_common.h"
#include "tx_common.h"
#include "nic.h"
#include "farch_regs.h"
#include "sriov.h"
#include "siena_sriov.h"
#include "io.h"
#include "workarounds.h"
/* Falcon-architecture (SFC9000-family) support */
/**************************************************************************
*
* Configurable values
*
**************************************************************************
*/
/* This is set to 16 for a good reason. In summary, if larger than
* 16, the descriptor cache holds more than a default socket
* buffer's worth of packets (for UDP we can only have at most one
* socket buffer's worth outstanding). This combined with the fact
* that we only get 1 TX event per descriptor cache means the NIC
* goes idle.
*/
#define TX_DC_ENTRIES 16
#define TX_DC_ENTRIES_ORDER 1
#define RX_DC_ENTRIES 64
#define RX_DC_ENTRIES_ORDER 3
/* If EFX_MAX_INT_ERRORS internal errors occur within
* EFX_INT_ERROR_EXPIRE seconds, we consider the NIC broken and
* disable it.
*/
#define EFX_INT_ERROR_EXPIRE 3600
#define EFX_MAX_INT_ERRORS 5
/* Depth of RX flush request fifo */
#define EFX_RX_FLUSH_COUNT 4
/* Driver generated events */
#define _EFX_CHANNEL_MAGIC_TEST 0x000101
#define _EFX_CHANNEL_MAGIC_FILL 0x000102
#define _EFX_CHANNEL_MAGIC_RX_DRAIN 0x000103
#define _EFX_CHANNEL_MAGIC_TX_DRAIN 0x000104
#define _EFX_CHANNEL_MAGIC(_code, _data) ((_code) << 8 | (_data))
#define _EFX_CHANNEL_MAGIC_CODE(_magic) ((_magic) >> 8)
#define EFX_CHANNEL_MAGIC_TEST(_channel) \
_EFX_CHANNEL_MAGIC(_EFX_CHANNEL_MAGIC_TEST, (_channel)->channel)
#define EFX_CHANNEL_MAGIC_FILL(_rx_queue) \
_EFX_CHANNEL_MAGIC(_EFX_CHANNEL_MAGIC_FILL, \
efx_rx_queue_index(_rx_queue))
#define EFX_CHANNEL_MAGIC_RX_DRAIN(_rx_queue) \
_EFX_CHANNEL_MAGIC(_EFX_CHANNEL_MAGIC_RX_DRAIN, \
efx_rx_queue_index(_rx_queue))
#define EFX_CHANNEL_MAGIC_TX_DRAIN(_tx_queue) \
_EFX_CHANNEL_MAGIC(_EFX_CHANNEL_MAGIC_TX_DRAIN, \
(_tx_queue)->queue)
static void efx_farch_magic_event(struct efx_channel *channel, u32 magic);
/**************************************************************************
*
* Hardware access
*
**************************************************************************/
static inline void efx_write_buf_tbl(struct efx_nic *efx, efx_qword_t *value,
unsigned int index)
{
efx_sram_writeq(efx, efx->membase + efx->type->buf_tbl_base,
value, index);
}
static bool efx_masked_compare_oword(const efx_oword_t *a, const efx_oword_t *b,
const efx_oword_t *mask)
{
return ((a->u64[0] ^ b->u64[0]) & mask->u64[0]) ||
((a->u64[1] ^ b->u64[1]) & mask->u64[1]);
}
int efx_farch_test_registers(struct efx_nic *efx,
const struct efx_farch_register_test *regs,
size_t n_regs)
{
unsigned address = 0;
int i, j;
efx_oword_t mask, imask, original, reg, buf;
for (i = 0; i < n_regs; ++i) {
address = regs[i].address;
mask = imask = regs[i].mask;
EFX_INVERT_OWORD(imask);
efx_reado(efx, &original, address);
/* bit sweep on and off */
for (j = 0; j < 128; j++) {
if (!EFX_EXTRACT_OWORD32(mask, j, j))
continue;
/* Test this testable bit can be set in isolation */
EFX_AND_OWORD(reg, original, mask);
EFX_SET_OWORD32(reg, j, j, 1);
efx_writeo(efx, ®, address);
efx_reado(efx, &buf, address);
if (efx_masked_compare_oword(®, &buf, &mask))
goto fail;
/* Test this testable bit can be cleared in isolation */
EFX_OR_OWORD(reg, original, mask);
EFX_SET_OWORD32(reg, j, j, 0);
efx_writeo(efx, ®, address);
efx_reado(efx, &buf, address);
if (efx_masked_compare_oword(®, &buf, &mask))
goto fail;
}
efx_writeo(efx, &original, address);
}
return 0;
fail:
netif_err(efx, hw, efx->net_dev,
"wrote "EFX_OWORD_FMT" read "EFX_OWORD_FMT
" at address 0x%x mask "EFX_OWORD_FMT"\n", EFX_OWORD_VAL(reg),
EFX_OWORD_VAL(buf), address, EFX_OWORD_VAL(mask));
return -EIO;
}
/**************************************************************************
*
* Special buffer handling
* Special buffers are used for event queues and the TX and RX
* descriptor rings.
*
*************************************************************************/
/*
* Initialise a special buffer
*
* This will define a buffer (previously allocated via
* efx_alloc_special_buffer()) in the buffer table, allowing
* it to be used for event queues, descriptor rings etc.
*/
static void
efx_init_special_buffer(struct efx_nic *efx, struct efx_special_buffer *buffer)
{
efx_qword_t buf_desc;
unsigned int index;
dma_addr_t dma_addr;
int i;
EFX_WARN_ON_PARANOID(!buffer->buf.addr);
/* Write buffer descriptors to NIC */
for (i = 0; i < buffer->entries; i++) {
index = buffer->index + i;
dma_addr = buffer->buf.dma_addr + (i * EFX_BUF_SIZE);
netif_dbg(efx, probe, efx->net_dev,
"mapping special buffer %d at %llx\n",
index, (unsigned long long)dma_addr);
EFX_POPULATE_QWORD_3(buf_desc,
FRF_AZ_BUF_ADR_REGION, 0,
FRF_AZ_BUF_ADR_FBUF, dma_addr >> 12,
FRF_AZ_BUF_OWNER_ID_FBUF, 0);
efx_write_buf_tbl(efx, &buf_desc, index);
}
}
/* Unmaps a buffer and clears the buffer table entries */
static void
efx_fini_special_buffer(struct efx_nic *efx, struct efx_special_buffer *buffer)
{
efx_oword_t buf_tbl_upd;
unsigned int start = buffer->index;
unsigned int end = (buffer->index + buffer->entries - 1);
if (!buffer->entries)
return;
netif_dbg(efx, hw, efx->net_dev, "unmapping special buffers %d-%d\n",
buffer->index, buffer->index + buffer->entries - 1);
EFX_POPULATE_OWORD_4(buf_tbl_upd,
FRF_AZ_BUF_UPD_CMD, 0,
FRF_AZ_BUF_CLR_CMD, 1,
FRF_AZ_BUF_CLR_END_ID, end,
FRF_AZ_BUF_CLR_START_ID, start);
efx_writeo(efx, &buf_tbl_upd, FR_AZ_BUF_TBL_UPD);
}
/*
* Allocate a new special buffer
*
* This allocates memory for a new buffer, clears it and allocates a
* new buffer ID range. It does not write into the buffer table.
*
* This call will allocate 4KB buffers, since 8KB buffers can't be
* used for event queues and descriptor rings.
*/
static int efx_alloc_special_buffer(struct efx_nic *efx,
struct efx_special_buffer *buffer,
unsigned int len)
{
#ifdef CONFIG_SFC_SIENA_SRIOV
struct siena_nic_data *nic_data = efx->nic_data;
#endif
len = ALIGN(len, EFX_BUF_SIZE);
if (efx_siena_alloc_buffer(efx, &buffer->buf, len, GFP_KERNEL))
return -ENOMEM;
buffer->entries = len / EFX_BUF_SIZE;
BUG_ON(buffer->buf.dma_addr & (EFX_BUF_SIZE - 1));
/* Select new buffer ID */
buffer->index = efx->next_buffer_table;
efx->next_buffer_table += buffer->entries;
#ifdef CONFIG_SFC_SIENA_SRIOV
BUG_ON(efx_siena_sriov_enabled(efx) &&
nic_data->vf_buftbl_base < efx->next_buffer_table);
#endif
netif_dbg(efx, probe, efx->net_dev,
"allocating special buffers %d-%d at %llx+%x "
"(virt %p phys %llx)\n", buffer->index,
buffer->index + buffer->entries - 1,
(u64)buffer->buf.dma_addr, len,
buffer->buf.addr, (u64)virt_to_phys(buffer->buf.addr));
return 0;
}
static void
efx_free_special_buffer(struct efx_nic *efx, struct efx_special_buffer *buffer)
{
if (!buffer->buf.addr)
return;
netif_dbg(efx, hw, efx->net_dev,
"deallocating special buffers %d-%d at %llx+%x "
"(virt %p phys %llx)\n", buffer->index,
buffer->index + buffer->entries - 1,
(u64)buffer->buf.dma_addr, buffer->buf.len,
buffer->buf.addr, (u64)virt_to_phys(buffer->buf.addr));
efx_siena_free_buffer(efx, &buffer->buf);
buffer->entries = 0;
}
/**************************************************************************
*
* TX path
*
**************************************************************************/
/* This writes to the TX_DESC_WPTR; write pointer for TX descriptor ring */
static inline void efx_farch_notify_tx_desc(struct efx_tx_queue *tx_queue)
{
unsigned write_ptr;
efx_dword_t reg;
write_ptr = tx_queue->write_count & tx_queue->ptr_mask;
EFX_POPULATE_DWORD_1(reg, FRF_AZ_TX_DESC_WPTR_DWORD, write_ptr);
efx_writed_page(tx_queue->efx, ®,
FR_AZ_TX_DESC_UPD_DWORD_P0, tx_queue->queue);
}
/* Write pointer and first descriptor for TX descriptor ring */
static inline void efx_farch_push_tx_desc(struct efx_tx_queue *tx_queue,
const efx_qword_t *txd)
{
unsigned write_ptr;
efx_oword_t reg;
BUILD_BUG_ON(FRF_AZ_TX_DESC_LBN != 0);
BUILD_BUG_ON(FR_AA_TX_DESC_UPD_KER != FR_BZ_TX_DESC_UPD_P0);
write_ptr = tx_queue->write_count & tx_queue->ptr_mask;
EFX_POPULATE_OWORD_2(reg, FRF_AZ_TX_DESC_PUSH_CMD, true,
FRF_AZ_TX_DESC_WPTR, write_ptr);
reg.qword[0] = *txd;
efx_writeo_page(tx_queue->efx, ®,
FR_BZ_TX_DESC_UPD_P0, tx_queue->queue);
}
/* For each entry inserted into the software descriptor ring, create a
* descriptor in the hardware TX descriptor ring (in host memory), and
* write a doorbell.
*/
void efx_farch_tx_write(struct efx_tx_queue *tx_queue)
{
struct efx_tx_buffer *buffer;
efx_qword_t *txd;
unsigned write_ptr;
unsigned old_write_count = tx_queue->write_count;
tx_queue->xmit_pending = false;
if (unlikely(tx_queue->write_count == tx_queue->insert_count))
return;
do {
write_ptr = tx_queue->write_count & tx_queue->ptr_mask;
buffer = &tx_queue->buffer[write_ptr];
txd = efx_tx_desc(tx_queue, write_ptr);
++tx_queue->write_count;
EFX_WARN_ON_ONCE_PARANOID(buffer->flags & EFX_TX_BUF_OPTION);
/* Create TX descriptor ring entry */
BUILD_BUG_ON(EFX_TX_BUF_CONT != 1);
EFX_POPULATE_QWORD_4(*txd,
FSF_AZ_TX_KER_CONT,
buffer->flags & EFX_TX_BUF_CONT,
FSF_AZ_TX_KER_BYTE_COUNT, buffer->len,
FSF_AZ_TX_KER_BUF_REGION, 0,
FSF_AZ_TX_KER_BUF_ADDR, buffer->dma_addr);
} while (tx_queue->write_count != tx_queue->insert_count);
wmb(); /* Ensure descriptors are written before they are fetched */
if (efx_nic_may_push_tx_desc(tx_queue, old_write_count)) {
txd = efx_tx_desc(tx_queue,
old_write_count & tx_queue->ptr_mask);
efx_farch_push_tx_desc(tx_queue, txd);
++tx_queue->pushes;
} else {
efx_farch_notify_tx_desc(tx_queue);
}
}
unsigned int efx_farch_tx_limit_len(struct efx_tx_queue *tx_queue,
dma_addr_t dma_addr, unsigned int len)
{
/* Don't cross 4K boundaries with descriptors. */
unsigned int limit = (~dma_addr & (EFX_PAGE_SIZE - 1)) + 1;
len = min(limit, len);
return len;
}
/* Allocate hardware resources for a TX queue */
int efx_farch_tx_probe(struct efx_tx_queue *tx_queue)
{
struct efx_nic *efx = tx_queue->efx;
unsigned entries;
tx_queue->type = ((tx_queue->label & 1) ? EFX_TXQ_TYPE_OUTER_CSUM : 0) |
((tx_queue->label & 2) ? EFX_TXQ_TYPE_HIGHPRI : 0);
entries = tx_queue->ptr_mask + 1;
return efx_alloc_special_buffer(efx, &tx_queue->txd,
entries * sizeof(efx_qword_t));
}
void efx_farch_tx_init(struct efx_tx_queue *tx_queue)
{
int csum = tx_queue->type & EFX_TXQ_TYPE_OUTER_CSUM;
struct efx_nic *efx = tx_queue->efx;
efx_oword_t reg;
/* Pin TX descriptor ring */
efx_init_special_buffer(efx, &tx_queue->txd);
/* Push TX descriptor ring to card */
EFX_POPULATE_OWORD_10(reg,
FRF_AZ_TX_DESCQ_EN, 1,
FRF_AZ_TX_ISCSI_DDIG_EN, 0,
FRF_AZ_TX_ISCSI_HDIG_EN, 0,
FRF_AZ_TX_DESCQ_BUF_BASE_ID, tx_queue->txd.index,
FRF_AZ_TX_DESCQ_EVQ_ID,
tx_queue->channel->channel,
FRF_AZ_TX_DESCQ_OWNER_ID, 0,
FRF_AZ_TX_DESCQ_LABEL, tx_queue->label,
FRF_AZ_TX_DESCQ_SIZE,
__ffs(tx_queue->txd.entries),
FRF_AZ_TX_DESCQ_TYPE, 0,
FRF_BZ_TX_NON_IP_DROP_DIS, 1);
EFX_SET_OWORD_FIELD(reg, FRF_BZ_TX_IP_CHKSM_DIS, !csum);
EFX_SET_OWORD_FIELD(reg, FRF_BZ_TX_TCP_CHKSM_DIS, !csum);
efx_writeo_table(efx, ®, efx->type->txd_ptr_tbl_base,
tx_queue->queue);
EFX_POPULATE_OWORD_1(reg,
FRF_BZ_TX_PACE,
(tx_queue->type & EFX_TXQ_TYPE_HIGHPRI) ?
FFE_BZ_TX_PACE_OFF :
FFE_BZ_TX_PACE_RESERVED);
efx_writeo_table(efx, ®, FR_BZ_TX_PACE_TBL, tx_queue->queue);
tx_queue->tso_version = 1;
}
static void efx_farch_flush_tx_queue(struct efx_tx_queue *tx_queue)
{
struct efx_nic *efx = tx_queue->efx;
efx_oword_t tx_flush_descq;
WARN_ON(atomic_read(&tx_queue->flush_outstanding));
atomic_set(&tx_queue->flush_outstanding, 1);
EFX_POPULATE_OWORD_2(tx_flush_descq,
FRF_AZ_TX_FLUSH_DESCQ_CMD, 1,
FRF_AZ_TX_FLUSH_DESCQ, tx_queue->queue);
efx_writeo(efx, &tx_flush_descq, FR_AZ_TX_FLUSH_DESCQ);
}
void efx_farch_tx_fini(struct efx_tx_queue *tx_queue)
{
struct efx_nic *efx = tx_queue->efx;
efx_oword_t tx_desc_ptr;
/* Remove TX descriptor ring from card */
EFX_ZERO_OWORD(tx_desc_ptr);
efx_writeo_table(efx, &tx_desc_ptr, efx->type->txd_ptr_tbl_base,
tx_queue->queue);
/* Unpin TX descriptor ring */
efx_fini_special_buffer(efx, &tx_queue->txd);
}
/* Free buffers backing TX queue */
void efx_farch_tx_remove(struct efx_tx_queue *tx_queue)
{
efx_free_special_buffer(tx_queue->efx, &tx_queue->txd);
}
/**************************************************************************
*
* RX path
*
**************************************************************************/
/* This creates an entry in the RX descriptor queue */
static inline void
efx_farch_build_rx_desc(struct efx_rx_queue *rx_queue, unsigned index)
{
struct efx_rx_buffer *rx_buf;
efx_qword_t *rxd;
rxd = efx_rx_desc(rx_queue, index);
rx_buf = efx_rx_buffer(rx_queue, index);
EFX_POPULATE_QWORD_3(*rxd,
FSF_AZ_RX_KER_BUF_SIZE,
rx_buf->len -
rx_queue->efx->type->rx_buffer_padding,
FSF_AZ_RX_KER_BUF_REGION, 0,
FSF_AZ_RX_KER_BUF_ADDR, rx_buf->dma_addr);
}
/* This writes to the RX_DESC_WPTR register for the specified receive
* descriptor ring.
*/
void efx_farch_rx_write(struct efx_rx_queue *rx_queue)
{
struct efx_nic *efx = rx_queue->efx;
efx_dword_t reg;
unsigned write_ptr;
while (rx_queue->notified_count != rx_queue->added_count) {
efx_farch_build_rx_desc(
rx_queue,
rx_queue->notified_count & rx_queue->ptr_mask);
++rx_queue->notified_count;
}
wmb();
write_ptr = rx_queue->added_count & rx_queue->ptr_mask;
EFX_POPULATE_DWORD_1(reg, FRF_AZ_RX_DESC_WPTR_DWORD, write_ptr);
efx_writed_page(efx, ®, FR_AZ_RX_DESC_UPD_DWORD_P0,
efx_rx_queue_index(rx_queue));
}
int efx_farch_rx_probe(struct efx_rx_queue *rx_queue)
{
struct efx_nic *efx = rx_queue->efx;
unsigned entries;
entries = rx_queue->ptr_mask + 1;
return efx_alloc_special_buffer(efx, &rx_queue->rxd,
entries * sizeof(efx_qword_t));
}
void efx_farch_rx_init(struct efx_rx_queue *rx_queue)
{
efx_oword_t rx_desc_ptr;
struct efx_nic *efx = rx_queue->efx;
bool jumbo_en;
/* For kernel-mode queues in Siena, the JUMBO flag enables scatter. */
jumbo_en = efx->rx_scatter;
netif_dbg(efx, hw, efx->net_dev,
"RX queue %d ring in special buffers %d-%d\n",
efx_rx_queue_index(rx_queue), rx_queue->rxd.index,
rx_queue->rxd.index + rx_queue->rxd.entries - 1);
rx_queue->scatter_n = 0;
/* Pin RX descriptor ring */
efx_init_special_buffer(efx, &rx_queue->rxd);
/* Push RX descriptor ring to card */
EFX_POPULATE_OWORD_10(rx_desc_ptr,
FRF_AZ_RX_ISCSI_DDIG_EN, true,
FRF_AZ_RX_ISCSI_HDIG_EN, true,
FRF_AZ_RX_DESCQ_BUF_BASE_ID, rx_queue->rxd.index,
FRF_AZ_RX_DESCQ_EVQ_ID,
efx_rx_queue_channel(rx_queue)->channel,
FRF_AZ_RX_DESCQ_OWNER_ID, 0,
FRF_AZ_RX_DESCQ_LABEL,
efx_rx_queue_index(rx_queue),
FRF_AZ_RX_DESCQ_SIZE,
__ffs(rx_queue->rxd.entries),
FRF_AZ_RX_DESCQ_TYPE, 0 /* kernel queue */ ,
FRF_AZ_RX_DESCQ_JUMBO, jumbo_en,
FRF_AZ_RX_DESCQ_EN, 1);
efx_writeo_table(efx, &rx_desc_ptr, efx->type->rxd_ptr_tbl_base,
efx_rx_queue_index(rx_queue));
}
static void efx_farch_flush_rx_queue(struct efx_rx_queue *rx_queue)
{
struct efx_nic *efx = rx_queue->efx;
efx_oword_t rx_flush_descq;
EFX_POPULATE_OWORD_2(rx_flush_descq,
FRF_AZ_RX_FLUSH_DESCQ_CMD, 1,
FRF_AZ_RX_FLUSH_DESCQ,
efx_rx_queue_index(rx_queue));
efx_writeo(efx, &rx_flush_descq, FR_AZ_RX_FLUSH_DESCQ);
}
void efx_farch_rx_fini(struct efx_rx_queue *rx_queue)
{
efx_oword_t rx_desc_ptr;
struct efx_nic *efx = rx_queue->efx;
/* Remove RX descriptor ring from card */
EFX_ZERO_OWORD(rx_desc_ptr);
efx_writeo_table(efx, &rx_desc_ptr, efx->type->rxd_ptr_tbl_base,
efx_rx_queue_index(rx_queue));
/* Unpin RX descriptor ring */
efx_fini_special_buffer(efx, &rx_queue->rxd);
}
/* Free buffers backing RX queue */
void efx_farch_rx_remove(struct efx_rx_queue *rx_queue)
{
efx_free_special_buffer(rx_queue->efx, &rx_queue->rxd);
}
/**************************************************************************
*
* Flush handling
*
**************************************************************************/
/* efx_farch_flush_queues() must be woken up when all flushes are completed,
* or more RX flushes can be kicked off.
*/
static bool efx_farch_flush_wake(struct efx_nic *efx)
{
/* Ensure that all updates are visible to efx_farch_flush_queues() */
smp_mb();
return (atomic_read(&efx->active_queues) == 0 ||
(atomic_read(&efx->rxq_flush_outstanding) < EFX_RX_FLUSH_COUNT
&& atomic_read(&efx->rxq_flush_pending) > 0));
}
static bool efx_check_tx_flush_complete(struct efx_nic *efx)
{
bool i = true;
efx_oword_t txd_ptr_tbl;
struct efx_channel *channel;
struct efx_tx_queue *tx_queue;
efx_for_each_channel(channel, efx) {
efx_for_each_channel_tx_queue(tx_queue, channel) {
efx_reado_table(efx, &txd_ptr_tbl,
FR_BZ_TX_DESC_PTR_TBL, tx_queue->queue);
if (EFX_OWORD_FIELD(txd_ptr_tbl,
FRF_AZ_TX_DESCQ_FLUSH) ||
EFX_OWORD_FIELD(txd_ptr_tbl,
FRF_AZ_TX_DESCQ_EN)) {
netif_dbg(efx, hw, efx->net_dev,
"flush did not complete on TXQ %d\n",
tx_queue->queue);
i = false;
} else if (atomic_cmpxchg(&tx_queue->flush_outstanding,
1, 0)) {
/* The flush is complete, but we didn't
* receive a flush completion event
*/
netif_dbg(efx, hw, efx->net_dev,
"flush complete on TXQ %d, so drain "
"the queue\n", tx_queue->queue);
/* Don't need to increment active_queues as it
* has already been incremented for the queues
* which did not drain
*/
efx_farch_magic_event(channel,
EFX_CHANNEL_MAGIC_TX_DRAIN(
tx_queue));
}
}
}
return i;
}
/* Flush all the transmit queues, and continue flushing receive queues until
* they're all flushed. Wait for the DRAIN events to be received so that there
* are no more RX and TX events left on any channel. */
static int efx_farch_do_flush(struct efx_nic *efx)
{
unsigned timeout = msecs_to_jiffies(5000); /* 5s for all flushes and drains */
struct efx_channel *channel;
struct efx_rx_queue *rx_queue;
struct efx_tx_queue *tx_queue;
int rc = 0;
efx_for_each_channel(channel, efx) {
efx_for_each_channel_tx_queue(tx_queue, channel) {
efx_farch_flush_tx_queue(tx_queue);
}
efx_for_each_channel_rx_queue(rx_queue, channel) {
rx_queue->flush_pending = true;
atomic_inc(&efx->rxq_flush_pending);
}
}
while (timeout && atomic_read(&efx->active_queues) > 0) {
/* If SRIOV is enabled, then offload receive queue flushing to
* the firmware (though we will still have to poll for
* completion). If that fails, fall back to the old scheme.
*/
if (efx_siena_sriov_enabled(efx)) {
rc = efx_siena_mcdi_flush_rxqs(efx);
if (!rc)
goto wait;
}
/* The hardware supports four concurrent rx flushes, each of
* which may need to be retried if there is an outstanding
* descriptor fetch
*/
efx_for_each_channel(channel, efx) {
efx_for_each_channel_rx_queue(rx_queue, channel) {
if (atomic_read(&efx->rxq_flush_outstanding) >=
EFX_RX_FLUSH_COUNT)
break;
if (rx_queue->flush_pending) {
rx_queue->flush_pending = false;
atomic_dec(&efx->rxq_flush_pending);
atomic_inc(&efx->rxq_flush_outstanding);
efx_farch_flush_rx_queue(rx_queue);
}
}
}
wait:
timeout = wait_event_timeout(efx->flush_wq,
efx_farch_flush_wake(efx),
timeout);
}
if (atomic_read(&efx->active_queues) &&
!efx_check_tx_flush_complete(efx)) {
netif_err(efx, hw, efx->net_dev, "failed to flush %d queues "
"(rx %d+%d)\n", atomic_read(&efx->active_queues),
atomic_read(&efx->rxq_flush_outstanding),
atomic_read(&efx->rxq_flush_pending));
rc = -ETIMEDOUT;
atomic_set(&efx->active_queues, 0);
atomic_set(&efx->rxq_flush_pending, 0);
atomic_set(&efx->rxq_flush_outstanding, 0);
}
return rc;
}
int efx_farch_fini_dmaq(struct efx_nic *efx)
{
struct efx_channel *channel;
struct efx_tx_queue *tx_queue;
struct efx_rx_queue *rx_queue;
int rc = 0;
/* Do not attempt to write to the NIC during EEH recovery */
if (efx->state != STATE_RECOVERY) {
/* Only perform flush if DMA is enabled */
if (efx->pci_dev->is_busmaster) {
efx->type->prepare_flush(efx);
rc = efx_farch_do_flush(efx);
efx->type->finish_flush(efx);
}
efx_for_each_channel(channel, efx) {
efx_for_each_channel_rx_queue(rx_queue, channel)
efx_farch_rx_fini(rx_queue);
efx_for_each_channel_tx_queue(tx_queue, channel)
efx_farch_tx_fini(tx_queue);
}
}
return rc;
}
/* Reset queue and flush accounting after FLR
*
* One possible cause of FLR recovery is that DMA may be failing (eg. if bus
* mastering was disabled), in which case we don't receive (RXQ) flush
* completion events. This means that efx->rxq_flush_outstanding remained at 4
* after the FLR; also, efx->active_queues was non-zero (as no flush completion
* events were received, and we didn't go through efx_check_tx_flush_complete())
* If we don't fix this up, on the next call to efx_siena_realloc_channels() we
* won't flush any RX queues because efx->rxq_flush_outstanding is at the limit
* of 4 for batched flush requests; and the efx->active_queues gets messed up
* because we keep incrementing for the newly initialised queues, but it never
* went to zero previously. Then we get a timeout every time we try to restart
* the queues, as it doesn't go back to zero when we should be flushing the
* queues.
*/
void efx_farch_finish_flr(struct efx_nic *efx)
{
atomic_set(&efx->rxq_flush_pending, 0);
atomic_set(&efx->rxq_flush_outstanding, 0);
atomic_set(&efx->active_queues, 0);
}
/**************************************************************************
*
* Event queue processing
* Event queues are processed by per-channel tasklets.
*
**************************************************************************/
/* Update a channel's event queue's read pointer (RPTR) register
*
* This writes the EVQ_RPTR_REG register for the specified channel's
* event queue.
*/
void efx_farch_ev_read_ack(struct efx_channel *channel)
{
efx_dword_t reg;
struct efx_nic *efx = channel->efx;
EFX_POPULATE_DWORD_1(reg, FRF_AZ_EVQ_RPTR,
channel->eventq_read_ptr & channel->eventq_mask);
/* For Falcon A1, EVQ_RPTR_KER is documented as having a step size
* of 4 bytes, but it is really 16 bytes just like later revisions.
*/
efx_writed(efx, ®,
efx->type->evq_rptr_tbl_base +
FR_BZ_EVQ_RPTR_STEP * channel->channel);
}
/* Use HW to insert a SW defined event */
void efx_farch_generate_event(struct efx_nic *efx, unsigned int evq,
efx_qword_t *event)
{
efx_oword_t drv_ev_reg;
BUILD_BUG_ON(FRF_AZ_DRV_EV_DATA_LBN != 0 ||
FRF_AZ_DRV_EV_DATA_WIDTH != 64);
drv_ev_reg.u32[0] = event->u32[0];
drv_ev_reg.u32[1] = event->u32[1];
drv_ev_reg.u32[2] = 0;
drv_ev_reg.u32[3] = 0;
EFX_SET_OWORD_FIELD(drv_ev_reg, FRF_AZ_DRV_EV_QID, evq);
efx_writeo(efx, &drv_ev_reg, FR_AZ_DRV_EV);
}
static void efx_farch_magic_event(struct efx_channel *channel, u32 magic)
{
efx_qword_t event;
EFX_POPULATE_QWORD_2(event, FSF_AZ_EV_CODE,
FSE_AZ_EV_CODE_DRV_GEN_EV,
FSF_AZ_DRV_GEN_EV_MAGIC, magic);
efx_farch_generate_event(channel->efx, channel->channel, &event);
}
/* Handle a transmit completion event
*
* The NIC batches TX completion events; the message we receive is of
* the form "complete all TX events up to this index".
*/
static void
efx_farch_handle_tx_event(struct efx_channel *channel, efx_qword_t *event)
{
unsigned int tx_ev_desc_ptr;
unsigned int tx_ev_q_label;
struct efx_tx_queue *tx_queue;
struct efx_nic *efx = channel->efx;
if (unlikely(READ_ONCE(efx->reset_pending)))
return;
if (likely(EFX_QWORD_FIELD(*event, FSF_AZ_TX_EV_COMP))) {
/* Transmit completion */
tx_ev_desc_ptr = EFX_QWORD_FIELD(*event, FSF_AZ_TX_EV_DESC_PTR);
tx_ev_q_label = EFX_QWORD_FIELD(*event, FSF_AZ_TX_EV_Q_LABEL);
tx_queue = channel->tx_queue +
(tx_ev_q_label % EFX_MAX_TXQ_PER_CHANNEL);
efx_siena_xmit_done(tx_queue, tx_ev_desc_ptr);
} else if (EFX_QWORD_FIELD(*event, FSF_AZ_TX_EV_WQ_FF_FULL)) {
/* Rewrite the FIFO write pointer */
tx_ev_q_label = EFX_QWORD_FIELD(*event, FSF_AZ_TX_EV_Q_LABEL);
tx_queue = channel->tx_queue +
(tx_ev_q_label % EFX_MAX_TXQ_PER_CHANNEL);
netif_tx_lock(efx->net_dev);
efx_farch_notify_tx_desc(tx_queue);
netif_tx_unlock(efx->net_dev);
} else if (EFX_QWORD_FIELD(*event, FSF_AZ_TX_EV_PKT_ERR)) {
efx_siena_schedule_reset(efx, RESET_TYPE_DMA_ERROR);
} else {
netif_err(efx, tx_err, efx->net_dev,
"channel %d unexpected TX event "
EFX_QWORD_FMT"\n", channel->channel,
EFX_QWORD_VAL(*event));
}
}
/* Detect errors included in the rx_evt_pkt_ok bit. */
static u16 efx_farch_handle_rx_not_ok(struct efx_rx_queue *rx_queue,
const efx_qword_t *event)
{
struct efx_channel *channel = efx_rx_queue_channel(rx_queue);
struct efx_nic *efx = rx_queue->efx;
bool rx_ev_buf_owner_id_err, rx_ev_ip_hdr_chksum_err;
bool rx_ev_tcp_udp_chksum_err, rx_ev_eth_crc_err;
bool rx_ev_frm_trunc, rx_ev_tobe_disc;
bool rx_ev_other_err, rx_ev_pause_frm;
rx_ev_tobe_disc = EFX_QWORD_FIELD(*event, FSF_AZ_RX_EV_TOBE_DISC);
rx_ev_buf_owner_id_err = EFX_QWORD_FIELD(*event,
FSF_AZ_RX_EV_BUF_OWNER_ID_ERR);
rx_ev_ip_hdr_chksum_err = EFX_QWORD_FIELD(*event,
FSF_AZ_RX_EV_IP_HDR_CHKSUM_ERR);
rx_ev_tcp_udp_chksum_err = EFX_QWORD_FIELD(*event,
FSF_AZ_RX_EV_TCP_UDP_CHKSUM_ERR);
rx_ev_eth_crc_err = EFX_QWORD_FIELD(*event, FSF_AZ_RX_EV_ETH_CRC_ERR);
rx_ev_frm_trunc = EFX_QWORD_FIELD(*event, FSF_AZ_RX_EV_FRM_TRUNC);
rx_ev_pause_frm = EFX_QWORD_FIELD(*event, FSF_AZ_RX_EV_PAUSE_FRM_ERR);
/* Every error apart from tobe_disc and pause_frm */
rx_ev_other_err = (rx_ev_tcp_udp_chksum_err |
rx_ev_buf_owner_id_err | rx_ev_eth_crc_err |
rx_ev_frm_trunc | rx_ev_ip_hdr_chksum_err);
/* Count errors that are not in MAC stats. Ignore expected
* checksum errors during self-test. */
if (rx_ev_frm_trunc)
++channel->n_rx_frm_trunc;
else if (rx_ev_tobe_disc)
++channel->n_rx_tobe_disc;
else if (!efx->loopback_selftest) {
if (rx_ev_ip_hdr_chksum_err)
++channel->n_rx_ip_hdr_chksum_err;
else if (rx_ev_tcp_udp_chksum_err)
++channel->n_rx_tcp_udp_chksum_err;
}
/* TOBE_DISC is expected on unicast mismatches; don't print out an
* error message. FRM_TRUNC indicates RXDP dropped the packet due
* to a FIFO overflow.
*/
#ifdef DEBUG
if (rx_ev_other_err && net_ratelimit()) {
netif_dbg(efx, rx_err, efx->net_dev,
" RX queue %d unexpected RX event "
EFX_QWORD_FMT "%s%s%s%s%s%s%s\n",
efx_rx_queue_index(rx_queue), EFX_QWORD_VAL(*event),
rx_ev_buf_owner_id_err ? " [OWNER_ID_ERR]" : "",
rx_ev_ip_hdr_chksum_err ?
" [IP_HDR_CHKSUM_ERR]" : "",
rx_ev_tcp_udp_chksum_err ?
" [TCP_UDP_CHKSUM_ERR]" : "",
rx_ev_eth_crc_err ? " [ETH_CRC_ERR]" : "",
rx_ev_frm_trunc ? " [FRM_TRUNC]" : "",
rx_ev_tobe_disc ? " [TOBE_DISC]" : "",
rx_ev_pause_frm ? " [PAUSE]" : "");
}
#else
(void) rx_ev_other_err;
#endif
if (efx->net_dev->features & NETIF_F_RXALL)
/* don't discard frame for CRC error */
rx_ev_eth_crc_err = false;
/* The frame must be discarded if any of these are true. */
return (rx_ev_eth_crc_err | rx_ev_frm_trunc |
rx_ev_tobe_disc | rx_ev_pause_frm) ?
EFX_RX_PKT_DISCARD : 0;
}
/* Handle receive events that are not in-order. Return true if this
* can be handled as a partial packet discard, false if it's more
* serious.
*/
static bool
efx_farch_handle_rx_bad_index(struct efx_rx_queue *rx_queue, unsigned index)
{
struct efx_channel *channel = efx_rx_queue_channel(rx_queue);
struct efx_nic *efx = rx_queue->efx;
unsigned expected, dropped;
if (rx_queue->scatter_n &&
index == ((rx_queue->removed_count + rx_queue->scatter_n - 1) &
rx_queue->ptr_mask)) {
++channel->n_rx_nodesc_trunc;
return true;
}
expected = rx_queue->removed_count & rx_queue->ptr_mask;
dropped = (index - expected) & rx_queue->ptr_mask;
netif_info(efx, rx_err, efx->net_dev,
"dropped %d events (index=%d expected=%d)\n",
dropped, index, expected);
efx_siena_schedule_reset(efx, RESET_TYPE_DISABLE);
return false;
}
/* Handle a packet received event
*
* The NIC gives a "discard" flag if it's a unicast packet with the
* wrong destination address
* Also "is multicast" and "matches multicast filter" flags can be used to
* discard non-matching multicast packets.
*/
static void
efx_farch_handle_rx_event(struct efx_channel *channel, const efx_qword_t *event)
{
unsigned int rx_ev_desc_ptr, rx_ev_byte_cnt;
unsigned int rx_ev_hdr_type, rx_ev_mcast_pkt;
unsigned expected_ptr;
bool rx_ev_pkt_ok, rx_ev_sop, rx_ev_cont;
u16 flags;
struct efx_rx_queue *rx_queue;
struct efx_nic *efx = channel->efx;
if (unlikely(READ_ONCE(efx->reset_pending)))
return;
rx_ev_cont = EFX_QWORD_FIELD(*event, FSF_AZ_RX_EV_JUMBO_CONT);
rx_ev_sop = EFX_QWORD_FIELD(*event, FSF_AZ_RX_EV_SOP);
WARN_ON(EFX_QWORD_FIELD(*event, FSF_AZ_RX_EV_Q_LABEL) !=
channel->channel);
rx_queue = efx_channel_get_rx_queue(channel);
rx_ev_desc_ptr = EFX_QWORD_FIELD(*event, FSF_AZ_RX_EV_DESC_PTR);
expected_ptr = ((rx_queue->removed_count + rx_queue->scatter_n) &
rx_queue->ptr_mask);
/* Check for partial drops and other errors */
if (unlikely(rx_ev_desc_ptr != expected_ptr) ||
unlikely(rx_ev_sop != (rx_queue->scatter_n == 0))) {
if (rx_ev_desc_ptr != expected_ptr &&
!efx_farch_handle_rx_bad_index(rx_queue, rx_ev_desc_ptr))
return;
/* Discard all pending fragments */
if (rx_queue->scatter_n) {
efx_siena_rx_packet(
rx_queue,
rx_queue->removed_count & rx_queue->ptr_mask,
rx_queue->scatter_n, 0, EFX_RX_PKT_DISCARD);
rx_queue->removed_count += rx_queue->scatter_n;
rx_queue->scatter_n = 0;
}
/* Return if there is no new fragment */
if (rx_ev_desc_ptr != expected_ptr)
return;
/* Discard new fragment if not SOP */
if (!rx_ev_sop) {
efx_siena_rx_packet(
rx_queue,
rx_queue->removed_count & rx_queue->ptr_mask,
1, 0, EFX_RX_PKT_DISCARD);
++rx_queue->removed_count;
return;
}
}
++rx_queue->scatter_n;
if (rx_ev_cont)
return;
rx_ev_byte_cnt = EFX_QWORD_FIELD(*event, FSF_AZ_RX_EV_BYTE_CNT);
rx_ev_pkt_ok = EFX_QWORD_FIELD(*event, FSF_AZ_RX_EV_PKT_OK);
rx_ev_hdr_type = EFX_QWORD_FIELD(*event, FSF_AZ_RX_EV_HDR_TYPE);
if (likely(rx_ev_pkt_ok)) {
/* If packet is marked as OK then we can rely on the
* hardware checksum and classification.
*/
flags = 0;
switch (rx_ev_hdr_type) {
case FSE_CZ_RX_EV_HDR_TYPE_IPV4V6_TCP:
flags |= EFX_RX_PKT_TCP;
fallthrough;
case FSE_CZ_RX_EV_HDR_TYPE_IPV4V6_UDP:
flags |= EFX_RX_PKT_CSUMMED;
fallthrough;
case FSE_CZ_RX_EV_HDR_TYPE_IPV4V6_OTHER:
case FSE_AZ_RX_EV_HDR_TYPE_OTHER:
break;
}
} else {
flags = efx_farch_handle_rx_not_ok(rx_queue, event);
}
/* Detect multicast packets that didn't match the filter */
rx_ev_mcast_pkt = EFX_QWORD_FIELD(*event, FSF_AZ_RX_EV_MCAST_PKT);
if (rx_ev_mcast_pkt) {
unsigned int rx_ev_mcast_hash_match =
EFX_QWORD_FIELD(*event, FSF_AZ_RX_EV_MCAST_HASH_MATCH);
if (unlikely(!rx_ev_mcast_hash_match)) {
++channel->n_rx_mcast_mismatch;
flags |= EFX_RX_PKT_DISCARD;
}
}
channel->irq_mod_score += 2;
/* Handle received packet */
efx_siena_rx_packet(rx_queue,
rx_queue->removed_count & rx_queue->ptr_mask,
rx_queue->scatter_n, rx_ev_byte_cnt, flags);
rx_queue->removed_count += rx_queue->scatter_n;
rx_queue->scatter_n = 0;
}
/* If this flush done event corresponds to a &struct efx_tx_queue, then
* send an %EFX_CHANNEL_MAGIC_TX_DRAIN event to drain the event queue
* of all transmit completions.
*/
static void
efx_farch_handle_tx_flush_done(struct efx_nic *efx, efx_qword_t *event)
{
struct efx_tx_queue *tx_queue;
struct efx_channel *channel;
int qid;
qid = EFX_QWORD_FIELD(*event, FSF_AZ_DRIVER_EV_SUBDATA);
if (qid < EFX_MAX_TXQ_PER_CHANNEL * (efx->n_tx_channels + efx->n_extra_tx_channels)) {
channel = efx_get_tx_channel(efx, qid / EFX_MAX_TXQ_PER_CHANNEL);
tx_queue = channel->tx_queue + (qid % EFX_MAX_TXQ_PER_CHANNEL);
if (atomic_cmpxchg(&tx_queue->flush_outstanding, 1, 0))
efx_farch_magic_event(tx_queue->channel,
EFX_CHANNEL_MAGIC_TX_DRAIN(tx_queue));
}
}
/* If this flush done event corresponds to a &struct efx_rx_queue: If the flush
* was successful then send an %EFX_CHANNEL_MAGIC_RX_DRAIN, otherwise add
* the RX queue back to the mask of RX queues in need of flushing.
*/
static void
efx_farch_handle_rx_flush_done(struct efx_nic *efx, efx_qword_t *event)
{
struct efx_channel *channel;
struct efx_rx_queue *rx_queue;
int qid;
bool failed;
qid = EFX_QWORD_FIELD(*event, FSF_AZ_DRIVER_EV_RX_DESCQ_ID);
failed = EFX_QWORD_FIELD(*event, FSF_AZ_DRIVER_EV_RX_FLUSH_FAIL);
if (qid >= efx->n_channels)
return;
channel = efx_get_channel(efx, qid);
if (!efx_channel_has_rx_queue(channel))
return;
rx_queue = efx_channel_get_rx_queue(channel);
if (failed) {
netif_info(efx, hw, efx->net_dev,
"RXQ %d flush retry\n", qid);
rx_queue->flush_pending = true;
atomic_inc(&efx->rxq_flush_pending);
} else {
efx_farch_magic_event(efx_rx_queue_channel(rx_queue),
EFX_CHANNEL_MAGIC_RX_DRAIN(rx_queue));
}
atomic_dec(&efx->rxq_flush_outstanding);
if (efx_farch_flush_wake(efx))
wake_up(&efx->flush_wq);
}
static void
efx_farch_handle_drain_event(struct efx_channel *channel)
{
struct efx_nic *efx = channel->efx;
WARN_ON(atomic_read(&efx->active_queues) == 0);
atomic_dec(&efx->active_queues);
if (efx_farch_flush_wake(efx))
wake_up(&efx->flush_wq);
}
static void efx_farch_handle_generated_event(struct efx_channel *channel,
efx_qword_t *event)
{
struct efx_nic *efx = channel->efx;
struct efx_rx_queue *rx_queue =
efx_channel_has_rx_queue(channel) ?
efx_channel_get_rx_queue(channel) : NULL;
unsigned magic, code;
magic = EFX_QWORD_FIELD(*event, FSF_AZ_DRV_GEN_EV_MAGIC);
code = _EFX_CHANNEL_MAGIC_CODE(magic);
if (magic == EFX_CHANNEL_MAGIC_TEST(channel)) {
channel->event_test_cpu = raw_smp_processor_id();
} else if (rx_queue && magic == EFX_CHANNEL_MAGIC_FILL(rx_queue)) {
/* The queue must be empty, so we won't receive any rx
* events, so efx_process_channel() won't refill the
* queue. Refill it here */
efx_siena_fast_push_rx_descriptors(rx_queue, true);
} else if (rx_queue && magic == EFX_CHANNEL_MAGIC_RX_DRAIN(rx_queue)) {
efx_farch_handle_drain_event(channel);
} else if (code == _EFX_CHANNEL_MAGIC_TX_DRAIN) {
efx_farch_handle_drain_event(channel);
} else {
netif_dbg(efx, hw, efx->net_dev, "channel %d received "
"generated event "EFX_QWORD_FMT"\n",
channel->channel, EFX_QWORD_VAL(*event));
}
}
static void
efx_farch_handle_driver_event(struct efx_channel *channel, efx_qword_t *event)
{
struct efx_nic *efx = channel->efx;
unsigned int ev_sub_code;
unsigned int ev_sub_data;
ev_sub_code = EFX_QWORD_FIELD(*event, FSF_AZ_DRIVER_EV_SUBCODE);
ev_sub_data = EFX_QWORD_FIELD(*event, FSF_AZ_DRIVER_EV_SUBDATA);
switch (ev_sub_code) {
case FSE_AZ_TX_DESCQ_FLS_DONE_EV:
netif_vdbg(efx, hw, efx->net_dev, "channel %d TXQ %d flushed\n",
channel->channel, ev_sub_data);
efx_farch_handle_tx_flush_done(efx, event);
#ifdef CONFIG_SFC_SIENA_SRIOV
efx_siena_sriov_tx_flush_done(efx, event);
#endif
break;
case FSE_AZ_RX_DESCQ_FLS_DONE_EV:
netif_vdbg(efx, hw, efx->net_dev, "channel %d RXQ %d flushed\n",
channel->channel, ev_sub_data);
efx_farch_handle_rx_flush_done(efx, event);
#ifdef CONFIG_SFC_SIENA_SRIOV
efx_siena_sriov_rx_flush_done(efx, event);
#endif
break;
case FSE_AZ_EVQ_INIT_DONE_EV:
netif_dbg(efx, hw, efx->net_dev,
"channel %d EVQ %d initialised\n",
channel->channel, ev_sub_data);
break;
case FSE_AZ_SRM_UPD_DONE_EV:
netif_vdbg(efx, hw, efx->net_dev,
"channel %d SRAM update done\n", channel->channel);
break;
case FSE_AZ_WAKE_UP_EV:
netif_vdbg(efx, hw, efx->net_dev,
"channel %d RXQ %d wakeup event\n",
channel->channel, ev_sub_data);
break;
case FSE_AZ_TIMER_EV:
netif_vdbg(efx, hw, efx->net_dev,
"channel %d RX queue %d timer expired\n",
channel->channel, ev_sub_data);
break;
case FSE_AA_RX_RECOVER_EV:
netif_err(efx, rx_err, efx->net_dev,
"channel %d seen DRIVER RX_RESET event. "
"Resetting.\n", channel->channel);
atomic_inc(&efx->rx_reset);
efx_siena_schedule_reset(efx, RESET_TYPE_DISABLE);
break;
case FSE_BZ_RX_DSC_ERROR_EV:
if (ev_sub_data < EFX_VI_BASE) {
netif_err(efx, rx_err, efx->net_dev,
"RX DMA Q %d reports descriptor fetch error."
" RX Q %d is disabled.\n", ev_sub_data,
ev_sub_data);
efx_siena_schedule_reset(efx, RESET_TYPE_DMA_ERROR);
}
#ifdef CONFIG_SFC_SIENA_SRIOV
else
efx_siena_sriov_desc_fetch_err(efx, ev_sub_data);
#endif
break;
case FSE_BZ_TX_DSC_ERROR_EV:
if (ev_sub_data < EFX_VI_BASE) {
netif_err(efx, tx_err, efx->net_dev,
"TX DMA Q %d reports descriptor fetch error."
" TX Q %d is disabled.\n", ev_sub_data,
ev_sub_data);
efx_siena_schedule_reset(efx, RESET_TYPE_DMA_ERROR);
}
#ifdef CONFIG_SFC_SIENA_SRIOV
else
efx_siena_sriov_desc_fetch_err(efx, ev_sub_data);
#endif
break;
default:
netif_vdbg(efx, hw, efx->net_dev,
"channel %d unknown driver event code %d "
"data %04x\n", channel->channel, ev_sub_code,
ev_sub_data);
break;
}
}
int efx_farch_ev_process(struct efx_channel *channel, int budget)
{
struct efx_nic *efx = channel->efx;
unsigned int read_ptr;
efx_qword_t event, *p_event;
int ev_code;
int spent = 0;
if (budget <= 0)
return spent;
read_ptr = channel->eventq_read_ptr;
for (;;) {
p_event = efx_event(channel, read_ptr);
event = *p_event;
if (!efx_event_present(&event))
/* End of events */
break;
netif_vdbg(channel->efx, intr, channel->efx->net_dev,
"channel %d event is "EFX_QWORD_FMT"\n",
channel->channel, EFX_QWORD_VAL(event));
/* Clear this event by marking it all ones */
EFX_SET_QWORD(*p_event);
++read_ptr;
ev_code = EFX_QWORD_FIELD(event, FSF_AZ_EV_CODE);
switch (ev_code) {
case FSE_AZ_EV_CODE_RX_EV:
efx_farch_handle_rx_event(channel, &event);
if (++spent == budget)
goto out;
break;
case FSE_AZ_EV_CODE_TX_EV:
efx_farch_handle_tx_event(channel, &event);
break;
case FSE_AZ_EV_CODE_DRV_GEN_EV:
efx_farch_handle_generated_event(channel, &event);
break;
case FSE_AZ_EV_CODE_DRIVER_EV:
efx_farch_handle_driver_event(channel, &event);
break;
#ifdef CONFIG_SFC_SIENA_SRIOV
case FSE_CZ_EV_CODE_USER_EV:
efx_siena_sriov_event(channel, &event);
break;
#endif
case FSE_CZ_EV_CODE_MCDI_EV:
efx_siena_mcdi_process_event(channel, &event);
break;
case FSE_AZ_EV_CODE_GLOBAL_EV:
if (efx->type->handle_global_event &&
efx->type->handle_global_event(channel, &event))
break;
fallthrough;
default:
netif_err(channel->efx, hw, channel->efx->net_dev,
"channel %d unknown event type %d (data "
EFX_QWORD_FMT ")\n", channel->channel,
ev_code, EFX_QWORD_VAL(event));
}
}
out:
channel->eventq_read_ptr = read_ptr;
return spent;
}
/* Allocate buffer table entries for event queue */
int efx_farch_ev_probe(struct efx_channel *channel)
{
struct efx_nic *efx = channel->efx;
unsigned entries;
entries = channel->eventq_mask + 1;
return efx_alloc_special_buffer(efx, &channel->eventq,
entries * sizeof(efx_qword_t));
}
int efx_farch_ev_init(struct efx_channel *channel)
{
efx_oword_t reg;
struct efx_nic *efx = channel->efx;
netif_dbg(efx, hw, efx->net_dev,
"channel %d event queue in special buffers %d-%d\n",
channel->channel, channel->eventq.index,
channel->eventq.index + channel->eventq.entries - 1);
EFX_POPULATE_OWORD_3(reg,
FRF_CZ_TIMER_Q_EN, 1,
FRF_CZ_HOST_NOTIFY_MODE, 0,
FRF_CZ_TIMER_MODE, FFE_CZ_TIMER_MODE_DIS);
efx_writeo_table(efx, ®, FR_BZ_TIMER_TBL, channel->channel);
/* Pin event queue buffer */
efx_init_special_buffer(efx, &channel->eventq);
/* Fill event queue with all ones (i.e. empty events) */
memset(channel->eventq.buf.addr, 0xff, channel->eventq.buf.len);
/* Push event queue to card */
EFX_POPULATE_OWORD_3(reg,
FRF_AZ_EVQ_EN, 1,
FRF_AZ_EVQ_SIZE, __ffs(channel->eventq.entries),
FRF_AZ_EVQ_BUF_BASE_ID, channel->eventq.index);
efx_writeo_table(efx, ®, efx->type->evq_ptr_tbl_base,
channel->channel);
return 0;
}
void efx_farch_ev_fini(struct efx_channel *channel)
{
efx_oword_t reg;
struct efx_nic *efx = channel->efx;
/* Remove event queue from card */
EFX_ZERO_OWORD(reg);
efx_writeo_table(efx, ®, efx->type->evq_ptr_tbl_base,
channel->channel);
efx_writeo_table(efx, ®, FR_BZ_TIMER_TBL, channel->channel);
/* Unpin event queue */
efx_fini_special_buffer(efx, &channel->eventq);
}
/* Free buffers backing event queue */
void efx_farch_ev_remove(struct efx_channel *channel)
{
efx_free_special_buffer(channel->efx, &channel->eventq);
}
void efx_farch_ev_test_generate(struct efx_channel *channel)
{
efx_farch_magic_event(channel, EFX_CHANNEL_MAGIC_TEST(channel));
}
void efx_farch_rx_defer_refill(struct efx_rx_queue *rx_queue)
{
efx_farch_magic_event(efx_rx_queue_channel(rx_queue),
EFX_CHANNEL_MAGIC_FILL(rx_queue));
}
/**************************************************************************
*
* Hardware interrupts
* The hardware interrupt handler does very little work; all the event
* queue processing is carried out by per-channel tasklets.
*
**************************************************************************/
/* Enable/disable/generate interrupts */
static inline void efx_farch_interrupts(struct efx_nic *efx,
bool enabled, bool force)
{
efx_oword_t int_en_reg_ker;
EFX_POPULATE_OWORD_3(int_en_reg_ker,
FRF_AZ_KER_INT_LEVE_SEL, efx->irq_level,
FRF_AZ_KER_INT_KER, force,
FRF_AZ_DRV_INT_EN_KER, enabled);
efx_writeo(efx, &int_en_reg_ker, FR_AZ_INT_EN_KER);
}
void efx_farch_irq_enable_master(struct efx_nic *efx)
{
EFX_ZERO_OWORD(*((efx_oword_t *) efx->irq_status.addr));
wmb(); /* Ensure interrupt vector is clear before interrupts enabled */
efx_farch_interrupts(efx, true, false);
}
void efx_farch_irq_disable_master(struct efx_nic *efx)
{
/* Disable interrupts */
efx_farch_interrupts(efx, false, false);
}
/* Generate a test interrupt
* Interrupt must already have been enabled, otherwise nasty things
* may happen.
*/
int efx_farch_irq_test_generate(struct efx_nic *efx)
{
efx_farch_interrupts(efx, true, true);
return 0;
}
/* Process a fatal interrupt
* Disable bus mastering ASAP and schedule a reset
*/
irqreturn_t efx_farch_fatal_interrupt(struct efx_nic *efx)
{
efx_oword_t *int_ker = efx->irq_status.addr;
efx_oword_t fatal_intr;
int error, mem_perr;
efx_reado(efx, &fatal_intr, FR_AZ_FATAL_INTR_KER);
error = EFX_OWORD_FIELD(fatal_intr, FRF_AZ_FATAL_INTR);
netif_err(efx, hw, efx->net_dev, "SYSTEM ERROR "EFX_OWORD_FMT" status "
EFX_OWORD_FMT ": %s\n", EFX_OWORD_VAL(*int_ker),
EFX_OWORD_VAL(fatal_intr),
error ? "disabling bus mastering" : "no recognised error");
/* If this is a memory parity error dump which blocks are offending */
mem_perr = (EFX_OWORD_FIELD(fatal_intr, FRF_AZ_MEM_PERR_INT_KER) ||
EFX_OWORD_FIELD(fatal_intr, FRF_AZ_SRM_PERR_INT_KER));
if (mem_perr) {
efx_oword_t reg;
efx_reado(efx, ®, FR_AZ_MEM_STAT);
netif_err(efx, hw, efx->net_dev,
"SYSTEM ERROR: memory parity error "EFX_OWORD_FMT"\n",
EFX_OWORD_VAL(reg));
}
/* Disable both devices */
pci_clear_master(efx->pci_dev);
efx_farch_irq_disable_master(efx);
/* Count errors and reset or disable the NIC accordingly */
if (efx->int_error_count == 0 ||
time_after(jiffies, efx->int_error_expire)) {
efx->int_error_count = 0;
efx->int_error_expire =
jiffies + EFX_INT_ERROR_EXPIRE * HZ;
}
if (++efx->int_error_count < EFX_MAX_INT_ERRORS) {
netif_err(efx, hw, efx->net_dev,
"SYSTEM ERROR - reset scheduled\n");
efx_siena_schedule_reset(efx, RESET_TYPE_INT_ERROR);
} else {
netif_err(efx, hw, efx->net_dev,
"SYSTEM ERROR - max number of errors seen."
"NIC will be disabled\n");
efx_siena_schedule_reset(efx, RESET_TYPE_DISABLE);
}
return IRQ_HANDLED;
}
/* Handle a legacy interrupt
* Acknowledges the interrupt and schedule event queue processing.
*/
irqreturn_t efx_farch_legacy_interrupt(int irq, void *dev_id)
{
struct efx_nic *efx = dev_id;
bool soft_enabled = READ_ONCE(efx->irq_soft_enabled);
efx_oword_t *int_ker = efx->irq_status.addr;
irqreturn_t result = IRQ_NONE;
struct efx_channel *channel;
efx_dword_t reg;
u32 queues;
int syserr;
/* Read the ISR which also ACKs the interrupts */
efx_readd(efx, ®, FR_BZ_INT_ISR0);
queues = EFX_EXTRACT_DWORD(reg, 0, 31);
/* Legacy interrupts are disabled too late by the EEH kernel
* code. Disable them earlier.
* If an EEH error occurred, the read will have returned all ones.
*/
if (EFX_DWORD_IS_ALL_ONES(reg) && efx_siena_try_recovery(efx) &&
!efx->eeh_disabled_legacy_irq) {
disable_irq_nosync(efx->legacy_irq);
efx->eeh_disabled_legacy_irq = true;
}
/* Handle non-event-queue sources */
if (queues & (1U << efx->irq_level) && soft_enabled) {
syserr = EFX_OWORD_FIELD(*int_ker, FSF_AZ_NET_IVEC_FATAL_INT);
if (unlikely(syserr))
return efx_farch_fatal_interrupt(efx);
efx->last_irq_cpu = raw_smp_processor_id();
}
if (queues != 0) {
efx->irq_zero_count = 0;
/* Schedule processing of any interrupting queues */
if (likely(soft_enabled)) {
efx_for_each_channel(channel, efx) {
if (queues & 1)
efx_schedule_channel_irq(channel);
queues >>= 1;
}
}
result = IRQ_HANDLED;
} else {
efx_qword_t *event;
/* Legacy ISR read can return zero once (SF bug 15783) */
/* We can't return IRQ_HANDLED more than once on seeing ISR=0
* because this might be a shared interrupt. */
if (efx->irq_zero_count++ == 0)
result = IRQ_HANDLED;
/* Ensure we schedule or rearm all event queues */
if (likely(soft_enabled)) {
efx_for_each_channel(channel, efx) {
event = efx_event(channel,
channel->eventq_read_ptr);
if (efx_event_present(event))
efx_schedule_channel_irq(channel);
else
efx_farch_ev_read_ack(channel);
}
}
}
if (result == IRQ_HANDLED)
netif_vdbg(efx, intr, efx->net_dev,
"IRQ %d on CPU %d status " EFX_DWORD_FMT "\n",
irq, raw_smp_processor_id(), EFX_DWORD_VAL(reg));
return result;
}
/* Handle an MSI interrupt
*
* Handle an MSI hardware interrupt. This routine schedules event
* queue processing. No interrupt acknowledgement cycle is necessary.
* Also, we never need to check that the interrupt is for us, since
* MSI interrupts cannot be shared.
*/
irqreturn_t efx_farch_msi_interrupt(int irq, void *dev_id)
{
struct efx_msi_context *context = dev_id;
struct efx_nic *efx = context->efx;
efx_oword_t *int_ker = efx->irq_status.addr;
int syserr;
netif_vdbg(efx, intr, efx->net_dev,
"IRQ %d on CPU %d status " EFX_OWORD_FMT "\n",
irq, raw_smp_processor_id(), EFX_OWORD_VAL(*int_ker));
if (!likely(READ_ONCE(efx->irq_soft_enabled)))
return IRQ_HANDLED;
/* Handle non-event-queue sources */
if (context->index == efx->irq_level) {
syserr = EFX_OWORD_FIELD(*int_ker, FSF_AZ_NET_IVEC_FATAL_INT);
if (unlikely(syserr))
return efx_farch_fatal_interrupt(efx);
efx->last_irq_cpu = raw_smp_processor_id();
}
/* Schedule processing of the channel */
efx_schedule_channel_irq(efx->channel[context->index]);
return IRQ_HANDLED;
}
/* Setup RSS indirection table.
* This maps from the hash value of the packet to RXQ
*/
void efx_farch_rx_push_indir_table(struct efx_nic *efx)
{
size_t i = 0;
efx_dword_t dword;
BUILD_BUG_ON(ARRAY_SIZE(efx->rss_context.rx_indir_table) !=
FR_BZ_RX_INDIRECTION_TBL_ROWS);
for (i = 0; i < FR_BZ_RX_INDIRECTION_TBL_ROWS; i++) {
EFX_POPULATE_DWORD_1(dword, FRF_BZ_IT_QUEUE,
efx->rss_context.rx_indir_table[i]);
efx_writed(efx, &dword,
FR_BZ_RX_INDIRECTION_TBL +
FR_BZ_RX_INDIRECTION_TBL_STEP * i);
}
}
void efx_farch_rx_pull_indir_table(struct efx_nic *efx)
{
size_t i = 0;
efx_dword_t dword;
BUILD_BUG_ON(ARRAY_SIZE(efx->rss_context.rx_indir_table) !=
FR_BZ_RX_INDIRECTION_TBL_ROWS);
for (i = 0; i < FR_BZ_RX_INDIRECTION_TBL_ROWS; i++) {
efx_readd(efx, &dword,
FR_BZ_RX_INDIRECTION_TBL +
FR_BZ_RX_INDIRECTION_TBL_STEP * i);
efx->rss_context.rx_indir_table[i] = EFX_DWORD_FIELD(dword, FRF_BZ_IT_QUEUE);
}
}
/* Looks at available SRAM resources and works out how many queues we
* can support, and where things like descriptor caches should live.
*
* SRAM is split up as follows:
* 0 buftbl entries for channels
* efx->vf_buftbl_base buftbl entries for SR-IOV
* efx->rx_dc_base RX descriptor caches
* efx->tx_dc_base TX descriptor caches
*/
void efx_farch_dimension_resources(struct efx_nic *efx, unsigned sram_lim_qw)
{
unsigned vi_count, total_tx_channels;
#ifdef CONFIG_SFC_SIENA_SRIOV
struct siena_nic_data *nic_data;
unsigned buftbl_min;
#endif
total_tx_channels = efx->n_tx_channels + efx->n_extra_tx_channels;
vi_count = max(efx->n_channels, total_tx_channels * EFX_MAX_TXQ_PER_CHANNEL);
#ifdef CONFIG_SFC_SIENA_SRIOV
nic_data = efx->nic_data;
/* Account for the buffer table entries backing the datapath channels
* and the descriptor caches for those channels.
*/
buftbl_min = ((efx->n_rx_channels * EFX_MAX_DMAQ_SIZE +
total_tx_channels * EFX_MAX_TXQ_PER_CHANNEL * EFX_MAX_DMAQ_SIZE +
efx->n_channels * EFX_MAX_EVQ_SIZE)
* sizeof(efx_qword_t) / EFX_BUF_SIZE);
if (efx->type->sriov_wanted) {
if (efx->type->sriov_wanted(efx)) {
unsigned vi_dc_entries, buftbl_free;
unsigned entries_per_vf, vf_limit;
nic_data->vf_buftbl_base = buftbl_min;
vi_dc_entries = RX_DC_ENTRIES + TX_DC_ENTRIES;
vi_count = max(vi_count, EFX_VI_BASE);
buftbl_free = (sram_lim_qw - buftbl_min -
vi_count * vi_dc_entries);
entries_per_vf = ((vi_dc_entries +
EFX_VF_BUFTBL_PER_VI) *
efx_vf_size(efx));
vf_limit = min(buftbl_free / entries_per_vf,
(1024U - EFX_VI_BASE) >> efx->vi_scale);
if (efx->vf_count > vf_limit) {
netif_err(efx, probe, efx->net_dev,
"Reducing VF count from from %d to %d\n",
efx->vf_count, vf_limit);
efx->vf_count = vf_limit;
}
vi_count += efx->vf_count * efx_vf_size(efx);
}
}
#endif
efx->tx_dc_base = sram_lim_qw - vi_count * TX_DC_ENTRIES;
efx->rx_dc_base = efx->tx_dc_base - vi_count * RX_DC_ENTRIES;
}
u32 efx_farch_fpga_ver(struct efx_nic *efx)
{
efx_oword_t altera_build;
efx_reado(efx, &altera_build, FR_AZ_ALTERA_BUILD);
return EFX_OWORD_FIELD(altera_build, FRF_AZ_ALTERA_BUILD_VER);
}
void efx_farch_init_common(struct efx_nic *efx)
{
efx_oword_t temp;
/* Set positions of descriptor caches in SRAM. */
EFX_POPULATE_OWORD_1(temp, FRF_AZ_SRM_TX_DC_BASE_ADR, efx->tx_dc_base);
efx_writeo(efx, &temp, FR_AZ_SRM_TX_DC_CFG);
EFX_POPULATE_OWORD_1(temp, FRF_AZ_SRM_RX_DC_BASE_ADR, efx->rx_dc_base);
efx_writeo(efx, &temp, FR_AZ_SRM_RX_DC_CFG);
/* Set TX descriptor cache size. */
BUILD_BUG_ON(TX_DC_ENTRIES != (8 << TX_DC_ENTRIES_ORDER));
EFX_POPULATE_OWORD_1(temp, FRF_AZ_TX_DC_SIZE, TX_DC_ENTRIES_ORDER);
efx_writeo(efx, &temp, FR_AZ_TX_DC_CFG);
/* Set RX descriptor cache size. Set low watermark to size-8, as
* this allows most efficient prefetching.
*/
BUILD_BUG_ON(RX_DC_ENTRIES != (8 << RX_DC_ENTRIES_ORDER));
EFX_POPULATE_OWORD_1(temp, FRF_AZ_RX_DC_SIZE, RX_DC_ENTRIES_ORDER);
efx_writeo(efx, &temp, FR_AZ_RX_DC_CFG);
EFX_POPULATE_OWORD_1(temp, FRF_AZ_RX_DC_PF_LWM, RX_DC_ENTRIES - 8);
efx_writeo(efx, &temp, FR_AZ_RX_DC_PF_WM);
/* Program INT_KER address */
EFX_POPULATE_OWORD_2(temp,
FRF_AZ_NORM_INT_VEC_DIS_KER,
EFX_INT_MODE_USE_MSI(efx),
FRF_AZ_INT_ADR_KER, efx->irq_status.dma_addr);
efx_writeo(efx, &temp, FR_AZ_INT_ADR_KER);
if (EFX_WORKAROUND_17213(efx) && !EFX_INT_MODE_USE_MSI(efx))
/* Use an interrupt level unused by event queues */
efx->irq_level = 0x1f;
else
/* Use a valid MSI-X vector */
efx->irq_level = 0;
/* Enable all the genuinely fatal interrupts. (They are still
* masked by the overall interrupt mask, controlled by
* falcon_interrupts()).
*
* Note: All other fatal interrupts are enabled
*/
EFX_POPULATE_OWORD_3(temp,
FRF_AZ_ILL_ADR_INT_KER_EN, 1,
FRF_AZ_RBUF_OWN_INT_KER_EN, 1,
FRF_AZ_TBUF_OWN_INT_KER_EN, 1);
EFX_SET_OWORD_FIELD(temp, FRF_CZ_SRAM_PERR_INT_P_KER_EN, 1);
EFX_INVERT_OWORD(temp);
efx_writeo(efx, &temp, FR_AZ_FATAL_INTR_KER);
/* Disable the ugly timer-based TX DMA backoff and allow TX DMA to be
* controlled by the RX FIFO fill level. Set arbitration to one pkt/Q.
*/
efx_reado(efx, &temp, FR_AZ_TX_RESERVED);
EFX_SET_OWORD_FIELD(temp, FRF_AZ_TX_RX_SPACER, 0xfe);
EFX_SET_OWORD_FIELD(temp, FRF_AZ_TX_RX_SPACER_EN, 1);
EFX_SET_OWORD_FIELD(temp, FRF_AZ_TX_ONE_PKT_PER_Q, 1);
EFX_SET_OWORD_FIELD(temp, FRF_AZ_TX_PUSH_EN, 1);
EFX_SET_OWORD_FIELD(temp, FRF_AZ_TX_DIS_NON_IP_EV, 1);
/* Enable SW_EV to inherit in char driver - assume harmless here */
EFX_SET_OWORD_FIELD(temp, FRF_AZ_TX_SOFT_EVT_EN, 1);
/* Prefetch threshold 2 => fetch when descriptor cache half empty */
EFX_SET_OWORD_FIELD(temp, FRF_AZ_TX_PREF_THRESHOLD, 2);
/* Disable hardware watchdog which can misfire */
EFX_SET_OWORD_FIELD(temp, FRF_AZ_TX_PREF_WD_TMR, 0x3fffff);
/* Squash TX of packets of 16 bytes or less */
EFX_SET_OWORD_FIELD(temp, FRF_BZ_TX_FLUSH_MIN_LEN_EN, 1);
efx_writeo(efx, &temp, FR_AZ_TX_RESERVED);
EFX_POPULATE_OWORD_4(temp,
/* Default values */
FRF_BZ_TX_PACE_SB_NOT_AF, 0x15,
FRF_BZ_TX_PACE_SB_AF, 0xb,
FRF_BZ_TX_PACE_FB_BASE, 0,
/* Allow large pace values in the fast bin. */
FRF_BZ_TX_PACE_BIN_TH,
FFE_BZ_TX_PACE_RESERVED);
efx_writeo(efx, &temp, FR_BZ_TX_PACE);
}
/**************************************************************************
*
* Filter tables
*
**************************************************************************
*/
/* "Fudge factors" - difference between programmed value and actual depth.
* Due to pipelined implementation we need to program H/W with a value that
* is larger than the hop limit we want.
*/
#define EFX_FARCH_FILTER_CTL_SRCH_FUDGE_WILD 3
#define EFX_FARCH_FILTER_CTL_SRCH_FUDGE_FULL 1
/* Hard maximum search limit. Hardware will time-out beyond 200-something.
* We also need to avoid infinite loops in efx_farch_filter_search() when the
* table is full.
*/
#define EFX_FARCH_FILTER_CTL_SRCH_MAX 200
/* Don't try very hard to find space for performance hints, as this is
* counter-productive. */
#define EFX_FARCH_FILTER_CTL_SRCH_HINT_MAX 5
enum efx_farch_filter_type {
EFX_FARCH_FILTER_TCP_FULL = 0,
EFX_FARCH_FILTER_TCP_WILD,
EFX_FARCH_FILTER_UDP_FULL,
EFX_FARCH_FILTER_UDP_WILD,
EFX_FARCH_FILTER_MAC_FULL = 4,
EFX_FARCH_FILTER_MAC_WILD,
EFX_FARCH_FILTER_UC_DEF = 8,
EFX_FARCH_FILTER_MC_DEF,
EFX_FARCH_FILTER_TYPE_COUNT, /* number of specific types */
};
enum efx_farch_filter_table_id {
EFX_FARCH_FILTER_TABLE_RX_IP = 0,
EFX_FARCH_FILTER_TABLE_RX_MAC,
EFX_FARCH_FILTER_TABLE_RX_DEF,
EFX_FARCH_FILTER_TABLE_TX_MAC,
EFX_FARCH_FILTER_TABLE_COUNT,
};
enum efx_farch_filter_index {
EFX_FARCH_FILTER_INDEX_UC_DEF,
EFX_FARCH_FILTER_INDEX_MC_DEF,
EFX_FARCH_FILTER_SIZE_RX_DEF,
};
struct efx_farch_filter_spec {
u8 type:4;
u8 priority:4;
u8 flags;
u16 dmaq_id;
u32 data[3];
};
struct efx_farch_filter_table {
enum efx_farch_filter_table_id id;
u32 offset; /* address of table relative to BAR */
unsigned size; /* number of entries */
unsigned step; /* step between entries */
unsigned used; /* number currently used */
unsigned long *used_bitmap;
struct efx_farch_filter_spec *spec;
unsigned search_limit[EFX_FARCH_FILTER_TYPE_COUNT];
};
struct efx_farch_filter_state {
struct rw_semaphore lock; /* Protects table contents */
struct efx_farch_filter_table table[EFX_FARCH_FILTER_TABLE_COUNT];
};
static void
efx_farch_filter_table_clear_entry(struct efx_nic *efx,
struct efx_farch_filter_table *table,
unsigned int filter_idx);
/* The filter hash function is LFSR polynomial x^16 + x^3 + 1 of a 32-bit
* key derived from the n-tuple. The initial LFSR state is 0xffff. */
static u16 efx_farch_filter_hash(u32 key)
{
u16 tmp;
/* First 16 rounds */
tmp = 0x1fff ^ key >> 16;
tmp = tmp ^ tmp >> 3 ^ tmp >> 6;
tmp = tmp ^ tmp >> 9;
/* Last 16 rounds */
tmp = tmp ^ tmp << 13 ^ key;
tmp = tmp ^ tmp >> 3 ^ tmp >> 6;
return tmp ^ tmp >> 9;
}
/* To allow for hash collisions, filter search continues at these
* increments from the first possible entry selected by the hash. */
static u16 efx_farch_filter_increment(u32 key)
{
return key * 2 - 1;
}
static enum efx_farch_filter_table_id
efx_farch_filter_spec_table_id(const struct efx_farch_filter_spec *spec)
{
BUILD_BUG_ON(EFX_FARCH_FILTER_TABLE_RX_IP !=
(EFX_FARCH_FILTER_TCP_FULL >> 2));
BUILD_BUG_ON(EFX_FARCH_FILTER_TABLE_RX_IP !=
(EFX_FARCH_FILTER_TCP_WILD >> 2));
BUILD_BUG_ON(EFX_FARCH_FILTER_TABLE_RX_IP !=
(EFX_FARCH_FILTER_UDP_FULL >> 2));
BUILD_BUG_ON(EFX_FARCH_FILTER_TABLE_RX_IP !=
(EFX_FARCH_FILTER_UDP_WILD >> 2));
BUILD_BUG_ON(EFX_FARCH_FILTER_TABLE_RX_MAC !=
(EFX_FARCH_FILTER_MAC_FULL >> 2));
BUILD_BUG_ON(EFX_FARCH_FILTER_TABLE_RX_MAC !=
(EFX_FARCH_FILTER_MAC_WILD >> 2));
BUILD_BUG_ON(EFX_FARCH_FILTER_TABLE_TX_MAC !=
EFX_FARCH_FILTER_TABLE_RX_MAC + 2);
return (spec->type >> 2) + ((spec->flags & EFX_FILTER_FLAG_TX) ? 2 : 0);
}
static void efx_farch_filter_push_rx_config(struct efx_nic *efx)
{
struct efx_farch_filter_state *state = efx->filter_state;
struct efx_farch_filter_table *table;
efx_oword_t filter_ctl;
efx_reado(efx, &filter_ctl, FR_BZ_RX_FILTER_CTL);
table = &state->table[EFX_FARCH_FILTER_TABLE_RX_IP];
EFX_SET_OWORD_FIELD(filter_ctl, FRF_BZ_TCP_FULL_SRCH_LIMIT,
table->search_limit[EFX_FARCH_FILTER_TCP_FULL] +
EFX_FARCH_FILTER_CTL_SRCH_FUDGE_FULL);
EFX_SET_OWORD_FIELD(filter_ctl, FRF_BZ_TCP_WILD_SRCH_LIMIT,
table->search_limit[EFX_FARCH_FILTER_TCP_WILD] +
EFX_FARCH_FILTER_CTL_SRCH_FUDGE_WILD);
EFX_SET_OWORD_FIELD(filter_ctl, FRF_BZ_UDP_FULL_SRCH_LIMIT,
table->search_limit[EFX_FARCH_FILTER_UDP_FULL] +
EFX_FARCH_FILTER_CTL_SRCH_FUDGE_FULL);
EFX_SET_OWORD_FIELD(filter_ctl, FRF_BZ_UDP_WILD_SRCH_LIMIT,
table->search_limit[EFX_FARCH_FILTER_UDP_WILD] +
EFX_FARCH_FILTER_CTL_SRCH_FUDGE_WILD);
table = &state->table[EFX_FARCH_FILTER_TABLE_RX_MAC];
if (table->size) {
EFX_SET_OWORD_FIELD(
filter_ctl, FRF_CZ_ETHERNET_FULL_SEARCH_LIMIT,
table->search_limit[EFX_FARCH_FILTER_MAC_FULL] +
EFX_FARCH_FILTER_CTL_SRCH_FUDGE_FULL);
EFX_SET_OWORD_FIELD(
filter_ctl, FRF_CZ_ETHERNET_WILDCARD_SEARCH_LIMIT,
table->search_limit[EFX_FARCH_FILTER_MAC_WILD] +
EFX_FARCH_FILTER_CTL_SRCH_FUDGE_WILD);
}
table = &state->table[EFX_FARCH_FILTER_TABLE_RX_DEF];
if (table->size) {
EFX_SET_OWORD_FIELD(
filter_ctl, FRF_CZ_UNICAST_NOMATCH_Q_ID,
table->spec[EFX_FARCH_FILTER_INDEX_UC_DEF].dmaq_id);
EFX_SET_OWORD_FIELD(
filter_ctl, FRF_CZ_UNICAST_NOMATCH_RSS_ENABLED,
!!(table->spec[EFX_FARCH_FILTER_INDEX_UC_DEF].flags &
EFX_FILTER_FLAG_RX_RSS));
EFX_SET_OWORD_FIELD(
filter_ctl, FRF_CZ_MULTICAST_NOMATCH_Q_ID,
table->spec[EFX_FARCH_FILTER_INDEX_MC_DEF].dmaq_id);
EFX_SET_OWORD_FIELD(
filter_ctl, FRF_CZ_MULTICAST_NOMATCH_RSS_ENABLED,
!!(table->spec[EFX_FARCH_FILTER_INDEX_MC_DEF].flags &
EFX_FILTER_FLAG_RX_RSS));
/* There is a single bit to enable RX scatter for all
* unmatched packets. Only set it if scatter is
* enabled in both filter specs.
*/
EFX_SET_OWORD_FIELD(
filter_ctl, FRF_BZ_SCATTER_ENBL_NO_MATCH_Q,
!!(table->spec[EFX_FARCH_FILTER_INDEX_UC_DEF].flags &
table->spec[EFX_FARCH_FILTER_INDEX_MC_DEF].flags &
EFX_FILTER_FLAG_RX_SCATTER));
} else {
/* We don't expose 'default' filters because unmatched
* packets always go to the queue number found in the
* RSS table. But we still need to set the RX scatter
* bit here.
*/
EFX_SET_OWORD_FIELD(
filter_ctl, FRF_BZ_SCATTER_ENBL_NO_MATCH_Q,
efx->rx_scatter);
}
efx_writeo(efx, &filter_ctl, FR_BZ_RX_FILTER_CTL);
}
static void efx_farch_filter_push_tx_limits(struct efx_nic *efx)
{
struct efx_farch_filter_state *state = efx->filter_state;
struct efx_farch_filter_table *table;
efx_oword_t tx_cfg;
efx_reado(efx, &tx_cfg, FR_AZ_TX_CFG);
table = &state->table[EFX_FARCH_FILTER_TABLE_TX_MAC];
if (table->size) {
EFX_SET_OWORD_FIELD(
tx_cfg, FRF_CZ_TX_ETH_FILTER_FULL_SEARCH_RANGE,
table->search_limit[EFX_FARCH_FILTER_MAC_FULL] +
EFX_FARCH_FILTER_CTL_SRCH_FUDGE_FULL);
EFX_SET_OWORD_FIELD(
tx_cfg, FRF_CZ_TX_ETH_FILTER_WILD_SEARCH_RANGE,
table->search_limit[EFX_FARCH_FILTER_MAC_WILD] +
EFX_FARCH_FILTER_CTL_SRCH_FUDGE_WILD);
}
efx_writeo(efx, &tx_cfg, FR_AZ_TX_CFG);
}
static int
efx_farch_filter_from_gen_spec(struct efx_farch_filter_spec *spec,
const struct efx_filter_spec *gen_spec)
{
bool is_full = false;
if ((gen_spec->flags & EFX_FILTER_FLAG_RX_RSS) && gen_spec->rss_context)
return -EINVAL;
spec->priority = gen_spec->priority;
spec->flags = gen_spec->flags;
spec->dmaq_id = gen_spec->dmaq_id;
switch (gen_spec->match_flags) {
case (EFX_FILTER_MATCH_ETHER_TYPE | EFX_FILTER_MATCH_IP_PROTO |
EFX_FILTER_MATCH_LOC_HOST | EFX_FILTER_MATCH_LOC_PORT |
EFX_FILTER_MATCH_REM_HOST | EFX_FILTER_MATCH_REM_PORT):
is_full = true;
fallthrough;
case (EFX_FILTER_MATCH_ETHER_TYPE | EFX_FILTER_MATCH_IP_PROTO |
EFX_FILTER_MATCH_LOC_HOST | EFX_FILTER_MATCH_LOC_PORT): {
__be32 rhost, host1, host2;
__be16 rport, port1, port2;
EFX_WARN_ON_PARANOID(!(gen_spec->flags & EFX_FILTER_FLAG_RX));
if (gen_spec->ether_type != htons(ETH_P_IP))
return -EPROTONOSUPPORT;
if (gen_spec->loc_port == 0 ||
(is_full && gen_spec->rem_port == 0))
return -EADDRNOTAVAIL;
switch (gen_spec->ip_proto) {
case IPPROTO_TCP:
spec->type = (is_full ? EFX_FARCH_FILTER_TCP_FULL :
EFX_FARCH_FILTER_TCP_WILD);
break;
case IPPROTO_UDP:
spec->type = (is_full ? EFX_FARCH_FILTER_UDP_FULL :
EFX_FARCH_FILTER_UDP_WILD);
break;
default:
return -EPROTONOSUPPORT;
}
/* Filter is constructed in terms of source and destination,
* with the odd wrinkle that the ports are swapped in a UDP
* wildcard filter. We need to convert from local and remote
* (= zero for wildcard) addresses.
*/
rhost = is_full ? gen_spec->rem_host[0] : 0;
rport = is_full ? gen_spec->rem_port : 0;
host1 = rhost;
host2 = gen_spec->loc_host[0];
if (!is_full && gen_spec->ip_proto == IPPROTO_UDP) {
port1 = gen_spec->loc_port;
port2 = rport;
} else {
port1 = rport;
port2 = gen_spec->loc_port;
}
spec->data[0] = ntohl(host1) << 16 | ntohs(port1);
spec->data[1] = ntohs(port2) << 16 | ntohl(host1) >> 16;
spec->data[2] = ntohl(host2);
break;
}
case EFX_FILTER_MATCH_LOC_MAC | EFX_FILTER_MATCH_OUTER_VID:
is_full = true;
fallthrough;
case EFX_FILTER_MATCH_LOC_MAC:
spec->type = (is_full ? EFX_FARCH_FILTER_MAC_FULL :
EFX_FARCH_FILTER_MAC_WILD);
spec->data[0] = is_full ? ntohs(gen_spec->outer_vid) : 0;
spec->data[1] = (gen_spec->loc_mac[2] << 24 |
gen_spec->loc_mac[3] << 16 |
gen_spec->loc_mac[4] << 8 |
gen_spec->loc_mac[5]);
spec->data[2] = (gen_spec->loc_mac[0] << 8 |
gen_spec->loc_mac[1]);
break;
case EFX_FILTER_MATCH_LOC_MAC_IG:
spec->type = (is_multicast_ether_addr(gen_spec->loc_mac) ?
EFX_FARCH_FILTER_MC_DEF :
EFX_FARCH_FILTER_UC_DEF);
memset(spec->data, 0, sizeof(spec->data)); /* ensure equality */
break;
default:
return -EPROTONOSUPPORT;
}
return 0;
}
static void
efx_farch_filter_to_gen_spec(struct efx_filter_spec *gen_spec,
const struct efx_farch_filter_spec *spec)
{
bool is_full = false;
/* *gen_spec should be completely initialised, to be consistent
* with efx_filter_init_{rx,tx}() and in case we want to copy
* it back to userland.
*/
memset(gen_spec, 0, sizeof(*gen_spec));
gen_spec->priority = spec->priority;
gen_spec->flags = spec->flags;
gen_spec->dmaq_id = spec->dmaq_id;
switch (spec->type) {
case EFX_FARCH_FILTER_TCP_FULL:
case EFX_FARCH_FILTER_UDP_FULL:
is_full = true;
fallthrough;
case EFX_FARCH_FILTER_TCP_WILD:
case EFX_FARCH_FILTER_UDP_WILD: {
__be32 host1, host2;
__be16 port1, port2;
gen_spec->match_flags =
EFX_FILTER_MATCH_ETHER_TYPE |
EFX_FILTER_MATCH_IP_PROTO |
EFX_FILTER_MATCH_LOC_HOST | EFX_FILTER_MATCH_LOC_PORT;
if (is_full)
gen_spec->match_flags |= (EFX_FILTER_MATCH_REM_HOST |
EFX_FILTER_MATCH_REM_PORT);
gen_spec->ether_type = htons(ETH_P_IP);
gen_spec->ip_proto =
(spec->type == EFX_FARCH_FILTER_TCP_FULL ||
spec->type == EFX_FARCH_FILTER_TCP_WILD) ?
IPPROTO_TCP : IPPROTO_UDP;
host1 = htonl(spec->data[0] >> 16 | spec->data[1] << 16);
port1 = htons(spec->data[0]);
host2 = htonl(spec->data[2]);
port2 = htons(spec->data[1] >> 16);
if (spec->flags & EFX_FILTER_FLAG_TX) {
gen_spec->loc_host[0] = host1;
gen_spec->rem_host[0] = host2;
} else {
gen_spec->loc_host[0] = host2;
gen_spec->rem_host[0] = host1;
}
if (!!(gen_spec->flags & EFX_FILTER_FLAG_TX) ^
(!is_full && gen_spec->ip_proto == IPPROTO_UDP)) {
gen_spec->loc_port = port1;
gen_spec->rem_port = port2;
} else {
gen_spec->loc_port = port2;
gen_spec->rem_port = port1;
}
break;
}
case EFX_FARCH_FILTER_MAC_FULL:
is_full = true;
fallthrough;
case EFX_FARCH_FILTER_MAC_WILD:
gen_spec->match_flags = EFX_FILTER_MATCH_LOC_MAC;
if (is_full)
gen_spec->match_flags |= EFX_FILTER_MATCH_OUTER_VID;
gen_spec->loc_mac[0] = spec->data[2] >> 8;
gen_spec->loc_mac[1] = spec->data[2];
gen_spec->loc_mac[2] = spec->data[1] >> 24;
gen_spec->loc_mac[3] = spec->data[1] >> 16;
gen_spec->loc_mac[4] = spec->data[1] >> 8;
gen_spec->loc_mac[5] = spec->data[1];
gen_spec->outer_vid = htons(spec->data[0]);
break;
case EFX_FARCH_FILTER_UC_DEF:
case EFX_FARCH_FILTER_MC_DEF:
gen_spec->match_flags = EFX_FILTER_MATCH_LOC_MAC_IG;
gen_spec->loc_mac[0] = spec->type == EFX_FARCH_FILTER_MC_DEF;
break;
default:
WARN_ON(1);
break;
}
}
static void
efx_farch_filter_init_rx_auto(struct efx_nic *efx,
struct efx_farch_filter_spec *spec)
{
/* If there's only one channel then disable RSS for non VF
* traffic, thereby allowing VFs to use RSS when the PF can't.
*/
spec->priority = EFX_FILTER_PRI_AUTO;
spec->flags = (EFX_FILTER_FLAG_RX |
(efx_rss_enabled(efx) ? EFX_FILTER_FLAG_RX_RSS : 0) |
(efx->rx_scatter ? EFX_FILTER_FLAG_RX_SCATTER : 0));
spec->dmaq_id = 0;
}
/* Build a filter entry and return its n-tuple key. */
static u32 efx_farch_filter_build(efx_oword_t *filter,
struct efx_farch_filter_spec *spec)
{
u32 data3;
switch (efx_farch_filter_spec_table_id(spec)) {
case EFX_FARCH_FILTER_TABLE_RX_IP: {
bool is_udp = (spec->type == EFX_FARCH_FILTER_UDP_FULL ||
spec->type == EFX_FARCH_FILTER_UDP_WILD);
EFX_POPULATE_OWORD_7(
*filter,
FRF_BZ_RSS_EN,
!!(spec->flags & EFX_FILTER_FLAG_RX_RSS),
FRF_BZ_SCATTER_EN,
!!(spec->flags & EFX_FILTER_FLAG_RX_SCATTER),
FRF_BZ_TCP_UDP, is_udp,
FRF_BZ_RXQ_ID, spec->dmaq_id,
EFX_DWORD_2, spec->data[2],
EFX_DWORD_1, spec->data[1],
EFX_DWORD_0, spec->data[0]);
data3 = is_udp;
break;
}
case EFX_FARCH_FILTER_TABLE_RX_MAC: {
bool is_wild = spec->type == EFX_FARCH_FILTER_MAC_WILD;
EFX_POPULATE_OWORD_7(
*filter,
FRF_CZ_RMFT_RSS_EN,
!!(spec->flags & EFX_FILTER_FLAG_RX_RSS),
FRF_CZ_RMFT_SCATTER_EN,
!!(spec->flags & EFX_FILTER_FLAG_RX_SCATTER),
FRF_CZ_RMFT_RXQ_ID, spec->dmaq_id,
FRF_CZ_RMFT_WILDCARD_MATCH, is_wild,
FRF_CZ_RMFT_DEST_MAC_HI, spec->data[2],
FRF_CZ_RMFT_DEST_MAC_LO, spec->data[1],
FRF_CZ_RMFT_VLAN_ID, spec->data[0]);
data3 = is_wild;
break;
}
case EFX_FARCH_FILTER_TABLE_TX_MAC: {
bool is_wild = spec->type == EFX_FARCH_FILTER_MAC_WILD;
EFX_POPULATE_OWORD_5(*filter,
FRF_CZ_TMFT_TXQ_ID, spec->dmaq_id,
FRF_CZ_TMFT_WILDCARD_MATCH, is_wild,
FRF_CZ_TMFT_SRC_MAC_HI, spec->data[2],
FRF_CZ_TMFT_SRC_MAC_LO, spec->data[1],
FRF_CZ_TMFT_VLAN_ID, spec->data[0]);
data3 = is_wild | spec->dmaq_id << 1;
break;
}
default:
BUG();
}
return spec->data[0] ^ spec->data[1] ^ spec->data[2] ^ data3;
}
static bool efx_farch_filter_equal(const struct efx_farch_filter_spec *left,
const struct efx_farch_filter_spec *right)
{
if (left->type != right->type ||
memcmp(left->data, right->data, sizeof(left->data)))
return false;
if (left->flags & EFX_FILTER_FLAG_TX &&
left->dmaq_id != right->dmaq_id)
return false;
return true;
}
/*
* Construct/deconstruct external filter IDs. At least the RX filter
* IDs must be ordered by matching priority, for RX NFC semantics.
*
* Deconstruction needs to be robust against invalid IDs so that
* efx_filter_remove_id_safe() and efx_filter_get_filter_safe() can
* accept user-provided IDs.
*/
#define EFX_FARCH_FILTER_MATCH_PRI_COUNT 5
static const u8 efx_farch_filter_type_match_pri[EFX_FARCH_FILTER_TYPE_COUNT] = {
[EFX_FARCH_FILTER_TCP_FULL] = 0,
[EFX_FARCH_FILTER_UDP_FULL] = 0,
[EFX_FARCH_FILTER_TCP_WILD] = 1,
[EFX_FARCH_FILTER_UDP_WILD] = 1,
[EFX_FARCH_FILTER_MAC_FULL] = 2,
[EFX_FARCH_FILTER_MAC_WILD] = 3,
[EFX_FARCH_FILTER_UC_DEF] = 4,
[EFX_FARCH_FILTER_MC_DEF] = 4,
};
static const enum efx_farch_filter_table_id efx_farch_filter_range_table[] = {
EFX_FARCH_FILTER_TABLE_RX_IP, /* RX match pri 0 */
EFX_FARCH_FILTER_TABLE_RX_IP,
EFX_FARCH_FILTER_TABLE_RX_MAC,
EFX_FARCH_FILTER_TABLE_RX_MAC,
EFX_FARCH_FILTER_TABLE_RX_DEF, /* RX match pri 4 */
EFX_FARCH_FILTER_TABLE_TX_MAC, /* TX match pri 0 */
EFX_FARCH_FILTER_TABLE_TX_MAC, /* TX match pri 1 */
};
#define EFX_FARCH_FILTER_INDEX_WIDTH 13
#define EFX_FARCH_FILTER_INDEX_MASK ((1 << EFX_FARCH_FILTER_INDEX_WIDTH) - 1)
static inline u32
efx_farch_filter_make_id(const struct efx_farch_filter_spec *spec,
unsigned int index)
{
unsigned int range;
range = efx_farch_filter_type_match_pri[spec->type];
if (!(spec->flags & EFX_FILTER_FLAG_RX))
range += EFX_FARCH_FILTER_MATCH_PRI_COUNT;
return range << EFX_FARCH_FILTER_INDEX_WIDTH | index;
}
static inline enum efx_farch_filter_table_id
efx_farch_filter_id_table_id(u32 id)
{
unsigned int range = id >> EFX_FARCH_FILTER_INDEX_WIDTH;
if (range < ARRAY_SIZE(efx_farch_filter_range_table))
return efx_farch_filter_range_table[range];
else
return EFX_FARCH_FILTER_TABLE_COUNT; /* invalid */
}
static inline unsigned int efx_farch_filter_id_index(u32 id)
{
return id & EFX_FARCH_FILTER_INDEX_MASK;
}
u32 efx_farch_filter_get_rx_id_limit(struct efx_nic *efx)
{
struct efx_farch_filter_state *state = efx->filter_state;
unsigned int range = EFX_FARCH_FILTER_MATCH_PRI_COUNT - 1;
enum efx_farch_filter_table_id table_id;
do {
table_id = efx_farch_filter_range_table[range];
if (state->table[table_id].size != 0)
return range << EFX_FARCH_FILTER_INDEX_WIDTH |
state->table[table_id].size;
} while (range--);
return 0;
}
s32 efx_farch_filter_insert(struct efx_nic *efx,
struct efx_filter_spec *gen_spec,
bool replace_equal)
{
struct efx_farch_filter_state *state = efx->filter_state;
struct efx_farch_filter_table *table;
struct efx_farch_filter_spec spec;
efx_oword_t filter;
int rep_index, ins_index;
unsigned int depth = 0;
int rc;
rc = efx_farch_filter_from_gen_spec(&spec, gen_spec);
if (rc)
return rc;
down_write(&state->lock);
table = &state->table[efx_farch_filter_spec_table_id(&spec)];
if (table->size == 0) {
rc = -EINVAL;
goto out_unlock;
}
netif_vdbg(efx, hw, efx->net_dev,
"%s: type %d search_limit=%d", __func__, spec.type,
table->search_limit[spec.type]);
if (table->id == EFX_FARCH_FILTER_TABLE_RX_DEF) {
/* One filter spec per type */
BUILD_BUG_ON(EFX_FARCH_FILTER_INDEX_UC_DEF != 0);
BUILD_BUG_ON(EFX_FARCH_FILTER_INDEX_MC_DEF !=
EFX_FARCH_FILTER_MC_DEF - EFX_FARCH_FILTER_UC_DEF);
rep_index = spec.type - EFX_FARCH_FILTER_UC_DEF;
ins_index = rep_index;
} else {
/* Search concurrently for
* (1) a filter to be replaced (rep_index): any filter
* with the same match values, up to the current
* search depth for this type, and
* (2) the insertion point (ins_index): (1) or any
* free slot before it or up to the maximum search
* depth for this priority
* We fail if we cannot find (2).
*
* We can stop once either
* (a) we find (1), in which case we have definitely
* found (2) as well; or
* (b) we have searched exhaustively for (1), and have
* either found (2) or searched exhaustively for it
*/
u32 key = efx_farch_filter_build(&filter, &spec);
unsigned int hash = efx_farch_filter_hash(key);
unsigned int incr = efx_farch_filter_increment(key);
unsigned int max_rep_depth = table->search_limit[spec.type];
unsigned int max_ins_depth =
spec.priority <= EFX_FILTER_PRI_HINT ?
EFX_FARCH_FILTER_CTL_SRCH_HINT_MAX :
EFX_FARCH_FILTER_CTL_SRCH_MAX;
unsigned int i = hash & (table->size - 1);
ins_index = -1;
depth = 1;
for (;;) {
if (!test_bit(i, table->used_bitmap)) {
if (ins_index < 0)
ins_index = i;
} else if (efx_farch_filter_equal(&spec,
&table->spec[i])) {
/* Case (a) */
if (ins_index < 0)
ins_index = i;
rep_index = i;
break;
}
if (depth >= max_rep_depth &&
(ins_index >= 0 || depth >= max_ins_depth)) {
/* Case (b) */
if (ins_index < 0) {
rc = -EBUSY;
goto out_unlock;
}
rep_index = -1;
break;
}
i = (i + incr) & (table->size - 1);
++depth;
}
}
/* If we found a filter to be replaced, check whether we
* should do so
*/
if (rep_index >= 0) {
struct efx_farch_filter_spec *saved_spec =
&table->spec[rep_index];
if (spec.priority == saved_spec->priority && !replace_equal) {
rc = -EEXIST;
goto out_unlock;
}
if (spec.priority < saved_spec->priority) {
rc = -EPERM;
goto out_unlock;
}
if (saved_spec->priority == EFX_FILTER_PRI_AUTO ||
saved_spec->flags & EFX_FILTER_FLAG_RX_OVER_AUTO)
spec.flags |= EFX_FILTER_FLAG_RX_OVER_AUTO;
}
/* Insert the filter */
if (ins_index != rep_index) {
__set_bit(ins_index, table->used_bitmap);
++table->used;
}
table->spec[ins_index] = spec;
if (table->id == EFX_FARCH_FILTER_TABLE_RX_DEF) {
efx_farch_filter_push_rx_config(efx);
} else {
if (table->search_limit[spec.type] < depth) {
table->search_limit[spec.type] = depth;
if (spec.flags & EFX_FILTER_FLAG_TX)
efx_farch_filter_push_tx_limits(efx);
else
efx_farch_filter_push_rx_config(efx);
}
efx_writeo(efx, &filter,
table->offset + table->step * ins_index);
/* If we were able to replace a filter by inserting
* at a lower depth, clear the replaced filter
*/
if (ins_index != rep_index && rep_index >= 0)
efx_farch_filter_table_clear_entry(efx, table,
rep_index);
}
netif_vdbg(efx, hw, efx->net_dev,
"%s: filter type %d index %d rxq %u set",
__func__, spec.type, ins_index, spec.dmaq_id);
rc = efx_farch_filter_make_id(&spec, ins_index);
out_unlock:
up_write(&state->lock);
return rc;
}
static void
efx_farch_filter_table_clear_entry(struct efx_nic *efx,
struct efx_farch_filter_table *table,
unsigned int filter_idx)
{
static efx_oword_t filter;
EFX_WARN_ON_PARANOID(!test_bit(filter_idx, table->used_bitmap));
BUG_ON(table->offset == 0); /* can't clear MAC default filters */
__clear_bit(filter_idx, table->used_bitmap);
--table->used;
memset(&table->spec[filter_idx], 0, sizeof(table->spec[0]));
efx_writeo(efx, &filter, table->offset + table->step * filter_idx);
/* If this filter required a greater search depth than
* any other, the search limit for its type can now be
* decreased. However, it is hard to determine that
* unless the table has become completely empty - in
* which case, all its search limits can be set to 0.
*/
if (unlikely(table->used == 0)) {
memset(table->search_limit, 0, sizeof(table->search_limit));
if (table->id == EFX_FARCH_FILTER_TABLE_TX_MAC)
efx_farch_filter_push_tx_limits(efx);
else
efx_farch_filter_push_rx_config(efx);
}
}
static int efx_farch_filter_remove(struct efx_nic *efx,
struct efx_farch_filter_table *table,
unsigned int filter_idx,
enum efx_filter_priority priority)
{
struct efx_farch_filter_spec *spec = &table->spec[filter_idx];
if (!test_bit(filter_idx, table->used_bitmap) ||
spec->priority != priority)
return -ENOENT;
if (spec->flags & EFX_FILTER_FLAG_RX_OVER_AUTO) {
efx_farch_filter_init_rx_auto(efx, spec);
efx_farch_filter_push_rx_config(efx);
} else {
efx_farch_filter_table_clear_entry(efx, table, filter_idx);
}
return 0;
}
int efx_farch_filter_remove_safe(struct efx_nic *efx,
enum efx_filter_priority priority,
u32 filter_id)
{
struct efx_farch_filter_state *state = efx->filter_state;
enum efx_farch_filter_table_id table_id;
struct efx_farch_filter_table *table;
unsigned int filter_idx;
int rc;
table_id = efx_farch_filter_id_table_id(filter_id);
if ((unsigned int)table_id >= EFX_FARCH_FILTER_TABLE_COUNT)
return -ENOENT;
table = &state->table[table_id];
filter_idx = efx_farch_filter_id_index(filter_id);
if (filter_idx >= table->size)
return -ENOENT;
down_write(&state->lock);
rc = efx_farch_filter_remove(efx, table, filter_idx, priority);
up_write(&state->lock);
return rc;
}
int efx_farch_filter_get_safe(struct efx_nic *efx,
enum efx_filter_priority priority,
u32 filter_id, struct efx_filter_spec *spec_buf)
{
struct efx_farch_filter_state *state = efx->filter_state;
enum efx_farch_filter_table_id table_id;
struct efx_farch_filter_table *table;
struct efx_farch_filter_spec *spec;
unsigned int filter_idx;
int rc = -ENOENT;
down_read(&state->lock);
table_id = efx_farch_filter_id_table_id(filter_id);
if ((unsigned int)table_id >= EFX_FARCH_FILTER_TABLE_COUNT)
goto out_unlock;
table = &state->table[table_id];
filter_idx = efx_farch_filter_id_index(filter_id);
if (filter_idx >= table->size)
goto out_unlock;
spec = &table->spec[filter_idx];
if (test_bit(filter_idx, table->used_bitmap) &&
spec->priority == priority) {
efx_farch_filter_to_gen_spec(spec_buf, spec);
rc = 0;
}
out_unlock:
up_read(&state->lock);
return rc;
}
static void
efx_farch_filter_table_clear(struct efx_nic *efx,
enum efx_farch_filter_table_id table_id,
enum efx_filter_priority priority)
{
struct efx_farch_filter_state *state = efx->filter_state;
struct efx_farch_filter_table *table = &state->table[table_id];
unsigned int filter_idx;
down_write(&state->lock);
for (filter_idx = 0; filter_idx < table->size; ++filter_idx) {
if (table->spec[filter_idx].priority != EFX_FILTER_PRI_AUTO)
efx_farch_filter_remove(efx, table,
filter_idx, priority);
}
up_write(&state->lock);
}
int efx_farch_filter_clear_rx(struct efx_nic *efx,
enum efx_filter_priority priority)
{
efx_farch_filter_table_clear(efx, EFX_FARCH_FILTER_TABLE_RX_IP,
priority);
efx_farch_filter_table_clear(efx, EFX_FARCH_FILTER_TABLE_RX_MAC,
priority);
efx_farch_filter_table_clear(efx, EFX_FARCH_FILTER_TABLE_RX_DEF,
priority);
return 0;
}
u32 efx_farch_filter_count_rx_used(struct efx_nic *efx,
enum efx_filter_priority priority)
{
struct efx_farch_filter_state *state = efx->filter_state;
enum efx_farch_filter_table_id table_id;
struct efx_farch_filter_table *table;
unsigned int filter_idx;
u32 count = 0;
down_read(&state->lock);
for (table_id = EFX_FARCH_FILTER_TABLE_RX_IP;
table_id <= EFX_FARCH_FILTER_TABLE_RX_DEF;
table_id++) {
table = &state->table[table_id];
for (filter_idx = 0; filter_idx < table->size; filter_idx++) {
if (test_bit(filter_idx, table->used_bitmap) &&
table->spec[filter_idx].priority == priority)
++count;
}
}
up_read(&state->lock);
return count;
}
s32 efx_farch_filter_get_rx_ids(struct efx_nic *efx,
enum efx_filter_priority priority,
u32 *buf, u32 size)
{
struct efx_farch_filter_state *state = efx->filter_state;
enum efx_farch_filter_table_id table_id;
struct efx_farch_filter_table *table;
unsigned int filter_idx;
s32 count = 0;
down_read(&state->lock);
for (table_id = EFX_FARCH_FILTER_TABLE_RX_IP;
table_id <= EFX_FARCH_FILTER_TABLE_RX_DEF;
table_id++) {
table = &state->table[table_id];
for (filter_idx = 0; filter_idx < table->size; filter_idx++) {
if (test_bit(filter_idx, table->used_bitmap) &&
table->spec[filter_idx].priority == priority) {
if (count == size) {
count = -EMSGSIZE;
goto out;
}
buf[count++] = efx_farch_filter_make_id(
&table->spec[filter_idx], filter_idx);
}
}
}
out:
up_read(&state->lock);
return count;
}
/* Restore filter stater after reset */
void efx_farch_filter_table_restore(struct efx_nic *efx)
{
struct efx_farch_filter_state *state = efx->filter_state;
enum efx_farch_filter_table_id table_id;
struct efx_farch_filter_table *table;
efx_oword_t filter;
unsigned int filter_idx;
down_write(&state->lock);
for (table_id = 0; table_id < EFX_FARCH_FILTER_TABLE_COUNT; table_id++) {
table = &state->table[table_id];
/* Check whether this is a regular register table */
if (table->step == 0)
continue;
for (filter_idx = 0; filter_idx < table->size; filter_idx++) {
if (!test_bit(filter_idx, table->used_bitmap))
continue;
efx_farch_filter_build(&filter, &table->spec[filter_idx]);
efx_writeo(efx, &filter,
table->offset + table->step * filter_idx);
}
}
efx_farch_filter_push_rx_config(efx);
efx_farch_filter_push_tx_limits(efx);
up_write(&state->lock);
}
void efx_farch_filter_table_remove(struct efx_nic *efx)
{
struct efx_farch_filter_state *state = efx->filter_state;
enum efx_farch_filter_table_id table_id;
for (table_id = 0; table_id < EFX_FARCH_FILTER_TABLE_COUNT; table_id++) {
bitmap_free(state->table[table_id].used_bitmap);
vfree(state->table[table_id].spec);
}
kfree(state);
}
int efx_farch_filter_table_probe(struct efx_nic *efx)
{
struct efx_farch_filter_state *state;
struct efx_farch_filter_table *table;
unsigned table_id;
state = kzalloc(sizeof(struct efx_farch_filter_state), GFP_KERNEL);
if (!state)
return -ENOMEM;
efx->filter_state = state;
init_rwsem(&state->lock);
table = &state->table[EFX_FARCH_FILTER_TABLE_RX_IP];
table->id = EFX_FARCH_FILTER_TABLE_RX_IP;
table->offset = FR_BZ_RX_FILTER_TBL0;
table->size = FR_BZ_RX_FILTER_TBL0_ROWS;
table->step = FR_BZ_RX_FILTER_TBL0_STEP;
table = &state->table[EFX_FARCH_FILTER_TABLE_RX_MAC];
table->id = EFX_FARCH_FILTER_TABLE_RX_MAC;
table->offset = FR_CZ_RX_MAC_FILTER_TBL0;
table->size = FR_CZ_RX_MAC_FILTER_TBL0_ROWS;
table->step = FR_CZ_RX_MAC_FILTER_TBL0_STEP;
table = &state->table[EFX_FARCH_FILTER_TABLE_RX_DEF];
table->id = EFX_FARCH_FILTER_TABLE_RX_DEF;
table->size = EFX_FARCH_FILTER_SIZE_RX_DEF;
table = &state->table[EFX_FARCH_FILTER_TABLE_TX_MAC];
table->id = EFX_FARCH_FILTER_TABLE_TX_MAC;
table->offset = FR_CZ_TX_MAC_FILTER_TBL0;
table->size = FR_CZ_TX_MAC_FILTER_TBL0_ROWS;
table->step = FR_CZ_TX_MAC_FILTER_TBL0_STEP;
for (table_id = 0; table_id < EFX_FARCH_FILTER_TABLE_COUNT; table_id++) {
table = &state->table[table_id];
if (table->size == 0)
continue;
table->used_bitmap = bitmap_zalloc(table->size, GFP_KERNEL);
if (!table->used_bitmap)
goto fail;
table->spec = vzalloc(array_size(sizeof(*table->spec),
table->size));
if (!table->spec)
goto fail;
}
table = &state->table[EFX_FARCH_FILTER_TABLE_RX_DEF];
if (table->size) {
/* RX default filters must always exist */
struct efx_farch_filter_spec *spec;
unsigned i;
for (i = 0; i < EFX_FARCH_FILTER_SIZE_RX_DEF; i++) {
spec = &table->spec[i];
spec->type = EFX_FARCH_FILTER_UC_DEF + i;
efx_farch_filter_init_rx_auto(efx, spec);
__set_bit(i, table->used_bitmap);
}
}
efx_farch_filter_push_rx_config(efx);
return 0;
fail:
efx_farch_filter_table_remove(efx);
return -ENOMEM;
}
/* Update scatter enable flags for filters pointing to our own RX queues */
void efx_farch_filter_update_rx_scatter(struct efx_nic *efx)
{
struct efx_farch_filter_state *state = efx->filter_state;
enum efx_farch_filter_table_id table_id;
struct efx_farch_filter_table *table;
efx_oword_t filter;
unsigned int filter_idx;
down_write(&state->lock);
for (table_id = EFX_FARCH_FILTER_TABLE_RX_IP;
table_id <= EFX_FARCH_FILTER_TABLE_RX_DEF;
table_id++) {
table = &state->table[table_id];
for (filter_idx = 0; filter_idx < table->size; filter_idx++) {
if (!test_bit(filter_idx, table->used_bitmap) ||
table->spec[filter_idx].dmaq_id >=
efx->n_rx_channels)
continue;
if (efx->rx_scatter)
table->spec[filter_idx].flags |=
EFX_FILTER_FLAG_RX_SCATTER;
else
table->spec[filter_idx].flags &=
~EFX_FILTER_FLAG_RX_SCATTER;
if (table_id == EFX_FARCH_FILTER_TABLE_RX_DEF)
/* Pushed by efx_farch_filter_push_rx_config() */
continue;
efx_farch_filter_build(&filter, &table->spec[filter_idx]);
efx_writeo(efx, &filter,
table->offset + table->step * filter_idx);
}
}
efx_farch_filter_push_rx_config(efx);
up_write(&state->lock);
}
#ifdef CONFIG_RFS_ACCEL
bool efx_farch_filter_rfs_expire_one(struct efx_nic *efx, u32 flow_id,
unsigned int index)
{
struct efx_farch_filter_state *state = efx->filter_state;
struct efx_farch_filter_table *table;
bool ret = false, force = false;
u16 arfs_id;
down_write(&state->lock);
spin_lock_bh(&efx->rps_hash_lock);
table = &state->table[EFX_FARCH_FILTER_TABLE_RX_IP];
if (test_bit(index, table->used_bitmap) &&
table->spec[index].priority == EFX_FILTER_PRI_HINT) {
struct efx_arfs_rule *rule = NULL;
struct efx_filter_spec spec;
efx_farch_filter_to_gen_spec(&spec, &table->spec[index]);
if (!efx->rps_hash_table) {
/* In the absence of the table, we always returned 0 to
* ARFS, so use the same to query it.
*/
arfs_id = 0;
} else {
rule = efx_siena_rps_hash_find(efx, &spec);
if (!rule) {
/* ARFS table doesn't know of this filter, remove it */
force = true;
} else {
arfs_id = rule->arfs_id;
if (!efx_siena_rps_check_rule(rule, index,
&force))
goto out_unlock;
}
}
if (force || rps_may_expire_flow(efx->net_dev, spec.dmaq_id,
flow_id, arfs_id)) {
if (rule)
rule->filter_id = EFX_ARFS_FILTER_ID_REMOVING;
efx_siena_rps_hash_del(efx, &spec);
efx_farch_filter_table_clear_entry(efx, table, index);
ret = true;
}
}
out_unlock:
spin_unlock_bh(&efx->rps_hash_lock);
up_write(&state->lock);
return ret;
}
#endif /* CONFIG_RFS_ACCEL */
void efx_farch_filter_sync_rx_mode(struct efx_nic *efx)
{
struct net_device *net_dev = efx->net_dev;
struct netdev_hw_addr *ha;
union efx_multicast_hash *mc_hash = &efx->multicast_hash;
u32 crc;
int bit;
if (!efx_dev_registered(efx))
return;
netif_addr_lock_bh(net_dev);
efx->unicast_filter = !(net_dev->flags & IFF_PROMISC);
/* Build multicast hash table */
if (net_dev->flags & (IFF_PROMISC | IFF_ALLMULTI)) {
memset(mc_hash, 0xff, sizeof(*mc_hash));
} else {
memset(mc_hash, 0x00, sizeof(*mc_hash));
netdev_for_each_mc_addr(ha, net_dev) {
crc = ether_crc_le(ETH_ALEN, ha->addr);
bit = crc & (EFX_MCAST_HASH_ENTRIES - 1);
__set_bit_le(bit, mc_hash);
}
/* Broadcast packets go through the multicast hash filter.
* ether_crc_le() of the broadcast address is 0xbe2612ff
* so we always add bit 0xff to the mask.
*/
__set_bit_le(0xff, mc_hash);
}
netif_addr_unlock_bh(net_dev);
}
|
linux-master
|
drivers/net/ethernet/sfc/siena/farch.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2005-2006 Fen Systems Ltd.
* Copyright 2006-2012 Solarflare Communications Inc.
*/
#include <linux/netdevice.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/kernel_stat.h>
#include <linux/pci.h>
#include <linux/ethtool.h>
#include <linux/ip.h>
#include <linux/in.h>
#include <linux/udp.h>
#include <linux/rtnetlink.h>
#include <linux/slab.h>
#include "net_driver.h"
#include "efx.h"
#include "efx_common.h"
#include "efx_channels.h"
#include "nic.h"
#include "mcdi_port_common.h"
#include "selftest.h"
#include "workarounds.h"
/* IRQ latency can be enormous because:
* - All IRQs may be disabled on a CPU for a *long* time by e.g. a
* slow serial console or an old IDE driver doing error recovery
* - The PREEMPT_RT patches mostly deal with this, but also allow a
* tasklet or normal task to be given higher priority than our IRQ
* threads
* Try to avoid blaming the hardware for this.
*/
#define IRQ_TIMEOUT HZ
/*
* Loopback test packet structure
*
* The self-test should stress every RSS vector, and unfortunately
* Falcon only performs RSS on TCP/UDP packets.
*/
struct efx_loopback_payload {
char pad[2]; /* Ensures ip is 4-byte aligned */
struct_group_attr(packet, __packed,
struct ethhdr header;
struct iphdr ip;
struct udphdr udp;
__be16 iteration;
char msg[64];
);
} __packed __aligned(4);
#define EFX_LOOPBACK_PAYLOAD_LEN \
sizeof_field(struct efx_loopback_payload, packet)
/* Loopback test source MAC address */
static const u8 payload_source[ETH_ALEN] __aligned(2) = {
0x00, 0x0f, 0x53, 0x1b, 0x1b, 0x1b,
};
static const char payload_msg[] =
"Hello world! This is an Efx loopback test in progress!";
/* Interrupt mode names */
static const unsigned int efx_siena_interrupt_mode_max = EFX_INT_MODE_MAX;
static const char *const efx_siena_interrupt_mode_names[] = {
[EFX_INT_MODE_MSIX] = "MSI-X",
[EFX_INT_MODE_MSI] = "MSI",
[EFX_INT_MODE_LEGACY] = "legacy",
};
#define INT_MODE(efx) \
STRING_TABLE_LOOKUP(efx->interrupt_mode, efx_siena_interrupt_mode)
/**
* struct efx_loopback_state - persistent state during a loopback selftest
* @flush: Drop all packets in efx_siena_loopback_rx_packet
* @packet_count: Number of packets being used in this test
* @skbs: An array of skbs transmitted
* @offload_csum: Checksums are being offloaded
* @rx_good: RX good packet count
* @rx_bad: RX bad packet count
* @payload: Payload used in tests
*/
struct efx_loopback_state {
bool flush;
int packet_count;
struct sk_buff **skbs;
bool offload_csum;
atomic_t rx_good;
atomic_t rx_bad;
struct efx_loopback_payload payload;
};
/* How long to wait for all the packets to arrive (in ms) */
#define LOOPBACK_TIMEOUT_MS 1000
/**************************************************************************
*
* MII, NVRAM and register tests
*
**************************************************************************/
static int efx_test_phy_alive(struct efx_nic *efx, struct efx_self_tests *tests)
{
int rc = 0;
rc = efx_siena_mcdi_phy_test_alive(efx);
tests->phy_alive = rc ? -1 : 1;
return rc;
}
static int efx_test_nvram(struct efx_nic *efx, struct efx_self_tests *tests)
{
int rc = 0;
if (efx->type->test_nvram) {
rc = efx->type->test_nvram(efx);
if (rc == -EPERM)
rc = 0;
else
tests->nvram = rc ? -1 : 1;
}
return rc;
}
/**************************************************************************
*
* Interrupt and event queue testing
*
**************************************************************************/
/* Test generation and receipt of interrupts */
static int efx_test_interrupts(struct efx_nic *efx,
struct efx_self_tests *tests)
{
unsigned long timeout, wait;
int cpu;
int rc;
netif_dbg(efx, drv, efx->net_dev, "testing interrupts\n");
tests->interrupt = -1;
rc = efx_siena_irq_test_start(efx);
if (rc == -ENOTSUPP) {
netif_dbg(efx, drv, efx->net_dev,
"direct interrupt testing not supported\n");
tests->interrupt = 0;
return 0;
}
timeout = jiffies + IRQ_TIMEOUT;
wait = 1;
/* Wait for arrival of test interrupt. */
netif_dbg(efx, drv, efx->net_dev, "waiting for test interrupt\n");
do {
schedule_timeout_uninterruptible(wait);
cpu = efx_nic_irq_test_irq_cpu(efx);
if (cpu >= 0)
goto success;
wait *= 2;
} while (time_before(jiffies, timeout));
netif_err(efx, drv, efx->net_dev, "timed out waiting for interrupt\n");
return -ETIMEDOUT;
success:
netif_dbg(efx, drv, efx->net_dev, "%s test interrupt seen on CPU%d\n",
INT_MODE(efx), cpu);
tests->interrupt = 1;
return 0;
}
/* Test generation and receipt of interrupting events */
static int efx_test_eventq_irq(struct efx_nic *efx,
struct efx_self_tests *tests)
{
struct efx_channel *channel;
unsigned int read_ptr[EFX_MAX_CHANNELS];
unsigned long napi_ran = 0, dma_pend = 0, int_pend = 0;
unsigned long timeout, wait;
BUILD_BUG_ON(EFX_MAX_CHANNELS > BITS_PER_LONG);
efx_for_each_channel(channel, efx) {
read_ptr[channel->channel] = channel->eventq_read_ptr;
set_bit(channel->channel, &dma_pend);
set_bit(channel->channel, &int_pend);
efx_siena_event_test_start(channel);
}
timeout = jiffies + IRQ_TIMEOUT;
wait = 1;
/* Wait for arrival of interrupts. NAPI processing may or may
* not complete in time, but we can cope in any case.
*/
do {
schedule_timeout_uninterruptible(wait);
efx_for_each_channel(channel, efx) {
efx_siena_stop_eventq(channel);
if (channel->eventq_read_ptr !=
read_ptr[channel->channel]) {
set_bit(channel->channel, &napi_ran);
clear_bit(channel->channel, &dma_pend);
clear_bit(channel->channel, &int_pend);
} else {
if (efx_siena_event_present(channel))
clear_bit(channel->channel, &dma_pend);
if (efx_nic_event_test_irq_cpu(channel) >= 0)
clear_bit(channel->channel, &int_pend);
}
efx_siena_start_eventq(channel);
}
wait *= 2;
} while ((dma_pend || int_pend) && time_before(jiffies, timeout));
efx_for_each_channel(channel, efx) {
bool dma_seen = !test_bit(channel->channel, &dma_pend);
bool int_seen = !test_bit(channel->channel, &int_pend);
tests->eventq_dma[channel->channel] = dma_seen ? 1 : -1;
tests->eventq_int[channel->channel] = int_seen ? 1 : -1;
if (dma_seen && int_seen) {
netif_dbg(efx, drv, efx->net_dev,
"channel %d event queue passed (with%s NAPI)\n",
channel->channel,
test_bit(channel->channel, &napi_ran) ?
"" : "out");
} else {
/* Report failure and whether either interrupt or DMA
* worked
*/
netif_err(efx, drv, efx->net_dev,
"channel %d timed out waiting for event queue\n",
channel->channel);
if (int_seen)
netif_err(efx, drv, efx->net_dev,
"channel %d saw interrupt "
"during event queue test\n",
channel->channel);
if (dma_seen)
netif_err(efx, drv, efx->net_dev,
"channel %d event was generated, but "
"failed to trigger an interrupt\n",
channel->channel);
}
}
return (dma_pend || int_pend) ? -ETIMEDOUT : 0;
}
static int efx_test_phy(struct efx_nic *efx, struct efx_self_tests *tests,
unsigned flags)
{
int rc;
mutex_lock(&efx->mac_lock);
rc = efx_siena_mcdi_phy_run_tests(efx, tests->phy_ext, flags);
mutex_unlock(&efx->mac_lock);
if (rc == -EPERM)
rc = 0;
else
netif_info(efx, drv, efx->net_dev,
"%s phy selftest\n", rc ? "Failed" : "Passed");
return rc;
}
/**************************************************************************
*
* Loopback testing
* NB Only one loopback test can be executing concurrently.
*
**************************************************************************/
/* Loopback test RX callback
* This is called for each received packet during loopback testing.
*/
void efx_siena_loopback_rx_packet(struct efx_nic *efx,
const char *buf_ptr, int pkt_len)
{
struct efx_loopback_state *state = efx->loopback_selftest;
struct efx_loopback_payload received;
struct efx_loopback_payload *payload;
BUG_ON(!buf_ptr);
/* If we are just flushing, then drop the packet */
if ((state == NULL) || state->flush)
return;
payload = &state->payload;
memcpy(&received.packet, buf_ptr,
min_t(int, pkt_len, EFX_LOOPBACK_PAYLOAD_LEN));
received.ip.saddr = payload->ip.saddr;
if (state->offload_csum)
received.ip.check = payload->ip.check;
/* Check that header exists */
if (pkt_len < sizeof(received.header)) {
netif_err(efx, drv, efx->net_dev,
"saw runt RX packet (length %d) in %s loopback "
"test\n", pkt_len, LOOPBACK_MODE(efx));
goto err;
}
/* Check that the ethernet header exists */
if (memcmp(&received.header, &payload->header, ETH_HLEN) != 0) {
netif_err(efx, drv, efx->net_dev,
"saw non-loopback RX packet in %s loopback test\n",
LOOPBACK_MODE(efx));
goto err;
}
/* Check packet length */
if (pkt_len != EFX_LOOPBACK_PAYLOAD_LEN) {
netif_err(efx, drv, efx->net_dev,
"saw incorrect RX packet length %d (wanted %d) in "
"%s loopback test\n", pkt_len,
(int)EFX_LOOPBACK_PAYLOAD_LEN, LOOPBACK_MODE(efx));
goto err;
}
/* Check that IP header matches */
if (memcmp(&received.ip, &payload->ip, sizeof(payload->ip)) != 0) {
netif_err(efx, drv, efx->net_dev,
"saw corrupted IP header in %s loopback test\n",
LOOPBACK_MODE(efx));
goto err;
}
/* Check that msg and padding matches */
if (memcmp(&received.msg, &payload->msg, sizeof(received.msg)) != 0) {
netif_err(efx, drv, efx->net_dev,
"saw corrupted RX packet in %s loopback test\n",
LOOPBACK_MODE(efx));
goto err;
}
/* Check that iteration matches */
if (received.iteration != payload->iteration) {
netif_err(efx, drv, efx->net_dev,
"saw RX packet from iteration %d (wanted %d) in "
"%s loopback test\n", ntohs(received.iteration),
ntohs(payload->iteration), LOOPBACK_MODE(efx));
goto err;
}
/* Increase correct RX count */
netif_vdbg(efx, drv, efx->net_dev,
"got loopback RX in %s loopback test\n", LOOPBACK_MODE(efx));
atomic_inc(&state->rx_good);
return;
err:
#ifdef DEBUG
if (atomic_read(&state->rx_bad) == 0) {
netif_err(efx, drv, efx->net_dev, "received packet:\n");
print_hex_dump(KERN_ERR, "", DUMP_PREFIX_OFFSET, 0x10, 1,
buf_ptr, pkt_len, 0);
netif_err(efx, drv, efx->net_dev, "expected packet:\n");
print_hex_dump(KERN_ERR, "", DUMP_PREFIX_OFFSET, 0x10, 1,
&state->payload.packet, EFX_LOOPBACK_PAYLOAD_LEN,
0);
}
#endif
atomic_inc(&state->rx_bad);
}
/* Initialise an efx_siena_selftest_state for a new iteration */
static void efx_iterate_state(struct efx_nic *efx)
{
struct efx_loopback_state *state = efx->loopback_selftest;
struct net_device *net_dev = efx->net_dev;
struct efx_loopback_payload *payload = &state->payload;
/* Initialise the layerII header */
ether_addr_copy((u8 *)&payload->header.h_dest, net_dev->dev_addr);
ether_addr_copy((u8 *)&payload->header.h_source, payload_source);
payload->header.h_proto = htons(ETH_P_IP);
/* saddr set later and used as incrementing count */
payload->ip.daddr = htonl(INADDR_LOOPBACK);
payload->ip.ihl = 5;
payload->ip.check = (__force __sum16) htons(0xdead);
payload->ip.tot_len = htons(sizeof(*payload) -
offsetof(struct efx_loopback_payload, ip));
payload->ip.version = IPVERSION;
payload->ip.protocol = IPPROTO_UDP;
/* Initialise udp header */
payload->udp.source = 0;
payload->udp.len = htons(sizeof(*payload) -
offsetof(struct efx_loopback_payload, udp));
payload->udp.check = 0; /* checksum ignored */
/* Fill out payload */
payload->iteration = htons(ntohs(payload->iteration) + 1);
memcpy(&payload->msg, payload_msg, sizeof(payload_msg));
/* Fill out remaining state members */
atomic_set(&state->rx_good, 0);
atomic_set(&state->rx_bad, 0);
smp_wmb();
}
static int efx_begin_loopback(struct efx_tx_queue *tx_queue)
{
struct efx_nic *efx = tx_queue->efx;
struct efx_loopback_state *state = efx->loopback_selftest;
struct efx_loopback_payload *payload;
struct sk_buff *skb;
int i;
netdev_tx_t rc;
/* Transmit N copies of buffer */
for (i = 0; i < state->packet_count; i++) {
/* Allocate an skb, holding an extra reference for
* transmit completion counting */
skb = alloc_skb(sizeof(state->payload), GFP_KERNEL);
if (!skb)
return -ENOMEM;
state->skbs[i] = skb;
skb_get(skb);
/* Copy the payload in, incrementing the source address to
* exercise the rss vectors */
payload = skb_put(skb, sizeof(state->payload));
memcpy(payload, &state->payload, sizeof(state->payload));
payload->ip.saddr = htonl(INADDR_LOOPBACK | (i << 2));
/* Strip off the leading padding */
skb_pull(skb, offsetof(struct efx_loopback_payload, header));
/* Strip off the trailing padding */
skb_trim(skb, EFX_LOOPBACK_PAYLOAD_LEN);
/* Ensure everything we've written is visible to the
* interrupt handler. */
smp_wmb();
netif_tx_lock_bh(efx->net_dev);
rc = efx_enqueue_skb(tx_queue, skb);
netif_tx_unlock_bh(efx->net_dev);
if (rc != NETDEV_TX_OK) {
netif_err(efx, drv, efx->net_dev,
"TX queue %d could not transmit packet %d of "
"%d in %s loopback test\n", tx_queue->label,
i + 1, state->packet_count,
LOOPBACK_MODE(efx));
/* Defer cleaning up the other skbs for the caller */
kfree_skb(skb);
return -EPIPE;
}
}
return 0;
}
static int efx_poll_loopback(struct efx_nic *efx)
{
struct efx_loopback_state *state = efx->loopback_selftest;
return atomic_read(&state->rx_good) == state->packet_count;
}
static int efx_end_loopback(struct efx_tx_queue *tx_queue,
struct efx_loopback_self_tests *lb_tests)
{
struct efx_nic *efx = tx_queue->efx;
struct efx_loopback_state *state = efx->loopback_selftest;
struct sk_buff *skb;
int tx_done = 0, rx_good, rx_bad;
int i, rc = 0;
netif_tx_lock_bh(efx->net_dev);
/* Count the number of tx completions, and decrement the refcnt. Any
* skbs not already completed will be free'd when the queue is flushed */
for (i = 0; i < state->packet_count; i++) {
skb = state->skbs[i];
if (skb && !skb_shared(skb))
++tx_done;
dev_kfree_skb(skb);
}
netif_tx_unlock_bh(efx->net_dev);
/* Check TX completion and received packet counts */
rx_good = atomic_read(&state->rx_good);
rx_bad = atomic_read(&state->rx_bad);
if (tx_done != state->packet_count) {
/* Don't free the skbs; they will be picked up on TX
* overflow or channel teardown.
*/
netif_err(efx, drv, efx->net_dev,
"TX queue %d saw only %d out of an expected %d "
"TX completion events in %s loopback test\n",
tx_queue->label, tx_done, state->packet_count,
LOOPBACK_MODE(efx));
rc = -ETIMEDOUT;
/* Allow to fall through so we see the RX errors as well */
}
/* We may always be up to a flush away from our desired packet total */
if (rx_good != state->packet_count) {
netif_dbg(efx, drv, efx->net_dev,
"TX queue %d saw only %d out of an expected %d "
"received packets in %s loopback test\n",
tx_queue->label, rx_good, state->packet_count,
LOOPBACK_MODE(efx));
rc = -ETIMEDOUT;
/* Fall through */
}
/* Update loopback test structure */
lb_tests->tx_sent[tx_queue->label] += state->packet_count;
lb_tests->tx_done[tx_queue->label] += tx_done;
lb_tests->rx_good += rx_good;
lb_tests->rx_bad += rx_bad;
return rc;
}
static int
efx_test_loopback(struct efx_tx_queue *tx_queue,
struct efx_loopback_self_tests *lb_tests)
{
struct efx_nic *efx = tx_queue->efx;
struct efx_loopback_state *state = efx->loopback_selftest;
int i, begin_rc, end_rc;
for (i = 0; i < 3; i++) {
/* Determine how many packets to send */
state->packet_count = efx->txq_entries / 3;
state->packet_count = min(1 << (i << 2), state->packet_count);
state->skbs = kcalloc(state->packet_count,
sizeof(state->skbs[0]), GFP_KERNEL);
if (!state->skbs)
return -ENOMEM;
state->flush = false;
netif_dbg(efx, drv, efx->net_dev,
"TX queue %d (hw %d) testing %s loopback with %d packets\n",
tx_queue->label, tx_queue->queue, LOOPBACK_MODE(efx),
state->packet_count);
efx_iterate_state(efx);
begin_rc = efx_begin_loopback(tx_queue);
/* This will normally complete very quickly, but be
* prepared to wait much longer. */
msleep(1);
if (!efx_poll_loopback(efx)) {
msleep(LOOPBACK_TIMEOUT_MS);
efx_poll_loopback(efx);
}
end_rc = efx_end_loopback(tx_queue, lb_tests);
kfree(state->skbs);
if (begin_rc || end_rc) {
/* Wait a while to ensure there are no packets
* floating around after a failure. */
schedule_timeout_uninterruptible(HZ / 10);
return begin_rc ? begin_rc : end_rc;
}
}
netif_dbg(efx, drv, efx->net_dev,
"TX queue %d passed %s loopback test with a burst length "
"of %d packets\n", tx_queue->label, LOOPBACK_MODE(efx),
state->packet_count);
return 0;
}
/* Wait for link up. On Falcon, we would prefer to rely on efx_monitor, but
* any contention on the mac lock (via e.g. efx_mac_mcast_work) causes it
* to delay and retry. Therefore, it's safer to just poll directly. Wait
* for link up and any faults to dissipate. */
static int efx_wait_for_link(struct efx_nic *efx)
{
struct efx_link_state *link_state = &efx->link_state;
int count, link_up_count = 0;
bool link_up;
for (count = 0; count < 40; count++) {
schedule_timeout_uninterruptible(HZ / 10);
if (efx->type->monitor != NULL) {
mutex_lock(&efx->mac_lock);
efx->type->monitor(efx);
mutex_unlock(&efx->mac_lock);
}
mutex_lock(&efx->mac_lock);
link_up = link_state->up;
if (link_up)
link_up = !efx->type->check_mac_fault(efx);
mutex_unlock(&efx->mac_lock);
if (link_up) {
if (++link_up_count == 2)
return 0;
} else {
link_up_count = 0;
}
}
return -ETIMEDOUT;
}
static int efx_test_loopbacks(struct efx_nic *efx, struct efx_self_tests *tests,
unsigned int loopback_modes)
{
enum efx_loopback_mode mode;
struct efx_loopback_state *state;
struct efx_channel *channel =
efx_get_channel(efx, efx->tx_channel_offset);
struct efx_tx_queue *tx_queue;
int rc = 0;
/* Set the port loopback_selftest member. From this point on
* all received packets will be dropped. Mark the state as
* "flushing" so all inflight packets are dropped */
state = kzalloc(sizeof(*state), GFP_KERNEL);
if (state == NULL)
return -ENOMEM;
BUG_ON(efx->loopback_selftest);
state->flush = true;
efx->loopback_selftest = state;
/* Test all supported loopback modes */
for (mode = LOOPBACK_NONE; mode <= LOOPBACK_TEST_MAX; mode++) {
if (!(loopback_modes & (1 << mode)))
continue;
/* Move the port into the specified loopback mode. */
state->flush = true;
mutex_lock(&efx->mac_lock);
efx->loopback_mode = mode;
rc = __efx_siena_reconfigure_port(efx);
mutex_unlock(&efx->mac_lock);
if (rc) {
netif_err(efx, drv, efx->net_dev,
"unable to move into %s loopback\n",
LOOPBACK_MODE(efx));
goto out;
}
rc = efx_wait_for_link(efx);
if (rc) {
netif_err(efx, drv, efx->net_dev,
"loopback %s never came up\n",
LOOPBACK_MODE(efx));
goto out;
}
/* Test all enabled types of TX queue */
efx_for_each_channel_tx_queue(tx_queue, channel) {
state->offload_csum = (tx_queue->type &
EFX_TXQ_TYPE_OUTER_CSUM);
rc = efx_test_loopback(tx_queue,
&tests->loopback[mode]);
if (rc)
goto out;
}
}
out:
/* Remove the flush. The caller will remove the loopback setting */
state->flush = true;
efx->loopback_selftest = NULL;
wmb();
kfree(state);
if (rc == -EPERM)
rc = 0;
return rc;
}
/**************************************************************************
*
* Entry point
*
*************************************************************************/
int efx_siena_selftest(struct efx_nic *efx, struct efx_self_tests *tests,
unsigned int flags)
{
enum efx_loopback_mode loopback_mode = efx->loopback_mode;
int phy_mode = efx->phy_mode;
int rc_test = 0, rc_reset, rc;
efx_siena_selftest_async_cancel(efx);
/* Online (i.e. non-disruptive) testing
* This checks interrupt generation, event delivery and PHY presence. */
rc = efx_test_phy_alive(efx, tests);
if (rc && !rc_test)
rc_test = rc;
rc = efx_test_nvram(efx, tests);
if (rc && !rc_test)
rc_test = rc;
rc = efx_test_interrupts(efx, tests);
if (rc && !rc_test)
rc_test = rc;
rc = efx_test_eventq_irq(efx, tests);
if (rc && !rc_test)
rc_test = rc;
if (rc_test)
return rc_test;
if (!(flags & ETH_TEST_FL_OFFLINE))
return efx_test_phy(efx, tests, flags);
/* Offline (i.e. disruptive) testing
* This checks MAC and PHY loopback on the specified port. */
/* Detach the device so the kernel doesn't transmit during the
* loopback test and the watchdog timeout doesn't fire.
*/
efx_device_detach_sync(efx);
if (efx->type->test_chip) {
rc_reset = efx->type->test_chip(efx, tests);
if (rc_reset) {
netif_err(efx, hw, efx->net_dev,
"Unable to recover from chip test\n");
efx_siena_schedule_reset(efx, RESET_TYPE_DISABLE);
return rc_reset;
}
if ((tests->memory < 0 || tests->registers < 0) && !rc_test)
rc_test = -EIO;
}
/* Ensure that the phy is powered and out of loopback
* for the bist and loopback tests */
mutex_lock(&efx->mac_lock);
efx->phy_mode &= ~PHY_MODE_LOW_POWER;
efx->loopback_mode = LOOPBACK_NONE;
__efx_siena_reconfigure_port(efx);
mutex_unlock(&efx->mac_lock);
rc = efx_test_phy(efx, tests, flags);
if (rc && !rc_test)
rc_test = rc;
rc = efx_test_loopbacks(efx, tests, efx->loopback_modes);
if (rc && !rc_test)
rc_test = rc;
/* restore the PHY to the previous state */
mutex_lock(&efx->mac_lock);
efx->phy_mode = phy_mode;
efx->loopback_mode = loopback_mode;
__efx_siena_reconfigure_port(efx);
mutex_unlock(&efx->mac_lock);
efx_device_attach_if_not_resetting(efx);
return rc_test;
}
void efx_siena_selftest_async_start(struct efx_nic *efx)
{
struct efx_channel *channel;
efx_for_each_channel(channel, efx)
efx_siena_event_test_start(channel);
schedule_delayed_work(&efx->selftest_work, IRQ_TIMEOUT);
}
void efx_siena_selftest_async_cancel(struct efx_nic *efx)
{
cancel_delayed_work_sync(&efx->selftest_work);
}
static void efx_siena_selftest_async_work(struct work_struct *data)
{
struct efx_nic *efx = container_of(data, struct efx_nic,
selftest_work.work);
struct efx_channel *channel;
int cpu;
efx_for_each_channel(channel, efx) {
cpu = efx_nic_event_test_irq_cpu(channel);
if (cpu < 0)
netif_err(efx, ifup, efx->net_dev,
"channel %d failed to trigger an interrupt\n",
channel->channel);
else
netif_dbg(efx, ifup, efx->net_dev,
"channel %d triggered interrupt on CPU %d\n",
channel->channel, cpu);
}
}
void efx_siena_selftest_async_init(struct efx_nic *efx)
{
INIT_DELAYED_WORK(&efx->selftest_work, efx_siena_selftest_async_work);
}
|
linux-master
|
drivers/net/ethernet/sfc/siena/selftest.c
|
// SPDX-License-Identifier: GPL-2.0-only
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2005-2006 Fen Systems Ltd.
* Copyright 2006-2013 Solarflare Communications Inc.
*/
#include <linux/bitops.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/module.h>
#include <linux/seq_file.h>
#include <linux/cpu_rmap.h>
#include "net_driver.h"
#include "bitfield.h"
#include "efx.h"
#include "nic.h"
#include "farch_regs.h"
#include "io.h"
#include "workarounds.h"
#include "mcdi_pcol.h"
/**************************************************************************
*
* Generic buffer handling
* These buffers are used for interrupt status, MAC stats, etc.
*
**************************************************************************/
int efx_siena_alloc_buffer(struct efx_nic *efx, struct efx_buffer *buffer,
unsigned int len, gfp_t gfp_flags)
{
buffer->addr = dma_alloc_coherent(&efx->pci_dev->dev, len,
&buffer->dma_addr, gfp_flags);
if (!buffer->addr)
return -ENOMEM;
buffer->len = len;
return 0;
}
void efx_siena_free_buffer(struct efx_nic *efx, struct efx_buffer *buffer)
{
if (buffer->addr) {
dma_free_coherent(&efx->pci_dev->dev, buffer->len,
buffer->addr, buffer->dma_addr);
buffer->addr = NULL;
}
}
/* Check whether an event is present in the eventq at the current
* read pointer. Only useful for self-test.
*/
bool efx_siena_event_present(struct efx_channel *channel)
{
return efx_event_present(efx_event(channel, channel->eventq_read_ptr));
}
void efx_siena_event_test_start(struct efx_channel *channel)
{
channel->event_test_cpu = -1;
smp_wmb();
channel->efx->type->ev_test_generate(channel);
}
int efx_siena_irq_test_start(struct efx_nic *efx)
{
efx->last_irq_cpu = -1;
smp_wmb();
return efx->type->irq_test_generate(efx);
}
/* Hook interrupt handler(s)
* Try MSI and then legacy interrupts.
*/
int efx_siena_init_interrupt(struct efx_nic *efx)
{
struct efx_channel *channel;
unsigned int n_irqs;
int rc;
if (!EFX_INT_MODE_USE_MSI(efx)) {
rc = request_irq(efx->legacy_irq,
efx->type->irq_handle_legacy, IRQF_SHARED,
efx->name, efx);
if (rc) {
netif_err(efx, drv, efx->net_dev,
"failed to hook legacy IRQ %d\n",
efx->pci_dev->irq);
goto fail1;
}
efx->irqs_hooked = true;
return 0;
}
#ifdef CONFIG_RFS_ACCEL
if (efx->interrupt_mode == EFX_INT_MODE_MSIX) {
efx->net_dev->rx_cpu_rmap =
alloc_irq_cpu_rmap(efx->n_rx_channels);
if (!efx->net_dev->rx_cpu_rmap) {
rc = -ENOMEM;
goto fail1;
}
}
#endif
/* Hook MSI or MSI-X interrupt */
n_irqs = 0;
efx_for_each_channel(channel, efx) {
rc = request_irq(channel->irq, efx->type->irq_handle_msi,
IRQF_PROBE_SHARED, /* Not shared */
efx->msi_context[channel->channel].name,
&efx->msi_context[channel->channel]);
if (rc) {
netif_err(efx, drv, efx->net_dev,
"failed to hook IRQ %d\n", channel->irq);
goto fail2;
}
++n_irqs;
#ifdef CONFIG_RFS_ACCEL
if (efx->interrupt_mode == EFX_INT_MODE_MSIX &&
channel->channel < efx->n_rx_channels) {
rc = irq_cpu_rmap_add(efx->net_dev->rx_cpu_rmap,
channel->irq);
if (rc)
goto fail2;
}
#endif
}
efx->irqs_hooked = true;
return 0;
fail2:
#ifdef CONFIG_RFS_ACCEL
free_irq_cpu_rmap(efx->net_dev->rx_cpu_rmap);
efx->net_dev->rx_cpu_rmap = NULL;
#endif
efx_for_each_channel(channel, efx) {
if (n_irqs-- == 0)
break;
free_irq(channel->irq, &efx->msi_context[channel->channel]);
}
fail1:
return rc;
}
void efx_siena_fini_interrupt(struct efx_nic *efx)
{
struct efx_channel *channel;
#ifdef CONFIG_RFS_ACCEL
free_irq_cpu_rmap(efx->net_dev->rx_cpu_rmap);
efx->net_dev->rx_cpu_rmap = NULL;
#endif
if (!efx->irqs_hooked)
return;
if (EFX_INT_MODE_USE_MSI(efx)) {
/* Disable MSI/MSI-X interrupts */
efx_for_each_channel(channel, efx)
free_irq(channel->irq,
&efx->msi_context[channel->channel]);
} else {
/* Disable legacy interrupt */
free_irq(efx->legacy_irq, efx);
}
efx->irqs_hooked = false;
}
/* Register dump */
#define REGISTER_REVISION_FA 1
#define REGISTER_REVISION_FB 2
#define REGISTER_REVISION_FC 3
#define REGISTER_REVISION_FZ 3 /* last Falcon arch revision */
#define REGISTER_REVISION_ED 4
#define REGISTER_REVISION_EZ 4 /* latest EF10 revision */
struct efx_nic_reg {
u32 offset:24;
u32 min_revision:3, max_revision:3;
};
#define REGISTER(name, arch, min_rev, max_rev) { \
arch ## R_ ## min_rev ## max_rev ## _ ## name, \
REGISTER_REVISION_ ## arch ## min_rev, \
REGISTER_REVISION_ ## arch ## max_rev \
}
#define REGISTER_AA(name) REGISTER(name, F, A, A)
#define REGISTER_AB(name) REGISTER(name, F, A, B)
#define REGISTER_AZ(name) REGISTER(name, F, A, Z)
#define REGISTER_BB(name) REGISTER(name, F, B, B)
#define REGISTER_BZ(name) REGISTER(name, F, B, Z)
#define REGISTER_CZ(name) REGISTER(name, F, C, Z)
static const struct efx_nic_reg efx_nic_regs[] = {
REGISTER_AZ(ADR_REGION),
REGISTER_AZ(INT_EN_KER),
REGISTER_BZ(INT_EN_CHAR),
REGISTER_AZ(INT_ADR_KER),
REGISTER_BZ(INT_ADR_CHAR),
/* INT_ACK_KER is WO */
/* INT_ISR0 is RC */
REGISTER_AZ(HW_INIT),
REGISTER_CZ(USR_EV_CFG),
REGISTER_AB(EE_SPI_HCMD),
REGISTER_AB(EE_SPI_HADR),
REGISTER_AB(EE_SPI_HDATA),
REGISTER_AB(EE_BASE_PAGE),
REGISTER_AB(EE_VPD_CFG0),
/* EE_VPD_SW_CNTL and EE_VPD_SW_DATA are not used */
/* PMBX_DBG_IADDR and PBMX_DBG_IDATA are indirect */
/* PCIE_CORE_INDIRECT is indirect */
REGISTER_AB(NIC_STAT),
REGISTER_AB(GPIO_CTL),
REGISTER_AB(GLB_CTL),
/* FATAL_INTR_KER and FATAL_INTR_CHAR are partly RC */
REGISTER_BZ(DP_CTRL),
REGISTER_AZ(MEM_STAT),
REGISTER_AZ(CS_DEBUG),
REGISTER_AZ(ALTERA_BUILD),
REGISTER_AZ(CSR_SPARE),
REGISTER_AB(PCIE_SD_CTL0123),
REGISTER_AB(PCIE_SD_CTL45),
REGISTER_AB(PCIE_PCS_CTL_STAT),
/* DEBUG_DATA_OUT is not used */
/* DRV_EV is WO */
REGISTER_AZ(EVQ_CTL),
REGISTER_AZ(EVQ_CNT1),
REGISTER_AZ(EVQ_CNT2),
REGISTER_AZ(BUF_TBL_CFG),
REGISTER_AZ(SRM_RX_DC_CFG),
REGISTER_AZ(SRM_TX_DC_CFG),
REGISTER_AZ(SRM_CFG),
/* BUF_TBL_UPD is WO */
REGISTER_AZ(SRM_UPD_EVQ),
REGISTER_AZ(SRAM_PARITY),
REGISTER_AZ(RX_CFG),
REGISTER_BZ(RX_FILTER_CTL),
/* RX_FLUSH_DESCQ is WO */
REGISTER_AZ(RX_DC_CFG),
REGISTER_AZ(RX_DC_PF_WM),
REGISTER_BZ(RX_RSS_TKEY),
/* RX_NODESC_DROP is RC */
REGISTER_AA(RX_SELF_RST),
/* RX_DEBUG, RX_PUSH_DROP are not used */
REGISTER_CZ(RX_RSS_IPV6_REG1),
REGISTER_CZ(RX_RSS_IPV6_REG2),
REGISTER_CZ(RX_RSS_IPV6_REG3),
/* TX_FLUSH_DESCQ is WO */
REGISTER_AZ(TX_DC_CFG),
REGISTER_AA(TX_CHKSM_CFG),
REGISTER_AZ(TX_CFG),
/* TX_PUSH_DROP is not used */
REGISTER_AZ(TX_RESERVED),
REGISTER_BZ(TX_PACE),
/* TX_PACE_DROP_QID is RC */
REGISTER_BB(TX_VLAN),
REGISTER_BZ(TX_IPFIL_PORTEN),
REGISTER_AB(MD_TXD),
REGISTER_AB(MD_RXD),
REGISTER_AB(MD_CS),
REGISTER_AB(MD_PHY_ADR),
REGISTER_AB(MD_ID),
/* MD_STAT is RC */
REGISTER_AB(MAC_STAT_DMA),
REGISTER_AB(MAC_CTRL),
REGISTER_BB(GEN_MODE),
REGISTER_AB(MAC_MC_HASH_REG0),
REGISTER_AB(MAC_MC_HASH_REG1),
REGISTER_AB(GM_CFG1),
REGISTER_AB(GM_CFG2),
/* GM_IPG and GM_HD are not used */
REGISTER_AB(GM_MAX_FLEN),
/* GM_TEST is not used */
REGISTER_AB(GM_ADR1),
REGISTER_AB(GM_ADR2),
REGISTER_AB(GMF_CFG0),
REGISTER_AB(GMF_CFG1),
REGISTER_AB(GMF_CFG2),
REGISTER_AB(GMF_CFG3),
REGISTER_AB(GMF_CFG4),
REGISTER_AB(GMF_CFG5),
REGISTER_BB(TX_SRC_MAC_CTL),
REGISTER_AB(XM_ADR_LO),
REGISTER_AB(XM_ADR_HI),
REGISTER_AB(XM_GLB_CFG),
REGISTER_AB(XM_TX_CFG),
REGISTER_AB(XM_RX_CFG),
REGISTER_AB(XM_MGT_INT_MASK),
REGISTER_AB(XM_FC),
REGISTER_AB(XM_PAUSE_TIME),
REGISTER_AB(XM_TX_PARAM),
REGISTER_AB(XM_RX_PARAM),
/* XM_MGT_INT_MSK (note no 'A') is RC */
REGISTER_AB(XX_PWR_RST),
REGISTER_AB(XX_SD_CTL),
REGISTER_AB(XX_TXDRV_CTL),
/* XX_PRBS_CTL, XX_PRBS_CHK and XX_PRBS_ERR are not used */
/* XX_CORE_STAT is partly RC */
};
struct efx_nic_reg_table {
u32 offset:24;
u32 min_revision:3, max_revision:3;
u32 step:6, rows:21;
};
#define REGISTER_TABLE_DIMENSIONS(_, offset, arch, min_rev, max_rev, step, rows) { \
offset, \
REGISTER_REVISION_ ## arch ## min_rev, \
REGISTER_REVISION_ ## arch ## max_rev, \
step, rows \
}
#define REGISTER_TABLE(name, arch, min_rev, max_rev) \
REGISTER_TABLE_DIMENSIONS( \
name, arch ## R_ ## min_rev ## max_rev ## _ ## name, \
arch, min_rev, max_rev, \
arch ## R_ ## min_rev ## max_rev ## _ ## name ## _STEP, \
arch ## R_ ## min_rev ## max_rev ## _ ## name ## _ROWS)
#define REGISTER_TABLE_AA(name) REGISTER_TABLE(name, F, A, A)
#define REGISTER_TABLE_AZ(name) REGISTER_TABLE(name, F, A, Z)
#define REGISTER_TABLE_BB(name) REGISTER_TABLE(name, F, B, B)
#define REGISTER_TABLE_BZ(name) REGISTER_TABLE(name, F, B, Z)
#define REGISTER_TABLE_BB_CZ(name) \
REGISTER_TABLE_DIMENSIONS(name, FR_BZ_ ## name, F, B, B, \
FR_BZ_ ## name ## _STEP, \
FR_BB_ ## name ## _ROWS), \
REGISTER_TABLE_DIMENSIONS(name, FR_BZ_ ## name, F, C, Z, \
FR_BZ_ ## name ## _STEP, \
FR_CZ_ ## name ## _ROWS)
#define REGISTER_TABLE_CZ(name) REGISTER_TABLE(name, F, C, Z)
static const struct efx_nic_reg_table efx_nic_reg_tables[] = {
/* DRIVER is not used */
/* EVQ_RPTR, TIMER_COMMAND, USR_EV and {RX,TX}_DESC_UPD are WO */
REGISTER_TABLE_BB(TX_IPFIL_TBL),
REGISTER_TABLE_BB(TX_SRC_MAC_TBL),
REGISTER_TABLE_AA(RX_DESC_PTR_TBL_KER),
REGISTER_TABLE_BB_CZ(RX_DESC_PTR_TBL),
REGISTER_TABLE_AA(TX_DESC_PTR_TBL_KER),
REGISTER_TABLE_BB_CZ(TX_DESC_PTR_TBL),
REGISTER_TABLE_AA(EVQ_PTR_TBL_KER),
REGISTER_TABLE_BB_CZ(EVQ_PTR_TBL),
/* We can't reasonably read all of the buffer table (up to 8MB!).
* However this driver will only use a few entries. Reading
* 1K entries allows for some expansion of queue count and
* size before we need to change the version. */
REGISTER_TABLE_DIMENSIONS(BUF_FULL_TBL_KER, FR_AA_BUF_FULL_TBL_KER,
F, A, A, 8, 1024),
REGISTER_TABLE_DIMENSIONS(BUF_FULL_TBL, FR_BZ_BUF_FULL_TBL,
F, B, Z, 8, 1024),
REGISTER_TABLE_CZ(RX_MAC_FILTER_TBL0),
REGISTER_TABLE_BB_CZ(TIMER_TBL),
REGISTER_TABLE_BB_CZ(TX_PACE_TBL),
REGISTER_TABLE_BZ(RX_INDIRECTION_TBL),
/* TX_FILTER_TBL0 is huge and not used by this driver */
REGISTER_TABLE_CZ(TX_MAC_FILTER_TBL0),
REGISTER_TABLE_CZ(MC_TREG_SMEM),
/* MSIX_PBA_TABLE is not mapped */
/* SRM_DBG is not mapped (and is redundant with BUF_FLL_TBL) */
REGISTER_TABLE_BZ(RX_FILTER_TBL0),
};
size_t efx_siena_get_regs_len(struct efx_nic *efx)
{
const struct efx_nic_reg *reg;
const struct efx_nic_reg_table *table;
size_t len = 0;
for (reg = efx_nic_regs;
reg < efx_nic_regs + ARRAY_SIZE(efx_nic_regs);
reg++)
if (efx->type->revision >= reg->min_revision &&
efx->type->revision <= reg->max_revision)
len += sizeof(efx_oword_t);
for (table = efx_nic_reg_tables;
table < efx_nic_reg_tables + ARRAY_SIZE(efx_nic_reg_tables);
table++)
if (efx->type->revision >= table->min_revision &&
efx->type->revision <= table->max_revision)
len += table->rows * min_t(size_t, table->step, 16);
return len;
}
void efx_siena_get_regs(struct efx_nic *efx, void *buf)
{
const struct efx_nic_reg *reg;
const struct efx_nic_reg_table *table;
for (reg = efx_nic_regs;
reg < efx_nic_regs + ARRAY_SIZE(efx_nic_regs);
reg++) {
if (efx->type->revision >= reg->min_revision &&
efx->type->revision <= reg->max_revision) {
efx_reado(efx, (efx_oword_t *)buf, reg->offset);
buf += sizeof(efx_oword_t);
}
}
for (table = efx_nic_reg_tables;
table < efx_nic_reg_tables + ARRAY_SIZE(efx_nic_reg_tables);
table++) {
size_t size, i;
if (!(efx->type->revision >= table->min_revision &&
efx->type->revision <= table->max_revision))
continue;
size = min_t(size_t, table->step, 16);
for (i = 0; i < table->rows; i++) {
switch (table->step) {
case 4: /* 32-bit SRAM */
efx_readd(efx, buf, table->offset + 4 * i);
break;
case 8: /* 64-bit SRAM */
efx_sram_readq(efx,
efx->membase + table->offset,
buf, i);
break;
case 16: /* 128-bit-readable register */
efx_reado_table(efx, buf, table->offset, i);
break;
case 32: /* 128-bit register, interleaved */
efx_reado_table(efx, buf, table->offset, 2 * i);
break;
default:
WARN_ON(1);
return;
}
buf += size;
}
}
}
/**
* efx_siena_describe_stats - Describe supported statistics for ethtool
* @desc: Array of &struct efx_hw_stat_desc describing the statistics
* @count: Length of the @desc array
* @mask: Bitmask of which elements of @desc are enabled
* @names: Buffer to copy names to, or %NULL. The names are copied
* starting at intervals of %ETH_GSTRING_LEN bytes.
*
* Returns the number of visible statistics, i.e. the number of set
* bits in the first @count bits of @mask for which a name is defined.
*/
size_t efx_siena_describe_stats(const struct efx_hw_stat_desc *desc, size_t count,
const unsigned long *mask, u8 *names)
{
size_t visible = 0;
size_t index;
for_each_set_bit(index, mask, count) {
if (desc[index].name) {
if (names) {
strscpy(names, desc[index].name,
ETH_GSTRING_LEN);
names += ETH_GSTRING_LEN;
}
++visible;
}
}
return visible;
}
/**
* efx_siena_update_stats - Convert statistics DMA buffer to array of u64
* @desc: Array of &struct efx_hw_stat_desc describing the DMA buffer
* layout. DMA widths of 0, 16, 32 and 64 are supported; where
* the width is specified as 0 the corresponding element of
* @stats is not updated.
* @count: Length of the @desc array
* @mask: Bitmask of which elements of @desc are enabled
* @stats: Buffer to update with the converted statistics. The length
* of this array must be at least @count.
* @dma_buf: DMA buffer containing hardware statistics
* @accumulate: If set, the converted values will be added rather than
* directly stored to the corresponding elements of @stats
*/
void efx_siena_update_stats(const struct efx_hw_stat_desc *desc, size_t count,
const unsigned long *mask,
u64 *stats, const void *dma_buf, bool accumulate)
{
size_t index;
for_each_set_bit(index, mask, count) {
if (desc[index].dma_width) {
const void *addr = dma_buf + desc[index].offset;
u64 val;
switch (desc[index].dma_width) {
case 16:
val = le16_to_cpup((__le16 *)addr);
break;
case 32:
val = le32_to_cpup((__le32 *)addr);
break;
case 64:
val = le64_to_cpup((__le64 *)addr);
break;
default:
WARN_ON(1);
val = 0;
break;
}
if (accumulate)
stats[index] += val;
else
stats[index] = val;
}
}
}
void efx_siena_fix_nodesc_drop_stat(struct efx_nic *efx, u64 *rx_nodesc_drops)
{
/* if down, or this is the first update after coming up */
if (!(efx->net_dev->flags & IFF_UP) || !efx->rx_nodesc_drops_prev_state)
efx->rx_nodesc_drops_while_down +=
*rx_nodesc_drops - efx->rx_nodesc_drops_total;
efx->rx_nodesc_drops_total = *rx_nodesc_drops;
efx->rx_nodesc_drops_prev_state = !!(efx->net_dev->flags & IFF_UP);
*rx_nodesc_drops -= efx->rx_nodesc_drops_while_down;
}
|
linux-master
|
drivers/net/ethernet/sfc/siena/nic.c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.