python_code
stringlengths
0
1.8M
repo_name
stringclasses
7 values
file_path
stringlengths
5
99
/* Written 1998-2000 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 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. The author may be reached as [email protected], or C/O Scyld Computing Corporation 410 Severn Ave., Suite 210 Annapolis MD 21403 Support information and updates available at http://www.scyld.com/network/pci-skeleton.html Linux kernel updates: Version 2.51, Nov 17, 2001 (jgarzik): - Add ethtool support - Replace some MII-related magic numbers with constants */ #define DRV_NAME "fealnx" static int debug; /* 1-> print debug message */ static int max_interrupt_work = 20; /* Maximum number of multicast addresses to filter (vs. Rx-all-multicast). */ static int multicast_filter_limit = 32; /* Set the copy breakpoint for the copy-only-tiny-frames scheme. */ /* Setting to > 1518 effectively disables this feature. */ static int rx_copybreak; /* Used to pass the media type, etc. */ /* Both 'options[]' and 'full_duplex[]' should exist for driver */ /* interoperability. */ /* The media type is usually passed in 'options[]'. */ #define MAX_UNITS 8 /* More are supported, limit only on options */ static int options[MAX_UNITS] = { -1, -1, -1, -1, -1, -1, -1, -1 }; static int full_duplex[MAX_UNITS] = { -1, -1, -1, -1, -1, -1, -1, -1 }; /* Operational parameters that are set at compile time. */ /* Keep the ring sizes a power of two for compile efficiency. */ /* The compiler will convert <unsigned>'%'<2^N> into a bit mask. */ /* Making the Tx ring too large decreases the effectiveness of channel */ /* bonding and packet priority. */ /* There are no ill effects from too-large receive rings. */ // 88-12-9 modify, // #define TX_RING_SIZE 16 // #define RX_RING_SIZE 32 #define TX_RING_SIZE 6 #define RX_RING_SIZE 12 #define TX_TOTAL_SIZE TX_RING_SIZE*sizeof(struct fealnx_desc) #define RX_TOTAL_SIZE RX_RING_SIZE*sizeof(struct fealnx_desc) /* Operational parameters that usually are not changed. */ /* Time in jiffies before concluding the transmitter is hung. */ #define TX_TIMEOUT (2*HZ) #define PKT_BUF_SZ 1536 /* Size of each temporary Rx buffer. */ /* Include files, designed to support most kernel versions 2.0.0 and later. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/timer.h> #include <linux/errno.h> #include <linux/ioport.h> #include <linux/interrupt.h> #include <linux/pci.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/skbuff.h> #include <linux/init.h> #include <linux/mii.h> #include <linux/ethtool.h> #include <linux/crc32.h> #include <linux/delay.h> #include <linux/bitops.h> #include <asm/processor.h> /* Processor type for cache alignment. */ #include <asm/io.h> #include <linux/uaccess.h> #include <asm/byteorder.h> /* This driver was written to use PCI memory space, however some x86 systems work only with I/O space accesses. */ #ifndef __alpha__ #define USE_IO_OPS #endif /* Kernel compatibility defines, some common to David Hinds' PCMCIA package. */ /* This is only in the support-all-kernels source code. */ #define RUN_AT(x) (jiffies + (x)) MODULE_AUTHOR("Myson or whoever"); MODULE_DESCRIPTION("Myson MTD-8xx 100/10M Ethernet PCI Adapter Driver"); MODULE_LICENSE("GPL"); module_param(max_interrupt_work, int, 0); module_param(debug, int, 0); module_param(rx_copybreak, int, 0); module_param(multicast_filter_limit, int, 0); module_param_array(options, int, NULL, 0); module_param_array(full_duplex, int, NULL, 0); MODULE_PARM_DESC(max_interrupt_work, "fealnx maximum events handled per interrupt"); MODULE_PARM_DESC(debug, "fealnx enable debugging (0-1)"); MODULE_PARM_DESC(rx_copybreak, "fealnx copy breakpoint for copy-only-tiny-frames"); MODULE_PARM_DESC(multicast_filter_limit, "fealnx maximum number of filtered multicast addresses"); MODULE_PARM_DESC(options, "fealnx: Bits 0-3: media type, bit 17: full duplex"); MODULE_PARM_DESC(full_duplex, "fealnx full duplex setting(s) (1)"); enum { MIN_REGION_SIZE = 136, }; /* A chip capabilities table, matching the entries in pci_tbl[] above. */ enum chip_capability_flags { HAS_MII_XCVR, HAS_CHIP_XCVR, }; /* 89/6/13 add, */ /* for different PHY */ enum phy_type_flags { MysonPHY = 1, AhdocPHY = 2, SeeqPHY = 3, MarvellPHY = 4, Myson981 = 5, LevelOnePHY = 6, OtherPHY = 10, }; struct chip_info { char *chip_name; int flags; }; static const struct chip_info skel_netdrv_tbl[] = { { "100/10M Ethernet PCI Adapter", HAS_MII_XCVR }, { "100/10M Ethernet PCI Adapter", HAS_CHIP_XCVR }, { "1000/100/10M Ethernet PCI Adapter", HAS_MII_XCVR }, }; /* Offsets to the Command and Status Registers. */ enum fealnx_offsets { PAR0 = 0x0, /* physical address 0-3 */ PAR1 = 0x04, /* physical address 4-5 */ MAR0 = 0x08, /* multicast address 0-3 */ MAR1 = 0x0C, /* multicast address 4-7 */ FAR0 = 0x10, /* flow-control address 0-3 */ FAR1 = 0x14, /* flow-control address 4-5 */ TCRRCR = 0x18, /* receive & transmit configuration */ BCR = 0x1C, /* bus command */ TXPDR = 0x20, /* transmit polling demand */ RXPDR = 0x24, /* receive polling demand */ RXCWP = 0x28, /* receive current word pointer */ TXLBA = 0x2C, /* transmit list base address */ RXLBA = 0x30, /* receive list base address */ ISR = 0x34, /* interrupt status */ IMR = 0x38, /* interrupt mask */ FTH = 0x3C, /* flow control high/low threshold */ MANAGEMENT = 0x40, /* bootrom/eeprom and mii management */ TALLY = 0x44, /* tally counters for crc and mpa */ TSR = 0x48, /* tally counter for transmit status */ BMCRSR = 0x4c, /* basic mode control and status */ PHYIDENTIFIER = 0x50, /* phy identifier */ ANARANLPAR = 0x54, /* auto-negotiation advertisement and link partner ability */ ANEROCR = 0x58, /* auto-negotiation expansion and pci conf. */ BPREMRPSR = 0x5c, /* bypass & receive error mask and phy status */ }; /* Bits in the interrupt status/enable registers. */ /* The bits in the Intr Status/Enable registers, mostly interrupt sources. */ enum intr_status_bits { RFCON = 0x00020000, /* receive flow control xon packet */ RFCOFF = 0x00010000, /* receive flow control xoff packet */ LSCStatus = 0x00008000, /* link status change */ ANCStatus = 0x00004000, /* autonegotiation completed */ FBE = 0x00002000, /* fatal bus error */ FBEMask = 0x00001800, /* mask bit12-11 */ ParityErr = 0x00000000, /* parity error */ TargetErr = 0x00001000, /* target abort */ MasterErr = 0x00000800, /* master error */ TUNF = 0x00000400, /* transmit underflow */ ROVF = 0x00000200, /* receive overflow */ ETI = 0x00000100, /* transmit early int */ ERI = 0x00000080, /* receive early int */ CNTOVF = 0x00000040, /* counter overflow */ RBU = 0x00000020, /* receive buffer unavailable */ TBU = 0x00000010, /* transmit buffer unavilable */ TI = 0x00000008, /* transmit interrupt */ RI = 0x00000004, /* receive interrupt */ RxErr = 0x00000002, /* receive error */ }; /* Bits in the NetworkConfig register, W for writing, R for reading */ /* FIXME: some names are invented by me. Marked with (name?) */ /* If you have docs and know bit names, please fix 'em */ enum rx_mode_bits { CR_W_ENH = 0x02000000, /* enhanced mode (name?) */ CR_W_FD = 0x00100000, /* full duplex */ CR_W_PS10 = 0x00080000, /* 10 mbit */ CR_W_TXEN = 0x00040000, /* tx enable (name?) */ CR_W_PS1000 = 0x00010000, /* 1000 mbit */ /* CR_W_RXBURSTMASK= 0x00000e00, Im unsure about this */ CR_W_RXMODEMASK = 0x000000e0, CR_W_PROM = 0x00000080, /* promiscuous mode */ CR_W_AB = 0x00000040, /* accept broadcast */ CR_W_AM = 0x00000020, /* accept mutlicast */ CR_W_ARP = 0x00000008, /* receive runt pkt */ CR_W_ALP = 0x00000004, /* receive long pkt */ CR_W_SEP = 0x00000002, /* receive error pkt */ CR_W_RXEN = 0x00000001, /* rx enable (unicast?) (name?) */ CR_R_TXSTOP = 0x04000000, /* tx stopped (name?) */ CR_R_FD = 0x00100000, /* full duplex detected */ CR_R_PS10 = 0x00080000, /* 10 mbit detected */ CR_R_RXSTOP = 0x00008000, /* rx stopped (name?) */ }; /* The Tulip Rx and Tx buffer descriptors. */ struct fealnx_desc { s32 status; s32 control; u32 buffer; u32 next_desc; struct fealnx_desc *next_desc_logical; struct sk_buff *skbuff; u32 reserved1; u32 reserved2; }; /* Bits in network_desc.status */ enum rx_desc_status_bits { RXOWN = 0x80000000, /* own bit */ FLNGMASK = 0x0fff0000, /* frame length */ FLNGShift = 16, MARSTATUS = 0x00004000, /* multicast address received */ BARSTATUS = 0x00002000, /* broadcast address received */ PHYSTATUS = 0x00001000, /* physical address received */ RXFSD = 0x00000800, /* first descriptor */ RXLSD = 0x00000400, /* last descriptor */ ErrorSummary = 0x80, /* error summary */ RUNTPKT = 0x40, /* runt packet received */ LONGPKT = 0x20, /* long packet received */ FAE = 0x10, /* frame align error */ CRC = 0x08, /* crc error */ RXER = 0x04, /* receive error */ }; enum rx_desc_control_bits { RXIC = 0x00800000, /* interrupt control */ RBSShift = 0, }; enum tx_desc_status_bits { TXOWN = 0x80000000, /* own bit */ JABTO = 0x00004000, /* jabber timeout */ CSL = 0x00002000, /* carrier sense lost */ LC = 0x00001000, /* late collision */ EC = 0x00000800, /* excessive collision */ UDF = 0x00000400, /* fifo underflow */ DFR = 0x00000200, /* deferred */ HF = 0x00000100, /* heartbeat fail */ NCRMask = 0x000000ff, /* collision retry count */ NCRShift = 0, }; enum tx_desc_control_bits { TXIC = 0x80000000, /* interrupt control */ ETIControl = 0x40000000, /* early transmit interrupt */ TXLD = 0x20000000, /* last descriptor */ TXFD = 0x10000000, /* first descriptor */ CRCEnable = 0x08000000, /* crc control */ PADEnable = 0x04000000, /* padding control */ RetryTxLC = 0x02000000, /* retry late collision */ PKTSMask = 0x3ff800, /* packet size bit21-11 */ PKTSShift = 11, TBSMask = 0x000007ff, /* transmit buffer bit 10-0 */ TBSShift = 0, }; /* BootROM/EEPROM/MII Management Register */ #define MASK_MIIR_MII_READ 0x00000000 #define MASK_MIIR_MII_WRITE 0x00000008 #define MASK_MIIR_MII_MDO 0x00000004 #define MASK_MIIR_MII_MDI 0x00000002 #define MASK_MIIR_MII_MDC 0x00000001 /* ST+OP+PHYAD+REGAD+TA */ #define OP_READ 0x6000 /* ST:01+OP:10+PHYAD+REGAD+TA:Z0 */ #define OP_WRITE 0x5002 /* ST:01+OP:01+PHYAD+REGAD+TA:10 */ /* ------------------------------------------------------------------------- */ /* Constants for Myson PHY */ /* ------------------------------------------------------------------------- */ #define MysonPHYID 0xd0000302 /* 89-7-27 add, (begin) */ #define MysonPHYID0 0x0302 #define StatusRegister 18 #define SPEED100 0x0400 // bit10 #define FULLMODE 0x0800 // bit11 /* 89-7-27 add, (end) */ /* ------------------------------------------------------------------------- */ /* Constants for Seeq 80225 PHY */ /* ------------------------------------------------------------------------- */ #define SeeqPHYID0 0x0016 #define MIIRegister18 18 #define SPD_DET_100 0x80 #define DPLX_DET_FULL 0x40 /* ------------------------------------------------------------------------- */ /* Constants for Ahdoc 101 PHY */ /* ------------------------------------------------------------------------- */ #define AhdocPHYID0 0x0022 #define DiagnosticReg 18 #define DPLX_FULL 0x0800 #define Speed_100 0x0400 /* 89/6/13 add, */ /* -------------------------------------------------------------------------- */ /* Constants */ /* -------------------------------------------------------------------------- */ #define MarvellPHYID0 0x0141 #define LevelOnePHYID0 0x0013 #define MII1000BaseTControlReg 9 #define MII1000BaseTStatusReg 10 #define SpecificReg 17 /* for 1000BaseT Control Register */ #define PHYAbletoPerform1000FullDuplex 0x0200 #define PHYAbletoPerform1000HalfDuplex 0x0100 #define PHY1000AbilityMask 0x300 // for phy specific status register, marvell phy. #define SpeedMask 0x0c000 #define Speed_1000M 0x08000 #define Speed_100M 0x4000 #define Speed_10M 0 #define Full_Duplex 0x2000 // 89/12/29 add, for phy specific status register, levelone phy, (begin) #define LXT1000_100M 0x08000 #define LXT1000_1000M 0x0c000 #define LXT1000_Full 0x200 // 89/12/29 add, for phy specific status register, levelone phy, (end) /* for 3-in-1 case, BMCRSR register */ #define LinkIsUp2 0x00040000 /* for PHY */ #define LinkIsUp 0x0004 struct netdev_private { /* Descriptor rings first for alignment. */ struct fealnx_desc *rx_ring; struct fealnx_desc *tx_ring; dma_addr_t rx_ring_dma; dma_addr_t tx_ring_dma; spinlock_t lock; /* Media monitoring timer. */ struct timer_list timer; /* Reset timer */ struct timer_list reset_timer; int reset_timer_armed; unsigned long crvalue_sv; unsigned long imrvalue_sv; /* Frequently used values: keep some adjacent for cache effect. */ int flags; struct pci_dev *pci_dev; unsigned long crvalue; unsigned long bcrvalue; unsigned long imrvalue; struct fealnx_desc *cur_rx; struct fealnx_desc *lack_rxbuf; int really_rx_count; struct fealnx_desc *cur_tx; struct fealnx_desc *cur_tx_copy; int really_tx_count; int free_tx_count; unsigned int rx_buf_sz; /* Based on MTU+slack. */ /* These values are keep track of the transceiver/media in use. */ unsigned int linkok; unsigned int line_speed; unsigned int duplexmode; unsigned int default_port:4; /* Last dev->if_port value. */ unsigned int PHYType; /* MII transceiver section. */ int mii_cnt; /* MII device addresses. */ unsigned char phys[2]; /* MII device addresses. */ struct mii_if_info mii; void __iomem *mem; }; static int mdio_read(struct net_device *dev, int phy_id, int location); static void mdio_write(struct net_device *dev, int phy_id, int location, int value); static int netdev_open(struct net_device *dev); static void getlinktype(struct net_device *dev); static void getlinkstatus(struct net_device *dev); static void netdev_timer(struct timer_list *t); static void reset_timer(struct timer_list *t); static void fealnx_tx_timeout(struct net_device *dev, unsigned int txqueue); static void init_ring(struct net_device *dev); static netdev_tx_t start_tx(struct sk_buff *skb, struct net_device *dev); static irqreturn_t intr_handler(int irq, void *dev_instance); static int netdev_rx(struct net_device *dev); static void set_rx_mode(struct net_device *dev); static void __set_rx_mode(struct net_device *dev); static struct net_device_stats *get_stats(struct net_device *dev); static int mii_ioctl(struct net_device *dev, struct ifreq *rq, int cmd); static const struct ethtool_ops netdev_ethtool_ops; static int netdev_close(struct net_device *dev); static void reset_rx_descriptors(struct net_device *dev); static void reset_tx_descriptors(struct net_device *dev); static void stop_nic_rx(void __iomem *ioaddr, long crvalue) { int delay = 0x1000; iowrite32(crvalue & ~(CR_W_RXEN), ioaddr + TCRRCR); while (--delay) { if ( (ioread32(ioaddr + TCRRCR) & CR_R_RXSTOP) == CR_R_RXSTOP) break; } } static void stop_nic_rxtx(void __iomem *ioaddr, long crvalue) { int delay = 0x1000; iowrite32(crvalue & ~(CR_W_RXEN+CR_W_TXEN), ioaddr + TCRRCR); while (--delay) { if ( (ioread32(ioaddr + TCRRCR) & (CR_R_RXSTOP+CR_R_TXSTOP)) == (CR_R_RXSTOP+CR_R_TXSTOP) ) break; } } static const struct net_device_ops netdev_ops = { .ndo_open = netdev_open, .ndo_stop = netdev_close, .ndo_start_xmit = start_tx, .ndo_get_stats = get_stats, .ndo_set_rx_mode = set_rx_mode, .ndo_eth_ioctl = mii_ioctl, .ndo_tx_timeout = fealnx_tx_timeout, .ndo_set_mac_address = eth_mac_addr, .ndo_validate_addr = eth_validate_addr, }; static int fealnx_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) { struct netdev_private *np; int i, option, err, irq; static int card_idx = -1; char boardname[12]; void __iomem *ioaddr; unsigned long len; unsigned int chip_id = ent->driver_data; struct net_device *dev; void *ring_space; dma_addr_t ring_dma; u8 addr[ETH_ALEN]; #ifdef USE_IO_OPS int bar = 0; #else int bar = 1; #endif card_idx++; sprintf(boardname, "fealnx%d", card_idx); option = card_idx < MAX_UNITS ? options[card_idx] : 0; i = pci_enable_device(pdev); if (i) return i; pci_set_master(pdev); len = pci_resource_len(pdev, bar); if (len < MIN_REGION_SIZE) { dev_err(&pdev->dev, "region size %ld too small, aborting\n", len); return -ENODEV; } i = pci_request_regions(pdev, boardname); if (i) return i; irq = pdev->irq; ioaddr = pci_iomap(pdev, bar, len); if (!ioaddr) { err = -ENOMEM; goto err_out_res; } dev = alloc_etherdev(sizeof(struct netdev_private)); if (!dev) { err = -ENOMEM; goto err_out_unmap; } SET_NETDEV_DEV(dev, &pdev->dev); /* read ethernet id */ for (i = 0; i < 6; ++i) addr[i] = ioread8(ioaddr + PAR0 + i); eth_hw_addr_set(dev, addr); /* Reset the chip to erase previous misconfiguration. */ iowrite32(0x00000001, ioaddr + BCR); /* Make certain the descriptor lists are aligned. */ np = netdev_priv(dev); np->mem = ioaddr; spin_lock_init(&np->lock); np->pci_dev = pdev; np->flags = skel_netdrv_tbl[chip_id].flags; pci_set_drvdata(pdev, dev); np->mii.dev = dev; np->mii.mdio_read = mdio_read; np->mii.mdio_write = mdio_write; np->mii.phy_id_mask = 0x1f; np->mii.reg_num_mask = 0x1f; ring_space = dma_alloc_coherent(&pdev->dev, RX_TOTAL_SIZE, &ring_dma, GFP_KERNEL); if (!ring_space) { err = -ENOMEM; goto err_out_free_dev; } np->rx_ring = ring_space; np->rx_ring_dma = ring_dma; ring_space = dma_alloc_coherent(&pdev->dev, TX_TOTAL_SIZE, &ring_dma, GFP_KERNEL); if (!ring_space) { err = -ENOMEM; goto err_out_free_rx; } np->tx_ring = ring_space; np->tx_ring_dma = ring_dma; /* find the connected MII xcvrs */ if (np->flags == HAS_MII_XCVR) { int phy, phy_idx = 0; for (phy = 1; phy < 32 && phy_idx < ARRAY_SIZE(np->phys); phy++) { int mii_status = mdio_read(dev, phy, 1); if (mii_status != 0xffff && mii_status != 0x0000) { np->phys[phy_idx++] = phy; dev_info(&pdev->dev, "MII PHY found at address %d, status " "0x%4.4x.\n", phy, mii_status); /* get phy type */ { unsigned int data; data = mdio_read(dev, np->phys[0], 2); if (data == SeeqPHYID0) np->PHYType = SeeqPHY; else if (data == AhdocPHYID0) np->PHYType = AhdocPHY; else if (data == MarvellPHYID0) np->PHYType = MarvellPHY; else if (data == MysonPHYID0) np->PHYType = Myson981; else if (data == LevelOnePHYID0) np->PHYType = LevelOnePHY; else np->PHYType = OtherPHY; } } } np->mii_cnt = phy_idx; if (phy_idx == 0) dev_warn(&pdev->dev, "MII PHY not found -- this device may " "not operate correctly.\n"); } else { np->phys[0] = 32; /* 89/6/23 add, (begin) */ /* get phy type */ if (ioread32(ioaddr + PHYIDENTIFIER) == MysonPHYID) np->PHYType = MysonPHY; else np->PHYType = OtherPHY; } np->mii.phy_id = np->phys[0]; if (dev->mem_start) option = dev->mem_start; /* The lower four bits are the media type. */ if (option > 0) { if (option & 0x200) np->mii.full_duplex = 1; np->default_port = option & 15; } if (card_idx < MAX_UNITS && full_duplex[card_idx] > 0) np->mii.full_duplex = full_duplex[card_idx]; if (np->mii.full_duplex) { dev_info(&pdev->dev, "Media type forced to Full Duplex.\n"); /* 89/6/13 add, (begin) */ // if (np->PHYType==MarvellPHY) if ((np->PHYType == MarvellPHY) || (np->PHYType == LevelOnePHY)) { unsigned int data; data = mdio_read(dev, np->phys[0], 9); data = (data & 0xfcff) | 0x0200; mdio_write(dev, np->phys[0], 9, data); } /* 89/6/13 add, (end) */ if (np->flags == HAS_MII_XCVR) mdio_write(dev, np->phys[0], MII_ADVERTISE, ADVERTISE_FULL); else iowrite32(ADVERTISE_FULL, ioaddr + ANARANLPAR); np->mii.force_media = 1; } dev->netdev_ops = &netdev_ops; dev->ethtool_ops = &netdev_ethtool_ops; dev->watchdog_timeo = TX_TIMEOUT; err = register_netdev(dev); if (err) goto err_out_free_tx; printk(KERN_INFO "%s: %s at %p, %pM, IRQ %d.\n", dev->name, skel_netdrv_tbl[chip_id].chip_name, ioaddr, dev->dev_addr, irq); return 0; err_out_free_tx: dma_free_coherent(&pdev->dev, TX_TOTAL_SIZE, np->tx_ring, np->tx_ring_dma); err_out_free_rx: dma_free_coherent(&pdev->dev, RX_TOTAL_SIZE, np->rx_ring, np->rx_ring_dma); err_out_free_dev: free_netdev(dev); err_out_unmap: pci_iounmap(pdev, ioaddr); err_out_res: pci_release_regions(pdev); return err; } static void fealnx_remove_one(struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata(pdev); if (dev) { struct netdev_private *np = netdev_priv(dev); dma_free_coherent(&pdev->dev, TX_TOTAL_SIZE, np->tx_ring, np->tx_ring_dma); dma_free_coherent(&pdev->dev, RX_TOTAL_SIZE, np->rx_ring, np->rx_ring_dma); unregister_netdev(dev); pci_iounmap(pdev, np->mem); free_netdev(dev); pci_release_regions(pdev); } else printk(KERN_ERR "fealnx: remove for unknown device\n"); } static ulong m80x_send_cmd_to_phy(void __iomem *miiport, int opcode, int phyad, int regad) { ulong miir; int i; unsigned int mask, data; /* enable MII output */ miir = (ulong) ioread32(miiport); miir &= 0xfffffff0; miir |= MASK_MIIR_MII_WRITE + MASK_MIIR_MII_MDO; /* send 32 1's preamble */ for (i = 0; i < 32; i++) { /* low MDC; MDO is already high (miir) */ miir &= ~MASK_MIIR_MII_MDC; iowrite32(miir, miiport); /* high MDC */ miir |= MASK_MIIR_MII_MDC; iowrite32(miir, miiport); } /* calculate ST+OP+PHYAD+REGAD+TA */ data = opcode | (phyad << 7) | (regad << 2); /* sent out */ mask = 0x8000; while (mask) { /* low MDC, prepare MDO */ miir &= ~(MASK_MIIR_MII_MDC + MASK_MIIR_MII_MDO); if (mask & data) miir |= MASK_MIIR_MII_MDO; iowrite32(miir, miiport); /* high MDC */ miir |= MASK_MIIR_MII_MDC; iowrite32(miir, miiport); udelay(30); /* next */ mask >>= 1; if (mask == 0x2 && opcode == OP_READ) miir &= ~MASK_MIIR_MII_WRITE; } return miir; } static int mdio_read(struct net_device *dev, int phyad, int regad) { struct netdev_private *np = netdev_priv(dev); void __iomem *miiport = np->mem + MANAGEMENT; ulong miir; unsigned int mask, data; miir = m80x_send_cmd_to_phy(miiport, OP_READ, phyad, regad); /* read data */ mask = 0x8000; data = 0; while (mask) { /* low MDC */ miir &= ~MASK_MIIR_MII_MDC; iowrite32(miir, miiport); /* read MDI */ miir = ioread32(miiport); if (miir & MASK_MIIR_MII_MDI) data |= mask; /* high MDC, and wait */ miir |= MASK_MIIR_MII_MDC; iowrite32(miir, miiport); udelay(30); /* next */ mask >>= 1; } /* low MDC */ miir &= ~MASK_MIIR_MII_MDC; iowrite32(miir, miiport); return data & 0xffff; } static void mdio_write(struct net_device *dev, int phyad, int regad, int data) { struct netdev_private *np = netdev_priv(dev); void __iomem *miiport = np->mem + MANAGEMENT; ulong miir; unsigned int mask; miir = m80x_send_cmd_to_phy(miiport, OP_WRITE, phyad, regad); /* write data */ mask = 0x8000; while (mask) { /* low MDC, prepare MDO */ miir &= ~(MASK_MIIR_MII_MDC + MASK_MIIR_MII_MDO); if (mask & data) miir |= MASK_MIIR_MII_MDO; iowrite32(miir, miiport); /* high MDC */ miir |= MASK_MIIR_MII_MDC; iowrite32(miir, miiport); /* next */ mask >>= 1; } /* low MDC */ miir &= ~MASK_MIIR_MII_MDC; iowrite32(miir, miiport); } static int netdev_open(struct net_device *dev) { struct netdev_private *np = netdev_priv(dev); void __iomem *ioaddr = np->mem; const int irq = np->pci_dev->irq; int rc, i; iowrite32(0x00000001, ioaddr + BCR); /* Reset */ rc = request_irq(irq, intr_handler, IRQF_SHARED, dev->name, dev); if (rc) return -EAGAIN; for (i = 0; i < 3; i++) iowrite16(((const unsigned short *)dev->dev_addr)[i], ioaddr + PAR0 + i*2); init_ring(dev); iowrite32(np->rx_ring_dma, ioaddr + RXLBA); iowrite32(np->tx_ring_dma, ioaddr + TXLBA); /* Initialize other registers. */ /* Configure the PCI bus bursts and FIFO thresholds. 486: Set 8 longword burst. 586: no burst limit. Burst length 5:3 0 0 0 1 0 0 1 4 0 1 0 8 0 1 1 16 1 0 0 32 1 0 1 64 1 1 0 128 1 1 1 256 Wait the specified 50 PCI cycles after a reset by initializing Tx and Rx queues and the address filter list. FIXME (Ueimor): optimistic for alpha + posted writes ? */ np->bcrvalue = 0x10; /* little-endian, 8 burst length */ #ifdef __BIG_ENDIAN np->bcrvalue |= 0x04; /* big-endian */ #endif #if defined(__i386__) && !defined(MODULE) && !defined(CONFIG_UML) if (boot_cpu_data.x86 <= 4) np->crvalue = 0xa00; else #endif np->crvalue = 0xe00; /* rx 128 burst length */ // 89/12/29 add, // 90/1/16 modify, // np->imrvalue=FBE|TUNF|CNTOVF|RBU|TI|RI; np->imrvalue = TUNF | CNTOVF | RBU | TI | RI; if (np->pci_dev->device == 0x891) { np->bcrvalue |= 0x200; /* set PROG bit */ np->crvalue |= CR_W_ENH; /* set enhanced bit */ np->imrvalue |= ETI; } iowrite32(np->bcrvalue, ioaddr + BCR); if (dev->if_port == 0) dev->if_port = np->default_port; iowrite32(0, ioaddr + RXPDR); // 89/9/1 modify, // np->crvalue = 0x00e40001; /* tx store and forward, tx/rx enable */ np->crvalue |= 0x00e40001; /* tx store and forward, tx/rx enable */ np->mii.full_duplex = np->mii.force_media; getlinkstatus(dev); if (np->linkok) getlinktype(dev); __set_rx_mode(dev); netif_start_queue(dev); /* Clear and Enable interrupts by setting the interrupt mask. */ iowrite32(FBE | TUNF | CNTOVF | RBU | TI | RI, ioaddr + ISR); iowrite32(np->imrvalue, ioaddr + IMR); if (debug) printk(KERN_DEBUG "%s: Done netdev_open().\n", dev->name); /* Set the timer to check for link beat. */ timer_setup(&np->timer, netdev_timer, 0); np->timer.expires = RUN_AT(3 * HZ); /* timer handler */ add_timer(&np->timer); timer_setup(&np->reset_timer, reset_timer, 0); np->reset_timer_armed = 0; return rc; } static void getlinkstatus(struct net_device *dev) /* function: Routine will read MII Status Register to get link status. */ /* input : dev... pointer to the adapter block. */ /* output : none. */ { struct netdev_private *np = netdev_priv(dev); unsigned int i, DelayTime = 0x1000; np->linkok = 0; if (np->PHYType == MysonPHY) { for (i = 0; i < DelayTime; ++i) { if (ioread32(np->mem + BMCRSR) & LinkIsUp2) { np->linkok = 1; return; } udelay(100); } } else { for (i = 0; i < DelayTime; ++i) { if (mdio_read(dev, np->phys[0], MII_BMSR) & BMSR_LSTATUS) { np->linkok = 1; return; } udelay(100); } } } static void getlinktype(struct net_device *dev) { struct netdev_private *np = netdev_priv(dev); if (np->PHYType == MysonPHY) { /* 3-in-1 case */ if (ioread32(np->mem + TCRRCR) & CR_R_FD) np->duplexmode = 2; /* full duplex */ else np->duplexmode = 1; /* half duplex */ if (ioread32(np->mem + TCRRCR) & CR_R_PS10) np->line_speed = 1; /* 10M */ else np->line_speed = 2; /* 100M */ } else { if (np->PHYType == SeeqPHY) { /* this PHY is SEEQ 80225 */ unsigned int data; data = mdio_read(dev, np->phys[0], MIIRegister18); if (data & SPD_DET_100) np->line_speed = 2; /* 100M */ else np->line_speed = 1; /* 10M */ if (data & DPLX_DET_FULL) np->duplexmode = 2; /* full duplex mode */ else np->duplexmode = 1; /* half duplex mode */ } else if (np->PHYType == AhdocPHY) { unsigned int data; data = mdio_read(dev, np->phys[0], DiagnosticReg); if (data & Speed_100) np->line_speed = 2; /* 100M */ else np->line_speed = 1; /* 10M */ if (data & DPLX_FULL) np->duplexmode = 2; /* full duplex mode */ else np->duplexmode = 1; /* half duplex mode */ } /* 89/6/13 add, (begin) */ else if (np->PHYType == MarvellPHY) { unsigned int data; data = mdio_read(dev, np->phys[0], SpecificReg); if (data & Full_Duplex) np->duplexmode = 2; /* full duplex mode */ else np->duplexmode = 1; /* half duplex mode */ data &= SpeedMask; if (data == Speed_1000M) np->line_speed = 3; /* 1000M */ else if (data == Speed_100M) np->line_speed = 2; /* 100M */ else np->line_speed = 1; /* 10M */ } /* 89/6/13 add, (end) */ /* 89/7/27 add, (begin) */ else if (np->PHYType == Myson981) { unsigned int data; data = mdio_read(dev, np->phys[0], StatusRegister); if (data & SPEED100) np->line_speed = 2; else np->line_speed = 1; if (data & FULLMODE) np->duplexmode = 2; else np->duplexmode = 1; } /* 89/7/27 add, (end) */ /* 89/12/29 add */ else if (np->PHYType == LevelOnePHY) { unsigned int data; data = mdio_read(dev, np->phys[0], SpecificReg); if (data & LXT1000_Full) np->duplexmode = 2; /* full duplex mode */ else np->duplexmode = 1; /* half duplex mode */ data &= SpeedMask; if (data == LXT1000_1000M) np->line_speed = 3; /* 1000M */ else if (data == LXT1000_100M) np->line_speed = 2; /* 100M */ else np->line_speed = 1; /* 10M */ } np->crvalue &= (~CR_W_PS10) & (~CR_W_FD) & (~CR_W_PS1000); if (np->line_speed == 1) np->crvalue |= CR_W_PS10; else if (np->line_speed == 3) np->crvalue |= CR_W_PS1000; if (np->duplexmode == 2) np->crvalue |= CR_W_FD; } } /* Take lock before calling this */ static void allocate_rx_buffers(struct net_device *dev) { struct netdev_private *np = netdev_priv(dev); /* allocate skb for rx buffers */ while (np->really_rx_count != RX_RING_SIZE) { struct sk_buff *skb; skb = netdev_alloc_skb(dev, np->rx_buf_sz); if (skb == NULL) break; /* Better luck next round. */ while (np->lack_rxbuf->skbuff) np->lack_rxbuf = np->lack_rxbuf->next_desc_logical; np->lack_rxbuf->skbuff = skb; np->lack_rxbuf->buffer = dma_map_single(&np->pci_dev->dev, skb->data, np->rx_buf_sz, DMA_FROM_DEVICE); np->lack_rxbuf->status = RXOWN; ++np->really_rx_count; } } static void netdev_timer(struct timer_list *t) { struct netdev_private *np = from_timer(np, t, timer); struct net_device *dev = np->mii.dev; void __iomem *ioaddr = np->mem; int old_crvalue = np->crvalue; unsigned int old_linkok = np->linkok; unsigned long flags; if (debug) printk(KERN_DEBUG "%s: Media selection timer tick, status %8.8x " "config %8.8x.\n", dev->name, ioread32(ioaddr + ISR), ioread32(ioaddr + TCRRCR)); spin_lock_irqsave(&np->lock, flags); if (np->flags == HAS_MII_XCVR) { getlinkstatus(dev); if ((old_linkok == 0) && (np->linkok == 1)) { /* we need to detect the media type again */ getlinktype(dev); if (np->crvalue != old_crvalue) { stop_nic_rxtx(ioaddr, np->crvalue); iowrite32(np->crvalue, ioaddr + TCRRCR); } } } allocate_rx_buffers(dev); spin_unlock_irqrestore(&np->lock, flags); np->timer.expires = RUN_AT(10 * HZ); add_timer(&np->timer); } /* Take lock before calling */ /* Reset chip and disable rx, tx and interrupts */ static void reset_and_disable_rxtx(struct net_device *dev) { struct netdev_private *np = netdev_priv(dev); void __iomem *ioaddr = np->mem; int delay=51; /* Reset the chip's Tx and Rx processes. */ stop_nic_rxtx(ioaddr, 0); /* Disable interrupts by clearing the interrupt mask. */ iowrite32(0, ioaddr + IMR); /* Reset the chip to erase previous misconfiguration. */ iowrite32(0x00000001, ioaddr + BCR); /* Ueimor: wait for 50 PCI cycles (and flush posted writes btw). We surely wait too long (address+data phase). Who cares? */ while (--delay) { ioread32(ioaddr + BCR); rmb(); } } /* Take lock before calling */ /* Restore chip after reset */ static void enable_rxtx(struct net_device *dev) { struct netdev_private *np = netdev_priv(dev); void __iomem *ioaddr = np->mem; reset_rx_descriptors(dev); iowrite32(np->tx_ring_dma + ((char*)np->cur_tx - (char*)np->tx_ring), ioaddr + TXLBA); iowrite32(np->rx_ring_dma + ((char*)np->cur_rx - (char*)np->rx_ring), ioaddr + RXLBA); iowrite32(np->bcrvalue, ioaddr + BCR); iowrite32(0, ioaddr + RXPDR); __set_rx_mode(dev); /* changes np->crvalue, writes it into TCRRCR */ /* Clear and Enable interrupts by setting the interrupt mask. */ iowrite32(FBE | TUNF | CNTOVF | RBU | TI | RI, ioaddr + ISR); iowrite32(np->imrvalue, ioaddr + IMR); iowrite32(0, ioaddr + TXPDR); } static void reset_timer(struct timer_list *t) { struct netdev_private *np = from_timer(np, t, reset_timer); struct net_device *dev = np->mii.dev; unsigned long flags; printk(KERN_WARNING "%s: resetting tx and rx machinery\n", dev->name); spin_lock_irqsave(&np->lock, flags); np->crvalue = np->crvalue_sv; np->imrvalue = np->imrvalue_sv; reset_and_disable_rxtx(dev); /* works for me without this: reset_tx_descriptors(dev); */ enable_rxtx(dev); netif_start_queue(dev); /* FIXME: or netif_wake_queue(dev); ? */ np->reset_timer_armed = 0; spin_unlock_irqrestore(&np->lock, flags); } static void fealnx_tx_timeout(struct net_device *dev, unsigned int txqueue) { struct netdev_private *np = netdev_priv(dev); void __iomem *ioaddr = np->mem; unsigned long flags; int i; printk(KERN_WARNING "%s: Transmit timed out, status %8.8x, resetting...\n", dev->name, ioread32(ioaddr + ISR)); { printk(KERN_DEBUG " Rx ring %p: ", np->rx_ring); for (i = 0; i < RX_RING_SIZE; i++) printk(KERN_CONT " %8.8x", (unsigned int) np->rx_ring[i].status); printk(KERN_CONT "\n"); printk(KERN_DEBUG " Tx ring %p: ", np->tx_ring); for (i = 0; i < TX_RING_SIZE; i++) printk(KERN_CONT " %4.4x", np->tx_ring[i].status); printk(KERN_CONT "\n"); } spin_lock_irqsave(&np->lock, flags); reset_and_disable_rxtx(dev); reset_tx_descriptors(dev); enable_rxtx(dev); spin_unlock_irqrestore(&np->lock, flags); netif_trans_update(dev); /* prevent tx timeout */ dev->stats.tx_errors++; netif_wake_queue(dev); /* or .._start_.. ?? */ } /* Initialize the Rx and Tx rings, along with various 'dev' bits. */ static void init_ring(struct net_device *dev) { struct netdev_private *np = netdev_priv(dev); int i; /* initialize rx variables */ np->rx_buf_sz = (dev->mtu <= 1500 ? PKT_BUF_SZ : dev->mtu + 32); np->cur_rx = &np->rx_ring[0]; np->lack_rxbuf = np->rx_ring; np->really_rx_count = 0; /* initial rx descriptors. */ for (i = 0; i < RX_RING_SIZE; i++) { np->rx_ring[i].status = 0; np->rx_ring[i].control = np->rx_buf_sz << RBSShift; np->rx_ring[i].next_desc = np->rx_ring_dma + (i + 1)*sizeof(struct fealnx_desc); np->rx_ring[i].next_desc_logical = &np->rx_ring[i + 1]; np->rx_ring[i].skbuff = NULL; } /* for the last rx descriptor */ np->rx_ring[i - 1].next_desc = np->rx_ring_dma; np->rx_ring[i - 1].next_desc_logical = np->rx_ring; /* allocate skb for rx buffers */ for (i = 0; i < RX_RING_SIZE; i++) { struct sk_buff *skb = netdev_alloc_skb(dev, np->rx_buf_sz); if (skb == NULL) { np->lack_rxbuf = &np->rx_ring[i]; break; } ++np->really_rx_count; np->rx_ring[i].skbuff = skb; np->rx_ring[i].buffer = dma_map_single(&np->pci_dev->dev, skb->data, np->rx_buf_sz, DMA_FROM_DEVICE); np->rx_ring[i].status = RXOWN; np->rx_ring[i].control |= RXIC; } /* initialize tx variables */ np->cur_tx = &np->tx_ring[0]; np->cur_tx_copy = &np->tx_ring[0]; np->really_tx_count = 0; np->free_tx_count = TX_RING_SIZE; for (i = 0; i < TX_RING_SIZE; i++) { np->tx_ring[i].status = 0; /* do we need np->tx_ring[i].control = XXX; ?? */ np->tx_ring[i].next_desc = np->tx_ring_dma + (i + 1)*sizeof(struct fealnx_desc); np->tx_ring[i].next_desc_logical = &np->tx_ring[i + 1]; np->tx_ring[i].skbuff = NULL; } /* for the last tx descriptor */ np->tx_ring[i - 1].next_desc = np->tx_ring_dma; np->tx_ring[i - 1].next_desc_logical = &np->tx_ring[0]; } static netdev_tx_t start_tx(struct sk_buff *skb, struct net_device *dev) { struct netdev_private *np = netdev_priv(dev); unsigned long flags; spin_lock_irqsave(&np->lock, flags); np->cur_tx_copy->skbuff = skb; #define one_buffer #define BPT 1022 #if defined(one_buffer) np->cur_tx_copy->buffer = dma_map_single(&np->pci_dev->dev, skb->data, skb->len, DMA_TO_DEVICE); np->cur_tx_copy->control = TXIC | TXLD | TXFD | CRCEnable | PADEnable; np->cur_tx_copy->control |= (skb->len << PKTSShift); /* pkt size */ np->cur_tx_copy->control |= (skb->len << TBSShift); /* buffer size */ // 89/12/29 add, if (np->pci_dev->device == 0x891) np->cur_tx_copy->control |= ETIControl | RetryTxLC; np->cur_tx_copy->status = TXOWN; np->cur_tx_copy = np->cur_tx_copy->next_desc_logical; --np->free_tx_count; #elif defined(two_buffer) if (skb->len > BPT) { struct fealnx_desc *next; /* for the first descriptor */ np->cur_tx_copy->buffer = dma_map_single(&np->pci_dev->dev, skb->data, BPT, DMA_TO_DEVICE); np->cur_tx_copy->control = TXIC | TXFD | CRCEnable | PADEnable; np->cur_tx_copy->control |= (skb->len << PKTSShift); /* pkt size */ np->cur_tx_copy->control |= (BPT << TBSShift); /* buffer size */ /* for the last descriptor */ next = np->cur_tx_copy->next_desc_logical; next->skbuff = skb; next->control = TXIC | TXLD | CRCEnable | PADEnable; next->control |= (skb->len << PKTSShift); /* pkt size */ next->control |= ((skb->len - BPT) << TBSShift); /* buf size */ // 89/12/29 add, if (np->pci_dev->device == 0x891) np->cur_tx_copy->control |= ETIControl | RetryTxLC; next->buffer = dma_map_single(&ep->pci_dev->dev, skb->data + BPT, skb->len - BPT, DMA_TO_DEVICE); next->status = TXOWN; np->cur_tx_copy->status = TXOWN; np->cur_tx_copy = next->next_desc_logical; np->free_tx_count -= 2; } else { np->cur_tx_copy->buffer = dma_map_single(&np->pci_dev->dev, skb->data, skb->len, DMA_TO_DEVICE); np->cur_tx_copy->control = TXIC | TXLD | TXFD | CRCEnable | PADEnable; np->cur_tx_copy->control |= (skb->len << PKTSShift); /* pkt size */ np->cur_tx_copy->control |= (skb->len << TBSShift); /* buffer size */ // 89/12/29 add, if (np->pci_dev->device == 0x891) np->cur_tx_copy->control |= ETIControl | RetryTxLC; np->cur_tx_copy->status = TXOWN; np->cur_tx_copy = np->cur_tx_copy->next_desc_logical; --np->free_tx_count; } #endif if (np->free_tx_count < 2) netif_stop_queue(dev); ++np->really_tx_count; iowrite32(0, np->mem + TXPDR); spin_unlock_irqrestore(&np->lock, flags); return NETDEV_TX_OK; } /* Take lock before calling */ /* Chip probably hosed tx ring. Clean up. */ static void reset_tx_descriptors(struct net_device *dev) { struct netdev_private *np = netdev_priv(dev); struct fealnx_desc *cur; int i; /* initialize tx variables */ np->cur_tx = &np->tx_ring[0]; np->cur_tx_copy = &np->tx_ring[0]; np->really_tx_count = 0; np->free_tx_count = TX_RING_SIZE; for (i = 0; i < TX_RING_SIZE; i++) { cur = &np->tx_ring[i]; if (cur->skbuff) { dma_unmap_single(&np->pci_dev->dev, cur->buffer, cur->skbuff->len, DMA_TO_DEVICE); dev_kfree_skb_any(cur->skbuff); cur->skbuff = NULL; } cur->status = 0; cur->control = 0; /* needed? */ /* probably not needed. We do it for purely paranoid reasons */ cur->next_desc = np->tx_ring_dma + (i + 1)*sizeof(struct fealnx_desc); cur->next_desc_logical = &np->tx_ring[i + 1]; } /* for the last tx descriptor */ np->tx_ring[TX_RING_SIZE - 1].next_desc = np->tx_ring_dma; np->tx_ring[TX_RING_SIZE - 1].next_desc_logical = &np->tx_ring[0]; } /* Take lock and stop rx before calling this */ static void reset_rx_descriptors(struct net_device *dev) { struct netdev_private *np = netdev_priv(dev); struct fealnx_desc *cur = np->cur_rx; int i; allocate_rx_buffers(dev); for (i = 0; i < RX_RING_SIZE; i++) { if (cur->skbuff) cur->status = RXOWN; cur = cur->next_desc_logical; } iowrite32(np->rx_ring_dma + ((char*)np->cur_rx - (char*)np->rx_ring), np->mem + RXLBA); } /* The interrupt handler does all of the Rx thread work and cleans up after the Tx thread. */ static irqreturn_t intr_handler(int irq, void *dev_instance) { struct net_device *dev = (struct net_device *) dev_instance; struct netdev_private *np = netdev_priv(dev); void __iomem *ioaddr = np->mem; long boguscnt = max_interrupt_work; unsigned int num_tx = 0; int handled = 0; spin_lock(&np->lock); iowrite32(0, ioaddr + IMR); do { u32 intr_status = ioread32(ioaddr + ISR); /* Acknowledge all of the current interrupt sources ASAP. */ iowrite32(intr_status, ioaddr + ISR); if (debug) printk(KERN_DEBUG "%s: Interrupt, status %4.4x.\n", dev->name, intr_status); if (!(intr_status & np->imrvalue)) break; handled = 1; // 90/1/16 delete, // // if (intr_status & FBE) // { /* fatal error */ // stop_nic_tx(ioaddr, 0); // stop_nic_rx(ioaddr, 0); // break; // }; if (intr_status & TUNF) iowrite32(0, ioaddr + TXPDR); if (intr_status & CNTOVF) { /* missed pkts */ dev->stats.rx_missed_errors += ioread32(ioaddr + TALLY) & 0x7fff; /* crc error */ dev->stats.rx_crc_errors += (ioread32(ioaddr + TALLY) & 0x7fff0000) >> 16; } if (intr_status & (RI | RBU)) { if (intr_status & RI) netdev_rx(dev); else { stop_nic_rx(ioaddr, np->crvalue); reset_rx_descriptors(dev); iowrite32(np->crvalue, ioaddr + TCRRCR); } } while (np->really_tx_count) { long tx_status = np->cur_tx->status; long tx_control = np->cur_tx->control; if (!(tx_control & TXLD)) { /* this pkt is combined by two tx descriptors */ struct fealnx_desc *next; next = np->cur_tx->next_desc_logical; tx_status = next->status; tx_control = next->control; } if (tx_status & TXOWN) break; if (!(np->crvalue & CR_W_ENH)) { if (tx_status & (CSL | LC | EC | UDF | HF)) { dev->stats.tx_errors++; if (tx_status & EC) dev->stats.tx_aborted_errors++; if (tx_status & CSL) dev->stats.tx_carrier_errors++; if (tx_status & LC) dev->stats.tx_window_errors++; if (tx_status & UDF) dev->stats.tx_fifo_errors++; if ((tx_status & HF) && np->mii.full_duplex == 0) dev->stats.tx_heartbeat_errors++; } else { dev->stats.tx_bytes += ((tx_control & PKTSMask) >> PKTSShift); dev->stats.collisions += ((tx_status & NCRMask) >> NCRShift); dev->stats.tx_packets++; } } else { dev->stats.tx_bytes += ((tx_control & PKTSMask) >> PKTSShift); dev->stats.tx_packets++; } /* Free the original skb. */ dma_unmap_single(&np->pci_dev->dev, np->cur_tx->buffer, np->cur_tx->skbuff->len, DMA_TO_DEVICE); dev_consume_skb_irq(np->cur_tx->skbuff); np->cur_tx->skbuff = NULL; --np->really_tx_count; if (np->cur_tx->control & TXLD) { np->cur_tx = np->cur_tx->next_desc_logical; ++np->free_tx_count; } else { np->cur_tx = np->cur_tx->next_desc_logical; np->cur_tx = np->cur_tx->next_desc_logical; np->free_tx_count += 2; } num_tx++; } /* end of for loop */ if (num_tx && np->free_tx_count >= 2) netif_wake_queue(dev); /* read transmit status for enhanced mode only */ if (np->crvalue & CR_W_ENH) { long data; data = ioread32(ioaddr + TSR); dev->stats.tx_errors += (data & 0xff000000) >> 24; dev->stats.tx_aborted_errors += (data & 0xff000000) >> 24; dev->stats.tx_window_errors += (data & 0x00ff0000) >> 16; dev->stats.collisions += (data & 0x0000ffff); } if (--boguscnt < 0) { printk(KERN_WARNING "%s: Too much work at interrupt, " "status=0x%4.4x.\n", dev->name, intr_status); if (!np->reset_timer_armed) { np->reset_timer_armed = 1; np->reset_timer.expires = RUN_AT(HZ/2); add_timer(&np->reset_timer); stop_nic_rxtx(ioaddr, 0); netif_stop_queue(dev); /* or netif_tx_disable(dev); ?? */ /* Prevent other paths from enabling tx,rx,intrs */ np->crvalue_sv = np->crvalue; np->imrvalue_sv = np->imrvalue; np->crvalue &= ~(CR_W_TXEN | CR_W_RXEN); /* or simply = 0? */ np->imrvalue = 0; } break; } } while (1); /* read the tally counters */ /* missed pkts */ dev->stats.rx_missed_errors += ioread32(ioaddr + TALLY) & 0x7fff; /* crc error */ dev->stats.rx_crc_errors += (ioread32(ioaddr + TALLY) & 0x7fff0000) >> 16; if (debug) printk(KERN_DEBUG "%s: exiting interrupt, status=%#4.4x.\n", dev->name, ioread32(ioaddr + ISR)); iowrite32(np->imrvalue, ioaddr + IMR); spin_unlock(&np->lock); return IRQ_RETVAL(handled); } /* This routine is logically part of the interrupt handler, but separated for clarity and better register allocation. */ static int netdev_rx(struct net_device *dev) { struct netdev_private *np = netdev_priv(dev); void __iomem *ioaddr = np->mem; /* If EOP is set on the next entry, it's a new packet. Send it up. */ while (!(np->cur_rx->status & RXOWN) && np->cur_rx->skbuff) { s32 rx_status = np->cur_rx->status; if (np->really_rx_count == 0) break; if (debug) printk(KERN_DEBUG " netdev_rx() status was %8.8x.\n", rx_status); if ((!((rx_status & RXFSD) && (rx_status & RXLSD))) || (rx_status & ErrorSummary)) { if (rx_status & ErrorSummary) { /* there was a fatal error */ if (debug) printk(KERN_DEBUG "%s: Receive error, Rx status %8.8x.\n", dev->name, rx_status); dev->stats.rx_errors++; /* end of a packet. */ if (rx_status & (LONGPKT | RUNTPKT)) dev->stats.rx_length_errors++; if (rx_status & RXER) dev->stats.rx_frame_errors++; if (rx_status & CRC) dev->stats.rx_crc_errors++; } else { int need_to_reset = 0; int desno = 0; if (rx_status & RXFSD) { /* this pkt is too long, over one rx buffer */ struct fealnx_desc *cur; /* check this packet is received completely? */ cur = np->cur_rx; while (desno <= np->really_rx_count) { ++desno; if ((!(cur->status & RXOWN)) && (cur->status & RXLSD)) break; /* goto next rx descriptor */ cur = cur->next_desc_logical; } if (desno > np->really_rx_count) need_to_reset = 1; } else /* RXLSD did not find, something error */ need_to_reset = 1; if (need_to_reset == 0) { int i; dev->stats.rx_length_errors++; /* free all rx descriptors related this long pkt */ for (i = 0; i < desno; ++i) { if (!np->cur_rx->skbuff) { printk(KERN_DEBUG "%s: I'm scared\n", dev->name); break; } np->cur_rx->status = RXOWN; np->cur_rx = np->cur_rx->next_desc_logical; } continue; } else { /* rx error, need to reset this chip */ stop_nic_rx(ioaddr, np->crvalue); reset_rx_descriptors(dev); iowrite32(np->crvalue, ioaddr + TCRRCR); } break; /* exit the while loop */ } } else { /* this received pkt is ok */ struct sk_buff *skb; /* Omit the four octet CRC from the length. */ short pkt_len = ((rx_status & FLNGMASK) >> FLNGShift) - 4; #ifndef final_version if (debug) printk(KERN_DEBUG " netdev_rx() normal Rx pkt length %d" " status %x.\n", pkt_len, rx_status); #endif /* Check if the packet is long enough to accept without copying to a minimally-sized skbuff. */ if (pkt_len < rx_copybreak && (skb = netdev_alloc_skb(dev, pkt_len + 2)) != NULL) { skb_reserve(skb, 2); /* 16 byte align the IP header */ dma_sync_single_for_cpu(&np->pci_dev->dev, np->cur_rx->buffer, np->rx_buf_sz, DMA_FROM_DEVICE); /* Call copy + cksum if available. */ #if ! defined(__alpha__) skb_copy_to_linear_data(skb, np->cur_rx->skbuff->data, pkt_len); skb_put(skb, pkt_len); #else skb_put_data(skb, np->cur_rx->skbuff->data, pkt_len); #endif dma_sync_single_for_device(&np->pci_dev->dev, np->cur_rx->buffer, np->rx_buf_sz, DMA_FROM_DEVICE); } else { dma_unmap_single(&np->pci_dev->dev, np->cur_rx->buffer, np->rx_buf_sz, DMA_FROM_DEVICE); skb_put(skb = np->cur_rx->skbuff, pkt_len); np->cur_rx->skbuff = NULL; --np->really_rx_count; } skb->protocol = eth_type_trans(skb, dev); netif_rx(skb); dev->stats.rx_packets++; dev->stats.rx_bytes += pkt_len; } np->cur_rx = np->cur_rx->next_desc_logical; } /* end of while loop */ /* allocate skb for rx buffers */ allocate_rx_buffers(dev); return 0; } static struct net_device_stats *get_stats(struct net_device *dev) { struct netdev_private *np = netdev_priv(dev); void __iomem *ioaddr = np->mem; /* The chip only need report frame silently dropped. */ if (netif_running(dev)) { dev->stats.rx_missed_errors += ioread32(ioaddr + TALLY) & 0x7fff; dev->stats.rx_crc_errors += (ioread32(ioaddr + TALLY) & 0x7fff0000) >> 16; } return &dev->stats; } /* for dev->set_multicast_list */ static void set_rx_mode(struct net_device *dev) { spinlock_t *lp = &((struct netdev_private *)netdev_priv(dev))->lock; unsigned long flags; spin_lock_irqsave(lp, flags); __set_rx_mode(dev); spin_unlock_irqrestore(lp, flags); } /* Take lock before calling */ static void __set_rx_mode(struct net_device *dev) { struct netdev_private *np = netdev_priv(dev); void __iomem *ioaddr = np->mem; u32 mc_filter[2]; /* Multicast hash filter */ u32 rx_mode; if (dev->flags & IFF_PROMISC) { /* Set promiscuous. */ memset(mc_filter, 0xff, sizeof(mc_filter)); rx_mode = CR_W_PROM | CR_W_AB | CR_W_AM; } else if ((netdev_mc_count(dev) > multicast_filter_limit) || (dev->flags & IFF_ALLMULTI)) { /* Too many to match, or accept all multicasts. */ memset(mc_filter, 0xff, sizeof(mc_filter)); rx_mode = CR_W_AB | CR_W_AM; } else { struct netdev_hw_addr *ha; memset(mc_filter, 0, sizeof(mc_filter)); netdev_for_each_mc_addr(ha, dev) { unsigned int bit; bit = (ether_crc(ETH_ALEN, ha->addr) >> 26) ^ 0x3F; mc_filter[bit >> 5] |= (1 << bit); } rx_mode = CR_W_AB | CR_W_AM; } stop_nic_rxtx(ioaddr, np->crvalue); iowrite32(mc_filter[0], ioaddr + MAR0); iowrite32(mc_filter[1], ioaddr + MAR1); np->crvalue &= ~CR_W_RXMODEMASK; np->crvalue |= rx_mode; iowrite32(np->crvalue, ioaddr + TCRRCR); } static void netdev_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { struct netdev_private *np = netdev_priv(dev); strscpy(info->driver, DRV_NAME, sizeof(info->driver)); strscpy(info->bus_info, pci_name(np->pci_dev), sizeof(info->bus_info)); } static int netdev_get_link_ksettings(struct net_device *dev, struct ethtool_link_ksettings *cmd) { struct netdev_private *np = netdev_priv(dev); spin_lock_irq(&np->lock); mii_ethtool_get_link_ksettings(&np->mii, cmd); spin_unlock_irq(&np->lock); return 0; } static int netdev_set_link_ksettings(struct net_device *dev, const struct ethtool_link_ksettings *cmd) { struct netdev_private *np = netdev_priv(dev); int rc; spin_lock_irq(&np->lock); rc = mii_ethtool_set_link_ksettings(&np->mii, cmd); spin_unlock_irq(&np->lock); return rc; } static int netdev_nway_reset(struct net_device *dev) { struct netdev_private *np = netdev_priv(dev); return mii_nway_restart(&np->mii); } static u32 netdev_get_link(struct net_device *dev) { struct netdev_private *np = netdev_priv(dev); return mii_link_ok(&np->mii); } static u32 netdev_get_msglevel(struct net_device *dev) { return debug; } static void netdev_set_msglevel(struct net_device *dev, u32 value) { debug = value; } static const struct ethtool_ops netdev_ethtool_ops = { .get_drvinfo = netdev_get_drvinfo, .nway_reset = netdev_nway_reset, .get_link = netdev_get_link, .get_msglevel = netdev_get_msglevel, .set_msglevel = netdev_set_msglevel, .get_link_ksettings = netdev_get_link_ksettings, .set_link_ksettings = netdev_set_link_ksettings, }; static int mii_ioctl(struct net_device *dev, struct ifreq *rq, int cmd) { struct netdev_private *np = netdev_priv(dev); int rc; if (!netif_running(dev)) return -EINVAL; spin_lock_irq(&np->lock); rc = generic_mii_ioctl(&np->mii, if_mii(rq), cmd, NULL); spin_unlock_irq(&np->lock); return rc; } static int netdev_close(struct net_device *dev) { struct netdev_private *np = netdev_priv(dev); void __iomem *ioaddr = np->mem; int i; netif_stop_queue(dev); /* Disable interrupts by clearing the interrupt mask. */ iowrite32(0x0000, ioaddr + IMR); /* Stop the chip's Tx and Rx processes. */ stop_nic_rxtx(ioaddr, 0); del_timer_sync(&np->timer); del_timer_sync(&np->reset_timer); free_irq(np->pci_dev->irq, dev); /* Free all the skbuffs in the Rx queue. */ for (i = 0; i < RX_RING_SIZE; i++) { struct sk_buff *skb = np->rx_ring[i].skbuff; np->rx_ring[i].status = 0; if (skb) { dma_unmap_single(&np->pci_dev->dev, np->rx_ring[i].buffer, np->rx_buf_sz, DMA_FROM_DEVICE); dev_kfree_skb(skb); np->rx_ring[i].skbuff = NULL; } } for (i = 0; i < TX_RING_SIZE; i++) { struct sk_buff *skb = np->tx_ring[i].skbuff; if (skb) { dma_unmap_single(&np->pci_dev->dev, np->tx_ring[i].buffer, skb->len, DMA_TO_DEVICE); dev_kfree_skb(skb); np->tx_ring[i].skbuff = NULL; } } return 0; } static const struct pci_device_id fealnx_pci_tbl[] = { {0x1516, 0x0800, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {0x1516, 0x0803, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 1}, {0x1516, 0x0891, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 2}, {} /* terminate list */ }; MODULE_DEVICE_TABLE(pci, fealnx_pci_tbl); static struct pci_driver fealnx_driver = { .name = "fealnx", .id_table = fealnx_pci_tbl, .probe = fealnx_init_one, .remove = fealnx_remove_one, }; module_pci_driver(fealnx_driver);
linux-master
drivers/net/ethernet/fealnx.c
// SPDX-License-Identifier: GPL-2.0-only /* * linux/drivers/net/ethernet/ethoc.c * * Copyright (C) 2007-2008 Avionic Design Development GmbH * Copyright (C) 2008-2009 Avionic Design GmbH * * Written by Thierry Reding <[email protected]> */ #include <linux/dma-mapping.h> #include <linux/etherdevice.h> #include <linux/clk.h> #include <linux/crc32.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/mii.h> #include <linux/phy.h> #include <linux/platform_device.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/of.h> #include <linux/of_net.h> #include <linux/module.h> #include <net/ethoc.h> static int buffer_size = 0x8000; /* 32 KBytes */ module_param(buffer_size, int, 0); MODULE_PARM_DESC(buffer_size, "DMA buffer allocation size"); /* register offsets */ #define MODER 0x00 #define INT_SOURCE 0x04 #define INT_MASK 0x08 #define IPGT 0x0c #define IPGR1 0x10 #define IPGR2 0x14 #define PACKETLEN 0x18 #define COLLCONF 0x1c #define TX_BD_NUM 0x20 #define CTRLMODER 0x24 #define MIIMODER 0x28 #define MIICOMMAND 0x2c #define MIIADDRESS 0x30 #define MIITX_DATA 0x34 #define MIIRX_DATA 0x38 #define MIISTATUS 0x3c #define MAC_ADDR0 0x40 #define MAC_ADDR1 0x44 #define ETH_HASH0 0x48 #define ETH_HASH1 0x4c #define ETH_TXCTRL 0x50 #define ETH_END 0x54 /* mode register */ #define MODER_RXEN (1 << 0) /* receive enable */ #define MODER_TXEN (1 << 1) /* transmit enable */ #define MODER_NOPRE (1 << 2) /* no preamble */ #define MODER_BRO (1 << 3) /* broadcast address */ #define MODER_IAM (1 << 4) /* individual address mode */ #define MODER_PRO (1 << 5) /* promiscuous mode */ #define MODER_IFG (1 << 6) /* interframe gap for incoming frames */ #define MODER_LOOP (1 << 7) /* loopback */ #define MODER_NBO (1 << 8) /* no back-off */ #define MODER_EDE (1 << 9) /* excess defer enable */ #define MODER_FULLD (1 << 10) /* full duplex */ #define MODER_RESET (1 << 11) /* FIXME: reset (undocumented) */ #define MODER_DCRC (1 << 12) /* delayed CRC enable */ #define MODER_CRC (1 << 13) /* CRC enable */ #define MODER_HUGE (1 << 14) /* huge packets enable */ #define MODER_PAD (1 << 15) /* padding enabled */ #define MODER_RSM (1 << 16) /* receive small packets */ /* interrupt source and mask registers */ #define INT_MASK_TXF (1 << 0) /* transmit frame */ #define INT_MASK_TXE (1 << 1) /* transmit error */ #define INT_MASK_RXF (1 << 2) /* receive frame */ #define INT_MASK_RXE (1 << 3) /* receive error */ #define INT_MASK_BUSY (1 << 4) #define INT_MASK_TXC (1 << 5) /* transmit control frame */ #define INT_MASK_RXC (1 << 6) /* receive control frame */ #define INT_MASK_TX (INT_MASK_TXF | INT_MASK_TXE) #define INT_MASK_RX (INT_MASK_RXF | INT_MASK_RXE) #define INT_MASK_ALL ( \ INT_MASK_TXF | INT_MASK_TXE | \ INT_MASK_RXF | INT_MASK_RXE | \ INT_MASK_TXC | INT_MASK_RXC | \ INT_MASK_BUSY \ ) /* packet length register */ #define PACKETLEN_MIN(min) (((min) & 0xffff) << 16) #define PACKETLEN_MAX(max) (((max) & 0xffff) << 0) #define PACKETLEN_MIN_MAX(min, max) (PACKETLEN_MIN(min) | \ PACKETLEN_MAX(max)) /* transmit buffer number register */ #define TX_BD_NUM_VAL(x) (((x) <= 0x80) ? (x) : 0x80) /* control module mode register */ #define CTRLMODER_PASSALL (1 << 0) /* pass all receive frames */ #define CTRLMODER_RXFLOW (1 << 1) /* receive control flow */ #define CTRLMODER_TXFLOW (1 << 2) /* transmit control flow */ /* MII mode register */ #define MIIMODER_CLKDIV(x) ((x) & 0xfe) /* needs to be an even number */ #define MIIMODER_NOPRE (1 << 8) /* no preamble */ /* MII command register */ #define MIICOMMAND_SCAN (1 << 0) /* scan status */ #define MIICOMMAND_READ (1 << 1) /* read status */ #define MIICOMMAND_WRITE (1 << 2) /* write control data */ /* MII address register */ #define MIIADDRESS_FIAD(x) (((x) & 0x1f) << 0) #define MIIADDRESS_RGAD(x) (((x) & 0x1f) << 8) #define MIIADDRESS_ADDR(phy, reg) (MIIADDRESS_FIAD(phy) | \ MIIADDRESS_RGAD(reg)) /* MII transmit data register */ #define MIITX_DATA_VAL(x) ((x) & 0xffff) /* MII receive data register */ #define MIIRX_DATA_VAL(x) ((x) & 0xffff) /* MII status register */ #define MIISTATUS_LINKFAIL (1 << 0) #define MIISTATUS_BUSY (1 << 1) #define MIISTATUS_INVALID (1 << 2) /* TX buffer descriptor */ #define TX_BD_CS (1 << 0) /* carrier sense lost */ #define TX_BD_DF (1 << 1) /* defer indication */ #define TX_BD_LC (1 << 2) /* late collision */ #define TX_BD_RL (1 << 3) /* retransmission limit */ #define TX_BD_RETRY_MASK (0x00f0) #define TX_BD_RETRY(x) (((x) & 0x00f0) >> 4) #define TX_BD_UR (1 << 8) /* transmitter underrun */ #define TX_BD_CRC (1 << 11) /* TX CRC enable */ #define TX_BD_PAD (1 << 12) /* pad enable for short packets */ #define TX_BD_WRAP (1 << 13) #define TX_BD_IRQ (1 << 14) /* interrupt request enable */ #define TX_BD_READY (1 << 15) /* TX buffer ready */ #define TX_BD_LEN(x) (((x) & 0xffff) << 16) #define TX_BD_LEN_MASK (0xffff << 16) #define TX_BD_STATS (TX_BD_CS | TX_BD_DF | TX_BD_LC | \ TX_BD_RL | TX_BD_RETRY_MASK | TX_BD_UR) /* RX buffer descriptor */ #define RX_BD_LC (1 << 0) /* late collision */ #define RX_BD_CRC (1 << 1) /* RX CRC error */ #define RX_BD_SF (1 << 2) /* short frame */ #define RX_BD_TL (1 << 3) /* too long */ #define RX_BD_DN (1 << 4) /* dribble nibble */ #define RX_BD_IS (1 << 5) /* invalid symbol */ #define RX_BD_OR (1 << 6) /* receiver overrun */ #define RX_BD_MISS (1 << 7) #define RX_BD_CF (1 << 8) /* control frame */ #define RX_BD_WRAP (1 << 13) #define RX_BD_IRQ (1 << 14) /* interrupt request enable */ #define RX_BD_EMPTY (1 << 15) #define RX_BD_LEN(x) (((x) & 0xffff) << 16) #define RX_BD_STATS (RX_BD_LC | RX_BD_CRC | RX_BD_SF | RX_BD_TL | \ RX_BD_DN | RX_BD_IS | RX_BD_OR | RX_BD_MISS) #define ETHOC_BUFSIZ 1536 #define ETHOC_ZLEN 64 #define ETHOC_BD_BASE 0x400 #define ETHOC_TIMEOUT (HZ / 2) #define ETHOC_MII_TIMEOUT (1 + (HZ / 5)) /** * struct ethoc - driver-private device structure * @iobase: pointer to I/O memory region * @membase: pointer to buffer memory region * @big_endian: just big or little (endian) * @num_bd: number of buffer descriptors * @num_tx: number of send buffers * @cur_tx: last send buffer written * @dty_tx: last buffer actually sent * @num_rx: number of receive buffers * @cur_rx: current receive buffer * @vma: pointer to array of virtual memory addresses for buffers * @netdev: pointer to network device structure * @napi: NAPI structure * @msg_enable: device state flags * @lock: device lock * @mdio: MDIO bus for PHY access * @clk: clock * @phy_id: address of attached PHY * @old_link: previous link info * @old_duplex: previous duplex info */ struct ethoc { void __iomem *iobase; void __iomem *membase; bool big_endian; unsigned int num_bd; unsigned int num_tx; unsigned int cur_tx; unsigned int dty_tx; unsigned int num_rx; unsigned int cur_rx; void **vma; struct net_device *netdev; struct napi_struct napi; u32 msg_enable; spinlock_t lock; struct mii_bus *mdio; struct clk *clk; s8 phy_id; int old_link; int old_duplex; }; /** * struct ethoc_bd - buffer descriptor * @stat: buffer statistics * @addr: physical memory address */ struct ethoc_bd { u32 stat; u32 addr; }; static inline u32 ethoc_read(struct ethoc *dev, loff_t offset) { if (dev->big_endian) return ioread32be(dev->iobase + offset); else return ioread32(dev->iobase + offset); } static inline void ethoc_write(struct ethoc *dev, loff_t offset, u32 data) { if (dev->big_endian) iowrite32be(data, dev->iobase + offset); else iowrite32(data, dev->iobase + offset); } static inline void ethoc_read_bd(struct ethoc *dev, int index, struct ethoc_bd *bd) { loff_t offset = ETHOC_BD_BASE + (index * sizeof(struct ethoc_bd)); bd->stat = ethoc_read(dev, offset + 0); bd->addr = ethoc_read(dev, offset + 4); } static inline void ethoc_write_bd(struct ethoc *dev, int index, const struct ethoc_bd *bd) { loff_t offset = ETHOC_BD_BASE + (index * sizeof(struct ethoc_bd)); ethoc_write(dev, offset + 0, bd->stat); ethoc_write(dev, offset + 4, bd->addr); } static inline void ethoc_enable_irq(struct ethoc *dev, u32 mask) { u32 imask = ethoc_read(dev, INT_MASK); imask |= mask; ethoc_write(dev, INT_MASK, imask); } static inline void ethoc_disable_irq(struct ethoc *dev, u32 mask) { u32 imask = ethoc_read(dev, INT_MASK); imask &= ~mask; ethoc_write(dev, INT_MASK, imask); } static inline void ethoc_ack_irq(struct ethoc *dev, u32 mask) { ethoc_write(dev, INT_SOURCE, mask); } static inline void ethoc_enable_rx_and_tx(struct ethoc *dev) { u32 mode = ethoc_read(dev, MODER); mode |= MODER_RXEN | MODER_TXEN; ethoc_write(dev, MODER, mode); } static inline void ethoc_disable_rx_and_tx(struct ethoc *dev) { u32 mode = ethoc_read(dev, MODER); mode &= ~(MODER_RXEN | MODER_TXEN); ethoc_write(dev, MODER, mode); } static int ethoc_init_ring(struct ethoc *dev, unsigned long mem_start) { struct ethoc_bd bd; int i; void *vma; dev->cur_tx = 0; dev->dty_tx = 0; dev->cur_rx = 0; ethoc_write(dev, TX_BD_NUM, dev->num_tx); /* setup transmission buffers */ bd.addr = mem_start; bd.stat = TX_BD_IRQ | TX_BD_CRC; vma = dev->membase; for (i = 0; i < dev->num_tx; i++) { if (i == dev->num_tx - 1) bd.stat |= TX_BD_WRAP; ethoc_write_bd(dev, i, &bd); bd.addr += ETHOC_BUFSIZ; dev->vma[i] = vma; vma += ETHOC_BUFSIZ; } bd.stat = RX_BD_EMPTY | RX_BD_IRQ; for (i = 0; i < dev->num_rx; i++) { if (i == dev->num_rx - 1) bd.stat |= RX_BD_WRAP; ethoc_write_bd(dev, dev->num_tx + i, &bd); bd.addr += ETHOC_BUFSIZ; dev->vma[dev->num_tx + i] = vma; vma += ETHOC_BUFSIZ; } return 0; } static int ethoc_reset(struct ethoc *dev) { u32 mode; /* TODO: reset controller? */ ethoc_disable_rx_and_tx(dev); /* TODO: setup registers */ /* enable FCS generation and automatic padding */ mode = ethoc_read(dev, MODER); mode |= MODER_CRC | MODER_PAD; ethoc_write(dev, MODER, mode); /* set full-duplex mode */ mode = ethoc_read(dev, MODER); mode |= MODER_FULLD; ethoc_write(dev, MODER, mode); ethoc_write(dev, IPGT, 0x15); ethoc_ack_irq(dev, INT_MASK_ALL); ethoc_enable_irq(dev, INT_MASK_ALL); ethoc_enable_rx_and_tx(dev); return 0; } static unsigned int ethoc_update_rx_stats(struct ethoc *dev, struct ethoc_bd *bd) { struct net_device *netdev = dev->netdev; unsigned int ret = 0; if (bd->stat & RX_BD_TL) { dev_err(&netdev->dev, "RX: frame too long\n"); netdev->stats.rx_length_errors++; ret++; } if (bd->stat & RX_BD_SF) { dev_err(&netdev->dev, "RX: frame too short\n"); netdev->stats.rx_length_errors++; ret++; } if (bd->stat & RX_BD_DN) { dev_err(&netdev->dev, "RX: dribble nibble\n"); netdev->stats.rx_frame_errors++; } if (bd->stat & RX_BD_CRC) { dev_err(&netdev->dev, "RX: wrong CRC\n"); netdev->stats.rx_crc_errors++; ret++; } if (bd->stat & RX_BD_OR) { dev_err(&netdev->dev, "RX: overrun\n"); netdev->stats.rx_over_errors++; ret++; } if (bd->stat & RX_BD_MISS) netdev->stats.rx_missed_errors++; if (bd->stat & RX_BD_LC) { dev_err(&netdev->dev, "RX: late collision\n"); netdev->stats.collisions++; ret++; } return ret; } static int ethoc_rx(struct net_device *dev, int limit) { struct ethoc *priv = netdev_priv(dev); int count; for (count = 0; count < limit; ++count) { unsigned int entry; struct ethoc_bd bd; entry = priv->num_tx + priv->cur_rx; ethoc_read_bd(priv, entry, &bd); if (bd.stat & RX_BD_EMPTY) { ethoc_ack_irq(priv, INT_MASK_RX); /* If packet (interrupt) came in between checking * BD_EMTPY and clearing the interrupt source, then we * risk missing the packet as the RX interrupt won't * trigger right away when we reenable it; hence, check * BD_EMTPY here again to make sure there isn't such a * packet waiting for us... */ ethoc_read_bd(priv, entry, &bd); if (bd.stat & RX_BD_EMPTY) break; } if (ethoc_update_rx_stats(priv, &bd) == 0) { int size = bd.stat >> 16; struct sk_buff *skb; size -= 4; /* strip the CRC */ skb = netdev_alloc_skb_ip_align(dev, size); if (likely(skb)) { void *src = priv->vma[entry]; memcpy_fromio(skb_put(skb, size), src, size); skb->protocol = eth_type_trans(skb, dev); dev->stats.rx_packets++; dev->stats.rx_bytes += size; netif_receive_skb(skb); } else { if (net_ratelimit()) dev_warn(&dev->dev, "low on memory - packet dropped\n"); dev->stats.rx_dropped++; break; } } /* clear the buffer descriptor so it can be reused */ bd.stat &= ~RX_BD_STATS; bd.stat |= RX_BD_EMPTY; ethoc_write_bd(priv, entry, &bd); if (++priv->cur_rx == priv->num_rx) priv->cur_rx = 0; } return count; } static void ethoc_update_tx_stats(struct ethoc *dev, struct ethoc_bd *bd) { struct net_device *netdev = dev->netdev; if (bd->stat & TX_BD_LC) { dev_err(&netdev->dev, "TX: late collision\n"); netdev->stats.tx_window_errors++; } if (bd->stat & TX_BD_RL) { dev_err(&netdev->dev, "TX: retransmit limit\n"); netdev->stats.tx_aborted_errors++; } if (bd->stat & TX_BD_UR) { dev_err(&netdev->dev, "TX: underrun\n"); netdev->stats.tx_fifo_errors++; } if (bd->stat & TX_BD_CS) { dev_err(&netdev->dev, "TX: carrier sense lost\n"); netdev->stats.tx_carrier_errors++; } if (bd->stat & TX_BD_STATS) netdev->stats.tx_errors++; netdev->stats.collisions += (bd->stat >> 4) & 0xf; netdev->stats.tx_bytes += bd->stat >> 16; netdev->stats.tx_packets++; } static int ethoc_tx(struct net_device *dev, int limit) { struct ethoc *priv = netdev_priv(dev); int count; struct ethoc_bd bd; for (count = 0; count < limit; ++count) { unsigned int entry; entry = priv->dty_tx & (priv->num_tx-1); ethoc_read_bd(priv, entry, &bd); if (bd.stat & TX_BD_READY || (priv->dty_tx == priv->cur_tx)) { ethoc_ack_irq(priv, INT_MASK_TX); /* If interrupt came in between reading in the BD * and clearing the interrupt source, then we risk * missing the event as the TX interrupt won't trigger * right away when we reenable it; hence, check * BD_EMPTY here again to make sure there isn't such an * event pending... */ ethoc_read_bd(priv, entry, &bd); if (bd.stat & TX_BD_READY || (priv->dty_tx == priv->cur_tx)) break; } ethoc_update_tx_stats(priv, &bd); priv->dty_tx++; } if ((priv->cur_tx - priv->dty_tx) <= (priv->num_tx / 2)) netif_wake_queue(dev); return count; } static irqreturn_t ethoc_interrupt(int irq, void *dev_id) { struct net_device *dev = dev_id; struct ethoc *priv = netdev_priv(dev); u32 pending; u32 mask; /* Figure out what triggered the interrupt... * The tricky bit here is that the interrupt source bits get * set in INT_SOURCE for an event regardless of whether that * event is masked or not. Thus, in order to figure out what * triggered the interrupt, we need to remove the sources * for all events that are currently masked. This behaviour * is not particularly well documented but reasonable... */ mask = ethoc_read(priv, INT_MASK); pending = ethoc_read(priv, INT_SOURCE); pending &= mask; if (unlikely(pending == 0)) return IRQ_NONE; ethoc_ack_irq(priv, pending); /* We always handle the dropped packet interrupt */ if (pending & INT_MASK_BUSY) { dev_dbg(&dev->dev, "packet dropped\n"); dev->stats.rx_dropped++; } /* Handle receive/transmit event by switching to polling */ if (pending & (INT_MASK_TX | INT_MASK_RX)) { ethoc_disable_irq(priv, INT_MASK_TX | INT_MASK_RX); napi_schedule(&priv->napi); } return IRQ_HANDLED; } static int ethoc_get_mac_address(struct net_device *dev, void *addr) { struct ethoc *priv = netdev_priv(dev); u8 *mac = (u8 *)addr; u32 reg; reg = ethoc_read(priv, MAC_ADDR0); mac[2] = (reg >> 24) & 0xff; mac[3] = (reg >> 16) & 0xff; mac[4] = (reg >> 8) & 0xff; mac[5] = (reg >> 0) & 0xff; reg = ethoc_read(priv, MAC_ADDR1); mac[0] = (reg >> 8) & 0xff; mac[1] = (reg >> 0) & 0xff; return 0; } static int ethoc_poll(struct napi_struct *napi, int budget) { struct ethoc *priv = container_of(napi, struct ethoc, napi); int rx_work_done = 0; int tx_work_done = 0; rx_work_done = ethoc_rx(priv->netdev, budget); tx_work_done = ethoc_tx(priv->netdev, budget); if (rx_work_done < budget && tx_work_done < budget) { napi_complete_done(napi, rx_work_done); ethoc_enable_irq(priv, INT_MASK_TX | INT_MASK_RX); } return rx_work_done; } static int ethoc_mdio_read(struct mii_bus *bus, int phy, int reg) { struct ethoc *priv = bus->priv; int i; ethoc_write(priv, MIIADDRESS, MIIADDRESS_ADDR(phy, reg)); ethoc_write(priv, MIICOMMAND, MIICOMMAND_READ); for (i = 0; i < 5; i++) { u32 status = ethoc_read(priv, MIISTATUS); if (!(status & MIISTATUS_BUSY)) { u32 data = ethoc_read(priv, MIIRX_DATA); /* reset MII command register */ ethoc_write(priv, MIICOMMAND, 0); return data; } usleep_range(100, 200); } return -EBUSY; } static int ethoc_mdio_write(struct mii_bus *bus, int phy, int reg, u16 val) { struct ethoc *priv = bus->priv; int i; ethoc_write(priv, MIIADDRESS, MIIADDRESS_ADDR(phy, reg)); ethoc_write(priv, MIITX_DATA, val); ethoc_write(priv, MIICOMMAND, MIICOMMAND_WRITE); for (i = 0; i < 5; i++) { u32 stat = ethoc_read(priv, MIISTATUS); if (!(stat & MIISTATUS_BUSY)) { /* reset MII command register */ ethoc_write(priv, MIICOMMAND, 0); return 0; } usleep_range(100, 200); } return -EBUSY; } static void ethoc_mdio_poll(struct net_device *dev) { struct ethoc *priv = netdev_priv(dev); struct phy_device *phydev = dev->phydev; bool changed = false; u32 mode; if (priv->old_link != phydev->link) { changed = true; priv->old_link = phydev->link; } if (priv->old_duplex != phydev->duplex) { changed = true; priv->old_duplex = phydev->duplex; } if (!changed) return; mode = ethoc_read(priv, MODER); if (phydev->duplex == DUPLEX_FULL) mode |= MODER_FULLD; else mode &= ~MODER_FULLD; ethoc_write(priv, MODER, mode); phy_print_status(phydev); } static int ethoc_mdio_probe(struct net_device *dev) { struct ethoc *priv = netdev_priv(dev); struct phy_device *phy; int err; if (priv->phy_id != -1) phy = mdiobus_get_phy(priv->mdio, priv->phy_id); else phy = phy_find_first(priv->mdio); if (!phy) return dev_err_probe(&dev->dev, -ENXIO, "no PHY found\n"); priv->old_duplex = -1; priv->old_link = -1; err = phy_connect_direct(dev, phy, ethoc_mdio_poll, PHY_INTERFACE_MODE_GMII); if (err) return dev_err_probe(&dev->dev, err, "could not attach to PHY\n"); phy_set_max_speed(phy, SPEED_100); return 0; } static int ethoc_open(struct net_device *dev) { struct ethoc *priv = netdev_priv(dev); int ret; ret = request_irq(dev->irq, ethoc_interrupt, IRQF_SHARED, dev->name, dev); if (ret) return ret; napi_enable(&priv->napi); ethoc_init_ring(priv, dev->mem_start); ethoc_reset(priv); if (netif_queue_stopped(dev)) { dev_dbg(&dev->dev, " resuming queue\n"); netif_wake_queue(dev); } else { dev_dbg(&dev->dev, " starting queue\n"); netif_start_queue(dev); } priv->old_link = -1; priv->old_duplex = -1; phy_start(dev->phydev); if (netif_msg_ifup(priv)) { dev_info(&dev->dev, "I/O: %08lx Memory: %08lx-%08lx\n", dev->base_addr, dev->mem_start, dev->mem_end); } return 0; } static int ethoc_stop(struct net_device *dev) { struct ethoc *priv = netdev_priv(dev); napi_disable(&priv->napi); if (dev->phydev) phy_stop(dev->phydev); ethoc_disable_rx_and_tx(priv); free_irq(dev->irq, dev); if (!netif_queue_stopped(dev)) netif_stop_queue(dev); return 0; } static int ethoc_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { struct ethoc *priv = netdev_priv(dev); struct mii_ioctl_data *mdio = if_mii(ifr); struct phy_device *phy = NULL; if (!netif_running(dev)) return -EINVAL; if (cmd != SIOCGMIIPHY) { if (mdio->phy_id >= PHY_MAX_ADDR) return -ERANGE; phy = mdiobus_get_phy(priv->mdio, mdio->phy_id); if (!phy) return -ENODEV; } else { phy = dev->phydev; } return phy_mii_ioctl(phy, ifr, cmd); } static void ethoc_do_set_mac_address(struct net_device *dev) { const unsigned char *mac = dev->dev_addr; struct ethoc *priv = netdev_priv(dev); ethoc_write(priv, MAC_ADDR0, (mac[2] << 24) | (mac[3] << 16) | (mac[4] << 8) | (mac[5] << 0)); ethoc_write(priv, MAC_ADDR1, (mac[0] << 8) | (mac[1] << 0)); } static int ethoc_set_mac_address(struct net_device *dev, void *p) { const struct sockaddr *addr = p; if (!is_valid_ether_addr(addr->sa_data)) return -EADDRNOTAVAIL; eth_hw_addr_set(dev, addr->sa_data); ethoc_do_set_mac_address(dev); return 0; } static void ethoc_set_multicast_list(struct net_device *dev) { struct ethoc *priv = netdev_priv(dev); u32 mode = ethoc_read(priv, MODER); struct netdev_hw_addr *ha; u32 hash[2] = { 0, 0 }; /* set loopback mode if requested */ if (dev->flags & IFF_LOOPBACK) mode |= MODER_LOOP; else mode &= ~MODER_LOOP; /* receive broadcast frames if requested */ if (dev->flags & IFF_BROADCAST) mode &= ~MODER_BRO; else mode |= MODER_BRO; /* enable promiscuous mode if requested */ if (dev->flags & IFF_PROMISC) mode |= MODER_PRO; else mode &= ~MODER_PRO; ethoc_write(priv, MODER, mode); /* receive multicast frames */ if (dev->flags & IFF_ALLMULTI) { hash[0] = 0xffffffff; hash[1] = 0xffffffff; } else { netdev_for_each_mc_addr(ha, dev) { u32 crc = ether_crc(ETH_ALEN, ha->addr); int bit = (crc >> 26) & 0x3f; hash[bit >> 5] |= 1 << (bit & 0x1f); } } ethoc_write(priv, ETH_HASH0, hash[0]); ethoc_write(priv, ETH_HASH1, hash[1]); } static int ethoc_change_mtu(struct net_device *dev, int new_mtu) { return -ENOSYS; } static void ethoc_tx_timeout(struct net_device *dev, unsigned int txqueue) { struct ethoc *priv = netdev_priv(dev); u32 pending = ethoc_read(priv, INT_SOURCE); if (likely(pending)) ethoc_interrupt(dev->irq, dev); } static netdev_tx_t ethoc_start_xmit(struct sk_buff *skb, struct net_device *dev) { struct ethoc *priv = netdev_priv(dev); struct ethoc_bd bd; unsigned int entry; void *dest; if (skb_put_padto(skb, ETHOC_ZLEN)) { dev->stats.tx_errors++; goto out_no_free; } if (unlikely(skb->len > ETHOC_BUFSIZ)) { dev->stats.tx_errors++; goto out; } entry = priv->cur_tx % priv->num_tx; spin_lock_irq(&priv->lock); priv->cur_tx++; ethoc_read_bd(priv, entry, &bd); if (unlikely(skb->len < ETHOC_ZLEN)) bd.stat |= TX_BD_PAD; else bd.stat &= ~TX_BD_PAD; dest = priv->vma[entry]; memcpy_toio(dest, skb->data, skb->len); bd.stat &= ~(TX_BD_STATS | TX_BD_LEN_MASK); bd.stat |= TX_BD_LEN(skb->len); ethoc_write_bd(priv, entry, &bd); bd.stat |= TX_BD_READY; ethoc_write_bd(priv, entry, &bd); if (priv->cur_tx == (priv->dty_tx + priv->num_tx)) { dev_dbg(&dev->dev, "stopping queue\n"); netif_stop_queue(dev); } spin_unlock_irq(&priv->lock); skb_tx_timestamp(skb); out: dev_kfree_skb(skb); out_no_free: return NETDEV_TX_OK; } static int ethoc_get_regs_len(struct net_device *netdev) { return ETH_END; } static void ethoc_get_regs(struct net_device *dev, struct ethtool_regs *regs, void *p) { struct ethoc *priv = netdev_priv(dev); u32 *regs_buff = p; unsigned i; regs->version = 0; for (i = 0; i < ETH_END / sizeof(u32); ++i) regs_buff[i] = ethoc_read(priv, i * sizeof(u32)); } static void ethoc_get_ringparam(struct net_device *dev, struct ethtool_ringparam *ring, struct kernel_ethtool_ringparam *kernel_ring, struct netlink_ext_ack *extack) { struct ethoc *priv = netdev_priv(dev); ring->rx_max_pending = priv->num_bd - 1; ring->rx_mini_max_pending = 0; ring->rx_jumbo_max_pending = 0; ring->tx_max_pending = priv->num_bd - 1; ring->rx_pending = priv->num_rx; ring->rx_mini_pending = 0; ring->rx_jumbo_pending = 0; ring->tx_pending = priv->num_tx; } static int ethoc_set_ringparam(struct net_device *dev, struct ethtool_ringparam *ring, struct kernel_ethtool_ringparam *kernel_ring, struct netlink_ext_ack *extack) { struct ethoc *priv = netdev_priv(dev); if (ring->tx_pending < 1 || ring->rx_pending < 1 || ring->tx_pending + ring->rx_pending > priv->num_bd) return -EINVAL; if (ring->rx_mini_pending || ring->rx_jumbo_pending) return -EINVAL; if (netif_running(dev)) { netif_tx_disable(dev); ethoc_disable_rx_and_tx(priv); ethoc_disable_irq(priv, INT_MASK_TX | INT_MASK_RX); synchronize_irq(dev->irq); } priv->num_tx = rounddown_pow_of_two(ring->tx_pending); priv->num_rx = ring->rx_pending; ethoc_init_ring(priv, dev->mem_start); if (netif_running(dev)) { ethoc_enable_irq(priv, INT_MASK_TX | INT_MASK_RX); ethoc_enable_rx_and_tx(priv); netif_wake_queue(dev); } return 0; } static const struct ethtool_ops ethoc_ethtool_ops = { .get_regs_len = ethoc_get_regs_len, .get_regs = ethoc_get_regs, .nway_reset = phy_ethtool_nway_reset, .get_link = ethtool_op_get_link, .get_ringparam = ethoc_get_ringparam, .set_ringparam = ethoc_set_ringparam, .get_ts_info = ethtool_op_get_ts_info, .get_link_ksettings = phy_ethtool_get_link_ksettings, .set_link_ksettings = phy_ethtool_set_link_ksettings, }; static const struct net_device_ops ethoc_netdev_ops = { .ndo_open = ethoc_open, .ndo_stop = ethoc_stop, .ndo_eth_ioctl = ethoc_ioctl, .ndo_set_mac_address = ethoc_set_mac_address, .ndo_set_rx_mode = ethoc_set_multicast_list, .ndo_change_mtu = ethoc_change_mtu, .ndo_tx_timeout = ethoc_tx_timeout, .ndo_start_xmit = ethoc_start_xmit, }; /** * ethoc_probe - initialize OpenCores ethernet MAC * @pdev: platform device */ static int ethoc_probe(struct platform_device *pdev) { struct net_device *netdev = NULL; struct resource *res = NULL; struct resource *mmio = NULL; struct resource *mem = NULL; struct ethoc *priv = NULL; int num_bd; int ret = 0; struct ethoc_platform_data *pdata = dev_get_platdata(&pdev->dev); u32 eth_clkfreq = pdata ? pdata->eth_clkfreq : 0; /* allocate networking device */ netdev = alloc_etherdev(sizeof(struct ethoc)); if (!netdev) { ret = -ENOMEM; goto out; } SET_NETDEV_DEV(netdev, &pdev->dev); platform_set_drvdata(pdev, netdev); /* obtain I/O memory space */ res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { dev_err(&pdev->dev, "cannot obtain I/O memory space\n"); ret = -ENXIO; goto free; } mmio = devm_request_mem_region(&pdev->dev, res->start, resource_size(res), res->name); if (!mmio) { dev_err(&pdev->dev, "cannot request I/O memory space\n"); ret = -ENXIO; goto free; } netdev->base_addr = mmio->start; /* obtain buffer memory space */ res = platform_get_resource(pdev, IORESOURCE_MEM, 1); if (res) { mem = devm_request_mem_region(&pdev->dev, res->start, resource_size(res), res->name); if (!mem) { dev_err(&pdev->dev, "cannot request memory space\n"); ret = -ENXIO; goto free; } netdev->mem_start = mem->start; netdev->mem_end = mem->end; } /* obtain device IRQ number */ ret = platform_get_irq(pdev, 0); if (ret < 0) goto free; netdev->irq = ret; /* setup driver-private data */ priv = netdev_priv(netdev); priv->netdev = netdev; priv->iobase = devm_ioremap(&pdev->dev, netdev->base_addr, resource_size(mmio)); if (!priv->iobase) { dev_err(&pdev->dev, "cannot remap I/O memory space\n"); ret = -ENXIO; goto free; } if (netdev->mem_end) { priv->membase = devm_ioremap(&pdev->dev, netdev->mem_start, resource_size(mem)); if (!priv->membase) { dev_err(&pdev->dev, "cannot remap memory space\n"); ret = -ENXIO; goto free; } } else { /* Allocate buffer memory */ priv->membase = dmam_alloc_coherent(&pdev->dev, buffer_size, (void *)&netdev->mem_start, GFP_KERNEL); if (!priv->membase) { dev_err(&pdev->dev, "cannot allocate %dB buffer\n", buffer_size); ret = -ENOMEM; goto free; } netdev->mem_end = netdev->mem_start + buffer_size; } priv->big_endian = pdata ? pdata->big_endian : of_device_is_big_endian(pdev->dev.of_node); /* calculate the number of TX/RX buffers, maximum 128 supported */ num_bd = min_t(unsigned int, 128, (netdev->mem_end - netdev->mem_start + 1) / ETHOC_BUFSIZ); if (num_bd < 4) { ret = -ENODEV; goto free; } priv->num_bd = num_bd; /* num_tx must be a power of two */ priv->num_tx = rounddown_pow_of_two(num_bd >> 1); priv->num_rx = num_bd - priv->num_tx; dev_dbg(&pdev->dev, "ethoc: num_tx: %d num_rx: %d\n", priv->num_tx, priv->num_rx); priv->vma = devm_kcalloc(&pdev->dev, num_bd, sizeof(void *), GFP_KERNEL); if (!priv->vma) { ret = -ENOMEM; goto free; } /* Allow the platform setup code to pass in a MAC address. */ if (pdata) { eth_hw_addr_set(netdev, pdata->hwaddr); priv->phy_id = pdata->phy_id; } else { of_get_ethdev_address(pdev->dev.of_node, netdev); priv->phy_id = -1; } /* Check that the given MAC address is valid. If it isn't, read the * current MAC from the controller. */ if (!is_valid_ether_addr(netdev->dev_addr)) { u8 addr[ETH_ALEN]; ethoc_get_mac_address(netdev, addr); eth_hw_addr_set(netdev, addr); } /* Check the MAC again for validity, if it still isn't choose and * program a random one. */ if (!is_valid_ether_addr(netdev->dev_addr)) eth_hw_addr_random(netdev); ethoc_do_set_mac_address(netdev); /* Allow the platform setup code to adjust MII management bus clock. */ if (!eth_clkfreq) { struct clk *clk = devm_clk_get(&pdev->dev, NULL); if (!IS_ERR(clk)) { priv->clk = clk; clk_prepare_enable(clk); eth_clkfreq = clk_get_rate(clk); } } if (eth_clkfreq) { u32 clkdiv = MIIMODER_CLKDIV(eth_clkfreq / 2500000 + 1); if (!clkdiv) clkdiv = 2; dev_dbg(&pdev->dev, "setting MII clkdiv to %u\n", clkdiv); ethoc_write(priv, MIIMODER, (ethoc_read(priv, MIIMODER) & MIIMODER_NOPRE) | clkdiv); } /* register MII bus */ priv->mdio = mdiobus_alloc(); if (!priv->mdio) { ret = -ENOMEM; goto free2; } priv->mdio->name = "ethoc-mdio"; snprintf(priv->mdio->id, MII_BUS_ID_SIZE, "%s-%d", priv->mdio->name, pdev->id); priv->mdio->read = ethoc_mdio_read; priv->mdio->write = ethoc_mdio_write; priv->mdio->priv = priv; ret = mdiobus_register(priv->mdio); if (ret) { dev_err(&netdev->dev, "failed to register MDIO bus\n"); goto free3; } ret = ethoc_mdio_probe(netdev); if (ret) { dev_err(&netdev->dev, "failed to probe MDIO bus\n"); goto error; } /* setup the net_device structure */ netdev->netdev_ops = &ethoc_netdev_ops; netdev->watchdog_timeo = ETHOC_TIMEOUT; netdev->features |= 0; netdev->ethtool_ops = &ethoc_ethtool_ops; /* setup NAPI */ netif_napi_add(netdev, &priv->napi, ethoc_poll); spin_lock_init(&priv->lock); ret = register_netdev(netdev); if (ret < 0) { dev_err(&netdev->dev, "failed to register interface\n"); goto error2; } goto out; error2: netif_napi_del(&priv->napi); error: mdiobus_unregister(priv->mdio); free3: mdiobus_free(priv->mdio); free2: clk_disable_unprepare(priv->clk); free: free_netdev(netdev); out: return ret; } /** * ethoc_remove - shutdown OpenCores ethernet MAC * @pdev: platform device */ static int ethoc_remove(struct platform_device *pdev) { struct net_device *netdev = platform_get_drvdata(pdev); struct ethoc *priv = netdev_priv(netdev); if (netdev) { netif_napi_del(&priv->napi); phy_disconnect(netdev->phydev); if (priv->mdio) { mdiobus_unregister(priv->mdio); mdiobus_free(priv->mdio); } clk_disable_unprepare(priv->clk); unregister_netdev(netdev); free_netdev(netdev); } return 0; } #ifdef CONFIG_PM static int ethoc_suspend(struct platform_device *pdev, pm_message_t state) { return -ENOSYS; } static int ethoc_resume(struct platform_device *pdev) { return -ENOSYS; } #else # define ethoc_suspend NULL # define ethoc_resume NULL #endif static const struct of_device_id ethoc_match[] = { { .compatible = "opencores,ethoc", }, {}, }; MODULE_DEVICE_TABLE(of, ethoc_match); static struct platform_driver ethoc_driver = { .probe = ethoc_probe, .remove = ethoc_remove, .suspend = ethoc_suspend, .resume = ethoc_resume, .driver = { .name = "ethoc", .of_match_table = ethoc_match, }, }; module_platform_driver(ethoc_driver); MODULE_AUTHOR("Thierry Reding <[email protected]>"); MODULE_DESCRIPTION("OpenCores Ethernet MAC driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/net/ethernet/ethoc.c
// SPDX-License-Identifier: GPL-2.0-only /* * JMicron JMC2x0 series PCIe Ethernet Linux Device Driver * * Copyright 2008 JMicron Technology Corporation * https://www.jmicron.com/ * Copyright (c) 2009 - 2010 Guo-Fu Tseng <[email protected]> * * Author: Guo-Fu Tseng <[email protected]> */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/kernel.h> #include <linux/pci.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/ethtool.h> #include <linux/mii.h> #include <linux/crc32.h> #include <linux/delay.h> #include <linux/spinlock.h> #include <linux/in.h> #include <linux/ip.h> #include <linux/ipv6.h> #include <linux/tcp.h> #include <linux/udp.h> #include <linux/if_vlan.h> #include <linux/slab.h> #include <linux/jiffies.h> #include <net/ip6_checksum.h> #include "jme.h" static int force_pseudohp = -1; static int no_pseudohp = -1; static int no_extplug = -1; module_param(force_pseudohp, int, 0); MODULE_PARM_DESC(force_pseudohp, "Enable pseudo hot-plug feature manually by driver instead of BIOS."); module_param(no_pseudohp, int, 0); MODULE_PARM_DESC(no_pseudohp, "Disable pseudo hot-plug feature."); module_param(no_extplug, int, 0); MODULE_PARM_DESC(no_extplug, "Do not use external plug signal for pseudo hot-plug."); static int jme_mdio_read(struct net_device *netdev, int phy, int reg) { struct jme_adapter *jme = netdev_priv(netdev); int i, val, again = (reg == MII_BMSR) ? 1 : 0; read_again: jwrite32(jme, JME_SMI, SMI_OP_REQ | smi_phy_addr(phy) | smi_reg_addr(reg)); wmb(); for (i = JME_PHY_TIMEOUT * 50 ; i > 0 ; --i) { udelay(20); val = jread32(jme, JME_SMI); if ((val & SMI_OP_REQ) == 0) break; } if (i == 0) { pr_err("phy(%d) read timeout : %d\n", phy, reg); return 0; } if (again--) goto read_again; return (val & SMI_DATA_MASK) >> SMI_DATA_SHIFT; } static void jme_mdio_write(struct net_device *netdev, int phy, int reg, int val) { struct jme_adapter *jme = netdev_priv(netdev); int i; jwrite32(jme, JME_SMI, SMI_OP_WRITE | SMI_OP_REQ | ((val << SMI_DATA_SHIFT) & SMI_DATA_MASK) | smi_phy_addr(phy) | smi_reg_addr(reg)); wmb(); for (i = JME_PHY_TIMEOUT * 50 ; i > 0 ; --i) { udelay(20); if ((jread32(jme, JME_SMI) & SMI_OP_REQ) == 0) break; } if (i == 0) pr_err("phy(%d) write timeout : %d\n", phy, reg); } static inline void jme_reset_phy_processor(struct jme_adapter *jme) { u32 val; jme_mdio_write(jme->dev, jme->mii_if.phy_id, MII_ADVERTISE, ADVERTISE_ALL | ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM); if (jme->pdev->device == PCI_DEVICE_ID_JMICRON_JMC250) jme_mdio_write(jme->dev, jme->mii_if.phy_id, MII_CTRL1000, ADVERTISE_1000FULL | ADVERTISE_1000HALF); val = jme_mdio_read(jme->dev, jme->mii_if.phy_id, MII_BMCR); jme_mdio_write(jme->dev, jme->mii_if.phy_id, MII_BMCR, val | BMCR_RESET); } static void jme_setup_wakeup_frame(struct jme_adapter *jme, const u32 *mask, u32 crc, int fnr) { int i; /* * Setup CRC pattern */ jwrite32(jme, JME_WFOI, WFOI_CRC_SEL | (fnr & WFOI_FRAME_SEL)); wmb(); jwrite32(jme, JME_WFODP, crc); wmb(); /* * Setup Mask */ for (i = 0 ; i < WAKEUP_FRAME_MASK_DWNR ; ++i) { jwrite32(jme, JME_WFOI, ((i << WFOI_MASK_SHIFT) & WFOI_MASK_SEL) | (fnr & WFOI_FRAME_SEL)); wmb(); jwrite32(jme, JME_WFODP, mask[i]); wmb(); } } static inline void jme_mac_rxclk_off(struct jme_adapter *jme) { jme->reg_gpreg1 |= GPREG1_RXCLKOFF; jwrite32f(jme, JME_GPREG1, jme->reg_gpreg1); } static inline void jme_mac_rxclk_on(struct jme_adapter *jme) { jme->reg_gpreg1 &= ~GPREG1_RXCLKOFF; jwrite32f(jme, JME_GPREG1, jme->reg_gpreg1); } static inline void jme_mac_txclk_off(struct jme_adapter *jme) { jme->reg_ghc &= ~(GHC_TO_CLK_SRC | GHC_TXMAC_CLK_SRC); jwrite32f(jme, JME_GHC, jme->reg_ghc); } static inline void jme_mac_txclk_on(struct jme_adapter *jme) { u32 speed = jme->reg_ghc & GHC_SPEED; if (speed == GHC_SPEED_1000M) jme->reg_ghc |= GHC_TO_CLK_GPHY | GHC_TXMAC_CLK_GPHY; else jme->reg_ghc |= GHC_TO_CLK_PCIE | GHC_TXMAC_CLK_PCIE; jwrite32f(jme, JME_GHC, jme->reg_ghc); } static inline void jme_reset_ghc_speed(struct jme_adapter *jme) { jme->reg_ghc &= ~(GHC_SPEED | GHC_DPX); jwrite32f(jme, JME_GHC, jme->reg_ghc); } static inline void jme_reset_250A2_workaround(struct jme_adapter *jme) { jme->reg_gpreg1 &= ~(GPREG1_HALFMODEPATCH | GPREG1_RSSPATCH); jwrite32(jme, JME_GPREG1, jme->reg_gpreg1); } static inline void jme_assert_ghc_reset(struct jme_adapter *jme) { jme->reg_ghc |= GHC_SWRST; jwrite32f(jme, JME_GHC, jme->reg_ghc); } static inline void jme_clear_ghc_reset(struct jme_adapter *jme) { jme->reg_ghc &= ~GHC_SWRST; jwrite32f(jme, JME_GHC, jme->reg_ghc); } static void jme_reset_mac_processor(struct jme_adapter *jme) { static const u32 mask[WAKEUP_FRAME_MASK_DWNR] = {0, 0, 0, 0}; u32 crc = 0xCDCDCDCD; u32 gpreg0; int i; jme_reset_ghc_speed(jme); jme_reset_250A2_workaround(jme); jme_mac_rxclk_on(jme); jme_mac_txclk_on(jme); udelay(1); jme_assert_ghc_reset(jme); udelay(1); jme_mac_rxclk_off(jme); jme_mac_txclk_off(jme); udelay(1); jme_clear_ghc_reset(jme); udelay(1); jme_mac_rxclk_on(jme); jme_mac_txclk_on(jme); udelay(1); jme_mac_rxclk_off(jme); jme_mac_txclk_off(jme); jwrite32(jme, JME_RXDBA_LO, 0x00000000); jwrite32(jme, JME_RXDBA_HI, 0x00000000); jwrite32(jme, JME_RXQDC, 0x00000000); jwrite32(jme, JME_RXNDA, 0x00000000); jwrite32(jme, JME_TXDBA_LO, 0x00000000); jwrite32(jme, JME_TXDBA_HI, 0x00000000); jwrite32(jme, JME_TXQDC, 0x00000000); jwrite32(jme, JME_TXNDA, 0x00000000); jwrite32(jme, JME_RXMCHT_LO, 0x00000000); jwrite32(jme, JME_RXMCHT_HI, 0x00000000); for (i = 0 ; i < WAKEUP_FRAME_NR ; ++i) jme_setup_wakeup_frame(jme, mask, crc, i); if (jme->fpgaver) gpreg0 = GPREG0_DEFAULT | GPREG0_LNKINTPOLL; else gpreg0 = GPREG0_DEFAULT; jwrite32(jme, JME_GPREG0, gpreg0); } static inline void jme_clear_pm_enable_wol(struct jme_adapter *jme) { jwrite32(jme, JME_PMCS, PMCS_STMASK | jme->reg_pmcs); } static inline void jme_clear_pm_disable_wol(struct jme_adapter *jme) { jwrite32(jme, JME_PMCS, PMCS_STMASK); } static int jme_reload_eeprom(struct jme_adapter *jme) { u32 val; int i; val = jread32(jme, JME_SMBCSR); if (val & SMBCSR_EEPROMD) { val |= SMBCSR_CNACK; jwrite32(jme, JME_SMBCSR, val); val |= SMBCSR_RELOAD; jwrite32(jme, JME_SMBCSR, val); mdelay(12); for (i = JME_EEPROM_RELOAD_TIMEOUT; i > 0; --i) { mdelay(1); if ((jread32(jme, JME_SMBCSR) & SMBCSR_RELOAD) == 0) break; } if (i == 0) { pr_err("eeprom reload timeout\n"); return -EIO; } } return 0; } static void jme_load_macaddr(struct net_device *netdev) { struct jme_adapter *jme = netdev_priv(netdev); unsigned char macaddr[ETH_ALEN]; u32 val; spin_lock_bh(&jme->macaddr_lock); val = jread32(jme, JME_RXUMA_LO); macaddr[0] = (val >> 0) & 0xFF; macaddr[1] = (val >> 8) & 0xFF; macaddr[2] = (val >> 16) & 0xFF; macaddr[3] = (val >> 24) & 0xFF; val = jread32(jme, JME_RXUMA_HI); macaddr[4] = (val >> 0) & 0xFF; macaddr[5] = (val >> 8) & 0xFF; eth_hw_addr_set(netdev, macaddr); spin_unlock_bh(&jme->macaddr_lock); } static inline void jme_set_rx_pcc(struct jme_adapter *jme, int p) { switch (p) { case PCC_OFF: jwrite32(jme, JME_PCCRX0, ((PCC_OFF_TO << PCCRXTO_SHIFT) & PCCRXTO_MASK) | ((PCC_OFF_CNT << PCCRX_SHIFT) & PCCRX_MASK)); break; case PCC_P1: jwrite32(jme, JME_PCCRX0, ((PCC_P1_TO << PCCRXTO_SHIFT) & PCCRXTO_MASK) | ((PCC_P1_CNT << PCCRX_SHIFT) & PCCRX_MASK)); break; case PCC_P2: jwrite32(jme, JME_PCCRX0, ((PCC_P2_TO << PCCRXTO_SHIFT) & PCCRXTO_MASK) | ((PCC_P2_CNT << PCCRX_SHIFT) & PCCRX_MASK)); break; case PCC_P3: jwrite32(jme, JME_PCCRX0, ((PCC_P3_TO << PCCRXTO_SHIFT) & PCCRXTO_MASK) | ((PCC_P3_CNT << PCCRX_SHIFT) & PCCRX_MASK)); break; default: break; } wmb(); if (!(test_bit(JME_FLAG_POLL, &jme->flags))) netif_info(jme, rx_status, jme->dev, "Switched to PCC_P%d\n", p); } static void jme_start_irq(struct jme_adapter *jme) { register struct dynpcc_info *dpi = &(jme->dpi); jme_set_rx_pcc(jme, PCC_P1); dpi->cur = PCC_P1; dpi->attempt = PCC_P1; dpi->cnt = 0; jwrite32(jme, JME_PCCTX, ((PCC_TX_TO << PCCTXTO_SHIFT) & PCCTXTO_MASK) | ((PCC_TX_CNT << PCCTX_SHIFT) & PCCTX_MASK) | PCCTXQ0_EN ); /* * Enable Interrupts */ jwrite32(jme, JME_IENS, INTR_ENABLE); } static inline void jme_stop_irq(struct jme_adapter *jme) { /* * Disable Interrupts */ jwrite32f(jme, JME_IENC, INTR_ENABLE); } static u32 jme_linkstat_from_phy(struct jme_adapter *jme) { u32 phylink, bmsr; phylink = jme_mdio_read(jme->dev, jme->mii_if.phy_id, 17); bmsr = jme_mdio_read(jme->dev, jme->mii_if.phy_id, MII_BMSR); if (bmsr & BMSR_ANCOMP) phylink |= PHY_LINK_AUTONEG_COMPLETE; return phylink; } static inline void jme_set_phyfifo_5level(struct jme_adapter *jme) { jme_mdio_write(jme->dev, jme->mii_if.phy_id, 27, 0x0004); } static inline void jme_set_phyfifo_8level(struct jme_adapter *jme) { jme_mdio_write(jme->dev, jme->mii_if.phy_id, 27, 0x0000); } static int jme_check_link(struct net_device *netdev, int testonly) { struct jme_adapter *jme = netdev_priv(netdev); u32 phylink, cnt = JME_SPDRSV_TIMEOUT, bmcr; char linkmsg[64]; int rc = 0; linkmsg[0] = '\0'; if (jme->fpgaver) phylink = jme_linkstat_from_phy(jme); else phylink = jread32(jme, JME_PHY_LINK); if (phylink & PHY_LINK_UP) { if (!(phylink & PHY_LINK_AUTONEG_COMPLETE)) { /* * If we did not enable AN * Speed/Duplex Info should be obtained from SMI */ phylink = PHY_LINK_UP; bmcr = jme_mdio_read(jme->dev, jme->mii_if.phy_id, MII_BMCR); phylink |= ((bmcr & BMCR_SPEED1000) && (bmcr & BMCR_SPEED100) == 0) ? PHY_LINK_SPEED_1000M : (bmcr & BMCR_SPEED100) ? PHY_LINK_SPEED_100M : PHY_LINK_SPEED_10M; phylink |= (bmcr & BMCR_FULLDPLX) ? PHY_LINK_DUPLEX : 0; strcat(linkmsg, "Forced: "); } else { /* * Keep polling for speed/duplex resolve complete */ while (!(phylink & PHY_LINK_SPEEDDPU_RESOLVED) && --cnt) { udelay(1); if (jme->fpgaver) phylink = jme_linkstat_from_phy(jme); else phylink = jread32(jme, JME_PHY_LINK); } if (!cnt) pr_err("Waiting speed resolve timeout\n"); strcat(linkmsg, "ANed: "); } if (jme->phylink == phylink) { rc = 1; goto out; } if (testonly) goto out; jme->phylink = phylink; /* * The speed/duplex setting of jme->reg_ghc already cleared * by jme_reset_mac_processor() */ switch (phylink & PHY_LINK_SPEED_MASK) { case PHY_LINK_SPEED_10M: jme->reg_ghc |= GHC_SPEED_10M; strcat(linkmsg, "10 Mbps, "); break; case PHY_LINK_SPEED_100M: jme->reg_ghc |= GHC_SPEED_100M; strcat(linkmsg, "100 Mbps, "); break; case PHY_LINK_SPEED_1000M: jme->reg_ghc |= GHC_SPEED_1000M; strcat(linkmsg, "1000 Mbps, "); break; default: break; } if (phylink & PHY_LINK_DUPLEX) { jwrite32(jme, JME_TXMCS, TXMCS_DEFAULT); jwrite32(jme, JME_TXTRHD, TXTRHD_FULLDUPLEX); jme->reg_ghc |= GHC_DPX; } else { jwrite32(jme, JME_TXMCS, TXMCS_DEFAULT | TXMCS_BACKOFF | TXMCS_CARRIERSENSE | TXMCS_COLLISION); jwrite32(jme, JME_TXTRHD, TXTRHD_HALFDUPLEX); } jwrite32(jme, JME_GHC, jme->reg_ghc); if (is_buggy250(jme->pdev->device, jme->chiprev)) { jme->reg_gpreg1 &= ~(GPREG1_HALFMODEPATCH | GPREG1_RSSPATCH); if (!(phylink & PHY_LINK_DUPLEX)) jme->reg_gpreg1 |= GPREG1_HALFMODEPATCH; switch (phylink & PHY_LINK_SPEED_MASK) { case PHY_LINK_SPEED_10M: jme_set_phyfifo_8level(jme); jme->reg_gpreg1 |= GPREG1_RSSPATCH; break; case PHY_LINK_SPEED_100M: jme_set_phyfifo_5level(jme); jme->reg_gpreg1 |= GPREG1_RSSPATCH; break; case PHY_LINK_SPEED_1000M: jme_set_phyfifo_8level(jme); break; default: break; } } jwrite32(jme, JME_GPREG1, jme->reg_gpreg1); strcat(linkmsg, (phylink & PHY_LINK_DUPLEX) ? "Full-Duplex, " : "Half-Duplex, "); strcat(linkmsg, (phylink & PHY_LINK_MDI_STAT) ? "MDI-X" : "MDI"); netif_info(jme, link, jme->dev, "Link is up at %s\n", linkmsg); netif_carrier_on(netdev); } else { if (testonly) goto out; netif_info(jme, link, jme->dev, "Link is down\n"); jme->phylink = 0; netif_carrier_off(netdev); } out: return rc; } static int jme_setup_tx_resources(struct jme_adapter *jme) { struct jme_ring *txring = &(jme->txring[0]); txring->alloc = dma_alloc_coherent(&(jme->pdev->dev), TX_RING_ALLOC_SIZE(jme->tx_ring_size), &(txring->dmaalloc), GFP_ATOMIC); if (!txring->alloc) goto err_set_null; /* * 16 Bytes align */ txring->desc = (void *)ALIGN((unsigned long)(txring->alloc), RING_DESC_ALIGN); txring->dma = ALIGN(txring->dmaalloc, RING_DESC_ALIGN); txring->next_to_use = 0; atomic_set(&txring->next_to_clean, 0); atomic_set(&txring->nr_free, jme->tx_ring_size); txring->bufinf = kcalloc(jme->tx_ring_size, sizeof(struct jme_buffer_info), GFP_ATOMIC); if (unlikely(!(txring->bufinf))) goto err_free_txring; return 0; err_free_txring: dma_free_coherent(&(jme->pdev->dev), TX_RING_ALLOC_SIZE(jme->tx_ring_size), txring->alloc, txring->dmaalloc); err_set_null: txring->desc = NULL; txring->dmaalloc = 0; txring->dma = 0; txring->bufinf = NULL; return -ENOMEM; } static void jme_free_tx_resources(struct jme_adapter *jme) { int i; struct jme_ring *txring = &(jme->txring[0]); struct jme_buffer_info *txbi; if (txring->alloc) { if (txring->bufinf) { for (i = 0 ; i < jme->tx_ring_size ; ++i) { txbi = txring->bufinf + i; if (txbi->skb) { dev_kfree_skb(txbi->skb); txbi->skb = NULL; } txbi->mapping = 0; txbi->len = 0; txbi->nr_desc = 0; txbi->start_xmit = 0; } kfree(txring->bufinf); } dma_free_coherent(&(jme->pdev->dev), TX_RING_ALLOC_SIZE(jme->tx_ring_size), txring->alloc, txring->dmaalloc); txring->alloc = NULL; txring->desc = NULL; txring->dmaalloc = 0; txring->dma = 0; txring->bufinf = NULL; } txring->next_to_use = 0; atomic_set(&txring->next_to_clean, 0); atomic_set(&txring->nr_free, 0); } static inline void jme_enable_tx_engine(struct jme_adapter *jme) { /* * Select Queue 0 */ jwrite32(jme, JME_TXCS, TXCS_DEFAULT | TXCS_SELECT_QUEUE0); wmb(); /* * Setup TX Queue 0 DMA Bass Address */ jwrite32(jme, JME_TXDBA_LO, (__u64)jme->txring[0].dma & 0xFFFFFFFFUL); jwrite32(jme, JME_TXDBA_HI, (__u64)(jme->txring[0].dma) >> 32); jwrite32(jme, JME_TXNDA, (__u64)jme->txring[0].dma & 0xFFFFFFFFUL); /* * Setup TX Descptor Count */ jwrite32(jme, JME_TXQDC, jme->tx_ring_size); /* * Enable TX Engine */ wmb(); jwrite32f(jme, JME_TXCS, jme->reg_txcs | TXCS_SELECT_QUEUE0 | TXCS_ENABLE); /* * Start clock for TX MAC Processor */ jme_mac_txclk_on(jme); } static inline void jme_disable_tx_engine(struct jme_adapter *jme) { int i; u32 val; /* * Disable TX Engine */ jwrite32(jme, JME_TXCS, jme->reg_txcs | TXCS_SELECT_QUEUE0); wmb(); val = jread32(jme, JME_TXCS); for (i = JME_TX_DISABLE_TIMEOUT ; (val & TXCS_ENABLE) && i > 0 ; --i) { mdelay(1); val = jread32(jme, JME_TXCS); rmb(); } if (!i) pr_err("Disable TX engine timeout\n"); /* * Stop clock for TX MAC Processor */ jme_mac_txclk_off(jme); } static void jme_set_clean_rxdesc(struct jme_adapter *jme, int i) { struct jme_ring *rxring = &(jme->rxring[0]); register struct rxdesc *rxdesc = rxring->desc; struct jme_buffer_info *rxbi = rxring->bufinf; rxdesc += i; rxbi += i; rxdesc->dw[0] = 0; rxdesc->dw[1] = 0; rxdesc->desc1.bufaddrh = cpu_to_le32((__u64)rxbi->mapping >> 32); rxdesc->desc1.bufaddrl = cpu_to_le32( (__u64)rxbi->mapping & 0xFFFFFFFFUL); rxdesc->desc1.datalen = cpu_to_le16(rxbi->len); if (jme->dev->features & NETIF_F_HIGHDMA) rxdesc->desc1.flags = RXFLAG_64BIT; wmb(); rxdesc->desc1.flags |= RXFLAG_OWN | RXFLAG_INT; } static int jme_make_new_rx_buf(struct jme_adapter *jme, int i) { struct jme_ring *rxring = &(jme->rxring[0]); struct jme_buffer_info *rxbi = rxring->bufinf + i; struct sk_buff *skb; dma_addr_t mapping; skb = netdev_alloc_skb(jme->dev, jme->dev->mtu + RX_EXTRA_LEN); if (unlikely(!skb)) return -ENOMEM; mapping = dma_map_page(&jme->pdev->dev, virt_to_page(skb->data), offset_in_page(skb->data), skb_tailroom(skb), DMA_FROM_DEVICE); if (unlikely(dma_mapping_error(&jme->pdev->dev, mapping))) { dev_kfree_skb(skb); return -ENOMEM; } if (likely(rxbi->mapping)) dma_unmap_page(&jme->pdev->dev, rxbi->mapping, rxbi->len, DMA_FROM_DEVICE); rxbi->skb = skb; rxbi->len = skb_tailroom(skb); rxbi->mapping = mapping; return 0; } static void jme_free_rx_buf(struct jme_adapter *jme, int i) { struct jme_ring *rxring = &(jme->rxring[0]); struct jme_buffer_info *rxbi = rxring->bufinf; rxbi += i; if (rxbi->skb) { dma_unmap_page(&jme->pdev->dev, rxbi->mapping, rxbi->len, DMA_FROM_DEVICE); dev_kfree_skb(rxbi->skb); rxbi->skb = NULL; rxbi->mapping = 0; rxbi->len = 0; } } static void jme_free_rx_resources(struct jme_adapter *jme) { int i; struct jme_ring *rxring = &(jme->rxring[0]); if (rxring->alloc) { if (rxring->bufinf) { for (i = 0 ; i < jme->rx_ring_size ; ++i) jme_free_rx_buf(jme, i); kfree(rxring->bufinf); } dma_free_coherent(&(jme->pdev->dev), RX_RING_ALLOC_SIZE(jme->rx_ring_size), rxring->alloc, rxring->dmaalloc); rxring->alloc = NULL; rxring->desc = NULL; rxring->dmaalloc = 0; rxring->dma = 0; rxring->bufinf = NULL; } rxring->next_to_use = 0; atomic_set(&rxring->next_to_clean, 0); } static int jme_setup_rx_resources(struct jme_adapter *jme) { int i; struct jme_ring *rxring = &(jme->rxring[0]); rxring->alloc = dma_alloc_coherent(&(jme->pdev->dev), RX_RING_ALLOC_SIZE(jme->rx_ring_size), &(rxring->dmaalloc), GFP_ATOMIC); if (!rxring->alloc) goto err_set_null; /* * 16 Bytes align */ rxring->desc = (void *)ALIGN((unsigned long)(rxring->alloc), RING_DESC_ALIGN); rxring->dma = ALIGN(rxring->dmaalloc, RING_DESC_ALIGN); rxring->next_to_use = 0; atomic_set(&rxring->next_to_clean, 0); rxring->bufinf = kcalloc(jme->rx_ring_size, sizeof(struct jme_buffer_info), GFP_ATOMIC); if (unlikely(!(rxring->bufinf))) goto err_free_rxring; /* * Initiallize Receive Descriptors */ for (i = 0 ; i < jme->rx_ring_size ; ++i) { if (unlikely(jme_make_new_rx_buf(jme, i))) { jme_free_rx_resources(jme); return -ENOMEM; } jme_set_clean_rxdesc(jme, i); } return 0; err_free_rxring: dma_free_coherent(&(jme->pdev->dev), RX_RING_ALLOC_SIZE(jme->rx_ring_size), rxring->alloc, rxring->dmaalloc); err_set_null: rxring->desc = NULL; rxring->dmaalloc = 0; rxring->dma = 0; rxring->bufinf = NULL; return -ENOMEM; } static inline void jme_enable_rx_engine(struct jme_adapter *jme) { /* * Select Queue 0 */ jwrite32(jme, JME_RXCS, jme->reg_rxcs | RXCS_QUEUESEL_Q0); wmb(); /* * Setup RX DMA Bass Address */ jwrite32(jme, JME_RXDBA_LO, (__u64)(jme->rxring[0].dma) & 0xFFFFFFFFUL); jwrite32(jme, JME_RXDBA_HI, (__u64)(jme->rxring[0].dma) >> 32); jwrite32(jme, JME_RXNDA, (__u64)(jme->rxring[0].dma) & 0xFFFFFFFFUL); /* * Setup RX Descriptor Count */ jwrite32(jme, JME_RXQDC, jme->rx_ring_size); /* * Setup Unicast Filter */ jme_set_unicastaddr(jme->dev); jme_set_multi(jme->dev); /* * Enable RX Engine */ wmb(); jwrite32f(jme, JME_RXCS, jme->reg_rxcs | RXCS_QUEUESEL_Q0 | RXCS_ENABLE | RXCS_QST); /* * Start clock for RX MAC Processor */ jme_mac_rxclk_on(jme); } static inline void jme_restart_rx_engine(struct jme_adapter *jme) { /* * Start RX Engine */ jwrite32(jme, JME_RXCS, jme->reg_rxcs | RXCS_QUEUESEL_Q0 | RXCS_ENABLE | RXCS_QST); } static inline void jme_disable_rx_engine(struct jme_adapter *jme) { int i; u32 val; /* * Disable RX Engine */ jwrite32(jme, JME_RXCS, jme->reg_rxcs); wmb(); val = jread32(jme, JME_RXCS); for (i = JME_RX_DISABLE_TIMEOUT ; (val & RXCS_ENABLE) && i > 0 ; --i) { mdelay(1); val = jread32(jme, JME_RXCS); rmb(); } if (!i) pr_err("Disable RX engine timeout\n"); /* * Stop clock for RX MAC Processor */ jme_mac_rxclk_off(jme); } static u16 jme_udpsum(struct sk_buff *skb) { u16 csum = 0xFFFFu; if (skb->len < (ETH_HLEN + sizeof(struct iphdr))) return csum; if (skb->protocol != htons(ETH_P_IP)) return csum; skb_set_network_header(skb, ETH_HLEN); if ((ip_hdr(skb)->protocol != IPPROTO_UDP) || (skb->len < (ETH_HLEN + (ip_hdr(skb)->ihl << 2) + sizeof(struct udphdr)))) { skb_reset_network_header(skb); return csum; } skb_set_transport_header(skb, ETH_HLEN + (ip_hdr(skb)->ihl << 2)); csum = udp_hdr(skb)->check; skb_reset_transport_header(skb); skb_reset_network_header(skb); return csum; } static int jme_rxsum_ok(struct jme_adapter *jme, u16 flags, struct sk_buff *skb) { if (!(flags & (RXWBFLAG_TCPON | RXWBFLAG_UDPON | RXWBFLAG_IPV4))) return false; if (unlikely((flags & (RXWBFLAG_MF | RXWBFLAG_TCPON | RXWBFLAG_TCPCS)) == RXWBFLAG_TCPON)) { if (flags & RXWBFLAG_IPV4) netif_err(jme, rx_err, jme->dev, "TCP Checksum error\n"); return false; } if (unlikely((flags & (RXWBFLAG_MF | RXWBFLAG_UDPON | RXWBFLAG_UDPCS)) == RXWBFLAG_UDPON) && jme_udpsum(skb)) { if (flags & RXWBFLAG_IPV4) netif_err(jme, rx_err, jme->dev, "UDP Checksum error\n"); return false; } if (unlikely((flags & (RXWBFLAG_IPV4 | RXWBFLAG_IPCS)) == RXWBFLAG_IPV4)) { netif_err(jme, rx_err, jme->dev, "IPv4 Checksum error\n"); return false; } return true; } static void jme_alloc_and_feed_skb(struct jme_adapter *jme, int idx) { struct jme_ring *rxring = &(jme->rxring[0]); struct rxdesc *rxdesc = rxring->desc; struct jme_buffer_info *rxbi = rxring->bufinf; struct sk_buff *skb; int framesize; rxdesc += idx; rxbi += idx; skb = rxbi->skb; dma_sync_single_for_cpu(&jme->pdev->dev, rxbi->mapping, rxbi->len, DMA_FROM_DEVICE); if (unlikely(jme_make_new_rx_buf(jme, idx))) { dma_sync_single_for_device(&jme->pdev->dev, rxbi->mapping, rxbi->len, DMA_FROM_DEVICE); ++(NET_STAT(jme).rx_dropped); } else { framesize = le16_to_cpu(rxdesc->descwb.framesize) - RX_PREPAD_SIZE; skb_reserve(skb, RX_PREPAD_SIZE); skb_put(skb, framesize); skb->protocol = eth_type_trans(skb, jme->dev); if (jme_rxsum_ok(jme, le16_to_cpu(rxdesc->descwb.flags), skb)) skb->ip_summed = CHECKSUM_UNNECESSARY; else skb_checksum_none_assert(skb); if (rxdesc->descwb.flags & cpu_to_le16(RXWBFLAG_TAGON)) { u16 vid = le16_to_cpu(rxdesc->descwb.vlan); __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vid); NET_STAT(jme).rx_bytes += 4; } jme->jme_rx(skb); if ((rxdesc->descwb.flags & cpu_to_le16(RXWBFLAG_DEST)) == cpu_to_le16(RXWBFLAG_DEST_MUL)) ++(NET_STAT(jme).multicast); NET_STAT(jme).rx_bytes += framesize; ++(NET_STAT(jme).rx_packets); } jme_set_clean_rxdesc(jme, idx); } static int jme_process_receive(struct jme_adapter *jme, int limit) { struct jme_ring *rxring = &(jme->rxring[0]); struct rxdesc *rxdesc; int i, j, ccnt, desccnt, mask = jme->rx_ring_mask; if (unlikely(!atomic_dec_and_test(&jme->rx_cleaning))) goto out_inc; if (unlikely(atomic_read(&jme->link_changing) != 1)) goto out_inc; if (unlikely(!netif_carrier_ok(jme->dev))) goto out_inc; i = atomic_read(&rxring->next_to_clean); while (limit > 0) { rxdesc = rxring->desc; rxdesc += i; if ((rxdesc->descwb.flags & cpu_to_le16(RXWBFLAG_OWN)) || !(rxdesc->descwb.desccnt & RXWBDCNT_WBCPL)) goto out; --limit; rmb(); desccnt = rxdesc->descwb.desccnt & RXWBDCNT_DCNT; if (unlikely(desccnt > 1 || rxdesc->descwb.errstat & RXWBERR_ALLERR)) { if (rxdesc->descwb.errstat & RXWBERR_CRCERR) ++(NET_STAT(jme).rx_crc_errors); else if (rxdesc->descwb.errstat & RXWBERR_OVERUN) ++(NET_STAT(jme).rx_fifo_errors); else ++(NET_STAT(jme).rx_errors); if (desccnt > 1) limit -= desccnt - 1; for (j = i, ccnt = desccnt ; ccnt-- ; ) { jme_set_clean_rxdesc(jme, j); j = (j + 1) & (mask); } } else { jme_alloc_and_feed_skb(jme, i); } i = (i + desccnt) & (mask); } out: atomic_set(&rxring->next_to_clean, i); out_inc: atomic_inc(&jme->rx_cleaning); return limit > 0 ? limit : 0; } static void jme_attempt_pcc(struct dynpcc_info *dpi, int atmp) { if (likely(atmp == dpi->cur)) { dpi->cnt = 0; return; } if (dpi->attempt == atmp) { ++(dpi->cnt); } else { dpi->attempt = atmp; dpi->cnt = 0; } } static void jme_dynamic_pcc(struct jme_adapter *jme) { register struct dynpcc_info *dpi = &(jme->dpi); if ((NET_STAT(jme).rx_bytes - dpi->last_bytes) > PCC_P3_THRESHOLD) jme_attempt_pcc(dpi, PCC_P3); else if ((NET_STAT(jme).rx_packets - dpi->last_pkts) > PCC_P2_THRESHOLD || dpi->intr_cnt > PCC_INTR_THRESHOLD) jme_attempt_pcc(dpi, PCC_P2); else jme_attempt_pcc(dpi, PCC_P1); if (unlikely(dpi->attempt != dpi->cur && dpi->cnt > 5)) { if (dpi->attempt < dpi->cur) tasklet_schedule(&jme->rxclean_task); jme_set_rx_pcc(jme, dpi->attempt); dpi->cur = dpi->attempt; dpi->cnt = 0; } } static void jme_start_pcc_timer(struct jme_adapter *jme) { struct dynpcc_info *dpi = &(jme->dpi); dpi->last_bytes = NET_STAT(jme).rx_bytes; dpi->last_pkts = NET_STAT(jme).rx_packets; dpi->intr_cnt = 0; jwrite32(jme, JME_TMCSR, TMCSR_EN | ((0xFFFFFF - PCC_INTERVAL_US) & TMCSR_CNT)); } static inline void jme_stop_pcc_timer(struct jme_adapter *jme) { jwrite32(jme, JME_TMCSR, 0); } static void jme_shutdown_nic(struct jme_adapter *jme) { u32 phylink; phylink = jme_linkstat_from_phy(jme); if (!(phylink & PHY_LINK_UP)) { /* * Disable all interrupt before issue timer */ jme_stop_irq(jme); jwrite32(jme, JME_TIMER2, TMCSR_EN | 0xFFFFFE); } } static void jme_pcc_tasklet(struct tasklet_struct *t) { struct jme_adapter *jme = from_tasklet(jme, t, pcc_task); struct net_device *netdev = jme->dev; if (unlikely(test_bit(JME_FLAG_SHUTDOWN, &jme->flags))) { jme_shutdown_nic(jme); return; } if (unlikely(!netif_carrier_ok(netdev) || (atomic_read(&jme->link_changing) != 1) )) { jme_stop_pcc_timer(jme); return; } if (!(test_bit(JME_FLAG_POLL, &jme->flags))) jme_dynamic_pcc(jme); jme_start_pcc_timer(jme); } static inline void jme_polling_mode(struct jme_adapter *jme) { jme_set_rx_pcc(jme, PCC_OFF); } static inline void jme_interrupt_mode(struct jme_adapter *jme) { jme_set_rx_pcc(jme, PCC_P1); } static inline int jme_pseudo_hotplug_enabled(struct jme_adapter *jme) { u32 apmc; apmc = jread32(jme, JME_APMC); return apmc & JME_APMC_PSEUDO_HP_EN; } static void jme_start_shutdown_timer(struct jme_adapter *jme) { u32 apmc; apmc = jread32(jme, JME_APMC) | JME_APMC_PCIE_SD_EN; apmc &= ~JME_APMC_EPIEN_CTRL; if (!no_extplug) { jwrite32f(jme, JME_APMC, apmc | JME_APMC_EPIEN_CTRL_EN); wmb(); } jwrite32f(jme, JME_APMC, apmc); jwrite32f(jme, JME_TIMER2, 0); set_bit(JME_FLAG_SHUTDOWN, &jme->flags); jwrite32(jme, JME_TMCSR, TMCSR_EN | ((0xFFFFFF - APMC_PHP_SHUTDOWN_DELAY) & TMCSR_CNT)); } static void jme_stop_shutdown_timer(struct jme_adapter *jme) { u32 apmc; jwrite32f(jme, JME_TMCSR, 0); jwrite32f(jme, JME_TIMER2, 0); clear_bit(JME_FLAG_SHUTDOWN, &jme->flags); apmc = jread32(jme, JME_APMC); apmc &= ~(JME_APMC_PCIE_SD_EN | JME_APMC_EPIEN_CTRL); jwrite32f(jme, JME_APMC, apmc | JME_APMC_EPIEN_CTRL_DIS); wmb(); jwrite32f(jme, JME_APMC, apmc); } static void jme_link_change_work(struct work_struct *work) { struct jme_adapter *jme = container_of(work, struct jme_adapter, linkch_task); struct net_device *netdev = jme->dev; int rc; while (!atomic_dec_and_test(&jme->link_changing)) { atomic_inc(&jme->link_changing); netif_info(jme, intr, jme->dev, "Get link change lock failed\n"); while (atomic_read(&jme->link_changing) != 1) netif_info(jme, intr, jme->dev, "Waiting link change lock\n"); } if (jme_check_link(netdev, 1) && jme->old_mtu == netdev->mtu) goto out; jme->old_mtu = netdev->mtu; netif_stop_queue(netdev); if (jme_pseudo_hotplug_enabled(jme)) jme_stop_shutdown_timer(jme); jme_stop_pcc_timer(jme); tasklet_disable(&jme->txclean_task); tasklet_disable(&jme->rxclean_task); tasklet_disable(&jme->rxempty_task); if (netif_carrier_ok(netdev)) { jme_disable_rx_engine(jme); jme_disable_tx_engine(jme); jme_reset_mac_processor(jme); jme_free_rx_resources(jme); jme_free_tx_resources(jme); if (test_bit(JME_FLAG_POLL, &jme->flags)) jme_polling_mode(jme); netif_carrier_off(netdev); } jme_check_link(netdev, 0); if (netif_carrier_ok(netdev)) { rc = jme_setup_rx_resources(jme); if (rc) { pr_err("Allocating resources for RX error, Device STOPPED!\n"); goto out_enable_tasklet; } rc = jme_setup_tx_resources(jme); if (rc) { pr_err("Allocating resources for TX error, Device STOPPED!\n"); goto err_out_free_rx_resources; } jme_enable_rx_engine(jme); jme_enable_tx_engine(jme); netif_start_queue(netdev); if (test_bit(JME_FLAG_POLL, &jme->flags)) jme_interrupt_mode(jme); jme_start_pcc_timer(jme); } else if (jme_pseudo_hotplug_enabled(jme)) { jme_start_shutdown_timer(jme); } goto out_enable_tasklet; err_out_free_rx_resources: jme_free_rx_resources(jme); out_enable_tasklet: tasklet_enable(&jme->txclean_task); tasklet_enable(&jme->rxclean_task); tasklet_enable(&jme->rxempty_task); out: atomic_inc(&jme->link_changing); } static void jme_rx_clean_tasklet(struct tasklet_struct *t) { struct jme_adapter *jme = from_tasklet(jme, t, rxclean_task); struct dynpcc_info *dpi = &(jme->dpi); jme_process_receive(jme, jme->rx_ring_size); ++(dpi->intr_cnt); } static int jme_poll(JME_NAPI_HOLDER(holder), JME_NAPI_WEIGHT(budget)) { struct jme_adapter *jme = jme_napi_priv(holder); int rest; rest = jme_process_receive(jme, JME_NAPI_WEIGHT_VAL(budget)); while (atomic_read(&jme->rx_empty) > 0) { atomic_dec(&jme->rx_empty); ++(NET_STAT(jme).rx_dropped); jme_restart_rx_engine(jme); } atomic_inc(&jme->rx_empty); if (rest) { JME_RX_COMPLETE(netdev, holder); jme_interrupt_mode(jme); } JME_NAPI_WEIGHT_SET(budget, rest); return JME_NAPI_WEIGHT_VAL(budget) - rest; } static void jme_rx_empty_tasklet(struct tasklet_struct *t) { struct jme_adapter *jme = from_tasklet(jme, t, rxempty_task); if (unlikely(atomic_read(&jme->link_changing) != 1)) return; if (unlikely(!netif_carrier_ok(jme->dev))) return; netif_info(jme, rx_status, jme->dev, "RX Queue Full!\n"); jme_rx_clean_tasklet(&jme->rxclean_task); while (atomic_read(&jme->rx_empty) > 0) { atomic_dec(&jme->rx_empty); ++(NET_STAT(jme).rx_dropped); jme_restart_rx_engine(jme); } atomic_inc(&jme->rx_empty); } static void jme_wake_queue_if_stopped(struct jme_adapter *jme) { struct jme_ring *txring = &(jme->txring[0]); smp_wmb(); if (unlikely(netif_queue_stopped(jme->dev) && atomic_read(&txring->nr_free) >= (jme->tx_wake_threshold))) { netif_info(jme, tx_done, jme->dev, "TX Queue Waked\n"); netif_wake_queue(jme->dev); } } static void jme_tx_clean_tasklet(struct tasklet_struct *t) { struct jme_adapter *jme = from_tasklet(jme, t, txclean_task); struct jme_ring *txring = &(jme->txring[0]); struct txdesc *txdesc = txring->desc; struct jme_buffer_info *txbi = txring->bufinf, *ctxbi, *ttxbi; int i, j, cnt = 0, max, err, mask; tx_dbg(jme, "Into txclean\n"); if (unlikely(!atomic_dec_and_test(&jme->tx_cleaning))) goto out; if (unlikely(atomic_read(&jme->link_changing) != 1)) goto out; if (unlikely(!netif_carrier_ok(jme->dev))) goto out; max = jme->tx_ring_size - atomic_read(&txring->nr_free); mask = jme->tx_ring_mask; for (i = atomic_read(&txring->next_to_clean) ; cnt < max ; ) { ctxbi = txbi + i; if (likely(ctxbi->skb && !(txdesc[i].descwb.flags & TXWBFLAG_OWN))) { tx_dbg(jme, "txclean: %d+%d@%lu\n", i, ctxbi->nr_desc, jiffies); err = txdesc[i].descwb.flags & TXWBFLAG_ALLERR; for (j = 1 ; j < ctxbi->nr_desc ; ++j) { ttxbi = txbi + ((i + j) & (mask)); txdesc[(i + j) & (mask)].dw[0] = 0; dma_unmap_page(&jme->pdev->dev, ttxbi->mapping, ttxbi->len, DMA_TO_DEVICE); ttxbi->mapping = 0; ttxbi->len = 0; } dev_kfree_skb(ctxbi->skb); cnt += ctxbi->nr_desc; if (unlikely(err)) { ++(NET_STAT(jme).tx_carrier_errors); } else { ++(NET_STAT(jme).tx_packets); NET_STAT(jme).tx_bytes += ctxbi->len; } ctxbi->skb = NULL; ctxbi->len = 0; ctxbi->start_xmit = 0; } else { break; } i = (i + ctxbi->nr_desc) & mask; ctxbi->nr_desc = 0; } tx_dbg(jme, "txclean: done %d@%lu\n", i, jiffies); atomic_set(&txring->next_to_clean, i); atomic_add(cnt, &txring->nr_free); jme_wake_queue_if_stopped(jme); out: atomic_inc(&jme->tx_cleaning); } static void jme_intr_msi(struct jme_adapter *jme, u32 intrstat) { /* * Disable interrupt */ jwrite32f(jme, JME_IENC, INTR_ENABLE); if (intrstat & (INTR_LINKCH | INTR_SWINTR)) { /* * Link change event is critical * all other events are ignored */ jwrite32(jme, JME_IEVE, intrstat); schedule_work(&jme->linkch_task); goto out_reenable; } if (intrstat & INTR_TMINTR) { jwrite32(jme, JME_IEVE, INTR_TMINTR); tasklet_schedule(&jme->pcc_task); } if (intrstat & (INTR_PCCTXTO | INTR_PCCTX)) { jwrite32(jme, JME_IEVE, INTR_PCCTXTO | INTR_PCCTX | INTR_TX0); tasklet_schedule(&jme->txclean_task); } if ((intrstat & (INTR_PCCRX0TO | INTR_PCCRX0 | INTR_RX0EMP))) { jwrite32(jme, JME_IEVE, (intrstat & (INTR_PCCRX0TO | INTR_PCCRX0 | INTR_RX0EMP)) | INTR_RX0); } if (test_bit(JME_FLAG_POLL, &jme->flags)) { if (intrstat & INTR_RX0EMP) atomic_inc(&jme->rx_empty); if ((intrstat & (INTR_PCCRX0TO | INTR_PCCRX0 | INTR_RX0EMP))) { if (likely(JME_RX_SCHEDULE_PREP(jme))) { jme_polling_mode(jme); JME_RX_SCHEDULE(jme); } } } else { if (intrstat & INTR_RX0EMP) { atomic_inc(&jme->rx_empty); tasklet_hi_schedule(&jme->rxempty_task); } else if (intrstat & (INTR_PCCRX0TO | INTR_PCCRX0)) { tasklet_hi_schedule(&jme->rxclean_task); } } out_reenable: /* * Re-enable interrupt */ jwrite32f(jme, JME_IENS, INTR_ENABLE); } static irqreturn_t jme_intr(int irq, void *dev_id) { struct net_device *netdev = dev_id; struct jme_adapter *jme = netdev_priv(netdev); u32 intrstat; intrstat = jread32(jme, JME_IEVE); /* * Check if it's really an interrupt for us */ if (unlikely((intrstat & INTR_ENABLE) == 0)) return IRQ_NONE; /* * Check if the device still exist */ if (unlikely(intrstat == ~((typeof(intrstat))0))) return IRQ_NONE; jme_intr_msi(jme, intrstat); return IRQ_HANDLED; } static irqreturn_t jme_msi(int irq, void *dev_id) { struct net_device *netdev = dev_id; struct jme_adapter *jme = netdev_priv(netdev); u32 intrstat; intrstat = jread32(jme, JME_IEVE); jme_intr_msi(jme, intrstat); return IRQ_HANDLED; } static void jme_reset_link(struct jme_adapter *jme) { jwrite32(jme, JME_TMCSR, TMCSR_SWIT); } static void jme_restart_an(struct jme_adapter *jme) { u32 bmcr; spin_lock_bh(&jme->phy_lock); bmcr = jme_mdio_read(jme->dev, jme->mii_if.phy_id, MII_BMCR); bmcr |= (BMCR_ANENABLE | BMCR_ANRESTART); jme_mdio_write(jme->dev, jme->mii_if.phy_id, MII_BMCR, bmcr); spin_unlock_bh(&jme->phy_lock); } static int jme_request_irq(struct jme_adapter *jme) { int rc; struct net_device *netdev = jme->dev; irq_handler_t handler = jme_intr; int irq_flags = IRQF_SHARED; if (!pci_enable_msi(jme->pdev)) { set_bit(JME_FLAG_MSI, &jme->flags); handler = jme_msi; irq_flags = 0; } rc = request_irq(jme->pdev->irq, handler, irq_flags, netdev->name, netdev); if (rc) { netdev_err(netdev, "Unable to request %s interrupt (return: %d)\n", test_bit(JME_FLAG_MSI, &jme->flags) ? "MSI" : "INTx", rc); if (test_bit(JME_FLAG_MSI, &jme->flags)) { pci_disable_msi(jme->pdev); clear_bit(JME_FLAG_MSI, &jme->flags); } } else { netdev->irq = jme->pdev->irq; } return rc; } static void jme_free_irq(struct jme_adapter *jme) { free_irq(jme->pdev->irq, jme->dev); if (test_bit(JME_FLAG_MSI, &jme->flags)) { pci_disable_msi(jme->pdev); clear_bit(JME_FLAG_MSI, &jme->flags); jme->dev->irq = jme->pdev->irq; } } static inline void jme_new_phy_on(struct jme_adapter *jme) { u32 reg; reg = jread32(jme, JME_PHY_PWR); reg &= ~(PHY_PWR_DWN1SEL | PHY_PWR_DWN1SW | PHY_PWR_DWN2 | PHY_PWR_CLKSEL); jwrite32(jme, JME_PHY_PWR, reg); pci_read_config_dword(jme->pdev, PCI_PRIV_PE1, &reg); reg &= ~PE1_GPREG0_PBG; reg |= PE1_GPREG0_ENBG; pci_write_config_dword(jme->pdev, PCI_PRIV_PE1, reg); } static inline void jme_new_phy_off(struct jme_adapter *jme) { u32 reg; reg = jread32(jme, JME_PHY_PWR); reg |= PHY_PWR_DWN1SEL | PHY_PWR_DWN1SW | PHY_PWR_DWN2 | PHY_PWR_CLKSEL; jwrite32(jme, JME_PHY_PWR, reg); pci_read_config_dword(jme->pdev, PCI_PRIV_PE1, &reg); reg &= ~PE1_GPREG0_PBG; reg |= PE1_GPREG0_PDD3COLD; pci_write_config_dword(jme->pdev, PCI_PRIV_PE1, reg); } static inline void jme_phy_on(struct jme_adapter *jme) { u32 bmcr; bmcr = jme_mdio_read(jme->dev, jme->mii_if.phy_id, MII_BMCR); bmcr &= ~BMCR_PDOWN; jme_mdio_write(jme->dev, jme->mii_if.phy_id, MII_BMCR, bmcr); if (new_phy_power_ctrl(jme->chip_main_rev)) jme_new_phy_on(jme); } static inline void jme_phy_off(struct jme_adapter *jme) { u32 bmcr; bmcr = jme_mdio_read(jme->dev, jme->mii_if.phy_id, MII_BMCR); bmcr |= BMCR_PDOWN; jme_mdio_write(jme->dev, jme->mii_if.phy_id, MII_BMCR, bmcr); if (new_phy_power_ctrl(jme->chip_main_rev)) jme_new_phy_off(jme); } static int jme_phy_specreg_read(struct jme_adapter *jme, u32 specreg) { u32 phy_addr; phy_addr = JM_PHY_SPEC_REG_READ | specreg; jme_mdio_write(jme->dev, jme->mii_if.phy_id, JM_PHY_SPEC_ADDR_REG, phy_addr); return jme_mdio_read(jme->dev, jme->mii_if.phy_id, JM_PHY_SPEC_DATA_REG); } static void jme_phy_specreg_write(struct jme_adapter *jme, u32 ext_reg, u32 phy_data) { u32 phy_addr; phy_addr = JM_PHY_SPEC_REG_WRITE | ext_reg; jme_mdio_write(jme->dev, jme->mii_if.phy_id, JM_PHY_SPEC_DATA_REG, phy_data); jme_mdio_write(jme->dev, jme->mii_if.phy_id, JM_PHY_SPEC_ADDR_REG, phy_addr); } static int jme_phy_calibration(struct jme_adapter *jme) { u32 ctrl1000, phy_data; jme_phy_off(jme); jme_phy_on(jme); /* Enabel PHY test mode 1 */ ctrl1000 = jme_mdio_read(jme->dev, jme->mii_if.phy_id, MII_CTRL1000); ctrl1000 &= ~PHY_GAD_TEST_MODE_MSK; ctrl1000 |= PHY_GAD_TEST_MODE_1; jme_mdio_write(jme->dev, jme->mii_if.phy_id, MII_CTRL1000, ctrl1000); phy_data = jme_phy_specreg_read(jme, JM_PHY_EXT_COMM_2_REG); phy_data &= ~JM_PHY_EXT_COMM_2_CALI_MODE_0; phy_data |= JM_PHY_EXT_COMM_2_CALI_LATCH | JM_PHY_EXT_COMM_2_CALI_ENABLE; jme_phy_specreg_write(jme, JM_PHY_EXT_COMM_2_REG, phy_data); msleep(20); phy_data = jme_phy_specreg_read(jme, JM_PHY_EXT_COMM_2_REG); phy_data &= ~(JM_PHY_EXT_COMM_2_CALI_ENABLE | JM_PHY_EXT_COMM_2_CALI_MODE_0 | JM_PHY_EXT_COMM_2_CALI_LATCH); jme_phy_specreg_write(jme, JM_PHY_EXT_COMM_2_REG, phy_data); /* Disable PHY test mode */ ctrl1000 = jme_mdio_read(jme->dev, jme->mii_if.phy_id, MII_CTRL1000); ctrl1000 &= ~PHY_GAD_TEST_MODE_MSK; jme_mdio_write(jme->dev, jme->mii_if.phy_id, MII_CTRL1000, ctrl1000); return 0; } static int jme_phy_setEA(struct jme_adapter *jme) { u32 phy_comm0 = 0, phy_comm1 = 0; u8 nic_ctrl; pci_read_config_byte(jme->pdev, PCI_PRIV_SHARE_NICCTRL, &nic_ctrl); if ((nic_ctrl & 0x3) == JME_FLAG_PHYEA_ENABLE) return 0; switch (jme->pdev->device) { case PCI_DEVICE_ID_JMICRON_JMC250: if (((jme->chip_main_rev == 5) && ((jme->chip_sub_rev == 0) || (jme->chip_sub_rev == 1) || (jme->chip_sub_rev == 3))) || (jme->chip_main_rev >= 6)) { phy_comm0 = 0x008A; phy_comm1 = 0x4109; } if ((jme->chip_main_rev == 3) && ((jme->chip_sub_rev == 1) || (jme->chip_sub_rev == 2))) phy_comm0 = 0xE088; break; case PCI_DEVICE_ID_JMICRON_JMC260: if (((jme->chip_main_rev == 5) && ((jme->chip_sub_rev == 0) || (jme->chip_sub_rev == 1) || (jme->chip_sub_rev == 3))) || (jme->chip_main_rev >= 6)) { phy_comm0 = 0x008A; phy_comm1 = 0x4109; } if ((jme->chip_main_rev == 3) && ((jme->chip_sub_rev == 1) || (jme->chip_sub_rev == 2))) phy_comm0 = 0xE088; if ((jme->chip_main_rev == 2) && (jme->chip_sub_rev == 0)) phy_comm0 = 0x608A; if ((jme->chip_main_rev == 2) && (jme->chip_sub_rev == 2)) phy_comm0 = 0x408A; break; default: return -ENODEV; } if (phy_comm0) jme_phy_specreg_write(jme, JM_PHY_EXT_COMM_0_REG, phy_comm0); if (phy_comm1) jme_phy_specreg_write(jme, JM_PHY_EXT_COMM_1_REG, phy_comm1); return 0; } static int jme_open(struct net_device *netdev) { struct jme_adapter *jme = netdev_priv(netdev); int rc; jme_clear_pm_disable_wol(jme); JME_NAPI_ENABLE(jme); tasklet_setup(&jme->txclean_task, jme_tx_clean_tasklet); tasklet_setup(&jme->rxclean_task, jme_rx_clean_tasklet); tasklet_setup(&jme->rxempty_task, jme_rx_empty_tasklet); rc = jme_request_irq(jme); if (rc) goto err_out; jme_start_irq(jme); jme_phy_on(jme); if (test_bit(JME_FLAG_SSET, &jme->flags)) jme_set_link_ksettings(netdev, &jme->old_cmd); else jme_reset_phy_processor(jme); jme_phy_calibration(jme); jme_phy_setEA(jme); jme_reset_link(jme); return 0; err_out: netif_stop_queue(netdev); netif_carrier_off(netdev); return rc; } static void jme_set_100m_half(struct jme_adapter *jme) { u32 bmcr, tmp; jme_phy_on(jme); bmcr = jme_mdio_read(jme->dev, jme->mii_if.phy_id, MII_BMCR); tmp = bmcr & ~(BMCR_ANENABLE | BMCR_SPEED100 | BMCR_SPEED1000 | BMCR_FULLDPLX); tmp |= BMCR_SPEED100; if (bmcr != tmp) jme_mdio_write(jme->dev, jme->mii_if.phy_id, MII_BMCR, tmp); if (jme->fpgaver) jwrite32(jme, JME_GHC, GHC_SPEED_100M | GHC_LINK_POLL); else jwrite32(jme, JME_GHC, GHC_SPEED_100M); } #define JME_WAIT_LINK_TIME 2000 /* 2000ms */ static void jme_wait_link(struct jme_adapter *jme) { u32 phylink, to = JME_WAIT_LINK_TIME; msleep(1000); phylink = jme_linkstat_from_phy(jme); while (!(phylink & PHY_LINK_UP) && (to -= 10) > 0) { usleep_range(10000, 11000); phylink = jme_linkstat_from_phy(jme); } } static void jme_powersave_phy(struct jme_adapter *jme) { if (jme->reg_pmcs && device_may_wakeup(&jme->pdev->dev)) { jme_set_100m_half(jme); if (jme->reg_pmcs & (PMCS_LFEN | PMCS_LREN)) jme_wait_link(jme); jme_clear_pm_enable_wol(jme); } else { jme_phy_off(jme); } } static int jme_close(struct net_device *netdev) { struct jme_adapter *jme = netdev_priv(netdev); netif_stop_queue(netdev); netif_carrier_off(netdev); jme_stop_irq(jme); jme_free_irq(jme); JME_NAPI_DISABLE(jme); cancel_work_sync(&jme->linkch_task); tasklet_kill(&jme->txclean_task); tasklet_kill(&jme->rxclean_task); tasklet_kill(&jme->rxempty_task); jme_disable_rx_engine(jme); jme_disable_tx_engine(jme); jme_reset_mac_processor(jme); jme_free_rx_resources(jme); jme_free_tx_resources(jme); jme->phylink = 0; jme_phy_off(jme); return 0; } static int jme_alloc_txdesc(struct jme_adapter *jme, struct sk_buff *skb) { struct jme_ring *txring = &(jme->txring[0]); int idx, nr_alloc, mask = jme->tx_ring_mask; idx = txring->next_to_use; nr_alloc = skb_shinfo(skb)->nr_frags + 2; if (unlikely(atomic_read(&txring->nr_free) < nr_alloc)) return -1; atomic_sub(nr_alloc, &txring->nr_free); txring->next_to_use = (txring->next_to_use + nr_alloc) & mask; return idx; } static int jme_fill_tx_map(struct pci_dev *pdev, struct txdesc *txdesc, struct jme_buffer_info *txbi, struct page *page, u32 page_offset, u32 len, bool hidma) { dma_addr_t dmaaddr; dmaaddr = dma_map_page(&pdev->dev, page, page_offset, len, DMA_TO_DEVICE); if (unlikely(dma_mapping_error(&pdev->dev, dmaaddr))) return -EINVAL; dma_sync_single_for_device(&pdev->dev, dmaaddr, len, DMA_TO_DEVICE); txdesc->dw[0] = 0; txdesc->dw[1] = 0; txdesc->desc2.flags = TXFLAG_OWN; txdesc->desc2.flags |= (hidma) ? TXFLAG_64BIT : 0; txdesc->desc2.datalen = cpu_to_le16(len); txdesc->desc2.bufaddrh = cpu_to_le32((__u64)dmaaddr >> 32); txdesc->desc2.bufaddrl = cpu_to_le32( (__u64)dmaaddr & 0xFFFFFFFFUL); txbi->mapping = dmaaddr; txbi->len = len; return 0; } static void jme_drop_tx_map(struct jme_adapter *jme, int startidx, int count) { struct jme_ring *txring = &(jme->txring[0]); struct jme_buffer_info *txbi = txring->bufinf, *ctxbi; int mask = jme->tx_ring_mask; int j; for (j = 0 ; j < count ; j++) { ctxbi = txbi + ((startidx + j + 2) & (mask)); dma_unmap_page(&jme->pdev->dev, ctxbi->mapping, ctxbi->len, DMA_TO_DEVICE); ctxbi->mapping = 0; ctxbi->len = 0; } } static int jme_map_tx_skb(struct jme_adapter *jme, struct sk_buff *skb, int idx) { struct jme_ring *txring = &(jme->txring[0]); struct txdesc *txdesc = txring->desc, *ctxdesc; struct jme_buffer_info *txbi = txring->bufinf, *ctxbi; bool hidma = jme->dev->features & NETIF_F_HIGHDMA; int i, nr_frags = skb_shinfo(skb)->nr_frags; int mask = jme->tx_ring_mask; u32 len; int ret = 0; for (i = 0 ; i < nr_frags ; ++i) { const skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; ctxdesc = txdesc + ((idx + i + 2) & (mask)); ctxbi = txbi + ((idx + i + 2) & (mask)); ret = jme_fill_tx_map(jme->pdev, ctxdesc, ctxbi, skb_frag_page(frag), skb_frag_off(frag), skb_frag_size(frag), hidma); if (ret) { jme_drop_tx_map(jme, idx, i); goto out; } } len = skb_is_nonlinear(skb) ? skb_headlen(skb) : skb->len; ctxdesc = txdesc + ((idx + 1) & (mask)); ctxbi = txbi + ((idx + 1) & (mask)); ret = jme_fill_tx_map(jme->pdev, ctxdesc, ctxbi, virt_to_page(skb->data), offset_in_page(skb->data), len, hidma); if (ret) jme_drop_tx_map(jme, idx, i); out: return ret; } static int jme_tx_tso(struct sk_buff *skb, __le16 *mss, u8 *flags) { *mss = cpu_to_le16(skb_shinfo(skb)->gso_size << TXDESC_MSS_SHIFT); if (*mss) { *flags |= TXFLAG_LSEN; if (skb->protocol == htons(ETH_P_IP)) { struct iphdr *iph = ip_hdr(skb); iph->check = 0; tcp_hdr(skb)->check = ~csum_tcpudp_magic(iph->saddr, iph->daddr, 0, IPPROTO_TCP, 0); } else { tcp_v6_gso_csum_prep(skb); } return 0; } return 1; } static void jme_tx_csum(struct jme_adapter *jme, struct sk_buff *skb, u8 *flags) { if (skb->ip_summed == CHECKSUM_PARTIAL) { u8 ip_proto; switch (skb->protocol) { case htons(ETH_P_IP): ip_proto = ip_hdr(skb)->protocol; break; case htons(ETH_P_IPV6): ip_proto = ipv6_hdr(skb)->nexthdr; break; default: ip_proto = 0; break; } switch (ip_proto) { case IPPROTO_TCP: *flags |= TXFLAG_TCPCS; break; case IPPROTO_UDP: *flags |= TXFLAG_UDPCS; break; default: netif_err(jme, tx_err, jme->dev, "Error upper layer protocol\n"); break; } } } static inline void jme_tx_vlan(struct sk_buff *skb, __le16 *vlan, u8 *flags) { if (skb_vlan_tag_present(skb)) { *flags |= TXFLAG_TAGON; *vlan = cpu_to_le16(skb_vlan_tag_get(skb)); } } static int jme_fill_tx_desc(struct jme_adapter *jme, struct sk_buff *skb, int idx) { struct jme_ring *txring = &(jme->txring[0]); struct txdesc *txdesc; struct jme_buffer_info *txbi; u8 flags; int ret = 0; txdesc = (struct txdesc *)txring->desc + idx; txbi = txring->bufinf + idx; txdesc->dw[0] = 0; txdesc->dw[1] = 0; txdesc->dw[2] = 0; txdesc->dw[3] = 0; txdesc->desc1.pktsize = cpu_to_le16(skb->len); /* * Set OWN bit at final. * When kernel transmit faster than NIC. * And NIC trying to send this descriptor before we tell * it to start sending this TX queue. * Other fields are already filled correctly. */ wmb(); flags = TXFLAG_OWN | TXFLAG_INT; /* * Set checksum flags while not tso */ if (jme_tx_tso(skb, &txdesc->desc1.mss, &flags)) jme_tx_csum(jme, skb, &flags); jme_tx_vlan(skb, &txdesc->desc1.vlan, &flags); ret = jme_map_tx_skb(jme, skb, idx); if (ret) return ret; txdesc->desc1.flags = flags; /* * Set tx buffer info after telling NIC to send * For better tx_clean timing */ wmb(); txbi->nr_desc = skb_shinfo(skb)->nr_frags + 2; txbi->skb = skb; txbi->len = skb->len; txbi->start_xmit = jiffies; if (!txbi->start_xmit) txbi->start_xmit = (0UL-1); return 0; } static void jme_stop_queue_if_full(struct jme_adapter *jme) { struct jme_ring *txring = &(jme->txring[0]); struct jme_buffer_info *txbi = txring->bufinf; int idx = atomic_read(&txring->next_to_clean); txbi += idx; smp_wmb(); if (unlikely(atomic_read(&txring->nr_free) < (MAX_SKB_FRAGS+2))) { netif_stop_queue(jme->dev); netif_info(jme, tx_queued, jme->dev, "TX Queue Paused\n"); smp_wmb(); if (atomic_read(&txring->nr_free) >= (jme->tx_wake_threshold)) { netif_wake_queue(jme->dev); netif_info(jme, tx_queued, jme->dev, "TX Queue Fast Waked\n"); } } if (unlikely(txbi->start_xmit && time_is_before_eq_jiffies(txbi->start_xmit + TX_TIMEOUT) && txbi->skb)) { netif_stop_queue(jme->dev); netif_info(jme, tx_queued, jme->dev, "TX Queue Stopped %d@%lu\n", idx, jiffies); } } /* * This function is already protected by netif_tx_lock() */ static netdev_tx_t jme_start_xmit(struct sk_buff *skb, struct net_device *netdev) { struct jme_adapter *jme = netdev_priv(netdev); int idx; if (unlikely(skb_is_gso(skb) && skb_cow_head(skb, 0))) { dev_kfree_skb_any(skb); ++(NET_STAT(jme).tx_dropped); return NETDEV_TX_OK; } idx = jme_alloc_txdesc(jme, skb); if (unlikely(idx < 0)) { netif_stop_queue(netdev); netif_err(jme, tx_err, jme->dev, "BUG! Tx ring full when queue awake!\n"); return NETDEV_TX_BUSY; } if (jme_fill_tx_desc(jme, skb, idx)) return NETDEV_TX_OK; jwrite32(jme, JME_TXCS, jme->reg_txcs | TXCS_SELECT_QUEUE0 | TXCS_QUEUE0S | TXCS_ENABLE); tx_dbg(jme, "xmit: %d+%d@%lu\n", idx, skb_shinfo(skb)->nr_frags + 2, jiffies); jme_stop_queue_if_full(jme); return NETDEV_TX_OK; } static void jme_set_unicastaddr(struct net_device *netdev) { struct jme_adapter *jme = netdev_priv(netdev); u32 val; val = (netdev->dev_addr[3] & 0xff) << 24 | (netdev->dev_addr[2] & 0xff) << 16 | (netdev->dev_addr[1] & 0xff) << 8 | (netdev->dev_addr[0] & 0xff); jwrite32(jme, JME_RXUMA_LO, val); val = (netdev->dev_addr[5] & 0xff) << 8 | (netdev->dev_addr[4] & 0xff); jwrite32(jme, JME_RXUMA_HI, val); } static int jme_set_macaddr(struct net_device *netdev, void *p) { struct jme_adapter *jme = netdev_priv(netdev); struct sockaddr *addr = p; if (netif_running(netdev)) return -EBUSY; spin_lock_bh(&jme->macaddr_lock); eth_hw_addr_set(netdev, addr->sa_data); jme_set_unicastaddr(netdev); spin_unlock_bh(&jme->macaddr_lock); return 0; } static void jme_set_multi(struct net_device *netdev) { struct jme_adapter *jme = netdev_priv(netdev); u32 mc_hash[2] = {}; spin_lock_bh(&jme->rxmcs_lock); jme->reg_rxmcs |= RXMCS_BRDFRAME | RXMCS_UNIFRAME; if (netdev->flags & IFF_PROMISC) { jme->reg_rxmcs |= RXMCS_ALLFRAME; } else if (netdev->flags & IFF_ALLMULTI) { jme->reg_rxmcs |= RXMCS_ALLMULFRAME; } else if (netdev->flags & IFF_MULTICAST) { struct netdev_hw_addr *ha; int bit_nr; jme->reg_rxmcs |= RXMCS_MULFRAME | RXMCS_MULFILTERED; netdev_for_each_mc_addr(ha, netdev) { bit_nr = ether_crc(ETH_ALEN, ha->addr) & 0x3F; mc_hash[bit_nr >> 5] |= 1 << (bit_nr & 0x1F); } jwrite32(jme, JME_RXMCHT_LO, mc_hash[0]); jwrite32(jme, JME_RXMCHT_HI, mc_hash[1]); } wmb(); jwrite32(jme, JME_RXMCS, jme->reg_rxmcs); spin_unlock_bh(&jme->rxmcs_lock); } static int jme_change_mtu(struct net_device *netdev, int new_mtu) { struct jme_adapter *jme = netdev_priv(netdev); netdev->mtu = new_mtu; netdev_update_features(netdev); jme_restart_rx_engine(jme); jme_reset_link(jme); return 0; } static void jme_tx_timeout(struct net_device *netdev, unsigned int txqueue) { struct jme_adapter *jme = netdev_priv(netdev); jme->phylink = 0; jme_reset_phy_processor(jme); if (test_bit(JME_FLAG_SSET, &jme->flags)) jme_set_link_ksettings(netdev, &jme->old_cmd); /* * Force to Reset the link again */ jme_reset_link(jme); } static void jme_get_drvinfo(struct net_device *netdev, struct ethtool_drvinfo *info) { struct jme_adapter *jme = netdev_priv(netdev); strscpy(info->driver, DRV_NAME, sizeof(info->driver)); strscpy(info->version, DRV_VERSION, sizeof(info->version)); strscpy(info->bus_info, pci_name(jme->pdev), sizeof(info->bus_info)); } static int jme_get_regs_len(struct net_device *netdev) { return JME_REG_LEN; } static void mmapio_memcpy(struct jme_adapter *jme, u32 *p, u32 reg, int len) { int i; for (i = 0 ; i < len ; i += 4) p[i >> 2] = jread32(jme, reg + i); } static void mdio_memcpy(struct jme_adapter *jme, u32 *p, int reg_nr) { int i; u16 *p16 = (u16 *)p; for (i = 0 ; i < reg_nr ; ++i) p16[i] = jme_mdio_read(jme->dev, jme->mii_if.phy_id, i); } static void jme_get_regs(struct net_device *netdev, struct ethtool_regs *regs, void *p) { struct jme_adapter *jme = netdev_priv(netdev); u32 *p32 = (u32 *)p; memset(p, 0xFF, JME_REG_LEN); regs->version = 1; mmapio_memcpy(jme, p32, JME_MAC, JME_MAC_LEN); p32 += 0x100 >> 2; mmapio_memcpy(jme, p32, JME_PHY, JME_PHY_LEN); p32 += 0x100 >> 2; mmapio_memcpy(jme, p32, JME_MISC, JME_MISC_LEN); p32 += 0x100 >> 2; mmapio_memcpy(jme, p32, JME_RSS, JME_RSS_LEN); p32 += 0x100 >> 2; mdio_memcpy(jme, p32, JME_PHY_REG_NR); } static int jme_get_coalesce(struct net_device *netdev, struct ethtool_coalesce *ecmd, struct kernel_ethtool_coalesce *kernel_coal, struct netlink_ext_ack *extack) { struct jme_adapter *jme = netdev_priv(netdev); ecmd->tx_coalesce_usecs = PCC_TX_TO; ecmd->tx_max_coalesced_frames = PCC_TX_CNT; if (test_bit(JME_FLAG_POLL, &jme->flags)) { ecmd->use_adaptive_rx_coalesce = false; ecmd->rx_coalesce_usecs = 0; ecmd->rx_max_coalesced_frames = 0; return 0; } ecmd->use_adaptive_rx_coalesce = true; switch (jme->dpi.cur) { case PCC_P1: ecmd->rx_coalesce_usecs = PCC_P1_TO; ecmd->rx_max_coalesced_frames = PCC_P1_CNT; break; case PCC_P2: ecmd->rx_coalesce_usecs = PCC_P2_TO; ecmd->rx_max_coalesced_frames = PCC_P2_CNT; break; case PCC_P3: ecmd->rx_coalesce_usecs = PCC_P3_TO; ecmd->rx_max_coalesced_frames = PCC_P3_CNT; break; default: break; } return 0; } static int jme_set_coalesce(struct net_device *netdev, struct ethtool_coalesce *ecmd, struct kernel_ethtool_coalesce *kernel_coal, struct netlink_ext_ack *extack) { struct jme_adapter *jme = netdev_priv(netdev); struct dynpcc_info *dpi = &(jme->dpi); if (netif_running(netdev)) return -EBUSY; if (ecmd->use_adaptive_rx_coalesce && test_bit(JME_FLAG_POLL, &jme->flags)) { clear_bit(JME_FLAG_POLL, &jme->flags); jme->jme_rx = netif_rx; dpi->cur = PCC_P1; dpi->attempt = PCC_P1; dpi->cnt = 0; jme_set_rx_pcc(jme, PCC_P1); jme_interrupt_mode(jme); } else if (!(ecmd->use_adaptive_rx_coalesce) && !(test_bit(JME_FLAG_POLL, &jme->flags))) { set_bit(JME_FLAG_POLL, &jme->flags); jme->jme_rx = netif_receive_skb; jme_interrupt_mode(jme); } return 0; } static void jme_get_pauseparam(struct net_device *netdev, struct ethtool_pauseparam *ecmd) { struct jme_adapter *jme = netdev_priv(netdev); u32 val; ecmd->tx_pause = (jme->reg_txpfc & TXPFC_PF_EN) != 0; ecmd->rx_pause = (jme->reg_rxmcs & RXMCS_FLOWCTRL) != 0; spin_lock_bh(&jme->phy_lock); val = jme_mdio_read(jme->dev, jme->mii_if.phy_id, MII_ADVERTISE); spin_unlock_bh(&jme->phy_lock); ecmd->autoneg = (val & (ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM)) != 0; } static int jme_set_pauseparam(struct net_device *netdev, struct ethtool_pauseparam *ecmd) { struct jme_adapter *jme = netdev_priv(netdev); u32 val; if (((jme->reg_txpfc & TXPFC_PF_EN) != 0) ^ (ecmd->tx_pause != 0)) { if (ecmd->tx_pause) jme->reg_txpfc |= TXPFC_PF_EN; else jme->reg_txpfc &= ~TXPFC_PF_EN; jwrite32(jme, JME_TXPFC, jme->reg_txpfc); } spin_lock_bh(&jme->rxmcs_lock); if (((jme->reg_rxmcs & RXMCS_FLOWCTRL) != 0) ^ (ecmd->rx_pause != 0)) { if (ecmd->rx_pause) jme->reg_rxmcs |= RXMCS_FLOWCTRL; else jme->reg_rxmcs &= ~RXMCS_FLOWCTRL; jwrite32(jme, JME_RXMCS, jme->reg_rxmcs); } spin_unlock_bh(&jme->rxmcs_lock); spin_lock_bh(&jme->phy_lock); val = jme_mdio_read(jme->dev, jme->mii_if.phy_id, MII_ADVERTISE); if (((val & (ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM)) != 0) ^ (ecmd->autoneg != 0)) { if (ecmd->autoneg) val |= (ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM); else val &= ~(ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM); jme_mdio_write(jme->dev, jme->mii_if.phy_id, MII_ADVERTISE, val); } spin_unlock_bh(&jme->phy_lock); return 0; } static void jme_get_wol(struct net_device *netdev, struct ethtool_wolinfo *wol) { struct jme_adapter *jme = netdev_priv(netdev); wol->supported = WAKE_MAGIC | WAKE_PHY; wol->wolopts = 0; if (jme->reg_pmcs & (PMCS_LFEN | PMCS_LREN)) wol->wolopts |= WAKE_PHY; if (jme->reg_pmcs & PMCS_MFEN) wol->wolopts |= WAKE_MAGIC; } static int jme_set_wol(struct net_device *netdev, struct ethtool_wolinfo *wol) { struct jme_adapter *jme = netdev_priv(netdev); if (wol->wolopts & (WAKE_MAGICSECURE | WAKE_UCAST | WAKE_MCAST | WAKE_BCAST | WAKE_ARP)) return -EOPNOTSUPP; jme->reg_pmcs = 0; if (wol->wolopts & WAKE_PHY) jme->reg_pmcs |= PMCS_LFEN | PMCS_LREN; if (wol->wolopts & WAKE_MAGIC) jme->reg_pmcs |= PMCS_MFEN; return 0; } static int jme_get_link_ksettings(struct net_device *netdev, struct ethtool_link_ksettings *cmd) { struct jme_adapter *jme = netdev_priv(netdev); spin_lock_bh(&jme->phy_lock); mii_ethtool_get_link_ksettings(&jme->mii_if, cmd); spin_unlock_bh(&jme->phy_lock); return 0; } static int jme_set_link_ksettings(struct net_device *netdev, const struct ethtool_link_ksettings *cmd) { struct jme_adapter *jme = netdev_priv(netdev); int rc, fdc = 0; if (cmd->base.speed == SPEED_1000 && cmd->base.autoneg != AUTONEG_ENABLE) return -EINVAL; /* * Check If user changed duplex only while force_media. * Hardware would not generate link change interrupt. */ if (jme->mii_if.force_media && cmd->base.autoneg != AUTONEG_ENABLE && (jme->mii_if.full_duplex != cmd->base.duplex)) fdc = 1; spin_lock_bh(&jme->phy_lock); rc = mii_ethtool_set_link_ksettings(&jme->mii_if, cmd); spin_unlock_bh(&jme->phy_lock); if (!rc) { if (fdc) jme_reset_link(jme); jme->old_cmd = *cmd; set_bit(JME_FLAG_SSET, &jme->flags); } return rc; } static int jme_ioctl(struct net_device *netdev, struct ifreq *rq, int cmd) { int rc; struct jme_adapter *jme = netdev_priv(netdev); struct mii_ioctl_data *mii_data = if_mii(rq); unsigned int duplex_chg; if (cmd == SIOCSMIIREG) { u16 val = mii_data->val_in; if (!(val & (BMCR_RESET|BMCR_ANENABLE)) && (val & BMCR_SPEED1000)) return -EINVAL; } spin_lock_bh(&jme->phy_lock); rc = generic_mii_ioctl(&jme->mii_if, mii_data, cmd, &duplex_chg); spin_unlock_bh(&jme->phy_lock); if (!rc && (cmd == SIOCSMIIREG)) { if (duplex_chg) jme_reset_link(jme); jme_get_link_ksettings(netdev, &jme->old_cmd); set_bit(JME_FLAG_SSET, &jme->flags); } return rc; } static u32 jme_get_link(struct net_device *netdev) { struct jme_adapter *jme = netdev_priv(netdev); return jread32(jme, JME_PHY_LINK) & PHY_LINK_UP; } static u32 jme_get_msglevel(struct net_device *netdev) { struct jme_adapter *jme = netdev_priv(netdev); return jme->msg_enable; } static void jme_set_msglevel(struct net_device *netdev, u32 value) { struct jme_adapter *jme = netdev_priv(netdev); jme->msg_enable = value; } static netdev_features_t jme_fix_features(struct net_device *netdev, netdev_features_t features) { if (netdev->mtu > 1900) features &= ~(NETIF_F_ALL_TSO | NETIF_F_CSUM_MASK); return features; } static int jme_set_features(struct net_device *netdev, netdev_features_t features) { struct jme_adapter *jme = netdev_priv(netdev); spin_lock_bh(&jme->rxmcs_lock); if (features & NETIF_F_RXCSUM) jme->reg_rxmcs |= RXMCS_CHECKSUM; else jme->reg_rxmcs &= ~RXMCS_CHECKSUM; jwrite32(jme, JME_RXMCS, jme->reg_rxmcs); spin_unlock_bh(&jme->rxmcs_lock); return 0; } #ifdef CONFIG_NET_POLL_CONTROLLER static void jme_netpoll(struct net_device *dev) { unsigned long flags; local_irq_save(flags); jme_intr(dev->irq, dev); local_irq_restore(flags); } #endif static int jme_nway_reset(struct net_device *netdev) { struct jme_adapter *jme = netdev_priv(netdev); jme_restart_an(jme); return 0; } static u8 jme_smb_read(struct jme_adapter *jme, unsigned int addr) { u32 val; int to; val = jread32(jme, JME_SMBCSR); to = JME_SMB_BUSY_TIMEOUT; while ((val & SMBCSR_BUSY) && --to) { msleep(1); val = jread32(jme, JME_SMBCSR); } if (!to) { netif_err(jme, hw, jme->dev, "SMB Bus Busy\n"); return 0xFF; } jwrite32(jme, JME_SMBINTF, ((addr << SMBINTF_HWADDR_SHIFT) & SMBINTF_HWADDR) | SMBINTF_HWRWN_READ | SMBINTF_HWCMD); val = jread32(jme, JME_SMBINTF); to = JME_SMB_BUSY_TIMEOUT; while ((val & SMBINTF_HWCMD) && --to) { msleep(1); val = jread32(jme, JME_SMBINTF); } if (!to) { netif_err(jme, hw, jme->dev, "SMB Bus Busy\n"); return 0xFF; } return (val & SMBINTF_HWDATR) >> SMBINTF_HWDATR_SHIFT; } static void jme_smb_write(struct jme_adapter *jme, unsigned int addr, u8 data) { u32 val; int to; val = jread32(jme, JME_SMBCSR); to = JME_SMB_BUSY_TIMEOUT; while ((val & SMBCSR_BUSY) && --to) { msleep(1); val = jread32(jme, JME_SMBCSR); } if (!to) { netif_err(jme, hw, jme->dev, "SMB Bus Busy\n"); return; } jwrite32(jme, JME_SMBINTF, ((data << SMBINTF_HWDATW_SHIFT) & SMBINTF_HWDATW) | ((addr << SMBINTF_HWADDR_SHIFT) & SMBINTF_HWADDR) | SMBINTF_HWRWN_WRITE | SMBINTF_HWCMD); val = jread32(jme, JME_SMBINTF); to = JME_SMB_BUSY_TIMEOUT; while ((val & SMBINTF_HWCMD) && --to) { msleep(1); val = jread32(jme, JME_SMBINTF); } if (!to) { netif_err(jme, hw, jme->dev, "SMB Bus Busy\n"); return; } mdelay(2); } static int jme_get_eeprom_len(struct net_device *netdev) { struct jme_adapter *jme = netdev_priv(netdev); u32 val; val = jread32(jme, JME_SMBCSR); return (val & SMBCSR_EEPROMD) ? JME_SMB_LEN : 0; } static int jme_get_eeprom(struct net_device *netdev, struct ethtool_eeprom *eeprom, u8 *data) { struct jme_adapter *jme = netdev_priv(netdev); int i, offset = eeprom->offset, len = eeprom->len; /* * ethtool will check the boundary for us */ eeprom->magic = JME_EEPROM_MAGIC; for (i = 0 ; i < len ; ++i) data[i] = jme_smb_read(jme, i + offset); return 0; } static int jme_set_eeprom(struct net_device *netdev, struct ethtool_eeprom *eeprom, u8 *data) { struct jme_adapter *jme = netdev_priv(netdev); int i, offset = eeprom->offset, len = eeprom->len; if (eeprom->magic != JME_EEPROM_MAGIC) return -EINVAL; /* * ethtool will check the boundary for us */ for (i = 0 ; i < len ; ++i) jme_smb_write(jme, i + offset, data[i]); return 0; } static const struct ethtool_ops jme_ethtool_ops = { .supported_coalesce_params = ETHTOOL_COALESCE_USECS | ETHTOOL_COALESCE_MAX_FRAMES | ETHTOOL_COALESCE_USE_ADAPTIVE_RX, .get_drvinfo = jme_get_drvinfo, .get_regs_len = jme_get_regs_len, .get_regs = jme_get_regs, .get_coalesce = jme_get_coalesce, .set_coalesce = jme_set_coalesce, .get_pauseparam = jme_get_pauseparam, .set_pauseparam = jme_set_pauseparam, .get_wol = jme_get_wol, .set_wol = jme_set_wol, .get_link = jme_get_link, .get_msglevel = jme_get_msglevel, .set_msglevel = jme_set_msglevel, .nway_reset = jme_nway_reset, .get_eeprom_len = jme_get_eeprom_len, .get_eeprom = jme_get_eeprom, .set_eeprom = jme_set_eeprom, .get_link_ksettings = jme_get_link_ksettings, .set_link_ksettings = jme_set_link_ksettings, }; static int jme_pci_dma64(struct pci_dev *pdev) { if (pdev->device == PCI_DEVICE_ID_JMICRON_JMC250 && !dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64))) return 1; if (pdev->device == PCI_DEVICE_ID_JMICRON_JMC250 && !dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(40))) return 1; if (!dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32))) return 0; return -1; } static inline void jme_phy_init(struct jme_adapter *jme) { u16 reg26; reg26 = jme_mdio_read(jme->dev, jme->mii_if.phy_id, 26); jme_mdio_write(jme->dev, jme->mii_if.phy_id, 26, reg26 | 0x1000); } static inline void jme_check_hw_ver(struct jme_adapter *jme) { u32 chipmode; chipmode = jread32(jme, JME_CHIPMODE); jme->fpgaver = (chipmode & CM_FPGAVER_MASK) >> CM_FPGAVER_SHIFT; jme->chiprev = (chipmode & CM_CHIPREV_MASK) >> CM_CHIPREV_SHIFT; jme->chip_main_rev = jme->chiprev & 0xF; jme->chip_sub_rev = (jme->chiprev >> 4) & 0xF; } static const struct net_device_ops jme_netdev_ops = { .ndo_open = jme_open, .ndo_stop = jme_close, .ndo_validate_addr = eth_validate_addr, .ndo_eth_ioctl = jme_ioctl, .ndo_start_xmit = jme_start_xmit, .ndo_set_mac_address = jme_set_macaddr, .ndo_set_rx_mode = jme_set_multi, .ndo_change_mtu = jme_change_mtu, .ndo_tx_timeout = jme_tx_timeout, .ndo_fix_features = jme_fix_features, .ndo_set_features = jme_set_features, #ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = jme_netpoll, #endif }; static int jme_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) { int rc = 0, using_dac, i; struct net_device *netdev; struct jme_adapter *jme; u16 bmcr, bmsr; u32 apmc; /* * set up PCI device basics */ pci_disable_link_state(pdev, PCIE_LINK_STATE_L0S | PCIE_LINK_STATE_L1 | PCIE_LINK_STATE_CLKPM); rc = pci_enable_device(pdev); if (rc) { pr_err("Cannot enable PCI device\n"); goto err_out; } using_dac = jme_pci_dma64(pdev); if (using_dac < 0) { pr_err("Cannot set PCI DMA Mask\n"); rc = -EIO; goto err_out_disable_pdev; } if (!(pci_resource_flags(pdev, 0) & IORESOURCE_MEM)) { pr_err("No PCI resource region found\n"); rc = -ENOMEM; goto err_out_disable_pdev; } rc = pci_request_regions(pdev, DRV_NAME); if (rc) { pr_err("Cannot obtain PCI resource region\n"); goto err_out_disable_pdev; } pci_set_master(pdev); /* * alloc and init net device */ netdev = alloc_etherdev(sizeof(*jme)); if (!netdev) { rc = -ENOMEM; goto err_out_release_regions; } netdev->netdev_ops = &jme_netdev_ops; netdev->ethtool_ops = &jme_ethtool_ops; netdev->watchdog_timeo = TX_TIMEOUT; netdev->hw_features = NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM | NETIF_F_SG | NETIF_F_TSO | NETIF_F_TSO6 | NETIF_F_RXCSUM; netdev->features = NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM | NETIF_F_SG | NETIF_F_TSO | NETIF_F_TSO6 | NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX; if (using_dac) netdev->features |= NETIF_F_HIGHDMA; /* MTU range: 1280 - 9202*/ netdev->min_mtu = IPV6_MIN_MTU; netdev->max_mtu = MAX_ETHERNET_JUMBO_PACKET_SIZE - ETH_HLEN; SET_NETDEV_DEV(netdev, &pdev->dev); pci_set_drvdata(pdev, netdev); /* * init adapter info */ jme = netdev_priv(netdev); jme->pdev = pdev; jme->dev = netdev; jme->jme_rx = netif_rx; jme->old_mtu = netdev->mtu = 1500; jme->phylink = 0; jme->tx_ring_size = 1 << 10; jme->tx_ring_mask = jme->tx_ring_size - 1; jme->tx_wake_threshold = 1 << 9; jme->rx_ring_size = 1 << 9; jme->rx_ring_mask = jme->rx_ring_size - 1; jme->msg_enable = JME_DEF_MSG_ENABLE; jme->regs = ioremap(pci_resource_start(pdev, 0), pci_resource_len(pdev, 0)); if (!(jme->regs)) { pr_err("Mapping PCI resource region error\n"); rc = -ENOMEM; goto err_out_free_netdev; } if (no_pseudohp) { apmc = jread32(jme, JME_APMC) & ~JME_APMC_PSEUDO_HP_EN; jwrite32(jme, JME_APMC, apmc); } else if (force_pseudohp) { apmc = jread32(jme, JME_APMC) | JME_APMC_PSEUDO_HP_EN; jwrite32(jme, JME_APMC, apmc); } netif_napi_add(netdev, &jme->napi, jme_poll); spin_lock_init(&jme->phy_lock); spin_lock_init(&jme->macaddr_lock); spin_lock_init(&jme->rxmcs_lock); atomic_set(&jme->link_changing, 1); atomic_set(&jme->rx_cleaning, 1); atomic_set(&jme->tx_cleaning, 1); atomic_set(&jme->rx_empty, 1); tasklet_setup(&jme->pcc_task, jme_pcc_tasklet); INIT_WORK(&jme->linkch_task, jme_link_change_work); jme->dpi.cur = PCC_P1; jme->reg_ghc = 0; jme->reg_rxcs = RXCS_DEFAULT; jme->reg_rxmcs = RXMCS_DEFAULT; jme->reg_txpfc = 0; jme->reg_pmcs = PMCS_MFEN; jme->reg_gpreg1 = GPREG1_DEFAULT; if (jme->reg_rxmcs & RXMCS_CHECKSUM) netdev->features |= NETIF_F_RXCSUM; /* * Get Max Read Req Size from PCI Config Space */ pci_read_config_byte(pdev, PCI_DCSR_MRRS, &jme->mrrs); jme->mrrs &= PCI_DCSR_MRRS_MASK; switch (jme->mrrs) { case MRRS_128B: jme->reg_txcs = TXCS_DEFAULT | TXCS_DMASIZE_128B; break; case MRRS_256B: jme->reg_txcs = TXCS_DEFAULT | TXCS_DMASIZE_256B; break; default: jme->reg_txcs = TXCS_DEFAULT | TXCS_DMASIZE_512B; break; } /* * Must check before reset_mac_processor */ jme_check_hw_ver(jme); jme->mii_if.dev = netdev; if (jme->fpgaver) { jme->mii_if.phy_id = 0; for (i = 1 ; i < 32 ; ++i) { bmcr = jme_mdio_read(netdev, i, MII_BMCR); bmsr = jme_mdio_read(netdev, i, MII_BMSR); if (bmcr != 0xFFFFU && (bmcr != 0 || bmsr != 0)) { jme->mii_if.phy_id = i; break; } } if (!jme->mii_if.phy_id) { rc = -EIO; pr_err("Can not find phy_id\n"); goto err_out_unmap; } jme->reg_ghc |= GHC_LINK_POLL; } else { jme->mii_if.phy_id = 1; } if (pdev->device == PCI_DEVICE_ID_JMICRON_JMC250) jme->mii_if.supports_gmii = true; else jme->mii_if.supports_gmii = false; jme->mii_if.phy_id_mask = 0x1F; jme->mii_if.reg_num_mask = 0x1F; jme->mii_if.mdio_read = jme_mdio_read; jme->mii_if.mdio_write = jme_mdio_write; jme_clear_pm_disable_wol(jme); device_init_wakeup(&pdev->dev, true); jme_set_phyfifo_5level(jme); jme->pcirev = pdev->revision; if (!jme->fpgaver) jme_phy_init(jme); jme_phy_off(jme); /* * Reset MAC processor and reload EEPROM for MAC Address */ jme_reset_mac_processor(jme); rc = jme_reload_eeprom(jme); if (rc) { pr_err("Reload eeprom for reading MAC Address error\n"); goto err_out_unmap; } jme_load_macaddr(netdev); /* * Tell stack that we are not ready to work until open() */ netif_carrier_off(netdev); rc = register_netdev(netdev); if (rc) { pr_err("Cannot register net device\n"); goto err_out_unmap; } netif_info(jme, probe, jme->dev, "%s%s chiprev:%x pcirev:%x macaddr:%pM\n", (jme->pdev->device == PCI_DEVICE_ID_JMICRON_JMC250) ? "JMC250 Gigabit Ethernet" : (jme->pdev->device == PCI_DEVICE_ID_JMICRON_JMC260) ? "JMC260 Fast Ethernet" : "Unknown", (jme->fpgaver != 0) ? " (FPGA)" : "", (jme->fpgaver != 0) ? jme->fpgaver : jme->chiprev, jme->pcirev, netdev->dev_addr); return 0; err_out_unmap: iounmap(jme->regs); err_out_free_netdev: free_netdev(netdev); err_out_release_regions: pci_release_regions(pdev); err_out_disable_pdev: pci_disable_device(pdev); err_out: return rc; } static void jme_remove_one(struct pci_dev *pdev) { struct net_device *netdev = pci_get_drvdata(pdev); struct jme_adapter *jme = netdev_priv(netdev); unregister_netdev(netdev); iounmap(jme->regs); free_netdev(netdev); pci_release_regions(pdev); pci_disable_device(pdev); } static void jme_shutdown(struct pci_dev *pdev) { struct net_device *netdev = pci_get_drvdata(pdev); struct jme_adapter *jme = netdev_priv(netdev); jme_powersave_phy(jme); pci_pme_active(pdev, true); } #ifdef CONFIG_PM_SLEEP static int jme_suspend(struct device *dev) { struct net_device *netdev = dev_get_drvdata(dev); struct jme_adapter *jme = netdev_priv(netdev); if (!netif_running(netdev)) return 0; atomic_dec(&jme->link_changing); netif_device_detach(netdev); netif_stop_queue(netdev); jme_stop_irq(jme); tasklet_disable(&jme->txclean_task); tasklet_disable(&jme->rxclean_task); tasklet_disable(&jme->rxempty_task); if (netif_carrier_ok(netdev)) { if (test_bit(JME_FLAG_POLL, &jme->flags)) jme_polling_mode(jme); jme_stop_pcc_timer(jme); jme_disable_rx_engine(jme); jme_disable_tx_engine(jme); jme_reset_mac_processor(jme); jme_free_rx_resources(jme); jme_free_tx_resources(jme); netif_carrier_off(netdev); jme->phylink = 0; } tasklet_enable(&jme->txclean_task); tasklet_enable(&jme->rxclean_task); tasklet_enable(&jme->rxempty_task); jme_powersave_phy(jme); return 0; } static int jme_resume(struct device *dev) { struct net_device *netdev = dev_get_drvdata(dev); struct jme_adapter *jme = netdev_priv(netdev); if (!netif_running(netdev)) return 0; jme_clear_pm_disable_wol(jme); jme_phy_on(jme); if (test_bit(JME_FLAG_SSET, &jme->flags)) jme_set_link_ksettings(netdev, &jme->old_cmd); else jme_reset_phy_processor(jme); jme_phy_calibration(jme); jme_phy_setEA(jme); netif_device_attach(netdev); atomic_inc(&jme->link_changing); jme_reset_link(jme); jme_start_irq(jme); return 0; } static SIMPLE_DEV_PM_OPS(jme_pm_ops, jme_suspend, jme_resume); #define JME_PM_OPS (&jme_pm_ops) #else #define JME_PM_OPS NULL #endif static const struct pci_device_id jme_pci_tbl[] = { { PCI_VDEVICE(JMICRON, PCI_DEVICE_ID_JMICRON_JMC250) }, { PCI_VDEVICE(JMICRON, PCI_DEVICE_ID_JMICRON_JMC260) }, { } }; static struct pci_driver jme_driver = { .name = DRV_NAME, .id_table = jme_pci_tbl, .probe = jme_init_one, .remove = jme_remove_one, .shutdown = jme_shutdown, .driver.pm = JME_PM_OPS, }; static int __init jme_init_module(void) { pr_info("JMicron JMC2XX ethernet driver version %s\n", DRV_VERSION); return pci_register_driver(&jme_driver); } static void __exit jme_cleanup_module(void) { pci_unregister_driver(&jme_driver); } module_init(jme_init_module); module_exit(jme_cleanup_module); MODULE_AUTHOR("Guo-Fu Tseng <[email protected]>"); MODULE_DESCRIPTION("JMicron JMC2x0 PCI Express Ethernet driver"); MODULE_LICENSE("GPL"); MODULE_VERSION(DRV_VERSION); MODULE_DEVICE_TABLE(pci, jme_pci_tbl);
linux-master
drivers/net/ethernet/jme.c
// SPDX-License-Identifier: GPL-2.0 /* * Lantiq / Intel PMAC driver for XRX200 SoCs * * Copyright (C) 2010 Lantiq Deutschland * Copyright (C) 2012 John Crispin <[email protected]> * Copyright (C) 2017 - 2018 Hauke Mehrtens <[email protected]> */ #include <linux/etherdevice.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/interrupt.h> #include <linux/clk.h> #include <linux/delay.h> #include <linux/if_vlan.h> #include <linux/of_net.h> #include <linux/of_platform.h> #include <xway_dma.h> /* DMA */ #define XRX200_DMA_DATA_LEN (SZ_64K - 1) #define XRX200_DMA_RX 0 #define XRX200_DMA_TX 1 #define XRX200_DMA_BURST_LEN 8 #define XRX200_DMA_PACKET_COMPLETE 0 #define XRX200_DMA_PACKET_IN_PROGRESS 1 /* cpu port mac */ #define PMAC_RX_IPG 0x0024 #define PMAC_RX_IPG_MASK 0xf #define PMAC_HD_CTL 0x0000 /* Add Ethernet header to packets from DMA to PMAC */ #define PMAC_HD_CTL_ADD BIT(0) /* Add VLAN tag to Packets from DMA to PMAC */ #define PMAC_HD_CTL_TAG BIT(1) /* Add CRC to packets from DMA to PMAC */ #define PMAC_HD_CTL_AC BIT(2) /* Add status header to packets from PMAC to DMA */ #define PMAC_HD_CTL_AS BIT(3) /* Remove CRC from packets from PMAC to DMA */ #define PMAC_HD_CTL_RC BIT(4) /* Remove Layer-2 header from packets from PMAC to DMA */ #define PMAC_HD_CTL_RL2 BIT(5) /* Status header is present from DMA to PMAC */ #define PMAC_HD_CTL_RXSH BIT(6) /* Add special tag from PMAC to switch */ #define PMAC_HD_CTL_AST BIT(7) /* Remove specail Tag from PMAC to DMA */ #define PMAC_HD_CTL_RST BIT(8) /* Check CRC from DMA to PMAC */ #define PMAC_HD_CTL_CCRC BIT(9) /* Enable reaction to Pause frames in the PMAC */ #define PMAC_HD_CTL_FC BIT(10) struct xrx200_chan { int tx_free; struct napi_struct napi; struct ltq_dma_channel dma; union { struct sk_buff *skb[LTQ_DESC_NUM]; void *rx_buff[LTQ_DESC_NUM]; }; struct sk_buff *skb_head; struct sk_buff *skb_tail; struct xrx200_priv *priv; }; struct xrx200_priv { struct clk *clk; struct xrx200_chan chan_tx; struct xrx200_chan chan_rx; u16 rx_buf_size; u16 rx_skb_size; struct net_device *net_dev; struct device *dev; __iomem void *pmac_reg; }; static u32 xrx200_pmac_r32(struct xrx200_priv *priv, u32 offset) { return __raw_readl(priv->pmac_reg + offset); } static void xrx200_pmac_w32(struct xrx200_priv *priv, u32 val, u32 offset) { __raw_writel(val, priv->pmac_reg + offset); } static void xrx200_pmac_mask(struct xrx200_priv *priv, u32 clear, u32 set, u32 offset) { u32 val = xrx200_pmac_r32(priv, offset); val &= ~(clear); val |= set; xrx200_pmac_w32(priv, val, offset); } static int xrx200_max_frame_len(int mtu) { return VLAN_ETH_HLEN + mtu; } static int xrx200_buffer_size(int mtu) { return round_up(xrx200_max_frame_len(mtu), 4 * XRX200_DMA_BURST_LEN); } static int xrx200_skb_size(u16 buf_size) { return SKB_DATA_ALIGN(buf_size + NET_SKB_PAD + NET_IP_ALIGN) + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); } /* drop all the packets from the DMA ring */ static void xrx200_flush_dma(struct xrx200_chan *ch) { int i; for (i = 0; i < LTQ_DESC_NUM; i++) { struct ltq_dma_desc *desc = &ch->dma.desc_base[ch->dma.desc]; if ((desc->ctl & (LTQ_DMA_OWN | LTQ_DMA_C)) != LTQ_DMA_C) break; desc->ctl = LTQ_DMA_OWN | LTQ_DMA_RX_OFFSET(NET_IP_ALIGN) | ch->priv->rx_buf_size; ch->dma.desc++; ch->dma.desc %= LTQ_DESC_NUM; } } static int xrx200_open(struct net_device *net_dev) { struct xrx200_priv *priv = netdev_priv(net_dev); napi_enable(&priv->chan_tx.napi); ltq_dma_open(&priv->chan_tx.dma); ltq_dma_enable_irq(&priv->chan_tx.dma); napi_enable(&priv->chan_rx.napi); ltq_dma_open(&priv->chan_rx.dma); /* The boot loader does not always deactivate the receiving of frames * on the ports and then some packets queue up in the PPE buffers. * They already passed the PMAC so they do not have the tags * configured here. Read the these packets here and drop them. * The HW should have written them into memory after 10us */ usleep_range(20, 40); xrx200_flush_dma(&priv->chan_rx); ltq_dma_enable_irq(&priv->chan_rx.dma); netif_wake_queue(net_dev); return 0; } static int xrx200_close(struct net_device *net_dev) { struct xrx200_priv *priv = netdev_priv(net_dev); netif_stop_queue(net_dev); napi_disable(&priv->chan_rx.napi); ltq_dma_close(&priv->chan_rx.dma); napi_disable(&priv->chan_tx.napi); ltq_dma_close(&priv->chan_tx.dma); return 0; } static int xrx200_alloc_buf(struct xrx200_chan *ch, void *(*alloc)(unsigned int size)) { void *buf = ch->rx_buff[ch->dma.desc]; struct xrx200_priv *priv = ch->priv; dma_addr_t mapping; int ret = 0; ch->rx_buff[ch->dma.desc] = alloc(priv->rx_skb_size); if (!ch->rx_buff[ch->dma.desc]) { ch->rx_buff[ch->dma.desc] = buf; ret = -ENOMEM; goto skip; } mapping = dma_map_single(priv->dev, ch->rx_buff[ch->dma.desc], priv->rx_buf_size, DMA_FROM_DEVICE); if (unlikely(dma_mapping_error(priv->dev, mapping))) { skb_free_frag(ch->rx_buff[ch->dma.desc]); ch->rx_buff[ch->dma.desc] = buf; ret = -ENOMEM; goto skip; } ch->dma.desc_base[ch->dma.desc].addr = mapping + NET_SKB_PAD + NET_IP_ALIGN; /* Make sure the address is written before we give it to HW */ wmb(); skip: ch->dma.desc_base[ch->dma.desc].ctl = LTQ_DMA_OWN | LTQ_DMA_RX_OFFSET(NET_IP_ALIGN) | priv->rx_buf_size; return ret; } static int xrx200_hw_receive(struct xrx200_chan *ch) { struct xrx200_priv *priv = ch->priv; struct ltq_dma_desc *desc = &ch->dma.desc_base[ch->dma.desc]; void *buf = ch->rx_buff[ch->dma.desc]; u32 ctl = desc->ctl; int len = (ctl & LTQ_DMA_SIZE_MASK); struct net_device *net_dev = priv->net_dev; struct sk_buff *skb; int ret; ret = xrx200_alloc_buf(ch, napi_alloc_frag); ch->dma.desc++; ch->dma.desc %= LTQ_DESC_NUM; if (ret) { net_dev->stats.rx_dropped++; netdev_err(net_dev, "failed to allocate new rx buffer\n"); return ret; } skb = build_skb(buf, priv->rx_skb_size); if (!skb) { skb_free_frag(buf); net_dev->stats.rx_dropped++; return -ENOMEM; } skb_reserve(skb, NET_SKB_PAD); skb_put(skb, len); /* add buffers to skb via skb->frag_list */ if (ctl & LTQ_DMA_SOP) { ch->skb_head = skb; ch->skb_tail = skb; skb_reserve(skb, NET_IP_ALIGN); } else if (ch->skb_head) { if (ch->skb_head == ch->skb_tail) skb_shinfo(ch->skb_tail)->frag_list = skb; else ch->skb_tail->next = skb; ch->skb_tail = skb; ch->skb_head->len += skb->len; ch->skb_head->data_len += skb->len; ch->skb_head->truesize += skb->truesize; } if (ctl & LTQ_DMA_EOP) { ch->skb_head->protocol = eth_type_trans(ch->skb_head, net_dev); net_dev->stats.rx_packets++; net_dev->stats.rx_bytes += ch->skb_head->len; netif_receive_skb(ch->skb_head); ch->skb_head = NULL; ch->skb_tail = NULL; ret = XRX200_DMA_PACKET_COMPLETE; } else { ret = XRX200_DMA_PACKET_IN_PROGRESS; } return ret; } static int xrx200_poll_rx(struct napi_struct *napi, int budget) { struct xrx200_chan *ch = container_of(napi, struct xrx200_chan, napi); int rx = 0; int ret; while (rx < budget) { struct ltq_dma_desc *desc = &ch->dma.desc_base[ch->dma.desc]; if ((desc->ctl & (LTQ_DMA_OWN | LTQ_DMA_C)) == LTQ_DMA_C) { ret = xrx200_hw_receive(ch); if (ret == XRX200_DMA_PACKET_IN_PROGRESS) continue; if (ret != XRX200_DMA_PACKET_COMPLETE) break; rx++; } else { break; } } if (rx < budget) { if (napi_complete_done(&ch->napi, rx)) ltq_dma_enable_irq(&ch->dma); } return rx; } static int xrx200_tx_housekeeping(struct napi_struct *napi, int budget) { struct xrx200_chan *ch = container_of(napi, struct xrx200_chan, napi); struct net_device *net_dev = ch->priv->net_dev; int pkts = 0; int bytes = 0; netif_tx_lock(net_dev); while (pkts < budget) { struct ltq_dma_desc *desc = &ch->dma.desc_base[ch->tx_free]; if ((desc->ctl & (LTQ_DMA_OWN | LTQ_DMA_C)) == LTQ_DMA_C) { struct sk_buff *skb = ch->skb[ch->tx_free]; pkts++; bytes += skb->len; ch->skb[ch->tx_free] = NULL; consume_skb(skb); memset(&ch->dma.desc_base[ch->tx_free], 0, sizeof(struct ltq_dma_desc)); ch->tx_free++; ch->tx_free %= LTQ_DESC_NUM; } else { break; } } net_dev->stats.tx_packets += pkts; net_dev->stats.tx_bytes += bytes; netdev_completed_queue(ch->priv->net_dev, pkts, bytes); netif_tx_unlock(net_dev); if (netif_queue_stopped(net_dev)) netif_wake_queue(net_dev); if (pkts < budget) { if (napi_complete_done(&ch->napi, pkts)) ltq_dma_enable_irq(&ch->dma); } return pkts; } static netdev_tx_t xrx200_start_xmit(struct sk_buff *skb, struct net_device *net_dev) { struct xrx200_priv *priv = netdev_priv(net_dev); struct xrx200_chan *ch = &priv->chan_tx; struct ltq_dma_desc *desc = &ch->dma.desc_base[ch->dma.desc]; u32 byte_offset; dma_addr_t mapping; int len; skb->dev = net_dev; if (skb_put_padto(skb, ETH_ZLEN)) { net_dev->stats.tx_dropped++; return NETDEV_TX_OK; } len = skb->len; if ((desc->ctl & (LTQ_DMA_OWN | LTQ_DMA_C)) || ch->skb[ch->dma.desc]) { netdev_err(net_dev, "tx ring full\n"); netif_stop_queue(net_dev); return NETDEV_TX_BUSY; } ch->skb[ch->dma.desc] = skb; mapping = dma_map_single(priv->dev, skb->data, len, DMA_TO_DEVICE); if (unlikely(dma_mapping_error(priv->dev, mapping))) goto err_drop; /* dma needs to start on a burst length value aligned address */ byte_offset = mapping % (XRX200_DMA_BURST_LEN * 4); desc->addr = mapping - byte_offset; /* Make sure the address is written before we give it to HW */ wmb(); desc->ctl = LTQ_DMA_OWN | LTQ_DMA_SOP | LTQ_DMA_EOP | LTQ_DMA_TX_OFFSET(byte_offset) | (len & LTQ_DMA_SIZE_MASK); ch->dma.desc++; ch->dma.desc %= LTQ_DESC_NUM; if (ch->dma.desc == ch->tx_free) netif_stop_queue(net_dev); netdev_sent_queue(net_dev, len); return NETDEV_TX_OK; err_drop: dev_kfree_skb(skb); net_dev->stats.tx_dropped++; net_dev->stats.tx_errors++; return NETDEV_TX_OK; } static int xrx200_change_mtu(struct net_device *net_dev, int new_mtu) { struct xrx200_priv *priv = netdev_priv(net_dev); struct xrx200_chan *ch_rx = &priv->chan_rx; int old_mtu = net_dev->mtu; bool running = false; void *buff; int curr_desc; int ret = 0; net_dev->mtu = new_mtu; priv->rx_buf_size = xrx200_buffer_size(new_mtu); priv->rx_skb_size = xrx200_skb_size(priv->rx_buf_size); if (new_mtu <= old_mtu) return ret; running = netif_running(net_dev); if (running) { napi_disable(&ch_rx->napi); ltq_dma_close(&ch_rx->dma); } xrx200_poll_rx(&ch_rx->napi, LTQ_DESC_NUM); curr_desc = ch_rx->dma.desc; for (ch_rx->dma.desc = 0; ch_rx->dma.desc < LTQ_DESC_NUM; ch_rx->dma.desc++) { buff = ch_rx->rx_buff[ch_rx->dma.desc]; ret = xrx200_alloc_buf(ch_rx, netdev_alloc_frag); if (ret) { net_dev->mtu = old_mtu; priv->rx_buf_size = xrx200_buffer_size(old_mtu); priv->rx_skb_size = xrx200_skb_size(priv->rx_buf_size); break; } skb_free_frag(buff); } ch_rx->dma.desc = curr_desc; if (running) { napi_enable(&ch_rx->napi); ltq_dma_open(&ch_rx->dma); ltq_dma_enable_irq(&ch_rx->dma); } return ret; } static const struct net_device_ops xrx200_netdev_ops = { .ndo_open = xrx200_open, .ndo_stop = xrx200_close, .ndo_start_xmit = xrx200_start_xmit, .ndo_change_mtu = xrx200_change_mtu, .ndo_set_mac_address = eth_mac_addr, .ndo_validate_addr = eth_validate_addr, }; static irqreturn_t xrx200_dma_irq(int irq, void *ptr) { struct xrx200_chan *ch = ptr; if (napi_schedule_prep(&ch->napi)) { ltq_dma_disable_irq(&ch->dma); __napi_schedule(&ch->napi); } ltq_dma_ack_irq(&ch->dma); return IRQ_HANDLED; } static int xrx200_dma_init(struct xrx200_priv *priv) { struct xrx200_chan *ch_rx = &priv->chan_rx; struct xrx200_chan *ch_tx = &priv->chan_tx; int ret = 0; int i; ltq_dma_init_port(DMA_PORT_ETOP, XRX200_DMA_BURST_LEN, XRX200_DMA_BURST_LEN); ch_rx->dma.nr = XRX200_DMA_RX; ch_rx->dma.dev = priv->dev; ch_rx->priv = priv; ltq_dma_alloc_rx(&ch_rx->dma); for (ch_rx->dma.desc = 0; ch_rx->dma.desc < LTQ_DESC_NUM; ch_rx->dma.desc++) { ret = xrx200_alloc_buf(ch_rx, netdev_alloc_frag); if (ret) goto rx_free; } ch_rx->dma.desc = 0; ret = devm_request_irq(priv->dev, ch_rx->dma.irq, xrx200_dma_irq, 0, "xrx200_net_rx", &priv->chan_rx); if (ret) { dev_err(priv->dev, "failed to request RX irq %d\n", ch_rx->dma.irq); goto rx_ring_free; } ch_tx->dma.nr = XRX200_DMA_TX; ch_tx->dma.dev = priv->dev; ch_tx->priv = priv; ltq_dma_alloc_tx(&ch_tx->dma); ret = devm_request_irq(priv->dev, ch_tx->dma.irq, xrx200_dma_irq, 0, "xrx200_net_tx", &priv->chan_tx); if (ret) { dev_err(priv->dev, "failed to request TX irq %d\n", ch_tx->dma.irq); goto tx_free; } return ret; tx_free: ltq_dma_free(&ch_tx->dma); rx_ring_free: /* free the allocated RX ring */ for (i = 0; i < LTQ_DESC_NUM; i++) { if (priv->chan_rx.skb[i]) skb_free_frag(priv->chan_rx.rx_buff[i]); } rx_free: ltq_dma_free(&ch_rx->dma); return ret; } static void xrx200_hw_cleanup(struct xrx200_priv *priv) { int i; ltq_dma_free(&priv->chan_tx.dma); ltq_dma_free(&priv->chan_rx.dma); /* free the allocated RX ring */ for (i = 0; i < LTQ_DESC_NUM; i++) skb_free_frag(priv->chan_rx.rx_buff[i]); } static int xrx200_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct device_node *np = dev->of_node; struct xrx200_priv *priv; struct net_device *net_dev; int err; /* alloc the network device */ net_dev = devm_alloc_etherdev(dev, sizeof(struct xrx200_priv)); if (!net_dev) return -ENOMEM; priv = netdev_priv(net_dev); priv->net_dev = net_dev; priv->dev = dev; net_dev->netdev_ops = &xrx200_netdev_ops; SET_NETDEV_DEV(net_dev, dev); net_dev->min_mtu = ETH_ZLEN; net_dev->max_mtu = XRX200_DMA_DATA_LEN - xrx200_max_frame_len(0); priv->rx_buf_size = xrx200_buffer_size(ETH_DATA_LEN); priv->rx_skb_size = xrx200_skb_size(priv->rx_buf_size); /* load the memory ranges */ priv->pmac_reg = devm_platform_get_and_ioremap_resource(pdev, 0, NULL); if (IS_ERR(priv->pmac_reg)) return PTR_ERR(priv->pmac_reg); priv->chan_rx.dma.irq = platform_get_irq_byname(pdev, "rx"); if (priv->chan_rx.dma.irq < 0) return -ENOENT; priv->chan_tx.dma.irq = platform_get_irq_byname(pdev, "tx"); if (priv->chan_tx.dma.irq < 0) return -ENOENT; /* get the clock */ priv->clk = devm_clk_get(dev, NULL); if (IS_ERR(priv->clk)) { dev_err(dev, "failed to get clock\n"); return PTR_ERR(priv->clk); } err = of_get_ethdev_address(np, net_dev); if (err) eth_hw_addr_random(net_dev); /* bring up the dma engine and IP core */ err = xrx200_dma_init(priv); if (err) return err; /* enable clock gate */ err = clk_prepare_enable(priv->clk); if (err) goto err_uninit_dma; /* set IPG to 12 */ xrx200_pmac_mask(priv, PMAC_RX_IPG_MASK, 0xb, PMAC_RX_IPG); /* enable status header, enable CRC */ xrx200_pmac_mask(priv, 0, PMAC_HD_CTL_RST | PMAC_HD_CTL_AST | PMAC_HD_CTL_RXSH | PMAC_HD_CTL_AS | PMAC_HD_CTL_AC | PMAC_HD_CTL_RC, PMAC_HD_CTL); /* setup NAPI */ netif_napi_add(net_dev, &priv->chan_rx.napi, xrx200_poll_rx); netif_napi_add_tx(net_dev, &priv->chan_tx.napi, xrx200_tx_housekeeping); platform_set_drvdata(pdev, priv); err = register_netdev(net_dev); if (err) goto err_unprepare_clk; return 0; err_unprepare_clk: clk_disable_unprepare(priv->clk); err_uninit_dma: xrx200_hw_cleanup(priv); return err; } static int xrx200_remove(struct platform_device *pdev) { struct xrx200_priv *priv = platform_get_drvdata(pdev); struct net_device *net_dev = priv->net_dev; /* free stack related instances */ netif_stop_queue(net_dev); netif_napi_del(&priv->chan_tx.napi); netif_napi_del(&priv->chan_rx.napi); /* remove the actual device */ unregister_netdev(net_dev); /* release the clock */ clk_disable_unprepare(priv->clk); /* shut down hardware */ xrx200_hw_cleanup(priv); return 0; } static const struct of_device_id xrx200_match[] = { { .compatible = "lantiq,xrx200-net" }, {}, }; MODULE_DEVICE_TABLE(of, xrx200_match); static struct platform_driver xrx200_driver = { .probe = xrx200_probe, .remove = xrx200_remove, .driver = { .name = "lantiq,xrx200-net", .of_match_table = xrx200_match, }, }; module_platform_driver(xrx200_driver); MODULE_AUTHOR("John Crispin <[email protected]>"); MODULE_DESCRIPTION("Lantiq SoC XRX200 ethernet"); MODULE_LICENSE("GPL");
linux-master
drivers/net/ethernet/lantiq_xrx200.c
// SPDX-License-Identifier: GPL-2.0-only /* * * Copyright (C) 2011 John Crispin <[email protected]> */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/interrupt.h> #include <linux/uaccess.h> #include <linux/in.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/phy.h> #include <linux/ip.h> #include <linux/tcp.h> #include <linux/skbuff.h> #include <linux/mm.h> #include <linux/platform_device.h> #include <linux/ethtool.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/io.h> #include <linux/dma-mapping.h> #include <linux/module.h> #include <linux/property.h> #include <asm/checksum.h> #include <lantiq_soc.h> #include <xway_dma.h> #include <lantiq_platform.h> #define LTQ_ETOP_MDIO 0x11804 #define MDIO_REQUEST 0x80000000 #define MDIO_READ 0x40000000 #define MDIO_ADDR_MASK 0x1f #define MDIO_ADDR_OFFSET 0x15 #define MDIO_REG_MASK 0x1f #define MDIO_REG_OFFSET 0x10 #define MDIO_VAL_MASK 0xffff #define PPE32_CGEN 0x800 #define LQ_PPE32_ENET_MAC_CFG 0x1840 #define LTQ_ETOP_ENETS0 0x11850 #define LTQ_ETOP_MAC_DA0 0x1186C #define LTQ_ETOP_MAC_DA1 0x11870 #define LTQ_ETOP_CFG 0x16020 #define LTQ_ETOP_IGPLEN 0x16080 #define MAX_DMA_CHAN 0x8 #define MAX_DMA_CRC_LEN 0x4 #define MAX_DMA_DATA_LEN 0x600 #define ETOP_FTCU BIT(28) #define ETOP_MII_MASK 0xf #define ETOP_MII_NORMAL 0xd #define ETOP_MII_REVERSE 0xe #define ETOP_PLEN_UNDER 0x40 #define ETOP_CGEN 0x800 /* use 2 static channels for TX/RX */ #define LTQ_ETOP_TX_CHANNEL 1 #define LTQ_ETOP_RX_CHANNEL 6 #define IS_TX(x) ((x) == LTQ_ETOP_TX_CHANNEL) #define IS_RX(x) ((x) == LTQ_ETOP_RX_CHANNEL) #define ltq_etop_r32(x) ltq_r32(ltq_etop_membase + (x)) #define ltq_etop_w32(x, y) ltq_w32(x, ltq_etop_membase + (y)) #define ltq_etop_w32_mask(x, y, z) \ ltq_w32_mask(x, y, ltq_etop_membase + (z)) #define DRV_VERSION "1.0" static void __iomem *ltq_etop_membase; struct ltq_etop_chan { int idx; int tx_free; struct net_device *netdev; struct napi_struct napi; struct ltq_dma_channel dma; struct sk_buff *skb[LTQ_DESC_NUM]; }; struct ltq_etop_priv { struct net_device *netdev; struct platform_device *pdev; struct ltq_eth_data *pldata; struct resource *res; struct mii_bus *mii_bus; struct ltq_etop_chan ch[MAX_DMA_CHAN]; int tx_free[MAX_DMA_CHAN >> 1]; int tx_burst_len; int rx_burst_len; spinlock_t lock; }; static int ltq_etop_alloc_skb(struct ltq_etop_chan *ch) { struct ltq_etop_priv *priv = netdev_priv(ch->netdev); ch->skb[ch->dma.desc] = netdev_alloc_skb(ch->netdev, MAX_DMA_DATA_LEN); if (!ch->skb[ch->dma.desc]) return -ENOMEM; ch->dma.desc_base[ch->dma.desc].addr = dma_map_single(&priv->pdev->dev, ch->skb[ch->dma.desc]->data, MAX_DMA_DATA_LEN, DMA_FROM_DEVICE); ch->dma.desc_base[ch->dma.desc].addr = CPHYSADDR(ch->skb[ch->dma.desc]->data); ch->dma.desc_base[ch->dma.desc].ctl = LTQ_DMA_OWN | LTQ_DMA_RX_OFFSET(NET_IP_ALIGN) | MAX_DMA_DATA_LEN; skb_reserve(ch->skb[ch->dma.desc], NET_IP_ALIGN); return 0; } static void ltq_etop_hw_receive(struct ltq_etop_chan *ch) { struct ltq_etop_priv *priv = netdev_priv(ch->netdev); struct ltq_dma_desc *desc = &ch->dma.desc_base[ch->dma.desc]; struct sk_buff *skb = ch->skb[ch->dma.desc]; int len = (desc->ctl & LTQ_DMA_SIZE_MASK) - MAX_DMA_CRC_LEN; unsigned long flags; spin_lock_irqsave(&priv->lock, flags); if (ltq_etop_alloc_skb(ch)) { netdev_err(ch->netdev, "failed to allocate new rx buffer, stopping DMA\n"); ltq_dma_close(&ch->dma); } ch->dma.desc++; ch->dma.desc %= LTQ_DESC_NUM; spin_unlock_irqrestore(&priv->lock, flags); skb_put(skb, len); skb->protocol = eth_type_trans(skb, ch->netdev); netif_receive_skb(skb); } static int ltq_etop_poll_rx(struct napi_struct *napi, int budget) { struct ltq_etop_chan *ch = container_of(napi, struct ltq_etop_chan, napi); int work_done = 0; while (work_done < budget) { struct ltq_dma_desc *desc = &ch->dma.desc_base[ch->dma.desc]; if ((desc->ctl & (LTQ_DMA_OWN | LTQ_DMA_C)) != LTQ_DMA_C) break; ltq_etop_hw_receive(ch); work_done++; } if (work_done < budget) { napi_complete_done(&ch->napi, work_done); ltq_dma_ack_irq(&ch->dma); } return work_done; } static int ltq_etop_poll_tx(struct napi_struct *napi, int budget) { struct ltq_etop_chan *ch = container_of(napi, struct ltq_etop_chan, napi); struct ltq_etop_priv *priv = netdev_priv(ch->netdev); struct netdev_queue *txq = netdev_get_tx_queue(ch->netdev, ch->idx >> 1); unsigned long flags; spin_lock_irqsave(&priv->lock, flags); while ((ch->dma.desc_base[ch->tx_free].ctl & (LTQ_DMA_OWN | LTQ_DMA_C)) == LTQ_DMA_C) { dev_kfree_skb_any(ch->skb[ch->tx_free]); ch->skb[ch->tx_free] = NULL; memset(&ch->dma.desc_base[ch->tx_free], 0, sizeof(struct ltq_dma_desc)); ch->tx_free++; ch->tx_free %= LTQ_DESC_NUM; } spin_unlock_irqrestore(&priv->lock, flags); if (netif_tx_queue_stopped(txq)) netif_tx_start_queue(txq); napi_complete(&ch->napi); ltq_dma_ack_irq(&ch->dma); return 1; } static irqreturn_t ltq_etop_dma_irq(int irq, void *_priv) { struct ltq_etop_priv *priv = _priv; int ch = irq - LTQ_DMA_CH0_INT; napi_schedule(&priv->ch[ch].napi); return IRQ_HANDLED; } static void ltq_etop_free_channel(struct net_device *dev, struct ltq_etop_chan *ch) { struct ltq_etop_priv *priv = netdev_priv(dev); ltq_dma_free(&ch->dma); if (ch->dma.irq) free_irq(ch->dma.irq, priv); if (IS_RX(ch->idx)) { int desc; for (desc = 0; desc < LTQ_DESC_NUM; desc++) dev_kfree_skb_any(ch->skb[ch->dma.desc]); } } static void ltq_etop_hw_exit(struct net_device *dev) { struct ltq_etop_priv *priv = netdev_priv(dev); int i; ltq_pmu_disable(PMU_PPE); for (i = 0; i < MAX_DMA_CHAN; i++) if (IS_TX(i) || IS_RX(i)) ltq_etop_free_channel(dev, &priv->ch[i]); } static int ltq_etop_hw_init(struct net_device *dev) { struct ltq_etop_priv *priv = netdev_priv(dev); int i; int err; ltq_pmu_enable(PMU_PPE); switch (priv->pldata->mii_mode) { case PHY_INTERFACE_MODE_RMII: ltq_etop_w32_mask(ETOP_MII_MASK, ETOP_MII_REVERSE, LTQ_ETOP_CFG); break; case PHY_INTERFACE_MODE_MII: ltq_etop_w32_mask(ETOP_MII_MASK, ETOP_MII_NORMAL, LTQ_ETOP_CFG); break; default: netdev_err(dev, "unknown mii mode %d\n", priv->pldata->mii_mode); return -ENOTSUPP; } /* enable crc generation */ ltq_etop_w32(PPE32_CGEN, LQ_PPE32_ENET_MAC_CFG); ltq_dma_init_port(DMA_PORT_ETOP, priv->tx_burst_len, priv->rx_burst_len); for (i = 0; i < MAX_DMA_CHAN; i++) { int irq = LTQ_DMA_CH0_INT + i; struct ltq_etop_chan *ch = &priv->ch[i]; ch->dma.nr = i; ch->idx = ch->dma.nr; ch->dma.dev = &priv->pdev->dev; if (IS_TX(i)) { ltq_dma_alloc_tx(&ch->dma); err = request_irq(irq, ltq_etop_dma_irq, 0, "etop_tx", priv); if (err) { netdev_err(dev, "Unable to get Tx DMA IRQ %d\n", irq); return err; } } else if (IS_RX(i)) { ltq_dma_alloc_rx(&ch->dma); for (ch->dma.desc = 0; ch->dma.desc < LTQ_DESC_NUM; ch->dma.desc++) if (ltq_etop_alloc_skb(ch)) return -ENOMEM; ch->dma.desc = 0; err = request_irq(irq, ltq_etop_dma_irq, 0, "etop_rx", priv); if (err) { netdev_err(dev, "Unable to get Rx DMA IRQ %d\n", irq); return err; } } ch->dma.irq = irq; } return 0; } static void ltq_etop_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { strscpy(info->driver, "Lantiq ETOP", sizeof(info->driver)); strscpy(info->bus_info, "internal", sizeof(info->bus_info)); strscpy(info->version, DRV_VERSION, sizeof(info->version)); } static const struct ethtool_ops ltq_etop_ethtool_ops = { .get_drvinfo = ltq_etop_get_drvinfo, .nway_reset = phy_ethtool_nway_reset, .get_link_ksettings = phy_ethtool_get_link_ksettings, .set_link_ksettings = phy_ethtool_set_link_ksettings, }; static int ltq_etop_mdio_wr(struct mii_bus *bus, int phy_addr, int phy_reg, u16 phy_data) { u32 val = MDIO_REQUEST | ((phy_addr & MDIO_ADDR_MASK) << MDIO_ADDR_OFFSET) | ((phy_reg & MDIO_REG_MASK) << MDIO_REG_OFFSET) | phy_data; while (ltq_etop_r32(LTQ_ETOP_MDIO) & MDIO_REQUEST) ; ltq_etop_w32(val, LTQ_ETOP_MDIO); return 0; } static int ltq_etop_mdio_rd(struct mii_bus *bus, int phy_addr, int phy_reg) { u32 val = MDIO_REQUEST | MDIO_READ | ((phy_addr & MDIO_ADDR_MASK) << MDIO_ADDR_OFFSET) | ((phy_reg & MDIO_REG_MASK) << MDIO_REG_OFFSET); while (ltq_etop_r32(LTQ_ETOP_MDIO) & MDIO_REQUEST) ; ltq_etop_w32(val, LTQ_ETOP_MDIO); while (ltq_etop_r32(LTQ_ETOP_MDIO) & MDIO_REQUEST) ; val = ltq_etop_r32(LTQ_ETOP_MDIO) & MDIO_VAL_MASK; return val; } static void ltq_etop_mdio_link(struct net_device *dev) { /* nothing to do */ } static int ltq_etop_mdio_probe(struct net_device *dev) { struct ltq_etop_priv *priv = netdev_priv(dev); struct phy_device *phydev; phydev = phy_find_first(priv->mii_bus); if (!phydev) { netdev_err(dev, "no PHY found\n"); return -ENODEV; } phydev = phy_connect(dev, phydev_name(phydev), &ltq_etop_mdio_link, priv->pldata->mii_mode); if (IS_ERR(phydev)) { netdev_err(dev, "Could not attach to PHY\n"); return PTR_ERR(phydev); } phy_set_max_speed(phydev, SPEED_100); phy_attached_info(phydev); return 0; } static int ltq_etop_mdio_init(struct net_device *dev) { struct ltq_etop_priv *priv = netdev_priv(dev); int err; priv->mii_bus = mdiobus_alloc(); if (!priv->mii_bus) { netdev_err(dev, "failed to allocate mii bus\n"); err = -ENOMEM; goto err_out; } priv->mii_bus->priv = dev; priv->mii_bus->read = ltq_etop_mdio_rd; priv->mii_bus->write = ltq_etop_mdio_wr; priv->mii_bus->name = "ltq_mii"; snprintf(priv->mii_bus->id, MII_BUS_ID_SIZE, "%s-%x", priv->pdev->name, priv->pdev->id); if (mdiobus_register(priv->mii_bus)) { err = -ENXIO; goto err_out_free_mdiobus; } if (ltq_etop_mdio_probe(dev)) { err = -ENXIO; goto err_out_unregister_bus; } return 0; err_out_unregister_bus: mdiobus_unregister(priv->mii_bus); err_out_free_mdiobus: mdiobus_free(priv->mii_bus); err_out: return err; } static void ltq_etop_mdio_cleanup(struct net_device *dev) { struct ltq_etop_priv *priv = netdev_priv(dev); phy_disconnect(dev->phydev); mdiobus_unregister(priv->mii_bus); mdiobus_free(priv->mii_bus); } static int ltq_etop_open(struct net_device *dev) { struct ltq_etop_priv *priv = netdev_priv(dev); int i; for (i = 0; i < MAX_DMA_CHAN; i++) { struct ltq_etop_chan *ch = &priv->ch[i]; if (!IS_TX(i) && (!IS_RX(i))) continue; ltq_dma_open(&ch->dma); ltq_dma_enable_irq(&ch->dma); napi_enable(&ch->napi); } phy_start(dev->phydev); netif_tx_start_all_queues(dev); return 0; } static int ltq_etop_stop(struct net_device *dev) { struct ltq_etop_priv *priv = netdev_priv(dev); int i; netif_tx_stop_all_queues(dev); phy_stop(dev->phydev); for (i = 0; i < MAX_DMA_CHAN; i++) { struct ltq_etop_chan *ch = &priv->ch[i]; if (!IS_RX(i) && !IS_TX(i)) continue; napi_disable(&ch->napi); ltq_dma_close(&ch->dma); } return 0; } static netdev_tx_t ltq_etop_tx(struct sk_buff *skb, struct net_device *dev) { int queue = skb_get_queue_mapping(skb); struct netdev_queue *txq = netdev_get_tx_queue(dev, queue); struct ltq_etop_priv *priv = netdev_priv(dev); struct ltq_etop_chan *ch = &priv->ch[(queue << 1) | 1]; struct ltq_dma_desc *desc = &ch->dma.desc_base[ch->dma.desc]; int len; unsigned long flags; u32 byte_offset; len = skb->len < ETH_ZLEN ? ETH_ZLEN : skb->len; if ((desc->ctl & (LTQ_DMA_OWN | LTQ_DMA_C)) || ch->skb[ch->dma.desc]) { netdev_err(dev, "tx ring full\n"); netif_tx_stop_queue(txq); return NETDEV_TX_BUSY; } /* dma needs to start on a burst length value aligned address */ byte_offset = CPHYSADDR(skb->data) % (priv->tx_burst_len * 4); ch->skb[ch->dma.desc] = skb; netif_trans_update(dev); spin_lock_irqsave(&priv->lock, flags); desc->addr = ((unsigned int)dma_map_single(&priv->pdev->dev, skb->data, len, DMA_TO_DEVICE)) - byte_offset; /* Make sure the address is written before we give it to HW */ wmb(); desc->ctl = LTQ_DMA_OWN | LTQ_DMA_SOP | LTQ_DMA_EOP | LTQ_DMA_TX_OFFSET(byte_offset) | (len & LTQ_DMA_SIZE_MASK); ch->dma.desc++; ch->dma.desc %= LTQ_DESC_NUM; spin_unlock_irqrestore(&priv->lock, flags); if (ch->dma.desc_base[ch->dma.desc].ctl & LTQ_DMA_OWN) netif_tx_stop_queue(txq); return NETDEV_TX_OK; } static int ltq_etop_change_mtu(struct net_device *dev, int new_mtu) { struct ltq_etop_priv *priv = netdev_priv(dev); unsigned long flags; dev->mtu = new_mtu; spin_lock_irqsave(&priv->lock, flags); ltq_etop_w32((ETOP_PLEN_UNDER << 16) | new_mtu, LTQ_ETOP_IGPLEN); spin_unlock_irqrestore(&priv->lock, flags); return 0; } static int ltq_etop_set_mac_address(struct net_device *dev, void *p) { int ret = eth_mac_addr(dev, p); if (!ret) { struct ltq_etop_priv *priv = netdev_priv(dev); unsigned long flags; /* store the mac for the unicast filter */ spin_lock_irqsave(&priv->lock, flags); ltq_etop_w32(*((u32 *)dev->dev_addr), LTQ_ETOP_MAC_DA0); ltq_etop_w32(*((u16 *)&dev->dev_addr[4]) << 16, LTQ_ETOP_MAC_DA1); spin_unlock_irqrestore(&priv->lock, flags); } return ret; } static void ltq_etop_set_multicast_list(struct net_device *dev) { struct ltq_etop_priv *priv = netdev_priv(dev); unsigned long flags; /* ensure that the unicast filter is not enabled in promiscious mode */ spin_lock_irqsave(&priv->lock, flags); if ((dev->flags & IFF_PROMISC) || (dev->flags & IFF_ALLMULTI)) ltq_etop_w32_mask(ETOP_FTCU, 0, LTQ_ETOP_ENETS0); else ltq_etop_w32_mask(0, ETOP_FTCU, LTQ_ETOP_ENETS0); spin_unlock_irqrestore(&priv->lock, flags); } static int ltq_etop_init(struct net_device *dev) { struct ltq_etop_priv *priv = netdev_priv(dev); struct sockaddr mac; int err; bool random_mac = false; dev->watchdog_timeo = 10 * HZ; err = ltq_etop_hw_init(dev); if (err) goto err_hw; ltq_etop_change_mtu(dev, 1500); memcpy(&mac, &priv->pldata->mac, sizeof(struct sockaddr)); if (!is_valid_ether_addr(mac.sa_data)) { pr_warn("etop: invalid MAC, using random\n"); eth_random_addr(mac.sa_data); random_mac = true; } err = ltq_etop_set_mac_address(dev, &mac); if (err) goto err_netdev; /* Set addr_assign_type here, ltq_etop_set_mac_address would reset it. */ if (random_mac) dev->addr_assign_type = NET_ADDR_RANDOM; ltq_etop_set_multicast_list(dev); err = ltq_etop_mdio_init(dev); if (err) goto err_netdev; return 0; err_netdev: unregister_netdev(dev); free_netdev(dev); err_hw: ltq_etop_hw_exit(dev); return err; } static void ltq_etop_tx_timeout(struct net_device *dev, unsigned int txqueue) { int err; ltq_etop_hw_exit(dev); err = ltq_etop_hw_init(dev); if (err) goto err_hw; netif_trans_update(dev); netif_wake_queue(dev); return; err_hw: ltq_etop_hw_exit(dev); netdev_err(dev, "failed to restart etop after TX timeout\n"); } static const struct net_device_ops ltq_eth_netdev_ops = { .ndo_open = ltq_etop_open, .ndo_stop = ltq_etop_stop, .ndo_start_xmit = ltq_etop_tx, .ndo_change_mtu = ltq_etop_change_mtu, .ndo_eth_ioctl = phy_do_ioctl, .ndo_set_mac_address = ltq_etop_set_mac_address, .ndo_validate_addr = eth_validate_addr, .ndo_set_rx_mode = ltq_etop_set_multicast_list, .ndo_select_queue = dev_pick_tx_zero, .ndo_init = ltq_etop_init, .ndo_tx_timeout = ltq_etop_tx_timeout, }; static int __init ltq_etop_probe(struct platform_device *pdev) { struct net_device *dev; struct ltq_etop_priv *priv; struct resource *res; int err; int i; res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { dev_err(&pdev->dev, "failed to get etop resource\n"); err = -ENOENT; goto err_out; } res = devm_request_mem_region(&pdev->dev, res->start, resource_size(res), dev_name(&pdev->dev)); if (!res) { dev_err(&pdev->dev, "failed to request etop resource\n"); err = -EBUSY; goto err_out; } ltq_etop_membase = devm_ioremap(&pdev->dev, res->start, resource_size(res)); if (!ltq_etop_membase) { dev_err(&pdev->dev, "failed to remap etop engine %d\n", pdev->id); err = -ENOMEM; goto err_out; } dev = alloc_etherdev_mq(sizeof(struct ltq_etop_priv), 4); if (!dev) { err = -ENOMEM; goto err_out; } strcpy(dev->name, "eth%d"); dev->netdev_ops = &ltq_eth_netdev_ops; dev->ethtool_ops = &ltq_etop_ethtool_ops; priv = netdev_priv(dev); priv->res = res; priv->pdev = pdev; priv->pldata = dev_get_platdata(&pdev->dev); priv->netdev = dev; spin_lock_init(&priv->lock); SET_NETDEV_DEV(dev, &pdev->dev); err = device_property_read_u32(&pdev->dev, "lantiq,tx-burst-length", &priv->tx_burst_len); if (err < 0) { dev_err(&pdev->dev, "unable to read tx-burst-length property\n"); goto err_free; } err = device_property_read_u32(&pdev->dev, "lantiq,rx-burst-length", &priv->rx_burst_len); if (err < 0) { dev_err(&pdev->dev, "unable to read rx-burst-length property\n"); goto err_free; } for (i = 0; i < MAX_DMA_CHAN; i++) { if (IS_TX(i)) netif_napi_add_weight(dev, &priv->ch[i].napi, ltq_etop_poll_tx, 8); else if (IS_RX(i)) netif_napi_add_weight(dev, &priv->ch[i].napi, ltq_etop_poll_rx, 32); priv->ch[i].netdev = dev; } err = register_netdev(dev); if (err) goto err_free; platform_set_drvdata(pdev, dev); return 0; err_free: free_netdev(dev); err_out: return err; } static int ltq_etop_remove(struct platform_device *pdev) { struct net_device *dev = platform_get_drvdata(pdev); if (dev) { netif_tx_stop_all_queues(dev); ltq_etop_hw_exit(dev); ltq_etop_mdio_cleanup(dev); unregister_netdev(dev); } return 0; } static struct platform_driver ltq_mii_driver = { .remove = ltq_etop_remove, .driver = { .name = "ltq_etop", }, }; static int __init init_ltq_etop(void) { int ret = platform_driver_probe(&ltq_mii_driver, ltq_etop_probe); if (ret) pr_err("ltq_etop: Error registering platform driver!"); return ret; } static void __exit exit_ltq_etop(void) { platform_driver_unregister(&ltq_mii_driver); } module_init(init_ltq_etop); module_exit(exit_ltq_etop); MODULE_AUTHOR("John Crispin <[email protected]>"); MODULE_DESCRIPTION("Lantiq SoC ETOP"); MODULE_LICENSE("GPL");
linux-master
drivers/net/ethernet/lantiq_etop.c
// SPDX-License-Identifier: GPL-2.0-only /* * drivers/net/ethernet/ec_bhf.c * * Copyright (C) 2014 Darek Marcinkiewicz <[email protected]> */ /* This is a driver for EtherCAT master module present on CCAT FPGA. * Those can be found on Bechhoff CX50xx industrial PCs. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/pci.h> #include <linux/init.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/ip.h> #include <linux/skbuff.h> #include <linux/hrtimer.h> #include <linux/interrupt.h> #include <linux/stat.h> #define TIMER_INTERVAL_NSEC 20000 #define INFO_BLOCK_SIZE 0x10 #define INFO_BLOCK_TYPE 0x0 #define INFO_BLOCK_REV 0x2 #define INFO_BLOCK_BLK_CNT 0x4 #define INFO_BLOCK_TX_CHAN 0x4 #define INFO_BLOCK_RX_CHAN 0x5 #define INFO_BLOCK_OFFSET 0x8 #define EC_MII_OFFSET 0x4 #define EC_FIFO_OFFSET 0x8 #define EC_MAC_OFFSET 0xc #define MAC_FRAME_ERR_CNT 0x0 #define MAC_RX_ERR_CNT 0x1 #define MAC_CRC_ERR_CNT 0x2 #define MAC_LNK_LST_ERR_CNT 0x3 #define MAC_TX_FRAME_CNT 0x10 #define MAC_RX_FRAME_CNT 0x14 #define MAC_TX_FIFO_LVL 0x20 #define MAC_DROPPED_FRMS 0x28 #define MAC_CONNECTED_CCAT_FLAG 0x78 #define MII_MAC_ADDR 0x8 #define MII_MAC_FILT_FLAG 0xe #define MII_LINK_STATUS 0xf #define FIFO_TX_REG 0x0 #define FIFO_TX_RESET 0x8 #define FIFO_RX_REG 0x10 #define FIFO_RX_ADDR_VALID (1u << 31) #define FIFO_RX_RESET 0x18 #define DMA_CHAN_OFFSET 0x1000 #define DMA_CHAN_SIZE 0x8 #define DMA_WINDOW_SIZE_MASK 0xfffffffc #define ETHERCAT_MASTER_ID 0x14 static const struct pci_device_id ids[] = { { PCI_DEVICE(0x15ec, 0x5000), }, { 0, } }; MODULE_DEVICE_TABLE(pci, ids); struct rx_header { #define RXHDR_NEXT_ADDR_MASK 0xffffffu #define RXHDR_NEXT_VALID (1u << 31) __le32 next; #define RXHDR_NEXT_RECV_FLAG 0x1 __le32 recv; #define RXHDR_LEN_MASK 0xfffu __le16 len; __le16 port; __le32 reserved; u8 timestamp[8]; } __packed; #define PKT_PAYLOAD_SIZE 0x7e8 struct rx_desc { struct rx_header header; u8 data[PKT_PAYLOAD_SIZE]; } __packed; struct tx_header { __le16 len; #define TX_HDR_PORT_0 0x1 #define TX_HDR_PORT_1 0x2 u8 port; u8 ts_enable; #define TX_HDR_SENT 0x1 __le32 sent; u8 timestamp[8]; } __packed; struct tx_desc { struct tx_header header; u8 data[PKT_PAYLOAD_SIZE]; } __packed; #define FIFO_SIZE 64 static long polling_frequency = TIMER_INTERVAL_NSEC; struct bhf_dma { u8 *buf; size_t len; dma_addr_t buf_phys; u8 *alloc; size_t alloc_len; dma_addr_t alloc_phys; }; struct ec_bhf_priv { struct net_device *net_dev; struct pci_dev *dev; void __iomem *io; void __iomem *dma_io; struct hrtimer hrtimer; int tx_dma_chan; int rx_dma_chan; void __iomem *ec_io; void __iomem *fifo_io; void __iomem *mii_io; void __iomem *mac_io; struct bhf_dma rx_buf; struct rx_desc *rx_descs; int rx_dnext; int rx_dcount; struct bhf_dma tx_buf; struct tx_desc *tx_descs; int tx_dcount; int tx_dnext; u64 stat_rx_bytes; u64 stat_tx_bytes; }; #define PRIV_TO_DEV(priv) (&(priv)->dev->dev) static void ec_bhf_reset(struct ec_bhf_priv *priv) { iowrite8(0, priv->mac_io + MAC_FRAME_ERR_CNT); iowrite8(0, priv->mac_io + MAC_RX_ERR_CNT); iowrite8(0, priv->mac_io + MAC_CRC_ERR_CNT); iowrite8(0, priv->mac_io + MAC_LNK_LST_ERR_CNT); iowrite32(0, priv->mac_io + MAC_TX_FRAME_CNT); iowrite32(0, priv->mac_io + MAC_RX_FRAME_CNT); iowrite8(0, priv->mac_io + MAC_DROPPED_FRMS); iowrite8(0, priv->fifo_io + FIFO_TX_RESET); iowrite8(0, priv->fifo_io + FIFO_RX_RESET); iowrite8(0, priv->mac_io + MAC_TX_FIFO_LVL); } static void ec_bhf_send_packet(struct ec_bhf_priv *priv, struct tx_desc *desc) { u32 len = le16_to_cpu(desc->header.len) + sizeof(desc->header); u32 addr = (u8 *)desc - priv->tx_buf.buf; iowrite32((ALIGN(len, 8) << 24) | addr, priv->fifo_io + FIFO_TX_REG); } static int ec_bhf_desc_sent(struct tx_desc *desc) { return le32_to_cpu(desc->header.sent) & TX_HDR_SENT; } static void ec_bhf_process_tx(struct ec_bhf_priv *priv) { if (unlikely(netif_queue_stopped(priv->net_dev))) { /* Make sure that we perceive changes to tx_dnext. */ smp_rmb(); if (ec_bhf_desc_sent(&priv->tx_descs[priv->tx_dnext])) netif_wake_queue(priv->net_dev); } } static int ec_bhf_pkt_received(struct rx_desc *desc) { return le32_to_cpu(desc->header.recv) & RXHDR_NEXT_RECV_FLAG; } static void ec_bhf_add_rx_desc(struct ec_bhf_priv *priv, struct rx_desc *desc) { iowrite32(FIFO_RX_ADDR_VALID | ((u8 *)(desc) - priv->rx_buf.buf), priv->fifo_io + FIFO_RX_REG); } static void ec_bhf_process_rx(struct ec_bhf_priv *priv) { struct rx_desc *desc = &priv->rx_descs[priv->rx_dnext]; while (ec_bhf_pkt_received(desc)) { int pkt_size = (le16_to_cpu(desc->header.len) & RXHDR_LEN_MASK) - sizeof(struct rx_header) - 4; u8 *data = desc->data; struct sk_buff *skb; skb = netdev_alloc_skb_ip_align(priv->net_dev, pkt_size); if (skb) { skb_put_data(skb, data, pkt_size); skb->protocol = eth_type_trans(skb, priv->net_dev); priv->stat_rx_bytes += pkt_size; netif_rx(skb); } else { dev_err_ratelimited(PRIV_TO_DEV(priv), "Couldn't allocate a skb_buff for a packet of size %u\n", pkt_size); } desc->header.recv = 0; ec_bhf_add_rx_desc(priv, desc); priv->rx_dnext = (priv->rx_dnext + 1) % priv->rx_dcount; desc = &priv->rx_descs[priv->rx_dnext]; } } static enum hrtimer_restart ec_bhf_timer_fun(struct hrtimer *timer) { struct ec_bhf_priv *priv = container_of(timer, struct ec_bhf_priv, hrtimer); ec_bhf_process_rx(priv); ec_bhf_process_tx(priv); if (!netif_running(priv->net_dev)) return HRTIMER_NORESTART; hrtimer_forward_now(timer, polling_frequency); return HRTIMER_RESTART; } static int ec_bhf_setup_offsets(struct ec_bhf_priv *priv) { struct device *dev = PRIV_TO_DEV(priv); unsigned block_count, i; void __iomem *ec_info; block_count = ioread8(priv->io + INFO_BLOCK_BLK_CNT); for (i = 0; i < block_count; i++) { u16 type = ioread16(priv->io + i * INFO_BLOCK_SIZE + INFO_BLOCK_TYPE); if (type == ETHERCAT_MASTER_ID) break; } if (i == block_count) { dev_err(dev, "EtherCAT master with DMA block not found\n"); return -ENODEV; } ec_info = priv->io + i * INFO_BLOCK_SIZE; priv->tx_dma_chan = ioread8(ec_info + INFO_BLOCK_TX_CHAN); priv->rx_dma_chan = ioread8(ec_info + INFO_BLOCK_RX_CHAN); priv->ec_io = priv->io + ioread32(ec_info + INFO_BLOCK_OFFSET); priv->mii_io = priv->ec_io + ioread32(priv->ec_io + EC_MII_OFFSET); priv->fifo_io = priv->ec_io + ioread32(priv->ec_io + EC_FIFO_OFFSET); priv->mac_io = priv->ec_io + ioread32(priv->ec_io + EC_MAC_OFFSET); return 0; } static netdev_tx_t ec_bhf_start_xmit(struct sk_buff *skb, struct net_device *net_dev) { struct ec_bhf_priv *priv = netdev_priv(net_dev); struct tx_desc *desc; unsigned len; desc = &priv->tx_descs[priv->tx_dnext]; skb_copy_and_csum_dev(skb, desc->data); len = skb->len; memset(&desc->header, 0, sizeof(desc->header)); desc->header.len = cpu_to_le16(len); desc->header.port = TX_HDR_PORT_0; ec_bhf_send_packet(priv, desc); priv->tx_dnext = (priv->tx_dnext + 1) % priv->tx_dcount; if (!ec_bhf_desc_sent(&priv->tx_descs[priv->tx_dnext])) { /* Make sure that updates to tx_dnext are perceived * by timer routine. */ smp_wmb(); netif_stop_queue(net_dev); } priv->stat_tx_bytes += len; dev_kfree_skb(skb); return NETDEV_TX_OK; } static int ec_bhf_alloc_dma_mem(struct ec_bhf_priv *priv, struct bhf_dma *buf, int channel, int size) { int offset = channel * DMA_CHAN_SIZE + DMA_CHAN_OFFSET; struct device *dev = PRIV_TO_DEV(priv); u32 mask; iowrite32(0xffffffff, priv->dma_io + offset); mask = ioread32(priv->dma_io + offset); mask &= DMA_WINDOW_SIZE_MASK; /* We want to allocate a chunk of memory that is: * - aligned to the mask we just read * - is of size 2^mask bytes (at most) * In order to ensure that we will allocate buffer of * 2 * 2^mask bytes. */ buf->len = min_t(int, ~mask + 1, size); buf->alloc_len = 2 * buf->len; buf->alloc = dma_alloc_coherent(dev, buf->alloc_len, &buf->alloc_phys, GFP_KERNEL); if (buf->alloc == NULL) { dev_err(dev, "Failed to allocate buffer\n"); return -ENOMEM; } buf->buf_phys = (buf->alloc_phys + buf->len) & mask; buf->buf = buf->alloc + (buf->buf_phys - buf->alloc_phys); iowrite32(0, priv->dma_io + offset + 4); iowrite32(buf->buf_phys, priv->dma_io + offset); return 0; } static void ec_bhf_setup_tx_descs(struct ec_bhf_priv *priv) { int i = 0; priv->tx_dcount = priv->tx_buf.len / sizeof(struct tx_desc); priv->tx_descs = (struct tx_desc *)priv->tx_buf.buf; priv->tx_dnext = 0; for (i = 0; i < priv->tx_dcount; i++) priv->tx_descs[i].header.sent = cpu_to_le32(TX_HDR_SENT); } static void ec_bhf_setup_rx_descs(struct ec_bhf_priv *priv) { int i; priv->rx_dcount = priv->rx_buf.len / sizeof(struct rx_desc); priv->rx_descs = (struct rx_desc *)priv->rx_buf.buf; priv->rx_dnext = 0; for (i = 0; i < priv->rx_dcount; i++) { struct rx_desc *desc = &priv->rx_descs[i]; u32 next; if (i != priv->rx_dcount - 1) next = (u8 *)(desc + 1) - priv->rx_buf.buf; else next = 0; next |= RXHDR_NEXT_VALID; desc->header.next = cpu_to_le32(next); desc->header.recv = 0; ec_bhf_add_rx_desc(priv, desc); } } static int ec_bhf_open(struct net_device *net_dev) { struct ec_bhf_priv *priv = netdev_priv(net_dev); struct device *dev = PRIV_TO_DEV(priv); int err = 0; ec_bhf_reset(priv); err = ec_bhf_alloc_dma_mem(priv, &priv->rx_buf, priv->rx_dma_chan, FIFO_SIZE * sizeof(struct rx_desc)); if (err) { dev_err(dev, "Failed to allocate rx buffer\n"); goto out; } ec_bhf_setup_rx_descs(priv); err = ec_bhf_alloc_dma_mem(priv, &priv->tx_buf, priv->tx_dma_chan, FIFO_SIZE * sizeof(struct tx_desc)); if (err) { dev_err(dev, "Failed to allocate tx buffer\n"); goto error_rx_free; } iowrite8(0, priv->mii_io + MII_MAC_FILT_FLAG); ec_bhf_setup_tx_descs(priv); netif_start_queue(net_dev); hrtimer_init(&priv->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); priv->hrtimer.function = ec_bhf_timer_fun; hrtimer_start(&priv->hrtimer, polling_frequency, HRTIMER_MODE_REL); return 0; error_rx_free: dma_free_coherent(dev, priv->rx_buf.alloc_len, priv->rx_buf.alloc, priv->rx_buf.alloc_len); out: return err; } static int ec_bhf_stop(struct net_device *net_dev) { struct ec_bhf_priv *priv = netdev_priv(net_dev); struct device *dev = PRIV_TO_DEV(priv); hrtimer_cancel(&priv->hrtimer); ec_bhf_reset(priv); netif_tx_disable(net_dev); dma_free_coherent(dev, priv->tx_buf.alloc_len, priv->tx_buf.alloc, priv->tx_buf.alloc_phys); dma_free_coherent(dev, priv->rx_buf.alloc_len, priv->rx_buf.alloc, priv->rx_buf.alloc_phys); return 0; } static void ec_bhf_get_stats(struct net_device *net_dev, struct rtnl_link_stats64 *stats) { struct ec_bhf_priv *priv = netdev_priv(net_dev); stats->rx_errors = ioread8(priv->mac_io + MAC_RX_ERR_CNT) + ioread8(priv->mac_io + MAC_CRC_ERR_CNT) + ioread8(priv->mac_io + MAC_FRAME_ERR_CNT); stats->rx_packets = ioread32(priv->mac_io + MAC_RX_FRAME_CNT); stats->tx_packets = ioread32(priv->mac_io + MAC_TX_FRAME_CNT); stats->rx_dropped = ioread8(priv->mac_io + MAC_DROPPED_FRMS); stats->tx_bytes = priv->stat_tx_bytes; stats->rx_bytes = priv->stat_rx_bytes; } static const struct net_device_ops ec_bhf_netdev_ops = { .ndo_start_xmit = ec_bhf_start_xmit, .ndo_open = ec_bhf_open, .ndo_stop = ec_bhf_stop, .ndo_get_stats64 = ec_bhf_get_stats, .ndo_validate_addr = eth_validate_addr, .ndo_set_mac_address = eth_mac_addr }; static int ec_bhf_probe(struct pci_dev *dev, const struct pci_device_id *id) { struct net_device *net_dev; struct ec_bhf_priv *priv; void __iomem *dma_io; u8 addr[ETH_ALEN]; void __iomem *io; int err = 0; err = pci_enable_device(dev); if (err) return err; pci_set_master(dev); err = dma_set_mask_and_coherent(&dev->dev, DMA_BIT_MASK(32)); if (err) { dev_err(&dev->dev, "Required dma mask not supported, failed to initialize device\n"); goto err_disable_dev; } err = pci_request_regions(dev, "ec_bhf"); if (err) { dev_err(&dev->dev, "Failed to request pci memory regions\n"); goto err_disable_dev; } io = pci_iomap(dev, 0, 0); if (!io) { dev_err(&dev->dev, "Failed to map pci card memory bar 0"); err = -EIO; goto err_release_regions; } dma_io = pci_iomap(dev, 2, 0); if (!dma_io) { dev_err(&dev->dev, "Failed to map pci card memory bar 2"); err = -EIO; goto err_unmap; } net_dev = alloc_etherdev(sizeof(struct ec_bhf_priv)); if (net_dev == NULL) { err = -ENOMEM; goto err_unmap_dma_io; } pci_set_drvdata(dev, net_dev); SET_NETDEV_DEV(net_dev, &dev->dev); net_dev->features = 0; net_dev->flags |= IFF_NOARP; net_dev->netdev_ops = &ec_bhf_netdev_ops; priv = netdev_priv(net_dev); priv->net_dev = net_dev; priv->io = io; priv->dma_io = dma_io; priv->dev = dev; err = ec_bhf_setup_offsets(priv); if (err < 0) goto err_free_net_dev; memcpy_fromio(addr, priv->mii_io + MII_MAC_ADDR, ETH_ALEN); eth_hw_addr_set(net_dev, addr); err = register_netdev(net_dev); if (err < 0) goto err_free_net_dev; return 0; err_free_net_dev: free_netdev(net_dev); err_unmap_dma_io: pci_iounmap(dev, dma_io); err_unmap: pci_iounmap(dev, io); err_release_regions: pci_release_regions(dev); err_disable_dev: pci_disable_device(dev); return err; } static void ec_bhf_remove(struct pci_dev *dev) { struct net_device *net_dev = pci_get_drvdata(dev); struct ec_bhf_priv *priv = netdev_priv(net_dev); unregister_netdev(net_dev); pci_iounmap(dev, priv->dma_io); pci_iounmap(dev, priv->io); free_netdev(net_dev); pci_release_regions(dev); pci_disable_device(dev); } static struct pci_driver pci_driver = { .name = "ec_bhf", .id_table = ids, .probe = ec_bhf_probe, .remove = ec_bhf_remove, }; module_pci_driver(pci_driver); module_param(polling_frequency, long, 0444); MODULE_PARM_DESC(polling_frequency, "Polling timer frequency in ns"); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Dariusz Marcinkiewicz <[email protected]>");
linux-master
drivers/net/ethernet/ec_bhf.c
// SPDX-License-Identifier: GPL-2.0-only /* * Dave DNET Ethernet Controller driver * * Copyright (C) 2008 Dave S.r.l. <www.dave.eu> * Copyright (C) 2009 Ilya Yanok, Emcraft Systems Ltd, <[email protected]> */ #include <linux/io.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/interrupt.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/dma-mapping.h> #include <linux/platform_device.h> #include <linux/phy.h> #include "dnet.h" #undef DEBUG /* function for reading internal MAC register */ static u16 dnet_readw_mac(struct dnet *bp, u16 reg) { u16 data_read; /* issue a read */ dnet_writel(bp, reg, MACREG_ADDR); /* since a read/write op to the MAC is very slow, * we must wait before reading the data */ ndelay(500); /* read data read from the MAC register */ data_read = dnet_readl(bp, MACREG_DATA); /* all done */ return data_read; } /* function for writing internal MAC register */ static void dnet_writew_mac(struct dnet *bp, u16 reg, u16 val) { /* load data to write */ dnet_writel(bp, val, MACREG_DATA); /* issue a write */ dnet_writel(bp, reg | DNET_INTERNAL_WRITE, MACREG_ADDR); /* since a read/write op to the MAC is very slow, * we must wait before exiting */ ndelay(500); } static void __dnet_set_hwaddr(struct dnet *bp) { u16 tmp; tmp = be16_to_cpup((const __be16 *)bp->dev->dev_addr); dnet_writew_mac(bp, DNET_INTERNAL_MAC_ADDR_0_REG, tmp); tmp = be16_to_cpup((const __be16 *)(bp->dev->dev_addr + 2)); dnet_writew_mac(bp, DNET_INTERNAL_MAC_ADDR_1_REG, tmp); tmp = be16_to_cpup((const __be16 *)(bp->dev->dev_addr + 4)); dnet_writew_mac(bp, DNET_INTERNAL_MAC_ADDR_2_REG, tmp); } static void dnet_get_hwaddr(struct dnet *bp) { u16 tmp; u8 addr[6]; /* * from MAC docs: * "Note that the MAC address is stored in the registers in Hexadecimal * form. For example, to set the MAC Address to: AC-DE-48-00-00-80 * would require writing 0xAC (octet 0) to address 0x0B (high byte of * Mac_addr[15:0]), 0xDE (octet 1) to address 0x0A (Low byte of * Mac_addr[15:0]), 0x48 (octet 2) to address 0x0D (high byte of * Mac_addr[15:0]), 0x00 (octet 3) to address 0x0C (Low byte of * Mac_addr[15:0]), 0x00 (octet 4) to address 0x0F (high byte of * Mac_addr[15:0]), and 0x80 (octet 5) to address * 0x0E (Low byte of * Mac_addr[15:0]). */ tmp = dnet_readw_mac(bp, DNET_INTERNAL_MAC_ADDR_0_REG); *((__be16 *)addr) = cpu_to_be16(tmp); tmp = dnet_readw_mac(bp, DNET_INTERNAL_MAC_ADDR_1_REG); *((__be16 *)(addr + 2)) = cpu_to_be16(tmp); tmp = dnet_readw_mac(bp, DNET_INTERNAL_MAC_ADDR_2_REG); *((__be16 *)(addr + 4)) = cpu_to_be16(tmp); if (is_valid_ether_addr(addr)) eth_hw_addr_set(bp->dev, addr); } static int dnet_mdio_read(struct mii_bus *bus, int mii_id, int regnum) { struct dnet *bp = bus->priv; u16 value; while (!(dnet_readw_mac(bp, DNET_INTERNAL_GMII_MNG_CTL_REG) & DNET_INTERNAL_GMII_MNG_CMD_FIN)) cpu_relax(); /* only 5 bits allowed for phy-addr and reg_offset */ mii_id &= 0x1f; regnum &= 0x1f; /* prepare reg_value for a read */ value = (mii_id << 8); value |= regnum; /* write control word */ dnet_writew_mac(bp, DNET_INTERNAL_GMII_MNG_CTL_REG, value); /* wait for end of transfer */ while (!(dnet_readw_mac(bp, DNET_INTERNAL_GMII_MNG_CTL_REG) & DNET_INTERNAL_GMII_MNG_CMD_FIN)) cpu_relax(); value = dnet_readw_mac(bp, DNET_INTERNAL_GMII_MNG_DAT_REG); pr_debug("mdio_read %02x:%02x <- %04x\n", mii_id, regnum, value); return value; } static int dnet_mdio_write(struct mii_bus *bus, int mii_id, int regnum, u16 value) { struct dnet *bp = bus->priv; u16 tmp; pr_debug("mdio_write %02x:%02x <- %04x\n", mii_id, regnum, value); while (!(dnet_readw_mac(bp, DNET_INTERNAL_GMII_MNG_CTL_REG) & DNET_INTERNAL_GMII_MNG_CMD_FIN)) cpu_relax(); /* prepare for a write operation */ tmp = (1 << 13); /* only 5 bits allowed for phy-addr and reg_offset */ mii_id &= 0x1f; regnum &= 0x1f; /* only 16 bits on data */ value &= 0xffff; /* prepare reg_value for a write */ tmp |= (mii_id << 8); tmp |= regnum; /* write data to write first */ dnet_writew_mac(bp, DNET_INTERNAL_GMII_MNG_DAT_REG, value); /* write control word */ dnet_writew_mac(bp, DNET_INTERNAL_GMII_MNG_CTL_REG, tmp); while (!(dnet_readw_mac(bp, DNET_INTERNAL_GMII_MNG_CTL_REG) & DNET_INTERNAL_GMII_MNG_CMD_FIN)) cpu_relax(); return 0; } static void dnet_handle_link_change(struct net_device *dev) { struct dnet *bp = netdev_priv(dev); struct phy_device *phydev = dev->phydev; unsigned long flags; u32 mode_reg, ctl_reg; int status_change = 0; spin_lock_irqsave(&bp->lock, flags); mode_reg = dnet_readw_mac(bp, DNET_INTERNAL_MODE_REG); ctl_reg = dnet_readw_mac(bp, DNET_INTERNAL_RXTX_CONTROL_REG); if (phydev->link) { if (bp->duplex != phydev->duplex) { if (phydev->duplex) ctl_reg &= ~(DNET_INTERNAL_RXTX_CONTROL_ENABLEHALFDUP); else ctl_reg |= DNET_INTERNAL_RXTX_CONTROL_ENABLEHALFDUP; bp->duplex = phydev->duplex; status_change = 1; } if (bp->speed != phydev->speed) { status_change = 1; switch (phydev->speed) { case 1000: mode_reg |= DNET_INTERNAL_MODE_GBITEN; break; case 100: case 10: mode_reg &= ~DNET_INTERNAL_MODE_GBITEN; break; default: printk(KERN_WARNING "%s: Ack! Speed (%d) is not " "10/100/1000!\n", dev->name, phydev->speed); break; } bp->speed = phydev->speed; } } if (phydev->link != bp->link) { if (phydev->link) { mode_reg |= (DNET_INTERNAL_MODE_RXEN | DNET_INTERNAL_MODE_TXEN); } else { mode_reg &= ~(DNET_INTERNAL_MODE_RXEN | DNET_INTERNAL_MODE_TXEN); bp->speed = 0; bp->duplex = -1; } bp->link = phydev->link; status_change = 1; } if (status_change) { dnet_writew_mac(bp, DNET_INTERNAL_RXTX_CONTROL_REG, ctl_reg); dnet_writew_mac(bp, DNET_INTERNAL_MODE_REG, mode_reg); } spin_unlock_irqrestore(&bp->lock, flags); if (status_change) { if (phydev->link) printk(KERN_INFO "%s: link up (%d/%s)\n", dev->name, phydev->speed, DUPLEX_FULL == phydev->duplex ? "Full" : "Half"); else printk(KERN_INFO "%s: link down\n", dev->name); } } static int dnet_mii_probe(struct net_device *dev) { struct dnet *bp = netdev_priv(dev); struct phy_device *phydev = NULL; /* find the first phy */ phydev = phy_find_first(bp->mii_bus); if (!phydev) { printk(KERN_ERR "%s: no PHY found\n", dev->name); return -ENODEV; } /* TODO : add pin_irq */ /* attach the mac to the phy */ if (bp->capabilities & DNET_HAS_RMII) { phydev = phy_connect(dev, phydev_name(phydev), &dnet_handle_link_change, PHY_INTERFACE_MODE_RMII); } else { phydev = phy_connect(dev, phydev_name(phydev), &dnet_handle_link_change, PHY_INTERFACE_MODE_MII); } if (IS_ERR(phydev)) { printk(KERN_ERR "%s: Could not attach to PHY\n", dev->name); return PTR_ERR(phydev); } /* mask with MAC supported features */ if (bp->capabilities & DNET_HAS_GIGABIT) phy_set_max_speed(phydev, SPEED_1000); else phy_set_max_speed(phydev, SPEED_100); phy_support_asym_pause(phydev); bp->link = 0; bp->speed = 0; bp->duplex = -1; return 0; } static int dnet_mii_init(struct dnet *bp) { int err; bp->mii_bus = mdiobus_alloc(); if (bp->mii_bus == NULL) return -ENOMEM; bp->mii_bus->name = "dnet_mii_bus"; bp->mii_bus->read = &dnet_mdio_read; bp->mii_bus->write = &dnet_mdio_write; snprintf(bp->mii_bus->id, MII_BUS_ID_SIZE, "%s-%x", bp->pdev->name, bp->pdev->id); bp->mii_bus->priv = bp; if (mdiobus_register(bp->mii_bus)) { err = -ENXIO; goto err_out; } if (dnet_mii_probe(bp->dev) != 0) { err = -ENXIO; goto err_out_unregister_bus; } return 0; err_out_unregister_bus: mdiobus_unregister(bp->mii_bus); err_out: mdiobus_free(bp->mii_bus); return err; } /* For Neptune board: LINK1000 as Link LED and TX as activity LED */ static int dnet_phy_marvell_fixup(struct phy_device *phydev) { return phy_write(phydev, 0x18, 0x4148); } static void dnet_update_stats(struct dnet *bp) { u32 __iomem *reg = bp->regs + DNET_RX_PKT_IGNR_CNT; u32 *p = &bp->hw_stats.rx_pkt_ignr; u32 *end = &bp->hw_stats.rx_byte + 1; WARN_ON((unsigned long)(end - p - 1) != (DNET_RX_BYTE_CNT - DNET_RX_PKT_IGNR_CNT) / 4); for (; p < end; p++, reg++) *p += readl(reg); reg = bp->regs + DNET_TX_UNICAST_CNT; p = &bp->hw_stats.tx_unicast; end = &bp->hw_stats.tx_byte + 1; WARN_ON((unsigned long)(end - p - 1) != (DNET_TX_BYTE_CNT - DNET_TX_UNICAST_CNT) / 4); for (; p < end; p++, reg++) *p += readl(reg); } static int dnet_poll(struct napi_struct *napi, int budget) { struct dnet *bp = container_of(napi, struct dnet, napi); struct net_device *dev = bp->dev; int npackets = 0; unsigned int pkt_len; struct sk_buff *skb; unsigned int *data_ptr; u32 int_enable; u32 cmd_word; int i; while (npackets < budget) { /* * break out of while loop if there are no more * packets waiting */ if (!(dnet_readl(bp, RX_FIFO_WCNT) >> 16)) break; cmd_word = dnet_readl(bp, RX_LEN_FIFO); pkt_len = cmd_word & 0xFFFF; if (cmd_word & 0xDF180000) printk(KERN_ERR "%s packet receive error %x\n", __func__, cmd_word); skb = netdev_alloc_skb(dev, pkt_len + 5); if (skb != NULL) { /* Align IP on 16 byte boundaries */ skb_reserve(skb, 2); /* * 'skb_put()' points to the start of sk_buff * data area. */ data_ptr = skb_put(skb, pkt_len); for (i = 0; i < (pkt_len + 3) >> 2; i++) *data_ptr++ = dnet_readl(bp, RX_DATA_FIFO); skb->protocol = eth_type_trans(skb, dev); netif_receive_skb(skb); npackets++; } else printk(KERN_NOTICE "%s: No memory to allocate a sk_buff of " "size %u.\n", dev->name, pkt_len); } if (npackets < budget) { /* We processed all packets available. Tell NAPI it can * stop polling then re-enable rx interrupts. */ napi_complete_done(napi, npackets); int_enable = dnet_readl(bp, INTR_ENB); int_enable |= DNET_INTR_SRC_RX_CMDFIFOAF; dnet_writel(bp, int_enable, INTR_ENB); } return npackets; } static irqreturn_t dnet_interrupt(int irq, void *dev_id) { struct net_device *dev = dev_id; struct dnet *bp = netdev_priv(dev); u32 int_src, int_enable, int_current; unsigned long flags; unsigned int handled = 0; spin_lock_irqsave(&bp->lock, flags); /* read and clear the DNET irq (clear on read) */ int_src = dnet_readl(bp, INTR_SRC); int_enable = dnet_readl(bp, INTR_ENB); int_current = int_src & int_enable; /* restart the queue if we had stopped it for TX fifo almost full */ if (int_current & DNET_INTR_SRC_TX_FIFOAE) { int_enable = dnet_readl(bp, INTR_ENB); int_enable &= ~DNET_INTR_ENB_TX_FIFOAE; dnet_writel(bp, int_enable, INTR_ENB); netif_wake_queue(dev); handled = 1; } /* RX FIFO error checking */ if (int_current & (DNET_INTR_SRC_RX_CMDFIFOFF | DNET_INTR_SRC_RX_DATAFIFOFF)) { printk(KERN_ERR "%s: RX fifo error %x, irq %x\n", __func__, dnet_readl(bp, RX_STATUS), int_current); /* we can only flush the RX FIFOs */ dnet_writel(bp, DNET_SYS_CTL_RXFIFOFLUSH, SYS_CTL); ndelay(500); dnet_writel(bp, 0, SYS_CTL); handled = 1; } /* TX FIFO error checking */ if (int_current & (DNET_INTR_SRC_TX_FIFOFULL | DNET_INTR_SRC_TX_DISCFRM)) { printk(KERN_ERR "%s: TX fifo error %x, irq %x\n", __func__, dnet_readl(bp, TX_STATUS), int_current); /* we can only flush the TX FIFOs */ dnet_writel(bp, DNET_SYS_CTL_TXFIFOFLUSH, SYS_CTL); ndelay(500); dnet_writel(bp, 0, SYS_CTL); handled = 1; } if (int_current & DNET_INTR_SRC_RX_CMDFIFOAF) { if (napi_schedule_prep(&bp->napi)) { /* * There's no point taking any more interrupts * until we have processed the buffers */ /* Disable Rx interrupts and schedule NAPI poll */ int_enable = dnet_readl(bp, INTR_ENB); int_enable &= ~DNET_INTR_SRC_RX_CMDFIFOAF; dnet_writel(bp, int_enable, INTR_ENB); __napi_schedule(&bp->napi); } handled = 1; } if (!handled) pr_debug("%s: irq %x remains\n", __func__, int_current); spin_unlock_irqrestore(&bp->lock, flags); return IRQ_RETVAL(handled); } #ifdef DEBUG static inline void dnet_print_skb(struct sk_buff *skb) { int k; printk(KERN_DEBUG PFX "data:"); for (k = 0; k < skb->len; k++) printk(" %02x", (unsigned int)skb->data[k]); printk("\n"); } #else #define dnet_print_skb(skb) do {} while (0) #endif static netdev_tx_t dnet_start_xmit(struct sk_buff *skb, struct net_device *dev) { struct dnet *bp = netdev_priv(dev); unsigned int i, tx_cmd, wrsz; unsigned long flags; unsigned int *bufp; u32 irq_enable; dnet_readl(bp, TX_STATUS); pr_debug("start_xmit: len %u head %p data %p\n", skb->len, skb->head, skb->data); dnet_print_skb(skb); spin_lock_irqsave(&bp->lock, flags); dnet_readl(bp, TX_STATUS); bufp = (unsigned int *)(((unsigned long) skb->data) & ~0x3UL); wrsz = (u32) skb->len + 3; wrsz += ((unsigned long) skb->data) & 0x3; wrsz >>= 2; tx_cmd = ((((unsigned long)(skb->data)) & 0x03) << 16) | (u32) skb->len; /* check if there is enough room for the current frame */ if (wrsz < (DNET_FIFO_SIZE - dnet_readl(bp, TX_FIFO_WCNT))) { for (i = 0; i < wrsz; i++) dnet_writel(bp, *bufp++, TX_DATA_FIFO); /* * inform MAC that a packet's written and ready to be * shipped out */ dnet_writel(bp, tx_cmd, TX_LEN_FIFO); } if (dnet_readl(bp, TX_FIFO_WCNT) > DNET_FIFO_TX_DATA_AF_TH) { netif_stop_queue(dev); dnet_readl(bp, INTR_SRC); irq_enable = dnet_readl(bp, INTR_ENB); irq_enable |= DNET_INTR_ENB_TX_FIFOAE; dnet_writel(bp, irq_enable, INTR_ENB); } skb_tx_timestamp(skb); spin_unlock_irqrestore(&bp->lock, flags); /* free the buffer */ dev_kfree_skb(skb); return NETDEV_TX_OK; } static void dnet_reset_hw(struct dnet *bp) { /* put ts_mac in IDLE state i.e. disable rx/tx */ dnet_writew_mac(bp, DNET_INTERNAL_MODE_REG, DNET_INTERNAL_MODE_FCEN); /* * RX FIFO almost full threshold: only cmd FIFO almost full is * implemented for RX side */ dnet_writel(bp, DNET_FIFO_RX_CMD_AF_TH, RX_FIFO_TH); /* * TX FIFO almost empty threshold: only data FIFO almost empty * is implemented for TX side */ dnet_writel(bp, DNET_FIFO_TX_DATA_AE_TH, TX_FIFO_TH); /* flush rx/tx fifos */ dnet_writel(bp, DNET_SYS_CTL_RXFIFOFLUSH | DNET_SYS_CTL_TXFIFOFLUSH, SYS_CTL); msleep(1); dnet_writel(bp, 0, SYS_CTL); } static void dnet_init_hw(struct dnet *bp) { u32 config; dnet_reset_hw(bp); __dnet_set_hwaddr(bp); config = dnet_readw_mac(bp, DNET_INTERNAL_RXTX_CONTROL_REG); if (bp->dev->flags & IFF_PROMISC) /* Copy All Frames */ config |= DNET_INTERNAL_RXTX_CONTROL_ENPROMISC; if (!(bp->dev->flags & IFF_BROADCAST)) /* No BroadCast */ config |= DNET_INTERNAL_RXTX_CONTROL_RXMULTICAST; config |= DNET_INTERNAL_RXTX_CONTROL_RXPAUSE | DNET_INTERNAL_RXTX_CONTROL_RXBROADCAST | DNET_INTERNAL_RXTX_CONTROL_DROPCONTROL | DNET_INTERNAL_RXTX_CONTROL_DISCFXFCS; dnet_writew_mac(bp, DNET_INTERNAL_RXTX_CONTROL_REG, config); /* clear irq before enabling them */ config = dnet_readl(bp, INTR_SRC); /* enable RX/TX interrupt, recv packet ready interrupt */ dnet_writel(bp, DNET_INTR_ENB_GLOBAL_ENABLE | DNET_INTR_ENB_RX_SUMMARY | DNET_INTR_ENB_TX_SUMMARY | DNET_INTR_ENB_RX_FIFOERR | DNET_INTR_ENB_RX_ERROR | DNET_INTR_ENB_RX_FIFOFULL | DNET_INTR_ENB_TX_FIFOFULL | DNET_INTR_ENB_TX_DISCFRM | DNET_INTR_ENB_RX_PKTRDY, INTR_ENB); } static int dnet_open(struct net_device *dev) { struct dnet *bp = netdev_priv(dev); /* if the phy is not yet register, retry later */ if (!dev->phydev) return -EAGAIN; napi_enable(&bp->napi); dnet_init_hw(bp); phy_start_aneg(dev->phydev); /* schedule a link state check */ phy_start(dev->phydev); netif_start_queue(dev); return 0; } static int dnet_close(struct net_device *dev) { struct dnet *bp = netdev_priv(dev); netif_stop_queue(dev); napi_disable(&bp->napi); if (dev->phydev) phy_stop(dev->phydev); dnet_reset_hw(bp); netif_carrier_off(dev); return 0; } static inline void dnet_print_pretty_hwstats(struct dnet_stats *hwstat) { pr_debug("%s\n", __func__); pr_debug("----------------------------- RX statistics " "-------------------------------\n"); pr_debug("RX_PKT_IGNR_CNT %-8x\n", hwstat->rx_pkt_ignr); pr_debug("RX_LEN_CHK_ERR_CNT %-8x\n", hwstat->rx_len_chk_err); pr_debug("RX_LNG_FRM_CNT %-8x\n", hwstat->rx_lng_frm); pr_debug("RX_SHRT_FRM_CNT %-8x\n", hwstat->rx_shrt_frm); pr_debug("RX_IPG_VIOL_CNT %-8x\n", hwstat->rx_ipg_viol); pr_debug("RX_CRC_ERR_CNT %-8x\n", hwstat->rx_crc_err); pr_debug("RX_OK_PKT_CNT %-8x\n", hwstat->rx_ok_pkt); pr_debug("RX_CTL_FRM_CNT %-8x\n", hwstat->rx_ctl_frm); pr_debug("RX_PAUSE_FRM_CNT %-8x\n", hwstat->rx_pause_frm); pr_debug("RX_MULTICAST_CNT %-8x\n", hwstat->rx_multicast); pr_debug("RX_BROADCAST_CNT %-8x\n", hwstat->rx_broadcast); pr_debug("RX_VLAN_TAG_CNT %-8x\n", hwstat->rx_vlan_tag); pr_debug("RX_PRE_SHRINK_CNT %-8x\n", hwstat->rx_pre_shrink); pr_debug("RX_DRIB_NIB_CNT %-8x\n", hwstat->rx_drib_nib); pr_debug("RX_UNSUP_OPCD_CNT %-8x\n", hwstat->rx_unsup_opcd); pr_debug("RX_BYTE_CNT %-8x\n", hwstat->rx_byte); pr_debug("----------------------------- TX statistics " "-------------------------------\n"); pr_debug("TX_UNICAST_CNT %-8x\n", hwstat->tx_unicast); pr_debug("TX_PAUSE_FRM_CNT %-8x\n", hwstat->tx_pause_frm); pr_debug("TX_MULTICAST_CNT %-8x\n", hwstat->tx_multicast); pr_debug("TX_BRDCAST_CNT %-8x\n", hwstat->tx_brdcast); pr_debug("TX_VLAN_TAG_CNT %-8x\n", hwstat->tx_vlan_tag); pr_debug("TX_BAD_FCS_CNT %-8x\n", hwstat->tx_bad_fcs); pr_debug("TX_JUMBO_CNT %-8x\n", hwstat->tx_jumbo); pr_debug("TX_BYTE_CNT %-8x\n", hwstat->tx_byte); } static struct net_device_stats *dnet_get_stats(struct net_device *dev) { struct dnet *bp = netdev_priv(dev); struct net_device_stats *nstat = &dev->stats; struct dnet_stats *hwstat = &bp->hw_stats; /* read stats from hardware */ dnet_update_stats(bp); /* Convert HW stats into netdevice stats */ nstat->rx_errors = (hwstat->rx_len_chk_err + hwstat->rx_lng_frm + hwstat->rx_shrt_frm + /* ignore IGP violation error hwstat->rx_ipg_viol + */ hwstat->rx_crc_err + hwstat->rx_pre_shrink + hwstat->rx_drib_nib + hwstat->rx_unsup_opcd); nstat->tx_errors = hwstat->tx_bad_fcs; nstat->rx_length_errors = (hwstat->rx_len_chk_err + hwstat->rx_lng_frm + hwstat->rx_shrt_frm + hwstat->rx_pre_shrink); nstat->rx_crc_errors = hwstat->rx_crc_err; nstat->rx_frame_errors = hwstat->rx_pre_shrink + hwstat->rx_drib_nib; nstat->rx_packets = hwstat->rx_ok_pkt; nstat->tx_packets = (hwstat->tx_unicast + hwstat->tx_multicast + hwstat->tx_brdcast); nstat->rx_bytes = hwstat->rx_byte; nstat->tx_bytes = hwstat->tx_byte; nstat->multicast = hwstat->rx_multicast; nstat->rx_missed_errors = hwstat->rx_pkt_ignr; dnet_print_pretty_hwstats(hwstat); return nstat; } static void dnet_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { strscpy(info->driver, DRV_NAME, sizeof(info->driver)); strscpy(info->bus_info, "0", sizeof(info->bus_info)); } static const struct ethtool_ops dnet_ethtool_ops = { .get_drvinfo = dnet_get_drvinfo, .get_link = ethtool_op_get_link, .get_ts_info = ethtool_op_get_ts_info, .get_link_ksettings = phy_ethtool_get_link_ksettings, .set_link_ksettings = phy_ethtool_set_link_ksettings, }; static const struct net_device_ops dnet_netdev_ops = { .ndo_open = dnet_open, .ndo_stop = dnet_close, .ndo_get_stats = dnet_get_stats, .ndo_start_xmit = dnet_start_xmit, .ndo_eth_ioctl = phy_do_ioctl_running, .ndo_set_mac_address = eth_mac_addr, .ndo_validate_addr = eth_validate_addr, }; static int dnet_probe(struct platform_device *pdev) { struct resource *res; struct net_device *dev; struct dnet *bp; struct phy_device *phydev; int err; unsigned int irq; irq = platform_get_irq(pdev, 0); dev = alloc_etherdev(sizeof(*bp)); if (!dev) return -ENOMEM; /* TODO: Actually, we have some interesting features... */ dev->features |= 0; bp = netdev_priv(dev); bp->dev = dev; platform_set_drvdata(pdev, dev); SET_NETDEV_DEV(dev, &pdev->dev); spin_lock_init(&bp->lock); bp->regs = devm_platform_get_and_ioremap_resource(pdev, 0, &res); if (IS_ERR(bp->regs)) { err = PTR_ERR(bp->regs); goto err_out_free_dev; } dev->irq = irq; err = request_irq(dev->irq, dnet_interrupt, 0, DRV_NAME, dev); if (err) { dev_err(&pdev->dev, "Unable to request IRQ %d (error %d)\n", irq, err); goto err_out_free_dev; } dev->netdev_ops = &dnet_netdev_ops; netif_napi_add(dev, &bp->napi, dnet_poll); dev->ethtool_ops = &dnet_ethtool_ops; dev->base_addr = (unsigned long)bp->regs; bp->capabilities = dnet_readl(bp, VERCAPS) & DNET_CAPS_MASK; dnet_get_hwaddr(bp); if (!is_valid_ether_addr(dev->dev_addr)) { /* choose a random ethernet address */ eth_hw_addr_random(dev); __dnet_set_hwaddr(bp); } err = register_netdev(dev); if (err) { dev_err(&pdev->dev, "Cannot register net device, aborting.\n"); goto err_out_free_irq; } /* register the PHY board fixup (for Marvell 88E1111) */ err = phy_register_fixup_for_uid(0x01410cc0, 0xfffffff0, dnet_phy_marvell_fixup); /* we can live without it, so just issue a warning */ if (err) dev_warn(&pdev->dev, "Cannot register PHY board fixup.\n"); err = dnet_mii_init(bp); if (err) goto err_out_unregister_netdev; dev_info(&pdev->dev, "Dave DNET at 0x%p (0x%08x) irq %d %pM\n", bp->regs, (unsigned int)res->start, dev->irq, dev->dev_addr); dev_info(&pdev->dev, "has %smdio, %sirq, %sgigabit, %sdma\n", (bp->capabilities & DNET_HAS_MDIO) ? "" : "no ", (bp->capabilities & DNET_HAS_IRQ) ? "" : "no ", (bp->capabilities & DNET_HAS_GIGABIT) ? "" : "no ", (bp->capabilities & DNET_HAS_DMA) ? "" : "no "); phydev = dev->phydev; phy_attached_info(phydev); return 0; err_out_unregister_netdev: unregister_netdev(dev); err_out_free_irq: free_irq(dev->irq, dev); err_out_free_dev: free_netdev(dev); return err; } static int dnet_remove(struct platform_device *pdev) { struct net_device *dev; struct dnet *bp; dev = platform_get_drvdata(pdev); if (dev) { bp = netdev_priv(dev); if (dev->phydev) phy_disconnect(dev->phydev); mdiobus_unregister(bp->mii_bus); mdiobus_free(bp->mii_bus); unregister_netdev(dev); free_irq(dev->irq, dev); free_netdev(dev); } return 0; } static struct platform_driver dnet_driver = { .probe = dnet_probe, .remove = dnet_remove, .driver = { .name = "dnet", }, }; module_platform_driver(dnet_driver); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Dave DNET Ethernet driver"); MODULE_AUTHOR("Ilya Yanok <[email protected]>, " "Matteo Vit <[email protected]>");
linux-master
drivers/net/ethernet/dnet.c
/* * Driver for the IDT RC32434 (Korina) on-chip ethernet controller. * * Copyright 2004 IDT Inc. ([email protected]) * Copyright 2006 Felix Fietkau <[email protected]> * Copyright 2008 Florian Fainelli <[email protected]> * Copyright 2017 Roman Yeryomin <[email protected]> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 675 Mass Ave, Cambridge, MA 02139, USA. * * Writing to a DMA status register: * * When writing to the status register, you should mask the bit you have * been testing the status register with. Both Tx and Rx DMA registers * should stick to this procedure. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/moduleparam.h> #include <linux/sched.h> #include <linux/ctype.h> #include <linux/types.h> #include <linux/interrupt.h> #include <linux/ioport.h> #include <linux/iopoll.h> #include <linux/in.h> #include <linux/of.h> #include <linux/of_net.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/delay.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/skbuff.h> #include <linux/errno.h> #include <linux/platform_device.h> #include <linux/mii.h> #include <linux/ethtool.h> #include <linux/crc32.h> #include <linux/pgtable.h> #include <linux/clk.h> #define DRV_NAME "korina" #define DRV_VERSION "0.20" #define DRV_RELDATE "15Sep2017" struct eth_regs { u32 ethintfc; u32 ethfifott; u32 etharc; u32 ethhash0; u32 ethhash1; u32 ethu0[4]; /* Reserved. */ u32 ethpfs; u32 ethmcp; u32 eth_u1[10]; /* Reserved. */ u32 ethspare; u32 eth_u2[42]; /* Reserved. */ u32 ethsal0; u32 ethsah0; u32 ethsal1; u32 ethsah1; u32 ethsal2; u32 ethsah2; u32 ethsal3; u32 ethsah3; u32 ethrbc; u32 ethrpc; u32 ethrupc; u32 ethrfc; u32 ethtbc; u32 ethgpf; u32 eth_u9[50]; /* Reserved. */ u32 ethmac1; u32 ethmac2; u32 ethipgt; u32 ethipgr; u32 ethclrt; u32 ethmaxf; u32 eth_u10; /* Reserved. */ u32 ethmtest; u32 miimcfg; u32 miimcmd; u32 miimaddr; u32 miimwtd; u32 miimrdd; u32 miimind; u32 eth_u11; /* Reserved. */ u32 eth_u12; /* Reserved. */ u32 ethcfsa0; u32 ethcfsa1; u32 ethcfsa2; }; /* Ethernet interrupt registers */ #define ETH_INT_FC_EN BIT(0) #define ETH_INT_FC_ITS BIT(1) #define ETH_INT_FC_RIP BIT(2) #define ETH_INT_FC_JAM BIT(3) #define ETH_INT_FC_OVR BIT(4) #define ETH_INT_FC_UND BIT(5) #define ETH_INT_FC_IOC 0x000000c0 /* Ethernet FIFO registers */ #define ETH_FIFI_TT_TTH_BIT 0 #define ETH_FIFO_TT_TTH 0x0000007f /* Ethernet ARC/multicast registers */ #define ETH_ARC_PRO BIT(0) #define ETH_ARC_AM BIT(1) #define ETH_ARC_AFM BIT(2) #define ETH_ARC_AB BIT(3) /* Ethernet SAL registers */ #define ETH_SAL_BYTE_5 0x000000ff #define ETH_SAL_BYTE_4 0x0000ff00 #define ETH_SAL_BYTE_3 0x00ff0000 #define ETH_SAL_BYTE_2 0xff000000 /* Ethernet SAH registers */ #define ETH_SAH_BYTE1 0x000000ff #define ETH_SAH_BYTE0 0x0000ff00 /* Ethernet GPF register */ #define ETH_GPF_PTV 0x0000ffff /* Ethernet PFG register */ #define ETH_PFS_PFD BIT(0) /* Ethernet CFSA[0-3] registers */ #define ETH_CFSA0_CFSA4 0x000000ff #define ETH_CFSA0_CFSA5 0x0000ff00 #define ETH_CFSA1_CFSA2 0x000000ff #define ETH_CFSA1_CFSA3 0x0000ff00 #define ETH_CFSA1_CFSA0 0x000000ff #define ETH_CFSA1_CFSA1 0x0000ff00 /* Ethernet MAC1 registers */ #define ETH_MAC1_RE BIT(0) #define ETH_MAC1_PAF BIT(1) #define ETH_MAC1_RFC BIT(2) #define ETH_MAC1_TFC BIT(3) #define ETH_MAC1_LB BIT(4) #define ETH_MAC1_MR BIT(31) /* Ethernet MAC2 registers */ #define ETH_MAC2_FD BIT(0) #define ETH_MAC2_FLC BIT(1) #define ETH_MAC2_HFE BIT(2) #define ETH_MAC2_DC BIT(3) #define ETH_MAC2_CEN BIT(4) #define ETH_MAC2_PE BIT(5) #define ETH_MAC2_VPE BIT(6) #define ETH_MAC2_APE BIT(7) #define ETH_MAC2_PPE BIT(8) #define ETH_MAC2_LPE BIT(9) #define ETH_MAC2_NB BIT(12) #define ETH_MAC2_BP BIT(13) #define ETH_MAC2_ED BIT(14) /* Ethernet IPGT register */ #define ETH_IPGT 0x0000007f /* Ethernet IPGR registers */ #define ETH_IPGR_IPGR2 0x0000007f #define ETH_IPGR_IPGR1 0x00007f00 /* Ethernet CLRT registers */ #define ETH_CLRT_MAX_RET 0x0000000f #define ETH_CLRT_COL_WIN 0x00003f00 /* Ethernet MAXF register */ #define ETH_MAXF 0x0000ffff /* Ethernet test registers */ #define ETH_TEST_REG BIT(2) #define ETH_MCP_DIV 0x000000ff /* MII registers */ #define ETH_MII_CFG_RSVD 0x0000000c #define ETH_MII_CMD_RD BIT(0) #define ETH_MII_CMD_SCN BIT(1) #define ETH_MII_REG_ADDR 0x0000001f #define ETH_MII_PHY_ADDR 0x00001f00 #define ETH_MII_WTD_DATA 0x0000ffff #define ETH_MII_RDD_DATA 0x0000ffff #define ETH_MII_IND_BSY BIT(0) #define ETH_MII_IND_SCN BIT(1) #define ETH_MII_IND_NV BIT(2) /* Values for the DEVCS field of the Ethernet DMA Rx and Tx descriptors. */ #define ETH_RX_FD BIT(0) #define ETH_RX_LD BIT(1) #define ETH_RX_ROK BIT(2) #define ETH_RX_FM BIT(3) #define ETH_RX_MP BIT(4) #define ETH_RX_BP BIT(5) #define ETH_RX_VLT BIT(6) #define ETH_RX_CF BIT(7) #define ETH_RX_OVR BIT(8) #define ETH_RX_CRC BIT(9) #define ETH_RX_CV BIT(10) #define ETH_RX_DB BIT(11) #define ETH_RX_LE BIT(12) #define ETH_RX_LOR BIT(13) #define ETH_RX_CES BIT(14) #define ETH_RX_LEN_BIT 16 #define ETH_RX_LEN 0xffff0000 #define ETH_TX_FD BIT(0) #define ETH_TX_LD BIT(1) #define ETH_TX_OEN BIT(2) #define ETH_TX_PEN BIT(3) #define ETH_TX_CEN BIT(4) #define ETH_TX_HEN BIT(5) #define ETH_TX_TOK BIT(6) #define ETH_TX_MP BIT(7) #define ETH_TX_BP BIT(8) #define ETH_TX_UND BIT(9) #define ETH_TX_OF BIT(10) #define ETH_TX_ED BIT(11) #define ETH_TX_EC BIT(12) #define ETH_TX_LC BIT(13) #define ETH_TX_TD BIT(14) #define ETH_TX_CRC BIT(15) #define ETH_TX_LE BIT(16) #define ETH_TX_CC 0x001E0000 /* DMA descriptor (in physical memory). */ struct dma_desc { u32 control; /* Control. use DMAD_* */ u32 ca; /* Current Address. */ u32 devcs; /* Device control and status. */ u32 link; /* Next descriptor in chain. */ }; #define DMA_DESC_COUNT_BIT 0 #define DMA_DESC_COUNT_MSK 0x0003ffff #define DMA_DESC_DS_BIT 20 #define DMA_DESC_DS_MSK 0x00300000 #define DMA_DESC_DEV_CMD_BIT 22 #define DMA_DESC_DEV_CMD_MSK 0x01c00000 /* DMA descriptors interrupts */ #define DMA_DESC_COF BIT(25) /* Chain on finished */ #define DMA_DESC_COD BIT(26) /* Chain on done */ #define DMA_DESC_IOF BIT(27) /* Interrupt on finished */ #define DMA_DESC_IOD BIT(28) /* Interrupt on done */ #define DMA_DESC_TERM BIT(29) /* Terminated */ #define DMA_DESC_DONE BIT(30) /* Done */ #define DMA_DESC_FINI BIT(31) /* Finished */ /* DMA register (within Internal Register Map). */ struct dma_reg { u32 dmac; /* Control. */ u32 dmas; /* Status. */ u32 dmasm; /* Mask. */ u32 dmadptr; /* Descriptor pointer. */ u32 dmandptr; /* Next descriptor pointer. */ }; /* DMA channels specific registers */ #define DMA_CHAN_RUN_BIT BIT(0) #define DMA_CHAN_DONE_BIT BIT(1) #define DMA_CHAN_MODE_BIT BIT(2) #define DMA_CHAN_MODE_MSK 0x0000000c #define DMA_CHAN_MODE_AUTO 0 #define DMA_CHAN_MODE_BURST 1 #define DMA_CHAN_MODE_XFRT 2 #define DMA_CHAN_MODE_RSVD 3 #define DMA_CHAN_ACT_BIT BIT(4) /* DMA status registers */ #define DMA_STAT_FINI BIT(0) #define DMA_STAT_DONE BIT(1) #define DMA_STAT_CHAIN BIT(2) #define DMA_STAT_ERR BIT(3) #define DMA_STAT_HALT BIT(4) #define STATION_ADDRESS_HIGH(dev) (((dev)->dev_addr[0] << 8) | \ ((dev)->dev_addr[1])) #define STATION_ADDRESS_LOW(dev) (((dev)->dev_addr[2] << 24) | \ ((dev)->dev_addr[3] << 16) | \ ((dev)->dev_addr[4] << 8) | \ ((dev)->dev_addr[5])) #define MII_CLOCK 1250000 /* no more than 2.5MHz */ /* the following must be powers of two */ #define KORINA_NUM_RDS 64 /* number of receive descriptors */ #define KORINA_NUM_TDS 64 /* number of transmit descriptors */ /* KORINA_RBSIZE is the hardware's default maximum receive * frame size in bytes. Having this hardcoded means that there * is no support for MTU sizes greater than 1500. */ #define KORINA_RBSIZE 1536 /* size of one resource buffer = Ether MTU */ #define KORINA_RDS_MASK (KORINA_NUM_RDS - 1) #define KORINA_TDS_MASK (KORINA_NUM_TDS - 1) #define RD_RING_SIZE (KORINA_NUM_RDS * sizeof(struct dma_desc)) #define TD_RING_SIZE (KORINA_NUM_TDS * sizeof(struct dma_desc)) #define TX_TIMEOUT (6000 * HZ / 1000) enum chain_status { desc_filled, desc_is_empty }; #define DMA_COUNT(count) ((count) & DMA_DESC_COUNT_MSK) #define IS_DMA_FINISHED(X) (((X) & (DMA_DESC_FINI)) != 0) #define IS_DMA_DONE(X) (((X) & (DMA_DESC_DONE)) != 0) #define RCVPKT_LENGTH(X) (((X) & ETH_RX_LEN) >> ETH_RX_LEN_BIT) /* Information that need to be kept for each board. */ struct korina_private { struct eth_regs __iomem *eth_regs; struct dma_reg __iomem *rx_dma_regs; struct dma_reg __iomem *tx_dma_regs; struct dma_desc *td_ring; /* transmit descriptor ring */ struct dma_desc *rd_ring; /* receive descriptor ring */ dma_addr_t td_dma; dma_addr_t rd_dma; struct sk_buff *tx_skb[KORINA_NUM_TDS]; struct sk_buff *rx_skb[KORINA_NUM_RDS]; dma_addr_t rx_skb_dma[KORINA_NUM_RDS]; dma_addr_t tx_skb_dma[KORINA_NUM_TDS]; int rx_next_done; int rx_chain_head; int rx_chain_tail; enum chain_status rx_chain_status; int tx_next_done; int tx_chain_head; int tx_chain_tail; enum chain_status tx_chain_status; int tx_count; int tx_full; int rx_irq; int tx_irq; spinlock_t lock; /* NIC xmit lock */ int dma_halt_cnt; int dma_run_cnt; struct napi_struct napi; struct timer_list media_check_timer; struct mii_if_info mii_if; struct work_struct restart_task; struct net_device *dev; struct device *dmadev; int mii_clock_freq; }; static dma_addr_t korina_tx_dma(struct korina_private *lp, int idx) { return lp->td_dma + (idx * sizeof(struct dma_desc)); } static dma_addr_t korina_rx_dma(struct korina_private *lp, int idx) { return lp->rd_dma + (idx * sizeof(struct dma_desc)); } static inline void korina_abort_dma(struct net_device *dev, struct dma_reg *ch) { if (readl(&ch->dmac) & DMA_CHAN_RUN_BIT) { writel(0x10, &ch->dmac); while (!(readl(&ch->dmas) & DMA_STAT_HALT)) netif_trans_update(dev); writel(0, &ch->dmas); } writel(0, &ch->dmadptr); writel(0, &ch->dmandptr); } static void korina_abort_tx(struct net_device *dev) { struct korina_private *lp = netdev_priv(dev); korina_abort_dma(dev, lp->tx_dma_regs); } static void korina_abort_rx(struct net_device *dev) { struct korina_private *lp = netdev_priv(dev); korina_abort_dma(dev, lp->rx_dma_regs); } /* transmit packet */ static netdev_tx_t korina_send_packet(struct sk_buff *skb, struct net_device *dev) { struct korina_private *lp = netdev_priv(dev); u32 chain_prev, chain_next; unsigned long flags; struct dma_desc *td; dma_addr_t ca; u32 length; int idx; spin_lock_irqsave(&lp->lock, flags); idx = lp->tx_chain_tail; td = &lp->td_ring[idx]; /* stop queue when full, drop pkts if queue already full */ if (lp->tx_count >= (KORINA_NUM_TDS - 2)) { lp->tx_full = 1; if (lp->tx_count == (KORINA_NUM_TDS - 2)) netif_stop_queue(dev); else goto drop_packet; } lp->tx_count++; lp->tx_skb[idx] = skb; length = skb->len; /* Setup the transmit descriptor. */ ca = dma_map_single(lp->dmadev, skb->data, length, DMA_TO_DEVICE); if (dma_mapping_error(lp->dmadev, ca)) goto drop_packet; lp->tx_skb_dma[idx] = ca; td->ca = ca; chain_prev = (idx - 1) & KORINA_TDS_MASK; chain_next = (idx + 1) & KORINA_TDS_MASK; if (readl(&(lp->tx_dma_regs->dmandptr)) == 0) { if (lp->tx_chain_status == desc_is_empty) { /* Update tail */ td->control = DMA_COUNT(length) | DMA_DESC_COF | DMA_DESC_IOF; /* Move tail */ lp->tx_chain_tail = chain_next; /* Write to NDPTR */ writel(korina_tx_dma(lp, lp->tx_chain_head), &lp->tx_dma_regs->dmandptr); /* Move head to tail */ lp->tx_chain_head = lp->tx_chain_tail; } else { /* Update tail */ td->control = DMA_COUNT(length) | DMA_DESC_COF | DMA_DESC_IOF; /* Link to prev */ lp->td_ring[chain_prev].control &= ~DMA_DESC_COF; /* Link to prev */ lp->td_ring[chain_prev].link = korina_tx_dma(lp, idx); /* Move tail */ lp->tx_chain_tail = chain_next; /* Write to NDPTR */ writel(korina_tx_dma(lp, lp->tx_chain_head), &lp->tx_dma_regs->dmandptr); /* Move head to tail */ lp->tx_chain_head = lp->tx_chain_tail; lp->tx_chain_status = desc_is_empty; } } else { if (lp->tx_chain_status == desc_is_empty) { /* Update tail */ td->control = DMA_COUNT(length) | DMA_DESC_COF | DMA_DESC_IOF; /* Move tail */ lp->tx_chain_tail = chain_next; lp->tx_chain_status = desc_filled; } else { /* Update tail */ td->control = DMA_COUNT(length) | DMA_DESC_COF | DMA_DESC_IOF; lp->td_ring[chain_prev].control &= ~DMA_DESC_COF; lp->td_ring[chain_prev].link = korina_tx_dma(lp, idx); lp->tx_chain_tail = chain_next; } } netif_trans_update(dev); spin_unlock_irqrestore(&lp->lock, flags); return NETDEV_TX_OK; drop_packet: dev->stats.tx_dropped++; dev_kfree_skb_any(skb); spin_unlock_irqrestore(&lp->lock, flags); return NETDEV_TX_OK; } static int korina_mdio_wait(struct korina_private *lp) { u32 value; return readl_poll_timeout_atomic(&lp->eth_regs->miimind, value, value & ETH_MII_IND_BSY, 1, 1000); } static int korina_mdio_read(struct net_device *dev, int phy, int reg) { struct korina_private *lp = netdev_priv(dev); int ret; ret = korina_mdio_wait(lp); if (ret < 0) return ret; writel(phy << 8 | reg, &lp->eth_regs->miimaddr); writel(1, &lp->eth_regs->miimcmd); ret = korina_mdio_wait(lp); if (ret < 0) return ret; if (readl(&lp->eth_regs->miimind) & ETH_MII_IND_NV) return -EINVAL; ret = readl(&lp->eth_regs->miimrdd); writel(0, &lp->eth_regs->miimcmd); return ret; } static void korina_mdio_write(struct net_device *dev, int phy, int reg, int val) { struct korina_private *lp = netdev_priv(dev); if (korina_mdio_wait(lp)) return; writel(0, &lp->eth_regs->miimcmd); writel(phy << 8 | reg, &lp->eth_regs->miimaddr); writel(val, &lp->eth_regs->miimwtd); } /* Ethernet Rx DMA interrupt */ static irqreturn_t korina_rx_dma_interrupt(int irq, void *dev_id) { struct net_device *dev = dev_id; struct korina_private *lp = netdev_priv(dev); u32 dmas, dmasm; irqreturn_t retval; dmas = readl(&lp->rx_dma_regs->dmas); if (dmas & (DMA_STAT_DONE | DMA_STAT_HALT | DMA_STAT_ERR)) { dmasm = readl(&lp->rx_dma_regs->dmasm); writel(dmasm | (DMA_STAT_DONE | DMA_STAT_HALT | DMA_STAT_ERR), &lp->rx_dma_regs->dmasm); napi_schedule(&lp->napi); if (dmas & DMA_STAT_ERR) printk(KERN_ERR "%s: DMA error\n", dev->name); retval = IRQ_HANDLED; } else retval = IRQ_NONE; return retval; } static int korina_rx(struct net_device *dev, int limit) { struct korina_private *lp = netdev_priv(dev); struct dma_desc *rd = &lp->rd_ring[lp->rx_next_done]; struct sk_buff *skb, *skb_new; u32 devcs, pkt_len, dmas; dma_addr_t ca; int count; for (count = 0; count < limit; count++) { skb = lp->rx_skb[lp->rx_next_done]; skb_new = NULL; devcs = rd->devcs; if ((KORINA_RBSIZE - (u32)DMA_COUNT(rd->control)) == 0) break; /* check that this is a whole packet * WARNING: DMA_FD bit incorrectly set * in Rc32434 (errata ref #077) */ if (!(devcs & ETH_RX_LD)) goto next; if (!(devcs & ETH_RX_ROK)) { /* Update statistics counters */ dev->stats.rx_errors++; dev->stats.rx_dropped++; if (devcs & ETH_RX_CRC) dev->stats.rx_crc_errors++; if (devcs & ETH_RX_LE) dev->stats.rx_length_errors++; if (devcs & ETH_RX_OVR) dev->stats.rx_fifo_errors++; if (devcs & ETH_RX_CV) dev->stats.rx_frame_errors++; if (devcs & ETH_RX_CES) dev->stats.rx_frame_errors++; goto next; } /* Malloc up new buffer. */ skb_new = netdev_alloc_skb_ip_align(dev, KORINA_RBSIZE); if (!skb_new) break; ca = dma_map_single(lp->dmadev, skb_new->data, KORINA_RBSIZE, DMA_FROM_DEVICE); if (dma_mapping_error(lp->dmadev, ca)) { dev_kfree_skb_any(skb_new); break; } pkt_len = RCVPKT_LENGTH(devcs); dma_unmap_single(lp->dmadev, lp->rx_skb_dma[lp->rx_next_done], pkt_len, DMA_FROM_DEVICE); /* Do not count the CRC */ skb_put(skb, pkt_len - 4); skb->protocol = eth_type_trans(skb, dev); /* Pass the packet to upper layers */ napi_gro_receive(&lp->napi, skb); dev->stats.rx_packets++; dev->stats.rx_bytes += pkt_len; /* Update the mcast stats */ if (devcs & ETH_RX_MP) dev->stats.multicast++; lp->rx_skb[lp->rx_next_done] = skb_new; lp->rx_skb_dma[lp->rx_next_done] = ca; next: rd->devcs = 0; /* Restore descriptor's curr_addr */ rd->ca = lp->rx_skb_dma[lp->rx_next_done]; rd->control = DMA_COUNT(KORINA_RBSIZE) | DMA_DESC_COD | DMA_DESC_IOD; lp->rd_ring[(lp->rx_next_done - 1) & KORINA_RDS_MASK].control &= ~DMA_DESC_COD; lp->rx_next_done = (lp->rx_next_done + 1) & KORINA_RDS_MASK; rd = &lp->rd_ring[lp->rx_next_done]; writel((u32)~DMA_STAT_DONE, &lp->rx_dma_regs->dmas); } dmas = readl(&lp->rx_dma_regs->dmas); if (dmas & DMA_STAT_HALT) { writel((u32)~(DMA_STAT_HALT | DMA_STAT_ERR), &lp->rx_dma_regs->dmas); lp->dma_halt_cnt++; rd->devcs = 0; rd->ca = lp->rx_skb_dma[lp->rx_next_done]; writel(korina_rx_dma(lp, rd - lp->rd_ring), &lp->rx_dma_regs->dmandptr); } return count; } static int korina_poll(struct napi_struct *napi, int budget) { struct korina_private *lp = container_of(napi, struct korina_private, napi); struct net_device *dev = lp->dev; int work_done; work_done = korina_rx(dev, budget); if (work_done < budget) { napi_complete_done(napi, work_done); writel(readl(&lp->rx_dma_regs->dmasm) & ~(DMA_STAT_DONE | DMA_STAT_HALT | DMA_STAT_ERR), &lp->rx_dma_regs->dmasm); } return work_done; } /* * Set or clear the multicast filter for this adaptor. */ static void korina_multicast_list(struct net_device *dev) { struct korina_private *lp = netdev_priv(dev); unsigned long flags; struct netdev_hw_addr *ha; u32 recognise = ETH_ARC_AB; /* always accept broadcasts */ /* Set promiscuous mode */ if (dev->flags & IFF_PROMISC) recognise |= ETH_ARC_PRO; else if ((dev->flags & IFF_ALLMULTI) || (netdev_mc_count(dev) > 4)) /* All multicast and broadcast */ recognise |= ETH_ARC_AM; /* Build the hash table */ if (netdev_mc_count(dev) > 4) { u16 hash_table[4] = { 0 }; u32 crc; netdev_for_each_mc_addr(ha, dev) { crc = ether_crc_le(6, ha->addr); crc >>= 26; hash_table[crc >> 4] |= 1 << (15 - (crc & 0xf)); } /* Accept filtered multicast */ recognise |= ETH_ARC_AFM; /* Fill the MAC hash tables with their values */ writel((u32)(hash_table[1] << 16 | hash_table[0]), &lp->eth_regs->ethhash0); writel((u32)(hash_table[3] << 16 | hash_table[2]), &lp->eth_regs->ethhash1); } spin_lock_irqsave(&lp->lock, flags); writel(recognise, &lp->eth_regs->etharc); spin_unlock_irqrestore(&lp->lock, flags); } static void korina_tx(struct net_device *dev) { struct korina_private *lp = netdev_priv(dev); struct dma_desc *td = &lp->td_ring[lp->tx_next_done]; u32 devcs; u32 dmas; spin_lock(&lp->lock); /* Process all desc that are done */ while (IS_DMA_FINISHED(td->control)) { if (lp->tx_full == 1) { netif_wake_queue(dev); lp->tx_full = 0; } devcs = lp->td_ring[lp->tx_next_done].devcs; if ((devcs & (ETH_TX_FD | ETH_TX_LD)) != (ETH_TX_FD | ETH_TX_LD)) { dev->stats.tx_errors++; dev->stats.tx_dropped++; /* Should never happen */ printk(KERN_ERR "%s: split tx ignored\n", dev->name); } else if (devcs & ETH_TX_TOK) { dev->stats.tx_packets++; dev->stats.tx_bytes += lp->tx_skb[lp->tx_next_done]->len; } else { dev->stats.tx_errors++; dev->stats.tx_dropped++; /* Underflow */ if (devcs & ETH_TX_UND) dev->stats.tx_fifo_errors++; /* Oversized frame */ if (devcs & ETH_TX_OF) dev->stats.tx_aborted_errors++; /* Excessive deferrals */ if (devcs & ETH_TX_ED) dev->stats.tx_carrier_errors++; /* Collisions: medium busy */ if (devcs & ETH_TX_EC) dev->stats.collisions++; /* Late collision */ if (devcs & ETH_TX_LC) dev->stats.tx_window_errors++; } /* We must always free the original skb */ if (lp->tx_skb[lp->tx_next_done]) { dma_unmap_single(lp->dmadev, lp->tx_skb_dma[lp->tx_next_done], lp->tx_skb[lp->tx_next_done]->len, DMA_TO_DEVICE); dev_kfree_skb_any(lp->tx_skb[lp->tx_next_done]); lp->tx_skb[lp->tx_next_done] = NULL; } lp->td_ring[lp->tx_next_done].control = DMA_DESC_IOF; lp->td_ring[lp->tx_next_done].devcs = ETH_TX_FD | ETH_TX_LD; lp->td_ring[lp->tx_next_done].link = 0; lp->td_ring[lp->tx_next_done].ca = 0; lp->tx_count--; /* Go on to next transmission */ lp->tx_next_done = (lp->tx_next_done + 1) & KORINA_TDS_MASK; td = &lp->td_ring[lp->tx_next_done]; } /* Clear the DMA status register */ dmas = readl(&lp->tx_dma_regs->dmas); writel(~dmas, &lp->tx_dma_regs->dmas); writel(readl(&lp->tx_dma_regs->dmasm) & ~(DMA_STAT_FINI | DMA_STAT_ERR), &lp->tx_dma_regs->dmasm); spin_unlock(&lp->lock); } static irqreturn_t korina_tx_dma_interrupt(int irq, void *dev_id) { struct net_device *dev = dev_id; struct korina_private *lp = netdev_priv(dev); u32 dmas, dmasm; irqreturn_t retval; dmas = readl(&lp->tx_dma_regs->dmas); if (dmas & (DMA_STAT_FINI | DMA_STAT_ERR)) { dmasm = readl(&lp->tx_dma_regs->dmasm); writel(dmasm | (DMA_STAT_FINI | DMA_STAT_ERR), &lp->tx_dma_regs->dmasm); korina_tx(dev); if (lp->tx_chain_status == desc_filled && (readl(&(lp->tx_dma_regs->dmandptr)) == 0)) { writel(korina_tx_dma(lp, lp->tx_chain_head), &lp->tx_dma_regs->dmandptr); lp->tx_chain_status = desc_is_empty; lp->tx_chain_head = lp->tx_chain_tail; netif_trans_update(dev); } if (dmas & DMA_STAT_ERR) printk(KERN_ERR "%s: DMA error\n", dev->name); retval = IRQ_HANDLED; } else retval = IRQ_NONE; return retval; } static void korina_check_media(struct net_device *dev, unsigned int init_media) { struct korina_private *lp = netdev_priv(dev); mii_check_media(&lp->mii_if, 1, init_media); if (lp->mii_if.full_duplex) writel(readl(&lp->eth_regs->ethmac2) | ETH_MAC2_FD, &lp->eth_regs->ethmac2); else writel(readl(&lp->eth_regs->ethmac2) & ~ETH_MAC2_FD, &lp->eth_regs->ethmac2); } static void korina_poll_media(struct timer_list *t) { struct korina_private *lp = from_timer(lp, t, media_check_timer); struct net_device *dev = lp->dev; korina_check_media(dev, 0); mod_timer(&lp->media_check_timer, jiffies + HZ); } static void korina_set_carrier(struct mii_if_info *mii) { if (mii->force_media) { /* autoneg is off: Link is always assumed to be up */ if (!netif_carrier_ok(mii->dev)) netif_carrier_on(mii->dev); } else /* Let MMI library update carrier status */ korina_check_media(mii->dev, 0); } static int korina_ioctl(struct net_device *dev, struct ifreq *rq, int cmd) { struct korina_private *lp = netdev_priv(dev); struct mii_ioctl_data *data = if_mii(rq); int rc; if (!netif_running(dev)) return -EINVAL; spin_lock_irq(&lp->lock); rc = generic_mii_ioctl(&lp->mii_if, data, cmd, NULL); spin_unlock_irq(&lp->lock); korina_set_carrier(&lp->mii_if); return rc; } /* ethtool helpers */ static void netdev_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { struct korina_private *lp = netdev_priv(dev); strscpy(info->driver, DRV_NAME, sizeof(info->driver)); strscpy(info->version, DRV_VERSION, sizeof(info->version)); strscpy(info->bus_info, lp->dev->name, sizeof(info->bus_info)); } static int netdev_get_link_ksettings(struct net_device *dev, struct ethtool_link_ksettings *cmd) { struct korina_private *lp = netdev_priv(dev); spin_lock_irq(&lp->lock); mii_ethtool_get_link_ksettings(&lp->mii_if, cmd); spin_unlock_irq(&lp->lock); return 0; } static int netdev_set_link_ksettings(struct net_device *dev, const struct ethtool_link_ksettings *cmd) { struct korina_private *lp = netdev_priv(dev); int rc; spin_lock_irq(&lp->lock); rc = mii_ethtool_set_link_ksettings(&lp->mii_if, cmd); spin_unlock_irq(&lp->lock); korina_set_carrier(&lp->mii_if); return rc; } static u32 netdev_get_link(struct net_device *dev) { struct korina_private *lp = netdev_priv(dev); return mii_link_ok(&lp->mii_if); } static const struct ethtool_ops netdev_ethtool_ops = { .get_drvinfo = netdev_get_drvinfo, .get_link = netdev_get_link, .get_link_ksettings = netdev_get_link_ksettings, .set_link_ksettings = netdev_set_link_ksettings, }; static int korina_alloc_ring(struct net_device *dev) { struct korina_private *lp = netdev_priv(dev); struct sk_buff *skb; dma_addr_t ca; int i; /* Initialize the transmit descriptors */ for (i = 0; i < KORINA_NUM_TDS; i++) { lp->td_ring[i].control = DMA_DESC_IOF; lp->td_ring[i].devcs = ETH_TX_FD | ETH_TX_LD; lp->td_ring[i].ca = 0; lp->td_ring[i].link = 0; } lp->tx_next_done = lp->tx_chain_head = lp->tx_chain_tail = lp->tx_full = lp->tx_count = 0; lp->tx_chain_status = desc_is_empty; /* Initialize the receive descriptors */ for (i = 0; i < KORINA_NUM_RDS; i++) { skb = netdev_alloc_skb_ip_align(dev, KORINA_RBSIZE); if (!skb) return -ENOMEM; lp->rx_skb[i] = skb; lp->rd_ring[i].control = DMA_DESC_IOD | DMA_COUNT(KORINA_RBSIZE); lp->rd_ring[i].devcs = 0; ca = dma_map_single(lp->dmadev, skb->data, KORINA_RBSIZE, DMA_FROM_DEVICE); if (dma_mapping_error(lp->dmadev, ca)) return -ENOMEM; lp->rd_ring[i].ca = ca; lp->rx_skb_dma[i] = ca; lp->rd_ring[i].link = korina_rx_dma(lp, i + 1); } /* loop back receive descriptors, so the last * descriptor points to the first one */ lp->rd_ring[i - 1].link = lp->rd_dma; lp->rd_ring[i - 1].control |= DMA_DESC_COD; lp->rx_next_done = 0; lp->rx_chain_head = 0; lp->rx_chain_tail = 0; lp->rx_chain_status = desc_is_empty; return 0; } static void korina_free_ring(struct net_device *dev) { struct korina_private *lp = netdev_priv(dev); int i; for (i = 0; i < KORINA_NUM_RDS; i++) { lp->rd_ring[i].control = 0; if (lp->rx_skb[i]) { dma_unmap_single(lp->dmadev, lp->rx_skb_dma[i], KORINA_RBSIZE, DMA_FROM_DEVICE); dev_kfree_skb_any(lp->rx_skb[i]); lp->rx_skb[i] = NULL; } } for (i = 0; i < KORINA_NUM_TDS; i++) { lp->td_ring[i].control = 0; if (lp->tx_skb[i]) { dma_unmap_single(lp->dmadev, lp->tx_skb_dma[i], lp->tx_skb[i]->len, DMA_TO_DEVICE); dev_kfree_skb_any(lp->tx_skb[i]); lp->tx_skb[i] = NULL; } } } /* * Initialize the RC32434 ethernet controller. */ static int korina_init(struct net_device *dev) { struct korina_private *lp = netdev_priv(dev); /* Disable DMA */ korina_abort_tx(dev); korina_abort_rx(dev); /* reset ethernet logic */ writel(0, &lp->eth_regs->ethintfc); while ((readl(&lp->eth_regs->ethintfc) & ETH_INT_FC_RIP)) netif_trans_update(dev); /* Enable Ethernet Interface */ writel(ETH_INT_FC_EN, &lp->eth_regs->ethintfc); /* Allocate rings */ if (korina_alloc_ring(dev)) { printk(KERN_ERR "%s: descriptor allocation failed\n", dev->name); korina_free_ring(dev); return -ENOMEM; } writel(0, &lp->rx_dma_regs->dmas); /* Start Rx DMA */ writel(0, &lp->rx_dma_regs->dmandptr); writel(korina_rx_dma(lp, 0), &lp->rx_dma_regs->dmadptr); writel(readl(&lp->tx_dma_regs->dmasm) & ~(DMA_STAT_FINI | DMA_STAT_ERR), &lp->tx_dma_regs->dmasm); writel(readl(&lp->rx_dma_regs->dmasm) & ~(DMA_STAT_DONE | DMA_STAT_HALT | DMA_STAT_ERR), &lp->rx_dma_regs->dmasm); /* Accept only packets destined for this Ethernet device address */ writel(ETH_ARC_AB, &lp->eth_regs->etharc); /* Set all Ether station address registers to their initial values */ writel(STATION_ADDRESS_LOW(dev), &lp->eth_regs->ethsal0); writel(STATION_ADDRESS_HIGH(dev), &lp->eth_regs->ethsah0); writel(STATION_ADDRESS_LOW(dev), &lp->eth_regs->ethsal1); writel(STATION_ADDRESS_HIGH(dev), &lp->eth_regs->ethsah1); writel(STATION_ADDRESS_LOW(dev), &lp->eth_regs->ethsal2); writel(STATION_ADDRESS_HIGH(dev), &lp->eth_regs->ethsah2); writel(STATION_ADDRESS_LOW(dev), &lp->eth_regs->ethsal3); writel(STATION_ADDRESS_HIGH(dev), &lp->eth_regs->ethsah3); /* Frame Length Checking, Pad Enable, CRC Enable, Full Duplex set */ writel(ETH_MAC2_PE | ETH_MAC2_CEN | ETH_MAC2_FD, &lp->eth_regs->ethmac2); /* Back to back inter-packet-gap */ writel(0x15, &lp->eth_regs->ethipgt); /* Non - Back to back inter-packet-gap */ writel(0x12, &lp->eth_regs->ethipgr); /* Management Clock Prescaler Divisor * Clock independent setting */ writel(((lp->mii_clock_freq) / MII_CLOCK + 1) & ~1, &lp->eth_regs->ethmcp); writel(0, &lp->eth_regs->miimcfg); /* don't transmit until fifo contains 48b */ writel(48, &lp->eth_regs->ethfifott); writel(ETH_MAC1_RE, &lp->eth_regs->ethmac1); korina_check_media(dev, 1); napi_enable(&lp->napi); netif_start_queue(dev); return 0; } /* * Restart the RC32434 ethernet controller. */ static void korina_restart_task(struct work_struct *work) { struct korina_private *lp = container_of(work, struct korina_private, restart_task); struct net_device *dev = lp->dev; /* * Disable interrupts */ disable_irq(lp->rx_irq); disable_irq(lp->tx_irq); writel(readl(&lp->tx_dma_regs->dmasm) | DMA_STAT_FINI | DMA_STAT_ERR, &lp->tx_dma_regs->dmasm); writel(readl(&lp->rx_dma_regs->dmasm) | DMA_STAT_DONE | DMA_STAT_HALT | DMA_STAT_ERR, &lp->rx_dma_regs->dmasm); napi_disable(&lp->napi); korina_free_ring(dev); if (korina_init(dev) < 0) { printk(KERN_ERR "%s: cannot restart device\n", dev->name); return; } korina_multicast_list(dev); enable_irq(lp->tx_irq); enable_irq(lp->rx_irq); } static void korina_tx_timeout(struct net_device *dev, unsigned int txqueue) { struct korina_private *lp = netdev_priv(dev); schedule_work(&lp->restart_task); } #ifdef CONFIG_NET_POLL_CONTROLLER static void korina_poll_controller(struct net_device *dev) { disable_irq(dev->irq); korina_tx_dma_interrupt(dev->irq, dev); enable_irq(dev->irq); } #endif static int korina_open(struct net_device *dev) { struct korina_private *lp = netdev_priv(dev); int ret; /* Initialize */ ret = korina_init(dev); if (ret < 0) { printk(KERN_ERR "%s: cannot open device\n", dev->name); goto out; } /* Install the interrupt handler * that handles the Done Finished */ ret = request_irq(lp->rx_irq, korina_rx_dma_interrupt, 0, "Korina ethernet Rx", dev); if (ret < 0) { printk(KERN_ERR "%s: unable to get Rx DMA IRQ %d\n", dev->name, lp->rx_irq); goto err_release; } ret = request_irq(lp->tx_irq, korina_tx_dma_interrupt, 0, "Korina ethernet Tx", dev); if (ret < 0) { printk(KERN_ERR "%s: unable to get Tx DMA IRQ %d\n", dev->name, lp->tx_irq); goto err_free_rx_irq; } mod_timer(&lp->media_check_timer, jiffies + 1); out: return ret; err_free_rx_irq: free_irq(lp->rx_irq, dev); err_release: korina_free_ring(dev); goto out; } static int korina_close(struct net_device *dev) { struct korina_private *lp = netdev_priv(dev); u32 tmp; del_timer(&lp->media_check_timer); /* Disable interrupts */ disable_irq(lp->rx_irq); disable_irq(lp->tx_irq); korina_abort_tx(dev); tmp = readl(&lp->tx_dma_regs->dmasm); tmp = tmp | DMA_STAT_FINI | DMA_STAT_ERR; writel(tmp, &lp->tx_dma_regs->dmasm); korina_abort_rx(dev); tmp = readl(&lp->rx_dma_regs->dmasm); tmp = tmp | DMA_STAT_DONE | DMA_STAT_HALT | DMA_STAT_ERR; writel(tmp, &lp->rx_dma_regs->dmasm); napi_disable(&lp->napi); cancel_work_sync(&lp->restart_task); korina_free_ring(dev); free_irq(lp->rx_irq, dev); free_irq(lp->tx_irq, dev); return 0; } static const struct net_device_ops korina_netdev_ops = { .ndo_open = korina_open, .ndo_stop = korina_close, .ndo_start_xmit = korina_send_packet, .ndo_set_rx_mode = korina_multicast_list, .ndo_tx_timeout = korina_tx_timeout, .ndo_eth_ioctl = korina_ioctl, .ndo_validate_addr = eth_validate_addr, .ndo_set_mac_address = eth_mac_addr, #ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = korina_poll_controller, #endif }; static int korina_probe(struct platform_device *pdev) { u8 *mac_addr = dev_get_platdata(&pdev->dev); struct korina_private *lp; struct net_device *dev; struct clk *clk; void __iomem *p; int rc; dev = devm_alloc_etherdev(&pdev->dev, sizeof(struct korina_private)); if (!dev) return -ENOMEM; SET_NETDEV_DEV(dev, &pdev->dev); lp = netdev_priv(dev); if (mac_addr) eth_hw_addr_set(dev, mac_addr); else if (of_get_ethdev_address(pdev->dev.of_node, dev) < 0) eth_hw_addr_random(dev); clk = devm_clk_get_optional_enabled(&pdev->dev, "mdioclk"); if (IS_ERR(clk)) return PTR_ERR(clk); if (clk) { lp->mii_clock_freq = clk_get_rate(clk); } else { lp->mii_clock_freq = 200000000; /* max possible input clk */ } lp->rx_irq = platform_get_irq_byname(pdev, "rx"); lp->tx_irq = platform_get_irq_byname(pdev, "tx"); p = devm_platform_ioremap_resource_byname(pdev, "emac"); if (IS_ERR(p)) { printk(KERN_ERR DRV_NAME ": cannot remap registers\n"); return PTR_ERR(p); } lp->eth_regs = p; p = devm_platform_ioremap_resource_byname(pdev, "dma_rx"); if (IS_ERR(p)) { printk(KERN_ERR DRV_NAME ": cannot remap Rx DMA registers\n"); return PTR_ERR(p); } lp->rx_dma_regs = p; p = devm_platform_ioremap_resource_byname(pdev, "dma_tx"); if (IS_ERR(p)) { printk(KERN_ERR DRV_NAME ": cannot remap Tx DMA registers\n"); return PTR_ERR(p); } lp->tx_dma_regs = p; lp->td_ring = dmam_alloc_coherent(&pdev->dev, TD_RING_SIZE, &lp->td_dma, GFP_KERNEL); if (!lp->td_ring) return -ENOMEM; lp->rd_ring = dmam_alloc_coherent(&pdev->dev, RD_RING_SIZE, &lp->rd_dma, GFP_KERNEL); if (!lp->rd_ring) return -ENOMEM; spin_lock_init(&lp->lock); /* just use the rx dma irq */ dev->irq = lp->rx_irq; lp->dev = dev; lp->dmadev = &pdev->dev; dev->netdev_ops = &korina_netdev_ops; dev->ethtool_ops = &netdev_ethtool_ops; dev->watchdog_timeo = TX_TIMEOUT; netif_napi_add(dev, &lp->napi, korina_poll); lp->mii_if.dev = dev; lp->mii_if.mdio_read = korina_mdio_read; lp->mii_if.mdio_write = korina_mdio_write; lp->mii_if.phy_id = 1; lp->mii_if.phy_id_mask = 0x1f; lp->mii_if.reg_num_mask = 0x1f; platform_set_drvdata(pdev, dev); rc = register_netdev(dev); if (rc < 0) { printk(KERN_ERR DRV_NAME ": cannot register net device: %d\n", rc); return rc; } timer_setup(&lp->media_check_timer, korina_poll_media, 0); INIT_WORK(&lp->restart_task, korina_restart_task); printk(KERN_INFO "%s: " DRV_NAME "-" DRV_VERSION " " DRV_RELDATE "\n", dev->name); return rc; } static int korina_remove(struct platform_device *pdev) { struct net_device *dev = platform_get_drvdata(pdev); unregister_netdev(dev); return 0; } #ifdef CONFIG_OF static const struct of_device_id korina_match[] = { { .compatible = "idt,3243x-emac", }, { } }; MODULE_DEVICE_TABLE(of, korina_match); #endif static struct platform_driver korina_driver = { .driver = { .name = "korina", .of_match_table = of_match_ptr(korina_match), }, .probe = korina_probe, .remove = korina_remove, }; module_platform_driver(korina_driver); MODULE_AUTHOR("Philip Rischel <[email protected]>"); MODULE_AUTHOR("Felix Fietkau <[email protected]>"); MODULE_AUTHOR("Florian Fainelli <[email protected]>"); MODULE_AUTHOR("Roman Yeryomin <[email protected]>"); MODULE_DESCRIPTION("IDT RC32434 (Korina) Ethernet driver"); MODULE_LICENSE("GPL");
linux-master
drivers/net/ethernet/korina.c
// SPDX-License-Identifier: GPL-2.0-only /* * Network device driver for the MACE ethernet controller on * Apple Powermacs. Assumes it's under a DBDMA controller. * * Copyright (C) 1996 Paul Mackerras. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/delay.h> #include <linux/string.h> #include <linux/timer.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/crc32.h> #include <linux/spinlock.h> #include <linux/bitrev.h> #include <linux/slab.h> #include <linux/pgtable.h> #include <asm/dbdma.h> #include <asm/io.h> #include <asm/macio.h> #include "mace.h" static int port_aaui = -1; #define N_RX_RING 8 #define N_TX_RING 6 #define MAX_TX_ACTIVE 1 #define NCMDS_TX 1 /* dma commands per element in tx ring */ #define RX_BUFLEN (ETH_FRAME_LEN + 8) #define TX_TIMEOUT HZ /* 1 second */ /* Chip rev needs workaround on HW & multicast addr change */ #define BROKEN_ADDRCHG_REV 0x0941 /* Bits in transmit DMA status */ #define TX_DMA_ERR 0x80 struct mace_data { volatile struct mace __iomem *mace; volatile struct dbdma_regs __iomem *tx_dma; int tx_dma_intr; volatile struct dbdma_regs __iomem *rx_dma; int rx_dma_intr; volatile struct dbdma_cmd *tx_cmds; /* xmit dma command list */ volatile struct dbdma_cmd *rx_cmds; /* recv dma command list */ struct sk_buff *rx_bufs[N_RX_RING]; int rx_fill; int rx_empty; struct sk_buff *tx_bufs[N_TX_RING]; int tx_fill; int tx_empty; unsigned char maccc; unsigned char tx_fullup; unsigned char tx_active; unsigned char tx_bad_runt; struct timer_list tx_timeout; int timeout_active; int port_aaui; int chipid; struct macio_dev *mdev; spinlock_t lock; }; /* * Number of bytes of private data per MACE: allow enough for * the rx and tx dma commands plus a branch dma command each, * and another 16 bytes to allow us to align the dma command * buffers on a 16 byte boundary. */ #define PRIV_BYTES (sizeof(struct mace_data) \ + (N_RX_RING + NCMDS_TX * N_TX_RING + 3) * sizeof(struct dbdma_cmd)) static int mace_open(struct net_device *dev); static int mace_close(struct net_device *dev); static netdev_tx_t mace_xmit_start(struct sk_buff *skb, struct net_device *dev); static void mace_set_multicast(struct net_device *dev); static void mace_reset(struct net_device *dev); static int mace_set_address(struct net_device *dev, void *addr); static irqreturn_t mace_interrupt(int irq, void *dev_id); static irqreturn_t mace_txdma_intr(int irq, void *dev_id); static irqreturn_t mace_rxdma_intr(int irq, void *dev_id); static void mace_set_timeout(struct net_device *dev); static void mace_tx_timeout(struct timer_list *t); static inline void dbdma_reset(volatile struct dbdma_regs __iomem *dma); static inline void mace_clean_rings(struct mace_data *mp); static void __mace_set_address(struct net_device *dev, const void *addr); /* * If we can't get a skbuff when we need it, we use this area for DMA. */ static unsigned char *dummy_buf; static const struct net_device_ops mace_netdev_ops = { .ndo_open = mace_open, .ndo_stop = mace_close, .ndo_start_xmit = mace_xmit_start, .ndo_set_rx_mode = mace_set_multicast, .ndo_set_mac_address = mace_set_address, .ndo_validate_addr = eth_validate_addr, }; static int mace_probe(struct macio_dev *mdev, const struct of_device_id *match) { struct device_node *mace = macio_get_of_node(mdev); struct net_device *dev; struct mace_data *mp; const unsigned char *addr; u8 macaddr[ETH_ALEN]; int j, rev, rc = -EBUSY; if (macio_resource_count(mdev) != 3 || macio_irq_count(mdev) != 3) { printk(KERN_ERR "can't use MACE %pOF: need 3 addrs and 3 irqs\n", mace); return -ENODEV; } addr = of_get_property(mace, "mac-address", NULL); if (addr == NULL) { addr = of_get_property(mace, "local-mac-address", NULL); if (addr == NULL) { printk(KERN_ERR "Can't get mac-address for MACE %pOF\n", mace); return -ENODEV; } } /* * lazy allocate the driver-wide dummy buffer. (Note that we * never have more than one MACE in the system anyway) */ if (dummy_buf == NULL) { dummy_buf = kmalloc(RX_BUFLEN+2, GFP_KERNEL); if (dummy_buf == NULL) return -ENOMEM; } if (macio_request_resources(mdev, "mace")) { printk(KERN_ERR "MACE: can't request IO resources !\n"); return -EBUSY; } dev = alloc_etherdev(PRIV_BYTES); if (!dev) { rc = -ENOMEM; goto err_release; } SET_NETDEV_DEV(dev, &mdev->ofdev.dev); mp = netdev_priv(dev); mp->mdev = mdev; macio_set_drvdata(mdev, dev); dev->base_addr = macio_resource_start(mdev, 0); mp->mace = ioremap(dev->base_addr, 0x1000); if (mp->mace == NULL) { printk(KERN_ERR "MACE: can't map IO resources !\n"); rc = -ENOMEM; goto err_free; } dev->irq = macio_irq(mdev, 0); rev = addr[0] == 0 && addr[1] == 0xA0; for (j = 0; j < 6; ++j) { macaddr[j] = rev ? bitrev8(addr[j]): addr[j]; } eth_hw_addr_set(dev, macaddr); mp->chipid = (in_8(&mp->mace->chipid_hi) << 8) | in_8(&mp->mace->chipid_lo); mp = netdev_priv(dev); mp->maccc = ENXMT | ENRCV; mp->tx_dma = ioremap(macio_resource_start(mdev, 1), 0x1000); if (mp->tx_dma == NULL) { printk(KERN_ERR "MACE: can't map TX DMA resources !\n"); rc = -ENOMEM; goto err_unmap_io; } mp->tx_dma_intr = macio_irq(mdev, 1); mp->rx_dma = ioremap(macio_resource_start(mdev, 2), 0x1000); if (mp->rx_dma == NULL) { printk(KERN_ERR "MACE: can't map RX DMA resources !\n"); rc = -ENOMEM; goto err_unmap_tx_dma; } mp->rx_dma_intr = macio_irq(mdev, 2); mp->tx_cmds = (volatile struct dbdma_cmd *) DBDMA_ALIGN(mp + 1); mp->rx_cmds = mp->tx_cmds + NCMDS_TX * N_TX_RING + 1; memset((char *) mp->tx_cmds, 0, (NCMDS_TX*N_TX_RING + N_RX_RING + 2) * sizeof(struct dbdma_cmd)); timer_setup(&mp->tx_timeout, mace_tx_timeout, 0); spin_lock_init(&mp->lock); mp->timeout_active = 0; if (port_aaui >= 0) mp->port_aaui = port_aaui; else { /* Apple Network Server uses the AAUI port */ if (of_machine_is_compatible("AAPL,ShinerESB")) mp->port_aaui = 1; else { #ifdef CONFIG_MACE_AAUI_PORT mp->port_aaui = 1; #else mp->port_aaui = 0; #endif } } dev->netdev_ops = &mace_netdev_ops; /* * Most of what is below could be moved to mace_open() */ mace_reset(dev); rc = request_irq(dev->irq, mace_interrupt, 0, "MACE", dev); if (rc) { printk(KERN_ERR "MACE: can't get irq %d\n", dev->irq); goto err_unmap_rx_dma; } rc = request_irq(mp->tx_dma_intr, mace_txdma_intr, 0, "MACE-txdma", dev); if (rc) { printk(KERN_ERR "MACE: can't get irq %d\n", mp->tx_dma_intr); goto err_free_irq; } rc = request_irq(mp->rx_dma_intr, mace_rxdma_intr, 0, "MACE-rxdma", dev); if (rc) { printk(KERN_ERR "MACE: can't get irq %d\n", mp->rx_dma_intr); goto err_free_tx_irq; } rc = register_netdev(dev); if (rc) { printk(KERN_ERR "MACE: Cannot register net device, aborting.\n"); goto err_free_rx_irq; } printk(KERN_INFO "%s: MACE at %pM, chip revision %d.%d\n", dev->name, dev->dev_addr, mp->chipid >> 8, mp->chipid & 0xff); return 0; err_free_rx_irq: free_irq(macio_irq(mdev, 2), dev); err_free_tx_irq: free_irq(macio_irq(mdev, 1), dev); err_free_irq: free_irq(macio_irq(mdev, 0), dev); err_unmap_rx_dma: iounmap(mp->rx_dma); err_unmap_tx_dma: iounmap(mp->tx_dma); err_unmap_io: iounmap(mp->mace); err_free: free_netdev(dev); err_release: macio_release_resources(mdev); return rc; } static int mace_remove(struct macio_dev *mdev) { struct net_device *dev = macio_get_drvdata(mdev); struct mace_data *mp; BUG_ON(dev == NULL); macio_set_drvdata(mdev, NULL); mp = netdev_priv(dev); unregister_netdev(dev); free_irq(dev->irq, dev); free_irq(mp->tx_dma_intr, dev); free_irq(mp->rx_dma_intr, dev); iounmap(mp->rx_dma); iounmap(mp->tx_dma); iounmap(mp->mace); free_netdev(dev); macio_release_resources(mdev); return 0; } static void dbdma_reset(volatile struct dbdma_regs __iomem *dma) { int i; out_le32(&dma->control, (WAKE|FLUSH|PAUSE|RUN) << 16); /* * Yes this looks peculiar, but apparently it needs to be this * way on some machines. */ for (i = 200; i > 0; --i) if (le32_to_cpu(dma->control) & RUN) udelay(1); } static void mace_reset(struct net_device *dev) { struct mace_data *mp = netdev_priv(dev); volatile struct mace __iomem *mb = mp->mace; int i; /* soft-reset the chip */ i = 200; while (--i) { out_8(&mb->biucc, SWRST); if (in_8(&mb->biucc) & SWRST) { udelay(10); continue; } break; } if (!i) { printk(KERN_ERR "mace: cannot reset chip!\n"); return; } out_8(&mb->imr, 0xff); /* disable all intrs for now */ i = in_8(&mb->ir); out_8(&mb->maccc, 0); /* turn off tx, rx */ out_8(&mb->biucc, XMTSP_64); out_8(&mb->utr, RTRD); out_8(&mb->fifocc, RCVFW_32 | XMTFW_16 | XMTFWU | RCVFWU | XMTBRST); out_8(&mb->xmtfc, AUTO_PAD_XMIT); /* auto-pad short frames */ out_8(&mb->rcvfc, 0); /* load up the hardware address */ __mace_set_address(dev, dev->dev_addr); /* clear the multicast filter */ if (mp->chipid == BROKEN_ADDRCHG_REV) out_8(&mb->iac, LOGADDR); else { out_8(&mb->iac, ADDRCHG | LOGADDR); while ((in_8(&mb->iac) & ADDRCHG) != 0) ; } for (i = 0; i < 8; ++i) out_8(&mb->ladrf, 0); /* done changing address */ if (mp->chipid != BROKEN_ADDRCHG_REV) out_8(&mb->iac, 0); if (mp->port_aaui) out_8(&mb->plscc, PORTSEL_AUI + ENPLSIO); else out_8(&mb->plscc, PORTSEL_GPSI + ENPLSIO); } static void __mace_set_address(struct net_device *dev, const void *addr) { struct mace_data *mp = netdev_priv(dev); volatile struct mace __iomem *mb = mp->mace; const unsigned char *p = addr; u8 macaddr[ETH_ALEN]; int i; /* load up the hardware address */ if (mp->chipid == BROKEN_ADDRCHG_REV) out_8(&mb->iac, PHYADDR); else { out_8(&mb->iac, ADDRCHG | PHYADDR); while ((in_8(&mb->iac) & ADDRCHG) != 0) ; } for (i = 0; i < 6; ++i) out_8(&mb->padr, macaddr[i] = p[i]); eth_hw_addr_set(dev, macaddr); if (mp->chipid != BROKEN_ADDRCHG_REV) out_8(&mb->iac, 0); } static int mace_set_address(struct net_device *dev, void *addr) { struct mace_data *mp = netdev_priv(dev); volatile struct mace __iomem *mb = mp->mace; unsigned long flags; spin_lock_irqsave(&mp->lock, flags); __mace_set_address(dev, addr); /* note: setting ADDRCHG clears ENRCV */ out_8(&mb->maccc, mp->maccc); spin_unlock_irqrestore(&mp->lock, flags); return 0; } static inline void mace_clean_rings(struct mace_data *mp) { int i; /* free some skb's */ for (i = 0; i < N_RX_RING; ++i) { if (mp->rx_bufs[i] != NULL) { dev_kfree_skb(mp->rx_bufs[i]); mp->rx_bufs[i] = NULL; } } for (i = mp->tx_empty; i != mp->tx_fill; ) { dev_kfree_skb(mp->tx_bufs[i]); if (++i >= N_TX_RING) i = 0; } } static int mace_open(struct net_device *dev) { struct mace_data *mp = netdev_priv(dev); volatile struct mace __iomem *mb = mp->mace; volatile struct dbdma_regs __iomem *rd = mp->rx_dma; volatile struct dbdma_regs __iomem *td = mp->tx_dma; volatile struct dbdma_cmd *cp; int i; struct sk_buff *skb; unsigned char *data; /* reset the chip */ mace_reset(dev); /* initialize list of sk_buffs for receiving and set up recv dma */ mace_clean_rings(mp); memset((char *)mp->rx_cmds, 0, N_RX_RING * sizeof(struct dbdma_cmd)); cp = mp->rx_cmds; for (i = 0; i < N_RX_RING - 1; ++i) { skb = netdev_alloc_skb(dev, RX_BUFLEN + 2); if (!skb) { data = dummy_buf; } else { skb_reserve(skb, 2); /* so IP header lands on 4-byte bdry */ data = skb->data; } mp->rx_bufs[i] = skb; cp->req_count = cpu_to_le16(RX_BUFLEN); cp->command = cpu_to_le16(INPUT_LAST + INTR_ALWAYS); cp->phy_addr = cpu_to_le32(virt_to_bus(data)); cp->xfer_status = 0; ++cp; } mp->rx_bufs[i] = NULL; cp->command = cpu_to_le16(DBDMA_STOP); mp->rx_fill = i; mp->rx_empty = 0; /* Put a branch back to the beginning of the receive command list */ ++cp; cp->command = cpu_to_le16(DBDMA_NOP + BR_ALWAYS); cp->cmd_dep = cpu_to_le32(virt_to_bus(mp->rx_cmds)); /* start rx dma */ out_le32(&rd->control, (RUN|PAUSE|FLUSH|WAKE) << 16); /* clear run bit */ out_le32(&rd->cmdptr, virt_to_bus(mp->rx_cmds)); out_le32(&rd->control, (RUN << 16) | RUN); /* put a branch at the end of the tx command list */ cp = mp->tx_cmds + NCMDS_TX * N_TX_RING; cp->command = cpu_to_le16(DBDMA_NOP + BR_ALWAYS); cp->cmd_dep = cpu_to_le32(virt_to_bus(mp->tx_cmds)); /* reset tx dma */ out_le32(&td->control, (RUN|PAUSE|FLUSH|WAKE) << 16); out_le32(&td->cmdptr, virt_to_bus(mp->tx_cmds)); mp->tx_fill = 0; mp->tx_empty = 0; mp->tx_fullup = 0; mp->tx_active = 0; mp->tx_bad_runt = 0; /* turn it on! */ out_8(&mb->maccc, mp->maccc); /* enable all interrupts except receive interrupts */ out_8(&mb->imr, RCVINT); return 0; } static int mace_close(struct net_device *dev) { struct mace_data *mp = netdev_priv(dev); volatile struct mace __iomem *mb = mp->mace; volatile struct dbdma_regs __iomem *rd = mp->rx_dma; volatile struct dbdma_regs __iomem *td = mp->tx_dma; /* disable rx and tx */ out_8(&mb->maccc, 0); out_8(&mb->imr, 0xff); /* disable all intrs */ /* disable rx and tx dma */ rd->control = cpu_to_le32((RUN|PAUSE|FLUSH|WAKE) << 16); /* clear run bit */ td->control = cpu_to_le32((RUN|PAUSE|FLUSH|WAKE) << 16); /* clear run bit */ mace_clean_rings(mp); return 0; } static inline void mace_set_timeout(struct net_device *dev) { struct mace_data *mp = netdev_priv(dev); if (mp->timeout_active) del_timer(&mp->tx_timeout); mp->tx_timeout.expires = jiffies + TX_TIMEOUT; add_timer(&mp->tx_timeout); mp->timeout_active = 1; } static netdev_tx_t mace_xmit_start(struct sk_buff *skb, struct net_device *dev) { struct mace_data *mp = netdev_priv(dev); volatile struct dbdma_regs __iomem *td = mp->tx_dma; volatile struct dbdma_cmd *cp, *np; unsigned long flags; int fill, next, len; /* see if there's a free slot in the tx ring */ spin_lock_irqsave(&mp->lock, flags); fill = mp->tx_fill; next = fill + 1; if (next >= N_TX_RING) next = 0; if (next == mp->tx_empty) { netif_stop_queue(dev); mp->tx_fullup = 1; spin_unlock_irqrestore(&mp->lock, flags); return NETDEV_TX_BUSY; /* can't take it at the moment */ } spin_unlock_irqrestore(&mp->lock, flags); /* partially fill in the dma command block */ len = skb->len; if (len > ETH_FRAME_LEN) { printk(KERN_DEBUG "mace: xmit frame too long (%d)\n", len); len = ETH_FRAME_LEN; } mp->tx_bufs[fill] = skb; cp = mp->tx_cmds + NCMDS_TX * fill; cp->req_count = cpu_to_le16(len); cp->phy_addr = cpu_to_le32(virt_to_bus(skb->data)); np = mp->tx_cmds + NCMDS_TX * next; out_le16(&np->command, DBDMA_STOP); /* poke the tx dma channel */ spin_lock_irqsave(&mp->lock, flags); mp->tx_fill = next; if (!mp->tx_bad_runt && mp->tx_active < MAX_TX_ACTIVE) { out_le16(&cp->xfer_status, 0); out_le16(&cp->command, OUTPUT_LAST); out_le32(&td->control, ((RUN|WAKE) << 16) + (RUN|WAKE)); ++mp->tx_active; mace_set_timeout(dev); } if (++next >= N_TX_RING) next = 0; if (next == mp->tx_empty) netif_stop_queue(dev); spin_unlock_irqrestore(&mp->lock, flags); return NETDEV_TX_OK; } static void mace_set_multicast(struct net_device *dev) { struct mace_data *mp = netdev_priv(dev); volatile struct mace __iomem *mb = mp->mace; int i; u32 crc; unsigned long flags; spin_lock_irqsave(&mp->lock, flags); mp->maccc &= ~PROM; if (dev->flags & IFF_PROMISC) { mp->maccc |= PROM; } else { unsigned char multicast_filter[8]; struct netdev_hw_addr *ha; if (dev->flags & IFF_ALLMULTI) { for (i = 0; i < 8; i++) multicast_filter[i] = 0xff; } else { for (i = 0; i < 8; i++) multicast_filter[i] = 0; netdev_for_each_mc_addr(ha, dev) { crc = ether_crc_le(6, ha->addr); i = crc >> 26; /* bit number in multicast_filter */ multicast_filter[i >> 3] |= 1 << (i & 7); } } #if 0 printk("Multicast filter :"); for (i = 0; i < 8; i++) printk("%02x ", multicast_filter[i]); printk("\n"); #endif if (mp->chipid == BROKEN_ADDRCHG_REV) out_8(&mb->iac, LOGADDR); else { out_8(&mb->iac, ADDRCHG | LOGADDR); while ((in_8(&mb->iac) & ADDRCHG) != 0) ; } for (i = 0; i < 8; ++i) out_8(&mb->ladrf, multicast_filter[i]); if (mp->chipid != BROKEN_ADDRCHG_REV) out_8(&mb->iac, 0); } /* reset maccc */ out_8(&mb->maccc, mp->maccc); spin_unlock_irqrestore(&mp->lock, flags); } static void mace_handle_misc_intrs(struct mace_data *mp, int intr, struct net_device *dev) { volatile struct mace __iomem *mb = mp->mace; static int mace_babbles, mace_jabbers; if (intr & MPCO) dev->stats.rx_missed_errors += 256; dev->stats.rx_missed_errors += in_8(&mb->mpc); /* reading clears it */ if (intr & RNTPCO) dev->stats.rx_length_errors += 256; dev->stats.rx_length_errors += in_8(&mb->rntpc); /* reading clears it */ if (intr & CERR) ++dev->stats.tx_heartbeat_errors; if (intr & BABBLE) if (mace_babbles++ < 4) printk(KERN_DEBUG "mace: babbling transmitter\n"); if (intr & JABBER) if (mace_jabbers++ < 4) printk(KERN_DEBUG "mace: jabbering transceiver\n"); } static irqreturn_t mace_interrupt(int irq, void *dev_id) { struct net_device *dev = (struct net_device *) dev_id; struct mace_data *mp = netdev_priv(dev); volatile struct mace __iomem *mb = mp->mace; volatile struct dbdma_regs __iomem *td = mp->tx_dma; volatile struct dbdma_cmd *cp; int intr, fs, i, stat, x; int xcount, dstat; unsigned long flags; /* static int mace_last_fs, mace_last_xcount; */ spin_lock_irqsave(&mp->lock, flags); intr = in_8(&mb->ir); /* read interrupt register */ in_8(&mb->xmtrc); /* get retries */ mace_handle_misc_intrs(mp, intr, dev); i = mp->tx_empty; while (in_8(&mb->pr) & XMTSV) { del_timer(&mp->tx_timeout); mp->timeout_active = 0; /* * Clear any interrupt indication associated with this status * word. This appears to unlatch any error indication from * the DMA controller. */ intr = in_8(&mb->ir); if (intr != 0) mace_handle_misc_intrs(mp, intr, dev); if (mp->tx_bad_runt) { fs = in_8(&mb->xmtfs); mp->tx_bad_runt = 0; out_8(&mb->xmtfc, AUTO_PAD_XMIT); continue; } dstat = le32_to_cpu(td->status); /* stop DMA controller */ out_le32(&td->control, RUN << 16); /* * xcount is the number of complete frames which have been * written to the fifo but for which status has not been read. */ xcount = (in_8(&mb->fifofc) >> XMTFC_SH) & XMTFC_MASK; if (xcount == 0 || (dstat & DEAD)) { /* * If a packet was aborted before the DMA controller has * finished transferring it, it seems that there are 2 bytes * which are stuck in some buffer somewhere. These will get * transmitted as soon as we read the frame status (which * reenables the transmit data transfer request). Turning * off the DMA controller and/or resetting the MACE doesn't * help. So we disable auto-padding and FCS transmission * so the two bytes will only be a runt packet which should * be ignored by other stations. */ out_8(&mb->xmtfc, DXMTFCS); } fs = in_8(&mb->xmtfs); if ((fs & XMTSV) == 0) { printk(KERN_ERR "mace: xmtfs not valid! (fs=%x xc=%d ds=%x)\n", fs, xcount, dstat); mace_reset(dev); /* * XXX mace likes to hang the machine after a xmtfs error. * This is hard to reproduce, resetting *may* help */ } cp = mp->tx_cmds + NCMDS_TX * i; stat = le16_to_cpu(cp->xfer_status); if ((fs & (UFLO|LCOL|LCAR|RTRY)) || (dstat & DEAD) || xcount == 0) { /* * Check whether there were in fact 2 bytes written to * the transmit FIFO. */ udelay(1); x = (in_8(&mb->fifofc) >> XMTFC_SH) & XMTFC_MASK; if (x != 0) { /* there were two bytes with an end-of-packet indication */ mp->tx_bad_runt = 1; mace_set_timeout(dev); } else { /* * Either there weren't the two bytes buffered up, or they * didn't have an end-of-packet indication. * We flush the transmit FIFO just in case (by setting the * XMTFWU bit with the transmitter disabled). */ out_8(&mb->maccc, in_8(&mb->maccc) & ~ENXMT); out_8(&mb->fifocc, in_8(&mb->fifocc) | XMTFWU); udelay(1); out_8(&mb->maccc, in_8(&mb->maccc) | ENXMT); out_8(&mb->xmtfc, AUTO_PAD_XMIT); } } /* dma should have finished */ if (i == mp->tx_fill) { printk(KERN_DEBUG "mace: tx ring ran out? (fs=%x xc=%d ds=%x)\n", fs, xcount, dstat); continue; } /* Update stats */ if (fs & (UFLO|LCOL|LCAR|RTRY)) { ++dev->stats.tx_errors; if (fs & LCAR) ++dev->stats.tx_carrier_errors; if (fs & (UFLO|LCOL|RTRY)) ++dev->stats.tx_aborted_errors; } else { dev->stats.tx_bytes += mp->tx_bufs[i]->len; ++dev->stats.tx_packets; } dev_consume_skb_irq(mp->tx_bufs[i]); --mp->tx_active; if (++i >= N_TX_RING) i = 0; #if 0 mace_last_fs = fs; mace_last_xcount = xcount; #endif } if (i != mp->tx_empty) { mp->tx_fullup = 0; netif_wake_queue(dev); } mp->tx_empty = i; i += mp->tx_active; if (i >= N_TX_RING) i -= N_TX_RING; if (!mp->tx_bad_runt && i != mp->tx_fill && mp->tx_active < MAX_TX_ACTIVE) { do { /* set up the next one */ cp = mp->tx_cmds + NCMDS_TX * i; out_le16(&cp->xfer_status, 0); out_le16(&cp->command, OUTPUT_LAST); ++mp->tx_active; if (++i >= N_TX_RING) i = 0; } while (i != mp->tx_fill && mp->tx_active < MAX_TX_ACTIVE); out_le32(&td->control, ((RUN|WAKE) << 16) + (RUN|WAKE)); mace_set_timeout(dev); } spin_unlock_irqrestore(&mp->lock, flags); return IRQ_HANDLED; } static void mace_tx_timeout(struct timer_list *t) { struct mace_data *mp = from_timer(mp, t, tx_timeout); struct net_device *dev = macio_get_drvdata(mp->mdev); volatile struct mace __iomem *mb = mp->mace; volatile struct dbdma_regs __iomem *td = mp->tx_dma; volatile struct dbdma_regs __iomem *rd = mp->rx_dma; volatile struct dbdma_cmd *cp; unsigned long flags; int i; spin_lock_irqsave(&mp->lock, flags); mp->timeout_active = 0; if (mp->tx_active == 0 && !mp->tx_bad_runt) goto out; /* update various counters */ mace_handle_misc_intrs(mp, in_8(&mb->ir), dev); cp = mp->tx_cmds + NCMDS_TX * mp->tx_empty; /* turn off both tx and rx and reset the chip */ out_8(&mb->maccc, 0); printk(KERN_ERR "mace: transmit timeout - resetting\n"); dbdma_reset(td); mace_reset(dev); /* restart rx dma */ cp = bus_to_virt(le32_to_cpu(rd->cmdptr)); dbdma_reset(rd); out_le16(&cp->xfer_status, 0); out_le32(&rd->cmdptr, virt_to_bus(cp)); out_le32(&rd->control, (RUN << 16) | RUN); /* fix up the transmit side */ i = mp->tx_empty; mp->tx_active = 0; ++dev->stats.tx_errors; if (mp->tx_bad_runt) { mp->tx_bad_runt = 0; } else if (i != mp->tx_fill) { dev_kfree_skb_irq(mp->tx_bufs[i]); if (++i >= N_TX_RING) i = 0; mp->tx_empty = i; } mp->tx_fullup = 0; netif_wake_queue(dev); if (i != mp->tx_fill) { cp = mp->tx_cmds + NCMDS_TX * i; out_le16(&cp->xfer_status, 0); out_le16(&cp->command, OUTPUT_LAST); out_le32(&td->cmdptr, virt_to_bus(cp)); out_le32(&td->control, (RUN << 16) | RUN); ++mp->tx_active; mace_set_timeout(dev); } /* turn it back on */ out_8(&mb->imr, RCVINT); out_8(&mb->maccc, mp->maccc); out: spin_unlock_irqrestore(&mp->lock, flags); } static irqreturn_t mace_txdma_intr(int irq, void *dev_id) { return IRQ_HANDLED; } static irqreturn_t mace_rxdma_intr(int irq, void *dev_id) { struct net_device *dev = (struct net_device *) dev_id; struct mace_data *mp = netdev_priv(dev); volatile struct dbdma_regs __iomem *rd = mp->rx_dma; volatile struct dbdma_cmd *cp, *np; int i, nb, stat, next; struct sk_buff *skb; unsigned frame_status; static int mace_lost_status; unsigned char *data; unsigned long flags; spin_lock_irqsave(&mp->lock, flags); for (i = mp->rx_empty; i != mp->rx_fill; ) { cp = mp->rx_cmds + i; stat = le16_to_cpu(cp->xfer_status); if ((stat & ACTIVE) == 0) { next = i + 1; if (next >= N_RX_RING) next = 0; np = mp->rx_cmds + next; if (next != mp->rx_fill && (le16_to_cpu(np->xfer_status) & ACTIVE) != 0) { printk(KERN_DEBUG "mace: lost a status word\n"); ++mace_lost_status; } else break; } nb = le16_to_cpu(cp->req_count) - le16_to_cpu(cp->res_count); out_le16(&cp->command, DBDMA_STOP); /* got a packet, have a look at it */ skb = mp->rx_bufs[i]; if (!skb) { ++dev->stats.rx_dropped; } else if (nb > 8) { data = skb->data; frame_status = (data[nb-3] << 8) + data[nb-4]; if (frame_status & (RS_OFLO|RS_CLSN|RS_FRAMERR|RS_FCSERR)) { ++dev->stats.rx_errors; if (frame_status & RS_OFLO) ++dev->stats.rx_over_errors; if (frame_status & RS_FRAMERR) ++dev->stats.rx_frame_errors; if (frame_status & RS_FCSERR) ++dev->stats.rx_crc_errors; } else { /* Mace feature AUTO_STRIP_RCV is on by default, dropping the * FCS on frames with 802.3 headers. This means that Ethernet * frames have 8 extra octets at the end, while 802.3 frames * have only 4. We need to correctly account for this. */ if (*(unsigned short *)(data+12) < 1536) /* 802.3 header */ nb -= 4; else /* Ethernet header; mace includes FCS */ nb -= 8; skb_put(skb, nb); skb->protocol = eth_type_trans(skb, dev); dev->stats.rx_bytes += skb->len; netif_rx(skb); mp->rx_bufs[i] = NULL; ++dev->stats.rx_packets; } } else { ++dev->stats.rx_errors; ++dev->stats.rx_length_errors; } /* advance to next */ if (++i >= N_RX_RING) i = 0; } mp->rx_empty = i; i = mp->rx_fill; for (;;) { next = i + 1; if (next >= N_RX_RING) next = 0; if (next == mp->rx_empty) break; cp = mp->rx_cmds + i; skb = mp->rx_bufs[i]; if (!skb) { skb = netdev_alloc_skb(dev, RX_BUFLEN + 2); if (skb) { skb_reserve(skb, 2); mp->rx_bufs[i] = skb; } } cp->req_count = cpu_to_le16(RX_BUFLEN); data = skb? skb->data: dummy_buf; cp->phy_addr = cpu_to_le32(virt_to_bus(data)); out_le16(&cp->xfer_status, 0); out_le16(&cp->command, INPUT_LAST + INTR_ALWAYS); #if 0 if ((le32_to_cpu(rd->status) & ACTIVE) != 0) { out_le32(&rd->control, (PAUSE << 16) | PAUSE); while ((in_le32(&rd->status) & ACTIVE) != 0) ; } #endif i = next; } if (i != mp->rx_fill) { out_le32(&rd->control, ((RUN|WAKE) << 16) | (RUN|WAKE)); mp->rx_fill = i; } spin_unlock_irqrestore(&mp->lock, flags); return IRQ_HANDLED; } static const struct of_device_id mace_match[] = { { .name = "mace", }, {}, }; MODULE_DEVICE_TABLE (of, mace_match); static struct macio_driver mace_driver = { .driver = { .name = "mace", .owner = THIS_MODULE, .of_match_table = mace_match, }, .probe = mace_probe, .remove = mace_remove, }; static int __init mace_init(void) { return macio_register_driver(&mace_driver); } static void __exit mace_cleanup(void) { macio_unregister_driver(&mace_driver); kfree(dummy_buf); dummy_buf = NULL; } MODULE_AUTHOR("Paul Mackerras"); MODULE_DESCRIPTION("PowerMac MACE driver."); module_param(port_aaui, int, 0); MODULE_PARM_DESC(port_aaui, "MACE uses AAUI port (0-1)"); MODULE_LICENSE("GPL"); module_init(mace_init); module_exit(mace_cleanup);
linux-master
drivers/net/ethernet/apple/mace.c
// SPDX-License-Identifier: GPL-2.0-only /* * Network device driver for the BMAC ethernet controller on * Apple Powermacs. Assumes it's under a DBDMA controller. * * Copyright (C) 1998 Randy Gobbel. * * May 1999, Al Viro: proper release of /proc/net/bmac entry, switched to * dynamic procfs inode. */ #include <linux/interrupt.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/delay.h> #include <linux/string.h> #include <linux/timer.h> #include <linux/proc_fs.h> #include <linux/init.h> #include <linux/spinlock.h> #include <linux/crc32.h> #include <linux/crc32poly.h> #include <linux/bitrev.h> #include <linux/ethtool.h> #include <linux/slab.h> #include <linux/pgtable.h> #include <asm/dbdma.h> #include <asm/io.h> #include <asm/page.h> #include <asm/machdep.h> #include <asm/pmac_feature.h> #include <asm/macio.h> #include <asm/irq.h> #include "bmac.h" #define trunc_page(x) ((void *)(((unsigned long)(x)) & ~((unsigned long)(PAGE_SIZE - 1)))) #define round_page(x) trunc_page(((unsigned long)(x)) + ((unsigned long)(PAGE_SIZE - 1))) /* switch to use multicast code lifted from sunhme driver */ #define SUNHME_MULTICAST #define N_RX_RING 64 #define N_TX_RING 32 #define MAX_TX_ACTIVE 1 #define ETHERCRC 4 #define ETHERMINPACKET 64 #define ETHERMTU 1500 #define RX_BUFLEN (ETHERMTU + 14 + ETHERCRC + 2) #define TX_TIMEOUT HZ /* 1 second */ /* Bits in transmit DMA status */ #define TX_DMA_ERR 0x80 #define XXDEBUG(args) struct bmac_data { /* volatile struct bmac *bmac; */ struct sk_buff_head *queue; volatile struct dbdma_regs __iomem *tx_dma; int tx_dma_intr; volatile struct dbdma_regs __iomem *rx_dma; int rx_dma_intr; volatile struct dbdma_cmd *tx_cmds; /* xmit dma command list */ volatile struct dbdma_cmd *rx_cmds; /* recv dma command list */ struct macio_dev *mdev; int is_bmac_plus; struct sk_buff *rx_bufs[N_RX_RING]; int rx_fill; int rx_empty; struct sk_buff *tx_bufs[N_TX_RING]; int tx_fill; int tx_empty; unsigned char tx_fullup; struct timer_list tx_timeout; int timeout_active; int sleeping; int opened; unsigned short hash_use_count[64]; unsigned short hash_table_mask[4]; spinlock_t lock; }; #if 0 /* Move that to ethtool */ typedef struct bmac_reg_entry { char *name; unsigned short reg_offset; } bmac_reg_entry_t; #define N_REG_ENTRIES 31 static bmac_reg_entry_t reg_entries[N_REG_ENTRIES] = { {"MEMADD", MEMADD}, {"MEMDATAHI", MEMDATAHI}, {"MEMDATALO", MEMDATALO}, {"TXPNTR", TXPNTR}, {"RXPNTR", RXPNTR}, {"IPG1", IPG1}, {"IPG2", IPG2}, {"ALIMIT", ALIMIT}, {"SLOT", SLOT}, {"PALEN", PALEN}, {"PAPAT", PAPAT}, {"TXSFD", TXSFD}, {"JAM", JAM}, {"TXCFG", TXCFG}, {"TXMAX", TXMAX}, {"TXMIN", TXMIN}, {"PAREG", PAREG}, {"DCNT", DCNT}, {"NCCNT", NCCNT}, {"NTCNT", NTCNT}, {"EXCNT", EXCNT}, {"LTCNT", LTCNT}, {"TXSM", TXSM}, {"RXCFG", RXCFG}, {"RXMAX", RXMAX}, {"RXMIN", RXMIN}, {"FRCNT", FRCNT}, {"AECNT", AECNT}, {"FECNT", FECNT}, {"RXSM", RXSM}, {"RXCV", RXCV} }; #endif static unsigned char *bmac_emergency_rxbuf; /* * Number of bytes of private data per BMAC: allow enough for * the rx and tx dma commands plus a branch dma command each, * and another 16 bytes to allow us to align the dma command * buffers on a 16 byte boundary. */ #define PRIV_BYTES (sizeof(struct bmac_data) \ + (N_RX_RING + N_TX_RING + 4) * sizeof(struct dbdma_cmd) \ + sizeof(struct sk_buff_head)) static int bmac_open(struct net_device *dev); static int bmac_close(struct net_device *dev); static int bmac_transmit_packet(struct sk_buff *skb, struct net_device *dev); static void bmac_set_multicast(struct net_device *dev); static void bmac_reset_and_enable(struct net_device *dev); static void bmac_start_chip(struct net_device *dev); static void bmac_init_chip(struct net_device *dev); static void bmac_init_registers(struct net_device *dev); static void bmac_enable_and_reset_chip(struct net_device *dev); static int bmac_set_address(struct net_device *dev, void *addr); static irqreturn_t bmac_misc_intr(int irq, void *dev_id); static irqreturn_t bmac_txdma_intr(int irq, void *dev_id); static irqreturn_t bmac_rxdma_intr(int irq, void *dev_id); static void bmac_set_timeout(struct net_device *dev); static void bmac_tx_timeout(struct timer_list *t); static netdev_tx_t bmac_output(struct sk_buff *skb, struct net_device *dev); static void bmac_start(struct net_device *dev); #define DBDMA_SET(x) ( ((x) | (x) << 16) ) #define DBDMA_CLEAR(x) ( (x) << 16) static inline void dbdma_st32(volatile __u32 __iomem *a, unsigned long x) { __asm__ volatile( "stwbrx %0,0,%1" : : "r" (x), "r" (a) : "memory"); } static inline unsigned long dbdma_ld32(volatile __u32 __iomem *a) { __u32 swap; __asm__ volatile ("lwbrx %0,0,%1" : "=r" (swap) : "r" (a)); return swap; } static void dbdma_continue(volatile struct dbdma_regs __iomem *dmap) { dbdma_st32(&dmap->control, DBDMA_SET(RUN|WAKE) | DBDMA_CLEAR(PAUSE|DEAD)); eieio(); } static void dbdma_reset(volatile struct dbdma_regs __iomem *dmap) { dbdma_st32(&dmap->control, DBDMA_CLEAR(ACTIVE|DEAD|WAKE|FLUSH|PAUSE|RUN)); eieio(); while (dbdma_ld32(&dmap->status) & RUN) eieio(); } static void dbdma_setcmd(volatile struct dbdma_cmd *cp, unsigned short cmd, unsigned count, unsigned long addr, unsigned long cmd_dep) { out_le16(&cp->command, cmd); out_le16(&cp->req_count, count); out_le32(&cp->phy_addr, addr); out_le32(&cp->cmd_dep, cmd_dep); out_le16(&cp->xfer_status, 0); out_le16(&cp->res_count, 0); } static inline void bmwrite(struct net_device *dev, unsigned long reg_offset, unsigned data ) { out_le16((void __iomem *)dev->base_addr + reg_offset, data); } static inline unsigned short bmread(struct net_device *dev, unsigned long reg_offset ) { return in_le16((void __iomem *)dev->base_addr + reg_offset); } static void bmac_enable_and_reset_chip(struct net_device *dev) { struct bmac_data *bp = netdev_priv(dev); volatile struct dbdma_regs __iomem *rd = bp->rx_dma; volatile struct dbdma_regs __iomem *td = bp->tx_dma; if (rd) dbdma_reset(rd); if (td) dbdma_reset(td); pmac_call_feature(PMAC_FTR_BMAC_ENABLE, macio_get_of_node(bp->mdev), 0, 1); } #define MIFDELAY udelay(10) static unsigned int bmac_mif_readbits(struct net_device *dev, int nb) { unsigned int val = 0; while (--nb >= 0) { bmwrite(dev, MIFCSR, 0); MIFDELAY; if (bmread(dev, MIFCSR) & 8) val |= 1 << nb; bmwrite(dev, MIFCSR, 1); MIFDELAY; } bmwrite(dev, MIFCSR, 0); MIFDELAY; bmwrite(dev, MIFCSR, 1); MIFDELAY; return val; } static void bmac_mif_writebits(struct net_device *dev, unsigned int val, int nb) { int b; while (--nb >= 0) { b = (val & (1 << nb))? 6: 4; bmwrite(dev, MIFCSR, b); MIFDELAY; bmwrite(dev, MIFCSR, b|1); MIFDELAY; } } static unsigned int bmac_mif_read(struct net_device *dev, unsigned int addr) { unsigned int val; bmwrite(dev, MIFCSR, 4); MIFDELAY; bmac_mif_writebits(dev, ~0U, 32); bmac_mif_writebits(dev, 6, 4); bmac_mif_writebits(dev, addr, 10); bmwrite(dev, MIFCSR, 2); MIFDELAY; bmwrite(dev, MIFCSR, 1); MIFDELAY; val = bmac_mif_readbits(dev, 17); bmwrite(dev, MIFCSR, 4); MIFDELAY; return val; } static void bmac_mif_write(struct net_device *dev, unsigned int addr, unsigned int val) { bmwrite(dev, MIFCSR, 4); MIFDELAY; bmac_mif_writebits(dev, ~0U, 32); bmac_mif_writebits(dev, 5, 4); bmac_mif_writebits(dev, addr, 10); bmac_mif_writebits(dev, 2, 2); bmac_mif_writebits(dev, val, 16); bmac_mif_writebits(dev, 3, 2); } static void bmac_init_registers(struct net_device *dev) { struct bmac_data *bp = netdev_priv(dev); volatile unsigned short regValue; const unsigned short *pWord16; int i; /* XXDEBUG(("bmac: enter init_registers\n")); */ bmwrite(dev, RXRST, RxResetValue); bmwrite(dev, TXRST, TxResetBit); i = 100; do { --i; udelay(10000); regValue = bmread(dev, TXRST); /* wait for reset to clear..acknowledge */ } while ((regValue & TxResetBit) && i > 0); if (!bp->is_bmac_plus) { regValue = bmread(dev, XCVRIF); regValue |= ClkBit | SerialMode | COLActiveLow; bmwrite(dev, XCVRIF, regValue); udelay(10000); } bmwrite(dev, RSEED, (unsigned short)0x1968); regValue = bmread(dev, XIFC); regValue |= TxOutputEnable; bmwrite(dev, XIFC, regValue); bmread(dev, PAREG); /* set collision counters to 0 */ bmwrite(dev, NCCNT, 0); bmwrite(dev, NTCNT, 0); bmwrite(dev, EXCNT, 0); bmwrite(dev, LTCNT, 0); /* set rx counters to 0 */ bmwrite(dev, FRCNT, 0); bmwrite(dev, LECNT, 0); bmwrite(dev, AECNT, 0); bmwrite(dev, FECNT, 0); bmwrite(dev, RXCV, 0); /* set tx fifo information */ bmwrite(dev, TXTH, 4); /* 4 octets before tx starts */ bmwrite(dev, TXFIFOCSR, 0); /* first disable txFIFO */ bmwrite(dev, TXFIFOCSR, TxFIFOEnable ); /* set rx fifo information */ bmwrite(dev, RXFIFOCSR, 0); /* first disable rxFIFO */ bmwrite(dev, RXFIFOCSR, RxFIFOEnable ); //bmwrite(dev, TXCFG, TxMACEnable); /* TxNeverGiveUp maybe later */ bmread(dev, STATUS); /* read it just to clear it */ /* zero out the chip Hash Filter registers */ for (i=0; i<4; i++) bp->hash_table_mask[i] = 0; bmwrite(dev, BHASH3, bp->hash_table_mask[0]); /* bits 15 - 0 */ bmwrite(dev, BHASH2, bp->hash_table_mask[1]); /* bits 31 - 16 */ bmwrite(dev, BHASH1, bp->hash_table_mask[2]); /* bits 47 - 32 */ bmwrite(dev, BHASH0, bp->hash_table_mask[3]); /* bits 63 - 48 */ pWord16 = (const unsigned short *)dev->dev_addr; bmwrite(dev, MADD0, *pWord16++); bmwrite(dev, MADD1, *pWord16++); bmwrite(dev, MADD2, *pWord16); bmwrite(dev, RXCFG, RxCRCNoStrip | RxHashFilterEnable | RxRejectOwnPackets); bmwrite(dev, INTDISABLE, EnableNormal); } #if 0 static void bmac_disable_interrupts(struct net_device *dev) { bmwrite(dev, INTDISABLE, DisableAll); } static void bmac_enable_interrupts(struct net_device *dev) { bmwrite(dev, INTDISABLE, EnableNormal); } #endif static void bmac_start_chip(struct net_device *dev) { struct bmac_data *bp = netdev_priv(dev); volatile struct dbdma_regs __iomem *rd = bp->rx_dma; unsigned short oldConfig; /* enable rx dma channel */ dbdma_continue(rd); oldConfig = bmread(dev, TXCFG); bmwrite(dev, TXCFG, oldConfig | TxMACEnable ); /* turn on rx plus any other bits already on (promiscuous possibly) */ oldConfig = bmread(dev, RXCFG); bmwrite(dev, RXCFG, oldConfig | RxMACEnable ); udelay(20000); } static void bmac_init_phy(struct net_device *dev) { unsigned int addr; struct bmac_data *bp = netdev_priv(dev); printk(KERN_DEBUG "phy registers:"); for (addr = 0; addr < 32; ++addr) { if ((addr & 7) == 0) printk(KERN_DEBUG); printk(KERN_CONT " %.4x", bmac_mif_read(dev, addr)); } printk(KERN_CONT "\n"); if (bp->is_bmac_plus) { unsigned int capable, ctrl; ctrl = bmac_mif_read(dev, 0); capable = ((bmac_mif_read(dev, 1) & 0xf800) >> 6) | 1; if (bmac_mif_read(dev, 4) != capable || (ctrl & 0x1000) == 0) { bmac_mif_write(dev, 4, capable); bmac_mif_write(dev, 0, 0x1200); } else bmac_mif_write(dev, 0, 0x1000); } } static void bmac_init_chip(struct net_device *dev) { bmac_init_phy(dev); bmac_init_registers(dev); } #ifdef CONFIG_PM static int bmac_suspend(struct macio_dev *mdev, pm_message_t state) { struct net_device* dev = macio_get_drvdata(mdev); struct bmac_data *bp = netdev_priv(dev); unsigned long flags; unsigned short config; int i; netif_device_detach(dev); /* prolly should wait for dma to finish & turn off the chip */ spin_lock_irqsave(&bp->lock, flags); if (bp->timeout_active) { del_timer(&bp->tx_timeout); bp->timeout_active = 0; } disable_irq(dev->irq); disable_irq(bp->tx_dma_intr); disable_irq(bp->rx_dma_intr); bp->sleeping = 1; spin_unlock_irqrestore(&bp->lock, flags); if (bp->opened) { volatile struct dbdma_regs __iomem *rd = bp->rx_dma; volatile struct dbdma_regs __iomem *td = bp->tx_dma; config = bmread(dev, RXCFG); bmwrite(dev, RXCFG, (config & ~RxMACEnable)); config = bmread(dev, TXCFG); bmwrite(dev, TXCFG, (config & ~TxMACEnable)); bmwrite(dev, INTDISABLE, DisableAll); /* disable all intrs */ /* disable rx and tx dma */ rd->control = cpu_to_le32(DBDMA_CLEAR(RUN|PAUSE|FLUSH|WAKE)); /* clear run bit */ td->control = cpu_to_le32(DBDMA_CLEAR(RUN|PAUSE|FLUSH|WAKE)); /* clear run bit */ /* free some skb's */ for (i=0; i<N_RX_RING; i++) { if (bp->rx_bufs[i] != NULL) { dev_kfree_skb(bp->rx_bufs[i]); bp->rx_bufs[i] = NULL; } } for (i = 0; i<N_TX_RING; i++) { if (bp->tx_bufs[i] != NULL) { dev_kfree_skb(bp->tx_bufs[i]); bp->tx_bufs[i] = NULL; } } } pmac_call_feature(PMAC_FTR_BMAC_ENABLE, macio_get_of_node(bp->mdev), 0, 0); return 0; } static int bmac_resume(struct macio_dev *mdev) { struct net_device* dev = macio_get_drvdata(mdev); struct bmac_data *bp = netdev_priv(dev); /* see if this is enough */ if (bp->opened) bmac_reset_and_enable(dev); enable_irq(dev->irq); enable_irq(bp->tx_dma_intr); enable_irq(bp->rx_dma_intr); netif_device_attach(dev); return 0; } #endif /* CONFIG_PM */ static int bmac_set_address(struct net_device *dev, void *addr) { struct bmac_data *bp = netdev_priv(dev); const unsigned short *pWord16; unsigned long flags; XXDEBUG(("bmac: enter set_address\n")); spin_lock_irqsave(&bp->lock, flags); eth_hw_addr_set(dev, addr); /* load up the hardware address */ pWord16 = (const unsigned short *)dev->dev_addr; bmwrite(dev, MADD0, *pWord16++); bmwrite(dev, MADD1, *pWord16++); bmwrite(dev, MADD2, *pWord16); spin_unlock_irqrestore(&bp->lock, flags); XXDEBUG(("bmac: exit set_address\n")); return 0; } static inline void bmac_set_timeout(struct net_device *dev) { struct bmac_data *bp = netdev_priv(dev); unsigned long flags; spin_lock_irqsave(&bp->lock, flags); if (bp->timeout_active) del_timer(&bp->tx_timeout); bp->tx_timeout.expires = jiffies + TX_TIMEOUT; add_timer(&bp->tx_timeout); bp->timeout_active = 1; spin_unlock_irqrestore(&bp->lock, flags); } static void bmac_construct_xmt(struct sk_buff *skb, volatile struct dbdma_cmd *cp) { void *vaddr; unsigned long baddr; unsigned long len; len = skb->len; vaddr = skb->data; baddr = virt_to_bus(vaddr); dbdma_setcmd(cp, (OUTPUT_LAST | INTR_ALWAYS | WAIT_IFCLR), len, baddr, 0); } static void bmac_construct_rxbuff(struct sk_buff *skb, volatile struct dbdma_cmd *cp) { unsigned char *addr = skb? skb->data: bmac_emergency_rxbuf; dbdma_setcmd(cp, (INPUT_LAST | INTR_ALWAYS), RX_BUFLEN, virt_to_bus(addr), 0); } static void bmac_init_tx_ring(struct bmac_data *bp) { volatile struct dbdma_regs __iomem *td = bp->tx_dma; memset((char *)bp->tx_cmds, 0, (N_TX_RING+1) * sizeof(struct dbdma_cmd)); bp->tx_empty = 0; bp->tx_fill = 0; bp->tx_fullup = 0; /* put a branch at the end of the tx command list */ dbdma_setcmd(&bp->tx_cmds[N_TX_RING], (DBDMA_NOP | BR_ALWAYS), 0, 0, virt_to_bus(bp->tx_cmds)); /* reset tx dma */ dbdma_reset(td); out_le32(&td->wait_sel, 0x00200020); out_le32(&td->cmdptr, virt_to_bus(bp->tx_cmds)); } static int bmac_init_rx_ring(struct net_device *dev) { struct bmac_data *bp = netdev_priv(dev); volatile struct dbdma_regs __iomem *rd = bp->rx_dma; int i; struct sk_buff *skb; /* initialize list of sk_buffs for receiving and set up recv dma */ memset((char *)bp->rx_cmds, 0, (N_RX_RING + 1) * sizeof(struct dbdma_cmd)); for (i = 0; i < N_RX_RING; i++) { if ((skb = bp->rx_bufs[i]) == NULL) { bp->rx_bufs[i] = skb = netdev_alloc_skb(dev, RX_BUFLEN + 2); if (skb != NULL) skb_reserve(skb, 2); } bmac_construct_rxbuff(skb, &bp->rx_cmds[i]); } bp->rx_empty = 0; bp->rx_fill = i; /* Put a branch back to the beginning of the receive command list */ dbdma_setcmd(&bp->rx_cmds[N_RX_RING], (DBDMA_NOP | BR_ALWAYS), 0, 0, virt_to_bus(bp->rx_cmds)); /* start rx dma */ dbdma_reset(rd); out_le32(&rd->cmdptr, virt_to_bus(bp->rx_cmds)); return 1; } static int bmac_transmit_packet(struct sk_buff *skb, struct net_device *dev) { struct bmac_data *bp = netdev_priv(dev); volatile struct dbdma_regs __iomem *td = bp->tx_dma; int i; /* see if there's a free slot in the tx ring */ /* XXDEBUG(("bmac_xmit_start: empty=%d fill=%d\n", */ /* bp->tx_empty, bp->tx_fill)); */ i = bp->tx_fill + 1; if (i >= N_TX_RING) i = 0; if (i == bp->tx_empty) { netif_stop_queue(dev); bp->tx_fullup = 1; XXDEBUG(("bmac_transmit_packet: tx ring full\n")); return -1; /* can't take it at the moment */ } dbdma_setcmd(&bp->tx_cmds[i], DBDMA_STOP, 0, 0, 0); bmac_construct_xmt(skb, &bp->tx_cmds[bp->tx_fill]); bp->tx_bufs[bp->tx_fill] = skb; bp->tx_fill = i; dev->stats.tx_bytes += skb->len; dbdma_continue(td); return 0; } static int rxintcount; static irqreturn_t bmac_rxdma_intr(int irq, void *dev_id) { struct net_device *dev = (struct net_device *) dev_id; struct bmac_data *bp = netdev_priv(dev); volatile struct dbdma_regs __iomem *rd = bp->rx_dma; volatile struct dbdma_cmd *cp; int i, nb, stat; struct sk_buff *skb; unsigned int residual; int last; unsigned long flags; spin_lock_irqsave(&bp->lock, flags); if (++rxintcount < 10) { XXDEBUG(("bmac_rxdma_intr\n")); } last = -1; i = bp->rx_empty; while (1) { cp = &bp->rx_cmds[i]; stat = le16_to_cpu(cp->xfer_status); residual = le16_to_cpu(cp->res_count); if ((stat & ACTIVE) == 0) break; nb = RX_BUFLEN - residual - 2; if (nb < (ETHERMINPACKET - ETHERCRC)) { skb = NULL; dev->stats.rx_length_errors++; dev->stats.rx_errors++; } else { skb = bp->rx_bufs[i]; bp->rx_bufs[i] = NULL; } if (skb != NULL) { nb -= ETHERCRC; skb_put(skb, nb); skb->protocol = eth_type_trans(skb, dev); netif_rx(skb); ++dev->stats.rx_packets; dev->stats.rx_bytes += nb; } else { ++dev->stats.rx_dropped; } if ((skb = bp->rx_bufs[i]) == NULL) { bp->rx_bufs[i] = skb = netdev_alloc_skb(dev, RX_BUFLEN + 2); if (skb != NULL) skb_reserve(bp->rx_bufs[i], 2); } bmac_construct_rxbuff(skb, &bp->rx_cmds[i]); cp->res_count = cpu_to_le16(0); cp->xfer_status = cpu_to_le16(0); last = i; if (++i >= N_RX_RING) i = 0; } if (last != -1) { bp->rx_fill = last; bp->rx_empty = i; } dbdma_continue(rd); spin_unlock_irqrestore(&bp->lock, flags); if (rxintcount < 10) { XXDEBUG(("bmac_rxdma_intr done\n")); } return IRQ_HANDLED; } static int txintcount; static irqreturn_t bmac_txdma_intr(int irq, void *dev_id) { struct net_device *dev = (struct net_device *) dev_id; struct bmac_data *bp = netdev_priv(dev); volatile struct dbdma_cmd *cp; int stat; unsigned long flags; spin_lock_irqsave(&bp->lock, flags); if (txintcount++ < 10) { XXDEBUG(("bmac_txdma_intr\n")); } /* del_timer(&bp->tx_timeout); */ /* bp->timeout_active = 0; */ while (1) { cp = &bp->tx_cmds[bp->tx_empty]; stat = le16_to_cpu(cp->xfer_status); if (txintcount < 10) { XXDEBUG(("bmac_txdma_xfer_stat=%#0x\n", stat)); } if (!(stat & ACTIVE)) { /* * status field might not have been filled by DBDMA */ if (cp == bus_to_virt(in_le32(&bp->tx_dma->cmdptr))) break; } if (bp->tx_bufs[bp->tx_empty]) { ++dev->stats.tx_packets; dev_consume_skb_irq(bp->tx_bufs[bp->tx_empty]); } bp->tx_bufs[bp->tx_empty] = NULL; bp->tx_fullup = 0; netif_wake_queue(dev); if (++bp->tx_empty >= N_TX_RING) bp->tx_empty = 0; if (bp->tx_empty == bp->tx_fill) break; } spin_unlock_irqrestore(&bp->lock, flags); if (txintcount < 10) { XXDEBUG(("bmac_txdma_intr done->bmac_start\n")); } bmac_start(dev); return IRQ_HANDLED; } #ifndef SUNHME_MULTICAST /* Real fast bit-reversal algorithm, 6-bit values */ static int reverse6[64] = { 0x0,0x20,0x10,0x30,0x8,0x28,0x18,0x38, 0x4,0x24,0x14,0x34,0xc,0x2c,0x1c,0x3c, 0x2,0x22,0x12,0x32,0xa,0x2a,0x1a,0x3a, 0x6,0x26,0x16,0x36,0xe,0x2e,0x1e,0x3e, 0x1,0x21,0x11,0x31,0x9,0x29,0x19,0x39, 0x5,0x25,0x15,0x35,0xd,0x2d,0x1d,0x3d, 0x3,0x23,0x13,0x33,0xb,0x2b,0x1b,0x3b, 0x7,0x27,0x17,0x37,0xf,0x2f,0x1f,0x3f }; static unsigned int crc416(unsigned int curval, unsigned short nxtval) { unsigned int counter, cur = curval, next = nxtval; int high_crc_set, low_data_set; /* Swap bytes */ next = ((next & 0x00FF) << 8) | (next >> 8); /* Compute bit-by-bit */ for (counter = 0; counter < 16; ++counter) { /* is high CRC bit set? */ if ((cur & 0x80000000) == 0) high_crc_set = 0; else high_crc_set = 1; cur = cur << 1; if ((next & 0x0001) == 0) low_data_set = 0; else low_data_set = 1; next = next >> 1; /* do the XOR */ if (high_crc_set ^ low_data_set) cur = cur ^ CRC32_POLY_BE; } return cur; } static unsigned int bmac_crc(unsigned short *address) { unsigned int newcrc; XXDEBUG(("bmac_crc: addr=%#04x, %#04x, %#04x\n", *address, address[1], address[2])); newcrc = crc416(0xffffffff, *address); /* address bits 47 - 32 */ newcrc = crc416(newcrc, address[1]); /* address bits 31 - 16 */ newcrc = crc416(newcrc, address[2]); /* address bits 15 - 0 */ return(newcrc); } /* * Add requested mcast addr to BMac's hash table filter. * */ static void bmac_addhash(struct bmac_data *bp, unsigned char *addr) { unsigned int crc; unsigned short mask; if (!(*addr)) return; crc = bmac_crc((unsigned short *)addr) & 0x3f; /* Big-endian alert! */ crc = reverse6[crc]; /* Hyperfast bit-reversing algorithm */ if (bp->hash_use_count[crc]++) return; /* This bit is already set */ mask = crc % 16; mask = (unsigned char)1 << mask; bp->hash_use_count[crc/16] |= mask; } static void bmac_removehash(struct bmac_data *bp, unsigned char *addr) { unsigned int crc; unsigned char mask; /* Now, delete the address from the filter copy, as indicated */ crc = bmac_crc((unsigned short *)addr) & 0x3f; /* Big-endian alert! */ crc = reverse6[crc]; /* Hyperfast bit-reversing algorithm */ if (bp->hash_use_count[crc] == 0) return; /* That bit wasn't in use! */ if (--bp->hash_use_count[crc]) return; /* That bit is still in use */ mask = crc % 16; mask = ((unsigned char)1 << mask) ^ 0xffff; /* To turn off bit */ bp->hash_table_mask[crc/16] &= mask; } /* * Sync the adapter with the software copy of the multicast mask * (logical address filter). */ static void bmac_rx_off(struct net_device *dev) { unsigned short rx_cfg; rx_cfg = bmread(dev, RXCFG); rx_cfg &= ~RxMACEnable; bmwrite(dev, RXCFG, rx_cfg); do { rx_cfg = bmread(dev, RXCFG); } while (rx_cfg & RxMACEnable); } unsigned short bmac_rx_on(struct net_device *dev, int hash_enable, int promisc_enable) { unsigned short rx_cfg; rx_cfg = bmread(dev, RXCFG); rx_cfg |= RxMACEnable; if (hash_enable) rx_cfg |= RxHashFilterEnable; else rx_cfg &= ~RxHashFilterEnable; if (promisc_enable) rx_cfg |= RxPromiscEnable; else rx_cfg &= ~RxPromiscEnable; bmwrite(dev, RXRST, RxResetValue); bmwrite(dev, RXFIFOCSR, 0); /* first disable rxFIFO */ bmwrite(dev, RXFIFOCSR, RxFIFOEnable ); bmwrite(dev, RXCFG, rx_cfg ); return rx_cfg; } static void bmac_update_hash_table_mask(struct net_device *dev, struct bmac_data *bp) { bmwrite(dev, BHASH3, bp->hash_table_mask[0]); /* bits 15 - 0 */ bmwrite(dev, BHASH2, bp->hash_table_mask[1]); /* bits 31 - 16 */ bmwrite(dev, BHASH1, bp->hash_table_mask[2]); /* bits 47 - 32 */ bmwrite(dev, BHASH0, bp->hash_table_mask[3]); /* bits 63 - 48 */ } #if 0 static void bmac_add_multi(struct net_device *dev, struct bmac_data *bp, unsigned char *addr) { /* XXDEBUG(("bmac: enter bmac_add_multi\n")); */ bmac_addhash(bp, addr); bmac_rx_off(dev); bmac_update_hash_table_mask(dev, bp); bmac_rx_on(dev, 1, (dev->flags & IFF_PROMISC)? 1 : 0); /* XXDEBUG(("bmac: exit bmac_add_multi\n")); */ } static void bmac_remove_multi(struct net_device *dev, struct bmac_data *bp, unsigned char *addr) { bmac_removehash(bp, addr); bmac_rx_off(dev); bmac_update_hash_table_mask(dev, bp); bmac_rx_on(dev, 1, (dev->flags & IFF_PROMISC)? 1 : 0); } #endif /* Set or clear the multicast filter for this adaptor. num_addrs == -1 Promiscuous mode, receive all packets num_addrs == 0 Normal mode, clear multicast list num_addrs > 0 Multicast mode, receive normal and MC packets, and do best-effort filtering. */ static void bmac_set_multicast(struct net_device *dev) { struct netdev_hw_addr *ha; struct bmac_data *bp = netdev_priv(dev); int num_addrs = netdev_mc_count(dev); unsigned short rx_cfg; int i; if (bp->sleeping) return; XXDEBUG(("bmac: enter bmac_set_multicast, n_addrs=%d\n", num_addrs)); if((dev->flags & IFF_ALLMULTI) || (netdev_mc_count(dev) > 64)) { for (i=0; i<4; i++) bp->hash_table_mask[i] = 0xffff; bmac_update_hash_table_mask(dev, bp); rx_cfg = bmac_rx_on(dev, 1, 0); XXDEBUG(("bmac: all multi, rx_cfg=%#08x\n")); } else if ((dev->flags & IFF_PROMISC) || (num_addrs < 0)) { rx_cfg = bmread(dev, RXCFG); rx_cfg |= RxPromiscEnable; bmwrite(dev, RXCFG, rx_cfg); rx_cfg = bmac_rx_on(dev, 0, 1); XXDEBUG(("bmac: promisc mode enabled, rx_cfg=%#08x\n", rx_cfg)); } else { for (i=0; i<4; i++) bp->hash_table_mask[i] = 0; for (i=0; i<64; i++) bp->hash_use_count[i] = 0; if (num_addrs == 0) { rx_cfg = bmac_rx_on(dev, 0, 0); XXDEBUG(("bmac: multi disabled, rx_cfg=%#08x\n", rx_cfg)); } else { netdev_for_each_mc_addr(ha, dev) bmac_addhash(bp, ha->addr); bmac_update_hash_table_mask(dev, bp); rx_cfg = bmac_rx_on(dev, 1, 0); XXDEBUG(("bmac: multi enabled, rx_cfg=%#08x\n", rx_cfg)); } } /* XXDEBUG(("bmac: exit bmac_set_multicast\n")); */ } #else /* ifdef SUNHME_MULTICAST */ /* The version of set_multicast below was lifted from sunhme.c */ static void bmac_set_multicast(struct net_device *dev) { struct netdev_hw_addr *ha; unsigned short rx_cfg; u32 crc; if((dev->flags & IFF_ALLMULTI) || (netdev_mc_count(dev) > 64)) { bmwrite(dev, BHASH0, 0xffff); bmwrite(dev, BHASH1, 0xffff); bmwrite(dev, BHASH2, 0xffff); bmwrite(dev, BHASH3, 0xffff); } else if(dev->flags & IFF_PROMISC) { rx_cfg = bmread(dev, RXCFG); rx_cfg |= RxPromiscEnable; bmwrite(dev, RXCFG, rx_cfg); } else { u16 hash_table[4] = { 0 }; rx_cfg = bmread(dev, RXCFG); rx_cfg &= ~RxPromiscEnable; bmwrite(dev, RXCFG, rx_cfg); netdev_for_each_mc_addr(ha, dev) { crc = ether_crc_le(6, ha->addr); crc >>= 26; hash_table[crc >> 4] |= 1 << (crc & 0xf); } bmwrite(dev, BHASH0, hash_table[0]); bmwrite(dev, BHASH1, hash_table[1]); bmwrite(dev, BHASH2, hash_table[2]); bmwrite(dev, BHASH3, hash_table[3]); } } #endif /* SUNHME_MULTICAST */ static int miscintcount; static irqreturn_t bmac_misc_intr(int irq, void *dev_id) { struct net_device *dev = (struct net_device *) dev_id; unsigned int status = bmread(dev, STATUS); if (miscintcount++ < 10) { XXDEBUG(("bmac_misc_intr\n")); } /* XXDEBUG(("bmac_misc_intr, status=%#08x\n", status)); */ /* bmac_txdma_intr_inner(irq, dev_id); */ /* if (status & FrameReceived) dev->stats.rx_dropped++; */ if (status & RxErrorMask) dev->stats.rx_errors++; if (status & RxCRCCntExp) dev->stats.rx_crc_errors++; if (status & RxLenCntExp) dev->stats.rx_length_errors++; if (status & RxOverFlow) dev->stats.rx_over_errors++; if (status & RxAlignCntExp) dev->stats.rx_frame_errors++; /* if (status & FrameSent) dev->stats.tx_dropped++; */ if (status & TxErrorMask) dev->stats.tx_errors++; if (status & TxUnderrun) dev->stats.tx_fifo_errors++; if (status & TxNormalCollExp) dev->stats.collisions++; return IRQ_HANDLED; } /* * Procedure for reading EEPROM */ #define SROMAddressLength 5 #define DataInOn 0x0008 #define DataInOff 0x0000 #define Clk 0x0002 #define ChipSelect 0x0001 #define SDIShiftCount 3 #define SD0ShiftCount 2 #define DelayValue 1000 /* number of microseconds */ #define SROMStartOffset 10 /* this is in words */ #define SROMReadCount 3 /* number of words to read from SROM */ #define SROMAddressBits 6 #define EnetAddressOffset 20 static unsigned char bmac_clock_out_bit(struct net_device *dev) { unsigned short data; unsigned short val; bmwrite(dev, SROMCSR, ChipSelect | Clk); udelay(DelayValue); data = bmread(dev, SROMCSR); udelay(DelayValue); val = (data >> SD0ShiftCount) & 1; bmwrite(dev, SROMCSR, ChipSelect); udelay(DelayValue); return val; } static void bmac_clock_in_bit(struct net_device *dev, unsigned int val) { unsigned short data; if (val != 0 && val != 1) return; data = (val << SDIShiftCount); bmwrite(dev, SROMCSR, data | ChipSelect ); udelay(DelayValue); bmwrite(dev, SROMCSR, data | ChipSelect | Clk ); udelay(DelayValue); bmwrite(dev, SROMCSR, data | ChipSelect); udelay(DelayValue); } static void reset_and_select_srom(struct net_device *dev) { /* first reset */ bmwrite(dev, SROMCSR, 0); udelay(DelayValue); /* send it the read command (110) */ bmac_clock_in_bit(dev, 1); bmac_clock_in_bit(dev, 1); bmac_clock_in_bit(dev, 0); } static unsigned short read_srom(struct net_device *dev, unsigned int addr, unsigned int addr_len) { unsigned short data, val; int i; /* send out the address we want to read from */ for (i = 0; i < addr_len; i++) { val = addr >> (addr_len-i-1); bmac_clock_in_bit(dev, val & 1); } /* Now read in the 16-bit data */ data = 0; for (i = 0; i < 16; i++) { val = bmac_clock_out_bit(dev); data <<= 1; data |= val; } bmwrite(dev, SROMCSR, 0); return data; } /* * It looks like Cogent and SMC use different methods for calculating * checksums. What a pain.. */ static int bmac_verify_checksum(struct net_device *dev) { unsigned short data, storedCS; reset_and_select_srom(dev); data = read_srom(dev, 3, SROMAddressBits); storedCS = ((data >> 8) & 0x0ff) | ((data << 8) & 0xff00); return 0; } static void bmac_get_station_address(struct net_device *dev, unsigned char *ea) { int i; unsigned short data; for (i = 0; i < 3; i++) { reset_and_select_srom(dev); data = read_srom(dev, i + EnetAddressOffset/2, SROMAddressBits); ea[2*i] = bitrev8(data & 0x0ff); ea[2*i+1] = bitrev8((data >> 8) & 0x0ff); } } static void bmac_reset_and_enable(struct net_device *dev) { struct bmac_data *bp = netdev_priv(dev); unsigned long flags; struct sk_buff *skb; unsigned char *data; spin_lock_irqsave(&bp->lock, flags); bmac_enable_and_reset_chip(dev); bmac_init_tx_ring(bp); bmac_init_rx_ring(dev); bmac_init_chip(dev); bmac_start_chip(dev); bmwrite(dev, INTDISABLE, EnableNormal); bp->sleeping = 0; /* * It seems that the bmac can't receive until it's transmitted * a packet. So we give it a dummy packet to transmit. */ skb = netdev_alloc_skb(dev, ETHERMINPACKET); if (skb != NULL) { data = skb_put_zero(skb, ETHERMINPACKET); memcpy(data, dev->dev_addr, ETH_ALEN); memcpy(data + ETH_ALEN, dev->dev_addr, ETH_ALEN); bmac_transmit_packet(skb, dev); } spin_unlock_irqrestore(&bp->lock, flags); } static const struct ethtool_ops bmac_ethtool_ops = { .get_link = ethtool_op_get_link, }; static const struct net_device_ops bmac_netdev_ops = { .ndo_open = bmac_open, .ndo_stop = bmac_close, .ndo_start_xmit = bmac_output, .ndo_set_rx_mode = bmac_set_multicast, .ndo_set_mac_address = bmac_set_address, .ndo_validate_addr = eth_validate_addr, }; static int bmac_probe(struct macio_dev *mdev, const struct of_device_id *match) { int j, rev, ret; struct bmac_data *bp; const unsigned char *prop_addr; unsigned char addr[6]; u8 macaddr[6]; struct net_device *dev; int is_bmac_plus = ((int)match->data) != 0; if (macio_resource_count(mdev) != 3 || macio_irq_count(mdev) != 3) { printk(KERN_ERR "BMAC: can't use, need 3 addrs and 3 intrs\n"); return -ENODEV; } prop_addr = of_get_property(macio_get_of_node(mdev), "mac-address", NULL); if (prop_addr == NULL) { prop_addr = of_get_property(macio_get_of_node(mdev), "local-mac-address", NULL); if (prop_addr == NULL) { printk(KERN_ERR "BMAC: Can't get mac-address\n"); return -ENODEV; } } memcpy(addr, prop_addr, sizeof(addr)); dev = alloc_etherdev(PRIV_BYTES); if (!dev) return -ENOMEM; bp = netdev_priv(dev); SET_NETDEV_DEV(dev, &mdev->ofdev.dev); macio_set_drvdata(mdev, dev); bp->mdev = mdev; spin_lock_init(&bp->lock); if (macio_request_resources(mdev, "bmac")) { printk(KERN_ERR "BMAC: can't request IO resource !\n"); goto out_free; } dev->base_addr = (unsigned long) ioremap(macio_resource_start(mdev, 0), macio_resource_len(mdev, 0)); if (dev->base_addr == 0) goto out_release; dev->irq = macio_irq(mdev, 0); bmac_enable_and_reset_chip(dev); bmwrite(dev, INTDISABLE, DisableAll); rev = addr[0] == 0 && addr[1] == 0xA0; for (j = 0; j < 6; ++j) macaddr[j] = rev ? bitrev8(addr[j]): addr[j]; eth_hw_addr_set(dev, macaddr); /* Enable chip without interrupts for now */ bmac_enable_and_reset_chip(dev); bmwrite(dev, INTDISABLE, DisableAll); dev->netdev_ops = &bmac_netdev_ops; dev->ethtool_ops = &bmac_ethtool_ops; bmac_get_station_address(dev, addr); if (bmac_verify_checksum(dev) != 0) goto err_out_iounmap; bp->is_bmac_plus = is_bmac_plus; bp->tx_dma = ioremap(macio_resource_start(mdev, 1), macio_resource_len(mdev, 1)); if (!bp->tx_dma) goto err_out_iounmap; bp->tx_dma_intr = macio_irq(mdev, 1); bp->rx_dma = ioremap(macio_resource_start(mdev, 2), macio_resource_len(mdev, 2)); if (!bp->rx_dma) goto err_out_iounmap_tx; bp->rx_dma_intr = macio_irq(mdev, 2); bp->tx_cmds = (volatile struct dbdma_cmd *) DBDMA_ALIGN(bp + 1); bp->rx_cmds = bp->tx_cmds + N_TX_RING + 1; bp->queue = (struct sk_buff_head *)(bp->rx_cmds + N_RX_RING + 1); skb_queue_head_init(bp->queue); timer_setup(&bp->tx_timeout, bmac_tx_timeout, 0); ret = request_irq(dev->irq, bmac_misc_intr, 0, "BMAC-misc", dev); if (ret) { printk(KERN_ERR "BMAC: can't get irq %d\n", dev->irq); goto err_out_iounmap_rx; } ret = request_irq(bp->tx_dma_intr, bmac_txdma_intr, 0, "BMAC-txdma", dev); if (ret) { printk(KERN_ERR "BMAC: can't get irq %d\n", bp->tx_dma_intr); goto err_out_irq0; } ret = request_irq(bp->rx_dma_intr, bmac_rxdma_intr, 0, "BMAC-rxdma", dev); if (ret) { printk(KERN_ERR "BMAC: can't get irq %d\n", bp->rx_dma_intr); goto err_out_irq1; } /* Mask chip interrupts and disable chip, will be * re-enabled on open() */ disable_irq(dev->irq); pmac_call_feature(PMAC_FTR_BMAC_ENABLE, macio_get_of_node(bp->mdev), 0, 0); if (register_netdev(dev) != 0) { printk(KERN_ERR "BMAC: Ethernet registration failed\n"); goto err_out_irq2; } printk(KERN_INFO "%s: BMAC%s at %pM", dev->name, (is_bmac_plus ? "+" : ""), dev->dev_addr); XXDEBUG((", base_addr=%#0lx", dev->base_addr)); printk("\n"); return 0; err_out_irq2: free_irq(bp->rx_dma_intr, dev); err_out_irq1: free_irq(bp->tx_dma_intr, dev); err_out_irq0: free_irq(dev->irq, dev); err_out_iounmap_rx: iounmap(bp->rx_dma); err_out_iounmap_tx: iounmap(bp->tx_dma); err_out_iounmap: iounmap((void __iomem *)dev->base_addr); out_release: macio_release_resources(mdev); out_free: pmac_call_feature(PMAC_FTR_BMAC_ENABLE, macio_get_of_node(bp->mdev), 0, 0); free_netdev(dev); return -ENODEV; } static int bmac_open(struct net_device *dev) { struct bmac_data *bp = netdev_priv(dev); /* XXDEBUG(("bmac: enter open\n")); */ /* reset the chip */ bp->opened = 1; bmac_reset_and_enable(dev); enable_irq(dev->irq); return 0; } static int bmac_close(struct net_device *dev) { struct bmac_data *bp = netdev_priv(dev); volatile struct dbdma_regs __iomem *rd = bp->rx_dma; volatile struct dbdma_regs __iomem *td = bp->tx_dma; unsigned short config; int i; bp->sleeping = 1; /* disable rx and tx */ config = bmread(dev, RXCFG); bmwrite(dev, RXCFG, (config & ~RxMACEnable)); config = bmread(dev, TXCFG); bmwrite(dev, TXCFG, (config & ~TxMACEnable)); bmwrite(dev, INTDISABLE, DisableAll); /* disable all intrs */ /* disable rx and tx dma */ rd->control = cpu_to_le32(DBDMA_CLEAR(RUN|PAUSE|FLUSH|WAKE)); /* clear run bit */ td->control = cpu_to_le32(DBDMA_CLEAR(RUN|PAUSE|FLUSH|WAKE)); /* clear run bit */ /* free some skb's */ XXDEBUG(("bmac: free rx bufs\n")); for (i=0; i<N_RX_RING; i++) { if (bp->rx_bufs[i] != NULL) { dev_kfree_skb(bp->rx_bufs[i]); bp->rx_bufs[i] = NULL; } } XXDEBUG(("bmac: free tx bufs\n")); for (i = 0; i<N_TX_RING; i++) { if (bp->tx_bufs[i] != NULL) { dev_kfree_skb(bp->tx_bufs[i]); bp->tx_bufs[i] = NULL; } } XXDEBUG(("bmac: all bufs freed\n")); bp->opened = 0; disable_irq(dev->irq); pmac_call_feature(PMAC_FTR_BMAC_ENABLE, macio_get_of_node(bp->mdev), 0, 0); return 0; } static void bmac_start(struct net_device *dev) { struct bmac_data *bp = netdev_priv(dev); int i; struct sk_buff *skb; unsigned long flags; if (bp->sleeping) return; spin_lock_irqsave(&bp->lock, flags); while (1) { i = bp->tx_fill + 1; if (i >= N_TX_RING) i = 0; if (i == bp->tx_empty) break; skb = skb_dequeue(bp->queue); if (skb == NULL) break; bmac_transmit_packet(skb, dev); } spin_unlock_irqrestore(&bp->lock, flags); } static netdev_tx_t bmac_output(struct sk_buff *skb, struct net_device *dev) { struct bmac_data *bp = netdev_priv(dev); skb_queue_tail(bp->queue, skb); bmac_start(dev); return NETDEV_TX_OK; } static void bmac_tx_timeout(struct timer_list *t) { struct bmac_data *bp = from_timer(bp, t, tx_timeout); struct net_device *dev = macio_get_drvdata(bp->mdev); volatile struct dbdma_regs __iomem *td = bp->tx_dma; volatile struct dbdma_regs __iomem *rd = bp->rx_dma; volatile struct dbdma_cmd *cp; unsigned long flags; unsigned short config, oldConfig; int i; XXDEBUG(("bmac: tx_timeout called\n")); spin_lock_irqsave(&bp->lock, flags); bp->timeout_active = 0; /* update various counters */ /* bmac_handle_misc_intrs(bp, 0); */ cp = &bp->tx_cmds[bp->tx_empty]; /* XXDEBUG((KERN_DEBUG "bmac: tx dmastat=%x %x runt=%d pr=%x fs=%x fc=%x\n", */ /* le32_to_cpu(td->status), le16_to_cpu(cp->xfer_status), bp->tx_bad_runt, */ /* mb->pr, mb->xmtfs, mb->fifofc)); */ /* turn off both tx and rx and reset the chip */ config = bmread(dev, RXCFG); bmwrite(dev, RXCFG, (config & ~RxMACEnable)); config = bmread(dev, TXCFG); bmwrite(dev, TXCFG, (config & ~TxMACEnable)); out_le32(&td->control, DBDMA_CLEAR(RUN|PAUSE|FLUSH|WAKE|ACTIVE|DEAD)); printk(KERN_ERR "bmac: transmit timeout - resetting\n"); bmac_enable_and_reset_chip(dev); /* restart rx dma */ cp = bus_to_virt(le32_to_cpu(rd->cmdptr)); out_le32(&rd->control, DBDMA_CLEAR(RUN|PAUSE|FLUSH|WAKE|ACTIVE|DEAD)); out_le16(&cp->xfer_status, 0); out_le32(&rd->cmdptr, virt_to_bus(cp)); out_le32(&rd->control, DBDMA_SET(RUN|WAKE)); /* fix up the transmit side */ XXDEBUG((KERN_DEBUG "bmac: tx empty=%d fill=%d fullup=%d\n", bp->tx_empty, bp->tx_fill, bp->tx_fullup)); i = bp->tx_empty; ++dev->stats.tx_errors; if (i != bp->tx_fill) { dev_kfree_skb_irq(bp->tx_bufs[i]); bp->tx_bufs[i] = NULL; if (++i >= N_TX_RING) i = 0; bp->tx_empty = i; } bp->tx_fullup = 0; netif_wake_queue(dev); if (i != bp->tx_fill) { cp = &bp->tx_cmds[i]; out_le16(&cp->xfer_status, 0); out_le16(&cp->command, OUTPUT_LAST); out_le32(&td->cmdptr, virt_to_bus(cp)); out_le32(&td->control, DBDMA_SET(RUN)); /* bmac_set_timeout(dev); */ XXDEBUG((KERN_DEBUG "bmac: starting %d\n", i)); } /* turn it back on */ oldConfig = bmread(dev, RXCFG); bmwrite(dev, RXCFG, oldConfig | RxMACEnable ); oldConfig = bmread(dev, TXCFG); bmwrite(dev, TXCFG, oldConfig | TxMACEnable ); spin_unlock_irqrestore(&bp->lock, flags); } #if 0 static void dump_dbdma(volatile struct dbdma_cmd *cp,int count) { int i,*ip; for (i=0;i< count;i++) { ip = (int*)(cp+i); printk("dbdma req 0x%x addr 0x%x baddr 0x%x xfer/res 0x%x\n", le32_to_cpup(ip+0), le32_to_cpup(ip+1), le32_to_cpup(ip+2), le32_to_cpup(ip+3)); } } #endif #if 0 static int bmac_proc_info(char *buffer, char **start, off_t offset, int length) { int len = 0; off_t pos = 0; off_t begin = 0; int i; if (bmac_devs == NULL) return -ENOSYS; len += sprintf(buffer, "BMAC counters & registers\n"); for (i = 0; i<N_REG_ENTRIES; i++) { len += sprintf(buffer + len, "%s: %#08x\n", reg_entries[i].name, bmread(bmac_devs, reg_entries[i].reg_offset)); pos = begin + len; if (pos < offset) { len = 0; begin = pos; } if (pos > offset+length) break; } *start = buffer + (offset - begin); len -= (offset - begin); if (len > length) len = length; return len; } #endif static int bmac_remove(struct macio_dev *mdev) { struct net_device *dev = macio_get_drvdata(mdev); struct bmac_data *bp = netdev_priv(dev); unregister_netdev(dev); free_irq(dev->irq, dev); free_irq(bp->tx_dma_intr, dev); free_irq(bp->rx_dma_intr, dev); iounmap((void __iomem *)dev->base_addr); iounmap(bp->tx_dma); iounmap(bp->rx_dma); macio_release_resources(mdev); free_netdev(dev); return 0; } static const struct of_device_id bmac_match[] = { { .name = "bmac", .data = (void *)0, }, { .type = "network", .compatible = "bmac+", .data = (void *)1, }, {}, }; MODULE_DEVICE_TABLE (of, bmac_match); static struct macio_driver bmac_driver = { .driver = { .name = "bmac", .owner = THIS_MODULE, .of_match_table = bmac_match, }, .probe = bmac_probe, .remove = bmac_remove, #ifdef CONFIG_PM .suspend = bmac_suspend, .resume = bmac_resume, #endif }; static int __init bmac_init(void) { if (bmac_emergency_rxbuf == NULL) { bmac_emergency_rxbuf = kmalloc(RX_BUFLEN, GFP_KERNEL); if (bmac_emergency_rxbuf == NULL) return -ENOMEM; } return macio_register_driver(&bmac_driver); } static void __exit bmac_exit(void) { macio_unregister_driver(&bmac_driver); kfree(bmac_emergency_rxbuf); bmac_emergency_rxbuf = NULL; } MODULE_AUTHOR("Randy Gobbel/Paul Mackerras"); MODULE_DESCRIPTION("PowerMac BMAC ethernet driver."); MODULE_LICENSE("GPL"); module_init(bmac_init); module_exit(bmac_exit);
linux-master
drivers/net/ethernet/apple/bmac.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Driver for the Macintosh 68K onboard MACE controller with PSC * driven DMA. The MACE driver code is derived from mace.c. The * Mac68k theory of operation is courtesy of the MacBSD wizards. * * Copyright (C) 1996 Paul Mackerras. * Copyright (C) 1998 Alan Cox <[email protected]> * * Modified heavily by Joshua M. Thompson based on Dave Huang's NetBSD driver * * Copyright (C) 2007 Finn Thain * * Converted to DMA API, converted to unified driver model, * sync'd some routines with mace.c and fixed various bugs. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/delay.h> #include <linux/string.h> #include <linux/crc32.h> #include <linux/bitrev.h> #include <linux/dma-mapping.h> #include <linux/platform_device.h> #include <linux/gfp.h> #include <linux/interrupt.h> #include <asm/io.h> #include <asm/macints.h> #include <asm/mac_psc.h> #include <asm/page.h> #include "mace.h" static char mac_mace_string[] = "macmace"; #define N_TX_BUFF_ORDER 0 #define N_TX_RING (1 << N_TX_BUFF_ORDER) #define N_RX_BUFF_ORDER 3 #define N_RX_RING (1 << N_RX_BUFF_ORDER) #define TX_TIMEOUT HZ #define MACE_BUFF_SIZE 0x800 /* Chip rev needs workaround on HW & multicast addr change */ #define BROKEN_ADDRCHG_REV 0x0941 /* The MACE is simply wired down on a Mac68K box */ #define MACE_BASE (void *)(0x50F1C000) #define MACE_PROM (void *)(0x50F08001) struct mace_data { volatile struct mace *mace; unsigned char *tx_ring; dma_addr_t tx_ring_phys; unsigned char *rx_ring; dma_addr_t rx_ring_phys; int dma_intr; int rx_slot, rx_tail; int tx_slot, tx_sloti, tx_count; int chipid; struct device *device; }; struct mace_frame { u8 rcvcnt; u8 pad1; u8 rcvsts; u8 pad2; u8 rntpc; u8 pad3; u8 rcvcc; u8 pad4; u32 pad5; u32 pad6; DECLARE_FLEX_ARRAY(u8, data); /* And frame continues.. */ }; #define PRIV_BYTES sizeof(struct mace_data) static int mace_open(struct net_device *dev); static int mace_close(struct net_device *dev); static netdev_tx_t mace_xmit_start(struct sk_buff *skb, struct net_device *dev); static void mace_set_multicast(struct net_device *dev); static int mace_set_address(struct net_device *dev, void *addr); static void mace_reset(struct net_device *dev); static irqreturn_t mace_interrupt(int irq, void *dev_id); static irqreturn_t mace_dma_intr(int irq, void *dev_id); static void mace_tx_timeout(struct net_device *dev, unsigned int txqueue); static void __mace_set_address(struct net_device *dev, const void *addr); /* * Load a receive DMA channel with a base address and ring length */ static void mace_load_rxdma_base(struct net_device *dev, int set) { struct mace_data *mp = netdev_priv(dev); psc_write_word(PSC_ENETRD_CMD + set, 0x0100); psc_write_long(PSC_ENETRD_ADDR + set, (u32) mp->rx_ring_phys); psc_write_long(PSC_ENETRD_LEN + set, N_RX_RING); psc_write_word(PSC_ENETRD_CMD + set, 0x9800); mp->rx_tail = 0; } /* * Reset the receive DMA subsystem */ static void mace_rxdma_reset(struct net_device *dev) { struct mace_data *mp = netdev_priv(dev); volatile struct mace *mace = mp->mace; u8 maccc = mace->maccc; mace->maccc = maccc & ~ENRCV; psc_write_word(PSC_ENETRD_CTL, 0x8800); mace_load_rxdma_base(dev, 0x00); psc_write_word(PSC_ENETRD_CTL, 0x0400); psc_write_word(PSC_ENETRD_CTL, 0x8800); mace_load_rxdma_base(dev, 0x10); psc_write_word(PSC_ENETRD_CTL, 0x0400); mace->maccc = maccc; mp->rx_slot = 0; psc_write_word(PSC_ENETRD_CMD + PSC_SET0, 0x9800); psc_write_word(PSC_ENETRD_CMD + PSC_SET1, 0x9800); } /* * Reset the transmit DMA subsystem */ static void mace_txdma_reset(struct net_device *dev) { struct mace_data *mp = netdev_priv(dev); volatile struct mace *mace = mp->mace; u8 maccc; psc_write_word(PSC_ENETWR_CTL, 0x8800); maccc = mace->maccc; mace->maccc = maccc & ~ENXMT; mp->tx_slot = mp->tx_sloti = 0; mp->tx_count = N_TX_RING; psc_write_word(PSC_ENETWR_CTL, 0x0400); mace->maccc = maccc; } /* * Disable DMA */ static void mace_dma_off(struct net_device *dev) { psc_write_word(PSC_ENETRD_CTL, 0x8800); psc_write_word(PSC_ENETRD_CTL, 0x1000); psc_write_word(PSC_ENETRD_CMD + PSC_SET0, 0x1100); psc_write_word(PSC_ENETRD_CMD + PSC_SET1, 0x1100); psc_write_word(PSC_ENETWR_CTL, 0x8800); psc_write_word(PSC_ENETWR_CTL, 0x1000); psc_write_word(PSC_ENETWR_CMD + PSC_SET0, 0x1100); psc_write_word(PSC_ENETWR_CMD + PSC_SET1, 0x1100); } static const struct net_device_ops mace_netdev_ops = { .ndo_open = mace_open, .ndo_stop = mace_close, .ndo_start_xmit = mace_xmit_start, .ndo_tx_timeout = mace_tx_timeout, .ndo_set_rx_mode = mace_set_multicast, .ndo_set_mac_address = mace_set_address, .ndo_validate_addr = eth_validate_addr, }; /* * Not really much of a probe. The hardware table tells us if this * model of Macintrash has a MACE (AV macintoshes) */ static int mace_probe(struct platform_device *pdev) { int j; struct mace_data *mp; unsigned char *addr; struct net_device *dev; unsigned char checksum = 0; u8 macaddr[ETH_ALEN]; int err; dev = alloc_etherdev(PRIV_BYTES); if (!dev) return -ENOMEM; mp = netdev_priv(dev); mp->device = &pdev->dev; platform_set_drvdata(pdev, dev); SET_NETDEV_DEV(dev, &pdev->dev); dev->base_addr = (u32)MACE_BASE; mp->mace = MACE_BASE; dev->irq = IRQ_MAC_MACE; mp->dma_intr = IRQ_MAC_MACE_DMA; mp->chipid = mp->mace->chipid_hi << 8 | mp->mace->chipid_lo; /* * The PROM contains 8 bytes which total 0xFF when XOR'd * together. Due to the usual peculiar apple brain damage * the bytes are spaced out in a strange boundary and the * bits are reversed. */ addr = MACE_PROM; for (j = 0; j < 6; ++j) { u8 v = bitrev8(addr[j<<4]); checksum ^= v; macaddr[j] = v; } eth_hw_addr_set(dev, macaddr); for (; j < 8; ++j) { checksum ^= bitrev8(addr[j<<4]); } if (checksum != 0xFF) { free_netdev(dev); return -ENODEV; } dev->netdev_ops = &mace_netdev_ops; dev->watchdog_timeo = TX_TIMEOUT; pr_info("Onboard MACE, hardware address %pM, chip revision 0x%04X\n", dev->dev_addr, mp->chipid); err = register_netdev(dev); if (!err) return 0; free_netdev(dev); return err; } /* * Reset the chip. */ static void mace_reset(struct net_device *dev) { struct mace_data *mp = netdev_priv(dev); volatile struct mace *mb = mp->mace; int i; /* soft-reset the chip */ i = 200; while (--i) { mb->biucc = SWRST; if (mb->biucc & SWRST) { udelay(10); continue; } break; } if (!i) { printk(KERN_ERR "macmace: cannot reset chip!\n"); return; } mb->maccc = 0; /* turn off tx, rx */ mb->imr = 0xFF; /* disable all intrs for now */ i = mb->ir; mb->biucc = XMTSP_64; mb->utr = RTRD; mb->fifocc = XMTFW_8 | RCVFW_64 | XMTFWU | RCVFWU; mb->xmtfc = AUTO_PAD_XMIT; /* auto-pad short frames */ mb->rcvfc = 0; /* load up the hardware address */ __mace_set_address(dev, dev->dev_addr); /* clear the multicast filter */ if (mp->chipid == BROKEN_ADDRCHG_REV) mb->iac = LOGADDR; else { mb->iac = ADDRCHG | LOGADDR; while ((mb->iac & ADDRCHG) != 0) ; } for (i = 0; i < 8; ++i) mb->ladrf = 0; /* done changing address */ if (mp->chipid != BROKEN_ADDRCHG_REV) mb->iac = 0; mb->plscc = PORTSEL_AUI; } /* * Load the address on a mace controller. */ static void __mace_set_address(struct net_device *dev, const void *addr) { struct mace_data *mp = netdev_priv(dev); volatile struct mace *mb = mp->mace; const unsigned char *p = addr; u8 macaddr[ETH_ALEN]; int i; /* load up the hardware address */ if (mp->chipid == BROKEN_ADDRCHG_REV) mb->iac = PHYADDR; else { mb->iac = ADDRCHG | PHYADDR; while ((mb->iac & ADDRCHG) != 0) ; } for (i = 0; i < 6; ++i) mb->padr = macaddr[i] = p[i]; eth_hw_addr_set(dev, macaddr); if (mp->chipid != BROKEN_ADDRCHG_REV) mb->iac = 0; } static int mace_set_address(struct net_device *dev, void *addr) { struct mace_data *mp = netdev_priv(dev); volatile struct mace *mb = mp->mace; unsigned long flags; u8 maccc; local_irq_save(flags); maccc = mb->maccc; __mace_set_address(dev, addr); mb->maccc = maccc; local_irq_restore(flags); return 0; } /* * Open the Macintosh MACE. Most of this is playing with the DMA * engine. The ethernet chip is quite friendly. */ static int mace_open(struct net_device *dev) { struct mace_data *mp = netdev_priv(dev); volatile struct mace *mb = mp->mace; /* reset the chip */ mace_reset(dev); if (request_irq(dev->irq, mace_interrupt, 0, dev->name, dev)) { printk(KERN_ERR "%s: can't get irq %d\n", dev->name, dev->irq); return -EAGAIN; } if (request_irq(mp->dma_intr, mace_dma_intr, 0, dev->name, dev)) { printk(KERN_ERR "%s: can't get irq %d\n", dev->name, mp->dma_intr); free_irq(dev->irq, dev); return -EAGAIN; } /* Allocate the DMA ring buffers */ mp->tx_ring = dma_alloc_coherent(mp->device, N_TX_RING * MACE_BUFF_SIZE, &mp->tx_ring_phys, GFP_KERNEL); if (mp->tx_ring == NULL) goto out1; mp->rx_ring = dma_alloc_coherent(mp->device, N_RX_RING * MACE_BUFF_SIZE, &mp->rx_ring_phys, GFP_KERNEL); if (mp->rx_ring == NULL) goto out2; mace_dma_off(dev); /* Not sure what these do */ psc_write_word(PSC_ENETWR_CTL, 0x9000); psc_write_word(PSC_ENETRD_CTL, 0x9000); psc_write_word(PSC_ENETWR_CTL, 0x0400); psc_write_word(PSC_ENETRD_CTL, 0x0400); mace_rxdma_reset(dev); mace_txdma_reset(dev); /* turn it on! */ mb->maccc = ENXMT | ENRCV; /* enable all interrupts except receive interrupts */ mb->imr = RCVINT; return 0; out2: dma_free_coherent(mp->device, N_TX_RING * MACE_BUFF_SIZE, mp->tx_ring, mp->tx_ring_phys); out1: free_irq(dev->irq, dev); free_irq(mp->dma_intr, dev); return -ENOMEM; } /* * Shut down the mace and its interrupt channel */ static int mace_close(struct net_device *dev) { struct mace_data *mp = netdev_priv(dev); volatile struct mace *mb = mp->mace; mb->maccc = 0; /* disable rx and tx */ mb->imr = 0xFF; /* disable all irqs */ mace_dma_off(dev); /* disable rx and tx dma */ return 0; } /* * Transmit a frame */ static netdev_tx_t mace_xmit_start(struct sk_buff *skb, struct net_device *dev) { struct mace_data *mp = netdev_priv(dev); unsigned long flags; /* Stop the queue since there's only the one buffer */ local_irq_save(flags); netif_stop_queue(dev); if (!mp->tx_count) { printk(KERN_ERR "macmace: tx queue running but no free buffers.\n"); local_irq_restore(flags); return NETDEV_TX_BUSY; } mp->tx_count--; local_irq_restore(flags); dev->stats.tx_packets++; dev->stats.tx_bytes += skb->len; /* We need to copy into our xmit buffer to take care of alignment and caching issues */ skb_copy_from_linear_data(skb, mp->tx_ring, skb->len); /* load the Tx DMA and fire it off */ psc_write_long(PSC_ENETWR_ADDR + mp->tx_slot, (u32) mp->tx_ring_phys); psc_write_long(PSC_ENETWR_LEN + mp->tx_slot, skb->len); psc_write_word(PSC_ENETWR_CMD + mp->tx_slot, 0x9800); mp->tx_slot ^= 0x10; dev_kfree_skb(skb); return NETDEV_TX_OK; } static void mace_set_multicast(struct net_device *dev) { struct mace_data *mp = netdev_priv(dev); volatile struct mace *mb = mp->mace; int i; u32 crc; u8 maccc; unsigned long flags; local_irq_save(flags); maccc = mb->maccc; mb->maccc &= ~PROM; if (dev->flags & IFF_PROMISC) { mb->maccc |= PROM; } else { unsigned char multicast_filter[8]; struct netdev_hw_addr *ha; if (dev->flags & IFF_ALLMULTI) { for (i = 0; i < 8; i++) { multicast_filter[i] = 0xFF; } } else { for (i = 0; i < 8; i++) multicast_filter[i] = 0; netdev_for_each_mc_addr(ha, dev) { crc = ether_crc_le(6, ha->addr); /* bit number in multicast_filter */ i = crc >> 26; multicast_filter[i >> 3] |= 1 << (i & 7); } } if (mp->chipid == BROKEN_ADDRCHG_REV) mb->iac = LOGADDR; else { mb->iac = ADDRCHG | LOGADDR; while ((mb->iac & ADDRCHG) != 0) ; } for (i = 0; i < 8; ++i) mb->ladrf = multicast_filter[i]; if (mp->chipid != BROKEN_ADDRCHG_REV) mb->iac = 0; } mb->maccc = maccc; local_irq_restore(flags); } static void mace_handle_misc_intrs(struct net_device *dev, int intr) { struct mace_data *mp = netdev_priv(dev); volatile struct mace *mb = mp->mace; static int mace_babbles, mace_jabbers; if (intr & MPCO) dev->stats.rx_missed_errors += 256; dev->stats.rx_missed_errors += mb->mpc; /* reading clears it */ if (intr & RNTPCO) dev->stats.rx_length_errors += 256; dev->stats.rx_length_errors += mb->rntpc; /* reading clears it */ if (intr & CERR) ++dev->stats.tx_heartbeat_errors; if (intr & BABBLE) if (mace_babbles++ < 4) printk(KERN_DEBUG "macmace: babbling transmitter\n"); if (intr & JABBER) if (mace_jabbers++ < 4) printk(KERN_DEBUG "macmace: jabbering transceiver\n"); } static irqreturn_t mace_interrupt(int irq, void *dev_id) { struct net_device *dev = (struct net_device *) dev_id; struct mace_data *mp = netdev_priv(dev); volatile struct mace *mb = mp->mace; int intr, fs; unsigned long flags; /* don't want the dma interrupt handler to fire */ local_irq_save(flags); intr = mb->ir; /* read interrupt register */ mace_handle_misc_intrs(dev, intr); if (intr & XMTINT) { fs = mb->xmtfs; if ((fs & XMTSV) == 0) { printk(KERN_ERR "macmace: xmtfs not valid! (fs=%x)\n", fs); mace_reset(dev); /* * XXX mace likes to hang the machine after a xmtfs error. * This is hard to reproduce, resetting *may* help */ } /* dma should have finished */ if (!mp->tx_count) { printk(KERN_DEBUG "macmace: tx ring ran out? (fs=%x)\n", fs); } /* Update stats */ if (fs & (UFLO|LCOL|LCAR|RTRY)) { ++dev->stats.tx_errors; if (fs & LCAR) ++dev->stats.tx_carrier_errors; else if (fs & (UFLO|LCOL|RTRY)) { ++dev->stats.tx_aborted_errors; if (mb->xmtfs & UFLO) { dev->stats.tx_fifo_errors++; mace_txdma_reset(dev); } } } } if (mp->tx_count) netif_wake_queue(dev); local_irq_restore(flags); return IRQ_HANDLED; } static void mace_tx_timeout(struct net_device *dev, unsigned int txqueue) { struct mace_data *mp = netdev_priv(dev); volatile struct mace *mb = mp->mace; unsigned long flags; local_irq_save(flags); /* turn off both tx and rx and reset the chip */ mb->maccc = 0; printk(KERN_ERR "macmace: transmit timeout - resetting\n"); mace_txdma_reset(dev); mace_reset(dev); /* restart rx dma */ mace_rxdma_reset(dev); mp->tx_count = N_TX_RING; netif_wake_queue(dev); /* turn it on! */ mb->maccc = ENXMT | ENRCV; /* enable all interrupts except receive interrupts */ mb->imr = RCVINT; local_irq_restore(flags); } /* * Handle a newly arrived frame */ static void mace_dma_rx_frame(struct net_device *dev, struct mace_frame *mf) { struct sk_buff *skb; unsigned int frame_status = mf->rcvsts; if (frame_status & (RS_OFLO | RS_CLSN | RS_FRAMERR | RS_FCSERR)) { dev->stats.rx_errors++; if (frame_status & RS_OFLO) dev->stats.rx_fifo_errors++; if (frame_status & RS_CLSN) dev->stats.collisions++; if (frame_status & RS_FRAMERR) dev->stats.rx_frame_errors++; if (frame_status & RS_FCSERR) dev->stats.rx_crc_errors++; } else { unsigned int frame_length = mf->rcvcnt + ((frame_status & 0x0F) << 8 ); skb = netdev_alloc_skb(dev, frame_length + 2); if (!skb) { dev->stats.rx_dropped++; return; } skb_reserve(skb, 2); skb_put_data(skb, mf->data, frame_length); skb->protocol = eth_type_trans(skb, dev); netif_rx(skb); dev->stats.rx_packets++; dev->stats.rx_bytes += frame_length; } } /* * The PSC has passed us a DMA interrupt event. */ static irqreturn_t mace_dma_intr(int irq, void *dev_id) { struct net_device *dev = (struct net_device *) dev_id; struct mace_data *mp = netdev_priv(dev); int left, head; u16 status; u32 baka; /* Not sure what this does */ while ((baka = psc_read_long(PSC_MYSTERY)) != psc_read_long(PSC_MYSTERY)); if (!(baka & 0x60000000)) return IRQ_NONE; /* * Process the read queue */ status = psc_read_word(PSC_ENETRD_CTL); if (status & 0x2000) { mace_rxdma_reset(dev); } else if (status & 0x0100) { psc_write_word(PSC_ENETRD_CMD + mp->rx_slot, 0x1100); left = psc_read_long(PSC_ENETRD_LEN + mp->rx_slot); head = N_RX_RING - left; /* Loop through the ring buffer and process new packages */ while (mp->rx_tail < head) { mace_dma_rx_frame(dev, (struct mace_frame*) (mp->rx_ring + (mp->rx_tail * MACE_BUFF_SIZE))); mp->rx_tail++; } /* If we're out of buffers in this ring then switch to */ /* the other set, otherwise just reactivate this one. */ if (!left) { mace_load_rxdma_base(dev, mp->rx_slot); mp->rx_slot ^= 0x10; } else { psc_write_word(PSC_ENETRD_CMD + mp->rx_slot, 0x9800); } } /* * Process the write queue */ status = psc_read_word(PSC_ENETWR_CTL); if (status & 0x2000) { mace_txdma_reset(dev); } else if (status & 0x0100) { psc_write_word(PSC_ENETWR_CMD + mp->tx_sloti, 0x0100); mp->tx_sloti ^= 0x10; mp->tx_count++; } return IRQ_HANDLED; } MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Macintosh MACE ethernet driver"); MODULE_ALIAS("platform:macmace"); static int mac_mace_device_remove(struct platform_device *pdev) { struct net_device *dev = platform_get_drvdata(pdev); struct mace_data *mp = netdev_priv(dev); unregister_netdev(dev); free_irq(dev->irq, dev); free_irq(IRQ_MAC_MACE_DMA, dev); dma_free_coherent(mp->device, N_RX_RING * MACE_BUFF_SIZE, mp->rx_ring, mp->rx_ring_phys); dma_free_coherent(mp->device, N_TX_RING * MACE_BUFF_SIZE, mp->tx_ring, mp->tx_ring_phys); free_netdev(dev); return 0; } static struct platform_driver mac_mace_driver = { .probe = mace_probe, .remove = mac_mace_device_remove, .driver = { .name = mac_mace_string, }, }; module_platform_driver(mac_mace_driver);
linux-master
drivers/net/ethernet/apple/macmace.c
// SPDX-License-Identifier: GPL-2.0-only /* r8169_firmware.c: RealTek 8169/8168/8101 ethernet driver. * * Copyright (c) 2002 ShuChen <[email protected]> * Copyright (c) 2003 - 2007 Francois Romieu <[email protected]> * Copyright (c) a lot of people too. Please respect their work. * * See MAINTAINERS file for support contact information. */ #include <linux/delay.h> #include <linux/firmware.h> #include "r8169_firmware.h" enum rtl_fw_opcode { PHY_READ = 0x0, PHY_DATA_OR = 0x1, PHY_DATA_AND = 0x2, PHY_BJMPN = 0x3, PHY_MDIO_CHG = 0x4, PHY_CLEAR_READCOUNT = 0x7, PHY_WRITE = 0x8, PHY_READCOUNT_EQ_SKIP = 0x9, PHY_COMP_EQ_SKIPN = 0xa, PHY_COMP_NEQ_SKIPN = 0xb, PHY_WRITE_PREVIOUS = 0xc, PHY_SKIPN = 0xd, PHY_DELAY_MS = 0xe, }; struct fw_info { u32 magic; char version[RTL_VER_SIZE]; __le32 fw_start; __le32 fw_len; u8 chksum; } __packed; #define FW_OPCODE_SIZE sizeof_field(struct rtl_fw_phy_action, code[0]) static bool rtl_fw_format_ok(struct rtl_fw *rtl_fw) { const struct firmware *fw = rtl_fw->fw; struct fw_info *fw_info = (struct fw_info *)fw->data; struct rtl_fw_phy_action *pa = &rtl_fw->phy_action; if (fw->size < FW_OPCODE_SIZE) return false; if (!fw_info->magic) { size_t i, size, start; u8 checksum = 0; if (fw->size < sizeof(*fw_info)) return false; for (i = 0; i < fw->size; i++) checksum += fw->data[i]; if (checksum != 0) return false; start = le32_to_cpu(fw_info->fw_start); if (start > fw->size) return false; size = le32_to_cpu(fw_info->fw_len); if (size > (fw->size - start) / FW_OPCODE_SIZE) return false; strscpy(rtl_fw->version, fw_info->version, RTL_VER_SIZE); pa->code = (__le32 *)(fw->data + start); pa->size = size; } else { if (fw->size % FW_OPCODE_SIZE) return false; strscpy(rtl_fw->version, rtl_fw->fw_name, RTL_VER_SIZE); pa->code = (__le32 *)fw->data; pa->size = fw->size / FW_OPCODE_SIZE; } return true; } static bool rtl_fw_data_ok(struct rtl_fw *rtl_fw) { struct rtl_fw_phy_action *pa = &rtl_fw->phy_action; size_t index; for (index = 0; index < pa->size; index++) { u32 action = le32_to_cpu(pa->code[index]); u32 val = action & 0x0000ffff; u32 regno = (action & 0x0fff0000) >> 16; switch (action >> 28) { case PHY_READ: case PHY_DATA_OR: case PHY_DATA_AND: case PHY_CLEAR_READCOUNT: case PHY_WRITE: case PHY_WRITE_PREVIOUS: case PHY_DELAY_MS: break; case PHY_MDIO_CHG: if (val > 1) goto out; break; case PHY_BJMPN: if (regno > index) goto out; break; case PHY_READCOUNT_EQ_SKIP: if (index + 2 >= pa->size) goto out; break; case PHY_COMP_EQ_SKIPN: case PHY_COMP_NEQ_SKIPN: case PHY_SKIPN: if (index + 1 + regno >= pa->size) goto out; break; default: dev_err(rtl_fw->dev, "Invalid action 0x%08x\n", action); return false; } } return true; out: dev_err(rtl_fw->dev, "Out of range of firmware\n"); return false; } void rtl_fw_write_firmware(struct rtl8169_private *tp, struct rtl_fw *rtl_fw) { struct rtl_fw_phy_action *pa = &rtl_fw->phy_action; rtl_fw_write_t fw_write = rtl_fw->phy_write; rtl_fw_read_t fw_read = rtl_fw->phy_read; int predata = 0, count = 0; size_t index; for (index = 0; index < pa->size; index++) { u32 action = le32_to_cpu(pa->code[index]); u32 data = action & 0x0000ffff; u32 regno = (action & 0x0fff0000) >> 16; enum rtl_fw_opcode opcode = action >> 28; if (!action) break; switch (opcode) { case PHY_READ: predata = fw_read(tp, regno); count++; break; case PHY_DATA_OR: predata |= data; break; case PHY_DATA_AND: predata &= data; break; case PHY_BJMPN: index -= (regno + 1); break; case PHY_MDIO_CHG: if (data) { fw_write = rtl_fw->mac_mcu_write; fw_read = rtl_fw->mac_mcu_read; } else { fw_write = rtl_fw->phy_write; fw_read = rtl_fw->phy_read; } break; case PHY_CLEAR_READCOUNT: count = 0; break; case PHY_WRITE: fw_write(tp, regno, data); break; case PHY_READCOUNT_EQ_SKIP: if (count == data) index++; break; case PHY_COMP_EQ_SKIPN: if (predata == data) index += regno; break; case PHY_COMP_NEQ_SKIPN: if (predata != data) index += regno; break; case PHY_WRITE_PREVIOUS: fw_write(tp, regno, predata); break; case PHY_SKIPN: index += regno; break; case PHY_DELAY_MS: msleep(data); break; } } } void rtl_fw_release_firmware(struct rtl_fw *rtl_fw) { release_firmware(rtl_fw->fw); } int rtl_fw_request_firmware(struct rtl_fw *rtl_fw) { int rc; rc = request_firmware(&rtl_fw->fw, rtl_fw->fw_name, rtl_fw->dev); if (rc < 0) goto out; if (!rtl_fw_format_ok(rtl_fw) || !rtl_fw_data_ok(rtl_fw)) { release_firmware(rtl_fw->fw); rc = -EINVAL; goto out; } return 0; out: dev_err(rtl_fw->dev, "Unable to load firmware %s (%d)\n", rtl_fw->fw_name, rc); return rc; }
linux-master
drivers/net/ethernet/realtek/r8169_firmware.c
/* 8139cp.c: A Linux PCI Ethernet driver for the RealTek 8139C+ chips. */ /* Copyright 2001-2004 Jeff Garzik <[email protected]> Copyright (C) 2001, 2002 David S. Miller ([email protected]) [tg3.c] Copyright (C) 2000, 2001 David S. Miller ([email protected]) [sungem.c] Copyright 2001 Manfred Spraul [natsemi.c] Copyright 1999-2001 by Donald Becker. [natsemi.c] Written 1997-2001 by Donald Becker. [8139too.c] Copyright 1998-2001 by Jes Sorensen, <[email protected]>. [acenic.c] 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. Contributors: Wake-on-LAN support - Felipe Damasio <[email protected]> PCI suspend/resume - Felipe Damasio <[email protected]> LinkChg interrupt - Felipe Damasio <[email protected]> TODO: * Test Tx checksumming thoroughly Low priority TODO: * Complete reset on PciErr * Consider Rx interrupt mitigation using TimerIntr * Investigate using skb->priority with h/w VLAN priority * Investigate using High Priority Tx Queue with skb->priority * Adjust Rx FIFO threshold and Max Rx DMA burst on Rx FIFO error * Adjust Tx FIFO threshold and Max Tx DMA burst on Tx FIFO error * Implement Tx software interrupt mitigation via Tx descriptor bit * The real minimum of CP_MIN_MTU is 4 bytes. However, for this to be supported, one must(?) turn on packet padding. * Support external MII transceivers (patch available) NOTES: * TX checksumming is considered experimental. It is off by default, use ethtool to turn it on. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #define DRV_NAME "8139cp" #define DRV_VERSION "1.3" #define DRV_RELDATE "Mar 22, 2004" #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/kernel.h> #include <linux/compiler.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/pci.h> #include <linux/dma-mapping.h> #include <linux/delay.h> #include <linux/ethtool.h> #include <linux/gfp.h> #include <linux/mii.h> #include <linux/if_vlan.h> #include <linux/crc32.h> #include <linux/in.h> #include <linux/ip.h> #include <linux/tcp.h> #include <linux/udp.h> #include <linux/cache.h> #include <asm/io.h> #include <asm/irq.h> #include <linux/uaccess.h> /* These identify the driver base version and may not be removed. */ static char version[] = DRV_NAME ": 10/100 PCI Ethernet driver v" DRV_VERSION " (" DRV_RELDATE ")\n"; MODULE_AUTHOR("Jeff Garzik <[email protected]>"); MODULE_DESCRIPTION("RealTek RTL-8139C+ series 10/100 PCI Ethernet driver"); MODULE_VERSION(DRV_VERSION); MODULE_LICENSE("GPL"); static int debug = -1; module_param(debug, int, 0); MODULE_PARM_DESC (debug, "8139cp: bitmapped message enable number"); /* Maximum number of multicast addresses to filter (vs. Rx-all-multicast). The RTL chips use a 64 element hash table based on the Ethernet CRC. */ static int multicast_filter_limit = 32; module_param(multicast_filter_limit, int, 0); MODULE_PARM_DESC (multicast_filter_limit, "8139cp: maximum number of filtered multicast addresses"); #define CP_DEF_MSG_ENABLE (NETIF_MSG_DRV | \ NETIF_MSG_PROBE | \ NETIF_MSG_LINK) #define CP_NUM_STATS 14 /* struct cp_dma_stats, plus one */ #define CP_STATS_SIZE 64 /* size in bytes of DMA stats block */ #define CP_REGS_SIZE (0xff + 1) #define CP_REGS_VER 1 /* version 1 */ #define CP_RX_RING_SIZE 64 #define CP_TX_RING_SIZE 64 #define CP_RING_BYTES \ ((sizeof(struct cp_desc) * CP_RX_RING_SIZE) + \ (sizeof(struct cp_desc) * CP_TX_RING_SIZE) + \ CP_STATS_SIZE) #define NEXT_TX(N) (((N) + 1) & (CP_TX_RING_SIZE - 1)) #define NEXT_RX(N) (((N) + 1) & (CP_RX_RING_SIZE - 1)) #define TX_BUFFS_AVAIL(CP) \ (((CP)->tx_tail <= (CP)->tx_head) ? \ (CP)->tx_tail + (CP_TX_RING_SIZE - 1) - (CP)->tx_head : \ (CP)->tx_tail - (CP)->tx_head - 1) #define PKT_BUF_SZ 1536 /* Size of each temporary Rx buffer.*/ #define CP_INTERNAL_PHY 32 /* The following settings are log_2(bytes)-4: 0 == 16 bytes .. 6==1024, 7==end of packet. */ #define RX_FIFO_THRESH 5 /* Rx buffer level before first PCI xfer. */ #define RX_DMA_BURST 4 /* Maximum PCI burst, '4' is 256 */ #define TX_DMA_BURST 6 /* Maximum PCI burst, '6' is 1024 */ #define TX_EARLY_THRESH 256 /* Early Tx threshold, in bytes */ /* Time in jiffies before concluding the transmitter is hung. */ #define TX_TIMEOUT (6*HZ) /* hardware minimum and maximum for a single frame's data payload */ #define CP_MIN_MTU 60 /* TODO: allow lower, but pad */ #define CP_MAX_MTU 4096 enum { /* NIC register offsets */ MAC0 = 0x00, /* Ethernet hardware address. */ MAR0 = 0x08, /* Multicast filter. */ StatsAddr = 0x10, /* 64-bit start addr of 64-byte DMA stats blk */ TxRingAddr = 0x20, /* 64-bit start addr of Tx ring */ HiTxRingAddr = 0x28, /* 64-bit start addr of high priority Tx ring */ Cmd = 0x37, /* Command register */ IntrMask = 0x3C, /* Interrupt mask */ IntrStatus = 0x3E, /* Interrupt status */ TxConfig = 0x40, /* Tx configuration */ ChipVersion = 0x43, /* 8-bit chip version, inside TxConfig */ RxConfig = 0x44, /* Rx configuration */ RxMissed = 0x4C, /* 24 bits valid, write clears */ Cfg9346 = 0x50, /* EEPROM select/control; Cfg reg [un]lock */ Config1 = 0x52, /* Config1 */ Config3 = 0x59, /* Config3 */ Config4 = 0x5A, /* Config4 */ MultiIntr = 0x5C, /* Multiple interrupt select */ BasicModeCtrl = 0x62, /* MII BMCR */ BasicModeStatus = 0x64, /* MII BMSR */ NWayAdvert = 0x66, /* MII ADVERTISE */ NWayLPAR = 0x68, /* MII LPA */ NWayExpansion = 0x6A, /* MII Expansion */ TxDmaOkLowDesc = 0x82, /* Low 16 bit address of a Tx descriptor. */ Config5 = 0xD8, /* Config5 */ TxPoll = 0xD9, /* Tell chip to check Tx descriptors for work */ RxMaxSize = 0xDA, /* Max size of an Rx packet (8169 only) */ CpCmd = 0xE0, /* C+ Command register (C+ mode only) */ IntrMitigate = 0xE2, /* rx/tx interrupt mitigation control */ RxRingAddr = 0xE4, /* 64-bit start addr of Rx ring */ TxThresh = 0xEC, /* Early Tx threshold */ OldRxBufAddr = 0x30, /* DMA address of Rx ring buffer (C mode) */ OldTSD0 = 0x10, /* DMA address of first Tx desc (C mode) */ /* Tx and Rx status descriptors */ DescOwn = (1 << 31), /* Descriptor is owned by NIC */ RingEnd = (1 << 30), /* End of descriptor ring */ FirstFrag = (1 << 29), /* First segment of a packet */ LastFrag = (1 << 28), /* Final segment of a packet */ LargeSend = (1 << 27), /* TCP Large Send Offload (TSO) */ MSSShift = 16, /* MSS value position */ MSSMask = 0x7ff, /* MSS value: 11 bits */ TxError = (1 << 23), /* Tx error summary */ RxError = (1 << 20), /* Rx error summary */ IPCS = (1 << 18), /* Calculate IP checksum */ UDPCS = (1 << 17), /* Calculate UDP/IP checksum */ TCPCS = (1 << 16), /* Calculate TCP/IP checksum */ TxVlanTag = (1 << 17), /* Add VLAN tag */ RxVlanTagged = (1 << 16), /* Rx VLAN tag available */ IPFail = (1 << 15), /* IP checksum failed */ UDPFail = (1 << 14), /* UDP/IP checksum failed */ TCPFail = (1 << 13), /* TCP/IP checksum failed */ NormalTxPoll = (1 << 6), /* One or more normal Tx packets to send */ PID1 = (1 << 17), /* 2 protocol id bits: 0==non-IP, */ PID0 = (1 << 16), /* 1==UDP/IP, 2==TCP/IP, 3==IP */ RxProtoTCP = 1, RxProtoUDP = 2, RxProtoIP = 3, TxFIFOUnder = (1 << 25), /* Tx FIFO underrun */ TxOWC = (1 << 22), /* Tx Out-of-window collision */ TxLinkFail = (1 << 21), /* Link failed during Tx of packet */ TxMaxCol = (1 << 20), /* Tx aborted due to excessive collisions */ TxColCntShift = 16, /* Shift, to get 4-bit Tx collision cnt */ TxColCntMask = 0x01 | 0x02 | 0x04 | 0x08, /* 4-bit collision count */ RxErrFrame = (1 << 27), /* Rx frame alignment error */ RxMcast = (1 << 26), /* Rx multicast packet rcv'd */ RxErrCRC = (1 << 18), /* Rx CRC error */ RxErrRunt = (1 << 19), /* Rx error, packet < 64 bytes */ RxErrLong = (1 << 21), /* Rx error, packet > 4096 bytes */ RxErrFIFO = (1 << 22), /* Rx error, FIFO overflowed, pkt bad */ /* StatsAddr register */ DumpStats = (1 << 3), /* Begin stats dump */ /* RxConfig register */ RxCfgFIFOShift = 13, /* Shift, to get Rx FIFO thresh value */ RxCfgDMAShift = 8, /* Shift, to get Rx Max DMA value */ AcceptErr = 0x20, /* Accept packets with CRC errors */ AcceptRunt = 0x10, /* Accept runt (<64 bytes) packets */ AcceptBroadcast = 0x08, /* Accept broadcast packets */ AcceptMulticast = 0x04, /* Accept multicast packets */ AcceptMyPhys = 0x02, /* Accept pkts with our MAC as dest */ AcceptAllPhys = 0x01, /* Accept all pkts w/ physical dest */ /* IntrMask / IntrStatus registers */ PciErr = (1 << 15), /* System error on the PCI bus */ TimerIntr = (1 << 14), /* Asserted when TCTR reaches TimerInt value */ LenChg = (1 << 13), /* Cable length change */ SWInt = (1 << 8), /* Software-requested interrupt */ TxEmpty = (1 << 7), /* No Tx descriptors available */ RxFIFOOvr = (1 << 6), /* Rx FIFO Overflow */ LinkChg = (1 << 5), /* Packet underrun, or link change */ RxEmpty = (1 << 4), /* No Rx descriptors available */ TxErr = (1 << 3), /* Tx error */ TxOK = (1 << 2), /* Tx packet sent */ RxErr = (1 << 1), /* Rx error */ RxOK = (1 << 0), /* Rx packet received */ IntrResvd = (1 << 10), /* reserved, according to RealTek engineers, but hardware likes to raise it */ IntrAll = PciErr | TimerIntr | LenChg | SWInt | TxEmpty | RxFIFOOvr | LinkChg | RxEmpty | TxErr | TxOK | RxErr | RxOK | IntrResvd, /* C mode command register */ CmdReset = (1 << 4), /* Enable to reset; self-clearing */ RxOn = (1 << 3), /* Rx mode enable */ TxOn = (1 << 2), /* Tx mode enable */ /* C+ mode command register */ RxVlanOn = (1 << 6), /* Rx VLAN de-tagging enable */ RxChkSum = (1 << 5), /* Rx checksum offload enable */ PCIDAC = (1 << 4), /* PCI Dual Address Cycle (64-bit PCI) */ PCIMulRW = (1 << 3), /* Enable PCI read/write multiple */ CpRxOn = (1 << 1), /* Rx mode enable */ CpTxOn = (1 << 0), /* Tx mode enable */ /* Cfg9436 EEPROM control register */ Cfg9346_Lock = 0x00, /* Lock ConfigX/MII register access */ Cfg9346_Unlock = 0xC0, /* Unlock ConfigX/MII register access */ /* TxConfig register */ IFG = (1 << 25) | (1 << 24), /* standard IEEE interframe gap */ TxDMAShift = 8, /* DMA burst value (0-7) is shift this many bits */ /* Early Tx Threshold register */ TxThreshMask = 0x3f, /* Mask bits 5-0 */ TxThreshMax = 2048, /* Max early Tx threshold */ /* Config1 register */ DriverLoaded = (1 << 5), /* Software marker, driver is loaded */ LWACT = (1 << 4), /* LWAKE active mode */ PMEnable = (1 << 0), /* Enable various PM features of chip */ /* Config3 register */ PARMEnable = (1 << 6), /* Enable auto-loading of PHY parms */ MagicPacket = (1 << 5), /* Wake up when receives a Magic Packet */ LinkUp = (1 << 4), /* Wake up when the cable connection is re-established */ /* Config4 register */ LWPTN = (1 << 1), /* LWAKE Pattern */ LWPME = (1 << 4), /* LANWAKE vs PMEB */ /* Config5 register */ BWF = (1 << 6), /* Accept Broadcast wakeup frame */ MWF = (1 << 5), /* Accept Multicast wakeup frame */ UWF = (1 << 4), /* Accept Unicast wakeup frame */ LANWake = (1 << 1), /* Enable LANWake signal */ PMEStatus = (1 << 0), /* PME status can be reset by PCI RST# */ cp_norx_intr_mask = PciErr | LinkChg | TxOK | TxErr | TxEmpty, cp_rx_intr_mask = RxOK | RxErr | RxEmpty | RxFIFOOvr, cp_intr_mask = cp_rx_intr_mask | cp_norx_intr_mask, }; static const unsigned int cp_rx_config = (RX_FIFO_THRESH << RxCfgFIFOShift) | (RX_DMA_BURST << RxCfgDMAShift); struct cp_desc { __le32 opts1; __le32 opts2; __le64 addr; }; struct cp_dma_stats { __le64 tx_ok; __le64 rx_ok; __le64 tx_err; __le32 rx_err; __le16 rx_fifo; __le16 frame_align; __le32 tx_ok_1col; __le32 tx_ok_mcol; __le64 rx_ok_phys; __le64 rx_ok_bcast; __le32 rx_ok_mcast; __le16 tx_abort; __le16 tx_underrun; } __packed; struct cp_extra_stats { unsigned long rx_frags; }; struct cp_private { void __iomem *regs; struct net_device *dev; spinlock_t lock; u32 msg_enable; struct napi_struct napi; struct pci_dev *pdev; u32 rx_config; u16 cpcmd; struct cp_extra_stats cp_stats; unsigned rx_head ____cacheline_aligned; unsigned rx_tail; struct cp_desc *rx_ring; struct sk_buff *rx_skb[CP_RX_RING_SIZE]; unsigned tx_head ____cacheline_aligned; unsigned tx_tail; struct cp_desc *tx_ring; struct sk_buff *tx_skb[CP_TX_RING_SIZE]; u32 tx_opts[CP_TX_RING_SIZE]; unsigned rx_buf_sz; unsigned wol_enabled : 1; /* Is Wake-on-LAN enabled? */ dma_addr_t ring_dma; struct mii_if_info mii_if; }; #define cpr8(reg) readb(cp->regs + (reg)) #define cpr16(reg) readw(cp->regs + (reg)) #define cpr32(reg) readl(cp->regs + (reg)) #define cpw8(reg,val) writeb((val), cp->regs + (reg)) #define cpw16(reg,val) writew((val), cp->regs + (reg)) #define cpw32(reg,val) writel((val), cp->regs + (reg)) #define cpw8_f(reg,val) do { \ writeb((val), cp->regs + (reg)); \ readb(cp->regs + (reg)); \ } while (0) #define cpw16_f(reg,val) do { \ writew((val), cp->regs + (reg)); \ readw(cp->regs + (reg)); \ } while (0) #define cpw32_f(reg,val) do { \ writel((val), cp->regs + (reg)); \ readl(cp->regs + (reg)); \ } while (0) static void __cp_set_rx_mode (struct net_device *dev); static void cp_tx (struct cp_private *cp); static void cp_clean_rings (struct cp_private *cp); #ifdef CONFIG_NET_POLL_CONTROLLER static void cp_poll_controller(struct net_device *dev); #endif static int cp_get_eeprom_len(struct net_device *dev); static int cp_get_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom, u8 *data); static int cp_set_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom, u8 *data); static struct { const char str[ETH_GSTRING_LEN]; } ethtool_stats_keys[] = { { "tx_ok" }, { "rx_ok" }, { "tx_err" }, { "rx_err" }, { "rx_fifo" }, { "frame_align" }, { "tx_ok_1col" }, { "tx_ok_mcol" }, { "rx_ok_phys" }, { "rx_ok_bcast" }, { "rx_ok_mcast" }, { "tx_abort" }, { "tx_underrun" }, { "rx_frags" }, }; static inline void cp_set_rxbufsize (struct cp_private *cp) { unsigned int mtu = cp->dev->mtu; if (mtu > ETH_DATA_LEN) /* MTU + ethernet header + FCS + optional VLAN tag */ cp->rx_buf_sz = mtu + ETH_HLEN + 8; else cp->rx_buf_sz = PKT_BUF_SZ; } static inline void cp_rx_skb (struct cp_private *cp, struct sk_buff *skb, struct cp_desc *desc) { u32 opts2 = le32_to_cpu(desc->opts2); skb->protocol = eth_type_trans (skb, cp->dev); cp->dev->stats.rx_packets++; cp->dev->stats.rx_bytes += skb->len; if (opts2 & RxVlanTagged) __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), swab16(opts2 & 0xffff)); napi_gro_receive(&cp->napi, skb); } static void cp_rx_err_acct (struct cp_private *cp, unsigned rx_tail, u32 status, u32 len) { netif_dbg(cp, rx_err, cp->dev, "rx err, slot %d status 0x%x len %d\n", rx_tail, status, len); cp->dev->stats.rx_errors++; if (status & RxErrFrame) cp->dev->stats.rx_frame_errors++; if (status & RxErrCRC) cp->dev->stats.rx_crc_errors++; if ((status & RxErrRunt) || (status & RxErrLong)) cp->dev->stats.rx_length_errors++; if ((status & (FirstFrag | LastFrag)) != (FirstFrag | LastFrag)) cp->dev->stats.rx_length_errors++; if (status & RxErrFIFO) cp->dev->stats.rx_fifo_errors++; } static inline unsigned int cp_rx_csum_ok (u32 status) { unsigned int protocol = (status >> 16) & 0x3; if (((protocol == RxProtoTCP) && !(status & TCPFail)) || ((protocol == RxProtoUDP) && !(status & UDPFail))) return 1; else return 0; } static int cp_rx_poll(struct napi_struct *napi, int budget) { struct cp_private *cp = container_of(napi, struct cp_private, napi); struct net_device *dev = cp->dev; unsigned int rx_tail = cp->rx_tail; int rx = 0; cpw16(IntrStatus, cp_rx_intr_mask); while (rx < budget) { u32 status, len; dma_addr_t mapping, new_mapping; struct sk_buff *skb, *new_skb; struct cp_desc *desc; const unsigned buflen = cp->rx_buf_sz; skb = cp->rx_skb[rx_tail]; BUG_ON(!skb); desc = &cp->rx_ring[rx_tail]; status = le32_to_cpu(desc->opts1); if (status & DescOwn) break; len = (status & 0x1fff) - 4; mapping = le64_to_cpu(desc->addr); if ((status & (FirstFrag | LastFrag)) != (FirstFrag | LastFrag)) { /* we don't support incoming fragmented frames. * instead, we attempt to ensure that the * pre-allocated RX skbs are properly sized such * that RX fragments are never encountered */ cp_rx_err_acct(cp, rx_tail, status, len); dev->stats.rx_dropped++; cp->cp_stats.rx_frags++; goto rx_next; } if (status & (RxError | RxErrFIFO)) { cp_rx_err_acct(cp, rx_tail, status, len); goto rx_next; } netif_dbg(cp, rx_status, dev, "rx slot %d status 0x%x len %d\n", rx_tail, status, len); new_skb = napi_alloc_skb(napi, buflen); if (!new_skb) { dev->stats.rx_dropped++; goto rx_next; } new_mapping = dma_map_single(&cp->pdev->dev, new_skb->data, buflen, DMA_FROM_DEVICE); if (dma_mapping_error(&cp->pdev->dev, new_mapping)) { dev->stats.rx_dropped++; kfree_skb(new_skb); goto rx_next; } dma_unmap_single(&cp->pdev->dev, mapping, buflen, DMA_FROM_DEVICE); /* Handle checksum offloading for incoming packets. */ if (cp_rx_csum_ok(status)) skb->ip_summed = CHECKSUM_UNNECESSARY; else skb_checksum_none_assert(skb); skb_put(skb, len); cp->rx_skb[rx_tail] = new_skb; cp_rx_skb(cp, skb, desc); rx++; mapping = new_mapping; rx_next: cp->rx_ring[rx_tail].opts2 = 0; cp->rx_ring[rx_tail].addr = cpu_to_le64(mapping); if (rx_tail == (CP_RX_RING_SIZE - 1)) desc->opts1 = cpu_to_le32(DescOwn | RingEnd | cp->rx_buf_sz); else desc->opts1 = cpu_to_le32(DescOwn | cp->rx_buf_sz); rx_tail = NEXT_RX(rx_tail); } cp->rx_tail = rx_tail; /* if we did not reach work limit, then we're done with * this round of polling */ if (rx < budget && napi_complete_done(napi, rx)) { unsigned long flags; spin_lock_irqsave(&cp->lock, flags); cpw16_f(IntrMask, cp_intr_mask); spin_unlock_irqrestore(&cp->lock, flags); } return rx; } static irqreturn_t cp_interrupt (int irq, void *dev_instance) { struct net_device *dev = dev_instance; struct cp_private *cp; int handled = 0; u16 status; u16 mask; if (unlikely(dev == NULL)) return IRQ_NONE; cp = netdev_priv(dev); spin_lock(&cp->lock); mask = cpr16(IntrMask); if (!mask) goto out_unlock; status = cpr16(IntrStatus); if (!status || (status == 0xFFFF)) goto out_unlock; handled = 1; netif_dbg(cp, intr, dev, "intr, status %04x cmd %02x cpcmd %04x\n", status, cpr8(Cmd), cpr16(CpCmd)); cpw16(IntrStatus, status & ~cp_rx_intr_mask); /* close possible race's with dev_close */ if (unlikely(!netif_running(dev))) { cpw16(IntrMask, 0); goto out_unlock; } if (status & (RxOK | RxErr | RxEmpty | RxFIFOOvr)) if (napi_schedule_prep(&cp->napi)) { cpw16_f(IntrMask, cp_norx_intr_mask); __napi_schedule(&cp->napi); } if (status & (TxOK | TxErr | TxEmpty | SWInt)) cp_tx(cp); if (status & LinkChg) mii_check_media(&cp->mii_if, netif_msg_link(cp), false); if (status & PciErr) { u16 pci_status; pci_read_config_word(cp->pdev, PCI_STATUS, &pci_status); pci_write_config_word(cp->pdev, PCI_STATUS, pci_status); netdev_err(dev, "PCI bus error, status=%04x, PCI status=%04x\n", status, pci_status); /* TODO: reset hardware */ } out_unlock: spin_unlock(&cp->lock); return IRQ_RETVAL(handled); } #ifdef CONFIG_NET_POLL_CONTROLLER /* * Polling receive - used by netconsole and other diagnostic tools * to allow network i/o with interrupts disabled. */ static void cp_poll_controller(struct net_device *dev) { struct cp_private *cp = netdev_priv(dev); const int irq = cp->pdev->irq; disable_irq(irq); cp_interrupt(irq, dev); enable_irq(irq); } #endif static void cp_tx (struct cp_private *cp) { unsigned tx_head = cp->tx_head; unsigned tx_tail = cp->tx_tail; unsigned bytes_compl = 0, pkts_compl = 0; while (tx_tail != tx_head) { struct cp_desc *txd = cp->tx_ring + tx_tail; struct sk_buff *skb; u32 status; rmb(); status = le32_to_cpu(txd->opts1); if (status & DescOwn) break; skb = cp->tx_skb[tx_tail]; BUG_ON(!skb); dma_unmap_single(&cp->pdev->dev, le64_to_cpu(txd->addr), cp->tx_opts[tx_tail] & 0xffff, DMA_TO_DEVICE); if (status & LastFrag) { if (status & (TxError | TxFIFOUnder)) { netif_dbg(cp, tx_err, cp->dev, "tx err, status 0x%x\n", status); cp->dev->stats.tx_errors++; if (status & TxOWC) cp->dev->stats.tx_window_errors++; if (status & TxMaxCol) cp->dev->stats.tx_aborted_errors++; if (status & TxLinkFail) cp->dev->stats.tx_carrier_errors++; if (status & TxFIFOUnder) cp->dev->stats.tx_fifo_errors++; } else { cp->dev->stats.collisions += ((status >> TxColCntShift) & TxColCntMask); cp->dev->stats.tx_packets++; cp->dev->stats.tx_bytes += skb->len; netif_dbg(cp, tx_done, cp->dev, "tx done, slot %d\n", tx_tail); } bytes_compl += skb->len; pkts_compl++; dev_consume_skb_irq(skb); } cp->tx_skb[tx_tail] = NULL; tx_tail = NEXT_TX(tx_tail); } cp->tx_tail = tx_tail; netdev_completed_queue(cp->dev, pkts_compl, bytes_compl); if (TX_BUFFS_AVAIL(cp) > (MAX_SKB_FRAGS + 1)) netif_wake_queue(cp->dev); } static inline u32 cp_tx_vlan_tag(struct sk_buff *skb) { return skb_vlan_tag_present(skb) ? TxVlanTag | swab16(skb_vlan_tag_get(skb)) : 0x00; } static void unwind_tx_frag_mapping(struct cp_private *cp, struct sk_buff *skb, int first, int entry_last) { int frag, index; struct cp_desc *txd; skb_frag_t *this_frag; for (frag = 0; frag+first < entry_last; frag++) { index = first+frag; cp->tx_skb[index] = NULL; txd = &cp->tx_ring[index]; this_frag = &skb_shinfo(skb)->frags[frag]; dma_unmap_single(&cp->pdev->dev, le64_to_cpu(txd->addr), skb_frag_size(this_frag), DMA_TO_DEVICE); } } static netdev_tx_t cp_start_xmit (struct sk_buff *skb, struct net_device *dev) { struct cp_private *cp = netdev_priv(dev); unsigned entry; u32 eor, opts1; unsigned long intr_flags; __le32 opts2; int mss = 0; spin_lock_irqsave(&cp->lock, intr_flags); /* This is a hard error, log it. */ if (TX_BUFFS_AVAIL(cp) <= (skb_shinfo(skb)->nr_frags + 1)) { netif_stop_queue(dev); spin_unlock_irqrestore(&cp->lock, intr_flags); netdev_err(dev, "BUG! Tx Ring full when queue awake!\n"); return NETDEV_TX_BUSY; } entry = cp->tx_head; eor = (entry == (CP_TX_RING_SIZE - 1)) ? RingEnd : 0; mss = skb_shinfo(skb)->gso_size; if (mss > MSSMask) { netdev_WARN_ONCE(dev, "Net bug: GSO size %d too large for 8139CP\n", mss); goto out_dma_error; } opts2 = cpu_to_le32(cp_tx_vlan_tag(skb)); opts1 = DescOwn; if (mss) opts1 |= LargeSend | (mss << MSSShift); else if (skb->ip_summed == CHECKSUM_PARTIAL) { const struct iphdr *ip = ip_hdr(skb); if (ip->protocol == IPPROTO_TCP) opts1 |= IPCS | TCPCS; else if (ip->protocol == IPPROTO_UDP) opts1 |= IPCS | UDPCS; else { WARN_ONCE(1, "Net bug: asked to checksum invalid Legacy IP packet\n"); goto out_dma_error; } } if (skb_shinfo(skb)->nr_frags == 0) { struct cp_desc *txd = &cp->tx_ring[entry]; u32 len; dma_addr_t mapping; len = skb->len; mapping = dma_map_single(&cp->pdev->dev, skb->data, len, DMA_TO_DEVICE); if (dma_mapping_error(&cp->pdev->dev, mapping)) goto out_dma_error; txd->opts2 = opts2; txd->addr = cpu_to_le64(mapping); wmb(); opts1 |= eor | len | FirstFrag | LastFrag; txd->opts1 = cpu_to_le32(opts1); wmb(); cp->tx_skb[entry] = skb; cp->tx_opts[entry] = opts1; netif_dbg(cp, tx_queued, cp->dev, "tx queued, slot %d, skblen %d\n", entry, skb->len); } else { struct cp_desc *txd; u32 first_len, first_eor, ctrl; dma_addr_t first_mapping; int frag, first_entry = entry; /* We must give this initial chunk to the device last. * Otherwise we could race with the device. */ first_eor = eor; first_len = skb_headlen(skb); first_mapping = dma_map_single(&cp->pdev->dev, skb->data, first_len, DMA_TO_DEVICE); if (dma_mapping_error(&cp->pdev->dev, first_mapping)) goto out_dma_error; cp->tx_skb[entry] = skb; for (frag = 0; frag < skb_shinfo(skb)->nr_frags; frag++) { const skb_frag_t *this_frag = &skb_shinfo(skb)->frags[frag]; u32 len; dma_addr_t mapping; entry = NEXT_TX(entry); len = skb_frag_size(this_frag); mapping = dma_map_single(&cp->pdev->dev, skb_frag_address(this_frag), len, DMA_TO_DEVICE); if (dma_mapping_error(&cp->pdev->dev, mapping)) { unwind_tx_frag_mapping(cp, skb, first_entry, entry); goto out_dma_error; } eor = (entry == (CP_TX_RING_SIZE - 1)) ? RingEnd : 0; ctrl = opts1 | eor | len; if (frag == skb_shinfo(skb)->nr_frags - 1) ctrl |= LastFrag; txd = &cp->tx_ring[entry]; txd->opts2 = opts2; txd->addr = cpu_to_le64(mapping); wmb(); txd->opts1 = cpu_to_le32(ctrl); wmb(); cp->tx_opts[entry] = ctrl; cp->tx_skb[entry] = skb; } txd = &cp->tx_ring[first_entry]; txd->opts2 = opts2; txd->addr = cpu_to_le64(first_mapping); wmb(); ctrl = opts1 | first_eor | first_len | FirstFrag; txd->opts1 = cpu_to_le32(ctrl); wmb(); cp->tx_opts[first_entry] = ctrl; netif_dbg(cp, tx_queued, cp->dev, "tx queued, slots %d-%d, skblen %d\n", first_entry, entry, skb->len); } cp->tx_head = NEXT_TX(entry); netdev_sent_queue(dev, skb->len); if (TX_BUFFS_AVAIL(cp) <= (MAX_SKB_FRAGS + 1)) netif_stop_queue(dev); out_unlock: spin_unlock_irqrestore(&cp->lock, intr_flags); cpw8(TxPoll, NormalTxPoll); return NETDEV_TX_OK; out_dma_error: dev_kfree_skb_any(skb); cp->dev->stats.tx_dropped++; goto out_unlock; } /* Set or clear the multicast filter for this adaptor. This routine is not state sensitive and need not be SMP locked. */ static void __cp_set_rx_mode (struct net_device *dev) { struct cp_private *cp = netdev_priv(dev); u32 mc_filter[2]; /* Multicast hash filter */ int rx_mode; /* Note: do not reorder, GCC is clever about common statements. */ if (dev->flags & IFF_PROMISC) { /* Unconditionally log net taps. */ 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) >> 26; mc_filter[bit_nr >> 5] |= 1 << (bit_nr & 31); rx_mode |= AcceptMulticast; } } /* We can safely update without stopping the chip. */ cp->rx_config = cp_rx_config | rx_mode; cpw32_f(RxConfig, cp->rx_config); cpw32_f (MAR0 + 0, mc_filter[0]); cpw32_f (MAR0 + 4, mc_filter[1]); } static void cp_set_rx_mode (struct net_device *dev) { unsigned long flags; struct cp_private *cp = netdev_priv(dev); spin_lock_irqsave (&cp->lock, flags); __cp_set_rx_mode(dev); spin_unlock_irqrestore (&cp->lock, flags); } static void __cp_get_stats(struct cp_private *cp) { /* only lower 24 bits valid; write any value to clear */ cp->dev->stats.rx_missed_errors += (cpr32 (RxMissed) & 0xffffff); cpw32 (RxMissed, 0); } static struct net_device_stats *cp_get_stats(struct net_device *dev) { struct cp_private *cp = netdev_priv(dev); unsigned long flags; /* The chip only need report frame silently dropped. */ spin_lock_irqsave(&cp->lock, flags); if (netif_running(dev) && netif_device_present(dev)) __cp_get_stats(cp); spin_unlock_irqrestore(&cp->lock, flags); return &dev->stats; } static void cp_stop_hw (struct cp_private *cp) { cpw16(IntrStatus, ~(cpr16(IntrStatus))); cpw16_f(IntrMask, 0); cpw8(Cmd, 0); cpw16_f(CpCmd, 0); cpw16_f(IntrStatus, ~(cpr16(IntrStatus))); cp->rx_tail = 0; cp->tx_head = cp->tx_tail = 0; netdev_reset_queue(cp->dev); } static void cp_reset_hw (struct cp_private *cp) { unsigned work = 1000; cpw8(Cmd, CmdReset); while (work--) { if (!(cpr8(Cmd) & CmdReset)) return; schedule_timeout_uninterruptible(10); } netdev_err(cp->dev, "hardware reset timeout\n"); } static inline void cp_start_hw (struct cp_private *cp) { dma_addr_t ring_dma; cpw16(CpCmd, cp->cpcmd); /* * These (at least TxRingAddr) need to be configured after the * corresponding bits in CpCmd are enabled. Datasheet v1.6 §6.33 * (C+ Command Register) recommends that these and more be configured * *after* the [RT]xEnable bits in CpCmd are set. And on some hardware * it's been observed that the TxRingAddr is actually reset to garbage * when C+ mode Tx is enabled in CpCmd. */ cpw32_f(HiTxRingAddr, 0); cpw32_f(HiTxRingAddr + 4, 0); ring_dma = cp->ring_dma; cpw32_f(RxRingAddr, ring_dma & 0xffffffff); cpw32_f(RxRingAddr + 4, (ring_dma >> 16) >> 16); ring_dma += sizeof(struct cp_desc) * CP_RX_RING_SIZE; cpw32_f(TxRingAddr, ring_dma & 0xffffffff); cpw32_f(TxRingAddr + 4, (ring_dma >> 16) >> 16); /* * Strictly speaking, the datasheet says this should be enabled * *before* setting the descriptor addresses. But what, then, would * prevent it from doing DMA to random unconfigured addresses? * This variant appears to work fine. */ cpw8(Cmd, RxOn | TxOn); netdev_reset_queue(cp->dev); } static void cp_enable_irq(struct cp_private *cp) { cpw16_f(IntrMask, cp_intr_mask); } static void cp_init_hw (struct cp_private *cp) { struct net_device *dev = cp->dev; cp_reset_hw(cp); cpw8_f (Cfg9346, Cfg9346_Unlock); /* Restore our idea of the MAC address. */ cpw32_f (MAC0 + 0, le32_to_cpu (*(__le32 *) (dev->dev_addr + 0))); cpw32_f (MAC0 + 4, le32_to_cpu (*(__le32 *) (dev->dev_addr + 4))); cp_start_hw(cp); cpw8(TxThresh, 0x06); /* XXX convert magic num to a constant */ __cp_set_rx_mode(dev); cpw32_f (TxConfig, IFG | (TX_DMA_BURST << TxDMAShift)); cpw8(Config1, cpr8(Config1) | DriverLoaded | PMEnable); /* Disable Wake-on-LAN. Can be turned on with ETHTOOL_SWOL */ cpw8(Config3, PARMEnable); cp->wol_enabled = 0; cpw8(Config5, cpr8(Config5) & PMEStatus); cpw16(MultiIntr, 0); cpw8_f(Cfg9346, Cfg9346_Lock); } static int cp_refill_rx(struct cp_private *cp) { struct net_device *dev = cp->dev; unsigned i; for (i = 0; i < CP_RX_RING_SIZE; i++) { struct sk_buff *skb; dma_addr_t mapping; skb = netdev_alloc_skb_ip_align(dev, cp->rx_buf_sz); if (!skb) goto err_out; mapping = dma_map_single(&cp->pdev->dev, skb->data, cp->rx_buf_sz, DMA_FROM_DEVICE); if (dma_mapping_error(&cp->pdev->dev, mapping)) { kfree_skb(skb); goto err_out; } cp->rx_skb[i] = skb; cp->rx_ring[i].opts2 = 0; cp->rx_ring[i].addr = cpu_to_le64(mapping); if (i == (CP_RX_RING_SIZE - 1)) cp->rx_ring[i].opts1 = cpu_to_le32(DescOwn | RingEnd | cp->rx_buf_sz); else cp->rx_ring[i].opts1 = cpu_to_le32(DescOwn | cp->rx_buf_sz); } return 0; err_out: cp_clean_rings(cp); return -ENOMEM; } static void cp_init_rings_index (struct cp_private *cp) { cp->rx_tail = 0; cp->tx_head = cp->tx_tail = 0; } static int cp_init_rings (struct cp_private *cp) { memset(cp->tx_ring, 0, sizeof(struct cp_desc) * CP_TX_RING_SIZE); cp->tx_ring[CP_TX_RING_SIZE - 1].opts1 = cpu_to_le32(RingEnd); memset(cp->tx_opts, 0, sizeof(cp->tx_opts)); cp_init_rings_index(cp); return cp_refill_rx (cp); } static int cp_alloc_rings (struct cp_private *cp) { struct device *d = &cp->pdev->dev; void *mem; int rc; mem = dma_alloc_coherent(d, CP_RING_BYTES, &cp->ring_dma, GFP_KERNEL); if (!mem) return -ENOMEM; cp->rx_ring = mem; cp->tx_ring = &cp->rx_ring[CP_RX_RING_SIZE]; rc = cp_init_rings(cp); if (rc < 0) dma_free_coherent(d, CP_RING_BYTES, cp->rx_ring, cp->ring_dma); return rc; } static void cp_clean_rings (struct cp_private *cp) { struct cp_desc *desc; unsigned i; for (i = 0; i < CP_RX_RING_SIZE; i++) { if (cp->rx_skb[i]) { desc = cp->rx_ring + i; dma_unmap_single(&cp->pdev->dev,le64_to_cpu(desc->addr), cp->rx_buf_sz, DMA_FROM_DEVICE); dev_kfree_skb_any(cp->rx_skb[i]); } } for (i = 0; i < CP_TX_RING_SIZE; i++) { if (cp->tx_skb[i]) { struct sk_buff *skb = cp->tx_skb[i]; desc = cp->tx_ring + i; dma_unmap_single(&cp->pdev->dev,le64_to_cpu(desc->addr), le32_to_cpu(desc->opts1) & 0xffff, DMA_TO_DEVICE); if (le32_to_cpu(desc->opts1) & LastFrag) dev_kfree_skb_any(skb); cp->dev->stats.tx_dropped++; } } netdev_reset_queue(cp->dev); memset(cp->rx_ring, 0, sizeof(struct cp_desc) * CP_RX_RING_SIZE); memset(cp->tx_ring, 0, sizeof(struct cp_desc) * CP_TX_RING_SIZE); memset(cp->tx_opts, 0, sizeof(cp->tx_opts)); memset(cp->rx_skb, 0, sizeof(struct sk_buff *) * CP_RX_RING_SIZE); memset(cp->tx_skb, 0, sizeof(struct sk_buff *) * CP_TX_RING_SIZE); } static void cp_free_rings (struct cp_private *cp) { cp_clean_rings(cp); dma_free_coherent(&cp->pdev->dev, CP_RING_BYTES, cp->rx_ring, cp->ring_dma); cp->rx_ring = NULL; cp->tx_ring = NULL; } static int cp_open (struct net_device *dev) { struct cp_private *cp = netdev_priv(dev); const int irq = cp->pdev->irq; int rc; netif_dbg(cp, ifup, dev, "enabling interface\n"); rc = cp_alloc_rings(cp); if (rc) return rc; napi_enable(&cp->napi); cp_init_hw(cp); rc = request_irq(irq, cp_interrupt, IRQF_SHARED, dev->name, dev); if (rc) goto err_out_hw; cp_enable_irq(cp); netif_carrier_off(dev); mii_check_media(&cp->mii_if, netif_msg_link(cp), true); netif_start_queue(dev); return 0; err_out_hw: napi_disable(&cp->napi); cp_stop_hw(cp); cp_free_rings(cp); return rc; } static int cp_close (struct net_device *dev) { struct cp_private *cp = netdev_priv(dev); unsigned long flags; napi_disable(&cp->napi); netif_dbg(cp, ifdown, dev, "disabling interface\n"); spin_lock_irqsave(&cp->lock, flags); netif_stop_queue(dev); netif_carrier_off(dev); cp_stop_hw(cp); spin_unlock_irqrestore(&cp->lock, flags); free_irq(cp->pdev->irq, dev); cp_free_rings(cp); return 0; } static void cp_tx_timeout(struct net_device *dev, unsigned int txqueue) { struct cp_private *cp = netdev_priv(dev); unsigned long flags; int i; netdev_warn(dev, "Transmit timeout, status %2x %4x %4x %4x\n", cpr8(Cmd), cpr16(CpCmd), cpr16(IntrStatus), cpr16(IntrMask)); spin_lock_irqsave(&cp->lock, flags); netif_dbg(cp, tx_err, cp->dev, "TX ring head %d tail %d desc %x\n", cp->tx_head, cp->tx_tail, cpr16(TxDmaOkLowDesc)); for (i = 0; i < CP_TX_RING_SIZE; i++) { netif_dbg(cp, tx_err, cp->dev, "TX slot %d @%p: %08x (%08x) %08x %llx %p\n", i, &cp->tx_ring[i], le32_to_cpu(cp->tx_ring[i].opts1), cp->tx_opts[i], le32_to_cpu(cp->tx_ring[i].opts2), le64_to_cpu(cp->tx_ring[i].addr), cp->tx_skb[i]); } cp_stop_hw(cp); cp_clean_rings(cp); cp_init_rings(cp); cp_start_hw(cp); __cp_set_rx_mode(dev); cpw16_f(IntrMask, cp_norx_intr_mask); netif_wake_queue(dev); napi_schedule_irqoff(&cp->napi); spin_unlock_irqrestore(&cp->lock, flags); } static int cp_change_mtu(struct net_device *dev, int new_mtu) { struct cp_private *cp = netdev_priv(dev); /* if network interface not up, no need for complexity */ if (!netif_running(dev)) { dev->mtu = new_mtu; cp_set_rxbufsize(cp); /* set new rx buf size */ return 0; } /* network IS up, close it, reset MTU, and come up again. */ cp_close(dev); dev->mtu = new_mtu; cp_set_rxbufsize(cp); return cp_open(dev); } static const char mii_2_8139_map[8] = { BasicModeCtrl, BasicModeStatus, 0, 0, NWayAdvert, NWayLPAR, NWayExpansion, 0 }; static int mdio_read(struct net_device *dev, int phy_id, int location) { struct cp_private *cp = netdev_priv(dev); return location < 8 && mii_2_8139_map[location] ? readw(cp->regs + mii_2_8139_map[location]) : 0; } static void mdio_write(struct net_device *dev, int phy_id, int location, int value) { struct cp_private *cp = netdev_priv(dev); if (location == 0) { cpw8(Cfg9346, Cfg9346_Unlock); cpw16(BasicModeCtrl, value); cpw8(Cfg9346, Cfg9346_Lock); } else if (location < 8 && mii_2_8139_map[location]) cpw16(mii_2_8139_map[location], value); } /* Set the ethtool Wake-on-LAN settings */ static int netdev_set_wol (struct cp_private *cp, const struct ethtool_wolinfo *wol) { u8 options; options = cpr8 (Config3) & ~(LinkUp | MagicPacket); /* If WOL is being disabled, no need for complexity */ if (wol->wolopts) { if (wol->wolopts & WAKE_PHY) options |= LinkUp; if (wol->wolopts & WAKE_MAGIC) options |= MagicPacket; } cpw8 (Cfg9346, Cfg9346_Unlock); cpw8 (Config3, options); cpw8 (Cfg9346, Cfg9346_Lock); options = 0; /* Paranoia setting */ options = cpr8 (Config5) & ~(UWF | MWF | BWF); /* If WOL is being disabled, no need for complexity */ if (wol->wolopts) { if (wol->wolopts & WAKE_UCAST) options |= UWF; if (wol->wolopts & WAKE_BCAST) options |= BWF; if (wol->wolopts & WAKE_MCAST) options |= MWF; } cpw8 (Config5, options); cp->wol_enabled = (wol->wolopts) ? 1 : 0; return 0; } /* Get the ethtool Wake-on-LAN settings */ static void netdev_get_wol (struct cp_private *cp, struct ethtool_wolinfo *wol) { u8 options; wol->wolopts = 0; /* Start from scratch */ wol->supported = WAKE_PHY | WAKE_BCAST | WAKE_MAGIC | WAKE_MCAST | WAKE_UCAST; /* We don't need to go on if WOL is disabled */ if (!cp->wol_enabled) return; options = cpr8 (Config3); if (options & LinkUp) wol->wolopts |= WAKE_PHY; if (options & MagicPacket) wol->wolopts |= WAKE_MAGIC; options = 0; /* Paranoia setting */ options = cpr8 (Config5); if (options & UWF) wol->wolopts |= WAKE_UCAST; if (options & BWF) wol->wolopts |= WAKE_BCAST; if (options & MWF) wol->wolopts |= WAKE_MCAST; } static void cp_get_drvinfo (struct net_device *dev, struct ethtool_drvinfo *info) { struct cp_private *cp = 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(cp->pdev), sizeof(info->bus_info)); } static void cp_get_ringparam(struct net_device *dev, struct ethtool_ringparam *ring, struct kernel_ethtool_ringparam *kernel_ring, struct netlink_ext_ack *extack) { ring->rx_max_pending = CP_RX_RING_SIZE; ring->tx_max_pending = CP_TX_RING_SIZE; ring->rx_pending = CP_RX_RING_SIZE; ring->tx_pending = CP_TX_RING_SIZE; } static int cp_get_regs_len(struct net_device *dev) { return CP_REGS_SIZE; } static int cp_get_sset_count (struct net_device *dev, int sset) { switch (sset) { case ETH_SS_STATS: return CP_NUM_STATS; default: return -EOPNOTSUPP; } } static int cp_get_link_ksettings(struct net_device *dev, struct ethtool_link_ksettings *cmd) { struct cp_private *cp = netdev_priv(dev); unsigned long flags; spin_lock_irqsave(&cp->lock, flags); mii_ethtool_get_link_ksettings(&cp->mii_if, cmd); spin_unlock_irqrestore(&cp->lock, flags); return 0; } static int cp_set_link_ksettings(struct net_device *dev, const struct ethtool_link_ksettings *cmd) { struct cp_private *cp = netdev_priv(dev); int rc; unsigned long flags; spin_lock_irqsave(&cp->lock, flags); rc = mii_ethtool_set_link_ksettings(&cp->mii_if, cmd); spin_unlock_irqrestore(&cp->lock, flags); return rc; } static int cp_nway_reset(struct net_device *dev) { struct cp_private *cp = netdev_priv(dev); return mii_nway_restart(&cp->mii_if); } static u32 cp_get_msglevel(struct net_device *dev) { struct cp_private *cp = netdev_priv(dev); return cp->msg_enable; } static void cp_set_msglevel(struct net_device *dev, u32 value) { struct cp_private *cp = netdev_priv(dev); cp->msg_enable = value; } static int cp_set_features(struct net_device *dev, netdev_features_t features) { struct cp_private *cp = netdev_priv(dev); unsigned long flags; if (!((dev->features ^ features) & NETIF_F_RXCSUM)) return 0; spin_lock_irqsave(&cp->lock, flags); if (features & NETIF_F_RXCSUM) cp->cpcmd |= RxChkSum; else cp->cpcmd &= ~RxChkSum; if (features & NETIF_F_HW_VLAN_CTAG_RX) cp->cpcmd |= RxVlanOn; else cp->cpcmd &= ~RxVlanOn; cpw16_f(CpCmd, cp->cpcmd); spin_unlock_irqrestore(&cp->lock, flags); return 0; } static void cp_get_regs(struct net_device *dev, struct ethtool_regs *regs, void *p) { struct cp_private *cp = netdev_priv(dev); unsigned long flags; if (regs->len < CP_REGS_SIZE) return /* -EINVAL */; regs->version = CP_REGS_VER; spin_lock_irqsave(&cp->lock, flags); memcpy_fromio(p, cp->regs, CP_REGS_SIZE); spin_unlock_irqrestore(&cp->lock, flags); } static void cp_get_wol (struct net_device *dev, struct ethtool_wolinfo *wol) { struct cp_private *cp = netdev_priv(dev); unsigned long flags; spin_lock_irqsave (&cp->lock, flags); netdev_get_wol (cp, wol); spin_unlock_irqrestore (&cp->lock, flags); } static int cp_set_wol (struct net_device *dev, struct ethtool_wolinfo *wol) { struct cp_private *cp = netdev_priv(dev); unsigned long flags; int rc; spin_lock_irqsave (&cp->lock, flags); rc = netdev_set_wol (cp, wol); spin_unlock_irqrestore (&cp->lock, flags); return rc; } static void cp_get_strings (struct net_device *dev, u32 stringset, u8 *buf) { switch (stringset) { case ETH_SS_STATS: memcpy(buf, &ethtool_stats_keys, sizeof(ethtool_stats_keys)); break; default: BUG(); break; } } static void cp_get_ethtool_stats (struct net_device *dev, struct ethtool_stats *estats, u64 *tmp_stats) { struct cp_private *cp = netdev_priv(dev); struct cp_dma_stats *nic_stats; dma_addr_t dma; int i; nic_stats = dma_alloc_coherent(&cp->pdev->dev, sizeof(*nic_stats), &dma, GFP_KERNEL); if (!nic_stats) return; /* begin NIC statistics dump */ cpw32(StatsAddr + 4, (u64)dma >> 32); cpw32(StatsAddr, ((u64)dma & DMA_BIT_MASK(32)) | DumpStats); cpr32(StatsAddr); for (i = 0; i < 1000; i++) { if ((cpr32(StatsAddr) & DumpStats) == 0) break; udelay(10); } cpw32(StatsAddr, 0); cpw32(StatsAddr + 4, 0); cpr32(StatsAddr); i = 0; tmp_stats[i++] = le64_to_cpu(nic_stats->tx_ok); tmp_stats[i++] = le64_to_cpu(nic_stats->rx_ok); tmp_stats[i++] = le64_to_cpu(nic_stats->tx_err); tmp_stats[i++] = le32_to_cpu(nic_stats->rx_err); tmp_stats[i++] = le16_to_cpu(nic_stats->rx_fifo); tmp_stats[i++] = le16_to_cpu(nic_stats->frame_align); tmp_stats[i++] = le32_to_cpu(nic_stats->tx_ok_1col); tmp_stats[i++] = le32_to_cpu(nic_stats->tx_ok_mcol); tmp_stats[i++] = le64_to_cpu(nic_stats->rx_ok_phys); tmp_stats[i++] = le64_to_cpu(nic_stats->rx_ok_bcast); tmp_stats[i++] = le32_to_cpu(nic_stats->rx_ok_mcast); tmp_stats[i++] = le16_to_cpu(nic_stats->tx_abort); tmp_stats[i++] = le16_to_cpu(nic_stats->tx_underrun); tmp_stats[i++] = cp->cp_stats.rx_frags; BUG_ON(i != CP_NUM_STATS); dma_free_coherent(&cp->pdev->dev, sizeof(*nic_stats), nic_stats, dma); } static const struct ethtool_ops cp_ethtool_ops = { .get_drvinfo = cp_get_drvinfo, .get_regs_len = cp_get_regs_len, .get_sset_count = cp_get_sset_count, .nway_reset = cp_nway_reset, .get_link = ethtool_op_get_link, .get_msglevel = cp_get_msglevel, .set_msglevel = cp_set_msglevel, .get_regs = cp_get_regs, .get_wol = cp_get_wol, .set_wol = cp_set_wol, .get_strings = cp_get_strings, .get_ethtool_stats = cp_get_ethtool_stats, .get_eeprom_len = cp_get_eeprom_len, .get_eeprom = cp_get_eeprom, .set_eeprom = cp_set_eeprom, .get_ringparam = cp_get_ringparam, .get_link_ksettings = cp_get_link_ksettings, .set_link_ksettings = cp_set_link_ksettings, }; static int cp_ioctl (struct net_device *dev, struct ifreq *rq, int cmd) { struct cp_private *cp = netdev_priv(dev); int rc; unsigned long flags; if (!netif_running(dev)) return -EINVAL; spin_lock_irqsave(&cp->lock, flags); rc = generic_mii_ioctl(&cp->mii_if, if_mii(rq), cmd, NULL); spin_unlock_irqrestore(&cp->lock, flags); return rc; } static int cp_set_mac_address(struct net_device *dev, void *p) { struct cp_private *cp = netdev_priv(dev); struct sockaddr *addr = p; if (!is_valid_ether_addr(addr->sa_data)) return -EADDRNOTAVAIL; eth_hw_addr_set(dev, addr->sa_data); spin_lock_irq(&cp->lock); cpw8_f(Cfg9346, Cfg9346_Unlock); cpw32_f(MAC0 + 0, le32_to_cpu (*(__le32 *) (dev->dev_addr + 0))); cpw32_f(MAC0 + 4, le32_to_cpu (*(__le32 *) (dev->dev_addr + 4))); cpw8_f(Cfg9346, Cfg9346_Lock); spin_unlock_irq(&cp->lock); return 0; } /* Serial EEPROM section. */ /* EEPROM_Ctrl bits. */ #define EE_SHIFT_CLK 0x04 /* EEPROM shift clock. */ #define EE_CS 0x08 /* EEPROM chip select. */ #define EE_DATA_WRITE 0x02 /* EEPROM chip data in. */ #define EE_WRITE_0 0x00 #define EE_WRITE_1 0x02 #define EE_DATA_READ 0x01 /* EEPROM chip data out. */ #define EE_ENB (0x80 | EE_CS) /* Delay between EEPROM clock transitions. No extra delay is needed with 33Mhz PCI, but 66Mhz may change this. */ #define eeprom_delay() readb(ee_addr) /* The EEPROM commands include the alway-set leading bit. */ #define EE_EXTEND_CMD (4) #define EE_WRITE_CMD (5) #define EE_READ_CMD (6) #define EE_ERASE_CMD (7) #define EE_EWDS_ADDR (0) #define EE_WRAL_ADDR (1) #define EE_ERAL_ADDR (2) #define EE_EWEN_ADDR (3) #define CP_EEPROM_MAGIC PCI_DEVICE_ID_REALTEK_8139 static void eeprom_cmd_start(void __iomem *ee_addr) { writeb (EE_ENB & ~EE_CS, ee_addr); writeb (EE_ENB, ee_addr); eeprom_delay (); } static void eeprom_cmd(void __iomem *ee_addr, int cmd, int cmd_len) { int i; /* Shift the command bits out. */ for (i = cmd_len - 1; i >= 0; i--) { int dataval = (cmd & (1 << i)) ? EE_DATA_WRITE : 0; writeb (EE_ENB | dataval, ee_addr); eeprom_delay (); writeb (EE_ENB | dataval | EE_SHIFT_CLK, ee_addr); eeprom_delay (); } writeb (EE_ENB, ee_addr); eeprom_delay (); } static void eeprom_cmd_end(void __iomem *ee_addr) { writeb(0, ee_addr); eeprom_delay (); } static void eeprom_extend_cmd(void __iomem *ee_addr, int extend_cmd, int addr_len) { int cmd = (EE_EXTEND_CMD << addr_len) | (extend_cmd << (addr_len - 2)); eeprom_cmd_start(ee_addr); eeprom_cmd(ee_addr, cmd, 3 + addr_len); eeprom_cmd_end(ee_addr); } static u16 read_eeprom (void __iomem *ioaddr, int location, int addr_len) { int i; u16 retval = 0; void __iomem *ee_addr = ioaddr + Cfg9346; int read_cmd = location | (EE_READ_CMD << addr_len); eeprom_cmd_start(ee_addr); eeprom_cmd(ee_addr, read_cmd, 3 + addr_len); for (i = 16; i > 0; i--) { writeb (EE_ENB | EE_SHIFT_CLK, ee_addr); eeprom_delay (); retval = (retval << 1) | ((readb (ee_addr) & EE_DATA_READ) ? 1 : 0); writeb (EE_ENB, ee_addr); eeprom_delay (); } eeprom_cmd_end(ee_addr); return retval; } static void write_eeprom(void __iomem *ioaddr, int location, u16 val, int addr_len) { int i; void __iomem *ee_addr = ioaddr + Cfg9346; int write_cmd = location | (EE_WRITE_CMD << addr_len); eeprom_extend_cmd(ee_addr, EE_EWEN_ADDR, addr_len); eeprom_cmd_start(ee_addr); eeprom_cmd(ee_addr, write_cmd, 3 + addr_len); eeprom_cmd(ee_addr, val, 16); eeprom_cmd_end(ee_addr); eeprom_cmd_start(ee_addr); for (i = 0; i < 20000; i++) if (readb(ee_addr) & EE_DATA_READ) break; eeprom_cmd_end(ee_addr); eeprom_extend_cmd(ee_addr, EE_EWDS_ADDR, addr_len); } static int cp_get_eeprom_len(struct net_device *dev) { struct cp_private *cp = netdev_priv(dev); int size; spin_lock_irq(&cp->lock); size = read_eeprom(cp->regs, 0, 8) == 0x8129 ? 256 : 128; spin_unlock_irq(&cp->lock); return size; } static int cp_get_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom, u8 *data) { struct cp_private *cp = netdev_priv(dev); unsigned int addr_len; u16 val; u32 offset = eeprom->offset >> 1; u32 len = eeprom->len; u32 i = 0; eeprom->magic = CP_EEPROM_MAGIC; spin_lock_irq(&cp->lock); addr_len = read_eeprom(cp->regs, 0, 8) == 0x8129 ? 8 : 6; if (eeprom->offset & 1) { val = read_eeprom(cp->regs, offset, addr_len); data[i++] = (u8)(val >> 8); offset++; } while (i < len - 1) { val = read_eeprom(cp->regs, offset, addr_len); data[i++] = (u8)val; data[i++] = (u8)(val >> 8); offset++; } if (i < len) { val = read_eeprom(cp->regs, offset, addr_len); data[i] = (u8)val; } spin_unlock_irq(&cp->lock); return 0; } static int cp_set_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom, u8 *data) { struct cp_private *cp = netdev_priv(dev); unsigned int addr_len; u16 val; u32 offset = eeprom->offset >> 1; u32 len = eeprom->len; u32 i = 0; if (eeprom->magic != CP_EEPROM_MAGIC) return -EINVAL; spin_lock_irq(&cp->lock); addr_len = read_eeprom(cp->regs, 0, 8) == 0x8129 ? 8 : 6; if (eeprom->offset & 1) { val = read_eeprom(cp->regs, offset, addr_len) & 0xff; val |= (u16)data[i++] << 8; write_eeprom(cp->regs, offset, val, addr_len); offset++; } while (i < len - 1) { val = (u16)data[i++]; val |= (u16)data[i++] << 8; write_eeprom(cp->regs, offset, val, addr_len); offset++; } if (i < len) { val = read_eeprom(cp->regs, offset, addr_len) & 0xff00; val |= (u16)data[i]; write_eeprom(cp->regs, offset, val, addr_len); } spin_unlock_irq(&cp->lock); return 0; } /* Put the board into D3cold state and wait for WakeUp signal */ static void cp_set_d3_state (struct cp_private *cp) { pci_enable_wake(cp->pdev, PCI_D0, 1); /* Enable PME# generation */ pci_set_power_state (cp->pdev, PCI_D3hot); } static netdev_features_t cp_features_check(struct sk_buff *skb, struct net_device *dev, netdev_features_t features) { if (skb_shinfo(skb)->gso_size > MSSMask) features &= ~NETIF_F_TSO; return vlan_features_check(skb, features); } static const struct net_device_ops cp_netdev_ops = { .ndo_open = cp_open, .ndo_stop = cp_close, .ndo_validate_addr = eth_validate_addr, .ndo_set_mac_address = cp_set_mac_address, .ndo_set_rx_mode = cp_set_rx_mode, .ndo_get_stats = cp_get_stats, .ndo_eth_ioctl = cp_ioctl, .ndo_start_xmit = cp_start_xmit, .ndo_tx_timeout = cp_tx_timeout, .ndo_set_features = cp_set_features, .ndo_change_mtu = cp_change_mtu, .ndo_features_check = cp_features_check, #ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = cp_poll_controller, #endif }; static int cp_init_one (struct pci_dev *pdev, const struct pci_device_id *ent) { struct net_device *dev; struct cp_private *cp; int rc; void __iomem *regs; resource_size_t pciaddr; unsigned int addr_len, i, pci_using_dac; __le16 addr[ETH_ALEN / 2]; pr_info_once("%s", version); if (pdev->vendor == PCI_VENDOR_ID_REALTEK && pdev->device == PCI_DEVICE_ID_REALTEK_8139 && pdev->revision < 0x20) { dev_info(&pdev->dev, "This (id %04x:%04x rev %02x) is not an 8139C+ compatible chip, use 8139too\n", pdev->vendor, pdev->device, pdev->revision); return -ENODEV; } dev = alloc_etherdev(sizeof(struct cp_private)); if (!dev) return -ENOMEM; SET_NETDEV_DEV(dev, &pdev->dev); cp = netdev_priv(dev); cp->pdev = pdev; cp->dev = dev; cp->msg_enable = (debug < 0 ? CP_DEF_MSG_ENABLE : debug); spin_lock_init (&cp->lock); cp->mii_if.dev = dev; cp->mii_if.mdio_read = mdio_read; cp->mii_if.mdio_write = mdio_write; cp->mii_if.phy_id = CP_INTERNAL_PHY; cp->mii_if.phy_id_mask = 0x1f; cp->mii_if.reg_num_mask = 0x1f; cp_set_rxbufsize(cp); rc = pci_enable_device(pdev); if (rc) goto err_out_free; rc = pci_set_mwi(pdev); if (rc) goto err_out_disable; rc = pci_request_regions(pdev, DRV_NAME); if (rc) goto err_out_mwi; pciaddr = pci_resource_start(pdev, 1); if (!pciaddr) { rc = -EIO; dev_err(&pdev->dev, "no MMIO resource\n"); goto err_out_res; } if (pci_resource_len(pdev, 1) < CP_REGS_SIZE) { rc = -EIO; dev_err(&pdev->dev, "MMIO resource (%llx) too small\n", (unsigned long long)pci_resource_len(pdev, 1)); goto err_out_res; } /* Configure DMA attributes. */ if ((sizeof(dma_addr_t) > 4) && !dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64))) { pci_using_dac = 1; } else { pci_using_dac = 0; rc = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)); if (rc) { dev_err(&pdev->dev, "No usable DMA configuration, aborting\n"); goto err_out_res; } } cp->cpcmd = (pci_using_dac ? PCIDAC : 0) | PCIMulRW | RxChkSum | CpRxOn | CpTxOn; dev->features |= NETIF_F_RXCSUM; dev->hw_features |= NETIF_F_RXCSUM; regs = ioremap(pciaddr, CP_REGS_SIZE); if (!regs) { rc = -EIO; dev_err(&pdev->dev, "Cannot map PCI MMIO (%Lx@%Lx)\n", (unsigned long long)pci_resource_len(pdev, 1), (unsigned long long)pciaddr); goto err_out_res; } cp->regs = regs; cp_stop_hw(cp); /* read MAC address from EEPROM */ addr_len = read_eeprom (regs, 0, 8) == 0x8129 ? 8 : 6; for (i = 0; i < 3; i++) addr[i] = cpu_to_le16(read_eeprom (regs, i + 7, addr_len)); eth_hw_addr_set(dev, (u8 *)addr); dev->netdev_ops = &cp_netdev_ops; netif_napi_add_weight(dev, &cp->napi, cp_rx_poll, 16); dev->ethtool_ops = &cp_ethtool_ops; dev->watchdog_timeo = TX_TIMEOUT; dev->features |= NETIF_F_SG | NETIF_F_IP_CSUM | NETIF_F_TSO | NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX; if (pci_using_dac) dev->features |= NETIF_F_HIGHDMA; dev->hw_features |= NETIF_F_SG | NETIF_F_IP_CSUM | NETIF_F_TSO | NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX; dev->vlan_features = NETIF_F_SG | NETIF_F_IP_CSUM | NETIF_F_TSO | NETIF_F_HIGHDMA; /* MTU range: 60 - 4096 */ dev->min_mtu = CP_MIN_MTU; dev->max_mtu = CP_MAX_MTU; rc = register_netdev(dev); if (rc) goto err_out_iomap; netdev_info(dev, "RTL-8139C+ at 0x%p, %pM, IRQ %d\n", regs, dev->dev_addr, pdev->irq); pci_set_drvdata(pdev, dev); /* enable busmastering and memory-write-invalidate */ pci_set_master(pdev); if (cp->wol_enabled) cp_set_d3_state (cp); return 0; err_out_iomap: iounmap(regs); err_out_res: pci_release_regions(pdev); err_out_mwi: pci_clear_mwi(pdev); err_out_disable: pci_disable_device(pdev); err_out_free: free_netdev(dev); return rc; } static void cp_remove_one (struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata(pdev); struct cp_private *cp = netdev_priv(dev); unregister_netdev(dev); iounmap(cp->regs); if (cp->wol_enabled) pci_set_power_state (pdev, PCI_D0); pci_release_regions(pdev); pci_clear_mwi(pdev); pci_disable_device(pdev); free_netdev(dev); } static int __maybe_unused cp_suspend(struct device *device) { struct net_device *dev = dev_get_drvdata(device); struct cp_private *cp = netdev_priv(dev); unsigned long flags; if (!netif_running(dev)) return 0; netif_device_detach (dev); netif_stop_queue (dev); spin_lock_irqsave (&cp->lock, flags); /* Disable Rx and Tx */ cpw16 (IntrMask, 0); cpw8 (Cmd, cpr8 (Cmd) & (~RxOn | ~TxOn)); spin_unlock_irqrestore (&cp->lock, flags); device_set_wakeup_enable(device, cp->wol_enabled); return 0; } static int __maybe_unused cp_resume(struct device *device) { struct net_device *dev = dev_get_drvdata(device); struct cp_private *cp = netdev_priv(dev); unsigned long flags; if (!netif_running(dev)) return 0; netif_device_attach (dev); /* FIXME: sh*t may happen if the Rx ring buffer is depleted */ cp_init_rings_index (cp); cp_init_hw (cp); cp_enable_irq(cp); netif_start_queue (dev); spin_lock_irqsave (&cp->lock, flags); mii_check_media(&cp->mii_if, netif_msg_link(cp), false); spin_unlock_irqrestore (&cp->lock, flags); return 0; } static const struct pci_device_id cp_pci_tbl[] = { { PCI_DEVICE(PCI_VENDOR_ID_REALTEK, PCI_DEVICE_ID_REALTEK_8139), }, { PCI_DEVICE(PCI_VENDOR_ID_TTTECH, PCI_DEVICE_ID_TTTECH_MC322), }, { }, }; MODULE_DEVICE_TABLE(pci, cp_pci_tbl); static SIMPLE_DEV_PM_OPS(cp_pm_ops, cp_suspend, cp_resume); static struct pci_driver cp_driver = { .name = DRV_NAME, .id_table = cp_pci_tbl, .probe = cp_init_one, .remove = cp_remove_one, .driver.pm = &cp_pm_ops, }; module_pci_driver(cp_driver);
linux-master
drivers/net/ethernet/realtek/8139cp.c
/* 8139too.c: A RealTek RTL-8139 Fast Ethernet driver for Linux. Maintained by Jeff Garzik <[email protected]> Copyright 2000-2002 Jeff Garzik Much code comes from Donald Becker's rtl8139.c driver, versions 1.13 and older. This driver was originally based on rtl8139.c version 1.07. Header of rtl8139.c version 1.13: -----<snip>----- Written 1997-2001 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 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. This driver is for boards based on the RTL8129 and RTL8139 PCI ethernet chips. The author may be reached as [email protected], or C/O Scyld Computing Corporation 410 Severn Ave., Suite 210 Annapolis MD 21403 Support and updates available at http://www.scyld.com/network/rtl8139.html Twister-tuning table provided by Kinston <[email protected]>. -----<snip>----- This software may be used and distributed according to the terms of the GNU General Public License, incorporated herein by reference. Contributors: Donald Becker - he wrote the original driver, kudos to him! (but please don't e-mail him for support, this isn't his driver) Tigran Aivazian - bug fixes, skbuff free cleanup Martin Mares - suggestions for PCI cleanup David S. Miller - PCI DMA and softnet updates Ernst Gill - fixes ported from BSD driver Daniel Kobras - identified specific locations of posted MMIO write bugginess Gerard Sharp - bug fix, testing and feedback David Ford - Rx ring wrap fix Dan DeMaggio - swapped RTL8139 cards with me, and allowed me to find and fix a crucial bug on older chipsets. Donald Becker/Chris Butterworth/Marcus Westergren - Noticed various Rx packet size-related buglets. Santiago Garcia Mantinan - testing and feedback Jens David - 2.2.x kernel backports Martin Dennett - incredibly helpful insight on undocumented features of the 8139 chips Jean-Jacques Michel - bug fix Tobias Ringström - Rx interrupt status checking suggestion Andrew Morton - Clear blocked signals, avoid buffer overrun setting current->comm. Kalle Olavi Niemitalo - Wake-on-LAN ioctls Robert Kuebel - Save kernel thread from dying on any signal. Submitting bug reports: "rtl8139-diag -mmmaaavvveefN" output enable RTL8139_DEBUG below, and look at 'dmesg' or kernel log */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #define DRV_NAME "8139too" #define DRV_VERSION "0.9.28" #include <linux/module.h> #include <linux/kernel.h> #include <linux/compiler.h> #include <linux/pci.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/rtnetlink.h> #include <linux/delay.h> #include <linux/ethtool.h> #include <linux/mii.h> #include <linux/completion.h> #include <linux/crc32.h> #include <linux/io.h> #include <linux/uaccess.h> #include <linux/gfp.h> #include <linux/if_vlan.h> #include <asm/irq.h> #define RTL8139_DRIVER_NAME DRV_NAME " Fast Ethernet driver " DRV_VERSION /* Default Message level */ #define RTL8139_DEF_MSG_ENABLE (NETIF_MSG_DRV | \ NETIF_MSG_PROBE | \ NETIF_MSG_LINK) /* define to 1, 2 or 3 to enable copious debugging info */ #define RTL8139_DEBUG 0 /* define to 1 to disable lightweight runtime debugging checks */ #undef RTL8139_NDEBUG #ifdef RTL8139_NDEBUG # define assert(expr) do {} while (0) #else # define assert(expr) \ if (unlikely(!(expr))) { \ pr_err("Assertion failed! %s,%s,%s,line=%d\n", \ #expr, __FILE__, __func__, __LINE__); \ } #endif /* A few user-configurable values. */ /* media options */ #define MAX_UNITS 8 static int media[MAX_UNITS] = {-1, -1, -1, -1, -1, -1, -1, -1}; static int full_duplex[MAX_UNITS] = {-1, -1, -1, -1, -1, -1, -1, -1}; /* Whether to use MMIO or PIO. Default to MMIO. */ #ifdef CONFIG_8139TOO_PIO static bool use_io = true; #else static bool use_io = false; #endif /* Maximum number of multicast addresses to filter (vs. Rx-all-multicast). The RTL chips use a 64 element hash table based on the Ethernet CRC. */ static int multicast_filter_limit = 32; /* bitmapped message enable number */ static int debug = -1; /* * Receive ring size * Warning: 64K ring has hardware issues and may lock up. */ #if defined(CONFIG_SH_DREAMCAST) #define RX_BUF_IDX 0 /* 8K ring */ #else #define RX_BUF_IDX 2 /* 32K ring */ #endif #define RX_BUF_LEN (8192 << RX_BUF_IDX) #define RX_BUF_PAD 16 #define RX_BUF_WRAP_PAD 2048 /* spare padding to handle lack of packet wrap */ #if RX_BUF_LEN == 65536 #define RX_BUF_TOT_LEN RX_BUF_LEN #else #define RX_BUF_TOT_LEN (RX_BUF_LEN + RX_BUF_PAD + RX_BUF_WRAP_PAD) #endif /* Number of Tx descriptor registers. */ #define NUM_TX_DESC 4 /* max supported ethernet frame size -- must be at least (dev->mtu+18+4).*/ #define MAX_ETH_FRAME_SIZE 1792 /* max supported payload size */ #define MAX_ETH_DATA_SIZE (MAX_ETH_FRAME_SIZE - VLAN_ETH_HLEN - ETH_FCS_LEN) /* Size of the Tx bounce buffers -- must be at least (dev->mtu+18+4). */ #define TX_BUF_SIZE MAX_ETH_FRAME_SIZE #define TX_BUF_TOT_LEN (TX_BUF_SIZE * NUM_TX_DESC) /* PCI Tuning Parameters Threshold is bytes transferred to chip before transmission starts. */ #define TX_FIFO_THRESH 256 /* In bytes, rounded down to 32 byte units. */ /* The following settings are log_2(bytes)-4: 0 == 16 bytes .. 6==1024, 7==end of packet. */ #define RX_FIFO_THRESH 7 /* Rx buffer level before first PCI xfer. */ #define RX_DMA_BURST 7 /* Maximum PCI burst, '6' is 1024 */ #define TX_DMA_BURST 6 /* Maximum PCI burst, '6' is 1024 */ #define TX_RETRY 8 /* 0-15. retries = 16 + (TX_RETRY * 16) */ /* Operational parameters that usually are not changed. */ /* Time in jiffies before concluding the transmitter is hung. */ #define TX_TIMEOUT (6*HZ) enum { HAS_MII_XCVR = 0x010000, HAS_CHIP_XCVR = 0x020000, HAS_LNK_CHNG = 0x040000, }; #define RTL_NUM_STATS 4 /* number of ETHTOOL_GSTATS u64's */ #define RTL_REGS_VER 1 /* version of reg. data in ETHTOOL_GREGS */ #define RTL_MIN_IO_SIZE 0x80 #define RTL8139B_IO_SIZE 256 #define RTL8129_CAPS HAS_MII_XCVR #define RTL8139_CAPS (HAS_CHIP_XCVR|HAS_LNK_CHNG) typedef enum { RTL8139 = 0, RTL8129, } board_t; /* indexed by board_t, above */ static const struct { const char *name; u32 hw_flags; } board_info[] = { { "RealTek RTL8139", RTL8139_CAPS }, { "RealTek RTL8129", RTL8129_CAPS }, }; static const struct pci_device_id rtl8139_pci_tbl[] = { {0x10ec, 0x8139, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 }, {0x10ec, 0x8138, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 }, {0x1113, 0x1211, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 }, {0x1500, 0x1360, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 }, {0x4033, 0x1360, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 }, {0x1186, 0x1300, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 }, {0x1186, 0x1340, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 }, {0x13d1, 0xab06, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 }, {0x1259, 0xa117, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 }, {0x1259, 0xa11e, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 }, {0x14ea, 0xab06, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 }, {0x14ea, 0xab07, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 }, {0x11db, 0x1234, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 }, {0x1432, 0x9130, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 }, {0x02ac, 0x1012, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 }, {0x018a, 0x0106, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 }, {0x126c, 0x1211, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 }, {0x1743, 0x8139, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 }, {0x021b, 0x8139, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 }, {0x16ec, 0xab06, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 }, #ifdef CONFIG_SH_SECUREEDGE5410 /* Bogus 8139 silicon reports 8129 without external PROM :-( */ {0x10ec, 0x8129, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 }, #endif #ifdef CONFIG_8139TOO_8129 {0x10ec, 0x8129, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8129 }, #endif /* some crazy cards report invalid vendor ids like * 0x0001 here. The other ids are valid and constant, * so we simply don't match on the main vendor id. */ {PCI_ANY_ID, 0x8139, 0x10ec, 0x8139, 0, 0, RTL8139 }, {PCI_ANY_ID, 0x8139, 0x1186, 0x1300, 0, 0, RTL8139 }, {PCI_ANY_ID, 0x8139, 0x13d1, 0xab06, 0, 0, RTL8139 }, {0,} }; MODULE_DEVICE_TABLE (pci, rtl8139_pci_tbl); static struct { const char str[ETH_GSTRING_LEN]; } ethtool_stats_keys[] = { { "early_rx" }, { "tx_buf_mapped" }, { "tx_timeouts" }, { "rx_lost_in_ring" }, }; /* The rest of these values should never change. */ /* Symbolic offsets to registers. */ enum RTL8139_registers { MAC0 = 0, /* Ethernet hardware address. */ MAR0 = 8, /* Multicast filter. */ TxStatus0 = 0x10, /* Transmit status (Four 32bit registers). */ TxAddr0 = 0x20, /* Tx descriptors (also four 32bit). */ RxBuf = 0x30, ChipCmd = 0x37, RxBufPtr = 0x38, RxBufAddr = 0x3A, IntrMask = 0x3C, IntrStatus = 0x3E, TxConfig = 0x40, RxConfig = 0x44, Timer = 0x48, /* A general-purpose counter. */ RxMissed = 0x4C, /* 24 bits valid, write clears. */ Cfg9346 = 0x50, Config0 = 0x51, Config1 = 0x52, TimerInt = 0x54, MediaStatus = 0x58, Config3 = 0x59, Config4 = 0x5A, /* absent on RTL-8139A */ HltClk = 0x5B, MultiIntr = 0x5C, TxSummary = 0x60, BasicModeCtrl = 0x62, BasicModeStatus = 0x64, NWayAdvert = 0x66, NWayLPAR = 0x68, NWayExpansion = 0x6A, /* Undocumented registers, but required for proper operation. */ FIFOTMS = 0x70, /* FIFO Control and test. */ CSCR = 0x74, /* Chip Status and Configuration Register. */ PARA78 = 0x78, FlashReg = 0xD4, /* Communication with Flash ROM, four bytes. */ PARA7c = 0x7c, /* Magic transceiver parameter register. */ Config5 = 0xD8, /* absent on RTL-8139A */ }; enum ClearBitMasks { MultiIntrClear = 0xF000, ChipCmdClear = 0xE2, Config1Clear = (1<<7)|(1<<6)|(1<<3)|(1<<2)|(1<<1), }; enum ChipCmdBits { CmdReset = 0x10, CmdRxEnb = 0x08, CmdTxEnb = 0x04, RxBufEmpty = 0x01, }; /* Interrupt register bits, using my own meaningful names. */ enum IntrStatusBits { PCIErr = 0x8000, PCSTimeout = 0x4000, RxFIFOOver = 0x40, RxUnderrun = 0x20, RxOverflow = 0x10, TxErr = 0x08, TxOK = 0x04, RxErr = 0x02, RxOK = 0x01, RxAckBits = RxFIFOOver | RxOverflow | RxOK, }; enum TxStatusBits { TxHostOwns = 0x2000, TxUnderrun = 0x4000, TxStatOK = 0x8000, TxOutOfWindow = 0x20000000, TxAborted = 0x40000000, TxCarrierLost = 0x80000000, }; enum RxStatusBits { RxMulticast = 0x8000, RxPhysical = 0x4000, RxBroadcast = 0x2000, RxBadSymbol = 0x0020, RxRunt = 0x0010, RxTooLong = 0x0008, RxCRCErr = 0x0004, RxBadAlign = 0x0002, RxStatusOK = 0x0001, }; /* Bits in RxConfig. */ enum rx_mode_bits { AcceptErr = 0x20, AcceptRunt = 0x10, AcceptBroadcast = 0x08, AcceptMulticast = 0x04, AcceptMyPhys = 0x02, AcceptAllPhys = 0x01, }; /* Bits in TxConfig. */ enum tx_config_bits { /* Interframe Gap Time. Only TxIFG96 doesn't violate IEEE 802.3 */ TxIFGShift = 24, TxIFG84 = (0 << TxIFGShift), /* 8.4us / 840ns (10 / 100Mbps) */ TxIFG88 = (1 << TxIFGShift), /* 8.8us / 880ns (10 / 100Mbps) */ TxIFG92 = (2 << TxIFGShift), /* 9.2us / 920ns (10 / 100Mbps) */ TxIFG96 = (3 << TxIFGShift), /* 9.6us / 960ns (10 / 100Mbps) */ TxLoopBack = (1 << 18) | (1 << 17), /* enable loopback test mode */ TxCRC = (1 << 16), /* DISABLE Tx pkt CRC append */ TxClearAbt = (1 << 0), /* Clear abort (WO) */ TxDMAShift = 8, /* DMA burst value (0-7) is shifted X many bits */ TxRetryShift = 4, /* TXRR value (0-15) is shifted X many bits */ TxVersionMask = 0x7C800000, /* mask out version bits 30-26, 23 */ }; /* Bits in Config1 */ enum Config1Bits { Cfg1_PM_Enable = 0x01, Cfg1_VPD_Enable = 0x02, Cfg1_PIO = 0x04, Cfg1_MMIO = 0x08, LWAKE = 0x10, /* not on 8139, 8139A */ Cfg1_Driver_Load = 0x20, Cfg1_LED0 = 0x40, Cfg1_LED1 = 0x80, SLEEP = (1 << 1), /* only on 8139, 8139A */ PWRDN = (1 << 0), /* only on 8139, 8139A */ }; /* Bits in Config3 */ enum Config3Bits { Cfg3_FBtBEn = (1 << 0), /* 1 = Fast Back to Back */ Cfg3_FuncRegEn = (1 << 1), /* 1 = enable CardBus Function registers */ Cfg3_CLKRUN_En = (1 << 2), /* 1 = enable CLKRUN */ Cfg3_CardB_En = (1 << 3), /* 1 = enable CardBus registers */ Cfg3_LinkUp = (1 << 4), /* 1 = wake up on link up */ Cfg3_Magic = (1 << 5), /* 1 = wake up on Magic Packet (tm) */ Cfg3_PARM_En = (1 << 6), /* 0 = software can set twister parameters */ Cfg3_GNTSel = (1 << 7), /* 1 = delay 1 clock from PCI GNT signal */ }; /* Bits in Config4 */ enum Config4Bits { LWPTN = (1 << 2), /* not on 8139, 8139A */ }; /* Bits in Config5 */ enum Config5Bits { Cfg5_PME_STS = (1 << 0), /* 1 = PCI reset resets PME_Status */ Cfg5_LANWake = (1 << 1), /* 1 = enable LANWake signal */ Cfg5_LDPS = (1 << 2), /* 0 = save power when link is down */ Cfg5_FIFOAddrPtr= (1 << 3), /* Realtek internal SRAM testing */ Cfg5_UWF = (1 << 4), /* 1 = accept unicast wakeup frame */ Cfg5_MWF = (1 << 5), /* 1 = accept multicast wakeup frame */ Cfg5_BWF = (1 << 6), /* 1 = accept broadcast wakeup frame */ }; enum RxConfigBits { /* rx fifo threshold */ RxCfgFIFOShift = 13, RxCfgFIFONone = (7 << RxCfgFIFOShift), /* Max DMA burst */ RxCfgDMAShift = 8, RxCfgDMAUnlimited = (7 << RxCfgDMAShift), /* rx ring buffer length */ RxCfgRcv8K = 0, RxCfgRcv16K = (1 << 11), RxCfgRcv32K = (1 << 12), RxCfgRcv64K = (1 << 11) | (1 << 12), /* Disable packet wrap at end of Rx buffer. (not possible with 64k) */ RxNoWrap = (1 << 7), }; /* Twister tuning parameters from RealTek. Completely undocumented, but required to tune bad links on some boards. */ enum CSCRBits { CSCR_LinkOKBit = 0x0400, CSCR_LinkChangeBit = 0x0800, CSCR_LinkStatusBits = 0x0f000, CSCR_LinkDownOffCmd = 0x003c0, CSCR_LinkDownCmd = 0x0f3c0, }; enum Cfg9346Bits { Cfg9346_Lock = 0x00, Cfg9346_Unlock = 0xC0, }; typedef enum { CH_8139 = 0, CH_8139_K, CH_8139A, CH_8139A_G, CH_8139B, CH_8130, CH_8139C, CH_8100, CH_8100B_8139D, CH_8101, } chip_t; enum chip_flags { HasHltClk = (1 << 0), HasLWake = (1 << 1), }; #define HW_REVID(b30, b29, b28, b27, b26, b23, b22) \ (b30<<30 | b29<<29 | b28<<28 | b27<<27 | b26<<26 | b23<<23 | b22<<22) #define HW_REVID_MASK HW_REVID(1, 1, 1, 1, 1, 1, 1) /* directly indexed by chip_t, above */ static const struct { const char *name; u32 version; /* from RTL8139C/RTL8139D docs */ u32 flags; } rtl_chip_info[] = { { "RTL-8139", HW_REVID(1, 0, 0, 0, 0, 0, 0), HasHltClk, }, { "RTL-8139 rev K", HW_REVID(1, 1, 0, 0, 0, 0, 0), HasHltClk, }, { "RTL-8139A", HW_REVID(1, 1, 1, 0, 0, 0, 0), HasHltClk, /* XXX undocumented? */ }, { "RTL-8139A rev G", HW_REVID(1, 1, 1, 0, 0, 1, 0), HasHltClk, /* XXX undocumented? */ }, { "RTL-8139B", HW_REVID(1, 1, 1, 1, 0, 0, 0), HasLWake, }, { "RTL-8130", HW_REVID(1, 1, 1, 1, 1, 0, 0), HasLWake, }, { "RTL-8139C", HW_REVID(1, 1, 1, 0, 1, 0, 0), HasLWake, }, { "RTL-8100", HW_REVID(1, 1, 1, 1, 0, 1, 0), HasLWake, }, { "RTL-8100B/8139D", HW_REVID(1, 1, 1, 0, 1, 0, 1), HasHltClk /* XXX undocumented? */ | HasLWake, }, { "RTL-8101", HW_REVID(1, 1, 1, 0, 1, 1, 1), HasLWake, }, }; struct rtl_extra_stats { unsigned long early_rx; unsigned long tx_buf_mapped; unsigned long tx_timeouts; unsigned long rx_lost_in_ring; }; struct rtl8139_stats { u64 packets; u64 bytes; struct u64_stats_sync syncp; }; struct rtl8139_private { void __iomem *mmio_addr; int drv_flags; struct pci_dev *pci_dev; u32 msg_enable; struct napi_struct napi; struct net_device *dev; unsigned char *rx_ring; unsigned int cur_rx; /* RX buf index of next pkt */ struct rtl8139_stats rx_stats; dma_addr_t rx_ring_dma; unsigned int tx_flag; unsigned long cur_tx; unsigned long dirty_tx; struct rtl8139_stats tx_stats; unsigned char *tx_buf[NUM_TX_DESC]; /* Tx bounce buffers */ unsigned char *tx_bufs; /* Tx bounce buffer region. */ dma_addr_t tx_bufs_dma; signed char phys[4]; /* MII device addresses. */ /* Twister tune state. */ char twistie, twist_row, twist_col; unsigned int watchdog_fired : 1; unsigned int default_port : 4; /* Last dev->if_port value. */ unsigned int have_thread : 1; spinlock_t lock; spinlock_t rx_lock; chip_t chipset; u32 rx_config; struct rtl_extra_stats xstats; struct delayed_work thread; struct mii_if_info mii; unsigned int regs_len; unsigned long fifo_copy_timeout; }; MODULE_AUTHOR ("Jeff Garzik <[email protected]>"); MODULE_DESCRIPTION ("RealTek RTL-8139 Fast Ethernet driver"); MODULE_LICENSE("GPL"); MODULE_VERSION(DRV_VERSION); module_param(use_io, bool, 0); MODULE_PARM_DESC(use_io, "Force use of I/O access mode. 0=MMIO 1=PIO"); module_param(multicast_filter_limit, int, 0); module_param_array(media, int, NULL, 0); module_param_array(full_duplex, int, NULL, 0); module_param(debug, int, 0); MODULE_PARM_DESC (debug, "8139too bitmapped message enable number"); MODULE_PARM_DESC (multicast_filter_limit, "8139too maximum number of filtered multicast addresses"); MODULE_PARM_DESC (media, "8139too: Bits 4+9: force full duplex, bit 5: 100Mbps"); MODULE_PARM_DESC (full_duplex, "8139too: Force full duplex for board(s) (1)"); static int read_eeprom (void __iomem *ioaddr, int location, int addr_len); static int rtl8139_open (struct net_device *dev); static int mdio_read (struct net_device *dev, int phy_id, int location); static void mdio_write (struct net_device *dev, int phy_id, int location, int val); static void rtl8139_start_thread(struct rtl8139_private *tp); static void rtl8139_tx_timeout (struct net_device *dev, unsigned int txqueue); static void rtl8139_init_ring (struct net_device *dev); static netdev_tx_t rtl8139_start_xmit (struct sk_buff *skb, struct net_device *dev); #ifdef CONFIG_NET_POLL_CONTROLLER static void rtl8139_poll_controller(struct net_device *dev); #endif static int rtl8139_set_mac_address(struct net_device *dev, void *p); static int rtl8139_poll(struct napi_struct *napi, int budget); static irqreturn_t rtl8139_interrupt (int irq, void *dev_instance); static int rtl8139_close (struct net_device *dev); static int netdev_ioctl (struct net_device *dev, struct ifreq *rq, int cmd); static void rtl8139_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats); static void rtl8139_set_rx_mode (struct net_device *dev); static void __set_rx_mode (struct net_device *dev); static void rtl8139_hw_start (struct net_device *dev); static void rtl8139_thread (struct work_struct *work); static void rtl8139_tx_timeout_task(struct work_struct *work); static const struct ethtool_ops rtl8139_ethtool_ops; /* write MMIO register, with flush */ /* Flush avoids rtl8139 bug w/ posted MMIO writes */ #define RTL_W8_F(reg, val8) do { iowrite8 ((val8), ioaddr + (reg)); ioread8 (ioaddr + (reg)); } while (0) #define RTL_W16_F(reg, val16) do { iowrite16 ((val16), ioaddr + (reg)); ioread16 (ioaddr + (reg)); } while (0) #define RTL_W32_F(reg, val32) do { iowrite32 ((val32), ioaddr + (reg)); ioread32 (ioaddr + (reg)); } while (0) /* write MMIO register */ #define RTL_W8(reg, val8) iowrite8 ((val8), ioaddr + (reg)) #define RTL_W16(reg, val16) iowrite16 ((val16), ioaddr + (reg)) #define RTL_W32(reg, val32) iowrite32 ((val32), ioaddr + (reg)) /* read MMIO register */ #define RTL_R8(reg) ioread8 (ioaddr + (reg)) #define RTL_R16(reg) ioread16 (ioaddr + (reg)) #define RTL_R32(reg) ioread32 (ioaddr + (reg)) static const u16 rtl8139_intr_mask = PCIErr | PCSTimeout | RxUnderrun | RxOverflow | RxFIFOOver | TxErr | TxOK | RxErr | RxOK; static const u16 rtl8139_norx_intr_mask = PCIErr | PCSTimeout | RxUnderrun | TxErr | TxOK | RxErr ; #if RX_BUF_IDX == 0 static const unsigned int rtl8139_rx_config = RxCfgRcv8K | RxNoWrap | (RX_FIFO_THRESH << RxCfgFIFOShift) | (RX_DMA_BURST << RxCfgDMAShift); #elif RX_BUF_IDX == 1 static const unsigned int rtl8139_rx_config = RxCfgRcv16K | RxNoWrap | (RX_FIFO_THRESH << RxCfgFIFOShift) | (RX_DMA_BURST << RxCfgDMAShift); #elif RX_BUF_IDX == 2 static const unsigned int rtl8139_rx_config = RxCfgRcv32K | RxNoWrap | (RX_FIFO_THRESH << RxCfgFIFOShift) | (RX_DMA_BURST << RxCfgDMAShift); #elif RX_BUF_IDX == 3 static const unsigned int rtl8139_rx_config = RxCfgRcv64K | (RX_FIFO_THRESH << RxCfgFIFOShift) | (RX_DMA_BURST << RxCfgDMAShift); #else #error "Invalid configuration for 8139_RXBUF_IDX" #endif static const unsigned int rtl8139_tx_config = TxIFG96 | (TX_DMA_BURST << TxDMAShift) | (TX_RETRY << TxRetryShift); static void __rtl8139_cleanup_dev (struct net_device *dev) { struct rtl8139_private *tp = netdev_priv(dev); struct pci_dev *pdev; assert (dev != NULL); assert (tp->pci_dev != NULL); pdev = tp->pci_dev; if (tp->mmio_addr) pci_iounmap (pdev, tp->mmio_addr); /* it's ok to call this even if we have no regions to free */ pci_release_regions (pdev); free_netdev(dev); } static void rtl8139_chip_reset (void __iomem *ioaddr) { int i; /* Soft reset the chip. */ RTL_W8 (ChipCmd, CmdReset); /* Check that the chip has finished the reset. */ for (i = 1000; i > 0; i--) { barrier(); if ((RTL_R8 (ChipCmd) & CmdReset) == 0) break; udelay (10); } } static struct net_device *rtl8139_init_board(struct pci_dev *pdev) { struct device *d = &pdev->dev; void __iomem *ioaddr; struct net_device *dev; struct rtl8139_private *tp; u8 tmp8; int rc, disable_dev_on_err = 0; unsigned int i, bar; unsigned long io_len; u32 version; static const struct { unsigned long mask; char *type; } res[] = { { IORESOURCE_IO, "PIO" }, { IORESOURCE_MEM, "MMIO" } }; assert (pdev != NULL); /* dev and priv zeroed in alloc_etherdev */ dev = alloc_etherdev (sizeof (*tp)); if (dev == NULL) return ERR_PTR(-ENOMEM); SET_NETDEV_DEV(dev, &pdev->dev); tp = netdev_priv(dev); tp->pci_dev = pdev; /* enable device (incl. PCI PM wakeup and hotplug setup) */ rc = pci_enable_device (pdev); if (rc) goto err_out; disable_dev_on_err = 1; rc = pci_request_regions (pdev, DRV_NAME); if (rc) goto err_out; pci_set_master (pdev); u64_stats_init(&tp->rx_stats.syncp); u64_stats_init(&tp->tx_stats.syncp); retry: /* PIO bar register comes first. */ bar = !use_io; io_len = pci_resource_len(pdev, bar); dev_dbg(d, "%s region size = 0x%02lX\n", res[bar].type, io_len); if (!(pci_resource_flags(pdev, bar) & res[bar].mask)) { dev_err(d, "region #%d not a %s resource, aborting\n", bar, res[bar].type); rc = -ENODEV; goto err_out; } if (io_len < RTL_MIN_IO_SIZE) { dev_err(d, "Invalid PCI %s region size(s), aborting\n", res[bar].type); rc = -ENODEV; goto err_out; } ioaddr = pci_iomap(pdev, bar, 0); if (!ioaddr) { dev_err(d, "cannot map %s\n", res[bar].type); if (!use_io) { use_io = true; goto retry; } rc = -ENODEV; goto err_out; } tp->regs_len = io_len; tp->mmio_addr = ioaddr; /* Bring old chips out of low-power mode. */ RTL_W8 (HltClk, 'R'); /* check for missing/broken hardware */ if (RTL_R32 (TxConfig) == 0xFFFFFFFF) { dev_err(&pdev->dev, "Chip not responding, ignoring board\n"); rc = -EIO; goto err_out; } /* identify chip attached to board */ version = RTL_R32 (TxConfig) & HW_REVID_MASK; for (i = 0; i < ARRAY_SIZE (rtl_chip_info); i++) if (version == rtl_chip_info[i].version) { tp->chipset = i; goto match; } /* if unknown chip, assume array element #0, original RTL-8139 in this case */ i = 0; dev_dbg(&pdev->dev, "unknown chip version, assuming RTL-8139\n"); dev_dbg(&pdev->dev, "TxConfig = 0x%x\n", RTL_R32 (TxConfig)); tp->chipset = 0; match: pr_debug("chipset id (%d) == index %d, '%s'\n", version, i, rtl_chip_info[i].name); if (tp->chipset >= CH_8139B) { u8 new_tmp8 = tmp8 = RTL_R8 (Config1); pr_debug("PCI PM wakeup\n"); if ((rtl_chip_info[tp->chipset].flags & HasLWake) && (tmp8 & LWAKE)) new_tmp8 &= ~LWAKE; new_tmp8 |= Cfg1_PM_Enable; if (new_tmp8 != tmp8) { RTL_W8 (Cfg9346, Cfg9346_Unlock); RTL_W8 (Config1, tmp8); RTL_W8 (Cfg9346, Cfg9346_Lock); } if (rtl_chip_info[tp->chipset].flags & HasLWake) { tmp8 = RTL_R8 (Config4); if (tmp8 & LWPTN) { RTL_W8 (Cfg9346, Cfg9346_Unlock); RTL_W8 (Config4, tmp8 & ~LWPTN); RTL_W8 (Cfg9346, Cfg9346_Lock); } } } else { pr_debug("Old chip wakeup\n"); tmp8 = RTL_R8 (Config1); tmp8 &= ~(SLEEP | PWRDN); RTL_W8 (Config1, tmp8); } rtl8139_chip_reset (ioaddr); return dev; err_out: __rtl8139_cleanup_dev (dev); if (disable_dev_on_err) pci_disable_device (pdev); return ERR_PTR(rc); } static int rtl8139_set_features(struct net_device *dev, netdev_features_t features) { struct rtl8139_private *tp = netdev_priv(dev); unsigned long flags; netdev_features_t changed = features ^ dev->features; void __iomem *ioaddr = tp->mmio_addr; if (!(changed & (NETIF_F_RXALL))) return 0; spin_lock_irqsave(&tp->lock, flags); if (changed & NETIF_F_RXALL) { int rx_mode = tp->rx_config; if (features & NETIF_F_RXALL) rx_mode |= (AcceptErr | AcceptRunt); else rx_mode &= ~(AcceptErr | AcceptRunt); tp->rx_config = rtl8139_rx_config | rx_mode; RTL_W32_F(RxConfig, tp->rx_config); } spin_unlock_irqrestore(&tp->lock, flags); return 0; } static const struct net_device_ops rtl8139_netdev_ops = { .ndo_open = rtl8139_open, .ndo_stop = rtl8139_close, .ndo_get_stats64 = rtl8139_get_stats64, .ndo_validate_addr = eth_validate_addr, .ndo_set_mac_address = rtl8139_set_mac_address, .ndo_start_xmit = rtl8139_start_xmit, .ndo_set_rx_mode = rtl8139_set_rx_mode, .ndo_eth_ioctl = netdev_ioctl, .ndo_tx_timeout = rtl8139_tx_timeout, #ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = rtl8139_poll_controller, #endif .ndo_set_features = rtl8139_set_features, }; static int rtl8139_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) { struct net_device *dev = NULL; struct rtl8139_private *tp; __le16 addr[ETH_ALEN / 2]; int i, addr_len, option; void __iomem *ioaddr; static int board_idx = -1; assert (pdev != NULL); assert (ent != NULL); board_idx++; /* when we're built into the kernel, the driver version message * is only printed if at least one 8139 board has been found */ #ifndef MODULE { static int printed_version; if (!printed_version++) pr_info(RTL8139_DRIVER_NAME "\n"); } #endif if (pdev->vendor == PCI_VENDOR_ID_REALTEK && pdev->device == PCI_DEVICE_ID_REALTEK_8139 && pdev->revision >= 0x20) { dev_info(&pdev->dev, "This (id %04x:%04x rev %02x) is an enhanced 8139C+ chip, use 8139cp\n", pdev->vendor, pdev->device, pdev->revision); return -ENODEV; } if (pdev->vendor == PCI_VENDOR_ID_REALTEK && pdev->device == PCI_DEVICE_ID_REALTEK_8139 && pdev->subsystem_vendor == PCI_VENDOR_ID_ATHEROS && pdev->subsystem_device == PCI_DEVICE_ID_REALTEK_8139) { pr_info("OQO Model 2 detected. Forcing PIO\n"); use_io = true; } dev = rtl8139_init_board (pdev); if (IS_ERR(dev)) return PTR_ERR(dev); assert (dev != NULL); tp = netdev_priv(dev); tp->dev = dev; ioaddr = tp->mmio_addr; assert (ioaddr != NULL); addr_len = read_eeprom (ioaddr, 0, 8) == 0x8129 ? 8 : 6; for (i = 0; i < 3; i++) addr[i] = cpu_to_le16(read_eeprom (ioaddr, i + 7, addr_len)); eth_hw_addr_set(dev, (u8 *)addr); /* The Rtl8139-specific entries in the device structure. */ dev->netdev_ops = &rtl8139_netdev_ops; dev->ethtool_ops = &rtl8139_ethtool_ops; dev->watchdog_timeo = TX_TIMEOUT; netif_napi_add(dev, &tp->napi, rtl8139_poll); /* note: the hardware is not capable of sg/csum/highdma, however * through the use of skb_copy_and_csum_dev we enable these * features */ dev->features |= NETIF_F_SG | NETIF_F_HW_CSUM | NETIF_F_HIGHDMA; dev->vlan_features = dev->features; dev->hw_features |= NETIF_F_RXALL; dev->hw_features |= NETIF_F_RXFCS; /* MTU range: 68 - 1770 */ dev->min_mtu = ETH_MIN_MTU; dev->max_mtu = MAX_ETH_DATA_SIZE; /* tp zeroed and aligned in alloc_etherdev */ tp = netdev_priv(dev); /* note: tp->chipset set in rtl8139_init_board */ tp->drv_flags = board_info[ent->driver_data].hw_flags; tp->mmio_addr = ioaddr; tp->msg_enable = (debug < 0 ? RTL8139_DEF_MSG_ENABLE : ((1 << debug) - 1)); spin_lock_init (&tp->lock); spin_lock_init (&tp->rx_lock); INIT_DELAYED_WORK(&tp->thread, rtl8139_thread); tp->mii.dev = dev; tp->mii.mdio_read = mdio_read; tp->mii.mdio_write = mdio_write; tp->mii.phy_id_mask = 0x3f; tp->mii.reg_num_mask = 0x1f; /* dev is fully set up and ready to use now */ pr_debug("about to register device named %s (%p)...\n", dev->name, dev); i = register_netdev (dev); if (i) goto err_out; pci_set_drvdata (pdev, dev); netdev_info(dev, "%s at 0x%p, %pM, IRQ %d\n", board_info[ent->driver_data].name, ioaddr, dev->dev_addr, pdev->irq); netdev_dbg(dev, "Identified 8139 chip type '%s'\n", rtl_chip_info[tp->chipset].name); /* Find the connected MII xcvrs. Doing this in open() would allow detecting external xcvrs later, but takes too much time. */ #ifdef CONFIG_8139TOO_8129 if (tp->drv_flags & HAS_MII_XCVR) { int phy, phy_idx = 0; for (phy = 0; phy < 32 && phy_idx < sizeof(tp->phys); phy++) { int mii_status = mdio_read(dev, phy, 1); if (mii_status != 0xffff && mii_status != 0x0000) { u16 advertising = mdio_read(dev, phy, 4); tp->phys[phy_idx++] = phy; netdev_info(dev, "MII transceiver %d status 0x%04x advertising %04x\n", phy, mii_status, advertising); } } if (phy_idx == 0) { netdev_info(dev, "No MII transceivers found! Assuming SYM transceiver\n"); tp->phys[0] = 32; } } else #endif tp->phys[0] = 32; tp->mii.phy_id = tp->phys[0]; /* The lower four bits are the media type. */ option = (board_idx >= MAX_UNITS) ? 0 : media[board_idx]; if (option > 0) { tp->mii.full_duplex = (option & 0x210) ? 1 : 0; tp->default_port = option & 0xFF; if (tp->default_port) tp->mii.force_media = 1; } if (board_idx < MAX_UNITS && full_duplex[board_idx] > 0) tp->mii.full_duplex = full_duplex[board_idx]; if (tp->mii.full_duplex) { netdev_info(dev, "Media type forced to Full Duplex\n"); /* Changing the MII-advertised media because might prevent re-connection. */ tp->mii.force_media = 1; } if (tp->default_port) { netdev_info(dev, " Forcing %dMbps %s-duplex operation\n", (option & 0x20 ? 100 : 10), (option & 0x10 ? "full" : "half")); mdio_write(dev, tp->phys[0], 0, ((option & 0x20) ? 0x2000 : 0) | /* 100Mbps? */ ((option & 0x10) ? 0x0100 : 0)); /* Full duplex? */ } /* Put the chip into low-power mode. */ if (rtl_chip_info[tp->chipset].flags & HasHltClk) RTL_W8 (HltClk, 'H'); /* 'R' would leave the clock running. */ return 0; err_out: __rtl8139_cleanup_dev (dev); pci_disable_device (pdev); return i; } static void rtl8139_remove_one(struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata (pdev); struct rtl8139_private *tp = netdev_priv(dev); assert (dev != NULL); cancel_delayed_work_sync(&tp->thread); unregister_netdev (dev); __rtl8139_cleanup_dev (dev); pci_disable_device (pdev); } /* Serial EEPROM section. */ /* EEPROM_Ctrl bits. */ #define EE_SHIFT_CLK 0x04 /* EEPROM shift clock. */ #define EE_CS 0x08 /* EEPROM chip select. */ #define EE_DATA_WRITE 0x02 /* EEPROM chip data in. */ #define EE_WRITE_0 0x00 #define EE_WRITE_1 0x02 #define EE_DATA_READ 0x01 /* EEPROM chip data out. */ #define EE_ENB (0x80 | EE_CS) /* Delay between EEPROM clock transitions. No extra delay is needed with 33Mhz PCI, but 66Mhz may change this. */ #define eeprom_delay() (void)RTL_R8(Cfg9346) /* The EEPROM commands include the alway-set leading bit. */ #define EE_WRITE_CMD (5) #define EE_READ_CMD (6) #define EE_ERASE_CMD (7) static int read_eeprom(void __iomem *ioaddr, int location, int addr_len) { int i; unsigned retval = 0; int read_cmd = location | (EE_READ_CMD << addr_len); RTL_W8 (Cfg9346, EE_ENB & ~EE_CS); RTL_W8 (Cfg9346, EE_ENB); eeprom_delay (); /* Shift the read command bits out. */ for (i = 4 + addr_len; i >= 0; i--) { int dataval = (read_cmd & (1 << i)) ? EE_DATA_WRITE : 0; RTL_W8 (Cfg9346, EE_ENB | dataval); eeprom_delay (); RTL_W8 (Cfg9346, EE_ENB | dataval | EE_SHIFT_CLK); eeprom_delay (); } RTL_W8 (Cfg9346, EE_ENB); eeprom_delay (); for (i = 16; i > 0; i--) { RTL_W8 (Cfg9346, EE_ENB | EE_SHIFT_CLK); eeprom_delay (); retval = (retval << 1) | ((RTL_R8 (Cfg9346) & EE_DATA_READ) ? 1 : 0); RTL_W8 (Cfg9346, EE_ENB); eeprom_delay (); } /* Terminate the EEPROM access. */ RTL_W8(Cfg9346, 0); eeprom_delay (); return retval; } /* MII serial management: mostly bogus for now. */ /* Read and write the MII management registers using software-generated serial MDIO protocol. The maximum data clock rate is 2.5 Mhz. The minimum timing is usually met by back-to-back PCI I/O cycles, but we insert a delay to avoid "overclocking" issues. */ #define MDIO_DIR 0x80 #define MDIO_DATA_OUT 0x04 #define MDIO_DATA_IN 0x02 #define MDIO_CLK 0x01 #define MDIO_WRITE0 (MDIO_DIR) #define MDIO_WRITE1 (MDIO_DIR | MDIO_DATA_OUT) #define mdio_delay() RTL_R8(Config4) static const char mii_2_8139_map[8] = { BasicModeCtrl, BasicModeStatus, 0, 0, NWayAdvert, NWayLPAR, NWayExpansion, 0 }; #ifdef CONFIG_8139TOO_8129 /* Syncronize the MII management interface by shifting 32 one bits out. */ static void mdio_sync (void __iomem *ioaddr) { int i; for (i = 32; i >= 0; i--) { RTL_W8 (Config4, MDIO_WRITE1); mdio_delay (); RTL_W8 (Config4, MDIO_WRITE1 | MDIO_CLK); mdio_delay (); } } #endif static int mdio_read (struct net_device *dev, int phy_id, int location) { struct rtl8139_private *tp = netdev_priv(dev); int retval = 0; #ifdef CONFIG_8139TOO_8129 void __iomem *ioaddr = tp->mmio_addr; int mii_cmd = (0xf6 << 10) | (phy_id << 5) | location; int i; #endif if (phy_id > 31) { /* Really a 8139. Use internal registers. */ void __iomem *ioaddr = tp->mmio_addr; return location < 8 && mii_2_8139_map[location] ? RTL_R16 (mii_2_8139_map[location]) : 0; } #ifdef CONFIG_8139TOO_8129 mdio_sync (ioaddr); /* Shift the read command bits out. */ for (i = 15; i >= 0; i--) { int dataval = (mii_cmd & (1 << i)) ? MDIO_DATA_OUT : 0; RTL_W8 (Config4, MDIO_DIR | dataval); mdio_delay (); RTL_W8 (Config4, MDIO_DIR | dataval | MDIO_CLK); mdio_delay (); } /* Read the two transition, 16 data, and wire-idle bits. */ for (i = 19; i > 0; i--) { RTL_W8 (Config4, 0); mdio_delay (); retval = (retval << 1) | ((RTL_R8 (Config4) & MDIO_DATA_IN) ? 1 : 0); RTL_W8 (Config4, MDIO_CLK); mdio_delay (); } #endif return (retval >> 1) & 0xffff; } static void mdio_write (struct net_device *dev, int phy_id, int location, int value) { struct rtl8139_private *tp = netdev_priv(dev); #ifdef CONFIG_8139TOO_8129 void __iomem *ioaddr = tp->mmio_addr; int mii_cmd = (0x5002 << 16) | (phy_id << 23) | (location << 18) | value; int i; #endif if (phy_id > 31) { /* Really a 8139. Use internal registers. */ void __iomem *ioaddr = tp->mmio_addr; if (location == 0) { RTL_W8 (Cfg9346, Cfg9346_Unlock); RTL_W16 (BasicModeCtrl, value); RTL_W8 (Cfg9346, Cfg9346_Lock); } else if (location < 8 && mii_2_8139_map[location]) RTL_W16 (mii_2_8139_map[location], value); return; } #ifdef CONFIG_8139TOO_8129 mdio_sync (ioaddr); /* Shift the command bits out. */ for (i = 31; i >= 0; i--) { int dataval = (mii_cmd & (1 << i)) ? MDIO_WRITE1 : MDIO_WRITE0; RTL_W8 (Config4, dataval); mdio_delay (); RTL_W8 (Config4, dataval | MDIO_CLK); mdio_delay (); } /* Clear out extra bits. */ for (i = 2; i > 0; i--) { RTL_W8 (Config4, 0); mdio_delay (); RTL_W8 (Config4, MDIO_CLK); mdio_delay (); } #endif } static int rtl8139_open (struct net_device *dev) { struct rtl8139_private *tp = netdev_priv(dev); void __iomem *ioaddr = tp->mmio_addr; const int irq = tp->pci_dev->irq; int retval; retval = request_irq(irq, rtl8139_interrupt, IRQF_SHARED, dev->name, dev); if (retval) return retval; tp->tx_bufs = dma_alloc_coherent(&tp->pci_dev->dev, TX_BUF_TOT_LEN, &tp->tx_bufs_dma, GFP_KERNEL); tp->rx_ring = dma_alloc_coherent(&tp->pci_dev->dev, RX_BUF_TOT_LEN, &tp->rx_ring_dma, GFP_KERNEL); if (tp->tx_bufs == NULL || tp->rx_ring == NULL) { free_irq(irq, dev); if (tp->tx_bufs) dma_free_coherent(&tp->pci_dev->dev, TX_BUF_TOT_LEN, tp->tx_bufs, tp->tx_bufs_dma); if (tp->rx_ring) dma_free_coherent(&tp->pci_dev->dev, RX_BUF_TOT_LEN, tp->rx_ring, tp->rx_ring_dma); return -ENOMEM; } napi_enable(&tp->napi); tp->mii.full_duplex = tp->mii.force_media; tp->tx_flag = (TX_FIFO_THRESH << 11) & 0x003f0000; rtl8139_init_ring (dev); rtl8139_hw_start (dev); netif_start_queue (dev); netif_dbg(tp, ifup, dev, "%s() ioaddr %#llx IRQ %d GP Pins %02x %s-duplex\n", __func__, (unsigned long long)pci_resource_start (tp->pci_dev, 1), irq, RTL_R8 (MediaStatus), tp->mii.full_duplex ? "full" : "half"); rtl8139_start_thread(tp); return 0; } static void rtl_check_media (struct net_device *dev, unsigned int init_media) { struct rtl8139_private *tp = netdev_priv(dev); if (tp->phys[0] >= 0) { mii_check_media(&tp->mii, netif_msg_link(tp), init_media); } } /* Start the hardware at open or resume. */ static void rtl8139_hw_start (struct net_device *dev) { struct rtl8139_private *tp = netdev_priv(dev); void __iomem *ioaddr = tp->mmio_addr; u32 i; u8 tmp; /* Bring old chips out of low-power mode. */ if (rtl_chip_info[tp->chipset].flags & HasHltClk) RTL_W8 (HltClk, 'R'); rtl8139_chip_reset (ioaddr); /* unlock Config[01234] and BMCR register writes */ RTL_W8_F (Cfg9346, Cfg9346_Unlock); /* Restore our idea of the MAC address. */ RTL_W32_F (MAC0 + 0, le32_to_cpu (*(__le32 *) (dev->dev_addr + 0))); RTL_W32_F (MAC0 + 4, le16_to_cpu (*(__le16 *) (dev->dev_addr + 4))); tp->cur_rx = 0; /* init Rx ring buffer DMA address */ RTL_W32_F (RxBuf, tp->rx_ring_dma); /* Must enable Tx/Rx before setting transfer thresholds! */ RTL_W8 (ChipCmd, CmdRxEnb | CmdTxEnb); tp->rx_config = rtl8139_rx_config | AcceptBroadcast | AcceptMyPhys; RTL_W32 (RxConfig, tp->rx_config); RTL_W32 (TxConfig, rtl8139_tx_config); rtl_check_media (dev, 1); if (tp->chipset >= CH_8139B) { /* Disable magic packet scanning, which is enabled * when PM is enabled in Config1. It can be reenabled * via ETHTOOL_SWOL if desired. */ RTL_W8 (Config3, RTL_R8 (Config3) & ~Cfg3_Magic); } netdev_dbg(dev, "init buffer addresses\n"); /* Lock Config[01234] and BMCR register writes */ RTL_W8 (Cfg9346, Cfg9346_Lock); /* init Tx buffer DMA addresses */ for (i = 0; i < NUM_TX_DESC; i++) RTL_W32_F (TxAddr0 + (i * 4), tp->tx_bufs_dma + (tp->tx_buf[i] - tp->tx_bufs)); RTL_W32 (RxMissed, 0); rtl8139_set_rx_mode (dev); /* no early-rx interrupts */ RTL_W16 (MultiIntr, RTL_R16 (MultiIntr) & MultiIntrClear); /* make sure RxTx has started */ tmp = RTL_R8 (ChipCmd); if ((!(tmp & CmdRxEnb)) || (!(tmp & CmdTxEnb))) RTL_W8 (ChipCmd, CmdRxEnb | CmdTxEnb); /* Enable all known interrupts by setting the interrupt mask. */ RTL_W16 (IntrMask, rtl8139_intr_mask); } /* Initialize the Rx and Tx rings, along with various 'dev' bits. */ static void rtl8139_init_ring (struct net_device *dev) { struct rtl8139_private *tp = netdev_priv(dev); int i; tp->cur_rx = 0; tp->cur_tx = 0; tp->dirty_tx = 0; for (i = 0; i < NUM_TX_DESC; i++) tp->tx_buf[i] = &tp->tx_bufs[i * TX_BUF_SIZE]; } /* This must be global for CONFIG_8139TOO_TUNE_TWISTER case */ static int next_tick = 3 * HZ; #ifndef CONFIG_8139TOO_TUNE_TWISTER static inline void rtl8139_tune_twister (struct net_device *dev, struct rtl8139_private *tp) {} #else enum TwisterParamVals { PARA78_default = 0x78fa8388, PARA7c_default = 0xcb38de43, /* param[0][3] */ PARA7c_xxx = 0xcb38de43, }; static const unsigned long param[4][4] = { {0xcb39de43, 0xcb39ce43, 0xfb38de03, 0xcb38de43}, {0xcb39de43, 0xcb39ce43, 0xcb39ce83, 0xcb39ce83}, {0xcb39de43, 0xcb39ce43, 0xcb39ce83, 0xcb39ce83}, {0xbb39de43, 0xbb39ce43, 0xbb39ce83, 0xbb39ce83} }; static void rtl8139_tune_twister (struct net_device *dev, struct rtl8139_private *tp) { int linkcase; void __iomem *ioaddr = tp->mmio_addr; /* This is a complicated state machine to configure the "twister" for impedance/echos based on the cable length. All of this is magic and undocumented. */ switch (tp->twistie) { case 1: if (RTL_R16 (CSCR) & CSCR_LinkOKBit) { /* We have link beat, let us tune the twister. */ RTL_W16 (CSCR, CSCR_LinkDownOffCmd); tp->twistie = 2; /* Change to state 2. */ next_tick = HZ / 10; } else { /* Just put in some reasonable defaults for when beat returns. */ RTL_W16 (CSCR, CSCR_LinkDownCmd); RTL_W32 (FIFOTMS, 0x20); /* Turn on cable test mode. */ RTL_W32 (PARA78, PARA78_default); RTL_W32 (PARA7c, PARA7c_default); tp->twistie = 0; /* Bail from future actions. */ } break; case 2: /* Read how long it took to hear the echo. */ linkcase = RTL_R16 (CSCR) & CSCR_LinkStatusBits; if (linkcase == 0x7000) tp->twist_row = 3; else if (linkcase == 0x3000) tp->twist_row = 2; else if (linkcase == 0x1000) tp->twist_row = 1; else tp->twist_row = 0; tp->twist_col = 0; tp->twistie = 3; /* Change to state 2. */ next_tick = HZ / 10; break; case 3: /* Put out four tuning parameters, one per 100msec. */ if (tp->twist_col == 0) RTL_W16 (FIFOTMS, 0); RTL_W32 (PARA7c, param[(int) tp->twist_row] [(int) tp->twist_col]); next_tick = HZ / 10; if (++tp->twist_col >= 4) { /* For short cables we are done. For long cables (row == 3) check for mistune. */ tp->twistie = (tp->twist_row == 3) ? 4 : 0; } break; case 4: /* Special case for long cables: check for mistune. */ if ((RTL_R16 (CSCR) & CSCR_LinkStatusBits) == 0x7000) { tp->twistie = 0; break; } else { RTL_W32 (PARA7c, 0xfb38de03); tp->twistie = 5; next_tick = HZ / 10; } break; case 5: /* Retune for shorter cable (column 2). */ RTL_W32 (FIFOTMS, 0x20); RTL_W32 (PARA78, PARA78_default); RTL_W32 (PARA7c, PARA7c_default); RTL_W32 (FIFOTMS, 0x00); tp->twist_row = 2; tp->twist_col = 0; tp->twistie = 3; next_tick = HZ / 10; break; default: /* do nothing */ break; } } #endif /* CONFIG_8139TOO_TUNE_TWISTER */ static inline void rtl8139_thread_iter (struct net_device *dev, struct rtl8139_private *tp, void __iomem *ioaddr) { int mii_lpa; mii_lpa = mdio_read (dev, tp->phys[0], MII_LPA); if (!tp->mii.force_media && mii_lpa != 0xffff) { int duplex = ((mii_lpa & LPA_100FULL) || (mii_lpa & 0x01C0) == 0x0040); if (tp->mii.full_duplex != duplex) { tp->mii.full_duplex = duplex; if (mii_lpa) { netdev_info(dev, "Setting %s-duplex based on MII #%d link partner ability of %04x\n", tp->mii.full_duplex ? "full" : "half", tp->phys[0], mii_lpa); } else { netdev_info(dev, "media is unconnected, link down, or incompatible connection\n"); } #if 0 RTL_W8 (Cfg9346, Cfg9346_Unlock); RTL_W8 (Config1, tp->mii.full_duplex ? 0x60 : 0x20); RTL_W8 (Cfg9346, Cfg9346_Lock); #endif } } next_tick = HZ * 60; rtl8139_tune_twister (dev, tp); netdev_dbg(dev, "Media selection tick, Link partner %04x\n", RTL_R16(NWayLPAR)); netdev_dbg(dev, "Other registers are IntMask %04x IntStatus %04x\n", RTL_R16(IntrMask), RTL_R16(IntrStatus)); netdev_dbg(dev, "Chip config %02x %02x\n", RTL_R8(Config0), RTL_R8(Config1)); } static void rtl8139_thread (struct work_struct *work) { struct rtl8139_private *tp = container_of(work, struct rtl8139_private, thread.work); struct net_device *dev = tp->mii.dev; unsigned long thr_delay = next_tick; rtnl_lock(); if (!netif_running(dev)) goto out_unlock; if (tp->watchdog_fired) { tp->watchdog_fired = 0; rtl8139_tx_timeout_task(work); } else rtl8139_thread_iter(dev, tp, tp->mmio_addr); if (tp->have_thread) schedule_delayed_work(&tp->thread, thr_delay); out_unlock: rtnl_unlock (); } static void rtl8139_start_thread(struct rtl8139_private *tp) { tp->twistie = 0; if (tp->chipset == CH_8139_K) tp->twistie = 1; else if (tp->drv_flags & HAS_LNK_CHNG) return; tp->have_thread = 1; tp->watchdog_fired = 0; schedule_delayed_work(&tp->thread, next_tick); } static inline void rtl8139_tx_clear (struct rtl8139_private *tp) { tp->cur_tx = 0; tp->dirty_tx = 0; /* XXX account for unsent Tx packets in tp->stats.tx_dropped */ } static void rtl8139_tx_timeout_task (struct work_struct *work) { struct rtl8139_private *tp = container_of(work, struct rtl8139_private, thread.work); struct net_device *dev = tp->mii.dev; void __iomem *ioaddr = tp->mmio_addr; int i; u8 tmp8; napi_disable(&tp->napi); netif_stop_queue(dev); synchronize_rcu(); netdev_dbg(dev, "Transmit timeout, status %02x %04x %04x media %02x\n", RTL_R8(ChipCmd), RTL_R16(IntrStatus), RTL_R16(IntrMask), RTL_R8(MediaStatus)); /* Emit info to figure out what went wrong. */ netdev_dbg(dev, "Tx queue start entry %ld dirty entry %ld\n", tp->cur_tx, tp->dirty_tx); for (i = 0; i < NUM_TX_DESC; i++) netdev_dbg(dev, "Tx descriptor %d is %08x%s\n", i, RTL_R32(TxStatus0 + (i * 4)), i == tp->dirty_tx % NUM_TX_DESC ? " (queue head)" : ""); tp->xstats.tx_timeouts++; /* disable Tx ASAP, if not already */ tmp8 = RTL_R8 (ChipCmd); if (tmp8 & CmdTxEnb) RTL_W8 (ChipCmd, CmdRxEnb); spin_lock_bh(&tp->rx_lock); /* Disable interrupts by clearing the interrupt mask. */ RTL_W16 (IntrMask, 0x0000); /* Stop a shared interrupt from scavenging while we are. */ spin_lock_irq(&tp->lock); rtl8139_tx_clear (tp); spin_unlock_irq(&tp->lock); /* ...and finally, reset everything */ napi_enable(&tp->napi); rtl8139_hw_start(dev); netif_wake_queue(dev); spin_unlock_bh(&tp->rx_lock); } static void rtl8139_tx_timeout(struct net_device *dev, unsigned int txqueue) { struct rtl8139_private *tp = netdev_priv(dev); tp->watchdog_fired = 1; if (!tp->have_thread) { INIT_DELAYED_WORK(&tp->thread, rtl8139_thread); schedule_delayed_work(&tp->thread, next_tick); } } static netdev_tx_t rtl8139_start_xmit (struct sk_buff *skb, struct net_device *dev) { struct rtl8139_private *tp = netdev_priv(dev); void __iomem *ioaddr = tp->mmio_addr; unsigned int entry; unsigned int len = skb->len; unsigned long flags; /* Calculate the next Tx descriptor entry. */ entry = tp->cur_tx % NUM_TX_DESC; /* Note: the chip doesn't have auto-pad! */ if (likely(len < TX_BUF_SIZE)) { if (len < ETH_ZLEN) memset(tp->tx_buf[entry], 0, ETH_ZLEN); skb_copy_and_csum_dev(skb, tp->tx_buf[entry]); dev_kfree_skb_any(skb); } else { dev_kfree_skb_any(skb); dev->stats.tx_dropped++; return NETDEV_TX_OK; } spin_lock_irqsave(&tp->lock, flags); /* * Writing to TxStatus triggers a DMA transfer of the data * copied to tp->tx_buf[entry] above. Use a memory barrier * to make sure that the device sees the updated data. */ wmb(); RTL_W32_F (TxStatus0 + (entry * sizeof (u32)), tp->tx_flag | max(len, (unsigned int)ETH_ZLEN)); tp->cur_tx++; if ((tp->cur_tx - NUM_TX_DESC) == tp->dirty_tx) netif_stop_queue (dev); spin_unlock_irqrestore(&tp->lock, flags); netif_dbg(tp, tx_queued, dev, "Queued Tx packet size %u to slot %d\n", len, entry); return NETDEV_TX_OK; } static void rtl8139_tx_interrupt (struct net_device *dev, struct rtl8139_private *tp, void __iomem *ioaddr) { unsigned long dirty_tx, tx_left; assert (dev != NULL); assert (ioaddr != NULL); dirty_tx = tp->dirty_tx; tx_left = tp->cur_tx - dirty_tx; while (tx_left > 0) { int entry = dirty_tx % NUM_TX_DESC; int txstatus; txstatus = RTL_R32 (TxStatus0 + (entry * sizeof (u32))); if (!(txstatus & (TxStatOK | TxUnderrun | TxAborted))) break; /* It still hasn't been Txed */ /* Note: TxCarrierLost is always asserted at 100mbps. */ if (txstatus & (TxOutOfWindow | TxAborted)) { /* There was an major error, log it. */ netif_dbg(tp, tx_err, dev, "Transmit error, Tx status %08x\n", txstatus); dev->stats.tx_errors++; if (txstatus & TxAborted) { dev->stats.tx_aborted_errors++; RTL_W32 (TxConfig, TxClearAbt); RTL_W16 (IntrStatus, TxErr); wmb(); } if (txstatus & TxCarrierLost) dev->stats.tx_carrier_errors++; if (txstatus & TxOutOfWindow) dev->stats.tx_window_errors++; } else { if (txstatus & TxUnderrun) { /* Add 64 to the Tx FIFO threshold. */ if (tp->tx_flag < 0x00300000) tp->tx_flag += 0x00020000; dev->stats.tx_fifo_errors++; } dev->stats.collisions += (txstatus >> 24) & 15; u64_stats_update_begin(&tp->tx_stats.syncp); tp->tx_stats.packets++; tp->tx_stats.bytes += txstatus & 0x7ff; u64_stats_update_end(&tp->tx_stats.syncp); } dirty_tx++; tx_left--; } #ifndef RTL8139_NDEBUG if (tp->cur_tx - dirty_tx > NUM_TX_DESC) { netdev_err(dev, "Out-of-sync dirty pointer, %ld vs. %ld\n", dirty_tx, tp->cur_tx); dirty_tx += NUM_TX_DESC; } #endif /* RTL8139_NDEBUG */ /* only wake the queue if we did work, and the queue is stopped */ if (tp->dirty_tx != dirty_tx) { tp->dirty_tx = dirty_tx; mb(); netif_wake_queue (dev); } } /* TODO: clean this up! Rx reset need not be this intensive */ static void rtl8139_rx_err (u32 rx_status, struct net_device *dev, struct rtl8139_private *tp, void __iomem *ioaddr) { u8 tmp8; #ifdef CONFIG_8139_OLD_RX_RESET int tmp_work; #endif netif_dbg(tp, rx_err, dev, "Ethernet frame had errors, status %08x\n", rx_status); dev->stats.rx_errors++; if (!(rx_status & RxStatusOK)) { if (rx_status & RxTooLong) { netdev_dbg(dev, "Oversized Ethernet frame, status %04x!\n", rx_status); /* A.C.: The chip hangs here. */ } if (rx_status & (RxBadSymbol | RxBadAlign)) dev->stats.rx_frame_errors++; if (rx_status & (RxRunt | RxTooLong)) dev->stats.rx_length_errors++; if (rx_status & RxCRCErr) dev->stats.rx_crc_errors++; } else { tp->xstats.rx_lost_in_ring++; } #ifndef CONFIG_8139_OLD_RX_RESET tmp8 = RTL_R8 (ChipCmd); RTL_W8 (ChipCmd, tmp8 & ~CmdRxEnb); RTL_W8 (ChipCmd, tmp8); RTL_W32 (RxConfig, tp->rx_config); tp->cur_rx = 0; #else /* Reset the receiver, based on RealTek recommendation. (Bug?) */ /* disable receive */ RTL_W8_F (ChipCmd, CmdTxEnb); tmp_work = 200; while (--tmp_work > 0) { udelay(1); tmp8 = RTL_R8 (ChipCmd); if (!(tmp8 & CmdRxEnb)) break; } if (tmp_work <= 0) netdev_warn(dev, "rx stop wait too long\n"); /* restart receive */ tmp_work = 200; while (--tmp_work > 0) { RTL_W8_F (ChipCmd, CmdRxEnb | CmdTxEnb); udelay(1); tmp8 = RTL_R8 (ChipCmd); if ((tmp8 & CmdRxEnb) && (tmp8 & CmdTxEnb)) break; } if (tmp_work <= 0) netdev_warn(dev, "tx/rx enable wait too long\n"); /* and reinitialize all rx related registers */ RTL_W8_F (Cfg9346, Cfg9346_Unlock); /* Must enable Tx/Rx before setting transfer thresholds! */ RTL_W8 (ChipCmd, CmdRxEnb | CmdTxEnb); tp->rx_config = rtl8139_rx_config | AcceptBroadcast | AcceptMyPhys; RTL_W32 (RxConfig, tp->rx_config); tp->cur_rx = 0; netdev_dbg(dev, "init buffer addresses\n"); /* Lock Config[01234] and BMCR register writes */ RTL_W8 (Cfg9346, Cfg9346_Lock); /* init Rx ring buffer DMA address */ RTL_W32_F (RxBuf, tp->rx_ring_dma); /* A.C.: Reset the multicast list. */ __set_rx_mode (dev); #endif } #if RX_BUF_IDX == 3 static inline void wrap_copy(struct sk_buff *skb, const unsigned char *ring, u32 offset, unsigned int size) { u32 left = RX_BUF_LEN - offset; if (size > left) { skb_copy_to_linear_data(skb, ring + offset, left); skb_copy_to_linear_data_offset(skb, left, ring, size - left); } else skb_copy_to_linear_data(skb, ring + offset, size); } #endif static void rtl8139_isr_ack(struct rtl8139_private *tp) { void __iomem *ioaddr = tp->mmio_addr; u16 status; status = RTL_R16 (IntrStatus) & RxAckBits; /* Clear out errors and receive interrupts */ if (likely(status != 0)) { if (unlikely(status & (RxFIFOOver | RxOverflow))) { tp->dev->stats.rx_errors++; if (status & RxFIFOOver) tp->dev->stats.rx_fifo_errors++; } RTL_W16_F (IntrStatus, RxAckBits); } } static int rtl8139_rx(struct net_device *dev, struct rtl8139_private *tp, int budget) { void __iomem *ioaddr = tp->mmio_addr; int received = 0; unsigned char *rx_ring = tp->rx_ring; unsigned int cur_rx = tp->cur_rx; unsigned int rx_size = 0; netdev_dbg(dev, "In %s(), current %04x BufAddr %04x, free to %04x, Cmd %02x\n", __func__, (u16)cur_rx, RTL_R16(RxBufAddr), RTL_R16(RxBufPtr), RTL_R8(ChipCmd)); while (netif_running(dev) && received < budget && (RTL_R8 (ChipCmd) & RxBufEmpty) == 0) { u32 ring_offset = cur_rx % RX_BUF_LEN; u32 rx_status; unsigned int pkt_size; struct sk_buff *skb; rmb(); /* read size+status of next frame from DMA ring buffer */ rx_status = le32_to_cpu (*(__le32 *) (rx_ring + ring_offset)); rx_size = rx_status >> 16; if (likely(!(dev->features & NETIF_F_RXFCS))) pkt_size = rx_size - 4; else pkt_size = rx_size; netif_dbg(tp, rx_status, dev, "%s() status %04x, size %04x, cur %04x\n", __func__, rx_status, rx_size, cur_rx); #if RTL8139_DEBUG > 2 print_hex_dump(KERN_DEBUG, "Frame contents: ", DUMP_PREFIX_OFFSET, 16, 1, &rx_ring[ring_offset], 70, true); #endif /* Packet copy from FIFO still in progress. * Theoretically, this should never happen * since EarlyRx is disabled. */ if (unlikely(rx_size == 0xfff0)) { if (!tp->fifo_copy_timeout) tp->fifo_copy_timeout = jiffies + 2; else if (time_after(jiffies, tp->fifo_copy_timeout)) { netdev_dbg(dev, "hung FIFO. Reset\n"); rx_size = 0; goto no_early_rx; } netif_dbg(tp, intr, dev, "fifo copy in progress\n"); tp->xstats.early_rx++; break; } no_early_rx: tp->fifo_copy_timeout = 0; /* If Rx err or invalid rx_size/rx_status received * (which happens if we get lost in the ring), * Rx process gets reset, so we abort any further * Rx processing. */ if (unlikely((rx_size > (MAX_ETH_FRAME_SIZE+4)) || (rx_size < 8) || (!(rx_status & RxStatusOK)))) { if ((dev->features & NETIF_F_RXALL) && (rx_size <= (MAX_ETH_FRAME_SIZE + 4)) && (rx_size >= 8) && (!(rx_status & RxStatusOK))) { /* Length is at least mostly OK, but pkt has * error. I'm hoping we can handle some of these * errors without resetting the chip. --Ben */ dev->stats.rx_errors++; if (rx_status & RxCRCErr) { dev->stats.rx_crc_errors++; goto keep_pkt; } if (rx_status & RxRunt) { dev->stats.rx_length_errors++; goto keep_pkt; } } rtl8139_rx_err (rx_status, dev, tp, ioaddr); received = -1; goto out; } keep_pkt: /* Malloc up new buffer, compatible with net-2e. */ /* Omit the four octet CRC from the length. */ skb = napi_alloc_skb(&tp->napi, pkt_size); if (likely(skb)) { #if RX_BUF_IDX == 3 wrap_copy(skb, rx_ring, ring_offset+4, pkt_size); #else skb_copy_to_linear_data (skb, &rx_ring[ring_offset + 4], pkt_size); #endif skb_put (skb, pkt_size); skb->protocol = eth_type_trans (skb, dev); u64_stats_update_begin(&tp->rx_stats.syncp); tp->rx_stats.packets++; tp->rx_stats.bytes += pkt_size; u64_stats_update_end(&tp->rx_stats.syncp); netif_receive_skb (skb); } else { dev->stats.rx_dropped++; } received++; cur_rx = (cur_rx + rx_size + 4 + 3) & ~3; RTL_W16 (RxBufPtr, (u16) (cur_rx - 16)); rtl8139_isr_ack(tp); } if (unlikely(!received || rx_size == 0xfff0)) rtl8139_isr_ack(tp); netdev_dbg(dev, "Done %s(), current %04x BufAddr %04x, free to %04x, Cmd %02x\n", __func__, cur_rx, RTL_R16(RxBufAddr), RTL_R16(RxBufPtr), RTL_R8(ChipCmd)); tp->cur_rx = cur_rx; /* * The receive buffer should be mostly empty. * Tell NAPI to reenable the Rx irq. */ if (tp->fifo_copy_timeout) received = budget; out: return received; } static void rtl8139_weird_interrupt (struct net_device *dev, struct rtl8139_private *tp, void __iomem *ioaddr, int status, int link_changed) { netdev_dbg(dev, "Abnormal interrupt, status %08x\n", status); assert (dev != NULL); assert (tp != NULL); assert (ioaddr != NULL); /* Update the error count. */ dev->stats.rx_missed_errors += RTL_R32 (RxMissed); RTL_W32 (RxMissed, 0); if ((status & RxUnderrun) && link_changed && (tp->drv_flags & HAS_LNK_CHNG)) { rtl_check_media(dev, 0); status &= ~RxUnderrun; } if (status & (RxUnderrun | RxErr)) dev->stats.rx_errors++; if (status & PCSTimeout) dev->stats.rx_length_errors++; if (status & RxUnderrun) dev->stats.rx_fifo_errors++; if (status & PCIErr) { u16 pci_cmd_status; pci_read_config_word (tp->pci_dev, PCI_STATUS, &pci_cmd_status); pci_write_config_word (tp->pci_dev, PCI_STATUS, pci_cmd_status); netdev_err(dev, "PCI Bus error %04x\n", pci_cmd_status); } } static int rtl8139_poll(struct napi_struct *napi, int budget) { struct rtl8139_private *tp = container_of(napi, struct rtl8139_private, napi); struct net_device *dev = tp->dev; void __iomem *ioaddr = tp->mmio_addr; int work_done; spin_lock(&tp->rx_lock); work_done = 0; if (likely(RTL_R16(IntrStatus) & RxAckBits)) work_done += rtl8139_rx(dev, tp, budget); if (work_done < budget) { unsigned long flags; spin_lock_irqsave(&tp->lock, flags); if (napi_complete_done(napi, work_done)) RTL_W16_F(IntrMask, rtl8139_intr_mask); spin_unlock_irqrestore(&tp->lock, flags); } spin_unlock(&tp->rx_lock); return work_done; } /* The interrupt handler does all of the Rx thread work and cleans up after the Tx thread. */ static irqreturn_t rtl8139_interrupt (int irq, void *dev_instance) { struct net_device *dev = (struct net_device *) dev_instance; struct rtl8139_private *tp = netdev_priv(dev); void __iomem *ioaddr = tp->mmio_addr; u16 status, ackstat; int link_changed = 0; /* avoid bogus "uninit" warning */ int handled = 0; spin_lock (&tp->lock); status = RTL_R16 (IntrStatus); /* shared irq? */ if (unlikely((status & rtl8139_intr_mask) == 0)) goto out; handled = 1; /* h/w no longer present (hotplug?) or major error, bail */ if (unlikely(status == 0xFFFF)) goto out; /* close possible race's with dev_close */ if (unlikely(!netif_running(dev))) { RTL_W16 (IntrMask, 0); goto out; } /* Acknowledge all of the current interrupt sources ASAP, but an first get an additional status bit from CSCR. */ if (unlikely(status & RxUnderrun)) link_changed = RTL_R16 (CSCR) & CSCR_LinkChangeBit; ackstat = status & ~(RxAckBits | TxErr); if (ackstat) RTL_W16 (IntrStatus, ackstat); /* Receive packets are processed by poll routine. If not running start it now. */ if (status & RxAckBits){ if (napi_schedule_prep(&tp->napi)) { RTL_W16_F (IntrMask, rtl8139_norx_intr_mask); __napi_schedule(&tp->napi); } } /* Check uncommon events with one test. */ if (unlikely(status & (PCIErr | PCSTimeout | RxUnderrun | RxErr))) rtl8139_weird_interrupt (dev, tp, ioaddr, status, link_changed); if (status & (TxOK | TxErr)) { rtl8139_tx_interrupt (dev, tp, ioaddr); if (status & TxErr) RTL_W16 (IntrStatus, TxErr); } out: spin_unlock (&tp->lock); netdev_dbg(dev, "exiting interrupt, intr_status=%#4.4x\n", RTL_R16(IntrStatus)); return IRQ_RETVAL(handled); } #ifdef CONFIG_NET_POLL_CONTROLLER /* * Polling receive - used by netconsole and other diagnostic tools * to allow network i/o with interrupts disabled. */ static void rtl8139_poll_controller(struct net_device *dev) { struct rtl8139_private *tp = netdev_priv(dev); const int irq = tp->pci_dev->irq; disable_irq_nosync(irq); rtl8139_interrupt(irq, dev); enable_irq(irq); } #endif static int rtl8139_set_mac_address(struct net_device *dev, void *p) { struct rtl8139_private *tp = netdev_priv(dev); void __iomem *ioaddr = tp->mmio_addr; struct sockaddr *addr = p; if (!is_valid_ether_addr(addr->sa_data)) return -EADDRNOTAVAIL; eth_hw_addr_set(dev, addr->sa_data); spin_lock_irq(&tp->lock); RTL_W8_F(Cfg9346, Cfg9346_Unlock); RTL_W32_F(MAC0 + 0, cpu_to_le32 (*(u32 *) (dev->dev_addr + 0))); RTL_W32_F(MAC0 + 4, cpu_to_le32 (*(u32 *) (dev->dev_addr + 4))); RTL_W8_F(Cfg9346, Cfg9346_Lock); spin_unlock_irq(&tp->lock); return 0; } static int rtl8139_close (struct net_device *dev) { struct rtl8139_private *tp = netdev_priv(dev); void __iomem *ioaddr = tp->mmio_addr; unsigned long flags; netif_stop_queue(dev); napi_disable(&tp->napi); netif_dbg(tp, ifdown, dev, "Shutting down ethercard, status was 0x%04x\n", RTL_R16(IntrStatus)); spin_lock_irqsave (&tp->lock, flags); /* Stop the chip's Tx and Rx DMA processes. */ RTL_W8 (ChipCmd, 0); /* Disable interrupts by clearing the interrupt mask. */ RTL_W16 (IntrMask, 0); /* Update the error counts. */ dev->stats.rx_missed_errors += RTL_R32 (RxMissed); RTL_W32 (RxMissed, 0); spin_unlock_irqrestore (&tp->lock, flags); free_irq(tp->pci_dev->irq, dev); rtl8139_tx_clear (tp); dma_free_coherent(&tp->pci_dev->dev, RX_BUF_TOT_LEN, tp->rx_ring, tp->rx_ring_dma); dma_free_coherent(&tp->pci_dev->dev, TX_BUF_TOT_LEN, tp->tx_bufs, tp->tx_bufs_dma); tp->rx_ring = NULL; tp->tx_bufs = NULL; /* Green! Put the chip in low-power mode. */ RTL_W8 (Cfg9346, Cfg9346_Unlock); if (rtl_chip_info[tp->chipset].flags & HasHltClk) RTL_W8 (HltClk, 'H'); /* 'R' would leave the clock running. */ return 0; } /* Get the ethtool Wake-on-LAN settings. Assumes that wol points to kernel memory, *wol has been initialized as {ETHTOOL_GWOL}, and other threads or interrupts aren't messing with the 8139. */ static void rtl8139_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol) { struct rtl8139_private *tp = netdev_priv(dev); void __iomem *ioaddr = tp->mmio_addr; spin_lock_irq(&tp->lock); if (rtl_chip_info[tp->chipset].flags & HasLWake) { u8 cfg3 = RTL_R8 (Config3); u8 cfg5 = RTL_R8 (Config5); wol->supported = WAKE_PHY | WAKE_MAGIC | WAKE_UCAST | WAKE_MCAST | WAKE_BCAST; wol->wolopts = 0; if (cfg3 & Cfg3_LinkUp) wol->wolopts |= WAKE_PHY; if (cfg3 & Cfg3_Magic) wol->wolopts |= WAKE_MAGIC; /* (KON)FIXME: See how netdev_set_wol() handles the following constants. */ if (cfg5 & Cfg5_UWF) wol->wolopts |= WAKE_UCAST; if (cfg5 & Cfg5_MWF) wol->wolopts |= WAKE_MCAST; if (cfg5 & Cfg5_BWF) wol->wolopts |= WAKE_BCAST; } spin_unlock_irq(&tp->lock); } /* Set the ethtool Wake-on-LAN settings. Return 0 or -errno. Assumes that wol points to kernel memory and other threads or interrupts aren't messing with the 8139. */ static int rtl8139_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol) { struct rtl8139_private *tp = netdev_priv(dev); void __iomem *ioaddr = tp->mmio_addr; u32 support; u8 cfg3, cfg5; support = ((rtl_chip_info[tp->chipset].flags & HasLWake) ? (WAKE_PHY | WAKE_MAGIC | WAKE_UCAST | WAKE_MCAST | WAKE_BCAST) : 0); if (wol->wolopts & ~support) return -EINVAL; spin_lock_irq(&tp->lock); cfg3 = RTL_R8 (Config3) & ~(Cfg3_LinkUp | Cfg3_Magic); if (wol->wolopts & WAKE_PHY) cfg3 |= Cfg3_LinkUp; if (wol->wolopts & WAKE_MAGIC) cfg3 |= Cfg3_Magic; RTL_W8 (Cfg9346, Cfg9346_Unlock); RTL_W8 (Config3, cfg3); RTL_W8 (Cfg9346, Cfg9346_Lock); cfg5 = RTL_R8 (Config5) & ~(Cfg5_UWF | Cfg5_MWF | Cfg5_BWF); /* (KON)FIXME: These are untested. We may have to set the CRC0, Wakeup0 and LSBCRC0 registers too, but I have no documentation. */ if (wol->wolopts & WAKE_UCAST) cfg5 |= Cfg5_UWF; if (wol->wolopts & WAKE_MCAST) cfg5 |= Cfg5_MWF; if (wol->wolopts & WAKE_BCAST) cfg5 |= Cfg5_BWF; RTL_W8 (Config5, cfg5); /* need not unlock via Cfg9346 */ spin_unlock_irq(&tp->lock); return 0; } static void rtl8139_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { struct rtl8139_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 rtl8139_get_link_ksettings(struct net_device *dev, struct ethtool_link_ksettings *cmd) { struct rtl8139_private *tp = netdev_priv(dev); spin_lock_irq(&tp->lock); mii_ethtool_get_link_ksettings(&tp->mii, cmd); spin_unlock_irq(&tp->lock); return 0; } static int rtl8139_set_link_ksettings(struct net_device *dev, const struct ethtool_link_ksettings *cmd) { struct rtl8139_private *tp = netdev_priv(dev); int rc; spin_lock_irq(&tp->lock); rc = mii_ethtool_set_link_ksettings(&tp->mii, cmd); spin_unlock_irq(&tp->lock); return rc; } static int rtl8139_nway_reset(struct net_device *dev) { struct rtl8139_private *tp = netdev_priv(dev); return mii_nway_restart(&tp->mii); } static u32 rtl8139_get_link(struct net_device *dev) { struct rtl8139_private *tp = netdev_priv(dev); return mii_link_ok(&tp->mii); } static u32 rtl8139_get_msglevel(struct net_device *dev) { struct rtl8139_private *tp = netdev_priv(dev); return tp->msg_enable; } static void rtl8139_set_msglevel(struct net_device *dev, u32 datum) { struct rtl8139_private *tp = netdev_priv(dev); tp->msg_enable = datum; } static int rtl8139_get_regs_len(struct net_device *dev) { struct rtl8139_private *tp; /* TODO: we are too slack to do reg dumping for pio, for now */ if (use_io) return 0; tp = netdev_priv(dev); return tp->regs_len; } static void rtl8139_get_regs(struct net_device *dev, struct ethtool_regs *regs, void *regbuf) { struct rtl8139_private *tp; /* TODO: we are too slack to do reg dumping for pio, for now */ if (use_io) return; tp = netdev_priv(dev); regs->version = RTL_REGS_VER; spin_lock_irq(&tp->lock); memcpy_fromio(regbuf, tp->mmio_addr, regs->len); spin_unlock_irq(&tp->lock); } static int rtl8139_get_sset_count(struct net_device *dev, int sset) { switch (sset) { case ETH_SS_STATS: return RTL_NUM_STATS; default: return -EOPNOTSUPP; } } static void rtl8139_get_ethtool_stats(struct net_device *dev, struct ethtool_stats *stats, u64 *data) { struct rtl8139_private *tp = netdev_priv(dev); data[0] = tp->xstats.early_rx; data[1] = tp->xstats.tx_buf_mapped; data[2] = tp->xstats.tx_timeouts; data[3] = tp->xstats.rx_lost_in_ring; } static void rtl8139_get_strings(struct net_device *dev, u32 stringset, u8 *data) { memcpy(data, ethtool_stats_keys, sizeof(ethtool_stats_keys)); } static const struct ethtool_ops rtl8139_ethtool_ops = { .get_drvinfo = rtl8139_get_drvinfo, .get_regs_len = rtl8139_get_regs_len, .get_regs = rtl8139_get_regs, .nway_reset = rtl8139_nway_reset, .get_link = rtl8139_get_link, .get_msglevel = rtl8139_get_msglevel, .set_msglevel = rtl8139_set_msglevel, .get_wol = rtl8139_get_wol, .set_wol = rtl8139_set_wol, .get_strings = rtl8139_get_strings, .get_sset_count = rtl8139_get_sset_count, .get_ethtool_stats = rtl8139_get_ethtool_stats, .get_link_ksettings = rtl8139_get_link_ksettings, .set_link_ksettings = rtl8139_set_link_ksettings, }; static int netdev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd) { struct rtl8139_private *tp = netdev_priv(dev); int rc; if (!netif_running(dev)) return -EINVAL; spin_lock_irq(&tp->lock); rc = generic_mii_ioctl(&tp->mii, if_mii(rq), cmd, NULL); spin_unlock_irq(&tp->lock); return rc; } static void rtl8139_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats) { struct rtl8139_private *tp = netdev_priv(dev); void __iomem *ioaddr = tp->mmio_addr; unsigned long flags; unsigned int start; if (netif_running(dev)) { spin_lock_irqsave (&tp->lock, flags); dev->stats.rx_missed_errors += RTL_R32 (RxMissed); RTL_W32 (RxMissed, 0); spin_unlock_irqrestore (&tp->lock, flags); } netdev_stats_to_stats64(stats, &dev->stats); do { start = u64_stats_fetch_begin(&tp->rx_stats.syncp); stats->rx_packets = tp->rx_stats.packets; stats->rx_bytes = tp->rx_stats.bytes; } while (u64_stats_fetch_retry(&tp->rx_stats.syncp, start)); do { start = u64_stats_fetch_begin(&tp->tx_stats.syncp); stats->tx_packets = tp->tx_stats.packets; stats->tx_bytes = tp->tx_stats.bytes; } while (u64_stats_fetch_retry(&tp->tx_stats.syncp, start)); } /* Set or clear the multicast filter for this adaptor. This routine is not state sensitive and need not be SMP locked. */ static void __set_rx_mode (struct net_device *dev) { struct rtl8139_private *tp = netdev_priv(dev); void __iomem *ioaddr = tp->mmio_addr; u32 mc_filter[2]; /* Multicast hash filter */ int rx_mode; u32 tmp; netdev_dbg(dev, "rtl8139_set_rx_mode(%04x) done -- Rx config %08x\n", dev->flags, RTL_R32(RxConfig)); /* Note: do not reorder, GCC is clever about common statements. */ 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) >> 26; mc_filter[bit_nr >> 5] |= 1 << (bit_nr & 31); rx_mode |= AcceptMulticast; } } if (dev->features & NETIF_F_RXALL) rx_mode |= (AcceptErr | AcceptRunt); /* We can safely update without stopping the chip. */ tmp = rtl8139_rx_config | rx_mode; if (tp->rx_config != tmp) { RTL_W32_F (RxConfig, tmp); tp->rx_config = tmp; } RTL_W32_F (MAR0 + 0, mc_filter[0]); RTL_W32_F (MAR0 + 4, mc_filter[1]); } static void rtl8139_set_rx_mode (struct net_device *dev) { unsigned long flags; struct rtl8139_private *tp = netdev_priv(dev); spin_lock_irqsave (&tp->lock, flags); __set_rx_mode(dev); spin_unlock_irqrestore (&tp->lock, flags); } static int __maybe_unused rtl8139_suspend(struct device *device) { struct net_device *dev = dev_get_drvdata(device); struct rtl8139_private *tp = netdev_priv(dev); void __iomem *ioaddr = tp->mmio_addr; unsigned long flags; if (!netif_running (dev)) return 0; netif_device_detach (dev); spin_lock_irqsave (&tp->lock, flags); /* Disable interrupts, stop Tx and Rx. */ RTL_W16 (IntrMask, 0); RTL_W8 (ChipCmd, 0); /* Update the error counts. */ dev->stats.rx_missed_errors += RTL_R32 (RxMissed); RTL_W32 (RxMissed, 0); spin_unlock_irqrestore (&tp->lock, flags); return 0; } static int __maybe_unused rtl8139_resume(struct device *device) { struct net_device *dev = dev_get_drvdata(device); if (!netif_running (dev)) return 0; rtl8139_init_ring (dev); rtl8139_hw_start (dev); netif_device_attach (dev); return 0; } static SIMPLE_DEV_PM_OPS(rtl8139_pm_ops, rtl8139_suspend, rtl8139_resume); static struct pci_driver rtl8139_pci_driver = { .name = DRV_NAME, .id_table = rtl8139_pci_tbl, .probe = rtl8139_init_one, .remove = rtl8139_remove_one, .driver.pm = &rtl8139_pm_ops, }; static int __init rtl8139_init_module (void) { /* when we're a module, we always print a version message, * even if no 8139 board is found. */ #ifdef MODULE pr_info(RTL8139_DRIVER_NAME "\n"); #endif return pci_register_driver(&rtl8139_pci_driver); } static void __exit rtl8139_cleanup_module (void) { pci_unregister_driver (&rtl8139_pci_driver); } module_init(rtl8139_init_module); module_exit(rtl8139_cleanup_module);
linux-master
drivers/net/ethernet/realtek/8139too.c
// SPDX-License-Identifier: GPL-2.0-only /* * r8169.c: RealTek 8169/8168/8101 ethernet driver. * * Copyright (c) 2002 ShuChen <[email protected]> * Copyright (c) 2003 - 2007 Francois Romieu <[email protected]> * Copyright (c) a lot of people too. Please respect their work. * * See MAINTAINERS file for support contact information. */ #include <linux/module.h> #include <linux/pci.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/clk.h> #include <linux/delay.h> #include <linux/ethtool.h> #include <linux/phy.h> #include <linux/if_vlan.h> #include <linux/in.h> #include <linux/io.h> #include <linux/ip.h> #include <linux/tcp.h> #include <linux/interrupt.h> #include <linux/dma-mapping.h> #include <linux/pm_runtime.h> #include <linux/bitfield.h> #include <linux/prefetch.h> #include <linux/ipv6.h> #include <asm/unaligned.h> #include <net/ip6_checksum.h> #include <net/netdev_queues.h> #include "r8169.h" #include "r8169_firmware.h" #define FIRMWARE_8168D_1 "rtl_nic/rtl8168d-1.fw" #define FIRMWARE_8168D_2 "rtl_nic/rtl8168d-2.fw" #define FIRMWARE_8168E_1 "rtl_nic/rtl8168e-1.fw" #define FIRMWARE_8168E_2 "rtl_nic/rtl8168e-2.fw" #define FIRMWARE_8168E_3 "rtl_nic/rtl8168e-3.fw" #define FIRMWARE_8168F_1 "rtl_nic/rtl8168f-1.fw" #define FIRMWARE_8168F_2 "rtl_nic/rtl8168f-2.fw" #define FIRMWARE_8105E_1 "rtl_nic/rtl8105e-1.fw" #define FIRMWARE_8402_1 "rtl_nic/rtl8402-1.fw" #define FIRMWARE_8411_1 "rtl_nic/rtl8411-1.fw" #define FIRMWARE_8411_2 "rtl_nic/rtl8411-2.fw" #define FIRMWARE_8106E_1 "rtl_nic/rtl8106e-1.fw" #define FIRMWARE_8106E_2 "rtl_nic/rtl8106e-2.fw" #define FIRMWARE_8168G_2 "rtl_nic/rtl8168g-2.fw" #define FIRMWARE_8168G_3 "rtl_nic/rtl8168g-3.fw" #define FIRMWARE_8168H_2 "rtl_nic/rtl8168h-2.fw" #define FIRMWARE_8168FP_3 "rtl_nic/rtl8168fp-3.fw" #define FIRMWARE_8107E_2 "rtl_nic/rtl8107e-2.fw" #define FIRMWARE_8125A_3 "rtl_nic/rtl8125a-3.fw" #define FIRMWARE_8125B_2 "rtl_nic/rtl8125b-2.fw" /* Maximum number of multicast addresses to filter (vs. Rx-all-multicast). The RTL chips use a 64 element hash table based on the Ethernet CRC. */ #define MC_FILTER_LIMIT 32 #define TX_DMA_BURST 7 /* Maximum PCI burst, '7' is unlimited */ #define InterFrameGap 0x03 /* 3 means InterFrameGap = the shortest one */ #define R8169_REGS_SIZE 256 #define R8169_RX_BUF_SIZE (SZ_16K - 1) #define NUM_TX_DESC 256 /* Number of Tx descriptor registers */ #define NUM_RX_DESC 256 /* Number of Rx descriptor registers */ #define R8169_TX_RING_BYTES (NUM_TX_DESC * sizeof(struct TxDesc)) #define R8169_RX_RING_BYTES (NUM_RX_DESC * sizeof(struct RxDesc)) #define R8169_TX_STOP_THRS (MAX_SKB_FRAGS + 1) #define R8169_TX_START_THRS (2 * R8169_TX_STOP_THRS) #define OCP_STD_PHY_BASE 0xa400 #define RTL_CFG_NO_GBIT 1 /* write/read MMIO register */ #define RTL_W8(tp, reg, val8) writeb((val8), tp->mmio_addr + (reg)) #define RTL_W16(tp, reg, val16) writew((val16), tp->mmio_addr + (reg)) #define RTL_W32(tp, reg, val32) writel((val32), tp->mmio_addr + (reg)) #define RTL_R8(tp, reg) readb(tp->mmio_addr + (reg)) #define RTL_R16(tp, reg) readw(tp->mmio_addr + (reg)) #define RTL_R32(tp, reg) readl(tp->mmio_addr + (reg)) #define JUMBO_4K (4 * SZ_1K - VLAN_ETH_HLEN - ETH_FCS_LEN) #define JUMBO_6K (6 * SZ_1K - VLAN_ETH_HLEN - ETH_FCS_LEN) #define JUMBO_7K (7 * SZ_1K - VLAN_ETH_HLEN - ETH_FCS_LEN) #define JUMBO_9K (9 * SZ_1K - VLAN_ETH_HLEN - ETH_FCS_LEN) static const struct { const char *name; const char *fw_name; } rtl_chip_infos[] = { /* PCI devices. */ [RTL_GIGA_MAC_VER_02] = {"RTL8169s" }, [RTL_GIGA_MAC_VER_03] = {"RTL8110s" }, [RTL_GIGA_MAC_VER_04] = {"RTL8169sb/8110sb" }, [RTL_GIGA_MAC_VER_05] = {"RTL8169sc/8110sc" }, [RTL_GIGA_MAC_VER_06] = {"RTL8169sc/8110sc" }, /* PCI-E devices. */ [RTL_GIGA_MAC_VER_07] = {"RTL8102e" }, [RTL_GIGA_MAC_VER_08] = {"RTL8102e" }, [RTL_GIGA_MAC_VER_09] = {"RTL8102e/RTL8103e" }, [RTL_GIGA_MAC_VER_10] = {"RTL8101e/RTL8100e" }, [RTL_GIGA_MAC_VER_11] = {"RTL8168b/8111b" }, [RTL_GIGA_MAC_VER_14] = {"RTL8401" }, [RTL_GIGA_MAC_VER_17] = {"RTL8168b/8111b" }, [RTL_GIGA_MAC_VER_18] = {"RTL8168cp/8111cp" }, [RTL_GIGA_MAC_VER_19] = {"RTL8168c/8111c" }, [RTL_GIGA_MAC_VER_20] = {"RTL8168c/8111c" }, [RTL_GIGA_MAC_VER_21] = {"RTL8168c/8111c" }, [RTL_GIGA_MAC_VER_22] = {"RTL8168c/8111c" }, [RTL_GIGA_MAC_VER_23] = {"RTL8168cp/8111cp" }, [RTL_GIGA_MAC_VER_24] = {"RTL8168cp/8111cp" }, [RTL_GIGA_MAC_VER_25] = {"RTL8168d/8111d", FIRMWARE_8168D_1}, [RTL_GIGA_MAC_VER_26] = {"RTL8168d/8111d", FIRMWARE_8168D_2}, [RTL_GIGA_MAC_VER_28] = {"RTL8168dp/8111dp" }, [RTL_GIGA_MAC_VER_29] = {"RTL8105e", FIRMWARE_8105E_1}, [RTL_GIGA_MAC_VER_30] = {"RTL8105e", FIRMWARE_8105E_1}, [RTL_GIGA_MAC_VER_31] = {"RTL8168dp/8111dp" }, [RTL_GIGA_MAC_VER_32] = {"RTL8168e/8111e", FIRMWARE_8168E_1}, [RTL_GIGA_MAC_VER_33] = {"RTL8168e/8111e", FIRMWARE_8168E_2}, [RTL_GIGA_MAC_VER_34] = {"RTL8168evl/8111evl", FIRMWARE_8168E_3}, [RTL_GIGA_MAC_VER_35] = {"RTL8168f/8111f", FIRMWARE_8168F_1}, [RTL_GIGA_MAC_VER_36] = {"RTL8168f/8111f", FIRMWARE_8168F_2}, [RTL_GIGA_MAC_VER_37] = {"RTL8402", FIRMWARE_8402_1 }, [RTL_GIGA_MAC_VER_38] = {"RTL8411", FIRMWARE_8411_1 }, [RTL_GIGA_MAC_VER_39] = {"RTL8106e", FIRMWARE_8106E_1}, [RTL_GIGA_MAC_VER_40] = {"RTL8168g/8111g", FIRMWARE_8168G_2}, [RTL_GIGA_MAC_VER_42] = {"RTL8168gu/8111gu", FIRMWARE_8168G_3}, [RTL_GIGA_MAC_VER_43] = {"RTL8106eus", FIRMWARE_8106E_2}, [RTL_GIGA_MAC_VER_44] = {"RTL8411b", FIRMWARE_8411_2 }, [RTL_GIGA_MAC_VER_46] = {"RTL8168h/8111h", FIRMWARE_8168H_2}, [RTL_GIGA_MAC_VER_48] = {"RTL8107e", FIRMWARE_8107E_2}, [RTL_GIGA_MAC_VER_51] = {"RTL8168ep/8111ep" }, [RTL_GIGA_MAC_VER_52] = {"RTL8168fp/RTL8117", FIRMWARE_8168FP_3}, [RTL_GIGA_MAC_VER_53] = {"RTL8168fp/RTL8117", }, [RTL_GIGA_MAC_VER_61] = {"RTL8125A", FIRMWARE_8125A_3}, /* reserve 62 for CFG_METHOD_4 in the vendor driver */ [RTL_GIGA_MAC_VER_63] = {"RTL8125B", FIRMWARE_8125B_2}, }; static const struct pci_device_id rtl8169_pci_tbl[] = { { PCI_VDEVICE(REALTEK, 0x2502) }, { PCI_VDEVICE(REALTEK, 0x2600) }, { PCI_VDEVICE(REALTEK, 0x8129) }, { PCI_VDEVICE(REALTEK, 0x8136), RTL_CFG_NO_GBIT }, { PCI_VDEVICE(REALTEK, 0x8161) }, { PCI_VDEVICE(REALTEK, 0x8162) }, { PCI_VDEVICE(REALTEK, 0x8167) }, { PCI_VDEVICE(REALTEK, 0x8168) }, { PCI_VDEVICE(NCUBE, 0x8168) }, { PCI_VDEVICE(REALTEK, 0x8169) }, { PCI_VENDOR_ID_DLINK, 0x4300, PCI_VENDOR_ID_DLINK, 0x4b10, 0, 0 }, { PCI_VDEVICE(DLINK, 0x4300) }, { PCI_VDEVICE(DLINK, 0x4302) }, { PCI_VDEVICE(AT, 0xc107) }, { PCI_VDEVICE(USR, 0x0116) }, { PCI_VENDOR_ID_LINKSYS, 0x1032, PCI_ANY_ID, 0x0024 }, { 0x0001, 0x8168, PCI_ANY_ID, 0x2410 }, { PCI_VDEVICE(REALTEK, 0x8125) }, { PCI_VDEVICE(REALTEK, 0x3000) }, {} }; MODULE_DEVICE_TABLE(pci, rtl8169_pci_tbl); enum rtl_registers { MAC0 = 0, /* Ethernet hardware address. */ MAC4 = 4, MAR0 = 8, /* Multicast filter. */ CounterAddrLow = 0x10, CounterAddrHigh = 0x14, TxDescStartAddrLow = 0x20, TxDescStartAddrHigh = 0x24, TxHDescStartAddrLow = 0x28, TxHDescStartAddrHigh = 0x2c, FLASH = 0x30, ERSR = 0x36, ChipCmd = 0x37, TxPoll = 0x38, IntrMask = 0x3c, IntrStatus = 0x3e, TxConfig = 0x40, #define TXCFG_AUTO_FIFO (1 << 7) /* 8111e-vl */ #define TXCFG_EMPTY (1 << 11) /* 8111e-vl */ RxConfig = 0x44, #define RX128_INT_EN (1 << 15) /* 8111c and later */ #define RX_MULTI_EN (1 << 14) /* 8111c only */ #define RXCFG_FIFO_SHIFT 13 /* No threshold before first PCI xfer */ #define RX_FIFO_THRESH (7 << RXCFG_FIFO_SHIFT) #define RX_EARLY_OFF (1 << 11) #define RXCFG_DMA_SHIFT 8 /* Unlimited maximum PCI burst. */ #define RX_DMA_BURST (7 << RXCFG_DMA_SHIFT) Cfg9346 = 0x50, Config0 = 0x51, Config1 = 0x52, Config2 = 0x53, #define PME_SIGNAL (1 << 5) /* 8168c and later */ Config3 = 0x54, Config4 = 0x55, Config5 = 0x56, PHYAR = 0x60, PHYstatus = 0x6c, RxMaxSize = 0xda, CPlusCmd = 0xe0, IntrMitigate = 0xe2, #define RTL_COALESCE_TX_USECS GENMASK(15, 12) #define RTL_COALESCE_TX_FRAMES GENMASK(11, 8) #define RTL_COALESCE_RX_USECS GENMASK(7, 4) #define RTL_COALESCE_RX_FRAMES GENMASK(3, 0) #define RTL_COALESCE_T_MAX 0x0fU #define RTL_COALESCE_FRAME_MAX (RTL_COALESCE_T_MAX * 4) RxDescAddrLow = 0xe4, RxDescAddrHigh = 0xe8, EarlyTxThres = 0xec, /* 8169. Unit of 32 bytes. */ #define NoEarlyTx 0x3f /* Max value : no early transmit. */ MaxTxPacketSize = 0xec, /* 8101/8168. Unit of 128 bytes. */ #define TxPacketMax (8064 >> 7) #define EarlySize 0x27 FuncEvent = 0xf0, FuncEventMask = 0xf4, FuncPresetState = 0xf8, IBCR0 = 0xf8, IBCR2 = 0xf9, IBIMR0 = 0xfa, IBISR0 = 0xfb, FuncForceEvent = 0xfc, }; enum rtl8168_8101_registers { CSIDR = 0x64, CSIAR = 0x68, #define CSIAR_FLAG 0x80000000 #define CSIAR_WRITE_CMD 0x80000000 #define CSIAR_BYTE_ENABLE 0x0000f000 #define CSIAR_ADDR_MASK 0x00000fff PMCH = 0x6f, #define D3COLD_NO_PLL_DOWN BIT(7) #define D3HOT_NO_PLL_DOWN BIT(6) #define D3_NO_PLL_DOWN (BIT(7) | BIT(6)) EPHYAR = 0x80, #define EPHYAR_FLAG 0x80000000 #define EPHYAR_WRITE_CMD 0x80000000 #define EPHYAR_REG_MASK 0x1f #define EPHYAR_REG_SHIFT 16 #define EPHYAR_DATA_MASK 0xffff DLLPR = 0xd0, #define PFM_EN (1 << 6) #define TX_10M_PS_EN (1 << 7) DBG_REG = 0xd1, #define FIX_NAK_1 (1 << 4) #define FIX_NAK_2 (1 << 3) TWSI = 0xd2, MCU = 0xd3, #define NOW_IS_OOB (1 << 7) #define TX_EMPTY (1 << 5) #define RX_EMPTY (1 << 4) #define RXTX_EMPTY (TX_EMPTY | RX_EMPTY) #define EN_NDP (1 << 3) #define EN_OOB_RESET (1 << 2) #define LINK_LIST_RDY (1 << 1) EFUSEAR = 0xdc, #define EFUSEAR_FLAG 0x80000000 #define EFUSEAR_WRITE_CMD 0x80000000 #define EFUSEAR_READ_CMD 0x00000000 #define EFUSEAR_REG_MASK 0x03ff #define EFUSEAR_REG_SHIFT 8 #define EFUSEAR_DATA_MASK 0xff MISC_1 = 0xf2, #define PFM_D3COLD_EN (1 << 6) }; enum rtl8168_registers { LED_FREQ = 0x1a, EEE_LED = 0x1b, ERIDR = 0x70, ERIAR = 0x74, #define ERIAR_FLAG 0x80000000 #define ERIAR_WRITE_CMD 0x80000000 #define ERIAR_READ_CMD 0x00000000 #define ERIAR_ADDR_BYTE_ALIGN 4 #define ERIAR_TYPE_SHIFT 16 #define ERIAR_EXGMAC (0x00 << ERIAR_TYPE_SHIFT) #define ERIAR_MSIX (0x01 << ERIAR_TYPE_SHIFT) #define ERIAR_ASF (0x02 << ERIAR_TYPE_SHIFT) #define ERIAR_OOB (0x02 << ERIAR_TYPE_SHIFT) #define ERIAR_MASK_SHIFT 12 #define ERIAR_MASK_0001 (0x1 << ERIAR_MASK_SHIFT) #define ERIAR_MASK_0011 (0x3 << ERIAR_MASK_SHIFT) #define ERIAR_MASK_0100 (0x4 << ERIAR_MASK_SHIFT) #define ERIAR_MASK_0101 (0x5 << ERIAR_MASK_SHIFT) #define ERIAR_MASK_1111 (0xf << ERIAR_MASK_SHIFT) EPHY_RXER_NUM = 0x7c, OCPDR = 0xb0, /* OCP GPHY access */ #define OCPDR_WRITE_CMD 0x80000000 #define OCPDR_READ_CMD 0x00000000 #define OCPDR_REG_MASK 0x7f #define OCPDR_GPHY_REG_SHIFT 16 #define OCPDR_DATA_MASK 0xffff OCPAR = 0xb4, #define OCPAR_FLAG 0x80000000 #define OCPAR_GPHY_WRITE_CMD 0x8000f060 #define OCPAR_GPHY_READ_CMD 0x0000f060 GPHY_OCP = 0xb8, RDSAR1 = 0xd0, /* 8168c only. Undocumented on 8168dp */ MISC = 0xf0, /* 8168e only. */ #define TXPLA_RST (1 << 29) #define DISABLE_LAN_EN (1 << 23) /* Enable GPIO pin */ #define PWM_EN (1 << 22) #define RXDV_GATED_EN (1 << 19) #define EARLY_TALLY_EN (1 << 16) }; enum rtl8125_registers { IntrMask_8125 = 0x38, IntrStatus_8125 = 0x3c, TxPoll_8125 = 0x90, MAC0_BKP = 0x19e0, EEE_TXIDLE_TIMER_8125 = 0x6048, }; #define RX_VLAN_INNER_8125 BIT(22) #define RX_VLAN_OUTER_8125 BIT(23) #define RX_VLAN_8125 (RX_VLAN_INNER_8125 | RX_VLAN_OUTER_8125) #define RX_FETCH_DFLT_8125 (8 << 27) enum rtl_register_content { /* InterruptStatusBits */ SYSErr = 0x8000, PCSTimeout = 0x4000, SWInt = 0x0100, TxDescUnavail = 0x0080, RxFIFOOver = 0x0040, LinkChg = 0x0020, RxOverflow = 0x0010, TxErr = 0x0008, TxOK = 0x0004, RxErr = 0x0002, RxOK = 0x0001, /* RxStatusDesc */ RxRWT = (1 << 22), RxRES = (1 << 21), RxRUNT = (1 << 20), RxCRC = (1 << 19), /* ChipCmdBits */ StopReq = 0x80, CmdReset = 0x10, CmdRxEnb = 0x08, CmdTxEnb = 0x04, RxBufEmpty = 0x01, /* TXPoll register p.5 */ HPQ = 0x80, /* Poll cmd on the high prio queue */ NPQ = 0x40, /* Poll cmd on the low prio queue */ FSWInt = 0x01, /* Forced software interrupt */ /* Cfg9346Bits */ Cfg9346_Lock = 0x00, Cfg9346_Unlock = 0xc0, /* rx_mode_bits */ AcceptErr = 0x20, AcceptRunt = 0x10, #define RX_CONFIG_ACCEPT_ERR_MASK 0x30 AcceptBroadcast = 0x08, AcceptMulticast = 0x04, AcceptMyPhys = 0x02, AcceptAllPhys = 0x01, #define RX_CONFIG_ACCEPT_OK_MASK 0x0f #define RX_CONFIG_ACCEPT_MASK 0x3f /* TxConfigBits */ TxInterFrameGapShift = 24, TxDMAShift = 8, /* DMA burst value (0-7) is shift this many bits */ /* Config1 register p.24 */ LEDS1 = (1 << 7), LEDS0 = (1 << 6), Speed_down = (1 << 4), MEMMAP = (1 << 3), IOMAP = (1 << 2), VPD = (1 << 1), PMEnable = (1 << 0), /* Power Management Enable */ /* Config2 register p. 25 */ ClkReqEn = (1 << 7), /* Clock Request Enable */ MSIEnable = (1 << 5), /* 8169 only. Reserved in the 8168. */ PCI_Clock_66MHz = 0x01, PCI_Clock_33MHz = 0x00, /* Config3 register p.25 */ MagicPacket = (1 << 5), /* Wake up when receives a Magic Packet */ LinkUp = (1 << 4), /* Wake up when the cable connection is re-established */ Jumbo_En0 = (1 << 2), /* 8168 only. Reserved in the 8168b */ Rdy_to_L23 = (1 << 1), /* L23 Enable */ Beacon_en = (1 << 0), /* 8168 only. Reserved in the 8168b */ /* Config4 register */ Jumbo_En1 = (1 << 1), /* 8168 only. Reserved in the 8168b */ /* Config5 register p.27 */ BWF = (1 << 6), /* Accept Broadcast wakeup frame */ MWF = (1 << 5), /* Accept Multicast wakeup frame */ UWF = (1 << 4), /* Accept Unicast wakeup frame */ Spi_en = (1 << 3), LanWake = (1 << 1), /* LanWake enable/disable */ PMEStatus = (1 << 0), /* PME status can be reset by PCI RST# */ ASPM_en = (1 << 0), /* ASPM enable */ /* CPlusCmd p.31 */ EnableBist = (1 << 15), // 8168 8101 Mac_dbgo_oe = (1 << 14), // 8168 8101 EnAnaPLL = (1 << 14), // 8169 Normal_mode = (1 << 13), // unused Force_half_dup = (1 << 12), // 8168 8101 Force_rxflow_en = (1 << 11), // 8168 8101 Force_txflow_en = (1 << 10), // 8168 8101 Cxpl_dbg_sel = (1 << 9), // 8168 8101 ASF = (1 << 8), // 8168 8101 PktCntrDisable = (1 << 7), // 8168 8101 Mac_dbgo_sel = 0x001c, // 8168 RxVlan = (1 << 6), RxChkSum = (1 << 5), PCIDAC = (1 << 4), PCIMulRW = (1 << 3), #define INTT_MASK GENMASK(1, 0) #define CPCMD_MASK (Normal_mode | RxVlan | RxChkSum | INTT_MASK) /* rtl8169_PHYstatus */ TBI_Enable = 0x80, TxFlowCtrl = 0x40, RxFlowCtrl = 0x20, _1000bpsF = 0x10, _100bps = 0x08, _10bps = 0x04, LinkStatus = 0x02, FullDup = 0x01, /* ResetCounterCommand */ CounterReset = 0x1, /* DumpCounterCommand */ CounterDump = 0x8, /* magic enable v2 */ MagicPacket_v2 = (1 << 16), /* Wake up when receives a Magic Packet */ }; enum rtl_desc_bit { /* First doubleword. */ DescOwn = (1 << 31), /* Descriptor is owned by NIC */ RingEnd = (1 << 30), /* End of descriptor ring */ FirstFrag = (1 << 29), /* First segment of a packet */ LastFrag = (1 << 28), /* Final segment of a packet */ }; /* Generic case. */ enum rtl_tx_desc_bit { /* First doubleword. */ TD_LSO = (1 << 27), /* Large Send Offload */ #define TD_MSS_MAX 0x07ffu /* MSS value */ /* Second doubleword. */ TxVlanTag = (1 << 17), /* Add VLAN tag */ }; /* 8169, 8168b and 810x except 8102e. */ enum rtl_tx_desc_bit_0 { /* First doubleword. */ #define TD0_MSS_SHIFT 16 /* MSS position (11 bits) */ TD0_TCP_CS = (1 << 16), /* Calculate TCP/IP checksum */ TD0_UDP_CS = (1 << 17), /* Calculate UDP/IP checksum */ TD0_IP_CS = (1 << 18), /* Calculate IP checksum */ }; /* 8102e, 8168c and beyond. */ enum rtl_tx_desc_bit_1 { /* First doubleword. */ TD1_GTSENV4 = (1 << 26), /* Giant Send for IPv4 */ TD1_GTSENV6 = (1 << 25), /* Giant Send for IPv6 */ #define GTTCPHO_SHIFT 18 #define GTTCPHO_MAX 0x7f /* Second doubleword. */ #define TCPHO_SHIFT 18 #define TCPHO_MAX 0x3ff #define TD1_MSS_SHIFT 18 /* MSS position (11 bits) */ TD1_IPv6_CS = (1 << 28), /* Calculate IPv6 checksum */ TD1_IPv4_CS = (1 << 29), /* Calculate IPv4 checksum */ TD1_TCP_CS = (1 << 30), /* Calculate TCP/IP checksum */ TD1_UDP_CS = (1 << 31), /* Calculate UDP/IP checksum */ }; enum rtl_rx_desc_bit { /* Rx private */ PID1 = (1 << 18), /* Protocol ID bit 1/2 */ PID0 = (1 << 17), /* Protocol ID bit 0/2 */ #define RxProtoUDP (PID1) #define RxProtoTCP (PID0) #define RxProtoIP (PID1 | PID0) #define RxProtoMask RxProtoIP IPFail = (1 << 16), /* IP checksum failed */ UDPFail = (1 << 15), /* UDP/IP checksum failed */ TCPFail = (1 << 14), /* TCP/IP checksum failed */ #define RxCSFailMask (IPFail | UDPFail | TCPFail) RxVlanTag = (1 << 16), /* VLAN tag available */ }; #define RTL_GSO_MAX_SIZE_V1 32000 #define RTL_GSO_MAX_SEGS_V1 24 #define RTL_GSO_MAX_SIZE_V2 64000 #define RTL_GSO_MAX_SEGS_V2 64 struct TxDesc { __le32 opts1; __le32 opts2; __le64 addr; }; struct RxDesc { __le32 opts1; __le32 opts2; __le64 addr; }; struct ring_info { struct sk_buff *skb; u32 len; }; struct rtl8169_counters { __le64 tx_packets; __le64 rx_packets; __le64 tx_errors; __le32 rx_errors; __le16 rx_missed; __le16 align_errors; __le32 tx_one_collision; __le32 tx_multi_collision; __le64 rx_unicast; __le64 rx_broadcast; __le32 rx_multicast; __le16 tx_aborted; __le16 tx_underun; }; struct rtl8169_tc_offsets { bool inited; __le64 tx_errors; __le32 tx_multi_collision; __le16 tx_aborted; __le16 rx_missed; }; enum rtl_flag { RTL_FLAG_TASK_ENABLED = 0, RTL_FLAG_TASK_RESET_PENDING, RTL_FLAG_TASK_TX_TIMEOUT, RTL_FLAG_MAX }; enum rtl_dash_type { RTL_DASH_NONE, RTL_DASH_DP, RTL_DASH_EP, }; struct rtl8169_private { void __iomem *mmio_addr; /* memory map physical address */ struct pci_dev *pci_dev; struct net_device *dev; struct phy_device *phydev; struct napi_struct napi; enum mac_version mac_version; enum rtl_dash_type dash_type; u32 cur_rx; /* Index into the Rx descriptor buffer of next Rx pkt. */ u32 cur_tx; /* Index into the Tx descriptor buffer of next Rx pkt. */ u32 dirty_tx; struct TxDesc *TxDescArray; /* 256-aligned Tx descriptor ring */ struct RxDesc *RxDescArray; /* 256-aligned Rx descriptor ring */ dma_addr_t TxPhyAddr; dma_addr_t RxPhyAddr; struct page *Rx_databuff[NUM_RX_DESC]; /* Rx data buffers */ struct ring_info tx_skb[NUM_TX_DESC]; /* Tx data buffers */ u16 cp_cmd; u32 irq_mask; int irq; struct clk *clk; struct { DECLARE_BITMAP(flags, RTL_FLAG_MAX); struct work_struct work; } wk; raw_spinlock_t config25_lock; raw_spinlock_t mac_ocp_lock; raw_spinlock_t cfg9346_usage_lock; int cfg9346_usage_count; unsigned supports_gmii:1; unsigned aspm_manageable:1; dma_addr_t counters_phys_addr; struct rtl8169_counters *counters; struct rtl8169_tc_offsets tc_offset; u32 saved_wolopts; int eee_adv; const char *fw_name; struct rtl_fw *rtl_fw; u32 ocp_base; }; typedef void (*rtl_generic_fct)(struct rtl8169_private *tp); MODULE_AUTHOR("Realtek and the Linux r8169 crew <[email protected]>"); MODULE_DESCRIPTION("RealTek RTL-8169 Gigabit Ethernet driver"); MODULE_SOFTDEP("pre: realtek"); MODULE_LICENSE("GPL"); MODULE_FIRMWARE(FIRMWARE_8168D_1); MODULE_FIRMWARE(FIRMWARE_8168D_2); MODULE_FIRMWARE(FIRMWARE_8168E_1); MODULE_FIRMWARE(FIRMWARE_8168E_2); MODULE_FIRMWARE(FIRMWARE_8168E_3); MODULE_FIRMWARE(FIRMWARE_8105E_1); MODULE_FIRMWARE(FIRMWARE_8168F_1); MODULE_FIRMWARE(FIRMWARE_8168F_2); MODULE_FIRMWARE(FIRMWARE_8402_1); MODULE_FIRMWARE(FIRMWARE_8411_1); MODULE_FIRMWARE(FIRMWARE_8411_2); MODULE_FIRMWARE(FIRMWARE_8106E_1); MODULE_FIRMWARE(FIRMWARE_8106E_2); MODULE_FIRMWARE(FIRMWARE_8168G_2); MODULE_FIRMWARE(FIRMWARE_8168G_3); MODULE_FIRMWARE(FIRMWARE_8168H_2); MODULE_FIRMWARE(FIRMWARE_8168FP_3); MODULE_FIRMWARE(FIRMWARE_8107E_2); MODULE_FIRMWARE(FIRMWARE_8125A_3); MODULE_FIRMWARE(FIRMWARE_8125B_2); static inline struct device *tp_to_dev(struct rtl8169_private *tp) { return &tp->pci_dev->dev; } static void rtl_lock_config_regs(struct rtl8169_private *tp) { unsigned long flags; raw_spin_lock_irqsave(&tp->cfg9346_usage_lock, flags); if (!--tp->cfg9346_usage_count) RTL_W8(tp, Cfg9346, Cfg9346_Lock); raw_spin_unlock_irqrestore(&tp->cfg9346_usage_lock, flags); } static void rtl_unlock_config_regs(struct rtl8169_private *tp) { unsigned long flags; raw_spin_lock_irqsave(&tp->cfg9346_usage_lock, flags); if (!tp->cfg9346_usage_count++) RTL_W8(tp, Cfg9346, Cfg9346_Unlock); raw_spin_unlock_irqrestore(&tp->cfg9346_usage_lock, flags); } static void rtl_pci_commit(struct rtl8169_private *tp) { /* Read an arbitrary register to commit a preceding PCI write */ RTL_R8(tp, ChipCmd); } static void rtl_mod_config2(struct rtl8169_private *tp, u8 clear, u8 set) { unsigned long flags; u8 val; raw_spin_lock_irqsave(&tp->config25_lock, flags); val = RTL_R8(tp, Config2); RTL_W8(tp, Config2, (val & ~clear) | set); raw_spin_unlock_irqrestore(&tp->config25_lock, flags); } static void rtl_mod_config5(struct rtl8169_private *tp, u8 clear, u8 set) { unsigned long flags; u8 val; raw_spin_lock_irqsave(&tp->config25_lock, flags); val = RTL_R8(tp, Config5); RTL_W8(tp, Config5, (val & ~clear) | set); raw_spin_unlock_irqrestore(&tp->config25_lock, flags); } static bool rtl_is_8125(struct rtl8169_private *tp) { return tp->mac_version >= RTL_GIGA_MAC_VER_61; } static bool rtl_is_8168evl_up(struct rtl8169_private *tp) { return tp->mac_version >= RTL_GIGA_MAC_VER_34 && tp->mac_version != RTL_GIGA_MAC_VER_39 && tp->mac_version <= RTL_GIGA_MAC_VER_53; } static bool rtl_supports_eee(struct rtl8169_private *tp) { return tp->mac_version >= RTL_GIGA_MAC_VER_34 && tp->mac_version != RTL_GIGA_MAC_VER_37 && tp->mac_version != RTL_GIGA_MAC_VER_39; } static void rtl_read_mac_from_reg(struct rtl8169_private *tp, u8 *mac, int reg) { int i; for (i = 0; i < ETH_ALEN; i++) mac[i] = RTL_R8(tp, reg + i); } struct rtl_cond { bool (*check)(struct rtl8169_private *); const char *msg; }; static bool rtl_loop_wait(struct rtl8169_private *tp, const struct rtl_cond *c, unsigned long usecs, int n, bool high) { int i; for (i = 0; i < n; i++) { if (c->check(tp) == high) return true; fsleep(usecs); } if (net_ratelimit()) netdev_err(tp->dev, "%s == %d (loop: %d, delay: %lu).\n", c->msg, !high, n, usecs); return false; } static bool rtl_loop_wait_high(struct rtl8169_private *tp, const struct rtl_cond *c, unsigned long d, int n) { return rtl_loop_wait(tp, c, d, n, true); } static bool rtl_loop_wait_low(struct rtl8169_private *tp, const struct rtl_cond *c, unsigned long d, int n) { return rtl_loop_wait(tp, c, d, n, false); } #define DECLARE_RTL_COND(name) \ static bool name ## _check(struct rtl8169_private *); \ \ static const struct rtl_cond name = { \ .check = name ## _check, \ .msg = #name \ }; \ \ static bool name ## _check(struct rtl8169_private *tp) static void r8168fp_adjust_ocp_cmd(struct rtl8169_private *tp, u32 *cmd, int type) { /* based on RTL8168FP_OOBMAC_BASE in vendor driver */ if (type == ERIAR_OOB && (tp->mac_version == RTL_GIGA_MAC_VER_52 || tp->mac_version == RTL_GIGA_MAC_VER_53)) *cmd |= 0xf70 << 18; } DECLARE_RTL_COND(rtl_eriar_cond) { return RTL_R32(tp, ERIAR) & ERIAR_FLAG; } static void _rtl_eri_write(struct rtl8169_private *tp, int addr, u32 mask, u32 val, int type) { u32 cmd = ERIAR_WRITE_CMD | type | mask | addr; if (WARN(addr & 3 || !mask, "addr: 0x%x, mask: 0x%08x\n", addr, mask)) return; RTL_W32(tp, ERIDR, val); r8168fp_adjust_ocp_cmd(tp, &cmd, type); RTL_W32(tp, ERIAR, cmd); rtl_loop_wait_low(tp, &rtl_eriar_cond, 100, 100); } static void rtl_eri_write(struct rtl8169_private *tp, int addr, u32 mask, u32 val) { _rtl_eri_write(tp, addr, mask, val, ERIAR_EXGMAC); } static u32 _rtl_eri_read(struct rtl8169_private *tp, int addr, int type) { u32 cmd = ERIAR_READ_CMD | type | ERIAR_MASK_1111 | addr; r8168fp_adjust_ocp_cmd(tp, &cmd, type); RTL_W32(tp, ERIAR, cmd); return rtl_loop_wait_high(tp, &rtl_eriar_cond, 100, 100) ? RTL_R32(tp, ERIDR) : ~0; } static u32 rtl_eri_read(struct rtl8169_private *tp, int addr) { return _rtl_eri_read(tp, addr, ERIAR_EXGMAC); } static void rtl_w0w1_eri(struct rtl8169_private *tp, int addr, u32 p, u32 m) { u32 val = rtl_eri_read(tp, addr); rtl_eri_write(tp, addr, ERIAR_MASK_1111, (val & ~m) | p); } static void rtl_eri_set_bits(struct rtl8169_private *tp, int addr, u32 p) { rtl_w0w1_eri(tp, addr, p, 0); } static void rtl_eri_clear_bits(struct rtl8169_private *tp, int addr, u32 m) { rtl_w0w1_eri(tp, addr, 0, m); } static bool rtl_ocp_reg_failure(u32 reg) { return WARN_ONCE(reg & 0xffff0001, "Invalid ocp reg %x!\n", reg); } DECLARE_RTL_COND(rtl_ocp_gphy_cond) { return RTL_R32(tp, GPHY_OCP) & OCPAR_FLAG; } static void r8168_phy_ocp_write(struct rtl8169_private *tp, u32 reg, u32 data) { if (rtl_ocp_reg_failure(reg)) return; RTL_W32(tp, GPHY_OCP, OCPAR_FLAG | (reg << 15) | data); rtl_loop_wait_low(tp, &rtl_ocp_gphy_cond, 25, 10); } static int r8168_phy_ocp_read(struct rtl8169_private *tp, u32 reg) { if (rtl_ocp_reg_failure(reg)) return 0; RTL_W32(tp, GPHY_OCP, reg << 15); return rtl_loop_wait_high(tp, &rtl_ocp_gphy_cond, 25, 10) ? (RTL_R32(tp, GPHY_OCP) & 0xffff) : -ETIMEDOUT; } static void __r8168_mac_ocp_write(struct rtl8169_private *tp, u32 reg, u32 data) { if (rtl_ocp_reg_failure(reg)) return; RTL_W32(tp, OCPDR, OCPAR_FLAG | (reg << 15) | data); } static void r8168_mac_ocp_write(struct rtl8169_private *tp, u32 reg, u32 data) { unsigned long flags; raw_spin_lock_irqsave(&tp->mac_ocp_lock, flags); __r8168_mac_ocp_write(tp, reg, data); raw_spin_unlock_irqrestore(&tp->mac_ocp_lock, flags); } static u16 __r8168_mac_ocp_read(struct rtl8169_private *tp, u32 reg) { if (rtl_ocp_reg_failure(reg)) return 0; RTL_W32(tp, OCPDR, reg << 15); return RTL_R32(tp, OCPDR); } static u16 r8168_mac_ocp_read(struct rtl8169_private *tp, u32 reg) { unsigned long flags; u16 val; raw_spin_lock_irqsave(&tp->mac_ocp_lock, flags); val = __r8168_mac_ocp_read(tp, reg); raw_spin_unlock_irqrestore(&tp->mac_ocp_lock, flags); return val; } static void r8168_mac_ocp_modify(struct rtl8169_private *tp, u32 reg, u16 mask, u16 set) { unsigned long flags; u16 data; raw_spin_lock_irqsave(&tp->mac_ocp_lock, flags); data = __r8168_mac_ocp_read(tp, reg); __r8168_mac_ocp_write(tp, reg, (data & ~mask) | set); raw_spin_unlock_irqrestore(&tp->mac_ocp_lock, flags); } /* Work around a hw issue with RTL8168g PHY, the quirk disables * PHY MCU interrupts before PHY power-down. */ static void rtl8168g_phy_suspend_quirk(struct rtl8169_private *tp, int value) { switch (tp->mac_version) { case RTL_GIGA_MAC_VER_40: if (value & BMCR_RESET || !(value & BMCR_PDOWN)) rtl_eri_set_bits(tp, 0x1a8, 0xfc000000); else rtl_eri_clear_bits(tp, 0x1a8, 0xfc000000); break; default: break; } }; static void r8168g_mdio_write(struct rtl8169_private *tp, int reg, int value) { if (reg == 0x1f) { tp->ocp_base = value ? value << 4 : OCP_STD_PHY_BASE; return; } if (tp->ocp_base != OCP_STD_PHY_BASE) reg -= 0x10; if (tp->ocp_base == OCP_STD_PHY_BASE && reg == MII_BMCR) rtl8168g_phy_suspend_quirk(tp, value); r8168_phy_ocp_write(tp, tp->ocp_base + reg * 2, value); } static int r8168g_mdio_read(struct rtl8169_private *tp, int reg) { if (reg == 0x1f) return tp->ocp_base == OCP_STD_PHY_BASE ? 0 : tp->ocp_base >> 4; if (tp->ocp_base != OCP_STD_PHY_BASE) reg -= 0x10; return r8168_phy_ocp_read(tp, tp->ocp_base + reg * 2); } static void mac_mcu_write(struct rtl8169_private *tp, int reg, int value) { if (reg == 0x1f) { tp->ocp_base = value << 4; return; } r8168_mac_ocp_write(tp, tp->ocp_base + reg, value); } static int mac_mcu_read(struct rtl8169_private *tp, int reg) { return r8168_mac_ocp_read(tp, tp->ocp_base + reg); } DECLARE_RTL_COND(rtl_phyar_cond) { return RTL_R32(tp, PHYAR) & 0x80000000; } static void r8169_mdio_write(struct rtl8169_private *tp, int reg, int value) { RTL_W32(tp, PHYAR, 0x80000000 | (reg & 0x1f) << 16 | (value & 0xffff)); rtl_loop_wait_low(tp, &rtl_phyar_cond, 25, 20); /* * According to hardware specs a 20us delay is required after write * complete indication, but before sending next command. */ udelay(20); } static int r8169_mdio_read(struct rtl8169_private *tp, int reg) { int value; RTL_W32(tp, PHYAR, 0x0 | (reg & 0x1f) << 16); value = rtl_loop_wait_high(tp, &rtl_phyar_cond, 25, 20) ? RTL_R32(tp, PHYAR) & 0xffff : -ETIMEDOUT; /* * According to hardware specs a 20us delay is required after read * complete indication, but before sending next command. */ udelay(20); return value; } DECLARE_RTL_COND(rtl_ocpar_cond) { return RTL_R32(tp, OCPAR) & OCPAR_FLAG; } #define R8168DP_1_MDIO_ACCESS_BIT 0x00020000 static void r8168dp_2_mdio_start(struct rtl8169_private *tp) { RTL_W32(tp, 0xd0, RTL_R32(tp, 0xd0) & ~R8168DP_1_MDIO_ACCESS_BIT); } static void r8168dp_2_mdio_stop(struct rtl8169_private *tp) { RTL_W32(tp, 0xd0, RTL_R32(tp, 0xd0) | R8168DP_1_MDIO_ACCESS_BIT); } static void r8168dp_2_mdio_write(struct rtl8169_private *tp, int reg, int value) { r8168dp_2_mdio_start(tp); r8169_mdio_write(tp, reg, value); r8168dp_2_mdio_stop(tp); } static int r8168dp_2_mdio_read(struct rtl8169_private *tp, int reg) { int value; /* Work around issue with chip reporting wrong PHY ID */ if (reg == MII_PHYSID2) return 0xc912; r8168dp_2_mdio_start(tp); value = r8169_mdio_read(tp, reg); r8168dp_2_mdio_stop(tp); return value; } static void rtl_writephy(struct rtl8169_private *tp, int location, int val) { switch (tp->mac_version) { case RTL_GIGA_MAC_VER_28: case RTL_GIGA_MAC_VER_31: r8168dp_2_mdio_write(tp, location, val); break; case RTL_GIGA_MAC_VER_40 ... RTL_GIGA_MAC_VER_63: r8168g_mdio_write(tp, location, val); break; default: r8169_mdio_write(tp, location, val); break; } } static int rtl_readphy(struct rtl8169_private *tp, int location) { switch (tp->mac_version) { case RTL_GIGA_MAC_VER_28: case RTL_GIGA_MAC_VER_31: return r8168dp_2_mdio_read(tp, location); case RTL_GIGA_MAC_VER_40 ... RTL_GIGA_MAC_VER_63: return r8168g_mdio_read(tp, location); default: return r8169_mdio_read(tp, location); } } DECLARE_RTL_COND(rtl_ephyar_cond) { return RTL_R32(tp, EPHYAR) & EPHYAR_FLAG; } static void rtl_ephy_write(struct rtl8169_private *tp, int reg_addr, int value) { RTL_W32(tp, EPHYAR, EPHYAR_WRITE_CMD | (value & EPHYAR_DATA_MASK) | (reg_addr & EPHYAR_REG_MASK) << EPHYAR_REG_SHIFT); rtl_loop_wait_low(tp, &rtl_ephyar_cond, 10, 100); udelay(10); } static u16 rtl_ephy_read(struct rtl8169_private *tp, int reg_addr) { RTL_W32(tp, EPHYAR, (reg_addr & EPHYAR_REG_MASK) << EPHYAR_REG_SHIFT); return rtl_loop_wait_high(tp, &rtl_ephyar_cond, 10, 100) ? RTL_R32(tp, EPHYAR) & EPHYAR_DATA_MASK : ~0; } static u32 r8168dp_ocp_read(struct rtl8169_private *tp, u16 reg) { RTL_W32(tp, OCPAR, 0x0fu << 12 | (reg & 0x0fff)); return rtl_loop_wait_high(tp, &rtl_ocpar_cond, 100, 20) ? RTL_R32(tp, OCPDR) : ~0; } static u32 r8168ep_ocp_read(struct rtl8169_private *tp, u16 reg) { return _rtl_eri_read(tp, reg, ERIAR_OOB); } static void r8168dp_ocp_write(struct rtl8169_private *tp, u8 mask, u16 reg, u32 data) { RTL_W32(tp, OCPDR, data); RTL_W32(tp, OCPAR, OCPAR_FLAG | ((u32)mask & 0x0f) << 12 | (reg & 0x0fff)); rtl_loop_wait_low(tp, &rtl_ocpar_cond, 100, 20); } static void r8168ep_ocp_write(struct rtl8169_private *tp, u8 mask, u16 reg, u32 data) { _rtl_eri_write(tp, reg, ((u32)mask & 0x0f) << ERIAR_MASK_SHIFT, data, ERIAR_OOB); } static void r8168dp_oob_notify(struct rtl8169_private *tp, u8 cmd) { rtl_eri_write(tp, 0xe8, ERIAR_MASK_0001, cmd); r8168dp_ocp_write(tp, 0x1, 0x30, 0x00000001); } #define OOB_CMD_RESET 0x00 #define OOB_CMD_DRIVER_START 0x05 #define OOB_CMD_DRIVER_STOP 0x06 static u16 rtl8168_get_ocp_reg(struct rtl8169_private *tp) { return (tp->mac_version == RTL_GIGA_MAC_VER_31) ? 0xb8 : 0x10; } DECLARE_RTL_COND(rtl_dp_ocp_read_cond) { u16 reg; reg = rtl8168_get_ocp_reg(tp); return r8168dp_ocp_read(tp, reg) & 0x00000800; } DECLARE_RTL_COND(rtl_ep_ocp_read_cond) { return r8168ep_ocp_read(tp, 0x124) & 0x00000001; } DECLARE_RTL_COND(rtl_ocp_tx_cond) { return RTL_R8(tp, IBISR0) & 0x20; } static void rtl8168ep_stop_cmac(struct rtl8169_private *tp) { RTL_W8(tp, IBCR2, RTL_R8(tp, IBCR2) & ~0x01); rtl_loop_wait_high(tp, &rtl_ocp_tx_cond, 50000, 2000); RTL_W8(tp, IBISR0, RTL_R8(tp, IBISR0) | 0x20); RTL_W8(tp, IBCR0, RTL_R8(tp, IBCR0) & ~0x01); } static void rtl8168dp_driver_start(struct rtl8169_private *tp) { r8168dp_oob_notify(tp, OOB_CMD_DRIVER_START); rtl_loop_wait_high(tp, &rtl_dp_ocp_read_cond, 10000, 10); } static void rtl8168ep_driver_start(struct rtl8169_private *tp) { r8168ep_ocp_write(tp, 0x01, 0x180, OOB_CMD_DRIVER_START); r8168ep_ocp_write(tp, 0x01, 0x30, r8168ep_ocp_read(tp, 0x30) | 0x01); rtl_loop_wait_high(tp, &rtl_ep_ocp_read_cond, 10000, 10); } static void rtl8168_driver_start(struct rtl8169_private *tp) { if (tp->dash_type == RTL_DASH_DP) rtl8168dp_driver_start(tp); else rtl8168ep_driver_start(tp); } static void rtl8168dp_driver_stop(struct rtl8169_private *tp) { r8168dp_oob_notify(tp, OOB_CMD_DRIVER_STOP); rtl_loop_wait_low(tp, &rtl_dp_ocp_read_cond, 10000, 10); } static void rtl8168ep_driver_stop(struct rtl8169_private *tp) { rtl8168ep_stop_cmac(tp); r8168ep_ocp_write(tp, 0x01, 0x180, OOB_CMD_DRIVER_STOP); r8168ep_ocp_write(tp, 0x01, 0x30, r8168ep_ocp_read(tp, 0x30) | 0x01); rtl_loop_wait_low(tp, &rtl_ep_ocp_read_cond, 10000, 10); } static void rtl8168_driver_stop(struct rtl8169_private *tp) { if (tp->dash_type == RTL_DASH_DP) rtl8168dp_driver_stop(tp); else rtl8168ep_driver_stop(tp); } static bool r8168dp_check_dash(struct rtl8169_private *tp) { u16 reg = rtl8168_get_ocp_reg(tp); return r8168dp_ocp_read(tp, reg) & BIT(15); } static bool r8168ep_check_dash(struct rtl8169_private *tp) { return r8168ep_ocp_read(tp, 0x128) & BIT(0); } static enum rtl_dash_type rtl_check_dash(struct rtl8169_private *tp) { switch (tp->mac_version) { case RTL_GIGA_MAC_VER_28: case RTL_GIGA_MAC_VER_31: return r8168dp_check_dash(tp) ? RTL_DASH_DP : RTL_DASH_NONE; case RTL_GIGA_MAC_VER_51 ... RTL_GIGA_MAC_VER_53: return r8168ep_check_dash(tp) ? RTL_DASH_EP : RTL_DASH_NONE; default: return RTL_DASH_NONE; } } static void rtl_set_d3_pll_down(struct rtl8169_private *tp, bool enable) { switch (tp->mac_version) { case RTL_GIGA_MAC_VER_25 ... RTL_GIGA_MAC_VER_26: case RTL_GIGA_MAC_VER_29 ... RTL_GIGA_MAC_VER_30: case RTL_GIGA_MAC_VER_32 ... RTL_GIGA_MAC_VER_37: case RTL_GIGA_MAC_VER_39 ... RTL_GIGA_MAC_VER_63: if (enable) RTL_W8(tp, PMCH, RTL_R8(tp, PMCH) & ~D3_NO_PLL_DOWN); else RTL_W8(tp, PMCH, RTL_R8(tp, PMCH) | D3_NO_PLL_DOWN); break; default: break; } } static void rtl_reset_packet_filter(struct rtl8169_private *tp) { rtl_eri_clear_bits(tp, 0xdc, BIT(0)); rtl_eri_set_bits(tp, 0xdc, BIT(0)); } DECLARE_RTL_COND(rtl_efusear_cond) { return RTL_R32(tp, EFUSEAR) & EFUSEAR_FLAG; } u8 rtl8168d_efuse_read(struct rtl8169_private *tp, int reg_addr) { RTL_W32(tp, EFUSEAR, (reg_addr & EFUSEAR_REG_MASK) << EFUSEAR_REG_SHIFT); return rtl_loop_wait_high(tp, &rtl_efusear_cond, 100, 300) ? RTL_R32(tp, EFUSEAR) & EFUSEAR_DATA_MASK : ~0; } static u32 rtl_get_events(struct rtl8169_private *tp) { if (rtl_is_8125(tp)) return RTL_R32(tp, IntrStatus_8125); else return RTL_R16(tp, IntrStatus); } static void rtl_ack_events(struct rtl8169_private *tp, u32 bits) { if (rtl_is_8125(tp)) RTL_W32(tp, IntrStatus_8125, bits); else RTL_W16(tp, IntrStatus, bits); } static void rtl_irq_disable(struct rtl8169_private *tp) { if (rtl_is_8125(tp)) RTL_W32(tp, IntrMask_8125, 0); else RTL_W16(tp, IntrMask, 0); } static void rtl_irq_enable(struct rtl8169_private *tp) { if (rtl_is_8125(tp)) RTL_W32(tp, IntrMask_8125, tp->irq_mask); else RTL_W16(tp, IntrMask, tp->irq_mask); } static void rtl8169_irq_mask_and_ack(struct rtl8169_private *tp) { rtl_irq_disable(tp); rtl_ack_events(tp, 0xffffffff); rtl_pci_commit(tp); } static void rtl_link_chg_patch(struct rtl8169_private *tp) { struct phy_device *phydev = tp->phydev; if (tp->mac_version == RTL_GIGA_MAC_VER_34 || tp->mac_version == RTL_GIGA_MAC_VER_38) { if (phydev->speed == SPEED_1000) { rtl_eri_write(tp, 0x1bc, ERIAR_MASK_1111, 0x00000011); rtl_eri_write(tp, 0x1dc, ERIAR_MASK_1111, 0x00000005); } else if (phydev->speed == SPEED_100) { rtl_eri_write(tp, 0x1bc, ERIAR_MASK_1111, 0x0000001f); rtl_eri_write(tp, 0x1dc, ERIAR_MASK_1111, 0x00000005); } else { rtl_eri_write(tp, 0x1bc, ERIAR_MASK_1111, 0x0000001f); rtl_eri_write(tp, 0x1dc, ERIAR_MASK_1111, 0x0000003f); } rtl_reset_packet_filter(tp); } else if (tp->mac_version == RTL_GIGA_MAC_VER_35 || tp->mac_version == RTL_GIGA_MAC_VER_36) { if (phydev->speed == SPEED_1000) { rtl_eri_write(tp, 0x1bc, ERIAR_MASK_1111, 0x00000011); rtl_eri_write(tp, 0x1dc, ERIAR_MASK_1111, 0x00000005); } else { rtl_eri_write(tp, 0x1bc, ERIAR_MASK_1111, 0x0000001f); rtl_eri_write(tp, 0x1dc, ERIAR_MASK_1111, 0x0000003f); } } else if (tp->mac_version == RTL_GIGA_MAC_VER_37) { if (phydev->speed == SPEED_10) { rtl_eri_write(tp, 0x1d0, ERIAR_MASK_0011, 0x4d02); rtl_eri_write(tp, 0x1dc, ERIAR_MASK_0011, 0x0060a); } else { rtl_eri_write(tp, 0x1d0, ERIAR_MASK_0011, 0x0000); } } } #define WAKE_ANY (WAKE_PHY | WAKE_MAGIC | WAKE_UCAST | WAKE_BCAST | WAKE_MCAST) static void rtl8169_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol) { struct rtl8169_private *tp = netdev_priv(dev); wol->supported = WAKE_ANY; wol->wolopts = tp->saved_wolopts; } static void __rtl8169_set_wol(struct rtl8169_private *tp, u32 wolopts) { static const struct { u32 opt; u16 reg; u8 mask; } cfg[] = { { WAKE_PHY, Config3, LinkUp }, { WAKE_UCAST, Config5, UWF }, { WAKE_BCAST, Config5, BWF }, { WAKE_MCAST, Config5, MWF }, { WAKE_ANY, Config5, LanWake }, { WAKE_MAGIC, Config3, MagicPacket } }; unsigned int i, tmp = ARRAY_SIZE(cfg); unsigned long flags; u8 options; rtl_unlock_config_regs(tp); if (rtl_is_8168evl_up(tp)) { tmp--; if (wolopts & WAKE_MAGIC) rtl_eri_set_bits(tp, 0x0dc, MagicPacket_v2); else rtl_eri_clear_bits(tp, 0x0dc, MagicPacket_v2); } else if (rtl_is_8125(tp)) { tmp--; if (wolopts & WAKE_MAGIC) r8168_mac_ocp_modify(tp, 0xc0b6, 0, BIT(0)); else r8168_mac_ocp_modify(tp, 0xc0b6, BIT(0), 0); } raw_spin_lock_irqsave(&tp->config25_lock, flags); for (i = 0; i < tmp; i++) { options = RTL_R8(tp, cfg[i].reg) & ~cfg[i].mask; if (wolopts & cfg[i].opt) options |= cfg[i].mask; RTL_W8(tp, cfg[i].reg, options); } raw_spin_unlock_irqrestore(&tp->config25_lock, flags); switch (tp->mac_version) { case RTL_GIGA_MAC_VER_02 ... RTL_GIGA_MAC_VER_06: options = RTL_R8(tp, Config1) & ~PMEnable; if (wolopts) options |= PMEnable; RTL_W8(tp, Config1, options); break; case RTL_GIGA_MAC_VER_34: case RTL_GIGA_MAC_VER_37: case RTL_GIGA_MAC_VER_39 ... RTL_GIGA_MAC_VER_63: if (wolopts) rtl_mod_config2(tp, 0, PME_SIGNAL); else rtl_mod_config2(tp, PME_SIGNAL, 0); break; default: break; } rtl_lock_config_regs(tp); device_set_wakeup_enable(tp_to_dev(tp), wolopts); if (tp->dash_type == RTL_DASH_NONE) { rtl_set_d3_pll_down(tp, !wolopts); tp->dev->wol_enabled = wolopts ? 1 : 0; } } static int rtl8169_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol) { struct rtl8169_private *tp = netdev_priv(dev); if (wol->wolopts & ~WAKE_ANY) return -EINVAL; tp->saved_wolopts = wol->wolopts; __rtl8169_set_wol(tp, tp->saved_wolopts); return 0; } static void rtl8169_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { struct rtl8169_private *tp = netdev_priv(dev); struct rtl_fw *rtl_fw = tp->rtl_fw; strscpy(info->driver, KBUILD_MODNAME, sizeof(info->driver)); strscpy(info->bus_info, pci_name(tp->pci_dev), sizeof(info->bus_info)); BUILD_BUG_ON(sizeof(info->fw_version) < sizeof(rtl_fw->version)); if (rtl_fw) strscpy(info->fw_version, rtl_fw->version, sizeof(info->fw_version)); } static int rtl8169_get_regs_len(struct net_device *dev) { return R8169_REGS_SIZE; } static netdev_features_t rtl8169_fix_features(struct net_device *dev, netdev_features_t features) { struct rtl8169_private *tp = netdev_priv(dev); if (dev->mtu > TD_MSS_MAX) features &= ~NETIF_F_ALL_TSO; if (dev->mtu > ETH_DATA_LEN && tp->mac_version > RTL_GIGA_MAC_VER_06) features &= ~(NETIF_F_CSUM_MASK | NETIF_F_ALL_TSO); return features; } static void rtl_set_rx_config_features(struct rtl8169_private *tp, netdev_features_t features) { u32 rx_config = RTL_R32(tp, RxConfig); if (features & NETIF_F_RXALL) rx_config |= RX_CONFIG_ACCEPT_ERR_MASK; else rx_config &= ~RX_CONFIG_ACCEPT_ERR_MASK; if (rtl_is_8125(tp)) { if (features & NETIF_F_HW_VLAN_CTAG_RX) rx_config |= RX_VLAN_8125; else rx_config &= ~RX_VLAN_8125; } RTL_W32(tp, RxConfig, rx_config); } static int rtl8169_set_features(struct net_device *dev, netdev_features_t features) { struct rtl8169_private *tp = netdev_priv(dev); rtl_set_rx_config_features(tp, features); if (features & NETIF_F_RXCSUM) tp->cp_cmd |= RxChkSum; else tp->cp_cmd &= ~RxChkSum; if (!rtl_is_8125(tp)) { if (features & NETIF_F_HW_VLAN_CTAG_RX) tp->cp_cmd |= RxVlan; else tp->cp_cmd &= ~RxVlan; } RTL_W16(tp, CPlusCmd, tp->cp_cmd); rtl_pci_commit(tp); return 0; } static inline u32 rtl8169_tx_vlan_tag(struct sk_buff *skb) { return (skb_vlan_tag_present(skb)) ? TxVlanTag | swab16(skb_vlan_tag_get(skb)) : 0x00; } static void rtl8169_rx_vlan_tag(struct RxDesc *desc, struct sk_buff *skb) { u32 opts2 = le32_to_cpu(desc->opts2); if (opts2 & RxVlanTag) __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), swab16(opts2 & 0xffff)); } static void rtl8169_get_regs(struct net_device *dev, struct ethtool_regs *regs, void *p) { struct rtl8169_private *tp = netdev_priv(dev); u32 __iomem *data = tp->mmio_addr; u32 *dw = p; int i; for (i = 0; i < R8169_REGS_SIZE; i += 4) memcpy_fromio(dw++, data++, 4); } static const char rtl8169_gstrings[][ETH_GSTRING_LEN] = { "tx_packets", "rx_packets", "tx_errors", "rx_errors", "rx_missed", "align_errors", "tx_single_collisions", "tx_multi_collisions", "unicast", "broadcast", "multicast", "tx_aborted", "tx_underrun", }; static int rtl8169_get_sset_count(struct net_device *dev, int sset) { switch (sset) { case ETH_SS_STATS: return ARRAY_SIZE(rtl8169_gstrings); default: return -EOPNOTSUPP; } } DECLARE_RTL_COND(rtl_counters_cond) { return RTL_R32(tp, CounterAddrLow) & (CounterReset | CounterDump); } static void rtl8169_do_counters(struct rtl8169_private *tp, u32 counter_cmd) { u32 cmd = lower_32_bits(tp->counters_phys_addr); RTL_W32(tp, CounterAddrHigh, upper_32_bits(tp->counters_phys_addr)); rtl_pci_commit(tp); RTL_W32(tp, CounterAddrLow, cmd); RTL_W32(tp, CounterAddrLow, cmd | counter_cmd); rtl_loop_wait_low(tp, &rtl_counters_cond, 10, 1000); } static void rtl8169_update_counters(struct rtl8169_private *tp) { u8 val = RTL_R8(tp, ChipCmd); /* * Some chips are unable to dump tally counters when the receiver * is disabled. If 0xff chip may be in a PCI power-save state. */ if (val & CmdRxEnb && val != 0xff) rtl8169_do_counters(tp, CounterDump); } static void rtl8169_init_counter_offsets(struct rtl8169_private *tp) { struct rtl8169_counters *counters = tp->counters; /* * rtl8169_init_counter_offsets is called from rtl_open. On chip * versions prior to RTL_GIGA_MAC_VER_19 the tally counters are only * reset by a power cycle, while the counter values collected by the * driver are reset at every driver unload/load cycle. * * To make sure the HW values returned by @get_stats64 match the SW * values, we collect the initial values at first open(*) and use them * as offsets to normalize the values returned by @get_stats64. * * (*) We can't call rtl8169_init_counter_offsets from rtl_init_one * for the reason stated in rtl8169_update_counters; CmdRxEnb is only * set at open time by rtl_hw_start. */ if (tp->tc_offset.inited) return; if (tp->mac_version >= RTL_GIGA_MAC_VER_19) { rtl8169_do_counters(tp, CounterReset); } else { rtl8169_update_counters(tp); tp->tc_offset.tx_errors = counters->tx_errors; tp->tc_offset.tx_multi_collision = counters->tx_multi_collision; tp->tc_offset.tx_aborted = counters->tx_aborted; tp->tc_offset.rx_missed = counters->rx_missed; } tp->tc_offset.inited = true; } static void rtl8169_get_ethtool_stats(struct net_device *dev, struct ethtool_stats *stats, u64 *data) { struct rtl8169_private *tp = netdev_priv(dev); struct rtl8169_counters *counters; counters = tp->counters; rtl8169_update_counters(tp); data[0] = le64_to_cpu(counters->tx_packets); data[1] = le64_to_cpu(counters->rx_packets); data[2] = le64_to_cpu(counters->tx_errors); data[3] = le32_to_cpu(counters->rx_errors); data[4] = le16_to_cpu(counters->rx_missed); data[5] = le16_to_cpu(counters->align_errors); data[6] = le32_to_cpu(counters->tx_one_collision); data[7] = le32_to_cpu(counters->tx_multi_collision); data[8] = le64_to_cpu(counters->rx_unicast); data[9] = le64_to_cpu(counters->rx_broadcast); data[10] = le32_to_cpu(counters->rx_multicast); data[11] = le16_to_cpu(counters->tx_aborted); data[12] = le16_to_cpu(counters->tx_underun); } static void rtl8169_get_strings(struct net_device *dev, u32 stringset, u8 *data) { switch(stringset) { case ETH_SS_STATS: memcpy(data, rtl8169_gstrings, sizeof(rtl8169_gstrings)); break; } } /* * Interrupt coalescing * * > 1 - the availability of the IntrMitigate (0xe2) register through the * > 8169, 8168 and 810x line of chipsets * * 8169, 8168, and 8136(810x) serial chipsets support it. * * > 2 - the Tx timer unit at gigabit speed * * The unit of the timer depends on both the speed and the setting of CPlusCmd * (0xe0) bit 1 and bit 0. * * For 8169 * bit[1:0] \ speed 1000M 100M 10M * 0 0 320ns 2.56us 40.96us * 0 1 2.56us 20.48us 327.7us * 1 0 5.12us 40.96us 655.4us * 1 1 10.24us 81.92us 1.31ms * * For the other * bit[1:0] \ speed 1000M 100M 10M * 0 0 5us 2.56us 40.96us * 0 1 40us 20.48us 327.7us * 1 0 80us 40.96us 655.4us * 1 1 160us 81.92us 1.31ms */ /* rx/tx scale factors for all CPlusCmd[0:1] cases */ struct rtl_coalesce_info { u32 speed; u32 scale_nsecs[4]; }; /* produce array with base delay *1, *8, *8*2, *8*2*2 */ #define COALESCE_DELAY(d) { (d), 8 * (d), 16 * (d), 32 * (d) } static const struct rtl_coalesce_info rtl_coalesce_info_8169[] = { { SPEED_1000, COALESCE_DELAY(320) }, { SPEED_100, COALESCE_DELAY(2560) }, { SPEED_10, COALESCE_DELAY(40960) }, { 0 }, }; static const struct rtl_coalesce_info rtl_coalesce_info_8168_8136[] = { { SPEED_1000, COALESCE_DELAY(5000) }, { SPEED_100, COALESCE_DELAY(2560) }, { SPEED_10, COALESCE_DELAY(40960) }, { 0 }, }; #undef COALESCE_DELAY /* get rx/tx scale vector corresponding to current speed */ static const struct rtl_coalesce_info * rtl_coalesce_info(struct rtl8169_private *tp) { const struct rtl_coalesce_info *ci; if (tp->mac_version <= RTL_GIGA_MAC_VER_06) ci = rtl_coalesce_info_8169; else ci = rtl_coalesce_info_8168_8136; /* if speed is unknown assume highest one */ if (tp->phydev->speed == SPEED_UNKNOWN) return ci; for (; ci->speed; ci++) { if (tp->phydev->speed == ci->speed) return ci; } return ERR_PTR(-ELNRNG); } static int rtl_get_coalesce(struct net_device *dev, struct ethtool_coalesce *ec, struct kernel_ethtool_coalesce *kernel_coal, struct netlink_ext_ack *extack) { struct rtl8169_private *tp = netdev_priv(dev); const struct rtl_coalesce_info *ci; u32 scale, c_us, c_fr; u16 intrmit; if (rtl_is_8125(tp)) return -EOPNOTSUPP; memset(ec, 0, sizeof(*ec)); /* get rx/tx scale corresponding to current speed and CPlusCmd[0:1] */ ci = rtl_coalesce_info(tp); if (IS_ERR(ci)) return PTR_ERR(ci); scale = ci->scale_nsecs[tp->cp_cmd & INTT_MASK]; intrmit = RTL_R16(tp, IntrMitigate); c_us = FIELD_GET(RTL_COALESCE_TX_USECS, intrmit); ec->tx_coalesce_usecs = DIV_ROUND_UP(c_us * scale, 1000); c_fr = FIELD_GET(RTL_COALESCE_TX_FRAMES, intrmit); /* ethtool_coalesce states usecs and max_frames must not both be 0 */ ec->tx_max_coalesced_frames = (c_us || c_fr) ? c_fr * 4 : 1; c_us = FIELD_GET(RTL_COALESCE_RX_USECS, intrmit); ec->rx_coalesce_usecs = DIV_ROUND_UP(c_us * scale, 1000); c_fr = FIELD_GET(RTL_COALESCE_RX_FRAMES, intrmit); ec->rx_max_coalesced_frames = (c_us || c_fr) ? c_fr * 4 : 1; return 0; } /* choose appropriate scale factor and CPlusCmd[0:1] for (speed, usec) */ static int rtl_coalesce_choose_scale(struct rtl8169_private *tp, u32 usec, u16 *cp01) { const struct rtl_coalesce_info *ci; u16 i; ci = rtl_coalesce_info(tp); if (IS_ERR(ci)) return PTR_ERR(ci); for (i = 0; i < 4; i++) { if (usec <= ci->scale_nsecs[i] * RTL_COALESCE_T_MAX / 1000U) { *cp01 = i; return ci->scale_nsecs[i]; } } return -ERANGE; } static int rtl_set_coalesce(struct net_device *dev, struct ethtool_coalesce *ec, struct kernel_ethtool_coalesce *kernel_coal, struct netlink_ext_ack *extack) { struct rtl8169_private *tp = netdev_priv(dev); u32 tx_fr = ec->tx_max_coalesced_frames; u32 rx_fr = ec->rx_max_coalesced_frames; u32 coal_usec_max, units; u16 w = 0, cp01 = 0; int scale; if (rtl_is_8125(tp)) return -EOPNOTSUPP; if (rx_fr > RTL_COALESCE_FRAME_MAX || tx_fr > RTL_COALESCE_FRAME_MAX) return -ERANGE; coal_usec_max = max(ec->rx_coalesce_usecs, ec->tx_coalesce_usecs); scale = rtl_coalesce_choose_scale(tp, coal_usec_max, &cp01); if (scale < 0) return scale; /* Accept max_frames=1 we returned in rtl_get_coalesce. Accept it * not only when usecs=0 because of e.g. the following scenario: * * - both rx_usecs=0 & rx_frames=0 in hardware (no delay on RX) * - rtl_get_coalesce returns rx_usecs=0, rx_frames=1 * - then user does `ethtool -C eth0 rx-usecs 100` * * Since ethtool sends to kernel whole ethtool_coalesce settings, * if we want to ignore rx_frames then it has to be set to 0. */ if (rx_fr == 1) rx_fr = 0; if (tx_fr == 1) tx_fr = 0; /* HW requires time limit to be set if frame limit is set */ if ((tx_fr && !ec->tx_coalesce_usecs) || (rx_fr && !ec->rx_coalesce_usecs)) return -EINVAL; w |= FIELD_PREP(RTL_COALESCE_TX_FRAMES, DIV_ROUND_UP(tx_fr, 4)); w |= FIELD_PREP(RTL_COALESCE_RX_FRAMES, DIV_ROUND_UP(rx_fr, 4)); units = DIV_ROUND_UP(ec->tx_coalesce_usecs * 1000U, scale); w |= FIELD_PREP(RTL_COALESCE_TX_USECS, units); units = DIV_ROUND_UP(ec->rx_coalesce_usecs * 1000U, scale); w |= FIELD_PREP(RTL_COALESCE_RX_USECS, units); RTL_W16(tp, IntrMitigate, w); /* Meaning of PktCntrDisable bit changed from RTL8168e-vl */ if (rtl_is_8168evl_up(tp)) { if (!rx_fr && !tx_fr) /* disable packet counter */ tp->cp_cmd |= PktCntrDisable; else tp->cp_cmd &= ~PktCntrDisable; } tp->cp_cmd = (tp->cp_cmd & ~INTT_MASK) | cp01; RTL_W16(tp, CPlusCmd, tp->cp_cmd); rtl_pci_commit(tp); return 0; } static int rtl8169_get_eee(struct net_device *dev, struct ethtool_eee *data) { struct rtl8169_private *tp = netdev_priv(dev); if (!rtl_supports_eee(tp)) return -EOPNOTSUPP; return phy_ethtool_get_eee(tp->phydev, data); } static int rtl8169_set_eee(struct net_device *dev, struct ethtool_eee *data) { struct rtl8169_private *tp = netdev_priv(dev); int ret; if (!rtl_supports_eee(tp)) return -EOPNOTSUPP; ret = phy_ethtool_set_eee(tp->phydev, data); if (!ret) tp->eee_adv = phy_read_mmd(dev->phydev, MDIO_MMD_AN, MDIO_AN_EEE_ADV); return ret; } static void rtl8169_get_ringparam(struct net_device *dev, struct ethtool_ringparam *data, struct kernel_ethtool_ringparam *kernel_data, struct netlink_ext_ack *extack) { data->rx_max_pending = NUM_RX_DESC; data->rx_pending = NUM_RX_DESC; data->tx_max_pending = NUM_TX_DESC; data->tx_pending = NUM_TX_DESC; } static void rtl8169_get_pauseparam(struct net_device *dev, struct ethtool_pauseparam *data) { struct rtl8169_private *tp = netdev_priv(dev); bool tx_pause, rx_pause; phy_get_pause(tp->phydev, &tx_pause, &rx_pause); data->autoneg = tp->phydev->autoneg; data->tx_pause = tx_pause ? 1 : 0; data->rx_pause = rx_pause ? 1 : 0; } static int rtl8169_set_pauseparam(struct net_device *dev, struct ethtool_pauseparam *data) { struct rtl8169_private *tp = netdev_priv(dev); if (dev->mtu > ETH_DATA_LEN) return -EOPNOTSUPP; phy_set_asym_pause(tp->phydev, data->rx_pause, data->tx_pause); return 0; } static const struct ethtool_ops rtl8169_ethtool_ops = { .supported_coalesce_params = ETHTOOL_COALESCE_USECS | ETHTOOL_COALESCE_MAX_FRAMES, .get_drvinfo = rtl8169_get_drvinfo, .get_regs_len = rtl8169_get_regs_len, .get_link = ethtool_op_get_link, .get_coalesce = rtl_get_coalesce, .set_coalesce = rtl_set_coalesce, .get_regs = rtl8169_get_regs, .get_wol = rtl8169_get_wol, .set_wol = rtl8169_set_wol, .get_strings = rtl8169_get_strings, .get_sset_count = rtl8169_get_sset_count, .get_ethtool_stats = rtl8169_get_ethtool_stats, .get_ts_info = ethtool_op_get_ts_info, .nway_reset = phy_ethtool_nway_reset, .get_eee = rtl8169_get_eee, .set_eee = rtl8169_set_eee, .get_link_ksettings = phy_ethtool_get_link_ksettings, .set_link_ksettings = phy_ethtool_set_link_ksettings, .get_ringparam = rtl8169_get_ringparam, .get_pauseparam = rtl8169_get_pauseparam, .set_pauseparam = rtl8169_set_pauseparam, }; static void rtl_enable_eee(struct rtl8169_private *tp) { struct phy_device *phydev = tp->phydev; int adv; /* respect EEE advertisement the user may have set */ if (tp->eee_adv >= 0) adv = tp->eee_adv; else adv = phy_read_mmd(phydev, MDIO_MMD_PCS, MDIO_PCS_EEE_ABLE); if (adv >= 0) phy_write_mmd(phydev, MDIO_MMD_AN, MDIO_AN_EEE_ADV, adv); } static enum mac_version rtl8169_get_mac_version(u16 xid, bool gmii) { /* * The driver currently handles the 8168Bf and the 8168Be identically * but they can be identified more specifically through the test below * if needed: * * (RTL_R32(tp, TxConfig) & 0x700000) == 0x500000 ? 8168Bf : 8168Be * * Same thing for the 8101Eb and the 8101Ec: * * (RTL_R32(tp, TxConfig) & 0x700000) == 0x200000 ? 8101Eb : 8101Ec */ static const struct rtl_mac_info { u16 mask; u16 val; enum mac_version ver; } mac_info[] = { /* 8125B family. */ { 0x7cf, 0x641, RTL_GIGA_MAC_VER_63 }, /* 8125A family. */ { 0x7cf, 0x609, RTL_GIGA_MAC_VER_61 }, /* It seems only XID 609 made it to the mass market. * { 0x7cf, 0x608, RTL_GIGA_MAC_VER_60 }, * { 0x7c8, 0x608, RTL_GIGA_MAC_VER_61 }, */ /* RTL8117 */ { 0x7cf, 0x54b, RTL_GIGA_MAC_VER_53 }, { 0x7cf, 0x54a, RTL_GIGA_MAC_VER_52 }, /* 8168EP family. */ { 0x7cf, 0x502, RTL_GIGA_MAC_VER_51 }, /* It seems this chip version never made it to * the wild. Let's disable detection. * { 0x7cf, 0x501, RTL_GIGA_MAC_VER_50 }, * { 0x7cf, 0x500, RTL_GIGA_MAC_VER_49 }, */ /* 8168H family. */ { 0x7cf, 0x541, RTL_GIGA_MAC_VER_46 }, /* It seems this chip version never made it to * the wild. Let's disable detection. * { 0x7cf, 0x540, RTL_GIGA_MAC_VER_45 }, */ /* 8168G family. */ { 0x7cf, 0x5c8, RTL_GIGA_MAC_VER_44 }, { 0x7cf, 0x509, RTL_GIGA_MAC_VER_42 }, /* It seems this chip version never made it to * the wild. Let's disable detection. * { 0x7cf, 0x4c1, RTL_GIGA_MAC_VER_41 }, */ { 0x7cf, 0x4c0, RTL_GIGA_MAC_VER_40 }, /* 8168F family. */ { 0x7c8, 0x488, RTL_GIGA_MAC_VER_38 }, { 0x7cf, 0x481, RTL_GIGA_MAC_VER_36 }, { 0x7cf, 0x480, RTL_GIGA_MAC_VER_35 }, /* 8168E family. */ { 0x7c8, 0x2c8, RTL_GIGA_MAC_VER_34 }, { 0x7cf, 0x2c1, RTL_GIGA_MAC_VER_32 }, { 0x7c8, 0x2c0, RTL_GIGA_MAC_VER_33 }, /* 8168D family. */ { 0x7cf, 0x281, RTL_GIGA_MAC_VER_25 }, { 0x7c8, 0x280, RTL_GIGA_MAC_VER_26 }, /* 8168DP family. */ /* It seems this early RTL8168dp version never made it to * the wild. Support has been removed. * { 0x7cf, 0x288, RTL_GIGA_MAC_VER_27 }, */ { 0x7cf, 0x28a, RTL_GIGA_MAC_VER_28 }, { 0x7cf, 0x28b, RTL_GIGA_MAC_VER_31 }, /* 8168C family. */ { 0x7cf, 0x3c9, RTL_GIGA_MAC_VER_23 }, { 0x7cf, 0x3c8, RTL_GIGA_MAC_VER_18 }, { 0x7c8, 0x3c8, RTL_GIGA_MAC_VER_24 }, { 0x7cf, 0x3c0, RTL_GIGA_MAC_VER_19 }, { 0x7cf, 0x3c2, RTL_GIGA_MAC_VER_20 }, { 0x7cf, 0x3c3, RTL_GIGA_MAC_VER_21 }, { 0x7c8, 0x3c0, RTL_GIGA_MAC_VER_22 }, /* 8168B family. */ { 0x7c8, 0x380, RTL_GIGA_MAC_VER_17 }, { 0x7c8, 0x300, RTL_GIGA_MAC_VER_11 }, /* 8101 family. */ { 0x7c8, 0x448, RTL_GIGA_MAC_VER_39 }, { 0x7c8, 0x440, RTL_GIGA_MAC_VER_37 }, { 0x7cf, 0x409, RTL_GIGA_MAC_VER_29 }, { 0x7c8, 0x408, RTL_GIGA_MAC_VER_30 }, { 0x7cf, 0x349, RTL_GIGA_MAC_VER_08 }, { 0x7cf, 0x249, RTL_GIGA_MAC_VER_08 }, { 0x7cf, 0x348, RTL_GIGA_MAC_VER_07 }, { 0x7cf, 0x248, RTL_GIGA_MAC_VER_07 }, { 0x7cf, 0x240, RTL_GIGA_MAC_VER_14 }, { 0x7c8, 0x348, RTL_GIGA_MAC_VER_09 }, { 0x7c8, 0x248, RTL_GIGA_MAC_VER_09 }, { 0x7c8, 0x340, RTL_GIGA_MAC_VER_10 }, /* 8110 family. */ { 0xfc8, 0x980, RTL_GIGA_MAC_VER_06 }, { 0xfc8, 0x180, RTL_GIGA_MAC_VER_05 }, { 0xfc8, 0x100, RTL_GIGA_MAC_VER_04 }, { 0xfc8, 0x040, RTL_GIGA_MAC_VER_03 }, { 0xfc8, 0x008, RTL_GIGA_MAC_VER_02 }, /* Catch-all */ { 0x000, 0x000, RTL_GIGA_MAC_NONE } }; const struct rtl_mac_info *p = mac_info; enum mac_version ver; while ((xid & p->mask) != p->val) p++; ver = p->ver; if (ver != RTL_GIGA_MAC_NONE && !gmii) { if (ver == RTL_GIGA_MAC_VER_42) ver = RTL_GIGA_MAC_VER_43; else if (ver == RTL_GIGA_MAC_VER_46) ver = RTL_GIGA_MAC_VER_48; } return ver; } static void rtl_release_firmware(struct rtl8169_private *tp) { if (tp->rtl_fw) { rtl_fw_release_firmware(tp->rtl_fw); kfree(tp->rtl_fw); tp->rtl_fw = NULL; } } void r8169_apply_firmware(struct rtl8169_private *tp) { int val; /* TODO: release firmware if rtl_fw_write_firmware signals failure. */ if (tp->rtl_fw) { rtl_fw_write_firmware(tp, tp->rtl_fw); /* At least one firmware doesn't reset tp->ocp_base. */ tp->ocp_base = OCP_STD_PHY_BASE; /* PHY soft reset may still be in progress */ phy_read_poll_timeout(tp->phydev, MII_BMCR, val, !(val & BMCR_RESET), 50000, 600000, true); } } static void rtl8168_config_eee_mac(struct rtl8169_private *tp) { /* Adjust EEE LED frequency */ if (tp->mac_version != RTL_GIGA_MAC_VER_38) RTL_W8(tp, EEE_LED, RTL_R8(tp, EEE_LED) & ~0x07); rtl_eri_set_bits(tp, 0x1b0, 0x0003); } static void rtl8125a_config_eee_mac(struct rtl8169_private *tp) { r8168_mac_ocp_modify(tp, 0xe040, 0, BIT(1) | BIT(0)); r8168_mac_ocp_modify(tp, 0xeb62, 0, BIT(2) | BIT(1)); } static void rtl8125_set_eee_txidle_timer(struct rtl8169_private *tp) { RTL_W16(tp, EEE_TXIDLE_TIMER_8125, tp->dev->mtu + ETH_HLEN + 0x20); } static void rtl8125b_config_eee_mac(struct rtl8169_private *tp) { rtl8125_set_eee_txidle_timer(tp); r8168_mac_ocp_modify(tp, 0xe040, 0, BIT(1) | BIT(0)); } static void rtl_rar_exgmac_set(struct rtl8169_private *tp, const u8 *addr) { rtl_eri_write(tp, 0xe0, ERIAR_MASK_1111, get_unaligned_le32(addr)); rtl_eri_write(tp, 0xe4, ERIAR_MASK_1111, get_unaligned_le16(addr + 4)); rtl_eri_write(tp, 0xf0, ERIAR_MASK_1111, get_unaligned_le16(addr) << 16); rtl_eri_write(tp, 0xf4, ERIAR_MASK_1111, get_unaligned_le32(addr + 2)); } u16 rtl8168h_2_get_adc_bias_ioffset(struct rtl8169_private *tp) { u16 data1, data2, ioffset; r8168_mac_ocp_write(tp, 0xdd02, 0x807d); data1 = r8168_mac_ocp_read(tp, 0xdd02); data2 = r8168_mac_ocp_read(tp, 0xdd00); ioffset = (data2 >> 1) & 0x7ff8; ioffset |= data2 & 0x0007; if (data1 & BIT(7)) ioffset |= BIT(15); return ioffset; } static void rtl_schedule_task(struct rtl8169_private *tp, enum rtl_flag flag) { set_bit(flag, tp->wk.flags); schedule_work(&tp->wk.work); } static void rtl8169_init_phy(struct rtl8169_private *tp) { r8169_hw_phy_config(tp, tp->phydev, tp->mac_version); if (tp->mac_version <= RTL_GIGA_MAC_VER_06) { pci_write_config_byte(tp->pci_dev, PCI_LATENCY_TIMER, 0x40); pci_write_config_byte(tp->pci_dev, PCI_CACHE_LINE_SIZE, 0x08); /* set undocumented MAC Reg C+CR Offset 0x82h */ RTL_W8(tp, 0x82, 0x01); } if (tp->mac_version == RTL_GIGA_MAC_VER_05 && tp->pci_dev->subsystem_vendor == PCI_VENDOR_ID_GIGABYTE && tp->pci_dev->subsystem_device == 0xe000) phy_write_paged(tp->phydev, 0x0001, 0x10, 0xf01b); /* We may have called phy_speed_down before */ phy_speed_up(tp->phydev); if (rtl_supports_eee(tp)) rtl_enable_eee(tp); genphy_soft_reset(tp->phydev); } static void rtl_rar_set(struct rtl8169_private *tp, const u8 *addr) { rtl_unlock_config_regs(tp); RTL_W32(tp, MAC4, get_unaligned_le16(addr + 4)); rtl_pci_commit(tp); RTL_W32(tp, MAC0, get_unaligned_le32(addr)); rtl_pci_commit(tp); if (tp->mac_version == RTL_GIGA_MAC_VER_34) rtl_rar_exgmac_set(tp, addr); rtl_lock_config_regs(tp); } static int rtl_set_mac_address(struct net_device *dev, void *p) { struct rtl8169_private *tp = netdev_priv(dev); int ret; ret = eth_mac_addr(dev, p); if (ret) return ret; rtl_rar_set(tp, dev->dev_addr); return 0; } static void rtl_init_rxcfg(struct rtl8169_private *tp) { switch (tp->mac_version) { case RTL_GIGA_MAC_VER_02 ... RTL_GIGA_MAC_VER_06: case RTL_GIGA_MAC_VER_10 ... RTL_GIGA_MAC_VER_17: RTL_W32(tp, RxConfig, RX_FIFO_THRESH | RX_DMA_BURST); break; case RTL_GIGA_MAC_VER_18 ... RTL_GIGA_MAC_VER_24: case RTL_GIGA_MAC_VER_34 ... RTL_GIGA_MAC_VER_36: case RTL_GIGA_MAC_VER_38: RTL_W32(tp, RxConfig, RX128_INT_EN | RX_MULTI_EN | RX_DMA_BURST); break; case RTL_GIGA_MAC_VER_40 ... RTL_GIGA_MAC_VER_53: RTL_W32(tp, RxConfig, RX128_INT_EN | RX_MULTI_EN | RX_DMA_BURST | RX_EARLY_OFF); break; case RTL_GIGA_MAC_VER_61 ... RTL_GIGA_MAC_VER_63: RTL_W32(tp, RxConfig, RX_FETCH_DFLT_8125 | RX_DMA_BURST); break; default: RTL_W32(tp, RxConfig, RX128_INT_EN | RX_DMA_BURST); break; } } static void rtl8169_init_ring_indexes(struct rtl8169_private *tp) { tp->dirty_tx = tp->cur_tx = tp->cur_rx = 0; } static void r8168c_hw_jumbo_enable(struct rtl8169_private *tp) { RTL_W8(tp, Config3, RTL_R8(tp, Config3) | Jumbo_En0); RTL_W8(tp, Config4, RTL_R8(tp, Config4) | Jumbo_En1); } static void r8168c_hw_jumbo_disable(struct rtl8169_private *tp) { RTL_W8(tp, Config3, RTL_R8(tp, Config3) & ~Jumbo_En0); RTL_W8(tp, Config4, RTL_R8(tp, Config4) & ~Jumbo_En1); } static void r8168dp_hw_jumbo_enable(struct rtl8169_private *tp) { RTL_W8(tp, Config3, RTL_R8(tp, Config3) | Jumbo_En0); } static void r8168dp_hw_jumbo_disable(struct rtl8169_private *tp) { RTL_W8(tp, Config3, RTL_R8(tp, Config3) & ~Jumbo_En0); } static void r8168e_hw_jumbo_enable(struct rtl8169_private *tp) { RTL_W8(tp, MaxTxPacketSize, 0x24); RTL_W8(tp, Config3, RTL_R8(tp, Config3) | Jumbo_En0); RTL_W8(tp, Config4, RTL_R8(tp, Config4) | 0x01); } static void r8168e_hw_jumbo_disable(struct rtl8169_private *tp) { RTL_W8(tp, MaxTxPacketSize, 0x3f); RTL_W8(tp, Config3, RTL_R8(tp, Config3) & ~Jumbo_En0); RTL_W8(tp, Config4, RTL_R8(tp, Config4) & ~0x01); } static void r8168b_1_hw_jumbo_enable(struct rtl8169_private *tp) { RTL_W8(tp, Config4, RTL_R8(tp, Config4) | (1 << 0)); } static void r8168b_1_hw_jumbo_disable(struct rtl8169_private *tp) { RTL_W8(tp, Config4, RTL_R8(tp, Config4) & ~(1 << 0)); } static void rtl_jumbo_config(struct rtl8169_private *tp) { bool jumbo = tp->dev->mtu > ETH_DATA_LEN; int readrq = 4096; rtl_unlock_config_regs(tp); switch (tp->mac_version) { case RTL_GIGA_MAC_VER_17: if (jumbo) { readrq = 512; r8168b_1_hw_jumbo_enable(tp); } else { r8168b_1_hw_jumbo_disable(tp); } break; case RTL_GIGA_MAC_VER_18 ... RTL_GIGA_MAC_VER_26: if (jumbo) { readrq = 512; r8168c_hw_jumbo_enable(tp); } else { r8168c_hw_jumbo_disable(tp); } break; case RTL_GIGA_MAC_VER_28: if (jumbo) r8168dp_hw_jumbo_enable(tp); else r8168dp_hw_jumbo_disable(tp); break; case RTL_GIGA_MAC_VER_31 ... RTL_GIGA_MAC_VER_33: if (jumbo) r8168e_hw_jumbo_enable(tp); else r8168e_hw_jumbo_disable(tp); break; default: break; } rtl_lock_config_regs(tp); if (pci_is_pcie(tp->pci_dev) && tp->supports_gmii) pcie_set_readrq(tp->pci_dev, readrq); /* Chip doesn't support pause in jumbo mode */ if (jumbo) { linkmode_clear_bit(ETHTOOL_LINK_MODE_Pause_BIT, tp->phydev->advertising); linkmode_clear_bit(ETHTOOL_LINK_MODE_Asym_Pause_BIT, tp->phydev->advertising); phy_start_aneg(tp->phydev); } } DECLARE_RTL_COND(rtl_chipcmd_cond) { return RTL_R8(tp, ChipCmd) & CmdReset; } static void rtl_hw_reset(struct rtl8169_private *tp) { RTL_W8(tp, ChipCmd, CmdReset); rtl_loop_wait_low(tp, &rtl_chipcmd_cond, 100, 100); } static void rtl_request_firmware(struct rtl8169_private *tp) { struct rtl_fw *rtl_fw; /* firmware loaded already or no firmware available */ if (tp->rtl_fw || !tp->fw_name) return; rtl_fw = kzalloc(sizeof(*rtl_fw), GFP_KERNEL); if (!rtl_fw) return; rtl_fw->phy_write = rtl_writephy; rtl_fw->phy_read = rtl_readphy; rtl_fw->mac_mcu_write = mac_mcu_write; rtl_fw->mac_mcu_read = mac_mcu_read; rtl_fw->fw_name = tp->fw_name; rtl_fw->dev = tp_to_dev(tp); if (rtl_fw_request_firmware(rtl_fw)) kfree(rtl_fw); else tp->rtl_fw = rtl_fw; } static void rtl_rx_close(struct rtl8169_private *tp) { RTL_W32(tp, RxConfig, RTL_R32(tp, RxConfig) & ~RX_CONFIG_ACCEPT_MASK); } DECLARE_RTL_COND(rtl_npq_cond) { return RTL_R8(tp, TxPoll) & NPQ; } DECLARE_RTL_COND(rtl_txcfg_empty_cond) { return RTL_R32(tp, TxConfig) & TXCFG_EMPTY; } DECLARE_RTL_COND(rtl_rxtx_empty_cond) { return (RTL_R8(tp, MCU) & RXTX_EMPTY) == RXTX_EMPTY; } DECLARE_RTL_COND(rtl_rxtx_empty_cond_2) { /* IntrMitigate has new functionality on RTL8125 */ return (RTL_R16(tp, IntrMitigate) & 0x0103) == 0x0103; } static void rtl_wait_txrx_fifo_empty(struct rtl8169_private *tp) { switch (tp->mac_version) { case RTL_GIGA_MAC_VER_40 ... RTL_GIGA_MAC_VER_53: rtl_loop_wait_high(tp, &rtl_txcfg_empty_cond, 100, 42); rtl_loop_wait_high(tp, &rtl_rxtx_empty_cond, 100, 42); break; case RTL_GIGA_MAC_VER_61 ... RTL_GIGA_MAC_VER_61: rtl_loop_wait_high(tp, &rtl_rxtx_empty_cond, 100, 42); break; case RTL_GIGA_MAC_VER_63: RTL_W8(tp, ChipCmd, RTL_R8(tp, ChipCmd) | StopReq); rtl_loop_wait_high(tp, &rtl_rxtx_empty_cond, 100, 42); rtl_loop_wait_high(tp, &rtl_rxtx_empty_cond_2, 100, 42); break; default: break; } } static void rtl_disable_rxdvgate(struct rtl8169_private *tp) { RTL_W32(tp, MISC, RTL_R32(tp, MISC) & ~RXDV_GATED_EN); } static void rtl_enable_rxdvgate(struct rtl8169_private *tp) { RTL_W32(tp, MISC, RTL_R32(tp, MISC) | RXDV_GATED_EN); fsleep(2000); rtl_wait_txrx_fifo_empty(tp); } static void rtl_wol_enable_rx(struct rtl8169_private *tp) { if (tp->mac_version >= RTL_GIGA_MAC_VER_25) RTL_W32(tp, RxConfig, RTL_R32(tp, RxConfig) | AcceptBroadcast | AcceptMulticast | AcceptMyPhys); if (tp->mac_version >= RTL_GIGA_MAC_VER_40) rtl_disable_rxdvgate(tp); } static void rtl_prepare_power_down(struct rtl8169_private *tp) { if (tp->dash_type != RTL_DASH_NONE) return; if (tp->mac_version == RTL_GIGA_MAC_VER_32 || tp->mac_version == RTL_GIGA_MAC_VER_33) rtl_ephy_write(tp, 0x19, 0xff64); if (device_may_wakeup(tp_to_dev(tp))) { phy_speed_down(tp->phydev, false); rtl_wol_enable_rx(tp); } } static void rtl_set_tx_config_registers(struct rtl8169_private *tp) { u32 val = TX_DMA_BURST << TxDMAShift | InterFrameGap << TxInterFrameGapShift; if (rtl_is_8168evl_up(tp)) val |= TXCFG_AUTO_FIFO; RTL_W32(tp, TxConfig, val); } static void rtl_set_rx_max_size(struct rtl8169_private *tp) { /* Low hurts. Let's disable the filtering. */ RTL_W16(tp, RxMaxSize, R8169_RX_BUF_SIZE + 1); } static void rtl_set_rx_tx_desc_registers(struct rtl8169_private *tp) { /* * Magic spell: some iop3xx ARM board needs the TxDescAddrHigh * register to be written before TxDescAddrLow to work. * Switching from MMIO to I/O access fixes the issue as well. */ RTL_W32(tp, TxDescStartAddrHigh, ((u64) tp->TxPhyAddr) >> 32); RTL_W32(tp, TxDescStartAddrLow, ((u64) tp->TxPhyAddr) & DMA_BIT_MASK(32)); RTL_W32(tp, RxDescAddrHigh, ((u64) tp->RxPhyAddr) >> 32); RTL_W32(tp, RxDescAddrLow, ((u64) tp->RxPhyAddr) & DMA_BIT_MASK(32)); } static void rtl8169_set_magic_reg(struct rtl8169_private *tp) { u32 val; if (tp->mac_version == RTL_GIGA_MAC_VER_05) val = 0x000fff00; else if (tp->mac_version == RTL_GIGA_MAC_VER_06) val = 0x00ffff00; else return; if (RTL_R8(tp, Config2) & PCI_Clock_66MHz) val |= 0xff; RTL_W32(tp, 0x7c, val); } static void rtl_set_rx_mode(struct net_device *dev) { u32 rx_mode = AcceptBroadcast | AcceptMyPhys | AcceptMulticast; /* Multicast hash filter */ u32 mc_filter[2] = { 0xffffffff, 0xffffffff }; struct rtl8169_private *tp = netdev_priv(dev); u32 tmp; if (dev->flags & IFF_PROMISC) { rx_mode |= AcceptAllPhys; } else if (netdev_mc_count(dev) > MC_FILTER_LIMIT || dev->flags & IFF_ALLMULTI || tp->mac_version == RTL_GIGA_MAC_VER_35) { /* accept all multicasts */ } else if (netdev_mc_empty(dev)) { rx_mode &= ~AcceptMulticast; } else { struct netdev_hw_addr *ha; mc_filter[1] = mc_filter[0] = 0; netdev_for_each_mc_addr(ha, dev) { u32 bit_nr = eth_hw_addr_crc(ha) >> 26; mc_filter[bit_nr >> 5] |= BIT(bit_nr & 31); } if (tp->mac_version > RTL_GIGA_MAC_VER_06) { tmp = mc_filter[0]; mc_filter[0] = swab32(mc_filter[1]); mc_filter[1] = swab32(tmp); } } RTL_W32(tp, MAR0 + 4, mc_filter[1]); RTL_W32(tp, MAR0 + 0, mc_filter[0]); tmp = RTL_R32(tp, RxConfig); RTL_W32(tp, RxConfig, (tmp & ~RX_CONFIG_ACCEPT_OK_MASK) | rx_mode); } DECLARE_RTL_COND(rtl_csiar_cond) { return RTL_R32(tp, CSIAR) & CSIAR_FLAG; } static void rtl_csi_write(struct rtl8169_private *tp, int addr, int value) { u32 func = PCI_FUNC(tp->pci_dev->devfn); RTL_W32(tp, CSIDR, value); RTL_W32(tp, CSIAR, CSIAR_WRITE_CMD | (addr & CSIAR_ADDR_MASK) | CSIAR_BYTE_ENABLE | func << 16); rtl_loop_wait_low(tp, &rtl_csiar_cond, 10, 100); } static u32 rtl_csi_read(struct rtl8169_private *tp, int addr) { u32 func = PCI_FUNC(tp->pci_dev->devfn); RTL_W32(tp, CSIAR, (addr & CSIAR_ADDR_MASK) | func << 16 | CSIAR_BYTE_ENABLE); return rtl_loop_wait_high(tp, &rtl_csiar_cond, 10, 100) ? RTL_R32(tp, CSIDR) : ~0; } static void rtl_set_aspm_entry_latency(struct rtl8169_private *tp, u8 val) { struct pci_dev *pdev = tp->pci_dev; u32 csi; /* According to Realtek the value at config space address 0x070f * controls the L0s/L1 entrance latency. We try standard ECAM access * first and if it fails fall back to CSI. * bit 0..2: L0: 0 = 1us, 1 = 2us .. 6 = 7us, 7 = 7us (no typo) * bit 3..5: L1: 0 = 1us, 1 = 2us .. 6 = 64us, 7 = 64us */ if (pdev->cfg_size > 0x070f && pci_write_config_byte(pdev, 0x070f, val) == PCIBIOS_SUCCESSFUL) return; netdev_notice_once(tp->dev, "No native access to PCI extended config space, falling back to CSI\n"); csi = rtl_csi_read(tp, 0x070c) & 0x00ffffff; rtl_csi_write(tp, 0x070c, csi | val << 24); } static void rtl_set_def_aspm_entry_latency(struct rtl8169_private *tp) { /* L0 7us, L1 16us */ rtl_set_aspm_entry_latency(tp, 0x27); } struct ephy_info { unsigned int offset; u16 mask; u16 bits; }; static void __rtl_ephy_init(struct rtl8169_private *tp, const struct ephy_info *e, int len) { u16 w; while (len-- > 0) { w = (rtl_ephy_read(tp, e->offset) & ~e->mask) | e->bits; rtl_ephy_write(tp, e->offset, w); e++; } } #define rtl_ephy_init(tp, a) __rtl_ephy_init(tp, a, ARRAY_SIZE(a)) static void rtl_disable_clock_request(struct rtl8169_private *tp) { pcie_capability_clear_word(tp->pci_dev, PCI_EXP_LNKCTL, PCI_EXP_LNKCTL_CLKREQ_EN); } static void rtl_enable_clock_request(struct rtl8169_private *tp) { pcie_capability_set_word(tp->pci_dev, PCI_EXP_LNKCTL, PCI_EXP_LNKCTL_CLKREQ_EN); } static void rtl_pcie_state_l2l3_disable(struct rtl8169_private *tp) { /* work around an issue when PCI reset occurs during L2/L3 state */ RTL_W8(tp, Config3, RTL_R8(tp, Config3) & ~Rdy_to_L23); } static void rtl_enable_exit_l1(struct rtl8169_private *tp) { /* Bits control which events trigger ASPM L1 exit: * Bit 12: rxdv * Bit 11: ltr_msg * Bit 10: txdma_poll * Bit 9: xadm * Bit 8: pktavi * Bit 7: txpla */ switch (tp->mac_version) { case RTL_GIGA_MAC_VER_34 ... RTL_GIGA_MAC_VER_36: rtl_eri_set_bits(tp, 0xd4, 0x1f00); break; case RTL_GIGA_MAC_VER_37 ... RTL_GIGA_MAC_VER_38: rtl_eri_set_bits(tp, 0xd4, 0x0c00); break; case RTL_GIGA_MAC_VER_40 ... RTL_GIGA_MAC_VER_63: r8168_mac_ocp_modify(tp, 0xc0ac, 0, 0x1f80); break; default: break; } } static void rtl_disable_exit_l1(struct rtl8169_private *tp) { switch (tp->mac_version) { case RTL_GIGA_MAC_VER_34 ... RTL_GIGA_MAC_VER_38: rtl_eri_clear_bits(tp, 0xd4, 0x1f00); break; case RTL_GIGA_MAC_VER_40 ... RTL_GIGA_MAC_VER_63: r8168_mac_ocp_modify(tp, 0xc0ac, 0x1f80, 0); break; default: break; } } static void rtl_hw_aspm_clkreq_enable(struct rtl8169_private *tp, bool enable) { if (tp->mac_version < RTL_GIGA_MAC_VER_32) return; /* Don't enable ASPM in the chip if OS can't control ASPM */ if (enable && tp->aspm_manageable) { /* On these chip versions ASPM can even harm * bus communication of other PCI devices. */ if (tp->mac_version == RTL_GIGA_MAC_VER_42 || tp->mac_version == RTL_GIGA_MAC_VER_43) return; rtl_mod_config5(tp, 0, ASPM_en); rtl_mod_config2(tp, 0, ClkReqEn); switch (tp->mac_version) { case RTL_GIGA_MAC_VER_46 ... RTL_GIGA_MAC_VER_48: case RTL_GIGA_MAC_VER_61 ... RTL_GIGA_MAC_VER_63: /* reset ephy tx/rx disable timer */ r8168_mac_ocp_modify(tp, 0xe094, 0xff00, 0); /* chip can trigger L1.2 */ r8168_mac_ocp_modify(tp, 0xe092, 0x00ff, BIT(2)); break; default: break; } } else { switch (tp->mac_version) { case RTL_GIGA_MAC_VER_46 ... RTL_GIGA_MAC_VER_48: case RTL_GIGA_MAC_VER_61 ... RTL_GIGA_MAC_VER_63: r8168_mac_ocp_modify(tp, 0xe092, 0x00ff, 0); break; default: break; } rtl_mod_config2(tp, ClkReqEn, 0); rtl_mod_config5(tp, ASPM_en, 0); } } static void rtl_set_fifo_size(struct rtl8169_private *tp, u16 rx_stat, u16 tx_stat, u16 rx_dyn, u16 tx_dyn) { /* Usage of dynamic vs. static FIFO is controlled by bit * TXCFG_AUTO_FIFO. Exact meaning of FIFO values isn't known. */ rtl_eri_write(tp, 0xc8, ERIAR_MASK_1111, (rx_stat << 16) | rx_dyn); rtl_eri_write(tp, 0xe8, ERIAR_MASK_1111, (tx_stat << 16) | tx_dyn); } static void rtl8168g_set_pause_thresholds(struct rtl8169_private *tp, u8 low, u8 high) { /* FIFO thresholds for pause flow control */ rtl_eri_write(tp, 0xcc, ERIAR_MASK_0001, low); rtl_eri_write(tp, 0xd0, ERIAR_MASK_0001, high); } static void rtl_hw_start_8168b(struct rtl8169_private *tp) { RTL_W8(tp, Config3, RTL_R8(tp, Config3) & ~Beacon_en); } static void __rtl_hw_start_8168cp(struct rtl8169_private *tp) { RTL_W8(tp, Config1, RTL_R8(tp, Config1) | Speed_down); RTL_W8(tp, Config3, RTL_R8(tp, Config3) & ~Beacon_en); rtl_disable_clock_request(tp); } static void rtl_hw_start_8168cp_1(struct rtl8169_private *tp) { static const struct ephy_info e_info_8168cp[] = { { 0x01, 0, 0x0001 }, { 0x02, 0x0800, 0x1000 }, { 0x03, 0, 0x0042 }, { 0x06, 0x0080, 0x0000 }, { 0x07, 0, 0x2000 } }; rtl_set_def_aspm_entry_latency(tp); rtl_ephy_init(tp, e_info_8168cp); __rtl_hw_start_8168cp(tp); } static void rtl_hw_start_8168cp_2(struct rtl8169_private *tp) { rtl_set_def_aspm_entry_latency(tp); RTL_W8(tp, Config3, RTL_R8(tp, Config3) & ~Beacon_en); } static void rtl_hw_start_8168cp_3(struct rtl8169_private *tp) { rtl_set_def_aspm_entry_latency(tp); RTL_W8(tp, Config3, RTL_R8(tp, Config3) & ~Beacon_en); /* Magic. */ RTL_W8(tp, DBG_REG, 0x20); } static void rtl_hw_start_8168c_1(struct rtl8169_private *tp) { static const struct ephy_info e_info_8168c_1[] = { { 0x02, 0x0800, 0x1000 }, { 0x03, 0, 0x0002 }, { 0x06, 0x0080, 0x0000 } }; rtl_set_def_aspm_entry_latency(tp); RTL_W8(tp, DBG_REG, 0x06 | FIX_NAK_1 | FIX_NAK_2); rtl_ephy_init(tp, e_info_8168c_1); __rtl_hw_start_8168cp(tp); } static void rtl_hw_start_8168c_2(struct rtl8169_private *tp) { static const struct ephy_info e_info_8168c_2[] = { { 0x01, 0, 0x0001 }, { 0x03, 0x0400, 0x0020 } }; rtl_set_def_aspm_entry_latency(tp); rtl_ephy_init(tp, e_info_8168c_2); __rtl_hw_start_8168cp(tp); } static void rtl_hw_start_8168c_4(struct rtl8169_private *tp) { rtl_set_def_aspm_entry_latency(tp); __rtl_hw_start_8168cp(tp); } static void rtl_hw_start_8168d(struct rtl8169_private *tp) { rtl_set_def_aspm_entry_latency(tp); rtl_disable_clock_request(tp); } static void rtl_hw_start_8168d_4(struct rtl8169_private *tp) { static const struct ephy_info e_info_8168d_4[] = { { 0x0b, 0x0000, 0x0048 }, { 0x19, 0x0020, 0x0050 }, { 0x0c, 0x0100, 0x0020 }, { 0x10, 0x0004, 0x0000 }, }; rtl_set_def_aspm_entry_latency(tp); rtl_ephy_init(tp, e_info_8168d_4); rtl_enable_clock_request(tp); } static void rtl_hw_start_8168e_1(struct rtl8169_private *tp) { static const struct ephy_info e_info_8168e_1[] = { { 0x00, 0x0200, 0x0100 }, { 0x00, 0x0000, 0x0004 }, { 0x06, 0x0002, 0x0001 }, { 0x06, 0x0000, 0x0030 }, { 0x07, 0x0000, 0x2000 }, { 0x00, 0x0000, 0x0020 }, { 0x03, 0x5800, 0x2000 }, { 0x03, 0x0000, 0x0001 }, { 0x01, 0x0800, 0x1000 }, { 0x07, 0x0000, 0x4000 }, { 0x1e, 0x0000, 0x2000 }, { 0x19, 0xffff, 0xfe6c }, { 0x0a, 0x0000, 0x0040 } }; rtl_set_def_aspm_entry_latency(tp); rtl_ephy_init(tp, e_info_8168e_1); rtl_disable_clock_request(tp); /* Reset tx FIFO pointer */ RTL_W32(tp, MISC, RTL_R32(tp, MISC) | TXPLA_RST); RTL_W32(tp, MISC, RTL_R32(tp, MISC) & ~TXPLA_RST); rtl_mod_config5(tp, Spi_en, 0); } static void rtl_hw_start_8168e_2(struct rtl8169_private *tp) { static const struct ephy_info e_info_8168e_2[] = { { 0x09, 0x0000, 0x0080 }, { 0x19, 0x0000, 0x0224 }, { 0x00, 0x0000, 0x0004 }, { 0x0c, 0x3df0, 0x0200 }, }; rtl_set_def_aspm_entry_latency(tp); rtl_ephy_init(tp, e_info_8168e_2); rtl_eri_write(tp, 0xc0, ERIAR_MASK_0011, 0x0000); rtl_eri_write(tp, 0xb8, ERIAR_MASK_1111, 0x0000); rtl_set_fifo_size(tp, 0x10, 0x10, 0x02, 0x06); rtl_eri_set_bits(tp, 0x1d0, BIT(1)); rtl_reset_packet_filter(tp); rtl_eri_set_bits(tp, 0x1b0, BIT(4)); rtl_eri_write(tp, 0xcc, ERIAR_MASK_1111, 0x00000050); rtl_eri_write(tp, 0xd0, ERIAR_MASK_1111, 0x07ff0060); rtl_disable_clock_request(tp); RTL_W8(tp, MCU, RTL_R8(tp, MCU) & ~NOW_IS_OOB); rtl8168_config_eee_mac(tp); RTL_W8(tp, DLLPR, RTL_R8(tp, DLLPR) | PFM_EN); RTL_W32(tp, MISC, RTL_R32(tp, MISC) | PWM_EN); rtl_mod_config5(tp, Spi_en, 0); } static void rtl_hw_start_8168f(struct rtl8169_private *tp) { rtl_set_def_aspm_entry_latency(tp); rtl_eri_write(tp, 0xc0, ERIAR_MASK_0011, 0x0000); rtl_eri_write(tp, 0xb8, ERIAR_MASK_1111, 0x0000); rtl_set_fifo_size(tp, 0x10, 0x10, 0x02, 0x06); rtl_reset_packet_filter(tp); rtl_eri_set_bits(tp, 0x1b0, BIT(4)); rtl_eri_set_bits(tp, 0x1d0, BIT(4) | BIT(1)); rtl_eri_write(tp, 0xcc, ERIAR_MASK_1111, 0x00000050); rtl_eri_write(tp, 0xd0, ERIAR_MASK_1111, 0x00000060); rtl_disable_clock_request(tp); RTL_W8(tp, MCU, RTL_R8(tp, MCU) & ~NOW_IS_OOB); RTL_W8(tp, DLLPR, RTL_R8(tp, DLLPR) | PFM_EN); RTL_W32(tp, MISC, RTL_R32(tp, MISC) | PWM_EN); rtl_mod_config5(tp, Spi_en, 0); rtl8168_config_eee_mac(tp); } static void rtl_hw_start_8168f_1(struct rtl8169_private *tp) { static const struct ephy_info e_info_8168f_1[] = { { 0x06, 0x00c0, 0x0020 }, { 0x08, 0x0001, 0x0002 }, { 0x09, 0x0000, 0x0080 }, { 0x19, 0x0000, 0x0224 }, { 0x00, 0x0000, 0x0008 }, { 0x0c, 0x3df0, 0x0200 }, }; rtl_hw_start_8168f(tp); rtl_ephy_init(tp, e_info_8168f_1); } static void rtl_hw_start_8411(struct rtl8169_private *tp) { static const struct ephy_info e_info_8168f_1[] = { { 0x06, 0x00c0, 0x0020 }, { 0x0f, 0xffff, 0x5200 }, { 0x19, 0x0000, 0x0224 }, { 0x00, 0x0000, 0x0008 }, { 0x0c, 0x3df0, 0x0200 }, }; rtl_hw_start_8168f(tp); rtl_pcie_state_l2l3_disable(tp); rtl_ephy_init(tp, e_info_8168f_1); } static void rtl_hw_start_8168g(struct rtl8169_private *tp) { rtl_set_fifo_size(tp, 0x08, 0x10, 0x02, 0x06); rtl8168g_set_pause_thresholds(tp, 0x38, 0x48); rtl_set_def_aspm_entry_latency(tp); rtl_reset_packet_filter(tp); rtl_eri_write(tp, 0x2f8, ERIAR_MASK_0011, 0x1d8f); rtl_disable_rxdvgate(tp); rtl_eri_write(tp, 0xc0, ERIAR_MASK_0011, 0x0000); rtl_eri_write(tp, 0xb8, ERIAR_MASK_0011, 0x0000); rtl8168_config_eee_mac(tp); rtl_w0w1_eri(tp, 0x2fc, 0x01, 0x06); rtl_eri_clear_bits(tp, 0x1b0, BIT(12)); rtl_pcie_state_l2l3_disable(tp); } static void rtl_hw_start_8168g_1(struct rtl8169_private *tp) { static const struct ephy_info e_info_8168g_1[] = { { 0x00, 0x0008, 0x0000 }, { 0x0c, 0x3ff0, 0x0820 }, { 0x1e, 0x0000, 0x0001 }, { 0x19, 0x8000, 0x0000 } }; rtl_hw_start_8168g(tp); rtl_ephy_init(tp, e_info_8168g_1); } static void rtl_hw_start_8168g_2(struct rtl8169_private *tp) { static const struct ephy_info e_info_8168g_2[] = { { 0x00, 0x0008, 0x0000 }, { 0x0c, 0x3ff0, 0x0820 }, { 0x19, 0xffff, 0x7c00 }, { 0x1e, 0xffff, 0x20eb }, { 0x0d, 0xffff, 0x1666 }, { 0x00, 0xffff, 0x10a3 }, { 0x06, 0xffff, 0xf050 }, { 0x04, 0x0000, 0x0010 }, { 0x1d, 0x4000, 0x0000 }, }; rtl_hw_start_8168g(tp); rtl_ephy_init(tp, e_info_8168g_2); } static void rtl_hw_start_8411_2(struct rtl8169_private *tp) { static const struct ephy_info e_info_8411_2[] = { { 0x00, 0x0008, 0x0000 }, { 0x0c, 0x37d0, 0x0820 }, { 0x1e, 0x0000, 0x0001 }, { 0x19, 0x8021, 0x0000 }, { 0x1e, 0x0000, 0x2000 }, { 0x0d, 0x0100, 0x0200 }, { 0x00, 0x0000, 0x0080 }, { 0x06, 0x0000, 0x0010 }, { 0x04, 0x0000, 0x0010 }, { 0x1d, 0x0000, 0x4000 }, }; rtl_hw_start_8168g(tp); rtl_ephy_init(tp, e_info_8411_2); /* The following Realtek-provided magic fixes an issue with the RX unit * getting confused after the PHY having been powered-down. */ r8168_mac_ocp_write(tp, 0xFC28, 0x0000); r8168_mac_ocp_write(tp, 0xFC2A, 0x0000); r8168_mac_ocp_write(tp, 0xFC2C, 0x0000); r8168_mac_ocp_write(tp, 0xFC2E, 0x0000); r8168_mac_ocp_write(tp, 0xFC30, 0x0000); r8168_mac_ocp_write(tp, 0xFC32, 0x0000); r8168_mac_ocp_write(tp, 0xFC34, 0x0000); r8168_mac_ocp_write(tp, 0xFC36, 0x0000); mdelay(3); r8168_mac_ocp_write(tp, 0xFC26, 0x0000); r8168_mac_ocp_write(tp, 0xF800, 0xE008); r8168_mac_ocp_write(tp, 0xF802, 0xE00A); r8168_mac_ocp_write(tp, 0xF804, 0xE00C); r8168_mac_ocp_write(tp, 0xF806, 0xE00E); r8168_mac_ocp_write(tp, 0xF808, 0xE027); r8168_mac_ocp_write(tp, 0xF80A, 0xE04F); r8168_mac_ocp_write(tp, 0xF80C, 0xE05E); r8168_mac_ocp_write(tp, 0xF80E, 0xE065); r8168_mac_ocp_write(tp, 0xF810, 0xC602); r8168_mac_ocp_write(tp, 0xF812, 0xBE00); r8168_mac_ocp_write(tp, 0xF814, 0x0000); r8168_mac_ocp_write(tp, 0xF816, 0xC502); r8168_mac_ocp_write(tp, 0xF818, 0xBD00); r8168_mac_ocp_write(tp, 0xF81A, 0x074C); r8168_mac_ocp_write(tp, 0xF81C, 0xC302); r8168_mac_ocp_write(tp, 0xF81E, 0xBB00); r8168_mac_ocp_write(tp, 0xF820, 0x080A); r8168_mac_ocp_write(tp, 0xF822, 0x6420); r8168_mac_ocp_write(tp, 0xF824, 0x48C2); r8168_mac_ocp_write(tp, 0xF826, 0x8C20); r8168_mac_ocp_write(tp, 0xF828, 0xC516); r8168_mac_ocp_write(tp, 0xF82A, 0x64A4); r8168_mac_ocp_write(tp, 0xF82C, 0x49C0); r8168_mac_ocp_write(tp, 0xF82E, 0xF009); r8168_mac_ocp_write(tp, 0xF830, 0x74A2); r8168_mac_ocp_write(tp, 0xF832, 0x8CA5); r8168_mac_ocp_write(tp, 0xF834, 0x74A0); r8168_mac_ocp_write(tp, 0xF836, 0xC50E); r8168_mac_ocp_write(tp, 0xF838, 0x9CA2); r8168_mac_ocp_write(tp, 0xF83A, 0x1C11); r8168_mac_ocp_write(tp, 0xF83C, 0x9CA0); r8168_mac_ocp_write(tp, 0xF83E, 0xE006); r8168_mac_ocp_write(tp, 0xF840, 0x74F8); r8168_mac_ocp_write(tp, 0xF842, 0x48C4); r8168_mac_ocp_write(tp, 0xF844, 0x8CF8); r8168_mac_ocp_write(tp, 0xF846, 0xC404); r8168_mac_ocp_write(tp, 0xF848, 0xBC00); r8168_mac_ocp_write(tp, 0xF84A, 0xC403); r8168_mac_ocp_write(tp, 0xF84C, 0xBC00); r8168_mac_ocp_write(tp, 0xF84E, 0x0BF2); r8168_mac_ocp_write(tp, 0xF850, 0x0C0A); r8168_mac_ocp_write(tp, 0xF852, 0xE434); r8168_mac_ocp_write(tp, 0xF854, 0xD3C0); r8168_mac_ocp_write(tp, 0xF856, 0x49D9); r8168_mac_ocp_write(tp, 0xF858, 0xF01F); r8168_mac_ocp_write(tp, 0xF85A, 0xC526); r8168_mac_ocp_write(tp, 0xF85C, 0x64A5); r8168_mac_ocp_write(tp, 0xF85E, 0x1400); r8168_mac_ocp_write(tp, 0xF860, 0xF007); r8168_mac_ocp_write(tp, 0xF862, 0x0C01); r8168_mac_ocp_write(tp, 0xF864, 0x8CA5); r8168_mac_ocp_write(tp, 0xF866, 0x1C15); r8168_mac_ocp_write(tp, 0xF868, 0xC51B); r8168_mac_ocp_write(tp, 0xF86A, 0x9CA0); r8168_mac_ocp_write(tp, 0xF86C, 0xE013); r8168_mac_ocp_write(tp, 0xF86E, 0xC519); r8168_mac_ocp_write(tp, 0xF870, 0x74A0); r8168_mac_ocp_write(tp, 0xF872, 0x48C4); r8168_mac_ocp_write(tp, 0xF874, 0x8CA0); r8168_mac_ocp_write(tp, 0xF876, 0xC516); r8168_mac_ocp_write(tp, 0xF878, 0x74A4); r8168_mac_ocp_write(tp, 0xF87A, 0x48C8); r8168_mac_ocp_write(tp, 0xF87C, 0x48CA); r8168_mac_ocp_write(tp, 0xF87E, 0x9CA4); r8168_mac_ocp_write(tp, 0xF880, 0xC512); r8168_mac_ocp_write(tp, 0xF882, 0x1B00); r8168_mac_ocp_write(tp, 0xF884, 0x9BA0); r8168_mac_ocp_write(tp, 0xF886, 0x1B1C); r8168_mac_ocp_write(tp, 0xF888, 0x483F); r8168_mac_ocp_write(tp, 0xF88A, 0x9BA2); r8168_mac_ocp_write(tp, 0xF88C, 0x1B04); r8168_mac_ocp_write(tp, 0xF88E, 0xC508); r8168_mac_ocp_write(tp, 0xF890, 0x9BA0); r8168_mac_ocp_write(tp, 0xF892, 0xC505); r8168_mac_ocp_write(tp, 0xF894, 0xBD00); r8168_mac_ocp_write(tp, 0xF896, 0xC502); r8168_mac_ocp_write(tp, 0xF898, 0xBD00); r8168_mac_ocp_write(tp, 0xF89A, 0x0300); r8168_mac_ocp_write(tp, 0xF89C, 0x051E); r8168_mac_ocp_write(tp, 0xF89E, 0xE434); r8168_mac_ocp_write(tp, 0xF8A0, 0xE018); r8168_mac_ocp_write(tp, 0xF8A2, 0xE092); r8168_mac_ocp_write(tp, 0xF8A4, 0xDE20); r8168_mac_ocp_write(tp, 0xF8A6, 0xD3C0); r8168_mac_ocp_write(tp, 0xF8A8, 0xC50F); r8168_mac_ocp_write(tp, 0xF8AA, 0x76A4); r8168_mac_ocp_write(tp, 0xF8AC, 0x49E3); r8168_mac_ocp_write(tp, 0xF8AE, 0xF007); r8168_mac_ocp_write(tp, 0xF8B0, 0x49C0); r8168_mac_ocp_write(tp, 0xF8B2, 0xF103); r8168_mac_ocp_write(tp, 0xF8B4, 0xC607); r8168_mac_ocp_write(tp, 0xF8B6, 0xBE00); r8168_mac_ocp_write(tp, 0xF8B8, 0xC606); r8168_mac_ocp_write(tp, 0xF8BA, 0xBE00); r8168_mac_ocp_write(tp, 0xF8BC, 0xC602); r8168_mac_ocp_write(tp, 0xF8BE, 0xBE00); r8168_mac_ocp_write(tp, 0xF8C0, 0x0C4C); r8168_mac_ocp_write(tp, 0xF8C2, 0x0C28); r8168_mac_ocp_write(tp, 0xF8C4, 0x0C2C); r8168_mac_ocp_write(tp, 0xF8C6, 0xDC00); r8168_mac_ocp_write(tp, 0xF8C8, 0xC707); r8168_mac_ocp_write(tp, 0xF8CA, 0x1D00); r8168_mac_ocp_write(tp, 0xF8CC, 0x8DE2); r8168_mac_ocp_write(tp, 0xF8CE, 0x48C1); r8168_mac_ocp_write(tp, 0xF8D0, 0xC502); r8168_mac_ocp_write(tp, 0xF8D2, 0xBD00); r8168_mac_ocp_write(tp, 0xF8D4, 0x00AA); r8168_mac_ocp_write(tp, 0xF8D6, 0xE0C0); r8168_mac_ocp_write(tp, 0xF8D8, 0xC502); r8168_mac_ocp_write(tp, 0xF8DA, 0xBD00); r8168_mac_ocp_write(tp, 0xF8DC, 0x0132); r8168_mac_ocp_write(tp, 0xFC26, 0x8000); r8168_mac_ocp_write(tp, 0xFC2A, 0x0743); r8168_mac_ocp_write(tp, 0xFC2C, 0x0801); r8168_mac_ocp_write(tp, 0xFC2E, 0x0BE9); r8168_mac_ocp_write(tp, 0xFC30, 0x02FD); r8168_mac_ocp_write(tp, 0xFC32, 0x0C25); r8168_mac_ocp_write(tp, 0xFC34, 0x00A9); r8168_mac_ocp_write(tp, 0xFC36, 0x012D); } static void rtl_hw_start_8168h_1(struct rtl8169_private *tp) { static const struct ephy_info e_info_8168h_1[] = { { 0x1e, 0x0800, 0x0001 }, { 0x1d, 0x0000, 0x0800 }, { 0x05, 0xffff, 0x2089 }, { 0x06, 0xffff, 0x5881 }, { 0x04, 0xffff, 0x854a }, { 0x01, 0xffff, 0x068b } }; int rg_saw_cnt; rtl_ephy_init(tp, e_info_8168h_1); rtl_set_fifo_size(tp, 0x08, 0x10, 0x02, 0x06); rtl8168g_set_pause_thresholds(tp, 0x38, 0x48); rtl_set_def_aspm_entry_latency(tp); rtl_reset_packet_filter(tp); rtl_eri_set_bits(tp, 0xdc, 0x001c); rtl_eri_write(tp, 0x5f0, ERIAR_MASK_0011, 0x4f87); rtl_disable_rxdvgate(tp); rtl_eri_write(tp, 0xc0, ERIAR_MASK_0011, 0x0000); rtl_eri_write(tp, 0xb8, ERIAR_MASK_0011, 0x0000); rtl8168_config_eee_mac(tp); RTL_W8(tp, DLLPR, RTL_R8(tp, DLLPR) & ~PFM_EN); RTL_W8(tp, MISC_1, RTL_R8(tp, MISC_1) & ~PFM_D3COLD_EN); RTL_W8(tp, DLLPR, RTL_R8(tp, DLLPR) & ~TX_10M_PS_EN); rtl_eri_clear_bits(tp, 0x1b0, BIT(12)); rtl_pcie_state_l2l3_disable(tp); rg_saw_cnt = phy_read_paged(tp->phydev, 0x0c42, 0x13) & 0x3fff; if (rg_saw_cnt > 0) { u16 sw_cnt_1ms_ini; sw_cnt_1ms_ini = 16000000/rg_saw_cnt; sw_cnt_1ms_ini &= 0x0fff; r8168_mac_ocp_modify(tp, 0xd412, 0x0fff, sw_cnt_1ms_ini); } r8168_mac_ocp_modify(tp, 0xe056, 0x00f0, 0x0070); r8168_mac_ocp_modify(tp, 0xe052, 0x6000, 0x8008); r8168_mac_ocp_modify(tp, 0xe0d6, 0x01ff, 0x017f); r8168_mac_ocp_modify(tp, 0xd420, 0x0fff, 0x047f); r8168_mac_ocp_write(tp, 0xe63e, 0x0001); r8168_mac_ocp_write(tp, 0xe63e, 0x0000); r8168_mac_ocp_write(tp, 0xc094, 0x0000); r8168_mac_ocp_write(tp, 0xc09e, 0x0000); } static void rtl_hw_start_8168ep(struct rtl8169_private *tp) { rtl8168ep_stop_cmac(tp); rtl_set_fifo_size(tp, 0x08, 0x10, 0x02, 0x06); rtl8168g_set_pause_thresholds(tp, 0x2f, 0x5f); rtl_set_def_aspm_entry_latency(tp); rtl_reset_packet_filter(tp); rtl_eri_write(tp, 0x5f0, ERIAR_MASK_0011, 0x4f87); rtl_disable_rxdvgate(tp); rtl_eri_write(tp, 0xc0, ERIAR_MASK_0011, 0x0000); rtl_eri_write(tp, 0xb8, ERIAR_MASK_0011, 0x0000); rtl8168_config_eee_mac(tp); rtl_w0w1_eri(tp, 0x2fc, 0x01, 0x06); RTL_W8(tp, DLLPR, RTL_R8(tp, DLLPR) & ~TX_10M_PS_EN); rtl_pcie_state_l2l3_disable(tp); } static void rtl_hw_start_8168ep_3(struct rtl8169_private *tp) { static const struct ephy_info e_info_8168ep_3[] = { { 0x00, 0x0000, 0x0080 }, { 0x0d, 0x0100, 0x0200 }, { 0x19, 0x8021, 0x0000 }, { 0x1e, 0x0000, 0x2000 }, }; rtl_ephy_init(tp, e_info_8168ep_3); rtl_hw_start_8168ep(tp); RTL_W8(tp, DLLPR, RTL_R8(tp, DLLPR) & ~PFM_EN); RTL_W8(tp, MISC_1, RTL_R8(tp, MISC_1) & ~PFM_D3COLD_EN); r8168_mac_ocp_modify(tp, 0xd3e2, 0x0fff, 0x0271); r8168_mac_ocp_modify(tp, 0xd3e4, 0x00ff, 0x0000); r8168_mac_ocp_modify(tp, 0xe860, 0x0000, 0x0080); } static void rtl_hw_start_8117(struct rtl8169_private *tp) { static const struct ephy_info e_info_8117[] = { { 0x19, 0x0040, 0x1100 }, { 0x59, 0x0040, 0x1100 }, }; int rg_saw_cnt; rtl8168ep_stop_cmac(tp); rtl_ephy_init(tp, e_info_8117); rtl_set_fifo_size(tp, 0x08, 0x10, 0x02, 0x06); rtl8168g_set_pause_thresholds(tp, 0x2f, 0x5f); rtl_set_def_aspm_entry_latency(tp); rtl_reset_packet_filter(tp); rtl_eri_set_bits(tp, 0xd4, 0x0010); rtl_eri_write(tp, 0x5f0, ERIAR_MASK_0011, 0x4f87); rtl_disable_rxdvgate(tp); rtl_eri_write(tp, 0xc0, ERIAR_MASK_0011, 0x0000); rtl_eri_write(tp, 0xb8, ERIAR_MASK_0011, 0x0000); rtl8168_config_eee_mac(tp); RTL_W8(tp, DLLPR, RTL_R8(tp, DLLPR) & ~PFM_EN); RTL_W8(tp, MISC_1, RTL_R8(tp, MISC_1) & ~PFM_D3COLD_EN); RTL_W8(tp, DLLPR, RTL_R8(tp, DLLPR) & ~TX_10M_PS_EN); rtl_eri_clear_bits(tp, 0x1b0, BIT(12)); rtl_pcie_state_l2l3_disable(tp); rg_saw_cnt = phy_read_paged(tp->phydev, 0x0c42, 0x13) & 0x3fff; if (rg_saw_cnt > 0) { u16 sw_cnt_1ms_ini; sw_cnt_1ms_ini = (16000000 / rg_saw_cnt) & 0x0fff; r8168_mac_ocp_modify(tp, 0xd412, 0x0fff, sw_cnt_1ms_ini); } r8168_mac_ocp_modify(tp, 0xe056, 0x00f0, 0x0070); r8168_mac_ocp_write(tp, 0xea80, 0x0003); r8168_mac_ocp_modify(tp, 0xe052, 0x0000, 0x0009); r8168_mac_ocp_modify(tp, 0xd420, 0x0fff, 0x047f); r8168_mac_ocp_write(tp, 0xe63e, 0x0001); r8168_mac_ocp_write(tp, 0xe63e, 0x0000); r8168_mac_ocp_write(tp, 0xc094, 0x0000); r8168_mac_ocp_write(tp, 0xc09e, 0x0000); /* firmware is for MAC only */ r8169_apply_firmware(tp); } static void rtl_hw_start_8102e_1(struct rtl8169_private *tp) { static const struct ephy_info e_info_8102e_1[] = { { 0x01, 0, 0x6e65 }, { 0x02, 0, 0x091f }, { 0x03, 0, 0xc2f9 }, { 0x06, 0, 0xafb5 }, { 0x07, 0, 0x0e00 }, { 0x19, 0, 0xec80 }, { 0x01, 0, 0x2e65 }, { 0x01, 0, 0x6e65 } }; u8 cfg1; rtl_set_def_aspm_entry_latency(tp); RTL_W8(tp, DBG_REG, FIX_NAK_1); RTL_W8(tp, Config1, LEDS1 | LEDS0 | Speed_down | MEMMAP | IOMAP | VPD | PMEnable); RTL_W8(tp, Config3, RTL_R8(tp, Config3) & ~Beacon_en); cfg1 = RTL_R8(tp, Config1); if ((cfg1 & LEDS0) && (cfg1 & LEDS1)) RTL_W8(tp, Config1, cfg1 & ~LEDS0); rtl_ephy_init(tp, e_info_8102e_1); } static void rtl_hw_start_8102e_2(struct rtl8169_private *tp) { rtl_set_def_aspm_entry_latency(tp); RTL_W8(tp, Config1, MEMMAP | IOMAP | VPD | PMEnable); RTL_W8(tp, Config3, RTL_R8(tp, Config3) & ~Beacon_en); } static void rtl_hw_start_8102e_3(struct rtl8169_private *tp) { rtl_hw_start_8102e_2(tp); rtl_ephy_write(tp, 0x03, 0xc2f9); } static void rtl_hw_start_8401(struct rtl8169_private *tp) { static const struct ephy_info e_info_8401[] = { { 0x01, 0xffff, 0x6fe5 }, { 0x03, 0xffff, 0x0599 }, { 0x06, 0xffff, 0xaf25 }, { 0x07, 0xffff, 0x8e68 }, }; rtl_ephy_init(tp, e_info_8401); RTL_W8(tp, Config3, RTL_R8(tp, Config3) & ~Beacon_en); } static void rtl_hw_start_8105e_1(struct rtl8169_private *tp) { static const struct ephy_info e_info_8105e_1[] = { { 0x07, 0, 0x4000 }, { 0x19, 0, 0x0200 }, { 0x19, 0, 0x0020 }, { 0x1e, 0, 0x2000 }, { 0x03, 0, 0x0001 }, { 0x19, 0, 0x0100 }, { 0x19, 0, 0x0004 }, { 0x0a, 0, 0x0020 } }; /* Force LAN exit from ASPM if Rx/Tx are not idle */ RTL_W32(tp, FuncEvent, RTL_R32(tp, FuncEvent) | 0x002800); /* Disable Early Tally Counter */ RTL_W32(tp, FuncEvent, RTL_R32(tp, FuncEvent) & ~0x010000); RTL_W8(tp, MCU, RTL_R8(tp, MCU) | EN_NDP | EN_OOB_RESET); RTL_W8(tp, DLLPR, RTL_R8(tp, DLLPR) | PFM_EN); rtl_ephy_init(tp, e_info_8105e_1); rtl_pcie_state_l2l3_disable(tp); } static void rtl_hw_start_8105e_2(struct rtl8169_private *tp) { rtl_hw_start_8105e_1(tp); rtl_ephy_write(tp, 0x1e, rtl_ephy_read(tp, 0x1e) | 0x8000); } static void rtl_hw_start_8402(struct rtl8169_private *tp) { static const struct ephy_info e_info_8402[] = { { 0x19, 0xffff, 0xff64 }, { 0x1e, 0, 0x4000 } }; rtl_set_def_aspm_entry_latency(tp); /* Force LAN exit from ASPM if Rx/Tx are not idle */ RTL_W32(tp, FuncEvent, RTL_R32(tp, FuncEvent) | 0x002800); RTL_W8(tp, MCU, RTL_R8(tp, MCU) & ~NOW_IS_OOB); rtl_ephy_init(tp, e_info_8402); rtl_set_fifo_size(tp, 0x00, 0x00, 0x02, 0x06); rtl_reset_packet_filter(tp); rtl_eri_write(tp, 0xc0, ERIAR_MASK_0011, 0x0000); rtl_eri_write(tp, 0xb8, ERIAR_MASK_0011, 0x0000); rtl_w0w1_eri(tp, 0x0d4, 0x0e00, 0xff00); /* disable EEE */ rtl_eri_write(tp, 0x1b0, ERIAR_MASK_0011, 0x0000); rtl_pcie_state_l2l3_disable(tp); } static void rtl_hw_start_8106(struct rtl8169_private *tp) { /* Force LAN exit from ASPM if Rx/Tx are not idle */ RTL_W32(tp, FuncEvent, RTL_R32(tp, FuncEvent) | 0x002800); RTL_W32(tp, MISC, (RTL_R32(tp, MISC) | DISABLE_LAN_EN) & ~EARLY_TALLY_EN); RTL_W8(tp, MCU, RTL_R8(tp, MCU) | EN_NDP | EN_OOB_RESET); RTL_W8(tp, DLLPR, RTL_R8(tp, DLLPR) & ~PFM_EN); /* L0 7us, L1 32us - needed to avoid issues with link-up detection */ rtl_set_aspm_entry_latency(tp, 0x2f); rtl_eri_write(tp, 0x1d0, ERIAR_MASK_0011, 0x0000); /* disable EEE */ rtl_eri_write(tp, 0x1b0, ERIAR_MASK_0011, 0x0000); rtl_pcie_state_l2l3_disable(tp); } DECLARE_RTL_COND(rtl_mac_ocp_e00e_cond) { return r8168_mac_ocp_read(tp, 0xe00e) & BIT(13); } static void rtl_hw_start_8125_common(struct rtl8169_private *tp) { rtl_pcie_state_l2l3_disable(tp); RTL_W16(tp, 0x382, 0x221b); RTL_W8(tp, 0x4500, 0); RTL_W16(tp, 0x4800, 0); /* disable UPS */ r8168_mac_ocp_modify(tp, 0xd40a, 0x0010, 0x0000); RTL_W8(tp, Config1, RTL_R8(tp, Config1) & ~0x10); r8168_mac_ocp_write(tp, 0xc140, 0xffff); r8168_mac_ocp_write(tp, 0xc142, 0xffff); r8168_mac_ocp_modify(tp, 0xd3e2, 0x0fff, 0x03a9); r8168_mac_ocp_modify(tp, 0xd3e4, 0x00ff, 0x0000); r8168_mac_ocp_modify(tp, 0xe860, 0x0000, 0x0080); /* disable new tx descriptor format */ r8168_mac_ocp_modify(tp, 0xeb58, 0x0001, 0x0000); if (tp->mac_version == RTL_GIGA_MAC_VER_63) r8168_mac_ocp_modify(tp, 0xe614, 0x0700, 0x0200); else r8168_mac_ocp_modify(tp, 0xe614, 0x0700, 0x0400); if (tp->mac_version == RTL_GIGA_MAC_VER_63) r8168_mac_ocp_modify(tp, 0xe63e, 0x0c30, 0x0000); else r8168_mac_ocp_modify(tp, 0xe63e, 0x0c30, 0x0020); r8168_mac_ocp_modify(tp, 0xc0b4, 0x0000, 0x000c); r8168_mac_ocp_modify(tp, 0xeb6a, 0x00ff, 0x0033); r8168_mac_ocp_modify(tp, 0xeb50, 0x03e0, 0x0040); r8168_mac_ocp_modify(tp, 0xe056, 0x00f0, 0x0030); r8168_mac_ocp_modify(tp, 0xe040, 0x1000, 0x0000); r8168_mac_ocp_modify(tp, 0xea1c, 0x0003, 0x0001); r8168_mac_ocp_modify(tp, 0xe0c0, 0x4f0f, 0x4403); r8168_mac_ocp_modify(tp, 0xe052, 0x0080, 0x0068); r8168_mac_ocp_modify(tp, 0xd430, 0x0fff, 0x047f); r8168_mac_ocp_modify(tp, 0xea1c, 0x0004, 0x0000); r8168_mac_ocp_modify(tp, 0xeb54, 0x0000, 0x0001); udelay(1); r8168_mac_ocp_modify(tp, 0xeb54, 0x0001, 0x0000); RTL_W16(tp, 0x1880, RTL_R16(tp, 0x1880) & ~0x0030); r8168_mac_ocp_write(tp, 0xe098, 0xc302); rtl_loop_wait_low(tp, &rtl_mac_ocp_e00e_cond, 1000, 10); if (tp->mac_version == RTL_GIGA_MAC_VER_63) rtl8125b_config_eee_mac(tp); else rtl8125a_config_eee_mac(tp); rtl_disable_rxdvgate(tp); } static void rtl_hw_start_8125a_2(struct rtl8169_private *tp) { static const struct ephy_info e_info_8125a_2[] = { { 0x04, 0xffff, 0xd000 }, { 0x0a, 0xffff, 0x8653 }, { 0x23, 0xffff, 0xab66 }, { 0x20, 0xffff, 0x9455 }, { 0x21, 0xffff, 0x99ff }, { 0x29, 0xffff, 0xfe04 }, { 0x44, 0xffff, 0xd000 }, { 0x4a, 0xffff, 0x8653 }, { 0x63, 0xffff, 0xab66 }, { 0x60, 0xffff, 0x9455 }, { 0x61, 0xffff, 0x99ff }, { 0x69, 0xffff, 0xfe04 }, }; rtl_set_def_aspm_entry_latency(tp); rtl_ephy_init(tp, e_info_8125a_2); rtl_hw_start_8125_common(tp); } static void rtl_hw_start_8125b(struct rtl8169_private *tp) { static const struct ephy_info e_info_8125b[] = { { 0x0b, 0xffff, 0xa908 }, { 0x1e, 0xffff, 0x20eb }, { 0x4b, 0xffff, 0xa908 }, { 0x5e, 0xffff, 0x20eb }, { 0x22, 0x0030, 0x0020 }, { 0x62, 0x0030, 0x0020 }, }; rtl_set_def_aspm_entry_latency(tp); rtl_ephy_init(tp, e_info_8125b); rtl_hw_start_8125_common(tp); } static void rtl_hw_config(struct rtl8169_private *tp) { static const rtl_generic_fct hw_configs[] = { [RTL_GIGA_MAC_VER_07] = rtl_hw_start_8102e_1, [RTL_GIGA_MAC_VER_08] = rtl_hw_start_8102e_3, [RTL_GIGA_MAC_VER_09] = rtl_hw_start_8102e_2, [RTL_GIGA_MAC_VER_10] = NULL, [RTL_GIGA_MAC_VER_11] = rtl_hw_start_8168b, [RTL_GIGA_MAC_VER_14] = rtl_hw_start_8401, [RTL_GIGA_MAC_VER_17] = rtl_hw_start_8168b, [RTL_GIGA_MAC_VER_18] = rtl_hw_start_8168cp_1, [RTL_GIGA_MAC_VER_19] = rtl_hw_start_8168c_1, [RTL_GIGA_MAC_VER_20] = rtl_hw_start_8168c_2, [RTL_GIGA_MAC_VER_21] = rtl_hw_start_8168c_2, [RTL_GIGA_MAC_VER_22] = rtl_hw_start_8168c_4, [RTL_GIGA_MAC_VER_23] = rtl_hw_start_8168cp_2, [RTL_GIGA_MAC_VER_24] = rtl_hw_start_8168cp_3, [RTL_GIGA_MAC_VER_25] = rtl_hw_start_8168d, [RTL_GIGA_MAC_VER_26] = rtl_hw_start_8168d, [RTL_GIGA_MAC_VER_28] = rtl_hw_start_8168d_4, [RTL_GIGA_MAC_VER_29] = rtl_hw_start_8105e_1, [RTL_GIGA_MAC_VER_30] = rtl_hw_start_8105e_2, [RTL_GIGA_MAC_VER_31] = rtl_hw_start_8168d, [RTL_GIGA_MAC_VER_32] = rtl_hw_start_8168e_1, [RTL_GIGA_MAC_VER_33] = rtl_hw_start_8168e_1, [RTL_GIGA_MAC_VER_34] = rtl_hw_start_8168e_2, [RTL_GIGA_MAC_VER_35] = rtl_hw_start_8168f_1, [RTL_GIGA_MAC_VER_36] = rtl_hw_start_8168f_1, [RTL_GIGA_MAC_VER_37] = rtl_hw_start_8402, [RTL_GIGA_MAC_VER_38] = rtl_hw_start_8411, [RTL_GIGA_MAC_VER_39] = rtl_hw_start_8106, [RTL_GIGA_MAC_VER_40] = rtl_hw_start_8168g_1, [RTL_GIGA_MAC_VER_42] = rtl_hw_start_8168g_2, [RTL_GIGA_MAC_VER_43] = rtl_hw_start_8168g_2, [RTL_GIGA_MAC_VER_44] = rtl_hw_start_8411_2, [RTL_GIGA_MAC_VER_46] = rtl_hw_start_8168h_1, [RTL_GIGA_MAC_VER_48] = rtl_hw_start_8168h_1, [RTL_GIGA_MAC_VER_51] = rtl_hw_start_8168ep_3, [RTL_GIGA_MAC_VER_52] = rtl_hw_start_8117, [RTL_GIGA_MAC_VER_53] = rtl_hw_start_8117, [RTL_GIGA_MAC_VER_61] = rtl_hw_start_8125a_2, [RTL_GIGA_MAC_VER_63] = rtl_hw_start_8125b, }; if (hw_configs[tp->mac_version]) hw_configs[tp->mac_version](tp); } static void rtl_hw_start_8125(struct rtl8169_private *tp) { int i; /* disable interrupt coalescing */ for (i = 0xa00; i < 0xb00; i += 4) RTL_W32(tp, i, 0); rtl_hw_config(tp); } static void rtl_hw_start_8168(struct rtl8169_private *tp) { if (rtl_is_8168evl_up(tp)) RTL_W8(tp, MaxTxPacketSize, EarlySize); else RTL_W8(tp, MaxTxPacketSize, TxPacketMax); rtl_hw_config(tp); /* disable interrupt coalescing */ RTL_W16(tp, IntrMitigate, 0x0000); } static void rtl_hw_start_8169(struct rtl8169_private *tp) { RTL_W8(tp, EarlyTxThres, NoEarlyTx); tp->cp_cmd |= PCIMulRW; if (tp->mac_version == RTL_GIGA_MAC_VER_02 || tp->mac_version == RTL_GIGA_MAC_VER_03) tp->cp_cmd |= EnAnaPLL; RTL_W16(tp, CPlusCmd, tp->cp_cmd); rtl8169_set_magic_reg(tp); /* disable interrupt coalescing */ RTL_W16(tp, IntrMitigate, 0x0000); } static void rtl_hw_start(struct rtl8169_private *tp) { rtl_unlock_config_regs(tp); /* disable aspm and clock request before ephy access */ rtl_hw_aspm_clkreq_enable(tp, false); RTL_W16(tp, CPlusCmd, tp->cp_cmd); if (tp->mac_version <= RTL_GIGA_MAC_VER_06) rtl_hw_start_8169(tp); else if (rtl_is_8125(tp)) rtl_hw_start_8125(tp); else rtl_hw_start_8168(tp); rtl_enable_exit_l1(tp); rtl_hw_aspm_clkreq_enable(tp, true); rtl_set_rx_max_size(tp); rtl_set_rx_tx_desc_registers(tp); rtl_lock_config_regs(tp); rtl_jumbo_config(tp); /* Initially a 10 us delay. Turned it into a PCI commit. - FR */ rtl_pci_commit(tp); RTL_W8(tp, ChipCmd, CmdTxEnb | CmdRxEnb); rtl_init_rxcfg(tp); rtl_set_tx_config_registers(tp); rtl_set_rx_config_features(tp, tp->dev->features); rtl_set_rx_mode(tp->dev); rtl_irq_enable(tp); } static int rtl8169_change_mtu(struct net_device *dev, int new_mtu) { struct rtl8169_private *tp = netdev_priv(dev); dev->mtu = new_mtu; netdev_update_features(dev); rtl_jumbo_config(tp); switch (tp->mac_version) { case RTL_GIGA_MAC_VER_61: case RTL_GIGA_MAC_VER_63: rtl8125_set_eee_txidle_timer(tp); break; default: break; } return 0; } static void rtl8169_mark_to_asic(struct RxDesc *desc) { u32 eor = le32_to_cpu(desc->opts1) & RingEnd; desc->opts2 = 0; /* Force memory writes to complete before releasing descriptor */ dma_wmb(); WRITE_ONCE(desc->opts1, cpu_to_le32(DescOwn | eor | R8169_RX_BUF_SIZE)); } static struct page *rtl8169_alloc_rx_data(struct rtl8169_private *tp, struct RxDesc *desc) { struct device *d = tp_to_dev(tp); int node = dev_to_node(d); dma_addr_t mapping; struct page *data; data = alloc_pages_node(node, GFP_KERNEL, get_order(R8169_RX_BUF_SIZE)); if (!data) return NULL; mapping = dma_map_page(d, data, 0, R8169_RX_BUF_SIZE, DMA_FROM_DEVICE); if (unlikely(dma_mapping_error(d, mapping))) { netdev_err(tp->dev, "Failed to map RX DMA!\n"); __free_pages(data, get_order(R8169_RX_BUF_SIZE)); return NULL; } desc->addr = cpu_to_le64(mapping); rtl8169_mark_to_asic(desc); return data; } static void rtl8169_rx_clear(struct rtl8169_private *tp) { int i; for (i = 0; i < NUM_RX_DESC && tp->Rx_databuff[i]; i++) { dma_unmap_page(tp_to_dev(tp), le64_to_cpu(tp->RxDescArray[i].addr), R8169_RX_BUF_SIZE, DMA_FROM_DEVICE); __free_pages(tp->Rx_databuff[i], get_order(R8169_RX_BUF_SIZE)); tp->Rx_databuff[i] = NULL; tp->RxDescArray[i].addr = 0; tp->RxDescArray[i].opts1 = 0; } } static int rtl8169_rx_fill(struct rtl8169_private *tp) { int i; for (i = 0; i < NUM_RX_DESC; i++) { struct page *data; data = rtl8169_alloc_rx_data(tp, tp->RxDescArray + i); if (!data) { rtl8169_rx_clear(tp); return -ENOMEM; } tp->Rx_databuff[i] = data; } /* mark as last descriptor in the ring */ tp->RxDescArray[NUM_RX_DESC - 1].opts1 |= cpu_to_le32(RingEnd); return 0; } static int rtl8169_init_ring(struct rtl8169_private *tp) { rtl8169_init_ring_indexes(tp); memset(tp->tx_skb, 0, sizeof(tp->tx_skb)); memset(tp->Rx_databuff, 0, sizeof(tp->Rx_databuff)); return rtl8169_rx_fill(tp); } static void rtl8169_unmap_tx_skb(struct rtl8169_private *tp, unsigned int entry) { struct ring_info *tx_skb = tp->tx_skb + entry; struct TxDesc *desc = tp->TxDescArray + entry; dma_unmap_single(tp_to_dev(tp), le64_to_cpu(desc->addr), tx_skb->len, DMA_TO_DEVICE); memset(desc, 0, sizeof(*desc)); memset(tx_skb, 0, sizeof(*tx_skb)); } static void rtl8169_tx_clear_range(struct rtl8169_private *tp, u32 start, unsigned int n) { unsigned int i; for (i = 0; i < n; i++) { unsigned int entry = (start + i) % NUM_TX_DESC; struct ring_info *tx_skb = tp->tx_skb + entry; unsigned int len = tx_skb->len; if (len) { struct sk_buff *skb = tx_skb->skb; rtl8169_unmap_tx_skb(tp, entry); if (skb) dev_consume_skb_any(skb); } } } static void rtl8169_tx_clear(struct rtl8169_private *tp) { rtl8169_tx_clear_range(tp, tp->dirty_tx, NUM_TX_DESC); netdev_reset_queue(tp->dev); } static void rtl8169_cleanup(struct rtl8169_private *tp) { napi_disable(&tp->napi); /* Give a racing hard_start_xmit a few cycles to complete. */ synchronize_net(); /* Disable interrupts */ rtl8169_irq_mask_and_ack(tp); rtl_rx_close(tp); switch (tp->mac_version) { case RTL_GIGA_MAC_VER_28: case RTL_GIGA_MAC_VER_31: rtl_loop_wait_low(tp, &rtl_npq_cond, 20, 2000); break; case RTL_GIGA_MAC_VER_34 ... RTL_GIGA_MAC_VER_38: RTL_W8(tp, ChipCmd, RTL_R8(tp, ChipCmd) | StopReq); rtl_loop_wait_high(tp, &rtl_txcfg_empty_cond, 100, 666); break; case RTL_GIGA_MAC_VER_40 ... RTL_GIGA_MAC_VER_63: rtl_enable_rxdvgate(tp); fsleep(2000); break; default: RTL_W8(tp, ChipCmd, RTL_R8(tp, ChipCmd) | StopReq); fsleep(100); break; } rtl_hw_reset(tp); rtl8169_tx_clear(tp); rtl8169_init_ring_indexes(tp); } static void rtl_reset_work(struct rtl8169_private *tp) { int i; netif_stop_queue(tp->dev); rtl8169_cleanup(tp); for (i = 0; i < NUM_RX_DESC; i++) rtl8169_mark_to_asic(tp->RxDescArray + i); napi_enable(&tp->napi); rtl_hw_start(tp); } static void rtl8169_tx_timeout(struct net_device *dev, unsigned int txqueue) { struct rtl8169_private *tp = netdev_priv(dev); rtl_schedule_task(tp, RTL_FLAG_TASK_TX_TIMEOUT); } static int rtl8169_tx_map(struct rtl8169_private *tp, const u32 *opts, u32 len, void *addr, unsigned int entry, bool desc_own) { struct TxDesc *txd = tp->TxDescArray + entry; struct device *d = tp_to_dev(tp); dma_addr_t mapping; u32 opts1; int ret; mapping = dma_map_single(d, addr, len, DMA_TO_DEVICE); ret = dma_mapping_error(d, mapping); if (unlikely(ret)) { if (net_ratelimit()) netdev_err(tp->dev, "Failed to map TX data!\n"); return ret; } txd->addr = cpu_to_le64(mapping); txd->opts2 = cpu_to_le32(opts[1]); opts1 = opts[0] | len; if (entry == NUM_TX_DESC - 1) opts1 |= RingEnd; if (desc_own) opts1 |= DescOwn; txd->opts1 = cpu_to_le32(opts1); tp->tx_skb[entry].len = len; return 0; } static int rtl8169_xmit_frags(struct rtl8169_private *tp, struct sk_buff *skb, const u32 *opts, unsigned int entry) { struct skb_shared_info *info = skb_shinfo(skb); unsigned int cur_frag; for (cur_frag = 0; cur_frag < info->nr_frags; cur_frag++) { const skb_frag_t *frag = info->frags + cur_frag; void *addr = skb_frag_address(frag); u32 len = skb_frag_size(frag); entry = (entry + 1) % NUM_TX_DESC; if (unlikely(rtl8169_tx_map(tp, opts, len, addr, entry, true))) goto err_out; } return 0; err_out: rtl8169_tx_clear_range(tp, tp->cur_tx + 1, cur_frag); return -EIO; } static bool rtl_skb_is_udp(struct sk_buff *skb) { int no = skb_network_offset(skb); struct ipv6hdr *i6h, _i6h; struct iphdr *ih, _ih; switch (vlan_get_protocol(skb)) { case htons(ETH_P_IP): ih = skb_header_pointer(skb, no, sizeof(_ih), &_ih); return ih && ih->protocol == IPPROTO_UDP; case htons(ETH_P_IPV6): i6h = skb_header_pointer(skb, no, sizeof(_i6h), &_i6h); return i6h && i6h->nexthdr == IPPROTO_UDP; default: return false; } } #define RTL_MIN_PATCH_LEN 47 /* see rtl8125_get_patch_pad_len() in r8125 vendor driver */ static unsigned int rtl8125_quirk_udp_padto(struct rtl8169_private *tp, struct sk_buff *skb) { unsigned int padto = 0, len = skb->len; if (rtl_is_8125(tp) && len < 128 + RTL_MIN_PATCH_LEN && rtl_skb_is_udp(skb) && skb_transport_header_was_set(skb)) { unsigned int trans_data_len = skb_tail_pointer(skb) - skb_transport_header(skb); if (trans_data_len >= offsetof(struct udphdr, len) && trans_data_len < RTL_MIN_PATCH_LEN) { u16 dest = ntohs(udp_hdr(skb)->dest); /* dest is a standard PTP port */ if (dest == 319 || dest == 320) padto = len + RTL_MIN_PATCH_LEN - trans_data_len; } if (trans_data_len < sizeof(struct udphdr)) padto = max_t(unsigned int, padto, len + sizeof(struct udphdr) - trans_data_len); } return padto; } static unsigned int rtl_quirk_packet_padto(struct rtl8169_private *tp, struct sk_buff *skb) { unsigned int padto; padto = rtl8125_quirk_udp_padto(tp, skb); switch (tp->mac_version) { case RTL_GIGA_MAC_VER_34: case RTL_GIGA_MAC_VER_61: case RTL_GIGA_MAC_VER_63: padto = max_t(unsigned int, padto, ETH_ZLEN); break; default: break; } return padto; } static void rtl8169_tso_csum_v1(struct sk_buff *skb, u32 *opts) { u32 mss = skb_shinfo(skb)->gso_size; if (mss) { opts[0] |= TD_LSO; opts[0] |= mss << TD0_MSS_SHIFT; } else if (skb->ip_summed == CHECKSUM_PARTIAL) { const struct iphdr *ip = ip_hdr(skb); if (ip->protocol == IPPROTO_TCP) opts[0] |= TD0_IP_CS | TD0_TCP_CS; else if (ip->protocol == IPPROTO_UDP) opts[0] |= TD0_IP_CS | TD0_UDP_CS; else WARN_ON_ONCE(1); } } static bool rtl8169_tso_csum_v2(struct rtl8169_private *tp, struct sk_buff *skb, u32 *opts) { struct skb_shared_info *shinfo = skb_shinfo(skb); u32 mss = shinfo->gso_size; if (mss) { if (shinfo->gso_type & SKB_GSO_TCPV4) { opts[0] |= TD1_GTSENV4; } else if (shinfo->gso_type & SKB_GSO_TCPV6) { if (skb_cow_head(skb, 0)) return false; tcp_v6_gso_csum_prep(skb); opts[0] |= TD1_GTSENV6; } else { WARN_ON_ONCE(1); } opts[0] |= skb_transport_offset(skb) << GTTCPHO_SHIFT; opts[1] |= mss << TD1_MSS_SHIFT; } else if (skb->ip_summed == CHECKSUM_PARTIAL) { u8 ip_protocol; switch (vlan_get_protocol(skb)) { case htons(ETH_P_IP): opts[1] |= TD1_IPv4_CS; ip_protocol = ip_hdr(skb)->protocol; break; case htons(ETH_P_IPV6): opts[1] |= TD1_IPv6_CS; ip_protocol = ipv6_hdr(skb)->nexthdr; break; default: ip_protocol = IPPROTO_RAW; break; } if (ip_protocol == IPPROTO_TCP) opts[1] |= TD1_TCP_CS; else if (ip_protocol == IPPROTO_UDP) opts[1] |= TD1_UDP_CS; else WARN_ON_ONCE(1); opts[1] |= skb_transport_offset(skb) << TCPHO_SHIFT; } else { unsigned int padto = rtl_quirk_packet_padto(tp, skb); /* skb_padto would free the skb on error */ return !__skb_put_padto(skb, padto, false); } return true; } static unsigned int rtl_tx_slots_avail(struct rtl8169_private *tp) { return READ_ONCE(tp->dirty_tx) + NUM_TX_DESC - READ_ONCE(tp->cur_tx); } /* Versions RTL8102e and from RTL8168c onwards support csum_v2 */ static bool rtl_chip_supports_csum_v2(struct rtl8169_private *tp) { switch (tp->mac_version) { case RTL_GIGA_MAC_VER_02 ... RTL_GIGA_MAC_VER_06: case RTL_GIGA_MAC_VER_10 ... RTL_GIGA_MAC_VER_17: return false; default: return true; } } static void rtl8169_doorbell(struct rtl8169_private *tp) { if (rtl_is_8125(tp)) RTL_W16(tp, TxPoll_8125, BIT(0)); else RTL_W8(tp, TxPoll, NPQ); } static netdev_tx_t rtl8169_start_xmit(struct sk_buff *skb, struct net_device *dev) { unsigned int frags = skb_shinfo(skb)->nr_frags; struct rtl8169_private *tp = netdev_priv(dev); unsigned int entry = tp->cur_tx % NUM_TX_DESC; struct TxDesc *txd_first, *txd_last; bool stop_queue, door_bell; u32 opts[2]; if (unlikely(!rtl_tx_slots_avail(tp))) { if (net_ratelimit()) netdev_err(dev, "BUG! Tx Ring full when queue awake!\n"); goto err_stop_0; } opts[1] = rtl8169_tx_vlan_tag(skb); opts[0] = 0; if (!rtl_chip_supports_csum_v2(tp)) rtl8169_tso_csum_v1(skb, opts); else if (!rtl8169_tso_csum_v2(tp, skb, opts)) goto err_dma_0; if (unlikely(rtl8169_tx_map(tp, opts, skb_headlen(skb), skb->data, entry, false))) goto err_dma_0; txd_first = tp->TxDescArray + entry; if (frags) { if (rtl8169_xmit_frags(tp, skb, opts, entry)) goto err_dma_1; entry = (entry + frags) % NUM_TX_DESC; } txd_last = tp->TxDescArray + entry; txd_last->opts1 |= cpu_to_le32(LastFrag); tp->tx_skb[entry].skb = skb; skb_tx_timestamp(skb); /* Force memory writes to complete before releasing descriptor */ dma_wmb(); door_bell = __netdev_sent_queue(dev, skb->len, netdev_xmit_more()); txd_first->opts1 |= cpu_to_le32(DescOwn | FirstFrag); /* rtl_tx needs to see descriptor changes before updated tp->cur_tx */ smp_wmb(); WRITE_ONCE(tp->cur_tx, tp->cur_tx + frags + 1); stop_queue = !netif_subqueue_maybe_stop(dev, 0, rtl_tx_slots_avail(tp), R8169_TX_STOP_THRS, R8169_TX_START_THRS); if (door_bell || stop_queue) rtl8169_doorbell(tp); return NETDEV_TX_OK; err_dma_1: rtl8169_unmap_tx_skb(tp, entry); err_dma_0: dev_kfree_skb_any(skb); dev->stats.tx_dropped++; return NETDEV_TX_OK; err_stop_0: netif_stop_queue(dev); dev->stats.tx_dropped++; return NETDEV_TX_BUSY; } static unsigned int rtl_last_frag_len(struct sk_buff *skb) { struct skb_shared_info *info = skb_shinfo(skb); unsigned int nr_frags = info->nr_frags; if (!nr_frags) return UINT_MAX; return skb_frag_size(info->frags + nr_frags - 1); } /* Workaround for hw issues with TSO on RTL8168evl */ static netdev_features_t rtl8168evl_fix_tso(struct sk_buff *skb, netdev_features_t features) { /* IPv4 header has options field */ if (vlan_get_protocol(skb) == htons(ETH_P_IP) && ip_hdrlen(skb) > sizeof(struct iphdr)) features &= ~NETIF_F_ALL_TSO; /* IPv4 TCP header has options field */ else if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4 && tcp_hdrlen(skb) > sizeof(struct tcphdr)) features &= ~NETIF_F_ALL_TSO; else if (rtl_last_frag_len(skb) <= 6) features &= ~NETIF_F_ALL_TSO; return features; } static netdev_features_t rtl8169_features_check(struct sk_buff *skb, struct net_device *dev, netdev_features_t features) { struct rtl8169_private *tp = netdev_priv(dev); if (skb_is_gso(skb)) { if (tp->mac_version == RTL_GIGA_MAC_VER_34) features = rtl8168evl_fix_tso(skb, features); if (skb_transport_offset(skb) > GTTCPHO_MAX && rtl_chip_supports_csum_v2(tp)) features &= ~NETIF_F_ALL_TSO; } else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* work around hw bug on some chip versions */ if (skb->len < ETH_ZLEN) features &= ~NETIF_F_CSUM_MASK; if (rtl_quirk_packet_padto(tp, skb)) features &= ~NETIF_F_CSUM_MASK; if (skb_transport_offset(skb) > TCPHO_MAX && rtl_chip_supports_csum_v2(tp)) features &= ~NETIF_F_CSUM_MASK; } return vlan_features_check(skb, features); } static void rtl8169_pcierr_interrupt(struct net_device *dev) { struct rtl8169_private *tp = netdev_priv(dev); struct pci_dev *pdev = tp->pci_dev; int pci_status_errs; u16 pci_cmd; pci_read_config_word(pdev, PCI_COMMAND, &pci_cmd); pci_status_errs = pci_status_get_and_clear_errors(pdev); if (net_ratelimit()) netdev_err(dev, "PCI error (cmd = 0x%04x, status_errs = 0x%04x)\n", pci_cmd, pci_status_errs); rtl_schedule_task(tp, RTL_FLAG_TASK_RESET_PENDING); } static void rtl_tx(struct net_device *dev, struct rtl8169_private *tp, int budget) { unsigned int dirty_tx, bytes_compl = 0, pkts_compl = 0; struct sk_buff *skb; dirty_tx = tp->dirty_tx; while (READ_ONCE(tp->cur_tx) != dirty_tx) { unsigned int entry = dirty_tx % NUM_TX_DESC; u32 status; status = le32_to_cpu(tp->TxDescArray[entry].opts1); if (status & DescOwn) break; skb = tp->tx_skb[entry].skb; rtl8169_unmap_tx_skb(tp, entry); if (skb) { pkts_compl++; bytes_compl += skb->len; napi_consume_skb(skb, budget); } dirty_tx++; } if (tp->dirty_tx != dirty_tx) { dev_sw_netstats_tx_add(dev, pkts_compl, bytes_compl); WRITE_ONCE(tp->dirty_tx, dirty_tx); netif_subqueue_completed_wake(dev, 0, pkts_compl, bytes_compl, rtl_tx_slots_avail(tp), R8169_TX_START_THRS); /* * 8168 hack: TxPoll requests are lost when the Tx packets are * too close. Let's kick an extra TxPoll request when a burst * of start_xmit activity is detected (if it is not detected, * it is slow enough). -- FR * If skb is NULL then we come here again once a tx irq is * triggered after the last fragment is marked transmitted. */ if (tp->cur_tx != dirty_tx && skb) rtl8169_doorbell(tp); } } static inline int rtl8169_fragmented_frame(u32 status) { return (status & (FirstFrag | LastFrag)) != (FirstFrag | LastFrag); } static inline void rtl8169_rx_csum(struct sk_buff *skb, u32 opts1) { u32 status = opts1 & (RxProtoMask | RxCSFailMask); if (status == RxProtoTCP || status == RxProtoUDP) skb->ip_summed = CHECKSUM_UNNECESSARY; else skb_checksum_none_assert(skb); } static int rtl_rx(struct net_device *dev, struct rtl8169_private *tp, int budget) { struct device *d = tp_to_dev(tp); int count; for (count = 0; count < budget; count++, tp->cur_rx++) { unsigned int pkt_size, entry = tp->cur_rx % NUM_RX_DESC; struct RxDesc *desc = tp->RxDescArray + entry; struct sk_buff *skb; const void *rx_buf; dma_addr_t addr; u32 status; status = le32_to_cpu(desc->opts1); if (status & DescOwn) break; /* This barrier is needed to keep us from reading * any other fields out of the Rx descriptor until * we know the status of DescOwn */ dma_rmb(); if (unlikely(status & RxRES)) { if (net_ratelimit()) netdev_warn(dev, "Rx ERROR. status = %08x\n", status); dev->stats.rx_errors++; if (status & (RxRWT | RxRUNT)) dev->stats.rx_length_errors++; if (status & RxCRC) dev->stats.rx_crc_errors++; if (!(dev->features & NETIF_F_RXALL)) goto release_descriptor; else if (status & RxRWT || !(status & (RxRUNT | RxCRC))) goto release_descriptor; } pkt_size = status & GENMASK(13, 0); if (likely(!(dev->features & NETIF_F_RXFCS))) pkt_size -= ETH_FCS_LEN; /* The driver does not support incoming fragmented frames. * They are seen as a symptom of over-mtu sized frames. */ if (unlikely(rtl8169_fragmented_frame(status))) { dev->stats.rx_dropped++; dev->stats.rx_length_errors++; goto release_descriptor; } skb = napi_alloc_skb(&tp->napi, pkt_size); if (unlikely(!skb)) { dev->stats.rx_dropped++; goto release_descriptor; } addr = le64_to_cpu(desc->addr); rx_buf = page_address(tp->Rx_databuff[entry]); dma_sync_single_for_cpu(d, addr, pkt_size, DMA_FROM_DEVICE); prefetch(rx_buf); skb_copy_to_linear_data(skb, rx_buf, pkt_size); skb->tail += pkt_size; skb->len = pkt_size; dma_sync_single_for_device(d, addr, pkt_size, DMA_FROM_DEVICE); rtl8169_rx_csum(skb, status); skb->protocol = eth_type_trans(skb, dev); rtl8169_rx_vlan_tag(desc, skb); if (skb->pkt_type == PACKET_MULTICAST) dev->stats.multicast++; napi_gro_receive(&tp->napi, skb); dev_sw_netstats_rx_add(dev, pkt_size); release_descriptor: rtl8169_mark_to_asic(desc); } return count; } static irqreturn_t rtl8169_interrupt(int irq, void *dev_instance) { struct rtl8169_private *tp = dev_instance; u32 status = rtl_get_events(tp); if ((status & 0xffff) == 0xffff || !(status & tp->irq_mask)) return IRQ_NONE; if (unlikely(status & SYSErr)) { rtl8169_pcierr_interrupt(tp->dev); goto out; } if (status & LinkChg) phy_mac_interrupt(tp->phydev); if (unlikely(status & RxFIFOOver && tp->mac_version == RTL_GIGA_MAC_VER_11)) { netif_stop_queue(tp->dev); rtl_schedule_task(tp, RTL_FLAG_TASK_RESET_PENDING); } if (napi_schedule_prep(&tp->napi)) { rtl_irq_disable(tp); __napi_schedule(&tp->napi); } out: rtl_ack_events(tp, status); return IRQ_HANDLED; } static void rtl_task(struct work_struct *work) { struct rtl8169_private *tp = container_of(work, struct rtl8169_private, wk.work); int ret; rtnl_lock(); if (!netif_running(tp->dev) || !test_bit(RTL_FLAG_TASK_ENABLED, tp->wk.flags)) goto out_unlock; if (test_and_clear_bit(RTL_FLAG_TASK_TX_TIMEOUT, tp->wk.flags)) { /* if chip isn't accessible, reset bus to revive it */ if (RTL_R32(tp, TxConfig) == ~0) { ret = pci_reset_bus(tp->pci_dev); if (ret < 0) { netdev_err(tp->dev, "Can't reset secondary PCI bus, detach NIC\n"); netif_device_detach(tp->dev); goto out_unlock; } } /* ASPM compatibility issues are a typical reason for tx timeouts */ ret = pci_disable_link_state(tp->pci_dev, PCIE_LINK_STATE_L1 | PCIE_LINK_STATE_L0S); if (!ret) netdev_warn_once(tp->dev, "ASPM disabled on Tx timeout\n"); goto reset; } if (test_and_clear_bit(RTL_FLAG_TASK_RESET_PENDING, tp->wk.flags)) { reset: rtl_reset_work(tp); netif_wake_queue(tp->dev); } out_unlock: rtnl_unlock(); } static int rtl8169_poll(struct napi_struct *napi, int budget) { struct rtl8169_private *tp = container_of(napi, struct rtl8169_private, napi); struct net_device *dev = tp->dev; int work_done; rtl_tx(dev, tp, budget); work_done = rtl_rx(dev, tp, budget); if (work_done < budget && napi_complete_done(napi, work_done)) rtl_irq_enable(tp); return work_done; } static void r8169_phylink_handler(struct net_device *ndev) { struct rtl8169_private *tp = netdev_priv(ndev); struct device *d = tp_to_dev(tp); if (netif_carrier_ok(ndev)) { rtl_link_chg_patch(tp); pm_request_resume(d); } else { pm_runtime_idle(d); } phy_print_status(tp->phydev); } static int r8169_phy_connect(struct rtl8169_private *tp) { struct phy_device *phydev = tp->phydev; phy_interface_t phy_mode; int ret; phy_mode = tp->supports_gmii ? PHY_INTERFACE_MODE_GMII : PHY_INTERFACE_MODE_MII; ret = phy_connect_direct(tp->dev, phydev, r8169_phylink_handler, phy_mode); if (ret) return ret; if (!tp->supports_gmii) phy_set_max_speed(phydev, SPEED_100); phy_attached_info(phydev); return 0; } static void rtl8169_down(struct rtl8169_private *tp) { /* Clear all task flags */ bitmap_zero(tp->wk.flags, RTL_FLAG_MAX); phy_stop(tp->phydev); rtl8169_update_counters(tp); pci_clear_master(tp->pci_dev); rtl_pci_commit(tp); rtl8169_cleanup(tp); rtl_disable_exit_l1(tp); rtl_prepare_power_down(tp); } static void rtl8169_up(struct rtl8169_private *tp) { pci_set_master(tp->pci_dev); phy_init_hw(tp->phydev); phy_resume(tp->phydev); rtl8169_init_phy(tp); napi_enable(&tp->napi); set_bit(RTL_FLAG_TASK_ENABLED, tp->wk.flags); rtl_reset_work(tp); phy_start(tp->phydev); } static int rtl8169_close(struct net_device *dev) { struct rtl8169_private *tp = netdev_priv(dev); struct pci_dev *pdev = tp->pci_dev; pm_runtime_get_sync(&pdev->dev); netif_stop_queue(dev); rtl8169_down(tp); rtl8169_rx_clear(tp); cancel_work_sync(&tp->wk.work); free_irq(tp->irq, tp); phy_disconnect(tp->phydev); dma_free_coherent(&pdev->dev, R8169_RX_RING_BYTES, tp->RxDescArray, tp->RxPhyAddr); dma_free_coherent(&pdev->dev, R8169_TX_RING_BYTES, tp->TxDescArray, tp->TxPhyAddr); tp->TxDescArray = NULL; tp->RxDescArray = NULL; pm_runtime_put_sync(&pdev->dev); return 0; } #ifdef CONFIG_NET_POLL_CONTROLLER static void rtl8169_netpoll(struct net_device *dev) { struct rtl8169_private *tp = netdev_priv(dev); rtl8169_interrupt(tp->irq, tp); } #endif static int rtl_open(struct net_device *dev) { struct rtl8169_private *tp = netdev_priv(dev); struct pci_dev *pdev = tp->pci_dev; unsigned long irqflags; int retval = -ENOMEM; pm_runtime_get_sync(&pdev->dev); /* * Rx and Tx descriptors needs 256 bytes alignment. * dma_alloc_coherent provides more. */ tp->TxDescArray = dma_alloc_coherent(&pdev->dev, R8169_TX_RING_BYTES, &tp->TxPhyAddr, GFP_KERNEL); if (!tp->TxDescArray) goto out; tp->RxDescArray = dma_alloc_coherent(&pdev->dev, R8169_RX_RING_BYTES, &tp->RxPhyAddr, GFP_KERNEL); if (!tp->RxDescArray) goto err_free_tx_0; retval = rtl8169_init_ring(tp); if (retval < 0) goto err_free_rx_1; rtl_request_firmware(tp); irqflags = pci_dev_msi_enabled(pdev) ? IRQF_NO_THREAD : IRQF_SHARED; retval = request_irq(tp->irq, rtl8169_interrupt, irqflags, dev->name, tp); if (retval < 0) goto err_release_fw_2; retval = r8169_phy_connect(tp); if (retval) goto err_free_irq; rtl8169_up(tp); rtl8169_init_counter_offsets(tp); netif_start_queue(dev); out: pm_runtime_put_sync(&pdev->dev); return retval; err_free_irq: free_irq(tp->irq, tp); err_release_fw_2: rtl_release_firmware(tp); rtl8169_rx_clear(tp); err_free_rx_1: dma_free_coherent(&pdev->dev, R8169_RX_RING_BYTES, tp->RxDescArray, tp->RxPhyAddr); tp->RxDescArray = NULL; err_free_tx_0: dma_free_coherent(&pdev->dev, R8169_TX_RING_BYTES, tp->TxDescArray, tp->TxPhyAddr); tp->TxDescArray = NULL; goto out; } static void rtl8169_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats) { struct rtl8169_private *tp = netdev_priv(dev); struct pci_dev *pdev = tp->pci_dev; struct rtl8169_counters *counters = tp->counters; pm_runtime_get_noresume(&pdev->dev); netdev_stats_to_stats64(stats, &dev->stats); dev_fetch_sw_netstats(stats, dev->tstats); /* * Fetch additional counter values missing in stats collected by driver * from tally counters. */ if (pm_runtime_active(&pdev->dev)) rtl8169_update_counters(tp); /* * Subtract values fetched during initalization. * See rtl8169_init_counter_offsets for a description why we do that. */ stats->tx_errors = le64_to_cpu(counters->tx_errors) - le64_to_cpu(tp->tc_offset.tx_errors); stats->collisions = le32_to_cpu(counters->tx_multi_collision) - le32_to_cpu(tp->tc_offset.tx_multi_collision); stats->tx_aborted_errors = le16_to_cpu(counters->tx_aborted) - le16_to_cpu(tp->tc_offset.tx_aborted); stats->rx_missed_errors = le16_to_cpu(counters->rx_missed) - le16_to_cpu(tp->tc_offset.rx_missed); pm_runtime_put_noidle(&pdev->dev); } static void rtl8169_net_suspend(struct rtl8169_private *tp) { netif_device_detach(tp->dev); if (netif_running(tp->dev)) rtl8169_down(tp); } static int rtl8169_runtime_resume(struct device *dev) { struct rtl8169_private *tp = dev_get_drvdata(dev); rtl_rar_set(tp, tp->dev->dev_addr); __rtl8169_set_wol(tp, tp->saved_wolopts); if (tp->TxDescArray) rtl8169_up(tp); netif_device_attach(tp->dev); return 0; } static int rtl8169_suspend(struct device *device) { struct rtl8169_private *tp = dev_get_drvdata(device); rtnl_lock(); rtl8169_net_suspend(tp); if (!device_may_wakeup(tp_to_dev(tp))) clk_disable_unprepare(tp->clk); rtnl_unlock(); return 0; } static int rtl8169_resume(struct device *device) { struct rtl8169_private *tp = dev_get_drvdata(device); if (!device_may_wakeup(tp_to_dev(tp))) clk_prepare_enable(tp->clk); /* Reportedly at least Asus X453MA truncates packets otherwise */ if (tp->mac_version == RTL_GIGA_MAC_VER_37) rtl_init_rxcfg(tp); return rtl8169_runtime_resume(device); } static int rtl8169_runtime_suspend(struct device *device) { struct rtl8169_private *tp = dev_get_drvdata(device); if (!tp->TxDescArray) { netif_device_detach(tp->dev); return 0; } rtnl_lock(); __rtl8169_set_wol(tp, WAKE_PHY); rtl8169_net_suspend(tp); rtnl_unlock(); return 0; } static int rtl8169_runtime_idle(struct device *device) { struct rtl8169_private *tp = dev_get_drvdata(device); if (tp->dash_type != RTL_DASH_NONE) return -EBUSY; if (!netif_running(tp->dev) || !netif_carrier_ok(tp->dev)) pm_schedule_suspend(device, 10000); return -EBUSY; } static const struct dev_pm_ops rtl8169_pm_ops = { SYSTEM_SLEEP_PM_OPS(rtl8169_suspend, rtl8169_resume) RUNTIME_PM_OPS(rtl8169_runtime_suspend, rtl8169_runtime_resume, rtl8169_runtime_idle) }; static void rtl_shutdown(struct pci_dev *pdev) { struct rtl8169_private *tp = pci_get_drvdata(pdev); rtnl_lock(); rtl8169_net_suspend(tp); rtnl_unlock(); /* Restore original MAC address */ rtl_rar_set(tp, tp->dev->perm_addr); if (system_state == SYSTEM_POWER_OFF && tp->dash_type == RTL_DASH_NONE) { pci_wake_from_d3(pdev, tp->saved_wolopts); pci_set_power_state(pdev, PCI_D3hot); } } static void rtl_remove_one(struct pci_dev *pdev) { struct rtl8169_private *tp = pci_get_drvdata(pdev); if (pci_dev_run_wake(pdev)) pm_runtime_get_noresume(&pdev->dev); unregister_netdev(tp->dev); if (tp->dash_type != RTL_DASH_NONE) rtl8168_driver_stop(tp); rtl_release_firmware(tp); /* restore original MAC address */ rtl_rar_set(tp, tp->dev->perm_addr); } static const struct net_device_ops rtl_netdev_ops = { .ndo_open = rtl_open, .ndo_stop = rtl8169_close, .ndo_get_stats64 = rtl8169_get_stats64, .ndo_start_xmit = rtl8169_start_xmit, .ndo_features_check = rtl8169_features_check, .ndo_tx_timeout = rtl8169_tx_timeout, .ndo_validate_addr = eth_validate_addr, .ndo_change_mtu = rtl8169_change_mtu, .ndo_fix_features = rtl8169_fix_features, .ndo_set_features = rtl8169_set_features, .ndo_set_mac_address = rtl_set_mac_address, .ndo_eth_ioctl = phy_do_ioctl_running, .ndo_set_rx_mode = rtl_set_rx_mode, #ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = rtl8169_netpoll, #endif }; static void rtl_set_irq_mask(struct rtl8169_private *tp) { tp->irq_mask = RxOK | RxErr | TxOK | TxErr | LinkChg; if (tp->mac_version <= RTL_GIGA_MAC_VER_06) tp->irq_mask |= SYSErr | RxOverflow | RxFIFOOver; else if (tp->mac_version == RTL_GIGA_MAC_VER_11) /* special workaround needed */ tp->irq_mask |= RxFIFOOver; else tp->irq_mask |= RxOverflow; } static int rtl_alloc_irq(struct rtl8169_private *tp) { unsigned int flags; switch (tp->mac_version) { case RTL_GIGA_MAC_VER_02 ... RTL_GIGA_MAC_VER_06: rtl_unlock_config_regs(tp); RTL_W8(tp, Config2, RTL_R8(tp, Config2) & ~MSIEnable); rtl_lock_config_regs(tp); fallthrough; case RTL_GIGA_MAC_VER_07 ... RTL_GIGA_MAC_VER_17: flags = PCI_IRQ_LEGACY; break; default: flags = PCI_IRQ_ALL_TYPES; break; } return pci_alloc_irq_vectors(tp->pci_dev, 1, 1, flags); } static void rtl_read_mac_address(struct rtl8169_private *tp, u8 mac_addr[ETH_ALEN]) { /* Get MAC address */ if (rtl_is_8168evl_up(tp) && tp->mac_version != RTL_GIGA_MAC_VER_34) { u32 value; value = rtl_eri_read(tp, 0xe0); put_unaligned_le32(value, mac_addr); value = rtl_eri_read(tp, 0xe4); put_unaligned_le16(value, mac_addr + 4); } else if (rtl_is_8125(tp)) { rtl_read_mac_from_reg(tp, mac_addr, MAC0_BKP); } } DECLARE_RTL_COND(rtl_link_list_ready_cond) { return RTL_R8(tp, MCU) & LINK_LIST_RDY; } static void r8168g_wait_ll_share_fifo_ready(struct rtl8169_private *tp) { rtl_loop_wait_high(tp, &rtl_link_list_ready_cond, 100, 42); } static int r8169_mdio_read_reg(struct mii_bus *mii_bus, int phyaddr, int phyreg) { struct rtl8169_private *tp = mii_bus->priv; if (phyaddr > 0) return -ENODEV; return rtl_readphy(tp, phyreg); } static int r8169_mdio_write_reg(struct mii_bus *mii_bus, int phyaddr, int phyreg, u16 val) { struct rtl8169_private *tp = mii_bus->priv; if (phyaddr > 0) return -ENODEV; rtl_writephy(tp, phyreg, val); return 0; } static int r8169_mdio_register(struct rtl8169_private *tp) { struct pci_dev *pdev = tp->pci_dev; struct mii_bus *new_bus; int ret; new_bus = devm_mdiobus_alloc(&pdev->dev); if (!new_bus) return -ENOMEM; new_bus->name = "r8169"; new_bus->priv = tp; new_bus->parent = &pdev->dev; new_bus->irq[0] = PHY_MAC_INTERRUPT; snprintf(new_bus->id, MII_BUS_ID_SIZE, "r8169-%x-%x", pci_domain_nr(pdev->bus), pci_dev_id(pdev)); new_bus->read = r8169_mdio_read_reg; new_bus->write = r8169_mdio_write_reg; ret = devm_mdiobus_register(&pdev->dev, new_bus); if (ret) return ret; tp->phydev = mdiobus_get_phy(new_bus, 0); if (!tp->phydev) { return -ENODEV; } else if (!tp->phydev->drv) { /* Most chip versions fail with the genphy driver. * Therefore ensure that the dedicated PHY driver is loaded. */ dev_err(&pdev->dev, "no dedicated PHY driver found for PHY ID 0x%08x, maybe realtek.ko needs to be added to initramfs?\n", tp->phydev->phy_id); return -EUNATCH; } tp->phydev->mac_managed_pm = true; phy_support_asym_pause(tp->phydev); /* PHY will be woken up in rtl_open() */ phy_suspend(tp->phydev); return 0; } static void rtl_hw_init_8168g(struct rtl8169_private *tp) { rtl_enable_rxdvgate(tp); RTL_W8(tp, ChipCmd, RTL_R8(tp, ChipCmd) & ~(CmdTxEnb | CmdRxEnb)); msleep(1); RTL_W8(tp, MCU, RTL_R8(tp, MCU) & ~NOW_IS_OOB); r8168_mac_ocp_modify(tp, 0xe8de, BIT(14), 0); r8168g_wait_ll_share_fifo_ready(tp); r8168_mac_ocp_modify(tp, 0xe8de, 0, BIT(15)); r8168g_wait_ll_share_fifo_ready(tp); } static void rtl_hw_init_8125(struct rtl8169_private *tp) { rtl_enable_rxdvgate(tp); RTL_W8(tp, ChipCmd, RTL_R8(tp, ChipCmd) & ~(CmdTxEnb | CmdRxEnb)); msleep(1); RTL_W8(tp, MCU, RTL_R8(tp, MCU) & ~NOW_IS_OOB); r8168_mac_ocp_modify(tp, 0xe8de, BIT(14), 0); r8168g_wait_ll_share_fifo_ready(tp); r8168_mac_ocp_write(tp, 0xc0aa, 0x07d0); r8168_mac_ocp_write(tp, 0xc0a6, 0x0150); r8168_mac_ocp_write(tp, 0xc01e, 0x5555); r8168g_wait_ll_share_fifo_ready(tp); } static void rtl_hw_initialize(struct rtl8169_private *tp) { switch (tp->mac_version) { case RTL_GIGA_MAC_VER_51 ... RTL_GIGA_MAC_VER_53: rtl8168ep_stop_cmac(tp); fallthrough; case RTL_GIGA_MAC_VER_40 ... RTL_GIGA_MAC_VER_48: rtl_hw_init_8168g(tp); break; case RTL_GIGA_MAC_VER_61 ... RTL_GIGA_MAC_VER_63: rtl_hw_init_8125(tp); break; default: break; } } static int rtl_jumbo_max(struct rtl8169_private *tp) { /* Non-GBit versions don't support jumbo frames */ if (!tp->supports_gmii) return 0; switch (tp->mac_version) { /* RTL8169 */ case RTL_GIGA_MAC_VER_02 ... RTL_GIGA_MAC_VER_06: return JUMBO_7K; /* RTL8168b */ case RTL_GIGA_MAC_VER_11: case RTL_GIGA_MAC_VER_17: return JUMBO_4K; /* RTL8168c */ case RTL_GIGA_MAC_VER_18 ... RTL_GIGA_MAC_VER_24: return JUMBO_6K; default: return JUMBO_9K; } } static void rtl_init_mac_address(struct rtl8169_private *tp) { u8 mac_addr[ETH_ALEN] __aligned(2) = {}; struct net_device *dev = tp->dev; int rc; rc = eth_platform_get_mac_address(tp_to_dev(tp), mac_addr); if (!rc) goto done; rtl_read_mac_address(tp, mac_addr); if (is_valid_ether_addr(mac_addr)) goto done; rtl_read_mac_from_reg(tp, mac_addr, MAC0); if (is_valid_ether_addr(mac_addr)) goto done; eth_random_addr(mac_addr); dev->addr_assign_type = NET_ADDR_RANDOM; dev_warn(tp_to_dev(tp), "can't read MAC address, setting random one\n"); done: eth_hw_addr_set(dev, mac_addr); rtl_rar_set(tp, mac_addr); } /* register is set if system vendor successfully tested ASPM 1.2 */ static bool rtl_aspm_is_safe(struct rtl8169_private *tp) { if (tp->mac_version >= RTL_GIGA_MAC_VER_61 && r8168_mac_ocp_read(tp, 0xc0b2) & 0xf) return true; return false; } static int rtl_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) { struct rtl8169_private *tp; int jumbo_max, region, rc; enum mac_version chipset; struct net_device *dev; u32 txconfig; u16 xid; dev = devm_alloc_etherdev(&pdev->dev, sizeof (*tp)); if (!dev) return -ENOMEM; SET_NETDEV_DEV(dev, &pdev->dev); dev->netdev_ops = &rtl_netdev_ops; tp = netdev_priv(dev); tp->dev = dev; tp->pci_dev = pdev; tp->supports_gmii = ent->driver_data == RTL_CFG_NO_GBIT ? 0 : 1; tp->eee_adv = -1; tp->ocp_base = OCP_STD_PHY_BASE; raw_spin_lock_init(&tp->cfg9346_usage_lock); raw_spin_lock_init(&tp->config25_lock); raw_spin_lock_init(&tp->mac_ocp_lock); dev->tstats = devm_netdev_alloc_pcpu_stats(&pdev->dev, struct pcpu_sw_netstats); if (!dev->tstats) return -ENOMEM; /* Get the *optional* external "ether_clk" used on some boards */ tp->clk = devm_clk_get_optional_enabled(&pdev->dev, "ether_clk"); if (IS_ERR(tp->clk)) return dev_err_probe(&pdev->dev, PTR_ERR(tp->clk), "failed to get ether_clk\n"); /* enable device (incl. PCI PM wakeup and hotplug setup) */ rc = pcim_enable_device(pdev); if (rc < 0) return dev_err_probe(&pdev->dev, rc, "enable failure\n"); if (pcim_set_mwi(pdev) < 0) dev_info(&pdev->dev, "Mem-Wr-Inval unavailable\n"); /* use first MMIO region */ region = ffs(pci_select_bars(pdev, IORESOURCE_MEM)) - 1; if (region < 0) return dev_err_probe(&pdev->dev, -ENODEV, "no MMIO resource found\n"); rc = pcim_iomap_regions(pdev, BIT(region), KBUILD_MODNAME); if (rc < 0) return dev_err_probe(&pdev->dev, rc, "cannot remap MMIO, aborting\n"); tp->mmio_addr = pcim_iomap_table(pdev)[region]; txconfig = RTL_R32(tp, TxConfig); if (txconfig == ~0U) return dev_err_probe(&pdev->dev, -EIO, "PCI read failed\n"); xid = (txconfig >> 20) & 0xfcf; /* Identify chip attached to board */ chipset = rtl8169_get_mac_version(xid, tp->supports_gmii); if (chipset == RTL_GIGA_MAC_NONE) return dev_err_probe(&pdev->dev, -ENODEV, "unknown chip XID %03x, contact r8169 maintainers (see MAINTAINERS file)\n", xid); tp->mac_version = chipset; /* Disable ASPM L1 as that cause random device stop working * problems as well as full system hangs for some PCIe devices users. */ if (rtl_aspm_is_safe(tp)) rc = 0; else rc = pci_disable_link_state(pdev, PCIE_LINK_STATE_L1); tp->aspm_manageable = !rc; tp->dash_type = rtl_check_dash(tp); tp->cp_cmd = RTL_R16(tp, CPlusCmd) & CPCMD_MASK; if (sizeof(dma_addr_t) > 4 && tp->mac_version >= RTL_GIGA_MAC_VER_18 && !dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64))) dev->features |= NETIF_F_HIGHDMA; rtl_init_rxcfg(tp); rtl8169_irq_mask_and_ack(tp); rtl_hw_initialize(tp); rtl_hw_reset(tp); rc = rtl_alloc_irq(tp); if (rc < 0) return dev_err_probe(&pdev->dev, rc, "Can't allocate interrupt\n"); tp->irq = pci_irq_vector(pdev, 0); INIT_WORK(&tp->wk.work, rtl_task); rtl_init_mac_address(tp); dev->ethtool_ops = &rtl8169_ethtool_ops; netif_napi_add(dev, &tp->napi, rtl8169_poll); dev->hw_features = NETIF_F_IP_CSUM | NETIF_F_RXCSUM | NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX; dev->vlan_features = NETIF_F_SG | NETIF_F_IP_CSUM | NETIF_F_TSO; dev->priv_flags |= IFF_LIVE_ADDR_CHANGE; /* * Pretend we are using VLANs; This bypasses a nasty bug where * Interrupts stop flowing on high load on 8110SCd controllers. */ if (tp->mac_version == RTL_GIGA_MAC_VER_05) /* Disallow toggling */ dev->hw_features &= ~NETIF_F_HW_VLAN_CTAG_RX; if (rtl_chip_supports_csum_v2(tp)) dev->hw_features |= NETIF_F_IPV6_CSUM; dev->features |= dev->hw_features; /* There has been a number of reports that using SG/TSO results in * tx timeouts. However for a lot of people SG/TSO works fine. * Therefore disable both features by default, but allow users to * enable them. Use at own risk! */ if (rtl_chip_supports_csum_v2(tp)) { dev->hw_features |= NETIF_F_SG | NETIF_F_TSO | NETIF_F_TSO6; netif_set_tso_max_size(dev, RTL_GSO_MAX_SIZE_V2); netif_set_tso_max_segs(dev, RTL_GSO_MAX_SEGS_V2); } else { dev->hw_features |= NETIF_F_SG | NETIF_F_TSO; netif_set_tso_max_size(dev, RTL_GSO_MAX_SIZE_V1); netif_set_tso_max_segs(dev, RTL_GSO_MAX_SEGS_V1); } dev->hw_features |= NETIF_F_RXALL; dev->hw_features |= NETIF_F_RXFCS; netdev_sw_irq_coalesce_default_on(dev); /* configure chip for default features */ rtl8169_set_features(dev, dev->features); if (tp->dash_type == RTL_DASH_NONE) { rtl_set_d3_pll_down(tp, true); } else { rtl_set_d3_pll_down(tp, false); dev->wol_enabled = 1; } jumbo_max = rtl_jumbo_max(tp); if (jumbo_max) dev->max_mtu = jumbo_max; rtl_set_irq_mask(tp); tp->fw_name = rtl_chip_infos[chipset].fw_name; tp->counters = dmam_alloc_coherent (&pdev->dev, sizeof(*tp->counters), &tp->counters_phys_addr, GFP_KERNEL); if (!tp->counters) return -ENOMEM; pci_set_drvdata(pdev, tp); rc = r8169_mdio_register(tp); if (rc) return rc; rc = register_netdev(dev); if (rc) return rc; netdev_info(dev, "%s, %pM, XID %03x, IRQ %d\n", rtl_chip_infos[chipset].name, dev->dev_addr, xid, tp->irq); if (jumbo_max) netdev_info(dev, "jumbo features [frames: %d bytes, tx checksumming: %s]\n", jumbo_max, tp->mac_version <= RTL_GIGA_MAC_VER_06 ? "ok" : "ko"); if (tp->dash_type != RTL_DASH_NONE) { netdev_info(dev, "DASH enabled\n"); rtl8168_driver_start(tp); } if (pci_dev_run_wake(pdev)) pm_runtime_put_sync(&pdev->dev); return 0; } static struct pci_driver rtl8169_pci_driver = { .name = KBUILD_MODNAME, .id_table = rtl8169_pci_tbl, .probe = rtl_init_one, .remove = rtl_remove_one, .shutdown = rtl_shutdown, .driver.pm = pm_ptr(&rtl8169_pm_ops), }; module_pci_driver(rtl8169_pci_driver);
linux-master
drivers/net/ethernet/realtek/r8169_main.c
// SPDX-License-Identifier: GPL-2.0-only /* * r8169_phy_config.c: RealTek 8169/8168/8101 ethernet driver. * * Copyright (c) 2002 ShuChen <[email protected]> * Copyright (c) 2003 - 2007 Francois Romieu <[email protected]> * Copyright (c) a lot of people too. Please respect their work. * * See MAINTAINERS file for support contact information. */ #include <linux/delay.h> #include <linux/phy.h> #include "r8169.h" typedef void (*rtl_phy_cfg_fct)(struct rtl8169_private *tp, struct phy_device *phydev); static void r8168d_modify_extpage(struct phy_device *phydev, int extpage, int reg, u16 mask, u16 val) { int oldpage = phy_select_page(phydev, 0x0007); __phy_write(phydev, 0x1e, extpage); __phy_modify(phydev, reg, mask, val); phy_restore_page(phydev, oldpage, 0); } static void r8168d_phy_param(struct phy_device *phydev, u16 parm, u16 mask, u16 val) { int oldpage = phy_select_page(phydev, 0x0005); __phy_write(phydev, 0x05, parm); __phy_modify(phydev, 0x06, mask, val); phy_restore_page(phydev, oldpage, 0); } static void r8168g_phy_param(struct phy_device *phydev, u16 parm, u16 mask, u16 val) { int oldpage = phy_select_page(phydev, 0x0a43); __phy_write(phydev, 0x13, parm); __phy_modify(phydev, 0x14, mask, val); phy_restore_page(phydev, oldpage, 0); } struct phy_reg { u16 reg; u16 val; }; static void __rtl_writephy_batch(struct phy_device *phydev, const struct phy_reg *regs, int len) { phy_lock_mdio_bus(phydev); while (len-- > 0) { __phy_write(phydev, regs->reg, regs->val); regs++; } phy_unlock_mdio_bus(phydev); } #define rtl_writephy_batch(p, a) __rtl_writephy_batch(p, a, ARRAY_SIZE(a)) static void rtl8168f_config_eee_phy(struct phy_device *phydev) { r8168d_modify_extpage(phydev, 0x0020, 0x15, 0, BIT(8)); r8168d_phy_param(phydev, 0x8b85, 0, BIT(13)); } static void rtl8168g_config_eee_phy(struct phy_device *phydev) { phy_modify_paged(phydev, 0x0a43, 0x11, 0, BIT(4)); } static void rtl8168h_config_eee_phy(struct phy_device *phydev) { rtl8168g_config_eee_phy(phydev); phy_modify_paged(phydev, 0xa4a, 0x11, 0x0000, 0x0200); phy_modify_paged(phydev, 0xa42, 0x14, 0x0000, 0x0080); } static void rtl8125a_config_eee_phy(struct phy_device *phydev) { rtl8168h_config_eee_phy(phydev); phy_modify_paged(phydev, 0xa6d, 0x12, 0x0001, 0x0000); phy_modify_paged(phydev, 0xa6d, 0x14, 0x0010, 0x0000); } static void rtl8125b_config_eee_phy(struct phy_device *phydev) { phy_modify_paged(phydev, 0xa6d, 0x12, 0x0001, 0x0000); phy_modify_paged(phydev, 0xa6d, 0x14, 0x0010, 0x0000); phy_modify_paged(phydev, 0xa42, 0x14, 0x0080, 0x0000); phy_modify_paged(phydev, 0xa4a, 0x11, 0x0200, 0x0000); } static void rtl8169s_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { static const struct phy_reg phy_reg_init[] = { { 0x1f, 0x0001 }, { 0x06, 0x006e }, { 0x08, 0x0708 }, { 0x15, 0x4000 }, { 0x18, 0x65c7 }, { 0x1f, 0x0001 }, { 0x03, 0x00a1 }, { 0x02, 0x0008 }, { 0x01, 0x0120 }, { 0x00, 0x1000 }, { 0x04, 0x0800 }, { 0x04, 0x0000 }, { 0x03, 0xff41 }, { 0x02, 0xdf60 }, { 0x01, 0x0140 }, { 0x00, 0x0077 }, { 0x04, 0x7800 }, { 0x04, 0x7000 }, { 0x03, 0x802f }, { 0x02, 0x4f02 }, { 0x01, 0x0409 }, { 0x00, 0xf0f9 }, { 0x04, 0x9800 }, { 0x04, 0x9000 }, { 0x03, 0xdf01 }, { 0x02, 0xdf20 }, { 0x01, 0xff95 }, { 0x00, 0xba00 }, { 0x04, 0xa800 }, { 0x04, 0xa000 }, { 0x03, 0xff41 }, { 0x02, 0xdf20 }, { 0x01, 0x0140 }, { 0x00, 0x00bb }, { 0x04, 0xb800 }, { 0x04, 0xb000 }, { 0x03, 0xdf41 }, { 0x02, 0xdc60 }, { 0x01, 0x6340 }, { 0x00, 0x007d }, { 0x04, 0xd800 }, { 0x04, 0xd000 }, { 0x03, 0xdf01 }, { 0x02, 0xdf20 }, { 0x01, 0x100a }, { 0x00, 0xa0ff }, { 0x04, 0xf800 }, { 0x04, 0xf000 }, { 0x1f, 0x0000 }, { 0x0b, 0x0000 }, { 0x00, 0x9200 } }; rtl_writephy_batch(phydev, phy_reg_init); } static void rtl8169sb_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { phy_write_paged(phydev, 0x0002, 0x01, 0x90d0); } static void rtl8169scd_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { static const struct phy_reg phy_reg_init[] = { { 0x1f, 0x0001 }, { 0x04, 0x0000 }, { 0x03, 0x00a1 }, { 0x02, 0x0008 }, { 0x01, 0x0120 }, { 0x00, 0x1000 }, { 0x04, 0x0800 }, { 0x04, 0x9000 }, { 0x03, 0x802f }, { 0x02, 0x4f02 }, { 0x01, 0x0409 }, { 0x00, 0xf099 }, { 0x04, 0x9800 }, { 0x04, 0xa000 }, { 0x03, 0xdf01 }, { 0x02, 0xdf20 }, { 0x01, 0xff95 }, { 0x00, 0xba00 }, { 0x04, 0xa800 }, { 0x04, 0xf000 }, { 0x03, 0xdf01 }, { 0x02, 0xdf20 }, { 0x01, 0x101a }, { 0x00, 0xa0ff }, { 0x04, 0xf800 }, { 0x04, 0x0000 }, { 0x1f, 0x0000 }, { 0x1f, 0x0001 }, { 0x10, 0xf41b }, { 0x14, 0xfb54 }, { 0x18, 0xf5c7 }, { 0x1f, 0x0000 }, { 0x1f, 0x0001 }, { 0x17, 0x0cc0 }, { 0x1f, 0x0000 } }; rtl_writephy_batch(phydev, phy_reg_init); } static void rtl8169sce_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { static const struct phy_reg phy_reg_init[] = { { 0x1f, 0x0001 }, { 0x04, 0x0000 }, { 0x03, 0x00a1 }, { 0x02, 0x0008 }, { 0x01, 0x0120 }, { 0x00, 0x1000 }, { 0x04, 0x0800 }, { 0x04, 0x9000 }, { 0x03, 0x802f }, { 0x02, 0x4f02 }, { 0x01, 0x0409 }, { 0x00, 0xf099 }, { 0x04, 0x9800 }, { 0x04, 0xa000 }, { 0x03, 0xdf01 }, { 0x02, 0xdf20 }, { 0x01, 0xff95 }, { 0x00, 0xba00 }, { 0x04, 0xa800 }, { 0x04, 0xf000 }, { 0x03, 0xdf01 }, { 0x02, 0xdf20 }, { 0x01, 0x101a }, { 0x00, 0xa0ff }, { 0x04, 0xf800 }, { 0x04, 0x0000 }, { 0x1f, 0x0000 }, { 0x1f, 0x0001 }, { 0x0b, 0x8480 }, { 0x1f, 0x0000 }, { 0x1f, 0x0001 }, { 0x18, 0x67c7 }, { 0x04, 0x2000 }, { 0x03, 0x002f }, { 0x02, 0x4360 }, { 0x01, 0x0109 }, { 0x00, 0x3022 }, { 0x04, 0x2800 }, { 0x1f, 0x0000 }, { 0x1f, 0x0001 }, { 0x17, 0x0cc0 }, { 0x1f, 0x0000 } }; rtl_writephy_batch(phydev, phy_reg_init); } static void rtl8168bb_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { phy_write(phydev, 0x1f, 0x0001); phy_set_bits(phydev, 0x16, BIT(0)); phy_write(phydev, 0x10, 0xf41b); phy_write(phydev, 0x1f, 0x0000); } static void rtl8168bef_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { phy_write_paged(phydev, 0x0001, 0x10, 0xf41b); } static void rtl8168cp_1_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { phy_write(phydev, 0x1d, 0x0f00); phy_write_paged(phydev, 0x0002, 0x0c, 0x1ec8); } static void rtl8168cp_2_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { phy_set_bits(phydev, 0x14, BIT(5)); phy_set_bits(phydev, 0x0d, BIT(5)); phy_write_paged(phydev, 0x0001, 0x1d, 0x3d98); } static void rtl8168c_1_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { static const struct phy_reg phy_reg_init[] = { { 0x1f, 0x0001 }, { 0x12, 0x2300 }, { 0x1f, 0x0002 }, { 0x00, 0x88d4 }, { 0x01, 0x82b1 }, { 0x03, 0x7002 }, { 0x08, 0x9e30 }, { 0x09, 0x01f0 }, { 0x0a, 0x5500 }, { 0x0c, 0x00c8 }, { 0x1f, 0x0003 }, { 0x12, 0xc096 }, { 0x16, 0x000a }, { 0x1f, 0x0000 }, { 0x1f, 0x0000 }, { 0x09, 0x2000 }, { 0x09, 0x0000 } }; rtl_writephy_batch(phydev, phy_reg_init); phy_set_bits(phydev, 0x14, BIT(5)); phy_set_bits(phydev, 0x0d, BIT(5)); } static void rtl8168c_2_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { static const struct phy_reg phy_reg_init[] = { { 0x1f, 0x0001 }, { 0x12, 0x2300 }, { 0x03, 0x802f }, { 0x02, 0x4f02 }, { 0x01, 0x0409 }, { 0x00, 0xf099 }, { 0x04, 0x9800 }, { 0x04, 0x9000 }, { 0x1d, 0x3d98 }, { 0x1f, 0x0002 }, { 0x0c, 0x7eb8 }, { 0x06, 0x0761 }, { 0x1f, 0x0003 }, { 0x16, 0x0f0a }, { 0x1f, 0x0000 } }; rtl_writephy_batch(phydev, phy_reg_init); phy_set_bits(phydev, 0x16, BIT(0)); phy_set_bits(phydev, 0x14, BIT(5)); phy_set_bits(phydev, 0x0d, BIT(5)); } static void rtl8168c_3_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { static const struct phy_reg phy_reg_init[] = { { 0x1f, 0x0001 }, { 0x12, 0x2300 }, { 0x1d, 0x3d98 }, { 0x1f, 0x0002 }, { 0x0c, 0x7eb8 }, { 0x06, 0x5461 }, { 0x1f, 0x0003 }, { 0x16, 0x0f0a }, { 0x1f, 0x0000 } }; rtl_writephy_batch(phydev, phy_reg_init); phy_set_bits(phydev, 0x16, BIT(0)); phy_set_bits(phydev, 0x14, BIT(5)); phy_set_bits(phydev, 0x0d, BIT(5)); } static const struct phy_reg rtl8168d_1_phy_reg_init_0[] = { /* Channel Estimation */ { 0x1f, 0x0001 }, { 0x06, 0x4064 }, { 0x07, 0x2863 }, { 0x08, 0x059c }, { 0x09, 0x26b4 }, { 0x0a, 0x6a19 }, { 0x0b, 0xdcc8 }, { 0x10, 0xf06d }, { 0x14, 0x7f68 }, { 0x18, 0x7fd9 }, { 0x1c, 0xf0ff }, { 0x1d, 0x3d9c }, { 0x1f, 0x0003 }, { 0x12, 0xf49f }, { 0x13, 0x070b }, { 0x1a, 0x05ad }, { 0x14, 0x94c0 }, /* * Tx Error Issue * Enhance line driver power */ { 0x1f, 0x0002 }, { 0x06, 0x5561 }, { 0x1f, 0x0005 }, { 0x05, 0x8332 }, { 0x06, 0x5561 }, /* * Can not link to 1Gbps with bad cable * Decrease SNR threshold form 21.07dB to 19.04dB */ { 0x1f, 0x0001 }, { 0x17, 0x0cc0 }, { 0x1f, 0x0000 }, { 0x0d, 0xf880 } }; static void rtl8168d_apply_firmware_cond(struct rtl8169_private *tp, struct phy_device *phydev, u16 val) { u16 reg_val; phy_write(phydev, 0x1f, 0x0005); phy_write(phydev, 0x05, 0x001b); reg_val = phy_read(phydev, 0x06); phy_write(phydev, 0x1f, 0x0000); if (reg_val != val) phydev_warn(phydev, "chipset not ready for firmware\n"); else r8169_apply_firmware(tp); } static void rtl8168d_1_common(struct phy_device *phydev) { u16 val; phy_write_paged(phydev, 0x0002, 0x05, 0x669a); r8168d_phy_param(phydev, 0x8330, 0xffff, 0x669a); phy_write(phydev, 0x1f, 0x0002); val = phy_read(phydev, 0x0d); if ((val & 0x00ff) != 0x006c) { static const u16 set[] = { 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006a, 0x006b, 0x006c }; int i; val &= 0xff00; for (i = 0; i < ARRAY_SIZE(set); i++) phy_write(phydev, 0x0d, val | set[i]); } } static void rtl8168d_1_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { rtl_writephy_batch(phydev, rtl8168d_1_phy_reg_init_0); /* * Rx Error Issue * Fine Tune Switching regulator parameter */ phy_write(phydev, 0x1f, 0x0002); phy_modify(phydev, 0x0b, 0x00ef, 0x0010); phy_modify(phydev, 0x0c, 0x5d00, 0xa200); if (rtl8168d_efuse_read(tp, 0x01) == 0xb1) { rtl8168d_1_common(phydev); } else { phy_write_paged(phydev, 0x0002, 0x05, 0x6662); r8168d_phy_param(phydev, 0x8330, 0xffff, 0x6662); } /* RSET couple improve */ phy_write(phydev, 0x1f, 0x0002); phy_set_bits(phydev, 0x0d, 0x0300); phy_set_bits(phydev, 0x0f, 0x0010); /* Fine tune PLL performance */ phy_write(phydev, 0x1f, 0x0002); phy_modify(phydev, 0x02, 0x0600, 0x0100); phy_clear_bits(phydev, 0x03, 0xe000); phy_write(phydev, 0x1f, 0x0000); rtl8168d_apply_firmware_cond(tp, phydev, 0xbf00); } static void rtl8168d_2_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { rtl_writephy_batch(phydev, rtl8168d_1_phy_reg_init_0); if (rtl8168d_efuse_read(tp, 0x01) == 0xb1) { rtl8168d_1_common(phydev); } else { phy_write_paged(phydev, 0x0002, 0x05, 0x2642); r8168d_phy_param(phydev, 0x8330, 0xffff, 0x2642); } /* Fine tune PLL performance */ phy_write(phydev, 0x1f, 0x0002); phy_modify(phydev, 0x02, 0x0600, 0x0100); phy_clear_bits(phydev, 0x03, 0xe000); phy_write(phydev, 0x1f, 0x0000); /* Switching regulator Slew rate */ phy_modify_paged(phydev, 0x0002, 0x0f, 0x0000, 0x0017); rtl8168d_apply_firmware_cond(tp, phydev, 0xb300); } static void rtl8168d_4_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { phy_write_paged(phydev, 0x0001, 0x17, 0x0cc0); r8168d_modify_extpage(phydev, 0x002d, 0x18, 0xffff, 0x0040); phy_set_bits(phydev, 0x0d, BIT(5)); } static void rtl8168e_1_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { static const struct phy_reg phy_reg_init[] = { /* Channel estimation fine tune */ { 0x1f, 0x0001 }, { 0x0b, 0x6c20 }, { 0x07, 0x2872 }, { 0x1c, 0xefff }, { 0x1f, 0x0003 }, { 0x14, 0x6420 }, { 0x1f, 0x0000 }, }; r8169_apply_firmware(tp); /* Enable Delay cap */ r8168d_phy_param(phydev, 0x8b80, 0xffff, 0xc896); rtl_writephy_batch(phydev, phy_reg_init); /* Update PFM & 10M TX idle timer */ r8168d_modify_extpage(phydev, 0x002f, 0x15, 0xffff, 0x1919); r8168d_modify_extpage(phydev, 0x00ac, 0x18, 0xffff, 0x0006); /* DCO enable for 10M IDLE Power */ r8168d_modify_extpage(phydev, 0x0023, 0x17, 0x0000, 0x0006); /* For impedance matching */ phy_modify_paged(phydev, 0x0002, 0x08, 0x7f00, 0x8000); /* PHY auto speed down */ r8168d_modify_extpage(phydev, 0x002d, 0x18, 0x0000, 0x0050); phy_set_bits(phydev, 0x14, BIT(15)); r8168d_phy_param(phydev, 0x8b86, 0x0000, 0x0001); r8168d_phy_param(phydev, 0x8b85, 0x2000, 0x0000); r8168d_modify_extpage(phydev, 0x0020, 0x15, 0x1100, 0x0000); phy_write_paged(phydev, 0x0006, 0x00, 0x5a00); phy_write_mmd(phydev, MDIO_MMD_AN, MDIO_AN_EEE_ADV, 0x0000); } static void rtl8168e_2_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { r8169_apply_firmware(tp); /* Enable Delay cap */ r8168d_modify_extpage(phydev, 0x00ac, 0x18, 0xffff, 0x0006); /* Channel estimation fine tune */ phy_write_paged(phydev, 0x0003, 0x09, 0xa20f); /* Green Setting */ r8168d_phy_param(phydev, 0x8b5b, 0xffff, 0x9222); r8168d_phy_param(phydev, 0x8b6d, 0xffff, 0x8000); r8168d_phy_param(phydev, 0x8b76, 0xffff, 0x8000); /* For 4-corner performance improve */ phy_write(phydev, 0x1f, 0x0005); phy_write(phydev, 0x05, 0x8b80); phy_set_bits(phydev, 0x17, 0x0006); phy_write(phydev, 0x1f, 0x0000); /* PHY auto speed down */ r8168d_modify_extpage(phydev, 0x002d, 0x18, 0x0000, 0x0010); phy_set_bits(phydev, 0x14, BIT(15)); /* improve 10M EEE waveform */ r8168d_phy_param(phydev, 0x8b86, 0x0000, 0x0001); /* Improve 2-pair detection performance */ r8168d_phy_param(phydev, 0x8b85, 0x0000, 0x4000); rtl8168f_config_eee_phy(phydev); /* Green feature */ phy_write(phydev, 0x1f, 0x0003); phy_set_bits(phydev, 0x19, BIT(0)); phy_set_bits(phydev, 0x10, BIT(10)); phy_write(phydev, 0x1f, 0x0000); phy_modify_paged(phydev, 0x0005, 0x01, 0, BIT(8)); } static void rtl8168f_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { /* For 4-corner performance improve */ r8168d_phy_param(phydev, 0x8b80, 0x0000, 0x0006); /* PHY auto speed down */ r8168d_modify_extpage(phydev, 0x002d, 0x18, 0x0000, 0x0010); phy_set_bits(phydev, 0x14, BIT(15)); /* Improve 10M EEE waveform */ r8168d_phy_param(phydev, 0x8b86, 0x0000, 0x0001); rtl8168f_config_eee_phy(phydev); } static void rtl8168f_1_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { r8169_apply_firmware(tp); /* Channel estimation fine tune */ phy_write_paged(phydev, 0x0003, 0x09, 0xa20f); /* Modify green table for giga & fnet */ r8168d_phy_param(phydev, 0x8b55, 0xffff, 0x0000); r8168d_phy_param(phydev, 0x8b5e, 0xffff, 0x0000); r8168d_phy_param(phydev, 0x8b67, 0xffff, 0x0000); r8168d_phy_param(phydev, 0x8b70, 0xffff, 0x0000); r8168d_modify_extpage(phydev, 0x0078, 0x17, 0xffff, 0x0000); r8168d_modify_extpage(phydev, 0x0078, 0x19, 0xffff, 0x00fb); /* Modify green table for 10M */ r8168d_phy_param(phydev, 0x8b79, 0xffff, 0xaa00); /* Disable hiimpedance detection (RTCT) */ phy_write_paged(phydev, 0x0003, 0x01, 0x328a); rtl8168f_hw_phy_config(tp, phydev); /* Improve 2-pair detection performance */ r8168d_phy_param(phydev, 0x8b85, 0x0000, 0x4000); } static void rtl8168f_2_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { r8169_apply_firmware(tp); rtl8168f_hw_phy_config(tp, phydev); } static void rtl8411_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { r8169_apply_firmware(tp); rtl8168f_hw_phy_config(tp, phydev); /* Improve 2-pair detection performance */ r8168d_phy_param(phydev, 0x8b85, 0x0000, 0x4000); /* Channel estimation fine tune */ phy_write_paged(phydev, 0x0003, 0x09, 0xa20f); /* Modify green table for giga & fnet */ r8168d_phy_param(phydev, 0x8b55, 0xffff, 0x0000); r8168d_phy_param(phydev, 0x8b5e, 0xffff, 0x0000); r8168d_phy_param(phydev, 0x8b67, 0xffff, 0x0000); r8168d_phy_param(phydev, 0x8b70, 0xffff, 0x0000); r8168d_modify_extpage(phydev, 0x0078, 0x17, 0xffff, 0x0000); r8168d_modify_extpage(phydev, 0x0078, 0x19, 0xffff, 0x00aa); /* Modify green table for 10M */ r8168d_phy_param(phydev, 0x8b79, 0xffff, 0xaa00); /* Disable hiimpedance detection (RTCT) */ phy_write_paged(phydev, 0x0003, 0x01, 0x328a); /* Modify green table for giga */ r8168d_phy_param(phydev, 0x8b54, 0x0800, 0x0000); r8168d_phy_param(phydev, 0x8b5d, 0x0800, 0x0000); r8168d_phy_param(phydev, 0x8a7c, 0x0100, 0x0000); r8168d_phy_param(phydev, 0x8a7f, 0x0000, 0x0100); r8168d_phy_param(phydev, 0x8a82, 0x0100, 0x0000); r8168d_phy_param(phydev, 0x8a85, 0x0100, 0x0000); r8168d_phy_param(phydev, 0x8a88, 0x0100, 0x0000); /* uc same-seed solution */ r8168d_phy_param(phydev, 0x8b85, 0x0000, 0x8000); /* Green feature */ phy_write(phydev, 0x1f, 0x0003); phy_clear_bits(phydev, 0x19, BIT(0)); phy_clear_bits(phydev, 0x10, BIT(10)); phy_write(phydev, 0x1f, 0x0000); } static void rtl8168g_disable_aldps(struct phy_device *phydev) { phy_modify_paged(phydev, 0x0a43, 0x10, BIT(2), 0); } static void rtl8168g_enable_gphy_10m(struct phy_device *phydev) { phy_modify_paged(phydev, 0x0a44, 0x11, 0, BIT(11)); } static void rtl8168g_phy_adjust_10m_aldps(struct phy_device *phydev) { phy_modify_paged(phydev, 0x0bcc, 0x14, BIT(8), 0); phy_modify_paged(phydev, 0x0a44, 0x11, 0, BIT(7) | BIT(6)); r8168g_phy_param(phydev, 0x8084, 0x6000, 0x0000); phy_modify_paged(phydev, 0x0a43, 0x10, 0x0000, 0x1003); } static void rtl8168g_1_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { int ret; r8169_apply_firmware(tp); ret = phy_read_paged(phydev, 0x0a46, 0x10); if (ret & BIT(8)) phy_modify_paged(phydev, 0x0bcc, 0x12, BIT(15), 0); else phy_modify_paged(phydev, 0x0bcc, 0x12, 0, BIT(15)); ret = phy_read_paged(phydev, 0x0a46, 0x13); if (ret & BIT(8)) phy_modify_paged(phydev, 0x0c41, 0x15, 0, BIT(1)); else phy_modify_paged(phydev, 0x0c41, 0x15, BIT(1), 0); /* Enable PHY auto speed down */ phy_modify_paged(phydev, 0x0a44, 0x11, 0, BIT(3) | BIT(2)); rtl8168g_phy_adjust_10m_aldps(phydev); /* EEE auto-fallback function */ phy_modify_paged(phydev, 0x0a4b, 0x11, 0, BIT(2)); /* Enable UC LPF tune function */ r8168g_phy_param(phydev, 0x8012, 0x0000, 0x8000); phy_modify_paged(phydev, 0x0c42, 0x11, BIT(13), BIT(14)); /* Improve SWR Efficiency */ phy_write(phydev, 0x1f, 0x0bcd); phy_write(phydev, 0x14, 0x5065); phy_write(phydev, 0x14, 0xd065); phy_write(phydev, 0x1f, 0x0bc8); phy_write(phydev, 0x11, 0x5655); phy_write(phydev, 0x1f, 0x0bcd); phy_write(phydev, 0x14, 0x1065); phy_write(phydev, 0x14, 0x9065); phy_write(phydev, 0x14, 0x1065); phy_write(phydev, 0x1f, 0x0000); rtl8168g_disable_aldps(phydev); rtl8168g_config_eee_phy(phydev); } static void rtl8168g_2_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { r8169_apply_firmware(tp); rtl8168g_config_eee_phy(phydev); } static void rtl8168h_2_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { u16 ioffset, rlen; u32 data; r8169_apply_firmware(tp); /* CHIN EST parameter update */ r8168g_phy_param(phydev, 0x808a, 0x003f, 0x000a); /* enable R-tune & PGA-retune function */ r8168g_phy_param(phydev, 0x0811, 0x0000, 0x0800); phy_modify_paged(phydev, 0x0a42, 0x16, 0x0000, 0x0002); rtl8168g_enable_gphy_10m(phydev); ioffset = rtl8168h_2_get_adc_bias_ioffset(tp); if (ioffset != 0xffff) phy_write_paged(phydev, 0x0bcf, 0x16, ioffset); /* Modify rlen (TX LPF corner frequency) level */ data = phy_read_paged(phydev, 0x0bcd, 0x16); data &= 0x000f; rlen = 0; if (data > 3) rlen = data - 3; data = rlen | (rlen << 4) | (rlen << 8) | (rlen << 12); phy_write_paged(phydev, 0x0bcd, 0x17, data); /* disable phy pfm mode */ phy_modify_paged(phydev, 0x0a44, 0x11, BIT(7), 0); /* disable 10m pll off */ phy_modify_paged(phydev, 0x0a43, 0x10, BIT(0), 0); rtl8168g_disable_aldps(phydev); rtl8168g_config_eee_phy(phydev); } static void rtl8168ep_2_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { rtl8168g_phy_adjust_10m_aldps(phydev); /* Enable UC LPF tune function */ r8168g_phy_param(phydev, 0x8012, 0x0000, 0x8000); /* Set rg_sel_sdm_rate */ phy_modify_paged(phydev, 0x0c42, 0x11, BIT(13), BIT(14)); /* Channel estimation parameters */ r8168g_phy_param(phydev, 0x80f3, 0xff00, 0x8b00); r8168g_phy_param(phydev, 0x80f0, 0xff00, 0x3a00); r8168g_phy_param(phydev, 0x80ef, 0xff00, 0x0500); r8168g_phy_param(phydev, 0x80f6, 0xff00, 0x6e00); r8168g_phy_param(phydev, 0x80ec, 0xff00, 0x6800); r8168g_phy_param(phydev, 0x80ed, 0xff00, 0x7c00); r8168g_phy_param(phydev, 0x80f2, 0xff00, 0xf400); r8168g_phy_param(phydev, 0x80f4, 0xff00, 0x8500); r8168g_phy_param(phydev, 0x8110, 0xff00, 0xa800); r8168g_phy_param(phydev, 0x810f, 0xff00, 0x1d00); r8168g_phy_param(phydev, 0x8111, 0xff00, 0xf500); r8168g_phy_param(phydev, 0x8113, 0xff00, 0x6100); r8168g_phy_param(phydev, 0x8115, 0xff00, 0x9200); r8168g_phy_param(phydev, 0x810e, 0xff00, 0x0400); r8168g_phy_param(phydev, 0x810c, 0xff00, 0x7c00); r8168g_phy_param(phydev, 0x810b, 0xff00, 0x5a00); r8168g_phy_param(phydev, 0x80d1, 0xff00, 0xff00); r8168g_phy_param(phydev, 0x80cd, 0xff00, 0x9e00); r8168g_phy_param(phydev, 0x80d3, 0xff00, 0x0e00); r8168g_phy_param(phydev, 0x80d5, 0xff00, 0xca00); r8168g_phy_param(phydev, 0x80d7, 0xff00, 0x8400); /* Force PWM-mode */ phy_write(phydev, 0x1f, 0x0bcd); phy_write(phydev, 0x14, 0x5065); phy_write(phydev, 0x14, 0xd065); phy_write(phydev, 0x1f, 0x0bc8); phy_write(phydev, 0x12, 0x00ed); phy_write(phydev, 0x1f, 0x0bcd); phy_write(phydev, 0x14, 0x1065); phy_write(phydev, 0x14, 0x9065); phy_write(phydev, 0x14, 0x1065); phy_write(phydev, 0x1f, 0x0000); rtl8168g_disable_aldps(phydev); rtl8168g_config_eee_phy(phydev); } static void rtl8117_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { /* CHN EST parameters adjust - fnet */ r8168g_phy_param(phydev, 0x808e, 0xff00, 0x4800); r8168g_phy_param(phydev, 0x8090, 0xff00, 0xcc00); r8168g_phy_param(phydev, 0x8092, 0xff00, 0xb000); r8168g_phy_param(phydev, 0x8088, 0xff00, 0x6000); r8168g_phy_param(phydev, 0x808b, 0x3f00, 0x0b00); r8168g_phy_param(phydev, 0x808d, 0x1f00, 0x0600); r8168g_phy_param(phydev, 0x808c, 0xff00, 0xb000); r8168g_phy_param(phydev, 0x80a0, 0xff00, 0x2800); r8168g_phy_param(phydev, 0x80a2, 0xff00, 0x5000); r8168g_phy_param(phydev, 0x809b, 0xf800, 0xb000); r8168g_phy_param(phydev, 0x809a, 0xff00, 0x4b00); r8168g_phy_param(phydev, 0x809d, 0x3f00, 0x0800); r8168g_phy_param(phydev, 0x80a1, 0xff00, 0x7000); r8168g_phy_param(phydev, 0x809f, 0x1f00, 0x0300); r8168g_phy_param(phydev, 0x809e, 0xff00, 0x8800); r8168g_phy_param(phydev, 0x80b2, 0xff00, 0x2200); r8168g_phy_param(phydev, 0x80ad, 0xf800, 0x9800); r8168g_phy_param(phydev, 0x80af, 0x3f00, 0x0800); r8168g_phy_param(phydev, 0x80b3, 0xff00, 0x6f00); r8168g_phy_param(phydev, 0x80b1, 0x1f00, 0x0300); r8168g_phy_param(phydev, 0x80b0, 0xff00, 0x9300); r8168g_phy_param(phydev, 0x8011, 0x0000, 0x0800); rtl8168g_enable_gphy_10m(phydev); r8168g_phy_param(phydev, 0x8016, 0x0000, 0x0400); rtl8168g_disable_aldps(phydev); rtl8168h_config_eee_phy(phydev); } static void rtl8102e_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { static const struct phy_reg phy_reg_init[] = { { 0x1f, 0x0003 }, { 0x08, 0x441d }, { 0x01, 0x9100 }, { 0x1f, 0x0000 } }; phy_set_bits(phydev, 0x11, BIT(12)); phy_set_bits(phydev, 0x19, BIT(13)); phy_set_bits(phydev, 0x10, BIT(15)); rtl_writephy_batch(phydev, phy_reg_init); } static void rtl8401_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { phy_set_bits(phydev, 0x11, BIT(12)); phy_modify_paged(phydev, 0x0002, 0x0f, 0x0000, 0x0003); } static void rtl8105e_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { /* Disable ALDPS before ram code */ phy_write(phydev, 0x18, 0x0310); msleep(100); r8169_apply_firmware(tp); phy_write_paged(phydev, 0x0005, 0x1a, 0x0000); phy_write_paged(phydev, 0x0004, 0x1c, 0x0000); phy_write_paged(phydev, 0x0001, 0x15, 0x7701); } static void rtl8402_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { /* Disable ALDPS before setting firmware */ phy_write(phydev, 0x18, 0x0310); msleep(20); r8169_apply_firmware(tp); /* EEE setting */ phy_write(phydev, 0x1f, 0x0004); phy_write(phydev, 0x10, 0x401f); phy_write(phydev, 0x19, 0x7030); phy_write(phydev, 0x1f, 0x0000); } static void rtl8106e_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { static const struct phy_reg phy_reg_init[] = { { 0x1f, 0x0004 }, { 0x10, 0xc07f }, { 0x19, 0x7030 }, { 0x1f, 0x0000 } }; /* Disable ALDPS before ram code */ phy_write(phydev, 0x18, 0x0310); msleep(100); r8169_apply_firmware(tp); rtl_writephy_batch(phydev, phy_reg_init); } static void rtl8125_legacy_force_mode(struct phy_device *phydev) { phy_modify_paged(phydev, 0xa5b, 0x12, BIT(15), 0); } static void rtl8125a_2_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { int i; phy_modify_paged(phydev, 0xad4, 0x17, 0x0000, 0x0010); phy_modify_paged(phydev, 0xad1, 0x13, 0x03ff, 0x03ff); phy_modify_paged(phydev, 0xad3, 0x11, 0x003f, 0x0006); phy_modify_paged(phydev, 0xac0, 0x14, 0x1100, 0x0000); phy_modify_paged(phydev, 0xacc, 0x10, 0x0003, 0x0002); phy_modify_paged(phydev, 0xad4, 0x10, 0x00e7, 0x0044); phy_modify_paged(phydev, 0xac1, 0x12, 0x0080, 0x0000); phy_modify_paged(phydev, 0xac8, 0x10, 0x0300, 0x0000); phy_modify_paged(phydev, 0xac5, 0x17, 0x0007, 0x0002); phy_write_paged(phydev, 0xad4, 0x16, 0x00a8); phy_write_paged(phydev, 0xac5, 0x16, 0x01ff); phy_modify_paged(phydev, 0xac8, 0x15, 0x00f0, 0x0030); phy_write(phydev, 0x1f, 0x0b87); phy_write(phydev, 0x16, 0x80a2); phy_write(phydev, 0x17, 0x0153); phy_write(phydev, 0x16, 0x809c); phy_write(phydev, 0x17, 0x0153); phy_write(phydev, 0x1f, 0x0000); phy_write(phydev, 0x1f, 0x0a43); phy_write(phydev, 0x13, 0x81B3); phy_write(phydev, 0x14, 0x0043); phy_write(phydev, 0x14, 0x00A7); phy_write(phydev, 0x14, 0x00D6); phy_write(phydev, 0x14, 0x00EC); phy_write(phydev, 0x14, 0x00F6); phy_write(phydev, 0x14, 0x00FB); phy_write(phydev, 0x14, 0x00FD); phy_write(phydev, 0x14, 0x00FF); phy_write(phydev, 0x14, 0x00BB); phy_write(phydev, 0x14, 0x0058); phy_write(phydev, 0x14, 0x0029); phy_write(phydev, 0x14, 0x0013); phy_write(phydev, 0x14, 0x0009); phy_write(phydev, 0x14, 0x0004); phy_write(phydev, 0x14, 0x0002); for (i = 0; i < 25; i++) phy_write(phydev, 0x14, 0x0000); phy_write(phydev, 0x1f, 0x0000); r8168g_phy_param(phydev, 0x8257, 0xffff, 0x020F); r8168g_phy_param(phydev, 0x80ea, 0xffff, 0x7843); r8169_apply_firmware(tp); phy_modify_paged(phydev, 0xd06, 0x14, 0x0000, 0x2000); r8168g_phy_param(phydev, 0x81a2, 0x0000, 0x0100); phy_modify_paged(phydev, 0xb54, 0x16, 0xff00, 0xdb00); phy_modify_paged(phydev, 0xa45, 0x12, 0x0001, 0x0000); phy_modify_paged(phydev, 0xa5d, 0x12, 0x0000, 0x0020); phy_modify_paged(phydev, 0xad4, 0x17, 0x0010, 0x0000); phy_modify_paged(phydev, 0xa86, 0x15, 0x0001, 0x0000); rtl8168g_enable_gphy_10m(phydev); rtl8125a_config_eee_phy(phydev); } static void rtl8125b_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) { r8169_apply_firmware(tp); phy_modify_paged(phydev, 0xa44, 0x11, 0x0000, 0x0800); phy_modify_paged(phydev, 0xac4, 0x13, 0x00f0, 0x0090); phy_modify_paged(phydev, 0xad3, 0x10, 0x0003, 0x0001); phy_write(phydev, 0x1f, 0x0b87); phy_write(phydev, 0x16, 0x80f5); phy_write(phydev, 0x17, 0x760e); phy_write(phydev, 0x16, 0x8107); phy_write(phydev, 0x17, 0x360e); phy_write(phydev, 0x16, 0x8551); phy_modify(phydev, 0x17, 0xff00, 0x0800); phy_write(phydev, 0x1f, 0x0000); phy_modify_paged(phydev, 0xbf0, 0x10, 0xe000, 0xa000); phy_modify_paged(phydev, 0xbf4, 0x13, 0x0f00, 0x0300); r8168g_phy_param(phydev, 0x8044, 0xffff, 0x2417); r8168g_phy_param(phydev, 0x804a, 0xffff, 0x2417); r8168g_phy_param(phydev, 0x8050, 0xffff, 0x2417); r8168g_phy_param(phydev, 0x8056, 0xffff, 0x2417); r8168g_phy_param(phydev, 0x805c, 0xffff, 0x2417); r8168g_phy_param(phydev, 0x8062, 0xffff, 0x2417); r8168g_phy_param(phydev, 0x8068, 0xffff, 0x2417); r8168g_phy_param(phydev, 0x806e, 0xffff, 0x2417); r8168g_phy_param(phydev, 0x8074, 0xffff, 0x2417); r8168g_phy_param(phydev, 0x807a, 0xffff, 0x2417); phy_modify_paged(phydev, 0xa4c, 0x15, 0x0000, 0x0040); phy_modify_paged(phydev, 0xbf8, 0x12, 0xe000, 0xa000); rtl8125_legacy_force_mode(phydev); rtl8125b_config_eee_phy(phydev); } void r8169_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev, enum mac_version ver) { static const rtl_phy_cfg_fct phy_configs[] = { /* PCI devices. */ [RTL_GIGA_MAC_VER_02] = rtl8169s_hw_phy_config, [RTL_GIGA_MAC_VER_03] = rtl8169s_hw_phy_config, [RTL_GIGA_MAC_VER_04] = rtl8169sb_hw_phy_config, [RTL_GIGA_MAC_VER_05] = rtl8169scd_hw_phy_config, [RTL_GIGA_MAC_VER_06] = rtl8169sce_hw_phy_config, /* PCI-E devices. */ [RTL_GIGA_MAC_VER_07] = rtl8102e_hw_phy_config, [RTL_GIGA_MAC_VER_08] = rtl8102e_hw_phy_config, [RTL_GIGA_MAC_VER_09] = rtl8102e_hw_phy_config, [RTL_GIGA_MAC_VER_10] = NULL, [RTL_GIGA_MAC_VER_11] = rtl8168bb_hw_phy_config, [RTL_GIGA_MAC_VER_14] = rtl8401_hw_phy_config, [RTL_GIGA_MAC_VER_17] = rtl8168bef_hw_phy_config, [RTL_GIGA_MAC_VER_18] = rtl8168cp_1_hw_phy_config, [RTL_GIGA_MAC_VER_19] = rtl8168c_1_hw_phy_config, [RTL_GIGA_MAC_VER_20] = rtl8168c_2_hw_phy_config, [RTL_GIGA_MAC_VER_21] = rtl8168c_3_hw_phy_config, [RTL_GIGA_MAC_VER_22] = rtl8168c_3_hw_phy_config, [RTL_GIGA_MAC_VER_23] = rtl8168cp_2_hw_phy_config, [RTL_GIGA_MAC_VER_24] = rtl8168cp_2_hw_phy_config, [RTL_GIGA_MAC_VER_25] = rtl8168d_1_hw_phy_config, [RTL_GIGA_MAC_VER_26] = rtl8168d_2_hw_phy_config, [RTL_GIGA_MAC_VER_28] = rtl8168d_4_hw_phy_config, [RTL_GIGA_MAC_VER_29] = rtl8105e_hw_phy_config, [RTL_GIGA_MAC_VER_30] = rtl8105e_hw_phy_config, [RTL_GIGA_MAC_VER_31] = NULL, [RTL_GIGA_MAC_VER_32] = rtl8168e_1_hw_phy_config, [RTL_GIGA_MAC_VER_33] = rtl8168e_1_hw_phy_config, [RTL_GIGA_MAC_VER_34] = rtl8168e_2_hw_phy_config, [RTL_GIGA_MAC_VER_35] = rtl8168f_1_hw_phy_config, [RTL_GIGA_MAC_VER_36] = rtl8168f_2_hw_phy_config, [RTL_GIGA_MAC_VER_37] = rtl8402_hw_phy_config, [RTL_GIGA_MAC_VER_38] = rtl8411_hw_phy_config, [RTL_GIGA_MAC_VER_39] = rtl8106e_hw_phy_config, [RTL_GIGA_MAC_VER_40] = rtl8168g_1_hw_phy_config, [RTL_GIGA_MAC_VER_42] = rtl8168g_2_hw_phy_config, [RTL_GIGA_MAC_VER_43] = rtl8168g_2_hw_phy_config, [RTL_GIGA_MAC_VER_44] = rtl8168g_2_hw_phy_config, [RTL_GIGA_MAC_VER_46] = rtl8168h_2_hw_phy_config, [RTL_GIGA_MAC_VER_48] = rtl8168h_2_hw_phy_config, [RTL_GIGA_MAC_VER_51] = rtl8168ep_2_hw_phy_config, [RTL_GIGA_MAC_VER_52] = rtl8117_hw_phy_config, [RTL_GIGA_MAC_VER_53] = rtl8117_hw_phy_config, [RTL_GIGA_MAC_VER_61] = rtl8125a_2_hw_phy_config, [RTL_GIGA_MAC_VER_63] = rtl8125b_hw_phy_config, }; if (phy_configs[ver]) phy_configs[ver](tp, phydev); }
linux-master
drivers/net/ethernet/realtek/r8169_phy_config.c
/* atp.c: Attached (pocket) ethernet adapter driver for linux. */ /* This is a driver for commonly OEM pocket (parallel port) ethernet adapters based on the Realtek RTL8002 and RTL8012 chips. Written 1993-2000 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 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. Copyright 1993 United States Government as represented by the Director, National Security Agency. Copyright 1994-2000 retained by the original author, Donald Becker. The timer-based reset code was supplied in 1995 by Bill Carlson, [email protected]. The author may be reached as [email protected], or C/O Scyld Computing Corporation 410 Severn Ave., Suite 210 Annapolis MD 21403 Support information and updates available at http://www.scyld.com/network/atp.html Modular support/softnet added by Alan Cox. _bit abuse fixed up by Alan Cox */ static const char version[] = "atp.c:v1.09=ac 2002/10/01 Donald Becker <[email protected]>\n"; /* The user-configurable values. These may be modified when a driver module is loaded.*/ static int debug = 1; /* 1 normal messages, 0 quiet .. 7 verbose. */ #define net_debug debug /* Maximum events (Rx packets, etc.) to handle at each interrupt. */ static int max_interrupt_work = 15; #define NUM_UNITS 2 /* The standard set of ISA module parameters. */ static int io[NUM_UNITS]; static int irq[NUM_UNITS]; static int xcvr[NUM_UNITS]; /* The data transfer mode. */ /* Operational parameters that are set at compile time. */ /* Time in jiffies before concluding the transmitter is hung. */ #define TX_TIMEOUT (400*HZ/1000) /* This file is a device driver for the RealTek (aka AT-Lan-Tec) pocket ethernet adapter. This is a common low-cost OEM pocket ethernet adapter, sold under many names. Sources: This driver was written from the packet driver assembly code provided by Vincent Bono of AT-Lan-Tec. Ever try to figure out how a complicated device works just from the assembly code? It ain't pretty. The following description is written based on guesses and writing lots of special-purpose code to test my theorized operation. In 1997 Realtek made available the documentation for the second generation RTL8012 chip, which has lead to several driver improvements. http://www.realtek.com.tw/ Theory of Operation The RTL8002 adapter seems to be built around a custom spin of the SEEQ controller core. It probably has a 16K or 64K internal packet buffer, of which the first 4K is devoted to transmit and the rest to receive. The controller maintains the queue of received packet and the packet buffer access pointer internally, with only 'reset to beginning' and 'skip to next packet' commands visible. The transmit packet queue holds two (or more?) packets: both 'retransmit this packet' (due to collision) and 'transmit next packet' commands must be started by hand. The station address is stored in a standard bit-serial EEPROM which must be read (ughh) by the device driver. (Provisions have been made for substituting a 74S288 PROM, but I haven't gotten reports of any models using it.) Unlike built-in devices, a pocket adapter can temporarily lose power without indication to the device driver. The major effect is that the station address, receive filter (promiscuous, etc.) and transceiver must be reset. The controller itself has 16 registers, some of which use only the lower bits. The registers are read and written 4 bits at a time. The four bit register address is presented on the data lines along with a few additional timing and control bits. The data is then read from status port or written to the data port. Correction: the controller has two banks of 16 registers. The second bank contains only the multicast filter table (now used) and the EEPROM access registers. Since the bulk data transfer of the actual packets through the slow parallel port dominates the driver's running time, four distinct data (non-register) transfer modes are provided by the adapter, two in each direction. In the first mode timing for the nibble transfers is provided through the data port. In the second mode the same timing is provided through the control port. In either case the data is read from the status port and written to the data port, just as it is accessing registers. In addition to the basic data transfer methods, several more are modes are created by adding some delay by doing multiple reads of the data to allow it to stabilize. This delay seems to be needed on most machines. The data transfer mode is stored in the 'dev->if_port' field. Its default value is '4'. It may be overridden at boot-time using the third parameter to the "ether=..." initialization. The header file <atp.h> provides inline functions that encapsulate the register and data access methods. These functions are hand-tuned to generate reasonable object code. This header file also documents my interpretations of the device registers. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/types.h> #include <linux/fcntl.h> #include <linux/interrupt.h> #include <linux/ioport.h> #include <linux/in.h> #include <linux/string.h> #include <linux/errno.h> #include <linux/init.h> #include <linux/crc32.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/skbuff.h> #include <linux/spinlock.h> #include <linux/delay.h> #include <linux/bitops.h> #include <asm/io.h> #include <asm/dma.h> #include "atp.h" MODULE_AUTHOR("Donald Becker <[email protected]>"); MODULE_DESCRIPTION("RealTek RTL8002/8012 parallel port Ethernet driver"); MODULE_LICENSE("GPL"); module_param(max_interrupt_work, int, 0); module_param(debug, int, 0); module_param_hw_array(io, int, ioport, NULL, 0); module_param_hw_array(irq, int, irq, NULL, 0); module_param_array(xcvr, int, NULL, 0); MODULE_PARM_DESC(max_interrupt_work, "ATP maximum events handled per interrupt"); MODULE_PARM_DESC(debug, "ATP debug level (0-7)"); MODULE_PARM_DESC(io, "ATP I/O base address(es)"); MODULE_PARM_DESC(irq, "ATP IRQ number(s)"); MODULE_PARM_DESC(xcvr, "ATP transceiver(s) (0=internal, 1=external)"); /* The number of low I/O ports used by the ethercard. */ #define ETHERCARD_TOTAL_SIZE 3 /* Sequence to switch an 8012 from printer mux to ethernet mode. */ static char mux_8012[] = { 0xff, 0xf7, 0xff, 0xfb, 0xf3, 0xfb, 0xff, 0xf7,}; struct net_local { spinlock_t lock; struct net_device *next_module; struct timer_list timer; /* Media selection timer. */ struct net_device *dev; /* Timer dev. */ unsigned long last_rx_time; /* Last Rx, in jiffies, to handle Rx hang. */ int saved_tx_size; unsigned int tx_unit_busy:1; unsigned char re_tx, /* Number of packet retransmissions. */ addr_mode, /* Current Rx filter e.g. promiscuous, etc. */ pac_cnt_in_tx_buf; }; /* This code, written by [email protected], resets the adapter every TIMED_CHECKER ticks. This recovers from an unknown error which hangs the device. */ #define TIMED_CHECKER (HZ/4) #ifdef TIMED_CHECKER #include <linux/timer.h> static void atp_timed_checker(struct timer_list *t); #endif /* Index to functions, as function prototypes. */ static int atp_probe1(long ioaddr); static void get_node_ID(struct net_device *dev); static unsigned short eeprom_op(long ioaddr, unsigned int cmd); static int net_open(struct net_device *dev); static void hardware_init(struct net_device *dev); static void write_packet(long ioaddr, int length, unsigned char *packet, int pad, int mode); static void trigger_send(long ioaddr, int length); static netdev_tx_t atp_send_packet(struct sk_buff *skb, struct net_device *dev); static irqreturn_t atp_interrupt(int irq, void *dev_id); static void net_rx(struct net_device *dev); static void read_block(long ioaddr, int length, unsigned char *buffer, int data_mode); static int net_close(struct net_device *dev); static void set_rx_mode(struct net_device *dev); static void tx_timeout(struct net_device *dev, unsigned int txqueue); /* A list of all installed ATP devices, for removing the driver module. */ static struct net_device *root_atp_dev; /* Check for a network adapter of this type, and return '0' iff one exists. If dev->base_addr == 0, probe all likely locations. If dev->base_addr == 1, always return failure. If dev->base_addr == 2, allocate space for the device and return success (detachable devices only). FIXME: we should use the parport layer for this */ static int __init atp_init(void) { int *port, ports[] = {0x378, 0x278, 0x3bc, 0}; int base_addr = io[0]; if (base_addr > 0x1ff) /* Check a single specified location. */ return atp_probe1(base_addr); else if (base_addr == 1) /* Don't probe at all. */ return -ENXIO; for (port = ports; *port; port++) { long ioaddr = *port; outb(0x57, ioaddr + PAR_DATA); if (inb(ioaddr + PAR_DATA) != 0x57) continue; if (atp_probe1(ioaddr) == 0) return 0; } return -ENODEV; } static const struct net_device_ops atp_netdev_ops = { .ndo_open = net_open, .ndo_stop = net_close, .ndo_start_xmit = atp_send_packet, .ndo_set_rx_mode = set_rx_mode, .ndo_tx_timeout = tx_timeout, .ndo_set_mac_address = eth_mac_addr, .ndo_validate_addr = eth_validate_addr, }; static int __init atp_probe1(long ioaddr) { struct net_device *dev = NULL; struct net_local *lp; int saved_ctrl_reg, status, i; int res; outb(0xff, ioaddr + PAR_DATA); /* Save the original value of the Control register, in case we guessed wrong. */ saved_ctrl_reg = inb(ioaddr + PAR_CONTROL); if (net_debug > 3) printk("atp: Control register was %#2.2x.\n", saved_ctrl_reg); /* IRQEN=0, SLCTB=high INITB=high, AUTOFDB=high, STBB=high. */ outb(0x04, ioaddr + PAR_CONTROL); #ifndef final_version if (net_debug > 3) { /* Turn off the printer multiplexer on the 8012. */ for (i = 0; i < 8; i++) outb(mux_8012[i], ioaddr + PAR_DATA); write_reg(ioaddr, MODSEL, 0x00); printk("atp: Registers are "); for (i = 0; i < 32; i++) printk(" %2.2x", read_nibble(ioaddr, i)); printk(".\n"); } #endif /* Turn off the printer multiplexer on the 8012. */ for (i = 0; i < 8; i++) outb(mux_8012[i], ioaddr + PAR_DATA); write_reg_high(ioaddr, CMR1, CMR1h_RESET); /* udelay() here? */ status = read_nibble(ioaddr, CMR1); if (net_debug > 3) { printk(KERN_DEBUG "atp: Status nibble was %#2.2x..", status); for (i = 0; i < 32; i++) printk(" %2.2x", read_nibble(ioaddr, i)); printk("\n"); } if ((status & 0x78) != 0x08) { /* The pocket adapter probe failed, restore the control register. */ outb(saved_ctrl_reg, ioaddr + PAR_CONTROL); return -ENODEV; } status = read_nibble(ioaddr, CMR2_h); if ((status & 0x78) != 0x10) { outb(saved_ctrl_reg, ioaddr + PAR_CONTROL); return -ENODEV; } dev = alloc_etherdev(sizeof(struct net_local)); if (!dev) return -ENOMEM; /* Find the IRQ used by triggering an interrupt. */ write_reg_byte(ioaddr, CMR2, 0x01); /* No accept mode, IRQ out. */ write_reg_high(ioaddr, CMR1, CMR1h_RxENABLE | CMR1h_TxENABLE); /* Enable Tx and Rx. */ /* Omit autoIRQ routine for now. Use "table lookup" instead. Uhgggh. */ if (irq[0]) dev->irq = irq[0]; else if (ioaddr == 0x378) dev->irq = 7; else dev->irq = 5; write_reg_high(ioaddr, CMR1, CMR1h_TxRxOFF); /* Disable Tx and Rx units. */ write_reg(ioaddr, CMR2, CMR2_NULL); dev->base_addr = ioaddr; /* Read the station address PROM. */ get_node_ID(dev); #ifndef MODULE if (net_debug) printk(KERN_INFO "%s", version); #endif printk(KERN_NOTICE "%s: Pocket adapter found at %#3lx, IRQ %d, " "SAPROM %pM.\n", dev->name, dev->base_addr, dev->irq, dev->dev_addr); /* Reset the ethernet hardware and activate the printer pass-through. */ write_reg_high(ioaddr, CMR1, CMR1h_RESET | CMR1h_MUX); lp = netdev_priv(dev); lp->addr_mode = CMR2h_Normal; spin_lock_init(&lp->lock); /* For the ATP adapter the "if_port" is really the data transfer mode. */ if (xcvr[0]) dev->if_port = xcvr[0]; else dev->if_port = (dev->mem_start & 0xf) ? (dev->mem_start & 0x7) : 4; if (dev->mem_end & 0xf) net_debug = dev->mem_end & 7; dev->netdev_ops = &atp_netdev_ops; dev->watchdog_timeo = TX_TIMEOUT; res = register_netdev(dev); if (res) { free_netdev(dev); return res; } lp->next_module = root_atp_dev; root_atp_dev = dev; return 0; } /* Read the station address PROM, usually a word-wide EEPROM. */ static void __init get_node_ID(struct net_device *dev) { long ioaddr = dev->base_addr; __be16 addr[ETH_ALEN / 2]; int sa_offset = 0; int i; write_reg(ioaddr, CMR2, CMR2_EEPROM); /* Point to the EEPROM control registers. */ /* Some adapters have the station address at offset 15 instead of offset zero. Check for it, and fix it if needed. */ if (eeprom_op(ioaddr, EE_READ(0)) == 0xffff) sa_offset = 15; for (i = 0; i < 3; i++) addr[i] = cpu_to_be16(eeprom_op(ioaddr, EE_READ(sa_offset + i))); eth_hw_addr_set(dev, (u8 *)addr); write_reg(ioaddr, CMR2, CMR2_NULL); } /* An EEPROM read command starts by shifting out 0x60+address, and then shifting in the serial data. See the NatSemi databook for details. * ________________ * CS : __| * ___ ___ * CLK: ______| |___| | * __ _______ _______ * DI : __X_______X_______X * DO : _________X_______X */ static unsigned short __init eeprom_op(long ioaddr, u32 cmd) { unsigned eedata_out = 0; int num_bits = EE_CMD_SIZE; while (--num_bits >= 0) { char outval = (cmd & (1<<num_bits)) ? EE_DATA_WRITE : 0; write_reg_high(ioaddr, PROM_CMD, outval | EE_CLK_LOW); write_reg_high(ioaddr, PROM_CMD, outval | EE_CLK_HIGH); eedata_out <<= 1; if (read_nibble(ioaddr, PROM_DATA) & EE_DATA_READ) eedata_out++; } write_reg_high(ioaddr, PROM_CMD, EE_CLK_LOW & ~EE_CS); return eedata_out; } /* Open/initialize the board. This is called (in the current kernel) sometime after booting when the 'ifconfig' program is run. This routine sets everything up anew at each open, even registers that "should" only need to be set once at boot, so that there is non-reboot way to recover if something goes wrong. This is an attachable device: if there is no private entry then it wasn't probed for at boot-time, and we need to probe for it again. */ static int net_open(struct net_device *dev) { struct net_local *lp = netdev_priv(dev); int ret; /* The interrupt line is turned off (tri-stated) when the device isn't in use. That's especially important for "attached" interfaces where the port or interrupt may be shared. */ ret = request_irq(dev->irq, atp_interrupt, 0, dev->name, dev); if (ret) return ret; hardware_init(dev); lp->dev = dev; timer_setup(&lp->timer, atp_timed_checker, 0); lp->timer.expires = jiffies + TIMED_CHECKER; add_timer(&lp->timer); netif_start_queue(dev); return 0; } /* This routine resets the hardware. We initialize everything, assuming that the hardware may have been temporarily detached. */ static void hardware_init(struct net_device *dev) { struct net_local *lp = netdev_priv(dev); long ioaddr = dev->base_addr; int i; /* Turn off the printer multiplexer on the 8012. */ for (i = 0; i < 8; i++) outb(mux_8012[i], ioaddr + PAR_DATA); write_reg_high(ioaddr, CMR1, CMR1h_RESET); for (i = 0; i < 6; i++) write_reg_byte(ioaddr, PAR0 + i, dev->dev_addr[i]); write_reg_high(ioaddr, CMR2, lp->addr_mode); if (net_debug > 2) { printk(KERN_DEBUG "%s: Reset: current Rx mode %d.\n", dev->name, (read_nibble(ioaddr, CMR2_h) >> 3) & 0x0f); } write_reg(ioaddr, CMR2, CMR2_IRQOUT); write_reg_high(ioaddr, CMR1, CMR1h_RxENABLE | CMR1h_TxENABLE); /* Enable the interrupt line from the serial port. */ outb(Ctrl_SelData + Ctrl_IRQEN, ioaddr + PAR_CONTROL); /* Unmask the interesting interrupts. */ write_reg(ioaddr, IMR, ISR_RxOK | ISR_TxErr | ISR_TxOK); write_reg_high(ioaddr, IMR, ISRh_RxErr); lp->tx_unit_busy = 0; lp->pac_cnt_in_tx_buf = 0; lp->saved_tx_size = 0; } static void trigger_send(long ioaddr, int length) { write_reg_byte(ioaddr, TxCNT0, length & 0xff); write_reg(ioaddr, TxCNT1, length >> 8); write_reg(ioaddr, CMR1, CMR1_Xmit); } static void write_packet(long ioaddr, int length, unsigned char *packet, int pad_len, int data_mode) { if (length & 1) { length++; pad_len++; } outb(EOC+MAR, ioaddr + PAR_DATA); if ((data_mode & 1) == 0) { /* Write the packet out, starting with the write addr. */ outb(WrAddr+MAR, ioaddr + PAR_DATA); do { write_byte_mode0(ioaddr, *packet++); } while (--length > pad_len) ; do { write_byte_mode0(ioaddr, 0); } while (--length > 0) ; } else { /* Write the packet out in slow mode. */ unsigned char outbyte = *packet++; outb(Ctrl_LNibWrite + Ctrl_IRQEN, ioaddr + PAR_CONTROL); outb(WrAddr+MAR, ioaddr + PAR_DATA); outb((outbyte & 0x0f)|0x40, ioaddr + PAR_DATA); outb(outbyte & 0x0f, ioaddr + PAR_DATA); outbyte >>= 4; outb(outbyte & 0x0f, ioaddr + PAR_DATA); outb(Ctrl_HNibWrite + Ctrl_IRQEN, ioaddr + PAR_CONTROL); while (--length > pad_len) write_byte_mode1(ioaddr, *packet++); while (--length > 0) write_byte_mode1(ioaddr, 0); } /* Terminate the Tx frame. End of write: ECB. */ outb(0xff, ioaddr + PAR_DATA); outb(Ctrl_HNibWrite | Ctrl_SelData | Ctrl_IRQEN, ioaddr + PAR_CONTROL); } static void tx_timeout(struct net_device *dev, unsigned int txqueue) { long ioaddr = dev->base_addr; printk(KERN_WARNING "%s: Transmit timed out, %s?\n", dev->name, inb(ioaddr + PAR_CONTROL) & 0x10 ? "network cable problem" : "IRQ conflict"); dev->stats.tx_errors++; /* Try to restart the adapter. */ hardware_init(dev); netif_trans_update(dev); /* prevent tx timeout */ netif_wake_queue(dev); dev->stats.tx_errors++; } static netdev_tx_t atp_send_packet(struct sk_buff *skb, struct net_device *dev) { struct net_local *lp = netdev_priv(dev); long ioaddr = dev->base_addr; int length; unsigned long flags; length = ETH_ZLEN < skb->len ? skb->len : ETH_ZLEN; netif_stop_queue(dev); /* Disable interrupts by writing 0x00 to the Interrupt Mask Register. This sequence must not be interrupted by an incoming packet. */ spin_lock_irqsave(&lp->lock, flags); write_reg(ioaddr, IMR, 0); write_reg_high(ioaddr, IMR, 0); spin_unlock_irqrestore(&lp->lock, flags); write_packet(ioaddr, length, skb->data, length-skb->len, dev->if_port); lp->pac_cnt_in_tx_buf++; if (lp->tx_unit_busy == 0) { trigger_send(ioaddr, length); lp->saved_tx_size = 0; /* Redundant */ lp->re_tx = 0; lp->tx_unit_busy = 1; } else lp->saved_tx_size = length; /* Re-enable the LPT interrupts. */ write_reg(ioaddr, IMR, ISR_RxOK | ISR_TxErr | ISR_TxOK); write_reg_high(ioaddr, IMR, ISRh_RxErr); dev_kfree_skb (skb); return NETDEV_TX_OK; } /* The typical workload of the driver: Handle the network interface interrupts. */ static irqreturn_t atp_interrupt(int irq, void *dev_instance) { struct net_device *dev = dev_instance; struct net_local *lp; long ioaddr; static int num_tx_since_rx; int boguscount = max_interrupt_work; int handled = 0; ioaddr = dev->base_addr; lp = netdev_priv(dev); spin_lock(&lp->lock); /* Disable additional spurious interrupts. */ outb(Ctrl_SelData, ioaddr + PAR_CONTROL); /* The adapter's output is currently the IRQ line, switch it to data. */ write_reg(ioaddr, CMR2, CMR2_NULL); write_reg(ioaddr, IMR, 0); if (net_debug > 5) printk(KERN_DEBUG "%s: In interrupt ", dev->name); while (--boguscount > 0) { int status = read_nibble(ioaddr, ISR); if (net_debug > 5) printk("loop status %02x..", status); if (status & (ISR_RxOK<<3)) { handled = 1; write_reg(ioaddr, ISR, ISR_RxOK); /* Clear the Rx interrupt. */ do { int read_status = read_nibble(ioaddr, CMR1); if (net_debug > 6) printk("handling Rx packet %02x..", read_status); /* We acknowledged the normal Rx interrupt, so if the interrupt is still outstanding we must have a Rx error. */ if (read_status & (CMR1_IRQ << 3)) { /* Overrun. */ dev->stats.rx_over_errors++; /* Set to no-accept mode long enough to remove a packet. */ write_reg_high(ioaddr, CMR2, CMR2h_OFF); net_rx(dev); /* Clear the interrupt and return to normal Rx mode. */ write_reg_high(ioaddr, ISR, ISRh_RxErr); write_reg_high(ioaddr, CMR2, lp->addr_mode); } else if ((read_status & (CMR1_BufEnb << 3)) == 0) { net_rx(dev); num_tx_since_rx = 0; } else break; } while (--boguscount > 0); } else if (status & ((ISR_TxErr + ISR_TxOK)<<3)) { handled = 1; if (net_debug > 6) printk("handling Tx done.."); /* Clear the Tx interrupt. We should check for too many failures and reinitialize the adapter. */ write_reg(ioaddr, ISR, ISR_TxErr + ISR_TxOK); if (status & (ISR_TxErr<<3)) { dev->stats.collisions++; if (++lp->re_tx > 15) { dev->stats.tx_aborted_errors++; hardware_init(dev); break; } /* Attempt to retransmit. */ if (net_debug > 6) printk("attempting to ReTx"); write_reg(ioaddr, CMR1, CMR1_ReXmit + CMR1_Xmit); } else { /* Finish up the transmit. */ dev->stats.tx_packets++; lp->pac_cnt_in_tx_buf--; if ( lp->saved_tx_size) { trigger_send(ioaddr, lp->saved_tx_size); lp->saved_tx_size = 0; lp->re_tx = 0; } else lp->tx_unit_busy = 0; netif_wake_queue(dev); /* Inform upper layers. */ } num_tx_since_rx++; } else if (num_tx_since_rx > 8 && time_after(jiffies, lp->last_rx_time + HZ)) { if (net_debug > 2) printk(KERN_DEBUG "%s: Missed packet? No Rx after %d Tx and " "%ld jiffies status %02x CMR1 %02x.\n", dev->name, num_tx_since_rx, jiffies - lp->last_rx_time, status, (read_nibble(ioaddr, CMR1) >> 3) & 15); dev->stats.rx_missed_errors++; hardware_init(dev); num_tx_since_rx = 0; break; } else break; } /* This following code fixes a rare (and very difficult to track down) problem where the adapter forgets its ethernet address. */ { int i; for (i = 0; i < 6; i++) write_reg_byte(ioaddr, PAR0 + i, dev->dev_addr[i]); #if 0 && defined(TIMED_CHECKER) mod_timer(&lp->timer, jiffies + TIMED_CHECKER); #endif } /* Tell the adapter that it can go back to using the output line as IRQ. */ write_reg(ioaddr, CMR2, CMR2_IRQOUT); /* Enable the physical interrupt line, which is sure to be low until.. */ outb(Ctrl_SelData + Ctrl_IRQEN, ioaddr + PAR_CONTROL); /* .. we enable the interrupt sources. */ write_reg(ioaddr, IMR, ISR_RxOK | ISR_TxErr | ISR_TxOK); write_reg_high(ioaddr, IMR, ISRh_RxErr); /* Hmmm, really needed? */ spin_unlock(&lp->lock); if (net_debug > 5) printk("exiting interrupt.\n"); return IRQ_RETVAL(handled); } #ifdef TIMED_CHECKER /* This following code fixes a rare (and very difficult to track down) problem where the adapter forgets its ethernet address. */ static void atp_timed_checker(struct timer_list *t) { struct net_local *lp = from_timer(lp, t, timer); struct net_device *dev = lp->dev; long ioaddr = dev->base_addr; int tickssofar = jiffies - lp->last_rx_time; int i; spin_lock(&lp->lock); if (tickssofar > 2*HZ) { #if 1 for (i = 0; i < 6; i++) write_reg_byte(ioaddr, PAR0 + i, dev->dev_addr[i]); lp->last_rx_time = jiffies; #else for (i = 0; i < 6; i++) if (read_cmd_byte(ioaddr, PAR0 + i) != atp_timed_dev->dev_addr[i]) { struct net_local *lp = netdev_priv(atp_timed_dev); write_reg_byte(ioaddr, PAR0 + i, atp_timed_dev->dev_addr[i]); if (i == 2) dev->stats.tx_errors++; else if (i == 3) dev->stats.tx_dropped++; else if (i == 4) dev->stats.collisions++; else dev->stats.rx_errors++; } #endif } spin_unlock(&lp->lock); lp->timer.expires = jiffies + TIMED_CHECKER; add_timer(&lp->timer); } #endif /* We have a good packet(s), get it/them out of the buffers. */ static void net_rx(struct net_device *dev) { struct net_local *lp = netdev_priv(dev); long ioaddr = dev->base_addr; struct rx_header rx_head; /* Process the received packet. */ outb(EOC+MAR, ioaddr + PAR_DATA); read_block(ioaddr, 8, (unsigned char*)&rx_head, dev->if_port); if (net_debug > 5) printk(KERN_DEBUG " rx_count %04x %04x %04x %04x..", rx_head.pad, rx_head.rx_count, rx_head.rx_status, rx_head.cur_addr); if ((rx_head.rx_status & 0x77) != 0x01) { dev->stats.rx_errors++; if (rx_head.rx_status & 0x0004) dev->stats.rx_frame_errors++; else if (rx_head.rx_status & 0x0002) dev->stats.rx_crc_errors++; if (net_debug > 3) printk(KERN_DEBUG "%s: Unknown ATP Rx error %04x.\n", dev->name, rx_head.rx_status); if (rx_head.rx_status & 0x0020) { dev->stats.rx_fifo_errors++; write_reg_high(ioaddr, CMR1, CMR1h_TxENABLE); write_reg_high(ioaddr, CMR1, CMR1h_RxENABLE | CMR1h_TxENABLE); } else if (rx_head.rx_status & 0x0050) hardware_init(dev); return; } else { /* Malloc up new buffer. The "-4" omits the FCS (CRC). */ int pkt_len = (rx_head.rx_count & 0x7ff) - 4; struct sk_buff *skb; skb = netdev_alloc_skb(dev, pkt_len + 2); if (skb == NULL) { dev->stats.rx_dropped++; goto done; } skb_reserve(skb, 2); /* Align IP on 16 byte boundaries */ read_block(ioaddr, pkt_len, skb_put(skb,pkt_len), dev->if_port); skb->protocol = eth_type_trans(skb, dev); netif_rx(skb); dev->stats.rx_packets++; dev->stats.rx_bytes += pkt_len; } done: write_reg(ioaddr, CMR1, CMR1_NextPkt); lp->last_rx_time = jiffies; } static void read_block(long ioaddr, int length, unsigned char *p, int data_mode) { if (data_mode <= 3) { /* Mode 0 or 1 */ outb(Ctrl_LNibRead, ioaddr + PAR_CONTROL); outb(length == 8 ? RdAddr | HNib | MAR : RdAddr | MAR, ioaddr + PAR_DATA); if (data_mode <= 1) { /* Mode 0 or 1 */ do { *p++ = read_byte_mode0(ioaddr); } while (--length > 0); } else { /* Mode 2 or 3 */ do { *p++ = read_byte_mode2(ioaddr); } while (--length > 0); } } else if (data_mode <= 5) { do { *p++ = read_byte_mode4(ioaddr); } while (--length > 0); } else { do { *p++ = read_byte_mode6(ioaddr); } while (--length > 0); } outb(EOC+HNib+MAR, ioaddr + PAR_DATA); outb(Ctrl_SelData, ioaddr + PAR_CONTROL); } /* The inverse routine to net_open(). */ static int net_close(struct net_device *dev) { struct net_local *lp = netdev_priv(dev); long ioaddr = dev->base_addr; netif_stop_queue(dev); del_timer_sync(&lp->timer); /* Flush the Tx and disable Rx here. */ lp->addr_mode = CMR2h_OFF; write_reg_high(ioaddr, CMR2, CMR2h_OFF); /* Free the IRQ line. */ outb(0x00, ioaddr + PAR_CONTROL); free_irq(dev->irq, dev); /* Reset the ethernet hardware and activate the printer pass-through. */ write_reg_high(ioaddr, CMR1, CMR1h_RESET | CMR1h_MUX); return 0; } /* * Set or clear the multicast filter for this adapter. */ static void set_rx_mode(struct net_device *dev) { struct net_local *lp = netdev_priv(dev); long ioaddr = dev->base_addr; if (!netdev_mc_empty(dev) || (dev->flags & (IFF_ALLMULTI|IFF_PROMISC))) lp->addr_mode = CMR2h_PROMISC; else lp->addr_mode = CMR2h_Normal; write_reg_high(ioaddr, CMR2, lp->addr_mode); } static int __init atp_init_module(void) { if (debug) /* Emit version even if no cards detected. */ printk(KERN_INFO "%s", version); return atp_init(); } static void __exit atp_cleanup_module(void) { struct net_device *next_dev; while (root_atp_dev) { struct net_local *atp_local = netdev_priv(root_atp_dev); next_dev = atp_local->next_module; unregister_netdev(root_atp_dev); /* No need to release_region(), since we never snarf it. */ free_netdev(root_atp_dev); root_atp_dev = next_dev; } } module_init(atp_init_module); module_exit(atp_cleanup_module);
linux-master
drivers/net/ethernet/realtek/atp.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 1999 - 2006 Intel Corporation. */ /* * e100.c: Intel(R) PRO/100 ethernet driver * * (Re)written 2003 by [email protected]. Based loosely on * original e100 driver, but better described as a munging of * e100, e1000, eepro100, tg3, 8139cp, and other drivers. * * References: * Intel 8255x 10/100 Mbps Ethernet Controller Family, * Open Source Software Developers Manual, * http://sourceforge.net/projects/e1000 * * * Theory of Operation * * I. General * * The driver supports Intel(R) 10/100 Mbps PCI Fast Ethernet * controller family, which includes the 82557, 82558, 82559, 82550, * 82551, and 82562 devices. 82558 and greater controllers * integrate the Intel 82555 PHY. The controllers are used in * server and client network interface cards, as well as in * LAN-On-Motherboard (LOM), CardBus, MiniPCI, and ICHx * configurations. 8255x supports a 32-bit linear addressing * mode and operates at 33Mhz PCI clock rate. * * II. Driver Operation * * Memory-mapped mode is used exclusively to access the device's * shared-memory structure, the Control/Status Registers (CSR). All * setup, configuration, and control of the device, including queuing * of Tx, Rx, and configuration commands is through the CSR. * cmd_lock serializes accesses to the CSR command register. cb_lock * protects the shared Command Block List (CBL). * * 8255x is highly MII-compliant and all access to the PHY go * through the Management Data Interface (MDI). Consequently, the * driver leverages the mii.c library shared with other MII-compliant * devices. * * Big- and Little-Endian byte order as well as 32- and 64-bit * archs are supported. Weak-ordered memory and non-cache-coherent * archs are supported. * * III. Transmit * * A Tx skb is mapped and hangs off of a TCB. TCBs are linked * together in a fixed-size ring (CBL) thus forming the flexible mode * memory structure. A TCB marked with the suspend-bit indicates * the end of the ring. The last TCB processed suspends the * controller, and the controller can be restarted by issue a CU * resume command to continue from the suspend point, or a CU start * command to start at a given position in the ring. * * Non-Tx commands (config, multicast setup, etc) are linked * into the CBL ring along with Tx commands. The common structure * used for both Tx and non-Tx commands is the Command Block (CB). * * cb_to_use is the next CB to use for queuing a command; cb_to_clean * is the next CB to check for completion; cb_to_send is the first * CB to start on in case of a previous failure to resume. CB clean * up happens in interrupt context in response to a CU interrupt. * cbs_avail keeps track of number of free CB resources available. * * Hardware padding of short packets to minimum packet size is * enabled. 82557 pads with 7Eh, while the later controllers pad * with 00h. * * IV. Receive * * The Receive Frame Area (RFA) comprises a ring of Receive Frame * Descriptors (RFD) + data buffer, thus forming the simplified mode * memory structure. Rx skbs are allocated to contain both the RFD * and the data buffer, but the RFD is pulled off before the skb is * indicated. The data buffer is aligned such that encapsulated * protocol headers are u32-aligned. Since the RFD is part of the * mapped shared memory, and completion status is contained within * the RFD, the RFD must be dma_sync'ed to maintain a consistent * view from software and hardware. * * In order to keep updates to the RFD link field from colliding with * hardware writes to mark packets complete, we use the feature that * hardware will not write to a size 0 descriptor and mark the previous * packet as end-of-list (EL). After updating the link, we remove EL * and only then restore the size such that hardware may use the * previous-to-end RFD. * * Under typical operation, the receive unit (RU) is start once, * and the controller happily fills RFDs as frames arrive. If * replacement RFDs cannot be allocated, or the RU goes non-active, * the RU must be restarted. Frame arrival generates an interrupt, * and Rx indication and re-allocation happen in the same context, * therefore no locking is required. A software-generated interrupt * is generated from the watchdog to recover from a failed allocation * scenario where all Rx resources have been indicated and none re- * placed. * * V. Miscellaneous * * VLAN offloading of tagging, stripping and filtering is not * supported, but driver will accommodate the extra 4-byte VLAN tag * for processing by upper layers. Tx/Rx Checksum offloading is not * supported. Tx Scatter/Gather is not supported. Jumbo Frames is * not supported (hardware limitation). * * MagicPacket(tm) WoL support is enabled/disabled via ethtool. * * Thanks to JC ([email protected]) for helping with * testing/troubleshooting the development driver. * * TODO: * o several entry points race with dev->close * o check for tx-no-resources/stop Q races with tx clean/wake Q * * FIXES: * 2005/12/02 - Michael O'Donnell <Michael.ODonnell at stratus dot com> * - Stratus87247: protect MDI control register manipulations * 2009/06/01 - Andreas Mohr <andi at lisas dot de> * - add clean lowlevel I/O emulation for cards with MII-lacking PHYs */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/hardirq.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/init.h> #include <linux/pci.h> #include <linux/dma-mapping.h> #include <linux/dmapool.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/mii.h> #include <linux/if_vlan.h> #include <linux/skbuff.h> #include <linux/ethtool.h> #include <linux/string.h> #include <linux/firmware.h> #include <linux/rtnetlink.h> #include <asm/unaligned.h> #define DRV_NAME "e100" #define DRV_DESCRIPTION "Intel(R) PRO/100 Network Driver" #define DRV_COPYRIGHT "Copyright(c) 1999-2006 Intel Corporation" #define E100_WATCHDOG_PERIOD (2 * HZ) #define E100_NAPI_WEIGHT 16 #define FIRMWARE_D101M "e100/d101m_ucode.bin" #define FIRMWARE_D101S "e100/d101s_ucode.bin" #define FIRMWARE_D102E "e100/d102e_ucode.bin" MODULE_DESCRIPTION(DRV_DESCRIPTION); MODULE_AUTHOR(DRV_COPYRIGHT); MODULE_LICENSE("GPL v2"); MODULE_FIRMWARE(FIRMWARE_D101M); MODULE_FIRMWARE(FIRMWARE_D101S); MODULE_FIRMWARE(FIRMWARE_D102E); static int debug = 3; static int eeprom_bad_csum_allow = 0; static int use_io = 0; module_param(debug, int, 0); module_param(eeprom_bad_csum_allow, int, 0); module_param(use_io, int, 0); MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all)"); MODULE_PARM_DESC(eeprom_bad_csum_allow, "Allow bad eeprom checksums"); MODULE_PARM_DESC(use_io, "Force use of i/o access mode"); #define INTEL_8255X_ETHERNET_DEVICE(device_id, ich) {\ PCI_VENDOR_ID_INTEL, device_id, PCI_ANY_ID, PCI_ANY_ID, \ PCI_CLASS_NETWORK_ETHERNET << 8, 0xFFFF00, ich } static const struct pci_device_id e100_id_table[] = { INTEL_8255X_ETHERNET_DEVICE(0x1029, 0), INTEL_8255X_ETHERNET_DEVICE(0x1030, 0), INTEL_8255X_ETHERNET_DEVICE(0x1031, 3), INTEL_8255X_ETHERNET_DEVICE(0x1032, 3), INTEL_8255X_ETHERNET_DEVICE(0x1033, 3), INTEL_8255X_ETHERNET_DEVICE(0x1034, 3), INTEL_8255X_ETHERNET_DEVICE(0x1038, 3), INTEL_8255X_ETHERNET_DEVICE(0x1039, 4), INTEL_8255X_ETHERNET_DEVICE(0x103A, 4), INTEL_8255X_ETHERNET_DEVICE(0x103B, 4), INTEL_8255X_ETHERNET_DEVICE(0x103C, 4), INTEL_8255X_ETHERNET_DEVICE(0x103D, 4), INTEL_8255X_ETHERNET_DEVICE(0x103E, 4), INTEL_8255X_ETHERNET_DEVICE(0x1050, 5), INTEL_8255X_ETHERNET_DEVICE(0x1051, 5), INTEL_8255X_ETHERNET_DEVICE(0x1052, 5), INTEL_8255X_ETHERNET_DEVICE(0x1053, 5), INTEL_8255X_ETHERNET_DEVICE(0x1054, 5), INTEL_8255X_ETHERNET_DEVICE(0x1055, 5), INTEL_8255X_ETHERNET_DEVICE(0x1056, 5), INTEL_8255X_ETHERNET_DEVICE(0x1057, 5), INTEL_8255X_ETHERNET_DEVICE(0x1059, 0), INTEL_8255X_ETHERNET_DEVICE(0x1064, 6), INTEL_8255X_ETHERNET_DEVICE(0x1065, 6), INTEL_8255X_ETHERNET_DEVICE(0x1066, 6), INTEL_8255X_ETHERNET_DEVICE(0x1067, 6), INTEL_8255X_ETHERNET_DEVICE(0x1068, 6), INTEL_8255X_ETHERNET_DEVICE(0x1069, 6), INTEL_8255X_ETHERNET_DEVICE(0x106A, 6), INTEL_8255X_ETHERNET_DEVICE(0x106B, 6), INTEL_8255X_ETHERNET_DEVICE(0x1091, 7), INTEL_8255X_ETHERNET_DEVICE(0x1092, 7), INTEL_8255X_ETHERNET_DEVICE(0x1093, 7), INTEL_8255X_ETHERNET_DEVICE(0x1094, 7), INTEL_8255X_ETHERNET_DEVICE(0x1095, 7), INTEL_8255X_ETHERNET_DEVICE(0x10fe, 7), INTEL_8255X_ETHERNET_DEVICE(0x1209, 0), INTEL_8255X_ETHERNET_DEVICE(0x1229, 0), INTEL_8255X_ETHERNET_DEVICE(0x2449, 2), INTEL_8255X_ETHERNET_DEVICE(0x2459, 2), INTEL_8255X_ETHERNET_DEVICE(0x245D, 2), INTEL_8255X_ETHERNET_DEVICE(0x27DC, 7), { 0, } }; MODULE_DEVICE_TABLE(pci, e100_id_table); enum mac { mac_82557_D100_A = 0, mac_82557_D100_B = 1, mac_82557_D100_C = 2, mac_82558_D101_A4 = 4, mac_82558_D101_B0 = 5, mac_82559_D101M = 8, mac_82559_D101S = 9, mac_82550_D102 = 12, mac_82550_D102_C = 13, mac_82551_E = 14, mac_82551_F = 15, mac_82551_10 = 16, mac_unknown = 0xFF, }; enum phy { phy_100a = 0x000003E0, phy_100c = 0x035002A8, phy_82555_tx = 0x015002A8, phy_nsc_tx = 0x5C002000, phy_82562_et = 0x033002A8, phy_82562_em = 0x032002A8, phy_82562_ek = 0x031002A8, phy_82562_eh = 0x017002A8, phy_82552_v = 0xd061004d, phy_unknown = 0xFFFFFFFF, }; /* CSR (Control/Status Registers) */ struct csr { struct { u8 status; u8 stat_ack; u8 cmd_lo; u8 cmd_hi; u32 gen_ptr; } scb; u32 port; u16 flash_ctrl; u8 eeprom_ctrl_lo; u8 eeprom_ctrl_hi; u32 mdi_ctrl; u32 rx_dma_count; }; enum scb_status { rus_no_res = 0x08, rus_ready = 0x10, rus_mask = 0x3C, }; enum ru_state { RU_SUSPENDED = 0, RU_RUNNING = 1, RU_UNINITIALIZED = -1, }; enum scb_stat_ack { stat_ack_not_ours = 0x00, stat_ack_sw_gen = 0x04, stat_ack_rnr = 0x10, stat_ack_cu_idle = 0x20, stat_ack_frame_rx = 0x40, stat_ack_cu_cmd_done = 0x80, stat_ack_not_present = 0xFF, stat_ack_rx = (stat_ack_sw_gen | stat_ack_rnr | stat_ack_frame_rx), stat_ack_tx = (stat_ack_cu_idle | stat_ack_cu_cmd_done), }; enum scb_cmd_hi { irq_mask_none = 0x00, irq_mask_all = 0x01, irq_sw_gen = 0x02, }; enum scb_cmd_lo { cuc_nop = 0x00, ruc_start = 0x01, ruc_load_base = 0x06, cuc_start = 0x10, cuc_resume = 0x20, cuc_dump_addr = 0x40, cuc_dump_stats = 0x50, cuc_load_base = 0x60, cuc_dump_reset = 0x70, }; enum cuc_dump { cuc_dump_complete = 0x0000A005, cuc_dump_reset_complete = 0x0000A007, }; enum port { software_reset = 0x0000, selftest = 0x0001, selective_reset = 0x0002, }; enum eeprom_ctrl_lo { eesk = 0x01, eecs = 0x02, eedi = 0x04, eedo = 0x08, }; enum mdi_ctrl { mdi_write = 0x04000000, mdi_read = 0x08000000, mdi_ready = 0x10000000, }; enum eeprom_op { op_write = 0x05, op_read = 0x06, op_ewds = 0x10, op_ewen = 0x13, }; enum eeprom_offsets { eeprom_cnfg_mdix = 0x03, eeprom_phy_iface = 0x06, eeprom_id = 0x0A, eeprom_config_asf = 0x0D, eeprom_smbus_addr = 0x90, }; enum eeprom_cnfg_mdix { eeprom_mdix_enabled = 0x0080, }; enum eeprom_phy_iface { NoSuchPhy = 0, I82553AB, I82553C, I82503, DP83840, S80C240, S80C24, I82555, DP83840A = 10, }; enum eeprom_id { eeprom_id_wol = 0x0020, }; enum eeprom_config_asf { eeprom_asf = 0x8000, eeprom_gcl = 0x4000, }; enum cb_status { cb_complete = 0x8000, cb_ok = 0x2000, }; /* * cb_command - Command Block flags * @cb_tx_nc: 0: controller does CRC (normal), 1: CRC from skb memory */ enum cb_command { cb_nop = 0x0000, cb_iaaddr = 0x0001, cb_config = 0x0002, cb_multi = 0x0003, cb_tx = 0x0004, cb_ucode = 0x0005, cb_dump = 0x0006, cb_tx_sf = 0x0008, cb_tx_nc = 0x0010, cb_cid = 0x1f00, cb_i = 0x2000, cb_s = 0x4000, cb_el = 0x8000, }; struct rfd { __le16 status; __le16 command; __le32 link; __le32 rbd; __le16 actual_size; __le16 size; }; struct rx { struct rx *next, *prev; struct sk_buff *skb; dma_addr_t dma_addr; }; #if defined(__BIG_ENDIAN_BITFIELD) #define X(a,b) b,a #else #define X(a,b) a,b #endif struct config { /*0*/ u8 X(byte_count:6, pad0:2); /*1*/ u8 X(X(rx_fifo_limit:4, tx_fifo_limit:3), pad1:1); /*2*/ u8 adaptive_ifs; /*3*/ u8 X(X(X(X(mwi_enable:1, type_enable:1), read_align_enable:1), term_write_cache_line:1), pad3:4); /*4*/ u8 X(rx_dma_max_count:7, pad4:1); /*5*/ u8 X(tx_dma_max_count:7, dma_max_count_enable:1); /*6*/ u8 X(X(X(X(X(X(X(late_scb_update:1, direct_rx_dma:1), tno_intr:1), cna_intr:1), standard_tcb:1), standard_stat_counter:1), rx_save_overruns : 1), rx_save_bad_frames : 1); /*7*/ u8 X(X(X(X(X(rx_discard_short_frames:1, tx_underrun_retry:2), pad7:2), rx_extended_rfd:1), tx_two_frames_in_fifo:1), tx_dynamic_tbd:1); /*8*/ u8 X(X(mii_mode:1, pad8:6), csma_disabled:1); /*9*/ u8 X(X(X(X(X(rx_tcpudp_checksum:1, pad9:3), vlan_arp_tco:1), link_status_wake:1), arp_wake:1), mcmatch_wake:1); /*10*/ u8 X(X(X(pad10:3, no_source_addr_insertion:1), preamble_length:2), loopback:2); /*11*/ u8 X(linear_priority:3, pad11:5); /*12*/ u8 X(X(linear_priority_mode:1, pad12:3), ifs:4); /*13*/ u8 ip_addr_lo; /*14*/ u8 ip_addr_hi; /*15*/ u8 X(X(X(X(X(X(X(promiscuous_mode:1, broadcast_disabled:1), wait_after_win:1), pad15_1:1), ignore_ul_bit:1), crc_16_bit:1), pad15_2:1), crs_or_cdt:1); /*16*/ u8 fc_delay_lo; /*17*/ u8 fc_delay_hi; /*18*/ u8 X(X(X(X(X(rx_stripping:1, tx_padding:1), rx_crc_transfer:1), rx_long_ok:1), fc_priority_threshold:3), pad18:1); /*19*/ u8 X(X(X(X(X(X(X(addr_wake:1, magic_packet_disable:1), fc_disable:1), fc_restop:1), fc_restart:1), fc_reject:1), full_duplex_force:1), full_duplex_pin:1); /*20*/ u8 X(X(X(pad20_1:5, fc_priority_location:1), multi_ia:1), pad20_2:1); /*21*/ u8 X(X(pad21_1:3, multicast_all:1), pad21_2:4); /*22*/ u8 X(X(rx_d102_mode:1, rx_vlan_drop:1), pad22:6); u8 pad_d102[9]; }; #define E100_MAX_MULTICAST_ADDRS 64 struct multi { __le16 count; u8 addr[E100_MAX_MULTICAST_ADDRS * ETH_ALEN + 2/*pad*/]; }; /* Important: keep total struct u32-aligned */ #define UCODE_SIZE 134 struct cb { __le16 status; __le16 command; __le32 link; union { u8 iaaddr[ETH_ALEN]; __le32 ucode[UCODE_SIZE]; struct config config; struct multi multi; struct { u32 tbd_array; u16 tcb_byte_count; u8 threshold; u8 tbd_count; struct { __le32 buf_addr; __le16 size; u16 eol; } tbd; } tcb; __le32 dump_buffer_addr; } u; struct cb *next, *prev; dma_addr_t dma_addr; struct sk_buff *skb; }; enum loopback { lb_none = 0, lb_mac = 1, lb_phy = 3, }; struct stats { __le32 tx_good_frames, tx_max_collisions, tx_late_collisions, tx_underruns, tx_lost_crs, tx_deferred, tx_single_collisions, tx_multiple_collisions, tx_total_collisions; __le32 rx_good_frames, rx_crc_errors, rx_alignment_errors, rx_resource_errors, rx_overrun_errors, rx_cdt_errors, rx_short_frame_errors; __le32 fc_xmt_pause, fc_rcv_pause, fc_rcv_unsupported; __le16 xmt_tco_frames, rcv_tco_frames; __le32 complete; }; struct mem { struct { u32 signature; u32 result; } selftest; struct stats stats; u8 dump_buf[596]; }; struct param_range { u32 min; u32 max; u32 count; }; struct params { struct param_range rfds; struct param_range cbs; }; struct nic { /* Begin: frequently used values: keep adjacent for cache effect */ u32 msg_enable ____cacheline_aligned; struct net_device *netdev; struct pci_dev *pdev; u16 (*mdio_ctrl)(struct nic *nic, u32 addr, u32 dir, u32 reg, u16 data); struct rx *rxs ____cacheline_aligned; struct rx *rx_to_use; struct rx *rx_to_clean; struct rfd blank_rfd; enum ru_state ru_running; spinlock_t cb_lock ____cacheline_aligned; spinlock_t cmd_lock; struct csr __iomem *csr; enum scb_cmd_lo cuc_cmd; unsigned int cbs_avail; struct napi_struct napi; struct cb *cbs; struct cb *cb_to_use; struct cb *cb_to_send; struct cb *cb_to_clean; __le16 tx_command; /* End: frequently used values: keep adjacent for cache effect */ enum { ich = (1 << 0), promiscuous = (1 << 1), multicast_all = (1 << 2), wol_magic = (1 << 3), ich_10h_workaround = (1 << 4), } flags ____cacheline_aligned; enum mac mac; enum phy phy; struct params params; struct timer_list watchdog; struct mii_if_info mii; struct work_struct tx_timeout_task; enum loopback loopback; struct mem *mem; dma_addr_t dma_addr; struct dma_pool *cbs_pool; dma_addr_t cbs_dma_addr; u8 adaptive_ifs; u8 tx_threshold; u32 tx_frames; u32 tx_collisions; u32 tx_deferred; u32 tx_single_collisions; u32 tx_multiple_collisions; u32 tx_fc_pause; u32 tx_tco_frames; u32 rx_fc_pause; u32 rx_fc_unsupported; u32 rx_tco_frames; u32 rx_short_frame_errors; u32 rx_over_length_errors; u16 eeprom_wc; __le16 eeprom[256]; spinlock_t mdio_lock; const struct firmware *fw; }; static inline void e100_write_flush(struct nic *nic) { /* Flush previous PCI writes through intermediate bridges * by doing a benign read */ (void)ioread8(&nic->csr->scb.status); } static void e100_enable_irq(struct nic *nic) { unsigned long flags; spin_lock_irqsave(&nic->cmd_lock, flags); iowrite8(irq_mask_none, &nic->csr->scb.cmd_hi); e100_write_flush(nic); spin_unlock_irqrestore(&nic->cmd_lock, flags); } static void e100_disable_irq(struct nic *nic) { unsigned long flags; spin_lock_irqsave(&nic->cmd_lock, flags); iowrite8(irq_mask_all, &nic->csr->scb.cmd_hi); e100_write_flush(nic); spin_unlock_irqrestore(&nic->cmd_lock, flags); } static void e100_hw_reset(struct nic *nic) { /* Put CU and RU into idle with a selective reset to get * device off of PCI bus */ iowrite32(selective_reset, &nic->csr->port); e100_write_flush(nic); udelay(20); /* Now fully reset device */ iowrite32(software_reset, &nic->csr->port); e100_write_flush(nic); udelay(20); /* Mask off our interrupt line - it's unmasked after reset */ e100_disable_irq(nic); } static int e100_self_test(struct nic *nic) { u32 dma_addr = nic->dma_addr + offsetof(struct mem, selftest); /* Passing the self-test is a pretty good indication * that the device can DMA to/from host memory */ nic->mem->selftest.signature = 0; nic->mem->selftest.result = 0xFFFFFFFF; iowrite32(selftest | dma_addr, &nic->csr->port); e100_write_flush(nic); /* Wait 10 msec for self-test to complete */ msleep(10); /* Interrupts are enabled after self-test */ e100_disable_irq(nic); /* Check results of self-test */ if (nic->mem->selftest.result != 0) { netif_err(nic, hw, nic->netdev, "Self-test failed: result=0x%08X\n", nic->mem->selftest.result); return -ETIMEDOUT; } if (nic->mem->selftest.signature == 0) { netif_err(nic, hw, nic->netdev, "Self-test failed: timed out\n"); return -ETIMEDOUT; } return 0; } static void e100_eeprom_write(struct nic *nic, u16 addr_len, u16 addr, __le16 data) { u32 cmd_addr_data[3]; u8 ctrl; int i, j; /* Three cmds: write/erase enable, write data, write/erase disable */ cmd_addr_data[0] = op_ewen << (addr_len - 2); cmd_addr_data[1] = (((op_write << addr_len) | addr) << 16) | le16_to_cpu(data); cmd_addr_data[2] = op_ewds << (addr_len - 2); /* Bit-bang cmds to write word to eeprom */ for (j = 0; j < 3; j++) { /* Chip select */ iowrite8(eecs | eesk, &nic->csr->eeprom_ctrl_lo); e100_write_flush(nic); udelay(4); for (i = 31; i >= 0; i--) { ctrl = (cmd_addr_data[j] & (1 << i)) ? eecs | eedi : eecs; iowrite8(ctrl, &nic->csr->eeprom_ctrl_lo); e100_write_flush(nic); udelay(4); iowrite8(ctrl | eesk, &nic->csr->eeprom_ctrl_lo); e100_write_flush(nic); udelay(4); } /* Wait 10 msec for cmd to complete */ msleep(10); /* Chip deselect */ iowrite8(0, &nic->csr->eeprom_ctrl_lo); e100_write_flush(nic); udelay(4); } }; /* General technique stolen from the eepro100 driver - very clever */ static __le16 e100_eeprom_read(struct nic *nic, u16 *addr_len, u16 addr) { u32 cmd_addr_data; u16 data = 0; u8 ctrl; int i; cmd_addr_data = ((op_read << *addr_len) | addr) << 16; /* Chip select */ iowrite8(eecs | eesk, &nic->csr->eeprom_ctrl_lo); e100_write_flush(nic); udelay(4); /* Bit-bang to read word from eeprom */ for (i = 31; i >= 0; i--) { ctrl = (cmd_addr_data & (1 << i)) ? eecs | eedi : eecs; iowrite8(ctrl, &nic->csr->eeprom_ctrl_lo); e100_write_flush(nic); udelay(4); iowrite8(ctrl | eesk, &nic->csr->eeprom_ctrl_lo); e100_write_flush(nic); udelay(4); /* Eeprom drives a dummy zero to EEDO after receiving * complete address. Use this to adjust addr_len. */ ctrl = ioread8(&nic->csr->eeprom_ctrl_lo); if (!(ctrl & eedo) && i > 16) { *addr_len -= (i - 16); i = 17; } data = (data << 1) | (ctrl & eedo ? 1 : 0); } /* Chip deselect */ iowrite8(0, &nic->csr->eeprom_ctrl_lo); e100_write_flush(nic); udelay(4); return cpu_to_le16(data); }; /* Load entire EEPROM image into driver cache and validate checksum */ static int e100_eeprom_load(struct nic *nic) { u16 addr, addr_len = 8, checksum = 0; /* Try reading with an 8-bit addr len to discover actual addr len */ e100_eeprom_read(nic, &addr_len, 0); nic->eeprom_wc = 1 << addr_len; for (addr = 0; addr < nic->eeprom_wc; addr++) { nic->eeprom[addr] = e100_eeprom_read(nic, &addr_len, addr); if (addr < nic->eeprom_wc - 1) checksum += le16_to_cpu(nic->eeprom[addr]); } /* The checksum, stored in the last word, is calculated such that * the sum of words should be 0xBABA */ if (cpu_to_le16(0xBABA - checksum) != nic->eeprom[nic->eeprom_wc - 1]) { netif_err(nic, probe, nic->netdev, "EEPROM corrupted\n"); if (!eeprom_bad_csum_allow) return -EAGAIN; } return 0; } /* Save (portion of) driver EEPROM cache to device and update checksum */ static int e100_eeprom_save(struct nic *nic, u16 start, u16 count) { u16 addr, addr_len = 8, checksum = 0; /* Try reading with an 8-bit addr len to discover actual addr len */ e100_eeprom_read(nic, &addr_len, 0); nic->eeprom_wc = 1 << addr_len; if (start + count >= nic->eeprom_wc) return -EINVAL; for (addr = start; addr < start + count; addr++) e100_eeprom_write(nic, addr_len, addr, nic->eeprom[addr]); /* The checksum, stored in the last word, is calculated such that * the sum of words should be 0xBABA */ for (addr = 0; addr < nic->eeprom_wc - 1; addr++) checksum += le16_to_cpu(nic->eeprom[addr]); nic->eeprom[nic->eeprom_wc - 1] = cpu_to_le16(0xBABA - checksum); e100_eeprom_write(nic, addr_len, nic->eeprom_wc - 1, nic->eeprom[nic->eeprom_wc - 1]); return 0; } #define E100_WAIT_SCB_TIMEOUT 20000 /* we might have to wait 100ms!!! */ #define E100_WAIT_SCB_FAST 20 /* delay like the old code */ static int e100_exec_cmd(struct nic *nic, u8 cmd, dma_addr_t dma_addr) { unsigned long flags; unsigned int i; int err = 0; spin_lock_irqsave(&nic->cmd_lock, flags); /* Previous command is accepted when SCB clears */ for (i = 0; i < E100_WAIT_SCB_TIMEOUT; i++) { if (likely(!ioread8(&nic->csr->scb.cmd_lo))) break; cpu_relax(); if (unlikely(i > E100_WAIT_SCB_FAST)) udelay(5); } if (unlikely(i == E100_WAIT_SCB_TIMEOUT)) { err = -EAGAIN; goto err_unlock; } if (unlikely(cmd != cuc_resume)) iowrite32(dma_addr, &nic->csr->scb.gen_ptr); iowrite8(cmd, &nic->csr->scb.cmd_lo); err_unlock: spin_unlock_irqrestore(&nic->cmd_lock, flags); return err; } static int e100_exec_cb(struct nic *nic, struct sk_buff *skb, int (*cb_prepare)(struct nic *, struct cb *, struct sk_buff *)) { struct cb *cb; unsigned long flags; int err; spin_lock_irqsave(&nic->cb_lock, flags); if (unlikely(!nic->cbs_avail)) { err = -ENOMEM; goto err_unlock; } cb = nic->cb_to_use; nic->cb_to_use = cb->next; nic->cbs_avail--; cb->skb = skb; err = cb_prepare(nic, cb, skb); if (err) goto err_unlock; if (unlikely(!nic->cbs_avail)) err = -ENOSPC; /* Order is important otherwise we'll be in a race with h/w: * set S-bit in current first, then clear S-bit in previous. */ cb->command |= cpu_to_le16(cb_s); dma_wmb(); cb->prev->command &= cpu_to_le16(~cb_s); while (nic->cb_to_send != nic->cb_to_use) { if (unlikely(e100_exec_cmd(nic, nic->cuc_cmd, nic->cb_to_send->dma_addr))) { /* Ok, here's where things get sticky. It's * possible that we can't schedule the command * because the controller is too busy, so * let's just queue the command and try again * when another command is scheduled. */ if (err == -ENOSPC) { //request a reset schedule_work(&nic->tx_timeout_task); } break; } else { nic->cuc_cmd = cuc_resume; nic->cb_to_send = nic->cb_to_send->next; } } err_unlock: spin_unlock_irqrestore(&nic->cb_lock, flags); return err; } static int mdio_read(struct net_device *netdev, int addr, int reg) { struct nic *nic = netdev_priv(netdev); return nic->mdio_ctrl(nic, addr, mdi_read, reg, 0); } static void mdio_write(struct net_device *netdev, int addr, int reg, int data) { struct nic *nic = netdev_priv(netdev); nic->mdio_ctrl(nic, addr, mdi_write, reg, data); } /* the standard mdio_ctrl() function for usual MII-compliant hardware */ static u16 mdio_ctrl_hw(struct nic *nic, u32 addr, u32 dir, u32 reg, u16 data) { u32 data_out = 0; unsigned int i; unsigned long flags; /* * Stratus87247: we shouldn't be writing the MDI control * register until the Ready bit shows True. Also, since * manipulation of the MDI control registers is a multi-step * procedure it should be done under lock. */ spin_lock_irqsave(&nic->mdio_lock, flags); for (i = 100; i; --i) { if (ioread32(&nic->csr->mdi_ctrl) & mdi_ready) break; udelay(20); } if (unlikely(!i)) { netdev_err(nic->netdev, "e100.mdio_ctrl won't go Ready\n"); spin_unlock_irqrestore(&nic->mdio_lock, flags); return 0; /* No way to indicate timeout error */ } iowrite32((reg << 16) | (addr << 21) | dir | data, &nic->csr->mdi_ctrl); for (i = 0; i < 100; i++) { udelay(20); if ((data_out = ioread32(&nic->csr->mdi_ctrl)) & mdi_ready) break; } spin_unlock_irqrestore(&nic->mdio_lock, flags); netif_printk(nic, hw, KERN_DEBUG, nic->netdev, "%s:addr=%d, reg=%d, data_in=0x%04X, data_out=0x%04X\n", dir == mdi_read ? "READ" : "WRITE", addr, reg, data, data_out); return (u16)data_out; } /* slightly tweaked mdio_ctrl() function for phy_82552_v specifics */ static u16 mdio_ctrl_phy_82552_v(struct nic *nic, u32 addr, u32 dir, u32 reg, u16 data) { if ((reg == MII_BMCR) && (dir == mdi_write)) { if (data & (BMCR_ANRESTART | BMCR_ANENABLE)) { u16 advert = mdio_read(nic->netdev, nic->mii.phy_id, MII_ADVERTISE); /* * Workaround Si issue where sometimes the part will not * autoneg to 100Mbps even when advertised. */ if (advert & ADVERTISE_100FULL) data |= BMCR_SPEED100 | BMCR_FULLDPLX; else if (advert & ADVERTISE_100HALF) data |= BMCR_SPEED100; } } return mdio_ctrl_hw(nic, addr, dir, reg, data); } /* Fully software-emulated mdio_ctrl() function for cards without * MII-compliant PHYs. * For now, this is mainly geared towards 80c24 support; in case of further * requirements for other types (i82503, ...?) either extend this mechanism * or split it, whichever is cleaner. */ static u16 mdio_ctrl_phy_mii_emulated(struct nic *nic, u32 addr, u32 dir, u32 reg, u16 data) { /* might need to allocate a netdev_priv'ed register array eventually * to be able to record state changes, but for now * some fully hardcoded register handling ought to be ok I guess. */ if (dir == mdi_read) { switch (reg) { case MII_BMCR: /* Auto-negotiation, right? */ return BMCR_ANENABLE | BMCR_FULLDPLX; case MII_BMSR: return BMSR_LSTATUS /* for mii_link_ok() */ | BMSR_ANEGCAPABLE | BMSR_10FULL; case MII_ADVERTISE: /* 80c24 is a "combo card" PHY, right? */ return ADVERTISE_10HALF | ADVERTISE_10FULL; default: netif_printk(nic, hw, KERN_DEBUG, nic->netdev, "%s:addr=%d, reg=%d, data=0x%04X: unimplemented emulation!\n", dir == mdi_read ? "READ" : "WRITE", addr, reg, data); return 0xFFFF; } } else { switch (reg) { default: netif_printk(nic, hw, KERN_DEBUG, nic->netdev, "%s:addr=%d, reg=%d, data=0x%04X: unimplemented emulation!\n", dir == mdi_read ? "READ" : "WRITE", addr, reg, data); return 0xFFFF; } } } static inline int e100_phy_supports_mii(struct nic *nic) { /* for now, just check it by comparing whether we are using MII software emulation. */ return (nic->mdio_ctrl != mdio_ctrl_phy_mii_emulated); } static void e100_get_defaults(struct nic *nic) { struct param_range rfds = { .min = 16, .max = 256, .count = 256 }; struct param_range cbs = { .min = 64, .max = 256, .count = 128 }; /* MAC type is encoded as rev ID; exception: ICH is treated as 82559 */ nic->mac = (nic->flags & ich) ? mac_82559_D101M : nic->pdev->revision; if (nic->mac == mac_unknown) nic->mac = mac_82557_D100_A; nic->params.rfds = rfds; nic->params.cbs = cbs; /* Quadwords to DMA into FIFO before starting frame transmit */ nic->tx_threshold = 0xE0; /* no interrupt for every tx completion, delay = 256us if not 557 */ nic->tx_command = cpu_to_le16(cb_tx | cb_tx_sf | ((nic->mac >= mac_82558_D101_A4) ? cb_cid : cb_i)); /* Template for a freshly allocated RFD */ nic->blank_rfd.command = 0; nic->blank_rfd.rbd = cpu_to_le32(0xFFFFFFFF); nic->blank_rfd.size = cpu_to_le16(VLAN_ETH_FRAME_LEN + ETH_FCS_LEN); /* MII setup */ nic->mii.phy_id_mask = 0x1F; nic->mii.reg_num_mask = 0x1F; nic->mii.dev = nic->netdev; nic->mii.mdio_read = mdio_read; nic->mii.mdio_write = mdio_write; } static int e100_configure(struct nic *nic, struct cb *cb, struct sk_buff *skb) { struct config *config = &cb->u.config; u8 *c = (u8 *)config; struct net_device *netdev = nic->netdev; cb->command = cpu_to_le16(cb_config); memset(config, 0, sizeof(struct config)); config->byte_count = 0x16; /* bytes in this struct */ config->rx_fifo_limit = 0x8; /* bytes in FIFO before DMA */ config->direct_rx_dma = 0x1; /* reserved */ config->standard_tcb = 0x1; /* 1=standard, 0=extended */ config->standard_stat_counter = 0x1; /* 1=standard, 0=extended */ config->rx_discard_short_frames = 0x1; /* 1=discard, 0=pass */ config->tx_underrun_retry = 0x3; /* # of underrun retries */ if (e100_phy_supports_mii(nic)) config->mii_mode = 1; /* 1=MII mode, 0=i82503 mode */ config->pad10 = 0x6; config->no_source_addr_insertion = 0x1; /* 1=no, 0=yes */ config->preamble_length = 0x2; /* 0=1, 1=3, 2=7, 3=15 bytes */ config->ifs = 0x6; /* x16 = inter frame spacing */ config->ip_addr_hi = 0xF2; /* ARP IP filter - not used */ config->pad15_1 = 0x1; config->pad15_2 = 0x1; config->crs_or_cdt = 0x0; /* 0=CRS only, 1=CRS or CDT */ config->fc_delay_hi = 0x40; /* time delay for fc frame */ config->tx_padding = 0x1; /* 1=pad short frames */ config->fc_priority_threshold = 0x7; /* 7=priority fc disabled */ config->pad18 = 0x1; config->full_duplex_pin = 0x1; /* 1=examine FDX# pin */ config->pad20_1 = 0x1F; config->fc_priority_location = 0x1; /* 1=byte#31, 0=byte#19 */ config->pad21_1 = 0x5; config->adaptive_ifs = nic->adaptive_ifs; config->loopback = nic->loopback; if (nic->mii.force_media && nic->mii.full_duplex) config->full_duplex_force = 0x1; /* 1=force, 0=auto */ if (nic->flags & promiscuous || nic->loopback) { config->rx_save_bad_frames = 0x1; /* 1=save, 0=discard */ config->rx_discard_short_frames = 0x0; /* 1=discard, 0=save */ config->promiscuous_mode = 0x1; /* 1=on, 0=off */ } if (unlikely(netdev->features & NETIF_F_RXFCS)) config->rx_crc_transfer = 0x1; /* 1=save, 0=discard */ if (nic->flags & multicast_all) config->multicast_all = 0x1; /* 1=accept, 0=no */ /* disable WoL when up */ if (netif_running(nic->netdev) || !(nic->flags & wol_magic)) config->magic_packet_disable = 0x1; /* 1=off, 0=on */ if (nic->mac >= mac_82558_D101_A4) { config->fc_disable = 0x1; /* 1=Tx fc off, 0=Tx fc on */ config->mwi_enable = 0x1; /* 1=enable, 0=disable */ config->standard_tcb = 0x0; /* 1=standard, 0=extended */ config->rx_long_ok = 0x1; /* 1=VLANs ok, 0=standard */ if (nic->mac >= mac_82559_D101M) { config->tno_intr = 0x1; /* TCO stats enable */ /* Enable TCO in extended config */ if (nic->mac >= mac_82551_10) { config->byte_count = 0x20; /* extended bytes */ config->rx_d102_mode = 0x1; /* GMRC for TCO */ } } else { config->standard_stat_counter = 0x0; } } if (netdev->features & NETIF_F_RXALL) { config->rx_save_overruns = 0x1; /* 1=save, 0=discard */ config->rx_save_bad_frames = 0x1; /* 1=save, 0=discard */ config->rx_discard_short_frames = 0x0; /* 1=discard, 0=save */ } netif_printk(nic, hw, KERN_DEBUG, nic->netdev, "[00-07]=%8ph\n", c + 0); netif_printk(nic, hw, KERN_DEBUG, nic->netdev, "[08-15]=%8ph\n", c + 8); netif_printk(nic, hw, KERN_DEBUG, nic->netdev, "[16-23]=%8ph\n", c + 16); return 0; } /************************************************************************* * CPUSaver parameters * * All CPUSaver parameters are 16-bit literals that are part of a * "move immediate value" instruction. By changing the value of * the literal in the instruction before the code is loaded, the * driver can change the algorithm. * * INTDELAY - This loads the dead-man timer with its initial value. * When this timer expires the interrupt is asserted, and the * timer is reset each time a new packet is received. (see * BUNDLEMAX below to set the limit on number of chained packets) * The current default is 0x600 or 1536. Experiments show that * the value should probably stay within the 0x200 - 0x1000. * * BUNDLEMAX - * This sets the maximum number of frames that will be bundled. In * some situations, such as the TCP windowing algorithm, it may be * better to limit the growth of the bundle size than let it go as * high as it can, because that could cause too much added latency. * The default is six, because this is the number of packets in the * default TCP window size. A value of 1 would make CPUSaver indicate * an interrupt for every frame received. If you do not want to put * a limit on the bundle size, set this value to xFFFF. * * BUNDLESMALL - * This contains a bit-mask describing the minimum size frame that * will be bundled. The default masks the lower 7 bits, which means * that any frame less than 128 bytes in length will not be bundled, * but will instead immediately generate an interrupt. This does * not affect the current bundle in any way. Any frame that is 128 * bytes or large will be bundled normally. This feature is meant * to provide immediate indication of ACK frames in a TCP environment. * Customers were seeing poor performance when a machine with CPUSaver * enabled was sending but not receiving. The delay introduced when * the ACKs were received was enough to reduce total throughput, because * the sender would sit idle until the ACK was finally seen. * * The current default is 0xFF80, which masks out the lower 7 bits. * This means that any frame which is x7F (127) bytes or smaller * will cause an immediate interrupt. Because this value must be a * bit mask, there are only a few valid values that can be used. To * turn this feature off, the driver can write the value xFFFF to the * lower word of this instruction (in the same way that the other * parameters are used). Likewise, a value of 0xF800 (2047) would * cause an interrupt to be generated for every frame, because all * standard Ethernet frames are <= 2047 bytes in length. *************************************************************************/ /* if you wish to disable the ucode functionality, while maintaining the * workarounds it provides, set the following defines to: * BUNDLESMALL 0 * BUNDLEMAX 1 * INTDELAY 1 */ #define BUNDLESMALL 1 #define BUNDLEMAX (u16)6 #define INTDELAY (u16)1536 /* 0x600 */ /* Initialize firmware */ static const struct firmware *e100_request_firmware(struct nic *nic) { const char *fw_name; const struct firmware *fw = nic->fw; u8 timer, bundle, min_size; int err = 0; bool required = false; /* do not load u-code for ICH devices */ if (nic->flags & ich) return NULL; /* Search for ucode match against h/w revision * * Based on comments in the source code for the FreeBSD fxp * driver, the FIRMWARE_D102E ucode includes both CPUSaver and * * "fixes for bugs in the B-step hardware (specifically, bugs * with Inline Receive)." * * So we must fail if it cannot be loaded. * * The other microcode files are only required for the optional * CPUSaver feature. Nice to have, but no reason to fail. */ if (nic->mac == mac_82559_D101M) { fw_name = FIRMWARE_D101M; } else if (nic->mac == mac_82559_D101S) { fw_name = FIRMWARE_D101S; } else if (nic->mac == mac_82551_F || nic->mac == mac_82551_10) { fw_name = FIRMWARE_D102E; required = true; } else { /* No ucode on other devices */ return NULL; } /* If the firmware has not previously been loaded, request a pointer * to it. If it was previously loaded, we are reinitializing the * adapter, possibly in a resume from hibernate, in which case * request_firmware() cannot be used. */ if (!fw) err = request_firmware(&fw, fw_name, &nic->pdev->dev); if (err) { if (required) { netif_err(nic, probe, nic->netdev, "Failed to load firmware \"%s\": %d\n", fw_name, err); return ERR_PTR(err); } else { netif_info(nic, probe, nic->netdev, "CPUSaver disabled. Needs \"%s\": %d\n", fw_name, err); return NULL; } } /* Firmware should be precisely UCODE_SIZE (words) plus three bytes indicating the offsets for BUNDLESMALL, BUNDLEMAX, INTDELAY */ if (fw->size != UCODE_SIZE * 4 + 3) { netif_err(nic, probe, nic->netdev, "Firmware \"%s\" has wrong size %zu\n", fw_name, fw->size); release_firmware(fw); return ERR_PTR(-EINVAL); } /* Read timer, bundle and min_size from end of firmware blob */ timer = fw->data[UCODE_SIZE * 4]; bundle = fw->data[UCODE_SIZE * 4 + 1]; min_size = fw->data[UCODE_SIZE * 4 + 2]; if (timer >= UCODE_SIZE || bundle >= UCODE_SIZE || min_size >= UCODE_SIZE) { netif_err(nic, probe, nic->netdev, "\"%s\" has bogus offset values (0x%x,0x%x,0x%x)\n", fw_name, timer, bundle, min_size); release_firmware(fw); return ERR_PTR(-EINVAL); } /* OK, firmware is validated and ready to use. Save a pointer * to it in the nic */ nic->fw = fw; return fw; } static int e100_setup_ucode(struct nic *nic, struct cb *cb, struct sk_buff *skb) { const struct firmware *fw = (void *)skb; u8 timer, bundle, min_size; /* It's not a real skb; we just abused the fact that e100_exec_cb will pass it through to here... */ cb->skb = NULL; /* firmware is stored as little endian already */ memcpy(cb->u.ucode, fw->data, UCODE_SIZE * 4); /* Read timer, bundle and min_size from end of firmware blob */ timer = fw->data[UCODE_SIZE * 4]; bundle = fw->data[UCODE_SIZE * 4 + 1]; min_size = fw->data[UCODE_SIZE * 4 + 2]; /* Insert user-tunable settings in cb->u.ucode */ cb->u.ucode[timer] &= cpu_to_le32(0xFFFF0000); cb->u.ucode[timer] |= cpu_to_le32(INTDELAY); cb->u.ucode[bundle] &= cpu_to_le32(0xFFFF0000); cb->u.ucode[bundle] |= cpu_to_le32(BUNDLEMAX); cb->u.ucode[min_size] &= cpu_to_le32(0xFFFF0000); cb->u.ucode[min_size] |= cpu_to_le32((BUNDLESMALL) ? 0xFFFF : 0xFF80); cb->command = cpu_to_le16(cb_ucode | cb_el); return 0; } static inline int e100_load_ucode_wait(struct nic *nic) { const struct firmware *fw; int err = 0, counter = 50; struct cb *cb = nic->cb_to_clean; fw = e100_request_firmware(nic); /* If it's NULL, then no ucode is required */ if (IS_ERR_OR_NULL(fw)) return PTR_ERR_OR_ZERO(fw); if ((err = e100_exec_cb(nic, (void *)fw, e100_setup_ucode))) netif_err(nic, probe, nic->netdev, "ucode cmd failed with error %d\n", err); /* must restart cuc */ nic->cuc_cmd = cuc_start; /* wait for completion */ e100_write_flush(nic); udelay(10); /* wait for possibly (ouch) 500ms */ while (!(cb->status & cpu_to_le16(cb_complete))) { msleep(10); if (!--counter) break; } /* ack any interrupts, something could have been set */ iowrite8(~0, &nic->csr->scb.stat_ack); /* if the command failed, or is not OK, notify and return */ if (!counter || !(cb->status & cpu_to_le16(cb_ok))) { netif_err(nic, probe, nic->netdev, "ucode load failed\n"); err = -EPERM; } return err; } static int e100_setup_iaaddr(struct nic *nic, struct cb *cb, struct sk_buff *skb) { cb->command = cpu_to_le16(cb_iaaddr); memcpy(cb->u.iaaddr, nic->netdev->dev_addr, ETH_ALEN); return 0; } static int e100_dump(struct nic *nic, struct cb *cb, struct sk_buff *skb) { cb->command = cpu_to_le16(cb_dump); cb->u.dump_buffer_addr = cpu_to_le32(nic->dma_addr + offsetof(struct mem, dump_buf)); return 0; } static int e100_phy_check_without_mii(struct nic *nic) { u8 phy_type; int without_mii; phy_type = (le16_to_cpu(nic->eeprom[eeprom_phy_iface]) >> 8) & 0x0f; switch (phy_type) { case NoSuchPhy: /* Non-MII PHY; UNTESTED! */ case I82503: /* Non-MII PHY; UNTESTED! */ case S80C24: /* Non-MII PHY; tested and working */ /* paragraph from the FreeBSD driver, "FXP_PHY_80C24": * The Seeq 80c24 AutoDUPLEX(tm) Ethernet Interface Adapter * doesn't have a programming interface of any sort. The * media is sensed automatically based on how the link partner * is configured. This is, in essence, manual configuration. */ netif_info(nic, probe, nic->netdev, "found MII-less i82503 or 80c24 or other PHY\n"); nic->mdio_ctrl = mdio_ctrl_phy_mii_emulated; nic->mii.phy_id = 0; /* is this ok for an MII-less PHY? */ /* these might be needed for certain MII-less cards... * nic->flags |= ich; * nic->flags |= ich_10h_workaround; */ without_mii = 1; break; default: without_mii = 0; break; } return without_mii; } #define NCONFIG_AUTO_SWITCH 0x0080 #define MII_NSC_CONG MII_RESV1 #define NSC_CONG_ENABLE 0x0100 #define NSC_CONG_TXREADY 0x0400 static int e100_phy_init(struct nic *nic) { struct net_device *netdev = nic->netdev; u32 addr; u16 bmcr, stat, id_lo, id_hi, cong; /* Discover phy addr by searching addrs in order {1,0,2,..., 31} */ for (addr = 0; addr < 32; addr++) { nic->mii.phy_id = (addr == 0) ? 1 : (addr == 1) ? 0 : addr; bmcr = mdio_read(netdev, nic->mii.phy_id, MII_BMCR); stat = mdio_read(netdev, nic->mii.phy_id, MII_BMSR); stat = mdio_read(netdev, nic->mii.phy_id, MII_BMSR); if (!((bmcr == 0xFFFF) || ((stat == 0) && (bmcr == 0)))) break; } if (addr == 32) { /* uhoh, no PHY detected: check whether we seem to be some * weird, rare variant which is *known* to not have any MII. * But do this AFTER MII checking only, since this does * lookup of EEPROM values which may easily be unreliable. */ if (e100_phy_check_without_mii(nic)) return 0; /* simply return and hope for the best */ else { /* for unknown cases log a fatal error */ netif_err(nic, hw, nic->netdev, "Failed to locate any known PHY, aborting\n"); return -EAGAIN; } } else netif_printk(nic, hw, KERN_DEBUG, nic->netdev, "phy_addr = %d\n", nic->mii.phy_id); /* Get phy ID */ id_lo = mdio_read(netdev, nic->mii.phy_id, MII_PHYSID1); id_hi = mdio_read(netdev, nic->mii.phy_id, MII_PHYSID2); nic->phy = (u32)id_hi << 16 | (u32)id_lo; netif_printk(nic, hw, KERN_DEBUG, nic->netdev, "phy ID = 0x%08X\n", nic->phy); /* Select the phy and isolate the rest */ for (addr = 0; addr < 32; addr++) { if (addr != nic->mii.phy_id) { mdio_write(netdev, addr, MII_BMCR, BMCR_ISOLATE); } else if (nic->phy != phy_82552_v) { bmcr = mdio_read(netdev, addr, MII_BMCR); mdio_write(netdev, addr, MII_BMCR, bmcr & ~BMCR_ISOLATE); } } /* * Workaround for 82552: * Clear the ISOLATE bit on selected phy_id last (mirrored on all * other phy_id's) using bmcr value from addr discovery loop above. */ if (nic->phy == phy_82552_v) mdio_write(netdev, nic->mii.phy_id, MII_BMCR, bmcr & ~BMCR_ISOLATE); /* Handle National tx phys */ #define NCS_PHY_MODEL_MASK 0xFFF0FFFF if ((nic->phy & NCS_PHY_MODEL_MASK) == phy_nsc_tx) { /* Disable congestion control */ cong = mdio_read(netdev, nic->mii.phy_id, MII_NSC_CONG); cong |= NSC_CONG_TXREADY; cong &= ~NSC_CONG_ENABLE; mdio_write(netdev, nic->mii.phy_id, MII_NSC_CONG, cong); } if (nic->phy == phy_82552_v) { u16 advert = mdio_read(netdev, nic->mii.phy_id, MII_ADVERTISE); /* assign special tweaked mdio_ctrl() function */ nic->mdio_ctrl = mdio_ctrl_phy_82552_v; /* Workaround Si not advertising flow-control during autoneg */ advert |= ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM; mdio_write(netdev, nic->mii.phy_id, MII_ADVERTISE, advert); /* Reset for the above changes to take effect */ bmcr = mdio_read(netdev, nic->mii.phy_id, MII_BMCR); bmcr |= BMCR_RESET; mdio_write(netdev, nic->mii.phy_id, MII_BMCR, bmcr); } else if ((nic->mac >= mac_82550_D102) || ((nic->flags & ich) && (mdio_read(netdev, nic->mii.phy_id, MII_TPISTATUS) & 0x8000) && (le16_to_cpu(nic->eeprom[eeprom_cnfg_mdix]) & eeprom_mdix_enabled))) { /* enable/disable MDI/MDI-X auto-switching. */ mdio_write(netdev, nic->mii.phy_id, MII_NCONFIG, nic->mii.force_media ? 0 : NCONFIG_AUTO_SWITCH); } return 0; } static int e100_hw_init(struct nic *nic) { int err = 0; e100_hw_reset(nic); netif_err(nic, hw, nic->netdev, "e100_hw_init\n"); if ((err = e100_self_test(nic))) return err; if ((err = e100_phy_init(nic))) return err; if ((err = e100_exec_cmd(nic, cuc_load_base, 0))) return err; if ((err = e100_exec_cmd(nic, ruc_load_base, 0))) return err; if ((err = e100_load_ucode_wait(nic))) return err; if ((err = e100_exec_cb(nic, NULL, e100_configure))) return err; if ((err = e100_exec_cb(nic, NULL, e100_setup_iaaddr))) return err; if ((err = e100_exec_cmd(nic, cuc_dump_addr, nic->dma_addr + offsetof(struct mem, stats)))) return err; if ((err = e100_exec_cmd(nic, cuc_dump_reset, 0))) return err; e100_disable_irq(nic); return 0; } static int e100_multi(struct nic *nic, struct cb *cb, struct sk_buff *skb) { struct net_device *netdev = nic->netdev; struct netdev_hw_addr *ha; u16 i, count = min(netdev_mc_count(netdev), E100_MAX_MULTICAST_ADDRS); cb->command = cpu_to_le16(cb_multi); cb->u.multi.count = cpu_to_le16(count * ETH_ALEN); i = 0; netdev_for_each_mc_addr(ha, netdev) { if (i == count) break; memcpy(&cb->u.multi.addr[i++ * ETH_ALEN], &ha->addr, ETH_ALEN); } return 0; } static void e100_set_multicast_list(struct net_device *netdev) { struct nic *nic = netdev_priv(netdev); netif_printk(nic, hw, KERN_DEBUG, nic->netdev, "mc_count=%d, flags=0x%04X\n", netdev_mc_count(netdev), netdev->flags); if (netdev->flags & IFF_PROMISC) nic->flags |= promiscuous; else nic->flags &= ~promiscuous; if (netdev->flags & IFF_ALLMULTI || netdev_mc_count(netdev) > E100_MAX_MULTICAST_ADDRS) nic->flags |= multicast_all; else nic->flags &= ~multicast_all; e100_exec_cb(nic, NULL, e100_configure); e100_exec_cb(nic, NULL, e100_multi); } static void e100_update_stats(struct nic *nic) { struct net_device *dev = nic->netdev; struct net_device_stats *ns = &dev->stats; struct stats *s = &nic->mem->stats; __le32 *complete = (nic->mac < mac_82558_D101_A4) ? &s->fc_xmt_pause : (nic->mac < mac_82559_D101M) ? (__le32 *)&s->xmt_tco_frames : &s->complete; /* Device's stats reporting may take several microseconds to * complete, so we're always waiting for results of the * previous command. */ if (*complete == cpu_to_le32(cuc_dump_reset_complete)) { *complete = 0; nic->tx_frames = le32_to_cpu(s->tx_good_frames); nic->tx_collisions = le32_to_cpu(s->tx_total_collisions); ns->tx_aborted_errors += le32_to_cpu(s->tx_max_collisions); ns->tx_window_errors += le32_to_cpu(s->tx_late_collisions); ns->tx_carrier_errors += le32_to_cpu(s->tx_lost_crs); ns->tx_fifo_errors += le32_to_cpu(s->tx_underruns); ns->collisions += nic->tx_collisions; ns->tx_errors += le32_to_cpu(s->tx_max_collisions) + le32_to_cpu(s->tx_lost_crs); nic->rx_short_frame_errors += le32_to_cpu(s->rx_short_frame_errors); ns->rx_length_errors = nic->rx_short_frame_errors + nic->rx_over_length_errors; ns->rx_crc_errors += le32_to_cpu(s->rx_crc_errors); ns->rx_frame_errors += le32_to_cpu(s->rx_alignment_errors); ns->rx_over_errors += le32_to_cpu(s->rx_overrun_errors); ns->rx_fifo_errors += le32_to_cpu(s->rx_overrun_errors); ns->rx_missed_errors += le32_to_cpu(s->rx_resource_errors); ns->rx_errors += le32_to_cpu(s->rx_crc_errors) + le32_to_cpu(s->rx_alignment_errors) + le32_to_cpu(s->rx_short_frame_errors) + le32_to_cpu(s->rx_cdt_errors); nic->tx_deferred += le32_to_cpu(s->tx_deferred); nic->tx_single_collisions += le32_to_cpu(s->tx_single_collisions); nic->tx_multiple_collisions += le32_to_cpu(s->tx_multiple_collisions); if (nic->mac >= mac_82558_D101_A4) { nic->tx_fc_pause += le32_to_cpu(s->fc_xmt_pause); nic->rx_fc_pause += le32_to_cpu(s->fc_rcv_pause); nic->rx_fc_unsupported += le32_to_cpu(s->fc_rcv_unsupported); if (nic->mac >= mac_82559_D101M) { nic->tx_tco_frames += le16_to_cpu(s->xmt_tco_frames); nic->rx_tco_frames += le16_to_cpu(s->rcv_tco_frames); } } } if (e100_exec_cmd(nic, cuc_dump_reset, 0)) netif_printk(nic, tx_err, KERN_DEBUG, nic->netdev, "exec cuc_dump_reset failed\n"); } static void e100_adjust_adaptive_ifs(struct nic *nic, int speed, int duplex) { /* Adjust inter-frame-spacing (IFS) between two transmits if * we're getting collisions on a half-duplex connection. */ if (duplex == DUPLEX_HALF) { u32 prev = nic->adaptive_ifs; u32 min_frames = (speed == SPEED_100) ? 1000 : 100; if ((nic->tx_frames / 32 < nic->tx_collisions) && (nic->tx_frames > min_frames)) { if (nic->adaptive_ifs < 60) nic->adaptive_ifs += 5; } else if (nic->tx_frames < min_frames) { if (nic->adaptive_ifs >= 5) nic->adaptive_ifs -= 5; } if (nic->adaptive_ifs != prev) e100_exec_cb(nic, NULL, e100_configure); } } static void e100_watchdog(struct timer_list *t) { struct nic *nic = from_timer(nic, t, watchdog); struct ethtool_cmd cmd = { .cmd = ETHTOOL_GSET }; u32 speed; netif_printk(nic, timer, KERN_DEBUG, nic->netdev, "right now = %ld\n", jiffies); /* mii library handles link maintenance tasks */ mii_ethtool_gset(&nic->mii, &cmd); speed = ethtool_cmd_speed(&cmd); if (mii_link_ok(&nic->mii) && !netif_carrier_ok(nic->netdev)) { netdev_info(nic->netdev, "NIC Link is Up %u Mbps %s Duplex\n", speed == SPEED_100 ? 100 : 10, cmd.duplex == DUPLEX_FULL ? "Full" : "Half"); } else if (!mii_link_ok(&nic->mii) && netif_carrier_ok(nic->netdev)) { netdev_info(nic->netdev, "NIC Link is Down\n"); } mii_check_link(&nic->mii); /* Software generated interrupt to recover from (rare) Rx * allocation failure. * Unfortunately have to use a spinlock to not re-enable interrupts * accidentally, due to hardware that shares a register between the * interrupt mask bit and the SW Interrupt generation bit */ spin_lock_irq(&nic->cmd_lock); iowrite8(ioread8(&nic->csr->scb.cmd_hi) | irq_sw_gen,&nic->csr->scb.cmd_hi); e100_write_flush(nic); spin_unlock_irq(&nic->cmd_lock); e100_update_stats(nic); e100_adjust_adaptive_ifs(nic, speed, cmd.duplex); if (nic->mac <= mac_82557_D100_C) /* Issue a multicast command to workaround a 557 lock up */ e100_set_multicast_list(nic->netdev); if (nic->flags & ich && speed == SPEED_10 && cmd.duplex == DUPLEX_HALF) /* Need SW workaround for ICH[x] 10Mbps/half duplex Tx hang. */ nic->flags |= ich_10h_workaround; else nic->flags &= ~ich_10h_workaround; mod_timer(&nic->watchdog, round_jiffies(jiffies + E100_WATCHDOG_PERIOD)); } static int e100_xmit_prepare(struct nic *nic, struct cb *cb, struct sk_buff *skb) { dma_addr_t dma_addr; cb->command = nic->tx_command; dma_addr = dma_map_single(&nic->pdev->dev, skb->data, skb->len, DMA_TO_DEVICE); /* If we can't map the skb, have the upper layer try later */ if (dma_mapping_error(&nic->pdev->dev, dma_addr)) return -ENOMEM; /* * Use the last 4 bytes of the SKB payload packet as the CRC, used for * testing, ie sending frames with bad CRC. */ if (unlikely(skb->no_fcs)) cb->command |= cpu_to_le16(cb_tx_nc); else cb->command &= ~cpu_to_le16(cb_tx_nc); /* interrupt every 16 packets regardless of delay */ if ((nic->cbs_avail & ~15) == nic->cbs_avail) cb->command |= cpu_to_le16(cb_i); cb->u.tcb.tbd_array = cb->dma_addr + offsetof(struct cb, u.tcb.tbd); cb->u.tcb.tcb_byte_count = 0; cb->u.tcb.threshold = nic->tx_threshold; cb->u.tcb.tbd_count = 1; cb->u.tcb.tbd.buf_addr = cpu_to_le32(dma_addr); cb->u.tcb.tbd.size = cpu_to_le16(skb->len); skb_tx_timestamp(skb); return 0; } static netdev_tx_t e100_xmit_frame(struct sk_buff *skb, struct net_device *netdev) { struct nic *nic = netdev_priv(netdev); int err; if (nic->flags & ich_10h_workaround) { /* SW workaround for ICH[x] 10Mbps/half duplex Tx hang. Issue a NOP command followed by a 1us delay before issuing the Tx command. */ if (e100_exec_cmd(nic, cuc_nop, 0)) netif_printk(nic, tx_err, KERN_DEBUG, nic->netdev, "exec cuc_nop failed\n"); udelay(1); } err = e100_exec_cb(nic, skb, e100_xmit_prepare); switch (err) { case -ENOSPC: /* We queued the skb, but now we're out of space. */ netif_printk(nic, tx_err, KERN_DEBUG, nic->netdev, "No space for CB\n"); netif_stop_queue(netdev); break; case -ENOMEM: /* This is a hard error - log it. */ netif_printk(nic, tx_err, KERN_DEBUG, nic->netdev, "Out of Tx resources, returning skb\n"); netif_stop_queue(netdev); return NETDEV_TX_BUSY; } return NETDEV_TX_OK; } static int e100_tx_clean(struct nic *nic) { struct net_device *dev = nic->netdev; struct cb *cb; int tx_cleaned = 0; spin_lock(&nic->cb_lock); /* Clean CBs marked complete */ for (cb = nic->cb_to_clean; cb->status & cpu_to_le16(cb_complete); cb = nic->cb_to_clean = cb->next) { dma_rmb(); /* read skb after status */ netif_printk(nic, tx_done, KERN_DEBUG, nic->netdev, "cb[%d]->status = 0x%04X\n", (int)(((void*)cb - (void*)nic->cbs)/sizeof(struct cb)), cb->status); if (likely(cb->skb != NULL)) { dev->stats.tx_packets++; dev->stats.tx_bytes += cb->skb->len; dma_unmap_single(&nic->pdev->dev, le32_to_cpu(cb->u.tcb.tbd.buf_addr), le16_to_cpu(cb->u.tcb.tbd.size), DMA_TO_DEVICE); dev_kfree_skb_any(cb->skb); cb->skb = NULL; tx_cleaned = 1; } cb->status = 0; nic->cbs_avail++; } spin_unlock(&nic->cb_lock); /* Recover from running out of Tx resources in xmit_frame */ if (unlikely(tx_cleaned && netif_queue_stopped(nic->netdev))) netif_wake_queue(nic->netdev); return tx_cleaned; } static void e100_clean_cbs(struct nic *nic) { if (nic->cbs) { while (nic->cbs_avail != nic->params.cbs.count) { struct cb *cb = nic->cb_to_clean; if (cb->skb) { dma_unmap_single(&nic->pdev->dev, le32_to_cpu(cb->u.tcb.tbd.buf_addr), le16_to_cpu(cb->u.tcb.tbd.size), DMA_TO_DEVICE); dev_kfree_skb(cb->skb); } nic->cb_to_clean = nic->cb_to_clean->next; nic->cbs_avail++; } dma_pool_free(nic->cbs_pool, nic->cbs, nic->cbs_dma_addr); nic->cbs = NULL; nic->cbs_avail = 0; } nic->cuc_cmd = cuc_start; nic->cb_to_use = nic->cb_to_send = nic->cb_to_clean = nic->cbs; } static int e100_alloc_cbs(struct nic *nic) { struct cb *cb; unsigned int i, count = nic->params.cbs.count; nic->cuc_cmd = cuc_start; nic->cb_to_use = nic->cb_to_send = nic->cb_to_clean = NULL; nic->cbs_avail = 0; nic->cbs = dma_pool_zalloc(nic->cbs_pool, GFP_KERNEL, &nic->cbs_dma_addr); if (!nic->cbs) return -ENOMEM; for (cb = nic->cbs, i = 0; i < count; cb++, i++) { cb->next = (i + 1 < count) ? cb + 1 : nic->cbs; cb->prev = (i == 0) ? nic->cbs + count - 1 : cb - 1; cb->dma_addr = nic->cbs_dma_addr + i * sizeof(struct cb); cb->link = cpu_to_le32(nic->cbs_dma_addr + ((i+1) % count) * sizeof(struct cb)); } nic->cb_to_use = nic->cb_to_send = nic->cb_to_clean = nic->cbs; nic->cbs_avail = count; return 0; } static inline void e100_start_receiver(struct nic *nic, struct rx *rx) { if (!nic->rxs) return; if (RU_SUSPENDED != nic->ru_running) return; /* handle init time starts */ if (!rx) rx = nic->rxs; /* (Re)start RU if suspended or idle and RFA is non-NULL */ if (rx->skb) { e100_exec_cmd(nic, ruc_start, rx->dma_addr); nic->ru_running = RU_RUNNING; } } #define RFD_BUF_LEN (sizeof(struct rfd) + VLAN_ETH_FRAME_LEN + ETH_FCS_LEN) static int e100_rx_alloc_skb(struct nic *nic, struct rx *rx) { if (!(rx->skb = netdev_alloc_skb_ip_align(nic->netdev, RFD_BUF_LEN))) return -ENOMEM; /* Init, and map the RFD. */ skb_copy_to_linear_data(rx->skb, &nic->blank_rfd, sizeof(struct rfd)); rx->dma_addr = dma_map_single(&nic->pdev->dev, rx->skb->data, RFD_BUF_LEN, DMA_BIDIRECTIONAL); if (dma_mapping_error(&nic->pdev->dev, rx->dma_addr)) { dev_kfree_skb_any(rx->skb); rx->skb = NULL; rx->dma_addr = 0; return -ENOMEM; } /* Link the RFD to end of RFA by linking previous RFD to * this one. We are safe to touch the previous RFD because * it is protected by the before last buffer's el bit being set */ if (rx->prev->skb) { struct rfd *prev_rfd = (struct rfd *)rx->prev->skb->data; put_unaligned_le32(rx->dma_addr, &prev_rfd->link); dma_sync_single_for_device(&nic->pdev->dev, rx->prev->dma_addr, sizeof(struct rfd), DMA_BIDIRECTIONAL); } return 0; } static int e100_rx_indicate(struct nic *nic, struct rx *rx, unsigned int *work_done, unsigned int work_to_do) { struct net_device *dev = nic->netdev; struct sk_buff *skb = rx->skb; struct rfd *rfd = (struct rfd *)skb->data; u16 rfd_status, actual_size; u16 fcs_pad = 0; if (unlikely(work_done && *work_done >= work_to_do)) return -EAGAIN; /* Need to sync before taking a peek at cb_complete bit */ dma_sync_single_for_cpu(&nic->pdev->dev, rx->dma_addr, sizeof(struct rfd), DMA_BIDIRECTIONAL); rfd_status = le16_to_cpu(rfd->status); netif_printk(nic, rx_status, KERN_DEBUG, nic->netdev, "status=0x%04X\n", rfd_status); dma_rmb(); /* read size after status bit */ /* If data isn't ready, nothing to indicate */ if (unlikely(!(rfd_status & cb_complete))) { /* If the next buffer has the el bit, but we think the receiver * is still running, check to see if it really stopped while * we had interrupts off. * This allows for a fast restart without re-enabling * interrupts */ if ((le16_to_cpu(rfd->command) & cb_el) && (RU_RUNNING == nic->ru_running)) if (ioread8(&nic->csr->scb.status) & rus_no_res) nic->ru_running = RU_SUSPENDED; dma_sync_single_for_device(&nic->pdev->dev, rx->dma_addr, sizeof(struct rfd), DMA_FROM_DEVICE); return -ENODATA; } /* Get actual data size */ if (unlikely(dev->features & NETIF_F_RXFCS)) fcs_pad = 4; actual_size = le16_to_cpu(rfd->actual_size) & 0x3FFF; if (unlikely(actual_size > RFD_BUF_LEN - sizeof(struct rfd))) actual_size = RFD_BUF_LEN - sizeof(struct rfd); /* Get data */ dma_unmap_single(&nic->pdev->dev, rx->dma_addr, RFD_BUF_LEN, DMA_BIDIRECTIONAL); /* If this buffer has the el bit, but we think the receiver * is still running, check to see if it really stopped while * we had interrupts off. * This allows for a fast restart without re-enabling interrupts. * This can happen when the RU sees the size change but also sees * the el bit set. */ if ((le16_to_cpu(rfd->command) & cb_el) && (RU_RUNNING == nic->ru_running)) { if (ioread8(&nic->csr->scb.status) & rus_no_res) nic->ru_running = RU_SUSPENDED; } /* Pull off the RFD and put the actual data (minus eth hdr) */ skb_reserve(skb, sizeof(struct rfd)); skb_put(skb, actual_size); skb->protocol = eth_type_trans(skb, nic->netdev); /* If we are receiving all frames, then don't bother * checking for errors. */ if (unlikely(dev->features & NETIF_F_RXALL)) { if (actual_size > ETH_DATA_LEN + VLAN_ETH_HLEN + fcs_pad) /* Received oversized frame, but keep it. */ nic->rx_over_length_errors++; goto process_skb; } if (unlikely(!(rfd_status & cb_ok))) { /* Don't indicate if hardware indicates errors */ dev_kfree_skb_any(skb); } else if (actual_size > ETH_DATA_LEN + VLAN_ETH_HLEN + fcs_pad) { /* Don't indicate oversized frames */ nic->rx_over_length_errors++; dev_kfree_skb_any(skb); } else { process_skb: dev->stats.rx_packets++; dev->stats.rx_bytes += (actual_size - fcs_pad); netif_receive_skb(skb); if (work_done) (*work_done)++; } rx->skb = NULL; return 0; } static void e100_rx_clean(struct nic *nic, unsigned int *work_done, unsigned int work_to_do) { struct rx *rx; int restart_required = 0, err = 0; struct rx *old_before_last_rx, *new_before_last_rx; struct rfd *old_before_last_rfd, *new_before_last_rfd; /* Indicate newly arrived packets */ for (rx = nic->rx_to_clean; rx->skb; rx = nic->rx_to_clean = rx->next) { err = e100_rx_indicate(nic, rx, work_done, work_to_do); /* Hit quota or no more to clean */ if (-EAGAIN == err || -ENODATA == err) break; } /* On EAGAIN, hit quota so have more work to do, restart once * cleanup is complete. * Else, are we already rnr? then pay attention!!! this ensures that * the state machine progression never allows a start with a * partially cleaned list, avoiding a race between hardware * and rx_to_clean when in NAPI mode */ if (-EAGAIN != err && RU_SUSPENDED == nic->ru_running) restart_required = 1; old_before_last_rx = nic->rx_to_use->prev->prev; old_before_last_rfd = (struct rfd *)old_before_last_rx->skb->data; /* Alloc new skbs to refill list */ for (rx = nic->rx_to_use; !rx->skb; rx = nic->rx_to_use = rx->next) { if (unlikely(e100_rx_alloc_skb(nic, rx))) break; /* Better luck next time (see watchdog) */ } new_before_last_rx = nic->rx_to_use->prev->prev; if (new_before_last_rx != old_before_last_rx) { /* Set the el-bit on the buffer that is before the last buffer. * This lets us update the next pointer on the last buffer * without worrying about hardware touching it. * We set the size to 0 to prevent hardware from touching this * buffer. * When the hardware hits the before last buffer with el-bit * and size of 0, it will RNR interrupt, the RUS will go into * the No Resources state. It will not complete nor write to * this buffer. */ new_before_last_rfd = (struct rfd *)new_before_last_rx->skb->data; new_before_last_rfd->size = 0; new_before_last_rfd->command |= cpu_to_le16(cb_el); dma_sync_single_for_device(&nic->pdev->dev, new_before_last_rx->dma_addr, sizeof(struct rfd), DMA_BIDIRECTIONAL); /* Now that we have a new stopping point, we can clear the old * stopping point. We must sync twice to get the proper * ordering on the hardware side of things. */ old_before_last_rfd->command &= ~cpu_to_le16(cb_el); dma_sync_single_for_device(&nic->pdev->dev, old_before_last_rx->dma_addr, sizeof(struct rfd), DMA_BIDIRECTIONAL); old_before_last_rfd->size = cpu_to_le16(VLAN_ETH_FRAME_LEN + ETH_FCS_LEN); dma_sync_single_for_device(&nic->pdev->dev, old_before_last_rx->dma_addr, sizeof(struct rfd), DMA_BIDIRECTIONAL); } if (restart_required) { // ack the rnr? iowrite8(stat_ack_rnr, &nic->csr->scb.stat_ack); e100_start_receiver(nic, nic->rx_to_clean); if (work_done) (*work_done)++; } } static void e100_rx_clean_list(struct nic *nic) { struct rx *rx; unsigned int i, count = nic->params.rfds.count; nic->ru_running = RU_UNINITIALIZED; if (nic->rxs) { for (rx = nic->rxs, i = 0; i < count; rx++, i++) { if (rx->skb) { dma_unmap_single(&nic->pdev->dev, rx->dma_addr, RFD_BUF_LEN, DMA_BIDIRECTIONAL); dev_kfree_skb(rx->skb); } } kfree(nic->rxs); nic->rxs = NULL; } nic->rx_to_use = nic->rx_to_clean = NULL; } static int e100_rx_alloc_list(struct nic *nic) { struct rx *rx; unsigned int i, count = nic->params.rfds.count; struct rfd *before_last; nic->rx_to_use = nic->rx_to_clean = NULL; nic->ru_running = RU_UNINITIALIZED; if (!(nic->rxs = kcalloc(count, sizeof(struct rx), GFP_KERNEL))) return -ENOMEM; for (rx = nic->rxs, i = 0; i < count; rx++, i++) { rx->next = (i + 1 < count) ? rx + 1 : nic->rxs; rx->prev = (i == 0) ? nic->rxs + count - 1 : rx - 1; if (e100_rx_alloc_skb(nic, rx)) { e100_rx_clean_list(nic); return -ENOMEM; } } /* Set the el-bit on the buffer that is before the last buffer. * This lets us update the next pointer on the last buffer without * worrying about hardware touching it. * We set the size to 0 to prevent hardware from touching this buffer. * When the hardware hits the before last buffer with el-bit and size * of 0, it will RNR interrupt, the RU will go into the No Resources * state. It will not complete nor write to this buffer. */ rx = nic->rxs->prev->prev; before_last = (struct rfd *)rx->skb->data; before_last->command |= cpu_to_le16(cb_el); before_last->size = 0; dma_sync_single_for_device(&nic->pdev->dev, rx->dma_addr, sizeof(struct rfd), DMA_BIDIRECTIONAL); nic->rx_to_use = nic->rx_to_clean = nic->rxs; nic->ru_running = RU_SUSPENDED; return 0; } static irqreturn_t e100_intr(int irq, void *dev_id) { struct net_device *netdev = dev_id; struct nic *nic = netdev_priv(netdev); u8 stat_ack = ioread8(&nic->csr->scb.stat_ack); netif_printk(nic, intr, KERN_DEBUG, nic->netdev, "stat_ack = 0x%02X\n", stat_ack); if (stat_ack == stat_ack_not_ours || /* Not our interrupt */ stat_ack == stat_ack_not_present) /* Hardware is ejected */ return IRQ_NONE; /* Ack interrupt(s) */ iowrite8(stat_ack, &nic->csr->scb.stat_ack); /* We hit Receive No Resource (RNR); restart RU after cleaning */ if (stat_ack & stat_ack_rnr) nic->ru_running = RU_SUSPENDED; if (likely(napi_schedule_prep(&nic->napi))) { e100_disable_irq(nic); __napi_schedule(&nic->napi); } return IRQ_HANDLED; } static int e100_poll(struct napi_struct *napi, int budget) { struct nic *nic = container_of(napi, struct nic, napi); unsigned int work_done = 0; e100_rx_clean(nic, &work_done, budget); e100_tx_clean(nic); /* If budget fully consumed, continue polling */ if (work_done == budget) return budget; /* only re-enable interrupt if stack agrees polling is really done */ if (likely(napi_complete_done(napi, work_done))) e100_enable_irq(nic); return work_done; } #ifdef CONFIG_NET_POLL_CONTROLLER static void e100_netpoll(struct net_device *netdev) { struct nic *nic = netdev_priv(netdev); e100_disable_irq(nic); e100_intr(nic->pdev->irq, netdev); e100_tx_clean(nic); e100_enable_irq(nic); } #endif static int e100_set_mac_address(struct net_device *netdev, void *p) { struct nic *nic = netdev_priv(netdev); struct sockaddr *addr = p; if (!is_valid_ether_addr(addr->sa_data)) return -EADDRNOTAVAIL; eth_hw_addr_set(netdev, addr->sa_data); e100_exec_cb(nic, NULL, e100_setup_iaaddr); return 0; } static int e100_asf(struct nic *nic) { /* ASF can be enabled from eeprom */ return (nic->pdev->device >= 0x1050) && (nic->pdev->device <= 0x1057) && (le16_to_cpu(nic->eeprom[eeprom_config_asf]) & eeprom_asf) && !(le16_to_cpu(nic->eeprom[eeprom_config_asf]) & eeprom_gcl) && ((le16_to_cpu(nic->eeprom[eeprom_smbus_addr]) & 0xFF) != 0xFE); } static int e100_up(struct nic *nic) { int err; if ((err = e100_rx_alloc_list(nic))) return err; if ((err = e100_alloc_cbs(nic))) goto err_rx_clean_list; if ((err = e100_hw_init(nic))) goto err_clean_cbs; e100_set_multicast_list(nic->netdev); e100_start_receiver(nic, NULL); mod_timer(&nic->watchdog, jiffies); if ((err = request_irq(nic->pdev->irq, e100_intr, IRQF_SHARED, nic->netdev->name, nic->netdev))) goto err_no_irq; netif_wake_queue(nic->netdev); napi_enable(&nic->napi); /* enable ints _after_ enabling poll, preventing a race between * disable ints+schedule */ e100_enable_irq(nic); return 0; err_no_irq: del_timer_sync(&nic->watchdog); err_clean_cbs: e100_clean_cbs(nic); err_rx_clean_list: e100_rx_clean_list(nic); return err; } static void e100_down(struct nic *nic) { /* wait here for poll to complete */ napi_disable(&nic->napi); netif_stop_queue(nic->netdev); e100_hw_reset(nic); free_irq(nic->pdev->irq, nic->netdev); del_timer_sync(&nic->watchdog); netif_carrier_off(nic->netdev); e100_clean_cbs(nic); e100_rx_clean_list(nic); } static void e100_tx_timeout(struct net_device *netdev, unsigned int txqueue) { struct nic *nic = netdev_priv(netdev); /* Reset outside of interrupt context, to avoid request_irq * in interrupt context */ schedule_work(&nic->tx_timeout_task); } static void e100_tx_timeout_task(struct work_struct *work) { struct nic *nic = container_of(work, struct nic, tx_timeout_task); struct net_device *netdev = nic->netdev; netif_printk(nic, tx_err, KERN_DEBUG, nic->netdev, "scb.status=0x%02X\n", ioread8(&nic->csr->scb.status)); rtnl_lock(); if (netif_running(netdev)) { e100_down(netdev_priv(netdev)); e100_up(netdev_priv(netdev)); } rtnl_unlock(); } static int e100_loopback_test(struct nic *nic, enum loopback loopback_mode) { int err; struct sk_buff *skb; /* Use driver resources to perform internal MAC or PHY * loopback test. A single packet is prepared and transmitted * in loopback mode, and the test passes if the received * packet compares byte-for-byte to the transmitted packet. */ if ((err = e100_rx_alloc_list(nic))) return err; if ((err = e100_alloc_cbs(nic))) goto err_clean_rx; /* ICH PHY loopback is broken so do MAC loopback instead */ if (nic->flags & ich && loopback_mode == lb_phy) loopback_mode = lb_mac; nic->loopback = loopback_mode; if ((err = e100_hw_init(nic))) goto err_loopback_none; if (loopback_mode == lb_phy) mdio_write(nic->netdev, nic->mii.phy_id, MII_BMCR, BMCR_LOOPBACK); e100_start_receiver(nic, NULL); if (!(skb = netdev_alloc_skb(nic->netdev, ETH_DATA_LEN))) { err = -ENOMEM; goto err_loopback_none; } skb_put(skb, ETH_DATA_LEN); memset(skb->data, 0xFF, ETH_DATA_LEN); e100_xmit_frame(skb, nic->netdev); msleep(10); dma_sync_single_for_cpu(&nic->pdev->dev, nic->rx_to_clean->dma_addr, RFD_BUF_LEN, DMA_BIDIRECTIONAL); if (memcmp(nic->rx_to_clean->skb->data + sizeof(struct rfd), skb->data, ETH_DATA_LEN)) err = -EAGAIN; err_loopback_none: mdio_write(nic->netdev, nic->mii.phy_id, MII_BMCR, 0); nic->loopback = lb_none; e100_clean_cbs(nic); e100_hw_reset(nic); err_clean_rx: e100_rx_clean_list(nic); return err; } #define MII_LED_CONTROL 0x1B #define E100_82552_LED_OVERRIDE 0x19 #define E100_82552_LED_ON 0x000F /* LEDTX and LED_RX both on */ #define E100_82552_LED_OFF 0x000A /* LEDTX and LED_RX both off */ static int e100_get_link_ksettings(struct net_device *netdev, struct ethtool_link_ksettings *cmd) { struct nic *nic = netdev_priv(netdev); mii_ethtool_get_link_ksettings(&nic->mii, cmd); return 0; } static int e100_set_link_ksettings(struct net_device *netdev, const struct ethtool_link_ksettings *cmd) { struct nic *nic = netdev_priv(netdev); int err; mdio_write(netdev, nic->mii.phy_id, MII_BMCR, BMCR_RESET); err = mii_ethtool_set_link_ksettings(&nic->mii, cmd); e100_exec_cb(nic, NULL, e100_configure); return err; } static void e100_get_drvinfo(struct net_device *netdev, struct ethtool_drvinfo *info) { struct nic *nic = netdev_priv(netdev); strscpy(info->driver, DRV_NAME, sizeof(info->driver)); strscpy(info->bus_info, pci_name(nic->pdev), sizeof(info->bus_info)); } #define E100_PHY_REGS 0x1D static int e100_get_regs_len(struct net_device *netdev) { struct nic *nic = netdev_priv(netdev); /* We know the number of registers, and the size of the dump buffer. * Calculate the total size in bytes. */ return (1 + E100_PHY_REGS) * sizeof(u32) + sizeof(nic->mem->dump_buf); } static void e100_get_regs(struct net_device *netdev, struct ethtool_regs *regs, void *p) { struct nic *nic = netdev_priv(netdev); u32 *buff = p; int i; regs->version = (1 << 24) | nic->pdev->revision; buff[0] = ioread8(&nic->csr->scb.cmd_hi) << 24 | ioread8(&nic->csr->scb.cmd_lo) << 16 | ioread16(&nic->csr->scb.status); for (i = 0; i < E100_PHY_REGS; i++) /* Note that we read the registers in reverse order. This * ordering is the ABI apparently used by ethtool and other * applications. */ buff[1 + i] = mdio_read(netdev, nic->mii.phy_id, E100_PHY_REGS - 1 - i); memset(nic->mem->dump_buf, 0, sizeof(nic->mem->dump_buf)); e100_exec_cb(nic, NULL, e100_dump); msleep(10); memcpy(&buff[1 + E100_PHY_REGS], nic->mem->dump_buf, sizeof(nic->mem->dump_buf)); } static void e100_get_wol(struct net_device *netdev, struct ethtool_wolinfo *wol) { struct nic *nic = netdev_priv(netdev); wol->supported = (nic->mac >= mac_82558_D101_A4) ? WAKE_MAGIC : 0; wol->wolopts = (nic->flags & wol_magic) ? WAKE_MAGIC : 0; } static int e100_set_wol(struct net_device *netdev, struct ethtool_wolinfo *wol) { struct nic *nic = netdev_priv(netdev); if ((wol->wolopts && wol->wolopts != WAKE_MAGIC) || !device_can_wakeup(&nic->pdev->dev)) return -EOPNOTSUPP; if (wol->wolopts) nic->flags |= wol_magic; else nic->flags &= ~wol_magic; device_set_wakeup_enable(&nic->pdev->dev, wol->wolopts); e100_exec_cb(nic, NULL, e100_configure); return 0; } static u32 e100_get_msglevel(struct net_device *netdev) { struct nic *nic = netdev_priv(netdev); return nic->msg_enable; } static void e100_set_msglevel(struct net_device *netdev, u32 value) { struct nic *nic = netdev_priv(netdev); nic->msg_enable = value; } static int e100_nway_reset(struct net_device *netdev) { struct nic *nic = netdev_priv(netdev); return mii_nway_restart(&nic->mii); } static u32 e100_get_link(struct net_device *netdev) { struct nic *nic = netdev_priv(netdev); return mii_link_ok(&nic->mii); } static int e100_get_eeprom_len(struct net_device *netdev) { struct nic *nic = netdev_priv(netdev); return nic->eeprom_wc << 1; } #define E100_EEPROM_MAGIC 0x1234 static int e100_get_eeprom(struct net_device *netdev, struct ethtool_eeprom *eeprom, u8 *bytes) { struct nic *nic = netdev_priv(netdev); eeprom->magic = E100_EEPROM_MAGIC; memcpy(bytes, &((u8 *)nic->eeprom)[eeprom->offset], eeprom->len); return 0; } static int e100_set_eeprom(struct net_device *netdev, struct ethtool_eeprom *eeprom, u8 *bytes) { struct nic *nic = netdev_priv(netdev); if (eeprom->magic != E100_EEPROM_MAGIC) return -EINVAL; memcpy(&((u8 *)nic->eeprom)[eeprom->offset], bytes, eeprom->len); return e100_eeprom_save(nic, eeprom->offset >> 1, (eeprom->len >> 1) + 1); } static void e100_get_ringparam(struct net_device *netdev, struct ethtool_ringparam *ring, struct kernel_ethtool_ringparam *kernel_ring, struct netlink_ext_ack *extack) { struct nic *nic = netdev_priv(netdev); struct param_range *rfds = &nic->params.rfds; struct param_range *cbs = &nic->params.cbs; ring->rx_max_pending = rfds->max; ring->tx_max_pending = cbs->max; ring->rx_pending = rfds->count; ring->tx_pending = cbs->count; } static int e100_set_ringparam(struct net_device *netdev, struct ethtool_ringparam *ring, struct kernel_ethtool_ringparam *kernel_ring, struct netlink_ext_ack *extack) { struct nic *nic = netdev_priv(netdev); struct param_range *rfds = &nic->params.rfds; struct param_range *cbs = &nic->params.cbs; if ((ring->rx_mini_pending) || (ring->rx_jumbo_pending)) return -EINVAL; if (netif_running(netdev)) e100_down(nic); rfds->count = max(ring->rx_pending, rfds->min); rfds->count = min(rfds->count, rfds->max); cbs->count = max(ring->tx_pending, cbs->min); cbs->count = min(cbs->count, cbs->max); netif_info(nic, drv, nic->netdev, "Ring Param settings: rx: %d, tx %d\n", rfds->count, cbs->count); if (netif_running(netdev)) e100_up(nic); return 0; } static const char e100_gstrings_test[][ETH_GSTRING_LEN] = { "Link test (on/offline)", "Eeprom test (on/offline)", "Self test (offline)", "Mac loopback (offline)", "Phy loopback (offline)", }; #define E100_TEST_LEN ARRAY_SIZE(e100_gstrings_test) static void e100_diag_test(struct net_device *netdev, struct ethtool_test *test, u64 *data) { struct ethtool_cmd cmd; struct nic *nic = netdev_priv(netdev); int i; memset(data, 0, E100_TEST_LEN * sizeof(u64)); data[0] = !mii_link_ok(&nic->mii); data[1] = e100_eeprom_load(nic); if (test->flags & ETH_TEST_FL_OFFLINE) { /* save speed, duplex & autoneg settings */ mii_ethtool_gset(&nic->mii, &cmd); if (netif_running(netdev)) e100_down(nic); data[2] = e100_self_test(nic); data[3] = e100_loopback_test(nic, lb_mac); data[4] = e100_loopback_test(nic, lb_phy); /* restore speed, duplex & autoneg settings */ mii_ethtool_sset(&nic->mii, &cmd); if (netif_running(netdev)) e100_up(nic); } for (i = 0; i < E100_TEST_LEN; i++) test->flags |= data[i] ? ETH_TEST_FL_FAILED : 0; msleep_interruptible(4 * 1000); } static int e100_set_phys_id(struct net_device *netdev, enum ethtool_phys_id_state state) { struct nic *nic = netdev_priv(netdev); enum led_state { led_on = 0x01, led_off = 0x04, led_on_559 = 0x05, led_on_557 = 0x07, }; u16 led_reg = (nic->phy == phy_82552_v) ? E100_82552_LED_OVERRIDE : MII_LED_CONTROL; u16 leds = 0; switch (state) { case ETHTOOL_ID_ACTIVE: return 2; case ETHTOOL_ID_ON: leds = (nic->phy == phy_82552_v) ? E100_82552_LED_ON : (nic->mac < mac_82559_D101M) ? led_on_557 : led_on_559; break; case ETHTOOL_ID_OFF: leds = (nic->phy == phy_82552_v) ? E100_82552_LED_OFF : led_off; break; case ETHTOOL_ID_INACTIVE: break; } mdio_write(netdev, nic->mii.phy_id, led_reg, leds); return 0; } static const char e100_gstrings_stats[][ETH_GSTRING_LEN] = { "rx_packets", "tx_packets", "rx_bytes", "tx_bytes", "rx_errors", "tx_errors", "rx_dropped", "tx_dropped", "multicast", "collisions", "rx_length_errors", "rx_over_errors", "rx_crc_errors", "rx_frame_errors", "rx_fifo_errors", "rx_missed_errors", "tx_aborted_errors", "tx_carrier_errors", "tx_fifo_errors", "tx_heartbeat_errors", "tx_window_errors", /* device-specific stats */ "tx_deferred", "tx_single_collisions", "tx_multi_collisions", "tx_flow_control_pause", "rx_flow_control_pause", "rx_flow_control_unsupported", "tx_tco_packets", "rx_tco_packets", "rx_short_frame_errors", "rx_over_length_errors", }; #define E100_NET_STATS_LEN 21 #define E100_STATS_LEN ARRAY_SIZE(e100_gstrings_stats) static int e100_get_sset_count(struct net_device *netdev, int sset) { switch (sset) { case ETH_SS_TEST: return E100_TEST_LEN; case ETH_SS_STATS: return E100_STATS_LEN; default: return -EOPNOTSUPP; } } static void e100_get_ethtool_stats(struct net_device *netdev, struct ethtool_stats *stats, u64 *data) { struct nic *nic = netdev_priv(netdev); int i; for (i = 0; i < E100_NET_STATS_LEN; i++) data[i] = ((unsigned long *)&netdev->stats)[i]; data[i++] = nic->tx_deferred; data[i++] = nic->tx_single_collisions; data[i++] = nic->tx_multiple_collisions; data[i++] = nic->tx_fc_pause; data[i++] = nic->rx_fc_pause; data[i++] = nic->rx_fc_unsupported; data[i++] = nic->tx_tco_frames; data[i++] = nic->rx_tco_frames; data[i++] = nic->rx_short_frame_errors; data[i++] = nic->rx_over_length_errors; } static void e100_get_strings(struct net_device *netdev, u32 stringset, u8 *data) { switch (stringset) { case ETH_SS_TEST: memcpy(data, e100_gstrings_test, sizeof(e100_gstrings_test)); break; case ETH_SS_STATS: memcpy(data, e100_gstrings_stats, sizeof(e100_gstrings_stats)); break; } } static const struct ethtool_ops e100_ethtool_ops = { .get_drvinfo = e100_get_drvinfo, .get_regs_len = e100_get_regs_len, .get_regs = e100_get_regs, .get_wol = e100_get_wol, .set_wol = e100_set_wol, .get_msglevel = e100_get_msglevel, .set_msglevel = e100_set_msglevel, .nway_reset = e100_nway_reset, .get_link = e100_get_link, .get_eeprom_len = e100_get_eeprom_len, .get_eeprom = e100_get_eeprom, .set_eeprom = e100_set_eeprom, .get_ringparam = e100_get_ringparam, .set_ringparam = e100_set_ringparam, .self_test = e100_diag_test, .get_strings = e100_get_strings, .set_phys_id = e100_set_phys_id, .get_ethtool_stats = e100_get_ethtool_stats, .get_sset_count = e100_get_sset_count, .get_ts_info = ethtool_op_get_ts_info, .get_link_ksettings = e100_get_link_ksettings, .set_link_ksettings = e100_set_link_ksettings, }; static int e100_do_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd) { struct nic *nic = netdev_priv(netdev); return generic_mii_ioctl(&nic->mii, if_mii(ifr), cmd, NULL); } static int e100_alloc(struct nic *nic) { nic->mem = dma_alloc_coherent(&nic->pdev->dev, sizeof(struct mem), &nic->dma_addr, GFP_KERNEL); return nic->mem ? 0 : -ENOMEM; } static void e100_free(struct nic *nic) { if (nic->mem) { dma_free_coherent(&nic->pdev->dev, sizeof(struct mem), nic->mem, nic->dma_addr); nic->mem = NULL; } } static int e100_open(struct net_device *netdev) { struct nic *nic = netdev_priv(netdev); int err = 0; netif_carrier_off(netdev); if ((err = e100_up(nic))) netif_err(nic, ifup, nic->netdev, "Cannot open interface, aborting\n"); return err; } static int e100_close(struct net_device *netdev) { e100_down(netdev_priv(netdev)); return 0; } static int e100_set_features(struct net_device *netdev, netdev_features_t features) { struct nic *nic = netdev_priv(netdev); netdev_features_t changed = features ^ netdev->features; if (!(changed & (NETIF_F_RXFCS | NETIF_F_RXALL))) return 0; netdev->features = features; e100_exec_cb(nic, NULL, e100_configure); return 1; } static const struct net_device_ops e100_netdev_ops = { .ndo_open = e100_open, .ndo_stop = e100_close, .ndo_start_xmit = e100_xmit_frame, .ndo_validate_addr = eth_validate_addr, .ndo_set_rx_mode = e100_set_multicast_list, .ndo_set_mac_address = e100_set_mac_address, .ndo_eth_ioctl = e100_do_ioctl, .ndo_tx_timeout = e100_tx_timeout, #ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = e100_netpoll, #endif .ndo_set_features = e100_set_features, }; static int e100_probe(struct pci_dev *pdev, const struct pci_device_id *ent) { struct net_device *netdev; struct nic *nic; int err; if (!(netdev = alloc_etherdev(sizeof(struct nic)))) return -ENOMEM; netdev->hw_features |= NETIF_F_RXFCS; netdev->priv_flags |= IFF_SUPP_NOFCS; netdev->hw_features |= NETIF_F_RXALL; netdev->netdev_ops = &e100_netdev_ops; netdev->ethtool_ops = &e100_ethtool_ops; netdev->watchdog_timeo = E100_WATCHDOG_PERIOD; strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1); nic = netdev_priv(netdev); netif_napi_add_weight(netdev, &nic->napi, e100_poll, E100_NAPI_WEIGHT); nic->netdev = netdev; nic->pdev = pdev; nic->msg_enable = (1 << debug) - 1; nic->mdio_ctrl = mdio_ctrl_hw; pci_set_drvdata(pdev, netdev); if ((err = pci_enable_device(pdev))) { netif_err(nic, probe, nic->netdev, "Cannot enable PCI device, aborting\n"); goto err_out_free_dev; } if (!(pci_resource_flags(pdev, 0) & IORESOURCE_MEM)) { netif_err(nic, probe, nic->netdev, "Cannot find proper PCI device base address, aborting\n"); err = -ENODEV; goto err_out_disable_pdev; } if ((err = pci_request_regions(pdev, DRV_NAME))) { netif_err(nic, probe, nic->netdev, "Cannot obtain PCI resources, aborting\n"); goto err_out_disable_pdev; } if ((err = dma_set_mask(&pdev->dev, DMA_BIT_MASK(32)))) { netif_err(nic, probe, nic->netdev, "No usable DMA configuration, aborting\n"); goto err_out_free_res; } SET_NETDEV_DEV(netdev, &pdev->dev); if (use_io) netif_info(nic, probe, nic->netdev, "using i/o access mode\n"); nic->csr = pci_iomap(pdev, (use_io ? 1 : 0), sizeof(struct csr)); if (!nic->csr) { netif_err(nic, probe, nic->netdev, "Cannot map device registers, aborting\n"); err = -ENOMEM; goto err_out_free_res; } if (ent->driver_data) nic->flags |= ich; else nic->flags &= ~ich; e100_get_defaults(nic); /* D100 MAC doesn't allow rx of vlan packets with normal MTU */ if (nic->mac < mac_82558_D101_A4) netdev->features |= NETIF_F_VLAN_CHALLENGED; /* locks must be initialized before calling hw_reset */ spin_lock_init(&nic->cb_lock); spin_lock_init(&nic->cmd_lock); spin_lock_init(&nic->mdio_lock); /* Reset the device before pci_set_master() in case device is in some * funky state and has an interrupt pending - hint: we don't have the * interrupt handler registered yet. */ e100_hw_reset(nic); pci_set_master(pdev); timer_setup(&nic->watchdog, e100_watchdog, 0); INIT_WORK(&nic->tx_timeout_task, e100_tx_timeout_task); if ((err = e100_alloc(nic))) { netif_err(nic, probe, nic->netdev, "Cannot alloc driver memory, aborting\n"); goto err_out_iounmap; } if ((err = e100_eeprom_load(nic))) goto err_out_free; e100_phy_init(nic); eth_hw_addr_set(netdev, (u8 *)nic->eeprom); if (!is_valid_ether_addr(netdev->dev_addr)) { if (!eeprom_bad_csum_allow) { netif_err(nic, probe, nic->netdev, "Invalid MAC address from EEPROM, aborting\n"); err = -EAGAIN; goto err_out_free; } else { netif_err(nic, probe, nic->netdev, "Invalid MAC address from EEPROM, you MUST configure one.\n"); } } /* Wol magic packet can be enabled from eeprom */ if ((nic->mac >= mac_82558_D101_A4) && (le16_to_cpu(nic->eeprom[eeprom_id]) & eeprom_id_wol)) { nic->flags |= wol_magic; device_set_wakeup_enable(&pdev->dev, true); } /* ack any pending wake events, disable PME */ pci_pme_active(pdev, false); strcpy(netdev->name, "eth%d"); if ((err = register_netdev(netdev))) { netif_err(nic, probe, nic->netdev, "Cannot register net device, aborting\n"); goto err_out_free; } nic->cbs_pool = dma_pool_create(netdev->name, &nic->pdev->dev, nic->params.cbs.max * sizeof(struct cb), sizeof(u32), 0); if (!nic->cbs_pool) { netif_err(nic, probe, nic->netdev, "Cannot create DMA pool, aborting\n"); err = -ENOMEM; goto err_out_pool; } netif_info(nic, probe, nic->netdev, "addr 0x%llx, irq %d, MAC addr %pM\n", (unsigned long long)pci_resource_start(pdev, use_io ? 1 : 0), pdev->irq, netdev->dev_addr); return 0; err_out_pool: unregister_netdev(netdev); err_out_free: e100_free(nic); err_out_iounmap: pci_iounmap(pdev, nic->csr); err_out_free_res: pci_release_regions(pdev); err_out_disable_pdev: pci_disable_device(pdev); err_out_free_dev: free_netdev(netdev); return err; } static void e100_remove(struct pci_dev *pdev) { struct net_device *netdev = pci_get_drvdata(pdev); if (netdev) { struct nic *nic = netdev_priv(netdev); unregister_netdev(netdev); e100_free(nic); pci_iounmap(pdev, nic->csr); dma_pool_destroy(nic->cbs_pool); free_netdev(netdev); pci_release_regions(pdev); pci_disable_device(pdev); } } #define E100_82552_SMARTSPEED 0x14 /* SmartSpeed Ctrl register */ #define E100_82552_REV_ANEG 0x0200 /* Reverse auto-negotiation */ #define E100_82552_ANEG_NOW 0x0400 /* Auto-negotiate now */ static void __e100_shutdown(struct pci_dev *pdev, bool *enable_wake) { struct net_device *netdev = pci_get_drvdata(pdev); struct nic *nic = netdev_priv(netdev); netif_device_detach(netdev); if (netif_running(netdev)) e100_down(nic); if ((nic->flags & wol_magic) | e100_asf(nic)) { /* enable reverse auto-negotiation */ if (nic->phy == phy_82552_v) { u16 smartspeed = mdio_read(netdev, nic->mii.phy_id, E100_82552_SMARTSPEED); mdio_write(netdev, nic->mii.phy_id, E100_82552_SMARTSPEED, smartspeed | E100_82552_REV_ANEG | E100_82552_ANEG_NOW); } *enable_wake = true; } else { *enable_wake = false; } pci_disable_device(pdev); } static int __e100_power_off(struct pci_dev *pdev, bool wake) { if (wake) return pci_prepare_to_sleep(pdev); pci_wake_from_d3(pdev, false); pci_set_power_state(pdev, PCI_D3hot); return 0; } static int __maybe_unused e100_suspend(struct device *dev_d) { bool wake; __e100_shutdown(to_pci_dev(dev_d), &wake); return 0; } static int __maybe_unused e100_resume(struct device *dev_d) { struct net_device *netdev = dev_get_drvdata(dev_d); struct nic *nic = netdev_priv(netdev); int err; err = pci_enable_device(to_pci_dev(dev_d)); if (err) { netdev_err(netdev, "Resume cannot enable PCI device, aborting\n"); return err; } pci_set_master(to_pci_dev(dev_d)); /* disable reverse auto-negotiation */ if (nic->phy == phy_82552_v) { u16 smartspeed = mdio_read(netdev, nic->mii.phy_id, E100_82552_SMARTSPEED); mdio_write(netdev, nic->mii.phy_id, E100_82552_SMARTSPEED, smartspeed & ~(E100_82552_REV_ANEG)); } if (netif_running(netdev)) e100_up(nic); netif_device_attach(netdev); return 0; } static void e100_shutdown(struct pci_dev *pdev) { bool wake; __e100_shutdown(pdev, &wake); if (system_state == SYSTEM_POWER_OFF) __e100_power_off(pdev, wake); } /* ------------------ PCI Error Recovery infrastructure -------------- */ /** * e100_io_error_detected - called when PCI error is detected. * @pdev: Pointer to PCI device * @state: The current pci connection state */ static pci_ers_result_t e100_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state) { struct net_device *netdev = pci_get_drvdata(pdev); struct nic *nic = netdev_priv(netdev); netif_device_detach(netdev); if (state == pci_channel_io_perm_failure) return PCI_ERS_RESULT_DISCONNECT; if (netif_running(netdev)) e100_down(nic); pci_disable_device(pdev); /* Request a slot reset. */ return PCI_ERS_RESULT_NEED_RESET; } /** * e100_io_slot_reset - called after the pci bus has been reset. * @pdev: Pointer to PCI device * * Restart the card from scratch. */ static pci_ers_result_t e100_io_slot_reset(struct pci_dev *pdev) { struct net_device *netdev = pci_get_drvdata(pdev); struct nic *nic = netdev_priv(netdev); if (pci_enable_device(pdev)) { pr_err("Cannot re-enable PCI device after reset\n"); return PCI_ERS_RESULT_DISCONNECT; } pci_set_master(pdev); /* Only one device per card can do a reset */ if (0 != PCI_FUNC(pdev->devfn)) return PCI_ERS_RESULT_RECOVERED; e100_hw_reset(nic); e100_phy_init(nic); return PCI_ERS_RESULT_RECOVERED; } /** * e100_io_resume - resume normal operations * @pdev: Pointer to PCI device * * Resume normal operations after an error recovery * sequence has been completed. */ static void e100_io_resume(struct pci_dev *pdev) { struct net_device *netdev = pci_get_drvdata(pdev); struct nic *nic = netdev_priv(netdev); /* ack any pending wake events, disable PME */ pci_enable_wake(pdev, PCI_D0, 0); netif_device_attach(netdev); if (netif_running(netdev)) { e100_open(netdev); mod_timer(&nic->watchdog, jiffies); } } static const struct pci_error_handlers e100_err_handler = { .error_detected = e100_io_error_detected, .slot_reset = e100_io_slot_reset, .resume = e100_io_resume, }; static SIMPLE_DEV_PM_OPS(e100_pm_ops, e100_suspend, e100_resume); static struct pci_driver e100_driver = { .name = DRV_NAME, .id_table = e100_id_table, .probe = e100_probe, .remove = e100_remove, /* Power Management hooks */ .driver.pm = &e100_pm_ops, .shutdown = e100_shutdown, .err_handler = &e100_err_handler, }; static int __init e100_init_module(void) { if (((1 << debug) - 1) & NETIF_MSG_DRV) { pr_info("%s\n", DRV_DESCRIPTION); pr_info("%s\n", DRV_COPYRIGHT); } return pci_register_driver(&e100_driver); } static void __exit e100_cleanup_module(void) { pci_unregister_driver(&e100_driver); } module_init(e100_init_module); module_exit(e100_cleanup_module);
linux-master
drivers/net/ethernet/intel/e100.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2020, Intel Corporation. */ #include <linux/if_vlan.h> #include <net/xdp_sock_drv.h> #include "igc.h" #include "igc_xdp.h" int igc_xdp_set_prog(struct igc_adapter *adapter, struct bpf_prog *prog, struct netlink_ext_ack *extack) { struct net_device *dev = adapter->netdev; bool if_running = netif_running(dev); struct bpf_prog *old_prog; if (dev->mtu > ETH_DATA_LEN) { /* For now, the driver doesn't support XDP functionality with * jumbo frames so we return error. */ NL_SET_ERR_MSG_MOD(extack, "Jumbo frames not supported"); return -EOPNOTSUPP; } if (if_running) igc_close(dev); old_prog = xchg(&adapter->xdp_prog, prog); if (old_prog) bpf_prog_put(old_prog); if (prog) xdp_features_set_redirect_target(dev, true); else xdp_features_clear_redirect_target(dev); if (if_running) igc_open(dev); return 0; } static int igc_xdp_enable_pool(struct igc_adapter *adapter, struct xsk_buff_pool *pool, u16 queue_id) { struct net_device *ndev = adapter->netdev; struct device *dev = &adapter->pdev->dev; struct igc_ring *rx_ring, *tx_ring; struct napi_struct *napi; bool needs_reset; u32 frame_size; int err; if (queue_id >= adapter->num_rx_queues || queue_id >= adapter->num_tx_queues) return -EINVAL; frame_size = xsk_pool_get_rx_frame_size(pool); if (frame_size < ETH_FRAME_LEN + VLAN_HLEN * 2) { /* When XDP is enabled, the driver doesn't support frames that * span over multiple buffers. To avoid that, we check if xsk * frame size is big enough to fit the max ethernet frame size * + vlan double tagging. */ return -EOPNOTSUPP; } err = xsk_pool_dma_map(pool, dev, IGC_RX_DMA_ATTR); if (err) { netdev_err(ndev, "Failed to map xsk pool\n"); return err; } needs_reset = netif_running(adapter->netdev) && igc_xdp_is_enabled(adapter); rx_ring = adapter->rx_ring[queue_id]; tx_ring = adapter->tx_ring[queue_id]; /* Rx and Tx rings share the same napi context. */ napi = &rx_ring->q_vector->napi; if (needs_reset) { igc_disable_rx_ring(rx_ring); igc_disable_tx_ring(tx_ring); napi_disable(napi); } set_bit(IGC_RING_FLAG_AF_XDP_ZC, &rx_ring->flags); set_bit(IGC_RING_FLAG_AF_XDP_ZC, &tx_ring->flags); if (needs_reset) { napi_enable(napi); igc_enable_rx_ring(rx_ring); igc_enable_tx_ring(tx_ring); err = igc_xsk_wakeup(ndev, queue_id, XDP_WAKEUP_RX); if (err) { xsk_pool_dma_unmap(pool, IGC_RX_DMA_ATTR); return err; } } return 0; } static int igc_xdp_disable_pool(struct igc_adapter *adapter, u16 queue_id) { struct igc_ring *rx_ring, *tx_ring; struct xsk_buff_pool *pool; struct napi_struct *napi; bool needs_reset; if (queue_id >= adapter->num_rx_queues || queue_id >= adapter->num_tx_queues) return -EINVAL; pool = xsk_get_pool_from_qid(adapter->netdev, queue_id); if (!pool) return -EINVAL; needs_reset = netif_running(adapter->netdev) && igc_xdp_is_enabled(adapter); rx_ring = adapter->rx_ring[queue_id]; tx_ring = adapter->tx_ring[queue_id]; /* Rx and Tx rings share the same napi context. */ napi = &rx_ring->q_vector->napi; if (needs_reset) { igc_disable_rx_ring(rx_ring); igc_disable_tx_ring(tx_ring); napi_disable(napi); } xsk_pool_dma_unmap(pool, IGC_RX_DMA_ATTR); clear_bit(IGC_RING_FLAG_AF_XDP_ZC, &rx_ring->flags); clear_bit(IGC_RING_FLAG_AF_XDP_ZC, &tx_ring->flags); if (needs_reset) { napi_enable(napi); igc_enable_rx_ring(rx_ring); igc_enable_tx_ring(tx_ring); } return 0; } int igc_xdp_setup_pool(struct igc_adapter *adapter, struct xsk_buff_pool *pool, u16 queue_id) { return pool ? igc_xdp_enable_pool(adapter, pool, queue_id) : igc_xdp_disable_pool(adapter, queue_id); }
linux-master
drivers/net/ethernet/intel/igc/igc_xdp.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2018 Intel Corporation */ #include "igc_phy.h" /** * igc_check_reset_block - Check if PHY reset is blocked * @hw: pointer to the HW structure * * Read the PHY management control register and check whether a PHY reset * is blocked. If a reset is not blocked return 0, otherwise * return IGC_ERR_BLK_PHY_RESET (12). */ s32 igc_check_reset_block(struct igc_hw *hw) { u32 manc; manc = rd32(IGC_MANC); return (manc & IGC_MANC_BLK_PHY_RST_ON_IDE) ? IGC_ERR_BLK_PHY_RESET : 0; } /** * igc_get_phy_id - Retrieve the PHY ID and revision * @hw: pointer to the HW structure * * Reads the PHY registers and stores the PHY ID and possibly the PHY * revision in the hardware structure. */ s32 igc_get_phy_id(struct igc_hw *hw) { struct igc_phy_info *phy = &hw->phy; s32 ret_val = 0; u16 phy_id; ret_val = phy->ops.read_reg(hw, PHY_ID1, &phy_id); if (ret_val) goto out; phy->id = (u32)(phy_id << 16); usleep_range(200, 500); ret_val = phy->ops.read_reg(hw, PHY_ID2, &phy_id); if (ret_val) goto out; phy->id |= (u32)(phy_id & PHY_REVISION_MASK); phy->revision = (u32)(phy_id & ~PHY_REVISION_MASK); out: return ret_val; } /** * igc_phy_has_link - Polls PHY for link * @hw: pointer to the HW structure * @iterations: number of times to poll for link * @usec_interval: delay between polling attempts * @success: pointer to whether polling was successful or not * * Polls the PHY status register for link, 'iterations' number of times. */ s32 igc_phy_has_link(struct igc_hw *hw, u32 iterations, u32 usec_interval, bool *success) { u16 i, phy_status; s32 ret_val = 0; for (i = 0; i < iterations; i++) { /* Some PHYs require the PHY_STATUS register to be read * twice due to the link bit being sticky. No harm doing * it across the board. */ ret_val = hw->phy.ops.read_reg(hw, PHY_STATUS, &phy_status); if (ret_val && usec_interval > 0) { /* If the first read fails, another entity may have * ownership of the resources, wait and try again to * see if they have relinquished the resources yet. */ if (usec_interval >= 1000) mdelay(usec_interval / 1000); else udelay(usec_interval); } ret_val = hw->phy.ops.read_reg(hw, PHY_STATUS, &phy_status); if (ret_val) break; if (phy_status & MII_SR_LINK_STATUS) break; if (usec_interval >= 1000) mdelay(usec_interval / 1000); else udelay(usec_interval); } *success = (i < iterations) ? true : false; return ret_val; } /** * igc_power_up_phy_copper - Restore copper link in case of PHY power down * @hw: pointer to the HW structure * * In the case of a PHY power down to save power, or to turn off link during a * driver unload, restore the link to previous settings. */ void igc_power_up_phy_copper(struct igc_hw *hw) { u16 mii_reg = 0; /* The PHY will retain its settings across a power down/up cycle */ hw->phy.ops.read_reg(hw, PHY_CONTROL, &mii_reg); mii_reg &= ~MII_CR_POWER_DOWN; hw->phy.ops.write_reg(hw, PHY_CONTROL, mii_reg); } /** * igc_power_down_phy_copper - Power down copper PHY * @hw: pointer to the HW structure * * Power down PHY to save power when interface is down and wake on lan * is not enabled. */ void igc_power_down_phy_copper(struct igc_hw *hw) { u16 mii_reg = 0; /* The PHY will retain its settings across a power down/up cycle */ hw->phy.ops.read_reg(hw, PHY_CONTROL, &mii_reg); mii_reg |= MII_CR_POWER_DOWN; /* Temporary workaround - should be removed when PHY will implement * IEEE registers as properly */ /* hw->phy.ops.write_reg(hw, PHY_CONTROL, mii_reg);*/ usleep_range(1000, 2000); } /** * igc_check_downshift - Checks whether a downshift in speed occurred * @hw: pointer to the HW structure * * A downshift is detected by querying the PHY link health. */ void igc_check_downshift(struct igc_hw *hw) { struct igc_phy_info *phy = &hw->phy; /* speed downshift not supported */ phy->speed_downgraded = false; } /** * igc_phy_hw_reset - PHY hardware reset * @hw: pointer to the HW structure * * Verify the reset block is not blocking us from resetting. Acquire * semaphore (if necessary) and read/set/write the device control reset * bit in the PHY. Wait the appropriate delay time for the device to * reset and release the semaphore (if necessary). */ s32 igc_phy_hw_reset(struct igc_hw *hw) { struct igc_phy_info *phy = &hw->phy; u32 phpm = 0, timeout = 10000; s32 ret_val; u32 ctrl; ret_val = igc_check_reset_block(hw); if (ret_val) { ret_val = 0; goto out; } ret_val = phy->ops.acquire(hw); if (ret_val) goto out; phpm = rd32(IGC_I225_PHPM); ctrl = rd32(IGC_CTRL); wr32(IGC_CTRL, ctrl | IGC_CTRL_PHY_RST); wrfl(); udelay(phy->reset_delay_us); wr32(IGC_CTRL, ctrl); wrfl(); /* SW should guarantee 100us for the completion of the PHY reset */ usleep_range(100, 150); do { phpm = rd32(IGC_I225_PHPM); timeout--; udelay(1); } while (!(phpm & IGC_PHY_RST_COMP) && timeout); if (!timeout) hw_dbg("Timeout is expired after a phy reset\n"); usleep_range(100, 150); phy->ops.release(hw); out: return ret_val; } /** * igc_phy_setup_autoneg - Configure PHY for auto-negotiation * @hw: pointer to the HW structure * * Reads the MII auto-neg advertisement register and/or the 1000T control * register and if the PHY is already setup for auto-negotiation, then * return successful. Otherwise, setup advertisement and flow control to * the appropriate values for the wanted auto-negotiation. */ static s32 igc_phy_setup_autoneg(struct igc_hw *hw) { struct igc_phy_info *phy = &hw->phy; u16 aneg_multigbt_an_ctrl = 0; u16 mii_1000t_ctrl_reg = 0; u16 mii_autoneg_adv_reg; s32 ret_val; phy->autoneg_advertised &= phy->autoneg_mask; /* Read the MII Auto-Neg Advertisement Register (Address 4). */ ret_val = phy->ops.read_reg(hw, PHY_AUTONEG_ADV, &mii_autoneg_adv_reg); if (ret_val) return ret_val; if (phy->autoneg_mask & ADVERTISE_1000_FULL) { /* Read the MII 1000Base-T Control Register (Address 9). */ ret_val = phy->ops.read_reg(hw, PHY_1000T_CTRL, &mii_1000t_ctrl_reg); if (ret_val) return ret_val; } if (phy->autoneg_mask & ADVERTISE_2500_FULL) { /* Read the MULTI GBT AN Control Register - reg 7.32 */ ret_val = phy->ops.read_reg(hw, (STANDARD_AN_REG_MASK << MMD_DEVADDR_SHIFT) | ANEG_MULTIGBT_AN_CTRL, &aneg_multigbt_an_ctrl); if (ret_val) return ret_val; } /* Need to parse both autoneg_advertised and fc and set up * the appropriate PHY registers. First we will parse for * autoneg_advertised software override. Since we can advertise * a plethora of combinations, we need to check each bit * individually. */ /* First we clear all the 10/100 mb speed bits in the Auto-Neg * Advertisement Register (Address 4) and the 1000 mb speed bits in * the 1000Base-T Control Register (Address 9). */ mii_autoneg_adv_reg &= ~(NWAY_AR_100TX_FD_CAPS | NWAY_AR_100TX_HD_CAPS | NWAY_AR_10T_FD_CAPS | NWAY_AR_10T_HD_CAPS); mii_1000t_ctrl_reg &= ~(CR_1000T_HD_CAPS | CR_1000T_FD_CAPS); hw_dbg("autoneg_advertised %x\n", phy->autoneg_advertised); /* Do we want to advertise 10 Mb Half Duplex? */ if (phy->autoneg_advertised & ADVERTISE_10_HALF) { hw_dbg("Advertise 10mb Half duplex\n"); mii_autoneg_adv_reg |= NWAY_AR_10T_HD_CAPS; } /* Do we want to advertise 10 Mb Full Duplex? */ if (phy->autoneg_advertised & ADVERTISE_10_FULL) { hw_dbg("Advertise 10mb Full duplex\n"); mii_autoneg_adv_reg |= NWAY_AR_10T_FD_CAPS; } /* Do we want to advertise 100 Mb Half Duplex? */ if (phy->autoneg_advertised & ADVERTISE_100_HALF) { hw_dbg("Advertise 100mb Half duplex\n"); mii_autoneg_adv_reg |= NWAY_AR_100TX_HD_CAPS; } /* Do we want to advertise 100 Mb Full Duplex? */ if (phy->autoneg_advertised & ADVERTISE_100_FULL) { hw_dbg("Advertise 100mb Full duplex\n"); mii_autoneg_adv_reg |= NWAY_AR_100TX_FD_CAPS; } /* We do not allow the Phy to advertise 1000 Mb Half Duplex */ if (phy->autoneg_advertised & ADVERTISE_1000_HALF) hw_dbg("Advertise 1000mb Half duplex request denied!\n"); /* Do we want to advertise 1000 Mb Full Duplex? */ if (phy->autoneg_advertised & ADVERTISE_1000_FULL) { hw_dbg("Advertise 1000mb Full duplex\n"); mii_1000t_ctrl_reg |= CR_1000T_FD_CAPS; } /* We do not allow the Phy to advertise 2500 Mb Half Duplex */ if (phy->autoneg_advertised & ADVERTISE_2500_HALF) hw_dbg("Advertise 2500mb Half duplex request denied!\n"); /* Do we want to advertise 2500 Mb Full Duplex? */ if (phy->autoneg_advertised & ADVERTISE_2500_FULL) { hw_dbg("Advertise 2500mb Full duplex\n"); aneg_multigbt_an_ctrl |= CR_2500T_FD_CAPS; } else { aneg_multigbt_an_ctrl &= ~CR_2500T_FD_CAPS; } /* Check for a software override of the flow control settings, and * setup the PHY advertisement registers accordingly. If * auto-negotiation is enabled, then software will have to set the * "PAUSE" bits to the correct value in the Auto-Negotiation * Advertisement Register (PHY_AUTONEG_ADV) and re-start auto- * negotiation. * * The possible values of the "fc" parameter are: * 0: Flow control is completely disabled * 1: Rx flow control is enabled (we can receive pause frames * but not send pause frames). * 2: Tx flow control is enabled (we can send pause frames * but we do not support receiving pause frames). * 3: Both Rx and Tx flow control (symmetric) are enabled. * other: No software override. The flow control configuration * in the EEPROM is used. */ switch (hw->fc.current_mode) { case igc_fc_none: /* Flow control (Rx & Tx) is completely disabled by a * software over-ride. */ mii_autoneg_adv_reg &= ~(NWAY_AR_ASM_DIR | NWAY_AR_PAUSE); break; case igc_fc_rx_pause: /* Rx Flow control is enabled, and Tx Flow control is * disabled, by a software over-ride. * * Since there really isn't a way to advertise that we are * capable of Rx Pause ONLY, we will advertise that we * support both symmetric and asymmetric Rx PAUSE. Later * (in igc_config_fc_after_link_up) we will disable the * hw's ability to send PAUSE frames. */ mii_autoneg_adv_reg |= (NWAY_AR_ASM_DIR | NWAY_AR_PAUSE); break; case igc_fc_tx_pause: /* Tx Flow control is enabled, and Rx Flow control is * disabled, by a software over-ride. */ mii_autoneg_adv_reg |= NWAY_AR_ASM_DIR; mii_autoneg_adv_reg &= ~NWAY_AR_PAUSE; break; case igc_fc_full: /* Flow control (both Rx and Tx) is enabled by a software * over-ride. */ mii_autoneg_adv_reg |= (NWAY_AR_ASM_DIR | NWAY_AR_PAUSE); break; default: hw_dbg("Flow control param set incorrectly\n"); return -IGC_ERR_CONFIG; } ret_val = phy->ops.write_reg(hw, PHY_AUTONEG_ADV, mii_autoneg_adv_reg); if (ret_val) return ret_val; hw_dbg("Auto-Neg Advertising %x\n", mii_autoneg_adv_reg); if (phy->autoneg_mask & ADVERTISE_1000_FULL) ret_val = phy->ops.write_reg(hw, PHY_1000T_CTRL, mii_1000t_ctrl_reg); if (phy->autoneg_mask & ADVERTISE_2500_FULL) ret_val = phy->ops.write_reg(hw, (STANDARD_AN_REG_MASK << MMD_DEVADDR_SHIFT) | ANEG_MULTIGBT_AN_CTRL, aneg_multigbt_an_ctrl); return ret_val; } /** * igc_wait_autoneg - Wait for auto-neg completion * @hw: pointer to the HW structure * * Waits for auto-negotiation to complete or for the auto-negotiation time * limit to expire, which ever happens first. */ static s32 igc_wait_autoneg(struct igc_hw *hw) { u16 i, phy_status; s32 ret_val = 0; /* Break after autoneg completes or PHY_AUTO_NEG_LIMIT expires. */ for (i = PHY_AUTO_NEG_LIMIT; i > 0; i--) { ret_val = hw->phy.ops.read_reg(hw, PHY_STATUS, &phy_status); if (ret_val) break; ret_val = hw->phy.ops.read_reg(hw, PHY_STATUS, &phy_status); if (ret_val) break; if (phy_status & MII_SR_AUTONEG_COMPLETE) break; msleep(100); } /* PHY_AUTO_NEG_TIME expiration doesn't guarantee auto-negotiation * has completed. */ return ret_val; } /** * igc_copper_link_autoneg - Setup/Enable autoneg for copper link * @hw: pointer to the HW structure * * Performs initial bounds checking on autoneg advertisement parameter, then * configure to advertise the full capability. Setup the PHY to autoneg * and restart the negotiation process between the link partner. If * autoneg_wait_to_complete, then wait for autoneg to complete before exiting. */ static s32 igc_copper_link_autoneg(struct igc_hw *hw) { struct igc_phy_info *phy = &hw->phy; u16 phy_ctrl; s32 ret_val; /* Perform some bounds checking on the autoneg advertisement * parameter. */ phy->autoneg_advertised &= phy->autoneg_mask; /* If autoneg_advertised is zero, we assume it was not defaulted * by the calling code so we set to advertise full capability. */ if (phy->autoneg_advertised == 0) phy->autoneg_advertised = phy->autoneg_mask; hw_dbg("Reconfiguring auto-neg advertisement params\n"); ret_val = igc_phy_setup_autoneg(hw); if (ret_val) { hw_dbg("Error Setting up Auto-Negotiation\n"); goto out; } hw_dbg("Restarting Auto-Neg\n"); /* Restart auto-negotiation by setting the Auto Neg Enable bit and * the Auto Neg Restart bit in the PHY control register. */ ret_val = phy->ops.read_reg(hw, PHY_CONTROL, &phy_ctrl); if (ret_val) goto out; phy_ctrl |= (MII_CR_AUTO_NEG_EN | MII_CR_RESTART_AUTO_NEG); ret_val = phy->ops.write_reg(hw, PHY_CONTROL, phy_ctrl); if (ret_val) goto out; /* Does the user want to wait for Auto-Neg to complete here, or * check at a later time (for example, callback routine). */ if (phy->autoneg_wait_to_complete) { ret_val = igc_wait_autoneg(hw); if (ret_val) { hw_dbg("Error while waiting for autoneg to complete\n"); goto out; } } hw->mac.get_link_status = true; out: return ret_val; } /** * igc_setup_copper_link - Configure copper link settings * @hw: pointer to the HW structure * * Calls the appropriate function to configure the link for auto-neg or forced * speed and duplex. Then we check for link, once link is established calls * to configure collision distance and flow control are called. If link is * not established, we return -IGC_ERR_PHY (-2). */ s32 igc_setup_copper_link(struct igc_hw *hw) { s32 ret_val = 0; bool link; if (hw->mac.autoneg) { /* Setup autoneg and flow control advertisement and perform * autonegotiation. */ ret_val = igc_copper_link_autoneg(hw); if (ret_val) goto out; } else { /* PHY will be set to 10H, 10F, 100H or 100F * depending on user settings. */ hw_dbg("Forcing Speed and Duplex\n"); ret_val = hw->phy.ops.force_speed_duplex(hw); if (ret_val) { hw_dbg("Error Forcing Speed and Duplex\n"); goto out; } } /* Check link status. Wait up to 100 microseconds for link to become * valid. */ ret_val = igc_phy_has_link(hw, COPPER_LINK_UP_LIMIT, 10, &link); if (ret_val) goto out; if (link) { hw_dbg("Valid link established!!!\n"); igc_config_collision_dist(hw); ret_val = igc_config_fc_after_link_up(hw); } else { hw_dbg("Unable to establish link!!!\n"); } out: return ret_val; } /** * igc_read_phy_reg_mdic - Read MDI control register * @hw: pointer to the HW structure * @offset: register offset to be read * @data: pointer to the read data * * Reads the MDI control register in the PHY at offset and stores the * information read to data. */ static s32 igc_read_phy_reg_mdic(struct igc_hw *hw, u32 offset, u16 *data) { struct igc_phy_info *phy = &hw->phy; u32 i, mdic = 0; s32 ret_val = 0; if (offset > MAX_PHY_REG_ADDRESS) { hw_dbg("PHY Address %d is out of range\n", offset); ret_val = -IGC_ERR_PARAM; goto out; } /* Set up Op-code, Phy Address, and register offset in the MDI * Control register. The MAC will take care of interfacing with the * PHY to retrieve the desired data. */ mdic = ((offset << IGC_MDIC_REG_SHIFT) | (phy->addr << IGC_MDIC_PHY_SHIFT) | (IGC_MDIC_OP_READ)); wr32(IGC_MDIC, mdic); /* Poll the ready bit to see if the MDI read completed * Increasing the time out as testing showed failures with * the lower time out */ for (i = 0; i < IGC_GEN_POLL_TIMEOUT; i++) { udelay(50); mdic = rd32(IGC_MDIC); if (mdic & IGC_MDIC_READY) break; } if (!(mdic & IGC_MDIC_READY)) { hw_dbg("MDI Read did not complete\n"); ret_val = -IGC_ERR_PHY; goto out; } if (mdic & IGC_MDIC_ERROR) { hw_dbg("MDI Error\n"); ret_val = -IGC_ERR_PHY; goto out; } *data = (u16)mdic; out: return ret_val; } /** * igc_write_phy_reg_mdic - Write MDI control register * @hw: pointer to the HW structure * @offset: register offset to write to * @data: data to write to register at offset * * Writes data to MDI control register in the PHY at offset. */ static s32 igc_write_phy_reg_mdic(struct igc_hw *hw, u32 offset, u16 data) { struct igc_phy_info *phy = &hw->phy; u32 i, mdic = 0; s32 ret_val = 0; if (offset > MAX_PHY_REG_ADDRESS) { hw_dbg("PHY Address %d is out of range\n", offset); ret_val = -IGC_ERR_PARAM; goto out; } /* Set up Op-code, Phy Address, and register offset in the MDI * Control register. The MAC will take care of interfacing with the * PHY to write the desired data. */ mdic = (((u32)data) | (offset << IGC_MDIC_REG_SHIFT) | (phy->addr << IGC_MDIC_PHY_SHIFT) | (IGC_MDIC_OP_WRITE)); wr32(IGC_MDIC, mdic); /* Poll the ready bit to see if the MDI read completed * Increasing the time out as testing showed failures with * the lower time out */ for (i = 0; i < IGC_GEN_POLL_TIMEOUT; i++) { udelay(50); mdic = rd32(IGC_MDIC); if (mdic & IGC_MDIC_READY) break; } if (!(mdic & IGC_MDIC_READY)) { hw_dbg("MDI Write did not complete\n"); ret_val = -IGC_ERR_PHY; goto out; } if (mdic & IGC_MDIC_ERROR) { hw_dbg("MDI Error\n"); ret_val = -IGC_ERR_PHY; goto out; } out: return ret_val; } /** * __igc_access_xmdio_reg - Read/write XMDIO register * @hw: pointer to the HW structure * @address: XMDIO address to program * @dev_addr: device address to program * @data: pointer to value to read/write from/to the XMDIO address * @read: boolean flag to indicate read or write */ static s32 __igc_access_xmdio_reg(struct igc_hw *hw, u16 address, u8 dev_addr, u16 *data, bool read) { s32 ret_val; ret_val = hw->phy.ops.write_reg(hw, IGC_MMDAC, dev_addr); if (ret_val) return ret_val; ret_val = hw->phy.ops.write_reg(hw, IGC_MMDAAD, address); if (ret_val) return ret_val; ret_val = hw->phy.ops.write_reg(hw, IGC_MMDAC, IGC_MMDAC_FUNC_DATA | dev_addr); if (ret_val) return ret_val; if (read) ret_val = hw->phy.ops.read_reg(hw, IGC_MMDAAD, data); else ret_val = hw->phy.ops.write_reg(hw, IGC_MMDAAD, *data); if (ret_val) return ret_val; /* Recalibrate the device back to 0 */ ret_val = hw->phy.ops.write_reg(hw, IGC_MMDAC, 0); if (ret_val) return ret_val; return ret_val; } /** * igc_read_xmdio_reg - Read XMDIO register * @hw: pointer to the HW structure * @addr: XMDIO address to program * @dev_addr: device address to program * @data: value to be read from the EMI address */ static s32 igc_read_xmdio_reg(struct igc_hw *hw, u16 addr, u8 dev_addr, u16 *data) { return __igc_access_xmdio_reg(hw, addr, dev_addr, data, true); } /** * igc_write_xmdio_reg - Write XMDIO register * @hw: pointer to the HW structure * @addr: XMDIO address to program * @dev_addr: device address to program * @data: value to be written to the XMDIO address */ static s32 igc_write_xmdio_reg(struct igc_hw *hw, u16 addr, u8 dev_addr, u16 data) { return __igc_access_xmdio_reg(hw, addr, dev_addr, &data, false); } /** * igc_write_phy_reg_gpy - Write GPY PHY register * @hw: pointer to the HW structure * @offset: register offset to write to * @data: data to write at register offset * * Acquires semaphore, if necessary, then writes the data to PHY register * at the offset. Release any acquired semaphores before exiting. */ s32 igc_write_phy_reg_gpy(struct igc_hw *hw, u32 offset, u16 data) { u8 dev_addr = (offset & GPY_MMD_MASK) >> GPY_MMD_SHIFT; s32 ret_val; offset = offset & GPY_REG_MASK; if (!dev_addr) { ret_val = hw->phy.ops.acquire(hw); if (ret_val) return ret_val; ret_val = igc_write_phy_reg_mdic(hw, offset, data); hw->phy.ops.release(hw); } else { ret_val = igc_write_xmdio_reg(hw, (u16)offset, dev_addr, data); } return ret_val; } /** * igc_read_phy_reg_gpy - Read GPY PHY register * @hw: pointer to the HW structure * @offset: lower half is register offset to read to * upper half is MMD to use. * @data: data to read at register offset * * Acquires semaphore, if necessary, then reads the data in the PHY register * at the offset. Release any acquired semaphores before exiting. */ s32 igc_read_phy_reg_gpy(struct igc_hw *hw, u32 offset, u16 *data) { u8 dev_addr = (offset & GPY_MMD_MASK) >> GPY_MMD_SHIFT; s32 ret_val; offset = offset & GPY_REG_MASK; if (!dev_addr) { ret_val = hw->phy.ops.acquire(hw); if (ret_val) return ret_val; ret_val = igc_read_phy_reg_mdic(hw, offset, data); hw->phy.ops.release(hw); } else { ret_val = igc_read_xmdio_reg(hw, (u16)offset, dev_addr, data); } return ret_val; } /** * igc_read_phy_fw_version - Read gPHY firmware version * @hw: pointer to the HW structure */ u16 igc_read_phy_fw_version(struct igc_hw *hw) { struct igc_phy_info *phy = &hw->phy; u16 gphy_version = 0; u16 ret_val; /* NVM image version is reported as firmware version for i225 device */ ret_val = phy->ops.read_reg(hw, IGC_GPHY_VERSION, &gphy_version); if (ret_val) hw_dbg("igc_phy: read wrong gphy version\n"); return gphy_version; }
linux-master
drivers/net/ethernet/intel/igc/igc_phy.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2018 Intel Corporation */ #include <linux/delay.h> #include "igc_hw.h" /** * igc_acquire_nvm_i225 - Acquire exclusive access to EEPROM * @hw: pointer to the HW structure * * Acquire the necessary semaphores for exclusive access to the EEPROM. * Set the EEPROM access request bit and wait for EEPROM access grant bit. * Return successful if access grant bit set, else clear the request for * EEPROM access and return -IGC_ERR_NVM (-1). */ static s32 igc_acquire_nvm_i225(struct igc_hw *hw) { return igc_acquire_swfw_sync_i225(hw, IGC_SWFW_EEP_SM); } /** * igc_release_nvm_i225 - Release exclusive access to EEPROM * @hw: pointer to the HW structure * * Stop any current commands to the EEPROM and clear the EEPROM request bit, * then release the semaphores acquired. */ static void igc_release_nvm_i225(struct igc_hw *hw) { igc_release_swfw_sync_i225(hw, IGC_SWFW_EEP_SM); } /** * igc_get_hw_semaphore_i225 - Acquire hardware semaphore * @hw: pointer to the HW structure * * Acquire the HW semaphore to access the PHY or NVM */ static s32 igc_get_hw_semaphore_i225(struct igc_hw *hw) { s32 timeout = hw->nvm.word_size + 1; s32 i = 0; u32 swsm; /* Get the SW semaphore */ while (i < timeout) { swsm = rd32(IGC_SWSM); if (!(swsm & IGC_SWSM_SMBI)) break; usleep_range(500, 600); i++; } if (i == timeout) { /* In rare circumstances, the SW semaphore may already be held * unintentionally. Clear the semaphore once before giving up. */ if (hw->dev_spec._base.clear_semaphore_once) { hw->dev_spec._base.clear_semaphore_once = false; igc_put_hw_semaphore(hw); for (i = 0; i < timeout; i++) { swsm = rd32(IGC_SWSM); if (!(swsm & IGC_SWSM_SMBI)) break; usleep_range(500, 600); } } /* If we do not have the semaphore here, we have to give up. */ if (i == timeout) { hw_dbg("Driver can't access device - SMBI bit is set.\n"); return -IGC_ERR_NVM; } } /* Get the FW semaphore. */ for (i = 0; i < timeout; i++) { swsm = rd32(IGC_SWSM); wr32(IGC_SWSM, swsm | IGC_SWSM_SWESMBI); /* Semaphore acquired if bit latched */ if (rd32(IGC_SWSM) & IGC_SWSM_SWESMBI) break; usleep_range(500, 600); } if (i == timeout) { /* Release semaphores */ igc_put_hw_semaphore(hw); hw_dbg("Driver can't access the NVM\n"); return -IGC_ERR_NVM; } return 0; } /** * igc_acquire_swfw_sync_i225 - Acquire SW/FW semaphore * @hw: pointer to the HW structure * @mask: specifies which semaphore to acquire * * Acquire the SW/FW semaphore to access the PHY or NVM. The mask * will also specify which port we're acquiring the lock for. */ s32 igc_acquire_swfw_sync_i225(struct igc_hw *hw, u16 mask) { s32 i = 0, timeout = 200; u32 fwmask = mask << 16; u32 swmask = mask; s32 ret_val = 0; u32 swfw_sync; while (i < timeout) { if (igc_get_hw_semaphore_i225(hw)) { ret_val = -IGC_ERR_SWFW_SYNC; goto out; } swfw_sync = rd32(IGC_SW_FW_SYNC); if (!(swfw_sync & (fwmask | swmask))) break; /* Firmware currently using resource (fwmask) */ igc_put_hw_semaphore(hw); mdelay(5); i++; } if (i == timeout) { hw_dbg("Driver can't access resource, SW_FW_SYNC timeout.\n"); ret_val = -IGC_ERR_SWFW_SYNC; goto out; } swfw_sync |= swmask; wr32(IGC_SW_FW_SYNC, swfw_sync); igc_put_hw_semaphore(hw); out: return ret_val; } /** * igc_release_swfw_sync_i225 - Release SW/FW semaphore * @hw: pointer to the HW structure * @mask: specifies which semaphore to acquire * * Release the SW/FW semaphore used to access the PHY or NVM. The mask * will also specify which port we're releasing the lock for. */ void igc_release_swfw_sync_i225(struct igc_hw *hw, u16 mask) { u32 swfw_sync; /* Releasing the resource requires first getting the HW semaphore. * If we fail to get the semaphore, there is nothing we can do, * except log an error and quit. We are not allowed to hang here * indefinitely, as it may cause denial of service or system crash. */ if (igc_get_hw_semaphore_i225(hw)) { hw_dbg("Failed to release SW_FW_SYNC.\n"); return; } swfw_sync = rd32(IGC_SW_FW_SYNC); swfw_sync &= ~mask; wr32(IGC_SW_FW_SYNC, swfw_sync); igc_put_hw_semaphore(hw); } /** * igc_read_nvm_srrd_i225 - Reads Shadow Ram using EERD register * @hw: pointer to the HW structure * @offset: offset of word in the Shadow Ram to read * @words: number of words to read * @data: word read from the Shadow Ram * * Reads a 16 bit word from the Shadow Ram using the EERD register. * Uses necessary synchronization semaphores. */ static s32 igc_read_nvm_srrd_i225(struct igc_hw *hw, u16 offset, u16 words, u16 *data) { s32 status = 0; u16 i, count; /* We cannot hold synchronization semaphores for too long, * because of forceful takeover procedure. However it is more efficient * to read in bursts than synchronizing access for each word. */ for (i = 0; i < words; i += IGC_EERD_EEWR_MAX_COUNT) { count = (words - i) / IGC_EERD_EEWR_MAX_COUNT > 0 ? IGC_EERD_EEWR_MAX_COUNT : (words - i); status = hw->nvm.ops.acquire(hw); if (status) break; status = igc_read_nvm_eerd(hw, offset, count, data + i); hw->nvm.ops.release(hw); if (status) break; } return status; } /** * igc_write_nvm_srwr - Write to Shadow Ram using EEWR * @hw: pointer to the HW structure * @offset: offset within the Shadow Ram to be written to * @words: number of words to write * @data: 16 bit word(s) to be written to the Shadow Ram * * Writes data to Shadow Ram at offset using EEWR register. * * If igc_update_nvm_checksum is not called after this function , the * Shadow Ram will most likely contain an invalid checksum. */ static s32 igc_write_nvm_srwr(struct igc_hw *hw, u16 offset, u16 words, u16 *data) { struct igc_nvm_info *nvm = &hw->nvm; s32 ret_val = -IGC_ERR_NVM; u32 attempts = 100000; u32 i, k, eewr = 0; /* A check for invalid values: offset too large, too many words, * too many words for the offset, and not enough words. */ if (offset >= nvm->word_size || (words > (nvm->word_size - offset)) || words == 0) { hw_dbg("nvm parameter(s) out of bounds\n"); return ret_val; } for (i = 0; i < words; i++) { ret_val = -IGC_ERR_NVM; eewr = ((offset + i) << IGC_NVM_RW_ADDR_SHIFT) | (data[i] << IGC_NVM_RW_REG_DATA) | IGC_NVM_RW_REG_START; wr32(IGC_SRWR, eewr); for (k = 0; k < attempts; k++) { if (IGC_NVM_RW_REG_DONE & rd32(IGC_SRWR)) { ret_val = 0; break; } udelay(5); } if (ret_val) { hw_dbg("Shadow RAM write EEWR timed out\n"); break; } } return ret_val; } /** * igc_write_nvm_srwr_i225 - Write to Shadow RAM using EEWR * @hw: pointer to the HW structure * @offset: offset within the Shadow RAM to be written to * @words: number of words to write * @data: 16 bit word(s) to be written to the Shadow RAM * * Writes data to Shadow RAM at offset using EEWR register. * * If igc_update_nvm_checksum is not called after this function , the * data will not be committed to FLASH and also Shadow RAM will most likely * contain an invalid checksum. * * If error code is returned, data and Shadow RAM may be inconsistent - buffer * partially written. */ static s32 igc_write_nvm_srwr_i225(struct igc_hw *hw, u16 offset, u16 words, u16 *data) { s32 status = 0; u16 i, count; /* We cannot hold synchronization semaphores for too long, * because of forceful takeover procedure. However it is more efficient * to write in bursts than synchronizing access for each word. */ for (i = 0; i < words; i += IGC_EERD_EEWR_MAX_COUNT) { count = (words - i) / IGC_EERD_EEWR_MAX_COUNT > 0 ? IGC_EERD_EEWR_MAX_COUNT : (words - i); status = hw->nvm.ops.acquire(hw); if (status) break; status = igc_write_nvm_srwr(hw, offset, count, data + i); hw->nvm.ops.release(hw); if (status) break; } return status; } /** * igc_validate_nvm_checksum_i225 - Validate EEPROM checksum * @hw: pointer to the HW structure * * Calculates the EEPROM checksum by reading/adding each word of the EEPROM * and then verifies that the sum of the EEPROM is equal to 0xBABA. */ static s32 igc_validate_nvm_checksum_i225(struct igc_hw *hw) { s32 (*read_op_ptr)(struct igc_hw *hw, u16 offset, u16 count, u16 *data); s32 status = 0; status = hw->nvm.ops.acquire(hw); if (status) goto out; /* Replace the read function with semaphore grabbing with * the one that skips this for a while. * We have semaphore taken already here. */ read_op_ptr = hw->nvm.ops.read; hw->nvm.ops.read = igc_read_nvm_eerd; status = igc_validate_nvm_checksum(hw); /* Revert original read operation. */ hw->nvm.ops.read = read_op_ptr; hw->nvm.ops.release(hw); out: return status; } /** * igc_pool_flash_update_done_i225 - Pool FLUDONE status * @hw: pointer to the HW structure */ static s32 igc_pool_flash_update_done_i225(struct igc_hw *hw) { s32 ret_val = -IGC_ERR_NVM; u32 i, reg; for (i = 0; i < IGC_FLUDONE_ATTEMPTS; i++) { reg = rd32(IGC_EECD); if (reg & IGC_EECD_FLUDONE_I225) { ret_val = 0; break; } udelay(5); } return ret_val; } /** * igc_update_flash_i225 - Commit EEPROM to the flash * @hw: pointer to the HW structure */ static s32 igc_update_flash_i225(struct igc_hw *hw) { s32 ret_val = 0; u32 flup; ret_val = igc_pool_flash_update_done_i225(hw); if (ret_val == -IGC_ERR_NVM) { hw_dbg("Flash update time out\n"); goto out; } flup = rd32(IGC_EECD) | IGC_EECD_FLUPD_I225; wr32(IGC_EECD, flup); ret_val = igc_pool_flash_update_done_i225(hw); if (ret_val) hw_dbg("Flash update time out\n"); else hw_dbg("Flash update complete\n"); out: return ret_val; } /** * igc_update_nvm_checksum_i225 - Update EEPROM checksum * @hw: pointer to the HW structure * * Updates the EEPROM checksum by reading/adding each word of the EEPROM * up to the checksum. Then calculates the EEPROM checksum and writes the * value to the EEPROM. Next commit EEPROM data onto the Flash. */ static s32 igc_update_nvm_checksum_i225(struct igc_hw *hw) { u16 checksum = 0; s32 ret_val = 0; u16 i, nvm_data; /* Read the first word from the EEPROM. If this times out or fails, do * not continue or we could be in for a very long wait while every * EEPROM read fails */ ret_val = igc_read_nvm_eerd(hw, 0, 1, &nvm_data); if (ret_val) { hw_dbg("EEPROM read failed\n"); goto out; } ret_val = hw->nvm.ops.acquire(hw); if (ret_val) goto out; /* Do not use hw->nvm.ops.write, hw->nvm.ops.read * because we do not want to take the synchronization * semaphores twice here. */ for (i = 0; i < NVM_CHECKSUM_REG; i++) { ret_val = igc_read_nvm_eerd(hw, i, 1, &nvm_data); if (ret_val) { hw->nvm.ops.release(hw); hw_dbg("NVM Read Error while updating checksum.\n"); goto out; } checksum += nvm_data; } checksum = (u16)NVM_SUM - checksum; ret_val = igc_write_nvm_srwr(hw, NVM_CHECKSUM_REG, 1, &checksum); if (ret_val) { hw->nvm.ops.release(hw); hw_dbg("NVM Write Error while updating checksum.\n"); goto out; } hw->nvm.ops.release(hw); ret_val = igc_update_flash_i225(hw); out: return ret_val; } /** * igc_get_flash_presence_i225 - Check if flash device is detected * @hw: pointer to the HW structure */ bool igc_get_flash_presence_i225(struct igc_hw *hw) { bool ret_val = false; u32 eec = 0; eec = rd32(IGC_EECD); if (eec & IGC_EECD_FLASH_DETECTED_I225) ret_val = true; return ret_val; } /** * igc_init_nvm_params_i225 - Init NVM func ptrs. * @hw: pointer to the HW structure */ s32 igc_init_nvm_params_i225(struct igc_hw *hw) { struct igc_nvm_info *nvm = &hw->nvm; nvm->ops.acquire = igc_acquire_nvm_i225; nvm->ops.release = igc_release_nvm_i225; /* NVM Function Pointers */ if (igc_get_flash_presence_i225(hw)) { nvm->ops.read = igc_read_nvm_srrd_i225; nvm->ops.write = igc_write_nvm_srwr_i225; nvm->ops.validate = igc_validate_nvm_checksum_i225; nvm->ops.update = igc_update_nvm_checksum_i225; } else { nvm->ops.read = igc_read_nvm_eerd; nvm->ops.write = NULL; nvm->ops.validate = NULL; nvm->ops.update = NULL; } return 0; } /** * igc_set_eee_i225 - Enable/disable EEE support * @hw: pointer to the HW structure * @adv2p5G: boolean flag enabling 2.5G EEE advertisement * @adv1G: boolean flag enabling 1G EEE advertisement * @adv100M: boolean flag enabling 100M EEE advertisement * * Enable/disable EEE based on setting in dev_spec structure. **/ s32 igc_set_eee_i225(struct igc_hw *hw, bool adv2p5G, bool adv1G, bool adv100M) { u32 ipcnfg, eeer; ipcnfg = rd32(IGC_IPCNFG); eeer = rd32(IGC_EEER); /* enable or disable per user setting */ if (hw->dev_spec._base.eee_enable) { u32 eee_su = rd32(IGC_EEE_SU); if (adv100M) ipcnfg |= IGC_IPCNFG_EEE_100M_AN; else ipcnfg &= ~IGC_IPCNFG_EEE_100M_AN; if (adv1G) ipcnfg |= IGC_IPCNFG_EEE_1G_AN; else ipcnfg &= ~IGC_IPCNFG_EEE_1G_AN; if (adv2p5G) ipcnfg |= IGC_IPCNFG_EEE_2_5G_AN; else ipcnfg &= ~IGC_IPCNFG_EEE_2_5G_AN; eeer |= (IGC_EEER_TX_LPI_EN | IGC_EEER_RX_LPI_EN | IGC_EEER_LPI_FC); /* This bit should not be set in normal operation. */ if (eee_su & IGC_EEE_SU_LPI_CLK_STP) hw_dbg("LPI Clock Stop Bit should not be set!\n"); } else { ipcnfg &= ~(IGC_IPCNFG_EEE_2_5G_AN | IGC_IPCNFG_EEE_1G_AN | IGC_IPCNFG_EEE_100M_AN); eeer &= ~(IGC_EEER_TX_LPI_EN | IGC_EEER_RX_LPI_EN | IGC_EEER_LPI_FC); } wr32(IGC_IPCNFG, ipcnfg); wr32(IGC_EEER, eeer); rd32(IGC_IPCNFG); rd32(IGC_EEER); return IGC_SUCCESS; } /* igc_set_ltr_i225 - Set Latency Tolerance Reporting thresholds * @hw: pointer to the HW structure * @link: bool indicating link status * * Set the LTR thresholds based on the link speed (Mbps), EEE, and DMAC * settings, otherwise specify that there is no LTR requirement. */ s32 igc_set_ltr_i225(struct igc_hw *hw, bool link) { u32 tw_system, ltrc, ltrv, ltr_min, ltr_max, scale_min, scale_max; u16 speed, duplex; s32 size; /* If we do not have link, LTR thresholds are zero. */ if (link) { hw->mac.ops.get_speed_and_duplex(hw, &speed, &duplex); /* Check if using copper interface with EEE enabled or if the * link speed is 10 Mbps. */ if (hw->dev_spec._base.eee_enable && speed != SPEED_10) { /* EEE enabled, so send LTRMAX threshold. */ ltrc = rd32(IGC_LTRC) | IGC_LTRC_EEEMS_EN; wr32(IGC_LTRC, ltrc); /* Calculate tw_system (nsec). */ if (speed == SPEED_100) { tw_system = ((rd32(IGC_EEE_SU) & IGC_TW_SYSTEM_100_MASK) >> IGC_TW_SYSTEM_100_SHIFT) * 500; } else { tw_system = (rd32(IGC_EEE_SU) & IGC_TW_SYSTEM_1000_MASK) * 500; } } else { tw_system = 0; } /* Get the Rx packet buffer size. */ size = rd32(IGC_RXPBS) & IGC_RXPBS_SIZE_I225_MASK; /* Convert size to bytes, subtract the MTU, and then * convert the size to bits. */ size *= 1024; size *= 8; if (size < 0) { hw_dbg("Invalid effective Rx buffer size %d\n", size); return -IGC_ERR_CONFIG; } /* Calculate the thresholds. Since speed is in Mbps, simplify * the calculation by multiplying size/speed by 1000 for result * to be in nsec before dividing by the scale in nsec. Set the * scale such that the LTR threshold fits in the register. */ ltr_min = (1000 * size) / speed; ltr_max = ltr_min + tw_system; scale_min = (ltr_min / 1024) < 1024 ? IGC_LTRMINV_SCALE_1024 : IGC_LTRMINV_SCALE_32768; scale_max = (ltr_max / 1024) < 1024 ? IGC_LTRMAXV_SCALE_1024 : IGC_LTRMAXV_SCALE_32768; ltr_min /= scale_min == IGC_LTRMINV_SCALE_1024 ? 1024 : 32768; ltr_min -= 1; ltr_max /= scale_max == IGC_LTRMAXV_SCALE_1024 ? 1024 : 32768; ltr_max -= 1; /* Only write the LTR thresholds if they differ from before. */ ltrv = rd32(IGC_LTRMINV); if (ltr_min != (ltrv & IGC_LTRMINV_LTRV_MASK)) { ltrv = IGC_LTRMINV_LSNP_REQ | ltr_min | (scale_min << IGC_LTRMINV_SCALE_SHIFT); wr32(IGC_LTRMINV, ltrv); } ltrv = rd32(IGC_LTRMAXV); if (ltr_max != (ltrv & IGC_LTRMAXV_LTRV_MASK)) { ltrv = IGC_LTRMAXV_LSNP_REQ | ltr_max | (scale_max << IGC_LTRMAXV_SCALE_SHIFT); wr32(IGC_LTRMAXV, ltrv); } } return IGC_SUCCESS; }
linux-master
drivers/net/ethernet/intel/igc/igc_i225.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2019 Intel Corporation */ #include "igc.h" #include "igc_hw.h" #include "igc_tsn.h" static bool is_any_launchtime(struct igc_adapter *adapter) { int i; for (i = 0; i < adapter->num_tx_queues; i++) { struct igc_ring *ring = adapter->tx_ring[i]; if (ring->launchtime_enable) return true; } return false; } static bool is_cbs_enabled(struct igc_adapter *adapter) { int i; for (i = 0; i < adapter->num_tx_queues; i++) { struct igc_ring *ring = adapter->tx_ring[i]; if (ring->cbs_enable) return true; } return false; } static unsigned int igc_tsn_new_flags(struct igc_adapter *adapter) { unsigned int new_flags = adapter->flags & ~IGC_FLAG_TSN_ANY_ENABLED; if (adapter->taprio_offload_enable) new_flags |= IGC_FLAG_TSN_QBV_ENABLED; if (is_any_launchtime(adapter)) new_flags |= IGC_FLAG_TSN_QBV_ENABLED; if (is_cbs_enabled(adapter)) new_flags |= IGC_FLAG_TSN_QAV_ENABLED; return new_flags; } void igc_tsn_adjust_txtime_offset(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; u16 txoffset; if (!is_any_launchtime(adapter)) return; switch (adapter->link_speed) { case SPEED_10: txoffset = IGC_TXOFFSET_SPEED_10; break; case SPEED_100: txoffset = IGC_TXOFFSET_SPEED_100; break; case SPEED_1000: txoffset = IGC_TXOFFSET_SPEED_1000; break; case SPEED_2500: txoffset = IGC_TXOFFSET_SPEED_2500; break; default: txoffset = 0; break; } wr32(IGC_GTXOFFSET, txoffset); } /* Returns the TSN specific registers to their default values after * the adapter is reset. */ static int igc_tsn_disable_offload(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; u32 tqavctrl; int i; wr32(IGC_GTXOFFSET, 0); wr32(IGC_TXPBS, I225_TXPBSIZE_DEFAULT); wr32(IGC_DTXMXPKTSZ, IGC_DTXMXPKTSZ_DEFAULT); tqavctrl = rd32(IGC_TQAVCTRL); tqavctrl &= ~(IGC_TQAVCTRL_TRANSMIT_MODE_TSN | IGC_TQAVCTRL_ENHANCED_QAV | IGC_TQAVCTRL_FUTSCDDIS); wr32(IGC_TQAVCTRL, tqavctrl); for (i = 0; i < adapter->num_tx_queues; i++) { wr32(IGC_TXQCTL(i), 0); wr32(IGC_STQT(i), 0); wr32(IGC_ENDQT(i), NSEC_PER_SEC); } wr32(IGC_QBVCYCLET_S, 0); wr32(IGC_QBVCYCLET, NSEC_PER_SEC); adapter->flags &= ~IGC_FLAG_TSN_QBV_ENABLED; return 0; } static int igc_tsn_enable_offload(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; u32 tqavctrl, baset_l, baset_h; u32 sec, nsec, cycle; ktime_t base_time, systim; int i; wr32(IGC_TSAUXC, 0); wr32(IGC_DTXMXPKTSZ, IGC_DTXMXPKTSZ_TSN); wr32(IGC_TXPBS, IGC_TXPBSIZE_TSN); for (i = 0; i < adapter->num_tx_queues; i++) { struct igc_ring *ring = adapter->tx_ring[i]; u32 txqctl = 0; u16 cbs_value; u32 tqavcc; wr32(IGC_STQT(i), ring->start_time); wr32(IGC_ENDQT(i), ring->end_time); if (adapter->taprio_offload_enable) { /* If taprio_offload_enable is set we are in "taprio" * mode and we need to be strict about the * cycles: only transmit a packet if it can be * completed during that cycle. * * If taprio_offload_enable is NOT true when * enabling TSN offload, the cycle should have * no external effects, but is only used internally * to adapt the base time register after a second * has passed. * * Enabling strict mode in this case would * unnecessarily prevent the transmission of * certain packets (i.e. at the boundary of a * second) and thus interfere with the launchtime * feature that promises transmission at a * certain point in time. */ txqctl |= IGC_TXQCTL_STRICT_CYCLE | IGC_TXQCTL_STRICT_END; } if (ring->launchtime_enable) txqctl |= IGC_TXQCTL_QUEUE_MODE_LAUNCHT; /* Skip configuring CBS for Q2 and Q3 */ if (i > 1) goto skip_cbs; if (ring->cbs_enable) { if (i == 0) txqctl |= IGC_TXQCTL_QAV_SEL_CBS0; else txqctl |= IGC_TXQCTL_QAV_SEL_CBS1; /* According to i225 datasheet section 7.5.2.7, we * should set the 'idleSlope' field from TQAVCC * register following the equation: * * value = link-speed 0x7736 * BW * 0.2 * ---------- * ----------------- (E1) * 100Mbps 2.5 * * Note that 'link-speed' is in Mbps. * * 'BW' is the percentage bandwidth out of full * link speed which can be found with the * following equation. Note that idleSlope here * is the parameter from this function * which is in kbps. * * BW = idleSlope * ----------------- (E2) * link-speed * 1000 * * That said, we can come up with a generic * equation to calculate the value we should set * it TQAVCC register by replacing 'BW' in E1 by E2. * The resulting equation is: * * value = link-speed * 0x7736 * idleSlope * 0.2 * ------------------------------------- (E3) * 100 * 2.5 * link-speed * 1000 * * 'link-speed' is present in both sides of the * fraction so it is canceled out. The final * equation is the following: * * value = idleSlope * 61036 * ----------------- (E4) * 2500000 * * NOTE: For i225, given the above, we can see * that idleslope is represented in * 40.959433 kbps units by the value at * the TQAVCC register (2.5Gbps / 61036), * which reduces the granularity for * idleslope increments. * * In i225 controller, the sendSlope and loCredit * parameters from CBS are not configurable * by software so we don't do any * 'controller configuration' in respect to * these parameters. */ cbs_value = DIV_ROUND_UP_ULL(ring->idleslope * 61036ULL, 2500000); tqavcc = rd32(IGC_TQAVCC(i)); tqavcc &= ~IGC_TQAVCC_IDLESLOPE_MASK; tqavcc |= cbs_value | IGC_TQAVCC_KEEP_CREDITS; wr32(IGC_TQAVCC(i), tqavcc); wr32(IGC_TQAVHC(i), 0x80000000 + ring->hicredit * 0x7735); } else { /* Disable any CBS for the queue */ txqctl &= ~(IGC_TXQCTL_QAV_SEL_MASK); /* Set idleSlope to zero. */ tqavcc = rd32(IGC_TQAVCC(i)); tqavcc &= ~(IGC_TQAVCC_IDLESLOPE_MASK | IGC_TQAVCC_KEEP_CREDITS); wr32(IGC_TQAVCC(i), tqavcc); /* Set hiCredit to zero. */ wr32(IGC_TQAVHC(i), 0); } skip_cbs: wr32(IGC_TXQCTL(i), txqctl); } tqavctrl = rd32(IGC_TQAVCTRL) & ~IGC_TQAVCTRL_FUTSCDDIS; tqavctrl |= IGC_TQAVCTRL_TRANSMIT_MODE_TSN | IGC_TQAVCTRL_ENHANCED_QAV; adapter->qbv_count++; cycle = adapter->cycle_time; base_time = adapter->base_time; nsec = rd32(IGC_SYSTIML); sec = rd32(IGC_SYSTIMH); systim = ktime_set(sec, nsec); if (ktime_compare(systim, base_time) > 0) { s64 n = div64_s64(ktime_sub_ns(systim, base_time), cycle); base_time = ktime_add_ns(base_time, (n + 1) * cycle); /* Increase the counter if scheduling into the past while * Gate Control List (GCL) is running. */ if ((rd32(IGC_BASET_H) || rd32(IGC_BASET_L)) && (adapter->tc_setup_type == TC_SETUP_QDISC_TAPRIO) && (adapter->qbv_count > 1)) adapter->qbv_config_change_errors++; } else { if (igc_is_device_id_i226(hw)) { ktime_t adjust_time, expires_time; /* According to datasheet section 7.5.2.9.3.3, FutScdDis bit * has to be configured before the cycle time and base time. * Tx won't hang if a GCL is already running, * so in this case we don't need to set FutScdDis. */ if (!(rd32(IGC_BASET_H) || rd32(IGC_BASET_L))) tqavctrl |= IGC_TQAVCTRL_FUTSCDDIS; nsec = rd32(IGC_SYSTIML); sec = rd32(IGC_SYSTIMH); systim = ktime_set(sec, nsec); adjust_time = adapter->base_time; expires_time = ktime_sub_ns(adjust_time, systim); hrtimer_start(&adapter->hrtimer, expires_time, HRTIMER_MODE_REL); } } wr32(IGC_TQAVCTRL, tqavctrl); wr32(IGC_QBVCYCLET_S, cycle); wr32(IGC_QBVCYCLET, cycle); baset_h = div_s64_rem(base_time, NSEC_PER_SEC, &baset_l); wr32(IGC_BASET_H, baset_h); /* In i226, Future base time is only supported when FutScdDis bit * is enabled and only active for re-configuration. * In this case, initialize the base time with zero to create * "re-configuration" scenario then only set the desired base time. */ if (tqavctrl & IGC_TQAVCTRL_FUTSCDDIS) wr32(IGC_BASET_L, 0); wr32(IGC_BASET_L, baset_l); return 0; } int igc_tsn_reset(struct igc_adapter *adapter) { unsigned int new_flags; int err = 0; new_flags = igc_tsn_new_flags(adapter); if (!(new_flags & IGC_FLAG_TSN_ANY_ENABLED)) return igc_tsn_disable_offload(adapter); err = igc_tsn_enable_offload(adapter); if (err < 0) return err; adapter->flags = new_flags; return err; } int igc_tsn_offload_apply(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; /* Per I225/6 HW Design Section 7.5.2.1, transmit mode * cannot be changed dynamically. Require reset the adapter. */ if (netif_running(adapter->netdev) && (igc_is_device_id_i225(hw) || !adapter->qbv_count)) { schedule_work(&adapter->reset_task); return 0; } igc_tsn_reset(adapter); return 0; }
linux-master
drivers/net/ethernet/intel/igc/igc_tsn.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2018 Intel Corporation */ #include <linux/delay.h> #include "igc_hw.h" #include "igc_i225.h" #include "igc_mac.h" #include "igc_base.h" #include "igc.h" /** * igc_reset_hw_base - Reset hardware * @hw: pointer to the HW structure * * This resets the hardware into a known state. This is a * function pointer entry point called by the api module. */ static s32 igc_reset_hw_base(struct igc_hw *hw) { s32 ret_val; u32 ctrl; /* Prevent the PCI-E bus from sticking if there is no TLP connection * on the last TLP read/write transaction when MAC is reset. */ ret_val = igc_disable_pcie_master(hw); if (ret_val) hw_dbg("PCI-E Master disable polling has failed\n"); hw_dbg("Masking off all interrupts\n"); wr32(IGC_IMC, 0xffffffff); wr32(IGC_RCTL, 0); wr32(IGC_TCTL, IGC_TCTL_PSP); wrfl(); usleep_range(10000, 20000); ctrl = rd32(IGC_CTRL); hw_dbg("Issuing a global reset to MAC\n"); wr32(IGC_CTRL, ctrl | IGC_CTRL_RST); ret_val = igc_get_auto_rd_done(hw); if (ret_val) { /* When auto config read does not complete, do not * return with an error. This can happen in situations * where there is no eeprom and prevents getting link. */ hw_dbg("Auto Read Done did not complete\n"); } /* Clear any pending interrupt events. */ wr32(IGC_IMC, 0xffffffff); rd32(IGC_ICR); return ret_val; } /** * igc_init_nvm_params_base - Init NVM func ptrs. * @hw: pointer to the HW structure */ static s32 igc_init_nvm_params_base(struct igc_hw *hw) { struct igc_nvm_info *nvm = &hw->nvm; u32 eecd = rd32(IGC_EECD); u16 size; size = (u16)((eecd & IGC_EECD_SIZE_EX_MASK) >> IGC_EECD_SIZE_EX_SHIFT); /* Added to a constant, "size" becomes the left-shift value * for setting word_size. */ size += NVM_WORD_SIZE_BASE_SHIFT; /* Just in case size is out of range, cap it to the largest * EEPROM size supported */ if (size > 15) size = 15; nvm->type = igc_nvm_eeprom_spi; nvm->word_size = BIT(size); nvm->opcode_bits = 8; nvm->delay_usec = 1; nvm->page_size = eecd & IGC_EECD_ADDR_BITS ? 32 : 8; nvm->address_bits = eecd & IGC_EECD_ADDR_BITS ? 16 : 8; if (nvm->word_size == BIT(15)) nvm->page_size = 128; return 0; } /** * igc_setup_copper_link_base - Configure copper link settings * @hw: pointer to the HW structure * * Configures the link for auto-neg or forced speed and duplex. Then we check * for link, once link is established calls to configure collision distance * and flow control are called. */ static s32 igc_setup_copper_link_base(struct igc_hw *hw) { s32 ret_val = 0; u32 ctrl; ctrl = rd32(IGC_CTRL); ctrl |= IGC_CTRL_SLU; ctrl &= ~(IGC_CTRL_FRCSPD | IGC_CTRL_FRCDPX); wr32(IGC_CTRL, ctrl); ret_val = igc_setup_copper_link(hw); return ret_val; } /** * igc_init_mac_params_base - Init MAC func ptrs. * @hw: pointer to the HW structure */ static s32 igc_init_mac_params_base(struct igc_hw *hw) { struct igc_dev_spec_base *dev_spec = &hw->dev_spec._base; struct igc_mac_info *mac = &hw->mac; /* Set mta register count */ mac->mta_reg_count = 128; mac->rar_entry_count = IGC_RAR_ENTRIES; /* reset */ mac->ops.reset_hw = igc_reset_hw_base; mac->ops.acquire_swfw_sync = igc_acquire_swfw_sync_i225; mac->ops.release_swfw_sync = igc_release_swfw_sync_i225; /* Allow a single clear of the SW semaphore on I225 */ if (mac->type == igc_i225) dev_spec->clear_semaphore_once = true; /* physical interface link setup */ mac->ops.setup_physical_interface = igc_setup_copper_link_base; return 0; } /** * igc_init_phy_params_base - Init PHY func ptrs. * @hw: pointer to the HW structure */ static s32 igc_init_phy_params_base(struct igc_hw *hw) { struct igc_phy_info *phy = &hw->phy; s32 ret_val = 0; phy->autoneg_mask = AUTONEG_ADVERTISE_SPEED_DEFAULT_2500; phy->reset_delay_us = 100; /* set lan id */ hw->bus.func = (rd32(IGC_STATUS) & IGC_STATUS_FUNC_MASK) >> IGC_STATUS_FUNC_SHIFT; /* Make sure the PHY is in a good state. Several people have reported * firmware leaving the PHY's page select register set to something * other than the default of zero, which causes the PHY ID read to * access something other than the intended register. */ ret_val = hw->phy.ops.reset(hw); if (ret_val) { hw_dbg("Error resetting the PHY\n"); goto out; } ret_val = igc_get_phy_id(hw); if (ret_val) return ret_val; igc_check_for_copper_link(hw); out: return ret_val; } static s32 igc_get_invariants_base(struct igc_hw *hw) { struct igc_mac_info *mac = &hw->mac; s32 ret_val = 0; switch (hw->device_id) { case IGC_DEV_ID_I225_LM: case IGC_DEV_ID_I225_V: case IGC_DEV_ID_I225_I: case IGC_DEV_ID_I220_V: case IGC_DEV_ID_I225_K: case IGC_DEV_ID_I225_K2: case IGC_DEV_ID_I226_K: case IGC_DEV_ID_I225_LMVP: case IGC_DEV_ID_I226_LMVP: case IGC_DEV_ID_I225_IT: case IGC_DEV_ID_I226_LM: case IGC_DEV_ID_I226_V: case IGC_DEV_ID_I226_IT: case IGC_DEV_ID_I221_V: case IGC_DEV_ID_I226_BLANK_NVM: case IGC_DEV_ID_I225_BLANK_NVM: mac->type = igc_i225; break; default: return -IGC_ERR_MAC_INIT; } hw->phy.media_type = igc_media_type_copper; /* mac initialization and operations */ ret_val = igc_init_mac_params_base(hw); if (ret_val) goto out; /* NVM initialization */ ret_val = igc_init_nvm_params_base(hw); switch (hw->mac.type) { case igc_i225: ret_val = igc_init_nvm_params_i225(hw); break; default: break; } /* setup PHY parameters */ ret_val = igc_init_phy_params_base(hw); if (ret_val) goto out; out: return ret_val; } /** * igc_acquire_phy_base - Acquire rights to access PHY * @hw: pointer to the HW structure * * Acquire access rights to the correct PHY. This is a * function pointer entry point called by the api module. */ static s32 igc_acquire_phy_base(struct igc_hw *hw) { u16 mask = IGC_SWFW_PHY0_SM; return hw->mac.ops.acquire_swfw_sync(hw, mask); } /** * igc_release_phy_base - Release rights to access PHY * @hw: pointer to the HW structure * * A wrapper to release access rights to the correct PHY. This is a * function pointer entry point called by the api module. */ static void igc_release_phy_base(struct igc_hw *hw) { u16 mask = IGC_SWFW_PHY0_SM; hw->mac.ops.release_swfw_sync(hw, mask); } /** * igc_init_hw_base - Initialize hardware * @hw: pointer to the HW structure * * This inits the hardware readying it for operation. */ static s32 igc_init_hw_base(struct igc_hw *hw) { struct igc_mac_info *mac = &hw->mac; u16 i, rar_count = mac->rar_entry_count; s32 ret_val = 0; /* Setup the receive address */ igc_init_rx_addrs(hw, rar_count); /* Zero out the Multicast HASH table */ hw_dbg("Zeroing the MTA\n"); for (i = 0; i < mac->mta_reg_count; i++) array_wr32(IGC_MTA, i, 0); /* Zero out the Unicast HASH table */ hw_dbg("Zeroing the UTA\n"); for (i = 0; i < mac->uta_reg_count; i++) array_wr32(IGC_UTA, i, 0); /* Setup link and flow control */ ret_val = igc_setup_link(hw); /* Clear all of the statistics registers (clear on read). It is * important that we do this after we have tried to establish link * because the symbol error count will increment wildly if there * is no link. */ igc_clear_hw_cntrs_base(hw); return ret_val; } /** * igc_power_down_phy_copper_base - Remove link during PHY power down * @hw: pointer to the HW structure * * In the case of a PHY power down to save power, or to turn off link during a * driver unload, or wake on lan is not enabled, remove the link. */ void igc_power_down_phy_copper_base(struct igc_hw *hw) { /* If the management interface is not enabled, then power down */ if (!(igc_enable_mng_pass_thru(hw) || igc_check_reset_block(hw))) igc_power_down_phy_copper(hw); } /** * igc_rx_fifo_flush_base - Clean rx fifo after Rx enable * @hw: pointer to the HW structure * * After Rx enable, if manageability is enabled then there is likely some * bad data at the start of the fifo and possibly in the DMA fifo. This * function clears the fifos and flushes any packets that came in as rx was * being enabled. */ void igc_rx_fifo_flush_base(struct igc_hw *hw) { u32 rctl, rlpml, rxdctl[4], rfctl, temp_rctl, rx_enabled; int i, ms_wait; /* disable IPv6 options as per hardware errata */ rfctl = rd32(IGC_RFCTL); rfctl |= IGC_RFCTL_IPV6_EX_DIS; wr32(IGC_RFCTL, rfctl); if (!(rd32(IGC_MANC) & IGC_MANC_RCV_TCO_EN)) return; /* Disable all Rx queues */ for (i = 0; i < 4; i++) { rxdctl[i] = rd32(IGC_RXDCTL(i)); wr32(IGC_RXDCTL(i), rxdctl[i] & ~IGC_RXDCTL_QUEUE_ENABLE); } /* Poll all queues to verify they have shut down */ for (ms_wait = 0; ms_wait < 10; ms_wait++) { usleep_range(1000, 2000); rx_enabled = 0; for (i = 0; i < 4; i++) rx_enabled |= rd32(IGC_RXDCTL(i)); if (!(rx_enabled & IGC_RXDCTL_QUEUE_ENABLE)) break; } if (ms_wait == 10) hw_dbg("Queue disable timed out after 10ms\n"); /* Clear RLPML, RCTL.SBP, RFCTL.LEF, and set RCTL.LPE so that all * incoming packets are rejected. Set enable and wait 2ms so that * any packet that was coming in as RCTL.EN was set is flushed */ wr32(IGC_RFCTL, rfctl & ~IGC_RFCTL_LEF); rlpml = rd32(IGC_RLPML); wr32(IGC_RLPML, 0); rctl = rd32(IGC_RCTL); temp_rctl = rctl & ~(IGC_RCTL_EN | IGC_RCTL_SBP); temp_rctl |= IGC_RCTL_LPE; wr32(IGC_RCTL, temp_rctl); wr32(IGC_RCTL, temp_rctl | IGC_RCTL_EN); wrfl(); usleep_range(2000, 3000); /* Enable Rx queues that were previously enabled and restore our * previous state */ for (i = 0; i < 4; i++) wr32(IGC_RXDCTL(i), rxdctl[i]); wr32(IGC_RCTL, rctl); wrfl(); wr32(IGC_RLPML, rlpml); wr32(IGC_RFCTL, rfctl); /* Flush receive errors generated by workaround */ rd32(IGC_ROC); rd32(IGC_RNBC); rd32(IGC_MPC); } bool igc_is_device_id_i225(struct igc_hw *hw) { switch (hw->device_id) { case IGC_DEV_ID_I225_LM: case IGC_DEV_ID_I225_V: case IGC_DEV_ID_I225_I: case IGC_DEV_ID_I225_K: case IGC_DEV_ID_I225_K2: case IGC_DEV_ID_I225_LMVP: case IGC_DEV_ID_I225_IT: return true; default: return false; } } bool igc_is_device_id_i226(struct igc_hw *hw) { switch (hw->device_id) { case IGC_DEV_ID_I226_LM: case IGC_DEV_ID_I226_V: case IGC_DEV_ID_I226_K: case IGC_DEV_ID_I226_IT: return true; default: return false; } } static struct igc_mac_operations igc_mac_ops_base = { .init_hw = igc_init_hw_base, .check_for_link = igc_check_for_copper_link, .rar_set = igc_rar_set, .read_mac_addr = igc_read_mac_addr, .get_speed_and_duplex = igc_get_speed_and_duplex_copper, }; static const struct igc_phy_operations igc_phy_ops_base = { .acquire = igc_acquire_phy_base, .release = igc_release_phy_base, .reset = igc_phy_hw_reset, .read_reg = igc_read_phy_reg_gpy, .write_reg = igc_write_phy_reg_gpy, }; const struct igc_info igc_base_info = { .get_invariants = igc_get_invariants_base, .mac_ops = &igc_mac_ops_base, .phy_ops = &igc_phy_ops_base, };
linux-master
drivers/net/ethernet/intel/igc/igc_base.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2019 Intel Corporation */ #include "igc.h" #include <linux/module.h> #include <linux/device.h> #include <linux/pci.h> #include <linux/ptp_classify.h> #include <linux/clocksource.h> #include <linux/ktime.h> #include <linux/delay.h> #include <linux/iopoll.h> #define INCVALUE_MASK 0x7fffffff #define ISGN 0x80000000 #define IGC_PTP_TX_TIMEOUT (HZ * 15) #define IGC_PTM_STAT_SLEEP 2 #define IGC_PTM_STAT_TIMEOUT 100 /* SYSTIM read access for I225 */ void igc_ptp_read(struct igc_adapter *adapter, struct timespec64 *ts) { struct igc_hw *hw = &adapter->hw; u32 sec, nsec; /* The timestamp is latched when SYSTIML is read. */ nsec = rd32(IGC_SYSTIML); sec = rd32(IGC_SYSTIMH); ts->tv_sec = sec; ts->tv_nsec = nsec; } static void igc_ptp_write_i225(struct igc_adapter *adapter, const struct timespec64 *ts) { struct igc_hw *hw = &adapter->hw; wr32(IGC_SYSTIML, ts->tv_nsec); wr32(IGC_SYSTIMH, ts->tv_sec); } static int igc_ptp_adjfine_i225(struct ptp_clock_info *ptp, long scaled_ppm) { struct igc_adapter *igc = container_of(ptp, struct igc_adapter, ptp_caps); struct igc_hw *hw = &igc->hw; int neg_adj = 0; u64 rate; u32 inca; if (scaled_ppm < 0) { neg_adj = 1; scaled_ppm = -scaled_ppm; } rate = scaled_ppm; rate <<= 14; rate = div_u64(rate, 78125); inca = rate & INCVALUE_MASK; if (neg_adj) inca |= ISGN; wr32(IGC_TIMINCA, inca); return 0; } static int igc_ptp_adjtime_i225(struct ptp_clock_info *ptp, s64 delta) { struct igc_adapter *igc = container_of(ptp, struct igc_adapter, ptp_caps); struct timespec64 now, then = ns_to_timespec64(delta); unsigned long flags; spin_lock_irqsave(&igc->tmreg_lock, flags); igc_ptp_read(igc, &now); now = timespec64_add(now, then); igc_ptp_write_i225(igc, (const struct timespec64 *)&now); spin_unlock_irqrestore(&igc->tmreg_lock, flags); return 0; } static int igc_ptp_gettimex64_i225(struct ptp_clock_info *ptp, struct timespec64 *ts, struct ptp_system_timestamp *sts) { struct igc_adapter *igc = container_of(ptp, struct igc_adapter, ptp_caps); struct igc_hw *hw = &igc->hw; unsigned long flags; spin_lock_irqsave(&igc->tmreg_lock, flags); ptp_read_system_prets(sts); ts->tv_nsec = rd32(IGC_SYSTIML); ts->tv_sec = rd32(IGC_SYSTIMH); ptp_read_system_postts(sts); spin_unlock_irqrestore(&igc->tmreg_lock, flags); return 0; } static int igc_ptp_settime_i225(struct ptp_clock_info *ptp, const struct timespec64 *ts) { struct igc_adapter *igc = container_of(ptp, struct igc_adapter, ptp_caps); unsigned long flags; spin_lock_irqsave(&igc->tmreg_lock, flags); igc_ptp_write_i225(igc, ts); spin_unlock_irqrestore(&igc->tmreg_lock, flags); return 0; } static void igc_pin_direction(int pin, int input, u32 *ctrl, u32 *ctrl_ext) { u32 *ptr = pin < 2 ? ctrl : ctrl_ext; static const u32 mask[IGC_N_SDP] = { IGC_CTRL_SDP0_DIR, IGC_CTRL_SDP1_DIR, IGC_CTRL_EXT_SDP2_DIR, IGC_CTRL_EXT_SDP3_DIR, }; if (input) *ptr &= ~mask[pin]; else *ptr |= mask[pin]; } static void igc_pin_perout(struct igc_adapter *igc, int chan, int pin, int freq) { static const u32 igc_aux0_sel_sdp[IGC_N_SDP] = { IGC_AUX0_SEL_SDP0, IGC_AUX0_SEL_SDP1, IGC_AUX0_SEL_SDP2, IGC_AUX0_SEL_SDP3, }; static const u32 igc_aux1_sel_sdp[IGC_N_SDP] = { IGC_AUX1_SEL_SDP0, IGC_AUX1_SEL_SDP1, IGC_AUX1_SEL_SDP2, IGC_AUX1_SEL_SDP3, }; static const u32 igc_ts_sdp_en[IGC_N_SDP] = { IGC_TS_SDP0_EN, IGC_TS_SDP1_EN, IGC_TS_SDP2_EN, IGC_TS_SDP3_EN, }; static const u32 igc_ts_sdp_sel_tt0[IGC_N_SDP] = { IGC_TS_SDP0_SEL_TT0, IGC_TS_SDP1_SEL_TT0, IGC_TS_SDP2_SEL_TT0, IGC_TS_SDP3_SEL_TT0, }; static const u32 igc_ts_sdp_sel_tt1[IGC_N_SDP] = { IGC_TS_SDP0_SEL_TT1, IGC_TS_SDP1_SEL_TT1, IGC_TS_SDP2_SEL_TT1, IGC_TS_SDP3_SEL_TT1, }; static const u32 igc_ts_sdp_sel_fc0[IGC_N_SDP] = { IGC_TS_SDP0_SEL_FC0, IGC_TS_SDP1_SEL_FC0, IGC_TS_SDP2_SEL_FC0, IGC_TS_SDP3_SEL_FC0, }; static const u32 igc_ts_sdp_sel_fc1[IGC_N_SDP] = { IGC_TS_SDP0_SEL_FC1, IGC_TS_SDP1_SEL_FC1, IGC_TS_SDP2_SEL_FC1, IGC_TS_SDP3_SEL_FC1, }; static const u32 igc_ts_sdp_sel_clr[IGC_N_SDP] = { IGC_TS_SDP0_SEL_FC1, IGC_TS_SDP1_SEL_FC1, IGC_TS_SDP2_SEL_FC1, IGC_TS_SDP3_SEL_FC1, }; struct igc_hw *hw = &igc->hw; u32 ctrl, ctrl_ext, tssdp = 0; ctrl = rd32(IGC_CTRL); ctrl_ext = rd32(IGC_CTRL_EXT); tssdp = rd32(IGC_TSSDP); igc_pin_direction(pin, 0, &ctrl, &ctrl_ext); /* Make sure this pin is not enabled as an input. */ if ((tssdp & IGC_AUX0_SEL_SDP3) == igc_aux0_sel_sdp[pin]) tssdp &= ~IGC_AUX0_TS_SDP_EN; if ((tssdp & IGC_AUX1_SEL_SDP3) == igc_aux1_sel_sdp[pin]) tssdp &= ~IGC_AUX1_TS_SDP_EN; tssdp &= ~igc_ts_sdp_sel_clr[pin]; if (freq) { if (chan == 1) tssdp |= igc_ts_sdp_sel_fc1[pin]; else tssdp |= igc_ts_sdp_sel_fc0[pin]; } else { if (chan == 1) tssdp |= igc_ts_sdp_sel_tt1[pin]; else tssdp |= igc_ts_sdp_sel_tt0[pin]; } tssdp |= igc_ts_sdp_en[pin]; wr32(IGC_TSSDP, tssdp); wr32(IGC_CTRL, ctrl); wr32(IGC_CTRL_EXT, ctrl_ext); } static void igc_pin_extts(struct igc_adapter *igc, int chan, int pin) { static const u32 igc_aux0_sel_sdp[IGC_N_SDP] = { IGC_AUX0_SEL_SDP0, IGC_AUX0_SEL_SDP1, IGC_AUX0_SEL_SDP2, IGC_AUX0_SEL_SDP3, }; static const u32 igc_aux1_sel_sdp[IGC_N_SDP] = { IGC_AUX1_SEL_SDP0, IGC_AUX1_SEL_SDP1, IGC_AUX1_SEL_SDP2, IGC_AUX1_SEL_SDP3, }; static const u32 igc_ts_sdp_en[IGC_N_SDP] = { IGC_TS_SDP0_EN, IGC_TS_SDP1_EN, IGC_TS_SDP2_EN, IGC_TS_SDP3_EN, }; struct igc_hw *hw = &igc->hw; u32 ctrl, ctrl_ext, tssdp = 0; ctrl = rd32(IGC_CTRL); ctrl_ext = rd32(IGC_CTRL_EXT); tssdp = rd32(IGC_TSSDP); igc_pin_direction(pin, 1, &ctrl, &ctrl_ext); /* Make sure this pin is not enabled as an output. */ tssdp &= ~igc_ts_sdp_en[pin]; if (chan == 1) { tssdp &= ~IGC_AUX1_SEL_SDP3; tssdp |= igc_aux1_sel_sdp[pin] | IGC_AUX1_TS_SDP_EN; } else { tssdp &= ~IGC_AUX0_SEL_SDP3; tssdp |= igc_aux0_sel_sdp[pin] | IGC_AUX0_TS_SDP_EN; } wr32(IGC_TSSDP, tssdp); wr32(IGC_CTRL, ctrl); wr32(IGC_CTRL_EXT, ctrl_ext); } static int igc_ptp_feature_enable_i225(struct ptp_clock_info *ptp, struct ptp_clock_request *rq, int on) { struct igc_adapter *igc = container_of(ptp, struct igc_adapter, ptp_caps); struct igc_hw *hw = &igc->hw; unsigned long flags; struct timespec64 ts; int use_freq = 0, pin = -1; u32 tsim, tsauxc, tsauxc_mask, tsim_mask, trgttiml, trgttimh, freqout; s64 ns; switch (rq->type) { case PTP_CLK_REQ_EXTTS: /* Reject requests with unsupported flags */ if (rq->extts.flags & ~(PTP_ENABLE_FEATURE | PTP_RISING_EDGE | PTP_FALLING_EDGE | PTP_STRICT_FLAGS)) return -EOPNOTSUPP; /* Reject requests failing to enable both edges. */ if ((rq->extts.flags & PTP_STRICT_FLAGS) && (rq->extts.flags & PTP_ENABLE_FEATURE) && (rq->extts.flags & PTP_EXTTS_EDGES) != PTP_EXTTS_EDGES) return -EOPNOTSUPP; if (on) { pin = ptp_find_pin(igc->ptp_clock, PTP_PF_EXTTS, rq->extts.index); if (pin < 0) return -EBUSY; } if (rq->extts.index == 1) { tsauxc_mask = IGC_TSAUXC_EN_TS1; tsim_mask = IGC_TSICR_AUTT1; } else { tsauxc_mask = IGC_TSAUXC_EN_TS0; tsim_mask = IGC_TSICR_AUTT0; } spin_lock_irqsave(&igc->tmreg_lock, flags); tsauxc = rd32(IGC_TSAUXC); tsim = rd32(IGC_TSIM); if (on) { igc_pin_extts(igc, rq->extts.index, pin); tsauxc |= tsauxc_mask; tsim |= tsim_mask; } else { tsauxc &= ~tsauxc_mask; tsim &= ~tsim_mask; } wr32(IGC_TSAUXC, tsauxc); wr32(IGC_TSIM, tsim); spin_unlock_irqrestore(&igc->tmreg_lock, flags); return 0; case PTP_CLK_REQ_PEROUT: /* Reject requests with unsupported flags */ if (rq->perout.flags) return -EOPNOTSUPP; if (on) { pin = ptp_find_pin(igc->ptp_clock, PTP_PF_PEROUT, rq->perout.index); if (pin < 0) return -EBUSY; } ts.tv_sec = rq->perout.period.sec; ts.tv_nsec = rq->perout.period.nsec; ns = timespec64_to_ns(&ts); ns = ns >> 1; if (on && (ns <= 70000000LL || ns == 125000000LL || ns == 250000000LL || ns == 500000000LL)) { if (ns < 8LL) return -EINVAL; use_freq = 1; } ts = ns_to_timespec64(ns); if (rq->perout.index == 1) { if (use_freq) { tsauxc_mask = IGC_TSAUXC_EN_CLK1 | IGC_TSAUXC_ST1; tsim_mask = 0; } else { tsauxc_mask = IGC_TSAUXC_EN_TT1; tsim_mask = IGC_TSICR_TT1; } trgttiml = IGC_TRGTTIML1; trgttimh = IGC_TRGTTIMH1; freqout = IGC_FREQOUT1; } else { if (use_freq) { tsauxc_mask = IGC_TSAUXC_EN_CLK0 | IGC_TSAUXC_ST0; tsim_mask = 0; } else { tsauxc_mask = IGC_TSAUXC_EN_TT0; tsim_mask = IGC_TSICR_TT0; } trgttiml = IGC_TRGTTIML0; trgttimh = IGC_TRGTTIMH0; freqout = IGC_FREQOUT0; } spin_lock_irqsave(&igc->tmreg_lock, flags); tsauxc = rd32(IGC_TSAUXC); tsim = rd32(IGC_TSIM); if (rq->perout.index == 1) { tsauxc &= ~(IGC_TSAUXC_EN_TT1 | IGC_TSAUXC_EN_CLK1 | IGC_TSAUXC_ST1); tsim &= ~IGC_TSICR_TT1; } else { tsauxc &= ~(IGC_TSAUXC_EN_TT0 | IGC_TSAUXC_EN_CLK0 | IGC_TSAUXC_ST0); tsim &= ~IGC_TSICR_TT0; } if (on) { struct timespec64 safe_start; int i = rq->perout.index; igc_pin_perout(igc, i, pin, use_freq); igc_ptp_read(igc, &safe_start); /* PPS output start time is triggered by Target time(TT) * register. Programming any past time value into TT * register will cause PPS to never start. Need to make * sure we program the TT register a time ahead in * future. There isn't a stringent need to fire PPS out * right away. Adding +2 seconds should take care of * corner cases. Let's say if the SYSTIML is close to * wrap up and the timer keeps ticking as we program the * register, adding +2seconds is safe bet. */ safe_start.tv_sec += 2; if (rq->perout.start.sec < safe_start.tv_sec) igc->perout[i].start.tv_sec = safe_start.tv_sec; else igc->perout[i].start.tv_sec = rq->perout.start.sec; igc->perout[i].start.tv_nsec = rq->perout.start.nsec; igc->perout[i].period.tv_sec = ts.tv_sec; igc->perout[i].period.tv_nsec = ts.tv_nsec; wr32(trgttimh, (u32)igc->perout[i].start.tv_sec); /* For now, always select timer 0 as source. */ wr32(trgttiml, (u32)(igc->perout[i].start.tv_nsec | IGC_TT_IO_TIMER_SEL_SYSTIM0)); if (use_freq) wr32(freqout, ns); tsauxc |= tsauxc_mask; tsim |= tsim_mask; } wr32(IGC_TSAUXC, tsauxc); wr32(IGC_TSIM, tsim); spin_unlock_irqrestore(&igc->tmreg_lock, flags); return 0; case PTP_CLK_REQ_PPS: spin_lock_irqsave(&igc->tmreg_lock, flags); tsim = rd32(IGC_TSIM); if (on) tsim |= IGC_TSICR_SYS_WRAP; else tsim &= ~IGC_TSICR_SYS_WRAP; igc->pps_sys_wrap_on = on; wr32(IGC_TSIM, tsim); spin_unlock_irqrestore(&igc->tmreg_lock, flags); return 0; default: break; } return -EOPNOTSUPP; } static int igc_ptp_verify_pin(struct ptp_clock_info *ptp, unsigned int pin, enum ptp_pin_function func, unsigned int chan) { switch (func) { case PTP_PF_NONE: case PTP_PF_EXTTS: case PTP_PF_PEROUT: break; case PTP_PF_PHYSYNC: return -1; } return 0; } /** * igc_ptp_systim_to_hwtstamp - convert system time value to HW timestamp * @adapter: board private structure * @hwtstamps: timestamp structure to update * @systim: unsigned 64bit system time value * * We need to convert the system time value stored in the RX/TXSTMP registers * into a hwtstamp which can be used by the upper level timestamping functions. * * Returns 0 on success. **/ static int igc_ptp_systim_to_hwtstamp(struct igc_adapter *adapter, struct skb_shared_hwtstamps *hwtstamps, u64 systim) { switch (adapter->hw.mac.type) { case igc_i225: memset(hwtstamps, 0, sizeof(*hwtstamps)); /* Upper 32 bits contain s, lower 32 bits contain ns. */ hwtstamps->hwtstamp = ktime_set(systim >> 32, systim & 0xFFFFFFFF); break; default: return -EINVAL; } return 0; } /** * igc_ptp_rx_pktstamp - Retrieve timestamp from Rx packet buffer * @adapter: Pointer to adapter the packet buffer belongs to * @buf: Pointer to packet buffer * * This function retrieves the timestamp saved in the beginning of packet * buffer. While two timestamps are available, one in timer0 reference and the * other in timer1 reference, this function considers only the timestamp in * timer0 reference. * * Returns timestamp value. */ ktime_t igc_ptp_rx_pktstamp(struct igc_adapter *adapter, __le32 *buf) { ktime_t timestamp; u32 secs, nsecs; int adjust; /* Timestamps are saved in little endian at the beginning of the packet * buffer following the layout: * * DWORD: | 0 | 1 | 2 | 3 | * Field: | Timer1 SYSTIML | Timer1 SYSTIMH | Timer0 SYSTIML | Timer0 SYSTIMH | * * SYSTIML holds the nanoseconds part while SYSTIMH holds the seconds * part of the timestamp. */ nsecs = le32_to_cpu(buf[2]); secs = le32_to_cpu(buf[3]); timestamp = ktime_set(secs, nsecs); /* Adjust timestamp for the RX latency based on link speed */ switch (adapter->link_speed) { case SPEED_10: adjust = IGC_I225_RX_LATENCY_10; break; case SPEED_100: adjust = IGC_I225_RX_LATENCY_100; break; case SPEED_1000: adjust = IGC_I225_RX_LATENCY_1000; break; case SPEED_2500: adjust = IGC_I225_RX_LATENCY_2500; break; default: adjust = 0; netdev_warn_once(adapter->netdev, "Imprecise timestamp\n"); break; } return ktime_sub_ns(timestamp, adjust); } static void igc_ptp_disable_rx_timestamp(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; u32 val; int i; wr32(IGC_TSYNCRXCTL, 0); for (i = 0; i < adapter->num_rx_queues; i++) { val = rd32(IGC_SRRCTL(i)); val &= ~IGC_SRRCTL_TIMESTAMP; wr32(IGC_SRRCTL(i), val); } val = rd32(IGC_RXPBS); val &= ~IGC_RXPBS_CFG_TS_EN; wr32(IGC_RXPBS, val); } static void igc_ptp_enable_rx_timestamp(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; u32 val; int i; val = rd32(IGC_RXPBS); val |= IGC_RXPBS_CFG_TS_EN; wr32(IGC_RXPBS, val); for (i = 0; i < adapter->num_rx_queues; i++) { val = rd32(IGC_SRRCTL(i)); /* FIXME: For now, only support retrieving RX timestamps from * timer 0. */ val |= IGC_SRRCTL_TIMER1SEL(0) | IGC_SRRCTL_TIMER0SEL(0) | IGC_SRRCTL_TIMESTAMP; wr32(IGC_SRRCTL(i), val); } val = IGC_TSYNCRXCTL_ENABLED | IGC_TSYNCRXCTL_TYPE_ALL | IGC_TSYNCRXCTL_RXSYNSIG; wr32(IGC_TSYNCRXCTL, val); } static void igc_ptp_clear_tx_tstamp(struct igc_adapter *adapter) { unsigned long flags; int i; spin_lock_irqsave(&adapter->ptp_tx_lock, flags); for (i = 0; i < IGC_MAX_TX_TSTAMP_REGS; i++) { struct igc_tx_timestamp_request *tstamp = &adapter->tx_tstamp[i]; dev_kfree_skb_any(tstamp->skb); tstamp->skb = NULL; } spin_unlock_irqrestore(&adapter->ptp_tx_lock, flags); } static void igc_ptp_disable_tx_timestamp(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; int i; /* Clear the flags first to avoid new packets to be enqueued * for TX timestamping. */ for (i = 0; i < adapter->num_tx_queues; i++) { struct igc_ring *tx_ring = adapter->tx_ring[i]; clear_bit(IGC_RING_FLAG_TX_HWTSTAMP, &tx_ring->flags); } /* Now we can clean the pending TX timestamp requests. */ igc_ptp_clear_tx_tstamp(adapter); wr32(IGC_TSYNCTXCTL, 0); } static void igc_ptp_enable_tx_timestamp(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; int i; wr32(IGC_TSYNCTXCTL, IGC_TSYNCTXCTL_ENABLED | IGC_TSYNCTXCTL_TXSYNSIG); /* Read TXSTMP registers to discard any timestamp previously stored. */ rd32(IGC_TXSTMPL); rd32(IGC_TXSTMPH); /* The hardware is ready to accept TX timestamp requests, * notify the transmit path. */ for (i = 0; i < adapter->num_tx_queues; i++) { struct igc_ring *tx_ring = adapter->tx_ring[i]; set_bit(IGC_RING_FLAG_TX_HWTSTAMP, &tx_ring->flags); } } /** * igc_ptp_set_timestamp_mode - setup hardware for timestamping * @adapter: networking device structure * @config: hwtstamp configuration * * Return: 0 in case of success, negative errno code otherwise. */ static int igc_ptp_set_timestamp_mode(struct igc_adapter *adapter, struct hwtstamp_config *config) { switch (config->tx_type) { case HWTSTAMP_TX_OFF: igc_ptp_disable_tx_timestamp(adapter); break; case HWTSTAMP_TX_ON: igc_ptp_enable_tx_timestamp(adapter); break; default: return -ERANGE; } switch (config->rx_filter) { case HWTSTAMP_FILTER_NONE: igc_ptp_disable_rx_timestamp(adapter); break; case HWTSTAMP_FILTER_PTP_V1_L4_SYNC: case HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ: case HWTSTAMP_FILTER_PTP_V2_EVENT: case HWTSTAMP_FILTER_PTP_V2_L2_EVENT: case HWTSTAMP_FILTER_PTP_V2_L4_EVENT: case HWTSTAMP_FILTER_PTP_V2_SYNC: case HWTSTAMP_FILTER_PTP_V2_L2_SYNC: case HWTSTAMP_FILTER_PTP_V2_L4_SYNC: case HWTSTAMP_FILTER_PTP_V2_DELAY_REQ: case HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ: case HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ: case HWTSTAMP_FILTER_PTP_V1_L4_EVENT: case HWTSTAMP_FILTER_NTP_ALL: case HWTSTAMP_FILTER_ALL: igc_ptp_enable_rx_timestamp(adapter); config->rx_filter = HWTSTAMP_FILTER_ALL; break; default: return -ERANGE; } return 0; } /* Requires adapter->ptp_tx_lock held by caller. */ static void igc_ptp_tx_timeout(struct igc_adapter *adapter, struct igc_tx_timestamp_request *tstamp) { dev_kfree_skb_any(tstamp->skb); tstamp->skb = NULL; adapter->tx_hwtstamp_timeouts++; netdev_warn(adapter->netdev, "Tx timestamp timeout\n"); } void igc_ptp_tx_hang(struct igc_adapter *adapter) { struct igc_tx_timestamp_request *tstamp; struct igc_hw *hw = &adapter->hw; unsigned long flags; bool found = false; int i; spin_lock_irqsave(&adapter->ptp_tx_lock, flags); for (i = 0; i < IGC_MAX_TX_TSTAMP_REGS; i++) { tstamp = &adapter->tx_tstamp[i]; if (!tstamp->skb) continue; if (time_is_after_jiffies(tstamp->start + IGC_PTP_TX_TIMEOUT)) continue; igc_ptp_tx_timeout(adapter, tstamp); found = true; } if (found) { /* Reading the high register of the first set of timestamp registers * clears all the equivalent bits in the TSYNCTXCTL register. */ rd32(IGC_TXSTMPH_0); } spin_unlock_irqrestore(&adapter->ptp_tx_lock, flags); } static void igc_ptp_tx_reg_to_stamp(struct igc_adapter *adapter, struct igc_tx_timestamp_request *tstamp, u64 regval) { struct skb_shared_hwtstamps shhwtstamps; struct sk_buff *skb; int adjust = 0; skb = tstamp->skb; if (!skb) return; if (igc_ptp_systim_to_hwtstamp(adapter, &shhwtstamps, regval)) return; switch (adapter->link_speed) { case SPEED_10: adjust = IGC_I225_TX_LATENCY_10; break; case SPEED_100: adjust = IGC_I225_TX_LATENCY_100; break; case SPEED_1000: adjust = IGC_I225_TX_LATENCY_1000; break; case SPEED_2500: adjust = IGC_I225_TX_LATENCY_2500; break; } shhwtstamps.hwtstamp = ktime_add_ns(shhwtstamps.hwtstamp, adjust); tstamp->skb = NULL; skb_tstamp_tx(skb, &shhwtstamps); dev_kfree_skb_any(skb); } /** * igc_ptp_tx_hwtstamp - utility function which checks for TX time stamp * @adapter: Board private structure * * Check against the ready mask for which of the timestamp register * sets are ready to be retrieved, then retrieve that and notify the * rest of the stack. * * Context: Expects adapter->ptp_tx_lock to be held by caller. */ static void igc_ptp_tx_hwtstamp(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; u64 regval; u32 mask; int i; mask = rd32(IGC_TSYNCTXCTL) & IGC_TSYNCTXCTL_TXTT_ANY; if (mask & IGC_TSYNCTXCTL_TXTT_0) { regval = rd32(IGC_TXSTMPL); regval |= (u64)rd32(IGC_TXSTMPH) << 32; } else { /* There's a bug in the hardware that could cause * missing interrupts for TX timestamping. The issue * is that for new interrupts to be triggered, the * IGC_TXSTMPH_0 register must be read. * * To avoid discarding a valid timestamp that just * happened at the "wrong" time, we need to confirm * that there was no timestamp captured, we do that by * assuming that no two timestamps in sequence have * the same nanosecond value. * * So, we read the "low" register, read the "high" * register (to latch a new timestamp) and read the * "low" register again, if "old" and "new" versions * of the "low" register are different, a valid * timestamp was captured, we can read the "high" * register again. */ u32 txstmpl_old, txstmpl_new; txstmpl_old = rd32(IGC_TXSTMPL); rd32(IGC_TXSTMPH); txstmpl_new = rd32(IGC_TXSTMPL); if (txstmpl_old == txstmpl_new) goto done; regval = txstmpl_new; regval |= (u64)rd32(IGC_TXSTMPH) << 32; } igc_ptp_tx_reg_to_stamp(adapter, &adapter->tx_tstamp[0], regval); done: /* Now that the problematic first register was handled, we can * use retrieve the timestamps from the other registers * (starting from '1') with less complications. */ for (i = 1; i < IGC_MAX_TX_TSTAMP_REGS; i++) { struct igc_tx_timestamp_request *tstamp = &adapter->tx_tstamp[i]; if (!(tstamp->mask & mask)) continue; regval = rd32(tstamp->regl); regval |= (u64)rd32(tstamp->regh) << 32; igc_ptp_tx_reg_to_stamp(adapter, tstamp, regval); } } /** * igc_ptp_tx_tstamp_event * @adapter: board private structure * * Called when a TX timestamp interrupt happens to retrieve the * timestamp and send it up to the socket. */ void igc_ptp_tx_tstamp_event(struct igc_adapter *adapter) { unsigned long flags; spin_lock_irqsave(&adapter->ptp_tx_lock, flags); igc_ptp_tx_hwtstamp(adapter); spin_unlock_irqrestore(&adapter->ptp_tx_lock, flags); } /** * igc_ptp_set_ts_config - set hardware time stamping config * @netdev: network interface device structure * @ifr: interface request data * **/ int igc_ptp_set_ts_config(struct net_device *netdev, struct ifreq *ifr) { struct igc_adapter *adapter = netdev_priv(netdev); struct hwtstamp_config config; int err; if (copy_from_user(&config, ifr->ifr_data, sizeof(config))) return -EFAULT; err = igc_ptp_set_timestamp_mode(adapter, &config); if (err) return err; /* save these settings for future reference */ memcpy(&adapter->tstamp_config, &config, sizeof(adapter->tstamp_config)); return copy_to_user(ifr->ifr_data, &config, sizeof(config)) ? -EFAULT : 0; } /** * igc_ptp_get_ts_config - get hardware time stamping config * @netdev: network interface device structure * @ifr: interface request data * * Get the hwtstamp_config settings to return to the user. Rather than attempt * to deconstruct the settings from the registers, just return a shadow copy * of the last known settings. **/ int igc_ptp_get_ts_config(struct net_device *netdev, struct ifreq *ifr) { struct igc_adapter *adapter = netdev_priv(netdev); struct hwtstamp_config *config = &adapter->tstamp_config; return copy_to_user(ifr->ifr_data, config, sizeof(*config)) ? -EFAULT : 0; } /* The two conditions below must be met for cross timestamping via * PCIe PTM: * * 1. We have an way to convert the timestamps in the PTM messages * to something related to the system clocks (right now, only * X86 systems with support for the Always Running Timer allow that); * * 2. We have PTM enabled in the path from the device to the PCIe root port. */ static bool igc_is_crosststamp_supported(struct igc_adapter *adapter) { if (!IS_ENABLED(CONFIG_X86_TSC)) return false; /* FIXME: it was noticed that enabling support for PCIe PTM in * some i225-V models could cause lockups when bringing the * interface up/down. There should be no downsides to * disabling crosstimestamping support for i225-V, as it * doesn't have any PTP support. That way we gain some time * while root causing the issue. */ if (adapter->pdev->device == IGC_DEV_ID_I225_V) return false; return pcie_ptm_enabled(adapter->pdev); } static struct system_counterval_t igc_device_tstamp_to_system(u64 tstamp) { #if IS_ENABLED(CONFIG_X86_TSC) && !defined(CONFIG_UML) return convert_art_ns_to_tsc(tstamp); #else return (struct system_counterval_t) { }; #endif } static void igc_ptm_log_error(struct igc_adapter *adapter, u32 ptm_stat) { struct net_device *netdev = adapter->netdev; switch (ptm_stat) { case IGC_PTM_STAT_RET_ERR: netdev_err(netdev, "PTM Error: Root port timeout\n"); break; case IGC_PTM_STAT_BAD_PTM_RES: netdev_err(netdev, "PTM Error: Bad response, PTM Response Data expected\n"); break; case IGC_PTM_STAT_T4M1_OVFL: netdev_err(netdev, "PTM Error: T4 minus T1 overflow\n"); break; case IGC_PTM_STAT_ADJUST_1ST: netdev_err(netdev, "PTM Error: 1588 timer adjusted during first PTM cycle\n"); break; case IGC_PTM_STAT_ADJUST_CYC: netdev_err(netdev, "PTM Error: 1588 timer adjusted during non-first PTM cycle\n"); break; default: netdev_err(netdev, "PTM Error: Unknown error (%#x)\n", ptm_stat); break; } } static int igc_phc_get_syncdevicetime(ktime_t *device, struct system_counterval_t *system, void *ctx) { u32 stat, t2_curr_h, t2_curr_l, ctrl; struct igc_adapter *adapter = ctx; struct igc_hw *hw = &adapter->hw; int err, count = 100; ktime_t t1, t2_curr; /* Get a snapshot of system clocks to use as historic value. */ ktime_get_snapshot(&adapter->snapshot); do { /* Doing this in a loop because in the event of a * badly timed (ha!) system clock adjustment, we may * get PTM errors from the PCI root, but these errors * are transitory. Repeating the process returns valid * data eventually. */ /* To "manually" start the PTM cycle we need to clear and * then set again the TRIG bit. */ ctrl = rd32(IGC_PTM_CTRL); ctrl &= ~IGC_PTM_CTRL_TRIG; wr32(IGC_PTM_CTRL, ctrl); ctrl |= IGC_PTM_CTRL_TRIG; wr32(IGC_PTM_CTRL, ctrl); /* The cycle only starts "for real" when software notifies * that it has read the registers, this is done by setting * VALID bit. */ wr32(IGC_PTM_STAT, IGC_PTM_STAT_VALID); err = readx_poll_timeout(rd32, IGC_PTM_STAT, stat, stat, IGC_PTM_STAT_SLEEP, IGC_PTM_STAT_TIMEOUT); if (err < 0) { netdev_err(adapter->netdev, "Timeout reading IGC_PTM_STAT register\n"); return err; } if ((stat & IGC_PTM_STAT_VALID) == IGC_PTM_STAT_VALID) break; if (stat & ~IGC_PTM_STAT_VALID) { /* An error occurred, log it. */ igc_ptm_log_error(adapter, stat); /* The STAT register is write-1-to-clear (W1C), * so write the previous error status to clear it. */ wr32(IGC_PTM_STAT, stat); continue; } } while (--count); if (!count) { netdev_err(adapter->netdev, "Exceeded number of tries for PTM cycle\n"); return -ETIMEDOUT; } t1 = ktime_set(rd32(IGC_PTM_T1_TIM0_H), rd32(IGC_PTM_T1_TIM0_L)); t2_curr_l = rd32(IGC_PTM_CURR_T2_L); t2_curr_h = rd32(IGC_PTM_CURR_T2_H); /* FIXME: When the register that tells the endianness of the * PTM registers are implemented, check them here and add the * appropriate conversion. */ t2_curr_h = swab32(t2_curr_h); t2_curr = ((s64)t2_curr_h << 32 | t2_curr_l); *device = t1; *system = igc_device_tstamp_to_system(t2_curr); return 0; } static int igc_ptp_getcrosststamp(struct ptp_clock_info *ptp, struct system_device_crosststamp *cts) { struct igc_adapter *adapter = container_of(ptp, struct igc_adapter, ptp_caps); return get_device_system_crosststamp(igc_phc_get_syncdevicetime, adapter, &adapter->snapshot, cts); } /** * igc_ptp_init - Initialize PTP functionality * @adapter: Board private structure * * This function is called at device probe to initialize the PTP * functionality. */ void igc_ptp_init(struct igc_adapter *adapter) { struct net_device *netdev = adapter->netdev; struct igc_tx_timestamp_request *tstamp; struct igc_hw *hw = &adapter->hw; int i; tstamp = &adapter->tx_tstamp[0]; tstamp->mask = IGC_TSYNCTXCTL_TXTT_0; tstamp->regl = IGC_TXSTMPL_0; tstamp->regh = IGC_TXSTMPH_0; tstamp->flags = 0; tstamp = &adapter->tx_tstamp[1]; tstamp->mask = IGC_TSYNCTXCTL_TXTT_1; tstamp->regl = IGC_TXSTMPL_1; tstamp->regh = IGC_TXSTMPH_1; tstamp->flags = IGC_TX_FLAGS_TSTAMP_1; tstamp = &adapter->tx_tstamp[2]; tstamp->mask = IGC_TSYNCTXCTL_TXTT_2; tstamp->regl = IGC_TXSTMPL_2; tstamp->regh = IGC_TXSTMPH_2; tstamp->flags = IGC_TX_FLAGS_TSTAMP_2; tstamp = &adapter->tx_tstamp[3]; tstamp->mask = IGC_TSYNCTXCTL_TXTT_3; tstamp->regl = IGC_TXSTMPL_3; tstamp->regh = IGC_TXSTMPH_3; tstamp->flags = IGC_TX_FLAGS_TSTAMP_3; switch (hw->mac.type) { case igc_i225: for (i = 0; i < IGC_N_SDP; i++) { struct ptp_pin_desc *ppd = &adapter->sdp_config[i]; snprintf(ppd->name, sizeof(ppd->name), "SDP%d", i); ppd->index = i; ppd->func = PTP_PF_NONE; } snprintf(adapter->ptp_caps.name, 16, "%pm", netdev->dev_addr); adapter->ptp_caps.owner = THIS_MODULE; adapter->ptp_caps.max_adj = 62499999; adapter->ptp_caps.adjfine = igc_ptp_adjfine_i225; adapter->ptp_caps.adjtime = igc_ptp_adjtime_i225; adapter->ptp_caps.gettimex64 = igc_ptp_gettimex64_i225; adapter->ptp_caps.settime64 = igc_ptp_settime_i225; adapter->ptp_caps.enable = igc_ptp_feature_enable_i225; adapter->ptp_caps.pps = 1; adapter->ptp_caps.pin_config = adapter->sdp_config; adapter->ptp_caps.n_ext_ts = IGC_N_EXTTS; adapter->ptp_caps.n_per_out = IGC_N_PEROUT; adapter->ptp_caps.n_pins = IGC_N_SDP; adapter->ptp_caps.verify = igc_ptp_verify_pin; if (!igc_is_crosststamp_supported(adapter)) break; adapter->ptp_caps.getcrosststamp = igc_ptp_getcrosststamp; break; default: adapter->ptp_clock = NULL; return; } spin_lock_init(&adapter->ptp_tx_lock); spin_lock_init(&adapter->tmreg_lock); adapter->tstamp_config.rx_filter = HWTSTAMP_FILTER_NONE; adapter->tstamp_config.tx_type = HWTSTAMP_TX_OFF; adapter->prev_ptp_time = ktime_to_timespec64(ktime_get_real()); adapter->ptp_reset_start = ktime_get(); adapter->ptp_clock = ptp_clock_register(&adapter->ptp_caps, &adapter->pdev->dev); if (IS_ERR(adapter->ptp_clock)) { adapter->ptp_clock = NULL; netdev_err(netdev, "ptp_clock_register failed\n"); } else if (adapter->ptp_clock) { netdev_info(netdev, "PHC added\n"); adapter->ptp_flags |= IGC_PTP_ENABLED; } } static void igc_ptp_time_save(struct igc_adapter *adapter) { igc_ptp_read(adapter, &adapter->prev_ptp_time); adapter->ptp_reset_start = ktime_get(); } static void igc_ptp_time_restore(struct igc_adapter *adapter) { struct timespec64 ts = adapter->prev_ptp_time; ktime_t delta; delta = ktime_sub(ktime_get(), adapter->ptp_reset_start); timespec64_add_ns(&ts, ktime_to_ns(delta)); igc_ptp_write_i225(adapter, &ts); } static void igc_ptm_stop(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; u32 ctrl; ctrl = rd32(IGC_PTM_CTRL); ctrl &= ~IGC_PTM_CTRL_EN; wr32(IGC_PTM_CTRL, ctrl); } /** * igc_ptp_suspend - Disable PTP work items and prepare for suspend * @adapter: Board private structure * * This function stops the overflow check work and PTP Tx timestamp work, and * will prepare the device for OS suspend. */ void igc_ptp_suspend(struct igc_adapter *adapter) { if (!(adapter->ptp_flags & IGC_PTP_ENABLED)) return; igc_ptp_clear_tx_tstamp(adapter); if (pci_device_is_present(adapter->pdev)) { igc_ptp_time_save(adapter); igc_ptm_stop(adapter); } } /** * igc_ptp_stop - Disable PTP device and stop the overflow check. * @adapter: Board private structure. * * This function stops the PTP support and cancels the delayed work. **/ void igc_ptp_stop(struct igc_adapter *adapter) { igc_ptp_suspend(adapter); if (adapter->ptp_clock) { ptp_clock_unregister(adapter->ptp_clock); netdev_info(adapter->netdev, "PHC removed\n"); adapter->ptp_flags &= ~IGC_PTP_ENABLED; } } /** * igc_ptp_reset - Re-enable the adapter for PTP following a reset. * @adapter: Board private structure. * * This function handles the reset work required to re-enable the PTP device. **/ void igc_ptp_reset(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; u32 cycle_ctrl, ctrl; unsigned long flags; u32 timadj; /* reset the tstamp_config */ igc_ptp_set_timestamp_mode(adapter, &adapter->tstamp_config); spin_lock_irqsave(&adapter->tmreg_lock, flags); switch (adapter->hw.mac.type) { case igc_i225: timadj = rd32(IGC_TIMADJ); timadj |= IGC_TIMADJ_ADJUST_METH; wr32(IGC_TIMADJ, timadj); wr32(IGC_TSAUXC, 0x0); wr32(IGC_TSSDP, 0x0); wr32(IGC_TSIM, IGC_TSICR_INTERRUPTS | (adapter->pps_sys_wrap_on ? IGC_TSICR_SYS_WRAP : 0)); wr32(IGC_IMS, IGC_IMS_TS); if (!igc_is_crosststamp_supported(adapter)) break; wr32(IGC_PCIE_DIG_DELAY, IGC_PCIE_DIG_DELAY_DEFAULT); wr32(IGC_PCIE_PHY_DELAY, IGC_PCIE_PHY_DELAY_DEFAULT); cycle_ctrl = IGC_PTM_CYCLE_CTRL_CYC_TIME(IGC_PTM_CYC_TIME_DEFAULT); wr32(IGC_PTM_CYCLE_CTRL, cycle_ctrl); ctrl = IGC_PTM_CTRL_EN | IGC_PTM_CTRL_START_NOW | IGC_PTM_CTRL_SHRT_CYC(IGC_PTM_SHORT_CYC_DEFAULT) | IGC_PTM_CTRL_PTM_TO(IGC_PTM_TIMEOUT_DEFAULT) | IGC_PTM_CTRL_TRIG; wr32(IGC_PTM_CTRL, ctrl); /* Force the first cycle to run. */ wr32(IGC_PTM_STAT, IGC_PTM_STAT_VALID); break; default: /* No work to do. */ goto out; } /* Re-initialize the timer. */ if (hw->mac.type == igc_i225) { igc_ptp_time_restore(adapter); } else { timecounter_init(&adapter->tc, &adapter->cc, ktime_to_ns(ktime_get_real())); } out: spin_unlock_irqrestore(&adapter->tmreg_lock, flags); wrfl(); }
linux-master
drivers/net/ethernet/intel/igc/igc_ptp.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2020 Intel Corporation */ #include "igc.h" #include "igc_diag.h" static struct igc_reg_test reg_test[] = { { IGC_FCAL, 1, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { IGC_FCAH, 1, PATTERN_TEST, 0x0000FFFF, 0xFFFFFFFF }, { IGC_FCT, 1, PATTERN_TEST, 0x0000FFFF, 0xFFFFFFFF }, { IGC_RDBAH(0), 4, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { IGC_RDBAL(0), 4, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFF80 }, { IGC_RDLEN(0), 4, PATTERN_TEST, 0x000FFF80, 0x000FFFFF }, { IGC_RDT(0), 4, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF }, { IGC_FCRTH, 1, PATTERN_TEST, 0x0003FFF0, 0x0003FFF0 }, { IGC_FCTTV, 1, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF }, { IGC_TIPG, 1, PATTERN_TEST, 0x3FFFFFFF, 0x3FFFFFFF }, { IGC_TDBAH(0), 4, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { IGC_TDBAL(0), 4, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFF80 }, { IGC_TDLEN(0), 4, PATTERN_TEST, 0x000FFF80, 0x000FFFFF }, { IGC_TDT(0), 4, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF }, { IGC_RCTL, 1, SET_READ_TEST, 0xFFFFFFFF, 0x00000000 }, { IGC_RCTL, 1, SET_READ_TEST, 0x04CFB2FE, 0x003FFFFB }, { IGC_RCTL, 1, SET_READ_TEST, 0x04CFB2FE, 0xFFFFFFFF }, { IGC_TCTL, 1, SET_READ_TEST, 0xFFFFFFFF, 0x00000000 }, { IGC_RA, 16, TABLE64_TEST_LO, 0xFFFFFFFF, 0xFFFFFFFF }, { IGC_RA, 16, TABLE64_TEST_HI, 0x900FFFFF, 0xFFFFFFFF }, { IGC_MTA, 128, TABLE32_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { 0, 0, 0, 0} }; static bool reg_pattern_test(struct igc_adapter *adapter, u64 *data, int reg, u32 mask, u32 write) { struct igc_hw *hw = &adapter->hw; u32 pat, val, before; static const u32 test_pattern[] = { 0x5A5A5A5A, 0xA5A5A5A5, 0x00000000, 0xFFFFFFFF }; for (pat = 0; pat < ARRAY_SIZE(test_pattern); pat++) { before = rd32(reg); wr32(reg, test_pattern[pat] & write); val = rd32(reg); if (val != (test_pattern[pat] & write & mask)) { netdev_err(adapter->netdev, "pattern test reg %04X failed: got 0x%08X expected 0x%08X", reg, val, test_pattern[pat] & write & mask); *data = reg; wr32(reg, before); return false; } wr32(reg, before); } return true; } static bool reg_set_and_check(struct igc_adapter *adapter, u64 *data, int reg, u32 mask, u32 write) { struct igc_hw *hw = &adapter->hw; u32 val, before; before = rd32(reg); wr32(reg, write & mask); val = rd32(reg); if ((write & mask) != (val & mask)) { netdev_err(adapter->netdev, "set/check reg %04X test failed: got 0x%08X expected 0x%08X", reg, (val & mask), (write & mask)); *data = reg; wr32(reg, before); return false; } wr32(reg, before); return true; } bool igc_reg_test(struct igc_adapter *adapter, u64 *data) { struct igc_reg_test *test = reg_test; struct igc_hw *hw = &adapter->hw; u32 value, before, after; u32 i, toggle, b = false; /* Because the status register is such a special case, * we handle it separately from the rest of the register * tests. Some bits are read-only, some toggle, and some * are writeable. */ toggle = 0x6800D3; before = rd32(IGC_STATUS); value = before & toggle; wr32(IGC_STATUS, toggle); after = rd32(IGC_STATUS) & toggle; if (value != after) { netdev_err(adapter->netdev, "failed STATUS register test got: 0x%08X expected: 0x%08X", after, value); *data = 1; return false; } /* restore previous status */ wr32(IGC_STATUS, before); /* Perform the remainder of the register test, looping through * the test table until we either fail or reach the null entry. */ while (test->reg) { for (i = 0; i < test->array_len; i++) { switch (test->test_type) { case PATTERN_TEST: b = reg_pattern_test(adapter, data, test->reg + (i * 0x40), test->mask, test->write); break; case SET_READ_TEST: b = reg_set_and_check(adapter, data, test->reg + (i * 0x40), test->mask, test->write); break; case TABLE64_TEST_LO: b = reg_pattern_test(adapter, data, test->reg + (i * 8), test->mask, test->write); break; case TABLE64_TEST_HI: b = reg_pattern_test(adapter, data, test->reg + 4 + (i * 8), test->mask, test->write); break; case TABLE32_TEST: b = reg_pattern_test(adapter, data, test->reg + (i * 4), test->mask, test->write); break; } if (!b) return false; } test++; } *data = 0; return true; } bool igc_eeprom_test(struct igc_adapter *adapter, u64 *data) { struct igc_hw *hw = &adapter->hw; *data = 0; if (hw->nvm.ops.validate(hw) != IGC_SUCCESS) { *data = 1; return false; } return true; } bool igc_link_test(struct igc_adapter *adapter, u64 *data) { bool link_up; *data = 0; /* add delay to give enough time for autonegotioation to finish */ if (adapter->hw.mac.autoneg) ssleep(5); link_up = igc_has_link(adapter); if (!link_up) { *data = 1; return false; } return true; }
linux-master
drivers/net/ethernet/intel/igc/igc_diag.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2018 Intel Corporation */ /* ethtool support for igc */ #include <linux/if_vlan.h> #include <linux/pm_runtime.h> #include <linux/mdio.h> #include "igc.h" #include "igc_diag.h" /* forward declaration */ struct igc_stats { char stat_string[ETH_GSTRING_LEN]; int sizeof_stat; int stat_offset; }; #define IGC_STAT(_name, _stat) { \ .stat_string = _name, \ .sizeof_stat = sizeof_field(struct igc_adapter, _stat), \ .stat_offset = offsetof(struct igc_adapter, _stat) \ } static const struct igc_stats igc_gstrings_stats[] = { IGC_STAT("rx_packets", stats.gprc), IGC_STAT("tx_packets", stats.gptc), IGC_STAT("rx_bytes", stats.gorc), IGC_STAT("tx_bytes", stats.gotc), IGC_STAT("rx_broadcast", stats.bprc), IGC_STAT("tx_broadcast", stats.bptc), IGC_STAT("rx_multicast", stats.mprc), IGC_STAT("tx_multicast", stats.mptc), IGC_STAT("multicast", stats.mprc), IGC_STAT("collisions", stats.colc), IGC_STAT("rx_crc_errors", stats.crcerrs), IGC_STAT("rx_no_buffer_count", stats.rnbc), IGC_STAT("rx_missed_errors", stats.mpc), IGC_STAT("tx_aborted_errors", stats.ecol), IGC_STAT("tx_carrier_errors", stats.tncrs), IGC_STAT("tx_window_errors", stats.latecol), IGC_STAT("tx_abort_late_coll", stats.latecol), IGC_STAT("tx_deferred_ok", stats.dc), IGC_STAT("tx_single_coll_ok", stats.scc), IGC_STAT("tx_multi_coll_ok", stats.mcc), IGC_STAT("tx_timeout_count", tx_timeout_count), IGC_STAT("rx_long_length_errors", stats.roc), IGC_STAT("rx_short_length_errors", stats.ruc), IGC_STAT("rx_align_errors", stats.algnerrc), IGC_STAT("tx_tcp_seg_good", stats.tsctc), IGC_STAT("tx_tcp_seg_failed", stats.tsctfc), IGC_STAT("rx_flow_control_xon", stats.xonrxc), IGC_STAT("rx_flow_control_xoff", stats.xoffrxc), IGC_STAT("tx_flow_control_xon", stats.xontxc), IGC_STAT("tx_flow_control_xoff", stats.xofftxc), IGC_STAT("rx_long_byte_count", stats.gorc), IGC_STAT("tx_dma_out_of_sync", stats.doosync), IGC_STAT("tx_smbus", stats.mgptc), IGC_STAT("rx_smbus", stats.mgprc), IGC_STAT("dropped_smbus", stats.mgpdc), IGC_STAT("os2bmc_rx_by_bmc", stats.o2bgptc), IGC_STAT("os2bmc_tx_by_bmc", stats.b2ospc), IGC_STAT("os2bmc_tx_by_host", stats.o2bspc), IGC_STAT("os2bmc_rx_by_host", stats.b2ogprc), IGC_STAT("tx_hwtstamp_timeouts", tx_hwtstamp_timeouts), IGC_STAT("tx_hwtstamp_skipped", tx_hwtstamp_skipped), IGC_STAT("rx_hwtstamp_cleared", rx_hwtstamp_cleared), IGC_STAT("tx_lpi_counter", stats.tlpic), IGC_STAT("rx_lpi_counter", stats.rlpic), IGC_STAT("qbv_config_change_errors", qbv_config_change_errors), }; #define IGC_NETDEV_STAT(_net_stat) { \ .stat_string = __stringify(_net_stat), \ .sizeof_stat = sizeof_field(struct rtnl_link_stats64, _net_stat), \ .stat_offset = offsetof(struct rtnl_link_stats64, _net_stat) \ } static const struct igc_stats igc_gstrings_net_stats[] = { IGC_NETDEV_STAT(rx_errors), IGC_NETDEV_STAT(tx_errors), IGC_NETDEV_STAT(tx_dropped), IGC_NETDEV_STAT(rx_length_errors), IGC_NETDEV_STAT(rx_over_errors), IGC_NETDEV_STAT(rx_frame_errors), IGC_NETDEV_STAT(rx_fifo_errors), IGC_NETDEV_STAT(tx_fifo_errors), IGC_NETDEV_STAT(tx_heartbeat_errors) }; enum igc_diagnostics_results { TEST_REG = 0, TEST_EEP, TEST_IRQ, TEST_LOOP, TEST_LINK }; static const char igc_gstrings_test[][ETH_GSTRING_LEN] = { [TEST_REG] = "Register test (offline)", [TEST_EEP] = "Eeprom test (offline)", [TEST_IRQ] = "Interrupt test (offline)", [TEST_LOOP] = "Loopback test (offline)", [TEST_LINK] = "Link test (on/offline)" }; #define IGC_TEST_LEN (sizeof(igc_gstrings_test) / ETH_GSTRING_LEN) #define IGC_GLOBAL_STATS_LEN \ (sizeof(igc_gstrings_stats) / sizeof(struct igc_stats)) #define IGC_NETDEV_STATS_LEN \ (sizeof(igc_gstrings_net_stats) / sizeof(struct igc_stats)) #define IGC_RX_QUEUE_STATS_LEN \ (sizeof(struct igc_rx_queue_stats) / sizeof(u64)) #define IGC_TX_QUEUE_STATS_LEN 3 /* packets, bytes, restart_queue */ #define IGC_QUEUE_STATS_LEN \ ((((struct igc_adapter *)netdev_priv(netdev))->num_rx_queues * \ IGC_RX_QUEUE_STATS_LEN) + \ (((struct igc_adapter *)netdev_priv(netdev))->num_tx_queues * \ IGC_TX_QUEUE_STATS_LEN)) #define IGC_STATS_LEN \ (IGC_GLOBAL_STATS_LEN + IGC_NETDEV_STATS_LEN + IGC_QUEUE_STATS_LEN) static const char igc_priv_flags_strings[][ETH_GSTRING_LEN] = { #define IGC_PRIV_FLAGS_LEGACY_RX BIT(0) "legacy-rx", }; #define IGC_PRIV_FLAGS_STR_LEN ARRAY_SIZE(igc_priv_flags_strings) static void igc_ethtool_get_drvinfo(struct net_device *netdev, struct ethtool_drvinfo *drvinfo) { struct igc_adapter *adapter = netdev_priv(netdev); struct igc_hw *hw = &adapter->hw; u16 nvm_version = 0; u16 gphy_version; strscpy(drvinfo->driver, igc_driver_name, sizeof(drvinfo->driver)); /* NVM image version is reported as firmware version for i225 device */ hw->nvm.ops.read(hw, IGC_NVM_DEV_STARTER, 1, &nvm_version); /* gPHY firmware version is reported as PHY FW version */ gphy_version = igc_read_phy_fw_version(hw); scnprintf(adapter->fw_version, sizeof(adapter->fw_version), "%x:%x", nvm_version, gphy_version); strscpy(drvinfo->fw_version, adapter->fw_version, sizeof(drvinfo->fw_version)); strscpy(drvinfo->bus_info, pci_name(adapter->pdev), sizeof(drvinfo->bus_info)); drvinfo->n_priv_flags = IGC_PRIV_FLAGS_STR_LEN; } static int igc_ethtool_get_regs_len(struct net_device *netdev) { return IGC_REGS_LEN * sizeof(u32); } static void igc_ethtool_get_regs(struct net_device *netdev, struct ethtool_regs *regs, void *p) { struct igc_adapter *adapter = netdev_priv(netdev); struct igc_hw *hw = &adapter->hw; u32 *regs_buff = p; u8 i; memset(p, 0, IGC_REGS_LEN * sizeof(u32)); regs->version = (2u << 24) | (hw->revision_id << 16) | hw->device_id; /* General Registers */ regs_buff[0] = rd32(IGC_CTRL); regs_buff[1] = rd32(IGC_STATUS); regs_buff[2] = rd32(IGC_CTRL_EXT); regs_buff[3] = rd32(IGC_MDIC); regs_buff[4] = rd32(IGC_CONNSW); /* NVM Register */ regs_buff[5] = rd32(IGC_EECD); /* Interrupt */ /* Reading EICS for EICR because they read the * same but EICS does not clear on read */ regs_buff[6] = rd32(IGC_EICS); regs_buff[7] = rd32(IGC_EICS); regs_buff[8] = rd32(IGC_EIMS); regs_buff[9] = rd32(IGC_EIMC); regs_buff[10] = rd32(IGC_EIAC); regs_buff[11] = rd32(IGC_EIAM); /* Reading ICS for ICR because they read the * same but ICS does not clear on read */ regs_buff[12] = rd32(IGC_ICS); regs_buff[13] = rd32(IGC_ICS); regs_buff[14] = rd32(IGC_IMS); regs_buff[15] = rd32(IGC_IMC); regs_buff[16] = rd32(IGC_IAC); regs_buff[17] = rd32(IGC_IAM); /* Flow Control */ regs_buff[18] = rd32(IGC_FCAL); regs_buff[19] = rd32(IGC_FCAH); regs_buff[20] = rd32(IGC_FCTTV); regs_buff[21] = rd32(IGC_FCRTL); regs_buff[22] = rd32(IGC_FCRTH); regs_buff[23] = rd32(IGC_FCRTV); /* Receive */ regs_buff[24] = rd32(IGC_RCTL); regs_buff[25] = rd32(IGC_RXCSUM); regs_buff[26] = rd32(IGC_RLPML); regs_buff[27] = rd32(IGC_RFCTL); /* Transmit */ regs_buff[28] = rd32(IGC_TCTL); regs_buff[29] = rd32(IGC_TIPG); /* Wake Up */ /* MAC */ /* Statistics */ regs_buff[30] = adapter->stats.crcerrs; regs_buff[31] = adapter->stats.algnerrc; regs_buff[32] = adapter->stats.symerrs; regs_buff[33] = adapter->stats.rxerrc; regs_buff[34] = adapter->stats.mpc; regs_buff[35] = adapter->stats.scc; regs_buff[36] = adapter->stats.ecol; regs_buff[37] = adapter->stats.mcc; regs_buff[38] = adapter->stats.latecol; regs_buff[39] = adapter->stats.colc; regs_buff[40] = adapter->stats.dc; regs_buff[41] = adapter->stats.tncrs; regs_buff[42] = adapter->stats.sec; regs_buff[43] = adapter->stats.htdpmc; regs_buff[44] = adapter->stats.rlec; regs_buff[45] = adapter->stats.xonrxc; regs_buff[46] = adapter->stats.xontxc; regs_buff[47] = adapter->stats.xoffrxc; regs_buff[48] = adapter->stats.xofftxc; regs_buff[49] = adapter->stats.fcruc; regs_buff[50] = adapter->stats.prc64; regs_buff[51] = adapter->stats.prc127; regs_buff[52] = adapter->stats.prc255; regs_buff[53] = adapter->stats.prc511; regs_buff[54] = adapter->stats.prc1023; regs_buff[55] = adapter->stats.prc1522; regs_buff[56] = adapter->stats.gprc; regs_buff[57] = adapter->stats.bprc; regs_buff[58] = adapter->stats.mprc; regs_buff[59] = adapter->stats.gptc; regs_buff[60] = adapter->stats.gorc; regs_buff[61] = adapter->stats.gotc; regs_buff[62] = adapter->stats.rnbc; regs_buff[63] = adapter->stats.ruc; regs_buff[64] = adapter->stats.rfc; regs_buff[65] = adapter->stats.roc; regs_buff[66] = adapter->stats.rjc; regs_buff[67] = adapter->stats.mgprc; regs_buff[68] = adapter->stats.mgpdc; regs_buff[69] = adapter->stats.mgptc; regs_buff[70] = adapter->stats.tor; regs_buff[71] = adapter->stats.tot; regs_buff[72] = adapter->stats.tpr; regs_buff[73] = adapter->stats.tpt; regs_buff[74] = adapter->stats.ptc64; regs_buff[75] = adapter->stats.ptc127; regs_buff[76] = adapter->stats.ptc255; regs_buff[77] = adapter->stats.ptc511; regs_buff[78] = adapter->stats.ptc1023; regs_buff[79] = adapter->stats.ptc1522; regs_buff[80] = adapter->stats.mptc; regs_buff[81] = adapter->stats.bptc; regs_buff[82] = adapter->stats.tsctc; regs_buff[83] = adapter->stats.iac; regs_buff[84] = adapter->stats.rpthc; regs_buff[85] = adapter->stats.hgptc; regs_buff[86] = adapter->stats.hgorc; regs_buff[87] = adapter->stats.hgotc; regs_buff[88] = adapter->stats.lenerrs; regs_buff[89] = adapter->stats.scvpc; regs_buff[90] = adapter->stats.hrmpc; for (i = 0; i < 4; i++) regs_buff[91 + i] = rd32(IGC_SRRCTL(i)); for (i = 0; i < 4; i++) regs_buff[95 + i] = rd32(IGC_PSRTYPE(i)); for (i = 0; i < 4; i++) regs_buff[99 + i] = rd32(IGC_RDBAL(i)); for (i = 0; i < 4; i++) regs_buff[103 + i] = rd32(IGC_RDBAH(i)); for (i = 0; i < 4; i++) regs_buff[107 + i] = rd32(IGC_RDLEN(i)); for (i = 0; i < 4; i++) regs_buff[111 + i] = rd32(IGC_RDH(i)); for (i = 0; i < 4; i++) regs_buff[115 + i] = rd32(IGC_RDT(i)); for (i = 0; i < 4; i++) regs_buff[119 + i] = rd32(IGC_RXDCTL(i)); for (i = 0; i < 10; i++) regs_buff[123 + i] = rd32(IGC_EITR(i)); for (i = 0; i < 16; i++) regs_buff[139 + i] = rd32(IGC_RAL(i)); for (i = 0; i < 16; i++) regs_buff[145 + i] = rd32(IGC_RAH(i)); for (i = 0; i < 4; i++) regs_buff[149 + i] = rd32(IGC_TDBAL(i)); for (i = 0; i < 4; i++) regs_buff[152 + i] = rd32(IGC_TDBAH(i)); for (i = 0; i < 4; i++) regs_buff[156 + i] = rd32(IGC_TDLEN(i)); for (i = 0; i < 4; i++) regs_buff[160 + i] = rd32(IGC_TDH(i)); for (i = 0; i < 4; i++) regs_buff[164 + i] = rd32(IGC_TDT(i)); for (i = 0; i < 4; i++) regs_buff[168 + i] = rd32(IGC_TXDCTL(i)); /* XXX: Due to a bug few lines above, RAL and RAH registers are * overwritten. To preserve the ABI, we write these registers again in * regs_buff. */ for (i = 0; i < 16; i++) regs_buff[172 + i] = rd32(IGC_RAL(i)); for (i = 0; i < 16; i++) regs_buff[188 + i] = rd32(IGC_RAH(i)); regs_buff[204] = rd32(IGC_VLANPQF); for (i = 0; i < 8; i++) regs_buff[205 + i] = rd32(IGC_ETQF(i)); regs_buff[213] = adapter->stats.tlpic; regs_buff[214] = adapter->stats.rlpic; } static void igc_ethtool_get_wol(struct net_device *netdev, struct ethtool_wolinfo *wol) { struct igc_adapter *adapter = netdev_priv(netdev); wol->wolopts = 0; if (!(adapter->flags & IGC_FLAG_WOL_SUPPORTED)) return; wol->supported = WAKE_UCAST | WAKE_MCAST | WAKE_BCAST | WAKE_MAGIC | WAKE_PHY; /* apply any specific unsupported masks here */ switch (adapter->hw.device_id) { default: break; } if (adapter->wol & IGC_WUFC_EX) wol->wolopts |= WAKE_UCAST; if (adapter->wol & IGC_WUFC_MC) wol->wolopts |= WAKE_MCAST; if (adapter->wol & IGC_WUFC_BC) wol->wolopts |= WAKE_BCAST; if (adapter->wol & IGC_WUFC_MAG) wol->wolopts |= WAKE_MAGIC; if (adapter->wol & IGC_WUFC_LNKC) wol->wolopts |= WAKE_PHY; } static int igc_ethtool_set_wol(struct net_device *netdev, struct ethtool_wolinfo *wol) { struct igc_adapter *adapter = netdev_priv(netdev); if (wol->wolopts & (WAKE_ARP | WAKE_MAGICSECURE | WAKE_FILTER)) return -EOPNOTSUPP; if (!(adapter->flags & IGC_FLAG_WOL_SUPPORTED)) return wol->wolopts ? -EOPNOTSUPP : 0; /* these settings will always override what we currently have */ adapter->wol = 0; if (wol->wolopts & WAKE_UCAST) adapter->wol |= IGC_WUFC_EX; if (wol->wolopts & WAKE_MCAST) adapter->wol |= IGC_WUFC_MC; if (wol->wolopts & WAKE_BCAST) adapter->wol |= IGC_WUFC_BC; if (wol->wolopts & WAKE_MAGIC) adapter->wol |= IGC_WUFC_MAG; if (wol->wolopts & WAKE_PHY) adapter->wol |= IGC_WUFC_LNKC; device_set_wakeup_enable(&adapter->pdev->dev, adapter->wol); return 0; } static u32 igc_ethtool_get_msglevel(struct net_device *netdev) { struct igc_adapter *adapter = netdev_priv(netdev); return adapter->msg_enable; } static void igc_ethtool_set_msglevel(struct net_device *netdev, u32 data) { struct igc_adapter *adapter = netdev_priv(netdev); adapter->msg_enable = data; } static int igc_ethtool_nway_reset(struct net_device *netdev) { struct igc_adapter *adapter = netdev_priv(netdev); if (netif_running(netdev)) igc_reinit_locked(adapter); return 0; } static u32 igc_ethtool_get_link(struct net_device *netdev) { struct igc_adapter *adapter = netdev_priv(netdev); struct igc_mac_info *mac = &adapter->hw.mac; /* If the link is not reported up to netdev, interrupts are disabled, * and so the physical link state may have changed since we last * looked. Set get_link_status to make sure that the true link * state is interrogated, rather than pulling a cached and possibly * stale link state from the driver. */ if (!netif_carrier_ok(netdev)) mac->get_link_status = 1; return igc_has_link(adapter); } static int igc_ethtool_get_eeprom_len(struct net_device *netdev) { struct igc_adapter *adapter = netdev_priv(netdev); return adapter->hw.nvm.word_size * 2; } static int igc_ethtool_get_eeprom(struct net_device *netdev, struct ethtool_eeprom *eeprom, u8 *bytes) { struct igc_adapter *adapter = netdev_priv(netdev); struct igc_hw *hw = &adapter->hw; int first_word, last_word; u16 *eeprom_buff; int ret_val = 0; u16 i; if (eeprom->len == 0) return -EINVAL; eeprom->magic = hw->vendor_id | (hw->device_id << 16); first_word = eeprom->offset >> 1; last_word = (eeprom->offset + eeprom->len - 1) >> 1; eeprom_buff = kmalloc_array(last_word - first_word + 1, sizeof(u16), GFP_KERNEL); if (!eeprom_buff) return -ENOMEM; if (hw->nvm.type == igc_nvm_eeprom_spi) { ret_val = hw->nvm.ops.read(hw, first_word, last_word - first_word + 1, eeprom_buff); } else { for (i = 0; i < last_word - first_word + 1; i++) { ret_val = hw->nvm.ops.read(hw, first_word + i, 1, &eeprom_buff[i]); if (ret_val) break; } } /* Device's eeprom is always little-endian, word addressable */ for (i = 0; i < last_word - first_word + 1; i++) le16_to_cpus(&eeprom_buff[i]); memcpy(bytes, (u8 *)eeprom_buff + (eeprom->offset & 1), eeprom->len); kfree(eeprom_buff); return ret_val; } static int igc_ethtool_set_eeprom(struct net_device *netdev, struct ethtool_eeprom *eeprom, u8 *bytes) { struct igc_adapter *adapter = netdev_priv(netdev); struct igc_hw *hw = &adapter->hw; int max_len, first_word, last_word, ret_val = 0; u16 *eeprom_buff; void *ptr; u16 i; if (eeprom->len == 0) return -EOPNOTSUPP; if (hw->mac.type >= igc_i225 && !igc_get_flash_presence_i225(hw)) { return -EOPNOTSUPP; } if (eeprom->magic != (hw->vendor_id | (hw->device_id << 16))) return -EFAULT; max_len = hw->nvm.word_size * 2; first_word = eeprom->offset >> 1; last_word = (eeprom->offset + eeprom->len - 1) >> 1; eeprom_buff = kmalloc(max_len, GFP_KERNEL); if (!eeprom_buff) return -ENOMEM; ptr = (void *)eeprom_buff; if (eeprom->offset & 1) { /* need read/modify/write of first changed EEPROM word * only the second byte of the word is being modified */ ret_val = hw->nvm.ops.read(hw, first_word, 1, &eeprom_buff[0]); ptr++; } if (((eeprom->offset + eeprom->len) & 1) && ret_val == 0) { /* need read/modify/write of last changed EEPROM word * only the first byte of the word is being modified */ ret_val = hw->nvm.ops.read(hw, last_word, 1, &eeprom_buff[last_word - first_word]); } /* Device's eeprom is always little-endian, word addressable */ for (i = 0; i < last_word - first_word + 1; i++) le16_to_cpus(&eeprom_buff[i]); memcpy(ptr, bytes, eeprom->len); for (i = 0; i < last_word - first_word + 1; i++) cpu_to_le16s(&eeprom_buff[i]); ret_val = hw->nvm.ops.write(hw, first_word, last_word - first_word + 1, eeprom_buff); /* Update the checksum if nvm write succeeded */ if (ret_val == 0) hw->nvm.ops.update(hw); kfree(eeprom_buff); return ret_val; } static void igc_ethtool_get_ringparam(struct net_device *netdev, struct ethtool_ringparam *ring, struct kernel_ethtool_ringparam *kernel_ering, struct netlink_ext_ack *extack) { struct igc_adapter *adapter = netdev_priv(netdev); ring->rx_max_pending = IGC_MAX_RXD; ring->tx_max_pending = IGC_MAX_TXD; ring->rx_pending = adapter->rx_ring_count; ring->tx_pending = adapter->tx_ring_count; } static int igc_ethtool_set_ringparam(struct net_device *netdev, struct ethtool_ringparam *ring, struct kernel_ethtool_ringparam *kernel_ering, struct netlink_ext_ack *extack) { struct igc_adapter *adapter = netdev_priv(netdev); struct igc_ring *temp_ring; u16 new_rx_count, new_tx_count; int i, err = 0; if (ring->rx_mini_pending || ring->rx_jumbo_pending) return -EINVAL; new_rx_count = min_t(u32, ring->rx_pending, IGC_MAX_RXD); new_rx_count = max_t(u16, new_rx_count, IGC_MIN_RXD); new_rx_count = ALIGN(new_rx_count, REQ_RX_DESCRIPTOR_MULTIPLE); new_tx_count = min_t(u32, ring->tx_pending, IGC_MAX_TXD); new_tx_count = max_t(u16, new_tx_count, IGC_MIN_TXD); new_tx_count = ALIGN(new_tx_count, REQ_TX_DESCRIPTOR_MULTIPLE); if (new_tx_count == adapter->tx_ring_count && new_rx_count == adapter->rx_ring_count) { /* nothing to do */ return 0; } while (test_and_set_bit(__IGC_RESETTING, &adapter->state)) usleep_range(1000, 2000); if (!netif_running(adapter->netdev)) { for (i = 0; i < adapter->num_tx_queues; i++) adapter->tx_ring[i]->count = new_tx_count; for (i = 0; i < adapter->num_rx_queues; i++) adapter->rx_ring[i]->count = new_rx_count; adapter->tx_ring_count = new_tx_count; adapter->rx_ring_count = new_rx_count; goto clear_reset; } if (adapter->num_tx_queues > adapter->num_rx_queues) temp_ring = vmalloc(array_size(sizeof(struct igc_ring), adapter->num_tx_queues)); else temp_ring = vmalloc(array_size(sizeof(struct igc_ring), adapter->num_rx_queues)); if (!temp_ring) { err = -ENOMEM; goto clear_reset; } igc_down(adapter); /* We can't just free everything and then setup again, * because the ISRs in MSI-X mode get passed pointers * to the Tx and Rx ring structs. */ if (new_tx_count != adapter->tx_ring_count) { for (i = 0; i < adapter->num_tx_queues; i++) { memcpy(&temp_ring[i], adapter->tx_ring[i], sizeof(struct igc_ring)); temp_ring[i].count = new_tx_count; err = igc_setup_tx_resources(&temp_ring[i]); if (err) { while (i) { i--; igc_free_tx_resources(&temp_ring[i]); } goto err_setup; } } for (i = 0; i < adapter->num_tx_queues; i++) { igc_free_tx_resources(adapter->tx_ring[i]); memcpy(adapter->tx_ring[i], &temp_ring[i], sizeof(struct igc_ring)); } adapter->tx_ring_count = new_tx_count; } if (new_rx_count != adapter->rx_ring_count) { for (i = 0; i < adapter->num_rx_queues; i++) { memcpy(&temp_ring[i], adapter->rx_ring[i], sizeof(struct igc_ring)); temp_ring[i].count = new_rx_count; err = igc_setup_rx_resources(&temp_ring[i]); if (err) { while (i) { i--; igc_free_rx_resources(&temp_ring[i]); } goto err_setup; } } for (i = 0; i < adapter->num_rx_queues; i++) { igc_free_rx_resources(adapter->rx_ring[i]); memcpy(adapter->rx_ring[i], &temp_ring[i], sizeof(struct igc_ring)); } adapter->rx_ring_count = new_rx_count; } err_setup: igc_up(adapter); vfree(temp_ring); clear_reset: clear_bit(__IGC_RESETTING, &adapter->state); return err; } static void igc_ethtool_get_pauseparam(struct net_device *netdev, struct ethtool_pauseparam *pause) { struct igc_adapter *adapter = netdev_priv(netdev); struct igc_hw *hw = &adapter->hw; pause->autoneg = (adapter->fc_autoneg ? AUTONEG_ENABLE : AUTONEG_DISABLE); if (hw->fc.current_mode == igc_fc_rx_pause) { pause->rx_pause = 1; } else if (hw->fc.current_mode == igc_fc_tx_pause) { pause->tx_pause = 1; } else if (hw->fc.current_mode == igc_fc_full) { pause->rx_pause = 1; pause->tx_pause = 1; } } static int igc_ethtool_set_pauseparam(struct net_device *netdev, struct ethtool_pauseparam *pause) { struct igc_adapter *adapter = netdev_priv(netdev); struct igc_hw *hw = &adapter->hw; int retval = 0; adapter->fc_autoneg = pause->autoneg; while (test_and_set_bit(__IGC_RESETTING, &adapter->state)) usleep_range(1000, 2000); if (adapter->fc_autoneg == AUTONEG_ENABLE) { hw->fc.requested_mode = igc_fc_default; if (netif_running(adapter->netdev)) { igc_down(adapter); igc_up(adapter); } else { igc_reset(adapter); } } else { if (pause->rx_pause && pause->tx_pause) hw->fc.requested_mode = igc_fc_full; else if (pause->rx_pause && !pause->tx_pause) hw->fc.requested_mode = igc_fc_rx_pause; else if (!pause->rx_pause && pause->tx_pause) hw->fc.requested_mode = igc_fc_tx_pause; else if (!pause->rx_pause && !pause->tx_pause) hw->fc.requested_mode = igc_fc_none; hw->fc.current_mode = hw->fc.requested_mode; retval = ((hw->phy.media_type == igc_media_type_copper) ? igc_force_mac_fc(hw) : igc_setup_link(hw)); } clear_bit(__IGC_RESETTING, &adapter->state); return retval; } static void igc_ethtool_get_strings(struct net_device *netdev, u32 stringset, u8 *data) { struct igc_adapter *adapter = netdev_priv(netdev); u8 *p = data; int i; switch (stringset) { case ETH_SS_TEST: memcpy(data, *igc_gstrings_test, IGC_TEST_LEN * ETH_GSTRING_LEN); break; case ETH_SS_STATS: for (i = 0; i < IGC_GLOBAL_STATS_LEN; i++) ethtool_sprintf(&p, igc_gstrings_stats[i].stat_string); for (i = 0; i < IGC_NETDEV_STATS_LEN; i++) ethtool_sprintf(&p, igc_gstrings_net_stats[i].stat_string); for (i = 0; i < adapter->num_tx_queues; i++) { ethtool_sprintf(&p, "tx_queue_%u_packets", i); ethtool_sprintf(&p, "tx_queue_%u_bytes", i); ethtool_sprintf(&p, "tx_queue_%u_restart", i); } for (i = 0; i < adapter->num_rx_queues; i++) { ethtool_sprintf(&p, "rx_queue_%u_packets", i); ethtool_sprintf(&p, "rx_queue_%u_bytes", i); ethtool_sprintf(&p, "rx_queue_%u_drops", i); ethtool_sprintf(&p, "rx_queue_%u_csum_err", i); ethtool_sprintf(&p, "rx_queue_%u_alloc_failed", i); } /* BUG_ON(p - data != IGC_STATS_LEN * ETH_GSTRING_LEN); */ break; case ETH_SS_PRIV_FLAGS: memcpy(data, igc_priv_flags_strings, IGC_PRIV_FLAGS_STR_LEN * ETH_GSTRING_LEN); break; } } static int igc_ethtool_get_sset_count(struct net_device *netdev, int sset) { switch (sset) { case ETH_SS_STATS: return IGC_STATS_LEN; case ETH_SS_TEST: return IGC_TEST_LEN; case ETH_SS_PRIV_FLAGS: return IGC_PRIV_FLAGS_STR_LEN; default: return -ENOTSUPP; } } static void igc_ethtool_get_stats(struct net_device *netdev, struct ethtool_stats *stats, u64 *data) { struct igc_adapter *adapter = netdev_priv(netdev); struct rtnl_link_stats64 *net_stats = &adapter->stats64; unsigned int start; struct igc_ring *ring; int i, j; char *p; spin_lock(&adapter->stats64_lock); igc_update_stats(adapter); for (i = 0; i < IGC_GLOBAL_STATS_LEN; i++) { p = (char *)adapter + igc_gstrings_stats[i].stat_offset; data[i] = (igc_gstrings_stats[i].sizeof_stat == sizeof(u64)) ? *(u64 *)p : *(u32 *)p; } for (j = 0; j < IGC_NETDEV_STATS_LEN; j++, i++) { p = (char *)net_stats + igc_gstrings_net_stats[j].stat_offset; data[i] = (igc_gstrings_net_stats[j].sizeof_stat == sizeof(u64)) ? *(u64 *)p : *(u32 *)p; } for (j = 0; j < adapter->num_tx_queues; j++) { u64 restart2; ring = adapter->tx_ring[j]; do { start = u64_stats_fetch_begin(&ring->tx_syncp); data[i] = ring->tx_stats.packets; data[i + 1] = ring->tx_stats.bytes; data[i + 2] = ring->tx_stats.restart_queue; } while (u64_stats_fetch_retry(&ring->tx_syncp, start)); do { start = u64_stats_fetch_begin(&ring->tx_syncp2); restart2 = ring->tx_stats.restart_queue2; } while (u64_stats_fetch_retry(&ring->tx_syncp2, start)); data[i + 2] += restart2; i += IGC_TX_QUEUE_STATS_LEN; } for (j = 0; j < adapter->num_rx_queues; j++) { ring = adapter->rx_ring[j]; do { start = u64_stats_fetch_begin(&ring->rx_syncp); data[i] = ring->rx_stats.packets; data[i + 1] = ring->rx_stats.bytes; data[i + 2] = ring->rx_stats.drops; data[i + 3] = ring->rx_stats.csum_err; data[i + 4] = ring->rx_stats.alloc_failed; } while (u64_stats_fetch_retry(&ring->rx_syncp, start)); i += IGC_RX_QUEUE_STATS_LEN; } spin_unlock(&adapter->stats64_lock); } static int igc_ethtool_get_previous_rx_coalesce(struct igc_adapter *adapter) { return (adapter->rx_itr_setting <= 3) ? adapter->rx_itr_setting : adapter->rx_itr_setting >> 2; } static int igc_ethtool_get_previous_tx_coalesce(struct igc_adapter *adapter) { return (adapter->tx_itr_setting <= 3) ? adapter->tx_itr_setting : adapter->tx_itr_setting >> 2; } static int igc_ethtool_get_coalesce(struct net_device *netdev, struct ethtool_coalesce *ec, struct kernel_ethtool_coalesce *kernel_coal, struct netlink_ext_ack *extack) { struct igc_adapter *adapter = netdev_priv(netdev); ec->rx_coalesce_usecs = igc_ethtool_get_previous_rx_coalesce(adapter); ec->tx_coalesce_usecs = igc_ethtool_get_previous_tx_coalesce(adapter); return 0; } static int igc_ethtool_set_coalesce(struct net_device *netdev, struct ethtool_coalesce *ec, struct kernel_ethtool_coalesce *kernel_coal, struct netlink_ext_ack *extack) { struct igc_adapter *adapter = netdev_priv(netdev); int i; if (ec->rx_coalesce_usecs > IGC_MAX_ITR_USECS || (ec->rx_coalesce_usecs > 3 && ec->rx_coalesce_usecs < IGC_MIN_ITR_USECS) || ec->rx_coalesce_usecs == 2) return -EINVAL; if (ec->tx_coalesce_usecs > IGC_MAX_ITR_USECS || (ec->tx_coalesce_usecs > 3 && ec->tx_coalesce_usecs < IGC_MIN_ITR_USECS) || ec->tx_coalesce_usecs == 2) return -EINVAL; if ((adapter->flags & IGC_FLAG_QUEUE_PAIRS) && ec->tx_coalesce_usecs != igc_ethtool_get_previous_tx_coalesce(adapter)) { NL_SET_ERR_MSG_MOD(extack, "Queue Pair mode enabled, both Rx and Tx coalescing controlled by rx-usecs"); return -EINVAL; } /* If ITR is disabled, disable DMAC */ if (ec->rx_coalesce_usecs == 0) { if (adapter->flags & IGC_FLAG_DMAC) adapter->flags &= ~IGC_FLAG_DMAC; } /* convert to rate of irq's per second */ if (ec->rx_coalesce_usecs && ec->rx_coalesce_usecs <= 3) adapter->rx_itr_setting = ec->rx_coalesce_usecs; else adapter->rx_itr_setting = ec->rx_coalesce_usecs << 2; /* convert to rate of irq's per second */ if (adapter->flags & IGC_FLAG_QUEUE_PAIRS) adapter->tx_itr_setting = adapter->rx_itr_setting; else if (ec->tx_coalesce_usecs && ec->tx_coalesce_usecs <= 3) adapter->tx_itr_setting = ec->tx_coalesce_usecs; else adapter->tx_itr_setting = ec->tx_coalesce_usecs << 2; for (i = 0; i < adapter->num_q_vectors; i++) { struct igc_q_vector *q_vector = adapter->q_vector[i]; q_vector->tx.work_limit = adapter->tx_work_limit; if (q_vector->rx.ring) q_vector->itr_val = adapter->rx_itr_setting; else q_vector->itr_val = adapter->tx_itr_setting; if (q_vector->itr_val && q_vector->itr_val <= 3) q_vector->itr_val = IGC_START_ITR; q_vector->set_itr = 1; } return 0; } #define ETHER_TYPE_FULL_MASK ((__force __be16)~0) static int igc_ethtool_get_nfc_rule(struct igc_adapter *adapter, struct ethtool_rxnfc *cmd) { struct ethtool_rx_flow_spec *fsp = &cmd->fs; struct igc_nfc_rule *rule = NULL; cmd->data = IGC_MAX_RXNFC_RULES; mutex_lock(&adapter->nfc_rule_lock); rule = igc_get_nfc_rule(adapter, fsp->location); if (!rule) goto out; fsp->flow_type = ETHER_FLOW; fsp->ring_cookie = rule->action; if (rule->filter.match_flags & IGC_FILTER_FLAG_ETHER_TYPE) { fsp->h_u.ether_spec.h_proto = htons(rule->filter.etype); fsp->m_u.ether_spec.h_proto = ETHER_TYPE_FULL_MASK; } if (rule->filter.match_flags & IGC_FILTER_FLAG_VLAN_TCI) { fsp->flow_type |= FLOW_EXT; fsp->h_ext.vlan_tci = htons(rule->filter.vlan_tci); fsp->m_ext.vlan_tci = htons(VLAN_PRIO_MASK); } if (rule->filter.match_flags & IGC_FILTER_FLAG_DST_MAC_ADDR) { ether_addr_copy(fsp->h_u.ether_spec.h_dest, rule->filter.dst_addr); eth_broadcast_addr(fsp->m_u.ether_spec.h_dest); } if (rule->filter.match_flags & IGC_FILTER_FLAG_SRC_MAC_ADDR) { ether_addr_copy(fsp->h_u.ether_spec.h_source, rule->filter.src_addr); eth_broadcast_addr(fsp->m_u.ether_spec.h_source); } if (rule->filter.match_flags & IGC_FILTER_FLAG_USER_DATA) { fsp->flow_type |= FLOW_EXT; memcpy(fsp->h_ext.data, rule->filter.user_data, sizeof(fsp->h_ext.data)); memcpy(fsp->m_ext.data, rule->filter.user_mask, sizeof(fsp->m_ext.data)); } mutex_unlock(&adapter->nfc_rule_lock); return 0; out: mutex_unlock(&adapter->nfc_rule_lock); return -EINVAL; } static int igc_ethtool_get_nfc_rules(struct igc_adapter *adapter, struct ethtool_rxnfc *cmd, u32 *rule_locs) { struct igc_nfc_rule *rule; int cnt = 0; cmd->data = IGC_MAX_RXNFC_RULES; mutex_lock(&adapter->nfc_rule_lock); list_for_each_entry(rule, &adapter->nfc_rule_list, list) { if (cnt == cmd->rule_cnt) { mutex_unlock(&adapter->nfc_rule_lock); return -EMSGSIZE; } rule_locs[cnt] = rule->location; cnt++; } mutex_unlock(&adapter->nfc_rule_lock); cmd->rule_cnt = cnt; return 0; } static int igc_ethtool_get_rss_hash_opts(struct igc_adapter *adapter, struct ethtool_rxnfc *cmd) { cmd->data = 0; /* Report default options for RSS on igc */ switch (cmd->flow_type) { case TCP_V4_FLOW: cmd->data |= RXH_L4_B_0_1 | RXH_L4_B_2_3; fallthrough; case UDP_V4_FLOW: if (adapter->flags & IGC_FLAG_RSS_FIELD_IPV4_UDP) cmd->data |= RXH_L4_B_0_1 | RXH_L4_B_2_3; fallthrough; case SCTP_V4_FLOW: case AH_ESP_V4_FLOW: case AH_V4_FLOW: case ESP_V4_FLOW: case IPV4_FLOW: cmd->data |= RXH_IP_SRC | RXH_IP_DST; break; case TCP_V6_FLOW: cmd->data |= RXH_L4_B_0_1 | RXH_L4_B_2_3; fallthrough; case UDP_V6_FLOW: if (adapter->flags & IGC_FLAG_RSS_FIELD_IPV6_UDP) cmd->data |= RXH_L4_B_0_1 | RXH_L4_B_2_3; fallthrough; case SCTP_V6_FLOW: case AH_ESP_V6_FLOW: case AH_V6_FLOW: case ESP_V6_FLOW: case IPV6_FLOW: cmd->data |= RXH_IP_SRC | RXH_IP_DST; break; default: return -EINVAL; } return 0; } static int igc_ethtool_get_rxnfc(struct net_device *dev, struct ethtool_rxnfc *cmd, u32 *rule_locs) { struct igc_adapter *adapter = netdev_priv(dev); switch (cmd->cmd) { case ETHTOOL_GRXRINGS: cmd->data = adapter->num_rx_queues; return 0; case ETHTOOL_GRXCLSRLCNT: cmd->rule_cnt = adapter->nfc_rule_count; return 0; case ETHTOOL_GRXCLSRULE: return igc_ethtool_get_nfc_rule(adapter, cmd); case ETHTOOL_GRXCLSRLALL: return igc_ethtool_get_nfc_rules(adapter, cmd, rule_locs); case ETHTOOL_GRXFH: return igc_ethtool_get_rss_hash_opts(adapter, cmd); default: return -EOPNOTSUPP; } } #define UDP_RSS_FLAGS (IGC_FLAG_RSS_FIELD_IPV4_UDP | \ IGC_FLAG_RSS_FIELD_IPV6_UDP) static int igc_ethtool_set_rss_hash_opt(struct igc_adapter *adapter, struct ethtool_rxnfc *nfc) { u32 flags = adapter->flags; /* RSS does not support anything other than hashing * to queues on src and dst IPs and ports */ if (nfc->data & ~(RXH_IP_SRC | RXH_IP_DST | RXH_L4_B_0_1 | RXH_L4_B_2_3)) return -EINVAL; switch (nfc->flow_type) { case TCP_V4_FLOW: case TCP_V6_FLOW: if (!(nfc->data & RXH_IP_SRC) || !(nfc->data & RXH_IP_DST) || !(nfc->data & RXH_L4_B_0_1) || !(nfc->data & RXH_L4_B_2_3)) return -EINVAL; break; case UDP_V4_FLOW: if (!(nfc->data & RXH_IP_SRC) || !(nfc->data & RXH_IP_DST)) return -EINVAL; switch (nfc->data & (RXH_L4_B_0_1 | RXH_L4_B_2_3)) { case 0: flags &= ~IGC_FLAG_RSS_FIELD_IPV4_UDP; break; case (RXH_L4_B_0_1 | RXH_L4_B_2_3): flags |= IGC_FLAG_RSS_FIELD_IPV4_UDP; break; default: return -EINVAL; } break; case UDP_V6_FLOW: if (!(nfc->data & RXH_IP_SRC) || !(nfc->data & RXH_IP_DST)) return -EINVAL; switch (nfc->data & (RXH_L4_B_0_1 | RXH_L4_B_2_3)) { case 0: flags &= ~IGC_FLAG_RSS_FIELD_IPV6_UDP; break; case (RXH_L4_B_0_1 | RXH_L4_B_2_3): flags |= IGC_FLAG_RSS_FIELD_IPV6_UDP; break; default: return -EINVAL; } break; case AH_ESP_V4_FLOW: case AH_V4_FLOW: case ESP_V4_FLOW: case SCTP_V4_FLOW: case AH_ESP_V6_FLOW: case AH_V6_FLOW: case ESP_V6_FLOW: case SCTP_V6_FLOW: if (!(nfc->data & RXH_IP_SRC) || !(nfc->data & RXH_IP_DST) || (nfc->data & RXH_L4_B_0_1) || (nfc->data & RXH_L4_B_2_3)) return -EINVAL; break; default: return -EINVAL; } /* if we changed something we need to update flags */ if (flags != adapter->flags) { struct igc_hw *hw = &adapter->hw; u32 mrqc = rd32(IGC_MRQC); if ((flags & UDP_RSS_FLAGS) && !(adapter->flags & UDP_RSS_FLAGS)) netdev_err(adapter->netdev, "Enabling UDP RSS: fragmented packets may arrive out of order to the stack above\n"); adapter->flags = flags; /* Perform hash on these packet types */ mrqc |= IGC_MRQC_RSS_FIELD_IPV4 | IGC_MRQC_RSS_FIELD_IPV4_TCP | IGC_MRQC_RSS_FIELD_IPV6 | IGC_MRQC_RSS_FIELD_IPV6_TCP; mrqc &= ~(IGC_MRQC_RSS_FIELD_IPV4_UDP | IGC_MRQC_RSS_FIELD_IPV6_UDP); if (flags & IGC_FLAG_RSS_FIELD_IPV4_UDP) mrqc |= IGC_MRQC_RSS_FIELD_IPV4_UDP; if (flags & IGC_FLAG_RSS_FIELD_IPV6_UDP) mrqc |= IGC_MRQC_RSS_FIELD_IPV6_UDP; wr32(IGC_MRQC, mrqc); } return 0; } static void igc_ethtool_init_nfc_rule(struct igc_nfc_rule *rule, const struct ethtool_rx_flow_spec *fsp) { INIT_LIST_HEAD(&rule->list); rule->action = fsp->ring_cookie; rule->location = fsp->location; if ((fsp->flow_type & FLOW_EXT) && fsp->m_ext.vlan_tci) { rule->filter.vlan_tci = ntohs(fsp->h_ext.vlan_tci); rule->filter.match_flags |= IGC_FILTER_FLAG_VLAN_TCI; } if (fsp->m_u.ether_spec.h_proto == ETHER_TYPE_FULL_MASK) { rule->filter.etype = ntohs(fsp->h_u.ether_spec.h_proto); rule->filter.match_flags = IGC_FILTER_FLAG_ETHER_TYPE; } /* Both source and destination address filters only support the full * mask. */ if (is_broadcast_ether_addr(fsp->m_u.ether_spec.h_source)) { rule->filter.match_flags |= IGC_FILTER_FLAG_SRC_MAC_ADDR; ether_addr_copy(rule->filter.src_addr, fsp->h_u.ether_spec.h_source); } if (is_broadcast_ether_addr(fsp->m_u.ether_spec.h_dest)) { rule->filter.match_flags |= IGC_FILTER_FLAG_DST_MAC_ADDR; ether_addr_copy(rule->filter.dst_addr, fsp->h_u.ether_spec.h_dest); } /* VLAN etype matching */ if ((fsp->flow_type & FLOW_EXT) && fsp->h_ext.vlan_etype) { rule->filter.vlan_etype = fsp->h_ext.vlan_etype; rule->filter.match_flags |= IGC_FILTER_FLAG_VLAN_ETYPE; } /* Check for user defined data */ if ((fsp->flow_type & FLOW_EXT) && (fsp->h_ext.data[0] || fsp->h_ext.data[1])) { rule->filter.match_flags |= IGC_FILTER_FLAG_USER_DATA; memcpy(rule->filter.user_data, fsp->h_ext.data, sizeof(fsp->h_ext.data)); memcpy(rule->filter.user_mask, fsp->m_ext.data, sizeof(fsp->m_ext.data)); } /* When multiple filter options or user data or vlan etype is set, use a * flex filter. */ if ((rule->filter.match_flags & IGC_FILTER_FLAG_USER_DATA) || (rule->filter.match_flags & IGC_FILTER_FLAG_VLAN_ETYPE) || (rule->filter.match_flags & (rule->filter.match_flags - 1))) rule->flex = true; else rule->flex = false; } /** * igc_ethtool_check_nfc_rule() - Check if NFC rule is valid * @adapter: Pointer to adapter * @rule: Rule under evaluation * * The driver doesn't support rules with multiple matches so if more than * one bit in filter flags is set, @rule is considered invalid. * * Also, if there is already another rule with the same filter in a different * location, @rule is considered invalid. * * Context: Expects adapter->nfc_rule_lock to be held by caller. * * Return: 0 in case of success, negative errno code otherwise. */ static int igc_ethtool_check_nfc_rule(struct igc_adapter *adapter, struct igc_nfc_rule *rule) { struct net_device *dev = adapter->netdev; u8 flags = rule->filter.match_flags; struct igc_nfc_rule *tmp; if (!flags) { netdev_dbg(dev, "Rule with no match\n"); return -EINVAL; } list_for_each_entry(tmp, &adapter->nfc_rule_list, list) { if (!memcmp(&rule->filter, &tmp->filter, sizeof(rule->filter)) && tmp->location != rule->location) { netdev_dbg(dev, "Rule already exists\n"); return -EEXIST; } } return 0; } static int igc_ethtool_add_nfc_rule(struct igc_adapter *adapter, struct ethtool_rxnfc *cmd) { struct net_device *netdev = adapter->netdev; struct ethtool_rx_flow_spec *fsp = (struct ethtool_rx_flow_spec *)&cmd->fs; struct igc_nfc_rule *rule, *old_rule; int err; if (!(netdev->hw_features & NETIF_F_NTUPLE)) { netdev_dbg(netdev, "N-tuple filters disabled\n"); return -EOPNOTSUPP; } if ((fsp->flow_type & ~FLOW_EXT) != ETHER_FLOW) { netdev_dbg(netdev, "Only ethernet flow type is supported\n"); return -EOPNOTSUPP; } if (fsp->ring_cookie >= adapter->num_rx_queues) { netdev_dbg(netdev, "Invalid action\n"); return -EINVAL; } if (fsp->location >= IGC_MAX_RXNFC_RULES) { netdev_dbg(netdev, "Invalid location\n"); return -EINVAL; } rule = kzalloc(sizeof(*rule), GFP_KERNEL); if (!rule) return -ENOMEM; igc_ethtool_init_nfc_rule(rule, fsp); mutex_lock(&adapter->nfc_rule_lock); err = igc_ethtool_check_nfc_rule(adapter, rule); if (err) goto err; old_rule = igc_get_nfc_rule(adapter, fsp->location); if (old_rule) igc_del_nfc_rule(adapter, old_rule); err = igc_add_nfc_rule(adapter, rule); if (err) goto err; mutex_unlock(&adapter->nfc_rule_lock); return 0; err: mutex_unlock(&adapter->nfc_rule_lock); kfree(rule); return err; } static int igc_ethtool_del_nfc_rule(struct igc_adapter *adapter, struct ethtool_rxnfc *cmd) { struct ethtool_rx_flow_spec *fsp = (struct ethtool_rx_flow_spec *)&cmd->fs; struct igc_nfc_rule *rule; mutex_lock(&adapter->nfc_rule_lock); rule = igc_get_nfc_rule(adapter, fsp->location); if (!rule) { mutex_unlock(&adapter->nfc_rule_lock); return -EINVAL; } igc_del_nfc_rule(adapter, rule); mutex_unlock(&adapter->nfc_rule_lock); return 0; } static int igc_ethtool_set_rxnfc(struct net_device *dev, struct ethtool_rxnfc *cmd) { struct igc_adapter *adapter = netdev_priv(dev); switch (cmd->cmd) { case ETHTOOL_SRXFH: return igc_ethtool_set_rss_hash_opt(adapter, cmd); case ETHTOOL_SRXCLSRLINS: return igc_ethtool_add_nfc_rule(adapter, cmd); case ETHTOOL_SRXCLSRLDEL: return igc_ethtool_del_nfc_rule(adapter, cmd); default: return -EOPNOTSUPP; } } void igc_write_rss_indir_tbl(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; u32 reg = IGC_RETA(0); u32 shift = 0; int i = 0; while (i < IGC_RETA_SIZE) { u32 val = 0; int j; for (j = 3; j >= 0; j--) { val <<= 8; val |= adapter->rss_indir_tbl[i + j]; } wr32(reg, val << shift); reg += 4; i += 4; } } static u32 igc_ethtool_get_rxfh_indir_size(struct net_device *netdev) { return IGC_RETA_SIZE; } static int igc_ethtool_get_rxfh(struct net_device *netdev, u32 *indir, u8 *key, u8 *hfunc) { struct igc_adapter *adapter = netdev_priv(netdev); int i; if (hfunc) *hfunc = ETH_RSS_HASH_TOP; if (!indir) return 0; for (i = 0; i < IGC_RETA_SIZE; i++) indir[i] = adapter->rss_indir_tbl[i]; return 0; } static int igc_ethtool_set_rxfh(struct net_device *netdev, const u32 *indir, const u8 *key, const u8 hfunc) { struct igc_adapter *adapter = netdev_priv(netdev); u32 num_queues; int i; /* We do not allow change in unsupported parameters */ if (key || (hfunc != ETH_RSS_HASH_NO_CHANGE && hfunc != ETH_RSS_HASH_TOP)) return -EOPNOTSUPP; if (!indir) return 0; num_queues = adapter->rss_queues; /* Verify user input. */ for (i = 0; i < IGC_RETA_SIZE; i++) if (indir[i] >= num_queues) return -EINVAL; for (i = 0; i < IGC_RETA_SIZE; i++) adapter->rss_indir_tbl[i] = indir[i]; igc_write_rss_indir_tbl(adapter); return 0; } static void igc_ethtool_get_channels(struct net_device *netdev, struct ethtool_channels *ch) { struct igc_adapter *adapter = netdev_priv(netdev); /* Report maximum channels */ ch->max_combined = igc_get_max_rss_queues(adapter); /* Report info for other vector */ if (adapter->flags & IGC_FLAG_HAS_MSIX) { ch->max_other = NON_Q_VECTORS; ch->other_count = NON_Q_VECTORS; } ch->combined_count = adapter->rss_queues; } static int igc_ethtool_set_channels(struct net_device *netdev, struct ethtool_channels *ch) { struct igc_adapter *adapter = netdev_priv(netdev); unsigned int count = ch->combined_count; unsigned int max_combined = 0; /* Verify they are not requesting separate vectors */ if (!count || ch->rx_count || ch->tx_count) return -EINVAL; /* Verify other_count is valid and has not been changed */ if (ch->other_count != NON_Q_VECTORS) return -EINVAL; /* Verify the number of channels doesn't exceed hw limits */ max_combined = igc_get_max_rss_queues(adapter); if (count > max_combined) return -EINVAL; if (count != adapter->rss_queues) { adapter->rss_queues = count; igc_set_flag_queue_pairs(adapter, max_combined); /* Hardware has to reinitialize queues and interrupts to * match the new configuration. */ return igc_reinit_queues(adapter); } return 0; } static int igc_ethtool_get_ts_info(struct net_device *dev, struct ethtool_ts_info *info) { struct igc_adapter *adapter = netdev_priv(dev); if (adapter->ptp_clock) info->phc_index = ptp_clock_index(adapter->ptp_clock); else info->phc_index = -1; switch (adapter->hw.mac.type) { case igc_i225: info->so_timestamping = SOF_TIMESTAMPING_TX_SOFTWARE | SOF_TIMESTAMPING_RX_SOFTWARE | SOF_TIMESTAMPING_SOFTWARE | SOF_TIMESTAMPING_TX_HARDWARE | SOF_TIMESTAMPING_RX_HARDWARE | SOF_TIMESTAMPING_RAW_HARDWARE; info->tx_types = BIT(HWTSTAMP_TX_OFF) | BIT(HWTSTAMP_TX_ON); info->rx_filters = BIT(HWTSTAMP_FILTER_NONE); info->rx_filters |= BIT(HWTSTAMP_FILTER_ALL); return 0; default: return -EOPNOTSUPP; } } static u32 igc_ethtool_get_priv_flags(struct net_device *netdev) { struct igc_adapter *adapter = netdev_priv(netdev); u32 priv_flags = 0; if (adapter->flags & IGC_FLAG_RX_LEGACY) priv_flags |= IGC_PRIV_FLAGS_LEGACY_RX; return priv_flags; } static int igc_ethtool_set_priv_flags(struct net_device *netdev, u32 priv_flags) { struct igc_adapter *adapter = netdev_priv(netdev); unsigned int flags = adapter->flags; flags &= ~IGC_FLAG_RX_LEGACY; if (priv_flags & IGC_PRIV_FLAGS_LEGACY_RX) flags |= IGC_FLAG_RX_LEGACY; if (flags != adapter->flags) { adapter->flags = flags; /* reset interface to repopulate queues */ if (netif_running(netdev)) igc_reinit_locked(adapter); } return 0; } static int igc_ethtool_get_eee(struct net_device *netdev, struct ethtool_eee *edata) { struct igc_adapter *adapter = netdev_priv(netdev); struct igc_hw *hw = &adapter->hw; u32 eeer; if (hw->dev_spec._base.eee_enable) edata->advertised = mmd_eee_adv_to_ethtool_adv_t(adapter->eee_advert); *edata = adapter->eee; edata->supported = SUPPORTED_Autoneg; eeer = rd32(IGC_EEER); /* EEE status on negotiated link */ if (eeer & IGC_EEER_EEE_NEG) edata->eee_active = true; if (eeer & IGC_EEER_TX_LPI_EN) edata->tx_lpi_enabled = true; edata->eee_enabled = hw->dev_spec._base.eee_enable; edata->advertised = SUPPORTED_Autoneg; edata->lp_advertised = SUPPORTED_Autoneg; /* Report correct negotiated EEE status for devices that * wrongly report EEE at half-duplex */ if (adapter->link_duplex == HALF_DUPLEX) { edata->eee_enabled = false; edata->eee_active = false; edata->tx_lpi_enabled = false; edata->advertised &= ~edata->advertised; } return 0; } static int igc_ethtool_set_eee(struct net_device *netdev, struct ethtool_eee *edata) { struct igc_adapter *adapter = netdev_priv(netdev); struct igc_hw *hw = &adapter->hw; struct ethtool_eee eee_curr; s32 ret_val; memset(&eee_curr, 0, sizeof(struct ethtool_eee)); ret_val = igc_ethtool_get_eee(netdev, &eee_curr); if (ret_val) { netdev_err(netdev, "Problem setting EEE advertisement options\n"); return -EINVAL; } if (eee_curr.eee_enabled) { if (eee_curr.tx_lpi_enabled != edata->tx_lpi_enabled) { netdev_err(netdev, "Setting EEE tx-lpi is not supported\n"); return -EINVAL; } /* Tx LPI timer is not implemented currently */ if (edata->tx_lpi_timer) { netdev_err(netdev, "Setting EEE Tx LPI timer is not supported\n"); return -EINVAL; } } else if (!edata->eee_enabled) { netdev_err(netdev, "Setting EEE options are not supported with EEE disabled\n"); return -EINVAL; } adapter->eee_advert = ethtool_adv_to_mmd_eee_adv_t(edata->advertised); if (hw->dev_spec._base.eee_enable != edata->eee_enabled) { hw->dev_spec._base.eee_enable = edata->eee_enabled; adapter->flags |= IGC_FLAG_EEE; /* reset link */ if (netif_running(netdev)) igc_reinit_locked(adapter); else igc_reset(adapter); } return 0; } static int igc_ethtool_begin(struct net_device *netdev) { struct igc_adapter *adapter = netdev_priv(netdev); pm_runtime_get_sync(&adapter->pdev->dev); return 0; } static void igc_ethtool_complete(struct net_device *netdev) { struct igc_adapter *adapter = netdev_priv(netdev); pm_runtime_put(&adapter->pdev->dev); } static int igc_ethtool_get_link_ksettings(struct net_device *netdev, struct ethtool_link_ksettings *cmd) { struct igc_adapter *adapter = netdev_priv(netdev); struct igc_hw *hw = &adapter->hw; u32 status; u32 speed; ethtool_link_ksettings_zero_link_mode(cmd, supported); ethtool_link_ksettings_zero_link_mode(cmd, advertising); /* supported link modes */ ethtool_link_ksettings_add_link_mode(cmd, supported, 10baseT_Half); ethtool_link_ksettings_add_link_mode(cmd, supported, 10baseT_Full); ethtool_link_ksettings_add_link_mode(cmd, supported, 100baseT_Half); ethtool_link_ksettings_add_link_mode(cmd, supported, 100baseT_Full); ethtool_link_ksettings_add_link_mode(cmd, supported, 1000baseT_Full); ethtool_link_ksettings_add_link_mode(cmd, supported, 2500baseT_Full); /* twisted pair */ cmd->base.port = PORT_TP; cmd->base.phy_address = hw->phy.addr; ethtool_link_ksettings_add_link_mode(cmd, supported, TP); ethtool_link_ksettings_add_link_mode(cmd, advertising, TP); /* advertising link modes */ if (hw->phy.autoneg_advertised & ADVERTISE_10_HALF) ethtool_link_ksettings_add_link_mode(cmd, advertising, 10baseT_Half); if (hw->phy.autoneg_advertised & ADVERTISE_10_FULL) ethtool_link_ksettings_add_link_mode(cmd, advertising, 10baseT_Full); if (hw->phy.autoneg_advertised & ADVERTISE_100_HALF) ethtool_link_ksettings_add_link_mode(cmd, advertising, 100baseT_Half); if (hw->phy.autoneg_advertised & ADVERTISE_100_FULL) ethtool_link_ksettings_add_link_mode(cmd, advertising, 100baseT_Full); if (hw->phy.autoneg_advertised & ADVERTISE_1000_FULL) ethtool_link_ksettings_add_link_mode(cmd, advertising, 1000baseT_Full); if (hw->phy.autoneg_advertised & ADVERTISE_2500_FULL) ethtool_link_ksettings_add_link_mode(cmd, advertising, 2500baseT_Full); /* set autoneg settings */ if (hw->mac.autoneg == 1) { ethtool_link_ksettings_add_link_mode(cmd, supported, Autoneg); ethtool_link_ksettings_add_link_mode(cmd, advertising, Autoneg); } /* Set pause flow control settings */ ethtool_link_ksettings_add_link_mode(cmd, supported, Pause); switch (hw->fc.requested_mode) { case igc_fc_full: ethtool_link_ksettings_add_link_mode(cmd, advertising, Pause); break; case igc_fc_rx_pause: ethtool_link_ksettings_add_link_mode(cmd, advertising, Pause); ethtool_link_ksettings_add_link_mode(cmd, advertising, Asym_Pause); break; case igc_fc_tx_pause: ethtool_link_ksettings_add_link_mode(cmd, advertising, Asym_Pause); break; default: break; } status = pm_runtime_suspended(&adapter->pdev->dev) ? 0 : rd32(IGC_STATUS); if (status & IGC_STATUS_LU) { if (status & IGC_STATUS_SPEED_1000) { /* For I225, STATUS will indicate 1G speed in both * 1 Gbps and 2.5 Gbps link modes. * An additional bit is used * to differentiate between 1 Gbps and 2.5 Gbps. */ if (hw->mac.type == igc_i225 && (status & IGC_STATUS_SPEED_2500)) { speed = SPEED_2500; } else { speed = SPEED_1000; } } else if (status & IGC_STATUS_SPEED_100) { speed = SPEED_100; } else { speed = SPEED_10; } if ((status & IGC_STATUS_FD) || hw->phy.media_type != igc_media_type_copper) cmd->base.duplex = DUPLEX_FULL; else cmd->base.duplex = DUPLEX_HALF; } else { speed = SPEED_UNKNOWN; cmd->base.duplex = DUPLEX_UNKNOWN; } cmd->base.speed = speed; if (hw->mac.autoneg) cmd->base.autoneg = AUTONEG_ENABLE; else cmd->base.autoneg = AUTONEG_DISABLE; /* MDI-X => 2; MDI =>1; Invalid =>0 */ if (hw->phy.media_type == igc_media_type_copper) cmd->base.eth_tp_mdix = hw->phy.is_mdix ? ETH_TP_MDI_X : ETH_TP_MDI; else cmd->base.eth_tp_mdix = ETH_TP_MDI_INVALID; if (hw->phy.mdix == AUTO_ALL_MODES) cmd->base.eth_tp_mdix_ctrl = ETH_TP_MDI_AUTO; else cmd->base.eth_tp_mdix_ctrl = hw->phy.mdix; return 0; } static int igc_ethtool_set_link_ksettings(struct net_device *netdev, const struct ethtool_link_ksettings *cmd) { struct igc_adapter *adapter = netdev_priv(netdev); struct net_device *dev = adapter->netdev; struct igc_hw *hw = &adapter->hw; u32 advertising; /* When adapter in resetting mode, autoneg/speed/duplex * cannot be changed */ if (igc_check_reset_block(hw)) { netdev_err(dev, "Cannot change link characteristics when reset is active\n"); return -EINVAL; } /* MDI setting is only allowed when autoneg enabled because * some hardware doesn't allow MDI setting when speed or * duplex is forced. */ if (cmd->base.eth_tp_mdix_ctrl) { if (cmd->base.eth_tp_mdix_ctrl != ETH_TP_MDI_AUTO && cmd->base.autoneg != AUTONEG_ENABLE) { netdev_err(dev, "Forcing MDI/MDI-X state is not supported when link speed and/or duplex are forced\n"); return -EINVAL; } } while (test_and_set_bit(__IGC_RESETTING, &adapter->state)) usleep_range(1000, 2000); ethtool_convert_link_mode_to_legacy_u32(&advertising, cmd->link_modes.advertising); /* Converting to legacy u32 drops ETHTOOL_LINK_MODE_2500baseT_Full_BIT. * We have to check this and convert it to ADVERTISE_2500_FULL * (aka ETHTOOL_LINK_MODE_2500baseX_Full_BIT) explicitly. */ if (ethtool_link_ksettings_test_link_mode(cmd, advertising, 2500baseT_Full)) advertising |= ADVERTISE_2500_FULL; if (cmd->base.autoneg == AUTONEG_ENABLE) { hw->mac.autoneg = 1; hw->phy.autoneg_advertised = advertising; if (adapter->fc_autoneg) hw->fc.requested_mode = igc_fc_default; } else { netdev_info(dev, "Force mode currently not supported\n"); } /* MDI-X => 2; MDI => 1; Auto => 3 */ if (cmd->base.eth_tp_mdix_ctrl) { /* fix up the value for auto (3 => 0) as zero is mapped * internally to auto */ if (cmd->base.eth_tp_mdix_ctrl == ETH_TP_MDI_AUTO) hw->phy.mdix = AUTO_ALL_MODES; else hw->phy.mdix = cmd->base.eth_tp_mdix_ctrl; } /* reset the link */ if (netif_running(adapter->netdev)) { igc_down(adapter); igc_up(adapter); } else { igc_reset(adapter); } clear_bit(__IGC_RESETTING, &adapter->state); return 0; } static void igc_ethtool_diag_test(struct net_device *netdev, struct ethtool_test *eth_test, u64 *data) { struct igc_adapter *adapter = netdev_priv(netdev); bool if_running = netif_running(netdev); if (eth_test->flags == ETH_TEST_FL_OFFLINE) { netdev_info(adapter->netdev, "Offline testing starting"); set_bit(__IGC_TESTING, &adapter->state); /* Link test performed before hardware reset so autoneg doesn't * interfere with test result */ if (!igc_link_test(adapter, &data[TEST_LINK])) eth_test->flags |= ETH_TEST_FL_FAILED; if (if_running) igc_close(netdev); else igc_reset(adapter); netdev_info(adapter->netdev, "Register testing starting"); if (!igc_reg_test(adapter, &data[TEST_REG])) eth_test->flags |= ETH_TEST_FL_FAILED; igc_reset(adapter); netdev_info(adapter->netdev, "EEPROM testing starting"); if (!igc_eeprom_test(adapter, &data[TEST_EEP])) eth_test->flags |= ETH_TEST_FL_FAILED; igc_reset(adapter); /* loopback and interrupt tests * will be implemented in the future */ data[TEST_LOOP] = 0; data[TEST_IRQ] = 0; clear_bit(__IGC_TESTING, &adapter->state); if (if_running) igc_open(netdev); } else { netdev_info(adapter->netdev, "Online testing starting"); /* register, eeprom, intr and loopback tests not run online */ data[TEST_REG] = 0; data[TEST_EEP] = 0; data[TEST_IRQ] = 0; data[TEST_LOOP] = 0; if (!igc_link_test(adapter, &data[TEST_LINK])) eth_test->flags |= ETH_TEST_FL_FAILED; } msleep_interruptible(4 * 1000); } static const struct ethtool_ops igc_ethtool_ops = { .supported_coalesce_params = ETHTOOL_COALESCE_USECS, .get_drvinfo = igc_ethtool_get_drvinfo, .get_regs_len = igc_ethtool_get_regs_len, .get_regs = igc_ethtool_get_regs, .get_wol = igc_ethtool_get_wol, .set_wol = igc_ethtool_set_wol, .get_msglevel = igc_ethtool_get_msglevel, .set_msglevel = igc_ethtool_set_msglevel, .nway_reset = igc_ethtool_nway_reset, .get_link = igc_ethtool_get_link, .get_eeprom_len = igc_ethtool_get_eeprom_len, .get_eeprom = igc_ethtool_get_eeprom, .set_eeprom = igc_ethtool_set_eeprom, .get_ringparam = igc_ethtool_get_ringparam, .set_ringparam = igc_ethtool_set_ringparam, .get_pauseparam = igc_ethtool_get_pauseparam, .set_pauseparam = igc_ethtool_set_pauseparam, .get_strings = igc_ethtool_get_strings, .get_sset_count = igc_ethtool_get_sset_count, .get_ethtool_stats = igc_ethtool_get_stats, .get_coalesce = igc_ethtool_get_coalesce, .set_coalesce = igc_ethtool_set_coalesce, .get_rxnfc = igc_ethtool_get_rxnfc, .set_rxnfc = igc_ethtool_set_rxnfc, .get_rxfh_indir_size = igc_ethtool_get_rxfh_indir_size, .get_rxfh = igc_ethtool_get_rxfh, .set_rxfh = igc_ethtool_set_rxfh, .get_ts_info = igc_ethtool_get_ts_info, .get_channels = igc_ethtool_get_channels, .set_channels = igc_ethtool_set_channels, .get_priv_flags = igc_ethtool_get_priv_flags, .set_priv_flags = igc_ethtool_set_priv_flags, .get_eee = igc_ethtool_get_eee, .set_eee = igc_ethtool_set_eee, .begin = igc_ethtool_begin, .complete = igc_ethtool_complete, .get_link_ksettings = igc_ethtool_get_link_ksettings, .set_link_ksettings = igc_ethtool_set_link_ksettings, .self_test = igc_ethtool_diag_test, }; void igc_ethtool_set_ops(struct net_device *netdev) { netdev->ethtool_ops = &igc_ethtool_ops; }
linux-master
drivers/net/ethernet/intel/igc/igc_ethtool.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2018 Intel Corporation */ #include "igc_mac.h" #include "igc_nvm.h" /** * igc_poll_eerd_eewr_done - Poll for EEPROM read/write completion * @hw: pointer to the HW structure * @ee_reg: EEPROM flag for polling * * Polls the EEPROM status bit for either read or write completion based * upon the value of 'ee_reg'. */ static s32 igc_poll_eerd_eewr_done(struct igc_hw *hw, int ee_reg) { s32 ret_val = -IGC_ERR_NVM; u32 attempts = 100000; u32 i, reg = 0; for (i = 0; i < attempts; i++) { if (ee_reg == IGC_NVM_POLL_READ) reg = rd32(IGC_EERD); else reg = rd32(IGC_EEWR); if (reg & IGC_NVM_RW_REG_DONE) { ret_val = 0; break; } udelay(5); } return ret_val; } /** * igc_acquire_nvm - Generic request for access to EEPROM * @hw: pointer to the HW structure * * Set the EEPROM access request bit and wait for EEPROM access grant bit. * Return successful if access grant bit set, else clear the request for * EEPROM access and return -IGC_ERR_NVM (-1). */ s32 igc_acquire_nvm(struct igc_hw *hw) { s32 timeout = IGC_NVM_GRANT_ATTEMPTS; u32 eecd = rd32(IGC_EECD); s32 ret_val = 0; wr32(IGC_EECD, eecd | IGC_EECD_REQ); eecd = rd32(IGC_EECD); while (timeout) { if (eecd & IGC_EECD_GNT) break; udelay(5); eecd = rd32(IGC_EECD); timeout--; } if (!timeout) { eecd &= ~IGC_EECD_REQ; wr32(IGC_EECD, eecd); hw_dbg("Could not acquire NVM grant\n"); ret_val = -IGC_ERR_NVM; } return ret_val; } /** * igc_release_nvm - Release exclusive access to EEPROM * @hw: pointer to the HW structure * * Stop any current commands to the EEPROM and clear the EEPROM request bit. */ void igc_release_nvm(struct igc_hw *hw) { u32 eecd; eecd = rd32(IGC_EECD); eecd &= ~IGC_EECD_REQ; wr32(IGC_EECD, eecd); } /** * igc_read_nvm_eerd - Reads EEPROM using EERD register * @hw: pointer to the HW structure * @offset: offset of word in the EEPROM to read * @words: number of words to read * @data: word read from the EEPROM * * Reads a 16 bit word from the EEPROM using the EERD register. */ s32 igc_read_nvm_eerd(struct igc_hw *hw, u16 offset, u16 words, u16 *data) { struct igc_nvm_info *nvm = &hw->nvm; u32 i, eerd = 0; s32 ret_val = 0; /* A check for invalid values: offset too large, too many words, * and not enough words. */ if (offset >= nvm->word_size || (words > (nvm->word_size - offset)) || words == 0) { hw_dbg("nvm parameter(s) out of bounds\n"); ret_val = -IGC_ERR_NVM; goto out; } for (i = 0; i < words; i++) { eerd = ((offset + i) << IGC_NVM_RW_ADDR_SHIFT) + IGC_NVM_RW_REG_START; wr32(IGC_EERD, eerd); ret_val = igc_poll_eerd_eewr_done(hw, IGC_NVM_POLL_READ); if (ret_val) break; data[i] = (rd32(IGC_EERD) >> IGC_NVM_RW_REG_DATA); } out: return ret_val; } /** * igc_read_mac_addr - Read device MAC address * @hw: pointer to the HW structure */ s32 igc_read_mac_addr(struct igc_hw *hw) { u32 rar_high; u32 rar_low; u16 i; rar_high = rd32(IGC_RAH(0)); rar_low = rd32(IGC_RAL(0)); for (i = 0; i < IGC_RAL_MAC_ADDR_LEN; i++) hw->mac.perm_addr[i] = (u8)(rar_low >> (i * 8)); for (i = 0; i < IGC_RAH_MAC_ADDR_LEN; i++) hw->mac.perm_addr[i + 4] = (u8)(rar_high >> (i * 8)); for (i = 0; i < ETH_ALEN; i++) hw->mac.addr[i] = hw->mac.perm_addr[i]; return 0; } /** * igc_validate_nvm_checksum - Validate EEPROM checksum * @hw: pointer to the HW structure * * Calculates the EEPROM checksum by reading/adding each word of the EEPROM * and then verifies that the sum of the EEPROM is equal to 0xBABA. */ s32 igc_validate_nvm_checksum(struct igc_hw *hw) { u16 checksum = 0; u16 i, nvm_data; s32 ret_val = 0; for (i = 0; i < (NVM_CHECKSUM_REG + 1); i++) { ret_val = hw->nvm.ops.read(hw, i, 1, &nvm_data); if (ret_val) { hw_dbg("NVM Read Error\n"); goto out; } checksum += nvm_data; } if (checksum != (u16)NVM_SUM) { hw_dbg("NVM Checksum Invalid\n"); ret_val = -IGC_ERR_NVM; goto out; } out: return ret_val; } /** * igc_update_nvm_checksum - Update EEPROM checksum * @hw: pointer to the HW structure * * Updates the EEPROM checksum by reading/adding each word of the EEPROM * up to the checksum. Then calculates the EEPROM checksum and writes the * value to the EEPROM. */ s32 igc_update_nvm_checksum(struct igc_hw *hw) { u16 checksum = 0; u16 i, nvm_data; s32 ret_val; for (i = 0; i < NVM_CHECKSUM_REG; i++) { ret_val = hw->nvm.ops.read(hw, i, 1, &nvm_data); if (ret_val) { hw_dbg("NVM Read Error while updating checksum.\n"); goto out; } checksum += nvm_data; } checksum = (u16)NVM_SUM - checksum; ret_val = hw->nvm.ops.write(hw, NVM_CHECKSUM_REG, 1, &checksum); if (ret_val) hw_dbg("NVM Write Error while updating checksum.\n"); out: return ret_val; }
linux-master
drivers/net/ethernet/intel/igc/igc_nvm.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2018 Intel Corporation */ #include "igc.h" struct igc_reg_info { u32 ofs; char *name; }; static const struct igc_reg_info igc_reg_info_tbl[] = { /* General Registers */ {IGC_CTRL, "CTRL"}, {IGC_STATUS, "STATUS"}, {IGC_CTRL_EXT, "CTRL_EXT"}, {IGC_MDIC, "MDIC"}, /* Interrupt Registers */ {IGC_ICR, "ICR"}, /* RX Registers */ {IGC_RCTL, "RCTL"}, {IGC_RDLEN(0), "RDLEN"}, {IGC_RDH(0), "RDH"}, {IGC_RDT(0), "RDT"}, {IGC_RXDCTL(0), "RXDCTL"}, {IGC_RDBAL(0), "RDBAL"}, {IGC_RDBAH(0), "RDBAH"}, /* TX Registers */ {IGC_TCTL, "TCTL"}, {IGC_TDBAL(0), "TDBAL"}, {IGC_TDBAH(0), "TDBAH"}, {IGC_TDLEN(0), "TDLEN"}, {IGC_TDH(0), "TDH"}, {IGC_TDT(0), "TDT"}, {IGC_TXDCTL(0), "TXDCTL"}, /* List Terminator */ {} }; /* igc_regdump - register printout routine */ static void igc_regdump(struct igc_hw *hw, struct igc_reg_info *reginfo) { struct net_device *dev = igc_get_hw_dev(hw); int n = 0; char rname[16]; u32 regs[8]; switch (reginfo->ofs) { case IGC_RDLEN(0): for (n = 0; n < 4; n++) regs[n] = rd32(IGC_RDLEN(n)); break; case IGC_RDH(0): for (n = 0; n < 4; n++) regs[n] = rd32(IGC_RDH(n)); break; case IGC_RDT(0): for (n = 0; n < 4; n++) regs[n] = rd32(IGC_RDT(n)); break; case IGC_RXDCTL(0): for (n = 0; n < 4; n++) regs[n] = rd32(IGC_RXDCTL(n)); break; case IGC_RDBAL(0): for (n = 0; n < 4; n++) regs[n] = rd32(IGC_RDBAL(n)); break; case IGC_RDBAH(0): for (n = 0; n < 4; n++) regs[n] = rd32(IGC_RDBAH(n)); break; case IGC_TDBAL(0): for (n = 0; n < 4; n++) regs[n] = rd32(IGC_TDBAL(n)); break; case IGC_TDBAH(0): for (n = 0; n < 4; n++) regs[n] = rd32(IGC_TDBAH(n)); break; case IGC_TDLEN(0): for (n = 0; n < 4; n++) regs[n] = rd32(IGC_TDLEN(n)); break; case IGC_TDH(0): for (n = 0; n < 4; n++) regs[n] = rd32(IGC_TDH(n)); break; case IGC_TDT(0): for (n = 0; n < 4; n++) regs[n] = rd32(IGC_TDT(n)); break; case IGC_TXDCTL(0): for (n = 0; n < 4; n++) regs[n] = rd32(IGC_TXDCTL(n)); break; default: netdev_info(dev, "%-15s %08x\n", reginfo->name, rd32(reginfo->ofs)); return; } snprintf(rname, 16, "%s%s", reginfo->name, "[0-3]"); netdev_info(dev, "%-15s %08x %08x %08x %08x\n", rname, regs[0], regs[1], regs[2], regs[3]); } /* igc_rings_dump - Tx-rings and Rx-rings */ void igc_rings_dump(struct igc_adapter *adapter) { struct net_device *netdev = adapter->netdev; struct my_u0 { __le64 a; __le64 b; } *u0; union igc_adv_tx_desc *tx_desc; union igc_adv_rx_desc *rx_desc; struct igc_ring *tx_ring; struct igc_ring *rx_ring; u32 staterr; u16 i, n; if (!netif_msg_hw(adapter)) return; netdev_info(netdev, "Device info: state %016lX trans_start %016lX\n", netdev->state, dev_trans_start(netdev)); /* Print TX Ring Summary */ if (!netif_running(netdev)) goto exit; netdev_info(netdev, "TX Rings Summary\n"); netdev_info(netdev, "Queue [NTU] [NTC] [bi(ntc)->dma ] leng ntw timestamp\n"); for (n = 0; n < adapter->num_tx_queues; n++) { struct igc_tx_buffer *buffer_info; tx_ring = adapter->tx_ring[n]; buffer_info = &tx_ring->tx_buffer_info[tx_ring->next_to_clean]; netdev_info(netdev, "%5d %5X %5X %016llX %04X %p %016llX\n", n, tx_ring->next_to_use, tx_ring->next_to_clean, (u64)dma_unmap_addr(buffer_info, dma), dma_unmap_len(buffer_info, len), buffer_info->next_to_watch, (u64)buffer_info->time_stamp); } /* Print TX Rings */ if (!netif_msg_tx_done(adapter)) goto rx_ring_summary; netdev_info(netdev, "TX Rings Dump\n"); /* Transmit Descriptor Formats * * Advanced Transmit Descriptor * +--------------------------------------------------------------+ * 0 | Buffer Address [63:0] | * +--------------------------------------------------------------+ * 8 | PAYLEN | PORTS |CC|IDX | STA | DCMD |DTYP|MAC|RSV| DTALEN | * +--------------------------------------------------------------+ * 63 46 45 40 39 38 36 35 32 31 24 15 0 */ for (n = 0; n < adapter->num_tx_queues; n++) { tx_ring = adapter->tx_ring[n]; netdev_info(netdev, "------------------------------------\n"); netdev_info(netdev, "TX QUEUE INDEX = %d\n", tx_ring->queue_index); netdev_info(netdev, "------------------------------------\n"); netdev_info(netdev, "T [desc] [address 63:0 ] [PlPOCIStDDM Ln] [bi->dma ] leng ntw timestamp bi->skb\n"); for (i = 0; tx_ring->desc && (i < tx_ring->count); i++) { const char *next_desc; struct igc_tx_buffer *buffer_info; tx_desc = IGC_TX_DESC(tx_ring, i); buffer_info = &tx_ring->tx_buffer_info[i]; u0 = (struct my_u0 *)tx_desc; if (i == tx_ring->next_to_use && i == tx_ring->next_to_clean) next_desc = " NTC/U"; else if (i == tx_ring->next_to_use) next_desc = " NTU"; else if (i == tx_ring->next_to_clean) next_desc = " NTC"; else next_desc = ""; netdev_info(netdev, "T [0x%03X] %016llX %016llX %016llX %04X %p %016llX %p%s\n", i, le64_to_cpu(u0->a), le64_to_cpu(u0->b), (u64)dma_unmap_addr(buffer_info, dma), dma_unmap_len(buffer_info, len), buffer_info->next_to_watch, (u64)buffer_info->time_stamp, buffer_info->skb, next_desc); if (netif_msg_pktdata(adapter) && buffer_info->skb) print_hex_dump(KERN_INFO, "", DUMP_PREFIX_ADDRESS, 16, 1, buffer_info->skb->data, dma_unmap_len(buffer_info, len), true); } } /* Print RX Rings Summary */ rx_ring_summary: netdev_info(netdev, "RX Rings Summary\n"); netdev_info(netdev, "Queue [NTU] [NTC]\n"); for (n = 0; n < adapter->num_rx_queues; n++) { rx_ring = adapter->rx_ring[n]; netdev_info(netdev, "%5d %5X %5X\n", n, rx_ring->next_to_use, rx_ring->next_to_clean); } /* Print RX Rings */ if (!netif_msg_rx_status(adapter)) goto exit; netdev_info(netdev, "RX Rings Dump\n"); /* Advanced Receive Descriptor (Read) Format * 63 1 0 * +-----------------------------------------------------+ * 0 | Packet Buffer Address [63:1] |A0/NSE| * +----------------------------------------------+------+ * 8 | Header Buffer Address [63:1] | DD | * +-----------------------------------------------------+ * * * Advanced Receive Descriptor (Write-Back) Format * * 63 48 47 32 31 30 21 20 17 16 4 3 0 * +------------------------------------------------------+ * 0 | Packet IP |SPH| HDR_LEN | RSV|Packet| RSS | * | Checksum Ident | | | | Type | Type | * +------------------------------------------------------+ * 8 | VLAN Tag | Length | Extended Error | Extended Status | * +------------------------------------------------------+ * 63 48 47 32 31 20 19 0 */ for (n = 0; n < adapter->num_rx_queues; n++) { rx_ring = adapter->rx_ring[n]; netdev_info(netdev, "------------------------------------\n"); netdev_info(netdev, "RX QUEUE INDEX = %d\n", rx_ring->queue_index); netdev_info(netdev, "------------------------------------\n"); netdev_info(netdev, "R [desc] [ PktBuf A0] [ HeadBuf DD] [bi->dma ] [bi->skb] <-- Adv Rx Read format\n"); netdev_info(netdev, "RWB[desc] [PcsmIpSHl PtRs] [vl er S cks ln] ---------------- [bi->skb] <-- Adv Rx Write-Back format\n"); for (i = 0; i < rx_ring->count; i++) { const char *next_desc; struct igc_rx_buffer *buffer_info; buffer_info = &rx_ring->rx_buffer_info[i]; rx_desc = IGC_RX_DESC(rx_ring, i); u0 = (struct my_u0 *)rx_desc; staterr = le32_to_cpu(rx_desc->wb.upper.status_error); if (i == rx_ring->next_to_use) next_desc = " NTU"; else if (i == rx_ring->next_to_clean) next_desc = " NTC"; else next_desc = ""; if (staterr & IGC_RXD_STAT_DD) { /* Descriptor Done */ netdev_info(netdev, "%s[0x%03X] %016llX %016llX ---------------- %s\n", "RWB", i, le64_to_cpu(u0->a), le64_to_cpu(u0->b), next_desc); } else { netdev_info(netdev, "%s[0x%03X] %016llX %016llX %016llX %s\n", "R ", i, le64_to_cpu(u0->a), le64_to_cpu(u0->b), (u64)buffer_info->dma, next_desc); if (netif_msg_pktdata(adapter) && buffer_info->dma && buffer_info->page) { print_hex_dump(KERN_INFO, "", DUMP_PREFIX_ADDRESS, 16, 1, page_address (buffer_info->page) + buffer_info->page_offset, igc_rx_bufsz(rx_ring), true); } } } } exit: return; } /* igc_regs_dump - registers dump */ void igc_regs_dump(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; struct igc_reg_info *reginfo; /* Print Registers */ netdev_info(adapter->netdev, "Register Dump\n"); netdev_info(adapter->netdev, "Register Name Value\n"); for (reginfo = (struct igc_reg_info *)igc_reg_info_tbl; reginfo->name; reginfo++) { igc_regdump(hw, reginfo); } }
linux-master
drivers/net/ethernet/intel/igc/igc_dump.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2018 Intel Corporation */ #include <linux/module.h> #include <linux/types.h> #include <linux/if_vlan.h> #include <linux/tcp.h> #include <linux/udp.h> #include <linux/ip.h> #include <linux/pm_runtime.h> #include <net/pkt_sched.h> #include <linux/bpf_trace.h> #include <net/xdp_sock_drv.h> #include <linux/pci.h> #include <net/ipv6.h> #include "igc.h" #include "igc_hw.h" #include "igc_tsn.h" #include "igc_xdp.h" #define DRV_SUMMARY "Intel(R) 2.5G Ethernet Linux Driver" #define DEFAULT_MSG_ENABLE (NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_LINK) #define IGC_XDP_PASS 0 #define IGC_XDP_CONSUMED BIT(0) #define IGC_XDP_TX BIT(1) #define IGC_XDP_REDIRECT BIT(2) static int debug = -1; MODULE_AUTHOR("Intel Corporation, <[email protected]>"); MODULE_DESCRIPTION(DRV_SUMMARY); MODULE_LICENSE("GPL v2"); module_param(debug, int, 0); MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all)"); char igc_driver_name[] = "igc"; static const char igc_driver_string[] = DRV_SUMMARY; static const char igc_copyright[] = "Copyright(c) 2018 Intel Corporation."; static const struct igc_info *igc_info_tbl[] = { [board_base] = &igc_base_info, }; static const struct pci_device_id igc_pci_tbl[] = { { PCI_VDEVICE(INTEL, IGC_DEV_ID_I225_LM), board_base }, { PCI_VDEVICE(INTEL, IGC_DEV_ID_I225_V), board_base }, { PCI_VDEVICE(INTEL, IGC_DEV_ID_I225_I), board_base }, { PCI_VDEVICE(INTEL, IGC_DEV_ID_I220_V), board_base }, { PCI_VDEVICE(INTEL, IGC_DEV_ID_I225_K), board_base }, { PCI_VDEVICE(INTEL, IGC_DEV_ID_I225_K2), board_base }, { PCI_VDEVICE(INTEL, IGC_DEV_ID_I226_K), board_base }, { PCI_VDEVICE(INTEL, IGC_DEV_ID_I225_LMVP), board_base }, { PCI_VDEVICE(INTEL, IGC_DEV_ID_I226_LMVP), board_base }, { PCI_VDEVICE(INTEL, IGC_DEV_ID_I225_IT), board_base }, { PCI_VDEVICE(INTEL, IGC_DEV_ID_I226_LM), board_base }, { PCI_VDEVICE(INTEL, IGC_DEV_ID_I226_V), board_base }, { PCI_VDEVICE(INTEL, IGC_DEV_ID_I226_IT), board_base }, { PCI_VDEVICE(INTEL, IGC_DEV_ID_I221_V), board_base }, { PCI_VDEVICE(INTEL, IGC_DEV_ID_I226_BLANK_NVM), board_base }, { PCI_VDEVICE(INTEL, IGC_DEV_ID_I225_BLANK_NVM), board_base }, /* required last entry */ {0, } }; MODULE_DEVICE_TABLE(pci, igc_pci_tbl); enum latency_range { lowest_latency = 0, low_latency = 1, bulk_latency = 2, latency_invalid = 255 }; void igc_reset(struct igc_adapter *adapter) { struct net_device *dev = adapter->netdev; struct igc_hw *hw = &adapter->hw; struct igc_fc_info *fc = &hw->fc; u32 pba, hwm; /* Repartition PBA for greater than 9k MTU if required */ pba = IGC_PBA_34K; /* flow control settings * The high water mark must be low enough to fit one full frame * after transmitting the pause frame. As such we must have enough * space to allow for us to complete our current transmit and then * receive the frame that is in progress from the link partner. * Set it to: * - the full Rx FIFO size minus one full Tx plus one full Rx frame */ hwm = (pba << 10) - (adapter->max_frame_size + MAX_JUMBO_FRAME_SIZE); fc->high_water = hwm & 0xFFFFFFF0; /* 16-byte granularity */ fc->low_water = fc->high_water - 16; fc->pause_time = 0xFFFF; fc->send_xon = 1; fc->current_mode = fc->requested_mode; hw->mac.ops.reset_hw(hw); if (hw->mac.ops.init_hw(hw)) netdev_err(dev, "Error on hardware initialization\n"); /* Re-establish EEE setting */ igc_set_eee_i225(hw, true, true, true); if (!netif_running(adapter->netdev)) igc_power_down_phy_copper_base(&adapter->hw); /* Enable HW to recognize an 802.1Q VLAN Ethernet packet */ wr32(IGC_VET, ETH_P_8021Q); /* Re-enable PTP, where applicable. */ igc_ptp_reset(adapter); /* Re-enable TSN offloading, where applicable. */ igc_tsn_reset(adapter); igc_get_phy_info(hw); } /** * igc_power_up_link - Power up the phy link * @adapter: address of board private structure */ static void igc_power_up_link(struct igc_adapter *adapter) { igc_reset_phy(&adapter->hw); igc_power_up_phy_copper(&adapter->hw); igc_setup_link(&adapter->hw); } /** * igc_release_hw_control - release control of the h/w to f/w * @adapter: address of board private structure * * igc_release_hw_control resets CTRL_EXT:DRV_LOAD bit. * For ASF and Pass Through versions of f/w this means that the * driver is no longer loaded. */ static void igc_release_hw_control(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; u32 ctrl_ext; if (!pci_device_is_present(adapter->pdev)) return; /* Let firmware take over control of h/w */ ctrl_ext = rd32(IGC_CTRL_EXT); wr32(IGC_CTRL_EXT, ctrl_ext & ~IGC_CTRL_EXT_DRV_LOAD); } /** * igc_get_hw_control - get control of the h/w from f/w * @adapter: address of board private structure * * igc_get_hw_control sets CTRL_EXT:DRV_LOAD bit. * For ASF and Pass Through versions of f/w this means that * the driver is loaded. */ static void igc_get_hw_control(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; u32 ctrl_ext; /* Let firmware know the driver has taken over */ ctrl_ext = rd32(IGC_CTRL_EXT); wr32(IGC_CTRL_EXT, ctrl_ext | IGC_CTRL_EXT_DRV_LOAD); } static void igc_unmap_tx_buffer(struct device *dev, struct igc_tx_buffer *buf) { dma_unmap_single(dev, dma_unmap_addr(buf, dma), dma_unmap_len(buf, len), DMA_TO_DEVICE); dma_unmap_len_set(buf, len, 0); } /** * igc_clean_tx_ring - Free Tx Buffers * @tx_ring: ring to be cleaned */ static void igc_clean_tx_ring(struct igc_ring *tx_ring) { u16 i = tx_ring->next_to_clean; struct igc_tx_buffer *tx_buffer = &tx_ring->tx_buffer_info[i]; u32 xsk_frames = 0; while (i != tx_ring->next_to_use) { union igc_adv_tx_desc *eop_desc, *tx_desc; switch (tx_buffer->type) { case IGC_TX_BUFFER_TYPE_XSK: xsk_frames++; break; case IGC_TX_BUFFER_TYPE_XDP: xdp_return_frame(tx_buffer->xdpf); igc_unmap_tx_buffer(tx_ring->dev, tx_buffer); break; case IGC_TX_BUFFER_TYPE_SKB: dev_kfree_skb_any(tx_buffer->skb); igc_unmap_tx_buffer(tx_ring->dev, tx_buffer); break; default: netdev_warn_once(tx_ring->netdev, "Unknown Tx buffer type\n"); break; } /* check for eop_desc to determine the end of the packet */ eop_desc = tx_buffer->next_to_watch; tx_desc = IGC_TX_DESC(tx_ring, i); /* unmap remaining buffers */ while (tx_desc != eop_desc) { tx_buffer++; tx_desc++; i++; if (unlikely(i == tx_ring->count)) { i = 0; tx_buffer = tx_ring->tx_buffer_info; tx_desc = IGC_TX_DESC(tx_ring, 0); } /* unmap any remaining paged data */ if (dma_unmap_len(tx_buffer, len)) igc_unmap_tx_buffer(tx_ring->dev, tx_buffer); } tx_buffer->next_to_watch = NULL; /* move us one more past the eop_desc for start of next pkt */ tx_buffer++; i++; if (unlikely(i == tx_ring->count)) { i = 0; tx_buffer = tx_ring->tx_buffer_info; } } if (tx_ring->xsk_pool && xsk_frames) xsk_tx_completed(tx_ring->xsk_pool, xsk_frames); /* reset BQL for queue */ netdev_tx_reset_queue(txring_txq(tx_ring)); /* Zero out the buffer ring */ memset(tx_ring->tx_buffer_info, 0, sizeof(*tx_ring->tx_buffer_info) * tx_ring->count); /* Zero out the descriptor ring */ memset(tx_ring->desc, 0, tx_ring->size); /* reset next_to_use and next_to_clean */ tx_ring->next_to_use = 0; tx_ring->next_to_clean = 0; } /** * igc_free_tx_resources - Free Tx Resources per Queue * @tx_ring: Tx descriptor ring for a specific queue * * Free all transmit software resources */ void igc_free_tx_resources(struct igc_ring *tx_ring) { igc_disable_tx_ring(tx_ring); vfree(tx_ring->tx_buffer_info); tx_ring->tx_buffer_info = NULL; /* if not set, then don't free */ if (!tx_ring->desc) return; dma_free_coherent(tx_ring->dev, tx_ring->size, tx_ring->desc, tx_ring->dma); tx_ring->desc = NULL; } /** * igc_free_all_tx_resources - Free Tx Resources for All Queues * @adapter: board private structure * * Free all transmit software resources */ static void igc_free_all_tx_resources(struct igc_adapter *adapter) { int i; for (i = 0; i < adapter->num_tx_queues; i++) igc_free_tx_resources(adapter->tx_ring[i]); } /** * igc_clean_all_tx_rings - Free Tx Buffers for all queues * @adapter: board private structure */ static void igc_clean_all_tx_rings(struct igc_adapter *adapter) { int i; for (i = 0; i < adapter->num_tx_queues; i++) if (adapter->tx_ring[i]) igc_clean_tx_ring(adapter->tx_ring[i]); } static void igc_disable_tx_ring_hw(struct igc_ring *ring) { struct igc_hw *hw = &ring->q_vector->adapter->hw; u8 idx = ring->reg_idx; u32 txdctl; txdctl = rd32(IGC_TXDCTL(idx)); txdctl &= ~IGC_TXDCTL_QUEUE_ENABLE; txdctl |= IGC_TXDCTL_SWFLUSH; wr32(IGC_TXDCTL(idx), txdctl); } /** * igc_disable_all_tx_rings_hw - Disable all transmit queue operation * @adapter: board private structure */ static void igc_disable_all_tx_rings_hw(struct igc_adapter *adapter) { int i; for (i = 0; i < adapter->num_tx_queues; i++) { struct igc_ring *tx_ring = adapter->tx_ring[i]; igc_disable_tx_ring_hw(tx_ring); } } /** * igc_setup_tx_resources - allocate Tx resources (Descriptors) * @tx_ring: tx descriptor ring (for a specific queue) to setup * * Return 0 on success, negative on failure */ int igc_setup_tx_resources(struct igc_ring *tx_ring) { struct net_device *ndev = tx_ring->netdev; struct device *dev = tx_ring->dev; int size = 0; size = sizeof(struct igc_tx_buffer) * tx_ring->count; tx_ring->tx_buffer_info = vzalloc(size); if (!tx_ring->tx_buffer_info) goto err; /* round up to nearest 4K */ tx_ring->size = tx_ring->count * sizeof(union igc_adv_tx_desc); tx_ring->size = ALIGN(tx_ring->size, 4096); tx_ring->desc = dma_alloc_coherent(dev, tx_ring->size, &tx_ring->dma, GFP_KERNEL); if (!tx_ring->desc) goto err; tx_ring->next_to_use = 0; tx_ring->next_to_clean = 0; return 0; err: vfree(tx_ring->tx_buffer_info); netdev_err(ndev, "Unable to allocate memory for Tx descriptor ring\n"); return -ENOMEM; } /** * igc_setup_all_tx_resources - wrapper to allocate Tx resources for all queues * @adapter: board private structure * * Return 0 on success, negative on failure */ static int igc_setup_all_tx_resources(struct igc_adapter *adapter) { struct net_device *dev = adapter->netdev; int i, err = 0; for (i = 0; i < adapter->num_tx_queues; i++) { err = igc_setup_tx_resources(adapter->tx_ring[i]); if (err) { netdev_err(dev, "Error on Tx queue %u setup\n", i); for (i--; i >= 0; i--) igc_free_tx_resources(adapter->tx_ring[i]); break; } } return err; } static void igc_clean_rx_ring_page_shared(struct igc_ring *rx_ring) { u16 i = rx_ring->next_to_clean; dev_kfree_skb(rx_ring->skb); rx_ring->skb = NULL; /* Free all the Rx ring sk_buffs */ while (i != rx_ring->next_to_alloc) { struct igc_rx_buffer *buffer_info = &rx_ring->rx_buffer_info[i]; /* Invalidate cache lines that may have been written to by * device so that we avoid corrupting memory. */ dma_sync_single_range_for_cpu(rx_ring->dev, buffer_info->dma, buffer_info->page_offset, igc_rx_bufsz(rx_ring), DMA_FROM_DEVICE); /* free resources associated with mapping */ dma_unmap_page_attrs(rx_ring->dev, buffer_info->dma, igc_rx_pg_size(rx_ring), DMA_FROM_DEVICE, IGC_RX_DMA_ATTR); __page_frag_cache_drain(buffer_info->page, buffer_info->pagecnt_bias); i++; if (i == rx_ring->count) i = 0; } } static void igc_clean_rx_ring_xsk_pool(struct igc_ring *ring) { struct igc_rx_buffer *bi; u16 i; for (i = 0; i < ring->count; i++) { bi = &ring->rx_buffer_info[i]; if (!bi->xdp) continue; xsk_buff_free(bi->xdp); bi->xdp = NULL; } } /** * igc_clean_rx_ring - Free Rx Buffers per Queue * @ring: ring to free buffers from */ static void igc_clean_rx_ring(struct igc_ring *ring) { if (ring->xsk_pool) igc_clean_rx_ring_xsk_pool(ring); else igc_clean_rx_ring_page_shared(ring); clear_ring_uses_large_buffer(ring); ring->next_to_alloc = 0; ring->next_to_clean = 0; ring->next_to_use = 0; } /** * igc_clean_all_rx_rings - Free Rx Buffers for all queues * @adapter: board private structure */ static void igc_clean_all_rx_rings(struct igc_adapter *adapter) { int i; for (i = 0; i < adapter->num_rx_queues; i++) if (adapter->rx_ring[i]) igc_clean_rx_ring(adapter->rx_ring[i]); } /** * igc_free_rx_resources - Free Rx Resources * @rx_ring: ring to clean the resources from * * Free all receive software resources */ void igc_free_rx_resources(struct igc_ring *rx_ring) { igc_clean_rx_ring(rx_ring); xdp_rxq_info_unreg(&rx_ring->xdp_rxq); vfree(rx_ring->rx_buffer_info); rx_ring->rx_buffer_info = NULL; /* if not set, then don't free */ if (!rx_ring->desc) return; dma_free_coherent(rx_ring->dev, rx_ring->size, rx_ring->desc, rx_ring->dma); rx_ring->desc = NULL; } /** * igc_free_all_rx_resources - Free Rx Resources for All Queues * @adapter: board private structure * * Free all receive software resources */ static void igc_free_all_rx_resources(struct igc_adapter *adapter) { int i; for (i = 0; i < adapter->num_rx_queues; i++) igc_free_rx_resources(adapter->rx_ring[i]); } /** * igc_setup_rx_resources - allocate Rx resources (Descriptors) * @rx_ring: rx descriptor ring (for a specific queue) to setup * * Returns 0 on success, negative on failure */ int igc_setup_rx_resources(struct igc_ring *rx_ring) { struct net_device *ndev = rx_ring->netdev; struct device *dev = rx_ring->dev; u8 index = rx_ring->queue_index; int size, desc_len, res; /* XDP RX-queue info */ if (xdp_rxq_info_is_reg(&rx_ring->xdp_rxq)) xdp_rxq_info_unreg(&rx_ring->xdp_rxq); res = xdp_rxq_info_reg(&rx_ring->xdp_rxq, ndev, index, rx_ring->q_vector->napi.napi_id); if (res < 0) { netdev_err(ndev, "Failed to register xdp_rxq index %u\n", index); return res; } size = sizeof(struct igc_rx_buffer) * rx_ring->count; rx_ring->rx_buffer_info = vzalloc(size); if (!rx_ring->rx_buffer_info) goto err; desc_len = sizeof(union igc_adv_rx_desc); /* Round up to nearest 4K */ rx_ring->size = rx_ring->count * desc_len; rx_ring->size = ALIGN(rx_ring->size, 4096); rx_ring->desc = dma_alloc_coherent(dev, rx_ring->size, &rx_ring->dma, GFP_KERNEL); if (!rx_ring->desc) goto err; rx_ring->next_to_alloc = 0; rx_ring->next_to_clean = 0; rx_ring->next_to_use = 0; return 0; err: xdp_rxq_info_unreg(&rx_ring->xdp_rxq); vfree(rx_ring->rx_buffer_info); rx_ring->rx_buffer_info = NULL; netdev_err(ndev, "Unable to allocate memory for Rx descriptor ring\n"); return -ENOMEM; } /** * igc_setup_all_rx_resources - wrapper to allocate Rx resources * (Descriptors) for all queues * @adapter: board private structure * * Return 0 on success, negative on failure */ static int igc_setup_all_rx_resources(struct igc_adapter *adapter) { struct net_device *dev = adapter->netdev; int i, err = 0; for (i = 0; i < adapter->num_rx_queues; i++) { err = igc_setup_rx_resources(adapter->rx_ring[i]); if (err) { netdev_err(dev, "Error on Rx queue %u setup\n", i); for (i--; i >= 0; i--) igc_free_rx_resources(adapter->rx_ring[i]); break; } } return err; } static struct xsk_buff_pool *igc_get_xsk_pool(struct igc_adapter *adapter, struct igc_ring *ring) { if (!igc_xdp_is_enabled(adapter) || !test_bit(IGC_RING_FLAG_AF_XDP_ZC, &ring->flags)) return NULL; return xsk_get_pool_from_qid(ring->netdev, ring->queue_index); } /** * igc_configure_rx_ring - Configure a receive ring after Reset * @adapter: board private structure * @ring: receive ring to be configured * * Configure the Rx unit of the MAC after a reset. */ static void igc_configure_rx_ring(struct igc_adapter *adapter, struct igc_ring *ring) { struct igc_hw *hw = &adapter->hw; union igc_adv_rx_desc *rx_desc; int reg_idx = ring->reg_idx; u32 srrctl = 0, rxdctl = 0; u64 rdba = ring->dma; u32 buf_size; xdp_rxq_info_unreg_mem_model(&ring->xdp_rxq); ring->xsk_pool = igc_get_xsk_pool(adapter, ring); if (ring->xsk_pool) { WARN_ON(xdp_rxq_info_reg_mem_model(&ring->xdp_rxq, MEM_TYPE_XSK_BUFF_POOL, NULL)); xsk_pool_set_rxq_info(ring->xsk_pool, &ring->xdp_rxq); } else { WARN_ON(xdp_rxq_info_reg_mem_model(&ring->xdp_rxq, MEM_TYPE_PAGE_SHARED, NULL)); } if (igc_xdp_is_enabled(adapter)) set_ring_uses_large_buffer(ring); /* disable the queue */ wr32(IGC_RXDCTL(reg_idx), 0); /* Set DMA base address registers */ wr32(IGC_RDBAL(reg_idx), rdba & 0x00000000ffffffffULL); wr32(IGC_RDBAH(reg_idx), rdba >> 32); wr32(IGC_RDLEN(reg_idx), ring->count * sizeof(union igc_adv_rx_desc)); /* initialize head and tail */ ring->tail = adapter->io_addr + IGC_RDT(reg_idx); wr32(IGC_RDH(reg_idx), 0); writel(0, ring->tail); /* reset next-to- use/clean to place SW in sync with hardware */ ring->next_to_clean = 0; ring->next_to_use = 0; if (ring->xsk_pool) buf_size = xsk_pool_get_rx_frame_size(ring->xsk_pool); else if (ring_uses_large_buffer(ring)) buf_size = IGC_RXBUFFER_3072; else buf_size = IGC_RXBUFFER_2048; srrctl = rd32(IGC_SRRCTL(reg_idx)); srrctl &= ~(IGC_SRRCTL_BSIZEPKT_MASK | IGC_SRRCTL_BSIZEHDR_MASK | IGC_SRRCTL_DESCTYPE_MASK); srrctl |= IGC_SRRCTL_BSIZEHDR(IGC_RX_HDR_LEN); srrctl |= IGC_SRRCTL_BSIZEPKT(buf_size); srrctl |= IGC_SRRCTL_DESCTYPE_ADV_ONEBUF; wr32(IGC_SRRCTL(reg_idx), srrctl); rxdctl |= IGC_RX_PTHRESH; rxdctl |= IGC_RX_HTHRESH << 8; rxdctl |= IGC_RX_WTHRESH << 16; /* initialize rx_buffer_info */ memset(ring->rx_buffer_info, 0, sizeof(struct igc_rx_buffer) * ring->count); /* initialize Rx descriptor 0 */ rx_desc = IGC_RX_DESC(ring, 0); rx_desc->wb.upper.length = 0; /* enable receive descriptor fetching */ rxdctl |= IGC_RXDCTL_QUEUE_ENABLE; wr32(IGC_RXDCTL(reg_idx), rxdctl); } /** * igc_configure_rx - Configure receive Unit after Reset * @adapter: board private structure * * Configure the Rx unit of the MAC after a reset. */ static void igc_configure_rx(struct igc_adapter *adapter) { int i; /* Setup the HW Rx Head and Tail Descriptor Pointers and * the Base and Length of the Rx Descriptor Ring */ for (i = 0; i < adapter->num_rx_queues; i++) igc_configure_rx_ring(adapter, adapter->rx_ring[i]); } /** * igc_configure_tx_ring - Configure transmit ring after Reset * @adapter: board private structure * @ring: tx ring to configure * * Configure a transmit ring after a reset. */ static void igc_configure_tx_ring(struct igc_adapter *adapter, struct igc_ring *ring) { struct igc_hw *hw = &adapter->hw; int reg_idx = ring->reg_idx; u64 tdba = ring->dma; u32 txdctl = 0; ring->xsk_pool = igc_get_xsk_pool(adapter, ring); /* disable the queue */ wr32(IGC_TXDCTL(reg_idx), 0); wrfl(); wr32(IGC_TDLEN(reg_idx), ring->count * sizeof(union igc_adv_tx_desc)); wr32(IGC_TDBAL(reg_idx), tdba & 0x00000000ffffffffULL); wr32(IGC_TDBAH(reg_idx), tdba >> 32); ring->tail = adapter->io_addr + IGC_TDT(reg_idx); wr32(IGC_TDH(reg_idx), 0); writel(0, ring->tail); txdctl |= IGC_TX_PTHRESH; txdctl |= IGC_TX_HTHRESH << 8; txdctl |= IGC_TX_WTHRESH << 16; txdctl |= IGC_TXDCTL_QUEUE_ENABLE; wr32(IGC_TXDCTL(reg_idx), txdctl); } /** * igc_configure_tx - Configure transmit Unit after Reset * @adapter: board private structure * * Configure the Tx unit of the MAC after a reset. */ static void igc_configure_tx(struct igc_adapter *adapter) { int i; for (i = 0; i < adapter->num_tx_queues; i++) igc_configure_tx_ring(adapter, adapter->tx_ring[i]); } /** * igc_setup_mrqc - configure the multiple receive queue control registers * @adapter: Board private structure */ static void igc_setup_mrqc(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; u32 j, num_rx_queues; u32 mrqc, rxcsum; u32 rss_key[10]; netdev_rss_key_fill(rss_key, sizeof(rss_key)); for (j = 0; j < 10; j++) wr32(IGC_RSSRK(j), rss_key[j]); num_rx_queues = adapter->rss_queues; if (adapter->rss_indir_tbl_init != num_rx_queues) { for (j = 0; j < IGC_RETA_SIZE; j++) adapter->rss_indir_tbl[j] = (j * num_rx_queues) / IGC_RETA_SIZE; adapter->rss_indir_tbl_init = num_rx_queues; } igc_write_rss_indir_tbl(adapter); /* Disable raw packet checksumming so that RSS hash is placed in * descriptor on writeback. No need to enable TCP/UDP/IP checksum * offloads as they are enabled by default */ rxcsum = rd32(IGC_RXCSUM); rxcsum |= IGC_RXCSUM_PCSD; /* Enable Receive Checksum Offload for SCTP */ rxcsum |= IGC_RXCSUM_CRCOFL; /* Don't need to set TUOFL or IPOFL, they default to 1 */ wr32(IGC_RXCSUM, rxcsum); /* Generate RSS hash based on packet types, TCP/UDP * port numbers and/or IPv4/v6 src and dst addresses */ mrqc = IGC_MRQC_RSS_FIELD_IPV4 | IGC_MRQC_RSS_FIELD_IPV4_TCP | IGC_MRQC_RSS_FIELD_IPV6 | IGC_MRQC_RSS_FIELD_IPV6_TCP | IGC_MRQC_RSS_FIELD_IPV6_TCP_EX; if (adapter->flags & IGC_FLAG_RSS_FIELD_IPV4_UDP) mrqc |= IGC_MRQC_RSS_FIELD_IPV4_UDP; if (adapter->flags & IGC_FLAG_RSS_FIELD_IPV6_UDP) mrqc |= IGC_MRQC_RSS_FIELD_IPV6_UDP; mrqc |= IGC_MRQC_ENABLE_RSS_MQ; wr32(IGC_MRQC, mrqc); } /** * igc_setup_rctl - configure the receive control registers * @adapter: Board private structure */ static void igc_setup_rctl(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; u32 rctl; rctl = rd32(IGC_RCTL); rctl &= ~(3 << IGC_RCTL_MO_SHIFT); rctl &= ~(IGC_RCTL_LBM_TCVR | IGC_RCTL_LBM_MAC); rctl |= IGC_RCTL_EN | IGC_RCTL_BAM | IGC_RCTL_RDMTS_HALF | (hw->mac.mc_filter_type << IGC_RCTL_MO_SHIFT); /* enable stripping of CRC. Newer features require * that the HW strips the CRC. */ rctl |= IGC_RCTL_SECRC; /* disable store bad packets and clear size bits. */ rctl &= ~(IGC_RCTL_SBP | IGC_RCTL_SZ_256); /* enable LPE to allow for reception of jumbo frames */ rctl |= IGC_RCTL_LPE; /* disable queue 0 to prevent tail write w/o re-config */ wr32(IGC_RXDCTL(0), 0); /* This is useful for sniffing bad packets. */ if (adapter->netdev->features & NETIF_F_RXALL) { /* UPE and MPE will be handled by normal PROMISC logic * in set_rx_mode */ rctl |= (IGC_RCTL_SBP | /* Receive bad packets */ IGC_RCTL_BAM | /* RX All Bcast Pkts */ IGC_RCTL_PMCF); /* RX All MAC Ctrl Pkts */ rctl &= ~(IGC_RCTL_DPF | /* Allow filtered pause */ IGC_RCTL_CFIEN); /* Disable VLAN CFIEN Filter */ } wr32(IGC_RCTL, rctl); } /** * igc_setup_tctl - configure the transmit control registers * @adapter: Board private structure */ static void igc_setup_tctl(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; u32 tctl; /* disable queue 0 which icould be enabled by default */ wr32(IGC_TXDCTL(0), 0); /* Program the Transmit Control Register */ tctl = rd32(IGC_TCTL); tctl &= ~IGC_TCTL_CT; tctl |= IGC_TCTL_PSP | IGC_TCTL_RTLC | (IGC_COLLISION_THRESHOLD << IGC_CT_SHIFT); /* Enable transmits */ tctl |= IGC_TCTL_EN; wr32(IGC_TCTL, tctl); } /** * igc_set_mac_filter_hw() - Set MAC address filter in hardware * @adapter: Pointer to adapter where the filter should be set * @index: Filter index * @type: MAC address filter type (source or destination) * @addr: MAC address * @queue: If non-negative, queue assignment feature is enabled and frames * matching the filter are enqueued onto 'queue'. Otherwise, queue * assignment is disabled. */ static void igc_set_mac_filter_hw(struct igc_adapter *adapter, int index, enum igc_mac_filter_type type, const u8 *addr, int queue) { struct net_device *dev = adapter->netdev; struct igc_hw *hw = &adapter->hw; u32 ral, rah; if (WARN_ON(index >= hw->mac.rar_entry_count)) return; ral = le32_to_cpup((__le32 *)(addr)); rah = le16_to_cpup((__le16 *)(addr + 4)); if (type == IGC_MAC_FILTER_TYPE_SRC) { rah &= ~IGC_RAH_ASEL_MASK; rah |= IGC_RAH_ASEL_SRC_ADDR; } if (queue >= 0) { rah &= ~IGC_RAH_QSEL_MASK; rah |= (queue << IGC_RAH_QSEL_SHIFT); rah |= IGC_RAH_QSEL_ENABLE; } rah |= IGC_RAH_AV; wr32(IGC_RAL(index), ral); wr32(IGC_RAH(index), rah); netdev_dbg(dev, "MAC address filter set in HW: index %d", index); } /** * igc_clear_mac_filter_hw() - Clear MAC address filter in hardware * @adapter: Pointer to adapter where the filter should be cleared * @index: Filter index */ static void igc_clear_mac_filter_hw(struct igc_adapter *adapter, int index) { struct net_device *dev = adapter->netdev; struct igc_hw *hw = &adapter->hw; if (WARN_ON(index >= hw->mac.rar_entry_count)) return; wr32(IGC_RAL(index), 0); wr32(IGC_RAH(index), 0); netdev_dbg(dev, "MAC address filter cleared in HW: index %d", index); } /* Set default MAC address for the PF in the first RAR entry */ static void igc_set_default_mac_filter(struct igc_adapter *adapter) { struct net_device *dev = adapter->netdev; u8 *addr = adapter->hw.mac.addr; netdev_dbg(dev, "Set default MAC address filter: address %pM", addr); igc_set_mac_filter_hw(adapter, 0, IGC_MAC_FILTER_TYPE_DST, addr, -1); } /** * igc_set_mac - Change the Ethernet Address of the NIC * @netdev: network interface device structure * @p: pointer to an address structure * * Returns 0 on success, negative on failure */ static int igc_set_mac(struct net_device *netdev, void *p) { struct igc_adapter *adapter = netdev_priv(netdev); struct igc_hw *hw = &adapter->hw; struct sockaddr *addr = p; if (!is_valid_ether_addr(addr->sa_data)) return -EADDRNOTAVAIL; eth_hw_addr_set(netdev, addr->sa_data); memcpy(hw->mac.addr, addr->sa_data, netdev->addr_len); /* set the correct pool for the new PF MAC address in entry 0 */ igc_set_default_mac_filter(adapter); return 0; } /** * igc_write_mc_addr_list - write multicast addresses to MTA * @netdev: network interface device structure * * Writes multicast address list to the MTA hash table. * Returns: -ENOMEM on failure * 0 on no addresses written * X on writing X addresses to MTA **/ static int igc_write_mc_addr_list(struct net_device *netdev) { struct igc_adapter *adapter = netdev_priv(netdev); struct igc_hw *hw = &adapter->hw; struct netdev_hw_addr *ha; u8 *mta_list; int i; if (netdev_mc_empty(netdev)) { /* nothing to program, so clear mc list */ igc_update_mc_addr_list(hw, NULL, 0); return 0; } mta_list = kcalloc(netdev_mc_count(netdev), 6, GFP_ATOMIC); if (!mta_list) return -ENOMEM; /* The shared function expects a packed array of only addresses. */ i = 0; netdev_for_each_mc_addr(ha, netdev) memcpy(mta_list + (i++ * ETH_ALEN), ha->addr, ETH_ALEN); igc_update_mc_addr_list(hw, mta_list, i); kfree(mta_list); return netdev_mc_count(netdev); } static __le32 igc_tx_launchtime(struct igc_ring *ring, ktime_t txtime, bool *first_flag, bool *insert_empty) { struct igc_adapter *adapter = netdev_priv(ring->netdev); ktime_t cycle_time = adapter->cycle_time; ktime_t base_time = adapter->base_time; ktime_t now = ktime_get_clocktai(); ktime_t baset_est, end_of_cycle; s32 launchtime; s64 n; n = div64_s64(ktime_sub_ns(now, base_time), cycle_time); baset_est = ktime_add_ns(base_time, cycle_time * (n)); end_of_cycle = ktime_add_ns(baset_est, cycle_time); if (ktime_compare(txtime, end_of_cycle) >= 0) { if (baset_est != ring->last_ff_cycle) { *first_flag = true; ring->last_ff_cycle = baset_est; if (ktime_compare(end_of_cycle, ring->last_tx_cycle) > 0) *insert_empty = true; } } /* Introducing a window at end of cycle on which packets * potentially not honor launchtime. Window of 5us chosen * considering software update the tail pointer and packets * are dma'ed to packet buffer. */ if ((ktime_sub_ns(end_of_cycle, now) < 5 * NSEC_PER_USEC)) netdev_warn(ring->netdev, "Packet with txtime=%llu may not be honoured\n", txtime); ring->last_tx_cycle = end_of_cycle; launchtime = ktime_sub_ns(txtime, baset_est); if (launchtime > 0) div_s64_rem(launchtime, cycle_time, &launchtime); else launchtime = 0; return cpu_to_le32(launchtime); } static int igc_init_empty_frame(struct igc_ring *ring, struct igc_tx_buffer *buffer, struct sk_buff *skb) { unsigned int size; dma_addr_t dma; size = skb_headlen(skb); dma = dma_map_single(ring->dev, skb->data, size, DMA_TO_DEVICE); if (dma_mapping_error(ring->dev, dma)) { netdev_err_once(ring->netdev, "Failed to map DMA for TX\n"); return -ENOMEM; } buffer->skb = skb; buffer->protocol = 0; buffer->bytecount = skb->len; buffer->gso_segs = 1; buffer->time_stamp = jiffies; dma_unmap_len_set(buffer, len, skb->len); dma_unmap_addr_set(buffer, dma, dma); return 0; } static int igc_init_tx_empty_descriptor(struct igc_ring *ring, struct sk_buff *skb, struct igc_tx_buffer *first) { union igc_adv_tx_desc *desc; u32 cmd_type, olinfo_status; int err; if (!igc_desc_unused(ring)) return -EBUSY; err = igc_init_empty_frame(ring, first, skb); if (err) return err; cmd_type = IGC_ADVTXD_DTYP_DATA | IGC_ADVTXD_DCMD_DEXT | IGC_ADVTXD_DCMD_IFCS | IGC_TXD_DCMD | first->bytecount; olinfo_status = first->bytecount << IGC_ADVTXD_PAYLEN_SHIFT; desc = IGC_TX_DESC(ring, ring->next_to_use); desc->read.cmd_type_len = cpu_to_le32(cmd_type); desc->read.olinfo_status = cpu_to_le32(olinfo_status); desc->read.buffer_addr = cpu_to_le64(dma_unmap_addr(first, dma)); netdev_tx_sent_queue(txring_txq(ring), skb->len); first->next_to_watch = desc; ring->next_to_use++; if (ring->next_to_use == ring->count) ring->next_to_use = 0; return 0; } #define IGC_EMPTY_FRAME_SIZE 60 static void igc_tx_ctxtdesc(struct igc_ring *tx_ring, __le32 launch_time, bool first_flag, u32 vlan_macip_lens, u32 type_tucmd, u32 mss_l4len_idx) { struct igc_adv_tx_context_desc *context_desc; u16 i = tx_ring->next_to_use; context_desc = IGC_TX_CTXTDESC(tx_ring, i); i++; tx_ring->next_to_use = (i < tx_ring->count) ? i : 0; /* set bits to identify this as an advanced context descriptor */ type_tucmd |= IGC_TXD_CMD_DEXT | IGC_ADVTXD_DTYP_CTXT; /* For i225, context index must be unique per ring. */ if (test_bit(IGC_RING_FLAG_TX_CTX_IDX, &tx_ring->flags)) mss_l4len_idx |= tx_ring->reg_idx << 4; if (first_flag) mss_l4len_idx |= IGC_ADVTXD_TSN_CNTX_FIRST; context_desc->vlan_macip_lens = cpu_to_le32(vlan_macip_lens); context_desc->type_tucmd_mlhl = cpu_to_le32(type_tucmd); context_desc->mss_l4len_idx = cpu_to_le32(mss_l4len_idx); context_desc->launch_time = launch_time; } static void igc_tx_csum(struct igc_ring *tx_ring, struct igc_tx_buffer *first, __le32 launch_time, bool first_flag) { struct sk_buff *skb = first->skb; u32 vlan_macip_lens = 0; u32 type_tucmd = 0; if (skb->ip_summed != CHECKSUM_PARTIAL) { csum_failed: if (!(first->tx_flags & IGC_TX_FLAGS_VLAN) && !tx_ring->launchtime_enable) return; goto no_csum; } switch (skb->csum_offset) { case offsetof(struct tcphdr, check): type_tucmd = IGC_ADVTXD_TUCMD_L4T_TCP; fallthrough; case offsetof(struct udphdr, check): break; case offsetof(struct sctphdr, checksum): /* validate that this is actually an SCTP request */ if (skb_csum_is_sctp(skb)) { type_tucmd = IGC_ADVTXD_TUCMD_L4T_SCTP; break; } fallthrough; default: skb_checksum_help(skb); goto csum_failed; } /* update TX checksum flag */ first->tx_flags |= IGC_TX_FLAGS_CSUM; vlan_macip_lens = skb_checksum_start_offset(skb) - skb_network_offset(skb); no_csum: vlan_macip_lens |= skb_network_offset(skb) << IGC_ADVTXD_MACLEN_SHIFT; vlan_macip_lens |= first->tx_flags & IGC_TX_FLAGS_VLAN_MASK; igc_tx_ctxtdesc(tx_ring, launch_time, first_flag, vlan_macip_lens, type_tucmd, 0); } static int __igc_maybe_stop_tx(struct igc_ring *tx_ring, const u16 size) { struct net_device *netdev = tx_ring->netdev; netif_stop_subqueue(netdev, tx_ring->queue_index); /* memory barriier comment */ smp_mb(); /* We need to check again in a case another CPU has just * made room available. */ if (igc_desc_unused(tx_ring) < size) return -EBUSY; /* A reprieve! */ netif_wake_subqueue(netdev, tx_ring->queue_index); u64_stats_update_begin(&tx_ring->tx_syncp2); tx_ring->tx_stats.restart_queue2++; u64_stats_update_end(&tx_ring->tx_syncp2); return 0; } static inline int igc_maybe_stop_tx(struct igc_ring *tx_ring, const u16 size) { if (igc_desc_unused(tx_ring) >= size) return 0; return __igc_maybe_stop_tx(tx_ring, size); } #define IGC_SET_FLAG(_input, _flag, _result) \ (((_flag) <= (_result)) ? \ ((u32)((_input) & (_flag)) * ((_result) / (_flag))) : \ ((u32)((_input) & (_flag)) / ((_flag) / (_result)))) static u32 igc_tx_cmd_type(struct sk_buff *skb, u32 tx_flags) { /* set type for advanced descriptor with frame checksum insertion */ u32 cmd_type = IGC_ADVTXD_DTYP_DATA | IGC_ADVTXD_DCMD_DEXT | IGC_ADVTXD_DCMD_IFCS; /* set HW vlan bit if vlan is present */ cmd_type |= IGC_SET_FLAG(tx_flags, IGC_TX_FLAGS_VLAN, IGC_ADVTXD_DCMD_VLE); /* set segmentation bits for TSO */ cmd_type |= IGC_SET_FLAG(tx_flags, IGC_TX_FLAGS_TSO, (IGC_ADVTXD_DCMD_TSE)); /* set timestamp bit if present, will select the register set * based on the _TSTAMP(_X) bit. */ cmd_type |= IGC_SET_FLAG(tx_flags, IGC_TX_FLAGS_TSTAMP, (IGC_ADVTXD_MAC_TSTAMP)); cmd_type |= IGC_SET_FLAG(tx_flags, IGC_TX_FLAGS_TSTAMP_1, (IGC_ADVTXD_TSTAMP_REG_1)); cmd_type |= IGC_SET_FLAG(tx_flags, IGC_TX_FLAGS_TSTAMP_2, (IGC_ADVTXD_TSTAMP_REG_2)); cmd_type |= IGC_SET_FLAG(tx_flags, IGC_TX_FLAGS_TSTAMP_3, (IGC_ADVTXD_TSTAMP_REG_3)); /* insert frame checksum */ cmd_type ^= IGC_SET_FLAG(skb->no_fcs, 1, IGC_ADVTXD_DCMD_IFCS); return cmd_type; } static void igc_tx_olinfo_status(struct igc_ring *tx_ring, union igc_adv_tx_desc *tx_desc, u32 tx_flags, unsigned int paylen) { u32 olinfo_status = paylen << IGC_ADVTXD_PAYLEN_SHIFT; /* insert L4 checksum */ olinfo_status |= (tx_flags & IGC_TX_FLAGS_CSUM) * ((IGC_TXD_POPTS_TXSM << 8) / IGC_TX_FLAGS_CSUM); /* insert IPv4 checksum */ olinfo_status |= (tx_flags & IGC_TX_FLAGS_IPV4) * (((IGC_TXD_POPTS_IXSM << 8)) / IGC_TX_FLAGS_IPV4); tx_desc->read.olinfo_status = cpu_to_le32(olinfo_status); } static int igc_tx_map(struct igc_ring *tx_ring, struct igc_tx_buffer *first, const u8 hdr_len) { struct sk_buff *skb = first->skb; struct igc_tx_buffer *tx_buffer; union igc_adv_tx_desc *tx_desc; u32 tx_flags = first->tx_flags; skb_frag_t *frag; u16 i = tx_ring->next_to_use; unsigned int data_len, size; dma_addr_t dma; u32 cmd_type; cmd_type = igc_tx_cmd_type(skb, tx_flags); tx_desc = IGC_TX_DESC(tx_ring, i); igc_tx_olinfo_status(tx_ring, tx_desc, tx_flags, skb->len - hdr_len); size = skb_headlen(skb); data_len = skb->data_len; dma = dma_map_single(tx_ring->dev, skb->data, size, DMA_TO_DEVICE); tx_buffer = first; for (frag = &skb_shinfo(skb)->frags[0];; frag++) { if (dma_mapping_error(tx_ring->dev, dma)) goto dma_error; /* record length, and DMA address */ dma_unmap_len_set(tx_buffer, len, size); dma_unmap_addr_set(tx_buffer, dma, dma); tx_desc->read.buffer_addr = cpu_to_le64(dma); while (unlikely(size > IGC_MAX_DATA_PER_TXD)) { tx_desc->read.cmd_type_len = cpu_to_le32(cmd_type ^ IGC_MAX_DATA_PER_TXD); i++; tx_desc++; if (i == tx_ring->count) { tx_desc = IGC_TX_DESC(tx_ring, 0); i = 0; } tx_desc->read.olinfo_status = 0; dma += IGC_MAX_DATA_PER_TXD; size -= IGC_MAX_DATA_PER_TXD; tx_desc->read.buffer_addr = cpu_to_le64(dma); } if (likely(!data_len)) break; tx_desc->read.cmd_type_len = cpu_to_le32(cmd_type ^ size); i++; tx_desc++; if (i == tx_ring->count) { tx_desc = IGC_TX_DESC(tx_ring, 0); i = 0; } tx_desc->read.olinfo_status = 0; size = skb_frag_size(frag); data_len -= size; dma = skb_frag_dma_map(tx_ring->dev, frag, 0, size, DMA_TO_DEVICE); tx_buffer = &tx_ring->tx_buffer_info[i]; } /* write last descriptor with RS and EOP bits */ cmd_type |= size | IGC_TXD_DCMD; tx_desc->read.cmd_type_len = cpu_to_le32(cmd_type); netdev_tx_sent_queue(txring_txq(tx_ring), first->bytecount); /* set the timestamp */ first->time_stamp = jiffies; skb_tx_timestamp(skb); /* Force memory writes to complete before letting h/w know there * are new descriptors to fetch. (Only applicable for weak-ordered * memory model archs, such as IA-64). * * We also need this memory barrier to make certain all of the * status bits have been updated before next_to_watch is written. */ wmb(); /* set next_to_watch value indicating a packet is present */ first->next_to_watch = tx_desc; i++; if (i == tx_ring->count) i = 0; tx_ring->next_to_use = i; /* Make sure there is space in the ring for the next send. */ igc_maybe_stop_tx(tx_ring, DESC_NEEDED); if (netif_xmit_stopped(txring_txq(tx_ring)) || !netdev_xmit_more()) { writel(i, tx_ring->tail); } return 0; dma_error: netdev_err(tx_ring->netdev, "TX DMA map failed\n"); tx_buffer = &tx_ring->tx_buffer_info[i]; /* clear dma mappings for failed tx_buffer_info map */ while (tx_buffer != first) { if (dma_unmap_len(tx_buffer, len)) igc_unmap_tx_buffer(tx_ring->dev, tx_buffer); if (i-- == 0) i += tx_ring->count; tx_buffer = &tx_ring->tx_buffer_info[i]; } if (dma_unmap_len(tx_buffer, len)) igc_unmap_tx_buffer(tx_ring->dev, tx_buffer); dev_kfree_skb_any(tx_buffer->skb); tx_buffer->skb = NULL; tx_ring->next_to_use = i; return -1; } static int igc_tso(struct igc_ring *tx_ring, struct igc_tx_buffer *first, __le32 launch_time, bool first_flag, u8 *hdr_len) { u32 vlan_macip_lens, type_tucmd, mss_l4len_idx; struct sk_buff *skb = first->skb; union { struct iphdr *v4; struct ipv6hdr *v6; unsigned char *hdr; } ip; union { struct tcphdr *tcp; struct udphdr *udp; unsigned char *hdr; } l4; u32 paylen, l4_offset; int err; if (skb->ip_summed != CHECKSUM_PARTIAL) return 0; if (!skb_is_gso(skb)) return 0; err = skb_cow_head(skb, 0); if (err < 0) return err; ip.hdr = skb_network_header(skb); l4.hdr = skb_checksum_start(skb); /* ADV DTYP TUCMD MKRLOC/ISCSIHEDLEN */ type_tucmd = IGC_ADVTXD_TUCMD_L4T_TCP; /* initialize outer IP header fields */ if (ip.v4->version == 4) { unsigned char *csum_start = skb_checksum_start(skb); unsigned char *trans_start = ip.hdr + (ip.v4->ihl * 4); /* IP header will have to cancel out any data that * is not a part of the outer IP header */ ip.v4->check = csum_fold(csum_partial(trans_start, csum_start - trans_start, 0)); type_tucmd |= IGC_ADVTXD_TUCMD_IPV4; ip.v4->tot_len = 0; first->tx_flags |= IGC_TX_FLAGS_TSO | IGC_TX_FLAGS_CSUM | IGC_TX_FLAGS_IPV4; } else { ip.v6->payload_len = 0; first->tx_flags |= IGC_TX_FLAGS_TSO | IGC_TX_FLAGS_CSUM; } /* determine offset of inner transport header */ l4_offset = l4.hdr - skb->data; /* remove payload length from inner checksum */ paylen = skb->len - l4_offset; if (type_tucmd & IGC_ADVTXD_TUCMD_L4T_TCP) { /* compute length of segmentation header */ *hdr_len = (l4.tcp->doff * 4) + l4_offset; csum_replace_by_diff(&l4.tcp->check, (__force __wsum)htonl(paylen)); } else { /* compute length of segmentation header */ *hdr_len = sizeof(*l4.udp) + l4_offset; csum_replace_by_diff(&l4.udp->check, (__force __wsum)htonl(paylen)); } /* update gso size and bytecount with header size */ first->gso_segs = skb_shinfo(skb)->gso_segs; first->bytecount += (first->gso_segs - 1) * *hdr_len; /* MSS L4LEN IDX */ mss_l4len_idx = (*hdr_len - l4_offset) << IGC_ADVTXD_L4LEN_SHIFT; mss_l4len_idx |= skb_shinfo(skb)->gso_size << IGC_ADVTXD_MSS_SHIFT; /* VLAN MACLEN IPLEN */ vlan_macip_lens = l4.hdr - ip.hdr; vlan_macip_lens |= (ip.hdr - skb->data) << IGC_ADVTXD_MACLEN_SHIFT; vlan_macip_lens |= first->tx_flags & IGC_TX_FLAGS_VLAN_MASK; igc_tx_ctxtdesc(tx_ring, launch_time, first_flag, vlan_macip_lens, type_tucmd, mss_l4len_idx); return 1; } static bool igc_request_tx_tstamp(struct igc_adapter *adapter, struct sk_buff *skb, u32 *flags) { int i; for (i = 0; i < IGC_MAX_TX_TSTAMP_REGS; i++) { struct igc_tx_timestamp_request *tstamp = &adapter->tx_tstamp[i]; if (tstamp->skb) continue; tstamp->skb = skb_get(skb); tstamp->start = jiffies; *flags = tstamp->flags; return true; } return false; } static netdev_tx_t igc_xmit_frame_ring(struct sk_buff *skb, struct igc_ring *tx_ring) { struct igc_adapter *adapter = netdev_priv(tx_ring->netdev); bool first_flag = false, insert_empty = false; u16 count = TXD_USE_COUNT(skb_headlen(skb)); __be16 protocol = vlan_get_protocol(skb); struct igc_tx_buffer *first; __le32 launch_time = 0; u32 tx_flags = 0; unsigned short f; ktime_t txtime; u8 hdr_len = 0; int tso = 0; /* need: 1 descriptor per page * PAGE_SIZE/IGC_MAX_DATA_PER_TXD, * + 1 desc for skb_headlen/IGC_MAX_DATA_PER_TXD, * + 2 desc gap to keep tail from touching head, * + 1 desc for context descriptor, * otherwise try next time */ for (f = 0; f < skb_shinfo(skb)->nr_frags; f++) count += TXD_USE_COUNT(skb_frag_size( &skb_shinfo(skb)->frags[f])); if (igc_maybe_stop_tx(tx_ring, count + 5)) { /* this is a hard error */ return NETDEV_TX_BUSY; } if (!tx_ring->launchtime_enable) goto done; txtime = skb->tstamp; skb->tstamp = ktime_set(0, 0); launch_time = igc_tx_launchtime(tx_ring, txtime, &first_flag, &insert_empty); if (insert_empty) { struct igc_tx_buffer *empty_info; struct sk_buff *empty; void *data; empty_info = &tx_ring->tx_buffer_info[tx_ring->next_to_use]; empty = alloc_skb(IGC_EMPTY_FRAME_SIZE, GFP_ATOMIC); if (!empty) goto done; data = skb_put(empty, IGC_EMPTY_FRAME_SIZE); memset(data, 0, IGC_EMPTY_FRAME_SIZE); igc_tx_ctxtdesc(tx_ring, 0, false, 0, 0, 0); if (igc_init_tx_empty_descriptor(tx_ring, empty, empty_info) < 0) dev_kfree_skb_any(empty); } done: /* record the location of the first descriptor for this packet */ first = &tx_ring->tx_buffer_info[tx_ring->next_to_use]; first->type = IGC_TX_BUFFER_TYPE_SKB; first->skb = skb; first->bytecount = skb->len; first->gso_segs = 1; if (adapter->qbv_transition || tx_ring->oper_gate_closed) goto out_drop; if (tx_ring->max_sdu > 0 && first->bytecount > tx_ring->max_sdu) { adapter->stats.txdrop++; goto out_drop; } if (unlikely(test_bit(IGC_RING_FLAG_TX_HWTSTAMP, &tx_ring->flags) && skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP)) { /* FIXME: add support for retrieving timestamps from * the other timer registers before skipping the * timestamping request. */ unsigned long flags; u32 tstamp_flags; spin_lock_irqsave(&adapter->ptp_tx_lock, flags); if (igc_request_tx_tstamp(adapter, skb, &tstamp_flags)) { skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS; tx_flags |= IGC_TX_FLAGS_TSTAMP | tstamp_flags; } else { adapter->tx_hwtstamp_skipped++; } spin_unlock_irqrestore(&adapter->ptp_tx_lock, flags); } if (skb_vlan_tag_present(skb)) { tx_flags |= IGC_TX_FLAGS_VLAN; tx_flags |= (skb_vlan_tag_get(skb) << IGC_TX_FLAGS_VLAN_SHIFT); } /* record initial flags and protocol */ first->tx_flags = tx_flags; first->protocol = protocol; tso = igc_tso(tx_ring, first, launch_time, first_flag, &hdr_len); if (tso < 0) goto out_drop; else if (!tso) igc_tx_csum(tx_ring, first, launch_time, first_flag); igc_tx_map(tx_ring, first, hdr_len); return NETDEV_TX_OK; out_drop: dev_kfree_skb_any(first->skb); first->skb = NULL; return NETDEV_TX_OK; } static inline struct igc_ring *igc_tx_queue_mapping(struct igc_adapter *adapter, struct sk_buff *skb) { unsigned int r_idx = skb->queue_mapping; if (r_idx >= adapter->num_tx_queues) r_idx = r_idx % adapter->num_tx_queues; return adapter->tx_ring[r_idx]; } static netdev_tx_t igc_xmit_frame(struct sk_buff *skb, struct net_device *netdev) { struct igc_adapter *adapter = netdev_priv(netdev); /* The minimum packet size with TCTL.PSP set is 17 so pad the skb * in order to meet this minimum size requirement. */ if (skb->len < 17) { if (skb_padto(skb, 17)) return NETDEV_TX_OK; skb->len = 17; } return igc_xmit_frame_ring(skb, igc_tx_queue_mapping(adapter, skb)); } static void igc_rx_checksum(struct igc_ring *ring, union igc_adv_rx_desc *rx_desc, struct sk_buff *skb) { skb_checksum_none_assert(skb); /* Ignore Checksum bit is set */ if (igc_test_staterr(rx_desc, IGC_RXD_STAT_IXSM)) return; /* Rx checksum disabled via ethtool */ if (!(ring->netdev->features & NETIF_F_RXCSUM)) return; /* TCP/UDP checksum error bit is set */ if (igc_test_staterr(rx_desc, IGC_RXDEXT_STATERR_L4E | IGC_RXDEXT_STATERR_IPE)) { /* work around errata with sctp packets where the TCPE aka * L4E bit is set incorrectly on 64 byte (60 byte w/o crc) * packets (aka let the stack check the crc32c) */ if (!(skb->len == 60 && test_bit(IGC_RING_FLAG_RX_SCTP_CSUM, &ring->flags))) { u64_stats_update_begin(&ring->rx_syncp); ring->rx_stats.csum_err++; u64_stats_update_end(&ring->rx_syncp); } /* let the stack verify checksum errors */ return; } /* It must be a TCP or UDP packet with a valid checksum */ if (igc_test_staterr(rx_desc, IGC_RXD_STAT_TCPCS | IGC_RXD_STAT_UDPCS)) skb->ip_summed = CHECKSUM_UNNECESSARY; netdev_dbg(ring->netdev, "cksum success: bits %08X\n", le32_to_cpu(rx_desc->wb.upper.status_error)); } /* Mapping HW RSS Type to enum pkt_hash_types */ static const enum pkt_hash_types igc_rss_type_table[IGC_RSS_TYPE_MAX_TABLE] = { [IGC_RSS_TYPE_NO_HASH] = PKT_HASH_TYPE_L2, [IGC_RSS_TYPE_HASH_TCP_IPV4] = PKT_HASH_TYPE_L4, [IGC_RSS_TYPE_HASH_IPV4] = PKT_HASH_TYPE_L3, [IGC_RSS_TYPE_HASH_TCP_IPV6] = PKT_HASH_TYPE_L4, [IGC_RSS_TYPE_HASH_IPV6_EX] = PKT_HASH_TYPE_L3, [IGC_RSS_TYPE_HASH_IPV6] = PKT_HASH_TYPE_L3, [IGC_RSS_TYPE_HASH_TCP_IPV6_EX] = PKT_HASH_TYPE_L4, [IGC_RSS_TYPE_HASH_UDP_IPV4] = PKT_HASH_TYPE_L4, [IGC_RSS_TYPE_HASH_UDP_IPV6] = PKT_HASH_TYPE_L4, [IGC_RSS_TYPE_HASH_UDP_IPV6_EX] = PKT_HASH_TYPE_L4, [10] = PKT_HASH_TYPE_NONE, /* RSS Type above 9 "Reserved" by HW */ [11] = PKT_HASH_TYPE_NONE, /* keep array sized for SW bit-mask */ [12] = PKT_HASH_TYPE_NONE, /* to handle future HW revisons */ [13] = PKT_HASH_TYPE_NONE, [14] = PKT_HASH_TYPE_NONE, [15] = PKT_HASH_TYPE_NONE, }; static inline void igc_rx_hash(struct igc_ring *ring, union igc_adv_rx_desc *rx_desc, struct sk_buff *skb) { if (ring->netdev->features & NETIF_F_RXHASH) { u32 rss_hash = le32_to_cpu(rx_desc->wb.lower.hi_dword.rss); u32 rss_type = igc_rss_type(rx_desc); skb_set_hash(skb, rss_hash, igc_rss_type_table[rss_type]); } } static void igc_rx_vlan(struct igc_ring *rx_ring, union igc_adv_rx_desc *rx_desc, struct sk_buff *skb) { struct net_device *dev = rx_ring->netdev; u16 vid; if ((dev->features & NETIF_F_HW_VLAN_CTAG_RX) && igc_test_staterr(rx_desc, IGC_RXD_STAT_VP)) { if (igc_test_staterr(rx_desc, IGC_RXDEXT_STATERR_LB) && test_bit(IGC_RING_FLAG_RX_LB_VLAN_BSWAP, &rx_ring->flags)) vid = be16_to_cpu((__force __be16)rx_desc->wb.upper.vlan); else vid = le16_to_cpu(rx_desc->wb.upper.vlan); __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vid); } } /** * igc_process_skb_fields - Populate skb header fields from Rx descriptor * @rx_ring: rx descriptor ring packet is being transacted on * @rx_desc: pointer to the EOP Rx descriptor * @skb: pointer to current skb being populated * * This function checks the ring, descriptor, and packet information in order * to populate the hash, checksum, VLAN, protocol, and other fields within the * skb. */ static void igc_process_skb_fields(struct igc_ring *rx_ring, union igc_adv_rx_desc *rx_desc, struct sk_buff *skb) { igc_rx_hash(rx_ring, rx_desc, skb); igc_rx_checksum(rx_ring, rx_desc, skb); igc_rx_vlan(rx_ring, rx_desc, skb); skb_record_rx_queue(skb, rx_ring->queue_index); skb->protocol = eth_type_trans(skb, rx_ring->netdev); } static void igc_vlan_mode(struct net_device *netdev, netdev_features_t features) { bool enable = !!(features & NETIF_F_HW_VLAN_CTAG_RX); struct igc_adapter *adapter = netdev_priv(netdev); struct igc_hw *hw = &adapter->hw; u32 ctrl; ctrl = rd32(IGC_CTRL); if (enable) { /* enable VLAN tag insert/strip */ ctrl |= IGC_CTRL_VME; } else { /* disable VLAN tag insert/strip */ ctrl &= ~IGC_CTRL_VME; } wr32(IGC_CTRL, ctrl); } static void igc_restore_vlan(struct igc_adapter *adapter) { igc_vlan_mode(adapter->netdev, adapter->netdev->features); } static struct igc_rx_buffer *igc_get_rx_buffer(struct igc_ring *rx_ring, const unsigned int size, int *rx_buffer_pgcnt) { struct igc_rx_buffer *rx_buffer; rx_buffer = &rx_ring->rx_buffer_info[rx_ring->next_to_clean]; *rx_buffer_pgcnt = #if (PAGE_SIZE < 8192) page_count(rx_buffer->page); #else 0; #endif prefetchw(rx_buffer->page); /* we are reusing so sync this buffer for CPU use */ dma_sync_single_range_for_cpu(rx_ring->dev, rx_buffer->dma, rx_buffer->page_offset, size, DMA_FROM_DEVICE); rx_buffer->pagecnt_bias--; return rx_buffer; } static void igc_rx_buffer_flip(struct igc_rx_buffer *buffer, unsigned int truesize) { #if (PAGE_SIZE < 8192) buffer->page_offset ^= truesize; #else buffer->page_offset += truesize; #endif } static unsigned int igc_get_rx_frame_truesize(struct igc_ring *ring, unsigned int size) { unsigned int truesize; #if (PAGE_SIZE < 8192) truesize = igc_rx_pg_size(ring) / 2; #else truesize = ring_uses_build_skb(ring) ? SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) + SKB_DATA_ALIGN(IGC_SKB_PAD + size) : SKB_DATA_ALIGN(size); #endif return truesize; } /** * igc_add_rx_frag - Add contents of Rx buffer to sk_buff * @rx_ring: rx descriptor ring to transact packets on * @rx_buffer: buffer containing page to add * @skb: sk_buff to place the data into * @size: size of buffer to be added * * This function will add the data contained in rx_buffer->page to the skb. */ static void igc_add_rx_frag(struct igc_ring *rx_ring, struct igc_rx_buffer *rx_buffer, struct sk_buff *skb, unsigned int size) { unsigned int truesize; #if (PAGE_SIZE < 8192) truesize = igc_rx_pg_size(rx_ring) / 2; #else truesize = ring_uses_build_skb(rx_ring) ? SKB_DATA_ALIGN(IGC_SKB_PAD + size) : SKB_DATA_ALIGN(size); #endif skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, rx_buffer->page, rx_buffer->page_offset, size, truesize); igc_rx_buffer_flip(rx_buffer, truesize); } static struct sk_buff *igc_build_skb(struct igc_ring *rx_ring, struct igc_rx_buffer *rx_buffer, struct xdp_buff *xdp) { unsigned int size = xdp->data_end - xdp->data; unsigned int truesize = igc_get_rx_frame_truesize(rx_ring, size); unsigned int metasize = xdp->data - xdp->data_meta; struct sk_buff *skb; /* prefetch first cache line of first page */ net_prefetch(xdp->data_meta); /* build an skb around the page buffer */ skb = napi_build_skb(xdp->data_hard_start, truesize); if (unlikely(!skb)) return NULL; /* update pointers within the skb to store the data */ skb_reserve(skb, xdp->data - xdp->data_hard_start); __skb_put(skb, size); if (metasize) skb_metadata_set(skb, metasize); igc_rx_buffer_flip(rx_buffer, truesize); return skb; } static struct sk_buff *igc_construct_skb(struct igc_ring *rx_ring, struct igc_rx_buffer *rx_buffer, struct xdp_buff *xdp, ktime_t timestamp) { unsigned int metasize = xdp->data - xdp->data_meta; unsigned int size = xdp->data_end - xdp->data; unsigned int truesize = igc_get_rx_frame_truesize(rx_ring, size); void *va = xdp->data; unsigned int headlen; struct sk_buff *skb; /* prefetch first cache line of first page */ net_prefetch(xdp->data_meta); /* allocate a skb to store the frags */ skb = napi_alloc_skb(&rx_ring->q_vector->napi, IGC_RX_HDR_LEN + metasize); if (unlikely(!skb)) return NULL; if (timestamp) skb_hwtstamps(skb)->hwtstamp = timestamp; /* Determine available headroom for copy */ headlen = size; if (headlen > IGC_RX_HDR_LEN) headlen = eth_get_headlen(skb->dev, va, IGC_RX_HDR_LEN); /* align pull length to size of long to optimize memcpy performance */ memcpy(__skb_put(skb, headlen + metasize), xdp->data_meta, ALIGN(headlen + metasize, sizeof(long))); if (metasize) { skb_metadata_set(skb, metasize); __skb_pull(skb, metasize); } /* update all of the pointers */ size -= headlen; if (size) { skb_add_rx_frag(skb, 0, rx_buffer->page, (va + headlen) - page_address(rx_buffer->page), size, truesize); igc_rx_buffer_flip(rx_buffer, truesize); } else { rx_buffer->pagecnt_bias++; } return skb; } /** * igc_reuse_rx_page - page flip buffer and store it back on the ring * @rx_ring: rx descriptor ring to store buffers on * @old_buff: donor buffer to have page reused * * Synchronizes page for reuse by the adapter */ static void igc_reuse_rx_page(struct igc_ring *rx_ring, struct igc_rx_buffer *old_buff) { u16 nta = rx_ring->next_to_alloc; struct igc_rx_buffer *new_buff; new_buff = &rx_ring->rx_buffer_info[nta]; /* update, and store next to alloc */ nta++; rx_ring->next_to_alloc = (nta < rx_ring->count) ? nta : 0; /* Transfer page from old buffer to new buffer. * Move each member individually to avoid possible store * forwarding stalls. */ new_buff->dma = old_buff->dma; new_buff->page = old_buff->page; new_buff->page_offset = old_buff->page_offset; new_buff->pagecnt_bias = old_buff->pagecnt_bias; } static bool igc_can_reuse_rx_page(struct igc_rx_buffer *rx_buffer, int rx_buffer_pgcnt) { unsigned int pagecnt_bias = rx_buffer->pagecnt_bias; struct page *page = rx_buffer->page; /* avoid re-using remote and pfmemalloc pages */ if (!dev_page_is_reusable(page)) return false; #if (PAGE_SIZE < 8192) /* if we are only owner of page we can reuse it */ if (unlikely((rx_buffer_pgcnt - pagecnt_bias) > 1)) return false; #else #define IGC_LAST_OFFSET \ (SKB_WITH_OVERHEAD(PAGE_SIZE) - IGC_RXBUFFER_2048) if (rx_buffer->page_offset > IGC_LAST_OFFSET) return false; #endif /* If we have drained the page fragment pool we need to update * the pagecnt_bias and page count so that we fully restock the * number of references the driver holds. */ if (unlikely(pagecnt_bias == 1)) { page_ref_add(page, USHRT_MAX - 1); rx_buffer->pagecnt_bias = USHRT_MAX; } return true; } /** * igc_is_non_eop - process handling of non-EOP buffers * @rx_ring: Rx ring being processed * @rx_desc: Rx descriptor for current buffer * * This function updates next to clean. If the buffer is an EOP buffer * this function exits returning false, otherwise it will place the * sk_buff in the next buffer to be chained and return true indicating * that this is in fact a non-EOP buffer. */ static bool igc_is_non_eop(struct igc_ring *rx_ring, union igc_adv_rx_desc *rx_desc) { u32 ntc = rx_ring->next_to_clean + 1; /* fetch, update, and store next to clean */ ntc = (ntc < rx_ring->count) ? ntc : 0; rx_ring->next_to_clean = ntc; prefetch(IGC_RX_DESC(rx_ring, ntc)); if (likely(igc_test_staterr(rx_desc, IGC_RXD_STAT_EOP))) return false; return true; } /** * igc_cleanup_headers - Correct corrupted or empty headers * @rx_ring: rx descriptor ring packet is being transacted on * @rx_desc: pointer to the EOP Rx descriptor * @skb: pointer to current skb being fixed * * Address the case where we are pulling data in on pages only * and as such no data is present in the skb header. * * In addition if skb is not at least 60 bytes we need to pad it so that * it is large enough to qualify as a valid Ethernet frame. * * Returns true if an error was encountered and skb was freed. */ static bool igc_cleanup_headers(struct igc_ring *rx_ring, union igc_adv_rx_desc *rx_desc, struct sk_buff *skb) { /* XDP packets use error pointer so abort at this point */ if (IS_ERR(skb)) return true; if (unlikely(igc_test_staterr(rx_desc, IGC_RXDEXT_STATERR_RXE))) { struct net_device *netdev = rx_ring->netdev; if (!(netdev->features & NETIF_F_RXALL)) { dev_kfree_skb_any(skb); return true; } } /* if eth_skb_pad returns an error the skb was freed */ if (eth_skb_pad(skb)) return true; return false; } static void igc_put_rx_buffer(struct igc_ring *rx_ring, struct igc_rx_buffer *rx_buffer, int rx_buffer_pgcnt) { if (igc_can_reuse_rx_page(rx_buffer, rx_buffer_pgcnt)) { /* hand second half of page back to the ring */ igc_reuse_rx_page(rx_ring, rx_buffer); } else { /* We are not reusing the buffer so unmap it and free * any references we are holding to it */ dma_unmap_page_attrs(rx_ring->dev, rx_buffer->dma, igc_rx_pg_size(rx_ring), DMA_FROM_DEVICE, IGC_RX_DMA_ATTR); __page_frag_cache_drain(rx_buffer->page, rx_buffer->pagecnt_bias); } /* clear contents of rx_buffer */ rx_buffer->page = NULL; } static inline unsigned int igc_rx_offset(struct igc_ring *rx_ring) { struct igc_adapter *adapter = rx_ring->q_vector->adapter; if (ring_uses_build_skb(rx_ring)) return IGC_SKB_PAD; if (igc_xdp_is_enabled(adapter)) return XDP_PACKET_HEADROOM; return 0; } static bool igc_alloc_mapped_page(struct igc_ring *rx_ring, struct igc_rx_buffer *bi) { struct page *page = bi->page; dma_addr_t dma; /* since we are recycling buffers we should seldom need to alloc */ if (likely(page)) return true; /* alloc new page for storage */ page = dev_alloc_pages(igc_rx_pg_order(rx_ring)); if (unlikely(!page)) { rx_ring->rx_stats.alloc_failed++; return false; } /* map page for use */ dma = dma_map_page_attrs(rx_ring->dev, page, 0, igc_rx_pg_size(rx_ring), DMA_FROM_DEVICE, IGC_RX_DMA_ATTR); /* if mapping failed free memory back to system since * there isn't much point in holding memory we can't use */ if (dma_mapping_error(rx_ring->dev, dma)) { __free_page(page); rx_ring->rx_stats.alloc_failed++; return false; } bi->dma = dma; bi->page = page; bi->page_offset = igc_rx_offset(rx_ring); page_ref_add(page, USHRT_MAX - 1); bi->pagecnt_bias = USHRT_MAX; return true; } /** * igc_alloc_rx_buffers - Replace used receive buffers; packet split * @rx_ring: rx descriptor ring * @cleaned_count: number of buffers to clean */ static void igc_alloc_rx_buffers(struct igc_ring *rx_ring, u16 cleaned_count) { union igc_adv_rx_desc *rx_desc; u16 i = rx_ring->next_to_use; struct igc_rx_buffer *bi; u16 bufsz; /* nothing to do */ if (!cleaned_count) return; rx_desc = IGC_RX_DESC(rx_ring, i); bi = &rx_ring->rx_buffer_info[i]; i -= rx_ring->count; bufsz = igc_rx_bufsz(rx_ring); do { if (!igc_alloc_mapped_page(rx_ring, bi)) break; /* sync the buffer for use by the device */ dma_sync_single_range_for_device(rx_ring->dev, bi->dma, bi->page_offset, bufsz, DMA_FROM_DEVICE); /* Refresh the desc even if buffer_addrs didn't change * because each write-back erases this info. */ rx_desc->read.pkt_addr = cpu_to_le64(bi->dma + bi->page_offset); rx_desc++; bi++; i++; if (unlikely(!i)) { rx_desc = IGC_RX_DESC(rx_ring, 0); bi = rx_ring->rx_buffer_info; i -= rx_ring->count; } /* clear the length for the next_to_use descriptor */ rx_desc->wb.upper.length = 0; cleaned_count--; } while (cleaned_count); i += rx_ring->count; if (rx_ring->next_to_use != i) { /* record the next descriptor to use */ rx_ring->next_to_use = i; /* update next to alloc since we have filled the ring */ rx_ring->next_to_alloc = i; /* Force memory writes to complete before letting h/w * know there are new descriptors to fetch. (Only * applicable for weak-ordered memory model archs, * such as IA-64). */ wmb(); writel(i, rx_ring->tail); } } static bool igc_alloc_rx_buffers_zc(struct igc_ring *ring, u16 count) { union igc_adv_rx_desc *desc; u16 i = ring->next_to_use; struct igc_rx_buffer *bi; dma_addr_t dma; bool ok = true; if (!count) return ok; XSK_CHECK_PRIV_TYPE(struct igc_xdp_buff); desc = IGC_RX_DESC(ring, i); bi = &ring->rx_buffer_info[i]; i -= ring->count; do { bi->xdp = xsk_buff_alloc(ring->xsk_pool); if (!bi->xdp) { ok = false; break; } dma = xsk_buff_xdp_get_dma(bi->xdp); desc->read.pkt_addr = cpu_to_le64(dma); desc++; bi++; i++; if (unlikely(!i)) { desc = IGC_RX_DESC(ring, 0); bi = ring->rx_buffer_info; i -= ring->count; } /* Clear the length for the next_to_use descriptor. */ desc->wb.upper.length = 0; count--; } while (count); i += ring->count; if (ring->next_to_use != i) { ring->next_to_use = i; /* Force memory writes to complete before letting h/w * know there are new descriptors to fetch. (Only * applicable for weak-ordered memory model archs, * such as IA-64). */ wmb(); writel(i, ring->tail); } return ok; } /* This function requires __netif_tx_lock is held by the caller. */ static int igc_xdp_init_tx_descriptor(struct igc_ring *ring, struct xdp_frame *xdpf) { struct skb_shared_info *sinfo = xdp_get_shared_info_from_frame(xdpf); u8 nr_frags = unlikely(xdp_frame_has_frags(xdpf)) ? sinfo->nr_frags : 0; u16 count, index = ring->next_to_use; struct igc_tx_buffer *head = &ring->tx_buffer_info[index]; struct igc_tx_buffer *buffer = head; union igc_adv_tx_desc *desc = IGC_TX_DESC(ring, index); u32 olinfo_status, len = xdpf->len, cmd_type; void *data = xdpf->data; u16 i; count = TXD_USE_COUNT(len); for (i = 0; i < nr_frags; i++) count += TXD_USE_COUNT(skb_frag_size(&sinfo->frags[i])); if (igc_maybe_stop_tx(ring, count + 3)) { /* this is a hard error */ return -EBUSY; } i = 0; head->bytecount = xdp_get_frame_len(xdpf); head->type = IGC_TX_BUFFER_TYPE_XDP; head->gso_segs = 1; head->xdpf = xdpf; olinfo_status = head->bytecount << IGC_ADVTXD_PAYLEN_SHIFT; desc->read.olinfo_status = cpu_to_le32(olinfo_status); for (;;) { dma_addr_t dma; dma = dma_map_single(ring->dev, data, len, DMA_TO_DEVICE); if (dma_mapping_error(ring->dev, dma)) { netdev_err_once(ring->netdev, "Failed to map DMA for TX\n"); goto unmap; } dma_unmap_len_set(buffer, len, len); dma_unmap_addr_set(buffer, dma, dma); cmd_type = IGC_ADVTXD_DTYP_DATA | IGC_ADVTXD_DCMD_DEXT | IGC_ADVTXD_DCMD_IFCS | len; desc->read.cmd_type_len = cpu_to_le32(cmd_type); desc->read.buffer_addr = cpu_to_le64(dma); buffer->protocol = 0; if (++index == ring->count) index = 0; if (i == nr_frags) break; buffer = &ring->tx_buffer_info[index]; desc = IGC_TX_DESC(ring, index); desc->read.olinfo_status = 0; data = skb_frag_address(&sinfo->frags[i]); len = skb_frag_size(&sinfo->frags[i]); i++; } desc->read.cmd_type_len |= cpu_to_le32(IGC_TXD_DCMD); netdev_tx_sent_queue(txring_txq(ring), head->bytecount); /* set the timestamp */ head->time_stamp = jiffies; /* set next_to_watch value indicating a packet is present */ head->next_to_watch = desc; ring->next_to_use = index; return 0; unmap: for (;;) { buffer = &ring->tx_buffer_info[index]; if (dma_unmap_len(buffer, len)) dma_unmap_page(ring->dev, dma_unmap_addr(buffer, dma), dma_unmap_len(buffer, len), DMA_TO_DEVICE); dma_unmap_len_set(buffer, len, 0); if (buffer == head) break; if (!index) index += ring->count; index--; } return -ENOMEM; } static struct igc_ring *igc_xdp_get_tx_ring(struct igc_adapter *adapter, int cpu) { int index = cpu; if (unlikely(index < 0)) index = 0; while (index >= adapter->num_tx_queues) index -= adapter->num_tx_queues; return adapter->tx_ring[index]; } static int igc_xdp_xmit_back(struct igc_adapter *adapter, struct xdp_buff *xdp) { struct xdp_frame *xdpf = xdp_convert_buff_to_frame(xdp); int cpu = smp_processor_id(); struct netdev_queue *nq; struct igc_ring *ring; int res; if (unlikely(!xdpf)) return -EFAULT; ring = igc_xdp_get_tx_ring(adapter, cpu); nq = txring_txq(ring); __netif_tx_lock(nq, cpu); /* Avoid transmit queue timeout since we share it with the slow path */ txq_trans_cond_update(nq); res = igc_xdp_init_tx_descriptor(ring, xdpf); __netif_tx_unlock(nq); return res; } /* This function assumes rcu_read_lock() is held by the caller. */ static int __igc_xdp_run_prog(struct igc_adapter *adapter, struct bpf_prog *prog, struct xdp_buff *xdp) { u32 act = bpf_prog_run_xdp(prog, xdp); switch (act) { case XDP_PASS: return IGC_XDP_PASS; case XDP_TX: if (igc_xdp_xmit_back(adapter, xdp) < 0) goto out_failure; return IGC_XDP_TX; case XDP_REDIRECT: if (xdp_do_redirect(adapter->netdev, xdp, prog) < 0) goto out_failure; return IGC_XDP_REDIRECT; break; default: bpf_warn_invalid_xdp_action(adapter->netdev, prog, act); fallthrough; case XDP_ABORTED: out_failure: trace_xdp_exception(adapter->netdev, prog, act); fallthrough; case XDP_DROP: return IGC_XDP_CONSUMED; } } static struct sk_buff *igc_xdp_run_prog(struct igc_adapter *adapter, struct xdp_buff *xdp) { struct bpf_prog *prog; int res; prog = READ_ONCE(adapter->xdp_prog); if (!prog) { res = IGC_XDP_PASS; goto out; } res = __igc_xdp_run_prog(adapter, prog, xdp); out: return ERR_PTR(-res); } /* This function assumes __netif_tx_lock is held by the caller. */ static void igc_flush_tx_descriptors(struct igc_ring *ring) { /* Once tail pointer is updated, hardware can fetch the descriptors * any time so we issue a write membar here to ensure all memory * writes are complete before the tail pointer is updated. */ wmb(); writel(ring->next_to_use, ring->tail); } static void igc_finalize_xdp(struct igc_adapter *adapter, int status) { int cpu = smp_processor_id(); struct netdev_queue *nq; struct igc_ring *ring; if (status & IGC_XDP_TX) { ring = igc_xdp_get_tx_ring(adapter, cpu); nq = txring_txq(ring); __netif_tx_lock(nq, cpu); igc_flush_tx_descriptors(ring); __netif_tx_unlock(nq); } if (status & IGC_XDP_REDIRECT) xdp_do_flush(); } static void igc_update_rx_stats(struct igc_q_vector *q_vector, unsigned int packets, unsigned int bytes) { struct igc_ring *ring = q_vector->rx.ring; u64_stats_update_begin(&ring->rx_syncp); ring->rx_stats.packets += packets; ring->rx_stats.bytes += bytes; u64_stats_update_end(&ring->rx_syncp); q_vector->rx.total_packets += packets; q_vector->rx.total_bytes += bytes; } static int igc_clean_rx_irq(struct igc_q_vector *q_vector, const int budget) { unsigned int total_bytes = 0, total_packets = 0; struct igc_adapter *adapter = q_vector->adapter; struct igc_ring *rx_ring = q_vector->rx.ring; struct sk_buff *skb = rx_ring->skb; u16 cleaned_count = igc_desc_unused(rx_ring); int xdp_status = 0, rx_buffer_pgcnt; while (likely(total_packets < budget)) { union igc_adv_rx_desc *rx_desc; struct igc_rx_buffer *rx_buffer; unsigned int size, truesize; struct igc_xdp_buff ctx; ktime_t timestamp = 0; int pkt_offset = 0; void *pktbuf; /* return some buffers to hardware, one at a time is too slow */ if (cleaned_count >= IGC_RX_BUFFER_WRITE) { igc_alloc_rx_buffers(rx_ring, cleaned_count); cleaned_count = 0; } rx_desc = IGC_RX_DESC(rx_ring, rx_ring->next_to_clean); size = le16_to_cpu(rx_desc->wb.upper.length); if (!size) break; /* This memory barrier is needed to keep us from reading * any other fields out of the rx_desc until we know the * descriptor has been written back */ dma_rmb(); rx_buffer = igc_get_rx_buffer(rx_ring, size, &rx_buffer_pgcnt); truesize = igc_get_rx_frame_truesize(rx_ring, size); pktbuf = page_address(rx_buffer->page) + rx_buffer->page_offset; if (igc_test_staterr(rx_desc, IGC_RXDADV_STAT_TSIP)) { timestamp = igc_ptp_rx_pktstamp(q_vector->adapter, pktbuf); ctx.rx_ts = timestamp; pkt_offset = IGC_TS_HDR_LEN; size -= IGC_TS_HDR_LEN; } if (!skb) { xdp_init_buff(&ctx.xdp, truesize, &rx_ring->xdp_rxq); xdp_prepare_buff(&ctx.xdp, pktbuf - igc_rx_offset(rx_ring), igc_rx_offset(rx_ring) + pkt_offset, size, true); xdp_buff_clear_frags_flag(&ctx.xdp); ctx.rx_desc = rx_desc; skb = igc_xdp_run_prog(adapter, &ctx.xdp); } if (IS_ERR(skb)) { unsigned int xdp_res = -PTR_ERR(skb); switch (xdp_res) { case IGC_XDP_CONSUMED: rx_buffer->pagecnt_bias++; break; case IGC_XDP_TX: case IGC_XDP_REDIRECT: igc_rx_buffer_flip(rx_buffer, truesize); xdp_status |= xdp_res; break; } total_packets++; total_bytes += size; } else if (skb) igc_add_rx_frag(rx_ring, rx_buffer, skb, size); else if (ring_uses_build_skb(rx_ring)) skb = igc_build_skb(rx_ring, rx_buffer, &ctx.xdp); else skb = igc_construct_skb(rx_ring, rx_buffer, &ctx.xdp, timestamp); /* exit if we failed to retrieve a buffer */ if (!skb) { rx_ring->rx_stats.alloc_failed++; rx_buffer->pagecnt_bias++; break; } igc_put_rx_buffer(rx_ring, rx_buffer, rx_buffer_pgcnt); cleaned_count++; /* fetch next buffer in frame if non-eop */ if (igc_is_non_eop(rx_ring, rx_desc)) continue; /* verify the packet layout is correct */ if (igc_cleanup_headers(rx_ring, rx_desc, skb)) { skb = NULL; continue; } /* probably a little skewed due to removing CRC */ total_bytes += skb->len; /* populate checksum, VLAN, and protocol */ igc_process_skb_fields(rx_ring, rx_desc, skb); napi_gro_receive(&q_vector->napi, skb); /* reset skb pointer */ skb = NULL; /* update budget accounting */ total_packets++; } if (xdp_status) igc_finalize_xdp(adapter, xdp_status); /* place incomplete frames back on ring for completion */ rx_ring->skb = skb; igc_update_rx_stats(q_vector, total_packets, total_bytes); if (cleaned_count) igc_alloc_rx_buffers(rx_ring, cleaned_count); return total_packets; } static struct sk_buff *igc_construct_skb_zc(struct igc_ring *ring, struct xdp_buff *xdp) { unsigned int totalsize = xdp->data_end - xdp->data_meta; unsigned int metasize = xdp->data - xdp->data_meta; struct sk_buff *skb; net_prefetch(xdp->data_meta); skb = __napi_alloc_skb(&ring->q_vector->napi, totalsize, GFP_ATOMIC | __GFP_NOWARN); if (unlikely(!skb)) return NULL; memcpy(__skb_put(skb, totalsize), xdp->data_meta, ALIGN(totalsize, sizeof(long))); if (metasize) { skb_metadata_set(skb, metasize); __skb_pull(skb, metasize); } return skb; } static void igc_dispatch_skb_zc(struct igc_q_vector *q_vector, union igc_adv_rx_desc *desc, struct xdp_buff *xdp, ktime_t timestamp) { struct igc_ring *ring = q_vector->rx.ring; struct sk_buff *skb; skb = igc_construct_skb_zc(ring, xdp); if (!skb) { ring->rx_stats.alloc_failed++; return; } if (timestamp) skb_hwtstamps(skb)->hwtstamp = timestamp; if (igc_cleanup_headers(ring, desc, skb)) return; igc_process_skb_fields(ring, desc, skb); napi_gro_receive(&q_vector->napi, skb); } static struct igc_xdp_buff *xsk_buff_to_igc_ctx(struct xdp_buff *xdp) { /* xdp_buff pointer used by ZC code path is alloc as xdp_buff_xsk. The * igc_xdp_buff shares its layout with xdp_buff_xsk and private * igc_xdp_buff fields fall into xdp_buff_xsk->cb */ return (struct igc_xdp_buff *)xdp; } static int igc_clean_rx_irq_zc(struct igc_q_vector *q_vector, const int budget) { struct igc_adapter *adapter = q_vector->adapter; struct igc_ring *ring = q_vector->rx.ring; u16 cleaned_count = igc_desc_unused(ring); int total_bytes = 0, total_packets = 0; u16 ntc = ring->next_to_clean; struct bpf_prog *prog; bool failure = false; int xdp_status = 0; rcu_read_lock(); prog = READ_ONCE(adapter->xdp_prog); while (likely(total_packets < budget)) { union igc_adv_rx_desc *desc; struct igc_rx_buffer *bi; struct igc_xdp_buff *ctx; ktime_t timestamp = 0; unsigned int size; int res; desc = IGC_RX_DESC(ring, ntc); size = le16_to_cpu(desc->wb.upper.length); if (!size) break; /* This memory barrier is needed to keep us from reading * any other fields out of the rx_desc until we know the * descriptor has been written back */ dma_rmb(); bi = &ring->rx_buffer_info[ntc]; ctx = xsk_buff_to_igc_ctx(bi->xdp); ctx->rx_desc = desc; if (igc_test_staterr(desc, IGC_RXDADV_STAT_TSIP)) { timestamp = igc_ptp_rx_pktstamp(q_vector->adapter, bi->xdp->data); ctx->rx_ts = timestamp; bi->xdp->data += IGC_TS_HDR_LEN; /* HW timestamp has been copied into local variable. Metadata * length when XDP program is called should be 0. */ bi->xdp->data_meta += IGC_TS_HDR_LEN; size -= IGC_TS_HDR_LEN; } bi->xdp->data_end = bi->xdp->data + size; xsk_buff_dma_sync_for_cpu(bi->xdp, ring->xsk_pool); res = __igc_xdp_run_prog(adapter, prog, bi->xdp); switch (res) { case IGC_XDP_PASS: igc_dispatch_skb_zc(q_vector, desc, bi->xdp, timestamp); fallthrough; case IGC_XDP_CONSUMED: xsk_buff_free(bi->xdp); break; case IGC_XDP_TX: case IGC_XDP_REDIRECT: xdp_status |= res; break; } bi->xdp = NULL; total_bytes += size; total_packets++; cleaned_count++; ntc++; if (ntc == ring->count) ntc = 0; } ring->next_to_clean = ntc; rcu_read_unlock(); if (cleaned_count >= IGC_RX_BUFFER_WRITE) failure = !igc_alloc_rx_buffers_zc(ring, cleaned_count); if (xdp_status) igc_finalize_xdp(adapter, xdp_status); igc_update_rx_stats(q_vector, total_packets, total_bytes); if (xsk_uses_need_wakeup(ring->xsk_pool)) { if (failure || ring->next_to_clean == ring->next_to_use) xsk_set_rx_need_wakeup(ring->xsk_pool); else xsk_clear_rx_need_wakeup(ring->xsk_pool); return total_packets; } return failure ? budget : total_packets; } static void igc_update_tx_stats(struct igc_q_vector *q_vector, unsigned int packets, unsigned int bytes) { struct igc_ring *ring = q_vector->tx.ring; u64_stats_update_begin(&ring->tx_syncp); ring->tx_stats.bytes += bytes; ring->tx_stats.packets += packets; u64_stats_update_end(&ring->tx_syncp); q_vector->tx.total_bytes += bytes; q_vector->tx.total_packets += packets; } static void igc_xdp_xmit_zc(struct igc_ring *ring) { struct xsk_buff_pool *pool = ring->xsk_pool; struct netdev_queue *nq = txring_txq(ring); union igc_adv_tx_desc *tx_desc = NULL; int cpu = smp_processor_id(); struct xdp_desc xdp_desc; u16 budget, ntu; if (!netif_carrier_ok(ring->netdev)) return; __netif_tx_lock(nq, cpu); /* Avoid transmit queue timeout since we share it with the slow path */ txq_trans_cond_update(nq); ntu = ring->next_to_use; budget = igc_desc_unused(ring); while (xsk_tx_peek_desc(pool, &xdp_desc) && budget--) { u32 cmd_type, olinfo_status; struct igc_tx_buffer *bi; dma_addr_t dma; cmd_type = IGC_ADVTXD_DTYP_DATA | IGC_ADVTXD_DCMD_DEXT | IGC_ADVTXD_DCMD_IFCS | IGC_TXD_DCMD | xdp_desc.len; olinfo_status = xdp_desc.len << IGC_ADVTXD_PAYLEN_SHIFT; dma = xsk_buff_raw_get_dma(pool, xdp_desc.addr); xsk_buff_raw_dma_sync_for_device(pool, dma, xdp_desc.len); tx_desc = IGC_TX_DESC(ring, ntu); tx_desc->read.cmd_type_len = cpu_to_le32(cmd_type); tx_desc->read.olinfo_status = cpu_to_le32(olinfo_status); tx_desc->read.buffer_addr = cpu_to_le64(dma); bi = &ring->tx_buffer_info[ntu]; bi->type = IGC_TX_BUFFER_TYPE_XSK; bi->protocol = 0; bi->bytecount = xdp_desc.len; bi->gso_segs = 1; bi->time_stamp = jiffies; bi->next_to_watch = tx_desc; netdev_tx_sent_queue(txring_txq(ring), xdp_desc.len); ntu++; if (ntu == ring->count) ntu = 0; } ring->next_to_use = ntu; if (tx_desc) { igc_flush_tx_descriptors(ring); xsk_tx_release(pool); } __netif_tx_unlock(nq); } /** * igc_clean_tx_irq - Reclaim resources after transmit completes * @q_vector: pointer to q_vector containing needed info * @napi_budget: Used to determine if we are in netpoll * * returns true if ring is completely cleaned */ static bool igc_clean_tx_irq(struct igc_q_vector *q_vector, int napi_budget) { struct igc_adapter *adapter = q_vector->adapter; unsigned int total_bytes = 0, total_packets = 0; unsigned int budget = q_vector->tx.work_limit; struct igc_ring *tx_ring = q_vector->tx.ring; unsigned int i = tx_ring->next_to_clean; struct igc_tx_buffer *tx_buffer; union igc_adv_tx_desc *tx_desc; u32 xsk_frames = 0; if (test_bit(__IGC_DOWN, &adapter->state)) return true; tx_buffer = &tx_ring->tx_buffer_info[i]; tx_desc = IGC_TX_DESC(tx_ring, i); i -= tx_ring->count; do { union igc_adv_tx_desc *eop_desc = tx_buffer->next_to_watch; /* if next_to_watch is not set then there is no work pending */ if (!eop_desc) break; /* prevent any other reads prior to eop_desc */ smp_rmb(); /* if DD is not set pending work has not been completed */ if (!(eop_desc->wb.status & cpu_to_le32(IGC_TXD_STAT_DD))) break; /* clear next_to_watch to prevent false hangs */ tx_buffer->next_to_watch = NULL; /* update the statistics for this packet */ total_bytes += tx_buffer->bytecount; total_packets += tx_buffer->gso_segs; switch (tx_buffer->type) { case IGC_TX_BUFFER_TYPE_XSK: xsk_frames++; break; case IGC_TX_BUFFER_TYPE_XDP: xdp_return_frame(tx_buffer->xdpf); igc_unmap_tx_buffer(tx_ring->dev, tx_buffer); break; case IGC_TX_BUFFER_TYPE_SKB: napi_consume_skb(tx_buffer->skb, napi_budget); igc_unmap_tx_buffer(tx_ring->dev, tx_buffer); break; default: netdev_warn_once(tx_ring->netdev, "Unknown Tx buffer type\n"); break; } /* clear last DMA location and unmap remaining buffers */ while (tx_desc != eop_desc) { tx_buffer++; tx_desc++; i++; if (unlikely(!i)) { i -= tx_ring->count; tx_buffer = tx_ring->tx_buffer_info; tx_desc = IGC_TX_DESC(tx_ring, 0); } /* unmap any remaining paged data */ if (dma_unmap_len(tx_buffer, len)) igc_unmap_tx_buffer(tx_ring->dev, tx_buffer); } /* move us one more past the eop_desc for start of next pkt */ tx_buffer++; tx_desc++; i++; if (unlikely(!i)) { i -= tx_ring->count; tx_buffer = tx_ring->tx_buffer_info; tx_desc = IGC_TX_DESC(tx_ring, 0); } /* issue prefetch for next Tx descriptor */ prefetch(tx_desc); /* update budget accounting */ budget--; } while (likely(budget)); netdev_tx_completed_queue(txring_txq(tx_ring), total_packets, total_bytes); i += tx_ring->count; tx_ring->next_to_clean = i; igc_update_tx_stats(q_vector, total_packets, total_bytes); if (tx_ring->xsk_pool) { if (xsk_frames) xsk_tx_completed(tx_ring->xsk_pool, xsk_frames); if (xsk_uses_need_wakeup(tx_ring->xsk_pool)) xsk_set_tx_need_wakeup(tx_ring->xsk_pool); igc_xdp_xmit_zc(tx_ring); } if (test_bit(IGC_RING_FLAG_TX_DETECT_HANG, &tx_ring->flags)) { struct igc_hw *hw = &adapter->hw; /* Detect a transmit hang in hardware, this serializes the * check with the clearing of time_stamp and movement of i */ clear_bit(IGC_RING_FLAG_TX_DETECT_HANG, &tx_ring->flags); if (tx_buffer->next_to_watch && time_after(jiffies, tx_buffer->time_stamp + (adapter->tx_timeout_factor * HZ)) && !(rd32(IGC_STATUS) & IGC_STATUS_TXOFF) && (rd32(IGC_TDH(tx_ring->reg_idx)) != readl(tx_ring->tail)) && !tx_ring->oper_gate_closed) { /* detected Tx unit hang */ netdev_err(tx_ring->netdev, "Detected Tx Unit Hang\n" " Tx Queue <%d>\n" " TDH <%x>\n" " TDT <%x>\n" " next_to_use <%x>\n" " next_to_clean <%x>\n" "buffer_info[next_to_clean]\n" " time_stamp <%lx>\n" " next_to_watch <%p>\n" " jiffies <%lx>\n" " desc.status <%x>\n", tx_ring->queue_index, rd32(IGC_TDH(tx_ring->reg_idx)), readl(tx_ring->tail), tx_ring->next_to_use, tx_ring->next_to_clean, tx_buffer->time_stamp, tx_buffer->next_to_watch, jiffies, tx_buffer->next_to_watch->wb.status); netif_stop_subqueue(tx_ring->netdev, tx_ring->queue_index); /* we are about to reset, no point in enabling stuff */ return true; } } #define TX_WAKE_THRESHOLD (DESC_NEEDED * 2) if (unlikely(total_packets && netif_carrier_ok(tx_ring->netdev) && igc_desc_unused(tx_ring) >= TX_WAKE_THRESHOLD)) { /* Make sure that anybody stopping the queue after this * sees the new next_to_clean. */ smp_mb(); if (__netif_subqueue_stopped(tx_ring->netdev, tx_ring->queue_index) && !(test_bit(__IGC_DOWN, &adapter->state))) { netif_wake_subqueue(tx_ring->netdev, tx_ring->queue_index); u64_stats_update_begin(&tx_ring->tx_syncp); tx_ring->tx_stats.restart_queue++; u64_stats_update_end(&tx_ring->tx_syncp); } } return !!budget; } static int igc_find_mac_filter(struct igc_adapter *adapter, enum igc_mac_filter_type type, const u8 *addr) { struct igc_hw *hw = &adapter->hw; int max_entries = hw->mac.rar_entry_count; u32 ral, rah; int i; for (i = 0; i < max_entries; i++) { ral = rd32(IGC_RAL(i)); rah = rd32(IGC_RAH(i)); if (!(rah & IGC_RAH_AV)) continue; if (!!(rah & IGC_RAH_ASEL_SRC_ADDR) != type) continue; if ((rah & IGC_RAH_RAH_MASK) != le16_to_cpup((__le16 *)(addr + 4))) continue; if (ral != le32_to_cpup((__le32 *)(addr))) continue; return i; } return -1; } static int igc_get_avail_mac_filter_slot(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; int max_entries = hw->mac.rar_entry_count; u32 rah; int i; for (i = 0; i < max_entries; i++) { rah = rd32(IGC_RAH(i)); if (!(rah & IGC_RAH_AV)) return i; } return -1; } /** * igc_add_mac_filter() - Add MAC address filter * @adapter: Pointer to adapter where the filter should be added * @type: MAC address filter type (source or destination) * @addr: MAC address * @queue: If non-negative, queue assignment feature is enabled and frames * matching the filter are enqueued onto 'queue'. Otherwise, queue * assignment is disabled. * * Return: 0 in case of success, negative errno code otherwise. */ static int igc_add_mac_filter(struct igc_adapter *adapter, enum igc_mac_filter_type type, const u8 *addr, int queue) { struct net_device *dev = adapter->netdev; int index; index = igc_find_mac_filter(adapter, type, addr); if (index >= 0) goto update_filter; index = igc_get_avail_mac_filter_slot(adapter); if (index < 0) return -ENOSPC; netdev_dbg(dev, "Add MAC address filter: index %d type %s address %pM queue %d\n", index, type == IGC_MAC_FILTER_TYPE_DST ? "dst" : "src", addr, queue); update_filter: igc_set_mac_filter_hw(adapter, index, type, addr, queue); return 0; } /** * igc_del_mac_filter() - Delete MAC address filter * @adapter: Pointer to adapter where the filter should be deleted from * @type: MAC address filter type (source or destination) * @addr: MAC address */ static void igc_del_mac_filter(struct igc_adapter *adapter, enum igc_mac_filter_type type, const u8 *addr) { struct net_device *dev = adapter->netdev; int index; index = igc_find_mac_filter(adapter, type, addr); if (index < 0) return; if (index == 0) { /* If this is the default filter, we don't actually delete it. * We just reset to its default value i.e. disable queue * assignment. */ netdev_dbg(dev, "Disable default MAC filter queue assignment"); igc_set_mac_filter_hw(adapter, 0, type, addr, -1); } else { netdev_dbg(dev, "Delete MAC address filter: index %d type %s address %pM\n", index, type == IGC_MAC_FILTER_TYPE_DST ? "dst" : "src", addr); igc_clear_mac_filter_hw(adapter, index); } } /** * igc_add_vlan_prio_filter() - Add VLAN priority filter * @adapter: Pointer to adapter where the filter should be added * @prio: VLAN priority value * @queue: Queue number which matching frames are assigned to * * Return: 0 in case of success, negative errno code otherwise. */ static int igc_add_vlan_prio_filter(struct igc_adapter *adapter, int prio, int queue) { struct net_device *dev = adapter->netdev; struct igc_hw *hw = &adapter->hw; u32 vlanpqf; vlanpqf = rd32(IGC_VLANPQF); if (vlanpqf & IGC_VLANPQF_VALID(prio)) { netdev_dbg(dev, "VLAN priority filter already in use\n"); return -EEXIST; } vlanpqf |= IGC_VLANPQF_QSEL(prio, queue); vlanpqf |= IGC_VLANPQF_VALID(prio); wr32(IGC_VLANPQF, vlanpqf); netdev_dbg(dev, "Add VLAN priority filter: prio %d queue %d\n", prio, queue); return 0; } /** * igc_del_vlan_prio_filter() - Delete VLAN priority filter * @adapter: Pointer to adapter where the filter should be deleted from * @prio: VLAN priority value */ static void igc_del_vlan_prio_filter(struct igc_adapter *adapter, int prio) { struct igc_hw *hw = &adapter->hw; u32 vlanpqf; vlanpqf = rd32(IGC_VLANPQF); vlanpqf &= ~IGC_VLANPQF_VALID(prio); vlanpqf &= ~IGC_VLANPQF_QSEL(prio, IGC_VLANPQF_QUEUE_MASK); wr32(IGC_VLANPQF, vlanpqf); netdev_dbg(adapter->netdev, "Delete VLAN priority filter: prio %d\n", prio); } static int igc_get_avail_etype_filter_slot(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; int i; for (i = 0; i < MAX_ETYPE_FILTER; i++) { u32 etqf = rd32(IGC_ETQF(i)); if (!(etqf & IGC_ETQF_FILTER_ENABLE)) return i; } return -1; } /** * igc_add_etype_filter() - Add ethertype filter * @adapter: Pointer to adapter where the filter should be added * @etype: Ethertype value * @queue: If non-negative, queue assignment feature is enabled and frames * matching the filter are enqueued onto 'queue'. Otherwise, queue * assignment is disabled. * * Return: 0 in case of success, negative errno code otherwise. */ static int igc_add_etype_filter(struct igc_adapter *adapter, u16 etype, int queue) { struct igc_hw *hw = &adapter->hw; int index; u32 etqf; index = igc_get_avail_etype_filter_slot(adapter); if (index < 0) return -ENOSPC; etqf = rd32(IGC_ETQF(index)); etqf &= ~IGC_ETQF_ETYPE_MASK; etqf |= etype; if (queue >= 0) { etqf &= ~IGC_ETQF_QUEUE_MASK; etqf |= (queue << IGC_ETQF_QUEUE_SHIFT); etqf |= IGC_ETQF_QUEUE_ENABLE; } etqf |= IGC_ETQF_FILTER_ENABLE; wr32(IGC_ETQF(index), etqf); netdev_dbg(adapter->netdev, "Add ethertype filter: etype %04x queue %d\n", etype, queue); return 0; } static int igc_find_etype_filter(struct igc_adapter *adapter, u16 etype) { struct igc_hw *hw = &adapter->hw; int i; for (i = 0; i < MAX_ETYPE_FILTER; i++) { u32 etqf = rd32(IGC_ETQF(i)); if ((etqf & IGC_ETQF_ETYPE_MASK) == etype) return i; } return -1; } /** * igc_del_etype_filter() - Delete ethertype filter * @adapter: Pointer to adapter where the filter should be deleted from * @etype: Ethertype value */ static void igc_del_etype_filter(struct igc_adapter *adapter, u16 etype) { struct igc_hw *hw = &adapter->hw; int index; index = igc_find_etype_filter(adapter, etype); if (index < 0) return; wr32(IGC_ETQF(index), 0); netdev_dbg(adapter->netdev, "Delete ethertype filter: etype %04x\n", etype); } static int igc_flex_filter_select(struct igc_adapter *adapter, struct igc_flex_filter *input, u32 *fhft) { struct igc_hw *hw = &adapter->hw; u8 fhft_index; u32 fhftsl; if (input->index >= MAX_FLEX_FILTER) { dev_err(&adapter->pdev->dev, "Wrong Flex Filter index selected!\n"); return -EINVAL; } /* Indirect table select register */ fhftsl = rd32(IGC_FHFTSL); fhftsl &= ~IGC_FHFTSL_FTSL_MASK; switch (input->index) { case 0 ... 7: fhftsl |= 0x00; break; case 8 ... 15: fhftsl |= 0x01; break; case 16 ... 23: fhftsl |= 0x02; break; case 24 ... 31: fhftsl |= 0x03; break; } wr32(IGC_FHFTSL, fhftsl); /* Normalize index down to host table register */ fhft_index = input->index % 8; *fhft = (fhft_index < 4) ? IGC_FHFT(fhft_index) : IGC_FHFT_EXT(fhft_index - 4); return 0; } static int igc_write_flex_filter_ll(struct igc_adapter *adapter, struct igc_flex_filter *input) { struct device *dev = &adapter->pdev->dev; struct igc_hw *hw = &adapter->hw; u8 *data = input->data; u8 *mask = input->mask; u32 queuing; u32 fhft; u32 wufc; int ret; int i; /* Length has to be aligned to 8. Otherwise the filter will fail. Bail * out early to avoid surprises later. */ if (input->length % 8 != 0) { dev_err(dev, "The length of a flex filter has to be 8 byte aligned!\n"); return -EINVAL; } /* Select corresponding flex filter register and get base for host table. */ ret = igc_flex_filter_select(adapter, input, &fhft); if (ret) return ret; /* When adding a filter globally disable flex filter feature. That is * recommended within the datasheet. */ wufc = rd32(IGC_WUFC); wufc &= ~IGC_WUFC_FLEX_HQ; wr32(IGC_WUFC, wufc); /* Configure filter */ queuing = input->length & IGC_FHFT_LENGTH_MASK; queuing |= (input->rx_queue << IGC_FHFT_QUEUE_SHIFT) & IGC_FHFT_QUEUE_MASK; queuing |= (input->prio << IGC_FHFT_PRIO_SHIFT) & IGC_FHFT_PRIO_MASK; if (input->immediate_irq) queuing |= IGC_FHFT_IMM_INT; if (input->drop) queuing |= IGC_FHFT_DROP; wr32(fhft + 0xFC, queuing); /* Write data (128 byte) and mask (128 bit) */ for (i = 0; i < 16; ++i) { const size_t data_idx = i * 8; const size_t row_idx = i * 16; u32 dw0 = (data[data_idx + 0] << 0) | (data[data_idx + 1] << 8) | (data[data_idx + 2] << 16) | (data[data_idx + 3] << 24); u32 dw1 = (data[data_idx + 4] << 0) | (data[data_idx + 5] << 8) | (data[data_idx + 6] << 16) | (data[data_idx + 7] << 24); u32 tmp; /* Write row: dw0, dw1 and mask */ wr32(fhft + row_idx, dw0); wr32(fhft + row_idx + 4, dw1); /* mask is only valid for MASK(7, 0) */ tmp = rd32(fhft + row_idx + 8); tmp &= ~GENMASK(7, 0); tmp |= mask[i]; wr32(fhft + row_idx + 8, tmp); } /* Enable filter. */ wufc |= IGC_WUFC_FLEX_HQ; if (input->index > 8) { /* Filter 0-7 are enabled via WUFC. The other 24 filters are not. */ u32 wufc_ext = rd32(IGC_WUFC_EXT); wufc_ext |= (IGC_WUFC_EXT_FLX8 << (input->index - 8)); wr32(IGC_WUFC_EXT, wufc_ext); } else { wufc |= (IGC_WUFC_FLX0 << input->index); } wr32(IGC_WUFC, wufc); dev_dbg(&adapter->pdev->dev, "Added flex filter %u to HW.\n", input->index); return 0; } static void igc_flex_filter_add_field(struct igc_flex_filter *flex, const void *src, unsigned int offset, size_t len, const void *mask) { int i; /* data */ memcpy(&flex->data[offset], src, len); /* mask */ for (i = 0; i < len; ++i) { const unsigned int idx = i + offset; const u8 *ptr = mask; if (mask) { if (ptr[i] & 0xff) flex->mask[idx / 8] |= BIT(idx % 8); continue; } flex->mask[idx / 8] |= BIT(idx % 8); } } static int igc_find_avail_flex_filter_slot(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; u32 wufc, wufc_ext; int i; wufc = rd32(IGC_WUFC); wufc_ext = rd32(IGC_WUFC_EXT); for (i = 0; i < MAX_FLEX_FILTER; i++) { if (i < 8) { if (!(wufc & (IGC_WUFC_FLX0 << i))) return i; } else { if (!(wufc_ext & (IGC_WUFC_EXT_FLX8 << (i - 8)))) return i; } } return -ENOSPC; } static bool igc_flex_filter_in_use(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; u32 wufc, wufc_ext; wufc = rd32(IGC_WUFC); wufc_ext = rd32(IGC_WUFC_EXT); if (wufc & IGC_WUFC_FILTER_MASK) return true; if (wufc_ext & IGC_WUFC_EXT_FILTER_MASK) return true; return false; } static int igc_add_flex_filter(struct igc_adapter *adapter, struct igc_nfc_rule *rule) { struct igc_flex_filter flex = { }; struct igc_nfc_filter *filter = &rule->filter; unsigned int eth_offset, user_offset; int ret, index; bool vlan; index = igc_find_avail_flex_filter_slot(adapter); if (index < 0) return -ENOSPC; /* Construct the flex filter: * -> dest_mac [6] * -> src_mac [6] * -> tpid [2] * -> vlan tci [2] * -> ether type [2] * -> user data [8] * -> = 26 bytes => 32 length */ flex.index = index; flex.length = 32; flex.rx_queue = rule->action; vlan = rule->filter.vlan_tci || rule->filter.vlan_etype; eth_offset = vlan ? 16 : 12; user_offset = vlan ? 18 : 14; /* Add destination MAC */ if (rule->filter.match_flags & IGC_FILTER_FLAG_DST_MAC_ADDR) igc_flex_filter_add_field(&flex, &filter->dst_addr, 0, ETH_ALEN, NULL); /* Add source MAC */ if (rule->filter.match_flags & IGC_FILTER_FLAG_SRC_MAC_ADDR) igc_flex_filter_add_field(&flex, &filter->src_addr, 6, ETH_ALEN, NULL); /* Add VLAN etype */ if (rule->filter.match_flags & IGC_FILTER_FLAG_VLAN_ETYPE) igc_flex_filter_add_field(&flex, &filter->vlan_etype, 12, sizeof(filter->vlan_etype), NULL); /* Add VLAN TCI */ if (rule->filter.match_flags & IGC_FILTER_FLAG_VLAN_TCI) igc_flex_filter_add_field(&flex, &filter->vlan_tci, 14, sizeof(filter->vlan_tci), NULL); /* Add Ether type */ if (rule->filter.match_flags & IGC_FILTER_FLAG_ETHER_TYPE) { __be16 etype = cpu_to_be16(filter->etype); igc_flex_filter_add_field(&flex, &etype, eth_offset, sizeof(etype), NULL); } /* Add user data */ if (rule->filter.match_flags & IGC_FILTER_FLAG_USER_DATA) igc_flex_filter_add_field(&flex, &filter->user_data, user_offset, sizeof(filter->user_data), filter->user_mask); /* Add it down to the hardware and enable it. */ ret = igc_write_flex_filter_ll(adapter, &flex); if (ret) return ret; filter->flex_index = index; return 0; } static void igc_del_flex_filter(struct igc_adapter *adapter, u16 reg_index) { struct igc_hw *hw = &adapter->hw; u32 wufc; /* Just disable the filter. The filter table itself is kept * intact. Another flex_filter_add() should override the "old" data * then. */ if (reg_index > 8) { u32 wufc_ext = rd32(IGC_WUFC_EXT); wufc_ext &= ~(IGC_WUFC_EXT_FLX8 << (reg_index - 8)); wr32(IGC_WUFC_EXT, wufc_ext); } else { wufc = rd32(IGC_WUFC); wufc &= ~(IGC_WUFC_FLX0 << reg_index); wr32(IGC_WUFC, wufc); } if (igc_flex_filter_in_use(adapter)) return; /* No filters are in use, we may disable flex filters */ wufc = rd32(IGC_WUFC); wufc &= ~IGC_WUFC_FLEX_HQ; wr32(IGC_WUFC, wufc); } static int igc_enable_nfc_rule(struct igc_adapter *adapter, struct igc_nfc_rule *rule) { int err; if (rule->flex) { return igc_add_flex_filter(adapter, rule); } if (rule->filter.match_flags & IGC_FILTER_FLAG_ETHER_TYPE) { err = igc_add_etype_filter(adapter, rule->filter.etype, rule->action); if (err) return err; } if (rule->filter.match_flags & IGC_FILTER_FLAG_SRC_MAC_ADDR) { err = igc_add_mac_filter(adapter, IGC_MAC_FILTER_TYPE_SRC, rule->filter.src_addr, rule->action); if (err) return err; } if (rule->filter.match_flags & IGC_FILTER_FLAG_DST_MAC_ADDR) { err = igc_add_mac_filter(adapter, IGC_MAC_FILTER_TYPE_DST, rule->filter.dst_addr, rule->action); if (err) return err; } if (rule->filter.match_flags & IGC_FILTER_FLAG_VLAN_TCI) { int prio = (rule->filter.vlan_tci & VLAN_PRIO_MASK) >> VLAN_PRIO_SHIFT; err = igc_add_vlan_prio_filter(adapter, prio, rule->action); if (err) return err; } return 0; } static void igc_disable_nfc_rule(struct igc_adapter *adapter, const struct igc_nfc_rule *rule) { if (rule->flex) { igc_del_flex_filter(adapter, rule->filter.flex_index); return; } if (rule->filter.match_flags & IGC_FILTER_FLAG_ETHER_TYPE) igc_del_etype_filter(adapter, rule->filter.etype); if (rule->filter.match_flags & IGC_FILTER_FLAG_VLAN_TCI) { int prio = (rule->filter.vlan_tci & VLAN_PRIO_MASK) >> VLAN_PRIO_SHIFT; igc_del_vlan_prio_filter(adapter, prio); } if (rule->filter.match_flags & IGC_FILTER_FLAG_SRC_MAC_ADDR) igc_del_mac_filter(adapter, IGC_MAC_FILTER_TYPE_SRC, rule->filter.src_addr); if (rule->filter.match_flags & IGC_FILTER_FLAG_DST_MAC_ADDR) igc_del_mac_filter(adapter, IGC_MAC_FILTER_TYPE_DST, rule->filter.dst_addr); } /** * igc_get_nfc_rule() - Get NFC rule * @adapter: Pointer to adapter * @location: Rule location * * Context: Expects adapter->nfc_rule_lock to be held by caller. * * Return: Pointer to NFC rule at @location. If not found, NULL. */ struct igc_nfc_rule *igc_get_nfc_rule(struct igc_adapter *adapter, u32 location) { struct igc_nfc_rule *rule; list_for_each_entry(rule, &adapter->nfc_rule_list, list) { if (rule->location == location) return rule; if (rule->location > location) break; } return NULL; } /** * igc_del_nfc_rule() - Delete NFC rule * @adapter: Pointer to adapter * @rule: Pointer to rule to be deleted * * Disable NFC rule in hardware and delete it from adapter. * * Context: Expects adapter->nfc_rule_lock to be held by caller. */ void igc_del_nfc_rule(struct igc_adapter *adapter, struct igc_nfc_rule *rule) { igc_disable_nfc_rule(adapter, rule); list_del(&rule->list); adapter->nfc_rule_count--; kfree(rule); } static void igc_flush_nfc_rules(struct igc_adapter *adapter) { struct igc_nfc_rule *rule, *tmp; mutex_lock(&adapter->nfc_rule_lock); list_for_each_entry_safe(rule, tmp, &adapter->nfc_rule_list, list) igc_del_nfc_rule(adapter, rule); mutex_unlock(&adapter->nfc_rule_lock); } /** * igc_add_nfc_rule() - Add NFC rule * @adapter: Pointer to adapter * @rule: Pointer to rule to be added * * Enable NFC rule in hardware and add it to adapter. * * Context: Expects adapter->nfc_rule_lock to be held by caller. * * Return: 0 on success, negative errno on failure. */ int igc_add_nfc_rule(struct igc_adapter *adapter, struct igc_nfc_rule *rule) { struct igc_nfc_rule *pred, *cur; int err; err = igc_enable_nfc_rule(adapter, rule); if (err) return err; pred = NULL; list_for_each_entry(cur, &adapter->nfc_rule_list, list) { if (cur->location >= rule->location) break; pred = cur; } list_add(&rule->list, pred ? &pred->list : &adapter->nfc_rule_list); adapter->nfc_rule_count++; return 0; } static void igc_restore_nfc_rules(struct igc_adapter *adapter) { struct igc_nfc_rule *rule; mutex_lock(&adapter->nfc_rule_lock); list_for_each_entry_reverse(rule, &adapter->nfc_rule_list, list) igc_enable_nfc_rule(adapter, rule); mutex_unlock(&adapter->nfc_rule_lock); } static int igc_uc_sync(struct net_device *netdev, const unsigned char *addr) { struct igc_adapter *adapter = netdev_priv(netdev); return igc_add_mac_filter(adapter, IGC_MAC_FILTER_TYPE_DST, addr, -1); } static int igc_uc_unsync(struct net_device *netdev, const unsigned char *addr) { struct igc_adapter *adapter = netdev_priv(netdev); igc_del_mac_filter(adapter, IGC_MAC_FILTER_TYPE_DST, addr); return 0; } /** * igc_set_rx_mode - Secondary Unicast, Multicast and Promiscuous mode set * @netdev: network interface device structure * * The set_rx_mode entry point is called whenever the unicast or multicast * address lists or the network interface flags are updated. This routine is * responsible for configuring the hardware for proper unicast, multicast, * promiscuous mode, and all-multi behavior. */ static void igc_set_rx_mode(struct net_device *netdev) { struct igc_adapter *adapter = netdev_priv(netdev); struct igc_hw *hw = &adapter->hw; u32 rctl = 0, rlpml = MAX_JUMBO_FRAME_SIZE; int count; /* Check for Promiscuous and All Multicast modes */ if (netdev->flags & IFF_PROMISC) { rctl |= IGC_RCTL_UPE | IGC_RCTL_MPE; } else { if (netdev->flags & IFF_ALLMULTI) { rctl |= IGC_RCTL_MPE; } else { /* Write addresses to the MTA, if the attempt fails * then we should just turn on promiscuous mode so * that we can at least receive multicast traffic */ count = igc_write_mc_addr_list(netdev); if (count < 0) rctl |= IGC_RCTL_MPE; } } /* Write addresses to available RAR registers, if there is not * sufficient space to store all the addresses then enable * unicast promiscuous mode */ if (__dev_uc_sync(netdev, igc_uc_sync, igc_uc_unsync)) rctl |= IGC_RCTL_UPE; /* update state of unicast and multicast */ rctl |= rd32(IGC_RCTL) & ~(IGC_RCTL_UPE | IGC_RCTL_MPE); wr32(IGC_RCTL, rctl); #if (PAGE_SIZE < 8192) if (adapter->max_frame_size <= IGC_MAX_FRAME_BUILD_SKB) rlpml = IGC_MAX_FRAME_BUILD_SKB; #endif wr32(IGC_RLPML, rlpml); } /** * igc_configure - configure the hardware for RX and TX * @adapter: private board structure */ static void igc_configure(struct igc_adapter *adapter) { struct net_device *netdev = adapter->netdev; int i = 0; igc_get_hw_control(adapter); igc_set_rx_mode(netdev); igc_restore_vlan(adapter); igc_setup_tctl(adapter); igc_setup_mrqc(adapter); igc_setup_rctl(adapter); igc_set_default_mac_filter(adapter); igc_restore_nfc_rules(adapter); igc_configure_tx(adapter); igc_configure_rx(adapter); igc_rx_fifo_flush_base(&adapter->hw); /* call igc_desc_unused which always leaves * at least 1 descriptor unused to make sure * next_to_use != next_to_clean */ for (i = 0; i < adapter->num_rx_queues; i++) { struct igc_ring *ring = adapter->rx_ring[i]; if (ring->xsk_pool) igc_alloc_rx_buffers_zc(ring, igc_desc_unused(ring)); else igc_alloc_rx_buffers(ring, igc_desc_unused(ring)); } } /** * igc_write_ivar - configure ivar for given MSI-X vector * @hw: pointer to the HW structure * @msix_vector: vector number we are allocating to a given ring * @index: row index of IVAR register to write within IVAR table * @offset: column offset of in IVAR, should be multiple of 8 * * The IVAR table consists of 2 columns, * each containing an cause allocation for an Rx and Tx ring, and a * variable number of rows depending on the number of queues supported. */ static void igc_write_ivar(struct igc_hw *hw, int msix_vector, int index, int offset) { u32 ivar = array_rd32(IGC_IVAR0, index); /* clear any bits that are currently set */ ivar &= ~((u32)0xFF << offset); /* write vector and valid bit */ ivar |= (msix_vector | IGC_IVAR_VALID) << offset; array_wr32(IGC_IVAR0, index, ivar); } static void igc_assign_vector(struct igc_q_vector *q_vector, int msix_vector) { struct igc_adapter *adapter = q_vector->adapter; struct igc_hw *hw = &adapter->hw; int rx_queue = IGC_N0_QUEUE; int tx_queue = IGC_N0_QUEUE; if (q_vector->rx.ring) rx_queue = q_vector->rx.ring->reg_idx; if (q_vector->tx.ring) tx_queue = q_vector->tx.ring->reg_idx; switch (hw->mac.type) { case igc_i225: if (rx_queue > IGC_N0_QUEUE) igc_write_ivar(hw, msix_vector, rx_queue >> 1, (rx_queue & 0x1) << 4); if (tx_queue > IGC_N0_QUEUE) igc_write_ivar(hw, msix_vector, tx_queue >> 1, ((tx_queue & 0x1) << 4) + 8); q_vector->eims_value = BIT(msix_vector); break; default: WARN_ONCE(hw->mac.type != igc_i225, "Wrong MAC type\n"); break; } /* add q_vector eims value to global eims_enable_mask */ adapter->eims_enable_mask |= q_vector->eims_value; /* configure q_vector to set itr on first interrupt */ q_vector->set_itr = 1; } /** * igc_configure_msix - Configure MSI-X hardware * @adapter: Pointer to adapter structure * * igc_configure_msix sets up the hardware to properly * generate MSI-X interrupts. */ static void igc_configure_msix(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; int i, vector = 0; u32 tmp; adapter->eims_enable_mask = 0; /* set vector for other causes, i.e. link changes */ switch (hw->mac.type) { case igc_i225: /* Turn on MSI-X capability first, or our settings * won't stick. And it will take days to debug. */ wr32(IGC_GPIE, IGC_GPIE_MSIX_MODE | IGC_GPIE_PBA | IGC_GPIE_EIAME | IGC_GPIE_NSICR); /* enable msix_other interrupt */ adapter->eims_other = BIT(vector); tmp = (vector++ | IGC_IVAR_VALID) << 8; wr32(IGC_IVAR_MISC, tmp); break; default: /* do nothing, since nothing else supports MSI-X */ break; } /* switch (hw->mac.type) */ adapter->eims_enable_mask |= adapter->eims_other; for (i = 0; i < adapter->num_q_vectors; i++) igc_assign_vector(adapter->q_vector[i], vector++); wrfl(); } /** * igc_irq_enable - Enable default interrupt generation settings * @adapter: board private structure */ static void igc_irq_enable(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; if (adapter->msix_entries) { u32 ims = IGC_IMS_LSC | IGC_IMS_DOUTSYNC | IGC_IMS_DRSTA; u32 regval = rd32(IGC_EIAC); wr32(IGC_EIAC, regval | adapter->eims_enable_mask); regval = rd32(IGC_EIAM); wr32(IGC_EIAM, regval | adapter->eims_enable_mask); wr32(IGC_EIMS, adapter->eims_enable_mask); wr32(IGC_IMS, ims); } else { wr32(IGC_IMS, IMS_ENABLE_MASK | IGC_IMS_DRSTA); wr32(IGC_IAM, IMS_ENABLE_MASK | IGC_IMS_DRSTA); } } /** * igc_irq_disable - Mask off interrupt generation on the NIC * @adapter: board private structure */ static void igc_irq_disable(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; if (adapter->msix_entries) { u32 regval = rd32(IGC_EIAM); wr32(IGC_EIAM, regval & ~adapter->eims_enable_mask); wr32(IGC_EIMC, adapter->eims_enable_mask); regval = rd32(IGC_EIAC); wr32(IGC_EIAC, regval & ~adapter->eims_enable_mask); } wr32(IGC_IAM, 0); wr32(IGC_IMC, ~0); wrfl(); if (adapter->msix_entries) { int vector = 0, i; synchronize_irq(adapter->msix_entries[vector++].vector); for (i = 0; i < adapter->num_q_vectors; i++) synchronize_irq(adapter->msix_entries[vector++].vector); } else { synchronize_irq(adapter->pdev->irq); } } void igc_set_flag_queue_pairs(struct igc_adapter *adapter, const u32 max_rss_queues) { /* Determine if we need to pair queues. */ /* If rss_queues > half of max_rss_queues, pair the queues in * order to conserve interrupts due to limited supply. */ if (adapter->rss_queues > (max_rss_queues / 2)) adapter->flags |= IGC_FLAG_QUEUE_PAIRS; else adapter->flags &= ~IGC_FLAG_QUEUE_PAIRS; } unsigned int igc_get_max_rss_queues(struct igc_adapter *adapter) { return IGC_MAX_RX_QUEUES; } static void igc_init_queue_configuration(struct igc_adapter *adapter) { u32 max_rss_queues; max_rss_queues = igc_get_max_rss_queues(adapter); adapter->rss_queues = min_t(u32, max_rss_queues, num_online_cpus()); igc_set_flag_queue_pairs(adapter, max_rss_queues); } /** * igc_reset_q_vector - Reset config for interrupt vector * @adapter: board private structure to initialize * @v_idx: Index of vector to be reset * * If NAPI is enabled it will delete any references to the * NAPI struct. This is preparation for igc_free_q_vector. */ static void igc_reset_q_vector(struct igc_adapter *adapter, int v_idx) { struct igc_q_vector *q_vector = adapter->q_vector[v_idx]; /* if we're coming from igc_set_interrupt_capability, the vectors are * not yet allocated */ if (!q_vector) return; if (q_vector->tx.ring) adapter->tx_ring[q_vector->tx.ring->queue_index] = NULL; if (q_vector->rx.ring) adapter->rx_ring[q_vector->rx.ring->queue_index] = NULL; netif_napi_del(&q_vector->napi); } /** * igc_free_q_vector - Free memory allocated for specific interrupt vector * @adapter: board private structure to initialize * @v_idx: Index of vector to be freed * * This function frees the memory allocated to the q_vector. */ static void igc_free_q_vector(struct igc_adapter *adapter, int v_idx) { struct igc_q_vector *q_vector = adapter->q_vector[v_idx]; adapter->q_vector[v_idx] = NULL; /* igc_get_stats64() might access the rings on this vector, * we must wait a grace period before freeing it. */ if (q_vector) kfree_rcu(q_vector, rcu); } /** * igc_free_q_vectors - Free memory allocated for interrupt vectors * @adapter: board private structure to initialize * * This function frees the memory allocated to the q_vectors. In addition if * NAPI is enabled it will delete any references to the NAPI struct prior * to freeing the q_vector. */ static void igc_free_q_vectors(struct igc_adapter *adapter) { int v_idx = adapter->num_q_vectors; adapter->num_tx_queues = 0; adapter->num_rx_queues = 0; adapter->num_q_vectors = 0; while (v_idx--) { igc_reset_q_vector(adapter, v_idx); igc_free_q_vector(adapter, v_idx); } } /** * igc_update_itr - update the dynamic ITR value based on statistics * @q_vector: pointer to q_vector * @ring_container: ring info to update the itr for * * Stores a new ITR value based on packets and byte * counts during the last interrupt. The advantage of per interrupt * computation is faster updates and more accurate ITR for the current * traffic pattern. Constants in this function were computed * based on theoretical maximum wire speed and thresholds were set based * on testing data as well as attempting to minimize response time * while increasing bulk throughput. * NOTE: These calculations are only valid when operating in a single- * queue environment. */ static void igc_update_itr(struct igc_q_vector *q_vector, struct igc_ring_container *ring_container) { unsigned int packets = ring_container->total_packets; unsigned int bytes = ring_container->total_bytes; u8 itrval = ring_container->itr; /* no packets, exit with status unchanged */ if (packets == 0) return; switch (itrval) { case lowest_latency: /* handle TSO and jumbo frames */ if (bytes / packets > 8000) itrval = bulk_latency; else if ((packets < 5) && (bytes > 512)) itrval = low_latency; break; case low_latency: /* 50 usec aka 20000 ints/s */ if (bytes > 10000) { /* this if handles the TSO accounting */ if (bytes / packets > 8000) itrval = bulk_latency; else if ((packets < 10) || ((bytes / packets) > 1200)) itrval = bulk_latency; else if ((packets > 35)) itrval = lowest_latency; } else if (bytes / packets > 2000) { itrval = bulk_latency; } else if (packets <= 2 && bytes < 512) { itrval = lowest_latency; } break; case bulk_latency: /* 250 usec aka 4000 ints/s */ if (bytes > 25000) { if (packets > 35) itrval = low_latency; } else if (bytes < 1500) { itrval = low_latency; } break; } /* clear work counters since we have the values we need */ ring_container->total_bytes = 0; ring_container->total_packets = 0; /* write updated itr to ring container */ ring_container->itr = itrval; } static void igc_set_itr(struct igc_q_vector *q_vector) { struct igc_adapter *adapter = q_vector->adapter; u32 new_itr = q_vector->itr_val; u8 current_itr = 0; /* for non-gigabit speeds, just fix the interrupt rate at 4000 */ switch (adapter->link_speed) { case SPEED_10: case SPEED_100: current_itr = 0; new_itr = IGC_4K_ITR; goto set_itr_now; default: break; } igc_update_itr(q_vector, &q_vector->tx); igc_update_itr(q_vector, &q_vector->rx); current_itr = max(q_vector->rx.itr, q_vector->tx.itr); /* conservative mode (itr 3) eliminates the lowest_latency setting */ if (current_itr == lowest_latency && ((q_vector->rx.ring && adapter->rx_itr_setting == 3) || (!q_vector->rx.ring && adapter->tx_itr_setting == 3))) current_itr = low_latency; switch (current_itr) { /* counts and packets in update_itr are dependent on these numbers */ case lowest_latency: new_itr = IGC_70K_ITR; /* 70,000 ints/sec */ break; case low_latency: new_itr = IGC_20K_ITR; /* 20,000 ints/sec */ break; case bulk_latency: new_itr = IGC_4K_ITR; /* 4,000 ints/sec */ break; default: break; } set_itr_now: if (new_itr != q_vector->itr_val) { /* this attempts to bias the interrupt rate towards Bulk * by adding intermediate steps when interrupt rate is * increasing */ new_itr = new_itr > q_vector->itr_val ? max((new_itr * q_vector->itr_val) / (new_itr + (q_vector->itr_val >> 2)), new_itr) : new_itr; /* Don't write the value here; it resets the adapter's * internal timer, and causes us to delay far longer than * we should between interrupts. Instead, we write the ITR * value at the beginning of the next interrupt so the timing * ends up being correct. */ q_vector->itr_val = new_itr; q_vector->set_itr = 1; } } static void igc_reset_interrupt_capability(struct igc_adapter *adapter) { int v_idx = adapter->num_q_vectors; if (adapter->msix_entries) { pci_disable_msix(adapter->pdev); kfree(adapter->msix_entries); adapter->msix_entries = NULL; } else if (adapter->flags & IGC_FLAG_HAS_MSI) { pci_disable_msi(adapter->pdev); } while (v_idx--) igc_reset_q_vector(adapter, v_idx); } /** * igc_set_interrupt_capability - set MSI or MSI-X if supported * @adapter: Pointer to adapter structure * @msix: boolean value for MSI-X capability * * Attempt to configure interrupts using the best available * capabilities of the hardware and kernel. */ static void igc_set_interrupt_capability(struct igc_adapter *adapter, bool msix) { int numvecs, i; int err; if (!msix) goto msi_only; adapter->flags |= IGC_FLAG_HAS_MSIX; /* Number of supported queues. */ adapter->num_rx_queues = adapter->rss_queues; adapter->num_tx_queues = adapter->rss_queues; /* start with one vector for every Rx queue */ numvecs = adapter->num_rx_queues; /* if Tx handler is separate add 1 for every Tx queue */ if (!(adapter->flags & IGC_FLAG_QUEUE_PAIRS)) numvecs += adapter->num_tx_queues; /* store the number of vectors reserved for queues */ adapter->num_q_vectors = numvecs; /* add 1 vector for link status interrupts */ numvecs++; adapter->msix_entries = kcalloc(numvecs, sizeof(struct msix_entry), GFP_KERNEL); if (!adapter->msix_entries) return; /* populate entry values */ for (i = 0; i < numvecs; i++) adapter->msix_entries[i].entry = i; err = pci_enable_msix_range(adapter->pdev, adapter->msix_entries, numvecs, numvecs); if (err > 0) return; kfree(adapter->msix_entries); adapter->msix_entries = NULL; igc_reset_interrupt_capability(adapter); msi_only: adapter->flags &= ~IGC_FLAG_HAS_MSIX; adapter->rss_queues = 1; adapter->flags |= IGC_FLAG_QUEUE_PAIRS; adapter->num_rx_queues = 1; adapter->num_tx_queues = 1; adapter->num_q_vectors = 1; if (!pci_enable_msi(adapter->pdev)) adapter->flags |= IGC_FLAG_HAS_MSI; } /** * igc_update_ring_itr - update the dynamic ITR value based on packet size * @q_vector: pointer to q_vector * * Stores a new ITR value based on strictly on packet size. This * algorithm is less sophisticated than that used in igc_update_itr, * due to the difficulty of synchronizing statistics across multiple * receive rings. The divisors and thresholds used by this function * were determined based on theoretical maximum wire speed and testing * data, in order to minimize response time while increasing bulk * throughput. * NOTE: This function is called only when operating in a multiqueue * receive environment. */ static void igc_update_ring_itr(struct igc_q_vector *q_vector) { struct igc_adapter *adapter = q_vector->adapter; int new_val = q_vector->itr_val; int avg_wire_size = 0; unsigned int packets; /* For non-gigabit speeds, just fix the interrupt rate at 4000 * ints/sec - ITR timer value of 120 ticks. */ switch (adapter->link_speed) { case SPEED_10: case SPEED_100: new_val = IGC_4K_ITR; goto set_itr_val; default: break; } packets = q_vector->rx.total_packets; if (packets) avg_wire_size = q_vector->rx.total_bytes / packets; packets = q_vector->tx.total_packets; if (packets) avg_wire_size = max_t(u32, avg_wire_size, q_vector->tx.total_bytes / packets); /* if avg_wire_size isn't set no work was done */ if (!avg_wire_size) goto clear_counts; /* Add 24 bytes to size to account for CRC, preamble, and gap */ avg_wire_size += 24; /* Don't starve jumbo frames */ avg_wire_size = min(avg_wire_size, 3000); /* Give a little boost to mid-size frames */ if (avg_wire_size > 300 && avg_wire_size < 1200) new_val = avg_wire_size / 3; else new_val = avg_wire_size / 2; /* conservative mode (itr 3) eliminates the lowest_latency setting */ if (new_val < IGC_20K_ITR && ((q_vector->rx.ring && adapter->rx_itr_setting == 3) || (!q_vector->rx.ring && adapter->tx_itr_setting == 3))) new_val = IGC_20K_ITR; set_itr_val: if (new_val != q_vector->itr_val) { q_vector->itr_val = new_val; q_vector->set_itr = 1; } clear_counts: q_vector->rx.total_bytes = 0; q_vector->rx.total_packets = 0; q_vector->tx.total_bytes = 0; q_vector->tx.total_packets = 0; } static void igc_ring_irq_enable(struct igc_q_vector *q_vector) { struct igc_adapter *adapter = q_vector->adapter; struct igc_hw *hw = &adapter->hw; if ((q_vector->rx.ring && (adapter->rx_itr_setting & 3)) || (!q_vector->rx.ring && (adapter->tx_itr_setting & 3))) { if (adapter->num_q_vectors == 1) igc_set_itr(q_vector); else igc_update_ring_itr(q_vector); } if (!test_bit(__IGC_DOWN, &adapter->state)) { if (adapter->msix_entries) wr32(IGC_EIMS, q_vector->eims_value); else igc_irq_enable(adapter); } } static void igc_add_ring(struct igc_ring *ring, struct igc_ring_container *head) { head->ring = ring; head->count++; } /** * igc_cache_ring_register - Descriptor ring to register mapping * @adapter: board private structure to initialize * * Once we know the feature-set enabled for the device, we'll cache * the register offset the descriptor ring is assigned to. */ static void igc_cache_ring_register(struct igc_adapter *adapter) { int i = 0, j = 0; switch (adapter->hw.mac.type) { case igc_i225: default: for (; i < adapter->num_rx_queues; i++) adapter->rx_ring[i]->reg_idx = i; for (; j < adapter->num_tx_queues; j++) adapter->tx_ring[j]->reg_idx = j; break; } } /** * igc_poll - NAPI Rx polling callback * @napi: napi polling structure * @budget: count of how many packets we should handle */ static int igc_poll(struct napi_struct *napi, int budget) { struct igc_q_vector *q_vector = container_of(napi, struct igc_q_vector, napi); struct igc_ring *rx_ring = q_vector->rx.ring; bool clean_complete = true; int work_done = 0; if (q_vector->tx.ring) clean_complete = igc_clean_tx_irq(q_vector, budget); if (rx_ring) { int cleaned = rx_ring->xsk_pool ? igc_clean_rx_irq_zc(q_vector, budget) : igc_clean_rx_irq(q_vector, budget); work_done += cleaned; if (cleaned >= budget) clean_complete = false; } /* If all work not completed, return budget and keep polling */ if (!clean_complete) return budget; /* Exit the polling mode, but don't re-enable interrupts if stack might * poll us due to busy-polling */ if (likely(napi_complete_done(napi, work_done))) igc_ring_irq_enable(q_vector); return min(work_done, budget - 1); } /** * igc_alloc_q_vector - Allocate memory for a single interrupt vector * @adapter: board private structure to initialize * @v_count: q_vectors allocated on adapter, used for ring interleaving * @v_idx: index of vector in adapter struct * @txr_count: total number of Tx rings to allocate * @txr_idx: index of first Tx ring to allocate * @rxr_count: total number of Rx rings to allocate * @rxr_idx: index of first Rx ring to allocate * * We allocate one q_vector. If allocation fails we return -ENOMEM. */ static int igc_alloc_q_vector(struct igc_adapter *adapter, unsigned int v_count, unsigned int v_idx, unsigned int txr_count, unsigned int txr_idx, unsigned int rxr_count, unsigned int rxr_idx) { struct igc_q_vector *q_vector; struct igc_ring *ring; int ring_count; /* igc only supports 1 Tx and/or 1 Rx queue per vector */ if (txr_count > 1 || rxr_count > 1) return -ENOMEM; ring_count = txr_count + rxr_count; /* allocate q_vector and rings */ q_vector = adapter->q_vector[v_idx]; if (!q_vector) q_vector = kzalloc(struct_size(q_vector, ring, ring_count), GFP_KERNEL); else memset(q_vector, 0, struct_size(q_vector, ring, ring_count)); if (!q_vector) return -ENOMEM; /* initialize NAPI */ netif_napi_add(adapter->netdev, &q_vector->napi, igc_poll); /* tie q_vector and adapter together */ adapter->q_vector[v_idx] = q_vector; q_vector->adapter = adapter; /* initialize work limits */ q_vector->tx.work_limit = adapter->tx_work_limit; /* initialize ITR configuration */ q_vector->itr_register = adapter->io_addr + IGC_EITR(0); q_vector->itr_val = IGC_START_ITR; /* initialize pointer to rings */ ring = q_vector->ring; /* initialize ITR */ if (rxr_count) { /* rx or rx/tx vector */ if (!adapter->rx_itr_setting || adapter->rx_itr_setting > 3) q_vector->itr_val = adapter->rx_itr_setting; } else { /* tx only vector */ if (!adapter->tx_itr_setting || adapter->tx_itr_setting > 3) q_vector->itr_val = adapter->tx_itr_setting; } if (txr_count) { /* assign generic ring traits */ ring->dev = &adapter->pdev->dev; ring->netdev = adapter->netdev; /* configure backlink on ring */ ring->q_vector = q_vector; /* update q_vector Tx values */ igc_add_ring(ring, &q_vector->tx); /* apply Tx specific ring traits */ ring->count = adapter->tx_ring_count; ring->queue_index = txr_idx; /* assign ring to adapter */ adapter->tx_ring[txr_idx] = ring; /* push pointer to next ring */ ring++; } if (rxr_count) { /* assign generic ring traits */ ring->dev = &adapter->pdev->dev; ring->netdev = adapter->netdev; /* configure backlink on ring */ ring->q_vector = q_vector; /* update q_vector Rx values */ igc_add_ring(ring, &q_vector->rx); /* apply Rx specific ring traits */ ring->count = adapter->rx_ring_count; ring->queue_index = rxr_idx; /* assign ring to adapter */ adapter->rx_ring[rxr_idx] = ring; } return 0; } /** * igc_alloc_q_vectors - Allocate memory for interrupt vectors * @adapter: board private structure to initialize * * We allocate one q_vector per queue interrupt. If allocation fails we * return -ENOMEM. */ static int igc_alloc_q_vectors(struct igc_adapter *adapter) { int rxr_remaining = adapter->num_rx_queues; int txr_remaining = adapter->num_tx_queues; int rxr_idx = 0, txr_idx = 0, v_idx = 0; int q_vectors = adapter->num_q_vectors; int err; if (q_vectors >= (rxr_remaining + txr_remaining)) { for (; rxr_remaining; v_idx++) { err = igc_alloc_q_vector(adapter, q_vectors, v_idx, 0, 0, 1, rxr_idx); if (err) goto err_out; /* update counts and index */ rxr_remaining--; rxr_idx++; } } for (; v_idx < q_vectors; v_idx++) { int rqpv = DIV_ROUND_UP(rxr_remaining, q_vectors - v_idx); int tqpv = DIV_ROUND_UP(txr_remaining, q_vectors - v_idx); err = igc_alloc_q_vector(adapter, q_vectors, v_idx, tqpv, txr_idx, rqpv, rxr_idx); if (err) goto err_out; /* update counts and index */ rxr_remaining -= rqpv; txr_remaining -= tqpv; rxr_idx++; txr_idx++; } return 0; err_out: adapter->num_tx_queues = 0; adapter->num_rx_queues = 0; adapter->num_q_vectors = 0; while (v_idx--) igc_free_q_vector(adapter, v_idx); return -ENOMEM; } /** * igc_init_interrupt_scheme - initialize interrupts, allocate queues/vectors * @adapter: Pointer to adapter structure * @msix: boolean for MSI-X capability * * This function initializes the interrupts and allocates all of the queues. */ static int igc_init_interrupt_scheme(struct igc_adapter *adapter, bool msix) { struct net_device *dev = adapter->netdev; int err = 0; igc_set_interrupt_capability(adapter, msix); err = igc_alloc_q_vectors(adapter); if (err) { netdev_err(dev, "Unable to allocate memory for vectors\n"); goto err_alloc_q_vectors; } igc_cache_ring_register(adapter); return 0; err_alloc_q_vectors: igc_reset_interrupt_capability(adapter); return err; } /** * igc_sw_init - Initialize general software structures (struct igc_adapter) * @adapter: board private structure to initialize * * igc_sw_init initializes the Adapter private data structure. * Fields are initialized based on PCI device information and * OS network device settings (MTU size). */ static int igc_sw_init(struct igc_adapter *adapter) { struct net_device *netdev = adapter->netdev; struct pci_dev *pdev = adapter->pdev; struct igc_hw *hw = &adapter->hw; pci_read_config_word(pdev, PCI_COMMAND, &hw->bus.pci_cmd_word); /* set default ring sizes */ adapter->tx_ring_count = IGC_DEFAULT_TXD; adapter->rx_ring_count = IGC_DEFAULT_RXD; /* set default ITR values */ adapter->rx_itr_setting = IGC_DEFAULT_ITR; adapter->tx_itr_setting = IGC_DEFAULT_ITR; /* set default work limits */ adapter->tx_work_limit = IGC_DEFAULT_TX_WORK; /* adjust max frame to be at least the size of a standard frame */ adapter->max_frame_size = netdev->mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN; adapter->min_frame_size = ETH_ZLEN + ETH_FCS_LEN; mutex_init(&adapter->nfc_rule_lock); INIT_LIST_HEAD(&adapter->nfc_rule_list); adapter->nfc_rule_count = 0; spin_lock_init(&adapter->stats64_lock); spin_lock_init(&adapter->qbv_tx_lock); /* Assume MSI-X interrupts, will be checked during IRQ allocation */ adapter->flags |= IGC_FLAG_HAS_MSIX; igc_init_queue_configuration(adapter); /* This call may decrease the number of queues */ if (igc_init_interrupt_scheme(adapter, true)) { netdev_err(netdev, "Unable to allocate memory for queues\n"); return -ENOMEM; } /* Explicitly disable IRQ since the NIC can be in any state. */ igc_irq_disable(adapter); set_bit(__IGC_DOWN, &adapter->state); return 0; } /** * igc_up - Open the interface and prepare it to handle traffic * @adapter: board private structure */ void igc_up(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; int i = 0; /* hardware has been reset, we need to reload some things */ igc_configure(adapter); clear_bit(__IGC_DOWN, &adapter->state); for (i = 0; i < adapter->num_q_vectors; i++) napi_enable(&adapter->q_vector[i]->napi); if (adapter->msix_entries) igc_configure_msix(adapter); else igc_assign_vector(adapter->q_vector[0], 0); /* Clear any pending interrupts. */ rd32(IGC_ICR); igc_irq_enable(adapter); netif_tx_start_all_queues(adapter->netdev); /* start the watchdog. */ hw->mac.get_link_status = true; schedule_work(&adapter->watchdog_task); } /** * igc_update_stats - Update the board statistics counters * @adapter: board private structure */ void igc_update_stats(struct igc_adapter *adapter) { struct rtnl_link_stats64 *net_stats = &adapter->stats64; struct pci_dev *pdev = adapter->pdev; struct igc_hw *hw = &adapter->hw; u64 _bytes, _packets; u64 bytes, packets; unsigned int start; u32 mpc; int i; /* Prevent stats update while adapter is being reset, or if the pci * connection is down. */ if (adapter->link_speed == 0) return; if (pci_channel_offline(pdev)) return; packets = 0; bytes = 0; rcu_read_lock(); for (i = 0; i < adapter->num_rx_queues; i++) { struct igc_ring *ring = adapter->rx_ring[i]; u32 rqdpc = rd32(IGC_RQDPC(i)); if (hw->mac.type >= igc_i225) wr32(IGC_RQDPC(i), 0); if (rqdpc) { ring->rx_stats.drops += rqdpc; net_stats->rx_fifo_errors += rqdpc; } do { start = u64_stats_fetch_begin(&ring->rx_syncp); _bytes = ring->rx_stats.bytes; _packets = ring->rx_stats.packets; } while (u64_stats_fetch_retry(&ring->rx_syncp, start)); bytes += _bytes; packets += _packets; } net_stats->rx_bytes = bytes; net_stats->rx_packets = packets; packets = 0; bytes = 0; for (i = 0; i < adapter->num_tx_queues; i++) { struct igc_ring *ring = adapter->tx_ring[i]; do { start = u64_stats_fetch_begin(&ring->tx_syncp); _bytes = ring->tx_stats.bytes; _packets = ring->tx_stats.packets; } while (u64_stats_fetch_retry(&ring->tx_syncp, start)); bytes += _bytes; packets += _packets; } net_stats->tx_bytes = bytes; net_stats->tx_packets = packets; rcu_read_unlock(); /* read stats registers */ adapter->stats.crcerrs += rd32(IGC_CRCERRS); adapter->stats.gprc += rd32(IGC_GPRC); adapter->stats.gorc += rd32(IGC_GORCL); rd32(IGC_GORCH); /* clear GORCL */ adapter->stats.bprc += rd32(IGC_BPRC); adapter->stats.mprc += rd32(IGC_MPRC); adapter->stats.roc += rd32(IGC_ROC); adapter->stats.prc64 += rd32(IGC_PRC64); adapter->stats.prc127 += rd32(IGC_PRC127); adapter->stats.prc255 += rd32(IGC_PRC255); adapter->stats.prc511 += rd32(IGC_PRC511); adapter->stats.prc1023 += rd32(IGC_PRC1023); adapter->stats.prc1522 += rd32(IGC_PRC1522); adapter->stats.tlpic += rd32(IGC_TLPIC); adapter->stats.rlpic += rd32(IGC_RLPIC); adapter->stats.hgptc += rd32(IGC_HGPTC); mpc = rd32(IGC_MPC); adapter->stats.mpc += mpc; net_stats->rx_fifo_errors += mpc; adapter->stats.scc += rd32(IGC_SCC); adapter->stats.ecol += rd32(IGC_ECOL); adapter->stats.mcc += rd32(IGC_MCC); adapter->stats.latecol += rd32(IGC_LATECOL); adapter->stats.dc += rd32(IGC_DC); adapter->stats.rlec += rd32(IGC_RLEC); adapter->stats.xonrxc += rd32(IGC_XONRXC); adapter->stats.xontxc += rd32(IGC_XONTXC); adapter->stats.xoffrxc += rd32(IGC_XOFFRXC); adapter->stats.xofftxc += rd32(IGC_XOFFTXC); adapter->stats.fcruc += rd32(IGC_FCRUC); adapter->stats.gptc += rd32(IGC_GPTC); adapter->stats.gotc += rd32(IGC_GOTCL); rd32(IGC_GOTCH); /* clear GOTCL */ adapter->stats.rnbc += rd32(IGC_RNBC); adapter->stats.ruc += rd32(IGC_RUC); adapter->stats.rfc += rd32(IGC_RFC); adapter->stats.rjc += rd32(IGC_RJC); adapter->stats.tor += rd32(IGC_TORH); adapter->stats.tot += rd32(IGC_TOTH); adapter->stats.tpr += rd32(IGC_TPR); adapter->stats.ptc64 += rd32(IGC_PTC64); adapter->stats.ptc127 += rd32(IGC_PTC127); adapter->stats.ptc255 += rd32(IGC_PTC255); adapter->stats.ptc511 += rd32(IGC_PTC511); adapter->stats.ptc1023 += rd32(IGC_PTC1023); adapter->stats.ptc1522 += rd32(IGC_PTC1522); adapter->stats.mptc += rd32(IGC_MPTC); adapter->stats.bptc += rd32(IGC_BPTC); adapter->stats.tpt += rd32(IGC_TPT); adapter->stats.colc += rd32(IGC_COLC); adapter->stats.colc += rd32(IGC_RERC); adapter->stats.algnerrc += rd32(IGC_ALGNERRC); adapter->stats.tsctc += rd32(IGC_TSCTC); adapter->stats.iac += rd32(IGC_IAC); /* Fill out the OS statistics structure */ net_stats->multicast = adapter->stats.mprc; net_stats->collisions = adapter->stats.colc; /* Rx Errors */ /* RLEC on some newer hardware can be incorrect so build * our own version based on RUC and ROC */ net_stats->rx_errors = adapter->stats.rxerrc + adapter->stats.crcerrs + adapter->stats.algnerrc + adapter->stats.ruc + adapter->stats.roc + adapter->stats.cexterr; net_stats->rx_length_errors = adapter->stats.ruc + adapter->stats.roc; net_stats->rx_crc_errors = adapter->stats.crcerrs; net_stats->rx_frame_errors = adapter->stats.algnerrc; net_stats->rx_missed_errors = adapter->stats.mpc; /* Tx Errors */ net_stats->tx_errors = adapter->stats.ecol + adapter->stats.latecol; net_stats->tx_aborted_errors = adapter->stats.ecol; net_stats->tx_window_errors = adapter->stats.latecol; net_stats->tx_carrier_errors = adapter->stats.tncrs; /* Tx Dropped */ net_stats->tx_dropped = adapter->stats.txdrop; /* Management Stats */ adapter->stats.mgptc += rd32(IGC_MGTPTC); adapter->stats.mgprc += rd32(IGC_MGTPRC); adapter->stats.mgpdc += rd32(IGC_MGTPDC); } /** * igc_down - Close the interface * @adapter: board private structure */ void igc_down(struct igc_adapter *adapter) { struct net_device *netdev = adapter->netdev; struct igc_hw *hw = &adapter->hw; u32 tctl, rctl; int i = 0; set_bit(__IGC_DOWN, &adapter->state); igc_ptp_suspend(adapter); if (pci_device_is_present(adapter->pdev)) { /* disable receives in the hardware */ rctl = rd32(IGC_RCTL); wr32(IGC_RCTL, rctl & ~IGC_RCTL_EN); /* flush and sleep below */ } /* set trans_start so we don't get spurious watchdogs during reset */ netif_trans_update(netdev); netif_carrier_off(netdev); netif_tx_stop_all_queues(netdev); if (pci_device_is_present(adapter->pdev)) { /* disable transmits in the hardware */ tctl = rd32(IGC_TCTL); tctl &= ~IGC_TCTL_EN; wr32(IGC_TCTL, tctl); /* flush both disables and wait for them to finish */ wrfl(); usleep_range(10000, 20000); igc_irq_disable(adapter); } adapter->flags &= ~IGC_FLAG_NEED_LINK_UPDATE; for (i = 0; i < adapter->num_q_vectors; i++) { if (adapter->q_vector[i]) { napi_synchronize(&adapter->q_vector[i]->napi); napi_disable(&adapter->q_vector[i]->napi); } } del_timer_sync(&adapter->watchdog_timer); del_timer_sync(&adapter->phy_info_timer); /* record the stats before reset*/ spin_lock(&adapter->stats64_lock); igc_update_stats(adapter); spin_unlock(&adapter->stats64_lock); adapter->link_speed = 0; adapter->link_duplex = 0; if (!pci_channel_offline(adapter->pdev)) igc_reset(adapter); /* clear VLAN promisc flag so VFTA will be updated if necessary */ adapter->flags &= ~IGC_FLAG_VLAN_PROMISC; igc_disable_all_tx_rings_hw(adapter); igc_clean_all_tx_rings(adapter); igc_clean_all_rx_rings(adapter); } void igc_reinit_locked(struct igc_adapter *adapter) { while (test_and_set_bit(__IGC_RESETTING, &adapter->state)) usleep_range(1000, 2000); igc_down(adapter); igc_up(adapter); clear_bit(__IGC_RESETTING, &adapter->state); } static void igc_reset_task(struct work_struct *work) { struct igc_adapter *adapter; adapter = container_of(work, struct igc_adapter, reset_task); rtnl_lock(); /* If we're already down or resetting, just bail */ if (test_bit(__IGC_DOWN, &adapter->state) || test_bit(__IGC_RESETTING, &adapter->state)) { rtnl_unlock(); return; } igc_rings_dump(adapter); igc_regs_dump(adapter); netdev_err(adapter->netdev, "Reset adapter\n"); igc_reinit_locked(adapter); rtnl_unlock(); } /** * igc_change_mtu - Change the Maximum Transfer Unit * @netdev: network interface device structure * @new_mtu: new value for maximum frame size * * Returns 0 on success, negative on failure */ static int igc_change_mtu(struct net_device *netdev, int new_mtu) { int max_frame = new_mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN; struct igc_adapter *adapter = netdev_priv(netdev); if (igc_xdp_is_enabled(adapter) && new_mtu > ETH_DATA_LEN) { netdev_dbg(netdev, "Jumbo frames not supported with XDP"); return -EINVAL; } /* adjust max frame to be at least the size of a standard frame */ if (max_frame < (ETH_FRAME_LEN + ETH_FCS_LEN)) max_frame = ETH_FRAME_LEN + ETH_FCS_LEN; while (test_and_set_bit(__IGC_RESETTING, &adapter->state)) usleep_range(1000, 2000); /* igc_down has a dependency on max_frame_size */ adapter->max_frame_size = max_frame; if (netif_running(netdev)) igc_down(adapter); netdev_dbg(netdev, "changing MTU from %d to %d\n", netdev->mtu, new_mtu); netdev->mtu = new_mtu; if (netif_running(netdev)) igc_up(adapter); else igc_reset(adapter); clear_bit(__IGC_RESETTING, &adapter->state); return 0; } /** * igc_tx_timeout - Respond to a Tx Hang * @netdev: network interface device structure * @txqueue: queue number that timed out **/ static void igc_tx_timeout(struct net_device *netdev, unsigned int __always_unused txqueue) { struct igc_adapter *adapter = netdev_priv(netdev); struct igc_hw *hw = &adapter->hw; /* Do the reset outside of interrupt context */ adapter->tx_timeout_count++; schedule_work(&adapter->reset_task); wr32(IGC_EICS, (adapter->eims_enable_mask & ~adapter->eims_other)); } /** * igc_get_stats64 - Get System Network Statistics * @netdev: network interface device structure * @stats: rtnl_link_stats64 pointer * * Returns the address of the device statistics structure. * The statistics are updated here and also from the timer callback. */ static void igc_get_stats64(struct net_device *netdev, struct rtnl_link_stats64 *stats) { struct igc_adapter *adapter = netdev_priv(netdev); spin_lock(&adapter->stats64_lock); if (!test_bit(__IGC_RESETTING, &adapter->state)) igc_update_stats(adapter); memcpy(stats, &adapter->stats64, sizeof(*stats)); spin_unlock(&adapter->stats64_lock); } static netdev_features_t igc_fix_features(struct net_device *netdev, netdev_features_t features) { /* Since there is no support for separate Rx/Tx vlan accel * enable/disable make sure Tx flag is always in same state as Rx. */ if (features & NETIF_F_HW_VLAN_CTAG_RX) features |= NETIF_F_HW_VLAN_CTAG_TX; else features &= ~NETIF_F_HW_VLAN_CTAG_TX; return features; } static int igc_set_features(struct net_device *netdev, netdev_features_t features) { netdev_features_t changed = netdev->features ^ features; struct igc_adapter *adapter = netdev_priv(netdev); if (changed & NETIF_F_HW_VLAN_CTAG_RX) igc_vlan_mode(netdev, features); /* Add VLAN support */ if (!(changed & (NETIF_F_RXALL | NETIF_F_NTUPLE))) return 0; if (!(features & NETIF_F_NTUPLE)) igc_flush_nfc_rules(adapter); netdev->features = features; if (netif_running(netdev)) igc_reinit_locked(adapter); else igc_reset(adapter); return 1; } static netdev_features_t igc_features_check(struct sk_buff *skb, struct net_device *dev, netdev_features_t features) { unsigned int network_hdr_len, mac_hdr_len; /* Make certain the headers can be described by a context descriptor */ mac_hdr_len = skb_network_header(skb) - skb->data; if (unlikely(mac_hdr_len > IGC_MAX_MAC_HDR_LEN)) return features & ~(NETIF_F_HW_CSUM | NETIF_F_SCTP_CRC | NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_TSO | NETIF_F_TSO6); network_hdr_len = skb_checksum_start(skb) - skb_network_header(skb); if (unlikely(network_hdr_len > IGC_MAX_NETWORK_HDR_LEN)) return features & ~(NETIF_F_HW_CSUM | NETIF_F_SCTP_CRC | NETIF_F_TSO | NETIF_F_TSO6); /* We can only support IPv4 TSO in tunnels if we can mangle the * inner IP ID field, so strip TSO if MANGLEID is not supported. */ if (skb->encapsulation && !(features & NETIF_F_TSO_MANGLEID)) features &= ~NETIF_F_TSO; return features; } static void igc_tsync_interrupt(struct igc_adapter *adapter) { u32 ack, tsauxc, sec, nsec, tsicr; struct igc_hw *hw = &adapter->hw; struct ptp_clock_event event; struct timespec64 ts; tsicr = rd32(IGC_TSICR); ack = 0; if (tsicr & IGC_TSICR_SYS_WRAP) { event.type = PTP_CLOCK_PPS; if (adapter->ptp_caps.pps) ptp_clock_event(adapter->ptp_clock, &event); ack |= IGC_TSICR_SYS_WRAP; } if (tsicr & IGC_TSICR_TXTS) { /* retrieve hardware timestamp */ igc_ptp_tx_tstamp_event(adapter); ack |= IGC_TSICR_TXTS; } if (tsicr & IGC_TSICR_TT0) { spin_lock(&adapter->tmreg_lock); ts = timespec64_add(adapter->perout[0].start, adapter->perout[0].period); wr32(IGC_TRGTTIML0, ts.tv_nsec | IGC_TT_IO_TIMER_SEL_SYSTIM0); wr32(IGC_TRGTTIMH0, (u32)ts.tv_sec); tsauxc = rd32(IGC_TSAUXC); tsauxc |= IGC_TSAUXC_EN_TT0; wr32(IGC_TSAUXC, tsauxc); adapter->perout[0].start = ts; spin_unlock(&adapter->tmreg_lock); ack |= IGC_TSICR_TT0; } if (tsicr & IGC_TSICR_TT1) { spin_lock(&adapter->tmreg_lock); ts = timespec64_add(adapter->perout[1].start, adapter->perout[1].period); wr32(IGC_TRGTTIML1, ts.tv_nsec | IGC_TT_IO_TIMER_SEL_SYSTIM0); wr32(IGC_TRGTTIMH1, (u32)ts.tv_sec); tsauxc = rd32(IGC_TSAUXC); tsauxc |= IGC_TSAUXC_EN_TT1; wr32(IGC_TSAUXC, tsauxc); adapter->perout[1].start = ts; spin_unlock(&adapter->tmreg_lock); ack |= IGC_TSICR_TT1; } if (tsicr & IGC_TSICR_AUTT0) { nsec = rd32(IGC_AUXSTMPL0); sec = rd32(IGC_AUXSTMPH0); event.type = PTP_CLOCK_EXTTS; event.index = 0; event.timestamp = sec * NSEC_PER_SEC + nsec; ptp_clock_event(adapter->ptp_clock, &event); ack |= IGC_TSICR_AUTT0; } if (tsicr & IGC_TSICR_AUTT1) { nsec = rd32(IGC_AUXSTMPL1); sec = rd32(IGC_AUXSTMPH1); event.type = PTP_CLOCK_EXTTS; event.index = 1; event.timestamp = sec * NSEC_PER_SEC + nsec; ptp_clock_event(adapter->ptp_clock, &event); ack |= IGC_TSICR_AUTT1; } /* acknowledge the interrupts */ wr32(IGC_TSICR, ack); } /** * igc_msix_other - msix other interrupt handler * @irq: interrupt number * @data: pointer to a q_vector */ static irqreturn_t igc_msix_other(int irq, void *data) { struct igc_adapter *adapter = data; struct igc_hw *hw = &adapter->hw; u32 icr = rd32(IGC_ICR); /* reading ICR causes bit 31 of EICR to be cleared */ if (icr & IGC_ICR_DRSTA) schedule_work(&adapter->reset_task); if (icr & IGC_ICR_DOUTSYNC) { /* HW is reporting DMA is out of sync */ adapter->stats.doosync++; } if (icr & IGC_ICR_LSC) { hw->mac.get_link_status = true; /* guard against interrupt when we're going down */ if (!test_bit(__IGC_DOWN, &adapter->state)) mod_timer(&adapter->watchdog_timer, jiffies + 1); } if (icr & IGC_ICR_TS) igc_tsync_interrupt(adapter); wr32(IGC_EIMS, adapter->eims_other); return IRQ_HANDLED; } static void igc_write_itr(struct igc_q_vector *q_vector) { u32 itr_val = q_vector->itr_val & IGC_QVECTOR_MASK; if (!q_vector->set_itr) return; if (!itr_val) itr_val = IGC_ITR_VAL_MASK; itr_val |= IGC_EITR_CNT_IGNR; writel(itr_val, q_vector->itr_register); q_vector->set_itr = 0; } static irqreturn_t igc_msix_ring(int irq, void *data) { struct igc_q_vector *q_vector = data; /* Write the ITR value calculated from the previous interrupt. */ igc_write_itr(q_vector); napi_schedule(&q_vector->napi); return IRQ_HANDLED; } /** * igc_request_msix - Initialize MSI-X interrupts * @adapter: Pointer to adapter structure * * igc_request_msix allocates MSI-X vectors and requests interrupts from the * kernel. */ static int igc_request_msix(struct igc_adapter *adapter) { unsigned int num_q_vectors = adapter->num_q_vectors; int i = 0, err = 0, vector = 0, free_vector = 0; struct net_device *netdev = adapter->netdev; err = request_irq(adapter->msix_entries[vector].vector, &igc_msix_other, 0, netdev->name, adapter); if (err) goto err_out; if (num_q_vectors > MAX_Q_VECTORS) { num_q_vectors = MAX_Q_VECTORS; dev_warn(&adapter->pdev->dev, "The number of queue vectors (%d) is higher than max allowed (%d)\n", adapter->num_q_vectors, MAX_Q_VECTORS); } for (i = 0; i < num_q_vectors; i++) { struct igc_q_vector *q_vector = adapter->q_vector[i]; vector++; q_vector->itr_register = adapter->io_addr + IGC_EITR(vector); if (q_vector->rx.ring && q_vector->tx.ring) sprintf(q_vector->name, "%s-TxRx-%u", netdev->name, q_vector->rx.ring->queue_index); else if (q_vector->tx.ring) sprintf(q_vector->name, "%s-tx-%u", netdev->name, q_vector->tx.ring->queue_index); else if (q_vector->rx.ring) sprintf(q_vector->name, "%s-rx-%u", netdev->name, q_vector->rx.ring->queue_index); else sprintf(q_vector->name, "%s-unused", netdev->name); err = request_irq(adapter->msix_entries[vector].vector, igc_msix_ring, 0, q_vector->name, q_vector); if (err) goto err_free; } igc_configure_msix(adapter); return 0; err_free: /* free already assigned IRQs */ free_irq(adapter->msix_entries[free_vector++].vector, adapter); vector--; for (i = 0; i < vector; i++) { free_irq(adapter->msix_entries[free_vector++].vector, adapter->q_vector[i]); } err_out: return err; } /** * igc_clear_interrupt_scheme - reset the device to a state of no interrupts * @adapter: Pointer to adapter structure * * This function resets the device so that it has 0 rx queues, tx queues, and * MSI-X interrupts allocated. */ static void igc_clear_interrupt_scheme(struct igc_adapter *adapter) { igc_free_q_vectors(adapter); igc_reset_interrupt_capability(adapter); } /* Need to wait a few seconds after link up to get diagnostic information from * the phy */ static void igc_update_phy_info(struct timer_list *t) { struct igc_adapter *adapter = from_timer(adapter, t, phy_info_timer); igc_get_phy_info(&adapter->hw); } /** * igc_has_link - check shared code for link and determine up/down * @adapter: pointer to driver private info */ bool igc_has_link(struct igc_adapter *adapter) { struct igc_hw *hw = &adapter->hw; bool link_active = false; /* get_link_status is set on LSC (link status) interrupt or * rx sequence error interrupt. get_link_status will stay * false until the igc_check_for_link establishes link * for copper adapters ONLY */ if (!hw->mac.get_link_status) return true; hw->mac.ops.check_for_link(hw); link_active = !hw->mac.get_link_status; if (hw->mac.type == igc_i225) { if (!netif_carrier_ok(adapter->netdev)) { adapter->flags &= ~IGC_FLAG_NEED_LINK_UPDATE; } else if (!(adapter->flags & IGC_FLAG_NEED_LINK_UPDATE)) { adapter->flags |= IGC_FLAG_NEED_LINK_UPDATE; adapter->link_check_timeout = jiffies; } } return link_active; } /** * igc_watchdog - Timer Call-back * @t: timer for the watchdog */ static void igc_watchdog(struct timer_list *t) { struct igc_adapter *adapter = from_timer(adapter, t, watchdog_timer); /* Do the rest outside of interrupt context */ schedule_work(&adapter->watchdog_task); } static void igc_watchdog_task(struct work_struct *work) { struct igc_adapter *adapter = container_of(work, struct igc_adapter, watchdog_task); struct net_device *netdev = adapter->netdev; struct igc_hw *hw = &adapter->hw; struct igc_phy_info *phy = &hw->phy; u16 phy_data, retry_count = 20; u32 link; int i; link = igc_has_link(adapter); if (adapter->flags & IGC_FLAG_NEED_LINK_UPDATE) { if (time_after(jiffies, (adapter->link_check_timeout + HZ))) adapter->flags &= ~IGC_FLAG_NEED_LINK_UPDATE; else link = false; } if (link) { /* Cancel scheduled suspend requests. */ pm_runtime_resume(netdev->dev.parent); if (!netif_carrier_ok(netdev)) { u32 ctrl; hw->mac.ops.get_speed_and_duplex(hw, &adapter->link_speed, &adapter->link_duplex); ctrl = rd32(IGC_CTRL); /* Link status message must follow this format */ netdev_info(netdev, "NIC Link is Up %d Mbps %s Duplex, Flow Control: %s\n", adapter->link_speed, adapter->link_duplex == FULL_DUPLEX ? "Full" : "Half", (ctrl & IGC_CTRL_TFCE) && (ctrl & IGC_CTRL_RFCE) ? "RX/TX" : (ctrl & IGC_CTRL_RFCE) ? "RX" : (ctrl & IGC_CTRL_TFCE) ? "TX" : "None"); /* disable EEE if enabled */ if ((adapter->flags & IGC_FLAG_EEE) && adapter->link_duplex == HALF_DUPLEX) { netdev_info(netdev, "EEE Disabled: unsupported at half duplex. Re-enable using ethtool when at full duplex\n"); adapter->hw.dev_spec._base.eee_enable = false; adapter->flags &= ~IGC_FLAG_EEE; } /* check if SmartSpeed worked */ igc_check_downshift(hw); if (phy->speed_downgraded) netdev_warn(netdev, "Link Speed was downgraded by SmartSpeed\n"); /* adjust timeout factor according to speed/duplex */ adapter->tx_timeout_factor = 1; switch (adapter->link_speed) { case SPEED_10: adapter->tx_timeout_factor = 14; break; case SPEED_100: case SPEED_1000: case SPEED_2500: adapter->tx_timeout_factor = 1; break; } /* Once the launch time has been set on the wire, there * is a delay before the link speed can be determined * based on link-up activity. Write into the register * as soon as we know the correct link speed. */ igc_tsn_adjust_txtime_offset(adapter); if (adapter->link_speed != SPEED_1000) goto no_wait; /* wait for Remote receiver status OK */ retry_read_status: if (!igc_read_phy_reg(hw, PHY_1000T_STATUS, &phy_data)) { if (!(phy_data & SR_1000T_REMOTE_RX_STATUS) && retry_count) { msleep(100); retry_count--; goto retry_read_status; } else if (!retry_count) { netdev_err(netdev, "exceed max 2 second\n"); } } else { netdev_err(netdev, "read 1000Base-T Status Reg\n"); } no_wait: netif_carrier_on(netdev); /* link state has changed, schedule phy info update */ if (!test_bit(__IGC_DOWN, &adapter->state)) mod_timer(&adapter->phy_info_timer, round_jiffies(jiffies + 2 * HZ)); } } else { if (netif_carrier_ok(netdev)) { adapter->link_speed = 0; adapter->link_duplex = 0; /* Links status message must follow this format */ netdev_info(netdev, "NIC Link is Down\n"); netif_carrier_off(netdev); /* link state has changed, schedule phy info update */ if (!test_bit(__IGC_DOWN, &adapter->state)) mod_timer(&adapter->phy_info_timer, round_jiffies(jiffies + 2 * HZ)); pm_schedule_suspend(netdev->dev.parent, MSEC_PER_SEC * 5); } } spin_lock(&adapter->stats64_lock); igc_update_stats(adapter); spin_unlock(&adapter->stats64_lock); for (i = 0; i < adapter->num_tx_queues; i++) { struct igc_ring *tx_ring = adapter->tx_ring[i]; if (!netif_carrier_ok(netdev)) { /* We've lost link, so the controller stops DMA, * but we've got queued Tx work that's never going * to get done, so reset controller to flush Tx. * (Do the reset outside of interrupt context). */ if (igc_desc_unused(tx_ring) + 1 < tx_ring->count) { adapter->tx_timeout_count++; schedule_work(&adapter->reset_task); /* return immediately since reset is imminent */ return; } } /* Force detection of hung controller every watchdog period */ set_bit(IGC_RING_FLAG_TX_DETECT_HANG, &tx_ring->flags); } /* Cause software interrupt to ensure Rx ring is cleaned */ if (adapter->flags & IGC_FLAG_HAS_MSIX) { u32 eics = 0; for (i = 0; i < adapter->num_q_vectors; i++) eics |= adapter->q_vector[i]->eims_value; wr32(IGC_EICS, eics); } else { wr32(IGC_ICS, IGC_ICS_RXDMT0); } igc_ptp_tx_hang(adapter); /* Reset the timer */ if (!test_bit(__IGC_DOWN, &adapter->state)) { if (adapter->flags & IGC_FLAG_NEED_LINK_UPDATE) mod_timer(&adapter->watchdog_timer, round_jiffies(jiffies + HZ)); else mod_timer(&adapter->watchdog_timer, round_jiffies(jiffies + 2 * HZ)); } } /** * igc_intr_msi - Interrupt Handler * @irq: interrupt number * @data: pointer to a network interface device structure */ static irqreturn_t igc_intr_msi(int irq, void *data) { struct igc_adapter *adapter = data; struct igc_q_vector *q_vector = adapter->q_vector[0]; struct igc_hw *hw = &adapter->hw; /* read ICR disables interrupts using IAM */ u32 icr = rd32(IGC_ICR); igc_write_itr(q_vector); if (icr & IGC_ICR_DRSTA) schedule_work(&adapter->reset_task); if (icr & IGC_ICR_DOUTSYNC) { /* HW is reporting DMA is out of sync */ adapter->stats.doosync++; } if (icr & (IGC_ICR_RXSEQ | IGC_ICR_LSC)) { hw->mac.get_link_status = true; if (!test_bit(__IGC_DOWN, &adapter->state)) mod_timer(&adapter->watchdog_timer, jiffies + 1); } if (icr & IGC_ICR_TS) igc_tsync_interrupt(adapter); napi_schedule(&q_vector->napi); return IRQ_HANDLED; } /** * igc_intr - Legacy Interrupt Handler * @irq: interrupt number * @data: pointer to a network interface device structure */ static irqreturn_t igc_intr(int irq, void *data) { struct igc_adapter *adapter = data; struct igc_q_vector *q_vector = adapter->q_vector[0]; struct igc_hw *hw = &adapter->hw; /* Interrupt Auto-Mask...upon reading ICR, interrupts are masked. No * need for the IMC write */ u32 icr = rd32(IGC_ICR); /* IMS will not auto-mask if INT_ASSERTED is not set, and if it is * not set, then the adapter didn't send an interrupt */ if (!(icr & IGC_ICR_INT_ASSERTED)) return IRQ_NONE; igc_write_itr(q_vector); if (icr & IGC_ICR_DRSTA) schedule_work(&adapter->reset_task); if (icr & IGC_ICR_DOUTSYNC) { /* HW is reporting DMA is out of sync */ adapter->stats.doosync++; } if (icr & (IGC_ICR_RXSEQ | IGC_ICR_LSC)) { hw->mac.get_link_status = true; /* guard against interrupt when we're going down */ if (!test_bit(__IGC_DOWN, &adapter->state)) mod_timer(&adapter->watchdog_timer, jiffies + 1); } if (icr & IGC_ICR_TS) igc_tsync_interrupt(adapter); napi_schedule(&q_vector->napi); return IRQ_HANDLED; } static void igc_free_irq(struct igc_adapter *adapter) { if (adapter->msix_entries) { int vector = 0, i; free_irq(adapter->msix_entries[vector++].vector, adapter); for (i = 0; i < adapter->num_q_vectors; i++) free_irq(adapter->msix_entries[vector++].vector, adapter->q_vector[i]); } else { free_irq(adapter->pdev->irq, adapter); } } /** * igc_request_irq - initialize interrupts * @adapter: Pointer to adapter structure * * Attempts to configure interrupts using the best available * capabilities of the hardware and kernel. */ static int igc_request_irq(struct igc_adapter *adapter) { struct net_device *netdev = adapter->netdev; struct pci_dev *pdev = adapter->pdev; int err = 0; if (adapter->flags & IGC_FLAG_HAS_MSIX) { err = igc_request_msix(adapter); if (!err) goto request_done; /* fall back to MSI */ igc_free_all_tx_resources(adapter); igc_free_all_rx_resources(adapter); igc_clear_interrupt_scheme(adapter); err = igc_init_interrupt_scheme(adapter, false); if (err) goto request_done; igc_setup_all_tx_resources(adapter); igc_setup_all_rx_resources(adapter); igc_configure(adapter); } igc_assign_vector(adapter->q_vector[0], 0); if (adapter->flags & IGC_FLAG_HAS_MSI) { err = request_irq(pdev->irq, &igc_intr_msi, 0, netdev->name, adapter); if (!err) goto request_done; /* fall back to legacy interrupts */ igc_reset_interrupt_capability(adapter); adapter->flags &= ~IGC_FLAG_HAS_MSI; } err = request_irq(pdev->irq, &igc_intr, IRQF_SHARED, netdev->name, adapter); if (err) netdev_err(netdev, "Error %d getting interrupt\n", err); request_done: return err; } /** * __igc_open - Called when a network interface is made active * @netdev: network interface device structure * @resuming: boolean indicating if the device is resuming * * Returns 0 on success, negative value on failure * * The open entry point is called when a network interface is made * active by the system (IFF_UP). At this point all resources needed * for transmit and receive operations are allocated, the interrupt * handler is registered with the OS, the watchdog timer is started, * and the stack is notified that the interface is ready. */ static int __igc_open(struct net_device *netdev, bool resuming) { struct igc_adapter *adapter = netdev_priv(netdev); struct pci_dev *pdev = adapter->pdev; struct igc_hw *hw = &adapter->hw; int err = 0; int i = 0; /* disallow open during test */ if (test_bit(__IGC_TESTING, &adapter->state)) { WARN_ON(resuming); return -EBUSY; } if (!resuming) pm_runtime_get_sync(&pdev->dev); netif_carrier_off(netdev); /* allocate transmit descriptors */ err = igc_setup_all_tx_resources(adapter); if (err) goto err_setup_tx; /* allocate receive descriptors */ err = igc_setup_all_rx_resources(adapter); if (err) goto err_setup_rx; igc_power_up_link(adapter); igc_configure(adapter); err = igc_request_irq(adapter); if (err) goto err_req_irq; /* Notify the stack of the actual queue counts. */ err = netif_set_real_num_tx_queues(netdev, adapter->num_tx_queues); if (err) goto err_set_queues; err = netif_set_real_num_rx_queues(netdev, adapter->num_rx_queues); if (err) goto err_set_queues; clear_bit(__IGC_DOWN, &adapter->state); for (i = 0; i < adapter->num_q_vectors; i++) napi_enable(&adapter->q_vector[i]->napi); /* Clear any pending interrupts. */ rd32(IGC_ICR); igc_irq_enable(adapter); if (!resuming) pm_runtime_put(&pdev->dev); netif_tx_start_all_queues(netdev); /* start the watchdog. */ hw->mac.get_link_status = true; schedule_work(&adapter->watchdog_task); return IGC_SUCCESS; err_set_queues: igc_free_irq(adapter); err_req_irq: igc_release_hw_control(adapter); igc_power_down_phy_copper_base(&adapter->hw); igc_free_all_rx_resources(adapter); err_setup_rx: igc_free_all_tx_resources(adapter); err_setup_tx: igc_reset(adapter); if (!resuming) pm_runtime_put(&pdev->dev); return err; } int igc_open(struct net_device *netdev) { return __igc_open(netdev, false); } /** * __igc_close - Disables a network interface * @netdev: network interface device structure * @suspending: boolean indicating the device is suspending * * Returns 0, this is not allowed to fail * * The close entry point is called when an interface is de-activated * by the OS. The hardware is still under the driver's control, but * needs to be disabled. A global MAC reset is issued to stop the * hardware, and all transmit and receive resources are freed. */ static int __igc_close(struct net_device *netdev, bool suspending) { struct igc_adapter *adapter = netdev_priv(netdev); struct pci_dev *pdev = adapter->pdev; WARN_ON(test_bit(__IGC_RESETTING, &adapter->state)); if (!suspending) pm_runtime_get_sync(&pdev->dev); igc_down(adapter); igc_release_hw_control(adapter); igc_free_irq(adapter); igc_free_all_tx_resources(adapter); igc_free_all_rx_resources(adapter); if (!suspending) pm_runtime_put_sync(&pdev->dev); return 0; } int igc_close(struct net_device *netdev) { if (netif_device_present(netdev) || netdev->dismantle) return __igc_close(netdev, false); return 0; } /** * igc_ioctl - Access the hwtstamp interface * @netdev: network interface device structure * @ifr: interface request data * @cmd: ioctl command **/ static int igc_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd) { switch (cmd) { case SIOCGHWTSTAMP: return igc_ptp_get_ts_config(netdev, ifr); case SIOCSHWTSTAMP: return igc_ptp_set_ts_config(netdev, ifr); default: return -EOPNOTSUPP; } } static int igc_save_launchtime_params(struct igc_adapter *adapter, int queue, bool enable) { struct igc_ring *ring; if (queue < 0 || queue >= adapter->num_tx_queues) return -EINVAL; ring = adapter->tx_ring[queue]; ring->launchtime_enable = enable; return 0; } static bool is_base_time_past(ktime_t base_time, const struct timespec64 *now) { struct timespec64 b; b = ktime_to_timespec64(base_time); return timespec64_compare(now, &b) > 0; } static bool validate_schedule(struct igc_adapter *adapter, const struct tc_taprio_qopt_offload *qopt) { int queue_uses[IGC_MAX_TX_QUEUES] = { }; struct igc_hw *hw = &adapter->hw; struct timespec64 now; size_t n; if (qopt->cycle_time_extension) return false; igc_ptp_read(adapter, &now); /* If we program the controller's BASET registers with a time * in the future, it will hold all the packets until that * time, causing a lot of TX Hangs, so to avoid that, we * reject schedules that would start in the future. * Note: Limitation above is no longer in i226. */ if (!is_base_time_past(qopt->base_time, &now) && igc_is_device_id_i225(hw)) return false; for (n = 0; n < qopt->num_entries; n++) { const struct tc_taprio_sched_entry *e, *prev; int i; prev = n ? &qopt->entries[n - 1] : NULL; e = &qopt->entries[n]; /* i225 only supports "global" frame preemption * settings. */ if (e->command != TC_TAPRIO_CMD_SET_GATES) return false; for (i = 0; i < adapter->num_tx_queues; i++) if (e->gate_mask & BIT(i)) { queue_uses[i]++; /* There are limitations: A single queue cannot * be opened and closed multiple times per cycle * unless the gate stays open. Check for it. */ if (queue_uses[i] > 1 && !(prev->gate_mask & BIT(i))) return false; } } return true; } static int igc_tsn_enable_launchtime(struct igc_adapter *adapter, struct tc_etf_qopt_offload *qopt) { struct igc_hw *hw = &adapter->hw; int err; if (hw->mac.type != igc_i225) return -EOPNOTSUPP; err = igc_save_launchtime_params(adapter, qopt->queue, qopt->enable); if (err) return err; return igc_tsn_offload_apply(adapter); } static int igc_qbv_clear_schedule(struct igc_adapter *adapter) { unsigned long flags; int i; adapter->base_time = 0; adapter->cycle_time = NSEC_PER_SEC; adapter->taprio_offload_enable = false; adapter->qbv_config_change_errors = 0; adapter->qbv_count = 0; for (i = 0; i < adapter->num_tx_queues; i++) { struct igc_ring *ring = adapter->tx_ring[i]; ring->start_time = 0; ring->end_time = NSEC_PER_SEC; ring->max_sdu = 0; } spin_lock_irqsave(&adapter->qbv_tx_lock, flags); adapter->qbv_transition = false; for (i = 0; i < adapter->num_tx_queues; i++) { struct igc_ring *ring = adapter->tx_ring[i]; ring->oper_gate_closed = false; ring->admin_gate_closed = false; } spin_unlock_irqrestore(&adapter->qbv_tx_lock, flags); return 0; } static int igc_tsn_clear_schedule(struct igc_adapter *adapter) { igc_qbv_clear_schedule(adapter); return 0; } static void igc_taprio_stats(struct net_device *dev, struct tc_taprio_qopt_stats *stats) { /* When Strict_End is enabled, the tx_overruns counter * will always be zero. */ stats->tx_overruns = 0; } static void igc_taprio_queue_stats(struct net_device *dev, struct tc_taprio_qopt_queue_stats *queue_stats) { struct tc_taprio_qopt_stats *stats = &queue_stats->stats; /* When Strict_End is enabled, the tx_overruns counter * will always be zero. */ stats->tx_overruns = 0; } static int igc_save_qbv_schedule(struct igc_adapter *adapter, struct tc_taprio_qopt_offload *qopt) { bool queue_configured[IGC_MAX_TX_QUEUES] = { }; struct igc_hw *hw = &adapter->hw; u32 start_time = 0, end_time = 0; struct timespec64 now; unsigned long flags; size_t n; int i; switch (qopt->cmd) { case TAPRIO_CMD_REPLACE: break; case TAPRIO_CMD_DESTROY: return igc_tsn_clear_schedule(adapter); case TAPRIO_CMD_STATS: igc_taprio_stats(adapter->netdev, &qopt->stats); return 0; case TAPRIO_CMD_QUEUE_STATS: igc_taprio_queue_stats(adapter->netdev, &qopt->queue_stats); return 0; default: return -EOPNOTSUPP; } if (qopt->base_time < 0) return -ERANGE; if (igc_is_device_id_i225(hw) && adapter->taprio_offload_enable) return -EALREADY; if (!validate_schedule(adapter, qopt)) return -EINVAL; adapter->cycle_time = qopt->cycle_time; adapter->base_time = qopt->base_time; adapter->taprio_offload_enable = true; igc_ptp_read(adapter, &now); for (n = 0; n < qopt->num_entries; n++) { struct tc_taprio_sched_entry *e = &qopt->entries[n]; end_time += e->interval; /* If any of the conditions below are true, we need to manually * control the end time of the cycle. * 1. Qbv users can specify a cycle time that is not equal * to the total GCL intervals. Hence, recalculation is * necessary here to exclude the time interval that * exceeds the cycle time. * 2. According to IEEE Std. 802.1Q-2018 section 8.6.9.2, * once the end of the list is reached, it will switch * to the END_OF_CYCLE state and leave the gates in the * same state until the next cycle is started. */ if (end_time > adapter->cycle_time || n + 1 == qopt->num_entries) end_time = adapter->cycle_time; for (i = 0; i < adapter->num_tx_queues; i++) { struct igc_ring *ring = adapter->tx_ring[i]; if (!(e->gate_mask & BIT(i))) continue; /* Check whether a queue stays open for more than one * entry. If so, keep the start and advance the end * time. */ if (!queue_configured[i]) ring->start_time = start_time; ring->end_time = end_time; if (ring->start_time >= adapter->cycle_time) queue_configured[i] = false; else queue_configured[i] = true; } start_time += e->interval; } spin_lock_irqsave(&adapter->qbv_tx_lock, flags); /* Check whether a queue gets configured. * If not, set the start and end time to be end time. */ for (i = 0; i < adapter->num_tx_queues; i++) { struct igc_ring *ring = adapter->tx_ring[i]; if (!is_base_time_past(qopt->base_time, &now)) { ring->admin_gate_closed = false; } else { ring->oper_gate_closed = false; ring->admin_gate_closed = false; } if (!queue_configured[i]) { if (!is_base_time_past(qopt->base_time, &now)) ring->admin_gate_closed = true; else ring->oper_gate_closed = true; ring->start_time = end_time; ring->end_time = end_time; } } spin_unlock_irqrestore(&adapter->qbv_tx_lock, flags); for (i = 0; i < adapter->num_tx_queues; i++) { struct igc_ring *ring = adapter->tx_ring[i]; struct net_device *dev = adapter->netdev; if (qopt->max_sdu[i]) ring->max_sdu = qopt->max_sdu[i] + dev->hard_header_len - ETH_TLEN; else ring->max_sdu = 0; } return 0; } static int igc_tsn_enable_qbv_scheduling(struct igc_adapter *adapter, struct tc_taprio_qopt_offload *qopt) { struct igc_hw *hw = &adapter->hw; int err; if (hw->mac.type != igc_i225) return -EOPNOTSUPP; err = igc_save_qbv_schedule(adapter, qopt); if (err) return err; return igc_tsn_offload_apply(adapter); } static int igc_save_cbs_params(struct igc_adapter *adapter, int queue, bool enable, int idleslope, int sendslope, int hicredit, int locredit) { bool cbs_status[IGC_MAX_SR_QUEUES] = { false }; struct net_device *netdev = adapter->netdev; struct igc_ring *ring; int i; /* i225 has two sets of credit-based shaper logic. * Supporting it only on the top two priority queues */ if (queue < 0 || queue > 1) return -EINVAL; ring = adapter->tx_ring[queue]; for (i = 0; i < IGC_MAX_SR_QUEUES; i++) if (adapter->tx_ring[i]) cbs_status[i] = adapter->tx_ring[i]->cbs_enable; /* CBS should be enabled on the highest priority queue first in order * for the CBS algorithm to operate as intended. */ if (enable) { if (queue == 1 && !cbs_status[0]) { netdev_err(netdev, "Enabling CBS on queue1 before queue0\n"); return -EINVAL; } } else { if (queue == 0 && cbs_status[1]) { netdev_err(netdev, "Disabling CBS on queue0 before queue1\n"); return -EINVAL; } } ring->cbs_enable = enable; ring->idleslope = idleslope; ring->sendslope = sendslope; ring->hicredit = hicredit; ring->locredit = locredit; return 0; } static int igc_tsn_enable_cbs(struct igc_adapter *adapter, struct tc_cbs_qopt_offload *qopt) { struct igc_hw *hw = &adapter->hw; int err; if (hw->mac.type != igc_i225) return -EOPNOTSUPP; if (qopt->queue < 0 || qopt->queue > 1) return -EINVAL; err = igc_save_cbs_params(adapter, qopt->queue, qopt->enable, qopt->idleslope, qopt->sendslope, qopt->hicredit, qopt->locredit); if (err) return err; return igc_tsn_offload_apply(adapter); } static int igc_tc_query_caps(struct igc_adapter *adapter, struct tc_query_caps_base *base) { struct igc_hw *hw = &adapter->hw; switch (base->type) { case TC_SETUP_QDISC_TAPRIO: { struct tc_taprio_caps *caps = base->caps; caps->broken_mqprio = true; if (hw->mac.type == igc_i225) { caps->supports_queue_max_sdu = true; caps->gate_mask_per_txq = true; } return 0; } default: return -EOPNOTSUPP; } } static int igc_setup_tc(struct net_device *dev, enum tc_setup_type type, void *type_data) { struct igc_adapter *adapter = netdev_priv(dev); adapter->tc_setup_type = type; switch (type) { case TC_QUERY_CAPS: return igc_tc_query_caps(adapter, type_data); case TC_SETUP_QDISC_TAPRIO: return igc_tsn_enable_qbv_scheduling(adapter, type_data); case TC_SETUP_QDISC_ETF: return igc_tsn_enable_launchtime(adapter, type_data); case TC_SETUP_QDISC_CBS: return igc_tsn_enable_cbs(adapter, type_data); default: return -EOPNOTSUPP; } } static int igc_bpf(struct net_device *dev, struct netdev_bpf *bpf) { struct igc_adapter *adapter = netdev_priv(dev); switch (bpf->command) { case XDP_SETUP_PROG: return igc_xdp_set_prog(adapter, bpf->prog, bpf->extack); case XDP_SETUP_XSK_POOL: return igc_xdp_setup_pool(adapter, bpf->xsk.pool, bpf->xsk.queue_id); default: return -EOPNOTSUPP; } } static int igc_xdp_xmit(struct net_device *dev, int num_frames, struct xdp_frame **frames, u32 flags) { struct igc_adapter *adapter = netdev_priv(dev); int cpu = smp_processor_id(); struct netdev_queue *nq; struct igc_ring *ring; int i, drops; if (unlikely(!netif_carrier_ok(dev))) return -ENETDOWN; if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK)) return -EINVAL; ring = igc_xdp_get_tx_ring(adapter, cpu); nq = txring_txq(ring); __netif_tx_lock(nq, cpu); /* Avoid transmit queue timeout since we share it with the slow path */ txq_trans_cond_update(nq); drops = 0; for (i = 0; i < num_frames; i++) { int err; struct xdp_frame *xdpf = frames[i]; err = igc_xdp_init_tx_descriptor(ring, xdpf); if (err) { xdp_return_frame_rx_napi(xdpf); drops++; } } if (flags & XDP_XMIT_FLUSH) igc_flush_tx_descriptors(ring); __netif_tx_unlock(nq); return num_frames - drops; } static void igc_trigger_rxtxq_interrupt(struct igc_adapter *adapter, struct igc_q_vector *q_vector) { struct igc_hw *hw = &adapter->hw; u32 eics = 0; eics |= q_vector->eims_value; wr32(IGC_EICS, eics); } int igc_xsk_wakeup(struct net_device *dev, u32 queue_id, u32 flags) { struct igc_adapter *adapter = netdev_priv(dev); struct igc_q_vector *q_vector; struct igc_ring *ring; if (test_bit(__IGC_DOWN, &adapter->state)) return -ENETDOWN; if (!igc_xdp_is_enabled(adapter)) return -ENXIO; if (queue_id >= adapter->num_rx_queues) return -EINVAL; ring = adapter->rx_ring[queue_id]; if (!ring->xsk_pool) return -ENXIO; q_vector = adapter->q_vector[queue_id]; if (!napi_if_scheduled_mark_missed(&q_vector->napi)) igc_trigger_rxtxq_interrupt(adapter, q_vector); return 0; } static const struct net_device_ops igc_netdev_ops = { .ndo_open = igc_open, .ndo_stop = igc_close, .ndo_start_xmit = igc_xmit_frame, .ndo_set_rx_mode = igc_set_rx_mode, .ndo_set_mac_address = igc_set_mac, .ndo_change_mtu = igc_change_mtu, .ndo_tx_timeout = igc_tx_timeout, .ndo_get_stats64 = igc_get_stats64, .ndo_fix_features = igc_fix_features, .ndo_set_features = igc_set_features, .ndo_features_check = igc_features_check, .ndo_eth_ioctl = igc_ioctl, .ndo_setup_tc = igc_setup_tc, .ndo_bpf = igc_bpf, .ndo_xdp_xmit = igc_xdp_xmit, .ndo_xsk_wakeup = igc_xsk_wakeup, }; /* PCIe configuration access */ void igc_read_pci_cfg(struct igc_hw *hw, u32 reg, u16 *value) { struct igc_adapter *adapter = hw->back; pci_read_config_word(adapter->pdev, reg, value); } void igc_write_pci_cfg(struct igc_hw *hw, u32 reg, u16 *value) { struct igc_adapter *adapter = hw->back; pci_write_config_word(adapter->pdev, reg, *value); } s32 igc_read_pcie_cap_reg(struct igc_hw *hw, u32 reg, u16 *value) { struct igc_adapter *adapter = hw->back; if (!pci_is_pcie(adapter->pdev)) return -IGC_ERR_CONFIG; pcie_capability_read_word(adapter->pdev, reg, value); return IGC_SUCCESS; } s32 igc_write_pcie_cap_reg(struct igc_hw *hw, u32 reg, u16 *value) { struct igc_adapter *adapter = hw->back; if (!pci_is_pcie(adapter->pdev)) return -IGC_ERR_CONFIG; pcie_capability_write_word(adapter->pdev, reg, *value); return IGC_SUCCESS; } u32 igc_rd32(struct igc_hw *hw, u32 reg) { struct igc_adapter *igc = container_of(hw, struct igc_adapter, hw); u8 __iomem *hw_addr = READ_ONCE(hw->hw_addr); u32 value = 0; if (IGC_REMOVED(hw_addr)) return ~value; value = readl(&hw_addr[reg]); /* reads should not return all F's */ if (!(~value) && (!reg || !(~readl(hw_addr)))) { struct net_device *netdev = igc->netdev; hw->hw_addr = NULL; netif_device_detach(netdev); netdev_err(netdev, "PCIe link lost, device now detached\n"); WARN(pci_device_is_present(igc->pdev), "igc: Failed to read reg 0x%x!\n", reg); } return value; } /* Mapping HW RSS Type to enum xdp_rss_hash_type */ static enum xdp_rss_hash_type igc_xdp_rss_type[IGC_RSS_TYPE_MAX_TABLE] = { [IGC_RSS_TYPE_NO_HASH] = XDP_RSS_TYPE_L2, [IGC_RSS_TYPE_HASH_TCP_IPV4] = XDP_RSS_TYPE_L4_IPV4_TCP, [IGC_RSS_TYPE_HASH_IPV4] = XDP_RSS_TYPE_L3_IPV4, [IGC_RSS_TYPE_HASH_TCP_IPV6] = XDP_RSS_TYPE_L4_IPV6_TCP, [IGC_RSS_TYPE_HASH_IPV6_EX] = XDP_RSS_TYPE_L3_IPV6_EX, [IGC_RSS_TYPE_HASH_IPV6] = XDP_RSS_TYPE_L3_IPV6, [IGC_RSS_TYPE_HASH_TCP_IPV6_EX] = XDP_RSS_TYPE_L4_IPV6_TCP_EX, [IGC_RSS_TYPE_HASH_UDP_IPV4] = XDP_RSS_TYPE_L4_IPV4_UDP, [IGC_RSS_TYPE_HASH_UDP_IPV6] = XDP_RSS_TYPE_L4_IPV6_UDP, [IGC_RSS_TYPE_HASH_UDP_IPV6_EX] = XDP_RSS_TYPE_L4_IPV6_UDP_EX, [10] = XDP_RSS_TYPE_NONE, /* RSS Type above 9 "Reserved" by HW */ [11] = XDP_RSS_TYPE_NONE, /* keep array sized for SW bit-mask */ [12] = XDP_RSS_TYPE_NONE, /* to handle future HW revisons */ [13] = XDP_RSS_TYPE_NONE, [14] = XDP_RSS_TYPE_NONE, [15] = XDP_RSS_TYPE_NONE, }; static int igc_xdp_rx_hash(const struct xdp_md *_ctx, u32 *hash, enum xdp_rss_hash_type *rss_type) { const struct igc_xdp_buff *ctx = (void *)_ctx; if (!(ctx->xdp.rxq->dev->features & NETIF_F_RXHASH)) return -ENODATA; *hash = le32_to_cpu(ctx->rx_desc->wb.lower.hi_dword.rss); *rss_type = igc_xdp_rss_type[igc_rss_type(ctx->rx_desc)]; return 0; } static int igc_xdp_rx_timestamp(const struct xdp_md *_ctx, u64 *timestamp) { const struct igc_xdp_buff *ctx = (void *)_ctx; if (igc_test_staterr(ctx->rx_desc, IGC_RXDADV_STAT_TSIP)) { *timestamp = ctx->rx_ts; return 0; } return -ENODATA; } static const struct xdp_metadata_ops igc_xdp_metadata_ops = { .xmo_rx_hash = igc_xdp_rx_hash, .xmo_rx_timestamp = igc_xdp_rx_timestamp, }; static enum hrtimer_restart igc_qbv_scheduling_timer(struct hrtimer *timer) { struct igc_adapter *adapter = container_of(timer, struct igc_adapter, hrtimer); unsigned long flags; unsigned int i; spin_lock_irqsave(&adapter->qbv_tx_lock, flags); adapter->qbv_transition = true; for (i = 0; i < adapter->num_tx_queues; i++) { struct igc_ring *tx_ring = adapter->tx_ring[i]; if (tx_ring->admin_gate_closed) { tx_ring->admin_gate_closed = false; tx_ring->oper_gate_closed = true; } else { tx_ring->oper_gate_closed = false; } } adapter->qbv_transition = false; spin_unlock_irqrestore(&adapter->qbv_tx_lock, flags); return HRTIMER_NORESTART; } /** * igc_probe - Device Initialization Routine * @pdev: PCI device information struct * @ent: entry in igc_pci_tbl * * Returns 0 on success, negative on failure * * igc_probe initializes an adapter identified by a pci_dev structure. * The OS initialization, configuring the adapter private structure, * and a hardware reset occur. */ static int igc_probe(struct pci_dev *pdev, const struct pci_device_id *ent) { struct igc_adapter *adapter; struct net_device *netdev; struct igc_hw *hw; const struct igc_info *ei = igc_info_tbl[ent->driver_data]; int err; err = pci_enable_device_mem(pdev); if (err) return err; err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64)); if (err) { dev_err(&pdev->dev, "No usable DMA configuration, aborting\n"); goto err_dma; } err = pci_request_mem_regions(pdev, igc_driver_name); if (err) goto err_pci_reg; err = pci_enable_ptm(pdev, NULL); if (err < 0) dev_info(&pdev->dev, "PCIe PTM not supported by PCIe bus/controller\n"); pci_set_master(pdev); err = -ENOMEM; netdev = alloc_etherdev_mq(sizeof(struct igc_adapter), IGC_MAX_TX_QUEUES); if (!netdev) goto err_alloc_etherdev; SET_NETDEV_DEV(netdev, &pdev->dev); pci_set_drvdata(pdev, netdev); adapter = netdev_priv(netdev); adapter->netdev = netdev; adapter->pdev = pdev; hw = &adapter->hw; hw->back = adapter; adapter->port_num = hw->bus.func; adapter->msg_enable = netif_msg_init(debug, DEFAULT_MSG_ENABLE); err = pci_save_state(pdev); if (err) goto err_ioremap; err = -EIO; adapter->io_addr = ioremap(pci_resource_start(pdev, 0), pci_resource_len(pdev, 0)); if (!adapter->io_addr) goto err_ioremap; /* hw->hw_addr can be zeroed, so use adapter->io_addr for unmap */ hw->hw_addr = adapter->io_addr; netdev->netdev_ops = &igc_netdev_ops; netdev->xdp_metadata_ops = &igc_xdp_metadata_ops; igc_ethtool_set_ops(netdev); netdev->watchdog_timeo = 5 * HZ; netdev->mem_start = pci_resource_start(pdev, 0); netdev->mem_end = pci_resource_end(pdev, 0); /* PCI config space info */ hw->vendor_id = pdev->vendor; hw->device_id = pdev->device; hw->revision_id = pdev->revision; hw->subsystem_vendor_id = pdev->subsystem_vendor; hw->subsystem_device_id = pdev->subsystem_device; /* Copy the default MAC and PHY function pointers */ memcpy(&hw->mac.ops, ei->mac_ops, sizeof(hw->mac.ops)); memcpy(&hw->phy.ops, ei->phy_ops, sizeof(hw->phy.ops)); /* Initialize skew-specific constants */ err = ei->get_invariants(hw); if (err) goto err_sw_init; /* Add supported features to the features list*/ netdev->features |= NETIF_F_SG; netdev->features |= NETIF_F_TSO; netdev->features |= NETIF_F_TSO6; netdev->features |= NETIF_F_TSO_ECN; netdev->features |= NETIF_F_RXHASH; netdev->features |= NETIF_F_RXCSUM; netdev->features |= NETIF_F_HW_CSUM; netdev->features |= NETIF_F_SCTP_CRC; netdev->features |= NETIF_F_HW_TC; #define IGC_GSO_PARTIAL_FEATURES (NETIF_F_GSO_GRE | \ NETIF_F_GSO_GRE_CSUM | \ NETIF_F_GSO_IPXIP4 | \ NETIF_F_GSO_IPXIP6 | \ NETIF_F_GSO_UDP_TUNNEL | \ NETIF_F_GSO_UDP_TUNNEL_CSUM) netdev->gso_partial_features = IGC_GSO_PARTIAL_FEATURES; netdev->features |= NETIF_F_GSO_PARTIAL | IGC_GSO_PARTIAL_FEATURES; /* setup the private structure */ err = igc_sw_init(adapter); if (err) goto err_sw_init; /* copy netdev features into list of user selectable features */ netdev->hw_features |= NETIF_F_NTUPLE; netdev->hw_features |= NETIF_F_HW_VLAN_CTAG_TX; netdev->hw_features |= NETIF_F_HW_VLAN_CTAG_RX; netdev->hw_features |= netdev->features; netdev->features |= NETIF_F_HIGHDMA; netdev->vlan_features |= netdev->features | NETIF_F_TSO_MANGLEID; netdev->mpls_features |= NETIF_F_HW_CSUM; netdev->hw_enc_features |= netdev->vlan_features; netdev->xdp_features = NETDEV_XDP_ACT_BASIC | NETDEV_XDP_ACT_REDIRECT | NETDEV_XDP_ACT_XSK_ZEROCOPY; /* MTU range: 68 - 9216 */ netdev->min_mtu = ETH_MIN_MTU; netdev->max_mtu = MAX_STD_JUMBO_FRAME_SIZE; /* before reading the NVM, reset the controller to put the device in a * known good starting state */ hw->mac.ops.reset_hw(hw); if (igc_get_flash_presence_i225(hw)) { if (hw->nvm.ops.validate(hw) < 0) { dev_err(&pdev->dev, "The NVM Checksum Is Not Valid\n"); err = -EIO; goto err_eeprom; } } if (eth_platform_get_mac_address(&pdev->dev, hw->mac.addr)) { /* copy the MAC address out of the NVM */ if (hw->mac.ops.read_mac_addr(hw)) dev_err(&pdev->dev, "NVM Read Error\n"); } eth_hw_addr_set(netdev, hw->mac.addr); if (!is_valid_ether_addr(netdev->dev_addr)) { dev_err(&pdev->dev, "Invalid MAC Address\n"); err = -EIO; goto err_eeprom; } /* configure RXPBSIZE and TXPBSIZE */ wr32(IGC_RXPBS, I225_RXPBSIZE_DEFAULT); wr32(IGC_TXPBS, I225_TXPBSIZE_DEFAULT); timer_setup(&adapter->watchdog_timer, igc_watchdog, 0); timer_setup(&adapter->phy_info_timer, igc_update_phy_info, 0); INIT_WORK(&adapter->reset_task, igc_reset_task); INIT_WORK(&adapter->watchdog_task, igc_watchdog_task); hrtimer_init(&adapter->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); adapter->hrtimer.function = &igc_qbv_scheduling_timer; /* Initialize link properties that are user-changeable */ adapter->fc_autoneg = true; hw->mac.autoneg = true; hw->phy.autoneg_advertised = 0xaf; hw->fc.requested_mode = igc_fc_default; hw->fc.current_mode = igc_fc_default; /* By default, support wake on port A */ adapter->flags |= IGC_FLAG_WOL_SUPPORTED; /* initialize the wol settings based on the eeprom settings */ if (adapter->flags & IGC_FLAG_WOL_SUPPORTED) adapter->wol |= IGC_WUFC_MAG; device_set_wakeup_enable(&adapter->pdev->dev, adapter->flags & IGC_FLAG_WOL_SUPPORTED); igc_ptp_init(adapter); igc_tsn_clear_schedule(adapter); /* reset the hardware with the new settings */ igc_reset(adapter); /* let the f/w know that the h/w is now under the control of the * driver. */ igc_get_hw_control(adapter); strncpy(netdev->name, "eth%d", IFNAMSIZ); err = register_netdev(netdev); if (err) goto err_register; /* carrier off reporting is important to ethtool even BEFORE open */ netif_carrier_off(netdev); /* Check if Media Autosense is enabled */ adapter->ei = *ei; /* print pcie link status and MAC address */ pcie_print_link_status(pdev); netdev_info(netdev, "MAC: %pM\n", netdev->dev_addr); dev_pm_set_driver_flags(&pdev->dev, DPM_FLAG_NO_DIRECT_COMPLETE); /* Disable EEE for internal PHY devices */ hw->dev_spec._base.eee_enable = false; adapter->flags &= ~IGC_FLAG_EEE; igc_set_eee_i225(hw, false, false, false); pm_runtime_put_noidle(&pdev->dev); return 0; err_register: igc_release_hw_control(adapter); err_eeprom: if (!igc_check_reset_block(hw)) igc_reset_phy(hw); err_sw_init: igc_clear_interrupt_scheme(adapter); iounmap(adapter->io_addr); err_ioremap: free_netdev(netdev); err_alloc_etherdev: pci_release_mem_regions(pdev); err_pci_reg: err_dma: pci_disable_device(pdev); return err; } /** * igc_remove - Device Removal Routine * @pdev: PCI device information struct * * igc_remove is called by the PCI subsystem to alert the driver * that it should release a PCI device. This could be caused by a * Hot-Plug event, or because the driver is going to be removed from * memory. */ static void igc_remove(struct pci_dev *pdev) { struct net_device *netdev = pci_get_drvdata(pdev); struct igc_adapter *adapter = netdev_priv(netdev); pm_runtime_get_noresume(&pdev->dev); igc_flush_nfc_rules(adapter); igc_ptp_stop(adapter); pci_disable_ptm(pdev); pci_clear_master(pdev); set_bit(__IGC_DOWN, &adapter->state); del_timer_sync(&adapter->watchdog_timer); del_timer_sync(&adapter->phy_info_timer); cancel_work_sync(&adapter->reset_task); cancel_work_sync(&adapter->watchdog_task); hrtimer_cancel(&adapter->hrtimer); /* Release control of h/w to f/w. If f/w is AMT enabled, this * would have already happened in close and is redundant. */ igc_release_hw_control(adapter); unregister_netdev(netdev); igc_clear_interrupt_scheme(adapter); pci_iounmap(pdev, adapter->io_addr); pci_release_mem_regions(pdev); free_netdev(netdev); pci_disable_device(pdev); } static int __igc_shutdown(struct pci_dev *pdev, bool *enable_wake, bool runtime) { struct net_device *netdev = pci_get_drvdata(pdev); struct igc_adapter *adapter = netdev_priv(netdev); u32 wufc = runtime ? IGC_WUFC_LNKC : adapter->wol; struct igc_hw *hw = &adapter->hw; u32 ctrl, rctl, status; bool wake; rtnl_lock(); netif_device_detach(netdev); if (netif_running(netdev)) __igc_close(netdev, true); igc_ptp_suspend(adapter); igc_clear_interrupt_scheme(adapter); rtnl_unlock(); status = rd32(IGC_STATUS); if (status & IGC_STATUS_LU) wufc &= ~IGC_WUFC_LNKC; if (wufc) { igc_setup_rctl(adapter); igc_set_rx_mode(netdev); /* turn on all-multi mode if wake on multicast is enabled */ if (wufc & IGC_WUFC_MC) { rctl = rd32(IGC_RCTL); rctl |= IGC_RCTL_MPE; wr32(IGC_RCTL, rctl); } ctrl = rd32(IGC_CTRL); ctrl |= IGC_CTRL_ADVD3WUC; wr32(IGC_CTRL, ctrl); /* Allow time for pending master requests to run */ igc_disable_pcie_master(hw); wr32(IGC_WUC, IGC_WUC_PME_EN); wr32(IGC_WUFC, wufc); } else { wr32(IGC_WUC, 0); wr32(IGC_WUFC, 0); } wake = wufc || adapter->en_mng_pt; if (!wake) igc_power_down_phy_copper_base(&adapter->hw); else igc_power_up_link(adapter); if (enable_wake) *enable_wake = wake; /* Release control of h/w to f/w. If f/w is AMT enabled, this * would have already happened in close and is redundant. */ igc_release_hw_control(adapter); pci_disable_device(pdev); return 0; } #ifdef CONFIG_PM static int __maybe_unused igc_runtime_suspend(struct device *dev) { return __igc_shutdown(to_pci_dev(dev), NULL, 1); } static void igc_deliver_wake_packet(struct net_device *netdev) { struct igc_adapter *adapter = netdev_priv(netdev); struct igc_hw *hw = &adapter->hw; struct sk_buff *skb; u32 wupl; wupl = rd32(IGC_WUPL) & IGC_WUPL_MASK; /* WUPM stores only the first 128 bytes of the wake packet. * Read the packet only if we have the whole thing. */ if (wupl == 0 || wupl > IGC_WUPM_BYTES) return; skb = netdev_alloc_skb_ip_align(netdev, IGC_WUPM_BYTES); if (!skb) return; skb_put(skb, wupl); /* Ensure reads are 32-bit aligned */ wupl = roundup(wupl, 4); memcpy_fromio(skb->data, hw->hw_addr + IGC_WUPM_REG(0), wupl); skb->protocol = eth_type_trans(skb, netdev); netif_rx(skb); } static int __maybe_unused igc_resume(struct device *dev) { struct pci_dev *pdev = to_pci_dev(dev); struct net_device *netdev = pci_get_drvdata(pdev); struct igc_adapter *adapter = netdev_priv(netdev); struct igc_hw *hw = &adapter->hw; u32 err, val; pci_set_power_state(pdev, PCI_D0); pci_restore_state(pdev); pci_save_state(pdev); if (!pci_device_is_present(pdev)) return -ENODEV; err = pci_enable_device_mem(pdev); if (err) { netdev_err(netdev, "Cannot enable PCI device from suspend\n"); return err; } pci_set_master(pdev); pci_enable_wake(pdev, PCI_D3hot, 0); pci_enable_wake(pdev, PCI_D3cold, 0); if (igc_init_interrupt_scheme(adapter, true)) { netdev_err(netdev, "Unable to allocate memory for queues\n"); return -ENOMEM; } igc_reset(adapter); /* let the f/w know that the h/w is now under the control of the * driver. */ igc_get_hw_control(adapter); val = rd32(IGC_WUS); if (val & WAKE_PKT_WUS) igc_deliver_wake_packet(netdev); wr32(IGC_WUS, ~0); rtnl_lock(); if (!err && netif_running(netdev)) err = __igc_open(netdev, true); if (!err) netif_device_attach(netdev); rtnl_unlock(); return err; } static int __maybe_unused igc_runtime_resume(struct device *dev) { return igc_resume(dev); } static int __maybe_unused igc_suspend(struct device *dev) { return __igc_shutdown(to_pci_dev(dev), NULL, 0); } static int __maybe_unused igc_runtime_idle(struct device *dev) { struct net_device *netdev = dev_get_drvdata(dev); struct igc_adapter *adapter = netdev_priv(netdev); if (!igc_has_link(adapter)) pm_schedule_suspend(dev, MSEC_PER_SEC * 5); return -EBUSY; } #endif /* CONFIG_PM */ static void igc_shutdown(struct pci_dev *pdev) { bool wake; __igc_shutdown(pdev, &wake, 0); if (system_state == SYSTEM_POWER_OFF) { pci_wake_from_d3(pdev, wake); pci_set_power_state(pdev, PCI_D3hot); } } /** * igc_io_error_detected - called when PCI error is detected * @pdev: Pointer to PCI device * @state: The current PCI connection state * * This function is called after a PCI bus error affecting * this device has been detected. **/ static pci_ers_result_t igc_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state) { struct net_device *netdev = pci_get_drvdata(pdev); struct igc_adapter *adapter = netdev_priv(netdev); netif_device_detach(netdev); if (state == pci_channel_io_perm_failure) return PCI_ERS_RESULT_DISCONNECT; if (netif_running(netdev)) igc_down(adapter); pci_disable_device(pdev); /* Request a slot reset. */ return PCI_ERS_RESULT_NEED_RESET; } /** * igc_io_slot_reset - called after the PCI bus has been reset. * @pdev: Pointer to PCI device * * Restart the card from scratch, as if from a cold-boot. Implementation * resembles the first-half of the igc_resume routine. **/ static pci_ers_result_t igc_io_slot_reset(struct pci_dev *pdev) { struct net_device *netdev = pci_get_drvdata(pdev); struct igc_adapter *adapter = netdev_priv(netdev); struct igc_hw *hw = &adapter->hw; pci_ers_result_t result; if (pci_enable_device_mem(pdev)) { netdev_err(netdev, "Could not re-enable PCI device after reset\n"); result = PCI_ERS_RESULT_DISCONNECT; } else { pci_set_master(pdev); pci_restore_state(pdev); pci_save_state(pdev); pci_enable_wake(pdev, PCI_D3hot, 0); pci_enable_wake(pdev, PCI_D3cold, 0); /* In case of PCI error, adapter loses its HW address * so we should re-assign it here. */ hw->hw_addr = adapter->io_addr; igc_reset(adapter); wr32(IGC_WUS, ~0); result = PCI_ERS_RESULT_RECOVERED; } return result; } /** * igc_io_resume - called when traffic can start to flow again. * @pdev: Pointer to PCI device * * This callback is called when the error recovery driver tells us that * its OK to resume normal operation. Implementation resembles the * second-half of the igc_resume routine. */ static void igc_io_resume(struct pci_dev *pdev) { struct net_device *netdev = pci_get_drvdata(pdev); struct igc_adapter *adapter = netdev_priv(netdev); rtnl_lock(); if (netif_running(netdev)) { if (igc_open(netdev)) { netdev_err(netdev, "igc_open failed after reset\n"); return; } } netif_device_attach(netdev); /* let the f/w know that the h/w is now under the control of the * driver. */ igc_get_hw_control(adapter); rtnl_unlock(); } static const struct pci_error_handlers igc_err_handler = { .error_detected = igc_io_error_detected, .slot_reset = igc_io_slot_reset, .resume = igc_io_resume, }; #ifdef CONFIG_PM static const struct dev_pm_ops igc_pm_ops = { SET_SYSTEM_SLEEP_PM_OPS(igc_suspend, igc_resume) SET_RUNTIME_PM_OPS(igc_runtime_suspend, igc_runtime_resume, igc_runtime_idle) }; #endif static struct pci_driver igc_driver = { .name = igc_driver_name, .id_table = igc_pci_tbl, .probe = igc_probe, .remove = igc_remove, #ifdef CONFIG_PM .driver.pm = &igc_pm_ops, #endif .shutdown = igc_shutdown, .err_handler = &igc_err_handler, }; /** * igc_reinit_queues - return error * @adapter: pointer to adapter structure */ int igc_reinit_queues(struct igc_adapter *adapter) { struct net_device *netdev = adapter->netdev; int err = 0; if (netif_running(netdev)) igc_close(netdev); igc_reset_interrupt_capability(adapter); if (igc_init_interrupt_scheme(adapter, true)) { netdev_err(netdev, "Unable to allocate memory for queues\n"); return -ENOMEM; } if (netif_running(netdev)) err = igc_open(netdev); return err; } /** * igc_get_hw_dev - return device * @hw: pointer to hardware structure * * used by hardware layer to print debugging information */ struct net_device *igc_get_hw_dev(struct igc_hw *hw) { struct igc_adapter *adapter = hw->back; return adapter->netdev; } static void igc_disable_rx_ring_hw(struct igc_ring *ring) { struct igc_hw *hw = &ring->q_vector->adapter->hw; u8 idx = ring->reg_idx; u32 rxdctl; rxdctl = rd32(IGC_RXDCTL(idx)); rxdctl &= ~IGC_RXDCTL_QUEUE_ENABLE; rxdctl |= IGC_RXDCTL_SWFLUSH; wr32(IGC_RXDCTL(idx), rxdctl); } void igc_disable_rx_ring(struct igc_ring *ring) { igc_disable_rx_ring_hw(ring); igc_clean_rx_ring(ring); } void igc_enable_rx_ring(struct igc_ring *ring) { struct igc_adapter *adapter = ring->q_vector->adapter; igc_configure_rx_ring(adapter, ring); if (ring->xsk_pool) igc_alloc_rx_buffers_zc(ring, igc_desc_unused(ring)); else igc_alloc_rx_buffers(ring, igc_desc_unused(ring)); } void igc_disable_tx_ring(struct igc_ring *ring) { igc_disable_tx_ring_hw(ring); igc_clean_tx_ring(ring); } void igc_enable_tx_ring(struct igc_ring *ring) { struct igc_adapter *adapter = ring->q_vector->adapter; igc_configure_tx_ring(adapter, ring); } /** * igc_init_module - Driver Registration Routine * * igc_init_module is the first routine called when the driver is * loaded. All it does is register with the PCI subsystem. */ static int __init igc_init_module(void) { int ret; pr_info("%s\n", igc_driver_string); pr_info("%s\n", igc_copyright); ret = pci_register_driver(&igc_driver); return ret; } module_init(igc_init_module); /** * igc_exit_module - Driver Exit Cleanup Routine * * igc_exit_module is called just before the driver is removed * from memory. */ static void __exit igc_exit_module(void) { pci_unregister_driver(&igc_driver); } module_exit(igc_exit_module); /* igc_main.c */
linux-master
drivers/net/ethernet/intel/igc/igc_main.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2018 Intel Corporation */ #include <linux/pci.h> #include <linux/delay.h> #include "igc_mac.h" #include "igc_hw.h" /** * igc_disable_pcie_master - Disables PCI-express master access * @hw: pointer to the HW structure * * Returns 0 (0) if successful, else returns -10 * (-IGC_ERR_MASTER_REQUESTS_PENDING) if master disable bit has not caused * the master requests to be disabled. * * Disables PCI-Express master access and verifies there are no pending * requests. */ s32 igc_disable_pcie_master(struct igc_hw *hw) { s32 timeout = MASTER_DISABLE_TIMEOUT; s32 ret_val = 0; u32 ctrl; ctrl = rd32(IGC_CTRL); ctrl |= IGC_CTRL_GIO_MASTER_DISABLE; wr32(IGC_CTRL, ctrl); while (timeout) { if (!(rd32(IGC_STATUS) & IGC_STATUS_GIO_MASTER_ENABLE)) break; usleep_range(2000, 3000); timeout--; } if (!timeout) { hw_dbg("Master requests are pending.\n"); ret_val = -IGC_ERR_MASTER_REQUESTS_PENDING; goto out; } out: return ret_val; } /** * igc_init_rx_addrs - Initialize receive addresses * @hw: pointer to the HW structure * @rar_count: receive address registers * * Setup the receive address registers by setting the base receive address * register to the devices MAC address and clearing all the other receive * address registers to 0. */ void igc_init_rx_addrs(struct igc_hw *hw, u16 rar_count) { u8 mac_addr[ETH_ALEN] = {0}; u32 i; /* Setup the receive address */ hw_dbg("Programming MAC Address into RAR[0]\n"); hw->mac.ops.rar_set(hw, hw->mac.addr, 0); /* Zero out the other (rar_entry_count - 1) receive addresses */ hw_dbg("Clearing RAR[1-%u]\n", rar_count - 1); for (i = 1; i < rar_count; i++) hw->mac.ops.rar_set(hw, mac_addr, i); } /** * igc_set_fc_watermarks - Set flow control high/low watermarks * @hw: pointer to the HW structure * * Sets the flow control high/low threshold (watermark) registers. If * flow control XON frame transmission is enabled, then set XON frame * transmission as well. */ static s32 igc_set_fc_watermarks(struct igc_hw *hw) { u32 fcrtl = 0, fcrth = 0; /* Set the flow control receive threshold registers. Normally, * these registers will be set to a default threshold that may be * adjusted later by the driver's runtime code. However, if the * ability to transmit pause frames is not enabled, then these * registers will be set to 0. */ if (hw->fc.current_mode & igc_fc_tx_pause) { /* We need to set up the Receive Threshold high and low water * marks as well as (optionally) enabling the transmission of * XON frames. */ fcrtl = hw->fc.low_water; if (hw->fc.send_xon) fcrtl |= IGC_FCRTL_XONE; fcrth = hw->fc.high_water; } wr32(IGC_FCRTL, fcrtl); wr32(IGC_FCRTH, fcrth); return 0; } /** * igc_setup_link - Setup flow control and link settings * @hw: pointer to the HW structure * * Determines which flow control settings to use, then configures flow * control. Calls the appropriate media-specific link configuration * function. Assuming the adapter has a valid link partner, a valid link * should be established. Assumes the hardware has previously been reset * and the transmitter and receiver are not enabled. */ s32 igc_setup_link(struct igc_hw *hw) { s32 ret_val = 0; /* In the case of the phy reset being blocked, we already have a link. * We do not need to set it up again. */ if (igc_check_reset_block(hw)) goto out; /* If requested flow control is set to default, set flow control * to the both 'rx' and 'tx' pause frames. */ if (hw->fc.requested_mode == igc_fc_default) hw->fc.requested_mode = igc_fc_full; /* We want to save off the original Flow Control configuration just * in case we get disconnected and then reconnected into a different * hub or switch with different Flow Control capabilities. */ hw->fc.current_mode = hw->fc.requested_mode; hw_dbg("After fix-ups FlowControl is now = %x\n", hw->fc.current_mode); /* Call the necessary media_type subroutine to configure the link. */ ret_val = hw->mac.ops.setup_physical_interface(hw); if (ret_val) goto out; /* Initialize the flow control address, type, and PAUSE timer * registers to their default values. This is done even if flow * control is disabled, because it does not hurt anything to * initialize these registers. */ hw_dbg("Initializing the Flow Control address, type and timer regs\n"); wr32(IGC_FCT, FLOW_CONTROL_TYPE); wr32(IGC_FCAH, FLOW_CONTROL_ADDRESS_HIGH); wr32(IGC_FCAL, FLOW_CONTROL_ADDRESS_LOW); wr32(IGC_FCTTV, hw->fc.pause_time); ret_val = igc_set_fc_watermarks(hw); out: return ret_val; } /** * igc_force_mac_fc - Force the MAC's flow control settings * @hw: pointer to the HW structure * * Force the MAC's flow control settings. Sets the TFCE and RFCE bits in the * device control register to reflect the adapter settings. TFCE and RFCE * need to be explicitly set by software when a copper PHY is used because * autonegotiation is managed by the PHY rather than the MAC. Software must * also configure these bits when link is forced on a fiber connection. */ s32 igc_force_mac_fc(struct igc_hw *hw) { s32 ret_val = 0; u32 ctrl; ctrl = rd32(IGC_CTRL); /* Because we didn't get link via the internal auto-negotiation * mechanism (we either forced link or we got link via PHY * auto-neg), we have to manually enable/disable transmit an * receive flow control. * * The "Case" statement below enables/disable flow control * according to the "hw->fc.current_mode" parameter. * * The possible values of the "fc" parameter are: * 0: Flow control is completely disabled * 1: Rx flow control is enabled (we can receive pause * frames but not send pause frames). * 2: Tx flow control is enabled (we can send pause frames * but we do not receive pause frames). * 3: Both Rx and TX flow control (symmetric) is enabled. * other: No other values should be possible at this point. */ hw_dbg("hw->fc.current_mode = %u\n", hw->fc.current_mode); switch (hw->fc.current_mode) { case igc_fc_none: ctrl &= (~(IGC_CTRL_TFCE | IGC_CTRL_RFCE)); break; case igc_fc_rx_pause: ctrl &= (~IGC_CTRL_TFCE); ctrl |= IGC_CTRL_RFCE; break; case igc_fc_tx_pause: ctrl &= (~IGC_CTRL_RFCE); ctrl |= IGC_CTRL_TFCE; break; case igc_fc_full: ctrl |= (IGC_CTRL_TFCE | IGC_CTRL_RFCE); break; default: hw_dbg("Flow control param set incorrectly\n"); ret_val = -IGC_ERR_CONFIG; goto out; } wr32(IGC_CTRL, ctrl); out: return ret_val; } /** * igc_clear_hw_cntrs_base - Clear base hardware counters * @hw: pointer to the HW structure * * Clears the base hardware counters by reading the counter registers. */ void igc_clear_hw_cntrs_base(struct igc_hw *hw) { rd32(IGC_CRCERRS); rd32(IGC_MPC); rd32(IGC_SCC); rd32(IGC_ECOL); rd32(IGC_MCC); rd32(IGC_LATECOL); rd32(IGC_COLC); rd32(IGC_RERC); rd32(IGC_DC); rd32(IGC_RLEC); rd32(IGC_XONRXC); rd32(IGC_XONTXC); rd32(IGC_XOFFRXC); rd32(IGC_XOFFTXC); rd32(IGC_FCRUC); rd32(IGC_GPRC); rd32(IGC_BPRC); rd32(IGC_MPRC); rd32(IGC_GPTC); rd32(IGC_GORCL); rd32(IGC_GORCH); rd32(IGC_GOTCL); rd32(IGC_GOTCH); rd32(IGC_RNBC); rd32(IGC_RUC); rd32(IGC_RFC); rd32(IGC_ROC); rd32(IGC_RJC); rd32(IGC_TORL); rd32(IGC_TORH); rd32(IGC_TOTL); rd32(IGC_TOTH); rd32(IGC_TPR); rd32(IGC_TPT); rd32(IGC_MPTC); rd32(IGC_BPTC); rd32(IGC_PRC64); rd32(IGC_PRC127); rd32(IGC_PRC255); rd32(IGC_PRC511); rd32(IGC_PRC1023); rd32(IGC_PRC1522); rd32(IGC_PTC64); rd32(IGC_PTC127); rd32(IGC_PTC255); rd32(IGC_PTC511); rd32(IGC_PTC1023); rd32(IGC_PTC1522); rd32(IGC_ALGNERRC); rd32(IGC_RXERRC); rd32(IGC_TNCRS); rd32(IGC_HTDPMC); rd32(IGC_TSCTC); rd32(IGC_MGTPRC); rd32(IGC_MGTPDC); rd32(IGC_MGTPTC); rd32(IGC_IAC); rd32(IGC_RPTHC); rd32(IGC_TLPIC); rd32(IGC_RLPIC); rd32(IGC_HGPTC); rd32(IGC_RXDMTC); rd32(IGC_HGORCL); rd32(IGC_HGORCH); rd32(IGC_HGOTCL); rd32(IGC_HGOTCH); rd32(IGC_LENERRS); } /** * igc_rar_set - Set receive address register * @hw: pointer to the HW structure * @addr: pointer to the receive address * @index: receive address array register * * Sets the receive address array register at index to the address passed * in by addr. */ void igc_rar_set(struct igc_hw *hw, u8 *addr, u32 index) { u32 rar_low, rar_high; /* HW expects these in little endian so we reverse the byte order * from network order (big endian) to little endian */ rar_low = ((u32)addr[0] | ((u32)addr[1] << 8) | ((u32)addr[2] << 16) | ((u32)addr[3] << 24)); rar_high = ((u32)addr[4] | ((u32)addr[5] << 8)); /* If MAC address zero, no need to set the AV bit */ if (rar_low || rar_high) rar_high |= IGC_RAH_AV; /* Some bridges will combine consecutive 32-bit writes into * a single burst write, which will malfunction on some parts. * The flushes avoid this. */ wr32(IGC_RAL(index), rar_low); wrfl(); wr32(IGC_RAH(index), rar_high); wrfl(); } /** * igc_check_for_copper_link - Check for link (Copper) * @hw: pointer to the HW structure * * Checks to see of the link status of the hardware has changed. If a * change in link status has been detected, then we read the PHY registers * to get the current speed/duplex if link exists. */ s32 igc_check_for_copper_link(struct igc_hw *hw) { struct igc_mac_info *mac = &hw->mac; bool link = false; s32 ret_val; /* We only want to go out to the PHY registers to see if Auto-Neg * has completed and/or if our link status has changed. The * get_link_status flag is set upon receiving a Link Status * Change or Rx Sequence Error interrupt. */ if (!mac->get_link_status) { ret_val = 0; goto out; } /* First we want to see if the MII Status Register reports * link. If so, then we want to get the current speed/duplex * of the PHY. */ ret_val = igc_phy_has_link(hw, 1, 0, &link); if (ret_val) goto out; if (!link) goto out; /* No link detected */ mac->get_link_status = false; /* Check if there was DownShift, must be checked * immediately after link-up */ igc_check_downshift(hw); /* If we are forcing speed/duplex, then we simply return since * we have already determined whether we have link or not. */ if (!mac->autoneg) { ret_val = -IGC_ERR_CONFIG; goto out; } /* Auto-Neg is enabled. Auto Speed Detection takes care * of MAC speed/duplex configuration. So we only need to * configure Collision Distance in the MAC. */ igc_config_collision_dist(hw); /* Configure Flow Control now that Auto-Neg has completed. * First, we need to restore the desired flow control * settings because we may have had to re-autoneg with a * different link partner. */ ret_val = igc_config_fc_after_link_up(hw); if (ret_val) hw_dbg("Error configuring flow control\n"); out: /* Now that we are aware of our link settings, we can set the LTR * thresholds. */ ret_val = igc_set_ltr_i225(hw, link); return ret_val; } /** * igc_config_collision_dist - Configure collision distance * @hw: pointer to the HW structure * * Configures the collision distance to the default value and is used * during link setup. Currently no func pointer exists and all * implementations are handled in the generic version of this function. */ void igc_config_collision_dist(struct igc_hw *hw) { u32 tctl; tctl = rd32(IGC_TCTL); tctl &= ~IGC_TCTL_COLD; tctl |= IGC_COLLISION_DISTANCE << IGC_COLD_SHIFT; wr32(IGC_TCTL, tctl); wrfl(); } /** * igc_config_fc_after_link_up - Configures flow control after link * @hw: pointer to the HW structure * * Checks the status of auto-negotiation after link up to ensure that the * speed and duplex were not forced. If the link needed to be forced, then * flow control needs to be forced also. If auto-negotiation is enabled * and did not fail, then we configure flow control based on our link * partner. */ s32 igc_config_fc_after_link_up(struct igc_hw *hw) { u16 mii_status_reg, mii_nway_adv_reg, mii_nway_lp_ability_reg; struct igc_mac_info *mac = &hw->mac; u16 speed, duplex; s32 ret_val = 0; /* Check for the case where we have fiber media and auto-neg failed * so we had to force link. In this case, we need to force the * configuration of the MAC to match the "fc" parameter. */ if (mac->autoneg_failed) ret_val = igc_force_mac_fc(hw); if (ret_val) { hw_dbg("Error forcing flow control settings\n"); goto out; } /* Check for the case where we have copper media and auto-neg is * enabled. In this case, we need to check and see if Auto-Neg * has completed, and if so, how the PHY and link partner has * flow control configured. */ if (mac->autoneg) { /* Read the MII Status Register and check to see if AutoNeg * has completed. We read this twice because this reg has * some "sticky" (latched) bits. */ ret_val = hw->phy.ops.read_reg(hw, PHY_STATUS, &mii_status_reg); if (ret_val) goto out; ret_val = hw->phy.ops.read_reg(hw, PHY_STATUS, &mii_status_reg); if (ret_val) goto out; if (!(mii_status_reg & MII_SR_AUTONEG_COMPLETE)) { hw_dbg("Copper PHY and Auto Neg has not completed.\n"); goto out; } /* The AutoNeg process has completed, so we now need to * read both the Auto Negotiation Advertisement * Register (Address 4) and the Auto_Negotiation Base * Page Ability Register (Address 5) to determine how * flow control was negotiated. */ ret_val = hw->phy.ops.read_reg(hw, PHY_AUTONEG_ADV, &mii_nway_adv_reg); if (ret_val) goto out; ret_val = hw->phy.ops.read_reg(hw, PHY_LP_ABILITY, &mii_nway_lp_ability_reg); if (ret_val) goto out; /* Two bits in the Auto Negotiation Advertisement Register * (Address 4) and two bits in the Auto Negotiation Base * Page Ability Register (Address 5) determine flow control * for both the PHY and the link partner. The following * table, taken out of the IEEE 802.3ab/D6.0 dated March 25, * 1999, describes these PAUSE resolution bits and how flow * control is determined based upon these settings. * NOTE: DC = Don't Care * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | NIC Resolution *-------|---------|-------|---------|-------------------- * 0 | 0 | DC | DC | igc_fc_none * 0 | 1 | 0 | DC | igc_fc_none * 0 | 1 | 1 | 0 | igc_fc_none * 0 | 1 | 1 | 1 | igc_fc_tx_pause * 1 | 0 | 0 | DC | igc_fc_none * 1 | DC | 1 | DC | igc_fc_full * 1 | 1 | 0 | 0 | igc_fc_none * 1 | 1 | 0 | 1 | igc_fc_rx_pause * * Are both PAUSE bits set to 1? If so, this implies * Symmetric Flow Control is enabled at both ends. The * ASM_DIR bits are irrelevant per the spec. * * For Symmetric Flow Control: * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result *-------|---------|-------|---------|-------------------- * 1 | DC | 1 | DC | IGC_fc_full * */ if ((mii_nway_adv_reg & NWAY_AR_PAUSE) && (mii_nway_lp_ability_reg & NWAY_LPAR_PAUSE)) { /* Now we need to check if the user selected RX ONLY * of pause frames. In this case, we had to advertise * FULL flow control because we could not advertise RX * ONLY. Hence, we must now check to see if we need to * turn OFF the TRANSMISSION of PAUSE frames. */ if (hw->fc.requested_mode == igc_fc_full) { hw->fc.current_mode = igc_fc_full; hw_dbg("Flow Control = FULL.\n"); } else { hw->fc.current_mode = igc_fc_rx_pause; hw_dbg("Flow Control = RX PAUSE frames only.\n"); } } /* For receiving PAUSE frames ONLY. * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result *-------|---------|-------|---------|-------------------- * 0 | 1 | 1 | 1 | igc_fc_tx_pause */ else if (!(mii_nway_adv_reg & NWAY_AR_PAUSE) && (mii_nway_adv_reg & NWAY_AR_ASM_DIR) && (mii_nway_lp_ability_reg & NWAY_LPAR_PAUSE) && (mii_nway_lp_ability_reg & NWAY_LPAR_ASM_DIR)) { hw->fc.current_mode = igc_fc_tx_pause; hw_dbg("Flow Control = TX PAUSE frames only.\n"); } /* For transmitting PAUSE frames ONLY. * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result *-------|---------|-------|---------|-------------------- * 1 | 1 | 0 | 1 | igc_fc_rx_pause */ else if ((mii_nway_adv_reg & NWAY_AR_PAUSE) && (mii_nway_adv_reg & NWAY_AR_ASM_DIR) && !(mii_nway_lp_ability_reg & NWAY_LPAR_PAUSE) && (mii_nway_lp_ability_reg & NWAY_LPAR_ASM_DIR)) { hw->fc.current_mode = igc_fc_rx_pause; hw_dbg("Flow Control = RX PAUSE frames only.\n"); } /* Per the IEEE spec, at this point flow control should be * disabled. However, we want to consider that we could * be connected to a legacy switch that doesn't advertise * desired flow control, but can be forced on the link * partner. So if we advertised no flow control, that is * what we will resolve to. If we advertised some kind of * receive capability (Rx Pause Only or Full Flow Control) * and the link partner advertised none, we will configure * ourselves to enable Rx Flow Control only. We can do * this safely for two reasons: If the link partner really * didn't want flow control enabled, and we enable Rx, no * harm done since we won't be receiving any PAUSE frames * anyway. If the intent on the link partner was to have * flow control enabled, then by us enabling RX only, we * can at least receive pause frames and process them. * This is a good idea because in most cases, since we are * predominantly a server NIC, more times than not we will * be asked to delay transmission of packets than asking * our link partner to pause transmission of frames. */ else if ((hw->fc.requested_mode == igc_fc_none) || (hw->fc.requested_mode == igc_fc_tx_pause) || (hw->fc.strict_ieee)) { hw->fc.current_mode = igc_fc_none; hw_dbg("Flow Control = NONE.\n"); } else { hw->fc.current_mode = igc_fc_rx_pause; hw_dbg("Flow Control = RX PAUSE frames only.\n"); } /* Now we need to do one last check... If we auto- * negotiated to HALF DUPLEX, flow control should not be * enabled per IEEE 802.3 spec. */ ret_val = hw->mac.ops.get_speed_and_duplex(hw, &speed, &duplex); if (ret_val) { hw_dbg("Error getting link speed and duplex\n"); goto out; } if (duplex == HALF_DUPLEX) hw->fc.current_mode = igc_fc_none; /* Now we call a subroutine to actually force the MAC * controller to use the correct flow control settings. */ ret_val = igc_force_mac_fc(hw); if (ret_val) { hw_dbg("Error forcing flow control settings\n"); goto out; } } out: return ret_val; } /** * igc_get_auto_rd_done - Check for auto read completion * @hw: pointer to the HW structure * * Check EEPROM for Auto Read done bit. */ s32 igc_get_auto_rd_done(struct igc_hw *hw) { s32 ret_val = 0; s32 i = 0; while (i < AUTO_READ_DONE_TIMEOUT) { if (rd32(IGC_EECD) & IGC_EECD_AUTO_RD) break; usleep_range(1000, 2000); i++; } if (i == AUTO_READ_DONE_TIMEOUT) { hw_dbg("Auto read by HW from NVM has not completed.\n"); ret_val = -IGC_ERR_RESET; goto out; } out: return ret_val; } /** * igc_get_speed_and_duplex_copper - Retrieve current speed/duplex * @hw: pointer to the HW structure * @speed: stores the current speed * @duplex: stores the current duplex * * Read the status register for the current speed/duplex and store the current * speed and duplex for copper connections. */ s32 igc_get_speed_and_duplex_copper(struct igc_hw *hw, u16 *speed, u16 *duplex) { u32 status; status = rd32(IGC_STATUS); if (status & IGC_STATUS_SPEED_1000) { /* For I225, STATUS will indicate 1G speed in both 1 Gbps * and 2.5 Gbps link modes. An additional bit is used * to differentiate between 1 Gbps and 2.5 Gbps. */ if (hw->mac.type == igc_i225 && (status & IGC_STATUS_SPEED_2500)) { *speed = SPEED_2500; hw_dbg("2500 Mbs, "); } else { *speed = SPEED_1000; hw_dbg("1000 Mbs, "); } } else if (status & IGC_STATUS_SPEED_100) { *speed = SPEED_100; hw_dbg("100 Mbs, "); } else { *speed = SPEED_10; hw_dbg("10 Mbs, "); } if (status & IGC_STATUS_FD) { *duplex = FULL_DUPLEX; hw_dbg("Full Duplex\n"); } else { *duplex = HALF_DUPLEX; hw_dbg("Half Duplex\n"); } return 0; } /** * igc_put_hw_semaphore - Release hardware semaphore * @hw: pointer to the HW structure * * Release hardware semaphore used to access the PHY or NVM */ void igc_put_hw_semaphore(struct igc_hw *hw) { u32 swsm; swsm = rd32(IGC_SWSM); swsm &= ~(IGC_SWSM_SMBI | IGC_SWSM_SWESMBI); wr32(IGC_SWSM, swsm); } /** * igc_enable_mng_pass_thru - Enable processing of ARP's * @hw: pointer to the HW structure * * Verifies the hardware needs to leave interface enabled so that frames can * be directed to and from the management interface. */ bool igc_enable_mng_pass_thru(struct igc_hw *hw) { bool ret_val = false; u32 fwsm, factps; u32 manc; if (!hw->mac.asf_firmware_present) goto out; manc = rd32(IGC_MANC); if (!(manc & IGC_MANC_RCV_TCO_EN)) goto out; if (hw->mac.arc_subsystem_valid) { fwsm = rd32(IGC_FWSM); factps = rd32(IGC_FACTPS); if (!(factps & IGC_FACTPS_MNGCG) && ((fwsm & IGC_FWSM_MODE_MASK) == (igc_mng_mode_pt << IGC_FWSM_MODE_SHIFT))) { ret_val = true; goto out; } } else { if ((manc & IGC_MANC_SMBUS_EN) && !(manc & IGC_MANC_ASF_EN)) { ret_val = true; goto out; } } out: return ret_val; } /** * igc_hash_mc_addr - Generate a multicast hash value * @hw: pointer to the HW structure * @mc_addr: pointer to a multicast address * * Generates a multicast address hash value which is used to determine * the multicast filter table array address and new table value. See * igc_mta_set() **/ static u32 igc_hash_mc_addr(struct igc_hw *hw, u8 *mc_addr) { u32 hash_value, hash_mask; u8 bit_shift = 0; /* Register count multiplied by bits per register */ hash_mask = (hw->mac.mta_reg_count * 32) - 1; /* For a mc_filter_type of 0, bit_shift is the number of left-shifts * where 0xFF would still fall within the hash mask. */ while (hash_mask >> bit_shift != 0xFF) bit_shift++; /* The portion of the address that is used for the hash table * is determined by the mc_filter_type setting. * The algorithm is such that there is a total of 8 bits of shifting. * The bit_shift for a mc_filter_type of 0 represents the number of * left-shifts where the MSB of mc_addr[5] would still fall within * the hash_mask. Case 0 does this exactly. Since there are a total * of 8 bits of shifting, then mc_addr[4] will shift right the * remaining number of bits. Thus 8 - bit_shift. The rest of the * cases are a variation of this algorithm...essentially raising the * number of bits to shift mc_addr[5] left, while still keeping the * 8-bit shifting total. * * For example, given the following Destination MAC Address and an * MTA register count of 128 (thus a 4096-bit vector and 0xFFF mask), * we can see that the bit_shift for case 0 is 4. These are the hash * values resulting from each mc_filter_type... * [0] [1] [2] [3] [4] [5] * 01 AA 00 12 34 56 * LSB MSB * * case 0: hash_value = ((0x34 >> 4) | (0x56 << 4)) & 0xFFF = 0x563 * case 1: hash_value = ((0x34 >> 3) | (0x56 << 5)) & 0xFFF = 0xAC6 * case 2: hash_value = ((0x34 >> 2) | (0x56 << 6)) & 0xFFF = 0x163 * case 3: hash_value = ((0x34 >> 0) | (0x56 << 8)) & 0xFFF = 0x634 */ switch (hw->mac.mc_filter_type) { default: case 0: break; case 1: bit_shift += 1; break; case 2: bit_shift += 2; break; case 3: bit_shift += 4; break; } hash_value = hash_mask & (((mc_addr[4] >> (8 - bit_shift)) | (((u16)mc_addr[5]) << bit_shift))); return hash_value; } /** * igc_update_mc_addr_list - Update Multicast addresses * @hw: pointer to the HW structure * @mc_addr_list: array of multicast addresses to program * @mc_addr_count: number of multicast addresses to program * * Updates entire Multicast Table Array. * The caller must have a packed mc_addr_list of multicast addresses. **/ void igc_update_mc_addr_list(struct igc_hw *hw, u8 *mc_addr_list, u32 mc_addr_count) { u32 hash_value, hash_bit, hash_reg; int i; /* clear mta_shadow */ memset(&hw->mac.mta_shadow, 0, sizeof(hw->mac.mta_shadow)); /* update mta_shadow from mc_addr_list */ for (i = 0; (u32)i < mc_addr_count; i++) { hash_value = igc_hash_mc_addr(hw, mc_addr_list); hash_reg = (hash_value >> 5) & (hw->mac.mta_reg_count - 1); hash_bit = hash_value & 0x1F; hw->mac.mta_shadow[hash_reg] |= BIT(hash_bit); mc_addr_list += ETH_ALEN; } /* replace the entire MTA table */ for (i = hw->mac.mta_reg_count - 1; i >= 0; i--) array_wr32(IGC_MTA, i, hw->mac.mta_shadow[i]); wrfl(); }
linux-master
drivers/net/ethernet/intel/igc/igc_mac.c
// SPDX-License-Identifier: GPL-2.0+ /* Copyright (C) 2011 Richard Cochran <[email protected]> */ #include <linux/module.h> #include <linux/device.h> #include <linux/pci.h> #include <linux/ptp_classify.h> #include "igb.h" #define INCVALUE_MASK 0x7fffffff #define ISGN 0x80000000 /* The 82580 timesync updates the system timer every 8ns by 8ns, * and this update value cannot be reprogrammed. * * Neither the 82576 nor the 82580 offer registers wide enough to hold * nanoseconds time values for very long. For the 82580, SYSTIM always * counts nanoseconds, but the upper 24 bits are not available. The * frequency is adjusted by changing the 32 bit fractional nanoseconds * register, TIMINCA. * * For the 82576, the SYSTIM register time unit is affect by the * choice of the 24 bit TININCA:IV (incvalue) field. Five bits of this * field are needed to provide the nominal 16 nanosecond period, * leaving 19 bits for fractional nanoseconds. * * We scale the NIC clock cycle by a large factor so that relatively * small clock corrections can be added or subtracted at each clock * tick. The drawbacks of a large factor are a) that the clock * register overflows more quickly (not such a big deal) and b) that * the increment per tick has to fit into 24 bits. As a result we * need to use a shift of 19 so we can fit a value of 16 into the * TIMINCA register. * * * SYSTIMH SYSTIML * +--------------+ +---+---+------+ * 82576 | 32 | | 8 | 5 | 19 | * +--------------+ +---+---+------+ * \________ 45 bits _______/ fract * * +----------+---+ +--------------+ * 82580 | 24 | 8 | | 32 | * +----------+---+ +--------------+ * reserved \______ 40 bits _____/ * * * The 45 bit 82576 SYSTIM overflows every * 2^45 * 10^-9 / 3600 = 9.77 hours. * * The 40 bit 82580 SYSTIM overflows every * 2^40 * 10^-9 / 60 = 18.3 minutes. * * SYSTIM is converted to real time using a timecounter. As * timecounter_cyc2time() allows old timestamps, the timecounter needs * to be updated at least once per half of the SYSTIM interval. * Scheduling of delayed work is not very accurate, and also the NIC * clock can be adjusted to run up to 6% faster and the system clock * up to 10% slower, so we aim for 6 minutes to be sure the actual * interval in the NIC time is shorter than 9.16 minutes. */ #define IGB_SYSTIM_OVERFLOW_PERIOD (HZ * 60 * 6) #define IGB_PTP_TX_TIMEOUT (HZ * 15) #define INCPERIOD_82576 BIT(E1000_TIMINCA_16NS_SHIFT) #define INCVALUE_82576_MASK GENMASK(E1000_TIMINCA_16NS_SHIFT - 1, 0) #define INCVALUE_82576 (16u << IGB_82576_TSYNC_SHIFT) #define IGB_NBITS_82580 40 #define IGB_82580_BASE_PERIOD 0x800000000 static void igb_ptp_tx_hwtstamp(struct igb_adapter *adapter); static void igb_ptp_sdp_init(struct igb_adapter *adapter); /* SYSTIM read access for the 82576 */ static u64 igb_ptp_read_82576(const struct cyclecounter *cc) { struct igb_adapter *igb = container_of(cc, struct igb_adapter, cc); struct e1000_hw *hw = &igb->hw; u64 val; u32 lo, hi; lo = rd32(E1000_SYSTIML); hi = rd32(E1000_SYSTIMH); val = ((u64) hi) << 32; val |= lo; return val; } /* SYSTIM read access for the 82580 */ static u64 igb_ptp_read_82580(const struct cyclecounter *cc) { struct igb_adapter *igb = container_of(cc, struct igb_adapter, cc); struct e1000_hw *hw = &igb->hw; u32 lo, hi; u64 val; /* The timestamp latches on lowest register read. For the 82580 * the lowest register is SYSTIMR instead of SYSTIML. However we only * need to provide nanosecond resolution, so we just ignore it. */ rd32(E1000_SYSTIMR); lo = rd32(E1000_SYSTIML); hi = rd32(E1000_SYSTIMH); val = ((u64) hi) << 32; val |= lo; return val; } /* SYSTIM read access for I210/I211 */ static void igb_ptp_read_i210(struct igb_adapter *adapter, struct timespec64 *ts) { struct e1000_hw *hw = &adapter->hw; u32 sec, nsec; /* The timestamp latches on lowest register read. For I210/I211, the * lowest register is SYSTIMR. Since we only need to provide nanosecond * resolution, we can ignore it. */ rd32(E1000_SYSTIMR); nsec = rd32(E1000_SYSTIML); sec = rd32(E1000_SYSTIMH); ts->tv_sec = sec; ts->tv_nsec = nsec; } static void igb_ptp_write_i210(struct igb_adapter *adapter, const struct timespec64 *ts) { struct e1000_hw *hw = &adapter->hw; /* Writing the SYSTIMR register is not necessary as it only provides * sub-nanosecond resolution. */ wr32(E1000_SYSTIML, ts->tv_nsec); wr32(E1000_SYSTIMH, (u32)ts->tv_sec); } /** * igb_ptp_systim_to_hwtstamp - convert system time value to hw timestamp * @adapter: board private structure * @hwtstamps: timestamp structure to update * @systim: unsigned 64bit system time value. * * We need to convert the system time value stored in the RX/TXSTMP registers * into a hwtstamp which can be used by the upper level timestamping functions. * * The 'tmreg_lock' spinlock is used to protect the consistency of the * system time value. This is needed because reading the 64 bit time * value involves reading two (or three) 32 bit registers. The first * read latches the value. Ditto for writing. * * In addition, here have extended the system time with an overflow * counter in software. **/ static void igb_ptp_systim_to_hwtstamp(struct igb_adapter *adapter, struct skb_shared_hwtstamps *hwtstamps, u64 systim) { unsigned long flags; u64 ns; memset(hwtstamps, 0, sizeof(*hwtstamps)); switch (adapter->hw.mac.type) { case e1000_82576: case e1000_82580: case e1000_i354: case e1000_i350: spin_lock_irqsave(&adapter->tmreg_lock, flags); ns = timecounter_cyc2time(&adapter->tc, systim); spin_unlock_irqrestore(&adapter->tmreg_lock, flags); hwtstamps->hwtstamp = ns_to_ktime(ns); break; case e1000_i210: case e1000_i211: /* Upper 32 bits contain s, lower 32 bits contain ns. */ hwtstamps->hwtstamp = ktime_set(systim >> 32, systim & 0xFFFFFFFF); break; default: break; } } /* PTP clock operations */ static int igb_ptp_adjfine_82576(struct ptp_clock_info *ptp, long scaled_ppm) { struct igb_adapter *igb = container_of(ptp, struct igb_adapter, ptp_caps); struct e1000_hw *hw = &igb->hw; u64 incvalue; incvalue = adjust_by_scaled_ppm(INCVALUE_82576, scaled_ppm); wr32(E1000_TIMINCA, INCPERIOD_82576 | (incvalue & INCVALUE_82576_MASK)); return 0; } static int igb_ptp_adjfine_82580(struct ptp_clock_info *ptp, long scaled_ppm) { struct igb_adapter *igb = container_of(ptp, struct igb_adapter, ptp_caps); struct e1000_hw *hw = &igb->hw; bool neg_adj; u64 rate; u32 inca; neg_adj = diff_by_scaled_ppm(IGB_82580_BASE_PERIOD, scaled_ppm, &rate); inca = rate & INCVALUE_MASK; if (neg_adj) inca |= ISGN; wr32(E1000_TIMINCA, inca); return 0; } static int igb_ptp_adjtime_82576(struct ptp_clock_info *ptp, s64 delta) { struct igb_adapter *igb = container_of(ptp, struct igb_adapter, ptp_caps); unsigned long flags; spin_lock_irqsave(&igb->tmreg_lock, flags); timecounter_adjtime(&igb->tc, delta); spin_unlock_irqrestore(&igb->tmreg_lock, flags); return 0; } static int igb_ptp_adjtime_i210(struct ptp_clock_info *ptp, s64 delta) { struct igb_adapter *igb = container_of(ptp, struct igb_adapter, ptp_caps); unsigned long flags; struct timespec64 now, then = ns_to_timespec64(delta); spin_lock_irqsave(&igb->tmreg_lock, flags); igb_ptp_read_i210(igb, &now); now = timespec64_add(now, then); igb_ptp_write_i210(igb, (const struct timespec64 *)&now); spin_unlock_irqrestore(&igb->tmreg_lock, flags); return 0; } static int igb_ptp_gettimex_82576(struct ptp_clock_info *ptp, struct timespec64 *ts, struct ptp_system_timestamp *sts) { struct igb_adapter *igb = container_of(ptp, struct igb_adapter, ptp_caps); struct e1000_hw *hw = &igb->hw; unsigned long flags; u32 lo, hi; u64 ns; spin_lock_irqsave(&igb->tmreg_lock, flags); ptp_read_system_prets(sts); lo = rd32(E1000_SYSTIML); ptp_read_system_postts(sts); hi = rd32(E1000_SYSTIMH); ns = timecounter_cyc2time(&igb->tc, ((u64)hi << 32) | lo); spin_unlock_irqrestore(&igb->tmreg_lock, flags); *ts = ns_to_timespec64(ns); return 0; } static int igb_ptp_gettimex_82580(struct ptp_clock_info *ptp, struct timespec64 *ts, struct ptp_system_timestamp *sts) { struct igb_adapter *igb = container_of(ptp, struct igb_adapter, ptp_caps); struct e1000_hw *hw = &igb->hw; unsigned long flags; u32 lo, hi; u64 ns; spin_lock_irqsave(&igb->tmreg_lock, flags); ptp_read_system_prets(sts); rd32(E1000_SYSTIMR); ptp_read_system_postts(sts); lo = rd32(E1000_SYSTIML); hi = rd32(E1000_SYSTIMH); ns = timecounter_cyc2time(&igb->tc, ((u64)hi << 32) | lo); spin_unlock_irqrestore(&igb->tmreg_lock, flags); *ts = ns_to_timespec64(ns); return 0; } static int igb_ptp_gettimex_i210(struct ptp_clock_info *ptp, struct timespec64 *ts, struct ptp_system_timestamp *sts) { struct igb_adapter *igb = container_of(ptp, struct igb_adapter, ptp_caps); struct e1000_hw *hw = &igb->hw; unsigned long flags; spin_lock_irqsave(&igb->tmreg_lock, flags); ptp_read_system_prets(sts); rd32(E1000_SYSTIMR); ptp_read_system_postts(sts); ts->tv_nsec = rd32(E1000_SYSTIML); ts->tv_sec = rd32(E1000_SYSTIMH); spin_unlock_irqrestore(&igb->tmreg_lock, flags); return 0; } static int igb_ptp_settime_82576(struct ptp_clock_info *ptp, const struct timespec64 *ts) { struct igb_adapter *igb = container_of(ptp, struct igb_adapter, ptp_caps); unsigned long flags; u64 ns; ns = timespec64_to_ns(ts); spin_lock_irqsave(&igb->tmreg_lock, flags); timecounter_init(&igb->tc, &igb->cc, ns); spin_unlock_irqrestore(&igb->tmreg_lock, flags); return 0; } static int igb_ptp_settime_i210(struct ptp_clock_info *ptp, const struct timespec64 *ts) { struct igb_adapter *igb = container_of(ptp, struct igb_adapter, ptp_caps); unsigned long flags; spin_lock_irqsave(&igb->tmreg_lock, flags); igb_ptp_write_i210(igb, ts); spin_unlock_irqrestore(&igb->tmreg_lock, flags); return 0; } static void igb_pin_direction(int pin, int input, u32 *ctrl, u32 *ctrl_ext) { u32 *ptr = pin < 2 ? ctrl : ctrl_ext; static const u32 mask[IGB_N_SDP] = { E1000_CTRL_SDP0_DIR, E1000_CTRL_SDP1_DIR, E1000_CTRL_EXT_SDP2_DIR, E1000_CTRL_EXT_SDP3_DIR, }; if (input) *ptr &= ~mask[pin]; else *ptr |= mask[pin]; } static void igb_pin_extts(struct igb_adapter *igb, int chan, int pin) { static const u32 aux0_sel_sdp[IGB_N_SDP] = { AUX0_SEL_SDP0, AUX0_SEL_SDP1, AUX0_SEL_SDP2, AUX0_SEL_SDP3, }; static const u32 aux1_sel_sdp[IGB_N_SDP] = { AUX1_SEL_SDP0, AUX1_SEL_SDP1, AUX1_SEL_SDP2, AUX1_SEL_SDP3, }; static const u32 ts_sdp_en[IGB_N_SDP] = { TS_SDP0_EN, TS_SDP1_EN, TS_SDP2_EN, TS_SDP3_EN, }; struct e1000_hw *hw = &igb->hw; u32 ctrl, ctrl_ext, tssdp = 0; ctrl = rd32(E1000_CTRL); ctrl_ext = rd32(E1000_CTRL_EXT); tssdp = rd32(E1000_TSSDP); igb_pin_direction(pin, 1, &ctrl, &ctrl_ext); /* Make sure this pin is not enabled as an output. */ tssdp &= ~ts_sdp_en[pin]; if (chan == 1) { tssdp &= ~AUX1_SEL_SDP3; tssdp |= aux1_sel_sdp[pin] | AUX1_TS_SDP_EN; } else { tssdp &= ~AUX0_SEL_SDP3; tssdp |= aux0_sel_sdp[pin] | AUX0_TS_SDP_EN; } wr32(E1000_TSSDP, tssdp); wr32(E1000_CTRL, ctrl); wr32(E1000_CTRL_EXT, ctrl_ext); } static void igb_pin_perout(struct igb_adapter *igb, int chan, int pin, int freq) { static const u32 aux0_sel_sdp[IGB_N_SDP] = { AUX0_SEL_SDP0, AUX0_SEL_SDP1, AUX0_SEL_SDP2, AUX0_SEL_SDP3, }; static const u32 aux1_sel_sdp[IGB_N_SDP] = { AUX1_SEL_SDP0, AUX1_SEL_SDP1, AUX1_SEL_SDP2, AUX1_SEL_SDP3, }; static const u32 ts_sdp_en[IGB_N_SDP] = { TS_SDP0_EN, TS_SDP1_EN, TS_SDP2_EN, TS_SDP3_EN, }; static const u32 ts_sdp_sel_tt0[IGB_N_SDP] = { TS_SDP0_SEL_TT0, TS_SDP1_SEL_TT0, TS_SDP2_SEL_TT0, TS_SDP3_SEL_TT0, }; static const u32 ts_sdp_sel_tt1[IGB_N_SDP] = { TS_SDP0_SEL_TT1, TS_SDP1_SEL_TT1, TS_SDP2_SEL_TT1, TS_SDP3_SEL_TT1, }; static const u32 ts_sdp_sel_fc0[IGB_N_SDP] = { TS_SDP0_SEL_FC0, TS_SDP1_SEL_FC0, TS_SDP2_SEL_FC0, TS_SDP3_SEL_FC0, }; static const u32 ts_sdp_sel_fc1[IGB_N_SDP] = { TS_SDP0_SEL_FC1, TS_SDP1_SEL_FC1, TS_SDP2_SEL_FC1, TS_SDP3_SEL_FC1, }; static const u32 ts_sdp_sel_clr[IGB_N_SDP] = { TS_SDP0_SEL_FC1, TS_SDP1_SEL_FC1, TS_SDP2_SEL_FC1, TS_SDP3_SEL_FC1, }; struct e1000_hw *hw = &igb->hw; u32 ctrl, ctrl_ext, tssdp = 0; ctrl = rd32(E1000_CTRL); ctrl_ext = rd32(E1000_CTRL_EXT); tssdp = rd32(E1000_TSSDP); igb_pin_direction(pin, 0, &ctrl, &ctrl_ext); /* Make sure this pin is not enabled as an input. */ if ((tssdp & AUX0_SEL_SDP3) == aux0_sel_sdp[pin]) tssdp &= ~AUX0_TS_SDP_EN; if ((tssdp & AUX1_SEL_SDP3) == aux1_sel_sdp[pin]) tssdp &= ~AUX1_TS_SDP_EN; tssdp &= ~ts_sdp_sel_clr[pin]; if (freq) { if (chan == 1) tssdp |= ts_sdp_sel_fc1[pin]; else tssdp |= ts_sdp_sel_fc0[pin]; } else { if (chan == 1) tssdp |= ts_sdp_sel_tt1[pin]; else tssdp |= ts_sdp_sel_tt0[pin]; } tssdp |= ts_sdp_en[pin]; wr32(E1000_TSSDP, tssdp); wr32(E1000_CTRL, ctrl); wr32(E1000_CTRL_EXT, ctrl_ext); } static int igb_ptp_feature_enable_82580(struct ptp_clock_info *ptp, struct ptp_clock_request *rq, int on) { struct igb_adapter *igb = container_of(ptp, struct igb_adapter, ptp_caps); u32 tsauxc, tsim, tsauxc_mask, tsim_mask, trgttiml, trgttimh, systiml, systimh, level_mask, level, rem; struct e1000_hw *hw = &igb->hw; struct timespec64 ts, start; unsigned long flags; u64 systim, now; int pin = -1; s64 ns; switch (rq->type) { case PTP_CLK_REQ_EXTTS: /* Reject requests with unsupported flags */ if (rq->extts.flags & ~(PTP_ENABLE_FEATURE | PTP_RISING_EDGE | PTP_FALLING_EDGE | PTP_STRICT_FLAGS)) return -EOPNOTSUPP; if (on) { pin = ptp_find_pin(igb->ptp_clock, PTP_PF_EXTTS, rq->extts.index); if (pin < 0) return -EBUSY; } if (rq->extts.index == 1) { tsauxc_mask = TSAUXC_EN_TS1; tsim_mask = TSINTR_AUTT1; } else { tsauxc_mask = TSAUXC_EN_TS0; tsim_mask = TSINTR_AUTT0; } spin_lock_irqsave(&igb->tmreg_lock, flags); tsauxc = rd32(E1000_TSAUXC); tsim = rd32(E1000_TSIM); if (on) { igb_pin_extts(igb, rq->extts.index, pin); tsauxc |= tsauxc_mask; tsim |= tsim_mask; } else { tsauxc &= ~tsauxc_mask; tsim &= ~tsim_mask; } wr32(E1000_TSAUXC, tsauxc); wr32(E1000_TSIM, tsim); spin_unlock_irqrestore(&igb->tmreg_lock, flags); return 0; case PTP_CLK_REQ_PEROUT: /* Reject requests with unsupported flags */ if (rq->perout.flags) return -EOPNOTSUPP; if (on) { pin = ptp_find_pin(igb->ptp_clock, PTP_PF_PEROUT, rq->perout.index); if (pin < 0) return -EBUSY; } ts.tv_sec = rq->perout.period.sec; ts.tv_nsec = rq->perout.period.nsec; ns = timespec64_to_ns(&ts); ns = ns >> 1; if (on && ns < 8LL) return -EINVAL; ts = ns_to_timespec64(ns); if (rq->perout.index == 1) { tsauxc_mask = TSAUXC_EN_TT1; tsim_mask = TSINTR_TT1; trgttiml = E1000_TRGTTIML1; trgttimh = E1000_TRGTTIMH1; } else { tsauxc_mask = TSAUXC_EN_TT0; tsim_mask = TSINTR_TT0; trgttiml = E1000_TRGTTIML0; trgttimh = E1000_TRGTTIMH0; } spin_lock_irqsave(&igb->tmreg_lock, flags); tsauxc = rd32(E1000_TSAUXC); tsim = rd32(E1000_TSIM); if (rq->perout.index == 1) { tsauxc &= ~(TSAUXC_EN_TT1 | TSAUXC_EN_CLK1 | TSAUXC_ST1); tsim &= ~TSINTR_TT1; } else { tsauxc &= ~(TSAUXC_EN_TT0 | TSAUXC_EN_CLK0 | TSAUXC_ST0); tsim &= ~TSINTR_TT0; } if (on) { int i = rq->perout.index; /* read systim registers in sequence */ rd32(E1000_SYSTIMR); systiml = rd32(E1000_SYSTIML); systimh = rd32(E1000_SYSTIMH); systim = (((u64)(systimh & 0xFF)) << 32) | ((u64)systiml); now = timecounter_cyc2time(&igb->tc, systim); if (pin < 2) { level_mask = (i == 1) ? 0x80000 : 0x40000; level = (rd32(E1000_CTRL) & level_mask) ? 1 : 0; } else { level_mask = (i == 1) ? 0x80 : 0x40; level = (rd32(E1000_CTRL_EXT) & level_mask) ? 1 : 0; } div_u64_rem(now, ns, &rem); systim = systim + (ns - rem); /* synchronize pin level with rising/falling edges */ div_u64_rem(now, ns << 1, &rem); if (rem < ns) { /* first half of period */ if (level == 0) { /* output is already low, skip this period */ systim += ns; } } else { /* second half of period */ if (level == 1) { /* output is already high, skip this period */ systim += ns; } } start = ns_to_timespec64(systim + (ns - rem)); igb_pin_perout(igb, i, pin, 0); igb->perout[i].start.tv_sec = start.tv_sec; igb->perout[i].start.tv_nsec = start.tv_nsec; igb->perout[i].period.tv_sec = ts.tv_sec; igb->perout[i].period.tv_nsec = ts.tv_nsec; wr32(trgttiml, (u32)systim); wr32(trgttimh, ((u32)(systim >> 32)) & 0xFF); tsauxc |= tsauxc_mask; tsim |= tsim_mask; } wr32(E1000_TSAUXC, tsauxc); wr32(E1000_TSIM, tsim); spin_unlock_irqrestore(&igb->tmreg_lock, flags); return 0; case PTP_CLK_REQ_PPS: return -EOPNOTSUPP; } return -EOPNOTSUPP; } static int igb_ptp_feature_enable_i210(struct ptp_clock_info *ptp, struct ptp_clock_request *rq, int on) { struct igb_adapter *igb = container_of(ptp, struct igb_adapter, ptp_caps); struct e1000_hw *hw = &igb->hw; u32 tsauxc, tsim, tsauxc_mask, tsim_mask, trgttiml, trgttimh, freqout; unsigned long flags; struct timespec64 ts; int use_freq = 0, pin = -1; s64 ns; switch (rq->type) { case PTP_CLK_REQ_EXTTS: /* Reject requests with unsupported flags */ if (rq->extts.flags & ~(PTP_ENABLE_FEATURE | PTP_RISING_EDGE | PTP_FALLING_EDGE | PTP_STRICT_FLAGS)) return -EOPNOTSUPP; /* Reject requests failing to enable both edges. */ if ((rq->extts.flags & PTP_STRICT_FLAGS) && (rq->extts.flags & PTP_ENABLE_FEATURE) && (rq->extts.flags & PTP_EXTTS_EDGES) != PTP_EXTTS_EDGES) return -EOPNOTSUPP; if (on) { pin = ptp_find_pin(igb->ptp_clock, PTP_PF_EXTTS, rq->extts.index); if (pin < 0) return -EBUSY; } if (rq->extts.index == 1) { tsauxc_mask = TSAUXC_EN_TS1; tsim_mask = TSINTR_AUTT1; } else { tsauxc_mask = TSAUXC_EN_TS0; tsim_mask = TSINTR_AUTT0; } spin_lock_irqsave(&igb->tmreg_lock, flags); tsauxc = rd32(E1000_TSAUXC); tsim = rd32(E1000_TSIM); if (on) { igb_pin_extts(igb, rq->extts.index, pin); tsauxc |= tsauxc_mask; tsim |= tsim_mask; } else { tsauxc &= ~tsauxc_mask; tsim &= ~tsim_mask; } wr32(E1000_TSAUXC, tsauxc); wr32(E1000_TSIM, tsim); spin_unlock_irqrestore(&igb->tmreg_lock, flags); return 0; case PTP_CLK_REQ_PEROUT: /* Reject requests with unsupported flags */ if (rq->perout.flags) return -EOPNOTSUPP; if (on) { pin = ptp_find_pin(igb->ptp_clock, PTP_PF_PEROUT, rq->perout.index); if (pin < 0) return -EBUSY; } ts.tv_sec = rq->perout.period.sec; ts.tv_nsec = rq->perout.period.nsec; ns = timespec64_to_ns(&ts); ns = ns >> 1; if (on && ((ns <= 70000000LL) || (ns == 125000000LL) || (ns == 250000000LL) || (ns == 500000000LL))) { if (ns < 8LL) return -EINVAL; use_freq = 1; } ts = ns_to_timespec64(ns); if (rq->perout.index == 1) { if (use_freq) { tsauxc_mask = TSAUXC_EN_CLK1 | TSAUXC_ST1; tsim_mask = 0; } else { tsauxc_mask = TSAUXC_EN_TT1; tsim_mask = TSINTR_TT1; } trgttiml = E1000_TRGTTIML1; trgttimh = E1000_TRGTTIMH1; freqout = E1000_FREQOUT1; } else { if (use_freq) { tsauxc_mask = TSAUXC_EN_CLK0 | TSAUXC_ST0; tsim_mask = 0; } else { tsauxc_mask = TSAUXC_EN_TT0; tsim_mask = TSINTR_TT0; } trgttiml = E1000_TRGTTIML0; trgttimh = E1000_TRGTTIMH0; freqout = E1000_FREQOUT0; } spin_lock_irqsave(&igb->tmreg_lock, flags); tsauxc = rd32(E1000_TSAUXC); tsim = rd32(E1000_TSIM); if (rq->perout.index == 1) { tsauxc &= ~(TSAUXC_EN_TT1 | TSAUXC_EN_CLK1 | TSAUXC_ST1); tsim &= ~TSINTR_TT1; } else { tsauxc &= ~(TSAUXC_EN_TT0 | TSAUXC_EN_CLK0 | TSAUXC_ST0); tsim &= ~TSINTR_TT0; } if (on) { int i = rq->perout.index; igb_pin_perout(igb, i, pin, use_freq); igb->perout[i].start.tv_sec = rq->perout.start.sec; igb->perout[i].start.tv_nsec = rq->perout.start.nsec; igb->perout[i].period.tv_sec = ts.tv_sec; igb->perout[i].period.tv_nsec = ts.tv_nsec; wr32(trgttimh, rq->perout.start.sec); wr32(trgttiml, rq->perout.start.nsec); if (use_freq) wr32(freqout, ns); tsauxc |= tsauxc_mask; tsim |= tsim_mask; } wr32(E1000_TSAUXC, tsauxc); wr32(E1000_TSIM, tsim); spin_unlock_irqrestore(&igb->tmreg_lock, flags); return 0; case PTP_CLK_REQ_PPS: spin_lock_irqsave(&igb->tmreg_lock, flags); tsim = rd32(E1000_TSIM); if (on) tsim |= TSINTR_SYS_WRAP; else tsim &= ~TSINTR_SYS_WRAP; igb->pps_sys_wrap_on = !!on; wr32(E1000_TSIM, tsim); spin_unlock_irqrestore(&igb->tmreg_lock, flags); return 0; } return -EOPNOTSUPP; } static int igb_ptp_feature_enable(struct ptp_clock_info *ptp, struct ptp_clock_request *rq, int on) { return -EOPNOTSUPP; } static int igb_ptp_verify_pin(struct ptp_clock_info *ptp, unsigned int pin, enum ptp_pin_function func, unsigned int chan) { switch (func) { case PTP_PF_NONE: case PTP_PF_EXTTS: case PTP_PF_PEROUT: break; case PTP_PF_PHYSYNC: return -1; } return 0; } /** * igb_ptp_tx_work * @work: pointer to work struct * * This work function polls the TSYNCTXCTL valid bit to determine when a * timestamp has been taken for the current stored skb. **/ static void igb_ptp_tx_work(struct work_struct *work) { struct igb_adapter *adapter = container_of(work, struct igb_adapter, ptp_tx_work); struct e1000_hw *hw = &adapter->hw; u32 tsynctxctl; if (!adapter->ptp_tx_skb) return; if (time_is_before_jiffies(adapter->ptp_tx_start + IGB_PTP_TX_TIMEOUT)) { dev_kfree_skb_any(adapter->ptp_tx_skb); adapter->ptp_tx_skb = NULL; clear_bit_unlock(__IGB_PTP_TX_IN_PROGRESS, &adapter->state); adapter->tx_hwtstamp_timeouts++; /* Clear the tx valid bit in TSYNCTXCTL register to enable * interrupt */ rd32(E1000_TXSTMPH); dev_warn(&adapter->pdev->dev, "clearing Tx timestamp hang\n"); return; } tsynctxctl = rd32(E1000_TSYNCTXCTL); if (tsynctxctl & E1000_TSYNCTXCTL_VALID) igb_ptp_tx_hwtstamp(adapter); else /* reschedule to check later */ schedule_work(&adapter->ptp_tx_work); } static void igb_ptp_overflow_check(struct work_struct *work) { struct igb_adapter *igb = container_of(work, struct igb_adapter, ptp_overflow_work.work); struct timespec64 ts; u64 ns; /* Update the timecounter */ ns = timecounter_read(&igb->tc); ts = ns_to_timespec64(ns); pr_debug("igb overflow check at %lld.%09lu\n", (long long) ts.tv_sec, ts.tv_nsec); schedule_delayed_work(&igb->ptp_overflow_work, IGB_SYSTIM_OVERFLOW_PERIOD); } /** * igb_ptp_rx_hang - detect error case when Rx timestamp registers latched * @adapter: private network adapter structure * * This watchdog task is scheduled to detect error case where hardware has * dropped an Rx packet that was timestamped when the ring is full. The * particular error is rare but leaves the device in a state unable to timestamp * any future packets. **/ void igb_ptp_rx_hang(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 tsyncrxctl = rd32(E1000_TSYNCRXCTL); unsigned long rx_event; /* Other hardware uses per-packet timestamps */ if (hw->mac.type != e1000_82576) return; /* If we don't have a valid timestamp in the registers, just update the * timeout counter and exit */ if (!(tsyncrxctl & E1000_TSYNCRXCTL_VALID)) { adapter->last_rx_ptp_check = jiffies; return; } /* Determine the most recent watchdog or rx_timestamp event */ rx_event = adapter->last_rx_ptp_check; if (time_after(adapter->last_rx_timestamp, rx_event)) rx_event = adapter->last_rx_timestamp; /* Only need to read the high RXSTMP register to clear the lock */ if (time_is_before_jiffies(rx_event + 5 * HZ)) { rd32(E1000_RXSTMPH); adapter->last_rx_ptp_check = jiffies; adapter->rx_hwtstamp_cleared++; dev_warn(&adapter->pdev->dev, "clearing Rx timestamp hang\n"); } } /** * igb_ptp_tx_hang - detect error case where Tx timestamp never finishes * @adapter: private network adapter structure */ void igb_ptp_tx_hang(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; bool timeout = time_is_before_jiffies(adapter->ptp_tx_start + IGB_PTP_TX_TIMEOUT); if (!adapter->ptp_tx_skb) return; if (!test_bit(__IGB_PTP_TX_IN_PROGRESS, &adapter->state)) return; /* If we haven't received a timestamp within the timeout, it is * reasonable to assume that it will never occur, so we can unlock the * timestamp bit when this occurs. */ if (timeout) { cancel_work_sync(&adapter->ptp_tx_work); dev_kfree_skb_any(adapter->ptp_tx_skb); adapter->ptp_tx_skb = NULL; clear_bit_unlock(__IGB_PTP_TX_IN_PROGRESS, &adapter->state); adapter->tx_hwtstamp_timeouts++; /* Clear the tx valid bit in TSYNCTXCTL register to enable * interrupt */ rd32(E1000_TXSTMPH); dev_warn(&adapter->pdev->dev, "clearing Tx timestamp hang\n"); } } /** * igb_ptp_tx_hwtstamp - utility function which checks for TX time stamp * @adapter: Board private structure. * * If we were asked to do hardware stamping and such a time stamp is * available, then it must have been for this skb here because we only * allow only one such packet into the queue. **/ static void igb_ptp_tx_hwtstamp(struct igb_adapter *adapter) { struct sk_buff *skb = adapter->ptp_tx_skb; struct e1000_hw *hw = &adapter->hw; struct skb_shared_hwtstamps shhwtstamps; u64 regval; int adjust = 0; regval = rd32(E1000_TXSTMPL); regval |= (u64)rd32(E1000_TXSTMPH) << 32; igb_ptp_systim_to_hwtstamp(adapter, &shhwtstamps, regval); /* adjust timestamp for the TX latency based on link speed */ if (adapter->hw.mac.type == e1000_i210) { switch (adapter->link_speed) { case SPEED_10: adjust = IGB_I210_TX_LATENCY_10; break; case SPEED_100: adjust = IGB_I210_TX_LATENCY_100; break; case SPEED_1000: adjust = IGB_I210_TX_LATENCY_1000; break; } } shhwtstamps.hwtstamp = ktime_add_ns(shhwtstamps.hwtstamp, adjust); /* Clear the lock early before calling skb_tstamp_tx so that * applications are not woken up before the lock bit is clear. We use * a copy of the skb pointer to ensure other threads can't change it * while we're notifying the stack. */ adapter->ptp_tx_skb = NULL; clear_bit_unlock(__IGB_PTP_TX_IN_PROGRESS, &adapter->state); /* Notify the stack and free the skb after we've unlocked */ skb_tstamp_tx(skb, &shhwtstamps); dev_kfree_skb_any(skb); } /** * igb_ptp_rx_pktstamp - retrieve Rx per packet timestamp * @q_vector: Pointer to interrupt specific structure * @va: Pointer to address containing Rx buffer * @timestamp: Pointer where timestamp will be stored * * This function is meant to retrieve a timestamp from the first buffer of an * incoming frame. The value is stored in little endian format starting on * byte 8 * * Returns: The timestamp header length or 0 if not available **/ int igb_ptp_rx_pktstamp(struct igb_q_vector *q_vector, void *va, ktime_t *timestamp) { struct igb_adapter *adapter = q_vector->adapter; struct skb_shared_hwtstamps ts; __le64 *regval = (__le64 *)va; int adjust = 0; if (!(adapter->ptp_flags & IGB_PTP_ENABLED)) return 0; /* The timestamp is recorded in little endian format. * DWORD: 0 1 2 3 * Field: Reserved Reserved SYSTIML SYSTIMH */ /* check reserved dwords are zero, be/le doesn't matter for zero */ if (regval[0]) return 0; igb_ptp_systim_to_hwtstamp(adapter, &ts, le64_to_cpu(regval[1])); /* adjust timestamp for the RX latency based on link speed */ if (adapter->hw.mac.type == e1000_i210) { switch (adapter->link_speed) { case SPEED_10: adjust = IGB_I210_RX_LATENCY_10; break; case SPEED_100: adjust = IGB_I210_RX_LATENCY_100; break; case SPEED_1000: adjust = IGB_I210_RX_LATENCY_1000; break; } } *timestamp = ktime_sub_ns(ts.hwtstamp, adjust); return IGB_TS_HDR_LEN; } /** * igb_ptp_rx_rgtstamp - retrieve Rx timestamp stored in register * @q_vector: Pointer to interrupt specific structure * @skb: Buffer containing timestamp and packet * * This function is meant to retrieve a timestamp from the internal registers * of the adapter and store it in the skb. **/ void igb_ptp_rx_rgtstamp(struct igb_q_vector *q_vector, struct sk_buff *skb) { struct igb_adapter *adapter = q_vector->adapter; struct e1000_hw *hw = &adapter->hw; int adjust = 0; u64 regval; if (!(adapter->ptp_flags & IGB_PTP_ENABLED)) return; /* If this bit is set, then the RX registers contain the time stamp. No * other packet will be time stamped until we read these registers, so * read the registers to make them available again. Because only one * packet can be time stamped at a time, we know that the register * values must belong to this one here and therefore we don't need to * compare any of the additional attributes stored for it. * * If nothing went wrong, then it should have a shared tx_flags that we * can turn into a skb_shared_hwtstamps. */ if (!(rd32(E1000_TSYNCRXCTL) & E1000_TSYNCRXCTL_VALID)) return; regval = rd32(E1000_RXSTMPL); regval |= (u64)rd32(E1000_RXSTMPH) << 32; igb_ptp_systim_to_hwtstamp(adapter, skb_hwtstamps(skb), regval); /* adjust timestamp for the RX latency based on link speed */ if (adapter->hw.mac.type == e1000_i210) { switch (adapter->link_speed) { case SPEED_10: adjust = IGB_I210_RX_LATENCY_10; break; case SPEED_100: adjust = IGB_I210_RX_LATENCY_100; break; case SPEED_1000: adjust = IGB_I210_RX_LATENCY_1000; break; } } skb_hwtstamps(skb)->hwtstamp = ktime_sub_ns(skb_hwtstamps(skb)->hwtstamp, adjust); /* Update the last_rx_timestamp timer in order to enable watchdog check * for error case of latched timestamp on a dropped packet. */ adapter->last_rx_timestamp = jiffies; } /** * igb_ptp_get_ts_config - get hardware time stamping config * @netdev: netdev struct * @ifr: interface struct * * Get the hwtstamp_config settings to return to the user. Rather than attempt * to deconstruct the settings from the registers, just return a shadow copy * of the last known settings. **/ int igb_ptp_get_ts_config(struct net_device *netdev, struct ifreq *ifr) { struct igb_adapter *adapter = netdev_priv(netdev); struct hwtstamp_config *config = &adapter->tstamp_config; return copy_to_user(ifr->ifr_data, config, sizeof(*config)) ? -EFAULT : 0; } /** * igb_ptp_set_timestamp_mode - setup hardware for timestamping * @adapter: networking device structure * @config: hwtstamp configuration * * Outgoing time stamping can be enabled and disabled. Play nice and * disable it when requested, although it shouldn't case any overhead * when no packet needs it. At most one packet in the queue may be * marked for time stamping, otherwise it would be impossible to tell * for sure to which packet the hardware time stamp belongs. * * Incoming time stamping has to be configured via the hardware * filters. Not all combinations are supported, in particular event * type has to be specified. Matching the kind of event packet is * not supported, with the exception of "all V2 events regardless of * level 2 or 4". */ static int igb_ptp_set_timestamp_mode(struct igb_adapter *adapter, struct hwtstamp_config *config) { struct e1000_hw *hw = &adapter->hw; u32 tsync_tx_ctl = E1000_TSYNCTXCTL_ENABLED; u32 tsync_rx_ctl = E1000_TSYNCRXCTL_ENABLED; u32 tsync_rx_cfg = 0; bool is_l4 = false; bool is_l2 = false; u32 regval; switch (config->tx_type) { case HWTSTAMP_TX_OFF: tsync_tx_ctl = 0; break; case HWTSTAMP_TX_ON: break; default: return -ERANGE; } switch (config->rx_filter) { case HWTSTAMP_FILTER_NONE: tsync_rx_ctl = 0; break; case HWTSTAMP_FILTER_PTP_V1_L4_SYNC: tsync_rx_ctl |= E1000_TSYNCRXCTL_TYPE_L4_V1; tsync_rx_cfg = E1000_TSYNCRXCFG_PTP_V1_SYNC_MESSAGE; is_l4 = true; break; case HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ: tsync_rx_ctl |= E1000_TSYNCRXCTL_TYPE_L4_V1; tsync_rx_cfg = E1000_TSYNCRXCFG_PTP_V1_DELAY_REQ_MESSAGE; is_l4 = true; break; case HWTSTAMP_FILTER_PTP_V2_EVENT: case HWTSTAMP_FILTER_PTP_V2_L2_EVENT: case HWTSTAMP_FILTER_PTP_V2_L4_EVENT: case HWTSTAMP_FILTER_PTP_V2_SYNC: case HWTSTAMP_FILTER_PTP_V2_L2_SYNC: case HWTSTAMP_FILTER_PTP_V2_L4_SYNC: case HWTSTAMP_FILTER_PTP_V2_DELAY_REQ: case HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ: case HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ: tsync_rx_ctl |= E1000_TSYNCRXCTL_TYPE_EVENT_V2; config->rx_filter = HWTSTAMP_FILTER_PTP_V2_EVENT; is_l2 = true; is_l4 = true; break; case HWTSTAMP_FILTER_PTP_V1_L4_EVENT: case HWTSTAMP_FILTER_NTP_ALL: case HWTSTAMP_FILTER_ALL: /* 82576 cannot timestamp all packets, which it needs to do to * support both V1 Sync and Delay_Req messages */ if (hw->mac.type != e1000_82576) { tsync_rx_ctl |= E1000_TSYNCRXCTL_TYPE_ALL; config->rx_filter = HWTSTAMP_FILTER_ALL; break; } fallthrough; default: config->rx_filter = HWTSTAMP_FILTER_NONE; return -ERANGE; } if (hw->mac.type == e1000_82575) { if (tsync_rx_ctl | tsync_tx_ctl) return -EINVAL; return 0; } /* Per-packet timestamping only works if all packets are * timestamped, so enable timestamping in all packets as * long as one Rx filter was configured. */ if ((hw->mac.type >= e1000_82580) && tsync_rx_ctl) { tsync_rx_ctl = E1000_TSYNCRXCTL_ENABLED; tsync_rx_ctl |= E1000_TSYNCRXCTL_TYPE_ALL; config->rx_filter = HWTSTAMP_FILTER_ALL; is_l2 = true; is_l4 = true; if ((hw->mac.type == e1000_i210) || (hw->mac.type == e1000_i211)) { regval = rd32(E1000_RXPBS); regval |= E1000_RXPBS_CFG_TS_EN; wr32(E1000_RXPBS, regval); } } /* enable/disable TX */ regval = rd32(E1000_TSYNCTXCTL); regval &= ~E1000_TSYNCTXCTL_ENABLED; regval |= tsync_tx_ctl; wr32(E1000_TSYNCTXCTL, regval); /* enable/disable RX */ regval = rd32(E1000_TSYNCRXCTL); regval &= ~(E1000_TSYNCRXCTL_ENABLED | E1000_TSYNCRXCTL_TYPE_MASK); regval |= tsync_rx_ctl; wr32(E1000_TSYNCRXCTL, regval); /* define which PTP packets are time stamped */ wr32(E1000_TSYNCRXCFG, tsync_rx_cfg); /* define ethertype filter for timestamped packets */ if (is_l2) wr32(E1000_ETQF(IGB_ETQF_FILTER_1588), (E1000_ETQF_FILTER_ENABLE | /* enable filter */ E1000_ETQF_1588 | /* enable timestamping */ ETH_P_1588)); /* 1588 eth protocol type */ else wr32(E1000_ETQF(IGB_ETQF_FILTER_1588), 0); /* L4 Queue Filter[3]: filter by destination port and protocol */ if (is_l4) { u32 ftqf = (IPPROTO_UDP /* UDP */ | E1000_FTQF_VF_BP /* VF not compared */ | E1000_FTQF_1588_TIME_STAMP /* Enable Timestamping */ | E1000_FTQF_MASK); /* mask all inputs */ ftqf &= ~E1000_FTQF_MASK_PROTO_BP; /* enable protocol check */ wr32(E1000_IMIR(3), (__force unsigned int)htons(PTP_EV_PORT)); wr32(E1000_IMIREXT(3), (E1000_IMIREXT_SIZE_BP | E1000_IMIREXT_CTRL_BP)); if (hw->mac.type == e1000_82576) { /* enable source port check */ wr32(E1000_SPQF(3), (__force unsigned int)htons(PTP_EV_PORT)); ftqf &= ~E1000_FTQF_MASK_SOURCE_PORT_BP; } wr32(E1000_FTQF(3), ftqf); } else { wr32(E1000_FTQF(3), E1000_FTQF_MASK); } wrfl(); /* clear TX/RX time stamp registers, just to be sure */ regval = rd32(E1000_TXSTMPL); regval = rd32(E1000_TXSTMPH); regval = rd32(E1000_RXSTMPL); regval = rd32(E1000_RXSTMPH); return 0; } /** * igb_ptp_set_ts_config - set hardware time stamping config * @netdev: netdev struct * @ifr: interface struct * **/ int igb_ptp_set_ts_config(struct net_device *netdev, struct ifreq *ifr) { struct igb_adapter *adapter = netdev_priv(netdev); struct hwtstamp_config config; int err; if (copy_from_user(&config, ifr->ifr_data, sizeof(config))) return -EFAULT; err = igb_ptp_set_timestamp_mode(adapter, &config); if (err) return err; /* save these settings for future reference */ memcpy(&adapter->tstamp_config, &config, sizeof(adapter->tstamp_config)); return copy_to_user(ifr->ifr_data, &config, sizeof(config)) ? -EFAULT : 0; } /** * igb_ptp_init - Initialize PTP functionality * @adapter: Board private structure * * This function is called at device probe to initialize the PTP * functionality. */ void igb_ptp_init(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; struct net_device *netdev = adapter->netdev; switch (hw->mac.type) { case e1000_82576: snprintf(adapter->ptp_caps.name, 16, "%pm", netdev->dev_addr); adapter->ptp_caps.owner = THIS_MODULE; adapter->ptp_caps.max_adj = 999999881; adapter->ptp_caps.n_ext_ts = 0; adapter->ptp_caps.pps = 0; adapter->ptp_caps.adjfine = igb_ptp_adjfine_82576; adapter->ptp_caps.adjtime = igb_ptp_adjtime_82576; adapter->ptp_caps.gettimex64 = igb_ptp_gettimex_82576; adapter->ptp_caps.settime64 = igb_ptp_settime_82576; adapter->ptp_caps.enable = igb_ptp_feature_enable; adapter->cc.read = igb_ptp_read_82576; adapter->cc.mask = CYCLECOUNTER_MASK(64); adapter->cc.mult = 1; adapter->cc.shift = IGB_82576_TSYNC_SHIFT; adapter->ptp_flags |= IGB_PTP_OVERFLOW_CHECK; break; case e1000_82580: case e1000_i354: case e1000_i350: igb_ptp_sdp_init(adapter); snprintf(adapter->ptp_caps.name, 16, "%pm", netdev->dev_addr); adapter->ptp_caps.owner = THIS_MODULE; adapter->ptp_caps.max_adj = 62499999; adapter->ptp_caps.n_ext_ts = IGB_N_EXTTS; adapter->ptp_caps.n_per_out = IGB_N_PEROUT; adapter->ptp_caps.n_pins = IGB_N_SDP; adapter->ptp_caps.pps = 0; adapter->ptp_caps.pin_config = adapter->sdp_config; adapter->ptp_caps.adjfine = igb_ptp_adjfine_82580; adapter->ptp_caps.adjtime = igb_ptp_adjtime_82576; adapter->ptp_caps.gettimex64 = igb_ptp_gettimex_82580; adapter->ptp_caps.settime64 = igb_ptp_settime_82576; adapter->ptp_caps.enable = igb_ptp_feature_enable_82580; adapter->ptp_caps.verify = igb_ptp_verify_pin; adapter->cc.read = igb_ptp_read_82580; adapter->cc.mask = CYCLECOUNTER_MASK(IGB_NBITS_82580); adapter->cc.mult = 1; adapter->cc.shift = 0; adapter->ptp_flags |= IGB_PTP_OVERFLOW_CHECK; break; case e1000_i210: case e1000_i211: igb_ptp_sdp_init(adapter); snprintf(adapter->ptp_caps.name, 16, "%pm", netdev->dev_addr); adapter->ptp_caps.owner = THIS_MODULE; adapter->ptp_caps.max_adj = 62499999; adapter->ptp_caps.n_ext_ts = IGB_N_EXTTS; adapter->ptp_caps.n_per_out = IGB_N_PEROUT; adapter->ptp_caps.n_pins = IGB_N_SDP; adapter->ptp_caps.pps = 1; adapter->ptp_caps.pin_config = adapter->sdp_config; adapter->ptp_caps.adjfine = igb_ptp_adjfine_82580; adapter->ptp_caps.adjtime = igb_ptp_adjtime_i210; adapter->ptp_caps.gettimex64 = igb_ptp_gettimex_i210; adapter->ptp_caps.settime64 = igb_ptp_settime_i210; adapter->ptp_caps.enable = igb_ptp_feature_enable_i210; adapter->ptp_caps.verify = igb_ptp_verify_pin; break; default: adapter->ptp_clock = NULL; return; } adapter->ptp_clock = ptp_clock_register(&adapter->ptp_caps, &adapter->pdev->dev); if (IS_ERR(adapter->ptp_clock)) { adapter->ptp_clock = NULL; dev_err(&adapter->pdev->dev, "ptp_clock_register failed\n"); } else if (adapter->ptp_clock) { dev_info(&adapter->pdev->dev, "added PHC on %s\n", adapter->netdev->name); adapter->ptp_flags |= IGB_PTP_ENABLED; spin_lock_init(&adapter->tmreg_lock); INIT_WORK(&adapter->ptp_tx_work, igb_ptp_tx_work); if (adapter->ptp_flags & IGB_PTP_OVERFLOW_CHECK) INIT_DELAYED_WORK(&adapter->ptp_overflow_work, igb_ptp_overflow_check); adapter->tstamp_config.rx_filter = HWTSTAMP_FILTER_NONE; adapter->tstamp_config.tx_type = HWTSTAMP_TX_OFF; igb_ptp_reset(adapter); } } /** * igb_ptp_sdp_init - utility function which inits the SDP config structs * @adapter: Board private structure. **/ void igb_ptp_sdp_init(struct igb_adapter *adapter) { int i; for (i = 0; i < IGB_N_SDP; i++) { struct ptp_pin_desc *ppd = &adapter->sdp_config[i]; snprintf(ppd->name, sizeof(ppd->name), "SDP%d", i); ppd->index = i; ppd->func = PTP_PF_NONE; } } /** * igb_ptp_suspend - Disable PTP work items and prepare for suspend * @adapter: Board private structure * * This function stops the overflow check work and PTP Tx timestamp work, and * will prepare the device for OS suspend. */ void igb_ptp_suspend(struct igb_adapter *adapter) { if (!(adapter->ptp_flags & IGB_PTP_ENABLED)) return; if (adapter->ptp_flags & IGB_PTP_OVERFLOW_CHECK) cancel_delayed_work_sync(&adapter->ptp_overflow_work); cancel_work_sync(&adapter->ptp_tx_work); if (adapter->ptp_tx_skb) { dev_kfree_skb_any(adapter->ptp_tx_skb); adapter->ptp_tx_skb = NULL; clear_bit_unlock(__IGB_PTP_TX_IN_PROGRESS, &adapter->state); } } /** * igb_ptp_stop - Disable PTP device and stop the overflow check. * @adapter: Board private structure. * * This function stops the PTP support and cancels the delayed work. **/ void igb_ptp_stop(struct igb_adapter *adapter) { igb_ptp_suspend(adapter); if (adapter->ptp_clock) { ptp_clock_unregister(adapter->ptp_clock); dev_info(&adapter->pdev->dev, "removed PHC on %s\n", adapter->netdev->name); adapter->ptp_flags &= ~IGB_PTP_ENABLED; } } /** * igb_ptp_reset - Re-enable the adapter for PTP following a reset. * @adapter: Board private structure. * * This function handles the reset work required to re-enable the PTP device. **/ void igb_ptp_reset(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; unsigned long flags; /* reset the tstamp_config */ igb_ptp_set_timestamp_mode(adapter, &adapter->tstamp_config); spin_lock_irqsave(&adapter->tmreg_lock, flags); switch (adapter->hw.mac.type) { case e1000_82576: /* Dial the nominal frequency. */ wr32(E1000_TIMINCA, INCPERIOD_82576 | INCVALUE_82576); break; case e1000_82580: case e1000_i354: case e1000_i350: case e1000_i210: case e1000_i211: wr32(E1000_TSAUXC, 0x0); wr32(E1000_TSSDP, 0x0); wr32(E1000_TSIM, TSYNC_INTERRUPTS | (adapter->pps_sys_wrap_on ? TSINTR_SYS_WRAP : 0)); wr32(E1000_IMS, E1000_IMS_TS); break; default: /* No work to do. */ goto out; } /* Re-initialize the timer. */ if ((hw->mac.type == e1000_i210) || (hw->mac.type == e1000_i211)) { struct timespec64 ts = ktime_to_timespec64(ktime_get_real()); igb_ptp_write_i210(adapter, &ts); } else { timecounter_init(&adapter->tc, &adapter->cc, ktime_to_ns(ktime_get_real())); } out: spin_unlock_irqrestore(&adapter->tmreg_lock, flags); wrfl(); if (adapter->ptp_flags & IGB_PTP_OVERFLOW_CHECK) schedule_delayed_work(&adapter->ptp_overflow_work, IGB_SYSTIM_OVERFLOW_PERIOD); }
linux-master
drivers/net/ethernet/intel/igb/igb_ptp.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2007 - 2018 Intel Corporation. */ #include <linux/if_ether.h> #include <linux/delay.h> #include "e1000_mac.h" #include "e1000_phy.h" static s32 igb_phy_setup_autoneg(struct e1000_hw *hw); static void igb_phy_force_speed_duplex_setup(struct e1000_hw *hw, u16 *phy_ctrl); static s32 igb_wait_autoneg(struct e1000_hw *hw); static s32 igb_set_master_slave_mode(struct e1000_hw *hw); /* Cable length tables */ static const u16 e1000_m88_cable_length_table[] = { 0, 50, 80, 110, 140, 140, E1000_CABLE_LENGTH_UNDEFINED }; static const u16 e1000_igp_2_cable_length_table[] = { 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 8, 11, 13, 16, 18, 21, 0, 0, 0, 3, 6, 10, 13, 16, 19, 23, 26, 29, 32, 35, 38, 41, 6, 10, 14, 18, 22, 26, 30, 33, 37, 41, 44, 48, 51, 54, 58, 61, 21, 26, 31, 35, 40, 44, 49, 53, 57, 61, 65, 68, 72, 75, 79, 82, 40, 45, 51, 56, 61, 66, 70, 75, 79, 83, 87, 91, 94, 98, 101, 104, 60, 66, 72, 77, 82, 87, 92, 96, 100, 104, 108, 111, 114, 117, 119, 121, 83, 89, 95, 100, 105, 109, 113, 116, 119, 122, 124, 104, 109, 114, 118, 121, 124}; /** * igb_check_reset_block - Check if PHY reset is blocked * @hw: pointer to the HW structure * * Read the PHY management control register and check whether a PHY reset * is blocked. If a reset is not blocked return 0, otherwise * return E1000_BLK_PHY_RESET (12). **/ s32 igb_check_reset_block(struct e1000_hw *hw) { u32 manc; manc = rd32(E1000_MANC); return (manc & E1000_MANC_BLK_PHY_RST_ON_IDE) ? E1000_BLK_PHY_RESET : 0; } /** * igb_get_phy_id - Retrieve the PHY ID and revision * @hw: pointer to the HW structure * * Reads the PHY registers and stores the PHY ID and possibly the PHY * revision in the hardware structure. **/ s32 igb_get_phy_id(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val = 0; u16 phy_id; /* ensure PHY page selection to fix misconfigured i210 */ if ((hw->mac.type == e1000_i210) || (hw->mac.type == e1000_i211)) phy->ops.write_reg(hw, I347AT4_PAGE_SELECT, 0); ret_val = phy->ops.read_reg(hw, PHY_ID1, &phy_id); if (ret_val) goto out; phy->id = (u32)(phy_id << 16); udelay(20); ret_val = phy->ops.read_reg(hw, PHY_ID2, &phy_id); if (ret_val) goto out; phy->id |= (u32)(phy_id & PHY_REVISION_MASK); phy->revision = (u32)(phy_id & ~PHY_REVISION_MASK); out: return ret_val; } /** * igb_phy_reset_dsp - Reset PHY DSP * @hw: pointer to the HW structure * * Reset the digital signal processor. **/ static s32 igb_phy_reset_dsp(struct e1000_hw *hw) { s32 ret_val = 0; if (!(hw->phy.ops.write_reg)) goto out; ret_val = hw->phy.ops.write_reg(hw, M88E1000_PHY_GEN_CONTROL, 0xC1); if (ret_val) goto out; ret_val = hw->phy.ops.write_reg(hw, M88E1000_PHY_GEN_CONTROL, 0); out: return ret_val; } /** * igb_read_phy_reg_mdic - Read MDI control register * @hw: pointer to the HW structure * @offset: register offset to be read * @data: pointer to the read data * * Reads the MDI control register in the PHY at offset and stores the * information read to data. **/ s32 igb_read_phy_reg_mdic(struct e1000_hw *hw, u32 offset, u16 *data) { struct e1000_phy_info *phy = &hw->phy; u32 i, mdic = 0; s32 ret_val = 0; if (offset > MAX_PHY_REG_ADDRESS) { hw_dbg("PHY Address %d is out of range\n", offset); ret_val = -E1000_ERR_PARAM; goto out; } /* Set up Op-code, Phy Address, and register offset in the MDI * Control register. The MAC will take care of interfacing with the * PHY to retrieve the desired data. */ mdic = ((offset << E1000_MDIC_REG_SHIFT) | (phy->addr << E1000_MDIC_PHY_SHIFT) | (E1000_MDIC_OP_READ)); wr32(E1000_MDIC, mdic); /* Poll the ready bit to see if the MDI read completed * Increasing the time out as testing showed failures with * the lower time out */ for (i = 0; i < (E1000_GEN_POLL_TIMEOUT * 3); i++) { udelay(50); mdic = rd32(E1000_MDIC); if (mdic & E1000_MDIC_READY) break; } if (!(mdic & E1000_MDIC_READY)) { hw_dbg("MDI Read did not complete\n"); ret_val = -E1000_ERR_PHY; goto out; } if (mdic & E1000_MDIC_ERROR) { hw_dbg("MDI Error\n"); ret_val = -E1000_ERR_PHY; goto out; } *data = (u16) mdic; out: return ret_val; } /** * igb_write_phy_reg_mdic - Write MDI control register * @hw: pointer to the HW structure * @offset: register offset to write to * @data: data to write to register at offset * * Writes data to MDI control register in the PHY at offset. **/ s32 igb_write_phy_reg_mdic(struct e1000_hw *hw, u32 offset, u16 data) { struct e1000_phy_info *phy = &hw->phy; u32 i, mdic = 0; s32 ret_val = 0; if (offset > MAX_PHY_REG_ADDRESS) { hw_dbg("PHY Address %d is out of range\n", offset); ret_val = -E1000_ERR_PARAM; goto out; } /* Set up Op-code, Phy Address, and register offset in the MDI * Control register. The MAC will take care of interfacing with the * PHY to retrieve the desired data. */ mdic = (((u32)data) | (offset << E1000_MDIC_REG_SHIFT) | (phy->addr << E1000_MDIC_PHY_SHIFT) | (E1000_MDIC_OP_WRITE)); wr32(E1000_MDIC, mdic); /* Poll the ready bit to see if the MDI read completed * Increasing the time out as testing showed failures with * the lower time out */ for (i = 0; i < (E1000_GEN_POLL_TIMEOUT * 3); i++) { udelay(50); mdic = rd32(E1000_MDIC); if (mdic & E1000_MDIC_READY) break; } if (!(mdic & E1000_MDIC_READY)) { hw_dbg("MDI Write did not complete\n"); ret_val = -E1000_ERR_PHY; goto out; } if (mdic & E1000_MDIC_ERROR) { hw_dbg("MDI Error\n"); ret_val = -E1000_ERR_PHY; goto out; } out: return ret_val; } /** * igb_read_phy_reg_i2c - Read PHY register using i2c * @hw: pointer to the HW structure * @offset: register offset to be read * @data: pointer to the read data * * Reads the PHY register at offset using the i2c interface and stores the * retrieved information in data. **/ s32 igb_read_phy_reg_i2c(struct e1000_hw *hw, u32 offset, u16 *data) { struct e1000_phy_info *phy = &hw->phy; u32 i, i2ccmd = 0; /* Set up Op-code, Phy Address, and register address in the I2CCMD * register. The MAC will take care of interfacing with the * PHY to retrieve the desired data. */ i2ccmd = ((offset << E1000_I2CCMD_REG_ADDR_SHIFT) | (phy->addr << E1000_I2CCMD_PHY_ADDR_SHIFT) | (E1000_I2CCMD_OPCODE_READ)); wr32(E1000_I2CCMD, i2ccmd); /* Poll the ready bit to see if the I2C read completed */ for (i = 0; i < E1000_I2CCMD_PHY_TIMEOUT; i++) { udelay(50); i2ccmd = rd32(E1000_I2CCMD); if (i2ccmd & E1000_I2CCMD_READY) break; } if (!(i2ccmd & E1000_I2CCMD_READY)) { hw_dbg("I2CCMD Read did not complete\n"); return -E1000_ERR_PHY; } if (i2ccmd & E1000_I2CCMD_ERROR) { hw_dbg("I2CCMD Error bit set\n"); return -E1000_ERR_PHY; } /* Need to byte-swap the 16-bit value. */ *data = ((i2ccmd >> 8) & 0x00FF) | ((i2ccmd << 8) & 0xFF00); return 0; } /** * igb_write_phy_reg_i2c - Write PHY register using i2c * @hw: pointer to the HW structure * @offset: register offset to write to * @data: data to write at register offset * * Writes the data to PHY register at the offset using the i2c interface. **/ s32 igb_write_phy_reg_i2c(struct e1000_hw *hw, u32 offset, u16 data) { struct e1000_phy_info *phy = &hw->phy; u32 i, i2ccmd = 0; u16 phy_data_swapped; /* Prevent overwriting SFP I2C EEPROM which is at A0 address.*/ if ((hw->phy.addr == 0) || (hw->phy.addr > 7)) { hw_dbg("PHY I2C Address %d is out of range.\n", hw->phy.addr); return -E1000_ERR_CONFIG; } /* Swap the data bytes for the I2C interface */ phy_data_swapped = ((data >> 8) & 0x00FF) | ((data << 8) & 0xFF00); /* Set up Op-code, Phy Address, and register address in the I2CCMD * register. The MAC will take care of interfacing with the * PHY to retrieve the desired data. */ i2ccmd = ((offset << E1000_I2CCMD_REG_ADDR_SHIFT) | (phy->addr << E1000_I2CCMD_PHY_ADDR_SHIFT) | E1000_I2CCMD_OPCODE_WRITE | phy_data_swapped); wr32(E1000_I2CCMD, i2ccmd); /* Poll the ready bit to see if the I2C read completed */ for (i = 0; i < E1000_I2CCMD_PHY_TIMEOUT; i++) { udelay(50); i2ccmd = rd32(E1000_I2CCMD); if (i2ccmd & E1000_I2CCMD_READY) break; } if (!(i2ccmd & E1000_I2CCMD_READY)) { hw_dbg("I2CCMD Write did not complete\n"); return -E1000_ERR_PHY; } if (i2ccmd & E1000_I2CCMD_ERROR) { hw_dbg("I2CCMD Error bit set\n"); return -E1000_ERR_PHY; } return 0; } /** * igb_read_sfp_data_byte - Reads SFP module data. * @hw: pointer to the HW structure * @offset: byte location offset to be read * @data: read data buffer pointer * * Reads one byte from SFP module data stored * in SFP resided EEPROM memory or SFP diagnostic area. * Function should be called with * E1000_I2CCMD_SFP_DATA_ADDR(<byte offset>) for SFP module database access * E1000_I2CCMD_SFP_DIAG_ADDR(<byte offset>) for SFP diagnostics parameters * access **/ s32 igb_read_sfp_data_byte(struct e1000_hw *hw, u16 offset, u8 *data) { u32 i = 0; u32 i2ccmd = 0; u32 data_local = 0; if (offset > E1000_I2CCMD_SFP_DIAG_ADDR(255)) { hw_dbg("I2CCMD command address exceeds upper limit\n"); return -E1000_ERR_PHY; } /* Set up Op-code, EEPROM Address,in the I2CCMD * register. The MAC will take care of interfacing with the * EEPROM to retrieve the desired data. */ i2ccmd = ((offset << E1000_I2CCMD_REG_ADDR_SHIFT) | E1000_I2CCMD_OPCODE_READ); wr32(E1000_I2CCMD, i2ccmd); /* Poll the ready bit to see if the I2C read completed */ for (i = 0; i < E1000_I2CCMD_PHY_TIMEOUT; i++) { udelay(50); data_local = rd32(E1000_I2CCMD); if (data_local & E1000_I2CCMD_READY) break; } if (!(data_local & E1000_I2CCMD_READY)) { hw_dbg("I2CCMD Read did not complete\n"); return -E1000_ERR_PHY; } if (data_local & E1000_I2CCMD_ERROR) { hw_dbg("I2CCMD Error bit set\n"); return -E1000_ERR_PHY; } *data = (u8) data_local & 0xFF; return 0; } /** * igb_read_phy_reg_igp - Read igp PHY register * @hw: pointer to the HW structure * @offset: register offset to be read * @data: pointer to the read data * * Acquires semaphore, if necessary, then reads the PHY register at offset * and storing the retrieved information in data. Release any acquired * semaphores before exiting. **/ s32 igb_read_phy_reg_igp(struct e1000_hw *hw, u32 offset, u16 *data) { s32 ret_val = 0; if (!(hw->phy.ops.acquire)) goto out; ret_val = hw->phy.ops.acquire(hw); if (ret_val) goto out; if (offset > MAX_PHY_MULTI_PAGE_REG) { ret_val = igb_write_phy_reg_mdic(hw, IGP01E1000_PHY_PAGE_SELECT, (u16)offset); if (ret_val) { hw->phy.ops.release(hw); goto out; } } ret_val = igb_read_phy_reg_mdic(hw, MAX_PHY_REG_ADDRESS & offset, data); hw->phy.ops.release(hw); out: return ret_val; } /** * igb_write_phy_reg_igp - Write igp PHY register * @hw: pointer to the HW structure * @offset: register offset to write to * @data: data to write at register offset * * Acquires semaphore, if necessary, then writes the data to PHY register * at the offset. Release any acquired semaphores before exiting. **/ s32 igb_write_phy_reg_igp(struct e1000_hw *hw, u32 offset, u16 data) { s32 ret_val = 0; if (!(hw->phy.ops.acquire)) goto out; ret_val = hw->phy.ops.acquire(hw); if (ret_val) goto out; if (offset > MAX_PHY_MULTI_PAGE_REG) { ret_val = igb_write_phy_reg_mdic(hw, IGP01E1000_PHY_PAGE_SELECT, (u16)offset); if (ret_val) { hw->phy.ops.release(hw); goto out; } } ret_val = igb_write_phy_reg_mdic(hw, MAX_PHY_REG_ADDRESS & offset, data); hw->phy.ops.release(hw); out: return ret_val; } /** * igb_copper_link_setup_82580 - Setup 82580 PHY for copper link * @hw: pointer to the HW structure * * Sets up Carrier-sense on Transmit and downshift values. **/ s32 igb_copper_link_setup_82580(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; u16 phy_data; if (phy->reset_disable) { ret_val = 0; goto out; } if (phy->type == e1000_phy_82580) { ret_val = hw->phy.ops.reset(hw); if (ret_val) { hw_dbg("Error resetting the PHY.\n"); goto out; } } /* Enable CRS on TX. This must be set for half-duplex operation. */ ret_val = phy->ops.read_reg(hw, I82580_CFG_REG, &phy_data); if (ret_val) goto out; phy_data |= I82580_CFG_ASSERT_CRS_ON_TX; /* Enable downshift */ phy_data |= I82580_CFG_ENABLE_DOWNSHIFT; ret_val = phy->ops.write_reg(hw, I82580_CFG_REG, phy_data); if (ret_val) goto out; /* Set MDI/MDIX mode */ ret_val = phy->ops.read_reg(hw, I82580_PHY_CTRL_2, &phy_data); if (ret_val) goto out; phy_data &= ~I82580_PHY_CTRL2_MDIX_CFG_MASK; /* Options: * 0 - Auto (default) * 1 - MDI mode * 2 - MDI-X mode */ switch (hw->phy.mdix) { case 1: break; case 2: phy_data |= I82580_PHY_CTRL2_MANUAL_MDIX; break; case 0: default: phy_data |= I82580_PHY_CTRL2_AUTO_MDI_MDIX; break; } ret_val = hw->phy.ops.write_reg(hw, I82580_PHY_CTRL_2, phy_data); out: return ret_val; } /** * igb_copper_link_setup_m88 - Setup m88 PHY's for copper link * @hw: pointer to the HW structure * * Sets up MDI/MDI-X and polarity for m88 PHY's. If necessary, transmit clock * and downshift values are set also. **/ s32 igb_copper_link_setup_m88(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; u16 phy_data; if (phy->reset_disable) { ret_val = 0; goto out; } /* Enable CRS on TX. This must be set for half-duplex operation. */ ret_val = phy->ops.read_reg(hw, M88E1000_PHY_SPEC_CTRL, &phy_data); if (ret_val) goto out; phy_data |= M88E1000_PSCR_ASSERT_CRS_ON_TX; /* Options: * MDI/MDI-X = 0 (default) * 0 - Auto for all speeds * 1 - MDI mode * 2 - MDI-X mode * 3 - Auto for 1000Base-T only (MDI-X for 10/100Base-T modes) */ phy_data &= ~M88E1000_PSCR_AUTO_X_MODE; switch (phy->mdix) { case 1: phy_data |= M88E1000_PSCR_MDI_MANUAL_MODE; break; case 2: phy_data |= M88E1000_PSCR_MDIX_MANUAL_MODE; break; case 3: phy_data |= M88E1000_PSCR_AUTO_X_1000T; break; case 0: default: phy_data |= M88E1000_PSCR_AUTO_X_MODE; break; } /* Options: * disable_polarity_correction = 0 (default) * Automatic Correction for Reversed Cable Polarity * 0 - Disabled * 1 - Enabled */ phy_data &= ~M88E1000_PSCR_POLARITY_REVERSAL; if (phy->disable_polarity_correction == 1) phy_data |= M88E1000_PSCR_POLARITY_REVERSAL; ret_val = phy->ops.write_reg(hw, M88E1000_PHY_SPEC_CTRL, phy_data); if (ret_val) goto out; if (phy->revision < E1000_REVISION_4) { /* Force TX_CLK in the Extended PHY Specific Control Register * to 25MHz clock. */ ret_val = phy->ops.read_reg(hw, M88E1000_EXT_PHY_SPEC_CTRL, &phy_data); if (ret_val) goto out; phy_data |= M88E1000_EPSCR_TX_CLK_25; if ((phy->revision == E1000_REVISION_2) && (phy->id == M88E1111_I_PHY_ID)) { /* 82573L PHY - set the downshift counter to 5x. */ phy_data &= ~M88EC018_EPSCR_DOWNSHIFT_COUNTER_MASK; phy_data |= M88EC018_EPSCR_DOWNSHIFT_COUNTER_5X; } else { /* Configure Master and Slave downshift values */ phy_data &= ~(M88E1000_EPSCR_MASTER_DOWNSHIFT_MASK | M88E1000_EPSCR_SLAVE_DOWNSHIFT_MASK); phy_data |= (M88E1000_EPSCR_MASTER_DOWNSHIFT_1X | M88E1000_EPSCR_SLAVE_DOWNSHIFT_1X); } ret_val = phy->ops.write_reg(hw, M88E1000_EXT_PHY_SPEC_CTRL, phy_data); if (ret_val) goto out; } /* Commit the changes. */ ret_val = igb_phy_sw_reset(hw); if (ret_val) { hw_dbg("Error committing the PHY changes\n"); goto out; } out: return ret_val; } /** * igb_copper_link_setup_m88_gen2 - Setup m88 PHY's for copper link * @hw: pointer to the HW structure * * Sets up MDI/MDI-X and polarity for i347-AT4, m88e1322 and m88e1112 PHY's. * Also enables and sets the downshift parameters. **/ s32 igb_copper_link_setup_m88_gen2(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; u16 phy_data; if (phy->reset_disable) return 0; /* Enable CRS on Tx. This must be set for half-duplex operation. */ ret_val = phy->ops.read_reg(hw, M88E1000_PHY_SPEC_CTRL, &phy_data); if (ret_val) return ret_val; /* Options: * MDI/MDI-X = 0 (default) * 0 - Auto for all speeds * 1 - MDI mode * 2 - MDI-X mode * 3 - Auto for 1000Base-T only (MDI-X for 10/100Base-T modes) */ phy_data &= ~M88E1000_PSCR_AUTO_X_MODE; switch (phy->mdix) { case 1: phy_data |= M88E1000_PSCR_MDI_MANUAL_MODE; break; case 2: phy_data |= M88E1000_PSCR_MDIX_MANUAL_MODE; break; case 3: /* M88E1112 does not support this mode) */ if (phy->id != M88E1112_E_PHY_ID) { phy_data |= M88E1000_PSCR_AUTO_X_1000T; break; } fallthrough; case 0: default: phy_data |= M88E1000_PSCR_AUTO_X_MODE; break; } /* Options: * disable_polarity_correction = 0 (default) * Automatic Correction for Reversed Cable Polarity * 0 - Disabled * 1 - Enabled */ phy_data &= ~M88E1000_PSCR_POLARITY_REVERSAL; if (phy->disable_polarity_correction == 1) phy_data |= M88E1000_PSCR_POLARITY_REVERSAL; /* Enable downshift and setting it to X6 */ if (phy->id == M88E1543_E_PHY_ID) { phy_data &= ~I347AT4_PSCR_DOWNSHIFT_ENABLE; ret_val = phy->ops.write_reg(hw, M88E1000_PHY_SPEC_CTRL, phy_data); if (ret_val) return ret_val; ret_val = igb_phy_sw_reset(hw); if (ret_val) { hw_dbg("Error committing the PHY changes\n"); return ret_val; } } phy_data &= ~I347AT4_PSCR_DOWNSHIFT_MASK; phy_data |= I347AT4_PSCR_DOWNSHIFT_6X; phy_data |= I347AT4_PSCR_DOWNSHIFT_ENABLE; ret_val = phy->ops.write_reg(hw, M88E1000_PHY_SPEC_CTRL, phy_data); if (ret_val) return ret_val; /* Commit the changes. */ ret_val = igb_phy_sw_reset(hw); if (ret_val) { hw_dbg("Error committing the PHY changes\n"); return ret_val; } ret_val = igb_set_master_slave_mode(hw); if (ret_val) return ret_val; return 0; } /** * igb_copper_link_setup_igp - Setup igp PHY's for copper link * @hw: pointer to the HW structure * * Sets up LPLU, MDI/MDI-X, polarity, Smartspeed and Master/Slave config for * igp PHY's. **/ s32 igb_copper_link_setup_igp(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; u16 data; if (phy->reset_disable) { ret_val = 0; goto out; } ret_val = phy->ops.reset(hw); if (ret_val) { hw_dbg("Error resetting the PHY.\n"); goto out; } /* Wait 100ms for MAC to configure PHY from NVM settings, to avoid * timeout issues when LFS is enabled. */ msleep(100); /* The NVM settings will configure LPLU in D3 for * non-IGP1 PHYs. */ if (phy->type == e1000_phy_igp) { /* disable lplu d3 during driver init */ if (phy->ops.set_d3_lplu_state) ret_val = phy->ops.set_d3_lplu_state(hw, false); if (ret_val) { hw_dbg("Error Disabling LPLU D3\n"); goto out; } } /* disable lplu d0 during driver init */ ret_val = phy->ops.set_d0_lplu_state(hw, false); if (ret_val) { hw_dbg("Error Disabling LPLU D0\n"); goto out; } /* Configure mdi-mdix settings */ ret_val = phy->ops.read_reg(hw, IGP01E1000_PHY_PORT_CTRL, &data); if (ret_val) goto out; data &= ~IGP01E1000_PSCR_AUTO_MDIX; switch (phy->mdix) { case 1: data &= ~IGP01E1000_PSCR_FORCE_MDI_MDIX; break; case 2: data |= IGP01E1000_PSCR_FORCE_MDI_MDIX; break; case 0: default: data |= IGP01E1000_PSCR_AUTO_MDIX; break; } ret_val = phy->ops.write_reg(hw, IGP01E1000_PHY_PORT_CTRL, data); if (ret_val) goto out; /* set auto-master slave resolution settings */ if (hw->mac.autoneg) { /* when autonegotiation advertisement is only 1000Mbps then we * should disable SmartSpeed and enable Auto MasterSlave * resolution as hardware default. */ if (phy->autoneg_advertised == ADVERTISE_1000_FULL) { /* Disable SmartSpeed */ ret_val = phy->ops.read_reg(hw, IGP01E1000_PHY_PORT_CONFIG, &data); if (ret_val) goto out; data &= ~IGP01E1000_PSCFR_SMART_SPEED; ret_val = phy->ops.write_reg(hw, IGP01E1000_PHY_PORT_CONFIG, data); if (ret_val) goto out; /* Set auto Master/Slave resolution process */ ret_val = phy->ops.read_reg(hw, PHY_1000T_CTRL, &data); if (ret_val) goto out; data &= ~CR_1000T_MS_ENABLE; ret_val = phy->ops.write_reg(hw, PHY_1000T_CTRL, data); if (ret_val) goto out; } ret_val = phy->ops.read_reg(hw, PHY_1000T_CTRL, &data); if (ret_val) goto out; /* load defaults for future use */ phy->original_ms_type = (data & CR_1000T_MS_ENABLE) ? ((data & CR_1000T_MS_VALUE) ? e1000_ms_force_master : e1000_ms_force_slave) : e1000_ms_auto; switch (phy->ms_type) { case e1000_ms_force_master: data |= (CR_1000T_MS_ENABLE | CR_1000T_MS_VALUE); break; case e1000_ms_force_slave: data |= CR_1000T_MS_ENABLE; data &= ~(CR_1000T_MS_VALUE); break; case e1000_ms_auto: data &= ~CR_1000T_MS_ENABLE; break; default: break; } ret_val = phy->ops.write_reg(hw, PHY_1000T_CTRL, data); if (ret_val) goto out; } out: return ret_val; } /** * igb_copper_link_autoneg - Setup/Enable autoneg for copper link * @hw: pointer to the HW structure * * Performs initial bounds checking on autoneg advertisement parameter, then * configure to advertise the full capability. Setup the PHY to autoneg * and restart the negotiation process between the link partner. If * autoneg_wait_to_complete, then wait for autoneg to complete before exiting. **/ static s32 igb_copper_link_autoneg(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; u16 phy_ctrl; /* Perform some bounds checking on the autoneg advertisement * parameter. */ phy->autoneg_advertised &= phy->autoneg_mask; /* If autoneg_advertised is zero, we assume it was not defaulted * by the calling code so we set to advertise full capability. */ if (phy->autoneg_advertised == 0) phy->autoneg_advertised = phy->autoneg_mask; hw_dbg("Reconfiguring auto-neg advertisement params\n"); ret_val = igb_phy_setup_autoneg(hw); if (ret_val) { hw_dbg("Error Setting up Auto-Negotiation\n"); goto out; } hw_dbg("Restarting Auto-Neg\n"); /* Restart auto-negotiation by setting the Auto Neg Enable bit and * the Auto Neg Restart bit in the PHY control register. */ ret_val = phy->ops.read_reg(hw, PHY_CONTROL, &phy_ctrl); if (ret_val) goto out; phy_ctrl |= (MII_CR_AUTO_NEG_EN | MII_CR_RESTART_AUTO_NEG); ret_val = phy->ops.write_reg(hw, PHY_CONTROL, phy_ctrl); if (ret_val) goto out; /* Does the user want to wait for Auto-Neg to complete here, or * check at a later time (for example, callback routine). */ if (phy->autoneg_wait_to_complete) { ret_val = igb_wait_autoneg(hw); if (ret_val) { hw_dbg("Error while waiting for autoneg to complete\n"); goto out; } } hw->mac.get_link_status = true; out: return ret_val; } /** * igb_phy_setup_autoneg - Configure PHY for auto-negotiation * @hw: pointer to the HW structure * * Reads the MII auto-neg advertisement register and/or the 1000T control * register and if the PHY is already setup for auto-negotiation, then * return successful. Otherwise, setup advertisement and flow control to * the appropriate values for the wanted auto-negotiation. **/ static s32 igb_phy_setup_autoneg(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; u16 mii_autoneg_adv_reg; u16 mii_1000t_ctrl_reg = 0; phy->autoneg_advertised &= phy->autoneg_mask; /* Read the MII Auto-Neg Advertisement Register (Address 4). */ ret_val = phy->ops.read_reg(hw, PHY_AUTONEG_ADV, &mii_autoneg_adv_reg); if (ret_val) goto out; if (phy->autoneg_mask & ADVERTISE_1000_FULL) { /* Read the MII 1000Base-T Control Register (Address 9). */ ret_val = phy->ops.read_reg(hw, PHY_1000T_CTRL, &mii_1000t_ctrl_reg); if (ret_val) goto out; } /* Need to parse both autoneg_advertised and fc and set up * the appropriate PHY registers. First we will parse for * autoneg_advertised software override. Since we can advertise * a plethora of combinations, we need to check each bit * individually. */ /* First we clear all the 10/100 mb speed bits in the Auto-Neg * Advertisement Register (Address 4) and the 1000 mb speed bits in * the 1000Base-T Control Register (Address 9). */ mii_autoneg_adv_reg &= ~(NWAY_AR_100TX_FD_CAPS | NWAY_AR_100TX_HD_CAPS | NWAY_AR_10T_FD_CAPS | NWAY_AR_10T_HD_CAPS); mii_1000t_ctrl_reg &= ~(CR_1000T_HD_CAPS | CR_1000T_FD_CAPS); hw_dbg("autoneg_advertised %x\n", phy->autoneg_advertised); /* Do we want to advertise 10 Mb Half Duplex? */ if (phy->autoneg_advertised & ADVERTISE_10_HALF) { hw_dbg("Advertise 10mb Half duplex\n"); mii_autoneg_adv_reg |= NWAY_AR_10T_HD_CAPS; } /* Do we want to advertise 10 Mb Full Duplex? */ if (phy->autoneg_advertised & ADVERTISE_10_FULL) { hw_dbg("Advertise 10mb Full duplex\n"); mii_autoneg_adv_reg |= NWAY_AR_10T_FD_CAPS; } /* Do we want to advertise 100 Mb Half Duplex? */ if (phy->autoneg_advertised & ADVERTISE_100_HALF) { hw_dbg("Advertise 100mb Half duplex\n"); mii_autoneg_adv_reg |= NWAY_AR_100TX_HD_CAPS; } /* Do we want to advertise 100 Mb Full Duplex? */ if (phy->autoneg_advertised & ADVERTISE_100_FULL) { hw_dbg("Advertise 100mb Full duplex\n"); mii_autoneg_adv_reg |= NWAY_AR_100TX_FD_CAPS; } /* We do not allow the Phy to advertise 1000 Mb Half Duplex */ if (phy->autoneg_advertised & ADVERTISE_1000_HALF) hw_dbg("Advertise 1000mb Half duplex request denied!\n"); /* Do we want to advertise 1000 Mb Full Duplex? */ if (phy->autoneg_advertised & ADVERTISE_1000_FULL) { hw_dbg("Advertise 1000mb Full duplex\n"); mii_1000t_ctrl_reg |= CR_1000T_FD_CAPS; } /* Check for a software override of the flow control settings, and * setup the PHY advertisement registers accordingly. If * auto-negotiation is enabled, then software will have to set the * "PAUSE" bits to the correct value in the Auto-Negotiation * Advertisement Register (PHY_AUTONEG_ADV) and re-start auto- * negotiation. * * The possible values of the "fc" parameter are: * 0: Flow control is completely disabled * 1: Rx flow control is enabled (we can receive pause frames * but not send pause frames). * 2: Tx flow control is enabled (we can send pause frames * but we do not support receiving pause frames). * 3: Both Rx and TX flow control (symmetric) are enabled. * other: No software override. The flow control configuration * in the EEPROM is used. */ switch (hw->fc.current_mode) { case e1000_fc_none: /* Flow control (RX & TX) is completely disabled by a * software over-ride. */ mii_autoneg_adv_reg &= ~(NWAY_AR_ASM_DIR | NWAY_AR_PAUSE); break; case e1000_fc_rx_pause: /* RX Flow control is enabled, and TX Flow control is * disabled, by a software over-ride. * * Since there really isn't a way to advertise that we are * capable of RX Pause ONLY, we will advertise that we * support both symmetric and asymmetric RX PAUSE. Later * (in e1000_config_fc_after_link_up) we will disable the * hw's ability to send PAUSE frames. */ mii_autoneg_adv_reg |= (NWAY_AR_ASM_DIR | NWAY_AR_PAUSE); break; case e1000_fc_tx_pause: /* TX Flow control is enabled, and RX Flow control is * disabled, by a software over-ride. */ mii_autoneg_adv_reg |= NWAY_AR_ASM_DIR; mii_autoneg_adv_reg &= ~NWAY_AR_PAUSE; break; case e1000_fc_full: /* Flow control (both RX and TX) is enabled by a software * over-ride. */ mii_autoneg_adv_reg |= (NWAY_AR_ASM_DIR | NWAY_AR_PAUSE); break; default: hw_dbg("Flow control param set incorrectly\n"); ret_val = -E1000_ERR_CONFIG; goto out; } ret_val = phy->ops.write_reg(hw, PHY_AUTONEG_ADV, mii_autoneg_adv_reg); if (ret_val) goto out; hw_dbg("Auto-Neg Advertising %x\n", mii_autoneg_adv_reg); if (phy->autoneg_mask & ADVERTISE_1000_FULL) { ret_val = phy->ops.write_reg(hw, PHY_1000T_CTRL, mii_1000t_ctrl_reg); if (ret_val) goto out; } out: return ret_val; } /** * igb_setup_copper_link - Configure copper link settings * @hw: pointer to the HW structure * * Calls the appropriate function to configure the link for auto-neg or forced * speed and duplex. Then we check for link, once link is established calls * to configure collision distance and flow control are called. If link is * not established, we return -E1000_ERR_PHY (-2). **/ s32 igb_setup_copper_link(struct e1000_hw *hw) { s32 ret_val; bool link; if (hw->mac.autoneg) { /* Setup autoneg and flow control advertisement and perform * autonegotiation. */ ret_val = igb_copper_link_autoneg(hw); if (ret_val) goto out; } else { /* PHY will be set to 10H, 10F, 100H or 100F * depending on user settings. */ hw_dbg("Forcing Speed and Duplex\n"); ret_val = hw->phy.ops.force_speed_duplex(hw); if (ret_val) { hw_dbg("Error Forcing Speed and Duplex\n"); goto out; } } /* Check link status. Wait up to 100 microseconds for link to become * valid. */ ret_val = igb_phy_has_link(hw, COPPER_LINK_UP_LIMIT, 10, &link); if (ret_val) goto out; if (link) { hw_dbg("Valid link established!!!\n"); igb_config_collision_dist(hw); ret_val = igb_config_fc_after_link_up(hw); } else { hw_dbg("Unable to establish link!!!\n"); } out: return ret_val; } /** * igb_phy_force_speed_duplex_igp - Force speed/duplex for igp PHY * @hw: pointer to the HW structure * * Calls the PHY setup function to force speed and duplex. Clears the * auto-crossover to force MDI manually. Waits for link and returns * successful if link up is successful, else -E1000_ERR_PHY (-2). **/ s32 igb_phy_force_speed_duplex_igp(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; u16 phy_data; bool link; ret_val = phy->ops.read_reg(hw, PHY_CONTROL, &phy_data); if (ret_val) goto out; igb_phy_force_speed_duplex_setup(hw, &phy_data); ret_val = phy->ops.write_reg(hw, PHY_CONTROL, phy_data); if (ret_val) goto out; /* Clear Auto-Crossover to force MDI manually. IGP requires MDI * forced whenever speed and duplex are forced. */ ret_val = phy->ops.read_reg(hw, IGP01E1000_PHY_PORT_CTRL, &phy_data); if (ret_val) goto out; phy_data &= ~IGP01E1000_PSCR_AUTO_MDIX; phy_data &= ~IGP01E1000_PSCR_FORCE_MDI_MDIX; ret_val = phy->ops.write_reg(hw, IGP01E1000_PHY_PORT_CTRL, phy_data); if (ret_val) goto out; hw_dbg("IGP PSCR: %X\n", phy_data); udelay(1); if (phy->autoneg_wait_to_complete) { hw_dbg("Waiting for forced speed/duplex link on IGP phy.\n"); ret_val = igb_phy_has_link(hw, PHY_FORCE_LIMIT, 10000, &link); if (ret_val) goto out; if (!link) hw_dbg("Link taking longer than expected.\n"); /* Try once more */ ret_val = igb_phy_has_link(hw, PHY_FORCE_LIMIT, 10000, &link); if (ret_val) goto out; } out: return ret_val; } /** * igb_phy_force_speed_duplex_m88 - Force speed/duplex for m88 PHY * @hw: pointer to the HW structure * * Calls the PHY setup function to force speed and duplex. Clears the * auto-crossover to force MDI manually. Resets the PHY to commit the * changes. If time expires while waiting for link up, we reset the DSP. * After reset, TX_CLK and CRS on TX must be set. Return successful upon * successful completion, else return corresponding error code. **/ s32 igb_phy_force_speed_duplex_m88(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; u16 phy_data; bool link; /* I210 and I211 devices support Auto-Crossover in forced operation. */ if (phy->type != e1000_phy_i210) { /* Clear Auto-Crossover to force MDI manually. M88E1000 * requires MDI forced whenever speed and duplex are forced. */ ret_val = phy->ops.read_reg(hw, M88E1000_PHY_SPEC_CTRL, &phy_data); if (ret_val) goto out; phy_data &= ~M88E1000_PSCR_AUTO_X_MODE; ret_val = phy->ops.write_reg(hw, M88E1000_PHY_SPEC_CTRL, phy_data); if (ret_val) goto out; hw_dbg("M88E1000 PSCR: %X\n", phy_data); } ret_val = phy->ops.read_reg(hw, PHY_CONTROL, &phy_data); if (ret_val) goto out; igb_phy_force_speed_duplex_setup(hw, &phy_data); ret_val = phy->ops.write_reg(hw, PHY_CONTROL, phy_data); if (ret_val) goto out; /* Reset the phy to commit changes. */ ret_val = igb_phy_sw_reset(hw); if (ret_val) goto out; if (phy->autoneg_wait_to_complete) { hw_dbg("Waiting for forced speed/duplex link on M88 phy.\n"); ret_val = igb_phy_has_link(hw, PHY_FORCE_LIMIT, 100000, &link); if (ret_val) goto out; if (!link) { bool reset_dsp = true; switch (hw->phy.id) { case I347AT4_E_PHY_ID: case M88E1112_E_PHY_ID: case M88E1543_E_PHY_ID: case M88E1512_E_PHY_ID: case I210_I_PHY_ID: reset_dsp = false; break; default: if (hw->phy.type != e1000_phy_m88) reset_dsp = false; break; } if (!reset_dsp) { hw_dbg("Link taking longer than expected.\n"); } else { /* We didn't get link. * Reset the DSP and cross our fingers. */ ret_val = phy->ops.write_reg(hw, M88E1000_PHY_PAGE_SELECT, 0x001d); if (ret_val) goto out; ret_val = igb_phy_reset_dsp(hw); if (ret_val) goto out; } } /* Try once more */ ret_val = igb_phy_has_link(hw, PHY_FORCE_LIMIT, 100000, &link); if (ret_val) goto out; } if (hw->phy.type != e1000_phy_m88 || hw->phy.id == I347AT4_E_PHY_ID || hw->phy.id == M88E1112_E_PHY_ID || hw->phy.id == M88E1543_E_PHY_ID || hw->phy.id == M88E1512_E_PHY_ID || hw->phy.id == I210_I_PHY_ID) goto out; ret_val = phy->ops.read_reg(hw, M88E1000_EXT_PHY_SPEC_CTRL, &phy_data); if (ret_val) goto out; /* Resetting the phy means we need to re-force TX_CLK in the * Extended PHY Specific Control Register to 25MHz clock from * the reset value of 2.5MHz. */ phy_data |= M88E1000_EPSCR_TX_CLK_25; ret_val = phy->ops.write_reg(hw, M88E1000_EXT_PHY_SPEC_CTRL, phy_data); if (ret_val) goto out; /* In addition, we must re-enable CRS on Tx for both half and full * duplex. */ ret_val = phy->ops.read_reg(hw, M88E1000_PHY_SPEC_CTRL, &phy_data); if (ret_val) goto out; phy_data |= M88E1000_PSCR_ASSERT_CRS_ON_TX; ret_val = phy->ops.write_reg(hw, M88E1000_PHY_SPEC_CTRL, phy_data); out: return ret_val; } /** * igb_phy_force_speed_duplex_setup - Configure forced PHY speed/duplex * @hw: pointer to the HW structure * @phy_ctrl: pointer to current value of PHY_CONTROL * * Forces speed and duplex on the PHY by doing the following: disable flow * control, force speed/duplex on the MAC, disable auto speed detection, * disable auto-negotiation, configure duplex, configure speed, configure * the collision distance, write configuration to CTRL register. The * caller must write to the PHY_CONTROL register for these settings to * take affect. **/ static void igb_phy_force_speed_duplex_setup(struct e1000_hw *hw, u16 *phy_ctrl) { struct e1000_mac_info *mac = &hw->mac; u32 ctrl; /* Turn off flow control when forcing speed/duplex */ hw->fc.current_mode = e1000_fc_none; /* Force speed/duplex on the mac */ ctrl = rd32(E1000_CTRL); ctrl |= (E1000_CTRL_FRCSPD | E1000_CTRL_FRCDPX); ctrl &= ~E1000_CTRL_SPD_SEL; /* Disable Auto Speed Detection */ ctrl &= ~E1000_CTRL_ASDE; /* Disable autoneg on the phy */ *phy_ctrl &= ~MII_CR_AUTO_NEG_EN; /* Forcing Full or Half Duplex? */ if (mac->forced_speed_duplex & E1000_ALL_HALF_DUPLEX) { ctrl &= ~E1000_CTRL_FD; *phy_ctrl &= ~MII_CR_FULL_DUPLEX; hw_dbg("Half Duplex\n"); } else { ctrl |= E1000_CTRL_FD; *phy_ctrl |= MII_CR_FULL_DUPLEX; hw_dbg("Full Duplex\n"); } /* Forcing 10mb or 100mb? */ if (mac->forced_speed_duplex & E1000_ALL_100_SPEED) { ctrl |= E1000_CTRL_SPD_100; *phy_ctrl |= MII_CR_SPEED_100; *phy_ctrl &= ~(MII_CR_SPEED_1000 | MII_CR_SPEED_10); hw_dbg("Forcing 100mb\n"); } else { ctrl &= ~(E1000_CTRL_SPD_1000 | E1000_CTRL_SPD_100); *phy_ctrl |= MII_CR_SPEED_10; *phy_ctrl &= ~(MII_CR_SPEED_1000 | MII_CR_SPEED_100); hw_dbg("Forcing 10mb\n"); } igb_config_collision_dist(hw); wr32(E1000_CTRL, ctrl); } /** * igb_set_d3_lplu_state - Sets low power link up state for D3 * @hw: pointer to the HW structure * @active: boolean used to enable/disable lplu * * Success returns 0, Failure returns 1 * * The low power link up (lplu) state is set to the power management level D3 * and SmartSpeed is disabled when active is true, else clear lplu for D3 * and enable Smartspeed. LPLU and Smartspeed are mutually exclusive. LPLU * is used during Dx states where the power conservation is most important. * During driver activity, SmartSpeed should be enabled so performance is * maintained. **/ s32 igb_set_d3_lplu_state(struct e1000_hw *hw, bool active) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val = 0; u16 data; if (!(hw->phy.ops.read_reg)) goto out; ret_val = phy->ops.read_reg(hw, IGP02E1000_PHY_POWER_MGMT, &data); if (ret_val) goto out; if (!active) { data &= ~IGP02E1000_PM_D3_LPLU; ret_val = phy->ops.write_reg(hw, IGP02E1000_PHY_POWER_MGMT, data); if (ret_val) goto out; /* LPLU and SmartSpeed are mutually exclusive. LPLU is used * during Dx states where the power conservation is most * important. During driver activity we should enable * SmartSpeed, so performance is maintained. */ if (phy->smart_speed == e1000_smart_speed_on) { ret_val = phy->ops.read_reg(hw, IGP01E1000_PHY_PORT_CONFIG, &data); if (ret_val) goto out; data |= IGP01E1000_PSCFR_SMART_SPEED; ret_val = phy->ops.write_reg(hw, IGP01E1000_PHY_PORT_CONFIG, data); if (ret_val) goto out; } else if (phy->smart_speed == e1000_smart_speed_off) { ret_val = phy->ops.read_reg(hw, IGP01E1000_PHY_PORT_CONFIG, &data); if (ret_val) goto out; data &= ~IGP01E1000_PSCFR_SMART_SPEED; ret_val = phy->ops.write_reg(hw, IGP01E1000_PHY_PORT_CONFIG, data); if (ret_val) goto out; } } else if ((phy->autoneg_advertised == E1000_ALL_SPEED_DUPLEX) || (phy->autoneg_advertised == E1000_ALL_NOT_GIG) || (phy->autoneg_advertised == E1000_ALL_10_SPEED)) { data |= IGP02E1000_PM_D3_LPLU; ret_val = phy->ops.write_reg(hw, IGP02E1000_PHY_POWER_MGMT, data); if (ret_val) goto out; /* When LPLU is enabled, we should disable SmartSpeed */ ret_val = phy->ops.read_reg(hw, IGP01E1000_PHY_PORT_CONFIG, &data); if (ret_val) goto out; data &= ~IGP01E1000_PSCFR_SMART_SPEED; ret_val = phy->ops.write_reg(hw, IGP01E1000_PHY_PORT_CONFIG, data); } out: return ret_val; } /** * igb_check_downshift - Checks whether a downshift in speed occurred * @hw: pointer to the HW structure * * Success returns 0, Failure returns 1 * * A downshift is detected by querying the PHY link health. **/ s32 igb_check_downshift(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; u16 phy_data, offset, mask; switch (phy->type) { case e1000_phy_i210: case e1000_phy_m88: case e1000_phy_gg82563: offset = M88E1000_PHY_SPEC_STATUS; mask = M88E1000_PSSR_DOWNSHIFT; break; case e1000_phy_igp_2: case e1000_phy_igp: case e1000_phy_igp_3: offset = IGP01E1000_PHY_LINK_HEALTH; mask = IGP01E1000_PLHR_SS_DOWNGRADE; break; default: /* speed downshift not supported */ phy->speed_downgraded = false; ret_val = 0; goto out; } ret_val = phy->ops.read_reg(hw, offset, &phy_data); if (!ret_val) phy->speed_downgraded = (phy_data & mask) ? true : false; out: return ret_val; } /** * igb_check_polarity_m88 - Checks the polarity. * @hw: pointer to the HW structure * * Success returns 0, Failure returns -E1000_ERR_PHY (-2) * * Polarity is determined based on the PHY specific status register. **/ s32 igb_check_polarity_m88(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; u16 data; ret_val = phy->ops.read_reg(hw, M88E1000_PHY_SPEC_STATUS, &data); if (!ret_val) phy->cable_polarity = (data & M88E1000_PSSR_REV_POLARITY) ? e1000_rev_polarity_reversed : e1000_rev_polarity_normal; return ret_val; } /** * igb_check_polarity_igp - Checks the polarity. * @hw: pointer to the HW structure * * Success returns 0, Failure returns -E1000_ERR_PHY (-2) * * Polarity is determined based on the PHY port status register, and the * current speed (since there is no polarity at 100Mbps). **/ static s32 igb_check_polarity_igp(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; u16 data, offset, mask; /* Polarity is determined based on the speed of * our connection. */ ret_val = phy->ops.read_reg(hw, IGP01E1000_PHY_PORT_STATUS, &data); if (ret_val) goto out; if ((data & IGP01E1000_PSSR_SPEED_MASK) == IGP01E1000_PSSR_SPEED_1000MBPS) { offset = IGP01E1000_PHY_PCS_INIT_REG; mask = IGP01E1000_PHY_POLARITY_MASK; } else { /* This really only applies to 10Mbps since * there is no polarity for 100Mbps (always 0). */ offset = IGP01E1000_PHY_PORT_STATUS; mask = IGP01E1000_PSSR_POLARITY_REVERSED; } ret_val = phy->ops.read_reg(hw, offset, &data); if (!ret_val) phy->cable_polarity = (data & mask) ? e1000_rev_polarity_reversed : e1000_rev_polarity_normal; out: return ret_val; } /** * igb_wait_autoneg - Wait for auto-neg completion * @hw: pointer to the HW structure * * Waits for auto-negotiation to complete or for the auto-negotiation time * limit to expire, which ever happens first. **/ static s32 igb_wait_autoneg(struct e1000_hw *hw) { s32 ret_val = 0; u16 i, phy_status; /* Break after autoneg completes or PHY_AUTO_NEG_LIMIT expires. */ for (i = PHY_AUTO_NEG_LIMIT; i > 0; i--) { ret_val = hw->phy.ops.read_reg(hw, PHY_STATUS, &phy_status); if (ret_val) break; ret_val = hw->phy.ops.read_reg(hw, PHY_STATUS, &phy_status); if (ret_val) break; if (phy_status & MII_SR_AUTONEG_COMPLETE) break; msleep(100); } /* PHY_AUTO_NEG_TIME expiration doesn't guarantee auto-negotiation * has completed. */ return ret_val; } /** * igb_phy_has_link - Polls PHY for link * @hw: pointer to the HW structure * @iterations: number of times to poll for link * @usec_interval: delay between polling attempts * @success: pointer to whether polling was successful or not * * Polls the PHY status register for link, 'iterations' number of times. **/ s32 igb_phy_has_link(struct e1000_hw *hw, u32 iterations, u32 usec_interval, bool *success) { s32 ret_val = 0; u16 i, phy_status; for (i = 0; i < iterations; i++) { /* Some PHYs require the PHY_STATUS register to be read * twice due to the link bit being sticky. No harm doing * it across the board. */ ret_val = hw->phy.ops.read_reg(hw, PHY_STATUS, &phy_status); if (ret_val && usec_interval > 0) { /* If the first read fails, another entity may have * ownership of the resources, wait and try again to * see if they have relinquished the resources yet. */ if (usec_interval >= 1000) mdelay(usec_interval/1000); else udelay(usec_interval); } ret_val = hw->phy.ops.read_reg(hw, PHY_STATUS, &phy_status); if (ret_val) break; if (phy_status & MII_SR_LINK_STATUS) break; if (usec_interval >= 1000) mdelay(usec_interval/1000); else udelay(usec_interval); } *success = (i < iterations) ? true : false; return ret_val; } /** * igb_get_cable_length_m88 - Determine cable length for m88 PHY * @hw: pointer to the HW structure * * Reads the PHY specific status register to retrieve the cable length * information. The cable length is determined by averaging the minimum and * maximum values to get the "average" cable length. The m88 PHY has four * possible cable length values, which are: * Register Value Cable Length * 0 < 50 meters * 1 50 - 80 meters * 2 80 - 110 meters * 3 110 - 140 meters * 4 > 140 meters **/ s32 igb_get_cable_length_m88(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; u16 phy_data, index; ret_val = phy->ops.read_reg(hw, M88E1000_PHY_SPEC_STATUS, &phy_data); if (ret_val) goto out; index = (phy_data & M88E1000_PSSR_CABLE_LENGTH) >> M88E1000_PSSR_CABLE_LENGTH_SHIFT; if (index >= ARRAY_SIZE(e1000_m88_cable_length_table) - 1) { ret_val = -E1000_ERR_PHY; goto out; } phy->min_cable_length = e1000_m88_cable_length_table[index]; phy->max_cable_length = e1000_m88_cable_length_table[index + 1]; phy->cable_length = (phy->min_cable_length + phy->max_cable_length) / 2; out: return ret_val; } s32 igb_get_cable_length_m88_gen2(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; u16 phy_data, phy_data2, index, default_page, is_cm; int len_tot = 0; u16 len_min; u16 len_max; switch (hw->phy.id) { case M88E1543_E_PHY_ID: case M88E1512_E_PHY_ID: case I347AT4_E_PHY_ID: case I210_I_PHY_ID: /* Remember the original page select and set it to 7 */ ret_val = phy->ops.read_reg(hw, I347AT4_PAGE_SELECT, &default_page); if (ret_val) goto out; ret_val = phy->ops.write_reg(hw, I347AT4_PAGE_SELECT, 0x07); if (ret_val) goto out; /* Check if the unit of cable length is meters or cm */ ret_val = phy->ops.read_reg(hw, I347AT4_PCDC, &phy_data2); if (ret_val) goto out; is_cm = !(phy_data2 & I347AT4_PCDC_CABLE_LENGTH_UNIT); /* Get cable length from Pair 0 length Regs */ ret_val = phy->ops.read_reg(hw, I347AT4_PCDL0, &phy_data); if (ret_val) goto out; phy->pair_length[0] = phy_data / (is_cm ? 100 : 1); len_tot = phy->pair_length[0]; len_min = phy->pair_length[0]; len_max = phy->pair_length[0]; /* Get cable length from Pair 1 length Regs */ ret_val = phy->ops.read_reg(hw, I347AT4_PCDL1, &phy_data); if (ret_val) goto out; phy->pair_length[1] = phy_data / (is_cm ? 100 : 1); len_tot += phy->pair_length[1]; len_min = min(len_min, phy->pair_length[1]); len_max = max(len_max, phy->pair_length[1]); /* Get cable length from Pair 2 length Regs */ ret_val = phy->ops.read_reg(hw, I347AT4_PCDL2, &phy_data); if (ret_val) goto out; phy->pair_length[2] = phy_data / (is_cm ? 100 : 1); len_tot += phy->pair_length[2]; len_min = min(len_min, phy->pair_length[2]); len_max = max(len_max, phy->pair_length[2]); /* Get cable length from Pair 3 length Regs */ ret_val = phy->ops.read_reg(hw, I347AT4_PCDL3, &phy_data); if (ret_val) goto out; phy->pair_length[3] = phy_data / (is_cm ? 100 : 1); len_tot += phy->pair_length[3]; len_min = min(len_min, phy->pair_length[3]); len_max = max(len_max, phy->pair_length[3]); /* Populate the phy structure with cable length in meters */ phy->min_cable_length = len_min; phy->max_cable_length = len_max; phy->cable_length = len_tot / 4; /* Reset the page selec to its original value */ ret_val = phy->ops.write_reg(hw, I347AT4_PAGE_SELECT, default_page); if (ret_val) goto out; break; case M88E1112_E_PHY_ID: /* Remember the original page select and set it to 5 */ ret_val = phy->ops.read_reg(hw, I347AT4_PAGE_SELECT, &default_page); if (ret_val) goto out; ret_val = phy->ops.write_reg(hw, I347AT4_PAGE_SELECT, 0x05); if (ret_val) goto out; ret_val = phy->ops.read_reg(hw, M88E1112_VCT_DSP_DISTANCE, &phy_data); if (ret_val) goto out; index = (phy_data & M88E1000_PSSR_CABLE_LENGTH) >> M88E1000_PSSR_CABLE_LENGTH_SHIFT; if (index >= ARRAY_SIZE(e1000_m88_cable_length_table) - 1) { ret_val = -E1000_ERR_PHY; goto out; } phy->min_cable_length = e1000_m88_cable_length_table[index]; phy->max_cable_length = e1000_m88_cable_length_table[index + 1]; phy->cable_length = (phy->min_cable_length + phy->max_cable_length) / 2; /* Reset the page select to its original value */ ret_val = phy->ops.write_reg(hw, I347AT4_PAGE_SELECT, default_page); if (ret_val) goto out; break; default: ret_val = -E1000_ERR_PHY; goto out; } out: return ret_val; } /** * igb_get_cable_length_igp_2 - Determine cable length for igp2 PHY * @hw: pointer to the HW structure * * The automatic gain control (agc) normalizes the amplitude of the * received signal, adjusting for the attenuation produced by the * cable. By reading the AGC registers, which represent the * combination of coarse and fine gain value, the value can be put * into a lookup table to obtain the approximate cable length * for each channel. **/ s32 igb_get_cable_length_igp_2(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val = 0; u16 phy_data, i, agc_value = 0; u16 cur_agc_index, max_agc_index = 0; u16 min_agc_index = ARRAY_SIZE(e1000_igp_2_cable_length_table) - 1; static const u16 agc_reg_array[IGP02E1000_PHY_CHANNEL_NUM] = { IGP02E1000_PHY_AGC_A, IGP02E1000_PHY_AGC_B, IGP02E1000_PHY_AGC_C, IGP02E1000_PHY_AGC_D }; /* Read the AGC registers for all channels */ for (i = 0; i < IGP02E1000_PHY_CHANNEL_NUM; i++) { ret_val = phy->ops.read_reg(hw, agc_reg_array[i], &phy_data); if (ret_val) goto out; /* Getting bits 15:9, which represent the combination of * coarse and fine gain values. The result is a number * that can be put into the lookup table to obtain the * approximate cable length. */ cur_agc_index = (phy_data >> IGP02E1000_AGC_LENGTH_SHIFT) & IGP02E1000_AGC_LENGTH_MASK; /* Array index bound check. */ if ((cur_agc_index >= ARRAY_SIZE(e1000_igp_2_cable_length_table)) || (cur_agc_index == 0)) { ret_val = -E1000_ERR_PHY; goto out; } /* Remove min & max AGC values from calculation. */ if (e1000_igp_2_cable_length_table[min_agc_index] > e1000_igp_2_cable_length_table[cur_agc_index]) min_agc_index = cur_agc_index; if (e1000_igp_2_cable_length_table[max_agc_index] < e1000_igp_2_cable_length_table[cur_agc_index]) max_agc_index = cur_agc_index; agc_value += e1000_igp_2_cable_length_table[cur_agc_index]; } agc_value -= (e1000_igp_2_cable_length_table[min_agc_index] + e1000_igp_2_cable_length_table[max_agc_index]); agc_value /= (IGP02E1000_PHY_CHANNEL_NUM - 2); /* Calculate cable length with the error range of +/- 10 meters. */ phy->min_cable_length = ((agc_value - IGP02E1000_AGC_RANGE) > 0) ? (agc_value - IGP02E1000_AGC_RANGE) : 0; phy->max_cable_length = agc_value + IGP02E1000_AGC_RANGE; phy->cable_length = (phy->min_cable_length + phy->max_cable_length) / 2; out: return ret_val; } /** * igb_get_phy_info_m88 - Retrieve PHY information * @hw: pointer to the HW structure * * Valid for only copper links. Read the PHY status register (sticky read) * to verify that link is up. Read the PHY special control register to * determine the polarity and 10base-T extended distance. Read the PHY * special status register to determine MDI/MDIx and current speed. If * speed is 1000, then determine cable length, local and remote receiver. **/ s32 igb_get_phy_info_m88(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; u16 phy_data; bool link; if (phy->media_type != e1000_media_type_copper) { hw_dbg("Phy info is only valid for copper media\n"); ret_val = -E1000_ERR_CONFIG; goto out; } ret_val = igb_phy_has_link(hw, 1, 0, &link); if (ret_val) goto out; if (!link) { hw_dbg("Phy info is only valid if link is up\n"); ret_val = -E1000_ERR_CONFIG; goto out; } ret_val = phy->ops.read_reg(hw, M88E1000_PHY_SPEC_CTRL, &phy_data); if (ret_val) goto out; phy->polarity_correction = (phy_data & M88E1000_PSCR_POLARITY_REVERSAL) ? true : false; ret_val = igb_check_polarity_m88(hw); if (ret_val) goto out; ret_val = phy->ops.read_reg(hw, M88E1000_PHY_SPEC_STATUS, &phy_data); if (ret_val) goto out; phy->is_mdix = (phy_data & M88E1000_PSSR_MDIX) ? true : false; if ((phy_data & M88E1000_PSSR_SPEED) == M88E1000_PSSR_1000MBS) { ret_val = phy->ops.get_cable_length(hw); if (ret_val) goto out; ret_val = phy->ops.read_reg(hw, PHY_1000T_STATUS, &phy_data); if (ret_val) goto out; phy->local_rx = (phy_data & SR_1000T_LOCAL_RX_STATUS) ? e1000_1000t_rx_status_ok : e1000_1000t_rx_status_not_ok; phy->remote_rx = (phy_data & SR_1000T_REMOTE_RX_STATUS) ? e1000_1000t_rx_status_ok : e1000_1000t_rx_status_not_ok; } else { /* Set values to "undefined" */ phy->cable_length = E1000_CABLE_LENGTH_UNDEFINED; phy->local_rx = e1000_1000t_rx_status_undefined; phy->remote_rx = e1000_1000t_rx_status_undefined; } out: return ret_val; } /** * igb_get_phy_info_igp - Retrieve igp PHY information * @hw: pointer to the HW structure * * Read PHY status to determine if link is up. If link is up, then * set/determine 10base-T extended distance and polarity correction. Read * PHY port status to determine MDI/MDIx and speed. Based on the speed, * determine on the cable length, local and remote receiver. **/ s32 igb_get_phy_info_igp(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; u16 data; bool link; ret_val = igb_phy_has_link(hw, 1, 0, &link); if (ret_val) goto out; if (!link) { hw_dbg("Phy info is only valid if link is up\n"); ret_val = -E1000_ERR_CONFIG; goto out; } phy->polarity_correction = true; ret_val = igb_check_polarity_igp(hw); if (ret_val) goto out; ret_val = phy->ops.read_reg(hw, IGP01E1000_PHY_PORT_STATUS, &data); if (ret_val) goto out; phy->is_mdix = (data & IGP01E1000_PSSR_MDIX) ? true : false; if ((data & IGP01E1000_PSSR_SPEED_MASK) == IGP01E1000_PSSR_SPEED_1000MBPS) { ret_val = phy->ops.get_cable_length(hw); if (ret_val) goto out; ret_val = phy->ops.read_reg(hw, PHY_1000T_STATUS, &data); if (ret_val) goto out; phy->local_rx = (data & SR_1000T_LOCAL_RX_STATUS) ? e1000_1000t_rx_status_ok : e1000_1000t_rx_status_not_ok; phy->remote_rx = (data & SR_1000T_REMOTE_RX_STATUS) ? e1000_1000t_rx_status_ok : e1000_1000t_rx_status_not_ok; } else { phy->cable_length = E1000_CABLE_LENGTH_UNDEFINED; phy->local_rx = e1000_1000t_rx_status_undefined; phy->remote_rx = e1000_1000t_rx_status_undefined; } out: return ret_val; } /** * igb_phy_sw_reset - PHY software reset * @hw: pointer to the HW structure * * Does a software reset of the PHY by reading the PHY control register and * setting/write the control register reset bit to the PHY. **/ s32 igb_phy_sw_reset(struct e1000_hw *hw) { s32 ret_val = 0; u16 phy_ctrl; if (!(hw->phy.ops.read_reg)) goto out; ret_val = hw->phy.ops.read_reg(hw, PHY_CONTROL, &phy_ctrl); if (ret_val) goto out; phy_ctrl |= MII_CR_RESET; ret_val = hw->phy.ops.write_reg(hw, PHY_CONTROL, phy_ctrl); if (ret_val) goto out; udelay(1); out: return ret_val; } /** * igb_phy_hw_reset - PHY hardware reset * @hw: pointer to the HW structure * * Verify the reset block is not blocking us from resetting. Acquire * semaphore (if necessary) and read/set/write the device control reset * bit in the PHY. Wait the appropriate delay time for the device to * reset and release the semaphore (if necessary). **/ s32 igb_phy_hw_reset(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; u32 ctrl; ret_val = igb_check_reset_block(hw); if (ret_val) { ret_val = 0; goto out; } ret_val = phy->ops.acquire(hw); if (ret_val) goto out; ctrl = rd32(E1000_CTRL); wr32(E1000_CTRL, ctrl | E1000_CTRL_PHY_RST); wrfl(); udelay(phy->reset_delay_us); wr32(E1000_CTRL, ctrl); wrfl(); udelay(150); phy->ops.release(hw); ret_val = phy->ops.get_cfg_done(hw); out: return ret_val; } /** * igb_phy_init_script_igp3 - Inits the IGP3 PHY * @hw: pointer to the HW structure * * Initializes a Intel Gigabit PHY3 when an EEPROM is not present. **/ s32 igb_phy_init_script_igp3(struct e1000_hw *hw) { hw_dbg("Running IGP 3 PHY init script\n"); /* PHY init IGP 3 */ /* Enable rise/fall, 10-mode work in class-A */ hw->phy.ops.write_reg(hw, 0x2F5B, 0x9018); /* Remove all caps from Replica path filter */ hw->phy.ops.write_reg(hw, 0x2F52, 0x0000); /* Bias trimming for ADC, AFE and Driver (Default) */ hw->phy.ops.write_reg(hw, 0x2FB1, 0x8B24); /* Increase Hybrid poly bias */ hw->phy.ops.write_reg(hw, 0x2FB2, 0xF8F0); /* Add 4% to TX amplitude in Giga mode */ hw->phy.ops.write_reg(hw, 0x2010, 0x10B0); /* Disable trimming (TTT) */ hw->phy.ops.write_reg(hw, 0x2011, 0x0000); /* Poly DC correction to 94.6% + 2% for all channels */ hw->phy.ops.write_reg(hw, 0x20DD, 0x249A); /* ABS DC correction to 95.9% */ hw->phy.ops.write_reg(hw, 0x20DE, 0x00D3); /* BG temp curve trim */ hw->phy.ops.write_reg(hw, 0x28B4, 0x04CE); /* Increasing ADC OPAMP stage 1 currents to max */ hw->phy.ops.write_reg(hw, 0x2F70, 0x29E4); /* Force 1000 ( required for enabling PHY regs configuration) */ hw->phy.ops.write_reg(hw, 0x0000, 0x0140); /* Set upd_freq to 6 */ hw->phy.ops.write_reg(hw, 0x1F30, 0x1606); /* Disable NPDFE */ hw->phy.ops.write_reg(hw, 0x1F31, 0xB814); /* Disable adaptive fixed FFE (Default) */ hw->phy.ops.write_reg(hw, 0x1F35, 0x002A); /* Enable FFE hysteresis */ hw->phy.ops.write_reg(hw, 0x1F3E, 0x0067); /* Fixed FFE for short cable lengths */ hw->phy.ops.write_reg(hw, 0x1F54, 0x0065); /* Fixed FFE for medium cable lengths */ hw->phy.ops.write_reg(hw, 0x1F55, 0x002A); /* Fixed FFE for long cable lengths */ hw->phy.ops.write_reg(hw, 0x1F56, 0x002A); /* Enable Adaptive Clip Threshold */ hw->phy.ops.write_reg(hw, 0x1F72, 0x3FB0); /* AHT reset limit to 1 */ hw->phy.ops.write_reg(hw, 0x1F76, 0xC0FF); /* Set AHT master delay to 127 msec */ hw->phy.ops.write_reg(hw, 0x1F77, 0x1DEC); /* Set scan bits for AHT */ hw->phy.ops.write_reg(hw, 0x1F78, 0xF9EF); /* Set AHT Preset bits */ hw->phy.ops.write_reg(hw, 0x1F79, 0x0210); /* Change integ_factor of channel A to 3 */ hw->phy.ops.write_reg(hw, 0x1895, 0x0003); /* Change prop_factor of channels BCD to 8 */ hw->phy.ops.write_reg(hw, 0x1796, 0x0008); /* Change cg_icount + enable integbp for channels BCD */ hw->phy.ops.write_reg(hw, 0x1798, 0xD008); /* Change cg_icount + enable integbp + change prop_factor_master * to 8 for channel A */ hw->phy.ops.write_reg(hw, 0x1898, 0xD918); /* Disable AHT in Slave mode on channel A */ hw->phy.ops.write_reg(hw, 0x187A, 0x0800); /* Enable LPLU and disable AN to 1000 in non-D0a states, * Enable SPD+B2B */ hw->phy.ops.write_reg(hw, 0x0019, 0x008D); /* Enable restart AN on an1000_dis change */ hw->phy.ops.write_reg(hw, 0x001B, 0x2080); /* Enable wh_fifo read clock in 10/100 modes */ hw->phy.ops.write_reg(hw, 0x0014, 0x0045); /* Restart AN, Speed selection is 1000 */ hw->phy.ops.write_reg(hw, 0x0000, 0x1340); return 0; } /** * igb_initialize_M88E1512_phy - Initialize M88E1512 PHY * @hw: pointer to the HW structure * * Initialize Marvel 1512 to work correctly with Avoton. **/ s32 igb_initialize_M88E1512_phy(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val = 0; /* Switch to PHY page 0xFF. */ ret_val = phy->ops.write_reg(hw, E1000_M88E1543_PAGE_ADDR, 0x00FF); if (ret_val) goto out; ret_val = phy->ops.write_reg(hw, E1000_M88E1512_CFG_REG_2, 0x214B); if (ret_val) goto out; ret_val = phy->ops.write_reg(hw, E1000_M88E1512_CFG_REG_1, 0x2144); if (ret_val) goto out; ret_val = phy->ops.write_reg(hw, E1000_M88E1512_CFG_REG_2, 0x0C28); if (ret_val) goto out; ret_val = phy->ops.write_reg(hw, E1000_M88E1512_CFG_REG_1, 0x2146); if (ret_val) goto out; ret_val = phy->ops.write_reg(hw, E1000_M88E1512_CFG_REG_2, 0xB233); if (ret_val) goto out; ret_val = phy->ops.write_reg(hw, E1000_M88E1512_CFG_REG_1, 0x214D); if (ret_val) goto out; ret_val = phy->ops.write_reg(hw, E1000_M88E1512_CFG_REG_2, 0xCC0C); if (ret_val) goto out; ret_val = phy->ops.write_reg(hw, E1000_M88E1512_CFG_REG_1, 0x2159); if (ret_val) goto out; /* Switch to PHY page 0xFB. */ ret_val = phy->ops.write_reg(hw, E1000_M88E1543_PAGE_ADDR, 0x00FB); if (ret_val) goto out; ret_val = phy->ops.write_reg(hw, E1000_M88E1512_CFG_REG_3, 0x000D); if (ret_val) goto out; /* Switch to PHY page 0x12. */ ret_val = phy->ops.write_reg(hw, E1000_M88E1543_PAGE_ADDR, 0x12); if (ret_val) goto out; /* Change mode to SGMII-to-Copper */ ret_val = phy->ops.write_reg(hw, E1000_M88E1512_MODE, 0x8001); if (ret_val) goto out; /* Return the PHY to page 0. */ ret_val = phy->ops.write_reg(hw, E1000_M88E1543_PAGE_ADDR, 0); if (ret_val) goto out; ret_val = igb_phy_sw_reset(hw); if (ret_val) { hw_dbg("Error committing the PHY changes\n"); return ret_val; } /* msec_delay(1000); */ usleep_range(1000, 2000); out: return ret_val; } /** * igb_initialize_M88E1543_phy - Initialize M88E1512 PHY * @hw: pointer to the HW structure * * Initialize Marvell 1543 to work correctly with Avoton. **/ s32 igb_initialize_M88E1543_phy(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val = 0; /* Switch to PHY page 0xFF. */ ret_val = phy->ops.write_reg(hw, E1000_M88E1543_PAGE_ADDR, 0x00FF); if (ret_val) goto out; ret_val = phy->ops.write_reg(hw, E1000_M88E1512_CFG_REG_2, 0x214B); if (ret_val) goto out; ret_val = phy->ops.write_reg(hw, E1000_M88E1512_CFG_REG_1, 0x2144); if (ret_val) goto out; ret_val = phy->ops.write_reg(hw, E1000_M88E1512_CFG_REG_2, 0x0C28); if (ret_val) goto out; ret_val = phy->ops.write_reg(hw, E1000_M88E1512_CFG_REG_1, 0x2146); if (ret_val) goto out; ret_val = phy->ops.write_reg(hw, E1000_M88E1512_CFG_REG_2, 0xB233); if (ret_val) goto out; ret_val = phy->ops.write_reg(hw, E1000_M88E1512_CFG_REG_1, 0x214D); if (ret_val) goto out; ret_val = phy->ops.write_reg(hw, E1000_M88E1512_CFG_REG_2, 0xDC0C); if (ret_val) goto out; ret_val = phy->ops.write_reg(hw, E1000_M88E1512_CFG_REG_1, 0x2159); if (ret_val) goto out; /* Switch to PHY page 0xFB. */ ret_val = phy->ops.write_reg(hw, E1000_M88E1543_PAGE_ADDR, 0x00FB); if (ret_val) goto out; ret_val = phy->ops.write_reg(hw, E1000_M88E1512_CFG_REG_3, 0x0C0D); if (ret_val) goto out; /* Switch to PHY page 0x12. */ ret_val = phy->ops.write_reg(hw, E1000_M88E1543_PAGE_ADDR, 0x12); if (ret_val) goto out; /* Change mode to SGMII-to-Copper */ ret_val = phy->ops.write_reg(hw, E1000_M88E1512_MODE, 0x8001); if (ret_val) goto out; /* Switch to PHY page 1. */ ret_val = phy->ops.write_reg(hw, E1000_M88E1543_PAGE_ADDR, 0x1); if (ret_val) goto out; /* Change mode to 1000BASE-X/SGMII and autoneg enable */ ret_val = phy->ops.write_reg(hw, E1000_M88E1543_FIBER_CTRL, 0x9140); if (ret_val) goto out; /* Return the PHY to page 0. */ ret_val = phy->ops.write_reg(hw, E1000_M88E1543_PAGE_ADDR, 0); if (ret_val) goto out; ret_val = igb_phy_sw_reset(hw); if (ret_val) { hw_dbg("Error committing the PHY changes\n"); return ret_val; } /* msec_delay(1000); */ usleep_range(1000, 2000); out: return ret_val; } /** * igb_power_up_phy_copper - Restore copper link in case of PHY power down * @hw: pointer to the HW structure * * In the case of a PHY power down to save power, or to turn off link during a * driver unload, restore the link to previous settings. **/ void igb_power_up_phy_copper(struct e1000_hw *hw) { u16 mii_reg = 0; /* The PHY will retain its settings across a power down/up cycle */ hw->phy.ops.read_reg(hw, PHY_CONTROL, &mii_reg); mii_reg &= ~MII_CR_POWER_DOWN; hw->phy.ops.write_reg(hw, PHY_CONTROL, mii_reg); } /** * igb_power_down_phy_copper - Power down copper PHY * @hw: pointer to the HW structure * * Power down PHY to save power when interface is down and wake on lan * is not enabled. **/ void igb_power_down_phy_copper(struct e1000_hw *hw) { u16 mii_reg = 0; /* The PHY will retain its settings across a power down/up cycle */ hw->phy.ops.read_reg(hw, PHY_CONTROL, &mii_reg); mii_reg |= MII_CR_POWER_DOWN; hw->phy.ops.write_reg(hw, PHY_CONTROL, mii_reg); usleep_range(1000, 2000); } /** * igb_check_polarity_82580 - Checks the polarity. * @hw: pointer to the HW structure * * Success returns 0, Failure returns -E1000_ERR_PHY (-2) * * Polarity is determined based on the PHY specific status register. **/ static s32 igb_check_polarity_82580(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; u16 data; ret_val = phy->ops.read_reg(hw, I82580_PHY_STATUS_2, &data); if (!ret_val) phy->cable_polarity = (data & I82580_PHY_STATUS2_REV_POLARITY) ? e1000_rev_polarity_reversed : e1000_rev_polarity_normal; return ret_val; } /** * igb_phy_force_speed_duplex_82580 - Force speed/duplex for I82580 PHY * @hw: pointer to the HW structure * * Calls the PHY setup function to force speed and duplex. Clears the * auto-crossover to force MDI manually. Waits for link and returns * successful if link up is successful, else -E1000_ERR_PHY (-2). **/ s32 igb_phy_force_speed_duplex_82580(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; u16 phy_data; bool link; ret_val = phy->ops.read_reg(hw, PHY_CONTROL, &phy_data); if (ret_val) goto out; igb_phy_force_speed_duplex_setup(hw, &phy_data); ret_val = phy->ops.write_reg(hw, PHY_CONTROL, phy_data); if (ret_val) goto out; /* Clear Auto-Crossover to force MDI manually. 82580 requires MDI * forced whenever speed and duplex are forced. */ ret_val = phy->ops.read_reg(hw, I82580_PHY_CTRL_2, &phy_data); if (ret_val) goto out; phy_data &= ~I82580_PHY_CTRL2_MDIX_CFG_MASK; ret_val = phy->ops.write_reg(hw, I82580_PHY_CTRL_2, phy_data); if (ret_val) goto out; hw_dbg("I82580_PHY_CTRL_2: %X\n", phy_data); udelay(1); if (phy->autoneg_wait_to_complete) { hw_dbg("Waiting for forced speed/duplex link on 82580 phy\n"); ret_val = igb_phy_has_link(hw, PHY_FORCE_LIMIT, 100000, &link); if (ret_val) goto out; if (!link) hw_dbg("Link taking longer than expected.\n"); /* Try once more */ ret_val = igb_phy_has_link(hw, PHY_FORCE_LIMIT, 100000, &link); if (ret_val) goto out; } out: return ret_val; } /** * igb_get_phy_info_82580 - Retrieve I82580 PHY information * @hw: pointer to the HW structure * * Read PHY status to determine if link is up. If link is up, then * set/determine 10base-T extended distance and polarity correction. Read * PHY port status to determine MDI/MDIx and speed. Based on the speed, * determine on the cable length, local and remote receiver. **/ s32 igb_get_phy_info_82580(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; u16 data; bool link; ret_val = igb_phy_has_link(hw, 1, 0, &link); if (ret_val) goto out; if (!link) { hw_dbg("Phy info is only valid if link is up\n"); ret_val = -E1000_ERR_CONFIG; goto out; } phy->polarity_correction = true; ret_val = igb_check_polarity_82580(hw); if (ret_val) goto out; ret_val = phy->ops.read_reg(hw, I82580_PHY_STATUS_2, &data); if (ret_val) goto out; phy->is_mdix = (data & I82580_PHY_STATUS2_MDIX) ? true : false; if ((data & I82580_PHY_STATUS2_SPEED_MASK) == I82580_PHY_STATUS2_SPEED_1000MBPS) { ret_val = hw->phy.ops.get_cable_length(hw); if (ret_val) goto out; ret_val = phy->ops.read_reg(hw, PHY_1000T_STATUS, &data); if (ret_val) goto out; phy->local_rx = (data & SR_1000T_LOCAL_RX_STATUS) ? e1000_1000t_rx_status_ok : e1000_1000t_rx_status_not_ok; phy->remote_rx = (data & SR_1000T_REMOTE_RX_STATUS) ? e1000_1000t_rx_status_ok : e1000_1000t_rx_status_not_ok; } else { phy->cable_length = E1000_CABLE_LENGTH_UNDEFINED; phy->local_rx = e1000_1000t_rx_status_undefined; phy->remote_rx = e1000_1000t_rx_status_undefined; } out: return ret_val; } /** * igb_get_cable_length_82580 - Determine cable length for 82580 PHY * @hw: pointer to the HW structure * * Reads the diagnostic status register and verifies result is valid before * placing it in the phy_cable_length field. **/ s32 igb_get_cable_length_82580(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; u16 phy_data, length; ret_val = phy->ops.read_reg(hw, I82580_PHY_DIAG_STATUS, &phy_data); if (ret_val) goto out; length = (phy_data & I82580_DSTATUS_CABLE_LENGTH) >> I82580_DSTATUS_CABLE_LENGTH_SHIFT; if (length == E1000_CABLE_LENGTH_UNDEFINED) ret_val = -E1000_ERR_PHY; phy->cable_length = length; out: return ret_val; } /** * igb_set_master_slave_mode - Setup PHY for Master/slave mode * @hw: pointer to the HW structure * * Sets up Master/slave mode **/ static s32 igb_set_master_slave_mode(struct e1000_hw *hw) { s32 ret_val; u16 phy_data; /* Resolve Master/Slave mode */ ret_val = hw->phy.ops.read_reg(hw, PHY_1000T_CTRL, &phy_data); if (ret_val) return ret_val; /* load defaults for future use */ hw->phy.original_ms_type = (phy_data & CR_1000T_MS_ENABLE) ? ((phy_data & CR_1000T_MS_VALUE) ? e1000_ms_force_master : e1000_ms_force_slave) : e1000_ms_auto; switch (hw->phy.ms_type) { case e1000_ms_force_master: phy_data |= (CR_1000T_MS_ENABLE | CR_1000T_MS_VALUE); break; case e1000_ms_force_slave: phy_data |= CR_1000T_MS_ENABLE; phy_data &= ~(CR_1000T_MS_VALUE); break; case e1000_ms_auto: phy_data &= ~CR_1000T_MS_ENABLE; fallthrough; default: break; } return hw->phy.ops.write_reg(hw, PHY_1000T_CTRL, phy_data); }
linux-master
drivers/net/ethernet/intel/igb/e1000_phy.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2007 - 2018 Intel Corporation. */ /* e1000_82575 * e1000_82576 */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/types.h> #include <linux/if_ether.h> #include <linux/i2c.h> #include "e1000_mac.h" #include "e1000_82575.h" #include "e1000_i210.h" #include "igb.h" static s32 igb_get_invariants_82575(struct e1000_hw *); static s32 igb_acquire_phy_82575(struct e1000_hw *); static void igb_release_phy_82575(struct e1000_hw *); static s32 igb_acquire_nvm_82575(struct e1000_hw *); static void igb_release_nvm_82575(struct e1000_hw *); static s32 igb_check_for_link_82575(struct e1000_hw *); static s32 igb_get_cfg_done_82575(struct e1000_hw *); static s32 igb_init_hw_82575(struct e1000_hw *); static s32 igb_phy_hw_reset_sgmii_82575(struct e1000_hw *); static s32 igb_read_phy_reg_sgmii_82575(struct e1000_hw *, u32, u16 *); static s32 igb_reset_hw_82575(struct e1000_hw *); static s32 igb_reset_hw_82580(struct e1000_hw *); static s32 igb_set_d0_lplu_state_82575(struct e1000_hw *, bool); static s32 igb_set_d0_lplu_state_82580(struct e1000_hw *, bool); static s32 igb_set_d3_lplu_state_82580(struct e1000_hw *, bool); static s32 igb_setup_copper_link_82575(struct e1000_hw *); static s32 igb_setup_serdes_link_82575(struct e1000_hw *); static s32 igb_write_phy_reg_sgmii_82575(struct e1000_hw *, u32, u16); static void igb_clear_hw_cntrs_82575(struct e1000_hw *); static s32 igb_acquire_swfw_sync_82575(struct e1000_hw *, u16); static s32 igb_get_pcs_speed_and_duplex_82575(struct e1000_hw *, u16 *, u16 *); static s32 igb_get_phy_id_82575(struct e1000_hw *); static void igb_release_swfw_sync_82575(struct e1000_hw *, u16); static bool igb_sgmii_active_82575(struct e1000_hw *); static s32 igb_reset_init_script_82575(struct e1000_hw *); static s32 igb_read_mac_addr_82575(struct e1000_hw *); static s32 igb_set_pcie_completion_timeout(struct e1000_hw *hw); static s32 igb_reset_mdicnfg_82580(struct e1000_hw *hw); static s32 igb_validate_nvm_checksum_82580(struct e1000_hw *hw); static s32 igb_update_nvm_checksum_82580(struct e1000_hw *hw); static s32 igb_validate_nvm_checksum_i350(struct e1000_hw *hw); static s32 igb_update_nvm_checksum_i350(struct e1000_hw *hw); static const u16 e1000_82580_rxpbs_table[] = { 36, 72, 144, 1, 2, 4, 8, 16, 35, 70, 140 }; /* Due to a hw errata, if the host tries to configure the VFTA register * while performing queries from the BMC or DMA, then the VFTA in some * cases won't be written. */ /** * igb_write_vfta_i350 - Write value to VLAN filter table * @hw: pointer to the HW structure * @offset: register offset in VLAN filter table * @value: register value written to VLAN filter table * * Writes value at the given offset in the register array which stores * the VLAN filter table. **/ static void igb_write_vfta_i350(struct e1000_hw *hw, u32 offset, u32 value) { struct igb_adapter *adapter = hw->back; int i; for (i = 10; i--;) array_wr32(E1000_VFTA, offset, value); wrfl(); adapter->shadow_vfta[offset] = value; } /** * igb_sgmii_uses_mdio_82575 - Determine if I2C pins are for external MDIO * @hw: pointer to the HW structure * * Called to determine if the I2C pins are being used for I2C or as an * external MDIO interface since the two options are mutually exclusive. **/ static bool igb_sgmii_uses_mdio_82575(struct e1000_hw *hw) { u32 reg = 0; bool ext_mdio = false; switch (hw->mac.type) { case e1000_82575: case e1000_82576: reg = rd32(E1000_MDIC); ext_mdio = !!(reg & E1000_MDIC_DEST); break; case e1000_82580: case e1000_i350: case e1000_i354: case e1000_i210: case e1000_i211: reg = rd32(E1000_MDICNFG); ext_mdio = !!(reg & E1000_MDICNFG_EXT_MDIO); break; default: break; } return ext_mdio; } /** * igb_check_for_link_media_swap - Check which M88E1112 interface linked * @hw: pointer to the HW structure * * Poll the M88E1112 interfaces to see which interface achieved link. */ static s32 igb_check_for_link_media_swap(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; u16 data; u8 port = 0; /* Check the copper medium. */ ret_val = phy->ops.write_reg(hw, E1000_M88E1112_PAGE_ADDR, 0); if (ret_val) return ret_val; ret_val = phy->ops.read_reg(hw, E1000_M88E1112_STATUS, &data); if (ret_val) return ret_val; if (data & E1000_M88E1112_STATUS_LINK) port = E1000_MEDIA_PORT_COPPER; /* Check the other medium. */ ret_val = phy->ops.write_reg(hw, E1000_M88E1112_PAGE_ADDR, 1); if (ret_val) return ret_val; ret_val = phy->ops.read_reg(hw, E1000_M88E1112_STATUS, &data); if (ret_val) return ret_val; if (data & E1000_M88E1112_STATUS_LINK) port = E1000_MEDIA_PORT_OTHER; /* Determine if a swap needs to happen. */ if (port && (hw->dev_spec._82575.media_port != port)) { hw->dev_spec._82575.media_port = port; hw->dev_spec._82575.media_changed = true; } if (port == E1000_MEDIA_PORT_COPPER) { /* reset page to 0 */ ret_val = phy->ops.write_reg(hw, E1000_M88E1112_PAGE_ADDR, 0); if (ret_val) return ret_val; igb_check_for_link_82575(hw); } else { igb_check_for_link_82575(hw); /* reset page to 0 */ ret_val = phy->ops.write_reg(hw, E1000_M88E1112_PAGE_ADDR, 0); if (ret_val) return ret_val; } return 0; } /** * igb_init_phy_params_82575 - Init PHY func ptrs. * @hw: pointer to the HW structure **/ static s32 igb_init_phy_params_82575(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val = 0; u32 ctrl_ext; if (hw->phy.media_type != e1000_media_type_copper) { phy->type = e1000_phy_none; goto out; } phy->autoneg_mask = AUTONEG_ADVERTISE_SPEED_DEFAULT; phy->reset_delay_us = 100; ctrl_ext = rd32(E1000_CTRL_EXT); if (igb_sgmii_active_82575(hw)) { phy->ops.reset = igb_phy_hw_reset_sgmii_82575; ctrl_ext |= E1000_CTRL_I2C_ENA; } else { phy->ops.reset = igb_phy_hw_reset; ctrl_ext &= ~E1000_CTRL_I2C_ENA; } wr32(E1000_CTRL_EXT, ctrl_ext); igb_reset_mdicnfg_82580(hw); if (igb_sgmii_active_82575(hw) && !igb_sgmii_uses_mdio_82575(hw)) { phy->ops.read_reg = igb_read_phy_reg_sgmii_82575; phy->ops.write_reg = igb_write_phy_reg_sgmii_82575; } else { switch (hw->mac.type) { case e1000_82580: case e1000_i350: case e1000_i354: case e1000_i210: case e1000_i211: phy->ops.read_reg = igb_read_phy_reg_82580; phy->ops.write_reg = igb_write_phy_reg_82580; break; default: phy->ops.read_reg = igb_read_phy_reg_igp; phy->ops.write_reg = igb_write_phy_reg_igp; } } /* set lan id */ hw->bus.func = (rd32(E1000_STATUS) & E1000_STATUS_FUNC_MASK) >> E1000_STATUS_FUNC_SHIFT; /* Set phy->phy_addr and phy->id. */ ret_val = igb_get_phy_id_82575(hw); if (ret_val) return ret_val; /* Verify phy id and set remaining function pointers */ switch (phy->id) { case M88E1543_E_PHY_ID: case M88E1512_E_PHY_ID: case I347AT4_E_PHY_ID: case M88E1112_E_PHY_ID: case M88E1111_I_PHY_ID: phy->type = e1000_phy_m88; phy->ops.check_polarity = igb_check_polarity_m88; phy->ops.get_phy_info = igb_get_phy_info_m88; if (phy->id != M88E1111_I_PHY_ID) phy->ops.get_cable_length = igb_get_cable_length_m88_gen2; else phy->ops.get_cable_length = igb_get_cable_length_m88; phy->ops.force_speed_duplex = igb_phy_force_speed_duplex_m88; /* Check if this PHY is configured for media swap. */ if (phy->id == M88E1112_E_PHY_ID) { u16 data; ret_val = phy->ops.write_reg(hw, E1000_M88E1112_PAGE_ADDR, 2); if (ret_val) goto out; ret_val = phy->ops.read_reg(hw, E1000_M88E1112_MAC_CTRL_1, &data); if (ret_val) goto out; data = (data & E1000_M88E1112_MAC_CTRL_1_MODE_MASK) >> E1000_M88E1112_MAC_CTRL_1_MODE_SHIFT; if (data == E1000_M88E1112_AUTO_COPPER_SGMII || data == E1000_M88E1112_AUTO_COPPER_BASEX) hw->mac.ops.check_for_link = igb_check_for_link_media_swap; } if (phy->id == M88E1512_E_PHY_ID) { ret_val = igb_initialize_M88E1512_phy(hw); if (ret_val) goto out; } if (phy->id == M88E1543_E_PHY_ID) { ret_val = igb_initialize_M88E1543_phy(hw); if (ret_val) goto out; } break; case IGP03E1000_E_PHY_ID: phy->type = e1000_phy_igp_3; phy->ops.get_phy_info = igb_get_phy_info_igp; phy->ops.get_cable_length = igb_get_cable_length_igp_2; phy->ops.force_speed_duplex = igb_phy_force_speed_duplex_igp; phy->ops.set_d0_lplu_state = igb_set_d0_lplu_state_82575; phy->ops.set_d3_lplu_state = igb_set_d3_lplu_state; break; case I82580_I_PHY_ID: case I350_I_PHY_ID: phy->type = e1000_phy_82580; phy->ops.force_speed_duplex = igb_phy_force_speed_duplex_82580; phy->ops.get_cable_length = igb_get_cable_length_82580; phy->ops.get_phy_info = igb_get_phy_info_82580; phy->ops.set_d0_lplu_state = igb_set_d0_lplu_state_82580; phy->ops.set_d3_lplu_state = igb_set_d3_lplu_state_82580; break; case I210_I_PHY_ID: phy->type = e1000_phy_i210; phy->ops.check_polarity = igb_check_polarity_m88; phy->ops.get_cfg_done = igb_get_cfg_done_i210; phy->ops.get_phy_info = igb_get_phy_info_m88; phy->ops.get_cable_length = igb_get_cable_length_m88_gen2; phy->ops.set_d0_lplu_state = igb_set_d0_lplu_state_82580; phy->ops.set_d3_lplu_state = igb_set_d3_lplu_state_82580; phy->ops.force_speed_duplex = igb_phy_force_speed_duplex_m88; break; case BCM54616_E_PHY_ID: phy->type = e1000_phy_bcm54616; break; default: ret_val = -E1000_ERR_PHY; goto out; } out: return ret_val; } /** * igb_init_nvm_params_82575 - Init NVM func ptrs. * @hw: pointer to the HW structure **/ static s32 igb_init_nvm_params_82575(struct e1000_hw *hw) { struct e1000_nvm_info *nvm = &hw->nvm; u32 eecd = rd32(E1000_EECD); u16 size; size = (u16)((eecd & E1000_EECD_SIZE_EX_MASK) >> E1000_EECD_SIZE_EX_SHIFT); /* Added to a constant, "size" becomes the left-shift value * for setting word_size. */ size += NVM_WORD_SIZE_BASE_SHIFT; /* Just in case size is out of range, cap it to the largest * EEPROM size supported */ if (size > 15) size = 15; nvm->word_size = BIT(size); nvm->opcode_bits = 8; nvm->delay_usec = 1; switch (nvm->override) { case e1000_nvm_override_spi_large: nvm->page_size = 32; nvm->address_bits = 16; break; case e1000_nvm_override_spi_small: nvm->page_size = 8; nvm->address_bits = 8; break; default: nvm->page_size = eecd & E1000_EECD_ADDR_BITS ? 32 : 8; nvm->address_bits = eecd & E1000_EECD_ADDR_BITS ? 16 : 8; break; } if (nvm->word_size == BIT(15)) nvm->page_size = 128; nvm->type = e1000_nvm_eeprom_spi; /* NVM Function Pointers */ nvm->ops.acquire = igb_acquire_nvm_82575; nvm->ops.release = igb_release_nvm_82575; nvm->ops.write = igb_write_nvm_spi; nvm->ops.validate = igb_validate_nvm_checksum; nvm->ops.update = igb_update_nvm_checksum; if (nvm->word_size < BIT(15)) nvm->ops.read = igb_read_nvm_eerd; else nvm->ops.read = igb_read_nvm_spi; /* override generic family function pointers for specific descendants */ switch (hw->mac.type) { case e1000_82580: nvm->ops.validate = igb_validate_nvm_checksum_82580; nvm->ops.update = igb_update_nvm_checksum_82580; break; case e1000_i354: case e1000_i350: nvm->ops.validate = igb_validate_nvm_checksum_i350; nvm->ops.update = igb_update_nvm_checksum_i350; break; default: break; } return 0; } /** * igb_init_mac_params_82575 - Init MAC func ptrs. * @hw: pointer to the HW structure **/ static s32 igb_init_mac_params_82575(struct e1000_hw *hw) { struct e1000_mac_info *mac = &hw->mac; struct e1000_dev_spec_82575 *dev_spec = &hw->dev_spec._82575; /* Set mta register count */ mac->mta_reg_count = 128; /* Set uta register count */ mac->uta_reg_count = (hw->mac.type == e1000_82575) ? 0 : 128; /* Set rar entry count */ switch (mac->type) { case e1000_82576: mac->rar_entry_count = E1000_RAR_ENTRIES_82576; break; case e1000_82580: mac->rar_entry_count = E1000_RAR_ENTRIES_82580; break; case e1000_i350: case e1000_i354: mac->rar_entry_count = E1000_RAR_ENTRIES_I350; break; default: mac->rar_entry_count = E1000_RAR_ENTRIES_82575; break; } /* reset */ if (mac->type >= e1000_82580) mac->ops.reset_hw = igb_reset_hw_82580; else mac->ops.reset_hw = igb_reset_hw_82575; if (mac->type >= e1000_i210) { mac->ops.acquire_swfw_sync = igb_acquire_swfw_sync_i210; mac->ops.release_swfw_sync = igb_release_swfw_sync_i210; } else { mac->ops.acquire_swfw_sync = igb_acquire_swfw_sync_82575; mac->ops.release_swfw_sync = igb_release_swfw_sync_82575; } if ((hw->mac.type == e1000_i350) || (hw->mac.type == e1000_i354)) mac->ops.write_vfta = igb_write_vfta_i350; else mac->ops.write_vfta = igb_write_vfta; /* Set if part includes ASF firmware */ mac->asf_firmware_present = true; /* Set if manageability features are enabled. */ mac->arc_subsystem_valid = (rd32(E1000_FWSM) & E1000_FWSM_MODE_MASK) ? true : false; /* enable EEE on i350 parts and later parts */ if (mac->type >= e1000_i350) dev_spec->eee_disable = false; else dev_spec->eee_disable = true; /* Allow a single clear of the SW semaphore on I210 and newer */ if (mac->type >= e1000_i210) dev_spec->clear_semaphore_once = true; /* physical interface link setup */ mac->ops.setup_physical_interface = (hw->phy.media_type == e1000_media_type_copper) ? igb_setup_copper_link_82575 : igb_setup_serdes_link_82575; if (mac->type == e1000_82580 || mac->type == e1000_i350) { switch (hw->device_id) { /* feature not supported on these id's */ case E1000_DEV_ID_DH89XXCC_SGMII: case E1000_DEV_ID_DH89XXCC_SERDES: case E1000_DEV_ID_DH89XXCC_BACKPLANE: case E1000_DEV_ID_DH89XXCC_SFP: break; default: hw->dev_spec._82575.mas_capable = true; break; } } return 0; } /** * igb_set_sfp_media_type_82575 - derives SFP module media type. * @hw: pointer to the HW structure * * The media type is chosen based on SFP module. * compatibility flags retrieved from SFP ID EEPROM. **/ static s32 igb_set_sfp_media_type_82575(struct e1000_hw *hw) { s32 ret_val = E1000_ERR_CONFIG; u32 ctrl_ext = 0; struct e1000_dev_spec_82575 *dev_spec = &hw->dev_spec._82575; struct e1000_sfp_flags *eth_flags = &dev_spec->eth_flags; u8 tranceiver_type = 0; s32 timeout = 3; /* Turn I2C interface ON and power on sfp cage */ ctrl_ext = rd32(E1000_CTRL_EXT); ctrl_ext &= ~E1000_CTRL_EXT_SDP3_DATA; wr32(E1000_CTRL_EXT, ctrl_ext | E1000_CTRL_I2C_ENA); wrfl(); /* Read SFP module data */ while (timeout) { ret_val = igb_read_sfp_data_byte(hw, E1000_I2CCMD_SFP_DATA_ADDR(E1000_SFF_IDENTIFIER_OFFSET), &tranceiver_type); if (ret_val == 0) break; msleep(100); timeout--; } if (ret_val != 0) goto out; ret_val = igb_read_sfp_data_byte(hw, E1000_I2CCMD_SFP_DATA_ADDR(E1000_SFF_ETH_FLAGS_OFFSET), (u8 *)eth_flags); if (ret_val != 0) goto out; /* Check if there is some SFP module plugged and powered */ if ((tranceiver_type == E1000_SFF_IDENTIFIER_SFP) || (tranceiver_type == E1000_SFF_IDENTIFIER_SFF)) { dev_spec->module_plugged = true; if (eth_flags->e1000_base_lx || eth_flags->e1000_base_sx) { hw->phy.media_type = e1000_media_type_internal_serdes; } else if (eth_flags->e100_base_fx || eth_flags->e100_base_lx) { dev_spec->sgmii_active = true; hw->phy.media_type = e1000_media_type_internal_serdes; } else if (eth_flags->e1000_base_t) { dev_spec->sgmii_active = true; hw->phy.media_type = e1000_media_type_copper; } else { hw->phy.media_type = e1000_media_type_unknown; hw_dbg("PHY module has not been recognized\n"); goto out; } } else { hw->phy.media_type = e1000_media_type_unknown; } ret_val = 0; out: /* Restore I2C interface setting */ wr32(E1000_CTRL_EXT, ctrl_ext); return ret_val; } static s32 igb_get_invariants_82575(struct e1000_hw *hw) { struct e1000_mac_info *mac = &hw->mac; struct e1000_dev_spec_82575 *dev_spec = &hw->dev_spec._82575; s32 ret_val; u32 ctrl_ext = 0; u32 link_mode = 0; switch (hw->device_id) { case E1000_DEV_ID_82575EB_COPPER: case E1000_DEV_ID_82575EB_FIBER_SERDES: case E1000_DEV_ID_82575GB_QUAD_COPPER: mac->type = e1000_82575; break; case E1000_DEV_ID_82576: case E1000_DEV_ID_82576_NS: case E1000_DEV_ID_82576_NS_SERDES: case E1000_DEV_ID_82576_FIBER: case E1000_DEV_ID_82576_SERDES: case E1000_DEV_ID_82576_QUAD_COPPER: case E1000_DEV_ID_82576_QUAD_COPPER_ET2: case E1000_DEV_ID_82576_SERDES_QUAD: mac->type = e1000_82576; break; case E1000_DEV_ID_82580_COPPER: case E1000_DEV_ID_82580_FIBER: case E1000_DEV_ID_82580_QUAD_FIBER: case E1000_DEV_ID_82580_SERDES: case E1000_DEV_ID_82580_SGMII: case E1000_DEV_ID_82580_COPPER_DUAL: case E1000_DEV_ID_DH89XXCC_SGMII: case E1000_DEV_ID_DH89XXCC_SERDES: case E1000_DEV_ID_DH89XXCC_BACKPLANE: case E1000_DEV_ID_DH89XXCC_SFP: mac->type = e1000_82580; break; case E1000_DEV_ID_I350_COPPER: case E1000_DEV_ID_I350_FIBER: case E1000_DEV_ID_I350_SERDES: case E1000_DEV_ID_I350_SGMII: mac->type = e1000_i350; break; case E1000_DEV_ID_I210_COPPER: case E1000_DEV_ID_I210_FIBER: case E1000_DEV_ID_I210_SERDES: case E1000_DEV_ID_I210_SGMII: case E1000_DEV_ID_I210_COPPER_FLASHLESS: case E1000_DEV_ID_I210_SERDES_FLASHLESS: mac->type = e1000_i210; break; case E1000_DEV_ID_I211_COPPER: mac->type = e1000_i211; break; case E1000_DEV_ID_I354_BACKPLANE_1GBPS: case E1000_DEV_ID_I354_SGMII: case E1000_DEV_ID_I354_BACKPLANE_2_5GBPS: mac->type = e1000_i354; break; default: return -E1000_ERR_MAC_INIT; } /* Set media type */ /* The 82575 uses bits 22:23 for link mode. The mode can be changed * based on the EEPROM. We cannot rely upon device ID. There * is no distinguishable difference between fiber and internal * SerDes mode on the 82575. There can be an external PHY attached * on the SGMII interface. For this, we'll set sgmii_active to true. */ hw->phy.media_type = e1000_media_type_copper; dev_spec->sgmii_active = false; dev_spec->module_plugged = false; ctrl_ext = rd32(E1000_CTRL_EXT); link_mode = ctrl_ext & E1000_CTRL_EXT_LINK_MODE_MASK; switch (link_mode) { case E1000_CTRL_EXT_LINK_MODE_1000BASE_KX: hw->phy.media_type = e1000_media_type_internal_serdes; break; case E1000_CTRL_EXT_LINK_MODE_SGMII: /* Get phy control interface type set (MDIO vs. I2C)*/ if (igb_sgmii_uses_mdio_82575(hw)) { hw->phy.media_type = e1000_media_type_copper; dev_spec->sgmii_active = true; break; } fallthrough; /* for I2C based SGMII */ case E1000_CTRL_EXT_LINK_MODE_PCIE_SERDES: /* read media type from SFP EEPROM */ ret_val = igb_set_sfp_media_type_82575(hw); if ((ret_val != 0) || (hw->phy.media_type == e1000_media_type_unknown)) { /* If media type was not identified then return media * type defined by the CTRL_EXT settings. */ hw->phy.media_type = e1000_media_type_internal_serdes; if (link_mode == E1000_CTRL_EXT_LINK_MODE_SGMII) { hw->phy.media_type = e1000_media_type_copper; dev_spec->sgmii_active = true; } break; } /* change current link mode setting */ ctrl_ext &= ~E1000_CTRL_EXT_LINK_MODE_MASK; if (dev_spec->sgmii_active) ctrl_ext |= E1000_CTRL_EXT_LINK_MODE_SGMII; else ctrl_ext |= E1000_CTRL_EXT_LINK_MODE_PCIE_SERDES; wr32(E1000_CTRL_EXT, ctrl_ext); break; default: break; } /* mac initialization and operations */ ret_val = igb_init_mac_params_82575(hw); if (ret_val) goto out; /* NVM initialization */ ret_val = igb_init_nvm_params_82575(hw); switch (hw->mac.type) { case e1000_i210: case e1000_i211: ret_val = igb_init_nvm_params_i210(hw); break; default: break; } if (ret_val) goto out; /* if part supports SR-IOV then initialize mailbox parameters */ switch (mac->type) { case e1000_82576: case e1000_i350: igb_init_mbx_params_pf(hw); break; default: break; } /* setup PHY parameters */ ret_val = igb_init_phy_params_82575(hw); out: return ret_val; } /** * igb_acquire_phy_82575 - Acquire rights to access PHY * @hw: pointer to the HW structure * * Acquire access rights to the correct PHY. This is a * function pointer entry point called by the api module. **/ static s32 igb_acquire_phy_82575(struct e1000_hw *hw) { u16 mask = E1000_SWFW_PHY0_SM; if (hw->bus.func == E1000_FUNC_1) mask = E1000_SWFW_PHY1_SM; else if (hw->bus.func == E1000_FUNC_2) mask = E1000_SWFW_PHY2_SM; else if (hw->bus.func == E1000_FUNC_3) mask = E1000_SWFW_PHY3_SM; return hw->mac.ops.acquire_swfw_sync(hw, mask); } /** * igb_release_phy_82575 - Release rights to access PHY * @hw: pointer to the HW structure * * A wrapper to release access rights to the correct PHY. This is a * function pointer entry point called by the api module. **/ static void igb_release_phy_82575(struct e1000_hw *hw) { u16 mask = E1000_SWFW_PHY0_SM; if (hw->bus.func == E1000_FUNC_1) mask = E1000_SWFW_PHY1_SM; else if (hw->bus.func == E1000_FUNC_2) mask = E1000_SWFW_PHY2_SM; else if (hw->bus.func == E1000_FUNC_3) mask = E1000_SWFW_PHY3_SM; hw->mac.ops.release_swfw_sync(hw, mask); } /** * igb_read_phy_reg_sgmii_82575 - Read PHY register using sgmii * @hw: pointer to the HW structure * @offset: register offset to be read * @data: pointer to the read data * * Reads the PHY register at offset using the serial gigabit media independent * interface and stores the retrieved information in data. **/ static s32 igb_read_phy_reg_sgmii_82575(struct e1000_hw *hw, u32 offset, u16 *data) { s32 ret_val = -E1000_ERR_PARAM; if (offset > E1000_MAX_SGMII_PHY_REG_ADDR) { hw_dbg("PHY Address %u is out of range\n", offset); goto out; } ret_val = hw->phy.ops.acquire(hw); if (ret_val) goto out; ret_val = igb_read_phy_reg_i2c(hw, offset, data); hw->phy.ops.release(hw); out: return ret_val; } /** * igb_write_phy_reg_sgmii_82575 - Write PHY register using sgmii * @hw: pointer to the HW structure * @offset: register offset to write to * @data: data to write at register offset * * Writes the data to PHY register at the offset using the serial gigabit * media independent interface. **/ static s32 igb_write_phy_reg_sgmii_82575(struct e1000_hw *hw, u32 offset, u16 data) { s32 ret_val = -E1000_ERR_PARAM; if (offset > E1000_MAX_SGMII_PHY_REG_ADDR) { hw_dbg("PHY Address %d is out of range\n", offset); goto out; } ret_val = hw->phy.ops.acquire(hw); if (ret_val) goto out; ret_val = igb_write_phy_reg_i2c(hw, offset, data); hw->phy.ops.release(hw); out: return ret_val; } /** * igb_get_phy_id_82575 - Retrieve PHY addr and id * @hw: pointer to the HW structure * * Retrieves the PHY address and ID for both PHY's which do and do not use * sgmi interface. **/ static s32 igb_get_phy_id_82575(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val = 0; u16 phy_id; u32 ctrl_ext; u32 mdic; /* Extra read required for some PHY's on i354 */ if (hw->mac.type == e1000_i354) igb_get_phy_id(hw); /* For SGMII PHYs, we try the list of possible addresses until * we find one that works. For non-SGMII PHYs * (e.g. integrated copper PHYs), an address of 1 should * work. The result of this function should mean phy->phy_addr * and phy->id are set correctly. */ if (!(igb_sgmii_active_82575(hw))) { phy->addr = 1; ret_val = igb_get_phy_id(hw); goto out; } if (igb_sgmii_uses_mdio_82575(hw)) { switch (hw->mac.type) { case e1000_82575: case e1000_82576: mdic = rd32(E1000_MDIC); mdic &= E1000_MDIC_PHY_MASK; phy->addr = mdic >> E1000_MDIC_PHY_SHIFT; break; case e1000_82580: case e1000_i350: case e1000_i354: case e1000_i210: case e1000_i211: mdic = rd32(E1000_MDICNFG); mdic &= E1000_MDICNFG_PHY_MASK; phy->addr = mdic >> E1000_MDICNFG_PHY_SHIFT; break; default: ret_val = -E1000_ERR_PHY; goto out; } ret_val = igb_get_phy_id(hw); goto out; } /* Power on sgmii phy if it is disabled */ ctrl_ext = rd32(E1000_CTRL_EXT); wr32(E1000_CTRL_EXT, ctrl_ext & ~E1000_CTRL_EXT_SDP3_DATA); wrfl(); msleep(300); /* The address field in the I2CCMD register is 3 bits and 0 is invalid. * Therefore, we need to test 1-7 */ for (phy->addr = 1; phy->addr < 8; phy->addr++) { ret_val = igb_read_phy_reg_sgmii_82575(hw, PHY_ID1, &phy_id); if (ret_val == 0) { hw_dbg("Vendor ID 0x%08X read at address %u\n", phy_id, phy->addr); /* At the time of this writing, The M88 part is * the only supported SGMII PHY product. */ if (phy_id == M88_VENDOR) break; } else { hw_dbg("PHY address %u was unreadable\n", phy->addr); } } /* A valid PHY type couldn't be found. */ if (phy->addr == 8) { phy->addr = 0; ret_val = -E1000_ERR_PHY; goto out; } else { ret_val = igb_get_phy_id(hw); } /* restore previous sfp cage power state */ wr32(E1000_CTRL_EXT, ctrl_ext); out: return ret_val; } /** * igb_phy_hw_reset_sgmii_82575 - Performs a PHY reset * @hw: pointer to the HW structure * * Resets the PHY using the serial gigabit media independent interface. **/ static s32 igb_phy_hw_reset_sgmii_82575(struct e1000_hw *hw) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; /* This isn't a true "hard" reset, but is the only reset * available to us at this time. */ hw_dbg("Soft resetting SGMII attached PHY...\n"); /* SFP documentation requires the following to configure the SPF module * to work on SGMII. No further documentation is given. */ ret_val = hw->phy.ops.write_reg(hw, 0x1B, 0x8084); if (ret_val) goto out; ret_val = igb_phy_sw_reset(hw); if (ret_val) goto out; if (phy->id == M88E1512_E_PHY_ID) ret_val = igb_initialize_M88E1512_phy(hw); if (phy->id == M88E1543_E_PHY_ID) ret_val = igb_initialize_M88E1543_phy(hw); out: return ret_val; } /** * igb_set_d0_lplu_state_82575 - Set Low Power Linkup D0 state * @hw: pointer to the HW structure * @active: true to enable LPLU, false to disable * * Sets the LPLU D0 state according to the active flag. When * activating LPLU this function also disables smart speed * and vice versa. LPLU will not be activated unless the * device autonegotiation advertisement meets standards of * either 10 or 10/100 or 10/100/1000 at all duplexes. * This is a function pointer entry point only called by * PHY setup routines. **/ static s32 igb_set_d0_lplu_state_82575(struct e1000_hw *hw, bool active) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val; u16 data; ret_val = phy->ops.read_reg(hw, IGP02E1000_PHY_POWER_MGMT, &data); if (ret_val) goto out; if (active) { data |= IGP02E1000_PM_D0_LPLU; ret_val = phy->ops.write_reg(hw, IGP02E1000_PHY_POWER_MGMT, data); if (ret_val) goto out; /* When LPLU is enabled, we should disable SmartSpeed */ ret_val = phy->ops.read_reg(hw, IGP01E1000_PHY_PORT_CONFIG, &data); data &= ~IGP01E1000_PSCFR_SMART_SPEED; ret_val = phy->ops.write_reg(hw, IGP01E1000_PHY_PORT_CONFIG, data); if (ret_val) goto out; } else { data &= ~IGP02E1000_PM_D0_LPLU; ret_val = phy->ops.write_reg(hw, IGP02E1000_PHY_POWER_MGMT, data); /* LPLU and SmartSpeed are mutually exclusive. LPLU is used * during Dx states where the power conservation is most * important. During driver activity we should enable * SmartSpeed, so performance is maintained. */ if (phy->smart_speed == e1000_smart_speed_on) { ret_val = phy->ops.read_reg(hw, IGP01E1000_PHY_PORT_CONFIG, &data); if (ret_val) goto out; data |= IGP01E1000_PSCFR_SMART_SPEED; ret_val = phy->ops.write_reg(hw, IGP01E1000_PHY_PORT_CONFIG, data); if (ret_val) goto out; } else if (phy->smart_speed == e1000_smart_speed_off) { ret_val = phy->ops.read_reg(hw, IGP01E1000_PHY_PORT_CONFIG, &data); if (ret_val) goto out; data &= ~IGP01E1000_PSCFR_SMART_SPEED; ret_val = phy->ops.write_reg(hw, IGP01E1000_PHY_PORT_CONFIG, data); if (ret_val) goto out; } } out: return ret_val; } /** * igb_set_d0_lplu_state_82580 - Set Low Power Linkup D0 state * @hw: pointer to the HW structure * @active: true to enable LPLU, false to disable * * Sets the LPLU D0 state according to the active flag. When * activating LPLU this function also disables smart speed * and vice versa. LPLU will not be activated unless the * device autonegotiation advertisement meets standards of * either 10 or 10/100 or 10/100/1000 at all duplexes. * This is a function pointer entry point only called by * PHY setup routines. **/ static s32 igb_set_d0_lplu_state_82580(struct e1000_hw *hw, bool active) { struct e1000_phy_info *phy = &hw->phy; u16 data; data = rd32(E1000_82580_PHY_POWER_MGMT); if (active) { data |= E1000_82580_PM_D0_LPLU; /* When LPLU is enabled, we should disable SmartSpeed */ data &= ~E1000_82580_PM_SPD; } else { data &= ~E1000_82580_PM_D0_LPLU; /* LPLU and SmartSpeed are mutually exclusive. LPLU is used * during Dx states where the power conservation is most * important. During driver activity we should enable * SmartSpeed, so performance is maintained. */ if (phy->smart_speed == e1000_smart_speed_on) data |= E1000_82580_PM_SPD; else if (phy->smart_speed == e1000_smart_speed_off) data &= ~E1000_82580_PM_SPD; } wr32(E1000_82580_PHY_POWER_MGMT, data); return 0; } /** * igb_set_d3_lplu_state_82580 - Sets low power link up state for D3 * @hw: pointer to the HW structure * @active: boolean used to enable/disable lplu * * Success returns 0, Failure returns 1 * * The low power link up (lplu) state is set to the power management level D3 * and SmartSpeed is disabled when active is true, else clear lplu for D3 * and enable Smartspeed. LPLU and Smartspeed are mutually exclusive. LPLU * is used during Dx states where the power conservation is most important. * During driver activity, SmartSpeed should be enabled so performance is * maintained. **/ static s32 igb_set_d3_lplu_state_82580(struct e1000_hw *hw, bool active) { struct e1000_phy_info *phy = &hw->phy; u16 data; data = rd32(E1000_82580_PHY_POWER_MGMT); if (!active) { data &= ~E1000_82580_PM_D3_LPLU; /* LPLU and SmartSpeed are mutually exclusive. LPLU is used * during Dx states where the power conservation is most * important. During driver activity we should enable * SmartSpeed, so performance is maintained. */ if (phy->smart_speed == e1000_smart_speed_on) data |= E1000_82580_PM_SPD; else if (phy->smart_speed == e1000_smart_speed_off) data &= ~E1000_82580_PM_SPD; } else if ((phy->autoneg_advertised == E1000_ALL_SPEED_DUPLEX) || (phy->autoneg_advertised == E1000_ALL_NOT_GIG) || (phy->autoneg_advertised == E1000_ALL_10_SPEED)) { data |= E1000_82580_PM_D3_LPLU; /* When LPLU is enabled, we should disable SmartSpeed */ data &= ~E1000_82580_PM_SPD; } wr32(E1000_82580_PHY_POWER_MGMT, data); return 0; } /** * igb_acquire_nvm_82575 - Request for access to EEPROM * @hw: pointer to the HW structure * * Acquire the necessary semaphores for exclusive access to the EEPROM. * Set the EEPROM access request bit and wait for EEPROM access grant bit. * Return successful if access grant bit set, else clear the request for * EEPROM access and return -E1000_ERR_NVM (-1). **/ static s32 igb_acquire_nvm_82575(struct e1000_hw *hw) { s32 ret_val; ret_val = hw->mac.ops.acquire_swfw_sync(hw, E1000_SWFW_EEP_SM); if (ret_val) goto out; ret_val = igb_acquire_nvm(hw); if (ret_val) hw->mac.ops.release_swfw_sync(hw, E1000_SWFW_EEP_SM); out: return ret_val; } /** * igb_release_nvm_82575 - Release exclusive access to EEPROM * @hw: pointer to the HW structure * * Stop any current commands to the EEPROM and clear the EEPROM request bit, * then release the semaphores acquired. **/ static void igb_release_nvm_82575(struct e1000_hw *hw) { igb_release_nvm(hw); hw->mac.ops.release_swfw_sync(hw, E1000_SWFW_EEP_SM); } /** * igb_acquire_swfw_sync_82575 - Acquire SW/FW semaphore * @hw: pointer to the HW structure * @mask: specifies which semaphore to acquire * * Acquire the SW/FW semaphore to access the PHY or NVM. The mask * will also specify which port we're acquiring the lock for. **/ static s32 igb_acquire_swfw_sync_82575(struct e1000_hw *hw, u16 mask) { u32 swfw_sync; u32 swmask = mask; u32 fwmask = mask << 16; s32 ret_val = 0; s32 i = 0, timeout = 200; while (i < timeout) { if (igb_get_hw_semaphore(hw)) { ret_val = -E1000_ERR_SWFW_SYNC; goto out; } swfw_sync = rd32(E1000_SW_FW_SYNC); if (!(swfw_sync & (fwmask | swmask))) break; /* Firmware currently using resource (fwmask) * or other software thread using resource (swmask) */ igb_put_hw_semaphore(hw); mdelay(5); i++; } if (i == timeout) { hw_dbg("Driver can't access resource, SW_FW_SYNC timeout.\n"); ret_val = -E1000_ERR_SWFW_SYNC; goto out; } swfw_sync |= swmask; wr32(E1000_SW_FW_SYNC, swfw_sync); igb_put_hw_semaphore(hw); out: return ret_val; } /** * igb_release_swfw_sync_82575 - Release SW/FW semaphore * @hw: pointer to the HW structure * @mask: specifies which semaphore to acquire * * Release the SW/FW semaphore used to access the PHY or NVM. The mask * will also specify which port we're releasing the lock for. **/ static void igb_release_swfw_sync_82575(struct e1000_hw *hw, u16 mask) { u32 swfw_sync; while (igb_get_hw_semaphore(hw) != 0) ; /* Empty */ swfw_sync = rd32(E1000_SW_FW_SYNC); swfw_sync &= ~mask; wr32(E1000_SW_FW_SYNC, swfw_sync); igb_put_hw_semaphore(hw); } /** * igb_get_cfg_done_82575 - Read config done bit * @hw: pointer to the HW structure * * Read the management control register for the config done bit for * completion status. NOTE: silicon which is EEPROM-less will fail trying * to read the config done bit, so an error is *ONLY* logged and returns * 0. If we were to return with error, EEPROM-less silicon * would not be able to be reset or change link. **/ static s32 igb_get_cfg_done_82575(struct e1000_hw *hw) { s32 timeout = PHY_CFG_TIMEOUT; u32 mask = E1000_NVM_CFG_DONE_PORT_0; if (hw->bus.func == 1) mask = E1000_NVM_CFG_DONE_PORT_1; else if (hw->bus.func == E1000_FUNC_2) mask = E1000_NVM_CFG_DONE_PORT_2; else if (hw->bus.func == E1000_FUNC_3) mask = E1000_NVM_CFG_DONE_PORT_3; while (timeout) { if (rd32(E1000_EEMNGCTL) & mask) break; usleep_range(1000, 2000); timeout--; } if (!timeout) hw_dbg("MNG configuration cycle has not completed.\n"); /* If EEPROM is not marked present, init the PHY manually */ if (((rd32(E1000_EECD) & E1000_EECD_PRES) == 0) && (hw->phy.type == e1000_phy_igp_3)) igb_phy_init_script_igp3(hw); return 0; } /** * igb_get_link_up_info_82575 - Get link speed/duplex info * @hw: pointer to the HW structure * @speed: stores the current speed * @duplex: stores the current duplex * * This is a wrapper function, if using the serial gigabit media independent * interface, use PCS to retrieve the link speed and duplex information. * Otherwise, use the generic function to get the link speed and duplex info. **/ static s32 igb_get_link_up_info_82575(struct e1000_hw *hw, u16 *speed, u16 *duplex) { s32 ret_val; if (hw->phy.media_type != e1000_media_type_copper) ret_val = igb_get_pcs_speed_and_duplex_82575(hw, speed, duplex); else ret_val = igb_get_speed_and_duplex_copper(hw, speed, duplex); return ret_val; } /** * igb_check_for_link_82575 - Check for link * @hw: pointer to the HW structure * * If sgmii is enabled, then use the pcs register to determine link, otherwise * use the generic interface for determining link. **/ static s32 igb_check_for_link_82575(struct e1000_hw *hw) { s32 ret_val; u16 speed, duplex; if (hw->phy.media_type != e1000_media_type_copper) { ret_val = igb_get_pcs_speed_and_duplex_82575(hw, &speed, &duplex); /* Use this flag to determine if link needs to be checked or * not. If we have link clear the flag so that we do not * continue to check for link. */ hw->mac.get_link_status = !hw->mac.serdes_has_link; /* Configure Flow Control now that Auto-Neg has completed. * First, we need to restore the desired flow control * settings because we may have had to re-autoneg with a * different link partner. */ ret_val = igb_config_fc_after_link_up(hw); if (ret_val) hw_dbg("Error configuring flow control\n"); } else { ret_val = igb_check_for_copper_link(hw); } return ret_val; } /** * igb_power_up_serdes_link_82575 - Power up the serdes link after shutdown * @hw: pointer to the HW structure **/ void igb_power_up_serdes_link_82575(struct e1000_hw *hw) { u32 reg; if ((hw->phy.media_type != e1000_media_type_internal_serdes) && !igb_sgmii_active_82575(hw)) return; /* Enable PCS to turn on link */ reg = rd32(E1000_PCS_CFG0); reg |= E1000_PCS_CFG_PCS_EN; wr32(E1000_PCS_CFG0, reg); /* Power up the laser */ reg = rd32(E1000_CTRL_EXT); reg &= ~E1000_CTRL_EXT_SDP3_DATA; wr32(E1000_CTRL_EXT, reg); /* flush the write to verify completion */ wrfl(); usleep_range(1000, 2000); } /** * igb_get_pcs_speed_and_duplex_82575 - Retrieve current speed/duplex * @hw: pointer to the HW structure * @speed: stores the current speed * @duplex: stores the current duplex * * Using the physical coding sub-layer (PCS), retrieve the current speed and * duplex, then store the values in the pointers provided. **/ static s32 igb_get_pcs_speed_and_duplex_82575(struct e1000_hw *hw, u16 *speed, u16 *duplex) { struct e1000_mac_info *mac = &hw->mac; u32 pcs, status; /* Set up defaults for the return values of this function */ mac->serdes_has_link = false; *speed = 0; *duplex = 0; /* Read the PCS Status register for link state. For non-copper mode, * the status register is not accurate. The PCS status register is * used instead. */ pcs = rd32(E1000_PCS_LSTAT); /* The link up bit determines when link is up on autoneg. The sync ok * gets set once both sides sync up and agree upon link. Stable link * can be determined by checking for both link up and link sync ok */ if ((pcs & E1000_PCS_LSTS_LINK_OK) && (pcs & E1000_PCS_LSTS_SYNK_OK)) { mac->serdes_has_link = true; /* Detect and store PCS speed */ if (pcs & E1000_PCS_LSTS_SPEED_1000) *speed = SPEED_1000; else if (pcs & E1000_PCS_LSTS_SPEED_100) *speed = SPEED_100; else *speed = SPEED_10; /* Detect and store PCS duplex */ if (pcs & E1000_PCS_LSTS_DUPLEX_FULL) *duplex = FULL_DUPLEX; else *duplex = HALF_DUPLEX; /* Check if it is an I354 2.5Gb backplane connection. */ if (mac->type == e1000_i354) { status = rd32(E1000_STATUS); if ((status & E1000_STATUS_2P5_SKU) && !(status & E1000_STATUS_2P5_SKU_OVER)) { *speed = SPEED_2500; *duplex = FULL_DUPLEX; hw_dbg("2500 Mbs, "); hw_dbg("Full Duplex\n"); } } } return 0; } /** * igb_shutdown_serdes_link_82575 - Remove link during power down * @hw: pointer to the HW structure * * In the case of fiber serdes, shut down optics and PCS on driver unload * when management pass thru is not enabled. **/ void igb_shutdown_serdes_link_82575(struct e1000_hw *hw) { u32 reg; if (hw->phy.media_type != e1000_media_type_internal_serdes && igb_sgmii_active_82575(hw)) return; if (!igb_enable_mng_pass_thru(hw)) { /* Disable PCS to turn off link */ reg = rd32(E1000_PCS_CFG0); reg &= ~E1000_PCS_CFG_PCS_EN; wr32(E1000_PCS_CFG0, reg); /* shutdown the laser */ reg = rd32(E1000_CTRL_EXT); reg |= E1000_CTRL_EXT_SDP3_DATA; wr32(E1000_CTRL_EXT, reg); /* flush the write to verify completion */ wrfl(); usleep_range(1000, 2000); } } /** * igb_reset_hw_82575 - Reset hardware * @hw: pointer to the HW structure * * This resets the hardware into a known state. This is a * function pointer entry point called by the api module. **/ static s32 igb_reset_hw_82575(struct e1000_hw *hw) { u32 ctrl; s32 ret_val; /* Prevent the PCI-E bus from sticking if there is no TLP connection * on the last TLP read/write transaction when MAC is reset. */ ret_val = igb_disable_pcie_master(hw); if (ret_val) hw_dbg("PCI-E Master disable polling has failed.\n"); /* set the completion timeout for interface */ ret_val = igb_set_pcie_completion_timeout(hw); if (ret_val) hw_dbg("PCI-E Set completion timeout has failed.\n"); hw_dbg("Masking off all interrupts\n"); wr32(E1000_IMC, 0xffffffff); wr32(E1000_RCTL, 0); wr32(E1000_TCTL, E1000_TCTL_PSP); wrfl(); usleep_range(10000, 20000); ctrl = rd32(E1000_CTRL); hw_dbg("Issuing a global reset to MAC\n"); wr32(E1000_CTRL, ctrl | E1000_CTRL_RST); ret_val = igb_get_auto_rd_done(hw); if (ret_val) { /* When auto config read does not complete, do not * return with an error. This can happen in situations * where there is no eeprom and prevents getting link. */ hw_dbg("Auto Read Done did not complete\n"); } /* If EEPROM is not present, run manual init scripts */ if ((rd32(E1000_EECD) & E1000_EECD_PRES) == 0) igb_reset_init_script_82575(hw); /* Clear any pending interrupt events. */ wr32(E1000_IMC, 0xffffffff); rd32(E1000_ICR); /* Install any alternate MAC address into RAR0 */ ret_val = igb_check_alt_mac_addr(hw); return ret_val; } /** * igb_init_hw_82575 - Initialize hardware * @hw: pointer to the HW structure * * This inits the hardware readying it for operation. **/ static s32 igb_init_hw_82575(struct e1000_hw *hw) { struct e1000_mac_info *mac = &hw->mac; s32 ret_val; u16 i, rar_count = mac->rar_entry_count; if ((hw->mac.type >= e1000_i210) && !(igb_get_flash_presence_i210(hw))) { ret_val = igb_pll_workaround_i210(hw); if (ret_val) return ret_val; } /* Initialize identification LED */ ret_val = igb_id_led_init(hw); if (ret_val) { hw_dbg("Error initializing identification LED\n"); /* This is not fatal and we should not stop init due to this */ } /* Disabling VLAN filtering */ hw_dbg("Initializing the IEEE VLAN\n"); igb_clear_vfta(hw); /* Setup the receive address */ igb_init_rx_addrs(hw, rar_count); /* Zero out the Multicast HASH table */ hw_dbg("Zeroing the MTA\n"); for (i = 0; i < mac->mta_reg_count; i++) array_wr32(E1000_MTA, i, 0); /* Zero out the Unicast HASH table */ hw_dbg("Zeroing the UTA\n"); for (i = 0; i < mac->uta_reg_count; i++) array_wr32(E1000_UTA, i, 0); /* Setup link and flow control */ ret_val = igb_setup_link(hw); /* Clear all of the statistics registers (clear on read). It is * important that we do this after we have tried to establish link * because the symbol error count will increment wildly if there * is no link. */ igb_clear_hw_cntrs_82575(hw); return ret_val; } /** * igb_setup_copper_link_82575 - Configure copper link settings * @hw: pointer to the HW structure * * Configures the link for auto-neg or forced speed and duplex. Then we check * for link, once link is established calls to configure collision distance * and flow control are called. **/ static s32 igb_setup_copper_link_82575(struct e1000_hw *hw) { u32 ctrl; s32 ret_val; u32 phpm_reg; ctrl = rd32(E1000_CTRL); ctrl |= E1000_CTRL_SLU; ctrl &= ~(E1000_CTRL_FRCSPD | E1000_CTRL_FRCDPX); wr32(E1000_CTRL, ctrl); /* Clear Go Link Disconnect bit on supported devices */ switch (hw->mac.type) { case e1000_82580: case e1000_i350: case e1000_i210: case e1000_i211: phpm_reg = rd32(E1000_82580_PHY_POWER_MGMT); phpm_reg &= ~E1000_82580_PM_GO_LINKD; wr32(E1000_82580_PHY_POWER_MGMT, phpm_reg); break; default: break; } ret_val = igb_setup_serdes_link_82575(hw); if (ret_val) goto out; if (igb_sgmii_active_82575(hw) && !hw->phy.reset_disable) { /* allow time for SFP cage time to power up phy */ msleep(300); ret_val = hw->phy.ops.reset(hw); if (ret_val) { hw_dbg("Error resetting the PHY.\n"); goto out; } } switch (hw->phy.type) { case e1000_phy_i210: case e1000_phy_m88: switch (hw->phy.id) { case I347AT4_E_PHY_ID: case M88E1112_E_PHY_ID: case M88E1543_E_PHY_ID: case M88E1512_E_PHY_ID: case I210_I_PHY_ID: ret_val = igb_copper_link_setup_m88_gen2(hw); break; default: ret_val = igb_copper_link_setup_m88(hw); break; } break; case e1000_phy_igp_3: ret_val = igb_copper_link_setup_igp(hw); break; case e1000_phy_82580: ret_val = igb_copper_link_setup_82580(hw); break; case e1000_phy_bcm54616: ret_val = 0; break; default: ret_val = -E1000_ERR_PHY; break; } if (ret_val) goto out; ret_val = igb_setup_copper_link(hw); out: return ret_val; } /** * igb_setup_serdes_link_82575 - Setup link for serdes * @hw: pointer to the HW structure * * Configure the physical coding sub-layer (PCS) link. The PCS link is * used on copper connections where the serialized gigabit media independent * interface (sgmii), or serdes fiber is being used. Configures the link * for auto-negotiation or forces speed/duplex. **/ static s32 igb_setup_serdes_link_82575(struct e1000_hw *hw) { u32 ctrl_ext, ctrl_reg, reg, anadv_reg; bool pcs_autoneg; s32 ret_val = 0; u16 data; if ((hw->phy.media_type != e1000_media_type_internal_serdes) && !igb_sgmii_active_82575(hw)) return ret_val; /* On the 82575, SerDes loopback mode persists until it is * explicitly turned off or a power cycle is performed. A read to * the register does not indicate its status. Therefore, we ensure * loopback mode is disabled during initialization. */ wr32(E1000_SCTL, E1000_SCTL_DISABLE_SERDES_LOOPBACK); /* power on the sfp cage if present and turn on I2C */ ctrl_ext = rd32(E1000_CTRL_EXT); ctrl_ext &= ~E1000_CTRL_EXT_SDP3_DATA; ctrl_ext |= E1000_CTRL_I2C_ENA; wr32(E1000_CTRL_EXT, ctrl_ext); ctrl_reg = rd32(E1000_CTRL); ctrl_reg |= E1000_CTRL_SLU; if (hw->mac.type == e1000_82575 || hw->mac.type == e1000_82576) { /* set both sw defined pins */ ctrl_reg |= E1000_CTRL_SWDPIN0 | E1000_CTRL_SWDPIN1; /* Set switch control to serdes energy detect */ reg = rd32(E1000_CONNSW); reg |= E1000_CONNSW_ENRGSRC; wr32(E1000_CONNSW, reg); } reg = rd32(E1000_PCS_LCTL); /* default pcs_autoneg to the same setting as mac autoneg */ pcs_autoneg = hw->mac.autoneg; switch (ctrl_ext & E1000_CTRL_EXT_LINK_MODE_MASK) { case E1000_CTRL_EXT_LINK_MODE_SGMII: /* sgmii mode lets the phy handle forcing speed/duplex */ pcs_autoneg = true; /* autoneg time out should be disabled for SGMII mode */ reg &= ~(E1000_PCS_LCTL_AN_TIMEOUT); break; case E1000_CTRL_EXT_LINK_MODE_1000BASE_KX: /* disable PCS autoneg and support parallel detect only */ pcs_autoneg = false; fallthrough; default: if (hw->mac.type == e1000_82575 || hw->mac.type == e1000_82576) { ret_val = hw->nvm.ops.read(hw, NVM_COMPAT, 1, &data); if (ret_val) { hw_dbg(KERN_DEBUG "NVM Read Error\n\n"); return ret_val; } if (data & E1000_EEPROM_PCS_AUTONEG_DISABLE_BIT) pcs_autoneg = false; } /* non-SGMII modes only supports a speed of 1000/Full for the * link so it is best to just force the MAC and let the pcs * link either autoneg or be forced to 1000/Full */ ctrl_reg |= E1000_CTRL_SPD_1000 | E1000_CTRL_FRCSPD | E1000_CTRL_FD | E1000_CTRL_FRCDPX; /* set speed of 1000/Full if speed/duplex is forced */ reg |= E1000_PCS_LCTL_FSV_1000 | E1000_PCS_LCTL_FDV_FULL; break; } wr32(E1000_CTRL, ctrl_reg); /* New SerDes mode allows for forcing speed or autonegotiating speed * at 1gb. Autoneg should be default set by most drivers. This is the * mode that will be compatible with older link partners and switches. * However, both are supported by the hardware and some drivers/tools. */ reg &= ~(E1000_PCS_LCTL_AN_ENABLE | E1000_PCS_LCTL_FLV_LINK_UP | E1000_PCS_LCTL_FSD | E1000_PCS_LCTL_FORCE_LINK); if (pcs_autoneg) { /* Set PCS register for autoneg */ reg |= E1000_PCS_LCTL_AN_ENABLE | /* Enable Autoneg */ E1000_PCS_LCTL_AN_RESTART; /* Restart autoneg */ /* Disable force flow control for autoneg */ reg &= ~E1000_PCS_LCTL_FORCE_FCTRL; /* Configure flow control advertisement for autoneg */ anadv_reg = rd32(E1000_PCS_ANADV); anadv_reg &= ~(E1000_TXCW_ASM_DIR | E1000_TXCW_PAUSE); switch (hw->fc.requested_mode) { case e1000_fc_full: case e1000_fc_rx_pause: anadv_reg |= E1000_TXCW_ASM_DIR; anadv_reg |= E1000_TXCW_PAUSE; break; case e1000_fc_tx_pause: anadv_reg |= E1000_TXCW_ASM_DIR; break; default: break; } wr32(E1000_PCS_ANADV, anadv_reg); hw_dbg("Configuring Autoneg:PCS_LCTL=0x%08X\n", reg); } else { /* Set PCS register for forced link */ reg |= E1000_PCS_LCTL_FSD; /* Force Speed */ /* Force flow control for forced link */ reg |= E1000_PCS_LCTL_FORCE_FCTRL; hw_dbg("Configuring Forced Link:PCS_LCTL=0x%08X\n", reg); } wr32(E1000_PCS_LCTL, reg); if (!pcs_autoneg && !igb_sgmii_active_82575(hw)) igb_force_mac_fc(hw); return ret_val; } /** * igb_sgmii_active_82575 - Return sgmii state * @hw: pointer to the HW structure * * 82575 silicon has a serialized gigabit media independent interface (sgmii) * which can be enabled for use in the embedded applications. Simply * return the current state of the sgmii interface. **/ static bool igb_sgmii_active_82575(struct e1000_hw *hw) { struct e1000_dev_spec_82575 *dev_spec = &hw->dev_spec._82575; return dev_spec->sgmii_active; } /** * igb_reset_init_script_82575 - Inits HW defaults after reset * @hw: pointer to the HW structure * * Inits recommended HW defaults after a reset when there is no EEPROM * detected. This is only for the 82575. **/ static s32 igb_reset_init_script_82575(struct e1000_hw *hw) { if (hw->mac.type == e1000_82575) { hw_dbg("Running reset init script for 82575\n"); /* SerDes configuration via SERDESCTRL */ igb_write_8bit_ctrl_reg(hw, E1000_SCTL, 0x00, 0x0C); igb_write_8bit_ctrl_reg(hw, E1000_SCTL, 0x01, 0x78); igb_write_8bit_ctrl_reg(hw, E1000_SCTL, 0x1B, 0x23); igb_write_8bit_ctrl_reg(hw, E1000_SCTL, 0x23, 0x15); /* CCM configuration via CCMCTL register */ igb_write_8bit_ctrl_reg(hw, E1000_CCMCTL, 0x14, 0x00); igb_write_8bit_ctrl_reg(hw, E1000_CCMCTL, 0x10, 0x00); /* PCIe lanes configuration */ igb_write_8bit_ctrl_reg(hw, E1000_GIOCTL, 0x00, 0xEC); igb_write_8bit_ctrl_reg(hw, E1000_GIOCTL, 0x61, 0xDF); igb_write_8bit_ctrl_reg(hw, E1000_GIOCTL, 0x34, 0x05); igb_write_8bit_ctrl_reg(hw, E1000_GIOCTL, 0x2F, 0x81); /* PCIe PLL Configuration */ igb_write_8bit_ctrl_reg(hw, E1000_SCCTL, 0x02, 0x47); igb_write_8bit_ctrl_reg(hw, E1000_SCCTL, 0x14, 0x00); igb_write_8bit_ctrl_reg(hw, E1000_SCCTL, 0x10, 0x00); } return 0; } /** * igb_read_mac_addr_82575 - Read device MAC address * @hw: pointer to the HW structure **/ static s32 igb_read_mac_addr_82575(struct e1000_hw *hw) { s32 ret_val = 0; /* If there's an alternate MAC address place it in RAR0 * so that it will override the Si installed default perm * address. */ ret_val = igb_check_alt_mac_addr(hw); if (ret_val) goto out; ret_val = igb_read_mac_addr(hw); out: return ret_val; } /** * igb_power_down_phy_copper_82575 - Remove link during PHY power down * @hw: pointer to the HW structure * * In the case of a PHY power down to save power, or to turn off link during a * driver unload, or wake on lan is not enabled, remove the link. **/ void igb_power_down_phy_copper_82575(struct e1000_hw *hw) { /* If the management interface is not enabled, then power down */ if (!(igb_enable_mng_pass_thru(hw) || igb_check_reset_block(hw))) igb_power_down_phy_copper(hw); } /** * igb_clear_hw_cntrs_82575 - Clear device specific hardware counters * @hw: pointer to the HW structure * * Clears the hardware counters by reading the counter registers. **/ static void igb_clear_hw_cntrs_82575(struct e1000_hw *hw) { igb_clear_hw_cntrs_base(hw); rd32(E1000_PRC64); rd32(E1000_PRC127); rd32(E1000_PRC255); rd32(E1000_PRC511); rd32(E1000_PRC1023); rd32(E1000_PRC1522); rd32(E1000_PTC64); rd32(E1000_PTC127); rd32(E1000_PTC255); rd32(E1000_PTC511); rd32(E1000_PTC1023); rd32(E1000_PTC1522); rd32(E1000_ALGNERRC); rd32(E1000_RXERRC); rd32(E1000_TNCRS); rd32(E1000_CEXTERR); rd32(E1000_TSCTC); rd32(E1000_TSCTFC); rd32(E1000_MGTPRC); rd32(E1000_MGTPDC); rd32(E1000_MGTPTC); rd32(E1000_IAC); rd32(E1000_ICRXOC); rd32(E1000_ICRXPTC); rd32(E1000_ICRXATC); rd32(E1000_ICTXPTC); rd32(E1000_ICTXATC); rd32(E1000_ICTXQEC); rd32(E1000_ICTXQMTC); rd32(E1000_ICRXDMTC); rd32(E1000_CBTMPC); rd32(E1000_HTDPMC); rd32(E1000_CBRMPC); rd32(E1000_RPTHC); rd32(E1000_HGPTC); rd32(E1000_HTCBDPC); rd32(E1000_HGORCL); rd32(E1000_HGORCH); rd32(E1000_HGOTCL); rd32(E1000_HGOTCH); rd32(E1000_LENERRS); /* This register should not be read in copper configurations */ if (hw->phy.media_type == e1000_media_type_internal_serdes || igb_sgmii_active_82575(hw)) rd32(E1000_SCVPC); } /** * igb_rx_fifo_flush_82575 - Clean rx fifo after RX enable * @hw: pointer to the HW structure * * After rx enable if manageability is enabled then there is likely some * bad data at the start of the fifo and possibly in the DMA fifo. This * function clears the fifos and flushes any packets that came in as rx was * being enabled. **/ void igb_rx_fifo_flush_82575(struct e1000_hw *hw) { u32 rctl, rlpml, rxdctl[4], rfctl, temp_rctl, rx_enabled; int i, ms_wait; /* disable IPv6 options as per hardware errata */ rfctl = rd32(E1000_RFCTL); rfctl |= E1000_RFCTL_IPV6_EX_DIS; wr32(E1000_RFCTL, rfctl); if (hw->mac.type != e1000_82575 || !(rd32(E1000_MANC) & E1000_MANC_RCV_TCO_EN)) return; /* Disable all RX queues */ for (i = 0; i < 4; i++) { rxdctl[i] = rd32(E1000_RXDCTL(i)); wr32(E1000_RXDCTL(i), rxdctl[i] & ~E1000_RXDCTL_QUEUE_ENABLE); } /* Poll all queues to verify they have shut down */ for (ms_wait = 0; ms_wait < 10; ms_wait++) { usleep_range(1000, 2000); rx_enabled = 0; for (i = 0; i < 4; i++) rx_enabled |= rd32(E1000_RXDCTL(i)); if (!(rx_enabled & E1000_RXDCTL_QUEUE_ENABLE)) break; } if (ms_wait == 10) hw_dbg("Queue disable timed out after 10ms\n"); /* Clear RLPML, RCTL.SBP, RFCTL.LEF, and set RCTL.LPE so that all * incoming packets are rejected. Set enable and wait 2ms so that * any packet that was coming in as RCTL.EN was set is flushed */ wr32(E1000_RFCTL, rfctl & ~E1000_RFCTL_LEF); rlpml = rd32(E1000_RLPML); wr32(E1000_RLPML, 0); rctl = rd32(E1000_RCTL); temp_rctl = rctl & ~(E1000_RCTL_EN | E1000_RCTL_SBP); temp_rctl |= E1000_RCTL_LPE; wr32(E1000_RCTL, temp_rctl); wr32(E1000_RCTL, temp_rctl | E1000_RCTL_EN); wrfl(); usleep_range(2000, 3000); /* Enable RX queues that were previously enabled and restore our * previous state */ for (i = 0; i < 4; i++) wr32(E1000_RXDCTL(i), rxdctl[i]); wr32(E1000_RCTL, rctl); wrfl(); wr32(E1000_RLPML, rlpml); wr32(E1000_RFCTL, rfctl); /* Flush receive errors generated by workaround */ rd32(E1000_ROC); rd32(E1000_RNBC); rd32(E1000_MPC); } /** * igb_set_pcie_completion_timeout - set pci-e completion timeout * @hw: pointer to the HW structure * * The defaults for 82575 and 82576 should be in the range of 50us to 50ms, * however the hardware default for these parts is 500us to 1ms which is less * than the 10ms recommended by the pci-e spec. To address this we need to * increase the value to either 10ms to 200ms for capability version 1 config, * or 16ms to 55ms for version 2. **/ static s32 igb_set_pcie_completion_timeout(struct e1000_hw *hw) { u32 gcr = rd32(E1000_GCR); s32 ret_val = 0; u16 pcie_devctl2; /* only take action if timeout value is defaulted to 0 */ if (gcr & E1000_GCR_CMPL_TMOUT_MASK) goto out; /* if capabilities version is type 1 we can write the * timeout of 10ms to 200ms through the GCR register */ if (!(gcr & E1000_GCR_CAP_VER2)) { gcr |= E1000_GCR_CMPL_TMOUT_10ms; goto out; } /* for version 2 capabilities we need to write the config space * directly in order to set the completion timeout value for * 16ms to 55ms */ ret_val = igb_read_pcie_cap_reg(hw, PCIE_DEVICE_CONTROL2, &pcie_devctl2); if (ret_val) goto out; pcie_devctl2 |= PCIE_DEVICE_CONTROL2_16ms; ret_val = igb_write_pcie_cap_reg(hw, PCIE_DEVICE_CONTROL2, &pcie_devctl2); out: /* disable completion timeout resend */ gcr &= ~E1000_GCR_CMPL_TMOUT_RESEND; wr32(E1000_GCR, gcr); return ret_val; } /** * igb_vmdq_set_anti_spoofing_pf - enable or disable anti-spoofing * @hw: pointer to the hardware struct * @enable: state to enter, either enabled or disabled * @pf: Physical Function pool - do not set anti-spoofing for the PF * * enables/disables L2 switch anti-spoofing functionality. **/ void igb_vmdq_set_anti_spoofing_pf(struct e1000_hw *hw, bool enable, int pf) { u32 reg_val, reg_offset; switch (hw->mac.type) { case e1000_82576: reg_offset = E1000_DTXSWC; break; case e1000_i350: case e1000_i354: reg_offset = E1000_TXSWC; break; default: return; } reg_val = rd32(reg_offset); if (enable) { reg_val |= (E1000_DTXSWC_MAC_SPOOF_MASK | E1000_DTXSWC_VLAN_SPOOF_MASK); /* The PF can spoof - it has to in order to * support emulation mode NICs */ reg_val ^= (BIT(pf) | BIT(pf + MAX_NUM_VFS)); } else { reg_val &= ~(E1000_DTXSWC_MAC_SPOOF_MASK | E1000_DTXSWC_VLAN_SPOOF_MASK); } wr32(reg_offset, reg_val); } /** * igb_vmdq_set_loopback_pf - enable or disable vmdq loopback * @hw: pointer to the hardware struct * @enable: state to enter, either enabled or disabled * * enables/disables L2 switch loopback functionality. **/ void igb_vmdq_set_loopback_pf(struct e1000_hw *hw, bool enable) { u32 dtxswc; switch (hw->mac.type) { case e1000_82576: dtxswc = rd32(E1000_DTXSWC); if (enable) dtxswc |= E1000_DTXSWC_VMDQ_LOOPBACK_EN; else dtxswc &= ~E1000_DTXSWC_VMDQ_LOOPBACK_EN; wr32(E1000_DTXSWC, dtxswc); break; case e1000_i354: case e1000_i350: dtxswc = rd32(E1000_TXSWC); if (enable) dtxswc |= E1000_DTXSWC_VMDQ_LOOPBACK_EN; else dtxswc &= ~E1000_DTXSWC_VMDQ_LOOPBACK_EN; wr32(E1000_TXSWC, dtxswc); break; default: /* Currently no other hardware supports loopback */ break; } } /** * igb_vmdq_set_replication_pf - enable or disable vmdq replication * @hw: pointer to the hardware struct * @enable: state to enter, either enabled or disabled * * enables/disables replication of packets across multiple pools. **/ void igb_vmdq_set_replication_pf(struct e1000_hw *hw, bool enable) { u32 vt_ctl = rd32(E1000_VT_CTL); if (enable) vt_ctl |= E1000_VT_CTL_VM_REPL_EN; else vt_ctl &= ~E1000_VT_CTL_VM_REPL_EN; wr32(E1000_VT_CTL, vt_ctl); } /** * igb_read_phy_reg_82580 - Read 82580 MDI control register * @hw: pointer to the HW structure * @offset: register offset to be read * @data: pointer to the read data * * Reads the MDI control register in the PHY at offset and stores the * information read to data. **/ s32 igb_read_phy_reg_82580(struct e1000_hw *hw, u32 offset, u16 *data) { s32 ret_val; ret_val = hw->phy.ops.acquire(hw); if (ret_val) goto out; ret_val = igb_read_phy_reg_mdic(hw, offset, data); hw->phy.ops.release(hw); out: return ret_val; } /** * igb_write_phy_reg_82580 - Write 82580 MDI control register * @hw: pointer to the HW structure * @offset: register offset to write to * @data: data to write to register at offset * * Writes data to MDI control register in the PHY at offset. **/ s32 igb_write_phy_reg_82580(struct e1000_hw *hw, u32 offset, u16 data) { s32 ret_val; ret_val = hw->phy.ops.acquire(hw); if (ret_val) goto out; ret_val = igb_write_phy_reg_mdic(hw, offset, data); hw->phy.ops.release(hw); out: return ret_val; } /** * igb_reset_mdicnfg_82580 - Reset MDICNFG destination and com_mdio bits * @hw: pointer to the HW structure * * This resets the MDICNFG.Destination and MDICNFG.Com_MDIO bits based on * the values found in the EEPROM. This addresses an issue in which these * bits are not restored from EEPROM after reset. **/ static s32 igb_reset_mdicnfg_82580(struct e1000_hw *hw) { s32 ret_val = 0; u32 mdicnfg; u16 nvm_data = 0; if (hw->mac.type != e1000_82580) goto out; if (!igb_sgmii_active_82575(hw)) goto out; ret_val = hw->nvm.ops.read(hw, NVM_INIT_CONTROL3_PORT_A + NVM_82580_LAN_FUNC_OFFSET(hw->bus.func), 1, &nvm_data); if (ret_val) { hw_dbg("NVM Read Error\n"); goto out; } mdicnfg = rd32(E1000_MDICNFG); if (nvm_data & NVM_WORD24_EXT_MDIO) mdicnfg |= E1000_MDICNFG_EXT_MDIO; if (nvm_data & NVM_WORD24_COM_MDIO) mdicnfg |= E1000_MDICNFG_COM_MDIO; wr32(E1000_MDICNFG, mdicnfg); out: return ret_val; } /** * igb_reset_hw_82580 - Reset hardware * @hw: pointer to the HW structure * * This resets function or entire device (all ports, etc.) * to a known state. **/ static s32 igb_reset_hw_82580(struct e1000_hw *hw) { s32 ret_val = 0; /* BH SW mailbox bit in SW_FW_SYNC */ u16 swmbsw_mask = E1000_SW_SYNCH_MB; u32 ctrl; bool global_device_reset = hw->dev_spec._82575.global_device_reset; hw->dev_spec._82575.global_device_reset = false; /* due to hw errata, global device reset doesn't always * work on 82580 */ if (hw->mac.type == e1000_82580) global_device_reset = false; /* Get current control state. */ ctrl = rd32(E1000_CTRL); /* Prevent the PCI-E bus from sticking if there is no TLP connection * on the last TLP read/write transaction when MAC is reset. */ ret_val = igb_disable_pcie_master(hw); if (ret_val) hw_dbg("PCI-E Master disable polling has failed.\n"); hw_dbg("Masking off all interrupts\n"); wr32(E1000_IMC, 0xffffffff); wr32(E1000_RCTL, 0); wr32(E1000_TCTL, E1000_TCTL_PSP); wrfl(); usleep_range(10000, 11000); /* Determine whether or not a global dev reset is requested */ if (global_device_reset && hw->mac.ops.acquire_swfw_sync(hw, swmbsw_mask)) global_device_reset = false; if (global_device_reset && !(rd32(E1000_STATUS) & E1000_STAT_DEV_RST_SET)) ctrl |= E1000_CTRL_DEV_RST; else ctrl |= E1000_CTRL_RST; wr32(E1000_CTRL, ctrl); wrfl(); /* Add delay to insure DEV_RST has time to complete */ if (global_device_reset) usleep_range(5000, 6000); ret_val = igb_get_auto_rd_done(hw); if (ret_val) { /* When auto config read does not complete, do not * return with an error. This can happen in situations * where there is no eeprom and prevents getting link. */ hw_dbg("Auto Read Done did not complete\n"); } /* clear global device reset status bit */ wr32(E1000_STATUS, E1000_STAT_DEV_RST_SET); /* Clear any pending interrupt events. */ wr32(E1000_IMC, 0xffffffff); rd32(E1000_ICR); ret_val = igb_reset_mdicnfg_82580(hw); if (ret_val) hw_dbg("Could not reset MDICNFG based on EEPROM\n"); /* Install any alternate MAC address into RAR0 */ ret_val = igb_check_alt_mac_addr(hw); /* Release semaphore */ if (global_device_reset) hw->mac.ops.release_swfw_sync(hw, swmbsw_mask); return ret_val; } /** * igb_rxpbs_adjust_82580 - adjust RXPBS value to reflect actual RX PBA size * @data: data received by reading RXPBS register * * The 82580 uses a table based approach for packet buffer allocation sizes. * This function converts the retrieved value into the correct table value * 0x0 0x1 0x2 0x3 0x4 0x5 0x6 0x7 * 0x0 36 72 144 1 2 4 8 16 * 0x8 35 70 140 rsv rsv rsv rsv rsv */ u16 igb_rxpbs_adjust_82580(u32 data) { u16 ret_val = 0; if (data < ARRAY_SIZE(e1000_82580_rxpbs_table)) ret_val = e1000_82580_rxpbs_table[data]; return ret_val; } /** * igb_validate_nvm_checksum_with_offset - Validate EEPROM * checksum * @hw: pointer to the HW structure * @offset: offset in words of the checksum protected region * * Calculates the EEPROM checksum by reading/adding each word of the EEPROM * and then verifies that the sum of the EEPROM is equal to 0xBABA. **/ static s32 igb_validate_nvm_checksum_with_offset(struct e1000_hw *hw, u16 offset) { s32 ret_val = 0; u16 checksum = 0; u16 i, nvm_data; for (i = offset; i < ((NVM_CHECKSUM_REG + offset) + 1); i++) { ret_val = hw->nvm.ops.read(hw, i, 1, &nvm_data); if (ret_val) { hw_dbg("NVM Read Error\n"); goto out; } checksum += nvm_data; } if (checksum != (u16) NVM_SUM) { hw_dbg("NVM Checksum Invalid\n"); ret_val = -E1000_ERR_NVM; goto out; } out: return ret_val; } /** * igb_update_nvm_checksum_with_offset - Update EEPROM * checksum * @hw: pointer to the HW structure * @offset: offset in words of the checksum protected region * * Updates the EEPROM checksum by reading/adding each word of the EEPROM * up to the checksum. Then calculates the EEPROM checksum and writes the * value to the EEPROM. **/ static s32 igb_update_nvm_checksum_with_offset(struct e1000_hw *hw, u16 offset) { s32 ret_val; u16 checksum = 0; u16 i, nvm_data; for (i = offset; i < (NVM_CHECKSUM_REG + offset); i++) { ret_val = hw->nvm.ops.read(hw, i, 1, &nvm_data); if (ret_val) { hw_dbg("NVM Read Error while updating checksum.\n"); goto out; } checksum += nvm_data; } checksum = (u16) NVM_SUM - checksum; ret_val = hw->nvm.ops.write(hw, (NVM_CHECKSUM_REG + offset), 1, &checksum); if (ret_val) hw_dbg("NVM Write Error while updating checksum.\n"); out: return ret_val; } /** * igb_validate_nvm_checksum_82580 - Validate EEPROM checksum * @hw: pointer to the HW structure * * Calculates the EEPROM section checksum by reading/adding each word of * the EEPROM and then verifies that the sum of the EEPROM is * equal to 0xBABA. **/ static s32 igb_validate_nvm_checksum_82580(struct e1000_hw *hw) { s32 ret_val = 0; u16 eeprom_regions_count = 1; u16 j, nvm_data; u16 nvm_offset; ret_val = hw->nvm.ops.read(hw, NVM_COMPATIBILITY_REG_3, 1, &nvm_data); if (ret_val) { hw_dbg("NVM Read Error\n"); goto out; } if (nvm_data & NVM_COMPATIBILITY_BIT_MASK) { /* if checksums compatibility bit is set validate checksums * for all 4 ports. */ eeprom_regions_count = 4; } for (j = 0; j < eeprom_regions_count; j++) { nvm_offset = NVM_82580_LAN_FUNC_OFFSET(j); ret_val = igb_validate_nvm_checksum_with_offset(hw, nvm_offset); if (ret_val != 0) goto out; } out: return ret_val; } /** * igb_update_nvm_checksum_82580 - Update EEPROM checksum * @hw: pointer to the HW structure * * Updates the EEPROM section checksums for all 4 ports by reading/adding * each word of the EEPROM up to the checksum. Then calculates the EEPROM * checksum and writes the value to the EEPROM. **/ static s32 igb_update_nvm_checksum_82580(struct e1000_hw *hw) { s32 ret_val; u16 j, nvm_data; u16 nvm_offset; ret_val = hw->nvm.ops.read(hw, NVM_COMPATIBILITY_REG_3, 1, &nvm_data); if (ret_val) { hw_dbg("NVM Read Error while updating checksum compatibility bit.\n"); goto out; } if ((nvm_data & NVM_COMPATIBILITY_BIT_MASK) == 0) { /* set compatibility bit to validate checksums appropriately */ nvm_data = nvm_data | NVM_COMPATIBILITY_BIT_MASK; ret_val = hw->nvm.ops.write(hw, NVM_COMPATIBILITY_REG_3, 1, &nvm_data); if (ret_val) { hw_dbg("NVM Write Error while updating checksum compatibility bit.\n"); goto out; } } for (j = 0; j < 4; j++) { nvm_offset = NVM_82580_LAN_FUNC_OFFSET(j); ret_val = igb_update_nvm_checksum_with_offset(hw, nvm_offset); if (ret_val) goto out; } out: return ret_val; } /** * igb_validate_nvm_checksum_i350 - Validate EEPROM checksum * @hw: pointer to the HW structure * * Calculates the EEPROM section checksum by reading/adding each word of * the EEPROM and then verifies that the sum of the EEPROM is * equal to 0xBABA. **/ static s32 igb_validate_nvm_checksum_i350(struct e1000_hw *hw) { s32 ret_val = 0; u16 j; u16 nvm_offset; for (j = 0; j < 4; j++) { nvm_offset = NVM_82580_LAN_FUNC_OFFSET(j); ret_val = igb_validate_nvm_checksum_with_offset(hw, nvm_offset); if (ret_val != 0) goto out; } out: return ret_val; } /** * igb_update_nvm_checksum_i350 - Update EEPROM checksum * @hw: pointer to the HW structure * * Updates the EEPROM section checksums for all 4 ports by reading/adding * each word of the EEPROM up to the checksum. Then calculates the EEPROM * checksum and writes the value to the EEPROM. **/ static s32 igb_update_nvm_checksum_i350(struct e1000_hw *hw) { s32 ret_val = 0; u16 j; u16 nvm_offset; for (j = 0; j < 4; j++) { nvm_offset = NVM_82580_LAN_FUNC_OFFSET(j); ret_val = igb_update_nvm_checksum_with_offset(hw, nvm_offset); if (ret_val != 0) goto out; } out: return ret_val; } /** * __igb_access_emi_reg - Read/write EMI register * @hw: pointer to the HW structure * @address: EMI address to program * @data: pointer to value to read/write from/to the EMI address * @read: boolean flag to indicate read or write **/ static s32 __igb_access_emi_reg(struct e1000_hw *hw, u16 address, u16 *data, bool read) { s32 ret_val = 0; ret_val = hw->phy.ops.write_reg(hw, E1000_EMIADD, address); if (ret_val) return ret_val; if (read) ret_val = hw->phy.ops.read_reg(hw, E1000_EMIDATA, data); else ret_val = hw->phy.ops.write_reg(hw, E1000_EMIDATA, *data); return ret_val; } /** * igb_read_emi_reg - Read Extended Management Interface register * @hw: pointer to the HW structure * @addr: EMI address to program * @data: value to be read from the EMI address **/ s32 igb_read_emi_reg(struct e1000_hw *hw, u16 addr, u16 *data) { return __igb_access_emi_reg(hw, addr, data, true); } /** * igb_set_eee_i350 - Enable/disable EEE support * @hw: pointer to the HW structure * @adv1G: boolean flag enabling 1G EEE advertisement * @adv100M: boolean flag enabling 100M EEE advertisement * * Enable/disable EEE based on setting in dev_spec structure. * **/ s32 igb_set_eee_i350(struct e1000_hw *hw, bool adv1G, bool adv100M) { u32 ipcnfg, eeer; if ((hw->mac.type < e1000_i350) || (hw->phy.media_type != e1000_media_type_copper)) goto out; ipcnfg = rd32(E1000_IPCNFG); eeer = rd32(E1000_EEER); /* enable or disable per user setting */ if (!(hw->dev_spec._82575.eee_disable)) { u32 eee_su = rd32(E1000_EEE_SU); if (adv100M) ipcnfg |= E1000_IPCNFG_EEE_100M_AN; else ipcnfg &= ~E1000_IPCNFG_EEE_100M_AN; if (adv1G) ipcnfg |= E1000_IPCNFG_EEE_1G_AN; else ipcnfg &= ~E1000_IPCNFG_EEE_1G_AN; eeer |= (E1000_EEER_TX_LPI_EN | E1000_EEER_RX_LPI_EN | E1000_EEER_LPI_FC); /* This bit should not be set in normal operation. */ if (eee_su & E1000_EEE_SU_LPI_CLK_STP) hw_dbg("LPI Clock Stop Bit should not be set!\n"); } else { ipcnfg &= ~(E1000_IPCNFG_EEE_1G_AN | E1000_IPCNFG_EEE_100M_AN); eeer &= ~(E1000_EEER_TX_LPI_EN | E1000_EEER_RX_LPI_EN | E1000_EEER_LPI_FC); } wr32(E1000_IPCNFG, ipcnfg); wr32(E1000_EEER, eeer); rd32(E1000_IPCNFG); rd32(E1000_EEER); out: return 0; } /** * igb_set_eee_i354 - Enable/disable EEE support * @hw: pointer to the HW structure * @adv1G: boolean flag enabling 1G EEE advertisement * @adv100M: boolean flag enabling 100M EEE advertisement * * Enable/disable EEE legacy mode based on setting in dev_spec structure. * **/ s32 igb_set_eee_i354(struct e1000_hw *hw, bool adv1G, bool adv100M) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val = 0; u16 phy_data; if ((hw->phy.media_type != e1000_media_type_copper) || ((phy->id != M88E1543_E_PHY_ID) && (phy->id != M88E1512_E_PHY_ID))) goto out; if (!hw->dev_spec._82575.eee_disable) { /* Switch to PHY page 18. */ ret_val = phy->ops.write_reg(hw, E1000_M88E1543_PAGE_ADDR, 18); if (ret_val) goto out; ret_val = phy->ops.read_reg(hw, E1000_M88E1543_EEE_CTRL_1, &phy_data); if (ret_val) goto out; phy_data |= E1000_M88E1543_EEE_CTRL_1_MS; ret_val = phy->ops.write_reg(hw, E1000_M88E1543_EEE_CTRL_1, phy_data); if (ret_val) goto out; /* Return the PHY to page 0. */ ret_val = phy->ops.write_reg(hw, E1000_M88E1543_PAGE_ADDR, 0); if (ret_val) goto out; /* Turn on EEE advertisement. */ ret_val = igb_read_xmdio_reg(hw, E1000_EEE_ADV_ADDR_I354, E1000_EEE_ADV_DEV_I354, &phy_data); if (ret_val) goto out; if (adv100M) phy_data |= E1000_EEE_ADV_100_SUPPORTED; else phy_data &= ~E1000_EEE_ADV_100_SUPPORTED; if (adv1G) phy_data |= E1000_EEE_ADV_1000_SUPPORTED; else phy_data &= ~E1000_EEE_ADV_1000_SUPPORTED; ret_val = igb_write_xmdio_reg(hw, E1000_EEE_ADV_ADDR_I354, E1000_EEE_ADV_DEV_I354, phy_data); } else { /* Turn off EEE advertisement. */ ret_val = igb_read_xmdio_reg(hw, E1000_EEE_ADV_ADDR_I354, E1000_EEE_ADV_DEV_I354, &phy_data); if (ret_val) goto out; phy_data &= ~(E1000_EEE_ADV_100_SUPPORTED | E1000_EEE_ADV_1000_SUPPORTED); ret_val = igb_write_xmdio_reg(hw, E1000_EEE_ADV_ADDR_I354, E1000_EEE_ADV_DEV_I354, phy_data); } out: return ret_val; } /** * igb_get_eee_status_i354 - Get EEE status * @hw: pointer to the HW structure * @status: EEE status * * Get EEE status by guessing based on whether Tx or Rx LPI indications have * been received. **/ s32 igb_get_eee_status_i354(struct e1000_hw *hw, bool *status) { struct e1000_phy_info *phy = &hw->phy; s32 ret_val = 0; u16 phy_data; /* Check if EEE is supported on this device. */ if ((hw->phy.media_type != e1000_media_type_copper) || ((phy->id != M88E1543_E_PHY_ID) && (phy->id != M88E1512_E_PHY_ID))) goto out; ret_val = igb_read_xmdio_reg(hw, E1000_PCS_STATUS_ADDR_I354, E1000_PCS_STATUS_DEV_I354, &phy_data); if (ret_val) goto out; *status = phy_data & (E1000_PCS_STATUS_TX_LPI_RCVD | E1000_PCS_STATUS_RX_LPI_RCVD) ? true : false; out: return ret_val; } #ifdef CONFIG_IGB_HWMON static const u8 e1000_emc_temp_data[4] = { E1000_EMC_INTERNAL_DATA, E1000_EMC_DIODE1_DATA, E1000_EMC_DIODE2_DATA, E1000_EMC_DIODE3_DATA }; static const u8 e1000_emc_therm_limit[4] = { E1000_EMC_INTERNAL_THERM_LIMIT, E1000_EMC_DIODE1_THERM_LIMIT, E1000_EMC_DIODE2_THERM_LIMIT, E1000_EMC_DIODE3_THERM_LIMIT }; /** * igb_get_thermal_sensor_data_generic - Gathers thermal sensor data * @hw: pointer to hardware structure * * Updates the temperatures in mac.thermal_sensor_data **/ static s32 igb_get_thermal_sensor_data_generic(struct e1000_hw *hw) { u16 ets_offset; u16 ets_cfg; u16 ets_sensor; u8 num_sensors; u8 sensor_index; u8 sensor_location; u8 i; struct e1000_thermal_sensor_data *data = &hw->mac.thermal_sensor_data; if ((hw->mac.type != e1000_i350) || (hw->bus.func != 0)) return E1000_NOT_IMPLEMENTED; data->sensor[0].temp = (rd32(E1000_THMJT) & 0xFF); /* Return the internal sensor only if ETS is unsupported */ hw->nvm.ops.read(hw, NVM_ETS_CFG, 1, &ets_offset); if ((ets_offset == 0x0000) || (ets_offset == 0xFFFF)) return 0; hw->nvm.ops.read(hw, ets_offset, 1, &ets_cfg); if (((ets_cfg & NVM_ETS_TYPE_MASK) >> NVM_ETS_TYPE_SHIFT) != NVM_ETS_TYPE_EMC) return E1000_NOT_IMPLEMENTED; num_sensors = (ets_cfg & NVM_ETS_NUM_SENSORS_MASK); if (num_sensors > E1000_MAX_SENSORS) num_sensors = E1000_MAX_SENSORS; for (i = 1; i < num_sensors; i++) { hw->nvm.ops.read(hw, (ets_offset + i), 1, &ets_sensor); sensor_index = ((ets_sensor & NVM_ETS_DATA_INDEX_MASK) >> NVM_ETS_DATA_INDEX_SHIFT); sensor_location = ((ets_sensor & NVM_ETS_DATA_LOC_MASK) >> NVM_ETS_DATA_LOC_SHIFT); if (sensor_location != 0) hw->phy.ops.read_i2c_byte(hw, e1000_emc_temp_data[sensor_index], E1000_I2C_THERMAL_SENSOR_ADDR, &data->sensor[i].temp); } return 0; } /** * igb_init_thermal_sensor_thresh_generic - Sets thermal sensor thresholds * @hw: pointer to hardware structure * * Sets the thermal sensor thresholds according to the NVM map * and save off the threshold and location values into mac.thermal_sensor_data **/ static s32 igb_init_thermal_sensor_thresh_generic(struct e1000_hw *hw) { u16 ets_offset; u16 ets_cfg; u16 ets_sensor; u8 low_thresh_delta; u8 num_sensors; u8 sensor_index; u8 sensor_location; u8 therm_limit; u8 i; struct e1000_thermal_sensor_data *data = &hw->mac.thermal_sensor_data; if ((hw->mac.type != e1000_i350) || (hw->bus.func != 0)) return E1000_NOT_IMPLEMENTED; memset(data, 0, sizeof(struct e1000_thermal_sensor_data)); data->sensor[0].location = 0x1; data->sensor[0].caution_thresh = (rd32(E1000_THHIGHTC) & 0xFF); data->sensor[0].max_op_thresh = (rd32(E1000_THLOWTC) & 0xFF); /* Return the internal sensor only if ETS is unsupported */ hw->nvm.ops.read(hw, NVM_ETS_CFG, 1, &ets_offset); if ((ets_offset == 0x0000) || (ets_offset == 0xFFFF)) return 0; hw->nvm.ops.read(hw, ets_offset, 1, &ets_cfg); if (((ets_cfg & NVM_ETS_TYPE_MASK) >> NVM_ETS_TYPE_SHIFT) != NVM_ETS_TYPE_EMC) return E1000_NOT_IMPLEMENTED; low_thresh_delta = ((ets_cfg & NVM_ETS_LTHRES_DELTA_MASK) >> NVM_ETS_LTHRES_DELTA_SHIFT); num_sensors = (ets_cfg & NVM_ETS_NUM_SENSORS_MASK); for (i = 1; i <= num_sensors; i++) { hw->nvm.ops.read(hw, (ets_offset + i), 1, &ets_sensor); sensor_index = ((ets_sensor & NVM_ETS_DATA_INDEX_MASK) >> NVM_ETS_DATA_INDEX_SHIFT); sensor_location = ((ets_sensor & NVM_ETS_DATA_LOC_MASK) >> NVM_ETS_DATA_LOC_SHIFT); therm_limit = ets_sensor & NVM_ETS_DATA_HTHRESH_MASK; hw->phy.ops.write_i2c_byte(hw, e1000_emc_therm_limit[sensor_index], E1000_I2C_THERMAL_SENSOR_ADDR, therm_limit); if ((i < E1000_MAX_SENSORS) && (sensor_location != 0)) { data->sensor[i].location = sensor_location; data->sensor[i].caution_thresh = therm_limit; data->sensor[i].max_op_thresh = therm_limit - low_thresh_delta; } } return 0; } #endif static struct e1000_mac_operations e1000_mac_ops_82575 = { .init_hw = igb_init_hw_82575, .check_for_link = igb_check_for_link_82575, .rar_set = igb_rar_set, .read_mac_addr = igb_read_mac_addr_82575, .get_speed_and_duplex = igb_get_link_up_info_82575, #ifdef CONFIG_IGB_HWMON .get_thermal_sensor_data = igb_get_thermal_sensor_data_generic, .init_thermal_sensor_thresh = igb_init_thermal_sensor_thresh_generic, #endif }; static const struct e1000_phy_operations e1000_phy_ops_82575 = { .acquire = igb_acquire_phy_82575, .get_cfg_done = igb_get_cfg_done_82575, .release = igb_release_phy_82575, .write_i2c_byte = igb_write_i2c_byte, .read_i2c_byte = igb_read_i2c_byte, }; static struct e1000_nvm_operations e1000_nvm_ops_82575 = { .acquire = igb_acquire_nvm_82575, .read = igb_read_nvm_eerd, .release = igb_release_nvm_82575, .write = igb_write_nvm_spi, }; const struct e1000_info e1000_82575_info = { .get_invariants = igb_get_invariants_82575, .mac_ops = &e1000_mac_ops_82575, .phy_ops = &e1000_phy_ops_82575, .nvm_ops = &e1000_nvm_ops_82575, };
linux-master
drivers/net/ethernet/intel/igb/e1000_82575.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2007 - 2018 Intel Corporation. */ /* e1000_i210 * e1000_i211 */ #include <linux/types.h> #include <linux/if_ether.h> #include "e1000_hw.h" #include "e1000_i210.h" static s32 igb_update_flash_i210(struct e1000_hw *hw); /** * igb_get_hw_semaphore_i210 - Acquire hardware semaphore * @hw: pointer to the HW structure * * Acquire the HW semaphore to access the PHY or NVM */ static s32 igb_get_hw_semaphore_i210(struct e1000_hw *hw) { u32 swsm; s32 timeout = hw->nvm.word_size + 1; s32 i = 0; /* Get the SW semaphore */ while (i < timeout) { swsm = rd32(E1000_SWSM); if (!(swsm & E1000_SWSM_SMBI)) break; udelay(50); i++; } if (i == timeout) { /* In rare circumstances, the SW semaphore may already be held * unintentionally. Clear the semaphore once before giving up. */ if (hw->dev_spec._82575.clear_semaphore_once) { hw->dev_spec._82575.clear_semaphore_once = false; igb_put_hw_semaphore(hw); for (i = 0; i < timeout; i++) { swsm = rd32(E1000_SWSM); if (!(swsm & E1000_SWSM_SMBI)) break; udelay(50); } } /* If we do not have the semaphore here, we have to give up. */ if (i == timeout) { hw_dbg("Driver can't access device - SMBI bit is set.\n"); return -E1000_ERR_NVM; } } /* Get the FW semaphore. */ for (i = 0; i < timeout; i++) { swsm = rd32(E1000_SWSM); wr32(E1000_SWSM, swsm | E1000_SWSM_SWESMBI); /* Semaphore acquired if bit latched */ if (rd32(E1000_SWSM) & E1000_SWSM_SWESMBI) break; udelay(50); } if (i == timeout) { /* Release semaphores */ igb_put_hw_semaphore(hw); hw_dbg("Driver can't access the NVM\n"); return -E1000_ERR_NVM; } return 0; } /** * igb_acquire_nvm_i210 - Request for access to EEPROM * @hw: pointer to the HW structure * * Acquire the necessary semaphores for exclusive access to the EEPROM. * Set the EEPROM access request bit and wait for EEPROM access grant bit. * Return successful if access grant bit set, else clear the request for * EEPROM access and return -E1000_ERR_NVM (-1). **/ static s32 igb_acquire_nvm_i210(struct e1000_hw *hw) { return igb_acquire_swfw_sync_i210(hw, E1000_SWFW_EEP_SM); } /** * igb_release_nvm_i210 - Release exclusive access to EEPROM * @hw: pointer to the HW structure * * Stop any current commands to the EEPROM and clear the EEPROM request bit, * then release the semaphores acquired. **/ static void igb_release_nvm_i210(struct e1000_hw *hw) { igb_release_swfw_sync_i210(hw, E1000_SWFW_EEP_SM); } /** * igb_acquire_swfw_sync_i210 - Acquire SW/FW semaphore * @hw: pointer to the HW structure * @mask: specifies which semaphore to acquire * * Acquire the SW/FW semaphore to access the PHY or NVM. The mask * will also specify which port we're acquiring the lock for. **/ s32 igb_acquire_swfw_sync_i210(struct e1000_hw *hw, u16 mask) { u32 swfw_sync; u32 swmask = mask; u32 fwmask = mask << 16; s32 ret_val = 0; s32 i = 0, timeout = 200; /* FIXME: find real value to use here */ while (i < timeout) { if (igb_get_hw_semaphore_i210(hw)) { ret_val = -E1000_ERR_SWFW_SYNC; goto out; } swfw_sync = rd32(E1000_SW_FW_SYNC); if (!(swfw_sync & (fwmask | swmask))) break; /* Firmware currently using resource (fwmask) */ igb_put_hw_semaphore(hw); mdelay(5); i++; } if (i == timeout) { hw_dbg("Driver can't access resource, SW_FW_SYNC timeout.\n"); ret_val = -E1000_ERR_SWFW_SYNC; goto out; } swfw_sync |= swmask; wr32(E1000_SW_FW_SYNC, swfw_sync); igb_put_hw_semaphore(hw); out: return ret_val; } /** * igb_release_swfw_sync_i210 - Release SW/FW semaphore * @hw: pointer to the HW structure * @mask: specifies which semaphore to acquire * * Release the SW/FW semaphore used to access the PHY or NVM. The mask * will also specify which port we're releasing the lock for. **/ void igb_release_swfw_sync_i210(struct e1000_hw *hw, u16 mask) { u32 swfw_sync; while (igb_get_hw_semaphore_i210(hw)) ; /* Empty */ swfw_sync = rd32(E1000_SW_FW_SYNC); swfw_sync &= ~mask; wr32(E1000_SW_FW_SYNC, swfw_sync); igb_put_hw_semaphore(hw); } /** * igb_read_nvm_srrd_i210 - Reads Shadow Ram using EERD register * @hw: pointer to the HW structure * @offset: offset of word in the Shadow Ram to read * @words: number of words to read * @data: word read from the Shadow Ram * * Reads a 16 bit word from the Shadow Ram using the EERD register. * Uses necessary synchronization semaphores. **/ static s32 igb_read_nvm_srrd_i210(struct e1000_hw *hw, u16 offset, u16 words, u16 *data) { s32 status = 0; u16 i, count; /* We cannot hold synchronization semaphores for too long, * because of forceful takeover procedure. However it is more efficient * to read in bursts than synchronizing access for each word. */ for (i = 0; i < words; i += E1000_EERD_EEWR_MAX_COUNT) { count = (words - i) / E1000_EERD_EEWR_MAX_COUNT > 0 ? E1000_EERD_EEWR_MAX_COUNT : (words - i); if (!(hw->nvm.ops.acquire(hw))) { status = igb_read_nvm_eerd(hw, offset, count, data + i); hw->nvm.ops.release(hw); } else { status = E1000_ERR_SWFW_SYNC; } if (status) break; } return status; } /** * igb_write_nvm_srwr - Write to Shadow Ram using EEWR * @hw: pointer to the HW structure * @offset: offset within the Shadow Ram to be written to * @words: number of words to write * @data: 16 bit word(s) to be written to the Shadow Ram * * Writes data to Shadow Ram at offset using EEWR register. * * If igb_update_nvm_checksum is not called after this function , the * Shadow Ram will most likely contain an invalid checksum. **/ static s32 igb_write_nvm_srwr(struct e1000_hw *hw, u16 offset, u16 words, u16 *data) { struct e1000_nvm_info *nvm = &hw->nvm; u32 i, k, eewr = 0; u32 attempts = 100000; s32 ret_val = 0; /* A check for invalid values: offset too large, too many words, * too many words for the offset, and not enough words. */ if ((offset >= nvm->word_size) || (words > (nvm->word_size - offset)) || (words == 0)) { hw_dbg("nvm parameter(s) out of bounds\n"); ret_val = -E1000_ERR_NVM; goto out; } for (i = 0; i < words; i++) { eewr = ((offset+i) << E1000_NVM_RW_ADDR_SHIFT) | (data[i] << E1000_NVM_RW_REG_DATA) | E1000_NVM_RW_REG_START; wr32(E1000_SRWR, eewr); for (k = 0; k < attempts; k++) { if (E1000_NVM_RW_REG_DONE & rd32(E1000_SRWR)) { ret_val = 0; break; } udelay(5); } if (ret_val) { hw_dbg("Shadow RAM write EEWR timed out\n"); break; } } out: return ret_val; } /** * igb_write_nvm_srwr_i210 - Write to Shadow RAM using EEWR * @hw: pointer to the HW structure * @offset: offset within the Shadow RAM to be written to * @words: number of words to write * @data: 16 bit word(s) to be written to the Shadow RAM * * Writes data to Shadow RAM at offset using EEWR register. * * If e1000_update_nvm_checksum is not called after this function , the * data will not be committed to FLASH and also Shadow RAM will most likely * contain an invalid checksum. * * If error code is returned, data and Shadow RAM may be inconsistent - buffer * partially written. **/ static s32 igb_write_nvm_srwr_i210(struct e1000_hw *hw, u16 offset, u16 words, u16 *data) { s32 status = 0; u16 i, count; /* We cannot hold synchronization semaphores for too long, * because of forceful takeover procedure. However it is more efficient * to write in bursts than synchronizing access for each word. */ for (i = 0; i < words; i += E1000_EERD_EEWR_MAX_COUNT) { count = (words - i) / E1000_EERD_EEWR_MAX_COUNT > 0 ? E1000_EERD_EEWR_MAX_COUNT : (words - i); if (!(hw->nvm.ops.acquire(hw))) { status = igb_write_nvm_srwr(hw, offset, count, data + i); hw->nvm.ops.release(hw); } else { status = E1000_ERR_SWFW_SYNC; } if (status) break; } return status; } /** * igb_read_invm_word_i210 - Reads OTP * @hw: pointer to the HW structure * @address: the word address (aka eeprom offset) to read * @data: pointer to the data read * * Reads 16-bit words from the OTP. Return error when the word is not * stored in OTP. **/ static s32 igb_read_invm_word_i210(struct e1000_hw *hw, u8 address, u16 *data) { s32 status = -E1000_ERR_INVM_VALUE_NOT_FOUND; u32 invm_dword; u16 i; u8 record_type, word_address; for (i = 0; i < E1000_INVM_SIZE; i++) { invm_dword = rd32(E1000_INVM_DATA_REG(i)); /* Get record type */ record_type = INVM_DWORD_TO_RECORD_TYPE(invm_dword); if (record_type == E1000_INVM_UNINITIALIZED_STRUCTURE) break; if (record_type == E1000_INVM_CSR_AUTOLOAD_STRUCTURE) i += E1000_INVM_CSR_AUTOLOAD_DATA_SIZE_IN_DWORDS; if (record_type == E1000_INVM_RSA_KEY_SHA256_STRUCTURE) i += E1000_INVM_RSA_KEY_SHA256_DATA_SIZE_IN_DWORDS; if (record_type == E1000_INVM_WORD_AUTOLOAD_STRUCTURE) { word_address = INVM_DWORD_TO_WORD_ADDRESS(invm_dword); if (word_address == address) { *data = INVM_DWORD_TO_WORD_DATA(invm_dword); hw_dbg("Read INVM Word 0x%02x = %x\n", address, *data); status = 0; break; } } } if (status) hw_dbg("Requested word 0x%02x not found in OTP\n", address); return status; } /** * igb_read_invm_i210 - Read invm wrapper function for I210/I211 * @hw: pointer to the HW structure * @offset: offset to read from * @words: number of words to read (unused) * @data: pointer to the data read * * Wrapper function to return data formerly found in the NVM. **/ static s32 igb_read_invm_i210(struct e1000_hw *hw, u16 offset, u16 __always_unused words, u16 *data) { s32 ret_val = 0; /* Only the MAC addr is required to be present in the iNVM */ switch (offset) { case NVM_MAC_ADDR: ret_val = igb_read_invm_word_i210(hw, (u8)offset, &data[0]); ret_val |= igb_read_invm_word_i210(hw, (u8)offset+1, &data[1]); ret_val |= igb_read_invm_word_i210(hw, (u8)offset+2, &data[2]); if (ret_val) hw_dbg("MAC Addr not found in iNVM\n"); break; case NVM_INIT_CTRL_2: ret_val = igb_read_invm_word_i210(hw, (u8)offset, data); if (ret_val) { *data = NVM_INIT_CTRL_2_DEFAULT_I211; ret_val = 0; } break; case NVM_INIT_CTRL_4: ret_val = igb_read_invm_word_i210(hw, (u8)offset, data); if (ret_val) { *data = NVM_INIT_CTRL_4_DEFAULT_I211; ret_val = 0; } break; case NVM_LED_1_CFG: ret_val = igb_read_invm_word_i210(hw, (u8)offset, data); if (ret_val) { *data = NVM_LED_1_CFG_DEFAULT_I211; ret_val = 0; } break; case NVM_LED_0_2_CFG: ret_val = igb_read_invm_word_i210(hw, (u8)offset, data); if (ret_val) { *data = NVM_LED_0_2_CFG_DEFAULT_I211; ret_val = 0; } break; case NVM_ID_LED_SETTINGS: ret_val = igb_read_invm_word_i210(hw, (u8)offset, data); if (ret_val) { *data = ID_LED_RESERVED_FFFF; ret_val = 0; } break; case NVM_SUB_DEV_ID: *data = hw->subsystem_device_id; break; case NVM_SUB_VEN_ID: *data = hw->subsystem_vendor_id; break; case NVM_DEV_ID: *data = hw->device_id; break; case NVM_VEN_ID: *data = hw->vendor_id; break; default: hw_dbg("NVM word 0x%02x is not mapped.\n", offset); *data = NVM_RESERVED_WORD; break; } return ret_val; } /** * igb_read_invm_version - Reads iNVM version and image type * @hw: pointer to the HW structure * @invm_ver: version structure for the version read * * Reads iNVM version and image type. **/ s32 igb_read_invm_version(struct e1000_hw *hw, struct e1000_fw_version *invm_ver) { u32 *record = NULL; u32 *next_record = NULL; u32 i = 0; u32 invm_dword = 0; u32 invm_blocks = E1000_INVM_SIZE - (E1000_INVM_ULT_BYTES_SIZE / E1000_INVM_RECORD_SIZE_IN_BYTES); u32 buffer[E1000_INVM_SIZE]; s32 status = -E1000_ERR_INVM_VALUE_NOT_FOUND; u16 version = 0; /* Read iNVM memory */ for (i = 0; i < E1000_INVM_SIZE; i++) { invm_dword = rd32(E1000_INVM_DATA_REG(i)); buffer[i] = invm_dword; } /* Read version number */ for (i = 1; i < invm_blocks; i++) { record = &buffer[invm_blocks - i]; next_record = &buffer[invm_blocks - i + 1]; /* Check if we have first version location used */ if ((i == 1) && ((*record & E1000_INVM_VER_FIELD_ONE) == 0)) { version = 0; status = 0; break; } /* Check if we have second version location used */ else if ((i == 1) && ((*record & E1000_INVM_VER_FIELD_TWO) == 0)) { version = (*record & E1000_INVM_VER_FIELD_ONE) >> 3; status = 0; break; } /* Check if we have odd version location * used and it is the last one used */ else if ((((*record & E1000_INVM_VER_FIELD_ONE) == 0) && ((*record & 0x3) == 0)) || (((*record & 0x3) != 0) && (i != 1))) { version = (*next_record & E1000_INVM_VER_FIELD_TWO) >> 13; status = 0; break; } /* Check if we have even version location * used and it is the last one used */ else if (((*record & E1000_INVM_VER_FIELD_TWO) == 0) && ((*record & 0x3) == 0)) { version = (*record & E1000_INVM_VER_FIELD_ONE) >> 3; status = 0; break; } } if (!status) { invm_ver->invm_major = (version & E1000_INVM_MAJOR_MASK) >> E1000_INVM_MAJOR_SHIFT; invm_ver->invm_minor = version & E1000_INVM_MINOR_MASK; } /* Read Image Type */ for (i = 1; i < invm_blocks; i++) { record = &buffer[invm_blocks - i]; next_record = &buffer[invm_blocks - i + 1]; /* Check if we have image type in first location used */ if ((i == 1) && ((*record & E1000_INVM_IMGTYPE_FIELD) == 0)) { invm_ver->invm_img_type = 0; status = 0; break; } /* Check if we have image type in first location used */ else if ((((*record & 0x3) == 0) && ((*record & E1000_INVM_IMGTYPE_FIELD) == 0)) || ((((*record & 0x3) != 0) && (i != 1)))) { invm_ver->invm_img_type = (*next_record & E1000_INVM_IMGTYPE_FIELD) >> 23; status = 0; break; } } return status; } /** * igb_validate_nvm_checksum_i210 - Validate EEPROM checksum * @hw: pointer to the HW structure * * Calculates the EEPROM checksum by reading/adding each word of the EEPROM * and then verifies that the sum of the EEPROM is equal to 0xBABA. **/ static s32 igb_validate_nvm_checksum_i210(struct e1000_hw *hw) { s32 status = 0; s32 (*read_op_ptr)(struct e1000_hw *, u16, u16, u16 *); if (!(hw->nvm.ops.acquire(hw))) { /* Replace the read function with semaphore grabbing with * the one that skips this for a while. * We have semaphore taken already here. */ read_op_ptr = hw->nvm.ops.read; hw->nvm.ops.read = igb_read_nvm_eerd; status = igb_validate_nvm_checksum(hw); /* Revert original read operation. */ hw->nvm.ops.read = read_op_ptr; hw->nvm.ops.release(hw); } else { status = E1000_ERR_SWFW_SYNC; } return status; } /** * igb_update_nvm_checksum_i210 - Update EEPROM checksum * @hw: pointer to the HW structure * * Updates the EEPROM checksum by reading/adding each word of the EEPROM * up to the checksum. Then calculates the EEPROM checksum and writes the * value to the EEPROM. Next commit EEPROM data onto the Flash. **/ static s32 igb_update_nvm_checksum_i210(struct e1000_hw *hw) { s32 ret_val = 0; u16 checksum = 0; u16 i, nvm_data; /* Read the first word from the EEPROM. If this times out or fails, do * not continue or we could be in for a very long wait while every * EEPROM read fails */ ret_val = igb_read_nvm_eerd(hw, 0, 1, &nvm_data); if (ret_val) { hw_dbg("EEPROM read failed\n"); goto out; } if (!(hw->nvm.ops.acquire(hw))) { /* Do not use hw->nvm.ops.write, hw->nvm.ops.read * because we do not want to take the synchronization * semaphores twice here. */ for (i = 0; i < NVM_CHECKSUM_REG; i++) { ret_val = igb_read_nvm_eerd(hw, i, 1, &nvm_data); if (ret_val) { hw->nvm.ops.release(hw); hw_dbg("NVM Read Error while updating checksum.\n"); goto out; } checksum += nvm_data; } checksum = (u16) NVM_SUM - checksum; ret_val = igb_write_nvm_srwr(hw, NVM_CHECKSUM_REG, 1, &checksum); if (ret_val) { hw->nvm.ops.release(hw); hw_dbg("NVM Write Error while updating checksum.\n"); goto out; } hw->nvm.ops.release(hw); ret_val = igb_update_flash_i210(hw); } else { ret_val = -E1000_ERR_SWFW_SYNC; } out: return ret_val; } /** * igb_pool_flash_update_done_i210 - Pool FLUDONE status. * @hw: pointer to the HW structure * **/ static s32 igb_pool_flash_update_done_i210(struct e1000_hw *hw) { s32 ret_val = -E1000_ERR_NVM; u32 i, reg; for (i = 0; i < E1000_FLUDONE_ATTEMPTS; i++) { reg = rd32(E1000_EECD); if (reg & E1000_EECD_FLUDONE_I210) { ret_val = 0; break; } udelay(5); } return ret_val; } /** * igb_get_flash_presence_i210 - Check if flash device is detected. * @hw: pointer to the HW structure * **/ bool igb_get_flash_presence_i210(struct e1000_hw *hw) { u32 eec = 0; bool ret_val = false; eec = rd32(E1000_EECD); if (eec & E1000_EECD_FLASH_DETECTED_I210) ret_val = true; return ret_val; } /** * igb_update_flash_i210 - Commit EEPROM to the flash * @hw: pointer to the HW structure * **/ static s32 igb_update_flash_i210(struct e1000_hw *hw) { s32 ret_val = 0; u32 flup; ret_val = igb_pool_flash_update_done_i210(hw); if (ret_val == -E1000_ERR_NVM) { hw_dbg("Flash update time out\n"); goto out; } flup = rd32(E1000_EECD) | E1000_EECD_FLUPD_I210; wr32(E1000_EECD, flup); ret_val = igb_pool_flash_update_done_i210(hw); if (ret_val) hw_dbg("Flash update time out\n"); else hw_dbg("Flash update complete\n"); out: return ret_val; } /** * igb_valid_led_default_i210 - Verify a valid default LED config * @hw: pointer to the HW structure * @data: pointer to the NVM (EEPROM) * * Read the EEPROM for the current default LED configuration. If the * LED configuration is not valid, set to a valid LED configuration. **/ s32 igb_valid_led_default_i210(struct e1000_hw *hw, u16 *data) { s32 ret_val; ret_val = hw->nvm.ops.read(hw, NVM_ID_LED_SETTINGS, 1, data); if (ret_val) { hw_dbg("NVM Read Error\n"); goto out; } if (*data == ID_LED_RESERVED_0000 || *data == ID_LED_RESERVED_FFFF) { switch (hw->phy.media_type) { case e1000_media_type_internal_serdes: *data = ID_LED_DEFAULT_I210_SERDES; break; case e1000_media_type_copper: default: *data = ID_LED_DEFAULT_I210; break; } } out: return ret_val; } /** * __igb_access_xmdio_reg - Read/write XMDIO register * @hw: pointer to the HW structure * @address: XMDIO address to program * @dev_addr: device address to program * @data: pointer to value to read/write from/to the XMDIO address * @read: boolean flag to indicate read or write **/ static s32 __igb_access_xmdio_reg(struct e1000_hw *hw, u16 address, u8 dev_addr, u16 *data, bool read) { s32 ret_val = 0; ret_val = hw->phy.ops.write_reg(hw, E1000_MMDAC, dev_addr); if (ret_val) return ret_val; ret_val = hw->phy.ops.write_reg(hw, E1000_MMDAAD, address); if (ret_val) return ret_val; ret_val = hw->phy.ops.write_reg(hw, E1000_MMDAC, E1000_MMDAC_FUNC_DATA | dev_addr); if (ret_val) return ret_val; if (read) ret_val = hw->phy.ops.read_reg(hw, E1000_MMDAAD, data); else ret_val = hw->phy.ops.write_reg(hw, E1000_MMDAAD, *data); if (ret_val) return ret_val; /* Recalibrate the device back to 0 */ ret_val = hw->phy.ops.write_reg(hw, E1000_MMDAC, 0); if (ret_val) return ret_val; return ret_val; } /** * igb_read_xmdio_reg - Read XMDIO register * @hw: pointer to the HW structure * @addr: XMDIO address to program * @dev_addr: device address to program * @data: value to be read from the EMI address **/ s32 igb_read_xmdio_reg(struct e1000_hw *hw, u16 addr, u8 dev_addr, u16 *data) { return __igb_access_xmdio_reg(hw, addr, dev_addr, data, true); } /** * igb_write_xmdio_reg - Write XMDIO register * @hw: pointer to the HW structure * @addr: XMDIO address to program * @dev_addr: device address to program * @data: value to be written to the XMDIO address **/ s32 igb_write_xmdio_reg(struct e1000_hw *hw, u16 addr, u8 dev_addr, u16 data) { return __igb_access_xmdio_reg(hw, addr, dev_addr, &data, false); } /** * igb_init_nvm_params_i210 - Init NVM func ptrs. * @hw: pointer to the HW structure **/ s32 igb_init_nvm_params_i210(struct e1000_hw *hw) { struct e1000_nvm_info *nvm = &hw->nvm; nvm->ops.acquire = igb_acquire_nvm_i210; nvm->ops.release = igb_release_nvm_i210; nvm->ops.valid_led_default = igb_valid_led_default_i210; /* NVM Function Pointers */ if (igb_get_flash_presence_i210(hw)) { hw->nvm.type = e1000_nvm_flash_hw; nvm->ops.read = igb_read_nvm_srrd_i210; nvm->ops.write = igb_write_nvm_srwr_i210; nvm->ops.validate = igb_validate_nvm_checksum_i210; nvm->ops.update = igb_update_nvm_checksum_i210; } else { hw->nvm.type = e1000_nvm_invm; nvm->ops.read = igb_read_invm_i210; nvm->ops.write = NULL; nvm->ops.validate = NULL; nvm->ops.update = NULL; } return 0; } /** * igb_pll_workaround_i210 * @hw: pointer to the HW structure * * Works around an errata in the PLL circuit where it occasionally * provides the wrong clock frequency after power up. **/ s32 igb_pll_workaround_i210(struct e1000_hw *hw) { s32 ret_val; u32 wuc, mdicnfg, ctrl, ctrl_ext, reg_val; u16 nvm_word, phy_word, pci_word, tmp_nvm; int i; /* Get and set needed register values */ wuc = rd32(E1000_WUC); mdicnfg = rd32(E1000_MDICNFG); reg_val = mdicnfg & ~E1000_MDICNFG_EXT_MDIO; wr32(E1000_MDICNFG, reg_val); /* Get data from NVM, or set default */ ret_val = igb_read_invm_word_i210(hw, E1000_INVM_AUTOLOAD, &nvm_word); if (ret_val) nvm_word = E1000_INVM_DEFAULT_AL; tmp_nvm = nvm_word | E1000_INVM_PLL_WO_VAL; igb_write_phy_reg_82580(hw, I347AT4_PAGE_SELECT, E1000_PHY_PLL_FREQ_PAGE); phy_word = E1000_PHY_PLL_UNCONF; for (i = 0; i < E1000_MAX_PLL_TRIES; i++) { /* check current state directly from internal PHY */ igb_read_phy_reg_82580(hw, E1000_PHY_PLL_FREQ_REG, &phy_word); if ((phy_word & E1000_PHY_PLL_UNCONF) != E1000_PHY_PLL_UNCONF) { ret_val = 0; break; } else { ret_val = -E1000_ERR_PHY; } /* directly reset the internal PHY */ ctrl = rd32(E1000_CTRL); wr32(E1000_CTRL, ctrl|E1000_CTRL_PHY_RST); ctrl_ext = rd32(E1000_CTRL_EXT); ctrl_ext |= (E1000_CTRL_EXT_PHYPDEN | E1000_CTRL_EXT_SDLPE); wr32(E1000_CTRL_EXT, ctrl_ext); wr32(E1000_WUC, 0); reg_val = (E1000_INVM_AUTOLOAD << 4) | (tmp_nvm << 16); wr32(E1000_EEARBC_I210, reg_val); igb_read_pci_cfg(hw, E1000_PCI_PMCSR, &pci_word); pci_word |= E1000_PCI_PMCSR_D3; igb_write_pci_cfg(hw, E1000_PCI_PMCSR, &pci_word); usleep_range(1000, 2000); pci_word &= ~E1000_PCI_PMCSR_D3; igb_write_pci_cfg(hw, E1000_PCI_PMCSR, &pci_word); reg_val = (E1000_INVM_AUTOLOAD << 4) | (nvm_word << 16); wr32(E1000_EEARBC_I210, reg_val); /* restore WUC register */ wr32(E1000_WUC, wuc); } igb_write_phy_reg_82580(hw, I347AT4_PAGE_SELECT, 0); /* restore MDICNFG setting */ wr32(E1000_MDICNFG, mdicnfg); return ret_val; } /** * igb_get_cfg_done_i210 - Read config done bit * @hw: pointer to the HW structure * * Read the management control register for the config done bit for * completion status. NOTE: silicon which is EEPROM-less will fail trying * to read the config done bit, so an error is *ONLY* logged and returns * 0. If we were to return with error, EEPROM-less silicon * would not be able to be reset or change link. **/ s32 igb_get_cfg_done_i210(struct e1000_hw *hw) { s32 timeout = PHY_CFG_TIMEOUT; u32 mask = E1000_NVM_CFG_DONE_PORT_0; while (timeout) { if (rd32(E1000_EEMNGCTL_I210) & mask) break; usleep_range(1000, 2000); timeout--; } if (!timeout) hw_dbg("MNG configuration cycle has not completed.\n"); return 0; }
linux-master
drivers/net/ethernet/intel/igb/e1000_i210.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2007 - 2018 Intel Corporation. */ #include "e1000_mbx.h" /** * igb_read_mbx - Reads a message from the mailbox * @hw: pointer to the HW structure * @msg: The message buffer * @size: Length of buffer * @mbx_id: id of mailbox to read * @unlock: skip locking or not * * returns SUCCESS if it successfully read message from buffer **/ s32 igb_read_mbx(struct e1000_hw *hw, u32 *msg, u16 size, u16 mbx_id, bool unlock) { struct e1000_mbx_info *mbx = &hw->mbx; s32 ret_val = -E1000_ERR_MBX; /* limit read to size of mailbox */ if (size > mbx->size) size = mbx->size; if (mbx->ops.read) ret_val = mbx->ops.read(hw, msg, size, mbx_id, unlock); return ret_val; } /** * igb_write_mbx - Write a message to the mailbox * @hw: pointer to the HW structure * @msg: The message buffer * @size: Length of buffer * @mbx_id: id of mailbox to write * * returns SUCCESS if it successfully copied message into the buffer **/ s32 igb_write_mbx(struct e1000_hw *hw, u32 *msg, u16 size, u16 mbx_id) { struct e1000_mbx_info *mbx = &hw->mbx; s32 ret_val = 0; if (size > mbx->size) ret_val = -E1000_ERR_MBX; else if (mbx->ops.write) ret_val = mbx->ops.write(hw, msg, size, mbx_id); return ret_val; } /** * igb_check_for_msg - checks to see if someone sent us mail * @hw: pointer to the HW structure * @mbx_id: id of mailbox to check * * returns SUCCESS if the Status bit was found or else ERR_MBX **/ s32 igb_check_for_msg(struct e1000_hw *hw, u16 mbx_id) { struct e1000_mbx_info *mbx = &hw->mbx; s32 ret_val = -E1000_ERR_MBX; if (mbx->ops.check_for_msg) ret_val = mbx->ops.check_for_msg(hw, mbx_id); return ret_val; } /** * igb_check_for_ack - checks to see if someone sent us ACK * @hw: pointer to the HW structure * @mbx_id: id of mailbox to check * * returns SUCCESS if the Status bit was found or else ERR_MBX **/ s32 igb_check_for_ack(struct e1000_hw *hw, u16 mbx_id) { struct e1000_mbx_info *mbx = &hw->mbx; s32 ret_val = -E1000_ERR_MBX; if (mbx->ops.check_for_ack) ret_val = mbx->ops.check_for_ack(hw, mbx_id); return ret_val; } /** * igb_check_for_rst - checks to see if other side has reset * @hw: pointer to the HW structure * @mbx_id: id of mailbox to check * * returns SUCCESS if the Status bit was found or else ERR_MBX **/ s32 igb_check_for_rst(struct e1000_hw *hw, u16 mbx_id) { struct e1000_mbx_info *mbx = &hw->mbx; s32 ret_val = -E1000_ERR_MBX; if (mbx->ops.check_for_rst) ret_val = mbx->ops.check_for_rst(hw, mbx_id); return ret_val; } /** * igb_unlock_mbx - unlock the mailbox * @hw: pointer to the HW structure * @mbx_id: id of mailbox to check * * returns SUCCESS if the mailbox was unlocked or else ERR_MBX **/ s32 igb_unlock_mbx(struct e1000_hw *hw, u16 mbx_id) { struct e1000_mbx_info *mbx = &hw->mbx; s32 ret_val = -E1000_ERR_MBX; if (mbx->ops.unlock) ret_val = mbx->ops.unlock(hw, mbx_id); return ret_val; } /** * igb_poll_for_msg - Wait for message notification * @hw: pointer to the HW structure * @mbx_id: id of mailbox to write * * returns SUCCESS if it successfully received a message notification **/ static s32 igb_poll_for_msg(struct e1000_hw *hw, u16 mbx_id) { struct e1000_mbx_info *mbx = &hw->mbx; int countdown = mbx->timeout; if (!countdown || !mbx->ops.check_for_msg) goto out; while (countdown && mbx->ops.check_for_msg(hw, mbx_id)) { countdown--; if (!countdown) break; udelay(mbx->usec_delay); } /* if we failed, all future posted messages fail until reset */ if (!countdown) mbx->timeout = 0; out: return countdown ? 0 : -E1000_ERR_MBX; } /** * igb_poll_for_ack - Wait for message acknowledgement * @hw: pointer to the HW structure * @mbx_id: id of mailbox to write * * returns SUCCESS if it successfully received a message acknowledgement **/ static s32 igb_poll_for_ack(struct e1000_hw *hw, u16 mbx_id) { struct e1000_mbx_info *mbx = &hw->mbx; int countdown = mbx->timeout; if (!countdown || !mbx->ops.check_for_ack) goto out; while (countdown && mbx->ops.check_for_ack(hw, mbx_id)) { countdown--; if (!countdown) break; udelay(mbx->usec_delay); } /* if we failed, all future posted messages fail until reset */ if (!countdown) mbx->timeout = 0; out: return countdown ? 0 : -E1000_ERR_MBX; } /** * igb_read_posted_mbx - Wait for message notification and receive message * @hw: pointer to the HW structure * @msg: The message buffer * @size: Length of buffer * @mbx_id: id of mailbox to write * * returns SUCCESS if it successfully received a message notification and * copied it into the receive buffer. **/ static s32 igb_read_posted_mbx(struct e1000_hw *hw, u32 *msg, u16 size, u16 mbx_id) { struct e1000_mbx_info *mbx = &hw->mbx; s32 ret_val = -E1000_ERR_MBX; if (!mbx->ops.read) goto out; ret_val = igb_poll_for_msg(hw, mbx_id); if (!ret_val) ret_val = mbx->ops.read(hw, msg, size, mbx_id, true); out: return ret_val; } /** * igb_write_posted_mbx - Write a message to the mailbox, wait for ack * @hw: pointer to the HW structure * @msg: The message buffer * @size: Length of buffer * @mbx_id: id of mailbox to write * * returns SUCCESS if it successfully copied message into the buffer and * received an ack to that message within delay * timeout period **/ static s32 igb_write_posted_mbx(struct e1000_hw *hw, u32 *msg, u16 size, u16 mbx_id) { struct e1000_mbx_info *mbx = &hw->mbx; s32 ret_val = -E1000_ERR_MBX; /* exit if either we can't write or there isn't a defined timeout */ if (!mbx->ops.write || !mbx->timeout) goto out; /* send msg */ ret_val = mbx->ops.write(hw, msg, size, mbx_id); /* if msg sent wait until we receive an ack */ if (!ret_val) ret_val = igb_poll_for_ack(hw, mbx_id); out: return ret_val; } static s32 igb_check_for_bit_pf(struct e1000_hw *hw, u32 mask) { u32 mbvficr = rd32(E1000_MBVFICR); s32 ret_val = -E1000_ERR_MBX; if (mbvficr & mask) { ret_val = 0; wr32(E1000_MBVFICR, mask); } return ret_val; } /** * igb_check_for_msg_pf - checks to see if the VF has sent mail * @hw: pointer to the HW structure * @vf_number: the VF index * * returns SUCCESS if the VF has set the Status bit or else ERR_MBX **/ static s32 igb_check_for_msg_pf(struct e1000_hw *hw, u16 vf_number) { s32 ret_val = -E1000_ERR_MBX; if (!igb_check_for_bit_pf(hw, E1000_MBVFICR_VFREQ_VF1 << vf_number)) { ret_val = 0; hw->mbx.stats.reqs++; } return ret_val; } /** * igb_check_for_ack_pf - checks to see if the VF has ACKed * @hw: pointer to the HW structure * @vf_number: the VF index * * returns SUCCESS if the VF has set the Status bit or else ERR_MBX **/ static s32 igb_check_for_ack_pf(struct e1000_hw *hw, u16 vf_number) { s32 ret_val = -E1000_ERR_MBX; if (!igb_check_for_bit_pf(hw, E1000_MBVFICR_VFACK_VF1 << vf_number)) { ret_val = 0; hw->mbx.stats.acks++; } return ret_val; } /** * igb_check_for_rst_pf - checks to see if the VF has reset * @hw: pointer to the HW structure * @vf_number: the VF index * * returns SUCCESS if the VF has set the Status bit or else ERR_MBX **/ static s32 igb_check_for_rst_pf(struct e1000_hw *hw, u16 vf_number) { u32 vflre = rd32(E1000_VFLRE); s32 ret_val = -E1000_ERR_MBX; if (vflre & BIT(vf_number)) { ret_val = 0; wr32(E1000_VFLRE, BIT(vf_number)); hw->mbx.stats.rsts++; } return ret_val; } /** * igb_obtain_mbx_lock_pf - obtain mailbox lock * @hw: pointer to the HW structure * @vf_number: the VF index * * return SUCCESS if we obtained the mailbox lock **/ static s32 igb_obtain_mbx_lock_pf(struct e1000_hw *hw, u16 vf_number) { s32 ret_val = -E1000_ERR_MBX; u32 p2v_mailbox; int count = 10; do { /* Take ownership of the buffer */ wr32(E1000_P2VMAILBOX(vf_number), E1000_P2VMAILBOX_PFU); /* reserve mailbox for vf use */ p2v_mailbox = rd32(E1000_P2VMAILBOX(vf_number)); if (p2v_mailbox & E1000_P2VMAILBOX_PFU) { ret_val = 0; break; } udelay(1000); } while (count-- > 0); return ret_val; } /** * igb_release_mbx_lock_pf - release mailbox lock * @hw: pointer to the HW structure * @vf_number: the VF index * * return SUCCESS if we released the mailbox lock **/ static s32 igb_release_mbx_lock_pf(struct e1000_hw *hw, u16 vf_number) { u32 p2v_mailbox; /* drop PF lock of mailbox, if set */ p2v_mailbox = rd32(E1000_P2VMAILBOX(vf_number)); if (p2v_mailbox & E1000_P2VMAILBOX_PFU) wr32(E1000_P2VMAILBOX(vf_number), p2v_mailbox & ~E1000_P2VMAILBOX_PFU); return 0; } /** * igb_write_mbx_pf - Places a message in the mailbox * @hw: pointer to the HW structure * @msg: The message buffer * @size: Length of buffer * @vf_number: the VF index * * returns SUCCESS if it successfully copied message into the buffer **/ static s32 igb_write_mbx_pf(struct e1000_hw *hw, u32 *msg, u16 size, u16 vf_number) { s32 ret_val; u16 i; /* lock the mailbox to prevent pf/vf race condition */ ret_val = igb_obtain_mbx_lock_pf(hw, vf_number); if (ret_val) goto out_no_write; /* flush msg and acks as we are overwriting the message buffer */ igb_check_for_msg_pf(hw, vf_number); igb_check_for_ack_pf(hw, vf_number); /* copy the caller specified message to the mailbox memory buffer */ for (i = 0; i < size; i++) array_wr32(E1000_VMBMEM(vf_number), i, msg[i]); /* Interrupt VF to tell it a message has been sent and release buffer*/ wr32(E1000_P2VMAILBOX(vf_number), E1000_P2VMAILBOX_STS); /* update stats */ hw->mbx.stats.msgs_tx++; out_no_write: return ret_val; } /** * igb_read_mbx_pf - Read a message from the mailbox * @hw: pointer to the HW structure * @msg: The message buffer * @size: Length of buffer * @vf_number: the VF index * @unlock: unlock the mailbox when done? * * This function copies a message from the mailbox buffer to the caller's * memory buffer. The presumption is that the caller knows that there was * a message due to a VF request so no polling for message is needed. **/ static s32 igb_read_mbx_pf(struct e1000_hw *hw, u32 *msg, u16 size, u16 vf_number, bool unlock) { s32 ret_val; u16 i; /* lock the mailbox to prevent pf/vf race condition */ ret_val = igb_obtain_mbx_lock_pf(hw, vf_number); if (ret_val) goto out_no_read; /* copy the message to the mailbox memory buffer */ for (i = 0; i < size; i++) msg[i] = array_rd32(E1000_VMBMEM(vf_number), i); /* Acknowledge the message and release mailbox lock (or not) */ if (unlock) wr32(E1000_P2VMAILBOX(vf_number), E1000_P2VMAILBOX_ACK); else wr32(E1000_P2VMAILBOX(vf_number), E1000_P2VMAILBOX_ACK | E1000_P2VMAILBOX_PFU); /* update stats */ hw->mbx.stats.msgs_rx++; out_no_read: return ret_val; } /** * igb_init_mbx_params_pf - set initial values for pf mailbox * @hw: pointer to the HW structure * * Initializes the hw->mbx struct to correct values for pf mailbox */ s32 igb_init_mbx_params_pf(struct e1000_hw *hw) { struct e1000_mbx_info *mbx = &hw->mbx; mbx->timeout = 0; mbx->usec_delay = 0; mbx->size = E1000_VFMAILBOX_SIZE; mbx->ops.read = igb_read_mbx_pf; mbx->ops.write = igb_write_mbx_pf; mbx->ops.read_posted = igb_read_posted_mbx; mbx->ops.write_posted = igb_write_posted_mbx; mbx->ops.check_for_msg = igb_check_for_msg_pf; mbx->ops.check_for_ack = igb_check_for_ack_pf; mbx->ops.check_for_rst = igb_check_for_rst_pf; mbx->ops.unlock = igb_release_mbx_lock_pf; mbx->stats.msgs_tx = 0; mbx->stats.msgs_rx = 0; mbx->stats.reqs = 0; mbx->stats.acks = 0; mbx->stats.rsts = 0; return 0; }
linux-master
drivers/net/ethernet/intel/igb/e1000_mbx.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2007 - 2018 Intel Corporation. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/types.h> #include <linux/init.h> #include <linux/bitops.h> #include <linux/vmalloc.h> #include <linux/pagemap.h> #include <linux/netdevice.h> #include <linux/ipv6.h> #include <linux/slab.h> #include <net/checksum.h> #include <net/ip6_checksum.h> #include <net/pkt_sched.h> #include <net/pkt_cls.h> #include <linux/net_tstamp.h> #include <linux/mii.h> #include <linux/ethtool.h> #include <linux/if.h> #include <linux/if_vlan.h> #include <linux/pci.h> #include <linux/delay.h> #include <linux/interrupt.h> #include <linux/ip.h> #include <linux/tcp.h> #include <linux/sctp.h> #include <linux/if_ether.h> #include <linux/prefetch.h> #include <linux/bpf.h> #include <linux/bpf_trace.h> #include <linux/pm_runtime.h> #include <linux/etherdevice.h> #ifdef CONFIG_IGB_DCA #include <linux/dca.h> #endif #include <linux/i2c.h> #include "igb.h" enum queue_mode { QUEUE_MODE_STRICT_PRIORITY, QUEUE_MODE_STREAM_RESERVATION, }; enum tx_queue_prio { TX_QUEUE_PRIO_HIGH, TX_QUEUE_PRIO_LOW, }; char igb_driver_name[] = "igb"; static const char igb_driver_string[] = "Intel(R) Gigabit Ethernet Network Driver"; static const char igb_copyright[] = "Copyright (c) 2007-2014 Intel Corporation."; static const struct e1000_info *igb_info_tbl[] = { [board_82575] = &e1000_82575_info, }; static const struct pci_device_id igb_pci_tbl[] = { { PCI_VDEVICE(INTEL, E1000_DEV_ID_I354_BACKPLANE_1GBPS) }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_I354_SGMII) }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_I354_BACKPLANE_2_5GBPS) }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_I211_COPPER), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_I210_COPPER), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_I210_FIBER), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_I210_SERDES), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_I210_SGMII), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_I210_COPPER_FLASHLESS), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_I210_SERDES_FLASHLESS), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_I350_COPPER), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_I350_FIBER), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_I350_SERDES), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_I350_SGMII), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_82580_COPPER), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_82580_FIBER), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_82580_QUAD_FIBER), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_82580_SERDES), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_82580_SGMII), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_82580_COPPER_DUAL), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_DH89XXCC_SGMII), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_DH89XXCC_SERDES), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_DH89XXCC_BACKPLANE), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_DH89XXCC_SFP), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_82576), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_82576_NS), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_82576_NS_SERDES), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_82576_FIBER), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_82576_SERDES), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_82576_SERDES_QUAD), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_82576_QUAD_COPPER_ET2), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_82576_QUAD_COPPER), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_82575EB_COPPER), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_82575EB_FIBER_SERDES), board_82575 }, { PCI_VDEVICE(INTEL, E1000_DEV_ID_82575GB_QUAD_COPPER), board_82575 }, /* required last entry */ {0, } }; MODULE_DEVICE_TABLE(pci, igb_pci_tbl); static int igb_setup_all_tx_resources(struct igb_adapter *); static int igb_setup_all_rx_resources(struct igb_adapter *); static void igb_free_all_tx_resources(struct igb_adapter *); static void igb_free_all_rx_resources(struct igb_adapter *); static void igb_setup_mrqc(struct igb_adapter *); static int igb_probe(struct pci_dev *, const struct pci_device_id *); static void igb_remove(struct pci_dev *pdev); static void igb_init_queue_configuration(struct igb_adapter *adapter); static int igb_sw_init(struct igb_adapter *); int igb_open(struct net_device *); int igb_close(struct net_device *); static void igb_configure(struct igb_adapter *); static void igb_configure_tx(struct igb_adapter *); static void igb_configure_rx(struct igb_adapter *); static void igb_clean_all_tx_rings(struct igb_adapter *); static void igb_clean_all_rx_rings(struct igb_adapter *); static void igb_clean_tx_ring(struct igb_ring *); static void igb_clean_rx_ring(struct igb_ring *); static void igb_set_rx_mode(struct net_device *); static void igb_update_phy_info(struct timer_list *); static void igb_watchdog(struct timer_list *); static void igb_watchdog_task(struct work_struct *); static netdev_tx_t igb_xmit_frame(struct sk_buff *skb, struct net_device *); static void igb_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats); static int igb_change_mtu(struct net_device *, int); static int igb_set_mac(struct net_device *, void *); static void igb_set_uta(struct igb_adapter *adapter, bool set); static irqreturn_t igb_intr(int irq, void *); static irqreturn_t igb_intr_msi(int irq, void *); static irqreturn_t igb_msix_other(int irq, void *); static irqreturn_t igb_msix_ring(int irq, void *); #ifdef CONFIG_IGB_DCA static void igb_update_dca(struct igb_q_vector *); static void igb_setup_dca(struct igb_adapter *); #endif /* CONFIG_IGB_DCA */ static int igb_poll(struct napi_struct *, int); static bool igb_clean_tx_irq(struct igb_q_vector *, int); static int igb_clean_rx_irq(struct igb_q_vector *, int); static int igb_ioctl(struct net_device *, struct ifreq *, int cmd); static void igb_tx_timeout(struct net_device *, unsigned int txqueue); static void igb_reset_task(struct work_struct *); static void igb_vlan_mode(struct net_device *netdev, netdev_features_t features); static int igb_vlan_rx_add_vid(struct net_device *, __be16, u16); static int igb_vlan_rx_kill_vid(struct net_device *, __be16, u16); static void igb_restore_vlan(struct igb_adapter *); static void igb_rar_set_index(struct igb_adapter *, u32); static void igb_ping_all_vfs(struct igb_adapter *); static void igb_msg_task(struct igb_adapter *); static void igb_vmm_control(struct igb_adapter *); static int igb_set_vf_mac(struct igb_adapter *, int, unsigned char *); static void igb_flush_mac_table(struct igb_adapter *); static int igb_available_rars(struct igb_adapter *, u8); static void igb_set_default_mac_filter(struct igb_adapter *); static int igb_uc_sync(struct net_device *, const unsigned char *); static int igb_uc_unsync(struct net_device *, const unsigned char *); static void igb_restore_vf_multicasts(struct igb_adapter *adapter); static int igb_ndo_set_vf_mac(struct net_device *netdev, int vf, u8 *mac); static int igb_ndo_set_vf_vlan(struct net_device *netdev, int vf, u16 vlan, u8 qos, __be16 vlan_proto); static int igb_ndo_set_vf_bw(struct net_device *, int, int, int); static int igb_ndo_set_vf_spoofchk(struct net_device *netdev, int vf, bool setting); static int igb_ndo_set_vf_trust(struct net_device *netdev, int vf, bool setting); static int igb_ndo_get_vf_config(struct net_device *netdev, int vf, struct ifla_vf_info *ivi); static void igb_check_vf_rate_limit(struct igb_adapter *); static void igb_nfc_filter_exit(struct igb_adapter *adapter); static void igb_nfc_filter_restore(struct igb_adapter *adapter); #ifdef CONFIG_PCI_IOV static int igb_vf_configure(struct igb_adapter *adapter, int vf); static int igb_disable_sriov(struct pci_dev *dev, bool reinit); #endif static int igb_suspend(struct device *); static int igb_resume(struct device *); static int igb_runtime_suspend(struct device *dev); static int igb_runtime_resume(struct device *dev); static int igb_runtime_idle(struct device *dev); #ifdef CONFIG_PM static const struct dev_pm_ops igb_pm_ops = { SET_SYSTEM_SLEEP_PM_OPS(igb_suspend, igb_resume) SET_RUNTIME_PM_OPS(igb_runtime_suspend, igb_runtime_resume, igb_runtime_idle) }; #endif static void igb_shutdown(struct pci_dev *); static int igb_pci_sriov_configure(struct pci_dev *dev, int num_vfs); #ifdef CONFIG_IGB_DCA static int igb_notify_dca(struct notifier_block *, unsigned long, void *); static struct notifier_block dca_notifier = { .notifier_call = igb_notify_dca, .next = NULL, .priority = 0 }; #endif #ifdef CONFIG_PCI_IOV static unsigned int max_vfs; module_param(max_vfs, uint, 0); MODULE_PARM_DESC(max_vfs, "Maximum number of virtual functions to allocate per physical function"); #endif /* CONFIG_PCI_IOV */ static pci_ers_result_t igb_io_error_detected(struct pci_dev *, pci_channel_state_t); static pci_ers_result_t igb_io_slot_reset(struct pci_dev *); static void igb_io_resume(struct pci_dev *); static const struct pci_error_handlers igb_err_handler = { .error_detected = igb_io_error_detected, .slot_reset = igb_io_slot_reset, .resume = igb_io_resume, }; static void igb_init_dmac(struct igb_adapter *adapter, u32 pba); static struct pci_driver igb_driver = { .name = igb_driver_name, .id_table = igb_pci_tbl, .probe = igb_probe, .remove = igb_remove, #ifdef CONFIG_PM .driver.pm = &igb_pm_ops, #endif .shutdown = igb_shutdown, .sriov_configure = igb_pci_sriov_configure, .err_handler = &igb_err_handler }; MODULE_AUTHOR("Intel Corporation, <[email protected]>"); MODULE_DESCRIPTION("Intel(R) Gigabit Ethernet Network Driver"); MODULE_LICENSE("GPL v2"); #define DEFAULT_MSG_ENABLE (NETIF_MSG_DRV|NETIF_MSG_PROBE|NETIF_MSG_LINK) static int debug = -1; module_param(debug, int, 0); MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all)"); struct igb_reg_info { u32 ofs; char *name; }; static const struct igb_reg_info igb_reg_info_tbl[] = { /* General Registers */ {E1000_CTRL, "CTRL"}, {E1000_STATUS, "STATUS"}, {E1000_CTRL_EXT, "CTRL_EXT"}, /* Interrupt Registers */ {E1000_ICR, "ICR"}, /* RX Registers */ {E1000_RCTL, "RCTL"}, {E1000_RDLEN(0), "RDLEN"}, {E1000_RDH(0), "RDH"}, {E1000_RDT(0), "RDT"}, {E1000_RXDCTL(0), "RXDCTL"}, {E1000_RDBAL(0), "RDBAL"}, {E1000_RDBAH(0), "RDBAH"}, /* TX Registers */ {E1000_TCTL, "TCTL"}, {E1000_TDBAL(0), "TDBAL"}, {E1000_TDBAH(0), "TDBAH"}, {E1000_TDLEN(0), "TDLEN"}, {E1000_TDH(0), "TDH"}, {E1000_TDT(0), "TDT"}, {E1000_TXDCTL(0), "TXDCTL"}, {E1000_TDFH, "TDFH"}, {E1000_TDFT, "TDFT"}, {E1000_TDFHS, "TDFHS"}, {E1000_TDFPC, "TDFPC"}, /* List Terminator */ {} }; /* igb_regdump - register printout routine */ static void igb_regdump(struct e1000_hw *hw, struct igb_reg_info *reginfo) { int n = 0; char rname[16]; u32 regs[8]; switch (reginfo->ofs) { case E1000_RDLEN(0): for (n = 0; n < 4; n++) regs[n] = rd32(E1000_RDLEN(n)); break; case E1000_RDH(0): for (n = 0; n < 4; n++) regs[n] = rd32(E1000_RDH(n)); break; case E1000_RDT(0): for (n = 0; n < 4; n++) regs[n] = rd32(E1000_RDT(n)); break; case E1000_RXDCTL(0): for (n = 0; n < 4; n++) regs[n] = rd32(E1000_RXDCTL(n)); break; case E1000_RDBAL(0): for (n = 0; n < 4; n++) regs[n] = rd32(E1000_RDBAL(n)); break; case E1000_RDBAH(0): for (n = 0; n < 4; n++) regs[n] = rd32(E1000_RDBAH(n)); break; case E1000_TDBAL(0): for (n = 0; n < 4; n++) regs[n] = rd32(E1000_TDBAL(n)); break; case E1000_TDBAH(0): for (n = 0; n < 4; n++) regs[n] = rd32(E1000_TDBAH(n)); break; case E1000_TDLEN(0): for (n = 0; n < 4; n++) regs[n] = rd32(E1000_TDLEN(n)); break; case E1000_TDH(0): for (n = 0; n < 4; n++) regs[n] = rd32(E1000_TDH(n)); break; case E1000_TDT(0): for (n = 0; n < 4; n++) regs[n] = rd32(E1000_TDT(n)); break; case E1000_TXDCTL(0): for (n = 0; n < 4; n++) regs[n] = rd32(E1000_TXDCTL(n)); break; default: pr_info("%-15s %08x\n", reginfo->name, rd32(reginfo->ofs)); return; } snprintf(rname, 16, "%s%s", reginfo->name, "[0-3]"); pr_info("%-15s %08x %08x %08x %08x\n", rname, regs[0], regs[1], regs[2], regs[3]); } /* igb_dump - Print registers, Tx-rings and Rx-rings */ static void igb_dump(struct igb_adapter *adapter) { struct net_device *netdev = adapter->netdev; struct e1000_hw *hw = &adapter->hw; struct igb_reg_info *reginfo; struct igb_ring *tx_ring; union e1000_adv_tx_desc *tx_desc; struct my_u0 { __le64 a; __le64 b; } *u0; struct igb_ring *rx_ring; union e1000_adv_rx_desc *rx_desc; u32 staterr; u16 i, n; if (!netif_msg_hw(adapter)) return; /* Print netdevice Info */ if (netdev) { dev_info(&adapter->pdev->dev, "Net device Info\n"); pr_info("Device Name state trans_start\n"); pr_info("%-15s %016lX %016lX\n", netdev->name, netdev->state, dev_trans_start(netdev)); } /* Print Registers */ dev_info(&adapter->pdev->dev, "Register Dump\n"); pr_info(" Register Name Value\n"); for (reginfo = (struct igb_reg_info *)igb_reg_info_tbl; reginfo->name; reginfo++) { igb_regdump(hw, reginfo); } /* Print TX Ring Summary */ if (!netdev || !netif_running(netdev)) goto exit; dev_info(&adapter->pdev->dev, "TX Rings Summary\n"); pr_info("Queue [NTU] [NTC] [bi(ntc)->dma ] leng ntw timestamp\n"); for (n = 0; n < adapter->num_tx_queues; n++) { struct igb_tx_buffer *buffer_info; tx_ring = adapter->tx_ring[n]; buffer_info = &tx_ring->tx_buffer_info[tx_ring->next_to_clean]; pr_info(" %5d %5X %5X %016llX %04X %p %016llX\n", n, tx_ring->next_to_use, tx_ring->next_to_clean, (u64)dma_unmap_addr(buffer_info, dma), dma_unmap_len(buffer_info, len), buffer_info->next_to_watch, (u64)buffer_info->time_stamp); } /* Print TX Rings */ if (!netif_msg_tx_done(adapter)) goto rx_ring_summary; dev_info(&adapter->pdev->dev, "TX Rings Dump\n"); /* Transmit Descriptor Formats * * Advanced Transmit Descriptor * +--------------------------------------------------------------+ * 0 | Buffer Address [63:0] | * +--------------------------------------------------------------+ * 8 | PAYLEN | PORTS |CC|IDX | STA | DCMD |DTYP|MAC|RSV| DTALEN | * +--------------------------------------------------------------+ * 63 46 45 40 39 38 36 35 32 31 24 15 0 */ for (n = 0; n < adapter->num_tx_queues; n++) { tx_ring = adapter->tx_ring[n]; pr_info("------------------------------------\n"); pr_info("TX QUEUE INDEX = %d\n", tx_ring->queue_index); pr_info("------------------------------------\n"); pr_info("T [desc] [address 63:0 ] [PlPOCIStDDM Ln] [bi->dma ] leng ntw timestamp bi->skb\n"); for (i = 0; tx_ring->desc && (i < tx_ring->count); i++) { const char *next_desc; struct igb_tx_buffer *buffer_info; tx_desc = IGB_TX_DESC(tx_ring, i); buffer_info = &tx_ring->tx_buffer_info[i]; u0 = (struct my_u0 *)tx_desc; if (i == tx_ring->next_to_use && i == tx_ring->next_to_clean) next_desc = " NTC/U"; else if (i == tx_ring->next_to_use) next_desc = " NTU"; else if (i == tx_ring->next_to_clean) next_desc = " NTC"; else next_desc = ""; pr_info("T [0x%03X] %016llX %016llX %016llX %04X %p %016llX %p%s\n", i, le64_to_cpu(u0->a), le64_to_cpu(u0->b), (u64)dma_unmap_addr(buffer_info, dma), dma_unmap_len(buffer_info, len), buffer_info->next_to_watch, (u64)buffer_info->time_stamp, buffer_info->skb, next_desc); if (netif_msg_pktdata(adapter) && buffer_info->skb) print_hex_dump(KERN_INFO, "", DUMP_PREFIX_ADDRESS, 16, 1, buffer_info->skb->data, dma_unmap_len(buffer_info, len), true); } } /* Print RX Rings Summary */ rx_ring_summary: dev_info(&adapter->pdev->dev, "RX Rings Summary\n"); pr_info("Queue [NTU] [NTC]\n"); for (n = 0; n < adapter->num_rx_queues; n++) { rx_ring = adapter->rx_ring[n]; pr_info(" %5d %5X %5X\n", n, rx_ring->next_to_use, rx_ring->next_to_clean); } /* Print RX Rings */ if (!netif_msg_rx_status(adapter)) goto exit; dev_info(&adapter->pdev->dev, "RX Rings Dump\n"); /* Advanced Receive Descriptor (Read) Format * 63 1 0 * +-----------------------------------------------------+ * 0 | Packet Buffer Address [63:1] |A0/NSE| * +----------------------------------------------+------+ * 8 | Header Buffer Address [63:1] | DD | * +-----------------------------------------------------+ * * * Advanced Receive Descriptor (Write-Back) Format * * 63 48 47 32 31 30 21 20 17 16 4 3 0 * +------------------------------------------------------+ * 0 | Packet IP |SPH| HDR_LEN | RSV|Packet| RSS | * | Checksum Ident | | | | Type | Type | * +------------------------------------------------------+ * 8 | VLAN Tag | Length | Extended Error | Extended Status | * +------------------------------------------------------+ * 63 48 47 32 31 20 19 0 */ for (n = 0; n < adapter->num_rx_queues; n++) { rx_ring = adapter->rx_ring[n]; pr_info("------------------------------------\n"); pr_info("RX QUEUE INDEX = %d\n", rx_ring->queue_index); pr_info("------------------------------------\n"); pr_info("R [desc] [ PktBuf A0] [ HeadBuf DD] [bi->dma ] [bi->skb] <-- Adv Rx Read format\n"); pr_info("RWB[desc] [PcsmIpSHl PtRs] [vl er S cks ln] ---------------- [bi->skb] <-- Adv Rx Write-Back format\n"); for (i = 0; i < rx_ring->count; i++) { const char *next_desc; struct igb_rx_buffer *buffer_info; buffer_info = &rx_ring->rx_buffer_info[i]; rx_desc = IGB_RX_DESC(rx_ring, i); u0 = (struct my_u0 *)rx_desc; staterr = le32_to_cpu(rx_desc->wb.upper.status_error); if (i == rx_ring->next_to_use) next_desc = " NTU"; else if (i == rx_ring->next_to_clean) next_desc = " NTC"; else next_desc = ""; if (staterr & E1000_RXD_STAT_DD) { /* Descriptor Done */ pr_info("%s[0x%03X] %016llX %016llX ---------------- %s\n", "RWB", i, le64_to_cpu(u0->a), le64_to_cpu(u0->b), next_desc); } else { pr_info("%s[0x%03X] %016llX %016llX %016llX %s\n", "R ", i, le64_to_cpu(u0->a), le64_to_cpu(u0->b), (u64)buffer_info->dma, next_desc); if (netif_msg_pktdata(adapter) && buffer_info->dma && buffer_info->page) { print_hex_dump(KERN_INFO, "", DUMP_PREFIX_ADDRESS, 16, 1, page_address(buffer_info->page) + buffer_info->page_offset, igb_rx_bufsz(rx_ring), true); } } } } exit: return; } /** * igb_get_i2c_data - Reads the I2C SDA data bit * @data: opaque pointer to adapter struct * * Returns the I2C data bit value **/ static int igb_get_i2c_data(void *data) { struct igb_adapter *adapter = (struct igb_adapter *)data; struct e1000_hw *hw = &adapter->hw; s32 i2cctl = rd32(E1000_I2CPARAMS); return !!(i2cctl & E1000_I2C_DATA_IN); } /** * igb_set_i2c_data - Sets the I2C data bit * @data: pointer to hardware structure * @state: I2C data value (0 or 1) to set * * Sets the I2C data bit **/ static void igb_set_i2c_data(void *data, int state) { struct igb_adapter *adapter = (struct igb_adapter *)data; struct e1000_hw *hw = &adapter->hw; s32 i2cctl = rd32(E1000_I2CPARAMS); if (state) { i2cctl |= E1000_I2C_DATA_OUT | E1000_I2C_DATA_OE_N; } else { i2cctl &= ~E1000_I2C_DATA_OE_N; i2cctl &= ~E1000_I2C_DATA_OUT; } wr32(E1000_I2CPARAMS, i2cctl); wrfl(); } /** * igb_set_i2c_clk - Sets the I2C SCL clock * @data: pointer to hardware structure * @state: state to set clock * * Sets the I2C clock line to state **/ static void igb_set_i2c_clk(void *data, int state) { struct igb_adapter *adapter = (struct igb_adapter *)data; struct e1000_hw *hw = &adapter->hw; s32 i2cctl = rd32(E1000_I2CPARAMS); if (state) { i2cctl |= E1000_I2C_CLK_OUT | E1000_I2C_CLK_OE_N; } else { i2cctl &= ~E1000_I2C_CLK_OUT; i2cctl &= ~E1000_I2C_CLK_OE_N; } wr32(E1000_I2CPARAMS, i2cctl); wrfl(); } /** * igb_get_i2c_clk - Gets the I2C SCL clock state * @data: pointer to hardware structure * * Gets the I2C clock state **/ static int igb_get_i2c_clk(void *data) { struct igb_adapter *adapter = (struct igb_adapter *)data; struct e1000_hw *hw = &adapter->hw; s32 i2cctl = rd32(E1000_I2CPARAMS); return !!(i2cctl & E1000_I2C_CLK_IN); } static const struct i2c_algo_bit_data igb_i2c_algo = { .setsda = igb_set_i2c_data, .setscl = igb_set_i2c_clk, .getsda = igb_get_i2c_data, .getscl = igb_get_i2c_clk, .udelay = 5, .timeout = 20, }; /** * igb_get_hw_dev - return device * @hw: pointer to hardware structure * * used by hardware layer to print debugging information **/ struct net_device *igb_get_hw_dev(struct e1000_hw *hw) { struct igb_adapter *adapter = hw->back; return adapter->netdev; } /** * igb_init_module - Driver Registration Routine * * igb_init_module is the first routine called when the driver is * loaded. All it does is register with the PCI subsystem. **/ static int __init igb_init_module(void) { int ret; pr_info("%s\n", igb_driver_string); pr_info("%s\n", igb_copyright); #ifdef CONFIG_IGB_DCA dca_register_notify(&dca_notifier); #endif ret = pci_register_driver(&igb_driver); return ret; } module_init(igb_init_module); /** * igb_exit_module - Driver Exit Cleanup Routine * * igb_exit_module is called just before the driver is removed * from memory. **/ static void __exit igb_exit_module(void) { #ifdef CONFIG_IGB_DCA dca_unregister_notify(&dca_notifier); #endif pci_unregister_driver(&igb_driver); } module_exit(igb_exit_module); #define Q_IDX_82576(i) (((i & 0x1) << 3) + (i >> 1)) /** * igb_cache_ring_register - Descriptor ring to register mapping * @adapter: board private structure to initialize * * Once we know the feature-set enabled for the device, we'll cache * the register offset the descriptor ring is assigned to. **/ static void igb_cache_ring_register(struct igb_adapter *adapter) { int i = 0, j = 0; u32 rbase_offset = adapter->vfs_allocated_count; switch (adapter->hw.mac.type) { case e1000_82576: /* The queues are allocated for virtualization such that VF 0 * is allocated queues 0 and 8, VF 1 queues 1 and 9, etc. * In order to avoid collision we start at the first free queue * and continue consuming queues in the same sequence */ if (adapter->vfs_allocated_count) { for (; i < adapter->rss_queues; i++) adapter->rx_ring[i]->reg_idx = rbase_offset + Q_IDX_82576(i); } fallthrough; case e1000_82575: case e1000_82580: case e1000_i350: case e1000_i354: case e1000_i210: case e1000_i211: default: for (; i < adapter->num_rx_queues; i++) adapter->rx_ring[i]->reg_idx = rbase_offset + i; for (; j < adapter->num_tx_queues; j++) adapter->tx_ring[j]->reg_idx = rbase_offset + j; break; } } u32 igb_rd32(struct e1000_hw *hw, u32 reg) { struct igb_adapter *igb = container_of(hw, struct igb_adapter, hw); u8 __iomem *hw_addr = READ_ONCE(hw->hw_addr); u32 value = 0; if (E1000_REMOVED(hw_addr)) return ~value; value = readl(&hw_addr[reg]); /* reads should not return all F's */ if (!(~value) && (!reg || !(~readl(hw_addr)))) { struct net_device *netdev = igb->netdev; hw->hw_addr = NULL; netdev_err(netdev, "PCIe link lost\n"); WARN(pci_device_is_present(igb->pdev), "igb: Failed to read reg 0x%x!\n", reg); } return value; } /** * igb_write_ivar - configure ivar for given MSI-X vector * @hw: pointer to the HW structure * @msix_vector: vector number we are allocating to a given ring * @index: row index of IVAR register to write within IVAR table * @offset: column offset of in IVAR, should be multiple of 8 * * This function is intended to handle the writing of the IVAR register * for adapters 82576 and newer. The IVAR table consists of 2 columns, * each containing an cause allocation for an Rx and Tx ring, and a * variable number of rows depending on the number of queues supported. **/ static void igb_write_ivar(struct e1000_hw *hw, int msix_vector, int index, int offset) { u32 ivar = array_rd32(E1000_IVAR0, index); /* clear any bits that are currently set */ ivar &= ~((u32)0xFF << offset); /* write vector and valid bit */ ivar |= (msix_vector | E1000_IVAR_VALID) << offset; array_wr32(E1000_IVAR0, index, ivar); } #define IGB_N0_QUEUE -1 static void igb_assign_vector(struct igb_q_vector *q_vector, int msix_vector) { struct igb_adapter *adapter = q_vector->adapter; struct e1000_hw *hw = &adapter->hw; int rx_queue = IGB_N0_QUEUE; int tx_queue = IGB_N0_QUEUE; u32 msixbm = 0; if (q_vector->rx.ring) rx_queue = q_vector->rx.ring->reg_idx; if (q_vector->tx.ring) tx_queue = q_vector->tx.ring->reg_idx; switch (hw->mac.type) { case e1000_82575: /* The 82575 assigns vectors using a bitmask, which matches the * bitmask for the EICR/EIMS/EIMC registers. To assign one * or more queues to a vector, we write the appropriate bits * into the MSIXBM register for that vector. */ if (rx_queue > IGB_N0_QUEUE) msixbm = E1000_EICR_RX_QUEUE0 << rx_queue; if (tx_queue > IGB_N0_QUEUE) msixbm |= E1000_EICR_TX_QUEUE0 << tx_queue; if (!(adapter->flags & IGB_FLAG_HAS_MSIX) && msix_vector == 0) msixbm |= E1000_EIMS_OTHER; array_wr32(E1000_MSIXBM(0), msix_vector, msixbm); q_vector->eims_value = msixbm; break; case e1000_82576: /* 82576 uses a table that essentially consists of 2 columns * with 8 rows. The ordering is column-major so we use the * lower 3 bits as the row index, and the 4th bit as the * column offset. */ if (rx_queue > IGB_N0_QUEUE) igb_write_ivar(hw, msix_vector, rx_queue & 0x7, (rx_queue & 0x8) << 1); if (tx_queue > IGB_N0_QUEUE) igb_write_ivar(hw, msix_vector, tx_queue & 0x7, ((tx_queue & 0x8) << 1) + 8); q_vector->eims_value = BIT(msix_vector); break; case e1000_82580: case e1000_i350: case e1000_i354: case e1000_i210: case e1000_i211: /* On 82580 and newer adapters the scheme is similar to 82576 * however instead of ordering column-major we have things * ordered row-major. So we traverse the table by using * bit 0 as the column offset, and the remaining bits as the * row index. */ if (rx_queue > IGB_N0_QUEUE) igb_write_ivar(hw, msix_vector, rx_queue >> 1, (rx_queue & 0x1) << 4); if (tx_queue > IGB_N0_QUEUE) igb_write_ivar(hw, msix_vector, tx_queue >> 1, ((tx_queue & 0x1) << 4) + 8); q_vector->eims_value = BIT(msix_vector); break; default: BUG(); break; } /* add q_vector eims value to global eims_enable_mask */ adapter->eims_enable_mask |= q_vector->eims_value; /* configure q_vector to set itr on first interrupt */ q_vector->set_itr = 1; } /** * igb_configure_msix - Configure MSI-X hardware * @adapter: board private structure to initialize * * igb_configure_msix sets up the hardware to properly * generate MSI-X interrupts. **/ static void igb_configure_msix(struct igb_adapter *adapter) { u32 tmp; int i, vector = 0; struct e1000_hw *hw = &adapter->hw; adapter->eims_enable_mask = 0; /* set vector for other causes, i.e. link changes */ switch (hw->mac.type) { case e1000_82575: tmp = rd32(E1000_CTRL_EXT); /* enable MSI-X PBA support*/ tmp |= E1000_CTRL_EXT_PBA_CLR; /* Auto-Mask interrupts upon ICR read. */ tmp |= E1000_CTRL_EXT_EIAME; tmp |= E1000_CTRL_EXT_IRCA; wr32(E1000_CTRL_EXT, tmp); /* enable msix_other interrupt */ array_wr32(E1000_MSIXBM(0), vector++, E1000_EIMS_OTHER); adapter->eims_other = E1000_EIMS_OTHER; break; case e1000_82576: case e1000_82580: case e1000_i350: case e1000_i354: case e1000_i210: case e1000_i211: /* Turn on MSI-X capability first, or our settings * won't stick. And it will take days to debug. */ wr32(E1000_GPIE, E1000_GPIE_MSIX_MODE | E1000_GPIE_PBA | E1000_GPIE_EIAME | E1000_GPIE_NSICR); /* enable msix_other interrupt */ adapter->eims_other = BIT(vector); tmp = (vector++ | E1000_IVAR_VALID) << 8; wr32(E1000_IVAR_MISC, tmp); break; default: /* do nothing, since nothing else supports MSI-X */ break; } /* switch (hw->mac.type) */ adapter->eims_enable_mask |= adapter->eims_other; for (i = 0; i < adapter->num_q_vectors; i++) igb_assign_vector(adapter->q_vector[i], vector++); wrfl(); } /** * igb_request_msix - Initialize MSI-X interrupts * @adapter: board private structure to initialize * * igb_request_msix allocates MSI-X vectors and requests interrupts from the * kernel. **/ static int igb_request_msix(struct igb_adapter *adapter) { unsigned int num_q_vectors = adapter->num_q_vectors; struct net_device *netdev = adapter->netdev; int i, err = 0, vector = 0, free_vector = 0; err = request_irq(adapter->msix_entries[vector].vector, igb_msix_other, 0, netdev->name, adapter); if (err) goto err_out; if (num_q_vectors > MAX_Q_VECTORS) { num_q_vectors = MAX_Q_VECTORS; dev_warn(&adapter->pdev->dev, "The number of queue vectors (%d) is higher than max allowed (%d)\n", adapter->num_q_vectors, MAX_Q_VECTORS); } for (i = 0; i < num_q_vectors; i++) { struct igb_q_vector *q_vector = adapter->q_vector[i]; vector++; q_vector->itr_register = adapter->io_addr + E1000_EITR(vector); if (q_vector->rx.ring && q_vector->tx.ring) sprintf(q_vector->name, "%s-TxRx-%u", netdev->name, q_vector->rx.ring->queue_index); else if (q_vector->tx.ring) sprintf(q_vector->name, "%s-tx-%u", netdev->name, q_vector->tx.ring->queue_index); else if (q_vector->rx.ring) sprintf(q_vector->name, "%s-rx-%u", netdev->name, q_vector->rx.ring->queue_index); else sprintf(q_vector->name, "%s-unused", netdev->name); err = request_irq(adapter->msix_entries[vector].vector, igb_msix_ring, 0, q_vector->name, q_vector); if (err) goto err_free; } igb_configure_msix(adapter); return 0; err_free: /* free already assigned IRQs */ free_irq(adapter->msix_entries[free_vector++].vector, adapter); vector--; for (i = 0; i < vector; i++) { free_irq(adapter->msix_entries[free_vector++].vector, adapter->q_vector[i]); } err_out: return err; } /** * igb_free_q_vector - Free memory allocated for specific interrupt vector * @adapter: board private structure to initialize * @v_idx: Index of vector to be freed * * This function frees the memory allocated to the q_vector. **/ static void igb_free_q_vector(struct igb_adapter *adapter, int v_idx) { struct igb_q_vector *q_vector = adapter->q_vector[v_idx]; adapter->q_vector[v_idx] = NULL; /* igb_get_stats64() might access the rings on this vector, * we must wait a grace period before freeing it. */ if (q_vector) kfree_rcu(q_vector, rcu); } /** * igb_reset_q_vector - Reset config for interrupt vector * @adapter: board private structure to initialize * @v_idx: Index of vector to be reset * * If NAPI is enabled it will delete any references to the * NAPI struct. This is preparation for igb_free_q_vector. **/ static void igb_reset_q_vector(struct igb_adapter *adapter, int v_idx) { struct igb_q_vector *q_vector = adapter->q_vector[v_idx]; /* Coming from igb_set_interrupt_capability, the vectors are not yet * allocated. So, q_vector is NULL so we should stop here. */ if (!q_vector) return; if (q_vector->tx.ring) adapter->tx_ring[q_vector->tx.ring->queue_index] = NULL; if (q_vector->rx.ring) adapter->rx_ring[q_vector->rx.ring->queue_index] = NULL; netif_napi_del(&q_vector->napi); } static void igb_reset_interrupt_capability(struct igb_adapter *adapter) { int v_idx = adapter->num_q_vectors; if (adapter->flags & IGB_FLAG_HAS_MSIX) pci_disable_msix(adapter->pdev); else if (adapter->flags & IGB_FLAG_HAS_MSI) pci_disable_msi(adapter->pdev); while (v_idx--) igb_reset_q_vector(adapter, v_idx); } /** * igb_free_q_vectors - Free memory allocated for interrupt vectors * @adapter: board private structure to initialize * * This function frees the memory allocated to the q_vectors. In addition if * NAPI is enabled it will delete any references to the NAPI struct prior * to freeing the q_vector. **/ static void igb_free_q_vectors(struct igb_adapter *adapter) { int v_idx = adapter->num_q_vectors; adapter->num_tx_queues = 0; adapter->num_rx_queues = 0; adapter->num_q_vectors = 0; while (v_idx--) { igb_reset_q_vector(adapter, v_idx); igb_free_q_vector(adapter, v_idx); } } /** * igb_clear_interrupt_scheme - reset the device to a state of no interrupts * @adapter: board private structure to initialize * * This function resets the device so that it has 0 Rx queues, Tx queues, and * MSI-X interrupts allocated. */ static void igb_clear_interrupt_scheme(struct igb_adapter *adapter) { igb_free_q_vectors(adapter); igb_reset_interrupt_capability(adapter); } /** * igb_set_interrupt_capability - set MSI or MSI-X if supported * @adapter: board private structure to initialize * @msix: boolean value of MSIX capability * * Attempt to configure interrupts using the best available * capabilities of the hardware and kernel. **/ static void igb_set_interrupt_capability(struct igb_adapter *adapter, bool msix) { int err; int numvecs, i; if (!msix) goto msi_only; adapter->flags |= IGB_FLAG_HAS_MSIX; /* Number of supported queues. */ adapter->num_rx_queues = adapter->rss_queues; if (adapter->vfs_allocated_count) adapter->num_tx_queues = 1; else adapter->num_tx_queues = adapter->rss_queues; /* start with one vector for every Rx queue */ numvecs = adapter->num_rx_queues; /* if Tx handler is separate add 1 for every Tx queue */ if (!(adapter->flags & IGB_FLAG_QUEUE_PAIRS)) numvecs += adapter->num_tx_queues; /* store the number of vectors reserved for queues */ adapter->num_q_vectors = numvecs; /* add 1 vector for link status interrupts */ numvecs++; for (i = 0; i < numvecs; i++) adapter->msix_entries[i].entry = i; err = pci_enable_msix_range(adapter->pdev, adapter->msix_entries, numvecs, numvecs); if (err > 0) return; igb_reset_interrupt_capability(adapter); /* If we can't do MSI-X, try MSI */ msi_only: adapter->flags &= ~IGB_FLAG_HAS_MSIX; #ifdef CONFIG_PCI_IOV /* disable SR-IOV for non MSI-X configurations */ if (adapter->vf_data) { struct e1000_hw *hw = &adapter->hw; /* disable iov and allow time for transactions to clear */ pci_disable_sriov(adapter->pdev); msleep(500); kfree(adapter->vf_mac_list); adapter->vf_mac_list = NULL; kfree(adapter->vf_data); adapter->vf_data = NULL; wr32(E1000_IOVCTL, E1000_IOVCTL_REUSE_VFQ); wrfl(); msleep(100); dev_info(&adapter->pdev->dev, "IOV Disabled\n"); } #endif adapter->vfs_allocated_count = 0; adapter->rss_queues = 1; adapter->flags |= IGB_FLAG_QUEUE_PAIRS; adapter->num_rx_queues = 1; adapter->num_tx_queues = 1; adapter->num_q_vectors = 1; if (!pci_enable_msi(adapter->pdev)) adapter->flags |= IGB_FLAG_HAS_MSI; } static void igb_add_ring(struct igb_ring *ring, struct igb_ring_container *head) { head->ring = ring; head->count++; } /** * igb_alloc_q_vector - Allocate memory for a single interrupt vector * @adapter: board private structure to initialize * @v_count: q_vectors allocated on adapter, used for ring interleaving * @v_idx: index of vector in adapter struct * @txr_count: total number of Tx rings to allocate * @txr_idx: index of first Tx ring to allocate * @rxr_count: total number of Rx rings to allocate * @rxr_idx: index of first Rx ring to allocate * * We allocate one q_vector. If allocation fails we return -ENOMEM. **/ static int igb_alloc_q_vector(struct igb_adapter *adapter, int v_count, int v_idx, int txr_count, int txr_idx, int rxr_count, int rxr_idx) { struct igb_q_vector *q_vector; struct igb_ring *ring; int ring_count; size_t size; /* igb only supports 1 Tx and/or 1 Rx queue per vector */ if (txr_count > 1 || rxr_count > 1) return -ENOMEM; ring_count = txr_count + rxr_count; size = kmalloc_size_roundup(struct_size(q_vector, ring, ring_count)); /* allocate q_vector and rings */ q_vector = adapter->q_vector[v_idx]; if (!q_vector) { q_vector = kzalloc(size, GFP_KERNEL); } else if (size > ksize(q_vector)) { struct igb_q_vector *new_q_vector; new_q_vector = kzalloc(size, GFP_KERNEL); if (new_q_vector) kfree_rcu(q_vector, rcu); q_vector = new_q_vector; } else { memset(q_vector, 0, size); } if (!q_vector) return -ENOMEM; /* initialize NAPI */ netif_napi_add(adapter->netdev, &q_vector->napi, igb_poll); /* tie q_vector and adapter together */ adapter->q_vector[v_idx] = q_vector; q_vector->adapter = adapter; /* initialize work limits */ q_vector->tx.work_limit = adapter->tx_work_limit; /* initialize ITR configuration */ q_vector->itr_register = adapter->io_addr + E1000_EITR(0); q_vector->itr_val = IGB_START_ITR; /* initialize pointer to rings */ ring = q_vector->ring; /* intialize ITR */ if (rxr_count) { /* rx or rx/tx vector */ if (!adapter->rx_itr_setting || adapter->rx_itr_setting > 3) q_vector->itr_val = adapter->rx_itr_setting; } else { /* tx only vector */ if (!adapter->tx_itr_setting || adapter->tx_itr_setting > 3) q_vector->itr_val = adapter->tx_itr_setting; } if (txr_count) { /* assign generic ring traits */ ring->dev = &adapter->pdev->dev; ring->netdev = adapter->netdev; /* configure backlink on ring */ ring->q_vector = q_vector; /* update q_vector Tx values */ igb_add_ring(ring, &q_vector->tx); /* For 82575, context index must be unique per ring. */ if (adapter->hw.mac.type == e1000_82575) set_bit(IGB_RING_FLAG_TX_CTX_IDX, &ring->flags); /* apply Tx specific ring traits */ ring->count = adapter->tx_ring_count; ring->queue_index = txr_idx; ring->cbs_enable = false; ring->idleslope = 0; ring->sendslope = 0; ring->hicredit = 0; ring->locredit = 0; u64_stats_init(&ring->tx_syncp); u64_stats_init(&ring->tx_syncp2); /* assign ring to adapter */ adapter->tx_ring[txr_idx] = ring; /* push pointer to next ring */ ring++; } if (rxr_count) { /* assign generic ring traits */ ring->dev = &adapter->pdev->dev; ring->netdev = adapter->netdev; /* configure backlink on ring */ ring->q_vector = q_vector; /* update q_vector Rx values */ igb_add_ring(ring, &q_vector->rx); /* set flag indicating ring supports SCTP checksum offload */ if (adapter->hw.mac.type >= e1000_82576) set_bit(IGB_RING_FLAG_RX_SCTP_CSUM, &ring->flags); /* On i350, i354, i210, and i211, loopback VLAN packets * have the tag byte-swapped. */ if (adapter->hw.mac.type >= e1000_i350) set_bit(IGB_RING_FLAG_RX_LB_VLAN_BSWAP, &ring->flags); /* apply Rx specific ring traits */ ring->count = adapter->rx_ring_count; ring->queue_index = rxr_idx; u64_stats_init(&ring->rx_syncp); /* assign ring to adapter */ adapter->rx_ring[rxr_idx] = ring; } return 0; } /** * igb_alloc_q_vectors - Allocate memory for interrupt vectors * @adapter: board private structure to initialize * * We allocate one q_vector per queue interrupt. If allocation fails we * return -ENOMEM. **/ static int igb_alloc_q_vectors(struct igb_adapter *adapter) { int q_vectors = adapter->num_q_vectors; int rxr_remaining = adapter->num_rx_queues; int txr_remaining = adapter->num_tx_queues; int rxr_idx = 0, txr_idx = 0, v_idx = 0; int err; if (q_vectors >= (rxr_remaining + txr_remaining)) { for (; rxr_remaining; v_idx++) { err = igb_alloc_q_vector(adapter, q_vectors, v_idx, 0, 0, 1, rxr_idx); if (err) goto err_out; /* update counts and index */ rxr_remaining--; rxr_idx++; } } for (; v_idx < q_vectors; v_idx++) { int rqpv = DIV_ROUND_UP(rxr_remaining, q_vectors - v_idx); int tqpv = DIV_ROUND_UP(txr_remaining, q_vectors - v_idx); err = igb_alloc_q_vector(adapter, q_vectors, v_idx, tqpv, txr_idx, rqpv, rxr_idx); if (err) goto err_out; /* update counts and index */ rxr_remaining -= rqpv; txr_remaining -= tqpv; rxr_idx++; txr_idx++; } return 0; err_out: adapter->num_tx_queues = 0; adapter->num_rx_queues = 0; adapter->num_q_vectors = 0; while (v_idx--) igb_free_q_vector(adapter, v_idx); return -ENOMEM; } /** * igb_init_interrupt_scheme - initialize interrupts, allocate queues/vectors * @adapter: board private structure to initialize * @msix: boolean value of MSIX capability * * This function initializes the interrupts and allocates all of the queues. **/ static int igb_init_interrupt_scheme(struct igb_adapter *adapter, bool msix) { struct pci_dev *pdev = adapter->pdev; int err; igb_set_interrupt_capability(adapter, msix); err = igb_alloc_q_vectors(adapter); if (err) { dev_err(&pdev->dev, "Unable to allocate memory for vectors\n"); goto err_alloc_q_vectors; } igb_cache_ring_register(adapter); return 0; err_alloc_q_vectors: igb_reset_interrupt_capability(adapter); return err; } /** * igb_request_irq - initialize interrupts * @adapter: board private structure to initialize * * Attempts to configure interrupts using the best available * capabilities of the hardware and kernel. **/ static int igb_request_irq(struct igb_adapter *adapter) { struct net_device *netdev = adapter->netdev; struct pci_dev *pdev = adapter->pdev; int err = 0; if (adapter->flags & IGB_FLAG_HAS_MSIX) { err = igb_request_msix(adapter); if (!err) goto request_done; /* fall back to MSI */ igb_free_all_tx_resources(adapter); igb_free_all_rx_resources(adapter); igb_clear_interrupt_scheme(adapter); err = igb_init_interrupt_scheme(adapter, false); if (err) goto request_done; igb_setup_all_tx_resources(adapter); igb_setup_all_rx_resources(adapter); igb_configure(adapter); } igb_assign_vector(adapter->q_vector[0], 0); if (adapter->flags & IGB_FLAG_HAS_MSI) { err = request_irq(pdev->irq, igb_intr_msi, 0, netdev->name, adapter); if (!err) goto request_done; /* fall back to legacy interrupts */ igb_reset_interrupt_capability(adapter); adapter->flags &= ~IGB_FLAG_HAS_MSI; } err = request_irq(pdev->irq, igb_intr, IRQF_SHARED, netdev->name, adapter); if (err) dev_err(&pdev->dev, "Error %d getting interrupt\n", err); request_done: return err; } static void igb_free_irq(struct igb_adapter *adapter) { if (adapter->flags & IGB_FLAG_HAS_MSIX) { int vector = 0, i; free_irq(adapter->msix_entries[vector++].vector, adapter); for (i = 0; i < adapter->num_q_vectors; i++) free_irq(adapter->msix_entries[vector++].vector, adapter->q_vector[i]); } else { free_irq(adapter->pdev->irq, adapter); } } /** * igb_irq_disable - Mask off interrupt generation on the NIC * @adapter: board private structure **/ static void igb_irq_disable(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; /* we need to be careful when disabling interrupts. The VFs are also * mapped into these registers and so clearing the bits can cause * issues on the VF drivers so we only need to clear what we set */ if (adapter->flags & IGB_FLAG_HAS_MSIX) { u32 regval = rd32(E1000_EIAM); wr32(E1000_EIAM, regval & ~adapter->eims_enable_mask); wr32(E1000_EIMC, adapter->eims_enable_mask); regval = rd32(E1000_EIAC); wr32(E1000_EIAC, regval & ~adapter->eims_enable_mask); } wr32(E1000_IAM, 0); wr32(E1000_IMC, ~0); wrfl(); if (adapter->flags & IGB_FLAG_HAS_MSIX) { int i; for (i = 0; i < adapter->num_q_vectors; i++) synchronize_irq(adapter->msix_entries[i].vector); } else { synchronize_irq(adapter->pdev->irq); } } /** * igb_irq_enable - Enable default interrupt generation settings * @adapter: board private structure **/ static void igb_irq_enable(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; if (adapter->flags & IGB_FLAG_HAS_MSIX) { u32 ims = E1000_IMS_LSC | E1000_IMS_DOUTSYNC | E1000_IMS_DRSTA; u32 regval = rd32(E1000_EIAC); wr32(E1000_EIAC, regval | adapter->eims_enable_mask); regval = rd32(E1000_EIAM); wr32(E1000_EIAM, regval | adapter->eims_enable_mask); wr32(E1000_EIMS, adapter->eims_enable_mask); if (adapter->vfs_allocated_count) { wr32(E1000_MBVFIMR, 0xFF); ims |= E1000_IMS_VMMB; } wr32(E1000_IMS, ims); } else { wr32(E1000_IMS, IMS_ENABLE_MASK | E1000_IMS_DRSTA); wr32(E1000_IAM, IMS_ENABLE_MASK | E1000_IMS_DRSTA); } } static void igb_update_mng_vlan(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u16 pf_id = adapter->vfs_allocated_count; u16 vid = adapter->hw.mng_cookie.vlan_id; u16 old_vid = adapter->mng_vlan_id; if (hw->mng_cookie.status & E1000_MNG_DHCP_COOKIE_STATUS_VLAN) { /* add VID to filter table */ igb_vfta_set(hw, vid, pf_id, true, true); adapter->mng_vlan_id = vid; } else { adapter->mng_vlan_id = IGB_MNG_VLAN_NONE; } if ((old_vid != (u16)IGB_MNG_VLAN_NONE) && (vid != old_vid) && !test_bit(old_vid, adapter->active_vlans)) { /* remove VID from filter table */ igb_vfta_set(hw, vid, pf_id, false, true); } } /** * igb_release_hw_control - release control of the h/w to f/w * @adapter: address of board private structure * * igb_release_hw_control resets CTRL_EXT:DRV_LOAD bit. * For ASF and Pass Through versions of f/w this means that the * driver is no longer loaded. **/ static void igb_release_hw_control(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 ctrl_ext; /* Let firmware take over control of h/w */ ctrl_ext = rd32(E1000_CTRL_EXT); wr32(E1000_CTRL_EXT, ctrl_ext & ~E1000_CTRL_EXT_DRV_LOAD); } /** * igb_get_hw_control - get control of the h/w from f/w * @adapter: address of board private structure * * igb_get_hw_control sets CTRL_EXT:DRV_LOAD bit. * For ASF and Pass Through versions of f/w this means that * the driver is loaded. **/ static void igb_get_hw_control(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 ctrl_ext; /* Let firmware know the driver has taken over */ ctrl_ext = rd32(E1000_CTRL_EXT); wr32(E1000_CTRL_EXT, ctrl_ext | E1000_CTRL_EXT_DRV_LOAD); } static void enable_fqtss(struct igb_adapter *adapter, bool enable) { struct net_device *netdev = adapter->netdev; struct e1000_hw *hw = &adapter->hw; WARN_ON(hw->mac.type != e1000_i210); if (enable) adapter->flags |= IGB_FLAG_FQTSS; else adapter->flags &= ~IGB_FLAG_FQTSS; if (netif_running(netdev)) schedule_work(&adapter->reset_task); } static bool is_fqtss_enabled(struct igb_adapter *adapter) { return (adapter->flags & IGB_FLAG_FQTSS) ? true : false; } static void set_tx_desc_fetch_prio(struct e1000_hw *hw, int queue, enum tx_queue_prio prio) { u32 val; WARN_ON(hw->mac.type != e1000_i210); WARN_ON(queue < 0 || queue > 4); val = rd32(E1000_I210_TXDCTL(queue)); if (prio == TX_QUEUE_PRIO_HIGH) val |= E1000_TXDCTL_PRIORITY; else val &= ~E1000_TXDCTL_PRIORITY; wr32(E1000_I210_TXDCTL(queue), val); } static void set_queue_mode(struct e1000_hw *hw, int queue, enum queue_mode mode) { u32 val; WARN_ON(hw->mac.type != e1000_i210); WARN_ON(queue < 0 || queue > 1); val = rd32(E1000_I210_TQAVCC(queue)); if (mode == QUEUE_MODE_STREAM_RESERVATION) val |= E1000_TQAVCC_QUEUEMODE; else val &= ~E1000_TQAVCC_QUEUEMODE; wr32(E1000_I210_TQAVCC(queue), val); } static bool is_any_cbs_enabled(struct igb_adapter *adapter) { int i; for (i = 0; i < adapter->num_tx_queues; i++) { if (adapter->tx_ring[i]->cbs_enable) return true; } return false; } static bool is_any_txtime_enabled(struct igb_adapter *adapter) { int i; for (i = 0; i < adapter->num_tx_queues; i++) { if (adapter->tx_ring[i]->launchtime_enable) return true; } return false; } /** * igb_config_tx_modes - Configure "Qav Tx mode" features on igb * @adapter: pointer to adapter struct * @queue: queue number * * Configure CBS and Launchtime for a given hardware queue. * Parameters are retrieved from the correct Tx ring, so * igb_save_cbs_params() and igb_save_txtime_params() should be used * for setting those correctly prior to this function being called. **/ static void igb_config_tx_modes(struct igb_adapter *adapter, int queue) { struct net_device *netdev = adapter->netdev; struct e1000_hw *hw = &adapter->hw; struct igb_ring *ring; u32 tqavcc, tqavctrl; u16 value; WARN_ON(hw->mac.type != e1000_i210); WARN_ON(queue < 0 || queue > 1); ring = adapter->tx_ring[queue]; /* If any of the Qav features is enabled, configure queues as SR and * with HIGH PRIO. If none is, then configure them with LOW PRIO and * as SP. */ if (ring->cbs_enable || ring->launchtime_enable) { set_tx_desc_fetch_prio(hw, queue, TX_QUEUE_PRIO_HIGH); set_queue_mode(hw, queue, QUEUE_MODE_STREAM_RESERVATION); } else { set_tx_desc_fetch_prio(hw, queue, TX_QUEUE_PRIO_LOW); set_queue_mode(hw, queue, QUEUE_MODE_STRICT_PRIORITY); } /* If CBS is enabled, set DataTranARB and config its parameters. */ if (ring->cbs_enable || queue == 0) { /* i210 does not allow the queue 0 to be in the Strict * Priority mode while the Qav mode is enabled, so, * instead of disabling strict priority mode, we give * queue 0 the maximum of credits possible. * * See section 8.12.19 of the i210 datasheet, "Note: * Queue0 QueueMode must be set to 1b when * TransmitMode is set to Qav." */ if (queue == 0 && !ring->cbs_enable) { /* max "linkspeed" idleslope in kbps */ ring->idleslope = 1000000; ring->hicredit = ETH_FRAME_LEN; } /* Always set data transfer arbitration to credit-based * shaper algorithm on TQAVCTRL if CBS is enabled for any of * the queues. */ tqavctrl = rd32(E1000_I210_TQAVCTRL); tqavctrl |= E1000_TQAVCTRL_DATATRANARB; wr32(E1000_I210_TQAVCTRL, tqavctrl); /* According to i210 datasheet section 7.2.7.7, we should set * the 'idleSlope' field from TQAVCC register following the * equation: * * For 100 Mbps link speed: * * value = BW * 0x7735 * 0.2 (E1) * * For 1000Mbps link speed: * * value = BW * 0x7735 * 2 (E2) * * E1 and E2 can be merged into one equation as shown below. * Note that 'link-speed' is in Mbps. * * value = BW * 0x7735 * 2 * link-speed * -------------- (E3) * 1000 * * 'BW' is the percentage bandwidth out of full link speed * which can be found with the following equation. Note that * idleSlope here is the parameter from this function which * is in kbps. * * BW = idleSlope * ----------------- (E4) * link-speed * 1000 * * That said, we can come up with a generic equation to * calculate the value we should set it TQAVCC register by * replacing 'BW' in E3 by E4. The resulting equation is: * * value = idleSlope * 0x7735 * 2 * link-speed * ----------------- -------------- (E5) * link-speed * 1000 1000 * * 'link-speed' is present in both sides of the fraction so * it is canceled out. The final equation is the following: * * value = idleSlope * 61034 * ----------------- (E6) * 1000000 * * NOTE: For i210, given the above, we can see that idleslope * is represented in 16.38431 kbps units by the value at * the TQAVCC register (1Gbps / 61034), which reduces * the granularity for idleslope increments. * For instance, if you want to configure a 2576kbps * idleslope, the value to be written on the register * would have to be 157.23. If rounded down, you end * up with less bandwidth available than originally * required (~2572 kbps). If rounded up, you end up * with a higher bandwidth (~2589 kbps). Below the * approach we take is to always round up the * calculated value, so the resulting bandwidth might * be slightly higher for some configurations. */ value = DIV_ROUND_UP_ULL(ring->idleslope * 61034ULL, 1000000); tqavcc = rd32(E1000_I210_TQAVCC(queue)); tqavcc &= ~E1000_TQAVCC_IDLESLOPE_MASK; tqavcc |= value; wr32(E1000_I210_TQAVCC(queue), tqavcc); wr32(E1000_I210_TQAVHC(queue), 0x80000000 + ring->hicredit * 0x7735); } else { /* Set idleSlope to zero. */ tqavcc = rd32(E1000_I210_TQAVCC(queue)); tqavcc &= ~E1000_TQAVCC_IDLESLOPE_MASK; wr32(E1000_I210_TQAVCC(queue), tqavcc); /* Set hiCredit to zero. */ wr32(E1000_I210_TQAVHC(queue), 0); /* If CBS is not enabled for any queues anymore, then return to * the default state of Data Transmission Arbitration on * TQAVCTRL. */ if (!is_any_cbs_enabled(adapter)) { tqavctrl = rd32(E1000_I210_TQAVCTRL); tqavctrl &= ~E1000_TQAVCTRL_DATATRANARB; wr32(E1000_I210_TQAVCTRL, tqavctrl); } } /* If LaunchTime is enabled, set DataTranTIM. */ if (ring->launchtime_enable) { /* Always set DataTranTIM on TQAVCTRL if LaunchTime is enabled * for any of the SR queues, and configure fetchtime delta. * XXX NOTE: * - LaunchTime will be enabled for all SR queues. * - A fixed offset can be added relative to the launch * time of all packets if configured at reg LAUNCH_OS0. * We are keeping it as 0 for now (default value). */ tqavctrl = rd32(E1000_I210_TQAVCTRL); tqavctrl |= E1000_TQAVCTRL_DATATRANTIM | E1000_TQAVCTRL_FETCHTIME_DELTA; wr32(E1000_I210_TQAVCTRL, tqavctrl); } else { /* If Launchtime is not enabled for any SR queues anymore, * then clear DataTranTIM on TQAVCTRL and clear fetchtime delta, * effectively disabling Launchtime. */ if (!is_any_txtime_enabled(adapter)) { tqavctrl = rd32(E1000_I210_TQAVCTRL); tqavctrl &= ~E1000_TQAVCTRL_DATATRANTIM; tqavctrl &= ~E1000_TQAVCTRL_FETCHTIME_DELTA; wr32(E1000_I210_TQAVCTRL, tqavctrl); } } /* XXX: In i210 controller the sendSlope and loCredit parameters from * CBS are not configurable by software so we don't do any 'controller * configuration' in respect to these parameters. */ netdev_dbg(netdev, "Qav Tx mode: cbs %s, launchtime %s, queue %d idleslope %d sendslope %d hiCredit %d locredit %d\n", ring->cbs_enable ? "enabled" : "disabled", ring->launchtime_enable ? "enabled" : "disabled", queue, ring->idleslope, ring->sendslope, ring->hicredit, ring->locredit); } static int igb_save_txtime_params(struct igb_adapter *adapter, int queue, bool enable) { struct igb_ring *ring; if (queue < 0 || queue > adapter->num_tx_queues) return -EINVAL; ring = adapter->tx_ring[queue]; ring->launchtime_enable = enable; return 0; } static int igb_save_cbs_params(struct igb_adapter *adapter, int queue, bool enable, int idleslope, int sendslope, int hicredit, int locredit) { struct igb_ring *ring; if (queue < 0 || queue > adapter->num_tx_queues) return -EINVAL; ring = adapter->tx_ring[queue]; ring->cbs_enable = enable; ring->idleslope = idleslope; ring->sendslope = sendslope; ring->hicredit = hicredit; ring->locredit = locredit; return 0; } /** * igb_setup_tx_mode - Switch to/from Qav Tx mode when applicable * @adapter: pointer to adapter struct * * Configure TQAVCTRL register switching the controller's Tx mode * if FQTSS mode is enabled or disabled. Additionally, will issue * a call to igb_config_tx_modes() per queue so any previously saved * Tx parameters are applied. **/ static void igb_setup_tx_mode(struct igb_adapter *adapter) { struct net_device *netdev = adapter->netdev; struct e1000_hw *hw = &adapter->hw; u32 val; /* Only i210 controller supports changing the transmission mode. */ if (hw->mac.type != e1000_i210) return; if (is_fqtss_enabled(adapter)) { int i, max_queue; /* Configure TQAVCTRL register: set transmit mode to 'Qav', * set data fetch arbitration to 'round robin', set SP_WAIT_SR * so SP queues wait for SR ones. */ val = rd32(E1000_I210_TQAVCTRL); val |= E1000_TQAVCTRL_XMIT_MODE | E1000_TQAVCTRL_SP_WAIT_SR; val &= ~E1000_TQAVCTRL_DATAFETCHARB; wr32(E1000_I210_TQAVCTRL, val); /* Configure Tx and Rx packet buffers sizes as described in * i210 datasheet section 7.2.7.7. */ val = rd32(E1000_TXPBS); val &= ~I210_TXPBSIZE_MASK; val |= I210_TXPBSIZE_PB0_6KB | I210_TXPBSIZE_PB1_6KB | I210_TXPBSIZE_PB2_6KB | I210_TXPBSIZE_PB3_6KB; wr32(E1000_TXPBS, val); val = rd32(E1000_RXPBS); val &= ~I210_RXPBSIZE_MASK; val |= I210_RXPBSIZE_PB_30KB; wr32(E1000_RXPBS, val); /* Section 8.12.9 states that MAX_TPKT_SIZE from DTXMXPKTSZ * register should not exceed the buffer size programmed in * TXPBS. The smallest buffer size programmed in TXPBS is 4kB * so according to the datasheet we should set MAX_TPKT_SIZE to * 4kB / 64. * * However, when we do so, no frame from queue 2 and 3 are * transmitted. It seems the MAX_TPKT_SIZE should not be great * or _equal_ to the buffer size programmed in TXPBS. For this * reason, we set MAX_ TPKT_SIZE to (4kB - 1) / 64. */ val = (4096 - 1) / 64; wr32(E1000_I210_DTXMXPKTSZ, val); /* Since FQTSS mode is enabled, apply any CBS configuration * previously set. If no previous CBS configuration has been * done, then the initial configuration is applied, which means * CBS is disabled. */ max_queue = (adapter->num_tx_queues < I210_SR_QUEUES_NUM) ? adapter->num_tx_queues : I210_SR_QUEUES_NUM; for (i = 0; i < max_queue; i++) { igb_config_tx_modes(adapter, i); } } else { wr32(E1000_RXPBS, I210_RXPBSIZE_DEFAULT); wr32(E1000_TXPBS, I210_TXPBSIZE_DEFAULT); wr32(E1000_I210_DTXMXPKTSZ, I210_DTXMXPKTSZ_DEFAULT); val = rd32(E1000_I210_TQAVCTRL); /* According to Section 8.12.21, the other flags we've set when * enabling FQTSS are not relevant when disabling FQTSS so we * don't set they here. */ val &= ~E1000_TQAVCTRL_XMIT_MODE; wr32(E1000_I210_TQAVCTRL, val); } netdev_dbg(netdev, "FQTSS %s\n", (is_fqtss_enabled(adapter)) ? "enabled" : "disabled"); } /** * igb_configure - configure the hardware for RX and TX * @adapter: private board structure **/ static void igb_configure(struct igb_adapter *adapter) { struct net_device *netdev = adapter->netdev; int i; igb_get_hw_control(adapter); igb_set_rx_mode(netdev); igb_setup_tx_mode(adapter); igb_restore_vlan(adapter); igb_setup_tctl(adapter); igb_setup_mrqc(adapter); igb_setup_rctl(adapter); igb_nfc_filter_restore(adapter); igb_configure_tx(adapter); igb_configure_rx(adapter); igb_rx_fifo_flush_82575(&adapter->hw); /* call igb_desc_unused which always leaves * at least 1 descriptor unused to make sure * next_to_use != next_to_clean */ for (i = 0; i < adapter->num_rx_queues; i++) { struct igb_ring *ring = adapter->rx_ring[i]; igb_alloc_rx_buffers(ring, igb_desc_unused(ring)); } } /** * igb_power_up_link - Power up the phy/serdes link * @adapter: address of board private structure **/ void igb_power_up_link(struct igb_adapter *adapter) { igb_reset_phy(&adapter->hw); if (adapter->hw.phy.media_type == e1000_media_type_copper) igb_power_up_phy_copper(&adapter->hw); else igb_power_up_serdes_link_82575(&adapter->hw); igb_setup_link(&adapter->hw); } /** * igb_power_down_link - Power down the phy/serdes link * @adapter: address of board private structure */ static void igb_power_down_link(struct igb_adapter *adapter) { if (adapter->hw.phy.media_type == e1000_media_type_copper) igb_power_down_phy_copper_82575(&adapter->hw); else igb_shutdown_serdes_link_82575(&adapter->hw); } /** * igb_check_swap_media - Detect and switch function for Media Auto Sense * @adapter: address of the board private structure **/ static void igb_check_swap_media(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 ctrl_ext, connsw; bool swap_now = false; ctrl_ext = rd32(E1000_CTRL_EXT); connsw = rd32(E1000_CONNSW); /* need to live swap if current media is copper and we have fiber/serdes * to go to. */ if ((hw->phy.media_type == e1000_media_type_copper) && (!(connsw & E1000_CONNSW_AUTOSENSE_EN))) { swap_now = true; } else if ((hw->phy.media_type != e1000_media_type_copper) && !(connsw & E1000_CONNSW_SERDESD)) { /* copper signal takes time to appear */ if (adapter->copper_tries < 4) { adapter->copper_tries++; connsw |= E1000_CONNSW_AUTOSENSE_CONF; wr32(E1000_CONNSW, connsw); return; } else { adapter->copper_tries = 0; if ((connsw & E1000_CONNSW_PHYSD) && (!(connsw & E1000_CONNSW_PHY_PDN))) { swap_now = true; connsw &= ~E1000_CONNSW_AUTOSENSE_CONF; wr32(E1000_CONNSW, connsw); } } } if (!swap_now) return; switch (hw->phy.media_type) { case e1000_media_type_copper: netdev_info(adapter->netdev, "MAS: changing media to fiber/serdes\n"); ctrl_ext |= E1000_CTRL_EXT_LINK_MODE_PCIE_SERDES; adapter->flags |= IGB_FLAG_MEDIA_RESET; adapter->copper_tries = 0; break; case e1000_media_type_internal_serdes: case e1000_media_type_fiber: netdev_info(adapter->netdev, "MAS: changing media to copper\n"); ctrl_ext &= ~E1000_CTRL_EXT_LINK_MODE_PCIE_SERDES; adapter->flags |= IGB_FLAG_MEDIA_RESET; break; default: /* shouldn't get here during regular operation */ netdev_err(adapter->netdev, "AMS: Invalid media type found, returning\n"); break; } wr32(E1000_CTRL_EXT, ctrl_ext); } /** * igb_up - Open the interface and prepare it to handle traffic * @adapter: board private structure **/ int igb_up(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; int i; /* hardware has been reset, we need to reload some things */ igb_configure(adapter); clear_bit(__IGB_DOWN, &adapter->state); for (i = 0; i < adapter->num_q_vectors; i++) napi_enable(&(adapter->q_vector[i]->napi)); if (adapter->flags & IGB_FLAG_HAS_MSIX) igb_configure_msix(adapter); else igb_assign_vector(adapter->q_vector[0], 0); /* Clear any pending interrupts. */ rd32(E1000_TSICR); rd32(E1000_ICR); igb_irq_enable(adapter); /* notify VFs that reset has been completed */ if (adapter->vfs_allocated_count) { u32 reg_data = rd32(E1000_CTRL_EXT); reg_data |= E1000_CTRL_EXT_PFRSTD; wr32(E1000_CTRL_EXT, reg_data); } netif_tx_start_all_queues(adapter->netdev); /* start the watchdog. */ hw->mac.get_link_status = 1; schedule_work(&adapter->watchdog_task); if ((adapter->flags & IGB_FLAG_EEE) && (!hw->dev_spec._82575.eee_disable)) adapter->eee_advert = MDIO_EEE_100TX | MDIO_EEE_1000T; return 0; } void igb_down(struct igb_adapter *adapter) { struct net_device *netdev = adapter->netdev; struct e1000_hw *hw = &adapter->hw; u32 tctl, rctl; int i; /* signal that we're down so the interrupt handler does not * reschedule our watchdog timer */ set_bit(__IGB_DOWN, &adapter->state); /* disable receives in the hardware */ rctl = rd32(E1000_RCTL); wr32(E1000_RCTL, rctl & ~E1000_RCTL_EN); /* flush and sleep below */ igb_nfc_filter_exit(adapter); netif_carrier_off(netdev); netif_tx_stop_all_queues(netdev); /* disable transmits in the hardware */ tctl = rd32(E1000_TCTL); tctl &= ~E1000_TCTL_EN; wr32(E1000_TCTL, tctl); /* flush both disables and wait for them to finish */ wrfl(); usleep_range(10000, 11000); igb_irq_disable(adapter); adapter->flags &= ~IGB_FLAG_NEED_LINK_UPDATE; for (i = 0; i < adapter->num_q_vectors; i++) { if (adapter->q_vector[i]) { napi_synchronize(&adapter->q_vector[i]->napi); napi_disable(&adapter->q_vector[i]->napi); } } del_timer_sync(&adapter->watchdog_timer); del_timer_sync(&adapter->phy_info_timer); /* record the stats before reset*/ spin_lock(&adapter->stats64_lock); igb_update_stats(adapter); spin_unlock(&adapter->stats64_lock); adapter->link_speed = 0; adapter->link_duplex = 0; if (!pci_channel_offline(adapter->pdev)) igb_reset(adapter); /* clear VLAN promisc flag so VFTA will be updated if necessary */ adapter->flags &= ~IGB_FLAG_VLAN_PROMISC; igb_clean_all_tx_rings(adapter); igb_clean_all_rx_rings(adapter); #ifdef CONFIG_IGB_DCA /* since we reset the hardware DCA settings were cleared */ igb_setup_dca(adapter); #endif } void igb_reinit_locked(struct igb_adapter *adapter) { while (test_and_set_bit(__IGB_RESETTING, &adapter->state)) usleep_range(1000, 2000); igb_down(adapter); igb_up(adapter); clear_bit(__IGB_RESETTING, &adapter->state); } /** igb_enable_mas - Media Autosense re-enable after swap * * @adapter: adapter struct **/ static void igb_enable_mas(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 connsw = rd32(E1000_CONNSW); /* configure for SerDes media detect */ if ((hw->phy.media_type == e1000_media_type_copper) && (!(connsw & E1000_CONNSW_SERDESD))) { connsw |= E1000_CONNSW_ENRGSRC; connsw |= E1000_CONNSW_AUTOSENSE_EN; wr32(E1000_CONNSW, connsw); wrfl(); } } #ifdef CONFIG_IGB_HWMON /** * igb_set_i2c_bb - Init I2C interface * @hw: pointer to hardware structure **/ static void igb_set_i2c_bb(struct e1000_hw *hw) { u32 ctrl_ext; s32 i2cctl; ctrl_ext = rd32(E1000_CTRL_EXT); ctrl_ext |= E1000_CTRL_I2C_ENA; wr32(E1000_CTRL_EXT, ctrl_ext); wrfl(); i2cctl = rd32(E1000_I2CPARAMS); i2cctl |= E1000_I2CBB_EN | E1000_I2C_CLK_OE_N | E1000_I2C_DATA_OE_N; wr32(E1000_I2CPARAMS, i2cctl); wrfl(); } #endif void igb_reset(struct igb_adapter *adapter) { struct pci_dev *pdev = adapter->pdev; struct e1000_hw *hw = &adapter->hw; struct e1000_mac_info *mac = &hw->mac; struct e1000_fc_info *fc = &hw->fc; u32 pba, hwm; /* Repartition Pba for greater than 9k mtu * To take effect CTRL.RST is required. */ switch (mac->type) { case e1000_i350: case e1000_i354: case e1000_82580: pba = rd32(E1000_RXPBS); pba = igb_rxpbs_adjust_82580(pba); break; case e1000_82576: pba = rd32(E1000_RXPBS); pba &= E1000_RXPBS_SIZE_MASK_82576; break; case e1000_82575: case e1000_i210: case e1000_i211: default: pba = E1000_PBA_34K; break; } if (mac->type == e1000_82575) { u32 min_rx_space, min_tx_space, needed_tx_space; /* write Rx PBA so that hardware can report correct Tx PBA */ wr32(E1000_PBA, pba); /* To maintain wire speed transmits, the Tx FIFO should be * large enough to accommodate two full transmit packets, * rounded up to the next 1KB and expressed in KB. Likewise, * the Rx FIFO should be large enough to accommodate at least * one full receive packet and is similarly rounded up and * expressed in KB. */ min_rx_space = DIV_ROUND_UP(MAX_JUMBO_FRAME_SIZE, 1024); /* The Tx FIFO also stores 16 bytes of information about the Tx * but don't include Ethernet FCS because hardware appends it. * We only need to round down to the nearest 512 byte block * count since the value we care about is 2 frames, not 1. */ min_tx_space = adapter->max_frame_size; min_tx_space += sizeof(union e1000_adv_tx_desc) - ETH_FCS_LEN; min_tx_space = DIV_ROUND_UP(min_tx_space, 512); /* upper 16 bits has Tx packet buffer allocation size in KB */ needed_tx_space = min_tx_space - (rd32(E1000_PBA) >> 16); /* If current Tx allocation is less than the min Tx FIFO size, * and the min Tx FIFO size is less than the current Rx FIFO * allocation, take space away from current Rx allocation. */ if (needed_tx_space < pba) { pba -= needed_tx_space; /* if short on Rx space, Rx wins and must trump Tx * adjustment */ if (pba < min_rx_space) pba = min_rx_space; } /* adjust PBA for jumbo frames */ wr32(E1000_PBA, pba); } /* flow control settings * The high water mark must be low enough to fit one full frame * after transmitting the pause frame. As such we must have enough * space to allow for us to complete our current transmit and then * receive the frame that is in progress from the link partner. * Set it to: * - the full Rx FIFO size minus one full Tx plus one full Rx frame */ hwm = (pba << 10) - (adapter->max_frame_size + MAX_JUMBO_FRAME_SIZE); fc->high_water = hwm & 0xFFFFFFF0; /* 16-byte granularity */ fc->low_water = fc->high_water - 16; fc->pause_time = 0xFFFF; fc->send_xon = 1; fc->current_mode = fc->requested_mode; /* disable receive for all VFs and wait one second */ if (adapter->vfs_allocated_count) { int i; for (i = 0 ; i < adapter->vfs_allocated_count; i++) adapter->vf_data[i].flags &= IGB_VF_FLAG_PF_SET_MAC; /* ping all the active vfs to let them know we are going down */ igb_ping_all_vfs(adapter); /* disable transmits and receives */ wr32(E1000_VFRE, 0); wr32(E1000_VFTE, 0); } /* Allow time for pending master requests to run */ hw->mac.ops.reset_hw(hw); wr32(E1000_WUC, 0); if (adapter->flags & IGB_FLAG_MEDIA_RESET) { /* need to resetup here after media swap */ adapter->ei.get_invariants(hw); adapter->flags &= ~IGB_FLAG_MEDIA_RESET; } if ((mac->type == e1000_82575 || mac->type == e1000_i350) && (adapter->flags & IGB_FLAG_MAS_ENABLE)) { igb_enable_mas(adapter); } if (hw->mac.ops.init_hw(hw)) dev_err(&pdev->dev, "Hardware Error\n"); /* RAR registers were cleared during init_hw, clear mac table */ igb_flush_mac_table(adapter); __dev_uc_unsync(adapter->netdev, NULL); /* Recover default RAR entry */ igb_set_default_mac_filter(adapter); /* Flow control settings reset on hardware reset, so guarantee flow * control is off when forcing speed. */ if (!hw->mac.autoneg) igb_force_mac_fc(hw); igb_init_dmac(adapter, pba); #ifdef CONFIG_IGB_HWMON /* Re-initialize the thermal sensor on i350 devices. */ if (!test_bit(__IGB_DOWN, &adapter->state)) { if (mac->type == e1000_i350 && hw->bus.func == 0) { /* If present, re-initialize the external thermal sensor * interface. */ if (adapter->ets) igb_set_i2c_bb(hw); mac->ops.init_thermal_sensor_thresh(hw); } } #endif /* Re-establish EEE setting */ if (hw->phy.media_type == e1000_media_type_copper) { switch (mac->type) { case e1000_i350: case e1000_i210: case e1000_i211: igb_set_eee_i350(hw, true, true); break; case e1000_i354: igb_set_eee_i354(hw, true, true); break; default: break; } } if (!netif_running(adapter->netdev)) igb_power_down_link(adapter); igb_update_mng_vlan(adapter); /* Enable h/w to recognize an 802.1Q VLAN Ethernet packet */ wr32(E1000_VET, ETHERNET_IEEE_VLAN_TYPE); /* Re-enable PTP, where applicable. */ if (adapter->ptp_flags & IGB_PTP_ENABLED) igb_ptp_reset(adapter); igb_get_phy_info(hw); } static netdev_features_t igb_fix_features(struct net_device *netdev, netdev_features_t features) { /* Since there is no support for separate Rx/Tx vlan accel * enable/disable make sure Tx flag is always in same state as Rx. */ if (features & NETIF_F_HW_VLAN_CTAG_RX) features |= NETIF_F_HW_VLAN_CTAG_TX; else features &= ~NETIF_F_HW_VLAN_CTAG_TX; return features; } static int igb_set_features(struct net_device *netdev, netdev_features_t features) { netdev_features_t changed = netdev->features ^ features; struct igb_adapter *adapter = netdev_priv(netdev); if (changed & NETIF_F_HW_VLAN_CTAG_RX) igb_vlan_mode(netdev, features); if (!(changed & (NETIF_F_RXALL | NETIF_F_NTUPLE))) return 0; if (!(features & NETIF_F_NTUPLE)) { struct hlist_node *node2; struct igb_nfc_filter *rule; spin_lock(&adapter->nfc_lock); hlist_for_each_entry_safe(rule, node2, &adapter->nfc_filter_list, nfc_node) { igb_erase_filter(adapter, rule); hlist_del(&rule->nfc_node); kfree(rule); } spin_unlock(&adapter->nfc_lock); adapter->nfc_filter_count = 0; } netdev->features = features; if (netif_running(netdev)) igb_reinit_locked(adapter); else igb_reset(adapter); return 1; } static int igb_ndo_fdb_add(struct ndmsg *ndm, struct nlattr *tb[], struct net_device *dev, const unsigned char *addr, u16 vid, u16 flags, struct netlink_ext_ack *extack) { /* guarantee we can provide a unique filter for the unicast address */ if (is_unicast_ether_addr(addr) || is_link_local_ether_addr(addr)) { struct igb_adapter *adapter = netdev_priv(dev); int vfn = adapter->vfs_allocated_count; if (netdev_uc_count(dev) >= igb_available_rars(adapter, vfn)) return -ENOMEM; } return ndo_dflt_fdb_add(ndm, tb, dev, addr, vid, flags); } #define IGB_MAX_MAC_HDR_LEN 127 #define IGB_MAX_NETWORK_HDR_LEN 511 static netdev_features_t igb_features_check(struct sk_buff *skb, struct net_device *dev, netdev_features_t features) { unsigned int network_hdr_len, mac_hdr_len; /* Make certain the headers can be described by a context descriptor */ mac_hdr_len = skb_network_header(skb) - skb->data; if (unlikely(mac_hdr_len > IGB_MAX_MAC_HDR_LEN)) return features & ~(NETIF_F_HW_CSUM | NETIF_F_SCTP_CRC | NETIF_F_GSO_UDP_L4 | NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_TSO | NETIF_F_TSO6); network_hdr_len = skb_checksum_start(skb) - skb_network_header(skb); if (unlikely(network_hdr_len > IGB_MAX_NETWORK_HDR_LEN)) return features & ~(NETIF_F_HW_CSUM | NETIF_F_SCTP_CRC | NETIF_F_GSO_UDP_L4 | NETIF_F_TSO | NETIF_F_TSO6); /* We can only support IPV4 TSO in tunnels if we can mangle the * inner IP ID field, so strip TSO if MANGLEID is not supported. */ if (skb->encapsulation && !(features & NETIF_F_TSO_MANGLEID)) features &= ~NETIF_F_TSO; return features; } static void igb_offload_apply(struct igb_adapter *adapter, s32 queue) { if (!is_fqtss_enabled(adapter)) { enable_fqtss(adapter, true); return; } igb_config_tx_modes(adapter, queue); if (!is_any_cbs_enabled(adapter) && !is_any_txtime_enabled(adapter)) enable_fqtss(adapter, false); } static int igb_offload_cbs(struct igb_adapter *adapter, struct tc_cbs_qopt_offload *qopt) { struct e1000_hw *hw = &adapter->hw; int err; /* CBS offloading is only supported by i210 controller. */ if (hw->mac.type != e1000_i210) return -EOPNOTSUPP; /* CBS offloading is only supported by queue 0 and queue 1. */ if (qopt->queue < 0 || qopt->queue > 1) return -EINVAL; err = igb_save_cbs_params(adapter, qopt->queue, qopt->enable, qopt->idleslope, qopt->sendslope, qopt->hicredit, qopt->locredit); if (err) return err; igb_offload_apply(adapter, qopt->queue); return 0; } #define ETHER_TYPE_FULL_MASK ((__force __be16)~0) #define VLAN_PRIO_FULL_MASK (0x07) static int igb_parse_cls_flower(struct igb_adapter *adapter, struct flow_cls_offload *f, int traffic_class, struct igb_nfc_filter *input) { struct flow_rule *rule = flow_cls_offload_flow_rule(f); struct flow_dissector *dissector = rule->match.dissector; struct netlink_ext_ack *extack = f->common.extack; if (dissector->used_keys & ~(BIT_ULL(FLOW_DISSECTOR_KEY_BASIC) | BIT_ULL(FLOW_DISSECTOR_KEY_CONTROL) | BIT_ULL(FLOW_DISSECTOR_KEY_ETH_ADDRS) | BIT_ULL(FLOW_DISSECTOR_KEY_VLAN))) { NL_SET_ERR_MSG_MOD(extack, "Unsupported key used, only BASIC, CONTROL, ETH_ADDRS and VLAN are supported"); return -EOPNOTSUPP; } if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ETH_ADDRS)) { struct flow_match_eth_addrs match; flow_rule_match_eth_addrs(rule, &match); if (!is_zero_ether_addr(match.mask->dst)) { if (!is_broadcast_ether_addr(match.mask->dst)) { NL_SET_ERR_MSG_MOD(extack, "Only full masks are supported for destination MAC address"); return -EINVAL; } input->filter.match_flags |= IGB_FILTER_FLAG_DST_MAC_ADDR; ether_addr_copy(input->filter.dst_addr, match.key->dst); } if (!is_zero_ether_addr(match.mask->src)) { if (!is_broadcast_ether_addr(match.mask->src)) { NL_SET_ERR_MSG_MOD(extack, "Only full masks are supported for source MAC address"); return -EINVAL; } input->filter.match_flags |= IGB_FILTER_FLAG_SRC_MAC_ADDR; ether_addr_copy(input->filter.src_addr, match.key->src); } } if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_BASIC)) { struct flow_match_basic match; flow_rule_match_basic(rule, &match); if (match.mask->n_proto) { if (match.mask->n_proto != ETHER_TYPE_FULL_MASK) { NL_SET_ERR_MSG_MOD(extack, "Only full mask is supported for EtherType filter"); return -EINVAL; } input->filter.match_flags |= IGB_FILTER_FLAG_ETHER_TYPE; input->filter.etype = match.key->n_proto; } } if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_VLAN)) { struct flow_match_vlan match; flow_rule_match_vlan(rule, &match); if (match.mask->vlan_priority) { if (match.mask->vlan_priority != VLAN_PRIO_FULL_MASK) { NL_SET_ERR_MSG_MOD(extack, "Only full mask is supported for VLAN priority"); return -EINVAL; } input->filter.match_flags |= IGB_FILTER_FLAG_VLAN_TCI; input->filter.vlan_tci = (__force __be16)match.key->vlan_priority; } } input->action = traffic_class; input->cookie = f->cookie; return 0; } static int igb_configure_clsflower(struct igb_adapter *adapter, struct flow_cls_offload *cls_flower) { struct netlink_ext_ack *extack = cls_flower->common.extack; struct igb_nfc_filter *filter, *f; int err, tc; tc = tc_classid_to_hwtc(adapter->netdev, cls_flower->classid); if (tc < 0) { NL_SET_ERR_MSG_MOD(extack, "Invalid traffic class"); return -EINVAL; } filter = kzalloc(sizeof(*filter), GFP_KERNEL); if (!filter) return -ENOMEM; err = igb_parse_cls_flower(adapter, cls_flower, tc, filter); if (err < 0) goto err_parse; spin_lock(&adapter->nfc_lock); hlist_for_each_entry(f, &adapter->nfc_filter_list, nfc_node) { if (!memcmp(&f->filter, &filter->filter, sizeof(f->filter))) { err = -EEXIST; NL_SET_ERR_MSG_MOD(extack, "This filter is already set in ethtool"); goto err_locked; } } hlist_for_each_entry(f, &adapter->cls_flower_list, nfc_node) { if (!memcmp(&f->filter, &filter->filter, sizeof(f->filter))) { err = -EEXIST; NL_SET_ERR_MSG_MOD(extack, "This filter is already set in cls_flower"); goto err_locked; } } err = igb_add_filter(adapter, filter); if (err < 0) { NL_SET_ERR_MSG_MOD(extack, "Could not add filter to the adapter"); goto err_locked; } hlist_add_head(&filter->nfc_node, &adapter->cls_flower_list); spin_unlock(&adapter->nfc_lock); return 0; err_locked: spin_unlock(&adapter->nfc_lock); err_parse: kfree(filter); return err; } static int igb_delete_clsflower(struct igb_adapter *adapter, struct flow_cls_offload *cls_flower) { struct igb_nfc_filter *filter; int err; spin_lock(&adapter->nfc_lock); hlist_for_each_entry(filter, &adapter->cls_flower_list, nfc_node) if (filter->cookie == cls_flower->cookie) break; if (!filter) { err = -ENOENT; goto out; } err = igb_erase_filter(adapter, filter); if (err < 0) goto out; hlist_del(&filter->nfc_node); kfree(filter); out: spin_unlock(&adapter->nfc_lock); return err; } static int igb_setup_tc_cls_flower(struct igb_adapter *adapter, struct flow_cls_offload *cls_flower) { switch (cls_flower->command) { case FLOW_CLS_REPLACE: return igb_configure_clsflower(adapter, cls_flower); case FLOW_CLS_DESTROY: return igb_delete_clsflower(adapter, cls_flower); case FLOW_CLS_STATS: return -EOPNOTSUPP; default: return -EOPNOTSUPP; } } static int igb_setup_tc_block_cb(enum tc_setup_type type, void *type_data, void *cb_priv) { struct igb_adapter *adapter = cb_priv; if (!tc_cls_can_offload_and_chain0(adapter->netdev, type_data)) return -EOPNOTSUPP; switch (type) { case TC_SETUP_CLSFLOWER: return igb_setup_tc_cls_flower(adapter, type_data); default: return -EOPNOTSUPP; } } static int igb_offload_txtime(struct igb_adapter *adapter, struct tc_etf_qopt_offload *qopt) { struct e1000_hw *hw = &adapter->hw; int err; /* Launchtime offloading is only supported by i210 controller. */ if (hw->mac.type != e1000_i210) return -EOPNOTSUPP; /* Launchtime offloading is only supported by queues 0 and 1. */ if (qopt->queue < 0 || qopt->queue > 1) return -EINVAL; err = igb_save_txtime_params(adapter, qopt->queue, qopt->enable); if (err) return err; igb_offload_apply(adapter, qopt->queue); return 0; } static int igb_tc_query_caps(struct igb_adapter *adapter, struct tc_query_caps_base *base) { switch (base->type) { case TC_SETUP_QDISC_TAPRIO: { struct tc_taprio_caps *caps = base->caps; caps->broken_mqprio = true; return 0; } default: return -EOPNOTSUPP; } } static LIST_HEAD(igb_block_cb_list); static int igb_setup_tc(struct net_device *dev, enum tc_setup_type type, void *type_data) { struct igb_adapter *adapter = netdev_priv(dev); switch (type) { case TC_QUERY_CAPS: return igb_tc_query_caps(adapter, type_data); case TC_SETUP_QDISC_CBS: return igb_offload_cbs(adapter, type_data); case TC_SETUP_BLOCK: return flow_block_cb_setup_simple(type_data, &igb_block_cb_list, igb_setup_tc_block_cb, adapter, adapter, true); case TC_SETUP_QDISC_ETF: return igb_offload_txtime(adapter, type_data); default: return -EOPNOTSUPP; } } static int igb_xdp_setup(struct net_device *dev, struct netdev_bpf *bpf) { int i, frame_size = dev->mtu + IGB_ETH_PKT_HDR_PAD; struct igb_adapter *adapter = netdev_priv(dev); struct bpf_prog *prog = bpf->prog, *old_prog; bool running = netif_running(dev); bool need_reset; /* verify igb ring attributes are sufficient for XDP */ for (i = 0; i < adapter->num_rx_queues; i++) { struct igb_ring *ring = adapter->rx_ring[i]; if (frame_size > igb_rx_bufsz(ring)) { NL_SET_ERR_MSG_MOD(bpf->extack, "The RX buffer size is too small for the frame size"); netdev_warn(dev, "XDP RX buffer size %d is too small for the frame size %d\n", igb_rx_bufsz(ring), frame_size); return -EINVAL; } } old_prog = xchg(&adapter->xdp_prog, prog); need_reset = (!!prog != !!old_prog); /* device is up and bpf is added/removed, must setup the RX queues */ if (need_reset && running) { igb_close(dev); } else { for (i = 0; i < adapter->num_rx_queues; i++) (void)xchg(&adapter->rx_ring[i]->xdp_prog, adapter->xdp_prog); } if (old_prog) bpf_prog_put(old_prog); /* bpf is just replaced, RXQ and MTU are already setup */ if (!need_reset) { return 0; } else { if (prog) xdp_features_set_redirect_target(dev, true); else xdp_features_clear_redirect_target(dev); } if (running) igb_open(dev); return 0; } static int igb_xdp(struct net_device *dev, struct netdev_bpf *xdp) { switch (xdp->command) { case XDP_SETUP_PROG: return igb_xdp_setup(dev, xdp); default: return -EINVAL; } } static void igb_xdp_ring_update_tail(struct igb_ring *ring) { /* Force memory writes to complete before letting h/w know there * are new descriptors to fetch. */ wmb(); writel(ring->next_to_use, ring->tail); } static struct igb_ring *igb_xdp_tx_queue_mapping(struct igb_adapter *adapter) { unsigned int r_idx = smp_processor_id(); if (r_idx >= adapter->num_tx_queues) r_idx = r_idx % adapter->num_tx_queues; return adapter->tx_ring[r_idx]; } static int igb_xdp_xmit_back(struct igb_adapter *adapter, struct xdp_buff *xdp) { struct xdp_frame *xdpf = xdp_convert_buff_to_frame(xdp); int cpu = smp_processor_id(); struct igb_ring *tx_ring; struct netdev_queue *nq; u32 ret; if (unlikely(!xdpf)) return IGB_XDP_CONSUMED; /* During program transitions its possible adapter->xdp_prog is assigned * but ring has not been configured yet. In this case simply abort xmit. */ tx_ring = adapter->xdp_prog ? igb_xdp_tx_queue_mapping(adapter) : NULL; if (unlikely(!tx_ring)) return IGB_XDP_CONSUMED; nq = txring_txq(tx_ring); __netif_tx_lock(nq, cpu); /* Avoid transmit queue timeout since we share it with the slow path */ txq_trans_cond_update(nq); ret = igb_xmit_xdp_ring(adapter, tx_ring, xdpf); __netif_tx_unlock(nq); return ret; } static int igb_xdp_xmit(struct net_device *dev, int n, struct xdp_frame **frames, u32 flags) { struct igb_adapter *adapter = netdev_priv(dev); int cpu = smp_processor_id(); struct igb_ring *tx_ring; struct netdev_queue *nq; int nxmit = 0; int i; if (unlikely(test_bit(__IGB_DOWN, &adapter->state))) return -ENETDOWN; if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK)) return -EINVAL; /* During program transitions its possible adapter->xdp_prog is assigned * but ring has not been configured yet. In this case simply abort xmit. */ tx_ring = adapter->xdp_prog ? igb_xdp_tx_queue_mapping(adapter) : NULL; if (unlikely(!tx_ring)) return -ENXIO; nq = txring_txq(tx_ring); __netif_tx_lock(nq, cpu); /* Avoid transmit queue timeout since we share it with the slow path */ txq_trans_cond_update(nq); for (i = 0; i < n; i++) { struct xdp_frame *xdpf = frames[i]; int err; err = igb_xmit_xdp_ring(adapter, tx_ring, xdpf); if (err != IGB_XDP_TX) break; nxmit++; } __netif_tx_unlock(nq); if (unlikely(flags & XDP_XMIT_FLUSH)) igb_xdp_ring_update_tail(tx_ring); return nxmit; } static const struct net_device_ops igb_netdev_ops = { .ndo_open = igb_open, .ndo_stop = igb_close, .ndo_start_xmit = igb_xmit_frame, .ndo_get_stats64 = igb_get_stats64, .ndo_set_rx_mode = igb_set_rx_mode, .ndo_set_mac_address = igb_set_mac, .ndo_change_mtu = igb_change_mtu, .ndo_eth_ioctl = igb_ioctl, .ndo_tx_timeout = igb_tx_timeout, .ndo_validate_addr = eth_validate_addr, .ndo_vlan_rx_add_vid = igb_vlan_rx_add_vid, .ndo_vlan_rx_kill_vid = igb_vlan_rx_kill_vid, .ndo_set_vf_mac = igb_ndo_set_vf_mac, .ndo_set_vf_vlan = igb_ndo_set_vf_vlan, .ndo_set_vf_rate = igb_ndo_set_vf_bw, .ndo_set_vf_spoofchk = igb_ndo_set_vf_spoofchk, .ndo_set_vf_trust = igb_ndo_set_vf_trust, .ndo_get_vf_config = igb_ndo_get_vf_config, .ndo_fix_features = igb_fix_features, .ndo_set_features = igb_set_features, .ndo_fdb_add = igb_ndo_fdb_add, .ndo_features_check = igb_features_check, .ndo_setup_tc = igb_setup_tc, .ndo_bpf = igb_xdp, .ndo_xdp_xmit = igb_xdp_xmit, }; /** * igb_set_fw_version - Configure version string for ethtool * @adapter: adapter struct **/ void igb_set_fw_version(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; struct e1000_fw_version fw; igb_get_fw_version(hw, &fw); switch (hw->mac.type) { case e1000_i210: case e1000_i211: if (!(igb_get_flash_presence_i210(hw))) { snprintf(adapter->fw_version, sizeof(adapter->fw_version), "%2d.%2d-%d", fw.invm_major, fw.invm_minor, fw.invm_img_type); break; } fallthrough; default: /* if option is rom valid, display its version too */ if (fw.or_valid) { snprintf(adapter->fw_version, sizeof(adapter->fw_version), "%d.%d, 0x%08x, %d.%d.%d", fw.eep_major, fw.eep_minor, fw.etrack_id, fw.or_major, fw.or_build, fw.or_patch); /* no option rom */ } else if (fw.etrack_id != 0X0000) { snprintf(adapter->fw_version, sizeof(adapter->fw_version), "%d.%d, 0x%08x", fw.eep_major, fw.eep_minor, fw.etrack_id); } else { snprintf(adapter->fw_version, sizeof(adapter->fw_version), "%d.%d.%d", fw.eep_major, fw.eep_minor, fw.eep_build); } break; } } /** * igb_init_mas - init Media Autosense feature if enabled in the NVM * * @adapter: adapter struct **/ static void igb_init_mas(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u16 eeprom_data; hw->nvm.ops.read(hw, NVM_COMPAT, 1, &eeprom_data); switch (hw->bus.func) { case E1000_FUNC_0: if (eeprom_data & IGB_MAS_ENABLE_0) { adapter->flags |= IGB_FLAG_MAS_ENABLE; netdev_info(adapter->netdev, "MAS: Enabling Media Autosense for port %d\n", hw->bus.func); } break; case E1000_FUNC_1: if (eeprom_data & IGB_MAS_ENABLE_1) { adapter->flags |= IGB_FLAG_MAS_ENABLE; netdev_info(adapter->netdev, "MAS: Enabling Media Autosense for port %d\n", hw->bus.func); } break; case E1000_FUNC_2: if (eeprom_data & IGB_MAS_ENABLE_2) { adapter->flags |= IGB_FLAG_MAS_ENABLE; netdev_info(adapter->netdev, "MAS: Enabling Media Autosense for port %d\n", hw->bus.func); } break; case E1000_FUNC_3: if (eeprom_data & IGB_MAS_ENABLE_3) { adapter->flags |= IGB_FLAG_MAS_ENABLE; netdev_info(adapter->netdev, "MAS: Enabling Media Autosense for port %d\n", hw->bus.func); } break; default: /* Shouldn't get here */ netdev_err(adapter->netdev, "MAS: Invalid port configuration, returning\n"); break; } } /** * igb_init_i2c - Init I2C interface * @adapter: pointer to adapter structure **/ static s32 igb_init_i2c(struct igb_adapter *adapter) { s32 status = 0; /* I2C interface supported on i350 devices */ if (adapter->hw.mac.type != e1000_i350) return 0; /* Initialize the i2c bus which is controlled by the registers. * This bus will use the i2c_algo_bit structure that implements * the protocol through toggling of the 4 bits in the register. */ adapter->i2c_adap.owner = THIS_MODULE; adapter->i2c_algo = igb_i2c_algo; adapter->i2c_algo.data = adapter; adapter->i2c_adap.algo_data = &adapter->i2c_algo; adapter->i2c_adap.dev.parent = &adapter->pdev->dev; strscpy(adapter->i2c_adap.name, "igb BB", sizeof(adapter->i2c_adap.name)); status = i2c_bit_add_bus(&adapter->i2c_adap); return status; } /** * igb_probe - Device Initialization Routine * @pdev: PCI device information struct * @ent: entry in igb_pci_tbl * * Returns 0 on success, negative on failure * * igb_probe initializes an adapter identified by a pci_dev structure. * The OS initialization, configuring of the adapter private structure, * and a hardware reset occur. **/ static int igb_probe(struct pci_dev *pdev, const struct pci_device_id *ent) { struct net_device *netdev; struct igb_adapter *adapter; struct e1000_hw *hw; u16 eeprom_data = 0; s32 ret_val; static int global_quad_port_a; /* global quad port a indication */ const struct e1000_info *ei = igb_info_tbl[ent->driver_data]; u8 part_str[E1000_PBANUM_LENGTH]; int err; /* Catch broken hardware that put the wrong VF device ID in * the PCIe SR-IOV capability. */ if (pdev->is_virtfn) { WARN(1, KERN_ERR "%s (%x:%x) should not be a VF!\n", pci_name(pdev), pdev->vendor, pdev->device); return -EINVAL; } err = pci_enable_device_mem(pdev); if (err) return err; err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64)); if (err) { dev_err(&pdev->dev, "No usable DMA configuration, aborting\n"); goto err_dma; } err = pci_request_mem_regions(pdev, igb_driver_name); if (err) goto err_pci_reg; pci_set_master(pdev); pci_save_state(pdev); err = -ENOMEM; netdev = alloc_etherdev_mq(sizeof(struct igb_adapter), IGB_MAX_TX_QUEUES); if (!netdev) goto err_alloc_etherdev; SET_NETDEV_DEV(netdev, &pdev->dev); pci_set_drvdata(pdev, netdev); adapter = netdev_priv(netdev); adapter->netdev = netdev; adapter->pdev = pdev; hw = &adapter->hw; hw->back = adapter; adapter->msg_enable = netif_msg_init(debug, DEFAULT_MSG_ENABLE); err = -EIO; adapter->io_addr = pci_iomap(pdev, 0, 0); if (!adapter->io_addr) goto err_ioremap; /* hw->hw_addr can be altered, we'll use adapter->io_addr for unmap */ hw->hw_addr = adapter->io_addr; netdev->netdev_ops = &igb_netdev_ops; igb_set_ethtool_ops(netdev); netdev->watchdog_timeo = 5 * HZ; strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1); netdev->mem_start = pci_resource_start(pdev, 0); netdev->mem_end = pci_resource_end(pdev, 0); /* PCI config space info */ hw->vendor_id = pdev->vendor; hw->device_id = pdev->device; hw->revision_id = pdev->revision; hw->subsystem_vendor_id = pdev->subsystem_vendor; hw->subsystem_device_id = pdev->subsystem_device; /* Copy the default MAC, PHY and NVM function pointers */ memcpy(&hw->mac.ops, ei->mac_ops, sizeof(hw->mac.ops)); memcpy(&hw->phy.ops, ei->phy_ops, sizeof(hw->phy.ops)); memcpy(&hw->nvm.ops, ei->nvm_ops, sizeof(hw->nvm.ops)); /* Initialize skew-specific constants */ err = ei->get_invariants(hw); if (err) goto err_sw_init; /* setup the private structure */ err = igb_sw_init(adapter); if (err) goto err_sw_init; igb_get_bus_info_pcie(hw); hw->phy.autoneg_wait_to_complete = false; /* Copper options */ if (hw->phy.media_type == e1000_media_type_copper) { hw->phy.mdix = AUTO_ALL_MODES; hw->phy.disable_polarity_correction = false; hw->phy.ms_type = e1000_ms_hw_default; } if (igb_check_reset_block(hw)) dev_info(&pdev->dev, "PHY reset is blocked due to SOL/IDER session.\n"); /* features is initialized to 0 in allocation, it might have bits * set by igb_sw_init so we should use an or instead of an * assignment. */ netdev->features |= NETIF_F_SG | NETIF_F_TSO | NETIF_F_TSO6 | NETIF_F_RXHASH | NETIF_F_RXCSUM | NETIF_F_HW_CSUM; if (hw->mac.type >= e1000_82576) netdev->features |= NETIF_F_SCTP_CRC | NETIF_F_GSO_UDP_L4; if (hw->mac.type >= e1000_i350) netdev->features |= NETIF_F_HW_TC; #define IGB_GSO_PARTIAL_FEATURES (NETIF_F_GSO_GRE | \ NETIF_F_GSO_GRE_CSUM | \ NETIF_F_GSO_IPXIP4 | \ NETIF_F_GSO_IPXIP6 | \ NETIF_F_GSO_UDP_TUNNEL | \ NETIF_F_GSO_UDP_TUNNEL_CSUM) netdev->gso_partial_features = IGB_GSO_PARTIAL_FEATURES; netdev->features |= NETIF_F_GSO_PARTIAL | IGB_GSO_PARTIAL_FEATURES; /* copy netdev features into list of user selectable features */ netdev->hw_features |= netdev->features | NETIF_F_HW_VLAN_CTAG_RX | NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_RXALL; if (hw->mac.type >= e1000_i350) netdev->hw_features |= NETIF_F_NTUPLE; netdev->features |= NETIF_F_HIGHDMA; netdev->vlan_features |= netdev->features | NETIF_F_TSO_MANGLEID; netdev->mpls_features |= NETIF_F_HW_CSUM; netdev->hw_enc_features |= netdev->vlan_features; /* set this bit last since it cannot be part of vlan_features */ netdev->features |= NETIF_F_HW_VLAN_CTAG_FILTER | NETIF_F_HW_VLAN_CTAG_RX | NETIF_F_HW_VLAN_CTAG_TX; netdev->priv_flags |= IFF_SUPP_NOFCS; netdev->priv_flags |= IFF_UNICAST_FLT; netdev->xdp_features = NETDEV_XDP_ACT_BASIC | NETDEV_XDP_ACT_REDIRECT; /* MTU range: 68 - 9216 */ netdev->min_mtu = ETH_MIN_MTU; netdev->max_mtu = MAX_STD_JUMBO_FRAME_SIZE; adapter->en_mng_pt = igb_enable_mng_pass_thru(hw); /* before reading the NVM, reset the controller to put the device in a * known good starting state */ hw->mac.ops.reset_hw(hw); /* make sure the NVM is good , i211/i210 parts can have special NVM * that doesn't contain a checksum */ switch (hw->mac.type) { case e1000_i210: case e1000_i211: if (igb_get_flash_presence_i210(hw)) { if (hw->nvm.ops.validate(hw) < 0) { dev_err(&pdev->dev, "The NVM Checksum Is Not Valid\n"); err = -EIO; goto err_eeprom; } } break; default: if (hw->nvm.ops.validate(hw) < 0) { dev_err(&pdev->dev, "The NVM Checksum Is Not Valid\n"); err = -EIO; goto err_eeprom; } break; } if (eth_platform_get_mac_address(&pdev->dev, hw->mac.addr)) { /* copy the MAC address out of the NVM */ if (hw->mac.ops.read_mac_addr(hw)) dev_err(&pdev->dev, "NVM Read Error\n"); } eth_hw_addr_set(netdev, hw->mac.addr); if (!is_valid_ether_addr(netdev->dev_addr)) { dev_err(&pdev->dev, "Invalid MAC Address\n"); err = -EIO; goto err_eeprom; } igb_set_default_mac_filter(adapter); /* get firmware version for ethtool -i */ igb_set_fw_version(adapter); /* configure RXPBSIZE and TXPBSIZE */ if (hw->mac.type == e1000_i210) { wr32(E1000_RXPBS, I210_RXPBSIZE_DEFAULT); wr32(E1000_TXPBS, I210_TXPBSIZE_DEFAULT); } timer_setup(&adapter->watchdog_timer, igb_watchdog, 0); timer_setup(&adapter->phy_info_timer, igb_update_phy_info, 0); INIT_WORK(&adapter->reset_task, igb_reset_task); INIT_WORK(&adapter->watchdog_task, igb_watchdog_task); /* Initialize link properties that are user-changeable */ adapter->fc_autoneg = true; hw->mac.autoneg = true; hw->phy.autoneg_advertised = 0x2f; hw->fc.requested_mode = e1000_fc_default; hw->fc.current_mode = e1000_fc_default; igb_validate_mdi_setting(hw); /* By default, support wake on port A */ if (hw->bus.func == 0) adapter->flags |= IGB_FLAG_WOL_SUPPORTED; /* Check the NVM for wake support on non-port A ports */ if (hw->mac.type >= e1000_82580) hw->nvm.ops.read(hw, NVM_INIT_CONTROL3_PORT_A + NVM_82580_LAN_FUNC_OFFSET(hw->bus.func), 1, &eeprom_data); else if (hw->bus.func == 1) hw->nvm.ops.read(hw, NVM_INIT_CONTROL3_PORT_B, 1, &eeprom_data); if (eeprom_data & IGB_EEPROM_APME) adapter->flags |= IGB_FLAG_WOL_SUPPORTED; /* now that we have the eeprom settings, apply the special cases where * the eeprom may be wrong or the board simply won't support wake on * lan on a particular port */ switch (pdev->device) { case E1000_DEV_ID_82575GB_QUAD_COPPER: adapter->flags &= ~IGB_FLAG_WOL_SUPPORTED; break; case E1000_DEV_ID_82575EB_FIBER_SERDES: case E1000_DEV_ID_82576_FIBER: case E1000_DEV_ID_82576_SERDES: /* Wake events only supported on port A for dual fiber * regardless of eeprom setting */ if (rd32(E1000_STATUS) & E1000_STATUS_FUNC_1) adapter->flags &= ~IGB_FLAG_WOL_SUPPORTED; break; case E1000_DEV_ID_82576_QUAD_COPPER: case E1000_DEV_ID_82576_QUAD_COPPER_ET2: /* if quad port adapter, disable WoL on all but port A */ if (global_quad_port_a != 0) adapter->flags &= ~IGB_FLAG_WOL_SUPPORTED; else adapter->flags |= IGB_FLAG_QUAD_PORT_A; /* Reset for multiple quad port adapters */ if (++global_quad_port_a == 4) global_quad_port_a = 0; break; default: /* If the device can't wake, don't set software support */ if (!device_can_wakeup(&adapter->pdev->dev)) adapter->flags &= ~IGB_FLAG_WOL_SUPPORTED; } /* initialize the wol settings based on the eeprom settings */ if (adapter->flags & IGB_FLAG_WOL_SUPPORTED) adapter->wol |= E1000_WUFC_MAG; /* Some vendors want WoL disabled by default, but still supported */ if ((hw->mac.type == e1000_i350) && (pdev->subsystem_vendor == PCI_VENDOR_ID_HP)) { adapter->flags |= IGB_FLAG_WOL_SUPPORTED; adapter->wol = 0; } /* Some vendors want the ability to Use the EEPROM setting as * enable/disable only, and not for capability */ if (((hw->mac.type == e1000_i350) || (hw->mac.type == e1000_i354)) && (pdev->subsystem_vendor == PCI_VENDOR_ID_DELL)) { adapter->flags |= IGB_FLAG_WOL_SUPPORTED; adapter->wol = 0; } if (hw->mac.type == e1000_i350) { if (((pdev->subsystem_device == 0x5001) || (pdev->subsystem_device == 0x5002)) && (hw->bus.func == 0)) { adapter->flags |= IGB_FLAG_WOL_SUPPORTED; adapter->wol = 0; } if (pdev->subsystem_device == 0x1F52) adapter->flags |= IGB_FLAG_WOL_SUPPORTED; } device_set_wakeup_enable(&adapter->pdev->dev, adapter->flags & IGB_FLAG_WOL_SUPPORTED); /* reset the hardware with the new settings */ igb_reset(adapter); /* Init the I2C interface */ err = igb_init_i2c(adapter); if (err) { dev_err(&pdev->dev, "failed to init i2c interface\n"); goto err_eeprom; } /* let the f/w know that the h/w is now under the control of the * driver. */ igb_get_hw_control(adapter); strcpy(netdev->name, "eth%d"); err = register_netdev(netdev); if (err) goto err_register; /* carrier off reporting is important to ethtool even BEFORE open */ netif_carrier_off(netdev); #ifdef CONFIG_IGB_DCA if (dca_add_requester(&pdev->dev) == 0) { adapter->flags |= IGB_FLAG_DCA_ENABLED; dev_info(&pdev->dev, "DCA enabled\n"); igb_setup_dca(adapter); } #endif #ifdef CONFIG_IGB_HWMON /* Initialize the thermal sensor on i350 devices. */ if (hw->mac.type == e1000_i350 && hw->bus.func == 0) { u16 ets_word; /* Read the NVM to determine if this i350 device supports an * external thermal sensor. */ hw->nvm.ops.read(hw, NVM_ETS_CFG, 1, &ets_word); if (ets_word != 0x0000 && ets_word != 0xFFFF) adapter->ets = true; else adapter->ets = false; /* Only enable I2C bit banging if an external thermal * sensor is supported. */ if (adapter->ets) igb_set_i2c_bb(hw); hw->mac.ops.init_thermal_sensor_thresh(hw); if (igb_sysfs_init(adapter)) dev_err(&pdev->dev, "failed to allocate sysfs resources\n"); } else { adapter->ets = false; } #endif /* Check if Media Autosense is enabled */ adapter->ei = *ei; if (hw->dev_spec._82575.mas_capable) igb_init_mas(adapter); /* do hw tstamp init after resetting */ igb_ptp_init(adapter); dev_info(&pdev->dev, "Intel(R) Gigabit Ethernet Network Connection\n"); /* print bus type/speed/width info, not applicable to i354 */ if (hw->mac.type != e1000_i354) { dev_info(&pdev->dev, "%s: (PCIe:%s:%s) %pM\n", netdev->name, ((hw->bus.speed == e1000_bus_speed_2500) ? "2.5Gb/s" : (hw->bus.speed == e1000_bus_speed_5000) ? "5.0Gb/s" : "unknown"), ((hw->bus.width == e1000_bus_width_pcie_x4) ? "Width x4" : (hw->bus.width == e1000_bus_width_pcie_x2) ? "Width x2" : (hw->bus.width == e1000_bus_width_pcie_x1) ? "Width x1" : "unknown"), netdev->dev_addr); } if ((hw->mac.type == e1000_82576 && rd32(E1000_EECD) & E1000_EECD_PRES) || (hw->mac.type >= e1000_i210 || igb_get_flash_presence_i210(hw))) { ret_val = igb_read_part_string(hw, part_str, E1000_PBANUM_LENGTH); } else { ret_val = -E1000_ERR_INVM_VALUE_NOT_FOUND; } if (ret_val) strcpy(part_str, "Unknown"); dev_info(&pdev->dev, "%s: PBA No: %s\n", netdev->name, part_str); dev_info(&pdev->dev, "Using %s interrupts. %d rx queue(s), %d tx queue(s)\n", (adapter->flags & IGB_FLAG_HAS_MSIX) ? "MSI-X" : (adapter->flags & IGB_FLAG_HAS_MSI) ? "MSI" : "legacy", adapter->num_rx_queues, adapter->num_tx_queues); if (hw->phy.media_type == e1000_media_type_copper) { switch (hw->mac.type) { case e1000_i350: case e1000_i210: case e1000_i211: /* Enable EEE for internal copper PHY devices */ err = igb_set_eee_i350(hw, true, true); if ((!err) && (!hw->dev_spec._82575.eee_disable)) { adapter->eee_advert = MDIO_EEE_100TX | MDIO_EEE_1000T; adapter->flags |= IGB_FLAG_EEE; } break; case e1000_i354: if ((rd32(E1000_CTRL_EXT) & E1000_CTRL_EXT_LINK_MODE_SGMII)) { err = igb_set_eee_i354(hw, true, true); if ((!err) && (!hw->dev_spec._82575.eee_disable)) { adapter->eee_advert = MDIO_EEE_100TX | MDIO_EEE_1000T; adapter->flags |= IGB_FLAG_EEE; } } break; default: break; } } dev_pm_set_driver_flags(&pdev->dev, DPM_FLAG_NO_DIRECT_COMPLETE); pm_runtime_put_noidle(&pdev->dev); return 0; err_register: igb_release_hw_control(adapter); memset(&adapter->i2c_adap, 0, sizeof(adapter->i2c_adap)); err_eeprom: if (!igb_check_reset_block(hw)) igb_reset_phy(hw); if (hw->flash_address) iounmap(hw->flash_address); err_sw_init: kfree(adapter->mac_table); kfree(adapter->shadow_vfta); igb_clear_interrupt_scheme(adapter); #ifdef CONFIG_PCI_IOV igb_disable_sriov(pdev, false); #endif pci_iounmap(pdev, adapter->io_addr); err_ioremap: free_netdev(netdev); err_alloc_etherdev: pci_release_mem_regions(pdev); err_pci_reg: err_dma: pci_disable_device(pdev); return err; } #ifdef CONFIG_PCI_IOV static int igb_sriov_reinit(struct pci_dev *dev) { struct net_device *netdev = pci_get_drvdata(dev); struct igb_adapter *adapter = netdev_priv(netdev); struct pci_dev *pdev = adapter->pdev; rtnl_lock(); if (netif_running(netdev)) igb_close(netdev); else igb_reset(adapter); igb_clear_interrupt_scheme(adapter); igb_init_queue_configuration(adapter); if (igb_init_interrupt_scheme(adapter, true)) { rtnl_unlock(); dev_err(&pdev->dev, "Unable to allocate memory for queues\n"); return -ENOMEM; } if (netif_running(netdev)) igb_open(netdev); rtnl_unlock(); return 0; } static int igb_disable_sriov(struct pci_dev *pdev, bool reinit) { struct net_device *netdev = pci_get_drvdata(pdev); struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; unsigned long flags; /* reclaim resources allocated to VFs */ if (adapter->vf_data) { /* disable iov and allow time for transactions to clear */ if (pci_vfs_assigned(pdev)) { dev_warn(&pdev->dev, "Cannot deallocate SR-IOV virtual functions while they are assigned - VFs will not be deallocated\n"); return -EPERM; } else { pci_disable_sriov(pdev); msleep(500); } spin_lock_irqsave(&adapter->vfs_lock, flags); kfree(adapter->vf_mac_list); adapter->vf_mac_list = NULL; kfree(adapter->vf_data); adapter->vf_data = NULL; adapter->vfs_allocated_count = 0; spin_unlock_irqrestore(&adapter->vfs_lock, flags); wr32(E1000_IOVCTL, E1000_IOVCTL_REUSE_VFQ); wrfl(); msleep(100); dev_info(&pdev->dev, "IOV Disabled\n"); /* Re-enable DMA Coalescing flag since IOV is turned off */ adapter->flags |= IGB_FLAG_DMAC; } return reinit ? igb_sriov_reinit(pdev) : 0; } static int igb_enable_sriov(struct pci_dev *pdev, int num_vfs, bool reinit) { struct net_device *netdev = pci_get_drvdata(pdev); struct igb_adapter *adapter = netdev_priv(netdev); int old_vfs = pci_num_vf(pdev); struct vf_mac_filter *mac_list; int err = 0; int num_vf_mac_filters, i; if (!(adapter->flags & IGB_FLAG_HAS_MSIX) || num_vfs > 7) { err = -EPERM; goto out; } if (!num_vfs) goto out; if (old_vfs) { dev_info(&pdev->dev, "%d pre-allocated VFs found - override max_vfs setting of %d\n", old_vfs, max_vfs); adapter->vfs_allocated_count = old_vfs; } else adapter->vfs_allocated_count = num_vfs; adapter->vf_data = kcalloc(adapter->vfs_allocated_count, sizeof(struct vf_data_storage), GFP_KERNEL); /* if allocation failed then we do not support SR-IOV */ if (!adapter->vf_data) { adapter->vfs_allocated_count = 0; err = -ENOMEM; goto out; } /* Due to the limited number of RAR entries calculate potential * number of MAC filters available for the VFs. Reserve entries * for PF default MAC, PF MAC filters and at least one RAR entry * for each VF for VF MAC. */ num_vf_mac_filters = adapter->hw.mac.rar_entry_count - (1 + IGB_PF_MAC_FILTERS_RESERVED + adapter->vfs_allocated_count); adapter->vf_mac_list = kcalloc(num_vf_mac_filters, sizeof(struct vf_mac_filter), GFP_KERNEL); mac_list = adapter->vf_mac_list; INIT_LIST_HEAD(&adapter->vf_macs.l); if (adapter->vf_mac_list) { /* Initialize list of VF MAC filters */ for (i = 0; i < num_vf_mac_filters; i++) { mac_list->vf = -1; mac_list->free = true; list_add(&mac_list->l, &adapter->vf_macs.l); mac_list++; } } else { /* If we could not allocate memory for the VF MAC filters * we can continue without this feature but warn user. */ dev_err(&pdev->dev, "Unable to allocate memory for VF MAC filter list\n"); } dev_info(&pdev->dev, "%d VFs allocated\n", adapter->vfs_allocated_count); for (i = 0; i < adapter->vfs_allocated_count; i++) igb_vf_configure(adapter, i); /* DMA Coalescing is not supported in IOV mode. */ adapter->flags &= ~IGB_FLAG_DMAC; if (reinit) { err = igb_sriov_reinit(pdev); if (err) goto err_out; } /* only call pci_enable_sriov() if no VFs are allocated already */ if (!old_vfs) { err = pci_enable_sriov(pdev, adapter->vfs_allocated_count); if (err) goto err_out; } goto out; err_out: kfree(adapter->vf_mac_list); adapter->vf_mac_list = NULL; kfree(adapter->vf_data); adapter->vf_data = NULL; adapter->vfs_allocated_count = 0; out: return err; } #endif /** * igb_remove_i2c - Cleanup I2C interface * @adapter: pointer to adapter structure **/ static void igb_remove_i2c(struct igb_adapter *adapter) { /* free the adapter bus structure */ i2c_del_adapter(&adapter->i2c_adap); } /** * igb_remove - Device Removal Routine * @pdev: PCI device information struct * * igb_remove is called by the PCI subsystem to alert the driver * that it should release a PCI device. The could be caused by a * Hot-Plug event, or because the driver is going to be removed from * memory. **/ static void igb_remove(struct pci_dev *pdev) { struct net_device *netdev = pci_get_drvdata(pdev); struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; pm_runtime_get_noresume(&pdev->dev); #ifdef CONFIG_IGB_HWMON igb_sysfs_exit(adapter); #endif igb_remove_i2c(adapter); igb_ptp_stop(adapter); /* The watchdog timer may be rescheduled, so explicitly * disable watchdog from being rescheduled. */ set_bit(__IGB_DOWN, &adapter->state); del_timer_sync(&adapter->watchdog_timer); del_timer_sync(&adapter->phy_info_timer); cancel_work_sync(&adapter->reset_task); cancel_work_sync(&adapter->watchdog_task); #ifdef CONFIG_IGB_DCA if (adapter->flags & IGB_FLAG_DCA_ENABLED) { dev_info(&pdev->dev, "DCA disabled\n"); dca_remove_requester(&pdev->dev); adapter->flags &= ~IGB_FLAG_DCA_ENABLED; wr32(E1000_DCA_CTRL, E1000_DCA_CTRL_DCA_MODE_DISABLE); } #endif /* Release control of h/w to f/w. If f/w is AMT enabled, this * would have already happened in close and is redundant. */ igb_release_hw_control(adapter); #ifdef CONFIG_PCI_IOV igb_disable_sriov(pdev, false); #endif unregister_netdev(netdev); igb_clear_interrupt_scheme(adapter); pci_iounmap(pdev, adapter->io_addr); if (hw->flash_address) iounmap(hw->flash_address); pci_release_mem_regions(pdev); kfree(adapter->mac_table); kfree(adapter->shadow_vfta); free_netdev(netdev); pci_disable_device(pdev); } /** * igb_probe_vfs - Initialize vf data storage and add VFs to pci config space * @adapter: board private structure to initialize * * This function initializes the vf specific data storage and then attempts to * allocate the VFs. The reason for ordering it this way is because it is much * mor expensive time wise to disable SR-IOV than it is to allocate and free * the memory for the VFs. **/ static void igb_probe_vfs(struct igb_adapter *adapter) { #ifdef CONFIG_PCI_IOV struct pci_dev *pdev = adapter->pdev; struct e1000_hw *hw = &adapter->hw; /* Virtualization features not supported on i210 and 82580 family. */ if ((hw->mac.type == e1000_i210) || (hw->mac.type == e1000_i211) || (hw->mac.type == e1000_82580)) return; /* Of the below we really only want the effect of getting * IGB_FLAG_HAS_MSIX set (if available), without which * igb_enable_sriov() has no effect. */ igb_set_interrupt_capability(adapter, true); igb_reset_interrupt_capability(adapter); pci_sriov_set_totalvfs(pdev, 7); igb_enable_sriov(pdev, max_vfs, false); #endif /* CONFIG_PCI_IOV */ } unsigned int igb_get_max_rss_queues(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; unsigned int max_rss_queues; /* Determine the maximum number of RSS queues supported. */ switch (hw->mac.type) { case e1000_i211: max_rss_queues = IGB_MAX_RX_QUEUES_I211; break; case e1000_82575: case e1000_i210: max_rss_queues = IGB_MAX_RX_QUEUES_82575; break; case e1000_i350: /* I350 cannot do RSS and SR-IOV at the same time */ if (!!adapter->vfs_allocated_count) { max_rss_queues = 1; break; } fallthrough; case e1000_82576: if (!!adapter->vfs_allocated_count) { max_rss_queues = 2; break; } fallthrough; case e1000_82580: case e1000_i354: default: max_rss_queues = IGB_MAX_RX_QUEUES; break; } return max_rss_queues; } static void igb_init_queue_configuration(struct igb_adapter *adapter) { u32 max_rss_queues; max_rss_queues = igb_get_max_rss_queues(adapter); adapter->rss_queues = min_t(u32, max_rss_queues, num_online_cpus()); igb_set_flag_queue_pairs(adapter, max_rss_queues); } void igb_set_flag_queue_pairs(struct igb_adapter *adapter, const u32 max_rss_queues) { struct e1000_hw *hw = &adapter->hw; /* Determine if we need to pair queues. */ switch (hw->mac.type) { case e1000_82575: case e1000_i211: /* Device supports enough interrupts without queue pairing. */ break; case e1000_82576: case e1000_82580: case e1000_i350: case e1000_i354: case e1000_i210: default: /* If rss_queues > half of max_rss_queues, pair the queues in * order to conserve interrupts due to limited supply. */ if (adapter->rss_queues > (max_rss_queues / 2)) adapter->flags |= IGB_FLAG_QUEUE_PAIRS; else adapter->flags &= ~IGB_FLAG_QUEUE_PAIRS; break; } } /** * igb_sw_init - Initialize general software structures (struct igb_adapter) * @adapter: board private structure to initialize * * igb_sw_init initializes the Adapter private data structure. * Fields are initialized based on PCI device information and * OS network device settings (MTU size). **/ static int igb_sw_init(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; struct net_device *netdev = adapter->netdev; struct pci_dev *pdev = adapter->pdev; pci_read_config_word(pdev, PCI_COMMAND, &hw->bus.pci_cmd_word); /* set default ring sizes */ adapter->tx_ring_count = IGB_DEFAULT_TXD; adapter->rx_ring_count = IGB_DEFAULT_RXD; /* set default ITR values */ adapter->rx_itr_setting = IGB_DEFAULT_ITR; adapter->tx_itr_setting = IGB_DEFAULT_ITR; /* set default work limits */ adapter->tx_work_limit = IGB_DEFAULT_TX_WORK; adapter->max_frame_size = netdev->mtu + IGB_ETH_PKT_HDR_PAD; adapter->min_frame_size = ETH_ZLEN + ETH_FCS_LEN; spin_lock_init(&adapter->nfc_lock); spin_lock_init(&adapter->stats64_lock); /* init spinlock to avoid concurrency of VF resources */ spin_lock_init(&adapter->vfs_lock); #ifdef CONFIG_PCI_IOV switch (hw->mac.type) { case e1000_82576: case e1000_i350: if (max_vfs > 7) { dev_warn(&pdev->dev, "Maximum of 7 VFs per PF, using max\n"); max_vfs = adapter->vfs_allocated_count = 7; } else adapter->vfs_allocated_count = max_vfs; if (adapter->vfs_allocated_count) dev_warn(&pdev->dev, "Enabling SR-IOV VFs using the module parameter is deprecated - please use the pci sysfs interface.\n"); break; default: break; } #endif /* CONFIG_PCI_IOV */ /* Assume MSI-X interrupts, will be checked during IRQ allocation */ adapter->flags |= IGB_FLAG_HAS_MSIX; adapter->mac_table = kcalloc(hw->mac.rar_entry_count, sizeof(struct igb_mac_addr), GFP_KERNEL); if (!adapter->mac_table) return -ENOMEM; igb_probe_vfs(adapter); igb_init_queue_configuration(adapter); /* Setup and initialize a copy of the hw vlan table array */ adapter->shadow_vfta = kcalloc(E1000_VLAN_FILTER_TBL_SIZE, sizeof(u32), GFP_KERNEL); if (!adapter->shadow_vfta) return -ENOMEM; /* This call may decrease the number of queues */ if (igb_init_interrupt_scheme(adapter, true)) { dev_err(&pdev->dev, "Unable to allocate memory for queues\n"); return -ENOMEM; } /* Explicitly disable IRQ since the NIC can be in any state. */ igb_irq_disable(adapter); if (hw->mac.type >= e1000_i350) adapter->flags &= ~IGB_FLAG_DMAC; set_bit(__IGB_DOWN, &adapter->state); return 0; } /** * __igb_open - Called when a network interface is made active * @netdev: network interface device structure * @resuming: indicates whether we are in a resume call * * Returns 0 on success, negative value on failure * * The open entry point is called when a network interface is made * active by the system (IFF_UP). At this point all resources needed * for transmit and receive operations are allocated, the interrupt * handler is registered with the OS, the watchdog timer is started, * and the stack is notified that the interface is ready. **/ static int __igb_open(struct net_device *netdev, bool resuming) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; struct pci_dev *pdev = adapter->pdev; int err; int i; /* disallow open during test */ if (test_bit(__IGB_TESTING, &adapter->state)) { WARN_ON(resuming); return -EBUSY; } if (!resuming) pm_runtime_get_sync(&pdev->dev); netif_carrier_off(netdev); /* allocate transmit descriptors */ err = igb_setup_all_tx_resources(adapter); if (err) goto err_setup_tx; /* allocate receive descriptors */ err = igb_setup_all_rx_resources(adapter); if (err) goto err_setup_rx; igb_power_up_link(adapter); /* before we allocate an interrupt, we must be ready to handle it. * Setting DEBUG_SHIRQ in the kernel makes it fire an interrupt * as soon as we call pci_request_irq, so we have to setup our * clean_rx handler before we do so. */ igb_configure(adapter); err = igb_request_irq(adapter); if (err) goto err_req_irq; /* Notify the stack of the actual queue counts. */ err = netif_set_real_num_tx_queues(adapter->netdev, adapter->num_tx_queues); if (err) goto err_set_queues; err = netif_set_real_num_rx_queues(adapter->netdev, adapter->num_rx_queues); if (err) goto err_set_queues; /* From here on the code is the same as igb_up() */ clear_bit(__IGB_DOWN, &adapter->state); for (i = 0; i < adapter->num_q_vectors; i++) napi_enable(&(adapter->q_vector[i]->napi)); /* Clear any pending interrupts. */ rd32(E1000_TSICR); rd32(E1000_ICR); igb_irq_enable(adapter); /* notify VFs that reset has been completed */ if (adapter->vfs_allocated_count) { u32 reg_data = rd32(E1000_CTRL_EXT); reg_data |= E1000_CTRL_EXT_PFRSTD; wr32(E1000_CTRL_EXT, reg_data); } netif_tx_start_all_queues(netdev); if (!resuming) pm_runtime_put(&pdev->dev); /* start the watchdog. */ hw->mac.get_link_status = 1; schedule_work(&adapter->watchdog_task); return 0; err_set_queues: igb_free_irq(adapter); err_req_irq: igb_release_hw_control(adapter); igb_power_down_link(adapter); igb_free_all_rx_resources(adapter); err_setup_rx: igb_free_all_tx_resources(adapter); err_setup_tx: igb_reset(adapter); if (!resuming) pm_runtime_put(&pdev->dev); return err; } int igb_open(struct net_device *netdev) { return __igb_open(netdev, false); } /** * __igb_close - Disables a network interface * @netdev: network interface device structure * @suspending: indicates we are in a suspend call * * Returns 0, this is not allowed to fail * * The close entry point is called when an interface is de-activated * by the OS. The hardware is still under the driver's control, but * needs to be disabled. A global MAC reset is issued to stop the * hardware, and all transmit and receive resources are freed. **/ static int __igb_close(struct net_device *netdev, bool suspending) { struct igb_adapter *adapter = netdev_priv(netdev); struct pci_dev *pdev = adapter->pdev; WARN_ON(test_bit(__IGB_RESETTING, &adapter->state)); if (!suspending) pm_runtime_get_sync(&pdev->dev); igb_down(adapter); igb_free_irq(adapter); igb_free_all_tx_resources(adapter); igb_free_all_rx_resources(adapter); if (!suspending) pm_runtime_put_sync(&pdev->dev); return 0; } int igb_close(struct net_device *netdev) { if (netif_device_present(netdev) || netdev->dismantle) return __igb_close(netdev, false); return 0; } /** * igb_setup_tx_resources - allocate Tx resources (Descriptors) * @tx_ring: tx descriptor ring (for a specific queue) to setup * * Return 0 on success, negative on failure **/ int igb_setup_tx_resources(struct igb_ring *tx_ring) { struct device *dev = tx_ring->dev; int size; size = sizeof(struct igb_tx_buffer) * tx_ring->count; tx_ring->tx_buffer_info = vmalloc(size); if (!tx_ring->tx_buffer_info) goto err; /* round up to nearest 4K */ tx_ring->size = tx_ring->count * sizeof(union e1000_adv_tx_desc); tx_ring->size = ALIGN(tx_ring->size, 4096); tx_ring->desc = dma_alloc_coherent(dev, tx_ring->size, &tx_ring->dma, GFP_KERNEL); if (!tx_ring->desc) goto err; tx_ring->next_to_use = 0; tx_ring->next_to_clean = 0; return 0; err: vfree(tx_ring->tx_buffer_info); tx_ring->tx_buffer_info = NULL; dev_err(dev, "Unable to allocate memory for the Tx descriptor ring\n"); return -ENOMEM; } /** * igb_setup_all_tx_resources - wrapper to allocate Tx resources * (Descriptors) for all queues * @adapter: board private structure * * Return 0 on success, negative on failure **/ static int igb_setup_all_tx_resources(struct igb_adapter *adapter) { struct pci_dev *pdev = adapter->pdev; int i, err = 0; for (i = 0; i < adapter->num_tx_queues; i++) { err = igb_setup_tx_resources(adapter->tx_ring[i]); if (err) { dev_err(&pdev->dev, "Allocation for Tx Queue %u failed\n", i); for (i--; i >= 0; i--) igb_free_tx_resources(adapter->tx_ring[i]); break; } } return err; } /** * igb_setup_tctl - configure the transmit control registers * @adapter: Board private structure **/ void igb_setup_tctl(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 tctl; /* disable queue 0 which is enabled by default on 82575 and 82576 */ wr32(E1000_TXDCTL(0), 0); /* Program the Transmit Control Register */ tctl = rd32(E1000_TCTL); tctl &= ~E1000_TCTL_CT; tctl |= E1000_TCTL_PSP | E1000_TCTL_RTLC | (E1000_COLLISION_THRESHOLD << E1000_CT_SHIFT); igb_config_collision_dist(hw); /* Enable transmits */ tctl |= E1000_TCTL_EN; wr32(E1000_TCTL, tctl); } /** * igb_configure_tx_ring - Configure transmit ring after Reset * @adapter: board private structure * @ring: tx ring to configure * * Configure a transmit ring after a reset. **/ void igb_configure_tx_ring(struct igb_adapter *adapter, struct igb_ring *ring) { struct e1000_hw *hw = &adapter->hw; u32 txdctl = 0; u64 tdba = ring->dma; int reg_idx = ring->reg_idx; wr32(E1000_TDLEN(reg_idx), ring->count * sizeof(union e1000_adv_tx_desc)); wr32(E1000_TDBAL(reg_idx), tdba & 0x00000000ffffffffULL); wr32(E1000_TDBAH(reg_idx), tdba >> 32); ring->tail = adapter->io_addr + E1000_TDT(reg_idx); wr32(E1000_TDH(reg_idx), 0); writel(0, ring->tail); txdctl |= IGB_TX_PTHRESH; txdctl |= IGB_TX_HTHRESH << 8; txdctl |= IGB_TX_WTHRESH << 16; /* reinitialize tx_buffer_info */ memset(ring->tx_buffer_info, 0, sizeof(struct igb_tx_buffer) * ring->count); txdctl |= E1000_TXDCTL_QUEUE_ENABLE; wr32(E1000_TXDCTL(reg_idx), txdctl); } /** * igb_configure_tx - Configure transmit Unit after Reset * @adapter: board private structure * * Configure the Tx unit of the MAC after a reset. **/ static void igb_configure_tx(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; int i; /* disable the queues */ for (i = 0; i < adapter->num_tx_queues; i++) wr32(E1000_TXDCTL(adapter->tx_ring[i]->reg_idx), 0); wrfl(); usleep_range(10000, 20000); for (i = 0; i < adapter->num_tx_queues; i++) igb_configure_tx_ring(adapter, adapter->tx_ring[i]); } /** * igb_setup_rx_resources - allocate Rx resources (Descriptors) * @rx_ring: Rx descriptor ring (for a specific queue) to setup * * Returns 0 on success, negative on failure **/ int igb_setup_rx_resources(struct igb_ring *rx_ring) { struct igb_adapter *adapter = netdev_priv(rx_ring->netdev); struct device *dev = rx_ring->dev; int size, res; /* XDP RX-queue info */ if (xdp_rxq_info_is_reg(&rx_ring->xdp_rxq)) xdp_rxq_info_unreg(&rx_ring->xdp_rxq); res = xdp_rxq_info_reg(&rx_ring->xdp_rxq, rx_ring->netdev, rx_ring->queue_index, 0); if (res < 0) { dev_err(dev, "Failed to register xdp_rxq index %u\n", rx_ring->queue_index); return res; } size = sizeof(struct igb_rx_buffer) * rx_ring->count; rx_ring->rx_buffer_info = vmalloc(size); if (!rx_ring->rx_buffer_info) goto err; /* Round up to nearest 4K */ rx_ring->size = rx_ring->count * sizeof(union e1000_adv_rx_desc); rx_ring->size = ALIGN(rx_ring->size, 4096); rx_ring->desc = dma_alloc_coherent(dev, rx_ring->size, &rx_ring->dma, GFP_KERNEL); if (!rx_ring->desc) goto err; rx_ring->next_to_alloc = 0; rx_ring->next_to_clean = 0; rx_ring->next_to_use = 0; rx_ring->xdp_prog = adapter->xdp_prog; return 0; err: xdp_rxq_info_unreg(&rx_ring->xdp_rxq); vfree(rx_ring->rx_buffer_info); rx_ring->rx_buffer_info = NULL; dev_err(dev, "Unable to allocate memory for the Rx descriptor ring\n"); return -ENOMEM; } /** * igb_setup_all_rx_resources - wrapper to allocate Rx resources * (Descriptors) for all queues * @adapter: board private structure * * Return 0 on success, negative on failure **/ static int igb_setup_all_rx_resources(struct igb_adapter *adapter) { struct pci_dev *pdev = adapter->pdev; int i, err = 0; for (i = 0; i < adapter->num_rx_queues; i++) { err = igb_setup_rx_resources(adapter->rx_ring[i]); if (err) { dev_err(&pdev->dev, "Allocation for Rx Queue %u failed\n", i); for (i--; i >= 0; i--) igb_free_rx_resources(adapter->rx_ring[i]); break; } } return err; } /** * igb_setup_mrqc - configure the multiple receive queue control registers * @adapter: Board private structure **/ static void igb_setup_mrqc(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 mrqc, rxcsum; u32 j, num_rx_queues; u32 rss_key[10]; netdev_rss_key_fill(rss_key, sizeof(rss_key)); for (j = 0; j < 10; j++) wr32(E1000_RSSRK(j), rss_key[j]); num_rx_queues = adapter->rss_queues; switch (hw->mac.type) { case e1000_82576: /* 82576 supports 2 RSS queues for SR-IOV */ if (adapter->vfs_allocated_count) num_rx_queues = 2; break; default: break; } if (adapter->rss_indir_tbl_init != num_rx_queues) { for (j = 0; j < IGB_RETA_SIZE; j++) adapter->rss_indir_tbl[j] = (j * num_rx_queues) / IGB_RETA_SIZE; adapter->rss_indir_tbl_init = num_rx_queues; } igb_write_rss_indir_tbl(adapter); /* Disable raw packet checksumming so that RSS hash is placed in * descriptor on writeback. No need to enable TCP/UDP/IP checksum * offloads as they are enabled by default */ rxcsum = rd32(E1000_RXCSUM); rxcsum |= E1000_RXCSUM_PCSD; if (adapter->hw.mac.type >= e1000_82576) /* Enable Receive Checksum Offload for SCTP */ rxcsum |= E1000_RXCSUM_CRCOFL; /* Don't need to set TUOFL or IPOFL, they default to 1 */ wr32(E1000_RXCSUM, rxcsum); /* Generate RSS hash based on packet types, TCP/UDP * port numbers and/or IPv4/v6 src and dst addresses */ mrqc = E1000_MRQC_RSS_FIELD_IPV4 | E1000_MRQC_RSS_FIELD_IPV4_TCP | E1000_MRQC_RSS_FIELD_IPV6 | E1000_MRQC_RSS_FIELD_IPV6_TCP | E1000_MRQC_RSS_FIELD_IPV6_TCP_EX; if (adapter->flags & IGB_FLAG_RSS_FIELD_IPV4_UDP) mrqc |= E1000_MRQC_RSS_FIELD_IPV4_UDP; if (adapter->flags & IGB_FLAG_RSS_FIELD_IPV6_UDP) mrqc |= E1000_MRQC_RSS_FIELD_IPV6_UDP; /* If VMDq is enabled then we set the appropriate mode for that, else * we default to RSS so that an RSS hash is calculated per packet even * if we are only using one queue */ if (adapter->vfs_allocated_count) { if (hw->mac.type > e1000_82575) { /* Set the default pool for the PF's first queue */ u32 vtctl = rd32(E1000_VT_CTL); vtctl &= ~(E1000_VT_CTL_DEFAULT_POOL_MASK | E1000_VT_CTL_DISABLE_DEF_POOL); vtctl |= adapter->vfs_allocated_count << E1000_VT_CTL_DEFAULT_POOL_SHIFT; wr32(E1000_VT_CTL, vtctl); } if (adapter->rss_queues > 1) mrqc |= E1000_MRQC_ENABLE_VMDQ_RSS_MQ; else mrqc |= E1000_MRQC_ENABLE_VMDQ; } else { mrqc |= E1000_MRQC_ENABLE_RSS_MQ; } igb_vmm_control(adapter); wr32(E1000_MRQC, mrqc); } /** * igb_setup_rctl - configure the receive control registers * @adapter: Board private structure **/ void igb_setup_rctl(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 rctl; rctl = rd32(E1000_RCTL); rctl &= ~(3 << E1000_RCTL_MO_SHIFT); rctl &= ~(E1000_RCTL_LBM_TCVR | E1000_RCTL_LBM_MAC); rctl |= E1000_RCTL_EN | E1000_RCTL_BAM | E1000_RCTL_RDMTS_HALF | (hw->mac.mc_filter_type << E1000_RCTL_MO_SHIFT); /* enable stripping of CRC. It's unlikely this will break BMC * redirection as it did with e1000. Newer features require * that the HW strips the CRC. */ rctl |= E1000_RCTL_SECRC; /* disable store bad packets and clear size bits. */ rctl &= ~(E1000_RCTL_SBP | E1000_RCTL_SZ_256); /* enable LPE to allow for reception of jumbo frames */ rctl |= E1000_RCTL_LPE; /* disable queue 0 to prevent tail write w/o re-config */ wr32(E1000_RXDCTL(0), 0); /* Attention!!! For SR-IOV PF driver operations you must enable * queue drop for all VF and PF queues to prevent head of line blocking * if an un-trusted VF does not provide descriptors to hardware. */ if (adapter->vfs_allocated_count) { /* set all queue drop enable bits */ wr32(E1000_QDE, ALL_QUEUES); } /* This is useful for sniffing bad packets. */ if (adapter->netdev->features & NETIF_F_RXALL) { /* UPE and MPE will be handled by normal PROMISC logic * in e1000e_set_rx_mode */ rctl |= (E1000_RCTL_SBP | /* Receive bad packets */ E1000_RCTL_BAM | /* RX All Bcast Pkts */ E1000_RCTL_PMCF); /* RX All MAC Ctrl Pkts */ rctl &= ~(E1000_RCTL_DPF | /* Allow filtered pause */ E1000_RCTL_CFIEN); /* Dis VLAN CFIEN Filter */ /* Do not mess with E1000_CTRL_VME, it affects transmit as well, * and that breaks VLANs. */ } wr32(E1000_RCTL, rctl); } static inline int igb_set_vf_rlpml(struct igb_adapter *adapter, int size, int vfn) { struct e1000_hw *hw = &adapter->hw; u32 vmolr; if (size > MAX_JUMBO_FRAME_SIZE) size = MAX_JUMBO_FRAME_SIZE; vmolr = rd32(E1000_VMOLR(vfn)); vmolr &= ~E1000_VMOLR_RLPML_MASK; vmolr |= size | E1000_VMOLR_LPE; wr32(E1000_VMOLR(vfn), vmolr); return 0; } static inline void igb_set_vf_vlan_strip(struct igb_adapter *adapter, int vfn, bool enable) { struct e1000_hw *hw = &adapter->hw; u32 val, reg; if (hw->mac.type < e1000_82576) return; if (hw->mac.type == e1000_i350) reg = E1000_DVMOLR(vfn); else reg = E1000_VMOLR(vfn); val = rd32(reg); if (enable) val |= E1000_VMOLR_STRVLAN; else val &= ~(E1000_VMOLR_STRVLAN); wr32(reg, val); } static inline void igb_set_vmolr(struct igb_adapter *adapter, int vfn, bool aupe) { struct e1000_hw *hw = &adapter->hw; u32 vmolr; /* This register exists only on 82576 and newer so if we are older then * we should exit and do nothing */ if (hw->mac.type < e1000_82576) return; vmolr = rd32(E1000_VMOLR(vfn)); if (aupe) vmolr |= E1000_VMOLR_AUPE; /* Accept untagged packets */ else vmolr &= ~(E1000_VMOLR_AUPE); /* Tagged packets ONLY */ /* clear all bits that might not be set */ vmolr &= ~(E1000_VMOLR_BAM | E1000_VMOLR_RSSE); if (adapter->rss_queues > 1 && vfn == adapter->vfs_allocated_count) vmolr |= E1000_VMOLR_RSSE; /* enable RSS */ /* for VMDq only allow the VFs and pool 0 to accept broadcast and * multicast packets */ if (vfn <= adapter->vfs_allocated_count) vmolr |= E1000_VMOLR_BAM; /* Accept broadcast */ wr32(E1000_VMOLR(vfn), vmolr); } /** * igb_setup_srrctl - configure the split and replication receive control * registers * @adapter: Board private structure * @ring: receive ring to be configured **/ void igb_setup_srrctl(struct igb_adapter *adapter, struct igb_ring *ring) { struct e1000_hw *hw = &adapter->hw; int reg_idx = ring->reg_idx; u32 srrctl = 0; srrctl = IGB_RX_HDR_LEN << E1000_SRRCTL_BSIZEHDRSIZE_SHIFT; if (ring_uses_large_buffer(ring)) srrctl |= IGB_RXBUFFER_3072 >> E1000_SRRCTL_BSIZEPKT_SHIFT; else srrctl |= IGB_RXBUFFER_2048 >> E1000_SRRCTL_BSIZEPKT_SHIFT; srrctl |= E1000_SRRCTL_DESCTYPE_ADV_ONEBUF; if (hw->mac.type >= e1000_82580) srrctl |= E1000_SRRCTL_TIMESTAMP; /* Only set Drop Enable if VFs allocated, or we are supporting multiple * queues and rx flow control is disabled */ if (adapter->vfs_allocated_count || (!(hw->fc.current_mode & e1000_fc_rx_pause) && adapter->num_rx_queues > 1)) srrctl |= E1000_SRRCTL_DROP_EN; wr32(E1000_SRRCTL(reg_idx), srrctl); } /** * igb_configure_rx_ring - Configure a receive ring after Reset * @adapter: board private structure * @ring: receive ring to be configured * * Configure the Rx unit of the MAC after a reset. **/ void igb_configure_rx_ring(struct igb_adapter *adapter, struct igb_ring *ring) { struct e1000_hw *hw = &adapter->hw; union e1000_adv_rx_desc *rx_desc; u64 rdba = ring->dma; int reg_idx = ring->reg_idx; u32 rxdctl = 0; xdp_rxq_info_unreg_mem_model(&ring->xdp_rxq); WARN_ON(xdp_rxq_info_reg_mem_model(&ring->xdp_rxq, MEM_TYPE_PAGE_SHARED, NULL)); /* disable the queue */ wr32(E1000_RXDCTL(reg_idx), 0); /* Set DMA base address registers */ wr32(E1000_RDBAL(reg_idx), rdba & 0x00000000ffffffffULL); wr32(E1000_RDBAH(reg_idx), rdba >> 32); wr32(E1000_RDLEN(reg_idx), ring->count * sizeof(union e1000_adv_rx_desc)); /* initialize head and tail */ ring->tail = adapter->io_addr + E1000_RDT(reg_idx); wr32(E1000_RDH(reg_idx), 0); writel(0, ring->tail); /* set descriptor configuration */ igb_setup_srrctl(adapter, ring); /* set filtering for VMDQ pools */ igb_set_vmolr(adapter, reg_idx & 0x7, true); rxdctl |= IGB_RX_PTHRESH; rxdctl |= IGB_RX_HTHRESH << 8; rxdctl |= IGB_RX_WTHRESH << 16; /* initialize rx_buffer_info */ memset(ring->rx_buffer_info, 0, sizeof(struct igb_rx_buffer) * ring->count); /* initialize Rx descriptor 0 */ rx_desc = IGB_RX_DESC(ring, 0); rx_desc->wb.upper.length = 0; /* enable receive descriptor fetching */ rxdctl |= E1000_RXDCTL_QUEUE_ENABLE; wr32(E1000_RXDCTL(reg_idx), rxdctl); } static void igb_set_rx_buffer_len(struct igb_adapter *adapter, struct igb_ring *rx_ring) { #if (PAGE_SIZE < 8192) struct e1000_hw *hw = &adapter->hw; #endif /* set build_skb and buffer size flags */ clear_ring_build_skb_enabled(rx_ring); clear_ring_uses_large_buffer(rx_ring); if (adapter->flags & IGB_FLAG_RX_LEGACY) return; set_ring_build_skb_enabled(rx_ring); #if (PAGE_SIZE < 8192) if (adapter->max_frame_size > IGB_MAX_FRAME_BUILD_SKB || rd32(E1000_RCTL) & E1000_RCTL_SBP) set_ring_uses_large_buffer(rx_ring); #endif } /** * igb_configure_rx - Configure receive Unit after Reset * @adapter: board private structure * * Configure the Rx unit of the MAC after a reset. **/ static void igb_configure_rx(struct igb_adapter *adapter) { int i; /* set the correct pool for the PF default MAC address in entry 0 */ igb_set_default_mac_filter(adapter); /* Setup the HW Rx Head and Tail Descriptor Pointers and * the Base and Length of the Rx Descriptor Ring */ for (i = 0; i < adapter->num_rx_queues; i++) { struct igb_ring *rx_ring = adapter->rx_ring[i]; igb_set_rx_buffer_len(adapter, rx_ring); igb_configure_rx_ring(adapter, rx_ring); } } /** * igb_free_tx_resources - Free Tx Resources per Queue * @tx_ring: Tx descriptor ring for a specific queue * * Free all transmit software resources **/ void igb_free_tx_resources(struct igb_ring *tx_ring) { igb_clean_tx_ring(tx_ring); vfree(tx_ring->tx_buffer_info); tx_ring->tx_buffer_info = NULL; /* if not set, then don't free */ if (!tx_ring->desc) return; dma_free_coherent(tx_ring->dev, tx_ring->size, tx_ring->desc, tx_ring->dma); tx_ring->desc = NULL; } /** * igb_free_all_tx_resources - Free Tx Resources for All Queues * @adapter: board private structure * * Free all transmit software resources **/ static void igb_free_all_tx_resources(struct igb_adapter *adapter) { int i; for (i = 0; i < adapter->num_tx_queues; i++) if (adapter->tx_ring[i]) igb_free_tx_resources(adapter->tx_ring[i]); } /** * igb_clean_tx_ring - Free Tx Buffers * @tx_ring: ring to be cleaned **/ static void igb_clean_tx_ring(struct igb_ring *tx_ring) { u16 i = tx_ring->next_to_clean; struct igb_tx_buffer *tx_buffer = &tx_ring->tx_buffer_info[i]; while (i != tx_ring->next_to_use) { union e1000_adv_tx_desc *eop_desc, *tx_desc; /* Free all the Tx ring sk_buffs or xdp frames */ if (tx_buffer->type == IGB_TYPE_SKB) dev_kfree_skb_any(tx_buffer->skb); else xdp_return_frame(tx_buffer->xdpf); /* unmap skb header data */ dma_unmap_single(tx_ring->dev, dma_unmap_addr(tx_buffer, dma), dma_unmap_len(tx_buffer, len), DMA_TO_DEVICE); /* check for eop_desc to determine the end of the packet */ eop_desc = tx_buffer->next_to_watch; tx_desc = IGB_TX_DESC(tx_ring, i); /* unmap remaining buffers */ while (tx_desc != eop_desc) { tx_buffer++; tx_desc++; i++; if (unlikely(i == tx_ring->count)) { i = 0; tx_buffer = tx_ring->tx_buffer_info; tx_desc = IGB_TX_DESC(tx_ring, 0); } /* unmap any remaining paged data */ if (dma_unmap_len(tx_buffer, len)) dma_unmap_page(tx_ring->dev, dma_unmap_addr(tx_buffer, dma), dma_unmap_len(tx_buffer, len), DMA_TO_DEVICE); } tx_buffer->next_to_watch = NULL; /* move us one more past the eop_desc for start of next pkt */ tx_buffer++; i++; if (unlikely(i == tx_ring->count)) { i = 0; tx_buffer = tx_ring->tx_buffer_info; } } /* reset BQL for queue */ netdev_tx_reset_queue(txring_txq(tx_ring)); /* reset next_to_use and next_to_clean */ tx_ring->next_to_use = 0; tx_ring->next_to_clean = 0; } /** * igb_clean_all_tx_rings - Free Tx Buffers for all queues * @adapter: board private structure **/ static void igb_clean_all_tx_rings(struct igb_adapter *adapter) { int i; for (i = 0; i < adapter->num_tx_queues; i++) if (adapter->tx_ring[i]) igb_clean_tx_ring(adapter->tx_ring[i]); } /** * igb_free_rx_resources - Free Rx Resources * @rx_ring: ring to clean the resources from * * Free all receive software resources **/ void igb_free_rx_resources(struct igb_ring *rx_ring) { igb_clean_rx_ring(rx_ring); rx_ring->xdp_prog = NULL; xdp_rxq_info_unreg(&rx_ring->xdp_rxq); vfree(rx_ring->rx_buffer_info); rx_ring->rx_buffer_info = NULL; /* if not set, then don't free */ if (!rx_ring->desc) return; dma_free_coherent(rx_ring->dev, rx_ring->size, rx_ring->desc, rx_ring->dma); rx_ring->desc = NULL; } /** * igb_free_all_rx_resources - Free Rx Resources for All Queues * @adapter: board private structure * * Free all receive software resources **/ static void igb_free_all_rx_resources(struct igb_adapter *adapter) { int i; for (i = 0; i < adapter->num_rx_queues; i++) if (adapter->rx_ring[i]) igb_free_rx_resources(adapter->rx_ring[i]); } /** * igb_clean_rx_ring - Free Rx Buffers per Queue * @rx_ring: ring to free buffers from **/ static void igb_clean_rx_ring(struct igb_ring *rx_ring) { u16 i = rx_ring->next_to_clean; dev_kfree_skb(rx_ring->skb); rx_ring->skb = NULL; /* Free all the Rx ring sk_buffs */ while (i != rx_ring->next_to_alloc) { struct igb_rx_buffer *buffer_info = &rx_ring->rx_buffer_info[i]; /* Invalidate cache lines that may have been written to by * device so that we avoid corrupting memory. */ dma_sync_single_range_for_cpu(rx_ring->dev, buffer_info->dma, buffer_info->page_offset, igb_rx_bufsz(rx_ring), DMA_FROM_DEVICE); /* free resources associated with mapping */ dma_unmap_page_attrs(rx_ring->dev, buffer_info->dma, igb_rx_pg_size(rx_ring), DMA_FROM_DEVICE, IGB_RX_DMA_ATTR); __page_frag_cache_drain(buffer_info->page, buffer_info->pagecnt_bias); i++; if (i == rx_ring->count) i = 0; } rx_ring->next_to_alloc = 0; rx_ring->next_to_clean = 0; rx_ring->next_to_use = 0; } /** * igb_clean_all_rx_rings - Free Rx Buffers for all queues * @adapter: board private structure **/ static void igb_clean_all_rx_rings(struct igb_adapter *adapter) { int i; for (i = 0; i < adapter->num_rx_queues; i++) if (adapter->rx_ring[i]) igb_clean_rx_ring(adapter->rx_ring[i]); } /** * igb_set_mac - Change the Ethernet Address of the NIC * @netdev: network interface device structure * @p: pointer to an address structure * * Returns 0 on success, negative on failure **/ static int igb_set_mac(struct net_device *netdev, void *p) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; struct sockaddr *addr = p; if (!is_valid_ether_addr(addr->sa_data)) return -EADDRNOTAVAIL; eth_hw_addr_set(netdev, addr->sa_data); memcpy(hw->mac.addr, addr->sa_data, netdev->addr_len); /* set the correct pool for the new PF MAC address in entry 0 */ igb_set_default_mac_filter(adapter); return 0; } /** * igb_write_mc_addr_list - write multicast addresses to MTA * @netdev: network interface device structure * * Writes multicast address list to the MTA hash table. * Returns: -ENOMEM on failure * 0 on no addresses written * X on writing X addresses to MTA **/ static int igb_write_mc_addr_list(struct net_device *netdev) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; struct netdev_hw_addr *ha; u8 *mta_list; int i; if (netdev_mc_empty(netdev)) { /* nothing to program, so clear mc list */ igb_update_mc_addr_list(hw, NULL, 0); igb_restore_vf_multicasts(adapter); return 0; } mta_list = kcalloc(netdev_mc_count(netdev), 6, GFP_ATOMIC); if (!mta_list) return -ENOMEM; /* The shared function expects a packed array of only addresses. */ i = 0; netdev_for_each_mc_addr(ha, netdev) memcpy(mta_list + (i++ * ETH_ALEN), ha->addr, ETH_ALEN); igb_update_mc_addr_list(hw, mta_list, i); kfree(mta_list); return netdev_mc_count(netdev); } static int igb_vlan_promisc_enable(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 i, pf_id; switch (hw->mac.type) { case e1000_i210: case e1000_i211: case e1000_i350: /* VLAN filtering needed for VLAN prio filter */ if (adapter->netdev->features & NETIF_F_NTUPLE) break; fallthrough; case e1000_82576: case e1000_82580: case e1000_i354: /* VLAN filtering needed for pool filtering */ if (adapter->vfs_allocated_count) break; fallthrough; default: return 1; } /* We are already in VLAN promisc, nothing to do */ if (adapter->flags & IGB_FLAG_VLAN_PROMISC) return 0; if (!adapter->vfs_allocated_count) goto set_vfta; /* Add PF to all active pools */ pf_id = adapter->vfs_allocated_count + E1000_VLVF_POOLSEL_SHIFT; for (i = E1000_VLVF_ARRAY_SIZE; --i;) { u32 vlvf = rd32(E1000_VLVF(i)); vlvf |= BIT(pf_id); wr32(E1000_VLVF(i), vlvf); } set_vfta: /* Set all bits in the VLAN filter table array */ for (i = E1000_VLAN_FILTER_TBL_SIZE; i--;) hw->mac.ops.write_vfta(hw, i, ~0U); /* Set flag so we don't redo unnecessary work */ adapter->flags |= IGB_FLAG_VLAN_PROMISC; return 0; } #define VFTA_BLOCK_SIZE 8 static void igb_scrub_vfta(struct igb_adapter *adapter, u32 vfta_offset) { struct e1000_hw *hw = &adapter->hw; u32 vfta[VFTA_BLOCK_SIZE] = { 0 }; u32 vid_start = vfta_offset * 32; u32 vid_end = vid_start + (VFTA_BLOCK_SIZE * 32); u32 i, vid, word, bits, pf_id; /* guarantee that we don't scrub out management VLAN */ vid = adapter->mng_vlan_id; if (vid >= vid_start && vid < vid_end) vfta[(vid - vid_start) / 32] |= BIT(vid % 32); if (!adapter->vfs_allocated_count) goto set_vfta; pf_id = adapter->vfs_allocated_count + E1000_VLVF_POOLSEL_SHIFT; for (i = E1000_VLVF_ARRAY_SIZE; --i;) { u32 vlvf = rd32(E1000_VLVF(i)); /* pull VLAN ID from VLVF */ vid = vlvf & VLAN_VID_MASK; /* only concern ourselves with a certain range */ if (vid < vid_start || vid >= vid_end) continue; if (vlvf & E1000_VLVF_VLANID_ENABLE) { /* record VLAN ID in VFTA */ vfta[(vid - vid_start) / 32] |= BIT(vid % 32); /* if PF is part of this then continue */ if (test_bit(vid, adapter->active_vlans)) continue; } /* remove PF from the pool */ bits = ~BIT(pf_id); bits &= rd32(E1000_VLVF(i)); wr32(E1000_VLVF(i), bits); } set_vfta: /* extract values from active_vlans and write back to VFTA */ for (i = VFTA_BLOCK_SIZE; i--;) { vid = (vfta_offset + i) * 32; word = vid / BITS_PER_LONG; bits = vid % BITS_PER_LONG; vfta[i] |= adapter->active_vlans[word] >> bits; hw->mac.ops.write_vfta(hw, vfta_offset + i, vfta[i]); } } static void igb_vlan_promisc_disable(struct igb_adapter *adapter) { u32 i; /* We are not in VLAN promisc, nothing to do */ if (!(adapter->flags & IGB_FLAG_VLAN_PROMISC)) return; /* Set flag so we don't redo unnecessary work */ adapter->flags &= ~IGB_FLAG_VLAN_PROMISC; for (i = 0; i < E1000_VLAN_FILTER_TBL_SIZE; i += VFTA_BLOCK_SIZE) igb_scrub_vfta(adapter, i); } /** * igb_set_rx_mode - Secondary Unicast, Multicast and Promiscuous mode set * @netdev: network interface device structure * * The set_rx_mode entry point is called whenever the unicast or multicast * address lists or the network interface flags are updated. This routine is * responsible for configuring the hardware for proper unicast, multicast, * promiscuous mode, and all-multi behavior. **/ static void igb_set_rx_mode(struct net_device *netdev) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; unsigned int vfn = adapter->vfs_allocated_count; u32 rctl = 0, vmolr = 0, rlpml = MAX_JUMBO_FRAME_SIZE; int count; /* Check for Promiscuous and All Multicast modes */ if (netdev->flags & IFF_PROMISC) { rctl |= E1000_RCTL_UPE | E1000_RCTL_MPE; vmolr |= E1000_VMOLR_MPME; /* enable use of UTA filter to force packets to default pool */ if (hw->mac.type == e1000_82576) vmolr |= E1000_VMOLR_ROPE; } else { if (netdev->flags & IFF_ALLMULTI) { rctl |= E1000_RCTL_MPE; vmolr |= E1000_VMOLR_MPME; } else { /* Write addresses to the MTA, if the attempt fails * then we should just turn on promiscuous mode so * that we can at least receive multicast traffic */ count = igb_write_mc_addr_list(netdev); if (count < 0) { rctl |= E1000_RCTL_MPE; vmolr |= E1000_VMOLR_MPME; } else if (count) { vmolr |= E1000_VMOLR_ROMPE; } } } /* Write addresses to available RAR registers, if there is not * sufficient space to store all the addresses then enable * unicast promiscuous mode */ if (__dev_uc_sync(netdev, igb_uc_sync, igb_uc_unsync)) { rctl |= E1000_RCTL_UPE; vmolr |= E1000_VMOLR_ROPE; } /* enable VLAN filtering by default */ rctl |= E1000_RCTL_VFE; /* disable VLAN filtering for modes that require it */ if ((netdev->flags & IFF_PROMISC) || (netdev->features & NETIF_F_RXALL)) { /* if we fail to set all rules then just clear VFE */ if (igb_vlan_promisc_enable(adapter)) rctl &= ~E1000_RCTL_VFE; } else { igb_vlan_promisc_disable(adapter); } /* update state of unicast, multicast, and VLAN filtering modes */ rctl |= rd32(E1000_RCTL) & ~(E1000_RCTL_UPE | E1000_RCTL_MPE | E1000_RCTL_VFE); wr32(E1000_RCTL, rctl); #if (PAGE_SIZE < 8192) if (!adapter->vfs_allocated_count) { if (adapter->max_frame_size <= IGB_MAX_FRAME_BUILD_SKB) rlpml = IGB_MAX_FRAME_BUILD_SKB; } #endif wr32(E1000_RLPML, rlpml); /* In order to support SR-IOV and eventually VMDq it is necessary to set * the VMOLR to enable the appropriate modes. Without this workaround * we will have issues with VLAN tag stripping not being done for frames * that are only arriving because we are the default pool */ if ((hw->mac.type < e1000_82576) || (hw->mac.type > e1000_i350)) return; /* set UTA to appropriate mode */ igb_set_uta(adapter, !!(vmolr & E1000_VMOLR_ROPE)); vmolr |= rd32(E1000_VMOLR(vfn)) & ~(E1000_VMOLR_ROPE | E1000_VMOLR_MPME | E1000_VMOLR_ROMPE); /* enable Rx jumbo frames, restrict as needed to support build_skb */ vmolr &= ~E1000_VMOLR_RLPML_MASK; #if (PAGE_SIZE < 8192) if (adapter->max_frame_size <= IGB_MAX_FRAME_BUILD_SKB) vmolr |= IGB_MAX_FRAME_BUILD_SKB; else #endif vmolr |= MAX_JUMBO_FRAME_SIZE; vmolr |= E1000_VMOLR_LPE; wr32(E1000_VMOLR(vfn), vmolr); igb_restore_vf_multicasts(adapter); } static void igb_check_wvbr(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 wvbr = 0; switch (hw->mac.type) { case e1000_82576: case e1000_i350: wvbr = rd32(E1000_WVBR); if (!wvbr) return; break; default: break; } adapter->wvbr |= wvbr; } #define IGB_STAGGERED_QUEUE_OFFSET 8 static void igb_spoof_check(struct igb_adapter *adapter) { int j; if (!adapter->wvbr) return; for (j = 0; j < adapter->vfs_allocated_count; j++) { if (adapter->wvbr & BIT(j) || adapter->wvbr & BIT(j + IGB_STAGGERED_QUEUE_OFFSET)) { dev_warn(&adapter->pdev->dev, "Spoof event(s) detected on VF %d\n", j); adapter->wvbr &= ~(BIT(j) | BIT(j + IGB_STAGGERED_QUEUE_OFFSET)); } } } /* Need to wait a few seconds after link up to get diagnostic information from * the phy */ static void igb_update_phy_info(struct timer_list *t) { struct igb_adapter *adapter = from_timer(adapter, t, phy_info_timer); igb_get_phy_info(&adapter->hw); } /** * igb_has_link - check shared code for link and determine up/down * @adapter: pointer to driver private info **/ bool igb_has_link(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; bool link_active = false; /* get_link_status is set on LSC (link status) interrupt or * rx sequence error interrupt. get_link_status will stay * false until the e1000_check_for_link establishes link * for copper adapters ONLY */ switch (hw->phy.media_type) { case e1000_media_type_copper: if (!hw->mac.get_link_status) return true; fallthrough; case e1000_media_type_internal_serdes: hw->mac.ops.check_for_link(hw); link_active = !hw->mac.get_link_status; break; default: case e1000_media_type_unknown: break; } if (((hw->mac.type == e1000_i210) || (hw->mac.type == e1000_i211)) && (hw->phy.id == I210_I_PHY_ID)) { if (!netif_carrier_ok(adapter->netdev)) { adapter->flags &= ~IGB_FLAG_NEED_LINK_UPDATE; } else if (!(adapter->flags & IGB_FLAG_NEED_LINK_UPDATE)) { adapter->flags |= IGB_FLAG_NEED_LINK_UPDATE; adapter->link_check_timeout = jiffies; } } return link_active; } static bool igb_thermal_sensor_event(struct e1000_hw *hw, u32 event) { bool ret = false; u32 ctrl_ext, thstat; /* check for thermal sensor event on i350 copper only */ if (hw->mac.type == e1000_i350) { thstat = rd32(E1000_THSTAT); ctrl_ext = rd32(E1000_CTRL_EXT); if ((hw->phy.media_type == e1000_media_type_copper) && !(ctrl_ext & E1000_CTRL_EXT_LINK_MODE_SGMII)) ret = !!(thstat & event); } return ret; } /** * igb_check_lvmmc - check for malformed packets received * and indicated in LVMMC register * @adapter: pointer to adapter **/ static void igb_check_lvmmc(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 lvmmc; lvmmc = rd32(E1000_LVMMC); if (lvmmc) { if (unlikely(net_ratelimit())) { netdev_warn(adapter->netdev, "malformed Tx packet detected and dropped, LVMMC:0x%08x\n", lvmmc); } } } /** * igb_watchdog - Timer Call-back * @t: pointer to timer_list containing our private info pointer **/ static void igb_watchdog(struct timer_list *t) { struct igb_adapter *adapter = from_timer(adapter, t, watchdog_timer); /* Do the rest outside of interrupt context */ schedule_work(&adapter->watchdog_task); } static void igb_watchdog_task(struct work_struct *work) { struct igb_adapter *adapter = container_of(work, struct igb_adapter, watchdog_task); struct e1000_hw *hw = &adapter->hw; struct e1000_phy_info *phy = &hw->phy; struct net_device *netdev = adapter->netdev; u32 link; int i; u32 connsw; u16 phy_data, retry_count = 20; link = igb_has_link(adapter); if (adapter->flags & IGB_FLAG_NEED_LINK_UPDATE) { if (time_after(jiffies, (adapter->link_check_timeout + HZ))) adapter->flags &= ~IGB_FLAG_NEED_LINK_UPDATE; else link = false; } /* Force link down if we have fiber to swap to */ if (adapter->flags & IGB_FLAG_MAS_ENABLE) { if (hw->phy.media_type == e1000_media_type_copper) { connsw = rd32(E1000_CONNSW); if (!(connsw & E1000_CONNSW_AUTOSENSE_EN)) link = 0; } } if (link) { /* Perform a reset if the media type changed. */ if (hw->dev_spec._82575.media_changed) { hw->dev_spec._82575.media_changed = false; adapter->flags |= IGB_FLAG_MEDIA_RESET; igb_reset(adapter); } /* Cancel scheduled suspend requests. */ pm_runtime_resume(netdev->dev.parent); if (!netif_carrier_ok(netdev)) { u32 ctrl; hw->mac.ops.get_speed_and_duplex(hw, &adapter->link_speed, &adapter->link_duplex); ctrl = rd32(E1000_CTRL); /* Links status message must follow this format */ netdev_info(netdev, "igb: %s NIC Link is Up %d Mbps %s Duplex, Flow Control: %s\n", netdev->name, adapter->link_speed, adapter->link_duplex == FULL_DUPLEX ? "Full" : "Half", (ctrl & E1000_CTRL_TFCE) && (ctrl & E1000_CTRL_RFCE) ? "RX/TX" : (ctrl & E1000_CTRL_RFCE) ? "RX" : (ctrl & E1000_CTRL_TFCE) ? "TX" : "None"); /* disable EEE if enabled */ if ((adapter->flags & IGB_FLAG_EEE) && (adapter->link_duplex == HALF_DUPLEX)) { dev_info(&adapter->pdev->dev, "EEE Disabled: unsupported at half duplex. Re-enable using ethtool when at full duplex.\n"); adapter->hw.dev_spec._82575.eee_disable = true; adapter->flags &= ~IGB_FLAG_EEE; } /* check if SmartSpeed worked */ igb_check_downshift(hw); if (phy->speed_downgraded) netdev_warn(netdev, "Link Speed was downgraded by SmartSpeed\n"); /* check for thermal sensor event */ if (igb_thermal_sensor_event(hw, E1000_THSTAT_LINK_THROTTLE)) netdev_info(netdev, "The network adapter link speed was downshifted because it overheated\n"); /* adjust timeout factor according to speed/duplex */ adapter->tx_timeout_factor = 1; switch (adapter->link_speed) { case SPEED_10: adapter->tx_timeout_factor = 14; break; case SPEED_100: /* maybe add some timeout factor ? */ break; } if (adapter->link_speed != SPEED_1000 || !hw->phy.ops.read_reg) goto no_wait; /* wait for Remote receiver status OK */ retry_read_status: if (!igb_read_phy_reg(hw, PHY_1000T_STATUS, &phy_data)) { if (!(phy_data & SR_1000T_REMOTE_RX_STATUS) && retry_count) { msleep(100); retry_count--; goto retry_read_status; } else if (!retry_count) { dev_err(&adapter->pdev->dev, "exceed max 2 second\n"); } } else { dev_err(&adapter->pdev->dev, "read 1000Base-T Status Reg\n"); } no_wait: netif_carrier_on(netdev); igb_ping_all_vfs(adapter); igb_check_vf_rate_limit(adapter); /* link state has changed, schedule phy info update */ if (!test_bit(__IGB_DOWN, &adapter->state)) mod_timer(&adapter->phy_info_timer, round_jiffies(jiffies + 2 * HZ)); } } else { if (netif_carrier_ok(netdev)) { adapter->link_speed = 0; adapter->link_duplex = 0; /* check for thermal sensor event */ if (igb_thermal_sensor_event(hw, E1000_THSTAT_PWR_DOWN)) { netdev_err(netdev, "The network adapter was stopped because it overheated\n"); } /* Links status message must follow this format */ netdev_info(netdev, "igb: %s NIC Link is Down\n", netdev->name); netif_carrier_off(netdev); igb_ping_all_vfs(adapter); /* link state has changed, schedule phy info update */ if (!test_bit(__IGB_DOWN, &adapter->state)) mod_timer(&adapter->phy_info_timer, round_jiffies(jiffies + 2 * HZ)); /* link is down, time to check for alternate media */ if (adapter->flags & IGB_FLAG_MAS_ENABLE) { igb_check_swap_media(adapter); if (adapter->flags & IGB_FLAG_MEDIA_RESET) { schedule_work(&adapter->reset_task); /* return immediately */ return; } } pm_schedule_suspend(netdev->dev.parent, MSEC_PER_SEC * 5); /* also check for alternate media here */ } else if (!netif_carrier_ok(netdev) && (adapter->flags & IGB_FLAG_MAS_ENABLE)) { igb_check_swap_media(adapter); if (adapter->flags & IGB_FLAG_MEDIA_RESET) { schedule_work(&adapter->reset_task); /* return immediately */ return; } } } spin_lock(&adapter->stats64_lock); igb_update_stats(adapter); spin_unlock(&adapter->stats64_lock); for (i = 0; i < adapter->num_tx_queues; i++) { struct igb_ring *tx_ring = adapter->tx_ring[i]; if (!netif_carrier_ok(netdev)) { /* We've lost link, so the controller stops DMA, * but we've got queued Tx work that's never going * to get done, so reset controller to flush Tx. * (Do the reset outside of interrupt context). */ if (igb_desc_unused(tx_ring) + 1 < tx_ring->count) { adapter->tx_timeout_count++; schedule_work(&adapter->reset_task); /* return immediately since reset is imminent */ return; } } /* Force detection of hung controller every watchdog period */ set_bit(IGB_RING_FLAG_TX_DETECT_HANG, &tx_ring->flags); } /* Cause software interrupt to ensure Rx ring is cleaned */ if (adapter->flags & IGB_FLAG_HAS_MSIX) { u32 eics = 0; for (i = 0; i < adapter->num_q_vectors; i++) eics |= adapter->q_vector[i]->eims_value; wr32(E1000_EICS, eics); } else { wr32(E1000_ICS, E1000_ICS_RXDMT0); } igb_spoof_check(adapter); igb_ptp_rx_hang(adapter); igb_ptp_tx_hang(adapter); /* Check LVMMC register on i350/i354 only */ if ((adapter->hw.mac.type == e1000_i350) || (adapter->hw.mac.type == e1000_i354)) igb_check_lvmmc(adapter); /* Reset the timer */ if (!test_bit(__IGB_DOWN, &adapter->state)) { if (adapter->flags & IGB_FLAG_NEED_LINK_UPDATE) mod_timer(&adapter->watchdog_timer, round_jiffies(jiffies + HZ)); else mod_timer(&adapter->watchdog_timer, round_jiffies(jiffies + 2 * HZ)); } } enum latency_range { lowest_latency = 0, low_latency = 1, bulk_latency = 2, latency_invalid = 255 }; /** * igb_update_ring_itr - update the dynamic ITR value based on packet size * @q_vector: pointer to q_vector * * Stores a new ITR value based on strictly on packet size. This * algorithm is less sophisticated than that used in igb_update_itr, * due to the difficulty of synchronizing statistics across multiple * receive rings. The divisors and thresholds used by this function * were determined based on theoretical maximum wire speed and testing * data, in order to minimize response time while increasing bulk * throughput. * This functionality is controlled by ethtool's coalescing settings. * NOTE: This function is called only when operating in a multiqueue * receive environment. **/ static void igb_update_ring_itr(struct igb_q_vector *q_vector) { int new_val = q_vector->itr_val; int avg_wire_size = 0; struct igb_adapter *adapter = q_vector->adapter; unsigned int packets; /* For non-gigabit speeds, just fix the interrupt rate at 4000 * ints/sec - ITR timer value of 120 ticks. */ if (adapter->link_speed != SPEED_1000) { new_val = IGB_4K_ITR; goto set_itr_val; } packets = q_vector->rx.total_packets; if (packets) avg_wire_size = q_vector->rx.total_bytes / packets; packets = q_vector->tx.total_packets; if (packets) avg_wire_size = max_t(u32, avg_wire_size, q_vector->tx.total_bytes / packets); /* if avg_wire_size isn't set no work was done */ if (!avg_wire_size) goto clear_counts; /* Add 24 bytes to size to account for CRC, preamble, and gap */ avg_wire_size += 24; /* Don't starve jumbo frames */ avg_wire_size = min(avg_wire_size, 3000); /* Give a little boost to mid-size frames */ if ((avg_wire_size > 300) && (avg_wire_size < 1200)) new_val = avg_wire_size / 3; else new_val = avg_wire_size / 2; /* conservative mode (itr 3) eliminates the lowest_latency setting */ if (new_val < IGB_20K_ITR && ((q_vector->rx.ring && adapter->rx_itr_setting == 3) || (!q_vector->rx.ring && adapter->tx_itr_setting == 3))) new_val = IGB_20K_ITR; set_itr_val: if (new_val != q_vector->itr_val) { q_vector->itr_val = new_val; q_vector->set_itr = 1; } clear_counts: q_vector->rx.total_bytes = 0; q_vector->rx.total_packets = 0; q_vector->tx.total_bytes = 0; q_vector->tx.total_packets = 0; } /** * igb_update_itr - update the dynamic ITR value based on statistics * @q_vector: pointer to q_vector * @ring_container: ring info to update the itr for * * Stores a new ITR value based on packets and byte * counts during the last interrupt. The advantage of per interrupt * computation is faster updates and more accurate ITR for the current * traffic pattern. Constants in this function were computed * based on theoretical maximum wire speed and thresholds were set based * on testing data as well as attempting to minimize response time * while increasing bulk throughput. * This functionality is controlled by ethtool's coalescing settings. * NOTE: These calculations are only valid when operating in a single- * queue environment. **/ static void igb_update_itr(struct igb_q_vector *q_vector, struct igb_ring_container *ring_container) { unsigned int packets = ring_container->total_packets; unsigned int bytes = ring_container->total_bytes; u8 itrval = ring_container->itr; /* no packets, exit with status unchanged */ if (packets == 0) return; switch (itrval) { case lowest_latency: /* handle TSO and jumbo frames */ if (bytes/packets > 8000) itrval = bulk_latency; else if ((packets < 5) && (bytes > 512)) itrval = low_latency; break; case low_latency: /* 50 usec aka 20000 ints/s */ if (bytes > 10000) { /* this if handles the TSO accounting */ if (bytes/packets > 8000) itrval = bulk_latency; else if ((packets < 10) || ((bytes/packets) > 1200)) itrval = bulk_latency; else if ((packets > 35)) itrval = lowest_latency; } else if (bytes/packets > 2000) { itrval = bulk_latency; } else if (packets <= 2 && bytes < 512) { itrval = lowest_latency; } break; case bulk_latency: /* 250 usec aka 4000 ints/s */ if (bytes > 25000) { if (packets > 35) itrval = low_latency; } else if (bytes < 1500) { itrval = low_latency; } break; } /* clear work counters since we have the values we need */ ring_container->total_bytes = 0; ring_container->total_packets = 0; /* write updated itr to ring container */ ring_container->itr = itrval; } static void igb_set_itr(struct igb_q_vector *q_vector) { struct igb_adapter *adapter = q_vector->adapter; u32 new_itr = q_vector->itr_val; u8 current_itr = 0; /* for non-gigabit speeds, just fix the interrupt rate at 4000 */ if (adapter->link_speed != SPEED_1000) { current_itr = 0; new_itr = IGB_4K_ITR; goto set_itr_now; } igb_update_itr(q_vector, &q_vector->tx); igb_update_itr(q_vector, &q_vector->rx); current_itr = max(q_vector->rx.itr, q_vector->tx.itr); /* conservative mode (itr 3) eliminates the lowest_latency setting */ if (current_itr == lowest_latency && ((q_vector->rx.ring && adapter->rx_itr_setting == 3) || (!q_vector->rx.ring && adapter->tx_itr_setting == 3))) current_itr = low_latency; switch (current_itr) { /* counts and packets in update_itr are dependent on these numbers */ case lowest_latency: new_itr = IGB_70K_ITR; /* 70,000 ints/sec */ break; case low_latency: new_itr = IGB_20K_ITR; /* 20,000 ints/sec */ break; case bulk_latency: new_itr = IGB_4K_ITR; /* 4,000 ints/sec */ break; default: break; } set_itr_now: if (new_itr != q_vector->itr_val) { /* this attempts to bias the interrupt rate towards Bulk * by adding intermediate steps when interrupt rate is * increasing */ new_itr = new_itr > q_vector->itr_val ? max((new_itr * q_vector->itr_val) / (new_itr + (q_vector->itr_val >> 2)), new_itr) : new_itr; /* Don't write the value here; it resets the adapter's * internal timer, and causes us to delay far longer than * we should between interrupts. Instead, we write the ITR * value at the beginning of the next interrupt so the timing * ends up being correct. */ q_vector->itr_val = new_itr; q_vector->set_itr = 1; } } static void igb_tx_ctxtdesc(struct igb_ring *tx_ring, struct igb_tx_buffer *first, u32 vlan_macip_lens, u32 type_tucmd, u32 mss_l4len_idx) { struct e1000_adv_tx_context_desc *context_desc; u16 i = tx_ring->next_to_use; struct timespec64 ts; context_desc = IGB_TX_CTXTDESC(tx_ring, i); i++; tx_ring->next_to_use = (i < tx_ring->count) ? i : 0; /* set bits to identify this as an advanced context descriptor */ type_tucmd |= E1000_TXD_CMD_DEXT | E1000_ADVTXD_DTYP_CTXT; /* For 82575, context index must be unique per ring. */ if (test_bit(IGB_RING_FLAG_TX_CTX_IDX, &tx_ring->flags)) mss_l4len_idx |= tx_ring->reg_idx << 4; context_desc->vlan_macip_lens = cpu_to_le32(vlan_macip_lens); context_desc->type_tucmd_mlhl = cpu_to_le32(type_tucmd); context_desc->mss_l4len_idx = cpu_to_le32(mss_l4len_idx); /* We assume there is always a valid tx time available. Invalid times * should have been handled by the upper layers. */ if (tx_ring->launchtime_enable) { ts = ktime_to_timespec64(first->skb->tstamp); skb_txtime_consumed(first->skb); context_desc->seqnum_seed = cpu_to_le32(ts.tv_nsec / 32); } else { context_desc->seqnum_seed = 0; } } static int igb_tso(struct igb_ring *tx_ring, struct igb_tx_buffer *first, u8 *hdr_len) { u32 vlan_macip_lens, type_tucmd, mss_l4len_idx; struct sk_buff *skb = first->skb; union { struct iphdr *v4; struct ipv6hdr *v6; unsigned char *hdr; } ip; union { struct tcphdr *tcp; struct udphdr *udp; unsigned char *hdr; } l4; u32 paylen, l4_offset; int err; if (skb->ip_summed != CHECKSUM_PARTIAL) return 0; if (!skb_is_gso(skb)) return 0; err = skb_cow_head(skb, 0); if (err < 0) return err; ip.hdr = skb_network_header(skb); l4.hdr = skb_checksum_start(skb); /* ADV DTYP TUCMD MKRLOC/ISCSIHEDLEN */ type_tucmd = (skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) ? E1000_ADVTXD_TUCMD_L4T_UDP : E1000_ADVTXD_TUCMD_L4T_TCP; /* initialize outer IP header fields */ if (ip.v4->version == 4) { unsigned char *csum_start = skb_checksum_start(skb); unsigned char *trans_start = ip.hdr + (ip.v4->ihl * 4); /* IP header will have to cancel out any data that * is not a part of the outer IP header */ ip.v4->check = csum_fold(csum_partial(trans_start, csum_start - trans_start, 0)); type_tucmd |= E1000_ADVTXD_TUCMD_IPV4; ip.v4->tot_len = 0; first->tx_flags |= IGB_TX_FLAGS_TSO | IGB_TX_FLAGS_CSUM | IGB_TX_FLAGS_IPV4; } else { ip.v6->payload_len = 0; first->tx_flags |= IGB_TX_FLAGS_TSO | IGB_TX_FLAGS_CSUM; } /* determine offset of inner transport header */ l4_offset = l4.hdr - skb->data; /* remove payload length from inner checksum */ paylen = skb->len - l4_offset; if (type_tucmd & E1000_ADVTXD_TUCMD_L4T_TCP) { /* compute length of segmentation header */ *hdr_len = (l4.tcp->doff * 4) + l4_offset; csum_replace_by_diff(&l4.tcp->check, (__force __wsum)htonl(paylen)); } else { /* compute length of segmentation header */ *hdr_len = sizeof(*l4.udp) + l4_offset; csum_replace_by_diff(&l4.udp->check, (__force __wsum)htonl(paylen)); } /* update gso size and bytecount with header size */ first->gso_segs = skb_shinfo(skb)->gso_segs; first->bytecount += (first->gso_segs - 1) * *hdr_len; /* MSS L4LEN IDX */ mss_l4len_idx = (*hdr_len - l4_offset) << E1000_ADVTXD_L4LEN_SHIFT; mss_l4len_idx |= skb_shinfo(skb)->gso_size << E1000_ADVTXD_MSS_SHIFT; /* VLAN MACLEN IPLEN */ vlan_macip_lens = l4.hdr - ip.hdr; vlan_macip_lens |= (ip.hdr - skb->data) << E1000_ADVTXD_MACLEN_SHIFT; vlan_macip_lens |= first->tx_flags & IGB_TX_FLAGS_VLAN_MASK; igb_tx_ctxtdesc(tx_ring, first, vlan_macip_lens, type_tucmd, mss_l4len_idx); return 1; } static void igb_tx_csum(struct igb_ring *tx_ring, struct igb_tx_buffer *first) { struct sk_buff *skb = first->skb; u32 vlan_macip_lens = 0; u32 type_tucmd = 0; if (skb->ip_summed != CHECKSUM_PARTIAL) { csum_failed: if (!(first->tx_flags & IGB_TX_FLAGS_VLAN) && !tx_ring->launchtime_enable) return; goto no_csum; } switch (skb->csum_offset) { case offsetof(struct tcphdr, check): type_tucmd = E1000_ADVTXD_TUCMD_L4T_TCP; fallthrough; case offsetof(struct udphdr, check): break; case offsetof(struct sctphdr, checksum): /* validate that this is actually an SCTP request */ if (skb_csum_is_sctp(skb)) { type_tucmd = E1000_ADVTXD_TUCMD_L4T_SCTP; break; } fallthrough; default: skb_checksum_help(skb); goto csum_failed; } /* update TX checksum flag */ first->tx_flags |= IGB_TX_FLAGS_CSUM; vlan_macip_lens = skb_checksum_start_offset(skb) - skb_network_offset(skb); no_csum: vlan_macip_lens |= skb_network_offset(skb) << E1000_ADVTXD_MACLEN_SHIFT; vlan_macip_lens |= first->tx_flags & IGB_TX_FLAGS_VLAN_MASK; igb_tx_ctxtdesc(tx_ring, first, vlan_macip_lens, type_tucmd, 0); } #define IGB_SET_FLAG(_input, _flag, _result) \ ((_flag <= _result) ? \ ((u32)(_input & _flag) * (_result / _flag)) : \ ((u32)(_input & _flag) / (_flag / _result))) static u32 igb_tx_cmd_type(struct sk_buff *skb, u32 tx_flags) { /* set type for advanced descriptor with frame checksum insertion */ u32 cmd_type = E1000_ADVTXD_DTYP_DATA | E1000_ADVTXD_DCMD_DEXT | E1000_ADVTXD_DCMD_IFCS; /* set HW vlan bit if vlan is present */ cmd_type |= IGB_SET_FLAG(tx_flags, IGB_TX_FLAGS_VLAN, (E1000_ADVTXD_DCMD_VLE)); /* set segmentation bits for TSO */ cmd_type |= IGB_SET_FLAG(tx_flags, IGB_TX_FLAGS_TSO, (E1000_ADVTXD_DCMD_TSE)); /* set timestamp bit if present */ cmd_type |= IGB_SET_FLAG(tx_flags, IGB_TX_FLAGS_TSTAMP, (E1000_ADVTXD_MAC_TSTAMP)); /* insert frame checksum */ cmd_type ^= IGB_SET_FLAG(skb->no_fcs, 1, E1000_ADVTXD_DCMD_IFCS); return cmd_type; } static void igb_tx_olinfo_status(struct igb_ring *tx_ring, union e1000_adv_tx_desc *tx_desc, u32 tx_flags, unsigned int paylen) { u32 olinfo_status = paylen << E1000_ADVTXD_PAYLEN_SHIFT; /* 82575 requires a unique index per ring */ if (test_bit(IGB_RING_FLAG_TX_CTX_IDX, &tx_ring->flags)) olinfo_status |= tx_ring->reg_idx << 4; /* insert L4 checksum */ olinfo_status |= IGB_SET_FLAG(tx_flags, IGB_TX_FLAGS_CSUM, (E1000_TXD_POPTS_TXSM << 8)); /* insert IPv4 checksum */ olinfo_status |= IGB_SET_FLAG(tx_flags, IGB_TX_FLAGS_IPV4, (E1000_TXD_POPTS_IXSM << 8)); tx_desc->read.olinfo_status = cpu_to_le32(olinfo_status); } static int __igb_maybe_stop_tx(struct igb_ring *tx_ring, const u16 size) { struct net_device *netdev = tx_ring->netdev; netif_stop_subqueue(netdev, tx_ring->queue_index); /* Herbert's original patch had: * smp_mb__after_netif_stop_queue(); * but since that doesn't exist yet, just open code it. */ smp_mb(); /* We need to check again in a case another CPU has just * made room available. */ if (igb_desc_unused(tx_ring) < size) return -EBUSY; /* A reprieve! */ netif_wake_subqueue(netdev, tx_ring->queue_index); u64_stats_update_begin(&tx_ring->tx_syncp2); tx_ring->tx_stats.restart_queue2++; u64_stats_update_end(&tx_ring->tx_syncp2); return 0; } static inline int igb_maybe_stop_tx(struct igb_ring *tx_ring, const u16 size) { if (igb_desc_unused(tx_ring) >= size) return 0; return __igb_maybe_stop_tx(tx_ring, size); } static int igb_tx_map(struct igb_ring *tx_ring, struct igb_tx_buffer *first, const u8 hdr_len) { struct sk_buff *skb = first->skb; struct igb_tx_buffer *tx_buffer; union e1000_adv_tx_desc *tx_desc; skb_frag_t *frag; dma_addr_t dma; unsigned int data_len, size; u32 tx_flags = first->tx_flags; u32 cmd_type = igb_tx_cmd_type(skb, tx_flags); u16 i = tx_ring->next_to_use; tx_desc = IGB_TX_DESC(tx_ring, i); igb_tx_olinfo_status(tx_ring, tx_desc, tx_flags, skb->len - hdr_len); size = skb_headlen(skb); data_len = skb->data_len; dma = dma_map_single(tx_ring->dev, skb->data, size, DMA_TO_DEVICE); tx_buffer = first; for (frag = &skb_shinfo(skb)->frags[0];; frag++) { if (dma_mapping_error(tx_ring->dev, dma)) goto dma_error; /* record length, and DMA address */ dma_unmap_len_set(tx_buffer, len, size); dma_unmap_addr_set(tx_buffer, dma, dma); tx_desc->read.buffer_addr = cpu_to_le64(dma); while (unlikely(size > IGB_MAX_DATA_PER_TXD)) { tx_desc->read.cmd_type_len = cpu_to_le32(cmd_type ^ IGB_MAX_DATA_PER_TXD); i++; tx_desc++; if (i == tx_ring->count) { tx_desc = IGB_TX_DESC(tx_ring, 0); i = 0; } tx_desc->read.olinfo_status = 0; dma += IGB_MAX_DATA_PER_TXD; size -= IGB_MAX_DATA_PER_TXD; tx_desc->read.buffer_addr = cpu_to_le64(dma); } if (likely(!data_len)) break; tx_desc->read.cmd_type_len = cpu_to_le32(cmd_type ^ size); i++; tx_desc++; if (i == tx_ring->count) { tx_desc = IGB_TX_DESC(tx_ring, 0); i = 0; } tx_desc->read.olinfo_status = 0; size = skb_frag_size(frag); data_len -= size; dma = skb_frag_dma_map(tx_ring->dev, frag, 0, size, DMA_TO_DEVICE); tx_buffer = &tx_ring->tx_buffer_info[i]; } /* write last descriptor with RS and EOP bits */ cmd_type |= size | IGB_TXD_DCMD; tx_desc->read.cmd_type_len = cpu_to_le32(cmd_type); netdev_tx_sent_queue(txring_txq(tx_ring), first->bytecount); /* set the timestamp */ first->time_stamp = jiffies; skb_tx_timestamp(skb); /* Force memory writes to complete before letting h/w know there * are new descriptors to fetch. (Only applicable for weak-ordered * memory model archs, such as IA-64). * * We also need this memory barrier to make certain all of the * status bits have been updated before next_to_watch is written. */ dma_wmb(); /* set next_to_watch value indicating a packet is present */ first->next_to_watch = tx_desc; i++; if (i == tx_ring->count) i = 0; tx_ring->next_to_use = i; /* Make sure there is space in the ring for the next send. */ igb_maybe_stop_tx(tx_ring, DESC_NEEDED); if (netif_xmit_stopped(txring_txq(tx_ring)) || !netdev_xmit_more()) { writel(i, tx_ring->tail); } return 0; dma_error: dev_err(tx_ring->dev, "TX DMA map failed\n"); tx_buffer = &tx_ring->tx_buffer_info[i]; /* clear dma mappings for failed tx_buffer_info map */ while (tx_buffer != first) { if (dma_unmap_len(tx_buffer, len)) dma_unmap_page(tx_ring->dev, dma_unmap_addr(tx_buffer, dma), dma_unmap_len(tx_buffer, len), DMA_TO_DEVICE); dma_unmap_len_set(tx_buffer, len, 0); if (i-- == 0) i += tx_ring->count; tx_buffer = &tx_ring->tx_buffer_info[i]; } if (dma_unmap_len(tx_buffer, len)) dma_unmap_single(tx_ring->dev, dma_unmap_addr(tx_buffer, dma), dma_unmap_len(tx_buffer, len), DMA_TO_DEVICE); dma_unmap_len_set(tx_buffer, len, 0); dev_kfree_skb_any(tx_buffer->skb); tx_buffer->skb = NULL; tx_ring->next_to_use = i; return -1; } int igb_xmit_xdp_ring(struct igb_adapter *adapter, struct igb_ring *tx_ring, struct xdp_frame *xdpf) { struct skb_shared_info *sinfo = xdp_get_shared_info_from_frame(xdpf); u8 nr_frags = unlikely(xdp_frame_has_frags(xdpf)) ? sinfo->nr_frags : 0; u16 count, i, index = tx_ring->next_to_use; struct igb_tx_buffer *tx_head = &tx_ring->tx_buffer_info[index]; struct igb_tx_buffer *tx_buffer = tx_head; union e1000_adv_tx_desc *tx_desc = IGB_TX_DESC(tx_ring, index); u32 len = xdpf->len, cmd_type, olinfo_status; void *data = xdpf->data; count = TXD_USE_COUNT(len); for (i = 0; i < nr_frags; i++) count += TXD_USE_COUNT(skb_frag_size(&sinfo->frags[i])); if (igb_maybe_stop_tx(tx_ring, count + 3)) return IGB_XDP_CONSUMED; i = 0; /* record the location of the first descriptor for this packet */ tx_head->bytecount = xdp_get_frame_len(xdpf); tx_head->type = IGB_TYPE_XDP; tx_head->gso_segs = 1; tx_head->xdpf = xdpf; olinfo_status = tx_head->bytecount << E1000_ADVTXD_PAYLEN_SHIFT; /* 82575 requires a unique index per ring */ if (test_bit(IGB_RING_FLAG_TX_CTX_IDX, &tx_ring->flags)) olinfo_status |= tx_ring->reg_idx << 4; tx_desc->read.olinfo_status = cpu_to_le32(olinfo_status); for (;;) { dma_addr_t dma; dma = dma_map_single(tx_ring->dev, data, len, DMA_TO_DEVICE); if (dma_mapping_error(tx_ring->dev, dma)) goto unmap; /* record length, and DMA address */ dma_unmap_len_set(tx_buffer, len, len); dma_unmap_addr_set(tx_buffer, dma, dma); /* put descriptor type bits */ cmd_type = E1000_ADVTXD_DTYP_DATA | E1000_ADVTXD_DCMD_DEXT | E1000_ADVTXD_DCMD_IFCS | len; tx_desc->read.cmd_type_len = cpu_to_le32(cmd_type); tx_desc->read.buffer_addr = cpu_to_le64(dma); tx_buffer->protocol = 0; if (++index == tx_ring->count) index = 0; if (i == nr_frags) break; tx_buffer = &tx_ring->tx_buffer_info[index]; tx_desc = IGB_TX_DESC(tx_ring, index); tx_desc->read.olinfo_status = 0; data = skb_frag_address(&sinfo->frags[i]); len = skb_frag_size(&sinfo->frags[i]); i++; } tx_desc->read.cmd_type_len |= cpu_to_le32(IGB_TXD_DCMD); netdev_tx_sent_queue(txring_txq(tx_ring), tx_head->bytecount); /* set the timestamp */ tx_head->time_stamp = jiffies; /* Avoid any potential race with xdp_xmit and cleanup */ smp_wmb(); /* set next_to_watch value indicating a packet is present */ tx_head->next_to_watch = tx_desc; tx_ring->next_to_use = index; /* Make sure there is space in the ring for the next send. */ igb_maybe_stop_tx(tx_ring, DESC_NEEDED); if (netif_xmit_stopped(txring_txq(tx_ring)) || !netdev_xmit_more()) writel(index, tx_ring->tail); return IGB_XDP_TX; unmap: for (;;) { tx_buffer = &tx_ring->tx_buffer_info[index]; if (dma_unmap_len(tx_buffer, len)) dma_unmap_page(tx_ring->dev, dma_unmap_addr(tx_buffer, dma), dma_unmap_len(tx_buffer, len), DMA_TO_DEVICE); dma_unmap_len_set(tx_buffer, len, 0); if (tx_buffer == tx_head) break; if (!index) index += tx_ring->count; index--; } return IGB_XDP_CONSUMED; } netdev_tx_t igb_xmit_frame_ring(struct sk_buff *skb, struct igb_ring *tx_ring) { struct igb_tx_buffer *first; int tso; u32 tx_flags = 0; unsigned short f; u16 count = TXD_USE_COUNT(skb_headlen(skb)); __be16 protocol = vlan_get_protocol(skb); u8 hdr_len = 0; /* need: 1 descriptor per page * PAGE_SIZE/IGB_MAX_DATA_PER_TXD, * + 1 desc for skb_headlen/IGB_MAX_DATA_PER_TXD, * + 2 desc gap to keep tail from touching head, * + 1 desc for context descriptor, * otherwise try next time */ for (f = 0; f < skb_shinfo(skb)->nr_frags; f++) count += TXD_USE_COUNT(skb_frag_size( &skb_shinfo(skb)->frags[f])); if (igb_maybe_stop_tx(tx_ring, count + 3)) { /* this is a hard error */ return NETDEV_TX_BUSY; } /* record the location of the first descriptor for this packet */ first = &tx_ring->tx_buffer_info[tx_ring->next_to_use]; first->type = IGB_TYPE_SKB; first->skb = skb; first->bytecount = skb->len; first->gso_segs = 1; if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP)) { struct igb_adapter *adapter = netdev_priv(tx_ring->netdev); if (adapter->tstamp_config.tx_type == HWTSTAMP_TX_ON && !test_and_set_bit_lock(__IGB_PTP_TX_IN_PROGRESS, &adapter->state)) { skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS; tx_flags |= IGB_TX_FLAGS_TSTAMP; adapter->ptp_tx_skb = skb_get(skb); adapter->ptp_tx_start = jiffies; if (adapter->hw.mac.type == e1000_82576) schedule_work(&adapter->ptp_tx_work); } else { adapter->tx_hwtstamp_skipped++; } } if (skb_vlan_tag_present(skb)) { tx_flags |= IGB_TX_FLAGS_VLAN; tx_flags |= (skb_vlan_tag_get(skb) << IGB_TX_FLAGS_VLAN_SHIFT); } /* record initial flags and protocol */ first->tx_flags = tx_flags; first->protocol = protocol; tso = igb_tso(tx_ring, first, &hdr_len); if (tso < 0) goto out_drop; else if (!tso) igb_tx_csum(tx_ring, first); if (igb_tx_map(tx_ring, first, hdr_len)) goto cleanup_tx_tstamp; return NETDEV_TX_OK; out_drop: dev_kfree_skb_any(first->skb); first->skb = NULL; cleanup_tx_tstamp: if (unlikely(tx_flags & IGB_TX_FLAGS_TSTAMP)) { struct igb_adapter *adapter = netdev_priv(tx_ring->netdev); dev_kfree_skb_any(adapter->ptp_tx_skb); adapter->ptp_tx_skb = NULL; if (adapter->hw.mac.type == e1000_82576) cancel_work_sync(&adapter->ptp_tx_work); clear_bit_unlock(__IGB_PTP_TX_IN_PROGRESS, &adapter->state); } return NETDEV_TX_OK; } static inline struct igb_ring *igb_tx_queue_mapping(struct igb_adapter *adapter, struct sk_buff *skb) { unsigned int r_idx = skb->queue_mapping; if (r_idx >= adapter->num_tx_queues) r_idx = r_idx % adapter->num_tx_queues; return adapter->tx_ring[r_idx]; } static netdev_tx_t igb_xmit_frame(struct sk_buff *skb, struct net_device *netdev) { struct igb_adapter *adapter = netdev_priv(netdev); /* The minimum packet size with TCTL.PSP set is 17 so pad the skb * in order to meet this minimum size requirement. */ if (skb_put_padto(skb, 17)) return NETDEV_TX_OK; return igb_xmit_frame_ring(skb, igb_tx_queue_mapping(adapter, skb)); } /** * igb_tx_timeout - Respond to a Tx Hang * @netdev: network interface device structure * @txqueue: number of the Tx queue that hung (unused) **/ static void igb_tx_timeout(struct net_device *netdev, unsigned int __always_unused txqueue) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; /* Do the reset outside of interrupt context */ adapter->tx_timeout_count++; if (hw->mac.type >= e1000_82580) hw->dev_spec._82575.global_device_reset = true; schedule_work(&adapter->reset_task); wr32(E1000_EICS, (adapter->eims_enable_mask & ~adapter->eims_other)); } static void igb_reset_task(struct work_struct *work) { struct igb_adapter *adapter; adapter = container_of(work, struct igb_adapter, reset_task); rtnl_lock(); /* If we're already down or resetting, just bail */ if (test_bit(__IGB_DOWN, &adapter->state) || test_bit(__IGB_RESETTING, &adapter->state)) { rtnl_unlock(); return; } igb_dump(adapter); netdev_err(adapter->netdev, "Reset adapter\n"); igb_reinit_locked(adapter); rtnl_unlock(); } /** * igb_get_stats64 - Get System Network Statistics * @netdev: network interface device structure * @stats: rtnl_link_stats64 pointer **/ static void igb_get_stats64(struct net_device *netdev, struct rtnl_link_stats64 *stats) { struct igb_adapter *adapter = netdev_priv(netdev); spin_lock(&adapter->stats64_lock); igb_update_stats(adapter); memcpy(stats, &adapter->stats64, sizeof(*stats)); spin_unlock(&adapter->stats64_lock); } /** * igb_change_mtu - Change the Maximum Transfer Unit * @netdev: network interface device structure * @new_mtu: new value for maximum frame size * * Returns 0 on success, negative on failure **/ static int igb_change_mtu(struct net_device *netdev, int new_mtu) { struct igb_adapter *adapter = netdev_priv(netdev); int max_frame = new_mtu + IGB_ETH_PKT_HDR_PAD; if (adapter->xdp_prog) { int i; for (i = 0; i < adapter->num_rx_queues; i++) { struct igb_ring *ring = adapter->rx_ring[i]; if (max_frame > igb_rx_bufsz(ring)) { netdev_warn(adapter->netdev, "Requested MTU size is not supported with XDP. Max frame size is %d\n", max_frame); return -EINVAL; } } } /* adjust max frame to be at least the size of a standard frame */ if (max_frame < (ETH_FRAME_LEN + ETH_FCS_LEN)) max_frame = ETH_FRAME_LEN + ETH_FCS_LEN; while (test_and_set_bit(__IGB_RESETTING, &adapter->state)) usleep_range(1000, 2000); /* igb_down has a dependency on max_frame_size */ adapter->max_frame_size = max_frame; if (netif_running(netdev)) igb_down(adapter); netdev_dbg(netdev, "changing MTU from %d to %d\n", netdev->mtu, new_mtu); netdev->mtu = new_mtu; if (netif_running(netdev)) igb_up(adapter); else igb_reset(adapter); clear_bit(__IGB_RESETTING, &adapter->state); return 0; } /** * igb_update_stats - Update the board statistics counters * @adapter: board private structure **/ void igb_update_stats(struct igb_adapter *adapter) { struct rtnl_link_stats64 *net_stats = &adapter->stats64; struct e1000_hw *hw = &adapter->hw; struct pci_dev *pdev = adapter->pdev; u32 reg, mpc; int i; u64 bytes, packets; unsigned int start; u64 _bytes, _packets; /* Prevent stats update while adapter is being reset, or if the pci * connection is down. */ if (adapter->link_speed == 0) return; if (pci_channel_offline(pdev)) return; bytes = 0; packets = 0; rcu_read_lock(); for (i = 0; i < adapter->num_rx_queues; i++) { struct igb_ring *ring = adapter->rx_ring[i]; u32 rqdpc = rd32(E1000_RQDPC(i)); if (hw->mac.type >= e1000_i210) wr32(E1000_RQDPC(i), 0); if (rqdpc) { ring->rx_stats.drops += rqdpc; net_stats->rx_fifo_errors += rqdpc; } do { start = u64_stats_fetch_begin(&ring->rx_syncp); _bytes = ring->rx_stats.bytes; _packets = ring->rx_stats.packets; } while (u64_stats_fetch_retry(&ring->rx_syncp, start)); bytes += _bytes; packets += _packets; } net_stats->rx_bytes = bytes; net_stats->rx_packets = packets; bytes = 0; packets = 0; for (i = 0; i < adapter->num_tx_queues; i++) { struct igb_ring *ring = adapter->tx_ring[i]; do { start = u64_stats_fetch_begin(&ring->tx_syncp); _bytes = ring->tx_stats.bytes; _packets = ring->tx_stats.packets; } while (u64_stats_fetch_retry(&ring->tx_syncp, start)); bytes += _bytes; packets += _packets; } net_stats->tx_bytes = bytes; net_stats->tx_packets = packets; rcu_read_unlock(); /* read stats registers */ adapter->stats.crcerrs += rd32(E1000_CRCERRS); adapter->stats.gprc += rd32(E1000_GPRC); adapter->stats.gorc += rd32(E1000_GORCL); rd32(E1000_GORCH); /* clear GORCL */ adapter->stats.bprc += rd32(E1000_BPRC); adapter->stats.mprc += rd32(E1000_MPRC); adapter->stats.roc += rd32(E1000_ROC); adapter->stats.prc64 += rd32(E1000_PRC64); adapter->stats.prc127 += rd32(E1000_PRC127); adapter->stats.prc255 += rd32(E1000_PRC255); adapter->stats.prc511 += rd32(E1000_PRC511); adapter->stats.prc1023 += rd32(E1000_PRC1023); adapter->stats.prc1522 += rd32(E1000_PRC1522); adapter->stats.symerrs += rd32(E1000_SYMERRS); adapter->stats.sec += rd32(E1000_SEC); mpc = rd32(E1000_MPC); adapter->stats.mpc += mpc; net_stats->rx_fifo_errors += mpc; adapter->stats.scc += rd32(E1000_SCC); adapter->stats.ecol += rd32(E1000_ECOL); adapter->stats.mcc += rd32(E1000_MCC); adapter->stats.latecol += rd32(E1000_LATECOL); adapter->stats.dc += rd32(E1000_DC); adapter->stats.rlec += rd32(E1000_RLEC); adapter->stats.xonrxc += rd32(E1000_XONRXC); adapter->stats.xontxc += rd32(E1000_XONTXC); adapter->stats.xoffrxc += rd32(E1000_XOFFRXC); adapter->stats.xofftxc += rd32(E1000_XOFFTXC); adapter->stats.fcruc += rd32(E1000_FCRUC); adapter->stats.gptc += rd32(E1000_GPTC); adapter->stats.gotc += rd32(E1000_GOTCL); rd32(E1000_GOTCH); /* clear GOTCL */ adapter->stats.rnbc += rd32(E1000_RNBC); adapter->stats.ruc += rd32(E1000_RUC); adapter->stats.rfc += rd32(E1000_RFC); adapter->stats.rjc += rd32(E1000_RJC); adapter->stats.tor += rd32(E1000_TORH); adapter->stats.tot += rd32(E1000_TOTH); adapter->stats.tpr += rd32(E1000_TPR); adapter->stats.ptc64 += rd32(E1000_PTC64); adapter->stats.ptc127 += rd32(E1000_PTC127); adapter->stats.ptc255 += rd32(E1000_PTC255); adapter->stats.ptc511 += rd32(E1000_PTC511); adapter->stats.ptc1023 += rd32(E1000_PTC1023); adapter->stats.ptc1522 += rd32(E1000_PTC1522); adapter->stats.mptc += rd32(E1000_MPTC); adapter->stats.bptc += rd32(E1000_BPTC); adapter->stats.tpt += rd32(E1000_TPT); adapter->stats.colc += rd32(E1000_COLC); adapter->stats.algnerrc += rd32(E1000_ALGNERRC); /* read internal phy specific stats */ reg = rd32(E1000_CTRL_EXT); if (!(reg & E1000_CTRL_EXT_LINK_MODE_MASK)) { adapter->stats.rxerrc += rd32(E1000_RXERRC); /* this stat has invalid values on i210/i211 */ if ((hw->mac.type != e1000_i210) && (hw->mac.type != e1000_i211)) adapter->stats.tncrs += rd32(E1000_TNCRS); } adapter->stats.tsctc += rd32(E1000_TSCTC); adapter->stats.tsctfc += rd32(E1000_TSCTFC); adapter->stats.iac += rd32(E1000_IAC); adapter->stats.icrxoc += rd32(E1000_ICRXOC); adapter->stats.icrxptc += rd32(E1000_ICRXPTC); adapter->stats.icrxatc += rd32(E1000_ICRXATC); adapter->stats.ictxptc += rd32(E1000_ICTXPTC); adapter->stats.ictxatc += rd32(E1000_ICTXATC); adapter->stats.ictxqec += rd32(E1000_ICTXQEC); adapter->stats.ictxqmtc += rd32(E1000_ICTXQMTC); adapter->stats.icrxdmtc += rd32(E1000_ICRXDMTC); /* Fill out the OS statistics structure */ net_stats->multicast = adapter->stats.mprc; net_stats->collisions = adapter->stats.colc; /* Rx Errors */ /* RLEC on some newer hardware can be incorrect so build * our own version based on RUC and ROC */ net_stats->rx_errors = adapter->stats.rxerrc + adapter->stats.crcerrs + adapter->stats.algnerrc + adapter->stats.ruc + adapter->stats.roc + adapter->stats.cexterr; net_stats->rx_length_errors = adapter->stats.ruc + adapter->stats.roc; net_stats->rx_crc_errors = adapter->stats.crcerrs; net_stats->rx_frame_errors = adapter->stats.algnerrc; net_stats->rx_missed_errors = adapter->stats.mpc; /* Tx Errors */ net_stats->tx_errors = adapter->stats.ecol + adapter->stats.latecol; net_stats->tx_aborted_errors = adapter->stats.ecol; net_stats->tx_window_errors = adapter->stats.latecol; net_stats->tx_carrier_errors = adapter->stats.tncrs; /* Tx Dropped needs to be maintained elsewhere */ /* Management Stats */ adapter->stats.mgptc += rd32(E1000_MGTPTC); adapter->stats.mgprc += rd32(E1000_MGTPRC); adapter->stats.mgpdc += rd32(E1000_MGTPDC); /* OS2BMC Stats */ reg = rd32(E1000_MANC); if (reg & E1000_MANC_EN_BMC2OS) { adapter->stats.o2bgptc += rd32(E1000_O2BGPTC); adapter->stats.o2bspc += rd32(E1000_O2BSPC); adapter->stats.b2ospc += rd32(E1000_B2OSPC); adapter->stats.b2ogprc += rd32(E1000_B2OGPRC); } } static void igb_perout(struct igb_adapter *adapter, int tsintr_tt) { int pin = ptp_find_pin(adapter->ptp_clock, PTP_PF_PEROUT, tsintr_tt); struct e1000_hw *hw = &adapter->hw; struct timespec64 ts; u32 tsauxc; if (pin < 0 || pin >= IGB_N_SDP) return; spin_lock(&adapter->tmreg_lock); if (hw->mac.type == e1000_82580 || hw->mac.type == e1000_i354 || hw->mac.type == e1000_i350) { s64 ns = timespec64_to_ns(&adapter->perout[tsintr_tt].period); u32 systiml, systimh, level_mask, level, rem; u64 systim, now; /* read systim registers in sequence */ rd32(E1000_SYSTIMR); systiml = rd32(E1000_SYSTIML); systimh = rd32(E1000_SYSTIMH); systim = (((u64)(systimh & 0xFF)) << 32) | ((u64)systiml); now = timecounter_cyc2time(&adapter->tc, systim); if (pin < 2) { level_mask = (tsintr_tt == 1) ? 0x80000 : 0x40000; level = (rd32(E1000_CTRL) & level_mask) ? 1 : 0; } else { level_mask = (tsintr_tt == 1) ? 0x80 : 0x40; level = (rd32(E1000_CTRL_EXT) & level_mask) ? 1 : 0; } div_u64_rem(now, ns, &rem); systim = systim + (ns - rem); /* synchronize pin level with rising/falling edges */ div_u64_rem(now, ns << 1, &rem); if (rem < ns) { /* first half of period */ if (level == 0) { /* output is already low, skip this period */ systim += ns; pr_notice("igb: periodic output on %s missed falling edge\n", adapter->sdp_config[pin].name); } } else { /* second half of period */ if (level == 1) { /* output is already high, skip this period */ systim += ns; pr_notice("igb: periodic output on %s missed rising edge\n", adapter->sdp_config[pin].name); } } /* for this chip family tv_sec is the upper part of the binary value, * so not seconds */ ts.tv_nsec = (u32)systim; ts.tv_sec = ((u32)(systim >> 32)) & 0xFF; } else { ts = timespec64_add(adapter->perout[tsintr_tt].start, adapter->perout[tsintr_tt].period); } /* u32 conversion of tv_sec is safe until y2106 */ wr32((tsintr_tt == 1) ? E1000_TRGTTIML1 : E1000_TRGTTIML0, ts.tv_nsec); wr32((tsintr_tt == 1) ? E1000_TRGTTIMH1 : E1000_TRGTTIMH0, (u32)ts.tv_sec); tsauxc = rd32(E1000_TSAUXC); tsauxc |= TSAUXC_EN_TT0; wr32(E1000_TSAUXC, tsauxc); adapter->perout[tsintr_tt].start = ts; spin_unlock(&adapter->tmreg_lock); } static void igb_extts(struct igb_adapter *adapter, int tsintr_tt) { int pin = ptp_find_pin(adapter->ptp_clock, PTP_PF_EXTTS, tsintr_tt); int auxstmpl = (tsintr_tt == 1) ? E1000_AUXSTMPL1 : E1000_AUXSTMPL0; int auxstmph = (tsintr_tt == 1) ? E1000_AUXSTMPH1 : E1000_AUXSTMPH0; struct e1000_hw *hw = &adapter->hw; struct ptp_clock_event event; struct timespec64 ts; unsigned long flags; if (pin < 0 || pin >= IGB_N_SDP) return; if (hw->mac.type == e1000_82580 || hw->mac.type == e1000_i354 || hw->mac.type == e1000_i350) { u64 ns = rd32(auxstmpl); ns += ((u64)(rd32(auxstmph) & 0xFF)) << 32; spin_lock_irqsave(&adapter->tmreg_lock, flags); ns = timecounter_cyc2time(&adapter->tc, ns); spin_unlock_irqrestore(&adapter->tmreg_lock, flags); ts = ns_to_timespec64(ns); } else { ts.tv_nsec = rd32(auxstmpl); ts.tv_sec = rd32(auxstmph); } event.type = PTP_CLOCK_EXTTS; event.index = tsintr_tt; event.timestamp = ts.tv_sec * 1000000000ULL + ts.tv_nsec; ptp_clock_event(adapter->ptp_clock, &event); } static void igb_tsync_interrupt(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 ack = 0, tsicr = rd32(E1000_TSICR); struct ptp_clock_event event; if (tsicr & TSINTR_SYS_WRAP) { event.type = PTP_CLOCK_PPS; if (adapter->ptp_caps.pps) ptp_clock_event(adapter->ptp_clock, &event); ack |= TSINTR_SYS_WRAP; } if (tsicr & E1000_TSICR_TXTS) { /* retrieve hardware timestamp */ schedule_work(&adapter->ptp_tx_work); ack |= E1000_TSICR_TXTS; } if (tsicr & TSINTR_TT0) { igb_perout(adapter, 0); ack |= TSINTR_TT0; } if (tsicr & TSINTR_TT1) { igb_perout(adapter, 1); ack |= TSINTR_TT1; } if (tsicr & TSINTR_AUTT0) { igb_extts(adapter, 0); ack |= TSINTR_AUTT0; } if (tsicr & TSINTR_AUTT1) { igb_extts(adapter, 1); ack |= TSINTR_AUTT1; } /* acknowledge the interrupts */ wr32(E1000_TSICR, ack); } static irqreturn_t igb_msix_other(int irq, void *data) { struct igb_adapter *adapter = data; struct e1000_hw *hw = &adapter->hw; u32 icr = rd32(E1000_ICR); /* reading ICR causes bit 31 of EICR to be cleared */ if (icr & E1000_ICR_DRSTA) schedule_work(&adapter->reset_task); if (icr & E1000_ICR_DOUTSYNC) { /* HW is reporting DMA is out of sync */ adapter->stats.doosync++; /* The DMA Out of Sync is also indication of a spoof event * in IOV mode. Check the Wrong VM Behavior register to * see if it is really a spoof event. */ igb_check_wvbr(adapter); } /* Check for a mailbox event */ if (icr & E1000_ICR_VMMB) igb_msg_task(adapter); if (icr & E1000_ICR_LSC) { hw->mac.get_link_status = 1; /* guard against interrupt when we're going down */ if (!test_bit(__IGB_DOWN, &adapter->state)) mod_timer(&adapter->watchdog_timer, jiffies + 1); } if (icr & E1000_ICR_TS) igb_tsync_interrupt(adapter); wr32(E1000_EIMS, adapter->eims_other); return IRQ_HANDLED; } static void igb_write_itr(struct igb_q_vector *q_vector) { struct igb_adapter *adapter = q_vector->adapter; u32 itr_val = q_vector->itr_val & 0x7FFC; if (!q_vector->set_itr) return; if (!itr_val) itr_val = 0x4; if (adapter->hw.mac.type == e1000_82575) itr_val |= itr_val << 16; else itr_val |= E1000_EITR_CNT_IGNR; writel(itr_val, q_vector->itr_register); q_vector->set_itr = 0; } static irqreturn_t igb_msix_ring(int irq, void *data) { struct igb_q_vector *q_vector = data; /* Write the ITR value calculated from the previous interrupt. */ igb_write_itr(q_vector); napi_schedule(&q_vector->napi); return IRQ_HANDLED; } #ifdef CONFIG_IGB_DCA static void igb_update_tx_dca(struct igb_adapter *adapter, struct igb_ring *tx_ring, int cpu) { struct e1000_hw *hw = &adapter->hw; u32 txctrl = dca3_get_tag(tx_ring->dev, cpu); if (hw->mac.type != e1000_82575) txctrl <<= E1000_DCA_TXCTRL_CPUID_SHIFT; /* We can enable relaxed ordering for reads, but not writes when * DCA is enabled. This is due to a known issue in some chipsets * which will cause the DCA tag to be cleared. */ txctrl |= E1000_DCA_TXCTRL_DESC_RRO_EN | E1000_DCA_TXCTRL_DATA_RRO_EN | E1000_DCA_TXCTRL_DESC_DCA_EN; wr32(E1000_DCA_TXCTRL(tx_ring->reg_idx), txctrl); } static void igb_update_rx_dca(struct igb_adapter *adapter, struct igb_ring *rx_ring, int cpu) { struct e1000_hw *hw = &adapter->hw; u32 rxctrl = dca3_get_tag(&adapter->pdev->dev, cpu); if (hw->mac.type != e1000_82575) rxctrl <<= E1000_DCA_RXCTRL_CPUID_SHIFT; /* We can enable relaxed ordering for reads, but not writes when * DCA is enabled. This is due to a known issue in some chipsets * which will cause the DCA tag to be cleared. */ rxctrl |= E1000_DCA_RXCTRL_DESC_RRO_EN | E1000_DCA_RXCTRL_DESC_DCA_EN; wr32(E1000_DCA_RXCTRL(rx_ring->reg_idx), rxctrl); } static void igb_update_dca(struct igb_q_vector *q_vector) { struct igb_adapter *adapter = q_vector->adapter; int cpu = get_cpu(); if (q_vector->cpu == cpu) goto out_no_update; if (q_vector->tx.ring) igb_update_tx_dca(adapter, q_vector->tx.ring, cpu); if (q_vector->rx.ring) igb_update_rx_dca(adapter, q_vector->rx.ring, cpu); q_vector->cpu = cpu; out_no_update: put_cpu(); } static void igb_setup_dca(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; int i; if (!(adapter->flags & IGB_FLAG_DCA_ENABLED)) return; /* Always use CB2 mode, difference is masked in the CB driver. */ wr32(E1000_DCA_CTRL, E1000_DCA_CTRL_DCA_MODE_CB2); for (i = 0; i < adapter->num_q_vectors; i++) { adapter->q_vector[i]->cpu = -1; igb_update_dca(adapter->q_vector[i]); } } static int __igb_notify_dca(struct device *dev, void *data) { struct net_device *netdev = dev_get_drvdata(dev); struct igb_adapter *adapter = netdev_priv(netdev); struct pci_dev *pdev = adapter->pdev; struct e1000_hw *hw = &adapter->hw; unsigned long event = *(unsigned long *)data; switch (event) { case DCA_PROVIDER_ADD: /* if already enabled, don't do it again */ if (adapter->flags & IGB_FLAG_DCA_ENABLED) break; if (dca_add_requester(dev) == 0) { adapter->flags |= IGB_FLAG_DCA_ENABLED; dev_info(&pdev->dev, "DCA enabled\n"); igb_setup_dca(adapter); break; } fallthrough; /* since DCA is disabled. */ case DCA_PROVIDER_REMOVE: if (adapter->flags & IGB_FLAG_DCA_ENABLED) { /* without this a class_device is left * hanging around in the sysfs model */ dca_remove_requester(dev); dev_info(&pdev->dev, "DCA disabled\n"); adapter->flags &= ~IGB_FLAG_DCA_ENABLED; wr32(E1000_DCA_CTRL, E1000_DCA_CTRL_DCA_MODE_DISABLE); } break; } return 0; } static int igb_notify_dca(struct notifier_block *nb, unsigned long event, void *p) { int ret_val; ret_val = driver_for_each_device(&igb_driver.driver, NULL, &event, __igb_notify_dca); return ret_val ? NOTIFY_BAD : NOTIFY_DONE; } #endif /* CONFIG_IGB_DCA */ #ifdef CONFIG_PCI_IOV static int igb_vf_configure(struct igb_adapter *adapter, int vf) { unsigned char mac_addr[ETH_ALEN]; eth_zero_addr(mac_addr); igb_set_vf_mac(adapter, vf, mac_addr); /* By default spoof check is enabled for all VFs */ adapter->vf_data[vf].spoofchk_enabled = true; /* By default VFs are not trusted */ adapter->vf_data[vf].trusted = false; return 0; } #endif static void igb_ping_all_vfs(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 ping; int i; for (i = 0 ; i < adapter->vfs_allocated_count; i++) { ping = E1000_PF_CONTROL_MSG; if (adapter->vf_data[i].flags & IGB_VF_FLAG_CTS) ping |= E1000_VT_MSGTYPE_CTS; igb_write_mbx(hw, &ping, 1, i); } } static int igb_set_vf_promisc(struct igb_adapter *adapter, u32 *msgbuf, u32 vf) { struct e1000_hw *hw = &adapter->hw; u32 vmolr = rd32(E1000_VMOLR(vf)); struct vf_data_storage *vf_data = &adapter->vf_data[vf]; vf_data->flags &= ~(IGB_VF_FLAG_UNI_PROMISC | IGB_VF_FLAG_MULTI_PROMISC); vmolr &= ~(E1000_VMOLR_ROPE | E1000_VMOLR_ROMPE | E1000_VMOLR_MPME); if (*msgbuf & E1000_VF_SET_PROMISC_MULTICAST) { vmolr |= E1000_VMOLR_MPME; vf_data->flags |= IGB_VF_FLAG_MULTI_PROMISC; *msgbuf &= ~E1000_VF_SET_PROMISC_MULTICAST; } else { /* if we have hashes and we are clearing a multicast promisc * flag we need to write the hashes to the MTA as this step * was previously skipped */ if (vf_data->num_vf_mc_hashes > 30) { vmolr |= E1000_VMOLR_MPME; } else if (vf_data->num_vf_mc_hashes) { int j; vmolr |= E1000_VMOLR_ROMPE; for (j = 0; j < vf_data->num_vf_mc_hashes; j++) igb_mta_set(hw, vf_data->vf_mc_hashes[j]); } } wr32(E1000_VMOLR(vf), vmolr); /* there are flags left unprocessed, likely not supported */ if (*msgbuf & E1000_VT_MSGINFO_MASK) return -EINVAL; return 0; } static int igb_set_vf_multicasts(struct igb_adapter *adapter, u32 *msgbuf, u32 vf) { int n = (msgbuf[0] & E1000_VT_MSGINFO_MASK) >> E1000_VT_MSGINFO_SHIFT; u16 *hash_list = (u16 *)&msgbuf[1]; struct vf_data_storage *vf_data = &adapter->vf_data[vf]; int i; /* salt away the number of multicast addresses assigned * to this VF for later use to restore when the PF multi cast * list changes */ vf_data->num_vf_mc_hashes = n; /* only up to 30 hash values supported */ if (n > 30) n = 30; /* store the hashes for later use */ for (i = 0; i < n; i++) vf_data->vf_mc_hashes[i] = hash_list[i]; /* Flush and reset the mta with the new values */ igb_set_rx_mode(adapter->netdev); return 0; } static void igb_restore_vf_multicasts(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; struct vf_data_storage *vf_data; int i, j; for (i = 0; i < adapter->vfs_allocated_count; i++) { u32 vmolr = rd32(E1000_VMOLR(i)); vmolr &= ~(E1000_VMOLR_ROMPE | E1000_VMOLR_MPME); vf_data = &adapter->vf_data[i]; if ((vf_data->num_vf_mc_hashes > 30) || (vf_data->flags & IGB_VF_FLAG_MULTI_PROMISC)) { vmolr |= E1000_VMOLR_MPME; } else if (vf_data->num_vf_mc_hashes) { vmolr |= E1000_VMOLR_ROMPE; for (j = 0; j < vf_data->num_vf_mc_hashes; j++) igb_mta_set(hw, vf_data->vf_mc_hashes[j]); } wr32(E1000_VMOLR(i), vmolr); } } static void igb_clear_vf_vfta(struct igb_adapter *adapter, u32 vf) { struct e1000_hw *hw = &adapter->hw; u32 pool_mask, vlvf_mask, i; /* create mask for VF and other pools */ pool_mask = E1000_VLVF_POOLSEL_MASK; vlvf_mask = BIT(E1000_VLVF_POOLSEL_SHIFT + vf); /* drop PF from pool bits */ pool_mask &= ~BIT(E1000_VLVF_POOLSEL_SHIFT + adapter->vfs_allocated_count); /* Find the vlan filter for this id */ for (i = E1000_VLVF_ARRAY_SIZE; i--;) { u32 vlvf = rd32(E1000_VLVF(i)); u32 vfta_mask, vid, vfta; /* remove the vf from the pool */ if (!(vlvf & vlvf_mask)) continue; /* clear out bit from VLVF */ vlvf ^= vlvf_mask; /* if other pools are present, just remove ourselves */ if (vlvf & pool_mask) goto update_vlvfb; /* if PF is present, leave VFTA */ if (vlvf & E1000_VLVF_POOLSEL_MASK) goto update_vlvf; vid = vlvf & E1000_VLVF_VLANID_MASK; vfta_mask = BIT(vid % 32); /* clear bit from VFTA */ vfta = adapter->shadow_vfta[vid / 32]; if (vfta & vfta_mask) hw->mac.ops.write_vfta(hw, vid / 32, vfta ^ vfta_mask); update_vlvf: /* clear pool selection enable */ if (adapter->flags & IGB_FLAG_VLAN_PROMISC) vlvf &= E1000_VLVF_POOLSEL_MASK; else vlvf = 0; update_vlvfb: /* clear pool bits */ wr32(E1000_VLVF(i), vlvf); } } static int igb_find_vlvf_entry(struct e1000_hw *hw, u32 vlan) { u32 vlvf; int idx; /* short cut the special case */ if (vlan == 0) return 0; /* Search for the VLAN id in the VLVF entries */ for (idx = E1000_VLVF_ARRAY_SIZE; --idx;) { vlvf = rd32(E1000_VLVF(idx)); if ((vlvf & VLAN_VID_MASK) == vlan) break; } return idx; } static void igb_update_pf_vlvf(struct igb_adapter *adapter, u32 vid) { struct e1000_hw *hw = &adapter->hw; u32 bits, pf_id; int idx; idx = igb_find_vlvf_entry(hw, vid); if (!idx) return; /* See if any other pools are set for this VLAN filter * entry other than the PF. */ pf_id = adapter->vfs_allocated_count + E1000_VLVF_POOLSEL_SHIFT; bits = ~BIT(pf_id) & E1000_VLVF_POOLSEL_MASK; bits &= rd32(E1000_VLVF(idx)); /* Disable the filter so this falls into the default pool. */ if (!bits) { if (adapter->flags & IGB_FLAG_VLAN_PROMISC) wr32(E1000_VLVF(idx), BIT(pf_id)); else wr32(E1000_VLVF(idx), 0); } } static s32 igb_set_vf_vlan(struct igb_adapter *adapter, u32 vid, bool add, u32 vf) { int pf_id = adapter->vfs_allocated_count; struct e1000_hw *hw = &adapter->hw; int err; /* If VLAN overlaps with one the PF is currently monitoring make * sure that we are able to allocate a VLVF entry. This may be * redundant but it guarantees PF will maintain visibility to * the VLAN. */ if (add && test_bit(vid, adapter->active_vlans)) { err = igb_vfta_set(hw, vid, pf_id, true, false); if (err) return err; } err = igb_vfta_set(hw, vid, vf, add, false); if (add && !err) return err; /* If we failed to add the VF VLAN or we are removing the VF VLAN * we may need to drop the PF pool bit in order to allow us to free * up the VLVF resources. */ if (test_bit(vid, adapter->active_vlans) || (adapter->flags & IGB_FLAG_VLAN_PROMISC)) igb_update_pf_vlvf(adapter, vid); return err; } static void igb_set_vmvir(struct igb_adapter *adapter, u32 vid, u32 vf) { struct e1000_hw *hw = &adapter->hw; if (vid) wr32(E1000_VMVIR(vf), (vid | E1000_VMVIR_VLANA_DEFAULT)); else wr32(E1000_VMVIR(vf), 0); } static int igb_enable_port_vlan(struct igb_adapter *adapter, int vf, u16 vlan, u8 qos) { int err; err = igb_set_vf_vlan(adapter, vlan, true, vf); if (err) return err; igb_set_vmvir(adapter, vlan | (qos << VLAN_PRIO_SHIFT), vf); igb_set_vmolr(adapter, vf, !vlan); /* revoke access to previous VLAN */ if (vlan != adapter->vf_data[vf].pf_vlan) igb_set_vf_vlan(adapter, adapter->vf_data[vf].pf_vlan, false, vf); adapter->vf_data[vf].pf_vlan = vlan; adapter->vf_data[vf].pf_qos = qos; igb_set_vf_vlan_strip(adapter, vf, true); dev_info(&adapter->pdev->dev, "Setting VLAN %d, QOS 0x%x on VF %d\n", vlan, qos, vf); if (test_bit(__IGB_DOWN, &adapter->state)) { dev_warn(&adapter->pdev->dev, "The VF VLAN has been set, but the PF device is not up.\n"); dev_warn(&adapter->pdev->dev, "Bring the PF device up before attempting to use the VF device.\n"); } return err; } static int igb_disable_port_vlan(struct igb_adapter *adapter, int vf) { /* Restore tagless access via VLAN 0 */ igb_set_vf_vlan(adapter, 0, true, vf); igb_set_vmvir(adapter, 0, vf); igb_set_vmolr(adapter, vf, true); /* Remove any PF assigned VLAN */ if (adapter->vf_data[vf].pf_vlan) igb_set_vf_vlan(adapter, adapter->vf_data[vf].pf_vlan, false, vf); adapter->vf_data[vf].pf_vlan = 0; adapter->vf_data[vf].pf_qos = 0; igb_set_vf_vlan_strip(adapter, vf, false); return 0; } static int igb_ndo_set_vf_vlan(struct net_device *netdev, int vf, u16 vlan, u8 qos, __be16 vlan_proto) { struct igb_adapter *adapter = netdev_priv(netdev); if ((vf >= adapter->vfs_allocated_count) || (vlan > 4095) || (qos > 7)) return -EINVAL; if (vlan_proto != htons(ETH_P_8021Q)) return -EPROTONOSUPPORT; return (vlan || qos) ? igb_enable_port_vlan(adapter, vf, vlan, qos) : igb_disable_port_vlan(adapter, vf); } static int igb_set_vf_vlan_msg(struct igb_adapter *adapter, u32 *msgbuf, u32 vf) { int add = (msgbuf[0] & E1000_VT_MSGINFO_MASK) >> E1000_VT_MSGINFO_SHIFT; int vid = (msgbuf[1] & E1000_VLVF_VLANID_MASK); int ret; if (adapter->vf_data[vf].pf_vlan) return -1; /* VLAN 0 is a special case, don't allow it to be removed */ if (!vid && !add) return 0; ret = igb_set_vf_vlan(adapter, vid, !!add, vf); if (!ret) igb_set_vf_vlan_strip(adapter, vf, !!vid); return ret; } static inline void igb_vf_reset(struct igb_adapter *adapter, u32 vf) { struct vf_data_storage *vf_data = &adapter->vf_data[vf]; /* clear flags - except flag that indicates PF has set the MAC */ vf_data->flags &= IGB_VF_FLAG_PF_SET_MAC; vf_data->last_nack = jiffies; /* reset vlans for device */ igb_clear_vf_vfta(adapter, vf); igb_set_vf_vlan(adapter, vf_data->pf_vlan, true, vf); igb_set_vmvir(adapter, vf_data->pf_vlan | (vf_data->pf_qos << VLAN_PRIO_SHIFT), vf); igb_set_vmolr(adapter, vf, !vf_data->pf_vlan); igb_set_vf_vlan_strip(adapter, vf, !!(vf_data->pf_vlan)); /* reset multicast table array for vf */ adapter->vf_data[vf].num_vf_mc_hashes = 0; /* Flush and reset the mta with the new values */ igb_set_rx_mode(adapter->netdev); } static void igb_vf_reset_event(struct igb_adapter *adapter, u32 vf) { unsigned char *vf_mac = adapter->vf_data[vf].vf_mac_addresses; /* clear mac address as we were hotplug removed/added */ if (!(adapter->vf_data[vf].flags & IGB_VF_FLAG_PF_SET_MAC)) eth_zero_addr(vf_mac); /* process remaining reset events */ igb_vf_reset(adapter, vf); } static void igb_vf_reset_msg(struct igb_adapter *adapter, u32 vf) { struct e1000_hw *hw = &adapter->hw; unsigned char *vf_mac = adapter->vf_data[vf].vf_mac_addresses; u32 reg, msgbuf[3] = {}; u8 *addr = (u8 *)(&msgbuf[1]); /* process all the same items cleared in a function level reset */ igb_vf_reset(adapter, vf); /* set vf mac address */ igb_set_vf_mac(adapter, vf, vf_mac); /* enable transmit and receive for vf */ reg = rd32(E1000_VFTE); wr32(E1000_VFTE, reg | BIT(vf)); reg = rd32(E1000_VFRE); wr32(E1000_VFRE, reg | BIT(vf)); adapter->vf_data[vf].flags |= IGB_VF_FLAG_CTS; /* reply to reset with ack and vf mac address */ if (!is_zero_ether_addr(vf_mac)) { msgbuf[0] = E1000_VF_RESET | E1000_VT_MSGTYPE_ACK; memcpy(addr, vf_mac, ETH_ALEN); } else { msgbuf[0] = E1000_VF_RESET | E1000_VT_MSGTYPE_NACK; } igb_write_mbx(hw, msgbuf, 3, vf); } static void igb_flush_mac_table(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; int i; for (i = 0; i < hw->mac.rar_entry_count; i++) { adapter->mac_table[i].state &= ~IGB_MAC_STATE_IN_USE; eth_zero_addr(adapter->mac_table[i].addr); adapter->mac_table[i].queue = 0; igb_rar_set_index(adapter, i); } } static int igb_available_rars(struct igb_adapter *adapter, u8 queue) { struct e1000_hw *hw = &adapter->hw; /* do not count rar entries reserved for VFs MAC addresses */ int rar_entries = hw->mac.rar_entry_count - adapter->vfs_allocated_count; int i, count = 0; for (i = 0; i < rar_entries; i++) { /* do not count default entries */ if (adapter->mac_table[i].state & IGB_MAC_STATE_DEFAULT) continue; /* do not count "in use" entries for different queues */ if ((adapter->mac_table[i].state & IGB_MAC_STATE_IN_USE) && (adapter->mac_table[i].queue != queue)) continue; count++; } return count; } /* Set default MAC address for the PF in the first RAR entry */ static void igb_set_default_mac_filter(struct igb_adapter *adapter) { struct igb_mac_addr *mac_table = &adapter->mac_table[0]; ether_addr_copy(mac_table->addr, adapter->hw.mac.addr); mac_table->queue = adapter->vfs_allocated_count; mac_table->state = IGB_MAC_STATE_DEFAULT | IGB_MAC_STATE_IN_USE; igb_rar_set_index(adapter, 0); } /* If the filter to be added and an already existing filter express * the same address and address type, it should be possible to only * override the other configurations, for example the queue to steer * traffic. */ static bool igb_mac_entry_can_be_used(const struct igb_mac_addr *entry, const u8 *addr, const u8 flags) { if (!(entry->state & IGB_MAC_STATE_IN_USE)) return true; if ((entry->state & IGB_MAC_STATE_SRC_ADDR) != (flags & IGB_MAC_STATE_SRC_ADDR)) return false; if (!ether_addr_equal(addr, entry->addr)) return false; return true; } /* Add a MAC filter for 'addr' directing matching traffic to 'queue', * 'flags' is used to indicate what kind of match is made, match is by * default for the destination address, if matching by source address * is desired the flag IGB_MAC_STATE_SRC_ADDR can be used. */ static int igb_add_mac_filter_flags(struct igb_adapter *adapter, const u8 *addr, const u8 queue, const u8 flags) { struct e1000_hw *hw = &adapter->hw; int rar_entries = hw->mac.rar_entry_count - adapter->vfs_allocated_count; int i; if (is_zero_ether_addr(addr)) return -EINVAL; /* Search for the first empty entry in the MAC table. * Do not touch entries at the end of the table reserved for the VF MAC * addresses. */ for (i = 0; i < rar_entries; i++) { if (!igb_mac_entry_can_be_used(&adapter->mac_table[i], addr, flags)) continue; ether_addr_copy(adapter->mac_table[i].addr, addr); adapter->mac_table[i].queue = queue; adapter->mac_table[i].state |= IGB_MAC_STATE_IN_USE | flags; igb_rar_set_index(adapter, i); return i; } return -ENOSPC; } static int igb_add_mac_filter(struct igb_adapter *adapter, const u8 *addr, const u8 queue) { return igb_add_mac_filter_flags(adapter, addr, queue, 0); } /* Remove a MAC filter for 'addr' directing matching traffic to * 'queue', 'flags' is used to indicate what kind of match need to be * removed, match is by default for the destination address, if * matching by source address is to be removed the flag * IGB_MAC_STATE_SRC_ADDR can be used. */ static int igb_del_mac_filter_flags(struct igb_adapter *adapter, const u8 *addr, const u8 queue, const u8 flags) { struct e1000_hw *hw = &adapter->hw; int rar_entries = hw->mac.rar_entry_count - adapter->vfs_allocated_count; int i; if (is_zero_ether_addr(addr)) return -EINVAL; /* Search for matching entry in the MAC table based on given address * and queue. Do not touch entries at the end of the table reserved * for the VF MAC addresses. */ for (i = 0; i < rar_entries; i++) { if (!(adapter->mac_table[i].state & IGB_MAC_STATE_IN_USE)) continue; if ((adapter->mac_table[i].state & flags) != flags) continue; if (adapter->mac_table[i].queue != queue) continue; if (!ether_addr_equal(adapter->mac_table[i].addr, addr)) continue; /* When a filter for the default address is "deleted", * we return it to its initial configuration */ if (adapter->mac_table[i].state & IGB_MAC_STATE_DEFAULT) { adapter->mac_table[i].state = IGB_MAC_STATE_DEFAULT | IGB_MAC_STATE_IN_USE; adapter->mac_table[i].queue = adapter->vfs_allocated_count; } else { adapter->mac_table[i].state = 0; adapter->mac_table[i].queue = 0; eth_zero_addr(adapter->mac_table[i].addr); } igb_rar_set_index(adapter, i); return 0; } return -ENOENT; } static int igb_del_mac_filter(struct igb_adapter *adapter, const u8 *addr, const u8 queue) { return igb_del_mac_filter_flags(adapter, addr, queue, 0); } int igb_add_mac_steering_filter(struct igb_adapter *adapter, const u8 *addr, u8 queue, u8 flags) { struct e1000_hw *hw = &adapter->hw; /* In theory, this should be supported on 82575 as well, but * that part wasn't easily accessible during development. */ if (hw->mac.type != e1000_i210) return -EOPNOTSUPP; return igb_add_mac_filter_flags(adapter, addr, queue, IGB_MAC_STATE_QUEUE_STEERING | flags); } int igb_del_mac_steering_filter(struct igb_adapter *adapter, const u8 *addr, u8 queue, u8 flags) { return igb_del_mac_filter_flags(adapter, addr, queue, IGB_MAC_STATE_QUEUE_STEERING | flags); } static int igb_uc_sync(struct net_device *netdev, const unsigned char *addr) { struct igb_adapter *adapter = netdev_priv(netdev); int ret; ret = igb_add_mac_filter(adapter, addr, adapter->vfs_allocated_count); return min_t(int, ret, 0); } static int igb_uc_unsync(struct net_device *netdev, const unsigned char *addr) { struct igb_adapter *adapter = netdev_priv(netdev); igb_del_mac_filter(adapter, addr, adapter->vfs_allocated_count); return 0; } static int igb_set_vf_mac_filter(struct igb_adapter *adapter, const int vf, const u32 info, const u8 *addr) { struct pci_dev *pdev = adapter->pdev; struct vf_data_storage *vf_data = &adapter->vf_data[vf]; struct list_head *pos; struct vf_mac_filter *entry = NULL; int ret = 0; if ((vf_data->flags & IGB_VF_FLAG_PF_SET_MAC) && !vf_data->trusted) { dev_warn(&pdev->dev, "VF %d requested MAC filter but is administratively denied\n", vf); return -EINVAL; } if (!is_valid_ether_addr(addr)) { dev_warn(&pdev->dev, "VF %d attempted to set invalid MAC filter\n", vf); return -EINVAL; } switch (info) { case E1000_VF_MAC_FILTER_CLR: /* remove all unicast MAC filters related to the current VF */ list_for_each(pos, &adapter->vf_macs.l) { entry = list_entry(pos, struct vf_mac_filter, l); if (entry->vf == vf) { entry->vf = -1; entry->free = true; igb_del_mac_filter(adapter, entry->vf_mac, vf); } } break; case E1000_VF_MAC_FILTER_ADD: /* try to find empty slot in the list */ list_for_each(pos, &adapter->vf_macs.l) { entry = list_entry(pos, struct vf_mac_filter, l); if (entry->free) break; } if (entry && entry->free) { entry->free = false; entry->vf = vf; ether_addr_copy(entry->vf_mac, addr); ret = igb_add_mac_filter(adapter, addr, vf); ret = min_t(int, ret, 0); } else { ret = -ENOSPC; } if (ret == -ENOSPC) dev_warn(&pdev->dev, "VF %d has requested MAC filter but there is no space for it\n", vf); break; default: ret = -EINVAL; break; } return ret; } static int igb_set_vf_mac_addr(struct igb_adapter *adapter, u32 *msg, int vf) { struct pci_dev *pdev = adapter->pdev; struct vf_data_storage *vf_data = &adapter->vf_data[vf]; u32 info = msg[0] & E1000_VT_MSGINFO_MASK; /* The VF MAC Address is stored in a packed array of bytes * starting at the second 32 bit word of the msg array */ unsigned char *addr = (unsigned char *)&msg[1]; int ret = 0; if (!info) { if ((vf_data->flags & IGB_VF_FLAG_PF_SET_MAC) && !vf_data->trusted) { dev_warn(&pdev->dev, "VF %d attempted to override administratively set MAC address\nReload the VF driver to resume operations\n", vf); return -EINVAL; } if (!is_valid_ether_addr(addr)) { dev_warn(&pdev->dev, "VF %d attempted to set invalid MAC\n", vf); return -EINVAL; } ret = igb_set_vf_mac(adapter, vf, addr); } else { ret = igb_set_vf_mac_filter(adapter, vf, info, addr); } return ret; } static void igb_rcv_ack_from_vf(struct igb_adapter *adapter, u32 vf) { struct e1000_hw *hw = &adapter->hw; struct vf_data_storage *vf_data = &adapter->vf_data[vf]; u32 msg = E1000_VT_MSGTYPE_NACK; /* if device isn't clear to send it shouldn't be reading either */ if (!(vf_data->flags & IGB_VF_FLAG_CTS) && time_after(jiffies, vf_data->last_nack + (2 * HZ))) { igb_write_mbx(hw, &msg, 1, vf); vf_data->last_nack = jiffies; } } static void igb_rcv_msg_from_vf(struct igb_adapter *adapter, u32 vf) { struct pci_dev *pdev = adapter->pdev; u32 msgbuf[E1000_VFMAILBOX_SIZE]; struct e1000_hw *hw = &adapter->hw; struct vf_data_storage *vf_data = &adapter->vf_data[vf]; s32 retval; retval = igb_read_mbx(hw, msgbuf, E1000_VFMAILBOX_SIZE, vf, false); if (retval) { /* if receive failed revoke VF CTS stats and restart init */ dev_err(&pdev->dev, "Error receiving message from VF\n"); vf_data->flags &= ~IGB_VF_FLAG_CTS; if (!time_after(jiffies, vf_data->last_nack + (2 * HZ))) goto unlock; goto out; } /* this is a message we already processed, do nothing */ if (msgbuf[0] & (E1000_VT_MSGTYPE_ACK | E1000_VT_MSGTYPE_NACK)) goto unlock; /* until the vf completes a reset it should not be * allowed to start any configuration. */ if (msgbuf[0] == E1000_VF_RESET) { /* unlocks mailbox */ igb_vf_reset_msg(adapter, vf); return; } if (!(vf_data->flags & IGB_VF_FLAG_CTS)) { if (!time_after(jiffies, vf_data->last_nack + (2 * HZ))) goto unlock; retval = -1; goto out; } switch ((msgbuf[0] & 0xFFFF)) { case E1000_VF_SET_MAC_ADDR: retval = igb_set_vf_mac_addr(adapter, msgbuf, vf); break; case E1000_VF_SET_PROMISC: retval = igb_set_vf_promisc(adapter, msgbuf, vf); break; case E1000_VF_SET_MULTICAST: retval = igb_set_vf_multicasts(adapter, msgbuf, vf); break; case E1000_VF_SET_LPE: retval = igb_set_vf_rlpml(adapter, msgbuf[1], vf); break; case E1000_VF_SET_VLAN: retval = -1; if (vf_data->pf_vlan) dev_warn(&pdev->dev, "VF %d attempted to override administratively set VLAN tag\nReload the VF driver to resume operations\n", vf); else retval = igb_set_vf_vlan_msg(adapter, msgbuf, vf); break; default: dev_err(&pdev->dev, "Unhandled Msg %08x\n", msgbuf[0]); retval = -1; break; } msgbuf[0] |= E1000_VT_MSGTYPE_CTS; out: /* notify the VF of the results of what it sent us */ if (retval) msgbuf[0] |= E1000_VT_MSGTYPE_NACK; else msgbuf[0] |= E1000_VT_MSGTYPE_ACK; /* unlocks mailbox */ igb_write_mbx(hw, msgbuf, 1, vf); return; unlock: igb_unlock_mbx(hw, vf); } static void igb_msg_task(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; unsigned long flags; u32 vf; spin_lock_irqsave(&adapter->vfs_lock, flags); for (vf = 0; vf < adapter->vfs_allocated_count; vf++) { /* process any reset requests */ if (!igb_check_for_rst(hw, vf)) igb_vf_reset_event(adapter, vf); /* process any messages pending */ if (!igb_check_for_msg(hw, vf)) igb_rcv_msg_from_vf(adapter, vf); /* process any acks */ if (!igb_check_for_ack(hw, vf)) igb_rcv_ack_from_vf(adapter, vf); } spin_unlock_irqrestore(&adapter->vfs_lock, flags); } /** * igb_set_uta - Set unicast filter table address * @adapter: board private structure * @set: boolean indicating if we are setting or clearing bits * * The unicast table address is a register array of 32-bit registers. * The table is meant to be used in a way similar to how the MTA is used * however due to certain limitations in the hardware it is necessary to * set all the hash bits to 1 and use the VMOLR ROPE bit as a promiscuous * enable bit to allow vlan tag stripping when promiscuous mode is enabled **/ static void igb_set_uta(struct igb_adapter *adapter, bool set) { struct e1000_hw *hw = &adapter->hw; u32 uta = set ? ~0 : 0; int i; /* we only need to do this if VMDq is enabled */ if (!adapter->vfs_allocated_count) return; for (i = hw->mac.uta_reg_count; i--;) array_wr32(E1000_UTA, i, uta); } /** * igb_intr_msi - Interrupt Handler * @irq: interrupt number * @data: pointer to a network interface device structure **/ static irqreturn_t igb_intr_msi(int irq, void *data) { struct igb_adapter *adapter = data; struct igb_q_vector *q_vector = adapter->q_vector[0]; struct e1000_hw *hw = &adapter->hw; /* read ICR disables interrupts using IAM */ u32 icr = rd32(E1000_ICR); igb_write_itr(q_vector); if (icr & E1000_ICR_DRSTA) schedule_work(&adapter->reset_task); if (icr & E1000_ICR_DOUTSYNC) { /* HW is reporting DMA is out of sync */ adapter->stats.doosync++; } if (icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) { hw->mac.get_link_status = 1; if (!test_bit(__IGB_DOWN, &adapter->state)) mod_timer(&adapter->watchdog_timer, jiffies + 1); } if (icr & E1000_ICR_TS) igb_tsync_interrupt(adapter); napi_schedule(&q_vector->napi); return IRQ_HANDLED; } /** * igb_intr - Legacy Interrupt Handler * @irq: interrupt number * @data: pointer to a network interface device structure **/ static irqreturn_t igb_intr(int irq, void *data) { struct igb_adapter *adapter = data; struct igb_q_vector *q_vector = adapter->q_vector[0]; struct e1000_hw *hw = &adapter->hw; /* Interrupt Auto-Mask...upon reading ICR, interrupts are masked. No * need for the IMC write */ u32 icr = rd32(E1000_ICR); /* IMS will not auto-mask if INT_ASSERTED is not set, and if it is * not set, then the adapter didn't send an interrupt */ if (!(icr & E1000_ICR_INT_ASSERTED)) return IRQ_NONE; igb_write_itr(q_vector); if (icr & E1000_ICR_DRSTA) schedule_work(&adapter->reset_task); if (icr & E1000_ICR_DOUTSYNC) { /* HW is reporting DMA is out of sync */ adapter->stats.doosync++; } if (icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) { hw->mac.get_link_status = 1; /* guard against interrupt when we're going down */ if (!test_bit(__IGB_DOWN, &adapter->state)) mod_timer(&adapter->watchdog_timer, jiffies + 1); } if (icr & E1000_ICR_TS) igb_tsync_interrupt(adapter); napi_schedule(&q_vector->napi); return IRQ_HANDLED; } static void igb_ring_irq_enable(struct igb_q_vector *q_vector) { struct igb_adapter *adapter = q_vector->adapter; struct e1000_hw *hw = &adapter->hw; if ((q_vector->rx.ring && (adapter->rx_itr_setting & 3)) || (!q_vector->rx.ring && (adapter->tx_itr_setting & 3))) { if ((adapter->num_q_vectors == 1) && !adapter->vf_data) igb_set_itr(q_vector); else igb_update_ring_itr(q_vector); } if (!test_bit(__IGB_DOWN, &adapter->state)) { if (adapter->flags & IGB_FLAG_HAS_MSIX) wr32(E1000_EIMS, q_vector->eims_value); else igb_irq_enable(adapter); } } /** * igb_poll - NAPI Rx polling callback * @napi: napi polling structure * @budget: count of how many packets we should handle **/ static int igb_poll(struct napi_struct *napi, int budget) { struct igb_q_vector *q_vector = container_of(napi, struct igb_q_vector, napi); bool clean_complete = true; int work_done = 0; #ifdef CONFIG_IGB_DCA if (q_vector->adapter->flags & IGB_FLAG_DCA_ENABLED) igb_update_dca(q_vector); #endif if (q_vector->tx.ring) clean_complete = igb_clean_tx_irq(q_vector, budget); if (q_vector->rx.ring) { int cleaned = igb_clean_rx_irq(q_vector, budget); work_done += cleaned; if (cleaned >= budget) clean_complete = false; } /* If all work not completed, return budget and keep polling */ if (!clean_complete) return budget; /* Exit the polling mode, but don't re-enable interrupts if stack might * poll us due to busy-polling */ if (likely(napi_complete_done(napi, work_done))) igb_ring_irq_enable(q_vector); return work_done; } /** * igb_clean_tx_irq - Reclaim resources after transmit completes * @q_vector: pointer to q_vector containing needed info * @napi_budget: Used to determine if we are in netpoll * * returns true if ring is completely cleaned **/ static bool igb_clean_tx_irq(struct igb_q_vector *q_vector, int napi_budget) { struct igb_adapter *adapter = q_vector->adapter; struct igb_ring *tx_ring = q_vector->tx.ring; struct igb_tx_buffer *tx_buffer; union e1000_adv_tx_desc *tx_desc; unsigned int total_bytes = 0, total_packets = 0; unsigned int budget = q_vector->tx.work_limit; unsigned int i = tx_ring->next_to_clean; if (test_bit(__IGB_DOWN, &adapter->state)) return true; tx_buffer = &tx_ring->tx_buffer_info[i]; tx_desc = IGB_TX_DESC(tx_ring, i); i -= tx_ring->count; do { union e1000_adv_tx_desc *eop_desc = tx_buffer->next_to_watch; /* if next_to_watch is not set then there is no work pending */ if (!eop_desc) break; /* prevent any other reads prior to eop_desc */ smp_rmb(); /* if DD is not set pending work has not been completed */ if (!(eop_desc->wb.status & cpu_to_le32(E1000_TXD_STAT_DD))) break; /* clear next_to_watch to prevent false hangs */ tx_buffer->next_to_watch = NULL; /* update the statistics for this packet */ total_bytes += tx_buffer->bytecount; total_packets += tx_buffer->gso_segs; /* free the skb */ if (tx_buffer->type == IGB_TYPE_SKB) napi_consume_skb(tx_buffer->skb, napi_budget); else xdp_return_frame(tx_buffer->xdpf); /* unmap skb header data */ dma_unmap_single(tx_ring->dev, dma_unmap_addr(tx_buffer, dma), dma_unmap_len(tx_buffer, len), DMA_TO_DEVICE); /* clear tx_buffer data */ dma_unmap_len_set(tx_buffer, len, 0); /* clear last DMA location and unmap remaining buffers */ while (tx_desc != eop_desc) { tx_buffer++; tx_desc++; i++; if (unlikely(!i)) { i -= tx_ring->count; tx_buffer = tx_ring->tx_buffer_info; tx_desc = IGB_TX_DESC(tx_ring, 0); } /* unmap any remaining paged data */ if (dma_unmap_len(tx_buffer, len)) { dma_unmap_page(tx_ring->dev, dma_unmap_addr(tx_buffer, dma), dma_unmap_len(tx_buffer, len), DMA_TO_DEVICE); dma_unmap_len_set(tx_buffer, len, 0); } } /* move us one more past the eop_desc for start of next pkt */ tx_buffer++; tx_desc++; i++; if (unlikely(!i)) { i -= tx_ring->count; tx_buffer = tx_ring->tx_buffer_info; tx_desc = IGB_TX_DESC(tx_ring, 0); } /* issue prefetch for next Tx descriptor */ prefetch(tx_desc); /* update budget accounting */ budget--; } while (likely(budget)); netdev_tx_completed_queue(txring_txq(tx_ring), total_packets, total_bytes); i += tx_ring->count; tx_ring->next_to_clean = i; u64_stats_update_begin(&tx_ring->tx_syncp); tx_ring->tx_stats.bytes += total_bytes; tx_ring->tx_stats.packets += total_packets; u64_stats_update_end(&tx_ring->tx_syncp); q_vector->tx.total_bytes += total_bytes; q_vector->tx.total_packets += total_packets; if (test_bit(IGB_RING_FLAG_TX_DETECT_HANG, &tx_ring->flags)) { struct e1000_hw *hw = &adapter->hw; /* Detect a transmit hang in hardware, this serializes the * check with the clearing of time_stamp and movement of i */ clear_bit(IGB_RING_FLAG_TX_DETECT_HANG, &tx_ring->flags); if (tx_buffer->next_to_watch && time_after(jiffies, tx_buffer->time_stamp + (adapter->tx_timeout_factor * HZ)) && !(rd32(E1000_STATUS) & E1000_STATUS_TXOFF)) { /* detected Tx unit hang */ dev_err(tx_ring->dev, "Detected Tx Unit Hang\n" " Tx Queue <%d>\n" " TDH <%x>\n" " TDT <%x>\n" " next_to_use <%x>\n" " next_to_clean <%x>\n" "buffer_info[next_to_clean]\n" " time_stamp <%lx>\n" " next_to_watch <%p>\n" " jiffies <%lx>\n" " desc.status <%x>\n", tx_ring->queue_index, rd32(E1000_TDH(tx_ring->reg_idx)), readl(tx_ring->tail), tx_ring->next_to_use, tx_ring->next_to_clean, tx_buffer->time_stamp, tx_buffer->next_to_watch, jiffies, tx_buffer->next_to_watch->wb.status); netif_stop_subqueue(tx_ring->netdev, tx_ring->queue_index); /* we are about to reset, no point in enabling stuff */ return true; } } #define TX_WAKE_THRESHOLD (DESC_NEEDED * 2) if (unlikely(total_packets && netif_carrier_ok(tx_ring->netdev) && igb_desc_unused(tx_ring) >= TX_WAKE_THRESHOLD)) { /* Make sure that anybody stopping the queue after this * sees the new next_to_clean. */ smp_mb(); if (__netif_subqueue_stopped(tx_ring->netdev, tx_ring->queue_index) && !(test_bit(__IGB_DOWN, &adapter->state))) { netif_wake_subqueue(tx_ring->netdev, tx_ring->queue_index); u64_stats_update_begin(&tx_ring->tx_syncp); tx_ring->tx_stats.restart_queue++; u64_stats_update_end(&tx_ring->tx_syncp); } } return !!budget; } /** * igb_reuse_rx_page - page flip buffer and store it back on the ring * @rx_ring: rx descriptor ring to store buffers on * @old_buff: donor buffer to have page reused * * Synchronizes page for reuse by the adapter **/ static void igb_reuse_rx_page(struct igb_ring *rx_ring, struct igb_rx_buffer *old_buff) { struct igb_rx_buffer *new_buff; u16 nta = rx_ring->next_to_alloc; new_buff = &rx_ring->rx_buffer_info[nta]; /* update, and store next to alloc */ nta++; rx_ring->next_to_alloc = (nta < rx_ring->count) ? nta : 0; /* Transfer page from old buffer to new buffer. * Move each member individually to avoid possible store * forwarding stalls. */ new_buff->dma = old_buff->dma; new_buff->page = old_buff->page; new_buff->page_offset = old_buff->page_offset; new_buff->pagecnt_bias = old_buff->pagecnt_bias; } static bool igb_can_reuse_rx_page(struct igb_rx_buffer *rx_buffer, int rx_buf_pgcnt) { unsigned int pagecnt_bias = rx_buffer->pagecnt_bias; struct page *page = rx_buffer->page; /* avoid re-using remote and pfmemalloc pages */ if (!dev_page_is_reusable(page)) return false; #if (PAGE_SIZE < 8192) /* if we are only owner of page we can reuse it */ if (unlikely((rx_buf_pgcnt - pagecnt_bias) > 1)) return false; #else #define IGB_LAST_OFFSET \ (SKB_WITH_OVERHEAD(PAGE_SIZE) - IGB_RXBUFFER_2048) if (rx_buffer->page_offset > IGB_LAST_OFFSET) return false; #endif /* If we have drained the page fragment pool we need to update * the pagecnt_bias and page count so that we fully restock the * number of references the driver holds. */ if (unlikely(pagecnt_bias == 1)) { page_ref_add(page, USHRT_MAX - 1); rx_buffer->pagecnt_bias = USHRT_MAX; } return true; } /** * igb_add_rx_frag - Add contents of Rx buffer to sk_buff * @rx_ring: rx descriptor ring to transact packets on * @rx_buffer: buffer containing page to add * @skb: sk_buff to place the data into * @size: size of buffer to be added * * This function will add the data contained in rx_buffer->page to the skb. **/ static void igb_add_rx_frag(struct igb_ring *rx_ring, struct igb_rx_buffer *rx_buffer, struct sk_buff *skb, unsigned int size) { #if (PAGE_SIZE < 8192) unsigned int truesize = igb_rx_pg_size(rx_ring) / 2; #else unsigned int truesize = ring_uses_build_skb(rx_ring) ? SKB_DATA_ALIGN(IGB_SKB_PAD + size) : SKB_DATA_ALIGN(size); #endif skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, rx_buffer->page, rx_buffer->page_offset, size, truesize); #if (PAGE_SIZE < 8192) rx_buffer->page_offset ^= truesize; #else rx_buffer->page_offset += truesize; #endif } static struct sk_buff *igb_construct_skb(struct igb_ring *rx_ring, struct igb_rx_buffer *rx_buffer, struct xdp_buff *xdp, ktime_t timestamp) { #if (PAGE_SIZE < 8192) unsigned int truesize = igb_rx_pg_size(rx_ring) / 2; #else unsigned int truesize = SKB_DATA_ALIGN(xdp->data_end - xdp->data_hard_start); #endif unsigned int size = xdp->data_end - xdp->data; unsigned int headlen; struct sk_buff *skb; /* prefetch first cache line of first page */ net_prefetch(xdp->data); /* allocate a skb to store the frags */ skb = napi_alloc_skb(&rx_ring->q_vector->napi, IGB_RX_HDR_LEN); if (unlikely(!skb)) return NULL; if (timestamp) skb_hwtstamps(skb)->hwtstamp = timestamp; /* Determine available headroom for copy */ headlen = size; if (headlen > IGB_RX_HDR_LEN) headlen = eth_get_headlen(skb->dev, xdp->data, IGB_RX_HDR_LEN); /* align pull length to size of long to optimize memcpy performance */ memcpy(__skb_put(skb, headlen), xdp->data, ALIGN(headlen, sizeof(long))); /* update all of the pointers */ size -= headlen; if (size) { skb_add_rx_frag(skb, 0, rx_buffer->page, (xdp->data + headlen) - page_address(rx_buffer->page), size, truesize); #if (PAGE_SIZE < 8192) rx_buffer->page_offset ^= truesize; #else rx_buffer->page_offset += truesize; #endif } else { rx_buffer->pagecnt_bias++; } return skb; } static struct sk_buff *igb_build_skb(struct igb_ring *rx_ring, struct igb_rx_buffer *rx_buffer, struct xdp_buff *xdp, ktime_t timestamp) { #if (PAGE_SIZE < 8192) unsigned int truesize = igb_rx_pg_size(rx_ring) / 2; #else unsigned int truesize = SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) + SKB_DATA_ALIGN(xdp->data_end - xdp->data_hard_start); #endif unsigned int metasize = xdp->data - xdp->data_meta; struct sk_buff *skb; /* prefetch first cache line of first page */ net_prefetch(xdp->data_meta); /* build an skb around the page buffer */ skb = napi_build_skb(xdp->data_hard_start, truesize); if (unlikely(!skb)) return NULL; /* update pointers within the skb to store the data */ skb_reserve(skb, xdp->data - xdp->data_hard_start); __skb_put(skb, xdp->data_end - xdp->data); if (metasize) skb_metadata_set(skb, metasize); if (timestamp) skb_hwtstamps(skb)->hwtstamp = timestamp; /* update buffer offset */ #if (PAGE_SIZE < 8192) rx_buffer->page_offset ^= truesize; #else rx_buffer->page_offset += truesize; #endif return skb; } static struct sk_buff *igb_run_xdp(struct igb_adapter *adapter, struct igb_ring *rx_ring, struct xdp_buff *xdp) { int err, result = IGB_XDP_PASS; struct bpf_prog *xdp_prog; u32 act; xdp_prog = READ_ONCE(rx_ring->xdp_prog); if (!xdp_prog) goto xdp_out; prefetchw(xdp->data_hard_start); /* xdp_frame write */ act = bpf_prog_run_xdp(xdp_prog, xdp); switch (act) { case XDP_PASS: break; case XDP_TX: result = igb_xdp_xmit_back(adapter, xdp); if (result == IGB_XDP_CONSUMED) goto out_failure; break; case XDP_REDIRECT: err = xdp_do_redirect(adapter->netdev, xdp, xdp_prog); if (err) goto out_failure; result = IGB_XDP_REDIR; break; default: bpf_warn_invalid_xdp_action(adapter->netdev, xdp_prog, act); fallthrough; case XDP_ABORTED: out_failure: trace_xdp_exception(rx_ring->netdev, xdp_prog, act); fallthrough; case XDP_DROP: result = IGB_XDP_CONSUMED; break; } xdp_out: return ERR_PTR(-result); } static unsigned int igb_rx_frame_truesize(struct igb_ring *rx_ring, unsigned int size) { unsigned int truesize; #if (PAGE_SIZE < 8192) truesize = igb_rx_pg_size(rx_ring) / 2; /* Must be power-of-2 */ #else truesize = ring_uses_build_skb(rx_ring) ? SKB_DATA_ALIGN(IGB_SKB_PAD + size) + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) : SKB_DATA_ALIGN(size); #endif return truesize; } static void igb_rx_buffer_flip(struct igb_ring *rx_ring, struct igb_rx_buffer *rx_buffer, unsigned int size) { unsigned int truesize = igb_rx_frame_truesize(rx_ring, size); #if (PAGE_SIZE < 8192) rx_buffer->page_offset ^= truesize; #else rx_buffer->page_offset += truesize; #endif } static inline void igb_rx_checksum(struct igb_ring *ring, union e1000_adv_rx_desc *rx_desc, struct sk_buff *skb) { skb_checksum_none_assert(skb); /* Ignore Checksum bit is set */ if (igb_test_staterr(rx_desc, E1000_RXD_STAT_IXSM)) return; /* Rx checksum disabled via ethtool */ if (!(ring->netdev->features & NETIF_F_RXCSUM)) return; /* TCP/UDP checksum error bit is set */ if (igb_test_staterr(rx_desc, E1000_RXDEXT_STATERR_TCPE | E1000_RXDEXT_STATERR_IPE)) { /* work around errata with sctp packets where the TCPE aka * L4E bit is set incorrectly on 64 byte (60 byte w/o crc) * packets, (aka let the stack check the crc32c) */ if (!((skb->len == 60) && test_bit(IGB_RING_FLAG_RX_SCTP_CSUM, &ring->flags))) { u64_stats_update_begin(&ring->rx_syncp); ring->rx_stats.csum_err++; u64_stats_update_end(&ring->rx_syncp); } /* let the stack verify checksum errors */ return; } /* It must be a TCP or UDP packet with a valid checksum */ if (igb_test_staterr(rx_desc, E1000_RXD_STAT_TCPCS | E1000_RXD_STAT_UDPCS)) skb->ip_summed = CHECKSUM_UNNECESSARY; dev_dbg(ring->dev, "cksum success: bits %08X\n", le32_to_cpu(rx_desc->wb.upper.status_error)); } static inline void igb_rx_hash(struct igb_ring *ring, union e1000_adv_rx_desc *rx_desc, struct sk_buff *skb) { if (ring->netdev->features & NETIF_F_RXHASH) skb_set_hash(skb, le32_to_cpu(rx_desc->wb.lower.hi_dword.rss), PKT_HASH_TYPE_L3); } /** * igb_is_non_eop - process handling of non-EOP buffers * @rx_ring: Rx ring being processed * @rx_desc: Rx descriptor for current buffer * * This function updates next to clean. If the buffer is an EOP buffer * this function exits returning false, otherwise it will place the * sk_buff in the next buffer to be chained and return true indicating * that this is in fact a non-EOP buffer. **/ static bool igb_is_non_eop(struct igb_ring *rx_ring, union e1000_adv_rx_desc *rx_desc) { u32 ntc = rx_ring->next_to_clean + 1; /* fetch, update, and store next to clean */ ntc = (ntc < rx_ring->count) ? ntc : 0; rx_ring->next_to_clean = ntc; prefetch(IGB_RX_DESC(rx_ring, ntc)); if (likely(igb_test_staterr(rx_desc, E1000_RXD_STAT_EOP))) return false; return true; } /** * igb_cleanup_headers - Correct corrupted or empty headers * @rx_ring: rx descriptor ring packet is being transacted on * @rx_desc: pointer to the EOP Rx descriptor * @skb: pointer to current skb being fixed * * Address the case where we are pulling data in on pages only * and as such no data is present in the skb header. * * In addition if skb is not at least 60 bytes we need to pad it so that * it is large enough to qualify as a valid Ethernet frame. * * Returns true if an error was encountered and skb was freed. **/ static bool igb_cleanup_headers(struct igb_ring *rx_ring, union e1000_adv_rx_desc *rx_desc, struct sk_buff *skb) { /* XDP packets use error pointer so abort at this point */ if (IS_ERR(skb)) return true; if (unlikely((igb_test_staterr(rx_desc, E1000_RXDEXT_ERR_FRAME_ERR_MASK)))) { struct net_device *netdev = rx_ring->netdev; if (!(netdev->features & NETIF_F_RXALL)) { dev_kfree_skb_any(skb); return true; } } /* if eth_skb_pad returns an error the skb was freed */ if (eth_skb_pad(skb)) return true; return false; } /** * igb_process_skb_fields - Populate skb header fields from Rx descriptor * @rx_ring: rx descriptor ring packet is being transacted on * @rx_desc: pointer to the EOP Rx descriptor * @skb: pointer to current skb being populated * * This function checks the ring, descriptor, and packet information in * order to populate the hash, checksum, VLAN, timestamp, protocol, and * other fields within the skb. **/ static void igb_process_skb_fields(struct igb_ring *rx_ring, union e1000_adv_rx_desc *rx_desc, struct sk_buff *skb) { struct net_device *dev = rx_ring->netdev; igb_rx_hash(rx_ring, rx_desc, skb); igb_rx_checksum(rx_ring, rx_desc, skb); if (igb_test_staterr(rx_desc, E1000_RXDADV_STAT_TS) && !igb_test_staterr(rx_desc, E1000_RXDADV_STAT_TSIP)) igb_ptp_rx_rgtstamp(rx_ring->q_vector, skb); if ((dev->features & NETIF_F_HW_VLAN_CTAG_RX) && igb_test_staterr(rx_desc, E1000_RXD_STAT_VP)) { u16 vid; if (igb_test_staterr(rx_desc, E1000_RXDEXT_STATERR_LB) && test_bit(IGB_RING_FLAG_RX_LB_VLAN_BSWAP, &rx_ring->flags)) vid = be16_to_cpu((__force __be16)rx_desc->wb.upper.vlan); else vid = le16_to_cpu(rx_desc->wb.upper.vlan); __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vid); } skb_record_rx_queue(skb, rx_ring->queue_index); skb->protocol = eth_type_trans(skb, rx_ring->netdev); } static unsigned int igb_rx_offset(struct igb_ring *rx_ring) { return ring_uses_build_skb(rx_ring) ? IGB_SKB_PAD : 0; } static struct igb_rx_buffer *igb_get_rx_buffer(struct igb_ring *rx_ring, const unsigned int size, int *rx_buf_pgcnt) { struct igb_rx_buffer *rx_buffer; rx_buffer = &rx_ring->rx_buffer_info[rx_ring->next_to_clean]; *rx_buf_pgcnt = #if (PAGE_SIZE < 8192) page_count(rx_buffer->page); #else 0; #endif prefetchw(rx_buffer->page); /* we are reusing so sync this buffer for CPU use */ dma_sync_single_range_for_cpu(rx_ring->dev, rx_buffer->dma, rx_buffer->page_offset, size, DMA_FROM_DEVICE); rx_buffer->pagecnt_bias--; return rx_buffer; } static void igb_put_rx_buffer(struct igb_ring *rx_ring, struct igb_rx_buffer *rx_buffer, int rx_buf_pgcnt) { if (igb_can_reuse_rx_page(rx_buffer, rx_buf_pgcnt)) { /* hand second half of page back to the ring */ igb_reuse_rx_page(rx_ring, rx_buffer); } else { /* We are not reusing the buffer so unmap it and free * any references we are holding to it */ dma_unmap_page_attrs(rx_ring->dev, rx_buffer->dma, igb_rx_pg_size(rx_ring), DMA_FROM_DEVICE, IGB_RX_DMA_ATTR); __page_frag_cache_drain(rx_buffer->page, rx_buffer->pagecnt_bias); } /* clear contents of rx_buffer */ rx_buffer->page = NULL; } static int igb_clean_rx_irq(struct igb_q_vector *q_vector, const int budget) { struct igb_adapter *adapter = q_vector->adapter; struct igb_ring *rx_ring = q_vector->rx.ring; struct sk_buff *skb = rx_ring->skb; unsigned int total_bytes = 0, total_packets = 0; u16 cleaned_count = igb_desc_unused(rx_ring); unsigned int xdp_xmit = 0; struct xdp_buff xdp; u32 frame_sz = 0; int rx_buf_pgcnt; /* Frame size depend on rx_ring setup when PAGE_SIZE=4K */ #if (PAGE_SIZE < 8192) frame_sz = igb_rx_frame_truesize(rx_ring, 0); #endif xdp_init_buff(&xdp, frame_sz, &rx_ring->xdp_rxq); while (likely(total_packets < budget)) { union e1000_adv_rx_desc *rx_desc; struct igb_rx_buffer *rx_buffer; ktime_t timestamp = 0; int pkt_offset = 0; unsigned int size; void *pktbuf; /* return some buffers to hardware, one at a time is too slow */ if (cleaned_count >= IGB_RX_BUFFER_WRITE) { igb_alloc_rx_buffers(rx_ring, cleaned_count); cleaned_count = 0; } rx_desc = IGB_RX_DESC(rx_ring, rx_ring->next_to_clean); size = le16_to_cpu(rx_desc->wb.upper.length); if (!size) break; /* This memory barrier is needed to keep us from reading * any other fields out of the rx_desc until we know the * descriptor has been written back */ dma_rmb(); rx_buffer = igb_get_rx_buffer(rx_ring, size, &rx_buf_pgcnt); pktbuf = page_address(rx_buffer->page) + rx_buffer->page_offset; /* pull rx packet timestamp if available and valid */ if (igb_test_staterr(rx_desc, E1000_RXDADV_STAT_TSIP)) { int ts_hdr_len; ts_hdr_len = igb_ptp_rx_pktstamp(rx_ring->q_vector, pktbuf, &timestamp); pkt_offset += ts_hdr_len; size -= ts_hdr_len; } /* retrieve a buffer from the ring */ if (!skb) { unsigned char *hard_start = pktbuf - igb_rx_offset(rx_ring); unsigned int offset = pkt_offset + igb_rx_offset(rx_ring); xdp_prepare_buff(&xdp, hard_start, offset, size, true); xdp_buff_clear_frags_flag(&xdp); #if (PAGE_SIZE > 4096) /* At larger PAGE_SIZE, frame_sz depend on len size */ xdp.frame_sz = igb_rx_frame_truesize(rx_ring, size); #endif skb = igb_run_xdp(adapter, rx_ring, &xdp); } if (IS_ERR(skb)) { unsigned int xdp_res = -PTR_ERR(skb); if (xdp_res & (IGB_XDP_TX | IGB_XDP_REDIR)) { xdp_xmit |= xdp_res; igb_rx_buffer_flip(rx_ring, rx_buffer, size); } else { rx_buffer->pagecnt_bias++; } total_packets++; total_bytes += size; } else if (skb) igb_add_rx_frag(rx_ring, rx_buffer, skb, size); else if (ring_uses_build_skb(rx_ring)) skb = igb_build_skb(rx_ring, rx_buffer, &xdp, timestamp); else skb = igb_construct_skb(rx_ring, rx_buffer, &xdp, timestamp); /* exit if we failed to retrieve a buffer */ if (!skb) { rx_ring->rx_stats.alloc_failed++; rx_buffer->pagecnt_bias++; break; } igb_put_rx_buffer(rx_ring, rx_buffer, rx_buf_pgcnt); cleaned_count++; /* fetch next buffer in frame if non-eop */ if (igb_is_non_eop(rx_ring, rx_desc)) continue; /* verify the packet layout is correct */ if (igb_cleanup_headers(rx_ring, rx_desc, skb)) { skb = NULL; continue; } /* probably a little skewed due to removing CRC */ total_bytes += skb->len; /* populate checksum, timestamp, VLAN, and protocol */ igb_process_skb_fields(rx_ring, rx_desc, skb); napi_gro_receive(&q_vector->napi, skb); /* reset skb pointer */ skb = NULL; /* update budget accounting */ total_packets++; } /* place incomplete frames back on ring for completion */ rx_ring->skb = skb; if (xdp_xmit & IGB_XDP_REDIR) xdp_do_flush(); if (xdp_xmit & IGB_XDP_TX) { struct igb_ring *tx_ring = igb_xdp_tx_queue_mapping(adapter); igb_xdp_ring_update_tail(tx_ring); } u64_stats_update_begin(&rx_ring->rx_syncp); rx_ring->rx_stats.packets += total_packets; rx_ring->rx_stats.bytes += total_bytes; u64_stats_update_end(&rx_ring->rx_syncp); q_vector->rx.total_packets += total_packets; q_vector->rx.total_bytes += total_bytes; if (cleaned_count) igb_alloc_rx_buffers(rx_ring, cleaned_count); return total_packets; } static bool igb_alloc_mapped_page(struct igb_ring *rx_ring, struct igb_rx_buffer *bi) { struct page *page = bi->page; dma_addr_t dma; /* since we are recycling buffers we should seldom need to alloc */ if (likely(page)) return true; /* alloc new page for storage */ page = dev_alloc_pages(igb_rx_pg_order(rx_ring)); if (unlikely(!page)) { rx_ring->rx_stats.alloc_failed++; return false; } /* map page for use */ dma = dma_map_page_attrs(rx_ring->dev, page, 0, igb_rx_pg_size(rx_ring), DMA_FROM_DEVICE, IGB_RX_DMA_ATTR); /* if mapping failed free memory back to system since * there isn't much point in holding memory we can't use */ if (dma_mapping_error(rx_ring->dev, dma)) { __free_pages(page, igb_rx_pg_order(rx_ring)); rx_ring->rx_stats.alloc_failed++; return false; } bi->dma = dma; bi->page = page; bi->page_offset = igb_rx_offset(rx_ring); page_ref_add(page, USHRT_MAX - 1); bi->pagecnt_bias = USHRT_MAX; return true; } /** * igb_alloc_rx_buffers - Replace used receive buffers * @rx_ring: rx descriptor ring to allocate new receive buffers * @cleaned_count: count of buffers to allocate **/ void igb_alloc_rx_buffers(struct igb_ring *rx_ring, u16 cleaned_count) { union e1000_adv_rx_desc *rx_desc; struct igb_rx_buffer *bi; u16 i = rx_ring->next_to_use; u16 bufsz; /* nothing to do */ if (!cleaned_count) return; rx_desc = IGB_RX_DESC(rx_ring, i); bi = &rx_ring->rx_buffer_info[i]; i -= rx_ring->count; bufsz = igb_rx_bufsz(rx_ring); do { if (!igb_alloc_mapped_page(rx_ring, bi)) break; /* sync the buffer for use by the device */ dma_sync_single_range_for_device(rx_ring->dev, bi->dma, bi->page_offset, bufsz, DMA_FROM_DEVICE); /* Refresh the desc even if buffer_addrs didn't change * because each write-back erases this info. */ rx_desc->read.pkt_addr = cpu_to_le64(bi->dma + bi->page_offset); rx_desc++; bi++; i++; if (unlikely(!i)) { rx_desc = IGB_RX_DESC(rx_ring, 0); bi = rx_ring->rx_buffer_info; i -= rx_ring->count; } /* clear the length for the next_to_use descriptor */ rx_desc->wb.upper.length = 0; cleaned_count--; } while (cleaned_count); i += rx_ring->count; if (rx_ring->next_to_use != i) { /* record the next descriptor to use */ rx_ring->next_to_use = i; /* update next to alloc since we have filled the ring */ rx_ring->next_to_alloc = i; /* Force memory writes to complete before letting h/w * know there are new descriptors to fetch. (Only * applicable for weak-ordered memory model archs, * such as IA-64). */ dma_wmb(); writel(i, rx_ring->tail); } } /** * igb_mii_ioctl - * @netdev: pointer to netdev struct * @ifr: interface structure * @cmd: ioctl command to execute **/ static int igb_mii_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd) { struct igb_adapter *adapter = netdev_priv(netdev); struct mii_ioctl_data *data = if_mii(ifr); if (adapter->hw.phy.media_type != e1000_media_type_copper) return -EOPNOTSUPP; switch (cmd) { case SIOCGMIIPHY: data->phy_id = adapter->hw.phy.addr; break; case SIOCGMIIREG: if (igb_read_phy_reg(&adapter->hw, data->reg_num & 0x1F, &data->val_out)) return -EIO; break; case SIOCSMIIREG: default: return -EOPNOTSUPP; } return 0; } /** * igb_ioctl - * @netdev: pointer to netdev struct * @ifr: interface structure * @cmd: ioctl command to execute **/ static int igb_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd) { switch (cmd) { case SIOCGMIIPHY: case SIOCGMIIREG: case SIOCSMIIREG: return igb_mii_ioctl(netdev, ifr, cmd); case SIOCGHWTSTAMP: return igb_ptp_get_ts_config(netdev, ifr); case SIOCSHWTSTAMP: return igb_ptp_set_ts_config(netdev, ifr); default: return -EOPNOTSUPP; } } void igb_read_pci_cfg(struct e1000_hw *hw, u32 reg, u16 *value) { struct igb_adapter *adapter = hw->back; pci_read_config_word(adapter->pdev, reg, value); } void igb_write_pci_cfg(struct e1000_hw *hw, u32 reg, u16 *value) { struct igb_adapter *adapter = hw->back; pci_write_config_word(adapter->pdev, reg, *value); } s32 igb_read_pcie_cap_reg(struct e1000_hw *hw, u32 reg, u16 *value) { struct igb_adapter *adapter = hw->back; if (pcie_capability_read_word(adapter->pdev, reg, value)) return -E1000_ERR_CONFIG; return 0; } s32 igb_write_pcie_cap_reg(struct e1000_hw *hw, u32 reg, u16 *value) { struct igb_adapter *adapter = hw->back; if (pcie_capability_write_word(adapter->pdev, reg, *value)) return -E1000_ERR_CONFIG; return 0; } static void igb_vlan_mode(struct net_device *netdev, netdev_features_t features) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u32 ctrl, rctl; bool enable = !!(features & NETIF_F_HW_VLAN_CTAG_RX); if (enable) { /* enable VLAN tag insert/strip */ ctrl = rd32(E1000_CTRL); ctrl |= E1000_CTRL_VME; wr32(E1000_CTRL, ctrl); /* Disable CFI check */ rctl = rd32(E1000_RCTL); rctl &= ~E1000_RCTL_CFIEN; wr32(E1000_RCTL, rctl); } else { /* disable VLAN tag insert/strip */ ctrl = rd32(E1000_CTRL); ctrl &= ~E1000_CTRL_VME; wr32(E1000_CTRL, ctrl); } igb_set_vf_vlan_strip(adapter, adapter->vfs_allocated_count, enable); } static int igb_vlan_rx_add_vid(struct net_device *netdev, __be16 proto, u16 vid) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; int pf_id = adapter->vfs_allocated_count; /* add the filter since PF can receive vlans w/o entry in vlvf */ if (!vid || !(adapter->flags & IGB_FLAG_VLAN_PROMISC)) igb_vfta_set(hw, vid, pf_id, true, !!vid); set_bit(vid, adapter->active_vlans); return 0; } static int igb_vlan_rx_kill_vid(struct net_device *netdev, __be16 proto, u16 vid) { struct igb_adapter *adapter = netdev_priv(netdev); int pf_id = adapter->vfs_allocated_count; struct e1000_hw *hw = &adapter->hw; /* remove VID from filter table */ if (vid && !(adapter->flags & IGB_FLAG_VLAN_PROMISC)) igb_vfta_set(hw, vid, pf_id, false, true); clear_bit(vid, adapter->active_vlans); return 0; } static void igb_restore_vlan(struct igb_adapter *adapter) { u16 vid = 1; igb_vlan_mode(adapter->netdev, adapter->netdev->features); igb_vlan_rx_add_vid(adapter->netdev, htons(ETH_P_8021Q), 0); for_each_set_bit_from(vid, adapter->active_vlans, VLAN_N_VID) igb_vlan_rx_add_vid(adapter->netdev, htons(ETH_P_8021Q), vid); } int igb_set_spd_dplx(struct igb_adapter *adapter, u32 spd, u8 dplx) { struct pci_dev *pdev = adapter->pdev; struct e1000_mac_info *mac = &adapter->hw.mac; mac->autoneg = 0; /* Make sure dplx is at most 1 bit and lsb of speed is not set * for the switch() below to work */ if ((spd & 1) || (dplx & ~1)) goto err_inval; /* Fiber NIC's only allow 1000 gbps Full duplex * and 100Mbps Full duplex for 100baseFx sfp */ if (adapter->hw.phy.media_type == e1000_media_type_internal_serdes) { switch (spd + dplx) { case SPEED_10 + DUPLEX_HALF: case SPEED_10 + DUPLEX_FULL: case SPEED_100 + DUPLEX_HALF: goto err_inval; default: break; } } switch (spd + dplx) { case SPEED_10 + DUPLEX_HALF: mac->forced_speed_duplex = ADVERTISE_10_HALF; break; case SPEED_10 + DUPLEX_FULL: mac->forced_speed_duplex = ADVERTISE_10_FULL; break; case SPEED_100 + DUPLEX_HALF: mac->forced_speed_duplex = ADVERTISE_100_HALF; break; case SPEED_100 + DUPLEX_FULL: mac->forced_speed_duplex = ADVERTISE_100_FULL; break; case SPEED_1000 + DUPLEX_FULL: mac->autoneg = 1; adapter->hw.phy.autoneg_advertised = ADVERTISE_1000_FULL; break; case SPEED_1000 + DUPLEX_HALF: /* not supported */ default: goto err_inval; } /* clear MDI, MDI(-X) override is only allowed when autoneg enabled */ adapter->hw.phy.mdix = AUTO_ALL_MODES; return 0; err_inval: dev_err(&pdev->dev, "Unsupported Speed/Duplex configuration\n"); return -EINVAL; } static int __igb_shutdown(struct pci_dev *pdev, bool *enable_wake, bool runtime) { struct net_device *netdev = pci_get_drvdata(pdev); struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u32 ctrl, rctl, status; u32 wufc = runtime ? E1000_WUFC_LNKC : adapter->wol; bool wake; rtnl_lock(); netif_device_detach(netdev); if (netif_running(netdev)) __igb_close(netdev, true); igb_ptp_suspend(adapter); igb_clear_interrupt_scheme(adapter); rtnl_unlock(); status = rd32(E1000_STATUS); if (status & E1000_STATUS_LU) wufc &= ~E1000_WUFC_LNKC; if (wufc) { igb_setup_rctl(adapter); igb_set_rx_mode(netdev); /* turn on all-multi mode if wake on multicast is enabled */ if (wufc & E1000_WUFC_MC) { rctl = rd32(E1000_RCTL); rctl |= E1000_RCTL_MPE; wr32(E1000_RCTL, rctl); } ctrl = rd32(E1000_CTRL); ctrl |= E1000_CTRL_ADVD3WUC; wr32(E1000_CTRL, ctrl); /* Allow time for pending master requests to run */ igb_disable_pcie_master(hw); wr32(E1000_WUC, E1000_WUC_PME_EN); wr32(E1000_WUFC, wufc); } else { wr32(E1000_WUC, 0); wr32(E1000_WUFC, 0); } wake = wufc || adapter->en_mng_pt; if (!wake) igb_power_down_link(adapter); else igb_power_up_link(adapter); if (enable_wake) *enable_wake = wake; /* Release control of h/w to f/w. If f/w is AMT enabled, this * would have already happened in close and is redundant. */ igb_release_hw_control(adapter); pci_disable_device(pdev); return 0; } static void igb_deliver_wake_packet(struct net_device *netdev) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; struct sk_buff *skb; u32 wupl; wupl = rd32(E1000_WUPL) & E1000_WUPL_MASK; /* WUPM stores only the first 128 bytes of the wake packet. * Read the packet only if we have the whole thing. */ if ((wupl == 0) || (wupl > E1000_WUPM_BYTES)) return; skb = netdev_alloc_skb_ip_align(netdev, E1000_WUPM_BYTES); if (!skb) return; skb_put(skb, wupl); /* Ensure reads are 32-bit aligned */ wupl = roundup(wupl, 4); memcpy_fromio(skb->data, hw->hw_addr + E1000_WUPM_REG(0), wupl); skb->protocol = eth_type_trans(skb, netdev); netif_rx(skb); } static int __maybe_unused igb_suspend(struct device *dev) { return __igb_shutdown(to_pci_dev(dev), NULL, 0); } static int __maybe_unused __igb_resume(struct device *dev, bool rpm) { struct pci_dev *pdev = to_pci_dev(dev); struct net_device *netdev = pci_get_drvdata(pdev); struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u32 err, val; pci_set_power_state(pdev, PCI_D0); pci_restore_state(pdev); pci_save_state(pdev); if (!pci_device_is_present(pdev)) return -ENODEV; err = pci_enable_device_mem(pdev); if (err) { dev_err(&pdev->dev, "igb: Cannot enable PCI device from suspend\n"); return err; } pci_set_master(pdev); pci_enable_wake(pdev, PCI_D3hot, 0); pci_enable_wake(pdev, PCI_D3cold, 0); if (igb_init_interrupt_scheme(adapter, true)) { dev_err(&pdev->dev, "Unable to allocate memory for queues\n"); return -ENOMEM; } igb_reset(adapter); /* let the f/w know that the h/w is now under the control of the * driver. */ igb_get_hw_control(adapter); val = rd32(E1000_WUS); if (val & WAKE_PKT_WUS) igb_deliver_wake_packet(netdev); wr32(E1000_WUS, ~0); if (!rpm) rtnl_lock(); if (!err && netif_running(netdev)) err = __igb_open(netdev, true); if (!err) netif_device_attach(netdev); if (!rpm) rtnl_unlock(); return err; } static int __maybe_unused igb_resume(struct device *dev) { return __igb_resume(dev, false); } static int __maybe_unused igb_runtime_idle(struct device *dev) { struct net_device *netdev = dev_get_drvdata(dev); struct igb_adapter *adapter = netdev_priv(netdev); if (!igb_has_link(adapter)) pm_schedule_suspend(dev, MSEC_PER_SEC * 5); return -EBUSY; } static int __maybe_unused igb_runtime_suspend(struct device *dev) { return __igb_shutdown(to_pci_dev(dev), NULL, 1); } static int __maybe_unused igb_runtime_resume(struct device *dev) { return __igb_resume(dev, true); } static void igb_shutdown(struct pci_dev *pdev) { bool wake; __igb_shutdown(pdev, &wake, 0); if (system_state == SYSTEM_POWER_OFF) { pci_wake_from_d3(pdev, wake); pci_set_power_state(pdev, PCI_D3hot); } } static int igb_pci_sriov_configure(struct pci_dev *dev, int num_vfs) { #ifdef CONFIG_PCI_IOV int err; if (num_vfs == 0) { return igb_disable_sriov(dev, true); } else { err = igb_enable_sriov(dev, num_vfs, true); return err ? err : num_vfs; } #endif return 0; } /** * igb_io_error_detected - called when PCI error is detected * @pdev: Pointer to PCI device * @state: The current pci connection state * * This function is called after a PCI bus error affecting * this device has been detected. **/ static pci_ers_result_t igb_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state) { struct net_device *netdev = pci_get_drvdata(pdev); struct igb_adapter *adapter = netdev_priv(netdev); if (state == pci_channel_io_normal) { dev_warn(&pdev->dev, "Non-correctable non-fatal error reported.\n"); return PCI_ERS_RESULT_CAN_RECOVER; } netif_device_detach(netdev); if (state == pci_channel_io_perm_failure) return PCI_ERS_RESULT_DISCONNECT; if (netif_running(netdev)) igb_down(adapter); pci_disable_device(pdev); /* Request a slot reset. */ return PCI_ERS_RESULT_NEED_RESET; } /** * igb_io_slot_reset - called after the pci bus has been reset. * @pdev: Pointer to PCI device * * Restart the card from scratch, as if from a cold-boot. Implementation * resembles the first-half of the __igb_resume routine. **/ static pci_ers_result_t igb_io_slot_reset(struct pci_dev *pdev) { struct net_device *netdev = pci_get_drvdata(pdev); struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; pci_ers_result_t result; if (pci_enable_device_mem(pdev)) { dev_err(&pdev->dev, "Cannot re-enable PCI device after reset.\n"); result = PCI_ERS_RESULT_DISCONNECT; } else { pci_set_master(pdev); pci_restore_state(pdev); pci_save_state(pdev); pci_enable_wake(pdev, PCI_D3hot, 0); pci_enable_wake(pdev, PCI_D3cold, 0); /* In case of PCI error, adapter lose its HW address * so we should re-assign it here. */ hw->hw_addr = adapter->io_addr; igb_reset(adapter); wr32(E1000_WUS, ~0); result = PCI_ERS_RESULT_RECOVERED; } return result; } /** * igb_io_resume - called when traffic can start flowing again. * @pdev: Pointer to PCI device * * This callback is called when the error recovery driver tells us that * its OK to resume normal operation. Implementation resembles the * second-half of the __igb_resume routine. */ static void igb_io_resume(struct pci_dev *pdev) { struct net_device *netdev = pci_get_drvdata(pdev); struct igb_adapter *adapter = netdev_priv(netdev); if (netif_running(netdev)) { if (igb_up(adapter)) { dev_err(&pdev->dev, "igb_up failed after reset\n"); return; } } netif_device_attach(netdev); /* let the f/w know that the h/w is now under the control of the * driver. */ igb_get_hw_control(adapter); } /** * igb_rar_set_index - Sync RAL[index] and RAH[index] registers with MAC table * @adapter: Pointer to adapter structure * @index: Index of the RAR entry which need to be synced with MAC table **/ static void igb_rar_set_index(struct igb_adapter *adapter, u32 index) { struct e1000_hw *hw = &adapter->hw; u32 rar_low, rar_high; u8 *addr = adapter->mac_table[index].addr; /* HW expects these to be in network order when they are plugged * into the registers which are little endian. In order to guarantee * that ordering we need to do an leXX_to_cpup here in order to be * ready for the byteswap that occurs with writel */ rar_low = le32_to_cpup((__le32 *)(addr)); rar_high = le16_to_cpup((__le16 *)(addr + 4)); /* Indicate to hardware the Address is Valid. */ if (adapter->mac_table[index].state & IGB_MAC_STATE_IN_USE) { if (is_valid_ether_addr(addr)) rar_high |= E1000_RAH_AV; if (adapter->mac_table[index].state & IGB_MAC_STATE_SRC_ADDR) rar_high |= E1000_RAH_ASEL_SRC_ADDR; switch (hw->mac.type) { case e1000_82575: case e1000_i210: if (adapter->mac_table[index].state & IGB_MAC_STATE_QUEUE_STEERING) rar_high |= E1000_RAH_QSEL_ENABLE; rar_high |= E1000_RAH_POOL_1 * adapter->mac_table[index].queue; break; default: rar_high |= E1000_RAH_POOL_1 << adapter->mac_table[index].queue; break; } } wr32(E1000_RAL(index), rar_low); wrfl(); wr32(E1000_RAH(index), rar_high); wrfl(); } static int igb_set_vf_mac(struct igb_adapter *adapter, int vf, unsigned char *mac_addr) { struct e1000_hw *hw = &adapter->hw; /* VF MAC addresses start at end of receive addresses and moves * towards the first, as a result a collision should not be possible */ int rar_entry = hw->mac.rar_entry_count - (vf + 1); unsigned char *vf_mac_addr = adapter->vf_data[vf].vf_mac_addresses; ether_addr_copy(vf_mac_addr, mac_addr); ether_addr_copy(adapter->mac_table[rar_entry].addr, mac_addr); adapter->mac_table[rar_entry].queue = vf; adapter->mac_table[rar_entry].state |= IGB_MAC_STATE_IN_USE; igb_rar_set_index(adapter, rar_entry); return 0; } static int igb_ndo_set_vf_mac(struct net_device *netdev, int vf, u8 *mac) { struct igb_adapter *adapter = netdev_priv(netdev); if (vf >= adapter->vfs_allocated_count) return -EINVAL; /* Setting the VF MAC to 0 reverts the IGB_VF_FLAG_PF_SET_MAC * flag and allows to overwrite the MAC via VF netdev. This * is necessary to allow libvirt a way to restore the original * MAC after unbinding vfio-pci and reloading igbvf after shutting * down a VM. */ if (is_zero_ether_addr(mac)) { adapter->vf_data[vf].flags &= ~IGB_VF_FLAG_PF_SET_MAC; dev_info(&adapter->pdev->dev, "remove administratively set MAC on VF %d\n", vf); } else if (is_valid_ether_addr(mac)) { adapter->vf_data[vf].flags |= IGB_VF_FLAG_PF_SET_MAC; dev_info(&adapter->pdev->dev, "setting MAC %pM on VF %d\n", mac, vf); dev_info(&adapter->pdev->dev, "Reload the VF driver to make this change effective."); /* Generate additional warning if PF is down */ if (test_bit(__IGB_DOWN, &adapter->state)) { dev_warn(&adapter->pdev->dev, "The VF MAC address has been set, but the PF device is not up.\n"); dev_warn(&adapter->pdev->dev, "Bring the PF device up before attempting to use the VF device.\n"); } } else { return -EINVAL; } return igb_set_vf_mac(adapter, vf, mac); } static int igb_link_mbps(int internal_link_speed) { switch (internal_link_speed) { case SPEED_100: return 100; case SPEED_1000: return 1000; default: return 0; } } static void igb_set_vf_rate_limit(struct e1000_hw *hw, int vf, int tx_rate, int link_speed) { int rf_dec, rf_int; u32 bcnrc_val; if (tx_rate != 0) { /* Calculate the rate factor values to set */ rf_int = link_speed / tx_rate; rf_dec = (link_speed - (rf_int * tx_rate)); rf_dec = (rf_dec * BIT(E1000_RTTBCNRC_RF_INT_SHIFT)) / tx_rate; bcnrc_val = E1000_RTTBCNRC_RS_ENA; bcnrc_val |= ((rf_int << E1000_RTTBCNRC_RF_INT_SHIFT) & E1000_RTTBCNRC_RF_INT_MASK); bcnrc_val |= (rf_dec & E1000_RTTBCNRC_RF_DEC_MASK); } else { bcnrc_val = 0; } wr32(E1000_RTTDQSEL, vf); /* vf X uses queue X */ /* Set global transmit compensation time to the MMW_SIZE in RTTBCNRM * register. MMW_SIZE=0x014 if 9728-byte jumbo is supported. */ wr32(E1000_RTTBCNRM, 0x14); wr32(E1000_RTTBCNRC, bcnrc_val); } static void igb_check_vf_rate_limit(struct igb_adapter *adapter) { int actual_link_speed, i; bool reset_rate = false; /* VF TX rate limit was not set or not supported */ if ((adapter->vf_rate_link_speed == 0) || (adapter->hw.mac.type != e1000_82576)) return; actual_link_speed = igb_link_mbps(adapter->link_speed); if (actual_link_speed != adapter->vf_rate_link_speed) { reset_rate = true; adapter->vf_rate_link_speed = 0; dev_info(&adapter->pdev->dev, "Link speed has been changed. VF Transmit rate is disabled\n"); } for (i = 0; i < adapter->vfs_allocated_count; i++) { if (reset_rate) adapter->vf_data[i].tx_rate = 0; igb_set_vf_rate_limit(&adapter->hw, i, adapter->vf_data[i].tx_rate, actual_link_speed); } } static int igb_ndo_set_vf_bw(struct net_device *netdev, int vf, int min_tx_rate, int max_tx_rate) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; int actual_link_speed; if (hw->mac.type != e1000_82576) return -EOPNOTSUPP; if (min_tx_rate) return -EINVAL; actual_link_speed = igb_link_mbps(adapter->link_speed); if ((vf >= adapter->vfs_allocated_count) || (!(rd32(E1000_STATUS) & E1000_STATUS_LU)) || (max_tx_rate < 0) || (max_tx_rate > actual_link_speed)) return -EINVAL; adapter->vf_rate_link_speed = actual_link_speed; adapter->vf_data[vf].tx_rate = (u16)max_tx_rate; igb_set_vf_rate_limit(hw, vf, max_tx_rate, actual_link_speed); return 0; } static int igb_ndo_set_vf_spoofchk(struct net_device *netdev, int vf, bool setting) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u32 reg_val, reg_offset; if (!adapter->vfs_allocated_count) return -EOPNOTSUPP; if (vf >= adapter->vfs_allocated_count) return -EINVAL; reg_offset = (hw->mac.type == e1000_82576) ? E1000_DTXSWC : E1000_TXSWC; reg_val = rd32(reg_offset); if (setting) reg_val |= (BIT(vf) | BIT(vf + E1000_DTXSWC_VLAN_SPOOF_SHIFT)); else reg_val &= ~(BIT(vf) | BIT(vf + E1000_DTXSWC_VLAN_SPOOF_SHIFT)); wr32(reg_offset, reg_val); adapter->vf_data[vf].spoofchk_enabled = setting; return 0; } static int igb_ndo_set_vf_trust(struct net_device *netdev, int vf, bool setting) { struct igb_adapter *adapter = netdev_priv(netdev); if (vf >= adapter->vfs_allocated_count) return -EINVAL; if (adapter->vf_data[vf].trusted == setting) return 0; adapter->vf_data[vf].trusted = setting; dev_info(&adapter->pdev->dev, "VF %u is %strusted\n", vf, setting ? "" : "not "); return 0; } static int igb_ndo_get_vf_config(struct net_device *netdev, int vf, struct ifla_vf_info *ivi) { struct igb_adapter *adapter = netdev_priv(netdev); if (vf >= adapter->vfs_allocated_count) return -EINVAL; ivi->vf = vf; memcpy(&ivi->mac, adapter->vf_data[vf].vf_mac_addresses, ETH_ALEN); ivi->max_tx_rate = adapter->vf_data[vf].tx_rate; ivi->min_tx_rate = 0; ivi->vlan = adapter->vf_data[vf].pf_vlan; ivi->qos = adapter->vf_data[vf].pf_qos; ivi->spoofchk = adapter->vf_data[vf].spoofchk_enabled; ivi->trusted = adapter->vf_data[vf].trusted; return 0; } static void igb_vmm_control(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 reg; switch (hw->mac.type) { case e1000_82575: case e1000_i210: case e1000_i211: case e1000_i354: default: /* replication is not supported for 82575 */ return; case e1000_82576: /* notify HW that the MAC is adding vlan tags */ reg = rd32(E1000_DTXCTL); reg |= E1000_DTXCTL_VLAN_ADDED; wr32(E1000_DTXCTL, reg); fallthrough; case e1000_82580: /* enable replication vlan tag stripping */ reg = rd32(E1000_RPLOLR); reg |= E1000_RPLOLR_STRVLAN; wr32(E1000_RPLOLR, reg); fallthrough; case e1000_i350: /* none of the above registers are supported by i350 */ break; } if (adapter->vfs_allocated_count) { igb_vmdq_set_loopback_pf(hw, true); igb_vmdq_set_replication_pf(hw, true); igb_vmdq_set_anti_spoofing_pf(hw, true, adapter->vfs_allocated_count); } else { igb_vmdq_set_loopback_pf(hw, false); igb_vmdq_set_replication_pf(hw, false); } } static void igb_init_dmac(struct igb_adapter *adapter, u32 pba) { struct e1000_hw *hw = &adapter->hw; u32 dmac_thr; u16 hwm; u32 reg; if (hw->mac.type > e1000_82580) { if (adapter->flags & IGB_FLAG_DMAC) { /* force threshold to 0. */ wr32(E1000_DMCTXTH, 0); /* DMA Coalescing high water mark needs to be greater * than the Rx threshold. Set hwm to PBA - max frame * size in 16B units, capping it at PBA - 6KB. */ hwm = 64 * (pba - 6); reg = rd32(E1000_FCRTC); reg &= ~E1000_FCRTC_RTH_COAL_MASK; reg |= ((hwm << E1000_FCRTC_RTH_COAL_SHIFT) & E1000_FCRTC_RTH_COAL_MASK); wr32(E1000_FCRTC, reg); /* Set the DMA Coalescing Rx threshold to PBA - 2 * max * frame size, capping it at PBA - 10KB. */ dmac_thr = pba - 10; reg = rd32(E1000_DMACR); reg &= ~E1000_DMACR_DMACTHR_MASK; reg |= ((dmac_thr << E1000_DMACR_DMACTHR_SHIFT) & E1000_DMACR_DMACTHR_MASK); /* transition to L0x or L1 if available..*/ reg |= (E1000_DMACR_DMAC_EN | E1000_DMACR_DMAC_LX_MASK); /* watchdog timer= +-1000 usec in 32usec intervals */ reg |= (1000 >> 5); /* Disable BMC-to-OS Watchdog Enable */ if (hw->mac.type != e1000_i354) reg &= ~E1000_DMACR_DC_BMC2OSW_EN; wr32(E1000_DMACR, reg); /* no lower threshold to disable * coalescing(smart fifb)-UTRESH=0 */ wr32(E1000_DMCRTRH, 0); reg = (IGB_DMCTLX_DCFLUSH_DIS | 0x4); wr32(E1000_DMCTLX, reg); /* free space in tx packet buffer to wake from * DMA coal */ wr32(E1000_DMCTXTH, (IGB_MIN_TXPBSIZE - (IGB_TX_BUF_4096 + adapter->max_frame_size)) >> 6); } if (hw->mac.type >= e1000_i210 || (adapter->flags & IGB_FLAG_DMAC)) { reg = rd32(E1000_PCIEMISC); reg |= E1000_PCIEMISC_LX_DECISION; wr32(E1000_PCIEMISC, reg); } /* endif adapter->dmac is not disabled */ } else if (hw->mac.type == e1000_82580) { u32 reg = rd32(E1000_PCIEMISC); wr32(E1000_PCIEMISC, reg & ~E1000_PCIEMISC_LX_DECISION); wr32(E1000_DMACR, 0); } } /** * igb_read_i2c_byte - Reads 8 bit word over I2C * @hw: pointer to hardware structure * @byte_offset: byte offset to read * @dev_addr: device address * @data: value read * * Performs byte read operation over I2C interface at * a specified device address. **/ s32 igb_read_i2c_byte(struct e1000_hw *hw, u8 byte_offset, u8 dev_addr, u8 *data) { struct igb_adapter *adapter = container_of(hw, struct igb_adapter, hw); struct i2c_client *this_client = adapter->i2c_client; s32 status; u16 swfw_mask = 0; if (!this_client) return E1000_ERR_I2C; swfw_mask = E1000_SWFW_PHY0_SM; if (hw->mac.ops.acquire_swfw_sync(hw, swfw_mask)) return E1000_ERR_SWFW_SYNC; status = i2c_smbus_read_byte_data(this_client, byte_offset); hw->mac.ops.release_swfw_sync(hw, swfw_mask); if (status < 0) return E1000_ERR_I2C; else { *data = status; return 0; } } /** * igb_write_i2c_byte - Writes 8 bit word over I2C * @hw: pointer to hardware structure * @byte_offset: byte offset to write * @dev_addr: device address * @data: value to write * * Performs byte write operation over I2C interface at * a specified device address. **/ s32 igb_write_i2c_byte(struct e1000_hw *hw, u8 byte_offset, u8 dev_addr, u8 data) { struct igb_adapter *adapter = container_of(hw, struct igb_adapter, hw); struct i2c_client *this_client = adapter->i2c_client; s32 status; u16 swfw_mask = E1000_SWFW_PHY0_SM; if (!this_client) return E1000_ERR_I2C; if (hw->mac.ops.acquire_swfw_sync(hw, swfw_mask)) return E1000_ERR_SWFW_SYNC; status = i2c_smbus_write_byte_data(this_client, byte_offset, data); hw->mac.ops.release_swfw_sync(hw, swfw_mask); if (status) return E1000_ERR_I2C; else return 0; } int igb_reinit_queues(struct igb_adapter *adapter) { struct net_device *netdev = adapter->netdev; struct pci_dev *pdev = adapter->pdev; int err = 0; if (netif_running(netdev)) igb_close(netdev); igb_reset_interrupt_capability(adapter); if (igb_init_interrupt_scheme(adapter, true)) { dev_err(&pdev->dev, "Unable to allocate memory for queues\n"); return -ENOMEM; } if (netif_running(netdev)) err = igb_open(netdev); return err; } static void igb_nfc_filter_exit(struct igb_adapter *adapter) { struct igb_nfc_filter *rule; spin_lock(&adapter->nfc_lock); hlist_for_each_entry(rule, &adapter->nfc_filter_list, nfc_node) igb_erase_filter(adapter, rule); hlist_for_each_entry(rule, &adapter->cls_flower_list, nfc_node) igb_erase_filter(adapter, rule); spin_unlock(&adapter->nfc_lock); } static void igb_nfc_filter_restore(struct igb_adapter *adapter) { struct igb_nfc_filter *rule; spin_lock(&adapter->nfc_lock); hlist_for_each_entry(rule, &adapter->nfc_filter_list, nfc_node) igb_add_filter(adapter, rule); spin_unlock(&adapter->nfc_lock); } /* igb_main.c */
linux-master
drivers/net/ethernet/intel/igb/igb_main.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2007 - 2018 Intel Corporation. */ #include <linux/if_ether.h> #include <linux/delay.h> #include "e1000_mac.h" #include "e1000_nvm.h" /** * igb_raise_eec_clk - Raise EEPROM clock * @hw: pointer to the HW structure * @eecd: pointer to the EEPROM * * Enable/Raise the EEPROM clock bit. **/ static void igb_raise_eec_clk(struct e1000_hw *hw, u32 *eecd) { *eecd = *eecd | E1000_EECD_SK; wr32(E1000_EECD, *eecd); wrfl(); udelay(hw->nvm.delay_usec); } /** * igb_lower_eec_clk - Lower EEPROM clock * @hw: pointer to the HW structure * @eecd: pointer to the EEPROM * * Clear/Lower the EEPROM clock bit. **/ static void igb_lower_eec_clk(struct e1000_hw *hw, u32 *eecd) { *eecd = *eecd & ~E1000_EECD_SK; wr32(E1000_EECD, *eecd); wrfl(); udelay(hw->nvm.delay_usec); } /** * igb_shift_out_eec_bits - Shift data bits our to the EEPROM * @hw: pointer to the HW structure * @data: data to send to the EEPROM * @count: number of bits to shift out * * We need to shift 'count' bits out to the EEPROM. So, the value in the * "data" parameter will be shifted out to the EEPROM one bit at a time. * In order to do this, "data" must be broken down into bits. **/ static void igb_shift_out_eec_bits(struct e1000_hw *hw, u16 data, u16 count) { struct e1000_nvm_info *nvm = &hw->nvm; u32 eecd = rd32(E1000_EECD); u32 mask; mask = 1u << (count - 1); if (nvm->type == e1000_nvm_eeprom_spi) eecd |= E1000_EECD_DO; do { eecd &= ~E1000_EECD_DI; if (data & mask) eecd |= E1000_EECD_DI; wr32(E1000_EECD, eecd); wrfl(); udelay(nvm->delay_usec); igb_raise_eec_clk(hw, &eecd); igb_lower_eec_clk(hw, &eecd); mask >>= 1; } while (mask); eecd &= ~E1000_EECD_DI; wr32(E1000_EECD, eecd); } /** * igb_shift_in_eec_bits - Shift data bits in from the EEPROM * @hw: pointer to the HW structure * @count: number of bits to shift in * * In order to read a register from the EEPROM, we need to shift 'count' bits * in from the EEPROM. Bits are "shifted in" by raising the clock input to * the EEPROM (setting the SK bit), and then reading the value of the data out * "DO" bit. During this "shifting in" process the data in "DI" bit should * always be clear. **/ static u16 igb_shift_in_eec_bits(struct e1000_hw *hw, u16 count) { u32 eecd; u32 i; u16 data; eecd = rd32(E1000_EECD); eecd &= ~(E1000_EECD_DO | E1000_EECD_DI); data = 0; for (i = 0; i < count; i++) { data <<= 1; igb_raise_eec_clk(hw, &eecd); eecd = rd32(E1000_EECD); eecd &= ~E1000_EECD_DI; if (eecd & E1000_EECD_DO) data |= 1; igb_lower_eec_clk(hw, &eecd); } return data; } /** * igb_poll_eerd_eewr_done - Poll for EEPROM read/write completion * @hw: pointer to the HW structure * @ee_reg: EEPROM flag for polling * * Polls the EEPROM status bit for either read or write completion based * upon the value of 'ee_reg'. **/ static s32 igb_poll_eerd_eewr_done(struct e1000_hw *hw, int ee_reg) { u32 attempts = 100000; u32 i, reg = 0; s32 ret_val = -E1000_ERR_NVM; for (i = 0; i < attempts; i++) { if (ee_reg == E1000_NVM_POLL_READ) reg = rd32(E1000_EERD); else reg = rd32(E1000_EEWR); if (reg & E1000_NVM_RW_REG_DONE) { ret_val = 0; break; } udelay(5); } return ret_val; } /** * igb_acquire_nvm - Generic request for access to EEPROM * @hw: pointer to the HW structure * * Set the EEPROM access request bit and wait for EEPROM access grant bit. * Return successful if access grant bit set, else clear the request for * EEPROM access and return -E1000_ERR_NVM (-1). **/ s32 igb_acquire_nvm(struct e1000_hw *hw) { u32 eecd = rd32(E1000_EECD); s32 timeout = E1000_NVM_GRANT_ATTEMPTS; s32 ret_val = 0; wr32(E1000_EECD, eecd | E1000_EECD_REQ); eecd = rd32(E1000_EECD); while (timeout) { if (eecd & E1000_EECD_GNT) break; udelay(5); eecd = rd32(E1000_EECD); timeout--; } if (!timeout) { eecd &= ~E1000_EECD_REQ; wr32(E1000_EECD, eecd); hw_dbg("Could not acquire NVM grant\n"); ret_val = -E1000_ERR_NVM; } return ret_val; } /** * igb_standby_nvm - Return EEPROM to standby state * @hw: pointer to the HW structure * * Return the EEPROM to a standby state. **/ static void igb_standby_nvm(struct e1000_hw *hw) { struct e1000_nvm_info *nvm = &hw->nvm; u32 eecd = rd32(E1000_EECD); if (nvm->type == e1000_nvm_eeprom_spi) { /* Toggle CS to flush commands */ eecd |= E1000_EECD_CS; wr32(E1000_EECD, eecd); wrfl(); udelay(nvm->delay_usec); eecd &= ~E1000_EECD_CS; wr32(E1000_EECD, eecd); wrfl(); udelay(nvm->delay_usec); } } /** * e1000_stop_nvm - Terminate EEPROM command * @hw: pointer to the HW structure * * Terminates the current command by inverting the EEPROM's chip select pin. **/ static void e1000_stop_nvm(struct e1000_hw *hw) { u32 eecd; eecd = rd32(E1000_EECD); if (hw->nvm.type == e1000_nvm_eeprom_spi) { /* Pull CS high */ eecd |= E1000_EECD_CS; igb_lower_eec_clk(hw, &eecd); } } /** * igb_release_nvm - Release exclusive access to EEPROM * @hw: pointer to the HW structure * * Stop any current commands to the EEPROM and clear the EEPROM request bit. **/ void igb_release_nvm(struct e1000_hw *hw) { u32 eecd; e1000_stop_nvm(hw); eecd = rd32(E1000_EECD); eecd &= ~E1000_EECD_REQ; wr32(E1000_EECD, eecd); } /** * igb_ready_nvm_eeprom - Prepares EEPROM for read/write * @hw: pointer to the HW structure * * Setups the EEPROM for reading and writing. **/ static s32 igb_ready_nvm_eeprom(struct e1000_hw *hw) { struct e1000_nvm_info *nvm = &hw->nvm; u32 eecd = rd32(E1000_EECD); s32 ret_val = 0; u16 timeout = 0; u8 spi_stat_reg; if (nvm->type == e1000_nvm_eeprom_spi) { /* Clear SK and CS */ eecd &= ~(E1000_EECD_CS | E1000_EECD_SK); wr32(E1000_EECD, eecd); wrfl(); udelay(1); timeout = NVM_MAX_RETRY_SPI; /* Read "Status Register" repeatedly until the LSB is cleared. * The EEPROM will signal that the command has been completed * by clearing bit 0 of the internal status register. If it's * not cleared within 'timeout', then error out. */ while (timeout) { igb_shift_out_eec_bits(hw, NVM_RDSR_OPCODE_SPI, hw->nvm.opcode_bits); spi_stat_reg = (u8)igb_shift_in_eec_bits(hw, 8); if (!(spi_stat_reg & NVM_STATUS_RDY_SPI)) break; udelay(5); igb_standby_nvm(hw); timeout--; } if (!timeout) { hw_dbg("SPI NVM Status error\n"); ret_val = -E1000_ERR_NVM; goto out; } } out: return ret_val; } /** * igb_read_nvm_spi - Read EEPROM's using SPI * @hw: pointer to the HW structure * @offset: offset of word in the EEPROM to read * @words: number of words to read * @data: word read from the EEPROM * * Reads a 16 bit word from the EEPROM. **/ s32 igb_read_nvm_spi(struct e1000_hw *hw, u16 offset, u16 words, u16 *data) { struct e1000_nvm_info *nvm = &hw->nvm; u32 i = 0; s32 ret_val; u16 word_in; u8 read_opcode = NVM_READ_OPCODE_SPI; /* A check for invalid values: offset too large, too many words, * and not enough words. */ if ((offset >= nvm->word_size) || (words > (nvm->word_size - offset)) || (words == 0)) { hw_dbg("nvm parameter(s) out of bounds\n"); ret_val = -E1000_ERR_NVM; goto out; } ret_val = nvm->ops.acquire(hw); if (ret_val) goto out; ret_val = igb_ready_nvm_eeprom(hw); if (ret_val) goto release; igb_standby_nvm(hw); if ((nvm->address_bits == 8) && (offset >= 128)) read_opcode |= NVM_A8_OPCODE_SPI; /* Send the READ command (opcode + addr) */ igb_shift_out_eec_bits(hw, read_opcode, nvm->opcode_bits); igb_shift_out_eec_bits(hw, (u16)(offset*2), nvm->address_bits); /* Read the data. SPI NVMs increment the address with each byte * read and will roll over if reading beyond the end. This allows * us to read the whole NVM from any offset */ for (i = 0; i < words; i++) { word_in = igb_shift_in_eec_bits(hw, 16); data[i] = (word_in >> 8) | (word_in << 8); } release: nvm->ops.release(hw); out: return ret_val; } /** * igb_read_nvm_eerd - Reads EEPROM using EERD register * @hw: pointer to the HW structure * @offset: offset of word in the EEPROM to read * @words: number of words to read * @data: word read from the EEPROM * * Reads a 16 bit word from the EEPROM using the EERD register. **/ s32 igb_read_nvm_eerd(struct e1000_hw *hw, u16 offset, u16 words, u16 *data) { struct e1000_nvm_info *nvm = &hw->nvm; u32 i, eerd = 0; s32 ret_val = 0; /* A check for invalid values: offset too large, too many words, * and not enough words. */ if ((offset >= nvm->word_size) || (words > (nvm->word_size - offset)) || (words == 0)) { hw_dbg("nvm parameter(s) out of bounds\n"); ret_val = -E1000_ERR_NVM; goto out; } for (i = 0; i < words; i++) { eerd = ((offset+i) << E1000_NVM_RW_ADDR_SHIFT) + E1000_NVM_RW_REG_START; wr32(E1000_EERD, eerd); ret_val = igb_poll_eerd_eewr_done(hw, E1000_NVM_POLL_READ); if (ret_val) break; data[i] = (rd32(E1000_EERD) >> E1000_NVM_RW_REG_DATA); } out: return ret_val; } /** * igb_write_nvm_spi - Write to EEPROM using SPI * @hw: pointer to the HW structure * @offset: offset within the EEPROM to be written to * @words: number of words to write * @data: 16 bit word(s) to be written to the EEPROM * * Writes data to EEPROM at offset using SPI interface. * * If e1000_update_nvm_checksum is not called after this function , the * EEPROM will most likley contain an invalid checksum. **/ s32 igb_write_nvm_spi(struct e1000_hw *hw, u16 offset, u16 words, u16 *data) { struct e1000_nvm_info *nvm = &hw->nvm; s32 ret_val = -E1000_ERR_NVM; u16 widx = 0; /* A check for invalid values: offset too large, too many words, * and not enough words. */ if ((offset >= nvm->word_size) || (words > (nvm->word_size - offset)) || (words == 0)) { hw_dbg("nvm parameter(s) out of bounds\n"); return ret_val; } while (widx < words) { u8 write_opcode = NVM_WRITE_OPCODE_SPI; ret_val = nvm->ops.acquire(hw); if (ret_val) return ret_val; ret_val = igb_ready_nvm_eeprom(hw); if (ret_val) { nvm->ops.release(hw); return ret_val; } igb_standby_nvm(hw); /* Send the WRITE ENABLE command (8 bit opcode) */ igb_shift_out_eec_bits(hw, NVM_WREN_OPCODE_SPI, nvm->opcode_bits); igb_standby_nvm(hw); /* Some SPI eeproms use the 8th address bit embedded in the * opcode */ if ((nvm->address_bits == 8) && (offset >= 128)) write_opcode |= NVM_A8_OPCODE_SPI; /* Send the Write command (8-bit opcode + addr) */ igb_shift_out_eec_bits(hw, write_opcode, nvm->opcode_bits); igb_shift_out_eec_bits(hw, (u16)((offset + widx) * 2), nvm->address_bits); /* Loop to allow for up to whole page write of eeprom */ while (widx < words) { u16 word_out = data[widx]; word_out = (word_out >> 8) | (word_out << 8); igb_shift_out_eec_bits(hw, word_out, 16); widx++; if ((((offset + widx) * 2) % nvm->page_size) == 0) { igb_standby_nvm(hw); break; } } usleep_range(1000, 2000); nvm->ops.release(hw); } return ret_val; } /** * igb_read_part_string - Read device part number * @hw: pointer to the HW structure * @part_num: pointer to device part number * @part_num_size: size of part number buffer * * Reads the product board assembly (PBA) number from the EEPROM and stores * the value in part_num. **/ s32 igb_read_part_string(struct e1000_hw *hw, u8 *part_num, u32 part_num_size) { s32 ret_val; u16 nvm_data; u16 pointer; u16 offset; u16 length; if (part_num == NULL) { hw_dbg("PBA string buffer was null\n"); ret_val = E1000_ERR_INVALID_ARGUMENT; goto out; } ret_val = hw->nvm.ops.read(hw, NVM_PBA_OFFSET_0, 1, &nvm_data); if (ret_val) { hw_dbg("NVM Read Error\n"); goto out; } ret_val = hw->nvm.ops.read(hw, NVM_PBA_OFFSET_1, 1, &pointer); if (ret_val) { hw_dbg("NVM Read Error\n"); goto out; } /* if nvm_data is not ptr guard the PBA must be in legacy format which * means pointer is actually our second data word for the PBA number * and we can decode it into an ascii string */ if (nvm_data != NVM_PBA_PTR_GUARD) { hw_dbg("NVM PBA number is not stored as string\n"); /* we will need 11 characters to store the PBA */ if (part_num_size < 11) { hw_dbg("PBA string buffer too small\n"); return E1000_ERR_NO_SPACE; } /* extract hex string from data and pointer */ part_num[0] = (nvm_data >> 12) & 0xF; part_num[1] = (nvm_data >> 8) & 0xF; part_num[2] = (nvm_data >> 4) & 0xF; part_num[3] = nvm_data & 0xF; part_num[4] = (pointer >> 12) & 0xF; part_num[5] = (pointer >> 8) & 0xF; part_num[6] = '-'; part_num[7] = 0; part_num[8] = (pointer >> 4) & 0xF; part_num[9] = pointer & 0xF; /* put a null character on the end of our string */ part_num[10] = '\0'; /* switch all the data but the '-' to hex char */ for (offset = 0; offset < 10; offset++) { if (part_num[offset] < 0xA) part_num[offset] += '0'; else if (part_num[offset] < 0x10) part_num[offset] += 'A' - 0xA; } goto out; } ret_val = hw->nvm.ops.read(hw, pointer, 1, &length); if (ret_val) { hw_dbg("NVM Read Error\n"); goto out; } if (length == 0xFFFF || length == 0) { hw_dbg("NVM PBA number section invalid length\n"); ret_val = E1000_ERR_NVM_PBA_SECTION; goto out; } /* check if part_num buffer is big enough */ if (part_num_size < (((u32)length * 2) - 1)) { hw_dbg("PBA string buffer too small\n"); ret_val = E1000_ERR_NO_SPACE; goto out; } /* trim pba length from start of string */ pointer++; length--; for (offset = 0; offset < length; offset++) { ret_val = hw->nvm.ops.read(hw, pointer + offset, 1, &nvm_data); if (ret_val) { hw_dbg("NVM Read Error\n"); goto out; } part_num[offset * 2] = (u8)(nvm_data >> 8); part_num[(offset * 2) + 1] = (u8)(nvm_data & 0xFF); } part_num[offset * 2] = '\0'; out: return ret_val; } /** * igb_read_mac_addr - Read device MAC address * @hw: pointer to the HW structure * * Reads the device MAC address from the EEPROM and stores the value. * Since devices with two ports use the same EEPROM, we increment the * last bit in the MAC address for the second port. **/ s32 igb_read_mac_addr(struct e1000_hw *hw) { u32 rar_high; u32 rar_low; u16 i; rar_high = rd32(E1000_RAH(0)); rar_low = rd32(E1000_RAL(0)); for (i = 0; i < E1000_RAL_MAC_ADDR_LEN; i++) hw->mac.perm_addr[i] = (u8)(rar_low >> (i*8)); for (i = 0; i < E1000_RAH_MAC_ADDR_LEN; i++) hw->mac.perm_addr[i+4] = (u8)(rar_high >> (i*8)); for (i = 0; i < ETH_ALEN; i++) hw->mac.addr[i] = hw->mac.perm_addr[i]; return 0; } /** * igb_validate_nvm_checksum - Validate EEPROM checksum * @hw: pointer to the HW structure * * Calculates the EEPROM checksum by reading/adding each word of the EEPROM * and then verifies that the sum of the EEPROM is equal to 0xBABA. **/ s32 igb_validate_nvm_checksum(struct e1000_hw *hw) { s32 ret_val = 0; u16 checksum = 0; u16 i, nvm_data; for (i = 0; i < (NVM_CHECKSUM_REG + 1); i++) { ret_val = hw->nvm.ops.read(hw, i, 1, &nvm_data); if (ret_val) { hw_dbg("NVM Read Error\n"); goto out; } checksum += nvm_data; } if (checksum != (u16) NVM_SUM) { hw_dbg("NVM Checksum Invalid\n"); ret_val = -E1000_ERR_NVM; goto out; } out: return ret_val; } /** * igb_update_nvm_checksum - Update EEPROM checksum * @hw: pointer to the HW structure * * Updates the EEPROM checksum by reading/adding each word of the EEPROM * up to the checksum. Then calculates the EEPROM checksum and writes the * value to the EEPROM. **/ s32 igb_update_nvm_checksum(struct e1000_hw *hw) { s32 ret_val; u16 checksum = 0; u16 i, nvm_data; for (i = 0; i < NVM_CHECKSUM_REG; i++) { ret_val = hw->nvm.ops.read(hw, i, 1, &nvm_data); if (ret_val) { hw_dbg("NVM Read Error while updating checksum.\n"); goto out; } checksum += nvm_data; } checksum = (u16) NVM_SUM - checksum; ret_val = hw->nvm.ops.write(hw, NVM_CHECKSUM_REG, 1, &checksum); if (ret_val) hw_dbg("NVM Write Error while updating checksum.\n"); out: return ret_val; } /** * igb_get_fw_version - Get firmware version information * @hw: pointer to the HW structure * @fw_vers: pointer to output structure * * unsupported MAC types will return all 0 version structure **/ void igb_get_fw_version(struct e1000_hw *hw, struct e1000_fw_version *fw_vers) { u16 eeprom_verh, eeprom_verl, etrack_test, fw_version; u8 q, hval, rem, result; u16 comb_verh, comb_verl, comb_offset; memset(fw_vers, 0, sizeof(struct e1000_fw_version)); /* basic eeprom version numbers and bits used vary by part and by tool * used to create the nvm images. Check which data format we have. */ hw->nvm.ops.read(hw, NVM_ETRACK_HIWORD, 1, &etrack_test); switch (hw->mac.type) { case e1000_i211: igb_read_invm_version(hw, fw_vers); return; case e1000_82575: case e1000_82576: case e1000_82580: /* Use this format, unless EETRACK ID exists, * then use alternate format */ if ((etrack_test & NVM_MAJOR_MASK) != NVM_ETRACK_VALID) { hw->nvm.ops.read(hw, NVM_VERSION, 1, &fw_version); fw_vers->eep_major = (fw_version & NVM_MAJOR_MASK) >> NVM_MAJOR_SHIFT; fw_vers->eep_minor = (fw_version & NVM_MINOR_MASK) >> NVM_MINOR_SHIFT; fw_vers->eep_build = (fw_version & NVM_IMAGE_ID_MASK); goto etrack_id; } break; case e1000_i210: if (!(igb_get_flash_presence_i210(hw))) { igb_read_invm_version(hw, fw_vers); return; } fallthrough; case e1000_i350: /* find combo image version */ hw->nvm.ops.read(hw, NVM_COMB_VER_PTR, 1, &comb_offset); if ((comb_offset != 0x0) && (comb_offset != NVM_VER_INVALID)) { hw->nvm.ops.read(hw, (NVM_COMB_VER_OFF + comb_offset + 1), 1, &comb_verh); hw->nvm.ops.read(hw, (NVM_COMB_VER_OFF + comb_offset), 1, &comb_verl); /* get Option Rom version if it exists and is valid */ if ((comb_verh && comb_verl) && ((comb_verh != NVM_VER_INVALID) && (comb_verl != NVM_VER_INVALID))) { fw_vers->or_valid = true; fw_vers->or_major = comb_verl >> NVM_COMB_VER_SHFT; fw_vers->or_build = (comb_verl << NVM_COMB_VER_SHFT) | (comb_verh >> NVM_COMB_VER_SHFT); fw_vers->or_patch = comb_verh & NVM_COMB_VER_MASK; } } break; default: return; } hw->nvm.ops.read(hw, NVM_VERSION, 1, &fw_version); fw_vers->eep_major = (fw_version & NVM_MAJOR_MASK) >> NVM_MAJOR_SHIFT; /* check for old style version format in newer images*/ if ((fw_version & NVM_NEW_DEC_MASK) == 0x0) { eeprom_verl = (fw_version & NVM_COMB_VER_MASK); } else { eeprom_verl = (fw_version & NVM_MINOR_MASK) >> NVM_MINOR_SHIFT; } /* Convert minor value to hex before assigning to output struct * Val to be converted will not be higher than 99, per tool output */ q = eeprom_verl / NVM_HEX_CONV; hval = q * NVM_HEX_TENS; rem = eeprom_verl % NVM_HEX_CONV; result = hval + rem; fw_vers->eep_minor = result; etrack_id: if ((etrack_test & NVM_MAJOR_MASK) == NVM_ETRACK_VALID) { hw->nvm.ops.read(hw, NVM_ETRACK_WORD, 1, &eeprom_verl); hw->nvm.ops.read(hw, (NVM_ETRACK_WORD + 1), 1, &eeprom_verh); fw_vers->etrack_id = (eeprom_verh << NVM_ETRACK_SHIFT) | eeprom_verl; } }
linux-master
drivers/net/ethernet/intel/igb/e1000_nvm.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2007 - 2018 Intel Corporation. */ #include <linux/if_ether.h> #include <linux/delay.h> #include <linux/pci.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include "e1000_mac.h" #include "igb.h" static s32 igb_set_default_fc(struct e1000_hw *hw); static void igb_set_fc_watermarks(struct e1000_hw *hw); /** * igb_get_bus_info_pcie - Get PCIe bus information * @hw: pointer to the HW structure * * Determines and stores the system bus information for a particular * network interface. The following bus information is determined and stored: * bus speed, bus width, type (PCIe), and PCIe function. **/ s32 igb_get_bus_info_pcie(struct e1000_hw *hw) { struct e1000_bus_info *bus = &hw->bus; s32 ret_val; u32 reg; u16 pcie_link_status; bus->type = e1000_bus_type_pci_express; ret_val = igb_read_pcie_cap_reg(hw, PCI_EXP_LNKSTA, &pcie_link_status); if (ret_val) { bus->width = e1000_bus_width_unknown; bus->speed = e1000_bus_speed_unknown; } else { switch (pcie_link_status & PCI_EXP_LNKSTA_CLS) { case PCI_EXP_LNKSTA_CLS_2_5GB: bus->speed = e1000_bus_speed_2500; break; case PCI_EXP_LNKSTA_CLS_5_0GB: bus->speed = e1000_bus_speed_5000; break; default: bus->speed = e1000_bus_speed_unknown; break; } bus->width = (enum e1000_bus_width)((pcie_link_status & PCI_EXP_LNKSTA_NLW) >> PCI_EXP_LNKSTA_NLW_SHIFT); } reg = rd32(E1000_STATUS); bus->func = (reg & E1000_STATUS_FUNC_MASK) >> E1000_STATUS_FUNC_SHIFT; return 0; } /** * igb_clear_vfta - Clear VLAN filter table * @hw: pointer to the HW structure * * Clears the register array which contains the VLAN filter table by * setting all the values to 0. **/ void igb_clear_vfta(struct e1000_hw *hw) { u32 offset; for (offset = E1000_VLAN_FILTER_TBL_SIZE; offset--;) hw->mac.ops.write_vfta(hw, offset, 0); } /** * igb_write_vfta - Write value to VLAN filter table * @hw: pointer to the HW structure * @offset: register offset in VLAN filter table * @value: register value written to VLAN filter table * * Writes value at the given offset in the register array which stores * the VLAN filter table. **/ void igb_write_vfta(struct e1000_hw *hw, u32 offset, u32 value) { struct igb_adapter *adapter = hw->back; array_wr32(E1000_VFTA, offset, value); wrfl(); adapter->shadow_vfta[offset] = value; } /** * igb_init_rx_addrs - Initialize receive address's * @hw: pointer to the HW structure * @rar_count: receive address registers * * Setups the receive address registers by setting the base receive address * register to the devices MAC address and clearing all the other receive * address registers to 0. **/ void igb_init_rx_addrs(struct e1000_hw *hw, u16 rar_count) { u32 i; u8 mac_addr[ETH_ALEN] = {0}; /* Setup the receive address */ hw_dbg("Programming MAC Address into RAR[0]\n"); hw->mac.ops.rar_set(hw, hw->mac.addr, 0); /* Zero out the other (rar_entry_count - 1) receive addresses */ hw_dbg("Clearing RAR[1-%u]\n", rar_count-1); for (i = 1; i < rar_count; i++) hw->mac.ops.rar_set(hw, mac_addr, i); } /** * igb_find_vlvf_slot - find the VLAN id or the first empty slot * @hw: pointer to hardware structure * @vlan: VLAN id to write to VLAN filter * @vlvf_bypass: skip VLVF if no match is found * * return the VLVF index where this VLAN id should be placed * **/ static s32 igb_find_vlvf_slot(struct e1000_hw *hw, u32 vlan, bool vlvf_bypass) { s32 regindex, first_empty_slot; u32 bits; /* short cut the special case */ if (vlan == 0) return 0; /* if vlvf_bypass is set we don't want to use an empty slot, we * will simply bypass the VLVF if there are no entries present in the * VLVF that contain our VLAN */ first_empty_slot = vlvf_bypass ? -E1000_ERR_NO_SPACE : 0; /* Search for the VLAN id in the VLVF entries. Save off the first empty * slot found along the way. * * pre-decrement loop covering (IXGBE_VLVF_ENTRIES - 1) .. 1 */ for (regindex = E1000_VLVF_ARRAY_SIZE; --regindex > 0;) { bits = rd32(E1000_VLVF(regindex)) & E1000_VLVF_VLANID_MASK; if (bits == vlan) return regindex; if (!first_empty_slot && !bits) first_empty_slot = regindex; } return first_empty_slot ? : -E1000_ERR_NO_SPACE; } /** * igb_vfta_set - enable or disable vlan in VLAN filter table * @hw: pointer to the HW structure * @vlan: VLAN id to add or remove * @vind: VMDq output index that maps queue to VLAN id * @vlan_on: if true add filter, if false remove * @vlvf_bypass: skip VLVF if no match is found * * Sets or clears a bit in the VLAN filter table array based on VLAN id * and if we are adding or removing the filter **/ s32 igb_vfta_set(struct e1000_hw *hw, u32 vlan, u32 vind, bool vlan_on, bool vlvf_bypass) { struct igb_adapter *adapter = hw->back; u32 regidx, vfta_delta, vfta, bits; s32 vlvf_index; if ((vlan > 4095) || (vind > 7)) return -E1000_ERR_PARAM; /* this is a 2 part operation - first the VFTA, then the * VLVF and VLVFB if VT Mode is set * We don't write the VFTA until we know the VLVF part succeeded. */ /* Part 1 * The VFTA is a bitstring made up of 128 32-bit registers * that enable the particular VLAN id, much like the MTA: * bits[11-5]: which register * bits[4-0]: which bit in the register */ regidx = vlan / 32; vfta_delta = BIT(vlan % 32); vfta = adapter->shadow_vfta[regidx]; /* vfta_delta represents the difference between the current value * of vfta and the value we want in the register. Since the diff * is an XOR mask we can just update vfta using an XOR. */ vfta_delta &= vlan_on ? ~vfta : vfta; vfta ^= vfta_delta; /* Part 2 * If VT Mode is set * Either vlan_on * make sure the VLAN is in VLVF * set the vind bit in the matching VLVFB * Or !vlan_on * clear the pool bit and possibly the vind */ if (!adapter->vfs_allocated_count) goto vfta_update; vlvf_index = igb_find_vlvf_slot(hw, vlan, vlvf_bypass); if (vlvf_index < 0) { if (vlvf_bypass) goto vfta_update; return vlvf_index; } bits = rd32(E1000_VLVF(vlvf_index)); /* set the pool bit */ bits |= BIT(E1000_VLVF_POOLSEL_SHIFT + vind); if (vlan_on) goto vlvf_update; /* clear the pool bit */ bits ^= BIT(E1000_VLVF_POOLSEL_SHIFT + vind); if (!(bits & E1000_VLVF_POOLSEL_MASK)) { /* Clear VFTA first, then disable VLVF. Otherwise * we run the risk of stray packets leaking into * the PF via the default pool */ if (vfta_delta) hw->mac.ops.write_vfta(hw, regidx, vfta); /* disable VLVF and clear remaining bit from pool */ wr32(E1000_VLVF(vlvf_index), 0); return 0; } /* If there are still bits set in the VLVFB registers * for the VLAN ID indicated we need to see if the * caller is requesting that we clear the VFTA entry bit. * If the caller has requested that we clear the VFTA * entry bit but there are still pools/VFs using this VLAN * ID entry then ignore the request. We're not worried * about the case where we're turning the VFTA VLAN ID * entry bit on, only when requested to turn it off as * there may be multiple pools and/or VFs using the * VLAN ID entry. In that case we cannot clear the * VFTA bit until all pools/VFs using that VLAN ID have also * been cleared. This will be indicated by "bits" being * zero. */ vfta_delta = 0; vlvf_update: /* record pool change and enable VLAN ID if not already enabled */ wr32(E1000_VLVF(vlvf_index), bits | vlan | E1000_VLVF_VLANID_ENABLE); vfta_update: /* bit was set/cleared before we started */ if (vfta_delta) hw->mac.ops.write_vfta(hw, regidx, vfta); return 0; } /** * igb_check_alt_mac_addr - Check for alternate MAC addr * @hw: pointer to the HW structure * * Checks the nvm for an alternate MAC address. An alternate MAC address * can be setup by pre-boot software and must be treated like a permanent * address and must override the actual permanent MAC address. If an * alternate MAC address is found it is saved in the hw struct and * programmed into RAR0 and the function returns success, otherwise the * function returns an error. **/ s32 igb_check_alt_mac_addr(struct e1000_hw *hw) { u32 i; s32 ret_val = 0; u16 offset, nvm_alt_mac_addr_offset, nvm_data; u8 alt_mac_addr[ETH_ALEN]; /* Alternate MAC address is handled by the option ROM for 82580 * and newer. SW support not required. */ if (hw->mac.type >= e1000_82580) goto out; ret_val = hw->nvm.ops.read(hw, NVM_ALT_MAC_ADDR_PTR, 1, &nvm_alt_mac_addr_offset); if (ret_val) { hw_dbg("NVM Read Error\n"); goto out; } if ((nvm_alt_mac_addr_offset == 0xFFFF) || (nvm_alt_mac_addr_offset == 0x0000)) /* There is no Alternate MAC Address */ goto out; if (hw->bus.func == E1000_FUNC_1) nvm_alt_mac_addr_offset += E1000_ALT_MAC_ADDRESS_OFFSET_LAN1; if (hw->bus.func == E1000_FUNC_2) nvm_alt_mac_addr_offset += E1000_ALT_MAC_ADDRESS_OFFSET_LAN2; if (hw->bus.func == E1000_FUNC_3) nvm_alt_mac_addr_offset += E1000_ALT_MAC_ADDRESS_OFFSET_LAN3; for (i = 0; i < ETH_ALEN; i += 2) { offset = nvm_alt_mac_addr_offset + (i >> 1); ret_val = hw->nvm.ops.read(hw, offset, 1, &nvm_data); if (ret_val) { hw_dbg("NVM Read Error\n"); goto out; } alt_mac_addr[i] = (u8)(nvm_data & 0xFF); alt_mac_addr[i + 1] = (u8)(nvm_data >> 8); } /* if multicast bit is set, the alternate address will not be used */ if (is_multicast_ether_addr(alt_mac_addr)) { hw_dbg("Ignoring Alternate Mac Address with MC bit set\n"); goto out; } /* We have a valid alternate MAC address, and we want to treat it the * same as the normal permanent MAC address stored by the HW into the * RAR. Do this by mapping this address into RAR0. */ hw->mac.ops.rar_set(hw, alt_mac_addr, 0); out: return ret_val; } /** * igb_rar_set - Set receive address register * @hw: pointer to the HW structure * @addr: pointer to the receive address * @index: receive address array register * * Sets the receive address array register at index to the address passed * in by addr. **/ void igb_rar_set(struct e1000_hw *hw, u8 *addr, u32 index) { u32 rar_low, rar_high; /* HW expects these in little endian so we reverse the byte order * from network order (big endian) to little endian */ rar_low = ((u32) addr[0] | ((u32) addr[1] << 8) | ((u32) addr[2] << 16) | ((u32) addr[3] << 24)); rar_high = ((u32) addr[4] | ((u32) addr[5] << 8)); /* If MAC address zero, no need to set the AV bit */ if (rar_low || rar_high) rar_high |= E1000_RAH_AV; /* Some bridges will combine consecutive 32-bit writes into * a single burst write, which will malfunction on some parts. * The flushes avoid this. */ wr32(E1000_RAL(index), rar_low); wrfl(); wr32(E1000_RAH(index), rar_high); wrfl(); } /** * igb_mta_set - Set multicast filter table address * @hw: pointer to the HW structure * @hash_value: determines the MTA register and bit to set * * The multicast table address is a register array of 32-bit registers. * The hash_value is used to determine what register the bit is in, the * current value is read, the new bit is OR'd in and the new value is * written back into the register. **/ void igb_mta_set(struct e1000_hw *hw, u32 hash_value) { u32 hash_bit, hash_reg, mta; /* The MTA is a register array of 32-bit registers. It is * treated like an array of (32*mta_reg_count) bits. We want to * set bit BitArray[hash_value]. So we figure out what register * the bit is in, read it, OR in the new bit, then write * back the new value. The (hw->mac.mta_reg_count - 1) serves as a * mask to bits 31:5 of the hash value which gives us the * register we're modifying. The hash bit within that register * is determined by the lower 5 bits of the hash value. */ hash_reg = (hash_value >> 5) & (hw->mac.mta_reg_count - 1); hash_bit = hash_value & 0x1F; mta = array_rd32(E1000_MTA, hash_reg); mta |= BIT(hash_bit); array_wr32(E1000_MTA, hash_reg, mta); wrfl(); } /** * igb_hash_mc_addr - Generate a multicast hash value * @hw: pointer to the HW structure * @mc_addr: pointer to a multicast address * * Generates a multicast address hash value which is used to determine * the multicast filter table array address and new table value. See * igb_mta_set() **/ static u32 igb_hash_mc_addr(struct e1000_hw *hw, u8 *mc_addr) { u32 hash_value, hash_mask; u8 bit_shift = 1; /* Register count multiplied by bits per register */ hash_mask = (hw->mac.mta_reg_count * 32) - 1; /* For a mc_filter_type of 0, bit_shift is the number of left-shifts * where 0xFF would still fall within the hash mask. */ while (hash_mask >> bit_shift != 0xFF && bit_shift < 4) bit_shift++; /* The portion of the address that is used for the hash table * is determined by the mc_filter_type setting. * The algorithm is such that there is a total of 8 bits of shifting. * The bit_shift for a mc_filter_type of 0 represents the number of * left-shifts where the MSB of mc_addr[5] would still fall within * the hash_mask. Case 0 does this exactly. Since there are a total * of 8 bits of shifting, then mc_addr[4] will shift right the * remaining number of bits. Thus 8 - bit_shift. The rest of the * cases are a variation of this algorithm...essentially raising the * number of bits to shift mc_addr[5] left, while still keeping the * 8-bit shifting total. * * For example, given the following Destination MAC Address and an * mta register count of 128 (thus a 4096-bit vector and 0xFFF mask), * we can see that the bit_shift for case 0 is 4. These are the hash * values resulting from each mc_filter_type... * [0] [1] [2] [3] [4] [5] * 01 AA 00 12 34 56 * LSB MSB * * case 0: hash_value = ((0x34 >> 4) | (0x56 << 4)) & 0xFFF = 0x563 * case 1: hash_value = ((0x34 >> 3) | (0x56 << 5)) & 0xFFF = 0xAC6 * case 2: hash_value = ((0x34 >> 2) | (0x56 << 6)) & 0xFFF = 0x163 * case 3: hash_value = ((0x34 >> 0) | (0x56 << 8)) & 0xFFF = 0x634 */ switch (hw->mac.mc_filter_type) { default: case 0: break; case 1: bit_shift += 1; break; case 2: bit_shift += 2; break; case 3: bit_shift += 4; break; } hash_value = hash_mask & (((mc_addr[4] >> (8 - bit_shift)) | (((u16) mc_addr[5]) << bit_shift))); return hash_value; } /** * igb_i21x_hw_doublecheck - double checks potential HW issue in i21X * @hw: pointer to the HW structure * * Checks if multicast array is wrote correctly * If not then rewrites again to register **/ static void igb_i21x_hw_doublecheck(struct e1000_hw *hw) { int failed_cnt = 3; bool is_failed; int i; do { is_failed = false; for (i = hw->mac.mta_reg_count - 1; i >= 0; i--) { if (array_rd32(E1000_MTA, i) != hw->mac.mta_shadow[i]) { is_failed = true; array_wr32(E1000_MTA, i, hw->mac.mta_shadow[i]); wrfl(); } } if (is_failed && --failed_cnt <= 0) { hw_dbg("Failed to update MTA_REGISTER, too many retries"); break; } } while (is_failed); } /** * igb_update_mc_addr_list - Update Multicast addresses * @hw: pointer to the HW structure * @mc_addr_list: array of multicast addresses to program * @mc_addr_count: number of multicast addresses to program * * Updates entire Multicast Table Array. * The caller must have a packed mc_addr_list of multicast addresses. **/ void igb_update_mc_addr_list(struct e1000_hw *hw, u8 *mc_addr_list, u32 mc_addr_count) { u32 hash_value, hash_bit, hash_reg; int i; /* clear mta_shadow */ memset(&hw->mac.mta_shadow, 0, sizeof(hw->mac.mta_shadow)); /* update mta_shadow from mc_addr_list */ for (i = 0; (u32) i < mc_addr_count; i++) { hash_value = igb_hash_mc_addr(hw, mc_addr_list); hash_reg = (hash_value >> 5) & (hw->mac.mta_reg_count - 1); hash_bit = hash_value & 0x1F; hw->mac.mta_shadow[hash_reg] |= BIT(hash_bit); mc_addr_list += (ETH_ALEN); } /* replace the entire MTA table */ for (i = hw->mac.mta_reg_count - 1; i >= 0; i--) array_wr32(E1000_MTA, i, hw->mac.mta_shadow[i]); wrfl(); if (hw->mac.type == e1000_i210 || hw->mac.type == e1000_i211) igb_i21x_hw_doublecheck(hw); } /** * igb_clear_hw_cntrs_base - Clear base hardware counters * @hw: pointer to the HW structure * * Clears the base hardware counters by reading the counter registers. **/ void igb_clear_hw_cntrs_base(struct e1000_hw *hw) { rd32(E1000_CRCERRS); rd32(E1000_SYMERRS); rd32(E1000_MPC); rd32(E1000_SCC); rd32(E1000_ECOL); rd32(E1000_MCC); rd32(E1000_LATECOL); rd32(E1000_COLC); rd32(E1000_DC); rd32(E1000_SEC); rd32(E1000_RLEC); rd32(E1000_XONRXC); rd32(E1000_XONTXC); rd32(E1000_XOFFRXC); rd32(E1000_XOFFTXC); rd32(E1000_FCRUC); rd32(E1000_GPRC); rd32(E1000_BPRC); rd32(E1000_MPRC); rd32(E1000_GPTC); rd32(E1000_GORCL); rd32(E1000_GORCH); rd32(E1000_GOTCL); rd32(E1000_GOTCH); rd32(E1000_RNBC); rd32(E1000_RUC); rd32(E1000_RFC); rd32(E1000_ROC); rd32(E1000_RJC); rd32(E1000_TORL); rd32(E1000_TORH); rd32(E1000_TOTL); rd32(E1000_TOTH); rd32(E1000_TPR); rd32(E1000_TPT); rd32(E1000_MPTC); rd32(E1000_BPTC); } /** * igb_check_for_copper_link - Check for link (Copper) * @hw: pointer to the HW structure * * Checks to see of the link status of the hardware has changed. If a * change in link status has been detected, then we read the PHY registers * to get the current speed/duplex if link exists. **/ s32 igb_check_for_copper_link(struct e1000_hw *hw) { struct e1000_mac_info *mac = &hw->mac; s32 ret_val; bool link; /* We only want to go out to the PHY registers to see if Auto-Neg * has completed and/or if our link status has changed. The * get_link_status flag is set upon receiving a Link Status * Change or Rx Sequence Error interrupt. */ if (!mac->get_link_status) { ret_val = 0; goto out; } /* First we want to see if the MII Status Register reports * link. If so, then we want to get the current speed/duplex * of the PHY. */ ret_val = igb_phy_has_link(hw, 1, 0, &link); if (ret_val) goto out; if (!link) goto out; /* No link detected */ mac->get_link_status = false; /* Check if there was DownShift, must be checked * immediately after link-up */ igb_check_downshift(hw); /* If we are forcing speed/duplex, then we simply return since * we have already determined whether we have link or not. */ if (!mac->autoneg) { ret_val = -E1000_ERR_CONFIG; goto out; } /* Auto-Neg is enabled. Auto Speed Detection takes care * of MAC speed/duplex configuration. So we only need to * configure Collision Distance in the MAC. */ igb_config_collision_dist(hw); /* Configure Flow Control now that Auto-Neg has completed. * First, we need to restore the desired flow control * settings because we may have had to re-autoneg with a * different link partner. */ ret_val = igb_config_fc_after_link_up(hw); if (ret_val) hw_dbg("Error configuring flow control\n"); out: return ret_val; } /** * igb_setup_link - Setup flow control and link settings * @hw: pointer to the HW structure * * Determines which flow control settings to use, then configures flow * control. Calls the appropriate media-specific link configuration * function. Assuming the adapter has a valid link partner, a valid link * should be established. Assumes the hardware has previously been reset * and the transmitter and receiver are not enabled. **/ s32 igb_setup_link(struct e1000_hw *hw) { s32 ret_val = 0; /* In the case of the phy reset being blocked, we already have a link. * We do not need to set it up again. */ if (igb_check_reset_block(hw)) goto out; /* If requested flow control is set to default, set flow control * based on the EEPROM flow control settings. */ if (hw->fc.requested_mode == e1000_fc_default) { ret_val = igb_set_default_fc(hw); if (ret_val) goto out; } /* We want to save off the original Flow Control configuration just * in case we get disconnected and then reconnected into a different * hub or switch with different Flow Control capabilities. */ hw->fc.current_mode = hw->fc.requested_mode; hw_dbg("After fix-ups FlowControl is now = %x\n", hw->fc.current_mode); /* Call the necessary media_type subroutine to configure the link. */ ret_val = hw->mac.ops.setup_physical_interface(hw); if (ret_val) goto out; /* Initialize the flow control address, type, and PAUSE timer * registers to their default values. This is done even if flow * control is disabled, because it does not hurt anything to * initialize these registers. */ hw_dbg("Initializing the Flow Control address, type and timer regs\n"); wr32(E1000_FCT, FLOW_CONTROL_TYPE); wr32(E1000_FCAH, FLOW_CONTROL_ADDRESS_HIGH); wr32(E1000_FCAL, FLOW_CONTROL_ADDRESS_LOW); wr32(E1000_FCTTV, hw->fc.pause_time); igb_set_fc_watermarks(hw); out: return ret_val; } /** * igb_config_collision_dist - Configure collision distance * @hw: pointer to the HW structure * * Configures the collision distance to the default value and is used * during link setup. Currently no func pointer exists and all * implementations are handled in the generic version of this function. **/ void igb_config_collision_dist(struct e1000_hw *hw) { u32 tctl; tctl = rd32(E1000_TCTL); tctl &= ~E1000_TCTL_COLD; tctl |= E1000_COLLISION_DISTANCE << E1000_COLD_SHIFT; wr32(E1000_TCTL, tctl); wrfl(); } /** * igb_set_fc_watermarks - Set flow control high/low watermarks * @hw: pointer to the HW structure * * Sets the flow control high/low threshold (watermark) registers. If * flow control XON frame transmission is enabled, then set XON frame * tansmission as well. **/ static void igb_set_fc_watermarks(struct e1000_hw *hw) { u32 fcrtl = 0, fcrth = 0; /* Set the flow control receive threshold registers. Normally, * these registers will be set to a default threshold that may be * adjusted later by the driver's runtime code. However, if the * ability to transmit pause frames is not enabled, then these * registers will be set to 0. */ if (hw->fc.current_mode & e1000_fc_tx_pause) { /* We need to set up the Receive Threshold high and low water * marks as well as (optionally) enabling the transmission of * XON frames. */ fcrtl = hw->fc.low_water; if (hw->fc.send_xon) fcrtl |= E1000_FCRTL_XONE; fcrth = hw->fc.high_water; } wr32(E1000_FCRTL, fcrtl); wr32(E1000_FCRTH, fcrth); } /** * igb_set_default_fc - Set flow control default values * @hw: pointer to the HW structure * * Read the EEPROM for the default values for flow control and store the * values. **/ static s32 igb_set_default_fc(struct e1000_hw *hw) { s32 ret_val = 0; u16 lan_offset; u16 nvm_data; /* Read and store word 0x0F of the EEPROM. This word contains bits * that determine the hardware's default PAUSE (flow control) mode, * a bit that determines whether the HW defaults to enabling or * disabling auto-negotiation, and the direction of the * SW defined pins. If there is no SW over-ride of the flow * control setting, then the variable hw->fc will * be initialized based on a value in the EEPROM. */ if (hw->mac.type == e1000_i350) lan_offset = NVM_82580_LAN_FUNC_OFFSET(hw->bus.func); else lan_offset = 0; ret_val = hw->nvm.ops.read(hw, NVM_INIT_CONTROL2_REG + lan_offset, 1, &nvm_data); if (ret_val) { hw_dbg("NVM Read Error\n"); goto out; } if ((nvm_data & NVM_WORD0F_PAUSE_MASK) == 0) hw->fc.requested_mode = e1000_fc_none; else if ((nvm_data & NVM_WORD0F_PAUSE_MASK) == NVM_WORD0F_ASM_DIR) hw->fc.requested_mode = e1000_fc_tx_pause; else hw->fc.requested_mode = e1000_fc_full; out: return ret_val; } /** * igb_force_mac_fc - Force the MAC's flow control settings * @hw: pointer to the HW structure * * Force the MAC's flow control settings. Sets the TFCE and RFCE bits in the * device control register to reflect the adapter settings. TFCE and RFCE * need to be explicitly set by software when a copper PHY is used because * autonegotiation is managed by the PHY rather than the MAC. Software must * also configure these bits when link is forced on a fiber connection. **/ s32 igb_force_mac_fc(struct e1000_hw *hw) { u32 ctrl; s32 ret_val = 0; ctrl = rd32(E1000_CTRL); /* Because we didn't get link via the internal auto-negotiation * mechanism (we either forced link or we got link via PHY * auto-neg), we have to manually enable/disable transmit an * receive flow control. * * The "Case" statement below enables/disable flow control * according to the "hw->fc.current_mode" parameter. * * The possible values of the "fc" parameter are: * 0: Flow control is completely disabled * 1: Rx flow control is enabled (we can receive pause * frames but not send pause frames). * 2: Tx flow control is enabled (we can send pause frames * but we do not receive pause frames). * 3: Both Rx and TX flow control (symmetric) is enabled. * other: No other values should be possible at this point. */ hw_dbg("hw->fc.current_mode = %u\n", hw->fc.current_mode); switch (hw->fc.current_mode) { case e1000_fc_none: ctrl &= (~(E1000_CTRL_TFCE | E1000_CTRL_RFCE)); break; case e1000_fc_rx_pause: ctrl &= (~E1000_CTRL_TFCE); ctrl |= E1000_CTRL_RFCE; break; case e1000_fc_tx_pause: ctrl &= (~E1000_CTRL_RFCE); ctrl |= E1000_CTRL_TFCE; break; case e1000_fc_full: ctrl |= (E1000_CTRL_TFCE | E1000_CTRL_RFCE); break; default: hw_dbg("Flow control param set incorrectly\n"); ret_val = -E1000_ERR_CONFIG; goto out; } wr32(E1000_CTRL, ctrl); out: return ret_val; } /** * igb_config_fc_after_link_up - Configures flow control after link * @hw: pointer to the HW structure * * Checks the status of auto-negotiation after link up to ensure that the * speed and duplex were not forced. If the link needed to be forced, then * flow control needs to be forced also. If auto-negotiation is enabled * and did not fail, then we configure flow control based on our link * partner. **/ s32 igb_config_fc_after_link_up(struct e1000_hw *hw) { struct e1000_mac_info *mac = &hw->mac; s32 ret_val = 0; u32 pcs_status_reg, pcs_adv_reg, pcs_lp_ability_reg, pcs_ctrl_reg; u16 mii_status_reg, mii_nway_adv_reg, mii_nway_lp_ability_reg; u16 speed, duplex; /* Check for the case where we have fiber media and auto-neg failed * so we had to force link. In this case, we need to force the * configuration of the MAC to match the "fc" parameter. */ if (mac->autoneg_failed) { if (hw->phy.media_type == e1000_media_type_internal_serdes) ret_val = igb_force_mac_fc(hw); } else { if (hw->phy.media_type == e1000_media_type_copper) ret_val = igb_force_mac_fc(hw); } if (ret_val) { hw_dbg("Error forcing flow control settings\n"); goto out; } /* Check for the case where we have copper media and auto-neg is * enabled. In this case, we need to check and see if Auto-Neg * has completed, and if so, how the PHY and link partner has * flow control configured. */ if ((hw->phy.media_type == e1000_media_type_copper) && mac->autoneg) { /* Read the MII Status Register and check to see if AutoNeg * has completed. We read this twice because this reg has * some "sticky" (latched) bits. */ ret_val = hw->phy.ops.read_reg(hw, PHY_STATUS, &mii_status_reg); if (ret_val) goto out; ret_val = hw->phy.ops.read_reg(hw, PHY_STATUS, &mii_status_reg); if (ret_val) goto out; if (!(mii_status_reg & MII_SR_AUTONEG_COMPLETE)) { hw_dbg("Copper PHY and Auto Neg has not completed.\n"); goto out; } /* The AutoNeg process has completed, so we now need to * read both the Auto Negotiation Advertisement * Register (Address 4) and the Auto_Negotiation Base * Page Ability Register (Address 5) to determine how * flow control was negotiated. */ ret_val = hw->phy.ops.read_reg(hw, PHY_AUTONEG_ADV, &mii_nway_adv_reg); if (ret_val) goto out; ret_val = hw->phy.ops.read_reg(hw, PHY_LP_ABILITY, &mii_nway_lp_ability_reg); if (ret_val) goto out; /* Two bits in the Auto Negotiation Advertisement Register * (Address 4) and two bits in the Auto Negotiation Base * Page Ability Register (Address 5) determine flow control * for both the PHY and the link partner. The following * table, taken out of the IEEE 802.3ab/D6.0 dated March 25, * 1999, describes these PAUSE resolution bits and how flow * control is determined based upon these settings. * NOTE: DC = Don't Care * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | NIC Resolution *-------|---------|-------|---------|-------------------- * 0 | 0 | DC | DC | e1000_fc_none * 0 | 1 | 0 | DC | e1000_fc_none * 0 | 1 | 1 | 0 | e1000_fc_none * 0 | 1 | 1 | 1 | e1000_fc_tx_pause * 1 | 0 | 0 | DC | e1000_fc_none * 1 | DC | 1 | DC | e1000_fc_full * 1 | 1 | 0 | 0 | e1000_fc_none * 1 | 1 | 0 | 1 | e1000_fc_rx_pause * * Are both PAUSE bits set to 1? If so, this implies * Symmetric Flow Control is enabled at both ends. The * ASM_DIR bits are irrelevant per the spec. * * For Symmetric Flow Control: * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result *-------|---------|-------|---------|-------------------- * 1 | DC | 1 | DC | E1000_fc_full * */ if ((mii_nway_adv_reg & NWAY_AR_PAUSE) && (mii_nway_lp_ability_reg & NWAY_LPAR_PAUSE)) { /* Now we need to check if the user selected RX ONLY * of pause frames. In this case, we had to advertise * FULL flow control because we could not advertise RX * ONLY. Hence, we must now check to see if we need to * turn OFF the TRANSMISSION of PAUSE frames. */ if (hw->fc.requested_mode == e1000_fc_full) { hw->fc.current_mode = e1000_fc_full; hw_dbg("Flow Control = FULL.\n"); } else { hw->fc.current_mode = e1000_fc_rx_pause; hw_dbg("Flow Control = RX PAUSE frames only.\n"); } } /* For receiving PAUSE frames ONLY. * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result *-------|---------|-------|---------|-------------------- * 0 | 1 | 1 | 1 | e1000_fc_tx_pause */ else if (!(mii_nway_adv_reg & NWAY_AR_PAUSE) && (mii_nway_adv_reg & NWAY_AR_ASM_DIR) && (mii_nway_lp_ability_reg & NWAY_LPAR_PAUSE) && (mii_nway_lp_ability_reg & NWAY_LPAR_ASM_DIR)) { hw->fc.current_mode = e1000_fc_tx_pause; hw_dbg("Flow Control = TX PAUSE frames only.\n"); } /* For transmitting PAUSE frames ONLY. * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result *-------|---------|-------|---------|-------------------- * 1 | 1 | 0 | 1 | e1000_fc_rx_pause */ else if ((mii_nway_adv_reg & NWAY_AR_PAUSE) && (mii_nway_adv_reg & NWAY_AR_ASM_DIR) && !(mii_nway_lp_ability_reg & NWAY_LPAR_PAUSE) && (mii_nway_lp_ability_reg & NWAY_LPAR_ASM_DIR)) { hw->fc.current_mode = e1000_fc_rx_pause; hw_dbg("Flow Control = RX PAUSE frames only.\n"); } /* Per the IEEE spec, at this point flow control should be * disabled. However, we want to consider that we could * be connected to a legacy switch that doesn't advertise * desired flow control, but can be forced on the link * partner. So if we advertised no flow control, that is * what we will resolve to. If we advertised some kind of * receive capability (Rx Pause Only or Full Flow Control) * and the link partner advertised none, we will configure * ourselves to enable Rx Flow Control only. We can do * this safely for two reasons: If the link partner really * didn't want flow control enabled, and we enable Rx, no * harm done since we won't be receiving any PAUSE frames * anyway. If the intent on the link partner was to have * flow control enabled, then by us enabling RX only, we * can at least receive pause frames and process them. * This is a good idea because in most cases, since we are * predominantly a server NIC, more times than not we will * be asked to delay transmission of packets than asking * our link partner to pause transmission of frames. */ else if ((hw->fc.requested_mode == e1000_fc_none) || (hw->fc.requested_mode == e1000_fc_tx_pause) || (hw->fc.strict_ieee)) { hw->fc.current_mode = e1000_fc_none; hw_dbg("Flow Control = NONE.\n"); } else { hw->fc.current_mode = e1000_fc_rx_pause; hw_dbg("Flow Control = RX PAUSE frames only.\n"); } /* Now we need to do one last check... If we auto- * negotiated to HALF DUPLEX, flow control should not be * enabled per IEEE 802.3 spec. */ ret_val = hw->mac.ops.get_speed_and_duplex(hw, &speed, &duplex); if (ret_val) { hw_dbg("Error getting link speed and duplex\n"); goto out; } if (duplex == HALF_DUPLEX) hw->fc.current_mode = e1000_fc_none; /* Now we call a subroutine to actually force the MAC * controller to use the correct flow control settings. */ ret_val = igb_force_mac_fc(hw); if (ret_val) { hw_dbg("Error forcing flow control settings\n"); goto out; } } /* Check for the case where we have SerDes media and auto-neg is * enabled. In this case, we need to check and see if Auto-Neg * has completed, and if so, how the PHY and link partner has * flow control configured. */ if ((hw->phy.media_type == e1000_media_type_internal_serdes) && mac->autoneg) { /* Read the PCS_LSTS and check to see if AutoNeg * has completed. */ pcs_status_reg = rd32(E1000_PCS_LSTAT); if (!(pcs_status_reg & E1000_PCS_LSTS_AN_COMPLETE)) { hw_dbg("PCS Auto Neg has not completed.\n"); return ret_val; } /* The AutoNeg process has completed, so we now need to * read both the Auto Negotiation Advertisement * Register (PCS_ANADV) and the Auto_Negotiation Base * Page Ability Register (PCS_LPAB) to determine how * flow control was negotiated. */ pcs_adv_reg = rd32(E1000_PCS_ANADV); pcs_lp_ability_reg = rd32(E1000_PCS_LPAB); /* Two bits in the Auto Negotiation Advertisement Register * (PCS_ANADV) and two bits in the Auto Negotiation Base * Page Ability Register (PCS_LPAB) determine flow control * for both the PHY and the link partner. The following * table, taken out of the IEEE 802.3ab/D6.0 dated March 25, * 1999, describes these PAUSE resolution bits and how flow * control is determined based upon these settings. * NOTE: DC = Don't Care * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | NIC Resolution *-------|---------|-------|---------|-------------------- * 0 | 0 | DC | DC | e1000_fc_none * 0 | 1 | 0 | DC | e1000_fc_none * 0 | 1 | 1 | 0 | e1000_fc_none * 0 | 1 | 1 | 1 | e1000_fc_tx_pause * 1 | 0 | 0 | DC | e1000_fc_none * 1 | DC | 1 | DC | e1000_fc_full * 1 | 1 | 0 | 0 | e1000_fc_none * 1 | 1 | 0 | 1 | e1000_fc_rx_pause * * Are both PAUSE bits set to 1? If so, this implies * Symmetric Flow Control is enabled at both ends. The * ASM_DIR bits are irrelevant per the spec. * * For Symmetric Flow Control: * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result *-------|---------|-------|---------|-------------------- * 1 | DC | 1 | DC | e1000_fc_full * */ if ((pcs_adv_reg & E1000_TXCW_PAUSE) && (pcs_lp_ability_reg & E1000_TXCW_PAUSE)) { /* Now we need to check if the user selected Rx ONLY * of pause frames. In this case, we had to advertise * FULL flow control because we could not advertise Rx * ONLY. Hence, we must now check to see if we need to * turn OFF the TRANSMISSION of PAUSE frames. */ if (hw->fc.requested_mode == e1000_fc_full) { hw->fc.current_mode = e1000_fc_full; hw_dbg("Flow Control = FULL.\n"); } else { hw->fc.current_mode = e1000_fc_rx_pause; hw_dbg("Flow Control = Rx PAUSE frames only.\n"); } } /* For receiving PAUSE frames ONLY. * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result *-------|---------|-------|---------|-------------------- * 0 | 1 | 1 | 1 | e1000_fc_tx_pause */ else if (!(pcs_adv_reg & E1000_TXCW_PAUSE) && (pcs_adv_reg & E1000_TXCW_ASM_DIR) && (pcs_lp_ability_reg & E1000_TXCW_PAUSE) && (pcs_lp_ability_reg & E1000_TXCW_ASM_DIR)) { hw->fc.current_mode = e1000_fc_tx_pause; hw_dbg("Flow Control = Tx PAUSE frames only.\n"); } /* For transmitting PAUSE frames ONLY. * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result *-------|---------|-------|---------|-------------------- * 1 | 1 | 0 | 1 | e1000_fc_rx_pause */ else if ((pcs_adv_reg & E1000_TXCW_PAUSE) && (pcs_adv_reg & E1000_TXCW_ASM_DIR) && !(pcs_lp_ability_reg & E1000_TXCW_PAUSE) && (pcs_lp_ability_reg & E1000_TXCW_ASM_DIR)) { hw->fc.current_mode = e1000_fc_rx_pause; hw_dbg("Flow Control = Rx PAUSE frames only.\n"); } else { /* Per the IEEE spec, at this point flow control * should be disabled. */ hw->fc.current_mode = e1000_fc_none; hw_dbg("Flow Control = NONE.\n"); } /* Now we call a subroutine to actually force the MAC * controller to use the correct flow control settings. */ pcs_ctrl_reg = rd32(E1000_PCS_LCTL); pcs_ctrl_reg |= E1000_PCS_LCTL_FORCE_FCTRL; wr32(E1000_PCS_LCTL, pcs_ctrl_reg); ret_val = igb_force_mac_fc(hw); if (ret_val) { hw_dbg("Error forcing flow control settings\n"); return ret_val; } } out: return ret_val; } /** * igb_get_speed_and_duplex_copper - Retrieve current speed/duplex * @hw: pointer to the HW structure * @speed: stores the current speed * @duplex: stores the current duplex * * Read the status register for the current speed/duplex and store the current * speed and duplex for copper connections. **/ s32 igb_get_speed_and_duplex_copper(struct e1000_hw *hw, u16 *speed, u16 *duplex) { u32 status; status = rd32(E1000_STATUS); if (status & E1000_STATUS_SPEED_1000) { *speed = SPEED_1000; hw_dbg("1000 Mbs, "); } else if (status & E1000_STATUS_SPEED_100) { *speed = SPEED_100; hw_dbg("100 Mbs, "); } else { *speed = SPEED_10; hw_dbg("10 Mbs, "); } if (status & E1000_STATUS_FD) { *duplex = FULL_DUPLEX; hw_dbg("Full Duplex\n"); } else { *duplex = HALF_DUPLEX; hw_dbg("Half Duplex\n"); } return 0; } /** * igb_get_hw_semaphore - Acquire hardware semaphore * @hw: pointer to the HW structure * * Acquire the HW semaphore to access the PHY or NVM **/ s32 igb_get_hw_semaphore(struct e1000_hw *hw) { u32 swsm; s32 ret_val = 0; s32 timeout = hw->nvm.word_size + 1; s32 i = 0; /* Get the SW semaphore */ while (i < timeout) { swsm = rd32(E1000_SWSM); if (!(swsm & E1000_SWSM_SMBI)) break; udelay(50); i++; } if (i == timeout) { hw_dbg("Driver can't access device - SMBI bit is set.\n"); ret_val = -E1000_ERR_NVM; goto out; } /* Get the FW semaphore. */ for (i = 0; i < timeout; i++) { swsm = rd32(E1000_SWSM); wr32(E1000_SWSM, swsm | E1000_SWSM_SWESMBI); /* Semaphore acquired if bit latched */ if (rd32(E1000_SWSM) & E1000_SWSM_SWESMBI) break; udelay(50); } if (i == timeout) { /* Release semaphores */ igb_put_hw_semaphore(hw); hw_dbg("Driver can't access the NVM\n"); ret_val = -E1000_ERR_NVM; goto out; } out: return ret_val; } /** * igb_put_hw_semaphore - Release hardware semaphore * @hw: pointer to the HW structure * * Release hardware semaphore used to access the PHY or NVM **/ void igb_put_hw_semaphore(struct e1000_hw *hw) { u32 swsm; swsm = rd32(E1000_SWSM); swsm &= ~(E1000_SWSM_SMBI | E1000_SWSM_SWESMBI); wr32(E1000_SWSM, swsm); } /** * igb_get_auto_rd_done - Check for auto read completion * @hw: pointer to the HW structure * * Check EEPROM for Auto Read done bit. **/ s32 igb_get_auto_rd_done(struct e1000_hw *hw) { s32 i = 0; s32 ret_val = 0; while (i < AUTO_READ_DONE_TIMEOUT) { if (rd32(E1000_EECD) & E1000_EECD_AUTO_RD) break; usleep_range(1000, 2000); i++; } if (i == AUTO_READ_DONE_TIMEOUT) { hw_dbg("Auto read by HW from NVM has not completed.\n"); ret_val = -E1000_ERR_RESET; goto out; } out: return ret_val; } /** * igb_valid_led_default - Verify a valid default LED config * @hw: pointer to the HW structure * @data: pointer to the NVM (EEPROM) * * Read the EEPROM for the current default LED configuration. If the * LED configuration is not valid, set to a valid LED configuration. **/ static s32 igb_valid_led_default(struct e1000_hw *hw, u16 *data) { s32 ret_val; ret_val = hw->nvm.ops.read(hw, NVM_ID_LED_SETTINGS, 1, data); if (ret_val) { hw_dbg("NVM Read Error\n"); goto out; } if (*data == ID_LED_RESERVED_0000 || *data == ID_LED_RESERVED_FFFF) { switch (hw->phy.media_type) { case e1000_media_type_internal_serdes: *data = ID_LED_DEFAULT_82575_SERDES; break; case e1000_media_type_copper: default: *data = ID_LED_DEFAULT; break; } } out: return ret_val; } /** * igb_id_led_init - * @hw: pointer to the HW structure * **/ s32 igb_id_led_init(struct e1000_hw *hw) { struct e1000_mac_info *mac = &hw->mac; s32 ret_val; const u32 ledctl_mask = 0x000000FF; const u32 ledctl_on = E1000_LEDCTL_MODE_LED_ON; const u32 ledctl_off = E1000_LEDCTL_MODE_LED_OFF; u16 data, i, temp; const u16 led_mask = 0x0F; /* i210 and i211 devices have different LED mechanism */ if ((hw->mac.type == e1000_i210) || (hw->mac.type == e1000_i211)) ret_val = igb_valid_led_default_i210(hw, &data); else ret_val = igb_valid_led_default(hw, &data); if (ret_val) goto out; mac->ledctl_default = rd32(E1000_LEDCTL); mac->ledctl_mode1 = mac->ledctl_default; mac->ledctl_mode2 = mac->ledctl_default; for (i = 0; i < 4; i++) { temp = (data >> (i << 2)) & led_mask; switch (temp) { case ID_LED_ON1_DEF2: case ID_LED_ON1_ON2: case ID_LED_ON1_OFF2: mac->ledctl_mode1 &= ~(ledctl_mask << (i << 3)); mac->ledctl_mode1 |= ledctl_on << (i << 3); break; case ID_LED_OFF1_DEF2: case ID_LED_OFF1_ON2: case ID_LED_OFF1_OFF2: mac->ledctl_mode1 &= ~(ledctl_mask << (i << 3)); mac->ledctl_mode1 |= ledctl_off << (i << 3); break; default: /* Do nothing */ break; } switch (temp) { case ID_LED_DEF1_ON2: case ID_LED_ON1_ON2: case ID_LED_OFF1_ON2: mac->ledctl_mode2 &= ~(ledctl_mask << (i << 3)); mac->ledctl_mode2 |= ledctl_on << (i << 3); break; case ID_LED_DEF1_OFF2: case ID_LED_ON1_OFF2: case ID_LED_OFF1_OFF2: mac->ledctl_mode2 &= ~(ledctl_mask << (i << 3)); mac->ledctl_mode2 |= ledctl_off << (i << 3); break; default: /* Do nothing */ break; } } out: return ret_val; } /** * igb_cleanup_led - Set LED config to default operation * @hw: pointer to the HW structure * * Remove the current LED configuration and set the LED configuration * to the default value, saved from the EEPROM. **/ s32 igb_cleanup_led(struct e1000_hw *hw) { wr32(E1000_LEDCTL, hw->mac.ledctl_default); return 0; } /** * igb_blink_led - Blink LED * @hw: pointer to the HW structure * * Blink the led's which are set to be on. **/ s32 igb_blink_led(struct e1000_hw *hw) { u32 ledctl_blink = 0; u32 i; if (hw->phy.media_type == e1000_media_type_fiber) { /* always blink LED0 for PCI-E fiber */ ledctl_blink = E1000_LEDCTL_LED0_BLINK | (E1000_LEDCTL_MODE_LED_ON << E1000_LEDCTL_LED0_MODE_SHIFT); } else { /* Set the blink bit for each LED that's "on" (0x0E) * (or "off" if inverted) in ledctl_mode2. The blink * logic in hardware only works when mode is set to "on" * so it must be changed accordingly when the mode is * "off" and inverted. */ ledctl_blink = hw->mac.ledctl_mode2; for (i = 0; i < 32; i += 8) { u32 mode = (hw->mac.ledctl_mode2 >> i) & E1000_LEDCTL_LED0_MODE_MASK; u32 led_default = hw->mac.ledctl_default >> i; if ((!(led_default & E1000_LEDCTL_LED0_IVRT) && (mode == E1000_LEDCTL_MODE_LED_ON)) || ((led_default & E1000_LEDCTL_LED0_IVRT) && (mode == E1000_LEDCTL_MODE_LED_OFF))) { ledctl_blink &= ~(E1000_LEDCTL_LED0_MODE_MASK << i); ledctl_blink |= (E1000_LEDCTL_LED0_BLINK | E1000_LEDCTL_MODE_LED_ON) << i; } } } wr32(E1000_LEDCTL, ledctl_blink); return 0; } /** * igb_led_off - Turn LED off * @hw: pointer to the HW structure * * Turn LED off. **/ s32 igb_led_off(struct e1000_hw *hw) { switch (hw->phy.media_type) { case e1000_media_type_copper: wr32(E1000_LEDCTL, hw->mac.ledctl_mode1); break; default: break; } return 0; } /** * igb_disable_pcie_master - Disables PCI-express master access * @hw: pointer to the HW structure * * Returns 0 (0) if successful, else returns -10 * (-E1000_ERR_MASTER_REQUESTS_PENDING) if master disable bit has not caused * the master requests to be disabled. * * Disables PCI-Express master access and verifies there are no pending * requests. **/ s32 igb_disable_pcie_master(struct e1000_hw *hw) { u32 ctrl; s32 timeout = MASTER_DISABLE_TIMEOUT; s32 ret_val = 0; if (hw->bus.type != e1000_bus_type_pci_express) goto out; ctrl = rd32(E1000_CTRL); ctrl |= E1000_CTRL_GIO_MASTER_DISABLE; wr32(E1000_CTRL, ctrl); while (timeout) { if (!(rd32(E1000_STATUS) & E1000_STATUS_GIO_MASTER_ENABLE)) break; udelay(100); timeout--; } if (!timeout) { hw_dbg("Master requests are pending.\n"); ret_val = -E1000_ERR_MASTER_REQUESTS_PENDING; goto out; } out: return ret_val; } /** * igb_validate_mdi_setting - Verify MDI/MDIx settings * @hw: pointer to the HW structure * * Verify that when not using auto-negotitation that MDI/MDIx is correctly * set, which is forced to MDI mode only. **/ s32 igb_validate_mdi_setting(struct e1000_hw *hw) { s32 ret_val = 0; /* All MDI settings are supported on 82580 and newer. */ if (hw->mac.type >= e1000_82580) goto out; if (!hw->mac.autoneg && (hw->phy.mdix == 0 || hw->phy.mdix == 3)) { hw_dbg("Invalid MDI setting detected\n"); hw->phy.mdix = 1; ret_val = -E1000_ERR_CONFIG; goto out; } out: return ret_val; } /** * igb_write_8bit_ctrl_reg - Write a 8bit CTRL register * @hw: pointer to the HW structure * @reg: 32bit register offset such as E1000_SCTL * @offset: register offset to write to * @data: data to write at register offset * * Writes an address/data control type register. There are several of these * and they all have the format address << 8 | data and bit 31 is polled for * completion. **/ s32 igb_write_8bit_ctrl_reg(struct e1000_hw *hw, u32 reg, u32 offset, u8 data) { u32 i, regvalue = 0; s32 ret_val = 0; /* Set up the address and data */ regvalue = ((u32)data) | (offset << E1000_GEN_CTL_ADDRESS_SHIFT); wr32(reg, regvalue); /* Poll the ready bit to see if the MDI read completed */ for (i = 0; i < E1000_GEN_POLL_TIMEOUT; i++) { udelay(5); regvalue = rd32(reg); if (regvalue & E1000_GEN_CTL_READY) break; } if (!(regvalue & E1000_GEN_CTL_READY)) { hw_dbg("Reg %08x did not indicate ready\n", reg); ret_val = -E1000_ERR_PHY; goto out; } out: return ret_val; } /** * igb_enable_mng_pass_thru - Enable processing of ARP's * @hw: pointer to the HW structure * * Verifies the hardware needs to leave interface enabled so that frames can * be directed to and from the management interface. **/ bool igb_enable_mng_pass_thru(struct e1000_hw *hw) { u32 manc; u32 fwsm, factps; bool ret_val = false; if (!hw->mac.asf_firmware_present) goto out; manc = rd32(E1000_MANC); if (!(manc & E1000_MANC_RCV_TCO_EN)) goto out; if (hw->mac.arc_subsystem_valid) { fwsm = rd32(E1000_FWSM); factps = rd32(E1000_FACTPS); if (!(factps & E1000_FACTPS_MNGCG) && ((fwsm & E1000_FWSM_MODE_MASK) == (e1000_mng_mode_pt << E1000_FWSM_MODE_SHIFT))) { ret_val = true; goto out; } } else { if ((manc & E1000_MANC_SMBUS_EN) && !(manc & E1000_MANC_ASF_EN)) { ret_val = true; goto out; } } out: return ret_val; }
linux-master
drivers/net/ethernet/intel/igb/e1000_mac.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2007 - 2018 Intel Corporation. */ #include "igb.h" #include "e1000_82575.h" #include "e1000_hw.h" #include <linux/module.h> #include <linux/types.h> #include <linux/sysfs.h> #include <linux/kobject.h> #include <linux/device.h> #include <linux/netdevice.h> #include <linux/hwmon.h> #include <linux/pci.h> #ifdef CONFIG_IGB_HWMON static struct i2c_board_info i350_sensor_info = { I2C_BOARD_INFO("i350bb", (0Xf8 >> 1)), }; /* hwmon callback functions */ static ssize_t igb_hwmon_show_location(struct device *dev, struct device_attribute *attr, char *buf) { struct hwmon_attr *igb_attr = container_of(attr, struct hwmon_attr, dev_attr); return sprintf(buf, "loc%u\n", igb_attr->sensor->location); } static ssize_t igb_hwmon_show_temp(struct device *dev, struct device_attribute *attr, char *buf) { struct hwmon_attr *igb_attr = container_of(attr, struct hwmon_attr, dev_attr); unsigned int value; /* reset the temp field */ igb_attr->hw->mac.ops.get_thermal_sensor_data(igb_attr->hw); value = igb_attr->sensor->temp; /* display millidegree */ value *= 1000; return sprintf(buf, "%u\n", value); } static ssize_t igb_hwmon_show_cautionthresh(struct device *dev, struct device_attribute *attr, char *buf) { struct hwmon_attr *igb_attr = container_of(attr, struct hwmon_attr, dev_attr); unsigned int value = igb_attr->sensor->caution_thresh; /* display millidegree */ value *= 1000; return sprintf(buf, "%u\n", value); } static ssize_t igb_hwmon_show_maxopthresh(struct device *dev, struct device_attribute *attr, char *buf) { struct hwmon_attr *igb_attr = container_of(attr, struct hwmon_attr, dev_attr); unsigned int value = igb_attr->sensor->max_op_thresh; /* display millidegree */ value *= 1000; return sprintf(buf, "%u\n", value); } /* igb_add_hwmon_attr - Create hwmon attr table for a hwmon sysfs file. * @ adapter: pointer to the adapter structure * @ offset: offset in the eeprom sensor data table * @ type: type of sensor data to display * * For each file we want in hwmon's sysfs interface we need a device_attribute * This is included in our hwmon_attr struct that contains the references to * the data structures we need to get the data to display. */ static int igb_add_hwmon_attr(struct igb_adapter *adapter, unsigned int offset, int type) { int rc; unsigned int n_attr; struct hwmon_attr *igb_attr; n_attr = adapter->igb_hwmon_buff->n_hwmon; igb_attr = &adapter->igb_hwmon_buff->hwmon_list[n_attr]; switch (type) { case IGB_HWMON_TYPE_LOC: igb_attr->dev_attr.show = igb_hwmon_show_location; snprintf(igb_attr->name, sizeof(igb_attr->name), "temp%u_label", offset + 1); break; case IGB_HWMON_TYPE_TEMP: igb_attr->dev_attr.show = igb_hwmon_show_temp; snprintf(igb_attr->name, sizeof(igb_attr->name), "temp%u_input", offset + 1); break; case IGB_HWMON_TYPE_CAUTION: igb_attr->dev_attr.show = igb_hwmon_show_cautionthresh; snprintf(igb_attr->name, sizeof(igb_attr->name), "temp%u_max", offset + 1); break; case IGB_HWMON_TYPE_MAX: igb_attr->dev_attr.show = igb_hwmon_show_maxopthresh; snprintf(igb_attr->name, sizeof(igb_attr->name), "temp%u_crit", offset + 1); break; default: rc = -EPERM; return rc; } /* These always the same regardless of type */ igb_attr->sensor = &adapter->hw.mac.thermal_sensor_data.sensor[offset]; igb_attr->hw = &adapter->hw; igb_attr->dev_attr.store = NULL; igb_attr->dev_attr.attr.mode = 0444; igb_attr->dev_attr.attr.name = igb_attr->name; sysfs_attr_init(&igb_attr->dev_attr.attr); adapter->igb_hwmon_buff->attrs[n_attr] = &igb_attr->dev_attr.attr; ++adapter->igb_hwmon_buff->n_hwmon; return 0; } static void igb_sysfs_del_adapter(struct igb_adapter *adapter) { } /* called from igb_main.c */ void igb_sysfs_exit(struct igb_adapter *adapter) { igb_sysfs_del_adapter(adapter); } /* called from igb_main.c */ int igb_sysfs_init(struct igb_adapter *adapter) { struct hwmon_buff *igb_hwmon; struct i2c_client *client; struct device *hwmon_dev; unsigned int i; int rc = 0; /* If this method isn't defined we don't support thermals */ if (adapter->hw.mac.ops.init_thermal_sensor_thresh == NULL) goto exit; /* Don't create thermal hwmon interface if no sensors present */ rc = (adapter->hw.mac.ops.init_thermal_sensor_thresh(&adapter->hw)); if (rc) goto exit; igb_hwmon = devm_kzalloc(&adapter->pdev->dev, sizeof(*igb_hwmon), GFP_KERNEL); if (!igb_hwmon) { rc = -ENOMEM; goto exit; } adapter->igb_hwmon_buff = igb_hwmon; for (i = 0; i < E1000_MAX_SENSORS; i++) { /* Only create hwmon sysfs entries for sensors that have * meaningful data. */ if (adapter->hw.mac.thermal_sensor_data.sensor[i].location == 0) continue; /* Bail if any hwmon attr struct fails to initialize */ rc = igb_add_hwmon_attr(adapter, i, IGB_HWMON_TYPE_CAUTION); if (rc) goto exit; rc = igb_add_hwmon_attr(adapter, i, IGB_HWMON_TYPE_LOC); if (rc) goto exit; rc = igb_add_hwmon_attr(adapter, i, IGB_HWMON_TYPE_TEMP); if (rc) goto exit; rc = igb_add_hwmon_attr(adapter, i, IGB_HWMON_TYPE_MAX); if (rc) goto exit; } /* init i2c_client */ client = i2c_new_client_device(&adapter->i2c_adap, &i350_sensor_info); if (IS_ERR(client)) { dev_info(&adapter->pdev->dev, "Failed to create new i2c device.\n"); rc = PTR_ERR(client); goto exit; } adapter->i2c_client = client; igb_hwmon->groups[0] = &igb_hwmon->group; igb_hwmon->group.attrs = igb_hwmon->attrs; hwmon_dev = devm_hwmon_device_register_with_groups(&adapter->pdev->dev, client->name, igb_hwmon, igb_hwmon->groups); if (IS_ERR(hwmon_dev)) { rc = PTR_ERR(hwmon_dev); goto err; } goto exit; err: igb_sysfs_del_adapter(adapter); exit: return rc; } #endif
linux-master
drivers/net/ethernet/intel/igb/igb_hwmon.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2007 - 2018 Intel Corporation. */ /* ethtool support for igb */ #include <linux/vmalloc.h> #include <linux/netdevice.h> #include <linux/pci.h> #include <linux/delay.h> #include <linux/interrupt.h> #include <linux/if_ether.h> #include <linux/ethtool.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/pm_runtime.h> #include <linux/highmem.h> #include <linux/mdio.h> #include "igb.h" struct igb_stats { char stat_string[ETH_GSTRING_LEN]; int sizeof_stat; int stat_offset; }; #define IGB_STAT(_name, _stat) { \ .stat_string = _name, \ .sizeof_stat = sizeof_field(struct igb_adapter, _stat), \ .stat_offset = offsetof(struct igb_adapter, _stat) \ } static const struct igb_stats igb_gstrings_stats[] = { IGB_STAT("rx_packets", stats.gprc), IGB_STAT("tx_packets", stats.gptc), IGB_STAT("rx_bytes", stats.gorc), IGB_STAT("tx_bytes", stats.gotc), IGB_STAT("rx_broadcast", stats.bprc), IGB_STAT("tx_broadcast", stats.bptc), IGB_STAT("rx_multicast", stats.mprc), IGB_STAT("tx_multicast", stats.mptc), IGB_STAT("multicast", stats.mprc), IGB_STAT("collisions", stats.colc), IGB_STAT("rx_crc_errors", stats.crcerrs), IGB_STAT("rx_no_buffer_count", stats.rnbc), IGB_STAT("rx_missed_errors", stats.mpc), IGB_STAT("tx_aborted_errors", stats.ecol), IGB_STAT("tx_carrier_errors", stats.tncrs), IGB_STAT("tx_window_errors", stats.latecol), IGB_STAT("tx_abort_late_coll", stats.latecol), IGB_STAT("tx_deferred_ok", stats.dc), IGB_STAT("tx_single_coll_ok", stats.scc), IGB_STAT("tx_multi_coll_ok", stats.mcc), IGB_STAT("tx_timeout_count", tx_timeout_count), IGB_STAT("rx_long_length_errors", stats.roc), IGB_STAT("rx_short_length_errors", stats.ruc), IGB_STAT("rx_align_errors", stats.algnerrc), IGB_STAT("tx_tcp_seg_good", stats.tsctc), IGB_STAT("tx_tcp_seg_failed", stats.tsctfc), IGB_STAT("rx_flow_control_xon", stats.xonrxc), IGB_STAT("rx_flow_control_xoff", stats.xoffrxc), IGB_STAT("tx_flow_control_xon", stats.xontxc), IGB_STAT("tx_flow_control_xoff", stats.xofftxc), IGB_STAT("rx_long_byte_count", stats.gorc), IGB_STAT("tx_dma_out_of_sync", stats.doosync), IGB_STAT("tx_smbus", stats.mgptc), IGB_STAT("rx_smbus", stats.mgprc), IGB_STAT("dropped_smbus", stats.mgpdc), IGB_STAT("os2bmc_rx_by_bmc", stats.o2bgptc), IGB_STAT("os2bmc_tx_by_bmc", stats.b2ospc), IGB_STAT("os2bmc_tx_by_host", stats.o2bspc), IGB_STAT("os2bmc_rx_by_host", stats.b2ogprc), IGB_STAT("tx_hwtstamp_timeouts", tx_hwtstamp_timeouts), IGB_STAT("tx_hwtstamp_skipped", tx_hwtstamp_skipped), IGB_STAT("rx_hwtstamp_cleared", rx_hwtstamp_cleared), }; #define IGB_NETDEV_STAT(_net_stat) { \ .stat_string = __stringify(_net_stat), \ .sizeof_stat = sizeof_field(struct rtnl_link_stats64, _net_stat), \ .stat_offset = offsetof(struct rtnl_link_stats64, _net_stat) \ } static const struct igb_stats igb_gstrings_net_stats[] = { IGB_NETDEV_STAT(rx_errors), IGB_NETDEV_STAT(tx_errors), IGB_NETDEV_STAT(tx_dropped), IGB_NETDEV_STAT(rx_length_errors), IGB_NETDEV_STAT(rx_over_errors), IGB_NETDEV_STAT(rx_frame_errors), IGB_NETDEV_STAT(rx_fifo_errors), IGB_NETDEV_STAT(tx_fifo_errors), IGB_NETDEV_STAT(tx_heartbeat_errors) }; #define IGB_GLOBAL_STATS_LEN \ (sizeof(igb_gstrings_stats) / sizeof(struct igb_stats)) #define IGB_NETDEV_STATS_LEN \ (sizeof(igb_gstrings_net_stats) / sizeof(struct igb_stats)) #define IGB_RX_QUEUE_STATS_LEN \ (sizeof(struct igb_rx_queue_stats) / sizeof(u64)) #define IGB_TX_QUEUE_STATS_LEN 3 /* packets, bytes, restart_queue */ #define IGB_QUEUE_STATS_LEN \ ((((struct igb_adapter *)netdev_priv(netdev))->num_rx_queues * \ IGB_RX_QUEUE_STATS_LEN) + \ (((struct igb_adapter *)netdev_priv(netdev))->num_tx_queues * \ IGB_TX_QUEUE_STATS_LEN)) #define IGB_STATS_LEN \ (IGB_GLOBAL_STATS_LEN + IGB_NETDEV_STATS_LEN + IGB_QUEUE_STATS_LEN) enum igb_diagnostics_results { TEST_REG = 0, TEST_EEP, TEST_IRQ, TEST_LOOP, TEST_LINK }; static const char igb_gstrings_test[][ETH_GSTRING_LEN] = { [TEST_REG] = "Register test (offline)", [TEST_EEP] = "Eeprom test (offline)", [TEST_IRQ] = "Interrupt test (offline)", [TEST_LOOP] = "Loopback test (offline)", [TEST_LINK] = "Link test (on/offline)" }; #define IGB_TEST_LEN (sizeof(igb_gstrings_test) / ETH_GSTRING_LEN) static const char igb_priv_flags_strings[][ETH_GSTRING_LEN] = { #define IGB_PRIV_FLAGS_LEGACY_RX BIT(0) "legacy-rx", }; #define IGB_PRIV_FLAGS_STR_LEN ARRAY_SIZE(igb_priv_flags_strings) static int igb_get_link_ksettings(struct net_device *netdev, struct ethtool_link_ksettings *cmd) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; struct e1000_dev_spec_82575 *dev_spec = &hw->dev_spec._82575; struct e1000_sfp_flags *eth_flags = &dev_spec->eth_flags; u32 status; u32 speed; u32 supported, advertising; status = pm_runtime_suspended(&adapter->pdev->dev) ? 0 : rd32(E1000_STATUS); if (hw->phy.media_type == e1000_media_type_copper) { supported = (SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full | SUPPORTED_100baseT_Half | SUPPORTED_100baseT_Full | SUPPORTED_1000baseT_Full| SUPPORTED_Autoneg | SUPPORTED_TP | SUPPORTED_Pause); advertising = ADVERTISED_TP; if (hw->mac.autoneg == 1) { advertising |= ADVERTISED_Autoneg; /* the e1000 autoneg seems to match ethtool nicely */ advertising |= hw->phy.autoneg_advertised; } cmd->base.port = PORT_TP; cmd->base.phy_address = hw->phy.addr; } else { supported = (SUPPORTED_FIBRE | SUPPORTED_1000baseKX_Full | SUPPORTED_Autoneg | SUPPORTED_Pause); advertising = (ADVERTISED_FIBRE | ADVERTISED_1000baseKX_Full); if (hw->mac.type == e1000_i354) { if ((hw->device_id == E1000_DEV_ID_I354_BACKPLANE_2_5GBPS) && !(status & E1000_STATUS_2P5_SKU_OVER)) { supported |= SUPPORTED_2500baseX_Full; supported &= ~SUPPORTED_1000baseKX_Full; advertising |= ADVERTISED_2500baseX_Full; advertising &= ~ADVERTISED_1000baseKX_Full; } } if (eth_flags->e100_base_fx || eth_flags->e100_base_lx) { supported |= SUPPORTED_100baseT_Full; advertising |= ADVERTISED_100baseT_Full; } if (hw->mac.autoneg == 1) advertising |= ADVERTISED_Autoneg; cmd->base.port = PORT_FIBRE; } if (hw->mac.autoneg != 1) advertising &= ~(ADVERTISED_Pause | ADVERTISED_Asym_Pause); switch (hw->fc.requested_mode) { case e1000_fc_full: advertising |= ADVERTISED_Pause; break; case e1000_fc_rx_pause: advertising |= (ADVERTISED_Pause | ADVERTISED_Asym_Pause); break; case e1000_fc_tx_pause: advertising |= ADVERTISED_Asym_Pause; break; default: advertising &= ~(ADVERTISED_Pause | ADVERTISED_Asym_Pause); } if (status & E1000_STATUS_LU) { if ((status & E1000_STATUS_2P5_SKU) && !(status & E1000_STATUS_2P5_SKU_OVER)) { speed = SPEED_2500; } else if (status & E1000_STATUS_SPEED_1000) { speed = SPEED_1000; } else if (status & E1000_STATUS_SPEED_100) { speed = SPEED_100; } else { speed = SPEED_10; } if ((status & E1000_STATUS_FD) || hw->phy.media_type != e1000_media_type_copper) cmd->base.duplex = DUPLEX_FULL; else cmd->base.duplex = DUPLEX_HALF; } else { speed = SPEED_UNKNOWN; cmd->base.duplex = DUPLEX_UNKNOWN; } cmd->base.speed = speed; if ((hw->phy.media_type == e1000_media_type_fiber) || hw->mac.autoneg) cmd->base.autoneg = AUTONEG_ENABLE; else cmd->base.autoneg = AUTONEG_DISABLE; /* MDI-X => 2; MDI =>1; Invalid =>0 */ if (hw->phy.media_type == e1000_media_type_copper) cmd->base.eth_tp_mdix = hw->phy.is_mdix ? ETH_TP_MDI_X : ETH_TP_MDI; else cmd->base.eth_tp_mdix = ETH_TP_MDI_INVALID; if (hw->phy.mdix == AUTO_ALL_MODES) cmd->base.eth_tp_mdix_ctrl = ETH_TP_MDI_AUTO; else cmd->base.eth_tp_mdix_ctrl = hw->phy.mdix; ethtool_convert_legacy_u32_to_link_mode(cmd->link_modes.supported, supported); ethtool_convert_legacy_u32_to_link_mode(cmd->link_modes.advertising, advertising); return 0; } static int igb_set_link_ksettings(struct net_device *netdev, const struct ethtool_link_ksettings *cmd) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u32 advertising; /* When SoL/IDER sessions are active, autoneg/speed/duplex * cannot be changed */ if (igb_check_reset_block(hw)) { dev_err(&adapter->pdev->dev, "Cannot change link characteristics when SoL/IDER is active.\n"); return -EINVAL; } /* MDI setting is only allowed when autoneg enabled because * some hardware doesn't allow MDI setting when speed or * duplex is forced. */ if (cmd->base.eth_tp_mdix_ctrl) { if (hw->phy.media_type != e1000_media_type_copper) return -EOPNOTSUPP; if ((cmd->base.eth_tp_mdix_ctrl != ETH_TP_MDI_AUTO) && (cmd->base.autoneg != AUTONEG_ENABLE)) { dev_err(&adapter->pdev->dev, "forcing MDI/MDI-X state is not supported when link speed and/or duplex are forced\n"); return -EINVAL; } } while (test_and_set_bit(__IGB_RESETTING, &adapter->state)) usleep_range(1000, 2000); ethtool_convert_link_mode_to_legacy_u32(&advertising, cmd->link_modes.advertising); if (cmd->base.autoneg == AUTONEG_ENABLE) { hw->mac.autoneg = 1; if (hw->phy.media_type == e1000_media_type_fiber) { hw->phy.autoneg_advertised = advertising | ADVERTISED_FIBRE | ADVERTISED_Autoneg; switch (adapter->link_speed) { case SPEED_2500: hw->phy.autoneg_advertised = ADVERTISED_2500baseX_Full; break; case SPEED_1000: hw->phy.autoneg_advertised = ADVERTISED_1000baseT_Full; break; case SPEED_100: hw->phy.autoneg_advertised = ADVERTISED_100baseT_Full; break; default: break; } } else { hw->phy.autoneg_advertised = advertising | ADVERTISED_TP | ADVERTISED_Autoneg; } advertising = hw->phy.autoneg_advertised; if (adapter->fc_autoneg) hw->fc.requested_mode = e1000_fc_default; } else { u32 speed = cmd->base.speed; /* calling this overrides forced MDI setting */ if (igb_set_spd_dplx(adapter, speed, cmd->base.duplex)) { clear_bit(__IGB_RESETTING, &adapter->state); return -EINVAL; } } /* MDI-X => 2; MDI => 1; Auto => 3 */ if (cmd->base.eth_tp_mdix_ctrl) { /* fix up the value for auto (3 => 0) as zero is mapped * internally to auto */ if (cmd->base.eth_tp_mdix_ctrl == ETH_TP_MDI_AUTO) hw->phy.mdix = AUTO_ALL_MODES; else hw->phy.mdix = cmd->base.eth_tp_mdix_ctrl; } /* reset the link */ if (netif_running(adapter->netdev)) { igb_down(adapter); igb_up(adapter); } else igb_reset(adapter); clear_bit(__IGB_RESETTING, &adapter->state); return 0; } static u32 igb_get_link(struct net_device *netdev) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_mac_info *mac = &adapter->hw.mac; /* If the link is not reported up to netdev, interrupts are disabled, * and so the physical link state may have changed since we last * looked. Set get_link_status to make sure that the true link * state is interrogated, rather than pulling a cached and possibly * stale link state from the driver. */ if (!netif_carrier_ok(netdev)) mac->get_link_status = 1; return igb_has_link(adapter); } static void igb_get_pauseparam(struct net_device *netdev, struct ethtool_pauseparam *pause) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; pause->autoneg = (adapter->fc_autoneg ? AUTONEG_ENABLE : AUTONEG_DISABLE); if (hw->fc.current_mode == e1000_fc_rx_pause) pause->rx_pause = 1; else if (hw->fc.current_mode == e1000_fc_tx_pause) pause->tx_pause = 1; else if (hw->fc.current_mode == e1000_fc_full) { pause->rx_pause = 1; pause->tx_pause = 1; } } static int igb_set_pauseparam(struct net_device *netdev, struct ethtool_pauseparam *pause) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; int retval = 0; int i; /* 100basefx does not support setting link flow control */ if (hw->dev_spec._82575.eth_flags.e100_base_fx) return -EINVAL; adapter->fc_autoneg = pause->autoneg; while (test_and_set_bit(__IGB_RESETTING, &adapter->state)) usleep_range(1000, 2000); if (adapter->fc_autoneg == AUTONEG_ENABLE) { hw->fc.requested_mode = e1000_fc_default; if (netif_running(adapter->netdev)) { igb_down(adapter); igb_up(adapter); } else { igb_reset(adapter); } } else { if (pause->rx_pause && pause->tx_pause) hw->fc.requested_mode = e1000_fc_full; else if (pause->rx_pause && !pause->tx_pause) hw->fc.requested_mode = e1000_fc_rx_pause; else if (!pause->rx_pause && pause->tx_pause) hw->fc.requested_mode = e1000_fc_tx_pause; else if (!pause->rx_pause && !pause->tx_pause) hw->fc.requested_mode = e1000_fc_none; hw->fc.current_mode = hw->fc.requested_mode; retval = ((hw->phy.media_type == e1000_media_type_copper) ? igb_force_mac_fc(hw) : igb_setup_link(hw)); /* Make sure SRRCTL considers new fc settings for each ring */ for (i = 0; i < adapter->num_rx_queues; i++) { struct igb_ring *ring = adapter->rx_ring[i]; igb_setup_srrctl(adapter, ring); } } clear_bit(__IGB_RESETTING, &adapter->state); return retval; } static u32 igb_get_msglevel(struct net_device *netdev) { struct igb_adapter *adapter = netdev_priv(netdev); return adapter->msg_enable; } static void igb_set_msglevel(struct net_device *netdev, u32 data) { struct igb_adapter *adapter = netdev_priv(netdev); adapter->msg_enable = data; } static int igb_get_regs_len(struct net_device *netdev) { #define IGB_REGS_LEN 740 return IGB_REGS_LEN * sizeof(u32); } static void igb_get_regs(struct net_device *netdev, struct ethtool_regs *regs, void *p) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u32 *regs_buff = p; u8 i; memset(p, 0, IGB_REGS_LEN * sizeof(u32)); regs->version = (1u << 24) | (hw->revision_id << 16) | hw->device_id; /* General Registers */ regs_buff[0] = rd32(E1000_CTRL); regs_buff[1] = rd32(E1000_STATUS); regs_buff[2] = rd32(E1000_CTRL_EXT); regs_buff[3] = rd32(E1000_MDIC); regs_buff[4] = rd32(E1000_SCTL); regs_buff[5] = rd32(E1000_CONNSW); regs_buff[6] = rd32(E1000_VET); regs_buff[7] = rd32(E1000_LEDCTL); regs_buff[8] = rd32(E1000_PBA); regs_buff[9] = rd32(E1000_PBS); regs_buff[10] = rd32(E1000_FRTIMER); regs_buff[11] = rd32(E1000_TCPTIMER); /* NVM Register */ regs_buff[12] = rd32(E1000_EECD); /* Interrupt */ /* Reading EICS for EICR because they read the * same but EICS does not clear on read */ regs_buff[13] = rd32(E1000_EICS); regs_buff[14] = rd32(E1000_EICS); regs_buff[15] = rd32(E1000_EIMS); regs_buff[16] = rd32(E1000_EIMC); regs_buff[17] = rd32(E1000_EIAC); regs_buff[18] = rd32(E1000_EIAM); /* Reading ICS for ICR because they read the * same but ICS does not clear on read */ regs_buff[19] = rd32(E1000_ICS); regs_buff[20] = rd32(E1000_ICS); regs_buff[21] = rd32(E1000_IMS); regs_buff[22] = rd32(E1000_IMC); regs_buff[23] = rd32(E1000_IAC); regs_buff[24] = rd32(E1000_IAM); regs_buff[25] = rd32(E1000_IMIRVP); /* Flow Control */ regs_buff[26] = rd32(E1000_FCAL); regs_buff[27] = rd32(E1000_FCAH); regs_buff[28] = rd32(E1000_FCTTV); regs_buff[29] = rd32(E1000_FCRTL); regs_buff[30] = rd32(E1000_FCRTH); regs_buff[31] = rd32(E1000_FCRTV); /* Receive */ regs_buff[32] = rd32(E1000_RCTL); regs_buff[33] = rd32(E1000_RXCSUM); regs_buff[34] = rd32(E1000_RLPML); regs_buff[35] = rd32(E1000_RFCTL); regs_buff[36] = rd32(E1000_MRQC); regs_buff[37] = rd32(E1000_VT_CTL); /* Transmit */ regs_buff[38] = rd32(E1000_TCTL); regs_buff[39] = rd32(E1000_TCTL_EXT); regs_buff[40] = rd32(E1000_TIPG); regs_buff[41] = rd32(E1000_DTXCTL); /* Wake Up */ regs_buff[42] = rd32(E1000_WUC); regs_buff[43] = rd32(E1000_WUFC); regs_buff[44] = rd32(E1000_WUS); regs_buff[45] = rd32(E1000_IPAV); regs_buff[46] = rd32(E1000_WUPL); /* MAC */ regs_buff[47] = rd32(E1000_PCS_CFG0); regs_buff[48] = rd32(E1000_PCS_LCTL); regs_buff[49] = rd32(E1000_PCS_LSTAT); regs_buff[50] = rd32(E1000_PCS_ANADV); regs_buff[51] = rd32(E1000_PCS_LPAB); regs_buff[52] = rd32(E1000_PCS_NPTX); regs_buff[53] = rd32(E1000_PCS_LPABNP); /* Statistics */ regs_buff[54] = adapter->stats.crcerrs; regs_buff[55] = adapter->stats.algnerrc; regs_buff[56] = adapter->stats.symerrs; regs_buff[57] = adapter->stats.rxerrc; regs_buff[58] = adapter->stats.mpc; regs_buff[59] = adapter->stats.scc; regs_buff[60] = adapter->stats.ecol; regs_buff[61] = adapter->stats.mcc; regs_buff[62] = adapter->stats.latecol; regs_buff[63] = adapter->stats.colc; regs_buff[64] = adapter->stats.dc; regs_buff[65] = adapter->stats.tncrs; regs_buff[66] = adapter->stats.sec; regs_buff[67] = adapter->stats.htdpmc; regs_buff[68] = adapter->stats.rlec; regs_buff[69] = adapter->stats.xonrxc; regs_buff[70] = adapter->stats.xontxc; regs_buff[71] = adapter->stats.xoffrxc; regs_buff[72] = adapter->stats.xofftxc; regs_buff[73] = adapter->stats.fcruc; regs_buff[74] = adapter->stats.prc64; regs_buff[75] = adapter->stats.prc127; regs_buff[76] = adapter->stats.prc255; regs_buff[77] = adapter->stats.prc511; regs_buff[78] = adapter->stats.prc1023; regs_buff[79] = adapter->stats.prc1522; regs_buff[80] = adapter->stats.gprc; regs_buff[81] = adapter->stats.bprc; regs_buff[82] = adapter->stats.mprc; regs_buff[83] = adapter->stats.gptc; regs_buff[84] = adapter->stats.gorc; regs_buff[86] = adapter->stats.gotc; regs_buff[88] = adapter->stats.rnbc; regs_buff[89] = adapter->stats.ruc; regs_buff[90] = adapter->stats.rfc; regs_buff[91] = adapter->stats.roc; regs_buff[92] = adapter->stats.rjc; regs_buff[93] = adapter->stats.mgprc; regs_buff[94] = adapter->stats.mgpdc; regs_buff[95] = adapter->stats.mgptc; regs_buff[96] = adapter->stats.tor; regs_buff[98] = adapter->stats.tot; regs_buff[100] = adapter->stats.tpr; regs_buff[101] = adapter->stats.tpt; regs_buff[102] = adapter->stats.ptc64; regs_buff[103] = adapter->stats.ptc127; regs_buff[104] = adapter->stats.ptc255; regs_buff[105] = adapter->stats.ptc511; regs_buff[106] = adapter->stats.ptc1023; regs_buff[107] = adapter->stats.ptc1522; regs_buff[108] = adapter->stats.mptc; regs_buff[109] = adapter->stats.bptc; regs_buff[110] = adapter->stats.tsctc; regs_buff[111] = adapter->stats.iac; regs_buff[112] = adapter->stats.rpthc; regs_buff[113] = adapter->stats.hgptc; regs_buff[114] = adapter->stats.hgorc; regs_buff[116] = adapter->stats.hgotc; regs_buff[118] = adapter->stats.lenerrs; regs_buff[119] = adapter->stats.scvpc; regs_buff[120] = adapter->stats.hrmpc; for (i = 0; i < 4; i++) regs_buff[121 + i] = rd32(E1000_SRRCTL(i)); for (i = 0; i < 4; i++) regs_buff[125 + i] = rd32(E1000_PSRTYPE(i)); for (i = 0; i < 4; i++) regs_buff[129 + i] = rd32(E1000_RDBAL(i)); for (i = 0; i < 4; i++) regs_buff[133 + i] = rd32(E1000_RDBAH(i)); for (i = 0; i < 4; i++) regs_buff[137 + i] = rd32(E1000_RDLEN(i)); for (i = 0; i < 4; i++) regs_buff[141 + i] = rd32(E1000_RDH(i)); for (i = 0; i < 4; i++) regs_buff[145 + i] = rd32(E1000_RDT(i)); for (i = 0; i < 4; i++) regs_buff[149 + i] = rd32(E1000_RXDCTL(i)); for (i = 0; i < 10; i++) regs_buff[153 + i] = rd32(E1000_EITR(i)); for (i = 0; i < 8; i++) regs_buff[163 + i] = rd32(E1000_IMIR(i)); for (i = 0; i < 8; i++) regs_buff[171 + i] = rd32(E1000_IMIREXT(i)); for (i = 0; i < 16; i++) regs_buff[179 + i] = rd32(E1000_RAL(i)); for (i = 0; i < 16; i++) regs_buff[195 + i] = rd32(E1000_RAH(i)); for (i = 0; i < 4; i++) regs_buff[211 + i] = rd32(E1000_TDBAL(i)); for (i = 0; i < 4; i++) regs_buff[215 + i] = rd32(E1000_TDBAH(i)); for (i = 0; i < 4; i++) regs_buff[219 + i] = rd32(E1000_TDLEN(i)); for (i = 0; i < 4; i++) regs_buff[223 + i] = rd32(E1000_TDH(i)); for (i = 0; i < 4; i++) regs_buff[227 + i] = rd32(E1000_TDT(i)); for (i = 0; i < 4; i++) regs_buff[231 + i] = rd32(E1000_TXDCTL(i)); for (i = 0; i < 4; i++) regs_buff[235 + i] = rd32(E1000_TDWBAL(i)); for (i = 0; i < 4; i++) regs_buff[239 + i] = rd32(E1000_TDWBAH(i)); for (i = 0; i < 4; i++) regs_buff[243 + i] = rd32(E1000_DCA_TXCTRL(i)); for (i = 0; i < 4; i++) regs_buff[247 + i] = rd32(E1000_IP4AT_REG(i)); for (i = 0; i < 4; i++) regs_buff[251 + i] = rd32(E1000_IP6AT_REG(i)); for (i = 0; i < 32; i++) regs_buff[255 + i] = rd32(E1000_WUPM_REG(i)); for (i = 0; i < 128; i++) regs_buff[287 + i] = rd32(E1000_FFMT_REG(i)); for (i = 0; i < 128; i++) regs_buff[415 + i] = rd32(E1000_FFVT_REG(i)); for (i = 0; i < 4; i++) regs_buff[543 + i] = rd32(E1000_FFLT_REG(i)); regs_buff[547] = rd32(E1000_TDFH); regs_buff[548] = rd32(E1000_TDFT); regs_buff[549] = rd32(E1000_TDFHS); regs_buff[550] = rd32(E1000_TDFPC); if (hw->mac.type > e1000_82580) { regs_buff[551] = adapter->stats.o2bgptc; regs_buff[552] = adapter->stats.b2ospc; regs_buff[553] = adapter->stats.o2bspc; regs_buff[554] = adapter->stats.b2ogprc; } if (hw->mac.type == e1000_82576) { for (i = 0; i < 12; i++) regs_buff[555 + i] = rd32(E1000_SRRCTL(i + 4)); for (i = 0; i < 4; i++) regs_buff[567 + i] = rd32(E1000_PSRTYPE(i + 4)); for (i = 0; i < 12; i++) regs_buff[571 + i] = rd32(E1000_RDBAL(i + 4)); for (i = 0; i < 12; i++) regs_buff[583 + i] = rd32(E1000_RDBAH(i + 4)); for (i = 0; i < 12; i++) regs_buff[595 + i] = rd32(E1000_RDLEN(i + 4)); for (i = 0; i < 12; i++) regs_buff[607 + i] = rd32(E1000_RDH(i + 4)); for (i = 0; i < 12; i++) regs_buff[619 + i] = rd32(E1000_RDT(i + 4)); for (i = 0; i < 12; i++) regs_buff[631 + i] = rd32(E1000_RXDCTL(i + 4)); for (i = 0; i < 12; i++) regs_buff[643 + i] = rd32(E1000_TDBAL(i + 4)); for (i = 0; i < 12; i++) regs_buff[655 + i] = rd32(E1000_TDBAH(i + 4)); for (i = 0; i < 12; i++) regs_buff[667 + i] = rd32(E1000_TDLEN(i + 4)); for (i = 0; i < 12; i++) regs_buff[679 + i] = rd32(E1000_TDH(i + 4)); for (i = 0; i < 12; i++) regs_buff[691 + i] = rd32(E1000_TDT(i + 4)); for (i = 0; i < 12; i++) regs_buff[703 + i] = rd32(E1000_TXDCTL(i + 4)); for (i = 0; i < 12; i++) regs_buff[715 + i] = rd32(E1000_TDWBAL(i + 4)); for (i = 0; i < 12; i++) regs_buff[727 + i] = rd32(E1000_TDWBAH(i + 4)); } if (hw->mac.type == e1000_i210 || hw->mac.type == e1000_i211) regs_buff[739] = rd32(E1000_I210_RR2DCDELAY); } static int igb_get_eeprom_len(struct net_device *netdev) { struct igb_adapter *adapter = netdev_priv(netdev); return adapter->hw.nvm.word_size * 2; } static int igb_get_eeprom(struct net_device *netdev, struct ethtool_eeprom *eeprom, u8 *bytes) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u16 *eeprom_buff; int first_word, last_word; int ret_val = 0; u16 i; if (eeprom->len == 0) return -EINVAL; eeprom->magic = hw->vendor_id | (hw->device_id << 16); first_word = eeprom->offset >> 1; last_word = (eeprom->offset + eeprom->len - 1) >> 1; eeprom_buff = kmalloc_array(last_word - first_word + 1, sizeof(u16), GFP_KERNEL); if (!eeprom_buff) return -ENOMEM; if (hw->nvm.type == e1000_nvm_eeprom_spi) ret_val = hw->nvm.ops.read(hw, first_word, last_word - first_word + 1, eeprom_buff); else { for (i = 0; i < last_word - first_word + 1; i++) { ret_val = hw->nvm.ops.read(hw, first_word + i, 1, &eeprom_buff[i]); if (ret_val) break; } } /* Device's eeprom is always little-endian, word addressable */ for (i = 0; i < last_word - first_word + 1; i++) le16_to_cpus(&eeprom_buff[i]); memcpy(bytes, (u8 *)eeprom_buff + (eeprom->offset & 1), eeprom->len); kfree(eeprom_buff); return ret_val; } static int igb_set_eeprom(struct net_device *netdev, struct ethtool_eeprom *eeprom, u8 *bytes) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u16 *eeprom_buff; void *ptr; int max_len, first_word, last_word, ret_val = 0; u16 i; if (eeprom->len == 0) return -EOPNOTSUPP; if ((hw->mac.type >= e1000_i210) && !igb_get_flash_presence_i210(hw)) { return -EOPNOTSUPP; } if (eeprom->magic != (hw->vendor_id | (hw->device_id << 16))) return -EFAULT; max_len = hw->nvm.word_size * 2; first_word = eeprom->offset >> 1; last_word = (eeprom->offset + eeprom->len - 1) >> 1; eeprom_buff = kmalloc(max_len, GFP_KERNEL); if (!eeprom_buff) return -ENOMEM; ptr = (void *)eeprom_buff; if (eeprom->offset & 1) { /* need read/modify/write of first changed EEPROM word * only the second byte of the word is being modified */ ret_val = hw->nvm.ops.read(hw, first_word, 1, &eeprom_buff[0]); ptr++; } if (((eeprom->offset + eeprom->len) & 1) && (ret_val == 0)) { /* need read/modify/write of last changed EEPROM word * only the first byte of the word is being modified */ ret_val = hw->nvm.ops.read(hw, last_word, 1, &eeprom_buff[last_word - first_word]); if (ret_val) goto out; } /* Device's eeprom is always little-endian, word addressable */ for (i = 0; i < last_word - first_word + 1; i++) le16_to_cpus(&eeprom_buff[i]); memcpy(ptr, bytes, eeprom->len); for (i = 0; i < last_word - first_word + 1; i++) cpu_to_le16s(&eeprom_buff[i]); ret_val = hw->nvm.ops.write(hw, first_word, last_word - first_word + 1, eeprom_buff); /* Update the checksum if nvm write succeeded */ if (ret_val == 0) hw->nvm.ops.update(hw); igb_set_fw_version(adapter); out: kfree(eeprom_buff); return ret_val; } static void igb_get_drvinfo(struct net_device *netdev, struct ethtool_drvinfo *drvinfo) { struct igb_adapter *adapter = netdev_priv(netdev); strscpy(drvinfo->driver, igb_driver_name, sizeof(drvinfo->driver)); /* EEPROM image version # is reported as firmware version # for * 82575 controllers */ strscpy(drvinfo->fw_version, adapter->fw_version, sizeof(drvinfo->fw_version)); strscpy(drvinfo->bus_info, pci_name(adapter->pdev), sizeof(drvinfo->bus_info)); drvinfo->n_priv_flags = IGB_PRIV_FLAGS_STR_LEN; } static void igb_get_ringparam(struct net_device *netdev, struct ethtool_ringparam *ring, struct kernel_ethtool_ringparam *kernel_ring, struct netlink_ext_ack *extack) { struct igb_adapter *adapter = netdev_priv(netdev); ring->rx_max_pending = IGB_MAX_RXD; ring->tx_max_pending = IGB_MAX_TXD; ring->rx_pending = adapter->rx_ring_count; ring->tx_pending = adapter->tx_ring_count; } static int igb_set_ringparam(struct net_device *netdev, struct ethtool_ringparam *ring, struct kernel_ethtool_ringparam *kernel_ring, struct netlink_ext_ack *extack) { struct igb_adapter *adapter = netdev_priv(netdev); struct igb_ring *temp_ring; int i, err = 0; u16 new_rx_count, new_tx_count; if ((ring->rx_mini_pending) || (ring->rx_jumbo_pending)) return -EINVAL; new_rx_count = min_t(u32, ring->rx_pending, IGB_MAX_RXD); new_rx_count = max_t(u16, new_rx_count, IGB_MIN_RXD); new_rx_count = ALIGN(new_rx_count, REQ_RX_DESCRIPTOR_MULTIPLE); new_tx_count = min_t(u32, ring->tx_pending, IGB_MAX_TXD); new_tx_count = max_t(u16, new_tx_count, IGB_MIN_TXD); new_tx_count = ALIGN(new_tx_count, REQ_TX_DESCRIPTOR_MULTIPLE); if ((new_tx_count == adapter->tx_ring_count) && (new_rx_count == adapter->rx_ring_count)) { /* nothing to do */ return 0; } while (test_and_set_bit(__IGB_RESETTING, &adapter->state)) usleep_range(1000, 2000); if (!netif_running(adapter->netdev)) { for (i = 0; i < adapter->num_tx_queues; i++) adapter->tx_ring[i]->count = new_tx_count; for (i = 0; i < adapter->num_rx_queues; i++) adapter->rx_ring[i]->count = new_rx_count; adapter->tx_ring_count = new_tx_count; adapter->rx_ring_count = new_rx_count; goto clear_reset; } if (adapter->num_tx_queues > adapter->num_rx_queues) temp_ring = vmalloc(array_size(sizeof(struct igb_ring), adapter->num_tx_queues)); else temp_ring = vmalloc(array_size(sizeof(struct igb_ring), adapter->num_rx_queues)); if (!temp_ring) { err = -ENOMEM; goto clear_reset; } igb_down(adapter); /* We can't just free everything and then setup again, * because the ISRs in MSI-X mode get passed pointers * to the Tx and Rx ring structs. */ if (new_tx_count != adapter->tx_ring_count) { for (i = 0; i < adapter->num_tx_queues; i++) { memcpy(&temp_ring[i], adapter->tx_ring[i], sizeof(struct igb_ring)); temp_ring[i].count = new_tx_count; err = igb_setup_tx_resources(&temp_ring[i]); if (err) { while (i) { i--; igb_free_tx_resources(&temp_ring[i]); } goto err_setup; } } for (i = 0; i < adapter->num_tx_queues; i++) { igb_free_tx_resources(adapter->tx_ring[i]); memcpy(adapter->tx_ring[i], &temp_ring[i], sizeof(struct igb_ring)); } adapter->tx_ring_count = new_tx_count; } if (new_rx_count != adapter->rx_ring_count) { for (i = 0; i < adapter->num_rx_queues; i++) { memcpy(&temp_ring[i], adapter->rx_ring[i], sizeof(struct igb_ring)); temp_ring[i].count = new_rx_count; err = igb_setup_rx_resources(&temp_ring[i]); if (err) { while (i) { i--; igb_free_rx_resources(&temp_ring[i]); } goto err_setup; } } for (i = 0; i < adapter->num_rx_queues; i++) { igb_free_rx_resources(adapter->rx_ring[i]); memcpy(adapter->rx_ring[i], &temp_ring[i], sizeof(struct igb_ring)); } adapter->rx_ring_count = new_rx_count; } err_setup: igb_up(adapter); vfree(temp_ring); clear_reset: clear_bit(__IGB_RESETTING, &adapter->state); return err; } /* ethtool register test data */ struct igb_reg_test { u16 reg; u16 reg_offset; u16 array_len; u16 test_type; u32 mask; u32 write; }; /* In the hardware, registers are laid out either singly, in arrays * spaced 0x100 bytes apart, or in contiguous tables. We assume * most tests take place on arrays or single registers (handled * as a single-element array) and special-case the tables. * Table tests are always pattern tests. * * We also make provision for some required setup steps by specifying * registers to be written without any read-back testing. */ #define PATTERN_TEST 1 #define SET_READ_TEST 2 #define WRITE_NO_TEST 3 #define TABLE32_TEST 4 #define TABLE64_TEST_LO 5 #define TABLE64_TEST_HI 6 /* i210 reg test */ static struct igb_reg_test reg_test_i210[] = { { E1000_FCAL, 0x100, 1, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_FCAH, 0x100, 1, PATTERN_TEST, 0x0000FFFF, 0xFFFFFFFF }, { E1000_FCT, 0x100, 1, PATTERN_TEST, 0x0000FFFF, 0xFFFFFFFF }, { E1000_RDBAL(0), 0x100, 4, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF }, { E1000_RDBAH(0), 0x100, 4, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_RDLEN(0), 0x100, 4, PATTERN_TEST, 0x000FFF80, 0x000FFFFF }, /* RDH is read-only for i210, only test RDT. */ { E1000_RDT(0), 0x100, 4, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF }, { E1000_FCRTH, 0x100, 1, PATTERN_TEST, 0x0000FFF0, 0x0000FFF0 }, { E1000_FCTTV, 0x100, 1, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF }, { E1000_TIPG, 0x100, 1, PATTERN_TEST, 0x3FFFFFFF, 0x3FFFFFFF }, { E1000_TDBAL(0), 0x100, 4, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF }, { E1000_TDBAH(0), 0x100, 4, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_TDLEN(0), 0x100, 4, PATTERN_TEST, 0x000FFF80, 0x000FFFFF }, { E1000_TDT(0), 0x100, 4, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF }, { E1000_RCTL, 0x100, 1, SET_READ_TEST, 0xFFFFFFFF, 0x00000000 }, { E1000_RCTL, 0x100, 1, SET_READ_TEST, 0x04CFB0FE, 0x003FFFFB }, { E1000_RCTL, 0x100, 1, SET_READ_TEST, 0x04CFB0FE, 0xFFFFFFFF }, { E1000_TCTL, 0x100, 1, SET_READ_TEST, 0xFFFFFFFF, 0x00000000 }, { E1000_RA, 0, 16, TABLE64_TEST_LO, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_RA, 0, 16, TABLE64_TEST_HI, 0x900FFFFF, 0xFFFFFFFF }, { E1000_MTA, 0, 128, TABLE32_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { 0, 0, 0, 0, 0 } }; /* i350 reg test */ static struct igb_reg_test reg_test_i350[] = { { E1000_FCAL, 0x100, 1, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_FCAH, 0x100, 1, PATTERN_TEST, 0x0000FFFF, 0xFFFFFFFF }, { E1000_FCT, 0x100, 1, PATTERN_TEST, 0x0000FFFF, 0xFFFFFFFF }, { E1000_VET, 0x100, 1, PATTERN_TEST, 0xFFFF0000, 0xFFFF0000 }, { E1000_RDBAL(0), 0x100, 4, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF }, { E1000_RDBAH(0), 0x100, 4, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_RDLEN(0), 0x100, 4, PATTERN_TEST, 0x000FFF80, 0x000FFFFF }, { E1000_RDBAL(4), 0x40, 4, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF }, { E1000_RDBAH(4), 0x40, 4, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_RDLEN(4), 0x40, 4, PATTERN_TEST, 0x000FFF80, 0x000FFFFF }, /* RDH is read-only for i350, only test RDT. */ { E1000_RDT(0), 0x100, 4, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF }, { E1000_RDT(4), 0x40, 4, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF }, { E1000_FCRTH, 0x100, 1, PATTERN_TEST, 0x0000FFF0, 0x0000FFF0 }, { E1000_FCTTV, 0x100, 1, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF }, { E1000_TIPG, 0x100, 1, PATTERN_TEST, 0x3FFFFFFF, 0x3FFFFFFF }, { E1000_TDBAL(0), 0x100, 4, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF }, { E1000_TDBAH(0), 0x100, 4, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_TDLEN(0), 0x100, 4, PATTERN_TEST, 0x000FFF80, 0x000FFFFF }, { E1000_TDBAL(4), 0x40, 4, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF }, { E1000_TDBAH(4), 0x40, 4, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_TDLEN(4), 0x40, 4, PATTERN_TEST, 0x000FFF80, 0x000FFFFF }, { E1000_TDT(0), 0x100, 4, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF }, { E1000_TDT(4), 0x40, 4, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF }, { E1000_RCTL, 0x100, 1, SET_READ_TEST, 0xFFFFFFFF, 0x00000000 }, { E1000_RCTL, 0x100, 1, SET_READ_TEST, 0x04CFB0FE, 0x003FFFFB }, { E1000_RCTL, 0x100, 1, SET_READ_TEST, 0x04CFB0FE, 0xFFFFFFFF }, { E1000_TCTL, 0x100, 1, SET_READ_TEST, 0xFFFFFFFF, 0x00000000 }, { E1000_RA, 0, 16, TABLE64_TEST_LO, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_RA, 0, 16, TABLE64_TEST_HI, 0xC3FFFFFF, 0xFFFFFFFF }, { E1000_RA2, 0, 16, TABLE64_TEST_LO, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_RA2, 0, 16, TABLE64_TEST_HI, 0xC3FFFFFF, 0xFFFFFFFF }, { E1000_MTA, 0, 128, TABLE32_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { 0, 0, 0, 0 } }; /* 82580 reg test */ static struct igb_reg_test reg_test_82580[] = { { E1000_FCAL, 0x100, 1, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_FCAH, 0x100, 1, PATTERN_TEST, 0x0000FFFF, 0xFFFFFFFF }, { E1000_FCT, 0x100, 1, PATTERN_TEST, 0x0000FFFF, 0xFFFFFFFF }, { E1000_VET, 0x100, 1, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_RDBAL(0), 0x100, 4, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF }, { E1000_RDBAH(0), 0x100, 4, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_RDLEN(0), 0x100, 4, PATTERN_TEST, 0x000FFFF0, 0x000FFFFF }, { E1000_RDBAL(4), 0x40, 4, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF }, { E1000_RDBAH(4), 0x40, 4, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_RDLEN(4), 0x40, 4, PATTERN_TEST, 0x000FFFF0, 0x000FFFFF }, /* RDH is read-only for 82580, only test RDT. */ { E1000_RDT(0), 0x100, 4, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF }, { E1000_RDT(4), 0x40, 4, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF }, { E1000_FCRTH, 0x100, 1, PATTERN_TEST, 0x0000FFF0, 0x0000FFF0 }, { E1000_FCTTV, 0x100, 1, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF }, { E1000_TIPG, 0x100, 1, PATTERN_TEST, 0x3FFFFFFF, 0x3FFFFFFF }, { E1000_TDBAL(0), 0x100, 4, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF }, { E1000_TDBAH(0), 0x100, 4, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_TDLEN(0), 0x100, 4, PATTERN_TEST, 0x000FFFF0, 0x000FFFFF }, { E1000_TDBAL(4), 0x40, 4, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF }, { E1000_TDBAH(4), 0x40, 4, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_TDLEN(4), 0x40, 4, PATTERN_TEST, 0x000FFFF0, 0x000FFFFF }, { E1000_TDT(0), 0x100, 4, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF }, { E1000_TDT(4), 0x40, 4, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF }, { E1000_RCTL, 0x100, 1, SET_READ_TEST, 0xFFFFFFFF, 0x00000000 }, { E1000_RCTL, 0x100, 1, SET_READ_TEST, 0x04CFB0FE, 0x003FFFFB }, { E1000_RCTL, 0x100, 1, SET_READ_TEST, 0x04CFB0FE, 0xFFFFFFFF }, { E1000_TCTL, 0x100, 1, SET_READ_TEST, 0xFFFFFFFF, 0x00000000 }, { E1000_RA, 0, 16, TABLE64_TEST_LO, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_RA, 0, 16, TABLE64_TEST_HI, 0x83FFFFFF, 0xFFFFFFFF }, { E1000_RA2, 0, 8, TABLE64_TEST_LO, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_RA2, 0, 8, TABLE64_TEST_HI, 0x83FFFFFF, 0xFFFFFFFF }, { E1000_MTA, 0, 128, TABLE32_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { 0, 0, 0, 0 } }; /* 82576 reg test */ static struct igb_reg_test reg_test_82576[] = { { E1000_FCAL, 0x100, 1, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_FCAH, 0x100, 1, PATTERN_TEST, 0x0000FFFF, 0xFFFFFFFF }, { E1000_FCT, 0x100, 1, PATTERN_TEST, 0x0000FFFF, 0xFFFFFFFF }, { E1000_VET, 0x100, 1, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_RDBAL(0), 0x100, 4, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF }, { E1000_RDBAH(0), 0x100, 4, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_RDLEN(0), 0x100, 4, PATTERN_TEST, 0x000FFFF0, 0x000FFFFF }, { E1000_RDBAL(4), 0x40, 12, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF }, { E1000_RDBAH(4), 0x40, 12, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_RDLEN(4), 0x40, 12, PATTERN_TEST, 0x000FFFF0, 0x000FFFFF }, /* Enable all RX queues before testing. */ { E1000_RXDCTL(0), 0x100, 4, WRITE_NO_TEST, 0, E1000_RXDCTL_QUEUE_ENABLE }, { E1000_RXDCTL(4), 0x40, 12, WRITE_NO_TEST, 0, E1000_RXDCTL_QUEUE_ENABLE }, /* RDH is read-only for 82576, only test RDT. */ { E1000_RDT(0), 0x100, 4, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF }, { E1000_RDT(4), 0x40, 12, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF }, { E1000_RXDCTL(0), 0x100, 4, WRITE_NO_TEST, 0, 0 }, { E1000_RXDCTL(4), 0x40, 12, WRITE_NO_TEST, 0, 0 }, { E1000_FCRTH, 0x100, 1, PATTERN_TEST, 0x0000FFF0, 0x0000FFF0 }, { E1000_FCTTV, 0x100, 1, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF }, { E1000_TIPG, 0x100, 1, PATTERN_TEST, 0x3FFFFFFF, 0x3FFFFFFF }, { E1000_TDBAL(0), 0x100, 4, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF }, { E1000_TDBAH(0), 0x100, 4, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_TDLEN(0), 0x100, 4, PATTERN_TEST, 0x000FFFF0, 0x000FFFFF }, { E1000_TDBAL(4), 0x40, 12, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF }, { E1000_TDBAH(4), 0x40, 12, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_TDLEN(4), 0x40, 12, PATTERN_TEST, 0x000FFFF0, 0x000FFFFF }, { E1000_RCTL, 0x100, 1, SET_READ_TEST, 0xFFFFFFFF, 0x00000000 }, { E1000_RCTL, 0x100, 1, SET_READ_TEST, 0x04CFB0FE, 0x003FFFFB }, { E1000_RCTL, 0x100, 1, SET_READ_TEST, 0x04CFB0FE, 0xFFFFFFFF }, { E1000_TCTL, 0x100, 1, SET_READ_TEST, 0xFFFFFFFF, 0x00000000 }, { E1000_RA, 0, 16, TABLE64_TEST_LO, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_RA, 0, 16, TABLE64_TEST_HI, 0x83FFFFFF, 0xFFFFFFFF }, { E1000_RA2, 0, 8, TABLE64_TEST_LO, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_RA2, 0, 8, TABLE64_TEST_HI, 0x83FFFFFF, 0xFFFFFFFF }, { E1000_MTA, 0, 128, TABLE32_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { 0, 0, 0, 0 } }; /* 82575 register test */ static struct igb_reg_test reg_test_82575[] = { { E1000_FCAL, 0x100, 1, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_FCAH, 0x100, 1, PATTERN_TEST, 0x0000FFFF, 0xFFFFFFFF }, { E1000_FCT, 0x100, 1, PATTERN_TEST, 0x0000FFFF, 0xFFFFFFFF }, { E1000_VET, 0x100, 1, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_RDBAL(0), 0x100, 4, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF }, { E1000_RDBAH(0), 0x100, 4, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_RDLEN(0), 0x100, 4, PATTERN_TEST, 0x000FFF80, 0x000FFFFF }, /* Enable all four RX queues before testing. */ { E1000_RXDCTL(0), 0x100, 4, WRITE_NO_TEST, 0, E1000_RXDCTL_QUEUE_ENABLE }, /* RDH is read-only for 82575, only test RDT. */ { E1000_RDT(0), 0x100, 4, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF }, { E1000_RXDCTL(0), 0x100, 4, WRITE_NO_TEST, 0, 0 }, { E1000_FCRTH, 0x100, 1, PATTERN_TEST, 0x0000FFF0, 0x0000FFF0 }, { E1000_FCTTV, 0x100, 1, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF }, { E1000_TIPG, 0x100, 1, PATTERN_TEST, 0x3FFFFFFF, 0x3FFFFFFF }, { E1000_TDBAL(0), 0x100, 4, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF }, { E1000_TDBAH(0), 0x100, 4, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_TDLEN(0), 0x100, 4, PATTERN_TEST, 0x000FFF80, 0x000FFFFF }, { E1000_RCTL, 0x100, 1, SET_READ_TEST, 0xFFFFFFFF, 0x00000000 }, { E1000_RCTL, 0x100, 1, SET_READ_TEST, 0x04CFB3FE, 0x003FFFFB }, { E1000_RCTL, 0x100, 1, SET_READ_TEST, 0x04CFB3FE, 0xFFFFFFFF }, { E1000_TCTL, 0x100, 1, SET_READ_TEST, 0xFFFFFFFF, 0x00000000 }, { E1000_TXCW, 0x100, 1, PATTERN_TEST, 0xC000FFFF, 0x0000FFFF }, { E1000_RA, 0, 16, TABLE64_TEST_LO, 0xFFFFFFFF, 0xFFFFFFFF }, { E1000_RA, 0, 16, TABLE64_TEST_HI, 0x800FFFFF, 0xFFFFFFFF }, { E1000_MTA, 0, 128, TABLE32_TEST, 0xFFFFFFFF, 0xFFFFFFFF }, { 0, 0, 0, 0 } }; static bool reg_pattern_test(struct igb_adapter *adapter, u64 *data, int reg, u32 mask, u32 write) { struct e1000_hw *hw = &adapter->hw; u32 pat, val; static const u32 _test[] = { 0x5A5A5A5A, 0xA5A5A5A5, 0x00000000, 0xFFFFFFFF}; for (pat = 0; pat < ARRAY_SIZE(_test); pat++) { wr32(reg, (_test[pat] & write)); val = rd32(reg) & mask; if (val != (_test[pat] & write & mask)) { dev_err(&adapter->pdev->dev, "pattern test reg %04X failed: got 0x%08X expected 0x%08X\n", reg, val, (_test[pat] & write & mask)); *data = reg; return true; } } return false; } static bool reg_set_and_check(struct igb_adapter *adapter, u64 *data, int reg, u32 mask, u32 write) { struct e1000_hw *hw = &adapter->hw; u32 val; wr32(reg, write & mask); val = rd32(reg); if ((write & mask) != (val & mask)) { dev_err(&adapter->pdev->dev, "set/check reg %04X test failed: got 0x%08X expected 0x%08X\n", reg, (val & mask), (write & mask)); *data = reg; return true; } return false; } #define REG_PATTERN_TEST(reg, mask, write) \ do { \ if (reg_pattern_test(adapter, data, reg, mask, write)) \ return 1; \ } while (0) #define REG_SET_AND_CHECK(reg, mask, write) \ do { \ if (reg_set_and_check(adapter, data, reg, mask, write)) \ return 1; \ } while (0) static int igb_reg_test(struct igb_adapter *adapter, u64 *data) { struct e1000_hw *hw = &adapter->hw; struct igb_reg_test *test; u32 value, before, after; u32 i, toggle; switch (adapter->hw.mac.type) { case e1000_i350: case e1000_i354: test = reg_test_i350; toggle = 0x7FEFF3FF; break; case e1000_i210: case e1000_i211: test = reg_test_i210; toggle = 0x7FEFF3FF; break; case e1000_82580: test = reg_test_82580; toggle = 0x7FEFF3FF; break; case e1000_82576: test = reg_test_82576; toggle = 0x7FFFF3FF; break; default: test = reg_test_82575; toggle = 0x7FFFF3FF; break; } /* Because the status register is such a special case, * we handle it separately from the rest of the register * tests. Some bits are read-only, some toggle, and some * are writable on newer MACs. */ before = rd32(E1000_STATUS); value = (rd32(E1000_STATUS) & toggle); wr32(E1000_STATUS, toggle); after = rd32(E1000_STATUS) & toggle; if (value != after) { dev_err(&adapter->pdev->dev, "failed STATUS register test got: 0x%08X expected: 0x%08X\n", after, value); *data = 1; return 1; } /* restore previous status */ wr32(E1000_STATUS, before); /* Perform the remainder of the register test, looping through * the test table until we either fail or reach the null entry. */ while (test->reg) { for (i = 0; i < test->array_len; i++) { switch (test->test_type) { case PATTERN_TEST: REG_PATTERN_TEST(test->reg + (i * test->reg_offset), test->mask, test->write); break; case SET_READ_TEST: REG_SET_AND_CHECK(test->reg + (i * test->reg_offset), test->mask, test->write); break; case WRITE_NO_TEST: writel(test->write, (adapter->hw.hw_addr + test->reg) + (i * test->reg_offset)); break; case TABLE32_TEST: REG_PATTERN_TEST(test->reg + (i * 4), test->mask, test->write); break; case TABLE64_TEST_LO: REG_PATTERN_TEST(test->reg + (i * 8), test->mask, test->write); break; case TABLE64_TEST_HI: REG_PATTERN_TEST((test->reg + 4) + (i * 8), test->mask, test->write); break; } } test++; } *data = 0; return 0; } static int igb_eeprom_test(struct igb_adapter *adapter, u64 *data) { struct e1000_hw *hw = &adapter->hw; *data = 0; /* Validate eeprom on all parts but flashless */ switch (hw->mac.type) { case e1000_i210: case e1000_i211: if (igb_get_flash_presence_i210(hw)) { if (adapter->hw.nvm.ops.validate(&adapter->hw) < 0) *data = 2; } break; default: if (adapter->hw.nvm.ops.validate(&adapter->hw) < 0) *data = 2; break; } return *data; } static irqreturn_t igb_test_intr(int irq, void *data) { struct igb_adapter *adapter = (struct igb_adapter *) data; struct e1000_hw *hw = &adapter->hw; adapter->test_icr |= rd32(E1000_ICR); return IRQ_HANDLED; } static int igb_intr_test(struct igb_adapter *adapter, u64 *data) { struct e1000_hw *hw = &adapter->hw; struct net_device *netdev = adapter->netdev; u32 mask, ics_mask, i = 0, shared_int = true; u32 irq = adapter->pdev->irq; *data = 0; /* Hook up test interrupt handler just for this test */ if (adapter->flags & IGB_FLAG_HAS_MSIX) { if (request_irq(adapter->msix_entries[0].vector, igb_test_intr, 0, netdev->name, adapter)) { *data = 1; return -1; } wr32(E1000_IVAR_MISC, E1000_IVAR_VALID << 8); wr32(E1000_EIMS, BIT(0)); } else if (adapter->flags & IGB_FLAG_HAS_MSI) { shared_int = false; if (request_irq(irq, igb_test_intr, 0, netdev->name, adapter)) { *data = 1; return -1; } } else if (!request_irq(irq, igb_test_intr, IRQF_PROBE_SHARED, netdev->name, adapter)) { shared_int = false; } else if (request_irq(irq, igb_test_intr, IRQF_SHARED, netdev->name, adapter)) { *data = 1; return -1; } dev_info(&adapter->pdev->dev, "testing %s interrupt\n", (shared_int ? "shared" : "unshared")); /* Disable all the interrupts */ wr32(E1000_IMC, ~0); wrfl(); usleep_range(10000, 11000); /* Define all writable bits for ICS */ switch (hw->mac.type) { case e1000_82575: ics_mask = 0x37F47EDD; break; case e1000_82576: ics_mask = 0x77D4FBFD; break; case e1000_82580: ics_mask = 0x77DCFED5; break; case e1000_i350: case e1000_i354: case e1000_i210: case e1000_i211: ics_mask = 0x77DCFED5; break; default: ics_mask = 0x7FFFFFFF; break; } /* Test each interrupt */ for (; i < 31; i++) { /* Interrupt to test */ mask = BIT(i); if (!(mask & ics_mask)) continue; if (!shared_int) { /* Disable the interrupt to be reported in * the cause register and then force the same * interrupt and see if one gets posted. If * an interrupt was posted to the bus, the * test failed. */ adapter->test_icr = 0; /* Flush any pending interrupts */ wr32(E1000_ICR, ~0); wr32(E1000_IMC, mask); wr32(E1000_ICS, mask); wrfl(); usleep_range(10000, 11000); if (adapter->test_icr & mask) { *data = 3; break; } } /* Enable the interrupt to be reported in * the cause register and then force the same * interrupt and see if one gets posted. If * an interrupt was not posted to the bus, the * test failed. */ adapter->test_icr = 0; /* Flush any pending interrupts */ wr32(E1000_ICR, ~0); wr32(E1000_IMS, mask); wr32(E1000_ICS, mask); wrfl(); usleep_range(10000, 11000); if (!(adapter->test_icr & mask)) { *data = 4; break; } if (!shared_int) { /* Disable the other interrupts to be reported in * the cause register and then force the other * interrupts and see if any get posted. If * an interrupt was posted to the bus, the * test failed. */ adapter->test_icr = 0; /* Flush any pending interrupts */ wr32(E1000_ICR, ~0); wr32(E1000_IMC, ~mask); wr32(E1000_ICS, ~mask); wrfl(); usleep_range(10000, 11000); if (adapter->test_icr & mask) { *data = 5; break; } } } /* Disable all the interrupts */ wr32(E1000_IMC, ~0); wrfl(); usleep_range(10000, 11000); /* Unhook test interrupt handler */ if (adapter->flags & IGB_FLAG_HAS_MSIX) free_irq(adapter->msix_entries[0].vector, adapter); else free_irq(irq, adapter); return *data; } static void igb_free_desc_rings(struct igb_adapter *adapter) { igb_free_tx_resources(&adapter->test_tx_ring); igb_free_rx_resources(&adapter->test_rx_ring); } static int igb_setup_desc_rings(struct igb_adapter *adapter) { struct igb_ring *tx_ring = &adapter->test_tx_ring; struct igb_ring *rx_ring = &adapter->test_rx_ring; struct e1000_hw *hw = &adapter->hw; int ret_val; /* Setup Tx descriptor ring and Tx buffers */ tx_ring->count = IGB_DEFAULT_TXD; tx_ring->dev = &adapter->pdev->dev; tx_ring->netdev = adapter->netdev; tx_ring->reg_idx = adapter->vfs_allocated_count; if (igb_setup_tx_resources(tx_ring)) { ret_val = 1; goto err_nomem; } igb_setup_tctl(adapter); igb_configure_tx_ring(adapter, tx_ring); /* Setup Rx descriptor ring and Rx buffers */ rx_ring->count = IGB_DEFAULT_RXD; rx_ring->dev = &adapter->pdev->dev; rx_ring->netdev = adapter->netdev; rx_ring->reg_idx = adapter->vfs_allocated_count; if (igb_setup_rx_resources(rx_ring)) { ret_val = 3; goto err_nomem; } /* set the default queue to queue 0 of PF */ wr32(E1000_MRQC, adapter->vfs_allocated_count << 3); /* enable receive ring */ igb_setup_rctl(adapter); igb_configure_rx_ring(adapter, rx_ring); igb_alloc_rx_buffers(rx_ring, igb_desc_unused(rx_ring)); return 0; err_nomem: igb_free_desc_rings(adapter); return ret_val; } static void igb_phy_disable_receiver(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; /* Write out to PHY registers 29 and 30 to disable the Receiver. */ igb_write_phy_reg(hw, 29, 0x001F); igb_write_phy_reg(hw, 30, 0x8FFC); igb_write_phy_reg(hw, 29, 0x001A); igb_write_phy_reg(hw, 30, 0x8FF0); } static int igb_integrated_phy_loopback(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 ctrl_reg = 0; hw->mac.autoneg = false; if (hw->phy.type == e1000_phy_m88) { if (hw->phy.id != I210_I_PHY_ID) { /* Auto-MDI/MDIX Off */ igb_write_phy_reg(hw, M88E1000_PHY_SPEC_CTRL, 0x0808); /* reset to update Auto-MDI/MDIX */ igb_write_phy_reg(hw, PHY_CONTROL, 0x9140); /* autoneg off */ igb_write_phy_reg(hw, PHY_CONTROL, 0x8140); } else { /* force 1000, set loopback */ igb_write_phy_reg(hw, I347AT4_PAGE_SELECT, 0); igb_write_phy_reg(hw, PHY_CONTROL, 0x4140); } } else if (hw->phy.type == e1000_phy_82580) { /* enable MII loopback */ igb_write_phy_reg(hw, I82580_PHY_LBK_CTRL, 0x8041); } /* add small delay to avoid loopback test failure */ msleep(50); /* force 1000, set loopback */ igb_write_phy_reg(hw, PHY_CONTROL, 0x4140); /* Now set up the MAC to the same speed/duplex as the PHY. */ ctrl_reg = rd32(E1000_CTRL); ctrl_reg &= ~E1000_CTRL_SPD_SEL; /* Clear the speed sel bits */ ctrl_reg |= (E1000_CTRL_FRCSPD | /* Set the Force Speed Bit */ E1000_CTRL_FRCDPX | /* Set the Force Duplex Bit */ E1000_CTRL_SPD_1000 |/* Force Speed to 1000 */ E1000_CTRL_FD | /* Force Duplex to FULL */ E1000_CTRL_SLU); /* Set link up enable bit */ if (hw->phy.type == e1000_phy_m88) ctrl_reg |= E1000_CTRL_ILOS; /* Invert Loss of Signal */ wr32(E1000_CTRL, ctrl_reg); /* Disable the receiver on the PHY so when a cable is plugged in, the * PHY does not begin to autoneg when a cable is reconnected to the NIC. */ if (hw->phy.type == e1000_phy_m88) igb_phy_disable_receiver(adapter); msleep(500); return 0; } static int igb_set_phy_loopback(struct igb_adapter *adapter) { return igb_integrated_phy_loopback(adapter); } static int igb_setup_loopback_test(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 reg; reg = rd32(E1000_CTRL_EXT); /* use CTRL_EXT to identify link type as SGMII can appear as copper */ if (reg & E1000_CTRL_EXT_LINK_MODE_MASK) { if ((hw->device_id == E1000_DEV_ID_DH89XXCC_SGMII) || (hw->device_id == E1000_DEV_ID_DH89XXCC_SERDES) || (hw->device_id == E1000_DEV_ID_DH89XXCC_BACKPLANE) || (hw->device_id == E1000_DEV_ID_DH89XXCC_SFP) || (hw->device_id == E1000_DEV_ID_I354_SGMII) || (hw->device_id == E1000_DEV_ID_I354_BACKPLANE_2_5GBPS)) { /* Enable DH89xxCC MPHY for near end loopback */ reg = rd32(E1000_MPHY_ADDR_CTL); reg = (reg & E1000_MPHY_ADDR_CTL_OFFSET_MASK) | E1000_MPHY_PCS_CLK_REG_OFFSET; wr32(E1000_MPHY_ADDR_CTL, reg); reg = rd32(E1000_MPHY_DATA); reg |= E1000_MPHY_PCS_CLK_REG_DIGINELBEN; wr32(E1000_MPHY_DATA, reg); } reg = rd32(E1000_RCTL); reg |= E1000_RCTL_LBM_TCVR; wr32(E1000_RCTL, reg); wr32(E1000_SCTL, E1000_ENABLE_SERDES_LOOPBACK); reg = rd32(E1000_CTRL); reg &= ~(E1000_CTRL_RFCE | E1000_CTRL_TFCE | E1000_CTRL_LRST); reg |= E1000_CTRL_SLU | E1000_CTRL_FD; wr32(E1000_CTRL, reg); /* Unset switch control to serdes energy detect */ reg = rd32(E1000_CONNSW); reg &= ~E1000_CONNSW_ENRGSRC; wr32(E1000_CONNSW, reg); /* Unset sigdetect for SERDES loopback on * 82580 and newer devices. */ if (hw->mac.type >= e1000_82580) { reg = rd32(E1000_PCS_CFG0); reg |= E1000_PCS_CFG_IGN_SD; wr32(E1000_PCS_CFG0, reg); } /* Set PCS register for forced speed */ reg = rd32(E1000_PCS_LCTL); reg &= ~E1000_PCS_LCTL_AN_ENABLE; /* Disable Autoneg*/ reg |= E1000_PCS_LCTL_FLV_LINK_UP | /* Force link up */ E1000_PCS_LCTL_FSV_1000 | /* Force 1000 */ E1000_PCS_LCTL_FDV_FULL | /* SerDes Full duplex */ E1000_PCS_LCTL_FSD | /* Force Speed */ E1000_PCS_LCTL_FORCE_LINK; /* Force Link */ wr32(E1000_PCS_LCTL, reg); return 0; } return igb_set_phy_loopback(adapter); } static void igb_loopback_cleanup(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 rctl; u16 phy_reg; if ((hw->device_id == E1000_DEV_ID_DH89XXCC_SGMII) || (hw->device_id == E1000_DEV_ID_DH89XXCC_SERDES) || (hw->device_id == E1000_DEV_ID_DH89XXCC_BACKPLANE) || (hw->device_id == E1000_DEV_ID_DH89XXCC_SFP) || (hw->device_id == E1000_DEV_ID_I354_SGMII)) { u32 reg; /* Disable near end loopback on DH89xxCC */ reg = rd32(E1000_MPHY_ADDR_CTL); reg = (reg & E1000_MPHY_ADDR_CTL_OFFSET_MASK) | E1000_MPHY_PCS_CLK_REG_OFFSET; wr32(E1000_MPHY_ADDR_CTL, reg); reg = rd32(E1000_MPHY_DATA); reg &= ~E1000_MPHY_PCS_CLK_REG_DIGINELBEN; wr32(E1000_MPHY_DATA, reg); } rctl = rd32(E1000_RCTL); rctl &= ~(E1000_RCTL_LBM_TCVR | E1000_RCTL_LBM_MAC); wr32(E1000_RCTL, rctl); hw->mac.autoneg = true; igb_read_phy_reg(hw, PHY_CONTROL, &phy_reg); if (phy_reg & MII_CR_LOOPBACK) { phy_reg &= ~MII_CR_LOOPBACK; igb_write_phy_reg(hw, PHY_CONTROL, phy_reg); igb_phy_sw_reset(hw); } } static void igb_create_lbtest_frame(struct sk_buff *skb, unsigned int frame_size) { memset(skb->data, 0xFF, frame_size); frame_size /= 2; memset(&skb->data[frame_size], 0xAA, frame_size - 1); skb->data[frame_size + 10] = 0xBE; skb->data[frame_size + 12] = 0xAF; } static int igb_check_lbtest_frame(struct igb_rx_buffer *rx_buffer, unsigned int frame_size) { unsigned char *data; bool match = true; frame_size >>= 1; data = kmap_local_page(rx_buffer->page); if (data[3] != 0xFF || data[frame_size + 10] != 0xBE || data[frame_size + 12] != 0xAF) match = false; kunmap_local(data); return match; } static int igb_clean_test_rings(struct igb_ring *rx_ring, struct igb_ring *tx_ring, unsigned int size) { union e1000_adv_rx_desc *rx_desc; struct igb_rx_buffer *rx_buffer_info; struct igb_tx_buffer *tx_buffer_info; u16 rx_ntc, tx_ntc, count = 0; /* initialize next to clean and descriptor values */ rx_ntc = rx_ring->next_to_clean; tx_ntc = tx_ring->next_to_clean; rx_desc = IGB_RX_DESC(rx_ring, rx_ntc); while (rx_desc->wb.upper.length) { /* check Rx buffer */ rx_buffer_info = &rx_ring->rx_buffer_info[rx_ntc]; /* sync Rx buffer for CPU read */ dma_sync_single_for_cpu(rx_ring->dev, rx_buffer_info->dma, size, DMA_FROM_DEVICE); /* verify contents of skb */ if (igb_check_lbtest_frame(rx_buffer_info, size)) count++; /* sync Rx buffer for device write */ dma_sync_single_for_device(rx_ring->dev, rx_buffer_info->dma, size, DMA_FROM_DEVICE); /* unmap buffer on Tx side */ tx_buffer_info = &tx_ring->tx_buffer_info[tx_ntc]; /* Free all the Tx ring sk_buffs */ dev_kfree_skb_any(tx_buffer_info->skb); /* unmap skb header data */ dma_unmap_single(tx_ring->dev, dma_unmap_addr(tx_buffer_info, dma), dma_unmap_len(tx_buffer_info, len), DMA_TO_DEVICE); dma_unmap_len_set(tx_buffer_info, len, 0); /* increment Rx/Tx next to clean counters */ rx_ntc++; if (rx_ntc == rx_ring->count) rx_ntc = 0; tx_ntc++; if (tx_ntc == tx_ring->count) tx_ntc = 0; /* fetch next descriptor */ rx_desc = IGB_RX_DESC(rx_ring, rx_ntc); } netdev_tx_reset_queue(txring_txq(tx_ring)); /* re-map buffers to ring, store next to clean values */ igb_alloc_rx_buffers(rx_ring, count); rx_ring->next_to_clean = rx_ntc; tx_ring->next_to_clean = tx_ntc; return count; } static int igb_run_loopback_test(struct igb_adapter *adapter) { struct igb_ring *tx_ring = &adapter->test_tx_ring; struct igb_ring *rx_ring = &adapter->test_rx_ring; u16 i, j, lc, good_cnt; int ret_val = 0; unsigned int size = IGB_RX_HDR_LEN; netdev_tx_t tx_ret_val; struct sk_buff *skb; /* allocate test skb */ skb = alloc_skb(size, GFP_KERNEL); if (!skb) return 11; /* place data into test skb */ igb_create_lbtest_frame(skb, size); skb_put(skb, size); /* Calculate the loop count based on the largest descriptor ring * The idea is to wrap the largest ring a number of times using 64 * send/receive pairs during each loop */ if (rx_ring->count <= tx_ring->count) lc = ((tx_ring->count / 64) * 2) + 1; else lc = ((rx_ring->count / 64) * 2) + 1; for (j = 0; j <= lc; j++) { /* loop count loop */ /* reset count of good packets */ good_cnt = 0; /* place 64 packets on the transmit queue*/ for (i = 0; i < 64; i++) { skb_get(skb); tx_ret_val = igb_xmit_frame_ring(skb, tx_ring); if (tx_ret_val == NETDEV_TX_OK) good_cnt++; } if (good_cnt != 64) { ret_val = 12; break; } /* allow 200 milliseconds for packets to go from Tx to Rx */ msleep(200); good_cnt = igb_clean_test_rings(rx_ring, tx_ring, size); if (good_cnt != 64) { ret_val = 13; break; } } /* end loop count loop */ /* free the original skb */ kfree_skb(skb); return ret_val; } static int igb_loopback_test(struct igb_adapter *adapter, u64 *data) { /* PHY loopback cannot be performed if SoL/IDER * sessions are active */ if (igb_check_reset_block(&adapter->hw)) { dev_err(&adapter->pdev->dev, "Cannot do PHY loopback test when SoL/IDER is active.\n"); *data = 0; goto out; } if (adapter->hw.mac.type == e1000_i354) { dev_info(&adapter->pdev->dev, "Loopback test not supported on i354.\n"); *data = 0; goto out; } *data = igb_setup_desc_rings(adapter); if (*data) goto out; *data = igb_setup_loopback_test(adapter); if (*data) goto err_loopback; *data = igb_run_loopback_test(adapter); igb_loopback_cleanup(adapter); err_loopback: igb_free_desc_rings(adapter); out: return *data; } static int igb_link_test(struct igb_adapter *adapter, u64 *data) { struct e1000_hw *hw = &adapter->hw; *data = 0; if (hw->phy.media_type == e1000_media_type_internal_serdes) { int i = 0; hw->mac.serdes_has_link = false; /* On some blade server designs, link establishment * could take as long as 2-3 minutes */ do { hw->mac.ops.check_for_link(&adapter->hw); if (hw->mac.serdes_has_link) return *data; msleep(20); } while (i++ < 3750); *data = 1; } else { hw->mac.ops.check_for_link(&adapter->hw); if (hw->mac.autoneg) msleep(5000); if (!(rd32(E1000_STATUS) & E1000_STATUS_LU)) *data = 1; } return *data; } static void igb_diag_test(struct net_device *netdev, struct ethtool_test *eth_test, u64 *data) { struct igb_adapter *adapter = netdev_priv(netdev); u16 autoneg_advertised; u8 forced_speed_duplex, autoneg; bool if_running = netif_running(netdev); set_bit(__IGB_TESTING, &adapter->state); /* can't do offline tests on media switching devices */ if (adapter->hw.dev_spec._82575.mas_capable) eth_test->flags &= ~ETH_TEST_FL_OFFLINE; if (eth_test->flags == ETH_TEST_FL_OFFLINE) { /* Offline tests */ /* save speed, duplex, autoneg settings */ autoneg_advertised = adapter->hw.phy.autoneg_advertised; forced_speed_duplex = adapter->hw.mac.forced_speed_duplex; autoneg = adapter->hw.mac.autoneg; dev_info(&adapter->pdev->dev, "offline testing starting\n"); /* power up link for link test */ igb_power_up_link(adapter); /* Link test performed before hardware reset so autoneg doesn't * interfere with test result */ if (igb_link_test(adapter, &data[TEST_LINK])) eth_test->flags |= ETH_TEST_FL_FAILED; if (if_running) /* indicate we're in test mode */ igb_close(netdev); else igb_reset(adapter); if (igb_reg_test(adapter, &data[TEST_REG])) eth_test->flags |= ETH_TEST_FL_FAILED; igb_reset(adapter); if (igb_eeprom_test(adapter, &data[TEST_EEP])) eth_test->flags |= ETH_TEST_FL_FAILED; igb_reset(adapter); if (igb_intr_test(adapter, &data[TEST_IRQ])) eth_test->flags |= ETH_TEST_FL_FAILED; igb_reset(adapter); /* power up link for loopback test */ igb_power_up_link(adapter); if (igb_loopback_test(adapter, &data[TEST_LOOP])) eth_test->flags |= ETH_TEST_FL_FAILED; /* restore speed, duplex, autoneg settings */ adapter->hw.phy.autoneg_advertised = autoneg_advertised; adapter->hw.mac.forced_speed_duplex = forced_speed_duplex; adapter->hw.mac.autoneg = autoneg; /* force this routine to wait until autoneg complete/timeout */ adapter->hw.phy.autoneg_wait_to_complete = true; igb_reset(adapter); adapter->hw.phy.autoneg_wait_to_complete = false; clear_bit(__IGB_TESTING, &adapter->state); if (if_running) igb_open(netdev); } else { dev_info(&adapter->pdev->dev, "online testing starting\n"); /* PHY is powered down when interface is down */ if (if_running && igb_link_test(adapter, &data[TEST_LINK])) eth_test->flags |= ETH_TEST_FL_FAILED; else data[TEST_LINK] = 0; /* Online tests aren't run; pass by default */ data[TEST_REG] = 0; data[TEST_EEP] = 0; data[TEST_IRQ] = 0; data[TEST_LOOP] = 0; clear_bit(__IGB_TESTING, &adapter->state); } msleep_interruptible(4 * 1000); } static void igb_get_wol(struct net_device *netdev, struct ethtool_wolinfo *wol) { struct igb_adapter *adapter = netdev_priv(netdev); wol->wolopts = 0; if (!(adapter->flags & IGB_FLAG_WOL_SUPPORTED)) return; wol->supported = WAKE_UCAST | WAKE_MCAST | WAKE_BCAST | WAKE_MAGIC | WAKE_PHY; /* apply any specific unsupported masks here */ switch (adapter->hw.device_id) { default: break; } if (adapter->wol & E1000_WUFC_EX) wol->wolopts |= WAKE_UCAST; if (adapter->wol & E1000_WUFC_MC) wol->wolopts |= WAKE_MCAST; if (adapter->wol & E1000_WUFC_BC) wol->wolopts |= WAKE_BCAST; if (adapter->wol & E1000_WUFC_MAG) wol->wolopts |= WAKE_MAGIC; if (adapter->wol & E1000_WUFC_LNKC) wol->wolopts |= WAKE_PHY; } static int igb_set_wol(struct net_device *netdev, struct ethtool_wolinfo *wol) { struct igb_adapter *adapter = netdev_priv(netdev); if (wol->wolopts & (WAKE_ARP | WAKE_MAGICSECURE | WAKE_FILTER)) return -EOPNOTSUPP; if (!(adapter->flags & IGB_FLAG_WOL_SUPPORTED)) return wol->wolopts ? -EOPNOTSUPP : 0; /* these settings will always override what we currently have */ adapter->wol = 0; if (wol->wolopts & WAKE_UCAST) adapter->wol |= E1000_WUFC_EX; if (wol->wolopts & WAKE_MCAST) adapter->wol |= E1000_WUFC_MC; if (wol->wolopts & WAKE_BCAST) adapter->wol |= E1000_WUFC_BC; if (wol->wolopts & WAKE_MAGIC) adapter->wol |= E1000_WUFC_MAG; if (wol->wolopts & WAKE_PHY) adapter->wol |= E1000_WUFC_LNKC; device_set_wakeup_enable(&adapter->pdev->dev, adapter->wol); return 0; } /* bit defines for adapter->led_status */ #define IGB_LED_ON 0 static int igb_set_phys_id(struct net_device *netdev, enum ethtool_phys_id_state state) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; switch (state) { case ETHTOOL_ID_ACTIVE: igb_blink_led(hw); return 2; case ETHTOOL_ID_ON: igb_blink_led(hw); break; case ETHTOOL_ID_OFF: igb_led_off(hw); break; case ETHTOOL_ID_INACTIVE: igb_led_off(hw); clear_bit(IGB_LED_ON, &adapter->led_status); igb_cleanup_led(hw); break; } return 0; } static int igb_set_coalesce(struct net_device *netdev, struct ethtool_coalesce *ec, struct kernel_ethtool_coalesce *kernel_coal, struct netlink_ext_ack *extack) { struct igb_adapter *adapter = netdev_priv(netdev); int i; if ((ec->rx_coalesce_usecs > IGB_MAX_ITR_USECS) || ((ec->rx_coalesce_usecs > 3) && (ec->rx_coalesce_usecs < IGB_MIN_ITR_USECS)) || (ec->rx_coalesce_usecs == 2)) return -EINVAL; if ((ec->tx_coalesce_usecs > IGB_MAX_ITR_USECS) || ((ec->tx_coalesce_usecs > 3) && (ec->tx_coalesce_usecs < IGB_MIN_ITR_USECS)) || (ec->tx_coalesce_usecs == 2)) return -EINVAL; if ((adapter->flags & IGB_FLAG_QUEUE_PAIRS) && ec->tx_coalesce_usecs) return -EINVAL; /* If ITR is disabled, disable DMAC */ if (ec->rx_coalesce_usecs == 0) { if (adapter->flags & IGB_FLAG_DMAC) adapter->flags &= ~IGB_FLAG_DMAC; } /* convert to rate of irq's per second */ if (ec->rx_coalesce_usecs && ec->rx_coalesce_usecs <= 3) adapter->rx_itr_setting = ec->rx_coalesce_usecs; else adapter->rx_itr_setting = ec->rx_coalesce_usecs << 2; /* convert to rate of irq's per second */ if (adapter->flags & IGB_FLAG_QUEUE_PAIRS) adapter->tx_itr_setting = adapter->rx_itr_setting; else if (ec->tx_coalesce_usecs && ec->tx_coalesce_usecs <= 3) adapter->tx_itr_setting = ec->tx_coalesce_usecs; else adapter->tx_itr_setting = ec->tx_coalesce_usecs << 2; for (i = 0; i < adapter->num_q_vectors; i++) { struct igb_q_vector *q_vector = adapter->q_vector[i]; q_vector->tx.work_limit = adapter->tx_work_limit; if (q_vector->rx.ring) q_vector->itr_val = adapter->rx_itr_setting; else q_vector->itr_val = adapter->tx_itr_setting; if (q_vector->itr_val && q_vector->itr_val <= 3) q_vector->itr_val = IGB_START_ITR; q_vector->set_itr = 1; } return 0; } static int igb_get_coalesce(struct net_device *netdev, struct ethtool_coalesce *ec, struct kernel_ethtool_coalesce *kernel_coal, struct netlink_ext_ack *extack) { struct igb_adapter *adapter = netdev_priv(netdev); if (adapter->rx_itr_setting <= 3) ec->rx_coalesce_usecs = adapter->rx_itr_setting; else ec->rx_coalesce_usecs = adapter->rx_itr_setting >> 2; if (!(adapter->flags & IGB_FLAG_QUEUE_PAIRS)) { if (adapter->tx_itr_setting <= 3) ec->tx_coalesce_usecs = adapter->tx_itr_setting; else ec->tx_coalesce_usecs = adapter->tx_itr_setting >> 2; } return 0; } static int igb_nway_reset(struct net_device *netdev) { struct igb_adapter *adapter = netdev_priv(netdev); if (netif_running(netdev)) igb_reinit_locked(adapter); return 0; } static int igb_get_sset_count(struct net_device *netdev, int sset) { switch (sset) { case ETH_SS_STATS: return IGB_STATS_LEN; case ETH_SS_TEST: return IGB_TEST_LEN; case ETH_SS_PRIV_FLAGS: return IGB_PRIV_FLAGS_STR_LEN; default: return -ENOTSUPP; } } static void igb_get_ethtool_stats(struct net_device *netdev, struct ethtool_stats *stats, u64 *data) { struct igb_adapter *adapter = netdev_priv(netdev); struct rtnl_link_stats64 *net_stats = &adapter->stats64; unsigned int start; struct igb_ring *ring; int i, j; char *p; spin_lock(&adapter->stats64_lock); igb_update_stats(adapter); for (i = 0; i < IGB_GLOBAL_STATS_LEN; i++) { p = (char *)adapter + igb_gstrings_stats[i].stat_offset; data[i] = (igb_gstrings_stats[i].sizeof_stat == sizeof(u64)) ? *(u64 *)p : *(u32 *)p; } for (j = 0; j < IGB_NETDEV_STATS_LEN; j++, i++) { p = (char *)net_stats + igb_gstrings_net_stats[j].stat_offset; data[i] = (igb_gstrings_net_stats[j].sizeof_stat == sizeof(u64)) ? *(u64 *)p : *(u32 *)p; } for (j = 0; j < adapter->num_tx_queues; j++) { u64 restart2; ring = adapter->tx_ring[j]; do { start = u64_stats_fetch_begin(&ring->tx_syncp); data[i] = ring->tx_stats.packets; data[i+1] = ring->tx_stats.bytes; data[i+2] = ring->tx_stats.restart_queue; } while (u64_stats_fetch_retry(&ring->tx_syncp, start)); do { start = u64_stats_fetch_begin(&ring->tx_syncp2); restart2 = ring->tx_stats.restart_queue2; } while (u64_stats_fetch_retry(&ring->tx_syncp2, start)); data[i+2] += restart2; i += IGB_TX_QUEUE_STATS_LEN; } for (j = 0; j < adapter->num_rx_queues; j++) { ring = adapter->rx_ring[j]; do { start = u64_stats_fetch_begin(&ring->rx_syncp); data[i] = ring->rx_stats.packets; data[i+1] = ring->rx_stats.bytes; data[i+2] = ring->rx_stats.drops; data[i+3] = ring->rx_stats.csum_err; data[i+4] = ring->rx_stats.alloc_failed; } while (u64_stats_fetch_retry(&ring->rx_syncp, start)); i += IGB_RX_QUEUE_STATS_LEN; } spin_unlock(&adapter->stats64_lock); } static void igb_get_strings(struct net_device *netdev, u32 stringset, u8 *data) { struct igb_adapter *adapter = netdev_priv(netdev); u8 *p = data; int i; switch (stringset) { case ETH_SS_TEST: memcpy(data, igb_gstrings_test, sizeof(igb_gstrings_test)); break; case ETH_SS_STATS: for (i = 0; i < IGB_GLOBAL_STATS_LEN; i++) ethtool_sprintf(&p, igb_gstrings_stats[i].stat_string); for (i = 0; i < IGB_NETDEV_STATS_LEN; i++) ethtool_sprintf(&p, igb_gstrings_net_stats[i].stat_string); for (i = 0; i < adapter->num_tx_queues; i++) { ethtool_sprintf(&p, "tx_queue_%u_packets", i); ethtool_sprintf(&p, "tx_queue_%u_bytes", i); ethtool_sprintf(&p, "tx_queue_%u_restart", i); } for (i = 0; i < adapter->num_rx_queues; i++) { ethtool_sprintf(&p, "rx_queue_%u_packets", i); ethtool_sprintf(&p, "rx_queue_%u_bytes", i); ethtool_sprintf(&p, "rx_queue_%u_drops", i); ethtool_sprintf(&p, "rx_queue_%u_csum_err", i); ethtool_sprintf(&p, "rx_queue_%u_alloc_failed", i); } /* BUG_ON(p - data != IGB_STATS_LEN * ETH_GSTRING_LEN); */ break; case ETH_SS_PRIV_FLAGS: memcpy(data, igb_priv_flags_strings, IGB_PRIV_FLAGS_STR_LEN * ETH_GSTRING_LEN); break; } } static int igb_get_ts_info(struct net_device *dev, struct ethtool_ts_info *info) { struct igb_adapter *adapter = netdev_priv(dev); if (adapter->ptp_clock) info->phc_index = ptp_clock_index(adapter->ptp_clock); else info->phc_index = -1; switch (adapter->hw.mac.type) { case e1000_82575: info->so_timestamping = SOF_TIMESTAMPING_TX_SOFTWARE | SOF_TIMESTAMPING_RX_SOFTWARE | SOF_TIMESTAMPING_SOFTWARE; return 0; case e1000_82576: case e1000_82580: case e1000_i350: case e1000_i354: case e1000_i210: case e1000_i211: info->so_timestamping = SOF_TIMESTAMPING_TX_SOFTWARE | SOF_TIMESTAMPING_RX_SOFTWARE | SOF_TIMESTAMPING_SOFTWARE | SOF_TIMESTAMPING_TX_HARDWARE | SOF_TIMESTAMPING_RX_HARDWARE | SOF_TIMESTAMPING_RAW_HARDWARE; info->tx_types = BIT(HWTSTAMP_TX_OFF) | BIT(HWTSTAMP_TX_ON); info->rx_filters = BIT(HWTSTAMP_FILTER_NONE); /* 82576 does not support timestamping all packets. */ if (adapter->hw.mac.type >= e1000_82580) info->rx_filters |= BIT(HWTSTAMP_FILTER_ALL); else info->rx_filters |= BIT(HWTSTAMP_FILTER_PTP_V1_L4_SYNC) | BIT(HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ) | BIT(HWTSTAMP_FILTER_PTP_V2_EVENT); return 0; default: return -EOPNOTSUPP; } } #define ETHER_TYPE_FULL_MASK ((__force __be16)~0) static int igb_get_ethtool_nfc_entry(struct igb_adapter *adapter, struct ethtool_rxnfc *cmd) { struct ethtool_rx_flow_spec *fsp = &cmd->fs; struct igb_nfc_filter *rule = NULL; /* report total rule count */ cmd->data = IGB_MAX_RXNFC_FILTERS; hlist_for_each_entry(rule, &adapter->nfc_filter_list, nfc_node) { if (fsp->location <= rule->sw_idx) break; } if (!rule || fsp->location != rule->sw_idx) return -EINVAL; if (rule->filter.match_flags) { fsp->flow_type = ETHER_FLOW; fsp->ring_cookie = rule->action; if (rule->filter.match_flags & IGB_FILTER_FLAG_ETHER_TYPE) { fsp->h_u.ether_spec.h_proto = rule->filter.etype; fsp->m_u.ether_spec.h_proto = ETHER_TYPE_FULL_MASK; } if (rule->filter.match_flags & IGB_FILTER_FLAG_VLAN_TCI) { fsp->flow_type |= FLOW_EXT; fsp->h_ext.vlan_tci = rule->filter.vlan_tci; fsp->m_ext.vlan_tci = htons(VLAN_PRIO_MASK); } if (rule->filter.match_flags & IGB_FILTER_FLAG_DST_MAC_ADDR) { ether_addr_copy(fsp->h_u.ether_spec.h_dest, rule->filter.dst_addr); /* As we only support matching by the full * mask, return the mask to userspace */ eth_broadcast_addr(fsp->m_u.ether_spec.h_dest); } if (rule->filter.match_flags & IGB_FILTER_FLAG_SRC_MAC_ADDR) { ether_addr_copy(fsp->h_u.ether_spec.h_source, rule->filter.src_addr); /* As we only support matching by the full * mask, return the mask to userspace */ eth_broadcast_addr(fsp->m_u.ether_spec.h_source); } return 0; } return -EINVAL; } static int igb_get_ethtool_nfc_all(struct igb_adapter *adapter, struct ethtool_rxnfc *cmd, u32 *rule_locs) { struct igb_nfc_filter *rule; int cnt = 0; /* report total rule count */ cmd->data = IGB_MAX_RXNFC_FILTERS; hlist_for_each_entry(rule, &adapter->nfc_filter_list, nfc_node) { if (cnt == cmd->rule_cnt) return -EMSGSIZE; rule_locs[cnt] = rule->sw_idx; cnt++; } cmd->rule_cnt = cnt; return 0; } static int igb_get_rss_hash_opts(struct igb_adapter *adapter, struct ethtool_rxnfc *cmd) { cmd->data = 0; /* Report default options for RSS on igb */ switch (cmd->flow_type) { case TCP_V4_FLOW: cmd->data |= RXH_L4_B_0_1 | RXH_L4_B_2_3; fallthrough; case UDP_V4_FLOW: if (adapter->flags & IGB_FLAG_RSS_FIELD_IPV4_UDP) cmd->data |= RXH_L4_B_0_1 | RXH_L4_B_2_3; fallthrough; case SCTP_V4_FLOW: case AH_ESP_V4_FLOW: case AH_V4_FLOW: case ESP_V4_FLOW: case IPV4_FLOW: cmd->data |= RXH_IP_SRC | RXH_IP_DST; break; case TCP_V6_FLOW: cmd->data |= RXH_L4_B_0_1 | RXH_L4_B_2_3; fallthrough; case UDP_V6_FLOW: if (adapter->flags & IGB_FLAG_RSS_FIELD_IPV6_UDP) cmd->data |= RXH_L4_B_0_1 | RXH_L4_B_2_3; fallthrough; case SCTP_V6_FLOW: case AH_ESP_V6_FLOW: case AH_V6_FLOW: case ESP_V6_FLOW: case IPV6_FLOW: cmd->data |= RXH_IP_SRC | RXH_IP_DST; break; default: return -EINVAL; } return 0; } static int igb_get_rxnfc(struct net_device *dev, struct ethtool_rxnfc *cmd, u32 *rule_locs) { struct igb_adapter *adapter = netdev_priv(dev); int ret = -EOPNOTSUPP; switch (cmd->cmd) { case ETHTOOL_GRXRINGS: cmd->data = adapter->num_rx_queues; ret = 0; break; case ETHTOOL_GRXCLSRLCNT: cmd->rule_cnt = adapter->nfc_filter_count; ret = 0; break; case ETHTOOL_GRXCLSRULE: ret = igb_get_ethtool_nfc_entry(adapter, cmd); break; case ETHTOOL_GRXCLSRLALL: ret = igb_get_ethtool_nfc_all(adapter, cmd, rule_locs); break; case ETHTOOL_GRXFH: ret = igb_get_rss_hash_opts(adapter, cmd); break; default: break; } return ret; } #define UDP_RSS_FLAGS (IGB_FLAG_RSS_FIELD_IPV4_UDP | \ IGB_FLAG_RSS_FIELD_IPV6_UDP) static int igb_set_rss_hash_opt(struct igb_adapter *adapter, struct ethtool_rxnfc *nfc) { u32 flags = adapter->flags; /* RSS does not support anything other than hashing * to queues on src and dst IPs and ports */ if (nfc->data & ~(RXH_IP_SRC | RXH_IP_DST | RXH_L4_B_0_1 | RXH_L4_B_2_3)) return -EINVAL; switch (nfc->flow_type) { case TCP_V4_FLOW: case TCP_V6_FLOW: if (!(nfc->data & RXH_IP_SRC) || !(nfc->data & RXH_IP_DST) || !(nfc->data & RXH_L4_B_0_1) || !(nfc->data & RXH_L4_B_2_3)) return -EINVAL; break; case UDP_V4_FLOW: if (!(nfc->data & RXH_IP_SRC) || !(nfc->data & RXH_IP_DST)) return -EINVAL; switch (nfc->data & (RXH_L4_B_0_1 | RXH_L4_B_2_3)) { case 0: flags &= ~IGB_FLAG_RSS_FIELD_IPV4_UDP; break; case (RXH_L4_B_0_1 | RXH_L4_B_2_3): flags |= IGB_FLAG_RSS_FIELD_IPV4_UDP; break; default: return -EINVAL; } break; case UDP_V6_FLOW: if (!(nfc->data & RXH_IP_SRC) || !(nfc->data & RXH_IP_DST)) return -EINVAL; switch (nfc->data & (RXH_L4_B_0_1 | RXH_L4_B_2_3)) { case 0: flags &= ~IGB_FLAG_RSS_FIELD_IPV6_UDP; break; case (RXH_L4_B_0_1 | RXH_L4_B_2_3): flags |= IGB_FLAG_RSS_FIELD_IPV6_UDP; break; default: return -EINVAL; } break; case AH_ESP_V4_FLOW: case AH_V4_FLOW: case ESP_V4_FLOW: case SCTP_V4_FLOW: case AH_ESP_V6_FLOW: case AH_V6_FLOW: case ESP_V6_FLOW: case SCTP_V6_FLOW: if (!(nfc->data & RXH_IP_SRC) || !(nfc->data & RXH_IP_DST) || (nfc->data & RXH_L4_B_0_1) || (nfc->data & RXH_L4_B_2_3)) return -EINVAL; break; default: return -EINVAL; } /* if we changed something we need to update flags */ if (flags != adapter->flags) { struct e1000_hw *hw = &adapter->hw; u32 mrqc = rd32(E1000_MRQC); if ((flags & UDP_RSS_FLAGS) && !(adapter->flags & UDP_RSS_FLAGS)) dev_err(&adapter->pdev->dev, "enabling UDP RSS: fragmented packets may arrive out of order to the stack above\n"); adapter->flags = flags; /* Perform hash on these packet types */ mrqc |= E1000_MRQC_RSS_FIELD_IPV4 | E1000_MRQC_RSS_FIELD_IPV4_TCP | E1000_MRQC_RSS_FIELD_IPV6 | E1000_MRQC_RSS_FIELD_IPV6_TCP; mrqc &= ~(E1000_MRQC_RSS_FIELD_IPV4_UDP | E1000_MRQC_RSS_FIELD_IPV6_UDP); if (flags & IGB_FLAG_RSS_FIELD_IPV4_UDP) mrqc |= E1000_MRQC_RSS_FIELD_IPV4_UDP; if (flags & IGB_FLAG_RSS_FIELD_IPV6_UDP) mrqc |= E1000_MRQC_RSS_FIELD_IPV6_UDP; wr32(E1000_MRQC, mrqc); } return 0; } static int igb_rxnfc_write_etype_filter(struct igb_adapter *adapter, struct igb_nfc_filter *input) { struct e1000_hw *hw = &adapter->hw; u8 i; u32 etqf; u16 etype; /* find an empty etype filter register */ for (i = 0; i < MAX_ETYPE_FILTER; ++i) { if (!adapter->etype_bitmap[i]) break; } if (i == MAX_ETYPE_FILTER) { dev_err(&adapter->pdev->dev, "ethtool -N: etype filters are all used.\n"); return -EINVAL; } adapter->etype_bitmap[i] = true; etqf = rd32(E1000_ETQF(i)); etype = ntohs(input->filter.etype & ETHER_TYPE_FULL_MASK); etqf |= E1000_ETQF_FILTER_ENABLE; etqf &= ~E1000_ETQF_ETYPE_MASK; etqf |= (etype & E1000_ETQF_ETYPE_MASK); etqf &= ~E1000_ETQF_QUEUE_MASK; etqf |= ((input->action << E1000_ETQF_QUEUE_SHIFT) & E1000_ETQF_QUEUE_MASK); etqf |= E1000_ETQF_QUEUE_ENABLE; wr32(E1000_ETQF(i), etqf); input->etype_reg_index = i; return 0; } static int igb_rxnfc_write_vlan_prio_filter(struct igb_adapter *adapter, struct igb_nfc_filter *input) { struct e1000_hw *hw = &adapter->hw; u8 vlan_priority; u16 queue_index; u32 vlapqf; vlapqf = rd32(E1000_VLAPQF); vlan_priority = (ntohs(input->filter.vlan_tci) & VLAN_PRIO_MASK) >> VLAN_PRIO_SHIFT; queue_index = (vlapqf >> (vlan_priority * 4)) & E1000_VLAPQF_QUEUE_MASK; /* check whether this vlan prio is already set */ if ((vlapqf & E1000_VLAPQF_P_VALID(vlan_priority)) && (queue_index != input->action)) { dev_err(&adapter->pdev->dev, "ethtool rxnfc set vlan prio filter failed.\n"); return -EEXIST; } vlapqf |= E1000_VLAPQF_P_VALID(vlan_priority); vlapqf |= E1000_VLAPQF_QUEUE_SEL(vlan_priority, input->action); wr32(E1000_VLAPQF, vlapqf); return 0; } int igb_add_filter(struct igb_adapter *adapter, struct igb_nfc_filter *input) { struct e1000_hw *hw = &adapter->hw; int err = -EINVAL; if (hw->mac.type == e1000_i210 && !(input->filter.match_flags & ~IGB_FILTER_FLAG_SRC_MAC_ADDR)) { dev_err(&adapter->pdev->dev, "i210 doesn't support flow classification rules specifying only source addresses.\n"); return -EOPNOTSUPP; } if (input->filter.match_flags & IGB_FILTER_FLAG_ETHER_TYPE) { err = igb_rxnfc_write_etype_filter(adapter, input); if (err) return err; } if (input->filter.match_flags & IGB_FILTER_FLAG_DST_MAC_ADDR) { err = igb_add_mac_steering_filter(adapter, input->filter.dst_addr, input->action, 0); err = min_t(int, err, 0); if (err) return err; } if (input->filter.match_flags & IGB_FILTER_FLAG_SRC_MAC_ADDR) { err = igb_add_mac_steering_filter(adapter, input->filter.src_addr, input->action, IGB_MAC_STATE_SRC_ADDR); err = min_t(int, err, 0); if (err) return err; } if (input->filter.match_flags & IGB_FILTER_FLAG_VLAN_TCI) err = igb_rxnfc_write_vlan_prio_filter(adapter, input); return err; } static void igb_clear_etype_filter_regs(struct igb_adapter *adapter, u16 reg_index) { struct e1000_hw *hw = &adapter->hw; u32 etqf = rd32(E1000_ETQF(reg_index)); etqf &= ~E1000_ETQF_QUEUE_ENABLE; etqf &= ~E1000_ETQF_QUEUE_MASK; etqf &= ~E1000_ETQF_FILTER_ENABLE; wr32(E1000_ETQF(reg_index), etqf); adapter->etype_bitmap[reg_index] = false; } static void igb_clear_vlan_prio_filter(struct igb_adapter *adapter, u16 vlan_tci) { struct e1000_hw *hw = &adapter->hw; u8 vlan_priority; u32 vlapqf; vlan_priority = (vlan_tci & VLAN_PRIO_MASK) >> VLAN_PRIO_SHIFT; vlapqf = rd32(E1000_VLAPQF); vlapqf &= ~E1000_VLAPQF_P_VALID(vlan_priority); vlapqf &= ~E1000_VLAPQF_QUEUE_SEL(vlan_priority, E1000_VLAPQF_QUEUE_MASK); wr32(E1000_VLAPQF, vlapqf); } int igb_erase_filter(struct igb_adapter *adapter, struct igb_nfc_filter *input) { if (input->filter.match_flags & IGB_FILTER_FLAG_ETHER_TYPE) igb_clear_etype_filter_regs(adapter, input->etype_reg_index); if (input->filter.match_flags & IGB_FILTER_FLAG_VLAN_TCI) igb_clear_vlan_prio_filter(adapter, ntohs(input->filter.vlan_tci)); if (input->filter.match_flags & IGB_FILTER_FLAG_SRC_MAC_ADDR) igb_del_mac_steering_filter(adapter, input->filter.src_addr, input->action, IGB_MAC_STATE_SRC_ADDR); if (input->filter.match_flags & IGB_FILTER_FLAG_DST_MAC_ADDR) igb_del_mac_steering_filter(adapter, input->filter.dst_addr, input->action, 0); return 0; } static int igb_update_ethtool_nfc_entry(struct igb_adapter *adapter, struct igb_nfc_filter *input, u16 sw_idx) { struct igb_nfc_filter *rule, *parent; int err = -EINVAL; parent = NULL; rule = NULL; hlist_for_each_entry(rule, &adapter->nfc_filter_list, nfc_node) { /* hash found, or no matching entry */ if (rule->sw_idx >= sw_idx) break; parent = rule; } /* if there is an old rule occupying our place remove it */ if (rule && (rule->sw_idx == sw_idx)) { if (!input) err = igb_erase_filter(adapter, rule); hlist_del(&rule->nfc_node); kfree(rule); adapter->nfc_filter_count--; } /* If no input this was a delete, err should be 0 if a rule was * successfully found and removed from the list else -EINVAL */ if (!input) return err; /* initialize node */ INIT_HLIST_NODE(&input->nfc_node); /* add filter to the list */ if (parent) hlist_add_behind(&input->nfc_node, &parent->nfc_node); else hlist_add_head(&input->nfc_node, &adapter->nfc_filter_list); /* update counts */ adapter->nfc_filter_count++; return 0; } static int igb_add_ethtool_nfc_entry(struct igb_adapter *adapter, struct ethtool_rxnfc *cmd) { struct net_device *netdev = adapter->netdev; struct ethtool_rx_flow_spec *fsp = (struct ethtool_rx_flow_spec *)&cmd->fs; struct igb_nfc_filter *input, *rule; int err = 0; if (!(netdev->hw_features & NETIF_F_NTUPLE)) return -EOPNOTSUPP; /* Don't allow programming if the action is a queue greater than * the number of online Rx queues. */ if ((fsp->ring_cookie == RX_CLS_FLOW_DISC) || (fsp->ring_cookie >= adapter->num_rx_queues)) { dev_err(&adapter->pdev->dev, "ethtool -N: The specified action is invalid\n"); return -EINVAL; } /* Don't allow indexes to exist outside of available space */ if (fsp->location >= IGB_MAX_RXNFC_FILTERS) { dev_err(&adapter->pdev->dev, "Location out of range\n"); return -EINVAL; } if ((fsp->flow_type & ~FLOW_EXT) != ETHER_FLOW) return -EINVAL; input = kzalloc(sizeof(*input), GFP_KERNEL); if (!input) return -ENOMEM; if (fsp->m_u.ether_spec.h_proto == ETHER_TYPE_FULL_MASK) { input->filter.etype = fsp->h_u.ether_spec.h_proto; input->filter.match_flags = IGB_FILTER_FLAG_ETHER_TYPE; } /* Only support matching addresses by the full mask */ if (is_broadcast_ether_addr(fsp->m_u.ether_spec.h_source)) { input->filter.match_flags |= IGB_FILTER_FLAG_SRC_MAC_ADDR; ether_addr_copy(input->filter.src_addr, fsp->h_u.ether_spec.h_source); } /* Only support matching addresses by the full mask */ if (is_broadcast_ether_addr(fsp->m_u.ether_spec.h_dest)) { input->filter.match_flags |= IGB_FILTER_FLAG_DST_MAC_ADDR; ether_addr_copy(input->filter.dst_addr, fsp->h_u.ether_spec.h_dest); } if ((fsp->flow_type & FLOW_EXT) && fsp->m_ext.vlan_tci) { if (fsp->m_ext.vlan_tci != htons(VLAN_PRIO_MASK)) { err = -EINVAL; goto err_out; } input->filter.vlan_tci = fsp->h_ext.vlan_tci; input->filter.match_flags |= IGB_FILTER_FLAG_VLAN_TCI; } input->action = fsp->ring_cookie; input->sw_idx = fsp->location; spin_lock(&adapter->nfc_lock); hlist_for_each_entry(rule, &adapter->nfc_filter_list, nfc_node) { if (!memcmp(&input->filter, &rule->filter, sizeof(input->filter))) { err = -EEXIST; dev_err(&adapter->pdev->dev, "ethtool: this filter is already set\n"); goto err_out_w_lock; } } err = igb_add_filter(adapter, input); if (err) goto err_out_w_lock; igb_update_ethtool_nfc_entry(adapter, input, input->sw_idx); spin_unlock(&adapter->nfc_lock); return 0; err_out_w_lock: spin_unlock(&adapter->nfc_lock); err_out: kfree(input); return err; } static int igb_del_ethtool_nfc_entry(struct igb_adapter *adapter, struct ethtool_rxnfc *cmd) { struct ethtool_rx_flow_spec *fsp = (struct ethtool_rx_flow_spec *)&cmd->fs; int err; spin_lock(&adapter->nfc_lock); err = igb_update_ethtool_nfc_entry(adapter, NULL, fsp->location); spin_unlock(&adapter->nfc_lock); return err; } static int igb_set_rxnfc(struct net_device *dev, struct ethtool_rxnfc *cmd) { struct igb_adapter *adapter = netdev_priv(dev); int ret = -EOPNOTSUPP; switch (cmd->cmd) { case ETHTOOL_SRXFH: ret = igb_set_rss_hash_opt(adapter, cmd); break; case ETHTOOL_SRXCLSRLINS: ret = igb_add_ethtool_nfc_entry(adapter, cmd); break; case ETHTOOL_SRXCLSRLDEL: ret = igb_del_ethtool_nfc_entry(adapter, cmd); break; default: break; } return ret; } static int igb_get_eee(struct net_device *netdev, struct ethtool_eee *edata) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u32 ret_val; u16 phy_data; if ((hw->mac.type < e1000_i350) || (hw->phy.media_type != e1000_media_type_copper)) return -EOPNOTSUPP; edata->supported = (SUPPORTED_1000baseT_Full | SUPPORTED_100baseT_Full); if (!hw->dev_spec._82575.eee_disable) edata->advertised = mmd_eee_adv_to_ethtool_adv_t(adapter->eee_advert); /* The IPCNFG and EEER registers are not supported on I354. */ if (hw->mac.type == e1000_i354) { igb_get_eee_status_i354(hw, (bool *)&edata->eee_active); } else { u32 eeer; eeer = rd32(E1000_EEER); /* EEE status on negotiated link */ if (eeer & E1000_EEER_EEE_NEG) edata->eee_active = true; if (eeer & E1000_EEER_TX_LPI_EN) edata->tx_lpi_enabled = true; } /* EEE Link Partner Advertised */ switch (hw->mac.type) { case e1000_i350: ret_val = igb_read_emi_reg(hw, E1000_EEE_LP_ADV_ADDR_I350, &phy_data); if (ret_val) return -ENODATA; edata->lp_advertised = mmd_eee_adv_to_ethtool_adv_t(phy_data); break; case e1000_i354: case e1000_i210: case e1000_i211: ret_val = igb_read_xmdio_reg(hw, E1000_EEE_LP_ADV_ADDR_I210, E1000_EEE_LP_ADV_DEV_I210, &phy_data); if (ret_val) return -ENODATA; edata->lp_advertised = mmd_eee_adv_to_ethtool_adv_t(phy_data); break; default: break; } edata->eee_enabled = !hw->dev_spec._82575.eee_disable; if ((hw->mac.type == e1000_i354) && (edata->eee_enabled)) edata->tx_lpi_enabled = true; /* Report correct negotiated EEE status for devices that * wrongly report EEE at half-duplex */ if (adapter->link_duplex == HALF_DUPLEX) { edata->eee_enabled = false; edata->eee_active = false; edata->tx_lpi_enabled = false; edata->advertised &= ~edata->advertised; } return 0; } static int igb_set_eee(struct net_device *netdev, struct ethtool_eee *edata) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; struct ethtool_eee eee_curr; bool adv1g_eee = true, adv100m_eee = true; s32 ret_val; if ((hw->mac.type < e1000_i350) || (hw->phy.media_type != e1000_media_type_copper)) return -EOPNOTSUPP; memset(&eee_curr, 0, sizeof(struct ethtool_eee)); ret_val = igb_get_eee(netdev, &eee_curr); if (ret_val) return ret_val; if (eee_curr.eee_enabled) { if (eee_curr.tx_lpi_enabled != edata->tx_lpi_enabled) { dev_err(&adapter->pdev->dev, "Setting EEE tx-lpi is not supported\n"); return -EINVAL; } /* Tx LPI timer is not implemented currently */ if (edata->tx_lpi_timer) { dev_err(&adapter->pdev->dev, "Setting EEE Tx LPI timer is not supported\n"); return -EINVAL; } if (!edata->advertised || (edata->advertised & ~(ADVERTISE_100_FULL | ADVERTISE_1000_FULL))) { dev_err(&adapter->pdev->dev, "EEE Advertisement supports only 100Tx and/or 100T full duplex\n"); return -EINVAL; } adv100m_eee = !!(edata->advertised & ADVERTISE_100_FULL); adv1g_eee = !!(edata->advertised & ADVERTISE_1000_FULL); } else if (!edata->eee_enabled) { dev_err(&adapter->pdev->dev, "Setting EEE options are not supported with EEE disabled\n"); return -EINVAL; } adapter->eee_advert = ethtool_adv_to_mmd_eee_adv_t(edata->advertised); if (hw->dev_spec._82575.eee_disable != !edata->eee_enabled) { hw->dev_spec._82575.eee_disable = !edata->eee_enabled; adapter->flags |= IGB_FLAG_EEE; /* reset link */ if (netif_running(netdev)) igb_reinit_locked(adapter); else igb_reset(adapter); } if (hw->mac.type == e1000_i354) ret_val = igb_set_eee_i354(hw, adv1g_eee, adv100m_eee); else ret_val = igb_set_eee_i350(hw, adv1g_eee, adv100m_eee); if (ret_val) { dev_err(&adapter->pdev->dev, "Problem setting EEE advertisement options\n"); return -EINVAL; } return 0; } static int igb_get_module_info(struct net_device *netdev, struct ethtool_modinfo *modinfo) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u32 status = 0; u16 sff8472_rev, addr_mode; bool page_swap = false; if ((hw->phy.media_type == e1000_media_type_copper) || (hw->phy.media_type == e1000_media_type_unknown)) return -EOPNOTSUPP; /* Check whether we support SFF-8472 or not */ status = igb_read_phy_reg_i2c(hw, IGB_SFF_8472_COMP, &sff8472_rev); if (status) return -EIO; /* addressing mode is not supported */ status = igb_read_phy_reg_i2c(hw, IGB_SFF_8472_SWAP, &addr_mode); if (status) return -EIO; /* addressing mode is not supported */ if ((addr_mode & 0xFF) & IGB_SFF_ADDRESSING_MODE) { hw_dbg("Address change required to access page 0xA2, but not supported. Please report the module type to the driver maintainers.\n"); page_swap = true; } if ((sff8472_rev & 0xFF) == IGB_SFF_8472_UNSUP || page_swap) { /* We have an SFP, but it does not support SFF-8472 */ modinfo->type = ETH_MODULE_SFF_8079; modinfo->eeprom_len = ETH_MODULE_SFF_8079_LEN; } else { /* We have an SFP which supports a revision of SFF-8472 */ modinfo->type = ETH_MODULE_SFF_8472; modinfo->eeprom_len = ETH_MODULE_SFF_8472_LEN; } return 0; } static int igb_get_module_eeprom(struct net_device *netdev, struct ethtool_eeprom *ee, u8 *data) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u32 status = 0; u16 *dataword; u16 first_word, last_word; int i = 0; if (ee->len == 0) return -EINVAL; first_word = ee->offset >> 1; last_word = (ee->offset + ee->len - 1) >> 1; dataword = kmalloc_array(last_word - first_word + 1, sizeof(u16), GFP_KERNEL); if (!dataword) return -ENOMEM; /* Read EEPROM block, SFF-8079/SFF-8472, word at a time */ for (i = 0; i < last_word - first_word + 1; i++) { status = igb_read_phy_reg_i2c(hw, (first_word + i) * 2, &dataword[i]); if (status) { /* Error occurred while reading module */ kfree(dataword); return -EIO; } be16_to_cpus(&dataword[i]); } memcpy(data, (u8 *)dataword + (ee->offset & 1), ee->len); kfree(dataword); return 0; } static int igb_ethtool_begin(struct net_device *netdev) { struct igb_adapter *adapter = netdev_priv(netdev); pm_runtime_get_sync(&adapter->pdev->dev); return 0; } static void igb_ethtool_complete(struct net_device *netdev) { struct igb_adapter *adapter = netdev_priv(netdev); pm_runtime_put(&adapter->pdev->dev); } static u32 igb_get_rxfh_indir_size(struct net_device *netdev) { return IGB_RETA_SIZE; } static int igb_get_rxfh(struct net_device *netdev, u32 *indir, u8 *key, u8 *hfunc) { struct igb_adapter *adapter = netdev_priv(netdev); int i; if (hfunc) *hfunc = ETH_RSS_HASH_TOP; if (!indir) return 0; for (i = 0; i < IGB_RETA_SIZE; i++) indir[i] = adapter->rss_indir_tbl[i]; return 0; } void igb_write_rss_indir_tbl(struct igb_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 reg = E1000_RETA(0); u32 shift = 0; int i = 0; switch (hw->mac.type) { case e1000_82575: shift = 6; break; case e1000_82576: /* 82576 supports 2 RSS queues for SR-IOV */ if (adapter->vfs_allocated_count) shift = 3; break; default: break; } while (i < IGB_RETA_SIZE) { u32 val = 0; int j; for (j = 3; j >= 0; j--) { val <<= 8; val |= adapter->rss_indir_tbl[i + j]; } wr32(reg, val << shift); reg += 4; i += 4; } } static int igb_set_rxfh(struct net_device *netdev, const u32 *indir, const u8 *key, const u8 hfunc) { struct igb_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; int i; u32 num_queues; /* We do not allow change in unsupported parameters */ if (key || (hfunc != ETH_RSS_HASH_NO_CHANGE && hfunc != ETH_RSS_HASH_TOP)) return -EOPNOTSUPP; if (!indir) return 0; num_queues = adapter->rss_queues; switch (hw->mac.type) { case e1000_82576: /* 82576 supports 2 RSS queues for SR-IOV */ if (adapter->vfs_allocated_count) num_queues = 2; break; default: break; } /* Verify user input. */ for (i = 0; i < IGB_RETA_SIZE; i++) if (indir[i] >= num_queues) return -EINVAL; for (i = 0; i < IGB_RETA_SIZE; i++) adapter->rss_indir_tbl[i] = indir[i]; igb_write_rss_indir_tbl(adapter); return 0; } static unsigned int igb_max_channels(struct igb_adapter *adapter) { return igb_get_max_rss_queues(adapter); } static void igb_get_channels(struct net_device *netdev, struct ethtool_channels *ch) { struct igb_adapter *adapter = netdev_priv(netdev); /* Report maximum channels */ ch->max_combined = igb_max_channels(adapter); /* Report info for other vector */ if (adapter->flags & IGB_FLAG_HAS_MSIX) { ch->max_other = NON_Q_VECTORS; ch->other_count = NON_Q_VECTORS; } ch->combined_count = adapter->rss_queues; } static int igb_set_channels(struct net_device *netdev, struct ethtool_channels *ch) { struct igb_adapter *adapter = netdev_priv(netdev); unsigned int count = ch->combined_count; unsigned int max_combined = 0; /* Verify they are not requesting separate vectors */ if (!count || ch->rx_count || ch->tx_count) return -EINVAL; /* Verify other_count is valid and has not been changed */ if (ch->other_count != NON_Q_VECTORS) return -EINVAL; /* Verify the number of channels doesn't exceed hw limits */ max_combined = igb_max_channels(adapter); if (count > max_combined) return -EINVAL; if (count != adapter->rss_queues) { adapter->rss_queues = count; igb_set_flag_queue_pairs(adapter, max_combined); /* Hardware has to reinitialize queues and interrupts to * match the new configuration. */ return igb_reinit_queues(adapter); } return 0; } static u32 igb_get_priv_flags(struct net_device *netdev) { struct igb_adapter *adapter = netdev_priv(netdev); u32 priv_flags = 0; if (adapter->flags & IGB_FLAG_RX_LEGACY) priv_flags |= IGB_PRIV_FLAGS_LEGACY_RX; return priv_flags; } static int igb_set_priv_flags(struct net_device *netdev, u32 priv_flags) { struct igb_adapter *adapter = netdev_priv(netdev); unsigned int flags = adapter->flags; flags &= ~IGB_FLAG_RX_LEGACY; if (priv_flags & IGB_PRIV_FLAGS_LEGACY_RX) flags |= IGB_FLAG_RX_LEGACY; if (flags != adapter->flags) { adapter->flags = flags; /* reset interface to repopulate queues */ if (netif_running(netdev)) igb_reinit_locked(adapter); } return 0; } static const struct ethtool_ops igb_ethtool_ops = { .supported_coalesce_params = ETHTOOL_COALESCE_USECS, .get_drvinfo = igb_get_drvinfo, .get_regs_len = igb_get_regs_len, .get_regs = igb_get_regs, .get_wol = igb_get_wol, .set_wol = igb_set_wol, .get_msglevel = igb_get_msglevel, .set_msglevel = igb_set_msglevel, .nway_reset = igb_nway_reset, .get_link = igb_get_link, .get_eeprom_len = igb_get_eeprom_len, .get_eeprom = igb_get_eeprom, .set_eeprom = igb_set_eeprom, .get_ringparam = igb_get_ringparam, .set_ringparam = igb_set_ringparam, .get_pauseparam = igb_get_pauseparam, .set_pauseparam = igb_set_pauseparam, .self_test = igb_diag_test, .get_strings = igb_get_strings, .set_phys_id = igb_set_phys_id, .get_sset_count = igb_get_sset_count, .get_ethtool_stats = igb_get_ethtool_stats, .get_coalesce = igb_get_coalesce, .set_coalesce = igb_set_coalesce, .get_ts_info = igb_get_ts_info, .get_rxnfc = igb_get_rxnfc, .set_rxnfc = igb_set_rxnfc, .get_eee = igb_get_eee, .set_eee = igb_set_eee, .get_module_info = igb_get_module_info, .get_module_eeprom = igb_get_module_eeprom, .get_rxfh_indir_size = igb_get_rxfh_indir_size, .get_rxfh = igb_get_rxfh, .set_rxfh = igb_set_rxfh, .get_channels = igb_get_channels, .set_channels = igb_set_channels, .get_priv_flags = igb_get_priv_flags, .set_priv_flags = igb_set_priv_flags, .begin = igb_ethtool_begin, .complete = igb_ethtool_complete, .get_link_ksettings = igb_get_link_ksettings, .set_link_ksettings = igb_set_link_ksettings, }; void igb_set_ethtool_ops(struct net_device *netdev) { netdev->ethtool_ops = &igb_ethtool_ops; }
linux-master
drivers/net/ethernet/intel/igb/igb_ethtool.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2013 - 2018 Intel Corporation. */ #include "fm10k_common.h" /** * fm10k_get_bus_info_generic - Generic set PCI bus info * @hw: pointer to hardware structure * * Gets the PCI bus info (speed, width, type) then calls helper function to * store this data within the fm10k_hw structure. **/ s32 fm10k_get_bus_info_generic(struct fm10k_hw *hw) { u16 link_cap, link_status, device_cap, device_control; /* Get the maximum link width and speed from PCIe config space */ link_cap = fm10k_read_pci_cfg_word(hw, FM10K_PCIE_LINK_CAP); switch (link_cap & FM10K_PCIE_LINK_WIDTH) { case FM10K_PCIE_LINK_WIDTH_1: hw->bus_caps.width = fm10k_bus_width_pcie_x1; break; case FM10K_PCIE_LINK_WIDTH_2: hw->bus_caps.width = fm10k_bus_width_pcie_x2; break; case FM10K_PCIE_LINK_WIDTH_4: hw->bus_caps.width = fm10k_bus_width_pcie_x4; break; case FM10K_PCIE_LINK_WIDTH_8: hw->bus_caps.width = fm10k_bus_width_pcie_x8; break; default: hw->bus_caps.width = fm10k_bus_width_unknown; break; } switch (link_cap & FM10K_PCIE_LINK_SPEED) { case FM10K_PCIE_LINK_SPEED_2500: hw->bus_caps.speed = fm10k_bus_speed_2500; break; case FM10K_PCIE_LINK_SPEED_5000: hw->bus_caps.speed = fm10k_bus_speed_5000; break; case FM10K_PCIE_LINK_SPEED_8000: hw->bus_caps.speed = fm10k_bus_speed_8000; break; default: hw->bus_caps.speed = fm10k_bus_speed_unknown; break; } /* Get the PCIe maximum payload size for the PCIe function */ device_cap = fm10k_read_pci_cfg_word(hw, FM10K_PCIE_DEV_CAP); switch (device_cap & FM10K_PCIE_DEV_CAP_PAYLOAD) { case FM10K_PCIE_DEV_CAP_PAYLOAD_128: hw->bus_caps.payload = fm10k_bus_payload_128; break; case FM10K_PCIE_DEV_CAP_PAYLOAD_256: hw->bus_caps.payload = fm10k_bus_payload_256; break; case FM10K_PCIE_DEV_CAP_PAYLOAD_512: hw->bus_caps.payload = fm10k_bus_payload_512; break; default: hw->bus_caps.payload = fm10k_bus_payload_unknown; break; } /* Get the negotiated link width and speed from PCIe config space */ link_status = fm10k_read_pci_cfg_word(hw, FM10K_PCIE_LINK_STATUS); switch (link_status & FM10K_PCIE_LINK_WIDTH) { case FM10K_PCIE_LINK_WIDTH_1: hw->bus.width = fm10k_bus_width_pcie_x1; break; case FM10K_PCIE_LINK_WIDTH_2: hw->bus.width = fm10k_bus_width_pcie_x2; break; case FM10K_PCIE_LINK_WIDTH_4: hw->bus.width = fm10k_bus_width_pcie_x4; break; case FM10K_PCIE_LINK_WIDTH_8: hw->bus.width = fm10k_bus_width_pcie_x8; break; default: hw->bus.width = fm10k_bus_width_unknown; break; } switch (link_status & FM10K_PCIE_LINK_SPEED) { case FM10K_PCIE_LINK_SPEED_2500: hw->bus.speed = fm10k_bus_speed_2500; break; case FM10K_PCIE_LINK_SPEED_5000: hw->bus.speed = fm10k_bus_speed_5000; break; case FM10K_PCIE_LINK_SPEED_8000: hw->bus.speed = fm10k_bus_speed_8000; break; default: hw->bus.speed = fm10k_bus_speed_unknown; break; } /* Get the negotiated PCIe maximum payload size for the PCIe function */ device_control = fm10k_read_pci_cfg_word(hw, FM10K_PCIE_DEV_CTRL); switch (device_control & FM10K_PCIE_DEV_CTRL_PAYLOAD) { case FM10K_PCIE_DEV_CTRL_PAYLOAD_128: hw->bus.payload = fm10k_bus_payload_128; break; case FM10K_PCIE_DEV_CTRL_PAYLOAD_256: hw->bus.payload = fm10k_bus_payload_256; break; case FM10K_PCIE_DEV_CTRL_PAYLOAD_512: hw->bus.payload = fm10k_bus_payload_512; break; default: hw->bus.payload = fm10k_bus_payload_unknown; break; } return 0; } static u16 fm10k_get_pcie_msix_count_generic(struct fm10k_hw *hw) { u16 msix_count; /* read in value from MSI-X capability register */ msix_count = fm10k_read_pci_cfg_word(hw, FM10K_PCI_MSIX_MSG_CTRL); msix_count &= FM10K_PCI_MSIX_MSG_CTRL_TBL_SZ_MASK; /* MSI-X count is zero-based in HW */ msix_count++; if (msix_count > FM10K_MAX_MSIX_VECTORS) msix_count = FM10K_MAX_MSIX_VECTORS; return msix_count; } /** * fm10k_get_invariants_generic - Inits constant values * @hw: pointer to the hardware structure * * Initialize the common invariants for the device. **/ s32 fm10k_get_invariants_generic(struct fm10k_hw *hw) { struct fm10k_mac_info *mac = &hw->mac; /* initialize GLORT state to avoid any false hits */ mac->dglort_map = FM10K_DGLORTMAP_NONE; /* record maximum number of MSI-X vectors */ mac->max_msix_vectors = fm10k_get_pcie_msix_count_generic(hw); return 0; } /** * fm10k_start_hw_generic - Prepare hardware for Tx/Rx * @hw: pointer to hardware structure * * This function sets the Tx ready flag to indicate that the Tx path has * been initialized. **/ s32 fm10k_start_hw_generic(struct fm10k_hw *hw) { /* set flag indicating we are beginning Tx */ hw->mac.tx_ready = true; return 0; } /** * fm10k_disable_queues_generic - Stop Tx/Rx queues * @hw: pointer to hardware structure * @q_cnt: number of queues to be disabled * **/ s32 fm10k_disable_queues_generic(struct fm10k_hw *hw, u16 q_cnt) { u32 reg; u16 i, time; /* clear tx_ready to prevent any false hits for reset */ hw->mac.tx_ready = false; if (FM10K_REMOVED(hw->hw_addr)) return 0; /* clear the enable bit for all rings */ for (i = 0; i < q_cnt; i++) { reg = fm10k_read_reg(hw, FM10K_TXDCTL(i)); fm10k_write_reg(hw, FM10K_TXDCTL(i), reg & ~FM10K_TXDCTL_ENABLE); reg = fm10k_read_reg(hw, FM10K_RXQCTL(i)); fm10k_write_reg(hw, FM10K_RXQCTL(i), reg & ~FM10K_RXQCTL_ENABLE); } fm10k_write_flush(hw); udelay(1); /* loop through all queues to verify that they are all disabled */ for (i = 0, time = FM10K_QUEUE_DISABLE_TIMEOUT; time;) { /* if we are at end of rings all rings are disabled */ if (i == q_cnt) return 0; /* if queue enables cleared, then move to next ring pair */ reg = fm10k_read_reg(hw, FM10K_TXDCTL(i)); if (!~reg || !(reg & FM10K_TXDCTL_ENABLE)) { reg = fm10k_read_reg(hw, FM10K_RXQCTL(i)); if (!~reg || !(reg & FM10K_RXQCTL_ENABLE)) { i++; continue; } } /* decrement time and wait 1 usec */ time--; if (time) udelay(1); } return FM10K_ERR_REQUESTS_PENDING; } /** * fm10k_stop_hw_generic - Stop Tx/Rx units * @hw: pointer to hardware structure * **/ s32 fm10k_stop_hw_generic(struct fm10k_hw *hw) { return fm10k_disable_queues_generic(hw, hw->mac.max_queues); } /** * fm10k_read_hw_stats_32b - Reads value of 32-bit registers * @hw: pointer to the hardware structure * @addr: address of register containing a 32-bit value * @stat: pointer to structure holding hw stat information * * Function reads the content of the register and returns the delta * between the base and the current value. * **/ u32 fm10k_read_hw_stats_32b(struct fm10k_hw *hw, u32 addr, struct fm10k_hw_stat *stat) { u32 delta = fm10k_read_reg(hw, addr) - stat->base_l; if (FM10K_REMOVED(hw->hw_addr)) stat->base_h = 0; return delta; } /** * fm10k_read_hw_stats_48b - Reads value of 48-bit registers * @hw: pointer to the hardware structure * @addr: address of register containing the lower 32-bit value * @stat: pointer to structure holding hw stat information * * Function reads the content of 2 registers, combined to represent a 48-bit * statistical value. Extra processing is required to handle overflowing. * Finally, a delta value is returned representing the difference between the * values stored in registers and values stored in the statistic counters. * **/ static u64 fm10k_read_hw_stats_48b(struct fm10k_hw *hw, u32 addr, struct fm10k_hw_stat *stat) { u32 count_l; u32 count_h; u32 count_tmp; u64 delta; count_h = fm10k_read_reg(hw, addr + 1); /* Check for overflow */ do { count_tmp = count_h; count_l = fm10k_read_reg(hw, addr); count_h = fm10k_read_reg(hw, addr + 1); } while (count_h != count_tmp); delta = ((u64)(count_h - stat->base_h) << 32) + count_l; delta -= stat->base_l; return delta & FM10K_48_BIT_MASK; } /** * fm10k_update_hw_base_48b - Updates 48-bit statistic base value * @stat: pointer to the hardware statistic structure * @delta: value to be updated into the hardware statistic structure * * Function receives a value and determines if an update is required based on * a delta calculation. Only the base value will be updated. **/ static void fm10k_update_hw_base_48b(struct fm10k_hw_stat *stat, u64 delta) { if (!delta) return; /* update lower 32 bits */ delta += stat->base_l; stat->base_l = (u32)delta; /* update upper 32 bits */ stat->base_h += (u32)(delta >> 32); } /** * fm10k_update_hw_stats_tx_q - Updates TX queue statistics counters * @hw: pointer to the hardware structure * @q: pointer to the ring of hardware statistics queue * @idx: index pointing to the start of the ring iteration * * Function updates the TX queue statistics counters that are related to the * hardware. **/ static void fm10k_update_hw_stats_tx_q(struct fm10k_hw *hw, struct fm10k_hw_stats_q *q, u32 idx) { u32 id_tx, id_tx_prev, tx_packets; u64 tx_bytes = 0; /* Retrieve TX Owner Data */ id_tx = fm10k_read_reg(hw, FM10K_TXQCTL(idx)); /* Process TX Ring */ do { tx_packets = fm10k_read_hw_stats_32b(hw, FM10K_QPTC(idx), &q->tx_packets); if (tx_packets) tx_bytes = fm10k_read_hw_stats_48b(hw, FM10K_QBTC_L(idx), &q->tx_bytes); /* Re-Check Owner Data */ id_tx_prev = id_tx; id_tx = fm10k_read_reg(hw, FM10K_TXQCTL(idx)); } while ((id_tx ^ id_tx_prev) & FM10K_TXQCTL_ID_MASK); /* drop non-ID bits and set VALID ID bit */ id_tx &= FM10K_TXQCTL_ID_MASK; id_tx |= FM10K_STAT_VALID; /* update packet counts */ if (q->tx_stats_idx == id_tx) { q->tx_packets.count += tx_packets; q->tx_bytes.count += tx_bytes; } /* update bases and record ID */ fm10k_update_hw_base_32b(&q->tx_packets, tx_packets); fm10k_update_hw_base_48b(&q->tx_bytes, tx_bytes); q->tx_stats_idx = id_tx; } /** * fm10k_update_hw_stats_rx_q - Updates RX queue statistics counters * @hw: pointer to the hardware structure * @q: pointer to the ring of hardware statistics queue * @idx: index pointing to the start of the ring iteration * * Function updates the RX queue statistics counters that are related to the * hardware. **/ static void fm10k_update_hw_stats_rx_q(struct fm10k_hw *hw, struct fm10k_hw_stats_q *q, u32 idx) { u32 id_rx, id_rx_prev, rx_packets, rx_drops; u64 rx_bytes = 0; /* Retrieve RX Owner Data */ id_rx = fm10k_read_reg(hw, FM10K_RXQCTL(idx)); /* Process RX Ring */ do { rx_drops = fm10k_read_hw_stats_32b(hw, FM10K_QPRDC(idx), &q->rx_drops); rx_packets = fm10k_read_hw_stats_32b(hw, FM10K_QPRC(idx), &q->rx_packets); if (rx_packets) rx_bytes = fm10k_read_hw_stats_48b(hw, FM10K_QBRC_L(idx), &q->rx_bytes); /* Re-Check Owner Data */ id_rx_prev = id_rx; id_rx = fm10k_read_reg(hw, FM10K_RXQCTL(idx)); } while ((id_rx ^ id_rx_prev) & FM10K_RXQCTL_ID_MASK); /* drop non-ID bits and set VALID ID bit */ id_rx &= FM10K_RXQCTL_ID_MASK; id_rx |= FM10K_STAT_VALID; /* update packet counts */ if (q->rx_stats_idx == id_rx) { q->rx_drops.count += rx_drops; q->rx_packets.count += rx_packets; q->rx_bytes.count += rx_bytes; } /* update bases and record ID */ fm10k_update_hw_base_32b(&q->rx_drops, rx_drops); fm10k_update_hw_base_32b(&q->rx_packets, rx_packets); fm10k_update_hw_base_48b(&q->rx_bytes, rx_bytes); q->rx_stats_idx = id_rx; } /** * fm10k_update_hw_stats_q - Updates queue statistics counters * @hw: pointer to the hardware structure * @q: pointer to the ring of hardware statistics queue * @idx: index pointing to the start of the ring iteration * @count: number of queues to iterate over * * Function updates the queue statistics counters that are related to the * hardware. **/ void fm10k_update_hw_stats_q(struct fm10k_hw *hw, struct fm10k_hw_stats_q *q, u32 idx, u32 count) { u32 i; for (i = 0; i < count; i++, idx++, q++) { fm10k_update_hw_stats_tx_q(hw, q, idx); fm10k_update_hw_stats_rx_q(hw, q, idx); } } /** * fm10k_unbind_hw_stats_q - Unbind the queue counters from their queues * @q: pointer to the ring of hardware statistics queue * @idx: index pointing to the start of the ring iteration * @count: number of queues to iterate over * * Function invalidates the index values for the queues so any updates that * may have happened are ignored and the base for the queue stats is reset. **/ void fm10k_unbind_hw_stats_q(struct fm10k_hw_stats_q *q, u32 idx, u32 count) { u32 i; for (i = 0; i < count; i++, idx++, q++) { q->rx_stats_idx = 0; q->tx_stats_idx = 0; } } /** * fm10k_get_host_state_generic - Returns the state of the host * @hw: pointer to hardware structure * @host_ready: pointer to boolean value that will record host state * * This function will check the health of the mailbox and Tx queue 0 * in order to determine if we should report that the link is up or not. **/ s32 fm10k_get_host_state_generic(struct fm10k_hw *hw, bool *host_ready) { struct fm10k_mbx_info *mbx = &hw->mbx; struct fm10k_mac_info *mac = &hw->mac; s32 ret_val = 0; u32 txdctl = fm10k_read_reg(hw, FM10K_TXDCTL(0)); /* process upstream mailbox in case interrupts were disabled */ mbx->ops.process(hw, mbx); /* If Tx is no longer enabled link should come down */ if (!(~txdctl) || !(txdctl & FM10K_TXDCTL_ENABLE)) mac->get_host_state = true; /* exit if not checking for link, or link cannot be changed */ if (!mac->get_host_state || !(~txdctl)) goto out; /* if we somehow dropped the Tx enable we should reset */ if (mac->tx_ready && !(txdctl & FM10K_TXDCTL_ENABLE)) { ret_val = FM10K_ERR_RESET_REQUESTED; goto out; } /* if Mailbox timed out we should request reset */ if (!mbx->timeout) { ret_val = FM10K_ERR_RESET_REQUESTED; goto out; } /* verify Mailbox is still open */ if (mbx->state != FM10K_STATE_OPEN) goto out; /* interface cannot receive traffic without logical ports */ if (mac->dglort_map == FM10K_DGLORTMAP_NONE) { if (mac->ops.request_lport_map) ret_val = mac->ops.request_lport_map(hw); goto out; } /* if we passed all the tests above then the switch is ready and we no * longer need to check for link */ mac->get_host_state = false; out: *host_ready = !mac->get_host_state; return ret_val; }
linux-master
drivers/net/ethernet/intel/fm10k/fm10k_common.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2013 - 2018 Intel Corporation. */ #include "fm10k.h" #include <linux/debugfs.h> #include <linux/seq_file.h> static struct dentry *dbg_root; /* Descriptor Seq Functions */ static void *fm10k_dbg_desc_seq_start(struct seq_file *s, loff_t *pos) { struct fm10k_ring *ring = s->private; return (*pos < ring->count) ? pos : NULL; } static void *fm10k_dbg_desc_seq_next(struct seq_file *s, void __always_unused *v, loff_t *pos) { struct fm10k_ring *ring = s->private; return (++(*pos) < ring->count) ? pos : NULL; } static void fm10k_dbg_desc_seq_stop(struct seq_file __always_unused *s, void __always_unused *v) { /* Do nothing. */ } static void fm10k_dbg_desc_break(struct seq_file *s, int i) { while (i--) seq_putc(s, '-'); seq_putc(s, '\n'); } static int fm10k_dbg_tx_desc_seq_show(struct seq_file *s, void *v) { struct fm10k_ring *ring = s->private; int i = *(loff_t *)v; static const char tx_desc_hdr[] = "DES BUFFER_ADDRESS LENGTH VLAN MSS HDRLEN FLAGS\n"; /* Generate header */ if (!i) { seq_printf(s, tx_desc_hdr); fm10k_dbg_desc_break(s, sizeof(tx_desc_hdr) - 1); } /* Validate descriptor allocation */ if (!ring->desc) { seq_printf(s, "%03X Descriptor ring not allocated.\n", i); } else { struct fm10k_tx_desc *txd = FM10K_TX_DESC(ring, i); seq_printf(s, "%03X %#018llx %#06x %#06x %#06x %#06x %#04x\n", i, txd->buffer_addr, txd->buflen, txd->vlan, txd->mss, txd->hdrlen, txd->flags); } return 0; } static int fm10k_dbg_rx_desc_seq_show(struct seq_file *s, void *v) { struct fm10k_ring *ring = s->private; int i = *(loff_t *)v; static const char rx_desc_hdr[] = "DES DATA RSS STATERR LENGTH VLAN DGLORT SGLORT TIMESTAMP\n"; /* Generate header */ if (!i) { seq_printf(s, rx_desc_hdr); fm10k_dbg_desc_break(s, sizeof(rx_desc_hdr) - 1); } /* Validate descriptor allocation */ if (!ring->desc) { seq_printf(s, "%03X Descriptor ring not allocated.\n", i); } else { union fm10k_rx_desc *rxd = FM10K_RX_DESC(ring, i); seq_printf(s, "%03X %#010x %#010x %#010x %#06x %#06x %#06x %#06x %#018llx\n", i, rxd->d.data, rxd->d.rss, rxd->d.staterr, rxd->w.length, rxd->w.vlan, rxd->w.dglort, rxd->w.sglort, rxd->q.timestamp); } return 0; } static const struct seq_operations fm10k_dbg_tx_desc_seq_ops = { .start = fm10k_dbg_desc_seq_start, .next = fm10k_dbg_desc_seq_next, .stop = fm10k_dbg_desc_seq_stop, .show = fm10k_dbg_tx_desc_seq_show, }; static const struct seq_operations fm10k_dbg_rx_desc_seq_ops = { .start = fm10k_dbg_desc_seq_start, .next = fm10k_dbg_desc_seq_next, .stop = fm10k_dbg_desc_seq_stop, .show = fm10k_dbg_rx_desc_seq_show, }; static int fm10k_dbg_desc_open(struct inode *inode, struct file *filep) { struct fm10k_ring *ring = inode->i_private; struct fm10k_q_vector *q_vector = ring->q_vector; const struct seq_operations *desc_seq_ops; int err; if (ring < q_vector->rx.ring) desc_seq_ops = &fm10k_dbg_tx_desc_seq_ops; else desc_seq_ops = &fm10k_dbg_rx_desc_seq_ops; err = seq_open(filep, desc_seq_ops); if (err) return err; ((struct seq_file *)filep->private_data)->private = ring; return 0; } static const struct file_operations fm10k_dbg_desc_fops = { .owner = THIS_MODULE, .open = fm10k_dbg_desc_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; /** * fm10k_dbg_q_vector_init - setup debugfs for the q_vectors * @q_vector: q_vector to allocate directories for * * A folder is created for each q_vector found. In each q_vector * folder, a debugfs file is created for each tx and rx ring * allocated to the q_vector. **/ void fm10k_dbg_q_vector_init(struct fm10k_q_vector *q_vector) { struct fm10k_intfc *interface = q_vector->interface; char name[16]; int i; if (!interface->dbg_intfc) return; /* Generate a folder for each q_vector */ snprintf(name, sizeof(name), "q_vector.%03d", q_vector->v_idx); q_vector->dbg_q_vector = debugfs_create_dir(name, interface->dbg_intfc); /* Generate a file for each rx ring in the q_vector */ for (i = 0; i < q_vector->tx.count; i++) { struct fm10k_ring *ring = &q_vector->tx.ring[i]; snprintf(name, sizeof(name), "tx_ring.%03d", ring->queue_index); debugfs_create_file(name, 0600, q_vector->dbg_q_vector, ring, &fm10k_dbg_desc_fops); } /* Generate a file for each rx ring in the q_vector */ for (i = 0; i < q_vector->rx.count; i++) { struct fm10k_ring *ring = &q_vector->rx.ring[i]; snprintf(name, sizeof(name), "rx_ring.%03d", ring->queue_index); debugfs_create_file(name, 0600, q_vector->dbg_q_vector, ring, &fm10k_dbg_desc_fops); } } /** * fm10k_dbg_q_vector_exit - setup debugfs for the q_vectors * @q_vector: q_vector to allocate directories for **/ void fm10k_dbg_q_vector_exit(struct fm10k_q_vector *q_vector) { struct fm10k_intfc *interface = q_vector->interface; if (interface->dbg_intfc) debugfs_remove_recursive(q_vector->dbg_q_vector); q_vector->dbg_q_vector = NULL; } /** * fm10k_dbg_intfc_init - setup the debugfs directory for the intferface * @interface: the interface that is starting up **/ void fm10k_dbg_intfc_init(struct fm10k_intfc *interface) { const char *name = pci_name(interface->pdev); if (dbg_root) interface->dbg_intfc = debugfs_create_dir(name, dbg_root); } /** * fm10k_dbg_intfc_exit - clean out the interface's debugfs entries * @interface: the interface that is stopping **/ void fm10k_dbg_intfc_exit(struct fm10k_intfc *interface) { if (dbg_root) debugfs_remove_recursive(interface->dbg_intfc); interface->dbg_intfc = NULL; } /** * fm10k_dbg_init - start up debugfs for the driver **/ void fm10k_dbg_init(void) { dbg_root = debugfs_create_dir(fm10k_driver_name, NULL); } /** * fm10k_dbg_exit - clean out the driver's debugfs entries **/ void fm10k_dbg_exit(void) { debugfs_remove_recursive(dbg_root); dbg_root = NULL; }
linux-master
drivers/net/ethernet/intel/fm10k/fm10k_debugfs.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2013 - 2019 Intel Corporation. */ #include <linux/ethtool.h> #include <linux/vmalloc.h> #include "fm10k.h" struct fm10k_stats { /* The stat_string is expected to be a format string formatted using * vsnprintf by fm10k_add_stat_strings. Every member of a stats array * should use the same format specifiers as they will be formatted * using the same variadic arguments. */ char stat_string[ETH_GSTRING_LEN]; int sizeof_stat; int stat_offset; }; #define FM10K_STAT_FIELDS(_type, _name, _stat) { \ .stat_string = _name, \ .sizeof_stat = sizeof_field(_type, _stat), \ .stat_offset = offsetof(_type, _stat) \ } /* netdevice statistics */ #define FM10K_NETDEV_STAT(_net_stat) \ FM10K_STAT_FIELDS(struct net_device_stats, __stringify(_net_stat), \ _net_stat) static const struct fm10k_stats fm10k_gstrings_net_stats[] = { FM10K_NETDEV_STAT(tx_packets), FM10K_NETDEV_STAT(tx_bytes), FM10K_NETDEV_STAT(tx_errors), FM10K_NETDEV_STAT(rx_packets), FM10K_NETDEV_STAT(rx_bytes), FM10K_NETDEV_STAT(rx_errors), FM10K_NETDEV_STAT(rx_dropped), /* detailed Rx errors */ FM10K_NETDEV_STAT(rx_length_errors), FM10K_NETDEV_STAT(rx_crc_errors), FM10K_NETDEV_STAT(rx_fifo_errors), }; #define FM10K_NETDEV_STATS_LEN ARRAY_SIZE(fm10k_gstrings_net_stats) /* General interface statistics */ #define FM10K_STAT(_name, _stat) \ FM10K_STAT_FIELDS(struct fm10k_intfc, _name, _stat) static const struct fm10k_stats fm10k_gstrings_global_stats[] = { FM10K_STAT("tx_restart_queue", restart_queue), FM10K_STAT("tx_busy", tx_busy), FM10K_STAT("tx_csum_errors", tx_csum_errors), FM10K_STAT("rx_alloc_failed", alloc_failed), FM10K_STAT("rx_csum_errors", rx_csum_errors), FM10K_STAT("tx_packets_nic", tx_packets_nic), FM10K_STAT("tx_bytes_nic", tx_bytes_nic), FM10K_STAT("rx_packets_nic", rx_packets_nic), FM10K_STAT("rx_bytes_nic", rx_bytes_nic), FM10K_STAT("rx_drops_nic", rx_drops_nic), FM10K_STAT("rx_overrun_pf", rx_overrun_pf), FM10K_STAT("rx_overrun_vf", rx_overrun_vf), FM10K_STAT("swapi_status", hw.swapi.status), FM10K_STAT("mac_rules_used", hw.swapi.mac.used), FM10K_STAT("mac_rules_avail", hw.swapi.mac.avail), FM10K_STAT("reset_while_pending", hw.mac.reset_while_pending), FM10K_STAT("tx_hang_count", tx_timeout_count), }; static const struct fm10k_stats fm10k_gstrings_pf_stats[] = { FM10K_STAT("timeout", stats.timeout.count), FM10K_STAT("ur", stats.ur.count), FM10K_STAT("ca", stats.ca.count), FM10K_STAT("um", stats.um.count), FM10K_STAT("xec", stats.xec.count), FM10K_STAT("vlan_drop", stats.vlan_drop.count), FM10K_STAT("loopback_drop", stats.loopback_drop.count), FM10K_STAT("nodesc_drop", stats.nodesc_drop.count), }; /* mailbox statistics */ #define FM10K_MBX_STAT(_name, _stat) \ FM10K_STAT_FIELDS(struct fm10k_mbx_info, _name, _stat) static const struct fm10k_stats fm10k_gstrings_mbx_stats[] = { FM10K_MBX_STAT("mbx_tx_busy", tx_busy), FM10K_MBX_STAT("mbx_tx_dropped", tx_dropped), FM10K_MBX_STAT("mbx_tx_messages", tx_messages), FM10K_MBX_STAT("mbx_tx_dwords", tx_dwords), FM10K_MBX_STAT("mbx_tx_mbmem_pulled", tx_mbmem_pulled), FM10K_MBX_STAT("mbx_rx_messages", rx_messages), FM10K_MBX_STAT("mbx_rx_dwords", rx_dwords), FM10K_MBX_STAT("mbx_rx_parse_err", rx_parse_err), FM10K_MBX_STAT("mbx_rx_mbmem_pushed", rx_mbmem_pushed), }; /* per-queue ring statistics */ #define FM10K_QUEUE_STAT(_name, _stat) \ FM10K_STAT_FIELDS(struct fm10k_ring, _name, _stat) static const struct fm10k_stats fm10k_gstrings_queue_stats[] = { FM10K_QUEUE_STAT("%s_queue_%u_packets", stats.packets), FM10K_QUEUE_STAT("%s_queue_%u_bytes", stats.bytes), }; #define FM10K_GLOBAL_STATS_LEN ARRAY_SIZE(fm10k_gstrings_global_stats) #define FM10K_PF_STATS_LEN ARRAY_SIZE(fm10k_gstrings_pf_stats) #define FM10K_MBX_STATS_LEN ARRAY_SIZE(fm10k_gstrings_mbx_stats) #define FM10K_QUEUE_STATS_LEN ARRAY_SIZE(fm10k_gstrings_queue_stats) #define FM10K_STATIC_STATS_LEN (FM10K_GLOBAL_STATS_LEN + \ FM10K_NETDEV_STATS_LEN + \ FM10K_MBX_STATS_LEN) static const char fm10k_gstrings_test[][ETH_GSTRING_LEN] = { "Mailbox test (on/offline)" }; #define FM10K_TEST_LEN (sizeof(fm10k_gstrings_test) / ETH_GSTRING_LEN) enum fm10k_self_test_types { FM10K_TEST_MBX, FM10K_TEST_MAX = FM10K_TEST_LEN }; enum { FM10K_PRV_FLAG_LEN, }; static const char fm10k_prv_flags[FM10K_PRV_FLAG_LEN][ETH_GSTRING_LEN] = { }; static void __fm10k_add_stat_strings(u8 **p, const struct fm10k_stats stats[], const unsigned int size, ...) { unsigned int i; for (i = 0; i < size; i++) { va_list args; va_start(args, size); vsnprintf(*p, ETH_GSTRING_LEN, stats[i].stat_string, args); *p += ETH_GSTRING_LEN; va_end(args); } } #define fm10k_add_stat_strings(p, stats, ...) \ __fm10k_add_stat_strings(p, stats, ARRAY_SIZE(stats), ## __VA_ARGS__) static void fm10k_get_stat_strings(struct net_device *dev, u8 *data) { struct fm10k_intfc *interface = netdev_priv(dev); unsigned int i; fm10k_add_stat_strings(&data, fm10k_gstrings_net_stats); fm10k_add_stat_strings(&data, fm10k_gstrings_global_stats); fm10k_add_stat_strings(&data, fm10k_gstrings_mbx_stats); if (interface->hw.mac.type != fm10k_mac_vf) fm10k_add_stat_strings(&data, fm10k_gstrings_pf_stats); for (i = 0; i < interface->hw.mac.max_queues; i++) { fm10k_add_stat_strings(&data, fm10k_gstrings_queue_stats, "tx", i); fm10k_add_stat_strings(&data, fm10k_gstrings_queue_stats, "rx", i); } } static void fm10k_get_strings(struct net_device *dev, u32 stringset, u8 *data) { switch (stringset) { case ETH_SS_TEST: memcpy(data, fm10k_gstrings_test, FM10K_TEST_LEN * ETH_GSTRING_LEN); break; case ETH_SS_STATS: fm10k_get_stat_strings(dev, data); break; case ETH_SS_PRIV_FLAGS: memcpy(data, fm10k_prv_flags, FM10K_PRV_FLAG_LEN * ETH_GSTRING_LEN); break; } } static int fm10k_get_sset_count(struct net_device *dev, int sset) { struct fm10k_intfc *interface = netdev_priv(dev); struct fm10k_hw *hw = &interface->hw; int stats_len = FM10K_STATIC_STATS_LEN; switch (sset) { case ETH_SS_TEST: return FM10K_TEST_LEN; case ETH_SS_STATS: stats_len += hw->mac.max_queues * 2 * FM10K_QUEUE_STATS_LEN; if (hw->mac.type != fm10k_mac_vf) stats_len += FM10K_PF_STATS_LEN; return stats_len; case ETH_SS_PRIV_FLAGS: return FM10K_PRV_FLAG_LEN; default: return -EOPNOTSUPP; } } static void __fm10k_add_ethtool_stats(u64 **data, void *pointer, const struct fm10k_stats stats[], const unsigned int size) { unsigned int i; if (!pointer) { /* memory is not zero allocated so we have to clear it */ for (i = 0; i < size; i++) *((*data)++) = 0; return; } for (i = 0; i < size; i++) { char *p = (char *)pointer + stats[i].stat_offset; switch (stats[i].sizeof_stat) { case sizeof(u64): *((*data)++) = *(u64 *)p; break; case sizeof(u32): *((*data)++) = *(u32 *)p; break; case sizeof(u16): *((*data)++) = *(u16 *)p; break; case sizeof(u8): *((*data)++) = *(u8 *)p; break; default: WARN_ONCE(1, "unexpected stat size for %s", stats[i].stat_string); *((*data)++) = 0; } } } #define fm10k_add_ethtool_stats(data, pointer, stats) \ __fm10k_add_ethtool_stats(data, pointer, stats, ARRAY_SIZE(stats)) static void fm10k_get_ethtool_stats(struct net_device *netdev, struct ethtool_stats __always_unused *stats, u64 *data) { struct fm10k_intfc *interface = netdev_priv(netdev); struct net_device_stats *net_stats = &netdev->stats; int i; fm10k_update_stats(interface); fm10k_add_ethtool_stats(&data, net_stats, fm10k_gstrings_net_stats); fm10k_add_ethtool_stats(&data, interface, fm10k_gstrings_global_stats); fm10k_add_ethtool_stats(&data, &interface->hw.mbx, fm10k_gstrings_mbx_stats); if (interface->hw.mac.type != fm10k_mac_vf) { fm10k_add_ethtool_stats(&data, interface, fm10k_gstrings_pf_stats); } for (i = 0; i < interface->hw.mac.max_queues; i++) { struct fm10k_ring *ring; ring = interface->tx_ring[i]; fm10k_add_ethtool_stats(&data, ring, fm10k_gstrings_queue_stats); ring = interface->rx_ring[i]; fm10k_add_ethtool_stats(&data, ring, fm10k_gstrings_queue_stats); } } /* If function below adds more registers this define needs to be updated */ #define FM10K_REGS_LEN_Q 29 static void fm10k_get_reg_q(struct fm10k_hw *hw, u32 *buff, int i) { int idx = 0; buff[idx++] = fm10k_read_reg(hw, FM10K_RDBAL(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_RDBAH(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_RDLEN(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_TPH_RXCTRL(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_RDH(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_RDT(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_RXQCTL(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_RXDCTL(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_RXINT(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_SRRCTL(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_QPRC(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_QPRDC(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_QBRC_L(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_QBRC_H(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_TDBAL(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_TDBAH(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_TDLEN(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_TPH_TXCTRL(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_TDH(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_TDT(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_TXDCTL(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_TXQCTL(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_TXINT(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_QPTC(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_QBTC_L(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_QBTC_H(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_TQDLOC(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_TX_SGLORT(i)); buff[idx++] = fm10k_read_reg(hw, FM10K_PFVTCTL(i)); BUG_ON(idx != FM10K_REGS_LEN_Q); } /* If function above adds more registers this define needs to be updated */ #define FM10K_REGS_LEN_VSI 43 static void fm10k_get_reg_vsi(struct fm10k_hw *hw, u32 *buff, int i) { int idx = 0, j; buff[idx++] = fm10k_read_reg(hw, FM10K_MRQC(i)); for (j = 0; j < 10; j++) buff[idx++] = fm10k_read_reg(hw, FM10K_RSSRK(i, j)); for (j = 0; j < 32; j++) buff[idx++] = fm10k_read_reg(hw, FM10K_RETA(i, j)); BUG_ON(idx != FM10K_REGS_LEN_VSI); } static void fm10k_get_regs(struct net_device *netdev, struct ethtool_regs *regs, void *p) { struct fm10k_intfc *interface = netdev_priv(netdev); struct fm10k_hw *hw = &interface->hw; u32 *buff = p; u16 i; regs->version = BIT(24) | (hw->revision_id << 16) | hw->device_id; switch (hw->mac.type) { case fm10k_mac_pf: /* General PF Registers */ *(buff++) = fm10k_read_reg(hw, FM10K_CTRL); *(buff++) = fm10k_read_reg(hw, FM10K_CTRL_EXT); *(buff++) = fm10k_read_reg(hw, FM10K_GCR); *(buff++) = fm10k_read_reg(hw, FM10K_GCR_EXT); for (i = 0; i < 8; i++) { *(buff++) = fm10k_read_reg(hw, FM10K_DGLORTMAP(i)); *(buff++) = fm10k_read_reg(hw, FM10K_DGLORTDEC(i)); } for (i = 0; i < 65; i++) { fm10k_get_reg_vsi(hw, buff, i); buff += FM10K_REGS_LEN_VSI; } *(buff++) = fm10k_read_reg(hw, FM10K_DMA_CTRL); *(buff++) = fm10k_read_reg(hw, FM10K_DMA_CTRL2); for (i = 0; i < FM10K_MAX_QUEUES_PF; i++) { fm10k_get_reg_q(hw, buff, i); buff += FM10K_REGS_LEN_Q; } *(buff++) = fm10k_read_reg(hw, FM10K_TPH_CTRL); for (i = 0; i < 8; i++) *(buff++) = fm10k_read_reg(hw, FM10K_INT_MAP(i)); /* Interrupt Throttling Registers */ for (i = 0; i < 130; i++) *(buff++) = fm10k_read_reg(hw, FM10K_ITR(i)); break; case fm10k_mac_vf: /* General VF registers */ *(buff++) = fm10k_read_reg(hw, FM10K_VFCTRL); *(buff++) = fm10k_read_reg(hw, FM10K_VFINT_MAP); *(buff++) = fm10k_read_reg(hw, FM10K_VFSYSTIME); /* Interrupt Throttling Registers */ for (i = 0; i < 8; i++) *(buff++) = fm10k_read_reg(hw, FM10K_VFITR(i)); fm10k_get_reg_vsi(hw, buff, 0); buff += FM10K_REGS_LEN_VSI; for (i = 0; i < FM10K_MAX_QUEUES_POOL; i++) { if (i < hw->mac.max_queues) fm10k_get_reg_q(hw, buff, i); else memset(buff, 0, sizeof(u32) * FM10K_REGS_LEN_Q); buff += FM10K_REGS_LEN_Q; } break; default: return; } } /* If function above adds more registers these define need to be updated */ #define FM10K_REGS_LEN_PF \ (162 + (65 * FM10K_REGS_LEN_VSI) + (FM10K_MAX_QUEUES_PF * FM10K_REGS_LEN_Q)) #define FM10K_REGS_LEN_VF \ (11 + FM10K_REGS_LEN_VSI + (FM10K_MAX_QUEUES_POOL * FM10K_REGS_LEN_Q)) static int fm10k_get_regs_len(struct net_device *netdev) { struct fm10k_intfc *interface = netdev_priv(netdev); struct fm10k_hw *hw = &interface->hw; switch (hw->mac.type) { case fm10k_mac_pf: return FM10K_REGS_LEN_PF * sizeof(u32); case fm10k_mac_vf: return FM10K_REGS_LEN_VF * sizeof(u32); default: return 0; } } static void fm10k_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { struct fm10k_intfc *interface = netdev_priv(dev); strncpy(info->driver, fm10k_driver_name, sizeof(info->driver) - 1); strncpy(info->bus_info, pci_name(interface->pdev), sizeof(info->bus_info) - 1); } static void fm10k_get_pauseparam(struct net_device *dev, struct ethtool_pauseparam *pause) { struct fm10k_intfc *interface = netdev_priv(dev); /* record fixed values for autoneg and tx pause */ pause->autoneg = 0; pause->tx_pause = 1; pause->rx_pause = interface->rx_pause ? 1 : 0; } static int fm10k_set_pauseparam(struct net_device *dev, struct ethtool_pauseparam *pause) { struct fm10k_intfc *interface = netdev_priv(dev); struct fm10k_hw *hw = &interface->hw; if (pause->autoneg || !pause->tx_pause) return -EINVAL; /* we can only support pause on the PF to avoid head-of-line blocking */ if (hw->mac.type == fm10k_mac_pf) interface->rx_pause = pause->rx_pause ? ~0 : 0; else if (pause->rx_pause) return -EINVAL; if (netif_running(dev)) fm10k_update_rx_drop_en(interface); return 0; } static u32 fm10k_get_msglevel(struct net_device *netdev) { struct fm10k_intfc *interface = netdev_priv(netdev); return interface->msg_enable; } static void fm10k_set_msglevel(struct net_device *netdev, u32 data) { struct fm10k_intfc *interface = netdev_priv(netdev); interface->msg_enable = data; } static void fm10k_get_ringparam(struct net_device *netdev, struct ethtool_ringparam *ring, struct kernel_ethtool_ringparam *kernel_ring, struct netlink_ext_ack *extack) { struct fm10k_intfc *interface = netdev_priv(netdev); ring->rx_max_pending = FM10K_MAX_RXD; ring->tx_max_pending = FM10K_MAX_TXD; ring->rx_mini_max_pending = 0; ring->rx_jumbo_max_pending = 0; ring->rx_pending = interface->rx_ring_count; ring->tx_pending = interface->tx_ring_count; ring->rx_mini_pending = 0; ring->rx_jumbo_pending = 0; } static int fm10k_set_ringparam(struct net_device *netdev, struct ethtool_ringparam *ring, struct kernel_ethtool_ringparam *kernel_ring, struct netlink_ext_ack *extack) { struct fm10k_intfc *interface = netdev_priv(netdev); struct fm10k_ring *temp_ring; int i, err = 0; u32 new_rx_count, new_tx_count; if ((ring->rx_mini_pending) || (ring->rx_jumbo_pending)) return -EINVAL; new_tx_count = clamp_t(u32, ring->tx_pending, FM10K_MIN_TXD, FM10K_MAX_TXD); new_tx_count = ALIGN(new_tx_count, FM10K_REQ_TX_DESCRIPTOR_MULTIPLE); new_rx_count = clamp_t(u32, ring->rx_pending, FM10K_MIN_RXD, FM10K_MAX_RXD); new_rx_count = ALIGN(new_rx_count, FM10K_REQ_RX_DESCRIPTOR_MULTIPLE); if ((new_tx_count == interface->tx_ring_count) && (new_rx_count == interface->rx_ring_count)) { /* nothing to do */ return 0; } while (test_and_set_bit(__FM10K_RESETTING, interface->state)) usleep_range(1000, 2000); if (!netif_running(interface->netdev)) { for (i = 0; i < interface->num_tx_queues; i++) interface->tx_ring[i]->count = new_tx_count; for (i = 0; i < interface->num_rx_queues; i++) interface->rx_ring[i]->count = new_rx_count; interface->tx_ring_count = new_tx_count; interface->rx_ring_count = new_rx_count; goto clear_reset; } /* allocate temporary buffer to store rings in */ i = max_t(int, interface->num_tx_queues, interface->num_rx_queues); temp_ring = vmalloc(array_size(i, sizeof(struct fm10k_ring))); if (!temp_ring) { err = -ENOMEM; goto clear_reset; } fm10k_down(interface); /* Setup new Tx resources and free the old Tx resources in that order. * We can then assign the new resources to the rings via a memcpy. * The advantage to this approach is that we are guaranteed to still * have resources even in the case of an allocation failure. */ if (new_tx_count != interface->tx_ring_count) { for (i = 0; i < interface->num_tx_queues; i++) { memcpy(&temp_ring[i], interface->tx_ring[i], sizeof(struct fm10k_ring)); temp_ring[i].count = new_tx_count; err = fm10k_setup_tx_resources(&temp_ring[i]); if (err) { while (i) { i--; fm10k_free_tx_resources(&temp_ring[i]); } goto err_setup; } } for (i = 0; i < interface->num_tx_queues; i++) { fm10k_free_tx_resources(interface->tx_ring[i]); memcpy(interface->tx_ring[i], &temp_ring[i], sizeof(struct fm10k_ring)); } interface->tx_ring_count = new_tx_count; } /* Repeat the process for the Rx rings if needed */ if (new_rx_count != interface->rx_ring_count) { for (i = 0; i < interface->num_rx_queues; i++) { memcpy(&temp_ring[i], interface->rx_ring[i], sizeof(struct fm10k_ring)); temp_ring[i].count = new_rx_count; err = fm10k_setup_rx_resources(&temp_ring[i]); if (err) { while (i) { i--; fm10k_free_rx_resources(&temp_ring[i]); } goto err_setup; } } for (i = 0; i < interface->num_rx_queues; i++) { fm10k_free_rx_resources(interface->rx_ring[i]); memcpy(interface->rx_ring[i], &temp_ring[i], sizeof(struct fm10k_ring)); } interface->rx_ring_count = new_rx_count; } err_setup: fm10k_up(interface); vfree(temp_ring); clear_reset: clear_bit(__FM10K_RESETTING, interface->state); return err; } static int fm10k_get_coalesce(struct net_device *dev, struct ethtool_coalesce *ec, struct kernel_ethtool_coalesce *kernel_coal, struct netlink_ext_ack *extack) { struct fm10k_intfc *interface = netdev_priv(dev); ec->use_adaptive_tx_coalesce = ITR_IS_ADAPTIVE(interface->tx_itr); ec->tx_coalesce_usecs = interface->tx_itr & ~FM10K_ITR_ADAPTIVE; ec->use_adaptive_rx_coalesce = ITR_IS_ADAPTIVE(interface->rx_itr); ec->rx_coalesce_usecs = interface->rx_itr & ~FM10K_ITR_ADAPTIVE; return 0; } static int fm10k_set_coalesce(struct net_device *dev, struct ethtool_coalesce *ec, struct kernel_ethtool_coalesce *kernel_coal, struct netlink_ext_ack *extack) { struct fm10k_intfc *interface = netdev_priv(dev); u16 tx_itr, rx_itr; int i; /* verify limits */ if ((ec->rx_coalesce_usecs > FM10K_ITR_MAX) || (ec->tx_coalesce_usecs > FM10K_ITR_MAX)) return -EINVAL; /* record settings */ tx_itr = ec->tx_coalesce_usecs; rx_itr = ec->rx_coalesce_usecs; /* set initial values for adaptive ITR */ if (ec->use_adaptive_tx_coalesce) tx_itr = FM10K_ITR_ADAPTIVE | FM10K_TX_ITR_DEFAULT; if (ec->use_adaptive_rx_coalesce) rx_itr = FM10K_ITR_ADAPTIVE | FM10K_RX_ITR_DEFAULT; /* update interface */ interface->tx_itr = tx_itr; interface->rx_itr = rx_itr; /* update q_vectors */ for (i = 0; i < interface->num_q_vectors; i++) { struct fm10k_q_vector *qv = interface->q_vector[i]; qv->tx.itr = tx_itr; qv->rx.itr = rx_itr; } return 0; } static int fm10k_get_rss_hash_opts(struct fm10k_intfc *interface, struct ethtool_rxnfc *cmd) { cmd->data = 0; /* Report default options for RSS on fm10k */ switch (cmd->flow_type) { case TCP_V4_FLOW: case TCP_V6_FLOW: cmd->data |= RXH_L4_B_0_1 | RXH_L4_B_2_3; fallthrough; case UDP_V4_FLOW: if (test_bit(FM10K_FLAG_RSS_FIELD_IPV4_UDP, interface->flags)) cmd->data |= RXH_L4_B_0_1 | RXH_L4_B_2_3; fallthrough; case SCTP_V4_FLOW: case SCTP_V6_FLOW: case AH_ESP_V4_FLOW: case AH_ESP_V6_FLOW: case AH_V4_FLOW: case AH_V6_FLOW: case ESP_V4_FLOW: case ESP_V6_FLOW: case IPV4_FLOW: case IPV6_FLOW: cmd->data |= RXH_IP_SRC | RXH_IP_DST; break; case UDP_V6_FLOW: if (test_bit(FM10K_FLAG_RSS_FIELD_IPV6_UDP, interface->flags)) cmd->data |= RXH_L4_B_0_1 | RXH_L4_B_2_3; cmd->data |= RXH_IP_SRC | RXH_IP_DST; break; default: return -EINVAL; } return 0; } static int fm10k_get_rxnfc(struct net_device *dev, struct ethtool_rxnfc *cmd, u32 __always_unused *rule_locs) { struct fm10k_intfc *interface = netdev_priv(dev); int ret = -EOPNOTSUPP; switch (cmd->cmd) { case ETHTOOL_GRXRINGS: cmd->data = interface->num_rx_queues; ret = 0; break; case ETHTOOL_GRXFH: ret = fm10k_get_rss_hash_opts(interface, cmd); break; default: break; } return ret; } static int fm10k_set_rss_hash_opt(struct fm10k_intfc *interface, struct ethtool_rxnfc *nfc) { int rss_ipv4_udp = test_bit(FM10K_FLAG_RSS_FIELD_IPV4_UDP, interface->flags); int rss_ipv6_udp = test_bit(FM10K_FLAG_RSS_FIELD_IPV6_UDP, interface->flags); /* RSS does not support anything other than hashing * to queues on src and dst IPs and ports */ if (nfc->data & ~(RXH_IP_SRC | RXH_IP_DST | RXH_L4_B_0_1 | RXH_L4_B_2_3)) return -EINVAL; switch (nfc->flow_type) { case TCP_V4_FLOW: case TCP_V6_FLOW: if (!(nfc->data & RXH_IP_SRC) || !(nfc->data & RXH_IP_DST) || !(nfc->data & RXH_L4_B_0_1) || !(nfc->data & RXH_L4_B_2_3)) return -EINVAL; break; case UDP_V4_FLOW: if (!(nfc->data & RXH_IP_SRC) || !(nfc->data & RXH_IP_DST)) return -EINVAL; switch (nfc->data & (RXH_L4_B_0_1 | RXH_L4_B_2_3)) { case 0: clear_bit(FM10K_FLAG_RSS_FIELD_IPV4_UDP, interface->flags); break; case (RXH_L4_B_0_1 | RXH_L4_B_2_3): set_bit(FM10K_FLAG_RSS_FIELD_IPV4_UDP, interface->flags); break; default: return -EINVAL; } break; case UDP_V6_FLOW: if (!(nfc->data & RXH_IP_SRC) || !(nfc->data & RXH_IP_DST)) return -EINVAL; switch (nfc->data & (RXH_L4_B_0_1 | RXH_L4_B_2_3)) { case 0: clear_bit(FM10K_FLAG_RSS_FIELD_IPV6_UDP, interface->flags); break; case (RXH_L4_B_0_1 | RXH_L4_B_2_3): set_bit(FM10K_FLAG_RSS_FIELD_IPV6_UDP, interface->flags); break; default: return -EINVAL; } break; case AH_ESP_V4_FLOW: case AH_V4_FLOW: case ESP_V4_FLOW: case SCTP_V4_FLOW: case AH_ESP_V6_FLOW: case AH_V6_FLOW: case ESP_V6_FLOW: case SCTP_V6_FLOW: if (!(nfc->data & RXH_IP_SRC) || !(nfc->data & RXH_IP_DST) || (nfc->data & RXH_L4_B_0_1) || (nfc->data & RXH_L4_B_2_3)) return -EINVAL; break; default: return -EINVAL; } /* If something changed we need to update the MRQC register. Note that * test_bit() is guaranteed to return strictly 0 or 1, so testing for * equality is safe. */ if ((rss_ipv4_udp != test_bit(FM10K_FLAG_RSS_FIELD_IPV4_UDP, interface->flags)) || (rss_ipv6_udp != test_bit(FM10K_FLAG_RSS_FIELD_IPV6_UDP, interface->flags))) { struct fm10k_hw *hw = &interface->hw; bool warn = false; u32 mrqc; /* Perform hash on these packet types */ mrqc = FM10K_MRQC_IPV4 | FM10K_MRQC_TCP_IPV4 | FM10K_MRQC_IPV6 | FM10K_MRQC_TCP_IPV6; if (test_bit(FM10K_FLAG_RSS_FIELD_IPV4_UDP, interface->flags)) { mrqc |= FM10K_MRQC_UDP_IPV4; warn = true; } if (test_bit(FM10K_FLAG_RSS_FIELD_IPV6_UDP, interface->flags)) { mrqc |= FM10K_MRQC_UDP_IPV6; warn = true; } /* If we enable UDP RSS display a warning that this may cause * fragmented UDP packets to arrive out of order. */ if (warn) netif_warn(interface, drv, interface->netdev, "enabling UDP RSS: fragmented packets may arrive out of order to the stack above\n"); fm10k_write_reg(hw, FM10K_MRQC(0), mrqc); } return 0; } static int fm10k_set_rxnfc(struct net_device *dev, struct ethtool_rxnfc *cmd) { struct fm10k_intfc *interface = netdev_priv(dev); int ret = -EOPNOTSUPP; switch (cmd->cmd) { case ETHTOOL_SRXFH: ret = fm10k_set_rss_hash_opt(interface, cmd); break; default: break; } return ret; } static int fm10k_mbx_test(struct fm10k_intfc *interface, u64 *data) { struct fm10k_hw *hw = &interface->hw; struct fm10k_mbx_info *mbx = &hw->mbx; u32 attr_flag, test_msg[6]; unsigned long timeout; int err = -EINVAL; /* For now this is a VF only feature */ if (hw->mac.type != fm10k_mac_vf) return 0; /* loop through both nested and unnested attribute types */ for (attr_flag = BIT(FM10K_TEST_MSG_UNSET); attr_flag < BIT(2 * FM10K_TEST_MSG_NESTED); attr_flag += attr_flag) { /* generate message to be tested */ fm10k_tlv_msg_test_create(test_msg, attr_flag); fm10k_mbx_lock(interface); mbx->test_result = FM10K_NOT_IMPLEMENTED; err = mbx->ops.enqueue_tx(hw, mbx, test_msg); fm10k_mbx_unlock(interface); /* wait up to 1 second for response */ timeout = jiffies + HZ; do { if (err < 0) goto err_out; usleep_range(500, 1000); fm10k_mbx_lock(interface); mbx->ops.process(hw, mbx); fm10k_mbx_unlock(interface); err = mbx->test_result; if (!err) break; } while (time_is_after_jiffies(timeout)); /* reporting errors */ if (err) goto err_out; } err_out: *data = err < 0 ? (attr_flag) : (err > 0); return err; } static void fm10k_self_test(struct net_device *dev, struct ethtool_test *eth_test, u64 *data) { struct fm10k_intfc *interface = netdev_priv(dev); struct fm10k_hw *hw = &interface->hw; memset(data, 0, sizeof(*data) * FM10K_TEST_LEN); if (FM10K_REMOVED(hw->hw_addr)) { netif_err(interface, drv, dev, "Interface removed - test blocked\n"); eth_test->flags |= ETH_TEST_FL_FAILED; return; } if (fm10k_mbx_test(interface, &data[FM10K_TEST_MBX])) eth_test->flags |= ETH_TEST_FL_FAILED; } static u32 fm10k_get_priv_flags(struct net_device *netdev) { return 0; } static int fm10k_set_priv_flags(struct net_device *netdev, u32 priv_flags) { if (priv_flags >= BIT(FM10K_PRV_FLAG_LEN)) return -EINVAL; return 0; } static u32 fm10k_get_reta_size(struct net_device __always_unused *netdev) { return FM10K_RETA_SIZE * FM10K_RETA_ENTRIES_PER_REG; } void fm10k_write_reta(struct fm10k_intfc *interface, const u32 *indir) { u16 rss_i = interface->ring_feature[RING_F_RSS].indices; struct fm10k_hw *hw = &interface->hw; u32 table[4]; int i, j; /* record entries to reta table */ for (i = 0; i < FM10K_RETA_SIZE; i++) { u32 reta, n; /* generate a new table if we weren't given one */ for (j = 0; j < 4; j++) { if (indir) n = indir[4 * i + j]; else n = ethtool_rxfh_indir_default(4 * i + j, rss_i); table[j] = n; } reta = table[0] | (table[1] << 8) | (table[2] << 16) | (table[3] << 24); if (interface->reta[i] == reta) continue; interface->reta[i] = reta; fm10k_write_reg(hw, FM10K_RETA(0, i), reta); } } static int fm10k_get_reta(struct net_device *netdev, u32 *indir) { struct fm10k_intfc *interface = netdev_priv(netdev); int i; if (!indir) return 0; for (i = 0; i < FM10K_RETA_SIZE; i++, indir += 4) { u32 reta = interface->reta[i]; indir[0] = (reta << 24) >> 24; indir[1] = (reta << 16) >> 24; indir[2] = (reta << 8) >> 24; indir[3] = (reta) >> 24; } return 0; } static int fm10k_set_reta(struct net_device *netdev, const u32 *indir) { struct fm10k_intfc *interface = netdev_priv(netdev); int i; u16 rss_i; if (!indir) return 0; /* Verify user input. */ rss_i = interface->ring_feature[RING_F_RSS].indices; for (i = fm10k_get_reta_size(netdev); i--;) { if (indir[i] < rss_i) continue; return -EINVAL; } fm10k_write_reta(interface, indir); return 0; } static u32 fm10k_get_rssrk_size(struct net_device __always_unused *netdev) { return FM10K_RSSRK_SIZE * FM10K_RSSRK_ENTRIES_PER_REG; } static int fm10k_get_rssh(struct net_device *netdev, u32 *indir, u8 *key, u8 *hfunc) { struct fm10k_intfc *interface = netdev_priv(netdev); int i, err; if (hfunc) *hfunc = ETH_RSS_HASH_TOP; err = fm10k_get_reta(netdev, indir); if (err || !key) return err; for (i = 0; i < FM10K_RSSRK_SIZE; i++, key += 4) *(__le32 *)key = cpu_to_le32(interface->rssrk[i]); return 0; } static int fm10k_set_rssh(struct net_device *netdev, const u32 *indir, const u8 *key, const u8 hfunc) { struct fm10k_intfc *interface = netdev_priv(netdev); struct fm10k_hw *hw = &interface->hw; int i, err; /* We do not allow change in unsupported parameters */ if (hfunc != ETH_RSS_HASH_NO_CHANGE && hfunc != ETH_RSS_HASH_TOP) return -EOPNOTSUPP; err = fm10k_set_reta(netdev, indir); if (err || !key) return err; for (i = 0; i < FM10K_RSSRK_SIZE; i++, key += 4) { u32 rssrk = le32_to_cpu(*(__le32 *)key); if (interface->rssrk[i] == rssrk) continue; interface->rssrk[i] = rssrk; fm10k_write_reg(hw, FM10K_RSSRK(0, i), rssrk); } return 0; } static unsigned int fm10k_max_channels(struct net_device *dev) { struct fm10k_intfc *interface = netdev_priv(dev); unsigned int max_combined = interface->hw.mac.max_queues; u8 tcs = netdev_get_num_tc(dev); /* For QoS report channels per traffic class */ if (tcs > 1) max_combined = BIT((fls(max_combined / tcs) - 1)); return max_combined; } static void fm10k_get_channels(struct net_device *dev, struct ethtool_channels *ch) { struct fm10k_intfc *interface = netdev_priv(dev); /* report maximum channels */ ch->max_combined = fm10k_max_channels(dev); /* report info for other vector */ ch->max_other = NON_Q_VECTORS; ch->other_count = ch->max_other; /* record RSS queues */ ch->combined_count = interface->ring_feature[RING_F_RSS].indices; } static int fm10k_set_channels(struct net_device *dev, struct ethtool_channels *ch) { struct fm10k_intfc *interface = netdev_priv(dev); unsigned int count = ch->combined_count; /* verify they are not requesting separate vectors */ if (!count || ch->rx_count || ch->tx_count) return -EINVAL; /* verify other_count has not changed */ if (ch->other_count != NON_Q_VECTORS) return -EINVAL; /* verify the number of channels does not exceed hardware limits */ if (count > fm10k_max_channels(dev)) return -EINVAL; interface->ring_feature[RING_F_RSS].limit = count; /* use setup TC to update any traffic class queue mapping */ return fm10k_setup_tc(dev, netdev_get_num_tc(dev)); } static const struct ethtool_ops fm10k_ethtool_ops = { .supported_coalesce_params = ETHTOOL_COALESCE_USECS | ETHTOOL_COALESCE_USE_ADAPTIVE, .get_strings = fm10k_get_strings, .get_sset_count = fm10k_get_sset_count, .get_ethtool_stats = fm10k_get_ethtool_stats, .get_drvinfo = fm10k_get_drvinfo, .get_link = ethtool_op_get_link, .get_pauseparam = fm10k_get_pauseparam, .set_pauseparam = fm10k_set_pauseparam, .get_msglevel = fm10k_get_msglevel, .set_msglevel = fm10k_set_msglevel, .get_ringparam = fm10k_get_ringparam, .set_ringparam = fm10k_set_ringparam, .get_coalesce = fm10k_get_coalesce, .set_coalesce = fm10k_set_coalesce, .get_rxnfc = fm10k_get_rxnfc, .set_rxnfc = fm10k_set_rxnfc, .get_regs = fm10k_get_regs, .get_regs_len = fm10k_get_regs_len, .self_test = fm10k_self_test, .get_priv_flags = fm10k_get_priv_flags, .set_priv_flags = fm10k_set_priv_flags, .get_rxfh_indir_size = fm10k_get_reta_size, .get_rxfh_key_size = fm10k_get_rssrk_size, .get_rxfh = fm10k_get_rssh, .set_rxfh = fm10k_set_rssh, .get_channels = fm10k_get_channels, .set_channels = fm10k_set_channels, .get_ts_info = ethtool_op_get_ts_info, }; void fm10k_set_ethtool_ops(struct net_device *dev) { dev->ethtool_ops = &fm10k_ethtool_ops; }
linux-master
drivers/net/ethernet/intel/fm10k/fm10k_ethtool.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2013 - 2019 Intel Corporation. */ #include "fm10k.h" /** * fm10k_dcbnl_ieee_getets - get the ETS configuration for the device * @dev: netdev interface for the device * @ets: ETS structure to push configuration to **/ static int fm10k_dcbnl_ieee_getets(struct net_device *dev, struct ieee_ets *ets) { int i; /* we support 8 TCs in all modes */ ets->ets_cap = IEEE_8021QAZ_MAX_TCS; ets->cbs = 0; /* we only support strict priority and cannot do traffic shaping */ memset(ets->tc_tx_bw, 0, sizeof(ets->tc_tx_bw)); memset(ets->tc_rx_bw, 0, sizeof(ets->tc_rx_bw)); memset(ets->tc_tsa, IEEE_8021QAZ_TSA_STRICT, sizeof(ets->tc_tsa)); /* populate the prio map based on the netdev */ for (i = 0; i < IEEE_8021QAZ_MAX_TCS; i++) ets->prio_tc[i] = netdev_get_prio_tc_map(dev, i); return 0; } /** * fm10k_dcbnl_ieee_setets - set the ETS configuration for the device * @dev: netdev interface for the device * @ets: ETS structure to pull configuration from **/ static int fm10k_dcbnl_ieee_setets(struct net_device *dev, struct ieee_ets *ets) { u8 num_tc = 0; int i; /* verify type and determine num_tcs needed */ for (i = 0; i < IEEE_8021QAZ_MAX_TCS; i++) { if (ets->tc_tx_bw[i] || ets->tc_rx_bw[i]) return -EINVAL; if (ets->tc_tsa[i] != IEEE_8021QAZ_TSA_STRICT) return -EINVAL; if (ets->prio_tc[i] > num_tc) num_tc = ets->prio_tc[i]; } /* if requested TC is greater than 0 then num_tcs is max + 1 */ if (num_tc) num_tc++; if (num_tc > IEEE_8021QAZ_MAX_TCS) return -EINVAL; /* update TC hardware mapping if necessary */ if (num_tc != netdev_get_num_tc(dev)) { int err = fm10k_setup_tc(dev, num_tc); if (err) return err; } /* update priority mapping */ for (i = 0; i < IEEE_8021QAZ_MAX_TCS; i++) netdev_set_prio_tc_map(dev, i, ets->prio_tc[i]); return 0; } /** * fm10k_dcbnl_ieee_getpfc - get the PFC configuration for the device * @dev: netdev interface for the device * @pfc: PFC structure to push configuration to **/ static int fm10k_dcbnl_ieee_getpfc(struct net_device *dev, struct ieee_pfc *pfc) { struct fm10k_intfc *interface = netdev_priv(dev); /* record flow control max count and state of TCs */ pfc->pfc_cap = IEEE_8021QAZ_MAX_TCS; pfc->pfc_en = interface->pfc_en; return 0; } /** * fm10k_dcbnl_ieee_setpfc - set the PFC configuration for the device * @dev: netdev interface for the device * @pfc: PFC structure to pull configuration from **/ static int fm10k_dcbnl_ieee_setpfc(struct net_device *dev, struct ieee_pfc *pfc) { struct fm10k_intfc *interface = netdev_priv(dev); /* record PFC configuration to interface */ interface->pfc_en = pfc->pfc_en; /* if we are running update the drop_en state for all queues */ if (netif_running(dev)) fm10k_update_rx_drop_en(interface); return 0; } /** * fm10k_dcbnl_getdcbx - get the DCBX configuration for the device * @dev: netdev interface for the device * * Returns that we support only IEEE DCB for this interface **/ static u8 fm10k_dcbnl_getdcbx(struct net_device __always_unused *dev) { return DCB_CAP_DCBX_HOST | DCB_CAP_DCBX_VER_IEEE; } /** * fm10k_dcbnl_setdcbx - get the DCBX configuration for the device * @dev: netdev interface for the device * @mode: new mode for this device * * Returns error on attempt to enable anything but IEEE DCB for this interface **/ static u8 fm10k_dcbnl_setdcbx(struct net_device __always_unused *dev, u8 mode) { return (mode != (DCB_CAP_DCBX_HOST | DCB_CAP_DCBX_VER_IEEE)) ? 1 : 0; } static const struct dcbnl_rtnl_ops fm10k_dcbnl_ops = { .ieee_getets = fm10k_dcbnl_ieee_getets, .ieee_setets = fm10k_dcbnl_ieee_setets, .ieee_getpfc = fm10k_dcbnl_ieee_getpfc, .ieee_setpfc = fm10k_dcbnl_ieee_setpfc, .getdcbx = fm10k_dcbnl_getdcbx, .setdcbx = fm10k_dcbnl_setdcbx, }; /** * fm10k_dcbnl_set_ops - Configures dcbnl ops pointer for netdev * @dev: netdev interface for the device * * Enables PF for DCB by assigning DCBNL ops pointer. **/ void fm10k_dcbnl_set_ops(struct net_device *dev) { struct fm10k_intfc *interface = netdev_priv(dev); struct fm10k_hw *hw = &interface->hw; if (hw->mac.type == fm10k_mac_pf) dev->dcbnl_ops = &fm10k_dcbnl_ops; }
linux-master
drivers/net/ethernet/intel/fm10k/fm10k_dcbnl.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2013 - 2019 Intel Corporation. */ #include "fm10k_common.h" /** * fm10k_fifo_init - Initialize a message FIFO * @fifo: pointer to FIFO * @buffer: pointer to memory to be used to store FIFO * @size: maximum message size to store in FIFO, must be 2^n - 1 **/ static void fm10k_fifo_init(struct fm10k_mbx_fifo *fifo, u32 *buffer, u16 size) { fifo->buffer = buffer; fifo->size = size; fifo->head = 0; fifo->tail = 0; } /** * fm10k_fifo_used - Retrieve used space in FIFO * @fifo: pointer to FIFO * * This function returns the number of DWORDs used in the FIFO **/ static u16 fm10k_fifo_used(struct fm10k_mbx_fifo *fifo) { return fifo->tail - fifo->head; } /** * fm10k_fifo_unused - Retrieve unused space in FIFO * @fifo: pointer to FIFO * * This function returns the number of unused DWORDs in the FIFO **/ static u16 fm10k_fifo_unused(struct fm10k_mbx_fifo *fifo) { return fifo->size + fifo->head - fifo->tail; } /** * fm10k_fifo_empty - Test to verify if FIFO is empty * @fifo: pointer to FIFO * * This function returns true if the FIFO is empty, else false **/ static bool fm10k_fifo_empty(struct fm10k_mbx_fifo *fifo) { return fifo->head == fifo->tail; } /** * fm10k_fifo_head_offset - returns indices of head with given offset * @fifo: pointer to FIFO * @offset: offset to add to head * * This function returns the indices into the FIFO based on head + offset **/ static u16 fm10k_fifo_head_offset(struct fm10k_mbx_fifo *fifo, u16 offset) { return (fifo->head + offset) & (fifo->size - 1); } /** * fm10k_fifo_tail_offset - returns indices of tail with given offset * @fifo: pointer to FIFO * @offset: offset to add to tail * * This function returns the indices into the FIFO based on tail + offset **/ static u16 fm10k_fifo_tail_offset(struct fm10k_mbx_fifo *fifo, u16 offset) { return (fifo->tail + offset) & (fifo->size - 1); } /** * fm10k_fifo_head_len - Retrieve length of first message in FIFO * @fifo: pointer to FIFO * * This function returns the size of the first message in the FIFO **/ static u16 fm10k_fifo_head_len(struct fm10k_mbx_fifo *fifo) { u32 *head = fifo->buffer + fm10k_fifo_head_offset(fifo, 0); /* verify there is at least 1 DWORD in the fifo so *head is valid */ if (fm10k_fifo_empty(fifo)) return 0; /* retieve the message length */ return FM10K_TLV_DWORD_LEN(*head); } /** * fm10k_fifo_head_drop - Drop the first message in FIFO * @fifo: pointer to FIFO * * This function returns the size of the message dropped from the FIFO **/ static u16 fm10k_fifo_head_drop(struct fm10k_mbx_fifo *fifo) { u16 len = fm10k_fifo_head_len(fifo); /* update head so it is at the start of next frame */ fifo->head += len; return len; } /** * fm10k_fifo_drop_all - Drop all messages in FIFO * @fifo: pointer to FIFO * * This function resets the head pointer to drop all messages in the FIFO and * ensure the FIFO is empty. **/ static void fm10k_fifo_drop_all(struct fm10k_mbx_fifo *fifo) { fifo->head = fifo->tail; } /** * fm10k_mbx_index_len - Convert a head/tail index into a length value * @mbx: pointer to mailbox * @head: head index * @tail: head index * * This function takes the head and tail index and determines the length * of the data indicated by this pair. **/ static u16 fm10k_mbx_index_len(struct fm10k_mbx_info *mbx, u16 head, u16 tail) { u16 len = tail - head; /* we wrapped so subtract 2, one for index 0, one for all 1s index */ if (len > tail) len -= 2; return len & ((mbx->mbmem_len << 1) - 1); } /** * fm10k_mbx_tail_add - Determine new tail value with added offset * @mbx: pointer to mailbox * @offset: length to add to tail offset * * This function takes the local tail index and recomputes it for * a given length added as an offset. **/ static u16 fm10k_mbx_tail_add(struct fm10k_mbx_info *mbx, u16 offset) { u16 tail = (mbx->tail + offset + 1) & ((mbx->mbmem_len << 1) - 1); /* add/sub 1 because we cannot have offset 0 or all 1s */ return (tail > mbx->tail) ? --tail : ++tail; } /** * fm10k_mbx_tail_sub - Determine new tail value with subtracted offset * @mbx: pointer to mailbox * @offset: length to add to tail offset * * This function takes the local tail index and recomputes it for * a given length added as an offset. **/ static u16 fm10k_mbx_tail_sub(struct fm10k_mbx_info *mbx, u16 offset) { u16 tail = (mbx->tail - offset - 1) & ((mbx->mbmem_len << 1) - 1); /* sub/add 1 because we cannot have offset 0 or all 1s */ return (tail < mbx->tail) ? ++tail : --tail; } /** * fm10k_mbx_head_add - Determine new head value with added offset * @mbx: pointer to mailbox * @offset: length to add to head offset * * This function takes the local head index and recomputes it for * a given length added as an offset. **/ static u16 fm10k_mbx_head_add(struct fm10k_mbx_info *mbx, u16 offset) { u16 head = (mbx->head + offset + 1) & ((mbx->mbmem_len << 1) - 1); /* add/sub 1 because we cannot have offset 0 or all 1s */ return (head > mbx->head) ? --head : ++head; } /** * fm10k_mbx_head_sub - Determine new head value with subtracted offset * @mbx: pointer to mailbox * @offset: length to add to head offset * * This function takes the local head index and recomputes it for * a given length added as an offset. **/ static u16 fm10k_mbx_head_sub(struct fm10k_mbx_info *mbx, u16 offset) { u16 head = (mbx->head - offset - 1) & ((mbx->mbmem_len << 1) - 1); /* sub/add 1 because we cannot have offset 0 or all 1s */ return (head < mbx->head) ? ++head : --head; } /** * fm10k_mbx_pushed_tail_len - Retrieve the length of message being pushed * @mbx: pointer to mailbox * * This function will return the length of the message currently being * pushed onto the tail of the Rx queue. **/ static u16 fm10k_mbx_pushed_tail_len(struct fm10k_mbx_info *mbx) { u32 *tail = mbx->rx.buffer + fm10k_fifo_tail_offset(&mbx->rx, 0); /* pushed tail is only valid if pushed is set */ if (!mbx->pushed) return 0; return FM10K_TLV_DWORD_LEN(*tail); } /** * fm10k_fifo_write_copy - pulls data off of msg and places it in FIFO * @fifo: pointer to FIFO * @msg: message array to populate * @tail_offset: additional offset to add to tail pointer * @len: length of FIFO to copy into message header * * This function will take a message and copy it into a section of the * FIFO. In order to get something into a location other than just * the tail you can use tail_offset to adjust the pointer. **/ static void fm10k_fifo_write_copy(struct fm10k_mbx_fifo *fifo, const u32 *msg, u16 tail_offset, u16 len) { u16 end = fm10k_fifo_tail_offset(fifo, tail_offset); u32 *tail = fifo->buffer + end; /* track when we should cross the end of the FIFO */ end = fifo->size - end; /* copy end of message before start of message */ if (end < len) memcpy(fifo->buffer, msg + end, (len - end) << 2); else end = len; /* Copy remaining message into Tx FIFO */ memcpy(tail, msg, end << 2); } /** * fm10k_fifo_enqueue - Enqueues the message to the tail of the FIFO * @fifo: pointer to FIFO * @msg: message array to read * * This function enqueues a message up to the size specified by the length * contained in the first DWORD of the message and will place at the tail * of the FIFO. It will return 0 on success, or a negative value on error. **/ static s32 fm10k_fifo_enqueue(struct fm10k_mbx_fifo *fifo, const u32 *msg) { u16 len = FM10K_TLV_DWORD_LEN(*msg); /* verify parameters */ if (len > fifo->size) return FM10K_MBX_ERR_SIZE; /* verify there is room for the message */ if (len > fm10k_fifo_unused(fifo)) return FM10K_MBX_ERR_NO_SPACE; /* Copy message into FIFO */ fm10k_fifo_write_copy(fifo, msg, 0, len); /* memory barrier to guarantee FIFO is written before tail update */ wmb(); /* Update Tx FIFO tail */ fifo->tail += len; return 0; } /** * fm10k_mbx_validate_msg_size - Validate incoming message based on size * @mbx: pointer to mailbox * @len: length of data pushed onto buffer * * This function analyzes the frame and will return a non-zero value when * the start of a message larger than the mailbox is detected. **/ static u16 fm10k_mbx_validate_msg_size(struct fm10k_mbx_info *mbx, u16 len) { struct fm10k_mbx_fifo *fifo = &mbx->rx; u16 total_len = 0, msg_len; /* length should include previous amounts pushed */ len += mbx->pushed; /* offset in message is based off of current message size */ do { u32 *msg; msg = fifo->buffer + fm10k_fifo_tail_offset(fifo, total_len); msg_len = FM10K_TLV_DWORD_LEN(*msg); total_len += msg_len; } while (total_len < len); /* message extends out of pushed section, but fits in FIFO */ if ((len < total_len) && (msg_len <= mbx->max_size)) return 0; /* return length of invalid section */ return (len < total_len) ? len : (len - total_len); } /** * fm10k_mbx_write_copy - pulls data off of Tx FIFO and places it in mbmem * @hw: pointer to hardware structure * @mbx: pointer to mailbox * * This function will take a section of the Tx FIFO and copy it into the * mailbox memory. The offset in mbmem is based on the lower bits of the * tail and len determines the length to copy. **/ static void fm10k_mbx_write_copy(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx) { struct fm10k_mbx_fifo *fifo = &mbx->tx; u32 mbmem = mbx->mbmem_reg; u32 *head = fifo->buffer; u16 end, len, tail, mask; if (!mbx->tail_len) return; /* determine data length and mbmem tail index */ mask = mbx->mbmem_len - 1; len = mbx->tail_len; tail = fm10k_mbx_tail_sub(mbx, len); if (tail > mask) tail++; /* determine offset in the ring */ end = fm10k_fifo_head_offset(fifo, mbx->pulled); head += end; /* memory barrier to guarantee data is ready to be read */ rmb(); /* Copy message from Tx FIFO */ for (end = fifo->size - end; len; head = fifo->buffer) { do { /* adjust tail to match offset for FIFO */ tail &= mask; if (!tail) tail++; mbx->tx_mbmem_pulled++; /* write message to hardware FIFO */ fm10k_write_reg(hw, mbmem + tail++, *(head++)); } while (--len && --end); } } /** * fm10k_mbx_pull_head - Pulls data off of head of Tx FIFO * @hw: pointer to hardware structure * @mbx: pointer to mailbox * @head: acknowledgement number last received * * This function will push the tail index forward based on the remote * head index. It will then pull up to mbmem_len DWORDs off of the * head of the FIFO and will place it in the MBMEM registers * associated with the mailbox. **/ static void fm10k_mbx_pull_head(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx, u16 head) { u16 mbmem_len, len, ack = fm10k_mbx_index_len(mbx, head, mbx->tail); struct fm10k_mbx_fifo *fifo = &mbx->tx; /* update number of bytes pulled and update bytes in transit */ mbx->pulled += mbx->tail_len - ack; /* determine length of data to pull, reserve space for mbmem header */ mbmem_len = mbx->mbmem_len - 1; len = fm10k_fifo_used(fifo) - mbx->pulled; if (len > mbmem_len) len = mbmem_len; /* update tail and record number of bytes in transit */ mbx->tail = fm10k_mbx_tail_add(mbx, len - ack); mbx->tail_len = len; /* drop pulled messages from the FIFO */ for (len = fm10k_fifo_head_len(fifo); len && (mbx->pulled >= len); len = fm10k_fifo_head_len(fifo)) { mbx->pulled -= fm10k_fifo_head_drop(fifo); mbx->tx_messages++; mbx->tx_dwords += len; } /* Copy message out from the Tx FIFO */ fm10k_mbx_write_copy(hw, mbx); } /** * fm10k_mbx_read_copy - pulls data off of mbmem and places it in Rx FIFO * @hw: pointer to hardware structure * @mbx: pointer to mailbox * * This function will take a section of the mailbox memory and copy it * into the Rx FIFO. The offset is based on the lower bits of the * head and len determines the length to copy. **/ static void fm10k_mbx_read_copy(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx) { struct fm10k_mbx_fifo *fifo = &mbx->rx; u32 mbmem = mbx->mbmem_reg ^ mbx->mbmem_len; u32 *tail = fifo->buffer; u16 end, len, head; /* determine data length and mbmem head index */ len = mbx->head_len; head = fm10k_mbx_head_sub(mbx, len); if (head >= mbx->mbmem_len) head++; /* determine offset in the ring */ end = fm10k_fifo_tail_offset(fifo, mbx->pushed); tail += end; /* Copy message into Rx FIFO */ for (end = fifo->size - end; len; tail = fifo->buffer) { do { /* adjust head to match offset for FIFO */ head &= mbx->mbmem_len - 1; if (!head) head++; mbx->rx_mbmem_pushed++; /* read message from hardware FIFO */ *(tail++) = fm10k_read_reg(hw, mbmem + head++); } while (--len && --end); } /* memory barrier to guarantee FIFO is written before tail update */ wmb(); } /** * fm10k_mbx_push_tail - Pushes up to 15 DWORDs on to tail of FIFO * @hw: pointer to hardware structure * @mbx: pointer to mailbox * @tail: tail index of message * * This function will first validate the tail index and size for the * incoming message. It then updates the acknowledgment number and * copies the data into the FIFO. It will return the number of messages * dequeued on success and a negative value on error. **/ static s32 fm10k_mbx_push_tail(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx, u16 tail) { struct fm10k_mbx_fifo *fifo = &mbx->rx; u16 len, seq = fm10k_mbx_index_len(mbx, mbx->head, tail); /* determine length of data to push */ len = fm10k_fifo_unused(fifo) - mbx->pushed; if (len > seq) len = seq; /* update head and record bytes received */ mbx->head = fm10k_mbx_head_add(mbx, len); mbx->head_len = len; /* nothing to do if there is no data */ if (!len) return 0; /* Copy msg into Rx FIFO */ fm10k_mbx_read_copy(hw, mbx); /* determine if there are any invalid lengths in message */ if (fm10k_mbx_validate_msg_size(mbx, len)) return FM10K_MBX_ERR_SIZE; /* Update pushed */ mbx->pushed += len; /* flush any completed messages */ for (len = fm10k_mbx_pushed_tail_len(mbx); len && (mbx->pushed >= len); len = fm10k_mbx_pushed_tail_len(mbx)) { fifo->tail += len; mbx->pushed -= len; mbx->rx_messages++; mbx->rx_dwords += len; } return 0; } /* pre-generated data for generating the CRC based on the poly 0xAC9A. */ static const u16 fm10k_crc_16b_table[256] = { 0x0000, 0x7956, 0xF2AC, 0x8BFA, 0xBC6D, 0xC53B, 0x4EC1, 0x3797, 0x21EF, 0x58B9, 0xD343, 0xAA15, 0x9D82, 0xE4D4, 0x6F2E, 0x1678, 0x43DE, 0x3A88, 0xB172, 0xC824, 0xFFB3, 0x86E5, 0x0D1F, 0x7449, 0x6231, 0x1B67, 0x909D, 0xE9CB, 0xDE5C, 0xA70A, 0x2CF0, 0x55A6, 0x87BC, 0xFEEA, 0x7510, 0x0C46, 0x3BD1, 0x4287, 0xC97D, 0xB02B, 0xA653, 0xDF05, 0x54FF, 0x2DA9, 0x1A3E, 0x6368, 0xE892, 0x91C4, 0xC462, 0xBD34, 0x36CE, 0x4F98, 0x780F, 0x0159, 0x8AA3, 0xF3F5, 0xE58D, 0x9CDB, 0x1721, 0x6E77, 0x59E0, 0x20B6, 0xAB4C, 0xD21A, 0x564D, 0x2F1B, 0xA4E1, 0xDDB7, 0xEA20, 0x9376, 0x188C, 0x61DA, 0x77A2, 0x0EF4, 0x850E, 0xFC58, 0xCBCF, 0xB299, 0x3963, 0x4035, 0x1593, 0x6CC5, 0xE73F, 0x9E69, 0xA9FE, 0xD0A8, 0x5B52, 0x2204, 0x347C, 0x4D2A, 0xC6D0, 0xBF86, 0x8811, 0xF147, 0x7ABD, 0x03EB, 0xD1F1, 0xA8A7, 0x235D, 0x5A0B, 0x6D9C, 0x14CA, 0x9F30, 0xE666, 0xF01E, 0x8948, 0x02B2, 0x7BE4, 0x4C73, 0x3525, 0xBEDF, 0xC789, 0x922F, 0xEB79, 0x6083, 0x19D5, 0x2E42, 0x5714, 0xDCEE, 0xA5B8, 0xB3C0, 0xCA96, 0x416C, 0x383A, 0x0FAD, 0x76FB, 0xFD01, 0x8457, 0xAC9A, 0xD5CC, 0x5E36, 0x2760, 0x10F7, 0x69A1, 0xE25B, 0x9B0D, 0x8D75, 0xF423, 0x7FD9, 0x068F, 0x3118, 0x484E, 0xC3B4, 0xBAE2, 0xEF44, 0x9612, 0x1DE8, 0x64BE, 0x5329, 0x2A7F, 0xA185, 0xD8D3, 0xCEAB, 0xB7FD, 0x3C07, 0x4551, 0x72C6, 0x0B90, 0x806A, 0xF93C, 0x2B26, 0x5270, 0xD98A, 0xA0DC, 0x974B, 0xEE1D, 0x65E7, 0x1CB1, 0x0AC9, 0x739F, 0xF865, 0x8133, 0xB6A4, 0xCFF2, 0x4408, 0x3D5E, 0x68F8, 0x11AE, 0x9A54, 0xE302, 0xD495, 0xADC3, 0x2639, 0x5F6F, 0x4917, 0x3041, 0xBBBB, 0xC2ED, 0xF57A, 0x8C2C, 0x07D6, 0x7E80, 0xFAD7, 0x8381, 0x087B, 0x712D, 0x46BA, 0x3FEC, 0xB416, 0xCD40, 0xDB38, 0xA26E, 0x2994, 0x50C2, 0x6755, 0x1E03, 0x95F9, 0xECAF, 0xB909, 0xC05F, 0x4BA5, 0x32F3, 0x0564, 0x7C32, 0xF7C8, 0x8E9E, 0x98E6, 0xE1B0, 0x6A4A, 0x131C, 0x248B, 0x5DDD, 0xD627, 0xAF71, 0x7D6B, 0x043D, 0x8FC7, 0xF691, 0xC106, 0xB850, 0x33AA, 0x4AFC, 0x5C84, 0x25D2, 0xAE28, 0xD77E, 0xE0E9, 0x99BF, 0x1245, 0x6B13, 0x3EB5, 0x47E3, 0xCC19, 0xB54F, 0x82D8, 0xFB8E, 0x7074, 0x0922, 0x1F5A, 0x660C, 0xEDF6, 0x94A0, 0xA337, 0xDA61, 0x519B, 0x28CD }; /** * fm10k_crc_16b - Generate a 16 bit CRC for a region of 16 bit data * @data: pointer to data to process * @seed: seed value for CRC * @len: length measured in 16 bits words * * This function will generate a CRC based on the polynomial 0xAC9A and * whatever value is stored in the seed variable. Note that this * value inverts the local seed and the result in order to capture all * leading and trailing zeros. */ static u16 fm10k_crc_16b(const u32 *data, u16 seed, u16 len) { u32 result = seed; while (len--) { result ^= *(data++); result = (result >> 8) ^ fm10k_crc_16b_table[result & 0xFF]; result = (result >> 8) ^ fm10k_crc_16b_table[result & 0xFF]; if (!(len--)) break; result = (result >> 8) ^ fm10k_crc_16b_table[result & 0xFF]; result = (result >> 8) ^ fm10k_crc_16b_table[result & 0xFF]; } return (u16)result; } /** * fm10k_fifo_crc - generate a CRC based off of FIFO data * @fifo: pointer to FIFO * @offset: offset point for start of FIFO * @len: number of DWORDS words to process * @seed: seed value for CRC * * This function generates a CRC for some region of the FIFO **/ static u16 fm10k_fifo_crc(struct fm10k_mbx_fifo *fifo, u16 offset, u16 len, u16 seed) { u32 *data = fifo->buffer + offset; /* track when we should cross the end of the FIFO */ offset = fifo->size - offset; /* if we are in 2 blocks process the end of the FIFO first */ if (offset < len) { seed = fm10k_crc_16b(data, seed, offset * 2); data = fifo->buffer; len -= offset; } /* process any remaining bits */ return fm10k_crc_16b(data, seed, len * 2); } /** * fm10k_mbx_update_local_crc - Update the local CRC for outgoing data * @mbx: pointer to mailbox * @head: head index provided by remote mailbox * * This function will generate the CRC for all data from the end of the * last head update to the current one. It uses the result of the * previous CRC as the seed for this update. The result is stored in * mbx->local. **/ static void fm10k_mbx_update_local_crc(struct fm10k_mbx_info *mbx, u16 head) { u16 len = mbx->tail_len - fm10k_mbx_index_len(mbx, head, mbx->tail); /* determine the offset for the start of the region to be pulled */ head = fm10k_fifo_head_offset(&mbx->tx, mbx->pulled); /* update local CRC to include all of the pulled data */ mbx->local = fm10k_fifo_crc(&mbx->tx, head, len, mbx->local); } /** * fm10k_mbx_verify_remote_crc - Verify the CRC is correct for current data * @mbx: pointer to mailbox * * This function will take all data that has been provided from the remote * end and generate a CRC for it. This is stored in mbx->remote. The * CRC for the header is then computed and if the result is non-zero this * is an error and we signal an error dropping all data and resetting the * connection. */ static s32 fm10k_mbx_verify_remote_crc(struct fm10k_mbx_info *mbx) { struct fm10k_mbx_fifo *fifo = &mbx->rx; u16 len = mbx->head_len; u16 offset = fm10k_fifo_tail_offset(fifo, mbx->pushed) - len; u16 crc; /* update the remote CRC if new data has been received */ if (len) mbx->remote = fm10k_fifo_crc(fifo, offset, len, mbx->remote); /* process the full header as we have to validate the CRC */ crc = fm10k_crc_16b(&mbx->mbx_hdr, mbx->remote, 1); /* notify other end if we have a problem */ return crc ? FM10K_MBX_ERR_CRC : 0; } /** * fm10k_mbx_rx_ready - Indicates that a message is ready in the Rx FIFO * @mbx: pointer to mailbox * * This function returns true if there is a message in the Rx FIFO to dequeue. **/ static bool fm10k_mbx_rx_ready(struct fm10k_mbx_info *mbx) { u16 msg_size = fm10k_fifo_head_len(&mbx->rx); return msg_size && (fm10k_fifo_used(&mbx->rx) >= msg_size); } /** * fm10k_mbx_tx_ready - Indicates that the mailbox is in state ready for Tx * @mbx: pointer to mailbox * @len: verify free space is >= this value * * This function returns true if the mailbox is in a state ready to transmit. **/ static bool fm10k_mbx_tx_ready(struct fm10k_mbx_info *mbx, u16 len) { u16 fifo_unused = fm10k_fifo_unused(&mbx->tx); return (mbx->state == FM10K_STATE_OPEN) && (fifo_unused >= len); } /** * fm10k_mbx_tx_complete - Indicates that the Tx FIFO has been emptied * @mbx: pointer to mailbox * * This function returns true if the Tx FIFO is empty. **/ static bool fm10k_mbx_tx_complete(struct fm10k_mbx_info *mbx) { return fm10k_fifo_empty(&mbx->tx); } /** * fm10k_mbx_dequeue_rx - Dequeues the message from the head in the Rx FIFO * @hw: pointer to hardware structure * @mbx: pointer to mailbox * * This function dequeues messages and hands them off to the TLV parser. * It will return the number of messages processed when called. **/ static u16 fm10k_mbx_dequeue_rx(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx) { struct fm10k_mbx_fifo *fifo = &mbx->rx; s32 err; u16 cnt; /* parse Rx messages out of the Rx FIFO to empty it */ for (cnt = 0; !fm10k_fifo_empty(fifo); cnt++) { err = fm10k_tlv_msg_parse(hw, fifo->buffer + fifo->head, mbx, mbx->msg_data); if (err < 0) mbx->rx_parse_err++; fm10k_fifo_head_drop(fifo); } /* shift remaining bytes back to start of FIFO */ memmove(fifo->buffer, fifo->buffer + fifo->tail, mbx->pushed << 2); /* shift head and tail based on the memory we moved */ fifo->tail -= fifo->head; fifo->head = 0; return cnt; } /** * fm10k_mbx_enqueue_tx - Enqueues the message to the tail of the Tx FIFO * @hw: pointer to hardware structure * @mbx: pointer to mailbox * @msg: message array to read * * This function enqueues a message up to the size specified by the length * contained in the first DWORD of the message and will place at the tail * of the FIFO. It will return 0 on success, or a negative value on error. **/ static s32 fm10k_mbx_enqueue_tx(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx, const u32 *msg) { u32 countdown = mbx->timeout; s32 err; switch (mbx->state) { case FM10K_STATE_CLOSED: case FM10K_STATE_DISCONNECT: return FM10K_MBX_ERR_NO_MBX; default: break; } /* enqueue the message on the Tx FIFO */ err = fm10k_fifo_enqueue(&mbx->tx, msg); /* if it failed give the FIFO a chance to drain */ while (err && countdown) { countdown--; udelay(mbx->udelay); mbx->ops.process(hw, mbx); err = fm10k_fifo_enqueue(&mbx->tx, msg); } /* if we failed treat the error */ if (err) { mbx->timeout = 0; mbx->tx_busy++; } /* begin processing message, ignore errors as this is just meant * to start the mailbox flow so we are not concerned if there * is a bad error, or the mailbox is already busy with a request */ if (!mbx->tail_len) mbx->ops.process(hw, mbx); return 0; } /** * fm10k_mbx_read - Copies the mbmem to local message buffer * @hw: pointer to hardware structure * @mbx: pointer to mailbox * * This function copies the message from the mbmem to the message array **/ static s32 fm10k_mbx_read(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx) { /* only allow one reader in here at a time */ if (mbx->mbx_hdr) return FM10K_MBX_ERR_BUSY; /* read to capture initial interrupt bits */ if (fm10k_read_reg(hw, mbx->mbx_reg) & FM10K_MBX_REQ_INTERRUPT) mbx->mbx_lock = FM10K_MBX_ACK; /* write back interrupt bits to clear */ fm10k_write_reg(hw, mbx->mbx_reg, FM10K_MBX_REQ_INTERRUPT | FM10K_MBX_ACK_INTERRUPT); /* read remote header */ mbx->mbx_hdr = fm10k_read_reg(hw, mbx->mbmem_reg ^ mbx->mbmem_len); return 0; } /** * fm10k_mbx_write - Copies the local message buffer to mbmem * @hw: pointer to hardware structure * @mbx: pointer to mailbox * * This function copies the message from the message array to mbmem **/ static void fm10k_mbx_write(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx) { u32 mbmem = mbx->mbmem_reg; /* write new msg header to notify recipient of change */ fm10k_write_reg(hw, mbmem, mbx->mbx_hdr); /* write mailbox to send interrupt */ if (mbx->mbx_lock) fm10k_write_reg(hw, mbx->mbx_reg, mbx->mbx_lock); /* we no longer are using the header so free it */ mbx->mbx_hdr = 0; mbx->mbx_lock = 0; } /** * fm10k_mbx_create_connect_hdr - Generate a connect mailbox header * @mbx: pointer to mailbox * * This function returns a connection mailbox header **/ static void fm10k_mbx_create_connect_hdr(struct fm10k_mbx_info *mbx) { mbx->mbx_lock |= FM10K_MBX_REQ; mbx->mbx_hdr = FM10K_MSG_HDR_FIELD_SET(FM10K_MSG_CONNECT, TYPE) | FM10K_MSG_HDR_FIELD_SET(mbx->head, HEAD) | FM10K_MSG_HDR_FIELD_SET(mbx->rx.size - 1, CONNECT_SIZE); } /** * fm10k_mbx_create_data_hdr - Generate a data mailbox header * @mbx: pointer to mailbox * * This function returns a data mailbox header **/ static void fm10k_mbx_create_data_hdr(struct fm10k_mbx_info *mbx) { u32 hdr = FM10K_MSG_HDR_FIELD_SET(FM10K_MSG_DATA, TYPE) | FM10K_MSG_HDR_FIELD_SET(mbx->tail, TAIL) | FM10K_MSG_HDR_FIELD_SET(mbx->head, HEAD); struct fm10k_mbx_fifo *fifo = &mbx->tx; u16 crc; if (mbx->tail_len) mbx->mbx_lock |= FM10K_MBX_REQ; /* generate CRC for data in flight and header */ crc = fm10k_fifo_crc(fifo, fm10k_fifo_head_offset(fifo, mbx->pulled), mbx->tail_len, mbx->local); crc = fm10k_crc_16b(&hdr, crc, 1); /* load header to memory to be written */ mbx->mbx_hdr = hdr | FM10K_MSG_HDR_FIELD_SET(crc, CRC); } /** * fm10k_mbx_create_disconnect_hdr - Generate a disconnect mailbox header * @mbx: pointer to mailbox * * This function returns a disconnect mailbox header **/ static void fm10k_mbx_create_disconnect_hdr(struct fm10k_mbx_info *mbx) { u32 hdr = FM10K_MSG_HDR_FIELD_SET(FM10K_MSG_DISCONNECT, TYPE) | FM10K_MSG_HDR_FIELD_SET(mbx->tail, TAIL) | FM10K_MSG_HDR_FIELD_SET(mbx->head, HEAD); u16 crc = fm10k_crc_16b(&hdr, mbx->local, 1); mbx->mbx_lock |= FM10K_MBX_ACK; /* load header to memory to be written */ mbx->mbx_hdr = hdr | FM10K_MSG_HDR_FIELD_SET(crc, CRC); } /** * fm10k_mbx_create_fake_disconnect_hdr - Generate a false disconnect mbox hdr * @mbx: pointer to mailbox * * This function creates a fake disconnect header for loading into remote * mailbox header. The primary purpose is to prevent errors on immediate * start up after mbx->connect. **/ static void fm10k_mbx_create_fake_disconnect_hdr(struct fm10k_mbx_info *mbx) { u32 hdr = FM10K_MSG_HDR_FIELD_SET(FM10K_MSG_DISCONNECT, TYPE) | FM10K_MSG_HDR_FIELD_SET(mbx->head, TAIL) | FM10K_MSG_HDR_FIELD_SET(mbx->tail, HEAD); u16 crc = fm10k_crc_16b(&hdr, mbx->local, 1); mbx->mbx_lock |= FM10K_MBX_ACK; /* load header to memory to be written */ mbx->mbx_hdr = hdr | FM10K_MSG_HDR_FIELD_SET(crc, CRC); } /** * fm10k_mbx_create_error_msg - Generate an error message * @mbx: pointer to mailbox * @err: local error encountered * * This function will interpret the error provided by err, and based on * that it may shift the message by 1 DWORD and then place an error header * at the start of the message. **/ static void fm10k_mbx_create_error_msg(struct fm10k_mbx_info *mbx, s32 err) { /* only generate an error message for these types */ switch (err) { case FM10K_MBX_ERR_TAIL: case FM10K_MBX_ERR_HEAD: case FM10K_MBX_ERR_TYPE: case FM10K_MBX_ERR_SIZE: case FM10K_MBX_ERR_RSVD0: case FM10K_MBX_ERR_CRC: break; default: return; } mbx->mbx_lock |= FM10K_MBX_REQ; mbx->mbx_hdr = FM10K_MSG_HDR_FIELD_SET(FM10K_MSG_ERROR, TYPE) | FM10K_MSG_HDR_FIELD_SET(err, ERR_NO) | FM10K_MSG_HDR_FIELD_SET(mbx->head, HEAD); } /** * fm10k_mbx_validate_msg_hdr - Validate common fields in the message header * @mbx: pointer to mailbox * * This function will parse up the fields in the mailbox header and return * an error if the header contains any of a number of invalid configurations * including unrecognized type, invalid route, or a malformed message. **/ static s32 fm10k_mbx_validate_msg_hdr(struct fm10k_mbx_info *mbx) { u16 type, rsvd0, head, tail, size; const u32 *hdr = &mbx->mbx_hdr; type = FM10K_MSG_HDR_FIELD_GET(*hdr, TYPE); rsvd0 = FM10K_MSG_HDR_FIELD_GET(*hdr, RSVD0); tail = FM10K_MSG_HDR_FIELD_GET(*hdr, TAIL); head = FM10K_MSG_HDR_FIELD_GET(*hdr, HEAD); size = FM10K_MSG_HDR_FIELD_GET(*hdr, CONNECT_SIZE); if (rsvd0) return FM10K_MBX_ERR_RSVD0; switch (type) { case FM10K_MSG_DISCONNECT: /* validate that all data has been received */ if (tail != mbx->head) return FM10K_MBX_ERR_TAIL; fallthrough; case FM10K_MSG_DATA: /* validate that head is moving correctly */ if (!head || (head == FM10K_MSG_HDR_MASK(HEAD))) return FM10K_MBX_ERR_HEAD; if (fm10k_mbx_index_len(mbx, head, mbx->tail) > mbx->tail_len) return FM10K_MBX_ERR_HEAD; /* validate that tail is moving correctly */ if (!tail || (tail == FM10K_MSG_HDR_MASK(TAIL))) return FM10K_MBX_ERR_TAIL; if (fm10k_mbx_index_len(mbx, mbx->head, tail) < mbx->mbmem_len) break; return FM10K_MBX_ERR_TAIL; case FM10K_MSG_CONNECT: /* validate size is in range and is power of 2 mask */ if ((size < FM10K_VFMBX_MSG_MTU) || (size & (size + 1))) return FM10K_MBX_ERR_SIZE; fallthrough; case FM10K_MSG_ERROR: if (!head || (head == FM10K_MSG_HDR_MASK(HEAD))) return FM10K_MBX_ERR_HEAD; /* neither create nor error include a tail offset */ if (tail) return FM10K_MBX_ERR_TAIL; break; default: return FM10K_MBX_ERR_TYPE; } return 0; } /** * fm10k_mbx_create_reply - Generate reply based on state and remote head * @hw: pointer to hardware structure * @mbx: pointer to mailbox * @head: acknowledgement number * * This function will generate an outgoing message based on the current * mailbox state and the remote FIFO head. It will return the length * of the outgoing message excluding header on success, and a negative value * on error. **/ static s32 fm10k_mbx_create_reply(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx, u16 head) { switch (mbx->state) { case FM10K_STATE_OPEN: case FM10K_STATE_DISCONNECT: /* update our checksum for the outgoing data */ fm10k_mbx_update_local_crc(mbx, head); /* as long as other end recognizes us keep sending data */ fm10k_mbx_pull_head(hw, mbx, head); /* generate new header based on data */ if (mbx->tail_len || (mbx->state == FM10K_STATE_OPEN)) fm10k_mbx_create_data_hdr(mbx); else fm10k_mbx_create_disconnect_hdr(mbx); break; case FM10K_STATE_CONNECT: /* send disconnect even if we aren't connected */ fm10k_mbx_create_connect_hdr(mbx); break; case FM10K_STATE_CLOSED: /* generate new header based on data */ fm10k_mbx_create_disconnect_hdr(mbx); break; default: break; } return 0; } /** * fm10k_mbx_reset_work- Reset internal pointers for any pending work * @mbx: pointer to mailbox * * This function will reset all internal pointers so any work in progress * is dropped. This call should occur every time we transition from the * open state to the connect state. **/ static void fm10k_mbx_reset_work(struct fm10k_mbx_info *mbx) { u16 len, head, ack; /* reset our outgoing max size back to Rx limits */ mbx->max_size = mbx->rx.size - 1; /* update mbx->pulled to account for tail_len and ack */ head = FM10K_MSG_HDR_FIELD_GET(mbx->mbx_hdr, HEAD); ack = fm10k_mbx_index_len(mbx, head, mbx->tail); mbx->pulled += mbx->tail_len - ack; /* now drop any messages which have started or finished transmitting */ while (fm10k_fifo_head_len(&mbx->tx) && mbx->pulled) { len = fm10k_fifo_head_drop(&mbx->tx); mbx->tx_dropped++; if (mbx->pulled >= len) mbx->pulled -= len; else mbx->pulled = 0; } /* just do a quick resysnc to start of message */ mbx->pushed = 0; mbx->pulled = 0; mbx->tail_len = 0; mbx->head_len = 0; mbx->rx.tail = 0; mbx->rx.head = 0; } /** * fm10k_mbx_update_max_size - Update the max_size and drop any large messages * @mbx: pointer to mailbox * @size: new value for max_size * * This function updates the max_size value and drops any outgoing messages * at the head of the Tx FIFO if they are larger than max_size. It does not * drop all messages, as this is too difficult to parse and remove them from * the FIFO. Instead, rely on the checking to ensure that messages larger * than max_size aren't pushed into the memory buffer. **/ static void fm10k_mbx_update_max_size(struct fm10k_mbx_info *mbx, u16 size) { u16 len; mbx->max_size = size; /* flush any oversized messages from the queue */ for (len = fm10k_fifo_head_len(&mbx->tx); len > size; len = fm10k_fifo_head_len(&mbx->tx)) { fm10k_fifo_head_drop(&mbx->tx); mbx->tx_dropped++; } } /** * fm10k_mbx_connect_reset - Reset following request for reset * @mbx: pointer to mailbox * * This function resets the mailbox to either a disconnected state * or a connect state depending on the current mailbox state **/ static void fm10k_mbx_connect_reset(struct fm10k_mbx_info *mbx) { /* just do a quick resysnc to start of frame */ fm10k_mbx_reset_work(mbx); /* reset CRC seeds */ mbx->local = FM10K_MBX_CRC_SEED; mbx->remote = FM10K_MBX_CRC_SEED; /* we cannot exit connect until the size is good */ if (mbx->state == FM10K_STATE_OPEN) mbx->state = FM10K_STATE_CONNECT; else mbx->state = FM10K_STATE_CLOSED; } /** * fm10k_mbx_process_connect - Process connect header * @hw: pointer to hardware structure * @mbx: pointer to mailbox * * This function will read an incoming connect header and reply with the * appropriate message. It will return a value indicating the number of * data DWORDs on success, or will return a negative value on failure. **/ static s32 fm10k_mbx_process_connect(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx) { const enum fm10k_mbx_state state = mbx->state; const u32 *hdr = &mbx->mbx_hdr; u16 size, head; /* we will need to pull all of the fields for verification */ size = FM10K_MSG_HDR_FIELD_GET(*hdr, CONNECT_SIZE); head = FM10K_MSG_HDR_FIELD_GET(*hdr, HEAD); switch (state) { case FM10K_STATE_DISCONNECT: case FM10K_STATE_OPEN: /* reset any in-progress work */ fm10k_mbx_connect_reset(mbx); break; case FM10K_STATE_CONNECT: /* we cannot exit connect until the size is good */ if (size > mbx->rx.size) { mbx->max_size = mbx->rx.size - 1; } else { /* record the remote system requesting connection */ mbx->state = FM10K_STATE_OPEN; fm10k_mbx_update_max_size(mbx, size); } break; default: break; } /* align our tail index to remote head index */ mbx->tail = head; return fm10k_mbx_create_reply(hw, mbx, head); } /** * fm10k_mbx_process_data - Process data header * @hw: pointer to hardware structure * @mbx: pointer to mailbox * * This function will read an incoming data header and reply with the * appropriate message. It will return a value indicating the number of * data DWORDs on success, or will return a negative value on failure. **/ static s32 fm10k_mbx_process_data(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx) { const u32 *hdr = &mbx->mbx_hdr; u16 head, tail; s32 err; /* we will need to pull all of the fields for verification */ head = FM10K_MSG_HDR_FIELD_GET(*hdr, HEAD); tail = FM10K_MSG_HDR_FIELD_GET(*hdr, TAIL); /* if we are in connect just update our data and go */ if (mbx->state == FM10K_STATE_CONNECT) { mbx->tail = head; mbx->state = FM10K_STATE_OPEN; } /* abort on message size errors */ err = fm10k_mbx_push_tail(hw, mbx, tail); if (err < 0) return err; /* verify the checksum on the incoming data */ err = fm10k_mbx_verify_remote_crc(mbx); if (err) return err; /* process messages if we have received any */ fm10k_mbx_dequeue_rx(hw, mbx); return fm10k_mbx_create_reply(hw, mbx, head); } /** * fm10k_mbx_process_disconnect - Process disconnect header * @hw: pointer to hardware structure * @mbx: pointer to mailbox * * This function will read an incoming disconnect header and reply with the * appropriate message. It will return a value indicating the number of * data DWORDs on success, or will return a negative value on failure. **/ static s32 fm10k_mbx_process_disconnect(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx) { const enum fm10k_mbx_state state = mbx->state; const u32 *hdr = &mbx->mbx_hdr; u16 head; s32 err; /* we will need to pull the header field for verification */ head = FM10K_MSG_HDR_FIELD_GET(*hdr, HEAD); /* We should not be receiving disconnect if Rx is incomplete */ if (mbx->pushed) return FM10K_MBX_ERR_TAIL; /* we have already verified mbx->head == tail so we know this is 0 */ mbx->head_len = 0; /* verify the checksum on the incoming header is correct */ err = fm10k_mbx_verify_remote_crc(mbx); if (err) return err; switch (state) { case FM10K_STATE_DISCONNECT: case FM10K_STATE_OPEN: /* state doesn't change if we still have work to do */ if (!fm10k_mbx_tx_complete(mbx)) break; /* verify the head indicates we completed all transmits */ if (head != mbx->tail) return FM10K_MBX_ERR_HEAD; /* reset any in-progress work */ fm10k_mbx_connect_reset(mbx); break; default: break; } return fm10k_mbx_create_reply(hw, mbx, head); } /** * fm10k_mbx_process_error - Process error header * @hw: pointer to hardware structure * @mbx: pointer to mailbox * * This function will read an incoming error header and reply with the * appropriate message. It will return a value indicating the number of * data DWORDs on success, or will return a negative value on failure. **/ static s32 fm10k_mbx_process_error(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx) { const u32 *hdr = &mbx->mbx_hdr; u16 head; /* we will need to pull all of the fields for verification */ head = FM10K_MSG_HDR_FIELD_GET(*hdr, HEAD); switch (mbx->state) { case FM10K_STATE_OPEN: case FM10K_STATE_DISCONNECT: /* flush any uncompleted work */ fm10k_mbx_reset_work(mbx); /* reset CRC seeds */ mbx->local = FM10K_MBX_CRC_SEED; mbx->remote = FM10K_MBX_CRC_SEED; /* reset tail index and size to prepare for reconnect */ mbx->tail = head; /* if open then reset max_size and go back to connect */ if (mbx->state == FM10K_STATE_OPEN) { mbx->state = FM10K_STATE_CONNECT; break; } /* send a connect message to get data flowing again */ fm10k_mbx_create_connect_hdr(mbx); return 0; default: break; } return fm10k_mbx_create_reply(hw, mbx, mbx->tail); } /** * fm10k_mbx_process - Process mailbox interrupt * @hw: pointer to hardware structure * @mbx: pointer to mailbox * * This function will process incoming mailbox events and generate mailbox * replies. It will return a value indicating the number of DWORDs * transmitted excluding header on success or a negative value on error. **/ static s32 fm10k_mbx_process(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx) { s32 err; /* we do not read mailbox if closed */ if (mbx->state == FM10K_STATE_CLOSED) return 0; /* copy data from mailbox */ err = fm10k_mbx_read(hw, mbx); if (err) return err; /* validate type, source, and destination */ err = fm10k_mbx_validate_msg_hdr(mbx); if (err < 0) goto msg_err; switch (FM10K_MSG_HDR_FIELD_GET(mbx->mbx_hdr, TYPE)) { case FM10K_MSG_CONNECT: err = fm10k_mbx_process_connect(hw, mbx); break; case FM10K_MSG_DATA: err = fm10k_mbx_process_data(hw, mbx); break; case FM10K_MSG_DISCONNECT: err = fm10k_mbx_process_disconnect(hw, mbx); break; case FM10K_MSG_ERROR: err = fm10k_mbx_process_error(hw, mbx); break; default: err = FM10K_MBX_ERR_TYPE; break; } msg_err: /* notify partner of errors on our end */ if (err < 0) fm10k_mbx_create_error_msg(mbx, err); /* copy data from mailbox */ fm10k_mbx_write(hw, mbx); return err; } /** * fm10k_mbx_disconnect - Shutdown mailbox connection * @hw: pointer to hardware structure * @mbx: pointer to mailbox * * This function will shut down the mailbox. It places the mailbox first * in the disconnect state, it then allows up to a predefined timeout for * the mailbox to transition to close on its own. If this does not occur * then the mailbox will be forced into the closed state. * * Any mailbox transactions not completed before calling this function * are not guaranteed to complete and may be dropped. **/ static void fm10k_mbx_disconnect(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx) { int timeout = mbx->timeout ? FM10K_MBX_DISCONNECT_TIMEOUT : 0; /* Place mbx in ready to disconnect state */ mbx->state = FM10K_STATE_DISCONNECT; /* trigger interrupt to start shutdown process */ fm10k_write_reg(hw, mbx->mbx_reg, FM10K_MBX_REQ | FM10K_MBX_INTERRUPT_DISABLE); do { udelay(FM10K_MBX_POLL_DELAY); mbx->ops.process(hw, mbx); timeout -= FM10K_MBX_POLL_DELAY; } while ((timeout > 0) && (mbx->state != FM10K_STATE_CLOSED)); /* in case we didn't close, just force the mailbox into shutdown and * drop all left over messages in the FIFO. */ fm10k_mbx_connect_reset(mbx); fm10k_fifo_drop_all(&mbx->tx); fm10k_write_reg(hw, mbx->mbmem_reg, 0); } /** * fm10k_mbx_connect - Start mailbox connection * @hw: pointer to hardware structure * @mbx: pointer to mailbox * * This function will initiate a mailbox connection. It will populate the * mailbox with a broadcast connect message and then initialize the lock. * This is safe since the connect message is a single DWORD so the mailbox * transaction is guaranteed to be atomic. * * This function will return an error if the mailbox has not been initiated * or is currently in use. **/ static s32 fm10k_mbx_connect(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx) { /* we cannot connect an uninitialized mailbox */ if (!mbx->rx.buffer) return FM10K_MBX_ERR_NO_SPACE; /* we cannot connect an already connected mailbox */ if (mbx->state != FM10K_STATE_CLOSED) return FM10K_MBX_ERR_BUSY; /* mailbox timeout can now become active */ mbx->timeout = FM10K_MBX_INIT_TIMEOUT; /* Place mbx in ready to connect state */ mbx->state = FM10K_STATE_CONNECT; fm10k_mbx_reset_work(mbx); /* initialize header of remote mailbox */ fm10k_mbx_create_fake_disconnect_hdr(mbx); fm10k_write_reg(hw, mbx->mbmem_reg ^ mbx->mbmem_len, mbx->mbx_hdr); /* enable interrupt and notify other party of new message */ mbx->mbx_lock = FM10K_MBX_REQ_INTERRUPT | FM10K_MBX_ACK_INTERRUPT | FM10K_MBX_INTERRUPT_ENABLE; /* generate and load connect header into mailbox */ fm10k_mbx_create_connect_hdr(mbx); fm10k_mbx_write(hw, mbx); return 0; } /** * fm10k_mbx_validate_handlers - Validate layout of message parsing data * @msg_data: handlers for mailbox events * * This function validates the layout of the message parsing data. This * should be mostly static, but it is important to catch any errors that * are made when constructing the parsers. **/ static s32 fm10k_mbx_validate_handlers(const struct fm10k_msg_data *msg_data) { const struct fm10k_tlv_attr *attr; unsigned int id; /* Allow NULL mailboxes that transmit but don't receive */ if (!msg_data) return 0; while (msg_data->id != FM10K_TLV_ERROR) { /* all messages should have a function handler */ if (!msg_data->func) return FM10K_ERR_PARAM; /* parser is optional */ attr = msg_data->attr; if (attr) { while (attr->id != FM10K_TLV_ERROR) { id = attr->id; attr++; /* ID should always be increasing */ if (id >= attr->id) return FM10K_ERR_PARAM; /* ID should fit in results array */ if (id >= FM10K_TLV_RESULTS_MAX) return FM10K_ERR_PARAM; } /* verify terminator is in the list */ if (attr->id != FM10K_TLV_ERROR) return FM10K_ERR_PARAM; } id = msg_data->id; msg_data++; /* ID should always be increasing */ if (id >= msg_data->id) return FM10K_ERR_PARAM; } /* verify terminator is in the list */ if ((msg_data->id != FM10K_TLV_ERROR) || !msg_data->func) return FM10K_ERR_PARAM; return 0; } /** * fm10k_mbx_register_handlers - Register a set of handler ops for mailbox * @mbx: pointer to mailbox * @msg_data: handlers for mailbox events * * This function associates a set of message handling ops with a mailbox. **/ static s32 fm10k_mbx_register_handlers(struct fm10k_mbx_info *mbx, const struct fm10k_msg_data *msg_data) { /* validate layout of handlers before assigning them */ if (fm10k_mbx_validate_handlers(msg_data)) return FM10K_ERR_PARAM; /* initialize the message handlers */ mbx->msg_data = msg_data; return 0; } /** * fm10k_pfvf_mbx_init - Initialize mailbox memory for PF/VF mailbox * @hw: pointer to hardware structure * @mbx: pointer to mailbox * @msg_data: handlers for mailbox events * @id: ID reference for PF as it supports up to 64 PF/VF mailboxes * * This function initializes the mailbox for use. It will split the * buffer provided and use that to populate both the Tx and Rx FIFO by * evenly splitting it. In order to allow for easy masking of head/tail * the value reported in size must be a power of 2 and is reported in * DWORDs, not bytes. Any invalid values will cause the mailbox to return * error. **/ s32 fm10k_pfvf_mbx_init(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx, const struct fm10k_msg_data *msg_data, u8 id) { /* initialize registers */ switch (hw->mac.type) { case fm10k_mac_vf: mbx->mbx_reg = FM10K_VFMBX; mbx->mbmem_reg = FM10K_VFMBMEM(FM10K_VFMBMEM_VF_XOR); break; case fm10k_mac_pf: /* there are only 64 VF <-> PF mailboxes */ if (id < 64) { mbx->mbx_reg = FM10K_MBX(id); mbx->mbmem_reg = FM10K_MBMEM_VF(id, 0); break; } fallthrough; default: return FM10K_MBX_ERR_NO_MBX; } /* start out in closed state */ mbx->state = FM10K_STATE_CLOSED; /* validate layout of handlers before assigning them */ if (fm10k_mbx_validate_handlers(msg_data)) return FM10K_ERR_PARAM; /* initialize the message handlers */ mbx->msg_data = msg_data; /* start mailbox as timed out and let the reset_hw call * set the timeout value to begin communications */ mbx->timeout = 0; mbx->udelay = FM10K_MBX_INIT_DELAY; /* initialize tail and head */ mbx->tail = 1; mbx->head = 1; /* initialize CRC seeds */ mbx->local = FM10K_MBX_CRC_SEED; mbx->remote = FM10K_MBX_CRC_SEED; /* Split buffer for use by Tx/Rx FIFOs */ mbx->max_size = FM10K_MBX_MSG_MAX_SIZE; mbx->mbmem_len = FM10K_VFMBMEM_VF_XOR; /* initialize the FIFOs, sizes are in 4 byte increments */ fm10k_fifo_init(&mbx->tx, mbx->buffer, FM10K_MBX_TX_BUFFER_SIZE); fm10k_fifo_init(&mbx->rx, &mbx->buffer[FM10K_MBX_TX_BUFFER_SIZE], FM10K_MBX_RX_BUFFER_SIZE); /* initialize function pointers */ mbx->ops.connect = fm10k_mbx_connect; mbx->ops.disconnect = fm10k_mbx_disconnect; mbx->ops.rx_ready = fm10k_mbx_rx_ready; mbx->ops.tx_ready = fm10k_mbx_tx_ready; mbx->ops.tx_complete = fm10k_mbx_tx_complete; mbx->ops.enqueue_tx = fm10k_mbx_enqueue_tx; mbx->ops.process = fm10k_mbx_process; mbx->ops.register_handlers = fm10k_mbx_register_handlers; return 0; } /** * fm10k_sm_mbx_create_data_hdr - Generate a mailbox header for local FIFO * @mbx: pointer to mailbox * * This function returns a data mailbox header **/ static void fm10k_sm_mbx_create_data_hdr(struct fm10k_mbx_info *mbx) { if (mbx->tail_len) mbx->mbx_lock |= FM10K_MBX_REQ; mbx->mbx_hdr = FM10K_MSG_HDR_FIELD_SET(mbx->tail, SM_TAIL) | FM10K_MSG_HDR_FIELD_SET(mbx->remote, SM_VER) | FM10K_MSG_HDR_FIELD_SET(mbx->head, SM_HEAD); } /** * fm10k_sm_mbx_create_connect_hdr - Generate a mailbox header for local FIFO * @mbx: pointer to mailbox * @err: error flags to report if any * * This function returns a connection mailbox header **/ static void fm10k_sm_mbx_create_connect_hdr(struct fm10k_mbx_info *mbx, u8 err) { if (mbx->local) mbx->mbx_lock |= FM10K_MBX_REQ; mbx->mbx_hdr = FM10K_MSG_HDR_FIELD_SET(mbx->tail, SM_TAIL) | FM10K_MSG_HDR_FIELD_SET(mbx->remote, SM_VER) | FM10K_MSG_HDR_FIELD_SET(mbx->head, SM_HEAD) | FM10K_MSG_HDR_FIELD_SET(err, SM_ERR); } /** * fm10k_sm_mbx_connect_reset - Reset following request for reset * @mbx: pointer to mailbox * * This function resets the mailbox to a just connected state **/ static void fm10k_sm_mbx_connect_reset(struct fm10k_mbx_info *mbx) { /* flush any uncompleted work */ fm10k_mbx_reset_work(mbx); /* set local version to max and remote version to 0 */ mbx->local = FM10K_SM_MBX_VERSION; mbx->remote = 0; /* initialize tail and head */ mbx->tail = 1; mbx->head = 1; /* reset state back to connect */ mbx->state = FM10K_STATE_CONNECT; } /** * fm10k_sm_mbx_connect - Start switch manager mailbox connection * @hw: pointer to hardware structure * @mbx: pointer to mailbox * * This function will initiate a mailbox connection with the switch * manager. To do this it will first disconnect the mailbox, and then * reconnect it in order to complete a reset of the mailbox. * * This function will return an error if the mailbox has not been initiated * or is currently in use. **/ static s32 fm10k_sm_mbx_connect(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx) { /* we cannot connect an uninitialized mailbox */ if (!mbx->rx.buffer) return FM10K_MBX_ERR_NO_SPACE; /* we cannot connect an already connected mailbox */ if (mbx->state != FM10K_STATE_CLOSED) return FM10K_MBX_ERR_BUSY; /* mailbox timeout can now become active */ mbx->timeout = FM10K_MBX_INIT_TIMEOUT; /* Place mbx in ready to connect state */ mbx->state = FM10K_STATE_CONNECT; mbx->max_size = FM10K_MBX_MSG_MAX_SIZE; /* reset interface back to connect */ fm10k_sm_mbx_connect_reset(mbx); /* enable interrupt and notify other party of new message */ mbx->mbx_lock = FM10K_MBX_REQ_INTERRUPT | FM10K_MBX_ACK_INTERRUPT | FM10K_MBX_INTERRUPT_ENABLE; /* generate and load connect header into mailbox */ fm10k_sm_mbx_create_connect_hdr(mbx, 0); fm10k_mbx_write(hw, mbx); return 0; } /** * fm10k_sm_mbx_disconnect - Shutdown mailbox connection * @hw: pointer to hardware structure * @mbx: pointer to mailbox * * This function will shut down the mailbox. It places the mailbox first * in the disconnect state, it then allows up to a predefined timeout for * the mailbox to transition to close on its own. If this does not occur * then the mailbox will be forced into the closed state. * * Any mailbox transactions not completed before calling this function * are not guaranteed to complete and may be dropped. **/ static void fm10k_sm_mbx_disconnect(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx) { int timeout = mbx->timeout ? FM10K_MBX_DISCONNECT_TIMEOUT : 0; /* Place mbx in ready to disconnect state */ mbx->state = FM10K_STATE_DISCONNECT; /* trigger interrupt to start shutdown process */ fm10k_write_reg(hw, mbx->mbx_reg, FM10K_MBX_REQ | FM10K_MBX_INTERRUPT_DISABLE); do { udelay(FM10K_MBX_POLL_DELAY); mbx->ops.process(hw, mbx); timeout -= FM10K_MBX_POLL_DELAY; } while ((timeout > 0) && (mbx->state != FM10K_STATE_CLOSED)); /* in case we didn't close just force the mailbox into shutdown */ mbx->state = FM10K_STATE_CLOSED; mbx->remote = 0; fm10k_mbx_reset_work(mbx); fm10k_fifo_drop_all(&mbx->tx); fm10k_write_reg(hw, mbx->mbmem_reg, 0); } /** * fm10k_sm_mbx_validate_fifo_hdr - Validate fields in the remote FIFO header * @mbx: pointer to mailbox * * This function will parse up the fields in the mailbox header and return * an error if the header contains any of a number of invalid configurations * including unrecognized offsets or version numbers. **/ static s32 fm10k_sm_mbx_validate_fifo_hdr(struct fm10k_mbx_info *mbx) { const u32 *hdr = &mbx->mbx_hdr; u16 tail, head, ver; tail = FM10K_MSG_HDR_FIELD_GET(*hdr, SM_TAIL); ver = FM10K_MSG_HDR_FIELD_GET(*hdr, SM_VER); head = FM10K_MSG_HDR_FIELD_GET(*hdr, SM_HEAD); switch (ver) { case 0: break; case FM10K_SM_MBX_VERSION: if (!head || head > FM10K_SM_MBX_FIFO_LEN) return FM10K_MBX_ERR_HEAD; if (!tail || tail > FM10K_SM_MBX_FIFO_LEN) return FM10K_MBX_ERR_TAIL; if (mbx->tail < head) head += mbx->mbmem_len - 1; if (tail < mbx->head) tail += mbx->mbmem_len - 1; if (fm10k_mbx_index_len(mbx, head, mbx->tail) > mbx->tail_len) return FM10K_MBX_ERR_HEAD; if (fm10k_mbx_index_len(mbx, mbx->head, tail) < mbx->mbmem_len) break; return FM10K_MBX_ERR_TAIL; default: return FM10K_MBX_ERR_SRC; } return 0; } /** * fm10k_sm_mbx_process_error - Process header with error flag set * @mbx: pointer to mailbox * * This function is meant to respond to a request where the error flag * is set. As a result we will terminate a connection if one is present * and fall back into the reset state with a connection header of version * 0 (RESET). **/ static void fm10k_sm_mbx_process_error(struct fm10k_mbx_info *mbx) { const enum fm10k_mbx_state state = mbx->state; switch (state) { case FM10K_STATE_DISCONNECT: /* if there is an error just disconnect */ mbx->remote = 0; break; case FM10K_STATE_OPEN: /* flush any uncompleted work */ fm10k_sm_mbx_connect_reset(mbx); break; case FM10K_STATE_CONNECT: /* try connecting at lower version */ if (mbx->remote) { while (mbx->local > 1) mbx->local--; mbx->remote = 0; } break; default: break; } fm10k_sm_mbx_create_connect_hdr(mbx, 0); } /** * fm10k_sm_mbx_create_error_msg - Process an error in FIFO header * @mbx: pointer to mailbox * @err: local error encountered * * This function will interpret the error provided by err, and based on * that it may set the error bit in the local message header **/ static void fm10k_sm_mbx_create_error_msg(struct fm10k_mbx_info *mbx, s32 err) { /* only generate an error message for these types */ switch (err) { case FM10K_MBX_ERR_TAIL: case FM10K_MBX_ERR_HEAD: case FM10K_MBX_ERR_SRC: case FM10K_MBX_ERR_SIZE: case FM10K_MBX_ERR_RSVD0: break; default: return; } /* process it as though we received an error, and send error reply */ fm10k_sm_mbx_process_error(mbx); fm10k_sm_mbx_create_connect_hdr(mbx, 1); } /** * fm10k_sm_mbx_receive - Take message from Rx mailbox FIFO and put it in Rx * @hw: pointer to hardware structure * @mbx: pointer to mailbox * @tail: tail index of message * * This function will dequeue one message from the Rx switch manager mailbox * FIFO and place it in the Rx mailbox FIFO for processing by software. **/ static s32 fm10k_sm_mbx_receive(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx, u16 tail) { /* reduce length by 1 to convert to a mask */ u16 mbmem_len = mbx->mbmem_len - 1; s32 err; /* push tail in front of head */ if (tail < mbx->head) tail += mbmem_len; /* copy data to the Rx FIFO */ err = fm10k_mbx_push_tail(hw, mbx, tail); if (err < 0) return err; /* process messages if we have received any */ fm10k_mbx_dequeue_rx(hw, mbx); /* guarantee head aligns with the end of the last message */ mbx->head = fm10k_mbx_head_sub(mbx, mbx->pushed); mbx->pushed = 0; /* clear any extra bits left over since index adds 1 extra bit */ if (mbx->head > mbmem_len) mbx->head -= mbmem_len; return err; } /** * fm10k_sm_mbx_transmit - Take message from Tx and put it in Tx mailbox FIFO * @hw: pointer to hardware structure * @mbx: pointer to mailbox * @head: head index of message * * This function will dequeue one message from the Tx mailbox FIFO and place * it in the Tx switch manager mailbox FIFO for processing by hardware. **/ static void fm10k_sm_mbx_transmit(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx, u16 head) { struct fm10k_mbx_fifo *fifo = &mbx->tx; /* reduce length by 1 to convert to a mask */ u16 mbmem_len = mbx->mbmem_len - 1; u16 tail_len, len = 0; /* push head behind tail */ if (mbx->tail < head) head += mbmem_len; fm10k_mbx_pull_head(hw, mbx, head); /* determine msg aligned offset for end of buffer */ do { u32 *msg; msg = fifo->buffer + fm10k_fifo_head_offset(fifo, len); tail_len = len; len += FM10K_TLV_DWORD_LEN(*msg); } while ((len <= mbx->tail_len) && (len < mbmem_len)); /* guarantee we stop on a message boundary */ if (mbx->tail_len > tail_len) { mbx->tail = fm10k_mbx_tail_sub(mbx, mbx->tail_len - tail_len); mbx->tail_len = tail_len; } /* clear any extra bits left over since index adds 1 extra bit */ if (mbx->tail > mbmem_len) mbx->tail -= mbmem_len; } /** * fm10k_sm_mbx_create_reply - Generate reply based on state and remote head * @hw: pointer to hardware structure * @mbx: pointer to mailbox * @head: acknowledgement number * * This function will generate an outgoing message based on the current * mailbox state and the remote FIFO head. It will return the length * of the outgoing message excluding header on success, and a negative value * on error. **/ static void fm10k_sm_mbx_create_reply(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx, u16 head) { switch (mbx->state) { case FM10K_STATE_OPEN: case FM10K_STATE_DISCONNECT: /* flush out Tx data */ fm10k_sm_mbx_transmit(hw, mbx, head); /* generate new header based on data */ if (mbx->tail_len || (mbx->state == FM10K_STATE_OPEN)) { fm10k_sm_mbx_create_data_hdr(mbx); } else { mbx->remote = 0; fm10k_sm_mbx_create_connect_hdr(mbx, 0); } break; case FM10K_STATE_CONNECT: case FM10K_STATE_CLOSED: fm10k_sm_mbx_create_connect_hdr(mbx, 0); break; default: break; } } /** * fm10k_sm_mbx_process_reset - Process header with version == 0 (RESET) * @hw: pointer to hardware structure * @mbx: pointer to mailbox * * This function is meant to respond to a request where the version data * is set to 0. As such we will either terminate the connection or go * into the connect state in order to re-establish the connection. This * function can also be used to respond to an error as the connection * resetting would also be a means of dealing with errors. **/ static s32 fm10k_sm_mbx_process_reset(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx) { s32 err = 0; const enum fm10k_mbx_state state = mbx->state; switch (state) { case FM10K_STATE_DISCONNECT: /* drop remote connections and disconnect */ mbx->state = FM10K_STATE_CLOSED; mbx->remote = 0; mbx->local = 0; break; case FM10K_STATE_OPEN: /* flush any incomplete work */ fm10k_sm_mbx_connect_reset(mbx); err = FM10K_ERR_RESET_REQUESTED; break; case FM10K_STATE_CONNECT: /* Update remote value to match local value */ mbx->remote = mbx->local; break; default: break; } fm10k_sm_mbx_create_reply(hw, mbx, mbx->tail); return err; } /** * fm10k_sm_mbx_process_version_1 - Process header with version == 1 * @hw: pointer to hardware structure * @mbx: pointer to mailbox * * This function is meant to process messages received when the remote * mailbox is active. **/ static s32 fm10k_sm_mbx_process_version_1(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx) { const u32 *hdr = &mbx->mbx_hdr; u16 head, tail; s32 len; /* pull all fields needed for verification */ tail = FM10K_MSG_HDR_FIELD_GET(*hdr, SM_TAIL); head = FM10K_MSG_HDR_FIELD_GET(*hdr, SM_HEAD); /* if we are in connect and wanting version 1 then start up and go */ if (mbx->state == FM10K_STATE_CONNECT) { if (!mbx->remote) goto send_reply; if (mbx->remote != 1) return FM10K_MBX_ERR_SRC; mbx->state = FM10K_STATE_OPEN; } do { /* abort on message size errors */ len = fm10k_sm_mbx_receive(hw, mbx, tail); if (len < 0) return len; /* continue until we have flushed the Rx FIFO */ } while (len); send_reply: fm10k_sm_mbx_create_reply(hw, mbx, head); return 0; } /** * fm10k_sm_mbx_process - Process switch manager mailbox interrupt * @hw: pointer to hardware structure * @mbx: pointer to mailbox * * This function will process incoming mailbox events and generate mailbox * replies. It will return a value indicating the number of DWORDs * transmitted excluding header on success or a negative value on error. **/ static s32 fm10k_sm_mbx_process(struct fm10k_hw *hw, struct fm10k_mbx_info *mbx) { s32 err; /* we do not read mailbox if closed */ if (mbx->state == FM10K_STATE_CLOSED) return 0; /* retrieve data from switch manager */ err = fm10k_mbx_read(hw, mbx); if (err) return err; err = fm10k_sm_mbx_validate_fifo_hdr(mbx); if (err < 0) goto fifo_err; if (FM10K_MSG_HDR_FIELD_GET(mbx->mbx_hdr, SM_ERR)) { fm10k_sm_mbx_process_error(mbx); goto fifo_err; } switch (FM10K_MSG_HDR_FIELD_GET(mbx->mbx_hdr, SM_VER)) { case 0: err = fm10k_sm_mbx_process_reset(hw, mbx); break; case FM10K_SM_MBX_VERSION: err = fm10k_sm_mbx_process_version_1(hw, mbx); break; } fifo_err: if (err < 0) fm10k_sm_mbx_create_error_msg(mbx, err); /* report data to switch manager */ fm10k_mbx_write(hw, mbx); return err; } /** * fm10k_sm_mbx_init - Initialize mailbox memory for PF/SM mailbox * @hw: pointer to hardware structure * @mbx: pointer to mailbox * @msg_data: handlers for mailbox events * * This function initializes the PF/SM mailbox for use. It will split the * buffer provided and use that to populate both the Tx and Rx FIFO by * evenly splitting it. In order to allow for easy masking of head/tail * the value reported in size must be a power of 2 and is reported in * DWORDs, not bytes. Any invalid values will cause the mailbox to return * error. **/ s32 fm10k_sm_mbx_init(struct fm10k_hw __always_unused *hw, struct fm10k_mbx_info *mbx, const struct fm10k_msg_data *msg_data) { mbx->mbx_reg = FM10K_GMBX; mbx->mbmem_reg = FM10K_MBMEM_PF(0); /* start out in closed state */ mbx->state = FM10K_STATE_CLOSED; /* validate layout of handlers before assigning them */ if (fm10k_mbx_validate_handlers(msg_data)) return FM10K_ERR_PARAM; /* initialize the message handlers */ mbx->msg_data = msg_data; /* start mailbox as timed out and let the reset_hw call * set the timeout value to begin communications */ mbx->timeout = 0; mbx->udelay = FM10K_MBX_INIT_DELAY; /* Split buffer for use by Tx/Rx FIFOs */ mbx->max_size = FM10K_MBX_MSG_MAX_SIZE; mbx->mbmem_len = FM10K_MBMEM_PF_XOR; /* initialize the FIFOs, sizes are in 4 byte increments */ fm10k_fifo_init(&mbx->tx, mbx->buffer, FM10K_MBX_TX_BUFFER_SIZE); fm10k_fifo_init(&mbx->rx, &mbx->buffer[FM10K_MBX_TX_BUFFER_SIZE], FM10K_MBX_RX_BUFFER_SIZE); /* initialize function pointers */ mbx->ops.connect = fm10k_sm_mbx_connect; mbx->ops.disconnect = fm10k_sm_mbx_disconnect; mbx->ops.rx_ready = fm10k_mbx_rx_ready; mbx->ops.tx_ready = fm10k_mbx_tx_ready; mbx->ops.tx_complete = fm10k_mbx_tx_complete; mbx->ops.enqueue_tx = fm10k_mbx_enqueue_tx; mbx->ops.process = fm10k_sm_mbx_process; mbx->ops.register_handlers = fm10k_mbx_register_handlers; return 0; }
linux-master
drivers/net/ethernet/intel/fm10k/fm10k_mbx.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2013 - 2019 Intel Corporation. */ #include "fm10k_vf.h" /** * fm10k_stop_hw_vf - Stop Tx/Rx units * @hw: pointer to hardware structure * **/ static s32 fm10k_stop_hw_vf(struct fm10k_hw *hw) { u8 *perm_addr = hw->mac.perm_addr; u32 bal = 0, bah = 0, tdlen; s32 err; u16 i; /* we need to disable the queues before taking further steps */ err = fm10k_stop_hw_generic(hw); if (err && err != FM10K_ERR_REQUESTS_PENDING) return err; /* If permanent address is set then we need to restore it */ if (is_valid_ether_addr(perm_addr)) { bal = (((u32)perm_addr[3]) << 24) | (((u32)perm_addr[4]) << 16) | (((u32)perm_addr[5]) << 8); bah = (((u32)0xFF) << 24) | (((u32)perm_addr[0]) << 16) | (((u32)perm_addr[1]) << 8) | ((u32)perm_addr[2]); } /* restore default itr_scale for next VF initialization */ tdlen = hw->mac.itr_scale << FM10K_TDLEN_ITR_SCALE_SHIFT; /* The queues have already been disabled so we just need to * update their base address registers */ for (i = 0; i < hw->mac.max_queues; i++) { fm10k_write_reg(hw, FM10K_TDBAL(i), bal); fm10k_write_reg(hw, FM10K_TDBAH(i), bah); fm10k_write_reg(hw, FM10K_RDBAL(i), bal); fm10k_write_reg(hw, FM10K_RDBAH(i), bah); /* Restore ITR scale in software-defined mechanism in TDLEN * for next VF initialization. See definition of * FM10K_TDLEN_ITR_SCALE_SHIFT for more details on the use of * TDLEN here. */ fm10k_write_reg(hw, FM10K_TDLEN(i), tdlen); } return err; } /** * fm10k_reset_hw_vf - VF hardware reset * @hw: pointer to hardware structure * * This function should return the hardware to a state similar to the * one it is in after just being initialized. **/ static s32 fm10k_reset_hw_vf(struct fm10k_hw *hw) { s32 err; /* shut down queues we own and reset DMA configuration */ err = fm10k_stop_hw_vf(hw); if (err == FM10K_ERR_REQUESTS_PENDING) hw->mac.reset_while_pending++; else if (err) return err; /* Inititate VF reset */ fm10k_write_reg(hw, FM10K_VFCTRL, FM10K_VFCTRL_RST); /* Flush write and allow 100us for reset to complete */ fm10k_write_flush(hw); udelay(FM10K_RESET_TIMEOUT); /* Clear reset bit and verify it was cleared */ fm10k_write_reg(hw, FM10K_VFCTRL, 0); if (fm10k_read_reg(hw, FM10K_VFCTRL) & FM10K_VFCTRL_RST) return FM10K_ERR_RESET_FAILED; return 0; } /** * fm10k_init_hw_vf - VF hardware initialization * @hw: pointer to hardware structure * **/ static s32 fm10k_init_hw_vf(struct fm10k_hw *hw) { u32 tqdloc, tqdloc0 = ~fm10k_read_reg(hw, FM10K_TQDLOC(0)); s32 err; u16 i; /* verify we have at least 1 queue */ if (!~fm10k_read_reg(hw, FM10K_TXQCTL(0)) || !~fm10k_read_reg(hw, FM10K_RXQCTL(0))) { err = FM10K_ERR_NO_RESOURCES; goto reset_max_queues; } /* determine how many queues we have */ for (i = 1; tqdloc0 && (i < FM10K_MAX_QUEUES_POOL); i++) { /* verify the Descriptor cache offsets are increasing */ tqdloc = ~fm10k_read_reg(hw, FM10K_TQDLOC(i)); if (!tqdloc || (tqdloc == tqdloc0)) break; /* check to verify the PF doesn't own any of our queues */ if (!~fm10k_read_reg(hw, FM10K_TXQCTL(i)) || !~fm10k_read_reg(hw, FM10K_RXQCTL(i))) break; } /* shut down queues we own and reset DMA configuration */ err = fm10k_disable_queues_generic(hw, i); if (err) goto reset_max_queues; /* record maximum queue count */ hw->mac.max_queues = i; /* fetch default VLAN and ITR scale */ hw->mac.default_vid = (fm10k_read_reg(hw, FM10K_TXQCTL(0)) & FM10K_TXQCTL_VID_MASK) >> FM10K_TXQCTL_VID_SHIFT; /* Read the ITR scale from TDLEN. See the definition of * FM10K_TDLEN_ITR_SCALE_SHIFT for more information about how TDLEN is * used here. */ hw->mac.itr_scale = (fm10k_read_reg(hw, FM10K_TDLEN(0)) & FM10K_TDLEN_ITR_SCALE_MASK) >> FM10K_TDLEN_ITR_SCALE_SHIFT; return 0; reset_max_queues: hw->mac.max_queues = 0; return err; } /* This structure defines the attibutes to be parsed below */ const struct fm10k_tlv_attr fm10k_mac_vlan_msg_attr[] = { FM10K_TLV_ATTR_U32(FM10K_MAC_VLAN_MSG_VLAN), FM10K_TLV_ATTR_BOOL(FM10K_MAC_VLAN_MSG_SET), FM10K_TLV_ATTR_MAC_ADDR(FM10K_MAC_VLAN_MSG_MAC), FM10K_TLV_ATTR_MAC_ADDR(FM10K_MAC_VLAN_MSG_DEFAULT_MAC), FM10K_TLV_ATTR_MAC_ADDR(FM10K_MAC_VLAN_MSG_MULTICAST), FM10K_TLV_ATTR_LAST }; /** * fm10k_update_vlan_vf - Update status of VLAN ID in VLAN filter table * @hw: pointer to hardware structure * @vid: VLAN ID to add to table * @vsi: Reserved, should always be 0 * @set: Indicates if this is a set or clear operation * * This function adds or removes the corresponding VLAN ID from the VLAN * filter table for this VF. **/ static s32 fm10k_update_vlan_vf(struct fm10k_hw *hw, u32 vid, u8 vsi, bool set) { struct fm10k_mbx_info *mbx = &hw->mbx; u32 msg[4]; /* verify the index is not set */ if (vsi) return FM10K_ERR_PARAM; /* clever trick to verify reserved bits in both vid and length */ if ((vid << 16 | vid) >> 28) return FM10K_ERR_PARAM; /* encode set bit into the VLAN ID */ if (!set) vid |= FM10K_VLAN_CLEAR; /* generate VLAN request */ fm10k_tlv_msg_init(msg, FM10K_VF_MSG_ID_MAC_VLAN); fm10k_tlv_attr_put_u32(msg, FM10K_MAC_VLAN_MSG_VLAN, vid); /* load onto outgoing mailbox */ return mbx->ops.enqueue_tx(hw, mbx, msg); } /** * fm10k_msg_mac_vlan_vf - Read device MAC address from mailbox message * @hw: pointer to the HW structure * @results: Attributes for message * @mbx: unused mailbox data * * This function should determine the MAC address for the VF **/ s32 fm10k_msg_mac_vlan_vf(struct fm10k_hw *hw, u32 **results, struct fm10k_mbx_info __always_unused *mbx) { u8 perm_addr[ETH_ALEN]; u16 vid; s32 err; /* record MAC address requested */ err = fm10k_tlv_attr_get_mac_vlan( results[FM10K_MAC_VLAN_MSG_DEFAULT_MAC], perm_addr, &vid); if (err) return err; ether_addr_copy(hw->mac.perm_addr, perm_addr); hw->mac.default_vid = vid & (FM10K_VLAN_TABLE_VID_MAX - 1); hw->mac.vlan_override = !!(vid & FM10K_VLAN_OVERRIDE); return 0; } /** * fm10k_read_mac_addr_vf - Read device MAC address * @hw: pointer to the HW structure * * This function should determine the MAC address for the VF **/ static s32 fm10k_read_mac_addr_vf(struct fm10k_hw *hw) { u8 perm_addr[ETH_ALEN]; u32 base_addr; base_addr = fm10k_read_reg(hw, FM10K_TDBAL(0)); /* last byte should be 0 */ if (base_addr << 24) return FM10K_ERR_INVALID_MAC_ADDR; perm_addr[3] = (u8)(base_addr >> 24); perm_addr[4] = (u8)(base_addr >> 16); perm_addr[5] = (u8)(base_addr >> 8); base_addr = fm10k_read_reg(hw, FM10K_TDBAH(0)); /* first byte should be all 1's */ if ((~base_addr) >> 24) return FM10K_ERR_INVALID_MAC_ADDR; perm_addr[0] = (u8)(base_addr >> 16); perm_addr[1] = (u8)(base_addr >> 8); perm_addr[2] = (u8)(base_addr); ether_addr_copy(hw->mac.perm_addr, perm_addr); ether_addr_copy(hw->mac.addr, perm_addr); return 0; } /** * fm10k_update_uc_addr_vf - Update device unicast addresses * @hw: pointer to the HW structure * @glort: unused * @mac: MAC address to add/remove from table * @vid: VLAN ID to add/remove from table * @add: Indicates if this is an add or remove operation * @flags: flags field to indicate add and secure - unused * * This function is used to add or remove unicast MAC addresses for * the VF. **/ static s32 fm10k_update_uc_addr_vf(struct fm10k_hw *hw, u16 __always_unused glort, const u8 *mac, u16 vid, bool add, u8 __always_unused flags) { struct fm10k_mbx_info *mbx = &hw->mbx; u32 msg[7]; /* verify VLAN ID is valid */ if (vid >= FM10K_VLAN_TABLE_VID_MAX) return FM10K_ERR_PARAM; /* verify MAC address is valid */ if (!is_valid_ether_addr(mac)) return FM10K_ERR_PARAM; /* verify we are not locked down on the MAC address */ if (is_valid_ether_addr(hw->mac.perm_addr) && !ether_addr_equal(hw->mac.perm_addr, mac)) return FM10K_ERR_PARAM; /* add bit to notify us if this is a set or clear operation */ if (!add) vid |= FM10K_VLAN_CLEAR; /* generate VLAN request */ fm10k_tlv_msg_init(msg, FM10K_VF_MSG_ID_MAC_VLAN); fm10k_tlv_attr_put_mac_vlan(msg, FM10K_MAC_VLAN_MSG_MAC, mac, vid); /* load onto outgoing mailbox */ return mbx->ops.enqueue_tx(hw, mbx, msg); } /** * fm10k_update_mc_addr_vf - Update device multicast addresses * @hw: pointer to the HW structure * @glort: unused * @mac: MAC address to add/remove from table * @vid: VLAN ID to add/remove from table * @add: Indicates if this is an add or remove operation * * This function is used to add or remove multicast MAC addresses for * the VF. **/ static s32 fm10k_update_mc_addr_vf(struct fm10k_hw *hw, u16 __always_unused glort, const u8 *mac, u16 vid, bool add) { struct fm10k_mbx_info *mbx = &hw->mbx; u32 msg[7]; /* verify VLAN ID is valid */ if (vid >= FM10K_VLAN_TABLE_VID_MAX) return FM10K_ERR_PARAM; /* verify multicast address is valid */ if (!is_multicast_ether_addr(mac)) return FM10K_ERR_PARAM; /* add bit to notify us if this is a set or clear operation */ if (!add) vid |= FM10K_VLAN_CLEAR; /* generate VLAN request */ fm10k_tlv_msg_init(msg, FM10K_VF_MSG_ID_MAC_VLAN); fm10k_tlv_attr_put_mac_vlan(msg, FM10K_MAC_VLAN_MSG_MULTICAST, mac, vid); /* load onto outgoing mailbox */ return mbx->ops.enqueue_tx(hw, mbx, msg); } /** * fm10k_update_int_moderator_vf - Request update of interrupt moderator list * @hw: pointer to hardware structure * * This function will issue a request to the PF to rescan our MSI-X table * and to update the interrupt moderator linked list. **/ static void fm10k_update_int_moderator_vf(struct fm10k_hw *hw) { struct fm10k_mbx_info *mbx = &hw->mbx; u32 msg[1]; /* generate MSI-X request */ fm10k_tlv_msg_init(msg, FM10K_VF_MSG_ID_MSIX); /* load onto outgoing mailbox */ mbx->ops.enqueue_tx(hw, mbx, msg); } /* This structure defines the attibutes to be parsed below */ const struct fm10k_tlv_attr fm10k_lport_state_msg_attr[] = { FM10K_TLV_ATTR_BOOL(FM10K_LPORT_STATE_MSG_DISABLE), FM10K_TLV_ATTR_U8(FM10K_LPORT_STATE_MSG_XCAST_MODE), FM10K_TLV_ATTR_BOOL(FM10K_LPORT_STATE_MSG_READY), FM10K_TLV_ATTR_LAST }; /** * fm10k_msg_lport_state_vf - Message handler for lport_state message from PF * @hw: Pointer to hardware structure * @results: pointer array containing parsed data * @mbx: Pointer to mailbox information structure * * This handler is meant to capture the indication from the PF that we * are ready to bring up the interface. **/ s32 fm10k_msg_lport_state_vf(struct fm10k_hw *hw, u32 **results, struct fm10k_mbx_info __always_unused *mbx) { hw->mac.dglort_map = !results[FM10K_LPORT_STATE_MSG_READY] ? FM10K_DGLORTMAP_NONE : FM10K_DGLORTMAP_ZERO; return 0; } /** * fm10k_update_lport_state_vf - Update device state in lower device * @hw: pointer to the HW structure * @glort: unused * @count: number of logical ports to enable - unused (always 1) * @enable: boolean value indicating if this is an enable or disable request * * Notify the lower device of a state change. If the lower device is * enabled we can add filters, if it is disabled all filters for this * logical port are flushed. **/ static s32 fm10k_update_lport_state_vf(struct fm10k_hw *hw, u16 __always_unused glort, u16 __always_unused count, bool enable) { struct fm10k_mbx_info *mbx = &hw->mbx; u32 msg[2]; /* reset glort mask 0 as we have to wait to be enabled */ hw->mac.dglort_map = FM10K_DGLORTMAP_NONE; /* generate port state request */ fm10k_tlv_msg_init(msg, FM10K_VF_MSG_ID_LPORT_STATE); if (!enable) fm10k_tlv_attr_put_bool(msg, FM10K_LPORT_STATE_MSG_DISABLE); /* load onto outgoing mailbox */ return mbx->ops.enqueue_tx(hw, mbx, msg); } /** * fm10k_update_xcast_mode_vf - Request update of multicast mode * @hw: pointer to hardware structure * @glort: unused * @mode: integer value indicating mode being requested * * This function will attempt to request a higher mode for the port * so that it can enable either multicast, multicast promiscuous, or * promiscuous mode of operation. **/ static s32 fm10k_update_xcast_mode_vf(struct fm10k_hw *hw, u16 __always_unused glort, u8 mode) { struct fm10k_mbx_info *mbx = &hw->mbx; u32 msg[3]; if (mode > FM10K_XCAST_MODE_NONE) return FM10K_ERR_PARAM; /* generate message requesting to change xcast mode */ fm10k_tlv_msg_init(msg, FM10K_VF_MSG_ID_LPORT_STATE); fm10k_tlv_attr_put_u8(msg, FM10K_LPORT_STATE_MSG_XCAST_MODE, mode); /* load onto outgoing mailbox */ return mbx->ops.enqueue_tx(hw, mbx, msg); } /** * fm10k_update_hw_stats_vf - Updates hardware related statistics of VF * @hw: pointer to hardware structure * @stats: pointer to statistics structure * * This function collects and aggregates per queue hardware statistics. **/ static void fm10k_update_hw_stats_vf(struct fm10k_hw *hw, struct fm10k_hw_stats *stats) { fm10k_update_hw_stats_q(hw, stats->q, 0, hw->mac.max_queues); } /** * fm10k_rebind_hw_stats_vf - Resets base for hardware statistics of VF * @hw: pointer to hardware structure * @stats: pointer to the stats structure to update * * This function resets the base for queue hardware statistics. **/ static void fm10k_rebind_hw_stats_vf(struct fm10k_hw *hw, struct fm10k_hw_stats *stats) { /* Unbind Queue Statistics */ fm10k_unbind_hw_stats_q(stats->q, 0, hw->mac.max_queues); /* Reinitialize bases for all stats */ fm10k_update_hw_stats_vf(hw, stats); } /** * fm10k_configure_dglort_map_vf - Configures GLORT entry and queues * @hw: pointer to hardware structure * @dglort: pointer to dglort configuration structure * * Reads the configuration structure contained in dglort_cfg and uses * that information to then populate a DGLORTMAP/DEC entry and the queues * to which it has been assigned. **/ static s32 fm10k_configure_dglort_map_vf(struct fm10k_hw __always_unused *hw, struct fm10k_dglort_cfg *dglort) { /* verify the dglort pointer */ if (!dglort) return FM10K_ERR_PARAM; /* stub for now until we determine correct message for this */ return 0; } static const struct fm10k_msg_data fm10k_msg_data_vf[] = { FM10K_TLV_MSG_TEST_HANDLER(fm10k_tlv_msg_test), FM10K_VF_MSG_MAC_VLAN_HANDLER(fm10k_msg_mac_vlan_vf), FM10K_VF_MSG_LPORT_STATE_HANDLER(fm10k_msg_lport_state_vf), FM10K_TLV_MSG_ERROR_HANDLER(fm10k_tlv_msg_error), }; static const struct fm10k_mac_ops mac_ops_vf = { .get_bus_info = fm10k_get_bus_info_generic, .reset_hw = fm10k_reset_hw_vf, .init_hw = fm10k_init_hw_vf, .start_hw = fm10k_start_hw_generic, .stop_hw = fm10k_stop_hw_vf, .update_vlan = fm10k_update_vlan_vf, .read_mac_addr = fm10k_read_mac_addr_vf, .update_uc_addr = fm10k_update_uc_addr_vf, .update_mc_addr = fm10k_update_mc_addr_vf, .update_xcast_mode = fm10k_update_xcast_mode_vf, .update_int_moderator = fm10k_update_int_moderator_vf, .update_lport_state = fm10k_update_lport_state_vf, .update_hw_stats = fm10k_update_hw_stats_vf, .rebind_hw_stats = fm10k_rebind_hw_stats_vf, .configure_dglort_map = fm10k_configure_dglort_map_vf, .get_host_state = fm10k_get_host_state_generic, }; static s32 fm10k_get_invariants_vf(struct fm10k_hw *hw) { fm10k_get_invariants_generic(hw); return fm10k_pfvf_mbx_init(hw, &hw->mbx, fm10k_msg_data_vf, 0); } const struct fm10k_info fm10k_vf_info = { .mac = fm10k_mac_vf, .get_invariants = fm10k_get_invariants_vf, .mac_ops = &mac_ops_vf, };
linux-master
drivers/net/ethernet/intel/fm10k/fm10k_vf.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2013 - 2019 Intel Corporation. */ #include "fm10k_tlv.h" /** * fm10k_tlv_msg_init - Initialize message block for TLV data storage * @msg: Pointer to message block * @msg_id: Message ID indicating message type * * This function return success if provided with a valid message pointer **/ s32 fm10k_tlv_msg_init(u32 *msg, u16 msg_id) { /* verify pointer is not NULL */ if (!msg) return FM10K_ERR_PARAM; *msg = (FM10K_TLV_FLAGS_MSG << FM10K_TLV_FLAGS_SHIFT) | msg_id; return 0; } /** * fm10k_tlv_attr_put_null_string - Place null terminated string on message * @msg: Pointer to message block * @attr_id: Attribute ID * @string: Pointer to string to be stored in attribute * * This function will reorder a string to be CPU endian and store it in * the attribute buffer. It will return success if provided with a valid * pointers. **/ static s32 fm10k_tlv_attr_put_null_string(u32 *msg, u16 attr_id, const unsigned char *string) { u32 attr_data = 0, len = 0; u32 *attr; /* verify pointers are not NULL */ if (!string || !msg) return FM10K_ERR_PARAM; attr = &msg[FM10K_TLV_DWORD_LEN(*msg)]; /* copy string into local variable and then write to msg */ do { /* write data to message */ if (len && !(len % 4)) { attr[len / 4] = attr_data; attr_data = 0; } /* record character to offset location */ attr_data |= (u32)(*string) << (8 * (len % 4)); len++; /* test for NULL and then increment */ } while (*(string++)); /* write last piece of data to message */ attr[(len + 3) / 4] = attr_data; /* record attribute header, update message length */ len <<= FM10K_TLV_LEN_SHIFT; attr[0] = len | attr_id; /* add header length to length */ len += FM10K_TLV_HDR_LEN << FM10K_TLV_LEN_SHIFT; *msg += FM10K_TLV_LEN_ALIGN(len); return 0; } /** * fm10k_tlv_attr_get_null_string - Get null terminated string from attribute * @attr: Pointer to attribute * @string: Pointer to location of destination string * * This function pulls the string back out of the attribute and will place * it in the array pointed by string. It will return success if provided * with a valid pointers. **/ static s32 fm10k_tlv_attr_get_null_string(u32 *attr, unsigned char *string) { u32 len; /* verify pointers are not NULL */ if (!string || !attr) return FM10K_ERR_PARAM; len = *attr >> FM10K_TLV_LEN_SHIFT; attr++; while (len--) string[len] = (u8)(attr[len / 4] >> (8 * (len % 4))); return 0; } /** * fm10k_tlv_attr_put_mac_vlan - Store MAC/VLAN attribute in message * @msg: Pointer to message block * @attr_id: Attribute ID * @mac_addr: MAC address to be stored * @vlan: VLAN to be stored * * This function will reorder a MAC address to be CPU endian and store it * in the attribute buffer. It will return success if provided with a * valid pointers. **/ s32 fm10k_tlv_attr_put_mac_vlan(u32 *msg, u16 attr_id, const u8 *mac_addr, u16 vlan) { u32 len = ETH_ALEN << FM10K_TLV_LEN_SHIFT; u32 *attr; /* verify pointers are not NULL */ if (!msg || !mac_addr) return FM10K_ERR_PARAM; attr = &msg[FM10K_TLV_DWORD_LEN(*msg)]; /* record attribute header, update message length */ attr[0] = len | attr_id; /* copy value into local variable and then write to msg */ attr[1] = le32_to_cpu(*(const __le32 *)&mac_addr[0]); attr[2] = le16_to_cpu(*(const __le16 *)&mac_addr[4]); attr[2] |= (u32)vlan << 16; /* add header length to length */ len += FM10K_TLV_HDR_LEN << FM10K_TLV_LEN_SHIFT; *msg += FM10K_TLV_LEN_ALIGN(len); return 0; } /** * fm10k_tlv_attr_get_mac_vlan - Get MAC/VLAN stored in attribute * @attr: Pointer to attribute * @mac_addr: location of buffer to store MAC address * @vlan: location of buffer to store VLAN * * This function pulls the MAC address back out of the attribute and will * place it in the array pointed by mac_addr. It will return success * if provided with a valid pointers. **/ s32 fm10k_tlv_attr_get_mac_vlan(u32 *attr, u8 *mac_addr, u16 *vlan) { /* verify pointers are not NULL */ if (!mac_addr || !attr) return FM10K_ERR_PARAM; *(__le32 *)&mac_addr[0] = cpu_to_le32(attr[1]); *(__le16 *)&mac_addr[4] = cpu_to_le16((u16)(attr[2])); *vlan = (u16)(attr[2] >> 16); return 0; } /** * fm10k_tlv_attr_put_bool - Add header indicating value "true" * @msg: Pointer to message block * @attr_id: Attribute ID * * This function will simply add an attribute header, the fact * that the header is here means the attribute value is true, else * it is false. The function will return success if provided with a * valid pointers. **/ s32 fm10k_tlv_attr_put_bool(u32 *msg, u16 attr_id) { /* verify pointers are not NULL */ if (!msg) return FM10K_ERR_PARAM; /* record attribute header */ msg[FM10K_TLV_DWORD_LEN(*msg)] = attr_id; /* add header length to length */ *msg += FM10K_TLV_HDR_LEN << FM10K_TLV_LEN_SHIFT; return 0; } /** * fm10k_tlv_attr_put_value - Store integer value attribute in message * @msg: Pointer to message block * @attr_id: Attribute ID * @value: Value to be written * @len: Size of value * * This function will place an integer value of up to 8 bytes in size * in a message attribute. The function will return success provided * that msg is a valid pointer, and len is 1, 2, 4, or 8. **/ s32 fm10k_tlv_attr_put_value(u32 *msg, u16 attr_id, s64 value, u32 len) { u32 *attr; /* verify non-null msg and len is 1, 2, 4, or 8 */ if (!msg || !len || len > 8 || (len & (len - 1))) return FM10K_ERR_PARAM; attr = &msg[FM10K_TLV_DWORD_LEN(*msg)]; if (len < 4) { attr[1] = (u32)value & (BIT(8 * len) - 1); } else { attr[1] = (u32)value; if (len > 4) attr[2] = (u32)(value >> 32); } /* record attribute header, update message length */ len <<= FM10K_TLV_LEN_SHIFT; attr[0] = len | attr_id; /* add header length to length */ len += FM10K_TLV_HDR_LEN << FM10K_TLV_LEN_SHIFT; *msg += FM10K_TLV_LEN_ALIGN(len); return 0; } /** * fm10k_tlv_attr_get_value - Get integer value stored in attribute * @attr: Pointer to attribute * @value: Pointer to destination buffer * @len: Size of value * * This function will place an integer value of up to 8 bytes in size * in the offset pointed to by value. The function will return success * provided that pointers are valid and the len value matches the * attribute length. **/ s32 fm10k_tlv_attr_get_value(u32 *attr, void *value, u32 len) { /* verify pointers are not NULL */ if (!attr || !value) return FM10K_ERR_PARAM; if ((*attr >> FM10K_TLV_LEN_SHIFT) != len) return FM10K_ERR_PARAM; if (len == 8) *(u64 *)value = ((u64)attr[2] << 32) | attr[1]; else if (len == 4) *(u32 *)value = attr[1]; else if (len == 2) *(u16 *)value = (u16)attr[1]; else *(u8 *)value = (u8)attr[1]; return 0; } /** * fm10k_tlv_attr_put_le_struct - Store little endian structure in message * @msg: Pointer to message block * @attr_id: Attribute ID * @le_struct: Pointer to structure to be written * @len: Size of le_struct * * This function will place a little endian structure value in a message * attribute. The function will return success provided that all pointers * are valid and length is a non-zero multiple of 4. **/ s32 fm10k_tlv_attr_put_le_struct(u32 *msg, u16 attr_id, const void *le_struct, u32 len) { const __le32 *le32_ptr = (const __le32 *)le_struct; u32 *attr; u32 i; /* verify non-null msg and len is in 32 bit words */ if (!msg || !len || (len % 4)) return FM10K_ERR_PARAM; attr = &msg[FM10K_TLV_DWORD_LEN(*msg)]; /* copy le32 structure into host byte order at 32b boundaries */ for (i = 0; i < (len / 4); i++) attr[i + 1] = le32_to_cpu(le32_ptr[i]); /* record attribute header, update message length */ len <<= FM10K_TLV_LEN_SHIFT; attr[0] = len | attr_id; /* add header length to length */ len += FM10K_TLV_HDR_LEN << FM10K_TLV_LEN_SHIFT; *msg += FM10K_TLV_LEN_ALIGN(len); return 0; } /** * fm10k_tlv_attr_get_le_struct - Get little endian struct form attribute * @attr: Pointer to attribute * @le_struct: Pointer to structure to be written * @len: Size of structure * * This function will place a little endian structure in the buffer * pointed to by le_struct. The function will return success * provided that pointers are valid and the len value matches the * attribute length. **/ s32 fm10k_tlv_attr_get_le_struct(u32 *attr, void *le_struct, u32 len) { __le32 *le32_ptr = (__le32 *)le_struct; u32 i; /* verify pointers are not NULL */ if (!le_struct || !attr) return FM10K_ERR_PARAM; if ((*attr >> FM10K_TLV_LEN_SHIFT) != len) return FM10K_ERR_PARAM; attr++; for (i = 0; len; i++, len -= 4) le32_ptr[i] = cpu_to_le32(attr[i]); return 0; } /** * fm10k_tlv_attr_nest_start - Start a set of nested attributes * @msg: Pointer to message block * @attr_id: Attribute ID * * This function will mark off a new nested region for encapsulating * a given set of attributes. The idea is if you wish to place a secondary * structure within the message this mechanism allows for that. The * function will return NULL on failure, and a pointer to the start * of the nested attributes on success. **/ static u32 *fm10k_tlv_attr_nest_start(u32 *msg, u16 attr_id) { u32 *attr; /* verify pointer is not NULL */ if (!msg) return NULL; attr = &msg[FM10K_TLV_DWORD_LEN(*msg)]; attr[0] = attr_id; /* return pointer to nest header */ return attr; } /** * fm10k_tlv_attr_nest_stop - Stop a set of nested attributes * @msg: Pointer to message block * * This function closes off an existing set of nested attributes. The * message pointer should be pointing to the parent of the nest. So in * the case of a nest within the nest this would be the outer nest pointer. * This function will return success provided all pointers are valid. **/ static s32 fm10k_tlv_attr_nest_stop(u32 *msg) { u32 *attr; u32 len; /* verify pointer is not NULL */ if (!msg) return FM10K_ERR_PARAM; /* locate the nested header and retrieve its length */ attr = &msg[FM10K_TLV_DWORD_LEN(*msg)]; len = (attr[0] >> FM10K_TLV_LEN_SHIFT) << FM10K_TLV_LEN_SHIFT; /* only include nest if data was added to it */ if (len) { len += FM10K_TLV_HDR_LEN << FM10K_TLV_LEN_SHIFT; *msg += len; } return 0; } /** * fm10k_tlv_attr_validate - Validate attribute metadata * @attr: Pointer to attribute * @tlv_attr: Type and length info for attribute * * This function does some basic validation of the input TLV. It * verifies the length, and in the case of null terminated strings * it verifies that the last byte is null. The function will * return FM10K_ERR_PARAM if any attribute is malformed, otherwise * it returns 0. **/ static s32 fm10k_tlv_attr_validate(u32 *attr, const struct fm10k_tlv_attr *tlv_attr) { u32 attr_id = *attr & FM10K_TLV_ID_MASK; u16 len = *attr >> FM10K_TLV_LEN_SHIFT; /* verify this is an attribute and not a message */ if (*attr & (FM10K_TLV_FLAGS_MSG << FM10K_TLV_FLAGS_SHIFT)) return FM10K_ERR_PARAM; /* search through the list of attributes to find a matching ID */ while (tlv_attr->id < attr_id) tlv_attr++; /* if didn't find a match then we should exit */ if (tlv_attr->id != attr_id) return FM10K_NOT_IMPLEMENTED; /* move to start of attribute data */ attr++; switch (tlv_attr->type) { case FM10K_TLV_NULL_STRING: if (!len || (attr[(len - 1) / 4] & (0xFF << (8 * ((len - 1) % 4))))) return FM10K_ERR_PARAM; if (len > tlv_attr->len) return FM10K_ERR_PARAM; break; case FM10K_TLV_MAC_ADDR: if (len != ETH_ALEN) return FM10K_ERR_PARAM; break; case FM10K_TLV_BOOL: if (len) return FM10K_ERR_PARAM; break; case FM10K_TLV_UNSIGNED: case FM10K_TLV_SIGNED: if (len != tlv_attr->len) return FM10K_ERR_PARAM; break; case FM10K_TLV_LE_STRUCT: /* struct must be 4 byte aligned */ if ((len % 4) || len != tlv_attr->len) return FM10K_ERR_PARAM; break; case FM10K_TLV_NESTED: /* nested attributes must be 4 byte aligned */ if (len % 4) return FM10K_ERR_PARAM; break; default: /* attribute id is mapped to bad value */ return FM10K_ERR_PARAM; } return 0; } /** * fm10k_tlv_attr_parse - Parses stream of attribute data * @attr: Pointer to attribute list * @results: Pointer array to store pointers to attributes * @tlv_attr: Type and length info for attributes * * This function validates a stream of attributes and parses them * up into an array of pointers stored in results. The function will * return FM10K_ERR_PARAM on any input or message error, * FM10K_NOT_IMPLEMENTED for any attribute that is outside of the array * and 0 on success. Any attributes not found in tlv_attr will be silently * ignored. **/ static s32 fm10k_tlv_attr_parse(u32 *attr, u32 **results, const struct fm10k_tlv_attr *tlv_attr) { u32 i, attr_id, offset = 0; s32 err; u16 len; /* verify pointers are not NULL */ if (!attr || !results) return FM10K_ERR_PARAM; /* initialize results to NULL */ for (i = 0; i < FM10K_TLV_RESULTS_MAX; i++) results[i] = NULL; /* pull length from the message header */ len = *attr >> FM10K_TLV_LEN_SHIFT; /* no attributes to parse if there is no length */ if (!len) return 0; /* no attributes to parse, just raw data, message becomes attribute */ if (!tlv_attr) { results[0] = attr; return 0; } /* move to start of attribute data */ attr++; /* run through list parsing all attributes */ while (offset < len) { attr_id = *attr & FM10K_TLV_ID_MASK; if (attr_id >= FM10K_TLV_RESULTS_MAX) return FM10K_NOT_IMPLEMENTED; err = fm10k_tlv_attr_validate(attr, tlv_attr); if (err == FM10K_NOT_IMPLEMENTED) ; /* silently ignore non-implemented attributes */ else if (err) return err; else results[attr_id] = attr; /* update offset */ offset += FM10K_TLV_DWORD_LEN(*attr) * 4; /* move to next attribute */ attr = &attr[FM10K_TLV_DWORD_LEN(*attr)]; } /* we should find ourselves at the end of the list */ if (offset != len) return FM10K_ERR_PARAM; return 0; } /** * fm10k_tlv_msg_parse - Parses message header and calls function handler * @hw: Pointer to hardware structure * @msg: Pointer to message * @mbx: Pointer to mailbox information structure * @data: Pointer to message handler data structure * * This function should be the first function called upon receiving a * message. The handler will identify the message type and call the correct * handler for the given message. It will return the value from the function * call on a recognized message type, otherwise it will return * FM10K_NOT_IMPLEMENTED on an unrecognized type. **/ s32 fm10k_tlv_msg_parse(struct fm10k_hw *hw, u32 *msg, struct fm10k_mbx_info *mbx, const struct fm10k_msg_data *data) { u32 *results[FM10K_TLV_RESULTS_MAX]; u32 msg_id; s32 err; /* verify pointer is not NULL */ if (!msg || !data) return FM10K_ERR_PARAM; /* verify this is a message and not an attribute */ if (!(*msg & (FM10K_TLV_FLAGS_MSG << FM10K_TLV_FLAGS_SHIFT))) return FM10K_ERR_PARAM; /* grab message ID */ msg_id = *msg & FM10K_TLV_ID_MASK; while (data->id < msg_id) data++; /* if we didn't find it then pass it up as an error */ if (data->id != msg_id) { while (data->id != FM10K_TLV_ERROR) data++; } /* parse the attributes into the results list */ err = fm10k_tlv_attr_parse(msg, results, data->attr); if (err < 0) return err; return data->func(hw, results, mbx); } /** * fm10k_tlv_msg_error - Default handler for unrecognized TLV message IDs * @hw: Pointer to hardware structure * @results: Pointer array to message, results[0] is pointer to message * @mbx: Unused mailbox pointer * * This function is a default handler for unrecognized messages. At a * minimum it just indicates that the message requested was * unimplemented. **/ s32 fm10k_tlv_msg_error(struct fm10k_hw __always_unused *hw, u32 __always_unused **results, struct fm10k_mbx_info __always_unused *mbx) { return FM10K_NOT_IMPLEMENTED; } static const unsigned char test_str[] = "fm10k"; static const unsigned char test_mac[ETH_ALEN] = { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc }; static const u16 test_vlan = 0x0FED; static const u64 test_u64 = 0xfedcba9876543210ull; static const u32 test_u32 = 0x87654321; static const u16 test_u16 = 0x8765; static const u8 test_u8 = 0x87; static const s64 test_s64 = -0x123456789abcdef0ll; static const s32 test_s32 = -0x1235678; static const s16 test_s16 = -0x1234; static const s8 test_s8 = -0x12; static const __le32 test_le[2] = { cpu_to_le32(0x12345678), cpu_to_le32(0x9abcdef0)}; /* The message below is meant to be used as a test message to demonstrate * how to use the TLV interface and to test the types. Normally this code * be compiled out by stripping the code wrapped in FM10K_TLV_TEST_MSG */ const struct fm10k_tlv_attr fm10k_tlv_msg_test_attr[] = { FM10K_TLV_ATTR_NULL_STRING(FM10K_TEST_MSG_STRING, 80), FM10K_TLV_ATTR_MAC_ADDR(FM10K_TEST_MSG_MAC_ADDR), FM10K_TLV_ATTR_U8(FM10K_TEST_MSG_U8), FM10K_TLV_ATTR_U16(FM10K_TEST_MSG_U16), FM10K_TLV_ATTR_U32(FM10K_TEST_MSG_U32), FM10K_TLV_ATTR_U64(FM10K_TEST_MSG_U64), FM10K_TLV_ATTR_S8(FM10K_TEST_MSG_S8), FM10K_TLV_ATTR_S16(FM10K_TEST_MSG_S16), FM10K_TLV_ATTR_S32(FM10K_TEST_MSG_S32), FM10K_TLV_ATTR_S64(FM10K_TEST_MSG_S64), FM10K_TLV_ATTR_LE_STRUCT(FM10K_TEST_MSG_LE_STRUCT, 8), FM10K_TLV_ATTR_NESTED(FM10K_TEST_MSG_NESTED), FM10K_TLV_ATTR_S32(FM10K_TEST_MSG_RESULT), FM10K_TLV_ATTR_LAST }; /** * fm10k_tlv_msg_test_generate_data - Stuff message with data * @msg: Pointer to message * @attr_flags: List of flags indicating what attributes to add * * This function is meant to load a message buffer with attribute data **/ static void fm10k_tlv_msg_test_generate_data(u32 *msg, u32 attr_flags) { if (attr_flags & BIT(FM10K_TEST_MSG_STRING)) fm10k_tlv_attr_put_null_string(msg, FM10K_TEST_MSG_STRING, test_str); if (attr_flags & BIT(FM10K_TEST_MSG_MAC_ADDR)) fm10k_tlv_attr_put_mac_vlan(msg, FM10K_TEST_MSG_MAC_ADDR, test_mac, test_vlan); if (attr_flags & BIT(FM10K_TEST_MSG_U8)) fm10k_tlv_attr_put_u8(msg, FM10K_TEST_MSG_U8, test_u8); if (attr_flags & BIT(FM10K_TEST_MSG_U16)) fm10k_tlv_attr_put_u16(msg, FM10K_TEST_MSG_U16, test_u16); if (attr_flags & BIT(FM10K_TEST_MSG_U32)) fm10k_tlv_attr_put_u32(msg, FM10K_TEST_MSG_U32, test_u32); if (attr_flags & BIT(FM10K_TEST_MSG_U64)) fm10k_tlv_attr_put_u64(msg, FM10K_TEST_MSG_U64, test_u64); if (attr_flags & BIT(FM10K_TEST_MSG_S8)) fm10k_tlv_attr_put_s8(msg, FM10K_TEST_MSG_S8, test_s8); if (attr_flags & BIT(FM10K_TEST_MSG_S16)) fm10k_tlv_attr_put_s16(msg, FM10K_TEST_MSG_S16, test_s16); if (attr_flags & BIT(FM10K_TEST_MSG_S32)) fm10k_tlv_attr_put_s32(msg, FM10K_TEST_MSG_S32, test_s32); if (attr_flags & BIT(FM10K_TEST_MSG_S64)) fm10k_tlv_attr_put_s64(msg, FM10K_TEST_MSG_S64, test_s64); if (attr_flags & BIT(FM10K_TEST_MSG_LE_STRUCT)) fm10k_tlv_attr_put_le_struct(msg, FM10K_TEST_MSG_LE_STRUCT, test_le, 8); } /** * fm10k_tlv_msg_test_create - Create a test message testing all attributes * @msg: Pointer to message * @attr_flags: List of flags indicating what attributes to add * * This function is meant to load a message buffer with all attribute types * including a nested attribute. **/ void fm10k_tlv_msg_test_create(u32 *msg, u32 attr_flags) { u32 *nest = NULL; fm10k_tlv_msg_init(msg, FM10K_TLV_MSG_ID_TEST); fm10k_tlv_msg_test_generate_data(msg, attr_flags); /* check for nested attributes */ attr_flags >>= FM10K_TEST_MSG_NESTED; if (attr_flags) { nest = fm10k_tlv_attr_nest_start(msg, FM10K_TEST_MSG_NESTED); fm10k_tlv_msg_test_generate_data(nest, attr_flags); fm10k_tlv_attr_nest_stop(msg); } } /** * fm10k_tlv_msg_test - Validate all results on test message receive * @hw: Pointer to hardware structure * @results: Pointer array to attributes in the message * @mbx: Pointer to mailbox information structure * * This function does a check to verify all attributes match what the test * message placed in the message buffer. It is the default handler * for TLV test messages. **/ s32 fm10k_tlv_msg_test(struct fm10k_hw *hw, u32 **results, struct fm10k_mbx_info *mbx) { u32 *nest_results[FM10K_TLV_RESULTS_MAX]; unsigned char result_str[80]; unsigned char result_mac[ETH_ALEN]; s32 err = 0; __le32 result_le[2]; u16 result_vlan; u64 result_u64; u32 result_u32; u16 result_u16; u8 result_u8; s64 result_s64; s32 result_s32; s16 result_s16; s8 result_s8; u32 reply[3]; /* retrieve results of a previous test */ if (!!results[FM10K_TEST_MSG_RESULT]) return fm10k_tlv_attr_get_s32(results[FM10K_TEST_MSG_RESULT], &mbx->test_result); parse_nested: if (!!results[FM10K_TEST_MSG_STRING]) { err = fm10k_tlv_attr_get_null_string( results[FM10K_TEST_MSG_STRING], result_str); if (!err && memcmp(test_str, result_str, sizeof(test_str))) err = FM10K_ERR_INVALID_VALUE; if (err) goto report_result; } if (!!results[FM10K_TEST_MSG_MAC_ADDR]) { err = fm10k_tlv_attr_get_mac_vlan( results[FM10K_TEST_MSG_MAC_ADDR], result_mac, &result_vlan); if (!err && !ether_addr_equal(test_mac, result_mac)) err = FM10K_ERR_INVALID_VALUE; if (!err && test_vlan != result_vlan) err = FM10K_ERR_INVALID_VALUE; if (err) goto report_result; } if (!!results[FM10K_TEST_MSG_U8]) { err = fm10k_tlv_attr_get_u8(results[FM10K_TEST_MSG_U8], &result_u8); if (!err && test_u8 != result_u8) err = FM10K_ERR_INVALID_VALUE; if (err) goto report_result; } if (!!results[FM10K_TEST_MSG_U16]) { err = fm10k_tlv_attr_get_u16(results[FM10K_TEST_MSG_U16], &result_u16); if (!err && test_u16 != result_u16) err = FM10K_ERR_INVALID_VALUE; if (err) goto report_result; } if (!!results[FM10K_TEST_MSG_U32]) { err = fm10k_tlv_attr_get_u32(results[FM10K_TEST_MSG_U32], &result_u32); if (!err && test_u32 != result_u32) err = FM10K_ERR_INVALID_VALUE; if (err) goto report_result; } if (!!results[FM10K_TEST_MSG_U64]) { err = fm10k_tlv_attr_get_u64(results[FM10K_TEST_MSG_U64], &result_u64); if (!err && test_u64 != result_u64) err = FM10K_ERR_INVALID_VALUE; if (err) goto report_result; } if (!!results[FM10K_TEST_MSG_S8]) { err = fm10k_tlv_attr_get_s8(results[FM10K_TEST_MSG_S8], &result_s8); if (!err && test_s8 != result_s8) err = FM10K_ERR_INVALID_VALUE; if (err) goto report_result; } if (!!results[FM10K_TEST_MSG_S16]) { err = fm10k_tlv_attr_get_s16(results[FM10K_TEST_MSG_S16], &result_s16); if (!err && test_s16 != result_s16) err = FM10K_ERR_INVALID_VALUE; if (err) goto report_result; } if (!!results[FM10K_TEST_MSG_S32]) { err = fm10k_tlv_attr_get_s32(results[FM10K_TEST_MSG_S32], &result_s32); if (!err && test_s32 != result_s32) err = FM10K_ERR_INVALID_VALUE; if (err) goto report_result; } if (!!results[FM10K_TEST_MSG_S64]) { err = fm10k_tlv_attr_get_s64(results[FM10K_TEST_MSG_S64], &result_s64); if (!err && test_s64 != result_s64) err = FM10K_ERR_INVALID_VALUE; if (err) goto report_result; } if (!!results[FM10K_TEST_MSG_LE_STRUCT]) { err = fm10k_tlv_attr_get_le_struct( results[FM10K_TEST_MSG_LE_STRUCT], result_le, sizeof(result_le)); if (!err && memcmp(test_le, result_le, sizeof(test_le))) err = FM10K_ERR_INVALID_VALUE; if (err) goto report_result; } if (!!results[FM10K_TEST_MSG_NESTED]) { /* clear any pointers */ memset(nest_results, 0, sizeof(nest_results)); /* parse the nested attributes into the nest results list */ err = fm10k_tlv_attr_parse(results[FM10K_TEST_MSG_NESTED], nest_results, fm10k_tlv_msg_test_attr); if (err) goto report_result; /* loop back through to the start */ results = nest_results; goto parse_nested; } report_result: /* generate reply with test result */ fm10k_tlv_msg_init(reply, FM10K_TLV_MSG_ID_TEST); fm10k_tlv_attr_put_s32(reply, FM10K_TEST_MSG_RESULT, err); /* load onto outgoing mailbox */ return mbx->ops.enqueue_tx(hw, mbx, reply); }
linux-master
drivers/net/ethernet/intel/fm10k/fm10k_tlv.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2013 - 2019 Intel Corporation. */ #include "fm10k.h" #include "fm10k_vf.h" #include "fm10k_pf.h" static s32 fm10k_iov_msg_error(struct fm10k_hw *hw, u32 **results, struct fm10k_mbx_info *mbx) { struct fm10k_vf_info *vf_info = (struct fm10k_vf_info *)mbx; struct fm10k_intfc *interface = hw->back; struct pci_dev *pdev = interface->pdev; dev_err(&pdev->dev, "Unknown message ID %u on VF %d\n", **results & FM10K_TLV_ID_MASK, vf_info->vf_idx); return fm10k_tlv_msg_error(hw, results, mbx); } /** * fm10k_iov_msg_queue_mac_vlan - Message handler for MAC/VLAN request from VF * @hw: Pointer to hardware structure * @results: Pointer array to message, results[0] is pointer to message * @mbx: Pointer to mailbox information structure * * This function is a custom handler for MAC/VLAN requests from the VF. The * assumption is that it is acceptable to directly hand off the message from * the VF to the PF's switch manager. However, we use a MAC/VLAN message * queue to avoid overloading the mailbox when a large number of requests * come in. **/ static s32 fm10k_iov_msg_queue_mac_vlan(struct fm10k_hw *hw, u32 **results, struct fm10k_mbx_info *mbx) { struct fm10k_vf_info *vf_info = (struct fm10k_vf_info *)mbx; struct fm10k_intfc *interface = hw->back; u8 mac[ETH_ALEN]; u32 *result; int err = 0; bool set; u16 vlan; u32 vid; /* we shouldn't be updating rules on a disabled interface */ if (!FM10K_VF_FLAG_ENABLED(vf_info)) err = FM10K_ERR_PARAM; if (!err && !!results[FM10K_MAC_VLAN_MSG_VLAN]) { result = results[FM10K_MAC_VLAN_MSG_VLAN]; /* record VLAN id requested */ err = fm10k_tlv_attr_get_u32(result, &vid); if (err) return err; set = !(vid & FM10K_VLAN_CLEAR); vid &= ~FM10K_VLAN_CLEAR; /* if the length field has been set, this is a multi-bit * update request. For multi-bit requests, simply disallow * them when the pf_vid has been set. In this case, the PF * should have already cleared the VLAN_TABLE, and if we * allowed them, it could allow a rogue VF to receive traffic * on a VLAN it was not assigned. In the single-bit case, we * need to modify requests for VLAN 0 to use the default PF or * SW vid when assigned. */ if (vid >> 16) { /* prevent multi-bit requests when PF has * administratively set the VLAN for this VF */ if (vf_info->pf_vid) return FM10K_ERR_PARAM; } else { err = fm10k_iov_select_vid(vf_info, (u16)vid); if (err < 0) return err; vid = err; } /* update VSI info for VF in regards to VLAN table */ err = hw->mac.ops.update_vlan(hw, vid, vf_info->vsi, set); } if (!err && !!results[FM10K_MAC_VLAN_MSG_MAC]) { result = results[FM10K_MAC_VLAN_MSG_MAC]; /* record unicast MAC address requested */ err = fm10k_tlv_attr_get_mac_vlan(result, mac, &vlan); if (err) return err; /* block attempts to set MAC for a locked device */ if (is_valid_ether_addr(vf_info->mac) && !ether_addr_equal(mac, vf_info->mac)) return FM10K_ERR_PARAM; set = !(vlan & FM10K_VLAN_CLEAR); vlan &= ~FM10K_VLAN_CLEAR; err = fm10k_iov_select_vid(vf_info, vlan); if (err < 0) return err; vlan = (u16)err; /* Add this request to the MAC/VLAN queue */ err = fm10k_queue_mac_request(interface, vf_info->glort, mac, vlan, set); } if (!err && !!results[FM10K_MAC_VLAN_MSG_MULTICAST]) { result = results[FM10K_MAC_VLAN_MSG_MULTICAST]; /* record multicast MAC address requested */ err = fm10k_tlv_attr_get_mac_vlan(result, mac, &vlan); if (err) return err; /* verify that the VF is allowed to request multicast */ if (!(vf_info->vf_flags & FM10K_VF_FLAG_MULTI_ENABLED)) return FM10K_ERR_PARAM; set = !(vlan & FM10K_VLAN_CLEAR); vlan &= ~FM10K_VLAN_CLEAR; err = fm10k_iov_select_vid(vf_info, vlan); if (err < 0) return err; vlan = (u16)err; /* Add this request to the MAC/VLAN queue */ err = fm10k_queue_mac_request(interface, vf_info->glort, mac, vlan, set); } return err; } static const struct fm10k_msg_data iov_mbx_data[] = { FM10K_TLV_MSG_TEST_HANDLER(fm10k_tlv_msg_test), FM10K_VF_MSG_MSIX_HANDLER(fm10k_iov_msg_msix_pf), FM10K_VF_MSG_MAC_VLAN_HANDLER(fm10k_iov_msg_queue_mac_vlan), FM10K_VF_MSG_LPORT_STATE_HANDLER(fm10k_iov_msg_lport_state_pf), FM10K_TLV_MSG_ERROR_HANDLER(fm10k_iov_msg_error), }; s32 fm10k_iov_event(struct fm10k_intfc *interface) { struct fm10k_hw *hw = &interface->hw; struct fm10k_iov_data *iov_data; s64 vflre; int i; /* if there is no iov_data then there is no mailbox to process */ if (!READ_ONCE(interface->iov_data)) return 0; rcu_read_lock(); iov_data = interface->iov_data; /* check again now that we are in the RCU block */ if (!iov_data) goto read_unlock; if (!(fm10k_read_reg(hw, FM10K_EICR) & FM10K_EICR_VFLR)) goto read_unlock; /* read VFLRE to determine if any VFs have been reset */ vflre = fm10k_read_reg(hw, FM10K_PFVFLRE(1)); vflre <<= 32; vflre |= fm10k_read_reg(hw, FM10K_PFVFLRE(0)); i = iov_data->num_vfs; for (vflre <<= 64 - i; vflre && i--; vflre += vflre) { struct fm10k_vf_info *vf_info = &iov_data->vf_info[i]; if (vflre >= 0) continue; hw->iov.ops.reset_resources(hw, vf_info); vf_info->mbx.ops.connect(hw, &vf_info->mbx); } read_unlock: rcu_read_unlock(); return 0; } s32 fm10k_iov_mbx(struct fm10k_intfc *interface) { struct fm10k_hw *hw = &interface->hw; struct fm10k_iov_data *iov_data; int i; /* if there is no iov_data then there is no mailbox to process */ if (!READ_ONCE(interface->iov_data)) return 0; rcu_read_lock(); iov_data = interface->iov_data; /* check again now that we are in the RCU block */ if (!iov_data) goto read_unlock; /* lock the mailbox for transmit and receive */ fm10k_mbx_lock(interface); /* Most VF messages sent to the PF cause the PF to respond by * requesting from the SM mailbox. This means that too many VF * messages processed at once could cause a mailbox timeout on the PF. * To prevent this, store a pointer to the next VF mbx to process. Use * that as the start of the loop so that we don't starve whichever VF * got ignored on the previous run. */ process_mbx: for (i = iov_data->next_vf_mbx ? : iov_data->num_vfs; i--;) { struct fm10k_vf_info *vf_info = &iov_data->vf_info[i]; struct fm10k_mbx_info *mbx = &vf_info->mbx; u16 glort = vf_info->glort; /* process the SM mailbox first to drain outgoing messages */ hw->mbx.ops.process(hw, &hw->mbx); /* verify port mapping is valid, if not reset port */ if (vf_info->vf_flags && !fm10k_glort_valid_pf(hw, glort)) { hw->iov.ops.reset_lport(hw, vf_info); fm10k_clear_macvlan_queue(interface, glort, false); } /* reset VFs that have mailbox timed out */ if (!mbx->timeout) { hw->iov.ops.reset_resources(hw, vf_info); mbx->ops.connect(hw, mbx); } /* guarantee we have free space in the SM mailbox */ if (hw->mbx.state == FM10K_STATE_OPEN && !hw->mbx.ops.tx_ready(&hw->mbx, FM10K_VFMBX_MSG_MTU)) { /* keep track of how many times this occurs */ interface->hw_sm_mbx_full++; /* make sure we try again momentarily */ fm10k_service_event_schedule(interface); break; } /* cleanup mailbox and process received messages */ mbx->ops.process(hw, mbx); } /* if we stopped processing mailboxes early, update next_vf_mbx. * Otherwise, reset next_vf_mbx, and restart loop so that we process * the remaining mailboxes we skipped at the start. */ if (i >= 0) { iov_data->next_vf_mbx = i + 1; } else if (iov_data->next_vf_mbx) { iov_data->next_vf_mbx = 0; goto process_mbx; } /* free the lock */ fm10k_mbx_unlock(interface); read_unlock: rcu_read_unlock(); return 0; } void fm10k_iov_suspend(struct pci_dev *pdev) { struct fm10k_intfc *interface = pci_get_drvdata(pdev); struct fm10k_iov_data *iov_data = interface->iov_data; struct fm10k_hw *hw = &interface->hw; int num_vfs, i; /* pull out num_vfs from iov_data */ num_vfs = iov_data ? iov_data->num_vfs : 0; /* shut down queue mapping for VFs */ fm10k_write_reg(hw, FM10K_DGLORTMAP(fm10k_dglort_vf_rss), FM10K_DGLORTMAP_NONE); /* Stop any active VFs and reset their resources */ for (i = 0; i < num_vfs; i++) { struct fm10k_vf_info *vf_info = &iov_data->vf_info[i]; hw->iov.ops.reset_resources(hw, vf_info); hw->iov.ops.reset_lport(hw, vf_info); fm10k_clear_macvlan_queue(interface, vf_info->glort, false); } } static void fm10k_mask_aer_comp_abort(struct pci_dev *pdev) { u32 err_mask; int pos; pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ERR); if (!pos) return; /* Mask the completion abort bit in the ERR_UNCOR_MASK register, * preventing the device from reporting these errors to the upstream * PCIe root device. This avoids bringing down platforms which upgrade * non-fatal completer aborts into machine check exceptions. Completer * aborts can occur whenever a VF reads a queue it doesn't own. */ pci_read_config_dword(pdev, pos + PCI_ERR_UNCOR_MASK, &err_mask); err_mask |= PCI_ERR_UNC_COMP_ABORT; pci_write_config_dword(pdev, pos + PCI_ERR_UNCOR_MASK, err_mask); } int fm10k_iov_resume(struct pci_dev *pdev) { struct fm10k_intfc *interface = pci_get_drvdata(pdev); struct fm10k_iov_data *iov_data = interface->iov_data; struct fm10k_dglort_cfg dglort = { 0 }; struct fm10k_hw *hw = &interface->hw; int num_vfs, i; /* pull out num_vfs from iov_data */ num_vfs = iov_data ? iov_data->num_vfs : 0; /* return error if iov_data is not already populated */ if (!iov_data) return -ENOMEM; /* Lower severity of completer abort error reporting as * the VFs can trigger this any time they read a queue * that they don't own. */ fm10k_mask_aer_comp_abort(pdev); /* allocate hardware resources for the VFs */ hw->iov.ops.assign_resources(hw, num_vfs, num_vfs); /* configure DGLORT mapping for RSS */ dglort.glort = hw->mac.dglort_map & FM10K_DGLORTMAP_NONE; dglort.idx = fm10k_dglort_vf_rss; dglort.inner_rss = 1; dglort.rss_l = fls(fm10k_queues_per_pool(hw) - 1); dglort.queue_b = fm10k_vf_queue_index(hw, 0); dglort.vsi_l = fls(hw->iov.total_vfs - 1); dglort.vsi_b = 1; hw->mac.ops.configure_dglort_map(hw, &dglort); /* assign resources to the device */ for (i = 0; i < num_vfs; i++) { struct fm10k_vf_info *vf_info = &iov_data->vf_info[i]; /* allocate all but the last GLORT to the VFs */ if (i == (~hw->mac.dglort_map >> FM10K_DGLORTMAP_MASK_SHIFT)) break; /* assign GLORT to VF, and restrict it to multicast */ hw->iov.ops.set_lport(hw, vf_info, i, FM10K_VF_FLAG_MULTI_CAPABLE); /* mailbox is disconnected so we don't send a message */ hw->iov.ops.assign_default_mac_vlan(hw, vf_info); /* now we are ready so we can connect */ vf_info->mbx.ops.connect(hw, &vf_info->mbx); } return 0; } s32 fm10k_iov_update_pvid(struct fm10k_intfc *interface, u16 glort, u16 pvid) { struct fm10k_iov_data *iov_data = interface->iov_data; struct fm10k_hw *hw = &interface->hw; struct fm10k_vf_info *vf_info; u16 vf_idx = (glort - hw->mac.dglort_map) & FM10K_DGLORTMAP_NONE; /* no IOV support, not our message to process */ if (!iov_data) return FM10K_ERR_PARAM; /* glort outside our range, not our message to process */ if (vf_idx >= iov_data->num_vfs) return FM10K_ERR_PARAM; /* determine if an update has occurred and if so notify the VF */ vf_info = &iov_data->vf_info[vf_idx]; if (vf_info->sw_vid != pvid) { vf_info->sw_vid = pvid; hw->iov.ops.assign_default_mac_vlan(hw, vf_info); } return 0; } static void fm10k_iov_free_data(struct pci_dev *pdev) { struct fm10k_intfc *interface = pci_get_drvdata(pdev); if (!interface->iov_data) return; /* reclaim hardware resources */ fm10k_iov_suspend(pdev); /* drop iov_data from interface */ kfree_rcu(interface->iov_data, rcu); interface->iov_data = NULL; } static s32 fm10k_iov_alloc_data(struct pci_dev *pdev, int num_vfs) { struct fm10k_intfc *interface = pci_get_drvdata(pdev); struct fm10k_iov_data *iov_data = interface->iov_data; struct fm10k_hw *hw = &interface->hw; size_t size; int i; /* return error if iov_data is already populated */ if (iov_data) return -EBUSY; /* The PF should always be able to assign resources */ if (!hw->iov.ops.assign_resources) return -ENODEV; /* nothing to do if no VFs are requested */ if (!num_vfs) return 0; /* allocate memory for VF storage */ size = offsetof(struct fm10k_iov_data, vf_info[num_vfs]); iov_data = kzalloc(size, GFP_KERNEL); if (!iov_data) return -ENOMEM; /* record number of VFs */ iov_data->num_vfs = num_vfs; /* loop through vf_info structures initializing each entry */ for (i = 0; i < num_vfs; i++) { struct fm10k_vf_info *vf_info = &iov_data->vf_info[i]; int err; /* Record VF VSI value */ vf_info->vsi = i + 1; vf_info->vf_idx = i; /* initialize mailbox memory */ err = fm10k_pfvf_mbx_init(hw, &vf_info->mbx, iov_mbx_data, i); if (err) { dev_err(&pdev->dev, "Unable to initialize SR-IOV mailbox\n"); kfree(iov_data); return err; } } /* assign iov_data to interface */ interface->iov_data = iov_data; /* allocate hardware resources for the VFs */ fm10k_iov_resume(pdev); return 0; } void fm10k_iov_disable(struct pci_dev *pdev) { if (pci_num_vf(pdev) && pci_vfs_assigned(pdev)) dev_err(&pdev->dev, "Cannot disable SR-IOV while VFs are assigned\n"); else pci_disable_sriov(pdev); fm10k_iov_free_data(pdev); } int fm10k_iov_configure(struct pci_dev *pdev, int num_vfs) { int current_vfs = pci_num_vf(pdev); int err = 0; if (current_vfs && pci_vfs_assigned(pdev)) { dev_err(&pdev->dev, "Cannot modify SR-IOV while VFs are assigned\n"); num_vfs = current_vfs; } else { pci_disable_sriov(pdev); fm10k_iov_free_data(pdev); } /* allocate resources for the VFs */ err = fm10k_iov_alloc_data(pdev, num_vfs); if (err) return err; /* allocate VFs if not already allocated */ if (num_vfs && num_vfs != current_vfs) { err = pci_enable_sriov(pdev, num_vfs); if (err) { dev_err(&pdev->dev, "Enable PCI SR-IOV failed: %d\n", err); return err; } } return num_vfs; } /** * fm10k_iov_update_stats - Update stats for all VFs * @interface: device private structure * * Updates the VF statistics for all enabled VFs. Expects to be called by * fm10k_update_stats and assumes that locking via the __FM10K_UPDATING_STATS * bit is already handled. */ void fm10k_iov_update_stats(struct fm10k_intfc *interface) { struct fm10k_iov_data *iov_data = interface->iov_data; struct fm10k_hw *hw = &interface->hw; int i; if (!iov_data) return; for (i = 0; i < iov_data->num_vfs; i++) hw->iov.ops.update_stats(hw, iov_data->vf_info[i].stats, i); } static inline void fm10k_reset_vf_info(struct fm10k_intfc *interface, struct fm10k_vf_info *vf_info) { struct fm10k_hw *hw = &interface->hw; /* assigning the MAC address will send a mailbox message */ fm10k_mbx_lock(interface); /* disable LPORT for this VF which clears switch rules */ hw->iov.ops.reset_lport(hw, vf_info); fm10k_clear_macvlan_queue(interface, vf_info->glort, false); /* assign new MAC+VLAN for this VF */ hw->iov.ops.assign_default_mac_vlan(hw, vf_info); /* re-enable the LPORT for this VF */ hw->iov.ops.set_lport(hw, vf_info, vf_info->vf_idx, FM10K_VF_FLAG_MULTI_CAPABLE); fm10k_mbx_unlock(interface); } int fm10k_ndo_set_vf_mac(struct net_device *netdev, int vf_idx, u8 *mac) { struct fm10k_intfc *interface = netdev_priv(netdev); struct fm10k_iov_data *iov_data = interface->iov_data; struct fm10k_vf_info *vf_info; /* verify SR-IOV is active and that vf idx is valid */ if (!iov_data || vf_idx >= iov_data->num_vfs) return -EINVAL; /* verify MAC addr is valid */ if (!is_zero_ether_addr(mac) && !is_valid_ether_addr(mac)) return -EINVAL; /* record new MAC address */ vf_info = &iov_data->vf_info[vf_idx]; ether_addr_copy(vf_info->mac, mac); fm10k_reset_vf_info(interface, vf_info); return 0; } int fm10k_ndo_set_vf_vlan(struct net_device *netdev, int vf_idx, u16 vid, u8 qos, __be16 vlan_proto) { struct fm10k_intfc *interface = netdev_priv(netdev); struct fm10k_iov_data *iov_data = interface->iov_data; struct fm10k_hw *hw = &interface->hw; struct fm10k_vf_info *vf_info; /* verify SR-IOV is active and that vf idx is valid */ if (!iov_data || vf_idx >= iov_data->num_vfs) return -EINVAL; /* QOS is unsupported and VLAN IDs accepted range 0-4094 */ if (qos || (vid > (VLAN_VID_MASK - 1))) return -EINVAL; /* VF VLAN Protocol part to default is unsupported */ if (vlan_proto != htons(ETH_P_8021Q)) return -EPROTONOSUPPORT; vf_info = &iov_data->vf_info[vf_idx]; /* exit if there is nothing to do */ if (vf_info->pf_vid == vid) return 0; /* record default VLAN ID for VF */ vf_info->pf_vid = vid; /* Clear the VLAN table for the VF */ hw->mac.ops.update_vlan(hw, FM10K_VLAN_ALL, vf_info->vsi, false); fm10k_reset_vf_info(interface, vf_info); return 0; } int fm10k_ndo_set_vf_bw(struct net_device *netdev, int vf_idx, int __always_unused min_rate, int max_rate) { struct fm10k_intfc *interface = netdev_priv(netdev); struct fm10k_iov_data *iov_data = interface->iov_data; struct fm10k_hw *hw = &interface->hw; /* verify SR-IOV is active and that vf idx is valid */ if (!iov_data || vf_idx >= iov_data->num_vfs) return -EINVAL; /* rate limit cannot be less than 10Mbs or greater than link speed */ if (max_rate && (max_rate < FM10K_VF_TC_MIN || max_rate > FM10K_VF_TC_MAX)) return -EINVAL; /* store values */ iov_data->vf_info[vf_idx].rate = max_rate; /* update hardware configuration */ hw->iov.ops.configure_tc(hw, vf_idx, max_rate); return 0; } int fm10k_ndo_get_vf_config(struct net_device *netdev, int vf_idx, struct ifla_vf_info *ivi) { struct fm10k_intfc *interface = netdev_priv(netdev); struct fm10k_iov_data *iov_data = interface->iov_data; struct fm10k_vf_info *vf_info; /* verify SR-IOV is active and that vf idx is valid */ if (!iov_data || vf_idx >= iov_data->num_vfs) return -EINVAL; vf_info = &iov_data->vf_info[vf_idx]; ivi->vf = vf_idx; ivi->max_tx_rate = vf_info->rate; ivi->min_tx_rate = 0; ether_addr_copy(ivi->mac, vf_info->mac); ivi->vlan = vf_info->pf_vid; ivi->qos = 0; return 0; } int fm10k_ndo_get_vf_stats(struct net_device *netdev, int vf_idx, struct ifla_vf_stats *stats) { struct fm10k_intfc *interface = netdev_priv(netdev); struct fm10k_iov_data *iov_data = interface->iov_data; struct fm10k_hw *hw = &interface->hw; struct fm10k_hw_stats_q *hw_stats; u32 idx, qpp; /* verify SR-IOV is active and that vf idx is valid */ if (!iov_data || vf_idx >= iov_data->num_vfs) return -EINVAL; qpp = fm10k_queues_per_pool(hw); hw_stats = iov_data->vf_info[vf_idx].stats; for (idx = 0; idx < qpp; idx++) { stats->rx_packets += hw_stats[idx].rx_packets.count; stats->tx_packets += hw_stats[idx].tx_packets.count; stats->rx_bytes += hw_stats[idx].rx_bytes.count; stats->tx_bytes += hw_stats[idx].tx_bytes.count; stats->rx_dropped += hw_stats[idx].rx_drops.count; } return 0; }
linux-master
drivers/net/ethernet/intel/fm10k/fm10k_iov.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2013 - 2019 Intel Corporation. */ #include "fm10k_pf.h" #include "fm10k_vf.h" /** * fm10k_reset_hw_pf - PF hardware reset * @hw: pointer to hardware structure * * This function should return the hardware to a state similar to the * one it is in after being powered on. **/ static s32 fm10k_reset_hw_pf(struct fm10k_hw *hw) { s32 err; u32 reg; u16 i; /* Disable interrupts */ fm10k_write_reg(hw, FM10K_EIMR, FM10K_EIMR_DISABLE(ALL)); /* Lock ITR2 reg 0 into itself and disable interrupt moderation */ fm10k_write_reg(hw, FM10K_ITR2(0), 0); fm10k_write_reg(hw, FM10K_INT_CTRL, 0); /* We assume here Tx and Rx queue 0 are owned by the PF */ /* Shut off VF access to their queues forcing them to queue 0 */ for (i = 0; i < FM10K_TQMAP_TABLE_SIZE; i++) { fm10k_write_reg(hw, FM10K_TQMAP(i), 0); fm10k_write_reg(hw, FM10K_RQMAP(i), 0); } /* shut down all rings */ err = fm10k_disable_queues_generic(hw, FM10K_MAX_QUEUES); if (err == FM10K_ERR_REQUESTS_PENDING) { hw->mac.reset_while_pending++; goto force_reset; } else if (err) { return err; } /* Verify that DMA is no longer active */ reg = fm10k_read_reg(hw, FM10K_DMA_CTRL); if (reg & (FM10K_DMA_CTRL_TX_ACTIVE | FM10K_DMA_CTRL_RX_ACTIVE)) return FM10K_ERR_DMA_PENDING; force_reset: /* Inititate data path reset */ reg = FM10K_DMA_CTRL_DATAPATH_RESET; fm10k_write_reg(hw, FM10K_DMA_CTRL, reg); /* Flush write and allow 100us for reset to complete */ fm10k_write_flush(hw); udelay(FM10K_RESET_TIMEOUT); /* Verify we made it out of reset */ reg = fm10k_read_reg(hw, FM10K_IP); if (!(reg & FM10K_IP_NOTINRESET)) return FM10K_ERR_RESET_FAILED; return 0; } /** * fm10k_is_ari_hierarchy_pf - Indicate ARI hierarchy support * @hw: pointer to hardware structure * * Looks at the ARI hierarchy bit to determine whether ARI is supported or not. **/ static bool fm10k_is_ari_hierarchy_pf(struct fm10k_hw *hw) { u16 sriov_ctrl = fm10k_read_pci_cfg_word(hw, FM10K_PCIE_SRIOV_CTRL); return !!(sriov_ctrl & FM10K_PCIE_SRIOV_CTRL_VFARI); } /** * fm10k_init_hw_pf - PF hardware initialization * @hw: pointer to hardware structure * **/ static s32 fm10k_init_hw_pf(struct fm10k_hw *hw) { u32 dma_ctrl, txqctl; u16 i; /* Establish default VSI as valid */ fm10k_write_reg(hw, FM10K_DGLORTDEC(fm10k_dglort_default), 0); fm10k_write_reg(hw, FM10K_DGLORTMAP(fm10k_dglort_default), FM10K_DGLORTMAP_ANY); /* Invalidate all other GLORT entries */ for (i = 1; i < FM10K_DGLORT_COUNT; i++) fm10k_write_reg(hw, FM10K_DGLORTMAP(i), FM10K_DGLORTMAP_NONE); /* reset ITR2(0) to point to itself */ fm10k_write_reg(hw, FM10K_ITR2(0), 0); /* reset VF ITR2(0) to point to 0 avoid PF registers */ fm10k_write_reg(hw, FM10K_ITR2(FM10K_ITR_REG_COUNT_PF), 0); /* loop through all PF ITR2 registers pointing them to the previous */ for (i = 1; i < FM10K_ITR_REG_COUNT_PF; i++) fm10k_write_reg(hw, FM10K_ITR2(i), i - 1); /* Enable interrupt moderator if not already enabled */ fm10k_write_reg(hw, FM10K_INT_CTRL, FM10K_INT_CTRL_ENABLEMODERATOR); /* compute the default txqctl configuration */ txqctl = FM10K_TXQCTL_PF | FM10K_TXQCTL_UNLIMITED_BW | (hw->mac.default_vid << FM10K_TXQCTL_VID_SHIFT); for (i = 0; i < FM10K_MAX_QUEUES; i++) { /* configure rings for 256 Queue / 32 Descriptor cache mode */ fm10k_write_reg(hw, FM10K_TQDLOC(i), (i * FM10K_TQDLOC_BASE_32_DESC) | FM10K_TQDLOC_SIZE_32_DESC); fm10k_write_reg(hw, FM10K_TXQCTL(i), txqctl); /* configure rings to provide TPH processing hints */ fm10k_write_reg(hw, FM10K_TPH_TXCTRL(i), FM10K_TPH_TXCTRL_DESC_TPHEN | FM10K_TPH_TXCTRL_DESC_RROEN | FM10K_TPH_TXCTRL_DESC_WROEN | FM10K_TPH_TXCTRL_DATA_RROEN); fm10k_write_reg(hw, FM10K_TPH_RXCTRL(i), FM10K_TPH_RXCTRL_DESC_TPHEN | FM10K_TPH_RXCTRL_DESC_RROEN | FM10K_TPH_RXCTRL_DATA_WROEN | FM10K_TPH_RXCTRL_HDR_WROEN); } /* set max hold interval to align with 1.024 usec in all modes and * store ITR scale */ switch (hw->bus.speed) { case fm10k_bus_speed_2500: dma_ctrl = FM10K_DMA_CTRL_MAX_HOLD_1US_GEN1; hw->mac.itr_scale = FM10K_TDLEN_ITR_SCALE_GEN1; break; case fm10k_bus_speed_5000: dma_ctrl = FM10K_DMA_CTRL_MAX_HOLD_1US_GEN2; hw->mac.itr_scale = FM10K_TDLEN_ITR_SCALE_GEN2; break; case fm10k_bus_speed_8000: dma_ctrl = FM10K_DMA_CTRL_MAX_HOLD_1US_GEN3; hw->mac.itr_scale = FM10K_TDLEN_ITR_SCALE_GEN3; break; default: dma_ctrl = 0; /* just in case, assume Gen3 ITR scale */ hw->mac.itr_scale = FM10K_TDLEN_ITR_SCALE_GEN3; break; } /* Configure TSO flags */ fm10k_write_reg(hw, FM10K_DTXTCPFLGL, FM10K_TSO_FLAGS_LOW); fm10k_write_reg(hw, FM10K_DTXTCPFLGH, FM10K_TSO_FLAGS_HI); /* Enable DMA engine * Set Rx Descriptor size to 32 * Set Minimum MSS to 64 * Set Maximum number of Rx queues to 256 / 32 Descriptor */ dma_ctrl |= FM10K_DMA_CTRL_TX_ENABLE | FM10K_DMA_CTRL_RX_ENABLE | FM10K_DMA_CTRL_RX_DESC_SIZE | FM10K_DMA_CTRL_MINMSS_64 | FM10K_DMA_CTRL_32_DESC; fm10k_write_reg(hw, FM10K_DMA_CTRL, dma_ctrl); /* record maximum queue count, we limit ourselves to 128 */ hw->mac.max_queues = FM10K_MAX_QUEUES_PF; /* We support either 64 VFs or 7 VFs depending on if we have ARI */ hw->iov.total_vfs = fm10k_is_ari_hierarchy_pf(hw) ? 64 : 7; return 0; } /** * fm10k_update_vlan_pf - Update status of VLAN ID in VLAN filter table * @hw: pointer to hardware structure * @vid: VLAN ID to add to table * @vsi: Index indicating VF ID or PF ID in table * @set: Indicates if this is a set or clear operation * * This function adds or removes the corresponding VLAN ID from the VLAN * filter table for the corresponding function. In addition to the * standard set/clear that supports one bit a multi-bit write is * supported to set 64 bits at a time. **/ static s32 fm10k_update_vlan_pf(struct fm10k_hw *hw, u32 vid, u8 vsi, bool set) { u32 vlan_table, reg, mask, bit, len; /* verify the VSI index is valid */ if (vsi > FM10K_VLAN_TABLE_VSI_MAX) return FM10K_ERR_PARAM; /* VLAN multi-bit write: * The multi-bit write has several parts to it. * 24 16 8 0 * 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | RSVD0 | Length |C|RSVD0| VLAN ID | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * VLAN ID: Vlan Starting value * RSVD0: Reserved section, must be 0 * C: Flag field, 0 is set, 1 is clear (Used in VF VLAN message) * Length: Number of times to repeat the bit being set */ len = vid >> 16; vid = (vid << 17) >> 17; /* verify the reserved 0 fields are 0 */ if (len >= FM10K_VLAN_TABLE_VID_MAX || vid >= FM10K_VLAN_TABLE_VID_MAX) return FM10K_ERR_PARAM; /* Loop through the table updating all required VLANs */ for (reg = FM10K_VLAN_TABLE(vsi, vid / 32), bit = vid % 32; len < FM10K_VLAN_TABLE_VID_MAX; len -= 32 - bit, reg++, bit = 0) { /* record the initial state of the register */ vlan_table = fm10k_read_reg(hw, reg); /* truncate mask if we are at the start or end of the run */ mask = (~(u32)0 >> ((len < 31) ? 31 - len : 0)) << bit; /* make necessary modifications to the register */ mask &= set ? ~vlan_table : vlan_table; if (mask) fm10k_write_reg(hw, reg, vlan_table ^ mask); } return 0; } /** * fm10k_read_mac_addr_pf - Read device MAC address * @hw: pointer to the HW structure * * Reads the device MAC address from the SM_AREA and stores the value. **/ static s32 fm10k_read_mac_addr_pf(struct fm10k_hw *hw) { u8 perm_addr[ETH_ALEN]; u32 serial_num; serial_num = fm10k_read_reg(hw, FM10K_SM_AREA(1)); /* last byte should be all 1's */ if ((~serial_num) << 24) return FM10K_ERR_INVALID_MAC_ADDR; perm_addr[0] = (u8)(serial_num >> 24); perm_addr[1] = (u8)(serial_num >> 16); perm_addr[2] = (u8)(serial_num >> 8); serial_num = fm10k_read_reg(hw, FM10K_SM_AREA(0)); /* first byte should be all 1's */ if ((~serial_num) >> 24) return FM10K_ERR_INVALID_MAC_ADDR; perm_addr[3] = (u8)(serial_num >> 16); perm_addr[4] = (u8)(serial_num >> 8); perm_addr[5] = (u8)(serial_num); ether_addr_copy(hw->mac.perm_addr, perm_addr); ether_addr_copy(hw->mac.addr, perm_addr); return 0; } /** * fm10k_glort_valid_pf - Validate that the provided glort is valid * @hw: pointer to the HW structure * @glort: base glort to be validated * * This function will return an error if the provided glort is invalid **/ bool fm10k_glort_valid_pf(struct fm10k_hw *hw, u16 glort) { glort &= hw->mac.dglort_map >> FM10K_DGLORTMAP_MASK_SHIFT; return glort == (hw->mac.dglort_map & FM10K_DGLORTMAP_NONE); } /** * fm10k_update_xc_addr_pf - Update device addresses * @hw: pointer to the HW structure * @glort: base resource tag for this request * @mac: MAC address to add/remove from table * @vid: VLAN ID to add/remove from table * @add: Indicates if this is an add or remove operation * @flags: flags field to indicate add and secure * * This function generates a message to the Switch API requesting * that the given logical port add/remove the given L2 MAC/VLAN address. **/ static s32 fm10k_update_xc_addr_pf(struct fm10k_hw *hw, u16 glort, const u8 *mac, u16 vid, bool add, u8 flags) { struct fm10k_mbx_info *mbx = &hw->mbx; struct fm10k_mac_update mac_update; u32 msg[5]; /* clear set bit from VLAN ID */ vid &= ~FM10K_VLAN_CLEAR; /* if glort or VLAN are not valid return error */ if (!fm10k_glort_valid_pf(hw, glort) || vid >= FM10K_VLAN_TABLE_VID_MAX) return FM10K_ERR_PARAM; /* record fields */ mac_update.mac_lower = cpu_to_le32(((u32)mac[2] << 24) | ((u32)mac[3] << 16) | ((u32)mac[4] << 8) | ((u32)mac[5])); mac_update.mac_upper = cpu_to_le16(((u16)mac[0] << 8) | ((u16)mac[1])); mac_update.vlan = cpu_to_le16(vid); mac_update.glort = cpu_to_le16(glort); mac_update.action = add ? 0 : 1; mac_update.flags = flags; /* populate mac_update fields */ fm10k_tlv_msg_init(msg, FM10K_PF_MSG_ID_UPDATE_MAC_FWD_RULE); fm10k_tlv_attr_put_le_struct(msg, FM10K_PF_ATTR_ID_MAC_UPDATE, &mac_update, sizeof(mac_update)); /* load onto outgoing mailbox */ return mbx->ops.enqueue_tx(hw, mbx, msg); } /** * fm10k_update_uc_addr_pf - Update device unicast addresses * @hw: pointer to the HW structure * @glort: base resource tag for this request * @mac: MAC address to add/remove from table * @vid: VLAN ID to add/remove from table * @add: Indicates if this is an add or remove operation * @flags: flags field to indicate add and secure * * This function is used to add or remove unicast addresses for * the PF. **/ static s32 fm10k_update_uc_addr_pf(struct fm10k_hw *hw, u16 glort, const u8 *mac, u16 vid, bool add, u8 flags) { /* verify MAC address is valid */ if (!is_valid_ether_addr(mac)) return FM10K_ERR_PARAM; return fm10k_update_xc_addr_pf(hw, glort, mac, vid, add, flags); } /** * fm10k_update_mc_addr_pf - Update device multicast addresses * @hw: pointer to the HW structure * @glort: base resource tag for this request * @mac: MAC address to add/remove from table * @vid: VLAN ID to add/remove from table * @add: Indicates if this is an add or remove operation * * This function is used to add or remove multicast MAC addresses for * the PF. **/ static s32 fm10k_update_mc_addr_pf(struct fm10k_hw *hw, u16 glort, const u8 *mac, u16 vid, bool add) { /* verify multicast address is valid */ if (!is_multicast_ether_addr(mac)) return FM10K_ERR_PARAM; return fm10k_update_xc_addr_pf(hw, glort, mac, vid, add, 0); } /** * fm10k_update_xcast_mode_pf - Request update of multicast mode * @hw: pointer to hardware structure * @glort: base resource tag for this request * @mode: integer value indicating mode being requested * * This function will attempt to request a higher mode for the port * so that it can enable either multicast, multicast promiscuous, or * promiscuous mode of operation. **/ static s32 fm10k_update_xcast_mode_pf(struct fm10k_hw *hw, u16 glort, u8 mode) { struct fm10k_mbx_info *mbx = &hw->mbx; u32 msg[3], xcast_mode; if (mode > FM10K_XCAST_MODE_NONE) return FM10K_ERR_PARAM; /* if glort is not valid return error */ if (!fm10k_glort_valid_pf(hw, glort)) return FM10K_ERR_PARAM; /* write xcast mode as a single u32 value, * lower 16 bits: glort * upper 16 bits: mode */ xcast_mode = ((u32)mode << 16) | glort; /* generate message requesting to change xcast mode */ fm10k_tlv_msg_init(msg, FM10K_PF_MSG_ID_XCAST_MODES); fm10k_tlv_attr_put_u32(msg, FM10K_PF_ATTR_ID_XCAST_MODE, xcast_mode); /* load onto outgoing mailbox */ return mbx->ops.enqueue_tx(hw, mbx, msg); } /** * fm10k_update_int_moderator_pf - Update interrupt moderator linked list * @hw: pointer to hardware structure * * This function walks through the MSI-X vector table to determine the * number of active interrupts and based on that information updates the * interrupt moderator linked list. **/ static void fm10k_update_int_moderator_pf(struct fm10k_hw *hw) { u32 i; /* Disable interrupt moderator */ fm10k_write_reg(hw, FM10K_INT_CTRL, 0); /* loop through PF from last to first looking enabled vectors */ for (i = FM10K_ITR_REG_COUNT_PF - 1; i; i--) { if (!fm10k_read_reg(hw, FM10K_MSIX_VECTOR_MASK(i))) break; } /* always reset VFITR2[0] to point to last enabled PF vector */ fm10k_write_reg(hw, FM10K_ITR2(FM10K_ITR_REG_COUNT_PF), i); /* reset ITR2[0] to point to last enabled PF vector */ if (!hw->iov.num_vfs) fm10k_write_reg(hw, FM10K_ITR2(0), i); /* Enable interrupt moderator */ fm10k_write_reg(hw, FM10K_INT_CTRL, FM10K_INT_CTRL_ENABLEMODERATOR); } /** * fm10k_update_lport_state_pf - Notify the switch of a change in port state * @hw: pointer to the HW structure * @glort: base resource tag for this request * @count: number of logical ports being updated * @enable: boolean value indicating enable or disable * * This function is used to add/remove a logical port from the switch. **/ static s32 fm10k_update_lport_state_pf(struct fm10k_hw *hw, u16 glort, u16 count, bool enable) { struct fm10k_mbx_info *mbx = &hw->mbx; u32 msg[3], lport_msg; /* do nothing if we are being asked to create or destroy 0 ports */ if (!count) return 0; /* if glort is not valid return error */ if (!fm10k_glort_valid_pf(hw, glort)) return FM10K_ERR_PARAM; /* reset multicast mode if deleting lport */ if (!enable) fm10k_update_xcast_mode_pf(hw, glort, FM10K_XCAST_MODE_NONE); /* construct the lport message from the 2 pieces of data we have */ lport_msg = ((u32)count << 16) | glort; /* generate lport create/delete message */ fm10k_tlv_msg_init(msg, enable ? FM10K_PF_MSG_ID_LPORT_CREATE : FM10K_PF_MSG_ID_LPORT_DELETE); fm10k_tlv_attr_put_u32(msg, FM10K_PF_ATTR_ID_PORT, lport_msg); /* load onto outgoing mailbox */ return mbx->ops.enqueue_tx(hw, mbx, msg); } /** * fm10k_configure_dglort_map_pf - Configures GLORT entry and queues * @hw: pointer to hardware structure * @dglort: pointer to dglort configuration structure * * Reads the configuration structure contained in dglort_cfg and uses * that information to then populate a DGLORTMAP/DEC entry and the queues * to which it has been assigned. **/ static s32 fm10k_configure_dglort_map_pf(struct fm10k_hw *hw, struct fm10k_dglort_cfg *dglort) { u16 glort, queue_count, vsi_count, pc_count; u16 vsi, queue, pc, q_idx; u32 txqctl, dglortdec, dglortmap; /* verify the dglort pointer */ if (!dglort) return FM10K_ERR_PARAM; /* verify the dglort values */ if ((dglort->idx > 7) || (dglort->rss_l > 7) || (dglort->pc_l > 3) || (dglort->vsi_l > 6) || (dglort->vsi_b > 64) || (dglort->queue_l > 8) || (dglort->queue_b >= 256)) return FM10K_ERR_PARAM; /* determine count of VSIs and queues */ queue_count = BIT(dglort->rss_l + dglort->pc_l); vsi_count = BIT(dglort->vsi_l + dglort->queue_l); glort = dglort->glort; q_idx = dglort->queue_b; /* configure SGLORT for queues */ for (vsi = 0; vsi < vsi_count; vsi++, glort++) { for (queue = 0; queue < queue_count; queue++, q_idx++) { if (q_idx >= FM10K_MAX_QUEUES) break; fm10k_write_reg(hw, FM10K_TX_SGLORT(q_idx), glort); fm10k_write_reg(hw, FM10K_RX_SGLORT(q_idx), glort); } } /* determine count of PCs and queues */ queue_count = BIT(dglort->queue_l + dglort->rss_l + dglort->vsi_l); pc_count = BIT(dglort->pc_l); /* configure PC for Tx queues */ for (pc = 0; pc < pc_count; pc++) { q_idx = pc + dglort->queue_b; for (queue = 0; queue < queue_count; queue++) { if (q_idx >= FM10K_MAX_QUEUES) break; txqctl = fm10k_read_reg(hw, FM10K_TXQCTL(q_idx)); txqctl &= ~FM10K_TXQCTL_PC_MASK; txqctl |= pc << FM10K_TXQCTL_PC_SHIFT; fm10k_write_reg(hw, FM10K_TXQCTL(q_idx), txqctl); q_idx += pc_count; } } /* configure DGLORTDEC */ dglortdec = ((u32)(dglort->rss_l) << FM10K_DGLORTDEC_RSSLENGTH_SHIFT) | ((u32)(dglort->queue_b) << FM10K_DGLORTDEC_QBASE_SHIFT) | ((u32)(dglort->pc_l) << FM10K_DGLORTDEC_PCLENGTH_SHIFT) | ((u32)(dglort->vsi_b) << FM10K_DGLORTDEC_VSIBASE_SHIFT) | ((u32)(dglort->vsi_l) << FM10K_DGLORTDEC_VSILENGTH_SHIFT) | ((u32)(dglort->queue_l)); if (dglort->inner_rss) dglortdec |= FM10K_DGLORTDEC_INNERRSS_ENABLE; /* configure DGLORTMAP */ dglortmap = (dglort->idx == fm10k_dglort_default) ? FM10K_DGLORTMAP_ANY : FM10K_DGLORTMAP_ZERO; dglortmap <<= dglort->vsi_l + dglort->queue_l + dglort->shared_l; dglortmap |= dglort->glort; /* write values to hardware */ fm10k_write_reg(hw, FM10K_DGLORTDEC(dglort->idx), dglortdec); fm10k_write_reg(hw, FM10K_DGLORTMAP(dglort->idx), dglortmap); return 0; } u16 fm10k_queues_per_pool(struct fm10k_hw *hw) { u16 num_pools = hw->iov.num_pools; return (num_pools > 32) ? 2 : (num_pools > 16) ? 4 : (num_pools > 8) ? 8 : FM10K_MAX_QUEUES_POOL; } u16 fm10k_vf_queue_index(struct fm10k_hw *hw, u16 vf_idx) { u16 num_vfs = hw->iov.num_vfs; u16 vf_q_idx = FM10K_MAX_QUEUES; vf_q_idx -= fm10k_queues_per_pool(hw) * (num_vfs - vf_idx); return vf_q_idx; } static u16 fm10k_vectors_per_pool(struct fm10k_hw *hw) { u16 num_pools = hw->iov.num_pools; return (num_pools > 32) ? 8 : (num_pools > 16) ? 16 : FM10K_MAX_VECTORS_POOL; } static u16 fm10k_vf_vector_index(struct fm10k_hw *hw, u16 vf_idx) { u16 vf_v_idx = FM10K_MAX_VECTORS_PF; vf_v_idx += fm10k_vectors_per_pool(hw) * vf_idx; return vf_v_idx; } /** * fm10k_iov_assign_resources_pf - Assign pool resources for virtualization * @hw: pointer to the HW structure * @num_vfs: number of VFs to be allocated * @num_pools: number of virtualization pools to be allocated * * Allocates queues and traffic classes to virtualization entities to prepare * the PF for SR-IOV and VMDq **/ static s32 fm10k_iov_assign_resources_pf(struct fm10k_hw *hw, u16 num_vfs, u16 num_pools) { u16 qmap_stride, qpp, vpp, vf_q_idx, vf_q_idx0, qmap_idx; u32 vid = hw->mac.default_vid << FM10K_TXQCTL_VID_SHIFT; int i, j; /* hardware only supports up to 64 pools */ if (num_pools > 64) return FM10K_ERR_PARAM; /* the number of VFs cannot exceed the number of pools */ if ((num_vfs > num_pools) || (num_vfs > hw->iov.total_vfs)) return FM10K_ERR_PARAM; /* record number of virtualization entities */ hw->iov.num_vfs = num_vfs; hw->iov.num_pools = num_pools; /* determine qmap offsets and counts */ qmap_stride = (num_vfs > 8) ? 32 : 256; qpp = fm10k_queues_per_pool(hw); vpp = fm10k_vectors_per_pool(hw); /* calculate starting index for queues */ vf_q_idx = fm10k_vf_queue_index(hw, 0); qmap_idx = 0; /* establish TCs with -1 credits and no quanta to prevent transmit */ for (i = 0; i < num_vfs; i++) { fm10k_write_reg(hw, FM10K_TC_MAXCREDIT(i), 0); fm10k_write_reg(hw, FM10K_TC_RATE(i), 0); fm10k_write_reg(hw, FM10K_TC_CREDIT(i), FM10K_TC_CREDIT_CREDIT_MASK); } /* zero out all mbmem registers */ for (i = FM10K_VFMBMEM_LEN * num_vfs; i--;) fm10k_write_reg(hw, FM10K_MBMEM(i), 0); /* clear event notification of VF FLR */ fm10k_write_reg(hw, FM10K_PFVFLREC(0), ~0); fm10k_write_reg(hw, FM10K_PFVFLREC(1), ~0); /* loop through unallocated rings assigning them back to PF */ for (i = FM10K_MAX_QUEUES_PF; i < vf_q_idx; i++) { fm10k_write_reg(hw, FM10K_TXDCTL(i), 0); fm10k_write_reg(hw, FM10K_TXQCTL(i), FM10K_TXQCTL_PF | FM10K_TXQCTL_UNLIMITED_BW | vid); fm10k_write_reg(hw, FM10K_RXQCTL(i), FM10K_RXQCTL_PF); } /* PF should have already updated VFITR2[0] */ /* update all ITR registers to flow to VFITR2[0] */ for (i = FM10K_ITR_REG_COUNT_PF + 1; i < FM10K_ITR_REG_COUNT; i++) { if (!(i & (vpp - 1))) fm10k_write_reg(hw, FM10K_ITR2(i), i - vpp); else fm10k_write_reg(hw, FM10K_ITR2(i), i - 1); } /* update PF ITR2[0] to reference the last vector */ fm10k_write_reg(hw, FM10K_ITR2(0), fm10k_vf_vector_index(hw, num_vfs - 1)); /* loop through rings populating rings and TCs */ for (i = 0; i < num_vfs; i++) { /* record index for VF queue 0 for use in end of loop */ vf_q_idx0 = vf_q_idx; for (j = 0; j < qpp; j++, qmap_idx++, vf_q_idx++) { /* assign VF and locked TC to queues */ fm10k_write_reg(hw, FM10K_TXDCTL(vf_q_idx), 0); fm10k_write_reg(hw, FM10K_TXQCTL(vf_q_idx), (i << FM10K_TXQCTL_TC_SHIFT) | i | FM10K_TXQCTL_VF | vid); fm10k_write_reg(hw, FM10K_RXDCTL(vf_q_idx), FM10K_RXDCTL_WRITE_BACK_MIN_DELAY | FM10K_RXDCTL_DROP_ON_EMPTY); fm10k_write_reg(hw, FM10K_RXQCTL(vf_q_idx), (i << FM10K_RXQCTL_VF_SHIFT) | FM10K_RXQCTL_VF); /* map queue pair to VF */ fm10k_write_reg(hw, FM10K_TQMAP(qmap_idx), vf_q_idx); fm10k_write_reg(hw, FM10K_RQMAP(qmap_idx), vf_q_idx); } /* repeat the first ring for all of the remaining VF rings */ for (; j < qmap_stride; j++, qmap_idx++) { fm10k_write_reg(hw, FM10K_TQMAP(qmap_idx), vf_q_idx0); fm10k_write_reg(hw, FM10K_RQMAP(qmap_idx), vf_q_idx0); } } /* loop through remaining indexes assigning all to queue 0 */ while (qmap_idx < FM10K_TQMAP_TABLE_SIZE) { fm10k_write_reg(hw, FM10K_TQMAP(qmap_idx), 0); fm10k_write_reg(hw, FM10K_RQMAP(qmap_idx), 0); qmap_idx++; } return 0; } /** * fm10k_iov_configure_tc_pf - Configure the shaping group for VF * @hw: pointer to the HW structure * @vf_idx: index of VF receiving GLORT * @rate: Rate indicated in Mb/s * * Configured the TC for a given VF to allow only up to a given number * of Mb/s of outgoing Tx throughput. **/ static s32 fm10k_iov_configure_tc_pf(struct fm10k_hw *hw, u16 vf_idx, int rate) { /* configure defaults */ u32 interval = FM10K_TC_RATE_INTERVAL_4US_GEN3; u32 tc_rate = FM10K_TC_RATE_QUANTA_MASK; /* verify vf is in range */ if (vf_idx >= hw->iov.num_vfs) return FM10K_ERR_PARAM; /* set interval to align with 4.096 usec in all modes */ switch (hw->bus.speed) { case fm10k_bus_speed_2500: interval = FM10K_TC_RATE_INTERVAL_4US_GEN1; break; case fm10k_bus_speed_5000: interval = FM10K_TC_RATE_INTERVAL_4US_GEN2; break; default: break; } if (rate) { if (rate > FM10K_VF_TC_MAX || rate < FM10K_VF_TC_MIN) return FM10K_ERR_PARAM; /* The quanta is measured in Bytes per 4.096 or 8.192 usec * The rate is provided in Mbits per second * To tralslate from rate to quanta we need to multiply the * rate by 8.192 usec and divide by 8 bits/byte. To avoid * dealing with floating point we can round the values up * to the nearest whole number ratio which gives us 128 / 125. */ tc_rate = (rate * 128) / 125; /* try to keep the rate limiting accurate by increasing * the number of credits and interval for rates less than 4Gb/s */ if (rate < 4000) interval <<= 1; else tc_rate >>= 1; } /* update rate limiter with new values */ fm10k_write_reg(hw, FM10K_TC_RATE(vf_idx), tc_rate | interval); fm10k_write_reg(hw, FM10K_TC_MAXCREDIT(vf_idx), FM10K_TC_MAXCREDIT_64K); fm10k_write_reg(hw, FM10K_TC_CREDIT(vf_idx), FM10K_TC_MAXCREDIT_64K); return 0; } /** * fm10k_iov_assign_int_moderator_pf - Add VF interrupts to moderator list * @hw: pointer to the HW structure * @vf_idx: index of VF receiving GLORT * * Update the interrupt moderator linked list to include any MSI-X * interrupts which the VF has enabled in the MSI-X vector table. **/ static s32 fm10k_iov_assign_int_moderator_pf(struct fm10k_hw *hw, u16 vf_idx) { u16 vf_v_idx, vf_v_limit, i; /* verify vf is in range */ if (vf_idx >= hw->iov.num_vfs) return FM10K_ERR_PARAM; /* determine vector offset and count */ vf_v_idx = fm10k_vf_vector_index(hw, vf_idx); vf_v_limit = vf_v_idx + fm10k_vectors_per_pool(hw); /* search for first vector that is not masked */ for (i = vf_v_limit - 1; i > vf_v_idx; i--) { if (!fm10k_read_reg(hw, FM10K_MSIX_VECTOR_MASK(i))) break; } /* reset linked list so it now includes our active vectors */ if (vf_idx == (hw->iov.num_vfs - 1)) fm10k_write_reg(hw, FM10K_ITR2(0), i); else fm10k_write_reg(hw, FM10K_ITR2(vf_v_limit), i); return 0; } /** * fm10k_iov_assign_default_mac_vlan_pf - Assign a MAC and VLAN to VF * @hw: pointer to the HW structure * @vf_info: pointer to VF information structure * * Assign a MAC address and default VLAN to a VF and notify it of the update **/ static s32 fm10k_iov_assign_default_mac_vlan_pf(struct fm10k_hw *hw, struct fm10k_vf_info *vf_info) { u16 qmap_stride, queues_per_pool, vf_q_idx, timeout, qmap_idx, i; u32 msg[4], txdctl, txqctl, tdbal = 0, tdbah = 0; s32 err = 0; u16 vf_idx, vf_vid; /* verify vf is in range */ if (!vf_info || vf_info->vf_idx >= hw->iov.num_vfs) return FM10K_ERR_PARAM; /* determine qmap offsets and counts */ qmap_stride = (hw->iov.num_vfs > 8) ? 32 : 256; queues_per_pool = fm10k_queues_per_pool(hw); /* calculate starting index for queues */ vf_idx = vf_info->vf_idx; vf_q_idx = fm10k_vf_queue_index(hw, vf_idx); qmap_idx = qmap_stride * vf_idx; /* Determine correct default VLAN ID. The FM10K_VLAN_OVERRIDE bit is * used here to indicate to the VF that it will not have privilege to * write VLAN_TABLE. All policy is enforced on the PF but this allows * the VF to correctly report errors to userspace requests. */ if (vf_info->pf_vid) vf_vid = vf_info->pf_vid | FM10K_VLAN_OVERRIDE; else vf_vid = vf_info->sw_vid; /* generate MAC_ADDR request */ fm10k_tlv_msg_init(msg, FM10K_VF_MSG_ID_MAC_VLAN); fm10k_tlv_attr_put_mac_vlan(msg, FM10K_MAC_VLAN_MSG_DEFAULT_MAC, vf_info->mac, vf_vid); /* Configure Queue control register with new VLAN ID. The TXQCTL * register is RO from the VF, so the PF must do this even in the * case of notifying the VF of a new VID via the mailbox. */ txqctl = ((u32)vf_vid << FM10K_TXQCTL_VID_SHIFT) & FM10K_TXQCTL_VID_MASK; txqctl |= (vf_idx << FM10K_TXQCTL_TC_SHIFT) | FM10K_TXQCTL_VF | vf_idx; for (i = 0; i < queues_per_pool; i++) fm10k_write_reg(hw, FM10K_TXQCTL(vf_q_idx + i), txqctl); /* try loading a message onto outgoing mailbox first */ if (vf_info->mbx.ops.enqueue_tx) { err = vf_info->mbx.ops.enqueue_tx(hw, &vf_info->mbx, msg); if (err != FM10K_MBX_ERR_NO_MBX) return err; err = 0; } /* If we aren't connected to a mailbox, this is most likely because * the VF driver is not running. It should thus be safe to re-map * queues and use the registers to pass the MAC address so that the VF * driver gets correct information during its initialization. */ /* MAP Tx queue back to 0 temporarily, and disable it */ fm10k_write_reg(hw, FM10K_TQMAP(qmap_idx), 0); fm10k_write_reg(hw, FM10K_TXDCTL(vf_q_idx), 0); /* verify ring has disabled before modifying base address registers */ txdctl = fm10k_read_reg(hw, FM10K_TXDCTL(vf_q_idx)); for (timeout = 0; txdctl & FM10K_TXDCTL_ENABLE; timeout++) { /* limit ourselves to a 1ms timeout */ if (timeout == 10) { err = FM10K_ERR_DMA_PENDING; goto err_out; } usleep_range(100, 200); txdctl = fm10k_read_reg(hw, FM10K_TXDCTL(vf_q_idx)); } /* Update base address registers to contain MAC address */ if (is_valid_ether_addr(vf_info->mac)) { tdbal = (((u32)vf_info->mac[3]) << 24) | (((u32)vf_info->mac[4]) << 16) | (((u32)vf_info->mac[5]) << 8); tdbah = (((u32)0xFF) << 24) | (((u32)vf_info->mac[0]) << 16) | (((u32)vf_info->mac[1]) << 8) | ((u32)vf_info->mac[2]); } /* Record the base address into queue 0 */ fm10k_write_reg(hw, FM10K_TDBAL(vf_q_idx), tdbal); fm10k_write_reg(hw, FM10K_TDBAH(vf_q_idx), tdbah); /* Provide the VF the ITR scale, using software-defined fields in TDLEN * to pass the information during VF initialization. See definition of * FM10K_TDLEN_ITR_SCALE_SHIFT for more details. */ fm10k_write_reg(hw, FM10K_TDLEN(vf_q_idx), hw->mac.itr_scale << FM10K_TDLEN_ITR_SCALE_SHIFT); err_out: /* restore the queue back to VF ownership */ fm10k_write_reg(hw, FM10K_TQMAP(qmap_idx), vf_q_idx); return err; } /** * fm10k_iov_reset_resources_pf - Reassign queues and interrupts to a VF * @hw: pointer to the HW structure * @vf_info: pointer to VF information structure * * Reassign the interrupts and queues to a VF following an FLR **/ static s32 fm10k_iov_reset_resources_pf(struct fm10k_hw *hw, struct fm10k_vf_info *vf_info) { u16 qmap_stride, queues_per_pool, vf_q_idx, qmap_idx; u32 tdbal = 0, tdbah = 0, txqctl, rxqctl; u16 vf_v_idx, vf_v_limit, vf_vid; u8 vf_idx = vf_info->vf_idx; int i; /* verify vf is in range */ if (vf_idx >= hw->iov.num_vfs) return FM10K_ERR_PARAM; /* clear event notification of VF FLR */ fm10k_write_reg(hw, FM10K_PFVFLREC(vf_idx / 32), BIT(vf_idx % 32)); /* force timeout and then disconnect the mailbox */ vf_info->mbx.timeout = 0; if (vf_info->mbx.ops.disconnect) vf_info->mbx.ops.disconnect(hw, &vf_info->mbx); /* determine vector offset and count */ vf_v_idx = fm10k_vf_vector_index(hw, vf_idx); vf_v_limit = vf_v_idx + fm10k_vectors_per_pool(hw); /* determine qmap offsets and counts */ qmap_stride = (hw->iov.num_vfs > 8) ? 32 : 256; queues_per_pool = fm10k_queues_per_pool(hw); qmap_idx = qmap_stride * vf_idx; /* make all the queues inaccessible to the VF */ for (i = qmap_idx; i < (qmap_idx + qmap_stride); i++) { fm10k_write_reg(hw, FM10K_TQMAP(i), 0); fm10k_write_reg(hw, FM10K_RQMAP(i), 0); } /* calculate starting index for queues */ vf_q_idx = fm10k_vf_queue_index(hw, vf_idx); /* determine correct default VLAN ID */ if (vf_info->pf_vid) vf_vid = vf_info->pf_vid; else vf_vid = vf_info->sw_vid; /* configure Queue control register */ txqctl = ((u32)vf_vid << FM10K_TXQCTL_VID_SHIFT) | (vf_idx << FM10K_TXQCTL_TC_SHIFT) | FM10K_TXQCTL_VF | vf_idx; rxqctl = (vf_idx << FM10K_RXQCTL_VF_SHIFT) | FM10K_RXQCTL_VF; /* stop further DMA and reset queue ownership back to VF */ for (i = vf_q_idx; i < (queues_per_pool + vf_q_idx); i++) { fm10k_write_reg(hw, FM10K_TXDCTL(i), 0); fm10k_write_reg(hw, FM10K_TXQCTL(i), txqctl); fm10k_write_reg(hw, FM10K_RXDCTL(i), FM10K_RXDCTL_WRITE_BACK_MIN_DELAY | FM10K_RXDCTL_DROP_ON_EMPTY); fm10k_write_reg(hw, FM10K_RXQCTL(i), rxqctl); } /* reset TC with -1 credits and no quanta to prevent transmit */ fm10k_write_reg(hw, FM10K_TC_MAXCREDIT(vf_idx), 0); fm10k_write_reg(hw, FM10K_TC_RATE(vf_idx), 0); fm10k_write_reg(hw, FM10K_TC_CREDIT(vf_idx), FM10K_TC_CREDIT_CREDIT_MASK); /* update our first entry in the table based on previous VF */ if (!vf_idx) hw->mac.ops.update_int_moderator(hw); else hw->iov.ops.assign_int_moderator(hw, vf_idx - 1); /* reset linked list so it now includes our active vectors */ if (vf_idx == (hw->iov.num_vfs - 1)) fm10k_write_reg(hw, FM10K_ITR2(0), vf_v_idx); else fm10k_write_reg(hw, FM10K_ITR2(vf_v_limit), vf_v_idx); /* link remaining vectors so that next points to previous */ for (vf_v_idx++; vf_v_idx < vf_v_limit; vf_v_idx++) fm10k_write_reg(hw, FM10K_ITR2(vf_v_idx), vf_v_idx - 1); /* zero out MBMEM, VLAN_TABLE, RETA, RSSRK, and MRQC registers */ for (i = FM10K_VFMBMEM_LEN; i--;) fm10k_write_reg(hw, FM10K_MBMEM_VF(vf_idx, i), 0); for (i = FM10K_VLAN_TABLE_SIZE; i--;) fm10k_write_reg(hw, FM10K_VLAN_TABLE(vf_info->vsi, i), 0); for (i = FM10K_RETA_SIZE; i--;) fm10k_write_reg(hw, FM10K_RETA(vf_info->vsi, i), 0); for (i = FM10K_RSSRK_SIZE; i--;) fm10k_write_reg(hw, FM10K_RSSRK(vf_info->vsi, i), 0); fm10k_write_reg(hw, FM10K_MRQC(vf_info->vsi), 0); /* Update base address registers to contain MAC address */ if (is_valid_ether_addr(vf_info->mac)) { tdbal = (((u32)vf_info->mac[3]) << 24) | (((u32)vf_info->mac[4]) << 16) | (((u32)vf_info->mac[5]) << 8); tdbah = (((u32)0xFF) << 24) | (((u32)vf_info->mac[0]) << 16) | (((u32)vf_info->mac[1]) << 8) | ((u32)vf_info->mac[2]); } /* map queue pairs back to VF from last to first */ for (i = queues_per_pool; i--;) { fm10k_write_reg(hw, FM10K_TDBAL(vf_q_idx + i), tdbal); fm10k_write_reg(hw, FM10K_TDBAH(vf_q_idx + i), tdbah); /* See definition of FM10K_TDLEN_ITR_SCALE_SHIFT for an * explanation of how TDLEN is used. */ fm10k_write_reg(hw, FM10K_TDLEN(vf_q_idx + i), hw->mac.itr_scale << FM10K_TDLEN_ITR_SCALE_SHIFT); fm10k_write_reg(hw, FM10K_TQMAP(qmap_idx + i), vf_q_idx + i); fm10k_write_reg(hw, FM10K_RQMAP(qmap_idx + i), vf_q_idx + i); } /* repeat the first ring for all the remaining VF rings */ for (i = queues_per_pool; i < qmap_stride; i++) { fm10k_write_reg(hw, FM10K_TQMAP(qmap_idx + i), vf_q_idx); fm10k_write_reg(hw, FM10K_RQMAP(qmap_idx + i), vf_q_idx); } return 0; } /** * fm10k_iov_set_lport_pf - Assign and enable a logical port for a given VF * @hw: pointer to hardware structure * @vf_info: pointer to VF information structure * @lport_idx: Logical port offset from the hardware glort * @flags: Set of capability flags to extend port beyond basic functionality * * This function allows enabling a VF port by assigning it a GLORT and * setting the flags so that it can enable an Rx mode. **/ static s32 fm10k_iov_set_lport_pf(struct fm10k_hw *hw, struct fm10k_vf_info *vf_info, u16 lport_idx, u8 flags) { u16 glort = (hw->mac.dglort_map + lport_idx) & FM10K_DGLORTMAP_NONE; /* if glort is not valid return error */ if (!fm10k_glort_valid_pf(hw, glort)) return FM10K_ERR_PARAM; vf_info->vf_flags = flags | FM10K_VF_FLAG_NONE_CAPABLE; vf_info->glort = glort; return 0; } /** * fm10k_iov_reset_lport_pf - Disable a logical port for a given VF * @hw: pointer to hardware structure * @vf_info: pointer to VF information structure * * This function disables a VF port by stripping it of a GLORT and * setting the flags so that it cannot enable any Rx mode. **/ static void fm10k_iov_reset_lport_pf(struct fm10k_hw *hw, struct fm10k_vf_info *vf_info) { u32 msg[1]; /* need to disable the port if it is already enabled */ if (FM10K_VF_FLAG_ENABLED(vf_info)) { /* notify switch that this port has been disabled */ fm10k_update_lport_state_pf(hw, vf_info->glort, 1, false); /* generate port state response to notify VF it is not ready */ fm10k_tlv_msg_init(msg, FM10K_VF_MSG_ID_LPORT_STATE); vf_info->mbx.ops.enqueue_tx(hw, &vf_info->mbx, msg); } /* clear flags and glort if it exists */ vf_info->vf_flags = 0; vf_info->glort = 0; } /** * fm10k_iov_update_stats_pf - Updates hardware related statistics for VFs * @hw: pointer to hardware structure * @q: stats for all queues of a VF * @vf_idx: index of VF * * This function collects queue stats for VFs. **/ static void fm10k_iov_update_stats_pf(struct fm10k_hw *hw, struct fm10k_hw_stats_q *q, u16 vf_idx) { u32 idx, qpp; /* get stats for all of the queues */ qpp = fm10k_queues_per_pool(hw); idx = fm10k_vf_queue_index(hw, vf_idx); fm10k_update_hw_stats_q(hw, q, idx, qpp); } /** * fm10k_iov_msg_msix_pf - Message handler for MSI-X request from VF * @hw: Pointer to hardware structure * @results: Pointer array to message, results[0] is pointer to message * @mbx: Pointer to mailbox information structure * * This function is a default handler for MSI-X requests from the VF. The * assumption is that in this case it is acceptable to just directly * hand off the message from the VF to the underlying shared code. **/ s32 fm10k_iov_msg_msix_pf(struct fm10k_hw *hw, u32 __always_unused **results, struct fm10k_mbx_info *mbx) { struct fm10k_vf_info *vf_info = (struct fm10k_vf_info *)mbx; u8 vf_idx = vf_info->vf_idx; return hw->iov.ops.assign_int_moderator(hw, vf_idx); } /** * fm10k_iov_select_vid - Select correct default VLAN ID * @vf_info: pointer to VF information structure * @vid: VLAN ID to correct * * Will report an error if the VLAN ID is out of range. For VID = 0, it will * return either the pf_vid or sw_vid depending on which one is set. */ s32 fm10k_iov_select_vid(struct fm10k_vf_info *vf_info, u16 vid) { if (!vid) return vf_info->pf_vid ? vf_info->pf_vid : vf_info->sw_vid; else if (vf_info->pf_vid && vid != vf_info->pf_vid) return FM10K_ERR_PARAM; else return vid; } /** * fm10k_iov_msg_mac_vlan_pf - Message handler for MAC/VLAN request from VF * @hw: Pointer to hardware structure * @results: Pointer array to message, results[0] is pointer to message * @mbx: Pointer to mailbox information structure * * This function is a default handler for MAC/VLAN requests from the VF. * The assumption is that in this case it is acceptable to just directly * hand off the message from the VF to the underlying shared code. **/ s32 fm10k_iov_msg_mac_vlan_pf(struct fm10k_hw *hw, u32 **results, struct fm10k_mbx_info *mbx) { struct fm10k_vf_info *vf_info = (struct fm10k_vf_info *)mbx; u8 mac[ETH_ALEN]; u32 *result; int err = 0; bool set; u16 vlan; u32 vid; /* we shouldn't be updating rules on a disabled interface */ if (!FM10K_VF_FLAG_ENABLED(vf_info)) err = FM10K_ERR_PARAM; if (!err && !!results[FM10K_MAC_VLAN_MSG_VLAN]) { result = results[FM10K_MAC_VLAN_MSG_VLAN]; /* record VLAN id requested */ err = fm10k_tlv_attr_get_u32(result, &vid); if (err) return err; set = !(vid & FM10K_VLAN_CLEAR); vid &= ~FM10K_VLAN_CLEAR; /* if the length field has been set, this is a multi-bit * update request. For multi-bit requests, simply disallow * them when the pf_vid has been set. In this case, the PF * should have already cleared the VLAN_TABLE, and if we * allowed them, it could allow a rogue VF to receive traffic * on a VLAN it was not assigned. In the single-bit case, we * need to modify requests for VLAN 0 to use the default PF or * SW vid when assigned. */ if (vid >> 16) { /* prevent multi-bit requests when PF has * administratively set the VLAN for this VF */ if (vf_info->pf_vid) return FM10K_ERR_PARAM; } else { err = fm10k_iov_select_vid(vf_info, (u16)vid); if (err < 0) return err; vid = err; } /* update VSI info for VF in regards to VLAN table */ err = hw->mac.ops.update_vlan(hw, vid, vf_info->vsi, set); } if (!err && !!results[FM10K_MAC_VLAN_MSG_MAC]) { result = results[FM10K_MAC_VLAN_MSG_MAC]; /* record unicast MAC address requested */ err = fm10k_tlv_attr_get_mac_vlan(result, mac, &vlan); if (err) return err; /* block attempts to set MAC for a locked device */ if (is_valid_ether_addr(vf_info->mac) && !ether_addr_equal(mac, vf_info->mac)) return FM10K_ERR_PARAM; set = !(vlan & FM10K_VLAN_CLEAR); vlan &= ~FM10K_VLAN_CLEAR; err = fm10k_iov_select_vid(vf_info, vlan); if (err < 0) return err; vlan = (u16)err; /* notify switch of request for new unicast address */ err = hw->mac.ops.update_uc_addr(hw, vf_info->glort, mac, vlan, set, 0); } if (!err && !!results[FM10K_MAC_VLAN_MSG_MULTICAST]) { result = results[FM10K_MAC_VLAN_MSG_MULTICAST]; /* record multicast MAC address requested */ err = fm10k_tlv_attr_get_mac_vlan(result, mac, &vlan); if (err) return err; /* verify that the VF is allowed to request multicast */ if (!(vf_info->vf_flags & FM10K_VF_FLAG_MULTI_ENABLED)) return FM10K_ERR_PARAM; set = !(vlan & FM10K_VLAN_CLEAR); vlan &= ~FM10K_VLAN_CLEAR; err = fm10k_iov_select_vid(vf_info, vlan); if (err < 0) return err; vlan = (u16)err; /* notify switch of request for new multicast address */ err = hw->mac.ops.update_mc_addr(hw, vf_info->glort, mac, vlan, set); } return err; } /** * fm10k_iov_supported_xcast_mode_pf - Determine best match for xcast mode * @vf_info: VF info structure containing capability flags * @mode: Requested xcast mode * * This function outputs the mode that most closely matches the requested * mode. If not modes match it will request we disable the port **/ static u8 fm10k_iov_supported_xcast_mode_pf(struct fm10k_vf_info *vf_info, u8 mode) { u8 vf_flags = vf_info->vf_flags; /* match up mode to capabilities as best as possible */ switch (mode) { case FM10K_XCAST_MODE_PROMISC: if (vf_flags & FM10K_VF_FLAG_PROMISC_CAPABLE) return FM10K_XCAST_MODE_PROMISC; fallthrough; case FM10K_XCAST_MODE_ALLMULTI: if (vf_flags & FM10K_VF_FLAG_ALLMULTI_CAPABLE) return FM10K_XCAST_MODE_ALLMULTI; fallthrough; case FM10K_XCAST_MODE_MULTI: if (vf_flags & FM10K_VF_FLAG_MULTI_CAPABLE) return FM10K_XCAST_MODE_MULTI; fallthrough; case FM10K_XCAST_MODE_NONE: if (vf_flags & FM10K_VF_FLAG_NONE_CAPABLE) return FM10K_XCAST_MODE_NONE; fallthrough; default: break; } /* disable interface as it should not be able to request any */ return FM10K_XCAST_MODE_DISABLE; } /** * fm10k_iov_msg_lport_state_pf - Message handler for port state requests * @hw: Pointer to hardware structure * @results: Pointer array to message, results[0] is pointer to message * @mbx: Pointer to mailbox information structure * * This function is a default handler for port state requests. The port * state requests for now are basic and consist of enabling or disabling * the port. **/ s32 fm10k_iov_msg_lport_state_pf(struct fm10k_hw *hw, u32 **results, struct fm10k_mbx_info *mbx) { struct fm10k_vf_info *vf_info = (struct fm10k_vf_info *)mbx; s32 err = 0; u32 msg[2]; u8 mode = 0; /* verify VF is allowed to enable even minimal mode */ if (!(vf_info->vf_flags & FM10K_VF_FLAG_NONE_CAPABLE)) return FM10K_ERR_PARAM; if (!!results[FM10K_LPORT_STATE_MSG_XCAST_MODE]) { u32 *result = results[FM10K_LPORT_STATE_MSG_XCAST_MODE]; /* XCAST mode update requested */ err = fm10k_tlv_attr_get_u8(result, &mode); if (err) return FM10K_ERR_PARAM; /* prep for possible demotion depending on capabilities */ mode = fm10k_iov_supported_xcast_mode_pf(vf_info, mode); /* if mode is not currently enabled, enable it */ if (!(FM10K_VF_FLAG_ENABLED(vf_info) & BIT(mode))) fm10k_update_xcast_mode_pf(hw, vf_info->glort, mode); /* swap mode back to a bit flag */ mode = FM10K_VF_FLAG_SET_MODE(mode); } else if (!results[FM10K_LPORT_STATE_MSG_DISABLE]) { /* need to disable the port if it is already enabled */ if (FM10K_VF_FLAG_ENABLED(vf_info)) err = fm10k_update_lport_state_pf(hw, vf_info->glort, 1, false); /* we need to clear VF_FLAG_ENABLED flags in order to ensure * that we actually re-enable the LPORT state below. Note that * this has no impact if the VF is already disabled, as the * flags are already cleared. */ if (!err) vf_info->vf_flags = FM10K_VF_FLAG_CAPABLE(vf_info); /* when enabling the port we should reset the rate limiters */ hw->iov.ops.configure_tc(hw, vf_info->vf_idx, vf_info->rate); /* set mode for minimal functionality */ mode = FM10K_VF_FLAG_SET_MODE_NONE; /* generate port state response to notify VF it is ready */ fm10k_tlv_msg_init(msg, FM10K_VF_MSG_ID_LPORT_STATE); fm10k_tlv_attr_put_bool(msg, FM10K_LPORT_STATE_MSG_READY); mbx->ops.enqueue_tx(hw, mbx, msg); } /* if enable state toggled note the update */ if (!err && (!FM10K_VF_FLAG_ENABLED(vf_info) != !mode)) err = fm10k_update_lport_state_pf(hw, vf_info->glort, 1, !!mode); /* if state change succeeded, then update our stored state */ mode |= FM10K_VF_FLAG_CAPABLE(vf_info); if (!err) vf_info->vf_flags = mode; return err; } /** * fm10k_update_hw_stats_pf - Updates hardware related statistics of PF * @hw: pointer to hardware structure * @stats: pointer to the stats structure to update * * This function collects and aggregates global and per queue hardware * statistics. **/ static void fm10k_update_hw_stats_pf(struct fm10k_hw *hw, struct fm10k_hw_stats *stats) { u32 timeout, ur, ca, um, xec, vlan_drop, loopback_drop, nodesc_drop; u32 id, id_prev; /* Use Tx queue 0 as a canary to detect a reset */ id = fm10k_read_reg(hw, FM10K_TXQCTL(0)); /* Read Global Statistics */ do { timeout = fm10k_read_hw_stats_32b(hw, FM10K_STATS_TIMEOUT, &stats->timeout); ur = fm10k_read_hw_stats_32b(hw, FM10K_STATS_UR, &stats->ur); ca = fm10k_read_hw_stats_32b(hw, FM10K_STATS_CA, &stats->ca); um = fm10k_read_hw_stats_32b(hw, FM10K_STATS_UM, &stats->um); xec = fm10k_read_hw_stats_32b(hw, FM10K_STATS_XEC, &stats->xec); vlan_drop = fm10k_read_hw_stats_32b(hw, FM10K_STATS_VLAN_DROP, &stats->vlan_drop); loopback_drop = fm10k_read_hw_stats_32b(hw, FM10K_STATS_LOOPBACK_DROP, &stats->loopback_drop); nodesc_drop = fm10k_read_hw_stats_32b(hw, FM10K_STATS_NODESC_DROP, &stats->nodesc_drop); /* if value has not changed then we have consistent data */ id_prev = id; id = fm10k_read_reg(hw, FM10K_TXQCTL(0)); } while ((id ^ id_prev) & FM10K_TXQCTL_ID_MASK); /* drop non-ID bits and set VALID ID bit */ id &= FM10K_TXQCTL_ID_MASK; id |= FM10K_STAT_VALID; /* Update Global Statistics */ if (stats->stats_idx == id) { stats->timeout.count += timeout; stats->ur.count += ur; stats->ca.count += ca; stats->um.count += um; stats->xec.count += xec; stats->vlan_drop.count += vlan_drop; stats->loopback_drop.count += loopback_drop; stats->nodesc_drop.count += nodesc_drop; } /* Update bases and record current PF id */ fm10k_update_hw_base_32b(&stats->timeout, timeout); fm10k_update_hw_base_32b(&stats->ur, ur); fm10k_update_hw_base_32b(&stats->ca, ca); fm10k_update_hw_base_32b(&stats->um, um); fm10k_update_hw_base_32b(&stats->xec, xec); fm10k_update_hw_base_32b(&stats->vlan_drop, vlan_drop); fm10k_update_hw_base_32b(&stats->loopback_drop, loopback_drop); fm10k_update_hw_base_32b(&stats->nodesc_drop, nodesc_drop); stats->stats_idx = id; /* Update Queue Statistics */ fm10k_update_hw_stats_q(hw, stats->q, 0, hw->mac.max_queues); } /** * fm10k_rebind_hw_stats_pf - Resets base for hardware statistics of PF * @hw: pointer to hardware structure * @stats: pointer to the stats structure to update * * This function resets the base for global and per queue hardware * statistics. **/ static void fm10k_rebind_hw_stats_pf(struct fm10k_hw *hw, struct fm10k_hw_stats *stats) { /* Unbind Global Statistics */ fm10k_unbind_hw_stats_32b(&stats->timeout); fm10k_unbind_hw_stats_32b(&stats->ur); fm10k_unbind_hw_stats_32b(&stats->ca); fm10k_unbind_hw_stats_32b(&stats->um); fm10k_unbind_hw_stats_32b(&stats->xec); fm10k_unbind_hw_stats_32b(&stats->vlan_drop); fm10k_unbind_hw_stats_32b(&stats->loopback_drop); fm10k_unbind_hw_stats_32b(&stats->nodesc_drop); /* Unbind Queue Statistics */ fm10k_unbind_hw_stats_q(stats->q, 0, hw->mac.max_queues); /* Reinitialize bases for all stats */ fm10k_update_hw_stats_pf(hw, stats); } /** * fm10k_set_dma_mask_pf - Configures PhyAddrSpace to limit DMA to system * @hw: pointer to hardware structure * @dma_mask: 64 bit DMA mask required for platform * * This function sets the PHYADDR.PhyAddrSpace bits for the endpoint in order * to limit the access to memory beyond what is physically in the system. **/ static void fm10k_set_dma_mask_pf(struct fm10k_hw *hw, u64 dma_mask) { /* we need to write the upper 32 bits of DMA mask to PhyAddrSpace */ u32 phyaddr = (u32)(dma_mask >> 32); fm10k_write_reg(hw, FM10K_PHYADDR, phyaddr); } /** * fm10k_get_fault_pf - Record a fault in one of the interface units * @hw: pointer to hardware structure * @type: pointer to fault type register offset * @fault: pointer to memory location to record the fault * * Record the fault register contents to the fault data structure and * clear the entry from the register. * * Returns ERR_PARAM if invalid register is specified or no error is present. **/ static s32 fm10k_get_fault_pf(struct fm10k_hw *hw, int type, struct fm10k_fault *fault) { u32 func; /* verify the fault register is in range and is aligned */ switch (type) { case FM10K_PCA_FAULT: case FM10K_THI_FAULT: case FM10K_FUM_FAULT: break; default: return FM10K_ERR_PARAM; } /* only service faults that are valid */ func = fm10k_read_reg(hw, type + FM10K_FAULT_FUNC); if (!(func & FM10K_FAULT_FUNC_VALID)) return FM10K_ERR_PARAM; /* read remaining fields */ fault->address = fm10k_read_reg(hw, type + FM10K_FAULT_ADDR_HI); fault->address <<= 32; fault->address |= fm10k_read_reg(hw, type + FM10K_FAULT_ADDR_LO); fault->specinfo = fm10k_read_reg(hw, type + FM10K_FAULT_SPECINFO); /* clear valid bit to allow for next error */ fm10k_write_reg(hw, type + FM10K_FAULT_FUNC, FM10K_FAULT_FUNC_VALID); /* Record which function triggered the error */ if (func & FM10K_FAULT_FUNC_PF) fault->func = 0; else fault->func = 1 + ((func & FM10K_FAULT_FUNC_VF_MASK) >> FM10K_FAULT_FUNC_VF_SHIFT); /* record fault type */ fault->type = func & FM10K_FAULT_FUNC_TYPE_MASK; return 0; } /** * fm10k_request_lport_map_pf - Request LPORT map from the switch API * @hw: pointer to hardware structure * **/ static s32 fm10k_request_lport_map_pf(struct fm10k_hw *hw) { struct fm10k_mbx_info *mbx = &hw->mbx; u32 msg[1]; /* issue request asking for LPORT map */ fm10k_tlv_msg_init(msg, FM10K_PF_MSG_ID_LPORT_MAP); /* load onto outgoing mailbox */ return mbx->ops.enqueue_tx(hw, mbx, msg); } /** * fm10k_get_host_state_pf - Returns the state of the switch and mailbox * @hw: pointer to hardware structure * @switch_ready: pointer to boolean value that will record switch state * * This function will check the DMA_CTRL2 register and mailbox in order * to determine if the switch is ready for the PF to begin requesting * addresses and mapping traffic to the local interface. **/ static s32 fm10k_get_host_state_pf(struct fm10k_hw *hw, bool *switch_ready) { u32 dma_ctrl2; /* verify the switch is ready for interaction */ dma_ctrl2 = fm10k_read_reg(hw, FM10K_DMA_CTRL2); if (!(dma_ctrl2 & FM10K_DMA_CTRL2_SWITCH_READY)) return 0; /* retrieve generic host state info */ return fm10k_get_host_state_generic(hw, switch_ready); } /* This structure defines the attibutes to be parsed below */ const struct fm10k_tlv_attr fm10k_lport_map_msg_attr[] = { FM10K_TLV_ATTR_LE_STRUCT(FM10K_PF_ATTR_ID_ERR, sizeof(struct fm10k_swapi_error)), FM10K_TLV_ATTR_U32(FM10K_PF_ATTR_ID_LPORT_MAP), FM10K_TLV_ATTR_LAST }; /** * fm10k_msg_lport_map_pf - Message handler for lport_map message from SM * @hw: Pointer to hardware structure * @results: pointer array containing parsed data * @mbx: Pointer to mailbox information structure * * This handler configures the lport mapping based on the reply from the * switch API. **/ s32 fm10k_msg_lport_map_pf(struct fm10k_hw *hw, u32 **results, struct fm10k_mbx_info __always_unused *mbx) { u16 glort, mask; u32 dglort_map; s32 err; err = fm10k_tlv_attr_get_u32(results[FM10K_PF_ATTR_ID_LPORT_MAP], &dglort_map); if (err) return err; /* extract values out of the header */ glort = FM10K_MSG_HDR_FIELD_GET(dglort_map, LPORT_MAP_GLORT); mask = FM10K_MSG_HDR_FIELD_GET(dglort_map, LPORT_MAP_MASK); /* verify mask is set and none of the masked bits in glort are set */ if (!mask || (glort & ~mask)) return FM10K_ERR_PARAM; /* verify the mask is contiguous, and that it is 1's followed by 0's */ if (((~(mask - 1) & mask) + mask) & FM10K_DGLORTMAP_NONE) return FM10K_ERR_PARAM; /* record the glort, mask, and port count */ hw->mac.dglort_map = dglort_map; return 0; } const struct fm10k_tlv_attr fm10k_update_pvid_msg_attr[] = { FM10K_TLV_ATTR_U32(FM10K_PF_ATTR_ID_UPDATE_PVID), FM10K_TLV_ATTR_LAST }; /** * fm10k_msg_update_pvid_pf - Message handler for port VLAN message from SM * @hw: Pointer to hardware structure * @results: pointer array containing parsed data * @mbx: Pointer to mailbox information structure * * This handler configures the default VLAN for the PF **/ static s32 fm10k_msg_update_pvid_pf(struct fm10k_hw *hw, u32 **results, struct fm10k_mbx_info __always_unused *mbx) { u16 glort, pvid; u32 pvid_update; s32 err; err = fm10k_tlv_attr_get_u32(results[FM10K_PF_ATTR_ID_UPDATE_PVID], &pvid_update); if (err) return err; /* extract values from the pvid update */ glort = FM10K_MSG_HDR_FIELD_GET(pvid_update, UPDATE_PVID_GLORT); pvid = FM10K_MSG_HDR_FIELD_GET(pvid_update, UPDATE_PVID_PVID); /* if glort is not valid return error */ if (!fm10k_glort_valid_pf(hw, glort)) return FM10K_ERR_PARAM; /* verify VLAN ID is valid */ if (pvid >= FM10K_VLAN_TABLE_VID_MAX) return FM10K_ERR_PARAM; /* record the port VLAN ID value */ hw->mac.default_vid = pvid; return 0; } /** * fm10k_record_global_table_data - Move global table data to swapi table info * @from: pointer to source table data structure * @to: pointer to destination table info structure * * This function is will copy table_data to the table_info contained in * the hw struct. **/ static void fm10k_record_global_table_data(struct fm10k_global_table_data *from, struct fm10k_swapi_table_info *to) { /* convert from le32 struct to CPU byte ordered values */ to->used = le32_to_cpu(from->used); to->avail = le32_to_cpu(from->avail); } const struct fm10k_tlv_attr fm10k_err_msg_attr[] = { FM10K_TLV_ATTR_LE_STRUCT(FM10K_PF_ATTR_ID_ERR, sizeof(struct fm10k_swapi_error)), FM10K_TLV_ATTR_LAST }; /** * fm10k_msg_err_pf - Message handler for error reply * @hw: Pointer to hardware structure * @results: pointer array containing parsed data * @mbx: Pointer to mailbox information structure * * This handler will capture the data for any error replies to previous * messages that the PF has sent. **/ s32 fm10k_msg_err_pf(struct fm10k_hw *hw, u32 **results, struct fm10k_mbx_info __always_unused *mbx) { struct fm10k_swapi_error err_msg; s32 err; /* extract structure from message */ err = fm10k_tlv_attr_get_le_struct(results[FM10K_PF_ATTR_ID_ERR], &err_msg, sizeof(err_msg)); if (err) return err; /* record table status */ fm10k_record_global_table_data(&err_msg.mac, &hw->swapi.mac); fm10k_record_global_table_data(&err_msg.nexthop, &hw->swapi.nexthop); fm10k_record_global_table_data(&err_msg.ffu, &hw->swapi.ffu); /* record SW API status value */ hw->swapi.status = le32_to_cpu(err_msg.status); return 0; } static const struct fm10k_msg_data fm10k_msg_data_pf[] = { FM10K_PF_MSG_ERR_HANDLER(XCAST_MODES, fm10k_msg_err_pf), FM10K_PF_MSG_ERR_HANDLER(UPDATE_MAC_FWD_RULE, fm10k_msg_err_pf), FM10K_PF_MSG_LPORT_MAP_HANDLER(fm10k_msg_lport_map_pf), FM10K_PF_MSG_ERR_HANDLER(LPORT_CREATE, fm10k_msg_err_pf), FM10K_PF_MSG_ERR_HANDLER(LPORT_DELETE, fm10k_msg_err_pf), FM10K_PF_MSG_UPDATE_PVID_HANDLER(fm10k_msg_update_pvid_pf), FM10K_TLV_MSG_ERROR_HANDLER(fm10k_tlv_msg_error), }; static const struct fm10k_mac_ops mac_ops_pf = { .get_bus_info = fm10k_get_bus_info_generic, .reset_hw = fm10k_reset_hw_pf, .init_hw = fm10k_init_hw_pf, .start_hw = fm10k_start_hw_generic, .stop_hw = fm10k_stop_hw_generic, .update_vlan = fm10k_update_vlan_pf, .read_mac_addr = fm10k_read_mac_addr_pf, .update_uc_addr = fm10k_update_uc_addr_pf, .update_mc_addr = fm10k_update_mc_addr_pf, .update_xcast_mode = fm10k_update_xcast_mode_pf, .update_int_moderator = fm10k_update_int_moderator_pf, .update_lport_state = fm10k_update_lport_state_pf, .update_hw_stats = fm10k_update_hw_stats_pf, .rebind_hw_stats = fm10k_rebind_hw_stats_pf, .configure_dglort_map = fm10k_configure_dglort_map_pf, .set_dma_mask = fm10k_set_dma_mask_pf, .get_fault = fm10k_get_fault_pf, .get_host_state = fm10k_get_host_state_pf, .request_lport_map = fm10k_request_lport_map_pf, }; static const struct fm10k_iov_ops iov_ops_pf = { .assign_resources = fm10k_iov_assign_resources_pf, .configure_tc = fm10k_iov_configure_tc_pf, .assign_int_moderator = fm10k_iov_assign_int_moderator_pf, .assign_default_mac_vlan = fm10k_iov_assign_default_mac_vlan_pf, .reset_resources = fm10k_iov_reset_resources_pf, .set_lport = fm10k_iov_set_lport_pf, .reset_lport = fm10k_iov_reset_lport_pf, .update_stats = fm10k_iov_update_stats_pf, }; static s32 fm10k_get_invariants_pf(struct fm10k_hw *hw) { fm10k_get_invariants_generic(hw); return fm10k_sm_mbx_init(hw, &hw->mbx, fm10k_msg_data_pf); } const struct fm10k_info fm10k_pf_info = { .mac = fm10k_mac_pf, .get_invariants = fm10k_get_invariants_pf, .mac_ops = &mac_ops_pf, .iov_ops = &iov_ops_pf, };
linux-master
drivers/net/ethernet/intel/fm10k/fm10k_pf.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2013 - 2019 Intel Corporation. */ #include <linux/module.h> #include <linux/interrupt.h> #include "fm10k.h" static const struct fm10k_info *fm10k_info_tbl[] = { [fm10k_device_pf] = &fm10k_pf_info, [fm10k_device_vf] = &fm10k_vf_info, }; /* * fm10k_pci_tbl - PCI Device ID Table * * Wildcard entries (PCI_ANY_ID) should come last * Last entry must be all 0s * * { Vendor ID, Device ID, SubVendor ID, SubDevice ID, * Class, Class Mask, private data (not used) } */ static const struct pci_device_id fm10k_pci_tbl[] = { { PCI_VDEVICE(INTEL, FM10K_DEV_ID_PF), fm10k_device_pf }, { PCI_VDEVICE(INTEL, FM10K_DEV_ID_SDI_FM10420_QDA2), fm10k_device_pf }, { PCI_VDEVICE(INTEL, FM10K_DEV_ID_SDI_FM10420_DA2), fm10k_device_pf }, { PCI_VDEVICE(INTEL, FM10K_DEV_ID_VF), fm10k_device_vf }, /* required last entry */ { 0, } }; MODULE_DEVICE_TABLE(pci, fm10k_pci_tbl); u16 fm10k_read_pci_cfg_word(struct fm10k_hw *hw, u32 reg) { struct fm10k_intfc *interface = hw->back; u16 value = 0; if (FM10K_REMOVED(hw->hw_addr)) return ~value; pci_read_config_word(interface->pdev, reg, &value); if (value == 0xFFFF) fm10k_write_flush(hw); return value; } u32 fm10k_read_reg(struct fm10k_hw *hw, int reg) { u32 __iomem *hw_addr = READ_ONCE(hw->hw_addr); u32 value = 0; if (FM10K_REMOVED(hw_addr)) return ~value; value = readl(&hw_addr[reg]); if (!(~value) && (!reg || !(~readl(hw_addr)))) { struct fm10k_intfc *interface = hw->back; struct net_device *netdev = interface->netdev; hw->hw_addr = NULL; netif_device_detach(netdev); netdev_err(netdev, "PCIe link lost, device now detached\n"); } return value; } static int fm10k_hw_ready(struct fm10k_intfc *interface) { struct fm10k_hw *hw = &interface->hw; fm10k_write_flush(hw); return FM10K_REMOVED(hw->hw_addr) ? -ENODEV : 0; } /** * fm10k_macvlan_schedule - Schedule MAC/VLAN queue task * @interface: fm10k private interface structure * * Schedule the MAC/VLAN queue monitor task. If the MAC/VLAN task cannot be * started immediately, request that it be restarted when possible. */ void fm10k_macvlan_schedule(struct fm10k_intfc *interface) { /* Avoid processing the MAC/VLAN queue when the service task is * disabled, or when we're resetting the device. */ if (!test_bit(__FM10K_MACVLAN_DISABLE, interface->state) && !test_and_set_bit(__FM10K_MACVLAN_SCHED, interface->state)) { clear_bit(__FM10K_MACVLAN_REQUEST, interface->state); /* We delay the actual start of execution in order to allow * multiple MAC/VLAN updates to accumulate before handling * them, and to allow some time to let the mailbox drain * between runs. */ queue_delayed_work(fm10k_workqueue, &interface->macvlan_task, 10); } else { set_bit(__FM10K_MACVLAN_REQUEST, interface->state); } } /** * fm10k_stop_macvlan_task - Stop the MAC/VLAN queue monitor * @interface: fm10k private interface structure * * Wait until the MAC/VLAN queue task has stopped, and cancel any future * requests. */ static void fm10k_stop_macvlan_task(struct fm10k_intfc *interface) { /* Disable the MAC/VLAN work item */ set_bit(__FM10K_MACVLAN_DISABLE, interface->state); /* Make sure we waited until any current invocations have stopped */ cancel_delayed_work_sync(&interface->macvlan_task); /* We set the __FM10K_MACVLAN_SCHED bit when we schedule the task. * However, it may not be unset of the MAC/VLAN task never actually * got a chance to run. Since we've canceled the task here, and it * cannot be rescheuled right now, we need to ensure the scheduled bit * gets unset. */ clear_bit(__FM10K_MACVLAN_SCHED, interface->state); } /** * fm10k_resume_macvlan_task - Restart the MAC/VLAN queue monitor * @interface: fm10k private interface structure * * Clear the __FM10K_MACVLAN_DISABLE bit and, if a request occurred, schedule * the MAC/VLAN work monitor. */ static void fm10k_resume_macvlan_task(struct fm10k_intfc *interface) { /* Re-enable the MAC/VLAN work item */ clear_bit(__FM10K_MACVLAN_DISABLE, interface->state); /* We might have received a MAC/VLAN request while disabled. If so, * kick off the queue now. */ if (test_bit(__FM10K_MACVLAN_REQUEST, interface->state)) fm10k_macvlan_schedule(interface); } void fm10k_service_event_schedule(struct fm10k_intfc *interface) { if (!test_bit(__FM10K_SERVICE_DISABLE, interface->state) && !test_and_set_bit(__FM10K_SERVICE_SCHED, interface->state)) { clear_bit(__FM10K_SERVICE_REQUEST, interface->state); queue_work(fm10k_workqueue, &interface->service_task); } else { set_bit(__FM10K_SERVICE_REQUEST, interface->state); } } static void fm10k_service_event_complete(struct fm10k_intfc *interface) { WARN_ON(!test_bit(__FM10K_SERVICE_SCHED, interface->state)); /* flush memory to make sure state is correct before next watchog */ smp_mb__before_atomic(); clear_bit(__FM10K_SERVICE_SCHED, interface->state); /* If a service event was requested since we started, immediately * re-schedule now. This ensures we don't drop a request until the * next timer event. */ if (test_bit(__FM10K_SERVICE_REQUEST, interface->state)) fm10k_service_event_schedule(interface); } static void fm10k_stop_service_event(struct fm10k_intfc *interface) { set_bit(__FM10K_SERVICE_DISABLE, interface->state); cancel_work_sync(&interface->service_task); /* It's possible that cancel_work_sync stopped the service task from * running before it could actually start. In this case the * __FM10K_SERVICE_SCHED bit will never be cleared. Since we know that * the service task cannot be running at this point, we need to clear * the scheduled bit, as otherwise the service task may never be * restarted. */ clear_bit(__FM10K_SERVICE_SCHED, interface->state); } static void fm10k_start_service_event(struct fm10k_intfc *interface) { clear_bit(__FM10K_SERVICE_DISABLE, interface->state); fm10k_service_event_schedule(interface); } /** * fm10k_service_timer - Timer Call-back * @t: pointer to timer data **/ static void fm10k_service_timer(struct timer_list *t) { struct fm10k_intfc *interface = from_timer(interface, t, service_timer); /* Reset the timer */ mod_timer(&interface->service_timer, (HZ * 2) + jiffies); fm10k_service_event_schedule(interface); } /** * fm10k_prepare_for_reset - Prepare the driver and device for a pending reset * @interface: fm10k private data structure * * This function prepares for a device reset by shutting as much down as we * can. It does nothing and returns false if __FM10K_RESETTING was already set * prior to calling this function. It returns true if it actually did work. */ static bool fm10k_prepare_for_reset(struct fm10k_intfc *interface) { struct net_device *netdev = interface->netdev; /* put off any impending NetWatchDogTimeout */ netif_trans_update(netdev); /* Nothing to do if a reset is already in progress */ if (test_and_set_bit(__FM10K_RESETTING, interface->state)) return false; /* As the MAC/VLAN task will be accessing registers it must not be * running while we reset. Although the task will not be scheduled * once we start resetting it may already be running */ fm10k_stop_macvlan_task(interface); rtnl_lock(); fm10k_iov_suspend(interface->pdev); if (netif_running(netdev)) fm10k_close(netdev); fm10k_mbx_free_irq(interface); /* free interrupts */ fm10k_clear_queueing_scheme(interface); /* delay any future reset requests */ interface->last_reset = jiffies + (10 * HZ); rtnl_unlock(); return true; } static int fm10k_handle_reset(struct fm10k_intfc *interface) { struct net_device *netdev = interface->netdev; struct fm10k_hw *hw = &interface->hw; int err; WARN_ON(!test_bit(__FM10K_RESETTING, interface->state)); rtnl_lock(); pci_set_master(interface->pdev); /* reset and initialize the hardware so it is in a known state */ err = hw->mac.ops.reset_hw(hw); if (err) { dev_err(&interface->pdev->dev, "reset_hw failed: %d\n", err); goto reinit_err; } err = hw->mac.ops.init_hw(hw); if (err) { dev_err(&interface->pdev->dev, "init_hw failed: %d\n", err); goto reinit_err; } err = fm10k_init_queueing_scheme(interface); if (err) { dev_err(&interface->pdev->dev, "init_queueing_scheme failed: %d\n", err); goto reinit_err; } /* re-associate interrupts */ err = fm10k_mbx_request_irq(interface); if (err) goto err_mbx_irq; err = fm10k_hw_ready(interface); if (err) goto err_open; /* update hardware address for VFs if perm_addr has changed */ if (hw->mac.type == fm10k_mac_vf) { if (is_valid_ether_addr(hw->mac.perm_addr)) { ether_addr_copy(hw->mac.addr, hw->mac.perm_addr); ether_addr_copy(netdev->perm_addr, hw->mac.perm_addr); eth_hw_addr_set(netdev, hw->mac.perm_addr); netdev->addr_assign_type &= ~NET_ADDR_RANDOM; } if (hw->mac.vlan_override) netdev->features &= ~NETIF_F_HW_VLAN_CTAG_RX; else netdev->features |= NETIF_F_HW_VLAN_CTAG_RX; } err = netif_running(netdev) ? fm10k_open(netdev) : 0; if (err) goto err_open; fm10k_iov_resume(interface->pdev); rtnl_unlock(); fm10k_resume_macvlan_task(interface); clear_bit(__FM10K_RESETTING, interface->state); return err; err_open: fm10k_mbx_free_irq(interface); err_mbx_irq: fm10k_clear_queueing_scheme(interface); reinit_err: netif_device_detach(netdev); rtnl_unlock(); clear_bit(__FM10K_RESETTING, interface->state); return err; } static void fm10k_detach_subtask(struct fm10k_intfc *interface) { struct net_device *netdev = interface->netdev; u32 __iomem *hw_addr; u32 value; /* do nothing if netdev is still present or hw_addr is set */ if (netif_device_present(netdev) || interface->hw.hw_addr) return; /* We've lost the PCIe register space, and can no longer access the * device. Shut everything except the detach subtask down and prepare * to reset the device in case we recover. If we actually prepare for * reset, indicate that we're detached. */ if (fm10k_prepare_for_reset(interface)) set_bit(__FM10K_RESET_DETACHED, interface->state); /* check the real address space to see if we've recovered */ hw_addr = READ_ONCE(interface->uc_addr); value = readl(hw_addr); if (~value) { int err; /* Make sure the reset was initiated because we detached, * otherwise we might race with a different reset flow. */ if (!test_and_clear_bit(__FM10K_RESET_DETACHED, interface->state)) return; /* Restore the hardware address */ interface->hw.hw_addr = interface->uc_addr; /* PCIe link has been restored, and the device is active * again. Restore everything and reset the device. */ err = fm10k_handle_reset(interface); if (err) { netdev_err(netdev, "Unable to reset device: %d\n", err); interface->hw.hw_addr = NULL; return; } /* Re-attach the netdev */ netif_device_attach(netdev); netdev_warn(netdev, "PCIe link restored, device now attached\n"); return; } } static void fm10k_reset_subtask(struct fm10k_intfc *interface) { int err; if (!test_and_clear_bit(FM10K_FLAG_RESET_REQUESTED, interface->flags)) return; /* If another thread has already prepared to reset the device, we * should not attempt to handle a reset here, since we'd race with * that thread. This may happen if we suspend the device or if the * PCIe link is lost. In this case, we'll just ignore the RESET * request, as it will (eventually) be taken care of when the thread * which actually started the reset is finished. */ if (!fm10k_prepare_for_reset(interface)) return; netdev_err(interface->netdev, "Reset interface\n"); err = fm10k_handle_reset(interface); if (err) dev_err(&interface->pdev->dev, "fm10k_handle_reset failed: %d\n", err); } /** * fm10k_configure_swpri_map - Configure Receive SWPRI to PC mapping * @interface: board private structure * * Configure the SWPRI to PC mapping for the port. **/ static void fm10k_configure_swpri_map(struct fm10k_intfc *interface) { struct net_device *netdev = interface->netdev; struct fm10k_hw *hw = &interface->hw; int i; /* clear flag indicating update is needed */ clear_bit(FM10K_FLAG_SWPRI_CONFIG, interface->flags); /* these registers are only available on the PF */ if (hw->mac.type != fm10k_mac_pf) return; /* configure SWPRI to PC map */ for (i = 0; i < FM10K_SWPRI_MAX; i++) fm10k_write_reg(hw, FM10K_SWPRI_MAP(i), netdev_get_prio_tc_map(netdev, i)); } /** * fm10k_watchdog_update_host_state - Update the link status based on host. * @interface: board private structure **/ static void fm10k_watchdog_update_host_state(struct fm10k_intfc *interface) { struct fm10k_hw *hw = &interface->hw; s32 err; if (test_bit(__FM10K_LINK_DOWN, interface->state)) { interface->host_ready = false; if (time_is_after_jiffies(interface->link_down_event)) return; clear_bit(__FM10K_LINK_DOWN, interface->state); } if (test_bit(FM10K_FLAG_SWPRI_CONFIG, interface->flags)) { if (rtnl_trylock()) { fm10k_configure_swpri_map(interface); rtnl_unlock(); } } /* lock the mailbox for transmit and receive */ fm10k_mbx_lock(interface); err = hw->mac.ops.get_host_state(hw, &interface->host_ready); if (err && time_is_before_jiffies(interface->last_reset)) set_bit(FM10K_FLAG_RESET_REQUESTED, interface->flags); /* free the lock */ fm10k_mbx_unlock(interface); } /** * fm10k_mbx_subtask - Process upstream and downstream mailboxes * @interface: board private structure * * This function will process both the upstream and downstream mailboxes. **/ static void fm10k_mbx_subtask(struct fm10k_intfc *interface) { /* If we're resetting, bail out */ if (test_bit(__FM10K_RESETTING, interface->state)) return; /* process upstream mailbox and update device state */ fm10k_watchdog_update_host_state(interface); /* process downstream mailboxes */ fm10k_iov_mbx(interface); } /** * fm10k_watchdog_host_is_ready - Update netdev status based on host ready * @interface: board private structure **/ static void fm10k_watchdog_host_is_ready(struct fm10k_intfc *interface) { struct net_device *netdev = interface->netdev; /* only continue if link state is currently down */ if (netif_carrier_ok(netdev)) return; netif_info(interface, drv, netdev, "NIC Link is up\n"); netif_carrier_on(netdev); netif_tx_wake_all_queues(netdev); } /** * fm10k_watchdog_host_not_ready - Update netdev status based on host not ready * @interface: board private structure **/ static void fm10k_watchdog_host_not_ready(struct fm10k_intfc *interface) { struct net_device *netdev = interface->netdev; /* only continue if link state is currently up */ if (!netif_carrier_ok(netdev)) return; netif_info(interface, drv, netdev, "NIC Link is down\n"); netif_carrier_off(netdev); netif_tx_stop_all_queues(netdev); } /** * fm10k_update_stats - Update the board statistics counters. * @interface: board private structure **/ void fm10k_update_stats(struct fm10k_intfc *interface) { struct net_device_stats *net_stats = &interface->netdev->stats; struct fm10k_hw *hw = &interface->hw; u64 hw_csum_tx_good = 0, hw_csum_rx_good = 0, rx_length_errors = 0; u64 rx_switch_errors = 0, rx_drops = 0, rx_pp_errors = 0; u64 rx_link_errors = 0; u64 rx_errors = 0, rx_csum_errors = 0, tx_csum_errors = 0; u64 restart_queue = 0, tx_busy = 0, alloc_failed = 0; u64 rx_bytes_nic = 0, rx_pkts_nic = 0, rx_drops_nic = 0; u64 tx_bytes_nic = 0, tx_pkts_nic = 0; u64 bytes, pkts; int i; /* ensure only one thread updates stats at a time */ if (test_and_set_bit(__FM10K_UPDATING_STATS, interface->state)) return; /* do not allow stats update via service task for next second */ interface->next_stats_update = jiffies + HZ; /* gather some stats to the interface struct that are per queue */ for (bytes = 0, pkts = 0, i = 0; i < interface->num_tx_queues; i++) { struct fm10k_ring *tx_ring = READ_ONCE(interface->tx_ring[i]); if (!tx_ring) continue; restart_queue += tx_ring->tx_stats.restart_queue; tx_busy += tx_ring->tx_stats.tx_busy; tx_csum_errors += tx_ring->tx_stats.csum_err; bytes += tx_ring->stats.bytes; pkts += tx_ring->stats.packets; hw_csum_tx_good += tx_ring->tx_stats.csum_good; } interface->restart_queue = restart_queue; interface->tx_busy = tx_busy; net_stats->tx_bytes = bytes; net_stats->tx_packets = pkts; interface->tx_csum_errors = tx_csum_errors; interface->hw_csum_tx_good = hw_csum_tx_good; /* gather some stats to the interface struct that are per queue */ for (bytes = 0, pkts = 0, i = 0; i < interface->num_rx_queues; i++) { struct fm10k_ring *rx_ring = READ_ONCE(interface->rx_ring[i]); if (!rx_ring) continue; bytes += rx_ring->stats.bytes; pkts += rx_ring->stats.packets; alloc_failed += rx_ring->rx_stats.alloc_failed; rx_csum_errors += rx_ring->rx_stats.csum_err; rx_errors += rx_ring->rx_stats.errors; hw_csum_rx_good += rx_ring->rx_stats.csum_good; rx_switch_errors += rx_ring->rx_stats.switch_errors; rx_drops += rx_ring->rx_stats.drops; rx_pp_errors += rx_ring->rx_stats.pp_errors; rx_link_errors += rx_ring->rx_stats.link_errors; rx_length_errors += rx_ring->rx_stats.length_errors; } net_stats->rx_bytes = bytes; net_stats->rx_packets = pkts; interface->alloc_failed = alloc_failed; interface->rx_csum_errors = rx_csum_errors; interface->hw_csum_rx_good = hw_csum_rx_good; interface->rx_switch_errors = rx_switch_errors; interface->rx_drops = rx_drops; interface->rx_pp_errors = rx_pp_errors; interface->rx_link_errors = rx_link_errors; interface->rx_length_errors = rx_length_errors; hw->mac.ops.update_hw_stats(hw, &interface->stats); for (i = 0; i < hw->mac.max_queues; i++) { struct fm10k_hw_stats_q *q = &interface->stats.q[i]; tx_bytes_nic += q->tx_bytes.count; tx_pkts_nic += q->tx_packets.count; rx_bytes_nic += q->rx_bytes.count; rx_pkts_nic += q->rx_packets.count; rx_drops_nic += q->rx_drops.count; } interface->tx_bytes_nic = tx_bytes_nic; interface->tx_packets_nic = tx_pkts_nic; interface->rx_bytes_nic = rx_bytes_nic; interface->rx_packets_nic = rx_pkts_nic; interface->rx_drops_nic = rx_drops_nic; /* Fill out the OS statistics structure */ net_stats->rx_errors = rx_errors; net_stats->rx_dropped = interface->stats.nodesc_drop.count; /* Update VF statistics */ fm10k_iov_update_stats(interface); clear_bit(__FM10K_UPDATING_STATS, interface->state); } /** * fm10k_watchdog_flush_tx - flush queues on host not ready * @interface: pointer to the device interface structure **/ static void fm10k_watchdog_flush_tx(struct fm10k_intfc *interface) { int some_tx_pending = 0; int i; /* nothing to do if carrier is up */ if (netif_carrier_ok(interface->netdev)) return; for (i = 0; i < interface->num_tx_queues; i++) { struct fm10k_ring *tx_ring = interface->tx_ring[i]; if (tx_ring->next_to_use != tx_ring->next_to_clean) { some_tx_pending = 1; break; } } /* We've lost link, so the controller stops DMA, but we've got * queued Tx work that's never going to get done, so reset * controller to flush Tx. */ if (some_tx_pending) set_bit(FM10K_FLAG_RESET_REQUESTED, interface->flags); } /** * fm10k_watchdog_subtask - check and bring link up * @interface: pointer to the device interface structure **/ static void fm10k_watchdog_subtask(struct fm10k_intfc *interface) { /* if interface is down do nothing */ if (test_bit(__FM10K_DOWN, interface->state) || test_bit(__FM10K_RESETTING, interface->state)) return; if (interface->host_ready) fm10k_watchdog_host_is_ready(interface); else fm10k_watchdog_host_not_ready(interface); /* update stats only once every second */ if (time_is_before_jiffies(interface->next_stats_update)) fm10k_update_stats(interface); /* flush any uncompleted work */ fm10k_watchdog_flush_tx(interface); } /** * fm10k_check_hang_subtask - check for hung queues and dropped interrupts * @interface: pointer to the device interface structure * * This function serves two purposes. First it strobes the interrupt lines * in order to make certain interrupts are occurring. Secondly it sets the * bits needed to check for TX hangs. As a result we should immediately * determine if a hang has occurred. */ static void fm10k_check_hang_subtask(struct fm10k_intfc *interface) { /* If we're down or resetting, just bail */ if (test_bit(__FM10K_DOWN, interface->state) || test_bit(__FM10K_RESETTING, interface->state)) return; /* rate limit tx hang checks to only once every 2 seconds */ if (time_is_after_eq_jiffies(interface->next_tx_hang_check)) return; interface->next_tx_hang_check = jiffies + (2 * HZ); if (netif_carrier_ok(interface->netdev)) { int i; /* Force detection of hung controller */ for (i = 0; i < interface->num_tx_queues; i++) set_check_for_tx_hang(interface->tx_ring[i]); /* Rearm all in-use q_vectors for immediate firing */ for (i = 0; i < interface->num_q_vectors; i++) { struct fm10k_q_vector *qv = interface->q_vector[i]; if (!qv->tx.count && !qv->rx.count) continue; writel(FM10K_ITR_ENABLE | FM10K_ITR_PENDING2, qv->itr); } } } /** * fm10k_service_task - manages and runs subtasks * @work: pointer to work_struct containing our data **/ static void fm10k_service_task(struct work_struct *work) { struct fm10k_intfc *interface; interface = container_of(work, struct fm10k_intfc, service_task); /* Check whether we're detached first */ fm10k_detach_subtask(interface); /* tasks run even when interface is down */ fm10k_mbx_subtask(interface); fm10k_reset_subtask(interface); /* tasks only run when interface is up */ fm10k_watchdog_subtask(interface); fm10k_check_hang_subtask(interface); /* release lock on service events to allow scheduling next event */ fm10k_service_event_complete(interface); } /** * fm10k_macvlan_task - send queued MAC/VLAN requests to switch manager * @work: pointer to work_struct containing our data * * This work item handles sending MAC/VLAN updates to the switch manager. When * the interface is up, it will attempt to queue mailbox messages to the * switch manager requesting updates for MAC/VLAN pairs. If the Tx fifo of the * mailbox is full, it will reschedule itself to try again in a short while. * This ensures that the driver does not overload the switch mailbox with too * many simultaneous requests, causing an unnecessary reset. **/ static void fm10k_macvlan_task(struct work_struct *work) { struct fm10k_macvlan_request *item; struct fm10k_intfc *interface; struct delayed_work *dwork; struct list_head *requests; struct fm10k_hw *hw; unsigned long flags; dwork = to_delayed_work(work); interface = container_of(dwork, struct fm10k_intfc, macvlan_task); hw = &interface->hw; requests = &interface->macvlan_requests; do { /* Pop the first item off the list */ spin_lock_irqsave(&interface->macvlan_lock, flags); item = list_first_entry_or_null(requests, struct fm10k_macvlan_request, list); if (item) list_del_init(&item->list); spin_unlock_irqrestore(&interface->macvlan_lock, flags); /* We have no more items to process */ if (!item) goto done; fm10k_mbx_lock(interface); /* Check that we have plenty of space to send the message. We * want to ensure that the mailbox stays low enough to avoid a * change in the host state, otherwise we may see spurious * link up / link down notifications. */ if (!hw->mbx.ops.tx_ready(&hw->mbx, FM10K_VFMBX_MSG_MTU + 5)) { hw->mbx.ops.process(hw, &hw->mbx); set_bit(__FM10K_MACVLAN_REQUEST, interface->state); fm10k_mbx_unlock(interface); /* Put the request back on the list */ spin_lock_irqsave(&interface->macvlan_lock, flags); list_add(&item->list, requests); spin_unlock_irqrestore(&interface->macvlan_lock, flags); break; } switch (item->type) { case FM10K_MC_MAC_REQUEST: hw->mac.ops.update_mc_addr(hw, item->mac.glort, item->mac.addr, item->mac.vid, item->set); break; case FM10K_UC_MAC_REQUEST: hw->mac.ops.update_uc_addr(hw, item->mac.glort, item->mac.addr, item->mac.vid, item->set, 0); break; case FM10K_VLAN_REQUEST: hw->mac.ops.update_vlan(hw, item->vlan.vid, item->vlan.vsi, item->set); break; default: break; } fm10k_mbx_unlock(interface); /* Free the item now that we've sent the update */ kfree(item); } while (true); done: WARN_ON(!test_bit(__FM10K_MACVLAN_SCHED, interface->state)); /* flush memory to make sure state is correct */ smp_mb__before_atomic(); clear_bit(__FM10K_MACVLAN_SCHED, interface->state); /* If a MAC/VLAN request was scheduled since we started, we should * re-schedule. However, there is no reason to re-schedule if there is * no work to do. */ if (test_bit(__FM10K_MACVLAN_REQUEST, interface->state)) fm10k_macvlan_schedule(interface); } /** * fm10k_configure_tx_ring - Configure Tx ring after Reset * @interface: board private structure * @ring: structure containing ring specific data * * Configure the Tx descriptor ring after a reset. **/ static void fm10k_configure_tx_ring(struct fm10k_intfc *interface, struct fm10k_ring *ring) { struct fm10k_hw *hw = &interface->hw; u64 tdba = ring->dma; u32 size = ring->count * sizeof(struct fm10k_tx_desc); u32 txint = FM10K_INT_MAP_DISABLE; u32 txdctl = BIT(FM10K_TXDCTL_MAX_TIME_SHIFT) | FM10K_TXDCTL_ENABLE; u8 reg_idx = ring->reg_idx; /* disable queue to avoid issues while updating state */ fm10k_write_reg(hw, FM10K_TXDCTL(reg_idx), 0); fm10k_write_flush(hw); /* possible poll here to verify ring resources have been cleaned */ /* set location and size for descriptor ring */ fm10k_write_reg(hw, FM10K_TDBAL(reg_idx), tdba & DMA_BIT_MASK(32)); fm10k_write_reg(hw, FM10K_TDBAH(reg_idx), tdba >> 32); fm10k_write_reg(hw, FM10K_TDLEN(reg_idx), size); /* reset head and tail pointers */ fm10k_write_reg(hw, FM10K_TDH(reg_idx), 0); fm10k_write_reg(hw, FM10K_TDT(reg_idx), 0); /* store tail pointer */ ring->tail = &interface->uc_addr[FM10K_TDT(reg_idx)]; /* reset ntu and ntc to place SW in sync with hardware */ ring->next_to_clean = 0; ring->next_to_use = 0; /* Map interrupt */ if (ring->q_vector) { txint = ring->q_vector->v_idx + NON_Q_VECTORS; txint |= FM10K_INT_MAP_TIMER0; } fm10k_write_reg(hw, FM10K_TXINT(reg_idx), txint); /* enable use of FTAG bit in Tx descriptor, register is RO for VF */ fm10k_write_reg(hw, FM10K_PFVTCTL(reg_idx), FM10K_PFVTCTL_FTAG_DESC_ENABLE); /* Initialize XPS */ if (!test_and_set_bit(__FM10K_TX_XPS_INIT_DONE, ring->state) && ring->q_vector) netif_set_xps_queue(ring->netdev, &ring->q_vector->affinity_mask, ring->queue_index); /* enable queue */ fm10k_write_reg(hw, FM10K_TXDCTL(reg_idx), txdctl); } /** * fm10k_enable_tx_ring - Verify Tx ring is enabled after configuration * @interface: board private structure * @ring: structure containing ring specific data * * Verify the Tx descriptor ring is ready for transmit. **/ static void fm10k_enable_tx_ring(struct fm10k_intfc *interface, struct fm10k_ring *ring) { struct fm10k_hw *hw = &interface->hw; int wait_loop = 10; u32 txdctl; u8 reg_idx = ring->reg_idx; /* if we are already enabled just exit */ if (fm10k_read_reg(hw, FM10K_TXDCTL(reg_idx)) & FM10K_TXDCTL_ENABLE) return; /* poll to verify queue is enabled */ do { usleep_range(1000, 2000); txdctl = fm10k_read_reg(hw, FM10K_TXDCTL(reg_idx)); } while (!(txdctl & FM10K_TXDCTL_ENABLE) && --wait_loop); if (!wait_loop) netif_err(interface, drv, interface->netdev, "Could not enable Tx Queue %d\n", reg_idx); } /** * fm10k_configure_tx - Configure Transmit Unit after Reset * @interface: board private structure * * Configure the Tx unit of the MAC after a reset. **/ static void fm10k_configure_tx(struct fm10k_intfc *interface) { int i; /* Setup the HW Tx Head and Tail descriptor pointers */ for (i = 0; i < interface->num_tx_queues; i++) fm10k_configure_tx_ring(interface, interface->tx_ring[i]); /* poll here to verify that Tx rings are now enabled */ for (i = 0; i < interface->num_tx_queues; i++) fm10k_enable_tx_ring(interface, interface->tx_ring[i]); } /** * fm10k_configure_rx_ring - Configure Rx ring after Reset * @interface: board private structure * @ring: structure containing ring specific data * * Configure the Rx descriptor ring after a reset. **/ static void fm10k_configure_rx_ring(struct fm10k_intfc *interface, struct fm10k_ring *ring) { u64 rdba = ring->dma; struct fm10k_hw *hw = &interface->hw; u32 size = ring->count * sizeof(union fm10k_rx_desc); u32 rxqctl, rxdctl = FM10K_RXDCTL_WRITE_BACK_MIN_DELAY; u32 srrctl = FM10K_SRRCTL_BUFFER_CHAINING_EN; u32 rxint = FM10K_INT_MAP_DISABLE; u8 rx_pause = interface->rx_pause; u8 reg_idx = ring->reg_idx; /* disable queue to avoid issues while updating state */ rxqctl = fm10k_read_reg(hw, FM10K_RXQCTL(reg_idx)); rxqctl &= ~FM10K_RXQCTL_ENABLE; fm10k_write_reg(hw, FM10K_RXQCTL(reg_idx), rxqctl); fm10k_write_flush(hw); /* possible poll here to verify ring resources have been cleaned */ /* set location and size for descriptor ring */ fm10k_write_reg(hw, FM10K_RDBAL(reg_idx), rdba & DMA_BIT_MASK(32)); fm10k_write_reg(hw, FM10K_RDBAH(reg_idx), rdba >> 32); fm10k_write_reg(hw, FM10K_RDLEN(reg_idx), size); /* reset head and tail pointers */ fm10k_write_reg(hw, FM10K_RDH(reg_idx), 0); fm10k_write_reg(hw, FM10K_RDT(reg_idx), 0); /* store tail pointer */ ring->tail = &interface->uc_addr[FM10K_RDT(reg_idx)]; /* reset ntu and ntc to place SW in sync with hardware */ ring->next_to_clean = 0; ring->next_to_use = 0; ring->next_to_alloc = 0; /* Configure the Rx buffer size for one buff without split */ srrctl |= FM10K_RX_BUFSZ >> FM10K_SRRCTL_BSIZEPKT_SHIFT; /* Configure the Rx ring to suppress loopback packets */ srrctl |= FM10K_SRRCTL_LOOPBACK_SUPPRESS; fm10k_write_reg(hw, FM10K_SRRCTL(reg_idx), srrctl); /* Enable drop on empty */ #ifdef CONFIG_DCB if (interface->pfc_en) rx_pause = interface->pfc_en; #endif if (!(rx_pause & BIT(ring->qos_pc))) rxdctl |= FM10K_RXDCTL_DROP_ON_EMPTY; fm10k_write_reg(hw, FM10K_RXDCTL(reg_idx), rxdctl); /* assign default VLAN to queue */ ring->vid = hw->mac.default_vid; /* if we have an active VLAN, disable default VLAN ID */ if (test_bit(hw->mac.default_vid, interface->active_vlans)) ring->vid |= FM10K_VLAN_CLEAR; /* Map interrupt */ if (ring->q_vector) { rxint = ring->q_vector->v_idx + NON_Q_VECTORS; rxint |= FM10K_INT_MAP_TIMER1; } fm10k_write_reg(hw, FM10K_RXINT(reg_idx), rxint); /* enable queue */ rxqctl = fm10k_read_reg(hw, FM10K_RXQCTL(reg_idx)); rxqctl |= FM10K_RXQCTL_ENABLE; fm10k_write_reg(hw, FM10K_RXQCTL(reg_idx), rxqctl); /* place buffers on ring for receive data */ fm10k_alloc_rx_buffers(ring, fm10k_desc_unused(ring)); } /** * fm10k_update_rx_drop_en - Configures the drop enable bits for Rx rings * @interface: board private structure * * Configure the drop enable bits for the Rx rings. **/ void fm10k_update_rx_drop_en(struct fm10k_intfc *interface) { struct fm10k_hw *hw = &interface->hw; u8 rx_pause = interface->rx_pause; int i; #ifdef CONFIG_DCB if (interface->pfc_en) rx_pause = interface->pfc_en; #endif for (i = 0; i < interface->num_rx_queues; i++) { struct fm10k_ring *ring = interface->rx_ring[i]; u32 rxdctl = FM10K_RXDCTL_WRITE_BACK_MIN_DELAY; u8 reg_idx = ring->reg_idx; if (!(rx_pause & BIT(ring->qos_pc))) rxdctl |= FM10K_RXDCTL_DROP_ON_EMPTY; fm10k_write_reg(hw, FM10K_RXDCTL(reg_idx), rxdctl); } } /** * fm10k_configure_dglort - Configure Receive DGLORT after reset * @interface: board private structure * * Configure the DGLORT description and RSS tables. **/ static void fm10k_configure_dglort(struct fm10k_intfc *interface) { struct fm10k_dglort_cfg dglort = { 0 }; struct fm10k_hw *hw = &interface->hw; int i; u32 mrqc; /* Fill out hash function seeds */ for (i = 0; i < FM10K_RSSRK_SIZE; i++) fm10k_write_reg(hw, FM10K_RSSRK(0, i), interface->rssrk[i]); /* Write RETA table to hardware */ for (i = 0; i < FM10K_RETA_SIZE; i++) fm10k_write_reg(hw, FM10K_RETA(0, i), interface->reta[i]); /* Generate RSS hash based on packet types, TCP/UDP * port numbers and/or IPv4/v6 src and dst addresses */ mrqc = FM10K_MRQC_IPV4 | FM10K_MRQC_TCP_IPV4 | FM10K_MRQC_IPV6 | FM10K_MRQC_TCP_IPV6; if (test_bit(FM10K_FLAG_RSS_FIELD_IPV4_UDP, interface->flags)) mrqc |= FM10K_MRQC_UDP_IPV4; if (test_bit(FM10K_FLAG_RSS_FIELD_IPV6_UDP, interface->flags)) mrqc |= FM10K_MRQC_UDP_IPV6; fm10k_write_reg(hw, FM10K_MRQC(0), mrqc); /* configure default DGLORT mapping for RSS/DCB */ dglort.inner_rss = 1; dglort.rss_l = fls(interface->ring_feature[RING_F_RSS].mask); dglort.pc_l = fls(interface->ring_feature[RING_F_QOS].mask); hw->mac.ops.configure_dglort_map(hw, &dglort); /* assign GLORT per queue for queue mapped testing */ if (interface->glort_count > 64) { memset(&dglort, 0, sizeof(dglort)); dglort.inner_rss = 1; dglort.glort = interface->glort + 64; dglort.idx = fm10k_dglort_pf_queue; dglort.queue_l = fls(interface->num_rx_queues - 1); hw->mac.ops.configure_dglort_map(hw, &dglort); } /* assign glort value for RSS/DCB specific to this interface */ memset(&dglort, 0, sizeof(dglort)); dglort.inner_rss = 1; dglort.glort = interface->glort; dglort.rss_l = fls(interface->ring_feature[RING_F_RSS].mask); dglort.pc_l = fls(interface->ring_feature[RING_F_QOS].mask); /* configure DGLORT mapping for RSS/DCB */ dglort.idx = fm10k_dglort_pf_rss; if (interface->l2_accel) dglort.shared_l = fls(interface->l2_accel->size); hw->mac.ops.configure_dglort_map(hw, &dglort); } /** * fm10k_configure_rx - Configure Receive Unit after Reset * @interface: board private structure * * Configure the Rx unit of the MAC after a reset. **/ static void fm10k_configure_rx(struct fm10k_intfc *interface) { int i; /* Configure SWPRI to PC map */ fm10k_configure_swpri_map(interface); /* Configure RSS and DGLORT map */ fm10k_configure_dglort(interface); /* Setup the HW Rx Head and Tail descriptor pointers */ for (i = 0; i < interface->num_rx_queues; i++) fm10k_configure_rx_ring(interface, interface->rx_ring[i]); /* possible poll here to verify that Rx rings are now enabled */ } static void fm10k_napi_enable_all(struct fm10k_intfc *interface) { struct fm10k_q_vector *q_vector; int q_idx; for (q_idx = 0; q_idx < interface->num_q_vectors; q_idx++) { q_vector = interface->q_vector[q_idx]; napi_enable(&q_vector->napi); } } static irqreturn_t fm10k_msix_clean_rings(int __always_unused irq, void *data) { struct fm10k_q_vector *q_vector = data; if (q_vector->rx.count || q_vector->tx.count) napi_schedule_irqoff(&q_vector->napi); return IRQ_HANDLED; } static irqreturn_t fm10k_msix_mbx_vf(int __always_unused irq, void *data) { struct fm10k_intfc *interface = data; struct fm10k_hw *hw = &interface->hw; struct fm10k_mbx_info *mbx = &hw->mbx; /* re-enable mailbox interrupt and indicate 20us delay */ fm10k_write_reg(hw, FM10K_VFITR(FM10K_MBX_VECTOR), (FM10K_MBX_INT_DELAY >> hw->mac.itr_scale) | FM10K_ITR_ENABLE); /* service upstream mailbox */ if (fm10k_mbx_trylock(interface)) { mbx->ops.process(hw, mbx); fm10k_mbx_unlock(interface); } hw->mac.get_host_state = true; fm10k_service_event_schedule(interface); return IRQ_HANDLED; } #define FM10K_ERR_MSG(type) case (type): error = #type; break static void fm10k_handle_fault(struct fm10k_intfc *interface, int type, struct fm10k_fault *fault) { struct pci_dev *pdev = interface->pdev; struct fm10k_hw *hw = &interface->hw; struct fm10k_iov_data *iov_data = interface->iov_data; char *error; switch (type) { case FM10K_PCA_FAULT: switch (fault->type) { default: error = "Unknown PCA error"; break; FM10K_ERR_MSG(PCA_NO_FAULT); FM10K_ERR_MSG(PCA_UNMAPPED_ADDR); FM10K_ERR_MSG(PCA_BAD_QACCESS_PF); FM10K_ERR_MSG(PCA_BAD_QACCESS_VF); FM10K_ERR_MSG(PCA_MALICIOUS_REQ); FM10K_ERR_MSG(PCA_POISONED_TLP); FM10K_ERR_MSG(PCA_TLP_ABORT); } break; case FM10K_THI_FAULT: switch (fault->type) { default: error = "Unknown THI error"; break; FM10K_ERR_MSG(THI_NO_FAULT); FM10K_ERR_MSG(THI_MAL_DIS_Q_FAULT); } break; case FM10K_FUM_FAULT: switch (fault->type) { default: error = "Unknown FUM error"; break; FM10K_ERR_MSG(FUM_NO_FAULT); FM10K_ERR_MSG(FUM_UNMAPPED_ADDR); FM10K_ERR_MSG(FUM_BAD_VF_QACCESS); FM10K_ERR_MSG(FUM_ADD_DECODE_ERR); FM10K_ERR_MSG(FUM_RO_ERROR); FM10K_ERR_MSG(FUM_QPRC_CRC_ERROR); FM10K_ERR_MSG(FUM_CSR_TIMEOUT); FM10K_ERR_MSG(FUM_INVALID_TYPE); FM10K_ERR_MSG(FUM_INVALID_LENGTH); FM10K_ERR_MSG(FUM_INVALID_BE); FM10K_ERR_MSG(FUM_INVALID_ALIGN); } break; default: error = "Undocumented fault"; break; } dev_warn(&pdev->dev, "%s Address: 0x%llx SpecInfo: 0x%x Func: %02x.%0x\n", error, fault->address, fault->specinfo, PCI_SLOT(fault->func), PCI_FUNC(fault->func)); /* For VF faults, clear out the respective LPORT, reset the queue * resources, and then reconnect to the mailbox. This allows the * VF in question to resume behavior. For transient faults that are * the result of non-malicious behavior this will log the fault and * allow the VF to resume functionality. Obviously for malicious VFs * they will be able to attempt malicious behavior again. In this * case, the system administrator will need to step in and manually * remove or disable the VF in question. */ if (fault->func && iov_data) { int vf = fault->func - 1; struct fm10k_vf_info *vf_info = &iov_data->vf_info[vf]; hw->iov.ops.reset_lport(hw, vf_info); hw->iov.ops.reset_resources(hw, vf_info); /* reset_lport disables the VF, so re-enable it */ hw->iov.ops.set_lport(hw, vf_info, vf, FM10K_VF_FLAG_MULTI_CAPABLE); /* reset_resources will disconnect from the mbx */ vf_info->mbx.ops.connect(hw, &vf_info->mbx); } } static void fm10k_report_fault(struct fm10k_intfc *interface, u32 eicr) { struct fm10k_hw *hw = &interface->hw; struct fm10k_fault fault = { 0 }; int type, err; for (eicr &= FM10K_EICR_FAULT_MASK, type = FM10K_PCA_FAULT; eicr; eicr >>= 1, type += FM10K_FAULT_SIZE) { /* only check if there is an error reported */ if (!(eicr & 0x1)) continue; /* retrieve fault info */ err = hw->mac.ops.get_fault(hw, type, &fault); if (err) { dev_err(&interface->pdev->dev, "error reading fault\n"); continue; } fm10k_handle_fault(interface, type, &fault); } } static void fm10k_reset_drop_on_empty(struct fm10k_intfc *interface, u32 eicr) { struct fm10k_hw *hw = &interface->hw; const u32 rxdctl = FM10K_RXDCTL_WRITE_BACK_MIN_DELAY; u32 maxholdq; int q; if (!(eicr & FM10K_EICR_MAXHOLDTIME)) return; maxholdq = fm10k_read_reg(hw, FM10K_MAXHOLDQ(7)); if (maxholdq) fm10k_write_reg(hw, FM10K_MAXHOLDQ(7), maxholdq); for (q = 255;;) { if (maxholdq & BIT(31)) { if (q < FM10K_MAX_QUEUES_PF) { interface->rx_overrun_pf++; fm10k_write_reg(hw, FM10K_RXDCTL(q), rxdctl); } else { interface->rx_overrun_vf++; } } maxholdq *= 2; if (!maxholdq) q &= ~(32 - 1); if (!q) break; if (q-- % 32) continue; maxholdq = fm10k_read_reg(hw, FM10K_MAXHOLDQ(q / 32)); if (maxholdq) fm10k_write_reg(hw, FM10K_MAXHOLDQ(q / 32), maxholdq); } } static irqreturn_t fm10k_msix_mbx_pf(int __always_unused irq, void *data) { struct fm10k_intfc *interface = data; struct fm10k_hw *hw = &interface->hw; struct fm10k_mbx_info *mbx = &hw->mbx; u32 eicr; /* unmask any set bits related to this interrupt */ eicr = fm10k_read_reg(hw, FM10K_EICR); fm10k_write_reg(hw, FM10K_EICR, eicr & (FM10K_EICR_MAILBOX | FM10K_EICR_SWITCHREADY | FM10K_EICR_SWITCHNOTREADY)); /* report any faults found to the message log */ fm10k_report_fault(interface, eicr); /* reset any queues disabled due to receiver overrun */ fm10k_reset_drop_on_empty(interface, eicr); /* service mailboxes */ if (fm10k_mbx_trylock(interface)) { s32 err = mbx->ops.process(hw, mbx); if (err == FM10K_ERR_RESET_REQUESTED) set_bit(FM10K_FLAG_RESET_REQUESTED, interface->flags); /* handle VFLRE events */ fm10k_iov_event(interface); fm10k_mbx_unlock(interface); } /* if switch toggled state we should reset GLORTs */ if (eicr & FM10K_EICR_SWITCHNOTREADY) { /* force link down for at least 4 seconds */ interface->link_down_event = jiffies + (4 * HZ); set_bit(__FM10K_LINK_DOWN, interface->state); /* reset dglort_map back to no config */ hw->mac.dglort_map = FM10K_DGLORTMAP_NONE; } /* we should validate host state after interrupt event */ hw->mac.get_host_state = true; /* validate host state, and handle VF mailboxes in the service task */ fm10k_service_event_schedule(interface); /* re-enable mailbox interrupt and indicate 20us delay */ fm10k_write_reg(hw, FM10K_ITR(FM10K_MBX_VECTOR), (FM10K_MBX_INT_DELAY >> hw->mac.itr_scale) | FM10K_ITR_ENABLE); return IRQ_HANDLED; } void fm10k_mbx_free_irq(struct fm10k_intfc *interface) { struct fm10k_hw *hw = &interface->hw; struct msix_entry *entry; int itr_reg; /* no mailbox IRQ to free if MSI-X is not enabled */ if (!interface->msix_entries) return; entry = &interface->msix_entries[FM10K_MBX_VECTOR]; /* disconnect the mailbox */ hw->mbx.ops.disconnect(hw, &hw->mbx); /* disable Mailbox cause */ if (hw->mac.type == fm10k_mac_pf) { fm10k_write_reg(hw, FM10K_EIMR, FM10K_EIMR_DISABLE(PCA_FAULT) | FM10K_EIMR_DISABLE(FUM_FAULT) | FM10K_EIMR_DISABLE(MAILBOX) | FM10K_EIMR_DISABLE(SWITCHREADY) | FM10K_EIMR_DISABLE(SWITCHNOTREADY) | FM10K_EIMR_DISABLE(SRAMERROR) | FM10K_EIMR_DISABLE(VFLR) | FM10K_EIMR_DISABLE(MAXHOLDTIME)); itr_reg = FM10K_ITR(FM10K_MBX_VECTOR); } else { itr_reg = FM10K_VFITR(FM10K_MBX_VECTOR); } fm10k_write_reg(hw, itr_reg, FM10K_ITR_MASK_SET); free_irq(entry->vector, interface); } static s32 fm10k_mbx_mac_addr(struct fm10k_hw *hw, u32 **results, struct fm10k_mbx_info *mbx) { bool vlan_override = hw->mac.vlan_override; u16 default_vid = hw->mac.default_vid; struct fm10k_intfc *interface; s32 err; err = fm10k_msg_mac_vlan_vf(hw, results, mbx); if (err) return err; interface = container_of(hw, struct fm10k_intfc, hw); /* MAC was changed so we need reset */ if (is_valid_ether_addr(hw->mac.perm_addr) && !ether_addr_equal(hw->mac.perm_addr, hw->mac.addr)) set_bit(FM10K_FLAG_RESET_REQUESTED, interface->flags); /* VLAN override was changed, or default VLAN changed */ if ((vlan_override != hw->mac.vlan_override) || (default_vid != hw->mac.default_vid)) set_bit(FM10K_FLAG_RESET_REQUESTED, interface->flags); return 0; } /* generic error handler for mailbox issues */ static s32 fm10k_mbx_error(struct fm10k_hw *hw, u32 **results, struct fm10k_mbx_info __always_unused *mbx) { struct fm10k_intfc *interface; struct pci_dev *pdev; interface = container_of(hw, struct fm10k_intfc, hw); pdev = interface->pdev; dev_err(&pdev->dev, "Unknown message ID %u\n", **results & FM10K_TLV_ID_MASK); return 0; } static const struct fm10k_msg_data vf_mbx_data[] = { FM10K_TLV_MSG_TEST_HANDLER(fm10k_tlv_msg_test), FM10K_VF_MSG_MAC_VLAN_HANDLER(fm10k_mbx_mac_addr), FM10K_VF_MSG_LPORT_STATE_HANDLER(fm10k_msg_lport_state_vf), FM10K_TLV_MSG_ERROR_HANDLER(fm10k_mbx_error), }; static int fm10k_mbx_request_irq_vf(struct fm10k_intfc *interface) { struct msix_entry *entry = &interface->msix_entries[FM10K_MBX_VECTOR]; struct net_device *dev = interface->netdev; struct fm10k_hw *hw = &interface->hw; int err; /* Use timer0 for interrupt moderation on the mailbox */ u32 itr = entry->entry | FM10K_INT_MAP_TIMER0; /* register mailbox handlers */ err = hw->mbx.ops.register_handlers(&hw->mbx, vf_mbx_data); if (err) return err; /* request the IRQ */ err = request_irq(entry->vector, fm10k_msix_mbx_vf, 0, dev->name, interface); if (err) { netif_err(interface, probe, dev, "request_irq for msix_mbx failed: %d\n", err); return err; } /* map all of the interrupt sources */ fm10k_write_reg(hw, FM10K_VFINT_MAP, itr); /* enable interrupt */ fm10k_write_reg(hw, FM10K_VFITR(entry->entry), FM10K_ITR_ENABLE); return 0; } static s32 fm10k_lport_map(struct fm10k_hw *hw, u32 **results, struct fm10k_mbx_info *mbx) { struct fm10k_intfc *interface; u32 dglort_map = hw->mac.dglort_map; s32 err; interface = container_of(hw, struct fm10k_intfc, hw); err = fm10k_msg_err_pf(hw, results, mbx); if (!err && hw->swapi.status) { /* force link down for a reasonable delay */ interface->link_down_event = jiffies + (2 * HZ); set_bit(__FM10K_LINK_DOWN, interface->state); /* reset dglort_map back to no config */ hw->mac.dglort_map = FM10K_DGLORTMAP_NONE; fm10k_service_event_schedule(interface); /* prevent overloading kernel message buffer */ if (interface->lport_map_failed) return 0; interface->lport_map_failed = true; if (hw->swapi.status == FM10K_MSG_ERR_PEP_NOT_SCHEDULED) dev_warn(&interface->pdev->dev, "cannot obtain link because the host interface is configured for a PCIe host interface bandwidth of zero\n"); dev_warn(&interface->pdev->dev, "request logical port map failed: %d\n", hw->swapi.status); return 0; } err = fm10k_msg_lport_map_pf(hw, results, mbx); if (err) return err; interface->lport_map_failed = false; /* we need to reset if port count was just updated */ if (dglort_map != hw->mac.dglort_map) set_bit(FM10K_FLAG_RESET_REQUESTED, interface->flags); return 0; } static s32 fm10k_update_pvid(struct fm10k_hw *hw, u32 **results, struct fm10k_mbx_info __always_unused *mbx) { struct fm10k_intfc *interface; u16 glort, pvid; u32 pvid_update; s32 err; err = fm10k_tlv_attr_get_u32(results[FM10K_PF_ATTR_ID_UPDATE_PVID], &pvid_update); if (err) return err; /* extract values from the pvid update */ glort = FM10K_MSG_HDR_FIELD_GET(pvid_update, UPDATE_PVID_GLORT); pvid = FM10K_MSG_HDR_FIELD_GET(pvid_update, UPDATE_PVID_PVID); /* if glort is not valid return error */ if (!fm10k_glort_valid_pf(hw, glort)) return FM10K_ERR_PARAM; /* verify VLAN ID is valid */ if (pvid >= FM10K_VLAN_TABLE_VID_MAX) return FM10K_ERR_PARAM; interface = container_of(hw, struct fm10k_intfc, hw); /* check to see if this belongs to one of the VFs */ err = fm10k_iov_update_pvid(interface, glort, pvid); if (!err) return 0; /* we need to reset if default VLAN was just updated */ if (pvid != hw->mac.default_vid) set_bit(FM10K_FLAG_RESET_REQUESTED, interface->flags); hw->mac.default_vid = pvid; return 0; } static const struct fm10k_msg_data pf_mbx_data[] = { FM10K_PF_MSG_ERR_HANDLER(XCAST_MODES, fm10k_msg_err_pf), FM10K_PF_MSG_ERR_HANDLER(UPDATE_MAC_FWD_RULE, fm10k_msg_err_pf), FM10K_PF_MSG_LPORT_MAP_HANDLER(fm10k_lport_map), FM10K_PF_MSG_ERR_HANDLER(LPORT_CREATE, fm10k_msg_err_pf), FM10K_PF_MSG_ERR_HANDLER(LPORT_DELETE, fm10k_msg_err_pf), FM10K_PF_MSG_UPDATE_PVID_HANDLER(fm10k_update_pvid), FM10K_TLV_MSG_ERROR_HANDLER(fm10k_mbx_error), }; static int fm10k_mbx_request_irq_pf(struct fm10k_intfc *interface) { struct msix_entry *entry = &interface->msix_entries[FM10K_MBX_VECTOR]; struct net_device *dev = interface->netdev; struct fm10k_hw *hw = &interface->hw; int err; /* Use timer0 for interrupt moderation on the mailbox */ u32 mbx_itr = entry->entry | FM10K_INT_MAP_TIMER0; u32 other_itr = entry->entry | FM10K_INT_MAP_IMMEDIATE; /* register mailbox handlers */ err = hw->mbx.ops.register_handlers(&hw->mbx, pf_mbx_data); if (err) return err; /* request the IRQ */ err = request_irq(entry->vector, fm10k_msix_mbx_pf, 0, dev->name, interface); if (err) { netif_err(interface, probe, dev, "request_irq for msix_mbx failed: %d\n", err); return err; } /* Enable interrupts w/ no moderation for "other" interrupts */ fm10k_write_reg(hw, FM10K_INT_MAP(fm10k_int_pcie_fault), other_itr); fm10k_write_reg(hw, FM10K_INT_MAP(fm10k_int_switch_up_down), other_itr); fm10k_write_reg(hw, FM10K_INT_MAP(fm10k_int_sram), other_itr); fm10k_write_reg(hw, FM10K_INT_MAP(fm10k_int_max_hold_time), other_itr); fm10k_write_reg(hw, FM10K_INT_MAP(fm10k_int_vflr), other_itr); /* Enable interrupts w/ moderation for mailbox */ fm10k_write_reg(hw, FM10K_INT_MAP(fm10k_int_mailbox), mbx_itr); /* Enable individual interrupt causes */ fm10k_write_reg(hw, FM10K_EIMR, FM10K_EIMR_ENABLE(PCA_FAULT) | FM10K_EIMR_ENABLE(FUM_FAULT) | FM10K_EIMR_ENABLE(MAILBOX) | FM10K_EIMR_ENABLE(SWITCHREADY) | FM10K_EIMR_ENABLE(SWITCHNOTREADY) | FM10K_EIMR_ENABLE(SRAMERROR) | FM10K_EIMR_ENABLE(VFLR) | FM10K_EIMR_ENABLE(MAXHOLDTIME)); /* enable interrupt */ fm10k_write_reg(hw, FM10K_ITR(entry->entry), FM10K_ITR_ENABLE); return 0; } int fm10k_mbx_request_irq(struct fm10k_intfc *interface) { struct fm10k_hw *hw = &interface->hw; int err; /* enable Mailbox cause */ if (hw->mac.type == fm10k_mac_pf) err = fm10k_mbx_request_irq_pf(interface); else err = fm10k_mbx_request_irq_vf(interface); if (err) return err; /* connect mailbox */ err = hw->mbx.ops.connect(hw, &hw->mbx); /* if the mailbox failed to connect, then free IRQ */ if (err) fm10k_mbx_free_irq(interface); return err; } /** * fm10k_qv_free_irq - release interrupts associated with queue vectors * @interface: board private structure * * Release all interrupts associated with this interface **/ void fm10k_qv_free_irq(struct fm10k_intfc *interface) { int vector = interface->num_q_vectors; struct msix_entry *entry; entry = &interface->msix_entries[NON_Q_VECTORS + vector]; while (vector) { struct fm10k_q_vector *q_vector; vector--; entry--; q_vector = interface->q_vector[vector]; if (!q_vector->tx.count && !q_vector->rx.count) continue; /* clear the affinity_mask in the IRQ descriptor */ irq_set_affinity_hint(entry->vector, NULL); /* disable interrupts */ writel(FM10K_ITR_MASK_SET, q_vector->itr); free_irq(entry->vector, q_vector); } } /** * fm10k_qv_request_irq - initialize interrupts for queue vectors * @interface: board private structure * * Attempts to configure interrupts using the best available * capabilities of the hardware and kernel. **/ int fm10k_qv_request_irq(struct fm10k_intfc *interface) { struct net_device *dev = interface->netdev; struct fm10k_hw *hw = &interface->hw; struct msix_entry *entry; unsigned int ri = 0, ti = 0; int vector, err; entry = &interface->msix_entries[NON_Q_VECTORS]; for (vector = 0; vector < interface->num_q_vectors; vector++) { struct fm10k_q_vector *q_vector = interface->q_vector[vector]; /* name the vector */ if (q_vector->tx.count && q_vector->rx.count) { snprintf(q_vector->name, sizeof(q_vector->name), "%s-TxRx-%u", dev->name, ri++); ti++; } else if (q_vector->rx.count) { snprintf(q_vector->name, sizeof(q_vector->name), "%s-rx-%u", dev->name, ri++); } else if (q_vector->tx.count) { snprintf(q_vector->name, sizeof(q_vector->name), "%s-tx-%u", dev->name, ti++); } else { /* skip this unused q_vector */ continue; } /* Assign ITR register to q_vector */ q_vector->itr = (hw->mac.type == fm10k_mac_pf) ? &interface->uc_addr[FM10K_ITR(entry->entry)] : &interface->uc_addr[FM10K_VFITR(entry->entry)]; /* request the IRQ */ err = request_irq(entry->vector, &fm10k_msix_clean_rings, 0, q_vector->name, q_vector); if (err) { netif_err(interface, probe, dev, "request_irq failed for MSIX interrupt Error: %d\n", err); goto err_out; } /* assign the mask for this irq */ irq_set_affinity_hint(entry->vector, &q_vector->affinity_mask); /* Enable q_vector */ writel(FM10K_ITR_ENABLE, q_vector->itr); entry++; } return 0; err_out: /* wind through the ring freeing all entries and vectors */ while (vector) { struct fm10k_q_vector *q_vector; entry--; vector--; q_vector = interface->q_vector[vector]; if (!q_vector->tx.count && !q_vector->rx.count) continue; /* clear the affinity_mask in the IRQ descriptor */ irq_set_affinity_hint(entry->vector, NULL); /* disable interrupts */ writel(FM10K_ITR_MASK_SET, q_vector->itr); free_irq(entry->vector, q_vector); } return err; } void fm10k_up(struct fm10k_intfc *interface) { struct fm10k_hw *hw = &interface->hw; /* Enable Tx/Rx DMA */ hw->mac.ops.start_hw(hw); /* configure Tx descriptor rings */ fm10k_configure_tx(interface); /* configure Rx descriptor rings */ fm10k_configure_rx(interface); /* configure interrupts */ hw->mac.ops.update_int_moderator(hw); /* enable statistics capture again */ clear_bit(__FM10K_UPDATING_STATS, interface->state); /* clear down bit to indicate we are ready to go */ clear_bit(__FM10K_DOWN, interface->state); /* enable polling cleanups */ fm10k_napi_enable_all(interface); /* re-establish Rx filters */ fm10k_restore_rx_state(interface); /* enable transmits */ netif_tx_start_all_queues(interface->netdev); /* kick off the service timer now */ hw->mac.get_host_state = true; mod_timer(&interface->service_timer, jiffies); } static void fm10k_napi_disable_all(struct fm10k_intfc *interface) { struct fm10k_q_vector *q_vector; int q_idx; for (q_idx = 0; q_idx < interface->num_q_vectors; q_idx++) { q_vector = interface->q_vector[q_idx]; napi_disable(&q_vector->napi); } } void fm10k_down(struct fm10k_intfc *interface) { struct net_device *netdev = interface->netdev; struct fm10k_hw *hw = &interface->hw; int err, i = 0, count = 0; /* signal that we are down to the interrupt handler and service task */ if (test_and_set_bit(__FM10K_DOWN, interface->state)) return; /* call carrier off first to avoid false dev_watchdog timeouts */ netif_carrier_off(netdev); /* disable transmits */ netif_tx_stop_all_queues(netdev); netif_tx_disable(netdev); /* reset Rx filters */ fm10k_reset_rx_state(interface); /* disable polling routines */ fm10k_napi_disable_all(interface); /* capture stats one last time before stopping interface */ fm10k_update_stats(interface); /* prevent updating statistics while we're down */ while (test_and_set_bit(__FM10K_UPDATING_STATS, interface->state)) usleep_range(1000, 2000); /* skip waiting for TX DMA if we lost PCIe link */ if (FM10K_REMOVED(hw->hw_addr)) goto skip_tx_dma_drain; /* In some rare circumstances it can take a while for Tx queues to * quiesce and be fully disabled. Attempt to .stop_hw() first, and * then if we get ERR_REQUESTS_PENDING, go ahead and wait in a loop * until the Tx queues have emptied, or until a number of retries. If * we fail to clear within the retry loop, we will issue a warning * indicating that Tx DMA is probably hung. Note this means we call * .stop_hw() twice but this shouldn't cause any problems. */ err = hw->mac.ops.stop_hw(hw); if (err != FM10K_ERR_REQUESTS_PENDING) goto skip_tx_dma_drain; #define TX_DMA_DRAIN_RETRIES 25 for (count = 0; count < TX_DMA_DRAIN_RETRIES; count++) { usleep_range(10000, 20000); /* start checking at the last ring to have pending Tx */ for (; i < interface->num_tx_queues; i++) if (fm10k_get_tx_pending(interface->tx_ring[i], false)) break; /* if all the queues are drained, we can break now */ if (i == interface->num_tx_queues) break; } if (count >= TX_DMA_DRAIN_RETRIES) dev_err(&interface->pdev->dev, "Tx queues failed to drain after %d tries. Tx DMA is probably hung.\n", count); skip_tx_dma_drain: /* Disable DMA engine for Tx/Rx */ err = hw->mac.ops.stop_hw(hw); if (err == FM10K_ERR_REQUESTS_PENDING) dev_err(&interface->pdev->dev, "due to pending requests hw was not shut down gracefully\n"); else if (err) dev_err(&interface->pdev->dev, "stop_hw failed: %d\n", err); /* free any buffers still on the rings */ fm10k_clean_all_tx_rings(interface); fm10k_clean_all_rx_rings(interface); } /** * fm10k_sw_init - Initialize general software structures * @interface: host interface private structure to initialize * @ent: PCI device ID entry * * fm10k_sw_init initializes the interface private data structure. * Fields are initialized based on PCI device information and * OS network device settings (MTU size). **/ static int fm10k_sw_init(struct fm10k_intfc *interface, const struct pci_device_id *ent) { const struct fm10k_info *fi = fm10k_info_tbl[ent->driver_data]; struct fm10k_hw *hw = &interface->hw; struct pci_dev *pdev = interface->pdev; struct net_device *netdev = interface->netdev; u32 rss_key[FM10K_RSSRK_SIZE]; unsigned int rss; int err; /* initialize back pointer */ hw->back = interface; hw->hw_addr = interface->uc_addr; /* PCI config space info */ hw->vendor_id = pdev->vendor; hw->device_id = pdev->device; hw->revision_id = pdev->revision; hw->subsystem_vendor_id = pdev->subsystem_vendor; hw->subsystem_device_id = pdev->subsystem_device; /* Setup hw api */ memcpy(&hw->mac.ops, fi->mac_ops, sizeof(hw->mac.ops)); hw->mac.type = fi->mac; /* Setup IOV handlers */ if (fi->iov_ops) memcpy(&hw->iov.ops, fi->iov_ops, sizeof(hw->iov.ops)); /* Set common capability flags and settings */ rss = min_t(int, FM10K_MAX_RSS_INDICES, num_online_cpus()); interface->ring_feature[RING_F_RSS].limit = rss; fi->get_invariants(hw); /* pick up the PCIe bus settings for reporting later */ if (hw->mac.ops.get_bus_info) hw->mac.ops.get_bus_info(hw); /* limit the usable DMA range */ if (hw->mac.ops.set_dma_mask) hw->mac.ops.set_dma_mask(hw, dma_get_mask(&pdev->dev)); /* update netdev with DMA restrictions */ if (dma_get_mask(&pdev->dev) > DMA_BIT_MASK(32)) { netdev->features |= NETIF_F_HIGHDMA; netdev->vlan_features |= NETIF_F_HIGHDMA; } /* reset and initialize the hardware so it is in a known state */ err = hw->mac.ops.reset_hw(hw); if (err) { dev_err(&pdev->dev, "reset_hw failed: %d\n", err); return err; } err = hw->mac.ops.init_hw(hw); if (err) { dev_err(&pdev->dev, "init_hw failed: %d\n", err); return err; } /* initialize hardware statistics */ hw->mac.ops.update_hw_stats(hw, &interface->stats); /* Set upper limit on IOV VFs that can be allocated */ pci_sriov_set_totalvfs(pdev, hw->iov.total_vfs); /* Start with random Ethernet address */ eth_random_addr(hw->mac.addr); /* Initialize MAC address from hardware */ err = hw->mac.ops.read_mac_addr(hw); if (err) { dev_warn(&pdev->dev, "Failed to obtain MAC address defaulting to random\n"); /* tag address assignment as random */ netdev->addr_assign_type |= NET_ADDR_RANDOM; } eth_hw_addr_set(netdev, hw->mac.addr); ether_addr_copy(netdev->perm_addr, hw->mac.addr); if (!is_valid_ether_addr(netdev->perm_addr)) { dev_err(&pdev->dev, "Invalid MAC Address\n"); return -EIO; } /* initialize DCBNL interface */ fm10k_dcbnl_set_ops(netdev); /* set default ring sizes */ interface->tx_ring_count = FM10K_DEFAULT_TXD; interface->rx_ring_count = FM10K_DEFAULT_RXD; /* set default interrupt moderation */ interface->tx_itr = FM10K_TX_ITR_DEFAULT; interface->rx_itr = FM10K_ITR_ADAPTIVE | FM10K_RX_ITR_DEFAULT; /* Initialize the MAC/VLAN queue */ INIT_LIST_HEAD(&interface->macvlan_requests); netdev_rss_key_fill(rss_key, sizeof(rss_key)); memcpy(interface->rssrk, rss_key, sizeof(rss_key)); /* Initialize the mailbox lock */ spin_lock_init(&interface->mbx_lock); spin_lock_init(&interface->macvlan_lock); /* Start off interface as being down */ set_bit(__FM10K_DOWN, interface->state); set_bit(__FM10K_UPDATING_STATS, interface->state); return 0; } /** * fm10k_probe - Device Initialization Routine * @pdev: PCI device information struct * @ent: entry in fm10k_pci_tbl * * Returns 0 on success, negative on failure * * fm10k_probe initializes an interface identified by a pci_dev structure. * The OS initialization, configuring of the interface private structure, * and a hardware reset occur. **/ static int fm10k_probe(struct pci_dev *pdev, const struct pci_device_id *ent) { struct net_device *netdev; struct fm10k_intfc *interface; int err; if (pdev->error_state != pci_channel_io_normal) { dev_err(&pdev->dev, "PCI device still in an error state. Unable to load...\n"); return -EIO; } err = pci_enable_device_mem(pdev); if (err) { dev_err(&pdev->dev, "PCI enable device failed: %d\n", err); return err; } err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(48)); if (err) err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)); if (err) { dev_err(&pdev->dev, "DMA configuration failed: %d\n", err); goto err_dma; } err = pci_request_mem_regions(pdev, fm10k_driver_name); if (err) { dev_err(&pdev->dev, "pci_request_selected_regions failed: %d\n", err); goto err_pci_reg; } pci_set_master(pdev); pci_save_state(pdev); netdev = fm10k_alloc_netdev(fm10k_info_tbl[ent->driver_data]); if (!netdev) { err = -ENOMEM; goto err_alloc_netdev; } SET_NETDEV_DEV(netdev, &pdev->dev); interface = netdev_priv(netdev); pci_set_drvdata(pdev, interface); interface->netdev = netdev; interface->pdev = pdev; interface->uc_addr = ioremap(pci_resource_start(pdev, 0), FM10K_UC_ADDR_SIZE); if (!interface->uc_addr) { err = -EIO; goto err_ioremap; } err = fm10k_sw_init(interface, ent); if (err) goto err_sw_init; /* enable debugfs support */ fm10k_dbg_intfc_init(interface); err = fm10k_init_queueing_scheme(interface); if (err) goto err_sw_init; /* the mbx interrupt might attempt to schedule the service task, so we * must ensure it is disabled since we haven't yet requested the timer * or work item. */ set_bit(__FM10K_SERVICE_DISABLE, interface->state); err = fm10k_mbx_request_irq(interface); if (err) goto err_mbx_interrupt; /* final check of hardware state before registering the interface */ err = fm10k_hw_ready(interface); if (err) goto err_register; err = register_netdev(netdev); if (err) goto err_register; /* carrier off reporting is important to ethtool even BEFORE open */ netif_carrier_off(netdev); /* stop all the transmit queues from transmitting until link is up */ netif_tx_stop_all_queues(netdev); /* Initialize service timer and service task late in order to avoid * cleanup issues. */ timer_setup(&interface->service_timer, fm10k_service_timer, 0); INIT_WORK(&interface->service_task, fm10k_service_task); /* Setup the MAC/VLAN queue */ INIT_DELAYED_WORK(&interface->macvlan_task, fm10k_macvlan_task); /* kick off service timer now, even when interface is down */ mod_timer(&interface->service_timer, (HZ * 2) + jiffies); /* print warning for non-optimal configurations */ pcie_print_link_status(interface->pdev); /* report MAC address for logging */ dev_info(&pdev->dev, "%pM\n", netdev->dev_addr); /* enable SR-IOV after registering netdev to enforce PF/VF ordering */ fm10k_iov_configure(pdev, 0); /* clear the service task disable bit and kick off service task */ clear_bit(__FM10K_SERVICE_DISABLE, interface->state); fm10k_service_event_schedule(interface); return 0; err_register: fm10k_mbx_free_irq(interface); err_mbx_interrupt: fm10k_clear_queueing_scheme(interface); err_sw_init: if (interface->sw_addr) iounmap(interface->sw_addr); iounmap(interface->uc_addr); err_ioremap: free_netdev(netdev); err_alloc_netdev: pci_release_mem_regions(pdev); err_pci_reg: err_dma: pci_disable_device(pdev); return err; } /** * fm10k_remove - Device Removal Routine * @pdev: PCI device information struct * * fm10k_remove is called by the PCI subsystem to alert the driver * that it should release a PCI device. The could be caused by a * Hot-Plug event, or because the driver is going to be removed from * memory. **/ static void fm10k_remove(struct pci_dev *pdev) { struct fm10k_intfc *interface = pci_get_drvdata(pdev); struct net_device *netdev = interface->netdev; del_timer_sync(&interface->service_timer); fm10k_stop_service_event(interface); fm10k_stop_macvlan_task(interface); /* Remove all pending MAC/VLAN requests */ fm10k_clear_macvlan_queue(interface, interface->glort, true); /* free netdev, this may bounce the interrupts due to setup_tc */ if (netdev->reg_state == NETREG_REGISTERED) unregister_netdev(netdev); /* release VFs */ fm10k_iov_disable(pdev); /* disable mailbox interrupt */ fm10k_mbx_free_irq(interface); /* free interrupts */ fm10k_clear_queueing_scheme(interface); /* remove any debugfs interfaces */ fm10k_dbg_intfc_exit(interface); if (interface->sw_addr) iounmap(interface->sw_addr); iounmap(interface->uc_addr); free_netdev(netdev); pci_release_mem_regions(pdev); pci_disable_device(pdev); } static void fm10k_prepare_suspend(struct fm10k_intfc *interface) { /* the watchdog task reads from registers, which might appear like * a surprise remove if the PCIe device is disabled while we're * stopped. We stop the watchdog task until after we resume software * activity. * * Note that the MAC/VLAN task will be stopped as part of preparing * for reset so we don't need to handle it here. */ fm10k_stop_service_event(interface); if (fm10k_prepare_for_reset(interface)) set_bit(__FM10K_RESET_SUSPENDED, interface->state); } static int fm10k_handle_resume(struct fm10k_intfc *interface) { struct fm10k_hw *hw = &interface->hw; int err; /* Even if we didn't properly prepare for reset in * fm10k_prepare_suspend, we'll attempt to resume anyways. */ if (!test_and_clear_bit(__FM10K_RESET_SUSPENDED, interface->state)) dev_warn(&interface->pdev->dev, "Device was shut down as part of suspend... Attempting to recover\n"); /* reset statistics starting values */ hw->mac.ops.rebind_hw_stats(hw, &interface->stats); err = fm10k_handle_reset(interface); if (err) return err; /* assume host is not ready, to prevent race with watchdog in case we * actually don't have connection to the switch */ interface->host_ready = false; fm10k_watchdog_host_not_ready(interface); /* force link to stay down for a second to prevent link flutter */ interface->link_down_event = jiffies + (HZ); set_bit(__FM10K_LINK_DOWN, interface->state); /* restart the service task */ fm10k_start_service_event(interface); /* Restart the MAC/VLAN request queue in-case of outstanding events */ fm10k_macvlan_schedule(interface); return 0; } /** * fm10k_resume - Generic PM resume hook * @dev: generic device structure * * Generic PM hook used when waking the device from a low power state after * suspend or hibernation. This function does not need to handle lower PCIe * device state as the stack takes care of that for us. **/ static int __maybe_unused fm10k_resume(struct device *dev) { struct fm10k_intfc *interface = dev_get_drvdata(dev); struct net_device *netdev = interface->netdev; struct fm10k_hw *hw = &interface->hw; int err; /* refresh hw_addr in case it was dropped */ hw->hw_addr = interface->uc_addr; err = fm10k_handle_resume(interface); if (err) return err; netif_device_attach(netdev); return 0; } /** * fm10k_suspend - Generic PM suspend hook * @dev: generic device structure * * Generic PM hook used when setting the device into a low power state for * system suspend or hibernation. This function does not need to handle lower * PCIe device state as the stack takes care of that for us. **/ static int __maybe_unused fm10k_suspend(struct device *dev) { struct fm10k_intfc *interface = dev_get_drvdata(dev); struct net_device *netdev = interface->netdev; netif_device_detach(netdev); fm10k_prepare_suspend(interface); return 0; } /** * fm10k_io_error_detected - called when PCI error is detected * @pdev: Pointer to PCI device * @state: The current pci connection state * * This function is called after a PCI bus error affecting * this device has been detected. */ static pci_ers_result_t fm10k_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state) { struct fm10k_intfc *interface = pci_get_drvdata(pdev); struct net_device *netdev = interface->netdev; netif_device_detach(netdev); if (state == pci_channel_io_perm_failure) return PCI_ERS_RESULT_DISCONNECT; fm10k_prepare_suspend(interface); /* Request a slot reset. */ return PCI_ERS_RESULT_NEED_RESET; } /** * fm10k_io_slot_reset - called after the pci bus has been reset. * @pdev: Pointer to PCI device * * Restart the card from scratch, as if from a cold-boot. */ static pci_ers_result_t fm10k_io_slot_reset(struct pci_dev *pdev) { pci_ers_result_t result; if (pci_reenable_device(pdev)) { dev_err(&pdev->dev, "Cannot re-enable PCI device after reset.\n"); result = PCI_ERS_RESULT_DISCONNECT; } else { pci_set_master(pdev); pci_restore_state(pdev); /* After second error pci->state_saved is false, this * resets it so EEH doesn't break. */ pci_save_state(pdev); pci_wake_from_d3(pdev, false); result = PCI_ERS_RESULT_RECOVERED; } return result; } /** * fm10k_io_resume - called when traffic can start flowing again. * @pdev: Pointer to PCI device * * This callback is called when the error recovery driver tells us that * its OK to resume normal operation. */ static void fm10k_io_resume(struct pci_dev *pdev) { struct fm10k_intfc *interface = pci_get_drvdata(pdev); struct net_device *netdev = interface->netdev; int err; err = fm10k_handle_resume(interface); if (err) dev_warn(&pdev->dev, "%s failed: %d\n", __func__, err); else netif_device_attach(netdev); } /** * fm10k_io_reset_prepare - called when PCI function is about to be reset * @pdev: Pointer to PCI device * * This callback is called when the PCI function is about to be reset, * allowing the device driver to prepare for it. */ static void fm10k_io_reset_prepare(struct pci_dev *pdev) { /* warn incase we have any active VF devices */ if (pci_num_vf(pdev)) dev_warn(&pdev->dev, "PCIe FLR may cause issues for any active VF devices\n"); fm10k_prepare_suspend(pci_get_drvdata(pdev)); } /** * fm10k_io_reset_done - called when PCI function has finished resetting * @pdev: Pointer to PCI device * * This callback is called just after the PCI function is reset, such as via * /sys/class/net/<enpX>/device/reset or similar. */ static void fm10k_io_reset_done(struct pci_dev *pdev) { struct fm10k_intfc *interface = pci_get_drvdata(pdev); int err = fm10k_handle_resume(interface); if (err) { dev_warn(&pdev->dev, "%s failed: %d\n", __func__, err); netif_device_detach(interface->netdev); } } static const struct pci_error_handlers fm10k_err_handler = { .error_detected = fm10k_io_error_detected, .slot_reset = fm10k_io_slot_reset, .resume = fm10k_io_resume, .reset_prepare = fm10k_io_reset_prepare, .reset_done = fm10k_io_reset_done, }; static SIMPLE_DEV_PM_OPS(fm10k_pm_ops, fm10k_suspend, fm10k_resume); static struct pci_driver fm10k_driver = { .name = fm10k_driver_name, .id_table = fm10k_pci_tbl, .probe = fm10k_probe, .remove = fm10k_remove, .driver = { .pm = &fm10k_pm_ops, }, .sriov_configure = fm10k_iov_configure, .err_handler = &fm10k_err_handler }; /** * fm10k_register_pci_driver - register driver interface * * This function is called on module load in order to register the driver. **/ int fm10k_register_pci_driver(void) { return pci_register_driver(&fm10k_driver); } /** * fm10k_unregister_pci_driver - unregister driver interface * * This function is called on module unload in order to remove the driver. **/ void fm10k_unregister_pci_driver(void) { pci_unregister_driver(&fm10k_driver); }
linux-master
drivers/net/ethernet/intel/fm10k/fm10k_pci.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2013 - 2019 Intel Corporation. */ #include "fm10k.h" #include <linux/vmalloc.h> #include <net/udp_tunnel.h> #include <linux/if_macvlan.h> /** * fm10k_setup_tx_resources - allocate Tx resources (Descriptors) * @tx_ring: tx descriptor ring (for a specific queue) to setup * * Return 0 on success, negative on failure **/ int fm10k_setup_tx_resources(struct fm10k_ring *tx_ring) { struct device *dev = tx_ring->dev; int size; size = sizeof(struct fm10k_tx_buffer) * tx_ring->count; tx_ring->tx_buffer = vzalloc(size); if (!tx_ring->tx_buffer) goto err; u64_stats_init(&tx_ring->syncp); /* round up to nearest 4K */ tx_ring->size = tx_ring->count * sizeof(struct fm10k_tx_desc); tx_ring->size = ALIGN(tx_ring->size, 4096); tx_ring->desc = dma_alloc_coherent(dev, tx_ring->size, &tx_ring->dma, GFP_KERNEL); if (!tx_ring->desc) goto err; return 0; err: vfree(tx_ring->tx_buffer); tx_ring->tx_buffer = NULL; return -ENOMEM; } /** * fm10k_setup_all_tx_resources - allocate all queues Tx resources * @interface: board private structure * * If this function returns with an error, then it's possible one or * more of the rings is populated (while the rest are not). It is the * callers duty to clean those orphaned rings. * * Return 0 on success, negative on failure **/ static int fm10k_setup_all_tx_resources(struct fm10k_intfc *interface) { int i, err; for (i = 0; i < interface->num_tx_queues; i++) { err = fm10k_setup_tx_resources(interface->tx_ring[i]); if (!err) continue; netif_err(interface, probe, interface->netdev, "Allocation for Tx Queue %u failed\n", i); goto err_setup_tx; } return 0; err_setup_tx: /* rewind the index freeing the rings as we go */ while (i--) fm10k_free_tx_resources(interface->tx_ring[i]); return err; } /** * fm10k_setup_rx_resources - allocate Rx resources (Descriptors) * @rx_ring: rx descriptor ring (for a specific queue) to setup * * Returns 0 on success, negative on failure **/ int fm10k_setup_rx_resources(struct fm10k_ring *rx_ring) { struct device *dev = rx_ring->dev; int size; size = sizeof(struct fm10k_rx_buffer) * rx_ring->count; rx_ring->rx_buffer = vzalloc(size); if (!rx_ring->rx_buffer) goto err; u64_stats_init(&rx_ring->syncp); /* Round up to nearest 4K */ rx_ring->size = rx_ring->count * sizeof(union fm10k_rx_desc); rx_ring->size = ALIGN(rx_ring->size, 4096); rx_ring->desc = dma_alloc_coherent(dev, rx_ring->size, &rx_ring->dma, GFP_KERNEL); if (!rx_ring->desc) goto err; return 0; err: vfree(rx_ring->rx_buffer); rx_ring->rx_buffer = NULL; return -ENOMEM; } /** * fm10k_setup_all_rx_resources - allocate all queues Rx resources * @interface: board private structure * * If this function returns with an error, then it's possible one or * more of the rings is populated (while the rest are not). It is the * callers duty to clean those orphaned rings. * * Return 0 on success, negative on failure **/ static int fm10k_setup_all_rx_resources(struct fm10k_intfc *interface) { int i, err; for (i = 0; i < interface->num_rx_queues; i++) { err = fm10k_setup_rx_resources(interface->rx_ring[i]); if (!err) continue; netif_err(interface, probe, interface->netdev, "Allocation for Rx Queue %u failed\n", i); goto err_setup_rx; } return 0; err_setup_rx: /* rewind the index freeing the rings as we go */ while (i--) fm10k_free_rx_resources(interface->rx_ring[i]); return err; } void fm10k_unmap_and_free_tx_resource(struct fm10k_ring *ring, struct fm10k_tx_buffer *tx_buffer) { if (tx_buffer->skb) { dev_kfree_skb_any(tx_buffer->skb); if (dma_unmap_len(tx_buffer, len)) dma_unmap_single(ring->dev, dma_unmap_addr(tx_buffer, dma), dma_unmap_len(tx_buffer, len), DMA_TO_DEVICE); } else if (dma_unmap_len(tx_buffer, len)) { dma_unmap_page(ring->dev, dma_unmap_addr(tx_buffer, dma), dma_unmap_len(tx_buffer, len), DMA_TO_DEVICE); } tx_buffer->next_to_watch = NULL; tx_buffer->skb = NULL; dma_unmap_len_set(tx_buffer, len, 0); /* tx_buffer must be completely set up in the transmit path */ } /** * fm10k_clean_tx_ring - Free Tx Buffers * @tx_ring: ring to be cleaned **/ static void fm10k_clean_tx_ring(struct fm10k_ring *tx_ring) { unsigned long size; u16 i; /* ring already cleared, nothing to do */ if (!tx_ring->tx_buffer) return; /* Free all the Tx ring sk_buffs */ for (i = 0; i < tx_ring->count; i++) { struct fm10k_tx_buffer *tx_buffer = &tx_ring->tx_buffer[i]; fm10k_unmap_and_free_tx_resource(tx_ring, tx_buffer); } /* reset BQL values */ netdev_tx_reset_queue(txring_txq(tx_ring)); size = sizeof(struct fm10k_tx_buffer) * tx_ring->count; memset(tx_ring->tx_buffer, 0, size); /* Zero out the descriptor ring */ memset(tx_ring->desc, 0, tx_ring->size); } /** * fm10k_free_tx_resources - Free Tx Resources per Queue * @tx_ring: Tx descriptor ring for a specific queue * * Free all transmit software resources **/ void fm10k_free_tx_resources(struct fm10k_ring *tx_ring) { fm10k_clean_tx_ring(tx_ring); vfree(tx_ring->tx_buffer); tx_ring->tx_buffer = NULL; /* if not set, then don't free */ if (!tx_ring->desc) return; dma_free_coherent(tx_ring->dev, tx_ring->size, tx_ring->desc, tx_ring->dma); tx_ring->desc = NULL; } /** * fm10k_clean_all_tx_rings - Free Tx Buffers for all queues * @interface: board private structure **/ void fm10k_clean_all_tx_rings(struct fm10k_intfc *interface) { int i; for (i = 0; i < interface->num_tx_queues; i++) fm10k_clean_tx_ring(interface->tx_ring[i]); } /** * fm10k_free_all_tx_resources - Free Tx Resources for All Queues * @interface: board private structure * * Free all transmit software resources **/ static void fm10k_free_all_tx_resources(struct fm10k_intfc *interface) { int i = interface->num_tx_queues; while (i--) fm10k_free_tx_resources(interface->tx_ring[i]); } /** * fm10k_clean_rx_ring - Free Rx Buffers per Queue * @rx_ring: ring to free buffers from **/ static void fm10k_clean_rx_ring(struct fm10k_ring *rx_ring) { unsigned long size; u16 i; if (!rx_ring->rx_buffer) return; dev_kfree_skb(rx_ring->skb); rx_ring->skb = NULL; /* Free all the Rx ring sk_buffs */ for (i = 0; i < rx_ring->count; i++) { struct fm10k_rx_buffer *buffer = &rx_ring->rx_buffer[i]; /* clean-up will only set page pointer to NULL */ if (!buffer->page) continue; dma_unmap_page(rx_ring->dev, buffer->dma, PAGE_SIZE, DMA_FROM_DEVICE); __free_page(buffer->page); buffer->page = NULL; } size = sizeof(struct fm10k_rx_buffer) * rx_ring->count; memset(rx_ring->rx_buffer, 0, size); /* Zero out the descriptor ring */ memset(rx_ring->desc, 0, rx_ring->size); rx_ring->next_to_alloc = 0; rx_ring->next_to_clean = 0; rx_ring->next_to_use = 0; } /** * fm10k_free_rx_resources - Free Rx Resources * @rx_ring: ring to clean the resources from * * Free all receive software resources **/ void fm10k_free_rx_resources(struct fm10k_ring *rx_ring) { fm10k_clean_rx_ring(rx_ring); vfree(rx_ring->rx_buffer); rx_ring->rx_buffer = NULL; /* if not set, then don't free */ if (!rx_ring->desc) return; dma_free_coherent(rx_ring->dev, rx_ring->size, rx_ring->desc, rx_ring->dma); rx_ring->desc = NULL; } /** * fm10k_clean_all_rx_rings - Free Rx Buffers for all queues * @interface: board private structure **/ void fm10k_clean_all_rx_rings(struct fm10k_intfc *interface) { int i; for (i = 0; i < interface->num_rx_queues; i++) fm10k_clean_rx_ring(interface->rx_ring[i]); } /** * fm10k_free_all_rx_resources - Free Rx Resources for All Queues * @interface: board private structure * * Free all receive software resources **/ static void fm10k_free_all_rx_resources(struct fm10k_intfc *interface) { int i = interface->num_rx_queues; while (i--) fm10k_free_rx_resources(interface->rx_ring[i]); } /** * fm10k_request_glort_range - Request GLORTs for use in configuring rules * @interface: board private structure * * This function allocates a range of glorts for this interface to use. **/ static void fm10k_request_glort_range(struct fm10k_intfc *interface) { struct fm10k_hw *hw = &interface->hw; u16 mask = (~hw->mac.dglort_map) >> FM10K_DGLORTMAP_MASK_SHIFT; /* establish GLORT base */ interface->glort = hw->mac.dglort_map & FM10K_DGLORTMAP_NONE; interface->glort_count = 0; /* nothing we can do until mask is allocated */ if (hw->mac.dglort_map == FM10K_DGLORTMAP_NONE) return; /* we support 3 possible GLORT configurations. * 1: VFs consume all but the last 1 * 2: VFs and PF split glorts with possible gap between * 3: VFs allocated first 64, all others belong to PF */ if (mask <= hw->iov.total_vfs) { interface->glort_count = 1; interface->glort += mask; } else if (mask < 64) { interface->glort_count = (mask + 1) / 2; interface->glort += interface->glort_count; } else { interface->glort_count = mask - 63; interface->glort += 64; } } /** * fm10k_restore_udp_port_info * @interface: board private structure * * This function restores the value in the tunnel_cfg register(s) after reset **/ static void fm10k_restore_udp_port_info(struct fm10k_intfc *interface) { struct fm10k_hw *hw = &interface->hw; /* only the PF supports configuring tunnels */ if (hw->mac.type != fm10k_mac_pf) return; /* restore tunnel configuration register */ fm10k_write_reg(hw, FM10K_TUNNEL_CFG, ntohs(interface->vxlan_port) | (ETH_P_TEB << FM10K_TUNNEL_CFG_NVGRE_SHIFT)); /* restore Geneve tunnel configuration register */ fm10k_write_reg(hw, FM10K_TUNNEL_CFG_GENEVE, ntohs(interface->geneve_port)); } /** * fm10k_udp_tunnel_sync - Called when UDP tunnel ports change * @dev: network interface device structure * @table: Tunnel table (according to tables of @fm10k_udp_tunnels) * * This function is called when a new UDP tunnel port is added or deleted. * Due to hardware restrictions, only one port per type can be offloaded at * once. Core will send to the driver a port of its choice. **/ static int fm10k_udp_tunnel_sync(struct net_device *dev, unsigned int table) { struct fm10k_intfc *interface = netdev_priv(dev); struct udp_tunnel_info ti; udp_tunnel_nic_get_port(dev, table, 0, &ti); if (!table) interface->vxlan_port = ti.port; else interface->geneve_port = ti.port; fm10k_restore_udp_port_info(interface); return 0; } static const struct udp_tunnel_nic_info fm10k_udp_tunnels = { .sync_table = fm10k_udp_tunnel_sync, .tables = { { .n_entries = 1, .tunnel_types = UDP_TUNNEL_TYPE_VXLAN, }, { .n_entries = 1, .tunnel_types = UDP_TUNNEL_TYPE_GENEVE, }, }, }; /** * fm10k_open - Called when a network interface is made active * @netdev: network interface device structure * * Returns 0 on success, negative value on failure * * The open entry point is called when a network interface is made * active by the system (IFF_UP). At this point all resources needed * for transmit and receive operations are allocated, the interrupt * handler is registered with the OS, the watchdog timer is started, * and the stack is notified that the interface is ready. **/ int fm10k_open(struct net_device *netdev) { struct fm10k_intfc *interface = netdev_priv(netdev); int err; /* allocate transmit descriptors */ err = fm10k_setup_all_tx_resources(interface); if (err) goto err_setup_tx; /* allocate receive descriptors */ err = fm10k_setup_all_rx_resources(interface); if (err) goto err_setup_rx; /* allocate interrupt resources */ err = fm10k_qv_request_irq(interface); if (err) goto err_req_irq; /* setup GLORT assignment for this port */ fm10k_request_glort_range(interface); /* Notify the stack of the actual queue counts */ err = netif_set_real_num_tx_queues(netdev, interface->num_tx_queues); if (err) goto err_set_queues; err = netif_set_real_num_rx_queues(netdev, interface->num_rx_queues); if (err) goto err_set_queues; fm10k_up(interface); return 0; err_set_queues: fm10k_qv_free_irq(interface); err_req_irq: fm10k_free_all_rx_resources(interface); err_setup_rx: fm10k_free_all_tx_resources(interface); err_setup_tx: return err; } /** * fm10k_close - Disables a network interface * @netdev: network interface device structure * * Returns 0, this is not allowed to fail * * The close entry point is called when an interface is de-activated * by the OS. The hardware is still under the drivers control, but * needs to be disabled. A global MAC reset is issued to stop the * hardware, and all transmit and receive resources are freed. **/ int fm10k_close(struct net_device *netdev) { struct fm10k_intfc *interface = netdev_priv(netdev); fm10k_down(interface); fm10k_qv_free_irq(interface); fm10k_free_all_tx_resources(interface); fm10k_free_all_rx_resources(interface); return 0; } static netdev_tx_t fm10k_xmit_frame(struct sk_buff *skb, struct net_device *dev) { struct fm10k_intfc *interface = netdev_priv(dev); int num_tx_queues = READ_ONCE(interface->num_tx_queues); unsigned int r_idx = skb->queue_mapping; int err; if (!num_tx_queues) return NETDEV_TX_BUSY; if ((skb->protocol == htons(ETH_P_8021Q)) && !skb_vlan_tag_present(skb)) { /* FM10K only supports hardware tagging, any tags in frame * are considered 2nd level or "outer" tags */ struct vlan_hdr *vhdr; __be16 proto; /* make sure skb is not shared */ skb = skb_share_check(skb, GFP_ATOMIC); if (!skb) return NETDEV_TX_OK; /* make sure there is enough room to move the ethernet header */ if (unlikely(!pskb_may_pull(skb, VLAN_ETH_HLEN))) return NETDEV_TX_OK; /* verify the skb head is not shared */ err = skb_cow_head(skb, 0); if (err) { dev_kfree_skb(skb); return NETDEV_TX_OK; } /* locate VLAN header */ vhdr = (struct vlan_hdr *)(skb->data + ETH_HLEN); /* pull the 2 key pieces of data out of it */ __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), ntohs(vhdr->h_vlan_TCI)); proto = vhdr->h_vlan_encapsulated_proto; skb->protocol = (ntohs(proto) >= 1536) ? proto : htons(ETH_P_802_2); /* squash it by moving the ethernet addresses up 4 bytes */ memmove(skb->data + VLAN_HLEN, skb->data, 12); __skb_pull(skb, VLAN_HLEN); skb_reset_mac_header(skb); } /* The minimum packet size for a single buffer is 17B so pad the skb * in order to meet this minimum size requirement. */ if (unlikely(skb->len < 17)) { int pad_len = 17 - skb->len; if (skb_pad(skb, pad_len)) return NETDEV_TX_OK; __skb_put(skb, pad_len); } if (r_idx >= num_tx_queues) r_idx %= num_tx_queues; err = fm10k_xmit_frame_ring(skb, interface->tx_ring[r_idx]); return err; } /** * fm10k_tx_timeout - Respond to a Tx Hang * @netdev: network interface device structure * @txqueue: the index of the Tx queue that timed out **/ static void fm10k_tx_timeout(struct net_device *netdev, unsigned int txqueue) { struct fm10k_intfc *interface = netdev_priv(netdev); struct fm10k_ring *tx_ring; bool real_tx_hang = false; if (txqueue >= interface->num_tx_queues) { WARN(1, "invalid Tx queue index %d", txqueue); return; } tx_ring = interface->tx_ring[txqueue]; if (check_for_tx_hang(tx_ring) && fm10k_check_tx_hang(tx_ring)) real_tx_hang = true; #define TX_TIMEO_LIMIT 16000 if (real_tx_hang) { fm10k_tx_timeout_reset(interface); } else { netif_info(interface, drv, netdev, "Fake Tx hang detected with timeout of %d seconds\n", netdev->watchdog_timeo / HZ); /* fake Tx hang - increase the kernel timeout */ if (netdev->watchdog_timeo < TX_TIMEO_LIMIT) netdev->watchdog_timeo *= 2; } } /** * fm10k_host_mbx_ready - Check PF interface's mailbox readiness * @interface: board private structure * * This function checks if the PF interface's mailbox is ready before queueing * mailbox messages for transmission. This will prevent filling the TX mailbox * queue when the receiver is not ready. VF interfaces are exempt from this * check since it will block all PF-VF mailbox messages from being sent from * the VF to the PF at initialization. **/ static bool fm10k_host_mbx_ready(struct fm10k_intfc *interface) { struct fm10k_hw *hw = &interface->hw; return (hw->mac.type == fm10k_mac_vf || interface->host_ready); } /** * fm10k_queue_vlan_request - Queue a VLAN update request * @interface: the fm10k interface structure * @vid: the VLAN vid * @vsi: VSI index number * @set: whether to set or clear * * This function queues up a VLAN update. For VFs, this must be sent to the * managing PF over the mailbox. For PFs, we'll use the same handling so that * it's similar to the VF. This avoids storming the PF<->VF mailbox with too * many VLAN updates during reset. */ int fm10k_queue_vlan_request(struct fm10k_intfc *interface, u32 vid, u8 vsi, bool set) { struct fm10k_macvlan_request *request; unsigned long flags; /* This must be atomic since we may be called while the netdev * addr_list_lock is held */ request = kzalloc(sizeof(*request), GFP_ATOMIC); if (!request) return -ENOMEM; request->type = FM10K_VLAN_REQUEST; request->vlan.vid = vid; request->vlan.vsi = vsi; request->set = set; spin_lock_irqsave(&interface->macvlan_lock, flags); list_add_tail(&request->list, &interface->macvlan_requests); spin_unlock_irqrestore(&interface->macvlan_lock, flags); fm10k_macvlan_schedule(interface); return 0; } /** * fm10k_queue_mac_request - Queue a MAC update request * @interface: the fm10k interface structure * @glort: the target glort for this update * @addr: the address to update * @vid: the vid to update * @set: whether to add or remove * * This function queues up a MAC request for sending to the switch manager. * A separate thread monitors the queue and sends updates to the switch * manager. Return 0 on success, and negative error code on failure. **/ int fm10k_queue_mac_request(struct fm10k_intfc *interface, u16 glort, const unsigned char *addr, u16 vid, bool set) { struct fm10k_macvlan_request *request; unsigned long flags; /* This must be atomic since we may be called while the netdev * addr_list_lock is held */ request = kzalloc(sizeof(*request), GFP_ATOMIC); if (!request) return -ENOMEM; if (is_multicast_ether_addr(addr)) request->type = FM10K_MC_MAC_REQUEST; else request->type = FM10K_UC_MAC_REQUEST; ether_addr_copy(request->mac.addr, addr); request->mac.glort = glort; request->mac.vid = vid; request->set = set; spin_lock_irqsave(&interface->macvlan_lock, flags); list_add_tail(&request->list, &interface->macvlan_requests); spin_unlock_irqrestore(&interface->macvlan_lock, flags); fm10k_macvlan_schedule(interface); return 0; } /** * fm10k_clear_macvlan_queue - Cancel pending updates for a given glort * @interface: the fm10k interface structure * @glort: the target glort to clear * @vlans: true to clear VLAN messages, false to ignore them * * Cancel any outstanding MAC/VLAN requests for a given glort. This is * expected to be called when a logical port goes down. **/ void fm10k_clear_macvlan_queue(struct fm10k_intfc *interface, u16 glort, bool vlans) { struct fm10k_macvlan_request *r, *tmp; unsigned long flags; spin_lock_irqsave(&interface->macvlan_lock, flags); /* Free any outstanding MAC/VLAN requests for this interface */ list_for_each_entry_safe(r, tmp, &interface->macvlan_requests, list) { switch (r->type) { case FM10K_MC_MAC_REQUEST: case FM10K_UC_MAC_REQUEST: /* Don't free requests for other interfaces */ if (r->mac.glort != glort) break; fallthrough; case FM10K_VLAN_REQUEST: if (vlans) { list_del(&r->list); kfree(r); } break; } } spin_unlock_irqrestore(&interface->macvlan_lock, flags); } static int fm10k_uc_vlan_unsync(struct net_device *netdev, const unsigned char *uc_addr) { struct fm10k_intfc *interface = netdev_priv(netdev); u16 glort = interface->glort; u16 vid = interface->vid; bool set = !!(vid / VLAN_N_VID); int err; /* drop any leading bits on the VLAN ID */ vid &= VLAN_N_VID - 1; err = fm10k_queue_mac_request(interface, glort, uc_addr, vid, set); if (err) return err; /* return non-zero value as we are only doing a partial sync/unsync */ return 1; } static int fm10k_mc_vlan_unsync(struct net_device *netdev, const unsigned char *mc_addr) { struct fm10k_intfc *interface = netdev_priv(netdev); u16 glort = interface->glort; u16 vid = interface->vid; bool set = !!(vid / VLAN_N_VID); int err; /* drop any leading bits on the VLAN ID */ vid &= VLAN_N_VID - 1; err = fm10k_queue_mac_request(interface, glort, mc_addr, vid, set); if (err) return err; /* return non-zero value as we are only doing a partial sync/unsync */ return 1; } static int fm10k_update_vid(struct net_device *netdev, u16 vid, bool set) { struct fm10k_intfc *interface = netdev_priv(netdev); struct fm10k_l2_accel *l2_accel = interface->l2_accel; struct fm10k_hw *hw = &interface->hw; u16 glort; s32 err; int i; /* updates do not apply to VLAN 0 */ if (!vid) return 0; if (vid >= VLAN_N_VID) return -EINVAL; /* Verify that we have permission to add VLANs. If this is a request * to remove a VLAN, we still want to allow the user to remove the * VLAN device. In that case, we need to clear the bit in the * active_vlans bitmask. */ if (set && hw->mac.vlan_override) return -EACCES; /* update active_vlans bitmask */ set_bit(vid, interface->active_vlans); if (!set) clear_bit(vid, interface->active_vlans); /* disable the default VLAN ID on ring if we have an active VLAN */ for (i = 0; i < interface->num_rx_queues; i++) { struct fm10k_ring *rx_ring = interface->rx_ring[i]; u16 rx_vid = rx_ring->vid & (VLAN_N_VID - 1); if (test_bit(rx_vid, interface->active_vlans)) rx_ring->vid |= FM10K_VLAN_CLEAR; else rx_ring->vid &= ~FM10K_VLAN_CLEAR; } /* If our VLAN has been overridden, there is no reason to send VLAN * removal requests as they will be silently ignored. */ if (hw->mac.vlan_override) return 0; /* Do not remove default VLAN ID related entries from VLAN and MAC * tables */ if (!set && vid == hw->mac.default_vid) return 0; /* Do not throw an error if the interface is down. We will sync once * we come up */ if (test_bit(__FM10K_DOWN, interface->state)) return 0; fm10k_mbx_lock(interface); /* only need to update the VLAN if not in promiscuous mode */ if (!(netdev->flags & IFF_PROMISC)) { err = fm10k_queue_vlan_request(interface, vid, 0, set); if (err) goto err_out; } /* Update our base MAC address */ err = fm10k_queue_mac_request(interface, interface->glort, hw->mac.addr, vid, set); if (err) goto err_out; /* Update L2 accelerated macvlan addresses */ if (l2_accel) { for (i = 0; i < l2_accel->size; i++) { struct net_device *sdev = l2_accel->macvlan[i]; if (!sdev) continue; glort = l2_accel->dglort + 1 + i; fm10k_queue_mac_request(interface, glort, sdev->dev_addr, vid, set); } } /* set VLAN ID prior to syncing/unsyncing the VLAN */ interface->vid = vid + (set ? VLAN_N_VID : 0); /* Update the unicast and multicast address list to add/drop VLAN */ __dev_uc_unsync(netdev, fm10k_uc_vlan_unsync); __dev_mc_unsync(netdev, fm10k_mc_vlan_unsync); err_out: fm10k_mbx_unlock(interface); return err; } static int fm10k_vlan_rx_add_vid(struct net_device *netdev, __always_unused __be16 proto, u16 vid) { /* update VLAN and address table based on changes */ return fm10k_update_vid(netdev, vid, true); } static int fm10k_vlan_rx_kill_vid(struct net_device *netdev, __always_unused __be16 proto, u16 vid) { /* update VLAN and address table based on changes */ return fm10k_update_vid(netdev, vid, false); } static u16 fm10k_find_next_vlan(struct fm10k_intfc *interface, u16 vid) { struct fm10k_hw *hw = &interface->hw; u16 default_vid = hw->mac.default_vid; u16 vid_limit = vid < default_vid ? default_vid : VLAN_N_VID; vid = find_next_bit(interface->active_vlans, vid_limit, ++vid); return vid; } static void fm10k_clear_unused_vlans(struct fm10k_intfc *interface) { u32 vid, prev_vid; /* loop through and find any gaps in the table */ for (vid = 0, prev_vid = 0; prev_vid < VLAN_N_VID; prev_vid = vid + 1, vid = fm10k_find_next_vlan(interface, vid)) { if (prev_vid == vid) continue; /* send request to clear multiple bits at a time */ prev_vid += (vid - prev_vid - 1) << FM10K_VLAN_LENGTH_SHIFT; fm10k_queue_vlan_request(interface, prev_vid, 0, false); } } static int __fm10k_uc_sync(struct net_device *dev, const unsigned char *addr, bool sync) { struct fm10k_intfc *interface = netdev_priv(dev); u16 vid, glort = interface->glort; s32 err; if (!is_valid_ether_addr(addr)) return -EADDRNOTAVAIL; for (vid = fm10k_find_next_vlan(interface, 0); vid < VLAN_N_VID; vid = fm10k_find_next_vlan(interface, vid)) { err = fm10k_queue_mac_request(interface, glort, addr, vid, sync); if (err) return err; } return 0; } static int fm10k_uc_sync(struct net_device *dev, const unsigned char *addr) { return __fm10k_uc_sync(dev, addr, true); } static int fm10k_uc_unsync(struct net_device *dev, const unsigned char *addr) { return __fm10k_uc_sync(dev, addr, false); } static int fm10k_set_mac(struct net_device *dev, void *p) { struct fm10k_intfc *interface = netdev_priv(dev); struct fm10k_hw *hw = &interface->hw; struct sockaddr *addr = p; s32 err = 0; if (!is_valid_ether_addr(addr->sa_data)) return -EADDRNOTAVAIL; if (dev->flags & IFF_UP) { /* setting MAC address requires mailbox */ fm10k_mbx_lock(interface); err = fm10k_uc_sync(dev, addr->sa_data); if (!err) fm10k_uc_unsync(dev, hw->mac.addr); fm10k_mbx_unlock(interface); } if (!err) { eth_hw_addr_set(dev, addr->sa_data); ether_addr_copy(hw->mac.addr, addr->sa_data); dev->addr_assign_type &= ~NET_ADDR_RANDOM; } /* if we had a mailbox error suggest trying again */ return err ? -EAGAIN : 0; } static int __fm10k_mc_sync(struct net_device *dev, const unsigned char *addr, bool sync) { struct fm10k_intfc *interface = netdev_priv(dev); u16 vid, glort = interface->glort; s32 err; if (!is_multicast_ether_addr(addr)) return -EADDRNOTAVAIL; for (vid = fm10k_find_next_vlan(interface, 0); vid < VLAN_N_VID; vid = fm10k_find_next_vlan(interface, vid)) { err = fm10k_queue_mac_request(interface, glort, addr, vid, sync); if (err) return err; } return 0; } static int fm10k_mc_sync(struct net_device *dev, const unsigned char *addr) { return __fm10k_mc_sync(dev, addr, true); } static int fm10k_mc_unsync(struct net_device *dev, const unsigned char *addr) { return __fm10k_mc_sync(dev, addr, false); } static void fm10k_set_rx_mode(struct net_device *dev) { struct fm10k_intfc *interface = netdev_priv(dev); struct fm10k_hw *hw = &interface->hw; int xcast_mode; /* no need to update the harwdare if we are not running */ if (!(dev->flags & IFF_UP)) return; /* determine new mode based on flags */ xcast_mode = (dev->flags & IFF_PROMISC) ? FM10K_XCAST_MODE_PROMISC : (dev->flags & IFF_ALLMULTI) ? FM10K_XCAST_MODE_ALLMULTI : (dev->flags & (IFF_BROADCAST | IFF_MULTICAST)) ? FM10K_XCAST_MODE_MULTI : FM10K_XCAST_MODE_NONE; fm10k_mbx_lock(interface); /* update xcast mode first, but only if it changed */ if (interface->xcast_mode != xcast_mode) { /* update VLAN table when entering promiscuous mode */ if (xcast_mode == FM10K_XCAST_MODE_PROMISC) fm10k_queue_vlan_request(interface, FM10K_VLAN_ALL, 0, true); /* clear VLAN table when exiting promiscuous mode */ if (interface->xcast_mode == FM10K_XCAST_MODE_PROMISC) fm10k_clear_unused_vlans(interface); /* update xcast mode if host's mailbox is ready */ if (fm10k_host_mbx_ready(interface)) hw->mac.ops.update_xcast_mode(hw, interface->glort, xcast_mode); /* record updated xcast mode state */ interface->xcast_mode = xcast_mode; } /* synchronize all of the addresses */ __dev_uc_sync(dev, fm10k_uc_sync, fm10k_uc_unsync); __dev_mc_sync(dev, fm10k_mc_sync, fm10k_mc_unsync); fm10k_mbx_unlock(interface); } void fm10k_restore_rx_state(struct fm10k_intfc *interface) { struct fm10k_l2_accel *l2_accel = interface->l2_accel; struct net_device *netdev = interface->netdev; struct fm10k_hw *hw = &interface->hw; int xcast_mode, i; u16 vid, glort; /* record glort for this interface */ glort = interface->glort; /* convert interface flags to xcast mode */ if (netdev->flags & IFF_PROMISC) xcast_mode = FM10K_XCAST_MODE_PROMISC; else if (netdev->flags & IFF_ALLMULTI) xcast_mode = FM10K_XCAST_MODE_ALLMULTI; else if (netdev->flags & (IFF_BROADCAST | IFF_MULTICAST)) xcast_mode = FM10K_XCAST_MODE_MULTI; else xcast_mode = FM10K_XCAST_MODE_NONE; fm10k_mbx_lock(interface); /* Enable logical port if host's mailbox is ready */ if (fm10k_host_mbx_ready(interface)) hw->mac.ops.update_lport_state(hw, glort, interface->glort_count, true); /* update VLAN table */ fm10k_queue_vlan_request(interface, FM10K_VLAN_ALL, 0, xcast_mode == FM10K_XCAST_MODE_PROMISC); /* update table with current entries */ for (vid = fm10k_find_next_vlan(interface, 0); vid < VLAN_N_VID; vid = fm10k_find_next_vlan(interface, vid)) { fm10k_queue_vlan_request(interface, vid, 0, true); fm10k_queue_mac_request(interface, glort, hw->mac.addr, vid, true); /* synchronize macvlan addresses */ if (l2_accel) { for (i = 0; i < l2_accel->size; i++) { struct net_device *sdev = l2_accel->macvlan[i]; if (!sdev) continue; glort = l2_accel->dglort + 1 + i; fm10k_queue_mac_request(interface, glort, sdev->dev_addr, vid, true); } } } /* update xcast mode before synchronizing addresses if host's mailbox * is ready */ if (fm10k_host_mbx_ready(interface)) hw->mac.ops.update_xcast_mode(hw, glort, xcast_mode); /* synchronize all of the addresses */ __dev_uc_sync(netdev, fm10k_uc_sync, fm10k_uc_unsync); __dev_mc_sync(netdev, fm10k_mc_sync, fm10k_mc_unsync); /* synchronize macvlan addresses */ if (l2_accel) { for (i = 0; i < l2_accel->size; i++) { struct net_device *sdev = l2_accel->macvlan[i]; if (!sdev) continue; glort = l2_accel->dglort + 1 + i; hw->mac.ops.update_xcast_mode(hw, glort, FM10K_XCAST_MODE_NONE); fm10k_queue_mac_request(interface, glort, sdev->dev_addr, hw->mac.default_vid, true); } } fm10k_mbx_unlock(interface); /* record updated xcast mode state */ interface->xcast_mode = xcast_mode; /* Restore tunnel configuration */ fm10k_restore_udp_port_info(interface); } void fm10k_reset_rx_state(struct fm10k_intfc *interface) { struct net_device *netdev = interface->netdev; struct fm10k_hw *hw = &interface->hw; /* Wait for MAC/VLAN work to finish */ while (test_bit(__FM10K_MACVLAN_SCHED, interface->state)) usleep_range(1000, 2000); /* Cancel pending MAC/VLAN requests */ fm10k_clear_macvlan_queue(interface, interface->glort, true); fm10k_mbx_lock(interface); /* clear the logical port state on lower device if host's mailbox is * ready */ if (fm10k_host_mbx_ready(interface)) hw->mac.ops.update_lport_state(hw, interface->glort, interface->glort_count, false); fm10k_mbx_unlock(interface); /* reset flags to default state */ interface->xcast_mode = FM10K_XCAST_MODE_NONE; /* clear the sync flag since the lport has been dropped */ __dev_uc_unsync(netdev, NULL); __dev_mc_unsync(netdev, NULL); } /** * fm10k_get_stats64 - Get System Network Statistics * @netdev: network interface device structure * @stats: storage space for 64bit statistics * * Obtain 64bit statistics in a way that is safe for both 32bit and 64bit * architectures. */ static void fm10k_get_stats64(struct net_device *netdev, struct rtnl_link_stats64 *stats) { struct fm10k_intfc *interface = netdev_priv(netdev); struct fm10k_ring *ring; unsigned int start, i; u64 bytes, packets; rcu_read_lock(); for (i = 0; i < interface->num_rx_queues; i++) { ring = READ_ONCE(interface->rx_ring[i]); if (!ring) continue; do { start = u64_stats_fetch_begin(&ring->syncp); packets = ring->stats.packets; bytes = ring->stats.bytes; } while (u64_stats_fetch_retry(&ring->syncp, start)); stats->rx_packets += packets; stats->rx_bytes += bytes; } for (i = 0; i < interface->num_tx_queues; i++) { ring = READ_ONCE(interface->tx_ring[i]); if (!ring) continue; do { start = u64_stats_fetch_begin(&ring->syncp); packets = ring->stats.packets; bytes = ring->stats.bytes; } while (u64_stats_fetch_retry(&ring->syncp, start)); stats->tx_packets += packets; stats->tx_bytes += bytes; } rcu_read_unlock(); /* following stats updated by fm10k_service_task() */ stats->rx_missed_errors = netdev->stats.rx_missed_errors; } int fm10k_setup_tc(struct net_device *dev, u8 tc) { struct fm10k_intfc *interface = netdev_priv(dev); int err; /* Currently only the PF supports priority classes */ if (tc && (interface->hw.mac.type != fm10k_mac_pf)) return -EINVAL; /* Hardware supports up to 8 traffic classes */ if (tc > 8) return -EINVAL; /* Hardware has to reinitialize queues to match packet * buffer alignment. Unfortunately, the hardware is not * flexible enough to do this dynamically. */ if (netif_running(dev)) fm10k_close(dev); fm10k_mbx_free_irq(interface); fm10k_clear_queueing_scheme(interface); /* we expect the prio_tc map to be repopulated later */ netdev_reset_tc(dev); netdev_set_num_tc(dev, tc); err = fm10k_init_queueing_scheme(interface); if (err) goto err_queueing_scheme; err = fm10k_mbx_request_irq(interface); if (err) goto err_mbx_irq; err = netif_running(dev) ? fm10k_open(dev) : 0; if (err) goto err_open; /* flag to indicate SWPRI has yet to be updated */ set_bit(FM10K_FLAG_SWPRI_CONFIG, interface->flags); return 0; err_open: fm10k_mbx_free_irq(interface); err_mbx_irq: fm10k_clear_queueing_scheme(interface); err_queueing_scheme: netif_device_detach(dev); return err; } static int __fm10k_setup_tc(struct net_device *dev, enum tc_setup_type type, void *type_data) { struct tc_mqprio_qopt *mqprio = type_data; if (type != TC_SETUP_QDISC_MQPRIO) return -EOPNOTSUPP; mqprio->hw = TC_MQPRIO_HW_OFFLOAD_TCS; return fm10k_setup_tc(dev, mqprio->num_tc); } static void fm10k_assign_l2_accel(struct fm10k_intfc *interface, struct fm10k_l2_accel *l2_accel) { int i; for (i = 0; i < interface->num_rx_queues; i++) { struct fm10k_ring *ring = interface->rx_ring[i]; rcu_assign_pointer(ring->l2_accel, l2_accel); } interface->l2_accel = l2_accel; } static void *fm10k_dfwd_add_station(struct net_device *dev, struct net_device *sdev) { struct fm10k_intfc *interface = netdev_priv(dev); struct fm10k_l2_accel *l2_accel = interface->l2_accel; struct fm10k_l2_accel *old_l2_accel = NULL; struct fm10k_dglort_cfg dglort = { 0 }; struct fm10k_hw *hw = &interface->hw; int size, i; u16 vid, glort; /* The hardware supported by fm10k only filters on the destination MAC * address. In order to avoid issues we only support offloading modes * where the hardware can actually provide the functionality. */ if (!macvlan_supports_dest_filter(sdev)) return ERR_PTR(-EMEDIUMTYPE); /* allocate l2 accel structure if it is not available */ if (!l2_accel) { /* verify there is enough free GLORTs to support l2_accel */ if (interface->glort_count < 7) return ERR_PTR(-EBUSY); size = offsetof(struct fm10k_l2_accel, macvlan[7]); l2_accel = kzalloc(size, GFP_KERNEL); if (!l2_accel) return ERR_PTR(-ENOMEM); l2_accel->size = 7; l2_accel->dglort = interface->glort; /* update pointers */ fm10k_assign_l2_accel(interface, l2_accel); /* do not expand if we are at our limit */ } else if ((l2_accel->count == FM10K_MAX_STATIONS) || (l2_accel->count == (interface->glort_count - 1))) { return ERR_PTR(-EBUSY); /* expand if we have hit the size limit */ } else if (l2_accel->count == l2_accel->size) { old_l2_accel = l2_accel; size = offsetof(struct fm10k_l2_accel, macvlan[(l2_accel->size * 2) + 1]); l2_accel = kzalloc(size, GFP_KERNEL); if (!l2_accel) return ERR_PTR(-ENOMEM); memcpy(l2_accel, old_l2_accel, offsetof(struct fm10k_l2_accel, macvlan[old_l2_accel->size])); l2_accel->size = (old_l2_accel->size * 2) + 1; /* update pointers */ fm10k_assign_l2_accel(interface, l2_accel); kfree_rcu(old_l2_accel, rcu); } /* add macvlan to accel table, and record GLORT for position */ for (i = 0; i < l2_accel->size; i++) { if (!l2_accel->macvlan[i]) break; } /* record station */ l2_accel->macvlan[i] = sdev; l2_accel->count++; /* configure default DGLORT mapping for RSS/DCB */ dglort.idx = fm10k_dglort_pf_rss; dglort.inner_rss = 1; dglort.rss_l = fls(interface->ring_feature[RING_F_RSS].mask); dglort.pc_l = fls(interface->ring_feature[RING_F_QOS].mask); dglort.glort = interface->glort; dglort.shared_l = fls(l2_accel->size); hw->mac.ops.configure_dglort_map(hw, &dglort); /* Add rules for this specific dglort to the switch */ fm10k_mbx_lock(interface); glort = l2_accel->dglort + 1 + i; if (fm10k_host_mbx_ready(interface)) hw->mac.ops.update_xcast_mode(hw, glort, FM10K_XCAST_MODE_NONE); fm10k_queue_mac_request(interface, glort, sdev->dev_addr, hw->mac.default_vid, true); for (vid = fm10k_find_next_vlan(interface, 0); vid < VLAN_N_VID; vid = fm10k_find_next_vlan(interface, vid)) fm10k_queue_mac_request(interface, glort, sdev->dev_addr, vid, true); fm10k_mbx_unlock(interface); return sdev; } static void fm10k_dfwd_del_station(struct net_device *dev, void *priv) { struct fm10k_intfc *interface = netdev_priv(dev); struct fm10k_l2_accel *l2_accel = READ_ONCE(interface->l2_accel); struct fm10k_dglort_cfg dglort = { 0 }; struct fm10k_hw *hw = &interface->hw; struct net_device *sdev = priv; u16 vid, glort; int i; if (!l2_accel) return; /* search table for matching interface */ for (i = 0; i < l2_accel->size; i++) { if (l2_accel->macvlan[i] == sdev) break; } /* exit if macvlan not found */ if (i == l2_accel->size) return; /* Remove any rules specific to this dglort */ fm10k_mbx_lock(interface); glort = l2_accel->dglort + 1 + i; if (fm10k_host_mbx_ready(interface)) hw->mac.ops.update_xcast_mode(hw, glort, FM10K_XCAST_MODE_NONE); fm10k_queue_mac_request(interface, glort, sdev->dev_addr, hw->mac.default_vid, false); for (vid = fm10k_find_next_vlan(interface, 0); vid < VLAN_N_VID; vid = fm10k_find_next_vlan(interface, vid)) fm10k_queue_mac_request(interface, glort, sdev->dev_addr, vid, false); fm10k_mbx_unlock(interface); /* record removal */ l2_accel->macvlan[i] = NULL; l2_accel->count--; /* configure default DGLORT mapping for RSS/DCB */ dglort.idx = fm10k_dglort_pf_rss; dglort.inner_rss = 1; dglort.rss_l = fls(interface->ring_feature[RING_F_RSS].mask); dglort.pc_l = fls(interface->ring_feature[RING_F_QOS].mask); dglort.glort = interface->glort; dglort.shared_l = fls(l2_accel->size); hw->mac.ops.configure_dglort_map(hw, &dglort); /* If table is empty remove it */ if (l2_accel->count == 0) { fm10k_assign_l2_accel(interface, NULL); kfree_rcu(l2_accel, rcu); } } static netdev_features_t fm10k_features_check(struct sk_buff *skb, struct net_device *dev, netdev_features_t features) { if (!skb->encapsulation || fm10k_tx_encap_offload(skb)) return features; return features & ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK); } static const struct net_device_ops fm10k_netdev_ops = { .ndo_open = fm10k_open, .ndo_stop = fm10k_close, .ndo_validate_addr = eth_validate_addr, .ndo_start_xmit = fm10k_xmit_frame, .ndo_set_mac_address = fm10k_set_mac, .ndo_tx_timeout = fm10k_tx_timeout, .ndo_vlan_rx_add_vid = fm10k_vlan_rx_add_vid, .ndo_vlan_rx_kill_vid = fm10k_vlan_rx_kill_vid, .ndo_set_rx_mode = fm10k_set_rx_mode, .ndo_get_stats64 = fm10k_get_stats64, .ndo_setup_tc = __fm10k_setup_tc, .ndo_set_vf_mac = fm10k_ndo_set_vf_mac, .ndo_set_vf_vlan = fm10k_ndo_set_vf_vlan, .ndo_set_vf_rate = fm10k_ndo_set_vf_bw, .ndo_get_vf_config = fm10k_ndo_get_vf_config, .ndo_get_vf_stats = fm10k_ndo_get_vf_stats, .ndo_dfwd_add_station = fm10k_dfwd_add_station, .ndo_dfwd_del_station = fm10k_dfwd_del_station, .ndo_features_check = fm10k_features_check, }; #define DEFAULT_DEBUG_LEVEL_SHIFT 3 struct net_device *fm10k_alloc_netdev(const struct fm10k_info *info) { netdev_features_t hw_features; struct fm10k_intfc *interface; struct net_device *dev; dev = alloc_etherdev_mq(sizeof(struct fm10k_intfc), MAX_QUEUES); if (!dev) return NULL; /* set net device and ethtool ops */ dev->netdev_ops = &fm10k_netdev_ops; fm10k_set_ethtool_ops(dev); /* configure default debug level */ interface = netdev_priv(dev); interface->msg_enable = BIT(DEFAULT_DEBUG_LEVEL_SHIFT) - 1; /* configure default features */ dev->features |= NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM | NETIF_F_SG | NETIF_F_TSO | NETIF_F_TSO6 | NETIF_F_TSO_ECN | NETIF_F_RXHASH | NETIF_F_RXCSUM; /* Only the PF can support VXLAN and NVGRE tunnel offloads */ if (info->mac == fm10k_mac_pf) { dev->hw_enc_features = NETIF_F_IP_CSUM | NETIF_F_TSO | NETIF_F_TSO6 | NETIF_F_TSO_ECN | NETIF_F_GSO_UDP_TUNNEL | NETIF_F_IPV6_CSUM | NETIF_F_SG; dev->features |= NETIF_F_GSO_UDP_TUNNEL; dev->udp_tunnel_nic_info = &fm10k_udp_tunnels; } /* all features defined to this point should be changeable */ hw_features = dev->features; /* allow user to enable L2 forwarding acceleration */ hw_features |= NETIF_F_HW_L2FW_DOFFLOAD; /* configure VLAN features */ dev->vlan_features |= dev->features; /* we want to leave these both on as we cannot disable VLAN tag * insertion or stripping on the hardware since it is contained * in the FTAG and not in the frame itself. */ dev->features |= NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX | NETIF_F_HW_VLAN_CTAG_FILTER; dev->priv_flags |= IFF_UNICAST_FLT; dev->hw_features |= hw_features; /* MTU range: 68 - 15342 */ dev->min_mtu = ETH_MIN_MTU; dev->max_mtu = FM10K_MAX_JUMBO_FRAME_SIZE; return dev; }
linux-master
drivers/net/ethernet/intel/fm10k/fm10k_netdev.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2013 - 2019 Intel Corporation. */ #include <linux/types.h> #include <linux/module.h> #include <net/ipv6.h> #include <net/ip.h> #include <net/tcp.h> #include <linux/if_macvlan.h> #include <linux/prefetch.h> #include "fm10k.h" #define DRV_SUMMARY "Intel(R) Ethernet Switch Host Interface Driver" char fm10k_driver_name[] = "fm10k"; static const char fm10k_driver_string[] = DRV_SUMMARY; static const char fm10k_copyright[] = "Copyright(c) 2013 - 2019 Intel Corporation."; MODULE_AUTHOR("Intel Corporation, <[email protected]>"); MODULE_DESCRIPTION(DRV_SUMMARY); MODULE_LICENSE("GPL v2"); /* single workqueue for entire fm10k driver */ struct workqueue_struct *fm10k_workqueue; /** * fm10k_init_module - Driver Registration Routine * * fm10k_init_module is the first routine called when the driver is * loaded. All it does is register with the PCI subsystem. **/ static int __init fm10k_init_module(void) { int ret; pr_info("%s\n", fm10k_driver_string); pr_info("%s\n", fm10k_copyright); /* create driver workqueue */ fm10k_workqueue = alloc_workqueue("%s", WQ_MEM_RECLAIM, 0, fm10k_driver_name); if (!fm10k_workqueue) return -ENOMEM; fm10k_dbg_init(); ret = fm10k_register_pci_driver(); if (ret) { fm10k_dbg_exit(); destroy_workqueue(fm10k_workqueue); } return ret; } module_init(fm10k_init_module); /** * fm10k_exit_module - Driver Exit Cleanup Routine * * fm10k_exit_module is called just before the driver is removed * from memory. **/ static void __exit fm10k_exit_module(void) { fm10k_unregister_pci_driver(); fm10k_dbg_exit(); /* destroy driver workqueue */ destroy_workqueue(fm10k_workqueue); } module_exit(fm10k_exit_module); static bool fm10k_alloc_mapped_page(struct fm10k_ring *rx_ring, struct fm10k_rx_buffer *bi) { struct page *page = bi->page; dma_addr_t dma; /* Only page will be NULL if buffer was consumed */ if (likely(page)) return true; /* alloc new page for storage */ page = dev_alloc_page(); if (unlikely(!page)) { rx_ring->rx_stats.alloc_failed++; return false; } /* map page for use */ dma = dma_map_page(rx_ring->dev, page, 0, PAGE_SIZE, DMA_FROM_DEVICE); /* if mapping failed free memory back to system since * there isn't much point in holding memory we can't use */ if (dma_mapping_error(rx_ring->dev, dma)) { __free_page(page); rx_ring->rx_stats.alloc_failed++; return false; } bi->dma = dma; bi->page = page; bi->page_offset = 0; return true; } /** * fm10k_alloc_rx_buffers - Replace used receive buffers * @rx_ring: ring to place buffers on * @cleaned_count: number of buffers to replace **/ void fm10k_alloc_rx_buffers(struct fm10k_ring *rx_ring, u16 cleaned_count) { union fm10k_rx_desc *rx_desc; struct fm10k_rx_buffer *bi; u16 i = rx_ring->next_to_use; /* nothing to do */ if (!cleaned_count) return; rx_desc = FM10K_RX_DESC(rx_ring, i); bi = &rx_ring->rx_buffer[i]; i -= rx_ring->count; do { if (!fm10k_alloc_mapped_page(rx_ring, bi)) break; /* Refresh the desc even if buffer_addrs didn't change * because each write-back erases this info. */ rx_desc->q.pkt_addr = cpu_to_le64(bi->dma + bi->page_offset); rx_desc++; bi++; i++; if (unlikely(!i)) { rx_desc = FM10K_RX_DESC(rx_ring, 0); bi = rx_ring->rx_buffer; i -= rx_ring->count; } /* clear the status bits for the next_to_use descriptor */ rx_desc->d.staterr = 0; cleaned_count--; } while (cleaned_count); i += rx_ring->count; if (rx_ring->next_to_use != i) { /* record the next descriptor to use */ rx_ring->next_to_use = i; /* update next to alloc since we have filled the ring */ rx_ring->next_to_alloc = i; /* Force memory writes to complete before letting h/w * know there are new descriptors to fetch. (Only * applicable for weak-ordered memory model archs, * such as IA-64). */ wmb(); /* notify hardware of new descriptors */ writel(i, rx_ring->tail); } } /** * fm10k_reuse_rx_page - page flip buffer and store it back on the ring * @rx_ring: rx descriptor ring to store buffers on * @old_buff: donor buffer to have page reused * * Synchronizes page for reuse by the interface **/ static void fm10k_reuse_rx_page(struct fm10k_ring *rx_ring, struct fm10k_rx_buffer *old_buff) { struct fm10k_rx_buffer *new_buff; u16 nta = rx_ring->next_to_alloc; new_buff = &rx_ring->rx_buffer[nta]; /* update, and store next to alloc */ nta++; rx_ring->next_to_alloc = (nta < rx_ring->count) ? nta : 0; /* transfer page from old buffer to new buffer */ *new_buff = *old_buff; /* sync the buffer for use by the device */ dma_sync_single_range_for_device(rx_ring->dev, old_buff->dma, old_buff->page_offset, FM10K_RX_BUFSZ, DMA_FROM_DEVICE); } static bool fm10k_can_reuse_rx_page(struct fm10k_rx_buffer *rx_buffer, struct page *page, unsigned int __maybe_unused truesize) { /* avoid re-using remote and pfmemalloc pages */ if (!dev_page_is_reusable(page)) return false; #if (PAGE_SIZE < 8192) /* if we are only owner of page we can reuse it */ if (unlikely(page_count(page) != 1)) return false; /* flip page offset to other buffer */ rx_buffer->page_offset ^= FM10K_RX_BUFSZ; #else /* move offset up to the next cache line */ rx_buffer->page_offset += truesize; if (rx_buffer->page_offset > (PAGE_SIZE - FM10K_RX_BUFSZ)) return false; #endif /* Even if we own the page, we are not allowed to use atomic_set() * This would break get_page_unless_zero() users. */ page_ref_inc(page); return true; } /** * fm10k_add_rx_frag - Add contents of Rx buffer to sk_buff * @rx_buffer: buffer containing page to add * @size: packet size from rx_desc * @rx_desc: descriptor containing length of buffer written by hardware * @skb: sk_buff to place the data into * * This function will add the data contained in rx_buffer->page to the skb. * This is done either through a direct copy if the data in the buffer is * less than the skb header size, otherwise it will just attach the page as * a frag to the skb. * * The function will then update the page offset if necessary and return * true if the buffer can be reused by the interface. **/ static bool fm10k_add_rx_frag(struct fm10k_rx_buffer *rx_buffer, unsigned int size, union fm10k_rx_desc *rx_desc, struct sk_buff *skb) { struct page *page = rx_buffer->page; unsigned char *va = page_address(page) + rx_buffer->page_offset; #if (PAGE_SIZE < 8192) unsigned int truesize = FM10K_RX_BUFSZ; #else unsigned int truesize = ALIGN(size, 512); #endif unsigned int pull_len; if (unlikely(skb_is_nonlinear(skb))) goto add_tail_frag; if (likely(size <= FM10K_RX_HDR_LEN)) { memcpy(__skb_put(skb, size), va, ALIGN(size, sizeof(long))); /* page is reusable, we can reuse buffer as-is */ if (dev_page_is_reusable(page)) return true; /* this page cannot be reused so discard it */ __free_page(page); return false; } /* we need the header to contain the greater of either ETH_HLEN or * 60 bytes if the skb->len is less than 60 for skb_pad. */ pull_len = eth_get_headlen(skb->dev, va, FM10K_RX_HDR_LEN); /* align pull length to size of long to optimize memcpy performance */ memcpy(__skb_put(skb, pull_len), va, ALIGN(pull_len, sizeof(long))); /* update all of the pointers */ va += pull_len; size -= pull_len; add_tail_frag: skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, (unsigned long)va & ~PAGE_MASK, size, truesize); return fm10k_can_reuse_rx_page(rx_buffer, page, truesize); } static struct sk_buff *fm10k_fetch_rx_buffer(struct fm10k_ring *rx_ring, union fm10k_rx_desc *rx_desc, struct sk_buff *skb) { unsigned int size = le16_to_cpu(rx_desc->w.length); struct fm10k_rx_buffer *rx_buffer; struct page *page; rx_buffer = &rx_ring->rx_buffer[rx_ring->next_to_clean]; page = rx_buffer->page; prefetchw(page); if (likely(!skb)) { void *page_addr = page_address(page) + rx_buffer->page_offset; /* prefetch first cache line of first page */ net_prefetch(page_addr); /* allocate a skb to store the frags */ skb = napi_alloc_skb(&rx_ring->q_vector->napi, FM10K_RX_HDR_LEN); if (unlikely(!skb)) { rx_ring->rx_stats.alloc_failed++; return NULL; } /* we will be copying header into skb->data in * pskb_may_pull so it is in our interest to prefetch * it now to avoid a possible cache miss */ prefetchw(skb->data); } /* we are reusing so sync this buffer for CPU use */ dma_sync_single_range_for_cpu(rx_ring->dev, rx_buffer->dma, rx_buffer->page_offset, size, DMA_FROM_DEVICE); /* pull page into skb */ if (fm10k_add_rx_frag(rx_buffer, size, rx_desc, skb)) { /* hand second half of page back to the ring */ fm10k_reuse_rx_page(rx_ring, rx_buffer); } else { /* we are not reusing the buffer so unmap it */ dma_unmap_page(rx_ring->dev, rx_buffer->dma, PAGE_SIZE, DMA_FROM_DEVICE); } /* clear contents of rx_buffer */ rx_buffer->page = NULL; return skb; } static inline void fm10k_rx_checksum(struct fm10k_ring *ring, union fm10k_rx_desc *rx_desc, struct sk_buff *skb) { skb_checksum_none_assert(skb); /* Rx checksum disabled via ethtool */ if (!(ring->netdev->features & NETIF_F_RXCSUM)) return; /* TCP/UDP checksum error bit is set */ if (fm10k_test_staterr(rx_desc, FM10K_RXD_STATUS_L4E | FM10K_RXD_STATUS_L4E2 | FM10K_RXD_STATUS_IPE | FM10K_RXD_STATUS_IPE2)) { ring->rx_stats.csum_err++; return; } /* It must be a TCP or UDP packet with a valid checksum */ if (fm10k_test_staterr(rx_desc, FM10K_RXD_STATUS_L4CS2)) skb->encapsulation = true; else if (!fm10k_test_staterr(rx_desc, FM10K_RXD_STATUS_L4CS)) return; skb->ip_summed = CHECKSUM_UNNECESSARY; ring->rx_stats.csum_good++; } #define FM10K_RSS_L4_TYPES_MASK \ (BIT(FM10K_RSSTYPE_IPV4_TCP) | \ BIT(FM10K_RSSTYPE_IPV4_UDP) | \ BIT(FM10K_RSSTYPE_IPV6_TCP) | \ BIT(FM10K_RSSTYPE_IPV6_UDP)) static inline void fm10k_rx_hash(struct fm10k_ring *ring, union fm10k_rx_desc *rx_desc, struct sk_buff *skb) { u16 rss_type; if (!(ring->netdev->features & NETIF_F_RXHASH)) return; rss_type = le16_to_cpu(rx_desc->w.pkt_info) & FM10K_RXD_RSSTYPE_MASK; if (!rss_type) return; skb_set_hash(skb, le32_to_cpu(rx_desc->d.rss), (BIT(rss_type) & FM10K_RSS_L4_TYPES_MASK) ? PKT_HASH_TYPE_L4 : PKT_HASH_TYPE_L3); } static void fm10k_type_trans(struct fm10k_ring *rx_ring, union fm10k_rx_desc __maybe_unused *rx_desc, struct sk_buff *skb) { struct net_device *dev = rx_ring->netdev; struct fm10k_l2_accel *l2_accel = rcu_dereference_bh(rx_ring->l2_accel); /* check to see if DGLORT belongs to a MACVLAN */ if (l2_accel) { u16 idx = le16_to_cpu(FM10K_CB(skb)->fi.w.dglort) - 1; idx -= l2_accel->dglort; if (idx < l2_accel->size && l2_accel->macvlan[idx]) dev = l2_accel->macvlan[idx]; else l2_accel = NULL; } /* Record Rx queue, or update macvlan statistics */ if (!l2_accel) skb_record_rx_queue(skb, rx_ring->queue_index); else macvlan_count_rx(netdev_priv(dev), skb->len + ETH_HLEN, true, false); skb->protocol = eth_type_trans(skb, dev); } /** * fm10k_process_skb_fields - Populate skb header fields from Rx descriptor * @rx_ring: rx descriptor ring packet is being transacted on * @rx_desc: pointer to the EOP Rx descriptor * @skb: pointer to current skb being populated * * This function checks the ring, descriptor, and packet information in * order to populate the hash, checksum, VLAN, timestamp, protocol, and * other fields within the skb. **/ static unsigned int fm10k_process_skb_fields(struct fm10k_ring *rx_ring, union fm10k_rx_desc *rx_desc, struct sk_buff *skb) { unsigned int len = skb->len; fm10k_rx_hash(rx_ring, rx_desc, skb); fm10k_rx_checksum(rx_ring, rx_desc, skb); FM10K_CB(skb)->tstamp = rx_desc->q.timestamp; FM10K_CB(skb)->fi.w.vlan = rx_desc->w.vlan; FM10K_CB(skb)->fi.d.glort = rx_desc->d.glort; if (rx_desc->w.vlan) { u16 vid = le16_to_cpu(rx_desc->w.vlan); if ((vid & VLAN_VID_MASK) != rx_ring->vid) __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vid); else if (vid & VLAN_PRIO_MASK) __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vid & VLAN_PRIO_MASK); } fm10k_type_trans(rx_ring, rx_desc, skb); return len; } /** * fm10k_is_non_eop - process handling of non-EOP buffers * @rx_ring: Rx ring being processed * @rx_desc: Rx descriptor for current buffer * * This function updates next to clean. If the buffer is an EOP buffer * this function exits returning false, otherwise it will place the * sk_buff in the next buffer to be chained and return true indicating * that this is in fact a non-EOP buffer. **/ static bool fm10k_is_non_eop(struct fm10k_ring *rx_ring, union fm10k_rx_desc *rx_desc) { u32 ntc = rx_ring->next_to_clean + 1; /* fetch, update, and store next to clean */ ntc = (ntc < rx_ring->count) ? ntc : 0; rx_ring->next_to_clean = ntc; prefetch(FM10K_RX_DESC(rx_ring, ntc)); if (likely(fm10k_test_staterr(rx_desc, FM10K_RXD_STATUS_EOP))) return false; return true; } /** * fm10k_cleanup_headers - Correct corrupted or empty headers * @rx_ring: rx descriptor ring packet is being transacted on * @rx_desc: pointer to the EOP Rx descriptor * @skb: pointer to current skb being fixed * * Address the case where we are pulling data in on pages only * and as such no data is present in the skb header. * * In addition if skb is not at least 60 bytes we need to pad it so that * it is large enough to qualify as a valid Ethernet frame. * * Returns true if an error was encountered and skb was freed. **/ static bool fm10k_cleanup_headers(struct fm10k_ring *rx_ring, union fm10k_rx_desc *rx_desc, struct sk_buff *skb) { if (unlikely((fm10k_test_staterr(rx_desc, FM10K_RXD_STATUS_RXE)))) { #define FM10K_TEST_RXD_BIT(rxd, bit) \ ((rxd)->w.csum_err & cpu_to_le16(bit)) if (FM10K_TEST_RXD_BIT(rx_desc, FM10K_RXD_ERR_SWITCH_ERROR)) rx_ring->rx_stats.switch_errors++; if (FM10K_TEST_RXD_BIT(rx_desc, FM10K_RXD_ERR_NO_DESCRIPTOR)) rx_ring->rx_stats.drops++; if (FM10K_TEST_RXD_BIT(rx_desc, FM10K_RXD_ERR_PP_ERROR)) rx_ring->rx_stats.pp_errors++; if (FM10K_TEST_RXD_BIT(rx_desc, FM10K_RXD_ERR_SWITCH_READY)) rx_ring->rx_stats.link_errors++; if (FM10K_TEST_RXD_BIT(rx_desc, FM10K_RXD_ERR_TOO_BIG)) rx_ring->rx_stats.length_errors++; dev_kfree_skb_any(skb); rx_ring->rx_stats.errors++; return true; } /* if eth_skb_pad returns an error the skb was freed */ if (eth_skb_pad(skb)) return true; return false; } /** * fm10k_receive_skb - helper function to handle rx indications * @q_vector: structure containing interrupt and ring information * @skb: packet to send up **/ static void fm10k_receive_skb(struct fm10k_q_vector *q_vector, struct sk_buff *skb) { napi_gro_receive(&q_vector->napi, skb); } static int fm10k_clean_rx_irq(struct fm10k_q_vector *q_vector, struct fm10k_ring *rx_ring, int budget) { struct sk_buff *skb = rx_ring->skb; unsigned int total_bytes = 0, total_packets = 0; u16 cleaned_count = fm10k_desc_unused(rx_ring); while (likely(total_packets < budget)) { union fm10k_rx_desc *rx_desc; /* return some buffers to hardware, one at a time is too slow */ if (cleaned_count >= FM10K_RX_BUFFER_WRITE) { fm10k_alloc_rx_buffers(rx_ring, cleaned_count); cleaned_count = 0; } rx_desc = FM10K_RX_DESC(rx_ring, rx_ring->next_to_clean); if (!rx_desc->d.staterr) break; /* This memory barrier is needed to keep us from reading * any other fields out of the rx_desc until we know the * descriptor has been written back */ dma_rmb(); /* retrieve a buffer from the ring */ skb = fm10k_fetch_rx_buffer(rx_ring, rx_desc, skb); /* exit if we failed to retrieve a buffer */ if (!skb) break; cleaned_count++; /* fetch next buffer in frame if non-eop */ if (fm10k_is_non_eop(rx_ring, rx_desc)) continue; /* verify the packet layout is correct */ if (fm10k_cleanup_headers(rx_ring, rx_desc, skb)) { skb = NULL; continue; } /* populate checksum, timestamp, VLAN, and protocol */ total_bytes += fm10k_process_skb_fields(rx_ring, rx_desc, skb); fm10k_receive_skb(q_vector, skb); /* reset skb pointer */ skb = NULL; /* update budget accounting */ total_packets++; } /* place incomplete frames back on ring for completion */ rx_ring->skb = skb; u64_stats_update_begin(&rx_ring->syncp); rx_ring->stats.packets += total_packets; rx_ring->stats.bytes += total_bytes; u64_stats_update_end(&rx_ring->syncp); q_vector->rx.total_packets += total_packets; q_vector->rx.total_bytes += total_bytes; return total_packets; } #define VXLAN_HLEN (sizeof(struct udphdr) + 8) static struct ethhdr *fm10k_port_is_vxlan(struct sk_buff *skb) { struct fm10k_intfc *interface = netdev_priv(skb->dev); if (interface->vxlan_port != udp_hdr(skb)->dest) return NULL; /* return offset of udp_hdr plus 8 bytes for VXLAN header */ return (struct ethhdr *)(skb_transport_header(skb) + VXLAN_HLEN); } #define FM10K_NVGRE_RESERVED0_FLAGS htons(0x9FFF) #define NVGRE_TNI htons(0x2000) struct fm10k_nvgre_hdr { __be16 flags; __be16 proto; __be32 tni; }; static struct ethhdr *fm10k_gre_is_nvgre(struct sk_buff *skb) { struct fm10k_nvgre_hdr *nvgre_hdr; int hlen = ip_hdrlen(skb); /* currently only IPv4 is supported due to hlen above */ if (vlan_get_protocol(skb) != htons(ETH_P_IP)) return NULL; /* our transport header should be NVGRE */ nvgre_hdr = (struct fm10k_nvgre_hdr *)(skb_network_header(skb) + hlen); /* verify all reserved flags are 0 */ if (nvgre_hdr->flags & FM10K_NVGRE_RESERVED0_FLAGS) return NULL; /* report start of ethernet header */ if (nvgre_hdr->flags & NVGRE_TNI) return (struct ethhdr *)(nvgre_hdr + 1); return (struct ethhdr *)(&nvgre_hdr->tni); } __be16 fm10k_tx_encap_offload(struct sk_buff *skb) { u8 l4_hdr = 0, inner_l4_hdr = 0, inner_l4_hlen; struct ethhdr *eth_hdr; if (skb->inner_protocol_type != ENCAP_TYPE_ETHER || skb->inner_protocol != htons(ETH_P_TEB)) return 0; switch (vlan_get_protocol(skb)) { case htons(ETH_P_IP): l4_hdr = ip_hdr(skb)->protocol; break; case htons(ETH_P_IPV6): l4_hdr = ipv6_hdr(skb)->nexthdr; break; default: return 0; } switch (l4_hdr) { case IPPROTO_UDP: eth_hdr = fm10k_port_is_vxlan(skb); break; case IPPROTO_GRE: eth_hdr = fm10k_gre_is_nvgre(skb); break; default: return 0; } if (!eth_hdr) return 0; switch (eth_hdr->h_proto) { case htons(ETH_P_IP): inner_l4_hdr = inner_ip_hdr(skb)->protocol; break; case htons(ETH_P_IPV6): inner_l4_hdr = inner_ipv6_hdr(skb)->nexthdr; break; default: return 0; } switch (inner_l4_hdr) { case IPPROTO_TCP: inner_l4_hlen = inner_tcp_hdrlen(skb); break; case IPPROTO_UDP: inner_l4_hlen = 8; break; default: return 0; } /* The hardware allows tunnel offloads only if the combined inner and * outer header is 184 bytes or less */ if (skb_inner_transport_header(skb) + inner_l4_hlen - skb_mac_header(skb) > FM10K_TUNNEL_HEADER_LENGTH) return 0; return eth_hdr->h_proto; } static int fm10k_tso(struct fm10k_ring *tx_ring, struct fm10k_tx_buffer *first) { struct sk_buff *skb = first->skb; struct fm10k_tx_desc *tx_desc; unsigned char *th; u8 hdrlen; if (skb->ip_summed != CHECKSUM_PARTIAL) return 0; if (!skb_is_gso(skb)) return 0; /* compute header lengths */ if (skb->encapsulation) { if (!fm10k_tx_encap_offload(skb)) goto err_vxlan; th = skb_inner_transport_header(skb); } else { th = skb_transport_header(skb); } /* compute offset from SOF to transport header and add header len */ hdrlen = (th - skb->data) + (((struct tcphdr *)th)->doff << 2); first->tx_flags |= FM10K_TX_FLAGS_CSUM; /* update gso size and bytecount with header size */ first->gso_segs = skb_shinfo(skb)->gso_segs; first->bytecount += (first->gso_segs - 1) * hdrlen; /* populate Tx descriptor header size and mss */ tx_desc = FM10K_TX_DESC(tx_ring, tx_ring->next_to_use); tx_desc->hdrlen = hdrlen; tx_desc->mss = cpu_to_le16(skb_shinfo(skb)->gso_size); return 1; err_vxlan: tx_ring->netdev->features &= ~NETIF_F_GSO_UDP_TUNNEL; if (net_ratelimit()) netdev_err(tx_ring->netdev, "TSO requested for unsupported tunnel, disabling offload\n"); return -1; } static void fm10k_tx_csum(struct fm10k_ring *tx_ring, struct fm10k_tx_buffer *first) { struct sk_buff *skb = first->skb; struct fm10k_tx_desc *tx_desc; union { struct iphdr *ipv4; struct ipv6hdr *ipv6; u8 *raw; } network_hdr; u8 *transport_hdr; __be16 frag_off; __be16 protocol; u8 l4_hdr = 0; if (skb->ip_summed != CHECKSUM_PARTIAL) goto no_csum; if (skb->encapsulation) { protocol = fm10k_tx_encap_offload(skb); if (!protocol) { if (skb_checksum_help(skb)) { dev_warn(tx_ring->dev, "failed to offload encap csum!\n"); tx_ring->tx_stats.csum_err++; } goto no_csum; } network_hdr.raw = skb_inner_network_header(skb); transport_hdr = skb_inner_transport_header(skb); } else { protocol = vlan_get_protocol(skb); network_hdr.raw = skb_network_header(skb); transport_hdr = skb_transport_header(skb); } switch (protocol) { case htons(ETH_P_IP): l4_hdr = network_hdr.ipv4->protocol; break; case htons(ETH_P_IPV6): l4_hdr = network_hdr.ipv6->nexthdr; if (likely((transport_hdr - network_hdr.raw) == sizeof(struct ipv6hdr))) break; ipv6_skip_exthdr(skb, network_hdr.raw - skb->data + sizeof(struct ipv6hdr), &l4_hdr, &frag_off); if (unlikely(frag_off)) l4_hdr = NEXTHDR_FRAGMENT; break; default: break; } switch (l4_hdr) { case IPPROTO_TCP: case IPPROTO_UDP: break; case IPPROTO_GRE: if (skb->encapsulation) break; fallthrough; default: if (unlikely(net_ratelimit())) { dev_warn(tx_ring->dev, "partial checksum, version=%d l4 proto=%x\n", protocol, l4_hdr); } skb_checksum_help(skb); tx_ring->tx_stats.csum_err++; goto no_csum; } /* update TX checksum flag */ first->tx_flags |= FM10K_TX_FLAGS_CSUM; tx_ring->tx_stats.csum_good++; no_csum: /* populate Tx descriptor header size and mss */ tx_desc = FM10K_TX_DESC(tx_ring, tx_ring->next_to_use); tx_desc->hdrlen = 0; tx_desc->mss = 0; } #define FM10K_SET_FLAG(_input, _flag, _result) \ ((_flag <= _result) ? \ ((u32)(_input & _flag) * (_result / _flag)) : \ ((u32)(_input & _flag) / (_flag / _result))) static u8 fm10k_tx_desc_flags(struct sk_buff *skb, u32 tx_flags) { /* set type for advanced descriptor with frame checksum insertion */ u32 desc_flags = 0; /* set checksum offload bits */ desc_flags |= FM10K_SET_FLAG(tx_flags, FM10K_TX_FLAGS_CSUM, FM10K_TXD_FLAG_CSUM); return desc_flags; } static bool fm10k_tx_desc_push(struct fm10k_ring *tx_ring, struct fm10k_tx_desc *tx_desc, u16 i, dma_addr_t dma, unsigned int size, u8 desc_flags) { /* set RS and INT for last frame in a cache line */ if ((++i & (FM10K_TXD_WB_FIFO_SIZE - 1)) == 0) desc_flags |= FM10K_TXD_FLAG_RS | FM10K_TXD_FLAG_INT; /* record values to descriptor */ tx_desc->buffer_addr = cpu_to_le64(dma); tx_desc->flags = desc_flags; tx_desc->buflen = cpu_to_le16(size); /* return true if we just wrapped the ring */ return i == tx_ring->count; } static int __fm10k_maybe_stop_tx(struct fm10k_ring *tx_ring, u16 size) { netif_stop_subqueue(tx_ring->netdev, tx_ring->queue_index); /* Memory barrier before checking head and tail */ smp_mb(); /* Check again in a case another CPU has just made room available */ if (likely(fm10k_desc_unused(tx_ring) < size)) return -EBUSY; /* A reprieve! - use start_queue because it doesn't call schedule */ netif_start_subqueue(tx_ring->netdev, tx_ring->queue_index); ++tx_ring->tx_stats.restart_queue; return 0; } static inline int fm10k_maybe_stop_tx(struct fm10k_ring *tx_ring, u16 size) { if (likely(fm10k_desc_unused(tx_ring) >= size)) return 0; return __fm10k_maybe_stop_tx(tx_ring, size); } static void fm10k_tx_map(struct fm10k_ring *tx_ring, struct fm10k_tx_buffer *first) { struct sk_buff *skb = first->skb; struct fm10k_tx_buffer *tx_buffer; struct fm10k_tx_desc *tx_desc; skb_frag_t *frag; unsigned char *data; dma_addr_t dma; unsigned int data_len, size; u32 tx_flags = first->tx_flags; u16 i = tx_ring->next_to_use; u8 flags = fm10k_tx_desc_flags(skb, tx_flags); tx_desc = FM10K_TX_DESC(tx_ring, i); /* add HW VLAN tag */ if (skb_vlan_tag_present(skb)) tx_desc->vlan = cpu_to_le16(skb_vlan_tag_get(skb)); else tx_desc->vlan = 0; size = skb_headlen(skb); data = skb->data; dma = dma_map_single(tx_ring->dev, data, size, DMA_TO_DEVICE); data_len = skb->data_len; tx_buffer = first; for (frag = &skb_shinfo(skb)->frags[0];; frag++) { if (dma_mapping_error(tx_ring->dev, dma)) goto dma_error; /* record length, and DMA address */ dma_unmap_len_set(tx_buffer, len, size); dma_unmap_addr_set(tx_buffer, dma, dma); while (unlikely(size > FM10K_MAX_DATA_PER_TXD)) { if (fm10k_tx_desc_push(tx_ring, tx_desc++, i++, dma, FM10K_MAX_DATA_PER_TXD, flags)) { tx_desc = FM10K_TX_DESC(tx_ring, 0); i = 0; } dma += FM10K_MAX_DATA_PER_TXD; size -= FM10K_MAX_DATA_PER_TXD; } if (likely(!data_len)) break; if (fm10k_tx_desc_push(tx_ring, tx_desc++, i++, dma, size, flags)) { tx_desc = FM10K_TX_DESC(tx_ring, 0); i = 0; } size = skb_frag_size(frag); data_len -= size; dma = skb_frag_dma_map(tx_ring->dev, frag, 0, size, DMA_TO_DEVICE); tx_buffer = &tx_ring->tx_buffer[i]; } /* write last descriptor with LAST bit set */ flags |= FM10K_TXD_FLAG_LAST; if (fm10k_tx_desc_push(tx_ring, tx_desc, i++, dma, size, flags)) i = 0; /* record bytecount for BQL */ netdev_tx_sent_queue(txring_txq(tx_ring), first->bytecount); /* record SW timestamp if HW timestamp is not available */ skb_tx_timestamp(first->skb); /* Force memory writes to complete before letting h/w know there * are new descriptors to fetch. (Only applicable for weak-ordered * memory model archs, such as IA-64). * * We also need this memory barrier to make certain all of the * status bits have been updated before next_to_watch is written. */ wmb(); /* set next_to_watch value indicating a packet is present */ first->next_to_watch = tx_desc; tx_ring->next_to_use = i; /* Make sure there is space in the ring for the next send. */ fm10k_maybe_stop_tx(tx_ring, DESC_NEEDED); /* notify HW of packet */ if (netif_xmit_stopped(txring_txq(tx_ring)) || !netdev_xmit_more()) { writel(i, tx_ring->tail); } return; dma_error: dev_err(tx_ring->dev, "TX DMA map failed\n"); /* clear dma mappings for failed tx_buffer map */ for (;;) { tx_buffer = &tx_ring->tx_buffer[i]; fm10k_unmap_and_free_tx_resource(tx_ring, tx_buffer); if (tx_buffer == first) break; if (i == 0) i = tx_ring->count; i--; } tx_ring->next_to_use = i; } netdev_tx_t fm10k_xmit_frame_ring(struct sk_buff *skb, struct fm10k_ring *tx_ring) { u16 count = TXD_USE_COUNT(skb_headlen(skb)); struct fm10k_tx_buffer *first; unsigned short f; u32 tx_flags = 0; int tso; /* need: 1 descriptor per page * PAGE_SIZE/FM10K_MAX_DATA_PER_TXD, * + 1 desc for skb_headlen/FM10K_MAX_DATA_PER_TXD, * + 2 desc gap to keep tail from touching head * otherwise try next time */ for (f = 0; f < skb_shinfo(skb)->nr_frags; f++) { skb_frag_t *frag = &skb_shinfo(skb)->frags[f]; count += TXD_USE_COUNT(skb_frag_size(frag)); } if (fm10k_maybe_stop_tx(tx_ring, count + 3)) { tx_ring->tx_stats.tx_busy++; return NETDEV_TX_BUSY; } /* record the location of the first descriptor for this packet */ first = &tx_ring->tx_buffer[tx_ring->next_to_use]; first->skb = skb; first->bytecount = max_t(unsigned int, skb->len, ETH_ZLEN); first->gso_segs = 1; /* record initial flags and protocol */ first->tx_flags = tx_flags; tso = fm10k_tso(tx_ring, first); if (tso < 0) goto out_drop; else if (!tso) fm10k_tx_csum(tx_ring, first); fm10k_tx_map(tx_ring, first); return NETDEV_TX_OK; out_drop: dev_kfree_skb_any(first->skb); first->skb = NULL; return NETDEV_TX_OK; } static u64 fm10k_get_tx_completed(struct fm10k_ring *ring) { return ring->stats.packets; } /** * fm10k_get_tx_pending - how many Tx descriptors not processed * @ring: the ring structure * @in_sw: is tx_pending being checked in SW or in HW? */ u64 fm10k_get_tx_pending(struct fm10k_ring *ring, bool in_sw) { struct fm10k_intfc *interface = ring->q_vector->interface; struct fm10k_hw *hw = &interface->hw; u32 head, tail; if (likely(in_sw)) { head = ring->next_to_clean; tail = ring->next_to_use; } else { head = fm10k_read_reg(hw, FM10K_TDH(ring->reg_idx)); tail = fm10k_read_reg(hw, FM10K_TDT(ring->reg_idx)); } return ((head <= tail) ? tail : tail + ring->count) - head; } bool fm10k_check_tx_hang(struct fm10k_ring *tx_ring) { u32 tx_done = fm10k_get_tx_completed(tx_ring); u32 tx_done_old = tx_ring->tx_stats.tx_done_old; u32 tx_pending = fm10k_get_tx_pending(tx_ring, true); clear_check_for_tx_hang(tx_ring); /* Check for a hung queue, but be thorough. This verifies * that a transmit has been completed since the previous * check AND there is at least one packet pending. By * requiring this to fail twice we avoid races with * clearing the ARMED bit and conditions where we * run the check_tx_hang logic with a transmit completion * pending but without time to complete it yet. */ if (!tx_pending || (tx_done_old != tx_done)) { /* update completed stats and continue */ tx_ring->tx_stats.tx_done_old = tx_done; /* reset the countdown */ clear_bit(__FM10K_HANG_CHECK_ARMED, tx_ring->state); return false; } /* make sure it is true for two checks in a row */ return test_and_set_bit(__FM10K_HANG_CHECK_ARMED, tx_ring->state); } /** * fm10k_tx_timeout_reset - initiate reset due to Tx timeout * @interface: driver private struct **/ void fm10k_tx_timeout_reset(struct fm10k_intfc *interface) { /* Do the reset outside of interrupt context */ if (!test_bit(__FM10K_DOWN, interface->state)) { interface->tx_timeout_count++; set_bit(FM10K_FLAG_RESET_REQUESTED, interface->flags); fm10k_service_event_schedule(interface); } } /** * fm10k_clean_tx_irq - Reclaim resources after transmit completes * @q_vector: structure containing interrupt and ring information * @tx_ring: tx ring to clean * @napi_budget: Used to determine if we are in netpoll **/ static bool fm10k_clean_tx_irq(struct fm10k_q_vector *q_vector, struct fm10k_ring *tx_ring, int napi_budget) { struct fm10k_intfc *interface = q_vector->interface; struct fm10k_tx_buffer *tx_buffer; struct fm10k_tx_desc *tx_desc; unsigned int total_bytes = 0, total_packets = 0; unsigned int budget = q_vector->tx.work_limit; unsigned int i = tx_ring->next_to_clean; if (test_bit(__FM10K_DOWN, interface->state)) return true; tx_buffer = &tx_ring->tx_buffer[i]; tx_desc = FM10K_TX_DESC(tx_ring, i); i -= tx_ring->count; do { struct fm10k_tx_desc *eop_desc = tx_buffer->next_to_watch; /* if next_to_watch is not set then there is no work pending */ if (!eop_desc) break; /* prevent any other reads prior to eop_desc */ smp_rmb(); /* if DD is not set pending work has not been completed */ if (!(eop_desc->flags & FM10K_TXD_FLAG_DONE)) break; /* clear next_to_watch to prevent false hangs */ tx_buffer->next_to_watch = NULL; /* update the statistics for this packet */ total_bytes += tx_buffer->bytecount; total_packets += tx_buffer->gso_segs; /* free the skb */ napi_consume_skb(tx_buffer->skb, napi_budget); /* unmap skb header data */ dma_unmap_single(tx_ring->dev, dma_unmap_addr(tx_buffer, dma), dma_unmap_len(tx_buffer, len), DMA_TO_DEVICE); /* clear tx_buffer data */ tx_buffer->skb = NULL; dma_unmap_len_set(tx_buffer, len, 0); /* unmap remaining buffers */ while (tx_desc != eop_desc) { tx_buffer++; tx_desc++; i++; if (unlikely(!i)) { i -= tx_ring->count; tx_buffer = tx_ring->tx_buffer; tx_desc = FM10K_TX_DESC(tx_ring, 0); } /* unmap any remaining paged data */ if (dma_unmap_len(tx_buffer, len)) { dma_unmap_page(tx_ring->dev, dma_unmap_addr(tx_buffer, dma), dma_unmap_len(tx_buffer, len), DMA_TO_DEVICE); dma_unmap_len_set(tx_buffer, len, 0); } } /* move us one more past the eop_desc for start of next pkt */ tx_buffer++; tx_desc++; i++; if (unlikely(!i)) { i -= tx_ring->count; tx_buffer = tx_ring->tx_buffer; tx_desc = FM10K_TX_DESC(tx_ring, 0); } /* issue prefetch for next Tx descriptor */ prefetch(tx_desc); /* update budget accounting */ budget--; } while (likely(budget)); i += tx_ring->count; tx_ring->next_to_clean = i; u64_stats_update_begin(&tx_ring->syncp); tx_ring->stats.bytes += total_bytes; tx_ring->stats.packets += total_packets; u64_stats_update_end(&tx_ring->syncp); q_vector->tx.total_bytes += total_bytes; q_vector->tx.total_packets += total_packets; if (check_for_tx_hang(tx_ring) && fm10k_check_tx_hang(tx_ring)) { /* schedule immediate reset if we believe we hung */ struct fm10k_hw *hw = &interface->hw; netif_err(interface, drv, tx_ring->netdev, "Detected Tx Unit Hang\n" " Tx Queue <%d>\n" " TDH, TDT <%x>, <%x>\n" " next_to_use <%x>\n" " next_to_clean <%x>\n", tx_ring->queue_index, fm10k_read_reg(hw, FM10K_TDH(tx_ring->reg_idx)), fm10k_read_reg(hw, FM10K_TDT(tx_ring->reg_idx)), tx_ring->next_to_use, i); netif_stop_subqueue(tx_ring->netdev, tx_ring->queue_index); netif_info(interface, probe, tx_ring->netdev, "tx hang %d detected on queue %d, resetting interface\n", interface->tx_timeout_count + 1, tx_ring->queue_index); fm10k_tx_timeout_reset(interface); /* the netdev is about to reset, no point in enabling stuff */ return true; } /* notify netdev of completed buffers */ netdev_tx_completed_queue(txring_txq(tx_ring), total_packets, total_bytes); #define TX_WAKE_THRESHOLD min_t(u16, FM10K_MIN_TXD - 1, DESC_NEEDED * 2) if (unlikely(total_packets && netif_carrier_ok(tx_ring->netdev) && (fm10k_desc_unused(tx_ring) >= TX_WAKE_THRESHOLD))) { /* Make sure that anybody stopping the queue after this * sees the new next_to_clean. */ smp_mb(); if (__netif_subqueue_stopped(tx_ring->netdev, tx_ring->queue_index) && !test_bit(__FM10K_DOWN, interface->state)) { netif_wake_subqueue(tx_ring->netdev, tx_ring->queue_index); ++tx_ring->tx_stats.restart_queue; } } return !!budget; } /** * fm10k_update_itr - update the dynamic ITR value based on packet size * * Stores a new ITR value based on strictly on packet size. The * divisors and thresholds used by this function were determined based * on theoretical maximum wire speed and testing data, in order to * minimize response time while increasing bulk throughput. * * @ring_container: Container for rings to have ITR updated **/ static void fm10k_update_itr(struct fm10k_ring_container *ring_container) { unsigned int avg_wire_size, packets, itr_round; /* Only update ITR if we are using adaptive setting */ if (!ITR_IS_ADAPTIVE(ring_container->itr)) goto clear_counts; packets = ring_container->total_packets; if (!packets) goto clear_counts; avg_wire_size = ring_container->total_bytes / packets; /* The following is a crude approximation of: * wmem_default / (size + overhead) = desired_pkts_per_int * rate / bits_per_byte / (size + ethernet overhead) = pkt_rate * (desired_pkt_rate / pkt_rate) * usecs_per_sec = ITR value * * Assuming wmem_default is 212992 and overhead is 640 bytes per * packet, (256 skb, 64 headroom, 320 shared info), we can reduce the * formula down to * * (34 * (size + 24)) / (size + 640) = ITR * * We first do some math on the packet size and then finally bitshift * by 8 after rounding up. We also have to account for PCIe link speed * difference as ITR scales based on this. */ if (avg_wire_size <= 360) { /* Start at 250K ints/sec and gradually drop to 77K ints/sec */ avg_wire_size *= 8; avg_wire_size += 376; } else if (avg_wire_size <= 1152) { /* 77K ints/sec to 45K ints/sec */ avg_wire_size *= 3; avg_wire_size += 2176; } else if (avg_wire_size <= 1920) { /* 45K ints/sec to 38K ints/sec */ avg_wire_size += 4480; } else { /* plateau at a limit of 38K ints/sec */ avg_wire_size = 6656; } /* Perform final bitshift for division after rounding up to ensure * that the calculation will never get below a 1. The bit shift * accounts for changes in the ITR due to PCIe link speed. */ itr_round = READ_ONCE(ring_container->itr_scale) + 8; avg_wire_size += BIT(itr_round) - 1; avg_wire_size >>= itr_round; /* write back value and retain adaptive flag */ ring_container->itr = avg_wire_size | FM10K_ITR_ADAPTIVE; clear_counts: ring_container->total_bytes = 0; ring_container->total_packets = 0; } static void fm10k_qv_enable(struct fm10k_q_vector *q_vector) { /* Enable auto-mask and clear the current mask */ u32 itr = FM10K_ITR_ENABLE; /* Update Tx ITR */ fm10k_update_itr(&q_vector->tx); /* Update Rx ITR */ fm10k_update_itr(&q_vector->rx); /* Store Tx itr in timer slot 0 */ itr |= (q_vector->tx.itr & FM10K_ITR_MAX); /* Shift Rx itr to timer slot 1 */ itr |= (q_vector->rx.itr & FM10K_ITR_MAX) << FM10K_ITR_INTERVAL1_SHIFT; /* Write the final value to the ITR register */ writel(itr, q_vector->itr); } static int fm10k_poll(struct napi_struct *napi, int budget) { struct fm10k_q_vector *q_vector = container_of(napi, struct fm10k_q_vector, napi); struct fm10k_ring *ring; int per_ring_budget, work_done = 0; bool clean_complete = true; fm10k_for_each_ring(ring, q_vector->tx) { if (!fm10k_clean_tx_irq(q_vector, ring, budget)) clean_complete = false; } /* Handle case where we are called by netpoll with a budget of 0 */ if (budget <= 0) return budget; /* attempt to distribute budget to each queue fairly, but don't * allow the budget to go below 1 because we'll exit polling */ if (q_vector->rx.count > 1) per_ring_budget = max(budget / q_vector->rx.count, 1); else per_ring_budget = budget; fm10k_for_each_ring(ring, q_vector->rx) { int work = fm10k_clean_rx_irq(q_vector, ring, per_ring_budget); work_done += work; if (work >= per_ring_budget) clean_complete = false; } /* If all work not completed, return budget and keep polling */ if (!clean_complete) return budget; /* Exit the polling mode, but don't re-enable interrupts if stack might * poll us due to busy-polling */ if (likely(napi_complete_done(napi, work_done))) fm10k_qv_enable(q_vector); return min(work_done, budget - 1); } /** * fm10k_set_qos_queues: Allocate queues for a QOS-enabled device * @interface: board private structure to initialize * * When QoS (Quality of Service) is enabled, allocate queues for * each traffic class. If multiqueue isn't available,then abort QoS * initialization. * * This function handles all combinations of Qos and RSS. * **/ static bool fm10k_set_qos_queues(struct fm10k_intfc *interface) { struct net_device *dev = interface->netdev; struct fm10k_ring_feature *f; int rss_i, i; int pcs; /* Map queue offset and counts onto allocated tx queues */ pcs = netdev_get_num_tc(dev); if (pcs <= 1) return false; /* set QoS mask and indices */ f = &interface->ring_feature[RING_F_QOS]; f->indices = pcs; f->mask = BIT(fls(pcs - 1)) - 1; /* determine the upper limit for our current DCB mode */ rss_i = interface->hw.mac.max_queues / pcs; rss_i = BIT(fls(rss_i) - 1); /* set RSS mask and indices */ f = &interface->ring_feature[RING_F_RSS]; rss_i = min_t(u16, rss_i, f->limit); f->indices = rss_i; f->mask = BIT(fls(rss_i - 1)) - 1; /* configure pause class to queue mapping */ for (i = 0; i < pcs; i++) netdev_set_tc_queue(dev, i, rss_i, rss_i * i); interface->num_rx_queues = rss_i * pcs; interface->num_tx_queues = rss_i * pcs; return true; } /** * fm10k_set_rss_queues: Allocate queues for RSS * @interface: board private structure to initialize * * This is our "base" multiqueue mode. RSS (Receive Side Scaling) will try * to allocate one Rx queue per CPU, and if available, one Tx queue per CPU. * **/ static bool fm10k_set_rss_queues(struct fm10k_intfc *interface) { struct fm10k_ring_feature *f; u16 rss_i; f = &interface->ring_feature[RING_F_RSS]; rss_i = min_t(u16, interface->hw.mac.max_queues, f->limit); /* record indices and power of 2 mask for RSS */ f->indices = rss_i; f->mask = BIT(fls(rss_i - 1)) - 1; interface->num_rx_queues = rss_i; interface->num_tx_queues = rss_i; return true; } /** * fm10k_set_num_queues: Allocate queues for device, feature dependent * @interface: board private structure to initialize * * This is the top level queue allocation routine. The order here is very * important, starting with the "most" number of features turned on at once, * and ending with the smallest set of features. This way large combinations * can be allocated if they're turned on, and smaller combinations are the * fall through conditions. * **/ static void fm10k_set_num_queues(struct fm10k_intfc *interface) { /* Attempt to setup QoS and RSS first */ if (fm10k_set_qos_queues(interface)) return; /* If we don't have QoS, just fallback to only RSS. */ fm10k_set_rss_queues(interface); } /** * fm10k_reset_num_queues - Reset the number of queues to zero * @interface: board private structure * * This function should be called whenever we need to reset the number of * queues after an error condition. */ static void fm10k_reset_num_queues(struct fm10k_intfc *interface) { interface->num_tx_queues = 0; interface->num_rx_queues = 0; interface->num_q_vectors = 0; } /** * fm10k_alloc_q_vector - Allocate memory for a single interrupt vector * @interface: board private structure to initialize * @v_count: q_vectors allocated on interface, used for ring interleaving * @v_idx: index of vector in interface struct * @txr_count: total number of Tx rings to allocate * @txr_idx: index of first Tx ring to allocate * @rxr_count: total number of Rx rings to allocate * @rxr_idx: index of first Rx ring to allocate * * We allocate one q_vector. If allocation fails we return -ENOMEM. **/ static int fm10k_alloc_q_vector(struct fm10k_intfc *interface, unsigned int v_count, unsigned int v_idx, unsigned int txr_count, unsigned int txr_idx, unsigned int rxr_count, unsigned int rxr_idx) { struct fm10k_q_vector *q_vector; struct fm10k_ring *ring; int ring_count; ring_count = txr_count + rxr_count; /* allocate q_vector and rings */ q_vector = kzalloc(struct_size(q_vector, ring, ring_count), GFP_KERNEL); if (!q_vector) return -ENOMEM; /* initialize NAPI */ netif_napi_add(interface->netdev, &q_vector->napi, fm10k_poll); /* tie q_vector and interface together */ interface->q_vector[v_idx] = q_vector; q_vector->interface = interface; q_vector->v_idx = v_idx; /* initialize pointer to rings */ ring = q_vector->ring; /* save Tx ring container info */ q_vector->tx.ring = ring; q_vector->tx.work_limit = FM10K_DEFAULT_TX_WORK; q_vector->tx.itr = interface->tx_itr; q_vector->tx.itr_scale = interface->hw.mac.itr_scale; q_vector->tx.count = txr_count; while (txr_count) { /* assign generic ring traits */ ring->dev = &interface->pdev->dev; ring->netdev = interface->netdev; /* configure backlink on ring */ ring->q_vector = q_vector; /* apply Tx specific ring traits */ ring->count = interface->tx_ring_count; ring->queue_index = txr_idx; /* assign ring to interface */ interface->tx_ring[txr_idx] = ring; /* update count and index */ txr_count--; txr_idx += v_count; /* push pointer to next ring */ ring++; } /* save Rx ring container info */ q_vector->rx.ring = ring; q_vector->rx.itr = interface->rx_itr; q_vector->rx.itr_scale = interface->hw.mac.itr_scale; q_vector->rx.count = rxr_count; while (rxr_count) { /* assign generic ring traits */ ring->dev = &interface->pdev->dev; ring->netdev = interface->netdev; rcu_assign_pointer(ring->l2_accel, interface->l2_accel); /* configure backlink on ring */ ring->q_vector = q_vector; /* apply Rx specific ring traits */ ring->count = interface->rx_ring_count; ring->queue_index = rxr_idx; /* assign ring to interface */ interface->rx_ring[rxr_idx] = ring; /* update count and index */ rxr_count--; rxr_idx += v_count; /* push pointer to next ring */ ring++; } fm10k_dbg_q_vector_init(q_vector); return 0; } /** * fm10k_free_q_vector - Free memory allocated for specific interrupt vector * @interface: board private structure to initialize * @v_idx: Index of vector to be freed * * This function frees the memory allocated to the q_vector. In addition if * NAPI is enabled it will delete any references to the NAPI struct prior * to freeing the q_vector. **/ static void fm10k_free_q_vector(struct fm10k_intfc *interface, int v_idx) { struct fm10k_q_vector *q_vector = interface->q_vector[v_idx]; struct fm10k_ring *ring; fm10k_dbg_q_vector_exit(q_vector); fm10k_for_each_ring(ring, q_vector->tx) interface->tx_ring[ring->queue_index] = NULL; fm10k_for_each_ring(ring, q_vector->rx) interface->rx_ring[ring->queue_index] = NULL; interface->q_vector[v_idx] = NULL; netif_napi_del(&q_vector->napi); kfree_rcu(q_vector, rcu); } /** * fm10k_alloc_q_vectors - Allocate memory for interrupt vectors * @interface: board private structure to initialize * * We allocate one q_vector per queue interrupt. If allocation fails we * return -ENOMEM. **/ static int fm10k_alloc_q_vectors(struct fm10k_intfc *interface) { unsigned int q_vectors = interface->num_q_vectors; unsigned int rxr_remaining = interface->num_rx_queues; unsigned int txr_remaining = interface->num_tx_queues; unsigned int rxr_idx = 0, txr_idx = 0, v_idx = 0; int err; if (q_vectors >= (rxr_remaining + txr_remaining)) { for (; rxr_remaining; v_idx++) { err = fm10k_alloc_q_vector(interface, q_vectors, v_idx, 0, 0, 1, rxr_idx); if (err) goto err_out; /* update counts and index */ rxr_remaining--; rxr_idx++; } } for (; v_idx < q_vectors; v_idx++) { int rqpv = DIV_ROUND_UP(rxr_remaining, q_vectors - v_idx); int tqpv = DIV_ROUND_UP(txr_remaining, q_vectors - v_idx); err = fm10k_alloc_q_vector(interface, q_vectors, v_idx, tqpv, txr_idx, rqpv, rxr_idx); if (err) goto err_out; /* update counts and index */ rxr_remaining -= rqpv; txr_remaining -= tqpv; rxr_idx++; txr_idx++; } return 0; err_out: fm10k_reset_num_queues(interface); while (v_idx--) fm10k_free_q_vector(interface, v_idx); return -ENOMEM; } /** * fm10k_free_q_vectors - Free memory allocated for interrupt vectors * @interface: board private structure to initialize * * This function frees the memory allocated to the q_vectors. In addition if * NAPI is enabled it will delete any references to the NAPI struct prior * to freeing the q_vector. **/ static void fm10k_free_q_vectors(struct fm10k_intfc *interface) { int v_idx = interface->num_q_vectors; fm10k_reset_num_queues(interface); while (v_idx--) fm10k_free_q_vector(interface, v_idx); } /** * fm10k_reset_msix_capability - reset MSI-X capability * @interface: board private structure to initialize * * Reset the MSI-X capability back to its starting state **/ static void fm10k_reset_msix_capability(struct fm10k_intfc *interface) { pci_disable_msix(interface->pdev); kfree(interface->msix_entries); interface->msix_entries = NULL; } /** * fm10k_init_msix_capability - configure MSI-X capability * @interface: board private structure to initialize * * Attempt to configure the interrupts using the best available * capabilities of the hardware and the kernel. **/ static int fm10k_init_msix_capability(struct fm10k_intfc *interface) { struct fm10k_hw *hw = &interface->hw; int v_budget, vector; /* It's easy to be greedy for MSI-X vectors, but it really * doesn't do us much good if we have a lot more vectors * than CPU's. So let's be conservative and only ask for * (roughly) the same number of vectors as there are CPU's. * the default is to use pairs of vectors */ v_budget = max(interface->num_rx_queues, interface->num_tx_queues); v_budget = min_t(u16, v_budget, num_online_cpus()); /* account for vectors not related to queues */ v_budget += NON_Q_VECTORS; /* At the same time, hardware can only support a maximum of * hw.mac->max_msix_vectors vectors. With features * such as RSS and VMDq, we can easily surpass the number of Rx and Tx * descriptor queues supported by our device. Thus, we cap it off in * those rare cases where the cpu count also exceeds our vector limit. */ v_budget = min_t(int, v_budget, hw->mac.max_msix_vectors); /* A failure in MSI-X entry allocation is fatal. */ interface->msix_entries = kcalloc(v_budget, sizeof(struct msix_entry), GFP_KERNEL); if (!interface->msix_entries) return -ENOMEM; /* populate entry values */ for (vector = 0; vector < v_budget; vector++) interface->msix_entries[vector].entry = vector; /* Attempt to enable MSI-X with requested value */ v_budget = pci_enable_msix_range(interface->pdev, interface->msix_entries, MIN_MSIX_COUNT(hw), v_budget); if (v_budget < 0) { kfree(interface->msix_entries); interface->msix_entries = NULL; return v_budget; } /* record the number of queues available for q_vectors */ interface->num_q_vectors = v_budget - NON_Q_VECTORS; return 0; } /** * fm10k_cache_ring_qos - Descriptor ring to register mapping for QoS * @interface: Interface structure continaining rings and devices * * Cache the descriptor ring offsets for Qos **/ static bool fm10k_cache_ring_qos(struct fm10k_intfc *interface) { struct net_device *dev = interface->netdev; int pc, offset, rss_i, i; u16 pc_stride = interface->ring_feature[RING_F_QOS].mask + 1; u8 num_pcs = netdev_get_num_tc(dev); if (num_pcs <= 1) return false; rss_i = interface->ring_feature[RING_F_RSS].indices; for (pc = 0, offset = 0; pc < num_pcs; pc++, offset += rss_i) { int q_idx = pc; for (i = 0; i < rss_i; i++) { interface->tx_ring[offset + i]->reg_idx = q_idx; interface->tx_ring[offset + i]->qos_pc = pc; interface->rx_ring[offset + i]->reg_idx = q_idx; interface->rx_ring[offset + i]->qos_pc = pc; q_idx += pc_stride; } } return true; } /** * fm10k_cache_ring_rss - Descriptor ring to register mapping for RSS * @interface: Interface structure continaining rings and devices * * Cache the descriptor ring offsets for RSS **/ static void fm10k_cache_ring_rss(struct fm10k_intfc *interface) { int i; for (i = 0; i < interface->num_rx_queues; i++) interface->rx_ring[i]->reg_idx = i; for (i = 0; i < interface->num_tx_queues; i++) interface->tx_ring[i]->reg_idx = i; } /** * fm10k_assign_rings - Map rings to network devices * @interface: Interface structure containing rings and devices * * This function is meant to go though and configure both the network * devices so that they contain rings, and configure the rings so that * they function with their network devices. **/ static void fm10k_assign_rings(struct fm10k_intfc *interface) { if (fm10k_cache_ring_qos(interface)) return; fm10k_cache_ring_rss(interface); } static void fm10k_init_reta(struct fm10k_intfc *interface) { u16 i, rss_i = interface->ring_feature[RING_F_RSS].indices; u32 reta; /* If the Rx flow indirection table has been configured manually, we * need to maintain it when possible. */ if (netif_is_rxfh_configured(interface->netdev)) { for (i = FM10K_RETA_SIZE; i--;) { reta = interface->reta[i]; if ((((reta << 24) >> 24) < rss_i) && (((reta << 16) >> 24) < rss_i) && (((reta << 8) >> 24) < rss_i) && (((reta) >> 24) < rss_i)) continue; /* this should never happen */ dev_err(&interface->pdev->dev, "RSS indirection table assigned flows out of queue bounds. Reconfiguring.\n"); goto repopulate_reta; } /* do nothing if all of the elements are in bounds */ return; } repopulate_reta: fm10k_write_reta(interface, NULL); } /** * fm10k_init_queueing_scheme - Determine proper queueing scheme * @interface: board private structure to initialize * * We determine which queueing scheme to use based on... * - Hardware queue count (num_*_queues) * - defined by miscellaneous hardware support/features (RSS, etc.) **/ int fm10k_init_queueing_scheme(struct fm10k_intfc *interface) { int err; /* Number of supported queues */ fm10k_set_num_queues(interface); /* Configure MSI-X capability */ err = fm10k_init_msix_capability(interface); if (err) { dev_err(&interface->pdev->dev, "Unable to initialize MSI-X capability\n"); goto err_init_msix; } /* Allocate memory for queues */ err = fm10k_alloc_q_vectors(interface); if (err) { dev_err(&interface->pdev->dev, "Unable to allocate queue vectors\n"); goto err_alloc_q_vectors; } /* Map rings to devices, and map devices to physical queues */ fm10k_assign_rings(interface); /* Initialize RSS redirection table */ fm10k_init_reta(interface); return 0; err_alloc_q_vectors: fm10k_reset_msix_capability(interface); err_init_msix: fm10k_reset_num_queues(interface); return err; } /** * fm10k_clear_queueing_scheme - Clear the current queueing scheme settings * @interface: board private structure to clear queueing scheme on * * We go through and clear queueing specific resources and reset the structure * to pre-load conditions **/ void fm10k_clear_queueing_scheme(struct fm10k_intfc *interface) { fm10k_free_q_vectors(interface); fm10k_reset_msix_capability(interface); }
linux-master
drivers/net/ethernet/intel/fm10k/fm10k_main.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 1999 - 2006 Intel Corporation. */ /* e1000_hw.c * Shared functions for accessing and configuring the MAC */ #include "e1000.h" static s32 e1000_check_downshift(struct e1000_hw *hw); static s32 e1000_check_polarity(struct e1000_hw *hw, e1000_rev_polarity *polarity); static void e1000_clear_hw_cntrs(struct e1000_hw *hw); static void e1000_clear_vfta(struct e1000_hw *hw); static s32 e1000_config_dsp_after_link_change(struct e1000_hw *hw, bool link_up); static s32 e1000_config_fc_after_link_up(struct e1000_hw *hw); static s32 e1000_detect_gig_phy(struct e1000_hw *hw); static s32 e1000_get_auto_rd_done(struct e1000_hw *hw); static s32 e1000_get_cable_length(struct e1000_hw *hw, u16 *min_length, u16 *max_length); static s32 e1000_get_phy_cfg_done(struct e1000_hw *hw); static s32 e1000_id_led_init(struct e1000_hw *hw); static void e1000_init_rx_addrs(struct e1000_hw *hw); static s32 e1000_phy_igp_get_info(struct e1000_hw *hw, struct e1000_phy_info *phy_info); static s32 e1000_phy_m88_get_info(struct e1000_hw *hw, struct e1000_phy_info *phy_info); static s32 e1000_set_d3_lplu_state(struct e1000_hw *hw, bool active); static s32 e1000_wait_autoneg(struct e1000_hw *hw); static void e1000_write_reg_io(struct e1000_hw *hw, u32 offset, u32 value); static s32 e1000_set_phy_type(struct e1000_hw *hw); static void e1000_phy_init_script(struct e1000_hw *hw); static s32 e1000_setup_copper_link(struct e1000_hw *hw); static s32 e1000_setup_fiber_serdes_link(struct e1000_hw *hw); static s32 e1000_adjust_serdes_amplitude(struct e1000_hw *hw); static s32 e1000_phy_force_speed_duplex(struct e1000_hw *hw); static s32 e1000_config_mac_to_phy(struct e1000_hw *hw); static void e1000_raise_mdi_clk(struct e1000_hw *hw, u32 *ctrl); static void e1000_lower_mdi_clk(struct e1000_hw *hw, u32 *ctrl); static void e1000_shift_out_mdi_bits(struct e1000_hw *hw, u32 data, u16 count); static u16 e1000_shift_in_mdi_bits(struct e1000_hw *hw); static s32 e1000_phy_reset_dsp(struct e1000_hw *hw); static s32 e1000_write_eeprom_spi(struct e1000_hw *hw, u16 offset, u16 words, u16 *data); static s32 e1000_write_eeprom_microwire(struct e1000_hw *hw, u16 offset, u16 words, u16 *data); static s32 e1000_spi_eeprom_ready(struct e1000_hw *hw); static void e1000_raise_ee_clk(struct e1000_hw *hw, u32 *eecd); static void e1000_lower_ee_clk(struct e1000_hw *hw, u32 *eecd); static void e1000_shift_out_ee_bits(struct e1000_hw *hw, u16 data, u16 count); static s32 e1000_write_phy_reg_ex(struct e1000_hw *hw, u32 reg_addr, u16 phy_data); static s32 e1000_read_phy_reg_ex(struct e1000_hw *hw, u32 reg_addr, u16 *phy_data); static u16 e1000_shift_in_ee_bits(struct e1000_hw *hw, u16 count); static s32 e1000_acquire_eeprom(struct e1000_hw *hw); static void e1000_release_eeprom(struct e1000_hw *hw); static void e1000_standby_eeprom(struct e1000_hw *hw); static s32 e1000_set_vco_speed(struct e1000_hw *hw); static s32 e1000_polarity_reversal_workaround(struct e1000_hw *hw); static s32 e1000_set_phy_mode(struct e1000_hw *hw); static s32 e1000_do_read_eeprom(struct e1000_hw *hw, u16 offset, u16 words, u16 *data); static s32 e1000_do_write_eeprom(struct e1000_hw *hw, u16 offset, u16 words, u16 *data); /* IGP cable length table */ static const u16 e1000_igp_cable_length_table[IGP01E1000_AGC_LENGTH_TABLE_SIZE] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 10, 10, 10, 10, 10, 10, 10, 20, 20, 20, 20, 20, 25, 25, 25, 25, 25, 25, 25, 30, 30, 30, 30, 40, 40, 40, 40, 40, 40, 40, 40, 40, 50, 50, 50, 50, 50, 50, 50, 60, 60, 60, 60, 60, 60, 60, 60, 60, 70, 70, 70, 70, 70, 70, 80, 80, 80, 80, 80, 80, 90, 90, 90, 90, 90, 90, 90, 90, 90, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120 }; static DEFINE_MUTEX(e1000_eeprom_lock); static DEFINE_SPINLOCK(e1000_phy_lock); /** * e1000_set_phy_type - Set the phy type member in the hw struct. * @hw: Struct containing variables accessed by shared code */ static s32 e1000_set_phy_type(struct e1000_hw *hw) { if (hw->mac_type == e1000_undefined) return -E1000_ERR_PHY_TYPE; switch (hw->phy_id) { case M88E1000_E_PHY_ID: case M88E1000_I_PHY_ID: case M88E1011_I_PHY_ID: case M88E1111_I_PHY_ID: case M88E1118_E_PHY_ID: hw->phy_type = e1000_phy_m88; break; case IGP01E1000_I_PHY_ID: if (hw->mac_type == e1000_82541 || hw->mac_type == e1000_82541_rev_2 || hw->mac_type == e1000_82547 || hw->mac_type == e1000_82547_rev_2) hw->phy_type = e1000_phy_igp; break; case RTL8211B_PHY_ID: hw->phy_type = e1000_phy_8211; break; case RTL8201N_PHY_ID: hw->phy_type = e1000_phy_8201; break; default: /* Should never have loaded on this device */ hw->phy_type = e1000_phy_undefined; return -E1000_ERR_PHY_TYPE; } return E1000_SUCCESS; } /** * e1000_phy_init_script - IGP phy init script - initializes the GbE PHY * @hw: Struct containing variables accessed by shared code */ static void e1000_phy_init_script(struct e1000_hw *hw) { u16 phy_saved_data; if (hw->phy_init_script) { msleep(20); /* Save off the current value of register 0x2F5B to be restored * at the end of this routine. */ e1000_read_phy_reg(hw, 0x2F5B, &phy_saved_data); /* Disabled the PHY transmitter */ e1000_write_phy_reg(hw, 0x2F5B, 0x0003); msleep(20); e1000_write_phy_reg(hw, 0x0000, 0x0140); msleep(5); switch (hw->mac_type) { case e1000_82541: case e1000_82547: e1000_write_phy_reg(hw, 0x1F95, 0x0001); e1000_write_phy_reg(hw, 0x1F71, 0xBD21); e1000_write_phy_reg(hw, 0x1F79, 0x0018); e1000_write_phy_reg(hw, 0x1F30, 0x1600); e1000_write_phy_reg(hw, 0x1F31, 0x0014); e1000_write_phy_reg(hw, 0x1F32, 0x161C); e1000_write_phy_reg(hw, 0x1F94, 0x0003); e1000_write_phy_reg(hw, 0x1F96, 0x003F); e1000_write_phy_reg(hw, 0x2010, 0x0008); break; case e1000_82541_rev_2: case e1000_82547_rev_2: e1000_write_phy_reg(hw, 0x1F73, 0x0099); break; default: break; } e1000_write_phy_reg(hw, 0x0000, 0x3300); msleep(20); /* Now enable the transmitter */ e1000_write_phy_reg(hw, 0x2F5B, phy_saved_data); if (hw->mac_type == e1000_82547) { u16 fused, fine, coarse; /* Move to analog registers page */ e1000_read_phy_reg(hw, IGP01E1000_ANALOG_SPARE_FUSE_STATUS, &fused); if (!(fused & IGP01E1000_ANALOG_SPARE_FUSE_ENABLED)) { e1000_read_phy_reg(hw, IGP01E1000_ANALOG_FUSE_STATUS, &fused); fine = fused & IGP01E1000_ANALOG_FUSE_FINE_MASK; coarse = fused & IGP01E1000_ANALOG_FUSE_COARSE_MASK; if (coarse > IGP01E1000_ANALOG_FUSE_COARSE_THRESH) { coarse -= IGP01E1000_ANALOG_FUSE_COARSE_10; fine -= IGP01E1000_ANALOG_FUSE_FINE_1; } else if (coarse == IGP01E1000_ANALOG_FUSE_COARSE_THRESH) fine -= IGP01E1000_ANALOG_FUSE_FINE_10; fused = (fused & IGP01E1000_ANALOG_FUSE_POLY_MASK) | (fine & IGP01E1000_ANALOG_FUSE_FINE_MASK) | (coarse & IGP01E1000_ANALOG_FUSE_COARSE_MASK); e1000_write_phy_reg(hw, IGP01E1000_ANALOG_FUSE_CONTROL, fused); e1000_write_phy_reg(hw, IGP01E1000_ANALOG_FUSE_BYPASS, IGP01E1000_ANALOG_FUSE_ENABLE_SW_CONTROL); } } } } /** * e1000_set_mac_type - Set the mac type member in the hw struct. * @hw: Struct containing variables accessed by shared code */ s32 e1000_set_mac_type(struct e1000_hw *hw) { switch (hw->device_id) { case E1000_DEV_ID_82542: switch (hw->revision_id) { case E1000_82542_2_0_REV_ID: hw->mac_type = e1000_82542_rev2_0; break; case E1000_82542_2_1_REV_ID: hw->mac_type = e1000_82542_rev2_1; break; default: /* Invalid 82542 revision ID */ return -E1000_ERR_MAC_TYPE; } break; case E1000_DEV_ID_82543GC_FIBER: case E1000_DEV_ID_82543GC_COPPER: hw->mac_type = e1000_82543; break; case E1000_DEV_ID_82544EI_COPPER: case E1000_DEV_ID_82544EI_FIBER: case E1000_DEV_ID_82544GC_COPPER: case E1000_DEV_ID_82544GC_LOM: hw->mac_type = e1000_82544; break; case E1000_DEV_ID_82540EM: case E1000_DEV_ID_82540EM_LOM: case E1000_DEV_ID_82540EP: case E1000_DEV_ID_82540EP_LOM: case E1000_DEV_ID_82540EP_LP: hw->mac_type = e1000_82540; break; case E1000_DEV_ID_82545EM_COPPER: case E1000_DEV_ID_82545EM_FIBER: hw->mac_type = e1000_82545; break; case E1000_DEV_ID_82545GM_COPPER: case E1000_DEV_ID_82545GM_FIBER: case E1000_DEV_ID_82545GM_SERDES: hw->mac_type = e1000_82545_rev_3; break; case E1000_DEV_ID_82546EB_COPPER: case E1000_DEV_ID_82546EB_FIBER: case E1000_DEV_ID_82546EB_QUAD_COPPER: hw->mac_type = e1000_82546; break; case E1000_DEV_ID_82546GB_COPPER: case E1000_DEV_ID_82546GB_FIBER: case E1000_DEV_ID_82546GB_SERDES: case E1000_DEV_ID_82546GB_PCIE: case E1000_DEV_ID_82546GB_QUAD_COPPER: case E1000_DEV_ID_82546GB_QUAD_COPPER_KSP3: hw->mac_type = e1000_82546_rev_3; break; case E1000_DEV_ID_82541EI: case E1000_DEV_ID_82541EI_MOBILE: case E1000_DEV_ID_82541ER_LOM: hw->mac_type = e1000_82541; break; case E1000_DEV_ID_82541ER: case E1000_DEV_ID_82541GI: case E1000_DEV_ID_82541GI_LF: case E1000_DEV_ID_82541GI_MOBILE: hw->mac_type = e1000_82541_rev_2; break; case E1000_DEV_ID_82547EI: case E1000_DEV_ID_82547EI_MOBILE: hw->mac_type = e1000_82547; break; case E1000_DEV_ID_82547GI: hw->mac_type = e1000_82547_rev_2; break; case E1000_DEV_ID_INTEL_CE4100_GBE: hw->mac_type = e1000_ce4100; break; default: /* Should never have loaded on this device */ return -E1000_ERR_MAC_TYPE; } switch (hw->mac_type) { case e1000_82541: case e1000_82547: case e1000_82541_rev_2: case e1000_82547_rev_2: hw->asf_firmware_present = true; break; default: break; } /* The 82543 chip does not count tx_carrier_errors properly in * FD mode */ if (hw->mac_type == e1000_82543) hw->bad_tx_carr_stats_fd = true; if (hw->mac_type > e1000_82544) hw->has_smbus = true; return E1000_SUCCESS; } /** * e1000_set_media_type - Set media type and TBI compatibility. * @hw: Struct containing variables accessed by shared code */ void e1000_set_media_type(struct e1000_hw *hw) { u32 status; if (hw->mac_type != e1000_82543) { /* tbi_compatibility is only valid on 82543 */ hw->tbi_compatibility_en = false; } switch (hw->device_id) { case E1000_DEV_ID_82545GM_SERDES: case E1000_DEV_ID_82546GB_SERDES: hw->media_type = e1000_media_type_internal_serdes; break; default: switch (hw->mac_type) { case e1000_82542_rev2_0: case e1000_82542_rev2_1: hw->media_type = e1000_media_type_fiber; break; case e1000_ce4100: hw->media_type = e1000_media_type_copper; break; default: status = er32(STATUS); if (status & E1000_STATUS_TBIMODE) { hw->media_type = e1000_media_type_fiber; /* tbi_compatibility not valid on fiber */ hw->tbi_compatibility_en = false; } else { hw->media_type = e1000_media_type_copper; } break; } } } /** * e1000_reset_hw - reset the hardware completely * @hw: Struct containing variables accessed by shared code * * Reset the transmit and receive units; mask and clear all interrupts. */ s32 e1000_reset_hw(struct e1000_hw *hw) { u32 ctrl; u32 ctrl_ext; u32 manc; u32 led_ctrl; s32 ret_val; /* For 82542 (rev 2.0), disable MWI before issuing a device reset */ if (hw->mac_type == e1000_82542_rev2_0) { e_dbg("Disabling MWI on 82542 rev 2.0\n"); e1000_pci_clear_mwi(hw); } /* Clear interrupt mask to stop board from generating interrupts */ e_dbg("Masking off all interrupts\n"); ew32(IMC, 0xffffffff); /* Disable the Transmit and Receive units. Then delay to allow * any pending transactions to complete before we hit the MAC with * the global reset. */ ew32(RCTL, 0); ew32(TCTL, E1000_TCTL_PSP); E1000_WRITE_FLUSH(); /* The tbi_compatibility_on Flag must be cleared when Rctl is cleared. */ hw->tbi_compatibility_on = false; /* Delay to allow any outstanding PCI transactions to complete before * resetting the device */ msleep(10); ctrl = er32(CTRL); /* Must reset the PHY before resetting the MAC */ if ((hw->mac_type == e1000_82541) || (hw->mac_type == e1000_82547)) { ew32(CTRL, (ctrl | E1000_CTRL_PHY_RST)); E1000_WRITE_FLUSH(); msleep(5); } /* Issue a global reset to the MAC. This will reset the chip's * transmit, receive, DMA, and link units. It will not effect * the current PCI configuration. The global reset bit is self- * clearing, and should clear within a microsecond. */ e_dbg("Issuing a global reset to MAC\n"); switch (hw->mac_type) { case e1000_82544: case e1000_82540: case e1000_82545: case e1000_82546: case e1000_82541: case e1000_82541_rev_2: /* These controllers can't ack the 64-bit write when issuing the * reset, so use IO-mapping as a workaround to issue the reset */ E1000_WRITE_REG_IO(hw, CTRL, (ctrl | E1000_CTRL_RST)); break; case e1000_82545_rev_3: case e1000_82546_rev_3: /* Reset is performed on a shadow of the control register */ ew32(CTRL_DUP, (ctrl | E1000_CTRL_RST)); break; case e1000_ce4100: default: ew32(CTRL, (ctrl | E1000_CTRL_RST)); break; } /* After MAC reset, force reload of EEPROM to restore power-on settings * to device. Later controllers reload the EEPROM automatically, so * just wait for reload to complete. */ switch (hw->mac_type) { case e1000_82542_rev2_0: case e1000_82542_rev2_1: case e1000_82543: case e1000_82544: /* Wait for reset to complete */ udelay(10); ctrl_ext = er32(CTRL_EXT); ctrl_ext |= E1000_CTRL_EXT_EE_RST; ew32(CTRL_EXT, ctrl_ext); E1000_WRITE_FLUSH(); /* Wait for EEPROM reload */ msleep(2); break; case e1000_82541: case e1000_82541_rev_2: case e1000_82547: case e1000_82547_rev_2: /* Wait for EEPROM reload */ msleep(20); break; default: /* Auto read done will delay 5ms or poll based on mac type */ ret_val = e1000_get_auto_rd_done(hw); if (ret_val) return ret_val; break; } /* Disable HW ARPs on ASF enabled adapters */ if (hw->mac_type >= e1000_82540) { manc = er32(MANC); manc &= ~(E1000_MANC_ARP_EN); ew32(MANC, manc); } if ((hw->mac_type == e1000_82541) || (hw->mac_type == e1000_82547)) { e1000_phy_init_script(hw); /* Configure activity LED after PHY reset */ led_ctrl = er32(LEDCTL); led_ctrl &= IGP_ACTIVITY_LED_MASK; led_ctrl |= (IGP_ACTIVITY_LED_ENABLE | IGP_LED3_MODE); ew32(LEDCTL, led_ctrl); } /* Clear interrupt mask to stop board from generating interrupts */ e_dbg("Masking off all interrupts\n"); ew32(IMC, 0xffffffff); /* Clear any pending interrupt events. */ er32(ICR); /* If MWI was previously enabled, reenable it. */ if (hw->mac_type == e1000_82542_rev2_0) { if (hw->pci_cmd_word & PCI_COMMAND_INVALIDATE) e1000_pci_set_mwi(hw); } return E1000_SUCCESS; } /** * e1000_init_hw - Performs basic configuration of the adapter. * @hw: Struct containing variables accessed by shared code * * Assumes that the controller has previously been reset and is in a * post-reset uninitialized state. Initializes the receive address registers, * multicast table, and VLAN filter table. Calls routines to setup link * configuration and flow control settings. Clears all on-chip counters. Leaves * the transmit and receive units disabled and uninitialized. */ s32 e1000_init_hw(struct e1000_hw *hw) { u32 ctrl; u32 i; s32 ret_val; u32 mta_size; u32 ctrl_ext; /* Initialize Identification LED */ ret_val = e1000_id_led_init(hw); if (ret_val) { e_dbg("Error Initializing Identification LED\n"); return ret_val; } /* Set the media type and TBI compatibility */ e1000_set_media_type(hw); /* Disabling VLAN filtering. */ e_dbg("Initializing the IEEE VLAN\n"); if (hw->mac_type < e1000_82545_rev_3) ew32(VET, 0); e1000_clear_vfta(hw); /* For 82542 (rev 2.0), disable MWI and put the receiver into reset */ if (hw->mac_type == e1000_82542_rev2_0) { e_dbg("Disabling MWI on 82542 rev 2.0\n"); e1000_pci_clear_mwi(hw); ew32(RCTL, E1000_RCTL_RST); E1000_WRITE_FLUSH(); msleep(5); } /* Setup the receive address. This involves initializing all of the * Receive Address Registers (RARs 0 - 15). */ e1000_init_rx_addrs(hw); /* For 82542 (rev 2.0), take the receiver out of reset and enable MWI */ if (hw->mac_type == e1000_82542_rev2_0) { ew32(RCTL, 0); E1000_WRITE_FLUSH(); msleep(1); if (hw->pci_cmd_word & PCI_COMMAND_INVALIDATE) e1000_pci_set_mwi(hw); } /* Zero out the Multicast HASH table */ e_dbg("Zeroing the MTA\n"); mta_size = E1000_MC_TBL_SIZE; for (i = 0; i < mta_size; i++) { E1000_WRITE_REG_ARRAY(hw, MTA, i, 0); /* use write flush to prevent Memory Write Block (MWB) from * occurring when accessing our register space */ E1000_WRITE_FLUSH(); } /* Set the PCI priority bit correctly in the CTRL register. This * determines if the adapter gives priority to receives, or if it * gives equal priority to transmits and receives. Valid only on * 82542 and 82543 silicon. */ if (hw->dma_fairness && hw->mac_type <= e1000_82543) { ctrl = er32(CTRL); ew32(CTRL, ctrl | E1000_CTRL_PRIOR); } switch (hw->mac_type) { case e1000_82545_rev_3: case e1000_82546_rev_3: break; default: /* Workaround for PCI-X problem when BIOS sets MMRBC * incorrectly. */ if (hw->bus_type == e1000_bus_type_pcix && e1000_pcix_get_mmrbc(hw) > 2048) e1000_pcix_set_mmrbc(hw, 2048); break; } /* Call a subroutine to configure the link and setup flow control. */ ret_val = e1000_setup_link(hw); /* Set the transmit descriptor write-back policy */ if (hw->mac_type > e1000_82544) { ctrl = er32(TXDCTL); ctrl = (ctrl & ~E1000_TXDCTL_WTHRESH) | E1000_TXDCTL_FULL_TX_DESC_WB; ew32(TXDCTL, ctrl); } /* Clear all of the statistics registers (clear on read). It is * important that we do this after we have tried to establish link * because the symbol error count will increment wildly if there * is no link. */ e1000_clear_hw_cntrs(hw); if (hw->device_id == E1000_DEV_ID_82546GB_QUAD_COPPER || hw->device_id == E1000_DEV_ID_82546GB_QUAD_COPPER_KSP3) { ctrl_ext = er32(CTRL_EXT); /* Relaxed ordering must be disabled to avoid a parity * error crash in a PCI slot. */ ctrl_ext |= E1000_CTRL_EXT_RO_DIS; ew32(CTRL_EXT, ctrl_ext); } return ret_val; } /** * e1000_adjust_serdes_amplitude - Adjust SERDES output amplitude based on EEPROM setting. * @hw: Struct containing variables accessed by shared code. */ static s32 e1000_adjust_serdes_amplitude(struct e1000_hw *hw) { u16 eeprom_data; s32 ret_val; if (hw->media_type != e1000_media_type_internal_serdes) return E1000_SUCCESS; switch (hw->mac_type) { case e1000_82545_rev_3: case e1000_82546_rev_3: break; default: return E1000_SUCCESS; } ret_val = e1000_read_eeprom(hw, EEPROM_SERDES_AMPLITUDE, 1, &eeprom_data); if (ret_val) return ret_val; if (eeprom_data != EEPROM_RESERVED_WORD) { /* Adjust SERDES output amplitude only. */ eeprom_data &= EEPROM_SERDES_AMPLITUDE_MASK; ret_val = e1000_write_phy_reg(hw, M88E1000_PHY_EXT_CTRL, eeprom_data); if (ret_val) return ret_val; } return E1000_SUCCESS; } /** * e1000_setup_link - Configures flow control and link settings. * @hw: Struct containing variables accessed by shared code * * Determines which flow control settings to use. Calls the appropriate media- * specific link configuration function. Configures the flow control settings. * Assuming the adapter has a valid link partner, a valid link should be * established. Assumes the hardware has previously been reset and the * transmitter and receiver are not enabled. */ s32 e1000_setup_link(struct e1000_hw *hw) { u32 ctrl_ext; s32 ret_val; u16 eeprom_data; /* Read and store word 0x0F of the EEPROM. This word contains bits * that determine the hardware's default PAUSE (flow control) mode, * a bit that determines whether the HW defaults to enabling or * disabling auto-negotiation, and the direction of the * SW defined pins. If there is no SW over-ride of the flow * control setting, then the variable hw->fc will * be initialized based on a value in the EEPROM. */ if (hw->fc == E1000_FC_DEFAULT) { ret_val = e1000_read_eeprom(hw, EEPROM_INIT_CONTROL2_REG, 1, &eeprom_data); if (ret_val) { e_dbg("EEPROM Read Error\n"); return -E1000_ERR_EEPROM; } if ((eeprom_data & EEPROM_WORD0F_PAUSE_MASK) == 0) hw->fc = E1000_FC_NONE; else if ((eeprom_data & EEPROM_WORD0F_PAUSE_MASK) == EEPROM_WORD0F_ASM_DIR) hw->fc = E1000_FC_TX_PAUSE; else hw->fc = E1000_FC_FULL; } /* We want to save off the original Flow Control configuration just * in case we get disconnected and then reconnected into a different * hub or switch with different Flow Control capabilities. */ if (hw->mac_type == e1000_82542_rev2_0) hw->fc &= (~E1000_FC_TX_PAUSE); if ((hw->mac_type < e1000_82543) && (hw->report_tx_early == 1)) hw->fc &= (~E1000_FC_RX_PAUSE); hw->original_fc = hw->fc; e_dbg("After fix-ups FlowControl is now = %x\n", hw->fc); /* Take the 4 bits from EEPROM word 0x0F that determine the initial * polarity value for the SW controlled pins, and setup the * Extended Device Control reg with that info. * This is needed because one of the SW controlled pins is used for * signal detection. So this should be done before e1000_setup_pcs_link() * or e1000_phy_setup() is called. */ if (hw->mac_type == e1000_82543) { ret_val = e1000_read_eeprom(hw, EEPROM_INIT_CONTROL2_REG, 1, &eeprom_data); if (ret_val) { e_dbg("EEPROM Read Error\n"); return -E1000_ERR_EEPROM; } ctrl_ext = ((eeprom_data & EEPROM_WORD0F_SWPDIO_EXT) << SWDPIO__EXT_SHIFT); ew32(CTRL_EXT, ctrl_ext); } /* Call the necessary subroutine to configure the link. */ ret_val = (hw->media_type == e1000_media_type_copper) ? e1000_setup_copper_link(hw) : e1000_setup_fiber_serdes_link(hw); /* Initialize the flow control address, type, and PAUSE timer * registers to their default values. This is done even if flow * control is disabled, because it does not hurt anything to * initialize these registers. */ e_dbg("Initializing the Flow Control address, type and timer regs\n"); ew32(FCT, FLOW_CONTROL_TYPE); ew32(FCAH, FLOW_CONTROL_ADDRESS_HIGH); ew32(FCAL, FLOW_CONTROL_ADDRESS_LOW); ew32(FCTTV, hw->fc_pause_time); /* Set the flow control receive threshold registers. Normally, * these registers will be set to a default threshold that may be * adjusted later by the driver's runtime code. However, if the * ability to transmit pause frames in not enabled, then these * registers will be set to 0. */ if (!(hw->fc & E1000_FC_TX_PAUSE)) { ew32(FCRTL, 0); ew32(FCRTH, 0); } else { /* We need to set up the Receive Threshold high and low water * marks as well as (optionally) enabling the transmission of * XON frames. */ if (hw->fc_send_xon) { ew32(FCRTL, (hw->fc_low_water | E1000_FCRTL_XONE)); ew32(FCRTH, hw->fc_high_water); } else { ew32(FCRTL, hw->fc_low_water); ew32(FCRTH, hw->fc_high_water); } } return ret_val; } /** * e1000_setup_fiber_serdes_link - prepare fiber or serdes link * @hw: Struct containing variables accessed by shared code * * Manipulates Physical Coding Sublayer functions in order to configure * link. Assumes the hardware has been previously reset and the transmitter * and receiver are not enabled. */ static s32 e1000_setup_fiber_serdes_link(struct e1000_hw *hw) { u32 ctrl; u32 status; u32 txcw = 0; u32 i; u32 signal = 0; s32 ret_val; /* On adapters with a MAC newer than 82544, SWDP 1 will be * set when the optics detect a signal. On older adapters, it will be * cleared when there is a signal. This applies to fiber media only. * If we're on serdes media, adjust the output amplitude to value * set in the EEPROM. */ ctrl = er32(CTRL); if (hw->media_type == e1000_media_type_fiber) signal = (hw->mac_type > e1000_82544) ? E1000_CTRL_SWDPIN1 : 0; ret_val = e1000_adjust_serdes_amplitude(hw); if (ret_val) return ret_val; /* Take the link out of reset */ ctrl &= ~(E1000_CTRL_LRST); /* Adjust VCO speed to improve BER performance */ ret_val = e1000_set_vco_speed(hw); if (ret_val) return ret_val; e1000_config_collision_dist(hw); /* Check for a software override of the flow control settings, and setup * the device accordingly. If auto-negotiation is enabled, then * software will have to set the "PAUSE" bits to the correct value in * the Tranmsit Config Word Register (TXCW) and re-start * auto-negotiation. However, if auto-negotiation is disabled, then * software will have to manually configure the two flow control enable * bits in the CTRL register. * * The possible values of the "fc" parameter are: * 0: Flow control is completely disabled * 1: Rx flow control is enabled (we can receive pause frames, but * not send pause frames). * 2: Tx flow control is enabled (we can send pause frames but we do * not support receiving pause frames). * 3: Both Rx and TX flow control (symmetric) are enabled. */ switch (hw->fc) { case E1000_FC_NONE: /* Flow ctrl is completely disabled by a software over-ride */ txcw = (E1000_TXCW_ANE | E1000_TXCW_FD); break; case E1000_FC_RX_PAUSE: /* Rx Flow control is enabled and Tx Flow control is disabled by * a software over-ride. Since there really isn't a way to * advertise that we are capable of Rx Pause ONLY, we will * advertise that we support both symmetric and asymmetric Rx * PAUSE. Later, we will disable the adapter's ability to send * PAUSE frames. */ txcw = (E1000_TXCW_ANE | E1000_TXCW_FD | E1000_TXCW_PAUSE_MASK); break; case E1000_FC_TX_PAUSE: /* Tx Flow control is enabled, and Rx Flow control is disabled, * by a software over-ride. */ txcw = (E1000_TXCW_ANE | E1000_TXCW_FD | E1000_TXCW_ASM_DIR); break; case E1000_FC_FULL: /* Flow control (both Rx and Tx) is enabled by a software * over-ride. */ txcw = (E1000_TXCW_ANE | E1000_TXCW_FD | E1000_TXCW_PAUSE_MASK); break; default: e_dbg("Flow control param set incorrectly\n"); return -E1000_ERR_CONFIG; } /* Since auto-negotiation is enabled, take the link out of reset (the * link will be in reset, because we previously reset the chip). This * will restart auto-negotiation. If auto-negotiation is successful * then the link-up status bit will be set and the flow control enable * bits (RFCE and TFCE) will be set according to their negotiated value. */ e_dbg("Auto-negotiation enabled\n"); ew32(TXCW, txcw); ew32(CTRL, ctrl); E1000_WRITE_FLUSH(); hw->txcw = txcw; msleep(1); /* If we have a signal (the cable is plugged in) then poll for a * "Link-Up" indication in the Device Status Register. Time-out if a * link isn't seen in 500 milliseconds seconds (Auto-negotiation should * complete in less than 500 milliseconds even if the other end is doing * it in SW). For internal serdes, we just assume a signal is present, * then poll. */ if (hw->media_type == e1000_media_type_internal_serdes || (er32(CTRL) & E1000_CTRL_SWDPIN1) == signal) { e_dbg("Looking for Link\n"); for (i = 0; i < (LINK_UP_TIMEOUT / 10); i++) { msleep(10); status = er32(STATUS); if (status & E1000_STATUS_LU) break; } if (i == (LINK_UP_TIMEOUT / 10)) { e_dbg("Never got a valid link from auto-neg!!!\n"); hw->autoneg_failed = 1; /* AutoNeg failed to achieve a link, so we'll call * e1000_check_for_link. This routine will force the * link up if we detect a signal. This will allow us to * communicate with non-autonegotiating link partners. */ ret_val = e1000_check_for_link(hw); if (ret_val) { e_dbg("Error while checking for link\n"); return ret_val; } hw->autoneg_failed = 0; } else { hw->autoneg_failed = 0; e_dbg("Valid Link Found\n"); } } else { e_dbg("No Signal Detected\n"); } return E1000_SUCCESS; } /** * e1000_copper_link_rtl_setup - Copper link setup for e1000_phy_rtl series. * @hw: Struct containing variables accessed by shared code * * Commits changes to PHY configuration by calling e1000_phy_reset(). */ static s32 e1000_copper_link_rtl_setup(struct e1000_hw *hw) { s32 ret_val; /* SW reset the PHY so all changes take effect */ ret_val = e1000_phy_reset(hw); if (ret_val) { e_dbg("Error Resetting the PHY\n"); return ret_val; } return E1000_SUCCESS; } static s32 gbe_dhg_phy_setup(struct e1000_hw *hw) { s32 ret_val; u32 ctrl_aux; switch (hw->phy_type) { case e1000_phy_8211: ret_val = e1000_copper_link_rtl_setup(hw); if (ret_val) { e_dbg("e1000_copper_link_rtl_setup failed!\n"); return ret_val; } break; case e1000_phy_8201: /* Set RMII mode */ ctrl_aux = er32(CTL_AUX); ctrl_aux |= E1000_CTL_AUX_RMII; ew32(CTL_AUX, ctrl_aux); E1000_WRITE_FLUSH(); /* Disable the J/K bits required for receive */ ctrl_aux = er32(CTL_AUX); ctrl_aux |= 0x4; ctrl_aux &= ~0x2; ew32(CTL_AUX, ctrl_aux); E1000_WRITE_FLUSH(); ret_val = e1000_copper_link_rtl_setup(hw); if (ret_val) { e_dbg("e1000_copper_link_rtl_setup failed!\n"); return ret_val; } break; default: e_dbg("Error Resetting the PHY\n"); return E1000_ERR_PHY_TYPE; } return E1000_SUCCESS; } /** * e1000_copper_link_preconfig - early configuration for copper * @hw: Struct containing variables accessed by shared code * * Make sure we have a valid PHY and change PHY mode before link setup. */ static s32 e1000_copper_link_preconfig(struct e1000_hw *hw) { u32 ctrl; s32 ret_val; u16 phy_data; ctrl = er32(CTRL); /* With 82543, we need to force speed and duplex on the MAC equal to * what the PHY speed and duplex configuration is. In addition, we need * to perform a hardware reset on the PHY to take it out of reset. */ if (hw->mac_type > e1000_82543) { ctrl |= E1000_CTRL_SLU; ctrl &= ~(E1000_CTRL_FRCSPD | E1000_CTRL_FRCDPX); ew32(CTRL, ctrl); } else { ctrl |= (E1000_CTRL_FRCSPD | E1000_CTRL_FRCDPX | E1000_CTRL_SLU); ew32(CTRL, ctrl); ret_val = e1000_phy_hw_reset(hw); if (ret_val) return ret_val; } /* Make sure we have a valid PHY */ ret_val = e1000_detect_gig_phy(hw); if (ret_val) { e_dbg("Error, did not detect valid phy.\n"); return ret_val; } e_dbg("Phy ID = %x\n", hw->phy_id); /* Set PHY to class A mode (if necessary) */ ret_val = e1000_set_phy_mode(hw); if (ret_val) return ret_val; if ((hw->mac_type == e1000_82545_rev_3) || (hw->mac_type == e1000_82546_rev_3)) { ret_val = e1000_read_phy_reg(hw, M88E1000_PHY_SPEC_CTRL, &phy_data); phy_data |= 0x00000008; ret_val = e1000_write_phy_reg(hw, M88E1000_PHY_SPEC_CTRL, phy_data); } if (hw->mac_type <= e1000_82543 || hw->mac_type == e1000_82541 || hw->mac_type == e1000_82547 || hw->mac_type == e1000_82541_rev_2 || hw->mac_type == e1000_82547_rev_2) hw->phy_reset_disable = false; return E1000_SUCCESS; } /** * e1000_copper_link_igp_setup - Copper link setup for e1000_phy_igp series. * @hw: Struct containing variables accessed by shared code */ static s32 e1000_copper_link_igp_setup(struct e1000_hw *hw) { u32 led_ctrl; s32 ret_val; u16 phy_data; if (hw->phy_reset_disable) return E1000_SUCCESS; ret_val = e1000_phy_reset(hw); if (ret_val) { e_dbg("Error Resetting the PHY\n"); return ret_val; } /* Wait 15ms for MAC to configure PHY from eeprom settings */ msleep(15); /* Configure activity LED after PHY reset */ led_ctrl = er32(LEDCTL); led_ctrl &= IGP_ACTIVITY_LED_MASK; led_ctrl |= (IGP_ACTIVITY_LED_ENABLE | IGP_LED3_MODE); ew32(LEDCTL, led_ctrl); /* The NVM settings will configure LPLU in D3 for IGP2 and IGP3 PHYs */ if (hw->phy_type == e1000_phy_igp) { /* disable lplu d3 during driver init */ ret_val = e1000_set_d3_lplu_state(hw, false); if (ret_val) { e_dbg("Error Disabling LPLU D3\n"); return ret_val; } } /* Configure mdi-mdix settings */ ret_val = e1000_read_phy_reg(hw, IGP01E1000_PHY_PORT_CTRL, &phy_data); if (ret_val) return ret_val; if ((hw->mac_type == e1000_82541) || (hw->mac_type == e1000_82547)) { hw->dsp_config_state = e1000_dsp_config_disabled; /* Force MDI for earlier revs of the IGP PHY */ phy_data &= ~(IGP01E1000_PSCR_AUTO_MDIX | IGP01E1000_PSCR_FORCE_MDI_MDIX); hw->mdix = 1; } else { hw->dsp_config_state = e1000_dsp_config_enabled; phy_data &= ~IGP01E1000_PSCR_AUTO_MDIX; switch (hw->mdix) { case 1: phy_data &= ~IGP01E1000_PSCR_FORCE_MDI_MDIX; break; case 2: phy_data |= IGP01E1000_PSCR_FORCE_MDI_MDIX; break; case 0: default: phy_data |= IGP01E1000_PSCR_AUTO_MDIX; break; } } ret_val = e1000_write_phy_reg(hw, IGP01E1000_PHY_PORT_CTRL, phy_data); if (ret_val) return ret_val; /* set auto-master slave resolution settings */ if (hw->autoneg) { e1000_ms_type phy_ms_setting = hw->master_slave; if (hw->ffe_config_state == e1000_ffe_config_active) hw->ffe_config_state = e1000_ffe_config_enabled; if (hw->dsp_config_state == e1000_dsp_config_activated) hw->dsp_config_state = e1000_dsp_config_enabled; /* when autonegotiation advertisement is only 1000Mbps then we * should disable SmartSpeed and enable Auto MasterSlave * resolution as hardware default. */ if (hw->autoneg_advertised == ADVERTISE_1000_FULL) { /* Disable SmartSpeed */ ret_val = e1000_read_phy_reg(hw, IGP01E1000_PHY_PORT_CONFIG, &phy_data); if (ret_val) return ret_val; phy_data &= ~IGP01E1000_PSCFR_SMART_SPEED; ret_val = e1000_write_phy_reg(hw, IGP01E1000_PHY_PORT_CONFIG, phy_data); if (ret_val) return ret_val; /* Set auto Master/Slave resolution process */ ret_val = e1000_read_phy_reg(hw, PHY_1000T_CTRL, &phy_data); if (ret_val) return ret_val; phy_data &= ~CR_1000T_MS_ENABLE; ret_val = e1000_write_phy_reg(hw, PHY_1000T_CTRL, phy_data); if (ret_val) return ret_val; } ret_val = e1000_read_phy_reg(hw, PHY_1000T_CTRL, &phy_data); if (ret_val) return ret_val; /* load defaults for future use */ hw->original_master_slave = (phy_data & CR_1000T_MS_ENABLE) ? ((phy_data & CR_1000T_MS_VALUE) ? e1000_ms_force_master : e1000_ms_force_slave) : e1000_ms_auto; switch (phy_ms_setting) { case e1000_ms_force_master: phy_data |= (CR_1000T_MS_ENABLE | CR_1000T_MS_VALUE); break; case e1000_ms_force_slave: phy_data |= CR_1000T_MS_ENABLE; phy_data &= ~(CR_1000T_MS_VALUE); break; case e1000_ms_auto: phy_data &= ~CR_1000T_MS_ENABLE; break; default: break; } ret_val = e1000_write_phy_reg(hw, PHY_1000T_CTRL, phy_data); if (ret_val) return ret_val; } return E1000_SUCCESS; } /** * e1000_copper_link_mgp_setup - Copper link setup for e1000_phy_m88 series. * @hw: Struct containing variables accessed by shared code */ static s32 e1000_copper_link_mgp_setup(struct e1000_hw *hw) { s32 ret_val; u16 phy_data; if (hw->phy_reset_disable) return E1000_SUCCESS; /* Enable CRS on TX. This must be set for half-duplex operation. */ ret_val = e1000_read_phy_reg(hw, M88E1000_PHY_SPEC_CTRL, &phy_data); if (ret_val) return ret_val; phy_data |= M88E1000_PSCR_ASSERT_CRS_ON_TX; /* Options: * MDI/MDI-X = 0 (default) * 0 - Auto for all speeds * 1 - MDI mode * 2 - MDI-X mode * 3 - Auto for 1000Base-T only (MDI-X for 10/100Base-T modes) */ phy_data &= ~M88E1000_PSCR_AUTO_X_MODE; switch (hw->mdix) { case 1: phy_data |= M88E1000_PSCR_MDI_MANUAL_MODE; break; case 2: phy_data |= M88E1000_PSCR_MDIX_MANUAL_MODE; break; case 3: phy_data |= M88E1000_PSCR_AUTO_X_1000T; break; case 0: default: phy_data |= M88E1000_PSCR_AUTO_X_MODE; break; } /* Options: * disable_polarity_correction = 0 (default) * Automatic Correction for Reversed Cable Polarity * 0 - Disabled * 1 - Enabled */ phy_data &= ~M88E1000_PSCR_POLARITY_REVERSAL; if (hw->disable_polarity_correction == 1) phy_data |= M88E1000_PSCR_POLARITY_REVERSAL; ret_val = e1000_write_phy_reg(hw, M88E1000_PHY_SPEC_CTRL, phy_data); if (ret_val) return ret_val; if (hw->phy_revision < M88E1011_I_REV_4) { /* Force TX_CLK in the Extended PHY Specific Control Register * to 25MHz clock. */ ret_val = e1000_read_phy_reg(hw, M88E1000_EXT_PHY_SPEC_CTRL, &phy_data); if (ret_val) return ret_val; phy_data |= M88E1000_EPSCR_TX_CLK_25; if ((hw->phy_revision == E1000_REVISION_2) && (hw->phy_id == M88E1111_I_PHY_ID)) { /* Vidalia Phy, set the downshift counter to 5x */ phy_data &= ~(M88EC018_EPSCR_DOWNSHIFT_COUNTER_MASK); phy_data |= M88EC018_EPSCR_DOWNSHIFT_COUNTER_5X; ret_val = e1000_write_phy_reg(hw, M88E1000_EXT_PHY_SPEC_CTRL, phy_data); if (ret_val) return ret_val; } else { /* Configure Master and Slave downshift values */ phy_data &= ~(M88E1000_EPSCR_MASTER_DOWNSHIFT_MASK | M88E1000_EPSCR_SLAVE_DOWNSHIFT_MASK); phy_data |= (M88E1000_EPSCR_MASTER_DOWNSHIFT_1X | M88E1000_EPSCR_SLAVE_DOWNSHIFT_1X); ret_val = e1000_write_phy_reg(hw, M88E1000_EXT_PHY_SPEC_CTRL, phy_data); if (ret_val) return ret_val; } } /* SW Reset the PHY so all changes take effect */ ret_val = e1000_phy_reset(hw); if (ret_val) { e_dbg("Error Resetting the PHY\n"); return ret_val; } return E1000_SUCCESS; } /** * e1000_copper_link_autoneg - setup auto-neg * @hw: Struct containing variables accessed by shared code * * Setup auto-negotiation and flow control advertisements, * and then perform auto-negotiation. */ static s32 e1000_copper_link_autoneg(struct e1000_hw *hw) { s32 ret_val; u16 phy_data; /* Perform some bounds checking on the hw->autoneg_advertised * parameter. If this variable is zero, then set it to the default. */ hw->autoneg_advertised &= AUTONEG_ADVERTISE_SPEED_DEFAULT; /* If autoneg_advertised is zero, we assume it was not defaulted * by the calling code so we set to advertise full capability. */ if (hw->autoneg_advertised == 0) hw->autoneg_advertised = AUTONEG_ADVERTISE_SPEED_DEFAULT; /* IFE/RTL8201N PHY only supports 10/100 */ if (hw->phy_type == e1000_phy_8201) hw->autoneg_advertised &= AUTONEG_ADVERTISE_10_100_ALL; e_dbg("Reconfiguring auto-neg advertisement params\n"); ret_val = e1000_phy_setup_autoneg(hw); if (ret_val) { e_dbg("Error Setting up Auto-Negotiation\n"); return ret_val; } e_dbg("Restarting Auto-Neg\n"); /* Restart auto-negotiation by setting the Auto Neg Enable bit and * the Auto Neg Restart bit in the PHY control register. */ ret_val = e1000_read_phy_reg(hw, PHY_CTRL, &phy_data); if (ret_val) return ret_val; phy_data |= (MII_CR_AUTO_NEG_EN | MII_CR_RESTART_AUTO_NEG); ret_val = e1000_write_phy_reg(hw, PHY_CTRL, phy_data); if (ret_val) return ret_val; /* Does the user want to wait for Auto-Neg to complete here, or * check at a later time (for example, callback routine). */ if (hw->wait_autoneg_complete) { ret_val = e1000_wait_autoneg(hw); if (ret_val) { e_dbg ("Error while waiting for autoneg to complete\n"); return ret_val; } } hw->get_link_status = true; return E1000_SUCCESS; } /** * e1000_copper_link_postconfig - post link setup * @hw: Struct containing variables accessed by shared code * * Config the MAC and the PHY after link is up. * 1) Set up the MAC to the current PHY speed/duplex * if we are on 82543. If we * are on newer silicon, we only need to configure * collision distance in the Transmit Control Register. * 2) Set up flow control on the MAC to that established with * the link partner. * 3) Config DSP to improve Gigabit link quality for some PHY revisions. */ static s32 e1000_copper_link_postconfig(struct e1000_hw *hw) { s32 ret_val; if ((hw->mac_type >= e1000_82544) && (hw->mac_type != e1000_ce4100)) { e1000_config_collision_dist(hw); } else { ret_val = e1000_config_mac_to_phy(hw); if (ret_val) { e_dbg("Error configuring MAC to PHY settings\n"); return ret_val; } } ret_val = e1000_config_fc_after_link_up(hw); if (ret_val) { e_dbg("Error Configuring Flow Control\n"); return ret_val; } /* Config DSP to improve Giga link quality */ if (hw->phy_type == e1000_phy_igp) { ret_val = e1000_config_dsp_after_link_change(hw, true); if (ret_val) { e_dbg("Error Configuring DSP after link up\n"); return ret_val; } } return E1000_SUCCESS; } /** * e1000_setup_copper_link - phy/speed/duplex setting * @hw: Struct containing variables accessed by shared code * * Detects which PHY is present and sets up the speed and duplex */ static s32 e1000_setup_copper_link(struct e1000_hw *hw) { s32 ret_val; u16 i; u16 phy_data; /* Check if it is a valid PHY and set PHY mode if necessary. */ ret_val = e1000_copper_link_preconfig(hw); if (ret_val) return ret_val; if (hw->phy_type == e1000_phy_igp) { ret_val = e1000_copper_link_igp_setup(hw); if (ret_val) return ret_val; } else if (hw->phy_type == e1000_phy_m88) { ret_val = e1000_copper_link_mgp_setup(hw); if (ret_val) return ret_val; } else { ret_val = gbe_dhg_phy_setup(hw); if (ret_val) { e_dbg("gbe_dhg_phy_setup failed!\n"); return ret_val; } } if (hw->autoneg) { /* Setup autoneg and flow control advertisement * and perform autonegotiation */ ret_val = e1000_copper_link_autoneg(hw); if (ret_val) return ret_val; } else { /* PHY will be set to 10H, 10F, 100H,or 100F * depending on value from forced_speed_duplex. */ e_dbg("Forcing speed and duplex\n"); ret_val = e1000_phy_force_speed_duplex(hw); if (ret_val) { e_dbg("Error Forcing Speed and Duplex\n"); return ret_val; } } /* Check link status. Wait up to 100 microseconds for link to become * valid. */ for (i = 0; i < 10; i++) { ret_val = e1000_read_phy_reg(hw, PHY_STATUS, &phy_data); if (ret_val) return ret_val; ret_val = e1000_read_phy_reg(hw, PHY_STATUS, &phy_data); if (ret_val) return ret_val; if (phy_data & MII_SR_LINK_STATUS) { /* Config the MAC and PHY after link is up */ ret_val = e1000_copper_link_postconfig(hw); if (ret_val) return ret_val; e_dbg("Valid link established!!!\n"); return E1000_SUCCESS; } udelay(10); } e_dbg("Unable to establish link!!!\n"); return E1000_SUCCESS; } /** * e1000_phy_setup_autoneg - phy settings * @hw: Struct containing variables accessed by shared code * * Configures PHY autoneg and flow control advertisement settings */ s32 e1000_phy_setup_autoneg(struct e1000_hw *hw) { s32 ret_val; u16 mii_autoneg_adv_reg; u16 mii_1000t_ctrl_reg; /* Read the MII Auto-Neg Advertisement Register (Address 4). */ ret_val = e1000_read_phy_reg(hw, PHY_AUTONEG_ADV, &mii_autoneg_adv_reg); if (ret_val) return ret_val; /* Read the MII 1000Base-T Control Register (Address 9). */ ret_val = e1000_read_phy_reg(hw, PHY_1000T_CTRL, &mii_1000t_ctrl_reg); if (ret_val) return ret_val; else if (hw->phy_type == e1000_phy_8201) mii_1000t_ctrl_reg &= ~REG9_SPEED_MASK; /* Need to parse both autoneg_advertised and fc and set up * the appropriate PHY registers. First we will parse for * autoneg_advertised software override. Since we can advertise * a plethora of combinations, we need to check each bit * individually. */ /* First we clear all the 10/100 mb speed bits in the Auto-Neg * Advertisement Register (Address 4) and the 1000 mb speed bits in * the 1000Base-T Control Register (Address 9). */ mii_autoneg_adv_reg &= ~REG4_SPEED_MASK; mii_1000t_ctrl_reg &= ~REG9_SPEED_MASK; e_dbg("autoneg_advertised %x\n", hw->autoneg_advertised); /* Do we want to advertise 10 Mb Half Duplex? */ if (hw->autoneg_advertised & ADVERTISE_10_HALF) { e_dbg("Advertise 10mb Half duplex\n"); mii_autoneg_adv_reg |= NWAY_AR_10T_HD_CAPS; } /* Do we want to advertise 10 Mb Full Duplex? */ if (hw->autoneg_advertised & ADVERTISE_10_FULL) { e_dbg("Advertise 10mb Full duplex\n"); mii_autoneg_adv_reg |= NWAY_AR_10T_FD_CAPS; } /* Do we want to advertise 100 Mb Half Duplex? */ if (hw->autoneg_advertised & ADVERTISE_100_HALF) { e_dbg("Advertise 100mb Half duplex\n"); mii_autoneg_adv_reg |= NWAY_AR_100TX_HD_CAPS; } /* Do we want to advertise 100 Mb Full Duplex? */ if (hw->autoneg_advertised & ADVERTISE_100_FULL) { e_dbg("Advertise 100mb Full duplex\n"); mii_autoneg_adv_reg |= NWAY_AR_100TX_FD_CAPS; } /* We do not allow the Phy to advertise 1000 Mb Half Duplex */ if (hw->autoneg_advertised & ADVERTISE_1000_HALF) { e_dbg ("Advertise 1000mb Half duplex requested, request denied!\n"); } /* Do we want to advertise 1000 Mb Full Duplex? */ if (hw->autoneg_advertised & ADVERTISE_1000_FULL) { e_dbg("Advertise 1000mb Full duplex\n"); mii_1000t_ctrl_reg |= CR_1000T_FD_CAPS; } /* Check for a software override of the flow control settings, and * setup the PHY advertisement registers accordingly. If * auto-negotiation is enabled, then software will have to set the * "PAUSE" bits to the correct value in the Auto-Negotiation * Advertisement Register (PHY_AUTONEG_ADV) and re-start * auto-negotiation. * * The possible values of the "fc" parameter are: * 0: Flow control is completely disabled * 1: Rx flow control is enabled (we can receive pause frames * but not send pause frames). * 2: Tx flow control is enabled (we can send pause frames * but we do not support receiving pause frames). * 3: Both Rx and TX flow control (symmetric) are enabled. * other: No software override. The flow control configuration * in the EEPROM is used. */ switch (hw->fc) { case E1000_FC_NONE: /* 0 */ /* Flow control (RX & TX) is completely disabled by a * software over-ride. */ mii_autoneg_adv_reg &= ~(NWAY_AR_ASM_DIR | NWAY_AR_PAUSE); break; case E1000_FC_RX_PAUSE: /* 1 */ /* RX Flow control is enabled, and TX Flow control is * disabled, by a software over-ride. */ /* Since there really isn't a way to advertise that we are * capable of RX Pause ONLY, we will advertise that we * support both symmetric and asymmetric RX PAUSE. Later * (in e1000_config_fc_after_link_up) we will disable the * hw's ability to send PAUSE frames. */ mii_autoneg_adv_reg |= (NWAY_AR_ASM_DIR | NWAY_AR_PAUSE); break; case E1000_FC_TX_PAUSE: /* 2 */ /* TX Flow control is enabled, and RX Flow control is * disabled, by a software over-ride. */ mii_autoneg_adv_reg |= NWAY_AR_ASM_DIR; mii_autoneg_adv_reg &= ~NWAY_AR_PAUSE; break; case E1000_FC_FULL: /* 3 */ /* Flow control (both RX and TX) is enabled by a software * over-ride. */ mii_autoneg_adv_reg |= (NWAY_AR_ASM_DIR | NWAY_AR_PAUSE); break; default: e_dbg("Flow control param set incorrectly\n"); return -E1000_ERR_CONFIG; } ret_val = e1000_write_phy_reg(hw, PHY_AUTONEG_ADV, mii_autoneg_adv_reg); if (ret_val) return ret_val; e_dbg("Auto-Neg Advertising %x\n", mii_autoneg_adv_reg); if (hw->phy_type == e1000_phy_8201) { mii_1000t_ctrl_reg = 0; } else { ret_val = e1000_write_phy_reg(hw, PHY_1000T_CTRL, mii_1000t_ctrl_reg); if (ret_val) return ret_val; } return E1000_SUCCESS; } /** * e1000_phy_force_speed_duplex - force link settings * @hw: Struct containing variables accessed by shared code * * Force PHY speed and duplex settings to hw->forced_speed_duplex */ static s32 e1000_phy_force_speed_duplex(struct e1000_hw *hw) { u32 ctrl; s32 ret_val; u16 mii_ctrl_reg; u16 mii_status_reg; u16 phy_data; u16 i; /* Turn off Flow control if we are forcing speed and duplex. */ hw->fc = E1000_FC_NONE; e_dbg("hw->fc = %d\n", hw->fc); /* Read the Device Control Register. */ ctrl = er32(CTRL); /* Set the bits to Force Speed and Duplex in the Device Ctrl Reg. */ ctrl |= (E1000_CTRL_FRCSPD | E1000_CTRL_FRCDPX); ctrl &= ~(DEVICE_SPEED_MASK); /* Clear the Auto Speed Detect Enable bit. */ ctrl &= ~E1000_CTRL_ASDE; /* Read the MII Control Register. */ ret_val = e1000_read_phy_reg(hw, PHY_CTRL, &mii_ctrl_reg); if (ret_val) return ret_val; /* We need to disable autoneg in order to force link and duplex. */ mii_ctrl_reg &= ~MII_CR_AUTO_NEG_EN; /* Are we forcing Full or Half Duplex? */ if (hw->forced_speed_duplex == e1000_100_full || hw->forced_speed_duplex == e1000_10_full) { /* We want to force full duplex so we SET the full duplex bits * in the Device and MII Control Registers. */ ctrl |= E1000_CTRL_FD; mii_ctrl_reg |= MII_CR_FULL_DUPLEX; e_dbg("Full Duplex\n"); } else { /* We want to force half duplex so we CLEAR the full duplex bits * in the Device and MII Control Registers. */ ctrl &= ~E1000_CTRL_FD; mii_ctrl_reg &= ~MII_CR_FULL_DUPLEX; e_dbg("Half Duplex\n"); } /* Are we forcing 100Mbps??? */ if (hw->forced_speed_duplex == e1000_100_full || hw->forced_speed_duplex == e1000_100_half) { /* Set the 100Mb bit and turn off the 1000Mb and 10Mb bits. */ ctrl |= E1000_CTRL_SPD_100; mii_ctrl_reg |= MII_CR_SPEED_100; mii_ctrl_reg &= ~(MII_CR_SPEED_1000 | MII_CR_SPEED_10); e_dbg("Forcing 100mb "); } else { /* Set the 10Mb bit and turn off the 1000Mb and 100Mb bits. */ ctrl &= ~(E1000_CTRL_SPD_1000 | E1000_CTRL_SPD_100); mii_ctrl_reg |= MII_CR_SPEED_10; mii_ctrl_reg &= ~(MII_CR_SPEED_1000 | MII_CR_SPEED_100); e_dbg("Forcing 10mb "); } e1000_config_collision_dist(hw); /* Write the configured values back to the Device Control Reg. */ ew32(CTRL, ctrl); if (hw->phy_type == e1000_phy_m88) { ret_val = e1000_read_phy_reg(hw, M88E1000_PHY_SPEC_CTRL, &phy_data); if (ret_val) return ret_val; /* Clear Auto-Crossover to force MDI manually. M88E1000 requires * MDI forced whenever speed are duplex are forced. */ phy_data &= ~M88E1000_PSCR_AUTO_X_MODE; ret_val = e1000_write_phy_reg(hw, M88E1000_PHY_SPEC_CTRL, phy_data); if (ret_val) return ret_val; e_dbg("M88E1000 PSCR: %x\n", phy_data); /* Need to reset the PHY or these changes will be ignored */ mii_ctrl_reg |= MII_CR_RESET; /* Disable MDI-X support for 10/100 */ } else { /* Clear Auto-Crossover to force MDI manually. IGP requires MDI * forced whenever speed or duplex are forced. */ ret_val = e1000_read_phy_reg(hw, IGP01E1000_PHY_PORT_CTRL, &phy_data); if (ret_val) return ret_val; phy_data &= ~IGP01E1000_PSCR_AUTO_MDIX; phy_data &= ~IGP01E1000_PSCR_FORCE_MDI_MDIX; ret_val = e1000_write_phy_reg(hw, IGP01E1000_PHY_PORT_CTRL, phy_data); if (ret_val) return ret_val; } /* Write back the modified PHY MII control register. */ ret_val = e1000_write_phy_reg(hw, PHY_CTRL, mii_ctrl_reg); if (ret_val) return ret_val; udelay(1); /* The wait_autoneg_complete flag may be a little misleading here. * Since we are forcing speed and duplex, Auto-Neg is not enabled. * But we do want to delay for a period while forcing only so we * don't generate false No Link messages. So we will wait here * only if the user has set wait_autoneg_complete to 1, which is * the default. */ if (hw->wait_autoneg_complete) { /* We will wait for autoneg to complete. */ e_dbg("Waiting for forced speed/duplex link.\n"); mii_status_reg = 0; /* Wait for autoneg to complete or 4.5 seconds to expire */ for (i = PHY_FORCE_TIME; i > 0; i--) { /* Read the MII Status Register and wait for Auto-Neg * Complete bit to be set. */ ret_val = e1000_read_phy_reg(hw, PHY_STATUS, &mii_status_reg); if (ret_val) return ret_val; ret_val = e1000_read_phy_reg(hw, PHY_STATUS, &mii_status_reg); if (ret_val) return ret_val; if (mii_status_reg & MII_SR_LINK_STATUS) break; msleep(100); } if ((i == 0) && (hw->phy_type == e1000_phy_m88)) { /* We didn't get link. Reset the DSP and wait again * for link. */ ret_val = e1000_phy_reset_dsp(hw); if (ret_val) { e_dbg("Error Resetting PHY DSP\n"); return ret_val; } } /* This loop will early-out if the link condition has been * met */ for (i = PHY_FORCE_TIME; i > 0; i--) { if (mii_status_reg & MII_SR_LINK_STATUS) break; msleep(100); /* Read the MII Status Register and wait for Auto-Neg * Complete bit to be set. */ ret_val = e1000_read_phy_reg(hw, PHY_STATUS, &mii_status_reg); if (ret_val) return ret_val; ret_val = e1000_read_phy_reg(hw, PHY_STATUS, &mii_status_reg); if (ret_val) return ret_val; } } if (hw->phy_type == e1000_phy_m88) { /* Because we reset the PHY above, we need to re-force TX_CLK in * the Extended PHY Specific Control Register to 25MHz clock. * This value defaults back to a 2.5MHz clock when the PHY is * reset. */ ret_val = e1000_read_phy_reg(hw, M88E1000_EXT_PHY_SPEC_CTRL, &phy_data); if (ret_val) return ret_val; phy_data |= M88E1000_EPSCR_TX_CLK_25; ret_val = e1000_write_phy_reg(hw, M88E1000_EXT_PHY_SPEC_CTRL, phy_data); if (ret_val) return ret_val; /* In addition, because of the s/w reset above, we need to * enable CRS on Tx. This must be set for both full and half * duplex operation. */ ret_val = e1000_read_phy_reg(hw, M88E1000_PHY_SPEC_CTRL, &phy_data); if (ret_val) return ret_val; phy_data |= M88E1000_PSCR_ASSERT_CRS_ON_TX; ret_val = e1000_write_phy_reg(hw, M88E1000_PHY_SPEC_CTRL, phy_data); if (ret_val) return ret_val; if ((hw->mac_type == e1000_82544 || hw->mac_type == e1000_82543) && (!hw->autoneg) && (hw->forced_speed_duplex == e1000_10_full || hw->forced_speed_duplex == e1000_10_half)) { ret_val = e1000_polarity_reversal_workaround(hw); if (ret_val) return ret_val; } } return E1000_SUCCESS; } /** * e1000_config_collision_dist - set collision distance register * @hw: Struct containing variables accessed by shared code * * Sets the collision distance in the Transmit Control register. * Link should have been established previously. Reads the speed and duplex * information from the Device Status register. */ void e1000_config_collision_dist(struct e1000_hw *hw) { u32 tctl, coll_dist; if (hw->mac_type < e1000_82543) coll_dist = E1000_COLLISION_DISTANCE_82542; else coll_dist = E1000_COLLISION_DISTANCE; tctl = er32(TCTL); tctl &= ~E1000_TCTL_COLD; tctl |= coll_dist << E1000_COLD_SHIFT; ew32(TCTL, tctl); E1000_WRITE_FLUSH(); } /** * e1000_config_mac_to_phy - sync phy and mac settings * @hw: Struct containing variables accessed by shared code * * Sets MAC speed and duplex settings to reflect the those in the PHY * The contents of the PHY register containing the needed information need to * be passed in. */ static s32 e1000_config_mac_to_phy(struct e1000_hw *hw) { u32 ctrl; s32 ret_val; u16 phy_data; /* 82544 or newer MAC, Auto Speed Detection takes care of * MAC speed/duplex configuration. */ if ((hw->mac_type >= e1000_82544) && (hw->mac_type != e1000_ce4100)) return E1000_SUCCESS; /* Read the Device Control Register and set the bits to Force Speed * and Duplex. */ ctrl = er32(CTRL); ctrl |= (E1000_CTRL_FRCSPD | E1000_CTRL_FRCDPX); ctrl &= ~(E1000_CTRL_SPD_SEL | E1000_CTRL_ILOS); switch (hw->phy_type) { case e1000_phy_8201: ret_val = e1000_read_phy_reg(hw, PHY_CTRL, &phy_data); if (ret_val) return ret_val; if (phy_data & RTL_PHY_CTRL_FD) ctrl |= E1000_CTRL_FD; else ctrl &= ~E1000_CTRL_FD; if (phy_data & RTL_PHY_CTRL_SPD_100) ctrl |= E1000_CTRL_SPD_100; else ctrl |= E1000_CTRL_SPD_10; e1000_config_collision_dist(hw); break; default: /* Set up duplex in the Device Control and Transmit Control * registers depending on negotiated values. */ ret_val = e1000_read_phy_reg(hw, M88E1000_PHY_SPEC_STATUS, &phy_data); if (ret_val) return ret_val; if (phy_data & M88E1000_PSSR_DPLX) ctrl |= E1000_CTRL_FD; else ctrl &= ~E1000_CTRL_FD; e1000_config_collision_dist(hw); /* Set up speed in the Device Control register depending on * negotiated values. */ if ((phy_data & M88E1000_PSSR_SPEED) == M88E1000_PSSR_1000MBS) ctrl |= E1000_CTRL_SPD_1000; else if ((phy_data & M88E1000_PSSR_SPEED) == M88E1000_PSSR_100MBS) ctrl |= E1000_CTRL_SPD_100; } /* Write the configured values back to the Device Control Reg. */ ew32(CTRL, ctrl); return E1000_SUCCESS; } /** * e1000_force_mac_fc - force flow control settings * @hw: Struct containing variables accessed by shared code * * Forces the MAC's flow control settings. * Sets the TFCE and RFCE bits in the device control register to reflect * the adapter settings. TFCE and RFCE need to be explicitly set by * software when a Copper PHY is used because autonegotiation is managed * by the PHY rather than the MAC. Software must also configure these * bits when link is forced on a fiber connection. */ s32 e1000_force_mac_fc(struct e1000_hw *hw) { u32 ctrl; /* Get the current configuration of the Device Control Register */ ctrl = er32(CTRL); /* Because we didn't get link via the internal auto-negotiation * mechanism (we either forced link or we got link via PHY * auto-neg), we have to manually enable/disable transmit an * receive flow control. * * The "Case" statement below enables/disable flow control * according to the "hw->fc" parameter. * * The possible values of the "fc" parameter are: * 0: Flow control is completely disabled * 1: Rx flow control is enabled (we can receive pause * frames but not send pause frames). * 2: Tx flow control is enabled (we can send pause frames * but we do not receive pause frames). * 3: Both Rx and TX flow control (symmetric) is enabled. * other: No other values should be possible at this point. */ switch (hw->fc) { case E1000_FC_NONE: ctrl &= (~(E1000_CTRL_TFCE | E1000_CTRL_RFCE)); break; case E1000_FC_RX_PAUSE: ctrl &= (~E1000_CTRL_TFCE); ctrl |= E1000_CTRL_RFCE; break; case E1000_FC_TX_PAUSE: ctrl &= (~E1000_CTRL_RFCE); ctrl |= E1000_CTRL_TFCE; break; case E1000_FC_FULL: ctrl |= (E1000_CTRL_TFCE | E1000_CTRL_RFCE); break; default: e_dbg("Flow control param set incorrectly\n"); return -E1000_ERR_CONFIG; } /* Disable TX Flow Control for 82542 (rev 2.0) */ if (hw->mac_type == e1000_82542_rev2_0) ctrl &= (~E1000_CTRL_TFCE); ew32(CTRL, ctrl); return E1000_SUCCESS; } /** * e1000_config_fc_after_link_up - configure flow control after autoneg * @hw: Struct containing variables accessed by shared code * * Configures flow control settings after link is established * Should be called immediately after a valid link has been established. * Forces MAC flow control settings if link was forced. When in MII/GMII mode * and autonegotiation is enabled, the MAC flow control settings will be set * based on the flow control negotiated by the PHY. In TBI mode, the TFCE * and RFCE bits will be automatically set to the negotiated flow control mode. */ static s32 e1000_config_fc_after_link_up(struct e1000_hw *hw) { s32 ret_val; u16 mii_status_reg; u16 mii_nway_adv_reg; u16 mii_nway_lp_ability_reg; u16 speed; u16 duplex; /* Check for the case where we have fiber media and auto-neg failed * so we had to force link. In this case, we need to force the * configuration of the MAC to match the "fc" parameter. */ if (((hw->media_type == e1000_media_type_fiber) && (hw->autoneg_failed)) || ((hw->media_type == e1000_media_type_internal_serdes) && (hw->autoneg_failed)) || ((hw->media_type == e1000_media_type_copper) && (!hw->autoneg))) { ret_val = e1000_force_mac_fc(hw); if (ret_val) { e_dbg("Error forcing flow control settings\n"); return ret_val; } } /* Check for the case where we have copper media and auto-neg is * enabled. In this case, we need to check and see if Auto-Neg * has completed, and if so, how the PHY and link partner has * flow control configured. */ if ((hw->media_type == e1000_media_type_copper) && hw->autoneg) { /* Read the MII Status Register and check to see if AutoNeg * has completed. We read this twice because this reg has * some "sticky" (latched) bits. */ ret_val = e1000_read_phy_reg(hw, PHY_STATUS, &mii_status_reg); if (ret_val) return ret_val; ret_val = e1000_read_phy_reg(hw, PHY_STATUS, &mii_status_reg); if (ret_val) return ret_val; if (mii_status_reg & MII_SR_AUTONEG_COMPLETE) { /* The AutoNeg process has completed, so we now need to * read both the Auto Negotiation Advertisement Register * (Address 4) and the Auto_Negotiation Base Page * Ability Register (Address 5) to determine how flow * control was negotiated. */ ret_val = e1000_read_phy_reg(hw, PHY_AUTONEG_ADV, &mii_nway_adv_reg); if (ret_val) return ret_val; ret_val = e1000_read_phy_reg(hw, PHY_LP_ABILITY, &mii_nway_lp_ability_reg); if (ret_val) return ret_val; /* Two bits in the Auto Negotiation Advertisement * Register (Address 4) and two bits in the Auto * Negotiation Base Page Ability Register (Address 5) * determine flow control for both the PHY and the link * partner. The following table, taken out of the IEEE * 802.3ab/D6.0 dated March 25, 1999, describes these * PAUSE resolution bits and how flow control is * determined based upon these settings. * NOTE: DC = Don't Care * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | NIC Resolution *-------|---------|-------|---------|------------------ * 0 | 0 | DC | DC | E1000_FC_NONE * 0 | 1 | 0 | DC | E1000_FC_NONE * 0 | 1 | 1 | 0 | E1000_FC_NONE * 0 | 1 | 1 | 1 | E1000_FC_TX_PAUSE * 1 | 0 | 0 | DC | E1000_FC_NONE * 1 | DC | 1 | DC | E1000_FC_FULL * 1 | 1 | 0 | 0 | E1000_FC_NONE * 1 | 1 | 0 | 1 | E1000_FC_RX_PAUSE * */ /* Are both PAUSE bits set to 1? If so, this implies * Symmetric Flow Control is enabled at both ends. The * ASM_DIR bits are irrelevant per the spec. * * For Symmetric Flow Control: * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result *-------|---------|-------|---------|------------------ * 1 | DC | 1 | DC | E1000_FC_FULL * */ if ((mii_nway_adv_reg & NWAY_AR_PAUSE) && (mii_nway_lp_ability_reg & NWAY_LPAR_PAUSE)) { /* Now we need to check if the user selected Rx * ONLY of pause frames. In this case, we had * to advertise FULL flow control because we * could not advertise Rx ONLY. Hence, we must * now check to see if we need to turn OFF the * TRANSMISSION of PAUSE frames. */ if (hw->original_fc == E1000_FC_FULL) { hw->fc = E1000_FC_FULL; e_dbg("Flow Control = FULL.\n"); } else { hw->fc = E1000_FC_RX_PAUSE; e_dbg ("Flow Control = RX PAUSE frames only.\n"); } } /* For receiving PAUSE frames ONLY. * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result *-------|---------|-------|---------|------------------ * 0 | 1 | 1 | 1 | E1000_FC_TX_PAUSE * */ else if (!(mii_nway_adv_reg & NWAY_AR_PAUSE) && (mii_nway_adv_reg & NWAY_AR_ASM_DIR) && (mii_nway_lp_ability_reg & NWAY_LPAR_PAUSE) && (mii_nway_lp_ability_reg & NWAY_LPAR_ASM_DIR)) { hw->fc = E1000_FC_TX_PAUSE; e_dbg ("Flow Control = TX PAUSE frames only.\n"); } /* For transmitting PAUSE frames ONLY. * * LOCAL DEVICE | LINK PARTNER * PAUSE | ASM_DIR | PAUSE | ASM_DIR | Result *-------|---------|-------|---------|------------------ * 1 | 1 | 0 | 1 | E1000_FC_RX_PAUSE * */ else if ((mii_nway_adv_reg & NWAY_AR_PAUSE) && (mii_nway_adv_reg & NWAY_AR_ASM_DIR) && !(mii_nway_lp_ability_reg & NWAY_LPAR_PAUSE) && (mii_nway_lp_ability_reg & NWAY_LPAR_ASM_DIR)) { hw->fc = E1000_FC_RX_PAUSE; e_dbg ("Flow Control = RX PAUSE frames only.\n"); } /* Per the IEEE spec, at this point flow control should * be disabled. However, we want to consider that we * could be connected to a legacy switch that doesn't * advertise desired flow control, but can be forced on * the link partner. So if we advertised no flow * control, that is what we will resolve to. If we * advertised some kind of receive capability (Rx Pause * Only or Full Flow Control) and the link partner * advertised none, we will configure ourselves to * enable Rx Flow Control only. We can do this safely * for two reasons: If the link partner really * didn't want flow control enabled, and we enable Rx, * no harm done since we won't be receiving any PAUSE * frames anyway. If the intent on the link partner was * to have flow control enabled, then by us enabling Rx * only, we can at least receive pause frames and * process them. This is a good idea because in most * cases, since we are predominantly a server NIC, more * times than not we will be asked to delay transmission * of packets than asking our link partner to pause * transmission of frames. */ else if ((hw->original_fc == E1000_FC_NONE || hw->original_fc == E1000_FC_TX_PAUSE) || hw->fc_strict_ieee) { hw->fc = E1000_FC_NONE; e_dbg("Flow Control = NONE.\n"); } else { hw->fc = E1000_FC_RX_PAUSE; e_dbg ("Flow Control = RX PAUSE frames only.\n"); } /* Now we need to do one last check... If we auto- * negotiated to HALF DUPLEX, flow control should not be * enabled per IEEE 802.3 spec. */ ret_val = e1000_get_speed_and_duplex(hw, &speed, &duplex); if (ret_val) { e_dbg ("Error getting link speed and duplex\n"); return ret_val; } if (duplex == HALF_DUPLEX) hw->fc = E1000_FC_NONE; /* Now we call a subroutine to actually force the MAC * controller to use the correct flow control settings. */ ret_val = e1000_force_mac_fc(hw); if (ret_val) { e_dbg ("Error forcing flow control settings\n"); return ret_val; } } else { e_dbg ("Copper PHY and Auto Neg has not completed.\n"); } } return E1000_SUCCESS; } /** * e1000_check_for_serdes_link_generic - Check for link (Serdes) * @hw: pointer to the HW structure * * Checks for link up on the hardware. If link is not up and we have * a signal, then we need to force link up. */ static s32 e1000_check_for_serdes_link_generic(struct e1000_hw *hw) { u32 rxcw; u32 ctrl; u32 status; s32 ret_val = E1000_SUCCESS; ctrl = er32(CTRL); status = er32(STATUS); rxcw = er32(RXCW); /* If we don't have link (auto-negotiation failed or link partner * cannot auto-negotiate), and our link partner is not trying to * auto-negotiate with us (we are receiving idles or data), * we need to force link up. We also need to give auto-negotiation * time to complete. */ /* (ctrl & E1000_CTRL_SWDPIN1) == 1 == have signal */ if ((!(status & E1000_STATUS_LU)) && (!(rxcw & E1000_RXCW_C))) { if (hw->autoneg_failed == 0) { hw->autoneg_failed = 1; goto out; } e_dbg("NOT RXing /C/, disable AutoNeg and force link.\n"); /* Disable auto-negotiation in the TXCW register */ ew32(TXCW, (hw->txcw & ~E1000_TXCW_ANE)); /* Force link-up and also force full-duplex. */ ctrl = er32(CTRL); ctrl |= (E1000_CTRL_SLU | E1000_CTRL_FD); ew32(CTRL, ctrl); /* Configure Flow Control after forcing link up. */ ret_val = e1000_config_fc_after_link_up(hw); if (ret_val) { e_dbg("Error configuring flow control\n"); goto out; } } else if ((ctrl & E1000_CTRL_SLU) && (rxcw & E1000_RXCW_C)) { /* If we are forcing link and we are receiving /C/ ordered * sets, re-enable auto-negotiation in the TXCW register * and disable forced link in the Device Control register * in an attempt to auto-negotiate with our link partner. */ e_dbg("RXing /C/, enable AutoNeg and stop forcing link.\n"); ew32(TXCW, hw->txcw); ew32(CTRL, (ctrl & ~E1000_CTRL_SLU)); hw->serdes_has_link = true; } else if (!(E1000_TXCW_ANE & er32(TXCW))) { /* If we force link for non-auto-negotiation switch, check * link status based on MAC synchronization for internal * serdes media type. */ /* SYNCH bit and IV bit are sticky. */ udelay(10); rxcw = er32(RXCW); if (rxcw & E1000_RXCW_SYNCH) { if (!(rxcw & E1000_RXCW_IV)) { hw->serdes_has_link = true; e_dbg("SERDES: Link up - forced.\n"); } } else { hw->serdes_has_link = false; e_dbg("SERDES: Link down - force failed.\n"); } } if (E1000_TXCW_ANE & er32(TXCW)) { status = er32(STATUS); if (status & E1000_STATUS_LU) { /* SYNCH bit and IV bit are sticky, so reread rxcw. */ udelay(10); rxcw = er32(RXCW); if (rxcw & E1000_RXCW_SYNCH) { if (!(rxcw & E1000_RXCW_IV)) { hw->serdes_has_link = true; e_dbg("SERDES: Link up - autoneg " "completed successfully.\n"); } else { hw->serdes_has_link = false; e_dbg("SERDES: Link down - invalid" "codewords detected in autoneg.\n"); } } else { hw->serdes_has_link = false; e_dbg("SERDES: Link down - no sync.\n"); } } else { hw->serdes_has_link = false; e_dbg("SERDES: Link down - autoneg failed\n"); } } out: return ret_val; } /** * e1000_check_for_link * @hw: Struct containing variables accessed by shared code * * Checks to see if the link status of the hardware has changed. * Called by any function that needs to check the link status of the adapter. */ s32 e1000_check_for_link(struct e1000_hw *hw) { u32 status; u32 rctl; u32 icr; s32 ret_val; u16 phy_data; er32(CTRL); status = er32(STATUS); /* On adapters with a MAC newer than 82544, SW Definable pin 1 will be * set when the optics detect a signal. On older adapters, it will be * cleared when there is a signal. This applies to fiber media only. */ if ((hw->media_type == e1000_media_type_fiber) || (hw->media_type == e1000_media_type_internal_serdes)) { er32(RXCW); if (hw->media_type == e1000_media_type_fiber) { if (status & E1000_STATUS_LU) hw->get_link_status = false; } } /* If we have a copper PHY then we only want to go out to the PHY * registers to see if Auto-Neg has completed and/or if our link * status has changed. The get_link_status flag will be set if we * receive a Link Status Change interrupt or we have Rx Sequence * Errors. */ if ((hw->media_type == e1000_media_type_copper) && hw->get_link_status) { /* First we want to see if the MII Status Register reports * link. If so, then we want to get the current speed/duplex * of the PHY. * Read the register twice since the link bit is sticky. */ ret_val = e1000_read_phy_reg(hw, PHY_STATUS, &phy_data); if (ret_val) return ret_val; ret_val = e1000_read_phy_reg(hw, PHY_STATUS, &phy_data); if (ret_val) return ret_val; if (phy_data & MII_SR_LINK_STATUS) { hw->get_link_status = false; /* Check if there was DownShift, must be checked * immediately after link-up */ e1000_check_downshift(hw); /* If we are on 82544 or 82543 silicon and speed/duplex * are forced to 10H or 10F, then we will implement the * polarity reversal workaround. We disable interrupts * first, and upon returning, place the devices * interrupt state to its previous value except for the * link status change interrupt which will * happen due to the execution of this workaround. */ if ((hw->mac_type == e1000_82544 || hw->mac_type == e1000_82543) && (!hw->autoneg) && (hw->forced_speed_duplex == e1000_10_full || hw->forced_speed_duplex == e1000_10_half)) { ew32(IMC, 0xffffffff); ret_val = e1000_polarity_reversal_workaround(hw); icr = er32(ICR); ew32(ICS, (icr & ~E1000_ICS_LSC)); ew32(IMS, IMS_ENABLE_MASK); } } else { /* No link detected */ e1000_config_dsp_after_link_change(hw, false); return 0; } /* If we are forcing speed/duplex, then we simply return since * we have already determined whether we have link or not. */ if (!hw->autoneg) return -E1000_ERR_CONFIG; /* optimize the dsp settings for the igp phy */ e1000_config_dsp_after_link_change(hw, true); /* We have a M88E1000 PHY and Auto-Neg is enabled. If we * have Si on board that is 82544 or newer, Auto * Speed Detection takes care of MAC speed/duplex * configuration. So we only need to configure Collision * Distance in the MAC. Otherwise, we need to force * speed/duplex on the MAC to the current PHY speed/duplex * settings. */ if ((hw->mac_type >= e1000_82544) && (hw->mac_type != e1000_ce4100)) e1000_config_collision_dist(hw); else { ret_val = e1000_config_mac_to_phy(hw); if (ret_val) { e_dbg ("Error configuring MAC to PHY settings\n"); return ret_val; } } /* Configure Flow Control now that Auto-Neg has completed. * First, we need to restore the desired flow control settings * because we may have had to re-autoneg with a different link * partner. */ ret_val = e1000_config_fc_after_link_up(hw); if (ret_val) { e_dbg("Error configuring flow control\n"); return ret_val; } /* At this point we know that we are on copper and we have * auto-negotiated link. These are conditions for checking the * link partner capability register. We use the link speed to * determine if TBI compatibility needs to be turned on or off. * If the link is not at gigabit speed, then TBI compatibility * is not needed. If we are at gigabit speed, we turn on TBI * compatibility. */ if (hw->tbi_compatibility_en) { u16 speed, duplex; ret_val = e1000_get_speed_and_duplex(hw, &speed, &duplex); if (ret_val) { e_dbg ("Error getting link speed and duplex\n"); return ret_val; } if (speed != SPEED_1000) { /* If link speed is not set to gigabit speed, we * do not need to enable TBI compatibility. */ if (hw->tbi_compatibility_on) { /* If we previously were in the mode, * turn it off. */ rctl = er32(RCTL); rctl &= ~E1000_RCTL_SBP; ew32(RCTL, rctl); hw->tbi_compatibility_on = false; } } else { /* If TBI compatibility is was previously off, * turn it on. For compatibility with a TBI link * partner, we will store bad packets. Some * frames have an additional byte on the end and * will look like CRC errors to the hardware. */ if (!hw->tbi_compatibility_on) { hw->tbi_compatibility_on = true; rctl = er32(RCTL); rctl |= E1000_RCTL_SBP; ew32(RCTL, rctl); } } } } if ((hw->media_type == e1000_media_type_fiber) || (hw->media_type == e1000_media_type_internal_serdes)) e1000_check_for_serdes_link_generic(hw); return E1000_SUCCESS; } /** * e1000_get_speed_and_duplex * @hw: Struct containing variables accessed by shared code * @speed: Speed of the connection * @duplex: Duplex setting of the connection * * Detects the current speed and duplex settings of the hardware. */ s32 e1000_get_speed_and_duplex(struct e1000_hw *hw, u16 *speed, u16 *duplex) { u32 status; s32 ret_val; u16 phy_data; if (hw->mac_type >= e1000_82543) { status = er32(STATUS); if (status & E1000_STATUS_SPEED_1000) { *speed = SPEED_1000; e_dbg("1000 Mbs, "); } else if (status & E1000_STATUS_SPEED_100) { *speed = SPEED_100; e_dbg("100 Mbs, "); } else { *speed = SPEED_10; e_dbg("10 Mbs, "); } if (status & E1000_STATUS_FD) { *duplex = FULL_DUPLEX; e_dbg("Full Duplex\n"); } else { *duplex = HALF_DUPLEX; e_dbg(" Half Duplex\n"); } } else { e_dbg("1000 Mbs, Full Duplex\n"); *speed = SPEED_1000; *duplex = FULL_DUPLEX; } /* IGP01 PHY may advertise full duplex operation after speed downgrade * even if it is operating at half duplex. Here we set the duplex * settings to match the duplex in the link partner's capabilities. */ if (hw->phy_type == e1000_phy_igp && hw->speed_downgraded) { ret_val = e1000_read_phy_reg(hw, PHY_AUTONEG_EXP, &phy_data); if (ret_val) return ret_val; if (!(phy_data & NWAY_ER_LP_NWAY_CAPS)) *duplex = HALF_DUPLEX; else { ret_val = e1000_read_phy_reg(hw, PHY_LP_ABILITY, &phy_data); if (ret_val) return ret_val; if ((*speed == SPEED_100 && !(phy_data & NWAY_LPAR_100TX_FD_CAPS)) || (*speed == SPEED_10 && !(phy_data & NWAY_LPAR_10T_FD_CAPS))) *duplex = HALF_DUPLEX; } } return E1000_SUCCESS; } /** * e1000_wait_autoneg * @hw: Struct containing variables accessed by shared code * * Blocks until autoneg completes or times out (~4.5 seconds) */ static s32 e1000_wait_autoneg(struct e1000_hw *hw) { s32 ret_val; u16 i; u16 phy_data; e_dbg("Waiting for Auto-Neg to complete.\n"); /* We will wait for autoneg to complete or 4.5 seconds to expire. */ for (i = PHY_AUTO_NEG_TIME; i > 0; i--) { /* Read the MII Status Register and wait for Auto-Neg * Complete bit to be set. */ ret_val = e1000_read_phy_reg(hw, PHY_STATUS, &phy_data); if (ret_val) return ret_val; ret_val = e1000_read_phy_reg(hw, PHY_STATUS, &phy_data); if (ret_val) return ret_val; if (phy_data & MII_SR_AUTONEG_COMPLETE) return E1000_SUCCESS; msleep(100); } return E1000_SUCCESS; } /** * e1000_raise_mdi_clk - Raises the Management Data Clock * @hw: Struct containing variables accessed by shared code * @ctrl: Device control register's current value */ static void e1000_raise_mdi_clk(struct e1000_hw *hw, u32 *ctrl) { /* Raise the clock input to the Management Data Clock (by setting the * MDC bit), and then delay 10 microseconds. */ ew32(CTRL, (*ctrl | E1000_CTRL_MDC)); E1000_WRITE_FLUSH(); udelay(10); } /** * e1000_lower_mdi_clk - Lowers the Management Data Clock * @hw: Struct containing variables accessed by shared code * @ctrl: Device control register's current value */ static void e1000_lower_mdi_clk(struct e1000_hw *hw, u32 *ctrl) { /* Lower the clock input to the Management Data Clock (by clearing the * MDC bit), and then delay 10 microseconds. */ ew32(CTRL, (*ctrl & ~E1000_CTRL_MDC)); E1000_WRITE_FLUSH(); udelay(10); } /** * e1000_shift_out_mdi_bits - Shifts data bits out to the PHY * @hw: Struct containing variables accessed by shared code * @data: Data to send out to the PHY * @count: Number of bits to shift out * * Bits are shifted out in MSB to LSB order. */ static void e1000_shift_out_mdi_bits(struct e1000_hw *hw, u32 data, u16 count) { u32 ctrl; u32 mask; /* We need to shift "count" number of bits out to the PHY. So, the value * in the "data" parameter will be shifted out to the PHY one bit at a * time. In order to do this, "data" must be broken down into bits. */ mask = 0x01; mask <<= (count - 1); ctrl = er32(CTRL); /* Set MDIO_DIR and MDC_DIR direction bits to be used as output pins. */ ctrl |= (E1000_CTRL_MDIO_DIR | E1000_CTRL_MDC_DIR); while (mask) { /* A "1" is shifted out to the PHY by setting the MDIO bit to * "1" and then raising and lowering the Management Data Clock. * A "0" is shifted out to the PHY by setting the MDIO bit to * "0" and then raising and lowering the clock. */ if (data & mask) ctrl |= E1000_CTRL_MDIO; else ctrl &= ~E1000_CTRL_MDIO; ew32(CTRL, ctrl); E1000_WRITE_FLUSH(); udelay(10); e1000_raise_mdi_clk(hw, &ctrl); e1000_lower_mdi_clk(hw, &ctrl); mask = mask >> 1; } } /** * e1000_shift_in_mdi_bits - Shifts data bits in from the PHY * @hw: Struct containing variables accessed by shared code * * Bits are shifted in MSB to LSB order. */ static u16 e1000_shift_in_mdi_bits(struct e1000_hw *hw) { u32 ctrl; u16 data = 0; u8 i; /* In order to read a register from the PHY, we need to shift in a total * of 18 bits from the PHY. The first two bit (turnaround) times are * used to avoid contention on the MDIO pin when a read operation is * performed. These two bits are ignored by us and thrown away. Bits are * "shifted in" by raising the input to the Management Data Clock * (setting the MDC bit), and then reading the value of the MDIO bit. */ ctrl = er32(CTRL); /* Clear MDIO_DIR (SWDPIO1) to indicate this bit is to be used as * input. */ ctrl &= ~E1000_CTRL_MDIO_DIR; ctrl &= ~E1000_CTRL_MDIO; ew32(CTRL, ctrl); E1000_WRITE_FLUSH(); /* Raise and Lower the clock before reading in the data. This accounts * for the turnaround bits. The first clock occurred when we clocked out * the last bit of the Register Address. */ e1000_raise_mdi_clk(hw, &ctrl); e1000_lower_mdi_clk(hw, &ctrl); for (data = 0, i = 0; i < 16; i++) { data = data << 1; e1000_raise_mdi_clk(hw, &ctrl); ctrl = er32(CTRL); /* Check to see if we shifted in a "1". */ if (ctrl & E1000_CTRL_MDIO) data |= 1; e1000_lower_mdi_clk(hw, &ctrl); } e1000_raise_mdi_clk(hw, &ctrl); e1000_lower_mdi_clk(hw, &ctrl); return data; } /** * e1000_read_phy_reg - read a phy register * @hw: Struct containing variables accessed by shared code * @reg_addr: address of the PHY register to read * @phy_data: pointer to the value on the PHY register * * Reads the value from a PHY register, if the value is on a specific non zero * page, sets the page first. */ s32 e1000_read_phy_reg(struct e1000_hw *hw, u32 reg_addr, u16 *phy_data) { u32 ret_val; unsigned long flags; spin_lock_irqsave(&e1000_phy_lock, flags); if ((hw->phy_type == e1000_phy_igp) && (reg_addr > MAX_PHY_MULTI_PAGE_REG)) { ret_val = e1000_write_phy_reg_ex(hw, IGP01E1000_PHY_PAGE_SELECT, (u16) reg_addr); if (ret_val) goto out; } ret_val = e1000_read_phy_reg_ex(hw, MAX_PHY_REG_ADDRESS & reg_addr, phy_data); out: spin_unlock_irqrestore(&e1000_phy_lock, flags); return ret_val; } static s32 e1000_read_phy_reg_ex(struct e1000_hw *hw, u32 reg_addr, u16 *phy_data) { u32 i; u32 mdic = 0; const u32 phy_addr = (hw->mac_type == e1000_ce4100) ? hw->phy_addr : 1; if (reg_addr > MAX_PHY_REG_ADDRESS) { e_dbg("PHY Address %d is out of range\n", reg_addr); return -E1000_ERR_PARAM; } if (hw->mac_type > e1000_82543) { /* Set up Op-code, Phy Address, and register address in the MDI * Control register. The MAC will take care of interfacing with * the PHY to retrieve the desired data. */ if (hw->mac_type == e1000_ce4100) { mdic = ((reg_addr << E1000_MDIC_REG_SHIFT) | (phy_addr << E1000_MDIC_PHY_SHIFT) | (INTEL_CE_GBE_MDIC_OP_READ) | (INTEL_CE_GBE_MDIC_GO)); writel(mdic, E1000_MDIO_CMD); /* Poll the ready bit to see if the MDI read * completed */ for (i = 0; i < 64; i++) { udelay(50); mdic = readl(E1000_MDIO_CMD); if (!(mdic & INTEL_CE_GBE_MDIC_GO)) break; } if (mdic & INTEL_CE_GBE_MDIC_GO) { e_dbg("MDI Read did not complete\n"); return -E1000_ERR_PHY; } mdic = readl(E1000_MDIO_STS); if (mdic & INTEL_CE_GBE_MDIC_READ_ERROR) { e_dbg("MDI Read Error\n"); return -E1000_ERR_PHY; } *phy_data = (u16)mdic; } else { mdic = ((reg_addr << E1000_MDIC_REG_SHIFT) | (phy_addr << E1000_MDIC_PHY_SHIFT) | (E1000_MDIC_OP_READ)); ew32(MDIC, mdic); /* Poll the ready bit to see if the MDI read * completed */ for (i = 0; i < 64; i++) { udelay(50); mdic = er32(MDIC); if (mdic & E1000_MDIC_READY) break; } if (!(mdic & E1000_MDIC_READY)) { e_dbg("MDI Read did not complete\n"); return -E1000_ERR_PHY; } if (mdic & E1000_MDIC_ERROR) { e_dbg("MDI Error\n"); return -E1000_ERR_PHY; } *phy_data = (u16)mdic; } } else { /* We must first send a preamble through the MDIO pin to signal * the beginning of an MII instruction. This is done by sending * 32 consecutive "1" bits. */ e1000_shift_out_mdi_bits(hw, PHY_PREAMBLE, PHY_PREAMBLE_SIZE); /* Now combine the next few fields that are required for a read * operation. We use this method instead of calling the * e1000_shift_out_mdi_bits routine five different times. The * format of a MII read instruction consists of a shift out of * 14 bits and is defined as follows: * <Preamble><SOF><Op Code><Phy Addr><Reg Addr> * followed by a shift in of 18 bits. This first two bits * shifted in are TurnAround bits used to avoid contention on * the MDIO pin when a READ operation is performed. These two * bits are thrown away followed by a shift in of 16 bits which * contains the desired data. */ mdic = ((reg_addr) | (phy_addr << 5) | (PHY_OP_READ << 10) | (PHY_SOF << 12)); e1000_shift_out_mdi_bits(hw, mdic, 14); /* Now that we've shifted out the read command to the MII, we * need to "shift in" the 16-bit value (18 total bits) of the * requested PHY register address. */ *phy_data = e1000_shift_in_mdi_bits(hw); } return E1000_SUCCESS; } /** * e1000_write_phy_reg - write a phy register * * @hw: Struct containing variables accessed by shared code * @reg_addr: address of the PHY register to write * @phy_data: data to write to the PHY * * Writes a value to a PHY register */ s32 e1000_write_phy_reg(struct e1000_hw *hw, u32 reg_addr, u16 phy_data) { u32 ret_val; unsigned long flags; spin_lock_irqsave(&e1000_phy_lock, flags); if ((hw->phy_type == e1000_phy_igp) && (reg_addr > MAX_PHY_MULTI_PAGE_REG)) { ret_val = e1000_write_phy_reg_ex(hw, IGP01E1000_PHY_PAGE_SELECT, (u16)reg_addr); if (ret_val) { spin_unlock_irqrestore(&e1000_phy_lock, flags); return ret_val; } } ret_val = e1000_write_phy_reg_ex(hw, MAX_PHY_REG_ADDRESS & reg_addr, phy_data); spin_unlock_irqrestore(&e1000_phy_lock, flags); return ret_val; } static s32 e1000_write_phy_reg_ex(struct e1000_hw *hw, u32 reg_addr, u16 phy_data) { u32 i; u32 mdic = 0; const u32 phy_addr = (hw->mac_type == e1000_ce4100) ? hw->phy_addr : 1; if (reg_addr > MAX_PHY_REG_ADDRESS) { e_dbg("PHY Address %d is out of range\n", reg_addr); return -E1000_ERR_PARAM; } if (hw->mac_type > e1000_82543) { /* Set up Op-code, Phy Address, register address, and data * intended for the PHY register in the MDI Control register. * The MAC will take care of interfacing with the PHY to send * the desired data. */ if (hw->mac_type == e1000_ce4100) { mdic = (((u32)phy_data) | (reg_addr << E1000_MDIC_REG_SHIFT) | (phy_addr << E1000_MDIC_PHY_SHIFT) | (INTEL_CE_GBE_MDIC_OP_WRITE) | (INTEL_CE_GBE_MDIC_GO)); writel(mdic, E1000_MDIO_CMD); /* Poll the ready bit to see if the MDI read * completed */ for (i = 0; i < 640; i++) { udelay(5); mdic = readl(E1000_MDIO_CMD); if (!(mdic & INTEL_CE_GBE_MDIC_GO)) break; } if (mdic & INTEL_CE_GBE_MDIC_GO) { e_dbg("MDI Write did not complete\n"); return -E1000_ERR_PHY; } } else { mdic = (((u32)phy_data) | (reg_addr << E1000_MDIC_REG_SHIFT) | (phy_addr << E1000_MDIC_PHY_SHIFT) | (E1000_MDIC_OP_WRITE)); ew32(MDIC, mdic); /* Poll the ready bit to see if the MDI read * completed */ for (i = 0; i < 641; i++) { udelay(5); mdic = er32(MDIC); if (mdic & E1000_MDIC_READY) break; } if (!(mdic & E1000_MDIC_READY)) { e_dbg("MDI Write did not complete\n"); return -E1000_ERR_PHY; } } } else { /* We'll need to use the SW defined pins to shift the write * command out to the PHY. We first send a preamble to the PHY * to signal the beginning of the MII instruction. This is done * by sending 32 consecutive "1" bits. */ e1000_shift_out_mdi_bits(hw, PHY_PREAMBLE, PHY_PREAMBLE_SIZE); /* Now combine the remaining required fields that will indicate * a write operation. We use this method instead of calling the * e1000_shift_out_mdi_bits routine for each field in the * command. The format of a MII write instruction is as follows: * <Preamble><SOF><OpCode><PhyAddr><RegAddr><Turnaround><Data>. */ mdic = ((PHY_TURNAROUND) | (reg_addr << 2) | (phy_addr << 7) | (PHY_OP_WRITE << 12) | (PHY_SOF << 14)); mdic <<= 16; mdic |= (u32)phy_data; e1000_shift_out_mdi_bits(hw, mdic, 32); } return E1000_SUCCESS; } /** * e1000_phy_hw_reset - reset the phy, hardware style * @hw: Struct containing variables accessed by shared code * * Returns the PHY to the power-on reset state */ s32 e1000_phy_hw_reset(struct e1000_hw *hw) { u32 ctrl, ctrl_ext; u32 led_ctrl; e_dbg("Resetting Phy...\n"); if (hw->mac_type > e1000_82543) { /* Read the device control register and assert the * E1000_CTRL_PHY_RST bit. Then, take it out of reset. * For e1000 hardware, we delay for 10ms between the assert * and de-assert. */ ctrl = er32(CTRL); ew32(CTRL, ctrl | E1000_CTRL_PHY_RST); E1000_WRITE_FLUSH(); msleep(10); ew32(CTRL, ctrl); E1000_WRITE_FLUSH(); } else { /* Read the Extended Device Control Register, assert the * PHY_RESET_DIR bit to put the PHY into reset. Then, take it * out of reset. */ ctrl_ext = er32(CTRL_EXT); ctrl_ext |= E1000_CTRL_EXT_SDP4_DIR; ctrl_ext &= ~E1000_CTRL_EXT_SDP4_DATA; ew32(CTRL_EXT, ctrl_ext); E1000_WRITE_FLUSH(); msleep(10); ctrl_ext |= E1000_CTRL_EXT_SDP4_DATA; ew32(CTRL_EXT, ctrl_ext); E1000_WRITE_FLUSH(); } udelay(150); if ((hw->mac_type == e1000_82541) || (hw->mac_type == e1000_82547)) { /* Configure activity LED after PHY reset */ led_ctrl = er32(LEDCTL); led_ctrl &= IGP_ACTIVITY_LED_MASK; led_ctrl |= (IGP_ACTIVITY_LED_ENABLE | IGP_LED3_MODE); ew32(LEDCTL, led_ctrl); } /* Wait for FW to finish PHY configuration. */ return e1000_get_phy_cfg_done(hw); } /** * e1000_phy_reset - reset the phy to commit settings * @hw: Struct containing variables accessed by shared code * * Resets the PHY * Sets bit 15 of the MII Control register */ s32 e1000_phy_reset(struct e1000_hw *hw) { s32 ret_val; u16 phy_data; switch (hw->phy_type) { case e1000_phy_igp: ret_val = e1000_phy_hw_reset(hw); if (ret_val) return ret_val; break; default: ret_val = e1000_read_phy_reg(hw, PHY_CTRL, &phy_data); if (ret_val) return ret_val; phy_data |= MII_CR_RESET; ret_val = e1000_write_phy_reg(hw, PHY_CTRL, phy_data); if (ret_val) return ret_val; udelay(1); break; } if (hw->phy_type == e1000_phy_igp) e1000_phy_init_script(hw); return E1000_SUCCESS; } /** * e1000_detect_gig_phy - check the phy type * @hw: Struct containing variables accessed by shared code * * Probes the expected PHY address for known PHY IDs */ static s32 e1000_detect_gig_phy(struct e1000_hw *hw) { s32 phy_init_status, ret_val; u16 phy_id_high, phy_id_low; bool match = false; if (hw->phy_id != 0) return E1000_SUCCESS; /* Read the PHY ID Registers to identify which PHY is onboard. */ ret_val = e1000_read_phy_reg(hw, PHY_ID1, &phy_id_high); if (ret_val) return ret_val; hw->phy_id = (u32)(phy_id_high << 16); udelay(20); ret_val = e1000_read_phy_reg(hw, PHY_ID2, &phy_id_low); if (ret_val) return ret_val; hw->phy_id |= (u32)(phy_id_low & PHY_REVISION_MASK); hw->phy_revision = (u32)phy_id_low & ~PHY_REVISION_MASK; switch (hw->mac_type) { case e1000_82543: if (hw->phy_id == M88E1000_E_PHY_ID) match = true; break; case e1000_82544: if (hw->phy_id == M88E1000_I_PHY_ID) match = true; break; case e1000_82540: case e1000_82545: case e1000_82545_rev_3: case e1000_82546: case e1000_82546_rev_3: if (hw->phy_id == M88E1011_I_PHY_ID) match = true; break; case e1000_ce4100: if ((hw->phy_id == RTL8211B_PHY_ID) || (hw->phy_id == RTL8201N_PHY_ID) || (hw->phy_id == M88E1118_E_PHY_ID)) match = true; break; case e1000_82541: case e1000_82541_rev_2: case e1000_82547: case e1000_82547_rev_2: if (hw->phy_id == IGP01E1000_I_PHY_ID) match = true; break; default: e_dbg("Invalid MAC type %d\n", hw->mac_type); return -E1000_ERR_CONFIG; } phy_init_status = e1000_set_phy_type(hw); if ((match) && (phy_init_status == E1000_SUCCESS)) { e_dbg("PHY ID 0x%X detected\n", hw->phy_id); return E1000_SUCCESS; } e_dbg("Invalid PHY ID 0x%X\n", hw->phy_id); return -E1000_ERR_PHY; } /** * e1000_phy_reset_dsp - reset DSP * @hw: Struct containing variables accessed by shared code * * Resets the PHY's DSP */ static s32 e1000_phy_reset_dsp(struct e1000_hw *hw) { s32 ret_val; do { ret_val = e1000_write_phy_reg(hw, 29, 0x001d); if (ret_val) break; ret_val = e1000_write_phy_reg(hw, 30, 0x00c1); if (ret_val) break; ret_val = e1000_write_phy_reg(hw, 30, 0x0000); if (ret_val) break; ret_val = E1000_SUCCESS; } while (0); return ret_val; } /** * e1000_phy_igp_get_info - get igp specific registers * @hw: Struct containing variables accessed by shared code * @phy_info: PHY information structure * * Get PHY information from various PHY registers for igp PHY only. */ static s32 e1000_phy_igp_get_info(struct e1000_hw *hw, struct e1000_phy_info *phy_info) { s32 ret_val; u16 phy_data, min_length, max_length, average; e1000_rev_polarity polarity; /* The downshift status is checked only once, after link is established, * and it stored in the hw->speed_downgraded parameter. */ phy_info->downshift = (e1000_downshift) hw->speed_downgraded; /* IGP01E1000 does not need to support it. */ phy_info->extended_10bt_distance = e1000_10bt_ext_dist_enable_normal; /* IGP01E1000 always correct polarity reversal */ phy_info->polarity_correction = e1000_polarity_reversal_enabled; /* Check polarity status */ ret_val = e1000_check_polarity(hw, &polarity); if (ret_val) return ret_val; phy_info->cable_polarity = polarity; ret_val = e1000_read_phy_reg(hw, IGP01E1000_PHY_PORT_STATUS, &phy_data); if (ret_val) return ret_val; phy_info->mdix_mode = (e1000_auto_x_mode) ((phy_data & IGP01E1000_PSSR_MDIX) >> IGP01E1000_PSSR_MDIX_SHIFT); if ((phy_data & IGP01E1000_PSSR_SPEED_MASK) == IGP01E1000_PSSR_SPEED_1000MBPS) { /* Local/Remote Receiver Information are only valid @ 1000 * Mbps */ ret_val = e1000_read_phy_reg(hw, PHY_1000T_STATUS, &phy_data); if (ret_val) return ret_val; phy_info->local_rx = ((phy_data & SR_1000T_LOCAL_RX_STATUS) >> SR_1000T_LOCAL_RX_STATUS_SHIFT) ? e1000_1000t_rx_status_ok : e1000_1000t_rx_status_not_ok; phy_info->remote_rx = ((phy_data & SR_1000T_REMOTE_RX_STATUS) >> SR_1000T_REMOTE_RX_STATUS_SHIFT) ? e1000_1000t_rx_status_ok : e1000_1000t_rx_status_not_ok; /* Get cable length */ ret_val = e1000_get_cable_length(hw, &min_length, &max_length); if (ret_val) return ret_val; /* Translate to old method */ average = (max_length + min_length) / 2; if (average <= e1000_igp_cable_length_50) phy_info->cable_length = e1000_cable_length_50; else if (average <= e1000_igp_cable_length_80) phy_info->cable_length = e1000_cable_length_50_80; else if (average <= e1000_igp_cable_length_110) phy_info->cable_length = e1000_cable_length_80_110; else if (average <= e1000_igp_cable_length_140) phy_info->cable_length = e1000_cable_length_110_140; else phy_info->cable_length = e1000_cable_length_140; } return E1000_SUCCESS; } /** * e1000_phy_m88_get_info - get m88 specific registers * @hw: Struct containing variables accessed by shared code * @phy_info: PHY information structure * * Get PHY information from various PHY registers for m88 PHY only. */ static s32 e1000_phy_m88_get_info(struct e1000_hw *hw, struct e1000_phy_info *phy_info) { s32 ret_val; u16 phy_data; e1000_rev_polarity polarity; /* The downshift status is checked only once, after link is established, * and it stored in the hw->speed_downgraded parameter. */ phy_info->downshift = (e1000_downshift) hw->speed_downgraded; ret_val = e1000_read_phy_reg(hw, M88E1000_PHY_SPEC_CTRL, &phy_data); if (ret_val) return ret_val; phy_info->extended_10bt_distance = ((phy_data & M88E1000_PSCR_10BT_EXT_DIST_ENABLE) >> M88E1000_PSCR_10BT_EXT_DIST_ENABLE_SHIFT) ? e1000_10bt_ext_dist_enable_lower : e1000_10bt_ext_dist_enable_normal; phy_info->polarity_correction = ((phy_data & M88E1000_PSCR_POLARITY_REVERSAL) >> M88E1000_PSCR_POLARITY_REVERSAL_SHIFT) ? e1000_polarity_reversal_disabled : e1000_polarity_reversal_enabled; /* Check polarity status */ ret_val = e1000_check_polarity(hw, &polarity); if (ret_val) return ret_val; phy_info->cable_polarity = polarity; ret_val = e1000_read_phy_reg(hw, M88E1000_PHY_SPEC_STATUS, &phy_data); if (ret_val) return ret_val; phy_info->mdix_mode = (e1000_auto_x_mode) ((phy_data & M88E1000_PSSR_MDIX) >> M88E1000_PSSR_MDIX_SHIFT); if ((phy_data & M88E1000_PSSR_SPEED) == M88E1000_PSSR_1000MBS) { /* Cable Length Estimation and Local/Remote Receiver Information * are only valid at 1000 Mbps. */ phy_info->cable_length = (e1000_cable_length) ((phy_data & M88E1000_PSSR_CABLE_LENGTH) >> M88E1000_PSSR_CABLE_LENGTH_SHIFT); ret_val = e1000_read_phy_reg(hw, PHY_1000T_STATUS, &phy_data); if (ret_val) return ret_val; phy_info->local_rx = ((phy_data & SR_1000T_LOCAL_RX_STATUS) >> SR_1000T_LOCAL_RX_STATUS_SHIFT) ? e1000_1000t_rx_status_ok : e1000_1000t_rx_status_not_ok; phy_info->remote_rx = ((phy_data & SR_1000T_REMOTE_RX_STATUS) >> SR_1000T_REMOTE_RX_STATUS_SHIFT) ? e1000_1000t_rx_status_ok : e1000_1000t_rx_status_not_ok; } return E1000_SUCCESS; } /** * e1000_phy_get_info - request phy info * @hw: Struct containing variables accessed by shared code * @phy_info: PHY information structure * * Get PHY information from various PHY registers */ s32 e1000_phy_get_info(struct e1000_hw *hw, struct e1000_phy_info *phy_info) { s32 ret_val; u16 phy_data; phy_info->cable_length = e1000_cable_length_undefined; phy_info->extended_10bt_distance = e1000_10bt_ext_dist_enable_undefined; phy_info->cable_polarity = e1000_rev_polarity_undefined; phy_info->downshift = e1000_downshift_undefined; phy_info->polarity_correction = e1000_polarity_reversal_undefined; phy_info->mdix_mode = e1000_auto_x_mode_undefined; phy_info->local_rx = e1000_1000t_rx_status_undefined; phy_info->remote_rx = e1000_1000t_rx_status_undefined; if (hw->media_type != e1000_media_type_copper) { e_dbg("PHY info is only valid for copper media\n"); return -E1000_ERR_CONFIG; } ret_val = e1000_read_phy_reg(hw, PHY_STATUS, &phy_data); if (ret_val) return ret_val; ret_val = e1000_read_phy_reg(hw, PHY_STATUS, &phy_data); if (ret_val) return ret_val; if ((phy_data & MII_SR_LINK_STATUS) != MII_SR_LINK_STATUS) { e_dbg("PHY info is only valid if link is up\n"); return -E1000_ERR_CONFIG; } if (hw->phy_type == e1000_phy_igp) return e1000_phy_igp_get_info(hw, phy_info); else if ((hw->phy_type == e1000_phy_8211) || (hw->phy_type == e1000_phy_8201)) return E1000_SUCCESS; else return e1000_phy_m88_get_info(hw, phy_info); } s32 e1000_validate_mdi_setting(struct e1000_hw *hw) { if (!hw->autoneg && (hw->mdix == 0 || hw->mdix == 3)) { e_dbg("Invalid MDI setting detected\n"); hw->mdix = 1; return -E1000_ERR_CONFIG; } return E1000_SUCCESS; } /** * e1000_init_eeprom_params - initialize sw eeprom vars * @hw: Struct containing variables accessed by shared code * * Sets up eeprom variables in the hw struct. Must be called after mac_type * is configured. */ s32 e1000_init_eeprom_params(struct e1000_hw *hw) { struct e1000_eeprom_info *eeprom = &hw->eeprom; u32 eecd = er32(EECD); s32 ret_val = E1000_SUCCESS; u16 eeprom_size; switch (hw->mac_type) { case e1000_82542_rev2_0: case e1000_82542_rev2_1: case e1000_82543: case e1000_82544: eeprom->type = e1000_eeprom_microwire; eeprom->word_size = 64; eeprom->opcode_bits = 3; eeprom->address_bits = 6; eeprom->delay_usec = 50; break; case e1000_82540: case e1000_82545: case e1000_82545_rev_3: case e1000_82546: case e1000_82546_rev_3: eeprom->type = e1000_eeprom_microwire; eeprom->opcode_bits = 3; eeprom->delay_usec = 50; if (eecd & E1000_EECD_SIZE) { eeprom->word_size = 256; eeprom->address_bits = 8; } else { eeprom->word_size = 64; eeprom->address_bits = 6; } break; case e1000_82541: case e1000_82541_rev_2: case e1000_82547: case e1000_82547_rev_2: if (eecd & E1000_EECD_TYPE) { eeprom->type = e1000_eeprom_spi; eeprom->opcode_bits = 8; eeprom->delay_usec = 1; if (eecd & E1000_EECD_ADDR_BITS) { eeprom->page_size = 32; eeprom->address_bits = 16; } else { eeprom->page_size = 8; eeprom->address_bits = 8; } } else { eeprom->type = e1000_eeprom_microwire; eeprom->opcode_bits = 3; eeprom->delay_usec = 50; if (eecd & E1000_EECD_ADDR_BITS) { eeprom->word_size = 256; eeprom->address_bits = 8; } else { eeprom->word_size = 64; eeprom->address_bits = 6; } } break; default: break; } if (eeprom->type == e1000_eeprom_spi) { /* eeprom_size will be an enum [0..8] that maps to eeprom sizes * 128B to 32KB (incremented by powers of 2). */ /* Set to default value for initial eeprom read. */ eeprom->word_size = 64; ret_val = e1000_read_eeprom(hw, EEPROM_CFG, 1, &eeprom_size); if (ret_val) return ret_val; eeprom_size = (eeprom_size & EEPROM_SIZE_MASK) >> EEPROM_SIZE_SHIFT; /* 256B eeprom size was not supported in earlier hardware, so we * bump eeprom_size up one to ensure that "1" (which maps to * 256B) is never the result used in the shifting logic below. */ if (eeprom_size) eeprom_size++; eeprom->word_size = 1 << (eeprom_size + EEPROM_WORD_SIZE_SHIFT); } return ret_val; } /** * e1000_raise_ee_clk - Raises the EEPROM's clock input. * @hw: Struct containing variables accessed by shared code * @eecd: EECD's current value */ static void e1000_raise_ee_clk(struct e1000_hw *hw, u32 *eecd) { /* Raise the clock input to the EEPROM (by setting the SK bit), and then * wait <delay> microseconds. */ *eecd = *eecd | E1000_EECD_SK; ew32(EECD, *eecd); E1000_WRITE_FLUSH(); udelay(hw->eeprom.delay_usec); } /** * e1000_lower_ee_clk - Lowers the EEPROM's clock input. * @hw: Struct containing variables accessed by shared code * @eecd: EECD's current value */ static void e1000_lower_ee_clk(struct e1000_hw *hw, u32 *eecd) { /* Lower the clock input to the EEPROM (by clearing the SK bit), and * then wait 50 microseconds. */ *eecd = *eecd & ~E1000_EECD_SK; ew32(EECD, *eecd); E1000_WRITE_FLUSH(); udelay(hw->eeprom.delay_usec); } /** * e1000_shift_out_ee_bits - Shift data bits out to the EEPROM. * @hw: Struct containing variables accessed by shared code * @data: data to send to the EEPROM * @count: number of bits to shift out */ static void e1000_shift_out_ee_bits(struct e1000_hw *hw, u16 data, u16 count) { struct e1000_eeprom_info *eeprom = &hw->eeprom; u32 eecd; u32 mask; /* We need to shift "count" bits out to the EEPROM. So, value in the * "data" parameter will be shifted out to the EEPROM one bit at a time. * In order to do this, "data" must be broken down into bits. */ mask = 0x01 << (count - 1); eecd = er32(EECD); if (eeprom->type == e1000_eeprom_microwire) eecd &= ~E1000_EECD_DO; else if (eeprom->type == e1000_eeprom_spi) eecd |= E1000_EECD_DO; do { /* A "1" is shifted out to the EEPROM by setting bit "DI" to a * "1", and then raising and then lowering the clock (the SK bit * controls the clock input to the EEPROM). A "0" is shifted * out to the EEPROM by setting "DI" to "0" and then raising and * then lowering the clock. */ eecd &= ~E1000_EECD_DI; if (data & mask) eecd |= E1000_EECD_DI; ew32(EECD, eecd); E1000_WRITE_FLUSH(); udelay(eeprom->delay_usec); e1000_raise_ee_clk(hw, &eecd); e1000_lower_ee_clk(hw, &eecd); mask = mask >> 1; } while (mask); /* We leave the "DI" bit set to "0" when we leave this routine. */ eecd &= ~E1000_EECD_DI; ew32(EECD, eecd); } /** * e1000_shift_in_ee_bits - Shift data bits in from the EEPROM * @hw: Struct containing variables accessed by shared code * @count: number of bits to shift in */ static u16 e1000_shift_in_ee_bits(struct e1000_hw *hw, u16 count) { u32 eecd; u32 i; u16 data; /* In order to read a register from the EEPROM, we need to shift 'count' * bits in from the EEPROM. Bits are "shifted in" by raising the clock * input to the EEPROM (setting the SK bit), and then reading the value * of the "DO" bit. During this "shifting in" process the "DI" bit * should always be clear. */ eecd = er32(EECD); eecd &= ~(E1000_EECD_DO | E1000_EECD_DI); data = 0; for (i = 0; i < count; i++) { data = data << 1; e1000_raise_ee_clk(hw, &eecd); eecd = er32(EECD); eecd &= ~(E1000_EECD_DI); if (eecd & E1000_EECD_DO) data |= 1; e1000_lower_ee_clk(hw, &eecd); } return data; } /** * e1000_acquire_eeprom - Prepares EEPROM for access * @hw: Struct containing variables accessed by shared code * * Lowers EEPROM clock. Clears input pin. Sets the chip select pin. This * function should be called before issuing a command to the EEPROM. */ static s32 e1000_acquire_eeprom(struct e1000_hw *hw) { struct e1000_eeprom_info *eeprom = &hw->eeprom; u32 eecd, i = 0; eecd = er32(EECD); /* Request EEPROM Access */ if (hw->mac_type > e1000_82544) { eecd |= E1000_EECD_REQ; ew32(EECD, eecd); eecd = er32(EECD); while ((!(eecd & E1000_EECD_GNT)) && (i < E1000_EEPROM_GRANT_ATTEMPTS)) { i++; udelay(5); eecd = er32(EECD); } if (!(eecd & E1000_EECD_GNT)) { eecd &= ~E1000_EECD_REQ; ew32(EECD, eecd); e_dbg("Could not acquire EEPROM grant\n"); return -E1000_ERR_EEPROM; } } /* Setup EEPROM for Read/Write */ if (eeprom->type == e1000_eeprom_microwire) { /* Clear SK and DI */ eecd &= ~(E1000_EECD_DI | E1000_EECD_SK); ew32(EECD, eecd); /* Set CS */ eecd |= E1000_EECD_CS; ew32(EECD, eecd); } else if (eeprom->type == e1000_eeprom_spi) { /* Clear SK and CS */ eecd &= ~(E1000_EECD_CS | E1000_EECD_SK); ew32(EECD, eecd); E1000_WRITE_FLUSH(); udelay(1); } return E1000_SUCCESS; } /** * e1000_standby_eeprom - Returns EEPROM to a "standby" state * @hw: Struct containing variables accessed by shared code */ static void e1000_standby_eeprom(struct e1000_hw *hw) { struct e1000_eeprom_info *eeprom = &hw->eeprom; u32 eecd; eecd = er32(EECD); if (eeprom->type == e1000_eeprom_microwire) { eecd &= ~(E1000_EECD_CS | E1000_EECD_SK); ew32(EECD, eecd); E1000_WRITE_FLUSH(); udelay(eeprom->delay_usec); /* Clock high */ eecd |= E1000_EECD_SK; ew32(EECD, eecd); E1000_WRITE_FLUSH(); udelay(eeprom->delay_usec); /* Select EEPROM */ eecd |= E1000_EECD_CS; ew32(EECD, eecd); E1000_WRITE_FLUSH(); udelay(eeprom->delay_usec); /* Clock low */ eecd &= ~E1000_EECD_SK; ew32(EECD, eecd); E1000_WRITE_FLUSH(); udelay(eeprom->delay_usec); } else if (eeprom->type == e1000_eeprom_spi) { /* Toggle CS to flush commands */ eecd |= E1000_EECD_CS; ew32(EECD, eecd); E1000_WRITE_FLUSH(); udelay(eeprom->delay_usec); eecd &= ~E1000_EECD_CS; ew32(EECD, eecd); E1000_WRITE_FLUSH(); udelay(eeprom->delay_usec); } } /** * e1000_release_eeprom - drop chip select * @hw: Struct containing variables accessed by shared code * * Terminates a command by inverting the EEPROM's chip select pin */ static void e1000_release_eeprom(struct e1000_hw *hw) { u32 eecd; eecd = er32(EECD); if (hw->eeprom.type == e1000_eeprom_spi) { eecd |= E1000_EECD_CS; /* Pull CS high */ eecd &= ~E1000_EECD_SK; /* Lower SCK */ ew32(EECD, eecd); E1000_WRITE_FLUSH(); udelay(hw->eeprom.delay_usec); } else if (hw->eeprom.type == e1000_eeprom_microwire) { /* cleanup eeprom */ /* CS on Microwire is active-high */ eecd &= ~(E1000_EECD_CS | E1000_EECD_DI); ew32(EECD, eecd); /* Rising edge of clock */ eecd |= E1000_EECD_SK; ew32(EECD, eecd); E1000_WRITE_FLUSH(); udelay(hw->eeprom.delay_usec); /* Falling edge of clock */ eecd &= ~E1000_EECD_SK; ew32(EECD, eecd); E1000_WRITE_FLUSH(); udelay(hw->eeprom.delay_usec); } /* Stop requesting EEPROM access */ if (hw->mac_type > e1000_82544) { eecd &= ~E1000_EECD_REQ; ew32(EECD, eecd); } } /** * e1000_spi_eeprom_ready - Reads a 16 bit word from the EEPROM. * @hw: Struct containing variables accessed by shared code */ static s32 e1000_spi_eeprom_ready(struct e1000_hw *hw) { u16 retry_count = 0; u8 spi_stat_reg; /* Read "Status Register" repeatedly until the LSB is cleared. The * EEPROM will signal that the command has been completed by clearing * bit 0 of the internal status register. If it's not cleared within * 5 milliseconds, then error out. */ retry_count = 0; do { e1000_shift_out_ee_bits(hw, EEPROM_RDSR_OPCODE_SPI, hw->eeprom.opcode_bits); spi_stat_reg = (u8)e1000_shift_in_ee_bits(hw, 8); if (!(spi_stat_reg & EEPROM_STATUS_RDY_SPI)) break; udelay(5); retry_count += 5; e1000_standby_eeprom(hw); } while (retry_count < EEPROM_MAX_RETRY_SPI); /* ATMEL SPI write time could vary from 0-20mSec on 3.3V devices (and * only 0-5mSec on 5V devices) */ if (retry_count >= EEPROM_MAX_RETRY_SPI) { e_dbg("SPI EEPROM Status error\n"); return -E1000_ERR_EEPROM; } return E1000_SUCCESS; } /** * e1000_read_eeprom - Reads a 16 bit word from the EEPROM. * @hw: Struct containing variables accessed by shared code * @offset: offset of word in the EEPROM to read * @data: word read from the EEPROM * @words: number of words to read */ s32 e1000_read_eeprom(struct e1000_hw *hw, u16 offset, u16 words, u16 *data) { s32 ret; mutex_lock(&e1000_eeprom_lock); ret = e1000_do_read_eeprom(hw, offset, words, data); mutex_unlock(&e1000_eeprom_lock); return ret; } static s32 e1000_do_read_eeprom(struct e1000_hw *hw, u16 offset, u16 words, u16 *data) { struct e1000_eeprom_info *eeprom = &hw->eeprom; u32 i = 0; if (hw->mac_type == e1000_ce4100) { GBE_CONFIG_FLASH_READ(GBE_CONFIG_BASE_VIRT, offset, words, data); return E1000_SUCCESS; } /* A check for invalid values: offset too large, too many words, and * not enough words. */ if ((offset >= eeprom->word_size) || (words > eeprom->word_size - offset) || (words == 0)) { e_dbg("\"words\" parameter out of bounds. Words = %d," "size = %d\n", offset, eeprom->word_size); return -E1000_ERR_EEPROM; } /* EEPROM's that don't use EERD to read require us to bit-bang the SPI * directly. In this case, we need to acquire the EEPROM so that * FW or other port software does not interrupt. */ /* Prepare the EEPROM for bit-bang reading */ if (e1000_acquire_eeprom(hw) != E1000_SUCCESS) return -E1000_ERR_EEPROM; /* Set up the SPI or Microwire EEPROM for bit-bang reading. We have * acquired the EEPROM at this point, so any returns should release it */ if (eeprom->type == e1000_eeprom_spi) { u16 word_in; u8 read_opcode = EEPROM_READ_OPCODE_SPI; if (e1000_spi_eeprom_ready(hw)) { e1000_release_eeprom(hw); return -E1000_ERR_EEPROM; } e1000_standby_eeprom(hw); /* Some SPI eeproms use the 8th address bit embedded in the * opcode */ if ((eeprom->address_bits == 8) && (offset >= 128)) read_opcode |= EEPROM_A8_OPCODE_SPI; /* Send the READ command (opcode + addr) */ e1000_shift_out_ee_bits(hw, read_opcode, eeprom->opcode_bits); e1000_shift_out_ee_bits(hw, (u16)(offset * 2), eeprom->address_bits); /* Read the data. The address of the eeprom internally * increments with each byte (spi) being read, saving on the * overhead of eeprom setup and tear-down. The address counter * will roll over if reading beyond the size of the eeprom, thus * allowing the entire memory to be read starting from any * offset. */ for (i = 0; i < words; i++) { word_in = e1000_shift_in_ee_bits(hw, 16); data[i] = (word_in >> 8) | (word_in << 8); } } else if (eeprom->type == e1000_eeprom_microwire) { for (i = 0; i < words; i++) { /* Send the READ command (opcode + addr) */ e1000_shift_out_ee_bits(hw, EEPROM_READ_OPCODE_MICROWIRE, eeprom->opcode_bits); e1000_shift_out_ee_bits(hw, (u16)(offset + i), eeprom->address_bits); /* Read the data. For microwire, each word requires the * overhead of eeprom setup and tear-down. */ data[i] = e1000_shift_in_ee_bits(hw, 16); e1000_standby_eeprom(hw); cond_resched(); } } /* End this read operation */ e1000_release_eeprom(hw); return E1000_SUCCESS; } /** * e1000_validate_eeprom_checksum - Verifies that the EEPROM has a valid checksum * @hw: Struct containing variables accessed by shared code * * Reads the first 64 16 bit words of the EEPROM and sums the values read. * If the sum of the 64 16 bit words is 0xBABA, the EEPROM's checksum is * valid. */ s32 e1000_validate_eeprom_checksum(struct e1000_hw *hw) { u16 checksum = 0; u16 i, eeprom_data; for (i = 0; i < (EEPROM_CHECKSUM_REG + 1); i++) { if (e1000_read_eeprom(hw, i, 1, &eeprom_data) < 0) { e_dbg("EEPROM Read Error\n"); return -E1000_ERR_EEPROM; } checksum += eeprom_data; } #ifdef CONFIG_PARISC /* This is a signature and not a checksum on HP c8000 */ if ((hw->subsystem_vendor_id == 0x103C) && (eeprom_data == 0x16d6)) return E1000_SUCCESS; #endif if (checksum == (u16)EEPROM_SUM) return E1000_SUCCESS; else { e_dbg("EEPROM Checksum Invalid\n"); return -E1000_ERR_EEPROM; } } /** * e1000_update_eeprom_checksum - Calculates/writes the EEPROM checksum * @hw: Struct containing variables accessed by shared code * * Sums the first 63 16 bit words of the EEPROM. Subtracts the sum from 0xBABA. * Writes the difference to word offset 63 of the EEPROM. */ s32 e1000_update_eeprom_checksum(struct e1000_hw *hw) { u16 checksum = 0; u16 i, eeprom_data; for (i = 0; i < EEPROM_CHECKSUM_REG; i++) { if (e1000_read_eeprom(hw, i, 1, &eeprom_data) < 0) { e_dbg("EEPROM Read Error\n"); return -E1000_ERR_EEPROM; } checksum += eeprom_data; } checksum = (u16)EEPROM_SUM - checksum; if (e1000_write_eeprom(hw, EEPROM_CHECKSUM_REG, 1, &checksum) < 0) { e_dbg("EEPROM Write Error\n"); return -E1000_ERR_EEPROM; } return E1000_SUCCESS; } /** * e1000_write_eeprom - write words to the different EEPROM types. * @hw: Struct containing variables accessed by shared code * @offset: offset within the EEPROM to be written to * @words: number of words to write * @data: 16 bit word to be written to the EEPROM * * If e1000_update_eeprom_checksum is not called after this function, the * EEPROM will most likely contain an invalid checksum. */ s32 e1000_write_eeprom(struct e1000_hw *hw, u16 offset, u16 words, u16 *data) { s32 ret; mutex_lock(&e1000_eeprom_lock); ret = e1000_do_write_eeprom(hw, offset, words, data); mutex_unlock(&e1000_eeprom_lock); return ret; } static s32 e1000_do_write_eeprom(struct e1000_hw *hw, u16 offset, u16 words, u16 *data) { struct e1000_eeprom_info *eeprom = &hw->eeprom; s32 status = 0; if (hw->mac_type == e1000_ce4100) { GBE_CONFIG_FLASH_WRITE(GBE_CONFIG_BASE_VIRT, offset, words, data); return E1000_SUCCESS; } /* A check for invalid values: offset too large, too many words, and * not enough words. */ if ((offset >= eeprom->word_size) || (words > eeprom->word_size - offset) || (words == 0)) { e_dbg("\"words\" parameter out of bounds\n"); return -E1000_ERR_EEPROM; } /* Prepare the EEPROM for writing */ if (e1000_acquire_eeprom(hw) != E1000_SUCCESS) return -E1000_ERR_EEPROM; if (eeprom->type == e1000_eeprom_microwire) { status = e1000_write_eeprom_microwire(hw, offset, words, data); } else { status = e1000_write_eeprom_spi(hw, offset, words, data); msleep(10); } /* Done with writing */ e1000_release_eeprom(hw); return status; } /** * e1000_write_eeprom_spi - Writes a 16 bit word to a given offset in an SPI EEPROM. * @hw: Struct containing variables accessed by shared code * @offset: offset within the EEPROM to be written to * @words: number of words to write * @data: pointer to array of 8 bit words to be written to the EEPROM */ static s32 e1000_write_eeprom_spi(struct e1000_hw *hw, u16 offset, u16 words, u16 *data) { struct e1000_eeprom_info *eeprom = &hw->eeprom; u16 widx = 0; while (widx < words) { u8 write_opcode = EEPROM_WRITE_OPCODE_SPI; if (e1000_spi_eeprom_ready(hw)) return -E1000_ERR_EEPROM; e1000_standby_eeprom(hw); cond_resched(); /* Send the WRITE ENABLE command (8 bit opcode ) */ e1000_shift_out_ee_bits(hw, EEPROM_WREN_OPCODE_SPI, eeprom->opcode_bits); e1000_standby_eeprom(hw); /* Some SPI eeproms use the 8th address bit embedded in the * opcode */ if ((eeprom->address_bits == 8) && (offset >= 128)) write_opcode |= EEPROM_A8_OPCODE_SPI; /* Send the Write command (8-bit opcode + addr) */ e1000_shift_out_ee_bits(hw, write_opcode, eeprom->opcode_bits); e1000_shift_out_ee_bits(hw, (u16)((offset + widx) * 2), eeprom->address_bits); /* Send the data */ /* Loop to allow for up to whole page write (32 bytes) of * eeprom */ while (widx < words) { u16 word_out = data[widx]; word_out = (word_out >> 8) | (word_out << 8); e1000_shift_out_ee_bits(hw, word_out, 16); widx++; /* Some larger eeprom sizes are capable of a 32-byte * PAGE WRITE operation, while the smaller eeproms are * capable of an 8-byte PAGE WRITE operation. Break the * inner loop to pass new address */ if ((((offset + widx) * 2) % eeprom->page_size) == 0) { e1000_standby_eeprom(hw); break; } } } return E1000_SUCCESS; } /** * e1000_write_eeprom_microwire - Writes a 16 bit word to a given offset in a Microwire EEPROM. * @hw: Struct containing variables accessed by shared code * @offset: offset within the EEPROM to be written to * @words: number of words to write * @data: pointer to array of 8 bit words to be written to the EEPROM */ static s32 e1000_write_eeprom_microwire(struct e1000_hw *hw, u16 offset, u16 words, u16 *data) { struct e1000_eeprom_info *eeprom = &hw->eeprom; u32 eecd; u16 words_written = 0; u16 i = 0; /* Send the write enable command to the EEPROM (3-bit opcode plus * 6/8-bit dummy address beginning with 11). It's less work to include * the 11 of the dummy address as part of the opcode than it is to shift * it over the correct number of bits for the address. This puts the * EEPROM into write/erase mode. */ e1000_shift_out_ee_bits(hw, EEPROM_EWEN_OPCODE_MICROWIRE, (u16)(eeprom->opcode_bits + 2)); e1000_shift_out_ee_bits(hw, 0, (u16)(eeprom->address_bits - 2)); /* Prepare the EEPROM */ e1000_standby_eeprom(hw); while (words_written < words) { /* Send the Write command (3-bit opcode + addr) */ e1000_shift_out_ee_bits(hw, EEPROM_WRITE_OPCODE_MICROWIRE, eeprom->opcode_bits); e1000_shift_out_ee_bits(hw, (u16)(offset + words_written), eeprom->address_bits); /* Send the data */ e1000_shift_out_ee_bits(hw, data[words_written], 16); /* Toggle the CS line. This in effect tells the EEPROM to * execute the previous command. */ e1000_standby_eeprom(hw); /* Read DO repeatedly until it is high (equal to '1'). The * EEPROM will signal that the command has been completed by * raising the DO signal. If DO does not go high in 10 * milliseconds, then error out. */ for (i = 0; i < 200; i++) { eecd = er32(EECD); if (eecd & E1000_EECD_DO) break; udelay(50); } if (i == 200) { e_dbg("EEPROM Write did not complete\n"); return -E1000_ERR_EEPROM; } /* Recover from write */ e1000_standby_eeprom(hw); cond_resched(); words_written++; } /* Send the write disable command to the EEPROM (3-bit opcode plus * 6/8-bit dummy address beginning with 10). It's less work to include * the 10 of the dummy address as part of the opcode than it is to shift * it over the correct number of bits for the address. This takes the * EEPROM out of write/erase mode. */ e1000_shift_out_ee_bits(hw, EEPROM_EWDS_OPCODE_MICROWIRE, (u16)(eeprom->opcode_bits + 2)); e1000_shift_out_ee_bits(hw, 0, (u16)(eeprom->address_bits - 2)); return E1000_SUCCESS; } /** * e1000_read_mac_addr - read the adapters MAC from eeprom * @hw: Struct containing variables accessed by shared code * * Reads the adapter's MAC address from the EEPROM and inverts the LSB for the * second function of dual function devices */ s32 e1000_read_mac_addr(struct e1000_hw *hw) { u16 offset; u16 eeprom_data, i; for (i = 0; i < NODE_ADDRESS_SIZE; i += 2) { offset = i >> 1; if (e1000_read_eeprom(hw, offset, 1, &eeprom_data) < 0) { e_dbg("EEPROM Read Error\n"); return -E1000_ERR_EEPROM; } hw->perm_mac_addr[i] = (u8)(eeprom_data & 0x00FF); hw->perm_mac_addr[i + 1] = (u8)(eeprom_data >> 8); } switch (hw->mac_type) { default: break; case e1000_82546: case e1000_82546_rev_3: if (er32(STATUS) & E1000_STATUS_FUNC_1) hw->perm_mac_addr[5] ^= 0x01; break; } for (i = 0; i < NODE_ADDRESS_SIZE; i++) hw->mac_addr[i] = hw->perm_mac_addr[i]; return E1000_SUCCESS; } /** * e1000_init_rx_addrs - Initializes receive address filters. * @hw: Struct containing variables accessed by shared code * * Places the MAC address in receive address register 0 and clears the rest * of the receive address registers. Clears the multicast table. Assumes * the receiver is in reset when the routine is called. */ static void e1000_init_rx_addrs(struct e1000_hw *hw) { u32 i; u32 rar_num; /* Setup the receive address. */ e_dbg("Programming MAC Address into RAR[0]\n"); e1000_rar_set(hw, hw->mac_addr, 0); rar_num = E1000_RAR_ENTRIES; /* Zero out the following 14 receive addresses. RAR[15] is for * manageability */ e_dbg("Clearing RAR[1-14]\n"); for (i = 1; i < rar_num; i++) { E1000_WRITE_REG_ARRAY(hw, RA, (i << 1), 0); E1000_WRITE_FLUSH(); E1000_WRITE_REG_ARRAY(hw, RA, ((i << 1) + 1), 0); E1000_WRITE_FLUSH(); } } /** * e1000_hash_mc_addr - Hashes an address to determine its location in the multicast table * @hw: Struct containing variables accessed by shared code * @mc_addr: the multicast address to hash */ u32 e1000_hash_mc_addr(struct e1000_hw *hw, u8 *mc_addr) { u32 hash_value = 0; /* The portion of the address that is used for the hash table is * determined by the mc_filter_type setting. */ switch (hw->mc_filter_type) { /* [0] [1] [2] [3] [4] [5] * 01 AA 00 12 34 56 * LSB MSB */ case 0: /* [47:36] i.e. 0x563 for above example address */ hash_value = ((mc_addr[4] >> 4) | (((u16)mc_addr[5]) << 4)); break; case 1: /* [46:35] i.e. 0xAC6 for above example address */ hash_value = ((mc_addr[4] >> 3) | (((u16)mc_addr[5]) << 5)); break; case 2: /* [45:34] i.e. 0x5D8 for above example address */ hash_value = ((mc_addr[4] >> 2) | (((u16)mc_addr[5]) << 6)); break; case 3: /* [43:32] i.e. 0x634 for above example address */ hash_value = ((mc_addr[4]) | (((u16)mc_addr[5]) << 8)); break; } hash_value &= 0xFFF; return hash_value; } /** * e1000_rar_set - Puts an ethernet address into a receive address register. * @hw: Struct containing variables accessed by shared code * @addr: Address to put into receive address register * @index: Receive address register to write */ void e1000_rar_set(struct e1000_hw *hw, u8 *addr, u32 index) { u32 rar_low, rar_high; /* HW expects these in little endian so we reverse the byte order * from network order (big endian) to little endian */ rar_low = ((u32)addr[0] | ((u32)addr[1] << 8) | ((u32)addr[2] << 16) | ((u32)addr[3] << 24)); rar_high = ((u32)addr[4] | ((u32)addr[5] << 8)); /* Disable Rx and flush all Rx frames before enabling RSS to avoid Rx * unit hang. * * Description: * If there are any Rx frames queued up or otherwise present in the HW * before RSS is enabled, and then we enable RSS, the HW Rx unit will * hang. To work around this issue, we have to disable receives and * flush out all Rx frames before we enable RSS. To do so, we modify we * redirect all Rx traffic to manageability and then reset the HW. * This flushes away Rx frames, and (since the redirections to * manageability persists across resets) keeps new ones from coming in * while we work. Then, we clear the Address Valid AV bit for all MAC * addresses and undo the re-direction to manageability. * Now, frames are coming in again, but the MAC won't accept them, so * far so good. We now proceed to initialize RSS (if necessary) and * configure the Rx unit. Last, we re-enable the AV bits and continue * on our merry way. */ switch (hw->mac_type) { default: /* Indicate to hardware the Address is Valid. */ rar_high |= E1000_RAH_AV; break; } E1000_WRITE_REG_ARRAY(hw, RA, (index << 1), rar_low); E1000_WRITE_FLUSH(); E1000_WRITE_REG_ARRAY(hw, RA, ((index << 1) + 1), rar_high); E1000_WRITE_FLUSH(); } /** * e1000_write_vfta - Writes a value to the specified offset in the VLAN filter table. * @hw: Struct containing variables accessed by shared code * @offset: Offset in VLAN filter table to write * @value: Value to write into VLAN filter table */ void e1000_write_vfta(struct e1000_hw *hw, u32 offset, u32 value) { u32 temp; if ((hw->mac_type == e1000_82544) && ((offset & 0x1) == 1)) { temp = E1000_READ_REG_ARRAY(hw, VFTA, (offset - 1)); E1000_WRITE_REG_ARRAY(hw, VFTA, offset, value); E1000_WRITE_FLUSH(); E1000_WRITE_REG_ARRAY(hw, VFTA, (offset - 1), temp); E1000_WRITE_FLUSH(); } else { E1000_WRITE_REG_ARRAY(hw, VFTA, offset, value); E1000_WRITE_FLUSH(); } } /** * e1000_clear_vfta - Clears the VLAN filter table * @hw: Struct containing variables accessed by shared code */ static void e1000_clear_vfta(struct e1000_hw *hw) { u32 offset; for (offset = 0; offset < E1000_VLAN_FILTER_TBL_SIZE; offset++) { E1000_WRITE_REG_ARRAY(hw, VFTA, offset, 0); E1000_WRITE_FLUSH(); } } static s32 e1000_id_led_init(struct e1000_hw *hw) { u32 ledctl; const u32 ledctl_mask = 0x000000FF; const u32 ledctl_on = E1000_LEDCTL_MODE_LED_ON; const u32 ledctl_off = E1000_LEDCTL_MODE_LED_OFF; u16 eeprom_data, i, temp; const u16 led_mask = 0x0F; if (hw->mac_type < e1000_82540) { /* Nothing to do */ return E1000_SUCCESS; } ledctl = er32(LEDCTL); hw->ledctl_default = ledctl; hw->ledctl_mode1 = hw->ledctl_default; hw->ledctl_mode2 = hw->ledctl_default; if (e1000_read_eeprom(hw, EEPROM_ID_LED_SETTINGS, 1, &eeprom_data) < 0) { e_dbg("EEPROM Read Error\n"); return -E1000_ERR_EEPROM; } if ((eeprom_data == ID_LED_RESERVED_0000) || (eeprom_data == ID_LED_RESERVED_FFFF)) { eeprom_data = ID_LED_DEFAULT; } for (i = 0; i < 4; i++) { temp = (eeprom_data >> (i << 2)) & led_mask; switch (temp) { case ID_LED_ON1_DEF2: case ID_LED_ON1_ON2: case ID_LED_ON1_OFF2: hw->ledctl_mode1 &= ~(ledctl_mask << (i << 3)); hw->ledctl_mode1 |= ledctl_on << (i << 3); break; case ID_LED_OFF1_DEF2: case ID_LED_OFF1_ON2: case ID_LED_OFF1_OFF2: hw->ledctl_mode1 &= ~(ledctl_mask << (i << 3)); hw->ledctl_mode1 |= ledctl_off << (i << 3); break; default: /* Do nothing */ break; } switch (temp) { case ID_LED_DEF1_ON2: case ID_LED_ON1_ON2: case ID_LED_OFF1_ON2: hw->ledctl_mode2 &= ~(ledctl_mask << (i << 3)); hw->ledctl_mode2 |= ledctl_on << (i << 3); break; case ID_LED_DEF1_OFF2: case ID_LED_ON1_OFF2: case ID_LED_OFF1_OFF2: hw->ledctl_mode2 &= ~(ledctl_mask << (i << 3)); hw->ledctl_mode2 |= ledctl_off << (i << 3); break; default: /* Do nothing */ break; } } return E1000_SUCCESS; } /** * e1000_setup_led * @hw: Struct containing variables accessed by shared code * * Prepares SW controlable LED for use and saves the current state of the LED. */ s32 e1000_setup_led(struct e1000_hw *hw) { u32 ledctl; s32 ret_val = E1000_SUCCESS; switch (hw->mac_type) { case e1000_82542_rev2_0: case e1000_82542_rev2_1: case e1000_82543: case e1000_82544: /* No setup necessary */ break; case e1000_82541: case e1000_82547: case e1000_82541_rev_2: case e1000_82547_rev_2: /* Turn off PHY Smart Power Down (if enabled) */ ret_val = e1000_read_phy_reg(hw, IGP01E1000_GMII_FIFO, &hw->phy_spd_default); if (ret_val) return ret_val; ret_val = e1000_write_phy_reg(hw, IGP01E1000_GMII_FIFO, (u16)(hw->phy_spd_default & ~IGP01E1000_GMII_SPD)); if (ret_val) return ret_val; fallthrough; default: if (hw->media_type == e1000_media_type_fiber) { ledctl = er32(LEDCTL); /* Save current LEDCTL settings */ hw->ledctl_default = ledctl; /* Turn off LED0 */ ledctl &= ~(E1000_LEDCTL_LED0_IVRT | E1000_LEDCTL_LED0_BLINK | E1000_LEDCTL_LED0_MODE_MASK); ledctl |= (E1000_LEDCTL_MODE_LED_OFF << E1000_LEDCTL_LED0_MODE_SHIFT); ew32(LEDCTL, ledctl); } else if (hw->media_type == e1000_media_type_copper) ew32(LEDCTL, hw->ledctl_mode1); break; } return E1000_SUCCESS; } /** * e1000_cleanup_led - Restores the saved state of the SW controlable LED. * @hw: Struct containing variables accessed by shared code */ s32 e1000_cleanup_led(struct e1000_hw *hw) { s32 ret_val = E1000_SUCCESS; switch (hw->mac_type) { case e1000_82542_rev2_0: case e1000_82542_rev2_1: case e1000_82543: case e1000_82544: /* No cleanup necessary */ break; case e1000_82541: case e1000_82547: case e1000_82541_rev_2: case e1000_82547_rev_2: /* Turn on PHY Smart Power Down (if previously enabled) */ ret_val = e1000_write_phy_reg(hw, IGP01E1000_GMII_FIFO, hw->phy_spd_default); if (ret_val) return ret_val; fallthrough; default: /* Restore LEDCTL settings */ ew32(LEDCTL, hw->ledctl_default); break; } return E1000_SUCCESS; } /** * e1000_led_on - Turns on the software controllable LED * @hw: Struct containing variables accessed by shared code */ s32 e1000_led_on(struct e1000_hw *hw) { u32 ctrl = er32(CTRL); switch (hw->mac_type) { case e1000_82542_rev2_0: case e1000_82542_rev2_1: case e1000_82543: /* Set SW Defineable Pin 0 to turn on the LED */ ctrl |= E1000_CTRL_SWDPIN0; ctrl |= E1000_CTRL_SWDPIO0; break; case e1000_82544: if (hw->media_type == e1000_media_type_fiber) { /* Set SW Defineable Pin 0 to turn on the LED */ ctrl |= E1000_CTRL_SWDPIN0; ctrl |= E1000_CTRL_SWDPIO0; } else { /* Clear SW Defineable Pin 0 to turn on the LED */ ctrl &= ~E1000_CTRL_SWDPIN0; ctrl |= E1000_CTRL_SWDPIO0; } break; default: if (hw->media_type == e1000_media_type_fiber) { /* Clear SW Defineable Pin 0 to turn on the LED */ ctrl &= ~E1000_CTRL_SWDPIN0; ctrl |= E1000_CTRL_SWDPIO0; } else if (hw->media_type == e1000_media_type_copper) { ew32(LEDCTL, hw->ledctl_mode2); return E1000_SUCCESS; } break; } ew32(CTRL, ctrl); return E1000_SUCCESS; } /** * e1000_led_off - Turns off the software controllable LED * @hw: Struct containing variables accessed by shared code */ s32 e1000_led_off(struct e1000_hw *hw) { u32 ctrl = er32(CTRL); switch (hw->mac_type) { case e1000_82542_rev2_0: case e1000_82542_rev2_1: case e1000_82543: /* Clear SW Defineable Pin 0 to turn off the LED */ ctrl &= ~E1000_CTRL_SWDPIN0; ctrl |= E1000_CTRL_SWDPIO0; break; case e1000_82544: if (hw->media_type == e1000_media_type_fiber) { /* Clear SW Defineable Pin 0 to turn off the LED */ ctrl &= ~E1000_CTRL_SWDPIN0; ctrl |= E1000_CTRL_SWDPIO0; } else { /* Set SW Defineable Pin 0 to turn off the LED */ ctrl |= E1000_CTRL_SWDPIN0; ctrl |= E1000_CTRL_SWDPIO0; } break; default: if (hw->media_type == e1000_media_type_fiber) { /* Set SW Defineable Pin 0 to turn off the LED */ ctrl |= E1000_CTRL_SWDPIN0; ctrl |= E1000_CTRL_SWDPIO0; } else if (hw->media_type == e1000_media_type_copper) { ew32(LEDCTL, hw->ledctl_mode1); return E1000_SUCCESS; } break; } ew32(CTRL, ctrl); return E1000_SUCCESS; } /** * e1000_clear_hw_cntrs - Clears all hardware statistics counters. * @hw: Struct containing variables accessed by shared code */ static void e1000_clear_hw_cntrs(struct e1000_hw *hw) { er32(CRCERRS); er32(SYMERRS); er32(MPC); er32(SCC); er32(ECOL); er32(MCC); er32(LATECOL); er32(COLC); er32(DC); er32(SEC); er32(RLEC); er32(XONRXC); er32(XONTXC); er32(XOFFRXC); er32(XOFFTXC); er32(FCRUC); er32(PRC64); er32(PRC127); er32(PRC255); er32(PRC511); er32(PRC1023); er32(PRC1522); er32(GPRC); er32(BPRC); er32(MPRC); er32(GPTC); er32(GORCL); er32(GORCH); er32(GOTCL); er32(GOTCH); er32(RNBC); er32(RUC); er32(RFC); er32(ROC); er32(RJC); er32(TORL); er32(TORH); er32(TOTL); er32(TOTH); er32(TPR); er32(TPT); er32(PTC64); er32(PTC127); er32(PTC255); er32(PTC511); er32(PTC1023); er32(PTC1522); er32(MPTC); er32(BPTC); if (hw->mac_type < e1000_82543) return; er32(ALGNERRC); er32(RXERRC); er32(TNCRS); er32(CEXTERR); er32(TSCTC); er32(TSCTFC); if (hw->mac_type <= e1000_82544) return; er32(MGTPRC); er32(MGTPDC); er32(MGTPTC); } /** * e1000_reset_adaptive - Resets Adaptive IFS to its default state. * @hw: Struct containing variables accessed by shared code * * Call this after e1000_init_hw. You may override the IFS defaults by setting * hw->ifs_params_forced to true. However, you must initialize hw-> * current_ifs_val, ifs_min_val, ifs_max_val, ifs_step_size, and ifs_ratio * before calling this function. */ void e1000_reset_adaptive(struct e1000_hw *hw) { if (hw->adaptive_ifs) { if (!hw->ifs_params_forced) { hw->current_ifs_val = 0; hw->ifs_min_val = IFS_MIN; hw->ifs_max_val = IFS_MAX; hw->ifs_step_size = IFS_STEP; hw->ifs_ratio = IFS_RATIO; } hw->in_ifs_mode = false; ew32(AIT, 0); } else { e_dbg("Not in Adaptive IFS mode!\n"); } } /** * e1000_update_adaptive - update adaptive IFS * @hw: Struct containing variables accessed by shared code * * Called during the callback/watchdog routine to update IFS value based on * the ratio of transmits to collisions. */ void e1000_update_adaptive(struct e1000_hw *hw) { if (hw->adaptive_ifs) { if ((hw->collision_delta * hw->ifs_ratio) > hw->tx_packet_delta) { if (hw->tx_packet_delta > MIN_NUM_XMITS) { hw->in_ifs_mode = true; if (hw->current_ifs_val < hw->ifs_max_val) { if (hw->current_ifs_val == 0) hw->current_ifs_val = hw->ifs_min_val; else hw->current_ifs_val += hw->ifs_step_size; ew32(AIT, hw->current_ifs_val); } } } else { if (hw->in_ifs_mode && (hw->tx_packet_delta <= MIN_NUM_XMITS)) { hw->current_ifs_val = 0; hw->in_ifs_mode = false; ew32(AIT, 0); } } } else { e_dbg("Not in Adaptive IFS mode!\n"); } } /** * e1000_get_bus_info * @hw: Struct containing variables accessed by shared code * * Gets the current PCI bus type, speed, and width of the hardware */ void e1000_get_bus_info(struct e1000_hw *hw) { u32 status; switch (hw->mac_type) { case e1000_82542_rev2_0: case e1000_82542_rev2_1: hw->bus_type = e1000_bus_type_pci; hw->bus_speed = e1000_bus_speed_unknown; hw->bus_width = e1000_bus_width_unknown; break; default: status = er32(STATUS); hw->bus_type = (status & E1000_STATUS_PCIX_MODE) ? e1000_bus_type_pcix : e1000_bus_type_pci; if (hw->device_id == E1000_DEV_ID_82546EB_QUAD_COPPER) { hw->bus_speed = (hw->bus_type == e1000_bus_type_pci) ? e1000_bus_speed_66 : e1000_bus_speed_120; } else if (hw->bus_type == e1000_bus_type_pci) { hw->bus_speed = (status & E1000_STATUS_PCI66) ? e1000_bus_speed_66 : e1000_bus_speed_33; } else { switch (status & E1000_STATUS_PCIX_SPEED) { case E1000_STATUS_PCIX_SPEED_66: hw->bus_speed = e1000_bus_speed_66; break; case E1000_STATUS_PCIX_SPEED_100: hw->bus_speed = e1000_bus_speed_100; break; case E1000_STATUS_PCIX_SPEED_133: hw->bus_speed = e1000_bus_speed_133; break; default: hw->bus_speed = e1000_bus_speed_reserved; break; } } hw->bus_width = (status & E1000_STATUS_BUS64) ? e1000_bus_width_64 : e1000_bus_width_32; break; } } /** * e1000_write_reg_io * @hw: Struct containing variables accessed by shared code * @offset: offset to write to * @value: value to write * * Writes a value to one of the devices registers using port I/O (as opposed to * memory mapped I/O). Only 82544 and newer devices support port I/O. */ static void e1000_write_reg_io(struct e1000_hw *hw, u32 offset, u32 value) { unsigned long io_addr = hw->io_base; unsigned long io_data = hw->io_base + 4; e1000_io_write(hw, io_addr, offset); e1000_io_write(hw, io_data, value); } /** * e1000_get_cable_length - Estimates the cable length. * @hw: Struct containing variables accessed by shared code * @min_length: The estimated minimum length * @max_length: The estimated maximum length * * returns: - E1000_ERR_XXX * E1000_SUCCESS * * This function always returns a ranged length (minimum & maximum). * So for M88 phy's, this function interprets the one value returned from the * register to the minimum and maximum range. * For IGP phy's, the function calculates the range by the AGC registers. */ static s32 e1000_get_cable_length(struct e1000_hw *hw, u16 *min_length, u16 *max_length) { s32 ret_val; u16 agc_value = 0; u16 i, phy_data; u16 cable_length; *min_length = *max_length = 0; /* Use old method for Phy older than IGP */ if (hw->phy_type == e1000_phy_m88) { ret_val = e1000_read_phy_reg(hw, M88E1000_PHY_SPEC_STATUS, &phy_data); if (ret_val) return ret_val; cable_length = (phy_data & M88E1000_PSSR_CABLE_LENGTH) >> M88E1000_PSSR_CABLE_LENGTH_SHIFT; /* Convert the enum value to ranged values */ switch (cable_length) { case e1000_cable_length_50: *min_length = 0; *max_length = e1000_igp_cable_length_50; break; case e1000_cable_length_50_80: *min_length = e1000_igp_cable_length_50; *max_length = e1000_igp_cable_length_80; break; case e1000_cable_length_80_110: *min_length = e1000_igp_cable_length_80; *max_length = e1000_igp_cable_length_110; break; case e1000_cable_length_110_140: *min_length = e1000_igp_cable_length_110; *max_length = e1000_igp_cable_length_140; break; case e1000_cable_length_140: *min_length = e1000_igp_cable_length_140; *max_length = e1000_igp_cable_length_170; break; default: return -E1000_ERR_PHY; } } else if (hw->phy_type == e1000_phy_igp) { /* For IGP PHY */ u16 cur_agc_value; u16 min_agc_value = IGP01E1000_AGC_LENGTH_TABLE_SIZE; static const u16 agc_reg_array[IGP01E1000_PHY_CHANNEL_NUM] = { IGP01E1000_PHY_AGC_A, IGP01E1000_PHY_AGC_B, IGP01E1000_PHY_AGC_C, IGP01E1000_PHY_AGC_D }; /* Read the AGC registers for all channels */ for (i = 0; i < IGP01E1000_PHY_CHANNEL_NUM; i++) { ret_val = e1000_read_phy_reg(hw, agc_reg_array[i], &phy_data); if (ret_val) return ret_val; cur_agc_value = phy_data >> IGP01E1000_AGC_LENGTH_SHIFT; /* Value bound check. */ if ((cur_agc_value >= IGP01E1000_AGC_LENGTH_TABLE_SIZE - 1) || (cur_agc_value == 0)) return -E1000_ERR_PHY; agc_value += cur_agc_value; /* Update minimal AGC value. */ if (min_agc_value > cur_agc_value) min_agc_value = cur_agc_value; } /* Remove the minimal AGC result for length < 50m */ if (agc_value < IGP01E1000_PHY_CHANNEL_NUM * e1000_igp_cable_length_50) { agc_value -= min_agc_value; /* Get the average length of the remaining 3 channels */ agc_value /= (IGP01E1000_PHY_CHANNEL_NUM - 1); } else { /* Get the average length of all the 4 channels. */ agc_value /= IGP01E1000_PHY_CHANNEL_NUM; } /* Set the range of the calculated length. */ *min_length = ((e1000_igp_cable_length_table[agc_value] - IGP01E1000_AGC_RANGE) > 0) ? (e1000_igp_cable_length_table[agc_value] - IGP01E1000_AGC_RANGE) : 0; *max_length = e1000_igp_cable_length_table[agc_value] + IGP01E1000_AGC_RANGE; } return E1000_SUCCESS; } /** * e1000_check_polarity - Check the cable polarity * @hw: Struct containing variables accessed by shared code * @polarity: output parameter : 0 - Polarity is not reversed * 1 - Polarity is reversed. * * returns: - E1000_ERR_XXX * E1000_SUCCESS * * For phy's older than IGP, this function simply reads the polarity bit in the * Phy Status register. For IGP phy's, this bit is valid only if link speed is * 10 Mbps. If the link speed is 100 Mbps there is no polarity so this bit will * return 0. If the link speed is 1000 Mbps the polarity status is in the * IGP01E1000_PHY_PCS_INIT_REG. */ static s32 e1000_check_polarity(struct e1000_hw *hw, e1000_rev_polarity *polarity) { s32 ret_val; u16 phy_data; if (hw->phy_type == e1000_phy_m88) { /* return the Polarity bit in the Status register. */ ret_val = e1000_read_phy_reg(hw, M88E1000_PHY_SPEC_STATUS, &phy_data); if (ret_val) return ret_val; *polarity = ((phy_data & M88E1000_PSSR_REV_POLARITY) >> M88E1000_PSSR_REV_POLARITY_SHIFT) ? e1000_rev_polarity_reversed : e1000_rev_polarity_normal; } else if (hw->phy_type == e1000_phy_igp) { /* Read the Status register to check the speed */ ret_val = e1000_read_phy_reg(hw, IGP01E1000_PHY_PORT_STATUS, &phy_data); if (ret_val) return ret_val; /* If speed is 1000 Mbps, must read the * IGP01E1000_PHY_PCS_INIT_REG to find the polarity status */ if ((phy_data & IGP01E1000_PSSR_SPEED_MASK) == IGP01E1000_PSSR_SPEED_1000MBPS) { /* Read the GIG initialization PCS register (0x00B4) */ ret_val = e1000_read_phy_reg(hw, IGP01E1000_PHY_PCS_INIT_REG, &phy_data); if (ret_val) return ret_val; /* Check the polarity bits */ *polarity = (phy_data & IGP01E1000_PHY_POLARITY_MASK) ? e1000_rev_polarity_reversed : e1000_rev_polarity_normal; } else { /* For 10 Mbps, read the polarity bit in the status * register. (for 100 Mbps this bit is always 0) */ *polarity = (phy_data & IGP01E1000_PSSR_POLARITY_REVERSED) ? e1000_rev_polarity_reversed : e1000_rev_polarity_normal; } } return E1000_SUCCESS; } /** * e1000_check_downshift - Check if Downshift occurred * @hw: Struct containing variables accessed by shared code * * returns: - E1000_ERR_XXX * E1000_SUCCESS * * For phy's older than IGP, this function reads the Downshift bit in the Phy * Specific Status register. For IGP phy's, it reads the Downgrade bit in the * Link Health register. In IGP this bit is latched high, so the driver must * read it immediately after link is established. */ static s32 e1000_check_downshift(struct e1000_hw *hw) { s32 ret_val; u16 phy_data; if (hw->phy_type == e1000_phy_igp) { ret_val = e1000_read_phy_reg(hw, IGP01E1000_PHY_LINK_HEALTH, &phy_data); if (ret_val) return ret_val; hw->speed_downgraded = (phy_data & IGP01E1000_PLHR_SS_DOWNGRADE) ? 1 : 0; } else if (hw->phy_type == e1000_phy_m88) { ret_val = e1000_read_phy_reg(hw, M88E1000_PHY_SPEC_STATUS, &phy_data); if (ret_val) return ret_val; hw->speed_downgraded = (phy_data & M88E1000_PSSR_DOWNSHIFT) >> M88E1000_PSSR_DOWNSHIFT_SHIFT; } return E1000_SUCCESS; } static const u16 dsp_reg_array[IGP01E1000_PHY_CHANNEL_NUM] = { IGP01E1000_PHY_AGC_PARAM_A, IGP01E1000_PHY_AGC_PARAM_B, IGP01E1000_PHY_AGC_PARAM_C, IGP01E1000_PHY_AGC_PARAM_D }; static s32 e1000_1000Mb_check_cable_length(struct e1000_hw *hw) { u16 min_length, max_length; u16 phy_data, i; s32 ret_val; ret_val = e1000_get_cable_length(hw, &min_length, &max_length); if (ret_val) return ret_val; if (hw->dsp_config_state != e1000_dsp_config_enabled) return 0; if (min_length >= e1000_igp_cable_length_50) { for (i = 0; i < IGP01E1000_PHY_CHANNEL_NUM; i++) { ret_val = e1000_read_phy_reg(hw, dsp_reg_array[i], &phy_data); if (ret_val) return ret_val; phy_data &= ~IGP01E1000_PHY_EDAC_MU_INDEX; ret_val = e1000_write_phy_reg(hw, dsp_reg_array[i], phy_data); if (ret_val) return ret_val; } hw->dsp_config_state = e1000_dsp_config_activated; } else { u16 ffe_idle_err_timeout = FFE_IDLE_ERR_COUNT_TIMEOUT_20; u32 idle_errs = 0; /* clear previous idle error counts */ ret_val = e1000_read_phy_reg(hw, PHY_1000T_STATUS, &phy_data); if (ret_val) return ret_val; for (i = 0; i < ffe_idle_err_timeout; i++) { udelay(1000); ret_val = e1000_read_phy_reg(hw, PHY_1000T_STATUS, &phy_data); if (ret_val) return ret_val; idle_errs += (phy_data & SR_1000T_IDLE_ERROR_CNT); if (idle_errs > SR_1000T_PHY_EXCESSIVE_IDLE_ERR_COUNT) { hw->ffe_config_state = e1000_ffe_config_active; ret_val = e1000_write_phy_reg(hw, IGP01E1000_PHY_DSP_FFE, IGP01E1000_PHY_DSP_FFE_CM_CP); if (ret_val) return ret_val; break; } if (idle_errs) ffe_idle_err_timeout = FFE_IDLE_ERR_COUNT_TIMEOUT_100; } } return 0; } /** * e1000_config_dsp_after_link_change * @hw: Struct containing variables accessed by shared code * @link_up: was link up at the time this was called * * returns: - E1000_ERR_PHY if fail to read/write the PHY * E1000_SUCCESS at any other case. * * 82541_rev_2 & 82547_rev_2 have the capability to configure the DSP when a * gigabit link is achieved to improve link quality. */ static s32 e1000_config_dsp_after_link_change(struct e1000_hw *hw, bool link_up) { s32 ret_val; u16 phy_data, phy_saved_data, speed, duplex, i; if (hw->phy_type != e1000_phy_igp) return E1000_SUCCESS; if (link_up) { ret_val = e1000_get_speed_and_duplex(hw, &speed, &duplex); if (ret_val) { e_dbg("Error getting link speed and duplex\n"); return ret_val; } if (speed == SPEED_1000) { ret_val = e1000_1000Mb_check_cable_length(hw); if (ret_val) return ret_val; } } else { if (hw->dsp_config_state == e1000_dsp_config_activated) { /* Save off the current value of register 0x2F5B to be * restored at the end of the routines. */ ret_val = e1000_read_phy_reg(hw, 0x2F5B, &phy_saved_data); if (ret_val) return ret_val; /* Disable the PHY transmitter */ ret_val = e1000_write_phy_reg(hw, 0x2F5B, 0x0003); if (ret_val) return ret_val; msleep(20); ret_val = e1000_write_phy_reg(hw, 0x0000, IGP01E1000_IEEE_FORCE_GIGA); if (ret_val) return ret_val; for (i = 0; i < IGP01E1000_PHY_CHANNEL_NUM; i++) { ret_val = e1000_read_phy_reg(hw, dsp_reg_array[i], &phy_data); if (ret_val) return ret_val; phy_data &= ~IGP01E1000_PHY_EDAC_MU_INDEX; phy_data |= IGP01E1000_PHY_EDAC_SIGN_EXT_9_BITS; ret_val = e1000_write_phy_reg(hw, dsp_reg_array[i], phy_data); if (ret_val) return ret_val; } ret_val = e1000_write_phy_reg(hw, 0x0000, IGP01E1000_IEEE_RESTART_AUTONEG); if (ret_val) return ret_val; msleep(20); /* Now enable the transmitter */ ret_val = e1000_write_phy_reg(hw, 0x2F5B, phy_saved_data); if (ret_val) return ret_val; hw->dsp_config_state = e1000_dsp_config_enabled; } if (hw->ffe_config_state == e1000_ffe_config_active) { /* Save off the current value of register 0x2F5B to be * restored at the end of the routines. */ ret_val = e1000_read_phy_reg(hw, 0x2F5B, &phy_saved_data); if (ret_val) return ret_val; /* Disable the PHY transmitter */ ret_val = e1000_write_phy_reg(hw, 0x2F5B, 0x0003); if (ret_val) return ret_val; msleep(20); ret_val = e1000_write_phy_reg(hw, 0x0000, IGP01E1000_IEEE_FORCE_GIGA); if (ret_val) return ret_val; ret_val = e1000_write_phy_reg(hw, IGP01E1000_PHY_DSP_FFE, IGP01E1000_PHY_DSP_FFE_DEFAULT); if (ret_val) return ret_val; ret_val = e1000_write_phy_reg(hw, 0x0000, IGP01E1000_IEEE_RESTART_AUTONEG); if (ret_val) return ret_val; msleep(20); /* Now enable the transmitter */ ret_val = e1000_write_phy_reg(hw, 0x2F5B, phy_saved_data); if (ret_val) return ret_val; hw->ffe_config_state = e1000_ffe_config_enabled; } } return E1000_SUCCESS; } /** * e1000_set_phy_mode - Set PHY to class A mode * @hw: Struct containing variables accessed by shared code * * Assumes the following operations will follow to enable the new class mode. * 1. Do a PHY soft reset * 2. Restart auto-negotiation or force link. */ static s32 e1000_set_phy_mode(struct e1000_hw *hw) { s32 ret_val; u16 eeprom_data; if ((hw->mac_type == e1000_82545_rev_3) && (hw->media_type == e1000_media_type_copper)) { ret_val = e1000_read_eeprom(hw, EEPROM_PHY_CLASS_WORD, 1, &eeprom_data); if (ret_val) return ret_val; if ((eeprom_data != EEPROM_RESERVED_WORD) && (eeprom_data & EEPROM_PHY_CLASS_A)) { ret_val = e1000_write_phy_reg(hw, M88E1000_PHY_PAGE_SELECT, 0x000B); if (ret_val) return ret_val; ret_val = e1000_write_phy_reg(hw, M88E1000_PHY_GEN_CONTROL, 0x8104); if (ret_val) return ret_val; hw->phy_reset_disable = false; } } return E1000_SUCCESS; } /** * e1000_set_d3_lplu_state - set d3 link power state * @hw: Struct containing variables accessed by shared code * @active: true to enable lplu false to disable lplu. * * This function sets the lplu state according to the active flag. When * activating lplu this function also disables smart speed and vise versa. * lplu will not be activated unless the device autonegotiation advertisement * meets standards of either 10 or 10/100 or 10/100/1000 at all duplexes. * * returns: - E1000_ERR_PHY if fail to read/write the PHY * E1000_SUCCESS at any other case. */ static s32 e1000_set_d3_lplu_state(struct e1000_hw *hw, bool active) { s32 ret_val; u16 phy_data; if (hw->phy_type != e1000_phy_igp) return E1000_SUCCESS; /* During driver activity LPLU should not be used or it will attain link * from the lowest speeds starting from 10Mbps. The capability is used * for Dx transitions and states */ if (hw->mac_type == e1000_82541_rev_2 || hw->mac_type == e1000_82547_rev_2) { ret_val = e1000_read_phy_reg(hw, IGP01E1000_GMII_FIFO, &phy_data); if (ret_val) return ret_val; } if (!active) { if (hw->mac_type == e1000_82541_rev_2 || hw->mac_type == e1000_82547_rev_2) { phy_data &= ~IGP01E1000_GMII_FLEX_SPD; ret_val = e1000_write_phy_reg(hw, IGP01E1000_GMII_FIFO, phy_data); if (ret_val) return ret_val; } /* LPLU and SmartSpeed are mutually exclusive. LPLU is used * during Dx states where the power conservation is most * important. During driver activity we should enable * SmartSpeed, so performance is maintained. */ if (hw->smart_speed == e1000_smart_speed_on) { ret_val = e1000_read_phy_reg(hw, IGP01E1000_PHY_PORT_CONFIG, &phy_data); if (ret_val) return ret_val; phy_data |= IGP01E1000_PSCFR_SMART_SPEED; ret_val = e1000_write_phy_reg(hw, IGP01E1000_PHY_PORT_CONFIG, phy_data); if (ret_val) return ret_val; } else if (hw->smart_speed == e1000_smart_speed_off) { ret_val = e1000_read_phy_reg(hw, IGP01E1000_PHY_PORT_CONFIG, &phy_data); if (ret_val) return ret_val; phy_data &= ~IGP01E1000_PSCFR_SMART_SPEED; ret_val = e1000_write_phy_reg(hw, IGP01E1000_PHY_PORT_CONFIG, phy_data); if (ret_val) return ret_val; } } else if ((hw->autoneg_advertised == AUTONEG_ADVERTISE_SPEED_DEFAULT) || (hw->autoneg_advertised == AUTONEG_ADVERTISE_10_ALL) || (hw->autoneg_advertised == AUTONEG_ADVERTISE_10_100_ALL)) { if (hw->mac_type == e1000_82541_rev_2 || hw->mac_type == e1000_82547_rev_2) { phy_data |= IGP01E1000_GMII_FLEX_SPD; ret_val = e1000_write_phy_reg(hw, IGP01E1000_GMII_FIFO, phy_data); if (ret_val) return ret_val; } /* When LPLU is enabled we should disable SmartSpeed */ ret_val = e1000_read_phy_reg(hw, IGP01E1000_PHY_PORT_CONFIG, &phy_data); if (ret_val) return ret_val; phy_data &= ~IGP01E1000_PSCFR_SMART_SPEED; ret_val = e1000_write_phy_reg(hw, IGP01E1000_PHY_PORT_CONFIG, phy_data); if (ret_val) return ret_val; } return E1000_SUCCESS; } /** * e1000_set_vco_speed * @hw: Struct containing variables accessed by shared code * * Change VCO speed register to improve Bit Error Rate performance of SERDES. */ static s32 e1000_set_vco_speed(struct e1000_hw *hw) { s32 ret_val; u16 default_page = 0; u16 phy_data; switch (hw->mac_type) { case e1000_82545_rev_3: case e1000_82546_rev_3: break; default: return E1000_SUCCESS; } /* Set PHY register 30, page 5, bit 8 to 0 */ ret_val = e1000_read_phy_reg(hw, M88E1000_PHY_PAGE_SELECT, &default_page); if (ret_val) return ret_val; ret_val = e1000_write_phy_reg(hw, M88E1000_PHY_PAGE_SELECT, 0x0005); if (ret_val) return ret_val; ret_val = e1000_read_phy_reg(hw, M88E1000_PHY_GEN_CONTROL, &phy_data); if (ret_val) return ret_val; phy_data &= ~M88E1000_PHY_VCO_REG_BIT8; ret_val = e1000_write_phy_reg(hw, M88E1000_PHY_GEN_CONTROL, phy_data); if (ret_val) return ret_val; /* Set PHY register 30, page 4, bit 11 to 1 */ ret_val = e1000_write_phy_reg(hw, M88E1000_PHY_PAGE_SELECT, 0x0004); if (ret_val) return ret_val; ret_val = e1000_read_phy_reg(hw, M88E1000_PHY_GEN_CONTROL, &phy_data); if (ret_val) return ret_val; phy_data |= M88E1000_PHY_VCO_REG_BIT11; ret_val = e1000_write_phy_reg(hw, M88E1000_PHY_GEN_CONTROL, phy_data); if (ret_val) return ret_val; ret_val = e1000_write_phy_reg(hw, M88E1000_PHY_PAGE_SELECT, default_page); if (ret_val) return ret_val; return E1000_SUCCESS; } /** * e1000_enable_mng_pass_thru - check for bmc pass through * @hw: Struct containing variables accessed by shared code * * Verifies the hardware needs to allow ARPs to be processed by the host * returns: - true/false */ u32 e1000_enable_mng_pass_thru(struct e1000_hw *hw) { u32 manc; if (hw->asf_firmware_present) { manc = er32(MANC); if (!(manc & E1000_MANC_RCV_TCO_EN) || !(manc & E1000_MANC_EN_MAC_ADDR_FILTER)) return false; if ((manc & E1000_MANC_SMBUS_EN) && !(manc & E1000_MANC_ASF_EN)) return true; } return false; } static s32 e1000_polarity_reversal_workaround(struct e1000_hw *hw) { s32 ret_val; u16 mii_status_reg; u16 i; /* Polarity reversal workaround for forced 10F/10H links. */ /* Disable the transmitter on the PHY */ ret_val = e1000_write_phy_reg(hw, M88E1000_PHY_PAGE_SELECT, 0x0019); if (ret_val) return ret_val; ret_val = e1000_write_phy_reg(hw, M88E1000_PHY_GEN_CONTROL, 0xFFFF); if (ret_val) return ret_val; ret_val = e1000_write_phy_reg(hw, M88E1000_PHY_PAGE_SELECT, 0x0000); if (ret_val) return ret_val; /* This loop will early-out if the NO link condition has been met. */ for (i = PHY_FORCE_TIME; i > 0; i--) { /* Read the MII Status Register and wait for Link Status bit * to be clear. */ ret_val = e1000_read_phy_reg(hw, PHY_STATUS, &mii_status_reg); if (ret_val) return ret_val; ret_val = e1000_read_phy_reg(hw, PHY_STATUS, &mii_status_reg); if (ret_val) return ret_val; if ((mii_status_reg & ~MII_SR_LINK_STATUS) == 0) break; msleep(100); } /* Recommended delay time after link has been lost */ msleep(1000); /* Now we will re-enable th transmitter on the PHY */ ret_val = e1000_write_phy_reg(hw, M88E1000_PHY_PAGE_SELECT, 0x0019); if (ret_val) return ret_val; msleep(50); ret_val = e1000_write_phy_reg(hw, M88E1000_PHY_GEN_CONTROL, 0xFFF0); if (ret_val) return ret_val; msleep(50); ret_val = e1000_write_phy_reg(hw, M88E1000_PHY_GEN_CONTROL, 0xFF00); if (ret_val) return ret_val; msleep(50); ret_val = e1000_write_phy_reg(hw, M88E1000_PHY_GEN_CONTROL, 0x0000); if (ret_val) return ret_val; ret_val = e1000_write_phy_reg(hw, M88E1000_PHY_PAGE_SELECT, 0x0000); if (ret_val) return ret_val; /* This loop will early-out if the link condition has been met. */ for (i = PHY_FORCE_TIME; i > 0; i--) { /* Read the MII Status Register and wait for Link Status bit * to be set. */ ret_val = e1000_read_phy_reg(hw, PHY_STATUS, &mii_status_reg); if (ret_val) return ret_val; ret_val = e1000_read_phy_reg(hw, PHY_STATUS, &mii_status_reg); if (ret_val) return ret_val; if (mii_status_reg & MII_SR_LINK_STATUS) break; msleep(100); } return E1000_SUCCESS; } /** * e1000_get_auto_rd_done * @hw: Struct containing variables accessed by shared code * * Check for EEPROM Auto Read bit done. * returns: - E1000_ERR_RESET if fail to reset MAC * E1000_SUCCESS at any other case. */ static s32 e1000_get_auto_rd_done(struct e1000_hw *hw) { msleep(5); return E1000_SUCCESS; } /** * e1000_get_phy_cfg_done * @hw: Struct containing variables accessed by shared code * * Checks if the PHY configuration is done * returns: - E1000_ERR_RESET if fail to reset MAC * E1000_SUCCESS at any other case. */ static s32 e1000_get_phy_cfg_done(struct e1000_hw *hw) { msleep(10); return E1000_SUCCESS; }
linux-master
drivers/net/ethernet/intel/e1000/e1000_hw.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 1999 - 2006 Intel Corporation. */ #include "e1000.h" /* This is the only thing that needs to be changed to adjust the * maximum number of ports that the driver can manage. */ #define E1000_MAX_NIC 32 #define OPTION_UNSET -1 #define OPTION_DISABLED 0 #define OPTION_ENABLED 1 /* All parameters are treated the same, as an integer array of values. * This macro just reduces the need to repeat the same declaration code * over and over (plus this helps to avoid typo bugs). */ #define E1000_PARAM_INIT { [0 ... E1000_MAX_NIC] = OPTION_UNSET } #define E1000_PARAM(X, desc) \ static int X[E1000_MAX_NIC+1] = E1000_PARAM_INIT; \ static unsigned int num_##X; \ module_param_array_named(X, X, int, &num_##X, 0); \ MODULE_PARM_DESC(X, desc); /* Transmit Descriptor Count * * Valid Range: 80-256 for 82542 and 82543 gigabit ethernet controllers * Valid Range: 80-4096 for 82544 and newer * * Default Value: 256 */ E1000_PARAM(TxDescriptors, "Number of transmit descriptors"); /* Receive Descriptor Count * * Valid Range: 80-256 for 82542 and 82543 gigabit ethernet controllers * Valid Range: 80-4096 for 82544 and newer * * Default Value: 256 */ E1000_PARAM(RxDescriptors, "Number of receive descriptors"); /* User Specified Speed Override * * Valid Range: 0, 10, 100, 1000 * - 0 - auto-negotiate at all supported speeds * - 10 - only link at 10 Mbps * - 100 - only link at 100 Mbps * - 1000 - only link at 1000 Mbps * * Default Value: 0 */ E1000_PARAM(Speed, "Speed setting"); /* User Specified Duplex Override * * Valid Range: 0-2 * - 0 - auto-negotiate for duplex * - 1 - only link at half duplex * - 2 - only link at full duplex * * Default Value: 0 */ E1000_PARAM(Duplex, "Duplex setting"); /* Auto-negotiation Advertisement Override * * Valid Range: 0x01-0x0F, 0x20-0x2F (copper); 0x20 (fiber) * * The AutoNeg value is a bit mask describing which speed and duplex * combinations should be advertised during auto-negotiation. * The supported speed and duplex modes are listed below * * Bit 7 6 5 4 3 2 1 0 * Speed (Mbps) N/A N/A 1000 N/A 100 100 10 10 * Duplex Full Full Half Full Half * * Default Value: 0x2F (copper); 0x20 (fiber) */ E1000_PARAM(AutoNeg, "Advertised auto-negotiation setting"); #define AUTONEG_ADV_DEFAULT 0x2F /* User Specified Flow Control Override * * Valid Range: 0-3 * - 0 - No Flow Control * - 1 - Rx only, respond to PAUSE frames but do not generate them * - 2 - Tx only, generate PAUSE frames but ignore them on receive * - 3 - Full Flow Control Support * * Default Value: Read flow control settings from the EEPROM */ E1000_PARAM(FlowControl, "Flow Control setting"); /* XsumRX - Receive Checksum Offload Enable/Disable * * Valid Range: 0, 1 * - 0 - disables all checksum offload * - 1 - enables receive IP/TCP/UDP checksum offload * on 82543 and newer -based NICs * * Default Value: 1 */ E1000_PARAM(XsumRX, "Disable or enable Receive Checksum offload"); /* Transmit Interrupt Delay in units of 1.024 microseconds * Tx interrupt delay needs to typically be set to something non zero * * Valid Range: 0-65535 */ E1000_PARAM(TxIntDelay, "Transmit Interrupt Delay"); #define DEFAULT_TIDV 8 #define MAX_TXDELAY 0xFFFF #define MIN_TXDELAY 0 /* Transmit Absolute Interrupt Delay in units of 1.024 microseconds * * Valid Range: 0-65535 */ E1000_PARAM(TxAbsIntDelay, "Transmit Absolute Interrupt Delay"); #define DEFAULT_TADV 32 #define MAX_TXABSDELAY 0xFFFF #define MIN_TXABSDELAY 0 /* Receive Interrupt Delay in units of 1.024 microseconds * hardware will likely hang if you set this to anything but zero. * * Valid Range: 0-65535 */ E1000_PARAM(RxIntDelay, "Receive Interrupt Delay"); #define DEFAULT_RDTR 0 #define MAX_RXDELAY 0xFFFF #define MIN_RXDELAY 0 /* Receive Absolute Interrupt Delay in units of 1.024 microseconds * * Valid Range: 0-65535 */ E1000_PARAM(RxAbsIntDelay, "Receive Absolute Interrupt Delay"); #define DEFAULT_RADV 8 #define MAX_RXABSDELAY 0xFFFF #define MIN_RXABSDELAY 0 /* Interrupt Throttle Rate (interrupts/sec) * * Valid Range: 100-100000 (0=off, 1=dynamic, 3=dynamic conservative) */ E1000_PARAM(InterruptThrottleRate, "Interrupt Throttling Rate"); #define DEFAULT_ITR 3 #define MAX_ITR 100000 #define MIN_ITR 100 /* Enable Smart Power Down of the PHY * * Valid Range: 0, 1 * * Default Value: 0 (disabled) */ E1000_PARAM(SmartPowerDownEnable, "Enable PHY smart power down"); struct e1000_option { enum { enable_option, range_option, list_option } type; const char *name; const char *err; int def; union { struct { /* range_option info */ int min; int max; } r; struct { /* list_option info */ int nr; const struct e1000_opt_list { int i; char *str; } *p; } l; } arg; }; static int e1000_validate_option(unsigned int *value, const struct e1000_option *opt, struct e1000_adapter *adapter) { if (*value == OPTION_UNSET) { *value = opt->def; return 0; } switch (opt->type) { case enable_option: switch (*value) { case OPTION_ENABLED: e_dev_info("%s Enabled\n", opt->name); return 0; case OPTION_DISABLED: e_dev_info("%s Disabled\n", opt->name); return 0; } break; case range_option: if (*value >= opt->arg.r.min && *value <= opt->arg.r.max) { e_dev_info("%s set to %i\n", opt->name, *value); return 0; } break; case list_option: { int i; const struct e1000_opt_list *ent; for (i = 0; i < opt->arg.l.nr; i++) { ent = &opt->arg.l.p[i]; if (*value == ent->i) { if (ent->str[0] != '\0') e_dev_info("%s\n", ent->str); return 0; } } } break; default: BUG(); } e_dev_info("Invalid %s value specified (%i) %s\n", opt->name, *value, opt->err); *value = opt->def; return -1; } static void e1000_check_fiber_options(struct e1000_adapter *adapter); static void e1000_check_copper_options(struct e1000_adapter *adapter); /** * e1000_check_options - Range Checking for Command Line Parameters * @adapter: board private structure * * This routine checks all command line parameters for valid user * input. If an invalid value is given, or if no user specified * value exists, a default value is used. The final value is stored * in a variable in the adapter structure. **/ void e1000_check_options(struct e1000_adapter *adapter) { struct e1000_option opt; int bd = adapter->bd_number; if (bd >= E1000_MAX_NIC) { e_dev_warn("Warning: no configuration for board #%i " "using defaults for all values\n", bd); } { /* Transmit Descriptor Count */ struct e1000_tx_ring *tx_ring = adapter->tx_ring; int i; e1000_mac_type mac_type = adapter->hw.mac_type; opt = (struct e1000_option) { .type = range_option, .name = "Transmit Descriptors", .err = "using default of " __MODULE_STRING(E1000_DEFAULT_TXD), .def = E1000_DEFAULT_TXD, .arg = { .r = { .min = E1000_MIN_TXD, .max = mac_type < e1000_82544 ? E1000_MAX_TXD : E1000_MAX_82544_TXD }} }; if (num_TxDescriptors > bd) { tx_ring->count = TxDescriptors[bd]; e1000_validate_option(&tx_ring->count, &opt, adapter); tx_ring->count = ALIGN(tx_ring->count, REQ_TX_DESCRIPTOR_MULTIPLE); } else { tx_ring->count = opt.def; } for (i = 0; i < adapter->num_tx_queues; i++) tx_ring[i].count = tx_ring->count; } { /* Receive Descriptor Count */ struct e1000_rx_ring *rx_ring = adapter->rx_ring; int i; e1000_mac_type mac_type = adapter->hw.mac_type; opt = (struct e1000_option) { .type = range_option, .name = "Receive Descriptors", .err = "using default of " __MODULE_STRING(E1000_DEFAULT_RXD), .def = E1000_DEFAULT_RXD, .arg = { .r = { .min = E1000_MIN_RXD, .max = mac_type < e1000_82544 ? E1000_MAX_RXD : E1000_MAX_82544_RXD }} }; if (num_RxDescriptors > bd) { rx_ring->count = RxDescriptors[bd]; e1000_validate_option(&rx_ring->count, &opt, adapter); rx_ring->count = ALIGN(rx_ring->count, REQ_RX_DESCRIPTOR_MULTIPLE); } else { rx_ring->count = opt.def; } for (i = 0; i < adapter->num_rx_queues; i++) rx_ring[i].count = rx_ring->count; } { /* Checksum Offload Enable/Disable */ opt = (struct e1000_option) { .type = enable_option, .name = "Checksum Offload", .err = "defaulting to Enabled", .def = OPTION_ENABLED }; if (num_XsumRX > bd) { unsigned int rx_csum = XsumRX[bd]; e1000_validate_option(&rx_csum, &opt, adapter); adapter->rx_csum = rx_csum; } else { adapter->rx_csum = opt.def; } } { /* Flow Control */ static const struct e1000_opt_list fc_list[] = { { E1000_FC_NONE, "Flow Control Disabled" }, { E1000_FC_RX_PAUSE, "Flow Control Receive Only" }, { E1000_FC_TX_PAUSE, "Flow Control Transmit Only" }, { E1000_FC_FULL, "Flow Control Enabled" }, { E1000_FC_DEFAULT, "Flow Control Hardware Default" } }; opt = (struct e1000_option) { .type = list_option, .name = "Flow Control", .err = "reading default settings from EEPROM", .def = E1000_FC_DEFAULT, .arg = { .l = { .nr = ARRAY_SIZE(fc_list), .p = fc_list }} }; if (num_FlowControl > bd) { unsigned int fc = FlowControl[bd]; e1000_validate_option(&fc, &opt, adapter); adapter->hw.fc = adapter->hw.original_fc = fc; } else { adapter->hw.fc = adapter->hw.original_fc = opt.def; } } { /* Transmit Interrupt Delay */ opt = (struct e1000_option) { .type = range_option, .name = "Transmit Interrupt Delay", .err = "using default of " __MODULE_STRING(DEFAULT_TIDV), .def = DEFAULT_TIDV, .arg = { .r = { .min = MIN_TXDELAY, .max = MAX_TXDELAY }} }; if (num_TxIntDelay > bd) { adapter->tx_int_delay = TxIntDelay[bd]; e1000_validate_option(&adapter->tx_int_delay, &opt, adapter); } else { adapter->tx_int_delay = opt.def; } } { /* Transmit Absolute Interrupt Delay */ opt = (struct e1000_option) { .type = range_option, .name = "Transmit Absolute Interrupt Delay", .err = "using default of " __MODULE_STRING(DEFAULT_TADV), .def = DEFAULT_TADV, .arg = { .r = { .min = MIN_TXABSDELAY, .max = MAX_TXABSDELAY }} }; if (num_TxAbsIntDelay > bd) { adapter->tx_abs_int_delay = TxAbsIntDelay[bd]; e1000_validate_option(&adapter->tx_abs_int_delay, &opt, adapter); } else { adapter->tx_abs_int_delay = opt.def; } } { /* Receive Interrupt Delay */ opt = (struct e1000_option) { .type = range_option, .name = "Receive Interrupt Delay", .err = "using default of " __MODULE_STRING(DEFAULT_RDTR), .def = DEFAULT_RDTR, .arg = { .r = { .min = MIN_RXDELAY, .max = MAX_RXDELAY }} }; if (num_RxIntDelay > bd) { adapter->rx_int_delay = RxIntDelay[bd]; e1000_validate_option(&adapter->rx_int_delay, &opt, adapter); } else { adapter->rx_int_delay = opt.def; } } { /* Receive Absolute Interrupt Delay */ opt = (struct e1000_option) { .type = range_option, .name = "Receive Absolute Interrupt Delay", .err = "using default of " __MODULE_STRING(DEFAULT_RADV), .def = DEFAULT_RADV, .arg = { .r = { .min = MIN_RXABSDELAY, .max = MAX_RXABSDELAY }} }; if (num_RxAbsIntDelay > bd) { adapter->rx_abs_int_delay = RxAbsIntDelay[bd]; e1000_validate_option(&adapter->rx_abs_int_delay, &opt, adapter); } else { adapter->rx_abs_int_delay = opt.def; } } { /* Interrupt Throttling Rate */ opt = (struct e1000_option) { .type = range_option, .name = "Interrupt Throttling Rate (ints/sec)", .err = "using default of " __MODULE_STRING(DEFAULT_ITR), .def = DEFAULT_ITR, .arg = { .r = { .min = MIN_ITR, .max = MAX_ITR }} }; if (num_InterruptThrottleRate > bd) { adapter->itr = InterruptThrottleRate[bd]; switch (adapter->itr) { case 0: e_dev_info("%s turned off\n", opt.name); break; case 1: e_dev_info("%s set to dynamic mode\n", opt.name); adapter->itr_setting = adapter->itr; adapter->itr = 20000; break; case 3: e_dev_info("%s set to dynamic conservative " "mode\n", opt.name); adapter->itr_setting = adapter->itr; adapter->itr = 20000; break; case 4: e_dev_info("%s set to simplified " "(2000-8000) ints mode\n", opt.name); adapter->itr_setting = adapter->itr; break; default: e1000_validate_option(&adapter->itr, &opt, adapter); /* save the setting, because the dynamic bits * change itr. * clear the lower two bits because they are * used as control */ adapter->itr_setting = adapter->itr & ~3; break; } } else { adapter->itr_setting = opt.def; adapter->itr = 20000; } } { /* Smart Power Down */ opt = (struct e1000_option) { .type = enable_option, .name = "PHY Smart Power Down", .err = "defaulting to Disabled", .def = OPTION_DISABLED }; if (num_SmartPowerDownEnable > bd) { unsigned int spd = SmartPowerDownEnable[bd]; e1000_validate_option(&spd, &opt, adapter); adapter->smart_power_down = spd; } else { adapter->smart_power_down = opt.def; } } switch (adapter->hw.media_type) { case e1000_media_type_fiber: case e1000_media_type_internal_serdes: e1000_check_fiber_options(adapter); break; case e1000_media_type_copper: e1000_check_copper_options(adapter); break; default: BUG(); } } /** * e1000_check_fiber_options - Range Checking for Link Options, Fiber Version * @adapter: board private structure * * Handles speed and duplex options on fiber adapters **/ static void e1000_check_fiber_options(struct e1000_adapter *adapter) { int bd = adapter->bd_number; if (num_Speed > bd) { e_dev_info("Speed not valid for fiber adapters, parameter " "ignored\n"); } if (num_Duplex > bd) { e_dev_info("Duplex not valid for fiber adapters, parameter " "ignored\n"); } if ((num_AutoNeg > bd) && (AutoNeg[bd] != 0x20)) { e_dev_info("AutoNeg other than 1000/Full is not valid for fiber" "adapters, parameter ignored\n"); } } /** * e1000_check_copper_options - Range Checking for Link Options, Copper Version * @adapter: board private structure * * Handles speed and duplex options on copper adapters **/ static void e1000_check_copper_options(struct e1000_adapter *adapter) { struct e1000_option opt; unsigned int speed, dplx, an; int bd = adapter->bd_number; { /* Speed */ static const struct e1000_opt_list speed_list[] = { { 0, "" }, { SPEED_10, "" }, { SPEED_100, "" }, { SPEED_1000, "" }}; opt = (struct e1000_option) { .type = list_option, .name = "Speed", .err = "parameter ignored", .def = 0, .arg = { .l = { .nr = ARRAY_SIZE(speed_list), .p = speed_list }} }; if (num_Speed > bd) { speed = Speed[bd]; e1000_validate_option(&speed, &opt, adapter); } else { speed = opt.def; } } { /* Duplex */ static const struct e1000_opt_list dplx_list[] = { { 0, "" }, { HALF_DUPLEX, "" }, { FULL_DUPLEX, "" }}; opt = (struct e1000_option) { .type = list_option, .name = "Duplex", .err = "parameter ignored", .def = 0, .arg = { .l = { .nr = ARRAY_SIZE(dplx_list), .p = dplx_list }} }; if (num_Duplex > bd) { dplx = Duplex[bd]; e1000_validate_option(&dplx, &opt, adapter); } else { dplx = opt.def; } } if ((num_AutoNeg > bd) && (speed != 0 || dplx != 0)) { e_dev_info("AutoNeg specified along with Speed or Duplex, " "parameter ignored\n"); adapter->hw.autoneg_advertised = AUTONEG_ADV_DEFAULT; } else { /* Autoneg */ static const struct e1000_opt_list an_list[] = #define AA "AutoNeg advertising " {{ 0x01, AA "10/HD" }, { 0x02, AA "10/FD" }, { 0x03, AA "10/FD, 10/HD" }, { 0x04, AA "100/HD" }, { 0x05, AA "100/HD, 10/HD" }, { 0x06, AA "100/HD, 10/FD" }, { 0x07, AA "100/HD, 10/FD, 10/HD" }, { 0x08, AA "100/FD" }, { 0x09, AA "100/FD, 10/HD" }, { 0x0a, AA "100/FD, 10/FD" }, { 0x0b, AA "100/FD, 10/FD, 10/HD" }, { 0x0c, AA "100/FD, 100/HD" }, { 0x0d, AA "100/FD, 100/HD, 10/HD" }, { 0x0e, AA "100/FD, 100/HD, 10/FD" }, { 0x0f, AA "100/FD, 100/HD, 10/FD, 10/HD" }, { 0x20, AA "1000/FD" }, { 0x21, AA "1000/FD, 10/HD" }, { 0x22, AA "1000/FD, 10/FD" }, { 0x23, AA "1000/FD, 10/FD, 10/HD" }, { 0x24, AA "1000/FD, 100/HD" }, { 0x25, AA "1000/FD, 100/HD, 10/HD" }, { 0x26, AA "1000/FD, 100/HD, 10/FD" }, { 0x27, AA "1000/FD, 100/HD, 10/FD, 10/HD" }, { 0x28, AA "1000/FD, 100/FD" }, { 0x29, AA "1000/FD, 100/FD, 10/HD" }, { 0x2a, AA "1000/FD, 100/FD, 10/FD" }, { 0x2b, AA "1000/FD, 100/FD, 10/FD, 10/HD" }, { 0x2c, AA "1000/FD, 100/FD, 100/HD" }, { 0x2d, AA "1000/FD, 100/FD, 100/HD, 10/HD" }, { 0x2e, AA "1000/FD, 100/FD, 100/HD, 10/FD" }, { 0x2f, AA "1000/FD, 100/FD, 100/HD, 10/FD, 10/HD" }}; opt = (struct e1000_option) { .type = list_option, .name = "AutoNeg", .err = "parameter ignored", .def = AUTONEG_ADV_DEFAULT, .arg = { .l = { .nr = ARRAY_SIZE(an_list), .p = an_list }} }; if (num_AutoNeg > bd) { an = AutoNeg[bd]; e1000_validate_option(&an, &opt, adapter); } else { an = opt.def; } adapter->hw.autoneg_advertised = an; } switch (speed + dplx) { case 0: adapter->hw.autoneg = adapter->fc_autoneg = 1; if ((num_Speed > bd) && (speed != 0 || dplx != 0)) e_dev_info("Speed and duplex autonegotiation " "enabled\n"); break; case HALF_DUPLEX: e_dev_info("Half Duplex specified without Speed\n"); e_dev_info("Using Autonegotiation at Half Duplex only\n"); adapter->hw.autoneg = adapter->fc_autoneg = 1; adapter->hw.autoneg_advertised = ADVERTISE_10_HALF | ADVERTISE_100_HALF; break; case FULL_DUPLEX: e_dev_info("Full Duplex specified without Speed\n"); e_dev_info("Using Autonegotiation at Full Duplex only\n"); adapter->hw.autoneg = adapter->fc_autoneg = 1; adapter->hw.autoneg_advertised = ADVERTISE_10_FULL | ADVERTISE_100_FULL | ADVERTISE_1000_FULL; break; case SPEED_10: e_dev_info("10 Mbps Speed specified without Duplex\n"); e_dev_info("Using Autonegotiation at 10 Mbps only\n"); adapter->hw.autoneg = adapter->fc_autoneg = 1; adapter->hw.autoneg_advertised = ADVERTISE_10_HALF | ADVERTISE_10_FULL; break; case SPEED_10 + HALF_DUPLEX: e_dev_info("Forcing to 10 Mbps Half Duplex\n"); adapter->hw.autoneg = adapter->fc_autoneg = 0; adapter->hw.forced_speed_duplex = e1000_10_half; adapter->hw.autoneg_advertised = 0; break; case SPEED_10 + FULL_DUPLEX: e_dev_info("Forcing to 10 Mbps Full Duplex\n"); adapter->hw.autoneg = adapter->fc_autoneg = 0; adapter->hw.forced_speed_duplex = e1000_10_full; adapter->hw.autoneg_advertised = 0; break; case SPEED_100: e_dev_info("100 Mbps Speed specified without Duplex\n"); e_dev_info("Using Autonegotiation at 100 Mbps only\n"); adapter->hw.autoneg = adapter->fc_autoneg = 1; adapter->hw.autoneg_advertised = ADVERTISE_100_HALF | ADVERTISE_100_FULL; break; case SPEED_100 + HALF_DUPLEX: e_dev_info("Forcing to 100 Mbps Half Duplex\n"); adapter->hw.autoneg = adapter->fc_autoneg = 0; adapter->hw.forced_speed_duplex = e1000_100_half; adapter->hw.autoneg_advertised = 0; break; case SPEED_100 + FULL_DUPLEX: e_dev_info("Forcing to 100 Mbps Full Duplex\n"); adapter->hw.autoneg = adapter->fc_autoneg = 0; adapter->hw.forced_speed_duplex = e1000_100_full; adapter->hw.autoneg_advertised = 0; break; case SPEED_1000: e_dev_info("1000 Mbps Speed specified without Duplex\n"); goto full_duplex_only; case SPEED_1000 + HALF_DUPLEX: e_dev_info("Half Duplex is not supported at 1000 Mbps\n"); fallthrough; case SPEED_1000 + FULL_DUPLEX: full_duplex_only: e_dev_info("Using Autonegotiation at 1000 Mbps Full Duplex " "only\n"); adapter->hw.autoneg = adapter->fc_autoneg = 1; adapter->hw.autoneg_advertised = ADVERTISE_1000_FULL; break; default: BUG(); } /* Speed, AutoNeg and MDI/MDI-X must all play nice */ if (e1000_validate_mdi_setting(&(adapter->hw)) < 0) { e_dev_info("Speed, AutoNeg and MDI-X specs are incompatible. " "Setting MDI-X to a compatible value.\n"); } }
linux-master
drivers/net/ethernet/intel/e1000/e1000_param.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 1999 - 2006 Intel Corporation. */ /* ethtool support for e1000 */ #include "e1000.h" #include <linux/jiffies.h> #include <linux/uaccess.h> enum {NETDEV_STATS, E1000_STATS}; struct e1000_stats { char stat_string[ETH_GSTRING_LEN]; int type; int sizeof_stat; int stat_offset; }; #define E1000_STAT(m) E1000_STATS, \ sizeof(((struct e1000_adapter *)0)->m), \ offsetof(struct e1000_adapter, m) #define E1000_NETDEV_STAT(m) NETDEV_STATS, \ sizeof(((struct net_device *)0)->m), \ offsetof(struct net_device, m) static const struct e1000_stats e1000_gstrings_stats[] = { { "rx_packets", E1000_STAT(stats.gprc) }, { "tx_packets", E1000_STAT(stats.gptc) }, { "rx_bytes", E1000_STAT(stats.gorcl) }, { "tx_bytes", E1000_STAT(stats.gotcl) }, { "rx_broadcast", E1000_STAT(stats.bprc) }, { "tx_broadcast", E1000_STAT(stats.bptc) }, { "rx_multicast", E1000_STAT(stats.mprc) }, { "tx_multicast", E1000_STAT(stats.mptc) }, { "rx_errors", E1000_STAT(stats.rxerrc) }, { "tx_errors", E1000_STAT(stats.txerrc) }, { "tx_dropped", E1000_NETDEV_STAT(stats.tx_dropped) }, { "multicast", E1000_STAT(stats.mprc) }, { "collisions", E1000_STAT(stats.colc) }, { "rx_length_errors", E1000_STAT(stats.rlerrc) }, { "rx_over_errors", E1000_NETDEV_STAT(stats.rx_over_errors) }, { "rx_crc_errors", E1000_STAT(stats.crcerrs) }, { "rx_frame_errors", E1000_NETDEV_STAT(stats.rx_frame_errors) }, { "rx_no_buffer_count", E1000_STAT(stats.rnbc) }, { "rx_missed_errors", E1000_STAT(stats.mpc) }, { "tx_aborted_errors", E1000_STAT(stats.ecol) }, { "tx_carrier_errors", E1000_STAT(stats.tncrs) }, { "tx_fifo_errors", E1000_NETDEV_STAT(stats.tx_fifo_errors) }, { "tx_heartbeat_errors", E1000_NETDEV_STAT(stats.tx_heartbeat_errors) }, { "tx_window_errors", E1000_STAT(stats.latecol) }, { "tx_abort_late_coll", E1000_STAT(stats.latecol) }, { "tx_deferred_ok", E1000_STAT(stats.dc) }, { "tx_single_coll_ok", E1000_STAT(stats.scc) }, { "tx_multi_coll_ok", E1000_STAT(stats.mcc) }, { "tx_timeout_count", E1000_STAT(tx_timeout_count) }, { "tx_restart_queue", E1000_STAT(restart_queue) }, { "rx_long_length_errors", E1000_STAT(stats.roc) }, { "rx_short_length_errors", E1000_STAT(stats.ruc) }, { "rx_align_errors", E1000_STAT(stats.algnerrc) }, { "tx_tcp_seg_good", E1000_STAT(stats.tsctc) }, { "tx_tcp_seg_failed", E1000_STAT(stats.tsctfc) }, { "rx_flow_control_xon", E1000_STAT(stats.xonrxc) }, { "rx_flow_control_xoff", E1000_STAT(stats.xoffrxc) }, { "tx_flow_control_xon", E1000_STAT(stats.xontxc) }, { "tx_flow_control_xoff", E1000_STAT(stats.xofftxc) }, { "rx_long_byte_count", E1000_STAT(stats.gorcl) }, { "rx_csum_offload_good", E1000_STAT(hw_csum_good) }, { "rx_csum_offload_errors", E1000_STAT(hw_csum_err) }, { "alloc_rx_buff_failed", E1000_STAT(alloc_rx_buff_failed) }, { "tx_smbus", E1000_STAT(stats.mgptc) }, { "rx_smbus", E1000_STAT(stats.mgprc) }, { "dropped_smbus", E1000_STAT(stats.mgpdc) }, }; #define E1000_QUEUE_STATS_LEN 0 #define E1000_GLOBAL_STATS_LEN ARRAY_SIZE(e1000_gstrings_stats) #define E1000_STATS_LEN (E1000_GLOBAL_STATS_LEN + E1000_QUEUE_STATS_LEN) static const char e1000_gstrings_test[][ETH_GSTRING_LEN] = { "Register test (offline)", "Eeprom test (offline)", "Interrupt test (offline)", "Loopback test (offline)", "Link test (on/offline)" }; #define E1000_TEST_LEN ARRAY_SIZE(e1000_gstrings_test) static int e1000_get_link_ksettings(struct net_device *netdev, struct ethtool_link_ksettings *cmd) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u32 supported, advertising; if (hw->media_type == e1000_media_type_copper) { supported = (SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full | SUPPORTED_100baseT_Half | SUPPORTED_100baseT_Full | SUPPORTED_1000baseT_Full| SUPPORTED_Autoneg | SUPPORTED_TP); advertising = ADVERTISED_TP; if (hw->autoneg == 1) { advertising |= ADVERTISED_Autoneg; /* the e1000 autoneg seems to match ethtool nicely */ advertising |= hw->autoneg_advertised; } cmd->base.port = PORT_TP; cmd->base.phy_address = hw->phy_addr; } else { supported = (SUPPORTED_1000baseT_Full | SUPPORTED_FIBRE | SUPPORTED_Autoneg); advertising = (ADVERTISED_1000baseT_Full | ADVERTISED_FIBRE | ADVERTISED_Autoneg); cmd->base.port = PORT_FIBRE; } if (er32(STATUS) & E1000_STATUS_LU) { e1000_get_speed_and_duplex(hw, &adapter->link_speed, &adapter->link_duplex); cmd->base.speed = adapter->link_speed; /* unfortunately FULL_DUPLEX != DUPLEX_FULL * and HALF_DUPLEX != DUPLEX_HALF */ if (adapter->link_duplex == FULL_DUPLEX) cmd->base.duplex = DUPLEX_FULL; else cmd->base.duplex = DUPLEX_HALF; } else { cmd->base.speed = SPEED_UNKNOWN; cmd->base.duplex = DUPLEX_UNKNOWN; } cmd->base.autoneg = ((hw->media_type == e1000_media_type_fiber) || hw->autoneg) ? AUTONEG_ENABLE : AUTONEG_DISABLE; /* MDI-X => 1; MDI => 0 */ if ((hw->media_type == e1000_media_type_copper) && netif_carrier_ok(netdev)) cmd->base.eth_tp_mdix = (!!adapter->phy_info.mdix_mode ? ETH_TP_MDI_X : ETH_TP_MDI); else cmd->base.eth_tp_mdix = ETH_TP_MDI_INVALID; if (hw->mdix == AUTO_ALL_MODES) cmd->base.eth_tp_mdix_ctrl = ETH_TP_MDI_AUTO; else cmd->base.eth_tp_mdix_ctrl = hw->mdix; ethtool_convert_legacy_u32_to_link_mode(cmd->link_modes.supported, supported); ethtool_convert_legacy_u32_to_link_mode(cmd->link_modes.advertising, advertising); return 0; } static int e1000_set_link_ksettings(struct net_device *netdev, const struct ethtool_link_ksettings *cmd) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u32 advertising; ethtool_convert_link_mode_to_legacy_u32(&advertising, cmd->link_modes.advertising); /* MDI setting is only allowed when autoneg enabled because * some hardware doesn't allow MDI setting when speed or * duplex is forced. */ if (cmd->base.eth_tp_mdix_ctrl) { if (hw->media_type != e1000_media_type_copper) return -EOPNOTSUPP; if ((cmd->base.eth_tp_mdix_ctrl != ETH_TP_MDI_AUTO) && (cmd->base.autoneg != AUTONEG_ENABLE)) { e_err(drv, "forcing MDI/MDI-X state is not supported when link speed and/or duplex are forced\n"); return -EINVAL; } } while (test_and_set_bit(__E1000_RESETTING, &adapter->flags)) msleep(1); if (cmd->base.autoneg == AUTONEG_ENABLE) { hw->autoneg = 1; if (hw->media_type == e1000_media_type_fiber) hw->autoneg_advertised = ADVERTISED_1000baseT_Full | ADVERTISED_FIBRE | ADVERTISED_Autoneg; else hw->autoneg_advertised = advertising | ADVERTISED_TP | ADVERTISED_Autoneg; } else { u32 speed = cmd->base.speed; /* calling this overrides forced MDI setting */ if (e1000_set_spd_dplx(adapter, speed, cmd->base.duplex)) { clear_bit(__E1000_RESETTING, &adapter->flags); return -EINVAL; } } /* MDI-X => 2; MDI => 1; Auto => 3 */ if (cmd->base.eth_tp_mdix_ctrl) { if (cmd->base.eth_tp_mdix_ctrl == ETH_TP_MDI_AUTO) hw->mdix = AUTO_ALL_MODES; else hw->mdix = cmd->base.eth_tp_mdix_ctrl; } /* reset the link */ if (netif_running(adapter->netdev)) { e1000_down(adapter); e1000_up(adapter); } else { e1000_reset(adapter); } clear_bit(__E1000_RESETTING, &adapter->flags); return 0; } static u32 e1000_get_link(struct net_device *netdev) { struct e1000_adapter *adapter = netdev_priv(netdev); /* If the link is not reported up to netdev, interrupts are disabled, * and so the physical link state may have changed since we last * looked. Set get_link_status to make sure that the true link * state is interrogated, rather than pulling a cached and possibly * stale link state from the driver. */ if (!netif_carrier_ok(netdev)) adapter->hw.get_link_status = 1; return e1000_has_link(adapter); } static void e1000_get_pauseparam(struct net_device *netdev, struct ethtool_pauseparam *pause) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; pause->autoneg = (adapter->fc_autoneg ? AUTONEG_ENABLE : AUTONEG_DISABLE); if (hw->fc == E1000_FC_RX_PAUSE) { pause->rx_pause = 1; } else if (hw->fc == E1000_FC_TX_PAUSE) { pause->tx_pause = 1; } else if (hw->fc == E1000_FC_FULL) { pause->rx_pause = 1; pause->tx_pause = 1; } } static int e1000_set_pauseparam(struct net_device *netdev, struct ethtool_pauseparam *pause) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; int retval = 0; adapter->fc_autoneg = pause->autoneg; while (test_and_set_bit(__E1000_RESETTING, &adapter->flags)) msleep(1); if (pause->rx_pause && pause->tx_pause) hw->fc = E1000_FC_FULL; else if (pause->rx_pause && !pause->tx_pause) hw->fc = E1000_FC_RX_PAUSE; else if (!pause->rx_pause && pause->tx_pause) hw->fc = E1000_FC_TX_PAUSE; else if (!pause->rx_pause && !pause->tx_pause) hw->fc = E1000_FC_NONE; hw->original_fc = hw->fc; if (adapter->fc_autoneg == AUTONEG_ENABLE) { if (netif_running(adapter->netdev)) { e1000_down(adapter); e1000_up(adapter); } else { e1000_reset(adapter); } } else retval = ((hw->media_type == e1000_media_type_fiber) ? e1000_setup_link(hw) : e1000_force_mac_fc(hw)); clear_bit(__E1000_RESETTING, &adapter->flags); return retval; } static u32 e1000_get_msglevel(struct net_device *netdev) { struct e1000_adapter *adapter = netdev_priv(netdev); return adapter->msg_enable; } static void e1000_set_msglevel(struct net_device *netdev, u32 data) { struct e1000_adapter *adapter = netdev_priv(netdev); adapter->msg_enable = data; } static int e1000_get_regs_len(struct net_device *netdev) { #define E1000_REGS_LEN 32 return E1000_REGS_LEN * sizeof(u32); } static void e1000_get_regs(struct net_device *netdev, struct ethtool_regs *regs, void *p) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u32 *regs_buff = p; u16 phy_data; memset(p, 0, E1000_REGS_LEN * sizeof(u32)); regs->version = (1 << 24) | (hw->revision_id << 16) | hw->device_id; regs_buff[0] = er32(CTRL); regs_buff[1] = er32(STATUS); regs_buff[2] = er32(RCTL); regs_buff[3] = er32(RDLEN); regs_buff[4] = er32(RDH); regs_buff[5] = er32(RDT); regs_buff[6] = er32(RDTR); regs_buff[7] = er32(TCTL); regs_buff[8] = er32(TDLEN); regs_buff[9] = er32(TDH); regs_buff[10] = er32(TDT); regs_buff[11] = er32(TIDV); regs_buff[12] = hw->phy_type; /* PHY type (IGP=1, M88=0) */ if (hw->phy_type == e1000_phy_igp) { e1000_write_phy_reg(hw, IGP01E1000_PHY_PAGE_SELECT, IGP01E1000_PHY_AGC_A); e1000_read_phy_reg(hw, IGP01E1000_PHY_AGC_A & IGP01E1000_PHY_PAGE_SELECT, &phy_data); regs_buff[13] = (u32)phy_data; /* cable length */ e1000_write_phy_reg(hw, IGP01E1000_PHY_PAGE_SELECT, IGP01E1000_PHY_AGC_B); e1000_read_phy_reg(hw, IGP01E1000_PHY_AGC_B & IGP01E1000_PHY_PAGE_SELECT, &phy_data); regs_buff[14] = (u32)phy_data; /* cable length */ e1000_write_phy_reg(hw, IGP01E1000_PHY_PAGE_SELECT, IGP01E1000_PHY_AGC_C); e1000_read_phy_reg(hw, IGP01E1000_PHY_AGC_C & IGP01E1000_PHY_PAGE_SELECT, &phy_data); regs_buff[15] = (u32)phy_data; /* cable length */ e1000_write_phy_reg(hw, IGP01E1000_PHY_PAGE_SELECT, IGP01E1000_PHY_AGC_D); e1000_read_phy_reg(hw, IGP01E1000_PHY_AGC_D & IGP01E1000_PHY_PAGE_SELECT, &phy_data); regs_buff[16] = (u32)phy_data; /* cable length */ regs_buff[17] = 0; /* extended 10bt distance (not needed) */ e1000_write_phy_reg(hw, IGP01E1000_PHY_PAGE_SELECT, 0x0); e1000_read_phy_reg(hw, IGP01E1000_PHY_PORT_STATUS & IGP01E1000_PHY_PAGE_SELECT, &phy_data); regs_buff[18] = (u32)phy_data; /* cable polarity */ e1000_write_phy_reg(hw, IGP01E1000_PHY_PAGE_SELECT, IGP01E1000_PHY_PCS_INIT_REG); e1000_read_phy_reg(hw, IGP01E1000_PHY_PCS_INIT_REG & IGP01E1000_PHY_PAGE_SELECT, &phy_data); regs_buff[19] = (u32)phy_data; /* cable polarity */ regs_buff[20] = 0; /* polarity correction enabled (always) */ regs_buff[22] = 0; /* phy receive errors (unavailable) */ regs_buff[23] = regs_buff[18]; /* mdix mode */ e1000_write_phy_reg(hw, IGP01E1000_PHY_PAGE_SELECT, 0x0); } else { e1000_read_phy_reg(hw, M88E1000_PHY_SPEC_STATUS, &phy_data); regs_buff[13] = (u32)phy_data; /* cable length */ regs_buff[14] = 0; /* Dummy (to align w/ IGP phy reg dump) */ regs_buff[15] = 0; /* Dummy (to align w/ IGP phy reg dump) */ regs_buff[16] = 0; /* Dummy (to align w/ IGP phy reg dump) */ e1000_read_phy_reg(hw, M88E1000_PHY_SPEC_CTRL, &phy_data); regs_buff[17] = (u32)phy_data; /* extended 10bt distance */ regs_buff[18] = regs_buff[13]; /* cable polarity */ regs_buff[19] = 0; /* Dummy (to align w/ IGP phy reg dump) */ regs_buff[20] = regs_buff[17]; /* polarity correction */ /* phy receive errors */ regs_buff[22] = adapter->phy_stats.receive_errors; regs_buff[23] = regs_buff[13]; /* mdix mode */ } regs_buff[21] = adapter->phy_stats.idle_errors; /* phy idle errors */ e1000_read_phy_reg(hw, PHY_1000T_STATUS, &phy_data); regs_buff[24] = (u32)phy_data; /* phy local receiver status */ regs_buff[25] = regs_buff[24]; /* phy remote receiver status */ if (hw->mac_type >= e1000_82540 && hw->media_type == e1000_media_type_copper) { regs_buff[26] = er32(MANC); } } static int e1000_get_eeprom_len(struct net_device *netdev) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; return hw->eeprom.word_size * 2; } static int e1000_get_eeprom(struct net_device *netdev, struct ethtool_eeprom *eeprom, u8 *bytes) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u16 *eeprom_buff; int first_word, last_word; int ret_val = 0; u16 i; if (eeprom->len == 0) return -EINVAL; eeprom->magic = hw->vendor_id | (hw->device_id << 16); first_word = eeprom->offset >> 1; last_word = (eeprom->offset + eeprom->len - 1) >> 1; eeprom_buff = kmalloc_array(last_word - first_word + 1, sizeof(u16), GFP_KERNEL); if (!eeprom_buff) return -ENOMEM; if (hw->eeprom.type == e1000_eeprom_spi) ret_val = e1000_read_eeprom(hw, first_word, last_word - first_word + 1, eeprom_buff); else { for (i = 0; i < last_word - first_word + 1; i++) { ret_val = e1000_read_eeprom(hw, first_word + i, 1, &eeprom_buff[i]); if (ret_val) break; } } /* Device's eeprom is always little-endian, word addressable */ for (i = 0; i < last_word - first_word + 1; i++) le16_to_cpus(&eeprom_buff[i]); memcpy(bytes, (u8 *)eeprom_buff + (eeprom->offset & 1), eeprom->len); kfree(eeprom_buff); return ret_val; } static int e1000_set_eeprom(struct net_device *netdev, struct ethtool_eeprom *eeprom, u8 *bytes) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u16 *eeprom_buff; void *ptr; int max_len, first_word, last_word, ret_val = 0; u16 i; if (eeprom->len == 0) return -EOPNOTSUPP; if (eeprom->magic != (hw->vendor_id | (hw->device_id << 16))) return -EFAULT; max_len = hw->eeprom.word_size * 2; first_word = eeprom->offset >> 1; last_word = (eeprom->offset + eeprom->len - 1) >> 1; eeprom_buff = kmalloc(max_len, GFP_KERNEL); if (!eeprom_buff) return -ENOMEM; ptr = (void *)eeprom_buff; if (eeprom->offset & 1) { /* need read/modify/write of first changed EEPROM word * only the second byte of the word is being modified */ ret_val = e1000_read_eeprom(hw, first_word, 1, &eeprom_buff[0]); ptr++; } if (((eeprom->offset + eeprom->len) & 1) && (ret_val == 0)) { /* need read/modify/write of last changed EEPROM word * only the first byte of the word is being modified */ ret_val = e1000_read_eeprom(hw, last_word, 1, &eeprom_buff[last_word - first_word]); } /* Device's eeprom is always little-endian, word addressable */ for (i = 0; i < last_word - first_word + 1; i++) le16_to_cpus(&eeprom_buff[i]); memcpy(ptr, bytes, eeprom->len); for (i = 0; i < last_word - first_word + 1; i++) cpu_to_le16s(&eeprom_buff[i]); ret_val = e1000_write_eeprom(hw, first_word, last_word - first_word + 1, eeprom_buff); /* Update the checksum over the first part of the EEPROM if needed */ if ((ret_val == 0) && (first_word <= EEPROM_CHECKSUM_REG)) e1000_update_eeprom_checksum(hw); kfree(eeprom_buff); return ret_val; } static void e1000_get_drvinfo(struct net_device *netdev, struct ethtool_drvinfo *drvinfo) { struct e1000_adapter *adapter = netdev_priv(netdev); strscpy(drvinfo->driver, e1000_driver_name, sizeof(drvinfo->driver)); strscpy(drvinfo->bus_info, pci_name(adapter->pdev), sizeof(drvinfo->bus_info)); } static void e1000_get_ringparam(struct net_device *netdev, struct ethtool_ringparam *ring, struct kernel_ethtool_ringparam *kernel_ring, struct netlink_ext_ack *extack) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; e1000_mac_type mac_type = hw->mac_type; struct e1000_tx_ring *txdr = adapter->tx_ring; struct e1000_rx_ring *rxdr = adapter->rx_ring; ring->rx_max_pending = (mac_type < e1000_82544) ? E1000_MAX_RXD : E1000_MAX_82544_RXD; ring->tx_max_pending = (mac_type < e1000_82544) ? E1000_MAX_TXD : E1000_MAX_82544_TXD; ring->rx_pending = rxdr->count; ring->tx_pending = txdr->count; } static int e1000_set_ringparam(struct net_device *netdev, struct ethtool_ringparam *ring, struct kernel_ethtool_ringparam *kernel_ring, struct netlink_ext_ack *extack) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; e1000_mac_type mac_type = hw->mac_type; struct e1000_tx_ring *txdr, *tx_old; struct e1000_rx_ring *rxdr, *rx_old; int i, err; if ((ring->rx_mini_pending) || (ring->rx_jumbo_pending)) return -EINVAL; while (test_and_set_bit(__E1000_RESETTING, &adapter->flags)) msleep(1); if (netif_running(adapter->netdev)) e1000_down(adapter); tx_old = adapter->tx_ring; rx_old = adapter->rx_ring; err = -ENOMEM; txdr = kcalloc(adapter->num_tx_queues, sizeof(struct e1000_tx_ring), GFP_KERNEL); if (!txdr) goto err_alloc_tx; rxdr = kcalloc(adapter->num_rx_queues, sizeof(struct e1000_rx_ring), GFP_KERNEL); if (!rxdr) goto err_alloc_rx; adapter->tx_ring = txdr; adapter->rx_ring = rxdr; rxdr->count = max(ring->rx_pending, (u32)E1000_MIN_RXD); rxdr->count = min(rxdr->count, (u32)(mac_type < e1000_82544 ? E1000_MAX_RXD : E1000_MAX_82544_RXD)); rxdr->count = ALIGN(rxdr->count, REQ_RX_DESCRIPTOR_MULTIPLE); txdr->count = max(ring->tx_pending, (u32)E1000_MIN_TXD); txdr->count = min(txdr->count, (u32)(mac_type < e1000_82544 ? E1000_MAX_TXD : E1000_MAX_82544_TXD)); txdr->count = ALIGN(txdr->count, REQ_TX_DESCRIPTOR_MULTIPLE); for (i = 0; i < adapter->num_tx_queues; i++) txdr[i].count = txdr->count; for (i = 0; i < adapter->num_rx_queues; i++) rxdr[i].count = rxdr->count; err = 0; if (netif_running(adapter->netdev)) { /* Try to get new resources before deleting old */ err = e1000_setup_all_rx_resources(adapter); if (err) goto err_setup_rx; err = e1000_setup_all_tx_resources(adapter); if (err) goto err_setup_tx; /* save the new, restore the old in order to free it, * then restore the new back again */ adapter->rx_ring = rx_old; adapter->tx_ring = tx_old; e1000_free_all_rx_resources(adapter); e1000_free_all_tx_resources(adapter); adapter->rx_ring = rxdr; adapter->tx_ring = txdr; err = e1000_up(adapter); } kfree(tx_old); kfree(rx_old); clear_bit(__E1000_RESETTING, &adapter->flags); return err; err_setup_tx: e1000_free_all_rx_resources(adapter); err_setup_rx: adapter->rx_ring = rx_old; adapter->tx_ring = tx_old; kfree(rxdr); err_alloc_rx: kfree(txdr); err_alloc_tx: if (netif_running(adapter->netdev)) e1000_up(adapter); clear_bit(__E1000_RESETTING, &adapter->flags); return err; } static bool reg_pattern_test(struct e1000_adapter *adapter, u64 *data, int reg, u32 mask, u32 write) { struct e1000_hw *hw = &adapter->hw; static const u32 test[] = { 0x5A5A5A5A, 0xA5A5A5A5, 0x00000000, 0xFFFFFFFF }; u8 __iomem *address = hw->hw_addr + reg; u32 read; int i; for (i = 0; i < ARRAY_SIZE(test); i++) { writel(write & test[i], address); read = readl(address); if (read != (write & test[i] & mask)) { e_err(drv, "pattern test reg %04X failed: " "got 0x%08X expected 0x%08X\n", reg, read, (write & test[i] & mask)); *data = reg; return true; } } return false; } static bool reg_set_and_check(struct e1000_adapter *adapter, u64 *data, int reg, u32 mask, u32 write) { struct e1000_hw *hw = &adapter->hw; u8 __iomem *address = hw->hw_addr + reg; u32 read; writel(write & mask, address); read = readl(address); if ((read & mask) != (write & mask)) { e_err(drv, "set/check reg %04X test failed: " "got 0x%08X expected 0x%08X\n", reg, (read & mask), (write & mask)); *data = reg; return true; } return false; } #define REG_PATTERN_TEST(reg, mask, write) \ do { \ if (reg_pattern_test(adapter, data, \ (hw->mac_type >= e1000_82543) \ ? E1000_##reg : E1000_82542_##reg, \ mask, write)) \ return 1; \ } while (0) #define REG_SET_AND_CHECK(reg, mask, write) \ do { \ if (reg_set_and_check(adapter, data, \ (hw->mac_type >= e1000_82543) \ ? E1000_##reg : E1000_82542_##reg, \ mask, write)) \ return 1; \ } while (0) static int e1000_reg_test(struct e1000_adapter *adapter, u64 *data) { u32 value, before, after; u32 i, toggle; struct e1000_hw *hw = &adapter->hw; /* The status register is Read Only, so a write should fail. * Some bits that get toggled are ignored. */ /* there are several bits on newer hardware that are r/w */ toggle = 0xFFFFF833; before = er32(STATUS); value = (er32(STATUS) & toggle); ew32(STATUS, toggle); after = er32(STATUS) & toggle; if (value != after) { e_err(drv, "failed STATUS register test got: " "0x%08X expected: 0x%08X\n", after, value); *data = 1; return 1; } /* restore previous status */ ew32(STATUS, before); REG_PATTERN_TEST(FCAL, 0xFFFFFFFF, 0xFFFFFFFF); REG_PATTERN_TEST(FCAH, 0x0000FFFF, 0xFFFFFFFF); REG_PATTERN_TEST(FCT, 0x0000FFFF, 0xFFFFFFFF); REG_PATTERN_TEST(VET, 0x0000FFFF, 0xFFFFFFFF); REG_PATTERN_TEST(RDTR, 0x0000FFFF, 0xFFFFFFFF); REG_PATTERN_TEST(RDBAH, 0xFFFFFFFF, 0xFFFFFFFF); REG_PATTERN_TEST(RDLEN, 0x000FFF80, 0x000FFFFF); REG_PATTERN_TEST(RDH, 0x0000FFFF, 0x0000FFFF); REG_PATTERN_TEST(RDT, 0x0000FFFF, 0x0000FFFF); REG_PATTERN_TEST(FCRTH, 0x0000FFF8, 0x0000FFF8); REG_PATTERN_TEST(FCTTV, 0x0000FFFF, 0x0000FFFF); REG_PATTERN_TEST(TIPG, 0x3FFFFFFF, 0x3FFFFFFF); REG_PATTERN_TEST(TDBAH, 0xFFFFFFFF, 0xFFFFFFFF); REG_PATTERN_TEST(TDLEN, 0x000FFF80, 0x000FFFFF); REG_SET_AND_CHECK(RCTL, 0xFFFFFFFF, 0x00000000); before = 0x06DFB3FE; REG_SET_AND_CHECK(RCTL, before, 0x003FFFFB); REG_SET_AND_CHECK(TCTL, 0xFFFFFFFF, 0x00000000); if (hw->mac_type >= e1000_82543) { REG_SET_AND_CHECK(RCTL, before, 0xFFFFFFFF); REG_PATTERN_TEST(RDBAL, 0xFFFFFFF0, 0xFFFFFFFF); REG_PATTERN_TEST(TXCW, 0xC000FFFF, 0x0000FFFF); REG_PATTERN_TEST(TDBAL, 0xFFFFFFF0, 0xFFFFFFFF); REG_PATTERN_TEST(TIDV, 0x0000FFFF, 0x0000FFFF); value = E1000_RAR_ENTRIES; for (i = 0; i < value; i++) { REG_PATTERN_TEST(RA + (((i << 1) + 1) << 2), 0x8003FFFF, 0xFFFFFFFF); } } else { REG_SET_AND_CHECK(RCTL, 0xFFFFFFFF, 0x01FFFFFF); REG_PATTERN_TEST(RDBAL, 0xFFFFF000, 0xFFFFFFFF); REG_PATTERN_TEST(TXCW, 0x0000FFFF, 0x0000FFFF); REG_PATTERN_TEST(TDBAL, 0xFFFFF000, 0xFFFFFFFF); } value = E1000_MC_TBL_SIZE; for (i = 0; i < value; i++) REG_PATTERN_TEST(MTA + (i << 2), 0xFFFFFFFF, 0xFFFFFFFF); *data = 0; return 0; } static int e1000_eeprom_test(struct e1000_adapter *adapter, u64 *data) { struct e1000_hw *hw = &adapter->hw; u16 temp; u16 checksum = 0; u16 i; *data = 0; /* Read and add up the contents of the EEPROM */ for (i = 0; i < (EEPROM_CHECKSUM_REG + 1); i++) { if ((e1000_read_eeprom(hw, i, 1, &temp)) < 0) { *data = 1; break; } checksum += temp; } /* If Checksum is not Correct return error else test passed */ if ((checksum != (u16)EEPROM_SUM) && !(*data)) *data = 2; return *data; } static irqreturn_t e1000_test_intr(int irq, void *data) { struct net_device *netdev = (struct net_device *)data; struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; adapter->test_icr |= er32(ICR); return IRQ_HANDLED; } static int e1000_intr_test(struct e1000_adapter *adapter, u64 *data) { struct net_device *netdev = adapter->netdev; u32 mask, i = 0; bool shared_int = true; u32 irq = adapter->pdev->irq; struct e1000_hw *hw = &adapter->hw; *data = 0; /* NOTE: we don't test MSI interrupts here, yet * Hook up test interrupt handler just for this test */ if (!request_irq(irq, e1000_test_intr, IRQF_PROBE_SHARED, netdev->name, netdev)) shared_int = false; else if (request_irq(irq, e1000_test_intr, IRQF_SHARED, netdev->name, netdev)) { *data = 1; return -1; } e_info(hw, "testing %s interrupt\n", (shared_int ? "shared" : "unshared")); /* Disable all the interrupts */ ew32(IMC, 0xFFFFFFFF); E1000_WRITE_FLUSH(); msleep(10); /* Test each interrupt */ for (; i < 10; i++) { /* Interrupt to test */ mask = 1 << i; if (!shared_int) { /* Disable the interrupt to be reported in * the cause register and then force the same * interrupt and see if one gets posted. If * an interrupt was posted to the bus, the * test failed. */ adapter->test_icr = 0; ew32(IMC, mask); ew32(ICS, mask); E1000_WRITE_FLUSH(); msleep(10); if (adapter->test_icr & mask) { *data = 3; break; } } /* Enable the interrupt to be reported in * the cause register and then force the same * interrupt and see if one gets posted. If * an interrupt was not posted to the bus, the * test failed. */ adapter->test_icr = 0; ew32(IMS, mask); ew32(ICS, mask); E1000_WRITE_FLUSH(); msleep(10); if (!(adapter->test_icr & mask)) { *data = 4; break; } if (!shared_int) { /* Disable the other interrupts to be reported in * the cause register and then force the other * interrupts and see if any get posted. If * an interrupt was posted to the bus, the * test failed. */ adapter->test_icr = 0; ew32(IMC, ~mask & 0x00007FFF); ew32(ICS, ~mask & 0x00007FFF); E1000_WRITE_FLUSH(); msleep(10); if (adapter->test_icr) { *data = 5; break; } } } /* Disable all the interrupts */ ew32(IMC, 0xFFFFFFFF); E1000_WRITE_FLUSH(); msleep(10); /* Unhook test interrupt handler */ free_irq(irq, netdev); return *data; } static void e1000_free_desc_rings(struct e1000_adapter *adapter) { struct e1000_tx_ring *txdr = &adapter->test_tx_ring; struct e1000_rx_ring *rxdr = &adapter->test_rx_ring; struct pci_dev *pdev = adapter->pdev; int i; if (txdr->desc && txdr->buffer_info) { for (i = 0; i < txdr->count; i++) { if (txdr->buffer_info[i].dma) dma_unmap_single(&pdev->dev, txdr->buffer_info[i].dma, txdr->buffer_info[i].length, DMA_TO_DEVICE); dev_kfree_skb(txdr->buffer_info[i].skb); } } if (rxdr->desc && rxdr->buffer_info) { for (i = 0; i < rxdr->count; i++) { if (rxdr->buffer_info[i].dma) dma_unmap_single(&pdev->dev, rxdr->buffer_info[i].dma, E1000_RXBUFFER_2048, DMA_FROM_DEVICE); kfree(rxdr->buffer_info[i].rxbuf.data); } } if (txdr->desc) { dma_free_coherent(&pdev->dev, txdr->size, txdr->desc, txdr->dma); txdr->desc = NULL; } if (rxdr->desc) { dma_free_coherent(&pdev->dev, rxdr->size, rxdr->desc, rxdr->dma); rxdr->desc = NULL; } kfree(txdr->buffer_info); txdr->buffer_info = NULL; kfree(rxdr->buffer_info); rxdr->buffer_info = NULL; } static int e1000_setup_desc_rings(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; struct e1000_tx_ring *txdr = &adapter->test_tx_ring; struct e1000_rx_ring *rxdr = &adapter->test_rx_ring; struct pci_dev *pdev = adapter->pdev; u32 rctl; int i, ret_val; /* Setup Tx descriptor ring and Tx buffers */ if (!txdr->count) txdr->count = E1000_DEFAULT_TXD; txdr->buffer_info = kcalloc(txdr->count, sizeof(struct e1000_tx_buffer), GFP_KERNEL); if (!txdr->buffer_info) { ret_val = 1; goto err_nomem; } txdr->size = txdr->count * sizeof(struct e1000_tx_desc); txdr->size = ALIGN(txdr->size, 4096); txdr->desc = dma_alloc_coherent(&pdev->dev, txdr->size, &txdr->dma, GFP_KERNEL); if (!txdr->desc) { ret_val = 2; goto err_nomem; } txdr->next_to_use = txdr->next_to_clean = 0; ew32(TDBAL, ((u64)txdr->dma & 0x00000000FFFFFFFF)); ew32(TDBAH, ((u64)txdr->dma >> 32)); ew32(TDLEN, txdr->count * sizeof(struct e1000_tx_desc)); ew32(TDH, 0); ew32(TDT, 0); ew32(TCTL, E1000_TCTL_PSP | E1000_TCTL_EN | E1000_COLLISION_THRESHOLD << E1000_CT_SHIFT | E1000_FDX_COLLISION_DISTANCE << E1000_COLD_SHIFT); for (i = 0; i < txdr->count; i++) { struct e1000_tx_desc *tx_desc = E1000_TX_DESC(*txdr, i); struct sk_buff *skb; unsigned int size = 1024; skb = alloc_skb(size, GFP_KERNEL); if (!skb) { ret_val = 3; goto err_nomem; } skb_put(skb, size); txdr->buffer_info[i].skb = skb; txdr->buffer_info[i].length = skb->len; txdr->buffer_info[i].dma = dma_map_single(&pdev->dev, skb->data, skb->len, DMA_TO_DEVICE); if (dma_mapping_error(&pdev->dev, txdr->buffer_info[i].dma)) { ret_val = 4; goto err_nomem; } tx_desc->buffer_addr = cpu_to_le64(txdr->buffer_info[i].dma); tx_desc->lower.data = cpu_to_le32(skb->len); tx_desc->lower.data |= cpu_to_le32(E1000_TXD_CMD_EOP | E1000_TXD_CMD_IFCS | E1000_TXD_CMD_RPS); tx_desc->upper.data = 0; } /* Setup Rx descriptor ring and Rx buffers */ if (!rxdr->count) rxdr->count = E1000_DEFAULT_RXD; rxdr->buffer_info = kcalloc(rxdr->count, sizeof(struct e1000_rx_buffer), GFP_KERNEL); if (!rxdr->buffer_info) { ret_val = 5; goto err_nomem; } rxdr->size = rxdr->count * sizeof(struct e1000_rx_desc); rxdr->desc = dma_alloc_coherent(&pdev->dev, rxdr->size, &rxdr->dma, GFP_KERNEL); if (!rxdr->desc) { ret_val = 6; goto err_nomem; } rxdr->next_to_use = rxdr->next_to_clean = 0; rctl = er32(RCTL); ew32(RCTL, rctl & ~E1000_RCTL_EN); ew32(RDBAL, ((u64)rxdr->dma & 0xFFFFFFFF)); ew32(RDBAH, ((u64)rxdr->dma >> 32)); ew32(RDLEN, rxdr->size); ew32(RDH, 0); ew32(RDT, 0); rctl = E1000_RCTL_EN | E1000_RCTL_BAM | E1000_RCTL_SZ_2048 | E1000_RCTL_LBM_NO | E1000_RCTL_RDMTS_HALF | (hw->mc_filter_type << E1000_RCTL_MO_SHIFT); ew32(RCTL, rctl); for (i = 0; i < rxdr->count; i++) { struct e1000_rx_desc *rx_desc = E1000_RX_DESC(*rxdr, i); u8 *buf; buf = kzalloc(E1000_RXBUFFER_2048 + NET_SKB_PAD + NET_IP_ALIGN, GFP_KERNEL); if (!buf) { ret_val = 7; goto err_nomem; } rxdr->buffer_info[i].rxbuf.data = buf; rxdr->buffer_info[i].dma = dma_map_single(&pdev->dev, buf + NET_SKB_PAD + NET_IP_ALIGN, E1000_RXBUFFER_2048, DMA_FROM_DEVICE); if (dma_mapping_error(&pdev->dev, rxdr->buffer_info[i].dma)) { ret_val = 8; goto err_nomem; } rx_desc->buffer_addr = cpu_to_le64(rxdr->buffer_info[i].dma); } return 0; err_nomem: e1000_free_desc_rings(adapter); return ret_val; } static void e1000_phy_disable_receiver(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; /* Write out to PHY registers 29 and 30 to disable the Receiver. */ e1000_write_phy_reg(hw, 29, 0x001F); e1000_write_phy_reg(hw, 30, 0x8FFC); e1000_write_phy_reg(hw, 29, 0x001A); e1000_write_phy_reg(hw, 30, 0x8FF0); } static void e1000_phy_reset_clk_and_crs(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u16 phy_reg; /* Because we reset the PHY above, we need to re-force TX_CLK in the * Extended PHY Specific Control Register to 25MHz clock. This * value defaults back to a 2.5MHz clock when the PHY is reset. */ e1000_read_phy_reg(hw, M88E1000_EXT_PHY_SPEC_CTRL, &phy_reg); phy_reg |= M88E1000_EPSCR_TX_CLK_25; e1000_write_phy_reg(hw, M88E1000_EXT_PHY_SPEC_CTRL, phy_reg); /* In addition, because of the s/w reset above, we need to enable * CRS on TX. This must be set for both full and half duplex * operation. */ e1000_read_phy_reg(hw, M88E1000_PHY_SPEC_CTRL, &phy_reg); phy_reg |= M88E1000_PSCR_ASSERT_CRS_ON_TX; e1000_write_phy_reg(hw, M88E1000_PHY_SPEC_CTRL, phy_reg); } static int e1000_nonintegrated_phy_loopback(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 ctrl_reg; u16 phy_reg; /* Setup the Device Control Register for PHY loopback test. */ ctrl_reg = er32(CTRL); ctrl_reg |= (E1000_CTRL_ILOS | /* Invert Loss-Of-Signal */ E1000_CTRL_FRCSPD | /* Set the Force Speed Bit */ E1000_CTRL_FRCDPX | /* Set the Force Duplex Bit */ E1000_CTRL_SPD_1000 | /* Force Speed to 1000 */ E1000_CTRL_FD); /* Force Duplex to FULL */ ew32(CTRL, ctrl_reg); /* Read the PHY Specific Control Register (0x10) */ e1000_read_phy_reg(hw, M88E1000_PHY_SPEC_CTRL, &phy_reg); /* Clear Auto-Crossover bits in PHY Specific Control Register * (bits 6:5). */ phy_reg &= ~M88E1000_PSCR_AUTO_X_MODE; e1000_write_phy_reg(hw, M88E1000_PHY_SPEC_CTRL, phy_reg); /* Perform software reset on the PHY */ e1000_phy_reset(hw); /* Have to setup TX_CLK and TX_CRS after software reset */ e1000_phy_reset_clk_and_crs(adapter); e1000_write_phy_reg(hw, PHY_CTRL, 0x8100); /* Wait for reset to complete. */ udelay(500); /* Have to setup TX_CLK and TX_CRS after software reset */ e1000_phy_reset_clk_and_crs(adapter); /* Write out to PHY registers 29 and 30 to disable the Receiver. */ e1000_phy_disable_receiver(adapter); /* Set the loopback bit in the PHY control register. */ e1000_read_phy_reg(hw, PHY_CTRL, &phy_reg); phy_reg |= MII_CR_LOOPBACK; e1000_write_phy_reg(hw, PHY_CTRL, phy_reg); /* Setup TX_CLK and TX_CRS one more time. */ e1000_phy_reset_clk_and_crs(adapter); /* Check Phy Configuration */ e1000_read_phy_reg(hw, PHY_CTRL, &phy_reg); if (phy_reg != 0x4100) return 9; e1000_read_phy_reg(hw, M88E1000_EXT_PHY_SPEC_CTRL, &phy_reg); if (phy_reg != 0x0070) return 10; e1000_read_phy_reg(hw, 29, &phy_reg); if (phy_reg != 0x001A) return 11; return 0; } static int e1000_integrated_phy_loopback(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 ctrl_reg = 0; u32 stat_reg = 0; hw->autoneg = false; if (hw->phy_type == e1000_phy_m88) { /* Auto-MDI/MDIX Off */ e1000_write_phy_reg(hw, M88E1000_PHY_SPEC_CTRL, 0x0808); /* reset to update Auto-MDI/MDIX */ e1000_write_phy_reg(hw, PHY_CTRL, 0x9140); /* autoneg off */ e1000_write_phy_reg(hw, PHY_CTRL, 0x8140); } ctrl_reg = er32(CTRL); /* force 1000, set loopback */ e1000_write_phy_reg(hw, PHY_CTRL, 0x4140); /* Now set up the MAC to the same speed/duplex as the PHY. */ ctrl_reg = er32(CTRL); ctrl_reg &= ~E1000_CTRL_SPD_SEL; /* Clear the speed sel bits */ ctrl_reg |= (E1000_CTRL_FRCSPD | /* Set the Force Speed Bit */ E1000_CTRL_FRCDPX | /* Set the Force Duplex Bit */ E1000_CTRL_SPD_1000 |/* Force Speed to 1000 */ E1000_CTRL_FD); /* Force Duplex to FULL */ if (hw->media_type == e1000_media_type_copper && hw->phy_type == e1000_phy_m88) ctrl_reg |= E1000_CTRL_ILOS; /* Invert Loss of Signal */ else { /* Set the ILOS bit on the fiber Nic is half * duplex link is detected. */ stat_reg = er32(STATUS); if ((stat_reg & E1000_STATUS_FD) == 0) ctrl_reg |= (E1000_CTRL_ILOS | E1000_CTRL_SLU); } ew32(CTRL, ctrl_reg); /* Disable the receiver on the PHY so when a cable is plugged in, the * PHY does not begin to autoneg when a cable is reconnected to the NIC. */ if (hw->phy_type == e1000_phy_m88) e1000_phy_disable_receiver(adapter); udelay(500); return 0; } static int e1000_set_phy_loopback(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u16 phy_reg = 0; u16 count = 0; switch (hw->mac_type) { case e1000_82543: if (hw->media_type == e1000_media_type_copper) { /* Attempt to setup Loopback mode on Non-integrated PHY. * Some PHY registers get corrupted at random, so * attempt this 10 times. */ while (e1000_nonintegrated_phy_loopback(adapter) && count++ < 10); if (count < 11) return 0; } break; case e1000_82544: case e1000_82540: case e1000_82545: case e1000_82545_rev_3: case e1000_82546: case e1000_82546_rev_3: case e1000_82541: case e1000_82541_rev_2: case e1000_82547: case e1000_82547_rev_2: return e1000_integrated_phy_loopback(adapter); default: /* Default PHY loopback work is to read the MII * control register and assert bit 14 (loopback mode). */ e1000_read_phy_reg(hw, PHY_CTRL, &phy_reg); phy_reg |= MII_CR_LOOPBACK; e1000_write_phy_reg(hw, PHY_CTRL, phy_reg); return 0; } return 8; } static int e1000_setup_loopback_test(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 rctl; if (hw->media_type == e1000_media_type_fiber || hw->media_type == e1000_media_type_internal_serdes) { switch (hw->mac_type) { case e1000_82545: case e1000_82546: case e1000_82545_rev_3: case e1000_82546_rev_3: return e1000_set_phy_loopback(adapter); default: rctl = er32(RCTL); rctl |= E1000_RCTL_LBM_TCVR; ew32(RCTL, rctl); return 0; } } else if (hw->media_type == e1000_media_type_copper) { return e1000_set_phy_loopback(adapter); } return 7; } static void e1000_loopback_cleanup(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 rctl; u16 phy_reg; rctl = er32(RCTL); rctl &= ~(E1000_RCTL_LBM_TCVR | E1000_RCTL_LBM_MAC); ew32(RCTL, rctl); switch (hw->mac_type) { case e1000_82545: case e1000_82546: case e1000_82545_rev_3: case e1000_82546_rev_3: default: hw->autoneg = true; e1000_read_phy_reg(hw, PHY_CTRL, &phy_reg); if (phy_reg & MII_CR_LOOPBACK) { phy_reg &= ~MII_CR_LOOPBACK; e1000_write_phy_reg(hw, PHY_CTRL, phy_reg); e1000_phy_reset(hw); } break; } } static void e1000_create_lbtest_frame(struct sk_buff *skb, unsigned int frame_size) { memset(skb->data, 0xFF, frame_size); frame_size &= ~1; memset(&skb->data[frame_size / 2], 0xAA, frame_size / 2 - 1); skb->data[frame_size / 2 + 10] = 0xBE; skb->data[frame_size / 2 + 12] = 0xAF; } static int e1000_check_lbtest_frame(const unsigned char *data, unsigned int frame_size) { frame_size &= ~1; if (*(data + 3) == 0xFF) { if ((*(data + frame_size / 2 + 10) == 0xBE) && (*(data + frame_size / 2 + 12) == 0xAF)) { return 0; } } return 13; } static int e1000_run_loopback_test(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; struct e1000_tx_ring *txdr = &adapter->test_tx_ring; struct e1000_rx_ring *rxdr = &adapter->test_rx_ring; struct pci_dev *pdev = adapter->pdev; int i, j, k, l, lc, good_cnt, ret_val = 0; unsigned long time; ew32(RDT, rxdr->count - 1); /* Calculate the loop count based on the largest descriptor ring * The idea is to wrap the largest ring a number of times using 64 * send/receive pairs during each loop */ if (rxdr->count <= txdr->count) lc = ((txdr->count / 64) * 2) + 1; else lc = ((rxdr->count / 64) * 2) + 1; k = l = 0; for (j = 0; j <= lc; j++) { /* loop count loop */ for (i = 0; i < 64; i++) { /* send the packets */ e1000_create_lbtest_frame(txdr->buffer_info[i].skb, 1024); dma_sync_single_for_device(&pdev->dev, txdr->buffer_info[k].dma, txdr->buffer_info[k].length, DMA_TO_DEVICE); if (unlikely(++k == txdr->count)) k = 0; } ew32(TDT, k); E1000_WRITE_FLUSH(); msleep(200); time = jiffies; /* set the start time for the receive */ good_cnt = 0; do { /* receive the sent packets */ dma_sync_single_for_cpu(&pdev->dev, rxdr->buffer_info[l].dma, E1000_RXBUFFER_2048, DMA_FROM_DEVICE); ret_val = e1000_check_lbtest_frame( rxdr->buffer_info[l].rxbuf.data + NET_SKB_PAD + NET_IP_ALIGN, 1024); if (!ret_val) good_cnt++; if (unlikely(++l == rxdr->count)) l = 0; /* time + 20 msecs (200 msecs on 2.4) is more than * enough time to complete the receives, if it's * exceeded, break and error off */ } while (good_cnt < 64 && time_after(time + 20, jiffies)); if (good_cnt != 64) { ret_val = 13; /* ret_val is the same as mis-compare */ break; } if (time_after_eq(jiffies, time + 2)) { ret_val = 14; /* error code for time out error */ break; } } /* end loop count loop */ return ret_val; } static int e1000_loopback_test(struct e1000_adapter *adapter, u64 *data) { *data = e1000_setup_desc_rings(adapter); if (*data) goto out; *data = e1000_setup_loopback_test(adapter); if (*data) goto err_loopback; *data = e1000_run_loopback_test(adapter); e1000_loopback_cleanup(adapter); err_loopback: e1000_free_desc_rings(adapter); out: return *data; } static int e1000_link_test(struct e1000_adapter *adapter, u64 *data) { struct e1000_hw *hw = &adapter->hw; *data = 0; if (hw->media_type == e1000_media_type_internal_serdes) { int i = 0; hw->serdes_has_link = false; /* On some blade server designs, link establishment * could take as long as 2-3 minutes */ do { e1000_check_for_link(hw); if (hw->serdes_has_link) return *data; msleep(20); } while (i++ < 3750); *data = 1; } else { e1000_check_for_link(hw); if (hw->autoneg) /* if auto_neg is set wait for it */ msleep(4000); if (!(er32(STATUS) & E1000_STATUS_LU)) *data = 1; } return *data; } static int e1000_get_sset_count(struct net_device *netdev, int sset) { switch (sset) { case ETH_SS_TEST: return E1000_TEST_LEN; case ETH_SS_STATS: return E1000_STATS_LEN; default: return -EOPNOTSUPP; } } static void e1000_diag_test(struct net_device *netdev, struct ethtool_test *eth_test, u64 *data) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; bool if_running = netif_running(netdev); set_bit(__E1000_TESTING, &adapter->flags); if (eth_test->flags == ETH_TEST_FL_OFFLINE) { /* Offline tests */ /* save speed, duplex, autoneg settings */ u16 autoneg_advertised = hw->autoneg_advertised; u8 forced_speed_duplex = hw->forced_speed_duplex; u8 autoneg = hw->autoneg; e_info(hw, "offline testing starting\n"); /* Link test performed before hardware reset so autoneg doesn't * interfere with test result */ if (e1000_link_test(adapter, &data[4])) eth_test->flags |= ETH_TEST_FL_FAILED; if (if_running) /* indicate we're in test mode */ e1000_close(netdev); else e1000_reset(adapter); if (e1000_reg_test(adapter, &data[0])) eth_test->flags |= ETH_TEST_FL_FAILED; e1000_reset(adapter); if (e1000_eeprom_test(adapter, &data[1])) eth_test->flags |= ETH_TEST_FL_FAILED; e1000_reset(adapter); if (e1000_intr_test(adapter, &data[2])) eth_test->flags |= ETH_TEST_FL_FAILED; e1000_reset(adapter); /* make sure the phy is powered up */ e1000_power_up_phy(adapter); if (e1000_loopback_test(adapter, &data[3])) eth_test->flags |= ETH_TEST_FL_FAILED; /* restore speed, duplex, autoneg settings */ hw->autoneg_advertised = autoneg_advertised; hw->forced_speed_duplex = forced_speed_duplex; hw->autoneg = autoneg; e1000_reset(adapter); clear_bit(__E1000_TESTING, &adapter->flags); if (if_running) e1000_open(netdev); } else { e_info(hw, "online testing starting\n"); /* Online tests */ if (e1000_link_test(adapter, &data[4])) eth_test->flags |= ETH_TEST_FL_FAILED; /* Online tests aren't run; pass by default */ data[0] = 0; data[1] = 0; data[2] = 0; data[3] = 0; clear_bit(__E1000_TESTING, &adapter->flags); } msleep_interruptible(4 * 1000); } static int e1000_wol_exclusion(struct e1000_adapter *adapter, struct ethtool_wolinfo *wol) { struct e1000_hw *hw = &adapter->hw; int retval = 1; /* fail by default */ switch (hw->device_id) { case E1000_DEV_ID_82542: case E1000_DEV_ID_82543GC_FIBER: case E1000_DEV_ID_82543GC_COPPER: case E1000_DEV_ID_82544EI_FIBER: case E1000_DEV_ID_82546EB_QUAD_COPPER: case E1000_DEV_ID_82545EM_FIBER: case E1000_DEV_ID_82545EM_COPPER: case E1000_DEV_ID_82546GB_QUAD_COPPER: case E1000_DEV_ID_82546GB_PCIE: /* these don't support WoL at all */ wol->supported = 0; break; case E1000_DEV_ID_82546EB_FIBER: case E1000_DEV_ID_82546GB_FIBER: /* Wake events not supported on port B */ if (er32(STATUS) & E1000_STATUS_FUNC_1) { wol->supported = 0; break; } /* return success for non excluded adapter ports */ retval = 0; break; case E1000_DEV_ID_82546GB_QUAD_COPPER_KSP3: /* quad port adapters only support WoL on port A */ if (!adapter->quad_port_a) { wol->supported = 0; break; } /* return success for non excluded adapter ports */ retval = 0; break; default: /* dual port cards only support WoL on port A from now on * unless it was enabled in the eeprom for port B * so exclude FUNC_1 ports from having WoL enabled */ if (er32(STATUS) & E1000_STATUS_FUNC_1 && !adapter->eeprom_wol) { wol->supported = 0; break; } retval = 0; } return retval; } static void e1000_get_wol(struct net_device *netdev, struct ethtool_wolinfo *wol) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; wol->supported = WAKE_UCAST | WAKE_MCAST | WAKE_BCAST | WAKE_MAGIC; wol->wolopts = 0; /* this function will set ->supported = 0 and return 1 if wol is not * supported by this hardware */ if (e1000_wol_exclusion(adapter, wol) || !device_can_wakeup(&adapter->pdev->dev)) return; /* apply any specific unsupported masks here */ switch (hw->device_id) { case E1000_DEV_ID_82546GB_QUAD_COPPER_KSP3: /* KSP3 does not support UCAST wake-ups */ wol->supported &= ~WAKE_UCAST; if (adapter->wol & E1000_WUFC_EX) e_err(drv, "Interface does not support directed " "(unicast) frame wake-up packets\n"); break; default: break; } if (adapter->wol & E1000_WUFC_EX) wol->wolopts |= WAKE_UCAST; if (adapter->wol & E1000_WUFC_MC) wol->wolopts |= WAKE_MCAST; if (adapter->wol & E1000_WUFC_BC) wol->wolopts |= WAKE_BCAST; if (adapter->wol & E1000_WUFC_MAG) wol->wolopts |= WAKE_MAGIC; } static int e1000_set_wol(struct net_device *netdev, struct ethtool_wolinfo *wol) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; if (wol->wolopts & (WAKE_PHY | WAKE_ARP | WAKE_MAGICSECURE)) return -EOPNOTSUPP; if (e1000_wol_exclusion(adapter, wol) || !device_can_wakeup(&adapter->pdev->dev)) return wol->wolopts ? -EOPNOTSUPP : 0; switch (hw->device_id) { case E1000_DEV_ID_82546GB_QUAD_COPPER_KSP3: if (wol->wolopts & WAKE_UCAST) { e_err(drv, "Interface does not support directed " "(unicast) frame wake-up packets\n"); return -EOPNOTSUPP; } break; default: break; } /* these settings will always override what we currently have */ adapter->wol = 0; if (wol->wolopts & WAKE_UCAST) adapter->wol |= E1000_WUFC_EX; if (wol->wolopts & WAKE_MCAST) adapter->wol |= E1000_WUFC_MC; if (wol->wolopts & WAKE_BCAST) adapter->wol |= E1000_WUFC_BC; if (wol->wolopts & WAKE_MAGIC) adapter->wol |= E1000_WUFC_MAG; device_set_wakeup_enable(&adapter->pdev->dev, adapter->wol); return 0; } static int e1000_set_phys_id(struct net_device *netdev, enum ethtool_phys_id_state state) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; switch (state) { case ETHTOOL_ID_ACTIVE: e1000_setup_led(hw); return 2; case ETHTOOL_ID_ON: e1000_led_on(hw); break; case ETHTOOL_ID_OFF: e1000_led_off(hw); break; case ETHTOOL_ID_INACTIVE: e1000_cleanup_led(hw); } return 0; } static int e1000_get_coalesce(struct net_device *netdev, struct ethtool_coalesce *ec, struct kernel_ethtool_coalesce *kernel_coal, struct netlink_ext_ack *extack) { struct e1000_adapter *adapter = netdev_priv(netdev); if (adapter->hw.mac_type < e1000_82545) return -EOPNOTSUPP; if (adapter->itr_setting <= 4) ec->rx_coalesce_usecs = adapter->itr_setting; else ec->rx_coalesce_usecs = 1000000 / adapter->itr_setting; return 0; } static int e1000_set_coalesce(struct net_device *netdev, struct ethtool_coalesce *ec, struct kernel_ethtool_coalesce *kernel_coal, struct netlink_ext_ack *extack) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; if (hw->mac_type < e1000_82545) return -EOPNOTSUPP; if ((ec->rx_coalesce_usecs > E1000_MAX_ITR_USECS) || ((ec->rx_coalesce_usecs > 4) && (ec->rx_coalesce_usecs < E1000_MIN_ITR_USECS)) || (ec->rx_coalesce_usecs == 2)) return -EINVAL; if (ec->rx_coalesce_usecs == 4) { adapter->itr = adapter->itr_setting = 4; } else if (ec->rx_coalesce_usecs <= 3) { adapter->itr = 20000; adapter->itr_setting = ec->rx_coalesce_usecs; } else { adapter->itr = (1000000 / ec->rx_coalesce_usecs); adapter->itr_setting = adapter->itr & ~3; } if (adapter->itr_setting != 0) ew32(ITR, 1000000000 / (adapter->itr * 256)); else ew32(ITR, 0); return 0; } static int e1000_nway_reset(struct net_device *netdev) { struct e1000_adapter *adapter = netdev_priv(netdev); if (netif_running(netdev)) e1000_reinit_locked(adapter); return 0; } static void e1000_get_ethtool_stats(struct net_device *netdev, struct ethtool_stats *stats, u64 *data) { struct e1000_adapter *adapter = netdev_priv(netdev); int i; const struct e1000_stats *stat = e1000_gstrings_stats; e1000_update_stats(adapter); for (i = 0; i < E1000_GLOBAL_STATS_LEN; i++, stat++) { char *p; switch (stat->type) { case NETDEV_STATS: p = (char *)netdev + stat->stat_offset; break; case E1000_STATS: p = (char *)adapter + stat->stat_offset; break; default: netdev_WARN_ONCE(netdev, "Invalid E1000 stat type: %u index %d\n", stat->type, i); continue; } if (stat->sizeof_stat == sizeof(u64)) data[i] = *(u64 *)p; else data[i] = *(u32 *)p; } /* BUG_ON(i != E1000_STATS_LEN); */ } static void e1000_get_strings(struct net_device *netdev, u32 stringset, u8 *data) { u8 *p = data; int i; switch (stringset) { case ETH_SS_TEST: memcpy(data, e1000_gstrings_test, sizeof(e1000_gstrings_test)); break; case ETH_SS_STATS: for (i = 0; i < E1000_GLOBAL_STATS_LEN; i++) { memcpy(p, e1000_gstrings_stats[i].stat_string, ETH_GSTRING_LEN); p += ETH_GSTRING_LEN; } /* BUG_ON(p - data != E1000_STATS_LEN * ETH_GSTRING_LEN); */ break; } } static const struct ethtool_ops e1000_ethtool_ops = { .supported_coalesce_params = ETHTOOL_COALESCE_RX_USECS, .get_drvinfo = e1000_get_drvinfo, .get_regs_len = e1000_get_regs_len, .get_regs = e1000_get_regs, .get_wol = e1000_get_wol, .set_wol = e1000_set_wol, .get_msglevel = e1000_get_msglevel, .set_msglevel = e1000_set_msglevel, .nway_reset = e1000_nway_reset, .get_link = e1000_get_link, .get_eeprom_len = e1000_get_eeprom_len, .get_eeprom = e1000_get_eeprom, .set_eeprom = e1000_set_eeprom, .get_ringparam = e1000_get_ringparam, .set_ringparam = e1000_set_ringparam, .get_pauseparam = e1000_get_pauseparam, .set_pauseparam = e1000_set_pauseparam, .self_test = e1000_diag_test, .get_strings = e1000_get_strings, .set_phys_id = e1000_set_phys_id, .get_ethtool_stats = e1000_get_ethtool_stats, .get_sset_count = e1000_get_sset_count, .get_coalesce = e1000_get_coalesce, .set_coalesce = e1000_set_coalesce, .get_ts_info = ethtool_op_get_ts_info, .get_link_ksettings = e1000_get_link_ksettings, .set_link_ksettings = e1000_set_link_ksettings, }; void e1000_set_ethtool_ops(struct net_device *netdev) { netdev->ethtool_ops = &e1000_ethtool_ops; }
linux-master
drivers/net/ethernet/intel/e1000/e1000_ethtool.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 1999 - 2006 Intel Corporation. */ #include "e1000.h" #include <net/ip6_checksum.h> #include <linux/io.h> #include <linux/prefetch.h> #include <linux/bitops.h> #include <linux/if_vlan.h> char e1000_driver_name[] = "e1000"; static char e1000_driver_string[] = "Intel(R) PRO/1000 Network Driver"; static const char e1000_copyright[] = "Copyright (c) 1999-2006 Intel Corporation."; /* e1000_pci_tbl - PCI Device ID Table * * Last entry must be all 0s * * Macro expands to... * {PCI_DEVICE(PCI_VENDOR_ID_INTEL, device_id)} */ static const struct pci_device_id e1000_pci_tbl[] = { INTEL_E1000_ETHERNET_DEVICE(0x1000), INTEL_E1000_ETHERNET_DEVICE(0x1001), INTEL_E1000_ETHERNET_DEVICE(0x1004), INTEL_E1000_ETHERNET_DEVICE(0x1008), INTEL_E1000_ETHERNET_DEVICE(0x1009), INTEL_E1000_ETHERNET_DEVICE(0x100C), INTEL_E1000_ETHERNET_DEVICE(0x100D), INTEL_E1000_ETHERNET_DEVICE(0x100E), INTEL_E1000_ETHERNET_DEVICE(0x100F), INTEL_E1000_ETHERNET_DEVICE(0x1010), INTEL_E1000_ETHERNET_DEVICE(0x1011), INTEL_E1000_ETHERNET_DEVICE(0x1012), INTEL_E1000_ETHERNET_DEVICE(0x1013), INTEL_E1000_ETHERNET_DEVICE(0x1014), INTEL_E1000_ETHERNET_DEVICE(0x1015), INTEL_E1000_ETHERNET_DEVICE(0x1016), INTEL_E1000_ETHERNET_DEVICE(0x1017), INTEL_E1000_ETHERNET_DEVICE(0x1018), INTEL_E1000_ETHERNET_DEVICE(0x1019), INTEL_E1000_ETHERNET_DEVICE(0x101A), INTEL_E1000_ETHERNET_DEVICE(0x101D), INTEL_E1000_ETHERNET_DEVICE(0x101E), INTEL_E1000_ETHERNET_DEVICE(0x1026), INTEL_E1000_ETHERNET_DEVICE(0x1027), INTEL_E1000_ETHERNET_DEVICE(0x1028), INTEL_E1000_ETHERNET_DEVICE(0x1075), INTEL_E1000_ETHERNET_DEVICE(0x1076), INTEL_E1000_ETHERNET_DEVICE(0x1077), INTEL_E1000_ETHERNET_DEVICE(0x1078), INTEL_E1000_ETHERNET_DEVICE(0x1079), INTEL_E1000_ETHERNET_DEVICE(0x107A), INTEL_E1000_ETHERNET_DEVICE(0x107B), INTEL_E1000_ETHERNET_DEVICE(0x107C), INTEL_E1000_ETHERNET_DEVICE(0x108A), INTEL_E1000_ETHERNET_DEVICE(0x1099), INTEL_E1000_ETHERNET_DEVICE(0x10B5), INTEL_E1000_ETHERNET_DEVICE(0x2E6E), /* required last entry */ {0,} }; MODULE_DEVICE_TABLE(pci, e1000_pci_tbl); int e1000_up(struct e1000_adapter *adapter); void e1000_down(struct e1000_adapter *adapter); void e1000_reinit_locked(struct e1000_adapter *adapter); void e1000_reset(struct e1000_adapter *adapter); int e1000_setup_all_tx_resources(struct e1000_adapter *adapter); int e1000_setup_all_rx_resources(struct e1000_adapter *adapter); void e1000_free_all_tx_resources(struct e1000_adapter *adapter); void e1000_free_all_rx_resources(struct e1000_adapter *adapter); static int e1000_setup_tx_resources(struct e1000_adapter *adapter, struct e1000_tx_ring *txdr); static int e1000_setup_rx_resources(struct e1000_adapter *adapter, struct e1000_rx_ring *rxdr); static void e1000_free_tx_resources(struct e1000_adapter *adapter, struct e1000_tx_ring *tx_ring); static void e1000_free_rx_resources(struct e1000_adapter *adapter, struct e1000_rx_ring *rx_ring); void e1000_update_stats(struct e1000_adapter *adapter); static int e1000_init_module(void); static void e1000_exit_module(void); static int e1000_probe(struct pci_dev *pdev, const struct pci_device_id *ent); static void e1000_remove(struct pci_dev *pdev); static int e1000_alloc_queues(struct e1000_adapter *adapter); static int e1000_sw_init(struct e1000_adapter *adapter); int e1000_open(struct net_device *netdev); int e1000_close(struct net_device *netdev); static void e1000_configure_tx(struct e1000_adapter *adapter); static void e1000_configure_rx(struct e1000_adapter *adapter); static void e1000_setup_rctl(struct e1000_adapter *adapter); static void e1000_clean_all_tx_rings(struct e1000_adapter *adapter); static void e1000_clean_all_rx_rings(struct e1000_adapter *adapter); static void e1000_clean_tx_ring(struct e1000_adapter *adapter, struct e1000_tx_ring *tx_ring); static void e1000_clean_rx_ring(struct e1000_adapter *adapter, struct e1000_rx_ring *rx_ring); static void e1000_set_rx_mode(struct net_device *netdev); static void e1000_update_phy_info_task(struct work_struct *work); static void e1000_watchdog(struct work_struct *work); static void e1000_82547_tx_fifo_stall_task(struct work_struct *work); static netdev_tx_t e1000_xmit_frame(struct sk_buff *skb, struct net_device *netdev); static int e1000_change_mtu(struct net_device *netdev, int new_mtu); static int e1000_set_mac(struct net_device *netdev, void *p); static irqreturn_t e1000_intr(int irq, void *data); static bool e1000_clean_tx_irq(struct e1000_adapter *adapter, struct e1000_tx_ring *tx_ring); static int e1000_clean(struct napi_struct *napi, int budget); static bool e1000_clean_rx_irq(struct e1000_adapter *adapter, struct e1000_rx_ring *rx_ring, int *work_done, int work_to_do); static bool e1000_clean_jumbo_rx_irq(struct e1000_adapter *adapter, struct e1000_rx_ring *rx_ring, int *work_done, int work_to_do); static void e1000_alloc_dummy_rx_buffers(struct e1000_adapter *adapter, struct e1000_rx_ring *rx_ring, int cleaned_count) { } static void e1000_alloc_rx_buffers(struct e1000_adapter *adapter, struct e1000_rx_ring *rx_ring, int cleaned_count); static void e1000_alloc_jumbo_rx_buffers(struct e1000_adapter *adapter, struct e1000_rx_ring *rx_ring, int cleaned_count); static int e1000_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd); static int e1000_mii_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd); static void e1000_enter_82542_rst(struct e1000_adapter *adapter); static void e1000_leave_82542_rst(struct e1000_adapter *adapter); static void e1000_tx_timeout(struct net_device *dev, unsigned int txqueue); static void e1000_reset_task(struct work_struct *work); static void e1000_smartspeed(struct e1000_adapter *adapter); static int e1000_82547_fifo_workaround(struct e1000_adapter *adapter, struct sk_buff *skb); static bool e1000_vlan_used(struct e1000_adapter *adapter); static void e1000_vlan_mode(struct net_device *netdev, netdev_features_t features); static void e1000_vlan_filter_on_off(struct e1000_adapter *adapter, bool filter_on); static int e1000_vlan_rx_add_vid(struct net_device *netdev, __be16 proto, u16 vid); static int e1000_vlan_rx_kill_vid(struct net_device *netdev, __be16 proto, u16 vid); static void e1000_restore_vlan(struct e1000_adapter *adapter); static int __maybe_unused e1000_suspend(struct device *dev); static int __maybe_unused e1000_resume(struct device *dev); static void e1000_shutdown(struct pci_dev *pdev); #ifdef CONFIG_NET_POLL_CONTROLLER /* for netdump / net console */ static void e1000_netpoll (struct net_device *netdev); #endif #define COPYBREAK_DEFAULT 256 static unsigned int copybreak __read_mostly = COPYBREAK_DEFAULT; module_param(copybreak, uint, 0644); MODULE_PARM_DESC(copybreak, "Maximum size of packet that is copied to a new buffer on receive"); static pci_ers_result_t e1000_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state); static pci_ers_result_t e1000_io_slot_reset(struct pci_dev *pdev); static void e1000_io_resume(struct pci_dev *pdev); static const struct pci_error_handlers e1000_err_handler = { .error_detected = e1000_io_error_detected, .slot_reset = e1000_io_slot_reset, .resume = e1000_io_resume, }; static SIMPLE_DEV_PM_OPS(e1000_pm_ops, e1000_suspend, e1000_resume); static struct pci_driver e1000_driver = { .name = e1000_driver_name, .id_table = e1000_pci_tbl, .probe = e1000_probe, .remove = e1000_remove, .driver = { .pm = &e1000_pm_ops, }, .shutdown = e1000_shutdown, .err_handler = &e1000_err_handler }; MODULE_AUTHOR("Intel Corporation, <[email protected]>"); MODULE_DESCRIPTION("Intel(R) PRO/1000 Network Driver"); MODULE_LICENSE("GPL v2"); #define DEFAULT_MSG_ENABLE (NETIF_MSG_DRV|NETIF_MSG_PROBE|NETIF_MSG_LINK) static int debug = -1; module_param(debug, int, 0); MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all)"); /** * e1000_get_hw_dev - helper function for getting netdev * @hw: pointer to HW struct * * return device used by hardware layer to print debugging information * **/ struct net_device *e1000_get_hw_dev(struct e1000_hw *hw) { struct e1000_adapter *adapter = hw->back; return adapter->netdev; } /** * e1000_init_module - Driver Registration Routine * * e1000_init_module is the first routine called when the driver is * loaded. All it does is register with the PCI subsystem. **/ static int __init e1000_init_module(void) { int ret; pr_info("%s\n", e1000_driver_string); pr_info("%s\n", e1000_copyright); ret = pci_register_driver(&e1000_driver); if (copybreak != COPYBREAK_DEFAULT) { if (copybreak == 0) pr_info("copybreak disabled\n"); else pr_info("copybreak enabled for " "packets <= %u bytes\n", copybreak); } return ret; } module_init(e1000_init_module); /** * e1000_exit_module - Driver Exit Cleanup Routine * * e1000_exit_module is called just before the driver is removed * from memory. **/ static void __exit e1000_exit_module(void) { pci_unregister_driver(&e1000_driver); } module_exit(e1000_exit_module); static int e1000_request_irq(struct e1000_adapter *adapter) { struct net_device *netdev = adapter->netdev; irq_handler_t handler = e1000_intr; int irq_flags = IRQF_SHARED; int err; err = request_irq(adapter->pdev->irq, handler, irq_flags, netdev->name, netdev); if (err) { e_err(probe, "Unable to allocate interrupt Error: %d\n", err); } return err; } static void e1000_free_irq(struct e1000_adapter *adapter) { struct net_device *netdev = adapter->netdev; free_irq(adapter->pdev->irq, netdev); } /** * e1000_irq_disable - Mask off interrupt generation on the NIC * @adapter: board private structure **/ static void e1000_irq_disable(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; ew32(IMC, ~0); E1000_WRITE_FLUSH(); synchronize_irq(adapter->pdev->irq); } /** * e1000_irq_enable - Enable default interrupt generation settings * @adapter: board private structure **/ static void e1000_irq_enable(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; ew32(IMS, IMS_ENABLE_MASK); E1000_WRITE_FLUSH(); } static void e1000_update_mng_vlan(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; struct net_device *netdev = adapter->netdev; u16 vid = hw->mng_cookie.vlan_id; u16 old_vid = adapter->mng_vlan_id; if (!e1000_vlan_used(adapter)) return; if (!test_bit(vid, adapter->active_vlans)) { if (hw->mng_cookie.status & E1000_MNG_DHCP_COOKIE_STATUS_VLAN_SUPPORT) { e1000_vlan_rx_add_vid(netdev, htons(ETH_P_8021Q), vid); adapter->mng_vlan_id = vid; } else { adapter->mng_vlan_id = E1000_MNG_VLAN_NONE; } if ((old_vid != (u16)E1000_MNG_VLAN_NONE) && (vid != old_vid) && !test_bit(old_vid, adapter->active_vlans)) e1000_vlan_rx_kill_vid(netdev, htons(ETH_P_8021Q), old_vid); } else { adapter->mng_vlan_id = vid; } } static void e1000_init_manageability(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; if (adapter->en_mng_pt) { u32 manc = er32(MANC); /* disable hardware interception of ARP */ manc &= ~(E1000_MANC_ARP_EN); ew32(MANC, manc); } } static void e1000_release_manageability(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; if (adapter->en_mng_pt) { u32 manc = er32(MANC); /* re-enable hardware interception of ARP */ manc |= E1000_MANC_ARP_EN; ew32(MANC, manc); } } /** * e1000_configure - configure the hardware for RX and TX * @adapter: private board structure **/ static void e1000_configure(struct e1000_adapter *adapter) { struct net_device *netdev = adapter->netdev; int i; e1000_set_rx_mode(netdev); e1000_restore_vlan(adapter); e1000_init_manageability(adapter); e1000_configure_tx(adapter); e1000_setup_rctl(adapter); e1000_configure_rx(adapter); /* call E1000_DESC_UNUSED which always leaves * at least 1 descriptor unused to make sure * next_to_use != next_to_clean */ for (i = 0; i < adapter->num_rx_queues; i++) { struct e1000_rx_ring *ring = &adapter->rx_ring[i]; adapter->alloc_rx_buf(adapter, ring, E1000_DESC_UNUSED(ring)); } } int e1000_up(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; /* hardware has been reset, we need to reload some things */ e1000_configure(adapter); clear_bit(__E1000_DOWN, &adapter->flags); napi_enable(&adapter->napi); e1000_irq_enable(adapter); netif_wake_queue(adapter->netdev); /* fire a link change interrupt to start the watchdog */ ew32(ICS, E1000_ICS_LSC); return 0; } /** * e1000_power_up_phy - restore link in case the phy was powered down * @adapter: address of board private structure * * The phy may be powered down to save power and turn off link when the * driver is unloaded and wake on lan is not enabled (among others) * *** this routine MUST be followed by a call to e1000_reset *** **/ void e1000_power_up_phy(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u16 mii_reg = 0; /* Just clear the power down bit to wake the phy back up */ if (hw->media_type == e1000_media_type_copper) { /* according to the manual, the phy will retain its * settings across a power-down/up cycle */ e1000_read_phy_reg(hw, PHY_CTRL, &mii_reg); mii_reg &= ~MII_CR_POWER_DOWN; e1000_write_phy_reg(hw, PHY_CTRL, mii_reg); } } static void e1000_power_down_phy(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; /* Power down the PHY so no link is implied when interface is down * * The PHY cannot be powered down if any of the following is true * * (a) WoL is enabled * (b) AMT is active * (c) SoL/IDER session is active */ if (!adapter->wol && hw->mac_type >= e1000_82540 && hw->media_type == e1000_media_type_copper) { u16 mii_reg = 0; switch (hw->mac_type) { case e1000_82540: case e1000_82545: case e1000_82545_rev_3: case e1000_82546: case e1000_ce4100: case e1000_82546_rev_3: case e1000_82541: case e1000_82541_rev_2: case e1000_82547: case e1000_82547_rev_2: if (er32(MANC) & E1000_MANC_SMBUS_EN) goto out; break; default: goto out; } e1000_read_phy_reg(hw, PHY_CTRL, &mii_reg); mii_reg |= MII_CR_POWER_DOWN; e1000_write_phy_reg(hw, PHY_CTRL, mii_reg); msleep(1); } out: return; } static void e1000_down_and_stop(struct e1000_adapter *adapter) { set_bit(__E1000_DOWN, &adapter->flags); cancel_delayed_work_sync(&adapter->watchdog_task); /* * Since the watchdog task can reschedule other tasks, we should cancel * it first, otherwise we can run into the situation when a work is * still running after the adapter has been turned down. */ cancel_delayed_work_sync(&adapter->phy_info_task); cancel_delayed_work_sync(&adapter->fifo_stall_task); /* Only kill reset task if adapter is not resetting */ if (!test_bit(__E1000_RESETTING, &adapter->flags)) cancel_work_sync(&adapter->reset_task); } void e1000_down(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; struct net_device *netdev = adapter->netdev; u32 rctl, tctl; /* disable receives in the hardware */ rctl = er32(RCTL); ew32(RCTL, rctl & ~E1000_RCTL_EN); /* flush and sleep below */ netif_tx_disable(netdev); /* disable transmits in the hardware */ tctl = er32(TCTL); tctl &= ~E1000_TCTL_EN; ew32(TCTL, tctl); /* flush both disables and wait for them to finish */ E1000_WRITE_FLUSH(); msleep(10); /* Set the carrier off after transmits have been disabled in the * hardware, to avoid race conditions with e1000_watchdog() (which * may be running concurrently to us, checking for the carrier * bit to decide whether it should enable transmits again). Such * a race condition would result into transmission being disabled * in the hardware until the next IFF_DOWN+IFF_UP cycle. */ netif_carrier_off(netdev); napi_disable(&adapter->napi); e1000_irq_disable(adapter); /* Setting DOWN must be after irq_disable to prevent * a screaming interrupt. Setting DOWN also prevents * tasks from rescheduling. */ e1000_down_and_stop(adapter); adapter->link_speed = 0; adapter->link_duplex = 0; e1000_reset(adapter); e1000_clean_all_tx_rings(adapter); e1000_clean_all_rx_rings(adapter); } void e1000_reinit_locked(struct e1000_adapter *adapter) { while (test_and_set_bit(__E1000_RESETTING, &adapter->flags)) msleep(1); /* only run the task if not already down */ if (!test_bit(__E1000_DOWN, &adapter->flags)) { e1000_down(adapter); e1000_up(adapter); } clear_bit(__E1000_RESETTING, &adapter->flags); } void e1000_reset(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 pba = 0, tx_space, min_tx_space, min_rx_space; bool legacy_pba_adjust = false; u16 hwm; /* Repartition Pba for greater than 9k mtu * To take effect CTRL.RST is required. */ switch (hw->mac_type) { case e1000_82542_rev2_0: case e1000_82542_rev2_1: case e1000_82543: case e1000_82544: case e1000_82540: case e1000_82541: case e1000_82541_rev_2: legacy_pba_adjust = true; pba = E1000_PBA_48K; break; case e1000_82545: case e1000_82545_rev_3: case e1000_82546: case e1000_ce4100: case e1000_82546_rev_3: pba = E1000_PBA_48K; break; case e1000_82547: case e1000_82547_rev_2: legacy_pba_adjust = true; pba = E1000_PBA_30K; break; case e1000_undefined: case e1000_num_macs: break; } if (legacy_pba_adjust) { if (hw->max_frame_size > E1000_RXBUFFER_8192) pba -= 8; /* allocate more FIFO for Tx */ if (hw->mac_type == e1000_82547) { adapter->tx_fifo_head = 0; adapter->tx_head_addr = pba << E1000_TX_HEAD_ADDR_SHIFT; adapter->tx_fifo_size = (E1000_PBA_40K - pba) << E1000_PBA_BYTES_SHIFT; atomic_set(&adapter->tx_fifo_stall, 0); } } else if (hw->max_frame_size > ETH_FRAME_LEN + ETH_FCS_LEN) { /* adjust PBA for jumbo frames */ ew32(PBA, pba); /* To maintain wire speed transmits, the Tx FIFO should be * large enough to accommodate two full transmit packets, * rounded up to the next 1KB and expressed in KB. Likewise, * the Rx FIFO should be large enough to accommodate at least * one full receive packet and is similarly rounded up and * expressed in KB. */ pba = er32(PBA); /* upper 16 bits has Tx packet buffer allocation size in KB */ tx_space = pba >> 16; /* lower 16 bits has Rx packet buffer allocation size in KB */ pba &= 0xffff; /* the Tx fifo also stores 16 bytes of information about the Tx * but don't include ethernet FCS because hardware appends it */ min_tx_space = (hw->max_frame_size + sizeof(struct e1000_tx_desc) - ETH_FCS_LEN) * 2; min_tx_space = ALIGN(min_tx_space, 1024); min_tx_space >>= 10; /* software strips receive CRC, so leave room for it */ min_rx_space = hw->max_frame_size; min_rx_space = ALIGN(min_rx_space, 1024); min_rx_space >>= 10; /* If current Tx allocation is less than the min Tx FIFO size, * and the min Tx FIFO size is less than the current Rx FIFO * allocation, take space away from current Rx allocation */ if (tx_space < min_tx_space && ((min_tx_space - tx_space) < pba)) { pba = pba - (min_tx_space - tx_space); /* PCI/PCIx hardware has PBA alignment constraints */ switch (hw->mac_type) { case e1000_82545 ... e1000_82546_rev_3: pba &= ~(E1000_PBA_8K - 1); break; default: break; } /* if short on Rx space, Rx wins and must trump Tx * adjustment or use Early Receive if available */ if (pba < min_rx_space) pba = min_rx_space; } } ew32(PBA, pba); /* flow control settings: * The high water mark must be low enough to fit one full frame * (or the size used for early receive) above it in the Rx FIFO. * Set it to the lower of: * - 90% of the Rx FIFO size, and * - the full Rx FIFO size minus the early receive size (for parts * with ERT support assuming ERT set to E1000_ERT_2048), or * - the full Rx FIFO size minus one full frame */ hwm = min(((pba << 10) * 9 / 10), ((pba << 10) - hw->max_frame_size)); hw->fc_high_water = hwm & 0xFFF8; /* 8-byte granularity */ hw->fc_low_water = hw->fc_high_water - 8; hw->fc_pause_time = E1000_FC_PAUSE_TIME; hw->fc_send_xon = 1; hw->fc = hw->original_fc; /* Allow time for pending master requests to run */ e1000_reset_hw(hw); if (hw->mac_type >= e1000_82544) ew32(WUC, 0); if (e1000_init_hw(hw)) e_dev_err("Hardware Error\n"); e1000_update_mng_vlan(adapter); /* if (adapter->hwflags & HWFLAGS_PHY_PWR_BIT) { */ if (hw->mac_type >= e1000_82544 && hw->autoneg == 1 && hw->autoneg_advertised == ADVERTISE_1000_FULL) { u32 ctrl = er32(CTRL); /* clear phy power management bit if we are in gig only mode, * which if enabled will attempt negotiation to 100Mb, which * can cause a loss of link at power off or driver unload */ ctrl &= ~E1000_CTRL_SWDPIN3; ew32(CTRL, ctrl); } /* Enable h/w to recognize an 802.1Q VLAN Ethernet packet */ ew32(VET, ETHERNET_IEEE_VLAN_TYPE); e1000_reset_adaptive(hw); e1000_phy_get_info(hw, &adapter->phy_info); e1000_release_manageability(adapter); } /* Dump the eeprom for users having checksum issues */ static void e1000_dump_eeprom(struct e1000_adapter *adapter) { struct net_device *netdev = adapter->netdev; struct ethtool_eeprom eeprom; const struct ethtool_ops *ops = netdev->ethtool_ops; u8 *data; int i; u16 csum_old, csum_new = 0; eeprom.len = ops->get_eeprom_len(netdev); eeprom.offset = 0; data = kmalloc(eeprom.len, GFP_KERNEL); if (!data) return; ops->get_eeprom(netdev, &eeprom, data); csum_old = (data[EEPROM_CHECKSUM_REG * 2]) + (data[EEPROM_CHECKSUM_REG * 2 + 1] << 8); for (i = 0; i < EEPROM_CHECKSUM_REG * 2; i += 2) csum_new += data[i] + (data[i + 1] << 8); csum_new = EEPROM_SUM - csum_new; pr_err("/*********************/\n"); pr_err("Current EEPROM Checksum : 0x%04x\n", csum_old); pr_err("Calculated : 0x%04x\n", csum_new); pr_err("Offset Values\n"); pr_err("======== ======\n"); print_hex_dump(KERN_ERR, "", DUMP_PREFIX_OFFSET, 16, 1, data, 128, 0); pr_err("Include this output when contacting your support provider.\n"); pr_err("This is not a software error! Something bad happened to\n"); pr_err("your hardware or EEPROM image. Ignoring this problem could\n"); pr_err("result in further problems, possibly loss of data,\n"); pr_err("corruption or system hangs!\n"); pr_err("The MAC Address will be reset to 00:00:00:00:00:00,\n"); pr_err("which is invalid and requires you to set the proper MAC\n"); pr_err("address manually before continuing to enable this network\n"); pr_err("device. Please inspect the EEPROM dump and report the\n"); pr_err("issue to your hardware vendor or Intel Customer Support.\n"); pr_err("/*********************/\n"); kfree(data); } /** * e1000_is_need_ioport - determine if an adapter needs ioport resources or not * @pdev: PCI device information struct * * Return true if an adapter needs ioport resources **/ static int e1000_is_need_ioport(struct pci_dev *pdev) { switch (pdev->device) { case E1000_DEV_ID_82540EM: case E1000_DEV_ID_82540EM_LOM: case E1000_DEV_ID_82540EP: case E1000_DEV_ID_82540EP_LOM: case E1000_DEV_ID_82540EP_LP: case E1000_DEV_ID_82541EI: case E1000_DEV_ID_82541EI_MOBILE: case E1000_DEV_ID_82541ER: case E1000_DEV_ID_82541ER_LOM: case E1000_DEV_ID_82541GI: case E1000_DEV_ID_82541GI_LF: case E1000_DEV_ID_82541GI_MOBILE: case E1000_DEV_ID_82544EI_COPPER: case E1000_DEV_ID_82544EI_FIBER: case E1000_DEV_ID_82544GC_COPPER: case E1000_DEV_ID_82544GC_LOM: case E1000_DEV_ID_82545EM_COPPER: case E1000_DEV_ID_82545EM_FIBER: case E1000_DEV_ID_82546EB_COPPER: case E1000_DEV_ID_82546EB_FIBER: case E1000_DEV_ID_82546EB_QUAD_COPPER: return true; default: return false; } } static netdev_features_t e1000_fix_features(struct net_device *netdev, netdev_features_t features) { /* Since there is no support for separate Rx/Tx vlan accel * enable/disable make sure Tx flag is always in same state as Rx. */ if (features & NETIF_F_HW_VLAN_CTAG_RX) features |= NETIF_F_HW_VLAN_CTAG_TX; else features &= ~NETIF_F_HW_VLAN_CTAG_TX; return features; } static int e1000_set_features(struct net_device *netdev, netdev_features_t features) { struct e1000_adapter *adapter = netdev_priv(netdev); netdev_features_t changed = features ^ netdev->features; if (changed & NETIF_F_HW_VLAN_CTAG_RX) e1000_vlan_mode(netdev, features); if (!(changed & (NETIF_F_RXCSUM | NETIF_F_RXALL))) return 0; netdev->features = features; adapter->rx_csum = !!(features & NETIF_F_RXCSUM); if (netif_running(netdev)) e1000_reinit_locked(adapter); else e1000_reset(adapter); return 1; } static const struct net_device_ops e1000_netdev_ops = { .ndo_open = e1000_open, .ndo_stop = e1000_close, .ndo_start_xmit = e1000_xmit_frame, .ndo_set_rx_mode = e1000_set_rx_mode, .ndo_set_mac_address = e1000_set_mac, .ndo_tx_timeout = e1000_tx_timeout, .ndo_change_mtu = e1000_change_mtu, .ndo_eth_ioctl = e1000_ioctl, .ndo_validate_addr = eth_validate_addr, .ndo_vlan_rx_add_vid = e1000_vlan_rx_add_vid, .ndo_vlan_rx_kill_vid = e1000_vlan_rx_kill_vid, #ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = e1000_netpoll, #endif .ndo_fix_features = e1000_fix_features, .ndo_set_features = e1000_set_features, }; /** * e1000_init_hw_struct - initialize members of hw struct * @adapter: board private struct * @hw: structure used by e1000_hw.c * * Factors out initialization of the e1000_hw struct to its own function * that can be called very early at init (just after struct allocation). * Fields are initialized based on PCI device information and * OS network device settings (MTU size). * Returns negative error codes if MAC type setup fails. */ static int e1000_init_hw_struct(struct e1000_adapter *adapter, struct e1000_hw *hw) { struct pci_dev *pdev = adapter->pdev; /* PCI config space info */ hw->vendor_id = pdev->vendor; hw->device_id = pdev->device; hw->subsystem_vendor_id = pdev->subsystem_vendor; hw->subsystem_id = pdev->subsystem_device; hw->revision_id = pdev->revision; pci_read_config_word(pdev, PCI_COMMAND, &hw->pci_cmd_word); hw->max_frame_size = adapter->netdev->mtu + ENET_HEADER_SIZE + ETHERNET_FCS_SIZE; hw->min_frame_size = MINIMUM_ETHERNET_FRAME_SIZE; /* identify the MAC */ if (e1000_set_mac_type(hw)) { e_err(probe, "Unknown MAC Type\n"); return -EIO; } switch (hw->mac_type) { default: break; case e1000_82541: case e1000_82547: case e1000_82541_rev_2: case e1000_82547_rev_2: hw->phy_init_script = 1; break; } e1000_set_media_type(hw); e1000_get_bus_info(hw); hw->wait_autoneg_complete = false; hw->tbi_compatibility_en = true; hw->adaptive_ifs = true; /* Copper options */ if (hw->media_type == e1000_media_type_copper) { hw->mdix = AUTO_ALL_MODES; hw->disable_polarity_correction = false; hw->master_slave = E1000_MASTER_SLAVE; } return 0; } /** * e1000_probe - Device Initialization Routine * @pdev: PCI device information struct * @ent: entry in e1000_pci_tbl * * Returns 0 on success, negative on failure * * e1000_probe initializes an adapter identified by a pci_dev structure. * The OS initialization, configuring of the adapter private structure, * and a hardware reset occur. **/ static int e1000_probe(struct pci_dev *pdev, const struct pci_device_id *ent) { struct net_device *netdev; struct e1000_adapter *adapter = NULL; struct e1000_hw *hw; static int cards_found; static int global_quad_port_a; /* global ksp3 port a indication */ int i, err, pci_using_dac; u16 eeprom_data = 0; u16 tmp = 0; u16 eeprom_apme_mask = E1000_EEPROM_APME; int bars, need_ioport; bool disable_dev = false; /* do not allocate ioport bars when not needed */ need_ioport = e1000_is_need_ioport(pdev); if (need_ioport) { bars = pci_select_bars(pdev, IORESOURCE_MEM | IORESOURCE_IO); err = pci_enable_device(pdev); } else { bars = pci_select_bars(pdev, IORESOURCE_MEM); err = pci_enable_device_mem(pdev); } if (err) return err; err = pci_request_selected_regions(pdev, bars, e1000_driver_name); if (err) goto err_pci_reg; pci_set_master(pdev); err = pci_save_state(pdev); if (err) goto err_alloc_etherdev; err = -ENOMEM; netdev = alloc_etherdev(sizeof(struct e1000_adapter)); if (!netdev) goto err_alloc_etherdev; SET_NETDEV_DEV(netdev, &pdev->dev); pci_set_drvdata(pdev, netdev); adapter = netdev_priv(netdev); adapter->netdev = netdev; adapter->pdev = pdev; adapter->msg_enable = netif_msg_init(debug, DEFAULT_MSG_ENABLE); adapter->bars = bars; adapter->need_ioport = need_ioport; hw = &adapter->hw; hw->back = adapter; err = -EIO; hw->hw_addr = pci_ioremap_bar(pdev, BAR_0); if (!hw->hw_addr) goto err_ioremap; if (adapter->need_ioport) { for (i = BAR_1; i < PCI_STD_NUM_BARS; i++) { if (pci_resource_len(pdev, i) == 0) continue; if (pci_resource_flags(pdev, i) & IORESOURCE_IO) { hw->io_base = pci_resource_start(pdev, i); break; } } } /* make ready for any if (hw->...) below */ err = e1000_init_hw_struct(adapter, hw); if (err) goto err_sw_init; /* there is a workaround being applied below that limits * 64-bit DMA addresses to 64-bit hardware. There are some * 32-bit adapters that Tx hang when given 64-bit DMA addresses */ pci_using_dac = 0; if ((hw->bus_type == e1000_bus_type_pcix) && !dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64))) { pci_using_dac = 1; } else { err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)); if (err) { pr_err("No usable DMA config, aborting\n"); goto err_dma; } } netdev->netdev_ops = &e1000_netdev_ops; e1000_set_ethtool_ops(netdev); netdev->watchdog_timeo = 5 * HZ; netif_napi_add(netdev, &adapter->napi, e1000_clean); strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1); adapter->bd_number = cards_found; /* setup the private structure */ err = e1000_sw_init(adapter); if (err) goto err_sw_init; err = -EIO; if (hw->mac_type == e1000_ce4100) { hw->ce4100_gbe_mdio_base_virt = ioremap(pci_resource_start(pdev, BAR_1), pci_resource_len(pdev, BAR_1)); if (!hw->ce4100_gbe_mdio_base_virt) goto err_mdio_ioremap; } if (hw->mac_type >= e1000_82543) { netdev->hw_features = NETIF_F_SG | NETIF_F_HW_CSUM | NETIF_F_HW_VLAN_CTAG_RX; netdev->features = NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_FILTER; } if ((hw->mac_type >= e1000_82544) && (hw->mac_type != e1000_82547)) netdev->hw_features |= NETIF_F_TSO; netdev->priv_flags |= IFF_SUPP_NOFCS; netdev->features |= netdev->hw_features; netdev->hw_features |= (NETIF_F_RXCSUM | NETIF_F_RXALL | NETIF_F_RXFCS); if (pci_using_dac) { netdev->features |= NETIF_F_HIGHDMA; netdev->vlan_features |= NETIF_F_HIGHDMA; } netdev->vlan_features |= (NETIF_F_TSO | NETIF_F_HW_CSUM | NETIF_F_SG); /* Do not set IFF_UNICAST_FLT for VMWare's 82545EM */ if (hw->device_id != E1000_DEV_ID_82545EM_COPPER || hw->subsystem_vendor_id != PCI_VENDOR_ID_VMWARE) netdev->priv_flags |= IFF_UNICAST_FLT; /* MTU range: 46 - 16110 */ netdev->min_mtu = ETH_ZLEN - ETH_HLEN; netdev->max_mtu = MAX_JUMBO_FRAME_SIZE - (ETH_HLEN + ETH_FCS_LEN); adapter->en_mng_pt = e1000_enable_mng_pass_thru(hw); /* initialize eeprom parameters */ if (e1000_init_eeprom_params(hw)) { e_err(probe, "EEPROM initialization failed\n"); goto err_eeprom; } /* before reading the EEPROM, reset the controller to * put the device in a known good starting state */ e1000_reset_hw(hw); /* make sure the EEPROM is good */ if (e1000_validate_eeprom_checksum(hw) < 0) { e_err(probe, "The EEPROM Checksum Is Not Valid\n"); e1000_dump_eeprom(adapter); /* set MAC address to all zeroes to invalidate and temporary * disable this device for the user. This blocks regular * traffic while still permitting ethtool ioctls from reaching * the hardware as well as allowing the user to run the * interface after manually setting a hw addr using * `ip set address` */ memset(hw->mac_addr, 0, netdev->addr_len); } else { /* copy the MAC address out of the EEPROM */ if (e1000_read_mac_addr(hw)) e_err(probe, "EEPROM Read Error\n"); } /* don't block initialization here due to bad MAC address */ eth_hw_addr_set(netdev, hw->mac_addr); if (!is_valid_ether_addr(netdev->dev_addr)) e_err(probe, "Invalid MAC Address\n"); INIT_DELAYED_WORK(&adapter->watchdog_task, e1000_watchdog); INIT_DELAYED_WORK(&adapter->fifo_stall_task, e1000_82547_tx_fifo_stall_task); INIT_DELAYED_WORK(&adapter->phy_info_task, e1000_update_phy_info_task); INIT_WORK(&adapter->reset_task, e1000_reset_task); e1000_check_options(adapter); /* Initial Wake on LAN setting * If APM wake is enabled in the EEPROM, * enable the ACPI Magic Packet filter */ switch (hw->mac_type) { case e1000_82542_rev2_0: case e1000_82542_rev2_1: case e1000_82543: break; case e1000_82544: e1000_read_eeprom(hw, EEPROM_INIT_CONTROL2_REG, 1, &eeprom_data); eeprom_apme_mask = E1000_EEPROM_82544_APM; break; case e1000_82546: case e1000_82546_rev_3: if (er32(STATUS) & E1000_STATUS_FUNC_1) { e1000_read_eeprom(hw, EEPROM_INIT_CONTROL3_PORT_B, 1, &eeprom_data); break; } fallthrough; default: e1000_read_eeprom(hw, EEPROM_INIT_CONTROL3_PORT_A, 1, &eeprom_data); break; } if (eeprom_data & eeprom_apme_mask) adapter->eeprom_wol |= E1000_WUFC_MAG; /* now that we have the eeprom settings, apply the special cases * where the eeprom may be wrong or the board simply won't support * wake on lan on a particular port */ switch (pdev->device) { case E1000_DEV_ID_82546GB_PCIE: adapter->eeprom_wol = 0; break; case E1000_DEV_ID_82546EB_FIBER: case E1000_DEV_ID_82546GB_FIBER: /* Wake events only supported on port A for dual fiber * regardless of eeprom setting */ if (er32(STATUS) & E1000_STATUS_FUNC_1) adapter->eeprom_wol = 0; break; case E1000_DEV_ID_82546GB_QUAD_COPPER_KSP3: /* if quad port adapter, disable WoL on all but port A */ if (global_quad_port_a != 0) adapter->eeprom_wol = 0; else adapter->quad_port_a = true; /* Reset for multiple quad port adapters */ if (++global_quad_port_a == 4) global_quad_port_a = 0; break; } /* initialize the wol settings based on the eeprom settings */ adapter->wol = adapter->eeprom_wol; device_set_wakeup_enable(&adapter->pdev->dev, adapter->wol); /* Auto detect PHY address */ if (hw->mac_type == e1000_ce4100) { for (i = 0; i < 32; i++) { hw->phy_addr = i; e1000_read_phy_reg(hw, PHY_ID2, &tmp); if (tmp != 0 && tmp != 0xFF) break; } if (i >= 32) goto err_eeprom; } /* reset the hardware with the new settings */ e1000_reset(adapter); strcpy(netdev->name, "eth%d"); err = register_netdev(netdev); if (err) goto err_register; e1000_vlan_filter_on_off(adapter, false); /* print bus type/speed/width info */ e_info(probe, "(PCI%s:%dMHz:%d-bit) %pM\n", ((hw->bus_type == e1000_bus_type_pcix) ? "-X" : ""), ((hw->bus_speed == e1000_bus_speed_133) ? 133 : (hw->bus_speed == e1000_bus_speed_120) ? 120 : (hw->bus_speed == e1000_bus_speed_100) ? 100 : (hw->bus_speed == e1000_bus_speed_66) ? 66 : 33), ((hw->bus_width == e1000_bus_width_64) ? 64 : 32), netdev->dev_addr); /* carrier off reporting is important to ethtool even BEFORE open */ netif_carrier_off(netdev); e_info(probe, "Intel(R) PRO/1000 Network Connection\n"); cards_found++; return 0; err_register: err_eeprom: e1000_phy_hw_reset(hw); if (hw->flash_address) iounmap(hw->flash_address); kfree(adapter->tx_ring); kfree(adapter->rx_ring); err_dma: err_sw_init: err_mdio_ioremap: iounmap(hw->ce4100_gbe_mdio_base_virt); iounmap(hw->hw_addr); err_ioremap: disable_dev = !test_and_set_bit(__E1000_DISABLED, &adapter->flags); free_netdev(netdev); err_alloc_etherdev: pci_release_selected_regions(pdev, bars); err_pci_reg: if (!adapter || disable_dev) pci_disable_device(pdev); return err; } /** * e1000_remove - Device Removal Routine * @pdev: PCI device information struct * * e1000_remove is called by the PCI subsystem to alert the driver * that it should release a PCI device. That could be caused by a * Hot-Plug event, or because the driver is going to be removed from * memory. **/ static void e1000_remove(struct pci_dev *pdev) { struct net_device *netdev = pci_get_drvdata(pdev); struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; bool disable_dev; e1000_down_and_stop(adapter); e1000_release_manageability(adapter); unregister_netdev(netdev); e1000_phy_hw_reset(hw); kfree(adapter->tx_ring); kfree(adapter->rx_ring); if (hw->mac_type == e1000_ce4100) iounmap(hw->ce4100_gbe_mdio_base_virt); iounmap(hw->hw_addr); if (hw->flash_address) iounmap(hw->flash_address); pci_release_selected_regions(pdev, adapter->bars); disable_dev = !test_and_set_bit(__E1000_DISABLED, &adapter->flags); free_netdev(netdev); if (disable_dev) pci_disable_device(pdev); } /** * e1000_sw_init - Initialize general software structures (struct e1000_adapter) * @adapter: board private structure to initialize * * e1000_sw_init initializes the Adapter private data structure. * e1000_init_hw_struct MUST be called before this function **/ static int e1000_sw_init(struct e1000_adapter *adapter) { adapter->rx_buffer_len = MAXIMUM_ETHERNET_VLAN_SIZE; adapter->num_tx_queues = 1; adapter->num_rx_queues = 1; if (e1000_alloc_queues(adapter)) { e_err(probe, "Unable to allocate memory for queues\n"); return -ENOMEM; } /* Explicitly disable IRQ since the NIC can be in any state. */ e1000_irq_disable(adapter); spin_lock_init(&adapter->stats_lock); set_bit(__E1000_DOWN, &adapter->flags); return 0; } /** * e1000_alloc_queues - Allocate memory for all rings * @adapter: board private structure to initialize * * We allocate one ring per queue at run-time since we don't know the * number of queues at compile-time. **/ static int e1000_alloc_queues(struct e1000_adapter *adapter) { adapter->tx_ring = kcalloc(adapter->num_tx_queues, sizeof(struct e1000_tx_ring), GFP_KERNEL); if (!adapter->tx_ring) return -ENOMEM; adapter->rx_ring = kcalloc(adapter->num_rx_queues, sizeof(struct e1000_rx_ring), GFP_KERNEL); if (!adapter->rx_ring) { kfree(adapter->tx_ring); return -ENOMEM; } return E1000_SUCCESS; } /** * e1000_open - Called when a network interface is made active * @netdev: network interface device structure * * Returns 0 on success, negative value on failure * * The open entry point is called when a network interface is made * active by the system (IFF_UP). At this point all resources needed * for transmit and receive operations are allocated, the interrupt * handler is registered with the OS, the watchdog task is started, * and the stack is notified that the interface is ready. **/ int e1000_open(struct net_device *netdev) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; int err; /* disallow open during test */ if (test_bit(__E1000_TESTING, &adapter->flags)) return -EBUSY; netif_carrier_off(netdev); /* allocate transmit descriptors */ err = e1000_setup_all_tx_resources(adapter); if (err) goto err_setup_tx; /* allocate receive descriptors */ err = e1000_setup_all_rx_resources(adapter); if (err) goto err_setup_rx; e1000_power_up_phy(adapter); adapter->mng_vlan_id = E1000_MNG_VLAN_NONE; if ((hw->mng_cookie.status & E1000_MNG_DHCP_COOKIE_STATUS_VLAN_SUPPORT)) { e1000_update_mng_vlan(adapter); } /* before we allocate an interrupt, we must be ready to handle it. * Setting DEBUG_SHIRQ in the kernel makes it fire an interrupt * as soon as we call pci_request_irq, so we have to setup our * clean_rx handler before we do so. */ e1000_configure(adapter); err = e1000_request_irq(adapter); if (err) goto err_req_irq; /* From here on the code is the same as e1000_up() */ clear_bit(__E1000_DOWN, &adapter->flags); napi_enable(&adapter->napi); e1000_irq_enable(adapter); netif_start_queue(netdev); /* fire a link status change interrupt to start the watchdog */ ew32(ICS, E1000_ICS_LSC); return E1000_SUCCESS; err_req_irq: e1000_power_down_phy(adapter); e1000_free_all_rx_resources(adapter); err_setup_rx: e1000_free_all_tx_resources(adapter); err_setup_tx: e1000_reset(adapter); return err; } /** * e1000_close - Disables a network interface * @netdev: network interface device structure * * Returns 0, this is not allowed to fail * * The close entry point is called when an interface is de-activated * by the OS. The hardware is still under the drivers control, but * needs to be disabled. A global MAC reset is issued to stop the * hardware, and all transmit and receive resources are freed. **/ int e1000_close(struct net_device *netdev) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; int count = E1000_CHECK_RESET_COUNT; while (test_and_set_bit(__E1000_RESETTING, &adapter->flags) && count--) usleep_range(10000, 20000); WARN_ON(count < 0); /* signal that we're down so that the reset task will no longer run */ set_bit(__E1000_DOWN, &adapter->flags); clear_bit(__E1000_RESETTING, &adapter->flags); e1000_down(adapter); e1000_power_down_phy(adapter); e1000_free_irq(adapter); e1000_free_all_tx_resources(adapter); e1000_free_all_rx_resources(adapter); /* kill manageability vlan ID if supported, but not if a vlan with * the same ID is registered on the host OS (let 8021q kill it) */ if ((hw->mng_cookie.status & E1000_MNG_DHCP_COOKIE_STATUS_VLAN_SUPPORT) && !test_bit(adapter->mng_vlan_id, adapter->active_vlans)) { e1000_vlan_rx_kill_vid(netdev, htons(ETH_P_8021Q), adapter->mng_vlan_id); } return 0; } /** * e1000_check_64k_bound - check that memory doesn't cross 64kB boundary * @adapter: address of board private structure * @start: address of beginning of memory * @len: length of memory **/ static bool e1000_check_64k_bound(struct e1000_adapter *adapter, void *start, unsigned long len) { struct e1000_hw *hw = &adapter->hw; unsigned long begin = (unsigned long)start; unsigned long end = begin + len; /* First rev 82545 and 82546 need to not allow any memory * write location to cross 64k boundary due to errata 23 */ if (hw->mac_type == e1000_82545 || hw->mac_type == e1000_ce4100 || hw->mac_type == e1000_82546) { return ((begin ^ (end - 1)) >> 16) == 0; } return true; } /** * e1000_setup_tx_resources - allocate Tx resources (Descriptors) * @adapter: board private structure * @txdr: tx descriptor ring (for a specific queue) to setup * * Return 0 on success, negative on failure **/ static int e1000_setup_tx_resources(struct e1000_adapter *adapter, struct e1000_tx_ring *txdr) { struct pci_dev *pdev = adapter->pdev; int size; size = sizeof(struct e1000_tx_buffer) * txdr->count; txdr->buffer_info = vzalloc(size); if (!txdr->buffer_info) return -ENOMEM; /* round up to nearest 4K */ txdr->size = txdr->count * sizeof(struct e1000_tx_desc); txdr->size = ALIGN(txdr->size, 4096); txdr->desc = dma_alloc_coherent(&pdev->dev, txdr->size, &txdr->dma, GFP_KERNEL); if (!txdr->desc) { setup_tx_desc_die: vfree(txdr->buffer_info); return -ENOMEM; } /* Fix for errata 23, can't cross 64kB boundary */ if (!e1000_check_64k_bound(adapter, txdr->desc, txdr->size)) { void *olddesc = txdr->desc; dma_addr_t olddma = txdr->dma; e_err(tx_err, "txdr align check failed: %u bytes at %p\n", txdr->size, txdr->desc); /* Try again, without freeing the previous */ txdr->desc = dma_alloc_coherent(&pdev->dev, txdr->size, &txdr->dma, GFP_KERNEL); /* Failed allocation, critical failure */ if (!txdr->desc) { dma_free_coherent(&pdev->dev, txdr->size, olddesc, olddma); goto setup_tx_desc_die; } if (!e1000_check_64k_bound(adapter, txdr->desc, txdr->size)) { /* give up */ dma_free_coherent(&pdev->dev, txdr->size, txdr->desc, txdr->dma); dma_free_coherent(&pdev->dev, txdr->size, olddesc, olddma); e_err(probe, "Unable to allocate aligned memory " "for the transmit descriptor ring\n"); vfree(txdr->buffer_info); return -ENOMEM; } else { /* Free old allocation, new allocation was successful */ dma_free_coherent(&pdev->dev, txdr->size, olddesc, olddma); } } memset(txdr->desc, 0, txdr->size); txdr->next_to_use = 0; txdr->next_to_clean = 0; return 0; } /** * e1000_setup_all_tx_resources - wrapper to allocate Tx resources * (Descriptors) for all queues * @adapter: board private structure * * Return 0 on success, negative on failure **/ int e1000_setup_all_tx_resources(struct e1000_adapter *adapter) { int i, err = 0; for (i = 0; i < adapter->num_tx_queues; i++) { err = e1000_setup_tx_resources(adapter, &adapter->tx_ring[i]); if (err) { e_err(probe, "Allocation for Tx Queue %u failed\n", i); for (i-- ; i >= 0; i--) e1000_free_tx_resources(adapter, &adapter->tx_ring[i]); break; } } return err; } /** * e1000_configure_tx - Configure 8254x Transmit Unit after Reset * @adapter: board private structure * * Configure the Tx unit of the MAC after a reset. **/ static void e1000_configure_tx(struct e1000_adapter *adapter) { u64 tdba; struct e1000_hw *hw = &adapter->hw; u32 tdlen, tctl, tipg; u32 ipgr1, ipgr2; /* Setup the HW Tx Head and Tail descriptor pointers */ switch (adapter->num_tx_queues) { case 1: default: tdba = adapter->tx_ring[0].dma; tdlen = adapter->tx_ring[0].count * sizeof(struct e1000_tx_desc); ew32(TDLEN, tdlen); ew32(TDBAH, (tdba >> 32)); ew32(TDBAL, (tdba & 0x00000000ffffffffULL)); ew32(TDT, 0); ew32(TDH, 0); adapter->tx_ring[0].tdh = ((hw->mac_type >= e1000_82543) ? E1000_TDH : E1000_82542_TDH); adapter->tx_ring[0].tdt = ((hw->mac_type >= e1000_82543) ? E1000_TDT : E1000_82542_TDT); break; } /* Set the default values for the Tx Inter Packet Gap timer */ if ((hw->media_type == e1000_media_type_fiber || hw->media_type == e1000_media_type_internal_serdes)) tipg = DEFAULT_82543_TIPG_IPGT_FIBER; else tipg = DEFAULT_82543_TIPG_IPGT_COPPER; switch (hw->mac_type) { case e1000_82542_rev2_0: case e1000_82542_rev2_1: tipg = DEFAULT_82542_TIPG_IPGT; ipgr1 = DEFAULT_82542_TIPG_IPGR1; ipgr2 = DEFAULT_82542_TIPG_IPGR2; break; default: ipgr1 = DEFAULT_82543_TIPG_IPGR1; ipgr2 = DEFAULT_82543_TIPG_IPGR2; break; } tipg |= ipgr1 << E1000_TIPG_IPGR1_SHIFT; tipg |= ipgr2 << E1000_TIPG_IPGR2_SHIFT; ew32(TIPG, tipg); /* Set the Tx Interrupt Delay register */ ew32(TIDV, adapter->tx_int_delay); if (hw->mac_type >= e1000_82540) ew32(TADV, adapter->tx_abs_int_delay); /* Program the Transmit Control Register */ tctl = er32(TCTL); tctl &= ~E1000_TCTL_CT; tctl |= E1000_TCTL_PSP | E1000_TCTL_RTLC | (E1000_COLLISION_THRESHOLD << E1000_CT_SHIFT); e1000_config_collision_dist(hw); /* Setup Transmit Descriptor Settings for eop descriptor */ adapter->txd_cmd = E1000_TXD_CMD_EOP | E1000_TXD_CMD_IFCS; /* only set IDE if we are delaying interrupts using the timers */ if (adapter->tx_int_delay) adapter->txd_cmd |= E1000_TXD_CMD_IDE; if (hw->mac_type < e1000_82543) adapter->txd_cmd |= E1000_TXD_CMD_RPS; else adapter->txd_cmd |= E1000_TXD_CMD_RS; /* Cache if we're 82544 running in PCI-X because we'll * need this to apply a workaround later in the send path. */ if (hw->mac_type == e1000_82544 && hw->bus_type == e1000_bus_type_pcix) adapter->pcix_82544 = true; ew32(TCTL, tctl); } /** * e1000_setup_rx_resources - allocate Rx resources (Descriptors) * @adapter: board private structure * @rxdr: rx descriptor ring (for a specific queue) to setup * * Returns 0 on success, negative on failure **/ static int e1000_setup_rx_resources(struct e1000_adapter *adapter, struct e1000_rx_ring *rxdr) { struct pci_dev *pdev = adapter->pdev; int size, desc_len; size = sizeof(struct e1000_rx_buffer) * rxdr->count; rxdr->buffer_info = vzalloc(size); if (!rxdr->buffer_info) return -ENOMEM; desc_len = sizeof(struct e1000_rx_desc); /* Round up to nearest 4K */ rxdr->size = rxdr->count * desc_len; rxdr->size = ALIGN(rxdr->size, 4096); rxdr->desc = dma_alloc_coherent(&pdev->dev, rxdr->size, &rxdr->dma, GFP_KERNEL); if (!rxdr->desc) { setup_rx_desc_die: vfree(rxdr->buffer_info); return -ENOMEM; } /* Fix for errata 23, can't cross 64kB boundary */ if (!e1000_check_64k_bound(adapter, rxdr->desc, rxdr->size)) { void *olddesc = rxdr->desc; dma_addr_t olddma = rxdr->dma; e_err(rx_err, "rxdr align check failed: %u bytes at %p\n", rxdr->size, rxdr->desc); /* Try again, without freeing the previous */ rxdr->desc = dma_alloc_coherent(&pdev->dev, rxdr->size, &rxdr->dma, GFP_KERNEL); /* Failed allocation, critical failure */ if (!rxdr->desc) { dma_free_coherent(&pdev->dev, rxdr->size, olddesc, olddma); goto setup_rx_desc_die; } if (!e1000_check_64k_bound(adapter, rxdr->desc, rxdr->size)) { /* give up */ dma_free_coherent(&pdev->dev, rxdr->size, rxdr->desc, rxdr->dma); dma_free_coherent(&pdev->dev, rxdr->size, olddesc, olddma); e_err(probe, "Unable to allocate aligned memory for " "the Rx descriptor ring\n"); goto setup_rx_desc_die; } else { /* Free old allocation, new allocation was successful */ dma_free_coherent(&pdev->dev, rxdr->size, olddesc, olddma); } } memset(rxdr->desc, 0, rxdr->size); rxdr->next_to_clean = 0; rxdr->next_to_use = 0; rxdr->rx_skb_top = NULL; return 0; } /** * e1000_setup_all_rx_resources - wrapper to allocate Rx resources * (Descriptors) for all queues * @adapter: board private structure * * Return 0 on success, negative on failure **/ int e1000_setup_all_rx_resources(struct e1000_adapter *adapter) { int i, err = 0; for (i = 0; i < adapter->num_rx_queues; i++) { err = e1000_setup_rx_resources(adapter, &adapter->rx_ring[i]); if (err) { e_err(probe, "Allocation for Rx Queue %u failed\n", i); for (i-- ; i >= 0; i--) e1000_free_rx_resources(adapter, &adapter->rx_ring[i]); break; } } return err; } /** * e1000_setup_rctl - configure the receive control registers * @adapter: Board private structure **/ static void e1000_setup_rctl(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 rctl; rctl = er32(RCTL); rctl &= ~(3 << E1000_RCTL_MO_SHIFT); rctl |= E1000_RCTL_BAM | E1000_RCTL_LBM_NO | E1000_RCTL_RDMTS_HALF | (hw->mc_filter_type << E1000_RCTL_MO_SHIFT); if (hw->tbi_compatibility_on == 1) rctl |= E1000_RCTL_SBP; else rctl &= ~E1000_RCTL_SBP; if (adapter->netdev->mtu <= ETH_DATA_LEN) rctl &= ~E1000_RCTL_LPE; else rctl |= E1000_RCTL_LPE; /* Setup buffer sizes */ rctl &= ~E1000_RCTL_SZ_4096; rctl |= E1000_RCTL_BSEX; switch (adapter->rx_buffer_len) { case E1000_RXBUFFER_2048: default: rctl |= E1000_RCTL_SZ_2048; rctl &= ~E1000_RCTL_BSEX; break; case E1000_RXBUFFER_4096: rctl |= E1000_RCTL_SZ_4096; break; case E1000_RXBUFFER_8192: rctl |= E1000_RCTL_SZ_8192; break; case E1000_RXBUFFER_16384: rctl |= E1000_RCTL_SZ_16384; break; } /* This is useful for sniffing bad packets. */ if (adapter->netdev->features & NETIF_F_RXALL) { /* UPE and MPE will be handled by normal PROMISC logic * in e1000e_set_rx_mode */ rctl |= (E1000_RCTL_SBP | /* Receive bad packets */ E1000_RCTL_BAM | /* RX All Bcast Pkts */ E1000_RCTL_PMCF); /* RX All MAC Ctrl Pkts */ rctl &= ~(E1000_RCTL_VFE | /* Disable VLAN filter */ E1000_RCTL_DPF | /* Allow filtered pause */ E1000_RCTL_CFIEN); /* Dis VLAN CFIEN Filter */ /* Do not mess with E1000_CTRL_VME, it affects transmit as well, * and that breaks VLANs. */ } ew32(RCTL, rctl); } /** * e1000_configure_rx - Configure 8254x Receive Unit after Reset * @adapter: board private structure * * Configure the Rx unit of the MAC after a reset. **/ static void e1000_configure_rx(struct e1000_adapter *adapter) { u64 rdba; struct e1000_hw *hw = &adapter->hw; u32 rdlen, rctl, rxcsum; if (adapter->netdev->mtu > ETH_DATA_LEN) { rdlen = adapter->rx_ring[0].count * sizeof(struct e1000_rx_desc); adapter->clean_rx = e1000_clean_jumbo_rx_irq; adapter->alloc_rx_buf = e1000_alloc_jumbo_rx_buffers; } else { rdlen = adapter->rx_ring[0].count * sizeof(struct e1000_rx_desc); adapter->clean_rx = e1000_clean_rx_irq; adapter->alloc_rx_buf = e1000_alloc_rx_buffers; } /* disable receives while setting up the descriptors */ rctl = er32(RCTL); ew32(RCTL, rctl & ~E1000_RCTL_EN); /* set the Receive Delay Timer Register */ ew32(RDTR, adapter->rx_int_delay); if (hw->mac_type >= e1000_82540) { ew32(RADV, adapter->rx_abs_int_delay); if (adapter->itr_setting != 0) ew32(ITR, 1000000000 / (adapter->itr * 256)); } /* Setup the HW Rx Head and Tail Descriptor Pointers and * the Base and Length of the Rx Descriptor Ring */ switch (adapter->num_rx_queues) { case 1: default: rdba = adapter->rx_ring[0].dma; ew32(RDLEN, rdlen); ew32(RDBAH, (rdba >> 32)); ew32(RDBAL, (rdba & 0x00000000ffffffffULL)); ew32(RDT, 0); ew32(RDH, 0); adapter->rx_ring[0].rdh = ((hw->mac_type >= e1000_82543) ? E1000_RDH : E1000_82542_RDH); adapter->rx_ring[0].rdt = ((hw->mac_type >= e1000_82543) ? E1000_RDT : E1000_82542_RDT); break; } /* Enable 82543 Receive Checksum Offload for TCP and UDP */ if (hw->mac_type >= e1000_82543) { rxcsum = er32(RXCSUM); if (adapter->rx_csum) rxcsum |= E1000_RXCSUM_TUOFL; else /* don't need to clear IPPCSE as it defaults to 0 */ rxcsum &= ~E1000_RXCSUM_TUOFL; ew32(RXCSUM, rxcsum); } /* Enable Receives */ ew32(RCTL, rctl | E1000_RCTL_EN); } /** * e1000_free_tx_resources - Free Tx Resources per Queue * @adapter: board private structure * @tx_ring: Tx descriptor ring for a specific queue * * Free all transmit software resources **/ static void e1000_free_tx_resources(struct e1000_adapter *adapter, struct e1000_tx_ring *tx_ring) { struct pci_dev *pdev = adapter->pdev; e1000_clean_tx_ring(adapter, tx_ring); vfree(tx_ring->buffer_info); tx_ring->buffer_info = NULL; dma_free_coherent(&pdev->dev, tx_ring->size, tx_ring->desc, tx_ring->dma); tx_ring->desc = NULL; } /** * e1000_free_all_tx_resources - Free Tx Resources for All Queues * @adapter: board private structure * * Free all transmit software resources **/ void e1000_free_all_tx_resources(struct e1000_adapter *adapter) { int i; for (i = 0; i < adapter->num_tx_queues; i++) e1000_free_tx_resources(adapter, &adapter->tx_ring[i]); } static void e1000_unmap_and_free_tx_resource(struct e1000_adapter *adapter, struct e1000_tx_buffer *buffer_info, int budget) { if (buffer_info->dma) { if (buffer_info->mapped_as_page) dma_unmap_page(&adapter->pdev->dev, buffer_info->dma, buffer_info->length, DMA_TO_DEVICE); else dma_unmap_single(&adapter->pdev->dev, buffer_info->dma, buffer_info->length, DMA_TO_DEVICE); buffer_info->dma = 0; } if (buffer_info->skb) { napi_consume_skb(buffer_info->skb, budget); buffer_info->skb = NULL; } buffer_info->time_stamp = 0; /* buffer_info must be completely set up in the transmit path */ } /** * e1000_clean_tx_ring - Free Tx Buffers * @adapter: board private structure * @tx_ring: ring to be cleaned **/ static void e1000_clean_tx_ring(struct e1000_adapter *adapter, struct e1000_tx_ring *tx_ring) { struct e1000_hw *hw = &adapter->hw; struct e1000_tx_buffer *buffer_info; unsigned long size; unsigned int i; /* Free all the Tx ring sk_buffs */ for (i = 0; i < tx_ring->count; i++) { buffer_info = &tx_ring->buffer_info[i]; e1000_unmap_and_free_tx_resource(adapter, buffer_info, 0); } netdev_reset_queue(adapter->netdev); size = sizeof(struct e1000_tx_buffer) * tx_ring->count; memset(tx_ring->buffer_info, 0, size); /* Zero out the descriptor ring */ memset(tx_ring->desc, 0, tx_ring->size); tx_ring->next_to_use = 0; tx_ring->next_to_clean = 0; tx_ring->last_tx_tso = false; writel(0, hw->hw_addr + tx_ring->tdh); writel(0, hw->hw_addr + tx_ring->tdt); } /** * e1000_clean_all_tx_rings - Free Tx Buffers for all queues * @adapter: board private structure **/ static void e1000_clean_all_tx_rings(struct e1000_adapter *adapter) { int i; for (i = 0; i < adapter->num_tx_queues; i++) e1000_clean_tx_ring(adapter, &adapter->tx_ring[i]); } /** * e1000_free_rx_resources - Free Rx Resources * @adapter: board private structure * @rx_ring: ring to clean the resources from * * Free all receive software resources **/ static void e1000_free_rx_resources(struct e1000_adapter *adapter, struct e1000_rx_ring *rx_ring) { struct pci_dev *pdev = adapter->pdev; e1000_clean_rx_ring(adapter, rx_ring); vfree(rx_ring->buffer_info); rx_ring->buffer_info = NULL; dma_free_coherent(&pdev->dev, rx_ring->size, rx_ring->desc, rx_ring->dma); rx_ring->desc = NULL; } /** * e1000_free_all_rx_resources - Free Rx Resources for All Queues * @adapter: board private structure * * Free all receive software resources **/ void e1000_free_all_rx_resources(struct e1000_adapter *adapter) { int i; for (i = 0; i < adapter->num_rx_queues; i++) e1000_free_rx_resources(adapter, &adapter->rx_ring[i]); } #define E1000_HEADROOM (NET_SKB_PAD + NET_IP_ALIGN) static unsigned int e1000_frag_len(const struct e1000_adapter *a) { return SKB_DATA_ALIGN(a->rx_buffer_len + E1000_HEADROOM) + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); } static void *e1000_alloc_frag(const struct e1000_adapter *a) { unsigned int len = e1000_frag_len(a); u8 *data = netdev_alloc_frag(len); if (likely(data)) data += E1000_HEADROOM; return data; } /** * e1000_clean_rx_ring - Free Rx Buffers per Queue * @adapter: board private structure * @rx_ring: ring to free buffers from **/ static void e1000_clean_rx_ring(struct e1000_adapter *adapter, struct e1000_rx_ring *rx_ring) { struct e1000_hw *hw = &adapter->hw; struct e1000_rx_buffer *buffer_info; struct pci_dev *pdev = adapter->pdev; unsigned long size; unsigned int i; /* Free all the Rx netfrags */ for (i = 0; i < rx_ring->count; i++) { buffer_info = &rx_ring->buffer_info[i]; if (adapter->clean_rx == e1000_clean_rx_irq) { if (buffer_info->dma) dma_unmap_single(&pdev->dev, buffer_info->dma, adapter->rx_buffer_len, DMA_FROM_DEVICE); if (buffer_info->rxbuf.data) { skb_free_frag(buffer_info->rxbuf.data); buffer_info->rxbuf.data = NULL; } } else if (adapter->clean_rx == e1000_clean_jumbo_rx_irq) { if (buffer_info->dma) dma_unmap_page(&pdev->dev, buffer_info->dma, adapter->rx_buffer_len, DMA_FROM_DEVICE); if (buffer_info->rxbuf.page) { put_page(buffer_info->rxbuf.page); buffer_info->rxbuf.page = NULL; } } buffer_info->dma = 0; } /* there also may be some cached data from a chained receive */ napi_free_frags(&adapter->napi); rx_ring->rx_skb_top = NULL; size = sizeof(struct e1000_rx_buffer) * rx_ring->count; memset(rx_ring->buffer_info, 0, size); /* Zero out the descriptor ring */ memset(rx_ring->desc, 0, rx_ring->size); rx_ring->next_to_clean = 0; rx_ring->next_to_use = 0; writel(0, hw->hw_addr + rx_ring->rdh); writel(0, hw->hw_addr + rx_ring->rdt); } /** * e1000_clean_all_rx_rings - Free Rx Buffers for all queues * @adapter: board private structure **/ static void e1000_clean_all_rx_rings(struct e1000_adapter *adapter) { int i; for (i = 0; i < adapter->num_rx_queues; i++) e1000_clean_rx_ring(adapter, &adapter->rx_ring[i]); } /* The 82542 2.0 (revision 2) needs to have the receive unit in reset * and memory write and invalidate disabled for certain operations */ static void e1000_enter_82542_rst(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; struct net_device *netdev = adapter->netdev; u32 rctl; e1000_pci_clear_mwi(hw); rctl = er32(RCTL); rctl |= E1000_RCTL_RST; ew32(RCTL, rctl); E1000_WRITE_FLUSH(); mdelay(5); if (netif_running(netdev)) e1000_clean_all_rx_rings(adapter); } static void e1000_leave_82542_rst(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; struct net_device *netdev = adapter->netdev; u32 rctl; rctl = er32(RCTL); rctl &= ~E1000_RCTL_RST; ew32(RCTL, rctl); E1000_WRITE_FLUSH(); mdelay(5); if (hw->pci_cmd_word & PCI_COMMAND_INVALIDATE) e1000_pci_set_mwi(hw); if (netif_running(netdev)) { /* No need to loop, because 82542 supports only 1 queue */ struct e1000_rx_ring *ring = &adapter->rx_ring[0]; e1000_configure_rx(adapter); adapter->alloc_rx_buf(adapter, ring, E1000_DESC_UNUSED(ring)); } } /** * e1000_set_mac - Change the Ethernet Address of the NIC * @netdev: network interface device structure * @p: pointer to an address structure * * Returns 0 on success, negative on failure **/ static int e1000_set_mac(struct net_device *netdev, void *p) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; struct sockaddr *addr = p; if (!is_valid_ether_addr(addr->sa_data)) return -EADDRNOTAVAIL; /* 82542 2.0 needs to be in reset to write receive address registers */ if (hw->mac_type == e1000_82542_rev2_0) e1000_enter_82542_rst(adapter); eth_hw_addr_set(netdev, addr->sa_data); memcpy(hw->mac_addr, addr->sa_data, netdev->addr_len); e1000_rar_set(hw, hw->mac_addr, 0); if (hw->mac_type == e1000_82542_rev2_0) e1000_leave_82542_rst(adapter); return 0; } /** * e1000_set_rx_mode - Secondary Unicast, Multicast and Promiscuous mode set * @netdev: network interface device structure * * The set_rx_mode entry point is called whenever the unicast or multicast * address lists or the network interface flags are updated. This routine is * responsible for configuring the hardware for proper unicast, multicast, * promiscuous mode, and all-multi behavior. **/ static void e1000_set_rx_mode(struct net_device *netdev) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; struct netdev_hw_addr *ha; bool use_uc = false; u32 rctl; u32 hash_value; int i, rar_entries = E1000_RAR_ENTRIES; int mta_reg_count = E1000_NUM_MTA_REGISTERS; u32 *mcarray = kcalloc(mta_reg_count, sizeof(u32), GFP_ATOMIC); if (!mcarray) return; /* Check for Promiscuous and All Multicast modes */ rctl = er32(RCTL); if (netdev->flags & IFF_PROMISC) { rctl |= (E1000_RCTL_UPE | E1000_RCTL_MPE); rctl &= ~E1000_RCTL_VFE; } else { if (netdev->flags & IFF_ALLMULTI) rctl |= E1000_RCTL_MPE; else rctl &= ~E1000_RCTL_MPE; /* Enable VLAN filter if there is a VLAN */ if (e1000_vlan_used(adapter)) rctl |= E1000_RCTL_VFE; } if (netdev_uc_count(netdev) > rar_entries - 1) { rctl |= E1000_RCTL_UPE; } else if (!(netdev->flags & IFF_PROMISC)) { rctl &= ~E1000_RCTL_UPE; use_uc = true; } ew32(RCTL, rctl); /* 82542 2.0 needs to be in reset to write receive address registers */ if (hw->mac_type == e1000_82542_rev2_0) e1000_enter_82542_rst(adapter); /* load the first 14 addresses into the exact filters 1-14. Unicast * addresses take precedence to avoid disabling unicast filtering * when possible. * * RAR 0 is used for the station MAC address * if there are not 14 addresses, go ahead and clear the filters */ i = 1; if (use_uc) netdev_for_each_uc_addr(ha, netdev) { if (i == rar_entries) break; e1000_rar_set(hw, ha->addr, i++); } netdev_for_each_mc_addr(ha, netdev) { if (i == rar_entries) { /* load any remaining addresses into the hash table */ u32 hash_reg, hash_bit, mta; hash_value = e1000_hash_mc_addr(hw, ha->addr); hash_reg = (hash_value >> 5) & 0x7F; hash_bit = hash_value & 0x1F; mta = (1 << hash_bit); mcarray[hash_reg] |= mta; } else { e1000_rar_set(hw, ha->addr, i++); } } for (; i < rar_entries; i++) { E1000_WRITE_REG_ARRAY(hw, RA, i << 1, 0); E1000_WRITE_FLUSH(); E1000_WRITE_REG_ARRAY(hw, RA, (i << 1) + 1, 0); E1000_WRITE_FLUSH(); } /* write the hash table completely, write from bottom to avoid * both stupid write combining chipsets, and flushing each write */ for (i = mta_reg_count - 1; i >= 0 ; i--) { /* If we are on an 82544 has an errata where writing odd * offsets overwrites the previous even offset, but writing * backwards over the range solves the issue by always * writing the odd offset first */ E1000_WRITE_REG_ARRAY(hw, MTA, i, mcarray[i]); } E1000_WRITE_FLUSH(); if (hw->mac_type == e1000_82542_rev2_0) e1000_leave_82542_rst(adapter); kfree(mcarray); } /** * e1000_update_phy_info_task - get phy info * @work: work struct contained inside adapter struct * * Need to wait a few seconds after link up to get diagnostic information from * the phy */ static void e1000_update_phy_info_task(struct work_struct *work) { struct e1000_adapter *adapter = container_of(work, struct e1000_adapter, phy_info_task.work); e1000_phy_get_info(&adapter->hw, &adapter->phy_info); } /** * e1000_82547_tx_fifo_stall_task - task to complete work * @work: work struct contained inside adapter struct **/ static void e1000_82547_tx_fifo_stall_task(struct work_struct *work) { struct e1000_adapter *adapter = container_of(work, struct e1000_adapter, fifo_stall_task.work); struct e1000_hw *hw = &adapter->hw; struct net_device *netdev = adapter->netdev; u32 tctl; if (atomic_read(&adapter->tx_fifo_stall)) { if ((er32(TDT) == er32(TDH)) && (er32(TDFT) == er32(TDFH)) && (er32(TDFTS) == er32(TDFHS))) { tctl = er32(TCTL); ew32(TCTL, tctl & ~E1000_TCTL_EN); ew32(TDFT, adapter->tx_head_addr); ew32(TDFH, adapter->tx_head_addr); ew32(TDFTS, adapter->tx_head_addr); ew32(TDFHS, adapter->tx_head_addr); ew32(TCTL, tctl); E1000_WRITE_FLUSH(); adapter->tx_fifo_head = 0; atomic_set(&adapter->tx_fifo_stall, 0); netif_wake_queue(netdev); } else if (!test_bit(__E1000_DOWN, &adapter->flags)) { schedule_delayed_work(&adapter->fifo_stall_task, 1); } } } bool e1000_has_link(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; bool link_active = false; /* get_link_status is set on LSC (link status) interrupt or rx * sequence error interrupt (except on intel ce4100). * get_link_status will stay false until the * e1000_check_for_link establishes link for copper adapters * ONLY */ switch (hw->media_type) { case e1000_media_type_copper: if (hw->mac_type == e1000_ce4100) hw->get_link_status = 1; if (hw->get_link_status) { e1000_check_for_link(hw); link_active = !hw->get_link_status; } else { link_active = true; } break; case e1000_media_type_fiber: e1000_check_for_link(hw); link_active = !!(er32(STATUS) & E1000_STATUS_LU); break; case e1000_media_type_internal_serdes: e1000_check_for_link(hw); link_active = hw->serdes_has_link; break; default: break; } return link_active; } /** * e1000_watchdog - work function * @work: work struct contained inside adapter struct **/ static void e1000_watchdog(struct work_struct *work) { struct e1000_adapter *adapter = container_of(work, struct e1000_adapter, watchdog_task.work); struct e1000_hw *hw = &adapter->hw; struct net_device *netdev = adapter->netdev; struct e1000_tx_ring *txdr = adapter->tx_ring; u32 link, tctl; link = e1000_has_link(adapter); if ((netif_carrier_ok(netdev)) && link) goto link_up; if (link) { if (!netif_carrier_ok(netdev)) { u32 ctrl; /* update snapshot of PHY registers on LSC */ e1000_get_speed_and_duplex(hw, &adapter->link_speed, &adapter->link_duplex); ctrl = er32(CTRL); pr_info("%s NIC Link is Up %d Mbps %s, " "Flow Control: %s\n", netdev->name, adapter->link_speed, adapter->link_duplex == FULL_DUPLEX ? "Full Duplex" : "Half Duplex", ((ctrl & E1000_CTRL_TFCE) && (ctrl & E1000_CTRL_RFCE)) ? "RX/TX" : ((ctrl & E1000_CTRL_RFCE) ? "RX" : ((ctrl & E1000_CTRL_TFCE) ? "TX" : "None"))); /* adjust timeout factor according to speed/duplex */ adapter->tx_timeout_factor = 1; switch (adapter->link_speed) { case SPEED_10: adapter->tx_timeout_factor = 16; break; case SPEED_100: /* maybe add some timeout factor ? */ break; } /* enable transmits in the hardware */ tctl = er32(TCTL); tctl |= E1000_TCTL_EN; ew32(TCTL, tctl); netif_carrier_on(netdev); if (!test_bit(__E1000_DOWN, &adapter->flags)) schedule_delayed_work(&adapter->phy_info_task, 2 * HZ); adapter->smartspeed = 0; } } else { if (netif_carrier_ok(netdev)) { adapter->link_speed = 0; adapter->link_duplex = 0; pr_info("%s NIC Link is Down\n", netdev->name); netif_carrier_off(netdev); if (!test_bit(__E1000_DOWN, &adapter->flags)) schedule_delayed_work(&adapter->phy_info_task, 2 * HZ); } e1000_smartspeed(adapter); } link_up: e1000_update_stats(adapter); hw->tx_packet_delta = adapter->stats.tpt - adapter->tpt_old; adapter->tpt_old = adapter->stats.tpt; hw->collision_delta = adapter->stats.colc - adapter->colc_old; adapter->colc_old = adapter->stats.colc; adapter->gorcl = adapter->stats.gorcl - adapter->gorcl_old; adapter->gorcl_old = adapter->stats.gorcl; adapter->gotcl = adapter->stats.gotcl - adapter->gotcl_old; adapter->gotcl_old = adapter->stats.gotcl; e1000_update_adaptive(hw); if (!netif_carrier_ok(netdev)) { if (E1000_DESC_UNUSED(txdr) + 1 < txdr->count) { /* We've lost link, so the controller stops DMA, * but we've got queued Tx work that's never going * to get done, so reset controller to flush Tx. * (Do the reset outside of interrupt context). */ adapter->tx_timeout_count++; schedule_work(&adapter->reset_task); /* exit immediately since reset is imminent */ return; } } /* Simple mode for Interrupt Throttle Rate (ITR) */ if (hw->mac_type >= e1000_82540 && adapter->itr_setting == 4) { /* Symmetric Tx/Rx gets a reduced ITR=2000; * Total asymmetrical Tx or Rx gets ITR=8000; * everyone else is between 2000-8000. */ u32 goc = (adapter->gotcl + adapter->gorcl) / 10000; u32 dif = (adapter->gotcl > adapter->gorcl ? adapter->gotcl - adapter->gorcl : adapter->gorcl - adapter->gotcl) / 10000; u32 itr = goc > 0 ? (dif * 6000 / goc + 2000) : 8000; ew32(ITR, 1000000000 / (itr * 256)); } /* Cause software interrupt to ensure rx ring is cleaned */ ew32(ICS, E1000_ICS_RXDMT0); /* Force detection of hung controller every watchdog period */ adapter->detect_tx_hung = true; /* Reschedule the task */ if (!test_bit(__E1000_DOWN, &adapter->flags)) schedule_delayed_work(&adapter->watchdog_task, 2 * HZ); } enum latency_range { lowest_latency = 0, low_latency = 1, bulk_latency = 2, latency_invalid = 255 }; /** * e1000_update_itr - update the dynamic ITR value based on statistics * @adapter: pointer to adapter * @itr_setting: current adapter->itr * @packets: the number of packets during this measurement interval * @bytes: the number of bytes during this measurement interval * * Stores a new ITR value based on packets and byte * counts during the last interrupt. The advantage of per interrupt * computation is faster updates and more accurate ITR for the current * traffic pattern. Constants in this function were computed * based on theoretical maximum wire speed and thresholds were set based * on testing data as well as attempting to minimize response time * while increasing bulk throughput. * this functionality is controlled by the InterruptThrottleRate module * parameter (see e1000_param.c) **/ static unsigned int e1000_update_itr(struct e1000_adapter *adapter, u16 itr_setting, int packets, int bytes) { unsigned int retval = itr_setting; struct e1000_hw *hw = &adapter->hw; if (unlikely(hw->mac_type < e1000_82540)) goto update_itr_done; if (packets == 0) goto update_itr_done; switch (itr_setting) { case lowest_latency: /* jumbo frames get bulk treatment*/ if (bytes/packets > 8000) retval = bulk_latency; else if ((packets < 5) && (bytes > 512)) retval = low_latency; break; case low_latency: /* 50 usec aka 20000 ints/s */ if (bytes > 10000) { /* jumbo frames need bulk latency setting */ if (bytes/packets > 8000) retval = bulk_latency; else if ((packets < 10) || ((bytes/packets) > 1200)) retval = bulk_latency; else if ((packets > 35)) retval = lowest_latency; } else if (bytes/packets > 2000) retval = bulk_latency; else if (packets <= 2 && bytes < 512) retval = lowest_latency; break; case bulk_latency: /* 250 usec aka 4000 ints/s */ if (bytes > 25000) { if (packets > 35) retval = low_latency; } else if (bytes < 6000) { retval = low_latency; } break; } update_itr_done: return retval; } static void e1000_set_itr(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u16 current_itr; u32 new_itr = adapter->itr; if (unlikely(hw->mac_type < e1000_82540)) return; /* for non-gigabit speeds, just fix the interrupt rate at 4000 */ if (unlikely(adapter->link_speed != SPEED_1000)) { new_itr = 4000; goto set_itr_now; } adapter->tx_itr = e1000_update_itr(adapter, adapter->tx_itr, adapter->total_tx_packets, adapter->total_tx_bytes); /* conservative mode (itr 3) eliminates the lowest_latency setting */ if (adapter->itr_setting == 3 && adapter->tx_itr == lowest_latency) adapter->tx_itr = low_latency; adapter->rx_itr = e1000_update_itr(adapter, adapter->rx_itr, adapter->total_rx_packets, adapter->total_rx_bytes); /* conservative mode (itr 3) eliminates the lowest_latency setting */ if (adapter->itr_setting == 3 && adapter->rx_itr == lowest_latency) adapter->rx_itr = low_latency; current_itr = max(adapter->rx_itr, adapter->tx_itr); switch (current_itr) { /* counts and packets in update_itr are dependent on these numbers */ case lowest_latency: new_itr = 70000; break; case low_latency: new_itr = 20000; /* aka hwitr = ~200 */ break; case bulk_latency: new_itr = 4000; break; default: break; } set_itr_now: if (new_itr != adapter->itr) { /* this attempts to bias the interrupt rate towards Bulk * by adding intermediate steps when interrupt rate is * increasing */ new_itr = new_itr > adapter->itr ? min(adapter->itr + (new_itr >> 2), new_itr) : new_itr; adapter->itr = new_itr; ew32(ITR, 1000000000 / (new_itr * 256)); } } #define E1000_TX_FLAGS_CSUM 0x00000001 #define E1000_TX_FLAGS_VLAN 0x00000002 #define E1000_TX_FLAGS_TSO 0x00000004 #define E1000_TX_FLAGS_IPV4 0x00000008 #define E1000_TX_FLAGS_NO_FCS 0x00000010 #define E1000_TX_FLAGS_VLAN_MASK 0xffff0000 #define E1000_TX_FLAGS_VLAN_SHIFT 16 static int e1000_tso(struct e1000_adapter *adapter, struct e1000_tx_ring *tx_ring, struct sk_buff *skb, __be16 protocol) { struct e1000_context_desc *context_desc; struct e1000_tx_buffer *buffer_info; unsigned int i; u32 cmd_length = 0; u16 ipcse = 0, tucse, mss; u8 ipcss, ipcso, tucss, tucso, hdr_len; if (skb_is_gso(skb)) { int err; err = skb_cow_head(skb, 0); if (err < 0) return err; hdr_len = skb_tcp_all_headers(skb); mss = skb_shinfo(skb)->gso_size; if (protocol == htons(ETH_P_IP)) { struct iphdr *iph = ip_hdr(skb); iph->tot_len = 0; iph->check = 0; tcp_hdr(skb)->check = ~csum_tcpudp_magic(iph->saddr, iph->daddr, 0, IPPROTO_TCP, 0); cmd_length = E1000_TXD_CMD_IP; ipcse = skb_transport_offset(skb) - 1; } else if (skb_is_gso_v6(skb)) { tcp_v6_gso_csum_prep(skb); ipcse = 0; } ipcss = skb_network_offset(skb); ipcso = (void *)&(ip_hdr(skb)->check) - (void *)skb->data; tucss = skb_transport_offset(skb); tucso = (void *)&(tcp_hdr(skb)->check) - (void *)skb->data; tucse = 0; cmd_length |= (E1000_TXD_CMD_DEXT | E1000_TXD_CMD_TSE | E1000_TXD_CMD_TCP | (skb->len - (hdr_len))); i = tx_ring->next_to_use; context_desc = E1000_CONTEXT_DESC(*tx_ring, i); buffer_info = &tx_ring->buffer_info[i]; context_desc->lower_setup.ip_fields.ipcss = ipcss; context_desc->lower_setup.ip_fields.ipcso = ipcso; context_desc->lower_setup.ip_fields.ipcse = cpu_to_le16(ipcse); context_desc->upper_setup.tcp_fields.tucss = tucss; context_desc->upper_setup.tcp_fields.tucso = tucso; context_desc->upper_setup.tcp_fields.tucse = cpu_to_le16(tucse); context_desc->tcp_seg_setup.fields.mss = cpu_to_le16(mss); context_desc->tcp_seg_setup.fields.hdr_len = hdr_len; context_desc->cmd_and_length = cpu_to_le32(cmd_length); buffer_info->time_stamp = jiffies; buffer_info->next_to_watch = i; if (++i == tx_ring->count) i = 0; tx_ring->next_to_use = i; return true; } return false; } static bool e1000_tx_csum(struct e1000_adapter *adapter, struct e1000_tx_ring *tx_ring, struct sk_buff *skb, __be16 protocol) { struct e1000_context_desc *context_desc; struct e1000_tx_buffer *buffer_info; unsigned int i; u8 css; u32 cmd_len = E1000_TXD_CMD_DEXT; if (skb->ip_summed != CHECKSUM_PARTIAL) return false; switch (protocol) { case cpu_to_be16(ETH_P_IP): if (ip_hdr(skb)->protocol == IPPROTO_TCP) cmd_len |= E1000_TXD_CMD_TCP; break; case cpu_to_be16(ETH_P_IPV6): /* XXX not handling all IPV6 headers */ if (ipv6_hdr(skb)->nexthdr == IPPROTO_TCP) cmd_len |= E1000_TXD_CMD_TCP; break; default: if (unlikely(net_ratelimit())) e_warn(drv, "checksum_partial proto=%x!\n", skb->protocol); break; } css = skb_checksum_start_offset(skb); i = tx_ring->next_to_use; buffer_info = &tx_ring->buffer_info[i]; context_desc = E1000_CONTEXT_DESC(*tx_ring, i); context_desc->lower_setup.ip_config = 0; context_desc->upper_setup.tcp_fields.tucss = css; context_desc->upper_setup.tcp_fields.tucso = css + skb->csum_offset; context_desc->upper_setup.tcp_fields.tucse = 0; context_desc->tcp_seg_setup.data = 0; context_desc->cmd_and_length = cpu_to_le32(cmd_len); buffer_info->time_stamp = jiffies; buffer_info->next_to_watch = i; if (unlikely(++i == tx_ring->count)) i = 0; tx_ring->next_to_use = i; return true; } #define E1000_MAX_TXD_PWR 12 #define E1000_MAX_DATA_PER_TXD (1<<E1000_MAX_TXD_PWR) static int e1000_tx_map(struct e1000_adapter *adapter, struct e1000_tx_ring *tx_ring, struct sk_buff *skb, unsigned int first, unsigned int max_per_txd, unsigned int nr_frags, unsigned int mss) { struct e1000_hw *hw = &adapter->hw; struct pci_dev *pdev = adapter->pdev; struct e1000_tx_buffer *buffer_info; unsigned int len = skb_headlen(skb); unsigned int offset = 0, size, count = 0, i; unsigned int f, bytecount, segs; i = tx_ring->next_to_use; while (len) { buffer_info = &tx_ring->buffer_info[i]; size = min(len, max_per_txd); /* Workaround for Controller erratum -- * descriptor for non-tso packet in a linear SKB that follows a * tso gets written back prematurely before the data is fully * DMA'd to the controller */ if (!skb->data_len && tx_ring->last_tx_tso && !skb_is_gso(skb)) { tx_ring->last_tx_tso = false; size -= 4; } /* Workaround for premature desc write-backs * in TSO mode. Append 4-byte sentinel desc */ if (unlikely(mss && !nr_frags && size == len && size > 8)) size -= 4; /* work-around for errata 10 and it applies * to all controllers in PCI-X mode * The fix is to make sure that the first descriptor of a * packet is smaller than 2048 - 16 - 16 (or 2016) bytes */ if (unlikely((hw->bus_type == e1000_bus_type_pcix) && (size > 2015) && count == 0)) size = 2015; /* Workaround for potential 82544 hang in PCI-X. Avoid * terminating buffers within evenly-aligned dwords. */ if (unlikely(adapter->pcix_82544 && !((unsigned long)(skb->data + offset + size - 1) & 4) && size > 4)) size -= 4; buffer_info->length = size; /* set time_stamp *before* dma to help avoid a possible race */ buffer_info->time_stamp = jiffies; buffer_info->mapped_as_page = false; buffer_info->dma = dma_map_single(&pdev->dev, skb->data + offset, size, DMA_TO_DEVICE); if (dma_mapping_error(&pdev->dev, buffer_info->dma)) goto dma_error; buffer_info->next_to_watch = i; len -= size; offset += size; count++; if (len) { i++; if (unlikely(i == tx_ring->count)) i = 0; } } for (f = 0; f < nr_frags; f++) { const skb_frag_t *frag = &skb_shinfo(skb)->frags[f]; len = skb_frag_size(frag); offset = 0; while (len) { unsigned long bufend; i++; if (unlikely(i == tx_ring->count)) i = 0; buffer_info = &tx_ring->buffer_info[i]; size = min(len, max_per_txd); /* Workaround for premature desc write-backs * in TSO mode. Append 4-byte sentinel desc */ if (unlikely(mss && f == (nr_frags-1) && size == len && size > 8)) size -= 4; /* Workaround for potential 82544 hang in PCI-X. * Avoid terminating buffers within evenly-aligned * dwords. */ bufend = (unsigned long) page_to_phys(skb_frag_page(frag)); bufend += offset + size - 1; if (unlikely(adapter->pcix_82544 && !(bufend & 4) && size > 4)) size -= 4; buffer_info->length = size; buffer_info->time_stamp = jiffies; buffer_info->mapped_as_page = true; buffer_info->dma = skb_frag_dma_map(&pdev->dev, frag, offset, size, DMA_TO_DEVICE); if (dma_mapping_error(&pdev->dev, buffer_info->dma)) goto dma_error; buffer_info->next_to_watch = i; len -= size; offset += size; count++; } } segs = skb_shinfo(skb)->gso_segs ?: 1; /* multiply data chunks by size of headers */ bytecount = ((segs - 1) * skb_headlen(skb)) + skb->len; tx_ring->buffer_info[i].skb = skb; tx_ring->buffer_info[i].segs = segs; tx_ring->buffer_info[i].bytecount = bytecount; tx_ring->buffer_info[first].next_to_watch = i; return count; dma_error: dev_err(&pdev->dev, "TX DMA map failed\n"); buffer_info->dma = 0; if (count) count--; while (count--) { if (i == 0) i += tx_ring->count; i--; buffer_info = &tx_ring->buffer_info[i]; e1000_unmap_and_free_tx_resource(adapter, buffer_info, 0); } return 0; } static void e1000_tx_queue(struct e1000_adapter *adapter, struct e1000_tx_ring *tx_ring, int tx_flags, int count) { struct e1000_tx_desc *tx_desc = NULL; struct e1000_tx_buffer *buffer_info; u32 txd_upper = 0, txd_lower = E1000_TXD_CMD_IFCS; unsigned int i; if (likely(tx_flags & E1000_TX_FLAGS_TSO)) { txd_lower |= E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D | E1000_TXD_CMD_TSE; txd_upper |= E1000_TXD_POPTS_TXSM << 8; if (likely(tx_flags & E1000_TX_FLAGS_IPV4)) txd_upper |= E1000_TXD_POPTS_IXSM << 8; } if (likely(tx_flags & E1000_TX_FLAGS_CSUM)) { txd_lower |= E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D; txd_upper |= E1000_TXD_POPTS_TXSM << 8; } if (unlikely(tx_flags & E1000_TX_FLAGS_VLAN)) { txd_lower |= E1000_TXD_CMD_VLE; txd_upper |= (tx_flags & E1000_TX_FLAGS_VLAN_MASK); } if (unlikely(tx_flags & E1000_TX_FLAGS_NO_FCS)) txd_lower &= ~(E1000_TXD_CMD_IFCS); i = tx_ring->next_to_use; while (count--) { buffer_info = &tx_ring->buffer_info[i]; tx_desc = E1000_TX_DESC(*tx_ring, i); tx_desc->buffer_addr = cpu_to_le64(buffer_info->dma); tx_desc->lower.data = cpu_to_le32(txd_lower | buffer_info->length); tx_desc->upper.data = cpu_to_le32(txd_upper); if (unlikely(++i == tx_ring->count)) i = 0; } tx_desc->lower.data |= cpu_to_le32(adapter->txd_cmd); /* txd_cmd re-enables FCS, so we'll re-disable it here as desired. */ if (unlikely(tx_flags & E1000_TX_FLAGS_NO_FCS)) tx_desc->lower.data &= ~(cpu_to_le32(E1000_TXD_CMD_IFCS)); /* Force memory writes to complete before letting h/w * know there are new descriptors to fetch. (Only * applicable for weak-ordered memory model archs, * such as IA-64). */ dma_wmb(); tx_ring->next_to_use = i; } /* 82547 workaround to avoid controller hang in half-duplex environment. * The workaround is to avoid queuing a large packet that would span * the internal Tx FIFO ring boundary by notifying the stack to resend * the packet at a later time. This gives the Tx FIFO an opportunity to * flush all packets. When that occurs, we reset the Tx FIFO pointers * to the beginning of the Tx FIFO. */ #define E1000_FIFO_HDR 0x10 #define E1000_82547_PAD_LEN 0x3E0 static int e1000_82547_fifo_workaround(struct e1000_adapter *adapter, struct sk_buff *skb) { u32 fifo_space = adapter->tx_fifo_size - adapter->tx_fifo_head; u32 skb_fifo_len = skb->len + E1000_FIFO_HDR; skb_fifo_len = ALIGN(skb_fifo_len, E1000_FIFO_HDR); if (adapter->link_duplex != HALF_DUPLEX) goto no_fifo_stall_required; if (atomic_read(&adapter->tx_fifo_stall)) return 1; if (skb_fifo_len >= (E1000_82547_PAD_LEN + fifo_space)) { atomic_set(&adapter->tx_fifo_stall, 1); return 1; } no_fifo_stall_required: adapter->tx_fifo_head += skb_fifo_len; if (adapter->tx_fifo_head >= adapter->tx_fifo_size) adapter->tx_fifo_head -= adapter->tx_fifo_size; return 0; } static int __e1000_maybe_stop_tx(struct net_device *netdev, int size) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_tx_ring *tx_ring = adapter->tx_ring; netif_stop_queue(netdev); /* Herbert's original patch had: * smp_mb__after_netif_stop_queue(); * but since that doesn't exist yet, just open code it. */ smp_mb(); /* We need to check again in a case another CPU has just * made room available. */ if (likely(E1000_DESC_UNUSED(tx_ring) < size)) return -EBUSY; /* A reprieve! */ netif_start_queue(netdev); ++adapter->restart_queue; return 0; } static int e1000_maybe_stop_tx(struct net_device *netdev, struct e1000_tx_ring *tx_ring, int size) { if (likely(E1000_DESC_UNUSED(tx_ring) >= size)) return 0; return __e1000_maybe_stop_tx(netdev, size); } #define TXD_USE_COUNT(S, X) (((S) + ((1 << (X)) - 1)) >> (X)) static netdev_tx_t e1000_xmit_frame(struct sk_buff *skb, struct net_device *netdev) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; struct e1000_tx_ring *tx_ring; unsigned int first, max_per_txd = E1000_MAX_DATA_PER_TXD; unsigned int max_txd_pwr = E1000_MAX_TXD_PWR; unsigned int tx_flags = 0; unsigned int len = skb_headlen(skb); unsigned int nr_frags; unsigned int mss; int count = 0; int tso; unsigned int f; __be16 protocol = vlan_get_protocol(skb); /* This goes back to the question of how to logically map a Tx queue * to a flow. Right now, performance is impacted slightly negatively * if using multiple Tx queues. If the stack breaks away from a * single qdisc implementation, we can look at this again. */ tx_ring = adapter->tx_ring; /* On PCI/PCI-X HW, if packet size is less than ETH_ZLEN, * packets may get corrupted during padding by HW. * To WA this issue, pad all small packets manually. */ if (eth_skb_pad(skb)) return NETDEV_TX_OK; mss = skb_shinfo(skb)->gso_size; /* The controller does a simple calculation to * make sure there is enough room in the FIFO before * initiating the DMA for each buffer. The calc is: * 4 = ceil(buffer len/mss). To make sure we don't * overrun the FIFO, adjust the max buffer len if mss * drops. */ if (mss) { u8 hdr_len; max_per_txd = min(mss << 2, max_per_txd); max_txd_pwr = fls(max_per_txd) - 1; hdr_len = skb_tcp_all_headers(skb); if (skb->data_len && hdr_len == len) { switch (hw->mac_type) { case e1000_82544: { unsigned int pull_size; /* Make sure we have room to chop off 4 bytes, * and that the end alignment will work out to * this hardware's requirements * NOTE: this is a TSO only workaround * if end byte alignment not correct move us * into the next dword */ if ((unsigned long)(skb_tail_pointer(skb) - 1) & 4) break; pull_size = min((unsigned int)4, skb->data_len); if (!__pskb_pull_tail(skb, pull_size)) { e_err(drv, "__pskb_pull_tail " "failed.\n"); dev_kfree_skb_any(skb); return NETDEV_TX_OK; } len = skb_headlen(skb); break; } default: /* do nothing */ break; } } } /* reserve a descriptor for the offload context */ if ((mss) || (skb->ip_summed == CHECKSUM_PARTIAL)) count++; count++; /* Controller Erratum workaround */ if (!skb->data_len && tx_ring->last_tx_tso && !skb_is_gso(skb)) count++; count += TXD_USE_COUNT(len, max_txd_pwr); if (adapter->pcix_82544) count++; /* work-around for errata 10 and it applies to all controllers * in PCI-X mode, so add one more descriptor to the count */ if (unlikely((hw->bus_type == e1000_bus_type_pcix) && (len > 2015))) count++; nr_frags = skb_shinfo(skb)->nr_frags; for (f = 0; f < nr_frags; f++) count += TXD_USE_COUNT(skb_frag_size(&skb_shinfo(skb)->frags[f]), max_txd_pwr); if (adapter->pcix_82544) count += nr_frags; /* need: count + 2 desc gap to keep tail from touching * head, otherwise try next time */ if (unlikely(e1000_maybe_stop_tx(netdev, tx_ring, count + 2))) return NETDEV_TX_BUSY; if (unlikely((hw->mac_type == e1000_82547) && (e1000_82547_fifo_workaround(adapter, skb)))) { netif_stop_queue(netdev); if (!test_bit(__E1000_DOWN, &adapter->flags)) schedule_delayed_work(&adapter->fifo_stall_task, 1); return NETDEV_TX_BUSY; } if (skb_vlan_tag_present(skb)) { tx_flags |= E1000_TX_FLAGS_VLAN; tx_flags |= (skb_vlan_tag_get(skb) << E1000_TX_FLAGS_VLAN_SHIFT); } first = tx_ring->next_to_use; tso = e1000_tso(adapter, tx_ring, skb, protocol); if (tso < 0) { dev_kfree_skb_any(skb); return NETDEV_TX_OK; } if (likely(tso)) { if (likely(hw->mac_type != e1000_82544)) tx_ring->last_tx_tso = true; tx_flags |= E1000_TX_FLAGS_TSO; } else if (likely(e1000_tx_csum(adapter, tx_ring, skb, protocol))) tx_flags |= E1000_TX_FLAGS_CSUM; if (protocol == htons(ETH_P_IP)) tx_flags |= E1000_TX_FLAGS_IPV4; if (unlikely(skb->no_fcs)) tx_flags |= E1000_TX_FLAGS_NO_FCS; count = e1000_tx_map(adapter, tx_ring, skb, first, max_per_txd, nr_frags, mss); if (count) { /* The descriptors needed is higher than other Intel drivers * due to a number of workarounds. The breakdown is below: * Data descriptors: MAX_SKB_FRAGS + 1 * Context Descriptor: 1 * Keep head from touching tail: 2 * Workarounds: 3 */ int desc_needed = MAX_SKB_FRAGS + 7; netdev_sent_queue(netdev, skb->len); skb_tx_timestamp(skb); e1000_tx_queue(adapter, tx_ring, tx_flags, count); /* 82544 potentially requires twice as many data descriptors * in order to guarantee buffers don't end on evenly-aligned * dwords */ if (adapter->pcix_82544) desc_needed += MAX_SKB_FRAGS + 1; /* Make sure there is space in the ring for the next send. */ e1000_maybe_stop_tx(netdev, tx_ring, desc_needed); if (!netdev_xmit_more() || netif_xmit_stopped(netdev_get_tx_queue(netdev, 0))) { writel(tx_ring->next_to_use, hw->hw_addr + tx_ring->tdt); } } else { dev_kfree_skb_any(skb); tx_ring->buffer_info[first].time_stamp = 0; tx_ring->next_to_use = first; } return NETDEV_TX_OK; } #define NUM_REGS 38 /* 1 based count */ static void e1000_regdump(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 regs[NUM_REGS]; u32 *regs_buff = regs; int i = 0; static const char * const reg_name[] = { "CTRL", "STATUS", "RCTL", "RDLEN", "RDH", "RDT", "RDTR", "TCTL", "TDBAL", "TDBAH", "TDLEN", "TDH", "TDT", "TIDV", "TXDCTL", "TADV", "TARC0", "TDBAL1", "TDBAH1", "TDLEN1", "TDH1", "TDT1", "TXDCTL1", "TARC1", "CTRL_EXT", "ERT", "RDBAL", "RDBAH", "TDFH", "TDFT", "TDFHS", "TDFTS", "TDFPC", "RDFH", "RDFT", "RDFHS", "RDFTS", "RDFPC" }; regs_buff[0] = er32(CTRL); regs_buff[1] = er32(STATUS); regs_buff[2] = er32(RCTL); regs_buff[3] = er32(RDLEN); regs_buff[4] = er32(RDH); regs_buff[5] = er32(RDT); regs_buff[6] = er32(RDTR); regs_buff[7] = er32(TCTL); regs_buff[8] = er32(TDBAL); regs_buff[9] = er32(TDBAH); regs_buff[10] = er32(TDLEN); regs_buff[11] = er32(TDH); regs_buff[12] = er32(TDT); regs_buff[13] = er32(TIDV); regs_buff[14] = er32(TXDCTL); regs_buff[15] = er32(TADV); regs_buff[16] = er32(TARC0); regs_buff[17] = er32(TDBAL1); regs_buff[18] = er32(TDBAH1); regs_buff[19] = er32(TDLEN1); regs_buff[20] = er32(TDH1); regs_buff[21] = er32(TDT1); regs_buff[22] = er32(TXDCTL1); regs_buff[23] = er32(TARC1); regs_buff[24] = er32(CTRL_EXT); regs_buff[25] = er32(ERT); regs_buff[26] = er32(RDBAL0); regs_buff[27] = er32(RDBAH0); regs_buff[28] = er32(TDFH); regs_buff[29] = er32(TDFT); regs_buff[30] = er32(TDFHS); regs_buff[31] = er32(TDFTS); regs_buff[32] = er32(TDFPC); regs_buff[33] = er32(RDFH); regs_buff[34] = er32(RDFT); regs_buff[35] = er32(RDFHS); regs_buff[36] = er32(RDFTS); regs_buff[37] = er32(RDFPC); pr_info("Register dump\n"); for (i = 0; i < NUM_REGS; i++) pr_info("%-15s %08x\n", reg_name[i], regs_buff[i]); } /* * e1000_dump: Print registers, tx ring and rx ring */ static void e1000_dump(struct e1000_adapter *adapter) { /* this code doesn't handle multiple rings */ struct e1000_tx_ring *tx_ring = adapter->tx_ring; struct e1000_rx_ring *rx_ring = adapter->rx_ring; int i; if (!netif_msg_hw(adapter)) return; /* Print Registers */ e1000_regdump(adapter); /* transmit dump */ pr_info("TX Desc ring0 dump\n"); /* Transmit Descriptor Formats - DEXT[29] is 0 (Legacy) or 1 (Extended) * * Legacy Transmit Descriptor * +--------------------------------------------------------------+ * 0 | Buffer Address [63:0] (Reserved on Write Back) | * +--------------------------------------------------------------+ * 8 | Special | CSS | Status | CMD | CSO | Length | * +--------------------------------------------------------------+ * 63 48 47 36 35 32 31 24 23 16 15 0 * * Extended Context Descriptor (DTYP=0x0) for TSO or checksum offload * 63 48 47 40 39 32 31 16 15 8 7 0 * +----------------------------------------------------------------+ * 0 | TUCSE | TUCS0 | TUCSS | IPCSE | IPCS0 | IPCSS | * +----------------------------------------------------------------+ * 8 | MSS | HDRLEN | RSV | STA | TUCMD | DTYP | PAYLEN | * +----------------------------------------------------------------+ * 63 48 47 40 39 36 35 32 31 24 23 20 19 0 * * Extended Data Descriptor (DTYP=0x1) * +----------------------------------------------------------------+ * 0 | Buffer Address [63:0] | * +----------------------------------------------------------------+ * 8 | VLAN tag | POPTS | Rsvd | Status | Command | DTYP | DTALEN | * +----------------------------------------------------------------+ * 63 48 47 40 39 36 35 32 31 24 23 20 19 0 */ pr_info("Tc[desc] [Ce CoCsIpceCoS] [MssHlRSCm0Plen] [bi->dma ] leng ntw timestmp bi->skb\n"); pr_info("Td[desc] [address 63:0 ] [VlaPoRSCm1Dlen] [bi->dma ] leng ntw timestmp bi->skb\n"); if (!netif_msg_tx_done(adapter)) goto rx_ring_summary; for (i = 0; tx_ring->desc && (i < tx_ring->count); i++) { struct e1000_tx_desc *tx_desc = E1000_TX_DESC(*tx_ring, i); struct e1000_tx_buffer *buffer_info = &tx_ring->buffer_info[i]; struct my_u { __le64 a; __le64 b; }; struct my_u *u = (struct my_u *)tx_desc; const char *type; if (i == tx_ring->next_to_use && i == tx_ring->next_to_clean) type = "NTC/U"; else if (i == tx_ring->next_to_use) type = "NTU"; else if (i == tx_ring->next_to_clean) type = "NTC"; else type = ""; pr_info("T%c[0x%03X] %016llX %016llX %016llX %04X %3X %016llX %p %s\n", ((le64_to_cpu(u->b) & (1<<20)) ? 'd' : 'c'), i, le64_to_cpu(u->a), le64_to_cpu(u->b), (u64)buffer_info->dma, buffer_info->length, buffer_info->next_to_watch, (u64)buffer_info->time_stamp, buffer_info->skb, type); } rx_ring_summary: /* receive dump */ pr_info("\nRX Desc ring dump\n"); /* Legacy Receive Descriptor Format * * +-----------------------------------------------------+ * | Buffer Address [63:0] | * +-----------------------------------------------------+ * | VLAN Tag | Errors | Status 0 | Packet csum | Length | * +-----------------------------------------------------+ * 63 48 47 40 39 32 31 16 15 0 */ pr_info("R[desc] [address 63:0 ] [vl er S cks ln] [bi->dma ] [bi->skb]\n"); if (!netif_msg_rx_status(adapter)) goto exit; for (i = 0; rx_ring->desc && (i < rx_ring->count); i++) { struct e1000_rx_desc *rx_desc = E1000_RX_DESC(*rx_ring, i); struct e1000_rx_buffer *buffer_info = &rx_ring->buffer_info[i]; struct my_u { __le64 a; __le64 b; }; struct my_u *u = (struct my_u *)rx_desc; const char *type; if (i == rx_ring->next_to_use) type = "NTU"; else if (i == rx_ring->next_to_clean) type = "NTC"; else type = ""; pr_info("R[0x%03X] %016llX %016llX %016llX %p %s\n", i, le64_to_cpu(u->a), le64_to_cpu(u->b), (u64)buffer_info->dma, buffer_info->rxbuf.data, type); } /* for */ /* dump the descriptor caches */ /* rx */ pr_info("Rx descriptor cache in 64bit format\n"); for (i = 0x6000; i <= 0x63FF ; i += 0x10) { pr_info("R%04X: %08X|%08X %08X|%08X\n", i, readl(adapter->hw.hw_addr + i+4), readl(adapter->hw.hw_addr + i), readl(adapter->hw.hw_addr + i+12), readl(adapter->hw.hw_addr + i+8)); } /* tx */ pr_info("Tx descriptor cache in 64bit format\n"); for (i = 0x7000; i <= 0x73FF ; i += 0x10) { pr_info("T%04X: %08X|%08X %08X|%08X\n", i, readl(adapter->hw.hw_addr + i+4), readl(adapter->hw.hw_addr + i), readl(adapter->hw.hw_addr + i+12), readl(adapter->hw.hw_addr + i+8)); } exit: return; } /** * e1000_tx_timeout - Respond to a Tx Hang * @netdev: network interface device structure * @txqueue: number of the Tx queue that hung (unused) **/ static void e1000_tx_timeout(struct net_device *netdev, unsigned int __always_unused txqueue) { struct e1000_adapter *adapter = netdev_priv(netdev); /* Do the reset outside of interrupt context */ adapter->tx_timeout_count++; schedule_work(&adapter->reset_task); } static void e1000_reset_task(struct work_struct *work) { struct e1000_adapter *adapter = container_of(work, struct e1000_adapter, reset_task); e_err(drv, "Reset adapter\n"); e1000_reinit_locked(adapter); } /** * e1000_change_mtu - Change the Maximum Transfer Unit * @netdev: network interface device structure * @new_mtu: new value for maximum frame size * * Returns 0 on success, negative on failure **/ static int e1000_change_mtu(struct net_device *netdev, int new_mtu) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; int max_frame = new_mtu + ETH_HLEN + ETH_FCS_LEN; /* Adapter-specific max frame size limits. */ switch (hw->mac_type) { case e1000_undefined ... e1000_82542_rev2_1: if (max_frame > (ETH_FRAME_LEN + ETH_FCS_LEN)) { e_err(probe, "Jumbo Frames not supported.\n"); return -EINVAL; } break; default: /* Capable of supporting up to MAX_JUMBO_FRAME_SIZE limit. */ break; } while (test_and_set_bit(__E1000_RESETTING, &adapter->flags)) msleep(1); /* e1000_down has a dependency on max_frame_size */ hw->max_frame_size = max_frame; if (netif_running(netdev)) { /* prevent buffers from being reallocated */ adapter->alloc_rx_buf = e1000_alloc_dummy_rx_buffers; e1000_down(adapter); } /* NOTE: netdev_alloc_skb reserves 16 bytes, and typically NET_IP_ALIGN * means we reserve 2 more, this pushes us to allocate from the next * larger slab size. * i.e. RXBUFFER_2048 --> size-4096 slab * however with the new *_jumbo_rx* routines, jumbo receives will use * fragmented skbs */ if (max_frame <= E1000_RXBUFFER_2048) adapter->rx_buffer_len = E1000_RXBUFFER_2048; else #if (PAGE_SIZE >= E1000_RXBUFFER_16384) adapter->rx_buffer_len = E1000_RXBUFFER_16384; #elif (PAGE_SIZE >= E1000_RXBUFFER_4096) adapter->rx_buffer_len = PAGE_SIZE; #endif /* adjust allocation if LPE protects us, and we aren't using SBP */ if (!hw->tbi_compatibility_on && ((max_frame == (ETH_FRAME_LEN + ETH_FCS_LEN)) || (max_frame == MAXIMUM_ETHERNET_VLAN_SIZE))) adapter->rx_buffer_len = MAXIMUM_ETHERNET_VLAN_SIZE; netdev_dbg(netdev, "changing MTU from %d to %d\n", netdev->mtu, new_mtu); netdev->mtu = new_mtu; if (netif_running(netdev)) e1000_up(adapter); else e1000_reset(adapter); clear_bit(__E1000_RESETTING, &adapter->flags); return 0; } /** * e1000_update_stats - Update the board statistics counters * @adapter: board private structure **/ void e1000_update_stats(struct e1000_adapter *adapter) { struct net_device *netdev = adapter->netdev; struct e1000_hw *hw = &adapter->hw; struct pci_dev *pdev = adapter->pdev; unsigned long flags; u16 phy_tmp; #define PHY_IDLE_ERROR_COUNT_MASK 0x00FF /* Prevent stats update while adapter is being reset, or if the pci * connection is down. */ if (adapter->link_speed == 0) return; if (pci_channel_offline(pdev)) return; spin_lock_irqsave(&adapter->stats_lock, flags); /* these counters are modified from e1000_tbi_adjust_stats, * called from the interrupt context, so they must only * be written while holding adapter->stats_lock */ adapter->stats.crcerrs += er32(CRCERRS); adapter->stats.gprc += er32(GPRC); adapter->stats.gorcl += er32(GORCL); adapter->stats.gorch += er32(GORCH); adapter->stats.bprc += er32(BPRC); adapter->stats.mprc += er32(MPRC); adapter->stats.roc += er32(ROC); adapter->stats.prc64 += er32(PRC64); adapter->stats.prc127 += er32(PRC127); adapter->stats.prc255 += er32(PRC255); adapter->stats.prc511 += er32(PRC511); adapter->stats.prc1023 += er32(PRC1023); adapter->stats.prc1522 += er32(PRC1522); adapter->stats.symerrs += er32(SYMERRS); adapter->stats.mpc += er32(MPC); adapter->stats.scc += er32(SCC); adapter->stats.ecol += er32(ECOL); adapter->stats.mcc += er32(MCC); adapter->stats.latecol += er32(LATECOL); adapter->stats.dc += er32(DC); adapter->stats.sec += er32(SEC); adapter->stats.rlec += er32(RLEC); adapter->stats.xonrxc += er32(XONRXC); adapter->stats.xontxc += er32(XONTXC); adapter->stats.xoffrxc += er32(XOFFRXC); adapter->stats.xofftxc += er32(XOFFTXC); adapter->stats.fcruc += er32(FCRUC); adapter->stats.gptc += er32(GPTC); adapter->stats.gotcl += er32(GOTCL); adapter->stats.gotch += er32(GOTCH); adapter->stats.rnbc += er32(RNBC); adapter->stats.ruc += er32(RUC); adapter->stats.rfc += er32(RFC); adapter->stats.rjc += er32(RJC); adapter->stats.torl += er32(TORL); adapter->stats.torh += er32(TORH); adapter->stats.totl += er32(TOTL); adapter->stats.toth += er32(TOTH); adapter->stats.tpr += er32(TPR); adapter->stats.ptc64 += er32(PTC64); adapter->stats.ptc127 += er32(PTC127); adapter->stats.ptc255 += er32(PTC255); adapter->stats.ptc511 += er32(PTC511); adapter->stats.ptc1023 += er32(PTC1023); adapter->stats.ptc1522 += er32(PTC1522); adapter->stats.mptc += er32(MPTC); adapter->stats.bptc += er32(BPTC); /* used for adaptive IFS */ hw->tx_packet_delta = er32(TPT); adapter->stats.tpt += hw->tx_packet_delta; hw->collision_delta = er32(COLC); adapter->stats.colc += hw->collision_delta; if (hw->mac_type >= e1000_82543) { adapter->stats.algnerrc += er32(ALGNERRC); adapter->stats.rxerrc += er32(RXERRC); adapter->stats.tncrs += er32(TNCRS); adapter->stats.cexterr += er32(CEXTERR); adapter->stats.tsctc += er32(TSCTC); adapter->stats.tsctfc += er32(TSCTFC); } /* Fill out the OS statistics structure */ netdev->stats.multicast = adapter->stats.mprc; netdev->stats.collisions = adapter->stats.colc; /* Rx Errors */ /* RLEC on some newer hardware can be incorrect so build * our own version based on RUC and ROC */ netdev->stats.rx_errors = adapter->stats.rxerrc + adapter->stats.crcerrs + adapter->stats.algnerrc + adapter->stats.ruc + adapter->stats.roc + adapter->stats.cexterr; adapter->stats.rlerrc = adapter->stats.ruc + adapter->stats.roc; netdev->stats.rx_length_errors = adapter->stats.rlerrc; netdev->stats.rx_crc_errors = adapter->stats.crcerrs; netdev->stats.rx_frame_errors = adapter->stats.algnerrc; netdev->stats.rx_missed_errors = adapter->stats.mpc; /* Tx Errors */ adapter->stats.txerrc = adapter->stats.ecol + adapter->stats.latecol; netdev->stats.tx_errors = adapter->stats.txerrc; netdev->stats.tx_aborted_errors = adapter->stats.ecol; netdev->stats.tx_window_errors = adapter->stats.latecol; netdev->stats.tx_carrier_errors = adapter->stats.tncrs; if (hw->bad_tx_carr_stats_fd && adapter->link_duplex == FULL_DUPLEX) { netdev->stats.tx_carrier_errors = 0; adapter->stats.tncrs = 0; } /* Tx Dropped needs to be maintained elsewhere */ /* Phy Stats */ if (hw->media_type == e1000_media_type_copper) { if ((adapter->link_speed == SPEED_1000) && (!e1000_read_phy_reg(hw, PHY_1000T_STATUS, &phy_tmp))) { phy_tmp &= PHY_IDLE_ERROR_COUNT_MASK; adapter->phy_stats.idle_errors += phy_tmp; } if ((hw->mac_type <= e1000_82546) && (hw->phy_type == e1000_phy_m88) && !e1000_read_phy_reg(hw, M88E1000_RX_ERR_CNTR, &phy_tmp)) adapter->phy_stats.receive_errors += phy_tmp; } /* Management Stats */ if (hw->has_smbus) { adapter->stats.mgptc += er32(MGTPTC); adapter->stats.mgprc += er32(MGTPRC); adapter->stats.mgpdc += er32(MGTPDC); } spin_unlock_irqrestore(&adapter->stats_lock, flags); } /** * e1000_intr - Interrupt Handler * @irq: interrupt number * @data: pointer to a network interface device structure **/ static irqreturn_t e1000_intr(int irq, void *data) { struct net_device *netdev = data; struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u32 icr = er32(ICR); if (unlikely((!icr))) return IRQ_NONE; /* Not our interrupt */ /* we might have caused the interrupt, but the above * read cleared it, and just in case the driver is * down there is nothing to do so return handled */ if (unlikely(test_bit(__E1000_DOWN, &adapter->flags))) return IRQ_HANDLED; if (unlikely(icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC))) { hw->get_link_status = 1; /* guard against interrupt when we're going down */ if (!test_bit(__E1000_DOWN, &adapter->flags)) schedule_delayed_work(&adapter->watchdog_task, 1); } /* disable interrupts, without the synchronize_irq bit */ ew32(IMC, ~0); E1000_WRITE_FLUSH(); if (likely(napi_schedule_prep(&adapter->napi))) { adapter->total_tx_bytes = 0; adapter->total_tx_packets = 0; adapter->total_rx_bytes = 0; adapter->total_rx_packets = 0; __napi_schedule(&adapter->napi); } else { /* this really should not happen! if it does it is basically a * bug, but not a hard error, so enable ints and continue */ if (!test_bit(__E1000_DOWN, &adapter->flags)) e1000_irq_enable(adapter); } return IRQ_HANDLED; } /** * e1000_clean - NAPI Rx polling callback * @napi: napi struct containing references to driver info * @budget: budget given to driver for receive packets **/ static int e1000_clean(struct napi_struct *napi, int budget) { struct e1000_adapter *adapter = container_of(napi, struct e1000_adapter, napi); int tx_clean_complete = 0, work_done = 0; tx_clean_complete = e1000_clean_tx_irq(adapter, &adapter->tx_ring[0]); adapter->clean_rx(adapter, &adapter->rx_ring[0], &work_done, budget); if (!tx_clean_complete || work_done == budget) return budget; /* Exit the polling mode, but don't re-enable interrupts if stack might * poll us due to busy-polling */ if (likely(napi_complete_done(napi, work_done))) { if (likely(adapter->itr_setting & 3)) e1000_set_itr(adapter); if (!test_bit(__E1000_DOWN, &adapter->flags)) e1000_irq_enable(adapter); } return work_done; } /** * e1000_clean_tx_irq - Reclaim resources after transmit completes * @adapter: board private structure * @tx_ring: ring to clean **/ static bool e1000_clean_tx_irq(struct e1000_adapter *adapter, struct e1000_tx_ring *tx_ring) { struct e1000_hw *hw = &adapter->hw; struct net_device *netdev = adapter->netdev; struct e1000_tx_desc *tx_desc, *eop_desc; struct e1000_tx_buffer *buffer_info; unsigned int i, eop; unsigned int count = 0; unsigned int total_tx_bytes = 0, total_tx_packets = 0; unsigned int bytes_compl = 0, pkts_compl = 0; i = tx_ring->next_to_clean; eop = tx_ring->buffer_info[i].next_to_watch; eop_desc = E1000_TX_DESC(*tx_ring, eop); while ((eop_desc->upper.data & cpu_to_le32(E1000_TXD_STAT_DD)) && (count < tx_ring->count)) { bool cleaned = false; dma_rmb(); /* read buffer_info after eop_desc */ for ( ; !cleaned; count++) { tx_desc = E1000_TX_DESC(*tx_ring, i); buffer_info = &tx_ring->buffer_info[i]; cleaned = (i == eop); if (cleaned) { total_tx_packets += buffer_info->segs; total_tx_bytes += buffer_info->bytecount; if (buffer_info->skb) { bytes_compl += buffer_info->skb->len; pkts_compl++; } } e1000_unmap_and_free_tx_resource(adapter, buffer_info, 64); tx_desc->upper.data = 0; if (unlikely(++i == tx_ring->count)) i = 0; } eop = tx_ring->buffer_info[i].next_to_watch; eop_desc = E1000_TX_DESC(*tx_ring, eop); } /* Synchronize with E1000_DESC_UNUSED called from e1000_xmit_frame, * which will reuse the cleaned buffers. */ smp_store_release(&tx_ring->next_to_clean, i); netdev_completed_queue(netdev, pkts_compl, bytes_compl); #define TX_WAKE_THRESHOLD 32 if (unlikely(count && netif_carrier_ok(netdev) && E1000_DESC_UNUSED(tx_ring) >= TX_WAKE_THRESHOLD)) { /* Make sure that anybody stopping the queue after this * sees the new next_to_clean. */ smp_mb(); if (netif_queue_stopped(netdev) && !(test_bit(__E1000_DOWN, &adapter->flags))) { netif_wake_queue(netdev); ++adapter->restart_queue; } } if (adapter->detect_tx_hung) { /* Detect a transmit hang in hardware, this serializes the * check with the clearing of time_stamp and movement of i */ adapter->detect_tx_hung = false; if (tx_ring->buffer_info[eop].time_stamp && time_after(jiffies, tx_ring->buffer_info[eop].time_stamp + (adapter->tx_timeout_factor * HZ)) && !(er32(STATUS) & E1000_STATUS_TXOFF)) { /* detected Tx unit hang */ e_err(drv, "Detected Tx Unit Hang\n" " Tx Queue <%lu>\n" " TDH <%x>\n" " TDT <%x>\n" " next_to_use <%x>\n" " next_to_clean <%x>\n" "buffer_info[next_to_clean]\n" " time_stamp <%lx>\n" " next_to_watch <%x>\n" " jiffies <%lx>\n" " next_to_watch.status <%x>\n", (unsigned long)(tx_ring - adapter->tx_ring), readl(hw->hw_addr + tx_ring->tdh), readl(hw->hw_addr + tx_ring->tdt), tx_ring->next_to_use, tx_ring->next_to_clean, tx_ring->buffer_info[eop].time_stamp, eop, jiffies, eop_desc->upper.fields.status); e1000_dump(adapter); netif_stop_queue(netdev); } } adapter->total_tx_bytes += total_tx_bytes; adapter->total_tx_packets += total_tx_packets; netdev->stats.tx_bytes += total_tx_bytes; netdev->stats.tx_packets += total_tx_packets; return count < tx_ring->count; } /** * e1000_rx_checksum - Receive Checksum Offload for 82543 * @adapter: board private structure * @status_err: receive descriptor status and error fields * @csum: receive descriptor csum field * @skb: socket buffer with received data **/ static void e1000_rx_checksum(struct e1000_adapter *adapter, u32 status_err, u32 csum, struct sk_buff *skb) { struct e1000_hw *hw = &adapter->hw; u16 status = (u16)status_err; u8 errors = (u8)(status_err >> 24); skb_checksum_none_assert(skb); /* 82543 or newer only */ if (unlikely(hw->mac_type < e1000_82543)) return; /* Ignore Checksum bit is set */ if (unlikely(status & E1000_RXD_STAT_IXSM)) return; /* TCP/UDP checksum error bit is set */ if (unlikely(errors & E1000_RXD_ERR_TCPE)) { /* let the stack verify checksum errors */ adapter->hw_csum_err++; return; } /* TCP/UDP Checksum has not been calculated */ if (!(status & E1000_RXD_STAT_TCPCS)) return; /* It must be a TCP or UDP packet with a valid checksum */ if (likely(status & E1000_RXD_STAT_TCPCS)) { /* TCP checksum is good */ skb->ip_summed = CHECKSUM_UNNECESSARY; } adapter->hw_csum_good++; } /** * e1000_consume_page - helper function for jumbo Rx path * @bi: software descriptor shadow data * @skb: skb being modified * @length: length of data being added **/ static void e1000_consume_page(struct e1000_rx_buffer *bi, struct sk_buff *skb, u16 length) { bi->rxbuf.page = NULL; skb->len += length; skb->data_len += length; skb->truesize += PAGE_SIZE; } /** * e1000_receive_skb - helper function to handle rx indications * @adapter: board private structure * @status: descriptor status field as written by hardware * @vlan: descriptor vlan field as written by hardware (no le/be conversion) * @skb: pointer to sk_buff to be indicated to stack */ static void e1000_receive_skb(struct e1000_adapter *adapter, u8 status, __le16 vlan, struct sk_buff *skb) { skb->protocol = eth_type_trans(skb, adapter->netdev); if (status & E1000_RXD_STAT_VP) { u16 vid = le16_to_cpu(vlan) & E1000_RXD_SPC_VLAN_MASK; __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vid); } napi_gro_receive(&adapter->napi, skb); } /** * e1000_tbi_adjust_stats * @hw: Struct containing variables accessed by shared code * @stats: point to stats struct * @frame_len: The length of the frame in question * @mac_addr: The Ethernet destination address of the frame in question * * Adjusts the statistic counters when a frame is accepted by TBI_ACCEPT */ static void e1000_tbi_adjust_stats(struct e1000_hw *hw, struct e1000_hw_stats *stats, u32 frame_len, const u8 *mac_addr) { u64 carry_bit; /* First adjust the frame length. */ frame_len--; /* We need to adjust the statistics counters, since the hardware * counters overcount this packet as a CRC error and undercount * the packet as a good packet */ /* This packet should not be counted as a CRC error. */ stats->crcerrs--; /* This packet does count as a Good Packet Received. */ stats->gprc++; /* Adjust the Good Octets received counters */ carry_bit = 0x80000000 & stats->gorcl; stats->gorcl += frame_len; /* If the high bit of Gorcl (the low 32 bits of the Good Octets * Received Count) was one before the addition, * AND it is zero after, then we lost the carry out, * need to add one to Gorch (Good Octets Received Count High). * This could be simplified if all environments supported * 64-bit integers. */ if (carry_bit && ((stats->gorcl & 0x80000000) == 0)) stats->gorch++; /* Is this a broadcast or multicast? Check broadcast first, * since the test for a multicast frame will test positive on * a broadcast frame. */ if (is_broadcast_ether_addr(mac_addr)) stats->bprc++; else if (is_multicast_ether_addr(mac_addr)) stats->mprc++; if (frame_len == hw->max_frame_size) { /* In this case, the hardware has overcounted the number of * oversize frames. */ if (stats->roc > 0) stats->roc--; } /* Adjust the bin counters when the extra byte put the frame in the * wrong bin. Remember that the frame_len was adjusted above. */ if (frame_len == 64) { stats->prc64++; stats->prc127--; } else if (frame_len == 127) { stats->prc127++; stats->prc255--; } else if (frame_len == 255) { stats->prc255++; stats->prc511--; } else if (frame_len == 511) { stats->prc511++; stats->prc1023--; } else if (frame_len == 1023) { stats->prc1023++; stats->prc1522--; } else if (frame_len == 1522) { stats->prc1522++; } } static bool e1000_tbi_should_accept(struct e1000_adapter *adapter, u8 status, u8 errors, u32 length, const u8 *data) { struct e1000_hw *hw = &adapter->hw; u8 last_byte = *(data + length - 1); if (TBI_ACCEPT(hw, status, errors, length, last_byte)) { unsigned long irq_flags; spin_lock_irqsave(&adapter->stats_lock, irq_flags); e1000_tbi_adjust_stats(hw, &adapter->stats, length, data); spin_unlock_irqrestore(&adapter->stats_lock, irq_flags); return true; } return false; } static struct sk_buff *e1000_alloc_rx_skb(struct e1000_adapter *adapter, unsigned int bufsz) { struct sk_buff *skb = napi_alloc_skb(&adapter->napi, bufsz); if (unlikely(!skb)) adapter->alloc_rx_buff_failed++; return skb; } /** * e1000_clean_jumbo_rx_irq - Send received data up the network stack; legacy * @adapter: board private structure * @rx_ring: ring to clean * @work_done: amount of napi work completed this call * @work_to_do: max amount of work allowed for this call to do * * the return value indicates whether actual cleaning was done, there * is no guarantee that everything was cleaned */ static bool e1000_clean_jumbo_rx_irq(struct e1000_adapter *adapter, struct e1000_rx_ring *rx_ring, int *work_done, int work_to_do) { struct net_device *netdev = adapter->netdev; struct pci_dev *pdev = adapter->pdev; struct e1000_rx_desc *rx_desc, *next_rxd; struct e1000_rx_buffer *buffer_info, *next_buffer; u32 length; unsigned int i; int cleaned_count = 0; bool cleaned = false; unsigned int total_rx_bytes = 0, total_rx_packets = 0; i = rx_ring->next_to_clean; rx_desc = E1000_RX_DESC(*rx_ring, i); buffer_info = &rx_ring->buffer_info[i]; while (rx_desc->status & E1000_RXD_STAT_DD) { struct sk_buff *skb; u8 status; if (*work_done >= work_to_do) break; (*work_done)++; dma_rmb(); /* read descriptor and rx_buffer_info after status DD */ status = rx_desc->status; if (++i == rx_ring->count) i = 0; next_rxd = E1000_RX_DESC(*rx_ring, i); prefetch(next_rxd); next_buffer = &rx_ring->buffer_info[i]; cleaned = true; cleaned_count++; dma_unmap_page(&pdev->dev, buffer_info->dma, adapter->rx_buffer_len, DMA_FROM_DEVICE); buffer_info->dma = 0; length = le16_to_cpu(rx_desc->length); /* errors is only valid for DD + EOP descriptors */ if (unlikely((status & E1000_RXD_STAT_EOP) && (rx_desc->errors & E1000_RXD_ERR_FRAME_ERR_MASK))) { u8 *mapped = page_address(buffer_info->rxbuf.page); if (e1000_tbi_should_accept(adapter, status, rx_desc->errors, length, mapped)) { length--; } else if (netdev->features & NETIF_F_RXALL) { goto process_skb; } else { /* an error means any chain goes out the window * too */ dev_kfree_skb(rx_ring->rx_skb_top); rx_ring->rx_skb_top = NULL; goto next_desc; } } #define rxtop rx_ring->rx_skb_top process_skb: if (!(status & E1000_RXD_STAT_EOP)) { /* this descriptor is only the beginning (or middle) */ if (!rxtop) { /* this is the beginning of a chain */ rxtop = napi_get_frags(&adapter->napi); if (!rxtop) break; skb_fill_page_desc(rxtop, 0, buffer_info->rxbuf.page, 0, length); } else { /* this is the middle of a chain */ skb_fill_page_desc(rxtop, skb_shinfo(rxtop)->nr_frags, buffer_info->rxbuf.page, 0, length); } e1000_consume_page(buffer_info, rxtop, length); goto next_desc; } else { if (rxtop) { /* end of the chain */ skb_fill_page_desc(rxtop, skb_shinfo(rxtop)->nr_frags, buffer_info->rxbuf.page, 0, length); skb = rxtop; rxtop = NULL; e1000_consume_page(buffer_info, skb, length); } else { struct page *p; /* no chain, got EOP, this buf is the packet * copybreak to save the put_page/alloc_page */ p = buffer_info->rxbuf.page; if (length <= copybreak) { if (likely(!(netdev->features & NETIF_F_RXFCS))) length -= 4; skb = e1000_alloc_rx_skb(adapter, length); if (!skb) break; memcpy(skb_tail_pointer(skb), page_address(p), length); /* re-use the page, so don't erase * buffer_info->rxbuf.page */ skb_put(skb, length); e1000_rx_checksum(adapter, status | rx_desc->errors << 24, le16_to_cpu(rx_desc->csum), skb); total_rx_bytes += skb->len; total_rx_packets++; e1000_receive_skb(adapter, status, rx_desc->special, skb); goto next_desc; } else { skb = napi_get_frags(&adapter->napi); if (!skb) { adapter->alloc_rx_buff_failed++; break; } skb_fill_page_desc(skb, 0, p, 0, length); e1000_consume_page(buffer_info, skb, length); } } } /* Receive Checksum Offload XXX recompute due to CRC strip? */ e1000_rx_checksum(adapter, (u32)(status) | ((u32)(rx_desc->errors) << 24), le16_to_cpu(rx_desc->csum), skb); total_rx_bytes += (skb->len - 4); /* don't count FCS */ if (likely(!(netdev->features & NETIF_F_RXFCS))) pskb_trim(skb, skb->len - 4); total_rx_packets++; if (status & E1000_RXD_STAT_VP) { __le16 vlan = rx_desc->special; u16 vid = le16_to_cpu(vlan) & E1000_RXD_SPC_VLAN_MASK; __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vid); } napi_gro_frags(&adapter->napi); next_desc: rx_desc->status = 0; /* return some buffers to hardware, one at a time is too slow */ if (unlikely(cleaned_count >= E1000_RX_BUFFER_WRITE)) { adapter->alloc_rx_buf(adapter, rx_ring, cleaned_count); cleaned_count = 0; } /* use prefetched values */ rx_desc = next_rxd; buffer_info = next_buffer; } rx_ring->next_to_clean = i; cleaned_count = E1000_DESC_UNUSED(rx_ring); if (cleaned_count) adapter->alloc_rx_buf(adapter, rx_ring, cleaned_count); adapter->total_rx_packets += total_rx_packets; adapter->total_rx_bytes += total_rx_bytes; netdev->stats.rx_bytes += total_rx_bytes; netdev->stats.rx_packets += total_rx_packets; return cleaned; } /* this should improve performance for small packets with large amounts * of reassembly being done in the stack */ static struct sk_buff *e1000_copybreak(struct e1000_adapter *adapter, struct e1000_rx_buffer *buffer_info, u32 length, const void *data) { struct sk_buff *skb; if (length > copybreak) return NULL; skb = e1000_alloc_rx_skb(adapter, length); if (!skb) return NULL; dma_sync_single_for_cpu(&adapter->pdev->dev, buffer_info->dma, length, DMA_FROM_DEVICE); skb_put_data(skb, data, length); return skb; } /** * e1000_clean_rx_irq - Send received data up the network stack; legacy * @adapter: board private structure * @rx_ring: ring to clean * @work_done: amount of napi work completed this call * @work_to_do: max amount of work allowed for this call to do */ static bool e1000_clean_rx_irq(struct e1000_adapter *adapter, struct e1000_rx_ring *rx_ring, int *work_done, int work_to_do) { struct net_device *netdev = adapter->netdev; struct pci_dev *pdev = adapter->pdev; struct e1000_rx_desc *rx_desc, *next_rxd; struct e1000_rx_buffer *buffer_info, *next_buffer; u32 length; unsigned int i; int cleaned_count = 0; bool cleaned = false; unsigned int total_rx_bytes = 0, total_rx_packets = 0; i = rx_ring->next_to_clean; rx_desc = E1000_RX_DESC(*rx_ring, i); buffer_info = &rx_ring->buffer_info[i]; while (rx_desc->status & E1000_RXD_STAT_DD) { struct sk_buff *skb; u8 *data; u8 status; if (*work_done >= work_to_do) break; (*work_done)++; dma_rmb(); /* read descriptor and rx_buffer_info after status DD */ status = rx_desc->status; length = le16_to_cpu(rx_desc->length); data = buffer_info->rxbuf.data; prefetch(data); skb = e1000_copybreak(adapter, buffer_info, length, data); if (!skb) { unsigned int frag_len = e1000_frag_len(adapter); skb = napi_build_skb(data - E1000_HEADROOM, frag_len); if (!skb) { adapter->alloc_rx_buff_failed++; break; } skb_reserve(skb, E1000_HEADROOM); dma_unmap_single(&pdev->dev, buffer_info->dma, adapter->rx_buffer_len, DMA_FROM_DEVICE); buffer_info->dma = 0; buffer_info->rxbuf.data = NULL; } if (++i == rx_ring->count) i = 0; next_rxd = E1000_RX_DESC(*rx_ring, i); prefetch(next_rxd); next_buffer = &rx_ring->buffer_info[i]; cleaned = true; cleaned_count++; /* !EOP means multiple descriptors were used to store a single * packet, if thats the case we need to toss it. In fact, we * to toss every packet with the EOP bit clear and the next * frame that _does_ have the EOP bit set, as it is by * definition only a frame fragment */ if (unlikely(!(status & E1000_RXD_STAT_EOP))) adapter->discarding = true; if (adapter->discarding) { /* All receives must fit into a single buffer */ netdev_dbg(netdev, "Receive packet consumed multiple buffers\n"); dev_kfree_skb(skb); if (status & E1000_RXD_STAT_EOP) adapter->discarding = false; goto next_desc; } if (unlikely(rx_desc->errors & E1000_RXD_ERR_FRAME_ERR_MASK)) { if (e1000_tbi_should_accept(adapter, status, rx_desc->errors, length, data)) { length--; } else if (netdev->features & NETIF_F_RXALL) { goto process_skb; } else { dev_kfree_skb(skb); goto next_desc; } } process_skb: total_rx_bytes += (length - 4); /* don't count FCS */ total_rx_packets++; if (likely(!(netdev->features & NETIF_F_RXFCS))) /* adjust length to remove Ethernet CRC, this must be * done after the TBI_ACCEPT workaround above */ length -= 4; if (buffer_info->rxbuf.data == NULL) skb_put(skb, length); else /* copybreak skb */ skb_trim(skb, length); /* Receive Checksum Offload */ e1000_rx_checksum(adapter, (u32)(status) | ((u32)(rx_desc->errors) << 24), le16_to_cpu(rx_desc->csum), skb); e1000_receive_skb(adapter, status, rx_desc->special, skb); next_desc: rx_desc->status = 0; /* return some buffers to hardware, one at a time is too slow */ if (unlikely(cleaned_count >= E1000_RX_BUFFER_WRITE)) { adapter->alloc_rx_buf(adapter, rx_ring, cleaned_count); cleaned_count = 0; } /* use prefetched values */ rx_desc = next_rxd; buffer_info = next_buffer; } rx_ring->next_to_clean = i; cleaned_count = E1000_DESC_UNUSED(rx_ring); if (cleaned_count) adapter->alloc_rx_buf(adapter, rx_ring, cleaned_count); adapter->total_rx_packets += total_rx_packets; adapter->total_rx_bytes += total_rx_bytes; netdev->stats.rx_bytes += total_rx_bytes; netdev->stats.rx_packets += total_rx_packets; return cleaned; } /** * e1000_alloc_jumbo_rx_buffers - Replace used jumbo receive buffers * @adapter: address of board private structure * @rx_ring: pointer to receive ring structure * @cleaned_count: number of buffers to allocate this pass **/ static void e1000_alloc_jumbo_rx_buffers(struct e1000_adapter *adapter, struct e1000_rx_ring *rx_ring, int cleaned_count) { struct pci_dev *pdev = adapter->pdev; struct e1000_rx_desc *rx_desc; struct e1000_rx_buffer *buffer_info; unsigned int i; i = rx_ring->next_to_use; buffer_info = &rx_ring->buffer_info[i]; while (cleaned_count--) { /* allocate a new page if necessary */ if (!buffer_info->rxbuf.page) { buffer_info->rxbuf.page = alloc_page(GFP_ATOMIC); if (unlikely(!buffer_info->rxbuf.page)) { adapter->alloc_rx_buff_failed++; break; } } if (!buffer_info->dma) { buffer_info->dma = dma_map_page(&pdev->dev, buffer_info->rxbuf.page, 0, adapter->rx_buffer_len, DMA_FROM_DEVICE); if (dma_mapping_error(&pdev->dev, buffer_info->dma)) { put_page(buffer_info->rxbuf.page); buffer_info->rxbuf.page = NULL; buffer_info->dma = 0; adapter->alloc_rx_buff_failed++; break; } } rx_desc = E1000_RX_DESC(*rx_ring, i); rx_desc->buffer_addr = cpu_to_le64(buffer_info->dma); if (unlikely(++i == rx_ring->count)) i = 0; buffer_info = &rx_ring->buffer_info[i]; } if (likely(rx_ring->next_to_use != i)) { rx_ring->next_to_use = i; if (unlikely(i-- == 0)) i = (rx_ring->count - 1); /* Force memory writes to complete before letting h/w * know there are new descriptors to fetch. (Only * applicable for weak-ordered memory model archs, * such as IA-64). */ dma_wmb(); writel(i, adapter->hw.hw_addr + rx_ring->rdt); } } /** * e1000_alloc_rx_buffers - Replace used receive buffers; legacy & extended * @adapter: address of board private structure * @rx_ring: pointer to ring struct * @cleaned_count: number of new Rx buffers to try to allocate **/ static void e1000_alloc_rx_buffers(struct e1000_adapter *adapter, struct e1000_rx_ring *rx_ring, int cleaned_count) { struct e1000_hw *hw = &adapter->hw; struct pci_dev *pdev = adapter->pdev; struct e1000_rx_desc *rx_desc; struct e1000_rx_buffer *buffer_info; unsigned int i; unsigned int bufsz = adapter->rx_buffer_len; i = rx_ring->next_to_use; buffer_info = &rx_ring->buffer_info[i]; while (cleaned_count--) { void *data; if (buffer_info->rxbuf.data) goto skip; data = e1000_alloc_frag(adapter); if (!data) { /* Better luck next round */ adapter->alloc_rx_buff_failed++; break; } /* Fix for errata 23, can't cross 64kB boundary */ if (!e1000_check_64k_bound(adapter, data, bufsz)) { void *olddata = data; e_err(rx_err, "skb align check failed: %u bytes at " "%p\n", bufsz, data); /* Try again, without freeing the previous */ data = e1000_alloc_frag(adapter); /* Failed allocation, critical failure */ if (!data) { skb_free_frag(olddata); adapter->alloc_rx_buff_failed++; break; } if (!e1000_check_64k_bound(adapter, data, bufsz)) { /* give up */ skb_free_frag(data); skb_free_frag(olddata); adapter->alloc_rx_buff_failed++; break; } /* Use new allocation */ skb_free_frag(olddata); } buffer_info->dma = dma_map_single(&pdev->dev, data, adapter->rx_buffer_len, DMA_FROM_DEVICE); if (dma_mapping_error(&pdev->dev, buffer_info->dma)) { skb_free_frag(data); buffer_info->dma = 0; adapter->alloc_rx_buff_failed++; break; } /* XXX if it was allocated cleanly it will never map to a * boundary crossing */ /* Fix for errata 23, can't cross 64kB boundary */ if (!e1000_check_64k_bound(adapter, (void *)(unsigned long)buffer_info->dma, adapter->rx_buffer_len)) { e_err(rx_err, "dma align check failed: %u bytes at " "%p\n", adapter->rx_buffer_len, (void *)(unsigned long)buffer_info->dma); dma_unmap_single(&pdev->dev, buffer_info->dma, adapter->rx_buffer_len, DMA_FROM_DEVICE); skb_free_frag(data); buffer_info->rxbuf.data = NULL; buffer_info->dma = 0; adapter->alloc_rx_buff_failed++; break; } buffer_info->rxbuf.data = data; skip: rx_desc = E1000_RX_DESC(*rx_ring, i); rx_desc->buffer_addr = cpu_to_le64(buffer_info->dma); if (unlikely(++i == rx_ring->count)) i = 0; buffer_info = &rx_ring->buffer_info[i]; } if (likely(rx_ring->next_to_use != i)) { rx_ring->next_to_use = i; if (unlikely(i-- == 0)) i = (rx_ring->count - 1); /* Force memory writes to complete before letting h/w * know there are new descriptors to fetch. (Only * applicable for weak-ordered memory model archs, * such as IA-64). */ dma_wmb(); writel(i, hw->hw_addr + rx_ring->rdt); } } /** * e1000_smartspeed - Workaround for SmartSpeed on 82541 and 82547 controllers. * @adapter: address of board private structure **/ static void e1000_smartspeed(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u16 phy_status; u16 phy_ctrl; if ((hw->phy_type != e1000_phy_igp) || !hw->autoneg || !(hw->autoneg_advertised & ADVERTISE_1000_FULL)) return; if (adapter->smartspeed == 0) { /* If Master/Slave config fault is asserted twice, * we assume back-to-back */ e1000_read_phy_reg(hw, PHY_1000T_STATUS, &phy_status); if (!(phy_status & SR_1000T_MS_CONFIG_FAULT)) return; e1000_read_phy_reg(hw, PHY_1000T_STATUS, &phy_status); if (!(phy_status & SR_1000T_MS_CONFIG_FAULT)) return; e1000_read_phy_reg(hw, PHY_1000T_CTRL, &phy_ctrl); if (phy_ctrl & CR_1000T_MS_ENABLE) { phy_ctrl &= ~CR_1000T_MS_ENABLE; e1000_write_phy_reg(hw, PHY_1000T_CTRL, phy_ctrl); adapter->smartspeed++; if (!e1000_phy_setup_autoneg(hw) && !e1000_read_phy_reg(hw, PHY_CTRL, &phy_ctrl)) { phy_ctrl |= (MII_CR_AUTO_NEG_EN | MII_CR_RESTART_AUTO_NEG); e1000_write_phy_reg(hw, PHY_CTRL, phy_ctrl); } } return; } else if (adapter->smartspeed == E1000_SMARTSPEED_DOWNSHIFT) { /* If still no link, perhaps using 2/3 pair cable */ e1000_read_phy_reg(hw, PHY_1000T_CTRL, &phy_ctrl); phy_ctrl |= CR_1000T_MS_ENABLE; e1000_write_phy_reg(hw, PHY_1000T_CTRL, phy_ctrl); if (!e1000_phy_setup_autoneg(hw) && !e1000_read_phy_reg(hw, PHY_CTRL, &phy_ctrl)) { phy_ctrl |= (MII_CR_AUTO_NEG_EN | MII_CR_RESTART_AUTO_NEG); e1000_write_phy_reg(hw, PHY_CTRL, phy_ctrl); } } /* Restart process after E1000_SMARTSPEED_MAX iterations */ if (adapter->smartspeed++ == E1000_SMARTSPEED_MAX) adapter->smartspeed = 0; } /** * e1000_ioctl - handle ioctl calls * @netdev: pointer to our netdev * @ifr: pointer to interface request structure * @cmd: ioctl data **/ static int e1000_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd) { switch (cmd) { case SIOCGMIIPHY: case SIOCGMIIREG: case SIOCSMIIREG: return e1000_mii_ioctl(netdev, ifr, cmd); default: return -EOPNOTSUPP; } } /** * e1000_mii_ioctl - * @netdev: pointer to our netdev * @ifr: pointer to interface request structure * @cmd: ioctl data **/ static int e1000_mii_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; struct mii_ioctl_data *data = if_mii(ifr); int retval; u16 mii_reg; unsigned long flags; if (hw->media_type != e1000_media_type_copper) return -EOPNOTSUPP; switch (cmd) { case SIOCGMIIPHY: data->phy_id = hw->phy_addr; break; case SIOCGMIIREG: spin_lock_irqsave(&adapter->stats_lock, flags); if (e1000_read_phy_reg(hw, data->reg_num & 0x1F, &data->val_out)) { spin_unlock_irqrestore(&adapter->stats_lock, flags); return -EIO; } spin_unlock_irqrestore(&adapter->stats_lock, flags); break; case SIOCSMIIREG: if (data->reg_num & ~(0x1F)) return -EFAULT; mii_reg = data->val_in; spin_lock_irqsave(&adapter->stats_lock, flags); if (e1000_write_phy_reg(hw, data->reg_num, mii_reg)) { spin_unlock_irqrestore(&adapter->stats_lock, flags); return -EIO; } spin_unlock_irqrestore(&adapter->stats_lock, flags); if (hw->media_type == e1000_media_type_copper) { switch (data->reg_num) { case PHY_CTRL: if (mii_reg & MII_CR_POWER_DOWN) break; if (mii_reg & MII_CR_AUTO_NEG_EN) { hw->autoneg = 1; hw->autoneg_advertised = 0x2F; } else { u32 speed; if (mii_reg & 0x40) speed = SPEED_1000; else if (mii_reg & 0x2000) speed = SPEED_100; else speed = SPEED_10; retval = e1000_set_spd_dplx( adapter, speed, ((mii_reg & 0x100) ? DUPLEX_FULL : DUPLEX_HALF)); if (retval) return retval; } if (netif_running(adapter->netdev)) e1000_reinit_locked(adapter); else e1000_reset(adapter); break; case M88E1000_PHY_SPEC_CTRL: case M88E1000_EXT_PHY_SPEC_CTRL: if (e1000_phy_reset(hw)) return -EIO; break; } } else { switch (data->reg_num) { case PHY_CTRL: if (mii_reg & MII_CR_POWER_DOWN) break; if (netif_running(adapter->netdev)) e1000_reinit_locked(adapter); else e1000_reset(adapter); break; } } break; default: return -EOPNOTSUPP; } return E1000_SUCCESS; } void e1000_pci_set_mwi(struct e1000_hw *hw) { struct e1000_adapter *adapter = hw->back; int ret_val = pci_set_mwi(adapter->pdev); if (ret_val) e_err(probe, "Error in setting MWI\n"); } void e1000_pci_clear_mwi(struct e1000_hw *hw) { struct e1000_adapter *adapter = hw->back; pci_clear_mwi(adapter->pdev); } int e1000_pcix_get_mmrbc(struct e1000_hw *hw) { struct e1000_adapter *adapter = hw->back; return pcix_get_mmrbc(adapter->pdev); } void e1000_pcix_set_mmrbc(struct e1000_hw *hw, int mmrbc) { struct e1000_adapter *adapter = hw->back; pcix_set_mmrbc(adapter->pdev, mmrbc); } void e1000_io_write(struct e1000_hw *hw, unsigned long port, u32 value) { outl(value, port); } static bool e1000_vlan_used(struct e1000_adapter *adapter) { u16 vid; for_each_set_bit(vid, adapter->active_vlans, VLAN_N_VID) return true; return false; } static void __e1000_vlan_mode(struct e1000_adapter *adapter, netdev_features_t features) { struct e1000_hw *hw = &adapter->hw; u32 ctrl; ctrl = er32(CTRL); if (features & NETIF_F_HW_VLAN_CTAG_RX) { /* enable VLAN tag insert/strip */ ctrl |= E1000_CTRL_VME; } else { /* disable VLAN tag insert/strip */ ctrl &= ~E1000_CTRL_VME; } ew32(CTRL, ctrl); } static void e1000_vlan_filter_on_off(struct e1000_adapter *adapter, bool filter_on) { struct e1000_hw *hw = &adapter->hw; u32 rctl; if (!test_bit(__E1000_DOWN, &adapter->flags)) e1000_irq_disable(adapter); __e1000_vlan_mode(adapter, adapter->netdev->features); if (filter_on) { /* enable VLAN receive filtering */ rctl = er32(RCTL); rctl &= ~E1000_RCTL_CFIEN; if (!(adapter->netdev->flags & IFF_PROMISC)) rctl |= E1000_RCTL_VFE; ew32(RCTL, rctl); e1000_update_mng_vlan(adapter); } else { /* disable VLAN receive filtering */ rctl = er32(RCTL); rctl &= ~E1000_RCTL_VFE; ew32(RCTL, rctl); } if (!test_bit(__E1000_DOWN, &adapter->flags)) e1000_irq_enable(adapter); } static void e1000_vlan_mode(struct net_device *netdev, netdev_features_t features) { struct e1000_adapter *adapter = netdev_priv(netdev); if (!test_bit(__E1000_DOWN, &adapter->flags)) e1000_irq_disable(adapter); __e1000_vlan_mode(adapter, features); if (!test_bit(__E1000_DOWN, &adapter->flags)) e1000_irq_enable(adapter); } static int e1000_vlan_rx_add_vid(struct net_device *netdev, __be16 proto, u16 vid) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u32 vfta, index; if ((hw->mng_cookie.status & E1000_MNG_DHCP_COOKIE_STATUS_VLAN_SUPPORT) && (vid == adapter->mng_vlan_id)) return 0; if (!e1000_vlan_used(adapter)) e1000_vlan_filter_on_off(adapter, true); /* add VID to filter table */ index = (vid >> 5) & 0x7F; vfta = E1000_READ_REG_ARRAY(hw, VFTA, index); vfta |= (1 << (vid & 0x1F)); e1000_write_vfta(hw, index, vfta); set_bit(vid, adapter->active_vlans); return 0; } static int e1000_vlan_rx_kill_vid(struct net_device *netdev, __be16 proto, u16 vid) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u32 vfta, index; if (!test_bit(__E1000_DOWN, &adapter->flags)) e1000_irq_disable(adapter); if (!test_bit(__E1000_DOWN, &adapter->flags)) e1000_irq_enable(adapter); /* remove VID from filter table */ index = (vid >> 5) & 0x7F; vfta = E1000_READ_REG_ARRAY(hw, VFTA, index); vfta &= ~(1 << (vid & 0x1F)); e1000_write_vfta(hw, index, vfta); clear_bit(vid, adapter->active_vlans); if (!e1000_vlan_used(adapter)) e1000_vlan_filter_on_off(adapter, false); return 0; } static void e1000_restore_vlan(struct e1000_adapter *adapter) { u16 vid; if (!e1000_vlan_used(adapter)) return; e1000_vlan_filter_on_off(adapter, true); for_each_set_bit(vid, adapter->active_vlans, VLAN_N_VID) e1000_vlan_rx_add_vid(adapter->netdev, htons(ETH_P_8021Q), vid); } int e1000_set_spd_dplx(struct e1000_adapter *adapter, u32 spd, u8 dplx) { struct e1000_hw *hw = &adapter->hw; hw->autoneg = 0; /* Make sure dplx is at most 1 bit and lsb of speed is not set * for the switch() below to work */ if ((spd & 1) || (dplx & ~1)) goto err_inval; /* Fiber NICs only allow 1000 gbps Full duplex */ if ((hw->media_type == e1000_media_type_fiber) && spd != SPEED_1000 && dplx != DUPLEX_FULL) goto err_inval; switch (spd + dplx) { case SPEED_10 + DUPLEX_HALF: hw->forced_speed_duplex = e1000_10_half; break; case SPEED_10 + DUPLEX_FULL: hw->forced_speed_duplex = e1000_10_full; break; case SPEED_100 + DUPLEX_HALF: hw->forced_speed_duplex = e1000_100_half; break; case SPEED_100 + DUPLEX_FULL: hw->forced_speed_duplex = e1000_100_full; break; case SPEED_1000 + DUPLEX_FULL: hw->autoneg = 1; hw->autoneg_advertised = ADVERTISE_1000_FULL; break; case SPEED_1000 + DUPLEX_HALF: /* not supported */ default: goto err_inval; } /* clear MDI, MDI(-X) override is only allowed when autoneg enabled */ hw->mdix = AUTO_ALL_MODES; return 0; err_inval: e_err(probe, "Unsupported Speed/Duplex configuration\n"); return -EINVAL; } static int __e1000_shutdown(struct pci_dev *pdev, bool *enable_wake) { struct net_device *netdev = pci_get_drvdata(pdev); struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u32 ctrl, ctrl_ext, rctl, status; u32 wufc = adapter->wol; netif_device_detach(netdev); if (netif_running(netdev)) { int count = E1000_CHECK_RESET_COUNT; while (test_bit(__E1000_RESETTING, &adapter->flags) && count--) usleep_range(10000, 20000); WARN_ON(test_bit(__E1000_RESETTING, &adapter->flags)); e1000_down(adapter); } status = er32(STATUS); if (status & E1000_STATUS_LU) wufc &= ~E1000_WUFC_LNKC; if (wufc) { e1000_setup_rctl(adapter); e1000_set_rx_mode(netdev); rctl = er32(RCTL); /* turn on all-multi mode if wake on multicast is enabled */ if (wufc & E1000_WUFC_MC) rctl |= E1000_RCTL_MPE; /* enable receives in the hardware */ ew32(RCTL, rctl | E1000_RCTL_EN); if (hw->mac_type >= e1000_82540) { ctrl = er32(CTRL); /* advertise wake from D3Cold */ #define E1000_CTRL_ADVD3WUC 0x00100000 /* phy power management enable */ #define E1000_CTRL_EN_PHY_PWR_MGMT 0x00200000 ctrl |= E1000_CTRL_ADVD3WUC | E1000_CTRL_EN_PHY_PWR_MGMT; ew32(CTRL, ctrl); } if (hw->media_type == e1000_media_type_fiber || hw->media_type == e1000_media_type_internal_serdes) { /* keep the laser running in D3 */ ctrl_ext = er32(CTRL_EXT); ctrl_ext |= E1000_CTRL_EXT_SDP7_DATA; ew32(CTRL_EXT, ctrl_ext); } ew32(WUC, E1000_WUC_PME_EN); ew32(WUFC, wufc); } else { ew32(WUC, 0); ew32(WUFC, 0); } e1000_release_manageability(adapter); *enable_wake = !!wufc; /* make sure adapter isn't asleep if manageability is enabled */ if (adapter->en_mng_pt) *enable_wake = true; if (netif_running(netdev)) e1000_free_irq(adapter); if (!test_and_set_bit(__E1000_DISABLED, &adapter->flags)) pci_disable_device(pdev); return 0; } static int __maybe_unused e1000_suspend(struct device *dev) { int retval; struct pci_dev *pdev = to_pci_dev(dev); bool wake; retval = __e1000_shutdown(pdev, &wake); device_set_wakeup_enable(dev, wake); return retval; } static int __maybe_unused e1000_resume(struct device *dev) { struct pci_dev *pdev = to_pci_dev(dev); struct net_device *netdev = pci_get_drvdata(pdev); struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u32 err; if (adapter->need_ioport) err = pci_enable_device(pdev); else err = pci_enable_device_mem(pdev); if (err) { pr_err("Cannot enable PCI device from suspend\n"); return err; } /* flush memory to make sure state is correct */ smp_mb__before_atomic(); clear_bit(__E1000_DISABLED, &adapter->flags); pci_set_master(pdev); pci_enable_wake(pdev, PCI_D3hot, 0); pci_enable_wake(pdev, PCI_D3cold, 0); if (netif_running(netdev)) { err = e1000_request_irq(adapter); if (err) return err; } e1000_power_up_phy(adapter); e1000_reset(adapter); ew32(WUS, ~0); e1000_init_manageability(adapter); if (netif_running(netdev)) e1000_up(adapter); netif_device_attach(netdev); return 0; } static void e1000_shutdown(struct pci_dev *pdev) { bool wake; __e1000_shutdown(pdev, &wake); if (system_state == SYSTEM_POWER_OFF) { pci_wake_from_d3(pdev, wake); pci_set_power_state(pdev, PCI_D3hot); } } #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 e1000_netpoll(struct net_device *netdev) { struct e1000_adapter *adapter = netdev_priv(netdev); if (disable_hardirq(adapter->pdev->irq)) e1000_intr(adapter->pdev->irq, netdev); enable_irq(adapter->pdev->irq); } #endif /** * e1000_io_error_detected - called when PCI error is detected * @pdev: Pointer to PCI device * @state: The current pci connection state * * This function is called after a PCI bus error affecting * this device has been detected. */ static pci_ers_result_t e1000_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state) { struct net_device *netdev = pci_get_drvdata(pdev); struct e1000_adapter *adapter = netdev_priv(netdev); netif_device_detach(netdev); if (state == pci_channel_io_perm_failure) return PCI_ERS_RESULT_DISCONNECT; if (netif_running(netdev)) e1000_down(adapter); if (!test_and_set_bit(__E1000_DISABLED, &adapter->flags)) pci_disable_device(pdev); /* Request a slot reset. */ return PCI_ERS_RESULT_NEED_RESET; } /** * e1000_io_slot_reset - called after the pci bus has been reset. * @pdev: Pointer to PCI device * * Restart the card from scratch, as if from a cold-boot. Implementation * resembles the first-half of the e1000_resume routine. */ static pci_ers_result_t e1000_io_slot_reset(struct pci_dev *pdev) { struct net_device *netdev = pci_get_drvdata(pdev); struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; int err; if (adapter->need_ioport) err = pci_enable_device(pdev); else err = pci_enable_device_mem(pdev); if (err) { pr_err("Cannot re-enable PCI device after reset.\n"); return PCI_ERS_RESULT_DISCONNECT; } /* flush memory to make sure state is correct */ smp_mb__before_atomic(); clear_bit(__E1000_DISABLED, &adapter->flags); pci_set_master(pdev); pci_enable_wake(pdev, PCI_D3hot, 0); pci_enable_wake(pdev, PCI_D3cold, 0); e1000_reset(adapter); ew32(WUS, ~0); return PCI_ERS_RESULT_RECOVERED; } /** * e1000_io_resume - called when traffic can start flowing again. * @pdev: Pointer to PCI device * * This callback is called when the error recovery driver tells us that * its OK to resume normal operation. Implementation resembles the * second-half of the e1000_resume routine. */ static void e1000_io_resume(struct pci_dev *pdev) { struct net_device *netdev = pci_get_drvdata(pdev); struct e1000_adapter *adapter = netdev_priv(netdev); e1000_init_manageability(adapter); if (netif_running(netdev)) { if (e1000_up(adapter)) { pr_info("can't bring device back up after reset\n"); return; } } netif_device_attach(netdev); } /* e1000_main.c */
linux-master
drivers/net/ethernet/intel/e1000/e1000_main.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2018, Intel Corporation. */ #include "ice_common.h" #include "ice_sched.h" #include "ice_adminq_cmd.h" #include "ice_flow.h" #include "ice_ptp_hw.h" #define ICE_PF_RESET_WAIT_COUNT 300 static const char * const ice_link_mode_str_low[] = { [0] = "100BASE_TX", [1] = "100M_SGMII", [2] = "1000BASE_T", [3] = "1000BASE_SX", [4] = "1000BASE_LX", [5] = "1000BASE_KX", [6] = "1G_SGMII", [7] = "2500BASE_T", [8] = "2500BASE_X", [9] = "2500BASE_KX", [10] = "5GBASE_T", [11] = "5GBASE_KR", [12] = "10GBASE_T", [13] = "10G_SFI_DA", [14] = "10GBASE_SR", [15] = "10GBASE_LR", [16] = "10GBASE_KR_CR1", [17] = "10G_SFI_AOC_ACC", [18] = "10G_SFI_C2C", [19] = "25GBASE_T", [20] = "25GBASE_CR", [21] = "25GBASE_CR_S", [22] = "25GBASE_CR1", [23] = "25GBASE_SR", [24] = "25GBASE_LR", [25] = "25GBASE_KR", [26] = "25GBASE_KR_S", [27] = "25GBASE_KR1", [28] = "25G_AUI_AOC_ACC", [29] = "25G_AUI_C2C", [30] = "40GBASE_CR4", [31] = "40GBASE_SR4", [32] = "40GBASE_LR4", [33] = "40GBASE_KR4", [34] = "40G_XLAUI_AOC_ACC", [35] = "40G_XLAUI", [36] = "50GBASE_CR2", [37] = "50GBASE_SR2", [38] = "50GBASE_LR2", [39] = "50GBASE_KR2", [40] = "50G_LAUI2_AOC_ACC", [41] = "50G_LAUI2", [42] = "50G_AUI2_AOC_ACC", [43] = "50G_AUI2", [44] = "50GBASE_CP", [45] = "50GBASE_SR", [46] = "50GBASE_FR", [47] = "50GBASE_LR", [48] = "50GBASE_KR_PAM4", [49] = "50G_AUI1_AOC_ACC", [50] = "50G_AUI1", [51] = "100GBASE_CR4", [52] = "100GBASE_SR4", [53] = "100GBASE_LR4", [54] = "100GBASE_KR4", [55] = "100G_CAUI4_AOC_ACC", [56] = "100G_CAUI4", [57] = "100G_AUI4_AOC_ACC", [58] = "100G_AUI4", [59] = "100GBASE_CR_PAM4", [60] = "100GBASE_KR_PAM4", [61] = "100GBASE_CP2", [62] = "100GBASE_SR2", [63] = "100GBASE_DR", }; static const char * const ice_link_mode_str_high[] = { [0] = "100GBASE_KR2_PAM4", [1] = "100G_CAUI2_AOC_ACC", [2] = "100G_CAUI2", [3] = "100G_AUI2_AOC_ACC", [4] = "100G_AUI2", }; /** * ice_dump_phy_type - helper function to dump phy_type * @hw: pointer to the HW structure * @low: 64 bit value for phy_type_low * @high: 64 bit value for phy_type_high * @prefix: prefix string to differentiate multiple dumps */ static void ice_dump_phy_type(struct ice_hw *hw, u64 low, u64 high, const char *prefix) { ice_debug(hw, ICE_DBG_PHY, "%s: phy_type_low: 0x%016llx\n", prefix, low); for (u32 i = 0; i < BITS_PER_TYPE(typeof(low)); i++) { if (low & BIT_ULL(i)) ice_debug(hw, ICE_DBG_PHY, "%s: bit(%d): %s\n", prefix, i, ice_link_mode_str_low[i]); } ice_debug(hw, ICE_DBG_PHY, "%s: phy_type_high: 0x%016llx\n", prefix, high); for (u32 i = 0; i < BITS_PER_TYPE(typeof(high)); i++) { if (high & BIT_ULL(i)) ice_debug(hw, ICE_DBG_PHY, "%s: bit(%d): %s\n", prefix, i, ice_link_mode_str_high[i]); } } /** * ice_set_mac_type - Sets MAC type * @hw: pointer to the HW structure * * This function sets the MAC type of the adapter based on the * vendor ID and device ID stored in the HW structure. */ static int ice_set_mac_type(struct ice_hw *hw) { if (hw->vendor_id != PCI_VENDOR_ID_INTEL) return -ENODEV; switch (hw->device_id) { case ICE_DEV_ID_E810C_BACKPLANE: case ICE_DEV_ID_E810C_QSFP: case ICE_DEV_ID_E810C_SFP: case ICE_DEV_ID_E810_XXV_BACKPLANE: case ICE_DEV_ID_E810_XXV_QSFP: case ICE_DEV_ID_E810_XXV_SFP: hw->mac_type = ICE_MAC_E810; break; case ICE_DEV_ID_E823C_10G_BASE_T: case ICE_DEV_ID_E823C_BACKPLANE: case ICE_DEV_ID_E823C_QSFP: case ICE_DEV_ID_E823C_SFP: case ICE_DEV_ID_E823C_SGMII: case ICE_DEV_ID_E822C_10G_BASE_T: case ICE_DEV_ID_E822C_BACKPLANE: case ICE_DEV_ID_E822C_QSFP: case ICE_DEV_ID_E822C_SFP: case ICE_DEV_ID_E822C_SGMII: case ICE_DEV_ID_E822L_10G_BASE_T: case ICE_DEV_ID_E822L_BACKPLANE: case ICE_DEV_ID_E822L_SFP: case ICE_DEV_ID_E822L_SGMII: case ICE_DEV_ID_E823L_10G_BASE_T: case ICE_DEV_ID_E823L_1GBE: case ICE_DEV_ID_E823L_BACKPLANE: case ICE_DEV_ID_E823L_QSFP: case ICE_DEV_ID_E823L_SFP: hw->mac_type = ICE_MAC_GENERIC; break; default: hw->mac_type = ICE_MAC_UNKNOWN; break; } ice_debug(hw, ICE_DBG_INIT, "mac_type: %d\n", hw->mac_type); return 0; } /** * ice_is_e810 * @hw: pointer to the hardware structure * * returns true if the device is E810 based, false if not. */ bool ice_is_e810(struct ice_hw *hw) { return hw->mac_type == ICE_MAC_E810; } /** * ice_is_e810t * @hw: pointer to the hardware structure * * returns true if the device is E810T based, false if not. */ bool ice_is_e810t(struct ice_hw *hw) { switch (hw->device_id) { case ICE_DEV_ID_E810C_SFP: switch (hw->subsystem_device_id) { case ICE_SUBDEV_ID_E810T: case ICE_SUBDEV_ID_E810T2: case ICE_SUBDEV_ID_E810T3: case ICE_SUBDEV_ID_E810T4: case ICE_SUBDEV_ID_E810T6: case ICE_SUBDEV_ID_E810T7: return true; } break; case ICE_DEV_ID_E810C_QSFP: switch (hw->subsystem_device_id) { case ICE_SUBDEV_ID_E810T2: case ICE_SUBDEV_ID_E810T3: case ICE_SUBDEV_ID_E810T5: return true; } break; default: break; } return false; } /** * ice_is_e823 * @hw: pointer to the hardware structure * * returns true if the device is E823-L or E823-C based, false if not. */ bool ice_is_e823(struct ice_hw *hw) { switch (hw->device_id) { case ICE_DEV_ID_E823L_BACKPLANE: case ICE_DEV_ID_E823L_SFP: case ICE_DEV_ID_E823L_10G_BASE_T: case ICE_DEV_ID_E823L_1GBE: case ICE_DEV_ID_E823L_QSFP: case ICE_DEV_ID_E823C_BACKPLANE: case ICE_DEV_ID_E823C_QSFP: case ICE_DEV_ID_E823C_SFP: case ICE_DEV_ID_E823C_10G_BASE_T: case ICE_DEV_ID_E823C_SGMII: return true; default: return false; } } /** * ice_clear_pf_cfg - Clear PF configuration * @hw: pointer to the hardware structure * * Clears any existing PF configuration (VSIs, VSI lists, switch rules, port * configuration, flow director filters, etc.). */ int ice_clear_pf_cfg(struct ice_hw *hw) { struct ice_aq_desc desc; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_clear_pf_cfg); return ice_aq_send_cmd(hw, &desc, NULL, 0, NULL); } /** * ice_aq_manage_mac_read - manage MAC address read command * @hw: pointer to the HW struct * @buf: a virtual buffer to hold the manage MAC read response * @buf_size: Size of the virtual buffer * @cd: pointer to command details structure or NULL * * This function is used to return per PF station MAC address (0x0107). * NOTE: Upon successful completion of this command, MAC address information * is returned in user specified buffer. Please interpret user specified * buffer as "manage_mac_read" response. * Response such as various MAC addresses are stored in HW struct (port.mac) * ice_discover_dev_caps is expected to be called before this function is * called. */ static int ice_aq_manage_mac_read(struct ice_hw *hw, void *buf, u16 buf_size, struct ice_sq_cd *cd) { struct ice_aqc_manage_mac_read_resp *resp; struct ice_aqc_manage_mac_read *cmd; struct ice_aq_desc desc; int status; u16 flags; u8 i; cmd = &desc.params.mac_read; if (buf_size < sizeof(*resp)) return -EINVAL; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_manage_mac_read); status = ice_aq_send_cmd(hw, &desc, buf, buf_size, cd); if (status) return status; resp = buf; flags = le16_to_cpu(cmd->flags) & ICE_AQC_MAN_MAC_READ_M; if (!(flags & ICE_AQC_MAN_MAC_LAN_ADDR_VALID)) { ice_debug(hw, ICE_DBG_LAN, "got invalid MAC address\n"); return -EIO; } /* A single port can report up to two (LAN and WoL) addresses */ for (i = 0; i < cmd->num_addr; i++) if (resp[i].addr_type == ICE_AQC_MAN_MAC_ADDR_TYPE_LAN) { ether_addr_copy(hw->port_info->mac.lan_addr, resp[i].mac_addr); ether_addr_copy(hw->port_info->mac.perm_addr, resp[i].mac_addr); break; } return 0; } /** * ice_aq_get_phy_caps - returns PHY capabilities * @pi: port information structure * @qual_mods: report qualified modules * @report_mode: report mode capabilities * @pcaps: structure for PHY capabilities to be filled * @cd: pointer to command details structure or NULL * * Returns the various PHY capabilities supported on the Port (0x0600) */ int ice_aq_get_phy_caps(struct ice_port_info *pi, bool qual_mods, u8 report_mode, struct ice_aqc_get_phy_caps_data *pcaps, struct ice_sq_cd *cd) { struct ice_aqc_get_phy_caps *cmd; u16 pcaps_size = sizeof(*pcaps); struct ice_aq_desc desc; const char *prefix; struct ice_hw *hw; int status; cmd = &desc.params.get_phy; if (!pcaps || (report_mode & ~ICE_AQC_REPORT_MODE_M) || !pi) return -EINVAL; hw = pi->hw; if (report_mode == ICE_AQC_REPORT_DFLT_CFG && !ice_fw_supports_report_dflt_cfg(hw)) return -EINVAL; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_get_phy_caps); if (qual_mods) cmd->param0 |= cpu_to_le16(ICE_AQC_GET_PHY_RQM); cmd->param0 |= cpu_to_le16(report_mode); status = ice_aq_send_cmd(hw, &desc, pcaps, pcaps_size, cd); ice_debug(hw, ICE_DBG_LINK, "get phy caps dump\n"); switch (report_mode) { case ICE_AQC_REPORT_TOPO_CAP_MEDIA: prefix = "phy_caps_media"; break; case ICE_AQC_REPORT_TOPO_CAP_NO_MEDIA: prefix = "phy_caps_no_media"; break; case ICE_AQC_REPORT_ACTIVE_CFG: prefix = "phy_caps_active"; break; case ICE_AQC_REPORT_DFLT_CFG: prefix = "phy_caps_default"; break; default: prefix = "phy_caps_invalid"; } ice_dump_phy_type(hw, le64_to_cpu(pcaps->phy_type_low), le64_to_cpu(pcaps->phy_type_high), prefix); ice_debug(hw, ICE_DBG_LINK, "%s: report_mode = 0x%x\n", prefix, report_mode); ice_debug(hw, ICE_DBG_LINK, "%s: caps = 0x%x\n", prefix, pcaps->caps); ice_debug(hw, ICE_DBG_LINK, "%s: low_power_ctrl_an = 0x%x\n", prefix, pcaps->low_power_ctrl_an); ice_debug(hw, ICE_DBG_LINK, "%s: eee_cap = 0x%x\n", prefix, pcaps->eee_cap); ice_debug(hw, ICE_DBG_LINK, "%s: eeer_value = 0x%x\n", prefix, pcaps->eeer_value); ice_debug(hw, ICE_DBG_LINK, "%s: link_fec_options = 0x%x\n", prefix, pcaps->link_fec_options); ice_debug(hw, ICE_DBG_LINK, "%s: module_compliance_enforcement = 0x%x\n", prefix, pcaps->module_compliance_enforcement); ice_debug(hw, ICE_DBG_LINK, "%s: extended_compliance_code = 0x%x\n", prefix, pcaps->extended_compliance_code); ice_debug(hw, ICE_DBG_LINK, "%s: module_type[0] = 0x%x\n", prefix, pcaps->module_type[0]); ice_debug(hw, ICE_DBG_LINK, "%s: module_type[1] = 0x%x\n", prefix, pcaps->module_type[1]); ice_debug(hw, ICE_DBG_LINK, "%s: module_type[2] = 0x%x\n", prefix, pcaps->module_type[2]); if (!status && report_mode == ICE_AQC_REPORT_TOPO_CAP_MEDIA) { pi->phy.phy_type_low = le64_to_cpu(pcaps->phy_type_low); pi->phy.phy_type_high = le64_to_cpu(pcaps->phy_type_high); memcpy(pi->phy.link_info.module_type, &pcaps->module_type, sizeof(pi->phy.link_info.module_type)); } return status; } /** * ice_aq_get_link_topo_handle - get link topology node return status * @pi: port information structure * @node_type: requested node type * @cd: pointer to command details structure or NULL * * Get link topology node return status for specified node type (0x06E0) * * Node type cage can be used to determine if cage is present. If AQC * returns error (ENOENT), then no cage present. If no cage present, then * connection type is backplane or BASE-T. */ static int ice_aq_get_link_topo_handle(struct ice_port_info *pi, u8 node_type, struct ice_sq_cd *cd) { struct ice_aqc_get_link_topo *cmd; struct ice_aq_desc desc; cmd = &desc.params.get_link_topo; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_get_link_topo); cmd->addr.topo_params.node_type_ctx = (ICE_AQC_LINK_TOPO_NODE_CTX_PORT << ICE_AQC_LINK_TOPO_NODE_CTX_S); /* set node type */ cmd->addr.topo_params.node_type_ctx |= (ICE_AQC_LINK_TOPO_NODE_TYPE_M & node_type); return ice_aq_send_cmd(pi->hw, &desc, NULL, 0, cd); } /** * ice_is_media_cage_present * @pi: port information structure * * Returns true if media cage is present, else false. If no cage, then * media type is backplane or BASE-T. */ static bool ice_is_media_cage_present(struct ice_port_info *pi) { /* Node type cage can be used to determine if cage is present. If AQC * returns error (ENOENT), then no cage present. If no cage present then * connection type is backplane or BASE-T. */ return !ice_aq_get_link_topo_handle(pi, ICE_AQC_LINK_TOPO_NODE_TYPE_CAGE, NULL); } /** * ice_get_media_type - Gets media type * @pi: port information structure */ static enum ice_media_type ice_get_media_type(struct ice_port_info *pi) { struct ice_link_status *hw_link_info; if (!pi) return ICE_MEDIA_UNKNOWN; hw_link_info = &pi->phy.link_info; if (hw_link_info->phy_type_low && hw_link_info->phy_type_high) /* If more than one media type is selected, report unknown */ return ICE_MEDIA_UNKNOWN; if (hw_link_info->phy_type_low) { /* 1G SGMII is a special case where some DA cable PHYs * may show this as an option when it really shouldn't * be since SGMII is meant to be between a MAC and a PHY * in a backplane. Try to detect this case and handle it */ if (hw_link_info->phy_type_low == ICE_PHY_TYPE_LOW_1G_SGMII && (hw_link_info->module_type[ICE_AQC_MOD_TYPE_IDENT] == ICE_AQC_MOD_TYPE_BYTE1_SFP_PLUS_CU_ACTIVE || hw_link_info->module_type[ICE_AQC_MOD_TYPE_IDENT] == ICE_AQC_MOD_TYPE_BYTE1_SFP_PLUS_CU_PASSIVE)) return ICE_MEDIA_DA; switch (hw_link_info->phy_type_low) { case ICE_PHY_TYPE_LOW_1000BASE_SX: case ICE_PHY_TYPE_LOW_1000BASE_LX: case ICE_PHY_TYPE_LOW_10GBASE_SR: case ICE_PHY_TYPE_LOW_10GBASE_LR: case ICE_PHY_TYPE_LOW_10G_SFI_C2C: case ICE_PHY_TYPE_LOW_25GBASE_SR: case ICE_PHY_TYPE_LOW_25GBASE_LR: case ICE_PHY_TYPE_LOW_40GBASE_SR4: case ICE_PHY_TYPE_LOW_40GBASE_LR4: case ICE_PHY_TYPE_LOW_50GBASE_SR2: case ICE_PHY_TYPE_LOW_50GBASE_LR2: case ICE_PHY_TYPE_LOW_50GBASE_SR: case ICE_PHY_TYPE_LOW_50GBASE_FR: case ICE_PHY_TYPE_LOW_50GBASE_LR: case ICE_PHY_TYPE_LOW_100GBASE_SR4: case ICE_PHY_TYPE_LOW_100GBASE_LR4: case ICE_PHY_TYPE_LOW_100GBASE_SR2: case ICE_PHY_TYPE_LOW_100GBASE_DR: case ICE_PHY_TYPE_LOW_10G_SFI_AOC_ACC: case ICE_PHY_TYPE_LOW_25G_AUI_AOC_ACC: case ICE_PHY_TYPE_LOW_40G_XLAUI_AOC_ACC: case ICE_PHY_TYPE_LOW_50G_LAUI2_AOC_ACC: case ICE_PHY_TYPE_LOW_50G_AUI2_AOC_ACC: case ICE_PHY_TYPE_LOW_50G_AUI1_AOC_ACC: case ICE_PHY_TYPE_LOW_100G_CAUI4_AOC_ACC: case ICE_PHY_TYPE_LOW_100G_AUI4_AOC_ACC: return ICE_MEDIA_FIBER; case ICE_PHY_TYPE_LOW_100BASE_TX: case ICE_PHY_TYPE_LOW_1000BASE_T: case ICE_PHY_TYPE_LOW_2500BASE_T: case ICE_PHY_TYPE_LOW_5GBASE_T: case ICE_PHY_TYPE_LOW_10GBASE_T: case ICE_PHY_TYPE_LOW_25GBASE_T: return ICE_MEDIA_BASET; case ICE_PHY_TYPE_LOW_10G_SFI_DA: case ICE_PHY_TYPE_LOW_25GBASE_CR: case ICE_PHY_TYPE_LOW_25GBASE_CR_S: case ICE_PHY_TYPE_LOW_25GBASE_CR1: case ICE_PHY_TYPE_LOW_40GBASE_CR4: case ICE_PHY_TYPE_LOW_50GBASE_CR2: case ICE_PHY_TYPE_LOW_50GBASE_CP: case ICE_PHY_TYPE_LOW_100GBASE_CR4: case ICE_PHY_TYPE_LOW_100GBASE_CR_PAM4: case ICE_PHY_TYPE_LOW_100GBASE_CP2: return ICE_MEDIA_DA; case ICE_PHY_TYPE_LOW_25G_AUI_C2C: case ICE_PHY_TYPE_LOW_40G_XLAUI: case ICE_PHY_TYPE_LOW_50G_LAUI2: case ICE_PHY_TYPE_LOW_50G_AUI2: case ICE_PHY_TYPE_LOW_50G_AUI1: case ICE_PHY_TYPE_LOW_100G_AUI4: case ICE_PHY_TYPE_LOW_100G_CAUI4: if (ice_is_media_cage_present(pi)) return ICE_MEDIA_DA; fallthrough; case ICE_PHY_TYPE_LOW_1000BASE_KX: case ICE_PHY_TYPE_LOW_2500BASE_KX: case ICE_PHY_TYPE_LOW_2500BASE_X: case ICE_PHY_TYPE_LOW_5GBASE_KR: case ICE_PHY_TYPE_LOW_10GBASE_KR_CR1: case ICE_PHY_TYPE_LOW_25GBASE_KR: case ICE_PHY_TYPE_LOW_25GBASE_KR1: case ICE_PHY_TYPE_LOW_25GBASE_KR_S: case ICE_PHY_TYPE_LOW_40GBASE_KR4: case ICE_PHY_TYPE_LOW_50GBASE_KR_PAM4: case ICE_PHY_TYPE_LOW_50GBASE_KR2: case ICE_PHY_TYPE_LOW_100GBASE_KR4: case ICE_PHY_TYPE_LOW_100GBASE_KR_PAM4: return ICE_MEDIA_BACKPLANE; } } else { switch (hw_link_info->phy_type_high) { case ICE_PHY_TYPE_HIGH_100G_AUI2: case ICE_PHY_TYPE_HIGH_100G_CAUI2: if (ice_is_media_cage_present(pi)) return ICE_MEDIA_DA; fallthrough; case ICE_PHY_TYPE_HIGH_100GBASE_KR2_PAM4: return ICE_MEDIA_BACKPLANE; case ICE_PHY_TYPE_HIGH_100G_CAUI2_AOC_ACC: case ICE_PHY_TYPE_HIGH_100G_AUI2_AOC_ACC: return ICE_MEDIA_FIBER; } } return ICE_MEDIA_UNKNOWN; } /** * ice_aq_get_link_info * @pi: port information structure * @ena_lse: enable/disable LinkStatusEvent reporting * @link: pointer to link status structure - optional * @cd: pointer to command details structure or NULL * * Get Link Status (0x607). Returns the link status of the adapter. */ int ice_aq_get_link_info(struct ice_port_info *pi, bool ena_lse, struct ice_link_status *link, struct ice_sq_cd *cd) { struct ice_aqc_get_link_status_data link_data = { 0 }; struct ice_aqc_get_link_status *resp; struct ice_link_status *li_old, *li; enum ice_media_type *hw_media_type; struct ice_fc_info *hw_fc_info; bool tx_pause, rx_pause; struct ice_aq_desc desc; struct ice_hw *hw; u16 cmd_flags; int status; if (!pi) return -EINVAL; hw = pi->hw; li_old = &pi->phy.link_info_old; hw_media_type = &pi->phy.media_type; li = &pi->phy.link_info; hw_fc_info = &pi->fc; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_get_link_status); cmd_flags = (ena_lse) ? ICE_AQ_LSE_ENA : ICE_AQ_LSE_DIS; resp = &desc.params.get_link_status; resp->cmd_flags = cpu_to_le16(cmd_flags); resp->lport_num = pi->lport; status = ice_aq_send_cmd(hw, &desc, &link_data, sizeof(link_data), cd); if (status) return status; /* save off old link status information */ *li_old = *li; /* update current link status information */ li->link_speed = le16_to_cpu(link_data.link_speed); li->phy_type_low = le64_to_cpu(link_data.phy_type_low); li->phy_type_high = le64_to_cpu(link_data.phy_type_high); *hw_media_type = ice_get_media_type(pi); li->link_info = link_data.link_info; li->link_cfg_err = link_data.link_cfg_err; li->an_info = link_data.an_info; li->ext_info = link_data.ext_info; li->max_frame_size = le16_to_cpu(link_data.max_frame_size); li->fec_info = link_data.cfg & ICE_AQ_FEC_MASK; li->topo_media_conflict = link_data.topo_media_conflict; li->pacing = link_data.cfg & (ICE_AQ_CFG_PACING_M | ICE_AQ_CFG_PACING_TYPE_M); /* update fc info */ tx_pause = !!(link_data.an_info & ICE_AQ_LINK_PAUSE_TX); rx_pause = !!(link_data.an_info & ICE_AQ_LINK_PAUSE_RX); if (tx_pause && rx_pause) hw_fc_info->current_mode = ICE_FC_FULL; else if (tx_pause) hw_fc_info->current_mode = ICE_FC_TX_PAUSE; else if (rx_pause) hw_fc_info->current_mode = ICE_FC_RX_PAUSE; else hw_fc_info->current_mode = ICE_FC_NONE; li->lse_ena = !!(resp->cmd_flags & cpu_to_le16(ICE_AQ_LSE_IS_ENABLED)); ice_debug(hw, ICE_DBG_LINK, "get link info\n"); ice_debug(hw, ICE_DBG_LINK, " link_speed = 0x%x\n", li->link_speed); ice_debug(hw, ICE_DBG_LINK, " phy_type_low = 0x%llx\n", (unsigned long long)li->phy_type_low); ice_debug(hw, ICE_DBG_LINK, " phy_type_high = 0x%llx\n", (unsigned long long)li->phy_type_high); ice_debug(hw, ICE_DBG_LINK, " media_type = 0x%x\n", *hw_media_type); ice_debug(hw, ICE_DBG_LINK, " link_info = 0x%x\n", li->link_info); ice_debug(hw, ICE_DBG_LINK, " link_cfg_err = 0x%x\n", li->link_cfg_err); ice_debug(hw, ICE_DBG_LINK, " an_info = 0x%x\n", li->an_info); ice_debug(hw, ICE_DBG_LINK, " ext_info = 0x%x\n", li->ext_info); ice_debug(hw, ICE_DBG_LINK, " fec_info = 0x%x\n", li->fec_info); ice_debug(hw, ICE_DBG_LINK, " lse_ena = 0x%x\n", li->lse_ena); ice_debug(hw, ICE_DBG_LINK, " max_frame = 0x%x\n", li->max_frame_size); ice_debug(hw, ICE_DBG_LINK, " pacing = 0x%x\n", li->pacing); /* save link status information */ if (link) *link = *li; /* flag cleared so calling functions don't call AQ again */ pi->phy.get_link_info = false; return 0; } /** * ice_fill_tx_timer_and_fc_thresh * @hw: pointer to the HW struct * @cmd: pointer to MAC cfg structure * * Add Tx timer and FC refresh threshold info to Set MAC Config AQ command * descriptor */ static void ice_fill_tx_timer_and_fc_thresh(struct ice_hw *hw, struct ice_aqc_set_mac_cfg *cmd) { u16 fc_thres_val, tx_timer_val; u32 val; /* We read back the transmit timer and FC threshold value of * LFC. Thus, we will use index = * PRTMAC_HSEC_CTL_TX_PAUSE_QUANTA_MAX_INDEX. * * Also, because we are operating on transmit timer and FC * threshold of LFC, we don't turn on any bit in tx_tmr_priority */ #define IDX_OF_LFC PRTMAC_HSEC_CTL_TX_PAUSE_QUANTA_MAX_INDEX /* Retrieve the transmit timer */ val = rd32(hw, PRTMAC_HSEC_CTL_TX_PAUSE_QUANTA(IDX_OF_LFC)); tx_timer_val = val & PRTMAC_HSEC_CTL_TX_PAUSE_QUANTA_HSEC_CTL_TX_PAUSE_QUANTA_M; cmd->tx_tmr_value = cpu_to_le16(tx_timer_val); /* Retrieve the FC threshold */ val = rd32(hw, PRTMAC_HSEC_CTL_TX_PAUSE_REFRESH_TIMER(IDX_OF_LFC)); fc_thres_val = val & PRTMAC_HSEC_CTL_TX_PAUSE_REFRESH_TIMER_M; cmd->fc_refresh_threshold = cpu_to_le16(fc_thres_val); } /** * ice_aq_set_mac_cfg * @hw: pointer to the HW struct * @max_frame_size: Maximum Frame Size to be supported * @cd: pointer to command details structure or NULL * * Set MAC configuration (0x0603) */ int ice_aq_set_mac_cfg(struct ice_hw *hw, u16 max_frame_size, struct ice_sq_cd *cd) { struct ice_aqc_set_mac_cfg *cmd; struct ice_aq_desc desc; cmd = &desc.params.set_mac_cfg; if (max_frame_size == 0) return -EINVAL; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_set_mac_cfg); cmd->max_frame_size = cpu_to_le16(max_frame_size); ice_fill_tx_timer_and_fc_thresh(hw, cmd); return ice_aq_send_cmd(hw, &desc, NULL, 0, cd); } /** * ice_init_fltr_mgmt_struct - initializes filter management list and locks * @hw: pointer to the HW struct */ static int ice_init_fltr_mgmt_struct(struct ice_hw *hw) { struct ice_switch_info *sw; int status; hw->switch_info = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*hw->switch_info), GFP_KERNEL); sw = hw->switch_info; if (!sw) return -ENOMEM; INIT_LIST_HEAD(&sw->vsi_list_map_head); sw->prof_res_bm_init = 0; status = ice_init_def_sw_recp(hw); if (status) { devm_kfree(ice_hw_to_dev(hw), hw->switch_info); return status; } return 0; } /** * ice_cleanup_fltr_mgmt_struct - cleanup filter management list and locks * @hw: pointer to the HW struct */ static void ice_cleanup_fltr_mgmt_struct(struct ice_hw *hw) { struct ice_switch_info *sw = hw->switch_info; struct ice_vsi_list_map_info *v_pos_map; struct ice_vsi_list_map_info *v_tmp_map; struct ice_sw_recipe *recps; u8 i; list_for_each_entry_safe(v_pos_map, v_tmp_map, &sw->vsi_list_map_head, list_entry) { list_del(&v_pos_map->list_entry); devm_kfree(ice_hw_to_dev(hw), v_pos_map); } recps = sw->recp_list; for (i = 0; i < ICE_MAX_NUM_RECIPES; i++) { struct ice_recp_grp_entry *rg_entry, *tmprg_entry; recps[i].root_rid = i; list_for_each_entry_safe(rg_entry, tmprg_entry, &recps[i].rg_list, l_entry) { list_del(&rg_entry->l_entry); devm_kfree(ice_hw_to_dev(hw), rg_entry); } if (recps[i].adv_rule) { struct ice_adv_fltr_mgmt_list_entry *tmp_entry; struct ice_adv_fltr_mgmt_list_entry *lst_itr; mutex_destroy(&recps[i].filt_rule_lock); list_for_each_entry_safe(lst_itr, tmp_entry, &recps[i].filt_rules, list_entry) { list_del(&lst_itr->list_entry); devm_kfree(ice_hw_to_dev(hw), lst_itr->lkups); devm_kfree(ice_hw_to_dev(hw), lst_itr); } } else { struct ice_fltr_mgmt_list_entry *lst_itr, *tmp_entry; mutex_destroy(&recps[i].filt_rule_lock); list_for_each_entry_safe(lst_itr, tmp_entry, &recps[i].filt_rules, list_entry) { list_del(&lst_itr->list_entry); devm_kfree(ice_hw_to_dev(hw), lst_itr); } } devm_kfree(ice_hw_to_dev(hw), recps[i].root_buf); } ice_rm_all_sw_replay_rule_info(hw); devm_kfree(ice_hw_to_dev(hw), sw->recp_list); devm_kfree(ice_hw_to_dev(hw), sw); } /** * ice_get_fw_log_cfg - get FW logging configuration * @hw: pointer to the HW struct */ static int ice_get_fw_log_cfg(struct ice_hw *hw) { struct ice_aq_desc desc; __le16 *config; int status; u16 size; size = sizeof(*config) * ICE_AQC_FW_LOG_ID_MAX; config = kzalloc(size, GFP_KERNEL); if (!config) return -ENOMEM; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_fw_logging_info); status = ice_aq_send_cmd(hw, &desc, config, size, NULL); if (!status) { u16 i; /* Save FW logging information into the HW structure */ for (i = 0; i < ICE_AQC_FW_LOG_ID_MAX; i++) { u16 v, m, flgs; v = le16_to_cpu(config[i]); m = (v & ICE_AQC_FW_LOG_ID_M) >> ICE_AQC_FW_LOG_ID_S; flgs = (v & ICE_AQC_FW_LOG_EN_M) >> ICE_AQC_FW_LOG_EN_S; if (m < ICE_AQC_FW_LOG_ID_MAX) hw->fw_log.evnts[m].cur = flgs; } } kfree(config); return status; } /** * ice_cfg_fw_log - configure FW logging * @hw: pointer to the HW struct * @enable: enable certain FW logging events if true, disable all if false * * This function enables/disables the FW logging via Rx CQ events and a UART * port based on predetermined configurations. FW logging via the Rx CQ can be * enabled/disabled for individual PF's. However, FW logging via the UART can * only be enabled/disabled for all PFs on the same device. * * To enable overall FW logging, the "cq_en" and "uart_en" enable bits in * hw->fw_log need to be set accordingly, e.g. based on user-provided input, * before initializing the device. * * When re/configuring FW logging, callers need to update the "cfg" elements of * the hw->fw_log.evnts array with the desired logging event configurations for * modules of interest. When disabling FW logging completely, the callers can * just pass false in the "enable" parameter. On completion, the function will * update the "cur" element of the hw->fw_log.evnts array with the resulting * logging event configurations of the modules that are being re/configured. FW * logging modules that are not part of a reconfiguration operation retain their * previous states. * * Before resetting the device, it is recommended that the driver disables FW * logging before shutting down the control queue. When disabling FW logging * ("enable" = false), the latest configurations of FW logging events stored in * hw->fw_log.evnts[] are not overridden to allow them to be reconfigured after * a device reset. * * When enabling FW logging to emit log messages via the Rx CQ during the * device's initialization phase, a mechanism alternative to interrupt handlers * needs to be used to extract FW log messages from the Rx CQ periodically and * to prevent the Rx CQ from being full and stalling other types of control * messages from FW to SW. Interrupts are typically disabled during the device's * initialization phase. */ static int ice_cfg_fw_log(struct ice_hw *hw, bool enable) { struct ice_aqc_fw_logging *cmd; u16 i, chgs = 0, len = 0; struct ice_aq_desc desc; __le16 *data = NULL; u8 actv_evnts = 0; void *buf = NULL; int status = 0; if (!hw->fw_log.cq_en && !hw->fw_log.uart_en) return 0; /* Disable FW logging only when the control queue is still responsive */ if (!enable && (!hw->fw_log.actv_evnts || !ice_check_sq_alive(hw, &hw->adminq))) return 0; /* Get current FW log settings */ status = ice_get_fw_log_cfg(hw); if (status) return status; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_fw_logging); cmd = &desc.params.fw_logging; /* Indicate which controls are valid */ if (hw->fw_log.cq_en) cmd->log_ctrl_valid |= ICE_AQC_FW_LOG_AQ_VALID; if (hw->fw_log.uart_en) cmd->log_ctrl_valid |= ICE_AQC_FW_LOG_UART_VALID; if (enable) { /* Fill in an array of entries with FW logging modules and * logging events being reconfigured. */ for (i = 0; i < ICE_AQC_FW_LOG_ID_MAX; i++) { u16 val; /* Keep track of enabled event types */ actv_evnts |= hw->fw_log.evnts[i].cfg; if (hw->fw_log.evnts[i].cfg == hw->fw_log.evnts[i].cur) continue; if (!data) { data = devm_kcalloc(ice_hw_to_dev(hw), ICE_AQC_FW_LOG_ID_MAX, sizeof(*data), GFP_KERNEL); if (!data) return -ENOMEM; } val = i << ICE_AQC_FW_LOG_ID_S; val |= hw->fw_log.evnts[i].cfg << ICE_AQC_FW_LOG_EN_S; data[chgs++] = cpu_to_le16(val); } /* Only enable FW logging if at least one module is specified. * If FW logging is currently enabled but all modules are not * enabled to emit log messages, disable FW logging altogether. */ if (actv_evnts) { /* Leave if there is effectively no change */ if (!chgs) goto out; if (hw->fw_log.cq_en) cmd->log_ctrl |= ICE_AQC_FW_LOG_AQ_EN; if (hw->fw_log.uart_en) cmd->log_ctrl |= ICE_AQC_FW_LOG_UART_EN; buf = data; len = sizeof(*data) * chgs; desc.flags |= cpu_to_le16(ICE_AQ_FLAG_RD); } } status = ice_aq_send_cmd(hw, &desc, buf, len, NULL); if (!status) { /* Update the current configuration to reflect events enabled. * hw->fw_log.cq_en and hw->fw_log.uart_en indicate if the FW * logging mode is enabled for the device. They do not reflect * actual modules being enabled to emit log messages. So, their * values remain unchanged even when all modules are disabled. */ u16 cnt = enable ? chgs : (u16)ICE_AQC_FW_LOG_ID_MAX; hw->fw_log.actv_evnts = actv_evnts; for (i = 0; i < cnt; i++) { u16 v, m; if (!enable) { /* When disabling all FW logging events as part * of device's de-initialization, the original * configurations are retained, and can be used * to reconfigure FW logging later if the device * is re-initialized. */ hw->fw_log.evnts[i].cur = 0; continue; } v = le16_to_cpu(data[i]); m = (v & ICE_AQC_FW_LOG_ID_M) >> ICE_AQC_FW_LOG_ID_S; hw->fw_log.evnts[m].cur = hw->fw_log.evnts[m].cfg; } } out: devm_kfree(ice_hw_to_dev(hw), data); return status; } /** * ice_output_fw_log * @hw: pointer to the HW struct * @desc: pointer to the AQ message descriptor * @buf: pointer to the buffer accompanying the AQ message * * Formats a FW Log message and outputs it via the standard driver logs. */ void ice_output_fw_log(struct ice_hw *hw, struct ice_aq_desc *desc, void *buf) { ice_debug(hw, ICE_DBG_FW_LOG, "[ FW Log Msg Start ]\n"); ice_debug_array(hw, ICE_DBG_FW_LOG, 16, 1, (u8 *)buf, le16_to_cpu(desc->datalen)); ice_debug(hw, ICE_DBG_FW_LOG, "[ FW Log Msg End ]\n"); } /** * ice_get_itr_intrl_gran * @hw: pointer to the HW struct * * Determines the ITR/INTRL granularities based on the maximum aggregate * bandwidth according to the device's configuration during power-on. */ static void ice_get_itr_intrl_gran(struct ice_hw *hw) { u8 max_agg_bw = (rd32(hw, GL_PWR_MODE_CTL) & GL_PWR_MODE_CTL_CAR_MAX_BW_M) >> GL_PWR_MODE_CTL_CAR_MAX_BW_S; switch (max_agg_bw) { case ICE_MAX_AGG_BW_200G: case ICE_MAX_AGG_BW_100G: case ICE_MAX_AGG_BW_50G: hw->itr_gran = ICE_ITR_GRAN_ABOVE_25; hw->intrl_gran = ICE_INTRL_GRAN_ABOVE_25; break; case ICE_MAX_AGG_BW_25G: hw->itr_gran = ICE_ITR_GRAN_MAX_25; hw->intrl_gran = ICE_INTRL_GRAN_MAX_25; break; } } /** * ice_init_hw - main hardware initialization routine * @hw: pointer to the hardware structure */ int ice_init_hw(struct ice_hw *hw) { struct ice_aqc_get_phy_caps_data *pcaps; u16 mac_buf_len; void *mac_buf; int status; /* Set MAC type based on DeviceID */ status = ice_set_mac_type(hw); if (status) return status; hw->pf_id = (u8)(rd32(hw, PF_FUNC_RID) & PF_FUNC_RID_FUNC_NUM_M) >> PF_FUNC_RID_FUNC_NUM_S; status = ice_reset(hw, ICE_RESET_PFR); if (status) return status; ice_get_itr_intrl_gran(hw); status = ice_create_all_ctrlq(hw); if (status) goto err_unroll_cqinit; /* Enable FW logging. Not fatal if this fails. */ status = ice_cfg_fw_log(hw, true); if (status) ice_debug(hw, ICE_DBG_INIT, "Failed to enable FW logging.\n"); status = ice_clear_pf_cfg(hw); if (status) goto err_unroll_cqinit; /* Set bit to enable Flow Director filters */ wr32(hw, PFQF_FD_ENA, PFQF_FD_ENA_FD_ENA_M); INIT_LIST_HEAD(&hw->fdir_list_head); ice_clear_pxe_mode(hw); status = ice_init_nvm(hw); if (status) goto err_unroll_cqinit; status = ice_get_caps(hw); if (status) goto err_unroll_cqinit; if (!hw->port_info) hw->port_info = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*hw->port_info), GFP_KERNEL); if (!hw->port_info) { status = -ENOMEM; goto err_unroll_cqinit; } /* set the back pointer to HW */ hw->port_info->hw = hw; /* Initialize port_info struct with switch configuration data */ status = ice_get_initial_sw_cfg(hw); if (status) goto err_unroll_alloc; hw->evb_veb = true; /* init xarray for identifying scheduling nodes uniquely */ xa_init_flags(&hw->port_info->sched_node_ids, XA_FLAGS_ALLOC); /* Query the allocated resources for Tx scheduler */ status = ice_sched_query_res_alloc(hw); if (status) { ice_debug(hw, ICE_DBG_SCHED, "Failed to get scheduler allocated resources\n"); goto err_unroll_alloc; } ice_sched_get_psm_clk_freq(hw); /* Initialize port_info struct with scheduler data */ status = ice_sched_init_port(hw->port_info); if (status) goto err_unroll_sched; pcaps = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*pcaps), GFP_KERNEL); if (!pcaps) { status = -ENOMEM; goto err_unroll_sched; } /* Initialize port_info struct with PHY capabilities */ status = ice_aq_get_phy_caps(hw->port_info, false, ICE_AQC_REPORT_TOPO_CAP_MEDIA, pcaps, NULL); devm_kfree(ice_hw_to_dev(hw), pcaps); if (status) dev_warn(ice_hw_to_dev(hw), "Get PHY capabilities failed status = %d, continuing anyway\n", status); /* Initialize port_info struct with link information */ status = ice_aq_get_link_info(hw->port_info, false, NULL, NULL); if (status) goto err_unroll_sched; /* need a valid SW entry point to build a Tx tree */ if (!hw->sw_entry_point_layer) { ice_debug(hw, ICE_DBG_SCHED, "invalid sw entry point\n"); status = -EIO; goto err_unroll_sched; } INIT_LIST_HEAD(&hw->agg_list); /* Initialize max burst size */ if (!hw->max_burst_size) ice_cfg_rl_burst_size(hw, ICE_SCHED_DFLT_BURST_SIZE); status = ice_init_fltr_mgmt_struct(hw); if (status) goto err_unroll_sched; /* Get MAC information */ /* A single port can report up to two (LAN and WoL) addresses */ mac_buf = devm_kcalloc(ice_hw_to_dev(hw), 2, sizeof(struct ice_aqc_manage_mac_read_resp), GFP_KERNEL); mac_buf_len = 2 * sizeof(struct ice_aqc_manage_mac_read_resp); if (!mac_buf) { status = -ENOMEM; goto err_unroll_fltr_mgmt_struct; } status = ice_aq_manage_mac_read(hw, mac_buf, mac_buf_len, NULL); devm_kfree(ice_hw_to_dev(hw), mac_buf); if (status) goto err_unroll_fltr_mgmt_struct; /* enable jumbo frame support at MAC level */ status = ice_aq_set_mac_cfg(hw, ICE_AQ_SET_MAC_FRAME_SIZE_MAX, NULL); if (status) goto err_unroll_fltr_mgmt_struct; /* Obtain counter base index which would be used by flow director */ status = ice_alloc_fd_res_cntr(hw, &hw->fd_ctr_base); if (status) goto err_unroll_fltr_mgmt_struct; status = ice_init_hw_tbls(hw); if (status) goto err_unroll_fltr_mgmt_struct; mutex_init(&hw->tnl_lock); return 0; err_unroll_fltr_mgmt_struct: ice_cleanup_fltr_mgmt_struct(hw); err_unroll_sched: ice_sched_cleanup_all(hw); err_unroll_alloc: devm_kfree(ice_hw_to_dev(hw), hw->port_info); err_unroll_cqinit: ice_destroy_all_ctrlq(hw); return status; } /** * ice_deinit_hw - unroll initialization operations done by ice_init_hw * @hw: pointer to the hardware structure * * This should be called only during nominal operation, not as a result of * ice_init_hw() failing since ice_init_hw() will take care of unrolling * applicable initializations if it fails for any reason. */ void ice_deinit_hw(struct ice_hw *hw) { ice_free_fd_res_cntr(hw, hw->fd_ctr_base); ice_cleanup_fltr_mgmt_struct(hw); ice_sched_cleanup_all(hw); ice_sched_clear_agg(hw); ice_free_seg(hw); ice_free_hw_tbls(hw); mutex_destroy(&hw->tnl_lock); /* Attempt to disable FW logging before shutting down control queues */ ice_cfg_fw_log(hw, false); ice_destroy_all_ctrlq(hw); /* Clear VSI contexts if not already cleared */ ice_clear_all_vsi_ctx(hw); } /** * ice_check_reset - Check to see if a global reset is complete * @hw: pointer to the hardware structure */ int ice_check_reset(struct ice_hw *hw) { u32 cnt, reg = 0, grst_timeout, uld_mask; /* Poll for Device Active state in case a recent CORER, GLOBR, * or EMPR has occurred. The grst delay value is in 100ms units. * Add 1sec for outstanding AQ commands that can take a long time. */ grst_timeout = ((rd32(hw, GLGEN_RSTCTL) & GLGEN_RSTCTL_GRSTDEL_M) >> GLGEN_RSTCTL_GRSTDEL_S) + 10; for (cnt = 0; cnt < grst_timeout; cnt++) { mdelay(100); reg = rd32(hw, GLGEN_RSTAT); if (!(reg & GLGEN_RSTAT_DEVSTATE_M)) break; } if (cnt == grst_timeout) { ice_debug(hw, ICE_DBG_INIT, "Global reset polling failed to complete.\n"); return -EIO; } #define ICE_RESET_DONE_MASK (GLNVM_ULD_PCIER_DONE_M |\ GLNVM_ULD_PCIER_DONE_1_M |\ GLNVM_ULD_CORER_DONE_M |\ GLNVM_ULD_GLOBR_DONE_M |\ GLNVM_ULD_POR_DONE_M |\ GLNVM_ULD_POR_DONE_1_M |\ GLNVM_ULD_PCIER_DONE_2_M) uld_mask = ICE_RESET_DONE_MASK | (hw->func_caps.common_cap.rdma ? GLNVM_ULD_PE_DONE_M : 0); /* Device is Active; check Global Reset processes are done */ for (cnt = 0; cnt < ICE_PF_RESET_WAIT_COUNT; cnt++) { reg = rd32(hw, GLNVM_ULD) & uld_mask; if (reg == uld_mask) { ice_debug(hw, ICE_DBG_INIT, "Global reset processes done. %d\n", cnt); break; } mdelay(10); } if (cnt == ICE_PF_RESET_WAIT_COUNT) { ice_debug(hw, ICE_DBG_INIT, "Wait for Reset Done timed out. GLNVM_ULD = 0x%x\n", reg); return -EIO; } return 0; } /** * ice_pf_reset - Reset the PF * @hw: pointer to the hardware structure * * If a global reset has been triggered, this function checks * for its completion and then issues the PF reset */ static int ice_pf_reset(struct ice_hw *hw) { u32 cnt, reg; /* If at function entry a global reset was already in progress, i.e. * state is not 'device active' or any of the reset done bits are not * set in GLNVM_ULD, there is no need for a PF Reset; poll until the * global reset is done. */ if ((rd32(hw, GLGEN_RSTAT) & GLGEN_RSTAT_DEVSTATE_M) || (rd32(hw, GLNVM_ULD) & ICE_RESET_DONE_MASK) ^ ICE_RESET_DONE_MASK) { /* poll on global reset currently in progress until done */ if (ice_check_reset(hw)) return -EIO; return 0; } /* Reset the PF */ reg = rd32(hw, PFGEN_CTRL); wr32(hw, PFGEN_CTRL, (reg | PFGEN_CTRL_PFSWR_M)); /* Wait for the PFR to complete. The wait time is the global config lock * timeout plus the PFR timeout which will account for a possible reset * that is occurring during a download package operation. */ for (cnt = 0; cnt < ICE_GLOBAL_CFG_LOCK_TIMEOUT + ICE_PF_RESET_WAIT_COUNT; cnt++) { reg = rd32(hw, PFGEN_CTRL); if (!(reg & PFGEN_CTRL_PFSWR_M)) break; mdelay(1); } if (cnt == ICE_PF_RESET_WAIT_COUNT) { ice_debug(hw, ICE_DBG_INIT, "PF reset polling failed to complete.\n"); return -EIO; } return 0; } /** * ice_reset - Perform different types of reset * @hw: pointer to the hardware structure * @req: reset request * * This function triggers a reset as specified by the req parameter. * * Note: * If anything other than a PF reset is triggered, PXE mode is restored. * This has to be cleared using ice_clear_pxe_mode again, once the AQ * interface has been restored in the rebuild flow. */ int ice_reset(struct ice_hw *hw, enum ice_reset_req req) { u32 val = 0; switch (req) { case ICE_RESET_PFR: return ice_pf_reset(hw); case ICE_RESET_CORER: ice_debug(hw, ICE_DBG_INIT, "CoreR requested\n"); val = GLGEN_RTRIG_CORER_M; break; case ICE_RESET_GLOBR: ice_debug(hw, ICE_DBG_INIT, "GlobalR requested\n"); val = GLGEN_RTRIG_GLOBR_M; break; default: return -EINVAL; } val |= rd32(hw, GLGEN_RTRIG); wr32(hw, GLGEN_RTRIG, val); ice_flush(hw); /* wait for the FW to be ready */ return ice_check_reset(hw); } /** * ice_copy_rxq_ctx_to_hw * @hw: pointer to the hardware structure * @ice_rxq_ctx: pointer to the rxq context * @rxq_index: the index of the Rx queue * * Copies rxq context from dense structure to HW register space */ static int ice_copy_rxq_ctx_to_hw(struct ice_hw *hw, u8 *ice_rxq_ctx, u32 rxq_index) { u8 i; if (!ice_rxq_ctx) return -EINVAL; if (rxq_index > QRX_CTRL_MAX_INDEX) return -EINVAL; /* Copy each dword separately to HW */ for (i = 0; i < ICE_RXQ_CTX_SIZE_DWORDS; i++) { wr32(hw, QRX_CONTEXT(i, rxq_index), *((u32 *)(ice_rxq_ctx + (i * sizeof(u32))))); ice_debug(hw, ICE_DBG_QCTX, "qrxdata[%d]: %08X\n", i, *((u32 *)(ice_rxq_ctx + (i * sizeof(u32))))); } return 0; } /* LAN Rx Queue Context */ static const struct ice_ctx_ele ice_rlan_ctx_info[] = { /* Field Width LSB */ ICE_CTX_STORE(ice_rlan_ctx, head, 13, 0), ICE_CTX_STORE(ice_rlan_ctx, cpuid, 8, 13), ICE_CTX_STORE(ice_rlan_ctx, base, 57, 32), ICE_CTX_STORE(ice_rlan_ctx, qlen, 13, 89), ICE_CTX_STORE(ice_rlan_ctx, dbuf, 7, 102), ICE_CTX_STORE(ice_rlan_ctx, hbuf, 5, 109), ICE_CTX_STORE(ice_rlan_ctx, dtype, 2, 114), ICE_CTX_STORE(ice_rlan_ctx, dsize, 1, 116), ICE_CTX_STORE(ice_rlan_ctx, crcstrip, 1, 117), ICE_CTX_STORE(ice_rlan_ctx, l2tsel, 1, 119), ICE_CTX_STORE(ice_rlan_ctx, hsplit_0, 4, 120), ICE_CTX_STORE(ice_rlan_ctx, hsplit_1, 2, 124), ICE_CTX_STORE(ice_rlan_ctx, showiv, 1, 127), ICE_CTX_STORE(ice_rlan_ctx, rxmax, 14, 174), ICE_CTX_STORE(ice_rlan_ctx, tphrdesc_ena, 1, 193), ICE_CTX_STORE(ice_rlan_ctx, tphwdesc_ena, 1, 194), ICE_CTX_STORE(ice_rlan_ctx, tphdata_ena, 1, 195), ICE_CTX_STORE(ice_rlan_ctx, tphhead_ena, 1, 196), ICE_CTX_STORE(ice_rlan_ctx, lrxqthresh, 3, 198), ICE_CTX_STORE(ice_rlan_ctx, prefena, 1, 201), { 0 } }; /** * ice_write_rxq_ctx * @hw: pointer to the hardware structure * @rlan_ctx: pointer to the rxq context * @rxq_index: the index of the Rx queue * * Converts rxq context from sparse to dense structure and then writes * it to HW register space and enables the hardware to prefetch descriptors * instead of only fetching them on demand */ int ice_write_rxq_ctx(struct ice_hw *hw, struct ice_rlan_ctx *rlan_ctx, u32 rxq_index) { u8 ctx_buf[ICE_RXQ_CTX_SZ] = { 0 }; if (!rlan_ctx) return -EINVAL; rlan_ctx->prefena = 1; ice_set_ctx(hw, (u8 *)rlan_ctx, ctx_buf, ice_rlan_ctx_info); return ice_copy_rxq_ctx_to_hw(hw, ctx_buf, rxq_index); } /* LAN Tx Queue Context */ const struct ice_ctx_ele ice_tlan_ctx_info[] = { /* Field Width LSB */ ICE_CTX_STORE(ice_tlan_ctx, base, 57, 0), ICE_CTX_STORE(ice_tlan_ctx, port_num, 3, 57), ICE_CTX_STORE(ice_tlan_ctx, cgd_num, 5, 60), ICE_CTX_STORE(ice_tlan_ctx, pf_num, 3, 65), ICE_CTX_STORE(ice_tlan_ctx, vmvf_num, 10, 68), ICE_CTX_STORE(ice_tlan_ctx, vmvf_type, 2, 78), ICE_CTX_STORE(ice_tlan_ctx, src_vsi, 10, 80), ICE_CTX_STORE(ice_tlan_ctx, tsyn_ena, 1, 90), ICE_CTX_STORE(ice_tlan_ctx, internal_usage_flag, 1, 91), ICE_CTX_STORE(ice_tlan_ctx, alt_vlan, 1, 92), ICE_CTX_STORE(ice_tlan_ctx, cpuid, 8, 93), ICE_CTX_STORE(ice_tlan_ctx, wb_mode, 1, 101), ICE_CTX_STORE(ice_tlan_ctx, tphrd_desc, 1, 102), ICE_CTX_STORE(ice_tlan_ctx, tphrd, 1, 103), ICE_CTX_STORE(ice_tlan_ctx, tphwr_desc, 1, 104), ICE_CTX_STORE(ice_tlan_ctx, cmpq_id, 9, 105), ICE_CTX_STORE(ice_tlan_ctx, qnum_in_func, 14, 114), ICE_CTX_STORE(ice_tlan_ctx, itr_notification_mode, 1, 128), ICE_CTX_STORE(ice_tlan_ctx, adjust_prof_id, 6, 129), ICE_CTX_STORE(ice_tlan_ctx, qlen, 13, 135), ICE_CTX_STORE(ice_tlan_ctx, quanta_prof_idx, 4, 148), ICE_CTX_STORE(ice_tlan_ctx, tso_ena, 1, 152), ICE_CTX_STORE(ice_tlan_ctx, tso_qnum, 11, 153), ICE_CTX_STORE(ice_tlan_ctx, legacy_int, 1, 164), ICE_CTX_STORE(ice_tlan_ctx, drop_ena, 1, 165), ICE_CTX_STORE(ice_tlan_ctx, cache_prof_idx, 2, 166), ICE_CTX_STORE(ice_tlan_ctx, pkt_shaper_prof_idx, 3, 168), ICE_CTX_STORE(ice_tlan_ctx, int_q_state, 122, 171), { 0 } }; /* Sideband Queue command wrappers */ /** * ice_sbq_send_cmd - send Sideband Queue command to Sideband Queue * @hw: pointer to the HW struct * @desc: descriptor describing the command * @buf: buffer to use for indirect commands (NULL for direct commands) * @buf_size: size of buffer for indirect commands (0 for direct commands) * @cd: pointer to command details structure */ static int ice_sbq_send_cmd(struct ice_hw *hw, struct ice_sbq_cmd_desc *desc, void *buf, u16 buf_size, struct ice_sq_cd *cd) { return ice_sq_send_cmd(hw, ice_get_sbq(hw), (struct ice_aq_desc *)desc, buf, buf_size, cd); } /** * ice_sbq_rw_reg - Fill Sideband Queue command * @hw: pointer to the HW struct * @in: message info to be filled in descriptor */ int ice_sbq_rw_reg(struct ice_hw *hw, struct ice_sbq_msg_input *in) { struct ice_sbq_cmd_desc desc = {0}; struct ice_sbq_msg_req msg = {0}; u16 msg_len; int status; msg_len = sizeof(msg); msg.dest_dev = in->dest_dev; msg.opcode = in->opcode; msg.flags = ICE_SBQ_MSG_FLAGS; msg.sbe_fbe = ICE_SBQ_MSG_SBE_FBE; msg.msg_addr_low = cpu_to_le16(in->msg_addr_low); msg.msg_addr_high = cpu_to_le32(in->msg_addr_high); if (in->opcode) msg.data = cpu_to_le32(in->data); else /* data read comes back in completion, so shorten the struct by * sizeof(msg.data) */ msg_len -= sizeof(msg.data); desc.flags = cpu_to_le16(ICE_AQ_FLAG_RD); desc.opcode = cpu_to_le16(ice_sbq_opc_neigh_dev_req); desc.param0.cmd_len = cpu_to_le16(msg_len); status = ice_sbq_send_cmd(hw, &desc, &msg, msg_len, NULL); if (!status && !in->opcode) in->data = le32_to_cpu (((struct ice_sbq_msg_cmpl *)&msg)->data); return status; } /* FW Admin Queue command wrappers */ /* Software lock/mutex that is meant to be held while the Global Config Lock * in firmware is acquired by the software to prevent most (but not all) types * of AQ commands from being sent to FW */ DEFINE_MUTEX(ice_global_cfg_lock_sw); /** * ice_should_retry_sq_send_cmd * @opcode: AQ opcode * * Decide if we should retry the send command routine for the ATQ, depending * on the opcode. */ static bool ice_should_retry_sq_send_cmd(u16 opcode) { switch (opcode) { case ice_aqc_opc_get_link_topo: case ice_aqc_opc_lldp_stop: case ice_aqc_opc_lldp_start: case ice_aqc_opc_lldp_filter_ctrl: return true; } return false; } /** * ice_sq_send_cmd_retry - send command to Control Queue (ATQ) * @hw: pointer to the HW struct * @cq: pointer to the specific Control queue * @desc: prefilled descriptor describing the command * @buf: buffer to use for indirect commands (or NULL for direct commands) * @buf_size: size of buffer for indirect commands (or 0 for direct commands) * @cd: pointer to command details structure * * Retry sending the FW Admin Queue command, multiple times, to the FW Admin * Queue if the EBUSY AQ error is returned. */ static int ice_sq_send_cmd_retry(struct ice_hw *hw, struct ice_ctl_q_info *cq, struct ice_aq_desc *desc, void *buf, u16 buf_size, struct ice_sq_cd *cd) { struct ice_aq_desc desc_cpy; bool is_cmd_for_retry; u8 idx = 0; u16 opcode; int status; opcode = le16_to_cpu(desc->opcode); is_cmd_for_retry = ice_should_retry_sq_send_cmd(opcode); memset(&desc_cpy, 0, sizeof(desc_cpy)); if (is_cmd_for_retry) { /* All retryable cmds are direct, without buf. */ WARN_ON(buf); memcpy(&desc_cpy, desc, sizeof(desc_cpy)); } do { status = ice_sq_send_cmd(hw, cq, desc, buf, buf_size, cd); if (!is_cmd_for_retry || !status || hw->adminq.sq_last_status != ICE_AQ_RC_EBUSY) break; memcpy(desc, &desc_cpy, sizeof(desc_cpy)); msleep(ICE_SQ_SEND_DELAY_TIME_MS); } while (++idx < ICE_SQ_SEND_MAX_EXECUTE); return status; } /** * ice_aq_send_cmd - send FW Admin Queue command to FW Admin Queue * @hw: pointer to the HW struct * @desc: descriptor describing the command * @buf: buffer to use for indirect commands (NULL for direct commands) * @buf_size: size of buffer for indirect commands (0 for direct commands) * @cd: pointer to command details structure * * Helper function to send FW Admin Queue commands to the FW Admin Queue. */ int ice_aq_send_cmd(struct ice_hw *hw, struct ice_aq_desc *desc, void *buf, u16 buf_size, struct ice_sq_cd *cd) { struct ice_aqc_req_res *cmd = &desc->params.res_owner; bool lock_acquired = false; int status; /* When a package download is in process (i.e. when the firmware's * Global Configuration Lock resource is held), only the Download * Package, Get Version, Get Package Info List, Upload Section, * Update Package, Set Port Parameters, Get/Set VLAN Mode Parameters, * Add Recipe, Set Recipes to Profile Association, Get Recipe, and Get * Recipes to Profile Association, and Release Resource (with resource * ID set to Global Config Lock) AdminQ commands are allowed; all others * must block until the package download completes and the Global Config * Lock is released. See also ice_acquire_global_cfg_lock(). */ switch (le16_to_cpu(desc->opcode)) { case ice_aqc_opc_download_pkg: case ice_aqc_opc_get_pkg_info_list: case ice_aqc_opc_get_ver: case ice_aqc_opc_upload_section: case ice_aqc_opc_update_pkg: case ice_aqc_opc_set_port_params: case ice_aqc_opc_get_vlan_mode_parameters: case ice_aqc_opc_set_vlan_mode_parameters: case ice_aqc_opc_add_recipe: case ice_aqc_opc_recipe_to_profile: case ice_aqc_opc_get_recipe: case ice_aqc_opc_get_recipe_to_profile: break; case ice_aqc_opc_release_res: if (le16_to_cpu(cmd->res_id) == ICE_AQC_RES_ID_GLBL_LOCK) break; fallthrough; default: mutex_lock(&ice_global_cfg_lock_sw); lock_acquired = true; break; } status = ice_sq_send_cmd_retry(hw, &hw->adminq, desc, buf, buf_size, cd); if (lock_acquired) mutex_unlock(&ice_global_cfg_lock_sw); return status; } /** * ice_aq_get_fw_ver * @hw: pointer to the HW struct * @cd: pointer to command details structure or NULL * * Get the firmware version (0x0001) from the admin queue commands */ int ice_aq_get_fw_ver(struct ice_hw *hw, struct ice_sq_cd *cd) { struct ice_aqc_get_ver *resp; struct ice_aq_desc desc; int status; resp = &desc.params.get_ver; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_get_ver); status = ice_aq_send_cmd(hw, &desc, NULL, 0, cd); if (!status) { hw->fw_branch = resp->fw_branch; hw->fw_maj_ver = resp->fw_major; hw->fw_min_ver = resp->fw_minor; hw->fw_patch = resp->fw_patch; hw->fw_build = le32_to_cpu(resp->fw_build); hw->api_branch = resp->api_branch; hw->api_maj_ver = resp->api_major; hw->api_min_ver = resp->api_minor; hw->api_patch = resp->api_patch; } return status; } /** * ice_aq_send_driver_ver * @hw: pointer to the HW struct * @dv: driver's major, minor version * @cd: pointer to command details structure or NULL * * Send the driver version (0x0002) to the firmware */ int ice_aq_send_driver_ver(struct ice_hw *hw, struct ice_driver_ver *dv, struct ice_sq_cd *cd) { struct ice_aqc_driver_ver *cmd; struct ice_aq_desc desc; u16 len; cmd = &desc.params.driver_ver; if (!dv) return -EINVAL; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_driver_ver); desc.flags |= cpu_to_le16(ICE_AQ_FLAG_RD); cmd->major_ver = dv->major_ver; cmd->minor_ver = dv->minor_ver; cmd->build_ver = dv->build_ver; cmd->subbuild_ver = dv->subbuild_ver; len = 0; while (len < sizeof(dv->driver_string) && isascii(dv->driver_string[len]) && dv->driver_string[len]) len++; return ice_aq_send_cmd(hw, &desc, dv->driver_string, len, cd); } /** * ice_aq_q_shutdown * @hw: pointer to the HW struct * @unloading: is the driver unloading itself * * Tell the Firmware that we're shutting down the AdminQ and whether * or not the driver is unloading as well (0x0003). */ int ice_aq_q_shutdown(struct ice_hw *hw, bool unloading) { struct ice_aqc_q_shutdown *cmd; struct ice_aq_desc desc; cmd = &desc.params.q_shutdown; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_q_shutdown); if (unloading) cmd->driver_unloading = ICE_AQC_DRIVER_UNLOADING; return ice_aq_send_cmd(hw, &desc, NULL, 0, NULL); } /** * ice_aq_req_res * @hw: pointer to the HW struct * @res: resource ID * @access: access type * @sdp_number: resource number * @timeout: the maximum time in ms that the driver may hold the resource * @cd: pointer to command details structure or NULL * * Requests common resource using the admin queue commands (0x0008). * When attempting to acquire the Global Config Lock, the driver can * learn of three states: * 1) 0 - acquired lock, and can perform download package * 2) -EIO - did not get lock, driver should fail to load * 3) -EALREADY - did not get lock, but another driver has * successfully downloaded the package; the driver does * not have to download the package and can continue * loading * * Note that if the caller is in an acquire lock, perform action, release lock * phase of operation, it is possible that the FW may detect a timeout and issue * a CORER. In this case, the driver will receive a CORER interrupt and will * have to determine its cause. The calling thread that is handling this flow * will likely get an error propagated back to it indicating the Download * Package, Update Package or the Release Resource AQ commands timed out. */ static int ice_aq_req_res(struct ice_hw *hw, enum ice_aq_res_ids res, enum ice_aq_res_access_type access, u8 sdp_number, u32 *timeout, struct ice_sq_cd *cd) { struct ice_aqc_req_res *cmd_resp; struct ice_aq_desc desc; int status; cmd_resp = &desc.params.res_owner; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_req_res); cmd_resp->res_id = cpu_to_le16(res); cmd_resp->access_type = cpu_to_le16(access); cmd_resp->res_number = cpu_to_le32(sdp_number); cmd_resp->timeout = cpu_to_le32(*timeout); *timeout = 0; status = ice_aq_send_cmd(hw, &desc, NULL, 0, cd); /* The completion specifies the maximum time in ms that the driver * may hold the resource in the Timeout field. */ /* Global config lock response utilizes an additional status field. * * If the Global config lock resource is held by some other driver, the * command completes with ICE_AQ_RES_GLBL_IN_PROG in the status field * and the timeout field indicates the maximum time the current owner * of the resource has to free it. */ if (res == ICE_GLOBAL_CFG_LOCK_RES_ID) { if (le16_to_cpu(cmd_resp->status) == ICE_AQ_RES_GLBL_SUCCESS) { *timeout = le32_to_cpu(cmd_resp->timeout); return 0; } else if (le16_to_cpu(cmd_resp->status) == ICE_AQ_RES_GLBL_IN_PROG) { *timeout = le32_to_cpu(cmd_resp->timeout); return -EIO; } else if (le16_to_cpu(cmd_resp->status) == ICE_AQ_RES_GLBL_DONE) { return -EALREADY; } /* invalid FW response, force a timeout immediately */ *timeout = 0; return -EIO; } /* If the resource is held by some other driver, the command completes * with a busy return value and the timeout field indicates the maximum * time the current owner of the resource has to free it. */ if (!status || hw->adminq.sq_last_status == ICE_AQ_RC_EBUSY) *timeout = le32_to_cpu(cmd_resp->timeout); return status; } /** * ice_aq_release_res * @hw: pointer to the HW struct * @res: resource ID * @sdp_number: resource number * @cd: pointer to command details structure or NULL * * release common resource using the admin queue commands (0x0009) */ static int ice_aq_release_res(struct ice_hw *hw, enum ice_aq_res_ids res, u8 sdp_number, struct ice_sq_cd *cd) { struct ice_aqc_req_res *cmd; struct ice_aq_desc desc; cmd = &desc.params.res_owner; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_release_res); cmd->res_id = cpu_to_le16(res); cmd->res_number = cpu_to_le32(sdp_number); return ice_aq_send_cmd(hw, &desc, NULL, 0, cd); } /** * ice_acquire_res * @hw: pointer to the HW structure * @res: resource ID * @access: access type (read or write) * @timeout: timeout in milliseconds * * This function will attempt to acquire the ownership of a resource. */ int ice_acquire_res(struct ice_hw *hw, enum ice_aq_res_ids res, enum ice_aq_res_access_type access, u32 timeout) { #define ICE_RES_POLLING_DELAY_MS 10 u32 delay = ICE_RES_POLLING_DELAY_MS; u32 time_left = timeout; int status; status = ice_aq_req_res(hw, res, access, 0, &time_left, NULL); /* A return code of -EALREADY means that another driver has * previously acquired the resource and performed any necessary updates; * in this case the caller does not obtain the resource and has no * further work to do. */ if (status == -EALREADY) goto ice_acquire_res_exit; if (status) ice_debug(hw, ICE_DBG_RES, "resource %d acquire type %d failed.\n", res, access); /* If necessary, poll until the current lock owner timeouts */ timeout = time_left; while (status && timeout && time_left) { mdelay(delay); timeout = (timeout > delay) ? timeout - delay : 0; status = ice_aq_req_res(hw, res, access, 0, &time_left, NULL); if (status == -EALREADY) /* lock free, but no work to do */ break; if (!status) /* lock acquired */ break; } if (status && status != -EALREADY) ice_debug(hw, ICE_DBG_RES, "resource acquire timed out.\n"); ice_acquire_res_exit: if (status == -EALREADY) { if (access == ICE_RES_WRITE) ice_debug(hw, ICE_DBG_RES, "resource indicates no work to do.\n"); else ice_debug(hw, ICE_DBG_RES, "Warning: -EALREADY not expected\n"); } return status; } /** * ice_release_res * @hw: pointer to the HW structure * @res: resource ID * * This function will release a resource using the proper Admin Command. */ void ice_release_res(struct ice_hw *hw, enum ice_aq_res_ids res) { unsigned long timeout; int status; /* there are some rare cases when trying to release the resource * results in an admin queue timeout, so handle them correctly */ timeout = jiffies + 10 * ICE_CTL_Q_SQ_CMD_TIMEOUT; do { status = ice_aq_release_res(hw, res, 0, NULL); if (status != -EIO) break; usleep_range(1000, 2000); } while (time_before(jiffies, timeout)); } /** * ice_aq_alloc_free_res - command to allocate/free resources * @hw: pointer to the HW struct * @buf: Indirect buffer to hold data parameters and response * @buf_size: size of buffer for indirect commands * @opc: pass in the command opcode * * Helper function to allocate/free resources using the admin queue commands */ int ice_aq_alloc_free_res(struct ice_hw *hw, struct ice_aqc_alloc_free_res_elem *buf, u16 buf_size, enum ice_adminq_opc opc) { struct ice_aqc_alloc_free_res_cmd *cmd; struct ice_aq_desc desc; cmd = &desc.params.sw_res_ctrl; if (!buf || buf_size < flex_array_size(buf, elem, 1)) return -EINVAL; ice_fill_dflt_direct_cmd_desc(&desc, opc); desc.flags |= cpu_to_le16(ICE_AQ_FLAG_RD); cmd->num_entries = cpu_to_le16(1); return ice_aq_send_cmd(hw, &desc, buf, buf_size, NULL); } /** * ice_alloc_hw_res - allocate resource * @hw: pointer to the HW struct * @type: type of resource * @num: number of resources to allocate * @btm: allocate from bottom * @res: pointer to array that will receive the resources */ int ice_alloc_hw_res(struct ice_hw *hw, u16 type, u16 num, bool btm, u16 *res) { struct ice_aqc_alloc_free_res_elem *buf; u16 buf_len; int status; buf_len = struct_size(buf, elem, num); buf = kzalloc(buf_len, GFP_KERNEL); if (!buf) return -ENOMEM; /* Prepare buffer to allocate resource. */ buf->num_elems = cpu_to_le16(num); buf->res_type = cpu_to_le16(type | ICE_AQC_RES_TYPE_FLAG_DEDICATED | ICE_AQC_RES_TYPE_FLAG_IGNORE_INDEX); if (btm) buf->res_type |= cpu_to_le16(ICE_AQC_RES_TYPE_FLAG_SCAN_BOTTOM); status = ice_aq_alloc_free_res(hw, buf, buf_len, ice_aqc_opc_alloc_res); if (status) goto ice_alloc_res_exit; memcpy(res, buf->elem, sizeof(*buf->elem) * num); ice_alloc_res_exit: kfree(buf); return status; } /** * ice_free_hw_res - free allocated HW resource * @hw: pointer to the HW struct * @type: type of resource to free * @num: number of resources * @res: pointer to array that contains the resources to free */ int ice_free_hw_res(struct ice_hw *hw, u16 type, u16 num, u16 *res) { struct ice_aqc_alloc_free_res_elem *buf; u16 buf_len; int status; buf_len = struct_size(buf, elem, num); buf = kzalloc(buf_len, GFP_KERNEL); if (!buf) return -ENOMEM; /* Prepare buffer to free resource. */ buf->num_elems = cpu_to_le16(num); buf->res_type = cpu_to_le16(type); memcpy(buf->elem, res, sizeof(*buf->elem) * num); status = ice_aq_alloc_free_res(hw, buf, buf_len, ice_aqc_opc_free_res); if (status) ice_debug(hw, ICE_DBG_SW, "CQ CMD Buffer:\n"); kfree(buf); return status; } /** * ice_get_num_per_func - determine number of resources per PF * @hw: pointer to the HW structure * @max: value to be evenly split between each PF * * Determine the number of valid functions by going through the bitmap returned * from parsing capabilities and use this to calculate the number of resources * per PF based on the max value passed in. */ static u32 ice_get_num_per_func(struct ice_hw *hw, u32 max) { u8 funcs; #define ICE_CAPS_VALID_FUNCS_M 0xFF funcs = hweight8(hw->dev_caps.common_cap.valid_functions & ICE_CAPS_VALID_FUNCS_M); if (!funcs) return 0; return max / funcs; } /** * ice_parse_common_caps - parse common device/function capabilities * @hw: pointer to the HW struct * @caps: pointer to common capabilities structure * @elem: the capability element to parse * @prefix: message prefix for tracing capabilities * * Given a capability element, extract relevant details into the common * capability structure. * * Returns: true if the capability matches one of the common capability ids, * false otherwise. */ static bool ice_parse_common_caps(struct ice_hw *hw, struct ice_hw_common_caps *caps, struct ice_aqc_list_caps_elem *elem, const char *prefix) { u32 logical_id = le32_to_cpu(elem->logical_id); u32 phys_id = le32_to_cpu(elem->phys_id); u32 number = le32_to_cpu(elem->number); u16 cap = le16_to_cpu(elem->cap); bool found = true; switch (cap) { case ICE_AQC_CAPS_VALID_FUNCTIONS: caps->valid_functions = number; ice_debug(hw, ICE_DBG_INIT, "%s: valid_functions (bitmap) = %d\n", prefix, caps->valid_functions); break; case ICE_AQC_CAPS_SRIOV: caps->sr_iov_1_1 = (number == 1); ice_debug(hw, ICE_DBG_INIT, "%s: sr_iov_1_1 = %d\n", prefix, caps->sr_iov_1_1); break; case ICE_AQC_CAPS_DCB: caps->dcb = (number == 1); caps->active_tc_bitmap = logical_id; caps->maxtc = phys_id; ice_debug(hw, ICE_DBG_INIT, "%s: dcb = %d\n", prefix, caps->dcb); ice_debug(hw, ICE_DBG_INIT, "%s: active_tc_bitmap = %d\n", prefix, caps->active_tc_bitmap); ice_debug(hw, ICE_DBG_INIT, "%s: maxtc = %d\n", prefix, caps->maxtc); break; case ICE_AQC_CAPS_RSS: caps->rss_table_size = number; caps->rss_table_entry_width = logical_id; ice_debug(hw, ICE_DBG_INIT, "%s: rss_table_size = %d\n", prefix, caps->rss_table_size); ice_debug(hw, ICE_DBG_INIT, "%s: rss_table_entry_width = %d\n", prefix, caps->rss_table_entry_width); break; case ICE_AQC_CAPS_RXQS: caps->num_rxq = number; caps->rxq_first_id = phys_id; ice_debug(hw, ICE_DBG_INIT, "%s: num_rxq = %d\n", prefix, caps->num_rxq); ice_debug(hw, ICE_DBG_INIT, "%s: rxq_first_id = %d\n", prefix, caps->rxq_first_id); break; case ICE_AQC_CAPS_TXQS: caps->num_txq = number; caps->txq_first_id = phys_id; ice_debug(hw, ICE_DBG_INIT, "%s: num_txq = %d\n", prefix, caps->num_txq); ice_debug(hw, ICE_DBG_INIT, "%s: txq_first_id = %d\n", prefix, caps->txq_first_id); break; case ICE_AQC_CAPS_MSIX: caps->num_msix_vectors = number; caps->msix_vector_first_id = phys_id; ice_debug(hw, ICE_DBG_INIT, "%s: num_msix_vectors = %d\n", prefix, caps->num_msix_vectors); ice_debug(hw, ICE_DBG_INIT, "%s: msix_vector_first_id = %d\n", prefix, caps->msix_vector_first_id); break; case ICE_AQC_CAPS_PENDING_NVM_VER: caps->nvm_update_pending_nvm = true; ice_debug(hw, ICE_DBG_INIT, "%s: update_pending_nvm\n", prefix); break; case ICE_AQC_CAPS_PENDING_OROM_VER: caps->nvm_update_pending_orom = true; ice_debug(hw, ICE_DBG_INIT, "%s: update_pending_orom\n", prefix); break; case ICE_AQC_CAPS_PENDING_NET_VER: caps->nvm_update_pending_netlist = true; ice_debug(hw, ICE_DBG_INIT, "%s: update_pending_netlist\n", prefix); break; case ICE_AQC_CAPS_NVM_MGMT: caps->nvm_unified_update = (number & ICE_NVM_MGMT_UNIFIED_UPD_SUPPORT) ? true : false; ice_debug(hw, ICE_DBG_INIT, "%s: nvm_unified_update = %d\n", prefix, caps->nvm_unified_update); break; case ICE_AQC_CAPS_RDMA: caps->rdma = (number == 1); ice_debug(hw, ICE_DBG_INIT, "%s: rdma = %d\n", prefix, caps->rdma); break; case ICE_AQC_CAPS_MAX_MTU: caps->max_mtu = number; ice_debug(hw, ICE_DBG_INIT, "%s: max_mtu = %d\n", prefix, caps->max_mtu); break; case ICE_AQC_CAPS_PCIE_RESET_AVOIDANCE: caps->pcie_reset_avoidance = (number > 0); ice_debug(hw, ICE_DBG_INIT, "%s: pcie_reset_avoidance = %d\n", prefix, caps->pcie_reset_avoidance); break; case ICE_AQC_CAPS_POST_UPDATE_RESET_RESTRICT: caps->reset_restrict_support = (number == 1); ice_debug(hw, ICE_DBG_INIT, "%s: reset_restrict_support = %d\n", prefix, caps->reset_restrict_support); break; case ICE_AQC_CAPS_FW_LAG_SUPPORT: caps->roce_lag = !!(number & ICE_AQC_BIT_ROCEV2_LAG); ice_debug(hw, ICE_DBG_INIT, "%s: roce_lag = %u\n", prefix, caps->roce_lag); caps->sriov_lag = !!(number & ICE_AQC_BIT_SRIOV_LAG); ice_debug(hw, ICE_DBG_INIT, "%s: sriov_lag = %u\n", prefix, caps->sriov_lag); break; default: /* Not one of the recognized common capabilities */ found = false; } return found; } /** * ice_recalc_port_limited_caps - Recalculate port limited capabilities * @hw: pointer to the HW structure * @caps: pointer to capabilities structure to fix * * Re-calculate the capabilities that are dependent on the number of physical * ports; i.e. some features are not supported or function differently on * devices with more than 4 ports. */ static void ice_recalc_port_limited_caps(struct ice_hw *hw, struct ice_hw_common_caps *caps) { /* This assumes device capabilities are always scanned before function * capabilities during the initialization flow. */ if (hw->dev_caps.num_funcs > 4) { /* Max 4 TCs per port */ caps->maxtc = 4; ice_debug(hw, ICE_DBG_INIT, "reducing maxtc to %d (based on #ports)\n", caps->maxtc); if (caps->rdma) { ice_debug(hw, ICE_DBG_INIT, "forcing RDMA off\n"); caps->rdma = 0; } /* print message only when processing device capabilities * during initialization. */ if (caps == &hw->dev_caps.common_cap) dev_info(ice_hw_to_dev(hw), "RDMA functionality is not available with the current device configuration.\n"); } } /** * ice_parse_vf_func_caps - Parse ICE_AQC_CAPS_VF function caps * @hw: pointer to the HW struct * @func_p: pointer to function capabilities structure * @cap: pointer to the capability element to parse * * Extract function capabilities for ICE_AQC_CAPS_VF. */ static void ice_parse_vf_func_caps(struct ice_hw *hw, struct ice_hw_func_caps *func_p, struct ice_aqc_list_caps_elem *cap) { u32 logical_id = le32_to_cpu(cap->logical_id); u32 number = le32_to_cpu(cap->number); func_p->num_allocd_vfs = number; func_p->vf_base_id = logical_id; ice_debug(hw, ICE_DBG_INIT, "func caps: num_allocd_vfs = %d\n", func_p->num_allocd_vfs); ice_debug(hw, ICE_DBG_INIT, "func caps: vf_base_id = %d\n", func_p->vf_base_id); } /** * ice_parse_vsi_func_caps - Parse ICE_AQC_CAPS_VSI function caps * @hw: pointer to the HW struct * @func_p: pointer to function capabilities structure * @cap: pointer to the capability element to parse * * Extract function capabilities for ICE_AQC_CAPS_VSI. */ static void ice_parse_vsi_func_caps(struct ice_hw *hw, struct ice_hw_func_caps *func_p, struct ice_aqc_list_caps_elem *cap) { func_p->guar_num_vsi = ice_get_num_per_func(hw, ICE_MAX_VSI); ice_debug(hw, ICE_DBG_INIT, "func caps: guar_num_vsi (fw) = %d\n", le32_to_cpu(cap->number)); ice_debug(hw, ICE_DBG_INIT, "func caps: guar_num_vsi = %d\n", func_p->guar_num_vsi); } /** * ice_parse_1588_func_caps - Parse ICE_AQC_CAPS_1588 function caps * @hw: pointer to the HW struct * @func_p: pointer to function capabilities structure * @cap: pointer to the capability element to parse * * Extract function capabilities for ICE_AQC_CAPS_1588. */ static void ice_parse_1588_func_caps(struct ice_hw *hw, struct ice_hw_func_caps *func_p, struct ice_aqc_list_caps_elem *cap) { struct ice_ts_func_info *info = &func_p->ts_func_info; u32 number = le32_to_cpu(cap->number); info->ena = ((number & ICE_TS_FUNC_ENA_M) != 0); func_p->common_cap.ieee_1588 = info->ena; info->src_tmr_owned = ((number & ICE_TS_SRC_TMR_OWND_M) != 0); info->tmr_ena = ((number & ICE_TS_TMR_ENA_M) != 0); info->tmr_index_owned = ((number & ICE_TS_TMR_IDX_OWND_M) != 0); info->tmr_index_assoc = ((number & ICE_TS_TMR_IDX_ASSOC_M) != 0); info->clk_freq = (number & ICE_TS_CLK_FREQ_M) >> ICE_TS_CLK_FREQ_S; info->clk_src = ((number & ICE_TS_CLK_SRC_M) != 0); if (info->clk_freq < NUM_ICE_TIME_REF_FREQ) { info->time_ref = (enum ice_time_ref_freq)info->clk_freq; } else { /* Unknown clock frequency, so assume a (probably incorrect) * default to avoid out-of-bounds look ups of frequency * related information. */ ice_debug(hw, ICE_DBG_INIT, "1588 func caps: unknown clock frequency %u\n", info->clk_freq); info->time_ref = ICE_TIME_REF_FREQ_25_000; } ice_debug(hw, ICE_DBG_INIT, "func caps: ieee_1588 = %u\n", func_p->common_cap.ieee_1588); ice_debug(hw, ICE_DBG_INIT, "func caps: src_tmr_owned = %u\n", info->src_tmr_owned); ice_debug(hw, ICE_DBG_INIT, "func caps: tmr_ena = %u\n", info->tmr_ena); ice_debug(hw, ICE_DBG_INIT, "func caps: tmr_index_owned = %u\n", info->tmr_index_owned); ice_debug(hw, ICE_DBG_INIT, "func caps: tmr_index_assoc = %u\n", info->tmr_index_assoc); ice_debug(hw, ICE_DBG_INIT, "func caps: clk_freq = %u\n", info->clk_freq); ice_debug(hw, ICE_DBG_INIT, "func caps: clk_src = %u\n", info->clk_src); } /** * ice_parse_fdir_func_caps - Parse ICE_AQC_CAPS_FD function caps * @hw: pointer to the HW struct * @func_p: pointer to function capabilities structure * * Extract function capabilities for ICE_AQC_CAPS_FD. */ static void ice_parse_fdir_func_caps(struct ice_hw *hw, struct ice_hw_func_caps *func_p) { u32 reg_val, val; reg_val = rd32(hw, GLQF_FD_SIZE); val = (reg_val & GLQF_FD_SIZE_FD_GSIZE_M) >> GLQF_FD_SIZE_FD_GSIZE_S; func_p->fd_fltr_guar = ice_get_num_per_func(hw, val); val = (reg_val & GLQF_FD_SIZE_FD_BSIZE_M) >> GLQF_FD_SIZE_FD_BSIZE_S; func_p->fd_fltr_best_effort = val; ice_debug(hw, ICE_DBG_INIT, "func caps: fd_fltr_guar = %d\n", func_p->fd_fltr_guar); ice_debug(hw, ICE_DBG_INIT, "func caps: fd_fltr_best_effort = %d\n", func_p->fd_fltr_best_effort); } /** * ice_parse_func_caps - Parse function capabilities * @hw: pointer to the HW struct * @func_p: pointer to function capabilities structure * @buf: buffer containing the function capability records * @cap_count: the number of capabilities * * Helper function to parse function (0x000A) capabilities list. For * capabilities shared between device and function, this relies on * ice_parse_common_caps. * * Loop through the list of provided capabilities and extract the relevant * data into the function capabilities structured. */ static void ice_parse_func_caps(struct ice_hw *hw, struct ice_hw_func_caps *func_p, void *buf, u32 cap_count) { struct ice_aqc_list_caps_elem *cap_resp; u32 i; cap_resp = buf; memset(func_p, 0, sizeof(*func_p)); for (i = 0; i < cap_count; i++) { u16 cap = le16_to_cpu(cap_resp[i].cap); bool found; found = ice_parse_common_caps(hw, &func_p->common_cap, &cap_resp[i], "func caps"); switch (cap) { case ICE_AQC_CAPS_VF: ice_parse_vf_func_caps(hw, func_p, &cap_resp[i]); break; case ICE_AQC_CAPS_VSI: ice_parse_vsi_func_caps(hw, func_p, &cap_resp[i]); break; case ICE_AQC_CAPS_1588: ice_parse_1588_func_caps(hw, func_p, &cap_resp[i]); break; case ICE_AQC_CAPS_FD: ice_parse_fdir_func_caps(hw, func_p); break; default: /* Don't list common capabilities as unknown */ if (!found) ice_debug(hw, ICE_DBG_INIT, "func caps: unknown capability[%d]: 0x%x\n", i, cap); break; } } ice_recalc_port_limited_caps(hw, &func_p->common_cap); } /** * ice_parse_valid_functions_cap - Parse ICE_AQC_CAPS_VALID_FUNCTIONS caps * @hw: pointer to the HW struct * @dev_p: pointer to device capabilities structure * @cap: capability element to parse * * Parse ICE_AQC_CAPS_VALID_FUNCTIONS for device capabilities. */ static void ice_parse_valid_functions_cap(struct ice_hw *hw, struct ice_hw_dev_caps *dev_p, struct ice_aqc_list_caps_elem *cap) { u32 number = le32_to_cpu(cap->number); dev_p->num_funcs = hweight32(number); ice_debug(hw, ICE_DBG_INIT, "dev caps: num_funcs = %d\n", dev_p->num_funcs); } /** * ice_parse_vf_dev_caps - Parse ICE_AQC_CAPS_VF device caps * @hw: pointer to the HW struct * @dev_p: pointer to device capabilities structure * @cap: capability element to parse * * Parse ICE_AQC_CAPS_VF for device capabilities. */ static void ice_parse_vf_dev_caps(struct ice_hw *hw, struct ice_hw_dev_caps *dev_p, struct ice_aqc_list_caps_elem *cap) { u32 number = le32_to_cpu(cap->number); dev_p->num_vfs_exposed = number; ice_debug(hw, ICE_DBG_INIT, "dev_caps: num_vfs_exposed = %d\n", dev_p->num_vfs_exposed); } /** * ice_parse_vsi_dev_caps - Parse ICE_AQC_CAPS_VSI device caps * @hw: pointer to the HW struct * @dev_p: pointer to device capabilities structure * @cap: capability element to parse * * Parse ICE_AQC_CAPS_VSI for device capabilities. */ static void ice_parse_vsi_dev_caps(struct ice_hw *hw, struct ice_hw_dev_caps *dev_p, struct ice_aqc_list_caps_elem *cap) { u32 number = le32_to_cpu(cap->number); dev_p->num_vsi_allocd_to_host = number; ice_debug(hw, ICE_DBG_INIT, "dev caps: num_vsi_allocd_to_host = %d\n", dev_p->num_vsi_allocd_to_host); } /** * ice_parse_1588_dev_caps - Parse ICE_AQC_CAPS_1588 device caps * @hw: pointer to the HW struct * @dev_p: pointer to device capabilities structure * @cap: capability element to parse * * Parse ICE_AQC_CAPS_1588 for device capabilities. */ static void ice_parse_1588_dev_caps(struct ice_hw *hw, struct ice_hw_dev_caps *dev_p, struct ice_aqc_list_caps_elem *cap) { struct ice_ts_dev_info *info = &dev_p->ts_dev_info; u32 logical_id = le32_to_cpu(cap->logical_id); u32 phys_id = le32_to_cpu(cap->phys_id); u32 number = le32_to_cpu(cap->number); info->ena = ((number & ICE_TS_DEV_ENA_M) != 0); dev_p->common_cap.ieee_1588 = info->ena; info->tmr0_owner = number & ICE_TS_TMR0_OWNR_M; info->tmr0_owned = ((number & ICE_TS_TMR0_OWND_M) != 0); info->tmr0_ena = ((number & ICE_TS_TMR0_ENA_M) != 0); info->tmr1_owner = (number & ICE_TS_TMR1_OWNR_M) >> ICE_TS_TMR1_OWNR_S; info->tmr1_owned = ((number & ICE_TS_TMR1_OWND_M) != 0); info->tmr1_ena = ((number & ICE_TS_TMR1_ENA_M) != 0); info->ts_ll_read = ((number & ICE_TS_LL_TX_TS_READ_M) != 0); info->ena_ports = logical_id; info->tmr_own_map = phys_id; ice_debug(hw, ICE_DBG_INIT, "dev caps: ieee_1588 = %u\n", dev_p->common_cap.ieee_1588); ice_debug(hw, ICE_DBG_INIT, "dev caps: tmr0_owner = %u\n", info->tmr0_owner); ice_debug(hw, ICE_DBG_INIT, "dev caps: tmr0_owned = %u\n", info->tmr0_owned); ice_debug(hw, ICE_DBG_INIT, "dev caps: tmr0_ena = %u\n", info->tmr0_ena); ice_debug(hw, ICE_DBG_INIT, "dev caps: tmr1_owner = %u\n", info->tmr1_owner); ice_debug(hw, ICE_DBG_INIT, "dev caps: tmr1_owned = %u\n", info->tmr1_owned); ice_debug(hw, ICE_DBG_INIT, "dev caps: tmr1_ena = %u\n", info->tmr1_ena); ice_debug(hw, ICE_DBG_INIT, "dev caps: ts_ll_read = %u\n", info->ts_ll_read); ice_debug(hw, ICE_DBG_INIT, "dev caps: ieee_1588 ena_ports = %u\n", info->ena_ports); ice_debug(hw, ICE_DBG_INIT, "dev caps: tmr_own_map = %u\n", info->tmr_own_map); } /** * ice_parse_fdir_dev_caps - Parse ICE_AQC_CAPS_FD device caps * @hw: pointer to the HW struct * @dev_p: pointer to device capabilities structure * @cap: capability element to parse * * Parse ICE_AQC_CAPS_FD for device capabilities. */ static void ice_parse_fdir_dev_caps(struct ice_hw *hw, struct ice_hw_dev_caps *dev_p, struct ice_aqc_list_caps_elem *cap) { u32 number = le32_to_cpu(cap->number); dev_p->num_flow_director_fltr = number; ice_debug(hw, ICE_DBG_INIT, "dev caps: num_flow_director_fltr = %d\n", dev_p->num_flow_director_fltr); } /** * ice_parse_dev_caps - Parse device capabilities * @hw: pointer to the HW struct * @dev_p: pointer to device capabilities structure * @buf: buffer containing the device capability records * @cap_count: the number of capabilities * * Helper device to parse device (0x000B) capabilities list. For * capabilities shared between device and function, this relies on * ice_parse_common_caps. * * Loop through the list of provided capabilities and extract the relevant * data into the device capabilities structured. */ static void ice_parse_dev_caps(struct ice_hw *hw, struct ice_hw_dev_caps *dev_p, void *buf, u32 cap_count) { struct ice_aqc_list_caps_elem *cap_resp; u32 i; cap_resp = buf; memset(dev_p, 0, sizeof(*dev_p)); for (i = 0; i < cap_count; i++) { u16 cap = le16_to_cpu(cap_resp[i].cap); bool found; found = ice_parse_common_caps(hw, &dev_p->common_cap, &cap_resp[i], "dev caps"); switch (cap) { case ICE_AQC_CAPS_VALID_FUNCTIONS: ice_parse_valid_functions_cap(hw, dev_p, &cap_resp[i]); break; case ICE_AQC_CAPS_VF: ice_parse_vf_dev_caps(hw, dev_p, &cap_resp[i]); break; case ICE_AQC_CAPS_VSI: ice_parse_vsi_dev_caps(hw, dev_p, &cap_resp[i]); break; case ICE_AQC_CAPS_1588: ice_parse_1588_dev_caps(hw, dev_p, &cap_resp[i]); break; case ICE_AQC_CAPS_FD: ice_parse_fdir_dev_caps(hw, dev_p, &cap_resp[i]); break; default: /* Don't list common capabilities as unknown */ if (!found) ice_debug(hw, ICE_DBG_INIT, "dev caps: unknown capability[%d]: 0x%x\n", i, cap); break; } } ice_recalc_port_limited_caps(hw, &dev_p->common_cap); } /** * ice_aq_get_netlist_node * @hw: pointer to the hw struct * @cmd: get_link_topo AQ structure * @node_part_number: output node part number if node found * @node_handle: output node handle parameter if node found */ static int ice_aq_get_netlist_node(struct ice_hw *hw, struct ice_aqc_get_link_topo *cmd, u8 *node_part_number, u16 *node_handle) { struct ice_aq_desc desc; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_get_link_topo); desc.params.get_link_topo = *cmd; if (ice_aq_send_cmd(hw, &desc, NULL, 0, NULL)) return -EIO; if (node_handle) *node_handle = le16_to_cpu(desc.params.get_link_topo.addr.handle); if (node_part_number) *node_part_number = desc.params.get_link_topo.node_part_num; return 0; } /** * ice_is_pf_c827 - check if pf contains c827 phy * @hw: pointer to the hw struct */ bool ice_is_pf_c827(struct ice_hw *hw) { struct ice_aqc_get_link_topo cmd = {}; u8 node_part_number; u16 node_handle; int status; if (hw->mac_type != ICE_MAC_E810) return false; if (hw->device_id != ICE_DEV_ID_E810C_QSFP) return true; cmd.addr.topo_params.node_type_ctx = FIELD_PREP(ICE_AQC_LINK_TOPO_NODE_TYPE_M, ICE_AQC_LINK_TOPO_NODE_TYPE_PHY) | FIELD_PREP(ICE_AQC_LINK_TOPO_NODE_CTX_M, ICE_AQC_LINK_TOPO_NODE_CTX_PORT); cmd.addr.topo_params.index = 0; status = ice_aq_get_netlist_node(hw, &cmd, &node_part_number, &node_handle); if (status || node_part_number != ICE_AQC_GET_LINK_TOPO_NODE_NR_C827) return false; if (node_handle == E810C_QSFP_C827_0_HANDLE || node_handle == E810C_QSFP_C827_1_HANDLE) return true; return false; } /** * ice_aq_list_caps - query function/device capabilities * @hw: pointer to the HW struct * @buf: a buffer to hold the capabilities * @buf_size: size of the buffer * @cap_count: if not NULL, set to the number of capabilities reported * @opc: capabilities type to discover, device or function * @cd: pointer to command details structure or NULL * * Get the function (0x000A) or device (0x000B) capabilities description from * firmware and store it in the buffer. * * If the cap_count pointer is not NULL, then it is set to the number of * capabilities firmware will report. Note that if the buffer size is too * small, it is possible the command will return ICE_AQ_ERR_ENOMEM. The * cap_count will still be updated in this case. It is recommended that the * buffer size be set to ICE_AQ_MAX_BUF_LEN (the largest possible buffer that * firmware could return) to avoid this. */ int ice_aq_list_caps(struct ice_hw *hw, void *buf, u16 buf_size, u32 *cap_count, enum ice_adminq_opc opc, struct ice_sq_cd *cd) { struct ice_aqc_list_caps *cmd; struct ice_aq_desc desc; int status; cmd = &desc.params.get_cap; if (opc != ice_aqc_opc_list_func_caps && opc != ice_aqc_opc_list_dev_caps) return -EINVAL; ice_fill_dflt_direct_cmd_desc(&desc, opc); status = ice_aq_send_cmd(hw, &desc, buf, buf_size, cd); if (cap_count) *cap_count = le32_to_cpu(cmd->count); return status; } /** * ice_discover_dev_caps - Read and extract device capabilities * @hw: pointer to the hardware structure * @dev_caps: pointer to device capabilities structure * * Read the device capabilities and extract them into the dev_caps structure * for later use. */ int ice_discover_dev_caps(struct ice_hw *hw, struct ice_hw_dev_caps *dev_caps) { u32 cap_count = 0; void *cbuf; int status; cbuf = kzalloc(ICE_AQ_MAX_BUF_LEN, GFP_KERNEL); if (!cbuf) return -ENOMEM; /* Although the driver doesn't know the number of capabilities the * device will return, we can simply send a 4KB buffer, the maximum * possible size that firmware can return. */ cap_count = ICE_AQ_MAX_BUF_LEN / sizeof(struct ice_aqc_list_caps_elem); status = ice_aq_list_caps(hw, cbuf, ICE_AQ_MAX_BUF_LEN, &cap_count, ice_aqc_opc_list_dev_caps, NULL); if (!status) ice_parse_dev_caps(hw, dev_caps, cbuf, cap_count); kfree(cbuf); return status; } /** * ice_discover_func_caps - Read and extract function capabilities * @hw: pointer to the hardware structure * @func_caps: pointer to function capabilities structure * * Read the function capabilities and extract them into the func_caps structure * for later use. */ static int ice_discover_func_caps(struct ice_hw *hw, struct ice_hw_func_caps *func_caps) { u32 cap_count = 0; void *cbuf; int status; cbuf = kzalloc(ICE_AQ_MAX_BUF_LEN, GFP_KERNEL); if (!cbuf) return -ENOMEM; /* Although the driver doesn't know the number of capabilities the * device will return, we can simply send a 4KB buffer, the maximum * possible size that firmware can return. */ cap_count = ICE_AQ_MAX_BUF_LEN / sizeof(struct ice_aqc_list_caps_elem); status = ice_aq_list_caps(hw, cbuf, ICE_AQ_MAX_BUF_LEN, &cap_count, ice_aqc_opc_list_func_caps, NULL); if (!status) ice_parse_func_caps(hw, func_caps, cbuf, cap_count); kfree(cbuf); return status; } /** * ice_set_safe_mode_caps - Override dev/func capabilities when in safe mode * @hw: pointer to the hardware structure */ void ice_set_safe_mode_caps(struct ice_hw *hw) { struct ice_hw_func_caps *func_caps = &hw->func_caps; struct ice_hw_dev_caps *dev_caps = &hw->dev_caps; struct ice_hw_common_caps cached_caps; u32 num_funcs; /* cache some func_caps values that should be restored after memset */ cached_caps = func_caps->common_cap; /* unset func capabilities */ memset(func_caps, 0, sizeof(*func_caps)); #define ICE_RESTORE_FUNC_CAP(name) \ func_caps->common_cap.name = cached_caps.name /* restore cached values */ ICE_RESTORE_FUNC_CAP(valid_functions); ICE_RESTORE_FUNC_CAP(txq_first_id); ICE_RESTORE_FUNC_CAP(rxq_first_id); ICE_RESTORE_FUNC_CAP(msix_vector_first_id); ICE_RESTORE_FUNC_CAP(max_mtu); ICE_RESTORE_FUNC_CAP(nvm_unified_update); ICE_RESTORE_FUNC_CAP(nvm_update_pending_nvm); ICE_RESTORE_FUNC_CAP(nvm_update_pending_orom); ICE_RESTORE_FUNC_CAP(nvm_update_pending_netlist); /* one Tx and one Rx queue in safe mode */ func_caps->common_cap.num_rxq = 1; func_caps->common_cap.num_txq = 1; /* two MSIX vectors, one for traffic and one for misc causes */ func_caps->common_cap.num_msix_vectors = 2; func_caps->guar_num_vsi = 1; /* cache some dev_caps values that should be restored after memset */ cached_caps = dev_caps->common_cap; num_funcs = dev_caps->num_funcs; /* unset dev capabilities */ memset(dev_caps, 0, sizeof(*dev_caps)); #define ICE_RESTORE_DEV_CAP(name) \ dev_caps->common_cap.name = cached_caps.name /* restore cached values */ ICE_RESTORE_DEV_CAP(valid_functions); ICE_RESTORE_DEV_CAP(txq_first_id); ICE_RESTORE_DEV_CAP(rxq_first_id); ICE_RESTORE_DEV_CAP(msix_vector_first_id); ICE_RESTORE_DEV_CAP(max_mtu); ICE_RESTORE_DEV_CAP(nvm_unified_update); ICE_RESTORE_DEV_CAP(nvm_update_pending_nvm); ICE_RESTORE_DEV_CAP(nvm_update_pending_orom); ICE_RESTORE_DEV_CAP(nvm_update_pending_netlist); dev_caps->num_funcs = num_funcs; /* one Tx and one Rx queue per function in safe mode */ dev_caps->common_cap.num_rxq = num_funcs; dev_caps->common_cap.num_txq = num_funcs; /* two MSIX vectors per function */ dev_caps->common_cap.num_msix_vectors = 2 * num_funcs; } /** * ice_get_caps - get info about the HW * @hw: pointer to the hardware structure */ int ice_get_caps(struct ice_hw *hw) { int status; status = ice_discover_dev_caps(hw, &hw->dev_caps); if (status) return status; return ice_discover_func_caps(hw, &hw->func_caps); } /** * ice_aq_manage_mac_write - manage MAC address write command * @hw: pointer to the HW struct * @mac_addr: MAC address to be written as LAA/LAA+WoL/Port address * @flags: flags to control write behavior * @cd: pointer to command details structure or NULL * * This function is used to write MAC address to the NVM (0x0108). */ int ice_aq_manage_mac_write(struct ice_hw *hw, const u8 *mac_addr, u8 flags, struct ice_sq_cd *cd) { struct ice_aqc_manage_mac_write *cmd; struct ice_aq_desc desc; cmd = &desc.params.mac_write; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_manage_mac_write); cmd->flags = flags; ether_addr_copy(cmd->mac_addr, mac_addr); return ice_aq_send_cmd(hw, &desc, NULL, 0, cd); } /** * ice_aq_clear_pxe_mode * @hw: pointer to the HW struct * * Tell the firmware that the driver is taking over from PXE (0x0110). */ static int ice_aq_clear_pxe_mode(struct ice_hw *hw) { struct ice_aq_desc desc; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_clear_pxe_mode); desc.params.clear_pxe.rx_cnt = ICE_AQC_CLEAR_PXE_RX_CNT; return ice_aq_send_cmd(hw, &desc, NULL, 0, NULL); } /** * ice_clear_pxe_mode - clear pxe operations mode * @hw: pointer to the HW struct * * Make sure all PXE mode settings are cleared, including things * like descriptor fetch/write-back mode. */ void ice_clear_pxe_mode(struct ice_hw *hw) { if (ice_check_sq_alive(hw, &hw->adminq)) ice_aq_clear_pxe_mode(hw); } /** * ice_aq_set_port_params - set physical port parameters. * @pi: pointer to the port info struct * @double_vlan: if set double VLAN is enabled * @cd: pointer to command details structure or NULL * * Set Physical port parameters (0x0203) */ int ice_aq_set_port_params(struct ice_port_info *pi, bool double_vlan, struct ice_sq_cd *cd) { struct ice_aqc_set_port_params *cmd; struct ice_hw *hw = pi->hw; struct ice_aq_desc desc; u16 cmd_flags = 0; cmd = &desc.params.set_port_params; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_set_port_params); if (double_vlan) cmd_flags |= ICE_AQC_SET_P_PARAMS_DOUBLE_VLAN_ENA; cmd->cmd_flags = cpu_to_le16(cmd_flags); return ice_aq_send_cmd(hw, &desc, NULL, 0, cd); } /** * ice_is_100m_speed_supported * @hw: pointer to the HW struct * * returns true if 100M speeds are supported by the device, * false otherwise. */ bool ice_is_100m_speed_supported(struct ice_hw *hw) { switch (hw->device_id) { case ICE_DEV_ID_E822C_SGMII: case ICE_DEV_ID_E822L_SGMII: case ICE_DEV_ID_E823L_1GBE: case ICE_DEV_ID_E823C_SGMII: return true; default: return false; } } /** * ice_get_link_speed_based_on_phy_type - returns link speed * @phy_type_low: lower part of phy_type * @phy_type_high: higher part of phy_type * * This helper function will convert an entry in PHY type structure * [phy_type_low, phy_type_high] to its corresponding link speed. * Note: In the structure of [phy_type_low, phy_type_high], there should * be one bit set, as this function will convert one PHY type to its * speed. * If no bit gets set, ICE_AQ_LINK_SPEED_UNKNOWN will be returned * If more than one bit gets set, ICE_AQ_LINK_SPEED_UNKNOWN will be returned */ static u16 ice_get_link_speed_based_on_phy_type(u64 phy_type_low, u64 phy_type_high) { u16 speed_phy_type_high = ICE_AQ_LINK_SPEED_UNKNOWN; u16 speed_phy_type_low = ICE_AQ_LINK_SPEED_UNKNOWN; switch (phy_type_low) { case ICE_PHY_TYPE_LOW_100BASE_TX: case ICE_PHY_TYPE_LOW_100M_SGMII: speed_phy_type_low = ICE_AQ_LINK_SPEED_100MB; break; case ICE_PHY_TYPE_LOW_1000BASE_T: case ICE_PHY_TYPE_LOW_1000BASE_SX: case ICE_PHY_TYPE_LOW_1000BASE_LX: case ICE_PHY_TYPE_LOW_1000BASE_KX: case ICE_PHY_TYPE_LOW_1G_SGMII: speed_phy_type_low = ICE_AQ_LINK_SPEED_1000MB; break; case ICE_PHY_TYPE_LOW_2500BASE_T: case ICE_PHY_TYPE_LOW_2500BASE_X: case ICE_PHY_TYPE_LOW_2500BASE_KX: speed_phy_type_low = ICE_AQ_LINK_SPEED_2500MB; break; case ICE_PHY_TYPE_LOW_5GBASE_T: case ICE_PHY_TYPE_LOW_5GBASE_KR: speed_phy_type_low = ICE_AQ_LINK_SPEED_5GB; break; case ICE_PHY_TYPE_LOW_10GBASE_T: case ICE_PHY_TYPE_LOW_10G_SFI_DA: case ICE_PHY_TYPE_LOW_10GBASE_SR: case ICE_PHY_TYPE_LOW_10GBASE_LR: case ICE_PHY_TYPE_LOW_10GBASE_KR_CR1: case ICE_PHY_TYPE_LOW_10G_SFI_AOC_ACC: case ICE_PHY_TYPE_LOW_10G_SFI_C2C: speed_phy_type_low = ICE_AQ_LINK_SPEED_10GB; break; case ICE_PHY_TYPE_LOW_25GBASE_T: case ICE_PHY_TYPE_LOW_25GBASE_CR: case ICE_PHY_TYPE_LOW_25GBASE_CR_S: case ICE_PHY_TYPE_LOW_25GBASE_CR1: case ICE_PHY_TYPE_LOW_25GBASE_SR: case ICE_PHY_TYPE_LOW_25GBASE_LR: case ICE_PHY_TYPE_LOW_25GBASE_KR: case ICE_PHY_TYPE_LOW_25GBASE_KR_S: case ICE_PHY_TYPE_LOW_25GBASE_KR1: case ICE_PHY_TYPE_LOW_25G_AUI_AOC_ACC: case ICE_PHY_TYPE_LOW_25G_AUI_C2C: speed_phy_type_low = ICE_AQ_LINK_SPEED_25GB; break; case ICE_PHY_TYPE_LOW_40GBASE_CR4: case ICE_PHY_TYPE_LOW_40GBASE_SR4: case ICE_PHY_TYPE_LOW_40GBASE_LR4: case ICE_PHY_TYPE_LOW_40GBASE_KR4: case ICE_PHY_TYPE_LOW_40G_XLAUI_AOC_ACC: case ICE_PHY_TYPE_LOW_40G_XLAUI: speed_phy_type_low = ICE_AQ_LINK_SPEED_40GB; break; case ICE_PHY_TYPE_LOW_50GBASE_CR2: case ICE_PHY_TYPE_LOW_50GBASE_SR2: case ICE_PHY_TYPE_LOW_50GBASE_LR2: case ICE_PHY_TYPE_LOW_50GBASE_KR2: case ICE_PHY_TYPE_LOW_50G_LAUI2_AOC_ACC: case ICE_PHY_TYPE_LOW_50G_LAUI2: case ICE_PHY_TYPE_LOW_50G_AUI2_AOC_ACC: case ICE_PHY_TYPE_LOW_50G_AUI2: case ICE_PHY_TYPE_LOW_50GBASE_CP: case ICE_PHY_TYPE_LOW_50GBASE_SR: case ICE_PHY_TYPE_LOW_50GBASE_FR: case ICE_PHY_TYPE_LOW_50GBASE_LR: case ICE_PHY_TYPE_LOW_50GBASE_KR_PAM4: case ICE_PHY_TYPE_LOW_50G_AUI1_AOC_ACC: case ICE_PHY_TYPE_LOW_50G_AUI1: speed_phy_type_low = ICE_AQ_LINK_SPEED_50GB; break; case ICE_PHY_TYPE_LOW_100GBASE_CR4: case ICE_PHY_TYPE_LOW_100GBASE_SR4: case ICE_PHY_TYPE_LOW_100GBASE_LR4: case ICE_PHY_TYPE_LOW_100GBASE_KR4: case ICE_PHY_TYPE_LOW_100G_CAUI4_AOC_ACC: case ICE_PHY_TYPE_LOW_100G_CAUI4: case ICE_PHY_TYPE_LOW_100G_AUI4_AOC_ACC: case ICE_PHY_TYPE_LOW_100G_AUI4: case ICE_PHY_TYPE_LOW_100GBASE_CR_PAM4: case ICE_PHY_TYPE_LOW_100GBASE_KR_PAM4: case ICE_PHY_TYPE_LOW_100GBASE_CP2: case ICE_PHY_TYPE_LOW_100GBASE_SR2: case ICE_PHY_TYPE_LOW_100GBASE_DR: speed_phy_type_low = ICE_AQ_LINK_SPEED_100GB; break; default: speed_phy_type_low = ICE_AQ_LINK_SPEED_UNKNOWN; break; } switch (phy_type_high) { case ICE_PHY_TYPE_HIGH_100GBASE_KR2_PAM4: case ICE_PHY_TYPE_HIGH_100G_CAUI2_AOC_ACC: case ICE_PHY_TYPE_HIGH_100G_CAUI2: case ICE_PHY_TYPE_HIGH_100G_AUI2_AOC_ACC: case ICE_PHY_TYPE_HIGH_100G_AUI2: speed_phy_type_high = ICE_AQ_LINK_SPEED_100GB; break; default: speed_phy_type_high = ICE_AQ_LINK_SPEED_UNKNOWN; break; } if (speed_phy_type_low == ICE_AQ_LINK_SPEED_UNKNOWN && speed_phy_type_high == ICE_AQ_LINK_SPEED_UNKNOWN) return ICE_AQ_LINK_SPEED_UNKNOWN; else if (speed_phy_type_low != ICE_AQ_LINK_SPEED_UNKNOWN && speed_phy_type_high != ICE_AQ_LINK_SPEED_UNKNOWN) return ICE_AQ_LINK_SPEED_UNKNOWN; else if (speed_phy_type_low != ICE_AQ_LINK_SPEED_UNKNOWN && speed_phy_type_high == ICE_AQ_LINK_SPEED_UNKNOWN) return speed_phy_type_low; else return speed_phy_type_high; } /** * ice_update_phy_type * @phy_type_low: pointer to the lower part of phy_type * @phy_type_high: pointer to the higher part of phy_type * @link_speeds_bitmap: targeted link speeds bitmap * * Note: For the link_speeds_bitmap structure, you can check it at * [ice_aqc_get_link_status->link_speed]. Caller can pass in * link_speeds_bitmap include multiple speeds. * * Each entry in this [phy_type_low, phy_type_high] structure will * present a certain link speed. This helper function will turn on bits * in [phy_type_low, phy_type_high] structure based on the value of * link_speeds_bitmap input parameter. */ void ice_update_phy_type(u64 *phy_type_low, u64 *phy_type_high, u16 link_speeds_bitmap) { u64 pt_high; u64 pt_low; int index; u16 speed; /* We first check with low part of phy_type */ for (index = 0; index <= ICE_PHY_TYPE_LOW_MAX_INDEX; index++) { pt_low = BIT_ULL(index); speed = ice_get_link_speed_based_on_phy_type(pt_low, 0); if (link_speeds_bitmap & speed) *phy_type_low |= BIT_ULL(index); } /* We then check with high part of phy_type */ for (index = 0; index <= ICE_PHY_TYPE_HIGH_MAX_INDEX; index++) { pt_high = BIT_ULL(index); speed = ice_get_link_speed_based_on_phy_type(0, pt_high); if (link_speeds_bitmap & speed) *phy_type_high |= BIT_ULL(index); } } /** * ice_aq_set_phy_cfg * @hw: pointer to the HW struct * @pi: port info structure of the interested logical port * @cfg: structure with PHY configuration data to be set * @cd: pointer to command details structure or NULL * * Set the various PHY configuration parameters supported on the Port. * One or more of the Set PHY config parameters may be ignored in an MFP * mode as the PF may not have the privilege to set some of the PHY Config * parameters. This status will be indicated by the command response (0x0601). */ int ice_aq_set_phy_cfg(struct ice_hw *hw, struct ice_port_info *pi, struct ice_aqc_set_phy_cfg_data *cfg, struct ice_sq_cd *cd) { struct ice_aq_desc desc; int status; if (!cfg) return -EINVAL; /* Ensure that only valid bits of cfg->caps can be turned on. */ if (cfg->caps & ~ICE_AQ_PHY_ENA_VALID_MASK) { ice_debug(hw, ICE_DBG_PHY, "Invalid bit is set in ice_aqc_set_phy_cfg_data->caps : 0x%x\n", cfg->caps); cfg->caps &= ICE_AQ_PHY_ENA_VALID_MASK; } ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_set_phy_cfg); desc.params.set_phy.lport_num = pi->lport; desc.flags |= cpu_to_le16(ICE_AQ_FLAG_RD); ice_debug(hw, ICE_DBG_LINK, "set phy cfg\n"); ice_debug(hw, ICE_DBG_LINK, " phy_type_low = 0x%llx\n", (unsigned long long)le64_to_cpu(cfg->phy_type_low)); ice_debug(hw, ICE_DBG_LINK, " phy_type_high = 0x%llx\n", (unsigned long long)le64_to_cpu(cfg->phy_type_high)); ice_debug(hw, ICE_DBG_LINK, " caps = 0x%x\n", cfg->caps); ice_debug(hw, ICE_DBG_LINK, " low_power_ctrl_an = 0x%x\n", cfg->low_power_ctrl_an); ice_debug(hw, ICE_DBG_LINK, " eee_cap = 0x%x\n", cfg->eee_cap); ice_debug(hw, ICE_DBG_LINK, " eeer_value = 0x%x\n", cfg->eeer_value); ice_debug(hw, ICE_DBG_LINK, " link_fec_opt = 0x%x\n", cfg->link_fec_opt); status = ice_aq_send_cmd(hw, &desc, cfg, sizeof(*cfg), cd); if (hw->adminq.sq_last_status == ICE_AQ_RC_EMODE) status = 0; if (!status) pi->phy.curr_user_phy_cfg = *cfg; return status; } /** * ice_update_link_info - update status of the HW network link * @pi: port info structure of the interested logical port */ int ice_update_link_info(struct ice_port_info *pi) { struct ice_link_status *li; int status; if (!pi) return -EINVAL; li = &pi->phy.link_info; status = ice_aq_get_link_info(pi, true, NULL, NULL); if (status) return status; if (li->link_info & ICE_AQ_MEDIA_AVAILABLE) { struct ice_aqc_get_phy_caps_data *pcaps; struct ice_hw *hw; hw = pi->hw; pcaps = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*pcaps), GFP_KERNEL); if (!pcaps) return -ENOMEM; status = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_TOPO_CAP_MEDIA, pcaps, NULL); devm_kfree(ice_hw_to_dev(hw), pcaps); } return status; } /** * ice_cache_phy_user_req * @pi: port information structure * @cache_data: PHY logging data * @cache_mode: PHY logging mode * * Log the user request on (FC, FEC, SPEED) for later use. */ static void ice_cache_phy_user_req(struct ice_port_info *pi, struct ice_phy_cache_mode_data cache_data, enum ice_phy_cache_mode cache_mode) { if (!pi) return; switch (cache_mode) { case ICE_FC_MODE: pi->phy.curr_user_fc_req = cache_data.data.curr_user_fc_req; break; case ICE_SPEED_MODE: pi->phy.curr_user_speed_req = cache_data.data.curr_user_speed_req; break; case ICE_FEC_MODE: pi->phy.curr_user_fec_req = cache_data.data.curr_user_fec_req; break; default: break; } } /** * ice_caps_to_fc_mode * @caps: PHY capabilities * * Convert PHY FC capabilities to ice FC mode */ enum ice_fc_mode ice_caps_to_fc_mode(u8 caps) { if (caps & ICE_AQC_PHY_EN_TX_LINK_PAUSE && caps & ICE_AQC_PHY_EN_RX_LINK_PAUSE) return ICE_FC_FULL; if (caps & ICE_AQC_PHY_EN_TX_LINK_PAUSE) return ICE_FC_TX_PAUSE; if (caps & ICE_AQC_PHY_EN_RX_LINK_PAUSE) return ICE_FC_RX_PAUSE; return ICE_FC_NONE; } /** * ice_caps_to_fec_mode * @caps: PHY capabilities * @fec_options: Link FEC options * * Convert PHY FEC capabilities to ice FEC mode */ enum ice_fec_mode ice_caps_to_fec_mode(u8 caps, u8 fec_options) { if (caps & ICE_AQC_PHY_EN_AUTO_FEC) return ICE_FEC_AUTO; if (fec_options & (ICE_AQC_PHY_FEC_10G_KR_40G_KR4_EN | ICE_AQC_PHY_FEC_10G_KR_40G_KR4_REQ | ICE_AQC_PHY_FEC_25G_KR_CLAUSE74_EN | ICE_AQC_PHY_FEC_25G_KR_REQ)) return ICE_FEC_BASER; if (fec_options & (ICE_AQC_PHY_FEC_25G_RS_528_REQ | ICE_AQC_PHY_FEC_25G_RS_544_REQ | ICE_AQC_PHY_FEC_25G_RS_CLAUSE91_EN)) return ICE_FEC_RS; return ICE_FEC_NONE; } /** * ice_cfg_phy_fc - Configure PHY FC data based on FC mode * @pi: port information structure * @cfg: PHY configuration data to set FC mode * @req_mode: FC mode to configure */ int ice_cfg_phy_fc(struct ice_port_info *pi, struct ice_aqc_set_phy_cfg_data *cfg, enum ice_fc_mode req_mode) { struct ice_phy_cache_mode_data cache_data; u8 pause_mask = 0x0; if (!pi || !cfg) return -EINVAL; switch (req_mode) { case ICE_FC_FULL: pause_mask |= ICE_AQC_PHY_EN_TX_LINK_PAUSE; pause_mask |= ICE_AQC_PHY_EN_RX_LINK_PAUSE; break; case ICE_FC_RX_PAUSE: pause_mask |= ICE_AQC_PHY_EN_RX_LINK_PAUSE; break; case ICE_FC_TX_PAUSE: pause_mask |= ICE_AQC_PHY_EN_TX_LINK_PAUSE; break; default: break; } /* clear the old pause settings */ cfg->caps &= ~(ICE_AQC_PHY_EN_TX_LINK_PAUSE | ICE_AQC_PHY_EN_RX_LINK_PAUSE); /* set the new capabilities */ cfg->caps |= pause_mask; /* Cache user FC request */ cache_data.data.curr_user_fc_req = req_mode; ice_cache_phy_user_req(pi, cache_data, ICE_FC_MODE); return 0; } /** * ice_set_fc * @pi: port information structure * @aq_failures: pointer to status code, specific to ice_set_fc routine * @ena_auto_link_update: enable automatic link update * * Set the requested flow control mode. */ int ice_set_fc(struct ice_port_info *pi, u8 *aq_failures, bool ena_auto_link_update) { struct ice_aqc_set_phy_cfg_data cfg = { 0 }; struct ice_aqc_get_phy_caps_data *pcaps; struct ice_hw *hw; int status; if (!pi || !aq_failures) return -EINVAL; *aq_failures = 0; hw = pi->hw; pcaps = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*pcaps), GFP_KERNEL); if (!pcaps) return -ENOMEM; /* Get the current PHY config */ status = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_ACTIVE_CFG, pcaps, NULL); if (status) { *aq_failures = ICE_SET_FC_AQ_FAIL_GET; goto out; } ice_copy_phy_caps_to_cfg(pi, pcaps, &cfg); /* Configure the set PHY data */ status = ice_cfg_phy_fc(pi, &cfg, pi->fc.req_mode); if (status) goto out; /* If the capabilities have changed, then set the new config */ if (cfg.caps != pcaps->caps) { int retry_count, retry_max = 10; /* Auto restart link so settings take effect */ if (ena_auto_link_update) cfg.caps |= ICE_AQ_PHY_ENA_AUTO_LINK_UPDT; status = ice_aq_set_phy_cfg(hw, pi, &cfg, NULL); if (status) { *aq_failures = ICE_SET_FC_AQ_FAIL_SET; goto out; } /* Update the link info * It sometimes takes a really long time for link to * come back from the atomic reset. Thus, we wait a * little bit. */ for (retry_count = 0; retry_count < retry_max; retry_count++) { status = ice_update_link_info(pi); if (!status) break; mdelay(100); } if (status) *aq_failures = ICE_SET_FC_AQ_FAIL_UPDATE; } out: devm_kfree(ice_hw_to_dev(hw), pcaps); return status; } /** * ice_phy_caps_equals_cfg * @phy_caps: PHY capabilities * @phy_cfg: PHY configuration * * Helper function to determine if PHY capabilities matches PHY * configuration */ bool ice_phy_caps_equals_cfg(struct ice_aqc_get_phy_caps_data *phy_caps, struct ice_aqc_set_phy_cfg_data *phy_cfg) { u8 caps_mask, cfg_mask; if (!phy_caps || !phy_cfg) return false; /* These bits are not common between capabilities and configuration. * Do not use them to determine equality. */ caps_mask = ICE_AQC_PHY_CAPS_MASK & ~(ICE_AQC_PHY_AN_MODE | ICE_AQC_GET_PHY_EN_MOD_QUAL); cfg_mask = ICE_AQ_PHY_ENA_VALID_MASK & ~ICE_AQ_PHY_ENA_AUTO_LINK_UPDT; if (phy_caps->phy_type_low != phy_cfg->phy_type_low || phy_caps->phy_type_high != phy_cfg->phy_type_high || ((phy_caps->caps & caps_mask) != (phy_cfg->caps & cfg_mask)) || phy_caps->low_power_ctrl_an != phy_cfg->low_power_ctrl_an || phy_caps->eee_cap != phy_cfg->eee_cap || phy_caps->eeer_value != phy_cfg->eeer_value || phy_caps->link_fec_options != phy_cfg->link_fec_opt) return false; return true; } /** * ice_copy_phy_caps_to_cfg - Copy PHY ability data to configuration data * @pi: port information structure * @caps: PHY ability structure to copy date from * @cfg: PHY configuration structure to copy data to * * Helper function to copy AQC PHY get ability data to PHY set configuration * data structure */ void ice_copy_phy_caps_to_cfg(struct ice_port_info *pi, struct ice_aqc_get_phy_caps_data *caps, struct ice_aqc_set_phy_cfg_data *cfg) { if (!pi || !caps || !cfg) return; memset(cfg, 0, sizeof(*cfg)); cfg->phy_type_low = caps->phy_type_low; cfg->phy_type_high = caps->phy_type_high; cfg->caps = caps->caps; cfg->low_power_ctrl_an = caps->low_power_ctrl_an; cfg->eee_cap = caps->eee_cap; cfg->eeer_value = caps->eeer_value; cfg->link_fec_opt = caps->link_fec_options; cfg->module_compliance_enforcement = caps->module_compliance_enforcement; } /** * ice_cfg_phy_fec - Configure PHY FEC data based on FEC mode * @pi: port information structure * @cfg: PHY configuration data to set FEC mode * @fec: FEC mode to configure */ int ice_cfg_phy_fec(struct ice_port_info *pi, struct ice_aqc_set_phy_cfg_data *cfg, enum ice_fec_mode fec) { struct ice_aqc_get_phy_caps_data *pcaps; struct ice_hw *hw; int status; if (!pi || !cfg) return -EINVAL; hw = pi->hw; pcaps = kzalloc(sizeof(*pcaps), GFP_KERNEL); if (!pcaps) return -ENOMEM; status = ice_aq_get_phy_caps(pi, false, (ice_fw_supports_report_dflt_cfg(hw) ? ICE_AQC_REPORT_DFLT_CFG : ICE_AQC_REPORT_TOPO_CAP_MEDIA), pcaps, NULL); if (status) goto out; cfg->caps |= pcaps->caps & ICE_AQC_PHY_EN_AUTO_FEC; cfg->link_fec_opt = pcaps->link_fec_options; switch (fec) { case ICE_FEC_BASER: /* Clear RS bits, and AND BASE-R ability * bits and OR request bits. */ cfg->link_fec_opt &= ICE_AQC_PHY_FEC_10G_KR_40G_KR4_EN | ICE_AQC_PHY_FEC_25G_KR_CLAUSE74_EN; cfg->link_fec_opt |= ICE_AQC_PHY_FEC_10G_KR_40G_KR4_REQ | ICE_AQC_PHY_FEC_25G_KR_REQ; break; case ICE_FEC_RS: /* Clear BASE-R bits, and AND RS ability * bits and OR request bits. */ cfg->link_fec_opt &= ICE_AQC_PHY_FEC_25G_RS_CLAUSE91_EN; cfg->link_fec_opt |= ICE_AQC_PHY_FEC_25G_RS_528_REQ | ICE_AQC_PHY_FEC_25G_RS_544_REQ; break; case ICE_FEC_NONE: /* Clear all FEC option bits. */ cfg->link_fec_opt &= ~ICE_AQC_PHY_FEC_MASK; break; case ICE_FEC_AUTO: /* AND auto FEC bit, and all caps bits. */ cfg->caps &= ICE_AQC_PHY_CAPS_MASK; cfg->link_fec_opt |= pcaps->link_fec_options; break; default: status = -EINVAL; break; } if (fec == ICE_FEC_AUTO && ice_fw_supports_link_override(hw) && !ice_fw_supports_report_dflt_cfg(hw)) { struct ice_link_default_override_tlv tlv = { 0 }; status = ice_get_link_default_override(&tlv, pi); if (status) goto out; if (!(tlv.options & ICE_LINK_OVERRIDE_STRICT_MODE) && (tlv.options & ICE_LINK_OVERRIDE_EN)) cfg->link_fec_opt = tlv.fec_options; } out: kfree(pcaps); return status; } /** * ice_get_link_status - get status of the HW network link * @pi: port information structure * @link_up: pointer to bool (true/false = linkup/linkdown) * * Variable link_up is true if link is up, false if link is down. * The variable link_up is invalid if status is non zero. As a * result of this call, link status reporting becomes enabled */ int ice_get_link_status(struct ice_port_info *pi, bool *link_up) { struct ice_phy_info *phy_info; int status = 0; if (!pi || !link_up) return -EINVAL; phy_info = &pi->phy; if (phy_info->get_link_info) { status = ice_update_link_info(pi); if (status) ice_debug(pi->hw, ICE_DBG_LINK, "get link status error, status = %d\n", status); } *link_up = phy_info->link_info.link_info & ICE_AQ_LINK_UP; return status; } /** * ice_aq_set_link_restart_an * @pi: pointer to the port information structure * @ena_link: if true: enable link, if false: disable link * @cd: pointer to command details structure or NULL * * Sets up the link and restarts the Auto-Negotiation over the link. */ int ice_aq_set_link_restart_an(struct ice_port_info *pi, bool ena_link, struct ice_sq_cd *cd) { struct ice_aqc_restart_an *cmd; struct ice_aq_desc desc; cmd = &desc.params.restart_an; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_restart_an); cmd->cmd_flags = ICE_AQC_RESTART_AN_LINK_RESTART; cmd->lport_num = pi->lport; if (ena_link) cmd->cmd_flags |= ICE_AQC_RESTART_AN_LINK_ENABLE; else cmd->cmd_flags &= ~ICE_AQC_RESTART_AN_LINK_ENABLE; return ice_aq_send_cmd(pi->hw, &desc, NULL, 0, cd); } /** * ice_aq_set_event_mask * @hw: pointer to the HW struct * @port_num: port number of the physical function * @mask: event mask to be set * @cd: pointer to command details structure or NULL * * Set event mask (0x0613) */ int ice_aq_set_event_mask(struct ice_hw *hw, u8 port_num, u16 mask, struct ice_sq_cd *cd) { struct ice_aqc_set_event_mask *cmd; struct ice_aq_desc desc; cmd = &desc.params.set_event_mask; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_set_event_mask); cmd->lport_num = port_num; cmd->event_mask = cpu_to_le16(mask); return ice_aq_send_cmd(hw, &desc, NULL, 0, cd); } /** * ice_aq_set_mac_loopback * @hw: pointer to the HW struct * @ena_lpbk: Enable or Disable loopback * @cd: pointer to command details structure or NULL * * Enable/disable loopback on a given port */ int ice_aq_set_mac_loopback(struct ice_hw *hw, bool ena_lpbk, struct ice_sq_cd *cd) { struct ice_aqc_set_mac_lb *cmd; struct ice_aq_desc desc; cmd = &desc.params.set_mac_lb; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_set_mac_lb); if (ena_lpbk) cmd->lb_mode = ICE_AQ_MAC_LB_EN; return ice_aq_send_cmd(hw, &desc, NULL, 0, cd); } /** * ice_aq_set_port_id_led * @pi: pointer to the port information * @is_orig_mode: is this LED set to original mode (by the net-list) * @cd: pointer to command details structure or NULL * * Set LED value for the given port (0x06e9) */ int ice_aq_set_port_id_led(struct ice_port_info *pi, bool is_orig_mode, struct ice_sq_cd *cd) { struct ice_aqc_set_port_id_led *cmd; struct ice_hw *hw = pi->hw; struct ice_aq_desc desc; cmd = &desc.params.set_port_id_led; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_set_port_id_led); if (is_orig_mode) cmd->ident_mode = ICE_AQC_PORT_IDENT_LED_ORIG; else cmd->ident_mode = ICE_AQC_PORT_IDENT_LED_BLINK; return ice_aq_send_cmd(hw, &desc, NULL, 0, cd); } /** * ice_aq_get_port_options * @hw: pointer to the HW struct * @options: buffer for the resultant port options * @option_count: input - size of the buffer in port options structures, * output - number of returned port options * @lport: logical port to call the command with (optional) * @lport_valid: when false, FW uses port owned by the PF instead of lport, * when PF owns more than 1 port it must be true * @active_option_idx: index of active port option in returned buffer * @active_option_valid: active option in returned buffer is valid * @pending_option_idx: index of pending port option in returned buffer * @pending_option_valid: pending option in returned buffer is valid * * Calls Get Port Options AQC (0x06ea) and verifies result. */ int ice_aq_get_port_options(struct ice_hw *hw, struct ice_aqc_get_port_options_elem *options, u8 *option_count, u8 lport, bool lport_valid, u8 *active_option_idx, bool *active_option_valid, u8 *pending_option_idx, bool *pending_option_valid) { struct ice_aqc_get_port_options *cmd; struct ice_aq_desc desc; int status; u8 i; /* options buffer shall be able to hold max returned options */ if (*option_count < ICE_AQC_PORT_OPT_COUNT_M) return -EINVAL; cmd = &desc.params.get_port_options; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_get_port_options); if (lport_valid) cmd->lport_num = lport; cmd->lport_num_valid = lport_valid; status = ice_aq_send_cmd(hw, &desc, options, *option_count * sizeof(*options), NULL); if (status) return status; /* verify direct FW response & set output parameters */ *option_count = FIELD_GET(ICE_AQC_PORT_OPT_COUNT_M, cmd->port_options_count); ice_debug(hw, ICE_DBG_PHY, "options: %x\n", *option_count); *active_option_valid = FIELD_GET(ICE_AQC_PORT_OPT_VALID, cmd->port_options); if (*active_option_valid) { *active_option_idx = FIELD_GET(ICE_AQC_PORT_OPT_ACTIVE_M, cmd->port_options); if (*active_option_idx > (*option_count - 1)) return -EIO; ice_debug(hw, ICE_DBG_PHY, "active idx: %x\n", *active_option_idx); } *pending_option_valid = FIELD_GET(ICE_AQC_PENDING_PORT_OPT_VALID, cmd->pending_port_option_status); if (*pending_option_valid) { *pending_option_idx = FIELD_GET(ICE_AQC_PENDING_PORT_OPT_IDX_M, cmd->pending_port_option_status); if (*pending_option_idx > (*option_count - 1)) return -EIO; ice_debug(hw, ICE_DBG_PHY, "pending idx: %x\n", *pending_option_idx); } /* mask output options fields */ for (i = 0; i < *option_count; i++) { options[i].pmd = FIELD_GET(ICE_AQC_PORT_OPT_PMD_COUNT_M, options[i].pmd); options[i].max_lane_speed = FIELD_GET(ICE_AQC_PORT_OPT_MAX_LANE_M, options[i].max_lane_speed); ice_debug(hw, ICE_DBG_PHY, "pmds: %x max speed: %x\n", options[i].pmd, options[i].max_lane_speed); } return 0; } /** * ice_aq_set_port_option * @hw: pointer to the HW struct * @lport: logical port to call the command with * @lport_valid: when false, FW uses port owned by the PF instead of lport, * when PF owns more than 1 port it must be true * @new_option: new port option to be written * * Calls Set Port Options AQC (0x06eb). */ int ice_aq_set_port_option(struct ice_hw *hw, u8 lport, u8 lport_valid, u8 new_option) { struct ice_aqc_set_port_option *cmd; struct ice_aq_desc desc; if (new_option > ICE_AQC_PORT_OPT_COUNT_M) return -EINVAL; cmd = &desc.params.set_port_option; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_set_port_option); if (lport_valid) cmd->lport_num = lport; cmd->lport_num_valid = lport_valid; cmd->selected_port_option = new_option; return ice_aq_send_cmd(hw, &desc, NULL, 0, NULL); } /** * ice_aq_sff_eeprom * @hw: pointer to the HW struct * @lport: bits [7:0] = logical port, bit [8] = logical port valid * @bus_addr: I2C bus address of the eeprom (typically 0xA0, 0=topo default) * @mem_addr: I2C offset. lower 8 bits for address, 8 upper bits zero padding. * @page: QSFP page * @set_page: set or ignore the page * @data: pointer to data buffer to be read/written to the I2C device. * @length: 1-16 for read, 1 for write. * @write: 0 read, 1 for write. * @cd: pointer to command details structure or NULL * * Read/Write SFF EEPROM (0x06EE) */ int ice_aq_sff_eeprom(struct ice_hw *hw, u16 lport, u8 bus_addr, u16 mem_addr, u8 page, u8 set_page, u8 *data, u8 length, bool write, struct ice_sq_cd *cd) { struct ice_aqc_sff_eeprom *cmd; struct ice_aq_desc desc; int status; if (!data || (mem_addr & 0xff00)) return -EINVAL; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_sff_eeprom); cmd = &desc.params.read_write_sff_param; desc.flags = cpu_to_le16(ICE_AQ_FLAG_RD); cmd->lport_num = (u8)(lport & 0xff); cmd->lport_num_valid = (u8)((lport >> 8) & 0x01); cmd->i2c_bus_addr = cpu_to_le16(((bus_addr >> 1) & ICE_AQC_SFF_I2CBUS_7BIT_M) | ((set_page << ICE_AQC_SFF_SET_EEPROM_PAGE_S) & ICE_AQC_SFF_SET_EEPROM_PAGE_M)); cmd->i2c_mem_addr = cpu_to_le16(mem_addr & 0xff); cmd->eeprom_page = cpu_to_le16((u16)page << ICE_AQC_SFF_EEPROM_PAGE_S); if (write) cmd->i2c_bus_addr |= cpu_to_le16(ICE_AQC_SFF_IS_WRITE); status = ice_aq_send_cmd(hw, &desc, data, length, cd); return status; } static enum ice_lut_size ice_lut_type_to_size(enum ice_lut_type type) { switch (type) { case ICE_LUT_VSI: return ICE_LUT_VSI_SIZE; case ICE_LUT_GLOBAL: return ICE_LUT_GLOBAL_SIZE; case ICE_LUT_PF: return ICE_LUT_PF_SIZE; } WARN_ONCE(1, "incorrect type passed"); return ICE_LUT_VSI_SIZE; } static enum ice_aqc_lut_flags ice_lut_size_to_flag(enum ice_lut_size size) { switch (size) { case ICE_LUT_VSI_SIZE: return ICE_AQC_LUT_SIZE_SMALL; case ICE_LUT_GLOBAL_SIZE: return ICE_AQC_LUT_SIZE_512; case ICE_LUT_PF_SIZE: return ICE_AQC_LUT_SIZE_2K; } WARN_ONCE(1, "incorrect size passed"); return 0; } /** * __ice_aq_get_set_rss_lut * @hw: pointer to the hardware structure * @params: RSS LUT parameters * @set: set true to set the table, false to get the table * * Internal function to get (0x0B05) or set (0x0B03) RSS look up table */ static int __ice_aq_get_set_rss_lut(struct ice_hw *hw, struct ice_aq_get_set_rss_lut_params *params, bool set) { u16 opcode, vsi_id, vsi_handle = params->vsi_handle, glob_lut_idx = 0; enum ice_lut_type lut_type = params->lut_type; struct ice_aqc_get_set_rss_lut *desc_params; enum ice_aqc_lut_flags flags; enum ice_lut_size lut_size; struct ice_aq_desc desc; u8 *lut = params->lut; if (!lut || !ice_is_vsi_valid(hw, vsi_handle)) return -EINVAL; lut_size = ice_lut_type_to_size(lut_type); if (lut_size > params->lut_size) return -EINVAL; else if (set && lut_size != params->lut_size) return -EINVAL; opcode = set ? ice_aqc_opc_set_rss_lut : ice_aqc_opc_get_rss_lut; ice_fill_dflt_direct_cmd_desc(&desc, opcode); if (set) desc.flags |= cpu_to_le16(ICE_AQ_FLAG_RD); desc_params = &desc.params.get_set_rss_lut; vsi_id = ice_get_hw_vsi_num(hw, vsi_handle); desc_params->vsi_id = cpu_to_le16(vsi_id | ICE_AQC_RSS_VSI_VALID); if (lut_type == ICE_LUT_GLOBAL) glob_lut_idx = FIELD_PREP(ICE_AQC_LUT_GLOBAL_IDX, params->global_lut_id); flags = lut_type | glob_lut_idx | ice_lut_size_to_flag(lut_size); desc_params->flags = cpu_to_le16(flags); return ice_aq_send_cmd(hw, &desc, lut, lut_size, NULL); } /** * ice_aq_get_rss_lut * @hw: pointer to the hardware structure * @get_params: RSS LUT parameters used to specify which RSS LUT to get * * get the RSS lookup table, PF or VSI type */ int ice_aq_get_rss_lut(struct ice_hw *hw, struct ice_aq_get_set_rss_lut_params *get_params) { return __ice_aq_get_set_rss_lut(hw, get_params, false); } /** * ice_aq_set_rss_lut * @hw: pointer to the hardware structure * @set_params: RSS LUT parameters used to specify how to set the RSS LUT * * set the RSS lookup table, PF or VSI type */ int ice_aq_set_rss_lut(struct ice_hw *hw, struct ice_aq_get_set_rss_lut_params *set_params) { return __ice_aq_get_set_rss_lut(hw, set_params, true); } /** * __ice_aq_get_set_rss_key * @hw: pointer to the HW struct * @vsi_id: VSI FW index * @key: pointer to key info struct * @set: set true to set the key, false to get the key * * get (0x0B04) or set (0x0B02) the RSS key per VSI */ static int __ice_aq_get_set_rss_key(struct ice_hw *hw, u16 vsi_id, struct ice_aqc_get_set_rss_keys *key, bool set) { struct ice_aqc_get_set_rss_key *desc_params; u16 key_size = sizeof(*key); struct ice_aq_desc desc; if (set) { ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_set_rss_key); desc.flags |= cpu_to_le16(ICE_AQ_FLAG_RD); } else { ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_get_rss_key); } desc_params = &desc.params.get_set_rss_key; desc_params->vsi_id = cpu_to_le16(vsi_id | ICE_AQC_RSS_VSI_VALID); return ice_aq_send_cmd(hw, &desc, key, key_size, NULL); } /** * ice_aq_get_rss_key * @hw: pointer to the HW struct * @vsi_handle: software VSI handle * @key: pointer to key info struct * * get the RSS key per VSI */ int ice_aq_get_rss_key(struct ice_hw *hw, u16 vsi_handle, struct ice_aqc_get_set_rss_keys *key) { if (!ice_is_vsi_valid(hw, vsi_handle) || !key) return -EINVAL; return __ice_aq_get_set_rss_key(hw, ice_get_hw_vsi_num(hw, vsi_handle), key, false); } /** * ice_aq_set_rss_key * @hw: pointer to the HW struct * @vsi_handle: software VSI handle * @keys: pointer to key info struct * * set the RSS key per VSI */ int ice_aq_set_rss_key(struct ice_hw *hw, u16 vsi_handle, struct ice_aqc_get_set_rss_keys *keys) { if (!ice_is_vsi_valid(hw, vsi_handle) || !keys) return -EINVAL; return __ice_aq_get_set_rss_key(hw, ice_get_hw_vsi_num(hw, vsi_handle), keys, true); } /** * ice_aq_add_lan_txq * @hw: pointer to the hardware structure * @num_qgrps: Number of added queue groups * @qg_list: list of queue groups to be added * @buf_size: size of buffer for indirect command * @cd: pointer to command details structure or NULL * * Add Tx LAN queue (0x0C30) * * NOTE: * Prior to calling add Tx LAN queue: * Initialize the following as part of the Tx queue context: * Completion queue ID if the queue uses Completion queue, Quanta profile, * Cache profile and Packet shaper profile. * * After add Tx LAN queue AQ command is completed: * Interrupts should be associated with specific queues, * Association of Tx queue to Doorbell queue is not part of Add LAN Tx queue * flow. */ static int ice_aq_add_lan_txq(struct ice_hw *hw, u8 num_qgrps, struct ice_aqc_add_tx_qgrp *qg_list, u16 buf_size, struct ice_sq_cd *cd) { struct ice_aqc_add_tx_qgrp *list; struct ice_aqc_add_txqs *cmd; struct ice_aq_desc desc; u16 i, sum_size = 0; cmd = &desc.params.add_txqs; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_add_txqs); if (!qg_list) return -EINVAL; if (num_qgrps > ICE_LAN_TXQ_MAX_QGRPS) return -EINVAL; for (i = 0, list = qg_list; i < num_qgrps; i++) { sum_size += struct_size(list, txqs, list->num_txqs); list = (struct ice_aqc_add_tx_qgrp *)(list->txqs + list->num_txqs); } if (buf_size != sum_size) return -EINVAL; desc.flags |= cpu_to_le16(ICE_AQ_FLAG_RD); cmd->num_qgrps = num_qgrps; return ice_aq_send_cmd(hw, &desc, qg_list, buf_size, cd); } /** * ice_aq_dis_lan_txq * @hw: pointer to the hardware structure * @num_qgrps: number of groups in the list * @qg_list: the list of groups to disable * @buf_size: the total size of the qg_list buffer in bytes * @rst_src: if called due to reset, specifies the reset source * @vmvf_num: the relative VM or VF number that is undergoing the reset * @cd: pointer to command details structure or NULL * * Disable LAN Tx queue (0x0C31) */ static int ice_aq_dis_lan_txq(struct ice_hw *hw, u8 num_qgrps, struct ice_aqc_dis_txq_item *qg_list, u16 buf_size, enum ice_disq_rst_src rst_src, u16 vmvf_num, struct ice_sq_cd *cd) { struct ice_aqc_dis_txq_item *item; struct ice_aqc_dis_txqs *cmd; struct ice_aq_desc desc; u16 i, sz = 0; int status; cmd = &desc.params.dis_txqs; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_dis_txqs); /* qg_list can be NULL only in VM/VF reset flow */ if (!qg_list && !rst_src) return -EINVAL; if (num_qgrps > ICE_LAN_TXQ_MAX_QGRPS) return -EINVAL; cmd->num_entries = num_qgrps; cmd->vmvf_and_timeout = cpu_to_le16((5 << ICE_AQC_Q_DIS_TIMEOUT_S) & ICE_AQC_Q_DIS_TIMEOUT_M); switch (rst_src) { case ICE_VM_RESET: cmd->cmd_type = ICE_AQC_Q_DIS_CMD_VM_RESET; cmd->vmvf_and_timeout |= cpu_to_le16(vmvf_num & ICE_AQC_Q_DIS_VMVF_NUM_M); break; case ICE_VF_RESET: cmd->cmd_type = ICE_AQC_Q_DIS_CMD_VF_RESET; /* In this case, FW expects vmvf_num to be absolute VF ID */ cmd->vmvf_and_timeout |= cpu_to_le16((vmvf_num + hw->func_caps.vf_base_id) & ICE_AQC_Q_DIS_VMVF_NUM_M); break; case ICE_NO_RESET: default: break; } /* flush pipe on time out */ cmd->cmd_type |= ICE_AQC_Q_DIS_CMD_FLUSH_PIPE; /* If no queue group info, we are in a reset flow. Issue the AQ */ if (!qg_list) goto do_aq; /* set RD bit to indicate that command buffer is provided by the driver * and it needs to be read by the firmware */ desc.flags |= cpu_to_le16(ICE_AQ_FLAG_RD); for (i = 0, item = qg_list; i < num_qgrps; i++) { u16 item_size = struct_size(item, q_id, item->num_qs); /* If the num of queues is even, add 2 bytes of padding */ if ((item->num_qs % 2) == 0) item_size += 2; sz += item_size; item = (struct ice_aqc_dis_txq_item *)((u8 *)item + item_size); } if (buf_size != sz) return -EINVAL; do_aq: status = ice_aq_send_cmd(hw, &desc, qg_list, buf_size, cd); if (status) { if (!qg_list) ice_debug(hw, ICE_DBG_SCHED, "VM%d disable failed %d\n", vmvf_num, hw->adminq.sq_last_status); else ice_debug(hw, ICE_DBG_SCHED, "disable queue %d failed %d\n", le16_to_cpu(qg_list[0].q_id[0]), hw->adminq.sq_last_status); } return status; } /** * ice_aq_cfg_lan_txq * @hw: pointer to the hardware structure * @buf: buffer for command * @buf_size: size of buffer in bytes * @num_qs: number of queues being configured * @oldport: origination lport * @newport: destination lport * @cd: pointer to command details structure or NULL * * Move/Configure LAN Tx queue (0x0C32) * * There is a better AQ command to use for moving nodes, so only coding * this one for configuring the node. */ int ice_aq_cfg_lan_txq(struct ice_hw *hw, struct ice_aqc_cfg_txqs_buf *buf, u16 buf_size, u16 num_qs, u8 oldport, u8 newport, struct ice_sq_cd *cd) { struct ice_aqc_cfg_txqs *cmd; struct ice_aq_desc desc; int status; cmd = &desc.params.cfg_txqs; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_cfg_txqs); desc.flags |= cpu_to_le16(ICE_AQ_FLAG_RD); if (!buf) return -EINVAL; cmd->cmd_type = ICE_AQC_Q_CFG_TC_CHNG; cmd->num_qs = num_qs; cmd->port_num_chng = (oldport & ICE_AQC_Q_CFG_SRC_PRT_M); cmd->port_num_chng |= (newport << ICE_AQC_Q_CFG_DST_PRT_S) & ICE_AQC_Q_CFG_DST_PRT_M; cmd->time_out = (5 << ICE_AQC_Q_CFG_TIMEOUT_S) & ICE_AQC_Q_CFG_TIMEOUT_M; cmd->blocked_cgds = 0; status = ice_aq_send_cmd(hw, &desc, buf, buf_size, cd); if (status) ice_debug(hw, ICE_DBG_SCHED, "Failed to reconfigure nodes %d\n", hw->adminq.sq_last_status); return status; } /** * ice_aq_add_rdma_qsets * @hw: pointer to the hardware structure * @num_qset_grps: Number of RDMA Qset groups * @qset_list: list of Qset groups to be added * @buf_size: size of buffer for indirect command * @cd: pointer to command details structure or NULL * * Add Tx RDMA Qsets (0x0C33) */ static int ice_aq_add_rdma_qsets(struct ice_hw *hw, u8 num_qset_grps, struct ice_aqc_add_rdma_qset_data *qset_list, u16 buf_size, struct ice_sq_cd *cd) { struct ice_aqc_add_rdma_qset_data *list; struct ice_aqc_add_rdma_qset *cmd; struct ice_aq_desc desc; u16 i, sum_size = 0; cmd = &desc.params.add_rdma_qset; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_add_rdma_qset); if (num_qset_grps > ICE_LAN_TXQ_MAX_QGRPS) return -EINVAL; for (i = 0, list = qset_list; i < num_qset_grps; i++) { u16 num_qsets = le16_to_cpu(list->num_qsets); sum_size += struct_size(list, rdma_qsets, num_qsets); list = (struct ice_aqc_add_rdma_qset_data *)(list->rdma_qsets + num_qsets); } if (buf_size != sum_size) return -EINVAL; desc.flags |= cpu_to_le16(ICE_AQ_FLAG_RD); cmd->num_qset_grps = num_qset_grps; return ice_aq_send_cmd(hw, &desc, qset_list, buf_size, cd); } /* End of FW Admin Queue command wrappers */ /** * ice_write_byte - write a byte to a packed context structure * @src_ctx: the context structure to read from * @dest_ctx: the context to be written to * @ce_info: a description of the struct to be filled */ static void ice_write_byte(u8 *src_ctx, u8 *dest_ctx, const struct ice_ctx_ele *ce_info) { u8 src_byte, dest_byte, mask; u8 *from, *dest; u16 shift_width; /* copy from the next struct field */ from = src_ctx + ce_info->offset; /* prepare the bits and mask */ shift_width = ce_info->lsb % 8; mask = (u8)(BIT(ce_info->width) - 1); src_byte = *from; src_byte &= mask; /* shift to correct alignment */ mask <<= shift_width; src_byte <<= shift_width; /* get the current bits from the target bit string */ dest = dest_ctx + (ce_info->lsb / 8); memcpy(&dest_byte, dest, sizeof(dest_byte)); dest_byte &= ~mask; /* get the bits not changing */ dest_byte |= src_byte; /* add in the new bits */ /* put it all back */ memcpy(dest, &dest_byte, sizeof(dest_byte)); } /** * ice_write_word - write a word to a packed context structure * @src_ctx: the context structure to read from * @dest_ctx: the context to be written to * @ce_info: a description of the struct to be filled */ static void ice_write_word(u8 *src_ctx, u8 *dest_ctx, const struct ice_ctx_ele *ce_info) { u16 src_word, mask; __le16 dest_word; u8 *from, *dest; u16 shift_width; /* copy from the next struct field */ from = src_ctx + ce_info->offset; /* prepare the bits and mask */ shift_width = ce_info->lsb % 8; mask = BIT(ce_info->width) - 1; /* don't swizzle the bits until after the mask because the mask bits * will be in a different bit position on big endian machines */ src_word = *(u16 *)from; src_word &= mask; /* shift to correct alignment */ mask <<= shift_width; src_word <<= shift_width; /* get the current bits from the target bit string */ dest = dest_ctx + (ce_info->lsb / 8); memcpy(&dest_word, dest, sizeof(dest_word)); dest_word &= ~(cpu_to_le16(mask)); /* get the bits not changing */ dest_word |= cpu_to_le16(src_word); /* add in the new bits */ /* put it all back */ memcpy(dest, &dest_word, sizeof(dest_word)); } /** * ice_write_dword - write a dword to a packed context structure * @src_ctx: the context structure to read from * @dest_ctx: the context to be written to * @ce_info: a description of the struct to be filled */ static void ice_write_dword(u8 *src_ctx, u8 *dest_ctx, const struct ice_ctx_ele *ce_info) { u32 src_dword, mask; __le32 dest_dword; u8 *from, *dest; u16 shift_width; /* copy from the next struct field */ from = src_ctx + ce_info->offset; /* prepare the bits and mask */ shift_width = ce_info->lsb % 8; /* if the field width is exactly 32 on an x86 machine, then the shift * operation will not work because the SHL instructions count is masked * to 5 bits so the shift will do nothing */ if (ce_info->width < 32) mask = BIT(ce_info->width) - 1; else mask = (u32)~0; /* don't swizzle the bits until after the mask because the mask bits * will be in a different bit position on big endian machines */ src_dword = *(u32 *)from; src_dword &= mask; /* shift to correct alignment */ mask <<= shift_width; src_dword <<= shift_width; /* get the current bits from the target bit string */ dest = dest_ctx + (ce_info->lsb / 8); memcpy(&dest_dword, dest, sizeof(dest_dword)); dest_dword &= ~(cpu_to_le32(mask)); /* get the bits not changing */ dest_dword |= cpu_to_le32(src_dword); /* add in the new bits */ /* put it all back */ memcpy(dest, &dest_dword, sizeof(dest_dword)); } /** * ice_write_qword - write a qword to a packed context structure * @src_ctx: the context structure to read from * @dest_ctx: the context to be written to * @ce_info: a description of the struct to be filled */ static void ice_write_qword(u8 *src_ctx, u8 *dest_ctx, const struct ice_ctx_ele *ce_info) { u64 src_qword, mask; __le64 dest_qword; u8 *from, *dest; u16 shift_width; /* copy from the next struct field */ from = src_ctx + ce_info->offset; /* prepare the bits and mask */ shift_width = ce_info->lsb % 8; /* if the field width is exactly 64 on an x86 machine, then the shift * operation will not work because the SHL instructions count is masked * to 6 bits so the shift will do nothing */ if (ce_info->width < 64) mask = BIT_ULL(ce_info->width) - 1; else mask = (u64)~0; /* don't swizzle the bits until after the mask because the mask bits * will be in a different bit position on big endian machines */ src_qword = *(u64 *)from; src_qword &= mask; /* shift to correct alignment */ mask <<= shift_width; src_qword <<= shift_width; /* get the current bits from the target bit string */ dest = dest_ctx + (ce_info->lsb / 8); memcpy(&dest_qword, dest, sizeof(dest_qword)); dest_qword &= ~(cpu_to_le64(mask)); /* get the bits not changing */ dest_qword |= cpu_to_le64(src_qword); /* add in the new bits */ /* put it all back */ memcpy(dest, &dest_qword, sizeof(dest_qword)); } /** * ice_set_ctx - set context bits in packed structure * @hw: pointer to the hardware structure * @src_ctx: pointer to a generic non-packed context structure * @dest_ctx: pointer to memory for the packed structure * @ce_info: a description of the structure to be transformed */ int ice_set_ctx(struct ice_hw *hw, u8 *src_ctx, u8 *dest_ctx, const struct ice_ctx_ele *ce_info) { int f; for (f = 0; ce_info[f].width; f++) { /* We have to deal with each element of the FW response * using the correct size so that we are correct regardless * of the endianness of the machine. */ if (ce_info[f].width > (ce_info[f].size_of * BITS_PER_BYTE)) { ice_debug(hw, ICE_DBG_QCTX, "Field %d width of %d bits larger than size of %d byte(s) ... skipping write\n", f, ce_info[f].width, ce_info[f].size_of); continue; } switch (ce_info[f].size_of) { case sizeof(u8): ice_write_byte(src_ctx, dest_ctx, &ce_info[f]); break; case sizeof(u16): ice_write_word(src_ctx, dest_ctx, &ce_info[f]); break; case sizeof(u32): ice_write_dword(src_ctx, dest_ctx, &ce_info[f]); break; case sizeof(u64): ice_write_qword(src_ctx, dest_ctx, &ce_info[f]); break; default: return -EINVAL; } } return 0; } /** * ice_get_lan_q_ctx - get the LAN queue context for the given VSI and TC * @hw: pointer to the HW struct * @vsi_handle: software VSI handle * @tc: TC number * @q_handle: software queue handle */ struct ice_q_ctx * ice_get_lan_q_ctx(struct ice_hw *hw, u16 vsi_handle, u8 tc, u16 q_handle) { struct ice_vsi_ctx *vsi; struct ice_q_ctx *q_ctx; vsi = ice_get_vsi_ctx(hw, vsi_handle); if (!vsi) return NULL; if (q_handle >= vsi->num_lan_q_entries[tc]) return NULL; if (!vsi->lan_q_ctx[tc]) return NULL; q_ctx = vsi->lan_q_ctx[tc]; return &q_ctx[q_handle]; } /** * ice_ena_vsi_txq * @pi: port information structure * @vsi_handle: software VSI handle * @tc: TC number * @q_handle: software queue handle * @num_qgrps: Number of added queue groups * @buf: list of queue groups to be added * @buf_size: size of buffer for indirect command * @cd: pointer to command details structure or NULL * * This function adds one LAN queue */ int ice_ena_vsi_txq(struct ice_port_info *pi, u16 vsi_handle, u8 tc, u16 q_handle, u8 num_qgrps, struct ice_aqc_add_tx_qgrp *buf, u16 buf_size, struct ice_sq_cd *cd) { struct ice_aqc_txsched_elem_data node = { 0 }; struct ice_sched_node *parent; struct ice_q_ctx *q_ctx; struct ice_hw *hw; int status; if (!pi || pi->port_state != ICE_SCHED_PORT_STATE_READY) return -EIO; if (num_qgrps > 1 || buf->num_txqs > 1) return -ENOSPC; hw = pi->hw; if (!ice_is_vsi_valid(hw, vsi_handle)) return -EINVAL; mutex_lock(&pi->sched_lock); q_ctx = ice_get_lan_q_ctx(hw, vsi_handle, tc, q_handle); if (!q_ctx) { ice_debug(hw, ICE_DBG_SCHED, "Enaq: invalid queue handle %d\n", q_handle); status = -EINVAL; goto ena_txq_exit; } /* find a parent node */ parent = ice_sched_get_free_qparent(pi, vsi_handle, tc, ICE_SCHED_NODE_OWNER_LAN); if (!parent) { status = -EINVAL; goto ena_txq_exit; } buf->parent_teid = parent->info.node_teid; node.parent_teid = parent->info.node_teid; /* Mark that the values in the "generic" section as valid. The default * value in the "generic" section is zero. This means that : * - Scheduling mode is Bytes Per Second (BPS), indicated by Bit 0. * - 0 priority among siblings, indicated by Bit 1-3. * - WFQ, indicated by Bit 4. * - 0 Adjustment value is used in PSM credit update flow, indicated by * Bit 5-6. * - Bit 7 is reserved. * Without setting the generic section as valid in valid_sections, the * Admin queue command will fail with error code ICE_AQ_RC_EINVAL. */ buf->txqs[0].info.valid_sections = ICE_AQC_ELEM_VALID_GENERIC | ICE_AQC_ELEM_VALID_CIR | ICE_AQC_ELEM_VALID_EIR; buf->txqs[0].info.generic = 0; buf->txqs[0].info.cir_bw.bw_profile_idx = cpu_to_le16(ICE_SCHED_DFLT_RL_PROF_ID); buf->txqs[0].info.cir_bw.bw_alloc = cpu_to_le16(ICE_SCHED_DFLT_BW_WT); buf->txqs[0].info.eir_bw.bw_profile_idx = cpu_to_le16(ICE_SCHED_DFLT_RL_PROF_ID); buf->txqs[0].info.eir_bw.bw_alloc = cpu_to_le16(ICE_SCHED_DFLT_BW_WT); /* add the LAN queue */ status = ice_aq_add_lan_txq(hw, num_qgrps, buf, buf_size, cd); if (status) { ice_debug(hw, ICE_DBG_SCHED, "enable queue %d failed %d\n", le16_to_cpu(buf->txqs[0].txq_id), hw->adminq.sq_last_status); goto ena_txq_exit; } node.node_teid = buf->txqs[0].q_teid; node.data.elem_type = ICE_AQC_ELEM_TYPE_LEAF; q_ctx->q_handle = q_handle; q_ctx->q_teid = le32_to_cpu(node.node_teid); /* add a leaf node into scheduler tree queue layer */ status = ice_sched_add_node(pi, hw->num_tx_sched_layers - 1, &node, NULL); if (!status) status = ice_sched_replay_q_bw(pi, q_ctx); ena_txq_exit: mutex_unlock(&pi->sched_lock); return status; } /** * ice_dis_vsi_txq * @pi: port information structure * @vsi_handle: software VSI handle * @tc: TC number * @num_queues: number of queues * @q_handles: pointer to software queue handle array * @q_ids: pointer to the q_id array * @q_teids: pointer to queue node teids * @rst_src: if called due to reset, specifies the reset source * @vmvf_num: the relative VM or VF number that is undergoing the reset * @cd: pointer to command details structure or NULL * * This function removes queues and their corresponding nodes in SW DB */ int ice_dis_vsi_txq(struct ice_port_info *pi, u16 vsi_handle, u8 tc, u8 num_queues, u16 *q_handles, u16 *q_ids, u32 *q_teids, enum ice_disq_rst_src rst_src, u16 vmvf_num, struct ice_sq_cd *cd) { struct ice_aqc_dis_txq_item *qg_list; struct ice_q_ctx *q_ctx; int status = -ENOENT; struct ice_hw *hw; u16 i, buf_size; if (!pi || pi->port_state != ICE_SCHED_PORT_STATE_READY) return -EIO; hw = pi->hw; if (!num_queues) { /* if queue is disabled already yet the disable queue command * has to be sent to complete the VF reset, then call * ice_aq_dis_lan_txq without any queue information */ if (rst_src) return ice_aq_dis_lan_txq(hw, 0, NULL, 0, rst_src, vmvf_num, NULL); return -EIO; } buf_size = struct_size(qg_list, q_id, 1); qg_list = kzalloc(buf_size, GFP_KERNEL); if (!qg_list) return -ENOMEM; mutex_lock(&pi->sched_lock); for (i = 0; i < num_queues; i++) { struct ice_sched_node *node; node = ice_sched_find_node_by_teid(pi->root, q_teids[i]); if (!node) continue; q_ctx = ice_get_lan_q_ctx(hw, vsi_handle, tc, q_handles[i]); if (!q_ctx) { ice_debug(hw, ICE_DBG_SCHED, "invalid queue handle%d\n", q_handles[i]); continue; } if (q_ctx->q_handle != q_handles[i]) { ice_debug(hw, ICE_DBG_SCHED, "Err:handles %d %d\n", q_ctx->q_handle, q_handles[i]); continue; } qg_list->parent_teid = node->info.parent_teid; qg_list->num_qs = 1; qg_list->q_id[0] = cpu_to_le16(q_ids[i]); status = ice_aq_dis_lan_txq(hw, 1, qg_list, buf_size, rst_src, vmvf_num, cd); if (status) break; ice_free_sched_node(pi, node); q_ctx->q_handle = ICE_INVAL_Q_HANDLE; q_ctx->q_teid = ICE_INVAL_TEID; } mutex_unlock(&pi->sched_lock); kfree(qg_list); return status; } /** * ice_cfg_vsi_qs - configure the new/existing VSI queues * @pi: port information structure * @vsi_handle: software VSI handle * @tc_bitmap: TC bitmap * @maxqs: max queues array per TC * @owner: LAN or RDMA * * This function adds/updates the VSI queues per TC. */ static int ice_cfg_vsi_qs(struct ice_port_info *pi, u16 vsi_handle, u8 tc_bitmap, u16 *maxqs, u8 owner) { int status = 0; u8 i; if (!pi || pi->port_state != ICE_SCHED_PORT_STATE_READY) return -EIO; if (!ice_is_vsi_valid(pi->hw, vsi_handle)) return -EINVAL; mutex_lock(&pi->sched_lock); ice_for_each_traffic_class(i) { /* configuration is possible only if TC node is present */ if (!ice_sched_get_tc_node(pi, i)) continue; status = ice_sched_cfg_vsi(pi, vsi_handle, i, maxqs[i], owner, ice_is_tc_ena(tc_bitmap, i)); if (status) break; } mutex_unlock(&pi->sched_lock); return status; } /** * ice_cfg_vsi_lan - configure VSI LAN queues * @pi: port information structure * @vsi_handle: software VSI handle * @tc_bitmap: TC bitmap * @max_lanqs: max LAN queues array per TC * * This function adds/updates the VSI LAN queues per TC. */ int ice_cfg_vsi_lan(struct ice_port_info *pi, u16 vsi_handle, u8 tc_bitmap, u16 *max_lanqs) { return ice_cfg_vsi_qs(pi, vsi_handle, tc_bitmap, max_lanqs, ICE_SCHED_NODE_OWNER_LAN); } /** * ice_cfg_vsi_rdma - configure the VSI RDMA queues * @pi: port information structure * @vsi_handle: software VSI handle * @tc_bitmap: TC bitmap * @max_rdmaqs: max RDMA queues array per TC * * This function adds/updates the VSI RDMA queues per TC. */ int ice_cfg_vsi_rdma(struct ice_port_info *pi, u16 vsi_handle, u16 tc_bitmap, u16 *max_rdmaqs) { return ice_cfg_vsi_qs(pi, vsi_handle, tc_bitmap, max_rdmaqs, ICE_SCHED_NODE_OWNER_RDMA); } /** * ice_ena_vsi_rdma_qset * @pi: port information structure * @vsi_handle: software VSI handle * @tc: TC number * @rdma_qset: pointer to RDMA Qset * @num_qsets: number of RDMA Qsets * @qset_teid: pointer to Qset node TEIDs * * This function adds RDMA Qset */ int ice_ena_vsi_rdma_qset(struct ice_port_info *pi, u16 vsi_handle, u8 tc, u16 *rdma_qset, u16 num_qsets, u32 *qset_teid) { struct ice_aqc_txsched_elem_data node = { 0 }; struct ice_aqc_add_rdma_qset_data *buf; struct ice_sched_node *parent; struct ice_hw *hw; u16 i, buf_size; int ret; if (!pi || pi->port_state != ICE_SCHED_PORT_STATE_READY) return -EIO; hw = pi->hw; if (!ice_is_vsi_valid(hw, vsi_handle)) return -EINVAL; buf_size = struct_size(buf, rdma_qsets, num_qsets); buf = kzalloc(buf_size, GFP_KERNEL); if (!buf) return -ENOMEM; mutex_lock(&pi->sched_lock); parent = ice_sched_get_free_qparent(pi, vsi_handle, tc, ICE_SCHED_NODE_OWNER_RDMA); if (!parent) { ret = -EINVAL; goto rdma_error_exit; } buf->parent_teid = parent->info.node_teid; node.parent_teid = parent->info.node_teid; buf->num_qsets = cpu_to_le16(num_qsets); for (i = 0; i < num_qsets; i++) { buf->rdma_qsets[i].tx_qset_id = cpu_to_le16(rdma_qset[i]); buf->rdma_qsets[i].info.valid_sections = ICE_AQC_ELEM_VALID_GENERIC | ICE_AQC_ELEM_VALID_CIR | ICE_AQC_ELEM_VALID_EIR; buf->rdma_qsets[i].info.generic = 0; buf->rdma_qsets[i].info.cir_bw.bw_profile_idx = cpu_to_le16(ICE_SCHED_DFLT_RL_PROF_ID); buf->rdma_qsets[i].info.cir_bw.bw_alloc = cpu_to_le16(ICE_SCHED_DFLT_BW_WT); buf->rdma_qsets[i].info.eir_bw.bw_profile_idx = cpu_to_le16(ICE_SCHED_DFLT_RL_PROF_ID); buf->rdma_qsets[i].info.eir_bw.bw_alloc = cpu_to_le16(ICE_SCHED_DFLT_BW_WT); } ret = ice_aq_add_rdma_qsets(hw, 1, buf, buf_size, NULL); if (ret) { ice_debug(hw, ICE_DBG_RDMA, "add RDMA qset failed\n"); goto rdma_error_exit; } node.data.elem_type = ICE_AQC_ELEM_TYPE_LEAF; for (i = 0; i < num_qsets; i++) { node.node_teid = buf->rdma_qsets[i].qset_teid; ret = ice_sched_add_node(pi, hw->num_tx_sched_layers - 1, &node, NULL); if (ret) break; qset_teid[i] = le32_to_cpu(node.node_teid); } rdma_error_exit: mutex_unlock(&pi->sched_lock); kfree(buf); return ret; } /** * ice_dis_vsi_rdma_qset - free RDMA resources * @pi: port_info struct * @count: number of RDMA Qsets to free * @qset_teid: TEID of Qset node * @q_id: list of queue IDs being disabled */ int ice_dis_vsi_rdma_qset(struct ice_port_info *pi, u16 count, u32 *qset_teid, u16 *q_id) { struct ice_aqc_dis_txq_item *qg_list; struct ice_hw *hw; int status = 0; u16 qg_size; int i; if (!pi || pi->port_state != ICE_SCHED_PORT_STATE_READY) return -EIO; hw = pi->hw; qg_size = struct_size(qg_list, q_id, 1); qg_list = kzalloc(qg_size, GFP_KERNEL); if (!qg_list) return -ENOMEM; mutex_lock(&pi->sched_lock); for (i = 0; i < count; i++) { struct ice_sched_node *node; node = ice_sched_find_node_by_teid(pi->root, qset_teid[i]); if (!node) continue; qg_list->parent_teid = node->info.parent_teid; qg_list->num_qs = 1; qg_list->q_id[0] = cpu_to_le16(q_id[i] | ICE_AQC_Q_DIS_BUF_ELEM_TYPE_RDMA_QSET); status = ice_aq_dis_lan_txq(hw, 1, qg_list, qg_size, ICE_NO_RESET, 0, NULL); if (status) break; ice_free_sched_node(pi, node); } mutex_unlock(&pi->sched_lock); kfree(qg_list); return status; } /** * ice_replay_pre_init - replay pre initialization * @hw: pointer to the HW struct * * Initializes required config data for VSI, FD, ACL, and RSS before replay. */ static int ice_replay_pre_init(struct ice_hw *hw) { struct ice_switch_info *sw = hw->switch_info; u8 i; /* Delete old entries from replay filter list head if there is any */ ice_rm_all_sw_replay_rule_info(hw); /* In start of replay, move entries into replay_rules list, it * will allow adding rules entries back to filt_rules list, * which is operational list. */ for (i = 0; i < ICE_MAX_NUM_RECIPES; i++) list_replace_init(&sw->recp_list[i].filt_rules, &sw->recp_list[i].filt_replay_rules); ice_sched_replay_agg_vsi_preinit(hw); return 0; } /** * ice_replay_vsi - replay VSI configuration * @hw: pointer to the HW struct * @vsi_handle: driver VSI handle * * Restore all VSI configuration after reset. It is required to call this * function with main VSI first. */ int ice_replay_vsi(struct ice_hw *hw, u16 vsi_handle) { int status; if (!ice_is_vsi_valid(hw, vsi_handle)) return -EINVAL; /* Replay pre-initialization if there is any */ if (vsi_handle == ICE_MAIN_VSI_HANDLE) { status = ice_replay_pre_init(hw); if (status) return status; } /* Replay per VSI all RSS configurations */ status = ice_replay_rss_cfg(hw, vsi_handle); if (status) return status; /* Replay per VSI all filters */ status = ice_replay_vsi_all_fltr(hw, vsi_handle); if (!status) status = ice_replay_vsi_agg(hw, vsi_handle); return status; } /** * ice_replay_post - post replay configuration cleanup * @hw: pointer to the HW struct * * Post replay cleanup. */ void ice_replay_post(struct ice_hw *hw) { /* Delete old entries from replay filter list head */ ice_rm_all_sw_replay_rule_info(hw); ice_sched_replay_agg(hw); } /** * ice_stat_update40 - read 40 bit stat from the chip and update stat values * @hw: ptr to the hardware info * @reg: offset of 64 bit HW register to read from * @prev_stat_loaded: bool to specify if previous stats are loaded * @prev_stat: ptr to previous loaded stat value * @cur_stat: ptr to current stat value */ void ice_stat_update40(struct ice_hw *hw, u32 reg, bool prev_stat_loaded, u64 *prev_stat, u64 *cur_stat) { u64 new_data = rd64(hw, reg) & (BIT_ULL(40) - 1); /* device stats are not reset at PFR, they likely will not be zeroed * when the driver starts. Thus, save the value from the first read * without adding to the statistic value so that we report stats which * count up from zero. */ if (!prev_stat_loaded) { *prev_stat = new_data; return; } /* Calculate the difference between the new and old values, and then * add it to the software stat value. */ if (new_data >= *prev_stat) *cur_stat += new_data - *prev_stat; else /* to manage the potential roll-over */ *cur_stat += (new_data + BIT_ULL(40)) - *prev_stat; /* Update the previously stored value to prepare for next read */ *prev_stat = new_data; } /** * ice_stat_update32 - read 32 bit stat from the chip and update stat values * @hw: ptr to the hardware info * @reg: offset of HW register to read from * @prev_stat_loaded: bool to specify if previous stats are loaded * @prev_stat: ptr to previous loaded stat value * @cur_stat: ptr to current stat value */ void ice_stat_update32(struct ice_hw *hw, u32 reg, bool prev_stat_loaded, u64 *prev_stat, u64 *cur_stat) { u32 new_data; new_data = rd32(hw, reg); /* device stats are not reset at PFR, they likely will not be zeroed * when the driver starts. Thus, save the value from the first read * without adding to the statistic value so that we report stats which * count up from zero. */ if (!prev_stat_loaded) { *prev_stat = new_data; return; } /* Calculate the difference between the new and old values, and then * add it to the software stat value. */ if (new_data >= *prev_stat) *cur_stat += new_data - *prev_stat; else /* to manage the potential roll-over */ *cur_stat += (new_data + BIT_ULL(32)) - *prev_stat; /* Update the previously stored value to prepare for next read */ *prev_stat = new_data; } /** * ice_sched_query_elem - query element information from HW * @hw: pointer to the HW struct * @node_teid: node TEID to be queried * @buf: buffer to element information * * This function queries HW element information */ int ice_sched_query_elem(struct ice_hw *hw, u32 node_teid, struct ice_aqc_txsched_elem_data *buf) { u16 buf_size, num_elem_ret = 0; int status; buf_size = sizeof(*buf); memset(buf, 0, buf_size); buf->node_teid = cpu_to_le32(node_teid); status = ice_aq_query_sched_elems(hw, 1, buf, buf_size, &num_elem_ret, NULL); if (status || num_elem_ret != 1) ice_debug(hw, ICE_DBG_SCHED, "query element failed\n"); return status; } /** * ice_aq_read_i2c * @hw: pointer to the hw struct * @topo_addr: topology address for a device to communicate with * @bus_addr: 7-bit I2C bus address * @addr: I2C memory address (I2C offset) with up to 16 bits * @params: I2C parameters: bit [7] - Repeated start, * bits [6:5] data offset size, * bit [4] - I2C address type, * bits [3:0] - data size to read (0-16 bytes) * @data: pointer to data (0 to 16 bytes) to be read from the I2C device * @cd: pointer to command details structure or NULL * * Read I2C (0x06E2) */ int ice_aq_read_i2c(struct ice_hw *hw, struct ice_aqc_link_topo_addr topo_addr, u16 bus_addr, __le16 addr, u8 params, u8 *data, struct ice_sq_cd *cd) { struct ice_aq_desc desc = { 0 }; struct ice_aqc_i2c *cmd; u8 data_size; int status; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_read_i2c); cmd = &desc.params.read_write_i2c; if (!data) return -EINVAL; data_size = FIELD_GET(ICE_AQC_I2C_DATA_SIZE_M, params); cmd->i2c_bus_addr = cpu_to_le16(bus_addr); cmd->topo_addr = topo_addr; cmd->i2c_params = params; cmd->i2c_addr = addr; status = ice_aq_send_cmd(hw, &desc, NULL, 0, cd); if (!status) { struct ice_aqc_read_i2c_resp *resp; u8 i; resp = &desc.params.read_i2c_resp; for (i = 0; i < data_size; i++) { *data = resp->i2c_data[i]; data++; } } return status; } /** * ice_aq_write_i2c * @hw: pointer to the hw struct * @topo_addr: topology address for a device to communicate with * @bus_addr: 7-bit I2C bus address * @addr: I2C memory address (I2C offset) with up to 16 bits * @params: I2C parameters: bit [4] - I2C address type, bits [3:0] - data size to write (0-7 bytes) * @data: pointer to data (0 to 4 bytes) to be written to the I2C device * @cd: pointer to command details structure or NULL * * Write I2C (0x06E3) * * * Return: * * 0 - Successful write to the i2c device * * -EINVAL - Data size greater than 4 bytes * * -EIO - FW error */ int ice_aq_write_i2c(struct ice_hw *hw, struct ice_aqc_link_topo_addr topo_addr, u16 bus_addr, __le16 addr, u8 params, const u8 *data, struct ice_sq_cd *cd) { struct ice_aq_desc desc = { 0 }; struct ice_aqc_i2c *cmd; u8 data_size; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_write_i2c); cmd = &desc.params.read_write_i2c; data_size = FIELD_GET(ICE_AQC_I2C_DATA_SIZE_M, params); /* data_size limited to 4 */ if (data_size > 4) return -EINVAL; cmd->i2c_bus_addr = cpu_to_le16(bus_addr); cmd->topo_addr = topo_addr; cmd->i2c_params = params; cmd->i2c_addr = addr; memcpy(cmd->i2c_data, data, data_size); return ice_aq_send_cmd(hw, &desc, NULL, 0, cd); } /** * ice_aq_set_driver_param - Set driver parameter to share via firmware * @hw: pointer to the HW struct * @idx: parameter index to set * @value: the value to set the parameter to * @cd: pointer to command details structure or NULL * * Set the value of one of the software defined parameters. All PFs connected * to this device can read the value using ice_aq_get_driver_param. * * Note that firmware provides no synchronization or locking, and will not * save the parameter value during a device reset. It is expected that * a single PF will write the parameter value, while all other PFs will only * read it. */ int ice_aq_set_driver_param(struct ice_hw *hw, enum ice_aqc_driver_params idx, u32 value, struct ice_sq_cd *cd) { struct ice_aqc_driver_shared_params *cmd; struct ice_aq_desc desc; if (idx >= ICE_AQC_DRIVER_PARAM_MAX) return -EIO; cmd = &desc.params.drv_shared_params; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_driver_shared_params); cmd->set_or_get_op = ICE_AQC_DRIVER_PARAM_SET; cmd->param_indx = idx; cmd->param_val = cpu_to_le32(value); return ice_aq_send_cmd(hw, &desc, NULL, 0, cd); } /** * ice_aq_get_driver_param - Get driver parameter shared via firmware * @hw: pointer to the HW struct * @idx: parameter index to set * @value: storage to return the shared parameter * @cd: pointer to command details structure or NULL * * Get the value of one of the software defined parameters. * * Note that firmware provides no synchronization or locking. It is expected * that only a single PF will write a given parameter. */ int ice_aq_get_driver_param(struct ice_hw *hw, enum ice_aqc_driver_params idx, u32 *value, struct ice_sq_cd *cd) { struct ice_aqc_driver_shared_params *cmd; struct ice_aq_desc desc; int status; if (idx >= ICE_AQC_DRIVER_PARAM_MAX) return -EIO; cmd = &desc.params.drv_shared_params; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_driver_shared_params); cmd->set_or_get_op = ICE_AQC_DRIVER_PARAM_GET; cmd->param_indx = idx; status = ice_aq_send_cmd(hw, &desc, NULL, 0, cd); if (status) return status; *value = le32_to_cpu(cmd->param_val); return 0; } /** * ice_aq_set_gpio * @hw: pointer to the hw struct * @gpio_ctrl_handle: GPIO controller node handle * @pin_idx: IO Number of the GPIO that needs to be set * @value: SW provide IO value to set in the LSB * @cd: pointer to command details structure or NULL * * Sends 0x06EC AQ command to set the GPIO pin state that's part of the topology */ int ice_aq_set_gpio(struct ice_hw *hw, u16 gpio_ctrl_handle, u8 pin_idx, bool value, struct ice_sq_cd *cd) { struct ice_aqc_gpio *cmd; struct ice_aq_desc desc; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_set_gpio); cmd = &desc.params.read_write_gpio; cmd->gpio_ctrl_handle = cpu_to_le16(gpio_ctrl_handle); cmd->gpio_num = pin_idx; cmd->gpio_val = value ? 1 : 0; return ice_aq_send_cmd(hw, &desc, NULL, 0, cd); } /** * ice_aq_get_gpio * @hw: pointer to the hw struct * @gpio_ctrl_handle: GPIO controller node handle * @pin_idx: IO Number of the GPIO that needs to be set * @value: IO value read * @cd: pointer to command details structure or NULL * * Sends 0x06ED AQ command to get the value of a GPIO signal which is part of * the topology */ int ice_aq_get_gpio(struct ice_hw *hw, u16 gpio_ctrl_handle, u8 pin_idx, bool *value, struct ice_sq_cd *cd) { struct ice_aqc_gpio *cmd; struct ice_aq_desc desc; int status; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_get_gpio); cmd = &desc.params.read_write_gpio; cmd->gpio_ctrl_handle = cpu_to_le16(gpio_ctrl_handle); cmd->gpio_num = pin_idx; status = ice_aq_send_cmd(hw, &desc, NULL, 0, cd); if (status) return status; *value = !!cmd->gpio_val; return 0; } /** * ice_is_fw_api_min_ver * @hw: pointer to the hardware structure * @maj: major version * @min: minor version * @patch: patch version * * Checks if the firmware API is minimum version */ static bool ice_is_fw_api_min_ver(struct ice_hw *hw, u8 maj, u8 min, u8 patch) { if (hw->api_maj_ver == maj) { if (hw->api_min_ver > min) return true; if (hw->api_min_ver == min && hw->api_patch >= patch) return true; } else if (hw->api_maj_ver > maj) { return true; } return false; } /** * ice_fw_supports_link_override * @hw: pointer to the hardware structure * * Checks if the firmware supports link override */ bool ice_fw_supports_link_override(struct ice_hw *hw) { return ice_is_fw_api_min_ver(hw, ICE_FW_API_LINK_OVERRIDE_MAJ, ICE_FW_API_LINK_OVERRIDE_MIN, ICE_FW_API_LINK_OVERRIDE_PATCH); } /** * ice_get_link_default_override * @ldo: pointer to the link default override struct * @pi: pointer to the port info struct * * Gets the link default override for a port */ int ice_get_link_default_override(struct ice_link_default_override_tlv *ldo, struct ice_port_info *pi) { u16 i, tlv, tlv_len, tlv_start, buf, offset; struct ice_hw *hw = pi->hw; int status; status = ice_get_pfa_module_tlv(hw, &tlv, &tlv_len, ICE_SR_LINK_DEFAULT_OVERRIDE_PTR); if (status) { ice_debug(hw, ICE_DBG_INIT, "Failed to read link override TLV.\n"); return status; } /* Each port has its own config; calculate for our port */ tlv_start = tlv + pi->lport * ICE_SR_PFA_LINK_OVERRIDE_WORDS + ICE_SR_PFA_LINK_OVERRIDE_OFFSET; /* link options first */ status = ice_read_sr_word(hw, tlv_start, &buf); if (status) { ice_debug(hw, ICE_DBG_INIT, "Failed to read override link options.\n"); return status; } ldo->options = buf & ICE_LINK_OVERRIDE_OPT_M; ldo->phy_config = (buf & ICE_LINK_OVERRIDE_PHY_CFG_M) >> ICE_LINK_OVERRIDE_PHY_CFG_S; /* link PHY config */ offset = tlv_start + ICE_SR_PFA_LINK_OVERRIDE_FEC_OFFSET; status = ice_read_sr_word(hw, offset, &buf); if (status) { ice_debug(hw, ICE_DBG_INIT, "Failed to read override phy config.\n"); return status; } ldo->fec_options = buf & ICE_LINK_OVERRIDE_FEC_OPT_M; /* PHY types low */ offset = tlv_start + ICE_SR_PFA_LINK_OVERRIDE_PHY_OFFSET; for (i = 0; i < ICE_SR_PFA_LINK_OVERRIDE_PHY_WORDS; i++) { status = ice_read_sr_word(hw, (offset + i), &buf); if (status) { ice_debug(hw, ICE_DBG_INIT, "Failed to read override link options.\n"); return status; } /* shift 16 bits at a time to fill 64 bits */ ldo->phy_type_low |= ((u64)buf << (i * 16)); } /* PHY types high */ offset = tlv_start + ICE_SR_PFA_LINK_OVERRIDE_PHY_OFFSET + ICE_SR_PFA_LINK_OVERRIDE_PHY_WORDS; for (i = 0; i < ICE_SR_PFA_LINK_OVERRIDE_PHY_WORDS; i++) { status = ice_read_sr_word(hw, (offset + i), &buf); if (status) { ice_debug(hw, ICE_DBG_INIT, "Failed to read override link options.\n"); return status; } /* shift 16 bits at a time to fill 64 bits */ ldo->phy_type_high |= ((u64)buf << (i * 16)); } return status; } /** * ice_is_phy_caps_an_enabled - check if PHY capabilities autoneg is enabled * @caps: get PHY capability data */ bool ice_is_phy_caps_an_enabled(struct ice_aqc_get_phy_caps_data *caps) { if (caps->caps & ICE_AQC_PHY_AN_MODE || caps->low_power_ctrl_an & (ICE_AQC_PHY_AN_EN_CLAUSE28 | ICE_AQC_PHY_AN_EN_CLAUSE73 | ICE_AQC_PHY_AN_EN_CLAUSE37)) return true; return false; } /** * ice_aq_set_lldp_mib - Set the LLDP MIB * @hw: pointer to the HW struct * @mib_type: Local, Remote or both Local and Remote MIBs * @buf: pointer to the caller-supplied buffer to store the MIB block * @buf_size: size of the buffer (in bytes) * @cd: pointer to command details structure or NULL * * Set the LLDP MIB. (0x0A08) */ int ice_aq_set_lldp_mib(struct ice_hw *hw, u8 mib_type, void *buf, u16 buf_size, struct ice_sq_cd *cd) { struct ice_aqc_lldp_set_local_mib *cmd; struct ice_aq_desc desc; cmd = &desc.params.lldp_set_mib; if (buf_size == 0 || !buf) return -EINVAL; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_lldp_set_local_mib); desc.flags |= cpu_to_le16((u16)ICE_AQ_FLAG_RD); desc.datalen = cpu_to_le16(buf_size); cmd->type = mib_type; cmd->length = cpu_to_le16(buf_size); return ice_aq_send_cmd(hw, &desc, buf, buf_size, cd); } /** * ice_fw_supports_lldp_fltr_ctrl - check NVM version supports lldp_fltr_ctrl * @hw: pointer to HW struct */ bool ice_fw_supports_lldp_fltr_ctrl(struct ice_hw *hw) { if (hw->mac_type != ICE_MAC_E810) return false; return ice_is_fw_api_min_ver(hw, ICE_FW_API_LLDP_FLTR_MAJ, ICE_FW_API_LLDP_FLTR_MIN, ICE_FW_API_LLDP_FLTR_PATCH); } /** * ice_lldp_fltr_add_remove - add or remove a LLDP Rx switch filter * @hw: pointer to HW struct * @vsi_num: absolute HW index for VSI * @add: boolean for if adding or removing a filter */ int ice_lldp_fltr_add_remove(struct ice_hw *hw, u16 vsi_num, bool add) { struct ice_aqc_lldp_filter_ctrl *cmd; struct ice_aq_desc desc; cmd = &desc.params.lldp_filter_ctrl; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_lldp_filter_ctrl); if (add) cmd->cmd_flags = ICE_AQC_LLDP_FILTER_ACTION_ADD; else cmd->cmd_flags = ICE_AQC_LLDP_FILTER_ACTION_DELETE; cmd->vsi_num = cpu_to_le16(vsi_num); return ice_aq_send_cmd(hw, &desc, NULL, 0, NULL); } /** * ice_lldp_execute_pending_mib - execute LLDP pending MIB request * @hw: pointer to HW struct */ int ice_lldp_execute_pending_mib(struct ice_hw *hw) { struct ice_aq_desc desc; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_lldp_execute_pending_mib); return ice_aq_send_cmd(hw, &desc, NULL, 0, NULL); } /** * ice_fw_supports_report_dflt_cfg * @hw: pointer to the hardware structure * * Checks if the firmware supports report default configuration */ bool ice_fw_supports_report_dflt_cfg(struct ice_hw *hw) { return ice_is_fw_api_min_ver(hw, ICE_FW_API_REPORT_DFLT_CFG_MAJ, ICE_FW_API_REPORT_DFLT_CFG_MIN, ICE_FW_API_REPORT_DFLT_CFG_PATCH); } /* each of the indexes into the following array match the speed of a return * value from the list of AQ returned speeds like the range: * ICE_AQ_LINK_SPEED_10MB .. ICE_AQ_LINK_SPEED_100GB excluding * ICE_AQ_LINK_SPEED_UNKNOWN which is BIT(15) and maps to BIT(14) in this * array. The array is defined as 15 elements long because the link_speed * returned by the firmware is a 16 bit * value, but is indexed * by [fls(speed) - 1] */ static const u32 ice_aq_to_link_speed[] = { SPEED_10, /* BIT(0) */ SPEED_100, SPEED_1000, SPEED_2500, SPEED_5000, SPEED_10000, SPEED_20000, SPEED_25000, SPEED_40000, SPEED_50000, SPEED_100000, /* BIT(10) */ }; /** * ice_get_link_speed - get integer speed from table * @index: array index from fls(aq speed) - 1 * * Returns: u32 value containing integer speed */ u32 ice_get_link_speed(u16 index) { if (index >= ARRAY_SIZE(ice_aq_to_link_speed)) return 0; return ice_aq_to_link_speed[index]; }
linux-master
drivers/net/ethernet/intel/ice/ice_common.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2019-2021, Intel Corporation. */ #include "ice.h" #include "ice_lib.h" #include "ice_eswitch.h" #include "ice_eswitch_br.h" #include "ice_fltr.h" #include "ice_repr.h" #include "ice_devlink.h" #include "ice_tc_lib.h" /** * ice_eswitch_add_vf_sp_rule - add adv rule with VF's VSI index * @pf: pointer to PF struct * @vf: pointer to VF struct * * This function adds advanced rule that forwards packets with * VF's VSI index to the corresponding switchdev ctrl VSI queue. */ static int ice_eswitch_add_vf_sp_rule(struct ice_pf *pf, struct ice_vf *vf) { struct ice_vsi *ctrl_vsi = pf->switchdev.control_vsi; struct ice_adv_rule_info rule_info = { 0 }; struct ice_adv_lkup_elem *list; struct ice_hw *hw = &pf->hw; const u16 lkups_cnt = 1; int err; list = kcalloc(lkups_cnt, sizeof(*list), GFP_ATOMIC); if (!list) return -ENOMEM; ice_rule_add_src_vsi_metadata(list); rule_info.sw_act.flag = ICE_FLTR_TX; rule_info.sw_act.vsi_handle = ctrl_vsi->idx; rule_info.sw_act.fltr_act = ICE_FWD_TO_Q; rule_info.sw_act.fwd_id.q_id = hw->func_caps.common_cap.rxq_first_id + ctrl_vsi->rxq_map[vf->vf_id]; rule_info.flags_info.act |= ICE_SINGLE_ACT_LB_ENABLE; rule_info.flags_info.act_valid = true; rule_info.tun_type = ICE_SW_TUN_AND_NON_TUN; rule_info.src_vsi = vf->lan_vsi_idx; err = ice_add_adv_rule(hw, list, lkups_cnt, &rule_info, &vf->repr->sp_rule); if (err) dev_err(ice_pf_to_dev(pf), "Unable to add VF slow-path rule in switchdev mode for VF %d", vf->vf_id); kfree(list); return err; } /** * ice_eswitch_del_vf_sp_rule - delete adv rule with VF's VSI index * @vf: pointer to the VF struct * * Delete the advanced rule that was used to forward packets with the VF's VSI * index to the corresponding switchdev ctrl VSI queue. */ static void ice_eswitch_del_vf_sp_rule(struct ice_vf *vf) { if (!vf->repr) return; ice_rem_adv_rule_by_id(&vf->pf->hw, &vf->repr->sp_rule); } /** * ice_eswitch_setup_env - configure switchdev HW filters * @pf: pointer to PF struct * * This function adds HW filters configuration specific for switchdev * mode. */ static int ice_eswitch_setup_env(struct ice_pf *pf) { struct ice_vsi *uplink_vsi = pf->switchdev.uplink_vsi; struct net_device *uplink_netdev = uplink_vsi->netdev; struct ice_vsi *ctrl_vsi = pf->switchdev.control_vsi; struct ice_vsi_vlan_ops *vlan_ops; bool rule_added = false; ice_remove_vsi_fltr(&pf->hw, uplink_vsi->idx); netif_addr_lock_bh(uplink_netdev); __dev_uc_unsync(uplink_netdev, NULL); __dev_mc_unsync(uplink_netdev, NULL); netif_addr_unlock_bh(uplink_netdev); if (ice_vsi_add_vlan_zero(uplink_vsi)) goto err_def_rx; if (!ice_is_dflt_vsi_in_use(uplink_vsi->port_info)) { if (ice_set_dflt_vsi(uplink_vsi)) goto err_def_rx; rule_added = true; } vlan_ops = ice_get_compat_vsi_vlan_ops(uplink_vsi); if (vlan_ops->dis_rx_filtering(uplink_vsi)) goto err_dis_rx; if (ice_vsi_update_security(uplink_vsi, ice_vsi_ctx_set_allow_override)) goto err_override_uplink; if (ice_vsi_update_security(ctrl_vsi, ice_vsi_ctx_set_allow_override)) goto err_override_control; if (ice_vsi_update_local_lb(uplink_vsi, true)) goto err_override_local_lb; return 0; err_override_local_lb: ice_vsi_update_security(ctrl_vsi, ice_vsi_ctx_clear_allow_override); err_override_control: ice_vsi_update_security(uplink_vsi, ice_vsi_ctx_clear_allow_override); err_override_uplink: vlan_ops->ena_rx_filtering(uplink_vsi); err_dis_rx: if (rule_added) ice_clear_dflt_vsi(uplink_vsi); err_def_rx: ice_fltr_add_mac_and_broadcast(uplink_vsi, uplink_vsi->port_info->mac.perm_addr, ICE_FWD_TO_VSI); return -ENODEV; } /** * ice_eswitch_remap_rings_to_vectors - reconfigure rings of switchdev ctrl VSI * @pf: pointer to PF struct * * In switchdev number of allocated Tx/Rx rings is equal. * * This function fills q_vectors structures associated with representor and * move each ring pairs to port representor netdevs. Each port representor * will have dedicated 1 Tx/Rx ring pair, so number of rings pair is equal to * number of VFs. */ static void ice_eswitch_remap_rings_to_vectors(struct ice_pf *pf) { struct ice_vsi *vsi = pf->switchdev.control_vsi; int q_id; ice_for_each_txq(vsi, q_id) { struct ice_q_vector *q_vector; struct ice_tx_ring *tx_ring; struct ice_rx_ring *rx_ring; struct ice_repr *repr; struct ice_vf *vf; vf = ice_get_vf_by_id(pf, q_id); if (WARN_ON(!vf)) continue; repr = vf->repr; q_vector = repr->q_vector; tx_ring = vsi->tx_rings[q_id]; rx_ring = vsi->rx_rings[q_id]; q_vector->vsi = vsi; q_vector->reg_idx = vsi->q_vectors[0]->reg_idx; q_vector->num_ring_tx = 1; q_vector->tx.tx_ring = tx_ring; tx_ring->q_vector = q_vector; tx_ring->next = NULL; tx_ring->netdev = repr->netdev; /* In switchdev mode, from OS stack perspective, there is only * one queue for given netdev, so it needs to be indexed as 0. */ tx_ring->q_index = 0; q_vector->num_ring_rx = 1; q_vector->rx.rx_ring = rx_ring; rx_ring->q_vector = q_vector; rx_ring->next = NULL; rx_ring->netdev = repr->netdev; ice_put_vf(vf); } } /** * ice_eswitch_release_reprs - clear PR VSIs configuration * @pf: poiner to PF struct * @ctrl_vsi: pointer to switchdev control VSI */ static void ice_eswitch_release_reprs(struct ice_pf *pf, struct ice_vsi *ctrl_vsi) { struct ice_vf *vf; unsigned int bkt; lockdep_assert_held(&pf->vfs.table_lock); ice_for_each_vf(pf, bkt, vf) { struct ice_vsi *vsi = vf->repr->src_vsi; /* Skip VFs that aren't configured */ if (!vf->repr->dst) continue; ice_vsi_update_security(vsi, ice_vsi_ctx_set_antispoof); metadata_dst_free(vf->repr->dst); vf->repr->dst = NULL; ice_eswitch_del_vf_sp_rule(vf); ice_fltr_add_mac_and_broadcast(vsi, vf->hw_lan_addr, ICE_FWD_TO_VSI); netif_napi_del(&vf->repr->q_vector->napi); } } /** * ice_eswitch_setup_reprs - configure port reprs to run in switchdev mode * @pf: pointer to PF struct */ static int ice_eswitch_setup_reprs(struct ice_pf *pf) { struct ice_vsi *ctrl_vsi = pf->switchdev.control_vsi; int max_vsi_num = 0; struct ice_vf *vf; unsigned int bkt; lockdep_assert_held(&pf->vfs.table_lock); ice_for_each_vf(pf, bkt, vf) { struct ice_vsi *vsi = vf->repr->src_vsi; ice_remove_vsi_fltr(&pf->hw, vsi->idx); vf->repr->dst = metadata_dst_alloc(0, METADATA_HW_PORT_MUX, GFP_KERNEL); if (!vf->repr->dst) { ice_fltr_add_mac_and_broadcast(vsi, vf->hw_lan_addr, ICE_FWD_TO_VSI); goto err; } if (ice_eswitch_add_vf_sp_rule(pf, vf)) { ice_fltr_add_mac_and_broadcast(vsi, vf->hw_lan_addr, ICE_FWD_TO_VSI); goto err; } if (ice_vsi_update_security(vsi, ice_vsi_ctx_clear_antispoof)) { ice_fltr_add_mac_and_broadcast(vsi, vf->hw_lan_addr, ICE_FWD_TO_VSI); ice_eswitch_del_vf_sp_rule(vf); metadata_dst_free(vf->repr->dst); vf->repr->dst = NULL; goto err; } if (ice_vsi_add_vlan_zero(vsi)) { ice_fltr_add_mac_and_broadcast(vsi, vf->hw_lan_addr, ICE_FWD_TO_VSI); ice_eswitch_del_vf_sp_rule(vf); metadata_dst_free(vf->repr->dst); vf->repr->dst = NULL; ice_vsi_update_security(vsi, ice_vsi_ctx_set_antispoof); goto err; } if (max_vsi_num < vsi->vsi_num) max_vsi_num = vsi->vsi_num; netif_napi_add(vf->repr->netdev, &vf->repr->q_vector->napi, ice_napi_poll); netif_keep_dst(vf->repr->netdev); } ice_for_each_vf(pf, bkt, vf) { struct ice_repr *repr = vf->repr; struct ice_vsi *vsi = repr->src_vsi; struct metadata_dst *dst; dst = repr->dst; dst->u.port_info.port_id = vsi->vsi_num; dst->u.port_info.lower_dev = repr->netdev; ice_repr_set_traffic_vsi(repr, ctrl_vsi); } return 0; err: ice_eswitch_release_reprs(pf, ctrl_vsi); return -ENODEV; } /** * ice_eswitch_update_repr - reconfigure VF port representor * @vsi: VF VSI for which port representor is configured */ void ice_eswitch_update_repr(struct ice_vsi *vsi) { struct ice_pf *pf = vsi->back; struct ice_repr *repr; struct ice_vf *vf; int ret; if (!ice_is_switchdev_running(pf)) return; vf = vsi->vf; repr = vf->repr; repr->src_vsi = vsi; repr->dst->u.port_info.port_id = vsi->vsi_num; if (repr->br_port) repr->br_port->vsi = vsi; ret = ice_vsi_update_security(vsi, ice_vsi_ctx_clear_antispoof); if (ret) { ice_fltr_add_mac_and_broadcast(vsi, vf->hw_lan_addr, ICE_FWD_TO_VSI); dev_err(ice_pf_to_dev(pf), "Failed to update VF %d port representor", vsi->vf->vf_id); } } /** * ice_eswitch_port_start_xmit - callback for packets transmit * @skb: send buffer * @netdev: network interface device structure * * Returns NETDEV_TX_OK if sent, else an error code */ netdev_tx_t ice_eswitch_port_start_xmit(struct sk_buff *skb, struct net_device *netdev) { struct ice_netdev_priv *np; struct ice_repr *repr; struct ice_vsi *vsi; np = netdev_priv(netdev); vsi = np->vsi; if (!vsi || !ice_is_switchdev_running(vsi->back)) return NETDEV_TX_BUSY; if (ice_is_reset_in_progress(vsi->back->state) || test_bit(ICE_VF_DIS, vsi->back->state)) return NETDEV_TX_BUSY; repr = ice_netdev_to_repr(netdev); skb_dst_drop(skb); dst_hold((struct dst_entry *)repr->dst); skb_dst_set(skb, (struct dst_entry *)repr->dst); skb->queue_mapping = repr->vf->vf_id; return ice_start_xmit(skb, netdev); } /** * ice_eswitch_set_target_vsi - set switchdev context in Tx context descriptor * @skb: pointer to send buffer * @off: pointer to offload struct */ void ice_eswitch_set_target_vsi(struct sk_buff *skb, struct ice_tx_offload_params *off) { struct metadata_dst *dst = skb_metadata_dst(skb); u64 cd_cmd, dst_vsi; if (!dst) { cd_cmd = ICE_TX_CTX_DESC_SWTCH_UPLINK << ICE_TXD_CTX_QW1_CMD_S; off->cd_qw1 |= (cd_cmd | ICE_TX_DESC_DTYPE_CTX); } else { cd_cmd = ICE_TX_CTX_DESC_SWTCH_VSI << ICE_TXD_CTX_QW1_CMD_S; dst_vsi = ((u64)dst->u.port_info.port_id << ICE_TXD_CTX_QW1_VSI_S) & ICE_TXD_CTX_QW1_VSI_M; off->cd_qw1 = cd_cmd | dst_vsi | ICE_TX_DESC_DTYPE_CTX; } } /** * ice_eswitch_release_env - clear switchdev HW filters * @pf: pointer to PF struct * * This function removes HW filters configuration specific for switchdev * mode and restores default legacy mode settings. */ static void ice_eswitch_release_env(struct ice_pf *pf) { struct ice_vsi *uplink_vsi = pf->switchdev.uplink_vsi; struct ice_vsi *ctrl_vsi = pf->switchdev.control_vsi; struct ice_vsi_vlan_ops *vlan_ops; vlan_ops = ice_get_compat_vsi_vlan_ops(uplink_vsi); ice_vsi_update_local_lb(uplink_vsi, false); ice_vsi_update_security(ctrl_vsi, ice_vsi_ctx_clear_allow_override); ice_vsi_update_security(uplink_vsi, ice_vsi_ctx_clear_allow_override); vlan_ops->ena_rx_filtering(uplink_vsi); ice_clear_dflt_vsi(uplink_vsi); ice_fltr_add_mac_and_broadcast(uplink_vsi, uplink_vsi->port_info->mac.perm_addr, ICE_FWD_TO_VSI); } /** * ice_eswitch_vsi_setup - configure switchdev control VSI * @pf: pointer to PF structure * @pi: pointer to port_info structure */ static struct ice_vsi * ice_eswitch_vsi_setup(struct ice_pf *pf, struct ice_port_info *pi) { struct ice_vsi_cfg_params params = {}; params.type = ICE_VSI_SWITCHDEV_CTRL; params.pi = pi; params.flags = ICE_VSI_FLAG_INIT; return ice_vsi_setup(pf, &params); } /** * ice_eswitch_napi_del - remove NAPI handle for all port representors * @pf: pointer to PF structure */ static void ice_eswitch_napi_del(struct ice_pf *pf) { struct ice_vf *vf; unsigned int bkt; lockdep_assert_held(&pf->vfs.table_lock); ice_for_each_vf(pf, bkt, vf) netif_napi_del(&vf->repr->q_vector->napi); } /** * ice_eswitch_napi_enable - enable NAPI for all port representors * @pf: pointer to PF structure */ static void ice_eswitch_napi_enable(struct ice_pf *pf) { struct ice_vf *vf; unsigned int bkt; lockdep_assert_held(&pf->vfs.table_lock); ice_for_each_vf(pf, bkt, vf) napi_enable(&vf->repr->q_vector->napi); } /** * ice_eswitch_napi_disable - disable NAPI for all port representors * @pf: pointer to PF structure */ static void ice_eswitch_napi_disable(struct ice_pf *pf) { struct ice_vf *vf; unsigned int bkt; lockdep_assert_held(&pf->vfs.table_lock); ice_for_each_vf(pf, bkt, vf) napi_disable(&vf->repr->q_vector->napi); } /** * ice_eswitch_enable_switchdev - configure eswitch in switchdev mode * @pf: pointer to PF structure */ static int ice_eswitch_enable_switchdev(struct ice_pf *pf) { struct ice_vsi *ctrl_vsi, *uplink_vsi; uplink_vsi = ice_get_main_vsi(pf); if (!uplink_vsi) return -ENODEV; if (netif_is_any_bridge_port(uplink_vsi->netdev)) { dev_err(ice_pf_to_dev(pf), "Uplink port cannot be a bridge port\n"); return -EINVAL; } pf->switchdev.control_vsi = ice_eswitch_vsi_setup(pf, pf->hw.port_info); if (!pf->switchdev.control_vsi) return -ENODEV; ctrl_vsi = pf->switchdev.control_vsi; pf->switchdev.uplink_vsi = uplink_vsi; if (ice_eswitch_setup_env(pf)) goto err_vsi; if (ice_repr_add_for_all_vfs(pf)) goto err_repr_add; if (ice_eswitch_setup_reprs(pf)) goto err_setup_reprs; ice_eswitch_remap_rings_to_vectors(pf); if (ice_vsi_open(ctrl_vsi)) goto err_setup_reprs; if (ice_eswitch_br_offloads_init(pf)) goto err_br_offloads; ice_eswitch_napi_enable(pf); return 0; err_br_offloads: ice_vsi_close(ctrl_vsi); err_setup_reprs: ice_repr_rem_from_all_vfs(pf); err_repr_add: ice_eswitch_release_env(pf); err_vsi: ice_vsi_release(ctrl_vsi); return -ENODEV; } /** * ice_eswitch_disable_switchdev - disable switchdev resources * @pf: pointer to PF structure */ static void ice_eswitch_disable_switchdev(struct ice_pf *pf) { struct ice_vsi *ctrl_vsi = pf->switchdev.control_vsi; ice_eswitch_napi_disable(pf); ice_eswitch_br_offloads_deinit(pf); ice_eswitch_release_env(pf); ice_eswitch_release_reprs(pf, ctrl_vsi); ice_vsi_release(ctrl_vsi); ice_repr_rem_from_all_vfs(pf); } /** * ice_eswitch_mode_set - set new eswitch mode * @devlink: pointer to devlink structure * @mode: eswitch mode to switch to * @extack: pointer to extack structure */ int ice_eswitch_mode_set(struct devlink *devlink, u16 mode, struct netlink_ext_ack *extack) { struct ice_pf *pf = devlink_priv(devlink); if (pf->eswitch_mode == mode) return 0; if (ice_has_vfs(pf)) { dev_info(ice_pf_to_dev(pf), "Changing eswitch mode is allowed only if there is no VFs created"); NL_SET_ERR_MSG_MOD(extack, "Changing eswitch mode is allowed only if there is no VFs created"); return -EOPNOTSUPP; } switch (mode) { case DEVLINK_ESWITCH_MODE_LEGACY: dev_info(ice_pf_to_dev(pf), "PF %d changed eswitch mode to legacy", pf->hw.pf_id); NL_SET_ERR_MSG_MOD(extack, "Changed eswitch mode to legacy"); break; case DEVLINK_ESWITCH_MODE_SWITCHDEV: { if (ice_is_adq_active(pf)) { dev_err(ice_pf_to_dev(pf), "Couldn't change eswitch mode to switchdev - ADQ is active. Delete ADQ configs and try again, e.g. tc qdisc del dev $PF root"); NL_SET_ERR_MSG_MOD(extack, "Couldn't change eswitch mode to switchdev - ADQ is active. Delete ADQ configs and try again, e.g. tc qdisc del dev $PF root"); return -EOPNOTSUPP; } dev_info(ice_pf_to_dev(pf), "PF %d changed eswitch mode to switchdev", pf->hw.pf_id); NL_SET_ERR_MSG_MOD(extack, "Changed eswitch mode to switchdev"); break; } default: NL_SET_ERR_MSG_MOD(extack, "Unknown eswitch mode"); return -EINVAL; } pf->eswitch_mode = mode; return 0; } /** * ice_eswitch_mode_get - get current eswitch mode * @devlink: pointer to devlink structure * @mode: output parameter for current eswitch mode */ int ice_eswitch_mode_get(struct devlink *devlink, u16 *mode) { struct ice_pf *pf = devlink_priv(devlink); *mode = pf->eswitch_mode; return 0; } /** * ice_is_eswitch_mode_switchdev - check if eswitch mode is set to switchdev * @pf: pointer to PF structure * * Returns true if eswitch mode is set to DEVLINK_ESWITCH_MODE_SWITCHDEV, * false otherwise. */ bool ice_is_eswitch_mode_switchdev(struct ice_pf *pf) { return pf->eswitch_mode == DEVLINK_ESWITCH_MODE_SWITCHDEV; } /** * ice_eswitch_release - cleanup eswitch * @pf: pointer to PF structure */ void ice_eswitch_release(struct ice_pf *pf) { if (pf->eswitch_mode == DEVLINK_ESWITCH_MODE_LEGACY) return; ice_eswitch_disable_switchdev(pf); pf->switchdev.is_running = false; } /** * ice_eswitch_configure - configure eswitch * @pf: pointer to PF structure */ int ice_eswitch_configure(struct ice_pf *pf) { int status; if (pf->eswitch_mode == DEVLINK_ESWITCH_MODE_LEGACY || pf->switchdev.is_running) return 0; status = ice_eswitch_enable_switchdev(pf); if (status) return status; pf->switchdev.is_running = true; return 0; } /** * ice_eswitch_start_all_tx_queues - start Tx queues of all port representors * @pf: pointer to PF structure */ static void ice_eswitch_start_all_tx_queues(struct ice_pf *pf) { struct ice_vf *vf; unsigned int bkt; lockdep_assert_held(&pf->vfs.table_lock); if (test_bit(ICE_DOWN, pf->state)) return; ice_for_each_vf(pf, bkt, vf) { if (vf->repr) ice_repr_start_tx_queues(vf->repr); } } /** * ice_eswitch_stop_all_tx_queues - stop Tx queues of all port representors * @pf: pointer to PF structure */ void ice_eswitch_stop_all_tx_queues(struct ice_pf *pf) { struct ice_vf *vf; unsigned int bkt; lockdep_assert_held(&pf->vfs.table_lock); if (test_bit(ICE_DOWN, pf->state)) return; ice_for_each_vf(pf, bkt, vf) { if (vf->repr) ice_repr_stop_tx_queues(vf->repr); } } /** * ice_eswitch_rebuild - rebuild eswitch * @pf: pointer to PF structure */ int ice_eswitch_rebuild(struct ice_pf *pf) { struct ice_vsi *ctrl_vsi = pf->switchdev.control_vsi; int status; ice_eswitch_napi_disable(pf); ice_eswitch_napi_del(pf); status = ice_eswitch_setup_env(pf); if (status) return status; status = ice_eswitch_setup_reprs(pf); if (status) return status; ice_eswitch_remap_rings_to_vectors(pf); ice_replay_tc_fltrs(pf); status = ice_vsi_open(ctrl_vsi); if (status) return status; ice_eswitch_napi_enable(pf); ice_eswitch_start_all_tx_queues(pf); return 0; }
linux-master
drivers/net/ethernet/intel/ice/ice_eswitch.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2018, Intel Corporation. */ #include "ice_common.h" #define ICE_CQ_INIT_REGS(qinfo, prefix) \ do { \ (qinfo)->sq.head = prefix##_ATQH; \ (qinfo)->sq.tail = prefix##_ATQT; \ (qinfo)->sq.len = prefix##_ATQLEN; \ (qinfo)->sq.bah = prefix##_ATQBAH; \ (qinfo)->sq.bal = prefix##_ATQBAL; \ (qinfo)->sq.len_mask = prefix##_ATQLEN_ATQLEN_M; \ (qinfo)->sq.len_ena_mask = prefix##_ATQLEN_ATQENABLE_M; \ (qinfo)->sq.len_crit_mask = prefix##_ATQLEN_ATQCRIT_M; \ (qinfo)->sq.head_mask = prefix##_ATQH_ATQH_M; \ (qinfo)->rq.head = prefix##_ARQH; \ (qinfo)->rq.tail = prefix##_ARQT; \ (qinfo)->rq.len = prefix##_ARQLEN; \ (qinfo)->rq.bah = prefix##_ARQBAH; \ (qinfo)->rq.bal = prefix##_ARQBAL; \ (qinfo)->rq.len_mask = prefix##_ARQLEN_ARQLEN_M; \ (qinfo)->rq.len_ena_mask = prefix##_ARQLEN_ARQENABLE_M; \ (qinfo)->rq.len_crit_mask = prefix##_ARQLEN_ARQCRIT_M; \ (qinfo)->rq.head_mask = prefix##_ARQH_ARQH_M; \ } while (0) /** * ice_adminq_init_regs - Initialize AdminQ registers * @hw: pointer to the hardware structure * * This assumes the alloc_sq and alloc_rq functions have already been called */ static void ice_adminq_init_regs(struct ice_hw *hw) { struct ice_ctl_q_info *cq = &hw->adminq; ICE_CQ_INIT_REGS(cq, PF_FW); } /** * ice_mailbox_init_regs - Initialize Mailbox registers * @hw: pointer to the hardware structure * * This assumes the alloc_sq and alloc_rq functions have already been called */ static void ice_mailbox_init_regs(struct ice_hw *hw) { struct ice_ctl_q_info *cq = &hw->mailboxq; ICE_CQ_INIT_REGS(cq, PF_MBX); } /** * ice_sb_init_regs - Initialize Sideband registers * @hw: pointer to the hardware structure * * This assumes the alloc_sq and alloc_rq functions have already been called */ static void ice_sb_init_regs(struct ice_hw *hw) { struct ice_ctl_q_info *cq = &hw->sbq; ICE_CQ_INIT_REGS(cq, PF_SB); } /** * ice_check_sq_alive * @hw: pointer to the HW struct * @cq: pointer to the specific Control queue * * Returns true if Queue is enabled else false. */ bool ice_check_sq_alive(struct ice_hw *hw, struct ice_ctl_q_info *cq) { /* check both queue-length and queue-enable fields */ if (cq->sq.len && cq->sq.len_mask && cq->sq.len_ena_mask) return (rd32(hw, cq->sq.len) & (cq->sq.len_mask | cq->sq.len_ena_mask)) == (cq->num_sq_entries | cq->sq.len_ena_mask); return false; } /** * ice_alloc_ctrlq_sq_ring - Allocate Control Transmit Queue (ATQ) rings * @hw: pointer to the hardware structure * @cq: pointer to the specific Control queue */ static int ice_alloc_ctrlq_sq_ring(struct ice_hw *hw, struct ice_ctl_q_info *cq) { size_t size = cq->num_sq_entries * sizeof(struct ice_aq_desc); cq->sq.desc_buf.va = dmam_alloc_coherent(ice_hw_to_dev(hw), size, &cq->sq.desc_buf.pa, GFP_KERNEL | __GFP_ZERO); if (!cq->sq.desc_buf.va) return -ENOMEM; cq->sq.desc_buf.size = size; cq->sq.cmd_buf = devm_kcalloc(ice_hw_to_dev(hw), cq->num_sq_entries, sizeof(struct ice_sq_cd), GFP_KERNEL); if (!cq->sq.cmd_buf) { dmam_free_coherent(ice_hw_to_dev(hw), cq->sq.desc_buf.size, cq->sq.desc_buf.va, cq->sq.desc_buf.pa); cq->sq.desc_buf.va = NULL; cq->sq.desc_buf.pa = 0; cq->sq.desc_buf.size = 0; return -ENOMEM; } return 0; } /** * ice_alloc_ctrlq_rq_ring - Allocate Control Receive Queue (ARQ) rings * @hw: pointer to the hardware structure * @cq: pointer to the specific Control queue */ static int ice_alloc_ctrlq_rq_ring(struct ice_hw *hw, struct ice_ctl_q_info *cq) { size_t size = cq->num_rq_entries * sizeof(struct ice_aq_desc); cq->rq.desc_buf.va = dmam_alloc_coherent(ice_hw_to_dev(hw), size, &cq->rq.desc_buf.pa, GFP_KERNEL | __GFP_ZERO); if (!cq->rq.desc_buf.va) return -ENOMEM; cq->rq.desc_buf.size = size; return 0; } /** * ice_free_cq_ring - Free control queue ring * @hw: pointer to the hardware structure * @ring: pointer to the specific control queue ring * * This assumes the posted buffers have already been cleaned * and de-allocated */ static void ice_free_cq_ring(struct ice_hw *hw, struct ice_ctl_q_ring *ring) { dmam_free_coherent(ice_hw_to_dev(hw), ring->desc_buf.size, ring->desc_buf.va, ring->desc_buf.pa); ring->desc_buf.va = NULL; ring->desc_buf.pa = 0; ring->desc_buf.size = 0; } /** * ice_alloc_rq_bufs - Allocate pre-posted buffers for the ARQ * @hw: pointer to the hardware structure * @cq: pointer to the specific Control queue */ static int ice_alloc_rq_bufs(struct ice_hw *hw, struct ice_ctl_q_info *cq) { int i; /* We'll be allocating the buffer info memory first, then we can * allocate the mapped buffers for the event processing */ cq->rq.dma_head = devm_kcalloc(ice_hw_to_dev(hw), cq->num_rq_entries, sizeof(cq->rq.desc_buf), GFP_KERNEL); if (!cq->rq.dma_head) return -ENOMEM; cq->rq.r.rq_bi = (struct ice_dma_mem *)cq->rq.dma_head; /* allocate the mapped buffers */ for (i = 0; i < cq->num_rq_entries; i++) { struct ice_aq_desc *desc; struct ice_dma_mem *bi; bi = &cq->rq.r.rq_bi[i]; bi->va = dmam_alloc_coherent(ice_hw_to_dev(hw), cq->rq_buf_size, &bi->pa, GFP_KERNEL | __GFP_ZERO); if (!bi->va) goto unwind_alloc_rq_bufs; bi->size = cq->rq_buf_size; /* now configure the descriptors for use */ desc = ICE_CTL_Q_DESC(cq->rq, i); desc->flags = cpu_to_le16(ICE_AQ_FLAG_BUF); if (cq->rq_buf_size > ICE_AQ_LG_BUF) desc->flags |= cpu_to_le16(ICE_AQ_FLAG_LB); desc->opcode = 0; /* This is in accordance with Admin queue design, there is no * register for buffer size configuration */ desc->datalen = cpu_to_le16(bi->size); desc->retval = 0; desc->cookie_high = 0; desc->cookie_low = 0; desc->params.generic.addr_high = cpu_to_le32(upper_32_bits(bi->pa)); desc->params.generic.addr_low = cpu_to_le32(lower_32_bits(bi->pa)); desc->params.generic.param0 = 0; desc->params.generic.param1 = 0; } return 0; unwind_alloc_rq_bufs: /* don't try to free the one that failed... */ i--; for (; i >= 0; i--) { dmam_free_coherent(ice_hw_to_dev(hw), cq->rq.r.rq_bi[i].size, cq->rq.r.rq_bi[i].va, cq->rq.r.rq_bi[i].pa); cq->rq.r.rq_bi[i].va = NULL; cq->rq.r.rq_bi[i].pa = 0; cq->rq.r.rq_bi[i].size = 0; } cq->rq.r.rq_bi = NULL; devm_kfree(ice_hw_to_dev(hw), cq->rq.dma_head); cq->rq.dma_head = NULL; return -ENOMEM; } /** * ice_alloc_sq_bufs - Allocate empty buffer structs for the ATQ * @hw: pointer to the hardware structure * @cq: pointer to the specific Control queue */ static int ice_alloc_sq_bufs(struct ice_hw *hw, struct ice_ctl_q_info *cq) { int i; /* No mapped memory needed yet, just the buffer info structures */ cq->sq.dma_head = devm_kcalloc(ice_hw_to_dev(hw), cq->num_sq_entries, sizeof(cq->sq.desc_buf), GFP_KERNEL); if (!cq->sq.dma_head) return -ENOMEM; cq->sq.r.sq_bi = (struct ice_dma_mem *)cq->sq.dma_head; /* allocate the mapped buffers */ for (i = 0; i < cq->num_sq_entries; i++) { struct ice_dma_mem *bi; bi = &cq->sq.r.sq_bi[i]; bi->va = dmam_alloc_coherent(ice_hw_to_dev(hw), cq->sq_buf_size, &bi->pa, GFP_KERNEL | __GFP_ZERO); if (!bi->va) goto unwind_alloc_sq_bufs; bi->size = cq->sq_buf_size; } return 0; unwind_alloc_sq_bufs: /* don't try to free the one that failed... */ i--; for (; i >= 0; i--) { dmam_free_coherent(ice_hw_to_dev(hw), cq->sq.r.sq_bi[i].size, cq->sq.r.sq_bi[i].va, cq->sq.r.sq_bi[i].pa); cq->sq.r.sq_bi[i].va = NULL; cq->sq.r.sq_bi[i].pa = 0; cq->sq.r.sq_bi[i].size = 0; } cq->sq.r.sq_bi = NULL; devm_kfree(ice_hw_to_dev(hw), cq->sq.dma_head); cq->sq.dma_head = NULL; return -ENOMEM; } static int ice_cfg_cq_regs(struct ice_hw *hw, struct ice_ctl_q_ring *ring, u16 num_entries) { /* Clear Head and Tail */ wr32(hw, ring->head, 0); wr32(hw, ring->tail, 0); /* set starting point */ wr32(hw, ring->len, (num_entries | ring->len_ena_mask)); wr32(hw, ring->bal, lower_32_bits(ring->desc_buf.pa)); wr32(hw, ring->bah, upper_32_bits(ring->desc_buf.pa)); /* Check one register to verify that config was applied */ if (rd32(hw, ring->bal) != lower_32_bits(ring->desc_buf.pa)) return -EIO; return 0; } /** * ice_cfg_sq_regs - configure Control ATQ registers * @hw: pointer to the hardware structure * @cq: pointer to the specific Control queue * * Configure base address and length registers for the transmit queue */ static int ice_cfg_sq_regs(struct ice_hw *hw, struct ice_ctl_q_info *cq) { return ice_cfg_cq_regs(hw, &cq->sq, cq->num_sq_entries); } /** * ice_cfg_rq_regs - configure Control ARQ register * @hw: pointer to the hardware structure * @cq: pointer to the specific Control queue * * Configure base address and length registers for the receive (event queue) */ static int ice_cfg_rq_regs(struct ice_hw *hw, struct ice_ctl_q_info *cq) { int status; status = ice_cfg_cq_regs(hw, &cq->rq, cq->num_rq_entries); if (status) return status; /* Update tail in the HW to post pre-allocated buffers */ wr32(hw, cq->rq.tail, (u32)(cq->num_rq_entries - 1)); return 0; } #define ICE_FREE_CQ_BUFS(hw, qi, ring) \ do { \ /* free descriptors */ \ if ((qi)->ring.r.ring##_bi) { \ int i; \ \ for (i = 0; i < (qi)->num_##ring##_entries; i++) \ if ((qi)->ring.r.ring##_bi[i].pa) { \ dmam_free_coherent(ice_hw_to_dev(hw), \ (qi)->ring.r.ring##_bi[i].size, \ (qi)->ring.r.ring##_bi[i].va, \ (qi)->ring.r.ring##_bi[i].pa); \ (qi)->ring.r.ring##_bi[i].va = NULL;\ (qi)->ring.r.ring##_bi[i].pa = 0;\ (qi)->ring.r.ring##_bi[i].size = 0;\ } \ } \ /* free the buffer info list */ \ devm_kfree(ice_hw_to_dev(hw), (qi)->ring.cmd_buf); \ /* free DMA head */ \ devm_kfree(ice_hw_to_dev(hw), (qi)->ring.dma_head); \ } while (0) /** * ice_init_sq - main initialization routine for Control ATQ * @hw: pointer to the hardware structure * @cq: pointer to the specific Control queue * * This is the main initialization routine for the Control Send Queue * Prior to calling this function, the driver *MUST* set the following fields * in the cq->structure: * - cq->num_sq_entries * - cq->sq_buf_size * * Do *NOT* hold the lock when calling this as the memory allocation routines * called are not going to be atomic context safe */ static int ice_init_sq(struct ice_hw *hw, struct ice_ctl_q_info *cq) { int ret_code; if (cq->sq.count > 0) { /* queue already initialized */ ret_code = -EBUSY; goto init_ctrlq_exit; } /* verify input for valid configuration */ if (!cq->num_sq_entries || !cq->sq_buf_size) { ret_code = -EIO; goto init_ctrlq_exit; } cq->sq.next_to_use = 0; cq->sq.next_to_clean = 0; /* allocate the ring memory */ ret_code = ice_alloc_ctrlq_sq_ring(hw, cq); if (ret_code) goto init_ctrlq_exit; /* allocate buffers in the rings */ ret_code = ice_alloc_sq_bufs(hw, cq); if (ret_code) goto init_ctrlq_free_rings; /* initialize base registers */ ret_code = ice_cfg_sq_regs(hw, cq); if (ret_code) goto init_ctrlq_free_rings; /* success! */ cq->sq.count = cq->num_sq_entries; goto init_ctrlq_exit; init_ctrlq_free_rings: ICE_FREE_CQ_BUFS(hw, cq, sq); ice_free_cq_ring(hw, &cq->sq); init_ctrlq_exit: return ret_code; } /** * ice_init_rq - initialize ARQ * @hw: pointer to the hardware structure * @cq: pointer to the specific Control queue * * The main initialization routine for the Admin Receive (Event) Queue. * Prior to calling this function, the driver *MUST* set the following fields * in the cq->structure: * - cq->num_rq_entries * - cq->rq_buf_size * * Do *NOT* hold the lock when calling this as the memory allocation routines * called are not going to be atomic context safe */ static int ice_init_rq(struct ice_hw *hw, struct ice_ctl_q_info *cq) { int ret_code; if (cq->rq.count > 0) { /* queue already initialized */ ret_code = -EBUSY; goto init_ctrlq_exit; } /* verify input for valid configuration */ if (!cq->num_rq_entries || !cq->rq_buf_size) { ret_code = -EIO; goto init_ctrlq_exit; } cq->rq.next_to_use = 0; cq->rq.next_to_clean = 0; /* allocate the ring memory */ ret_code = ice_alloc_ctrlq_rq_ring(hw, cq); if (ret_code) goto init_ctrlq_exit; /* allocate buffers in the rings */ ret_code = ice_alloc_rq_bufs(hw, cq); if (ret_code) goto init_ctrlq_free_rings; /* initialize base registers */ ret_code = ice_cfg_rq_regs(hw, cq); if (ret_code) goto init_ctrlq_free_rings; /* success! */ cq->rq.count = cq->num_rq_entries; goto init_ctrlq_exit; init_ctrlq_free_rings: ICE_FREE_CQ_BUFS(hw, cq, rq); ice_free_cq_ring(hw, &cq->rq); init_ctrlq_exit: return ret_code; } /** * ice_shutdown_sq - shutdown the Control ATQ * @hw: pointer to the hardware structure * @cq: pointer to the specific Control queue * * The main shutdown routine for the Control Transmit Queue */ static int ice_shutdown_sq(struct ice_hw *hw, struct ice_ctl_q_info *cq) { int ret_code = 0; mutex_lock(&cq->sq_lock); if (!cq->sq.count) { ret_code = -EBUSY; goto shutdown_sq_out; } /* Stop firmware AdminQ processing */ wr32(hw, cq->sq.head, 0); wr32(hw, cq->sq.tail, 0); wr32(hw, cq->sq.len, 0); wr32(hw, cq->sq.bal, 0); wr32(hw, cq->sq.bah, 0); cq->sq.count = 0; /* to indicate uninitialized queue */ /* free ring buffers and the ring itself */ ICE_FREE_CQ_BUFS(hw, cq, sq); ice_free_cq_ring(hw, &cq->sq); shutdown_sq_out: mutex_unlock(&cq->sq_lock); return ret_code; } /** * ice_aq_ver_check - Check the reported AQ API version. * @hw: pointer to the hardware structure * * Checks if the driver should load on a given AQ API version. * * Return: 'true' iff the driver should attempt to load. 'false' otherwise. */ static bool ice_aq_ver_check(struct ice_hw *hw) { if (hw->api_maj_ver > EXP_FW_API_VER_MAJOR) { /* Major API version is newer than expected, don't load */ dev_warn(ice_hw_to_dev(hw), "The driver for the device stopped because the NVM image is newer than expected. You must install the most recent version of the network driver.\n"); return false; } else if (hw->api_maj_ver == EXP_FW_API_VER_MAJOR) { if (hw->api_min_ver > (EXP_FW_API_VER_MINOR + 2)) dev_info(ice_hw_to_dev(hw), "The driver for the device detected a newer version of the NVM image than expected. Please install the most recent version of the network driver.\n"); else if ((hw->api_min_ver + 2) < EXP_FW_API_VER_MINOR) dev_info(ice_hw_to_dev(hw), "The driver for the device detected an older version of the NVM image than expected. Please update the NVM image.\n"); } else { /* Major API version is older than expected, log a warning */ dev_info(ice_hw_to_dev(hw), "The driver for the device detected an older version of the NVM image than expected. Please update the NVM image.\n"); } return true; } /** * ice_shutdown_rq - shutdown Control ARQ * @hw: pointer to the hardware structure * @cq: pointer to the specific Control queue * * The main shutdown routine for the Control Receive Queue */ static int ice_shutdown_rq(struct ice_hw *hw, struct ice_ctl_q_info *cq) { int ret_code = 0; mutex_lock(&cq->rq_lock); if (!cq->rq.count) { ret_code = -EBUSY; goto shutdown_rq_out; } /* Stop Control Queue processing */ wr32(hw, cq->rq.head, 0); wr32(hw, cq->rq.tail, 0); wr32(hw, cq->rq.len, 0); wr32(hw, cq->rq.bal, 0); wr32(hw, cq->rq.bah, 0); /* set rq.count to 0 to indicate uninitialized queue */ cq->rq.count = 0; /* free ring buffers and the ring itself */ ICE_FREE_CQ_BUFS(hw, cq, rq); ice_free_cq_ring(hw, &cq->rq); shutdown_rq_out: mutex_unlock(&cq->rq_lock); return ret_code; } /** * ice_init_check_adminq - Check version for Admin Queue to know if its alive * @hw: pointer to the hardware structure */ static int ice_init_check_adminq(struct ice_hw *hw) { struct ice_ctl_q_info *cq = &hw->adminq; int status; status = ice_aq_get_fw_ver(hw, NULL); if (status) goto init_ctrlq_free_rq; if (!ice_aq_ver_check(hw)) { status = -EIO; goto init_ctrlq_free_rq; } return 0; init_ctrlq_free_rq: ice_shutdown_rq(hw, cq); ice_shutdown_sq(hw, cq); return status; } /** * ice_init_ctrlq - main initialization routine for any control Queue * @hw: pointer to the hardware structure * @q_type: specific Control queue type * * Prior to calling this function, the driver *MUST* set the following fields * in the cq->structure: * - cq->num_sq_entries * - cq->num_rq_entries * - cq->rq_buf_size * - cq->sq_buf_size * * NOTE: this function does not initialize the controlq locks */ static int ice_init_ctrlq(struct ice_hw *hw, enum ice_ctl_q q_type) { struct ice_ctl_q_info *cq; int ret_code; switch (q_type) { case ICE_CTL_Q_ADMIN: ice_adminq_init_regs(hw); cq = &hw->adminq; break; case ICE_CTL_Q_SB: ice_sb_init_regs(hw); cq = &hw->sbq; break; case ICE_CTL_Q_MAILBOX: ice_mailbox_init_regs(hw); cq = &hw->mailboxq; break; default: return -EINVAL; } cq->qtype = q_type; /* verify input for valid configuration */ if (!cq->num_rq_entries || !cq->num_sq_entries || !cq->rq_buf_size || !cq->sq_buf_size) { return -EIO; } /* allocate the ATQ */ ret_code = ice_init_sq(hw, cq); if (ret_code) return ret_code; /* allocate the ARQ */ ret_code = ice_init_rq(hw, cq); if (ret_code) goto init_ctrlq_free_sq; /* success! */ return 0; init_ctrlq_free_sq: ice_shutdown_sq(hw, cq); return ret_code; } /** * ice_is_sbq_supported - is the sideband queue supported * @hw: pointer to the hardware structure * * Returns true if the sideband control queue interface is * supported for the device, false otherwise */ bool ice_is_sbq_supported(struct ice_hw *hw) { /* The device sideband queue is only supported on devices with the * generic MAC type. */ return hw->mac_type == ICE_MAC_GENERIC; } /** * ice_get_sbq - returns the right control queue to use for sideband * @hw: pointer to the hardware structure */ struct ice_ctl_q_info *ice_get_sbq(struct ice_hw *hw) { if (ice_is_sbq_supported(hw)) return &hw->sbq; return &hw->adminq; } /** * ice_shutdown_ctrlq - shutdown routine for any control queue * @hw: pointer to the hardware structure * @q_type: specific Control queue type * * NOTE: this function does not destroy the control queue locks. */ static void ice_shutdown_ctrlq(struct ice_hw *hw, enum ice_ctl_q q_type) { struct ice_ctl_q_info *cq; switch (q_type) { case ICE_CTL_Q_ADMIN: cq = &hw->adminq; if (ice_check_sq_alive(hw, cq)) ice_aq_q_shutdown(hw, true); break; case ICE_CTL_Q_SB: cq = &hw->sbq; break; case ICE_CTL_Q_MAILBOX: cq = &hw->mailboxq; break; default: return; } ice_shutdown_sq(hw, cq); ice_shutdown_rq(hw, cq); } /** * ice_shutdown_all_ctrlq - shutdown routine for all control queues * @hw: pointer to the hardware structure * * NOTE: this function does not destroy the control queue locks. The driver * may call this at runtime to shutdown and later restart control queues, such * as in response to a reset event. */ void ice_shutdown_all_ctrlq(struct ice_hw *hw) { /* Shutdown FW admin queue */ ice_shutdown_ctrlq(hw, ICE_CTL_Q_ADMIN); /* Shutdown PHY Sideband */ if (ice_is_sbq_supported(hw)) ice_shutdown_ctrlq(hw, ICE_CTL_Q_SB); /* Shutdown PF-VF Mailbox */ ice_shutdown_ctrlq(hw, ICE_CTL_Q_MAILBOX); } /** * ice_init_all_ctrlq - main initialization routine for all control queues * @hw: pointer to the hardware structure * * Prior to calling this function, the driver MUST* set the following fields * in the cq->structure for all control queues: * - cq->num_sq_entries * - cq->num_rq_entries * - cq->rq_buf_size * - cq->sq_buf_size * * NOTE: this function does not initialize the controlq locks. */ int ice_init_all_ctrlq(struct ice_hw *hw) { u32 retry = 0; int status; /* Init FW admin queue */ do { status = ice_init_ctrlq(hw, ICE_CTL_Q_ADMIN); if (status) return status; status = ice_init_check_adminq(hw); if (status != -EIO) break; ice_debug(hw, ICE_DBG_AQ_MSG, "Retry Admin Queue init due to FW critical error\n"); ice_shutdown_ctrlq(hw, ICE_CTL_Q_ADMIN); msleep(ICE_CTL_Q_ADMIN_INIT_MSEC); } while (retry++ < ICE_CTL_Q_ADMIN_INIT_TIMEOUT); if (status) return status; /* sideband control queue (SBQ) interface is not supported on some * devices. Initialize if supported, else fallback to the admin queue * interface */ if (ice_is_sbq_supported(hw)) { status = ice_init_ctrlq(hw, ICE_CTL_Q_SB); if (status) return status; } /* Init Mailbox queue */ return ice_init_ctrlq(hw, ICE_CTL_Q_MAILBOX); } /** * ice_init_ctrlq_locks - Initialize locks for a control queue * @cq: pointer to the control queue * * Initializes the send and receive queue locks for a given control queue. */ static void ice_init_ctrlq_locks(struct ice_ctl_q_info *cq) { mutex_init(&cq->sq_lock); mutex_init(&cq->rq_lock); } /** * ice_create_all_ctrlq - main initialization routine for all control queues * @hw: pointer to the hardware structure * * Prior to calling this function, the driver *MUST* set the following fields * in the cq->structure for all control queues: * - cq->num_sq_entries * - cq->num_rq_entries * - cq->rq_buf_size * - cq->sq_buf_size * * This function creates all the control queue locks and then calls * ice_init_all_ctrlq. It should be called once during driver load. If the * driver needs to re-initialize control queues at run time it should call * ice_init_all_ctrlq instead. */ int ice_create_all_ctrlq(struct ice_hw *hw) { ice_init_ctrlq_locks(&hw->adminq); if (ice_is_sbq_supported(hw)) ice_init_ctrlq_locks(&hw->sbq); ice_init_ctrlq_locks(&hw->mailboxq); return ice_init_all_ctrlq(hw); } /** * ice_destroy_ctrlq_locks - Destroy locks for a control queue * @cq: pointer to the control queue * * Destroys the send and receive queue locks for a given control queue. */ static void ice_destroy_ctrlq_locks(struct ice_ctl_q_info *cq) { mutex_destroy(&cq->sq_lock); mutex_destroy(&cq->rq_lock); } /** * ice_destroy_all_ctrlq - exit routine for all control queues * @hw: pointer to the hardware structure * * This function shuts down all the control queues and then destroys the * control queue locks. It should be called once during driver unload. The * driver should call ice_shutdown_all_ctrlq if it needs to shut down and * reinitialize control queues, such as in response to a reset event. */ void ice_destroy_all_ctrlq(struct ice_hw *hw) { /* shut down all the control queues first */ ice_shutdown_all_ctrlq(hw); ice_destroy_ctrlq_locks(&hw->adminq); if (ice_is_sbq_supported(hw)) ice_destroy_ctrlq_locks(&hw->sbq); ice_destroy_ctrlq_locks(&hw->mailboxq); } /** * ice_clean_sq - cleans Admin send queue (ATQ) * @hw: pointer to the hardware structure * @cq: pointer to the specific Control queue * * returns the number of free desc */ static u16 ice_clean_sq(struct ice_hw *hw, struct ice_ctl_q_info *cq) { struct ice_ctl_q_ring *sq = &cq->sq; u16 ntc = sq->next_to_clean; struct ice_sq_cd *details; struct ice_aq_desc *desc; desc = ICE_CTL_Q_DESC(*sq, ntc); details = ICE_CTL_Q_DETAILS(*sq, ntc); while (rd32(hw, cq->sq.head) != ntc) { ice_debug(hw, ICE_DBG_AQ_MSG, "ntc %d head %d.\n", ntc, rd32(hw, cq->sq.head)); memset(desc, 0, sizeof(*desc)); memset(details, 0, sizeof(*details)); ntc++; if (ntc == sq->count) ntc = 0; desc = ICE_CTL_Q_DESC(*sq, ntc); details = ICE_CTL_Q_DETAILS(*sq, ntc); } sq->next_to_clean = ntc; return ICE_CTL_Q_DESC_UNUSED(sq); } /** * ice_debug_cq * @hw: pointer to the hardware structure * @desc: pointer to control queue descriptor * @buf: pointer to command buffer * @buf_len: max length of buf * * Dumps debug log about control command with descriptor contents. */ static void ice_debug_cq(struct ice_hw *hw, void *desc, void *buf, u16 buf_len) { struct ice_aq_desc *cq_desc = desc; u16 len; if (!IS_ENABLED(CONFIG_DYNAMIC_DEBUG) && !((ICE_DBG_AQ_DESC | ICE_DBG_AQ_DESC_BUF) & hw->debug_mask)) return; if (!desc) return; len = le16_to_cpu(cq_desc->datalen); ice_debug(hw, ICE_DBG_AQ_DESC, "CQ CMD: opcode 0x%04X, flags 0x%04X, datalen 0x%04X, retval 0x%04X\n", le16_to_cpu(cq_desc->opcode), le16_to_cpu(cq_desc->flags), le16_to_cpu(cq_desc->datalen), le16_to_cpu(cq_desc->retval)); ice_debug(hw, ICE_DBG_AQ_DESC, "\tcookie (h,l) 0x%08X 0x%08X\n", le32_to_cpu(cq_desc->cookie_high), le32_to_cpu(cq_desc->cookie_low)); ice_debug(hw, ICE_DBG_AQ_DESC, "\tparam (0,1) 0x%08X 0x%08X\n", le32_to_cpu(cq_desc->params.generic.param0), le32_to_cpu(cq_desc->params.generic.param1)); ice_debug(hw, ICE_DBG_AQ_DESC, "\taddr (h,l) 0x%08X 0x%08X\n", le32_to_cpu(cq_desc->params.generic.addr_high), le32_to_cpu(cq_desc->params.generic.addr_low)); if (buf && cq_desc->datalen != 0) { ice_debug(hw, ICE_DBG_AQ_DESC_BUF, "Buffer:\n"); if (buf_len < len) len = buf_len; ice_debug_array(hw, ICE_DBG_AQ_DESC_BUF, 16, 1, buf, len); } } /** * ice_sq_done - check if FW has processed the Admin Send Queue (ATQ) * @hw: pointer to the HW struct * @cq: pointer to the specific Control queue * * Returns true if the firmware has processed all descriptors on the * admin send queue. Returns false if there are still requests pending. */ static bool ice_sq_done(struct ice_hw *hw, struct ice_ctl_q_info *cq) { /* AQ designers suggest use of head for better * timing reliability than DD bit */ return rd32(hw, cq->sq.head) == cq->sq.next_to_use; } /** * ice_sq_send_cmd - send command to Control Queue (ATQ) * @hw: pointer to the HW struct * @cq: pointer to the specific Control queue * @desc: prefilled descriptor describing the command * @buf: buffer to use for indirect commands (or NULL for direct commands) * @buf_size: size of buffer for indirect commands (or 0 for direct commands) * @cd: pointer to command details structure * * This is the main send command routine for the ATQ. It runs the queue, * cleans the queue, etc. */ int ice_sq_send_cmd(struct ice_hw *hw, struct ice_ctl_q_info *cq, struct ice_aq_desc *desc, void *buf, u16 buf_size, struct ice_sq_cd *cd) { struct ice_dma_mem *dma_buf = NULL; struct ice_aq_desc *desc_on_ring; bool cmd_completed = false; struct ice_sq_cd *details; unsigned long timeout; int status = 0; u16 retval = 0; u32 val = 0; /* if reset is in progress return a soft error */ if (hw->reset_ongoing) return -EBUSY; mutex_lock(&cq->sq_lock); cq->sq_last_status = ICE_AQ_RC_OK; if (!cq->sq.count) { ice_debug(hw, ICE_DBG_AQ_MSG, "Control Send queue not initialized.\n"); status = -EIO; goto sq_send_command_error; } if ((buf && !buf_size) || (!buf && buf_size)) { status = -EINVAL; goto sq_send_command_error; } if (buf) { if (buf_size > cq->sq_buf_size) { ice_debug(hw, ICE_DBG_AQ_MSG, "Invalid buffer size for Control Send queue: %d.\n", buf_size); status = -EINVAL; goto sq_send_command_error; } desc->flags |= cpu_to_le16(ICE_AQ_FLAG_BUF); if (buf_size > ICE_AQ_LG_BUF) desc->flags |= cpu_to_le16(ICE_AQ_FLAG_LB); } val = rd32(hw, cq->sq.head); if (val >= cq->num_sq_entries) { ice_debug(hw, ICE_DBG_AQ_MSG, "head overrun at %d in the Control Send Queue ring\n", val); status = -EIO; goto sq_send_command_error; } details = ICE_CTL_Q_DETAILS(cq->sq, cq->sq.next_to_use); if (cd) *details = *cd; else memset(details, 0, sizeof(*details)); /* Call clean and check queue available function to reclaim the * descriptors that were processed by FW/MBX; the function returns the * number of desc available. The clean function called here could be * called in a separate thread in case of asynchronous completions. */ if (ice_clean_sq(hw, cq) == 0) { ice_debug(hw, ICE_DBG_AQ_MSG, "Error: Control Send Queue is full.\n"); status = -ENOSPC; goto sq_send_command_error; } /* initialize the temp desc pointer with the right desc */ desc_on_ring = ICE_CTL_Q_DESC(cq->sq, cq->sq.next_to_use); /* if the desc is available copy the temp desc to the right place */ memcpy(desc_on_ring, desc, sizeof(*desc_on_ring)); /* if buf is not NULL assume indirect command */ if (buf) { dma_buf = &cq->sq.r.sq_bi[cq->sq.next_to_use]; /* copy the user buf into the respective DMA buf */ memcpy(dma_buf->va, buf, buf_size); desc_on_ring->datalen = cpu_to_le16(buf_size); /* Update the address values in the desc with the pa value * for respective buffer */ desc_on_ring->params.generic.addr_high = cpu_to_le32(upper_32_bits(dma_buf->pa)); desc_on_ring->params.generic.addr_low = cpu_to_le32(lower_32_bits(dma_buf->pa)); } /* Debug desc and buffer */ ice_debug(hw, ICE_DBG_AQ_DESC, "ATQ: Control Send queue desc and buffer:\n"); ice_debug_cq(hw, (void *)desc_on_ring, buf, buf_size); (cq->sq.next_to_use)++; if (cq->sq.next_to_use == cq->sq.count) cq->sq.next_to_use = 0; wr32(hw, cq->sq.tail, cq->sq.next_to_use); ice_flush(hw); /* Wait a short time before initial ice_sq_done() check, to allow * hardware time for completion. */ udelay(5); timeout = jiffies + ICE_CTL_Q_SQ_CMD_TIMEOUT; do { if (ice_sq_done(hw, cq)) break; usleep_range(100, 150); } while (time_before(jiffies, timeout)); /* if ready, copy the desc back to temp */ if (ice_sq_done(hw, cq)) { memcpy(desc, desc_on_ring, sizeof(*desc)); if (buf) { /* get returned length to copy */ u16 copy_size = le16_to_cpu(desc->datalen); if (copy_size > buf_size) { ice_debug(hw, ICE_DBG_AQ_MSG, "Return len %d > than buf len %d\n", copy_size, buf_size); status = -EIO; } else { memcpy(buf, dma_buf->va, copy_size); } } retval = le16_to_cpu(desc->retval); if (retval) { ice_debug(hw, ICE_DBG_AQ_MSG, "Control Send Queue command 0x%04X completed with error 0x%X\n", le16_to_cpu(desc->opcode), retval); /* strip off FW internal code */ retval &= 0xff; } cmd_completed = true; if (!status && retval != ICE_AQ_RC_OK) status = -EIO; cq->sq_last_status = (enum ice_aq_err)retval; } ice_debug(hw, ICE_DBG_AQ_MSG, "ATQ: desc and buffer writeback:\n"); ice_debug_cq(hw, (void *)desc, buf, buf_size); /* save writeback AQ if requested */ if (details->wb_desc) memcpy(details->wb_desc, desc_on_ring, sizeof(*details->wb_desc)); /* update the error if time out occurred */ if (!cmd_completed) { if (rd32(hw, cq->rq.len) & cq->rq.len_crit_mask || rd32(hw, cq->sq.len) & cq->sq.len_crit_mask) { ice_debug(hw, ICE_DBG_AQ_MSG, "Critical FW error.\n"); status = -EIO; } else { ice_debug(hw, ICE_DBG_AQ_MSG, "Control Send Queue Writeback timeout.\n"); status = -EIO; } } sq_send_command_error: mutex_unlock(&cq->sq_lock); return status; } /** * ice_fill_dflt_direct_cmd_desc - AQ descriptor helper function * @desc: pointer to the temp descriptor (non DMA mem) * @opcode: the opcode can be used to decide which flags to turn off or on * * Fill the desc with default values */ void ice_fill_dflt_direct_cmd_desc(struct ice_aq_desc *desc, u16 opcode) { /* zero out the desc */ memset(desc, 0, sizeof(*desc)); desc->opcode = cpu_to_le16(opcode); desc->flags = cpu_to_le16(ICE_AQ_FLAG_SI); } /** * ice_clean_rq_elem * @hw: pointer to the HW struct * @cq: pointer to the specific Control queue * @e: event info from the receive descriptor, includes any buffers * @pending: number of events that could be left to process * * This function cleans one Admin Receive Queue element and returns * the contents through e. It can also return how many events are * left to process through 'pending'. */ int ice_clean_rq_elem(struct ice_hw *hw, struct ice_ctl_q_info *cq, struct ice_rq_event_info *e, u16 *pending) { u16 ntc = cq->rq.next_to_clean; enum ice_aq_err rq_last_status; struct ice_aq_desc *desc; struct ice_dma_mem *bi; int ret_code = 0; u16 desc_idx; u16 datalen; u16 flags; u16 ntu; /* pre-clean the event info */ memset(&e->desc, 0, sizeof(e->desc)); /* take the lock before we start messing with the ring */ mutex_lock(&cq->rq_lock); if (!cq->rq.count) { ice_debug(hw, ICE_DBG_AQ_MSG, "Control Receive queue not initialized.\n"); ret_code = -EIO; goto clean_rq_elem_err; } /* set next_to_use to head */ ntu = (u16)(rd32(hw, cq->rq.head) & cq->rq.head_mask); if (ntu == ntc) { /* nothing to do - shouldn't need to update ring's values */ ret_code = -EALREADY; goto clean_rq_elem_out; } /* now clean the next descriptor */ desc = ICE_CTL_Q_DESC(cq->rq, ntc); desc_idx = ntc; rq_last_status = (enum ice_aq_err)le16_to_cpu(desc->retval); flags = le16_to_cpu(desc->flags); if (flags & ICE_AQ_FLAG_ERR) { ret_code = -EIO; ice_debug(hw, ICE_DBG_AQ_MSG, "Control Receive Queue Event 0x%04X received with error 0x%X\n", le16_to_cpu(desc->opcode), rq_last_status); } memcpy(&e->desc, desc, sizeof(e->desc)); datalen = le16_to_cpu(desc->datalen); e->msg_len = min_t(u16, datalen, e->buf_len); if (e->msg_buf && e->msg_len) memcpy(e->msg_buf, cq->rq.r.rq_bi[desc_idx].va, e->msg_len); ice_debug(hw, ICE_DBG_AQ_DESC, "ARQ: desc and buffer:\n"); ice_debug_cq(hw, (void *)desc, e->msg_buf, cq->rq_buf_size); /* Restore the original datalen and buffer address in the desc, * FW updates datalen to indicate the event message size */ bi = &cq->rq.r.rq_bi[ntc]; memset(desc, 0, sizeof(*desc)); desc->flags = cpu_to_le16(ICE_AQ_FLAG_BUF); if (cq->rq_buf_size > ICE_AQ_LG_BUF) desc->flags |= cpu_to_le16(ICE_AQ_FLAG_LB); desc->datalen = cpu_to_le16(bi->size); desc->params.generic.addr_high = cpu_to_le32(upper_32_bits(bi->pa)); desc->params.generic.addr_low = cpu_to_le32(lower_32_bits(bi->pa)); /* set tail = the last cleaned desc index. */ wr32(hw, cq->rq.tail, ntc); /* ntc is updated to tail + 1 */ ntc++; if (ntc == cq->num_rq_entries) ntc = 0; cq->rq.next_to_clean = ntc; cq->rq.next_to_use = ntu; clean_rq_elem_out: /* Set pending if needed, unlock and return */ if (pending) { /* re-read HW head to calculate actual pending messages */ ntu = (u16)(rd32(hw, cq->rq.head) & cq->rq.head_mask); *pending = (u16)((ntc > ntu ? cq->rq.count : 0) + (ntu - ntc)); } clean_rq_elem_err: mutex_unlock(&cq->rq_lock); return ret_code; }
linux-master
drivers/net/ethernet/intel/ice/ice_controlq.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2019, Intel Corporation. */ #include "ice_dcb_lib.h" #include "ice_dcb_nl.h" #include "ice_devlink.h" /** * ice_dcb_get_ena_tc - return bitmap of enabled TCs * @dcbcfg: DCB config to evaluate for enabled TCs */ static u8 ice_dcb_get_ena_tc(struct ice_dcbx_cfg *dcbcfg) { u8 i, num_tc, ena_tc = 1; num_tc = ice_dcb_get_num_tc(dcbcfg); for (i = 0; i < num_tc; i++) ena_tc |= BIT(i); return ena_tc; } /** * ice_is_pfc_causing_hung_q * @pf: pointer to PF structure * @txqueue: Tx queue which is supposedly hung queue * * find if PFC is causing the hung queue, if yes return true else false */ bool ice_is_pfc_causing_hung_q(struct ice_pf *pf, unsigned int txqueue) { u8 num_tcs = 0, i, tc, up_mapped_tc, up_in_tc = 0; u64 ref_prio_xoff[ICE_MAX_UP]; struct ice_vsi *vsi; u32 up2tc; vsi = ice_get_main_vsi(pf); if (!vsi) return false; ice_for_each_traffic_class(i) if (vsi->tc_cfg.ena_tc & BIT(i)) num_tcs++; /* first find out the TC to which the hung queue belongs to */ for (tc = 0; tc < num_tcs - 1; tc++) if (ice_find_q_in_range(vsi->tc_cfg.tc_info[tc].qoffset, vsi->tc_cfg.tc_info[tc + 1].qoffset, txqueue)) break; /* Build a bit map of all UPs associated to the suspect hung queue TC, * so that we check for its counter increment. */ up2tc = rd32(&pf->hw, PRTDCB_TUP2TC); for (i = 0; i < ICE_MAX_UP; i++) { up_mapped_tc = (up2tc >> (i * 3)) & 0x7; if (up_mapped_tc == tc) up_in_tc |= BIT(i); } /* Now that we figured out that hung queue is PFC enabled, still the * Tx timeout can be legitimate. So to make sure Tx timeout is * absolutely caused by PFC storm, check if the counters are * incrementing. */ for (i = 0; i < ICE_MAX_UP; i++) if (up_in_tc & BIT(i)) ref_prio_xoff[i] = pf->stats.priority_xoff_rx[i]; ice_update_dcb_stats(pf); for (i = 0; i < ICE_MAX_UP; i++) if (up_in_tc & BIT(i)) if (pf->stats.priority_xoff_rx[i] > ref_prio_xoff[i]) return true; return false; } /** * ice_dcb_get_mode - gets the DCB mode * @port_info: pointer to port info structure * @host: if set it's HOST if not it's MANAGED */ static u8 ice_dcb_get_mode(struct ice_port_info *port_info, bool host) { u8 mode; if (host) mode = DCB_CAP_DCBX_HOST; else mode = DCB_CAP_DCBX_LLD_MANAGED; if (port_info->qos_cfg.local_dcbx_cfg.dcbx_mode & ICE_DCBX_MODE_CEE) return mode | DCB_CAP_DCBX_VER_CEE; else return mode | DCB_CAP_DCBX_VER_IEEE; } /** * ice_dcb_get_num_tc - Get the number of TCs from DCBX config * @dcbcfg: config to retrieve number of TCs from */ u8 ice_dcb_get_num_tc(struct ice_dcbx_cfg *dcbcfg) { bool tc_unused = false; u8 num_tc = 0; u8 ret = 0; int i; /* Scan the ETS Config Priority Table to find traffic classes * enabled and create a bitmask of enabled TCs */ for (i = 0; i < CEE_DCBX_MAX_PRIO; i++) num_tc |= BIT(dcbcfg->etscfg.prio_table[i]); /* Scan bitmask for contiguous TCs starting with TC0 */ for (i = 0; i < IEEE_8021QAZ_MAX_TCS; i++) { if (num_tc & BIT(i)) { if (!tc_unused) { ret++; } else { pr_err("Non-contiguous TCs - Disabling DCB\n"); return 1; } } else { tc_unused = true; } } /* There is always at least 1 TC */ if (!ret) ret = 1; return ret; } /** * ice_get_first_droptc - returns number of first droptc * @vsi: used to find the first droptc * * This function returns the value of first_droptc. * When DCB is enabled, first droptc information is derived from enabled_tc * and PFC enabled bits. otherwise this function returns 0 as there is one * TC without DCB (tc0) */ static u8 ice_get_first_droptc(struct ice_vsi *vsi) { struct ice_dcbx_cfg *cfg = &vsi->port_info->qos_cfg.local_dcbx_cfg; struct device *dev = ice_pf_to_dev(vsi->back); u8 num_tc, ena_tc_map, pfc_ena_map; u8 i; num_tc = ice_dcb_get_num_tc(cfg); /* get bitmap of enabled TCs */ ena_tc_map = ice_dcb_get_ena_tc(cfg); /* get bitmap of PFC enabled TCs */ pfc_ena_map = cfg->pfc.pfcena; /* get first TC that is not PFC enabled */ for (i = 0; i < num_tc; i++) { if ((ena_tc_map & BIT(i)) && (!(pfc_ena_map & BIT(i)))) { dev_dbg(dev, "first drop tc = %d\n", i); return i; } } dev_dbg(dev, "first drop tc = 0\n"); return 0; } /** * ice_vsi_set_dcb_tc_cfg - Set VSI's TC based on DCB configuration * @vsi: pointer to the VSI instance */ void ice_vsi_set_dcb_tc_cfg(struct ice_vsi *vsi) { struct ice_dcbx_cfg *cfg = &vsi->port_info->qos_cfg.local_dcbx_cfg; switch (vsi->type) { case ICE_VSI_PF: vsi->tc_cfg.ena_tc = ice_dcb_get_ena_tc(cfg); vsi->tc_cfg.numtc = ice_dcb_get_num_tc(cfg); break; case ICE_VSI_CHNL: vsi->tc_cfg.ena_tc = BIT(ice_get_first_droptc(vsi)); vsi->tc_cfg.numtc = 1; break; case ICE_VSI_CTRL: case ICE_VSI_LB: default: vsi->tc_cfg.ena_tc = ICE_DFLT_TRAFFIC_CLASS; vsi->tc_cfg.numtc = 1; } } /** * ice_dcb_get_tc - Get the TC associated with the queue * @vsi: ptr to the VSI * @queue_index: queue number associated with VSI */ u8 ice_dcb_get_tc(struct ice_vsi *vsi, int queue_index) { return vsi->tx_rings[queue_index]->dcb_tc; } /** * ice_vsi_cfg_dcb_rings - Update rings to reflect DCB TC * @vsi: VSI owner of rings being updated */ void ice_vsi_cfg_dcb_rings(struct ice_vsi *vsi) { struct ice_tx_ring *tx_ring; struct ice_rx_ring *rx_ring; u16 qoffset, qcount; int i, n; if (!test_bit(ICE_FLAG_DCB_ENA, vsi->back->flags)) { /* Reset the TC information */ ice_for_each_txq(vsi, i) { tx_ring = vsi->tx_rings[i]; tx_ring->dcb_tc = 0; } ice_for_each_rxq(vsi, i) { rx_ring = vsi->rx_rings[i]; rx_ring->dcb_tc = 0; } return; } ice_for_each_traffic_class(n) { if (!(vsi->tc_cfg.ena_tc & BIT(n))) break; qoffset = vsi->tc_cfg.tc_info[n].qoffset; qcount = vsi->tc_cfg.tc_info[n].qcount_tx; for (i = qoffset; i < (qoffset + qcount); i++) vsi->tx_rings[i]->dcb_tc = n; qcount = vsi->tc_cfg.tc_info[n].qcount_rx; for (i = qoffset; i < (qoffset + qcount); i++) vsi->rx_rings[i]->dcb_tc = n; } /* applicable only if "all_enatc" is set, which will be set from * setup_tc method as part of configuring channels */ if (vsi->all_enatc) { u8 first_droptc = ice_get_first_droptc(vsi); /* When DCB is configured, TC for ADQ queues (which are really * PF queues) should be the first drop TC of the main VSI */ ice_for_each_chnl_tc(n) { if (!(vsi->all_enatc & BIT(n))) break; qoffset = vsi->mqprio_qopt.qopt.offset[n]; qcount = vsi->mqprio_qopt.qopt.count[n]; for (i = qoffset; i < (qoffset + qcount); i++) { vsi->tx_rings[i]->dcb_tc = first_droptc; vsi->rx_rings[i]->dcb_tc = first_droptc; } } } } /** * ice_dcb_ena_dis_vsi - disable certain VSIs for DCB config/reconfig * @pf: pointer to the PF instance * @ena: true to enable VSIs, false to disable * @locked: true if caller holds RTNL lock, false otherwise * * Before a new DCB configuration can be applied, VSIs of type PF, SWITCHDEV * and CHNL need to be brought down. Following completion of DCB configuration * the VSIs that were downed need to be brought up again. This helper function * does both. */ static void ice_dcb_ena_dis_vsi(struct ice_pf *pf, bool ena, bool locked) { int i; ice_for_each_vsi(pf, i) { struct ice_vsi *vsi = pf->vsi[i]; if (!vsi) continue; switch (vsi->type) { case ICE_VSI_CHNL: case ICE_VSI_SWITCHDEV_CTRL: case ICE_VSI_PF: if (ena) ice_ena_vsi(vsi, locked); else ice_dis_vsi(vsi, locked); break; default: continue; } } } /** * ice_dcb_bwchk - check if ETS bandwidth input parameters are correct * @pf: pointer to the PF struct * @dcbcfg: pointer to DCB config structure */ int ice_dcb_bwchk(struct ice_pf *pf, struct ice_dcbx_cfg *dcbcfg) { struct ice_dcb_ets_cfg *etscfg = &dcbcfg->etscfg; u8 num_tc, total_bw = 0; int i; /* returns number of contigous TCs and 1 TC for non-contigous TCs, * since at least 1 TC has to be configured */ num_tc = ice_dcb_get_num_tc(dcbcfg); /* no bandwidth checks required if there's only one TC, so assign * all bandwidth to TC0 and return */ if (num_tc == 1) { etscfg->tcbwtable[0] = ICE_TC_MAX_BW; return 0; } for (i = 0; i < num_tc; i++) total_bw += etscfg->tcbwtable[i]; if (!total_bw) { etscfg->tcbwtable[0] = ICE_TC_MAX_BW; } else if (total_bw != ICE_TC_MAX_BW) { dev_err(ice_pf_to_dev(pf), "Invalid config, total bandwidth must equal 100\n"); return -EINVAL; } return 0; } /** * ice_pf_dcb_cfg - Apply new DCB configuration * @pf: pointer to the PF struct * @new_cfg: DCBX config to apply * @locked: is the RTNL held */ int ice_pf_dcb_cfg(struct ice_pf *pf, struct ice_dcbx_cfg *new_cfg, bool locked) { struct ice_aqc_port_ets_elem buf = { 0 }; struct ice_dcbx_cfg *old_cfg, *curr_cfg; struct device *dev = ice_pf_to_dev(pf); int ret = ICE_DCB_NO_HW_CHG; struct iidc_event *event; struct ice_vsi *pf_vsi; curr_cfg = &pf->hw.port_info->qos_cfg.local_dcbx_cfg; /* FW does not care if change happened */ if (!pf->hw.port_info->qos_cfg.is_sw_lldp) ret = ICE_DCB_HW_CHG_RST; /* Enable DCB tagging only when more than one TC */ if (ice_dcb_get_num_tc(new_cfg) > 1) { dev_dbg(dev, "DCB tagging enabled (num TC > 1)\n"); if (pf->hw.port_info->is_custom_tx_enabled) { dev_err(dev, "Custom Tx scheduler feature enabled, can't configure DCB\n"); return -EBUSY; } ice_tear_down_devlink_rate_tree(pf); set_bit(ICE_FLAG_DCB_ENA, pf->flags); } else { dev_dbg(dev, "DCB tagging disabled (num TC = 1)\n"); clear_bit(ICE_FLAG_DCB_ENA, pf->flags); } if (!memcmp(new_cfg, curr_cfg, sizeof(*new_cfg))) { dev_dbg(dev, "No change in DCB config required\n"); return ret; } if (ice_dcb_bwchk(pf, new_cfg)) return -EINVAL; /* Store old config in case FW config fails */ old_cfg = kmemdup(curr_cfg, sizeof(*old_cfg), GFP_KERNEL); if (!old_cfg) return -ENOMEM; dev_info(dev, "Commit DCB Configuration to the hardware\n"); pf_vsi = ice_get_main_vsi(pf); if (!pf_vsi) { dev_dbg(dev, "PF VSI doesn't exist\n"); ret = -EINVAL; goto free_cfg; } /* Notify AUX drivers about impending change to TCs */ event = kzalloc(sizeof(*event), GFP_KERNEL); if (!event) { ret = -ENOMEM; goto free_cfg; } set_bit(IIDC_EVENT_BEFORE_TC_CHANGE, event->type); ice_send_event_to_aux(pf, event); kfree(event); /* avoid race conditions by holding the lock while disabling and * re-enabling the VSI */ if (!locked) rtnl_lock(); /* disable VSIs affected by DCB changes */ ice_dcb_ena_dis_vsi(pf, false, true); memcpy(curr_cfg, new_cfg, sizeof(*curr_cfg)); memcpy(&curr_cfg->etsrec, &curr_cfg->etscfg, sizeof(curr_cfg->etsrec)); memcpy(&new_cfg->etsrec, &curr_cfg->etscfg, sizeof(curr_cfg->etsrec)); /* Only send new config to HW if we are in SW LLDP mode. Otherwise, * the new config came from the HW in the first place. */ if (pf->hw.port_info->qos_cfg.is_sw_lldp) { ret = ice_set_dcb_cfg(pf->hw.port_info); if (ret) { dev_err(dev, "Set DCB Config failed\n"); /* Restore previous settings to local config */ memcpy(curr_cfg, old_cfg, sizeof(*curr_cfg)); goto out; } } ret = ice_query_port_ets(pf->hw.port_info, &buf, sizeof(buf), NULL); if (ret) { dev_err(dev, "Query Port ETS failed\n"); goto out; } ice_pf_dcb_recfg(pf, false); out: /* enable previously downed VSIs */ ice_dcb_ena_dis_vsi(pf, true, true); if (!locked) rtnl_unlock(); free_cfg: kfree(old_cfg); return ret; } /** * ice_cfg_etsrec_defaults - Set default ETS recommended DCB config * @pi: port information structure */ static void ice_cfg_etsrec_defaults(struct ice_port_info *pi) { struct ice_dcbx_cfg *dcbcfg = &pi->qos_cfg.local_dcbx_cfg; u8 i; /* Ensure ETS recommended DCB configuration is not already set */ if (dcbcfg->etsrec.maxtcs) return; /* In CEE mode, set the default to 1 TC */ dcbcfg->etsrec.maxtcs = 1; for (i = 0; i < ICE_MAX_TRAFFIC_CLASS; i++) { dcbcfg->etsrec.tcbwtable[i] = i ? 0 : 100; dcbcfg->etsrec.tsatable[i] = i ? ICE_IEEE_TSA_STRICT : ICE_IEEE_TSA_ETS; } } /** * ice_dcb_need_recfg - Check if DCB needs reconfig * @pf: board private structure * @old_cfg: current DCB config * @new_cfg: new DCB config */ static bool ice_dcb_need_recfg(struct ice_pf *pf, struct ice_dcbx_cfg *old_cfg, struct ice_dcbx_cfg *new_cfg) { struct device *dev = ice_pf_to_dev(pf); bool need_reconfig = false; /* Check if ETS configuration has changed */ if (memcmp(&new_cfg->etscfg, &old_cfg->etscfg, sizeof(new_cfg->etscfg))) { /* If Priority Table has changed reconfig is needed */ if (memcmp(&new_cfg->etscfg.prio_table, &old_cfg->etscfg.prio_table, sizeof(new_cfg->etscfg.prio_table))) { need_reconfig = true; dev_dbg(dev, "ETS UP2TC changed.\n"); } if (memcmp(&new_cfg->etscfg.tcbwtable, &old_cfg->etscfg.tcbwtable, sizeof(new_cfg->etscfg.tcbwtable))) dev_dbg(dev, "ETS TC BW Table changed.\n"); if (memcmp(&new_cfg->etscfg.tsatable, &old_cfg->etscfg.tsatable, sizeof(new_cfg->etscfg.tsatable))) dev_dbg(dev, "ETS TSA Table changed.\n"); } /* Check if PFC configuration has changed */ if (memcmp(&new_cfg->pfc, &old_cfg->pfc, sizeof(new_cfg->pfc))) { need_reconfig = true; dev_dbg(dev, "PFC config change detected.\n"); } /* Check if APP Table has changed */ if (memcmp(&new_cfg->app, &old_cfg->app, sizeof(new_cfg->app))) { need_reconfig = true; dev_dbg(dev, "APP Table change detected.\n"); } dev_dbg(dev, "dcb need_reconfig=%d\n", need_reconfig); return need_reconfig; } /** * ice_dcb_rebuild - rebuild DCB post reset * @pf: physical function instance */ void ice_dcb_rebuild(struct ice_pf *pf) { struct ice_aqc_port_ets_elem buf = { 0 }; struct device *dev = ice_pf_to_dev(pf); struct ice_dcbx_cfg *err_cfg; int ret; ret = ice_query_port_ets(pf->hw.port_info, &buf, sizeof(buf), NULL); if (ret) { dev_err(dev, "Query Port ETS failed\n"); goto dcb_error; } mutex_lock(&pf->tc_mutex); if (!pf->hw.port_info->qos_cfg.is_sw_lldp) ice_cfg_etsrec_defaults(pf->hw.port_info); ret = ice_set_dcb_cfg(pf->hw.port_info); if (ret) { dev_err(dev, "Failed to set DCB config in rebuild\n"); goto dcb_error; } if (!pf->hw.port_info->qos_cfg.is_sw_lldp) { ret = ice_cfg_lldp_mib_change(&pf->hw, true); if (ret && !pf->hw.port_info->qos_cfg.is_sw_lldp) { dev_err(dev, "Failed to register for MIB changes\n"); goto dcb_error; } } dev_info(dev, "DCB info restored\n"); ret = ice_query_port_ets(pf->hw.port_info, &buf, sizeof(buf), NULL); if (ret) { dev_err(dev, "Query Port ETS failed\n"); goto dcb_error; } mutex_unlock(&pf->tc_mutex); return; dcb_error: dev_err(dev, "Disabling DCB until new settings occur\n"); err_cfg = kzalloc(sizeof(*err_cfg), GFP_KERNEL); if (!err_cfg) { mutex_unlock(&pf->tc_mutex); return; } err_cfg->etscfg.willing = true; err_cfg->etscfg.tcbwtable[0] = ICE_TC_MAX_BW; err_cfg->etscfg.tsatable[0] = ICE_IEEE_TSA_ETS; memcpy(&err_cfg->etsrec, &err_cfg->etscfg, sizeof(err_cfg->etsrec)); /* Coverity warns the return code of ice_pf_dcb_cfg() is not checked * here as is done for other calls to that function. That check is * not necessary since this is in this function's error cleanup path. * Suppress the Coverity warning with the following comment... */ /* coverity[check_return] */ ice_pf_dcb_cfg(pf, err_cfg, false); kfree(err_cfg); mutex_unlock(&pf->tc_mutex); } /** * ice_dcb_init_cfg - set the initial DCB config in SW * @pf: PF to apply config to * @locked: Is the RTNL held */ static int ice_dcb_init_cfg(struct ice_pf *pf, bool locked) { struct ice_dcbx_cfg *newcfg; struct ice_port_info *pi; int ret = 0; pi = pf->hw.port_info; newcfg = kmemdup(&pi->qos_cfg.local_dcbx_cfg, sizeof(*newcfg), GFP_KERNEL); if (!newcfg) return -ENOMEM; memset(&pi->qos_cfg.local_dcbx_cfg, 0, sizeof(*newcfg)); dev_info(ice_pf_to_dev(pf), "Configuring initial DCB values\n"); if (ice_pf_dcb_cfg(pf, newcfg, locked)) ret = -EINVAL; kfree(newcfg); return ret; } /** * ice_dcb_sw_dflt_cfg - Apply a default DCB config * @pf: PF to apply config to * @ets_willing: configure ETS willing * @locked: was this function called with RTNL held */ int ice_dcb_sw_dflt_cfg(struct ice_pf *pf, bool ets_willing, bool locked) { struct ice_aqc_port_ets_elem buf = { 0 }; struct ice_dcbx_cfg *dcbcfg; struct ice_port_info *pi; struct ice_hw *hw; int ret; hw = &pf->hw; pi = hw->port_info; dcbcfg = kzalloc(sizeof(*dcbcfg), GFP_KERNEL); if (!dcbcfg) return -ENOMEM; memset(&pi->qos_cfg.local_dcbx_cfg, 0, sizeof(*dcbcfg)); dcbcfg->etscfg.willing = ets_willing ? 1 : 0; dcbcfg->etscfg.maxtcs = hw->func_caps.common_cap.maxtc; dcbcfg->etscfg.tcbwtable[0] = 100; dcbcfg->etscfg.tsatable[0] = ICE_IEEE_TSA_ETS; memcpy(&dcbcfg->etsrec, &dcbcfg->etscfg, sizeof(dcbcfg->etsrec)); dcbcfg->etsrec.willing = 0; dcbcfg->pfc.willing = 1; dcbcfg->pfc.pfccap = hw->func_caps.common_cap.maxtc; dcbcfg->numapps = 1; dcbcfg->app[0].selector = ICE_APP_SEL_ETHTYPE; dcbcfg->app[0].priority = 3; dcbcfg->app[0].prot_id = ETH_P_FCOE; ret = ice_pf_dcb_cfg(pf, dcbcfg, locked); kfree(dcbcfg); if (ret) return ret; return ice_query_port_ets(pi, &buf, sizeof(buf), NULL); } /** * ice_dcb_tc_contig - Check that TCs are contiguous * @prio_table: pointer to priority table * * Check if TCs begin with TC0 and are contiguous */ static bool ice_dcb_tc_contig(u8 *prio_table) { bool found_empty = false; u8 used_tc = 0; int i; /* Create a bitmap of used TCs */ for (i = 0; i < CEE_DCBX_MAX_PRIO; i++) used_tc |= BIT(prio_table[i]); for (i = 0; i < CEE_DCBX_MAX_PRIO; i++) { if (used_tc & BIT(i)) { if (found_empty) return false; } else { found_empty = true; } } return true; } /** * ice_dcb_noncontig_cfg - Configure DCB for non-contiguous TCs * @pf: pointer to the PF struct * * If non-contiguous TCs, then configure SW DCB with TC0 and ETS non-willing */ static int ice_dcb_noncontig_cfg(struct ice_pf *pf) { struct ice_dcbx_cfg *dcbcfg = &pf->hw.port_info->qos_cfg.local_dcbx_cfg; struct device *dev = ice_pf_to_dev(pf); int ret; /* Configure SW DCB default with ETS non-willing */ ret = ice_dcb_sw_dflt_cfg(pf, false, true); if (ret) { dev_err(dev, "Failed to set local DCB config %d\n", ret); return ret; } /* Reconfigure with ETS willing so that FW will send LLDP MIB event */ dcbcfg->etscfg.willing = 1; ret = ice_set_dcb_cfg(pf->hw.port_info); if (ret) dev_err(dev, "Failed to set DCB to unwilling\n"); return ret; } /** * ice_pf_dcb_recfg - Reconfigure all VEBs and VSIs * @pf: pointer to the PF struct * @locked: is adev device lock held * * Assumed caller has already disabled all VSIs before * calling this function. Reconfiguring DCB based on * local_dcbx_cfg. */ void ice_pf_dcb_recfg(struct ice_pf *pf, bool locked) { struct ice_dcbx_cfg *dcbcfg = &pf->hw.port_info->qos_cfg.local_dcbx_cfg; struct iidc_event *event; u8 tc_map = 0; int v, ret; /* Update each VSI */ ice_for_each_vsi(pf, v) { struct ice_vsi *vsi = pf->vsi[v]; if (!vsi) continue; if (vsi->type == ICE_VSI_PF) { tc_map = ice_dcb_get_ena_tc(dcbcfg); /* If DCBX request non-contiguous TC, then configure * default TC */ if (!ice_dcb_tc_contig(dcbcfg->etscfg.prio_table)) { tc_map = ICE_DFLT_TRAFFIC_CLASS; ice_dcb_noncontig_cfg(pf); } } else if (vsi->type == ICE_VSI_CHNL) { tc_map = BIT(ice_get_first_droptc(vsi)); } else { tc_map = ICE_DFLT_TRAFFIC_CLASS; } ret = ice_vsi_cfg_tc(vsi, tc_map); if (ret) { dev_err(ice_pf_to_dev(pf), "Failed to config TC for VSI index: %d\n", vsi->idx); continue; } /* no need to proceed with remaining cfg if it is CHNL * or switchdev VSI */ if (vsi->type == ICE_VSI_CHNL || vsi->type == ICE_VSI_SWITCHDEV_CTRL) continue; ice_vsi_map_rings_to_vectors(vsi); if (vsi->type == ICE_VSI_PF) ice_dcbnl_set_all(vsi); } if (!locked) { /* Notify the AUX drivers that TC change is finished */ event = kzalloc(sizeof(*event), GFP_KERNEL); if (!event) return; set_bit(IIDC_EVENT_AFTER_TC_CHANGE, event->type); ice_send_event_to_aux(pf, event); kfree(event); } } /** * ice_init_pf_dcb - initialize DCB for a PF * @pf: PF to initialize DCB for * @locked: Was function called with RTNL held */ int ice_init_pf_dcb(struct ice_pf *pf, bool locked) { struct device *dev = ice_pf_to_dev(pf); struct ice_port_info *port_info; struct ice_hw *hw = &pf->hw; int err; port_info = hw->port_info; err = ice_init_dcb(hw, false); if (err && !port_info->qos_cfg.is_sw_lldp) { dev_err(dev, "Error initializing DCB %d\n", err); goto dcb_init_err; } dev_info(dev, "DCB is enabled in the hardware, max number of TCs supported on this port are %d\n", pf->hw.func_caps.common_cap.maxtc); if (err) { struct ice_vsi *pf_vsi; /* FW LLDP is disabled, activate SW DCBX/LLDP mode */ dev_info(dev, "FW LLDP is disabled, DCBx/LLDP in SW mode.\n"); clear_bit(ICE_FLAG_FW_LLDP_AGENT, pf->flags); err = ice_aq_set_pfc_mode(&pf->hw, ICE_AQC_PFC_VLAN_BASED_PFC, NULL); if (err) dev_info(dev, "Failed to set VLAN PFC mode\n"); err = ice_dcb_sw_dflt_cfg(pf, true, locked); if (err) { dev_err(dev, "Failed to set local DCB config %d\n", err); err = -EIO; goto dcb_init_err; } /* If the FW DCBX engine is not running then Rx LLDP packets * need to be redirected up the stack. */ pf_vsi = ice_get_main_vsi(pf); if (!pf_vsi) { dev_err(dev, "Failed to set local DCB config\n"); err = -EIO; goto dcb_init_err; } ice_cfg_sw_lldp(pf_vsi, false, true); pf->dcbx_cap = ice_dcb_get_mode(port_info, true); return 0; } set_bit(ICE_FLAG_FW_LLDP_AGENT, pf->flags); /* DCBX/LLDP enabled in FW, set DCBNL mode advertisement */ pf->dcbx_cap = ice_dcb_get_mode(port_info, false); err = ice_dcb_init_cfg(pf, locked); if (err) goto dcb_init_err; return 0; dcb_init_err: dev_err(dev, "DCB init failed\n"); return err; } /** * ice_update_dcb_stats - Update DCB stats counters * @pf: PF whose stats needs to be updated */ void ice_update_dcb_stats(struct ice_pf *pf) { struct ice_hw_port_stats *prev_ps, *cur_ps; struct ice_hw *hw = &pf->hw; u8 port; int i; port = hw->port_info->lport; prev_ps = &pf->stats_prev; cur_ps = &pf->stats; if (ice_is_reset_in_progress(pf->state)) pf->stat_prev_loaded = false; for (i = 0; i < 8; i++) { ice_stat_update32(hw, GLPRT_PXOFFRXC(port, i), pf->stat_prev_loaded, &prev_ps->priority_xoff_rx[i], &cur_ps->priority_xoff_rx[i]); ice_stat_update32(hw, GLPRT_PXONRXC(port, i), pf->stat_prev_loaded, &prev_ps->priority_xon_rx[i], &cur_ps->priority_xon_rx[i]); ice_stat_update32(hw, GLPRT_PXONTXC(port, i), pf->stat_prev_loaded, &prev_ps->priority_xon_tx[i], &cur_ps->priority_xon_tx[i]); ice_stat_update32(hw, GLPRT_PXOFFTXC(port, i), pf->stat_prev_loaded, &prev_ps->priority_xoff_tx[i], &cur_ps->priority_xoff_tx[i]); ice_stat_update32(hw, GLPRT_RXON2OFFCNT(port, i), pf->stat_prev_loaded, &prev_ps->priority_xon_2_xoff[i], &cur_ps->priority_xon_2_xoff[i]); } } /** * ice_tx_prepare_vlan_flags_dcb - prepare VLAN tagging for DCB * @tx_ring: ring to send buffer on * @first: pointer to struct ice_tx_buf * * This should not be called if the outer VLAN is software offloaded as the VLAN * tag will already be configured with the correct ID and priority bits */ void ice_tx_prepare_vlan_flags_dcb(struct ice_tx_ring *tx_ring, struct ice_tx_buf *first) { struct sk_buff *skb = first->skb; if (!test_bit(ICE_FLAG_DCB_ENA, tx_ring->vsi->back->flags)) return; /* Insert 802.1p priority into VLAN header */ if ((first->tx_flags & ICE_TX_FLAGS_HW_VLAN || first->tx_flags & ICE_TX_FLAGS_HW_OUTER_SINGLE_VLAN) || skb->priority != TC_PRIO_CONTROL) { first->vid &= ~VLAN_PRIO_MASK; /* Mask the lower 3 bits to set the 802.1p priority */ first->vid |= (skb->priority << VLAN_PRIO_SHIFT) & VLAN_PRIO_MASK; /* if this is not already set it means a VLAN 0 + priority needs * to be offloaded */ if (tx_ring->flags & ICE_TX_FLAGS_RING_VLAN_L2TAG2) first->tx_flags |= ICE_TX_FLAGS_HW_OUTER_SINGLE_VLAN; else first->tx_flags |= ICE_TX_FLAGS_HW_VLAN; } } /** * ice_dcb_is_mib_change_pending - Check if MIB change is pending * @state: MIB change state */ static bool ice_dcb_is_mib_change_pending(u8 state) { return ICE_AQ_LLDP_MIB_CHANGE_PENDING == FIELD_GET(ICE_AQ_LLDP_MIB_CHANGE_STATE_M, state); } /** * ice_dcb_process_lldp_set_mib_change - Process MIB change * @pf: ptr to ice_pf * @event: pointer to the admin queue receive event */ void ice_dcb_process_lldp_set_mib_change(struct ice_pf *pf, struct ice_rq_event_info *event) { struct ice_aqc_port_ets_elem buf = { 0 }; struct device *dev = ice_pf_to_dev(pf); struct ice_aqc_lldp_get_mib *mib; struct ice_dcbx_cfg tmp_dcbx_cfg; bool pending_handled = true; bool need_reconfig = false; struct ice_port_info *pi; u8 mib_type; int ret; /* Not DCB capable or capability disabled */ if (!(test_bit(ICE_FLAG_DCB_CAPABLE, pf->flags))) return; if (pf->dcbx_cap & DCB_CAP_DCBX_HOST) { dev_dbg(dev, "MIB Change Event in HOST mode\n"); return; } pi = pf->hw.port_info; mib = (struct ice_aqc_lldp_get_mib *)&event->desc.params.raw; /* Ignore if event is not for Nearest Bridge */ mib_type = FIELD_GET(ICE_AQ_LLDP_BRID_TYPE_M, mib->type); dev_dbg(dev, "LLDP event MIB bridge type 0x%x\n", mib_type); if (mib_type != ICE_AQ_LLDP_BRID_TYPE_NEAREST_BRID) return; /* A pending change event contains accurate config information, and * the FW setting has not been updaed yet, so detect if change is * pending to determine where to pull config information from * (FW vs event) */ if (ice_dcb_is_mib_change_pending(mib->state)) pending_handled = false; /* Check MIB Type and return if event for Remote MIB update */ mib_type = FIELD_GET(ICE_AQ_LLDP_MIB_TYPE_M, mib->type); dev_dbg(dev, "LLDP event mib type %s\n", mib_type ? "remote" : "local"); if (mib_type == ICE_AQ_LLDP_MIB_REMOTE) { /* Update the remote cached instance and return */ if (!pending_handled) { ice_get_dcb_cfg_from_mib_change(pi, event); } else { ret = ice_aq_get_dcb_cfg(pi->hw, ICE_AQ_LLDP_MIB_REMOTE, ICE_AQ_LLDP_BRID_TYPE_NEAREST_BRID, &pi->qos_cfg.remote_dcbx_cfg); if (ret) dev_dbg(dev, "Failed to get remote DCB config\n"); } return; } /* That a DCB change has happened is now determined */ mutex_lock(&pf->tc_mutex); /* store the old configuration */ tmp_dcbx_cfg = pi->qos_cfg.local_dcbx_cfg; /* Reset the old DCBX configuration data */ memset(&pi->qos_cfg.local_dcbx_cfg, 0, sizeof(pi->qos_cfg.local_dcbx_cfg)); /* Get updated DCBX data from firmware */ if (!pending_handled) { ice_get_dcb_cfg_from_mib_change(pi, event); } else { ret = ice_get_dcb_cfg(pi); if (ret) { dev_err(dev, "Failed to get DCB config\n"); goto out; } } /* No change detected in DCBX configs */ if (!memcmp(&tmp_dcbx_cfg, &pi->qos_cfg.local_dcbx_cfg, sizeof(tmp_dcbx_cfg))) { dev_dbg(dev, "No change detected in DCBX configuration.\n"); goto out; } pf->dcbx_cap = ice_dcb_get_mode(pi, false); need_reconfig = ice_dcb_need_recfg(pf, &tmp_dcbx_cfg, &pi->qos_cfg.local_dcbx_cfg); ice_dcbnl_flush_apps(pf, &tmp_dcbx_cfg, &pi->qos_cfg.local_dcbx_cfg); if (!need_reconfig) goto out; /* Enable DCB tagging only when more than one TC */ if (ice_dcb_get_num_tc(&pi->qos_cfg.local_dcbx_cfg) > 1) { dev_dbg(dev, "DCB tagging enabled (num TC > 1)\n"); set_bit(ICE_FLAG_DCB_ENA, pf->flags); } else { dev_dbg(dev, "DCB tagging disabled (num TC = 1)\n"); clear_bit(ICE_FLAG_DCB_ENA, pf->flags); } /* Send Execute Pending MIB Change event if it is a Pending event */ if (!pending_handled) { ice_lldp_execute_pending_mib(&pf->hw); pending_handled = true; } rtnl_lock(); /* disable VSIs affected by DCB changes */ ice_dcb_ena_dis_vsi(pf, false, true); ret = ice_query_port_ets(pi, &buf, sizeof(buf), NULL); if (ret) { dev_err(dev, "Query Port ETS failed\n"); goto unlock_rtnl; } /* changes in configuration update VSI */ ice_pf_dcb_recfg(pf, false); /* enable previously downed VSIs */ ice_dcb_ena_dis_vsi(pf, true, true); unlock_rtnl: rtnl_unlock(); out: mutex_unlock(&pf->tc_mutex); /* Send Execute Pending MIB Change event if it is a Pending event */ if (!pending_handled) ice_lldp_execute_pending_mib(&pf->hw); }
linux-master
drivers/net/ethernet/intel/ice/ice_dcb_lib.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2018, Intel Corporation. */ #include "ice_common.h" #include "ice_vf_mbx.h" /** * ice_aq_send_msg_to_vf * @hw: pointer to the hardware structure * @vfid: VF ID to send msg * @v_opcode: opcodes for VF-PF communication * @v_retval: return error code * @msg: pointer to the msg buffer * @msglen: msg length * @cd: pointer to command details * * Send message to VF driver (0x0802) using mailbox * queue and asynchronously sending message via * ice_sq_send_cmd() function */ int ice_aq_send_msg_to_vf(struct ice_hw *hw, u16 vfid, u32 v_opcode, u32 v_retval, u8 *msg, u16 msglen, struct ice_sq_cd *cd) { struct ice_aqc_pf_vf_msg *cmd; struct ice_aq_desc desc; ice_fill_dflt_direct_cmd_desc(&desc, ice_mbx_opc_send_msg_to_vf); cmd = &desc.params.virt; cmd->id = cpu_to_le32(vfid); desc.cookie_high = cpu_to_le32(v_opcode); desc.cookie_low = cpu_to_le32(v_retval); if (msglen) desc.flags |= cpu_to_le16(ICE_AQ_FLAG_RD); return ice_sq_send_cmd(hw, &hw->mailboxq, &desc, msg, msglen, cd); } static const u32 ice_legacy_aq_to_vc_speed[] = { VIRTCHNL_LINK_SPEED_100MB, /* BIT(0) */ VIRTCHNL_LINK_SPEED_100MB, VIRTCHNL_LINK_SPEED_1GB, VIRTCHNL_LINK_SPEED_1GB, VIRTCHNL_LINK_SPEED_1GB, VIRTCHNL_LINK_SPEED_10GB, VIRTCHNL_LINK_SPEED_20GB, VIRTCHNL_LINK_SPEED_25GB, VIRTCHNL_LINK_SPEED_40GB, VIRTCHNL_LINK_SPEED_40GB, VIRTCHNL_LINK_SPEED_40GB, }; /** * ice_conv_link_speed_to_virtchnl * @adv_link_support: determines the format of the returned link speed * @link_speed: variable containing the link_speed to be converted * * Convert link speed supported by HW to link speed supported by virtchnl. * If adv_link_support is true, then return link speed in Mbps. Else return * link speed as a VIRTCHNL_LINK_SPEED_* casted to a u32. Note that the caller * needs to cast back to an enum virtchnl_link_speed in the case where * adv_link_support is false, but when adv_link_support is true the caller can * expect the speed in Mbps. */ u32 ice_conv_link_speed_to_virtchnl(bool adv_link_support, u16 link_speed) { /* convert a BIT() value into an array index */ u32 index = fls(link_speed) - 1; if (adv_link_support) return ice_get_link_speed(index); else if (index < ARRAY_SIZE(ice_legacy_aq_to_vc_speed)) /* Virtchnl speeds are not defined for every speed supported in * the hardware. To maintain compatibility with older AVF * drivers, while reporting the speed the new speed values are * resolved to the closest known virtchnl speeds */ return ice_legacy_aq_to_vc_speed[index]; return VIRTCHNL_LINK_SPEED_UNKNOWN; } /* The mailbox overflow detection algorithm helps to check if there * is a possibility of a malicious VF transmitting too many MBX messages to the * PF. * 1. The mailbox snapshot structure, ice_mbx_snapshot, is initialized during * driver initialization in ice_init_hw() using ice_mbx_init_snapshot(). * The struct ice_mbx_snapshot helps to track and traverse a static window of * messages within the mailbox queue while looking for a malicious VF. * * 2. When the caller starts processing its mailbox queue in response to an * interrupt, the structure ice_mbx_snapshot is expected to be cleared before * the algorithm can be run for the first time for that interrupt. This * requires calling ice_mbx_reset_snapshot() as well as calling * ice_mbx_reset_vf_info() for each VF tracking structure. * * 3. For every message read by the caller from the MBX Queue, the caller must * call the detection algorithm's entry function ice_mbx_vf_state_handler(). * Before every call to ice_mbx_vf_state_handler() the struct ice_mbx_data is * filled as it is required to be passed to the algorithm. * * 4. Every time a message is read from the MBX queue, a tracking structure * for the VF must be passed to the state handler. The boolean output * report_malvf from ice_mbx_vf_state_handler() serves as an indicator to the * caller whether it must report this VF as malicious or not. * * 5. When a VF is identified to be malicious, the caller can send a message * to the system administrator. * * 6. The PF is responsible for maintaining the struct ice_mbx_vf_info * structure for each VF. The PF should clear the VF tracking structure if the * VF is reset. When a VF is shut down and brought back up, we will then * assume that the new VF is not malicious and may report it again if we * detect it again. * * 7. The function ice_mbx_reset_snapshot() is called to reset the information * in ice_mbx_snapshot for every new mailbox interrupt handled. */ #define ICE_RQ_DATA_MASK(rq_data) ((rq_data) & PF_MBX_ARQH_ARQH_M) /* Using the highest value for an unsigned 16-bit value 0xFFFF to indicate that * the max messages check must be ignored in the algorithm */ #define ICE_IGNORE_MAX_MSG_CNT 0xFFFF /** * ice_mbx_reset_snapshot - Reset mailbox snapshot structure * @snap: pointer to the mailbox snapshot */ static void ice_mbx_reset_snapshot(struct ice_mbx_snapshot *snap) { struct ice_mbx_vf_info *vf_info; /* Clear mbx_buf in the mailbox snaphot structure and setting the * mailbox snapshot state to a new capture. */ memset(&snap->mbx_buf, 0, sizeof(snap->mbx_buf)); snap->mbx_buf.state = ICE_MAL_VF_DETECT_STATE_NEW_SNAPSHOT; /* Reset message counts for all VFs to zero */ list_for_each_entry(vf_info, &snap->mbx_vf, list_entry) vf_info->msg_count = 0; } /** * ice_mbx_traverse - Pass through mailbox snapshot * @hw: pointer to the HW struct * @new_state: new algorithm state * * Traversing the mailbox static snapshot without checking * for malicious VFs. */ static void ice_mbx_traverse(struct ice_hw *hw, enum ice_mbx_snapshot_state *new_state) { struct ice_mbx_snap_buffer_data *snap_buf; u32 num_iterations; snap_buf = &hw->mbx_snapshot.mbx_buf; /* As mailbox buffer is circular, applying a mask * on the incremented iteration count. */ num_iterations = ICE_RQ_DATA_MASK(++snap_buf->num_iterations); /* Checking either of the below conditions to exit snapshot traversal: * Condition-1: If the number of iterations in the mailbox is equal to * the mailbox head which would indicate that we have reached the end * of the static snapshot. * Condition-2: If the maximum messages serviced in the mailbox for a * given interrupt is the highest possible value then there is no need * to check if the number of messages processed is equal to it. If not * check if the number of messages processed is greater than or equal * to the maximum number of mailbox entries serviced in current work item. */ if (num_iterations == snap_buf->head || (snap_buf->max_num_msgs_mbx < ICE_IGNORE_MAX_MSG_CNT && ++snap_buf->num_msg_proc >= snap_buf->max_num_msgs_mbx)) *new_state = ICE_MAL_VF_DETECT_STATE_NEW_SNAPSHOT; } /** * ice_mbx_detect_malvf - Detect malicious VF in snapshot * @hw: pointer to the HW struct * @vf_info: mailbox tracking structure for a VF * @new_state: new algorithm state * @is_malvf: boolean output to indicate if VF is malicious * * This function tracks the number of asynchronous messages * sent per VF and marks the VF as malicious if it exceeds * the permissible number of messages to send. */ static int ice_mbx_detect_malvf(struct ice_hw *hw, struct ice_mbx_vf_info *vf_info, enum ice_mbx_snapshot_state *new_state, bool *is_malvf) { /* increment the message count for this VF */ vf_info->msg_count++; if (vf_info->msg_count >= ICE_ASYNC_VF_MSG_THRESHOLD) *is_malvf = true; /* continue to iterate through the mailbox snapshot */ ice_mbx_traverse(hw, new_state); return 0; } /** * ice_mbx_vf_state_handler - Handle states of the overflow algorithm * @hw: pointer to the HW struct * @mbx_data: pointer to structure containing mailbox data * @vf_info: mailbox tracking structure for the VF in question * @report_malvf: boolean output to indicate whether VF should be reported * * The function serves as an entry point for the malicious VF * detection algorithm by handling the different states and state * transitions of the algorithm: * New snapshot: This state is entered when creating a new static * snapshot. The data from any previous mailbox snapshot is * cleared and a new capture of the mailbox head and tail is * logged. This will be the new static snapshot to detect * asynchronous messages sent by VFs. On capturing the snapshot * and depending on whether the number of pending messages in that * snapshot exceed the watermark value, the state machine enters * traverse or detect states. * Traverse: If pending message count is below watermark then iterate * through the snapshot without any action on VF. * Detect: If pending message count exceeds watermark traverse * the static snapshot and look for a malicious VF. */ int ice_mbx_vf_state_handler(struct ice_hw *hw, struct ice_mbx_data *mbx_data, struct ice_mbx_vf_info *vf_info, bool *report_malvf) { struct ice_mbx_snapshot *snap = &hw->mbx_snapshot; struct ice_mbx_snap_buffer_data *snap_buf; struct ice_ctl_q_info *cq = &hw->mailboxq; enum ice_mbx_snapshot_state new_state; bool is_malvf = false; int status = 0; if (!report_malvf || !mbx_data || !vf_info) return -EINVAL; *report_malvf = false; /* When entering the mailbox state machine assume that the VF * is not malicious until detected. */ /* Checking if max messages allowed to be processed while servicing current * interrupt is not less than the defined AVF message threshold. */ if (mbx_data->max_num_msgs_mbx <= ICE_ASYNC_VF_MSG_THRESHOLD) return -EINVAL; /* The watermark value should not be lesser than the threshold limit * set for the number of asynchronous messages a VF can send to mailbox * nor should it be greater than the maximum number of messages in the * mailbox serviced in current interrupt. */ if (mbx_data->async_watermark_val < ICE_ASYNC_VF_MSG_THRESHOLD || mbx_data->async_watermark_val > mbx_data->max_num_msgs_mbx) return -EINVAL; new_state = ICE_MAL_VF_DETECT_STATE_INVALID; snap_buf = &snap->mbx_buf; switch (snap_buf->state) { case ICE_MAL_VF_DETECT_STATE_NEW_SNAPSHOT: /* Clear any previously held data in mailbox snapshot structure. */ ice_mbx_reset_snapshot(snap); /* Collect the pending ARQ count, number of messages processed and * the maximum number of messages allowed to be processed from the * Mailbox for current interrupt. */ snap_buf->num_pending_arq = mbx_data->num_pending_arq; snap_buf->num_msg_proc = mbx_data->num_msg_proc; snap_buf->max_num_msgs_mbx = mbx_data->max_num_msgs_mbx; /* Capture a new static snapshot of the mailbox by logging the * head and tail of snapshot and set num_iterations to the tail * value to mark the start of the iteration through the snapshot. */ snap_buf->head = ICE_RQ_DATA_MASK(cq->rq.next_to_clean + mbx_data->num_pending_arq); snap_buf->tail = ICE_RQ_DATA_MASK(cq->rq.next_to_clean - 1); snap_buf->num_iterations = snap_buf->tail; /* Pending ARQ messages returned by ice_clean_rq_elem * is the difference between the head and tail of the * mailbox queue. Comparing this value against the watermark * helps to check if we potentially have malicious VFs. */ if (snap_buf->num_pending_arq >= mbx_data->async_watermark_val) { new_state = ICE_MAL_VF_DETECT_STATE_DETECT; status = ice_mbx_detect_malvf(hw, vf_info, &new_state, &is_malvf); } else { new_state = ICE_MAL_VF_DETECT_STATE_TRAVERSE; ice_mbx_traverse(hw, &new_state); } break; case ICE_MAL_VF_DETECT_STATE_TRAVERSE: new_state = ICE_MAL_VF_DETECT_STATE_TRAVERSE; ice_mbx_traverse(hw, &new_state); break; case ICE_MAL_VF_DETECT_STATE_DETECT: new_state = ICE_MAL_VF_DETECT_STATE_DETECT; status = ice_mbx_detect_malvf(hw, vf_info, &new_state, &is_malvf); break; default: new_state = ICE_MAL_VF_DETECT_STATE_INVALID; status = -EIO; } snap_buf->state = new_state; /* Only report VFs as malicious the first time we detect it */ if (is_malvf && !vf_info->malicious) { vf_info->malicious = 1; *report_malvf = true; } return status; } /** * ice_mbx_clear_malvf - Clear VF mailbox info * @vf_info: the mailbox tracking structure for a VF * * In case of a VF reset, this function shall be called to clear the VF's * current mailbox tracking state. */ void ice_mbx_clear_malvf(struct ice_mbx_vf_info *vf_info) { vf_info->malicious = 0; vf_info->msg_count = 0; } /** * ice_mbx_init_vf_info - Initialize a new VF mailbox tracking info * @hw: pointer to the hardware structure * @vf_info: the mailbox tracking info structure for a VF * * Initialize a VF mailbox tracking info structure and insert it into the * snapshot list. * * If you remove the VF, you must also delete the associated VF info structure * from the linked list. */ void ice_mbx_init_vf_info(struct ice_hw *hw, struct ice_mbx_vf_info *vf_info) { struct ice_mbx_snapshot *snap = &hw->mbx_snapshot; ice_mbx_clear_malvf(vf_info); list_add(&vf_info->list_entry, &snap->mbx_vf); } /** * ice_mbx_init_snapshot - Initialize mailbox snapshot data * @hw: pointer to the hardware structure * * Clear the mailbox snapshot structure and initialize the VF mailbox list. */ void ice_mbx_init_snapshot(struct ice_hw *hw) { struct ice_mbx_snapshot *snap = &hw->mbx_snapshot; INIT_LIST_HEAD(&snap->mbx_vf); ice_mbx_reset_snapshot(snap); }
linux-master
drivers/net/ethernet/intel/ice/ice_vf_mbx.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2019, Intel Corporation. */ #include "ice.h" #include "ice_dcb.h" #include "ice_dcb_lib.h" #include "ice_dcb_nl.h" #include <net/dcbnl.h> /** * ice_dcbnl_devreset - perform enough of a ifdown/ifup to sync DCBNL info * @netdev: device associated with interface that needs reset */ static void ice_dcbnl_devreset(struct net_device *netdev) { struct ice_pf *pf = ice_netdev_to_pf(netdev); while (ice_is_reset_in_progress(pf->state)) usleep_range(1000, 2000); dev_close(netdev); netdev_state_change(netdev); dev_open(netdev, NULL); netdev_state_change(netdev); } /** * ice_dcbnl_getets - retrieve local ETS configuration * @netdev: the relevant netdev * @ets: struct to hold ETS configuration */ static int ice_dcbnl_getets(struct net_device *netdev, struct ieee_ets *ets) { struct ice_dcbx_cfg *dcbxcfg; struct ice_pf *pf; pf = ice_netdev_to_pf(netdev); dcbxcfg = &pf->hw.port_info->qos_cfg.local_dcbx_cfg; ets->willing = dcbxcfg->etscfg.willing; ets->ets_cap = dcbxcfg->etscfg.maxtcs; ets->cbs = dcbxcfg->etscfg.cbs; memcpy(ets->tc_tx_bw, dcbxcfg->etscfg.tcbwtable, sizeof(ets->tc_tx_bw)); memcpy(ets->tc_rx_bw, dcbxcfg->etscfg.tcbwtable, sizeof(ets->tc_rx_bw)); memcpy(ets->tc_tsa, dcbxcfg->etscfg.tsatable, sizeof(ets->tc_tsa)); memcpy(ets->prio_tc, dcbxcfg->etscfg.prio_table, sizeof(ets->prio_tc)); memcpy(ets->tc_reco_bw, dcbxcfg->etsrec.tcbwtable, sizeof(ets->tc_reco_bw)); memcpy(ets->tc_reco_tsa, dcbxcfg->etsrec.tsatable, sizeof(ets->tc_reco_tsa)); memcpy(ets->reco_prio_tc, dcbxcfg->etscfg.prio_table, sizeof(ets->reco_prio_tc)); return 0; } /** * ice_dcbnl_setets - set IEEE ETS configuration * @netdev: pointer to relevant netdev * @ets: struct to hold ETS configuration */ static int ice_dcbnl_setets(struct net_device *netdev, struct ieee_ets *ets) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_dcbx_cfg *new_cfg; int bwcfg = 0, bwrec = 0; int err, i; if ((pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED) || !(pf->dcbx_cap & DCB_CAP_DCBX_VER_IEEE)) return -EINVAL; if (pf->lag && pf->lag->bonded) { netdev_err(netdev, "DCB changes not allowed when in a bond\n"); return -EINVAL; } new_cfg = &pf->hw.port_info->qos_cfg.desired_dcbx_cfg; mutex_lock(&pf->tc_mutex); new_cfg->etscfg.willing = ets->willing; new_cfg->etscfg.cbs = ets->cbs; ice_for_each_traffic_class(i) { new_cfg->etscfg.tcbwtable[i] = ets->tc_tx_bw[i]; bwcfg += ets->tc_tx_bw[i]; new_cfg->etscfg.tsatable[i] = ets->tc_tsa[i]; if (new_cfg->pfc_mode == ICE_QOS_MODE_VLAN) { /* in DSCP mode up->tc mapping cannot change */ new_cfg->etscfg.prio_table[i] = ets->prio_tc[i]; new_cfg->etsrec.prio_table[i] = ets->reco_prio_tc[i]; } new_cfg->etsrec.tcbwtable[i] = ets->tc_reco_bw[i]; bwrec += ets->tc_reco_bw[i]; new_cfg->etsrec.tsatable[i] = ets->tc_reco_tsa[i]; } if (ice_dcb_bwchk(pf, new_cfg)) { err = -EINVAL; goto ets_out; } new_cfg->etscfg.maxtcs = pf->hw.func_caps.common_cap.maxtc; if (!bwcfg) new_cfg->etscfg.tcbwtable[0] = 100; if (!bwrec) new_cfg->etsrec.tcbwtable[0] = 100; err = ice_pf_dcb_cfg(pf, new_cfg, true); /* return of zero indicates new cfg applied */ if (err == ICE_DCB_HW_CHG_RST) ice_dcbnl_devreset(netdev); if (err == ICE_DCB_NO_HW_CHG) err = ICE_DCB_HW_CHG_RST; ets_out: mutex_unlock(&pf->tc_mutex); return err; } /** * ice_dcbnl_getnumtcs - Get max number of traffic classes supported * @dev: pointer to netdev struct * @tcid: TC ID * @num: total number of TCs supported by the adapter * * Return the total number of TCs supported */ static int ice_dcbnl_getnumtcs(struct net_device *dev, int __always_unused tcid, u8 *num) { struct ice_pf *pf = ice_netdev_to_pf(dev); if (!test_bit(ICE_FLAG_DCB_CAPABLE, pf->flags)) return -EINVAL; *num = pf->hw.func_caps.common_cap.maxtc; return 0; } /** * ice_dcbnl_getdcbx - retrieve current DCBX capability * @netdev: pointer to the netdev struct */ static u8 ice_dcbnl_getdcbx(struct net_device *netdev) { struct ice_pf *pf = ice_netdev_to_pf(netdev); return pf->dcbx_cap; } /** * ice_dcbnl_setdcbx - set required DCBX capability * @netdev: the corresponding netdev * @mode: required mode */ static u8 ice_dcbnl_setdcbx(struct net_device *netdev, u8 mode) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_qos_cfg *qos_cfg; /* if FW LLDP agent is running, DCBNL not allowed to change mode */ if (test_bit(ICE_FLAG_FW_LLDP_AGENT, pf->flags)) return ICE_DCB_NO_HW_CHG; /* No support for LLD_MANAGED modes or CEE+IEEE */ if ((mode & DCB_CAP_DCBX_LLD_MANAGED) || ((mode & DCB_CAP_DCBX_VER_IEEE) && (mode & DCB_CAP_DCBX_VER_CEE)) || !(mode & DCB_CAP_DCBX_HOST)) return ICE_DCB_NO_HW_CHG; /* Already set to the given mode no change */ if (mode == pf->dcbx_cap) return ICE_DCB_NO_HW_CHG; if (pf->lag && pf->lag->bonded) { netdev_err(netdev, "DCB changes not allowed when in a bond\n"); return ICE_DCB_NO_HW_CHG; } qos_cfg = &pf->hw.port_info->qos_cfg; /* DSCP configuration is not DCBx negotiated */ if (qos_cfg->local_dcbx_cfg.pfc_mode == ICE_QOS_MODE_DSCP) return ICE_DCB_NO_HW_CHG; pf->dcbx_cap = mode; if (mode & DCB_CAP_DCBX_VER_CEE) qos_cfg->local_dcbx_cfg.dcbx_mode = ICE_DCBX_MODE_CEE; else qos_cfg->local_dcbx_cfg.dcbx_mode = ICE_DCBX_MODE_IEEE; dev_info(ice_pf_to_dev(pf), "DCBx mode = 0x%x\n", mode); return ICE_DCB_HW_CHG_RST; } /** * ice_dcbnl_get_perm_hw_addr - MAC address used by DCBX * @netdev: pointer to netdev struct * @perm_addr: buffer to return permanent MAC address */ static void ice_dcbnl_get_perm_hw_addr(struct net_device *netdev, u8 *perm_addr) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_port_info *pi = pf->hw.port_info; int i, j; memset(perm_addr, 0xff, MAX_ADDR_LEN); for (i = 0; i < netdev->addr_len; i++) perm_addr[i] = pi->mac.perm_addr[i]; for (j = 0; j < netdev->addr_len; j++, i++) perm_addr[i] = pi->mac.perm_addr[j]; } /** * ice_get_pfc_delay - Retrieve PFC Link Delay * @hw: pointer to HW struct * @delay: holds the PFC Link Delay value */ static void ice_get_pfc_delay(struct ice_hw *hw, u16 *delay) { u32 val; val = rd32(hw, PRTDCB_GENC); *delay = (u16)((val & PRTDCB_GENC_PFCLDA_M) >> PRTDCB_GENC_PFCLDA_S); } /** * ice_dcbnl_getpfc - retrieve local IEEE PFC config * @netdev: pointer to netdev struct * @pfc: struct to hold PFC info */ static int ice_dcbnl_getpfc(struct net_device *netdev, struct ieee_pfc *pfc) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_port_info *pi = pf->hw.port_info; struct ice_dcbx_cfg *dcbxcfg; int i; dcbxcfg = &pi->qos_cfg.local_dcbx_cfg; pfc->pfc_cap = dcbxcfg->pfc.pfccap; pfc->pfc_en = dcbxcfg->pfc.pfcena; pfc->mbc = dcbxcfg->pfc.mbc; ice_get_pfc_delay(&pf->hw, &pfc->delay); ice_for_each_traffic_class(i) { pfc->requests[i] = pf->stats.priority_xoff_tx[i]; pfc->indications[i] = pf->stats.priority_xoff_rx[i]; } return 0; } /** * ice_dcbnl_setpfc - set local IEEE PFC config * @netdev: pointer to relevant netdev * @pfc: pointer to struct holding PFC config */ static int ice_dcbnl_setpfc(struct net_device *netdev, struct ieee_pfc *pfc) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_dcbx_cfg *new_cfg; int err; if ((pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED) || !(pf->dcbx_cap & DCB_CAP_DCBX_VER_IEEE)) return -EINVAL; if (pf->lag && pf->lag->bonded) { netdev_err(netdev, "DCB changes not allowed when in a bond\n"); return -EINVAL; } mutex_lock(&pf->tc_mutex); new_cfg = &pf->hw.port_info->qos_cfg.desired_dcbx_cfg; if (pfc->pfc_cap) new_cfg->pfc.pfccap = pfc->pfc_cap; else new_cfg->pfc.pfccap = pf->hw.func_caps.common_cap.maxtc; new_cfg->pfc.pfcena = pfc->pfc_en; err = ice_pf_dcb_cfg(pf, new_cfg, true); if (err == ICE_DCB_HW_CHG_RST) ice_dcbnl_devreset(netdev); if (err == ICE_DCB_NO_HW_CHG) err = ICE_DCB_HW_CHG_RST; mutex_unlock(&pf->tc_mutex); return err; } /** * ice_dcbnl_get_pfc_cfg - Get CEE PFC config * @netdev: pointer to netdev struct * @prio: corresponding user priority * @setting: the PFC setting for given priority */ static void ice_dcbnl_get_pfc_cfg(struct net_device *netdev, int prio, u8 *setting) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_port_info *pi = pf->hw.port_info; if ((pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED) || !(pf->dcbx_cap & DCB_CAP_DCBX_VER_CEE)) return; if (prio >= ICE_MAX_USER_PRIORITY) return; *setting = (pi->qos_cfg.local_dcbx_cfg.pfc.pfcena >> prio) & 0x1; dev_dbg(ice_pf_to_dev(pf), "Get PFC Config up=%d, setting=%d, pfcenable=0x%x\n", prio, *setting, pi->qos_cfg.local_dcbx_cfg.pfc.pfcena); } /** * ice_dcbnl_set_pfc_cfg - Set CEE PFC config * @netdev: the corresponding netdev * @prio: User Priority * @set: PFC setting to apply */ static void ice_dcbnl_set_pfc_cfg(struct net_device *netdev, int prio, u8 set) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_dcbx_cfg *new_cfg; if ((pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED) || !(pf->dcbx_cap & DCB_CAP_DCBX_VER_CEE)) return; if (prio >= ICE_MAX_USER_PRIORITY) return; if (pf->lag && pf->lag->bonded) { netdev_err(netdev, "DCB changes not allowed when in a bond\n"); return; } new_cfg = &pf->hw.port_info->qos_cfg.desired_dcbx_cfg; new_cfg->pfc.pfccap = pf->hw.func_caps.common_cap.maxtc; if (set) new_cfg->pfc.pfcena |= BIT(prio); else new_cfg->pfc.pfcena &= ~BIT(prio); dev_dbg(ice_pf_to_dev(pf), "Set PFC config UP:%d set:%d pfcena:0x%x\n", prio, set, new_cfg->pfc.pfcena); } /** * ice_dcbnl_getpfcstate - get CEE PFC mode * @netdev: pointer to netdev struct */ static u8 ice_dcbnl_getpfcstate(struct net_device *netdev) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_port_info *pi = pf->hw.port_info; /* Return enabled if any UP enabled for PFC */ if (pi->qos_cfg.local_dcbx_cfg.pfc.pfcena) return 1; return 0; } /** * ice_dcbnl_getstate - get DCB enabled state * @netdev: pointer to netdev struct */ static u8 ice_dcbnl_getstate(struct net_device *netdev) { struct ice_pf *pf = ice_netdev_to_pf(netdev); u8 state = 0; state = test_bit(ICE_FLAG_DCB_CAPABLE, pf->flags); dev_dbg(ice_pf_to_dev(pf), "DCB enabled state = %d\n", state); return state; } /** * ice_dcbnl_setstate - Set CEE DCB state * @netdev: pointer to relevant netdev * @state: state value to set */ static u8 ice_dcbnl_setstate(struct net_device *netdev, u8 state) { struct ice_pf *pf = ice_netdev_to_pf(netdev); if ((pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED) || !(pf->dcbx_cap & DCB_CAP_DCBX_VER_CEE)) return ICE_DCB_NO_HW_CHG; if (pf->lag && pf->lag->bonded) { netdev_err(netdev, "DCB changes not allowed when in a bond\n"); return ICE_DCB_NO_HW_CHG; } /* Nothing to do */ if (!!state == test_bit(ICE_FLAG_DCB_ENA, pf->flags)) return ICE_DCB_NO_HW_CHG; if (state) { set_bit(ICE_FLAG_DCB_ENA, pf->flags); memcpy(&pf->hw.port_info->qos_cfg.desired_dcbx_cfg, &pf->hw.port_info->qos_cfg.local_dcbx_cfg, sizeof(struct ice_dcbx_cfg)); } else { clear_bit(ICE_FLAG_DCB_ENA, pf->flags); } return ICE_DCB_HW_CHG; } /** * ice_dcbnl_get_pg_tc_cfg_tx - get CEE PG Tx config * @netdev: pointer to netdev struct * @prio: the corresponding user priority * @prio_type: traffic priority type * @pgid: the BW group ID the traffic class belongs to * @bw_pct: BW percentage for the corresponding BWG * @up_map: prio mapped to corresponding TC */ static void ice_dcbnl_get_pg_tc_cfg_tx(struct net_device *netdev, int prio, u8 __always_unused *prio_type, u8 *pgid, u8 __always_unused *bw_pct, u8 __always_unused *up_map) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_port_info *pi = pf->hw.port_info; if ((pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED) || !(pf->dcbx_cap & DCB_CAP_DCBX_VER_CEE)) return; if (prio >= ICE_MAX_USER_PRIORITY) return; *pgid = pi->qos_cfg.local_dcbx_cfg.etscfg.prio_table[prio]; dev_dbg(ice_pf_to_dev(pf), "Get PG config prio=%d tc=%d\n", prio, *pgid); } /** * ice_dcbnl_set_pg_tc_cfg_tx - set CEE PG Tx config * @netdev: pointer to relevant netdev * @tc: the corresponding traffic class * @prio_type: the traffic priority type * @bwg_id: the BW group ID the TC belongs to * @bw_pct: the BW perventage for the BWG * @up_map: prio mapped to corresponding TC */ static void ice_dcbnl_set_pg_tc_cfg_tx(struct net_device *netdev, int tc, u8 __always_unused prio_type, u8 __always_unused bwg_id, u8 __always_unused bw_pct, u8 up_map) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_dcbx_cfg *new_cfg; int i; if ((pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED) || !(pf->dcbx_cap & DCB_CAP_DCBX_VER_CEE)) return; if (tc >= ICE_MAX_TRAFFIC_CLASS) return; if (pf->lag && pf->lag->bonded) { netdev_err(netdev, "DCB changes not allowed when in a bond\n"); return; } new_cfg = &pf->hw.port_info->qos_cfg.desired_dcbx_cfg; /* prio_type, bwg_id and bw_pct per UP are not supported */ ice_for_each_traffic_class(i) { if (up_map & BIT(i)) new_cfg->etscfg.prio_table[i] = tc; } new_cfg->etscfg.tsatable[tc] = ICE_IEEE_TSA_ETS; } /** * ice_dcbnl_get_pg_bwg_cfg_tx - Get CEE PGBW config * @netdev: pointer to the netdev struct * @pgid: corresponding traffic class * @bw_pct: the BW percentage for the corresponding TC */ static void ice_dcbnl_get_pg_bwg_cfg_tx(struct net_device *netdev, int pgid, u8 *bw_pct) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_port_info *pi = pf->hw.port_info; if ((pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED) || !(pf->dcbx_cap & DCB_CAP_DCBX_VER_CEE)) return; if (pgid >= ICE_MAX_TRAFFIC_CLASS) return; *bw_pct = pi->qos_cfg.local_dcbx_cfg.etscfg.tcbwtable[pgid]; dev_dbg(ice_pf_to_dev(pf), "Get PG BW config tc=%d bw_pct=%d\n", pgid, *bw_pct); } /** * ice_dcbnl_set_pg_bwg_cfg_tx - set CEE PG Tx BW config * @netdev: the corresponding netdev * @pgid: Correspongind traffic class * @bw_pct: the BW percentage for the specified TC */ static void ice_dcbnl_set_pg_bwg_cfg_tx(struct net_device *netdev, int pgid, u8 bw_pct) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_dcbx_cfg *new_cfg; if ((pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED) || !(pf->dcbx_cap & DCB_CAP_DCBX_VER_CEE)) return; if (pgid >= ICE_MAX_TRAFFIC_CLASS) return; if (pf->lag && pf->lag->bonded) { netdev_err(netdev, "DCB changes not allowed when in a bond\n"); return; } new_cfg = &pf->hw.port_info->qos_cfg.desired_dcbx_cfg; new_cfg->etscfg.tcbwtable[pgid] = bw_pct; } /** * ice_dcbnl_get_pg_tc_cfg_rx - Get CEE PG Rx config * @netdev: pointer to netdev struct * @prio: the corresponding user priority * @prio_type: the traffic priority type * @pgid: the PG ID * @bw_pct: the BW percentage for the corresponding BWG * @up_map: prio mapped to corresponding TC */ static void ice_dcbnl_get_pg_tc_cfg_rx(struct net_device *netdev, int prio, u8 __always_unused *prio_type, u8 *pgid, u8 __always_unused *bw_pct, u8 __always_unused *up_map) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_port_info *pi = pf->hw.port_info; if ((pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED) || !(pf->dcbx_cap & DCB_CAP_DCBX_VER_CEE)) return; if (prio >= ICE_MAX_USER_PRIORITY) return; *pgid = pi->qos_cfg.local_dcbx_cfg.etscfg.prio_table[prio]; } /** * ice_dcbnl_set_pg_tc_cfg_rx * @netdev: relevant netdev struct * @prio: corresponding user priority * @prio_type: the traffic priority type * @pgid: the PG ID * @bw_pct: BW percentage for corresponding BWG * @up_map: prio mapped to corresponding TC * * lldpad requires this function pointer to be non-NULL to complete CEE config. */ static void ice_dcbnl_set_pg_tc_cfg_rx(struct net_device *netdev, int __always_unused prio, u8 __always_unused prio_type, u8 __always_unused pgid, u8 __always_unused bw_pct, u8 __always_unused up_map) { struct ice_pf *pf = ice_netdev_to_pf(netdev); dev_dbg(ice_pf_to_dev(pf), "Rx TC PG Config Not Supported.\n"); } /** * ice_dcbnl_get_pg_bwg_cfg_rx - Get CEE PG BW Rx config * @netdev: pointer to netdev struct * @pgid: the corresponding traffic class * @bw_pct: the BW percentage for the corresponding TC */ static void ice_dcbnl_get_pg_bwg_cfg_rx(struct net_device *netdev, int __always_unused pgid, u8 *bw_pct) { struct ice_pf *pf = ice_netdev_to_pf(netdev); if ((pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED) || !(pf->dcbx_cap & DCB_CAP_DCBX_VER_CEE)) return; *bw_pct = 0; } /** * ice_dcbnl_set_pg_bwg_cfg_rx * @netdev: the corresponding netdev * @pgid: corresponding TC * @bw_pct: BW percentage for given TC * * lldpad requires this function pointer to be non-NULL to complete CEE config. */ static void ice_dcbnl_set_pg_bwg_cfg_rx(struct net_device *netdev, int __always_unused pgid, u8 __always_unused bw_pct) { struct ice_pf *pf = ice_netdev_to_pf(netdev); dev_dbg(ice_pf_to_dev(pf), "Rx BWG PG Config Not Supported.\n"); } /** * ice_dcbnl_get_cap - Get DCBX capabilities of adapter * @netdev: pointer to netdev struct * @capid: the capability type * @cap: the capability value */ static u8 ice_dcbnl_get_cap(struct net_device *netdev, int capid, u8 *cap) { struct ice_pf *pf = ice_netdev_to_pf(netdev); if (!(test_bit(ICE_FLAG_DCB_CAPABLE, pf->flags))) return ICE_DCB_NO_HW_CHG; switch (capid) { case DCB_CAP_ATTR_PG: *cap = true; break; case DCB_CAP_ATTR_PFC: *cap = true; break; case DCB_CAP_ATTR_UP2TC: *cap = false; break; case DCB_CAP_ATTR_PG_TCS: *cap = 0x80; break; case DCB_CAP_ATTR_PFC_TCS: *cap = 0x80; break; case DCB_CAP_ATTR_GSP: *cap = false; break; case DCB_CAP_ATTR_BCN: *cap = false; break; case DCB_CAP_ATTR_DCBX: *cap = pf->dcbx_cap; break; default: *cap = false; break; } dev_dbg(ice_pf_to_dev(pf), "DCBX Get Capability cap=%d capval=0x%x\n", capid, *cap); return 0; } /** * ice_dcbnl_getapp - get CEE APP * @netdev: pointer to netdev struct * @idtype: the App selector * @id: the App ethtype or port number */ static int ice_dcbnl_getapp(struct net_device *netdev, u8 idtype, u16 id) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct dcb_app app = { .selector = idtype, .protocol = id, }; if ((pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED) || !(pf->dcbx_cap & DCB_CAP_DCBX_VER_CEE)) return -EINVAL; return dcb_getapp(netdev, &app); } /** * ice_dcbnl_find_app - Search for APP in given DCB config * @cfg: struct to hold DCBX config * @app: struct to hold app data to look for */ static bool ice_dcbnl_find_app(struct ice_dcbx_cfg *cfg, struct ice_dcb_app_priority_table *app) { unsigned int i; for (i = 0; i < cfg->numapps; i++) { if (app->selector == cfg->app[i].selector && app->prot_id == cfg->app[i].prot_id && app->priority == cfg->app[i].priority) return true; } return false; } #define ICE_BYTES_PER_DSCP_VAL 8 /** * ice_dcbnl_setapp - set local IEEE App config * @netdev: relevant netdev struct * @app: struct to hold app config info */ static int ice_dcbnl_setapp(struct net_device *netdev, struct dcb_app *app) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_dcb_app_priority_table new_app; struct ice_dcbx_cfg *old_cfg, *new_cfg; u8 max_tc; int ret; /* ONLY DSCP APP TLVs have operational significance */ if (app->selector != IEEE_8021QAZ_APP_SEL_DSCP) return -EINVAL; /* only allow APP TLVs in SW Mode */ if (pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED) { netdev_err(netdev, "can't do DSCP QoS when FW DCB agent active\n"); return -EINVAL; } if (!(pf->dcbx_cap & DCB_CAP_DCBX_VER_IEEE)) return -EINVAL; if (!ice_is_feature_supported(pf, ICE_F_DSCP)) return -EOPNOTSUPP; if (app->protocol >= ICE_DSCP_NUM_VAL) { netdev_err(netdev, "DSCP value 0x%04X out of range\n", app->protocol); return -EINVAL; } if (pf->lag && pf->lag->bonded) { netdev_err(netdev, "DCB changes not allowed when in a bond\n"); return -EINVAL; } max_tc = pf->hw.func_caps.common_cap.maxtc; if (app->priority >= max_tc) { netdev_err(netdev, "TC %d out of range, max TC %d\n", app->priority, max_tc); return -EINVAL; } /* grab TC mutex */ mutex_lock(&pf->tc_mutex); new_cfg = &pf->hw.port_info->qos_cfg.desired_dcbx_cfg; old_cfg = &pf->hw.port_info->qos_cfg.local_dcbx_cfg; ret = dcb_ieee_setapp(netdev, app); if (ret) goto setapp_out; if (test_and_set_bit(app->protocol, new_cfg->dscp_mapped)) { netdev_err(netdev, "DSCP value 0x%04X already user mapped\n", app->protocol); ret = dcb_ieee_delapp(netdev, app); if (ret) netdev_err(netdev, "Failed to delete re-mapping TLV\n"); ret = -EINVAL; goto setapp_out; } new_app.selector = app->selector; new_app.prot_id = app->protocol; new_app.priority = app->priority; /* If port is not in DSCP mode, need to set */ if (old_cfg->pfc_mode == ICE_QOS_MODE_VLAN) { int i, j; /* set DSCP mode */ ret = ice_aq_set_pfc_mode(&pf->hw, ICE_AQC_PFC_DSCP_BASED_PFC, NULL); if (ret) { netdev_err(netdev, "Failed to set DSCP PFC mode %d\n", ret); goto setapp_out; } netdev_info(netdev, "Switched QoS to L3 DSCP mode\n"); new_cfg->pfc_mode = ICE_QOS_MODE_DSCP; /* set default DSCP QoS values */ new_cfg->etscfg.willing = 0; new_cfg->pfc.pfccap = max_tc; new_cfg->pfc.willing = 0; for (i = 0; i < max_tc; i++) for (j = 0; j < ICE_BYTES_PER_DSCP_VAL; j++) { int dscp, offset; dscp = (i * max_tc) + j; offset = max_tc * ICE_BYTES_PER_DSCP_VAL; new_cfg->dscp_map[dscp] = i; /* if less that 8 TCs supported */ if (max_tc < ICE_MAX_TRAFFIC_CLASS) new_cfg->dscp_map[dscp + offset] = i; } new_cfg->etscfg.tcbwtable[0] = 100; new_cfg->etscfg.tsatable[0] = ICE_IEEE_TSA_ETS; new_cfg->etscfg.prio_table[0] = 0; for (i = 1; i < max_tc; i++) { new_cfg->etscfg.tcbwtable[i] = 0; new_cfg->etscfg.tsatable[i] = ICE_IEEE_TSA_ETS; new_cfg->etscfg.prio_table[i] = i; } } /* end of switching to DSCP mode */ /* apply new mapping for this DSCP value */ new_cfg->dscp_map[app->protocol] = app->priority; new_cfg->app[new_cfg->numapps++] = new_app; ret = ice_pf_dcb_cfg(pf, new_cfg, true); /* return of zero indicates new cfg applied */ if (ret == ICE_DCB_HW_CHG_RST) ice_dcbnl_devreset(netdev); else ret = ICE_DCB_NO_HW_CHG; setapp_out: mutex_unlock(&pf->tc_mutex); return ret; } /** * ice_dcbnl_delapp - Delete local IEEE App config * @netdev: relevant netdev * @app: struct to hold app too delete * * Will not delete first application required by the FW */ static int ice_dcbnl_delapp(struct net_device *netdev, struct dcb_app *app) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_dcbx_cfg *old_cfg, *new_cfg; unsigned int i, j; int ret = 0; if (pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED) { netdev_err(netdev, "can't delete DSCP netlink app when FW DCB agent is active\n"); return -EINVAL; } if (pf->lag && pf->lag->bonded) { netdev_err(netdev, "DCB changes not allowed when in a bond\n"); return -EINVAL; } mutex_lock(&pf->tc_mutex); old_cfg = &pf->hw.port_info->qos_cfg.local_dcbx_cfg; ret = dcb_ieee_delapp(netdev, app); if (ret) goto delapp_out; new_cfg = &pf->hw.port_info->qos_cfg.desired_dcbx_cfg; for (i = 0; i < new_cfg->numapps; i++) { if (app->selector == new_cfg->app[i].selector && app->protocol == new_cfg->app[i].prot_id && app->priority == new_cfg->app[i].priority) { new_cfg->app[i].selector = 0; new_cfg->app[i].prot_id = 0; new_cfg->app[i].priority = 0; break; } } /* Did not find DCB App */ if (i == new_cfg->numapps) { ret = -EINVAL; goto delapp_out; } new_cfg->numapps--; for (j = i; j < new_cfg->numapps; j++) { new_cfg->app[j].selector = old_cfg->app[j + 1].selector; new_cfg->app[j].prot_id = old_cfg->app[j + 1].prot_id; new_cfg->app[j].priority = old_cfg->app[j + 1].priority; } /* if not a DSCP APP TLV or DSCP is not supported, we are done */ if (app->selector != IEEE_8021QAZ_APP_SEL_DSCP || !ice_is_feature_supported(pf, ICE_F_DSCP)) { ret = ICE_DCB_HW_CHG; goto delapp_out; } /* if DSCP TLV, then need to address change in mapping */ clear_bit(app->protocol, new_cfg->dscp_mapped); /* remap this DSCP value to default value */ new_cfg->dscp_map[app->protocol] = app->protocol % ICE_BYTES_PER_DSCP_VAL; /* if the last DSCP mapping just got deleted, need to switch * to L2 VLAN QoS mode */ if (bitmap_empty(new_cfg->dscp_mapped, ICE_DSCP_NUM_VAL) && new_cfg->pfc_mode == ICE_QOS_MODE_DSCP) { ret = ice_aq_set_pfc_mode(&pf->hw, ICE_AQC_PFC_VLAN_BASED_PFC, NULL); if (ret) { netdev_info(netdev, "Failed to set VLAN PFC mode %d\n", ret); goto delapp_out; } netdev_info(netdev, "Switched QoS to L2 VLAN mode\n"); new_cfg->pfc_mode = ICE_QOS_MODE_VLAN; ret = ice_dcb_sw_dflt_cfg(pf, true, true); } else { ret = ice_pf_dcb_cfg(pf, new_cfg, true); } /* return of ICE_DCB_HW_CHG_RST indicates new cfg applied * and reset needs to be performed */ if (ret == ICE_DCB_HW_CHG_RST) ice_dcbnl_devreset(netdev); /* if the change was not siginificant enough to actually call * the reconfiguration flow, we still need to tell caller that * their request was successfully handled */ if (ret == ICE_DCB_NO_HW_CHG) ret = ICE_DCB_HW_CHG; delapp_out: mutex_unlock(&pf->tc_mutex); return ret; } /** * ice_dcbnl_cee_set_all - Commit CEE DCB settings to HW * @netdev: the corresponding netdev */ static u8 ice_dcbnl_cee_set_all(struct net_device *netdev) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_dcbx_cfg *new_cfg; int err; if ((pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED) || !(pf->dcbx_cap & DCB_CAP_DCBX_VER_CEE)) return ICE_DCB_NO_HW_CHG; if (pf->lag && pf->lag->bonded) { netdev_err(netdev, "DCB changes not allowed when in a bond\n"); return ICE_DCB_NO_HW_CHG; } new_cfg = &pf->hw.port_info->qos_cfg.desired_dcbx_cfg; mutex_lock(&pf->tc_mutex); err = ice_pf_dcb_cfg(pf, new_cfg, true); mutex_unlock(&pf->tc_mutex); return (err != ICE_DCB_HW_CHG_RST) ? ICE_DCB_NO_HW_CHG : err; } static const struct dcbnl_rtnl_ops dcbnl_ops = { /* IEEE 802.1Qaz std */ .ieee_getets = ice_dcbnl_getets, .ieee_setets = ice_dcbnl_setets, .ieee_getpfc = ice_dcbnl_getpfc, .ieee_setpfc = ice_dcbnl_setpfc, .ieee_setapp = ice_dcbnl_setapp, .ieee_delapp = ice_dcbnl_delapp, /* CEE std */ .getstate = ice_dcbnl_getstate, .setstate = ice_dcbnl_setstate, .getpermhwaddr = ice_dcbnl_get_perm_hw_addr, .setpgtccfgtx = ice_dcbnl_set_pg_tc_cfg_tx, .setpgbwgcfgtx = ice_dcbnl_set_pg_bwg_cfg_tx, .setpgtccfgrx = ice_dcbnl_set_pg_tc_cfg_rx, .setpgbwgcfgrx = ice_dcbnl_set_pg_bwg_cfg_rx, .getpgtccfgtx = ice_dcbnl_get_pg_tc_cfg_tx, .getpgbwgcfgtx = ice_dcbnl_get_pg_bwg_cfg_tx, .getpgtccfgrx = ice_dcbnl_get_pg_tc_cfg_rx, .getpgbwgcfgrx = ice_dcbnl_get_pg_bwg_cfg_rx, .setpfccfg = ice_dcbnl_set_pfc_cfg, .getpfccfg = ice_dcbnl_get_pfc_cfg, .setall = ice_dcbnl_cee_set_all, .getcap = ice_dcbnl_get_cap, .getnumtcs = ice_dcbnl_getnumtcs, .getpfcstate = ice_dcbnl_getpfcstate, .getapp = ice_dcbnl_getapp, /* DCBX configuration */ .getdcbx = ice_dcbnl_getdcbx, .setdcbx = ice_dcbnl_setdcbx, }; /** * ice_dcbnl_set_all - set all the apps and ieee data from DCBX config * @vsi: pointer to VSI struct */ void ice_dcbnl_set_all(struct ice_vsi *vsi) { struct net_device *netdev = vsi->netdev; struct ice_dcbx_cfg *dcbxcfg; struct ice_port_info *pi; struct dcb_app sapp; struct ice_pf *pf; unsigned int i; if (!netdev) return; pf = ice_netdev_to_pf(netdev); pi = pf->hw.port_info; /* SW DCB taken care of by SW Default Config */ if (pf->dcbx_cap & DCB_CAP_DCBX_HOST) return; /* DCB not enabled */ if (!test_bit(ICE_FLAG_DCB_ENA, pf->flags)) return; dcbxcfg = &pi->qos_cfg.local_dcbx_cfg; for (i = 0; i < dcbxcfg->numapps; i++) { u8 prio, tc_map; prio = dcbxcfg->app[i].priority; tc_map = BIT(dcbxcfg->etscfg.prio_table[prio]); /* Add APP only if the TC is enabled for this VSI */ if (tc_map & vsi->tc_cfg.ena_tc) { sapp.selector = dcbxcfg->app[i].selector; sapp.protocol = dcbxcfg->app[i].prot_id; sapp.priority = prio; dcb_ieee_setapp(netdev, &sapp); } } /* Notify user-space of the changes */ dcbnl_ieee_notify(netdev, RTM_SETDCB, DCB_CMD_IEEE_SET, 0, 0); } /** * ice_dcbnl_vsi_del_app - Delete APP on all VSIs * @vsi: pointer to the main VSI * @app: APP to delete * * Delete given APP from all the VSIs for given PF */ static void ice_dcbnl_vsi_del_app(struct ice_vsi *vsi, struct ice_dcb_app_priority_table *app) { struct dcb_app sapp; int err; sapp.selector = app->selector; sapp.protocol = app->prot_id; sapp.priority = app->priority; err = ice_dcbnl_delapp(vsi->netdev, &sapp); dev_dbg(ice_pf_to_dev(vsi->back), "Deleting app for VSI idx=%d err=%d sel=%d proto=0x%x, prio=%d\n", vsi->idx, err, app->selector, app->prot_id, app->priority); } /** * ice_dcbnl_flush_apps - Delete all removed APPs * @pf: the corresponding PF * @old_cfg: old DCBX configuration data * @new_cfg: new DCBX configuration data * * Find and delete all APPS that are not present in the passed * DCB configuration */ void ice_dcbnl_flush_apps(struct ice_pf *pf, struct ice_dcbx_cfg *old_cfg, struct ice_dcbx_cfg *new_cfg) { struct ice_vsi *main_vsi = ice_get_main_vsi(pf); unsigned int i; if (!main_vsi) return; for (i = 0; i < old_cfg->numapps; i++) { struct ice_dcb_app_priority_table app = old_cfg->app[i]; /* The APP is not available anymore delete it */ if (!ice_dcbnl_find_app(new_cfg, &app)) ice_dcbnl_vsi_del_app(main_vsi, &app); } } /** * ice_dcbnl_setup - setup DCBNL * @vsi: VSI to get associated netdev from */ void ice_dcbnl_setup(struct ice_vsi *vsi) { struct net_device *netdev = vsi->netdev; struct ice_pf *pf; pf = ice_netdev_to_pf(netdev); if (!test_bit(ICE_FLAG_DCB_CAPABLE, pf->flags)) return; netdev->dcbnl_ops = &dcbnl_ops; ice_dcbnl_set_all(vsi); }
linux-master
drivers/net/ethernet/intel/ice/ice_dcb_nl.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2018, Intel Corporation. */ /* ethtool support for ice */ #include "ice.h" #include "ice_ethtool.h" #include "ice_flow.h" #include "ice_fltr.h" #include "ice_lib.h" #include "ice_dcb_lib.h" #include <net/dcbnl.h> struct ice_stats { char stat_string[ETH_GSTRING_LEN]; int sizeof_stat; int stat_offset; }; #define ICE_STAT(_type, _name, _stat) { \ .stat_string = _name, \ .sizeof_stat = sizeof_field(_type, _stat), \ .stat_offset = offsetof(_type, _stat) \ } #define ICE_VSI_STAT(_name, _stat) \ ICE_STAT(struct ice_vsi, _name, _stat) #define ICE_PF_STAT(_name, _stat) \ ICE_STAT(struct ice_pf, _name, _stat) static int ice_q_stats_len(struct net_device *netdev) { struct ice_netdev_priv *np = netdev_priv(netdev); return ((np->vsi->alloc_txq + np->vsi->alloc_rxq) * (sizeof(struct ice_q_stats) / sizeof(u64))); } #define ICE_PF_STATS_LEN ARRAY_SIZE(ice_gstrings_pf_stats) #define ICE_VSI_STATS_LEN ARRAY_SIZE(ice_gstrings_vsi_stats) #define ICE_PFC_STATS_LEN ( \ (sizeof_field(struct ice_pf, stats.priority_xoff_rx) + \ sizeof_field(struct ice_pf, stats.priority_xon_rx) + \ sizeof_field(struct ice_pf, stats.priority_xoff_tx) + \ sizeof_field(struct ice_pf, stats.priority_xon_tx)) \ / sizeof(u64)) #define ICE_ALL_STATS_LEN(n) (ICE_PF_STATS_LEN + ICE_PFC_STATS_LEN + \ ICE_VSI_STATS_LEN + ice_q_stats_len(n)) static const struct ice_stats ice_gstrings_vsi_stats[] = { ICE_VSI_STAT("rx_unicast", eth_stats.rx_unicast), ICE_VSI_STAT("tx_unicast", eth_stats.tx_unicast), ICE_VSI_STAT("rx_multicast", eth_stats.rx_multicast), ICE_VSI_STAT("tx_multicast", eth_stats.tx_multicast), ICE_VSI_STAT("rx_broadcast", eth_stats.rx_broadcast), ICE_VSI_STAT("tx_broadcast", eth_stats.tx_broadcast), ICE_VSI_STAT("rx_bytes", eth_stats.rx_bytes), ICE_VSI_STAT("tx_bytes", eth_stats.tx_bytes), ICE_VSI_STAT("rx_dropped", eth_stats.rx_discards), ICE_VSI_STAT("rx_unknown_protocol", eth_stats.rx_unknown_protocol), ICE_VSI_STAT("rx_alloc_fail", rx_buf_failed), ICE_VSI_STAT("rx_pg_alloc_fail", rx_page_failed), ICE_VSI_STAT("tx_errors", eth_stats.tx_errors), ICE_VSI_STAT("tx_linearize", tx_linearize), ICE_VSI_STAT("tx_busy", tx_busy), ICE_VSI_STAT("tx_restart", tx_restart), }; enum ice_ethtool_test_id { ICE_ETH_TEST_REG = 0, ICE_ETH_TEST_EEPROM, ICE_ETH_TEST_INTR, ICE_ETH_TEST_LOOP, ICE_ETH_TEST_LINK, }; static const char ice_gstrings_test[][ETH_GSTRING_LEN] = { "Register test (offline)", "EEPROM test (offline)", "Interrupt test (offline)", "Loopback test (offline)", "Link test (on/offline)", }; #define ICE_TEST_LEN (sizeof(ice_gstrings_test) / ETH_GSTRING_LEN) /* These PF_STATs might look like duplicates of some NETDEV_STATs, * but they aren't. This device is capable of supporting multiple * VSIs/netdevs on a single PF. The NETDEV_STATs are for individual * netdevs whereas the PF_STATs are for the physical function that's * hosting these netdevs. * * The PF_STATs are appended to the netdev stats only when ethtool -S * is queried on the base PF netdev. */ static const struct ice_stats ice_gstrings_pf_stats[] = { ICE_PF_STAT("rx_bytes.nic", stats.eth.rx_bytes), ICE_PF_STAT("tx_bytes.nic", stats.eth.tx_bytes), ICE_PF_STAT("rx_unicast.nic", stats.eth.rx_unicast), ICE_PF_STAT("tx_unicast.nic", stats.eth.tx_unicast), ICE_PF_STAT("rx_multicast.nic", stats.eth.rx_multicast), ICE_PF_STAT("tx_multicast.nic", stats.eth.tx_multicast), ICE_PF_STAT("rx_broadcast.nic", stats.eth.rx_broadcast), ICE_PF_STAT("tx_broadcast.nic", stats.eth.tx_broadcast), ICE_PF_STAT("tx_errors.nic", stats.eth.tx_errors), ICE_PF_STAT("tx_timeout.nic", tx_timeout_count), ICE_PF_STAT("rx_size_64.nic", stats.rx_size_64), ICE_PF_STAT("tx_size_64.nic", stats.tx_size_64), ICE_PF_STAT("rx_size_127.nic", stats.rx_size_127), ICE_PF_STAT("tx_size_127.nic", stats.tx_size_127), ICE_PF_STAT("rx_size_255.nic", stats.rx_size_255), ICE_PF_STAT("tx_size_255.nic", stats.tx_size_255), ICE_PF_STAT("rx_size_511.nic", stats.rx_size_511), ICE_PF_STAT("tx_size_511.nic", stats.tx_size_511), ICE_PF_STAT("rx_size_1023.nic", stats.rx_size_1023), ICE_PF_STAT("tx_size_1023.nic", stats.tx_size_1023), ICE_PF_STAT("rx_size_1522.nic", stats.rx_size_1522), ICE_PF_STAT("tx_size_1522.nic", stats.tx_size_1522), ICE_PF_STAT("rx_size_big.nic", stats.rx_size_big), ICE_PF_STAT("tx_size_big.nic", stats.tx_size_big), ICE_PF_STAT("link_xon_rx.nic", stats.link_xon_rx), ICE_PF_STAT("link_xon_tx.nic", stats.link_xon_tx), ICE_PF_STAT("link_xoff_rx.nic", stats.link_xoff_rx), ICE_PF_STAT("link_xoff_tx.nic", stats.link_xoff_tx), ICE_PF_STAT("tx_dropped_link_down.nic", stats.tx_dropped_link_down), ICE_PF_STAT("rx_undersize.nic", stats.rx_undersize), ICE_PF_STAT("rx_fragments.nic", stats.rx_fragments), ICE_PF_STAT("rx_oversize.nic", stats.rx_oversize), ICE_PF_STAT("rx_jabber.nic", stats.rx_jabber), ICE_PF_STAT("rx_csum_bad.nic", hw_csum_rx_error), ICE_PF_STAT("rx_length_errors.nic", stats.rx_len_errors), ICE_PF_STAT("rx_dropped.nic", stats.eth.rx_discards), ICE_PF_STAT("rx_crc_errors.nic", stats.crc_errors), ICE_PF_STAT("illegal_bytes.nic", stats.illegal_bytes), ICE_PF_STAT("mac_local_faults.nic", stats.mac_local_faults), ICE_PF_STAT("mac_remote_faults.nic", stats.mac_remote_faults), ICE_PF_STAT("fdir_sb_match.nic", stats.fd_sb_match), ICE_PF_STAT("fdir_sb_status.nic", stats.fd_sb_status), ICE_PF_STAT("tx_hwtstamp_skipped", ptp.tx_hwtstamp_skipped), ICE_PF_STAT("tx_hwtstamp_timeouts", ptp.tx_hwtstamp_timeouts), ICE_PF_STAT("tx_hwtstamp_flushed", ptp.tx_hwtstamp_flushed), ICE_PF_STAT("tx_hwtstamp_discarded", ptp.tx_hwtstamp_discarded), ICE_PF_STAT("late_cached_phc_updates", ptp.late_cached_phc_updates), }; static const u32 ice_regs_dump_list[] = { PFGEN_STATE, PRTGEN_STATUS, QRX_CTRL(0), QINT_TQCTL(0), QINT_RQCTL(0), PFINT_OICR_ENA, QRX_ITR(0), #define GLDCB_TLPM_PCI_DM 0x000A0180 GLDCB_TLPM_PCI_DM, #define GLDCB_TLPM_TC2PFC 0x000A0194 GLDCB_TLPM_TC2PFC, #define TCDCB_TLPM_WAIT_DM(_i) (0x000A0080 + ((_i) * 4)) TCDCB_TLPM_WAIT_DM(0), TCDCB_TLPM_WAIT_DM(1), TCDCB_TLPM_WAIT_DM(2), TCDCB_TLPM_WAIT_DM(3), TCDCB_TLPM_WAIT_DM(4), TCDCB_TLPM_WAIT_DM(5), TCDCB_TLPM_WAIT_DM(6), TCDCB_TLPM_WAIT_DM(7), TCDCB_TLPM_WAIT_DM(8), TCDCB_TLPM_WAIT_DM(9), TCDCB_TLPM_WAIT_DM(10), TCDCB_TLPM_WAIT_DM(11), TCDCB_TLPM_WAIT_DM(12), TCDCB_TLPM_WAIT_DM(13), TCDCB_TLPM_WAIT_DM(14), TCDCB_TLPM_WAIT_DM(15), TCDCB_TLPM_WAIT_DM(16), TCDCB_TLPM_WAIT_DM(17), TCDCB_TLPM_WAIT_DM(18), TCDCB_TLPM_WAIT_DM(19), TCDCB_TLPM_WAIT_DM(20), TCDCB_TLPM_WAIT_DM(21), TCDCB_TLPM_WAIT_DM(22), TCDCB_TLPM_WAIT_DM(23), TCDCB_TLPM_WAIT_DM(24), TCDCB_TLPM_WAIT_DM(25), TCDCB_TLPM_WAIT_DM(26), TCDCB_TLPM_WAIT_DM(27), TCDCB_TLPM_WAIT_DM(28), TCDCB_TLPM_WAIT_DM(29), TCDCB_TLPM_WAIT_DM(30), TCDCB_TLPM_WAIT_DM(31), #define GLPCI_WATMK_CLNT_PIPEMON 0x000BFD90 GLPCI_WATMK_CLNT_PIPEMON, #define GLPCI_CUR_CLNT_COMMON 0x000BFD84 GLPCI_CUR_CLNT_COMMON, #define GLPCI_CUR_CLNT_PIPEMON 0x000BFD88 GLPCI_CUR_CLNT_PIPEMON, #define GLPCI_PCIERR 0x0009DEB0 GLPCI_PCIERR, #define GLPSM_DEBUG_CTL_STATUS 0x000B0600 GLPSM_DEBUG_CTL_STATUS, #define GLPSM0_DEBUG_FIFO_OVERFLOW_DETECT 0x000B0680 GLPSM0_DEBUG_FIFO_OVERFLOW_DETECT, #define GLPSM0_DEBUG_FIFO_UNDERFLOW_DETECT 0x000B0684 GLPSM0_DEBUG_FIFO_UNDERFLOW_DETECT, #define GLPSM0_DEBUG_DT_OUT_OF_WINDOW 0x000B0688 GLPSM0_DEBUG_DT_OUT_OF_WINDOW, #define GLPSM0_DEBUG_INTF_HW_ERROR_DETECT 0x000B069C GLPSM0_DEBUG_INTF_HW_ERROR_DETECT, #define GLPSM0_DEBUG_MISC_HW_ERROR_DETECT 0x000B06A0 GLPSM0_DEBUG_MISC_HW_ERROR_DETECT, #define GLPSM1_DEBUG_FIFO_OVERFLOW_DETECT 0x000B0E80 GLPSM1_DEBUG_FIFO_OVERFLOW_DETECT, #define GLPSM1_DEBUG_FIFO_UNDERFLOW_DETECT 0x000B0E84 GLPSM1_DEBUG_FIFO_UNDERFLOW_DETECT, #define GLPSM1_DEBUG_SRL_FIFO_OVERFLOW_DETECT 0x000B0E88 GLPSM1_DEBUG_SRL_FIFO_OVERFLOW_DETECT, #define GLPSM1_DEBUG_SRL_FIFO_UNDERFLOW_DETECT 0x000B0E8C GLPSM1_DEBUG_SRL_FIFO_UNDERFLOW_DETECT, #define GLPSM1_DEBUG_MISC_HW_ERROR_DETECT 0x000B0E90 GLPSM1_DEBUG_MISC_HW_ERROR_DETECT, #define GLPSM2_DEBUG_FIFO_OVERFLOW_DETECT 0x000B1680 GLPSM2_DEBUG_FIFO_OVERFLOW_DETECT, #define GLPSM2_DEBUG_FIFO_UNDERFLOW_DETECT 0x000B1684 GLPSM2_DEBUG_FIFO_UNDERFLOW_DETECT, #define GLPSM2_DEBUG_MISC_HW_ERROR_DETECT 0x000B1688 GLPSM2_DEBUG_MISC_HW_ERROR_DETECT, #define GLTDPU_TCLAN_COMP_BOB(_i) (0x00049ADC + ((_i) * 4)) GLTDPU_TCLAN_COMP_BOB(1), GLTDPU_TCLAN_COMP_BOB(2), GLTDPU_TCLAN_COMP_BOB(3), GLTDPU_TCLAN_COMP_BOB(4), GLTDPU_TCLAN_COMP_BOB(5), GLTDPU_TCLAN_COMP_BOB(6), GLTDPU_TCLAN_COMP_BOB(7), GLTDPU_TCLAN_COMP_BOB(8), #define GLTDPU_TCB_CMD_BOB(_i) (0x0004975C + ((_i) * 4)) GLTDPU_TCB_CMD_BOB(1), GLTDPU_TCB_CMD_BOB(2), GLTDPU_TCB_CMD_BOB(3), GLTDPU_TCB_CMD_BOB(4), GLTDPU_TCB_CMD_BOB(5), GLTDPU_TCB_CMD_BOB(6), GLTDPU_TCB_CMD_BOB(7), GLTDPU_TCB_CMD_BOB(8), #define GLTDPU_PSM_UPDATE_BOB(_i) (0x00049B5C + ((_i) * 4)) GLTDPU_PSM_UPDATE_BOB(1), GLTDPU_PSM_UPDATE_BOB(2), GLTDPU_PSM_UPDATE_BOB(3), GLTDPU_PSM_UPDATE_BOB(4), GLTDPU_PSM_UPDATE_BOB(5), GLTDPU_PSM_UPDATE_BOB(6), GLTDPU_PSM_UPDATE_BOB(7), GLTDPU_PSM_UPDATE_BOB(8), #define GLTCB_CMD_IN_BOB(_i) (0x000AE288 + ((_i) * 4)) GLTCB_CMD_IN_BOB(1), GLTCB_CMD_IN_BOB(2), GLTCB_CMD_IN_BOB(3), GLTCB_CMD_IN_BOB(4), GLTCB_CMD_IN_BOB(5), GLTCB_CMD_IN_BOB(6), GLTCB_CMD_IN_BOB(7), GLTCB_CMD_IN_BOB(8), #define GLLAN_TCLAN_FETCH_CTL_FBK_BOB_CTL(_i) (0x000FC148 + ((_i) * 4)) GLLAN_TCLAN_FETCH_CTL_FBK_BOB_CTL(1), GLLAN_TCLAN_FETCH_CTL_FBK_BOB_CTL(2), GLLAN_TCLAN_FETCH_CTL_FBK_BOB_CTL(3), GLLAN_TCLAN_FETCH_CTL_FBK_BOB_CTL(4), GLLAN_TCLAN_FETCH_CTL_FBK_BOB_CTL(5), GLLAN_TCLAN_FETCH_CTL_FBK_BOB_CTL(6), GLLAN_TCLAN_FETCH_CTL_FBK_BOB_CTL(7), GLLAN_TCLAN_FETCH_CTL_FBK_BOB_CTL(8), #define GLLAN_TCLAN_FETCH_CTL_SCHED_BOB_CTL(_i) (0x000FC248 + ((_i) * 4)) GLLAN_TCLAN_FETCH_CTL_SCHED_BOB_CTL(1), GLLAN_TCLAN_FETCH_CTL_SCHED_BOB_CTL(2), GLLAN_TCLAN_FETCH_CTL_SCHED_BOB_CTL(3), GLLAN_TCLAN_FETCH_CTL_SCHED_BOB_CTL(4), GLLAN_TCLAN_FETCH_CTL_SCHED_BOB_CTL(5), GLLAN_TCLAN_FETCH_CTL_SCHED_BOB_CTL(6), GLLAN_TCLAN_FETCH_CTL_SCHED_BOB_CTL(7), GLLAN_TCLAN_FETCH_CTL_SCHED_BOB_CTL(8), #define GLLAN_TCLAN_CACHE_CTL_BOB_CTL(_i) (0x000FC1C8 + ((_i) * 4)) GLLAN_TCLAN_CACHE_CTL_BOB_CTL(1), GLLAN_TCLAN_CACHE_CTL_BOB_CTL(2), GLLAN_TCLAN_CACHE_CTL_BOB_CTL(3), GLLAN_TCLAN_CACHE_CTL_BOB_CTL(4), GLLAN_TCLAN_CACHE_CTL_BOB_CTL(5), GLLAN_TCLAN_CACHE_CTL_BOB_CTL(6), GLLAN_TCLAN_CACHE_CTL_BOB_CTL(7), GLLAN_TCLAN_CACHE_CTL_BOB_CTL(8), #define GLLAN_TCLAN_FETCH_CTL_PROC_BOB_CTL(_i) (0x000FC188 + ((_i) * 4)) GLLAN_TCLAN_FETCH_CTL_PROC_BOB_CTL(1), GLLAN_TCLAN_FETCH_CTL_PROC_BOB_CTL(2), GLLAN_TCLAN_FETCH_CTL_PROC_BOB_CTL(3), GLLAN_TCLAN_FETCH_CTL_PROC_BOB_CTL(4), GLLAN_TCLAN_FETCH_CTL_PROC_BOB_CTL(5), GLLAN_TCLAN_FETCH_CTL_PROC_BOB_CTL(6), GLLAN_TCLAN_FETCH_CTL_PROC_BOB_CTL(7), GLLAN_TCLAN_FETCH_CTL_PROC_BOB_CTL(8), #define GLLAN_TCLAN_FETCH_CTL_PCIE_RD_BOB_CTL(_i) (0x000FC288 + ((_i) * 4)) GLLAN_TCLAN_FETCH_CTL_PCIE_RD_BOB_CTL(1), GLLAN_TCLAN_FETCH_CTL_PCIE_RD_BOB_CTL(2), GLLAN_TCLAN_FETCH_CTL_PCIE_RD_BOB_CTL(3), GLLAN_TCLAN_FETCH_CTL_PCIE_RD_BOB_CTL(4), GLLAN_TCLAN_FETCH_CTL_PCIE_RD_BOB_CTL(5), GLLAN_TCLAN_FETCH_CTL_PCIE_RD_BOB_CTL(6), GLLAN_TCLAN_FETCH_CTL_PCIE_RD_BOB_CTL(7), GLLAN_TCLAN_FETCH_CTL_PCIE_RD_BOB_CTL(8), #define PRTDCB_TCUPM_REG_CM(_i) (0x000BC360 + ((_i) * 4)) PRTDCB_TCUPM_REG_CM(0), PRTDCB_TCUPM_REG_CM(1), PRTDCB_TCUPM_REG_CM(2), PRTDCB_TCUPM_REG_CM(3), #define PRTDCB_TCUPM_REG_DM(_i) (0x000BC3A0 + ((_i) * 4)) PRTDCB_TCUPM_REG_DM(0), PRTDCB_TCUPM_REG_DM(1), PRTDCB_TCUPM_REG_DM(2), PRTDCB_TCUPM_REG_DM(3), #define PRTDCB_TLPM_REG_DM(_i) (0x000A0000 + ((_i) * 4)) PRTDCB_TLPM_REG_DM(0), PRTDCB_TLPM_REG_DM(1), PRTDCB_TLPM_REG_DM(2), PRTDCB_TLPM_REG_DM(3), }; struct ice_priv_flag { char name[ETH_GSTRING_LEN]; u32 bitno; /* bit position in pf->flags */ }; #define ICE_PRIV_FLAG(_name, _bitno) { \ .name = _name, \ .bitno = _bitno, \ } static const struct ice_priv_flag ice_gstrings_priv_flags[] = { ICE_PRIV_FLAG("link-down-on-close", ICE_FLAG_LINK_DOWN_ON_CLOSE_ENA), ICE_PRIV_FLAG("fw-lldp-agent", ICE_FLAG_FW_LLDP_AGENT), ICE_PRIV_FLAG("vf-true-promisc-support", ICE_FLAG_VF_TRUE_PROMISC_ENA), ICE_PRIV_FLAG("mdd-auto-reset-vf", ICE_FLAG_MDD_AUTO_RESET_VF), ICE_PRIV_FLAG("vf-vlan-pruning", ICE_FLAG_VF_VLAN_PRUNING), ICE_PRIV_FLAG("legacy-rx", ICE_FLAG_LEGACY_RX), }; #define ICE_PRIV_FLAG_ARRAY_SIZE ARRAY_SIZE(ice_gstrings_priv_flags) static void __ice_get_drvinfo(struct net_device *netdev, struct ethtool_drvinfo *drvinfo, struct ice_vsi *vsi) { struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; struct ice_orom_info *orom; struct ice_nvm_info *nvm; nvm = &hw->flash.nvm; orom = &hw->flash.orom; strscpy(drvinfo->driver, KBUILD_MODNAME, sizeof(drvinfo->driver)); /* Display NVM version (from which the firmware version can be * determined) which contains more pertinent information. */ snprintf(drvinfo->fw_version, sizeof(drvinfo->fw_version), "%x.%02x 0x%x %d.%d.%d", nvm->major, nvm->minor, nvm->eetrack, orom->major, orom->build, orom->patch); strscpy(drvinfo->bus_info, pci_name(pf->pdev), sizeof(drvinfo->bus_info)); } static void ice_get_drvinfo(struct net_device *netdev, struct ethtool_drvinfo *drvinfo) { struct ice_netdev_priv *np = netdev_priv(netdev); __ice_get_drvinfo(netdev, drvinfo, np->vsi); drvinfo->n_priv_flags = ICE_PRIV_FLAG_ARRAY_SIZE; } static int ice_get_regs_len(struct net_device __always_unused *netdev) { return sizeof(ice_regs_dump_list); } static void ice_get_regs(struct net_device *netdev, struct ethtool_regs *regs, void *p) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_pf *pf = np->vsi->back; struct ice_hw *hw = &pf->hw; u32 *regs_buf = (u32 *)p; unsigned int i; regs->version = 1; for (i = 0; i < ARRAY_SIZE(ice_regs_dump_list); ++i) regs_buf[i] = rd32(hw, ice_regs_dump_list[i]); } static u32 ice_get_msglevel(struct net_device *netdev) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_pf *pf = np->vsi->back; #ifndef CONFIG_DYNAMIC_DEBUG if (pf->hw.debug_mask) netdev_info(netdev, "hw debug_mask: 0x%llX\n", pf->hw.debug_mask); #endif /* !CONFIG_DYNAMIC_DEBUG */ return pf->msg_enable; } static void ice_set_msglevel(struct net_device *netdev, u32 data) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_pf *pf = np->vsi->back; #ifndef CONFIG_DYNAMIC_DEBUG if (ICE_DBG_USER & data) pf->hw.debug_mask = data; else pf->msg_enable = data; #else pf->msg_enable = data; #endif /* !CONFIG_DYNAMIC_DEBUG */ } static int ice_get_eeprom_len(struct net_device *netdev) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_pf *pf = np->vsi->back; return (int)pf->hw.flash.flash_size; } static int ice_get_eeprom(struct net_device *netdev, struct ethtool_eeprom *eeprom, u8 *bytes) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; struct device *dev; int ret; u8 *buf; dev = ice_pf_to_dev(pf); eeprom->magic = hw->vendor_id | (hw->device_id << 16); netdev_dbg(netdev, "GEEPROM cmd 0x%08x, offset 0x%08x, len 0x%08x\n", eeprom->cmd, eeprom->offset, eeprom->len); buf = kzalloc(eeprom->len, GFP_KERNEL); if (!buf) return -ENOMEM; ret = ice_acquire_nvm(hw, ICE_RES_READ); if (ret) { dev_err(dev, "ice_acquire_nvm failed, err %d aq_err %s\n", ret, ice_aq_str(hw->adminq.sq_last_status)); goto out; } ret = ice_read_flat_nvm(hw, eeprom->offset, &eeprom->len, buf, false); if (ret) { dev_err(dev, "ice_read_flat_nvm failed, err %d aq_err %s\n", ret, ice_aq_str(hw->adminq.sq_last_status)); goto release; } memcpy(bytes, buf, eeprom->len); release: ice_release_nvm(hw); out: kfree(buf); return ret; } /** * ice_active_vfs - check if there are any active VFs * @pf: board private structure * * Returns true if an active VF is found, otherwise returns false */ static bool ice_active_vfs(struct ice_pf *pf) { bool active = false; struct ice_vf *vf; unsigned int bkt; rcu_read_lock(); ice_for_each_vf_rcu(pf, bkt, vf) { if (test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) { active = true; break; } } rcu_read_unlock(); return active; } /** * ice_link_test - perform a link test on a given net_device * @netdev: network interface device structure * * This function performs one of the self-tests required by ethtool. * Returns 0 on success, non-zero on failure. */ static u64 ice_link_test(struct net_device *netdev) { struct ice_netdev_priv *np = netdev_priv(netdev); bool link_up = false; int status; netdev_info(netdev, "link test\n"); status = ice_get_link_status(np->vsi->port_info, &link_up); if (status) { netdev_err(netdev, "link query error, status = %d\n", status); return 1; } if (!link_up) return 2; return 0; } /** * ice_eeprom_test - perform an EEPROM test on a given net_device * @netdev: network interface device structure * * This function performs one of the self-tests required by ethtool. * Returns 0 on success, non-zero on failure. */ static u64 ice_eeprom_test(struct net_device *netdev) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_pf *pf = np->vsi->back; netdev_info(netdev, "EEPROM test\n"); return !!(ice_nvm_validate_checksum(&pf->hw)); } /** * ice_reg_pattern_test * @hw: pointer to the HW struct * @reg: reg to be tested * @mask: bits to be touched */ static int ice_reg_pattern_test(struct ice_hw *hw, u32 reg, u32 mask) { struct ice_pf *pf = (struct ice_pf *)hw->back; struct device *dev = ice_pf_to_dev(pf); static const u32 patterns[] = { 0x5A5A5A5A, 0xA5A5A5A5, 0x00000000, 0xFFFFFFFF }; u32 val, orig_val; unsigned int i; orig_val = rd32(hw, reg); for (i = 0; i < ARRAY_SIZE(patterns); ++i) { u32 pattern = patterns[i] & mask; wr32(hw, reg, pattern); val = rd32(hw, reg); if (val == pattern) continue; dev_err(dev, "%s: reg pattern test failed - reg 0x%08x pat 0x%08x val 0x%08x\n" , __func__, reg, pattern, val); return 1; } wr32(hw, reg, orig_val); val = rd32(hw, reg); if (val != orig_val) { dev_err(dev, "%s: reg restore test failed - reg 0x%08x orig 0x%08x val 0x%08x\n" , __func__, reg, orig_val, val); return 1; } return 0; } /** * ice_reg_test - perform a register test on a given net_device * @netdev: network interface device structure * * This function performs one of the self-tests required by ethtool. * Returns 0 on success, non-zero on failure. */ static u64 ice_reg_test(struct net_device *netdev) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_hw *hw = np->vsi->port_info->hw; u32 int_elements = hw->func_caps.common_cap.num_msix_vectors ? hw->func_caps.common_cap.num_msix_vectors - 1 : 1; struct ice_diag_reg_test_info { u32 address; u32 mask; u32 elem_num; u32 elem_size; } ice_reg_list[] = { {GLINT_ITR(0, 0), 0x00000fff, int_elements, GLINT_ITR(0, 1) - GLINT_ITR(0, 0)}, {GLINT_ITR(1, 0), 0x00000fff, int_elements, GLINT_ITR(1, 1) - GLINT_ITR(1, 0)}, {GLINT_ITR(0, 0), 0x00000fff, int_elements, GLINT_ITR(2, 1) - GLINT_ITR(2, 0)}, {GLINT_CTL, 0xffff0001, 1, 0} }; unsigned int i; netdev_dbg(netdev, "Register test\n"); for (i = 0; i < ARRAY_SIZE(ice_reg_list); ++i) { u32 j; for (j = 0; j < ice_reg_list[i].elem_num; ++j) { u32 mask = ice_reg_list[i].mask; u32 reg = ice_reg_list[i].address + (j * ice_reg_list[i].elem_size); /* bail on failure (non-zero return) */ if (ice_reg_pattern_test(hw, reg, mask)) return 1; } } return 0; } /** * ice_lbtest_prepare_rings - configure Tx/Rx test rings * @vsi: pointer to the VSI structure * * Function configures rings of a VSI for loopback test without * enabling interrupts or informing the kernel about new queues. * * Returns 0 on success, negative on failure. */ static int ice_lbtest_prepare_rings(struct ice_vsi *vsi) { int status; status = ice_vsi_setup_tx_rings(vsi); if (status) goto err_setup_tx_ring; status = ice_vsi_setup_rx_rings(vsi); if (status) goto err_setup_rx_ring; status = ice_vsi_cfg_lan(vsi); if (status) goto err_setup_rx_ring; status = ice_vsi_start_all_rx_rings(vsi); if (status) goto err_start_rx_ring; return 0; err_start_rx_ring: ice_vsi_free_rx_rings(vsi); err_setup_rx_ring: ice_vsi_stop_lan_tx_rings(vsi, ICE_NO_RESET, 0); err_setup_tx_ring: ice_vsi_free_tx_rings(vsi); return status; } /** * ice_lbtest_disable_rings - disable Tx/Rx test rings after loopback test * @vsi: pointer to the VSI structure * * Function stops and frees VSI rings after a loopback test. * Returns 0 on success, negative on failure. */ static int ice_lbtest_disable_rings(struct ice_vsi *vsi) { int status; status = ice_vsi_stop_lan_tx_rings(vsi, ICE_NO_RESET, 0); if (status) netdev_err(vsi->netdev, "Failed to stop Tx rings, VSI %d error %d\n", vsi->vsi_num, status); status = ice_vsi_stop_all_rx_rings(vsi); if (status) netdev_err(vsi->netdev, "Failed to stop Rx rings, VSI %d error %d\n", vsi->vsi_num, status); ice_vsi_free_tx_rings(vsi); ice_vsi_free_rx_rings(vsi); return status; } /** * ice_lbtest_create_frame - create test packet * @pf: pointer to the PF structure * @ret_data: allocated frame buffer * @size: size of the packet data * * Function allocates a frame with a test pattern on specific offsets. * Returns 0 on success, non-zero on failure. */ static int ice_lbtest_create_frame(struct ice_pf *pf, u8 **ret_data, u16 size) { u8 *data; if (!pf) return -EINVAL; data = devm_kzalloc(ice_pf_to_dev(pf), size, GFP_KERNEL); if (!data) return -ENOMEM; /* Since the ethernet test frame should always be at least * 64 bytes long, fill some octets in the payload with test data. */ memset(data, 0xFF, size); data[32] = 0xDE; data[42] = 0xAD; data[44] = 0xBE; data[46] = 0xEF; *ret_data = data; return 0; } /** * ice_lbtest_check_frame - verify received loopback frame * @frame: pointer to the raw packet data * * Function verifies received test frame with a pattern. * Returns true if frame matches the pattern, false otherwise. */ static bool ice_lbtest_check_frame(u8 *frame) { /* Validate bytes of a frame under offsets chosen earlier */ if (frame[32] == 0xDE && frame[42] == 0xAD && frame[44] == 0xBE && frame[46] == 0xEF && frame[48] == 0xFF) return true; return false; } /** * ice_diag_send - send test frames to the test ring * @tx_ring: pointer to the transmit ring * @data: pointer to the raw packet data * @size: size of the packet to send * * Function sends loopback packets on a test Tx ring. */ static int ice_diag_send(struct ice_tx_ring *tx_ring, u8 *data, u16 size) { struct ice_tx_desc *tx_desc; struct ice_tx_buf *tx_buf; dma_addr_t dma; u64 td_cmd; tx_desc = ICE_TX_DESC(tx_ring, tx_ring->next_to_use); tx_buf = &tx_ring->tx_buf[tx_ring->next_to_use]; dma = dma_map_single(tx_ring->dev, data, size, DMA_TO_DEVICE); if (dma_mapping_error(tx_ring->dev, dma)) return -EINVAL; tx_desc->buf_addr = cpu_to_le64(dma); /* These flags are required for a descriptor to be pushed out */ td_cmd = (u64)(ICE_TX_DESC_CMD_EOP | ICE_TX_DESC_CMD_RS); tx_desc->cmd_type_offset_bsz = cpu_to_le64(ICE_TX_DESC_DTYPE_DATA | (td_cmd << ICE_TXD_QW1_CMD_S) | ((u64)0 << ICE_TXD_QW1_OFFSET_S) | ((u64)size << ICE_TXD_QW1_TX_BUF_SZ_S) | ((u64)0 << ICE_TXD_QW1_L2TAG1_S)); tx_buf->next_to_watch = tx_desc; /* Force memory write to complete before letting h/w know * there are new descriptors to fetch. */ wmb(); tx_ring->next_to_use++; if (tx_ring->next_to_use >= tx_ring->count) tx_ring->next_to_use = 0; writel_relaxed(tx_ring->next_to_use, tx_ring->tail); /* Wait until the packets get transmitted to the receive queue. */ usleep_range(1000, 2000); dma_unmap_single(tx_ring->dev, dma, size, DMA_TO_DEVICE); return 0; } #define ICE_LB_FRAME_SIZE 64 /** * ice_lbtest_receive_frames - receive and verify test frames * @rx_ring: pointer to the receive ring * * Function receives loopback packets and verify their correctness. * Returns number of received valid frames. */ static int ice_lbtest_receive_frames(struct ice_rx_ring *rx_ring) { struct ice_rx_buf *rx_buf; int valid_frames, i; u8 *received_buf; valid_frames = 0; for (i = 0; i < rx_ring->count; i++) { union ice_32b_rx_flex_desc *rx_desc; rx_desc = ICE_RX_DESC(rx_ring, i); if (!(rx_desc->wb.status_error0 & (cpu_to_le16(BIT(ICE_RX_FLEX_DESC_STATUS0_DD_S)) | cpu_to_le16(BIT(ICE_RX_FLEX_DESC_STATUS0_EOF_S))))) continue; rx_buf = &rx_ring->rx_buf[i]; received_buf = page_address(rx_buf->page) + rx_buf->page_offset; if (ice_lbtest_check_frame(received_buf)) valid_frames++; } return valid_frames; } /** * ice_loopback_test - perform a loopback test on a given net_device * @netdev: network interface device structure * * This function performs one of the self-tests required by ethtool. * Returns 0 on success, non-zero on failure. */ static u64 ice_loopback_test(struct net_device *netdev) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *orig_vsi = np->vsi, *test_vsi; struct ice_pf *pf = orig_vsi->back; u8 broadcast[ETH_ALEN], ret = 0; int num_frames, valid_frames; struct ice_tx_ring *tx_ring; struct ice_rx_ring *rx_ring; struct device *dev; u8 *tx_frame; int i; dev = ice_pf_to_dev(pf); netdev_info(netdev, "loopback test\n"); test_vsi = ice_lb_vsi_setup(pf, pf->hw.port_info); if (!test_vsi) { netdev_err(netdev, "Failed to create a VSI for the loopback test\n"); return 1; } test_vsi->netdev = netdev; tx_ring = test_vsi->tx_rings[0]; rx_ring = test_vsi->rx_rings[0]; if (ice_lbtest_prepare_rings(test_vsi)) { ret = 2; goto lbtest_vsi_close; } if (ice_alloc_rx_bufs(rx_ring, rx_ring->count)) { ret = 3; goto lbtest_rings_dis; } /* Enable MAC loopback in firmware */ if (ice_aq_set_mac_loopback(&pf->hw, true, NULL)) { ret = 4; goto lbtest_mac_dis; } /* Test VSI needs to receive broadcast packets */ eth_broadcast_addr(broadcast); if (ice_fltr_add_mac(test_vsi, broadcast, ICE_FWD_TO_VSI)) { ret = 5; goto lbtest_mac_dis; } if (ice_lbtest_create_frame(pf, &tx_frame, ICE_LB_FRAME_SIZE)) { ret = 7; goto remove_mac_filters; } num_frames = min_t(int, tx_ring->count, 32); for (i = 0; i < num_frames; i++) { if (ice_diag_send(tx_ring, tx_frame, ICE_LB_FRAME_SIZE)) { ret = 8; goto lbtest_free_frame; } } valid_frames = ice_lbtest_receive_frames(rx_ring); if (!valid_frames) ret = 9; else if (valid_frames != num_frames) ret = 10; lbtest_free_frame: devm_kfree(dev, tx_frame); remove_mac_filters: if (ice_fltr_remove_mac(test_vsi, broadcast, ICE_FWD_TO_VSI)) netdev_err(netdev, "Could not remove MAC filter for the test VSI\n"); lbtest_mac_dis: /* Disable MAC loopback after the test is completed. */ if (ice_aq_set_mac_loopback(&pf->hw, false, NULL)) netdev_err(netdev, "Could not disable MAC loopback\n"); lbtest_rings_dis: if (ice_lbtest_disable_rings(test_vsi)) netdev_err(netdev, "Could not disable test rings\n"); lbtest_vsi_close: test_vsi->netdev = NULL; if (ice_vsi_release(test_vsi)) netdev_err(netdev, "Failed to remove the test VSI\n"); return ret; } /** * ice_intr_test - perform an interrupt test on a given net_device * @netdev: network interface device structure * * This function performs one of the self-tests required by ethtool. * Returns 0 on success, non-zero on failure. */ static u64 ice_intr_test(struct net_device *netdev) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_pf *pf = np->vsi->back; u16 swic_old = pf->sw_int_count; netdev_info(netdev, "interrupt test\n"); wr32(&pf->hw, GLINT_DYN_CTL(pf->oicr_irq.index), GLINT_DYN_CTL_SW_ITR_INDX_M | GLINT_DYN_CTL_INTENA_MSK_M | GLINT_DYN_CTL_SWINT_TRIG_M); usleep_range(1000, 2000); return (swic_old == pf->sw_int_count); } /** * ice_self_test - handler function for performing a self-test by ethtool * @netdev: network interface device structure * @eth_test: ethtool_test structure * @data: required by ethtool.self_test * * This function is called after invoking 'ethtool -t devname' command where * devname is the name of the network device on which ethtool should operate. * It performs a set of self-tests to check if a device works properly. */ static void ice_self_test(struct net_device *netdev, struct ethtool_test *eth_test, u64 *data) { struct ice_netdev_priv *np = netdev_priv(netdev); bool if_running = netif_running(netdev); struct ice_pf *pf = np->vsi->back; struct device *dev; dev = ice_pf_to_dev(pf); if (eth_test->flags == ETH_TEST_FL_OFFLINE) { netdev_info(netdev, "offline testing starting\n"); set_bit(ICE_TESTING, pf->state); if (ice_active_vfs(pf)) { dev_warn(dev, "Please take active VFs and Netqueues offline and restart the adapter before running NIC diagnostics\n"); data[ICE_ETH_TEST_REG] = 1; data[ICE_ETH_TEST_EEPROM] = 1; data[ICE_ETH_TEST_INTR] = 1; data[ICE_ETH_TEST_LOOP] = 1; data[ICE_ETH_TEST_LINK] = 1; eth_test->flags |= ETH_TEST_FL_FAILED; clear_bit(ICE_TESTING, pf->state); goto skip_ol_tests; } /* If the device is online then take it offline */ if (if_running) /* indicate we're in test mode */ ice_stop(netdev); data[ICE_ETH_TEST_LINK] = ice_link_test(netdev); data[ICE_ETH_TEST_EEPROM] = ice_eeprom_test(netdev); data[ICE_ETH_TEST_INTR] = ice_intr_test(netdev); data[ICE_ETH_TEST_LOOP] = ice_loopback_test(netdev); data[ICE_ETH_TEST_REG] = ice_reg_test(netdev); if (data[ICE_ETH_TEST_LINK] || data[ICE_ETH_TEST_EEPROM] || data[ICE_ETH_TEST_LOOP] || data[ICE_ETH_TEST_INTR] || data[ICE_ETH_TEST_REG]) eth_test->flags |= ETH_TEST_FL_FAILED; clear_bit(ICE_TESTING, pf->state); if (if_running) { int status = ice_open(netdev); if (status) { dev_err(dev, "Could not open device %s, err %d\n", pf->int_name, status); } } } else { /* Online tests */ netdev_info(netdev, "online testing starting\n"); data[ICE_ETH_TEST_LINK] = ice_link_test(netdev); if (data[ICE_ETH_TEST_LINK]) eth_test->flags |= ETH_TEST_FL_FAILED; /* Offline only tests, not run in online; pass by default */ data[ICE_ETH_TEST_REG] = 0; data[ICE_ETH_TEST_EEPROM] = 0; data[ICE_ETH_TEST_INTR] = 0; data[ICE_ETH_TEST_LOOP] = 0; } skip_ol_tests: netdev_info(netdev, "testing finished\n"); } static void __ice_get_strings(struct net_device *netdev, u32 stringset, u8 *data, struct ice_vsi *vsi) { unsigned int i; u8 *p = data; switch (stringset) { case ETH_SS_STATS: for (i = 0; i < ICE_VSI_STATS_LEN; i++) ethtool_sprintf(&p, ice_gstrings_vsi_stats[i].stat_string); if (ice_is_port_repr_netdev(netdev)) return; ice_for_each_alloc_txq(vsi, i) { ethtool_sprintf(&p, "tx_queue_%u_packets", i); ethtool_sprintf(&p, "tx_queue_%u_bytes", i); } ice_for_each_alloc_rxq(vsi, i) { ethtool_sprintf(&p, "rx_queue_%u_packets", i); ethtool_sprintf(&p, "rx_queue_%u_bytes", i); } if (vsi->type != ICE_VSI_PF) return; for (i = 0; i < ICE_PF_STATS_LEN; i++) ethtool_sprintf(&p, ice_gstrings_pf_stats[i].stat_string); for (i = 0; i < ICE_MAX_USER_PRIORITY; i++) { ethtool_sprintf(&p, "tx_priority_%u_xon.nic", i); ethtool_sprintf(&p, "tx_priority_%u_xoff.nic", i); } for (i = 0; i < ICE_MAX_USER_PRIORITY; i++) { ethtool_sprintf(&p, "rx_priority_%u_xon.nic", i); ethtool_sprintf(&p, "rx_priority_%u_xoff.nic", i); } break; case ETH_SS_TEST: memcpy(data, ice_gstrings_test, ICE_TEST_LEN * ETH_GSTRING_LEN); break; case ETH_SS_PRIV_FLAGS: for (i = 0; i < ICE_PRIV_FLAG_ARRAY_SIZE; i++) ethtool_sprintf(&p, ice_gstrings_priv_flags[i].name); break; default: break; } } static void ice_get_strings(struct net_device *netdev, u32 stringset, u8 *data) { struct ice_netdev_priv *np = netdev_priv(netdev); __ice_get_strings(netdev, stringset, data, np->vsi); } static int ice_set_phys_id(struct net_device *netdev, enum ethtool_phys_id_state state) { struct ice_netdev_priv *np = netdev_priv(netdev); bool led_active; switch (state) { case ETHTOOL_ID_ACTIVE: led_active = true; break; case ETHTOOL_ID_INACTIVE: led_active = false; break; default: return -EINVAL; } if (ice_aq_set_port_id_led(np->vsi->port_info, !led_active, NULL)) return -EIO; return 0; } /** * ice_set_fec_cfg - Set link FEC options * @netdev: network interface device structure * @req_fec: FEC mode to configure */ static int ice_set_fec_cfg(struct net_device *netdev, enum ice_fec_mode req_fec) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_aqc_set_phy_cfg_data config = { 0 }; struct ice_vsi *vsi = np->vsi; struct ice_port_info *pi; pi = vsi->port_info; if (!pi) return -EOPNOTSUPP; /* Changing the FEC parameters is not supported if not the PF VSI */ if (vsi->type != ICE_VSI_PF) { netdev_info(netdev, "Changing FEC parameters only supported for PF VSI\n"); return -EOPNOTSUPP; } /* Proceed only if requesting different FEC mode */ if (pi->phy.curr_user_fec_req == req_fec) return 0; /* Copy the current user PHY configuration. The current user PHY * configuration is initialized during probe from PHY capabilities * software mode, and updated on set PHY configuration. */ memcpy(&config, &pi->phy.curr_user_phy_cfg, sizeof(config)); ice_cfg_phy_fec(pi, &config, req_fec); config.caps |= ICE_AQ_PHY_ENA_AUTO_LINK_UPDT; if (ice_aq_set_phy_cfg(pi->hw, pi, &config, NULL)) return -EAGAIN; /* Save requested FEC config */ pi->phy.curr_user_fec_req = req_fec; return 0; } /** * ice_set_fecparam - Set FEC link options * @netdev: network interface device structure * @fecparam: Ethtool structure to retrieve FEC parameters */ static int ice_set_fecparam(struct net_device *netdev, struct ethtool_fecparam *fecparam) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; enum ice_fec_mode fec; switch (fecparam->fec) { case ETHTOOL_FEC_AUTO: fec = ICE_FEC_AUTO; break; case ETHTOOL_FEC_RS: fec = ICE_FEC_RS; break; case ETHTOOL_FEC_BASER: fec = ICE_FEC_BASER; break; case ETHTOOL_FEC_OFF: case ETHTOOL_FEC_NONE: fec = ICE_FEC_NONE; break; default: dev_warn(ice_pf_to_dev(vsi->back), "Unsupported FEC mode: %d\n", fecparam->fec); return -EINVAL; } return ice_set_fec_cfg(netdev, fec); } /** * ice_get_fecparam - Get link FEC options * @netdev: network interface device structure * @fecparam: Ethtool structure to retrieve FEC parameters */ static int ice_get_fecparam(struct net_device *netdev, struct ethtool_fecparam *fecparam) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_aqc_get_phy_caps_data *caps; struct ice_link_status *link_info; struct ice_vsi *vsi = np->vsi; struct ice_port_info *pi; int err; pi = vsi->port_info; if (!pi) return -EOPNOTSUPP; link_info = &pi->phy.link_info; /* Set FEC mode based on negotiated link info */ switch (link_info->fec_info) { case ICE_AQ_LINK_25G_KR_FEC_EN: fecparam->active_fec = ETHTOOL_FEC_BASER; break; case ICE_AQ_LINK_25G_RS_528_FEC_EN: case ICE_AQ_LINK_25G_RS_544_FEC_EN: fecparam->active_fec = ETHTOOL_FEC_RS; break; default: fecparam->active_fec = ETHTOOL_FEC_OFF; break; } caps = kzalloc(sizeof(*caps), GFP_KERNEL); if (!caps) return -ENOMEM; err = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_TOPO_CAP_MEDIA, caps, NULL); if (err) goto done; /* Set supported/configured FEC modes based on PHY capability */ if (caps->caps & ICE_AQC_PHY_EN_AUTO_FEC) fecparam->fec |= ETHTOOL_FEC_AUTO; if (caps->link_fec_options & ICE_AQC_PHY_FEC_10G_KR_40G_KR4_EN || caps->link_fec_options & ICE_AQC_PHY_FEC_10G_KR_40G_KR4_REQ || caps->link_fec_options & ICE_AQC_PHY_FEC_25G_KR_CLAUSE74_EN || caps->link_fec_options & ICE_AQC_PHY_FEC_25G_KR_REQ) fecparam->fec |= ETHTOOL_FEC_BASER; if (caps->link_fec_options & ICE_AQC_PHY_FEC_25G_RS_528_REQ || caps->link_fec_options & ICE_AQC_PHY_FEC_25G_RS_544_REQ || caps->link_fec_options & ICE_AQC_PHY_FEC_25G_RS_CLAUSE91_EN) fecparam->fec |= ETHTOOL_FEC_RS; if (caps->link_fec_options == 0) fecparam->fec |= ETHTOOL_FEC_OFF; done: kfree(caps); return err; } /** * ice_nway_reset - restart autonegotiation * @netdev: network interface device structure */ static int ice_nway_reset(struct net_device *netdev) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; int err; /* If VSI state is up, then restart autoneg with link up */ if (!test_bit(ICE_DOWN, vsi->back->state)) err = ice_set_link(vsi, true); else err = ice_set_link(vsi, false); return err; } /** * ice_get_priv_flags - report device private flags * @netdev: network interface device structure * * The get string set count and the string set should be matched for each * flag returned. Add new strings for each flag to the ice_gstrings_priv_flags * array. * * Returns a u32 bitmap of flags. */ static u32 ice_get_priv_flags(struct net_device *netdev) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; struct ice_pf *pf = vsi->back; u32 i, ret_flags = 0; for (i = 0; i < ICE_PRIV_FLAG_ARRAY_SIZE; i++) { const struct ice_priv_flag *priv_flag; priv_flag = &ice_gstrings_priv_flags[i]; if (test_bit(priv_flag->bitno, pf->flags)) ret_flags |= BIT(i); } return ret_flags; } /** * ice_set_priv_flags - set private flags * @netdev: network interface device structure * @flags: bit flags to be set */ static int ice_set_priv_flags(struct net_device *netdev, u32 flags) { struct ice_netdev_priv *np = netdev_priv(netdev); DECLARE_BITMAP(change_flags, ICE_PF_FLAGS_NBITS); DECLARE_BITMAP(orig_flags, ICE_PF_FLAGS_NBITS); struct ice_vsi *vsi = np->vsi; struct ice_pf *pf = vsi->back; struct device *dev; int ret = 0; u32 i; if (flags > BIT(ICE_PRIV_FLAG_ARRAY_SIZE)) return -EINVAL; dev = ice_pf_to_dev(pf); set_bit(ICE_FLAG_ETHTOOL_CTXT, pf->flags); bitmap_copy(orig_flags, pf->flags, ICE_PF_FLAGS_NBITS); for (i = 0; i < ICE_PRIV_FLAG_ARRAY_SIZE; i++) { const struct ice_priv_flag *priv_flag; priv_flag = &ice_gstrings_priv_flags[i]; if (flags & BIT(i)) set_bit(priv_flag->bitno, pf->flags); else clear_bit(priv_flag->bitno, pf->flags); } bitmap_xor(change_flags, pf->flags, orig_flags, ICE_PF_FLAGS_NBITS); /* Do not allow change to link-down-on-close when Total Port Shutdown * is enabled. */ if (test_bit(ICE_FLAG_LINK_DOWN_ON_CLOSE_ENA, change_flags) && test_bit(ICE_FLAG_TOTAL_PORT_SHUTDOWN_ENA, pf->flags)) { dev_err(dev, "Setting link-down-on-close not supported on this port\n"); set_bit(ICE_FLAG_LINK_DOWN_ON_CLOSE_ENA, pf->flags); ret = -EINVAL; goto ethtool_exit; } if (test_bit(ICE_FLAG_FW_LLDP_AGENT, change_flags)) { if (!test_bit(ICE_FLAG_FW_LLDP_AGENT, pf->flags)) { int status; /* Disable FW LLDP engine */ status = ice_cfg_lldp_mib_change(&pf->hw, false); /* If unregistering for LLDP events fails, this is * not an error state, as there shouldn't be any * events to respond to. */ if (status) dev_info(dev, "Failed to unreg for LLDP events\n"); /* The AQ call to stop the FW LLDP agent will generate * an error if the agent is already stopped. */ status = ice_aq_stop_lldp(&pf->hw, true, true, NULL); if (status) dev_warn(dev, "Fail to stop LLDP agent\n"); /* Use case for having the FW LLDP agent stopped * will likely not need DCB, so failure to init is * not a concern of ethtool */ status = ice_init_pf_dcb(pf, true); if (status) dev_warn(dev, "Fail to init DCB\n"); pf->dcbx_cap &= ~DCB_CAP_DCBX_LLD_MANAGED; pf->dcbx_cap |= DCB_CAP_DCBX_HOST; } else { bool dcbx_agent_status; int status; if (ice_get_pfc_mode(pf) == ICE_QOS_MODE_DSCP) { clear_bit(ICE_FLAG_FW_LLDP_AGENT, pf->flags); dev_err(dev, "QoS in L3 DSCP mode, FW Agent not allowed to start\n"); ret = -EOPNOTSUPP; goto ethtool_exit; } /* Remove rule to direct LLDP packets to default VSI. * The FW LLDP engine will now be consuming them. */ ice_cfg_sw_lldp(vsi, false, false); /* AQ command to start FW LLDP agent will return an * error if the agent is already started */ status = ice_aq_start_lldp(&pf->hw, true, NULL); if (status) dev_warn(dev, "Fail to start LLDP Agent\n"); /* AQ command to start FW DCBX agent will fail if * the agent is already started */ status = ice_aq_start_stop_dcbx(&pf->hw, true, &dcbx_agent_status, NULL); if (status) dev_dbg(dev, "Failed to start FW DCBX\n"); dev_info(dev, "FW DCBX agent is %s\n", dcbx_agent_status ? "ACTIVE" : "DISABLED"); /* Failure to configure MIB change or init DCB is not * relevant to ethtool. Print notification that * registration/init failed but do not return error * state to ethtool */ status = ice_init_pf_dcb(pf, true); if (status) dev_dbg(dev, "Fail to init DCB\n"); /* Register for MIB change events */ status = ice_cfg_lldp_mib_change(&pf->hw, true); if (status) dev_dbg(dev, "Fail to enable MIB change events\n"); pf->dcbx_cap &= ~DCB_CAP_DCBX_HOST; pf->dcbx_cap |= DCB_CAP_DCBX_LLD_MANAGED; ice_nway_reset(netdev); } } if (test_bit(ICE_FLAG_LEGACY_RX, change_flags)) { /* down and up VSI so that changes of Rx cfg are reflected. */ ice_down_up(vsi); } /* don't allow modification of this flag when a single VF is in * promiscuous mode because it's not supported */ if (test_bit(ICE_FLAG_VF_TRUE_PROMISC_ENA, change_flags) && ice_is_any_vf_in_unicast_promisc(pf)) { dev_err(dev, "Changing vf-true-promisc-support flag while VF(s) are in promiscuous mode not supported\n"); /* toggle bit back to previous state */ change_bit(ICE_FLAG_VF_TRUE_PROMISC_ENA, pf->flags); ret = -EAGAIN; } if (test_bit(ICE_FLAG_VF_VLAN_PRUNING, change_flags) && ice_has_vfs(pf)) { dev_err(dev, "vf-vlan-pruning: VLAN pruning cannot be changed while VFs are active.\n"); /* toggle bit back to previous state */ change_bit(ICE_FLAG_VF_VLAN_PRUNING, pf->flags); ret = -EOPNOTSUPP; } ethtool_exit: clear_bit(ICE_FLAG_ETHTOOL_CTXT, pf->flags); return ret; } static int ice_get_sset_count(struct net_device *netdev, int sset) { switch (sset) { case ETH_SS_STATS: /* The number (and order) of strings reported *must* remain * constant for a given netdevice. This function must not * report a different number based on run time parameters * (such as the number of queues in use, or the setting of * a private ethtool flag). This is due to the nature of the * ethtool stats API. * * Userspace programs such as ethtool must make 3 separate * ioctl requests, one for size, one for the strings, and * finally one for the stats. Since these cross into * userspace, changes to the number or size could result in * undefined memory access or incorrect string<->value * correlations for statistics. * * Even if it appears to be safe, changes to the size or * order of strings will suffer from race conditions and are * not safe. */ return ICE_ALL_STATS_LEN(netdev); case ETH_SS_TEST: return ICE_TEST_LEN; case ETH_SS_PRIV_FLAGS: return ICE_PRIV_FLAG_ARRAY_SIZE; default: return -EOPNOTSUPP; } } static void __ice_get_ethtool_stats(struct net_device *netdev, struct ethtool_stats __always_unused *stats, u64 *data, struct ice_vsi *vsi) { struct ice_pf *pf = vsi->back; struct ice_tx_ring *tx_ring; struct ice_rx_ring *rx_ring; unsigned int j; int i = 0; char *p; ice_update_pf_stats(pf); ice_update_vsi_stats(vsi); for (j = 0; j < ICE_VSI_STATS_LEN; j++) { p = (char *)vsi + ice_gstrings_vsi_stats[j].stat_offset; data[i++] = (ice_gstrings_vsi_stats[j].sizeof_stat == sizeof(u64)) ? *(u64 *)p : *(u32 *)p; } if (ice_is_port_repr_netdev(netdev)) return; /* populate per queue stats */ rcu_read_lock(); ice_for_each_alloc_txq(vsi, j) { tx_ring = READ_ONCE(vsi->tx_rings[j]); if (tx_ring && tx_ring->ring_stats) { data[i++] = tx_ring->ring_stats->stats.pkts; data[i++] = tx_ring->ring_stats->stats.bytes; } else { data[i++] = 0; data[i++] = 0; } } ice_for_each_alloc_rxq(vsi, j) { rx_ring = READ_ONCE(vsi->rx_rings[j]); if (rx_ring && rx_ring->ring_stats) { data[i++] = rx_ring->ring_stats->stats.pkts; data[i++] = rx_ring->ring_stats->stats.bytes; } else { data[i++] = 0; data[i++] = 0; } } rcu_read_unlock(); if (vsi->type != ICE_VSI_PF) return; for (j = 0; j < ICE_PF_STATS_LEN; j++) { p = (char *)pf + ice_gstrings_pf_stats[j].stat_offset; data[i++] = (ice_gstrings_pf_stats[j].sizeof_stat == sizeof(u64)) ? *(u64 *)p : *(u32 *)p; } for (j = 0; j < ICE_MAX_USER_PRIORITY; j++) { data[i++] = pf->stats.priority_xon_tx[j]; data[i++] = pf->stats.priority_xoff_tx[j]; } for (j = 0; j < ICE_MAX_USER_PRIORITY; j++) { data[i++] = pf->stats.priority_xon_rx[j]; data[i++] = pf->stats.priority_xoff_rx[j]; } } static void ice_get_ethtool_stats(struct net_device *netdev, struct ethtool_stats __always_unused *stats, u64 *data) { struct ice_netdev_priv *np = netdev_priv(netdev); __ice_get_ethtool_stats(netdev, stats, data, np->vsi); } #define ICE_PHY_TYPE_LOW_MASK_MIN_1G (ICE_PHY_TYPE_LOW_100BASE_TX | \ ICE_PHY_TYPE_LOW_100M_SGMII) #define ICE_PHY_TYPE_LOW_MASK_MIN_25G (ICE_PHY_TYPE_LOW_MASK_MIN_1G | \ ICE_PHY_TYPE_LOW_1000BASE_T | \ ICE_PHY_TYPE_LOW_1000BASE_SX | \ ICE_PHY_TYPE_LOW_1000BASE_LX | \ ICE_PHY_TYPE_LOW_1000BASE_KX | \ ICE_PHY_TYPE_LOW_1G_SGMII | \ ICE_PHY_TYPE_LOW_2500BASE_T | \ ICE_PHY_TYPE_LOW_2500BASE_X | \ ICE_PHY_TYPE_LOW_2500BASE_KX | \ ICE_PHY_TYPE_LOW_5GBASE_T | \ ICE_PHY_TYPE_LOW_5GBASE_KR | \ ICE_PHY_TYPE_LOW_10GBASE_T | \ ICE_PHY_TYPE_LOW_10G_SFI_DA | \ ICE_PHY_TYPE_LOW_10GBASE_SR | \ ICE_PHY_TYPE_LOW_10GBASE_LR | \ ICE_PHY_TYPE_LOW_10GBASE_KR_CR1 | \ ICE_PHY_TYPE_LOW_10G_SFI_AOC_ACC | \ ICE_PHY_TYPE_LOW_10G_SFI_C2C) #define ICE_PHY_TYPE_LOW_MASK_100G (ICE_PHY_TYPE_LOW_100GBASE_CR4 | \ ICE_PHY_TYPE_LOW_100GBASE_SR4 | \ ICE_PHY_TYPE_LOW_100GBASE_LR4 | \ ICE_PHY_TYPE_LOW_100GBASE_KR4 | \ ICE_PHY_TYPE_LOW_100G_CAUI4_AOC_ACC | \ ICE_PHY_TYPE_LOW_100G_CAUI4 | \ ICE_PHY_TYPE_LOW_100G_AUI4_AOC_ACC | \ ICE_PHY_TYPE_LOW_100G_AUI4 | \ ICE_PHY_TYPE_LOW_100GBASE_CR_PAM4 | \ ICE_PHY_TYPE_LOW_100GBASE_KR_PAM4 | \ ICE_PHY_TYPE_LOW_100GBASE_CP2 | \ ICE_PHY_TYPE_LOW_100GBASE_SR2 | \ ICE_PHY_TYPE_LOW_100GBASE_DR) #define ICE_PHY_TYPE_HIGH_MASK_100G (ICE_PHY_TYPE_HIGH_100GBASE_KR2_PAM4 | \ ICE_PHY_TYPE_HIGH_100G_CAUI2_AOC_ACC |\ ICE_PHY_TYPE_HIGH_100G_CAUI2 | \ ICE_PHY_TYPE_HIGH_100G_AUI2_AOC_ACC | \ ICE_PHY_TYPE_HIGH_100G_AUI2) /** * ice_mask_min_supported_speeds * @hw: pointer to the HW structure * @phy_types_high: PHY type high * @phy_types_low: PHY type low to apply minimum supported speeds mask * * Apply minimum supported speeds mask to PHY type low. These are the speeds * for ethtool supported link mode. */ static void ice_mask_min_supported_speeds(struct ice_hw *hw, u64 phy_types_high, u64 *phy_types_low) { /* if QSFP connection with 100G speed, minimum supported speed is 25G */ if (*phy_types_low & ICE_PHY_TYPE_LOW_MASK_100G || phy_types_high & ICE_PHY_TYPE_HIGH_MASK_100G) *phy_types_low &= ~ICE_PHY_TYPE_LOW_MASK_MIN_25G; else if (!ice_is_100m_speed_supported(hw)) *phy_types_low &= ~ICE_PHY_TYPE_LOW_MASK_MIN_1G; } /** * ice_linkmode_set_bit - set link mode bit * @phy_to_ethtool: PHY type to ethtool link mode struct to set * @ks: ethtool link ksettings struct to fill out * @req_speeds: speed requested by user * @advert_phy_type: advertised PHY type * @phy_type: PHY type */ static void ice_linkmode_set_bit(const struct ice_phy_type_to_ethtool *phy_to_ethtool, struct ethtool_link_ksettings *ks, u32 req_speeds, u64 advert_phy_type, u32 phy_type) { linkmode_set_bit(phy_to_ethtool->link_mode, ks->link_modes.supported); if (req_speeds & phy_to_ethtool->aq_link_speed || (!req_speeds && advert_phy_type & BIT(phy_type))) linkmode_set_bit(phy_to_ethtool->link_mode, ks->link_modes.advertising); } /** * ice_phy_type_to_ethtool - convert the phy_types to ethtool link modes * @netdev: network interface device structure * @ks: ethtool link ksettings struct to fill out */ static void ice_phy_type_to_ethtool(struct net_device *netdev, struct ethtool_link_ksettings *ks) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; struct ice_pf *pf = vsi->back; u64 advert_phy_type_lo = 0; u64 advert_phy_type_hi = 0; u64 phy_types_high = 0; u64 phy_types_low = 0; u32 req_speeds; u32 i; req_speeds = vsi->port_info->phy.link_info.req_speeds; /* Check if lenient mode is supported and enabled, or in strict mode. * * In lenient mode the Supported link modes are the PHY types without * media. The Advertising link mode is either 1. the user requested * speed, 2. the override PHY mask, or 3. the PHY types with media. * * In strict mode Supported link mode are the PHY type with media, * and Advertising link modes are the media PHY type or the speed * requested by user. */ if (test_bit(ICE_FLAG_LINK_LENIENT_MODE_ENA, pf->flags)) { phy_types_low = le64_to_cpu(pf->nvm_phy_type_lo); phy_types_high = le64_to_cpu(pf->nvm_phy_type_hi); ice_mask_min_supported_speeds(&pf->hw, phy_types_high, &phy_types_low); /* determine advertised modes based on link override only * if it's supported and if the FW doesn't abstract the * driver from having to account for link overrides */ if (ice_fw_supports_link_override(&pf->hw) && !ice_fw_supports_report_dflt_cfg(&pf->hw)) { struct ice_link_default_override_tlv *ldo; ldo = &pf->link_dflt_override; /* If override enabled and PHY mask set, then * Advertising link mode is the intersection of the PHY * types without media and the override PHY mask. */ if (ldo->options & ICE_LINK_OVERRIDE_EN && (ldo->phy_type_low || ldo->phy_type_high)) { advert_phy_type_lo = le64_to_cpu(pf->nvm_phy_type_lo) & ldo->phy_type_low; advert_phy_type_hi = le64_to_cpu(pf->nvm_phy_type_hi) & ldo->phy_type_high; } } } else { /* strict mode */ phy_types_low = vsi->port_info->phy.phy_type_low; phy_types_high = vsi->port_info->phy.phy_type_high; } /* If Advertising link mode PHY type is not using override PHY type, * then use PHY type with media. */ if (!advert_phy_type_lo && !advert_phy_type_hi) { advert_phy_type_lo = vsi->port_info->phy.phy_type_low; advert_phy_type_hi = vsi->port_info->phy.phy_type_high; } linkmode_zero(ks->link_modes.supported); linkmode_zero(ks->link_modes.advertising); for (i = 0; i < BITS_PER_TYPE(u64); i++) { if (phy_types_low & BIT_ULL(i)) ice_linkmode_set_bit(&phy_type_low_lkup[i], ks, req_speeds, advert_phy_type_lo, i); } for (i = 0; i < BITS_PER_TYPE(u64); i++) { if (phy_types_high & BIT_ULL(i)) ice_linkmode_set_bit(&phy_type_high_lkup[i], ks, req_speeds, advert_phy_type_hi, i); } } #define TEST_SET_BITS_TIMEOUT 50 #define TEST_SET_BITS_SLEEP_MAX 2000 #define TEST_SET_BITS_SLEEP_MIN 1000 /** * ice_get_settings_link_up - Get Link settings for when link is up * @ks: ethtool ksettings to fill in * @netdev: network interface device structure */ static void ice_get_settings_link_up(struct ethtool_link_ksettings *ks, struct net_device *netdev) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_port_info *pi = np->vsi->port_info; struct ice_link_status *link_info; struct ice_vsi *vsi = np->vsi; link_info = &vsi->port_info->phy.link_info; /* Get supported and advertised settings from PHY ability with media */ ice_phy_type_to_ethtool(netdev, ks); switch (link_info->link_speed) { case ICE_AQ_LINK_SPEED_100GB: ks->base.speed = SPEED_100000; break; case ICE_AQ_LINK_SPEED_50GB: ks->base.speed = SPEED_50000; break; case ICE_AQ_LINK_SPEED_40GB: ks->base.speed = SPEED_40000; break; case ICE_AQ_LINK_SPEED_25GB: ks->base.speed = SPEED_25000; break; case ICE_AQ_LINK_SPEED_20GB: ks->base.speed = SPEED_20000; break; case ICE_AQ_LINK_SPEED_10GB: ks->base.speed = SPEED_10000; break; case ICE_AQ_LINK_SPEED_5GB: ks->base.speed = SPEED_5000; break; case ICE_AQ_LINK_SPEED_2500MB: ks->base.speed = SPEED_2500; break; case ICE_AQ_LINK_SPEED_1000MB: ks->base.speed = SPEED_1000; break; case ICE_AQ_LINK_SPEED_100MB: ks->base.speed = SPEED_100; break; default: netdev_info(netdev, "WARNING: Unrecognized link_speed (0x%x).\n", link_info->link_speed); break; } ks->base.duplex = DUPLEX_FULL; if (link_info->an_info & ICE_AQ_AN_COMPLETED) ethtool_link_ksettings_add_link_mode(ks, lp_advertising, Autoneg); /* Set flow control negotiated Rx/Tx pause */ switch (pi->fc.current_mode) { case ICE_FC_FULL: ethtool_link_ksettings_add_link_mode(ks, lp_advertising, Pause); break; case ICE_FC_TX_PAUSE: ethtool_link_ksettings_add_link_mode(ks, lp_advertising, Pause); ethtool_link_ksettings_add_link_mode(ks, lp_advertising, Asym_Pause); break; case ICE_FC_RX_PAUSE: ethtool_link_ksettings_add_link_mode(ks, lp_advertising, Asym_Pause); break; case ICE_FC_PFC: default: ethtool_link_ksettings_del_link_mode(ks, lp_advertising, Pause); ethtool_link_ksettings_del_link_mode(ks, lp_advertising, Asym_Pause); break; } } /** * ice_get_settings_link_down - Get the Link settings when link is down * @ks: ethtool ksettings to fill in * @netdev: network interface device structure * * Reports link settings that can be determined when link is down */ static void ice_get_settings_link_down(struct ethtool_link_ksettings *ks, struct net_device *netdev) { /* link is down and the driver needs to fall back on * supported PHY types to figure out what info to display */ ice_phy_type_to_ethtool(netdev, ks); /* With no link, speed and duplex are unknown */ ks->base.speed = SPEED_UNKNOWN; ks->base.duplex = DUPLEX_UNKNOWN; } /** * ice_get_link_ksettings - Get Link Speed and Duplex settings * @netdev: network interface device structure * @ks: ethtool ksettings * * Reports speed/duplex settings based on media_type */ static int ice_get_link_ksettings(struct net_device *netdev, struct ethtool_link_ksettings *ks) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_aqc_get_phy_caps_data *caps; struct ice_link_status *hw_link_info; struct ice_vsi *vsi = np->vsi; int err; ethtool_link_ksettings_zero_link_mode(ks, supported); ethtool_link_ksettings_zero_link_mode(ks, advertising); ethtool_link_ksettings_zero_link_mode(ks, lp_advertising); hw_link_info = &vsi->port_info->phy.link_info; /* set speed and duplex */ if (hw_link_info->link_info & ICE_AQ_LINK_UP) ice_get_settings_link_up(ks, netdev); else ice_get_settings_link_down(ks, netdev); /* set autoneg settings */ ks->base.autoneg = (hw_link_info->an_info & ICE_AQ_AN_COMPLETED) ? AUTONEG_ENABLE : AUTONEG_DISABLE; /* set media type settings */ switch (vsi->port_info->phy.media_type) { case ICE_MEDIA_FIBER: ethtool_link_ksettings_add_link_mode(ks, supported, FIBRE); ks->base.port = PORT_FIBRE; break; case ICE_MEDIA_BASET: ethtool_link_ksettings_add_link_mode(ks, supported, TP); ethtool_link_ksettings_add_link_mode(ks, advertising, TP); ks->base.port = PORT_TP; break; case ICE_MEDIA_BACKPLANE: ethtool_link_ksettings_add_link_mode(ks, supported, Backplane); ethtool_link_ksettings_add_link_mode(ks, advertising, Backplane); ks->base.port = PORT_NONE; break; case ICE_MEDIA_DA: ethtool_link_ksettings_add_link_mode(ks, supported, FIBRE); ethtool_link_ksettings_add_link_mode(ks, advertising, FIBRE); ks->base.port = PORT_DA; break; default: ks->base.port = PORT_OTHER; break; } /* flow control is symmetric and always supported */ ethtool_link_ksettings_add_link_mode(ks, supported, Pause); caps = kzalloc(sizeof(*caps), GFP_KERNEL); if (!caps) return -ENOMEM; err = ice_aq_get_phy_caps(vsi->port_info, false, ICE_AQC_REPORT_ACTIVE_CFG, caps, NULL); if (err) goto done; /* Set the advertised flow control based on the PHY capability */ if ((caps->caps & ICE_AQC_PHY_EN_TX_LINK_PAUSE) && (caps->caps & ICE_AQC_PHY_EN_RX_LINK_PAUSE)) { ethtool_link_ksettings_add_link_mode(ks, advertising, Pause); ethtool_link_ksettings_add_link_mode(ks, advertising, Asym_Pause); } else if (caps->caps & ICE_AQC_PHY_EN_TX_LINK_PAUSE) { ethtool_link_ksettings_add_link_mode(ks, advertising, Asym_Pause); } else if (caps->caps & ICE_AQC_PHY_EN_RX_LINK_PAUSE) { ethtool_link_ksettings_add_link_mode(ks, advertising, Pause); ethtool_link_ksettings_add_link_mode(ks, advertising, Asym_Pause); } else { ethtool_link_ksettings_del_link_mode(ks, advertising, Pause); ethtool_link_ksettings_del_link_mode(ks, advertising, Asym_Pause); } /* Set advertised FEC modes based on PHY capability */ ethtool_link_ksettings_add_link_mode(ks, advertising, FEC_NONE); if (caps->link_fec_options & ICE_AQC_PHY_FEC_10G_KR_40G_KR4_REQ || caps->link_fec_options & ICE_AQC_PHY_FEC_25G_KR_REQ) ethtool_link_ksettings_add_link_mode(ks, advertising, FEC_BASER); if (caps->link_fec_options & ICE_AQC_PHY_FEC_25G_RS_528_REQ || caps->link_fec_options & ICE_AQC_PHY_FEC_25G_RS_544_REQ) ethtool_link_ksettings_add_link_mode(ks, advertising, FEC_RS); err = ice_aq_get_phy_caps(vsi->port_info, false, ICE_AQC_REPORT_TOPO_CAP_MEDIA, caps, NULL); if (err) goto done; /* Set supported FEC modes based on PHY capability */ ethtool_link_ksettings_add_link_mode(ks, supported, FEC_NONE); if (caps->link_fec_options & ICE_AQC_PHY_FEC_10G_KR_40G_KR4_EN || caps->link_fec_options & ICE_AQC_PHY_FEC_25G_KR_CLAUSE74_EN) ethtool_link_ksettings_add_link_mode(ks, supported, FEC_BASER); if (caps->link_fec_options & ICE_AQC_PHY_FEC_25G_RS_CLAUSE91_EN) ethtool_link_ksettings_add_link_mode(ks, supported, FEC_RS); /* Set supported and advertised autoneg */ if (ice_is_phy_caps_an_enabled(caps)) { ethtool_link_ksettings_add_link_mode(ks, supported, Autoneg); ethtool_link_ksettings_add_link_mode(ks, advertising, Autoneg); } done: kfree(caps); return err; } /** * ice_ksettings_find_adv_link_speed - Find advertising link speed * @ks: ethtool ksettings */ static u16 ice_ksettings_find_adv_link_speed(const struct ethtool_link_ksettings *ks) { u16 adv_link_speed = 0; if (ethtool_link_ksettings_test_link_mode(ks, advertising, 100baseT_Full)) adv_link_speed |= ICE_AQ_LINK_SPEED_100MB; if (ethtool_link_ksettings_test_link_mode(ks, advertising, 1000baseX_Full) || ethtool_link_ksettings_test_link_mode(ks, advertising, 1000baseT_Full) || ethtool_link_ksettings_test_link_mode(ks, advertising, 1000baseKX_Full)) adv_link_speed |= ICE_AQ_LINK_SPEED_1000MB; if (ethtool_link_ksettings_test_link_mode(ks, advertising, 2500baseT_Full) || ethtool_link_ksettings_test_link_mode(ks, advertising, 2500baseX_Full)) adv_link_speed |= ICE_AQ_LINK_SPEED_2500MB; if (ethtool_link_ksettings_test_link_mode(ks, advertising, 5000baseT_Full)) adv_link_speed |= ICE_AQ_LINK_SPEED_5GB; if (ethtool_link_ksettings_test_link_mode(ks, advertising, 10000baseT_Full) || ethtool_link_ksettings_test_link_mode(ks, advertising, 10000baseKR_Full) || ethtool_link_ksettings_test_link_mode(ks, advertising, 10000baseSR_Full) || ethtool_link_ksettings_test_link_mode(ks, advertising, 10000baseLR_Full)) adv_link_speed |= ICE_AQ_LINK_SPEED_10GB; if (ethtool_link_ksettings_test_link_mode(ks, advertising, 25000baseCR_Full) || ethtool_link_ksettings_test_link_mode(ks, advertising, 25000baseSR_Full) || ethtool_link_ksettings_test_link_mode(ks, advertising, 25000baseKR_Full)) adv_link_speed |= ICE_AQ_LINK_SPEED_25GB; if (ethtool_link_ksettings_test_link_mode(ks, advertising, 40000baseCR4_Full) || ethtool_link_ksettings_test_link_mode(ks, advertising, 40000baseSR4_Full) || ethtool_link_ksettings_test_link_mode(ks, advertising, 40000baseLR4_Full) || ethtool_link_ksettings_test_link_mode(ks, advertising, 40000baseKR4_Full)) adv_link_speed |= ICE_AQ_LINK_SPEED_40GB; if (ethtool_link_ksettings_test_link_mode(ks, advertising, 50000baseCR2_Full) || ethtool_link_ksettings_test_link_mode(ks, advertising, 50000baseKR2_Full) || ethtool_link_ksettings_test_link_mode(ks, advertising, 50000baseSR2_Full)) adv_link_speed |= ICE_AQ_LINK_SPEED_50GB; if (ethtool_link_ksettings_test_link_mode(ks, advertising, 100000baseCR4_Full) || ethtool_link_ksettings_test_link_mode(ks, advertising, 100000baseSR4_Full) || ethtool_link_ksettings_test_link_mode(ks, advertising, 100000baseLR4_ER4_Full) || ethtool_link_ksettings_test_link_mode(ks, advertising, 100000baseKR4_Full) || ethtool_link_ksettings_test_link_mode(ks, advertising, 100000baseCR2_Full) || ethtool_link_ksettings_test_link_mode(ks, advertising, 100000baseSR2_Full) || ethtool_link_ksettings_test_link_mode(ks, advertising, 100000baseKR2_Full)) adv_link_speed |= ICE_AQ_LINK_SPEED_100GB; return adv_link_speed; } /** * ice_setup_autoneg * @p: port info * @ks: ethtool_link_ksettings * @config: configuration that will be sent down to FW * @autoneg_enabled: autonegotiation is enabled or not * @autoneg_changed: will there a change in autonegotiation * @netdev: network interface device structure * * Setup PHY autonegotiation feature */ static int ice_setup_autoneg(struct ice_port_info *p, struct ethtool_link_ksettings *ks, struct ice_aqc_set_phy_cfg_data *config, u8 autoneg_enabled, u8 *autoneg_changed, struct net_device *netdev) { int err = 0; *autoneg_changed = 0; /* Check autoneg */ if (autoneg_enabled == AUTONEG_ENABLE) { /* If autoneg was not already enabled */ if (!(p->phy.link_info.an_info & ICE_AQ_AN_COMPLETED)) { /* If autoneg is not supported, return error */ if (!ethtool_link_ksettings_test_link_mode(ks, supported, Autoneg)) { netdev_info(netdev, "Autoneg not supported on this phy.\n"); err = -EINVAL; } else { /* Autoneg is allowed to change */ config->caps |= ICE_AQ_PHY_ENA_AUTO_LINK_UPDT; *autoneg_changed = 1; } } } else { /* If autoneg is currently enabled */ if (p->phy.link_info.an_info & ICE_AQ_AN_COMPLETED) { /* If autoneg is supported 10GBASE_T is the only PHY * that can disable it, so otherwise return error */ if (ethtool_link_ksettings_test_link_mode(ks, supported, Autoneg)) { netdev_info(netdev, "Autoneg cannot be disabled on this phy\n"); err = -EINVAL; } else { /* Autoneg is allowed to change */ config->caps &= ~ICE_AQ_PHY_ENA_AUTO_LINK_UPDT; *autoneg_changed = 1; } } } return err; } /** * ice_set_phy_type_from_speed - set phy_types based on speeds * and advertised modes * @ks: ethtool link ksettings struct * @phy_type_low: pointer to the lower part of phy_type * @phy_type_high: pointer to the higher part of phy_type * @adv_link_speed: targeted link speeds bitmap */ static void ice_set_phy_type_from_speed(const struct ethtool_link_ksettings *ks, u64 *phy_type_low, u64 *phy_type_high, u16 adv_link_speed) { /* Handle 1000M speed in a special way because ice_update_phy_type * enables all link modes, but having mixed copper and optical * standards is not supported. */ adv_link_speed &= ~ICE_AQ_LINK_SPEED_1000MB; if (ethtool_link_ksettings_test_link_mode(ks, advertising, 1000baseT_Full)) *phy_type_low |= ICE_PHY_TYPE_LOW_1000BASE_T | ICE_PHY_TYPE_LOW_1G_SGMII; if (ethtool_link_ksettings_test_link_mode(ks, advertising, 1000baseKX_Full)) *phy_type_low |= ICE_PHY_TYPE_LOW_1000BASE_KX; if (ethtool_link_ksettings_test_link_mode(ks, advertising, 1000baseX_Full)) *phy_type_low |= ICE_PHY_TYPE_LOW_1000BASE_SX | ICE_PHY_TYPE_LOW_1000BASE_LX; ice_update_phy_type(phy_type_low, phy_type_high, adv_link_speed); } /** * ice_set_link_ksettings - Set Speed and Duplex * @netdev: network interface device structure * @ks: ethtool ksettings * * Set speed/duplex per media_types advertised/forced */ static int ice_set_link_ksettings(struct net_device *netdev, const struct ethtool_link_ksettings *ks) { struct ice_netdev_priv *np = netdev_priv(netdev); u8 autoneg, timeout = TEST_SET_BITS_TIMEOUT; struct ethtool_link_ksettings copy_ks = *ks; struct ethtool_link_ksettings safe_ks = {}; struct ice_aqc_get_phy_caps_data *phy_caps; struct ice_aqc_set_phy_cfg_data config; u16 adv_link_speed, curr_link_speed; struct ice_pf *pf = np->vsi->back; struct ice_port_info *pi; u8 autoneg_changed = 0; u64 phy_type_high = 0; u64 phy_type_low = 0; bool linkup; int err; pi = np->vsi->port_info; if (!pi) return -EIO; if (pi->phy.media_type != ICE_MEDIA_BASET && pi->phy.media_type != ICE_MEDIA_FIBER && pi->phy.media_type != ICE_MEDIA_BACKPLANE && pi->phy.media_type != ICE_MEDIA_DA && pi->phy.link_info.link_info & ICE_AQ_LINK_UP) return -EOPNOTSUPP; phy_caps = kzalloc(sizeof(*phy_caps), GFP_KERNEL); if (!phy_caps) return -ENOMEM; /* Get the PHY capabilities based on media */ if (ice_fw_supports_report_dflt_cfg(pi->hw)) err = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_DFLT_CFG, phy_caps, NULL); else err = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_TOPO_CAP_MEDIA, phy_caps, NULL); if (err) goto done; /* save autoneg out of ksettings */ autoneg = copy_ks.base.autoneg; /* Get link modes supported by hardware.*/ ice_phy_type_to_ethtool(netdev, &safe_ks); /* and check against modes requested by user. * Return an error if unsupported mode was set. */ if (!bitmap_subset(copy_ks.link_modes.advertising, safe_ks.link_modes.supported, __ETHTOOL_LINK_MODE_MASK_NBITS)) { if (!test_bit(ICE_FLAG_LINK_LENIENT_MODE_ENA, pf->flags)) netdev_info(netdev, "The selected speed is not supported by the current media. Please select a link speed that is supported by the current media.\n"); err = -EOPNOTSUPP; goto done; } /* get our own copy of the bits to check against */ memset(&safe_ks, 0, sizeof(safe_ks)); safe_ks.base.cmd = copy_ks.base.cmd; safe_ks.base.link_mode_masks_nwords = copy_ks.base.link_mode_masks_nwords; ice_get_link_ksettings(netdev, &safe_ks); /* set autoneg back to what it currently is */ copy_ks.base.autoneg = safe_ks.base.autoneg; /* we don't compare the speed */ copy_ks.base.speed = safe_ks.base.speed; /* If copy_ks.base and safe_ks.base are not the same now, then they are * trying to set something that we do not support. */ if (memcmp(&copy_ks.base, &safe_ks.base, sizeof(copy_ks.base))) { err = -EOPNOTSUPP; goto done; } while (test_and_set_bit(ICE_CFG_BUSY, pf->state)) { timeout--; if (!timeout) { err = -EBUSY; goto done; } usleep_range(TEST_SET_BITS_SLEEP_MIN, TEST_SET_BITS_SLEEP_MAX); } /* Copy the current user PHY configuration. The current user PHY * configuration is initialized during probe from PHY capabilities * software mode, and updated on set PHY configuration. */ config = pi->phy.curr_user_phy_cfg; config.caps |= ICE_AQ_PHY_ENA_AUTO_LINK_UPDT; /* Check autoneg */ err = ice_setup_autoneg(pi, &safe_ks, &config, autoneg, &autoneg_changed, netdev); if (err) goto done; /* Call to get the current link speed */ pi->phy.get_link_info = true; err = ice_get_link_status(pi, &linkup); if (err) goto done; curr_link_speed = pi->phy.curr_user_speed_req; adv_link_speed = ice_ksettings_find_adv_link_speed(ks); /* If speed didn't get set, set it to what it currently is. * This is needed because if advertise is 0 (as it is when autoneg * is disabled) then speed won't get set. */ if (!adv_link_speed) adv_link_speed = curr_link_speed; /* Convert the advertise link speeds to their corresponded PHY_TYPE */ ice_set_phy_type_from_speed(ks, &phy_type_low, &phy_type_high, adv_link_speed); if (!autoneg_changed && adv_link_speed == curr_link_speed) { netdev_info(netdev, "Nothing changed, exiting without setting anything.\n"); goto done; } /* save the requested speeds */ pi->phy.link_info.req_speeds = adv_link_speed; /* set link and auto negotiation so changes take effect */ config.caps |= ICE_AQ_PHY_ENA_LINK; /* check if there is a PHY type for the requested advertised speed */ if (!(phy_type_low || phy_type_high)) { netdev_info(netdev, "The selected speed is not supported by the current media. Please select a link speed that is supported by the current media.\n"); err = -EOPNOTSUPP; goto done; } /* intersect requested advertised speed PHY types with media PHY types * for set PHY configuration */ config.phy_type_high = cpu_to_le64(phy_type_high) & phy_caps->phy_type_high; config.phy_type_low = cpu_to_le64(phy_type_low) & phy_caps->phy_type_low; if (!(config.phy_type_high || config.phy_type_low)) { /* If there is no intersection and lenient mode is enabled, then * intersect the requested advertised speed with NVM media type * PHY types. */ if (test_bit(ICE_FLAG_LINK_LENIENT_MODE_ENA, pf->flags)) { config.phy_type_high = cpu_to_le64(phy_type_high) & pf->nvm_phy_type_hi; config.phy_type_low = cpu_to_le64(phy_type_low) & pf->nvm_phy_type_lo; } else { netdev_info(netdev, "The selected speed is not supported by the current media. Please select a link speed that is supported by the current media.\n"); err = -EOPNOTSUPP; goto done; } } /* If link is up put link down */ if (pi->phy.link_info.link_info & ICE_AQ_LINK_UP) { /* Tell the OS link is going down, the link will go * back up when fw says it is ready asynchronously */ ice_print_link_msg(np->vsi, false); netif_carrier_off(netdev); netif_tx_stop_all_queues(netdev); } /* make the aq call */ err = ice_aq_set_phy_cfg(&pf->hw, pi, &config, NULL); if (err) { netdev_info(netdev, "Set phy config failed,\n"); goto done; } /* Save speed request */ pi->phy.curr_user_speed_req = adv_link_speed; done: kfree(phy_caps); clear_bit(ICE_CFG_BUSY, pf->state); return err; } /** * ice_parse_hdrs - parses headers from RSS hash input * @nfc: ethtool rxnfc command * * This function parses the rxnfc command and returns intended * header types for RSS configuration */ static u32 ice_parse_hdrs(struct ethtool_rxnfc *nfc) { u32 hdrs = ICE_FLOW_SEG_HDR_NONE; switch (nfc->flow_type) { case TCP_V4_FLOW: hdrs |= ICE_FLOW_SEG_HDR_TCP | ICE_FLOW_SEG_HDR_IPV4; break; case UDP_V4_FLOW: hdrs |= ICE_FLOW_SEG_HDR_UDP | ICE_FLOW_SEG_HDR_IPV4; break; case SCTP_V4_FLOW: hdrs |= ICE_FLOW_SEG_HDR_SCTP | ICE_FLOW_SEG_HDR_IPV4; break; case TCP_V6_FLOW: hdrs |= ICE_FLOW_SEG_HDR_TCP | ICE_FLOW_SEG_HDR_IPV6; break; case UDP_V6_FLOW: hdrs |= ICE_FLOW_SEG_HDR_UDP | ICE_FLOW_SEG_HDR_IPV6; break; case SCTP_V6_FLOW: hdrs |= ICE_FLOW_SEG_HDR_SCTP | ICE_FLOW_SEG_HDR_IPV6; break; default: break; } return hdrs; } #define ICE_FLOW_HASH_FLD_IPV4_SA BIT_ULL(ICE_FLOW_FIELD_IDX_IPV4_SA) #define ICE_FLOW_HASH_FLD_IPV6_SA BIT_ULL(ICE_FLOW_FIELD_IDX_IPV6_SA) #define ICE_FLOW_HASH_FLD_IPV4_DA BIT_ULL(ICE_FLOW_FIELD_IDX_IPV4_DA) #define ICE_FLOW_HASH_FLD_IPV6_DA BIT_ULL(ICE_FLOW_FIELD_IDX_IPV6_DA) #define ICE_FLOW_HASH_FLD_TCP_SRC_PORT BIT_ULL(ICE_FLOW_FIELD_IDX_TCP_SRC_PORT) #define ICE_FLOW_HASH_FLD_TCP_DST_PORT BIT_ULL(ICE_FLOW_FIELD_IDX_TCP_DST_PORT) #define ICE_FLOW_HASH_FLD_UDP_SRC_PORT BIT_ULL(ICE_FLOW_FIELD_IDX_UDP_SRC_PORT) #define ICE_FLOW_HASH_FLD_UDP_DST_PORT BIT_ULL(ICE_FLOW_FIELD_IDX_UDP_DST_PORT) #define ICE_FLOW_HASH_FLD_SCTP_SRC_PORT \ BIT_ULL(ICE_FLOW_FIELD_IDX_SCTP_SRC_PORT) #define ICE_FLOW_HASH_FLD_SCTP_DST_PORT \ BIT_ULL(ICE_FLOW_FIELD_IDX_SCTP_DST_PORT) /** * ice_parse_hash_flds - parses hash fields from RSS hash input * @nfc: ethtool rxnfc command * * This function parses the rxnfc command and returns intended * hash fields for RSS configuration */ static u64 ice_parse_hash_flds(struct ethtool_rxnfc *nfc) { u64 hfld = ICE_HASH_INVALID; if (nfc->data & RXH_IP_SRC || nfc->data & RXH_IP_DST) { switch (nfc->flow_type) { case TCP_V4_FLOW: case UDP_V4_FLOW: case SCTP_V4_FLOW: if (nfc->data & RXH_IP_SRC) hfld |= ICE_FLOW_HASH_FLD_IPV4_SA; if (nfc->data & RXH_IP_DST) hfld |= ICE_FLOW_HASH_FLD_IPV4_DA; break; case TCP_V6_FLOW: case UDP_V6_FLOW: case SCTP_V6_FLOW: if (nfc->data & RXH_IP_SRC) hfld |= ICE_FLOW_HASH_FLD_IPV6_SA; if (nfc->data & RXH_IP_DST) hfld |= ICE_FLOW_HASH_FLD_IPV6_DA; break; default: break; } } if (nfc->data & RXH_L4_B_0_1 || nfc->data & RXH_L4_B_2_3) { switch (nfc->flow_type) { case TCP_V4_FLOW: case TCP_V6_FLOW: if (nfc->data & RXH_L4_B_0_1) hfld |= ICE_FLOW_HASH_FLD_TCP_SRC_PORT; if (nfc->data & RXH_L4_B_2_3) hfld |= ICE_FLOW_HASH_FLD_TCP_DST_PORT; break; case UDP_V4_FLOW: case UDP_V6_FLOW: if (nfc->data & RXH_L4_B_0_1) hfld |= ICE_FLOW_HASH_FLD_UDP_SRC_PORT; if (nfc->data & RXH_L4_B_2_3) hfld |= ICE_FLOW_HASH_FLD_UDP_DST_PORT; break; case SCTP_V4_FLOW: case SCTP_V6_FLOW: if (nfc->data & RXH_L4_B_0_1) hfld |= ICE_FLOW_HASH_FLD_SCTP_SRC_PORT; if (nfc->data & RXH_L4_B_2_3) hfld |= ICE_FLOW_HASH_FLD_SCTP_DST_PORT; break; default: break; } } return hfld; } /** * ice_set_rss_hash_opt - Enable/Disable flow types for RSS hash * @vsi: the VSI being configured * @nfc: ethtool rxnfc command * * Returns Success if the flow input set is supported. */ static int ice_set_rss_hash_opt(struct ice_vsi *vsi, struct ethtool_rxnfc *nfc) { struct ice_pf *pf = vsi->back; struct device *dev; u64 hashed_flds; int status; u32 hdrs; dev = ice_pf_to_dev(pf); if (ice_is_safe_mode(pf)) { dev_dbg(dev, "Advanced RSS disabled. Package download failed, vsi num = %d\n", vsi->vsi_num); return -EINVAL; } hashed_flds = ice_parse_hash_flds(nfc); if (hashed_flds == ICE_HASH_INVALID) { dev_dbg(dev, "Invalid hash fields, vsi num = %d\n", vsi->vsi_num); return -EINVAL; } hdrs = ice_parse_hdrs(nfc); if (hdrs == ICE_FLOW_SEG_HDR_NONE) { dev_dbg(dev, "Header type is not valid, vsi num = %d\n", vsi->vsi_num); return -EINVAL; } status = ice_add_rss_cfg(&pf->hw, vsi->idx, hashed_flds, hdrs); if (status) { dev_dbg(dev, "ice_add_rss_cfg failed, vsi num = %d, error = %d\n", vsi->vsi_num, status); return status; } return 0; } /** * ice_get_rss_hash_opt - Retrieve hash fields for a given flow-type * @vsi: the VSI being configured * @nfc: ethtool rxnfc command */ static void ice_get_rss_hash_opt(struct ice_vsi *vsi, struct ethtool_rxnfc *nfc) { struct ice_pf *pf = vsi->back; struct device *dev; u64 hash_flds; u32 hdrs; dev = ice_pf_to_dev(pf); nfc->data = 0; if (ice_is_safe_mode(pf)) { dev_dbg(dev, "Advanced RSS disabled. Package download failed, vsi num = %d\n", vsi->vsi_num); return; } hdrs = ice_parse_hdrs(nfc); if (hdrs == ICE_FLOW_SEG_HDR_NONE) { dev_dbg(dev, "Header type is not valid, vsi num = %d\n", vsi->vsi_num); return; } hash_flds = ice_get_rss_cfg(&pf->hw, vsi->idx, hdrs); if (hash_flds == ICE_HASH_INVALID) { dev_dbg(dev, "No hash fields found for the given header type, vsi num = %d\n", vsi->vsi_num); return; } if (hash_flds & ICE_FLOW_HASH_FLD_IPV4_SA || hash_flds & ICE_FLOW_HASH_FLD_IPV6_SA) nfc->data |= (u64)RXH_IP_SRC; if (hash_flds & ICE_FLOW_HASH_FLD_IPV4_DA || hash_flds & ICE_FLOW_HASH_FLD_IPV6_DA) nfc->data |= (u64)RXH_IP_DST; if (hash_flds & ICE_FLOW_HASH_FLD_TCP_SRC_PORT || hash_flds & ICE_FLOW_HASH_FLD_UDP_SRC_PORT || hash_flds & ICE_FLOW_HASH_FLD_SCTP_SRC_PORT) nfc->data |= (u64)RXH_L4_B_0_1; if (hash_flds & ICE_FLOW_HASH_FLD_TCP_DST_PORT || hash_flds & ICE_FLOW_HASH_FLD_UDP_DST_PORT || hash_flds & ICE_FLOW_HASH_FLD_SCTP_DST_PORT) nfc->data |= (u64)RXH_L4_B_2_3; } /** * ice_set_rxnfc - command to set Rx flow rules. * @netdev: network interface device structure * @cmd: ethtool rxnfc command * * Returns 0 for success and negative values for errors */ static int ice_set_rxnfc(struct net_device *netdev, struct ethtool_rxnfc *cmd) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; switch (cmd->cmd) { case ETHTOOL_SRXCLSRLINS: return ice_add_fdir_ethtool(vsi, cmd); case ETHTOOL_SRXCLSRLDEL: return ice_del_fdir_ethtool(vsi, cmd); case ETHTOOL_SRXFH: return ice_set_rss_hash_opt(vsi, cmd); default: break; } return -EOPNOTSUPP; } /** * ice_get_rxnfc - command to get Rx flow classification rules * @netdev: network interface device structure * @cmd: ethtool rxnfc command * @rule_locs: buffer to rturn Rx flow classification rules * * Returns Success if the command is supported. */ static int ice_get_rxnfc(struct net_device *netdev, struct ethtool_rxnfc *cmd, u32 __always_unused *rule_locs) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; int ret = -EOPNOTSUPP; struct ice_hw *hw; hw = &vsi->back->hw; switch (cmd->cmd) { case ETHTOOL_GRXRINGS: cmd->data = vsi->rss_size; ret = 0; break; case ETHTOOL_GRXCLSRLCNT: cmd->rule_cnt = hw->fdir_active_fltr; /* report total rule count */ cmd->data = ice_get_fdir_cnt_all(hw); ret = 0; break; case ETHTOOL_GRXCLSRULE: ret = ice_get_ethtool_fdir_entry(hw, cmd); break; case ETHTOOL_GRXCLSRLALL: ret = ice_get_fdir_fltr_ids(hw, cmd, (u32 *)rule_locs); break; case ETHTOOL_GRXFH: ice_get_rss_hash_opt(vsi, cmd); ret = 0; break; default: break; } return ret; } static void ice_get_ringparam(struct net_device *netdev, struct ethtool_ringparam *ring, struct kernel_ethtool_ringparam *kernel_ring, struct netlink_ext_ack *extack) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; ring->rx_max_pending = ICE_MAX_NUM_DESC; ring->tx_max_pending = ICE_MAX_NUM_DESC; if (vsi->tx_rings && vsi->rx_rings) { ring->rx_pending = vsi->rx_rings[0]->count; ring->tx_pending = vsi->tx_rings[0]->count; } else { ring->rx_pending = 0; ring->tx_pending = 0; } /* Rx mini and jumbo rings are not supported */ ring->rx_mini_max_pending = 0; ring->rx_jumbo_max_pending = 0; ring->rx_mini_pending = 0; ring->rx_jumbo_pending = 0; } static int ice_set_ringparam(struct net_device *netdev, struct ethtool_ringparam *ring, struct kernel_ethtool_ringparam *kernel_ring, struct netlink_ext_ack *extack) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_tx_ring *xdp_rings = NULL; struct ice_tx_ring *tx_rings = NULL; struct ice_rx_ring *rx_rings = NULL; struct ice_vsi *vsi = np->vsi; struct ice_pf *pf = vsi->back; int i, timeout = 50, err = 0; u16 new_rx_cnt, new_tx_cnt; if (ring->tx_pending > ICE_MAX_NUM_DESC || ring->tx_pending < ICE_MIN_NUM_DESC || ring->rx_pending > ICE_MAX_NUM_DESC || ring->rx_pending < ICE_MIN_NUM_DESC) { netdev_err(netdev, "Descriptors requested (Tx: %d / Rx: %d) out of range [%d-%d] (increment %d)\n", ring->tx_pending, ring->rx_pending, ICE_MIN_NUM_DESC, ICE_MAX_NUM_DESC, ICE_REQ_DESC_MULTIPLE); return -EINVAL; } /* Return if there is no rings (device is reloading) */ if (!vsi->tx_rings || !vsi->rx_rings) return -EBUSY; new_tx_cnt = ALIGN(ring->tx_pending, ICE_REQ_DESC_MULTIPLE); if (new_tx_cnt != ring->tx_pending) netdev_info(netdev, "Requested Tx descriptor count rounded up to %d\n", new_tx_cnt); new_rx_cnt = ALIGN(ring->rx_pending, ICE_REQ_DESC_MULTIPLE); if (new_rx_cnt != ring->rx_pending) netdev_info(netdev, "Requested Rx descriptor count rounded up to %d\n", new_rx_cnt); /* if nothing to do return success */ if (new_tx_cnt == vsi->tx_rings[0]->count && new_rx_cnt == vsi->rx_rings[0]->count) { netdev_dbg(netdev, "Nothing to change, descriptor count is same as requested\n"); return 0; } /* If there is a AF_XDP UMEM attached to any of Rx rings, * disallow changing the number of descriptors -- regardless * if the netdev is running or not. */ if (ice_xsk_any_rx_ring_ena(vsi)) return -EBUSY; while (test_and_set_bit(ICE_CFG_BUSY, pf->state)) { timeout--; if (!timeout) return -EBUSY; usleep_range(1000, 2000); } /* set for the next time the netdev is started */ if (!netif_running(vsi->netdev)) { ice_for_each_alloc_txq(vsi, i) vsi->tx_rings[i]->count = new_tx_cnt; ice_for_each_alloc_rxq(vsi, i) vsi->rx_rings[i]->count = new_rx_cnt; if (ice_is_xdp_ena_vsi(vsi)) ice_for_each_xdp_txq(vsi, i) vsi->xdp_rings[i]->count = new_tx_cnt; vsi->num_tx_desc = (u16)new_tx_cnt; vsi->num_rx_desc = (u16)new_rx_cnt; netdev_dbg(netdev, "Link is down, descriptor count change happens when link is brought up\n"); goto done; } if (new_tx_cnt == vsi->tx_rings[0]->count) goto process_rx; /* alloc updated Tx resources */ netdev_info(netdev, "Changing Tx descriptor count from %d to %d\n", vsi->tx_rings[0]->count, new_tx_cnt); tx_rings = kcalloc(vsi->num_txq, sizeof(*tx_rings), GFP_KERNEL); if (!tx_rings) { err = -ENOMEM; goto done; } ice_for_each_txq(vsi, i) { /* clone ring and setup updated count */ tx_rings[i] = *vsi->tx_rings[i]; tx_rings[i].count = new_tx_cnt; tx_rings[i].desc = NULL; tx_rings[i].tx_buf = NULL; tx_rings[i].tx_tstamps = &pf->ptp.port.tx; err = ice_setup_tx_ring(&tx_rings[i]); if (err) { while (i--) ice_clean_tx_ring(&tx_rings[i]); kfree(tx_rings); goto done; } } if (!ice_is_xdp_ena_vsi(vsi)) goto process_rx; /* alloc updated XDP resources */ netdev_info(netdev, "Changing XDP descriptor count from %d to %d\n", vsi->xdp_rings[0]->count, new_tx_cnt); xdp_rings = kcalloc(vsi->num_xdp_txq, sizeof(*xdp_rings), GFP_KERNEL); if (!xdp_rings) { err = -ENOMEM; goto free_tx; } ice_for_each_xdp_txq(vsi, i) { /* clone ring and setup updated count */ xdp_rings[i] = *vsi->xdp_rings[i]; xdp_rings[i].count = new_tx_cnt; xdp_rings[i].desc = NULL; xdp_rings[i].tx_buf = NULL; err = ice_setup_tx_ring(&xdp_rings[i]); if (err) { while (i--) ice_clean_tx_ring(&xdp_rings[i]); kfree(xdp_rings); goto free_tx; } ice_set_ring_xdp(&xdp_rings[i]); } process_rx: if (new_rx_cnt == vsi->rx_rings[0]->count) goto process_link; /* alloc updated Rx resources */ netdev_info(netdev, "Changing Rx descriptor count from %d to %d\n", vsi->rx_rings[0]->count, new_rx_cnt); rx_rings = kcalloc(vsi->num_rxq, sizeof(*rx_rings), GFP_KERNEL); if (!rx_rings) { err = -ENOMEM; goto done; } ice_for_each_rxq(vsi, i) { /* clone ring and setup updated count */ rx_rings[i] = *vsi->rx_rings[i]; rx_rings[i].count = new_rx_cnt; rx_rings[i].cached_phctime = pf->ptp.cached_phc_time; rx_rings[i].desc = NULL; rx_rings[i].rx_buf = NULL; /* this is to allow wr32 to have something to write to * during early allocation of Rx buffers */ rx_rings[i].tail = vsi->back->hw.hw_addr + PRTGEN_STATUS; err = ice_setup_rx_ring(&rx_rings[i]); if (err) goto rx_unwind; /* allocate Rx buffers */ err = ice_alloc_rx_bufs(&rx_rings[i], ICE_RX_DESC_UNUSED(&rx_rings[i])); rx_unwind: if (err) { while (i) { i--; ice_free_rx_ring(&rx_rings[i]); } kfree(rx_rings); err = -ENOMEM; goto free_tx; } } process_link: /* Bring interface down, copy in the new ring info, then restore the * interface. if VSI is up, bring it down and then back up */ if (!test_and_set_bit(ICE_VSI_DOWN, vsi->state)) { ice_down(vsi); if (tx_rings) { ice_for_each_txq(vsi, i) { ice_free_tx_ring(vsi->tx_rings[i]); *vsi->tx_rings[i] = tx_rings[i]; } kfree(tx_rings); } if (rx_rings) { ice_for_each_rxq(vsi, i) { ice_free_rx_ring(vsi->rx_rings[i]); /* copy the real tail offset */ rx_rings[i].tail = vsi->rx_rings[i]->tail; /* this is to fake out the allocation routine * into thinking it has to realloc everything * but the recycling logic will let us re-use * the buffers allocated above */ rx_rings[i].next_to_use = 0; rx_rings[i].next_to_clean = 0; rx_rings[i].next_to_alloc = 0; *vsi->rx_rings[i] = rx_rings[i]; } kfree(rx_rings); } if (xdp_rings) { ice_for_each_xdp_txq(vsi, i) { ice_free_tx_ring(vsi->xdp_rings[i]); *vsi->xdp_rings[i] = xdp_rings[i]; } kfree(xdp_rings); } vsi->num_tx_desc = new_tx_cnt; vsi->num_rx_desc = new_rx_cnt; ice_up(vsi); } goto done; free_tx: /* error cleanup if the Rx allocations failed after getting Tx */ if (tx_rings) { ice_for_each_txq(vsi, i) ice_free_tx_ring(&tx_rings[i]); kfree(tx_rings); } done: clear_bit(ICE_CFG_BUSY, pf->state); return err; } /** * ice_get_pauseparam - Get Flow Control status * @netdev: network interface device structure * @pause: ethernet pause (flow control) parameters * * Get requested flow control status from PHY capability. * If autoneg is true, then ethtool will send the ETHTOOL_GSET ioctl which * is handled by ice_get_link_ksettings. ice_get_link_ksettings will report * the negotiated Rx/Tx pause via lp_advertising. */ static void ice_get_pauseparam(struct net_device *netdev, struct ethtool_pauseparam *pause) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_port_info *pi = np->vsi->port_info; struct ice_aqc_get_phy_caps_data *pcaps; struct ice_dcbx_cfg *dcbx_cfg; int status; /* Initialize pause params */ pause->rx_pause = 0; pause->tx_pause = 0; dcbx_cfg = &pi->qos_cfg.local_dcbx_cfg; pcaps = kzalloc(sizeof(*pcaps), GFP_KERNEL); if (!pcaps) return; /* Get current PHY config */ status = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_ACTIVE_CFG, pcaps, NULL); if (status) goto out; pause->autoneg = ice_is_phy_caps_an_enabled(pcaps) ? AUTONEG_ENABLE : AUTONEG_DISABLE; if (dcbx_cfg->pfc.pfcena) /* PFC enabled so report LFC as off */ goto out; if (pcaps->caps & ICE_AQC_PHY_EN_TX_LINK_PAUSE) pause->tx_pause = 1; if (pcaps->caps & ICE_AQC_PHY_EN_RX_LINK_PAUSE) pause->rx_pause = 1; out: kfree(pcaps); } /** * ice_set_pauseparam - Set Flow Control parameter * @netdev: network interface device structure * @pause: return Tx/Rx flow control status */ static int ice_set_pauseparam(struct net_device *netdev, struct ethtool_pauseparam *pause) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_aqc_get_phy_caps_data *pcaps; struct ice_link_status *hw_link_info; struct ice_pf *pf = np->vsi->back; struct ice_dcbx_cfg *dcbx_cfg; struct ice_vsi *vsi = np->vsi; struct ice_hw *hw = &pf->hw; struct ice_port_info *pi; u8 aq_failures; bool link_up; u32 is_an; int err; pi = vsi->port_info; hw_link_info = &pi->phy.link_info; dcbx_cfg = &pi->qos_cfg.local_dcbx_cfg; link_up = hw_link_info->link_info & ICE_AQ_LINK_UP; /* Changing the port's flow control is not supported if this isn't the * PF VSI */ if (vsi->type != ICE_VSI_PF) { netdev_info(netdev, "Changing flow control parameters only supported for PF VSI\n"); return -EOPNOTSUPP; } /* Get pause param reports configured and negotiated flow control pause * when ETHTOOL_GLINKSETTINGS is defined. Since ETHTOOL_GLINKSETTINGS is * defined get pause param pause->autoneg reports SW configured setting, * so compare pause->autoneg with SW configured to prevent the user from * using set pause param to chance autoneg. */ pcaps = kzalloc(sizeof(*pcaps), GFP_KERNEL); if (!pcaps) return -ENOMEM; /* Get current PHY config */ err = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_ACTIVE_CFG, pcaps, NULL); if (err) { kfree(pcaps); return err; } is_an = ice_is_phy_caps_an_enabled(pcaps) ? AUTONEG_ENABLE : AUTONEG_DISABLE; kfree(pcaps); if (pause->autoneg != is_an) { netdev_info(netdev, "To change autoneg please use: ethtool -s <dev> autoneg <on|off>\n"); return -EOPNOTSUPP; } /* If we have link and don't have autoneg */ if (!test_bit(ICE_DOWN, pf->state) && !(hw_link_info->an_info & ICE_AQ_AN_COMPLETED)) { /* Send message that it might not necessarily work*/ netdev_info(netdev, "Autoneg did not complete so changing settings may not result in an actual change.\n"); } if (dcbx_cfg->pfc.pfcena) { netdev_info(netdev, "Priority flow control enabled. Cannot set link flow control.\n"); return -EOPNOTSUPP; } if (pause->rx_pause && pause->tx_pause) pi->fc.req_mode = ICE_FC_FULL; else if (pause->rx_pause && !pause->tx_pause) pi->fc.req_mode = ICE_FC_RX_PAUSE; else if (!pause->rx_pause && pause->tx_pause) pi->fc.req_mode = ICE_FC_TX_PAUSE; else if (!pause->rx_pause && !pause->tx_pause) pi->fc.req_mode = ICE_FC_NONE; else return -EINVAL; /* Set the FC mode and only restart AN if link is up */ err = ice_set_fc(pi, &aq_failures, link_up); if (aq_failures & ICE_SET_FC_AQ_FAIL_GET) { netdev_info(netdev, "Set fc failed on the get_phy_capabilities call with err %d aq_err %s\n", err, ice_aq_str(hw->adminq.sq_last_status)); err = -EAGAIN; } else if (aq_failures & ICE_SET_FC_AQ_FAIL_SET) { netdev_info(netdev, "Set fc failed on the set_phy_config call with err %d aq_err %s\n", err, ice_aq_str(hw->adminq.sq_last_status)); err = -EAGAIN; } else if (aq_failures & ICE_SET_FC_AQ_FAIL_UPDATE) { netdev_info(netdev, "Set fc failed on the get_link_info call with err %d aq_err %s\n", err, ice_aq_str(hw->adminq.sq_last_status)); err = -EAGAIN; } return err; } /** * ice_get_rxfh_key_size - get the RSS hash key size * @netdev: network interface device structure * * Returns the table size. */ static u32 ice_get_rxfh_key_size(struct net_device __always_unused *netdev) { return ICE_VSIQF_HKEY_ARRAY_SIZE; } /** * ice_get_rxfh_indir_size - get the Rx flow hash indirection table size * @netdev: network interface device structure * * Returns the table size. */ static u32 ice_get_rxfh_indir_size(struct net_device *netdev) { struct ice_netdev_priv *np = netdev_priv(netdev); return np->vsi->rss_table_size; } static int ice_get_rxfh_context(struct net_device *netdev, u32 *indir, u8 *key, u8 *hfunc, u32 rss_context) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; struct ice_pf *pf = vsi->back; u16 qcount, offset; int err, num_tc, i; u8 *lut; if (!test_bit(ICE_FLAG_RSS_ENA, pf->flags)) { netdev_warn(netdev, "RSS is not supported on this VSI!\n"); return -EOPNOTSUPP; } if (rss_context && !ice_is_adq_active(pf)) { netdev_err(netdev, "RSS context cannot be non-zero when ADQ is not configured.\n"); return -EINVAL; } qcount = vsi->mqprio_qopt.qopt.count[rss_context]; offset = vsi->mqprio_qopt.qopt.offset[rss_context]; if (rss_context && ice_is_adq_active(pf)) { num_tc = vsi->mqprio_qopt.qopt.num_tc; if (rss_context >= num_tc) { netdev_err(netdev, "RSS context:%d > num_tc:%d\n", rss_context, num_tc); return -EINVAL; } /* Use channel VSI of given TC */ vsi = vsi->tc_map_vsi[rss_context]; } if (hfunc) *hfunc = ETH_RSS_HASH_TOP; if (!indir) return 0; lut = kzalloc(vsi->rss_table_size, GFP_KERNEL); if (!lut) return -ENOMEM; err = ice_get_rss_key(vsi, key); if (err) goto out; err = ice_get_rss_lut(vsi, lut, vsi->rss_table_size); if (err) goto out; if (ice_is_adq_active(pf)) { for (i = 0; i < vsi->rss_table_size; i++) indir[i] = offset + lut[i] % qcount; goto out; } for (i = 0; i < vsi->rss_table_size; i++) indir[i] = lut[i]; out: kfree(lut); return err; } /** * ice_get_rxfh - get the Rx flow hash indirection table * @netdev: network interface device structure * @indir: indirection table * @key: hash key * @hfunc: hash function * * Reads the indirection table directly from the hardware. */ static int ice_get_rxfh(struct net_device *netdev, u32 *indir, u8 *key, u8 *hfunc) { return ice_get_rxfh_context(netdev, indir, key, hfunc, 0); } /** * ice_set_rxfh - set the Rx flow hash indirection table * @netdev: network interface device structure * @indir: indirection table * @key: hash key * @hfunc: hash function * * Returns -EINVAL if the table specifies an invalid queue ID, otherwise * returns 0 after programming the table. */ static int ice_set_rxfh(struct net_device *netdev, const u32 *indir, const u8 *key, const u8 hfunc) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; struct ice_pf *pf = vsi->back; struct device *dev; int err; dev = ice_pf_to_dev(pf); if (hfunc != ETH_RSS_HASH_NO_CHANGE && hfunc != ETH_RSS_HASH_TOP) return -EOPNOTSUPP; if (!test_bit(ICE_FLAG_RSS_ENA, pf->flags)) { /* RSS not supported return error here */ netdev_warn(netdev, "RSS is not configured on this VSI!\n"); return -EIO; } if (ice_is_adq_active(pf)) { netdev_err(netdev, "Cannot change RSS params with ADQ configured.\n"); return -EOPNOTSUPP; } if (key) { if (!vsi->rss_hkey_user) { vsi->rss_hkey_user = devm_kzalloc(dev, ICE_VSIQF_HKEY_ARRAY_SIZE, GFP_KERNEL); if (!vsi->rss_hkey_user) return -ENOMEM; } memcpy(vsi->rss_hkey_user, key, ICE_VSIQF_HKEY_ARRAY_SIZE); err = ice_set_rss_key(vsi, vsi->rss_hkey_user); if (err) return err; } if (!vsi->rss_lut_user) { vsi->rss_lut_user = devm_kzalloc(dev, vsi->rss_table_size, GFP_KERNEL); if (!vsi->rss_lut_user) return -ENOMEM; } /* Each 32 bits pointed by 'indir' is stored with a lut entry */ if (indir) { int i; for (i = 0; i < vsi->rss_table_size; i++) vsi->rss_lut_user[i] = (u8)(indir[i]); } else { ice_fill_rss_lut(vsi->rss_lut_user, vsi->rss_table_size, vsi->rss_size); } err = ice_set_rss_lut(vsi, vsi->rss_lut_user, vsi->rss_table_size); if (err) return err; return 0; } static int ice_get_ts_info(struct net_device *dev, struct ethtool_ts_info *info) { struct ice_pf *pf = ice_netdev_to_pf(dev); /* only report timestamping if PTP is enabled */ if (!test_bit(ICE_FLAG_PTP, pf->flags)) return ethtool_op_get_ts_info(dev, info); info->so_timestamping = SOF_TIMESTAMPING_TX_SOFTWARE | SOF_TIMESTAMPING_RX_SOFTWARE | SOF_TIMESTAMPING_SOFTWARE | SOF_TIMESTAMPING_TX_HARDWARE | SOF_TIMESTAMPING_RX_HARDWARE | SOF_TIMESTAMPING_RAW_HARDWARE; info->phc_index = ice_get_ptp_clock_index(pf); info->tx_types = BIT(HWTSTAMP_TX_OFF) | BIT(HWTSTAMP_TX_ON); info->rx_filters = BIT(HWTSTAMP_FILTER_NONE) | BIT(HWTSTAMP_FILTER_ALL); return 0; } /** * ice_get_max_txq - return the maximum number of Tx queues for in a PF * @pf: PF structure */ static int ice_get_max_txq(struct ice_pf *pf) { return min3(pf->num_lan_msix, (u16)num_online_cpus(), (u16)pf->hw.func_caps.common_cap.num_txq); } /** * ice_get_max_rxq - return the maximum number of Rx queues for in a PF * @pf: PF structure */ static int ice_get_max_rxq(struct ice_pf *pf) { return min3(pf->num_lan_msix, (u16)num_online_cpus(), (u16)pf->hw.func_caps.common_cap.num_rxq); } /** * ice_get_combined_cnt - return the current number of combined channels * @vsi: PF VSI pointer * * Go through all queue vectors and count ones that have both Rx and Tx ring * attached */ static u32 ice_get_combined_cnt(struct ice_vsi *vsi) { u32 combined = 0; int q_idx; ice_for_each_q_vector(vsi, q_idx) { struct ice_q_vector *q_vector = vsi->q_vectors[q_idx]; if (q_vector->rx.rx_ring && q_vector->tx.tx_ring) combined++; } return combined; } /** * ice_get_channels - get the current and max supported channels * @dev: network interface device structure * @ch: ethtool channel data structure */ static void ice_get_channels(struct net_device *dev, struct ethtool_channels *ch) { struct ice_netdev_priv *np = netdev_priv(dev); struct ice_vsi *vsi = np->vsi; struct ice_pf *pf = vsi->back; /* report maximum channels */ ch->max_rx = ice_get_max_rxq(pf); ch->max_tx = ice_get_max_txq(pf); ch->max_combined = min_t(int, ch->max_rx, ch->max_tx); /* report current channels */ ch->combined_count = ice_get_combined_cnt(vsi); ch->rx_count = vsi->num_rxq - ch->combined_count; ch->tx_count = vsi->num_txq - ch->combined_count; /* report other queues */ ch->other_count = test_bit(ICE_FLAG_FD_ENA, pf->flags) ? 1 : 0; ch->max_other = ch->other_count; } /** * ice_get_valid_rss_size - return valid number of RSS queues * @hw: pointer to the HW structure * @new_size: requested RSS queues */ static int ice_get_valid_rss_size(struct ice_hw *hw, int new_size) { struct ice_hw_common_caps *caps = &hw->func_caps.common_cap; return min_t(int, new_size, BIT(caps->rss_table_entry_width)); } /** * ice_vsi_set_dflt_rss_lut - set default RSS LUT with requested RSS size * @vsi: VSI to reconfigure RSS LUT on * @req_rss_size: requested range of queue numbers for hashing * * Set the VSI's RSS parameters, configure the RSS LUT based on these. */ static int ice_vsi_set_dflt_rss_lut(struct ice_vsi *vsi, int req_rss_size) { struct ice_pf *pf = vsi->back; struct device *dev; struct ice_hw *hw; int err; u8 *lut; dev = ice_pf_to_dev(pf); hw = &pf->hw; if (!req_rss_size) return -EINVAL; lut = kzalloc(vsi->rss_table_size, GFP_KERNEL); if (!lut) return -ENOMEM; /* set RSS LUT parameters */ if (!test_bit(ICE_FLAG_RSS_ENA, pf->flags)) vsi->rss_size = 1; else vsi->rss_size = ice_get_valid_rss_size(hw, req_rss_size); /* create/set RSS LUT */ ice_fill_rss_lut(lut, vsi->rss_table_size, vsi->rss_size); err = ice_set_rss_lut(vsi, lut, vsi->rss_table_size); if (err) dev_err(dev, "Cannot set RSS lut, err %d aq_err %s\n", err, ice_aq_str(hw->adminq.sq_last_status)); kfree(lut); return err; } /** * ice_set_channels - set the number channels * @dev: network interface device structure * @ch: ethtool channel data structure */ static int ice_set_channels(struct net_device *dev, struct ethtool_channels *ch) { struct ice_netdev_priv *np = netdev_priv(dev); struct ice_vsi *vsi = np->vsi; struct ice_pf *pf = vsi->back; int new_rx = 0, new_tx = 0; bool locked = false; u32 curr_combined; int ret = 0; /* do not support changing channels in Safe Mode */ if (ice_is_safe_mode(pf)) { netdev_err(dev, "Changing channel in Safe Mode is not supported\n"); return -EOPNOTSUPP; } /* do not support changing other_count */ if (ch->other_count != (test_bit(ICE_FLAG_FD_ENA, pf->flags) ? 1U : 0U)) return -EINVAL; if (ice_is_adq_active(pf)) { netdev_err(dev, "Cannot set channels with ADQ configured.\n"); return -EOPNOTSUPP; } if (test_bit(ICE_FLAG_FD_ENA, pf->flags) && pf->hw.fdir_active_fltr) { netdev_err(dev, "Cannot set channels when Flow Director filters are active\n"); return -EOPNOTSUPP; } curr_combined = ice_get_combined_cnt(vsi); /* these checks are for cases where user didn't specify a particular * value on cmd line but we get non-zero value anyway via * get_channels(); look at ethtool.c in ethtool repository (the user * space part), particularly, do_schannels() routine */ if (ch->rx_count == vsi->num_rxq - curr_combined) ch->rx_count = 0; if (ch->tx_count == vsi->num_txq - curr_combined) ch->tx_count = 0; if (ch->combined_count == curr_combined) ch->combined_count = 0; if (!(ch->combined_count || (ch->rx_count && ch->tx_count))) { netdev_err(dev, "Please specify at least 1 Rx and 1 Tx channel\n"); return -EINVAL; } new_rx = ch->combined_count + ch->rx_count; new_tx = ch->combined_count + ch->tx_count; if (new_rx < vsi->tc_cfg.numtc) { netdev_err(dev, "Cannot set less Rx channels, than Traffic Classes you have (%u)\n", vsi->tc_cfg.numtc); return -EINVAL; } if (new_tx < vsi->tc_cfg.numtc) { netdev_err(dev, "Cannot set less Tx channels, than Traffic Classes you have (%u)\n", vsi->tc_cfg.numtc); return -EINVAL; } if (new_rx > ice_get_max_rxq(pf)) { netdev_err(dev, "Maximum allowed Rx channels is %d\n", ice_get_max_rxq(pf)); return -EINVAL; } if (new_tx > ice_get_max_txq(pf)) { netdev_err(dev, "Maximum allowed Tx channels is %d\n", ice_get_max_txq(pf)); return -EINVAL; } if (pf->adev) { mutex_lock(&pf->adev_mutex); device_lock(&pf->adev->dev); locked = true; if (pf->adev->dev.driver) { netdev_err(dev, "Cannot change channels when RDMA is active\n"); ret = -EBUSY; goto adev_unlock; } } ice_vsi_recfg_qs(vsi, new_rx, new_tx, locked); if (!netif_is_rxfh_configured(dev)) { ret = ice_vsi_set_dflt_rss_lut(vsi, new_rx); goto adev_unlock; } /* Update rss_size due to change in Rx queues */ vsi->rss_size = ice_get_valid_rss_size(&pf->hw, new_rx); adev_unlock: if (locked) { device_unlock(&pf->adev->dev); mutex_unlock(&pf->adev_mutex); } return ret; } /** * ice_get_wol - get current Wake on LAN configuration * @netdev: network interface device structure * @wol: Ethtool structure to retrieve WoL settings */ static void ice_get_wol(struct net_device *netdev, struct ethtool_wolinfo *wol) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_pf *pf = np->vsi->back; if (np->vsi->type != ICE_VSI_PF) netdev_warn(netdev, "Wake on LAN is not supported on this interface!\n"); /* Get WoL settings based on the HW capability */ if (ice_is_wol_supported(&pf->hw)) { wol->supported = WAKE_MAGIC; wol->wolopts = pf->wol_ena ? WAKE_MAGIC : 0; } else { wol->supported = 0; wol->wolopts = 0; } } /** * ice_set_wol - set Wake on LAN on supported device * @netdev: network interface device structure * @wol: Ethtool structure to set WoL */ static int ice_set_wol(struct net_device *netdev, struct ethtool_wolinfo *wol) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; struct ice_pf *pf = vsi->back; if (vsi->type != ICE_VSI_PF || !ice_is_wol_supported(&pf->hw)) return -EOPNOTSUPP; /* only magic packet is supported */ if (wol->wolopts && wol->wolopts != WAKE_MAGIC) return -EOPNOTSUPP; /* Set WoL only if there is a new value */ if (pf->wol_ena != !!wol->wolopts) { pf->wol_ena = !!wol->wolopts; device_set_wakeup_enable(ice_pf_to_dev(pf), pf->wol_ena); netdev_dbg(netdev, "WoL magic packet %sabled\n", pf->wol_ena ? "en" : "dis"); } return 0; } /** * ice_get_rc_coalesce - get ITR values for specific ring container * @ec: ethtool structure to fill with driver's coalesce settings * @rc: ring container that the ITR values will come from * * Query the device for ice_ring_container specific ITR values. This is * done per ice_ring_container because each q_vector can have 1 or more rings * and all of said ring(s) will have the same ITR values. * * Returns 0 on success, negative otherwise. */ static int ice_get_rc_coalesce(struct ethtool_coalesce *ec, struct ice_ring_container *rc) { if (!rc->rx_ring) return -EINVAL; switch (rc->type) { case ICE_RX_CONTAINER: ec->use_adaptive_rx_coalesce = ITR_IS_DYNAMIC(rc); ec->rx_coalesce_usecs = rc->itr_setting; ec->rx_coalesce_usecs_high = rc->rx_ring->q_vector->intrl; break; case ICE_TX_CONTAINER: ec->use_adaptive_tx_coalesce = ITR_IS_DYNAMIC(rc); ec->tx_coalesce_usecs = rc->itr_setting; break; default: dev_dbg(ice_pf_to_dev(rc->rx_ring->vsi->back), "Invalid c_type %d\n", rc->type); return -EINVAL; } return 0; } /** * ice_get_q_coalesce - get a queue's ITR/INTRL (coalesce) settings * @vsi: VSI associated to the queue for getting ITR/INTRL (coalesce) settings * @ec: coalesce settings to program the device with * @q_num: update ITR/INTRL (coalesce) settings for this queue number/index * * Return 0 on success, and negative under the following conditions: * 1. Getting Tx or Rx ITR/INTRL (coalesce) settings failed. * 2. The q_num passed in is not a valid number/index for Tx and Rx rings. */ static int ice_get_q_coalesce(struct ice_vsi *vsi, struct ethtool_coalesce *ec, int q_num) { if (q_num < vsi->num_rxq && q_num < vsi->num_txq) { if (ice_get_rc_coalesce(ec, &vsi->rx_rings[q_num]->q_vector->rx)) return -EINVAL; if (ice_get_rc_coalesce(ec, &vsi->tx_rings[q_num]->q_vector->tx)) return -EINVAL; } else if (q_num < vsi->num_rxq) { if (ice_get_rc_coalesce(ec, &vsi->rx_rings[q_num]->q_vector->rx)) return -EINVAL; } else if (q_num < vsi->num_txq) { if (ice_get_rc_coalesce(ec, &vsi->tx_rings[q_num]->q_vector->tx)) return -EINVAL; } else { return -EINVAL; } return 0; } /** * __ice_get_coalesce - get ITR/INTRL values for the device * @netdev: pointer to the netdev associated with this query * @ec: ethtool structure to fill with driver's coalesce settings * @q_num: queue number to get the coalesce settings for * * If the caller passes in a negative q_num then we return coalesce settings * based on queue number 0, else use the actual q_num passed in. */ static int __ice_get_coalesce(struct net_device *netdev, struct ethtool_coalesce *ec, int q_num) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; if (q_num < 0) q_num = 0; if (ice_get_q_coalesce(vsi, ec, q_num)) return -EINVAL; return 0; } static int ice_get_coalesce(struct net_device *netdev, struct ethtool_coalesce *ec, struct kernel_ethtool_coalesce *kernel_coal, struct netlink_ext_ack *extack) { return __ice_get_coalesce(netdev, ec, -1); } static int ice_get_per_q_coalesce(struct net_device *netdev, u32 q_num, struct ethtool_coalesce *ec) { return __ice_get_coalesce(netdev, ec, q_num); } /** * ice_set_rc_coalesce - set ITR values for specific ring container * @ec: ethtool structure from user to update ITR settings * @rc: ring container that the ITR values will come from * @vsi: VSI associated to the ring container * * Set specific ITR values. This is done per ice_ring_container because each * q_vector can have 1 or more rings and all of said ring(s) will have the same * ITR values. * * Returns 0 on success, negative otherwise. */ static int ice_set_rc_coalesce(struct ethtool_coalesce *ec, struct ice_ring_container *rc, struct ice_vsi *vsi) { const char *c_type_str = (rc->type == ICE_RX_CONTAINER) ? "rx" : "tx"; u32 use_adaptive_coalesce, coalesce_usecs; struct ice_pf *pf = vsi->back; u16 itr_setting; if (!rc->rx_ring) return -EINVAL; switch (rc->type) { case ICE_RX_CONTAINER: { struct ice_q_vector *q_vector = rc->rx_ring->q_vector; if (ec->rx_coalesce_usecs_high > ICE_MAX_INTRL || (ec->rx_coalesce_usecs_high && ec->rx_coalesce_usecs_high < pf->hw.intrl_gran)) { netdev_info(vsi->netdev, "Invalid value, %s-usecs-high valid values are 0 (disabled), %d-%d\n", c_type_str, pf->hw.intrl_gran, ICE_MAX_INTRL); return -EINVAL; } if (ec->rx_coalesce_usecs_high != q_vector->intrl && (ec->use_adaptive_rx_coalesce || ec->use_adaptive_tx_coalesce)) { netdev_info(vsi->netdev, "Invalid value, %s-usecs-high cannot be changed if adaptive-tx or adaptive-rx is enabled\n", c_type_str); return -EINVAL; } if (ec->rx_coalesce_usecs_high != q_vector->intrl) q_vector->intrl = ec->rx_coalesce_usecs_high; use_adaptive_coalesce = ec->use_adaptive_rx_coalesce; coalesce_usecs = ec->rx_coalesce_usecs; break; } case ICE_TX_CONTAINER: use_adaptive_coalesce = ec->use_adaptive_tx_coalesce; coalesce_usecs = ec->tx_coalesce_usecs; break; default: dev_dbg(ice_pf_to_dev(pf), "Invalid container type %d\n", rc->type); return -EINVAL; } itr_setting = rc->itr_setting; if (coalesce_usecs != itr_setting && use_adaptive_coalesce) { netdev_info(vsi->netdev, "%s interrupt throttling cannot be changed if adaptive-%s is enabled\n", c_type_str, c_type_str); return -EINVAL; } if (coalesce_usecs > ICE_ITR_MAX) { netdev_info(vsi->netdev, "Invalid value, %s-usecs range is 0-%d\n", c_type_str, ICE_ITR_MAX); return -EINVAL; } if (use_adaptive_coalesce) { rc->itr_mode = ITR_DYNAMIC; } else { rc->itr_mode = ITR_STATIC; /* store user facing value how it was set */ rc->itr_setting = coalesce_usecs; /* write the change to the register */ ice_write_itr(rc, coalesce_usecs); /* force writes to take effect immediately, the flush shouldn't * be done in the functions above because the intent is for * them to do lazy writes. */ ice_flush(&pf->hw); } return 0; } /** * ice_set_q_coalesce - set a queue's ITR/INTRL (coalesce) settings * @vsi: VSI associated to the queue that need updating * @ec: coalesce settings to program the device with * @q_num: update ITR/INTRL (coalesce) settings for this queue number/index * * Return 0 on success, and negative under the following conditions: * 1. Setting Tx or Rx ITR/INTRL (coalesce) settings failed. * 2. The q_num passed in is not a valid number/index for Tx and Rx rings. */ static int ice_set_q_coalesce(struct ice_vsi *vsi, struct ethtool_coalesce *ec, int q_num) { if (q_num < vsi->num_rxq && q_num < vsi->num_txq) { if (ice_set_rc_coalesce(ec, &vsi->rx_rings[q_num]->q_vector->rx, vsi)) return -EINVAL; if (ice_set_rc_coalesce(ec, &vsi->tx_rings[q_num]->q_vector->tx, vsi)) return -EINVAL; } else if (q_num < vsi->num_rxq) { if (ice_set_rc_coalesce(ec, &vsi->rx_rings[q_num]->q_vector->rx, vsi)) return -EINVAL; } else if (q_num < vsi->num_txq) { if (ice_set_rc_coalesce(ec, &vsi->tx_rings[q_num]->q_vector->tx, vsi)) return -EINVAL; } else { return -EINVAL; } return 0; } /** * ice_print_if_odd_usecs - print message if user tries to set odd [tx|rx]-usecs * @netdev: netdev used for print * @itr_setting: previous user setting * @use_adaptive_coalesce: if adaptive coalesce is enabled or being enabled * @coalesce_usecs: requested value of [tx|rx]-usecs * @c_type_str: either "rx" or "tx" to match user set field of [tx|rx]-usecs */ static void ice_print_if_odd_usecs(struct net_device *netdev, u16 itr_setting, u32 use_adaptive_coalesce, u32 coalesce_usecs, const char *c_type_str) { if (use_adaptive_coalesce) return; if (itr_setting != coalesce_usecs && (coalesce_usecs % 2)) netdev_info(netdev, "User set %s-usecs to %d, device only supports even values. Rounding down and attempting to set %s-usecs to %d\n", c_type_str, coalesce_usecs, c_type_str, ITR_REG_ALIGN(coalesce_usecs)); } /** * __ice_set_coalesce - set ITR/INTRL values for the device * @netdev: pointer to the netdev associated with this query * @ec: ethtool structure to fill with driver's coalesce settings * @q_num: queue number to get the coalesce settings for * * If the caller passes in a negative q_num then we set the coalesce settings * for all Tx/Rx queues, else use the actual q_num passed in. */ static int __ice_set_coalesce(struct net_device *netdev, struct ethtool_coalesce *ec, int q_num) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; if (q_num < 0) { struct ice_q_vector *q_vector = vsi->q_vectors[0]; int v_idx; if (q_vector) { ice_print_if_odd_usecs(netdev, q_vector->rx.itr_setting, ec->use_adaptive_rx_coalesce, ec->rx_coalesce_usecs, "rx"); ice_print_if_odd_usecs(netdev, q_vector->tx.itr_setting, ec->use_adaptive_tx_coalesce, ec->tx_coalesce_usecs, "tx"); } ice_for_each_q_vector(vsi, v_idx) { /* In some cases if DCB is configured the num_[rx|tx]q * can be less than vsi->num_q_vectors. This check * accounts for that so we don't report a false failure */ if (v_idx >= vsi->num_rxq && v_idx >= vsi->num_txq) goto set_complete; if (ice_set_q_coalesce(vsi, ec, v_idx)) return -EINVAL; ice_set_q_vector_intrl(vsi->q_vectors[v_idx]); } goto set_complete; } if (ice_set_q_coalesce(vsi, ec, q_num)) return -EINVAL; ice_set_q_vector_intrl(vsi->q_vectors[q_num]); set_complete: return 0; } static int ice_set_coalesce(struct net_device *netdev, struct ethtool_coalesce *ec, struct kernel_ethtool_coalesce *kernel_coal, struct netlink_ext_ack *extack) { return __ice_set_coalesce(netdev, ec, -1); } static int ice_set_per_q_coalesce(struct net_device *netdev, u32 q_num, struct ethtool_coalesce *ec) { return __ice_set_coalesce(netdev, ec, q_num); } static void ice_repr_get_drvinfo(struct net_device *netdev, struct ethtool_drvinfo *drvinfo) { struct ice_repr *repr = ice_netdev_to_repr(netdev); if (ice_check_vf_ready_for_cfg(repr->vf)) return; __ice_get_drvinfo(netdev, drvinfo, repr->src_vsi); } static void ice_repr_get_strings(struct net_device *netdev, u32 stringset, u8 *data) { struct ice_repr *repr = ice_netdev_to_repr(netdev); /* for port representors only ETH_SS_STATS is supported */ if (ice_check_vf_ready_for_cfg(repr->vf) || stringset != ETH_SS_STATS) return; __ice_get_strings(netdev, stringset, data, repr->src_vsi); } static void ice_repr_get_ethtool_stats(struct net_device *netdev, struct ethtool_stats __always_unused *stats, u64 *data) { struct ice_repr *repr = ice_netdev_to_repr(netdev); if (ice_check_vf_ready_for_cfg(repr->vf)) return; __ice_get_ethtool_stats(netdev, stats, data, repr->src_vsi); } static int ice_repr_get_sset_count(struct net_device *netdev, int sset) { switch (sset) { case ETH_SS_STATS: return ICE_VSI_STATS_LEN; default: return -EOPNOTSUPP; } } #define ICE_I2C_EEPROM_DEV_ADDR 0xA0 #define ICE_I2C_EEPROM_DEV_ADDR2 0xA2 #define ICE_MODULE_TYPE_SFP 0x03 #define ICE_MODULE_TYPE_QSFP_PLUS 0x0D #define ICE_MODULE_TYPE_QSFP28 0x11 #define ICE_MODULE_SFF_ADDR_MODE 0x04 #define ICE_MODULE_SFF_DIAG_CAPAB 0x40 #define ICE_MODULE_REVISION_ADDR 0x01 #define ICE_MODULE_SFF_8472_COMP 0x5E #define ICE_MODULE_SFF_8472_SWAP 0x5C #define ICE_MODULE_QSFP_MAX_LEN 640 /** * ice_get_module_info - get SFF module type and revision information * @netdev: network interface device structure * @modinfo: module EEPROM size and layout information structure */ static int ice_get_module_info(struct net_device *netdev, struct ethtool_modinfo *modinfo) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; u8 sff8472_comp = 0; u8 sff8472_swap = 0; u8 sff8636_rev = 0; u8 value = 0; int status; status = ice_aq_sff_eeprom(hw, 0, ICE_I2C_EEPROM_DEV_ADDR, 0x00, 0x00, 0, &value, 1, 0, NULL); if (status) return status; switch (value) { case ICE_MODULE_TYPE_SFP: status = ice_aq_sff_eeprom(hw, 0, ICE_I2C_EEPROM_DEV_ADDR, ICE_MODULE_SFF_8472_COMP, 0x00, 0, &sff8472_comp, 1, 0, NULL); if (status) return status; status = ice_aq_sff_eeprom(hw, 0, ICE_I2C_EEPROM_DEV_ADDR, ICE_MODULE_SFF_8472_SWAP, 0x00, 0, &sff8472_swap, 1, 0, NULL); if (status) return status; if (sff8472_swap & ICE_MODULE_SFF_ADDR_MODE) { modinfo->type = ETH_MODULE_SFF_8079; modinfo->eeprom_len = ETH_MODULE_SFF_8079_LEN; } else if (sff8472_comp && (sff8472_swap & ICE_MODULE_SFF_DIAG_CAPAB)) { modinfo->type = ETH_MODULE_SFF_8472; modinfo->eeprom_len = ETH_MODULE_SFF_8472_LEN; } else { modinfo->type = ETH_MODULE_SFF_8079; modinfo->eeprom_len = ETH_MODULE_SFF_8079_LEN; } break; case ICE_MODULE_TYPE_QSFP_PLUS: case ICE_MODULE_TYPE_QSFP28: status = ice_aq_sff_eeprom(hw, 0, ICE_I2C_EEPROM_DEV_ADDR, ICE_MODULE_REVISION_ADDR, 0x00, 0, &sff8636_rev, 1, 0, NULL); if (status) return status; /* Check revision compliance */ if (sff8636_rev > 0x02) { /* Module is SFF-8636 compliant */ modinfo->type = ETH_MODULE_SFF_8636; modinfo->eeprom_len = ICE_MODULE_QSFP_MAX_LEN; } else { modinfo->type = ETH_MODULE_SFF_8436; modinfo->eeprom_len = ICE_MODULE_QSFP_MAX_LEN; } break; default: netdev_warn(netdev, "SFF Module Type not recognized.\n"); return -EINVAL; } return 0; } /** * ice_get_module_eeprom - fill buffer with SFF EEPROM contents * @netdev: network interface device structure * @ee: EEPROM dump request structure * @data: buffer to be filled with EEPROM contents */ static int ice_get_module_eeprom(struct net_device *netdev, struct ethtool_eeprom *ee, u8 *data) { struct ice_netdev_priv *np = netdev_priv(netdev); #define SFF_READ_BLOCK_SIZE 8 u8 value[SFF_READ_BLOCK_SIZE] = { 0 }; u8 addr = ICE_I2C_EEPROM_DEV_ADDR; struct ice_vsi *vsi = np->vsi; struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; bool is_sfp = false; unsigned int i, j; u16 offset = 0; u8 page = 0; int status; if (!ee || !ee->len || !data) return -EINVAL; status = ice_aq_sff_eeprom(hw, 0, addr, offset, page, 0, value, 1, 0, NULL); if (status) return status; if (value[0] == ICE_MODULE_TYPE_SFP) is_sfp = true; memset(data, 0, ee->len); for (i = 0; i < ee->len; i += SFF_READ_BLOCK_SIZE) { offset = i + ee->offset; page = 0; /* Check if we need to access the other memory page */ if (is_sfp) { if (offset >= ETH_MODULE_SFF_8079_LEN) { offset -= ETH_MODULE_SFF_8079_LEN; addr = ICE_I2C_EEPROM_DEV_ADDR2; } } else { while (offset >= ETH_MODULE_SFF_8436_LEN) { /* Compute memory page number and offset. */ offset -= ETH_MODULE_SFF_8436_LEN / 2; page++; } } /* Bit 2 of EEPROM address 0x02 declares upper * pages are disabled on QSFP modules. * SFP modules only ever use page 0. */ if (page == 0 || !(data[0x2] & 0x4)) { u32 copy_len; /* If i2c bus is busy due to slow page change or * link management access, call can fail. This is normal. * So we retry this a few times. */ for (j = 0; j < 4; j++) { status = ice_aq_sff_eeprom(hw, 0, addr, offset, page, !is_sfp, value, SFF_READ_BLOCK_SIZE, 0, NULL); netdev_dbg(netdev, "SFF %02X %02X %02X %X = %02X%02X%02X%02X.%02X%02X%02X%02X (%X)\n", addr, offset, page, is_sfp, value[0], value[1], value[2], value[3], value[4], value[5], value[6], value[7], status); if (status) { usleep_range(1500, 2500); memset(value, 0, SFF_READ_BLOCK_SIZE); continue; } break; } /* Make sure we have enough room for the new block */ copy_len = min_t(u32, SFF_READ_BLOCK_SIZE, ee->len - i); memcpy(data + i, value, copy_len); } } return 0; } static const struct ethtool_ops ice_ethtool_ops = { .supported_coalesce_params = ETHTOOL_COALESCE_USECS | ETHTOOL_COALESCE_USE_ADAPTIVE | ETHTOOL_COALESCE_RX_USECS_HIGH, .get_link_ksettings = ice_get_link_ksettings, .set_link_ksettings = ice_set_link_ksettings, .get_drvinfo = ice_get_drvinfo, .get_regs_len = ice_get_regs_len, .get_regs = ice_get_regs, .get_wol = ice_get_wol, .set_wol = ice_set_wol, .get_msglevel = ice_get_msglevel, .set_msglevel = ice_set_msglevel, .self_test = ice_self_test, .get_link = ethtool_op_get_link, .get_eeprom_len = ice_get_eeprom_len, .get_eeprom = ice_get_eeprom, .get_coalesce = ice_get_coalesce, .set_coalesce = ice_set_coalesce, .get_strings = ice_get_strings, .set_phys_id = ice_set_phys_id, .get_ethtool_stats = ice_get_ethtool_stats, .get_priv_flags = ice_get_priv_flags, .set_priv_flags = ice_set_priv_flags, .get_sset_count = ice_get_sset_count, .get_rxnfc = ice_get_rxnfc, .set_rxnfc = ice_set_rxnfc, .get_ringparam = ice_get_ringparam, .set_ringparam = ice_set_ringparam, .nway_reset = ice_nway_reset, .get_pauseparam = ice_get_pauseparam, .set_pauseparam = ice_set_pauseparam, .get_rxfh_key_size = ice_get_rxfh_key_size, .get_rxfh_indir_size = ice_get_rxfh_indir_size, .get_rxfh_context = ice_get_rxfh_context, .get_rxfh = ice_get_rxfh, .set_rxfh = ice_set_rxfh, .get_channels = ice_get_channels, .set_channels = ice_set_channels, .get_ts_info = ice_get_ts_info, .get_per_queue_coalesce = ice_get_per_q_coalesce, .set_per_queue_coalesce = ice_set_per_q_coalesce, .get_fecparam = ice_get_fecparam, .set_fecparam = ice_set_fecparam, .get_module_info = ice_get_module_info, .get_module_eeprom = ice_get_module_eeprom, }; static const struct ethtool_ops ice_ethtool_safe_mode_ops = { .get_link_ksettings = ice_get_link_ksettings, .set_link_ksettings = ice_set_link_ksettings, .get_drvinfo = ice_get_drvinfo, .get_regs_len = ice_get_regs_len, .get_regs = ice_get_regs, .get_wol = ice_get_wol, .set_wol = ice_set_wol, .get_msglevel = ice_get_msglevel, .set_msglevel = ice_set_msglevel, .get_link = ethtool_op_get_link, .get_eeprom_len = ice_get_eeprom_len, .get_eeprom = ice_get_eeprom, .get_strings = ice_get_strings, .get_ethtool_stats = ice_get_ethtool_stats, .get_sset_count = ice_get_sset_count, .get_ringparam = ice_get_ringparam, .set_ringparam = ice_set_ringparam, .nway_reset = ice_nway_reset, .get_channels = ice_get_channels, }; /** * ice_set_ethtool_safe_mode_ops - setup safe mode ethtool ops * @netdev: network interface device structure */ void ice_set_ethtool_safe_mode_ops(struct net_device *netdev) { netdev->ethtool_ops = &ice_ethtool_safe_mode_ops; } static const struct ethtool_ops ice_ethtool_repr_ops = { .get_drvinfo = ice_repr_get_drvinfo, .get_link = ethtool_op_get_link, .get_strings = ice_repr_get_strings, .get_ethtool_stats = ice_repr_get_ethtool_stats, .get_sset_count = ice_repr_get_sset_count, }; /** * ice_set_ethtool_repr_ops - setup VF's port representor ethtool ops * @netdev: network interface device structure */ void ice_set_ethtool_repr_ops(struct net_device *netdev) { netdev->ethtool_ops = &ice_ethtool_repr_ops; } /** * ice_set_ethtool_ops - setup netdev ethtool ops * @netdev: network interface device structure * * setup netdev ethtool ops with ice specific ops */ void ice_set_ethtool_ops(struct net_device *netdev) { netdev->ethtool_ops = &ice_ethtool_ops; }
linux-master
drivers/net/ethernet/intel/ice/ice_ethtool.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2021, Intel Corporation. */ #include "ice.h" #include "ice_lib.h" #include "ice_trace.h" #define E810_OUT_PROP_DELAY_NS 1 #define UNKNOWN_INCVAL_E822 0x100000000ULL static const struct ptp_pin_desc ice_pin_desc_e810t[] = { /* name idx func chan */ { "GNSS", GNSS, PTP_PF_EXTTS, 0, { 0, } }, { "SMA1", SMA1, PTP_PF_NONE, 1, { 0, } }, { "U.FL1", UFL1, PTP_PF_NONE, 1, { 0, } }, { "SMA2", SMA2, PTP_PF_NONE, 2, { 0, } }, { "U.FL2", UFL2, PTP_PF_NONE, 2, { 0, } }, }; /** * ice_get_sma_config_e810t * @hw: pointer to the hw struct * @ptp_pins: pointer to the ptp_pin_desc struture * * Read the configuration of the SMA control logic and put it into the * ptp_pin_desc structure */ static int ice_get_sma_config_e810t(struct ice_hw *hw, struct ptp_pin_desc *ptp_pins) { u8 data, i; int status; /* Read initial pin state */ status = ice_read_sma_ctrl_e810t(hw, &data); if (status) return status; /* initialize with defaults */ for (i = 0; i < NUM_PTP_PINS_E810T; i++) { snprintf(ptp_pins[i].name, sizeof(ptp_pins[i].name), "%s", ice_pin_desc_e810t[i].name); ptp_pins[i].index = ice_pin_desc_e810t[i].index; ptp_pins[i].func = ice_pin_desc_e810t[i].func; ptp_pins[i].chan = ice_pin_desc_e810t[i].chan; } /* Parse SMA1/UFL1 */ switch (data & ICE_SMA1_MASK_E810T) { case ICE_SMA1_MASK_E810T: default: ptp_pins[SMA1].func = PTP_PF_NONE; ptp_pins[UFL1].func = PTP_PF_NONE; break; case ICE_SMA1_DIR_EN_E810T: ptp_pins[SMA1].func = PTP_PF_PEROUT; ptp_pins[UFL1].func = PTP_PF_NONE; break; case ICE_SMA1_TX_EN_E810T: ptp_pins[SMA1].func = PTP_PF_EXTTS; ptp_pins[UFL1].func = PTP_PF_NONE; break; case 0: ptp_pins[SMA1].func = PTP_PF_EXTTS; ptp_pins[UFL1].func = PTP_PF_PEROUT; break; } /* Parse SMA2/UFL2 */ switch (data & ICE_SMA2_MASK_E810T) { case ICE_SMA2_MASK_E810T: default: ptp_pins[SMA2].func = PTP_PF_NONE; ptp_pins[UFL2].func = PTP_PF_NONE; break; case (ICE_SMA2_TX_EN_E810T | ICE_SMA2_UFL2_RX_DIS_E810T): ptp_pins[SMA2].func = PTP_PF_EXTTS; ptp_pins[UFL2].func = PTP_PF_NONE; break; case (ICE_SMA2_DIR_EN_E810T | ICE_SMA2_UFL2_RX_DIS_E810T): ptp_pins[SMA2].func = PTP_PF_PEROUT; ptp_pins[UFL2].func = PTP_PF_NONE; break; case (ICE_SMA2_DIR_EN_E810T | ICE_SMA2_TX_EN_E810T): ptp_pins[SMA2].func = PTP_PF_NONE; ptp_pins[UFL2].func = PTP_PF_EXTTS; break; case ICE_SMA2_DIR_EN_E810T: ptp_pins[SMA2].func = PTP_PF_PEROUT; ptp_pins[UFL2].func = PTP_PF_EXTTS; break; } return 0; } /** * ice_ptp_set_sma_config_e810t * @hw: pointer to the hw struct * @ptp_pins: pointer to the ptp_pin_desc struture * * Set the configuration of the SMA control logic based on the configuration in * num_pins parameter */ static int ice_ptp_set_sma_config_e810t(struct ice_hw *hw, const struct ptp_pin_desc *ptp_pins) { int status; u8 data; /* SMA1 and UFL1 cannot be set to TX at the same time */ if (ptp_pins[SMA1].func == PTP_PF_PEROUT && ptp_pins[UFL1].func == PTP_PF_PEROUT) return -EINVAL; /* SMA2 and UFL2 cannot be set to RX at the same time */ if (ptp_pins[SMA2].func == PTP_PF_EXTTS && ptp_pins[UFL2].func == PTP_PF_EXTTS) return -EINVAL; /* Read initial pin state value */ status = ice_read_sma_ctrl_e810t(hw, &data); if (status) return status; /* Set the right sate based on the desired configuration */ data &= ~ICE_SMA1_MASK_E810T; if (ptp_pins[SMA1].func == PTP_PF_NONE && ptp_pins[UFL1].func == PTP_PF_NONE) { dev_info(ice_hw_to_dev(hw), "SMA1 + U.FL1 disabled"); data |= ICE_SMA1_MASK_E810T; } else if (ptp_pins[SMA1].func == PTP_PF_EXTTS && ptp_pins[UFL1].func == PTP_PF_NONE) { dev_info(ice_hw_to_dev(hw), "SMA1 RX"); data |= ICE_SMA1_TX_EN_E810T; } else if (ptp_pins[SMA1].func == PTP_PF_NONE && ptp_pins[UFL1].func == PTP_PF_PEROUT) { /* U.FL 1 TX will always enable SMA 1 RX */ dev_info(ice_hw_to_dev(hw), "SMA1 RX + U.FL1 TX"); } else if (ptp_pins[SMA1].func == PTP_PF_EXTTS && ptp_pins[UFL1].func == PTP_PF_PEROUT) { dev_info(ice_hw_to_dev(hw), "SMA1 RX + U.FL1 TX"); } else if (ptp_pins[SMA1].func == PTP_PF_PEROUT && ptp_pins[UFL1].func == PTP_PF_NONE) { dev_info(ice_hw_to_dev(hw), "SMA1 TX"); data |= ICE_SMA1_DIR_EN_E810T; } data &= ~ICE_SMA2_MASK_E810T; if (ptp_pins[SMA2].func == PTP_PF_NONE && ptp_pins[UFL2].func == PTP_PF_NONE) { dev_info(ice_hw_to_dev(hw), "SMA2 + U.FL2 disabled"); data |= ICE_SMA2_MASK_E810T; } else if (ptp_pins[SMA2].func == PTP_PF_EXTTS && ptp_pins[UFL2].func == PTP_PF_NONE) { dev_info(ice_hw_to_dev(hw), "SMA2 RX"); data |= (ICE_SMA2_TX_EN_E810T | ICE_SMA2_UFL2_RX_DIS_E810T); } else if (ptp_pins[SMA2].func == PTP_PF_NONE && ptp_pins[UFL2].func == PTP_PF_EXTTS) { dev_info(ice_hw_to_dev(hw), "UFL2 RX"); data |= (ICE_SMA2_DIR_EN_E810T | ICE_SMA2_TX_EN_E810T); } else if (ptp_pins[SMA2].func == PTP_PF_PEROUT && ptp_pins[UFL2].func == PTP_PF_NONE) { dev_info(ice_hw_to_dev(hw), "SMA2 TX"); data |= (ICE_SMA2_DIR_EN_E810T | ICE_SMA2_UFL2_RX_DIS_E810T); } else if (ptp_pins[SMA2].func == PTP_PF_PEROUT && ptp_pins[UFL2].func == PTP_PF_EXTTS) { dev_info(ice_hw_to_dev(hw), "SMA2 TX + U.FL2 RX"); data |= ICE_SMA2_DIR_EN_E810T; } return ice_write_sma_ctrl_e810t(hw, data); } /** * ice_ptp_set_sma_e810t * @info: the driver's PTP info structure * @pin: pin index in kernel structure * @func: Pin function to be set (PTP_PF_NONE, PTP_PF_EXTTS or PTP_PF_PEROUT) * * Set the configuration of a single SMA pin */ static int ice_ptp_set_sma_e810t(struct ptp_clock_info *info, unsigned int pin, enum ptp_pin_function func) { struct ptp_pin_desc ptp_pins[NUM_PTP_PINS_E810T]; struct ice_pf *pf = ptp_info_to_pf(info); struct ice_hw *hw = &pf->hw; int err; if (pin < SMA1 || func > PTP_PF_PEROUT) return -EOPNOTSUPP; err = ice_get_sma_config_e810t(hw, ptp_pins); if (err) return err; /* Disable the same function on the other pin sharing the channel */ if (pin == SMA1 && ptp_pins[UFL1].func == func) ptp_pins[UFL1].func = PTP_PF_NONE; if (pin == UFL1 && ptp_pins[SMA1].func == func) ptp_pins[SMA1].func = PTP_PF_NONE; if (pin == SMA2 && ptp_pins[UFL2].func == func) ptp_pins[UFL2].func = PTP_PF_NONE; if (pin == UFL2 && ptp_pins[SMA2].func == func) ptp_pins[SMA2].func = PTP_PF_NONE; /* Set up new pin function in the temp table */ ptp_pins[pin].func = func; return ice_ptp_set_sma_config_e810t(hw, ptp_pins); } /** * ice_verify_pin_e810t * @info: the driver's PTP info structure * @pin: Pin index * @func: Assigned function * @chan: Assigned channel * * Verify if pin supports requested pin function. If the Check pins consistency. * Reconfigure the SMA logic attached to the given pin to enable its * desired functionality */ static int ice_verify_pin_e810t(struct ptp_clock_info *info, unsigned int pin, enum ptp_pin_function func, unsigned int chan) { /* Don't allow channel reassignment */ if (chan != ice_pin_desc_e810t[pin].chan) return -EOPNOTSUPP; /* Check if functions are properly assigned */ switch (func) { case PTP_PF_NONE: break; case PTP_PF_EXTTS: if (pin == UFL1) return -EOPNOTSUPP; break; case PTP_PF_PEROUT: if (pin == UFL2 || pin == GNSS) return -EOPNOTSUPP; break; case PTP_PF_PHYSYNC: return -EOPNOTSUPP; } return ice_ptp_set_sma_e810t(info, pin, func); } /** * ice_set_tx_tstamp - Enable or disable Tx timestamping * @pf: The PF pointer to search in * @on: bool value for whether timestamps are enabled or disabled */ static void ice_set_tx_tstamp(struct ice_pf *pf, bool on) { struct ice_vsi *vsi; u32 val; u16 i; vsi = ice_get_main_vsi(pf); if (!vsi) return; /* Set the timestamp enable flag for all the Tx rings */ ice_for_each_txq(vsi, i) { if (!vsi->tx_rings[i]) continue; vsi->tx_rings[i]->ptp_tx = on; } /* Configure the Tx timestamp interrupt */ val = rd32(&pf->hw, PFINT_OICR_ENA); if (on) val |= PFINT_OICR_TSYN_TX_M; else val &= ~PFINT_OICR_TSYN_TX_M; wr32(&pf->hw, PFINT_OICR_ENA, val); pf->ptp.tstamp_config.tx_type = on ? HWTSTAMP_TX_ON : HWTSTAMP_TX_OFF; } /** * ice_set_rx_tstamp - Enable or disable Rx timestamping * @pf: The PF pointer to search in * @on: bool value for whether timestamps are enabled or disabled */ static void ice_set_rx_tstamp(struct ice_pf *pf, bool on) { struct ice_vsi *vsi; u16 i; vsi = ice_get_main_vsi(pf); if (!vsi) return; /* Set the timestamp flag for all the Rx rings */ ice_for_each_rxq(vsi, i) { if (!vsi->rx_rings[i]) continue; vsi->rx_rings[i]->ptp_rx = on; } pf->ptp.tstamp_config.rx_filter = on ? HWTSTAMP_FILTER_ALL : HWTSTAMP_FILTER_NONE; } /** * ice_ptp_cfg_timestamp - Configure timestamp for init/deinit * @pf: Board private structure * @ena: bool value to enable or disable time stamp * * This function will configure timestamping during PTP initialization * and deinitialization */ void ice_ptp_cfg_timestamp(struct ice_pf *pf, bool ena) { ice_set_tx_tstamp(pf, ena); ice_set_rx_tstamp(pf, ena); } /** * ice_get_ptp_clock_index - Get the PTP clock index * @pf: the PF pointer * * Determine the clock index of the PTP clock associated with this device. If * this is the PF controlling the clock, just use the local access to the * clock device pointer. * * Otherwise, read from the driver shared parameters to determine the clock * index value. * * Returns: the index of the PTP clock associated with this device, or -1 if * there is no associated clock. */ int ice_get_ptp_clock_index(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); enum ice_aqc_driver_params param_idx; struct ice_hw *hw = &pf->hw; u8 tmr_idx; u32 value; int err; /* Use the ptp_clock structure if we're the main PF */ if (pf->ptp.clock) return ptp_clock_index(pf->ptp.clock); tmr_idx = hw->func_caps.ts_func_info.tmr_index_assoc; if (!tmr_idx) param_idx = ICE_AQC_DRIVER_PARAM_CLK_IDX_TMR0; else param_idx = ICE_AQC_DRIVER_PARAM_CLK_IDX_TMR1; err = ice_aq_get_driver_param(hw, param_idx, &value, NULL); if (err) { dev_err(dev, "Failed to read PTP clock index parameter, err %d aq_err %s\n", err, ice_aq_str(hw->adminq.sq_last_status)); return -1; } /* The PTP clock index is an integer, and will be between 0 and * INT_MAX. The highest bit of the driver shared parameter is used to * indicate whether or not the currently stored clock index is valid. */ if (!(value & PTP_SHARED_CLK_IDX_VALID)) return -1; return value & ~PTP_SHARED_CLK_IDX_VALID; } /** * ice_set_ptp_clock_index - Set the PTP clock index * @pf: the PF pointer * * Set the PTP clock index for this device into the shared driver parameters, * so that other PFs associated with this device can read it. * * If the PF is unable to store the clock index, it will log an error, but * will continue operating PTP. */ static void ice_set_ptp_clock_index(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); enum ice_aqc_driver_params param_idx; struct ice_hw *hw = &pf->hw; u8 tmr_idx; u32 value; int err; if (!pf->ptp.clock) return; tmr_idx = hw->func_caps.ts_func_info.tmr_index_assoc; if (!tmr_idx) param_idx = ICE_AQC_DRIVER_PARAM_CLK_IDX_TMR0; else param_idx = ICE_AQC_DRIVER_PARAM_CLK_IDX_TMR1; value = (u32)ptp_clock_index(pf->ptp.clock); if (value > INT_MAX) { dev_err(dev, "PTP Clock index is too large to store\n"); return; } value |= PTP_SHARED_CLK_IDX_VALID; err = ice_aq_set_driver_param(hw, param_idx, value, NULL); if (err) { dev_err(dev, "Failed to set PTP clock index parameter, err %d aq_err %s\n", err, ice_aq_str(hw->adminq.sq_last_status)); } } /** * ice_clear_ptp_clock_index - Clear the PTP clock index * @pf: the PF pointer * * Clear the PTP clock index for this device. Must be called when * unregistering the PTP clock, in order to ensure other PFs stop reporting * a clock object that no longer exists. */ static void ice_clear_ptp_clock_index(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); enum ice_aqc_driver_params param_idx; struct ice_hw *hw = &pf->hw; u8 tmr_idx; int err; /* Do not clear the index if we don't own the timer */ if (!hw->func_caps.ts_func_info.src_tmr_owned) return; tmr_idx = hw->func_caps.ts_func_info.tmr_index_assoc; if (!tmr_idx) param_idx = ICE_AQC_DRIVER_PARAM_CLK_IDX_TMR0; else param_idx = ICE_AQC_DRIVER_PARAM_CLK_IDX_TMR1; err = ice_aq_set_driver_param(hw, param_idx, 0, NULL); if (err) { dev_dbg(dev, "Failed to clear PTP clock index parameter, err %d aq_err %s\n", err, ice_aq_str(hw->adminq.sq_last_status)); } } /** * ice_ptp_read_src_clk_reg - Read the source clock register * @pf: Board private structure * @sts: Optional parameter for holding a pair of system timestamps from * the system clock. Will be ignored if NULL is given. */ static u64 ice_ptp_read_src_clk_reg(struct ice_pf *pf, struct ptp_system_timestamp *sts) { struct ice_hw *hw = &pf->hw; u32 hi, lo, lo2; u8 tmr_idx; tmr_idx = ice_get_ptp_src_clock_index(hw); /* Read the system timestamp pre PHC read */ ptp_read_system_prets(sts); lo = rd32(hw, GLTSYN_TIME_L(tmr_idx)); /* Read the system timestamp post PHC read */ ptp_read_system_postts(sts); hi = rd32(hw, GLTSYN_TIME_H(tmr_idx)); lo2 = rd32(hw, GLTSYN_TIME_L(tmr_idx)); if (lo2 < lo) { /* if TIME_L rolled over read TIME_L again and update * system timestamps */ ptp_read_system_prets(sts); lo = rd32(hw, GLTSYN_TIME_L(tmr_idx)); ptp_read_system_postts(sts); hi = rd32(hw, GLTSYN_TIME_H(tmr_idx)); } return ((u64)hi << 32) | lo; } /** * ice_ptp_extend_32b_ts - Convert a 32b nanoseconds timestamp to 64b * @cached_phc_time: recently cached copy of PHC time * @in_tstamp: Ingress/egress 32b nanoseconds timestamp value * * Hardware captures timestamps which contain only 32 bits of nominal * nanoseconds, as opposed to the 64bit timestamps that the stack expects. * Note that the captured timestamp values may be 40 bits, but the lower * 8 bits are sub-nanoseconds and generally discarded. * * Extend the 32bit nanosecond timestamp using the following algorithm and * assumptions: * * 1) have a recently cached copy of the PHC time * 2) assume that the in_tstamp was captured 2^31 nanoseconds (~2.1 * seconds) before or after the PHC time was captured. * 3) calculate the delta between the cached time and the timestamp * 4) if the delta is smaller than 2^31 nanoseconds, then the timestamp was * captured after the PHC time. In this case, the full timestamp is just * the cached PHC time plus the delta. * 5) otherwise, if the delta is larger than 2^31 nanoseconds, then the * timestamp was captured *before* the PHC time, i.e. because the PHC * cache was updated after the timestamp was captured by hardware. In this * case, the full timestamp is the cached time minus the inverse delta. * * This algorithm works even if the PHC time was updated after a Tx timestamp * was requested, but before the Tx timestamp event was reported from * hardware. * * This calculation primarily relies on keeping the cached PHC time up to * date. If the timestamp was captured more than 2^31 nanoseconds after the * PHC time, it is possible that the lower 32bits of PHC time have * overflowed more than once, and we might generate an incorrect timestamp. * * This is prevented by (a) periodically updating the cached PHC time once * a second, and (b) discarding any Tx timestamp packet if it has waited for * a timestamp for more than one second. */ static u64 ice_ptp_extend_32b_ts(u64 cached_phc_time, u32 in_tstamp) { u32 delta, phc_time_lo; u64 ns; /* Extract the lower 32 bits of the PHC time */ phc_time_lo = (u32)cached_phc_time; /* Calculate the delta between the lower 32bits of the cached PHC * time and the in_tstamp value */ delta = (in_tstamp - phc_time_lo); /* Do not assume that the in_tstamp is always more recent than the * cached PHC time. If the delta is large, it indicates that the * in_tstamp was taken in the past, and should be converted * forward. */ if (delta > (U32_MAX / 2)) { /* reverse the delta calculation here */ delta = (phc_time_lo - in_tstamp); ns = cached_phc_time - delta; } else { ns = cached_phc_time + delta; } return ns; } /** * ice_ptp_extend_40b_ts - Convert a 40b timestamp to 64b nanoseconds * @pf: Board private structure * @in_tstamp: Ingress/egress 40b timestamp value * * The Tx and Rx timestamps are 40 bits wide, including 32 bits of nominal * nanoseconds, 7 bits of sub-nanoseconds, and a valid bit. * * *--------------------------------------------------------------* * | 32 bits of nanoseconds | 7 high bits of sub ns underflow | v | * *--------------------------------------------------------------* * * The low bit is an indicator of whether the timestamp is valid. The next * 7 bits are a capture of the upper 7 bits of the sub-nanosecond underflow, * and the remaining 32 bits are the lower 32 bits of the PHC timer. * * It is assumed that the caller verifies the timestamp is valid prior to * calling this function. * * Extract the 32bit nominal nanoseconds and extend them. Use the cached PHC * time stored in the device private PTP structure as the basis for timestamp * extension. * * See ice_ptp_extend_32b_ts for a detailed explanation of the extension * algorithm. */ static u64 ice_ptp_extend_40b_ts(struct ice_pf *pf, u64 in_tstamp) { const u64 mask = GENMASK_ULL(31, 0); unsigned long discard_time; /* Discard the hardware timestamp if the cached PHC time is too old */ discard_time = pf->ptp.cached_phc_jiffies + msecs_to_jiffies(2000); if (time_is_before_jiffies(discard_time)) { pf->ptp.tx_hwtstamp_discarded++; return 0; } return ice_ptp_extend_32b_ts(pf->ptp.cached_phc_time, (in_tstamp >> 8) & mask); } /** * ice_ptp_is_tx_tracker_up - Check if Tx tracker is ready for new timestamps * @tx: the PTP Tx timestamp tracker to check * * Check that a given PTP Tx timestamp tracker is up, i.e. that it is ready * to accept new timestamp requests. * * Assumes the tx->lock spinlock is already held. */ static bool ice_ptp_is_tx_tracker_up(struct ice_ptp_tx *tx) { lockdep_assert_held(&tx->lock); return tx->init && !tx->calibrating; } /** * ice_ptp_process_tx_tstamp - Process Tx timestamps for a port * @tx: the PTP Tx timestamp tracker * * Process timestamps captured by the PHY associated with this port. To do * this, loop over each index with a waiting skb. * * If a given index has a valid timestamp, perform the following steps: * * 1) check that the timestamp request is not stale * 2) check that a timestamp is ready and available in the PHY memory bank * 3) read and copy the timestamp out of the PHY register * 4) unlock the index by clearing the associated in_use bit * 5) check if the timestamp is stale, and discard if so * 6) extend the 40 bit timestamp value to get a 64 bit timestamp value * 7) send this 64 bit timestamp to the stack * * Note that we do not hold the tracking lock while reading the Tx timestamp. * This is because reading the timestamp requires taking a mutex that might * sleep. * * The only place where we set in_use is when a new timestamp is initiated * with a slot index. This is only called in the hard xmit routine where an * SKB has a request flag set. The only places where we clear this bit is this * function, or during teardown when the Tx timestamp tracker is being * removed. A timestamp index will never be re-used until the in_use bit for * that index is cleared. * * If a Tx thread starts a new timestamp, we might not begin processing it * right away but we will notice it at the end when we re-queue the task. * * If a Tx thread starts a new timestamp just after this function exits, the * interrupt for that timestamp should re-trigger this function once * a timestamp is ready. * * In cases where the PTP hardware clock was directly adjusted, some * timestamps may not be able to safely use the timestamp extension math. In * this case, software will set the stale bit for any outstanding Tx * timestamps when the clock is adjusted. Then this function will discard * those captured timestamps instead of sending them to the stack. * * If a Tx packet has been waiting for more than 2 seconds, it is not possible * to correctly extend the timestamp using the cached PHC time. It is * extremely unlikely that a packet will ever take this long to timestamp. If * we detect a Tx timestamp request that has waited for this long we assume * the packet will never be sent by hardware and discard it without reading * the timestamp register. */ static void ice_ptp_process_tx_tstamp(struct ice_ptp_tx *tx) { struct ice_ptp_port *ptp_port; struct ice_pf *pf; struct ice_hw *hw; u64 tstamp_ready; bool link_up; int err; u8 idx; if (!tx->init) return; ptp_port = container_of(tx, struct ice_ptp_port, tx); pf = ptp_port_to_pf(ptp_port); hw = &pf->hw; /* Read the Tx ready status first */ err = ice_get_phy_tx_tstamp_ready(hw, tx->block, &tstamp_ready); if (err) return; /* Drop packets if the link went down */ link_up = ptp_port->link_up; for_each_set_bit(idx, tx->in_use, tx->len) { struct skb_shared_hwtstamps shhwtstamps = {}; u8 phy_idx = idx + tx->offset; u64 raw_tstamp = 0, tstamp; bool drop_ts = !link_up; struct sk_buff *skb; /* Drop packets which have waited for more than 2 seconds */ if (time_is_before_jiffies(tx->tstamps[idx].start + 2 * HZ)) { drop_ts = true; /* Count the number of Tx timestamps that timed out */ pf->ptp.tx_hwtstamp_timeouts++; } /* Only read a timestamp from the PHY if its marked as ready * by the tstamp_ready register. This avoids unnecessary * reading of timestamps which are not yet valid. This is * important as we must read all timestamps which are valid * and only timestamps which are valid during each interrupt. * If we do not, the hardware logic for generating a new * interrupt can get stuck on some devices. */ if (!(tstamp_ready & BIT_ULL(phy_idx))) { if (drop_ts) goto skip_ts_read; continue; } ice_trace(tx_tstamp_fw_req, tx->tstamps[idx].skb, idx); err = ice_read_phy_tstamp(hw, tx->block, phy_idx, &raw_tstamp); if (err && !drop_ts) continue; ice_trace(tx_tstamp_fw_done, tx->tstamps[idx].skb, idx); /* For PHYs which don't implement a proper timestamp ready * bitmap, verify that the timestamp value is different * from the last cached timestamp. If it is not, skip this for * now assuming it hasn't yet been captured by hardware. */ if (!drop_ts && tx->verify_cached && raw_tstamp == tx->tstamps[idx].cached_tstamp) continue; /* Discard any timestamp value without the valid bit set */ if (!(raw_tstamp & ICE_PTP_TS_VALID)) drop_ts = true; skip_ts_read: spin_lock(&tx->lock); if (tx->verify_cached && raw_tstamp) tx->tstamps[idx].cached_tstamp = raw_tstamp; clear_bit(idx, tx->in_use); skb = tx->tstamps[idx].skb; tx->tstamps[idx].skb = NULL; if (test_and_clear_bit(idx, tx->stale)) drop_ts = true; spin_unlock(&tx->lock); /* It is unlikely but possible that the SKB will have been * flushed at this point due to link change or teardown. */ if (!skb) continue; if (drop_ts) { dev_kfree_skb_any(skb); continue; } /* Extend the timestamp using cached PHC time */ tstamp = ice_ptp_extend_40b_ts(pf, raw_tstamp); if (tstamp) { shhwtstamps.hwtstamp = ns_to_ktime(tstamp); ice_trace(tx_tstamp_complete, skb, idx); } skb_tstamp_tx(skb, &shhwtstamps); dev_kfree_skb_any(skb); } } /** * ice_ptp_tx_tstamp - Process Tx timestamps for this function. * @tx: Tx tracking structure to initialize * * Returns: ICE_TX_TSTAMP_WORK_PENDING if there are any outstanding incomplete * Tx timestamps, or ICE_TX_TSTAMP_WORK_DONE otherwise. */ static enum ice_tx_tstamp_work ice_ptp_tx_tstamp(struct ice_ptp_tx *tx) { bool more_timestamps; if (!tx->init) return ICE_TX_TSTAMP_WORK_DONE; /* Process the Tx timestamp tracker */ ice_ptp_process_tx_tstamp(tx); /* Check if there are outstanding Tx timestamps */ spin_lock(&tx->lock); more_timestamps = tx->init && !bitmap_empty(tx->in_use, tx->len); spin_unlock(&tx->lock); if (more_timestamps) return ICE_TX_TSTAMP_WORK_PENDING; return ICE_TX_TSTAMP_WORK_DONE; } /** * ice_ptp_alloc_tx_tracker - Initialize tracking for Tx timestamps * @tx: Tx tracking structure to initialize * * Assumes that the length has already been initialized. Do not call directly, * use the ice_ptp_init_tx_* instead. */ static int ice_ptp_alloc_tx_tracker(struct ice_ptp_tx *tx) { unsigned long *in_use, *stale; struct ice_tx_tstamp *tstamps; tstamps = kcalloc(tx->len, sizeof(*tstamps), GFP_KERNEL); in_use = bitmap_zalloc(tx->len, GFP_KERNEL); stale = bitmap_zalloc(tx->len, GFP_KERNEL); if (!tstamps || !in_use || !stale) { kfree(tstamps); bitmap_free(in_use); bitmap_free(stale); return -ENOMEM; } tx->tstamps = tstamps; tx->in_use = in_use; tx->stale = stale; tx->init = 1; spin_lock_init(&tx->lock); return 0; } /** * ice_ptp_flush_tx_tracker - Flush any remaining timestamps from the tracker * @pf: Board private structure * @tx: the tracker to flush * * Called during teardown when a Tx tracker is being removed. */ static void ice_ptp_flush_tx_tracker(struct ice_pf *pf, struct ice_ptp_tx *tx) { struct ice_hw *hw = &pf->hw; u64 tstamp_ready; int err; u8 idx; err = ice_get_phy_tx_tstamp_ready(hw, tx->block, &tstamp_ready); if (err) { dev_dbg(ice_pf_to_dev(pf), "Failed to get the Tx tstamp ready bitmap for block %u, err %d\n", tx->block, err); /* If we fail to read the Tx timestamp ready bitmap just * skip clearing the PHY timestamps. */ tstamp_ready = 0; } for_each_set_bit(idx, tx->in_use, tx->len) { u8 phy_idx = idx + tx->offset; struct sk_buff *skb; /* In case this timestamp is ready, we need to clear it. */ if (!hw->reset_ongoing && (tstamp_ready & BIT_ULL(phy_idx))) ice_clear_phy_tstamp(hw, tx->block, phy_idx); spin_lock(&tx->lock); skb = tx->tstamps[idx].skb; tx->tstamps[idx].skb = NULL; clear_bit(idx, tx->in_use); clear_bit(idx, tx->stale); spin_unlock(&tx->lock); /* Count the number of Tx timestamps flushed */ pf->ptp.tx_hwtstamp_flushed++; /* Free the SKB after we've cleared the bit */ dev_kfree_skb_any(skb); } } /** * ice_ptp_mark_tx_tracker_stale - Mark unfinished timestamps as stale * @tx: the tracker to mark * * Mark currently outstanding Tx timestamps as stale. This prevents sending * their timestamp value to the stack. This is required to prevent extending * the 40bit hardware timestamp incorrectly. * * This should be called when the PTP clock is modified such as after a set * time request. */ static void ice_ptp_mark_tx_tracker_stale(struct ice_ptp_tx *tx) { spin_lock(&tx->lock); bitmap_or(tx->stale, tx->stale, tx->in_use, tx->len); spin_unlock(&tx->lock); } /** * ice_ptp_release_tx_tracker - Release allocated memory for Tx tracker * @pf: Board private structure * @tx: Tx tracking structure to release * * Free memory associated with the Tx timestamp tracker. */ static void ice_ptp_release_tx_tracker(struct ice_pf *pf, struct ice_ptp_tx *tx) { spin_lock(&tx->lock); tx->init = 0; spin_unlock(&tx->lock); /* wait for potentially outstanding interrupt to complete */ synchronize_irq(pf->oicr_irq.virq); ice_ptp_flush_tx_tracker(pf, tx); kfree(tx->tstamps); tx->tstamps = NULL; bitmap_free(tx->in_use); tx->in_use = NULL; bitmap_free(tx->stale); tx->stale = NULL; tx->len = 0; } /** * ice_ptp_init_tx_e822 - Initialize tracking for Tx timestamps * @pf: Board private structure * @tx: the Tx tracking structure to initialize * @port: the port this structure tracks * * Initialize the Tx timestamp tracker for this port. For generic MAC devices, * the timestamp block is shared for all ports in the same quad. To avoid * ports using the same timestamp index, logically break the block of * registers into chunks based on the port number. */ static int ice_ptp_init_tx_e822(struct ice_pf *pf, struct ice_ptp_tx *tx, u8 port) { tx->block = port / ICE_PORTS_PER_QUAD; tx->offset = (port % ICE_PORTS_PER_QUAD) * INDEX_PER_PORT_E822; tx->len = INDEX_PER_PORT_E822; tx->verify_cached = 0; return ice_ptp_alloc_tx_tracker(tx); } /** * ice_ptp_init_tx_e810 - Initialize tracking for Tx timestamps * @pf: Board private structure * @tx: the Tx tracking structure to initialize * * Initialize the Tx timestamp tracker for this PF. For E810 devices, each * port has its own block of timestamps, independent of the other ports. */ static int ice_ptp_init_tx_e810(struct ice_pf *pf, struct ice_ptp_tx *tx) { tx->block = pf->hw.port_info->lport; tx->offset = 0; tx->len = INDEX_PER_PORT_E810; /* The E810 PHY does not provide a timestamp ready bitmap. Instead, * verify new timestamps against cached copy of the last read * timestamp. */ tx->verify_cached = 1; return ice_ptp_alloc_tx_tracker(tx); } /** * ice_ptp_update_cached_phctime - Update the cached PHC time values * @pf: Board specific private structure * * This function updates the system time values which are cached in the PF * structure and the Rx rings. * * This function must be called periodically to ensure that the cached value * is never more than 2 seconds old. * * Note that the cached copy in the PF PTP structure is always updated, even * if we can't update the copy in the Rx rings. * * Return: * * 0 - OK, successfully updated * * -EAGAIN - PF was busy, need to reschedule the update */ static int ice_ptp_update_cached_phctime(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); unsigned long update_before; u64 systime; int i; update_before = pf->ptp.cached_phc_jiffies + msecs_to_jiffies(2000); if (pf->ptp.cached_phc_time && time_is_before_jiffies(update_before)) { unsigned long time_taken = jiffies - pf->ptp.cached_phc_jiffies; dev_warn(dev, "%u msecs passed between update to cached PHC time\n", jiffies_to_msecs(time_taken)); pf->ptp.late_cached_phc_updates++; } /* Read the current PHC time */ systime = ice_ptp_read_src_clk_reg(pf, NULL); /* Update the cached PHC time stored in the PF structure */ WRITE_ONCE(pf->ptp.cached_phc_time, systime); WRITE_ONCE(pf->ptp.cached_phc_jiffies, jiffies); if (test_and_set_bit(ICE_CFG_BUSY, pf->state)) return -EAGAIN; ice_for_each_vsi(pf, i) { struct ice_vsi *vsi = pf->vsi[i]; int j; if (!vsi) continue; if (vsi->type != ICE_VSI_PF) continue; ice_for_each_rxq(vsi, j) { if (!vsi->rx_rings[j]) continue; WRITE_ONCE(vsi->rx_rings[j]->cached_phctime, systime); } } clear_bit(ICE_CFG_BUSY, pf->state); return 0; } /** * ice_ptp_reset_cached_phctime - Reset cached PHC time after an update * @pf: Board specific private structure * * This function must be called when the cached PHC time is no longer valid, * such as after a time adjustment. It marks any currently outstanding Tx * timestamps as stale and updates the cached PHC time for both the PF and Rx * rings. * * If updating the PHC time cannot be done immediately, a warning message is * logged and the work item is scheduled immediately to minimize the window * with a wrong cached timestamp. */ static void ice_ptp_reset_cached_phctime(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); int err; /* Update the cached PHC time immediately if possible, otherwise * schedule the work item to execute soon. */ err = ice_ptp_update_cached_phctime(pf); if (err) { /* If another thread is updating the Rx rings, we won't * properly reset them here. This could lead to reporting of * invalid timestamps, but there isn't much we can do. */ dev_warn(dev, "%s: ICE_CFG_BUSY, unable to immediately update cached PHC time\n", __func__); /* Queue the work item to update the Rx rings when possible */ kthread_queue_delayed_work(pf->ptp.kworker, &pf->ptp.work, msecs_to_jiffies(10)); } /* Mark any outstanding timestamps as stale, since they might have * been captured in hardware before the time update. This could lead * to us extending them with the wrong cached value resulting in * incorrect timestamp values. */ ice_ptp_mark_tx_tracker_stale(&pf->ptp.port.tx); } /** * ice_ptp_read_time - Read the time from the device * @pf: Board private structure * @ts: timespec structure to hold the current time value * @sts: Optional parameter for holding a pair of system timestamps from * the system clock. Will be ignored if NULL is given. * * This function reads the source clock registers and stores them in a timespec. * However, since the registers are 64 bits of nanoseconds, we must convert the * result to a timespec before we can return. */ static void ice_ptp_read_time(struct ice_pf *pf, struct timespec64 *ts, struct ptp_system_timestamp *sts) { u64 time_ns = ice_ptp_read_src_clk_reg(pf, sts); *ts = ns_to_timespec64(time_ns); } /** * ice_ptp_write_init - Set PHC time to provided value * @pf: Board private structure * @ts: timespec structure that holds the new time value * * Set the PHC time to the specified time provided in the timespec. */ static int ice_ptp_write_init(struct ice_pf *pf, struct timespec64 *ts) { u64 ns = timespec64_to_ns(ts); struct ice_hw *hw = &pf->hw; return ice_ptp_init_time(hw, ns); } /** * ice_ptp_write_adj - Adjust PHC clock time atomically * @pf: Board private structure * @adj: Adjustment in nanoseconds * * Perform an atomic adjustment of the PHC time by the specified number of * nanoseconds. */ static int ice_ptp_write_adj(struct ice_pf *pf, s32 adj) { struct ice_hw *hw = &pf->hw; return ice_ptp_adj_clock(hw, adj); } /** * ice_base_incval - Get base timer increment value * @pf: Board private structure * * Look up the base timer increment value for this device. The base increment * value is used to define the nominal clock tick rate. This increment value * is programmed during device initialization. It is also used as the basis * for calculating adjustments using scaled_ppm. */ static u64 ice_base_incval(struct ice_pf *pf) { struct ice_hw *hw = &pf->hw; u64 incval; if (ice_is_e810(hw)) incval = ICE_PTP_NOMINAL_INCVAL_E810; else if (ice_e822_time_ref(hw) < NUM_ICE_TIME_REF_FREQ) incval = ice_e822_nominal_incval(ice_e822_time_ref(hw)); else incval = UNKNOWN_INCVAL_E822; dev_dbg(ice_pf_to_dev(pf), "PTP: using base increment value of 0x%016llx\n", incval); return incval; } /** * ice_ptp_check_tx_fifo - Check whether Tx FIFO is in an OK state * @port: PTP port for which Tx FIFO is checked */ static int ice_ptp_check_tx_fifo(struct ice_ptp_port *port) { int quad = port->port_num / ICE_PORTS_PER_QUAD; int offs = port->port_num % ICE_PORTS_PER_QUAD; struct ice_pf *pf; struct ice_hw *hw; u32 val, phy_sts; int err; pf = ptp_port_to_pf(port); hw = &pf->hw; if (port->tx_fifo_busy_cnt == FIFO_OK) return 0; /* need to read FIFO state */ if (offs == 0 || offs == 1) err = ice_read_quad_reg_e822(hw, quad, Q_REG_FIFO01_STATUS, &val); else err = ice_read_quad_reg_e822(hw, quad, Q_REG_FIFO23_STATUS, &val); if (err) { dev_err(ice_pf_to_dev(pf), "PTP failed to check port %d Tx FIFO, err %d\n", port->port_num, err); return err; } if (offs & 0x1) phy_sts = (val & Q_REG_FIFO13_M) >> Q_REG_FIFO13_S; else phy_sts = (val & Q_REG_FIFO02_M) >> Q_REG_FIFO02_S; if (phy_sts & FIFO_EMPTY) { port->tx_fifo_busy_cnt = FIFO_OK; return 0; } port->tx_fifo_busy_cnt++; dev_dbg(ice_pf_to_dev(pf), "Try %d, port %d FIFO not empty\n", port->tx_fifo_busy_cnt, port->port_num); if (port->tx_fifo_busy_cnt == ICE_PTP_FIFO_NUM_CHECKS) { dev_dbg(ice_pf_to_dev(pf), "Port %d Tx FIFO still not empty; resetting quad %d\n", port->port_num, quad); ice_ptp_reset_ts_memory_quad_e822(hw, quad); port->tx_fifo_busy_cnt = FIFO_OK; return 0; } return -EAGAIN; } /** * ice_ptp_wait_for_offsets - Check for valid Tx and Rx offsets * @work: Pointer to the kthread_work structure for this task * * Check whether hardware has completed measuring the Tx and Rx offset values * used to configure and enable vernier timestamp calibration. * * Once the offset in either direction is measured, configure the associated * registers with the calibrated offset values and enable timestamping. The Tx * and Rx directions are configured independently as soon as their associated * offsets are known. * * This function reschedules itself until both Tx and Rx calibration have * completed. */ static void ice_ptp_wait_for_offsets(struct kthread_work *work) { struct ice_ptp_port *port; struct ice_pf *pf; struct ice_hw *hw; int tx_err; int rx_err; port = container_of(work, struct ice_ptp_port, ov_work.work); pf = ptp_port_to_pf(port); hw = &pf->hw; if (ice_is_reset_in_progress(pf->state)) { /* wait for device driver to complete reset */ kthread_queue_delayed_work(pf->ptp.kworker, &port->ov_work, msecs_to_jiffies(100)); return; } tx_err = ice_ptp_check_tx_fifo(port); if (!tx_err) tx_err = ice_phy_cfg_tx_offset_e822(hw, port->port_num); rx_err = ice_phy_cfg_rx_offset_e822(hw, port->port_num); if (tx_err || rx_err) { /* Tx and/or Rx offset not yet configured, try again later */ kthread_queue_delayed_work(pf->ptp.kworker, &port->ov_work, msecs_to_jiffies(100)); return; } } /** * ice_ptp_port_phy_stop - Stop timestamping for a PHY port * @ptp_port: PTP port to stop */ static int ice_ptp_port_phy_stop(struct ice_ptp_port *ptp_port) { struct ice_pf *pf = ptp_port_to_pf(ptp_port); u8 port = ptp_port->port_num; struct ice_hw *hw = &pf->hw; int err; if (ice_is_e810(hw)) return 0; mutex_lock(&ptp_port->ps_lock); kthread_cancel_delayed_work_sync(&ptp_port->ov_work); err = ice_stop_phy_timer_e822(hw, port, true); if (err) dev_err(ice_pf_to_dev(pf), "PTP failed to set PHY port %d down, err %d\n", port, err); mutex_unlock(&ptp_port->ps_lock); return err; } /** * ice_ptp_port_phy_restart - (Re)start and calibrate PHY timestamping * @ptp_port: PTP port for which the PHY start is set * * Start the PHY timestamping block, and initiate Vernier timestamping * calibration. If timestamping cannot be calibrated (such as if link is down) * then disable the timestamping block instead. */ static int ice_ptp_port_phy_restart(struct ice_ptp_port *ptp_port) { struct ice_pf *pf = ptp_port_to_pf(ptp_port); u8 port = ptp_port->port_num; struct ice_hw *hw = &pf->hw; int err; if (ice_is_e810(hw)) return 0; if (!ptp_port->link_up) return ice_ptp_port_phy_stop(ptp_port); mutex_lock(&ptp_port->ps_lock); kthread_cancel_delayed_work_sync(&ptp_port->ov_work); /* temporarily disable Tx timestamps while calibrating PHY offset */ spin_lock(&ptp_port->tx.lock); ptp_port->tx.calibrating = true; spin_unlock(&ptp_port->tx.lock); ptp_port->tx_fifo_busy_cnt = 0; /* Start the PHY timer in Vernier mode */ err = ice_start_phy_timer_e822(hw, port); if (err) goto out_unlock; /* Enable Tx timestamps right away */ spin_lock(&ptp_port->tx.lock); ptp_port->tx.calibrating = false; spin_unlock(&ptp_port->tx.lock); kthread_queue_delayed_work(pf->ptp.kworker, &ptp_port->ov_work, 0); out_unlock: if (err) dev_err(ice_pf_to_dev(pf), "PTP failed to set PHY port %d up, err %d\n", port, err); mutex_unlock(&ptp_port->ps_lock); return err; } /** * ice_ptp_link_change - Reconfigure PTP after link status change * @pf: Board private structure * @port: Port for which the PHY start is set * @linkup: Link is up or down */ void ice_ptp_link_change(struct ice_pf *pf, u8 port, bool linkup) { struct ice_ptp_port *ptp_port; if (!test_bit(ICE_FLAG_PTP, pf->flags)) return; if (WARN_ON_ONCE(port >= ICE_NUM_EXTERNAL_PORTS)) return; ptp_port = &pf->ptp.port; if (WARN_ON_ONCE(ptp_port->port_num != port)) return; /* Update cached link status for this port immediately */ ptp_port->link_up = linkup; /* E810 devices do not need to reconfigure the PHY */ if (ice_is_e810(&pf->hw)) return; ice_ptp_port_phy_restart(ptp_port); } /** * ice_ptp_tx_ena_intr - Enable or disable the Tx timestamp interrupt * @pf: PF private structure * @ena: bool value to enable or disable interrupt * @threshold: Minimum number of packets at which intr is triggered * * Utility function to enable or disable Tx timestamp interrupt and threshold */ static int ice_ptp_tx_ena_intr(struct ice_pf *pf, bool ena, u32 threshold) { struct ice_hw *hw = &pf->hw; int err = 0; int quad; u32 val; ice_ptp_reset_ts_memory(hw); for (quad = 0; quad < ICE_MAX_QUAD; quad++) { err = ice_read_quad_reg_e822(hw, quad, Q_REG_TX_MEM_GBL_CFG, &val); if (err) break; if (ena) { val |= Q_REG_TX_MEM_GBL_CFG_INTR_ENA_M; val &= ~Q_REG_TX_MEM_GBL_CFG_INTR_THR_M; val |= ((threshold << Q_REG_TX_MEM_GBL_CFG_INTR_THR_S) & Q_REG_TX_MEM_GBL_CFG_INTR_THR_M); } else { val &= ~Q_REG_TX_MEM_GBL_CFG_INTR_ENA_M; } err = ice_write_quad_reg_e822(hw, quad, Q_REG_TX_MEM_GBL_CFG, val); if (err) break; } if (err) dev_err(ice_pf_to_dev(pf), "PTP failed in intr ena, err %d\n", err); return err; } /** * ice_ptp_reset_phy_timestamping - Reset PHY timestamping block * @pf: Board private structure */ static void ice_ptp_reset_phy_timestamping(struct ice_pf *pf) { ice_ptp_port_phy_restart(&pf->ptp.port); } /** * ice_ptp_adjfine - Adjust clock increment rate * @info: the driver's PTP info structure * @scaled_ppm: Parts per million with 16-bit fractional field * * Adjust the frequency of the clock by the indicated scaled ppm from the * base frequency. */ static int ice_ptp_adjfine(struct ptp_clock_info *info, long scaled_ppm) { struct ice_pf *pf = ptp_info_to_pf(info); struct ice_hw *hw = &pf->hw; u64 incval; int err; incval = adjust_by_scaled_ppm(ice_base_incval(pf), scaled_ppm); err = ice_ptp_write_incval_locked(hw, incval); if (err) { dev_err(ice_pf_to_dev(pf), "PTP failed to set incval, err %d\n", err); return -EIO; } return 0; } /** * ice_ptp_extts_event - Process PTP external clock event * @pf: Board private structure */ void ice_ptp_extts_event(struct ice_pf *pf) { struct ptp_clock_event event; struct ice_hw *hw = &pf->hw; u8 chan, tmr_idx; u32 hi, lo; tmr_idx = hw->func_caps.ts_func_info.tmr_index_owned; /* Event time is captured by one of the two matched registers * GLTSYN_EVNT_L: 32 LSB of sampled time event * GLTSYN_EVNT_H: 32 MSB of sampled time event * Event is defined in GLTSYN_EVNT_0 register */ for (chan = 0; chan < GLTSYN_EVNT_H_IDX_MAX; chan++) { /* Check if channel is enabled */ if (pf->ptp.ext_ts_irq & (1 << chan)) { lo = rd32(hw, GLTSYN_EVNT_L(chan, tmr_idx)); hi = rd32(hw, GLTSYN_EVNT_H(chan, tmr_idx)); event.timestamp = (((u64)hi) << 32) | lo; event.type = PTP_CLOCK_EXTTS; event.index = chan; /* Fire event */ ptp_clock_event(pf->ptp.clock, &event); pf->ptp.ext_ts_irq &= ~(1 << chan); } } } /** * ice_ptp_cfg_extts - Configure EXTTS pin and channel * @pf: Board private structure * @ena: true to enable; false to disable * @chan: GPIO channel (0-3) * @gpio_pin: GPIO pin * @extts_flags: request flags from the ptp_extts_request.flags */ static int ice_ptp_cfg_extts(struct ice_pf *pf, bool ena, unsigned int chan, u32 gpio_pin, unsigned int extts_flags) { u32 func, aux_reg, gpio_reg, irq_reg; struct ice_hw *hw = &pf->hw; u8 tmr_idx; if (chan > (unsigned int)pf->ptp.info.n_ext_ts) return -EINVAL; tmr_idx = hw->func_caps.ts_func_info.tmr_index_owned; irq_reg = rd32(hw, PFINT_OICR_ENA); if (ena) { /* Enable the interrupt */ irq_reg |= PFINT_OICR_TSYN_EVNT_M; aux_reg = GLTSYN_AUX_IN_0_INT_ENA_M; #define GLTSYN_AUX_IN_0_EVNTLVL_RISING_EDGE BIT(0) #define GLTSYN_AUX_IN_0_EVNTLVL_FALLING_EDGE BIT(1) /* set event level to requested edge */ if (extts_flags & PTP_FALLING_EDGE) aux_reg |= GLTSYN_AUX_IN_0_EVNTLVL_FALLING_EDGE; if (extts_flags & PTP_RISING_EDGE) aux_reg |= GLTSYN_AUX_IN_0_EVNTLVL_RISING_EDGE; /* Write GPIO CTL reg. * 0x1 is input sampled by EVENT register(channel) * + num_in_channels * tmr_idx */ func = 1 + chan + (tmr_idx * 3); gpio_reg = ((func << GLGEN_GPIO_CTL_PIN_FUNC_S) & GLGEN_GPIO_CTL_PIN_FUNC_M); pf->ptp.ext_ts_chan |= (1 << chan); } else { /* clear the values we set to reset defaults */ aux_reg = 0; gpio_reg = 0; pf->ptp.ext_ts_chan &= ~(1 << chan); if (!pf->ptp.ext_ts_chan) irq_reg &= ~PFINT_OICR_TSYN_EVNT_M; } wr32(hw, PFINT_OICR_ENA, irq_reg); wr32(hw, GLTSYN_AUX_IN(chan, tmr_idx), aux_reg); wr32(hw, GLGEN_GPIO_CTL(gpio_pin), gpio_reg); return 0; } /** * ice_ptp_cfg_clkout - Configure clock to generate periodic wave * @pf: Board private structure * @chan: GPIO channel (0-3) * @config: desired periodic clk configuration. NULL will disable channel * @store: If set to true the values will be stored * * Configure the internal clock generator modules to generate the clock wave of * specified period. */ static int ice_ptp_cfg_clkout(struct ice_pf *pf, unsigned int chan, struct ice_perout_channel *config, bool store) { u64 current_time, period, start_time, phase; struct ice_hw *hw = &pf->hw; u32 func, val, gpio_pin; u8 tmr_idx; tmr_idx = hw->func_caps.ts_func_info.tmr_index_owned; /* 0. Reset mode & out_en in AUX_OUT */ wr32(hw, GLTSYN_AUX_OUT(chan, tmr_idx), 0); /* If we're disabling the output, clear out CLKO and TGT and keep * output level low */ if (!config || !config->ena) { wr32(hw, GLTSYN_CLKO(chan, tmr_idx), 0); wr32(hw, GLTSYN_TGT_L(chan, tmr_idx), 0); wr32(hw, GLTSYN_TGT_H(chan, tmr_idx), 0); val = GLGEN_GPIO_CTL_PIN_DIR_M; gpio_pin = pf->ptp.perout_channels[chan].gpio_pin; wr32(hw, GLGEN_GPIO_CTL(gpio_pin), val); /* Store the value if requested */ if (store) memset(&pf->ptp.perout_channels[chan], 0, sizeof(struct ice_perout_channel)); return 0; } period = config->period; start_time = config->start_time; div64_u64_rem(start_time, period, &phase); gpio_pin = config->gpio_pin; /* 1. Write clkout with half of required period value */ if (period & 0x1) { dev_err(ice_pf_to_dev(pf), "CLK Period must be an even value\n"); goto err; } period >>= 1; /* For proper operation, the GLTSYN_CLKO must be larger than clock tick */ #define MIN_PULSE 3 if (period <= MIN_PULSE || period > U32_MAX) { dev_err(ice_pf_to_dev(pf), "CLK Period must be > %d && < 2^33", MIN_PULSE * 2); goto err; } wr32(hw, GLTSYN_CLKO(chan, tmr_idx), lower_32_bits(period)); /* Allow time for programming before start_time is hit */ current_time = ice_ptp_read_src_clk_reg(pf, NULL); /* if start time is in the past start the timer at the nearest second * maintaining phase */ if (start_time < current_time) start_time = div64_u64(current_time + NSEC_PER_SEC - 1, NSEC_PER_SEC) * NSEC_PER_SEC + phase; if (ice_is_e810(hw)) start_time -= E810_OUT_PROP_DELAY_NS; else start_time -= ice_e822_pps_delay(ice_e822_time_ref(hw)); /* 2. Write TARGET time */ wr32(hw, GLTSYN_TGT_L(chan, tmr_idx), lower_32_bits(start_time)); wr32(hw, GLTSYN_TGT_H(chan, tmr_idx), upper_32_bits(start_time)); /* 3. Write AUX_OUT register */ val = GLTSYN_AUX_OUT_0_OUT_ENA_M | GLTSYN_AUX_OUT_0_OUTMOD_M; wr32(hw, GLTSYN_AUX_OUT(chan, tmr_idx), val); /* 4. write GPIO CTL reg */ func = 8 + chan + (tmr_idx * 4); val = GLGEN_GPIO_CTL_PIN_DIR_M | ((func << GLGEN_GPIO_CTL_PIN_FUNC_S) & GLGEN_GPIO_CTL_PIN_FUNC_M); wr32(hw, GLGEN_GPIO_CTL(gpio_pin), val); /* Store the value if requested */ if (store) { memcpy(&pf->ptp.perout_channels[chan], config, sizeof(struct ice_perout_channel)); pf->ptp.perout_channels[chan].start_time = phase; } return 0; err: dev_err(ice_pf_to_dev(pf), "PTP failed to cfg per_clk\n"); return -EFAULT; } /** * ice_ptp_disable_all_clkout - Disable all currently configured outputs * @pf: pointer to the PF structure * * Disable all currently configured clock outputs. This is necessary before * certain changes to the PTP hardware clock. Use ice_ptp_enable_all_clkout to * re-enable the clocks again. */ static void ice_ptp_disable_all_clkout(struct ice_pf *pf) { uint i; for (i = 0; i < pf->ptp.info.n_per_out; i++) if (pf->ptp.perout_channels[i].ena) ice_ptp_cfg_clkout(pf, i, NULL, false); } /** * ice_ptp_enable_all_clkout - Enable all configured periodic clock outputs * @pf: pointer to the PF structure * * Enable all currently configured clock outputs. Use this after * ice_ptp_disable_all_clkout to reconfigure the output signals according to * their configuration. */ static void ice_ptp_enable_all_clkout(struct ice_pf *pf) { uint i; for (i = 0; i < pf->ptp.info.n_per_out; i++) if (pf->ptp.perout_channels[i].ena) ice_ptp_cfg_clkout(pf, i, &pf->ptp.perout_channels[i], false); } /** * ice_ptp_gpio_enable_e810 - Enable/disable ancillary features of PHC * @info: the driver's PTP info structure * @rq: The requested feature to change * @on: Enable/disable flag */ static int ice_ptp_gpio_enable_e810(struct ptp_clock_info *info, struct ptp_clock_request *rq, int on) { struct ice_pf *pf = ptp_info_to_pf(info); struct ice_perout_channel clk_cfg = {0}; bool sma_pres = false; unsigned int chan; u32 gpio_pin; int err; if (ice_is_feature_supported(pf, ICE_F_SMA_CTRL)) sma_pres = true; switch (rq->type) { case PTP_CLK_REQ_PEROUT: chan = rq->perout.index; if (sma_pres) { if (chan == ice_pin_desc_e810t[SMA1].chan) clk_cfg.gpio_pin = GPIO_20; else if (chan == ice_pin_desc_e810t[SMA2].chan) clk_cfg.gpio_pin = GPIO_22; else return -1; } else if (ice_is_e810t(&pf->hw)) { if (chan == 0) clk_cfg.gpio_pin = GPIO_20; else clk_cfg.gpio_pin = GPIO_22; } else if (chan == PPS_CLK_GEN_CHAN) { clk_cfg.gpio_pin = PPS_PIN_INDEX; } else { clk_cfg.gpio_pin = chan; } clk_cfg.period = ((rq->perout.period.sec * NSEC_PER_SEC) + rq->perout.period.nsec); clk_cfg.start_time = ((rq->perout.start.sec * NSEC_PER_SEC) + rq->perout.start.nsec); clk_cfg.ena = !!on; err = ice_ptp_cfg_clkout(pf, chan, &clk_cfg, true); break; case PTP_CLK_REQ_EXTTS: chan = rq->extts.index; if (sma_pres) { if (chan < ice_pin_desc_e810t[SMA2].chan) gpio_pin = GPIO_21; else gpio_pin = GPIO_23; } else if (ice_is_e810t(&pf->hw)) { if (chan == 0) gpio_pin = GPIO_21; else gpio_pin = GPIO_23; } else { gpio_pin = chan; } err = ice_ptp_cfg_extts(pf, !!on, chan, gpio_pin, rq->extts.flags); break; default: return -EOPNOTSUPP; } return err; } /** * ice_ptp_gpio_enable_e823 - Enable/disable ancillary features of PHC * @info: the driver's PTP info structure * @rq: The requested feature to change * @on: Enable/disable flag */ static int ice_ptp_gpio_enable_e823(struct ptp_clock_info *info, struct ptp_clock_request *rq, int on) { struct ice_pf *pf = ptp_info_to_pf(info); struct ice_perout_channel clk_cfg = {0}; int err; switch (rq->type) { case PTP_CLK_REQ_PPS: clk_cfg.gpio_pin = PPS_PIN_INDEX; clk_cfg.period = NSEC_PER_SEC; clk_cfg.ena = !!on; err = ice_ptp_cfg_clkout(pf, PPS_CLK_GEN_CHAN, &clk_cfg, true); break; case PTP_CLK_REQ_EXTTS: err = ice_ptp_cfg_extts(pf, !!on, rq->extts.index, TIME_SYNC_PIN_INDEX, rq->extts.flags); break; default: return -EOPNOTSUPP; } return err; } /** * ice_ptp_gettimex64 - Get the time of the clock * @info: the driver's PTP info structure * @ts: timespec64 structure to hold the current time value * @sts: Optional parameter for holding a pair of system timestamps from * the system clock. Will be ignored if NULL is given. * * Read the device clock and return the correct value on ns, after converting it * into a timespec struct. */ static int ice_ptp_gettimex64(struct ptp_clock_info *info, struct timespec64 *ts, struct ptp_system_timestamp *sts) { struct ice_pf *pf = ptp_info_to_pf(info); struct ice_hw *hw = &pf->hw; if (!ice_ptp_lock(hw)) { dev_err(ice_pf_to_dev(pf), "PTP failed to get time\n"); return -EBUSY; } ice_ptp_read_time(pf, ts, sts); ice_ptp_unlock(hw); return 0; } /** * ice_ptp_settime64 - Set the time of the clock * @info: the driver's PTP info structure * @ts: timespec64 structure that holds the new time value * * Set the device clock to the user input value. The conversion from timespec * to ns happens in the write function. */ static int ice_ptp_settime64(struct ptp_clock_info *info, const struct timespec64 *ts) { struct ice_pf *pf = ptp_info_to_pf(info); struct timespec64 ts64 = *ts; struct ice_hw *hw = &pf->hw; int err; /* For Vernier mode, we need to recalibrate after new settime * Start with disabling timestamp block */ if (pf->ptp.port.link_up) ice_ptp_port_phy_stop(&pf->ptp.port); if (!ice_ptp_lock(hw)) { err = -EBUSY; goto exit; } /* Disable periodic outputs */ ice_ptp_disable_all_clkout(pf); err = ice_ptp_write_init(pf, &ts64); ice_ptp_unlock(hw); if (!err) ice_ptp_reset_cached_phctime(pf); /* Reenable periodic outputs */ ice_ptp_enable_all_clkout(pf); /* Recalibrate and re-enable timestamp block */ if (pf->ptp.port.link_up) ice_ptp_port_phy_restart(&pf->ptp.port); exit: if (err) { dev_err(ice_pf_to_dev(pf), "PTP failed to set time %d\n", err); return err; } return 0; } /** * ice_ptp_adjtime_nonatomic - Do a non-atomic clock adjustment * @info: the driver's PTP info structure * @delta: Offset in nanoseconds to adjust the time by */ static int ice_ptp_adjtime_nonatomic(struct ptp_clock_info *info, s64 delta) { struct timespec64 now, then; int ret; then = ns_to_timespec64(delta); ret = ice_ptp_gettimex64(info, &now, NULL); if (ret) return ret; now = timespec64_add(now, then); return ice_ptp_settime64(info, (const struct timespec64 *)&now); } /** * ice_ptp_adjtime - Adjust the time of the clock by the indicated delta * @info: the driver's PTP info structure * @delta: Offset in nanoseconds to adjust the time by */ static int ice_ptp_adjtime(struct ptp_clock_info *info, s64 delta) { struct ice_pf *pf = ptp_info_to_pf(info); struct ice_hw *hw = &pf->hw; struct device *dev; int err; dev = ice_pf_to_dev(pf); /* Hardware only supports atomic adjustments using signed 32-bit * integers. For any adjustment outside this range, perform * a non-atomic get->adjust->set flow. */ if (delta > S32_MAX || delta < S32_MIN) { dev_dbg(dev, "delta = %lld, adjtime non-atomic\n", delta); return ice_ptp_adjtime_nonatomic(info, delta); } if (!ice_ptp_lock(hw)) { dev_err(dev, "PTP failed to acquire semaphore in adjtime\n"); return -EBUSY; } /* Disable periodic outputs */ ice_ptp_disable_all_clkout(pf); err = ice_ptp_write_adj(pf, delta); /* Reenable periodic outputs */ ice_ptp_enable_all_clkout(pf); ice_ptp_unlock(hw); if (err) { dev_err(dev, "PTP failed to adjust time, err %d\n", err); return err; } ice_ptp_reset_cached_phctime(pf); return 0; } #ifdef CONFIG_ICE_HWTS /** * ice_ptp_get_syncdevicetime - Get the cross time stamp info * @device: Current device time * @system: System counter value read synchronously with device time * @ctx: Context provided by timekeeping code * * Read device and system (ART) clock simultaneously and return the corrected * clock values in ns. */ static int ice_ptp_get_syncdevicetime(ktime_t *device, struct system_counterval_t *system, void *ctx) { struct ice_pf *pf = (struct ice_pf *)ctx; struct ice_hw *hw = &pf->hw; u32 hh_lock, hh_art_ctl; int i; /* Get the HW lock */ hh_lock = rd32(hw, PFHH_SEM + (PFTSYN_SEM_BYTES * hw->pf_id)); if (hh_lock & PFHH_SEM_BUSY_M) { dev_err(ice_pf_to_dev(pf), "PTP failed to get hh lock\n"); return -EFAULT; } /* Start the ART and device clock sync sequence */ hh_art_ctl = rd32(hw, GLHH_ART_CTL); hh_art_ctl = hh_art_ctl | GLHH_ART_CTL_ACTIVE_M; wr32(hw, GLHH_ART_CTL, hh_art_ctl); #define MAX_HH_LOCK_TRIES 100 for (i = 0; i < MAX_HH_LOCK_TRIES; i++) { /* Wait for sync to complete */ hh_art_ctl = rd32(hw, GLHH_ART_CTL); if (hh_art_ctl & GLHH_ART_CTL_ACTIVE_M) { udelay(1); continue; } else { u32 hh_ts_lo, hh_ts_hi, tmr_idx; u64 hh_ts; tmr_idx = hw->func_caps.ts_func_info.tmr_index_assoc; /* Read ART time */ hh_ts_lo = rd32(hw, GLHH_ART_TIME_L); hh_ts_hi = rd32(hw, GLHH_ART_TIME_H); hh_ts = ((u64)hh_ts_hi << 32) | hh_ts_lo; *system = convert_art_ns_to_tsc(hh_ts); /* Read Device source clock time */ hh_ts_lo = rd32(hw, GLTSYN_HHTIME_L(tmr_idx)); hh_ts_hi = rd32(hw, GLTSYN_HHTIME_H(tmr_idx)); hh_ts = ((u64)hh_ts_hi << 32) | hh_ts_lo; *device = ns_to_ktime(hh_ts); break; } } /* Release HW lock */ hh_lock = rd32(hw, PFHH_SEM + (PFTSYN_SEM_BYTES * hw->pf_id)); hh_lock = hh_lock & ~PFHH_SEM_BUSY_M; wr32(hw, PFHH_SEM + (PFTSYN_SEM_BYTES * hw->pf_id), hh_lock); if (i == MAX_HH_LOCK_TRIES) return -ETIMEDOUT; return 0; } /** * ice_ptp_getcrosststamp_e822 - Capture a device cross timestamp * @info: the driver's PTP info structure * @cts: The memory to fill the cross timestamp info * * Capture a cross timestamp between the ART and the device PTP hardware * clock. Fill the cross timestamp information and report it back to the * caller. * * This is only valid for E822 devices which have support for generating the * cross timestamp via PCIe PTM. * * In order to correctly correlate the ART timestamp back to the TSC time, the * CPU must have X86_FEATURE_TSC_KNOWN_FREQ. */ static int ice_ptp_getcrosststamp_e822(struct ptp_clock_info *info, struct system_device_crosststamp *cts) { struct ice_pf *pf = ptp_info_to_pf(info); return get_device_system_crosststamp(ice_ptp_get_syncdevicetime, pf, NULL, cts); } #endif /* CONFIG_ICE_HWTS */ /** * ice_ptp_get_ts_config - ioctl interface to read the timestamping config * @pf: Board private structure * @ifr: ioctl data * * Copy the timestamping config to user buffer */ int ice_ptp_get_ts_config(struct ice_pf *pf, struct ifreq *ifr) { struct hwtstamp_config *config; if (!test_bit(ICE_FLAG_PTP, pf->flags)) return -EIO; config = &pf->ptp.tstamp_config; return copy_to_user(ifr->ifr_data, config, sizeof(*config)) ? -EFAULT : 0; } /** * ice_ptp_set_timestamp_mode - Setup driver for requested timestamp mode * @pf: Board private structure * @config: hwtstamp settings requested or saved */ static int ice_ptp_set_timestamp_mode(struct ice_pf *pf, struct hwtstamp_config *config) { switch (config->tx_type) { case HWTSTAMP_TX_OFF: ice_set_tx_tstamp(pf, false); break; case HWTSTAMP_TX_ON: ice_set_tx_tstamp(pf, true); break; default: return -ERANGE; } switch (config->rx_filter) { case HWTSTAMP_FILTER_NONE: ice_set_rx_tstamp(pf, false); break; 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_EVENT: case HWTSTAMP_FILTER_PTP_V2_L2_EVENT: case HWTSTAMP_FILTER_PTP_V2_L4_EVENT: case HWTSTAMP_FILTER_PTP_V2_SYNC: case HWTSTAMP_FILTER_PTP_V2_L2_SYNC: case HWTSTAMP_FILTER_PTP_V2_L4_SYNC: case HWTSTAMP_FILTER_PTP_V2_DELAY_REQ: case HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ: case HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ: case HWTSTAMP_FILTER_NTP_ALL: case HWTSTAMP_FILTER_ALL: ice_set_rx_tstamp(pf, true); break; default: return -ERANGE; } return 0; } /** * ice_ptp_set_ts_config - ioctl interface to control the timestamping * @pf: Board private structure * @ifr: ioctl data * * Get the user config and store it */ int ice_ptp_set_ts_config(struct ice_pf *pf, struct ifreq *ifr) { struct hwtstamp_config config; int err; if (!test_bit(ICE_FLAG_PTP, pf->flags)) return -EAGAIN; if (copy_from_user(&config, ifr->ifr_data, sizeof(config))) return -EFAULT; err = ice_ptp_set_timestamp_mode(pf, &config); if (err) return err; /* Return the actual configuration set */ config = pf->ptp.tstamp_config; return copy_to_user(ifr->ifr_data, &config, sizeof(config)) ? -EFAULT : 0; } /** * ice_ptp_rx_hwtstamp - Check for an Rx timestamp * @rx_ring: Ring to get the VSI info * @rx_desc: Receive descriptor * @skb: Particular skb to send timestamp with * * The driver receives a notification in the receive descriptor with timestamp. * The timestamp is in ns, so we must convert the result first. */ void ice_ptp_rx_hwtstamp(struct ice_rx_ring *rx_ring, union ice_32b_rx_flex_desc *rx_desc, struct sk_buff *skb) { struct skb_shared_hwtstamps *hwtstamps; u64 ts_ns, cached_time; u32 ts_high; if (!(rx_desc->wb.time_stamp_low & ICE_PTP_TS_VALID)) return; cached_time = READ_ONCE(rx_ring->cached_phctime); /* Do not report a timestamp if we don't have a cached PHC time */ if (!cached_time) return; /* Use ice_ptp_extend_32b_ts directly, using the ring-specific cached * PHC value, rather than accessing the PF. This also allows us to * simply pass the upper 32bits of nanoseconds directly. Calling * ice_ptp_extend_40b_ts is unnecessary as it would just discard these * bits itself. */ ts_high = le32_to_cpu(rx_desc->wb.flex_ts.ts_high); ts_ns = ice_ptp_extend_32b_ts(cached_time, ts_high); hwtstamps = skb_hwtstamps(skb); memset(hwtstamps, 0, sizeof(*hwtstamps)); hwtstamps->hwtstamp = ns_to_ktime(ts_ns); } /** * ice_ptp_disable_sma_pins_e810t - Disable E810-T SMA pins * @pf: pointer to the PF structure * @info: PTP clock info structure * * Disable the OS access to the SMA pins. Called to clear out the OS * indications of pin support when we fail to setup the E810-T SMA control * register. */ static void ice_ptp_disable_sma_pins_e810t(struct ice_pf *pf, struct ptp_clock_info *info) { struct device *dev = ice_pf_to_dev(pf); dev_warn(dev, "Failed to configure E810-T SMA pin control\n"); info->enable = NULL; info->verify = NULL; info->n_pins = 0; info->n_ext_ts = 0; info->n_per_out = 0; } /** * ice_ptp_setup_sma_pins_e810t - Setup the SMA pins * @pf: pointer to the PF structure * @info: PTP clock info structure * * Finish setting up the SMA pins by allocating pin_config, and setting it up * according to the current status of the SMA. On failure, disable all of the * extended SMA pin support. */ static void ice_ptp_setup_sma_pins_e810t(struct ice_pf *pf, struct ptp_clock_info *info) { struct device *dev = ice_pf_to_dev(pf); int err; /* Allocate memory for kernel pins interface */ info->pin_config = devm_kcalloc(dev, info->n_pins, sizeof(*info->pin_config), GFP_KERNEL); if (!info->pin_config) { ice_ptp_disable_sma_pins_e810t(pf, info); return; } /* Read current SMA status */ err = ice_get_sma_config_e810t(&pf->hw, info->pin_config); if (err) ice_ptp_disable_sma_pins_e810t(pf, info); } /** * ice_ptp_setup_pins_e810 - Setup PTP pins in sysfs * @pf: pointer to the PF instance * @info: PTP clock capabilities */ static void ice_ptp_setup_pins_e810(struct ice_pf *pf, struct ptp_clock_info *info) { info->n_per_out = N_PER_OUT_E810; if (ice_is_feature_supported(pf, ICE_F_PTP_EXTTS)) info->n_ext_ts = N_EXT_TS_E810; if (ice_is_feature_supported(pf, ICE_F_SMA_CTRL)) { info->n_ext_ts = N_EXT_TS_E810; info->n_pins = NUM_PTP_PINS_E810T; info->verify = ice_verify_pin_e810t; /* Complete setup of the SMA pins */ ice_ptp_setup_sma_pins_e810t(pf, info); } } /** * ice_ptp_setup_pins_e823 - Setup PTP pins in sysfs * @pf: pointer to the PF instance * @info: PTP clock capabilities */ static void ice_ptp_setup_pins_e823(struct ice_pf *pf, struct ptp_clock_info *info) { info->pps = 1; info->n_per_out = 0; info->n_ext_ts = 1; } /** * ice_ptp_set_funcs_e822 - Set specialized functions for E822 support * @pf: Board private structure * @info: PTP info to fill * * Assign functions to the PTP capabiltiies structure for E822 devices. * Functions which operate across all device families should be set directly * in ice_ptp_set_caps. Only add functions here which are distinct for E822 * devices. */ static void ice_ptp_set_funcs_e822(struct ice_pf *pf, struct ptp_clock_info *info) { #ifdef CONFIG_ICE_HWTS if (boot_cpu_has(X86_FEATURE_ART) && boot_cpu_has(X86_FEATURE_TSC_KNOWN_FREQ)) info->getcrosststamp = ice_ptp_getcrosststamp_e822; #endif /* CONFIG_ICE_HWTS */ } /** * ice_ptp_set_funcs_e810 - Set specialized functions for E810 support * @pf: Board private structure * @info: PTP info to fill * * Assign functions to the PTP capabiltiies structure for E810 devices. * Functions which operate across all device families should be set directly * in ice_ptp_set_caps. Only add functions here which are distinct for e810 * devices. */ static void ice_ptp_set_funcs_e810(struct ice_pf *pf, struct ptp_clock_info *info) { info->enable = ice_ptp_gpio_enable_e810; ice_ptp_setup_pins_e810(pf, info); } /** * ice_ptp_set_funcs_e823 - Set specialized functions for E823 support * @pf: Board private structure * @info: PTP info to fill * * Assign functions to the PTP capabiltiies structure for E823 devices. * Functions which operate across all device families should be set directly * in ice_ptp_set_caps. Only add functions here which are distinct for e823 * devices. */ static void ice_ptp_set_funcs_e823(struct ice_pf *pf, struct ptp_clock_info *info) { info->enable = ice_ptp_gpio_enable_e823; ice_ptp_setup_pins_e823(pf, info); } /** * ice_ptp_set_caps - Set PTP capabilities * @pf: Board private structure */ static void ice_ptp_set_caps(struct ice_pf *pf) { struct ptp_clock_info *info = &pf->ptp.info; struct device *dev = ice_pf_to_dev(pf); snprintf(info->name, sizeof(info->name) - 1, "%s-%s-clk", dev_driver_string(dev), dev_name(dev)); info->owner = THIS_MODULE; info->max_adj = 100000000; info->adjtime = ice_ptp_adjtime; info->adjfine = ice_ptp_adjfine; info->gettimex64 = ice_ptp_gettimex64; info->settime64 = ice_ptp_settime64; if (ice_is_e810(&pf->hw)) ice_ptp_set_funcs_e810(pf, info); else if (ice_is_e823(&pf->hw)) ice_ptp_set_funcs_e823(pf, info); else ice_ptp_set_funcs_e822(pf, info); } /** * ice_ptp_create_clock - Create PTP clock device for userspace * @pf: Board private structure * * This function creates a new PTP clock device. It only creates one if we * don't already have one. Will return error if it can't create one, but success * if we already have a device. Should be used by ice_ptp_init to create clock * initially, and prevent global resets from creating new clock devices. */ static long ice_ptp_create_clock(struct ice_pf *pf) { struct ptp_clock_info *info; struct ptp_clock *clock; struct device *dev; /* No need to create a clock device if we already have one */ if (pf->ptp.clock) return 0; ice_ptp_set_caps(pf); info = &pf->ptp.info; dev = ice_pf_to_dev(pf); /* Attempt to register the clock before enabling the hardware. */ clock = ptp_clock_register(info, dev); if (IS_ERR(clock)) return PTR_ERR(clock); pf->ptp.clock = clock; return 0; } /** * ice_ptp_request_ts - Request an available Tx timestamp index * @tx: the PTP Tx timestamp tracker to request from * @skb: the SKB to associate with this timestamp request */ s8 ice_ptp_request_ts(struct ice_ptp_tx *tx, struct sk_buff *skb) { u8 idx; spin_lock(&tx->lock); /* Check that this tracker is accepting new timestamp requests */ if (!ice_ptp_is_tx_tracker_up(tx)) { spin_unlock(&tx->lock); return -1; } /* Find and set the first available index */ idx = find_first_zero_bit(tx->in_use, tx->len); if (idx < tx->len) { /* We got a valid index that no other thread could have set. Store * a reference to the skb and the start time to allow discarding old * requests. */ set_bit(idx, tx->in_use); clear_bit(idx, tx->stale); tx->tstamps[idx].start = jiffies; tx->tstamps[idx].skb = skb_get(skb); skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS; ice_trace(tx_tstamp_request, skb, idx); } spin_unlock(&tx->lock); /* return the appropriate PHY timestamp register index, -1 if no * indexes were available. */ if (idx >= tx->len) return -1; else return idx + tx->offset; } /** * ice_ptp_process_ts - Process the PTP Tx timestamps * @pf: Board private structure * * Returns: ICE_TX_TSTAMP_WORK_PENDING if there are any outstanding Tx * timestamps that need processing, and ICE_TX_TSTAMP_WORK_DONE otherwise. */ enum ice_tx_tstamp_work ice_ptp_process_ts(struct ice_pf *pf) { return ice_ptp_tx_tstamp(&pf->ptp.port.tx); } static void ice_ptp_periodic_work(struct kthread_work *work) { struct ice_ptp *ptp = container_of(work, struct ice_ptp, work.work); struct ice_pf *pf = container_of(ptp, struct ice_pf, ptp); int err; if (!test_bit(ICE_FLAG_PTP, pf->flags)) return; err = ice_ptp_update_cached_phctime(pf); /* Run twice a second or reschedule if phc update failed */ kthread_queue_delayed_work(ptp->kworker, &ptp->work, msecs_to_jiffies(err ? 10 : 500)); } /** * ice_ptp_reset - Initialize PTP hardware clock support after reset * @pf: Board private structure */ void ice_ptp_reset(struct ice_pf *pf) { struct ice_ptp *ptp = &pf->ptp; struct ice_hw *hw = &pf->hw; struct timespec64 ts; int err, itr = 1; u64 time_diff; if (test_bit(ICE_PFR_REQ, pf->state)) goto pfr; if (!hw->func_caps.ts_func_info.src_tmr_owned) goto reset_ts; err = ice_ptp_init_phc(hw); if (err) goto err; /* Acquire the global hardware lock */ if (!ice_ptp_lock(hw)) { err = -EBUSY; goto err; } /* Write the increment time value to PHY and LAN */ err = ice_ptp_write_incval(hw, ice_base_incval(pf)); if (err) { ice_ptp_unlock(hw); goto err; } /* Write the initial Time value to PHY and LAN using the cached PHC * time before the reset and time difference between stopping and * starting the clock. */ if (ptp->cached_phc_time) { time_diff = ktime_get_real_ns() - ptp->reset_time; ts = ns_to_timespec64(ptp->cached_phc_time + time_diff); } else { ts = ktime_to_timespec64(ktime_get_real()); } err = ice_ptp_write_init(pf, &ts); if (err) { ice_ptp_unlock(hw); goto err; } /* Release the global hardware lock */ ice_ptp_unlock(hw); if (!ice_is_e810(hw)) { /* Enable quad interrupts */ err = ice_ptp_tx_ena_intr(pf, true, itr); if (err) goto err; } reset_ts: /* Restart the PHY timestamping block */ ice_ptp_reset_phy_timestamping(pf); pfr: /* Init Tx structures */ if (ice_is_e810(&pf->hw)) { err = ice_ptp_init_tx_e810(pf, &ptp->port.tx); } else { kthread_init_delayed_work(&ptp->port.ov_work, ice_ptp_wait_for_offsets); err = ice_ptp_init_tx_e822(pf, &ptp->port.tx, ptp->port.port_num); } if (err) goto err; set_bit(ICE_FLAG_PTP, pf->flags); /* Start periodic work going */ kthread_queue_delayed_work(ptp->kworker, &ptp->work, 0); dev_info(ice_pf_to_dev(pf), "PTP reset successful\n"); return; err: dev_err(ice_pf_to_dev(pf), "PTP reset failed %d\n", err); } /** * ice_ptp_prepare_for_reset - Prepare PTP for reset * @pf: Board private structure */ void ice_ptp_prepare_for_reset(struct ice_pf *pf) { struct ice_ptp *ptp = &pf->ptp; u8 src_tmr; clear_bit(ICE_FLAG_PTP, pf->flags); /* Disable timestamping for both Tx and Rx */ ice_ptp_cfg_timestamp(pf, false); kthread_cancel_delayed_work_sync(&ptp->work); if (test_bit(ICE_PFR_REQ, pf->state)) return; ice_ptp_release_tx_tracker(pf, &pf->ptp.port.tx); /* Disable periodic outputs */ ice_ptp_disable_all_clkout(pf); src_tmr = ice_get_ptp_src_clock_index(&pf->hw); /* Disable source clock */ wr32(&pf->hw, GLTSYN_ENA(src_tmr), (u32)~GLTSYN_ENA_TSYN_ENA_M); /* Acquire PHC and system timer to restore after reset */ ptp->reset_time = ktime_get_real_ns(); } /** * ice_ptp_init_owner - Initialize PTP_1588_CLOCK device * @pf: Board private structure * * Setup and initialize a PTP clock device that represents the device hardware * clock. Save the clock index for other functions connected to the same * hardware resource. */ static int ice_ptp_init_owner(struct ice_pf *pf) { struct ice_hw *hw = &pf->hw; struct timespec64 ts; int err, itr = 1; err = ice_ptp_init_phc(hw); if (err) { dev_err(ice_pf_to_dev(pf), "Failed to initialize PHC, err %d\n", err); return err; } /* Acquire the global hardware lock */ if (!ice_ptp_lock(hw)) { err = -EBUSY; goto err_exit; } /* Write the increment time value to PHY and LAN */ err = ice_ptp_write_incval(hw, ice_base_incval(pf)); if (err) { ice_ptp_unlock(hw); goto err_exit; } ts = ktime_to_timespec64(ktime_get_real()); /* Write the initial Time value to PHY and LAN */ err = ice_ptp_write_init(pf, &ts); if (err) { ice_ptp_unlock(hw); goto err_exit; } /* Release the global hardware lock */ ice_ptp_unlock(hw); if (!ice_is_e810(hw)) { /* Enable quad interrupts */ err = ice_ptp_tx_ena_intr(pf, true, itr); if (err) goto err_exit; } /* Ensure we have a clock device */ err = ice_ptp_create_clock(pf); if (err) goto err_clk; /* Store the PTP clock index for other PFs */ ice_set_ptp_clock_index(pf); return 0; err_clk: pf->ptp.clock = NULL; err_exit: return err; } /** * ice_ptp_init_work - Initialize PTP work threads * @pf: Board private structure * @ptp: PF PTP structure */ static int ice_ptp_init_work(struct ice_pf *pf, struct ice_ptp *ptp) { struct kthread_worker *kworker; /* Initialize work functions */ kthread_init_delayed_work(&ptp->work, ice_ptp_periodic_work); /* Allocate a kworker for handling work required for the ports * connected to the PTP hardware clock. */ kworker = kthread_create_worker(0, "ice-ptp-%s", dev_name(ice_pf_to_dev(pf))); if (IS_ERR(kworker)) return PTR_ERR(kworker); ptp->kworker = kworker; /* Start periodic work going */ kthread_queue_delayed_work(ptp->kworker, &ptp->work, 0); return 0; } /** * ice_ptp_init_port - Initialize PTP port structure * @pf: Board private structure * @ptp_port: PTP port structure */ static int ice_ptp_init_port(struct ice_pf *pf, struct ice_ptp_port *ptp_port) { mutex_init(&ptp_port->ps_lock); if (ice_is_e810(&pf->hw)) return ice_ptp_init_tx_e810(pf, &ptp_port->tx); kthread_init_delayed_work(&ptp_port->ov_work, ice_ptp_wait_for_offsets); return ice_ptp_init_tx_e822(pf, &ptp_port->tx, ptp_port->port_num); } /** * ice_ptp_init - Initialize PTP hardware clock support * @pf: Board private structure * * Set up the device for interacting with the PTP hardware clock for all * functions, both the function that owns the clock hardware, and the * functions connected to the clock hardware. * * The clock owner will allocate and register a ptp_clock with the * PTP_1588_CLOCK infrastructure. All functions allocate a kthread and work * items used for asynchronous work such as Tx timestamps and periodic work. */ void ice_ptp_init(struct ice_pf *pf) { struct ice_ptp *ptp = &pf->ptp; struct ice_hw *hw = &pf->hw; int err; /* If this function owns the clock hardware, it must allocate and * configure the PTP clock device to represent it. */ if (hw->func_caps.ts_func_info.src_tmr_owned) { err = ice_ptp_init_owner(pf); if (err) goto err; } ptp->port.port_num = hw->pf_id; err = ice_ptp_init_port(pf, &ptp->port); if (err) goto err; /* Start the PHY timestamping block */ ice_ptp_reset_phy_timestamping(pf); set_bit(ICE_FLAG_PTP, pf->flags); err = ice_ptp_init_work(pf, ptp); if (err) goto err; dev_info(ice_pf_to_dev(pf), "PTP init successful\n"); return; err: /* If we registered a PTP clock, release it */ if (pf->ptp.clock) { ptp_clock_unregister(ptp->clock); pf->ptp.clock = NULL; } clear_bit(ICE_FLAG_PTP, pf->flags); dev_err(ice_pf_to_dev(pf), "PTP failed %d\n", err); } /** * ice_ptp_release - Disable the driver/HW support and unregister the clock * @pf: Board private structure * * This function handles the cleanup work required from the initialization by * clearing out the important information and unregistering the clock */ void ice_ptp_release(struct ice_pf *pf) { if (!test_bit(ICE_FLAG_PTP, pf->flags)) return; /* Disable timestamping for both Tx and Rx */ ice_ptp_cfg_timestamp(pf, false); ice_ptp_release_tx_tracker(pf, &pf->ptp.port.tx); clear_bit(ICE_FLAG_PTP, pf->flags); kthread_cancel_delayed_work_sync(&pf->ptp.work); ice_ptp_port_phy_stop(&pf->ptp.port); mutex_destroy(&pf->ptp.port.ps_lock); if (pf->ptp.kworker) { kthread_destroy_worker(pf->ptp.kworker); pf->ptp.kworker = NULL; } if (!pf->ptp.clock) return; /* Disable periodic outputs */ ice_ptp_disable_all_clkout(pf); ice_clear_ptp_clock_index(pf); ptp_clock_unregister(pf->ptp.clock); pf->ptp.clock = NULL; dev_info(ice_pf_to_dev(pf), "Removed PTP clock\n"); }
linux-master
drivers/net/ethernet/intel/ice/ice_ptp.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2023, Intel Corporation. */ #include "ice.h" #include "ice_eswitch_br.h" #include "ice_repr.h" #include "ice_switch.h" #include "ice_vlan.h" #include "ice_vf_vsi_vlan_ops.h" #include "ice_trace.h" #define ICE_ESW_BRIDGE_UPDATE_INTERVAL msecs_to_jiffies(1000) static const struct rhashtable_params ice_fdb_ht_params = { .key_offset = offsetof(struct ice_esw_br_fdb_entry, data), .key_len = sizeof(struct ice_esw_br_fdb_data), .head_offset = offsetof(struct ice_esw_br_fdb_entry, ht_node), .automatic_shrinking = true, }; static bool ice_eswitch_br_is_dev_valid(const struct net_device *dev) { /* Accept only PF netdev, PRs and LAG */ return ice_is_port_repr_netdev(dev) || netif_is_ice(dev) || netif_is_lag_master(dev); } static struct net_device * ice_eswitch_br_get_uplink_from_lag(struct net_device *lag_dev) { struct net_device *lower; struct list_head *iter; netdev_for_each_lower_dev(lag_dev, lower, iter) { if (netif_is_ice(lower)) return lower; } return NULL; } static struct ice_esw_br_port * ice_eswitch_br_netdev_to_port(struct net_device *dev) { if (ice_is_port_repr_netdev(dev)) { struct ice_repr *repr = ice_netdev_to_repr(dev); return repr->br_port; } else if (netif_is_ice(dev) || netif_is_lag_master(dev)) { struct net_device *ice_dev; struct ice_pf *pf; if (netif_is_lag_master(dev)) ice_dev = ice_eswitch_br_get_uplink_from_lag(dev); else ice_dev = dev; if (!ice_dev) return NULL; pf = ice_netdev_to_pf(ice_dev); return pf->br_port; } return NULL; } static void ice_eswitch_br_ingress_rule_setup(struct ice_adv_rule_info *rule_info, u8 pf_id, u16 vf_vsi_idx) { rule_info->sw_act.vsi_handle = vf_vsi_idx; rule_info->sw_act.flag |= ICE_FLTR_RX; rule_info->sw_act.src = pf_id; rule_info->priority = 5; } static void ice_eswitch_br_egress_rule_setup(struct ice_adv_rule_info *rule_info, u16 pf_vsi_idx) { rule_info->sw_act.vsi_handle = pf_vsi_idx; rule_info->sw_act.flag |= ICE_FLTR_TX; rule_info->flags_info.act = ICE_SINGLE_ACT_LAN_ENABLE; rule_info->flags_info.act_valid = true; rule_info->priority = 5; } static int ice_eswitch_br_rule_delete(struct ice_hw *hw, struct ice_rule_query_data *rule) { int err; if (!rule) return -EINVAL; err = ice_rem_adv_rule_by_id(hw, rule); kfree(rule); return err; } static u16 ice_eswitch_br_get_lkups_cnt(u16 vid) { return ice_eswitch_br_is_vid_valid(vid) ? 2 : 1; } static void ice_eswitch_br_add_vlan_lkup(struct ice_adv_lkup_elem *list, u16 vid) { if (ice_eswitch_br_is_vid_valid(vid)) { list[1].type = ICE_VLAN_OFOS; list[1].h_u.vlan_hdr.vlan = cpu_to_be16(vid & VLAN_VID_MASK); list[1].m_u.vlan_hdr.vlan = cpu_to_be16(0xFFFF); } } static struct ice_rule_query_data * ice_eswitch_br_fwd_rule_create(struct ice_hw *hw, int vsi_idx, int port_type, const unsigned char *mac, u16 vid) { struct ice_adv_rule_info rule_info = { 0 }; struct ice_rule_query_data *rule; struct ice_adv_lkup_elem *list; u16 lkups_cnt; int err; lkups_cnt = ice_eswitch_br_get_lkups_cnt(vid); rule = kzalloc(sizeof(*rule), GFP_KERNEL); if (!rule) return ERR_PTR(-ENOMEM); list = kcalloc(lkups_cnt, sizeof(*list), GFP_ATOMIC); if (!list) { err = -ENOMEM; goto err_list_alloc; } switch (port_type) { case ICE_ESWITCH_BR_UPLINK_PORT: ice_eswitch_br_egress_rule_setup(&rule_info, vsi_idx); break; case ICE_ESWITCH_BR_VF_REPR_PORT: ice_eswitch_br_ingress_rule_setup(&rule_info, hw->pf_id, vsi_idx); break; default: err = -EINVAL; goto err_add_rule; } list[0].type = ICE_MAC_OFOS; ether_addr_copy(list[0].h_u.eth_hdr.dst_addr, mac); eth_broadcast_addr(list[0].m_u.eth_hdr.dst_addr); ice_eswitch_br_add_vlan_lkup(list, vid); rule_info.need_pass_l2 = true; rule_info.sw_act.fltr_act = ICE_FWD_TO_VSI; err = ice_add_adv_rule(hw, list, lkups_cnt, &rule_info, rule); if (err) goto err_add_rule; kfree(list); return rule; err_add_rule: kfree(list); err_list_alloc: kfree(rule); return ERR_PTR(err); } static struct ice_rule_query_data * ice_eswitch_br_guard_rule_create(struct ice_hw *hw, u16 vsi_idx, const unsigned char *mac, u16 vid) { struct ice_adv_rule_info rule_info = { 0 }; struct ice_rule_query_data *rule; struct ice_adv_lkup_elem *list; int err = -ENOMEM; u16 lkups_cnt; lkups_cnt = ice_eswitch_br_get_lkups_cnt(vid); rule = kzalloc(sizeof(*rule), GFP_KERNEL); if (!rule) goto err_exit; list = kcalloc(lkups_cnt, sizeof(*list), GFP_ATOMIC); if (!list) goto err_list_alloc; list[0].type = ICE_MAC_OFOS; ether_addr_copy(list[0].h_u.eth_hdr.src_addr, mac); eth_broadcast_addr(list[0].m_u.eth_hdr.src_addr); ice_eswitch_br_add_vlan_lkup(list, vid); rule_info.allow_pass_l2 = true; rule_info.sw_act.vsi_handle = vsi_idx; rule_info.sw_act.fltr_act = ICE_NOP; rule_info.priority = 5; err = ice_add_adv_rule(hw, list, lkups_cnt, &rule_info, rule); if (err) goto err_add_rule; kfree(list); return rule; err_add_rule: kfree(list); err_list_alloc: kfree(rule); err_exit: return ERR_PTR(err); } static struct ice_esw_br_flow * ice_eswitch_br_flow_create(struct device *dev, struct ice_hw *hw, int vsi_idx, int port_type, const unsigned char *mac, u16 vid) { struct ice_rule_query_data *fwd_rule, *guard_rule; struct ice_esw_br_flow *flow; int err; flow = kzalloc(sizeof(*flow), GFP_KERNEL); if (!flow) return ERR_PTR(-ENOMEM); fwd_rule = ice_eswitch_br_fwd_rule_create(hw, vsi_idx, port_type, mac, vid); err = PTR_ERR_OR_ZERO(fwd_rule); if (err) { dev_err(dev, "Failed to create eswitch bridge %sgress forward rule, err: %d\n", port_type == ICE_ESWITCH_BR_UPLINK_PORT ? "e" : "in", err); goto err_fwd_rule; } guard_rule = ice_eswitch_br_guard_rule_create(hw, vsi_idx, mac, vid); err = PTR_ERR_OR_ZERO(guard_rule); if (err) { dev_err(dev, "Failed to create eswitch bridge %sgress guard rule, err: %d\n", port_type == ICE_ESWITCH_BR_UPLINK_PORT ? "e" : "in", err); goto err_guard_rule; } flow->fwd_rule = fwd_rule; flow->guard_rule = guard_rule; return flow; err_guard_rule: ice_eswitch_br_rule_delete(hw, fwd_rule); err_fwd_rule: kfree(flow); return ERR_PTR(err); } static struct ice_esw_br_fdb_entry * ice_eswitch_br_fdb_find(struct ice_esw_br *bridge, const unsigned char *mac, u16 vid) { struct ice_esw_br_fdb_data data = { .vid = vid, }; ether_addr_copy(data.addr, mac); return rhashtable_lookup_fast(&bridge->fdb_ht, &data, ice_fdb_ht_params); } static void ice_eswitch_br_flow_delete(struct ice_pf *pf, struct ice_esw_br_flow *flow) { struct device *dev = ice_pf_to_dev(pf); int err; err = ice_eswitch_br_rule_delete(&pf->hw, flow->fwd_rule); if (err) dev_err(dev, "Failed to delete FDB forward rule, err: %d\n", err); err = ice_eswitch_br_rule_delete(&pf->hw, flow->guard_rule); if (err) dev_err(dev, "Failed to delete FDB guard rule, err: %d\n", err); kfree(flow); } static struct ice_esw_br_vlan * ice_esw_br_port_vlan_lookup(struct ice_esw_br *bridge, u16 vsi_idx, u16 vid) { struct ice_pf *pf = bridge->br_offloads->pf; struct device *dev = ice_pf_to_dev(pf); struct ice_esw_br_port *port; struct ice_esw_br_vlan *vlan; port = xa_load(&bridge->ports, vsi_idx); if (!port) { dev_info(dev, "Bridge port lookup failed (vsi=%u)\n", vsi_idx); return ERR_PTR(-EINVAL); } vlan = xa_load(&port->vlans, vid); if (!vlan) { dev_info(dev, "Bridge port vlan metadata lookup failed (vsi=%u)\n", vsi_idx); return ERR_PTR(-EINVAL); } return vlan; } static void ice_eswitch_br_fdb_entry_delete(struct ice_esw_br *bridge, struct ice_esw_br_fdb_entry *fdb_entry) { struct ice_pf *pf = bridge->br_offloads->pf; rhashtable_remove_fast(&bridge->fdb_ht, &fdb_entry->ht_node, ice_fdb_ht_params); list_del(&fdb_entry->list); ice_eswitch_br_flow_delete(pf, fdb_entry->flow); kfree(fdb_entry); } static void ice_eswitch_br_fdb_offload_notify(struct net_device *dev, const unsigned char *mac, u16 vid, unsigned long val) { struct switchdev_notifier_fdb_info fdb_info = { .addr = mac, .vid = vid, .offloaded = true, }; call_switchdev_notifiers(val, dev, &fdb_info.info, NULL); } static void ice_eswitch_br_fdb_entry_notify_and_cleanup(struct ice_esw_br *bridge, struct ice_esw_br_fdb_entry *entry) { if (!(entry->flags & ICE_ESWITCH_BR_FDB_ADDED_BY_USER)) ice_eswitch_br_fdb_offload_notify(entry->dev, entry->data.addr, entry->data.vid, SWITCHDEV_FDB_DEL_TO_BRIDGE); ice_eswitch_br_fdb_entry_delete(bridge, entry); } static void ice_eswitch_br_fdb_entry_find_and_delete(struct ice_esw_br *bridge, const unsigned char *mac, u16 vid) { struct ice_pf *pf = bridge->br_offloads->pf; struct ice_esw_br_fdb_entry *fdb_entry; struct device *dev = ice_pf_to_dev(pf); fdb_entry = ice_eswitch_br_fdb_find(bridge, mac, vid); if (!fdb_entry) { dev_err(dev, "FDB entry with mac: %pM and vid: %u not found\n", mac, vid); return; } trace_ice_eswitch_br_fdb_entry_find_and_delete(fdb_entry); ice_eswitch_br_fdb_entry_notify_and_cleanup(bridge, fdb_entry); } static void ice_eswitch_br_fdb_entry_create(struct net_device *netdev, struct ice_esw_br_port *br_port, bool added_by_user, const unsigned char *mac, u16 vid) { struct ice_esw_br *bridge = br_port->bridge; struct ice_pf *pf = bridge->br_offloads->pf; struct device *dev = ice_pf_to_dev(pf); struct ice_esw_br_fdb_entry *fdb_entry; struct ice_esw_br_flow *flow; struct ice_esw_br_vlan *vlan; struct ice_hw *hw = &pf->hw; unsigned long event; int err; /* untagged filtering is not yet supported */ if (!(bridge->flags & ICE_ESWITCH_BR_VLAN_FILTERING) && vid) return; if ((bridge->flags & ICE_ESWITCH_BR_VLAN_FILTERING)) { vlan = ice_esw_br_port_vlan_lookup(bridge, br_port->vsi_idx, vid); if (IS_ERR(vlan)) { dev_err(dev, "Failed to find vlan lookup, err: %ld\n", PTR_ERR(vlan)); return; } } fdb_entry = ice_eswitch_br_fdb_find(bridge, mac, vid); if (fdb_entry) ice_eswitch_br_fdb_entry_notify_and_cleanup(bridge, fdb_entry); fdb_entry = kzalloc(sizeof(*fdb_entry), GFP_KERNEL); if (!fdb_entry) { err = -ENOMEM; goto err_exit; } flow = ice_eswitch_br_flow_create(dev, hw, br_port->vsi_idx, br_port->type, mac, vid); if (IS_ERR(flow)) { err = PTR_ERR(flow); goto err_add_flow; } ether_addr_copy(fdb_entry->data.addr, mac); fdb_entry->data.vid = vid; fdb_entry->br_port = br_port; fdb_entry->flow = flow; fdb_entry->dev = netdev; fdb_entry->last_use = jiffies; event = SWITCHDEV_FDB_ADD_TO_BRIDGE; if (added_by_user) { fdb_entry->flags |= ICE_ESWITCH_BR_FDB_ADDED_BY_USER; event = SWITCHDEV_FDB_OFFLOADED; } err = rhashtable_insert_fast(&bridge->fdb_ht, &fdb_entry->ht_node, ice_fdb_ht_params); if (err) goto err_fdb_insert; list_add(&fdb_entry->list, &bridge->fdb_list); trace_ice_eswitch_br_fdb_entry_create(fdb_entry); ice_eswitch_br_fdb_offload_notify(netdev, mac, vid, event); return; err_fdb_insert: ice_eswitch_br_flow_delete(pf, flow); err_add_flow: kfree(fdb_entry); err_exit: dev_err(dev, "Failed to create fdb entry, err: %d\n", err); } static void ice_eswitch_br_fdb_work_dealloc(struct ice_esw_br_fdb_work *fdb_work) { kfree(fdb_work->fdb_info.addr); kfree(fdb_work); } static void ice_eswitch_br_fdb_event_work(struct work_struct *work) { struct ice_esw_br_fdb_work *fdb_work = ice_work_to_fdb_work(work); bool added_by_user = fdb_work->fdb_info.added_by_user; const unsigned char *mac = fdb_work->fdb_info.addr; u16 vid = fdb_work->fdb_info.vid; struct ice_esw_br_port *br_port; rtnl_lock(); br_port = ice_eswitch_br_netdev_to_port(fdb_work->dev); if (!br_port) goto err_exit; switch (fdb_work->event) { case SWITCHDEV_FDB_ADD_TO_DEVICE: ice_eswitch_br_fdb_entry_create(fdb_work->dev, br_port, added_by_user, mac, vid); break; case SWITCHDEV_FDB_DEL_TO_DEVICE: ice_eswitch_br_fdb_entry_find_and_delete(br_port->bridge, mac, vid); break; default: goto err_exit; } err_exit: rtnl_unlock(); dev_put(fdb_work->dev); ice_eswitch_br_fdb_work_dealloc(fdb_work); } static struct ice_esw_br_fdb_work * ice_eswitch_br_fdb_work_alloc(struct switchdev_notifier_fdb_info *fdb_info, struct net_device *dev, unsigned long event) { struct ice_esw_br_fdb_work *work; unsigned char *mac; work = kzalloc(sizeof(*work), GFP_ATOMIC); if (!work) return ERR_PTR(-ENOMEM); INIT_WORK(&work->work, ice_eswitch_br_fdb_event_work); memcpy(&work->fdb_info, fdb_info, sizeof(work->fdb_info)); mac = kzalloc(ETH_ALEN, GFP_ATOMIC); if (!mac) { kfree(work); return ERR_PTR(-ENOMEM); } ether_addr_copy(mac, fdb_info->addr); work->fdb_info.addr = mac; work->event = event; work->dev = dev; return work; } static int ice_eswitch_br_switchdev_event(struct notifier_block *nb, unsigned long event, void *ptr) { struct net_device *dev = switchdev_notifier_info_to_dev(ptr); struct switchdev_notifier_fdb_info *fdb_info; struct switchdev_notifier_info *info = ptr; struct ice_esw_br_offloads *br_offloads; struct ice_esw_br_fdb_work *work; struct netlink_ext_ack *extack; struct net_device *upper; br_offloads = ice_nb_to_br_offloads(nb, switchdev_nb); extack = switchdev_notifier_info_to_extack(ptr); upper = netdev_master_upper_dev_get_rcu(dev); if (!upper) return NOTIFY_DONE; if (!netif_is_bridge_master(upper)) return NOTIFY_DONE; if (!ice_eswitch_br_is_dev_valid(dev)) return NOTIFY_DONE; if (!ice_eswitch_br_netdev_to_port(dev)) return NOTIFY_DONE; switch (event) { case SWITCHDEV_FDB_ADD_TO_DEVICE: case SWITCHDEV_FDB_DEL_TO_DEVICE: fdb_info = container_of(info, typeof(*fdb_info), info); work = ice_eswitch_br_fdb_work_alloc(fdb_info, dev, event); if (IS_ERR(work)) { NL_SET_ERR_MSG_MOD(extack, "Failed to init switchdev fdb work"); return notifier_from_errno(PTR_ERR(work)); } dev_hold(dev); queue_work(br_offloads->wq, &work->work); break; default: break; } return NOTIFY_DONE; } static void ice_eswitch_br_fdb_flush(struct ice_esw_br *bridge) { struct ice_esw_br_fdb_entry *entry, *tmp; list_for_each_entry_safe(entry, tmp, &bridge->fdb_list, list) ice_eswitch_br_fdb_entry_notify_and_cleanup(bridge, entry); } static void ice_eswitch_br_vlan_filtering_set(struct ice_esw_br *bridge, bool enable) { if (enable == !!(bridge->flags & ICE_ESWITCH_BR_VLAN_FILTERING)) return; ice_eswitch_br_fdb_flush(bridge); if (enable) bridge->flags |= ICE_ESWITCH_BR_VLAN_FILTERING; else bridge->flags &= ~ICE_ESWITCH_BR_VLAN_FILTERING; } static void ice_eswitch_br_clear_pvid(struct ice_esw_br_port *port) { struct ice_vlan port_vlan = ICE_VLAN(ETH_P_8021Q, port->pvid, 0); struct ice_vsi_vlan_ops *vlan_ops; vlan_ops = ice_get_compat_vsi_vlan_ops(port->vsi); vlan_ops->del_vlan(port->vsi, &port_vlan); vlan_ops->clear_port_vlan(port->vsi); ice_vf_vsi_disable_port_vlan(port->vsi); port->pvid = 0; } static void ice_eswitch_br_vlan_cleanup(struct ice_esw_br_port *port, struct ice_esw_br_vlan *vlan) { struct ice_esw_br_fdb_entry *fdb_entry, *tmp; struct ice_esw_br *bridge = port->bridge; trace_ice_eswitch_br_vlan_cleanup(vlan); list_for_each_entry_safe(fdb_entry, tmp, &bridge->fdb_list, list) { if (vlan->vid == fdb_entry->data.vid) ice_eswitch_br_fdb_entry_delete(bridge, fdb_entry); } xa_erase(&port->vlans, vlan->vid); if (port->pvid == vlan->vid) ice_eswitch_br_clear_pvid(port); kfree(vlan); } static void ice_eswitch_br_port_vlans_flush(struct ice_esw_br_port *port) { struct ice_esw_br_vlan *vlan; unsigned long index; xa_for_each(&port->vlans, index, vlan) ice_eswitch_br_vlan_cleanup(port, vlan); } static int ice_eswitch_br_set_pvid(struct ice_esw_br_port *port, struct ice_esw_br_vlan *vlan) { struct ice_vlan port_vlan = ICE_VLAN(ETH_P_8021Q, vlan->vid, 0); struct device *dev = ice_pf_to_dev(port->vsi->back); struct ice_vsi_vlan_ops *vlan_ops; int err; if (port->pvid == vlan->vid || vlan->vid == 1) return 0; /* Setting port vlan on uplink isn't supported by hw */ if (port->type == ICE_ESWITCH_BR_UPLINK_PORT) return -EOPNOTSUPP; if (port->pvid) { dev_info(dev, "Port VLAN (vsi=%u, vid=%u) already exists on the port, remove it before adding new one\n", port->vsi_idx, port->pvid); return -EEXIST; } ice_vf_vsi_enable_port_vlan(port->vsi); vlan_ops = ice_get_compat_vsi_vlan_ops(port->vsi); err = vlan_ops->set_port_vlan(port->vsi, &port_vlan); if (err) return err; err = vlan_ops->add_vlan(port->vsi, &port_vlan); if (err) return err; ice_eswitch_br_port_vlans_flush(port); port->pvid = vlan->vid; return 0; } static struct ice_esw_br_vlan * ice_eswitch_br_vlan_create(u16 vid, u16 flags, struct ice_esw_br_port *port) { struct device *dev = ice_pf_to_dev(port->vsi->back); struct ice_esw_br_vlan *vlan; int err; vlan = kzalloc(sizeof(*vlan), GFP_KERNEL); if (!vlan) return ERR_PTR(-ENOMEM); vlan->vid = vid; vlan->flags = flags; if ((flags & BRIDGE_VLAN_INFO_PVID) && (flags & BRIDGE_VLAN_INFO_UNTAGGED)) { err = ice_eswitch_br_set_pvid(port, vlan); if (err) goto err_set_pvid; } else if ((flags & BRIDGE_VLAN_INFO_PVID) || (flags & BRIDGE_VLAN_INFO_UNTAGGED)) { dev_info(dev, "VLAN push and pop are supported only simultaneously\n"); err = -EOPNOTSUPP; goto err_set_pvid; } err = xa_insert(&port->vlans, vlan->vid, vlan, GFP_KERNEL); if (err) goto err_insert; trace_ice_eswitch_br_vlan_create(vlan); return vlan; err_insert: if (port->pvid) ice_eswitch_br_clear_pvid(port); err_set_pvid: kfree(vlan); return ERR_PTR(err); } static int ice_eswitch_br_port_vlan_add(struct ice_esw_br *bridge, u16 vsi_idx, u16 vid, u16 flags, struct netlink_ext_ack *extack) { struct ice_esw_br_port *port; struct ice_esw_br_vlan *vlan; port = xa_load(&bridge->ports, vsi_idx); if (!port) return -EINVAL; if (port->pvid) { dev_info(ice_pf_to_dev(port->vsi->back), "Port VLAN (vsi=%u, vid=%d) exists on the port, remove it to add trunk VLANs\n", port->vsi_idx, port->pvid); return -EEXIST; } vlan = xa_load(&port->vlans, vid); if (vlan) { if (vlan->flags == flags) return 0; ice_eswitch_br_vlan_cleanup(port, vlan); } vlan = ice_eswitch_br_vlan_create(vid, flags, port); if (IS_ERR(vlan)) { NL_SET_ERR_MSG_FMT_MOD(extack, "Failed to create VLAN entry, vid: %u, vsi: %u", vid, vsi_idx); return PTR_ERR(vlan); } return 0; } static void ice_eswitch_br_port_vlan_del(struct ice_esw_br *bridge, u16 vsi_idx, u16 vid) { struct ice_esw_br_port *port; struct ice_esw_br_vlan *vlan; port = xa_load(&bridge->ports, vsi_idx); if (!port) return; vlan = xa_load(&port->vlans, vid); if (!vlan) return; ice_eswitch_br_vlan_cleanup(port, vlan); } static int ice_eswitch_br_port_obj_add(struct net_device *netdev, const void *ctx, const struct switchdev_obj *obj, struct netlink_ext_ack *extack) { struct ice_esw_br_port *br_port = ice_eswitch_br_netdev_to_port(netdev); struct switchdev_obj_port_vlan *vlan; int err; if (!br_port) return -EINVAL; switch (obj->id) { case SWITCHDEV_OBJ_ID_PORT_VLAN: vlan = SWITCHDEV_OBJ_PORT_VLAN(obj); err = ice_eswitch_br_port_vlan_add(br_port->bridge, br_port->vsi_idx, vlan->vid, vlan->flags, extack); return err; default: return -EOPNOTSUPP; } } static int ice_eswitch_br_port_obj_del(struct net_device *netdev, const void *ctx, const struct switchdev_obj *obj) { struct ice_esw_br_port *br_port = ice_eswitch_br_netdev_to_port(netdev); struct switchdev_obj_port_vlan *vlan; if (!br_port) return -EINVAL; switch (obj->id) { case SWITCHDEV_OBJ_ID_PORT_VLAN: vlan = SWITCHDEV_OBJ_PORT_VLAN(obj); ice_eswitch_br_port_vlan_del(br_port->bridge, br_port->vsi_idx, vlan->vid); return 0; default: return -EOPNOTSUPP; } } static int ice_eswitch_br_port_obj_attr_set(struct net_device *netdev, const void *ctx, const struct switchdev_attr *attr, struct netlink_ext_ack *extack) { struct ice_esw_br_port *br_port = ice_eswitch_br_netdev_to_port(netdev); if (!br_port) return -EINVAL; switch (attr->id) { case SWITCHDEV_ATTR_ID_BRIDGE_VLAN_FILTERING: ice_eswitch_br_vlan_filtering_set(br_port->bridge, attr->u.vlan_filtering); return 0; case SWITCHDEV_ATTR_ID_BRIDGE_AGEING_TIME: br_port->bridge->ageing_time = clock_t_to_jiffies(attr->u.ageing_time); return 0; default: return -EOPNOTSUPP; } } static int ice_eswitch_br_event_blocking(struct notifier_block *nb, unsigned long event, void *ptr) { struct net_device *dev = switchdev_notifier_info_to_dev(ptr); int err; switch (event) { case SWITCHDEV_PORT_OBJ_ADD: err = switchdev_handle_port_obj_add(dev, ptr, ice_eswitch_br_is_dev_valid, ice_eswitch_br_port_obj_add); break; case SWITCHDEV_PORT_OBJ_DEL: err = switchdev_handle_port_obj_del(dev, ptr, ice_eswitch_br_is_dev_valid, ice_eswitch_br_port_obj_del); break; case SWITCHDEV_PORT_ATTR_SET: err = switchdev_handle_port_attr_set(dev, ptr, ice_eswitch_br_is_dev_valid, ice_eswitch_br_port_obj_attr_set); break; default: err = 0; } return notifier_from_errno(err); } static void ice_eswitch_br_port_deinit(struct ice_esw_br *bridge, struct ice_esw_br_port *br_port) { struct ice_esw_br_fdb_entry *fdb_entry, *tmp; struct ice_vsi *vsi = br_port->vsi; list_for_each_entry_safe(fdb_entry, tmp, &bridge->fdb_list, list) { if (br_port == fdb_entry->br_port) ice_eswitch_br_fdb_entry_delete(bridge, fdb_entry); } if (br_port->type == ICE_ESWITCH_BR_UPLINK_PORT && vsi->back) vsi->back->br_port = NULL; else if (vsi->vf && vsi->vf->repr) vsi->vf->repr->br_port = NULL; xa_erase(&bridge->ports, br_port->vsi_idx); ice_eswitch_br_port_vlans_flush(br_port); kfree(br_port); } static struct ice_esw_br_port * ice_eswitch_br_port_init(struct ice_esw_br *bridge) { struct ice_esw_br_port *br_port; br_port = kzalloc(sizeof(*br_port), GFP_KERNEL); if (!br_port) return ERR_PTR(-ENOMEM); xa_init(&br_port->vlans); br_port->bridge = bridge; return br_port; } static int ice_eswitch_br_vf_repr_port_init(struct ice_esw_br *bridge, struct ice_repr *repr) { struct ice_esw_br_port *br_port; int err; br_port = ice_eswitch_br_port_init(bridge); if (IS_ERR(br_port)) return PTR_ERR(br_port); br_port->vsi = repr->src_vsi; br_port->vsi_idx = br_port->vsi->idx; br_port->type = ICE_ESWITCH_BR_VF_REPR_PORT; repr->br_port = br_port; err = xa_insert(&bridge->ports, br_port->vsi_idx, br_port, GFP_KERNEL); if (err) { ice_eswitch_br_port_deinit(bridge, br_port); return err; } return 0; } static int ice_eswitch_br_uplink_port_init(struct ice_esw_br *bridge, struct ice_pf *pf) { struct ice_vsi *vsi = pf->switchdev.uplink_vsi; struct ice_esw_br_port *br_port; int err; br_port = ice_eswitch_br_port_init(bridge); if (IS_ERR(br_port)) return PTR_ERR(br_port); br_port->vsi = vsi; br_port->vsi_idx = br_port->vsi->idx; br_port->type = ICE_ESWITCH_BR_UPLINK_PORT; pf->br_port = br_port; err = xa_insert(&bridge->ports, br_port->vsi_idx, br_port, GFP_KERNEL); if (err) { ice_eswitch_br_port_deinit(bridge, br_port); return err; } return 0; } static void ice_eswitch_br_ports_flush(struct ice_esw_br *bridge) { struct ice_esw_br_port *port; unsigned long i; xa_for_each(&bridge->ports, i, port) ice_eswitch_br_port_deinit(bridge, port); } static void ice_eswitch_br_deinit(struct ice_esw_br_offloads *br_offloads, struct ice_esw_br *bridge) { if (!bridge) return; /* Cleanup all the ports that were added asynchronously * through NETDEV_CHANGEUPPER event. */ ice_eswitch_br_ports_flush(bridge); WARN_ON(!xa_empty(&bridge->ports)); xa_destroy(&bridge->ports); rhashtable_destroy(&bridge->fdb_ht); br_offloads->bridge = NULL; kfree(bridge); } static struct ice_esw_br * ice_eswitch_br_init(struct ice_esw_br_offloads *br_offloads, int ifindex) { struct ice_esw_br *bridge; int err; bridge = kzalloc(sizeof(*bridge), GFP_KERNEL); if (!bridge) return ERR_PTR(-ENOMEM); err = rhashtable_init(&bridge->fdb_ht, &ice_fdb_ht_params); if (err) { kfree(bridge); return ERR_PTR(err); } INIT_LIST_HEAD(&bridge->fdb_list); bridge->br_offloads = br_offloads; bridge->ifindex = ifindex; bridge->ageing_time = clock_t_to_jiffies(BR_DEFAULT_AGEING_TIME); xa_init(&bridge->ports); br_offloads->bridge = bridge; return bridge; } static struct ice_esw_br * ice_eswitch_br_get(struct ice_esw_br_offloads *br_offloads, int ifindex, struct netlink_ext_ack *extack) { struct ice_esw_br *bridge = br_offloads->bridge; if (bridge) { if (bridge->ifindex != ifindex) { NL_SET_ERR_MSG_MOD(extack, "Only one bridge is supported per eswitch"); return ERR_PTR(-EOPNOTSUPP); } return bridge; } /* Create the bridge if it doesn't exist yet */ bridge = ice_eswitch_br_init(br_offloads, ifindex); if (IS_ERR(bridge)) NL_SET_ERR_MSG_MOD(extack, "Failed to init the bridge"); return bridge; } static void ice_eswitch_br_verify_deinit(struct ice_esw_br_offloads *br_offloads, struct ice_esw_br *bridge) { /* Remove the bridge if it exists and there are no ports left */ if (!bridge || !xa_empty(&bridge->ports)) return; ice_eswitch_br_deinit(br_offloads, bridge); } static int ice_eswitch_br_port_unlink(struct ice_esw_br_offloads *br_offloads, struct net_device *dev, int ifindex, struct netlink_ext_ack *extack) { struct ice_esw_br_port *br_port = ice_eswitch_br_netdev_to_port(dev); struct ice_esw_br *bridge; if (!br_port) { NL_SET_ERR_MSG_MOD(extack, "Port representor is not attached to any bridge"); return -EINVAL; } if (br_port->bridge->ifindex != ifindex) { NL_SET_ERR_MSG_MOD(extack, "Port representor is attached to another bridge"); return -EINVAL; } bridge = br_port->bridge; trace_ice_eswitch_br_port_unlink(br_port); ice_eswitch_br_port_deinit(br_port->bridge, br_port); ice_eswitch_br_verify_deinit(br_offloads, bridge); return 0; } static int ice_eswitch_br_port_link(struct ice_esw_br_offloads *br_offloads, struct net_device *dev, int ifindex, struct netlink_ext_ack *extack) { struct ice_esw_br *bridge; int err; if (ice_eswitch_br_netdev_to_port(dev)) { NL_SET_ERR_MSG_MOD(extack, "Port is already attached to the bridge"); return -EINVAL; } bridge = ice_eswitch_br_get(br_offloads, ifindex, extack); if (IS_ERR(bridge)) return PTR_ERR(bridge); if (ice_is_port_repr_netdev(dev)) { struct ice_repr *repr = ice_netdev_to_repr(dev); err = ice_eswitch_br_vf_repr_port_init(bridge, repr); trace_ice_eswitch_br_port_link(repr->br_port); } else { struct net_device *ice_dev; struct ice_pf *pf; if (netif_is_lag_master(dev)) ice_dev = ice_eswitch_br_get_uplink_from_lag(dev); else ice_dev = dev; if (!ice_dev) return 0; pf = ice_netdev_to_pf(ice_dev); err = ice_eswitch_br_uplink_port_init(bridge, pf); trace_ice_eswitch_br_port_link(pf->br_port); } if (err) { NL_SET_ERR_MSG_MOD(extack, "Failed to init bridge port"); goto err_port_init; } return 0; err_port_init: ice_eswitch_br_verify_deinit(br_offloads, bridge); return err; } static int ice_eswitch_br_port_changeupper(struct notifier_block *nb, void *ptr) { struct net_device *dev = netdev_notifier_info_to_dev(ptr); struct netdev_notifier_changeupper_info *info = ptr; struct ice_esw_br_offloads *br_offloads; struct netlink_ext_ack *extack; struct net_device *upper; br_offloads = ice_nb_to_br_offloads(nb, netdev_nb); if (!ice_eswitch_br_is_dev_valid(dev)) return 0; upper = info->upper_dev; if (!netif_is_bridge_master(upper)) return 0; extack = netdev_notifier_info_to_extack(&info->info); if (info->linking) return ice_eswitch_br_port_link(br_offloads, dev, upper->ifindex, extack); else return ice_eswitch_br_port_unlink(br_offloads, dev, upper->ifindex, extack); } static int ice_eswitch_br_port_event(struct notifier_block *nb, unsigned long event, void *ptr) { int err = 0; switch (event) { case NETDEV_CHANGEUPPER: err = ice_eswitch_br_port_changeupper(nb, ptr); break; } return notifier_from_errno(err); } static void ice_eswitch_br_offloads_dealloc(struct ice_pf *pf) { struct ice_esw_br_offloads *br_offloads = pf->switchdev.br_offloads; ASSERT_RTNL(); if (!br_offloads) return; ice_eswitch_br_deinit(br_offloads, br_offloads->bridge); pf->switchdev.br_offloads = NULL; kfree(br_offloads); } static struct ice_esw_br_offloads * ice_eswitch_br_offloads_alloc(struct ice_pf *pf) { struct ice_esw_br_offloads *br_offloads; ASSERT_RTNL(); if (pf->switchdev.br_offloads) return ERR_PTR(-EEXIST); br_offloads = kzalloc(sizeof(*br_offloads), GFP_KERNEL); if (!br_offloads) return ERR_PTR(-ENOMEM); pf->switchdev.br_offloads = br_offloads; br_offloads->pf = pf; return br_offloads; } void ice_eswitch_br_offloads_deinit(struct ice_pf *pf) { struct ice_esw_br_offloads *br_offloads; br_offloads = pf->switchdev.br_offloads; if (!br_offloads) return; cancel_delayed_work_sync(&br_offloads->update_work); unregister_netdevice_notifier(&br_offloads->netdev_nb); unregister_switchdev_blocking_notifier(&br_offloads->switchdev_blk); unregister_switchdev_notifier(&br_offloads->switchdev_nb); destroy_workqueue(br_offloads->wq); /* Although notifier block is unregistered just before, * so we don't get any new events, some events might be * already in progress. Hold the rtnl lock and wait for * them to finished. */ rtnl_lock(); ice_eswitch_br_offloads_dealloc(pf); rtnl_unlock(); } static void ice_eswitch_br_update(struct ice_esw_br_offloads *br_offloads) { struct ice_esw_br *bridge = br_offloads->bridge; struct ice_esw_br_fdb_entry *entry, *tmp; if (!bridge) return; rtnl_lock(); list_for_each_entry_safe(entry, tmp, &bridge->fdb_list, list) { if (entry->flags & ICE_ESWITCH_BR_FDB_ADDED_BY_USER) continue; if (time_is_after_eq_jiffies(entry->last_use + bridge->ageing_time)) continue; ice_eswitch_br_fdb_entry_notify_and_cleanup(bridge, entry); } rtnl_unlock(); } static void ice_eswitch_br_update_work(struct work_struct *work) { struct ice_esw_br_offloads *br_offloads; br_offloads = ice_work_to_br_offloads(work); ice_eswitch_br_update(br_offloads); queue_delayed_work(br_offloads->wq, &br_offloads->update_work, ICE_ESW_BRIDGE_UPDATE_INTERVAL); } int ice_eswitch_br_offloads_init(struct ice_pf *pf) { struct ice_esw_br_offloads *br_offloads; struct device *dev = ice_pf_to_dev(pf); int err; rtnl_lock(); br_offloads = ice_eswitch_br_offloads_alloc(pf); rtnl_unlock(); if (IS_ERR(br_offloads)) { dev_err(dev, "Failed to init eswitch bridge\n"); return PTR_ERR(br_offloads); } br_offloads->wq = alloc_ordered_workqueue("ice_bridge_wq", 0); if (!br_offloads->wq) { err = -ENOMEM; dev_err(dev, "Failed to allocate bridge workqueue\n"); goto err_alloc_wq; } br_offloads->switchdev_nb.notifier_call = ice_eswitch_br_switchdev_event; err = register_switchdev_notifier(&br_offloads->switchdev_nb); if (err) { dev_err(dev, "Failed to register switchdev notifier\n"); goto err_reg_switchdev_nb; } br_offloads->switchdev_blk.notifier_call = ice_eswitch_br_event_blocking; err = register_switchdev_blocking_notifier(&br_offloads->switchdev_blk); if (err) { dev_err(dev, "Failed to register bridge blocking switchdev notifier\n"); goto err_reg_switchdev_blk; } br_offloads->netdev_nb.notifier_call = ice_eswitch_br_port_event; err = register_netdevice_notifier(&br_offloads->netdev_nb); if (err) { dev_err(dev, "Failed to register bridge port event notifier\n"); goto err_reg_netdev_nb; } INIT_DELAYED_WORK(&br_offloads->update_work, ice_eswitch_br_update_work); queue_delayed_work(br_offloads->wq, &br_offloads->update_work, ICE_ESW_BRIDGE_UPDATE_INTERVAL); return 0; err_reg_netdev_nb: unregister_switchdev_blocking_notifier(&br_offloads->switchdev_blk); err_reg_switchdev_blk: unregister_switchdev_notifier(&br_offloads->switchdev_nb); err_reg_switchdev_nb: destroy_workqueue(br_offloads->wq); err_alloc_wq: rtnl_lock(); ice_eswitch_br_offloads_dealloc(pf); rtnl_unlock(); return err; }
linux-master
drivers/net/ethernet/intel/ice/ice_eswitch_br.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2018, Intel Corporation. */ #include "ice.h" #include "ice_vf_lib_private.h" #include "ice_base.h" #include "ice_lib.h" #include "ice_fltr.h" #include "ice_dcb_lib.h" #include "ice_flow.h" #include "ice_eswitch.h" #include "ice_virtchnl_allowlist.h" #include "ice_flex_pipe.h" #include "ice_vf_vsi_vlan_ops.h" #include "ice_vlan.h" /** * ice_free_vf_entries - Free all VF entries from the hash table * @pf: pointer to the PF structure * * Iterate over the VF hash table, removing and releasing all VF entries. * Called during VF teardown or as cleanup during failed VF initialization. */ static void ice_free_vf_entries(struct ice_pf *pf) { struct ice_vfs *vfs = &pf->vfs; struct hlist_node *tmp; struct ice_vf *vf; unsigned int bkt; /* Remove all VFs from the hash table and release their main * reference. Once all references to the VF are dropped, ice_put_vf() * will call ice_release_vf which will remove the VF memory. */ lockdep_assert_held(&vfs->table_lock); hash_for_each_safe(vfs->table, bkt, tmp, vf, entry) { hash_del_rcu(&vf->entry); ice_put_vf(vf); } } /** * ice_free_vf_res - Free a VF's resources * @vf: pointer to the VF info */ static void ice_free_vf_res(struct ice_vf *vf) { struct ice_pf *pf = vf->pf; int i, last_vector_idx; /* First, disable VF's configuration API to prevent OS from * accessing the VF's VSI after it's freed or invalidated. */ clear_bit(ICE_VF_STATE_INIT, vf->vf_states); ice_vf_fdir_exit(vf); /* free VF control VSI */ if (vf->ctrl_vsi_idx != ICE_NO_VSI) ice_vf_ctrl_vsi_release(vf); /* free VSI and disconnect it from the parent uplink */ if (vf->lan_vsi_idx != ICE_NO_VSI) { ice_vf_vsi_release(vf); vf->num_mac = 0; } last_vector_idx = vf->first_vector_idx + pf->vfs.num_msix_per - 1; /* clear VF MDD event information */ memset(&vf->mdd_tx_events, 0, sizeof(vf->mdd_tx_events)); memset(&vf->mdd_rx_events, 0, sizeof(vf->mdd_rx_events)); /* Disable interrupts so that VF starts in a known state */ for (i = vf->first_vector_idx; i <= last_vector_idx; i++) { wr32(&pf->hw, GLINT_DYN_CTL(i), GLINT_DYN_CTL_CLEARPBA_M); ice_flush(&pf->hw); } /* reset some of the state variables keeping track of the resources */ clear_bit(ICE_VF_STATE_MC_PROMISC, vf->vf_states); clear_bit(ICE_VF_STATE_UC_PROMISC, vf->vf_states); } /** * ice_dis_vf_mappings * @vf: pointer to the VF structure */ static void ice_dis_vf_mappings(struct ice_vf *vf) { struct ice_pf *pf = vf->pf; struct ice_vsi *vsi; struct device *dev; int first, last, v; struct ice_hw *hw; hw = &pf->hw; vsi = ice_get_vf_vsi(vf); if (WARN_ON(!vsi)) return; dev = ice_pf_to_dev(pf); wr32(hw, VPINT_ALLOC(vf->vf_id), 0); wr32(hw, VPINT_ALLOC_PCI(vf->vf_id), 0); first = vf->first_vector_idx; last = first + pf->vfs.num_msix_per - 1; for (v = first; v <= last; v++) { u32 reg; reg = (((1 << GLINT_VECT2FUNC_IS_PF_S) & GLINT_VECT2FUNC_IS_PF_M) | ((hw->pf_id << GLINT_VECT2FUNC_PF_NUM_S) & GLINT_VECT2FUNC_PF_NUM_M)); wr32(hw, GLINT_VECT2FUNC(v), reg); } if (vsi->tx_mapping_mode == ICE_VSI_MAP_CONTIG) wr32(hw, VPLAN_TX_QBASE(vf->vf_id), 0); else dev_err(dev, "Scattered mode for VF Tx queues is not yet implemented\n"); if (vsi->rx_mapping_mode == ICE_VSI_MAP_CONTIG) wr32(hw, VPLAN_RX_QBASE(vf->vf_id), 0); else dev_err(dev, "Scattered mode for VF Rx queues is not yet implemented\n"); } /** * ice_sriov_free_msix_res - Reset/free any used MSIX resources * @pf: pointer to the PF structure * * Since no MSIX entries are taken from the pf->irq_tracker then just clear * the pf->sriov_base_vector. * * Returns 0 on success, and -EINVAL on error. */ static int ice_sriov_free_msix_res(struct ice_pf *pf) { if (!pf) return -EINVAL; pf->sriov_base_vector = 0; return 0; } /** * ice_free_vfs - Free all VFs * @pf: pointer to the PF structure */ void ice_free_vfs(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); struct ice_vfs *vfs = &pf->vfs; struct ice_hw *hw = &pf->hw; struct ice_vf *vf; unsigned int bkt; if (!ice_has_vfs(pf)) return; while (test_and_set_bit(ICE_VF_DIS, pf->state)) usleep_range(1000, 2000); /* Disable IOV before freeing resources. This lets any VF drivers * running in the host get themselves cleaned up before we yank * the carpet out from underneath their feet. */ if (!pci_vfs_assigned(pf->pdev)) pci_disable_sriov(pf->pdev); else dev_warn(dev, "VFs are assigned - not disabling SR-IOV\n"); mutex_lock(&vfs->table_lock); ice_eswitch_release(pf); ice_for_each_vf(pf, bkt, vf) { mutex_lock(&vf->cfg_lock); ice_dis_vf_qs(vf); if (test_bit(ICE_VF_STATE_INIT, vf->vf_states)) { /* disable VF qp mappings and set VF disable state */ ice_dis_vf_mappings(vf); set_bit(ICE_VF_STATE_DIS, vf->vf_states); ice_free_vf_res(vf); } if (!pci_vfs_assigned(pf->pdev)) { u32 reg_idx, bit_idx; reg_idx = (hw->func_caps.vf_base_id + vf->vf_id) / 32; bit_idx = (hw->func_caps.vf_base_id + vf->vf_id) % 32; wr32(hw, GLGEN_VFLRSTAT(reg_idx), BIT(bit_idx)); } /* clear malicious info since the VF is getting released */ list_del(&vf->mbx_info.list_entry); mutex_unlock(&vf->cfg_lock); } if (ice_sriov_free_msix_res(pf)) dev_err(dev, "Failed to free MSIX resources used by SR-IOV\n"); vfs->num_qps_per = 0; ice_free_vf_entries(pf); mutex_unlock(&vfs->table_lock); clear_bit(ICE_VF_DIS, pf->state); clear_bit(ICE_FLAG_SRIOV_ENA, pf->flags); } /** * ice_vf_vsi_setup - Set up a VF VSI * @vf: VF to setup VSI for * * Returns pointer to the successfully allocated VSI struct on success, * otherwise returns NULL on failure. */ static struct ice_vsi *ice_vf_vsi_setup(struct ice_vf *vf) { struct ice_vsi_cfg_params params = {}; struct ice_pf *pf = vf->pf; struct ice_vsi *vsi; params.type = ICE_VSI_VF; params.pi = ice_vf_get_port_info(vf); params.vf = vf; params.flags = ICE_VSI_FLAG_INIT; vsi = ice_vsi_setup(pf, &params); if (!vsi) { dev_err(ice_pf_to_dev(pf), "Failed to create VF VSI\n"); ice_vf_invalidate_vsi(vf); return NULL; } vf->lan_vsi_idx = vsi->idx; vf->lan_vsi_num = vsi->vsi_num; return vsi; } /** * ice_calc_vf_first_vector_idx - Calculate MSIX vector index in the PF space * @pf: pointer to PF structure * @vf: pointer to VF that the first MSIX vector index is being calculated for * * This returns the first MSIX vector index in PF space that is used by this VF. * This index is used when accessing PF relative registers such as * GLINT_VECT2FUNC and GLINT_DYN_CTL. * This will always be the OICR index in the AVF driver so any functionality * using vf->first_vector_idx for queue configuration will have to increment by * 1 to avoid meddling with the OICR index. */ static int ice_calc_vf_first_vector_idx(struct ice_pf *pf, struct ice_vf *vf) { return pf->sriov_base_vector + vf->vf_id * pf->vfs.num_msix_per; } /** * ice_ena_vf_msix_mappings - enable VF MSIX mappings in hardware * @vf: VF to enable MSIX mappings for * * Some of the registers need to be indexed/configured using hardware global * device values and other registers need 0-based values, which represent PF * based values. */ static void ice_ena_vf_msix_mappings(struct ice_vf *vf) { int device_based_first_msix, device_based_last_msix; int pf_based_first_msix, pf_based_last_msix, v; struct ice_pf *pf = vf->pf; int device_based_vf_id; struct ice_hw *hw; u32 reg; hw = &pf->hw; pf_based_first_msix = vf->first_vector_idx; pf_based_last_msix = (pf_based_first_msix + pf->vfs.num_msix_per) - 1; device_based_first_msix = pf_based_first_msix + pf->hw.func_caps.common_cap.msix_vector_first_id; device_based_last_msix = (device_based_first_msix + pf->vfs.num_msix_per) - 1; device_based_vf_id = vf->vf_id + hw->func_caps.vf_base_id; reg = (((device_based_first_msix << VPINT_ALLOC_FIRST_S) & VPINT_ALLOC_FIRST_M) | ((device_based_last_msix << VPINT_ALLOC_LAST_S) & VPINT_ALLOC_LAST_M) | VPINT_ALLOC_VALID_M); wr32(hw, VPINT_ALLOC(vf->vf_id), reg); reg = (((device_based_first_msix << VPINT_ALLOC_PCI_FIRST_S) & VPINT_ALLOC_PCI_FIRST_M) | ((device_based_last_msix << VPINT_ALLOC_PCI_LAST_S) & VPINT_ALLOC_PCI_LAST_M) | VPINT_ALLOC_PCI_VALID_M); wr32(hw, VPINT_ALLOC_PCI(vf->vf_id), reg); /* map the interrupts to its functions */ for (v = pf_based_first_msix; v <= pf_based_last_msix; v++) { reg = (((device_based_vf_id << GLINT_VECT2FUNC_VF_NUM_S) & GLINT_VECT2FUNC_VF_NUM_M) | ((hw->pf_id << GLINT_VECT2FUNC_PF_NUM_S) & GLINT_VECT2FUNC_PF_NUM_M)); wr32(hw, GLINT_VECT2FUNC(v), reg); } /* Map mailbox interrupt to VF MSI-X vector 0 */ wr32(hw, VPINT_MBX_CTL(device_based_vf_id), VPINT_MBX_CTL_CAUSE_ENA_M); } /** * ice_ena_vf_q_mappings - enable Rx/Tx queue mappings for a VF * @vf: VF to enable the mappings for * @max_txq: max Tx queues allowed on the VF's VSI * @max_rxq: max Rx queues allowed on the VF's VSI */ static void ice_ena_vf_q_mappings(struct ice_vf *vf, u16 max_txq, u16 max_rxq) { struct device *dev = ice_pf_to_dev(vf->pf); struct ice_vsi *vsi = ice_get_vf_vsi(vf); struct ice_hw *hw = &vf->pf->hw; u32 reg; if (WARN_ON(!vsi)) return; /* set regardless of mapping mode */ wr32(hw, VPLAN_TXQ_MAPENA(vf->vf_id), VPLAN_TXQ_MAPENA_TX_ENA_M); /* VF Tx queues allocation */ if (vsi->tx_mapping_mode == ICE_VSI_MAP_CONTIG) { /* set the VF PF Tx queue range * VFNUMQ value should be set to (number of queues - 1). A value * of 0 means 1 queue and a value of 255 means 256 queues */ reg = (((vsi->txq_map[0] << VPLAN_TX_QBASE_VFFIRSTQ_S) & VPLAN_TX_QBASE_VFFIRSTQ_M) | (((max_txq - 1) << VPLAN_TX_QBASE_VFNUMQ_S) & VPLAN_TX_QBASE_VFNUMQ_M)); wr32(hw, VPLAN_TX_QBASE(vf->vf_id), reg); } else { dev_err(dev, "Scattered mode for VF Tx queues is not yet implemented\n"); } /* set regardless of mapping mode */ wr32(hw, VPLAN_RXQ_MAPENA(vf->vf_id), VPLAN_RXQ_MAPENA_RX_ENA_M); /* VF Rx queues allocation */ if (vsi->rx_mapping_mode == ICE_VSI_MAP_CONTIG) { /* set the VF PF Rx queue range * VFNUMQ value should be set to (number of queues - 1). A value * of 0 means 1 queue and a value of 255 means 256 queues */ reg = (((vsi->rxq_map[0] << VPLAN_RX_QBASE_VFFIRSTQ_S) & VPLAN_RX_QBASE_VFFIRSTQ_M) | (((max_rxq - 1) << VPLAN_RX_QBASE_VFNUMQ_S) & VPLAN_RX_QBASE_VFNUMQ_M)); wr32(hw, VPLAN_RX_QBASE(vf->vf_id), reg); } else { dev_err(dev, "Scattered mode for VF Rx queues is not yet implemented\n"); } } /** * ice_ena_vf_mappings - enable VF MSIX and queue mapping * @vf: pointer to the VF structure */ static void ice_ena_vf_mappings(struct ice_vf *vf) { struct ice_vsi *vsi = ice_get_vf_vsi(vf); if (WARN_ON(!vsi)) return; ice_ena_vf_msix_mappings(vf); ice_ena_vf_q_mappings(vf, vsi->alloc_txq, vsi->alloc_rxq); } /** * ice_calc_vf_reg_idx - Calculate the VF's register index in the PF space * @vf: VF to calculate the register index for * @q_vector: a q_vector associated to the VF */ int ice_calc_vf_reg_idx(struct ice_vf *vf, struct ice_q_vector *q_vector) { struct ice_pf *pf; if (!vf || !q_vector) return -EINVAL; pf = vf->pf; /* always add one to account for the OICR being the first MSIX */ return pf->sriov_base_vector + pf->vfs.num_msix_per * vf->vf_id + q_vector->v_idx + 1; } /** * ice_sriov_set_msix_res - Set any used MSIX resources * @pf: pointer to PF structure * @num_msix_needed: number of MSIX vectors needed for all SR-IOV VFs * * This function allows SR-IOV resources to be taken from the end of the PF's * allowed HW MSIX vectors so that the irq_tracker will not be affected. We * just set the pf->sriov_base_vector and return success. * * If there are not enough resources available, return an error. This should * always be caught by ice_set_per_vf_res(). * * Return 0 on success, and -EINVAL when there are not enough MSIX vectors * in the PF's space available for SR-IOV. */ static int ice_sriov_set_msix_res(struct ice_pf *pf, u16 num_msix_needed) { u16 total_vectors = pf->hw.func_caps.common_cap.num_msix_vectors; int vectors_used = ice_get_max_used_msix_vector(pf); int sriov_base_vector; sriov_base_vector = total_vectors - num_msix_needed; /* make sure we only grab irq_tracker entries from the list end and * that we have enough available MSIX vectors */ if (sriov_base_vector < vectors_used) return -EINVAL; pf->sriov_base_vector = sriov_base_vector; return 0; } /** * ice_set_per_vf_res - check if vectors and queues are available * @pf: pointer to the PF structure * @num_vfs: the number of SR-IOV VFs being configured * * First, determine HW interrupts from common pool. If we allocate fewer VFs, we * get more vectors and can enable more queues per VF. Note that this does not * grab any vectors from the SW pool already allocated. Also note, that all * vector counts include one for each VF's miscellaneous interrupt vector * (i.e. OICR). * * Minimum VFs - 2 vectors, 1 queue pair * Small VFs - 5 vectors, 4 queue pairs * Medium VFs - 17 vectors, 16 queue pairs * * Second, determine number of queue pairs per VF by starting with a pre-defined * maximum each VF supports. If this is not possible, then we adjust based on * queue pairs available on the device. * * Lastly, set queue and MSI-X VF variables tracked by the PF so it can be used * by each VF during VF initialization and reset. */ static int ice_set_per_vf_res(struct ice_pf *pf, u16 num_vfs) { int vectors_used = ice_get_max_used_msix_vector(pf); u16 num_msix_per_vf, num_txq, num_rxq, avail_qs; int msix_avail_per_vf, msix_avail_for_sriov; struct device *dev = ice_pf_to_dev(pf); int err; lockdep_assert_held(&pf->vfs.table_lock); if (!num_vfs) return -EINVAL; /* determine MSI-X resources per VF */ msix_avail_for_sriov = pf->hw.func_caps.common_cap.num_msix_vectors - vectors_used; msix_avail_per_vf = msix_avail_for_sriov / num_vfs; if (msix_avail_per_vf >= ICE_NUM_VF_MSIX_MED) { num_msix_per_vf = ICE_NUM_VF_MSIX_MED; } else if (msix_avail_per_vf >= ICE_NUM_VF_MSIX_SMALL) { num_msix_per_vf = ICE_NUM_VF_MSIX_SMALL; } else if (msix_avail_per_vf >= ICE_NUM_VF_MSIX_MULTIQ_MIN) { num_msix_per_vf = ICE_NUM_VF_MSIX_MULTIQ_MIN; } else if (msix_avail_per_vf >= ICE_MIN_INTR_PER_VF) { num_msix_per_vf = ICE_MIN_INTR_PER_VF; } else { dev_err(dev, "Only %d MSI-X interrupts available for SR-IOV. Not enough to support minimum of %d MSI-X interrupts per VF for %d VFs\n", msix_avail_for_sriov, ICE_MIN_INTR_PER_VF, num_vfs); return -ENOSPC; } num_txq = min_t(u16, num_msix_per_vf - ICE_NONQ_VECS_VF, ICE_MAX_RSS_QS_PER_VF); avail_qs = ice_get_avail_txq_count(pf) / num_vfs; if (!avail_qs) num_txq = 0; else if (num_txq > avail_qs) num_txq = rounddown_pow_of_two(avail_qs); num_rxq = min_t(u16, num_msix_per_vf - ICE_NONQ_VECS_VF, ICE_MAX_RSS_QS_PER_VF); avail_qs = ice_get_avail_rxq_count(pf) / num_vfs; if (!avail_qs) num_rxq = 0; else if (num_rxq > avail_qs) num_rxq = rounddown_pow_of_two(avail_qs); if (num_txq < ICE_MIN_QS_PER_VF || num_rxq < ICE_MIN_QS_PER_VF) { dev_err(dev, "Not enough queues to support minimum of %d queue pairs per VF for %d VFs\n", ICE_MIN_QS_PER_VF, num_vfs); return -ENOSPC; } err = ice_sriov_set_msix_res(pf, num_msix_per_vf * num_vfs); if (err) { dev_err(dev, "Unable to set MSI-X resources for %d VFs, err %d\n", num_vfs, err); return err; } /* only allow equal Tx/Rx queue count (i.e. queue pairs) */ pf->vfs.num_qps_per = min_t(int, num_txq, num_rxq); pf->vfs.num_msix_per = num_msix_per_vf; dev_info(dev, "Enabling %d VFs with %d vectors and %d queues per VF\n", num_vfs, pf->vfs.num_msix_per, pf->vfs.num_qps_per); return 0; } /** * ice_init_vf_vsi_res - initialize/setup VF VSI resources * @vf: VF to initialize/setup the VSI for * * This function creates a VSI for the VF, adds a VLAN 0 filter, and sets up the * VF VSI's broadcast filter and is only used during initial VF creation. */ static int ice_init_vf_vsi_res(struct ice_vf *vf) { struct ice_pf *pf = vf->pf; struct ice_vsi *vsi; int err; vf->first_vector_idx = ice_calc_vf_first_vector_idx(pf, vf); vsi = ice_vf_vsi_setup(vf); if (!vsi) return -ENOMEM; err = ice_vf_init_host_cfg(vf, vsi); if (err) goto release_vsi; return 0; release_vsi: ice_vf_vsi_release(vf); return err; } /** * ice_start_vfs - start VFs so they are ready to be used by SR-IOV * @pf: PF the VFs are associated with */ static int ice_start_vfs(struct ice_pf *pf) { struct ice_hw *hw = &pf->hw; unsigned int bkt, it_cnt; struct ice_vf *vf; int retval; lockdep_assert_held(&pf->vfs.table_lock); it_cnt = 0; ice_for_each_vf(pf, bkt, vf) { vf->vf_ops->clear_reset_trigger(vf); retval = ice_init_vf_vsi_res(vf); if (retval) { dev_err(ice_pf_to_dev(pf), "Failed to initialize VSI resources for VF %d, error %d\n", vf->vf_id, retval); goto teardown; } set_bit(ICE_VF_STATE_INIT, vf->vf_states); ice_ena_vf_mappings(vf); wr32(hw, VFGEN_RSTAT(vf->vf_id), VIRTCHNL_VFR_VFACTIVE); it_cnt++; } ice_flush(hw); return 0; teardown: ice_for_each_vf(pf, bkt, vf) { if (it_cnt == 0) break; ice_dis_vf_mappings(vf); ice_vf_vsi_release(vf); it_cnt--; } return retval; } /** * ice_sriov_free_vf - Free VF memory after all references are dropped * @vf: pointer to VF to free * * Called by ice_put_vf through ice_release_vf once the last reference to a VF * structure has been dropped. */ static void ice_sriov_free_vf(struct ice_vf *vf) { mutex_destroy(&vf->cfg_lock); kfree_rcu(vf, rcu); } /** * ice_sriov_clear_reset_state - clears VF Reset status register * @vf: the vf to configure */ static void ice_sriov_clear_reset_state(struct ice_vf *vf) { struct ice_hw *hw = &vf->pf->hw; /* Clear the reset status register so that VF immediately sees that * the device is resetting, even if hardware hasn't yet gotten around * to clearing VFGEN_RSTAT for us. */ wr32(hw, VFGEN_RSTAT(vf->vf_id), VIRTCHNL_VFR_INPROGRESS); } /** * ice_sriov_clear_mbx_register - clears SRIOV VF's mailbox registers * @vf: the vf to configure */ static void ice_sriov_clear_mbx_register(struct ice_vf *vf) { struct ice_pf *pf = vf->pf; wr32(&pf->hw, VF_MBX_ARQLEN(vf->vf_id), 0); wr32(&pf->hw, VF_MBX_ATQLEN(vf->vf_id), 0); } /** * ice_sriov_trigger_reset_register - trigger VF reset for SRIOV VF * @vf: pointer to VF structure * @is_vflr: true if reset occurred due to VFLR * * Trigger and cleanup after a VF reset for a SR-IOV VF. */ static void ice_sriov_trigger_reset_register(struct ice_vf *vf, bool is_vflr) { struct ice_pf *pf = vf->pf; u32 reg, reg_idx, bit_idx; unsigned int vf_abs_id, i; struct device *dev; struct ice_hw *hw; dev = ice_pf_to_dev(pf); hw = &pf->hw; vf_abs_id = vf->vf_id + hw->func_caps.vf_base_id; /* In the case of a VFLR, HW has already reset the VF and we just need * to clean up. Otherwise we must first trigger the reset using the * VFRTRIG register. */ if (!is_vflr) { reg = rd32(hw, VPGEN_VFRTRIG(vf->vf_id)); reg |= VPGEN_VFRTRIG_VFSWR_M; wr32(hw, VPGEN_VFRTRIG(vf->vf_id), reg); } /* clear the VFLR bit in GLGEN_VFLRSTAT */ reg_idx = (vf_abs_id) / 32; bit_idx = (vf_abs_id) % 32; wr32(hw, GLGEN_VFLRSTAT(reg_idx), BIT(bit_idx)); ice_flush(hw); wr32(hw, PF_PCI_CIAA, VF_DEVICE_STATUS | (vf_abs_id << PF_PCI_CIAA_VF_NUM_S)); for (i = 0; i < ICE_PCI_CIAD_WAIT_COUNT; i++) { reg = rd32(hw, PF_PCI_CIAD); /* no transactions pending so stop polling */ if ((reg & VF_TRANS_PENDING_M) == 0) break; dev_err(dev, "VF %u PCI transactions stuck\n", vf->vf_id); udelay(ICE_PCI_CIAD_WAIT_DELAY_US); } } /** * ice_sriov_poll_reset_status - poll SRIOV VF reset status * @vf: pointer to VF structure * * Returns true when reset is successful, else returns false */ static bool ice_sriov_poll_reset_status(struct ice_vf *vf) { struct ice_pf *pf = vf->pf; unsigned int i; u32 reg; for (i = 0; i < 10; i++) { /* VF reset requires driver to first reset the VF and then * poll the status register to make sure that the reset * completed successfully. */ reg = rd32(&pf->hw, VPGEN_VFRSTAT(vf->vf_id)); if (reg & VPGEN_VFRSTAT_VFRD_M) return true; /* only sleep if the reset is not done */ usleep_range(10, 20); } return false; } /** * ice_sriov_clear_reset_trigger - enable VF to access hardware * @vf: VF to enabled hardware access for */ static void ice_sriov_clear_reset_trigger(struct ice_vf *vf) { struct ice_hw *hw = &vf->pf->hw; u32 reg; reg = rd32(hw, VPGEN_VFRTRIG(vf->vf_id)); reg &= ~VPGEN_VFRTRIG_VFSWR_M; wr32(hw, VPGEN_VFRTRIG(vf->vf_id), reg); ice_flush(hw); } /** * ice_sriov_create_vsi - Create a new VSI for a VF * @vf: VF to create the VSI for * * This is called by ice_vf_recreate_vsi to create the new VSI after the old * VSI has been released. */ static int ice_sriov_create_vsi(struct ice_vf *vf) { struct ice_vsi *vsi; vsi = ice_vf_vsi_setup(vf); if (!vsi) return -ENOMEM; return 0; } /** * ice_sriov_post_vsi_rebuild - tasks to do after the VF's VSI have been rebuilt * @vf: VF to perform tasks on */ static void ice_sriov_post_vsi_rebuild(struct ice_vf *vf) { ice_ena_vf_mappings(vf); wr32(&vf->pf->hw, VFGEN_RSTAT(vf->vf_id), VIRTCHNL_VFR_VFACTIVE); } static const struct ice_vf_ops ice_sriov_vf_ops = { .reset_type = ICE_VF_RESET, .free = ice_sriov_free_vf, .clear_reset_state = ice_sriov_clear_reset_state, .clear_mbx_register = ice_sriov_clear_mbx_register, .trigger_reset_register = ice_sriov_trigger_reset_register, .poll_reset_status = ice_sriov_poll_reset_status, .clear_reset_trigger = ice_sriov_clear_reset_trigger, .irq_close = NULL, .create_vsi = ice_sriov_create_vsi, .post_vsi_rebuild = ice_sriov_post_vsi_rebuild, }; /** * ice_create_vf_entries - Allocate and insert VF entries * @pf: pointer to the PF structure * @num_vfs: the number of VFs to allocate * * Allocate new VF entries and insert them into the hash table. Set some * basic default fields for initializing the new VFs. * * After this function exits, the hash table will have num_vfs entries * inserted. * * Returns 0 on success or an integer error code on failure. */ static int ice_create_vf_entries(struct ice_pf *pf, u16 num_vfs) { struct ice_vfs *vfs = &pf->vfs; struct ice_vf *vf; u16 vf_id; int err; lockdep_assert_held(&vfs->table_lock); for (vf_id = 0; vf_id < num_vfs; vf_id++) { vf = kzalloc(sizeof(*vf), GFP_KERNEL); if (!vf) { err = -ENOMEM; goto err_free_entries; } kref_init(&vf->refcnt); vf->pf = pf; vf->vf_id = vf_id; /* set sriov vf ops for VFs created during SRIOV flow */ vf->vf_ops = &ice_sriov_vf_ops; ice_initialize_vf_entry(vf); vf->vf_sw_id = pf->first_sw; hash_add_rcu(vfs->table, &vf->entry, vf_id); } return 0; err_free_entries: ice_free_vf_entries(pf); return err; } /** * ice_ena_vfs - enable VFs so they are ready to be used * @pf: pointer to the PF structure * @num_vfs: number of VFs to enable */ static int ice_ena_vfs(struct ice_pf *pf, u16 num_vfs) { struct device *dev = ice_pf_to_dev(pf); struct ice_hw *hw = &pf->hw; int ret; /* Disable global interrupt 0 so we don't try to handle the VFLR. */ wr32(hw, GLINT_DYN_CTL(pf->oicr_irq.index), ICE_ITR_NONE << GLINT_DYN_CTL_ITR_INDX_S); set_bit(ICE_OICR_INTR_DIS, pf->state); ice_flush(hw); ret = pci_enable_sriov(pf->pdev, num_vfs); if (ret) goto err_unroll_intr; mutex_lock(&pf->vfs.table_lock); ret = ice_set_per_vf_res(pf, num_vfs); if (ret) { dev_err(dev, "Not enough resources for %d VFs, err %d. Try with fewer number of VFs\n", num_vfs, ret); goto err_unroll_sriov; } ret = ice_create_vf_entries(pf, num_vfs); if (ret) { dev_err(dev, "Failed to allocate VF entries for %d VFs\n", num_vfs); goto err_unroll_sriov; } ret = ice_start_vfs(pf); if (ret) { dev_err(dev, "Failed to start %d VFs, err %d\n", num_vfs, ret); ret = -EAGAIN; goto err_unroll_vf_entries; } clear_bit(ICE_VF_DIS, pf->state); ret = ice_eswitch_configure(pf); if (ret) { dev_err(dev, "Failed to configure eswitch, err %d\n", ret); goto err_unroll_sriov; } /* rearm global interrupts */ if (test_and_clear_bit(ICE_OICR_INTR_DIS, pf->state)) ice_irq_dynamic_ena(hw, NULL, NULL); mutex_unlock(&pf->vfs.table_lock); return 0; err_unroll_vf_entries: ice_free_vf_entries(pf); err_unroll_sriov: mutex_unlock(&pf->vfs.table_lock); pci_disable_sriov(pf->pdev); err_unroll_intr: /* rearm interrupts here */ ice_irq_dynamic_ena(hw, NULL, NULL); clear_bit(ICE_OICR_INTR_DIS, pf->state); return ret; } /** * ice_pci_sriov_ena - Enable or change number of VFs * @pf: pointer to the PF structure * @num_vfs: number of VFs to allocate * * Returns 0 on success and negative on failure */ static int ice_pci_sriov_ena(struct ice_pf *pf, int num_vfs) { struct device *dev = ice_pf_to_dev(pf); int err; if (!num_vfs) { ice_free_vfs(pf); return 0; } if (num_vfs > pf->vfs.num_supported) { dev_err(dev, "Can't enable %d VFs, max VFs supported is %d\n", num_vfs, pf->vfs.num_supported); return -EOPNOTSUPP; } dev_info(dev, "Enabling %d VFs\n", num_vfs); err = ice_ena_vfs(pf, num_vfs); if (err) { dev_err(dev, "Failed to enable SR-IOV: %d\n", err); return err; } set_bit(ICE_FLAG_SRIOV_ENA, pf->flags); return 0; } /** * ice_check_sriov_allowed - check if SR-IOV is allowed based on various checks * @pf: PF to enabled SR-IOV on */ static int ice_check_sriov_allowed(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); if (!test_bit(ICE_FLAG_SRIOV_CAPABLE, pf->flags)) { dev_err(dev, "This device is not capable of SR-IOV\n"); return -EOPNOTSUPP; } if (ice_is_safe_mode(pf)) { dev_err(dev, "SR-IOV cannot be configured - Device is in Safe Mode\n"); return -EOPNOTSUPP; } if (!ice_pf_state_is_nominal(pf)) { dev_err(dev, "Cannot enable SR-IOV, device not ready\n"); return -EBUSY; } return 0; } /** * ice_sriov_configure - Enable or change number of VFs via sysfs * @pdev: pointer to a pci_dev structure * @num_vfs: number of VFs to allocate or 0 to free VFs * * This function is called when the user updates the number of VFs in sysfs. On * success return whatever num_vfs was set to by the caller. Return negative on * failure. */ int ice_sriov_configure(struct pci_dev *pdev, int num_vfs) { struct ice_pf *pf = pci_get_drvdata(pdev); struct device *dev = ice_pf_to_dev(pf); int err; err = ice_check_sriov_allowed(pf); if (err) return err; if (!num_vfs) { if (!pci_vfs_assigned(pdev)) { ice_free_vfs(pf); return 0; } dev_err(dev, "can't free VFs because some are assigned to VMs.\n"); return -EBUSY; } err = ice_pci_sriov_ena(pf, num_vfs); if (err) return err; return num_vfs; } /** * ice_process_vflr_event - Free VF resources via IRQ calls * @pf: pointer to the PF structure * * called from the VFLR IRQ handler to * free up VF resources and state variables */ void ice_process_vflr_event(struct ice_pf *pf) { struct ice_hw *hw = &pf->hw; struct ice_vf *vf; unsigned int bkt; u32 reg; if (!test_and_clear_bit(ICE_VFLR_EVENT_PENDING, pf->state) || !ice_has_vfs(pf)) return; mutex_lock(&pf->vfs.table_lock); ice_for_each_vf(pf, bkt, vf) { u32 reg_idx, bit_idx; reg_idx = (hw->func_caps.vf_base_id + vf->vf_id) / 32; bit_idx = (hw->func_caps.vf_base_id + vf->vf_id) % 32; /* read GLGEN_VFLRSTAT register to find out the flr VFs */ reg = rd32(hw, GLGEN_VFLRSTAT(reg_idx)); if (reg & BIT(bit_idx)) /* GLGEN_VFLRSTAT bit will be cleared in ice_reset_vf */ ice_reset_vf(vf, ICE_VF_RESET_VFLR | ICE_VF_RESET_LOCK); } mutex_unlock(&pf->vfs.table_lock); } /** * ice_get_vf_from_pfq - get the VF who owns the PF space queue passed in * @pf: PF used to index all VFs * @pfq: queue index relative to the PF's function space * * If no VF is found who owns the pfq then return NULL, otherwise return a * pointer to the VF who owns the pfq * * If this function returns non-NULL, it acquires a reference count of the VF * structure. The caller is responsible for calling ice_put_vf() to drop this * reference. */ static struct ice_vf *ice_get_vf_from_pfq(struct ice_pf *pf, u16 pfq) { struct ice_vf *vf; unsigned int bkt; rcu_read_lock(); ice_for_each_vf_rcu(pf, bkt, vf) { struct ice_vsi *vsi; u16 rxq_idx; vsi = ice_get_vf_vsi(vf); if (!vsi) continue; ice_for_each_rxq(vsi, rxq_idx) if (vsi->rxq_map[rxq_idx] == pfq) { struct ice_vf *found; if (kref_get_unless_zero(&vf->refcnt)) found = vf; else found = NULL; rcu_read_unlock(); return found; } } rcu_read_unlock(); return NULL; } /** * ice_globalq_to_pfq - convert from global queue index to PF space queue index * @pf: PF used for conversion * @globalq: global queue index used to convert to PF space queue index */ static u32 ice_globalq_to_pfq(struct ice_pf *pf, u32 globalq) { return globalq - pf->hw.func_caps.common_cap.rxq_first_id; } /** * ice_vf_lan_overflow_event - handle LAN overflow event for a VF * @pf: PF that the LAN overflow event happened on * @event: structure holding the event information for the LAN overflow event * * Determine if the LAN overflow event was caused by a VF queue. If it was not * caused by a VF, do nothing. If a VF caused this LAN overflow event trigger a * reset on the offending VF. */ void ice_vf_lan_overflow_event(struct ice_pf *pf, struct ice_rq_event_info *event) { u32 gldcb_rtctq, queue; struct ice_vf *vf; gldcb_rtctq = le32_to_cpu(event->desc.params.lan_overflow.prtdcb_ruptq); dev_dbg(ice_pf_to_dev(pf), "GLDCB_RTCTQ: 0x%08x\n", gldcb_rtctq); /* event returns device global Rx queue number */ queue = (gldcb_rtctq & GLDCB_RTCTQ_RXQNUM_M) >> GLDCB_RTCTQ_RXQNUM_S; vf = ice_get_vf_from_pfq(pf, ice_globalq_to_pfq(pf, queue)); if (!vf) return; ice_reset_vf(vf, ICE_VF_RESET_NOTIFY | ICE_VF_RESET_LOCK); ice_put_vf(vf); } /** * ice_set_vf_spoofchk * @netdev: network interface device structure * @vf_id: VF identifier * @ena: flag to enable or disable feature * * Enable or disable VF spoof checking */ int ice_set_vf_spoofchk(struct net_device *netdev, int vf_id, bool ena) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_pf *pf = np->vsi->back; struct ice_vsi *vf_vsi; struct device *dev; struct ice_vf *vf; int ret; dev = ice_pf_to_dev(pf); vf = ice_get_vf_by_id(pf, vf_id); if (!vf) return -EINVAL; ret = ice_check_vf_ready_for_cfg(vf); if (ret) goto out_put_vf; vf_vsi = ice_get_vf_vsi(vf); if (!vf_vsi) { netdev_err(netdev, "VSI %d for VF %d is null\n", vf->lan_vsi_idx, vf->vf_id); ret = -EINVAL; goto out_put_vf; } if (vf_vsi->type != ICE_VSI_VF) { netdev_err(netdev, "Type %d of VSI %d for VF %d is no ICE_VSI_VF\n", vf_vsi->type, vf_vsi->vsi_num, vf->vf_id); ret = -ENODEV; goto out_put_vf; } if (ena == vf->spoofchk) { dev_dbg(dev, "VF spoofchk already %s\n", ena ? "ON" : "OFF"); ret = 0; goto out_put_vf; } ret = ice_vsi_apply_spoofchk(vf_vsi, ena); if (ret) dev_err(dev, "Failed to set spoofchk %s for VF %d VSI %d\n error %d\n", ena ? "ON" : "OFF", vf->vf_id, vf_vsi->vsi_num, ret); else vf->spoofchk = ena; out_put_vf: ice_put_vf(vf); return ret; } /** * ice_get_vf_cfg * @netdev: network interface device structure * @vf_id: VF identifier * @ivi: VF configuration structure * * return VF configuration */ int ice_get_vf_cfg(struct net_device *netdev, int vf_id, struct ifla_vf_info *ivi) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_vf *vf; int ret; vf = ice_get_vf_by_id(pf, vf_id); if (!vf) return -EINVAL; ret = ice_check_vf_ready_for_cfg(vf); if (ret) goto out_put_vf; ivi->vf = vf_id; ether_addr_copy(ivi->mac, vf->hw_lan_addr); /* VF configuration for VLAN and applicable QoS */ ivi->vlan = ice_vf_get_port_vlan_id(vf); ivi->qos = ice_vf_get_port_vlan_prio(vf); if (ice_vf_is_port_vlan_ena(vf)) ivi->vlan_proto = cpu_to_be16(ice_vf_get_port_vlan_tpid(vf)); ivi->trusted = vf->trusted; ivi->spoofchk = vf->spoofchk; if (!vf->link_forced) ivi->linkstate = IFLA_VF_LINK_STATE_AUTO; else if (vf->link_up) ivi->linkstate = IFLA_VF_LINK_STATE_ENABLE; else ivi->linkstate = IFLA_VF_LINK_STATE_DISABLE; ivi->max_tx_rate = vf->max_tx_rate; ivi->min_tx_rate = vf->min_tx_rate; out_put_vf: ice_put_vf(vf); return ret; } /** * ice_set_vf_mac * @netdev: network interface device structure * @vf_id: VF identifier * @mac: MAC address * * program VF MAC address */ int ice_set_vf_mac(struct net_device *netdev, int vf_id, u8 *mac) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_vf *vf; int ret; if (is_multicast_ether_addr(mac)) { netdev_err(netdev, "%pM not a valid unicast address\n", mac); return -EINVAL; } vf = ice_get_vf_by_id(pf, vf_id); if (!vf) return -EINVAL; /* nothing left to do, unicast MAC already set */ if (ether_addr_equal(vf->dev_lan_addr, mac) && ether_addr_equal(vf->hw_lan_addr, mac)) { ret = 0; goto out_put_vf; } ret = ice_check_vf_ready_for_cfg(vf); if (ret) goto out_put_vf; mutex_lock(&vf->cfg_lock); /* VF is notified of its new MAC via the PF's response to the * VIRTCHNL_OP_GET_VF_RESOURCES message after the VF has been reset */ ether_addr_copy(vf->dev_lan_addr, mac); ether_addr_copy(vf->hw_lan_addr, mac); if (is_zero_ether_addr(mac)) { /* VF will send VIRTCHNL_OP_ADD_ETH_ADDR message with its MAC */ vf->pf_set_mac = false; netdev_info(netdev, "Removing MAC on VF %d. VF driver will be reinitialized\n", vf->vf_id); } else { /* PF will add MAC rule for the VF */ vf->pf_set_mac = true; netdev_info(netdev, "Setting MAC %pM on VF %d. VF driver will be reinitialized\n", mac, vf_id); } ice_reset_vf(vf, ICE_VF_RESET_NOTIFY); mutex_unlock(&vf->cfg_lock); out_put_vf: ice_put_vf(vf); return ret; } /** * ice_set_vf_trust * @netdev: network interface device structure * @vf_id: VF identifier * @trusted: Boolean value to enable/disable trusted VF * * Enable or disable a given VF as trusted */ int ice_set_vf_trust(struct net_device *netdev, int vf_id, bool trusted) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_vf *vf; int ret; vf = ice_get_vf_by_id(pf, vf_id); if (!vf) return -EINVAL; if (ice_is_eswitch_mode_switchdev(pf)) { dev_info(ice_pf_to_dev(pf), "Trusted VF is forbidden in switchdev mode\n"); return -EOPNOTSUPP; } ret = ice_check_vf_ready_for_cfg(vf); if (ret) goto out_put_vf; /* Check if already trusted */ if (trusted == vf->trusted) { ret = 0; goto out_put_vf; } mutex_lock(&vf->cfg_lock); vf->trusted = trusted; ice_reset_vf(vf, ICE_VF_RESET_NOTIFY); dev_info(ice_pf_to_dev(pf), "VF %u is now %strusted\n", vf_id, trusted ? "" : "un"); mutex_unlock(&vf->cfg_lock); out_put_vf: ice_put_vf(vf); return ret; } /** * ice_set_vf_link_state * @netdev: network interface device structure * @vf_id: VF identifier * @link_state: required link state * * Set VF's link state, irrespective of physical link state status */ int ice_set_vf_link_state(struct net_device *netdev, int vf_id, int link_state) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_vf *vf; int ret; vf = ice_get_vf_by_id(pf, vf_id); if (!vf) return -EINVAL; ret = ice_check_vf_ready_for_cfg(vf); if (ret) goto out_put_vf; switch (link_state) { case IFLA_VF_LINK_STATE_AUTO: vf->link_forced = false; break; case IFLA_VF_LINK_STATE_ENABLE: vf->link_forced = true; vf->link_up = true; break; case IFLA_VF_LINK_STATE_DISABLE: vf->link_forced = true; vf->link_up = false; break; default: ret = -EINVAL; goto out_put_vf; } ice_vc_notify_vf_link_state(vf); out_put_vf: ice_put_vf(vf); return ret; } /** * ice_calc_all_vfs_min_tx_rate - calculate cumulative min Tx rate on all VFs * @pf: PF associated with VFs */ static int ice_calc_all_vfs_min_tx_rate(struct ice_pf *pf) { struct ice_vf *vf; unsigned int bkt; int rate = 0; rcu_read_lock(); ice_for_each_vf_rcu(pf, bkt, vf) rate += vf->min_tx_rate; rcu_read_unlock(); return rate; } /** * ice_min_tx_rate_oversubscribed - check if min Tx rate causes oversubscription * @vf: VF trying to configure min_tx_rate * @min_tx_rate: min Tx rate in Mbps * * Check if the min_tx_rate being passed in will cause oversubscription of total * min_tx_rate based on the current link speed and all other VFs configured * min_tx_rate * * Return true if the passed min_tx_rate would cause oversubscription, else * return false */ static bool ice_min_tx_rate_oversubscribed(struct ice_vf *vf, int min_tx_rate) { struct ice_vsi *vsi = ice_get_vf_vsi(vf); int all_vfs_min_tx_rate; int link_speed_mbps; if (WARN_ON(!vsi)) return false; link_speed_mbps = ice_get_link_speed_mbps(vsi); all_vfs_min_tx_rate = ice_calc_all_vfs_min_tx_rate(vf->pf); /* this VF's previous rate is being overwritten */ all_vfs_min_tx_rate -= vf->min_tx_rate; if (all_vfs_min_tx_rate + min_tx_rate > link_speed_mbps) { dev_err(ice_pf_to_dev(vf->pf), "min_tx_rate of %d Mbps on VF %u would cause oversubscription of %d Mbps based on the current link speed %d Mbps\n", min_tx_rate, vf->vf_id, all_vfs_min_tx_rate + min_tx_rate - link_speed_mbps, link_speed_mbps); return true; } return false; } /** * ice_set_vf_bw - set min/max VF bandwidth * @netdev: network interface device structure * @vf_id: VF identifier * @min_tx_rate: Minimum Tx rate in Mbps * @max_tx_rate: Maximum Tx rate in Mbps */ int ice_set_vf_bw(struct net_device *netdev, int vf_id, int min_tx_rate, int max_tx_rate) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_vsi *vsi; struct device *dev; struct ice_vf *vf; int ret; dev = ice_pf_to_dev(pf); vf = ice_get_vf_by_id(pf, vf_id); if (!vf) return -EINVAL; ret = ice_check_vf_ready_for_cfg(vf); if (ret) goto out_put_vf; vsi = ice_get_vf_vsi(vf); if (!vsi) { ret = -EINVAL; goto out_put_vf; } if (min_tx_rate && ice_is_dcb_active(pf)) { dev_err(dev, "DCB on PF is currently enabled. VF min Tx rate limiting not allowed on this PF.\n"); ret = -EOPNOTSUPP; goto out_put_vf; } if (ice_min_tx_rate_oversubscribed(vf, min_tx_rate)) { ret = -EINVAL; goto out_put_vf; } if (vf->min_tx_rate != (unsigned int)min_tx_rate) { ret = ice_set_min_bw_limit(vsi, (u64)min_tx_rate * 1000); if (ret) { dev_err(dev, "Unable to set min-tx-rate for VF %d\n", vf->vf_id); goto out_put_vf; } vf->min_tx_rate = min_tx_rate; } if (vf->max_tx_rate != (unsigned int)max_tx_rate) { ret = ice_set_max_bw_limit(vsi, (u64)max_tx_rate * 1000); if (ret) { dev_err(dev, "Unable to set max-tx-rate for VF %d\n", vf->vf_id); goto out_put_vf; } vf->max_tx_rate = max_tx_rate; } out_put_vf: ice_put_vf(vf); return ret; } /** * ice_get_vf_stats - populate some stats for the VF * @netdev: the netdev of the PF * @vf_id: the host OS identifier (0-255) * @vf_stats: pointer to the OS memory to be initialized */ int ice_get_vf_stats(struct net_device *netdev, int vf_id, struct ifla_vf_stats *vf_stats) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_eth_stats *stats; struct ice_vsi *vsi; struct ice_vf *vf; int ret; vf = ice_get_vf_by_id(pf, vf_id); if (!vf) return -EINVAL; ret = ice_check_vf_ready_for_cfg(vf); if (ret) goto out_put_vf; vsi = ice_get_vf_vsi(vf); if (!vsi) { ret = -EINVAL; goto out_put_vf; } ice_update_eth_stats(vsi); stats = &vsi->eth_stats; memset(vf_stats, 0, sizeof(*vf_stats)); vf_stats->rx_packets = stats->rx_unicast + stats->rx_broadcast + stats->rx_multicast; vf_stats->tx_packets = stats->tx_unicast + stats->tx_broadcast + stats->tx_multicast; vf_stats->rx_bytes = stats->rx_bytes; vf_stats->tx_bytes = stats->tx_bytes; vf_stats->broadcast = stats->rx_broadcast; vf_stats->multicast = stats->rx_multicast; vf_stats->rx_dropped = stats->rx_discards; vf_stats->tx_dropped = stats->tx_discards; out_put_vf: ice_put_vf(vf); return ret; } /** * ice_is_supported_port_vlan_proto - make sure the vlan_proto is supported * @hw: hardware structure used to check the VLAN mode * @vlan_proto: VLAN TPID being checked * * If the device is configured in Double VLAN Mode (DVM), then both ETH_P_8021Q * and ETH_P_8021AD are supported. If the device is configured in Single VLAN * Mode (SVM), then only ETH_P_8021Q is supported. */ static bool ice_is_supported_port_vlan_proto(struct ice_hw *hw, u16 vlan_proto) { bool is_supported = false; switch (vlan_proto) { case ETH_P_8021Q: is_supported = true; break; case ETH_P_8021AD: if (ice_is_dvm_ena(hw)) is_supported = true; break; } return is_supported; } /** * ice_set_vf_port_vlan * @netdev: network interface device structure * @vf_id: VF identifier * @vlan_id: VLAN ID being set * @qos: priority setting * @vlan_proto: VLAN protocol * * program VF Port VLAN ID and/or QoS */ int ice_set_vf_port_vlan(struct net_device *netdev, int vf_id, u16 vlan_id, u8 qos, __be16 vlan_proto) { struct ice_pf *pf = ice_netdev_to_pf(netdev); u16 local_vlan_proto = ntohs(vlan_proto); struct device *dev; struct ice_vf *vf; int ret; dev = ice_pf_to_dev(pf); if (vlan_id >= VLAN_N_VID || qos > 7) { dev_err(dev, "Invalid Port VLAN parameters for VF %d, ID %d, QoS %d\n", vf_id, vlan_id, qos); return -EINVAL; } if (!ice_is_supported_port_vlan_proto(&pf->hw, local_vlan_proto)) { dev_err(dev, "VF VLAN protocol 0x%04x is not supported\n", local_vlan_proto); return -EPROTONOSUPPORT; } vf = ice_get_vf_by_id(pf, vf_id); if (!vf) return -EINVAL; ret = ice_check_vf_ready_for_cfg(vf); if (ret) goto out_put_vf; if (ice_vf_get_port_vlan_prio(vf) == qos && ice_vf_get_port_vlan_tpid(vf) == local_vlan_proto && ice_vf_get_port_vlan_id(vf) == vlan_id) { /* duplicate request, so just return success */ dev_dbg(dev, "Duplicate port VLAN %u, QoS %u, TPID 0x%04x request\n", vlan_id, qos, local_vlan_proto); ret = 0; goto out_put_vf; } mutex_lock(&vf->cfg_lock); vf->port_vlan_info = ICE_VLAN(local_vlan_proto, vlan_id, qos); if (ice_vf_is_port_vlan_ena(vf)) dev_info(dev, "Setting VLAN %u, QoS %u, TPID 0x%04x on VF %d\n", vlan_id, qos, local_vlan_proto, vf_id); else dev_info(dev, "Clearing port VLAN on VF %d\n", vf_id); ice_reset_vf(vf, ICE_VF_RESET_NOTIFY); mutex_unlock(&vf->cfg_lock); out_put_vf: ice_put_vf(vf); return ret; } /** * ice_print_vf_rx_mdd_event - print VF Rx malicious driver detect event * @vf: pointer to the VF structure */ void ice_print_vf_rx_mdd_event(struct ice_vf *vf) { struct ice_pf *pf = vf->pf; struct device *dev; dev = ice_pf_to_dev(pf); dev_info(dev, "%d Rx Malicious Driver Detection events detected on PF %d VF %d MAC %pM. mdd-auto-reset-vfs=%s\n", vf->mdd_rx_events.count, pf->hw.pf_id, vf->vf_id, vf->dev_lan_addr, test_bit(ICE_FLAG_MDD_AUTO_RESET_VF, pf->flags) ? "on" : "off"); } /** * ice_print_vfs_mdd_events - print VFs malicious driver detect event * @pf: pointer to the PF structure * * Called from ice_handle_mdd_event to rate limit and print VFs MDD events. */ void ice_print_vfs_mdd_events(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); struct ice_hw *hw = &pf->hw; struct ice_vf *vf; unsigned int bkt; /* check that there are pending MDD events to print */ if (!test_and_clear_bit(ICE_MDD_VF_PRINT_PENDING, pf->state)) return; /* VF MDD event logs are rate limited to one second intervals */ if (time_is_after_jiffies(pf->vfs.last_printed_mdd_jiffies + HZ * 1)) return; pf->vfs.last_printed_mdd_jiffies = jiffies; mutex_lock(&pf->vfs.table_lock); ice_for_each_vf(pf, bkt, vf) { /* only print Rx MDD event message if there are new events */ if (vf->mdd_rx_events.count != vf->mdd_rx_events.last_printed) { vf->mdd_rx_events.last_printed = vf->mdd_rx_events.count; ice_print_vf_rx_mdd_event(vf); } /* only print Tx MDD event message if there are new events */ if (vf->mdd_tx_events.count != vf->mdd_tx_events.last_printed) { vf->mdd_tx_events.last_printed = vf->mdd_tx_events.count; dev_info(dev, "%d Tx Malicious Driver Detection events detected on PF %d VF %d MAC %pM.\n", vf->mdd_tx_events.count, hw->pf_id, vf->vf_id, vf->dev_lan_addr); } } mutex_unlock(&pf->vfs.table_lock); } /** * ice_restore_all_vfs_msi_state - restore VF MSI state after PF FLR * @pdev: pointer to a pci_dev structure * * Called when recovering from a PF FLR to restore interrupt capability to * the VFs. */ void ice_restore_all_vfs_msi_state(struct pci_dev *pdev) { u16 vf_id; int pos; if (!pci_num_vf(pdev)) return; pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_SRIOV); if (pos) { struct pci_dev *vfdev; pci_read_config_word(pdev, pos + PCI_SRIOV_VF_DID, &vf_id); vfdev = pci_get_device(pdev->vendor, vf_id, NULL); while (vfdev) { if (vfdev->is_virtfn && vfdev->physfn == pdev) pci_restore_msi_state(vfdev); vfdev = pci_get_device(pdev->vendor, vf_id, vfdev); } } }
linux-master
drivers/net/ethernet/intel/ice/ice_sriov.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2019-2021, Intel Corporation. */ #include "ice.h" #include "ice_eswitch.h" #include "ice_devlink.h" #include "ice_sriov.h" #include "ice_tc_lib.h" #include "ice_dcb_lib.h" /** * ice_repr_get_sw_port_id - get port ID associated with representor * @repr: pointer to port representor */ static int ice_repr_get_sw_port_id(struct ice_repr *repr) { return repr->vf->pf->hw.port_info->lport; } /** * ice_repr_get_phys_port_name - get phys port name * @netdev: pointer to port representor netdev * @buf: write here port name * @len: max length of buf */ static int ice_repr_get_phys_port_name(struct net_device *netdev, char *buf, size_t len) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_repr *repr = np->repr; int res; /* Devlink port is registered and devlink core is taking care of name formatting. */ if (repr->vf->devlink_port.devlink) return -EOPNOTSUPP; res = snprintf(buf, len, "pf%dvfr%d", ice_repr_get_sw_port_id(repr), repr->vf->vf_id); if (res <= 0) return -EOPNOTSUPP; return 0; } /** * ice_repr_get_stats64 - get VF stats for VFPR use * @netdev: pointer to port representor netdev * @stats: pointer to struct where stats can be stored */ static void ice_repr_get_stats64(struct net_device *netdev, struct rtnl_link_stats64 *stats) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_eth_stats *eth_stats; struct ice_vsi *vsi; if (ice_is_vf_disabled(np->repr->vf)) return; vsi = np->repr->src_vsi; ice_update_vsi_stats(vsi); eth_stats = &vsi->eth_stats; stats->tx_packets = eth_stats->tx_unicast + eth_stats->tx_broadcast + eth_stats->tx_multicast; stats->rx_packets = eth_stats->rx_unicast + eth_stats->rx_broadcast + eth_stats->rx_multicast; stats->tx_bytes = eth_stats->tx_bytes; stats->rx_bytes = eth_stats->rx_bytes; stats->multicast = eth_stats->rx_multicast; stats->tx_errors = eth_stats->tx_errors; stats->tx_dropped = eth_stats->tx_discards; stats->rx_dropped = eth_stats->rx_discards; } /** * ice_netdev_to_repr - Get port representor for given netdevice * @netdev: pointer to port representor netdev */ struct ice_repr *ice_netdev_to_repr(struct net_device *netdev) { struct ice_netdev_priv *np = netdev_priv(netdev); return np->repr; } /** * ice_repr_open - Enable port representor's network interface * @netdev: network interface device structure * * The open entry point is called when a port representor's network * interface is made active by the system (IFF_UP). Corresponding * VF is notified about link status change. * * Returns 0 on success */ static int ice_repr_open(struct net_device *netdev) { struct ice_repr *repr = ice_netdev_to_repr(netdev); struct ice_vf *vf; vf = repr->vf; vf->link_forced = true; vf->link_up = true; ice_vc_notify_vf_link_state(vf); netif_carrier_on(netdev); netif_tx_start_all_queues(netdev); return 0; } /** * ice_repr_stop - Disable port representor's network interface * @netdev: network interface device structure * * The stop entry point is called when a port representor's network * interface is de-activated by the system. Corresponding * VF is notified about link status change. * * Returns 0 on success */ static int ice_repr_stop(struct net_device *netdev) { struct ice_repr *repr = ice_netdev_to_repr(netdev); struct ice_vf *vf; vf = repr->vf; vf->link_forced = true; vf->link_up = false; ice_vc_notify_vf_link_state(vf); netif_carrier_off(netdev); netif_tx_stop_all_queues(netdev); return 0; } /** * ice_repr_sp_stats64 - get slow path stats for port representor * @dev: network interface device structure * @stats: netlink stats structure * * RX/TX stats are being swapped here to be consistent with VF stats. In slow * path, port representor receives data when the corresponding VF is sending it * (and vice versa), TX and RX bytes/packets are effectively swapped on port * representor. */ static int ice_repr_sp_stats64(const struct net_device *dev, struct rtnl_link_stats64 *stats) { struct ice_netdev_priv *np = netdev_priv(dev); int vf_id = np->repr->vf->vf_id; struct ice_tx_ring *tx_ring; struct ice_rx_ring *rx_ring; u64 pkts, bytes; tx_ring = np->vsi->tx_rings[vf_id]; ice_fetch_u64_stats_per_ring(&tx_ring->ring_stats->syncp, tx_ring->ring_stats->stats, &pkts, &bytes); stats->rx_packets = pkts; stats->rx_bytes = bytes; rx_ring = np->vsi->rx_rings[vf_id]; ice_fetch_u64_stats_per_ring(&rx_ring->ring_stats->syncp, rx_ring->ring_stats->stats, &pkts, &bytes); stats->tx_packets = pkts; stats->tx_bytes = bytes; stats->tx_dropped = rx_ring->ring_stats->rx_stats.alloc_page_failed + rx_ring->ring_stats->rx_stats.alloc_buf_failed; return 0; } static bool ice_repr_ndo_has_offload_stats(const struct net_device *dev, int attr_id) { return attr_id == IFLA_OFFLOAD_XSTATS_CPU_HIT; } static int ice_repr_ndo_get_offload_stats(int attr_id, const struct net_device *dev, void *sp) { if (attr_id == IFLA_OFFLOAD_XSTATS_CPU_HIT) return ice_repr_sp_stats64(dev, (struct rtnl_link_stats64 *)sp); return -EINVAL; } static int ice_repr_setup_tc_cls_flower(struct ice_repr *repr, struct flow_cls_offload *flower) { switch (flower->command) { case FLOW_CLS_REPLACE: return ice_add_cls_flower(repr->netdev, repr->src_vsi, flower); case FLOW_CLS_DESTROY: return ice_del_cls_flower(repr->src_vsi, flower); default: return -EINVAL; } } static int ice_repr_setup_tc_block_cb(enum tc_setup_type type, void *type_data, void *cb_priv) { struct flow_cls_offload *flower = (struct flow_cls_offload *)type_data; struct ice_netdev_priv *np = (struct ice_netdev_priv *)cb_priv; switch (type) { case TC_SETUP_CLSFLOWER: return ice_repr_setup_tc_cls_flower(np->repr, flower); default: return -EOPNOTSUPP; } } static LIST_HEAD(ice_repr_block_cb_list); static int ice_repr_setup_tc(struct net_device *netdev, enum tc_setup_type type, void *type_data) { struct ice_netdev_priv *np = netdev_priv(netdev); switch (type) { case TC_SETUP_BLOCK: return flow_block_cb_setup_simple((struct flow_block_offload *) type_data, &ice_repr_block_cb_list, ice_repr_setup_tc_block_cb, np, np, true); default: return -EOPNOTSUPP; } } static const struct net_device_ops ice_repr_netdev_ops = { .ndo_get_phys_port_name = ice_repr_get_phys_port_name, .ndo_get_stats64 = ice_repr_get_stats64, .ndo_open = ice_repr_open, .ndo_stop = ice_repr_stop, .ndo_start_xmit = ice_eswitch_port_start_xmit, .ndo_setup_tc = ice_repr_setup_tc, .ndo_has_offload_stats = ice_repr_ndo_has_offload_stats, .ndo_get_offload_stats = ice_repr_ndo_get_offload_stats, }; /** * ice_is_port_repr_netdev - Check if a given netdevice is a port representor netdev * @netdev: pointer to netdev */ bool ice_is_port_repr_netdev(const struct net_device *netdev) { return netdev && (netdev->netdev_ops == &ice_repr_netdev_ops); } /** * ice_repr_reg_netdev - register port representor netdev * @netdev: pointer to port representor netdev */ static int ice_repr_reg_netdev(struct net_device *netdev) { eth_hw_addr_random(netdev); netdev->netdev_ops = &ice_repr_netdev_ops; ice_set_ethtool_repr_ops(netdev); netdev->hw_features |= NETIF_F_HW_TC; netif_carrier_off(netdev); netif_tx_stop_all_queues(netdev); return register_netdev(netdev); } /** * ice_repr_add - add representor for VF * @vf: pointer to VF structure */ static int ice_repr_add(struct ice_vf *vf) { struct ice_q_vector *q_vector; struct ice_netdev_priv *np; struct ice_repr *repr; struct ice_vsi *vsi; int err; vsi = ice_get_vf_vsi(vf); if (!vsi) return -EINVAL; repr = kzalloc(sizeof(*repr), GFP_KERNEL); if (!repr) return -ENOMEM; repr->netdev = alloc_etherdev(sizeof(struct ice_netdev_priv)); if (!repr->netdev) { err = -ENOMEM; goto err_alloc; } repr->src_vsi = vsi; repr->vf = vf; vf->repr = repr; np = netdev_priv(repr->netdev); np->repr = repr; q_vector = kzalloc(sizeof(*q_vector), GFP_KERNEL); if (!q_vector) { err = -ENOMEM; goto err_alloc_q_vector; } repr->q_vector = q_vector; err = ice_devlink_create_vf_port(vf); if (err) goto err_devlink; repr->netdev->min_mtu = ETH_MIN_MTU; repr->netdev->max_mtu = ICE_MAX_MTU; SET_NETDEV_DEV(repr->netdev, ice_pf_to_dev(vf->pf)); SET_NETDEV_DEVLINK_PORT(repr->netdev, &vf->devlink_port); err = ice_repr_reg_netdev(repr->netdev); if (err) goto err_netdev; ice_virtchnl_set_repr_ops(vf); return 0; err_netdev: ice_devlink_destroy_vf_port(vf); err_devlink: kfree(repr->q_vector); vf->repr->q_vector = NULL; err_alloc_q_vector: free_netdev(repr->netdev); repr->netdev = NULL; err_alloc: kfree(repr); vf->repr = NULL; return err; } /** * ice_repr_rem - remove representor from VF * @vf: pointer to VF structure */ static void ice_repr_rem(struct ice_vf *vf) { if (!vf->repr) return; kfree(vf->repr->q_vector); vf->repr->q_vector = NULL; unregister_netdev(vf->repr->netdev); ice_devlink_destroy_vf_port(vf); free_netdev(vf->repr->netdev); vf->repr->netdev = NULL; kfree(vf->repr); vf->repr = NULL; ice_virtchnl_set_dflt_ops(vf); } /** * ice_repr_rem_from_all_vfs - remove port representor for all VFs * @pf: pointer to PF structure */ void ice_repr_rem_from_all_vfs(struct ice_pf *pf) { struct devlink *devlink; struct ice_vf *vf; unsigned int bkt; lockdep_assert_held(&pf->vfs.table_lock); ice_for_each_vf(pf, bkt, vf) ice_repr_rem(vf); /* since all port representors are destroyed, there is * no point in keeping the nodes */ devlink = priv_to_devlink(pf); devl_lock(devlink); devl_rate_nodes_destroy(devlink); devl_unlock(devlink); } /** * ice_repr_add_for_all_vfs - add port representor for all VFs * @pf: pointer to PF structure */ int ice_repr_add_for_all_vfs(struct ice_pf *pf) { struct devlink *devlink; struct ice_vf *vf; unsigned int bkt; int err; lockdep_assert_held(&pf->vfs.table_lock); ice_for_each_vf(pf, bkt, vf) { err = ice_repr_add(vf); if (err) goto err; } /* only export if ADQ and DCB disabled */ if (ice_is_adq_active(pf) || ice_is_dcb_active(pf)) return 0; devlink = priv_to_devlink(pf); ice_devlink_rate_init_tx_topology(devlink, ice_get_main_vsi(pf)); return 0; err: ice_repr_rem_from_all_vfs(pf); return err; } /** * ice_repr_start_tx_queues - start Tx queues of port representor * @repr: pointer to repr structure */ void ice_repr_start_tx_queues(struct ice_repr *repr) { netif_carrier_on(repr->netdev); netif_tx_start_all_queues(repr->netdev); } /** * ice_repr_stop_tx_queues - stop Tx queues of port representor * @repr: pointer to repr structure */ void ice_repr_stop_tx_queues(struct ice_repr *repr) { netif_carrier_off(repr->netdev); netif_tx_stop_all_queues(repr->netdev); } /** * ice_repr_set_traffic_vsi - set traffic VSI for port representor * @repr: repr on with VSI will be set * @vsi: pointer to VSI that will be used by port representor to pass traffic */ void ice_repr_set_traffic_vsi(struct ice_repr *repr, struct ice_vsi *vsi) { struct ice_netdev_priv *np = netdev_priv(repr->netdev); np->vsi = vsi; }
linux-master
drivers/net/ethernet/intel/ice/ice_repr.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2018-2020, Intel Corporation. */ #include "ice_common.h" /* These are training packet headers used to program flow director filters. */ static const u8 ice_fdir_tcpv4_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x28, 0x00, 0x01, 0x00, 0x00, 0x40, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00 }; static const u8 ice_fdir_udpv4_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x1C, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_sctpv4_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x20, 0x00, 0x00, 0x40, 0x00, 0x40, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_ipv4_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x14, 0x00, 0x00, 0x40, 0x00, 0x40, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; static const u8 ice_fdir_udp4_gtpu4_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x68, 0x08, 0x68, 0x00, 0x00, 0x00, 0x00, 0x34, 0xff, 0x00, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x45, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_tcp4_gtpu4_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x58, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x68, 0x08, 0x68, 0x00, 0x00, 0x00, 0x00, 0x34, 0xff, 0x00, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x45, 0x00, 0x00, 0x28, 0x00, 0x00, 0x40, 0x00, 0x40, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_icmp4_gtpu4_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x68, 0x08, 0x68, 0x00, 0x00, 0x00, 0x00, 0x34, 0xff, 0x00, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x45, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x40, 0x00, 0x40, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_ipv4_gtpu4_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x44, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x68, 0x08, 0x68, 0x00, 0x00, 0x00, 0x00, 0x34, 0xff, 0x00, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x45, 0x00, 0x00, 0x14, 0x00, 0x00, 0x40, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_ipv4_l2tpv3_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x14, 0x00, 0x00, 0x40, 0x00, 0x40, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_ipv6_l2tpv3_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xDD, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x73, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_ipv4_esp_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x14, 0x00, 0x00, 0x40, 0x00, 0x40, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; static const u8 ice_fdir_ipv6_esp_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xDD, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x32, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_ipv4_ah_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x14, 0x00, 0x00, 0x40, 0x00, 0x40, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; static const u8 ice_fdir_ipv6_ah_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xDD, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x33, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_ipv4_nat_t_esp_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x1C, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x94, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_ipv6_nat_t_esp_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xDD, 0x60, 0x00, 0x00, 0x00, 0x00, 0x08, 0x11, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x94, 0x00, 0x00, 0x00, 0x08, }; static const u8 ice_fdir_ipv4_pfcp_node_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x22, 0x65, 0x22, 0x65, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_ipv4_pfcp_session_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x22, 0x65, 0x22, 0x65, 0x00, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_ipv6_pfcp_node_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xDD, 0x60, 0x00, 0x00, 0x00, 0x00, 0x18, 0x11, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x22, 0x65, 0x22, 0x65, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_ipv6_pfcp_session_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xDD, 0x60, 0x00, 0x00, 0x00, 0x00, 0x18, 0x11, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x22, 0x65, 0x22, 0x65, 0x00, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_non_ip_l2_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_tcpv6_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xDD, 0x60, 0x00, 0x00, 0x00, 0x00, 0x14, 0x06, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_udpv6_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xDD, 0x60, 0x00, 0x00, 0x00, 0x00, 0x08, 0x11, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, }; static const u8 ice_fdir_sctpv6_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xDD, 0x60, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x84, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_ipv6_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xDD, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3B, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_tcp4_tun_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x5a, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x28, 0x00, 0x00, 0x40, 0x00, 0x40, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_udp4_tun_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x4e, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_sctp4_tun_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x52, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x20, 0x00, 0x01, 0x00, 0x00, 0x40, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_ip4_tun_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x46, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_tcp6_tun_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x6e, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xdd, 0x60, 0x00, 0x00, 0x00, 0x00, 0x14, 0x06, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_udp6_tun_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x62, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xdd, 0x60, 0x00, 0x00, 0x00, 0x00, 0x08, 0x11, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_sctp6_tun_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x66, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xdd, 0x60, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x84, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const u8 ice_fdir_ip6_tun_pkt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x5a, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xdd, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3b, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; /* Flow Director no-op training packet table */ static const struct ice_fdir_base_pkt ice_fdir_pkt[] = { { ICE_FLTR_PTYPE_NONF_IPV4_TCP, sizeof(ice_fdir_tcpv4_pkt), ice_fdir_tcpv4_pkt, sizeof(ice_fdir_tcp4_tun_pkt), ice_fdir_tcp4_tun_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV4_UDP, sizeof(ice_fdir_udpv4_pkt), ice_fdir_udpv4_pkt, sizeof(ice_fdir_udp4_tun_pkt), ice_fdir_udp4_tun_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV4_SCTP, sizeof(ice_fdir_sctpv4_pkt), ice_fdir_sctpv4_pkt, sizeof(ice_fdir_sctp4_tun_pkt), ice_fdir_sctp4_tun_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV4_OTHER, sizeof(ice_fdir_ipv4_pkt), ice_fdir_ipv4_pkt, sizeof(ice_fdir_ip4_tun_pkt), ice_fdir_ip4_tun_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV4_GTPU_IPV4_UDP, sizeof(ice_fdir_udp4_gtpu4_pkt), ice_fdir_udp4_gtpu4_pkt, sizeof(ice_fdir_udp4_gtpu4_pkt), ice_fdir_udp4_gtpu4_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV4_GTPU_IPV4_TCP, sizeof(ice_fdir_tcp4_gtpu4_pkt), ice_fdir_tcp4_gtpu4_pkt, sizeof(ice_fdir_tcp4_gtpu4_pkt), ice_fdir_tcp4_gtpu4_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV4_GTPU_IPV4_ICMP, sizeof(ice_fdir_icmp4_gtpu4_pkt), ice_fdir_icmp4_gtpu4_pkt, sizeof(ice_fdir_icmp4_gtpu4_pkt), ice_fdir_icmp4_gtpu4_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV4_GTPU_IPV4_OTHER, sizeof(ice_fdir_ipv4_gtpu4_pkt), ice_fdir_ipv4_gtpu4_pkt, sizeof(ice_fdir_ipv4_gtpu4_pkt), ice_fdir_ipv4_gtpu4_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV4_L2TPV3, sizeof(ice_fdir_ipv4_l2tpv3_pkt), ice_fdir_ipv4_l2tpv3_pkt, sizeof(ice_fdir_ipv4_l2tpv3_pkt), ice_fdir_ipv4_l2tpv3_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV6_L2TPV3, sizeof(ice_fdir_ipv6_l2tpv3_pkt), ice_fdir_ipv6_l2tpv3_pkt, sizeof(ice_fdir_ipv6_l2tpv3_pkt), ice_fdir_ipv6_l2tpv3_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV4_ESP, sizeof(ice_fdir_ipv4_esp_pkt), ice_fdir_ipv4_esp_pkt, sizeof(ice_fdir_ipv4_esp_pkt), ice_fdir_ipv4_esp_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV6_ESP, sizeof(ice_fdir_ipv6_esp_pkt), ice_fdir_ipv6_esp_pkt, sizeof(ice_fdir_ipv6_esp_pkt), ice_fdir_ipv6_esp_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV4_AH, sizeof(ice_fdir_ipv4_ah_pkt), ice_fdir_ipv4_ah_pkt, sizeof(ice_fdir_ipv4_ah_pkt), ice_fdir_ipv4_ah_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV6_AH, sizeof(ice_fdir_ipv6_ah_pkt), ice_fdir_ipv6_ah_pkt, sizeof(ice_fdir_ipv6_ah_pkt), ice_fdir_ipv6_ah_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV4_NAT_T_ESP, sizeof(ice_fdir_ipv4_nat_t_esp_pkt), ice_fdir_ipv4_nat_t_esp_pkt, sizeof(ice_fdir_ipv4_nat_t_esp_pkt), ice_fdir_ipv4_nat_t_esp_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV6_NAT_T_ESP, sizeof(ice_fdir_ipv6_nat_t_esp_pkt), ice_fdir_ipv6_nat_t_esp_pkt, sizeof(ice_fdir_ipv6_nat_t_esp_pkt), ice_fdir_ipv6_nat_t_esp_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV4_PFCP_NODE, sizeof(ice_fdir_ipv4_pfcp_node_pkt), ice_fdir_ipv4_pfcp_node_pkt, sizeof(ice_fdir_ipv4_pfcp_node_pkt), ice_fdir_ipv4_pfcp_node_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV4_PFCP_SESSION, sizeof(ice_fdir_ipv4_pfcp_session_pkt), ice_fdir_ipv4_pfcp_session_pkt, sizeof(ice_fdir_ipv4_pfcp_session_pkt), ice_fdir_ipv4_pfcp_session_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV6_PFCP_NODE, sizeof(ice_fdir_ipv6_pfcp_node_pkt), ice_fdir_ipv6_pfcp_node_pkt, sizeof(ice_fdir_ipv6_pfcp_node_pkt), ice_fdir_ipv6_pfcp_node_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV6_PFCP_SESSION, sizeof(ice_fdir_ipv6_pfcp_session_pkt), ice_fdir_ipv6_pfcp_session_pkt, sizeof(ice_fdir_ipv6_pfcp_session_pkt), ice_fdir_ipv6_pfcp_session_pkt, }, { ICE_FLTR_PTYPE_NON_IP_L2, sizeof(ice_fdir_non_ip_l2_pkt), ice_fdir_non_ip_l2_pkt, sizeof(ice_fdir_non_ip_l2_pkt), ice_fdir_non_ip_l2_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV6_TCP, sizeof(ice_fdir_tcpv6_pkt), ice_fdir_tcpv6_pkt, sizeof(ice_fdir_tcp6_tun_pkt), ice_fdir_tcp6_tun_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV6_UDP, sizeof(ice_fdir_udpv6_pkt), ice_fdir_udpv6_pkt, sizeof(ice_fdir_udp6_tun_pkt), ice_fdir_udp6_tun_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV6_SCTP, sizeof(ice_fdir_sctpv6_pkt), ice_fdir_sctpv6_pkt, sizeof(ice_fdir_sctp6_tun_pkt), ice_fdir_sctp6_tun_pkt, }, { ICE_FLTR_PTYPE_NONF_IPV6_OTHER, sizeof(ice_fdir_ipv6_pkt), ice_fdir_ipv6_pkt, sizeof(ice_fdir_ip6_tun_pkt), ice_fdir_ip6_tun_pkt, }, }; #define ICE_FDIR_NUM_PKT ARRAY_SIZE(ice_fdir_pkt) /** * ice_set_dflt_val_fd_desc * @fd_fltr_ctx: pointer to fd filter descriptor */ static void ice_set_dflt_val_fd_desc(struct ice_fd_fltr_desc_ctx *fd_fltr_ctx) { fd_fltr_ctx->comp_q = ICE_FXD_FLTR_QW0_COMP_Q_ZERO; fd_fltr_ctx->comp_report = ICE_FXD_FLTR_QW0_COMP_REPORT_SW_FAIL; fd_fltr_ctx->fd_space = ICE_FXD_FLTR_QW0_FD_SPACE_GUAR_BEST; fd_fltr_ctx->cnt_ena = ICE_FXD_FLTR_QW0_STAT_ENA_PKTS; fd_fltr_ctx->evict_ena = ICE_FXD_FLTR_QW0_EVICT_ENA_TRUE; fd_fltr_ctx->toq = ICE_FXD_FLTR_QW0_TO_Q_EQUALS_QINDEX; fd_fltr_ctx->toq_prio = ICE_FXD_FLTR_QW0_TO_Q_PRIO1; fd_fltr_ctx->dpu_recipe = ICE_FXD_FLTR_QW0_DPU_RECIPE_DFLT; fd_fltr_ctx->drop = ICE_FXD_FLTR_QW0_DROP_NO; fd_fltr_ctx->flex_prio = ICE_FXD_FLTR_QW0_FLEX_PRI_NONE; fd_fltr_ctx->flex_mdid = ICE_FXD_FLTR_QW0_FLEX_MDID0; fd_fltr_ctx->flex_val = ICE_FXD_FLTR_QW0_FLEX_VAL0; fd_fltr_ctx->dtype = ICE_TX_DESC_DTYPE_FLTR_PROG; fd_fltr_ctx->desc_prof_prio = ICE_FXD_FLTR_QW1_PROF_PRIO_ZERO; fd_fltr_ctx->desc_prof = ICE_FXD_FLTR_QW1_PROF_ZERO; fd_fltr_ctx->swap = ICE_FXD_FLTR_QW1_SWAP_SET; fd_fltr_ctx->fdid_prio = ICE_FXD_FLTR_QW1_FDID_PRI_ONE; fd_fltr_ctx->fdid_mdid = ICE_FXD_FLTR_QW1_FDID_MDID_FD; fd_fltr_ctx->fdid = ICE_FXD_FLTR_QW1_FDID_ZERO; } /** * ice_set_fd_desc_val * @ctx: pointer to fd filter descriptor context * @fdir_desc: populated with fd filter descriptor values */ static void ice_set_fd_desc_val(struct ice_fd_fltr_desc_ctx *ctx, struct ice_fltr_desc *fdir_desc) { u64 qword; /* prep QW0 of FD filter programming desc */ qword = ((u64)ctx->qindex << ICE_FXD_FLTR_QW0_QINDEX_S) & ICE_FXD_FLTR_QW0_QINDEX_M; qword |= ((u64)ctx->comp_q << ICE_FXD_FLTR_QW0_COMP_Q_S) & ICE_FXD_FLTR_QW0_COMP_Q_M; qword |= ((u64)ctx->comp_report << ICE_FXD_FLTR_QW0_COMP_REPORT_S) & ICE_FXD_FLTR_QW0_COMP_REPORT_M; qword |= ((u64)ctx->fd_space << ICE_FXD_FLTR_QW0_FD_SPACE_S) & ICE_FXD_FLTR_QW0_FD_SPACE_M; qword |= ((u64)ctx->cnt_index << ICE_FXD_FLTR_QW0_STAT_CNT_S) & ICE_FXD_FLTR_QW0_STAT_CNT_M; qword |= ((u64)ctx->cnt_ena << ICE_FXD_FLTR_QW0_STAT_ENA_S) & ICE_FXD_FLTR_QW0_STAT_ENA_M; qword |= ((u64)ctx->evict_ena << ICE_FXD_FLTR_QW0_EVICT_ENA_S) & ICE_FXD_FLTR_QW0_EVICT_ENA_M; qword |= ((u64)ctx->toq << ICE_FXD_FLTR_QW0_TO_Q_S) & ICE_FXD_FLTR_QW0_TO_Q_M; qword |= ((u64)ctx->toq_prio << ICE_FXD_FLTR_QW0_TO_Q_PRI_S) & ICE_FXD_FLTR_QW0_TO_Q_PRI_M; qword |= ((u64)ctx->dpu_recipe << ICE_FXD_FLTR_QW0_DPU_RECIPE_S) & ICE_FXD_FLTR_QW0_DPU_RECIPE_M; qword |= ((u64)ctx->drop << ICE_FXD_FLTR_QW0_DROP_S) & ICE_FXD_FLTR_QW0_DROP_M; qword |= ((u64)ctx->flex_prio << ICE_FXD_FLTR_QW0_FLEX_PRI_S) & ICE_FXD_FLTR_QW0_FLEX_PRI_M; qword |= ((u64)ctx->flex_mdid << ICE_FXD_FLTR_QW0_FLEX_MDID_S) & ICE_FXD_FLTR_QW0_FLEX_MDID_M; qword |= ((u64)ctx->flex_val << ICE_FXD_FLTR_QW0_FLEX_VAL_S) & ICE_FXD_FLTR_QW0_FLEX_VAL_M; fdir_desc->qidx_compq_space_stat = cpu_to_le64(qword); /* prep QW1 of FD filter programming desc */ qword = ((u64)ctx->dtype << ICE_FXD_FLTR_QW1_DTYPE_S) & ICE_FXD_FLTR_QW1_DTYPE_M; qword |= ((u64)ctx->pcmd << ICE_FXD_FLTR_QW1_PCMD_S) & ICE_FXD_FLTR_QW1_PCMD_M; qword |= ((u64)ctx->desc_prof_prio << ICE_FXD_FLTR_QW1_PROF_PRI_S) & ICE_FXD_FLTR_QW1_PROF_PRI_M; qword |= ((u64)ctx->desc_prof << ICE_FXD_FLTR_QW1_PROF_S) & ICE_FXD_FLTR_QW1_PROF_M; qword |= ((u64)ctx->fd_vsi << ICE_FXD_FLTR_QW1_FD_VSI_S) & ICE_FXD_FLTR_QW1_FD_VSI_M; qword |= ((u64)ctx->swap << ICE_FXD_FLTR_QW1_SWAP_S) & ICE_FXD_FLTR_QW1_SWAP_M; qword |= ((u64)ctx->fdid_prio << ICE_FXD_FLTR_QW1_FDID_PRI_S) & ICE_FXD_FLTR_QW1_FDID_PRI_M; qword |= ((u64)ctx->fdid_mdid << ICE_FXD_FLTR_QW1_FDID_MDID_S) & ICE_FXD_FLTR_QW1_FDID_MDID_M; qword |= ((u64)ctx->fdid << ICE_FXD_FLTR_QW1_FDID_S) & ICE_FXD_FLTR_QW1_FDID_M; fdir_desc->dtype_cmd_vsi_fdid = cpu_to_le64(qword); } /** * ice_fdir_get_prgm_desc - set a fdir descriptor from a fdir filter struct * @hw: pointer to the hardware structure * @input: filter * @fdesc: filter descriptor * @add: if add is true, this is an add operation, false implies delete */ void ice_fdir_get_prgm_desc(struct ice_hw *hw, struct ice_fdir_fltr *input, struct ice_fltr_desc *fdesc, bool add) { struct ice_fd_fltr_desc_ctx fdir_fltr_ctx = { 0 }; /* set default context info */ ice_set_dflt_val_fd_desc(&fdir_fltr_ctx); /* change sideband filtering values */ fdir_fltr_ctx.fdid = input->fltr_id; if (input->dest_ctl == ICE_FLTR_PRGM_DESC_DEST_DROP_PKT) { fdir_fltr_ctx.drop = ICE_FXD_FLTR_QW0_DROP_YES; fdir_fltr_ctx.qindex = 0; } else if (input->dest_ctl == ICE_FLTR_PRGM_DESC_DEST_DIRECT_PKT_OTHER) { fdir_fltr_ctx.drop = ICE_FXD_FLTR_QW0_DROP_NO; fdir_fltr_ctx.qindex = 0; } else { if (input->dest_ctl == ICE_FLTR_PRGM_DESC_DEST_DIRECT_PKT_QGROUP) fdir_fltr_ctx.toq = input->q_region; fdir_fltr_ctx.drop = ICE_FXD_FLTR_QW0_DROP_NO; fdir_fltr_ctx.qindex = input->q_index; } fdir_fltr_ctx.cnt_ena = input->cnt_ena; fdir_fltr_ctx.cnt_index = input->cnt_index; fdir_fltr_ctx.fd_vsi = ice_get_hw_vsi_num(hw, input->dest_vsi); fdir_fltr_ctx.evict_ena = ICE_FXD_FLTR_QW0_EVICT_ENA_FALSE; if (input->dest_ctl == ICE_FLTR_PRGM_DESC_DEST_DIRECT_PKT_OTHER) fdir_fltr_ctx.toq_prio = 0; else fdir_fltr_ctx.toq_prio = 3; fdir_fltr_ctx.pcmd = add ? ICE_FXD_FLTR_QW1_PCMD_ADD : ICE_FXD_FLTR_QW1_PCMD_REMOVE; fdir_fltr_ctx.swap = ICE_FXD_FLTR_QW1_SWAP_NOT_SET; fdir_fltr_ctx.comp_q = ICE_FXD_FLTR_QW0_COMP_Q_ZERO; fdir_fltr_ctx.comp_report = input->comp_report; fdir_fltr_ctx.fdid_prio = input->fdid_prio; fdir_fltr_ctx.desc_prof = 1; fdir_fltr_ctx.desc_prof_prio = 3; ice_set_fd_desc_val(&fdir_fltr_ctx, fdesc); } /** * ice_alloc_fd_res_cntr - obtain counter resource for FD type * @hw: pointer to the hardware structure * @cntr_id: returns counter index */ int ice_alloc_fd_res_cntr(struct ice_hw *hw, u16 *cntr_id) { return ice_alloc_res_cntr(hw, ICE_AQC_RES_TYPE_FDIR_COUNTER_BLOCK, ICE_AQC_RES_TYPE_FLAG_DEDICATED, 1, cntr_id); } /** * ice_free_fd_res_cntr - Free counter resource for FD type * @hw: pointer to the hardware structure * @cntr_id: counter index to be freed */ int ice_free_fd_res_cntr(struct ice_hw *hw, u16 cntr_id) { return ice_free_res_cntr(hw, ICE_AQC_RES_TYPE_FDIR_COUNTER_BLOCK, ICE_AQC_RES_TYPE_FLAG_DEDICATED, 1, cntr_id); } /** * ice_alloc_fd_guar_item - allocate resource for FD guaranteed entries * @hw: pointer to the hardware structure * @cntr_id: returns counter index * @num_fltr: number of filter entries to be allocated */ int ice_alloc_fd_guar_item(struct ice_hw *hw, u16 *cntr_id, u16 num_fltr) { return ice_alloc_res_cntr(hw, ICE_AQC_RES_TYPE_FDIR_GUARANTEED_ENTRIES, ICE_AQC_RES_TYPE_FLAG_DEDICATED, num_fltr, cntr_id); } /** * ice_alloc_fd_shrd_item - allocate resource for flow director shared entries * @hw: pointer to the hardware structure * @cntr_id: returns counter index * @num_fltr: number of filter entries to be allocated */ int ice_alloc_fd_shrd_item(struct ice_hw *hw, u16 *cntr_id, u16 num_fltr) { return ice_alloc_res_cntr(hw, ICE_AQC_RES_TYPE_FDIR_SHARED_ENTRIES, ICE_AQC_RES_TYPE_FLAG_DEDICATED, num_fltr, cntr_id); } /** * ice_get_fdir_cnt_all - get the number of Flow Director filters * @hw: hardware data structure * * Returns the number of filters available on device */ int ice_get_fdir_cnt_all(struct ice_hw *hw) { return hw->func_caps.fd_fltr_guar + hw->func_caps.fd_fltr_best_effort; } /** * ice_pkt_insert_ipv6_addr - insert a be32 IPv6 address into a memory buffer * @pkt: packet buffer * @offset: offset into buffer * @addr: IPv6 address to convert and insert into pkt at offset */ static void ice_pkt_insert_ipv6_addr(u8 *pkt, int offset, __be32 *addr) { int idx; for (idx = 0; idx < ICE_IPV6_ADDR_LEN_AS_U32; idx++) memcpy(pkt + offset + idx * sizeof(*addr), &addr[idx], sizeof(*addr)); } /** * ice_pkt_insert_u6_qfi - insert a u6 value QFI into a memory buffer for GTPU * @pkt: packet buffer * @offset: offset into buffer * @data: 8 bit value to convert and insert into pkt at offset * * This function is designed for inserting QFI (6 bits) for GTPU. */ static void ice_pkt_insert_u6_qfi(u8 *pkt, int offset, u8 data) { u8 ret; ret = (data & 0x3F) + (*(pkt + offset) & 0xC0); memcpy(pkt + offset, &ret, sizeof(ret)); } /** * ice_pkt_insert_u8 - insert a u8 value into a memory buffer. * @pkt: packet buffer * @offset: offset into buffer * @data: 8 bit value to convert and insert into pkt at offset */ static void ice_pkt_insert_u8(u8 *pkt, int offset, u8 data) { memcpy(pkt + offset, &data, sizeof(data)); } /** * ice_pkt_insert_u8_tc - insert a u8 value into a memory buffer for TC ipv6. * @pkt: packet buffer * @offset: offset into buffer * @data: 8 bit value to convert and insert into pkt at offset * * This function is designed for inserting Traffic Class (TC) for IPv6, * since that TC is not aligned in number of bytes. Here we split it out * into two part and fill each byte with data copy from pkt, then insert * the two bytes data one by one. */ static void ice_pkt_insert_u8_tc(u8 *pkt, int offset, u8 data) { u8 high, low; high = (data >> 4) + (*(pkt + offset) & 0xF0); memcpy(pkt + offset, &high, sizeof(high)); low = (*(pkt + offset + 1) & 0x0F) + ((data & 0x0F) << 4); memcpy(pkt + offset + 1, &low, sizeof(low)); } /** * ice_pkt_insert_u16 - insert a be16 value into a memory buffer * @pkt: packet buffer * @offset: offset into buffer * @data: 16 bit value to convert and insert into pkt at offset */ static void ice_pkt_insert_u16(u8 *pkt, int offset, __be16 data) { memcpy(pkt + offset, &data, sizeof(data)); } /** * ice_pkt_insert_u32 - insert a be32 value into a memory buffer * @pkt: packet buffer * @offset: offset into buffer * @data: 32 bit value to convert and insert into pkt at offset */ static void ice_pkt_insert_u32(u8 *pkt, int offset, __be32 data) { memcpy(pkt + offset, &data, sizeof(data)); } /** * ice_pkt_insert_mac_addr - insert a MAC addr into a memory buffer. * @pkt: packet buffer * @addr: MAC address to convert and insert into pkt at offset */ static void ice_pkt_insert_mac_addr(u8 *pkt, u8 *addr) { ether_addr_copy(pkt, addr); } /** * ice_fdir_get_gen_prgm_pkt - generate a training packet * @hw: pointer to the hardware structure * @input: flow director filter data structure * @pkt: pointer to return filter packet * @frag: generate a fragment packet * @tun: true implies generate a tunnel packet */ int ice_fdir_get_gen_prgm_pkt(struct ice_hw *hw, struct ice_fdir_fltr *input, u8 *pkt, bool frag, bool tun) { enum ice_fltr_ptype flow; u16 tnl_port; u8 *loc; u16 idx; if (input->flow_type == ICE_FLTR_PTYPE_NONF_IPV4_OTHER) { switch (input->ip.v4.proto) { case IPPROTO_TCP: flow = ICE_FLTR_PTYPE_NONF_IPV4_TCP; break; case IPPROTO_UDP: flow = ICE_FLTR_PTYPE_NONF_IPV4_UDP; break; case IPPROTO_SCTP: flow = ICE_FLTR_PTYPE_NONF_IPV4_SCTP; break; default: flow = ICE_FLTR_PTYPE_NONF_IPV4_OTHER; break; } } else if (input->flow_type == ICE_FLTR_PTYPE_NONF_IPV6_OTHER) { switch (input->ip.v6.proto) { case IPPROTO_TCP: flow = ICE_FLTR_PTYPE_NONF_IPV6_TCP; break; case IPPROTO_UDP: flow = ICE_FLTR_PTYPE_NONF_IPV6_UDP; break; case IPPROTO_SCTP: flow = ICE_FLTR_PTYPE_NONF_IPV6_SCTP; break; default: flow = ICE_FLTR_PTYPE_NONF_IPV6_OTHER; break; } } else { flow = input->flow_type; } for (idx = 0; idx < ICE_FDIR_NUM_PKT; idx++) if (ice_fdir_pkt[idx].flow == flow) break; if (idx == ICE_FDIR_NUM_PKT) return -EINVAL; if (!tun) { memcpy(pkt, ice_fdir_pkt[idx].pkt, ice_fdir_pkt[idx].pkt_len); loc = pkt; } else { if (!ice_get_open_tunnel_port(hw, &tnl_port, TNL_ALL)) return -ENOENT; if (!ice_fdir_pkt[idx].tun_pkt) return -EINVAL; memcpy(pkt, ice_fdir_pkt[idx].tun_pkt, ice_fdir_pkt[idx].tun_pkt_len); ice_pkt_insert_u16(pkt, ICE_IPV4_UDP_DST_PORT_OFFSET, htons(tnl_port)); loc = &pkt[ICE_FDIR_TUN_PKT_OFF]; } /* Reverse the src and dst, since the HW expects them to be from Tx * perspective. The input from user is from Rx filter perspective. */ switch (flow) { case ICE_FLTR_PTYPE_NONF_IPV4_TCP: ice_pkt_insert_u32(loc, ICE_IPV4_DST_ADDR_OFFSET, input->ip.v4.src_ip); ice_pkt_insert_u16(loc, ICE_IPV4_TCP_DST_PORT_OFFSET, input->ip.v4.src_port); ice_pkt_insert_u32(loc, ICE_IPV4_SRC_ADDR_OFFSET, input->ip.v4.dst_ip); ice_pkt_insert_u16(loc, ICE_IPV4_TCP_SRC_PORT_OFFSET, input->ip.v4.dst_port); ice_pkt_insert_u8(loc, ICE_IPV4_TOS_OFFSET, input->ip.v4.tos); ice_pkt_insert_u8(loc, ICE_IPV4_TTL_OFFSET, input->ip.v4.ttl); ice_pkt_insert_mac_addr(loc, input->ext_data.dst_mac); if (frag) loc[20] = ICE_FDIR_IPV4_PKT_FLAG_MF; break; case ICE_FLTR_PTYPE_NONF_IPV4_UDP: ice_pkt_insert_u32(loc, ICE_IPV4_DST_ADDR_OFFSET, input->ip.v4.src_ip); ice_pkt_insert_u16(loc, ICE_IPV4_UDP_DST_PORT_OFFSET, input->ip.v4.src_port); ice_pkt_insert_u32(loc, ICE_IPV4_SRC_ADDR_OFFSET, input->ip.v4.dst_ip); ice_pkt_insert_u16(loc, ICE_IPV4_UDP_SRC_PORT_OFFSET, input->ip.v4.dst_port); ice_pkt_insert_u8(loc, ICE_IPV4_TOS_OFFSET, input->ip.v4.tos); ice_pkt_insert_u8(loc, ICE_IPV4_TTL_OFFSET, input->ip.v4.ttl); ice_pkt_insert_mac_addr(loc, input->ext_data.dst_mac); ice_pkt_insert_mac_addr(loc + ETH_ALEN, input->ext_data.src_mac); break; case ICE_FLTR_PTYPE_NONF_IPV4_SCTP: ice_pkt_insert_u32(loc, ICE_IPV4_DST_ADDR_OFFSET, input->ip.v4.src_ip); ice_pkt_insert_u16(loc, ICE_IPV4_SCTP_DST_PORT_OFFSET, input->ip.v4.src_port); ice_pkt_insert_u32(loc, ICE_IPV4_SRC_ADDR_OFFSET, input->ip.v4.dst_ip); ice_pkt_insert_u16(loc, ICE_IPV4_SCTP_SRC_PORT_OFFSET, input->ip.v4.dst_port); ice_pkt_insert_u8(loc, ICE_IPV4_TOS_OFFSET, input->ip.v4.tos); ice_pkt_insert_u8(loc, ICE_IPV4_TTL_OFFSET, input->ip.v4.ttl); ice_pkt_insert_mac_addr(loc, input->ext_data.dst_mac); break; case ICE_FLTR_PTYPE_NONF_IPV4_OTHER: ice_pkt_insert_u32(loc, ICE_IPV4_DST_ADDR_OFFSET, input->ip.v4.src_ip); ice_pkt_insert_u32(loc, ICE_IPV4_SRC_ADDR_OFFSET, input->ip.v4.dst_ip); ice_pkt_insert_u8(loc, ICE_IPV4_TOS_OFFSET, input->ip.v4.tos); ice_pkt_insert_u8(loc, ICE_IPV4_TTL_OFFSET, input->ip.v4.ttl); ice_pkt_insert_u8(loc, ICE_IPV4_PROTO_OFFSET, input->ip.v4.proto); ice_pkt_insert_mac_addr(loc, input->ext_data.dst_mac); break; case ICE_FLTR_PTYPE_NONF_IPV4_GTPU_IPV4_UDP: case ICE_FLTR_PTYPE_NONF_IPV4_GTPU_IPV4_TCP: case ICE_FLTR_PTYPE_NONF_IPV4_GTPU_IPV4_ICMP: case ICE_FLTR_PTYPE_NONF_IPV4_GTPU_IPV4_OTHER: ice_pkt_insert_u32(loc, ICE_IPV4_DST_ADDR_OFFSET, input->ip.v4.src_ip); ice_pkt_insert_u32(loc, ICE_IPV4_SRC_ADDR_OFFSET, input->ip.v4.dst_ip); ice_pkt_insert_u32(loc, ICE_IPV4_GTPU_TEID_OFFSET, input->gtpu_data.teid); ice_pkt_insert_u6_qfi(loc, ICE_IPV4_GTPU_QFI_OFFSET, input->gtpu_data.qfi); break; case ICE_FLTR_PTYPE_NONF_IPV4_L2TPV3: ice_pkt_insert_u32(loc, ICE_IPV4_L2TPV3_SESS_ID_OFFSET, input->l2tpv3_data.session_id); break; case ICE_FLTR_PTYPE_NONF_IPV6_L2TPV3: ice_pkt_insert_u32(loc, ICE_IPV6_L2TPV3_SESS_ID_OFFSET, input->l2tpv3_data.session_id); break; case ICE_FLTR_PTYPE_NONF_IPV4_ESP: ice_pkt_insert_u32(loc, ICE_IPV4_ESP_SPI_OFFSET, input->ip.v4.sec_parm_idx); break; case ICE_FLTR_PTYPE_NONF_IPV6_ESP: ice_pkt_insert_u32(loc, ICE_IPV6_ESP_SPI_OFFSET, input->ip.v6.sec_parm_idx); break; case ICE_FLTR_PTYPE_NONF_IPV4_AH: ice_pkt_insert_u32(loc, ICE_IPV4_AH_SPI_OFFSET, input->ip.v4.sec_parm_idx); break; case ICE_FLTR_PTYPE_NONF_IPV6_AH: ice_pkt_insert_u32(loc, ICE_IPV6_AH_SPI_OFFSET, input->ip.v6.sec_parm_idx); break; case ICE_FLTR_PTYPE_NONF_IPV4_NAT_T_ESP: ice_pkt_insert_u32(loc, ICE_IPV4_DST_ADDR_OFFSET, input->ip.v4.src_ip); ice_pkt_insert_u32(loc, ICE_IPV4_SRC_ADDR_OFFSET, input->ip.v4.dst_ip); ice_pkt_insert_u32(loc, ICE_IPV4_NAT_T_ESP_SPI_OFFSET, input->ip.v4.sec_parm_idx); break; case ICE_FLTR_PTYPE_NONF_IPV6_NAT_T_ESP: ice_pkt_insert_ipv6_addr(loc, ICE_IPV6_DST_ADDR_OFFSET, input->ip.v6.src_ip); ice_pkt_insert_ipv6_addr(loc, ICE_IPV6_SRC_ADDR_OFFSET, input->ip.v6.dst_ip); ice_pkt_insert_u32(loc, ICE_IPV6_NAT_T_ESP_SPI_OFFSET, input->ip.v6.sec_parm_idx); break; case ICE_FLTR_PTYPE_NONF_IPV4_PFCP_NODE: case ICE_FLTR_PTYPE_NONF_IPV4_PFCP_SESSION: ice_pkt_insert_u16(loc, ICE_IPV4_UDP_SRC_PORT_OFFSET, input->ip.v4.dst_port); break; case ICE_FLTR_PTYPE_NONF_IPV6_PFCP_NODE: case ICE_FLTR_PTYPE_NONF_IPV6_PFCP_SESSION: ice_pkt_insert_u16(loc, ICE_IPV6_UDP_SRC_PORT_OFFSET, input->ip.v6.dst_port); break; case ICE_FLTR_PTYPE_NON_IP_L2: ice_pkt_insert_u16(loc, ICE_MAC_ETHTYPE_OFFSET, input->ext_data.ether_type); break; case ICE_FLTR_PTYPE_NONF_IPV6_TCP: ice_pkt_insert_ipv6_addr(loc, ICE_IPV6_DST_ADDR_OFFSET, input->ip.v6.src_ip); ice_pkt_insert_ipv6_addr(loc, ICE_IPV6_SRC_ADDR_OFFSET, input->ip.v6.dst_ip); ice_pkt_insert_u16(loc, ICE_IPV6_TCP_DST_PORT_OFFSET, input->ip.v6.src_port); ice_pkt_insert_u16(loc, ICE_IPV6_TCP_SRC_PORT_OFFSET, input->ip.v6.dst_port); ice_pkt_insert_u8_tc(loc, ICE_IPV6_TC_OFFSET, input->ip.v6.tc); ice_pkt_insert_u8(loc, ICE_IPV6_HLIM_OFFSET, input->ip.v6.hlim); ice_pkt_insert_mac_addr(loc, input->ext_data.dst_mac); break; case ICE_FLTR_PTYPE_NONF_IPV6_UDP: ice_pkt_insert_ipv6_addr(loc, ICE_IPV6_DST_ADDR_OFFSET, input->ip.v6.src_ip); ice_pkt_insert_ipv6_addr(loc, ICE_IPV6_SRC_ADDR_OFFSET, input->ip.v6.dst_ip); ice_pkt_insert_u16(loc, ICE_IPV6_UDP_DST_PORT_OFFSET, input->ip.v6.src_port); ice_pkt_insert_u16(loc, ICE_IPV6_UDP_SRC_PORT_OFFSET, input->ip.v6.dst_port); ice_pkt_insert_u8_tc(loc, ICE_IPV6_TC_OFFSET, input->ip.v6.tc); ice_pkt_insert_u8(loc, ICE_IPV6_HLIM_OFFSET, input->ip.v6.hlim); ice_pkt_insert_mac_addr(loc, input->ext_data.dst_mac); break; case ICE_FLTR_PTYPE_NONF_IPV6_SCTP: ice_pkt_insert_ipv6_addr(loc, ICE_IPV6_DST_ADDR_OFFSET, input->ip.v6.src_ip); ice_pkt_insert_ipv6_addr(loc, ICE_IPV6_SRC_ADDR_OFFSET, input->ip.v6.dst_ip); ice_pkt_insert_u16(loc, ICE_IPV6_SCTP_DST_PORT_OFFSET, input->ip.v6.src_port); ice_pkt_insert_u16(loc, ICE_IPV6_SCTP_SRC_PORT_OFFSET, input->ip.v6.dst_port); ice_pkt_insert_u8_tc(loc, ICE_IPV6_TC_OFFSET, input->ip.v6.tc); ice_pkt_insert_u8(loc, ICE_IPV6_HLIM_OFFSET, input->ip.v6.hlim); ice_pkt_insert_mac_addr(loc, input->ext_data.dst_mac); break; case ICE_FLTR_PTYPE_NONF_IPV6_OTHER: ice_pkt_insert_ipv6_addr(loc, ICE_IPV6_DST_ADDR_OFFSET, input->ip.v6.src_ip); ice_pkt_insert_ipv6_addr(loc, ICE_IPV6_SRC_ADDR_OFFSET, input->ip.v6.dst_ip); ice_pkt_insert_u8_tc(loc, ICE_IPV6_TC_OFFSET, input->ip.v6.tc); ice_pkt_insert_u8(loc, ICE_IPV6_HLIM_OFFSET, input->ip.v6.hlim); ice_pkt_insert_u8(loc, ICE_IPV6_PROTO_OFFSET, input->ip.v6.proto); ice_pkt_insert_mac_addr(loc, input->ext_data.dst_mac); break; default: return -EINVAL; } if (input->flex_fltr) ice_pkt_insert_u16(loc, input->flex_offset, input->flex_word); return 0; } /** * ice_fdir_has_frag - does flow type have 2 ptypes * @flow: flow ptype * * returns true is there is a fragment packet for this ptype */ bool ice_fdir_has_frag(enum ice_fltr_ptype flow) { if (flow == ICE_FLTR_PTYPE_NONF_IPV4_OTHER) return true; else return false; } /** * ice_fdir_find_fltr_by_idx - find filter with idx * @hw: pointer to hardware structure * @fltr_idx: index to find. * * Returns pointer to filter if found or null */ struct ice_fdir_fltr * ice_fdir_find_fltr_by_idx(struct ice_hw *hw, u32 fltr_idx) { struct ice_fdir_fltr *rule; list_for_each_entry(rule, &hw->fdir_list_head, fltr_node) { /* rule ID found in the list */ if (fltr_idx == rule->fltr_id) return rule; if (fltr_idx < rule->fltr_id) break; } return NULL; } /** * ice_fdir_list_add_fltr - add a new node to the flow director filter list * @hw: hardware structure * @fltr: filter node to add to structure */ void ice_fdir_list_add_fltr(struct ice_hw *hw, struct ice_fdir_fltr *fltr) { struct ice_fdir_fltr *rule, *parent = NULL; list_for_each_entry(rule, &hw->fdir_list_head, fltr_node) { /* rule ID found or pass its spot in the list */ if (rule->fltr_id >= fltr->fltr_id) break; parent = rule; } if (parent) list_add(&fltr->fltr_node, &parent->fltr_node); else list_add(&fltr->fltr_node, &hw->fdir_list_head); } /** * ice_fdir_update_cntrs - increment / decrement filter counter * @hw: pointer to hardware structure * @flow: filter flow type * @add: true implies filters added */ void ice_fdir_update_cntrs(struct ice_hw *hw, enum ice_fltr_ptype flow, bool add) { int incr; incr = add ? 1 : -1; hw->fdir_active_fltr += incr; if (flow == ICE_FLTR_PTYPE_NONF_NONE || flow >= ICE_FLTR_PTYPE_MAX) ice_debug(hw, ICE_DBG_SW, "Unknown filter type %d\n", flow); else hw->fdir_fltr_cnt[flow] += incr; } /** * ice_cmp_ipv6_addr - compare 2 IP v6 addresses * @a: IP v6 address * @b: IP v6 address * * Returns 0 on equal, returns non-0 if different */ static int ice_cmp_ipv6_addr(__be32 *a, __be32 *b) { return memcmp(a, b, 4 * sizeof(__be32)); } /** * ice_fdir_comp_rules - compare 2 filters * @a: a Flow Director filter data structure * @b: a Flow Director filter data structure * @v6: bool true if v6 filter * * Returns true if the filters match */ static bool ice_fdir_comp_rules(struct ice_fdir_fltr *a, struct ice_fdir_fltr *b, bool v6) { enum ice_fltr_ptype flow_type = a->flow_type; /* The calling function already checks that the two filters have the * same flow_type. */ if (!v6) { if (flow_type == ICE_FLTR_PTYPE_NONF_IPV4_TCP || flow_type == ICE_FLTR_PTYPE_NONF_IPV4_UDP || flow_type == ICE_FLTR_PTYPE_NONF_IPV4_SCTP) { if (a->ip.v4.dst_ip == b->ip.v4.dst_ip && a->ip.v4.src_ip == b->ip.v4.src_ip && a->ip.v4.dst_port == b->ip.v4.dst_port && a->ip.v4.src_port == b->ip.v4.src_port) return true; } else if (flow_type == ICE_FLTR_PTYPE_NONF_IPV4_OTHER) { if (a->ip.v4.dst_ip == b->ip.v4.dst_ip && a->ip.v4.src_ip == b->ip.v4.src_ip && a->ip.v4.l4_header == b->ip.v4.l4_header && a->ip.v4.proto == b->ip.v4.proto && a->ip.v4.ip_ver == b->ip.v4.ip_ver && a->ip.v4.tos == b->ip.v4.tos) return true; } } else { if (flow_type == ICE_FLTR_PTYPE_NONF_IPV6_UDP || flow_type == ICE_FLTR_PTYPE_NONF_IPV6_TCP || flow_type == ICE_FLTR_PTYPE_NONF_IPV6_SCTP) { if (a->ip.v6.dst_port == b->ip.v6.dst_port && a->ip.v6.src_port == b->ip.v6.src_port && !ice_cmp_ipv6_addr(a->ip.v6.dst_ip, b->ip.v6.dst_ip) && !ice_cmp_ipv6_addr(a->ip.v6.src_ip, b->ip.v6.src_ip)) return true; } else if (flow_type == ICE_FLTR_PTYPE_NONF_IPV6_OTHER) { if (a->ip.v6.dst_port == b->ip.v6.dst_port && a->ip.v6.src_port == b->ip.v6.src_port) return true; } } return false; } /** * ice_fdir_is_dup_fltr - test if filter is already in list for PF * @hw: hardware data structure * @input: Flow Director filter data structure * * Returns true if the filter is found in the list */ bool ice_fdir_is_dup_fltr(struct ice_hw *hw, struct ice_fdir_fltr *input) { struct ice_fdir_fltr *rule; bool ret = false; list_for_each_entry(rule, &hw->fdir_list_head, fltr_node) { enum ice_fltr_ptype flow_type; if (rule->flow_type != input->flow_type) continue; flow_type = input->flow_type; if (flow_type == ICE_FLTR_PTYPE_NONF_IPV4_TCP || flow_type == ICE_FLTR_PTYPE_NONF_IPV4_UDP || flow_type == ICE_FLTR_PTYPE_NONF_IPV4_SCTP || flow_type == ICE_FLTR_PTYPE_NONF_IPV4_OTHER) ret = ice_fdir_comp_rules(rule, input, false); else ret = ice_fdir_comp_rules(rule, input, true); if (ret) { if (rule->fltr_id == input->fltr_id && rule->q_index != input->q_index) ret = false; else break; } } return ret; }
linux-master
drivers/net/ethernet/intel/ice/ice_fdir.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2019-2021, Intel Corporation. */ #include "ice_vsi_vlan_ops.h" #include "ice_vsi_vlan_lib.h" #include "ice_vlan_mode.h" #include "ice.h" #include "ice_pf_vsi_vlan_ops.h" void ice_pf_vsi_init_vlan_ops(struct ice_vsi *vsi) { struct ice_vsi_vlan_ops *vlan_ops; if (ice_is_dvm_ena(&vsi->back->hw)) { vlan_ops = &vsi->outer_vlan_ops; vlan_ops->add_vlan = ice_vsi_add_vlan; vlan_ops->del_vlan = ice_vsi_del_vlan; vlan_ops->ena_stripping = ice_vsi_ena_outer_stripping; vlan_ops->dis_stripping = ice_vsi_dis_outer_stripping; vlan_ops->ena_insertion = ice_vsi_ena_outer_insertion; vlan_ops->dis_insertion = ice_vsi_dis_outer_insertion; vlan_ops->ena_rx_filtering = ice_vsi_ena_rx_vlan_filtering; vlan_ops->dis_rx_filtering = ice_vsi_dis_rx_vlan_filtering; } else { vlan_ops = &vsi->inner_vlan_ops; vlan_ops->add_vlan = ice_vsi_add_vlan; vlan_ops->del_vlan = ice_vsi_del_vlan; vlan_ops->ena_stripping = ice_vsi_ena_inner_stripping; vlan_ops->dis_stripping = ice_vsi_dis_inner_stripping; vlan_ops->ena_insertion = ice_vsi_ena_inner_insertion; vlan_ops->dis_insertion = ice_vsi_dis_inner_insertion; vlan_ops->ena_rx_filtering = ice_vsi_ena_rx_vlan_filtering; vlan_ops->dis_rx_filtering = ice_vsi_dis_rx_vlan_filtering; } }
linux-master
drivers/net/ethernet/intel/ice/ice_pf_vsi_vlan_ops.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2021, Intel Corporation. */ #include <linux/delay.h> #include "ice_common.h" #include "ice_ptp_hw.h" #include "ice_ptp_consts.h" #include "ice_cgu_regs.h" /* Low level functions for interacting with and managing the device clock used * for the Precision Time Protocol. * * The ice hardware represents the current time using three registers: * * GLTSYN_TIME_H GLTSYN_TIME_L GLTSYN_TIME_R * +---------------+ +---------------+ +---------------+ * | 32 bits | | 32 bits | | 32 bits | * +---------------+ +---------------+ +---------------+ * * The registers are incremented every clock tick using a 40bit increment * value defined over two registers: * * GLTSYN_INCVAL_H GLTSYN_INCVAL_L * +---------------+ +---------------+ * | 8 bit s | | 32 bits | * +---------------+ +---------------+ * * The increment value is added to the GLSTYN_TIME_R and GLSTYN_TIME_L * registers every clock source tick. Depending on the specific device * configuration, the clock source frequency could be one of a number of * values. * * For E810 devices, the increment frequency is 812.5 MHz * * For E822 devices the clock can be derived from different sources, and the * increment has an effective frequency of one of the following: * - 823.4375 MHz * - 783.36 MHz * - 796.875 MHz * - 816 MHz * - 830.078125 MHz * - 783.36 MHz * * The hardware captures timestamps in the PHY for incoming packets, and for * outgoing packets on request. To support this, the PHY maintains a timer * that matches the lower 64 bits of the global source timer. * * In order to ensure that the PHY timers and the source timer are equivalent, * shadow registers are used to prepare the desired initial values. A special * sync command is issued to trigger copying from the shadow registers into * the appropriate source and PHY registers simultaneously. * * The driver supports devices which have different PHYs with subtly different * mechanisms to program and control the timers. We divide the devices into * families named after the first major device, E810 and similar devices, and * E822 and similar devices. * * - E822 based devices have additional support for fine grained Vernier * calibration which requires significant setup * - The layout of timestamp data in the PHY register blocks is different * - The way timer synchronization commands are issued is different. * * To support this, very low level functions have an e810 or e822 suffix * indicating what type of device they work on. Higher level abstractions for * tasks that can be done on both devices do not have the suffix and will * correctly look up the appropriate low level function when running. * * Functions which only make sense on a single device family may not have * a suitable generic implementation */ /** * ice_get_ptp_src_clock_index - determine source clock index * @hw: pointer to HW struct * * Determine the source clock index currently in use, based on device * capabilities reported during initialization. */ u8 ice_get_ptp_src_clock_index(struct ice_hw *hw) { return hw->func_caps.ts_func_info.tmr_index_assoc; } /** * ice_ptp_read_src_incval - Read source timer increment value * @hw: pointer to HW struct * * Read the increment value of the source timer and return it. */ static u64 ice_ptp_read_src_incval(struct ice_hw *hw) { u32 lo, hi; u8 tmr_idx; tmr_idx = ice_get_ptp_src_clock_index(hw); lo = rd32(hw, GLTSYN_INCVAL_L(tmr_idx)); hi = rd32(hw, GLTSYN_INCVAL_H(tmr_idx)); return ((u64)(hi & INCVAL_HIGH_M) << 32) | lo; } /** * ice_ptp_src_cmd - Prepare source timer for a timer command * @hw: pointer to HW structure * @cmd: Timer command * * Prepare the source timer for an upcoming timer sync command. */ static void ice_ptp_src_cmd(struct ice_hw *hw, enum ice_ptp_tmr_cmd cmd) { u32 cmd_val; u8 tmr_idx; tmr_idx = ice_get_ptp_src_clock_index(hw); cmd_val = tmr_idx << SEL_CPK_SRC; switch (cmd) { case INIT_TIME: cmd_val |= GLTSYN_CMD_INIT_TIME; break; case INIT_INCVAL: cmd_val |= GLTSYN_CMD_INIT_INCVAL; break; case ADJ_TIME: cmd_val |= GLTSYN_CMD_ADJ_TIME; break; case ADJ_TIME_AT_TIME: cmd_val |= GLTSYN_CMD_ADJ_INIT_TIME; break; case READ_TIME: cmd_val |= GLTSYN_CMD_READ_TIME; break; case ICE_PTP_NOP: break; } wr32(hw, GLTSYN_CMD, cmd_val); } /** * ice_ptp_exec_tmr_cmd - Execute all prepared timer commands * @hw: pointer to HW struct * * Write the SYNC_EXEC_CMD bit to the GLTSYN_CMD_SYNC register, and flush the * write immediately. This triggers the hardware to begin executing all of the * source and PHY timer commands synchronously. */ static void ice_ptp_exec_tmr_cmd(struct ice_hw *hw) { wr32(hw, GLTSYN_CMD_SYNC, SYNC_EXEC_CMD); ice_flush(hw); } /* E822 family functions * * The following functions operate on the E822 family of devices. */ /** * ice_fill_phy_msg_e822 - Fill message data for a PHY register access * @msg: the PHY message buffer to fill in * @port: the port to access * @offset: the register offset */ static void ice_fill_phy_msg_e822(struct ice_sbq_msg_input *msg, u8 port, u16 offset) { int phy_port, phy, quadtype; phy_port = port % ICE_PORTS_PER_PHY; phy = port / ICE_PORTS_PER_PHY; quadtype = (port / ICE_PORTS_PER_QUAD) % ICE_NUM_QUAD_TYPE; if (quadtype == 0) { msg->msg_addr_low = P_Q0_L(P_0_BASE + offset, phy_port); msg->msg_addr_high = P_Q0_H(P_0_BASE + offset, phy_port); } else { msg->msg_addr_low = P_Q1_L(P_4_BASE + offset, phy_port); msg->msg_addr_high = P_Q1_H(P_4_BASE + offset, phy_port); } if (phy == 0) msg->dest_dev = rmn_0; else if (phy == 1) msg->dest_dev = rmn_1; else msg->dest_dev = rmn_2; } /** * ice_is_64b_phy_reg_e822 - Check if this is a 64bit PHY register * @low_addr: the low address to check * @high_addr: on return, contains the high address of the 64bit register * * Checks if the provided low address is one of the known 64bit PHY values * represented as two 32bit registers. If it is, return the appropriate high * register offset to use. */ static bool ice_is_64b_phy_reg_e822(u16 low_addr, u16 *high_addr) { switch (low_addr) { case P_REG_PAR_PCS_TX_OFFSET_L: *high_addr = P_REG_PAR_PCS_TX_OFFSET_U; return true; case P_REG_PAR_PCS_RX_OFFSET_L: *high_addr = P_REG_PAR_PCS_RX_OFFSET_U; return true; case P_REG_PAR_TX_TIME_L: *high_addr = P_REG_PAR_TX_TIME_U; return true; case P_REG_PAR_RX_TIME_L: *high_addr = P_REG_PAR_RX_TIME_U; return true; case P_REG_TOTAL_TX_OFFSET_L: *high_addr = P_REG_TOTAL_TX_OFFSET_U; return true; case P_REG_TOTAL_RX_OFFSET_L: *high_addr = P_REG_TOTAL_RX_OFFSET_U; return true; case P_REG_UIX66_10G_40G_L: *high_addr = P_REG_UIX66_10G_40G_U; return true; case P_REG_UIX66_25G_100G_L: *high_addr = P_REG_UIX66_25G_100G_U; return true; case P_REG_TX_CAPTURE_L: *high_addr = P_REG_TX_CAPTURE_U; return true; case P_REG_RX_CAPTURE_L: *high_addr = P_REG_RX_CAPTURE_U; return true; case P_REG_TX_TIMER_INC_PRE_L: *high_addr = P_REG_TX_TIMER_INC_PRE_U; return true; case P_REG_RX_TIMER_INC_PRE_L: *high_addr = P_REG_RX_TIMER_INC_PRE_U; return true; default: return false; } } /** * ice_is_40b_phy_reg_e822 - Check if this is a 40bit PHY register * @low_addr: the low address to check * @high_addr: on return, contains the high address of the 40bit value * * Checks if the provided low address is one of the known 40bit PHY values * split into two registers with the lower 8 bits in the low register and the * upper 32 bits in the high register. If it is, return the appropriate high * register offset to use. */ static bool ice_is_40b_phy_reg_e822(u16 low_addr, u16 *high_addr) { switch (low_addr) { case P_REG_TIMETUS_L: *high_addr = P_REG_TIMETUS_U; return true; case P_REG_PAR_RX_TUS_L: *high_addr = P_REG_PAR_RX_TUS_U; return true; case P_REG_PAR_TX_TUS_L: *high_addr = P_REG_PAR_TX_TUS_U; return true; case P_REG_PCS_RX_TUS_L: *high_addr = P_REG_PCS_RX_TUS_U; return true; case P_REG_PCS_TX_TUS_L: *high_addr = P_REG_PCS_TX_TUS_U; return true; case P_REG_DESK_PAR_RX_TUS_L: *high_addr = P_REG_DESK_PAR_RX_TUS_U; return true; case P_REG_DESK_PAR_TX_TUS_L: *high_addr = P_REG_DESK_PAR_TX_TUS_U; return true; case P_REG_DESK_PCS_RX_TUS_L: *high_addr = P_REG_DESK_PCS_RX_TUS_U; return true; case P_REG_DESK_PCS_TX_TUS_L: *high_addr = P_REG_DESK_PCS_TX_TUS_U; return true; default: return false; } } /** * ice_read_phy_reg_e822 - Read a PHY register * @hw: pointer to the HW struct * @port: PHY port to read from * @offset: PHY register offset to read * @val: on return, the contents read from the PHY * * Read a PHY register for the given port over the device sideband queue. */ static int ice_read_phy_reg_e822(struct ice_hw *hw, u8 port, u16 offset, u32 *val) { struct ice_sbq_msg_input msg = {0}; int err; ice_fill_phy_msg_e822(&msg, port, offset); msg.opcode = ice_sbq_msg_rd; err = ice_sbq_rw_reg(hw, &msg); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to send message to PHY, err %d\n", err); return err; } *val = msg.data; return 0; } /** * ice_read_64b_phy_reg_e822 - Read a 64bit value from PHY registers * @hw: pointer to the HW struct * @port: PHY port to read from * @low_addr: offset of the lower register to read from * @val: on return, the contents of the 64bit value from the PHY registers * * Reads the two registers associated with a 64bit value and returns it in the * val pointer. The offset always specifies the lower register offset to use. * The high offset is looked up. This function only operates on registers * known to be two parts of a 64bit value. */ static int ice_read_64b_phy_reg_e822(struct ice_hw *hw, u8 port, u16 low_addr, u64 *val) { u32 low, high; u16 high_addr; int err; /* Only operate on registers known to be split into two 32bit * registers. */ if (!ice_is_64b_phy_reg_e822(low_addr, &high_addr)) { ice_debug(hw, ICE_DBG_PTP, "Invalid 64b register addr 0x%08x\n", low_addr); return -EINVAL; } err = ice_read_phy_reg_e822(hw, port, low_addr, &low); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read from low register 0x%08x\n, err %d", low_addr, err); return err; } err = ice_read_phy_reg_e822(hw, port, high_addr, &high); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read from high register 0x%08x\n, err %d", high_addr, err); return err; } *val = (u64)high << 32 | low; return 0; } /** * ice_write_phy_reg_e822 - Write a PHY register * @hw: pointer to the HW struct * @port: PHY port to write to * @offset: PHY register offset to write * @val: The value to write to the register * * Write a PHY register for the given port over the device sideband queue. */ static int ice_write_phy_reg_e822(struct ice_hw *hw, u8 port, u16 offset, u32 val) { struct ice_sbq_msg_input msg = {0}; int err; ice_fill_phy_msg_e822(&msg, port, offset); msg.opcode = ice_sbq_msg_wr; msg.data = val; err = ice_sbq_rw_reg(hw, &msg); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to send message to PHY, err %d\n", err); return err; } return 0; } /** * ice_write_40b_phy_reg_e822 - Write a 40b value to the PHY * @hw: pointer to the HW struct * @port: port to write to * @low_addr: offset of the low register * @val: 40b value to write * * Write the provided 40b value to the two associated registers by splitting * it up into two chunks, the lower 8 bits and the upper 32 bits. */ static int ice_write_40b_phy_reg_e822(struct ice_hw *hw, u8 port, u16 low_addr, u64 val) { u32 low, high; u16 high_addr; int err; /* Only operate on registers known to be split into a lower 8 bit * register and an upper 32 bit register. */ if (!ice_is_40b_phy_reg_e822(low_addr, &high_addr)) { ice_debug(hw, ICE_DBG_PTP, "Invalid 40b register addr 0x%08x\n", low_addr); return -EINVAL; } low = (u32)(val & P_REG_40B_LOW_M); high = (u32)(val >> P_REG_40B_HIGH_S); err = ice_write_phy_reg_e822(hw, port, low_addr, low); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to write to low register 0x%08x\n, err %d", low_addr, err); return err; } err = ice_write_phy_reg_e822(hw, port, high_addr, high); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to write to high register 0x%08x\n, err %d", high_addr, err); return err; } return 0; } /** * ice_write_64b_phy_reg_e822 - Write a 64bit value to PHY registers * @hw: pointer to the HW struct * @port: PHY port to read from * @low_addr: offset of the lower register to read from * @val: the contents of the 64bit value to write to PHY * * Write the 64bit value to the two associated 32bit PHY registers. The offset * is always specified as the lower register, and the high address is looked * up. This function only operates on registers known to be two parts of * a 64bit value. */ static int ice_write_64b_phy_reg_e822(struct ice_hw *hw, u8 port, u16 low_addr, u64 val) { u32 low, high; u16 high_addr; int err; /* Only operate on registers known to be split into two 32bit * registers. */ if (!ice_is_64b_phy_reg_e822(low_addr, &high_addr)) { ice_debug(hw, ICE_DBG_PTP, "Invalid 64b register addr 0x%08x\n", low_addr); return -EINVAL; } low = lower_32_bits(val); high = upper_32_bits(val); err = ice_write_phy_reg_e822(hw, port, low_addr, low); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to write to low register 0x%08x\n, err %d", low_addr, err); return err; } err = ice_write_phy_reg_e822(hw, port, high_addr, high); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to write to high register 0x%08x\n, err %d", high_addr, err); return err; } return 0; } /** * ice_fill_quad_msg_e822 - Fill message data for quad register access * @msg: the PHY message buffer to fill in * @quad: the quad to access * @offset: the register offset * * Fill a message buffer for accessing a register in a quad shared between * multiple PHYs. */ static void ice_fill_quad_msg_e822(struct ice_sbq_msg_input *msg, u8 quad, u16 offset) { u32 addr; msg->dest_dev = rmn_0; if ((quad % ICE_NUM_QUAD_TYPE) == 0) addr = Q_0_BASE + offset; else addr = Q_1_BASE + offset; msg->msg_addr_low = lower_16_bits(addr); msg->msg_addr_high = upper_16_bits(addr); } /** * ice_read_quad_reg_e822 - Read a PHY quad register * @hw: pointer to the HW struct * @quad: quad to read from * @offset: quad register offset to read * @val: on return, the contents read from the quad * * Read a quad register over the device sideband queue. Quad registers are * shared between multiple PHYs. */ int ice_read_quad_reg_e822(struct ice_hw *hw, u8 quad, u16 offset, u32 *val) { struct ice_sbq_msg_input msg = {0}; int err; if (quad >= ICE_MAX_QUAD) return -EINVAL; ice_fill_quad_msg_e822(&msg, quad, offset); msg.opcode = ice_sbq_msg_rd; err = ice_sbq_rw_reg(hw, &msg); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to send message to PHY, err %d\n", err); return err; } *val = msg.data; return 0; } /** * ice_write_quad_reg_e822 - Write a PHY quad register * @hw: pointer to the HW struct * @quad: quad to write to * @offset: quad register offset to write * @val: The value to write to the register * * Write a quad register over the device sideband queue. Quad registers are * shared between multiple PHYs. */ int ice_write_quad_reg_e822(struct ice_hw *hw, u8 quad, u16 offset, u32 val) { struct ice_sbq_msg_input msg = {0}; int err; if (quad >= ICE_MAX_QUAD) return -EINVAL; ice_fill_quad_msg_e822(&msg, quad, offset); msg.opcode = ice_sbq_msg_wr; msg.data = val; err = ice_sbq_rw_reg(hw, &msg); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to send message to PHY, err %d\n", err); return err; } return 0; } /** * ice_read_phy_tstamp_e822 - Read a PHY timestamp out of the quad block * @hw: pointer to the HW struct * @quad: the quad to read from * @idx: the timestamp index to read * @tstamp: on return, the 40bit timestamp value * * Read a 40bit timestamp value out of the two associated registers in the * quad memory block that is shared between the internal PHYs of the E822 * family of devices. */ static int ice_read_phy_tstamp_e822(struct ice_hw *hw, u8 quad, u8 idx, u64 *tstamp) { u16 lo_addr, hi_addr; u32 lo, hi; int err; lo_addr = (u16)TS_L(Q_REG_TX_MEMORY_BANK_START, idx); hi_addr = (u16)TS_H(Q_REG_TX_MEMORY_BANK_START, idx); err = ice_read_quad_reg_e822(hw, quad, lo_addr, &lo); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read low PTP timestamp register, err %d\n", err); return err; } err = ice_read_quad_reg_e822(hw, quad, hi_addr, &hi); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read high PTP timestamp register, err %d\n", err); return err; } /* For E822 based internal PHYs, the timestamp is reported with the * lower 8 bits in the low register, and the upper 32 bits in the high * register. */ *tstamp = ((u64)hi) << TS_PHY_HIGH_S | ((u64)lo & TS_PHY_LOW_M); return 0; } /** * ice_clear_phy_tstamp_e822 - Clear a timestamp from the quad block * @hw: pointer to the HW struct * @quad: the quad to read from * @idx: the timestamp index to reset * * Clear a timestamp, resetting its valid bit, from the PHY quad block that is * shared between the internal PHYs on the E822 devices. */ static int ice_clear_phy_tstamp_e822(struct ice_hw *hw, u8 quad, u8 idx) { u16 lo_addr, hi_addr; int err; lo_addr = (u16)TS_L(Q_REG_TX_MEMORY_BANK_START, idx); hi_addr = (u16)TS_H(Q_REG_TX_MEMORY_BANK_START, idx); err = ice_write_quad_reg_e822(hw, quad, lo_addr, 0); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to clear low PTP timestamp register, err %d\n", err); return err; } err = ice_write_quad_reg_e822(hw, quad, hi_addr, 0); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to clear high PTP timestamp register, err %d\n", err); return err; } return 0; } /** * ice_ptp_reset_ts_memory_quad_e822 - Clear all timestamps from the quad block * @hw: pointer to the HW struct * @quad: the quad to read from * * Clear all timestamps from the PHY quad block that is shared between the * internal PHYs on the E822 devices. */ void ice_ptp_reset_ts_memory_quad_e822(struct ice_hw *hw, u8 quad) { ice_write_quad_reg_e822(hw, quad, Q_REG_TS_CTRL, Q_REG_TS_CTRL_M); ice_write_quad_reg_e822(hw, quad, Q_REG_TS_CTRL, ~(u32)Q_REG_TS_CTRL_M); } /** * ice_ptp_reset_ts_memory_e822 - Clear all timestamps from all quad blocks * @hw: pointer to the HW struct */ static void ice_ptp_reset_ts_memory_e822(struct ice_hw *hw) { unsigned int quad; for (quad = 0; quad < ICE_MAX_QUAD; quad++) ice_ptp_reset_ts_memory_quad_e822(hw, quad); } /** * ice_read_cgu_reg_e822 - Read a CGU register * @hw: pointer to the HW struct * @addr: Register address to read * @val: storage for register value read * * Read the contents of a register of the Clock Generation Unit. Only * applicable to E822 devices. */ static int ice_read_cgu_reg_e822(struct ice_hw *hw, u32 addr, u32 *val) { struct ice_sbq_msg_input cgu_msg; int err; cgu_msg.opcode = ice_sbq_msg_rd; cgu_msg.dest_dev = cgu; cgu_msg.msg_addr_low = addr; cgu_msg.msg_addr_high = 0x0; err = ice_sbq_rw_reg(hw, &cgu_msg); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read CGU register 0x%04x, err %d\n", addr, err); return err; } *val = cgu_msg.data; return err; } /** * ice_write_cgu_reg_e822 - Write a CGU register * @hw: pointer to the HW struct * @addr: Register address to write * @val: value to write into the register * * Write the specified value to a register of the Clock Generation Unit. Only * applicable to E822 devices. */ static int ice_write_cgu_reg_e822(struct ice_hw *hw, u32 addr, u32 val) { struct ice_sbq_msg_input cgu_msg; int err; cgu_msg.opcode = ice_sbq_msg_wr; cgu_msg.dest_dev = cgu; cgu_msg.msg_addr_low = addr; cgu_msg.msg_addr_high = 0x0; cgu_msg.data = val; err = ice_sbq_rw_reg(hw, &cgu_msg); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to write CGU register 0x%04x, err %d\n", addr, err); return err; } return err; } /** * ice_clk_freq_str - Convert time_ref_freq to string * @clk_freq: Clock frequency * * Convert the specified TIME_REF clock frequency to a string. */ static const char *ice_clk_freq_str(u8 clk_freq) { switch ((enum ice_time_ref_freq)clk_freq) { case ICE_TIME_REF_FREQ_25_000: return "25 MHz"; case ICE_TIME_REF_FREQ_122_880: return "122.88 MHz"; case ICE_TIME_REF_FREQ_125_000: return "125 MHz"; case ICE_TIME_REF_FREQ_153_600: return "153.6 MHz"; case ICE_TIME_REF_FREQ_156_250: return "156.25 MHz"; case ICE_TIME_REF_FREQ_245_760: return "245.76 MHz"; default: return "Unknown"; } } /** * ice_clk_src_str - Convert time_ref_src to string * @clk_src: Clock source * * Convert the specified clock source to its string name. */ static const char *ice_clk_src_str(u8 clk_src) { switch ((enum ice_clk_src)clk_src) { case ICE_CLK_SRC_TCX0: return "TCX0"; case ICE_CLK_SRC_TIME_REF: return "TIME_REF"; default: return "Unknown"; } } /** * ice_cfg_cgu_pll_e822 - Configure the Clock Generation Unit * @hw: pointer to the HW struct * @clk_freq: Clock frequency to program * @clk_src: Clock source to select (TIME_REF, or TCX0) * * Configure the Clock Generation Unit with the desired clock frequency and * time reference, enabling the PLL which drives the PTP hardware clock. */ static int ice_cfg_cgu_pll_e822(struct ice_hw *hw, enum ice_time_ref_freq clk_freq, enum ice_clk_src clk_src) { union tspll_ro_bwm_lf bwm_lf; union nac_cgu_dword19 dw19; union nac_cgu_dword22 dw22; union nac_cgu_dword24 dw24; union nac_cgu_dword9 dw9; int err; if (clk_freq >= NUM_ICE_TIME_REF_FREQ) { dev_warn(ice_hw_to_dev(hw), "Invalid TIME_REF frequency %u\n", clk_freq); return -EINVAL; } if (clk_src >= NUM_ICE_CLK_SRC) { dev_warn(ice_hw_to_dev(hw), "Invalid clock source %u\n", clk_src); return -EINVAL; } if (clk_src == ICE_CLK_SRC_TCX0 && clk_freq != ICE_TIME_REF_FREQ_25_000) { dev_warn(ice_hw_to_dev(hw), "TCX0 only supports 25 MHz frequency\n"); return -EINVAL; } err = ice_read_cgu_reg_e822(hw, NAC_CGU_DWORD9, &dw9.val); if (err) return err; err = ice_read_cgu_reg_e822(hw, NAC_CGU_DWORD24, &dw24.val); if (err) return err; err = ice_read_cgu_reg_e822(hw, TSPLL_RO_BWM_LF, &bwm_lf.val); if (err) return err; /* Log the current clock configuration */ ice_debug(hw, ICE_DBG_PTP, "Current CGU configuration -- %s, clk_src %s, clk_freq %s, PLL %s\n", dw24.field.ts_pll_enable ? "enabled" : "disabled", ice_clk_src_str(dw24.field.time_ref_sel), ice_clk_freq_str(dw9.field.time_ref_freq_sel), bwm_lf.field.plllock_true_lock_cri ? "locked" : "unlocked"); /* Disable the PLL before changing the clock source or frequency */ if (dw24.field.ts_pll_enable) { dw24.field.ts_pll_enable = 0; err = ice_write_cgu_reg_e822(hw, NAC_CGU_DWORD24, dw24.val); if (err) return err; } /* Set the frequency */ dw9.field.time_ref_freq_sel = clk_freq; err = ice_write_cgu_reg_e822(hw, NAC_CGU_DWORD9, dw9.val); if (err) return err; /* Configure the TS PLL feedback divisor */ err = ice_read_cgu_reg_e822(hw, NAC_CGU_DWORD19, &dw19.val); if (err) return err; dw19.field.tspll_fbdiv_intgr = e822_cgu_params[clk_freq].feedback_div; dw19.field.tspll_ndivratio = 1; err = ice_write_cgu_reg_e822(hw, NAC_CGU_DWORD19, dw19.val); if (err) return err; /* Configure the TS PLL post divisor */ err = ice_read_cgu_reg_e822(hw, NAC_CGU_DWORD22, &dw22.val); if (err) return err; dw22.field.time1588clk_div = e822_cgu_params[clk_freq].post_pll_div; dw22.field.time1588clk_sel_div2 = 0; err = ice_write_cgu_reg_e822(hw, NAC_CGU_DWORD22, dw22.val); if (err) return err; /* Configure the TS PLL pre divisor and clock source */ err = ice_read_cgu_reg_e822(hw, NAC_CGU_DWORD24, &dw24.val); if (err) return err; dw24.field.ref1588_ck_div = e822_cgu_params[clk_freq].refclk_pre_div; dw24.field.tspll_fbdiv_frac = e822_cgu_params[clk_freq].frac_n_div; dw24.field.time_ref_sel = clk_src; err = ice_write_cgu_reg_e822(hw, NAC_CGU_DWORD24, dw24.val); if (err) return err; /* Finally, enable the PLL */ dw24.field.ts_pll_enable = 1; err = ice_write_cgu_reg_e822(hw, NAC_CGU_DWORD24, dw24.val); if (err) return err; /* Wait to verify if the PLL locks */ usleep_range(1000, 5000); err = ice_read_cgu_reg_e822(hw, TSPLL_RO_BWM_LF, &bwm_lf.val); if (err) return err; if (!bwm_lf.field.plllock_true_lock_cri) { dev_warn(ice_hw_to_dev(hw), "CGU PLL failed to lock\n"); return -EBUSY; } /* Log the current clock configuration */ ice_debug(hw, ICE_DBG_PTP, "New CGU configuration -- %s, clk_src %s, clk_freq %s, PLL %s\n", dw24.field.ts_pll_enable ? "enabled" : "disabled", ice_clk_src_str(dw24.field.time_ref_sel), ice_clk_freq_str(dw9.field.time_ref_freq_sel), bwm_lf.field.plllock_true_lock_cri ? "locked" : "unlocked"); return 0; } /** * ice_init_cgu_e822 - Initialize CGU with settings from firmware * @hw: pointer to the HW structure * * Initialize the Clock Generation Unit of the E822 device. */ static int ice_init_cgu_e822(struct ice_hw *hw) { struct ice_ts_func_info *ts_info = &hw->func_caps.ts_func_info; union tspll_cntr_bist_settings cntr_bist; int err; err = ice_read_cgu_reg_e822(hw, TSPLL_CNTR_BIST_SETTINGS, &cntr_bist.val); if (err) return err; /* Disable sticky lock detection so lock err reported is accurate */ cntr_bist.field.i_plllock_sel_0 = 0; cntr_bist.field.i_plllock_sel_1 = 0; err = ice_write_cgu_reg_e822(hw, TSPLL_CNTR_BIST_SETTINGS, cntr_bist.val); if (err) return err; /* Configure the CGU PLL using the parameters from the function * capabilities. */ err = ice_cfg_cgu_pll_e822(hw, ts_info->time_ref, (enum ice_clk_src)ts_info->clk_src); if (err) return err; return 0; } /** * ice_ptp_set_vernier_wl - Set the window length for vernier calibration * @hw: pointer to the HW struct * * Set the window length used for the vernier port calibration process. */ static int ice_ptp_set_vernier_wl(struct ice_hw *hw) { u8 port; for (port = 0; port < ICE_NUM_EXTERNAL_PORTS; port++) { int err; err = ice_write_phy_reg_e822(hw, port, P_REG_WL, PTP_VERNIER_WL); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to set vernier window length for port %u, err %d\n", port, err); return err; } } return 0; } /** * ice_ptp_init_phc_e822 - Perform E822 specific PHC initialization * @hw: pointer to HW struct * * Perform PHC initialization steps specific to E822 devices. */ static int ice_ptp_init_phc_e822(struct ice_hw *hw) { int err; u32 regval; /* Enable reading switch and PHY registers over the sideband queue */ #define PF_SB_REM_DEV_CTL_SWITCH_READ BIT(1) #define PF_SB_REM_DEV_CTL_PHY0 BIT(2) regval = rd32(hw, PF_SB_REM_DEV_CTL); regval |= (PF_SB_REM_DEV_CTL_SWITCH_READ | PF_SB_REM_DEV_CTL_PHY0); wr32(hw, PF_SB_REM_DEV_CTL, regval); /* Initialize the Clock Generation Unit */ err = ice_init_cgu_e822(hw); if (err) return err; /* Set window length for all the ports */ return ice_ptp_set_vernier_wl(hw); } /** * ice_ptp_prep_phy_time_e822 - Prepare PHY port with initial time * @hw: pointer to the HW struct * @time: Time to initialize the PHY port clocks to * * Program the PHY port registers with a new initial time value. The port * clock will be initialized once the driver issues an INIT_TIME sync * command. The time value is the upper 32 bits of the PHY timer, usually in * units of nominal nanoseconds. */ static int ice_ptp_prep_phy_time_e822(struct ice_hw *hw, u32 time) { u64 phy_time; u8 port; int err; /* The time represents the upper 32 bits of the PHY timer, so we need * to shift to account for this when programming. */ phy_time = (u64)time << 32; for (port = 0; port < ICE_NUM_EXTERNAL_PORTS; port++) { /* Tx case */ err = ice_write_64b_phy_reg_e822(hw, port, P_REG_TX_TIMER_INC_PRE_L, phy_time); if (err) goto exit_err; /* Rx case */ err = ice_write_64b_phy_reg_e822(hw, port, P_REG_RX_TIMER_INC_PRE_L, phy_time); if (err) goto exit_err; } return 0; exit_err: ice_debug(hw, ICE_DBG_PTP, "Failed to write init time for port %u, err %d\n", port, err); return err; } /** * ice_ptp_prep_port_adj_e822 - Prepare a single port for time adjust * @hw: pointer to HW struct * @port: Port number to be programmed * @time: time in cycles to adjust the port Tx and Rx clocks * * Program the port for an atomic adjustment by writing the Tx and Rx timer * registers. The atomic adjustment won't be completed until the driver issues * an ADJ_TIME command. * * Note that time is not in units of nanoseconds. It is in clock time * including the lower sub-nanosecond portion of the port timer. * * Negative adjustments are supported using 2s complement arithmetic. */ static int ice_ptp_prep_port_adj_e822(struct ice_hw *hw, u8 port, s64 time) { u32 l_time, u_time; int err; l_time = lower_32_bits(time); u_time = upper_32_bits(time); /* Tx case */ err = ice_write_phy_reg_e822(hw, port, P_REG_TX_TIMER_INC_PRE_L, l_time); if (err) goto exit_err; err = ice_write_phy_reg_e822(hw, port, P_REG_TX_TIMER_INC_PRE_U, u_time); if (err) goto exit_err; /* Rx case */ err = ice_write_phy_reg_e822(hw, port, P_REG_RX_TIMER_INC_PRE_L, l_time); if (err) goto exit_err; err = ice_write_phy_reg_e822(hw, port, P_REG_RX_TIMER_INC_PRE_U, u_time); if (err) goto exit_err; return 0; exit_err: ice_debug(hw, ICE_DBG_PTP, "Failed to write time adjust for port %u, err %d\n", port, err); return err; } /** * ice_ptp_prep_phy_adj_e822 - Prep PHY ports for a time adjustment * @hw: pointer to HW struct * @adj: adjustment in nanoseconds * * Prepare the PHY ports for an atomic time adjustment by programming the PHY * Tx and Rx port registers. The actual adjustment is completed by issuing an * ADJ_TIME or ADJ_TIME_AT_TIME sync command. */ static int ice_ptp_prep_phy_adj_e822(struct ice_hw *hw, s32 adj) { s64 cycles; u8 port; /* The port clock supports adjustment of the sub-nanosecond portion of * the clock. We shift the provided adjustment in nanoseconds to * calculate the appropriate adjustment to program into the PHY ports. */ if (adj > 0) cycles = (s64)adj << 32; else cycles = -(((s64)-adj) << 32); for (port = 0; port < ICE_NUM_EXTERNAL_PORTS; port++) { int err; err = ice_ptp_prep_port_adj_e822(hw, port, cycles); if (err) return err; } return 0; } /** * ice_ptp_prep_phy_incval_e822 - Prepare PHY ports for time adjustment * @hw: pointer to HW struct * @incval: new increment value to prepare * * Prepare each of the PHY ports for a new increment value by programming the * port's TIMETUS registers. The new increment value will be updated after * issuing an INIT_INCVAL command. */ static int ice_ptp_prep_phy_incval_e822(struct ice_hw *hw, u64 incval) { int err; u8 port; for (port = 0; port < ICE_NUM_EXTERNAL_PORTS; port++) { err = ice_write_40b_phy_reg_e822(hw, port, P_REG_TIMETUS_L, incval); if (err) goto exit_err; } return 0; exit_err: ice_debug(hw, ICE_DBG_PTP, "Failed to write incval for port %u, err %d\n", port, err); return err; } /** * ice_ptp_read_port_capture - Read a port's local time capture * @hw: pointer to HW struct * @port: Port number to read * @tx_ts: on return, the Tx port time capture * @rx_ts: on return, the Rx port time capture * * Read the port's Tx and Rx local time capture values. * * Note this has no equivalent for the E810 devices. */ static int ice_ptp_read_port_capture(struct ice_hw *hw, u8 port, u64 *tx_ts, u64 *rx_ts) { int err; /* Tx case */ err = ice_read_64b_phy_reg_e822(hw, port, P_REG_TX_CAPTURE_L, tx_ts); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read REG_TX_CAPTURE, err %d\n", err); return err; } ice_debug(hw, ICE_DBG_PTP, "tx_init = 0x%016llx\n", (unsigned long long)*tx_ts); /* Rx case */ err = ice_read_64b_phy_reg_e822(hw, port, P_REG_RX_CAPTURE_L, rx_ts); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read RX_CAPTURE, err %d\n", err); return err; } ice_debug(hw, ICE_DBG_PTP, "rx_init = 0x%016llx\n", (unsigned long long)*rx_ts); return 0; } /** * ice_ptp_write_port_cmd_e822 - Prepare a single PHY port for a timer command * @hw: pointer to HW struct * @port: Port to which cmd has to be sent * @cmd: Command to be sent to the port * * Prepare the requested port for an upcoming timer sync command. * * Do not use this function directly. If you want to configure exactly one * port, use ice_ptp_one_port_cmd() instead. */ static int ice_ptp_write_port_cmd_e822(struct ice_hw *hw, u8 port, enum ice_ptp_tmr_cmd cmd) { u32 cmd_val, val; u8 tmr_idx; int err; tmr_idx = ice_get_ptp_src_clock_index(hw); cmd_val = tmr_idx << SEL_PHY_SRC; switch (cmd) { case INIT_TIME: cmd_val |= PHY_CMD_INIT_TIME; break; case INIT_INCVAL: cmd_val |= PHY_CMD_INIT_INCVAL; break; case ADJ_TIME: cmd_val |= PHY_CMD_ADJ_TIME; break; case READ_TIME: cmd_val |= PHY_CMD_READ_TIME; break; case ADJ_TIME_AT_TIME: cmd_val |= PHY_CMD_ADJ_TIME_AT_TIME; break; case ICE_PTP_NOP: break; } /* Tx case */ /* Read, modify, write */ err = ice_read_phy_reg_e822(hw, port, P_REG_TX_TMR_CMD, &val); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read TX_TMR_CMD, err %d\n", err); return err; } /* Modify necessary bits only and perform write */ val &= ~TS_CMD_MASK; val |= cmd_val; err = ice_write_phy_reg_e822(hw, port, P_REG_TX_TMR_CMD, val); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to write back TX_TMR_CMD, err %d\n", err); return err; } /* Rx case */ /* Read, modify, write */ err = ice_read_phy_reg_e822(hw, port, P_REG_RX_TMR_CMD, &val); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read RX_TMR_CMD, err %d\n", err); return err; } /* Modify necessary bits only and perform write */ val &= ~TS_CMD_MASK; val |= cmd_val; err = ice_write_phy_reg_e822(hw, port, P_REG_RX_TMR_CMD, val); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to write back RX_TMR_CMD, err %d\n", err); return err; } return 0; } /** * ice_ptp_one_port_cmd - Prepare one port for a timer command * @hw: pointer to the HW struct * @configured_port: the port to configure with configured_cmd * @configured_cmd: timer command to prepare on the configured_port * * Prepare the configured_port for the configured_cmd, and prepare all other * ports for ICE_PTP_NOP. This causes the configured_port to execute the * desired command while all other ports perform no operation. */ static int ice_ptp_one_port_cmd(struct ice_hw *hw, u8 configured_port, enum ice_ptp_tmr_cmd configured_cmd) { u8 port; for (port = 0; port < ICE_NUM_EXTERNAL_PORTS; port++) { enum ice_ptp_tmr_cmd cmd; int err; if (port == configured_port) cmd = configured_cmd; else cmd = ICE_PTP_NOP; err = ice_ptp_write_port_cmd_e822(hw, port, cmd); if (err) return err; } return 0; } /** * ice_ptp_port_cmd_e822 - Prepare all ports for a timer command * @hw: pointer to the HW struct * @cmd: timer command to prepare * * Prepare all ports connected to this device for an upcoming timer sync * command. */ static int ice_ptp_port_cmd_e822(struct ice_hw *hw, enum ice_ptp_tmr_cmd cmd) { u8 port; for (port = 0; port < ICE_NUM_EXTERNAL_PORTS; port++) { int err; err = ice_ptp_write_port_cmd_e822(hw, port, cmd); if (err) return err; } return 0; } /* E822 Vernier calibration functions * * The following functions are used as part of the vernier calibration of * a port. This calibration increases the precision of the timestamps on the * port. */ /** * ice_phy_get_speed_and_fec_e822 - Get link speed and FEC based on serdes mode * @hw: pointer to HW struct * @port: the port to read from * @link_out: if non-NULL, holds link speed on success * @fec_out: if non-NULL, holds FEC algorithm on success * * Read the serdes data for the PHY port and extract the link speed and FEC * algorithm. */ static int ice_phy_get_speed_and_fec_e822(struct ice_hw *hw, u8 port, enum ice_ptp_link_spd *link_out, enum ice_ptp_fec_mode *fec_out) { enum ice_ptp_link_spd link; enum ice_ptp_fec_mode fec; u32 serdes; int err; err = ice_read_phy_reg_e822(hw, port, P_REG_LINK_SPEED, &serdes); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read serdes info\n"); return err; } /* Determine the FEC algorithm */ fec = (enum ice_ptp_fec_mode)P_REG_LINK_SPEED_FEC_MODE(serdes); serdes &= P_REG_LINK_SPEED_SERDES_M; /* Determine the link speed */ if (fec == ICE_PTP_FEC_MODE_RS_FEC) { switch (serdes) { case ICE_PTP_SERDES_25G: link = ICE_PTP_LNK_SPD_25G_RS; break; case ICE_PTP_SERDES_50G: link = ICE_PTP_LNK_SPD_50G_RS; break; case ICE_PTP_SERDES_100G: link = ICE_PTP_LNK_SPD_100G_RS; break; default: return -EIO; } } else { switch (serdes) { case ICE_PTP_SERDES_1G: link = ICE_PTP_LNK_SPD_1G; break; case ICE_PTP_SERDES_10G: link = ICE_PTP_LNK_SPD_10G; break; case ICE_PTP_SERDES_25G: link = ICE_PTP_LNK_SPD_25G; break; case ICE_PTP_SERDES_40G: link = ICE_PTP_LNK_SPD_40G; break; case ICE_PTP_SERDES_50G: link = ICE_PTP_LNK_SPD_50G; break; default: return -EIO; } } if (link_out) *link_out = link; if (fec_out) *fec_out = fec; return 0; } /** * ice_phy_cfg_lane_e822 - Configure PHY quad for single/multi-lane timestamp * @hw: pointer to HW struct * @port: to configure the quad for */ static void ice_phy_cfg_lane_e822(struct ice_hw *hw, u8 port) { enum ice_ptp_link_spd link_spd; int err; u32 val; u8 quad; err = ice_phy_get_speed_and_fec_e822(hw, port, &link_spd, NULL); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to get PHY link speed, err %d\n", err); return; } quad = port / ICE_PORTS_PER_QUAD; err = ice_read_quad_reg_e822(hw, quad, Q_REG_TX_MEM_GBL_CFG, &val); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read TX_MEM_GLB_CFG, err %d\n", err); return; } if (link_spd >= ICE_PTP_LNK_SPD_40G) val &= ~Q_REG_TX_MEM_GBL_CFG_LANE_TYPE_M; else val |= Q_REG_TX_MEM_GBL_CFG_LANE_TYPE_M; err = ice_write_quad_reg_e822(hw, quad, Q_REG_TX_MEM_GBL_CFG, val); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to write back TX_MEM_GBL_CFG, err %d\n", err); return; } } /** * ice_phy_cfg_uix_e822 - Configure Serdes UI to TU conversion for E822 * @hw: pointer to the HW structure * @port: the port to configure * * Program the conversion ration of Serdes clock "unit intervals" (UIs) to PHC * hardware clock time units (TUs). That is, determine the number of TUs per * serdes unit interval, and program the UIX registers with this conversion. * * This conversion is used as part of the calibration process when determining * the additional error of a timestamp vs the real time of transmission or * receipt of the packet. * * Hardware uses the number of TUs per 66 UIs, written to the UIX registers * for the two main serdes clock rates, 10G/40G and 25G/100G serdes clocks. * * To calculate the conversion ratio, we use the following facts: * * a) the clock frequency in Hz (cycles per second) * b) the number of TUs per cycle (the increment value of the clock) * c) 1 second per 1 billion nanoseconds * d) the duration of 66 UIs in nanoseconds * * Given these facts, we can use the following table to work out what ratios * to multiply in order to get the number of TUs per 66 UIs: * * cycles | 1 second | incval (TUs) | nanoseconds * -------+--------------+--------------+------------- * second | 1 billion ns | cycle | 66 UIs * * To perform the multiplication using integers without too much loss of * precision, we can take use the following equation: * * (freq * incval * 6600 LINE_UI ) / ( 100 * 1 billion) * * We scale up to using 6600 UI instead of 66 in order to avoid fractional * nanosecond UIs (66 UI at 10G/40G is 6.4 ns) * * The increment value has a maximum expected range of about 34 bits, while * the frequency value is about 29 bits. Multiplying these values shouldn't * overflow the 64 bits. However, we must then further multiply them again by * the Serdes unit interval duration. To avoid overflow here, we split the * overall divide by 1e11 into a divide by 256 (shift down by 8 bits) and * a divide by 390,625,000. This does lose some precision, but avoids * miscalculation due to arithmetic overflow. */ static int ice_phy_cfg_uix_e822(struct ice_hw *hw, u8 port) { u64 cur_freq, clk_incval, tu_per_sec, uix; int err; cur_freq = ice_e822_pll_freq(ice_e822_time_ref(hw)); clk_incval = ice_ptp_read_src_incval(hw); /* Calculate TUs per second divided by 256 */ tu_per_sec = (cur_freq * clk_incval) >> 8; #define LINE_UI_10G_40G 640 /* 6600 UIs is 640 nanoseconds at 10Gb/40Gb */ #define LINE_UI_25G_100G 256 /* 6600 UIs is 256 nanoseconds at 25Gb/100Gb */ /* Program the 10Gb/40Gb conversion ratio */ uix = div_u64(tu_per_sec * LINE_UI_10G_40G, 390625000); err = ice_write_64b_phy_reg_e822(hw, port, P_REG_UIX66_10G_40G_L, uix); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to write UIX66_10G_40G, err %d\n", err); return err; } /* Program the 25Gb/100Gb conversion ratio */ uix = div_u64(tu_per_sec * LINE_UI_25G_100G, 390625000); err = ice_write_64b_phy_reg_e822(hw, port, P_REG_UIX66_25G_100G_L, uix); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to write UIX66_25G_100G, err %d\n", err); return err; } return 0; } /** * ice_phy_cfg_parpcs_e822 - Configure TUs per PAR/PCS clock cycle * @hw: pointer to the HW struct * @port: port to configure * * Configure the number of TUs for the PAR and PCS clocks used as part of the * timestamp calibration process. This depends on the link speed, as the PHY * uses different markers depending on the speed. * * 1Gb/10Gb/25Gb: * - Tx/Rx PAR/PCS markers * * 25Gb RS: * - Tx/Rx Reed Solomon gearbox PAR/PCS markers * * 40Gb/50Gb: * - Tx/Rx PAR/PCS markers * - Rx Deskew PAR/PCS markers * * 50G RS and 100GB RS: * - Tx/Rx Reed Solomon gearbox PAR/PCS markers * - Rx Deskew PAR/PCS markers * - Tx PAR/PCS markers * * To calculate the conversion, we use the PHC clock frequency (cycles per * second), the increment value (TUs per cycle), and the related PHY clock * frequency to calculate the TUs per unit of the PHY link clock. The * following table shows how the units convert: * * cycles | TUs | second * -------+-------+-------- * second | cycle | cycles * * For each conversion register, look up the appropriate frequency from the * e822 PAR/PCS table and calculate the TUs per unit of that clock. Program * this to the appropriate register, preparing hardware to perform timestamp * calibration to calculate the total Tx or Rx offset to adjust the timestamp * in order to calibrate for the internal PHY delays. * * Note that the increment value ranges up to ~34 bits, and the clock * frequency is ~29 bits, so multiplying them together should fit within the * 64 bit arithmetic. */ static int ice_phy_cfg_parpcs_e822(struct ice_hw *hw, u8 port) { u64 cur_freq, clk_incval, tu_per_sec, phy_tus; enum ice_ptp_link_spd link_spd; enum ice_ptp_fec_mode fec_mode; int err; err = ice_phy_get_speed_and_fec_e822(hw, port, &link_spd, &fec_mode); if (err) return err; cur_freq = ice_e822_pll_freq(ice_e822_time_ref(hw)); clk_incval = ice_ptp_read_src_incval(hw); /* Calculate TUs per cycle of the PHC clock */ tu_per_sec = cur_freq * clk_incval; /* For each PHY conversion register, look up the appropriate link * speed frequency and determine the TUs per that clock's cycle time. * Split this into a high and low value and then program the * appropriate register. If that link speed does not use the * associated register, write zeros to clear it instead. */ /* P_REG_PAR_TX_TUS */ if (e822_vernier[link_spd].tx_par_clk) phy_tus = div_u64(tu_per_sec, e822_vernier[link_spd].tx_par_clk); else phy_tus = 0; err = ice_write_40b_phy_reg_e822(hw, port, P_REG_PAR_TX_TUS_L, phy_tus); if (err) return err; /* P_REG_PAR_RX_TUS */ if (e822_vernier[link_spd].rx_par_clk) phy_tus = div_u64(tu_per_sec, e822_vernier[link_spd].rx_par_clk); else phy_tus = 0; err = ice_write_40b_phy_reg_e822(hw, port, P_REG_PAR_RX_TUS_L, phy_tus); if (err) return err; /* P_REG_PCS_TX_TUS */ if (e822_vernier[link_spd].tx_pcs_clk) phy_tus = div_u64(tu_per_sec, e822_vernier[link_spd].tx_pcs_clk); else phy_tus = 0; err = ice_write_40b_phy_reg_e822(hw, port, P_REG_PCS_TX_TUS_L, phy_tus); if (err) return err; /* P_REG_PCS_RX_TUS */ if (e822_vernier[link_spd].rx_pcs_clk) phy_tus = div_u64(tu_per_sec, e822_vernier[link_spd].rx_pcs_clk); else phy_tus = 0; err = ice_write_40b_phy_reg_e822(hw, port, P_REG_PCS_RX_TUS_L, phy_tus); if (err) return err; /* P_REG_DESK_PAR_TX_TUS */ if (e822_vernier[link_spd].tx_desk_rsgb_par) phy_tus = div_u64(tu_per_sec, e822_vernier[link_spd].tx_desk_rsgb_par); else phy_tus = 0; err = ice_write_40b_phy_reg_e822(hw, port, P_REG_DESK_PAR_TX_TUS_L, phy_tus); if (err) return err; /* P_REG_DESK_PAR_RX_TUS */ if (e822_vernier[link_spd].rx_desk_rsgb_par) phy_tus = div_u64(tu_per_sec, e822_vernier[link_spd].rx_desk_rsgb_par); else phy_tus = 0; err = ice_write_40b_phy_reg_e822(hw, port, P_REG_DESK_PAR_RX_TUS_L, phy_tus); if (err) return err; /* P_REG_DESK_PCS_TX_TUS */ if (e822_vernier[link_spd].tx_desk_rsgb_pcs) phy_tus = div_u64(tu_per_sec, e822_vernier[link_spd].tx_desk_rsgb_pcs); else phy_tus = 0; err = ice_write_40b_phy_reg_e822(hw, port, P_REG_DESK_PCS_TX_TUS_L, phy_tus); if (err) return err; /* P_REG_DESK_PCS_RX_TUS */ if (e822_vernier[link_spd].rx_desk_rsgb_pcs) phy_tus = div_u64(tu_per_sec, e822_vernier[link_spd].rx_desk_rsgb_pcs); else phy_tus = 0; return ice_write_40b_phy_reg_e822(hw, port, P_REG_DESK_PCS_RX_TUS_L, phy_tus); } /** * ice_calc_fixed_tx_offset_e822 - Calculated Fixed Tx offset for a port * @hw: pointer to the HW struct * @link_spd: the Link speed to calculate for * * Calculate the fixed offset due to known static latency data. */ static u64 ice_calc_fixed_tx_offset_e822(struct ice_hw *hw, enum ice_ptp_link_spd link_spd) { u64 cur_freq, clk_incval, tu_per_sec, fixed_offset; cur_freq = ice_e822_pll_freq(ice_e822_time_ref(hw)); clk_incval = ice_ptp_read_src_incval(hw); /* Calculate TUs per second */ tu_per_sec = cur_freq * clk_incval; /* Calculate number of TUs to add for the fixed Tx latency. Since the * latency measurement is in 1/100th of a nanosecond, we need to * multiply by tu_per_sec and then divide by 1e11. This calculation * overflows 64 bit integer arithmetic, so break it up into two * divisions by 1e4 first then by 1e7. */ fixed_offset = div_u64(tu_per_sec, 10000); fixed_offset *= e822_vernier[link_spd].tx_fixed_delay; fixed_offset = div_u64(fixed_offset, 10000000); return fixed_offset; } /** * ice_phy_cfg_tx_offset_e822 - Configure total Tx timestamp offset * @hw: pointer to the HW struct * @port: the PHY port to configure * * Program the P_REG_TOTAL_TX_OFFSET register with the total number of TUs to * adjust Tx timestamps by. This is calculated by combining some known static * latency along with the Vernier offset computations done by hardware. * * This function will not return successfully until the Tx offset calculations * have been completed, which requires waiting until at least one packet has * been transmitted by the device. It is safe to call this function * periodically until calibration succeeds, as it will only program the offset * once. * * To avoid overflow, when calculating the offset based on the known static * latency values, we use measurements in 1/100th of a nanosecond, and divide * the TUs per second up front. This avoids overflow while allowing * calculation of the adjustment using integer arithmetic. * * Returns zero on success, -EBUSY if the hardware vernier offset * calibration has not completed, or another error code on failure. */ int ice_phy_cfg_tx_offset_e822(struct ice_hw *hw, u8 port) { enum ice_ptp_link_spd link_spd; enum ice_ptp_fec_mode fec_mode; u64 total_offset, val; int err; u32 reg; /* Nothing to do if we've already programmed the offset */ err = ice_read_phy_reg_e822(hw, port, P_REG_TX_OR, &reg); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read TX_OR for port %u, err %d\n", port, err); return err; } if (reg) return 0; err = ice_read_phy_reg_e822(hw, port, P_REG_TX_OV_STATUS, &reg); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read TX_OV_STATUS for port %u, err %d\n", port, err); return err; } if (!(reg & P_REG_TX_OV_STATUS_OV_M)) return -EBUSY; err = ice_phy_get_speed_and_fec_e822(hw, port, &link_spd, &fec_mode); if (err) return err; total_offset = ice_calc_fixed_tx_offset_e822(hw, link_spd); /* Read the first Vernier offset from the PHY register and add it to * the total offset. */ if (link_spd == ICE_PTP_LNK_SPD_1G || link_spd == ICE_PTP_LNK_SPD_10G || link_spd == ICE_PTP_LNK_SPD_25G || link_spd == ICE_PTP_LNK_SPD_25G_RS || link_spd == ICE_PTP_LNK_SPD_40G || link_spd == ICE_PTP_LNK_SPD_50G) { err = ice_read_64b_phy_reg_e822(hw, port, P_REG_PAR_PCS_TX_OFFSET_L, &val); if (err) return err; total_offset += val; } /* For Tx, we only need to use the second Vernier offset for * multi-lane link speeds with RS-FEC. The lanes will always be * aligned. */ if (link_spd == ICE_PTP_LNK_SPD_50G_RS || link_spd == ICE_PTP_LNK_SPD_100G_RS) { err = ice_read_64b_phy_reg_e822(hw, port, P_REG_PAR_TX_TIME_L, &val); if (err) return err; total_offset += val; } /* Now that the total offset has been calculated, program it to the * PHY and indicate that the Tx offset is ready. After this, * timestamps will be enabled. */ err = ice_write_64b_phy_reg_e822(hw, port, P_REG_TOTAL_TX_OFFSET_L, total_offset); if (err) return err; err = ice_write_phy_reg_e822(hw, port, P_REG_TX_OR, 1); if (err) return err; dev_info(ice_hw_to_dev(hw), "Port=%d Tx vernier offset calibration complete\n", port); return 0; } /** * ice_phy_calc_pmd_adj_e822 - Calculate PMD adjustment for Rx * @hw: pointer to the HW struct * @port: the PHY port to adjust for * @link_spd: the current link speed of the PHY * @fec_mode: the current FEC mode of the PHY * @pmd_adj: on return, the amount to adjust the Rx total offset by * * Calculates the adjustment to Rx timestamps due to PMD alignment in the PHY. * This varies by link speed and FEC mode. The value calculated accounts for * various delays caused when receiving a packet. */ static int ice_phy_calc_pmd_adj_e822(struct ice_hw *hw, u8 port, enum ice_ptp_link_spd link_spd, enum ice_ptp_fec_mode fec_mode, u64 *pmd_adj) { u64 cur_freq, clk_incval, tu_per_sec, mult, adj; u8 pmd_align; u32 val; int err; err = ice_read_phy_reg_e822(hw, port, P_REG_PMD_ALIGNMENT, &val); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read PMD alignment, err %d\n", err); return err; } pmd_align = (u8)val; cur_freq = ice_e822_pll_freq(ice_e822_time_ref(hw)); clk_incval = ice_ptp_read_src_incval(hw); /* Calculate TUs per second */ tu_per_sec = cur_freq * clk_incval; /* The PMD alignment adjustment measurement depends on the link speed, * and whether FEC is enabled. For each link speed, the alignment * adjustment is calculated by dividing a value by the length of * a Time Unit in nanoseconds. * * 1G: align == 4 ? 10 * 0.8 : (align + 6 % 10) * 0.8 * 10G: align == 65 ? 0 : (align * 0.1 * 32/33) * 10G w/FEC: align * 0.1 * 32/33 * 25G: align == 65 ? 0 : (align * 0.4 * 32/33) * 25G w/FEC: align * 0.4 * 32/33 * 40G: align == 65 ? 0 : (align * 0.1 * 32/33) * 40G w/FEC: align * 0.1 * 32/33 * 50G: align == 65 ? 0 : (align * 0.4 * 32/33) * 50G w/FEC: align * 0.8 * 32/33 * * For RS-FEC, if align is < 17 then we must also add 1.6 * 32/33. * * To allow for calculating this value using integer arithmetic, we * instead start with the number of TUs per second, (inverse of the * length of a Time Unit in nanoseconds), multiply by a value based * on the PMD alignment register, and then divide by the right value * calculated based on the table above. To avoid integer overflow this * division is broken up into a step of dividing by 125 first. */ if (link_spd == ICE_PTP_LNK_SPD_1G) { if (pmd_align == 4) mult = 10; else mult = (pmd_align + 6) % 10; } else if (link_spd == ICE_PTP_LNK_SPD_10G || link_spd == ICE_PTP_LNK_SPD_25G || link_spd == ICE_PTP_LNK_SPD_40G || link_spd == ICE_PTP_LNK_SPD_50G) { /* If Clause 74 FEC, always calculate PMD adjust */ if (pmd_align != 65 || fec_mode == ICE_PTP_FEC_MODE_CLAUSE74) mult = pmd_align; else mult = 0; } else if (link_spd == ICE_PTP_LNK_SPD_25G_RS || link_spd == ICE_PTP_LNK_SPD_50G_RS || link_spd == ICE_PTP_LNK_SPD_100G_RS) { if (pmd_align < 17) mult = pmd_align + 40; else mult = pmd_align; } else { ice_debug(hw, ICE_DBG_PTP, "Unknown link speed %d, skipping PMD adjustment\n", link_spd); mult = 0; } /* In some cases, there's no need to adjust for the PMD alignment */ if (!mult) { *pmd_adj = 0; return 0; } /* Calculate the adjustment by multiplying TUs per second by the * appropriate multiplier and divisor. To avoid overflow, we first * divide by 125, and then handle remaining divisor based on the link * speed pmd_adj_divisor value. */ adj = div_u64(tu_per_sec, 125); adj *= mult; adj = div_u64(adj, e822_vernier[link_spd].pmd_adj_divisor); /* Finally, for 25G-RS and 50G-RS, a further adjustment for the Rx * cycle count is necessary. */ if (link_spd == ICE_PTP_LNK_SPD_25G_RS) { u64 cycle_adj; u8 rx_cycle; err = ice_read_phy_reg_e822(hw, port, P_REG_RX_40_TO_160_CNT, &val); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read 25G-RS Rx cycle count, err %d\n", err); return err; } rx_cycle = val & P_REG_RX_40_TO_160_CNT_RXCYC_M; if (rx_cycle) { mult = (4 - rx_cycle) * 40; cycle_adj = div_u64(tu_per_sec, 125); cycle_adj *= mult; cycle_adj = div_u64(cycle_adj, e822_vernier[link_spd].pmd_adj_divisor); adj += cycle_adj; } } else if (link_spd == ICE_PTP_LNK_SPD_50G_RS) { u64 cycle_adj; u8 rx_cycle; err = ice_read_phy_reg_e822(hw, port, P_REG_RX_80_TO_160_CNT, &val); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read 50G-RS Rx cycle count, err %d\n", err); return err; } rx_cycle = val & P_REG_RX_80_TO_160_CNT_RXCYC_M; if (rx_cycle) { mult = rx_cycle * 40; cycle_adj = div_u64(tu_per_sec, 125); cycle_adj *= mult; cycle_adj = div_u64(cycle_adj, e822_vernier[link_spd].pmd_adj_divisor); adj += cycle_adj; } } /* Return the calculated adjustment */ *pmd_adj = adj; return 0; } /** * ice_calc_fixed_rx_offset_e822 - Calculated the fixed Rx offset for a port * @hw: pointer to HW struct * @link_spd: The Link speed to calculate for * * Determine the fixed Rx latency for a given link speed. */ static u64 ice_calc_fixed_rx_offset_e822(struct ice_hw *hw, enum ice_ptp_link_spd link_spd) { u64 cur_freq, clk_incval, tu_per_sec, fixed_offset; cur_freq = ice_e822_pll_freq(ice_e822_time_ref(hw)); clk_incval = ice_ptp_read_src_incval(hw); /* Calculate TUs per second */ tu_per_sec = cur_freq * clk_incval; /* Calculate number of TUs to add for the fixed Rx latency. Since the * latency measurement is in 1/100th of a nanosecond, we need to * multiply by tu_per_sec and then divide by 1e11. This calculation * overflows 64 bit integer arithmetic, so break it up into two * divisions by 1e4 first then by 1e7. */ fixed_offset = div_u64(tu_per_sec, 10000); fixed_offset *= e822_vernier[link_spd].rx_fixed_delay; fixed_offset = div_u64(fixed_offset, 10000000); return fixed_offset; } /** * ice_phy_cfg_rx_offset_e822 - Configure total Rx timestamp offset * @hw: pointer to the HW struct * @port: the PHY port to configure * * Program the P_REG_TOTAL_RX_OFFSET register with the number of Time Units to * adjust Rx timestamps by. This combines calculations from the Vernier offset * measurements taken in hardware with some data about known fixed delay as * well as adjusting for multi-lane alignment delay. * * This function will not return successfully until the Rx offset calculations * have been completed, which requires waiting until at least one packet has * been received by the device. It is safe to call this function periodically * until calibration succeeds, as it will only program the offset once. * * This function must be called only after the offset registers are valid, * i.e. after the Vernier calibration wait has passed, to ensure that the PHY * has measured the offset. * * To avoid overflow, when calculating the offset based on the known static * latency values, we use measurements in 1/100th of a nanosecond, and divide * the TUs per second up front. This avoids overflow while allowing * calculation of the adjustment using integer arithmetic. * * Returns zero on success, -EBUSY if the hardware vernier offset * calibration has not completed, or another error code on failure. */ int ice_phy_cfg_rx_offset_e822(struct ice_hw *hw, u8 port) { enum ice_ptp_link_spd link_spd; enum ice_ptp_fec_mode fec_mode; u64 total_offset, pmd, val; int err; u32 reg; /* Nothing to do if we've already programmed the offset */ err = ice_read_phy_reg_e822(hw, port, P_REG_RX_OR, &reg); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read RX_OR for port %u, err %d\n", port, err); return err; } if (reg) return 0; err = ice_read_phy_reg_e822(hw, port, P_REG_RX_OV_STATUS, &reg); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read RX_OV_STATUS for port %u, err %d\n", port, err); return err; } if (!(reg & P_REG_RX_OV_STATUS_OV_M)) return -EBUSY; err = ice_phy_get_speed_and_fec_e822(hw, port, &link_spd, &fec_mode); if (err) return err; total_offset = ice_calc_fixed_rx_offset_e822(hw, link_spd); /* Read the first Vernier offset from the PHY register and add it to * the total offset. */ err = ice_read_64b_phy_reg_e822(hw, port, P_REG_PAR_PCS_RX_OFFSET_L, &val); if (err) return err; total_offset += val; /* For Rx, all multi-lane link speeds include a second Vernier * calibration, because the lanes might not be aligned. */ if (link_spd == ICE_PTP_LNK_SPD_40G || link_spd == ICE_PTP_LNK_SPD_50G || link_spd == ICE_PTP_LNK_SPD_50G_RS || link_spd == ICE_PTP_LNK_SPD_100G_RS) { err = ice_read_64b_phy_reg_e822(hw, port, P_REG_PAR_RX_TIME_L, &val); if (err) return err; total_offset += val; } /* In addition, Rx must account for the PMD alignment */ err = ice_phy_calc_pmd_adj_e822(hw, port, link_spd, fec_mode, &pmd); if (err) return err; /* For RS-FEC, this adjustment adds delay, but for other modes, it * subtracts delay. */ if (fec_mode == ICE_PTP_FEC_MODE_RS_FEC) total_offset += pmd; else total_offset -= pmd; /* Now that the total offset has been calculated, program it to the * PHY and indicate that the Rx offset is ready. After this, * timestamps will be enabled. */ err = ice_write_64b_phy_reg_e822(hw, port, P_REG_TOTAL_RX_OFFSET_L, total_offset); if (err) return err; err = ice_write_phy_reg_e822(hw, port, P_REG_RX_OR, 1); if (err) return err; dev_info(ice_hw_to_dev(hw), "Port=%d Rx vernier offset calibration complete\n", port); return 0; } /** * ice_read_phy_and_phc_time_e822 - Simultaneously capture PHC and PHY time * @hw: pointer to the HW struct * @port: the PHY port to read * @phy_time: on return, the 64bit PHY timer value * @phc_time: on return, the lower 64bits of PHC time * * Issue a READ_TIME timer command to simultaneously capture the PHY and PHC * timer values. */ static int ice_read_phy_and_phc_time_e822(struct ice_hw *hw, u8 port, u64 *phy_time, u64 *phc_time) { u64 tx_time, rx_time; u32 zo, lo; u8 tmr_idx; int err; tmr_idx = ice_get_ptp_src_clock_index(hw); /* Prepare the PHC timer for a READ_TIME capture command */ ice_ptp_src_cmd(hw, READ_TIME); /* Prepare the PHY timer for a READ_TIME capture command */ err = ice_ptp_one_port_cmd(hw, port, READ_TIME); if (err) return err; /* Issue the sync to start the READ_TIME capture */ ice_ptp_exec_tmr_cmd(hw); /* Read the captured PHC time from the shadow time registers */ zo = rd32(hw, GLTSYN_SHTIME_0(tmr_idx)); lo = rd32(hw, GLTSYN_SHTIME_L(tmr_idx)); *phc_time = (u64)lo << 32 | zo; /* Read the captured PHY time from the PHY shadow registers */ err = ice_ptp_read_port_capture(hw, port, &tx_time, &rx_time); if (err) return err; /* If the PHY Tx and Rx timers don't match, log a warning message. * Note that this should not happen in normal circumstances since the * driver always programs them together. */ if (tx_time != rx_time) dev_warn(ice_hw_to_dev(hw), "PHY port %u Tx and Rx timers do not match, tx_time 0x%016llX, rx_time 0x%016llX\n", port, (unsigned long long)tx_time, (unsigned long long)rx_time); *phy_time = tx_time; return 0; } /** * ice_sync_phy_timer_e822 - Synchronize the PHY timer with PHC timer * @hw: pointer to the HW struct * @port: the PHY port to synchronize * * Perform an adjustment to ensure that the PHY and PHC timers are in sync. * This is done by issuing a READ_TIME command which triggers a simultaneous * read of the PHY timer and PHC timer. Then we use the difference to * calculate an appropriate 2s complement addition to add to the PHY timer in * order to ensure it reads the same value as the primary PHC timer. */ static int ice_sync_phy_timer_e822(struct ice_hw *hw, u8 port) { u64 phc_time, phy_time, difference; int err; if (!ice_ptp_lock(hw)) { ice_debug(hw, ICE_DBG_PTP, "Failed to acquire PTP semaphore\n"); return -EBUSY; } err = ice_read_phy_and_phc_time_e822(hw, port, &phy_time, &phc_time); if (err) goto err_unlock; /* Calculate the amount required to add to the port time in order for * it to match the PHC time. * * Note that the port adjustment is done using 2s complement * arithmetic. This is convenient since it means that we can simply * calculate the difference between the PHC time and the port time, * and it will be interpreted correctly. */ difference = phc_time - phy_time; err = ice_ptp_prep_port_adj_e822(hw, port, (s64)difference); if (err) goto err_unlock; err = ice_ptp_one_port_cmd(hw, port, ADJ_TIME); if (err) goto err_unlock; /* Do not perform any action on the main timer */ ice_ptp_src_cmd(hw, ICE_PTP_NOP); /* Issue the sync to activate the time adjustment */ ice_ptp_exec_tmr_cmd(hw); /* Re-capture the timer values to flush the command registers and * verify that the time was properly adjusted. */ err = ice_read_phy_and_phc_time_e822(hw, port, &phy_time, &phc_time); if (err) goto err_unlock; dev_info(ice_hw_to_dev(hw), "Port %u PHY time synced to PHC: 0x%016llX, 0x%016llX\n", port, (unsigned long long)phy_time, (unsigned long long)phc_time); ice_ptp_unlock(hw); return 0; err_unlock: ice_ptp_unlock(hw); return err; } /** * ice_stop_phy_timer_e822 - Stop the PHY clock timer * @hw: pointer to the HW struct * @port: the PHY port to stop * @soft_reset: if true, hold the SOFT_RESET bit of P_REG_PS * * Stop the clock of a PHY port. This must be done as part of the flow to * re-calibrate Tx and Rx timestamping offsets whenever the clock time is * initialized or when link speed changes. */ int ice_stop_phy_timer_e822(struct ice_hw *hw, u8 port, bool soft_reset) { int err; u32 val; err = ice_write_phy_reg_e822(hw, port, P_REG_TX_OR, 0); if (err) return err; err = ice_write_phy_reg_e822(hw, port, P_REG_RX_OR, 0); if (err) return err; err = ice_read_phy_reg_e822(hw, port, P_REG_PS, &val); if (err) return err; val &= ~P_REG_PS_START_M; err = ice_write_phy_reg_e822(hw, port, P_REG_PS, val); if (err) return err; val &= ~P_REG_PS_ENA_CLK_M; err = ice_write_phy_reg_e822(hw, port, P_REG_PS, val); if (err) return err; if (soft_reset) { val |= P_REG_PS_SFT_RESET_M; err = ice_write_phy_reg_e822(hw, port, P_REG_PS, val); if (err) return err; } ice_debug(hw, ICE_DBG_PTP, "Disabled clock on PHY port %u\n", port); return 0; } /** * ice_start_phy_timer_e822 - Start the PHY clock timer * @hw: pointer to the HW struct * @port: the PHY port to start * * Start the clock of a PHY port. This must be done as part of the flow to * re-calibrate Tx and Rx timestamping offsets whenever the clock time is * initialized or when link speed changes. * * Hardware will take Vernier measurements on Tx or Rx of packets. */ int ice_start_phy_timer_e822(struct ice_hw *hw, u8 port) { u32 lo, hi, val; u64 incval; u8 tmr_idx; int err; tmr_idx = ice_get_ptp_src_clock_index(hw); err = ice_stop_phy_timer_e822(hw, port, false); if (err) return err; ice_phy_cfg_lane_e822(hw, port); err = ice_phy_cfg_uix_e822(hw, port); if (err) return err; err = ice_phy_cfg_parpcs_e822(hw, port); if (err) return err; lo = rd32(hw, GLTSYN_INCVAL_L(tmr_idx)); hi = rd32(hw, GLTSYN_INCVAL_H(tmr_idx)); incval = (u64)hi << 32 | lo; err = ice_write_40b_phy_reg_e822(hw, port, P_REG_TIMETUS_L, incval); if (err) return err; err = ice_ptp_one_port_cmd(hw, port, INIT_INCVAL); if (err) return err; /* Do not perform any action on the main timer */ ice_ptp_src_cmd(hw, ICE_PTP_NOP); ice_ptp_exec_tmr_cmd(hw); err = ice_read_phy_reg_e822(hw, port, P_REG_PS, &val); if (err) return err; val |= P_REG_PS_SFT_RESET_M; err = ice_write_phy_reg_e822(hw, port, P_REG_PS, val); if (err) return err; val |= P_REG_PS_START_M; err = ice_write_phy_reg_e822(hw, port, P_REG_PS, val); if (err) return err; val &= ~P_REG_PS_SFT_RESET_M; err = ice_write_phy_reg_e822(hw, port, P_REG_PS, val); if (err) return err; err = ice_ptp_one_port_cmd(hw, port, INIT_INCVAL); if (err) return err; ice_ptp_exec_tmr_cmd(hw); val |= P_REG_PS_ENA_CLK_M; err = ice_write_phy_reg_e822(hw, port, P_REG_PS, val); if (err) return err; val |= P_REG_PS_LOAD_OFFSET_M; err = ice_write_phy_reg_e822(hw, port, P_REG_PS, val); if (err) return err; ice_ptp_exec_tmr_cmd(hw); err = ice_sync_phy_timer_e822(hw, port); if (err) return err; ice_debug(hw, ICE_DBG_PTP, "Enabled clock on PHY port %u\n", port); return 0; } /** * ice_get_phy_tx_tstamp_ready_e822 - Read Tx memory status register * @hw: pointer to the HW struct * @quad: the timestamp quad to read from * @tstamp_ready: contents of the Tx memory status register * * Read the Q_REG_TX_MEMORY_STATUS register indicating which timestamps in * the PHY are ready. A set bit means the corresponding timestamp is valid and * ready to be captured from the PHY timestamp block. */ static int ice_get_phy_tx_tstamp_ready_e822(struct ice_hw *hw, u8 quad, u64 *tstamp_ready) { u32 hi, lo; int err; err = ice_read_quad_reg_e822(hw, quad, Q_REG_TX_MEMORY_STATUS_U, &hi); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read TX_MEMORY_STATUS_U for quad %u, err %d\n", quad, err); return err; } err = ice_read_quad_reg_e822(hw, quad, Q_REG_TX_MEMORY_STATUS_L, &lo); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read TX_MEMORY_STATUS_L for quad %u, err %d\n", quad, err); return err; } *tstamp_ready = (u64)hi << 32 | (u64)lo; return 0; } /* E810 functions * * The following functions operate on the E810 series devices which use * a separate external PHY. */ /** * ice_read_phy_reg_e810 - Read register from external PHY on E810 * @hw: pointer to the HW struct * @addr: the address to read from * @val: On return, the value read from the PHY * * Read a register from the external PHY on the E810 device. */ static int ice_read_phy_reg_e810(struct ice_hw *hw, u32 addr, u32 *val) { struct ice_sbq_msg_input msg = {0}; int err; msg.msg_addr_low = lower_16_bits(addr); msg.msg_addr_high = upper_16_bits(addr); msg.opcode = ice_sbq_msg_rd; msg.dest_dev = rmn_0; err = ice_sbq_rw_reg(hw, &msg); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to send message to PHY, err %d\n", err); return err; } *val = msg.data; return 0; } /** * ice_write_phy_reg_e810 - Write register on external PHY on E810 * @hw: pointer to the HW struct * @addr: the address to writem to * @val: the value to write to the PHY * * Write a value to a register of the external PHY on the E810 device. */ static int ice_write_phy_reg_e810(struct ice_hw *hw, u32 addr, u32 val) { struct ice_sbq_msg_input msg = {0}; int err; msg.msg_addr_low = lower_16_bits(addr); msg.msg_addr_high = upper_16_bits(addr); msg.opcode = ice_sbq_msg_wr; msg.dest_dev = rmn_0; msg.data = val; err = ice_sbq_rw_reg(hw, &msg); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to send message to PHY, err %d\n", err); return err; } return 0; } /** * ice_read_phy_tstamp_ll_e810 - Read a PHY timestamp registers through the FW * @hw: pointer to the HW struct * @idx: the timestamp index to read * @hi: 8 bit timestamp high value * @lo: 32 bit timestamp low value * * Read a 8bit timestamp high value and 32 bit timestamp low value out of the * timestamp block of the external PHY on the E810 device using the low latency * timestamp read. */ static int ice_read_phy_tstamp_ll_e810(struct ice_hw *hw, u8 idx, u8 *hi, u32 *lo) { u32 val; u8 i; /* Write TS index to read to the PF register so the FW can read it */ val = FIELD_PREP(TS_LL_READ_TS_IDX, idx) | TS_LL_READ_TS; wr32(hw, PF_SB_ATQBAL, val); /* Read the register repeatedly until the FW provides us the TS */ for (i = TS_LL_READ_RETRIES; i > 0; i--) { val = rd32(hw, PF_SB_ATQBAL); /* When the bit is cleared, the TS is ready in the register */ if (!(FIELD_GET(TS_LL_READ_TS, val))) { /* High 8 bit value of the TS is on the bits 16:23 */ *hi = FIELD_GET(TS_LL_READ_TS_HIGH, val); /* Read the low 32 bit value and set the TS valid bit */ *lo = rd32(hw, PF_SB_ATQBAH) | TS_VALID; return 0; } udelay(10); } /* FW failed to provide the TS in time */ ice_debug(hw, ICE_DBG_PTP, "Failed to read PTP timestamp using low latency read\n"); return -EINVAL; } /** * ice_read_phy_tstamp_sbq_e810 - Read a PHY timestamp registers through the sbq * @hw: pointer to the HW struct * @lport: the lport to read from * @idx: the timestamp index to read * @hi: 8 bit timestamp high value * @lo: 32 bit timestamp low value * * Read a 8bit timestamp high value and 32 bit timestamp low value out of the * timestamp block of the external PHY on the E810 device using sideband queue. */ static int ice_read_phy_tstamp_sbq_e810(struct ice_hw *hw, u8 lport, u8 idx, u8 *hi, u32 *lo) { u32 hi_addr = TS_EXT(HIGH_TX_MEMORY_BANK_START, lport, idx); u32 lo_addr = TS_EXT(LOW_TX_MEMORY_BANK_START, lport, idx); u32 lo_val, hi_val; int err; err = ice_read_phy_reg_e810(hw, lo_addr, &lo_val); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read low PTP timestamp register, err %d\n", err); return err; } err = ice_read_phy_reg_e810(hw, hi_addr, &hi_val); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read high PTP timestamp register, err %d\n", err); return err; } *lo = lo_val; *hi = (u8)hi_val; return 0; } /** * ice_read_phy_tstamp_e810 - Read a PHY timestamp out of the external PHY * @hw: pointer to the HW struct * @lport: the lport to read from * @idx: the timestamp index to read * @tstamp: on return, the 40bit timestamp value * * Read a 40bit timestamp value out of the timestamp block of the external PHY * on the E810 device. */ static int ice_read_phy_tstamp_e810(struct ice_hw *hw, u8 lport, u8 idx, u64 *tstamp) { u32 lo = 0; u8 hi = 0; int err; if (hw->dev_caps.ts_dev_info.ts_ll_read) err = ice_read_phy_tstamp_ll_e810(hw, idx, &hi, &lo); else err = ice_read_phy_tstamp_sbq_e810(hw, lport, idx, &hi, &lo); if (err) return err; /* For E810 devices, the timestamp is reported with the lower 32 bits * in the low register, and the upper 8 bits in the high register. */ *tstamp = ((u64)hi) << TS_HIGH_S | ((u64)lo & TS_LOW_M); return 0; } /** * ice_clear_phy_tstamp_e810 - Clear a timestamp from the external PHY * @hw: pointer to the HW struct * @lport: the lport to read from * @idx: the timestamp index to reset * * Clear a timestamp, resetting its valid bit, from the timestamp block of the * external PHY on the E810 device. */ static int ice_clear_phy_tstamp_e810(struct ice_hw *hw, u8 lport, u8 idx) { u32 lo_addr, hi_addr; int err; lo_addr = TS_EXT(LOW_TX_MEMORY_BANK_START, lport, idx); hi_addr = TS_EXT(HIGH_TX_MEMORY_BANK_START, lport, idx); err = ice_write_phy_reg_e810(hw, lo_addr, 0); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to clear low PTP timestamp register, err %d\n", err); return err; } err = ice_write_phy_reg_e810(hw, hi_addr, 0); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to clear high PTP timestamp register, err %d\n", err); return err; } return 0; } /** * ice_ptp_init_phy_e810 - Enable PTP function on the external PHY * @hw: pointer to HW struct * * Enable the timesync PTP functionality for the external PHY connected to * this function. */ int ice_ptp_init_phy_e810(struct ice_hw *hw) { u8 tmr_idx; int err; tmr_idx = hw->func_caps.ts_func_info.tmr_index_owned; err = ice_write_phy_reg_e810(hw, ETH_GLTSYN_ENA(tmr_idx), GLTSYN_ENA_TSYN_ENA_M); if (err) ice_debug(hw, ICE_DBG_PTP, "PTP failed in ena_phy_time_syn %d\n", err); return err; } /** * ice_ptp_init_phc_e810 - Perform E810 specific PHC initialization * @hw: pointer to HW struct * * Perform E810-specific PTP hardware clock initialization steps. */ static int ice_ptp_init_phc_e810(struct ice_hw *hw) { /* Ensure synchronization delay is zero */ wr32(hw, GLTSYN_SYNC_DLAY, 0); /* Initialize the PHY */ return ice_ptp_init_phy_e810(hw); } /** * ice_ptp_prep_phy_time_e810 - Prepare PHY port with initial time * @hw: Board private structure * @time: Time to initialize the PHY port clock to * * Program the PHY port ETH_GLTSYN_SHTIME registers in preparation setting the * initial clock time. The time will not actually be programmed until the * driver issues an INIT_TIME command. * * The time value is the upper 32 bits of the PHY timer, usually in units of * nominal nanoseconds. */ static int ice_ptp_prep_phy_time_e810(struct ice_hw *hw, u32 time) { u8 tmr_idx; int err; tmr_idx = hw->func_caps.ts_func_info.tmr_index_owned; err = ice_write_phy_reg_e810(hw, ETH_GLTSYN_SHTIME_0(tmr_idx), 0); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to write SHTIME_0, err %d\n", err); return err; } err = ice_write_phy_reg_e810(hw, ETH_GLTSYN_SHTIME_L(tmr_idx), time); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to write SHTIME_L, err %d\n", err); return err; } return 0; } /** * ice_ptp_prep_phy_adj_e810 - Prep PHY port for a time adjustment * @hw: pointer to HW struct * @adj: adjustment value to program * * Prepare the PHY port for an atomic adjustment by programming the PHY * ETH_GLTSYN_SHADJ_L and ETH_GLTSYN_SHADJ_H registers. The actual adjustment * is completed by issuing an ADJ_TIME sync command. * * The adjustment value only contains the portion used for the upper 32bits of * the PHY timer, usually in units of nominal nanoseconds. Negative * adjustments are supported using 2s complement arithmetic. */ static int ice_ptp_prep_phy_adj_e810(struct ice_hw *hw, s32 adj) { u8 tmr_idx; int err; tmr_idx = hw->func_caps.ts_func_info.tmr_index_owned; /* Adjustments are represented as signed 2's complement values in * nanoseconds. Sub-nanosecond adjustment is not supported. */ err = ice_write_phy_reg_e810(hw, ETH_GLTSYN_SHADJ_L(tmr_idx), 0); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to write adj to PHY SHADJ_L, err %d\n", err); return err; } err = ice_write_phy_reg_e810(hw, ETH_GLTSYN_SHADJ_H(tmr_idx), adj); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to write adj to PHY SHADJ_H, err %d\n", err); return err; } return 0; } /** * ice_ptp_prep_phy_incval_e810 - Prep PHY port increment value change * @hw: pointer to HW struct * @incval: The new 40bit increment value to prepare * * Prepare the PHY port for a new increment value by programming the PHY * ETH_GLTSYN_SHADJ_L and ETH_GLTSYN_SHADJ_H registers. The actual change is * completed by issuing an INIT_INCVAL command. */ static int ice_ptp_prep_phy_incval_e810(struct ice_hw *hw, u64 incval) { u32 high, low; u8 tmr_idx; int err; tmr_idx = hw->func_caps.ts_func_info.tmr_index_owned; low = lower_32_bits(incval); high = upper_32_bits(incval); err = ice_write_phy_reg_e810(hw, ETH_GLTSYN_SHADJ_L(tmr_idx), low); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to write incval to PHY SHADJ_L, err %d\n", err); return err; } err = ice_write_phy_reg_e810(hw, ETH_GLTSYN_SHADJ_H(tmr_idx), high); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to write incval PHY SHADJ_H, err %d\n", err); return err; } return 0; } /** * ice_ptp_port_cmd_e810 - Prepare all external PHYs for a timer command * @hw: pointer to HW struct * @cmd: Command to be sent to the port * * Prepare the external PHYs connected to this device for a timer sync * command. */ static int ice_ptp_port_cmd_e810(struct ice_hw *hw, enum ice_ptp_tmr_cmd cmd) { u32 cmd_val, val; int err; switch (cmd) { case INIT_TIME: cmd_val = GLTSYN_CMD_INIT_TIME; break; case INIT_INCVAL: cmd_val = GLTSYN_CMD_INIT_INCVAL; break; case ADJ_TIME: cmd_val = GLTSYN_CMD_ADJ_TIME; break; case READ_TIME: cmd_val = GLTSYN_CMD_READ_TIME; break; case ADJ_TIME_AT_TIME: cmd_val = GLTSYN_CMD_ADJ_INIT_TIME; break; case ICE_PTP_NOP: return 0; } /* Read, modify, write */ err = ice_read_phy_reg_e810(hw, ETH_GLTSYN_CMD, &val); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to read GLTSYN_CMD, err %d\n", err); return err; } /* Modify necessary bits only and perform write */ val &= ~TS_CMD_MASK_E810; val |= cmd_val; err = ice_write_phy_reg_e810(hw, ETH_GLTSYN_CMD, val); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to write back GLTSYN_CMD, err %d\n", err); return err; } return 0; } /** * ice_get_phy_tx_tstamp_ready_e810 - Read Tx memory status register * @hw: pointer to the HW struct * @port: the PHY port to read * @tstamp_ready: contents of the Tx memory status register * * E810 devices do not use a Tx memory status register. Instead simply * indicate that all timestamps are currently ready. */ static int ice_get_phy_tx_tstamp_ready_e810(struct ice_hw *hw, u8 port, u64 *tstamp_ready) { *tstamp_ready = 0xFFFFFFFFFFFFFFFF; return 0; } /* E810T SMA functions * * The following functions operate specifically on E810T hardware and are used * to access the extended GPIOs available. */ /** * ice_get_pca9575_handle * @hw: pointer to the hw struct * @pca9575_handle: GPIO controller's handle * * Find and return the GPIO controller's handle in the netlist. * When found - the value will be cached in the hw structure and following calls * will return cached value */ static int ice_get_pca9575_handle(struct ice_hw *hw, u16 *pca9575_handle) { struct ice_aqc_get_link_topo *cmd; struct ice_aq_desc desc; int status; u8 idx; /* If handle was read previously return cached value */ if (hw->io_expander_handle) { *pca9575_handle = hw->io_expander_handle; return 0; } /* If handle was not detected read it from the netlist */ cmd = &desc.params.get_link_topo; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_get_link_topo); /* Set node type to GPIO controller */ cmd->addr.topo_params.node_type_ctx = (ICE_AQC_LINK_TOPO_NODE_TYPE_M & ICE_AQC_LINK_TOPO_NODE_TYPE_GPIO_CTRL); #define SW_PCA9575_SFP_TOPO_IDX 2 #define SW_PCA9575_QSFP_TOPO_IDX 1 /* Check if the SW IO expander controlling SMA exists in the netlist. */ if (hw->device_id == ICE_DEV_ID_E810C_SFP) idx = SW_PCA9575_SFP_TOPO_IDX; else if (hw->device_id == ICE_DEV_ID_E810C_QSFP) idx = SW_PCA9575_QSFP_TOPO_IDX; else return -EOPNOTSUPP; cmd->addr.topo_params.index = idx; status = ice_aq_send_cmd(hw, &desc, NULL, 0, NULL); if (status) return -EOPNOTSUPP; /* Verify if we found the right IO expander type */ if (desc.params.get_link_topo.node_part_num != ICE_AQC_GET_LINK_TOPO_NODE_NR_PCA9575) return -EOPNOTSUPP; /* If present save the handle and return it */ hw->io_expander_handle = le16_to_cpu(desc.params.get_link_topo.addr.handle); *pca9575_handle = hw->io_expander_handle; return 0; } /** * ice_read_sma_ctrl_e810t * @hw: pointer to the hw struct * @data: pointer to data to be read from the GPIO controller * * Read the SMA controller state. It is connected to pins 3-7 of Port 1 of the * PCA9575 expander, so only bits 3-7 in data are valid. */ int ice_read_sma_ctrl_e810t(struct ice_hw *hw, u8 *data) { int status; u16 handle; u8 i; status = ice_get_pca9575_handle(hw, &handle); if (status) return status; *data = 0; for (i = ICE_SMA_MIN_BIT_E810T; i <= ICE_SMA_MAX_BIT_E810T; i++) { bool pin; status = ice_aq_get_gpio(hw, handle, i + ICE_PCA9575_P1_OFFSET, &pin, NULL); if (status) break; *data |= (u8)(!pin) << i; } return status; } /** * ice_write_sma_ctrl_e810t * @hw: pointer to the hw struct * @data: data to be written to the GPIO controller * * Write the data to the SMA controller. It is connected to pins 3-7 of Port 1 * of the PCA9575 expander, so only bits 3-7 in data are valid. */ int ice_write_sma_ctrl_e810t(struct ice_hw *hw, u8 data) { int status; u16 handle; u8 i; status = ice_get_pca9575_handle(hw, &handle); if (status) return status; for (i = ICE_SMA_MIN_BIT_E810T; i <= ICE_SMA_MAX_BIT_E810T; i++) { bool pin; pin = !(data & (1 << i)); status = ice_aq_set_gpio(hw, handle, i + ICE_PCA9575_P1_OFFSET, pin, NULL); if (status) break; } return status; } /** * ice_read_pca9575_reg_e810t * @hw: pointer to the hw struct * @offset: GPIO controller register offset * @data: pointer to data to be read from the GPIO controller * * Read the register from the GPIO controller */ int ice_read_pca9575_reg_e810t(struct ice_hw *hw, u8 offset, u8 *data) { struct ice_aqc_link_topo_addr link_topo; __le16 addr; u16 handle; int err; memset(&link_topo, 0, sizeof(link_topo)); err = ice_get_pca9575_handle(hw, &handle); if (err) return err; link_topo.handle = cpu_to_le16(handle); link_topo.topo_params.node_type_ctx = FIELD_PREP(ICE_AQC_LINK_TOPO_NODE_CTX_M, ICE_AQC_LINK_TOPO_NODE_CTX_PROVIDED); addr = cpu_to_le16((u16)offset); return ice_aq_read_i2c(hw, link_topo, 0, addr, 1, data, NULL); } /* Device agnostic functions * * The following functions implement shared behavior common to both E822 and * E810 devices, possibly calling a device specific implementation where * necessary. */ /** * ice_ptp_lock - Acquire PTP global semaphore register lock * @hw: pointer to the HW struct * * Acquire the global PTP hardware semaphore lock. Returns true if the lock * was acquired, false otherwise. * * The PFTSYN_SEM register sets the busy bit on read, returning the previous * value. If software sees the busy bit cleared, this means that this function * acquired the lock (and the busy bit is now set). If software sees the busy * bit set, it means that another function acquired the lock. * * Software must clear the busy bit with a write to release the lock for other * functions when done. */ bool ice_ptp_lock(struct ice_hw *hw) { u32 hw_lock; int i; #define MAX_TRIES 15 for (i = 0; i < MAX_TRIES; i++) { hw_lock = rd32(hw, PFTSYN_SEM + (PFTSYN_SEM_BYTES * hw->pf_id)); hw_lock = hw_lock & PFTSYN_SEM_BUSY_M; if (hw_lock) { /* Somebody is holding the lock */ usleep_range(5000, 6000); continue; } break; } return !hw_lock; } /** * ice_ptp_unlock - Release PTP global semaphore register lock * @hw: pointer to the HW struct * * Release the global PTP hardware semaphore lock. This is done by writing to * the PFTSYN_SEM register. */ void ice_ptp_unlock(struct ice_hw *hw) { wr32(hw, PFTSYN_SEM + (PFTSYN_SEM_BYTES * hw->pf_id), 0); } /** * ice_ptp_tmr_cmd - Prepare and trigger a timer sync command * @hw: pointer to HW struct * @cmd: the command to issue * * Prepare the source timer and PHY timers and then trigger the requested * command. This causes the shadow registers previously written in preparation * for the command to be synchronously applied to both the source and PHY * timers. */ static int ice_ptp_tmr_cmd(struct ice_hw *hw, enum ice_ptp_tmr_cmd cmd) { int err; /* First, prepare the source timer */ ice_ptp_src_cmd(hw, cmd); /* Next, prepare the ports */ if (ice_is_e810(hw)) err = ice_ptp_port_cmd_e810(hw, cmd); else err = ice_ptp_port_cmd_e822(hw, cmd); if (err) { ice_debug(hw, ICE_DBG_PTP, "Failed to prepare PHY ports for timer command %u, err %d\n", cmd, err); return err; } /* Write the sync command register to drive both source and PHY timer * commands synchronously */ ice_ptp_exec_tmr_cmd(hw); return 0; } /** * ice_ptp_init_time - Initialize device time to provided value * @hw: pointer to HW struct * @time: 64bits of time (GLTSYN_TIME_L and GLTSYN_TIME_H) * * Initialize the device to the specified time provided. This requires a three * step process: * * 1) write the new init time to the source timer shadow registers * 2) write the new init time to the PHY timer shadow registers * 3) issue an init_time timer command to synchronously switch both the source * and port timers to the new init time value at the next clock cycle. */ int ice_ptp_init_time(struct ice_hw *hw, u64 time) { u8 tmr_idx; int err; tmr_idx = hw->func_caps.ts_func_info.tmr_index_owned; /* Source timers */ wr32(hw, GLTSYN_SHTIME_L(tmr_idx), lower_32_bits(time)); wr32(hw, GLTSYN_SHTIME_H(tmr_idx), upper_32_bits(time)); wr32(hw, GLTSYN_SHTIME_0(tmr_idx), 0); /* PHY timers */ /* Fill Rx and Tx ports and send msg to PHY */ if (ice_is_e810(hw)) err = ice_ptp_prep_phy_time_e810(hw, time & 0xFFFFFFFF); else err = ice_ptp_prep_phy_time_e822(hw, time & 0xFFFFFFFF); if (err) return err; return ice_ptp_tmr_cmd(hw, INIT_TIME); } /** * ice_ptp_write_incval - Program PHC with new increment value * @hw: pointer to HW struct * @incval: Source timer increment value per clock cycle * * Program the PHC with a new increment value. This requires a three-step * process: * * 1) Write the increment value to the source timer shadow registers * 2) Write the increment value to the PHY timer shadow registers * 3) Issue an INIT_INCVAL timer command to synchronously switch both the * source and port timers to the new increment value at the next clock * cycle. */ int ice_ptp_write_incval(struct ice_hw *hw, u64 incval) { u8 tmr_idx; int err; tmr_idx = hw->func_caps.ts_func_info.tmr_index_owned; /* Shadow Adjust */ wr32(hw, GLTSYN_SHADJ_L(tmr_idx), lower_32_bits(incval)); wr32(hw, GLTSYN_SHADJ_H(tmr_idx), upper_32_bits(incval)); if (ice_is_e810(hw)) err = ice_ptp_prep_phy_incval_e810(hw, incval); else err = ice_ptp_prep_phy_incval_e822(hw, incval); if (err) return err; return ice_ptp_tmr_cmd(hw, INIT_INCVAL); } /** * ice_ptp_write_incval_locked - Program new incval while holding semaphore * @hw: pointer to HW struct * @incval: Source timer increment value per clock cycle * * Program a new PHC incval while holding the PTP semaphore. */ int ice_ptp_write_incval_locked(struct ice_hw *hw, u64 incval) { int err; if (!ice_ptp_lock(hw)) return -EBUSY; err = ice_ptp_write_incval(hw, incval); ice_ptp_unlock(hw); return err; } /** * ice_ptp_adj_clock - Adjust PHC clock time atomically * @hw: pointer to HW struct * @adj: Adjustment in nanoseconds * * Perform an atomic adjustment of the PHC time by the specified number of * nanoseconds. This requires a three-step process: * * 1) Write the adjustment to the source timer shadow registers * 2) Write the adjustment to the PHY timer shadow registers * 3) Issue an ADJ_TIME timer command to synchronously apply the adjustment to * both the source and port timers at the next clock cycle. */ int ice_ptp_adj_clock(struct ice_hw *hw, s32 adj) { u8 tmr_idx; int err; tmr_idx = hw->func_caps.ts_func_info.tmr_index_owned; /* Write the desired clock adjustment into the GLTSYN_SHADJ register. * For an ADJ_TIME command, this set of registers represents the value * to add to the clock time. It supports subtraction by interpreting * the value as a 2's complement integer. */ wr32(hw, GLTSYN_SHADJ_L(tmr_idx), 0); wr32(hw, GLTSYN_SHADJ_H(tmr_idx), adj); if (ice_is_e810(hw)) err = ice_ptp_prep_phy_adj_e810(hw, adj); else err = ice_ptp_prep_phy_adj_e822(hw, adj); if (err) return err; return ice_ptp_tmr_cmd(hw, ADJ_TIME); } /** * ice_read_phy_tstamp - Read a PHY timestamp from the timestamo block * @hw: pointer to the HW struct * @block: the block to read from * @idx: the timestamp index to read * @tstamp: on return, the 40bit timestamp value * * Read a 40bit timestamp value out of the timestamp block. For E822 devices, * the block is the quad to read from. For E810 devices, the block is the * logical port to read from. */ int ice_read_phy_tstamp(struct ice_hw *hw, u8 block, u8 idx, u64 *tstamp) { if (ice_is_e810(hw)) return ice_read_phy_tstamp_e810(hw, block, idx, tstamp); else return ice_read_phy_tstamp_e822(hw, block, idx, tstamp); } /** * ice_clear_phy_tstamp - Clear a timestamp from the timestamp block * @hw: pointer to the HW struct * @block: the block to read from * @idx: the timestamp index to reset * * Clear a timestamp, resetting its valid bit, from the timestamp block. For * E822 devices, the block is the quad to clear from. For E810 devices, the * block is the logical port to clear from. */ int ice_clear_phy_tstamp(struct ice_hw *hw, u8 block, u8 idx) { if (ice_is_e810(hw)) return ice_clear_phy_tstamp_e810(hw, block, idx); else return ice_clear_phy_tstamp_e822(hw, block, idx); } /** * ice_ptp_reset_ts_memory - Reset timestamp memory for all blocks * @hw: pointer to the HW struct */ void ice_ptp_reset_ts_memory(struct ice_hw *hw) { if (ice_is_e810(hw)) return; ice_ptp_reset_ts_memory_e822(hw); } /** * ice_ptp_init_phc - Initialize PTP hardware clock * @hw: pointer to the HW struct * * Perform the steps required to initialize the PTP hardware clock. */ int ice_ptp_init_phc(struct ice_hw *hw) { u8 src_idx = hw->func_caps.ts_func_info.tmr_index_owned; /* Enable source clocks */ wr32(hw, GLTSYN_ENA(src_idx), GLTSYN_ENA_TSYN_ENA_M); /* Clear event err indications for auxiliary pins */ (void)rd32(hw, GLTSYN_STAT(src_idx)); if (ice_is_e810(hw)) return ice_ptp_init_phc_e810(hw); else return ice_ptp_init_phc_e822(hw); } /** * ice_get_phy_tx_tstamp_ready - Read PHY Tx memory status indication * @hw: pointer to the HW struct * @block: the timestamp block to check * @tstamp_ready: storage for the PHY Tx memory status information * * Check the PHY for Tx timestamp memory status. This reports a 64 bit value * which indicates which timestamps in the block may be captured. A set bit * means the timestamp can be read. An unset bit means the timestamp is not * ready and software should avoid reading the register. */ int ice_get_phy_tx_tstamp_ready(struct ice_hw *hw, u8 block, u64 *tstamp_ready) { if (ice_is_e810(hw)) return ice_get_phy_tx_tstamp_ready_e810(hw, block, tstamp_ready); else return ice_get_phy_tx_tstamp_ready_e822(hw, block, tstamp_ready); }
linux-master
drivers/net/ethernet/intel/ice/ice_ptp_hw.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2019, Intel Corporation. */ #include <linux/bpf_trace.h> #include <net/xdp_sock_drv.h> #include <net/xdp.h> #include "ice.h" #include "ice_base.h" #include "ice_type.h" #include "ice_xsk.h" #include "ice_txrx.h" #include "ice_txrx_lib.h" #include "ice_lib.h" static struct xdp_buff **ice_xdp_buf(struct ice_rx_ring *rx_ring, u32 idx) { return &rx_ring->xdp_buf[idx]; } /** * ice_qp_reset_stats - Resets all stats for rings of given index * @vsi: VSI that contains rings of interest * @q_idx: ring index in array */ static void ice_qp_reset_stats(struct ice_vsi *vsi, u16 q_idx) { struct ice_vsi_stats *vsi_stat; struct ice_pf *pf; pf = vsi->back; if (!pf->vsi_stats) return; vsi_stat = pf->vsi_stats[vsi->idx]; if (!vsi_stat) return; memset(&vsi_stat->rx_ring_stats[q_idx]->rx_stats, 0, sizeof(vsi_stat->rx_ring_stats[q_idx]->rx_stats)); memset(&vsi_stat->tx_ring_stats[q_idx]->stats, 0, sizeof(vsi_stat->tx_ring_stats[q_idx]->stats)); if (ice_is_xdp_ena_vsi(vsi)) memset(&vsi->xdp_rings[q_idx]->ring_stats->stats, 0, sizeof(vsi->xdp_rings[q_idx]->ring_stats->stats)); } /** * ice_qp_clean_rings - Cleans all the rings of a given index * @vsi: VSI that contains rings of interest * @q_idx: ring index in array */ static void ice_qp_clean_rings(struct ice_vsi *vsi, u16 q_idx) { ice_clean_tx_ring(vsi->tx_rings[q_idx]); if (ice_is_xdp_ena_vsi(vsi)) { synchronize_rcu(); ice_clean_tx_ring(vsi->xdp_rings[q_idx]); } ice_clean_rx_ring(vsi->rx_rings[q_idx]); } /** * ice_qvec_toggle_napi - Enables/disables NAPI for a given q_vector * @vsi: VSI that has netdev * @q_vector: q_vector that has NAPI context * @enable: true for enable, false for disable */ static void ice_qvec_toggle_napi(struct ice_vsi *vsi, struct ice_q_vector *q_vector, bool enable) { if (!vsi->netdev || !q_vector) return; if (enable) napi_enable(&q_vector->napi); else napi_disable(&q_vector->napi); } /** * ice_qvec_dis_irq - Mask off queue interrupt generation on given ring * @vsi: the VSI that contains queue vector being un-configured * @rx_ring: Rx ring that will have its IRQ disabled * @q_vector: queue vector */ static void ice_qvec_dis_irq(struct ice_vsi *vsi, struct ice_rx_ring *rx_ring, struct ice_q_vector *q_vector) { struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; u16 reg; u32 val; /* QINT_TQCTL is being cleared in ice_vsi_stop_tx_ring, so handle * here only QINT_RQCTL */ reg = rx_ring->reg_idx; val = rd32(hw, QINT_RQCTL(reg)); val &= ~QINT_RQCTL_CAUSE_ENA_M; wr32(hw, QINT_RQCTL(reg), val); if (q_vector) { wr32(hw, GLINT_DYN_CTL(q_vector->reg_idx), 0); ice_flush(hw); synchronize_irq(q_vector->irq.virq); } } /** * ice_qvec_cfg_msix - Enable IRQ for given queue vector * @vsi: the VSI that contains queue vector * @q_vector: queue vector */ static void ice_qvec_cfg_msix(struct ice_vsi *vsi, struct ice_q_vector *q_vector) { u16 reg_idx = q_vector->reg_idx; struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; struct ice_tx_ring *tx_ring; struct ice_rx_ring *rx_ring; ice_cfg_itr(hw, q_vector); ice_for_each_tx_ring(tx_ring, q_vector->tx) ice_cfg_txq_interrupt(vsi, tx_ring->reg_idx, reg_idx, q_vector->tx.itr_idx); ice_for_each_rx_ring(rx_ring, q_vector->rx) ice_cfg_rxq_interrupt(vsi, rx_ring->reg_idx, reg_idx, q_vector->rx.itr_idx); ice_flush(hw); } /** * ice_qvec_ena_irq - Enable IRQ for given queue vector * @vsi: the VSI that contains queue vector * @q_vector: queue vector */ static void ice_qvec_ena_irq(struct ice_vsi *vsi, struct ice_q_vector *q_vector) { struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; ice_irq_dynamic_ena(hw, vsi, q_vector); ice_flush(hw); } /** * ice_qp_dis - Disables a queue pair * @vsi: VSI of interest * @q_idx: ring index in array * * Returns 0 on success, negative on failure. */ static int ice_qp_dis(struct ice_vsi *vsi, u16 q_idx) { struct ice_txq_meta txq_meta = { }; struct ice_q_vector *q_vector; struct ice_tx_ring *tx_ring; struct ice_rx_ring *rx_ring; int timeout = 50; int err; if (q_idx >= vsi->num_rxq || q_idx >= vsi->num_txq) return -EINVAL; tx_ring = vsi->tx_rings[q_idx]; rx_ring = vsi->rx_rings[q_idx]; q_vector = rx_ring->q_vector; while (test_and_set_bit(ICE_CFG_BUSY, vsi->state)) { timeout--; if (!timeout) return -EBUSY; usleep_range(1000, 2000); } netif_tx_stop_queue(netdev_get_tx_queue(vsi->netdev, q_idx)); ice_fill_txq_meta(vsi, tx_ring, &txq_meta); err = ice_vsi_stop_tx_ring(vsi, ICE_NO_RESET, 0, tx_ring, &txq_meta); if (err) return err; if (ice_is_xdp_ena_vsi(vsi)) { struct ice_tx_ring *xdp_ring = vsi->xdp_rings[q_idx]; memset(&txq_meta, 0, sizeof(txq_meta)); ice_fill_txq_meta(vsi, xdp_ring, &txq_meta); err = ice_vsi_stop_tx_ring(vsi, ICE_NO_RESET, 0, xdp_ring, &txq_meta); if (err) return err; } ice_qvec_dis_irq(vsi, rx_ring, q_vector); err = ice_vsi_ctrl_one_rx_ring(vsi, false, q_idx, true); if (err) return err; ice_qvec_toggle_napi(vsi, q_vector, false); ice_qp_clean_rings(vsi, q_idx); ice_qp_reset_stats(vsi, q_idx); return 0; } /** * ice_qp_ena - Enables a queue pair * @vsi: VSI of interest * @q_idx: ring index in array * * Returns 0 on success, negative on failure. */ static int ice_qp_ena(struct ice_vsi *vsi, u16 q_idx) { struct ice_aqc_add_tx_qgrp *qg_buf; struct ice_q_vector *q_vector; struct ice_tx_ring *tx_ring; struct ice_rx_ring *rx_ring; u16 size; int err; if (q_idx >= vsi->num_rxq || q_idx >= vsi->num_txq) return -EINVAL; size = struct_size(qg_buf, txqs, 1); qg_buf = kzalloc(size, GFP_KERNEL); if (!qg_buf) return -ENOMEM; qg_buf->num_txqs = 1; tx_ring = vsi->tx_rings[q_idx]; rx_ring = vsi->rx_rings[q_idx]; q_vector = rx_ring->q_vector; err = ice_vsi_cfg_txq(vsi, tx_ring, qg_buf); if (err) goto free_buf; if (ice_is_xdp_ena_vsi(vsi)) { struct ice_tx_ring *xdp_ring = vsi->xdp_rings[q_idx]; memset(qg_buf, 0, size); qg_buf->num_txqs = 1; err = ice_vsi_cfg_txq(vsi, xdp_ring, qg_buf); if (err) goto free_buf; ice_set_ring_xdp(xdp_ring); ice_tx_xsk_pool(vsi, q_idx); } err = ice_vsi_cfg_rxq(rx_ring); if (err) goto free_buf; ice_qvec_cfg_msix(vsi, q_vector); err = ice_vsi_ctrl_one_rx_ring(vsi, true, q_idx, true); if (err) goto free_buf; clear_bit(ICE_CFG_BUSY, vsi->state); ice_qvec_toggle_napi(vsi, q_vector, true); ice_qvec_ena_irq(vsi, q_vector); netif_tx_start_queue(netdev_get_tx_queue(vsi->netdev, q_idx)); free_buf: kfree(qg_buf); return err; } /** * ice_xsk_pool_disable - disable a buffer pool region * @vsi: Current VSI * @qid: queue ID * * Returns 0 on success, negative on failure */ static int ice_xsk_pool_disable(struct ice_vsi *vsi, u16 qid) { struct xsk_buff_pool *pool = xsk_get_pool_from_qid(vsi->netdev, qid); if (!pool) return -EINVAL; clear_bit(qid, vsi->af_xdp_zc_qps); xsk_pool_dma_unmap(pool, ICE_RX_DMA_ATTR); return 0; } /** * ice_xsk_pool_enable - enable a buffer pool region * @vsi: Current VSI * @pool: pointer to a requested buffer pool region * @qid: queue ID * * Returns 0 on success, negative on failure */ static int ice_xsk_pool_enable(struct ice_vsi *vsi, struct xsk_buff_pool *pool, u16 qid) { int err; if (vsi->type != ICE_VSI_PF) return -EINVAL; if (qid >= vsi->netdev->real_num_rx_queues || qid >= vsi->netdev->real_num_tx_queues) return -EINVAL; err = xsk_pool_dma_map(pool, ice_pf_to_dev(vsi->back), ICE_RX_DMA_ATTR); if (err) return err; set_bit(qid, vsi->af_xdp_zc_qps); return 0; } /** * ice_realloc_rx_xdp_bufs - reallocate for either XSK or normal buffer * @rx_ring: Rx ring * @pool_present: is pool for XSK present * * Try allocating memory and return ENOMEM, if failed to allocate. * If allocation was successful, substitute buffer with allocated one. * Returns 0 on success, negative on failure */ static int ice_realloc_rx_xdp_bufs(struct ice_rx_ring *rx_ring, bool pool_present) { size_t elem_size = pool_present ? sizeof(*rx_ring->xdp_buf) : sizeof(*rx_ring->rx_buf); void *sw_ring = kcalloc(rx_ring->count, elem_size, GFP_KERNEL); if (!sw_ring) return -ENOMEM; if (pool_present) { kfree(rx_ring->rx_buf); rx_ring->rx_buf = NULL; rx_ring->xdp_buf = sw_ring; } else { kfree(rx_ring->xdp_buf); rx_ring->xdp_buf = NULL; rx_ring->rx_buf = sw_ring; } return 0; } /** * ice_realloc_zc_buf - reallocate XDP ZC queue pairs * @vsi: Current VSI * @zc: is zero copy set * * Reallocate buffer for rx_rings that might be used by XSK. * XDP requires more memory, than rx_buf provides. * Returns 0 on success, negative on failure */ int ice_realloc_zc_buf(struct ice_vsi *vsi, bool zc) { struct ice_rx_ring *rx_ring; unsigned long q; for_each_set_bit(q, vsi->af_xdp_zc_qps, max_t(int, vsi->alloc_txq, vsi->alloc_rxq)) { rx_ring = vsi->rx_rings[q]; if (ice_realloc_rx_xdp_bufs(rx_ring, zc)) return -ENOMEM; } return 0; } /** * ice_xsk_pool_setup - enable/disable a buffer pool region depending on its state * @vsi: Current VSI * @pool: buffer pool to enable/associate to a ring, NULL to disable * @qid: queue ID * * Returns 0 on success, negative on failure */ int ice_xsk_pool_setup(struct ice_vsi *vsi, struct xsk_buff_pool *pool, u16 qid) { bool if_running, pool_present = !!pool; int ret = 0, pool_failure = 0; if (qid >= vsi->num_rxq || qid >= vsi->num_txq) { netdev_err(vsi->netdev, "Please use queue id in scope of combined queues count\n"); pool_failure = -EINVAL; goto failure; } if_running = netif_running(vsi->netdev) && ice_is_xdp_ena_vsi(vsi); if (if_running) { struct ice_rx_ring *rx_ring = vsi->rx_rings[qid]; ret = ice_qp_dis(vsi, qid); if (ret) { netdev_err(vsi->netdev, "ice_qp_dis error = %d\n", ret); goto xsk_pool_if_up; } ret = ice_realloc_rx_xdp_bufs(rx_ring, pool_present); if (ret) goto xsk_pool_if_up; } pool_failure = pool_present ? ice_xsk_pool_enable(vsi, pool, qid) : ice_xsk_pool_disable(vsi, qid); xsk_pool_if_up: if (if_running) { ret = ice_qp_ena(vsi, qid); if (!ret && pool_present) napi_schedule(&vsi->rx_rings[qid]->xdp_ring->q_vector->napi); else if (ret) netdev_err(vsi->netdev, "ice_qp_ena error = %d\n", ret); } failure: if (pool_failure) { netdev_err(vsi->netdev, "Could not %sable buffer pool, error = %d\n", pool_present ? "en" : "dis", pool_failure); return pool_failure; } return ret; } /** * ice_fill_rx_descs - pick buffers from XSK buffer pool and use it * @pool: XSK Buffer pool to pull the buffers from * @xdp: SW ring of xdp_buff that will hold the buffers * @rx_desc: Pointer to Rx descriptors that will be filled * @count: The number of buffers to allocate * * This function allocates a number of Rx buffers from the fill ring * or the internal recycle mechanism and places them on the Rx ring. * * Note that ring wrap should be handled by caller of this function. * * Returns the amount of allocated Rx descriptors */ static u16 ice_fill_rx_descs(struct xsk_buff_pool *pool, struct xdp_buff **xdp, union ice_32b_rx_flex_desc *rx_desc, u16 count) { dma_addr_t dma; u16 buffs; int i; buffs = xsk_buff_alloc_batch(pool, xdp, count); for (i = 0; i < buffs; i++) { dma = xsk_buff_xdp_get_dma(*xdp); rx_desc->read.pkt_addr = cpu_to_le64(dma); rx_desc->wb.status_error0 = 0; rx_desc++; xdp++; } return buffs; } /** * __ice_alloc_rx_bufs_zc - allocate a number of Rx buffers * @rx_ring: Rx ring * @count: The number of buffers to allocate * * Place the @count of descriptors onto Rx ring. Handle the ring wrap * for case where space from next_to_use up to the end of ring is less * than @count. Finally do a tail bump. * * Returns true if all allocations were successful, false if any fail. */ static bool __ice_alloc_rx_bufs_zc(struct ice_rx_ring *rx_ring, u16 count) { u32 nb_buffs_extra = 0, nb_buffs = 0; union ice_32b_rx_flex_desc *rx_desc; u16 ntu = rx_ring->next_to_use; u16 total_count = count; struct xdp_buff **xdp; rx_desc = ICE_RX_DESC(rx_ring, ntu); xdp = ice_xdp_buf(rx_ring, ntu); if (ntu + count >= rx_ring->count) { nb_buffs_extra = ice_fill_rx_descs(rx_ring->xsk_pool, xdp, rx_desc, rx_ring->count - ntu); if (nb_buffs_extra != rx_ring->count - ntu) { ntu += nb_buffs_extra; goto exit; } rx_desc = ICE_RX_DESC(rx_ring, 0); xdp = ice_xdp_buf(rx_ring, 0); ntu = 0; count -= nb_buffs_extra; ice_release_rx_desc(rx_ring, 0); } nb_buffs = ice_fill_rx_descs(rx_ring->xsk_pool, xdp, rx_desc, count); ntu += nb_buffs; if (ntu == rx_ring->count) ntu = 0; exit: if (rx_ring->next_to_use != ntu) ice_release_rx_desc(rx_ring, ntu); return total_count == (nb_buffs_extra + nb_buffs); } /** * ice_alloc_rx_bufs_zc - allocate a number of Rx buffers * @rx_ring: Rx ring * @count: The number of buffers to allocate * * Wrapper for internal allocation routine; figure out how many tail * bumps should take place based on the given threshold * * Returns true if all calls to internal alloc routine succeeded */ bool ice_alloc_rx_bufs_zc(struct ice_rx_ring *rx_ring, u16 count) { u16 rx_thresh = ICE_RING_QUARTER(rx_ring); u16 leftover, i, tail_bumps; tail_bumps = count / rx_thresh; leftover = count - (tail_bumps * rx_thresh); for (i = 0; i < tail_bumps; i++) if (!__ice_alloc_rx_bufs_zc(rx_ring, rx_thresh)) return false; return __ice_alloc_rx_bufs_zc(rx_ring, leftover); } /** * ice_construct_skb_zc - Create an sk_buff from zero-copy buffer * @rx_ring: Rx ring * @xdp: Pointer to XDP buffer * * This function allocates a new skb from a zero-copy Rx buffer. * * Returns the skb on success, NULL on failure. */ static struct sk_buff * ice_construct_skb_zc(struct ice_rx_ring *rx_ring, struct xdp_buff *xdp) { unsigned int totalsize = xdp->data_end - xdp->data_meta; unsigned int metasize = xdp->data - xdp->data_meta; struct skb_shared_info *sinfo = NULL; struct sk_buff *skb; u32 nr_frags = 0; if (unlikely(xdp_buff_has_frags(xdp))) { sinfo = xdp_get_shared_info_from_buff(xdp); nr_frags = sinfo->nr_frags; } net_prefetch(xdp->data_meta); skb = __napi_alloc_skb(&rx_ring->q_vector->napi, totalsize, GFP_ATOMIC | __GFP_NOWARN); if (unlikely(!skb)) return NULL; memcpy(__skb_put(skb, totalsize), xdp->data_meta, ALIGN(totalsize, sizeof(long))); if (metasize) { skb_metadata_set(skb, metasize); __skb_pull(skb, metasize); } if (likely(!xdp_buff_has_frags(xdp))) goto out; for (int i = 0; i < nr_frags; i++) { struct skb_shared_info *skinfo = skb_shinfo(skb); skb_frag_t *frag = &sinfo->frags[i]; struct page *page; void *addr; page = dev_alloc_page(); if (!page) { dev_kfree_skb(skb); return NULL; } addr = page_to_virt(page); memcpy(addr, skb_frag_page(frag), skb_frag_size(frag)); __skb_fill_page_desc_noacc(skinfo, skinfo->nr_frags++, addr, 0, skb_frag_size(frag)); } out: xsk_buff_free(xdp); return skb; } /** * ice_clean_xdp_irq_zc - produce AF_XDP descriptors to CQ * @xdp_ring: XDP Tx ring */ static u32 ice_clean_xdp_irq_zc(struct ice_tx_ring *xdp_ring) { u16 ntc = xdp_ring->next_to_clean; struct ice_tx_desc *tx_desc; u16 cnt = xdp_ring->count; struct ice_tx_buf *tx_buf; u16 completed_frames = 0; u16 xsk_frames = 0; u16 last_rs; int i; last_rs = xdp_ring->next_to_use ? xdp_ring->next_to_use - 1 : cnt - 1; tx_desc = ICE_TX_DESC(xdp_ring, last_rs); if (tx_desc->cmd_type_offset_bsz & cpu_to_le64(ICE_TX_DESC_DTYPE_DESC_DONE)) { if (last_rs >= ntc) completed_frames = last_rs - ntc + 1; else completed_frames = last_rs + cnt - ntc + 1; } if (!completed_frames) return 0; if (likely(!xdp_ring->xdp_tx_active)) { xsk_frames = completed_frames; goto skip; } ntc = xdp_ring->next_to_clean; for (i = 0; i < completed_frames; i++) { tx_buf = &xdp_ring->tx_buf[ntc]; if (tx_buf->type == ICE_TX_BUF_XSK_TX) { tx_buf->type = ICE_TX_BUF_EMPTY; xsk_buff_free(tx_buf->xdp); xdp_ring->xdp_tx_active--; } else { xsk_frames++; } ntc++; if (ntc >= xdp_ring->count) ntc = 0; } skip: tx_desc->cmd_type_offset_bsz = 0; xdp_ring->next_to_clean += completed_frames; if (xdp_ring->next_to_clean >= cnt) xdp_ring->next_to_clean -= cnt; if (xsk_frames) xsk_tx_completed(xdp_ring->xsk_pool, xsk_frames); return completed_frames; } /** * ice_xmit_xdp_tx_zc - AF_XDP ZC handler for XDP_TX * @xdp: XDP buffer to xmit * @xdp_ring: XDP ring to produce descriptor onto * * note that this function works directly on xdp_buff, no need to convert * it to xdp_frame. xdp_buff pointer is stored to ice_tx_buf so that cleaning * side will be able to xsk_buff_free() it. * * Returns ICE_XDP_TX for successfully produced desc, ICE_XDP_CONSUMED if there * was not enough space on XDP ring */ static int ice_xmit_xdp_tx_zc(struct xdp_buff *xdp, struct ice_tx_ring *xdp_ring) { struct skb_shared_info *sinfo = NULL; u32 size = xdp->data_end - xdp->data; u32 ntu = xdp_ring->next_to_use; struct ice_tx_desc *tx_desc; struct ice_tx_buf *tx_buf; struct xdp_buff *head; u32 nr_frags = 0; u32 free_space; u32 frag = 0; free_space = ICE_DESC_UNUSED(xdp_ring); if (free_space < ICE_RING_QUARTER(xdp_ring)) free_space += ice_clean_xdp_irq_zc(xdp_ring); if (unlikely(!free_space)) goto busy; if (unlikely(xdp_buff_has_frags(xdp))) { sinfo = xdp_get_shared_info_from_buff(xdp); nr_frags = sinfo->nr_frags; if (free_space < nr_frags + 1) goto busy; } tx_desc = ICE_TX_DESC(xdp_ring, ntu); tx_buf = &xdp_ring->tx_buf[ntu]; head = xdp; for (;;) { dma_addr_t dma; dma = xsk_buff_xdp_get_dma(xdp); xsk_buff_raw_dma_sync_for_device(xdp_ring->xsk_pool, dma, size); tx_buf->xdp = xdp; tx_buf->type = ICE_TX_BUF_XSK_TX; tx_desc->buf_addr = cpu_to_le64(dma); tx_desc->cmd_type_offset_bsz = ice_build_ctob(0, 0, size, 0); /* account for each xdp_buff from xsk_buff_pool */ xdp_ring->xdp_tx_active++; if (++ntu == xdp_ring->count) ntu = 0; if (frag == nr_frags) break; tx_desc = ICE_TX_DESC(xdp_ring, ntu); tx_buf = &xdp_ring->tx_buf[ntu]; xdp = xsk_buff_get_frag(head); size = skb_frag_size(&sinfo->frags[frag]); frag++; } xdp_ring->next_to_use = ntu; /* update last descriptor from a frame with EOP */ tx_desc->cmd_type_offset_bsz |= cpu_to_le64(ICE_TX_DESC_CMD_EOP << ICE_TXD_QW1_CMD_S); return ICE_XDP_TX; busy: xdp_ring->ring_stats->tx_stats.tx_busy++; return ICE_XDP_CONSUMED; } /** * ice_run_xdp_zc - Executes an XDP program in zero-copy path * @rx_ring: Rx ring * @xdp: xdp_buff used as input to the XDP program * @xdp_prog: XDP program to run * @xdp_ring: ring to be used for XDP_TX action * * Returns any of ICE_XDP_{PASS, CONSUMED, TX, REDIR} */ static int ice_run_xdp_zc(struct ice_rx_ring *rx_ring, struct xdp_buff *xdp, struct bpf_prog *xdp_prog, struct ice_tx_ring *xdp_ring) { int err, result = ICE_XDP_PASS; u32 act; act = bpf_prog_run_xdp(xdp_prog, xdp); if (likely(act == XDP_REDIRECT)) { err = xdp_do_redirect(rx_ring->netdev, xdp, xdp_prog); if (!err) return ICE_XDP_REDIR; if (xsk_uses_need_wakeup(rx_ring->xsk_pool) && err == -ENOBUFS) result = ICE_XDP_EXIT; else result = ICE_XDP_CONSUMED; goto out_failure; } switch (act) { case XDP_PASS: break; case XDP_TX: result = ice_xmit_xdp_tx_zc(xdp, xdp_ring); if (result == ICE_XDP_CONSUMED) goto out_failure; break; case XDP_DROP: result = ICE_XDP_CONSUMED; break; default: bpf_warn_invalid_xdp_action(rx_ring->netdev, xdp_prog, act); fallthrough; case XDP_ABORTED: result = ICE_XDP_CONSUMED; out_failure: trace_xdp_exception(rx_ring->netdev, xdp_prog, act); break; } return result; } static int ice_add_xsk_frag(struct ice_rx_ring *rx_ring, struct xdp_buff *first, struct xdp_buff *xdp, const unsigned int size) { struct skb_shared_info *sinfo = xdp_get_shared_info_from_buff(first); if (!size) return 0; if (!xdp_buff_has_frags(first)) { sinfo->nr_frags = 0; sinfo->xdp_frags_size = 0; xdp_buff_set_frags_flag(first); } if (unlikely(sinfo->nr_frags == MAX_SKB_FRAGS)) { xsk_buff_free(first); return -ENOMEM; } __skb_fill_page_desc_noacc(sinfo, sinfo->nr_frags++, virt_to_page(xdp->data_hard_start), 0, size); sinfo->xdp_frags_size += size; xsk_buff_add_frag(xdp); return 0; } /** * ice_clean_rx_irq_zc - consumes packets from the hardware ring * @rx_ring: AF_XDP Rx ring * @budget: NAPI budget * * Returns number of processed packets on success, remaining budget on failure. */ int ice_clean_rx_irq_zc(struct ice_rx_ring *rx_ring, int budget) { unsigned int total_rx_bytes = 0, total_rx_packets = 0; struct xsk_buff_pool *xsk_pool = rx_ring->xsk_pool; u32 ntc = rx_ring->next_to_clean; u32 ntu = rx_ring->next_to_use; struct xdp_buff *first = NULL; struct ice_tx_ring *xdp_ring; unsigned int xdp_xmit = 0; struct bpf_prog *xdp_prog; u32 cnt = rx_ring->count; bool failure = false; int entries_to_alloc; /* ZC patch is enabled only when XDP program is set, * so here it can not be NULL */ xdp_prog = READ_ONCE(rx_ring->xdp_prog); xdp_ring = rx_ring->xdp_ring; if (ntc != rx_ring->first_desc) first = *ice_xdp_buf(rx_ring, rx_ring->first_desc); while (likely(total_rx_packets < (unsigned int)budget)) { union ice_32b_rx_flex_desc *rx_desc; unsigned int size, xdp_res = 0; struct xdp_buff *xdp; struct sk_buff *skb; u16 stat_err_bits; u16 vlan_tag = 0; u16 rx_ptype; rx_desc = ICE_RX_DESC(rx_ring, ntc); stat_err_bits = BIT(ICE_RX_FLEX_DESC_STATUS0_DD_S); if (!ice_test_staterr(rx_desc->wb.status_error0, stat_err_bits)) break; /* This memory barrier is needed to keep us from reading * any other fields out of the rx_desc until we have * verified the descriptor has been written back. */ dma_rmb(); if (unlikely(ntc == ntu)) break; xdp = *ice_xdp_buf(rx_ring, ntc); size = le16_to_cpu(rx_desc->wb.pkt_len) & ICE_RX_FLX_DESC_PKT_LEN_M; xsk_buff_set_size(xdp, size); xsk_buff_dma_sync_for_cpu(xdp, xsk_pool); if (!first) { first = xdp; xdp_buff_clear_frags_flag(first); } else if (ice_add_xsk_frag(rx_ring, first, xdp, size)) { break; } if (++ntc == cnt) ntc = 0; if (ice_is_non_eop(rx_ring, rx_desc)) continue; xdp_res = ice_run_xdp_zc(rx_ring, first, xdp_prog, xdp_ring); if (likely(xdp_res & (ICE_XDP_TX | ICE_XDP_REDIR))) { xdp_xmit |= xdp_res; } else if (xdp_res == ICE_XDP_EXIT) { failure = true; first = NULL; rx_ring->first_desc = ntc; break; } else if (xdp_res == ICE_XDP_CONSUMED) { xsk_buff_free(first); } else if (xdp_res == ICE_XDP_PASS) { goto construct_skb; } total_rx_bytes += xdp_get_buff_len(first); total_rx_packets++; first = NULL; rx_ring->first_desc = ntc; continue; construct_skb: /* XDP_PASS path */ skb = ice_construct_skb_zc(rx_ring, first); if (!skb) { rx_ring->ring_stats->rx_stats.alloc_buf_failed++; break; } first = NULL; rx_ring->first_desc = ntc; if (eth_skb_pad(skb)) { skb = NULL; continue; } total_rx_bytes += skb->len; total_rx_packets++; vlan_tag = ice_get_vlan_tag_from_rx_desc(rx_desc); rx_ptype = le16_to_cpu(rx_desc->wb.ptype_flex_flags0) & ICE_RX_FLEX_DESC_PTYPE_M; ice_process_skb_fields(rx_ring, rx_desc, skb, rx_ptype); ice_receive_skb(rx_ring, skb, vlan_tag); } rx_ring->next_to_clean = ntc; entries_to_alloc = ICE_RX_DESC_UNUSED(rx_ring); if (entries_to_alloc > ICE_RING_QUARTER(rx_ring)) failure |= !ice_alloc_rx_bufs_zc(rx_ring, entries_to_alloc); ice_finalize_xdp_rx(xdp_ring, xdp_xmit, 0); ice_update_rx_ring_stats(rx_ring, total_rx_packets, total_rx_bytes); if (xsk_uses_need_wakeup(xsk_pool)) { /* ntu could have changed when allocating entries above, so * use rx_ring value instead of stack based one */ if (failure || ntc == rx_ring->next_to_use) xsk_set_rx_need_wakeup(xsk_pool); else xsk_clear_rx_need_wakeup(xsk_pool); return (int)total_rx_packets; } return failure ? budget : (int)total_rx_packets; } /** * ice_xmit_pkt - produce a single HW Tx descriptor out of AF_XDP descriptor * @xdp_ring: XDP ring to produce the HW Tx descriptor on * @desc: AF_XDP descriptor to pull the DMA address and length from * @total_bytes: bytes accumulator that will be used for stats update */ static void ice_xmit_pkt(struct ice_tx_ring *xdp_ring, struct xdp_desc *desc, unsigned int *total_bytes) { struct ice_tx_desc *tx_desc; dma_addr_t dma; dma = xsk_buff_raw_get_dma(xdp_ring->xsk_pool, desc->addr); xsk_buff_raw_dma_sync_for_device(xdp_ring->xsk_pool, dma, desc->len); tx_desc = ICE_TX_DESC(xdp_ring, xdp_ring->next_to_use++); tx_desc->buf_addr = cpu_to_le64(dma); tx_desc->cmd_type_offset_bsz = ice_build_ctob(xsk_is_eop_desc(desc), 0, desc->len, 0); *total_bytes += desc->len; } /** * ice_xmit_pkt_batch - produce a batch of HW Tx descriptors out of AF_XDP descriptors * @xdp_ring: XDP ring to produce the HW Tx descriptors on * @descs: AF_XDP descriptors to pull the DMA addresses and lengths from * @total_bytes: bytes accumulator that will be used for stats update */ static void ice_xmit_pkt_batch(struct ice_tx_ring *xdp_ring, struct xdp_desc *descs, unsigned int *total_bytes) { u16 ntu = xdp_ring->next_to_use; struct ice_tx_desc *tx_desc; u32 i; loop_unrolled_for(i = 0; i < PKTS_PER_BATCH; i++) { dma_addr_t dma; dma = xsk_buff_raw_get_dma(xdp_ring->xsk_pool, descs[i].addr); xsk_buff_raw_dma_sync_for_device(xdp_ring->xsk_pool, dma, descs[i].len); tx_desc = ICE_TX_DESC(xdp_ring, ntu++); tx_desc->buf_addr = cpu_to_le64(dma); tx_desc->cmd_type_offset_bsz = ice_build_ctob(xsk_is_eop_desc(&descs[i]), 0, descs[i].len, 0); *total_bytes += descs[i].len; } xdp_ring->next_to_use = ntu; } /** * ice_fill_tx_hw_ring - produce the number of Tx descriptors onto ring * @xdp_ring: XDP ring to produce the HW Tx descriptors on * @descs: AF_XDP descriptors to pull the DMA addresses and lengths from * @nb_pkts: count of packets to be send * @total_bytes: bytes accumulator that will be used for stats update */ static void ice_fill_tx_hw_ring(struct ice_tx_ring *xdp_ring, struct xdp_desc *descs, u32 nb_pkts, unsigned int *total_bytes) { u32 batched, leftover, i; batched = ALIGN_DOWN(nb_pkts, PKTS_PER_BATCH); leftover = nb_pkts & (PKTS_PER_BATCH - 1); for (i = 0; i < batched; i += PKTS_PER_BATCH) ice_xmit_pkt_batch(xdp_ring, &descs[i], total_bytes); for (; i < batched + leftover; i++) ice_xmit_pkt(xdp_ring, &descs[i], total_bytes); } /** * ice_xmit_zc - take entries from XSK Tx ring and place them onto HW Tx ring * @xdp_ring: XDP ring to produce the HW Tx descriptors on * * Returns true if there is no more work that needs to be done, false otherwise */ bool ice_xmit_zc(struct ice_tx_ring *xdp_ring) { struct xdp_desc *descs = xdp_ring->xsk_pool->tx_descs; u32 nb_pkts, nb_processed = 0; unsigned int total_bytes = 0; int budget; ice_clean_xdp_irq_zc(xdp_ring); budget = ICE_DESC_UNUSED(xdp_ring); budget = min_t(u16, budget, ICE_RING_QUARTER(xdp_ring)); nb_pkts = xsk_tx_peek_release_desc_batch(xdp_ring->xsk_pool, budget); if (!nb_pkts) return true; if (xdp_ring->next_to_use + nb_pkts >= xdp_ring->count) { nb_processed = xdp_ring->count - xdp_ring->next_to_use; ice_fill_tx_hw_ring(xdp_ring, descs, nb_processed, &total_bytes); xdp_ring->next_to_use = 0; } ice_fill_tx_hw_ring(xdp_ring, &descs[nb_processed], nb_pkts - nb_processed, &total_bytes); ice_set_rs_bit(xdp_ring); ice_xdp_ring_update_tail(xdp_ring); ice_update_tx_ring_stats(xdp_ring, nb_pkts, total_bytes); if (xsk_uses_need_wakeup(xdp_ring->xsk_pool)) xsk_set_tx_need_wakeup(xdp_ring->xsk_pool); return nb_pkts < budget; } /** * ice_xsk_wakeup - Implements ndo_xsk_wakeup * @netdev: net_device * @queue_id: queue to wake up * @flags: ignored in our case, since we have Rx and Tx in the same NAPI * * Returns negative on error, zero otherwise. */ int ice_xsk_wakeup(struct net_device *netdev, u32 queue_id, u32 __always_unused flags) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_q_vector *q_vector; struct ice_vsi *vsi = np->vsi; struct ice_tx_ring *ring; if (test_bit(ICE_VSI_DOWN, vsi->state)) return -ENETDOWN; if (!ice_is_xdp_ena_vsi(vsi)) return -EINVAL; if (queue_id >= vsi->num_txq || queue_id >= vsi->num_rxq) return -EINVAL; ring = vsi->rx_rings[queue_id]->xdp_ring; if (!ring->xsk_pool) return -EINVAL; /* The idea here is that if NAPI is running, mark a miss, so * it will run again. If not, trigger an interrupt and * schedule the NAPI from interrupt context. If NAPI would be * scheduled here, the interrupt affinity would not be * honored. */ q_vector = ring->q_vector; if (!napi_if_scheduled_mark_missed(&q_vector->napi)) ice_trigger_sw_intr(&vsi->back->hw, q_vector); return 0; } /** * ice_xsk_any_rx_ring_ena - Checks if Rx rings have AF_XDP buff pool attached * @vsi: VSI to be checked * * Returns true if any of the Rx rings has an AF_XDP buff pool attached */ bool ice_xsk_any_rx_ring_ena(struct ice_vsi *vsi) { int i; ice_for_each_rxq(vsi, i) { if (xsk_get_pool_from_qid(vsi->netdev, i)) return true; } return false; } /** * ice_xsk_clean_rx_ring - clean buffer pool queues connected to a given Rx ring * @rx_ring: ring to be cleaned */ void ice_xsk_clean_rx_ring(struct ice_rx_ring *rx_ring) { u16 ntc = rx_ring->next_to_clean; u16 ntu = rx_ring->next_to_use; while (ntc != ntu) { struct xdp_buff *xdp = *ice_xdp_buf(rx_ring, ntc); xsk_buff_free(xdp); ntc++; if (ntc >= rx_ring->count) ntc = 0; } } /** * ice_xsk_clean_xdp_ring - Clean the XDP Tx ring and its buffer pool queues * @xdp_ring: XDP_Tx ring */ void ice_xsk_clean_xdp_ring(struct ice_tx_ring *xdp_ring) { u16 ntc = xdp_ring->next_to_clean, ntu = xdp_ring->next_to_use; u32 xsk_frames = 0; while (ntc != ntu) { struct ice_tx_buf *tx_buf = &xdp_ring->tx_buf[ntc]; if (tx_buf->type == ICE_TX_BUF_XSK_TX) { tx_buf->type = ICE_TX_BUF_EMPTY; xsk_buff_free(tx_buf->xdp); } else { xsk_frames++; } ntc++; if (ntc >= xdp_ring->count) ntc = 0; } if (xsk_frames) xsk_tx_completed(xdp_ring->xsk_pool, xsk_frames); }
linux-master
drivers/net/ethernet/intel/ice/ice_xsk.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2018, Intel Corporation. */ #include "ice_lib.h" #include "ice_switch.h" #define ICE_ETH_DA_OFFSET 0 #define ICE_ETH_ETHTYPE_OFFSET 12 #define ICE_ETH_VLAN_TCI_OFFSET 14 #define ICE_MAX_VLAN_ID 0xFFF #define ICE_IPV6_ETHER_ID 0x86DD /* Dummy ethernet header needed in the ice_aqc_sw_rules_elem * struct to configure any switch filter rules. * {DA (6 bytes), SA(6 bytes), * Ether type (2 bytes for header without VLAN tag) OR * VLAN tag (4 bytes for header with VLAN tag) } * * Word on Hardcoded values * byte 0 = 0x2: to identify it as locally administered DA MAC * byte 6 = 0x2: to identify it as locally administered SA MAC * byte 12 = 0x81 & byte 13 = 0x00: * In case of VLAN filter first two bytes defines ether type (0x8100) * and remaining two bytes are placeholder for programming a given VLAN ID * In case of Ether type filter it is treated as header without VLAN tag * and byte 12 and 13 is used to program a given Ether type instead */ static const u8 dummy_eth_header[DUMMY_ETH_HDR_LEN] = { 0x2, 0, 0, 0, 0, 0, 0x2, 0, 0, 0, 0, 0, 0x81, 0, 0, 0}; enum { ICE_PKT_OUTER_IPV6 = BIT(0), ICE_PKT_TUN_GTPC = BIT(1), ICE_PKT_TUN_GTPU = BIT(2), ICE_PKT_TUN_NVGRE = BIT(3), ICE_PKT_TUN_UDP = BIT(4), ICE_PKT_INNER_IPV6 = BIT(5), ICE_PKT_INNER_TCP = BIT(6), ICE_PKT_INNER_UDP = BIT(7), ICE_PKT_GTP_NOPAY = BIT(8), ICE_PKT_KMALLOC = BIT(9), ICE_PKT_PPPOE = BIT(10), ICE_PKT_L2TPV3 = BIT(11), }; struct ice_dummy_pkt_offsets { enum ice_protocol_type type; u16 offset; /* ICE_PROTOCOL_LAST indicates end of list */ }; struct ice_dummy_pkt_profile { const struct ice_dummy_pkt_offsets *offsets; const u8 *pkt; u32 match; u16 pkt_len; u16 offsets_len; }; #define ICE_DECLARE_PKT_OFFSETS(type) \ static const struct ice_dummy_pkt_offsets \ ice_dummy_##type##_packet_offsets[] #define ICE_DECLARE_PKT_TEMPLATE(type) \ static const u8 ice_dummy_##type##_packet[] #define ICE_PKT_PROFILE(type, m) { \ .match = (m), \ .pkt = ice_dummy_##type##_packet, \ .pkt_len = sizeof(ice_dummy_##type##_packet), \ .offsets = ice_dummy_##type##_packet_offsets, \ .offsets_len = sizeof(ice_dummy_##type##_packet_offsets), \ } ICE_DECLARE_PKT_OFFSETS(vlan) = { { ICE_VLAN_OFOS, 12 }, }; ICE_DECLARE_PKT_TEMPLATE(vlan) = { 0x81, 0x00, 0x00, 0x00, /* ICE_VLAN_OFOS 12 */ }; ICE_DECLARE_PKT_OFFSETS(qinq) = { { ICE_VLAN_EX, 12 }, { ICE_VLAN_IN, 16 }, }; ICE_DECLARE_PKT_TEMPLATE(qinq) = { 0x91, 0x00, 0x00, 0x00, /* ICE_VLAN_EX 12 */ 0x81, 0x00, 0x00, 0x00, /* ICE_VLAN_IN 16 */ }; ICE_DECLARE_PKT_OFFSETS(gre_tcp) = { { ICE_MAC_OFOS, 0 }, { ICE_ETYPE_OL, 12 }, { ICE_IPV4_OFOS, 14 }, { ICE_NVGRE, 34 }, { ICE_MAC_IL, 42 }, { ICE_ETYPE_IL, 54 }, { ICE_IPV4_IL, 56 }, { ICE_TCP_IL, 76 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(gre_tcp) = { 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_OFOS 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, /* ICE_ETYPE_OL 12 */ 0x45, 0x00, 0x00, 0x3E, /* ICE_IPV4_OFOS 14 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x2F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x65, 0x58, /* ICE_NVGRE 34 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_IL 42 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, /* ICE_ETYPE_IL 54 */ 0x45, 0x00, 0x00, 0x14, /* ICE_IPV4_IL 56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_TCP_IL 76 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x02, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00 }; ICE_DECLARE_PKT_OFFSETS(gre_udp) = { { ICE_MAC_OFOS, 0 }, { ICE_ETYPE_OL, 12 }, { ICE_IPV4_OFOS, 14 }, { ICE_NVGRE, 34 }, { ICE_MAC_IL, 42 }, { ICE_ETYPE_IL, 54 }, { ICE_IPV4_IL, 56 }, { ICE_UDP_ILOS, 76 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(gre_udp) = { 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_OFOS 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, /* ICE_ETYPE_OL 12 */ 0x45, 0x00, 0x00, 0x3E, /* ICE_IPV4_OFOS 14 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x2F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x65, 0x58, /* ICE_NVGRE 34 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_IL 42 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, /* ICE_ETYPE_IL 54 */ 0x45, 0x00, 0x00, 0x14, /* ICE_IPV4_IL 56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_UDP_ILOS 76 */ 0x00, 0x08, 0x00, 0x00, }; ICE_DECLARE_PKT_OFFSETS(udp_tun_tcp) = { { ICE_MAC_OFOS, 0 }, { ICE_ETYPE_OL, 12 }, { ICE_IPV4_OFOS, 14 }, { ICE_UDP_OF, 34 }, { ICE_VXLAN, 42 }, { ICE_GENEVE, 42 }, { ICE_VXLAN_GPE, 42 }, { ICE_MAC_IL, 50 }, { ICE_ETYPE_IL, 62 }, { ICE_IPV4_IL, 64 }, { ICE_TCP_IL, 84 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(udp_tun_tcp) = { 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_OFOS 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, /* ICE_ETYPE_OL 12 */ 0x45, 0x00, 0x00, 0x5a, /* ICE_IPV4_OFOS 14 */ 0x00, 0x01, 0x00, 0x00, 0x40, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0xb5, /* ICE_UDP_OF 34 */ 0x00, 0x46, 0x00, 0x00, 0x00, 0x00, 0x65, 0x58, /* ICE_VXLAN 42 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_IL 50 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, /* ICE_ETYPE_IL 62 */ 0x45, 0x00, 0x00, 0x28, /* ICE_IPV4_IL 64 */ 0x00, 0x01, 0x00, 0x00, 0x40, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_TCP_IL 84 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x02, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00 }; ICE_DECLARE_PKT_OFFSETS(udp_tun_udp) = { { ICE_MAC_OFOS, 0 }, { ICE_ETYPE_OL, 12 }, { ICE_IPV4_OFOS, 14 }, { ICE_UDP_OF, 34 }, { ICE_VXLAN, 42 }, { ICE_GENEVE, 42 }, { ICE_VXLAN_GPE, 42 }, { ICE_MAC_IL, 50 }, { ICE_ETYPE_IL, 62 }, { ICE_IPV4_IL, 64 }, { ICE_UDP_ILOS, 84 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(udp_tun_udp) = { 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_OFOS 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, /* ICE_ETYPE_OL 12 */ 0x45, 0x00, 0x00, 0x4e, /* ICE_IPV4_OFOS 14 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0xb5, /* ICE_UDP_OF 34 */ 0x00, 0x3a, 0x00, 0x00, 0x00, 0x00, 0x65, 0x58, /* ICE_VXLAN 42 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_IL 50 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, /* ICE_ETYPE_IL 62 */ 0x45, 0x00, 0x00, 0x1c, /* ICE_IPV4_IL 64 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_UDP_ILOS 84 */ 0x00, 0x08, 0x00, 0x00, }; ICE_DECLARE_PKT_OFFSETS(gre_ipv6_tcp) = { { ICE_MAC_OFOS, 0 }, { ICE_ETYPE_OL, 12 }, { ICE_IPV4_OFOS, 14 }, { ICE_NVGRE, 34 }, { ICE_MAC_IL, 42 }, { ICE_ETYPE_IL, 54 }, { ICE_IPV6_IL, 56 }, { ICE_TCP_IL, 96 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(gre_ipv6_tcp) = { 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_OFOS 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, /* ICE_ETYPE_OL 12 */ 0x45, 0x00, 0x00, 0x66, /* ICE_IPV4_OFOS 14 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x2F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x65, 0x58, /* ICE_NVGRE 34 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_IL 42 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xdd, /* ICE_ETYPE_IL 54 */ 0x60, 0x00, 0x00, 0x00, /* ICE_IPV6_IL 56 */ 0x00, 0x08, 0x06, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_TCP_IL 96 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x02, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00 }; ICE_DECLARE_PKT_OFFSETS(gre_ipv6_udp) = { { ICE_MAC_OFOS, 0 }, { ICE_ETYPE_OL, 12 }, { ICE_IPV4_OFOS, 14 }, { ICE_NVGRE, 34 }, { ICE_MAC_IL, 42 }, { ICE_ETYPE_IL, 54 }, { ICE_IPV6_IL, 56 }, { ICE_UDP_ILOS, 96 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(gre_ipv6_udp) = { 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_OFOS 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, /* ICE_ETYPE_OL 12 */ 0x45, 0x00, 0x00, 0x5a, /* ICE_IPV4_OFOS 14 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x2F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x65, 0x58, /* ICE_NVGRE 34 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_IL 42 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xdd, /* ICE_ETYPE_IL 54 */ 0x60, 0x00, 0x00, 0x00, /* ICE_IPV6_IL 56 */ 0x00, 0x08, 0x11, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_UDP_ILOS 96 */ 0x00, 0x08, 0x00, 0x00, }; ICE_DECLARE_PKT_OFFSETS(udp_tun_ipv6_tcp) = { { ICE_MAC_OFOS, 0 }, { ICE_ETYPE_OL, 12 }, { ICE_IPV4_OFOS, 14 }, { ICE_UDP_OF, 34 }, { ICE_VXLAN, 42 }, { ICE_GENEVE, 42 }, { ICE_VXLAN_GPE, 42 }, { ICE_MAC_IL, 50 }, { ICE_ETYPE_IL, 62 }, { ICE_IPV6_IL, 64 }, { ICE_TCP_IL, 104 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(udp_tun_ipv6_tcp) = { 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_OFOS 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, /* ICE_ETYPE_OL 12 */ 0x45, 0x00, 0x00, 0x6e, /* ICE_IPV4_OFOS 14 */ 0x00, 0x01, 0x00, 0x00, 0x40, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0xb5, /* ICE_UDP_OF 34 */ 0x00, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x65, 0x58, /* ICE_VXLAN 42 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_IL 50 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xdd, /* ICE_ETYPE_IL 62 */ 0x60, 0x00, 0x00, 0x00, /* ICE_IPV6_IL 64 */ 0x00, 0x08, 0x06, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_TCP_IL 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x02, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00 }; ICE_DECLARE_PKT_OFFSETS(udp_tun_ipv6_udp) = { { ICE_MAC_OFOS, 0 }, { ICE_ETYPE_OL, 12 }, { ICE_IPV4_OFOS, 14 }, { ICE_UDP_OF, 34 }, { ICE_VXLAN, 42 }, { ICE_GENEVE, 42 }, { ICE_VXLAN_GPE, 42 }, { ICE_MAC_IL, 50 }, { ICE_ETYPE_IL, 62 }, { ICE_IPV6_IL, 64 }, { ICE_UDP_ILOS, 104 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(udp_tun_ipv6_udp) = { 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_OFOS 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, /* ICE_ETYPE_OL 12 */ 0x45, 0x00, 0x00, 0x62, /* ICE_IPV4_OFOS 14 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0xb5, /* ICE_UDP_OF 34 */ 0x00, 0x4e, 0x00, 0x00, 0x00, 0x00, 0x65, 0x58, /* ICE_VXLAN 42 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_IL 50 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xdd, /* ICE_ETYPE_IL 62 */ 0x60, 0x00, 0x00, 0x00, /* ICE_IPV6_IL 64 */ 0x00, 0x08, 0x11, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_UDP_ILOS 104 */ 0x00, 0x08, 0x00, 0x00, }; /* offset info for MAC + IPv4 + UDP dummy packet */ ICE_DECLARE_PKT_OFFSETS(udp) = { { ICE_MAC_OFOS, 0 }, { ICE_ETYPE_OL, 12 }, { ICE_IPV4_OFOS, 14 }, { ICE_UDP_ILOS, 34 }, { ICE_PROTOCOL_LAST, 0 }, }; /* Dummy packet for MAC + IPv4 + UDP */ ICE_DECLARE_PKT_TEMPLATE(udp) = { 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_OFOS 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, /* ICE_ETYPE_OL 12 */ 0x45, 0x00, 0x00, 0x1c, /* ICE_IPV4_OFOS 14 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_UDP_ILOS 34 */ 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, /* 2 bytes for 4 byte alignment */ }; /* offset info for MAC + IPv4 + TCP dummy packet */ ICE_DECLARE_PKT_OFFSETS(tcp) = { { ICE_MAC_OFOS, 0 }, { ICE_ETYPE_OL, 12 }, { ICE_IPV4_OFOS, 14 }, { ICE_TCP_IL, 34 }, { ICE_PROTOCOL_LAST, 0 }, }; /* Dummy packet for MAC + IPv4 + TCP */ ICE_DECLARE_PKT_TEMPLATE(tcp) = { 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_OFOS 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, /* ICE_ETYPE_OL 12 */ 0x45, 0x00, 0x00, 0x28, /* ICE_IPV4_OFOS 14 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_TCP_IL 34 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 2 bytes for 4 byte alignment */ }; ICE_DECLARE_PKT_OFFSETS(tcp_ipv6) = { { ICE_MAC_OFOS, 0 }, { ICE_ETYPE_OL, 12 }, { ICE_IPV6_OFOS, 14 }, { ICE_TCP_IL, 54 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(tcp_ipv6) = { 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_OFOS 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xDD, /* ICE_ETYPE_OL 12 */ 0x60, 0x00, 0x00, 0x00, /* ICE_IPV6_OFOS 40 */ 0x00, 0x14, 0x06, 0x00, /* Next header is TCP */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_TCP_IL 54 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 2 bytes for 4 byte alignment */ }; /* IPv6 + UDP */ ICE_DECLARE_PKT_OFFSETS(udp_ipv6) = { { ICE_MAC_OFOS, 0 }, { ICE_ETYPE_OL, 12 }, { ICE_IPV6_OFOS, 14 }, { ICE_UDP_ILOS, 54 }, { ICE_PROTOCOL_LAST, 0 }, }; /* IPv6 + UDP dummy packet */ ICE_DECLARE_PKT_TEMPLATE(udp_ipv6) = { 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_OFOS 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xDD, /* ICE_ETYPE_OL 12 */ 0x60, 0x00, 0x00, 0x00, /* ICE_IPV6_OFOS 40 */ 0x00, 0x10, 0x11, 0x00, /* Next header UDP */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_UDP_ILOS 54 */ 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* needed for ESP packets */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 2 bytes for 4 byte alignment */ }; /* Outer IPv4 + Outer UDP + GTP + Inner IPv4 + Inner TCP */ ICE_DECLARE_PKT_OFFSETS(ipv4_gtpu_ipv4_tcp) = { { ICE_MAC_OFOS, 0 }, { ICE_IPV4_OFOS, 14 }, { ICE_UDP_OF, 34 }, { ICE_GTP, 42 }, { ICE_IPV4_IL, 62 }, { ICE_TCP_IL, 82 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(ipv4_gtpu_ipv4_tcp) = { 0x00, 0x00, 0x00, 0x00, /* Ethernet 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x58, /* IP 14 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x68, /* UDP 34 */ 0x00, 0x44, 0x00, 0x00, 0x34, 0xff, 0x00, 0x34, /* ICE_GTP Header 42 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85, 0x02, 0x00, 0x00, 0x00, /* GTP_PDUSession_ExtensionHeader 54 */ 0x00, 0x00, 0x00, 0x00, 0x45, 0x00, 0x00, 0x28, /* IP 62 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* TCP 82 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 2 bytes for 4 byte alignment */ }; /* Outer IPv4 + Outer UDP + GTP + Inner IPv4 + Inner UDP */ ICE_DECLARE_PKT_OFFSETS(ipv4_gtpu_ipv4_udp) = { { ICE_MAC_OFOS, 0 }, { ICE_IPV4_OFOS, 14 }, { ICE_UDP_OF, 34 }, { ICE_GTP, 42 }, { ICE_IPV4_IL, 62 }, { ICE_UDP_ILOS, 82 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(ipv4_gtpu_ipv4_udp) = { 0x00, 0x00, 0x00, 0x00, /* Ethernet 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x4c, /* IP 14 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x68, /* UDP 34 */ 0x00, 0x38, 0x00, 0x00, 0x34, 0xff, 0x00, 0x28, /* ICE_GTP Header 42 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85, 0x02, 0x00, 0x00, 0x00, /* GTP_PDUSession_ExtensionHeader 54 */ 0x00, 0x00, 0x00, 0x00, 0x45, 0x00, 0x00, 0x1c, /* IP 62 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* UDP 82 */ 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, /* 2 bytes for 4 byte alignment */ }; /* Outer IPv6 + Outer UDP + GTP + Inner IPv4 + Inner TCP */ ICE_DECLARE_PKT_OFFSETS(ipv4_gtpu_ipv6_tcp) = { { ICE_MAC_OFOS, 0 }, { ICE_IPV4_OFOS, 14 }, { ICE_UDP_OF, 34 }, { ICE_GTP, 42 }, { ICE_IPV6_IL, 62 }, { ICE_TCP_IL, 102 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(ipv4_gtpu_ipv6_tcp) = { 0x00, 0x00, 0x00, 0x00, /* Ethernet 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x6c, /* IP 14 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x68, /* UDP 34 */ 0x00, 0x58, 0x00, 0x00, 0x34, 0xff, 0x00, 0x48, /* ICE_GTP Header 42 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85, 0x02, 0x00, 0x00, 0x00, /* GTP_PDUSession_ExtensionHeader 54 */ 0x00, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, /* IPv6 62 */ 0x00, 0x14, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* TCP 102 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 2 bytes for 4 byte alignment */ }; ICE_DECLARE_PKT_OFFSETS(ipv4_gtpu_ipv6_udp) = { { ICE_MAC_OFOS, 0 }, { ICE_IPV4_OFOS, 14 }, { ICE_UDP_OF, 34 }, { ICE_GTP, 42 }, { ICE_IPV6_IL, 62 }, { ICE_UDP_ILOS, 102 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(ipv4_gtpu_ipv6_udp) = { 0x00, 0x00, 0x00, 0x00, /* Ethernet 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x60, /* IP 14 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x68, /* UDP 34 */ 0x00, 0x4c, 0x00, 0x00, 0x34, 0xff, 0x00, 0x3c, /* ICE_GTP Header 42 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85, 0x02, 0x00, 0x00, 0x00, /* GTP_PDUSession_ExtensionHeader 54 */ 0x00, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, /* IPv6 62 */ 0x00, 0x08, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* UDP 102 */ 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, /* 2 bytes for 4 byte alignment */ }; ICE_DECLARE_PKT_OFFSETS(ipv6_gtpu_ipv4_tcp) = { { ICE_MAC_OFOS, 0 }, { ICE_IPV6_OFOS, 14 }, { ICE_UDP_OF, 54 }, { ICE_GTP, 62 }, { ICE_IPV4_IL, 82 }, { ICE_TCP_IL, 102 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(ipv6_gtpu_ipv4_tcp) = { 0x00, 0x00, 0x00, 0x00, /* Ethernet 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xdd, 0x60, 0x00, 0x00, 0x00, /* IPv6 14 */ 0x00, 0x44, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x68, /* UDP 54 */ 0x00, 0x44, 0x00, 0x00, 0x34, 0xff, 0x00, 0x34, /* ICE_GTP Header 62 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85, 0x02, 0x00, 0x00, 0x00, /* GTP_PDUSession_ExtensionHeader 74 */ 0x00, 0x00, 0x00, 0x00, 0x45, 0x00, 0x00, 0x28, /* IP 82 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* TCP 102 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 2 bytes for 4 byte alignment */ }; ICE_DECLARE_PKT_OFFSETS(ipv6_gtpu_ipv4_udp) = { { ICE_MAC_OFOS, 0 }, { ICE_IPV6_OFOS, 14 }, { ICE_UDP_OF, 54 }, { ICE_GTP, 62 }, { ICE_IPV4_IL, 82 }, { ICE_UDP_ILOS, 102 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(ipv6_gtpu_ipv4_udp) = { 0x00, 0x00, 0x00, 0x00, /* Ethernet 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xdd, 0x60, 0x00, 0x00, 0x00, /* IPv6 14 */ 0x00, 0x38, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x68, /* UDP 54 */ 0x00, 0x38, 0x00, 0x00, 0x34, 0xff, 0x00, 0x28, /* ICE_GTP Header 62 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85, 0x02, 0x00, 0x00, 0x00, /* GTP_PDUSession_ExtensionHeader 74 */ 0x00, 0x00, 0x00, 0x00, 0x45, 0x00, 0x00, 0x1c, /* IP 82 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* UDP 102 */ 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, /* 2 bytes for 4 byte alignment */ }; ICE_DECLARE_PKT_OFFSETS(ipv6_gtpu_ipv6_tcp) = { { ICE_MAC_OFOS, 0 }, { ICE_IPV6_OFOS, 14 }, { ICE_UDP_OF, 54 }, { ICE_GTP, 62 }, { ICE_IPV6_IL, 82 }, { ICE_TCP_IL, 122 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(ipv6_gtpu_ipv6_tcp) = { 0x00, 0x00, 0x00, 0x00, /* Ethernet 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xdd, 0x60, 0x00, 0x00, 0x00, /* IPv6 14 */ 0x00, 0x58, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x68, /* UDP 54 */ 0x00, 0x58, 0x00, 0x00, 0x34, 0xff, 0x00, 0x48, /* ICE_GTP Header 62 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85, 0x02, 0x00, 0x00, 0x00, /* GTP_PDUSession_ExtensionHeader 74 */ 0x00, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, /* IPv6 82 */ 0x00, 0x14, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* TCP 122 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 2 bytes for 4 byte alignment */ }; ICE_DECLARE_PKT_OFFSETS(ipv6_gtpu_ipv6_udp) = { { ICE_MAC_OFOS, 0 }, { ICE_IPV6_OFOS, 14 }, { ICE_UDP_OF, 54 }, { ICE_GTP, 62 }, { ICE_IPV6_IL, 82 }, { ICE_UDP_ILOS, 122 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(ipv6_gtpu_ipv6_udp) = { 0x00, 0x00, 0x00, 0x00, /* Ethernet 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xdd, 0x60, 0x00, 0x00, 0x00, /* IPv6 14 */ 0x00, 0x4c, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x68, /* UDP 54 */ 0x00, 0x4c, 0x00, 0x00, 0x34, 0xff, 0x00, 0x3c, /* ICE_GTP Header 62 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85, 0x02, 0x00, 0x00, 0x00, /* GTP_PDUSession_ExtensionHeader 74 */ 0x00, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, /* IPv6 82 */ 0x00, 0x08, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* UDP 122 */ 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, /* 2 bytes for 4 byte alignment */ }; ICE_DECLARE_PKT_OFFSETS(ipv4_gtpu_ipv4) = { { ICE_MAC_OFOS, 0 }, { ICE_IPV4_OFOS, 14 }, { ICE_UDP_OF, 34 }, { ICE_GTP_NO_PAY, 42 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(ipv4_gtpu_ipv4) = { 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_OFOS 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, 0x00, 0x44, /* ICE_IPV4_OFOS 14 */ 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x68, 0x08, 0x68, /* ICE_UDP_OF 34 */ 0x00, 0x00, 0x00, 0x00, 0x34, 0xff, 0x00, 0x28, /* ICE_GTP 42 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85, 0x02, 0x00, 0x00, 0x00, /* PDU Session extension header */ 0x00, 0x00, 0x00, 0x00, 0x45, 0x00, 0x00, 0x14, /* ICE_IPV4_IL 62 */ 0x00, 0x00, 0x40, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; ICE_DECLARE_PKT_OFFSETS(ipv6_gtp) = { { ICE_MAC_OFOS, 0 }, { ICE_IPV6_OFOS, 14 }, { ICE_UDP_OF, 54 }, { ICE_GTP_NO_PAY, 62 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(ipv6_gtp) = { 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_OFOS 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xdd, 0x60, 0x00, 0x00, 0x00, /* ICE_IPV6_OFOS 14 */ 0x00, 0x6c, 0x11, 0x00, /* Next header UDP*/ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x68, 0x08, 0x68, /* ICE_UDP_OF 54 */ 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x28, /* ICE_GTP 62 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; ICE_DECLARE_PKT_OFFSETS(pppoe_ipv4_tcp) = { { ICE_MAC_OFOS, 0 }, { ICE_ETYPE_OL, 12 }, { ICE_PPPOE, 14 }, { ICE_IPV4_OFOS, 22 }, { ICE_TCP_IL, 42 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(pppoe_ipv4_tcp) = { 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_OFOS 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x64, /* ICE_ETYPE_OL 12 */ 0x11, 0x00, 0x00, 0x00, /* ICE_PPPOE 14 */ 0x00, 0x16, 0x00, 0x21, /* PPP Link Layer 20 */ 0x45, 0x00, 0x00, 0x28, /* ICE_IPV4_OFOS 22 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_TCP_IL 42 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 2 bytes for 4 bytes alignment */ }; ICE_DECLARE_PKT_OFFSETS(pppoe_ipv4_udp) = { { ICE_MAC_OFOS, 0 }, { ICE_ETYPE_OL, 12 }, { ICE_PPPOE, 14 }, { ICE_IPV4_OFOS, 22 }, { ICE_UDP_ILOS, 42 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(pppoe_ipv4_udp) = { 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_OFOS 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x64, /* ICE_ETYPE_OL 12 */ 0x11, 0x00, 0x00, 0x00, /* ICE_PPPOE 14 */ 0x00, 0x16, 0x00, 0x21, /* PPP Link Layer 20 */ 0x45, 0x00, 0x00, 0x1c, /* ICE_IPV4_OFOS 22 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_UDP_ILOS 42 */ 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, /* 2 bytes for 4 bytes alignment */ }; ICE_DECLARE_PKT_OFFSETS(pppoe_ipv6_tcp) = { { ICE_MAC_OFOS, 0 }, { ICE_ETYPE_OL, 12 }, { ICE_PPPOE, 14 }, { ICE_IPV6_OFOS, 22 }, { ICE_TCP_IL, 62 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(pppoe_ipv6_tcp) = { 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_OFOS 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x64, /* ICE_ETYPE_OL 12 */ 0x11, 0x00, 0x00, 0x00, /* ICE_PPPOE 14 */ 0x00, 0x2a, 0x00, 0x57, /* PPP Link Layer 20 */ 0x60, 0x00, 0x00, 0x00, /* ICE_IPV6_OFOS 22 */ 0x00, 0x14, 0x06, 0x00, /* Next header is TCP */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_TCP_IL 62 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 2 bytes for 4 bytes alignment */ }; ICE_DECLARE_PKT_OFFSETS(pppoe_ipv6_udp) = { { ICE_MAC_OFOS, 0 }, { ICE_ETYPE_OL, 12 }, { ICE_PPPOE, 14 }, { ICE_IPV6_OFOS, 22 }, { ICE_UDP_ILOS, 62 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(pppoe_ipv6_udp) = { 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_OFOS 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x64, /* ICE_ETYPE_OL 12 */ 0x11, 0x00, 0x00, 0x00, /* ICE_PPPOE 14 */ 0x00, 0x2a, 0x00, 0x57, /* PPP Link Layer 20 */ 0x60, 0x00, 0x00, 0x00, /* ICE_IPV6_OFOS 22 */ 0x00, 0x08, 0x11, 0x00, /* Next header UDP*/ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_UDP_ILOS 62 */ 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, /* 2 bytes for 4 bytes alignment */ }; ICE_DECLARE_PKT_OFFSETS(ipv4_l2tpv3) = { { ICE_MAC_OFOS, 0 }, { ICE_ETYPE_OL, 12 }, { ICE_IPV4_OFOS, 14 }, { ICE_L2TPV3, 34 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(ipv4_l2tpv3) = { 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_OFOS 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, /* ICE_ETYPE_OL 12 */ 0x45, 0x00, 0x00, 0x20, /* ICE_IPV4_IL 14 */ 0x00, 0x00, 0x40, 0x00, 0x40, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_L2TPV3 34 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 2 bytes for 4 bytes alignment */ }; ICE_DECLARE_PKT_OFFSETS(ipv6_l2tpv3) = { { ICE_MAC_OFOS, 0 }, { ICE_ETYPE_OL, 12 }, { ICE_IPV6_OFOS, 14 }, { ICE_L2TPV3, 54 }, { ICE_PROTOCOL_LAST, 0 }, }; ICE_DECLARE_PKT_TEMPLATE(ipv6_l2tpv3) = { 0x00, 0x00, 0x00, 0x00, /* ICE_MAC_OFOS 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0xDD, /* ICE_ETYPE_OL 12 */ 0x60, 0x00, 0x00, 0x00, /* ICE_IPV6_IL 14 */ 0x00, 0x0c, 0x73, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* ICE_L2TPV3 54 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 2 bytes for 4 bytes alignment */ }; static const struct ice_dummy_pkt_profile ice_dummy_pkt_profiles[] = { ICE_PKT_PROFILE(ipv6_gtp, ICE_PKT_TUN_GTPU | ICE_PKT_OUTER_IPV6 | ICE_PKT_GTP_NOPAY), ICE_PKT_PROFILE(ipv6_gtpu_ipv6_udp, ICE_PKT_TUN_GTPU | ICE_PKT_OUTER_IPV6 | ICE_PKT_INNER_IPV6 | ICE_PKT_INNER_UDP), ICE_PKT_PROFILE(ipv6_gtpu_ipv6_tcp, ICE_PKT_TUN_GTPU | ICE_PKT_OUTER_IPV6 | ICE_PKT_INNER_IPV6), ICE_PKT_PROFILE(ipv6_gtpu_ipv4_udp, ICE_PKT_TUN_GTPU | ICE_PKT_OUTER_IPV6 | ICE_PKT_INNER_UDP), ICE_PKT_PROFILE(ipv6_gtpu_ipv4_tcp, ICE_PKT_TUN_GTPU | ICE_PKT_OUTER_IPV6), ICE_PKT_PROFILE(ipv4_gtpu_ipv4, ICE_PKT_TUN_GTPU | ICE_PKT_GTP_NOPAY), ICE_PKT_PROFILE(ipv4_gtpu_ipv6_udp, ICE_PKT_TUN_GTPU | ICE_PKT_INNER_IPV6 | ICE_PKT_INNER_UDP), ICE_PKT_PROFILE(ipv4_gtpu_ipv6_tcp, ICE_PKT_TUN_GTPU | ICE_PKT_INNER_IPV6), ICE_PKT_PROFILE(ipv4_gtpu_ipv4_udp, ICE_PKT_TUN_GTPU | ICE_PKT_INNER_UDP), ICE_PKT_PROFILE(ipv4_gtpu_ipv4_tcp, ICE_PKT_TUN_GTPU), ICE_PKT_PROFILE(ipv6_gtp, ICE_PKT_TUN_GTPC | ICE_PKT_OUTER_IPV6), ICE_PKT_PROFILE(ipv4_gtpu_ipv4, ICE_PKT_TUN_GTPC), ICE_PKT_PROFILE(pppoe_ipv6_udp, ICE_PKT_PPPOE | ICE_PKT_OUTER_IPV6 | ICE_PKT_INNER_UDP), ICE_PKT_PROFILE(pppoe_ipv6_tcp, ICE_PKT_PPPOE | ICE_PKT_OUTER_IPV6), ICE_PKT_PROFILE(pppoe_ipv4_udp, ICE_PKT_PPPOE | ICE_PKT_INNER_UDP), ICE_PKT_PROFILE(pppoe_ipv4_tcp, ICE_PKT_PPPOE), ICE_PKT_PROFILE(gre_ipv6_tcp, ICE_PKT_TUN_NVGRE | ICE_PKT_INNER_IPV6 | ICE_PKT_INNER_TCP), ICE_PKT_PROFILE(gre_tcp, ICE_PKT_TUN_NVGRE | ICE_PKT_INNER_TCP), ICE_PKT_PROFILE(gre_ipv6_udp, ICE_PKT_TUN_NVGRE | ICE_PKT_INNER_IPV6), ICE_PKT_PROFILE(gre_udp, ICE_PKT_TUN_NVGRE), ICE_PKT_PROFILE(udp_tun_ipv6_tcp, ICE_PKT_TUN_UDP | ICE_PKT_INNER_IPV6 | ICE_PKT_INNER_TCP), ICE_PKT_PROFILE(ipv6_l2tpv3, ICE_PKT_L2TPV3 | ICE_PKT_OUTER_IPV6), ICE_PKT_PROFILE(ipv4_l2tpv3, ICE_PKT_L2TPV3), ICE_PKT_PROFILE(udp_tun_tcp, ICE_PKT_TUN_UDP | ICE_PKT_INNER_TCP), ICE_PKT_PROFILE(udp_tun_ipv6_udp, ICE_PKT_TUN_UDP | ICE_PKT_INNER_IPV6), ICE_PKT_PROFILE(udp_tun_udp, ICE_PKT_TUN_UDP), ICE_PKT_PROFILE(udp_ipv6, ICE_PKT_OUTER_IPV6 | ICE_PKT_INNER_UDP), ICE_PKT_PROFILE(udp, ICE_PKT_INNER_UDP), ICE_PKT_PROFILE(tcp_ipv6, ICE_PKT_OUTER_IPV6), ICE_PKT_PROFILE(tcp, 0), }; /* this is a recipe to profile association bitmap */ static DECLARE_BITMAP(recipe_to_profile[ICE_MAX_NUM_RECIPES], ICE_MAX_NUM_PROFILES); /* this is a profile to recipe association bitmap */ static DECLARE_BITMAP(profile_to_recipe[ICE_MAX_NUM_PROFILES], ICE_MAX_NUM_RECIPES); /** * ice_init_def_sw_recp - initialize the recipe book keeping tables * @hw: pointer to the HW struct * * Allocate memory for the entire recipe table and initialize the structures/ * entries corresponding to basic recipes. */ int ice_init_def_sw_recp(struct ice_hw *hw) { struct ice_sw_recipe *recps; u8 i; recps = devm_kcalloc(ice_hw_to_dev(hw), ICE_MAX_NUM_RECIPES, sizeof(*recps), GFP_KERNEL); if (!recps) return -ENOMEM; for (i = 0; i < ICE_MAX_NUM_RECIPES; i++) { recps[i].root_rid = i; INIT_LIST_HEAD(&recps[i].filt_rules); INIT_LIST_HEAD(&recps[i].filt_replay_rules); INIT_LIST_HEAD(&recps[i].rg_list); mutex_init(&recps[i].filt_rule_lock); } hw->switch_info->recp_list = recps; return 0; } /** * ice_aq_get_sw_cfg - get switch configuration * @hw: pointer to the hardware structure * @buf: pointer to the result buffer * @buf_size: length of the buffer available for response * @req_desc: pointer to requested descriptor * @num_elems: pointer to number of elements * @cd: pointer to command details structure or NULL * * Get switch configuration (0x0200) to be placed in buf. * This admin command returns information such as initial VSI/port number * and switch ID it belongs to. * * NOTE: *req_desc is both an input/output parameter. * The caller of this function first calls this function with *request_desc set * to 0. If the response from f/w has *req_desc set to 0, all the switch * configuration information has been returned; if non-zero (meaning not all * the information was returned), the caller should call this function again * with *req_desc set to the previous value returned by f/w to get the * next block of switch configuration information. * * *num_elems is output only parameter. This reflects the number of elements * in response buffer. The caller of this function to use *num_elems while * parsing the response buffer. */ static int ice_aq_get_sw_cfg(struct ice_hw *hw, struct ice_aqc_get_sw_cfg_resp_elem *buf, u16 buf_size, u16 *req_desc, u16 *num_elems, struct ice_sq_cd *cd) { struct ice_aqc_get_sw_cfg *cmd; struct ice_aq_desc desc; int status; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_get_sw_cfg); cmd = &desc.params.get_sw_conf; cmd->element = cpu_to_le16(*req_desc); status = ice_aq_send_cmd(hw, &desc, buf, buf_size, cd); if (!status) { *req_desc = le16_to_cpu(cmd->element); *num_elems = le16_to_cpu(cmd->num_elems); } return status; } /** * ice_aq_add_vsi * @hw: pointer to the HW struct * @vsi_ctx: pointer to a VSI context struct * @cd: pointer to command details structure or NULL * * Add a VSI context to the hardware (0x0210) */ static int ice_aq_add_vsi(struct ice_hw *hw, struct ice_vsi_ctx *vsi_ctx, struct ice_sq_cd *cd) { struct ice_aqc_add_update_free_vsi_resp *res; struct ice_aqc_add_get_update_free_vsi *cmd; struct ice_aq_desc desc; int status; cmd = &desc.params.vsi_cmd; res = &desc.params.add_update_free_vsi_res; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_add_vsi); if (!vsi_ctx->alloc_from_pool) cmd->vsi_num = cpu_to_le16(vsi_ctx->vsi_num | ICE_AQ_VSI_IS_VALID); cmd->vf_id = vsi_ctx->vf_num; cmd->vsi_flags = cpu_to_le16(vsi_ctx->flags); desc.flags |= cpu_to_le16(ICE_AQ_FLAG_RD); status = ice_aq_send_cmd(hw, &desc, &vsi_ctx->info, sizeof(vsi_ctx->info), cd); if (!status) { vsi_ctx->vsi_num = le16_to_cpu(res->vsi_num) & ICE_AQ_VSI_NUM_M; vsi_ctx->vsis_allocd = le16_to_cpu(res->vsi_used); vsi_ctx->vsis_unallocated = le16_to_cpu(res->vsi_free); } return status; } /** * ice_aq_free_vsi * @hw: pointer to the HW struct * @vsi_ctx: pointer to a VSI context struct * @keep_vsi_alloc: keep VSI allocation as part of this PF's resources * @cd: pointer to command details structure or NULL * * Free VSI context info from hardware (0x0213) */ static int ice_aq_free_vsi(struct ice_hw *hw, struct ice_vsi_ctx *vsi_ctx, bool keep_vsi_alloc, struct ice_sq_cd *cd) { struct ice_aqc_add_update_free_vsi_resp *resp; struct ice_aqc_add_get_update_free_vsi *cmd; struct ice_aq_desc desc; int status; cmd = &desc.params.vsi_cmd; resp = &desc.params.add_update_free_vsi_res; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_free_vsi); cmd->vsi_num = cpu_to_le16(vsi_ctx->vsi_num | ICE_AQ_VSI_IS_VALID); if (keep_vsi_alloc) cmd->cmd_flags = cpu_to_le16(ICE_AQ_VSI_KEEP_ALLOC); status = ice_aq_send_cmd(hw, &desc, NULL, 0, cd); if (!status) { vsi_ctx->vsis_allocd = le16_to_cpu(resp->vsi_used); vsi_ctx->vsis_unallocated = le16_to_cpu(resp->vsi_free); } return status; } /** * ice_aq_update_vsi * @hw: pointer to the HW struct * @vsi_ctx: pointer to a VSI context struct * @cd: pointer to command details structure or NULL * * Update VSI context in the hardware (0x0211) */ static int ice_aq_update_vsi(struct ice_hw *hw, struct ice_vsi_ctx *vsi_ctx, struct ice_sq_cd *cd) { struct ice_aqc_add_update_free_vsi_resp *resp; struct ice_aqc_add_get_update_free_vsi *cmd; struct ice_aq_desc desc; int status; cmd = &desc.params.vsi_cmd; resp = &desc.params.add_update_free_vsi_res; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_update_vsi); cmd->vsi_num = cpu_to_le16(vsi_ctx->vsi_num | ICE_AQ_VSI_IS_VALID); desc.flags |= cpu_to_le16(ICE_AQ_FLAG_RD); status = ice_aq_send_cmd(hw, &desc, &vsi_ctx->info, sizeof(vsi_ctx->info), cd); if (!status) { vsi_ctx->vsis_allocd = le16_to_cpu(resp->vsi_used); vsi_ctx->vsis_unallocated = le16_to_cpu(resp->vsi_free); } return status; } /** * ice_is_vsi_valid - check whether the VSI is valid or not * @hw: pointer to the HW struct * @vsi_handle: VSI handle * * check whether the VSI is valid or not */ bool ice_is_vsi_valid(struct ice_hw *hw, u16 vsi_handle) { return vsi_handle < ICE_MAX_VSI && hw->vsi_ctx[vsi_handle]; } /** * ice_get_hw_vsi_num - return the HW VSI number * @hw: pointer to the HW struct * @vsi_handle: VSI handle * * return the HW VSI number * Caution: call this function only if VSI is valid (ice_is_vsi_valid) */ u16 ice_get_hw_vsi_num(struct ice_hw *hw, u16 vsi_handle) { return hw->vsi_ctx[vsi_handle]->vsi_num; } /** * ice_get_vsi_ctx - return the VSI context entry for a given VSI handle * @hw: pointer to the HW struct * @vsi_handle: VSI handle * * return the VSI context entry for a given VSI handle */ struct ice_vsi_ctx *ice_get_vsi_ctx(struct ice_hw *hw, u16 vsi_handle) { return (vsi_handle >= ICE_MAX_VSI) ? NULL : hw->vsi_ctx[vsi_handle]; } /** * ice_save_vsi_ctx - save the VSI context for a given VSI handle * @hw: pointer to the HW struct * @vsi_handle: VSI handle * @vsi: VSI context pointer * * save the VSI context entry for a given VSI handle */ static void ice_save_vsi_ctx(struct ice_hw *hw, u16 vsi_handle, struct ice_vsi_ctx *vsi) { hw->vsi_ctx[vsi_handle] = vsi; } /** * ice_clear_vsi_q_ctx - clear VSI queue contexts for all TCs * @hw: pointer to the HW struct * @vsi_handle: VSI handle */ static void ice_clear_vsi_q_ctx(struct ice_hw *hw, u16 vsi_handle) { struct ice_vsi_ctx *vsi = ice_get_vsi_ctx(hw, vsi_handle); u8 i; if (!vsi) return; ice_for_each_traffic_class(i) { devm_kfree(ice_hw_to_dev(hw), vsi->lan_q_ctx[i]); vsi->lan_q_ctx[i] = NULL; devm_kfree(ice_hw_to_dev(hw), vsi->rdma_q_ctx[i]); vsi->rdma_q_ctx[i] = NULL; } } /** * ice_clear_vsi_ctx - clear the VSI context entry * @hw: pointer to the HW struct * @vsi_handle: VSI handle * * clear the VSI context entry */ static void ice_clear_vsi_ctx(struct ice_hw *hw, u16 vsi_handle) { struct ice_vsi_ctx *vsi; vsi = ice_get_vsi_ctx(hw, vsi_handle); if (vsi) { ice_clear_vsi_q_ctx(hw, vsi_handle); devm_kfree(ice_hw_to_dev(hw), vsi); hw->vsi_ctx[vsi_handle] = NULL; } } /** * ice_clear_all_vsi_ctx - clear all the VSI context entries * @hw: pointer to the HW struct */ void ice_clear_all_vsi_ctx(struct ice_hw *hw) { u16 i; for (i = 0; i < ICE_MAX_VSI; i++) ice_clear_vsi_ctx(hw, i); } /** * ice_add_vsi - add VSI context to the hardware and VSI handle list * @hw: pointer to the HW struct * @vsi_handle: unique VSI handle provided by drivers * @vsi_ctx: pointer to a VSI context struct * @cd: pointer to command details structure or NULL * * Add a VSI context to the hardware also add it into the VSI handle list. * If this function gets called after reset for existing VSIs then update * with the new HW VSI number in the corresponding VSI handle list entry. */ int ice_add_vsi(struct ice_hw *hw, u16 vsi_handle, struct ice_vsi_ctx *vsi_ctx, struct ice_sq_cd *cd) { struct ice_vsi_ctx *tmp_vsi_ctx; int status; if (vsi_handle >= ICE_MAX_VSI) return -EINVAL; status = ice_aq_add_vsi(hw, vsi_ctx, cd); if (status) return status; tmp_vsi_ctx = ice_get_vsi_ctx(hw, vsi_handle); if (!tmp_vsi_ctx) { /* Create a new VSI context */ tmp_vsi_ctx = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*tmp_vsi_ctx), GFP_KERNEL); if (!tmp_vsi_ctx) { ice_aq_free_vsi(hw, vsi_ctx, false, cd); return -ENOMEM; } *tmp_vsi_ctx = *vsi_ctx; ice_save_vsi_ctx(hw, vsi_handle, tmp_vsi_ctx); } else { /* update with new HW VSI num */ tmp_vsi_ctx->vsi_num = vsi_ctx->vsi_num; } return 0; } /** * ice_free_vsi- free VSI context from hardware and VSI handle list * @hw: pointer to the HW struct * @vsi_handle: unique VSI handle * @vsi_ctx: pointer to a VSI context struct * @keep_vsi_alloc: keep VSI allocation as part of this PF's resources * @cd: pointer to command details structure or NULL * * Free VSI context info from hardware as well as from VSI handle list */ int ice_free_vsi(struct ice_hw *hw, u16 vsi_handle, struct ice_vsi_ctx *vsi_ctx, bool keep_vsi_alloc, struct ice_sq_cd *cd) { int status; if (!ice_is_vsi_valid(hw, vsi_handle)) return -EINVAL; vsi_ctx->vsi_num = ice_get_hw_vsi_num(hw, vsi_handle); status = ice_aq_free_vsi(hw, vsi_ctx, keep_vsi_alloc, cd); if (!status) ice_clear_vsi_ctx(hw, vsi_handle); return status; } /** * ice_update_vsi * @hw: pointer to the HW struct * @vsi_handle: unique VSI handle * @vsi_ctx: pointer to a VSI context struct * @cd: pointer to command details structure or NULL * * Update VSI context in the hardware */ int ice_update_vsi(struct ice_hw *hw, u16 vsi_handle, struct ice_vsi_ctx *vsi_ctx, struct ice_sq_cd *cd) { if (!ice_is_vsi_valid(hw, vsi_handle)) return -EINVAL; vsi_ctx->vsi_num = ice_get_hw_vsi_num(hw, vsi_handle); return ice_aq_update_vsi(hw, vsi_ctx, cd); } /** * ice_cfg_rdma_fltr - enable/disable RDMA filtering on VSI * @hw: pointer to HW struct * @vsi_handle: VSI SW index * @enable: boolean for enable/disable */ int ice_cfg_rdma_fltr(struct ice_hw *hw, u16 vsi_handle, bool enable) { struct ice_vsi_ctx *ctx, *cached_ctx; int status; cached_ctx = ice_get_vsi_ctx(hw, vsi_handle); if (!cached_ctx) return -ENOENT; ctx = kzalloc(sizeof(*ctx), GFP_KERNEL); if (!ctx) return -ENOMEM; ctx->info.q_opt_rss = cached_ctx->info.q_opt_rss; ctx->info.q_opt_tc = cached_ctx->info.q_opt_tc; ctx->info.q_opt_flags = cached_ctx->info.q_opt_flags; ctx->info.valid_sections = cpu_to_le16(ICE_AQ_VSI_PROP_Q_OPT_VALID); if (enable) ctx->info.q_opt_flags |= ICE_AQ_VSI_Q_OPT_PE_FLTR_EN; else ctx->info.q_opt_flags &= ~ICE_AQ_VSI_Q_OPT_PE_FLTR_EN; status = ice_update_vsi(hw, vsi_handle, ctx, NULL); if (!status) { cached_ctx->info.q_opt_flags = ctx->info.q_opt_flags; cached_ctx->info.valid_sections |= ctx->info.valid_sections; } kfree(ctx); return status; } /** * ice_aq_alloc_free_vsi_list * @hw: pointer to the HW struct * @vsi_list_id: VSI list ID returned or used for lookup * @lkup_type: switch rule filter lookup type * @opc: switch rules population command type - pass in the command opcode * * allocates or free a VSI list resource */ static int ice_aq_alloc_free_vsi_list(struct ice_hw *hw, u16 *vsi_list_id, enum ice_sw_lkup_type lkup_type, enum ice_adminq_opc opc) { struct ice_aqc_alloc_free_res_elem *sw_buf; struct ice_aqc_res_elem *vsi_ele; u16 buf_len; int status; buf_len = struct_size(sw_buf, elem, 1); sw_buf = devm_kzalloc(ice_hw_to_dev(hw), buf_len, GFP_KERNEL); if (!sw_buf) return -ENOMEM; sw_buf->num_elems = cpu_to_le16(1); if (lkup_type == ICE_SW_LKUP_MAC || lkup_type == ICE_SW_LKUP_MAC_VLAN || lkup_type == ICE_SW_LKUP_ETHERTYPE || lkup_type == ICE_SW_LKUP_ETHERTYPE_MAC || lkup_type == ICE_SW_LKUP_PROMISC || lkup_type == ICE_SW_LKUP_PROMISC_VLAN || lkup_type == ICE_SW_LKUP_DFLT) { sw_buf->res_type = cpu_to_le16(ICE_AQC_RES_TYPE_VSI_LIST_REP); } else if (lkup_type == ICE_SW_LKUP_VLAN) { if (opc == ice_aqc_opc_alloc_res) sw_buf->res_type = cpu_to_le16(ICE_AQC_RES_TYPE_VSI_LIST_PRUNE | ICE_AQC_RES_TYPE_FLAG_SHARED); else sw_buf->res_type = cpu_to_le16(ICE_AQC_RES_TYPE_VSI_LIST_PRUNE); } else { status = -EINVAL; goto ice_aq_alloc_free_vsi_list_exit; } if (opc == ice_aqc_opc_free_res) sw_buf->elem[0].e.sw_resp = cpu_to_le16(*vsi_list_id); status = ice_aq_alloc_free_res(hw, sw_buf, buf_len, opc); if (status) goto ice_aq_alloc_free_vsi_list_exit; if (opc == ice_aqc_opc_alloc_res) { vsi_ele = &sw_buf->elem[0]; *vsi_list_id = le16_to_cpu(vsi_ele->e.sw_resp); } ice_aq_alloc_free_vsi_list_exit: devm_kfree(ice_hw_to_dev(hw), sw_buf); return status; } /** * ice_aq_sw_rules - add/update/remove switch rules * @hw: pointer to the HW struct * @rule_list: pointer to switch rule population list * @rule_list_sz: total size of the rule list in bytes * @num_rules: number of switch rules in the rule_list * @opc: switch rules population command type - pass in the command opcode * @cd: pointer to command details structure or NULL * * Add(0x02a0)/Update(0x02a1)/Remove(0x02a2) switch rules commands to firmware */ int ice_aq_sw_rules(struct ice_hw *hw, void *rule_list, u16 rule_list_sz, u8 num_rules, enum ice_adminq_opc opc, struct ice_sq_cd *cd) { struct ice_aq_desc desc; int status; if (opc != ice_aqc_opc_add_sw_rules && opc != ice_aqc_opc_update_sw_rules && opc != ice_aqc_opc_remove_sw_rules) return -EINVAL; ice_fill_dflt_direct_cmd_desc(&desc, opc); desc.flags |= cpu_to_le16(ICE_AQ_FLAG_RD); desc.params.sw_rules.num_rules_fltr_entry_index = cpu_to_le16(num_rules); status = ice_aq_send_cmd(hw, &desc, rule_list, rule_list_sz, cd); if (opc != ice_aqc_opc_add_sw_rules && hw->adminq.sq_last_status == ICE_AQ_RC_ENOENT) status = -ENOENT; return status; } /** * ice_aq_add_recipe - add switch recipe * @hw: pointer to the HW struct * @s_recipe_list: pointer to switch rule population list * @num_recipes: number of switch recipes in the list * @cd: pointer to command details structure or NULL * * Add(0x0290) */ int ice_aq_add_recipe(struct ice_hw *hw, struct ice_aqc_recipe_data_elem *s_recipe_list, u16 num_recipes, struct ice_sq_cd *cd) { struct ice_aqc_add_get_recipe *cmd; struct ice_aq_desc desc; u16 buf_size; cmd = &desc.params.add_get_recipe; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_add_recipe); cmd->num_sub_recipes = cpu_to_le16(num_recipes); desc.flags |= cpu_to_le16(ICE_AQ_FLAG_RD); buf_size = num_recipes * sizeof(*s_recipe_list); return ice_aq_send_cmd(hw, &desc, s_recipe_list, buf_size, cd); } /** * ice_aq_get_recipe - get switch recipe * @hw: pointer to the HW struct * @s_recipe_list: pointer to switch rule population list * @num_recipes: pointer to the number of recipes (input and output) * @recipe_root: root recipe number of recipe(s) to retrieve * @cd: pointer to command details structure or NULL * * Get(0x0292) * * On input, *num_recipes should equal the number of entries in s_recipe_list. * On output, *num_recipes will equal the number of entries returned in * s_recipe_list. * * The caller must supply enough space in s_recipe_list to hold all possible * recipes and *num_recipes must equal ICE_MAX_NUM_RECIPES. */ int ice_aq_get_recipe(struct ice_hw *hw, struct ice_aqc_recipe_data_elem *s_recipe_list, u16 *num_recipes, u16 recipe_root, struct ice_sq_cd *cd) { struct ice_aqc_add_get_recipe *cmd; struct ice_aq_desc desc; u16 buf_size; int status; if (*num_recipes != ICE_MAX_NUM_RECIPES) return -EINVAL; cmd = &desc.params.add_get_recipe; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_get_recipe); cmd->return_index = cpu_to_le16(recipe_root); cmd->num_sub_recipes = 0; buf_size = *num_recipes * sizeof(*s_recipe_list); status = ice_aq_send_cmd(hw, &desc, s_recipe_list, buf_size, cd); *num_recipes = le16_to_cpu(cmd->num_sub_recipes); return status; } /** * ice_update_recipe_lkup_idx - update a default recipe based on the lkup_idx * @hw: pointer to the HW struct * @params: parameters used to update the default recipe * * This function only supports updating default recipes and it only supports * updating a single recipe based on the lkup_idx at a time. * * This is done as a read-modify-write operation. First, get the current recipe * contents based on the recipe's ID. Then modify the field vector index and * mask if it's valid at the lkup_idx. Finally, use the add recipe AQ to update * the pre-existing recipe with the modifications. */ int ice_update_recipe_lkup_idx(struct ice_hw *hw, struct ice_update_recipe_lkup_idx_params *params) { struct ice_aqc_recipe_data_elem *rcp_list; u16 num_recps = ICE_MAX_NUM_RECIPES; int status; rcp_list = kcalloc(num_recps, sizeof(*rcp_list), GFP_KERNEL); if (!rcp_list) return -ENOMEM; /* read current recipe list from firmware */ rcp_list->recipe_indx = params->rid; status = ice_aq_get_recipe(hw, rcp_list, &num_recps, params->rid, NULL); if (status) { ice_debug(hw, ICE_DBG_SW, "Failed to get recipe %d, status %d\n", params->rid, status); goto error_out; } /* only modify existing recipe's lkup_idx and mask if valid, while * leaving all other fields the same, then update the recipe firmware */ rcp_list->content.lkup_indx[params->lkup_idx] = params->fv_idx; if (params->mask_valid) rcp_list->content.mask[params->lkup_idx] = cpu_to_le16(params->mask); if (params->ignore_valid) rcp_list->content.lkup_indx[params->lkup_idx] |= ICE_AQ_RECIPE_LKUP_IGNORE; status = ice_aq_add_recipe(hw, &rcp_list[0], 1, NULL); if (status) ice_debug(hw, ICE_DBG_SW, "Failed to update recipe %d lkup_idx %d fv_idx %d mask %d mask_valid %s, status %d\n", params->rid, params->lkup_idx, params->fv_idx, params->mask, params->mask_valid ? "true" : "false", status); error_out: kfree(rcp_list); return status; } /** * ice_aq_map_recipe_to_profile - Map recipe to packet profile * @hw: pointer to the HW struct * @profile_id: package profile ID to associate the recipe with * @r_bitmap: Recipe bitmap filled in and need to be returned as response * @cd: pointer to command details structure or NULL * Recipe to profile association (0x0291) */ int ice_aq_map_recipe_to_profile(struct ice_hw *hw, u32 profile_id, u8 *r_bitmap, struct ice_sq_cd *cd) { struct ice_aqc_recipe_to_profile *cmd; struct ice_aq_desc desc; cmd = &desc.params.recipe_to_profile; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_recipe_to_profile); cmd->profile_id = cpu_to_le16(profile_id); /* Set the recipe ID bit in the bitmask to let the device know which * profile we are associating the recipe to */ memcpy(cmd->recipe_assoc, r_bitmap, sizeof(cmd->recipe_assoc)); return ice_aq_send_cmd(hw, &desc, NULL, 0, cd); } /** * ice_aq_get_recipe_to_profile - Map recipe to packet profile * @hw: pointer to the HW struct * @profile_id: package profile ID to associate the recipe with * @r_bitmap: Recipe bitmap filled in and need to be returned as response * @cd: pointer to command details structure or NULL * Associate profile ID with given recipe (0x0293) */ int ice_aq_get_recipe_to_profile(struct ice_hw *hw, u32 profile_id, u8 *r_bitmap, struct ice_sq_cd *cd) { struct ice_aqc_recipe_to_profile *cmd; struct ice_aq_desc desc; int status; cmd = &desc.params.recipe_to_profile; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_get_recipe_to_profile); cmd->profile_id = cpu_to_le16(profile_id); status = ice_aq_send_cmd(hw, &desc, NULL, 0, cd); if (!status) memcpy(r_bitmap, cmd->recipe_assoc, sizeof(cmd->recipe_assoc)); return status; } /** * ice_alloc_recipe - add recipe resource * @hw: pointer to the hardware structure * @rid: recipe ID returned as response to AQ call */ int ice_alloc_recipe(struct ice_hw *hw, u16 *rid) { struct ice_aqc_alloc_free_res_elem *sw_buf; u16 buf_len; int status; buf_len = struct_size(sw_buf, elem, 1); sw_buf = kzalloc(buf_len, GFP_KERNEL); if (!sw_buf) return -ENOMEM; sw_buf->num_elems = cpu_to_le16(1); sw_buf->res_type = cpu_to_le16((ICE_AQC_RES_TYPE_RECIPE << ICE_AQC_RES_TYPE_S) | ICE_AQC_RES_TYPE_FLAG_SHARED); status = ice_aq_alloc_free_res(hw, sw_buf, buf_len, ice_aqc_opc_alloc_res); if (!status) *rid = le16_to_cpu(sw_buf->elem[0].e.sw_resp); kfree(sw_buf); return status; } /** * ice_get_recp_to_prof_map - updates recipe to profile mapping * @hw: pointer to hardware structure * * This function is used to populate recipe_to_profile matrix where index to * this array is the recipe ID and the element is the mapping of which profiles * is this recipe mapped to. */ static void ice_get_recp_to_prof_map(struct ice_hw *hw) { DECLARE_BITMAP(r_bitmap, ICE_MAX_NUM_RECIPES); u16 i; for (i = 0; i < hw->switch_info->max_used_prof_index + 1; i++) { u16 j; bitmap_zero(profile_to_recipe[i], ICE_MAX_NUM_RECIPES); bitmap_zero(r_bitmap, ICE_MAX_NUM_RECIPES); if (ice_aq_get_recipe_to_profile(hw, i, (u8 *)r_bitmap, NULL)) continue; bitmap_copy(profile_to_recipe[i], r_bitmap, ICE_MAX_NUM_RECIPES); for_each_set_bit(j, r_bitmap, ICE_MAX_NUM_RECIPES) set_bit(i, recipe_to_profile[j]); } } /** * ice_collect_result_idx - copy result index values * @buf: buffer that contains the result index * @recp: the recipe struct to copy data into */ static void ice_collect_result_idx(struct ice_aqc_recipe_data_elem *buf, struct ice_sw_recipe *recp) { if (buf->content.result_indx & ICE_AQ_RECIPE_RESULT_EN) set_bit(buf->content.result_indx & ~ICE_AQ_RECIPE_RESULT_EN, recp->res_idxs); } /** * ice_get_recp_frm_fw - update SW bookkeeping from FW recipe entries * @hw: pointer to hardware structure * @recps: struct that we need to populate * @rid: recipe ID that we are populating * @refresh_required: true if we should get recipe to profile mapping from FW * * This function is used to populate all the necessary entries into our * bookkeeping so that we have a current list of all the recipes that are * programmed in the firmware. */ static int ice_get_recp_frm_fw(struct ice_hw *hw, struct ice_sw_recipe *recps, u8 rid, bool *refresh_required) { DECLARE_BITMAP(result_bm, ICE_MAX_FV_WORDS); struct ice_aqc_recipe_data_elem *tmp; u16 num_recps = ICE_MAX_NUM_RECIPES; struct ice_prot_lkup_ext *lkup_exts; u8 fv_word_idx = 0; u16 sub_recps; int status; bitmap_zero(result_bm, ICE_MAX_FV_WORDS); /* we need a buffer big enough to accommodate all the recipes */ tmp = kcalloc(ICE_MAX_NUM_RECIPES, sizeof(*tmp), GFP_KERNEL); if (!tmp) return -ENOMEM; tmp[0].recipe_indx = rid; status = ice_aq_get_recipe(hw, tmp, &num_recps, rid, NULL); /* non-zero status meaning recipe doesn't exist */ if (status) goto err_unroll; /* Get recipe to profile map so that we can get the fv from lkups that * we read for a recipe from FW. Since we want to minimize the number of * times we make this FW call, just make one call and cache the copy * until a new recipe is added. This operation is only required the * first time to get the changes from FW. Then to search existing * entries we don't need to update the cache again until another recipe * gets added. */ if (*refresh_required) { ice_get_recp_to_prof_map(hw); *refresh_required = false; } /* Start populating all the entries for recps[rid] based on lkups from * firmware. Note that we are only creating the root recipe in our * database. */ lkup_exts = &recps[rid].lkup_exts; for (sub_recps = 0; sub_recps < num_recps; sub_recps++) { struct ice_aqc_recipe_data_elem root_bufs = tmp[sub_recps]; struct ice_recp_grp_entry *rg_entry; u8 i, prof, idx, prot = 0; bool is_root; u16 off = 0; rg_entry = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*rg_entry), GFP_KERNEL); if (!rg_entry) { status = -ENOMEM; goto err_unroll; } idx = root_bufs.recipe_indx; is_root = root_bufs.content.rid & ICE_AQ_RECIPE_ID_IS_ROOT; /* Mark all result indices in this chain */ if (root_bufs.content.result_indx & ICE_AQ_RECIPE_RESULT_EN) set_bit(root_bufs.content.result_indx & ~ICE_AQ_RECIPE_RESULT_EN, result_bm); /* get the first profile that is associated with rid */ prof = find_first_bit(recipe_to_profile[idx], ICE_MAX_NUM_PROFILES); for (i = 0; i < ICE_NUM_WORDS_RECIPE; i++) { u8 lkup_indx = root_bufs.content.lkup_indx[i + 1]; rg_entry->fv_idx[i] = lkup_indx; rg_entry->fv_mask[i] = le16_to_cpu(root_bufs.content.mask[i + 1]); /* If the recipe is a chained recipe then all its * child recipe's result will have a result index. * To fill fv_words we should not use those result * index, we only need the protocol ids and offsets. * We will skip all the fv_idx which stores result * index in them. We also need to skip any fv_idx which * has ICE_AQ_RECIPE_LKUP_IGNORE or 0 since it isn't a * valid offset value. */ if (test_bit(rg_entry->fv_idx[i], hw->switch_info->prof_res_bm[prof]) || rg_entry->fv_idx[i] & ICE_AQ_RECIPE_LKUP_IGNORE || rg_entry->fv_idx[i] == 0) continue; ice_find_prot_off(hw, ICE_BLK_SW, prof, rg_entry->fv_idx[i], &prot, &off); lkup_exts->fv_words[fv_word_idx].prot_id = prot; lkup_exts->fv_words[fv_word_idx].off = off; lkup_exts->field_mask[fv_word_idx] = rg_entry->fv_mask[i]; fv_word_idx++; } /* populate rg_list with the data from the child entry of this * recipe */ list_add(&rg_entry->l_entry, &recps[rid].rg_list); /* Propagate some data to the recipe database */ recps[idx].is_root = !!is_root; recps[idx].priority = root_bufs.content.act_ctrl_fwd_priority; recps[idx].need_pass_l2 = root_bufs.content.act_ctrl & ICE_AQ_RECIPE_ACT_NEED_PASS_L2; recps[idx].allow_pass_l2 = root_bufs.content.act_ctrl & ICE_AQ_RECIPE_ACT_ALLOW_PASS_L2; bitmap_zero(recps[idx].res_idxs, ICE_MAX_FV_WORDS); if (root_bufs.content.result_indx & ICE_AQ_RECIPE_RESULT_EN) { recps[idx].chain_idx = root_bufs.content.result_indx & ~ICE_AQ_RECIPE_RESULT_EN; set_bit(recps[idx].chain_idx, recps[idx].res_idxs); } else { recps[idx].chain_idx = ICE_INVAL_CHAIN_IND; } if (!is_root) continue; /* Only do the following for root recipes entries */ memcpy(recps[idx].r_bitmap, root_bufs.recipe_bitmap, sizeof(recps[idx].r_bitmap)); recps[idx].root_rid = root_bufs.content.rid & ~ICE_AQ_RECIPE_ID_IS_ROOT; recps[idx].priority = root_bufs.content.act_ctrl_fwd_priority; } /* Complete initialization of the root recipe entry */ lkup_exts->n_val_words = fv_word_idx; recps[rid].big_recp = (num_recps > 1); recps[rid].n_grp_count = (u8)num_recps; recps[rid].root_buf = devm_kmemdup(ice_hw_to_dev(hw), tmp, recps[rid].n_grp_count * sizeof(*recps[rid].root_buf), GFP_KERNEL); if (!recps[rid].root_buf) { status = -ENOMEM; goto err_unroll; } /* Copy result indexes */ bitmap_copy(recps[rid].res_idxs, result_bm, ICE_MAX_FV_WORDS); recps[rid].recp_created = true; err_unroll: kfree(tmp); return status; } /* ice_init_port_info - Initialize port_info with switch configuration data * @pi: pointer to port_info * @vsi_port_num: VSI number or port number * @type: Type of switch element (port or VSI) * @swid: switch ID of the switch the element is attached to * @pf_vf_num: PF or VF number * @is_vf: true if the element is a VF, false otherwise */ static void ice_init_port_info(struct ice_port_info *pi, u16 vsi_port_num, u8 type, u16 swid, u16 pf_vf_num, bool is_vf) { switch (type) { case ICE_AQC_GET_SW_CONF_RESP_PHYS_PORT: pi->lport = (u8)(vsi_port_num & ICE_LPORT_MASK); pi->sw_id = swid; pi->pf_vf_num = pf_vf_num; pi->is_vf = is_vf; break; default: ice_debug(pi->hw, ICE_DBG_SW, "incorrect VSI/port type received\n"); break; } } /* ice_get_initial_sw_cfg - Get initial port and default VSI data * @hw: pointer to the hardware structure */ int ice_get_initial_sw_cfg(struct ice_hw *hw) { struct ice_aqc_get_sw_cfg_resp_elem *rbuf; u16 req_desc = 0; u16 num_elems; int status; u16 i; rbuf = kzalloc(ICE_SW_CFG_MAX_BUF_LEN, GFP_KERNEL); if (!rbuf) return -ENOMEM; /* Multiple calls to ice_aq_get_sw_cfg may be required * to get all the switch configuration information. The need * for additional calls is indicated by ice_aq_get_sw_cfg * writing a non-zero value in req_desc */ do { struct ice_aqc_get_sw_cfg_resp_elem *ele; status = ice_aq_get_sw_cfg(hw, rbuf, ICE_SW_CFG_MAX_BUF_LEN, &req_desc, &num_elems, NULL); if (status) break; for (i = 0, ele = rbuf; i < num_elems; i++, ele++) { u16 pf_vf_num, swid, vsi_port_num; bool is_vf = false; u8 res_type; vsi_port_num = le16_to_cpu(ele->vsi_port_num) & ICE_AQC_GET_SW_CONF_RESP_VSI_PORT_NUM_M; pf_vf_num = le16_to_cpu(ele->pf_vf_num) & ICE_AQC_GET_SW_CONF_RESP_FUNC_NUM_M; swid = le16_to_cpu(ele->swid); if (le16_to_cpu(ele->pf_vf_num) & ICE_AQC_GET_SW_CONF_RESP_IS_VF) is_vf = true; res_type = (u8)(le16_to_cpu(ele->vsi_port_num) >> ICE_AQC_GET_SW_CONF_RESP_TYPE_S); if (res_type == ICE_AQC_GET_SW_CONF_RESP_VSI) { /* FW VSI is not needed. Just continue. */ continue; } ice_init_port_info(hw->port_info, vsi_port_num, res_type, swid, pf_vf_num, is_vf); } } while (req_desc && !status); kfree(rbuf); return status; } /** * ice_fill_sw_info - Helper function to populate lb_en and lan_en * @hw: pointer to the hardware structure * @fi: filter info structure to fill/update * * This helper function populates the lb_en and lan_en elements of the provided * ice_fltr_info struct using the switch's type and characteristics of the * switch rule being configured. */ static void ice_fill_sw_info(struct ice_hw *hw, struct ice_fltr_info *fi) { fi->lb_en = false; fi->lan_en = false; if ((fi->flag & ICE_FLTR_TX) && (fi->fltr_act == ICE_FWD_TO_VSI || fi->fltr_act == ICE_FWD_TO_VSI_LIST || fi->fltr_act == ICE_FWD_TO_Q || fi->fltr_act == ICE_FWD_TO_QGRP)) { /* Setting LB for prune actions will result in replicated * packets to the internal switch that will be dropped. */ if (fi->lkup_type != ICE_SW_LKUP_VLAN) fi->lb_en = true; /* Set lan_en to TRUE if * 1. The switch is a VEB AND * 2 * 2.1 The lookup is a directional lookup like ethertype, * promiscuous, ethertype-MAC, promiscuous-VLAN * and default-port OR * 2.2 The lookup is VLAN, OR * 2.3 The lookup is MAC with mcast or bcast addr for MAC, OR * 2.4 The lookup is MAC_VLAN with mcast or bcast addr for MAC. * * OR * * The switch is a VEPA. * * In all other cases, the LAN enable has to be set to false. */ if (hw->evb_veb) { if (fi->lkup_type == ICE_SW_LKUP_ETHERTYPE || fi->lkup_type == ICE_SW_LKUP_PROMISC || fi->lkup_type == ICE_SW_LKUP_ETHERTYPE_MAC || fi->lkup_type == ICE_SW_LKUP_PROMISC_VLAN || fi->lkup_type == ICE_SW_LKUP_DFLT || fi->lkup_type == ICE_SW_LKUP_VLAN || (fi->lkup_type == ICE_SW_LKUP_MAC && !is_unicast_ether_addr(fi->l_data.mac.mac_addr)) || (fi->lkup_type == ICE_SW_LKUP_MAC_VLAN && !is_unicast_ether_addr(fi->l_data.mac.mac_addr))) fi->lan_en = true; } else { fi->lan_en = true; } } } /** * ice_fill_eth_hdr - helper to copy dummy_eth_hdr into supplied buffer * @eth_hdr: pointer to buffer to populate */ void ice_fill_eth_hdr(u8 *eth_hdr) { memcpy(eth_hdr, dummy_eth_header, DUMMY_ETH_HDR_LEN); } /** * ice_fill_sw_rule - Helper function to fill switch rule structure * @hw: pointer to the hardware structure * @f_info: entry containing packet forwarding information * @s_rule: switch rule structure to be filled in based on mac_entry * @opc: switch rules population command type - pass in the command opcode */ static void ice_fill_sw_rule(struct ice_hw *hw, struct ice_fltr_info *f_info, struct ice_sw_rule_lkup_rx_tx *s_rule, enum ice_adminq_opc opc) { u16 vlan_id = ICE_MAX_VLAN_ID + 1; u16 vlan_tpid = ETH_P_8021Q; void *daddr = NULL; u16 eth_hdr_sz; u8 *eth_hdr; u32 act = 0; __be16 *off; u8 q_rgn; if (opc == ice_aqc_opc_remove_sw_rules) { s_rule->act = 0; s_rule->index = cpu_to_le16(f_info->fltr_rule_id); s_rule->hdr_len = 0; return; } eth_hdr_sz = sizeof(dummy_eth_header); eth_hdr = s_rule->hdr_data; /* initialize the ether header with a dummy header */ memcpy(eth_hdr, dummy_eth_header, eth_hdr_sz); ice_fill_sw_info(hw, f_info); switch (f_info->fltr_act) { case ICE_FWD_TO_VSI: act |= (f_info->fwd_id.hw_vsi_id << ICE_SINGLE_ACT_VSI_ID_S) & ICE_SINGLE_ACT_VSI_ID_M; if (f_info->lkup_type != ICE_SW_LKUP_VLAN) act |= ICE_SINGLE_ACT_VSI_FORWARDING | ICE_SINGLE_ACT_VALID_BIT; break; case ICE_FWD_TO_VSI_LIST: act |= ICE_SINGLE_ACT_VSI_LIST; act |= (f_info->fwd_id.vsi_list_id << ICE_SINGLE_ACT_VSI_LIST_ID_S) & ICE_SINGLE_ACT_VSI_LIST_ID_M; if (f_info->lkup_type != ICE_SW_LKUP_VLAN) act |= ICE_SINGLE_ACT_VSI_FORWARDING | ICE_SINGLE_ACT_VALID_BIT; break; case ICE_FWD_TO_Q: act |= ICE_SINGLE_ACT_TO_Q; act |= (f_info->fwd_id.q_id << ICE_SINGLE_ACT_Q_INDEX_S) & ICE_SINGLE_ACT_Q_INDEX_M; break; case ICE_DROP_PACKET: act |= ICE_SINGLE_ACT_VSI_FORWARDING | ICE_SINGLE_ACT_DROP | ICE_SINGLE_ACT_VALID_BIT; break; case ICE_FWD_TO_QGRP: q_rgn = f_info->qgrp_size > 0 ? (u8)ilog2(f_info->qgrp_size) : 0; act |= ICE_SINGLE_ACT_TO_Q; act |= (f_info->fwd_id.q_id << ICE_SINGLE_ACT_Q_INDEX_S) & ICE_SINGLE_ACT_Q_INDEX_M; act |= (q_rgn << ICE_SINGLE_ACT_Q_REGION_S) & ICE_SINGLE_ACT_Q_REGION_M; break; default: return; } if (f_info->lb_en) act |= ICE_SINGLE_ACT_LB_ENABLE; if (f_info->lan_en) act |= ICE_SINGLE_ACT_LAN_ENABLE; switch (f_info->lkup_type) { case ICE_SW_LKUP_MAC: daddr = f_info->l_data.mac.mac_addr; break; case ICE_SW_LKUP_VLAN: vlan_id = f_info->l_data.vlan.vlan_id; if (f_info->l_data.vlan.tpid_valid) vlan_tpid = f_info->l_data.vlan.tpid; if (f_info->fltr_act == ICE_FWD_TO_VSI || f_info->fltr_act == ICE_FWD_TO_VSI_LIST) { act |= ICE_SINGLE_ACT_PRUNE; act |= ICE_SINGLE_ACT_EGRESS | ICE_SINGLE_ACT_INGRESS; } break; case ICE_SW_LKUP_ETHERTYPE_MAC: daddr = f_info->l_data.ethertype_mac.mac_addr; fallthrough; case ICE_SW_LKUP_ETHERTYPE: off = (__force __be16 *)(eth_hdr + ICE_ETH_ETHTYPE_OFFSET); *off = cpu_to_be16(f_info->l_data.ethertype_mac.ethertype); break; case ICE_SW_LKUP_MAC_VLAN: daddr = f_info->l_data.mac_vlan.mac_addr; vlan_id = f_info->l_data.mac_vlan.vlan_id; break; case ICE_SW_LKUP_PROMISC_VLAN: vlan_id = f_info->l_data.mac_vlan.vlan_id; fallthrough; case ICE_SW_LKUP_PROMISC: daddr = f_info->l_data.mac_vlan.mac_addr; break; default: break; } s_rule->hdr.type = (f_info->flag & ICE_FLTR_RX) ? cpu_to_le16(ICE_AQC_SW_RULES_T_LKUP_RX) : cpu_to_le16(ICE_AQC_SW_RULES_T_LKUP_TX); /* Recipe set depending on lookup type */ s_rule->recipe_id = cpu_to_le16(f_info->lkup_type); s_rule->src = cpu_to_le16(f_info->src); s_rule->act = cpu_to_le32(act); if (daddr) ether_addr_copy(eth_hdr + ICE_ETH_DA_OFFSET, daddr); if (!(vlan_id > ICE_MAX_VLAN_ID)) { off = (__force __be16 *)(eth_hdr + ICE_ETH_VLAN_TCI_OFFSET); *off = cpu_to_be16(vlan_id); off = (__force __be16 *)(eth_hdr + ICE_ETH_ETHTYPE_OFFSET); *off = cpu_to_be16(vlan_tpid); } /* Create the switch rule with the final dummy Ethernet header */ if (opc != ice_aqc_opc_update_sw_rules) s_rule->hdr_len = cpu_to_le16(eth_hdr_sz); } /** * ice_add_marker_act * @hw: pointer to the hardware structure * @m_ent: the management entry for which sw marker needs to be added * @sw_marker: sw marker to tag the Rx descriptor with * @l_id: large action resource ID * * Create a large action to hold software marker and update the switch rule * entry pointed by m_ent with newly created large action */ static int ice_add_marker_act(struct ice_hw *hw, struct ice_fltr_mgmt_list_entry *m_ent, u16 sw_marker, u16 l_id) { struct ice_sw_rule_lkup_rx_tx *rx_tx; struct ice_sw_rule_lg_act *lg_act; /* For software marker we need 3 large actions * 1. FWD action: FWD TO VSI or VSI LIST * 2. GENERIC VALUE action to hold the profile ID * 3. GENERIC VALUE action to hold the software marker ID */ const u16 num_lg_acts = 3; u16 lg_act_size; u16 rules_size; int status; u32 act; u16 id; if (m_ent->fltr_info.lkup_type != ICE_SW_LKUP_MAC) return -EINVAL; /* Create two back-to-back switch rules and submit them to the HW using * one memory buffer: * 1. Large Action * 2. Look up Tx Rx */ lg_act_size = (u16)ICE_SW_RULE_LG_ACT_SIZE(lg_act, num_lg_acts); rules_size = lg_act_size + ICE_SW_RULE_RX_TX_ETH_HDR_SIZE(rx_tx); lg_act = devm_kzalloc(ice_hw_to_dev(hw), rules_size, GFP_KERNEL); if (!lg_act) return -ENOMEM; rx_tx = (typeof(rx_tx))((u8 *)lg_act + lg_act_size); /* Fill in the first switch rule i.e. large action */ lg_act->hdr.type = cpu_to_le16(ICE_AQC_SW_RULES_T_LG_ACT); lg_act->index = cpu_to_le16(l_id); lg_act->size = cpu_to_le16(num_lg_acts); /* First action VSI forwarding or VSI list forwarding depending on how * many VSIs */ id = (m_ent->vsi_count > 1) ? m_ent->fltr_info.fwd_id.vsi_list_id : m_ent->fltr_info.fwd_id.hw_vsi_id; act = ICE_LG_ACT_VSI_FORWARDING | ICE_LG_ACT_VALID_BIT; act |= (id << ICE_LG_ACT_VSI_LIST_ID_S) & ICE_LG_ACT_VSI_LIST_ID_M; if (m_ent->vsi_count > 1) act |= ICE_LG_ACT_VSI_LIST; lg_act->act[0] = cpu_to_le32(act); /* Second action descriptor type */ act = ICE_LG_ACT_GENERIC; act |= (1 << ICE_LG_ACT_GENERIC_VALUE_S) & ICE_LG_ACT_GENERIC_VALUE_M; lg_act->act[1] = cpu_to_le32(act); act = (ICE_LG_ACT_GENERIC_OFF_RX_DESC_PROF_IDX << ICE_LG_ACT_GENERIC_OFFSET_S) & ICE_LG_ACT_GENERIC_OFFSET_M; /* Third action Marker value */ act |= ICE_LG_ACT_GENERIC; act |= (sw_marker << ICE_LG_ACT_GENERIC_VALUE_S) & ICE_LG_ACT_GENERIC_VALUE_M; lg_act->act[2] = cpu_to_le32(act); /* call the fill switch rule to fill the lookup Tx Rx structure */ ice_fill_sw_rule(hw, &m_ent->fltr_info, rx_tx, ice_aqc_opc_update_sw_rules); /* Update the action to point to the large action ID */ rx_tx->act = cpu_to_le32(ICE_SINGLE_ACT_PTR | ((l_id << ICE_SINGLE_ACT_PTR_VAL_S) & ICE_SINGLE_ACT_PTR_VAL_M)); /* Use the filter rule ID of the previously created rule with single * act. Once the update happens, hardware will treat this as large * action */ rx_tx->index = cpu_to_le16(m_ent->fltr_info.fltr_rule_id); status = ice_aq_sw_rules(hw, lg_act, rules_size, 2, ice_aqc_opc_update_sw_rules, NULL); if (!status) { m_ent->lg_act_idx = l_id; m_ent->sw_marker_id = sw_marker; } devm_kfree(ice_hw_to_dev(hw), lg_act); return status; } /** * ice_create_vsi_list_map * @hw: pointer to the hardware structure * @vsi_handle_arr: array of VSI handles to set in the VSI mapping * @num_vsi: number of VSI handles in the array * @vsi_list_id: VSI list ID generated as part of allocate resource * * Helper function to create a new entry of VSI list ID to VSI mapping * using the given VSI list ID */ static struct ice_vsi_list_map_info * ice_create_vsi_list_map(struct ice_hw *hw, u16 *vsi_handle_arr, u16 num_vsi, u16 vsi_list_id) { struct ice_switch_info *sw = hw->switch_info; struct ice_vsi_list_map_info *v_map; int i; v_map = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*v_map), GFP_KERNEL); if (!v_map) return NULL; v_map->vsi_list_id = vsi_list_id; v_map->ref_cnt = 1; for (i = 0; i < num_vsi; i++) set_bit(vsi_handle_arr[i], v_map->vsi_map); list_add(&v_map->list_entry, &sw->vsi_list_map_head); return v_map; } /** * ice_update_vsi_list_rule * @hw: pointer to the hardware structure * @vsi_handle_arr: array of VSI handles to form a VSI list * @num_vsi: number of VSI handles in the array * @vsi_list_id: VSI list ID generated as part of allocate resource * @remove: Boolean value to indicate if this is a remove action * @opc: switch rules population command type - pass in the command opcode * @lkup_type: lookup type of the filter * * Call AQ command to add a new switch rule or update existing switch rule * using the given VSI list ID */ static int ice_update_vsi_list_rule(struct ice_hw *hw, u16 *vsi_handle_arr, u16 num_vsi, u16 vsi_list_id, bool remove, enum ice_adminq_opc opc, enum ice_sw_lkup_type lkup_type) { struct ice_sw_rule_vsi_list *s_rule; u16 s_rule_size; u16 rule_type; int status; int i; if (!num_vsi) return -EINVAL; if (lkup_type == ICE_SW_LKUP_MAC || lkup_type == ICE_SW_LKUP_MAC_VLAN || lkup_type == ICE_SW_LKUP_ETHERTYPE || lkup_type == ICE_SW_LKUP_ETHERTYPE_MAC || lkup_type == ICE_SW_LKUP_PROMISC || lkup_type == ICE_SW_LKUP_PROMISC_VLAN || lkup_type == ICE_SW_LKUP_DFLT) rule_type = remove ? ICE_AQC_SW_RULES_T_VSI_LIST_CLEAR : ICE_AQC_SW_RULES_T_VSI_LIST_SET; else if (lkup_type == ICE_SW_LKUP_VLAN) rule_type = remove ? ICE_AQC_SW_RULES_T_PRUNE_LIST_CLEAR : ICE_AQC_SW_RULES_T_PRUNE_LIST_SET; else return -EINVAL; s_rule_size = (u16)ICE_SW_RULE_VSI_LIST_SIZE(s_rule, num_vsi); s_rule = devm_kzalloc(ice_hw_to_dev(hw), s_rule_size, GFP_KERNEL); if (!s_rule) return -ENOMEM; for (i = 0; i < num_vsi; i++) { if (!ice_is_vsi_valid(hw, vsi_handle_arr[i])) { status = -EINVAL; goto exit; } /* AQ call requires hw_vsi_id(s) */ s_rule->vsi[i] = cpu_to_le16(ice_get_hw_vsi_num(hw, vsi_handle_arr[i])); } s_rule->hdr.type = cpu_to_le16(rule_type); s_rule->number_vsi = cpu_to_le16(num_vsi); s_rule->index = cpu_to_le16(vsi_list_id); status = ice_aq_sw_rules(hw, s_rule, s_rule_size, 1, opc, NULL); exit: devm_kfree(ice_hw_to_dev(hw), s_rule); return status; } /** * ice_create_vsi_list_rule - Creates and populates a VSI list rule * @hw: pointer to the HW struct * @vsi_handle_arr: array of VSI handles to form a VSI list * @num_vsi: number of VSI handles in the array * @vsi_list_id: stores the ID of the VSI list to be created * @lkup_type: switch rule filter's lookup type */ static int ice_create_vsi_list_rule(struct ice_hw *hw, u16 *vsi_handle_arr, u16 num_vsi, u16 *vsi_list_id, enum ice_sw_lkup_type lkup_type) { int status; status = ice_aq_alloc_free_vsi_list(hw, vsi_list_id, lkup_type, ice_aqc_opc_alloc_res); if (status) return status; /* Update the newly created VSI list to include the specified VSIs */ return ice_update_vsi_list_rule(hw, vsi_handle_arr, num_vsi, *vsi_list_id, false, ice_aqc_opc_add_sw_rules, lkup_type); } /** * ice_create_pkt_fwd_rule * @hw: pointer to the hardware structure * @f_entry: entry containing packet forwarding information * * Create switch rule with given filter information and add an entry * to the corresponding filter management list to track this switch rule * and VSI mapping */ static int ice_create_pkt_fwd_rule(struct ice_hw *hw, struct ice_fltr_list_entry *f_entry) { struct ice_fltr_mgmt_list_entry *fm_entry; struct ice_sw_rule_lkup_rx_tx *s_rule; enum ice_sw_lkup_type l_type; struct ice_sw_recipe *recp; int status; s_rule = devm_kzalloc(ice_hw_to_dev(hw), ICE_SW_RULE_RX_TX_ETH_HDR_SIZE(s_rule), GFP_KERNEL); if (!s_rule) return -ENOMEM; fm_entry = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*fm_entry), GFP_KERNEL); if (!fm_entry) { status = -ENOMEM; goto ice_create_pkt_fwd_rule_exit; } fm_entry->fltr_info = f_entry->fltr_info; /* Initialize all the fields for the management entry */ fm_entry->vsi_count = 1; fm_entry->lg_act_idx = ICE_INVAL_LG_ACT_INDEX; fm_entry->sw_marker_id = ICE_INVAL_SW_MARKER_ID; fm_entry->counter_index = ICE_INVAL_COUNTER_ID; ice_fill_sw_rule(hw, &fm_entry->fltr_info, s_rule, ice_aqc_opc_add_sw_rules); status = ice_aq_sw_rules(hw, s_rule, ICE_SW_RULE_RX_TX_ETH_HDR_SIZE(s_rule), 1, ice_aqc_opc_add_sw_rules, NULL); if (status) { devm_kfree(ice_hw_to_dev(hw), fm_entry); goto ice_create_pkt_fwd_rule_exit; } f_entry->fltr_info.fltr_rule_id = le16_to_cpu(s_rule->index); fm_entry->fltr_info.fltr_rule_id = le16_to_cpu(s_rule->index); /* The book keeping entries will get removed when base driver * calls remove filter AQ command */ l_type = fm_entry->fltr_info.lkup_type; recp = &hw->switch_info->recp_list[l_type]; list_add(&fm_entry->list_entry, &recp->filt_rules); ice_create_pkt_fwd_rule_exit: devm_kfree(ice_hw_to_dev(hw), s_rule); return status; } /** * ice_update_pkt_fwd_rule * @hw: pointer to the hardware structure * @f_info: filter information for switch rule * * Call AQ command to update a previously created switch rule with a * VSI list ID */ static int ice_update_pkt_fwd_rule(struct ice_hw *hw, struct ice_fltr_info *f_info) { struct ice_sw_rule_lkup_rx_tx *s_rule; int status; s_rule = devm_kzalloc(ice_hw_to_dev(hw), ICE_SW_RULE_RX_TX_ETH_HDR_SIZE(s_rule), GFP_KERNEL); if (!s_rule) return -ENOMEM; ice_fill_sw_rule(hw, f_info, s_rule, ice_aqc_opc_update_sw_rules); s_rule->index = cpu_to_le16(f_info->fltr_rule_id); /* Update switch rule with new rule set to forward VSI list */ status = ice_aq_sw_rules(hw, s_rule, ICE_SW_RULE_RX_TX_ETH_HDR_SIZE(s_rule), 1, ice_aqc_opc_update_sw_rules, NULL); devm_kfree(ice_hw_to_dev(hw), s_rule); return status; } /** * ice_update_sw_rule_bridge_mode * @hw: pointer to the HW struct * * Updates unicast switch filter rules based on VEB/VEPA mode */ int ice_update_sw_rule_bridge_mode(struct ice_hw *hw) { struct ice_switch_info *sw = hw->switch_info; struct ice_fltr_mgmt_list_entry *fm_entry; struct list_head *rule_head; struct mutex *rule_lock; /* Lock to protect filter rule list */ int status = 0; rule_lock = &sw->recp_list[ICE_SW_LKUP_MAC].filt_rule_lock; rule_head = &sw->recp_list[ICE_SW_LKUP_MAC].filt_rules; mutex_lock(rule_lock); list_for_each_entry(fm_entry, rule_head, list_entry) { struct ice_fltr_info *fi = &fm_entry->fltr_info; u8 *addr = fi->l_data.mac.mac_addr; /* Update unicast Tx rules to reflect the selected * VEB/VEPA mode */ if ((fi->flag & ICE_FLTR_TX) && is_unicast_ether_addr(addr) && (fi->fltr_act == ICE_FWD_TO_VSI || fi->fltr_act == ICE_FWD_TO_VSI_LIST || fi->fltr_act == ICE_FWD_TO_Q || fi->fltr_act == ICE_FWD_TO_QGRP)) { status = ice_update_pkt_fwd_rule(hw, fi); if (status) break; } } mutex_unlock(rule_lock); return status; } /** * ice_add_update_vsi_list * @hw: pointer to the hardware structure * @m_entry: pointer to current filter management list entry * @cur_fltr: filter information from the book keeping entry * @new_fltr: filter information with the new VSI to be added * * Call AQ command to add or update previously created VSI list with new VSI. * * Helper function to do book keeping associated with adding filter information * The algorithm to do the book keeping is described below : * When a VSI needs to subscribe to a given filter (MAC/VLAN/Ethtype etc.) * if only one VSI has been added till now * Allocate a new VSI list and add two VSIs * to this list using switch rule command * Update the previously created switch rule with the * newly created VSI list ID * if a VSI list was previously created * Add the new VSI to the previously created VSI list set * using the update switch rule command */ static int ice_add_update_vsi_list(struct ice_hw *hw, struct ice_fltr_mgmt_list_entry *m_entry, struct ice_fltr_info *cur_fltr, struct ice_fltr_info *new_fltr) { u16 vsi_list_id = 0; int status = 0; if ((cur_fltr->fltr_act == ICE_FWD_TO_Q || cur_fltr->fltr_act == ICE_FWD_TO_QGRP)) return -EOPNOTSUPP; if ((new_fltr->fltr_act == ICE_FWD_TO_Q || new_fltr->fltr_act == ICE_FWD_TO_QGRP) && (cur_fltr->fltr_act == ICE_FWD_TO_VSI || cur_fltr->fltr_act == ICE_FWD_TO_VSI_LIST)) return -EOPNOTSUPP; if (m_entry->vsi_count < 2 && !m_entry->vsi_list_info) { /* Only one entry existed in the mapping and it was not already * a part of a VSI list. So, create a VSI list with the old and * new VSIs. */ struct ice_fltr_info tmp_fltr; u16 vsi_handle_arr[2]; /* A rule already exists with the new VSI being added */ if (cur_fltr->fwd_id.hw_vsi_id == new_fltr->fwd_id.hw_vsi_id) return -EEXIST; vsi_handle_arr[0] = cur_fltr->vsi_handle; vsi_handle_arr[1] = new_fltr->vsi_handle; status = ice_create_vsi_list_rule(hw, &vsi_handle_arr[0], 2, &vsi_list_id, new_fltr->lkup_type); if (status) return status; tmp_fltr = *new_fltr; tmp_fltr.fltr_rule_id = cur_fltr->fltr_rule_id; tmp_fltr.fltr_act = ICE_FWD_TO_VSI_LIST; tmp_fltr.fwd_id.vsi_list_id = vsi_list_id; /* Update the previous switch rule of "MAC forward to VSI" to * "MAC fwd to VSI list" */ status = ice_update_pkt_fwd_rule(hw, &tmp_fltr); if (status) return status; cur_fltr->fwd_id.vsi_list_id = vsi_list_id; cur_fltr->fltr_act = ICE_FWD_TO_VSI_LIST; m_entry->vsi_list_info = ice_create_vsi_list_map(hw, &vsi_handle_arr[0], 2, vsi_list_id); if (!m_entry->vsi_list_info) return -ENOMEM; /* If this entry was large action then the large action needs * to be updated to point to FWD to VSI list */ if (m_entry->sw_marker_id != ICE_INVAL_SW_MARKER_ID) status = ice_add_marker_act(hw, m_entry, m_entry->sw_marker_id, m_entry->lg_act_idx); } else { u16 vsi_handle = new_fltr->vsi_handle; enum ice_adminq_opc opcode; if (!m_entry->vsi_list_info) return -EIO; /* A rule already exists with the new VSI being added */ if (test_bit(vsi_handle, m_entry->vsi_list_info->vsi_map)) return 0; /* Update the previously created VSI list set with * the new VSI ID passed in */ vsi_list_id = cur_fltr->fwd_id.vsi_list_id; opcode = ice_aqc_opc_update_sw_rules; status = ice_update_vsi_list_rule(hw, &vsi_handle, 1, vsi_list_id, false, opcode, new_fltr->lkup_type); /* update VSI list mapping info with new VSI ID */ if (!status) set_bit(vsi_handle, m_entry->vsi_list_info->vsi_map); } if (!status) m_entry->vsi_count++; return status; } /** * ice_find_rule_entry - Search a rule entry * @hw: pointer to the hardware structure * @recp_id: lookup type for which the specified rule needs to be searched * @f_info: rule information * * Helper function to search for a given rule entry * Returns pointer to entry storing the rule if found */ static struct ice_fltr_mgmt_list_entry * ice_find_rule_entry(struct ice_hw *hw, u8 recp_id, struct ice_fltr_info *f_info) { struct ice_fltr_mgmt_list_entry *list_itr, *ret = NULL; struct ice_switch_info *sw = hw->switch_info; struct list_head *list_head; list_head = &sw->recp_list[recp_id].filt_rules; list_for_each_entry(list_itr, list_head, list_entry) { if (!memcmp(&f_info->l_data, &list_itr->fltr_info.l_data, sizeof(f_info->l_data)) && f_info->flag == list_itr->fltr_info.flag) { ret = list_itr; break; } } return ret; } /** * ice_find_vsi_list_entry - Search VSI list map with VSI count 1 * @hw: pointer to the hardware structure * @recp_id: lookup type for which VSI lists needs to be searched * @vsi_handle: VSI handle to be found in VSI list * @vsi_list_id: VSI list ID found containing vsi_handle * * Helper function to search a VSI list with single entry containing given VSI * handle element. This can be extended further to search VSI list with more * than 1 vsi_count. Returns pointer to VSI list entry if found. */ struct ice_vsi_list_map_info * ice_find_vsi_list_entry(struct ice_hw *hw, u8 recp_id, u16 vsi_handle, u16 *vsi_list_id) { struct ice_vsi_list_map_info *map_info = NULL; struct ice_switch_info *sw = hw->switch_info; struct ice_fltr_mgmt_list_entry *list_itr; struct list_head *list_head; list_head = &sw->recp_list[recp_id].filt_rules; list_for_each_entry(list_itr, list_head, list_entry) { if (list_itr->vsi_list_info) { map_info = list_itr->vsi_list_info; if (test_bit(vsi_handle, map_info->vsi_map)) { *vsi_list_id = map_info->vsi_list_id; return map_info; } } } return NULL; } /** * ice_add_rule_internal - add rule for a given lookup type * @hw: pointer to the hardware structure * @recp_id: lookup type (recipe ID) for which rule has to be added * @f_entry: structure containing MAC forwarding information * * Adds or updates the rule lists for a given recipe */ static int ice_add_rule_internal(struct ice_hw *hw, u8 recp_id, struct ice_fltr_list_entry *f_entry) { struct ice_switch_info *sw = hw->switch_info; struct ice_fltr_info *new_fltr, *cur_fltr; struct ice_fltr_mgmt_list_entry *m_entry; struct mutex *rule_lock; /* Lock to protect filter rule list */ int status = 0; if (!ice_is_vsi_valid(hw, f_entry->fltr_info.vsi_handle)) return -EINVAL; f_entry->fltr_info.fwd_id.hw_vsi_id = ice_get_hw_vsi_num(hw, f_entry->fltr_info.vsi_handle); rule_lock = &sw->recp_list[recp_id].filt_rule_lock; mutex_lock(rule_lock); new_fltr = &f_entry->fltr_info; if (new_fltr->flag & ICE_FLTR_RX) new_fltr->src = hw->port_info->lport; else if (new_fltr->flag & ICE_FLTR_TX) new_fltr->src = f_entry->fltr_info.fwd_id.hw_vsi_id; m_entry = ice_find_rule_entry(hw, recp_id, new_fltr); if (!m_entry) { mutex_unlock(rule_lock); return ice_create_pkt_fwd_rule(hw, f_entry); } cur_fltr = &m_entry->fltr_info; status = ice_add_update_vsi_list(hw, m_entry, cur_fltr, new_fltr); mutex_unlock(rule_lock); return status; } /** * ice_remove_vsi_list_rule * @hw: pointer to the hardware structure * @vsi_list_id: VSI list ID generated as part of allocate resource * @lkup_type: switch rule filter lookup type * * The VSI list should be emptied before this function is called to remove the * VSI list. */ static int ice_remove_vsi_list_rule(struct ice_hw *hw, u16 vsi_list_id, enum ice_sw_lkup_type lkup_type) { struct ice_sw_rule_vsi_list *s_rule; u16 s_rule_size; int status; s_rule_size = (u16)ICE_SW_RULE_VSI_LIST_SIZE(s_rule, 0); s_rule = devm_kzalloc(ice_hw_to_dev(hw), s_rule_size, GFP_KERNEL); if (!s_rule) return -ENOMEM; s_rule->hdr.type = cpu_to_le16(ICE_AQC_SW_RULES_T_VSI_LIST_CLEAR); s_rule->index = cpu_to_le16(vsi_list_id); /* Free the vsi_list resource that we allocated. It is assumed that the * list is empty at this point. */ status = ice_aq_alloc_free_vsi_list(hw, &vsi_list_id, lkup_type, ice_aqc_opc_free_res); devm_kfree(ice_hw_to_dev(hw), s_rule); return status; } /** * ice_rem_update_vsi_list * @hw: pointer to the hardware structure * @vsi_handle: VSI handle of the VSI to remove * @fm_list: filter management entry for which the VSI list management needs to * be done */ static int ice_rem_update_vsi_list(struct ice_hw *hw, u16 vsi_handle, struct ice_fltr_mgmt_list_entry *fm_list) { enum ice_sw_lkup_type lkup_type; u16 vsi_list_id; int status = 0; if (fm_list->fltr_info.fltr_act != ICE_FWD_TO_VSI_LIST || fm_list->vsi_count == 0) return -EINVAL; /* A rule with the VSI being removed does not exist */ if (!test_bit(vsi_handle, fm_list->vsi_list_info->vsi_map)) return -ENOENT; lkup_type = fm_list->fltr_info.lkup_type; vsi_list_id = fm_list->fltr_info.fwd_id.vsi_list_id; status = ice_update_vsi_list_rule(hw, &vsi_handle, 1, vsi_list_id, true, ice_aqc_opc_update_sw_rules, lkup_type); if (status) return status; fm_list->vsi_count--; clear_bit(vsi_handle, fm_list->vsi_list_info->vsi_map); if (fm_list->vsi_count == 1 && lkup_type != ICE_SW_LKUP_VLAN) { struct ice_fltr_info tmp_fltr_info = fm_list->fltr_info; struct ice_vsi_list_map_info *vsi_list_info = fm_list->vsi_list_info; u16 rem_vsi_handle; rem_vsi_handle = find_first_bit(vsi_list_info->vsi_map, ICE_MAX_VSI); if (!ice_is_vsi_valid(hw, rem_vsi_handle)) return -EIO; /* Make sure VSI list is empty before removing it below */ status = ice_update_vsi_list_rule(hw, &rem_vsi_handle, 1, vsi_list_id, true, ice_aqc_opc_update_sw_rules, lkup_type); if (status) return status; tmp_fltr_info.fltr_act = ICE_FWD_TO_VSI; tmp_fltr_info.fwd_id.hw_vsi_id = ice_get_hw_vsi_num(hw, rem_vsi_handle); tmp_fltr_info.vsi_handle = rem_vsi_handle; status = ice_update_pkt_fwd_rule(hw, &tmp_fltr_info); if (status) { ice_debug(hw, ICE_DBG_SW, "Failed to update pkt fwd rule to FWD_TO_VSI on HW VSI %d, error %d\n", tmp_fltr_info.fwd_id.hw_vsi_id, status); return status; } fm_list->fltr_info = tmp_fltr_info; } if ((fm_list->vsi_count == 1 && lkup_type != ICE_SW_LKUP_VLAN) || (fm_list->vsi_count == 0 && lkup_type == ICE_SW_LKUP_VLAN)) { struct ice_vsi_list_map_info *vsi_list_info = fm_list->vsi_list_info; /* Remove the VSI list since it is no longer used */ status = ice_remove_vsi_list_rule(hw, vsi_list_id, lkup_type); if (status) { ice_debug(hw, ICE_DBG_SW, "Failed to remove VSI list %d, error %d\n", vsi_list_id, status); return status; } list_del(&vsi_list_info->list_entry); devm_kfree(ice_hw_to_dev(hw), vsi_list_info); fm_list->vsi_list_info = NULL; } return status; } /** * ice_remove_rule_internal - Remove a filter rule of a given type * @hw: pointer to the hardware structure * @recp_id: recipe ID for which the rule needs to removed * @f_entry: rule entry containing filter information */ static int ice_remove_rule_internal(struct ice_hw *hw, u8 recp_id, struct ice_fltr_list_entry *f_entry) { struct ice_switch_info *sw = hw->switch_info; struct ice_fltr_mgmt_list_entry *list_elem; struct mutex *rule_lock; /* Lock to protect filter rule list */ bool remove_rule = false; u16 vsi_handle; int status = 0; if (!ice_is_vsi_valid(hw, f_entry->fltr_info.vsi_handle)) return -EINVAL; f_entry->fltr_info.fwd_id.hw_vsi_id = ice_get_hw_vsi_num(hw, f_entry->fltr_info.vsi_handle); rule_lock = &sw->recp_list[recp_id].filt_rule_lock; mutex_lock(rule_lock); list_elem = ice_find_rule_entry(hw, recp_id, &f_entry->fltr_info); if (!list_elem) { status = -ENOENT; goto exit; } if (list_elem->fltr_info.fltr_act != ICE_FWD_TO_VSI_LIST) { remove_rule = true; } else if (!list_elem->vsi_list_info) { status = -ENOENT; goto exit; } else if (list_elem->vsi_list_info->ref_cnt > 1) { /* a ref_cnt > 1 indicates that the vsi_list is being * shared by multiple rules. Decrement the ref_cnt and * remove this rule, but do not modify the list, as it * is in-use by other rules. */ list_elem->vsi_list_info->ref_cnt--; remove_rule = true; } else { /* a ref_cnt of 1 indicates the vsi_list is only used * by one rule. However, the original removal request is only * for a single VSI. Update the vsi_list first, and only * remove the rule if there are no further VSIs in this list. */ vsi_handle = f_entry->fltr_info.vsi_handle; status = ice_rem_update_vsi_list(hw, vsi_handle, list_elem); if (status) goto exit; /* if VSI count goes to zero after updating the VSI list */ if (list_elem->vsi_count == 0) remove_rule = true; } if (remove_rule) { /* Remove the lookup rule */ struct ice_sw_rule_lkup_rx_tx *s_rule; s_rule = devm_kzalloc(ice_hw_to_dev(hw), ICE_SW_RULE_RX_TX_NO_HDR_SIZE(s_rule), GFP_KERNEL); if (!s_rule) { status = -ENOMEM; goto exit; } ice_fill_sw_rule(hw, &list_elem->fltr_info, s_rule, ice_aqc_opc_remove_sw_rules); status = ice_aq_sw_rules(hw, s_rule, ICE_SW_RULE_RX_TX_NO_HDR_SIZE(s_rule), 1, ice_aqc_opc_remove_sw_rules, NULL); /* Remove a book keeping from the list */ devm_kfree(ice_hw_to_dev(hw), s_rule); if (status) goto exit; list_del(&list_elem->list_entry); devm_kfree(ice_hw_to_dev(hw), list_elem); } exit: mutex_unlock(rule_lock); return status; } /** * ice_vlan_fltr_exist - does this VLAN filter exist for given VSI * @hw: pointer to the hardware structure * @vlan_id: VLAN ID * @vsi_handle: check MAC filter for this VSI */ bool ice_vlan_fltr_exist(struct ice_hw *hw, u16 vlan_id, u16 vsi_handle) { struct ice_fltr_mgmt_list_entry *entry; struct list_head *rule_head; struct ice_switch_info *sw; struct mutex *rule_lock; /* Lock to protect filter rule list */ u16 hw_vsi_id; if (vlan_id > ICE_MAX_VLAN_ID) return false; if (!ice_is_vsi_valid(hw, vsi_handle)) return false; hw_vsi_id = ice_get_hw_vsi_num(hw, vsi_handle); sw = hw->switch_info; rule_head = &sw->recp_list[ICE_SW_LKUP_VLAN].filt_rules; if (!rule_head) return false; rule_lock = &sw->recp_list[ICE_SW_LKUP_VLAN].filt_rule_lock; mutex_lock(rule_lock); list_for_each_entry(entry, rule_head, list_entry) { struct ice_fltr_info *f_info = &entry->fltr_info; u16 entry_vlan_id = f_info->l_data.vlan.vlan_id; struct ice_vsi_list_map_info *map_info; if (entry_vlan_id > ICE_MAX_VLAN_ID) continue; if (f_info->flag != ICE_FLTR_TX || f_info->src_id != ICE_SRC_ID_VSI || f_info->lkup_type != ICE_SW_LKUP_VLAN) continue; /* Only allowed filter action are FWD_TO_VSI/_VSI_LIST */ if (f_info->fltr_act != ICE_FWD_TO_VSI && f_info->fltr_act != ICE_FWD_TO_VSI_LIST) continue; if (f_info->fltr_act == ICE_FWD_TO_VSI) { if (hw_vsi_id != f_info->fwd_id.hw_vsi_id) continue; } else if (f_info->fltr_act == ICE_FWD_TO_VSI_LIST) { /* If filter_action is FWD_TO_VSI_LIST, make sure * that VSI being checked is part of VSI list */ if (entry->vsi_count == 1 && entry->vsi_list_info) { map_info = entry->vsi_list_info; if (!test_bit(vsi_handle, map_info->vsi_map)) continue; } } if (vlan_id == entry_vlan_id) { mutex_unlock(rule_lock); return true; } } mutex_unlock(rule_lock); return false; } /** * ice_add_mac - Add a MAC address based filter rule * @hw: pointer to the hardware structure * @m_list: list of MAC addresses and forwarding information */ int ice_add_mac(struct ice_hw *hw, struct list_head *m_list) { struct ice_fltr_list_entry *m_list_itr; int status = 0; if (!m_list || !hw) return -EINVAL; list_for_each_entry(m_list_itr, m_list, list_entry) { u8 *add = &m_list_itr->fltr_info.l_data.mac.mac_addr[0]; u16 vsi_handle; u16 hw_vsi_id; m_list_itr->fltr_info.flag = ICE_FLTR_TX; vsi_handle = m_list_itr->fltr_info.vsi_handle; if (!ice_is_vsi_valid(hw, vsi_handle)) return -EINVAL; hw_vsi_id = ice_get_hw_vsi_num(hw, vsi_handle); m_list_itr->fltr_info.fwd_id.hw_vsi_id = hw_vsi_id; /* update the src in case it is VSI num */ if (m_list_itr->fltr_info.src_id != ICE_SRC_ID_VSI) return -EINVAL; m_list_itr->fltr_info.src = hw_vsi_id; if (m_list_itr->fltr_info.lkup_type != ICE_SW_LKUP_MAC || is_zero_ether_addr(add)) return -EINVAL; m_list_itr->status = ice_add_rule_internal(hw, ICE_SW_LKUP_MAC, m_list_itr); if (m_list_itr->status) return m_list_itr->status; } return status; } /** * ice_add_vlan_internal - Add one VLAN based filter rule * @hw: pointer to the hardware structure * @f_entry: filter entry containing one VLAN information */ static int ice_add_vlan_internal(struct ice_hw *hw, struct ice_fltr_list_entry *f_entry) { struct ice_switch_info *sw = hw->switch_info; struct ice_fltr_mgmt_list_entry *v_list_itr; struct ice_fltr_info *new_fltr, *cur_fltr; enum ice_sw_lkup_type lkup_type; u16 vsi_list_id = 0, vsi_handle; struct mutex *rule_lock; /* Lock to protect filter rule list */ int status = 0; if (!ice_is_vsi_valid(hw, f_entry->fltr_info.vsi_handle)) return -EINVAL; f_entry->fltr_info.fwd_id.hw_vsi_id = ice_get_hw_vsi_num(hw, f_entry->fltr_info.vsi_handle); new_fltr = &f_entry->fltr_info; /* VLAN ID should only be 12 bits */ if (new_fltr->l_data.vlan.vlan_id > ICE_MAX_VLAN_ID) return -EINVAL; if (new_fltr->src_id != ICE_SRC_ID_VSI) return -EINVAL; new_fltr->src = new_fltr->fwd_id.hw_vsi_id; lkup_type = new_fltr->lkup_type; vsi_handle = new_fltr->vsi_handle; rule_lock = &sw->recp_list[ICE_SW_LKUP_VLAN].filt_rule_lock; mutex_lock(rule_lock); v_list_itr = ice_find_rule_entry(hw, ICE_SW_LKUP_VLAN, new_fltr); if (!v_list_itr) { struct ice_vsi_list_map_info *map_info = NULL; if (new_fltr->fltr_act == ICE_FWD_TO_VSI) { /* All VLAN pruning rules use a VSI list. Check if * there is already a VSI list containing VSI that we * want to add. If found, use the same vsi_list_id for * this new VLAN rule or else create a new list. */ map_info = ice_find_vsi_list_entry(hw, ICE_SW_LKUP_VLAN, vsi_handle, &vsi_list_id); if (!map_info) { status = ice_create_vsi_list_rule(hw, &vsi_handle, 1, &vsi_list_id, lkup_type); if (status) goto exit; } /* Convert the action to forwarding to a VSI list. */ new_fltr->fltr_act = ICE_FWD_TO_VSI_LIST; new_fltr->fwd_id.vsi_list_id = vsi_list_id; } status = ice_create_pkt_fwd_rule(hw, f_entry); if (!status) { v_list_itr = ice_find_rule_entry(hw, ICE_SW_LKUP_VLAN, new_fltr); if (!v_list_itr) { status = -ENOENT; goto exit; } /* reuse VSI list for new rule and increment ref_cnt */ if (map_info) { v_list_itr->vsi_list_info = map_info; map_info->ref_cnt++; } else { v_list_itr->vsi_list_info = ice_create_vsi_list_map(hw, &vsi_handle, 1, vsi_list_id); } } } else if (v_list_itr->vsi_list_info->ref_cnt == 1) { /* Update existing VSI list to add new VSI ID only if it used * by one VLAN rule. */ cur_fltr = &v_list_itr->fltr_info; status = ice_add_update_vsi_list(hw, v_list_itr, cur_fltr, new_fltr); } else { /* If VLAN rule exists and VSI list being used by this rule is * referenced by more than 1 VLAN rule. Then create a new VSI * list appending previous VSI with new VSI and update existing * VLAN rule to point to new VSI list ID */ struct ice_fltr_info tmp_fltr; u16 vsi_handle_arr[2]; u16 cur_handle; /* Current implementation only supports reusing VSI list with * one VSI count. We should never hit below condition */ if (v_list_itr->vsi_count > 1 && v_list_itr->vsi_list_info->ref_cnt > 1) { ice_debug(hw, ICE_DBG_SW, "Invalid configuration: Optimization to reuse VSI list with more than one VSI is not being done yet\n"); status = -EIO; goto exit; } cur_handle = find_first_bit(v_list_itr->vsi_list_info->vsi_map, ICE_MAX_VSI); /* A rule already exists with the new VSI being added */ if (cur_handle == vsi_handle) { status = -EEXIST; goto exit; } vsi_handle_arr[0] = cur_handle; vsi_handle_arr[1] = vsi_handle; status = ice_create_vsi_list_rule(hw, &vsi_handle_arr[0], 2, &vsi_list_id, lkup_type); if (status) goto exit; tmp_fltr = v_list_itr->fltr_info; tmp_fltr.fltr_rule_id = v_list_itr->fltr_info.fltr_rule_id; tmp_fltr.fwd_id.vsi_list_id = vsi_list_id; tmp_fltr.fltr_act = ICE_FWD_TO_VSI_LIST; /* Update the previous switch rule to a new VSI list which * includes current VSI that is requested */ status = ice_update_pkt_fwd_rule(hw, &tmp_fltr); if (status) goto exit; /* before overriding VSI list map info. decrement ref_cnt of * previous VSI list */ v_list_itr->vsi_list_info->ref_cnt--; /* now update to newly created list */ v_list_itr->fltr_info.fwd_id.vsi_list_id = vsi_list_id; v_list_itr->vsi_list_info = ice_create_vsi_list_map(hw, &vsi_handle_arr[0], 2, vsi_list_id); v_list_itr->vsi_count++; } exit: mutex_unlock(rule_lock); return status; } /** * ice_add_vlan - Add VLAN based filter rule * @hw: pointer to the hardware structure * @v_list: list of VLAN entries and forwarding information */ int ice_add_vlan(struct ice_hw *hw, struct list_head *v_list) { struct ice_fltr_list_entry *v_list_itr; if (!v_list || !hw) return -EINVAL; list_for_each_entry(v_list_itr, v_list, list_entry) { if (v_list_itr->fltr_info.lkup_type != ICE_SW_LKUP_VLAN) return -EINVAL; v_list_itr->fltr_info.flag = ICE_FLTR_TX; v_list_itr->status = ice_add_vlan_internal(hw, v_list_itr); if (v_list_itr->status) return v_list_itr->status; } return 0; } /** * ice_add_eth_mac - Add ethertype and MAC based filter rule * @hw: pointer to the hardware structure * @em_list: list of ether type MAC filter, MAC is optional * * This function requires the caller to populate the entries in * the filter list with the necessary fields (including flags to * indicate Tx or Rx rules). */ int ice_add_eth_mac(struct ice_hw *hw, struct list_head *em_list) { struct ice_fltr_list_entry *em_list_itr; if (!em_list || !hw) return -EINVAL; list_for_each_entry(em_list_itr, em_list, list_entry) { enum ice_sw_lkup_type l_type = em_list_itr->fltr_info.lkup_type; if (l_type != ICE_SW_LKUP_ETHERTYPE_MAC && l_type != ICE_SW_LKUP_ETHERTYPE) return -EINVAL; em_list_itr->status = ice_add_rule_internal(hw, l_type, em_list_itr); if (em_list_itr->status) return em_list_itr->status; } return 0; } /** * ice_remove_eth_mac - Remove an ethertype (or MAC) based filter rule * @hw: pointer to the hardware structure * @em_list: list of ethertype or ethertype MAC entries */ int ice_remove_eth_mac(struct ice_hw *hw, struct list_head *em_list) { struct ice_fltr_list_entry *em_list_itr, *tmp; if (!em_list || !hw) return -EINVAL; list_for_each_entry_safe(em_list_itr, tmp, em_list, list_entry) { enum ice_sw_lkup_type l_type = em_list_itr->fltr_info.lkup_type; if (l_type != ICE_SW_LKUP_ETHERTYPE_MAC && l_type != ICE_SW_LKUP_ETHERTYPE) return -EINVAL; em_list_itr->status = ice_remove_rule_internal(hw, l_type, em_list_itr); if (em_list_itr->status) return em_list_itr->status; } return 0; } /** * ice_rem_sw_rule_info * @hw: pointer to the hardware structure * @rule_head: pointer to the switch list structure that we want to delete */ static void ice_rem_sw_rule_info(struct ice_hw *hw, struct list_head *rule_head) { if (!list_empty(rule_head)) { struct ice_fltr_mgmt_list_entry *entry; struct ice_fltr_mgmt_list_entry *tmp; list_for_each_entry_safe(entry, tmp, rule_head, list_entry) { list_del(&entry->list_entry); devm_kfree(ice_hw_to_dev(hw), entry); } } } /** * ice_rem_adv_rule_info * @hw: pointer to the hardware structure * @rule_head: pointer to the switch list structure that we want to delete */ static void ice_rem_adv_rule_info(struct ice_hw *hw, struct list_head *rule_head) { struct ice_adv_fltr_mgmt_list_entry *tmp_entry; struct ice_adv_fltr_mgmt_list_entry *lst_itr; if (list_empty(rule_head)) return; list_for_each_entry_safe(lst_itr, tmp_entry, rule_head, list_entry) { list_del(&lst_itr->list_entry); devm_kfree(ice_hw_to_dev(hw), lst_itr->lkups); devm_kfree(ice_hw_to_dev(hw), lst_itr); } } /** * ice_cfg_dflt_vsi - change state of VSI to set/clear default * @pi: pointer to the port_info structure * @vsi_handle: VSI handle to set as default * @set: true to add the above mentioned switch rule, false to remove it * @direction: ICE_FLTR_RX or ICE_FLTR_TX * * add filter rule to set/unset given VSI as default VSI for the switch * (represented by swid) */ int ice_cfg_dflt_vsi(struct ice_port_info *pi, u16 vsi_handle, bool set, u8 direction) { struct ice_fltr_list_entry f_list_entry; struct ice_fltr_info f_info; struct ice_hw *hw = pi->hw; u16 hw_vsi_id; int status; if (!ice_is_vsi_valid(hw, vsi_handle)) return -EINVAL; hw_vsi_id = ice_get_hw_vsi_num(hw, vsi_handle); memset(&f_info, 0, sizeof(f_info)); f_info.lkup_type = ICE_SW_LKUP_DFLT; f_info.flag = direction; f_info.fltr_act = ICE_FWD_TO_VSI; f_info.fwd_id.hw_vsi_id = hw_vsi_id; f_info.vsi_handle = vsi_handle; if (f_info.flag & ICE_FLTR_RX) { f_info.src = hw->port_info->lport; f_info.src_id = ICE_SRC_ID_LPORT; } else if (f_info.flag & ICE_FLTR_TX) { f_info.src_id = ICE_SRC_ID_VSI; f_info.src = hw_vsi_id; } f_list_entry.fltr_info = f_info; if (set) status = ice_add_rule_internal(hw, ICE_SW_LKUP_DFLT, &f_list_entry); else status = ice_remove_rule_internal(hw, ICE_SW_LKUP_DFLT, &f_list_entry); return status; } /** * ice_vsi_uses_fltr - Determine if given VSI uses specified filter * @fm_entry: filter entry to inspect * @vsi_handle: VSI handle to compare with filter info */ static bool ice_vsi_uses_fltr(struct ice_fltr_mgmt_list_entry *fm_entry, u16 vsi_handle) { return ((fm_entry->fltr_info.fltr_act == ICE_FWD_TO_VSI && fm_entry->fltr_info.vsi_handle == vsi_handle) || (fm_entry->fltr_info.fltr_act == ICE_FWD_TO_VSI_LIST && fm_entry->vsi_list_info && (test_bit(vsi_handle, fm_entry->vsi_list_info->vsi_map)))); } /** * ice_check_if_dflt_vsi - check if VSI is default VSI * @pi: pointer to the port_info structure * @vsi_handle: vsi handle to check for in filter list * @rule_exists: indicates if there are any VSI's in the rule list * * checks if the VSI is in a default VSI list, and also indicates * if the default VSI list is empty */ bool ice_check_if_dflt_vsi(struct ice_port_info *pi, u16 vsi_handle, bool *rule_exists) { struct ice_fltr_mgmt_list_entry *fm_entry; struct ice_sw_recipe *recp_list; struct list_head *rule_head; struct mutex *rule_lock; /* Lock to protect filter rule list */ bool ret = false; recp_list = &pi->hw->switch_info->recp_list[ICE_SW_LKUP_DFLT]; rule_lock = &recp_list->filt_rule_lock; rule_head = &recp_list->filt_rules; mutex_lock(rule_lock); if (rule_exists && !list_empty(rule_head)) *rule_exists = true; list_for_each_entry(fm_entry, rule_head, list_entry) { if (ice_vsi_uses_fltr(fm_entry, vsi_handle)) { ret = true; break; } } mutex_unlock(rule_lock); return ret; } /** * ice_remove_mac - remove a MAC address based filter rule * @hw: pointer to the hardware structure * @m_list: list of MAC addresses and forwarding information * * This function removes either a MAC filter rule or a specific VSI from a * VSI list for a multicast MAC address. * * Returns -ENOENT if a given entry was not added by ice_add_mac. Caller should * be aware that this call will only work if all the entries passed into m_list * were added previously. It will not attempt to do a partial remove of entries * that were found. */ int ice_remove_mac(struct ice_hw *hw, struct list_head *m_list) { struct ice_fltr_list_entry *list_itr, *tmp; if (!m_list) return -EINVAL; list_for_each_entry_safe(list_itr, tmp, m_list, list_entry) { enum ice_sw_lkup_type l_type = list_itr->fltr_info.lkup_type; u16 vsi_handle; if (l_type != ICE_SW_LKUP_MAC) return -EINVAL; vsi_handle = list_itr->fltr_info.vsi_handle; if (!ice_is_vsi_valid(hw, vsi_handle)) return -EINVAL; list_itr->fltr_info.fwd_id.hw_vsi_id = ice_get_hw_vsi_num(hw, vsi_handle); list_itr->status = ice_remove_rule_internal(hw, ICE_SW_LKUP_MAC, list_itr); if (list_itr->status) return list_itr->status; } return 0; } /** * ice_remove_vlan - Remove VLAN based filter rule * @hw: pointer to the hardware structure * @v_list: list of VLAN entries and forwarding information */ int ice_remove_vlan(struct ice_hw *hw, struct list_head *v_list) { struct ice_fltr_list_entry *v_list_itr, *tmp; if (!v_list || !hw) return -EINVAL; list_for_each_entry_safe(v_list_itr, tmp, v_list, list_entry) { enum ice_sw_lkup_type l_type = v_list_itr->fltr_info.lkup_type; if (l_type != ICE_SW_LKUP_VLAN) return -EINVAL; v_list_itr->status = ice_remove_rule_internal(hw, ICE_SW_LKUP_VLAN, v_list_itr); if (v_list_itr->status) return v_list_itr->status; } return 0; } /** * ice_add_entry_to_vsi_fltr_list - Add copy of fltr_list_entry to remove list * @hw: pointer to the hardware structure * @vsi_handle: VSI handle to remove filters from * @vsi_list_head: pointer to the list to add entry to * @fi: pointer to fltr_info of filter entry to copy & add * * Helper function, used when creating a list of filters to remove from * a specific VSI. The entry added to vsi_list_head is a COPY of the * original filter entry, with the exception of fltr_info.fltr_act and * fltr_info.fwd_id fields. These are set such that later logic can * extract which VSI to remove the fltr from, and pass on that information. */ static int ice_add_entry_to_vsi_fltr_list(struct ice_hw *hw, u16 vsi_handle, struct list_head *vsi_list_head, struct ice_fltr_info *fi) { struct ice_fltr_list_entry *tmp; /* this memory is freed up in the caller function * once filters for this VSI are removed */ tmp = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*tmp), GFP_KERNEL); if (!tmp) return -ENOMEM; tmp->fltr_info = *fi; /* Overwrite these fields to indicate which VSI to remove filter from, * so find and remove logic can extract the information from the * list entries. Note that original entries will still have proper * values. */ tmp->fltr_info.fltr_act = ICE_FWD_TO_VSI; tmp->fltr_info.vsi_handle = vsi_handle; tmp->fltr_info.fwd_id.hw_vsi_id = ice_get_hw_vsi_num(hw, vsi_handle); list_add(&tmp->list_entry, vsi_list_head); return 0; } /** * ice_add_to_vsi_fltr_list - Add VSI filters to the list * @hw: pointer to the hardware structure * @vsi_handle: VSI handle to remove filters from * @lkup_list_head: pointer to the list that has certain lookup type filters * @vsi_list_head: pointer to the list pertaining to VSI with vsi_handle * * Locates all filters in lkup_list_head that are used by the given VSI, * and adds COPIES of those entries to vsi_list_head (intended to be used * to remove the listed filters). * Note that this means all entries in vsi_list_head must be explicitly * deallocated by the caller when done with list. */ static int ice_add_to_vsi_fltr_list(struct ice_hw *hw, u16 vsi_handle, struct list_head *lkup_list_head, struct list_head *vsi_list_head) { struct ice_fltr_mgmt_list_entry *fm_entry; int status = 0; /* check to make sure VSI ID is valid and within boundary */ if (!ice_is_vsi_valid(hw, vsi_handle)) return -EINVAL; list_for_each_entry(fm_entry, lkup_list_head, list_entry) { if (!ice_vsi_uses_fltr(fm_entry, vsi_handle)) continue; status = ice_add_entry_to_vsi_fltr_list(hw, vsi_handle, vsi_list_head, &fm_entry->fltr_info); if (status) return status; } return status; } /** * ice_determine_promisc_mask * @fi: filter info to parse * * Helper function to determine which ICE_PROMISC_ mask corresponds * to given filter into. */ static u8 ice_determine_promisc_mask(struct ice_fltr_info *fi) { u16 vid = fi->l_data.mac_vlan.vlan_id; u8 *macaddr = fi->l_data.mac.mac_addr; bool is_tx_fltr = false; u8 promisc_mask = 0; if (fi->flag == ICE_FLTR_TX) is_tx_fltr = true; if (is_broadcast_ether_addr(macaddr)) promisc_mask |= is_tx_fltr ? ICE_PROMISC_BCAST_TX : ICE_PROMISC_BCAST_RX; else if (is_multicast_ether_addr(macaddr)) promisc_mask |= is_tx_fltr ? ICE_PROMISC_MCAST_TX : ICE_PROMISC_MCAST_RX; else if (is_unicast_ether_addr(macaddr)) promisc_mask |= is_tx_fltr ? ICE_PROMISC_UCAST_TX : ICE_PROMISC_UCAST_RX; if (vid) promisc_mask |= is_tx_fltr ? ICE_PROMISC_VLAN_TX : ICE_PROMISC_VLAN_RX; return promisc_mask; } /** * ice_remove_promisc - Remove promisc based filter rules * @hw: pointer to the hardware structure * @recp_id: recipe ID for which the rule needs to removed * @v_list: list of promisc entries */ static int ice_remove_promisc(struct ice_hw *hw, u8 recp_id, struct list_head *v_list) { struct ice_fltr_list_entry *v_list_itr, *tmp; list_for_each_entry_safe(v_list_itr, tmp, v_list, list_entry) { v_list_itr->status = ice_remove_rule_internal(hw, recp_id, v_list_itr); if (v_list_itr->status) return v_list_itr->status; } return 0; } /** * ice_clear_vsi_promisc - clear specified promiscuous mode(s) for given VSI * @hw: pointer to the hardware structure * @vsi_handle: VSI handle to clear mode * @promisc_mask: mask of promiscuous config bits to clear * @vid: VLAN ID to clear VLAN promiscuous */ int ice_clear_vsi_promisc(struct ice_hw *hw, u16 vsi_handle, u8 promisc_mask, u16 vid) { struct ice_switch_info *sw = hw->switch_info; struct ice_fltr_list_entry *fm_entry, *tmp; struct list_head remove_list_head; struct ice_fltr_mgmt_list_entry *itr; struct list_head *rule_head; struct mutex *rule_lock; /* Lock to protect filter rule list */ int status = 0; u8 recipe_id; if (!ice_is_vsi_valid(hw, vsi_handle)) return -EINVAL; if (promisc_mask & (ICE_PROMISC_VLAN_RX | ICE_PROMISC_VLAN_TX)) recipe_id = ICE_SW_LKUP_PROMISC_VLAN; else recipe_id = ICE_SW_LKUP_PROMISC; rule_head = &sw->recp_list[recipe_id].filt_rules; rule_lock = &sw->recp_list[recipe_id].filt_rule_lock; INIT_LIST_HEAD(&remove_list_head); mutex_lock(rule_lock); list_for_each_entry(itr, rule_head, list_entry) { struct ice_fltr_info *fltr_info; u8 fltr_promisc_mask = 0; if (!ice_vsi_uses_fltr(itr, vsi_handle)) continue; fltr_info = &itr->fltr_info; if (recipe_id == ICE_SW_LKUP_PROMISC_VLAN && vid != fltr_info->l_data.mac_vlan.vlan_id) continue; fltr_promisc_mask |= ice_determine_promisc_mask(fltr_info); /* Skip if filter is not completely specified by given mask */ if (fltr_promisc_mask & ~promisc_mask) continue; status = ice_add_entry_to_vsi_fltr_list(hw, vsi_handle, &remove_list_head, fltr_info); if (status) { mutex_unlock(rule_lock); goto free_fltr_list; } } mutex_unlock(rule_lock); status = ice_remove_promisc(hw, recipe_id, &remove_list_head); free_fltr_list: list_for_each_entry_safe(fm_entry, tmp, &remove_list_head, list_entry) { list_del(&fm_entry->list_entry); devm_kfree(ice_hw_to_dev(hw), fm_entry); } return status; } /** * ice_set_vsi_promisc - set given VSI to given promiscuous mode(s) * @hw: pointer to the hardware structure * @vsi_handle: VSI handle to configure * @promisc_mask: mask of promiscuous config bits * @vid: VLAN ID to set VLAN promiscuous */ int ice_set_vsi_promisc(struct ice_hw *hw, u16 vsi_handle, u8 promisc_mask, u16 vid) { enum { UCAST_FLTR = 1, MCAST_FLTR, BCAST_FLTR }; struct ice_fltr_list_entry f_list_entry; struct ice_fltr_info new_fltr; bool is_tx_fltr; int status = 0; u16 hw_vsi_id; int pkt_type; u8 recipe_id; if (!ice_is_vsi_valid(hw, vsi_handle)) return -EINVAL; hw_vsi_id = ice_get_hw_vsi_num(hw, vsi_handle); memset(&new_fltr, 0, sizeof(new_fltr)); if (promisc_mask & (ICE_PROMISC_VLAN_RX | ICE_PROMISC_VLAN_TX)) { new_fltr.lkup_type = ICE_SW_LKUP_PROMISC_VLAN; new_fltr.l_data.mac_vlan.vlan_id = vid; recipe_id = ICE_SW_LKUP_PROMISC_VLAN; } else { new_fltr.lkup_type = ICE_SW_LKUP_PROMISC; recipe_id = ICE_SW_LKUP_PROMISC; } /* Separate filters must be set for each direction/packet type * combination, so we will loop over the mask value, store the * individual type, and clear it out in the input mask as it * is found. */ while (promisc_mask) { u8 *mac_addr; pkt_type = 0; is_tx_fltr = false; if (promisc_mask & ICE_PROMISC_UCAST_RX) { promisc_mask &= ~ICE_PROMISC_UCAST_RX; pkt_type = UCAST_FLTR; } else if (promisc_mask & ICE_PROMISC_UCAST_TX) { promisc_mask &= ~ICE_PROMISC_UCAST_TX; pkt_type = UCAST_FLTR; is_tx_fltr = true; } else if (promisc_mask & ICE_PROMISC_MCAST_RX) { promisc_mask &= ~ICE_PROMISC_MCAST_RX; pkt_type = MCAST_FLTR; } else if (promisc_mask & ICE_PROMISC_MCAST_TX) { promisc_mask &= ~ICE_PROMISC_MCAST_TX; pkt_type = MCAST_FLTR; is_tx_fltr = true; } else if (promisc_mask & ICE_PROMISC_BCAST_RX) { promisc_mask &= ~ICE_PROMISC_BCAST_RX; pkt_type = BCAST_FLTR; } else if (promisc_mask & ICE_PROMISC_BCAST_TX) { promisc_mask &= ~ICE_PROMISC_BCAST_TX; pkt_type = BCAST_FLTR; is_tx_fltr = true; } /* Check for VLAN promiscuous flag */ if (promisc_mask & ICE_PROMISC_VLAN_RX) { promisc_mask &= ~ICE_PROMISC_VLAN_RX; } else if (promisc_mask & ICE_PROMISC_VLAN_TX) { promisc_mask &= ~ICE_PROMISC_VLAN_TX; is_tx_fltr = true; } /* Set filter DA based on packet type */ mac_addr = new_fltr.l_data.mac.mac_addr; if (pkt_type == BCAST_FLTR) { eth_broadcast_addr(mac_addr); } else if (pkt_type == MCAST_FLTR || pkt_type == UCAST_FLTR) { /* Use the dummy ether header DA */ ether_addr_copy(mac_addr, dummy_eth_header); if (pkt_type == MCAST_FLTR) mac_addr[0] |= 0x1; /* Set multicast bit */ } /* Need to reset this to zero for all iterations */ new_fltr.flag = 0; if (is_tx_fltr) { new_fltr.flag |= ICE_FLTR_TX; new_fltr.src = hw_vsi_id; } else { new_fltr.flag |= ICE_FLTR_RX; new_fltr.src = hw->port_info->lport; } new_fltr.fltr_act = ICE_FWD_TO_VSI; new_fltr.vsi_handle = vsi_handle; new_fltr.fwd_id.hw_vsi_id = hw_vsi_id; f_list_entry.fltr_info = new_fltr; status = ice_add_rule_internal(hw, recipe_id, &f_list_entry); if (status) goto set_promisc_exit; } set_promisc_exit: return status; } /** * ice_set_vlan_vsi_promisc * @hw: pointer to the hardware structure * @vsi_handle: VSI handle to configure * @promisc_mask: mask of promiscuous config bits * @rm_vlan_promisc: Clear VLANs VSI promisc mode * * Configure VSI with all associated VLANs to given promiscuous mode(s) */ int ice_set_vlan_vsi_promisc(struct ice_hw *hw, u16 vsi_handle, u8 promisc_mask, bool rm_vlan_promisc) { struct ice_switch_info *sw = hw->switch_info; struct ice_fltr_list_entry *list_itr, *tmp; struct list_head vsi_list_head; struct list_head *vlan_head; struct mutex *vlan_lock; /* Lock to protect filter rule list */ u16 vlan_id; int status; INIT_LIST_HEAD(&vsi_list_head); vlan_lock = &sw->recp_list[ICE_SW_LKUP_VLAN].filt_rule_lock; vlan_head = &sw->recp_list[ICE_SW_LKUP_VLAN].filt_rules; mutex_lock(vlan_lock); status = ice_add_to_vsi_fltr_list(hw, vsi_handle, vlan_head, &vsi_list_head); mutex_unlock(vlan_lock); if (status) goto free_fltr_list; list_for_each_entry(list_itr, &vsi_list_head, list_entry) { /* Avoid enabling or disabling VLAN zero twice when in double * VLAN mode */ if (ice_is_dvm_ena(hw) && list_itr->fltr_info.l_data.vlan.tpid == 0) continue; vlan_id = list_itr->fltr_info.l_data.vlan.vlan_id; if (rm_vlan_promisc) status = ice_clear_vsi_promisc(hw, vsi_handle, promisc_mask, vlan_id); else status = ice_set_vsi_promisc(hw, vsi_handle, promisc_mask, vlan_id); if (status && status != -EEXIST) break; } free_fltr_list: list_for_each_entry_safe(list_itr, tmp, &vsi_list_head, list_entry) { list_del(&list_itr->list_entry); devm_kfree(ice_hw_to_dev(hw), list_itr); } return status; } /** * ice_remove_vsi_lkup_fltr - Remove lookup type filters for a VSI * @hw: pointer to the hardware structure * @vsi_handle: VSI handle to remove filters from * @lkup: switch rule filter lookup type */ static void ice_remove_vsi_lkup_fltr(struct ice_hw *hw, u16 vsi_handle, enum ice_sw_lkup_type lkup) { struct ice_switch_info *sw = hw->switch_info; struct ice_fltr_list_entry *fm_entry; struct list_head remove_list_head; struct list_head *rule_head; struct ice_fltr_list_entry *tmp; struct mutex *rule_lock; /* Lock to protect filter rule list */ int status; INIT_LIST_HEAD(&remove_list_head); rule_lock = &sw->recp_list[lkup].filt_rule_lock; rule_head = &sw->recp_list[lkup].filt_rules; mutex_lock(rule_lock); status = ice_add_to_vsi_fltr_list(hw, vsi_handle, rule_head, &remove_list_head); mutex_unlock(rule_lock); if (status) goto free_fltr_list; switch (lkup) { case ICE_SW_LKUP_MAC: ice_remove_mac(hw, &remove_list_head); break; case ICE_SW_LKUP_VLAN: ice_remove_vlan(hw, &remove_list_head); break; case ICE_SW_LKUP_PROMISC: case ICE_SW_LKUP_PROMISC_VLAN: ice_remove_promisc(hw, lkup, &remove_list_head); break; case ICE_SW_LKUP_MAC_VLAN: case ICE_SW_LKUP_ETHERTYPE: case ICE_SW_LKUP_ETHERTYPE_MAC: case ICE_SW_LKUP_DFLT: case ICE_SW_LKUP_LAST: default: ice_debug(hw, ICE_DBG_SW, "Unsupported lookup type %d\n", lkup); break; } free_fltr_list: list_for_each_entry_safe(fm_entry, tmp, &remove_list_head, list_entry) { list_del(&fm_entry->list_entry); devm_kfree(ice_hw_to_dev(hw), fm_entry); } } /** * ice_remove_vsi_fltr - Remove all filters for a VSI * @hw: pointer to the hardware structure * @vsi_handle: VSI handle to remove filters from */ void ice_remove_vsi_fltr(struct ice_hw *hw, u16 vsi_handle) { ice_remove_vsi_lkup_fltr(hw, vsi_handle, ICE_SW_LKUP_MAC); ice_remove_vsi_lkup_fltr(hw, vsi_handle, ICE_SW_LKUP_MAC_VLAN); ice_remove_vsi_lkup_fltr(hw, vsi_handle, ICE_SW_LKUP_PROMISC); ice_remove_vsi_lkup_fltr(hw, vsi_handle, ICE_SW_LKUP_VLAN); ice_remove_vsi_lkup_fltr(hw, vsi_handle, ICE_SW_LKUP_DFLT); ice_remove_vsi_lkup_fltr(hw, vsi_handle, ICE_SW_LKUP_ETHERTYPE); ice_remove_vsi_lkup_fltr(hw, vsi_handle, ICE_SW_LKUP_ETHERTYPE_MAC); ice_remove_vsi_lkup_fltr(hw, vsi_handle, ICE_SW_LKUP_PROMISC_VLAN); } /** * ice_alloc_res_cntr - allocating resource counter * @hw: pointer to the hardware structure * @type: type of resource * @alloc_shared: if set it is shared else dedicated * @num_items: number of entries requested for FD resource type * @counter_id: counter index returned by AQ call */ int ice_alloc_res_cntr(struct ice_hw *hw, u8 type, u8 alloc_shared, u16 num_items, u16 *counter_id) { struct ice_aqc_alloc_free_res_elem *buf; u16 buf_len; int status; /* Allocate resource */ buf_len = struct_size(buf, elem, 1); buf = kzalloc(buf_len, GFP_KERNEL); if (!buf) return -ENOMEM; buf->num_elems = cpu_to_le16(num_items); buf->res_type = cpu_to_le16(((type << ICE_AQC_RES_TYPE_S) & ICE_AQC_RES_TYPE_M) | alloc_shared); status = ice_aq_alloc_free_res(hw, buf, buf_len, ice_aqc_opc_alloc_res); if (status) goto exit; *counter_id = le16_to_cpu(buf->elem[0].e.sw_resp); exit: kfree(buf); return status; } /** * ice_free_res_cntr - free resource counter * @hw: pointer to the hardware structure * @type: type of resource * @alloc_shared: if set it is shared else dedicated * @num_items: number of entries to be freed for FD resource type * @counter_id: counter ID resource which needs to be freed */ int ice_free_res_cntr(struct ice_hw *hw, u8 type, u8 alloc_shared, u16 num_items, u16 counter_id) { struct ice_aqc_alloc_free_res_elem *buf; u16 buf_len; int status; /* Free resource */ buf_len = struct_size(buf, elem, 1); buf = kzalloc(buf_len, GFP_KERNEL); if (!buf) return -ENOMEM; buf->num_elems = cpu_to_le16(num_items); buf->res_type = cpu_to_le16(((type << ICE_AQC_RES_TYPE_S) & ICE_AQC_RES_TYPE_M) | alloc_shared); buf->elem[0].e.sw_resp = cpu_to_le16(counter_id); status = ice_aq_alloc_free_res(hw, buf, buf_len, ice_aqc_opc_free_res); if (status) ice_debug(hw, ICE_DBG_SW, "counter resource could not be freed\n"); kfree(buf); return status; } #define ICE_PROTOCOL_ENTRY(id, ...) { \ .prot_type = id, \ .offs = {__VA_ARGS__}, \ } /** * ice_share_res - set a resource as shared or dedicated * @hw: hw struct of original owner of resource * @type: resource type * @shared: is the resource being set to shared * @res_id: resource id (descriptor) */ int ice_share_res(struct ice_hw *hw, u16 type, u8 shared, u16 res_id) { struct ice_aqc_alloc_free_res_elem *buf; u16 buf_len; int status; buf_len = struct_size(buf, elem, 1); buf = kzalloc(buf_len, GFP_KERNEL); if (!buf) return -ENOMEM; buf->num_elems = cpu_to_le16(1); if (shared) buf->res_type = cpu_to_le16(((type << ICE_AQC_RES_TYPE_S) & ICE_AQC_RES_TYPE_M) | ICE_AQC_RES_TYPE_FLAG_SHARED); else buf->res_type = cpu_to_le16(((type << ICE_AQC_RES_TYPE_S) & ICE_AQC_RES_TYPE_M) & ~ICE_AQC_RES_TYPE_FLAG_SHARED); buf->elem[0].e.sw_resp = cpu_to_le16(res_id); status = ice_aq_alloc_free_res(hw, buf, buf_len, ice_aqc_opc_share_res); if (status) ice_debug(hw, ICE_DBG_SW, "Could not set resource type %u id %u to %s\n", type, res_id, shared ? "SHARED" : "DEDICATED"); kfree(buf); return status; } /* This is mapping table entry that maps every word within a given protocol * structure to the real byte offset as per the specification of that * protocol header. * for example dst address is 3 words in ethertype header and corresponding * bytes are 0, 2, 3 in the actual packet header and src address is at 4, 6, 8 * IMPORTANT: Every structure part of "ice_prot_hdr" union should have a * matching entry describing its field. This needs to be updated if new * structure is added to that union. */ static const struct ice_prot_ext_tbl_entry ice_prot_ext[ICE_PROTOCOL_LAST] = { ICE_PROTOCOL_ENTRY(ICE_MAC_OFOS, 0, 2, 4, 6, 8, 10, 12), ICE_PROTOCOL_ENTRY(ICE_MAC_IL, 0, 2, 4, 6, 8, 10, 12), ICE_PROTOCOL_ENTRY(ICE_ETYPE_OL, 0), ICE_PROTOCOL_ENTRY(ICE_ETYPE_IL, 0), ICE_PROTOCOL_ENTRY(ICE_VLAN_OFOS, 2, 0), ICE_PROTOCOL_ENTRY(ICE_IPV4_OFOS, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18), ICE_PROTOCOL_ENTRY(ICE_IPV4_IL, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18), ICE_PROTOCOL_ENTRY(ICE_IPV6_OFOS, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38), ICE_PROTOCOL_ENTRY(ICE_IPV6_IL, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38), ICE_PROTOCOL_ENTRY(ICE_TCP_IL, 0, 2), ICE_PROTOCOL_ENTRY(ICE_UDP_OF, 0, 2), ICE_PROTOCOL_ENTRY(ICE_UDP_ILOS, 0, 2), ICE_PROTOCOL_ENTRY(ICE_VXLAN, 8, 10, 12, 14), ICE_PROTOCOL_ENTRY(ICE_GENEVE, 8, 10, 12, 14), ICE_PROTOCOL_ENTRY(ICE_NVGRE, 0, 2, 4, 6), ICE_PROTOCOL_ENTRY(ICE_GTP, 8, 10, 12, 14, 16, 18, 20, 22), ICE_PROTOCOL_ENTRY(ICE_GTP_NO_PAY, 8, 10, 12, 14), ICE_PROTOCOL_ENTRY(ICE_PPPOE, 0, 2, 4, 6), ICE_PROTOCOL_ENTRY(ICE_L2TPV3, 0, 2, 4, 6, 8, 10), ICE_PROTOCOL_ENTRY(ICE_VLAN_EX, 2, 0), ICE_PROTOCOL_ENTRY(ICE_VLAN_IN, 2, 0), ICE_PROTOCOL_ENTRY(ICE_HW_METADATA, ICE_SOURCE_PORT_MDID_OFFSET, ICE_PTYPE_MDID_OFFSET, ICE_PACKET_LENGTH_MDID_OFFSET, ICE_SOURCE_VSI_MDID_OFFSET, ICE_PKT_VLAN_MDID_OFFSET, ICE_PKT_TUNNEL_MDID_OFFSET, ICE_PKT_TCP_MDID_OFFSET, ICE_PKT_ERROR_MDID_OFFSET), }; static struct ice_protocol_entry ice_prot_id_tbl[ICE_PROTOCOL_LAST] = { { ICE_MAC_OFOS, ICE_MAC_OFOS_HW }, { ICE_MAC_IL, ICE_MAC_IL_HW }, { ICE_ETYPE_OL, ICE_ETYPE_OL_HW }, { ICE_ETYPE_IL, ICE_ETYPE_IL_HW }, { ICE_VLAN_OFOS, ICE_VLAN_OL_HW }, { ICE_IPV4_OFOS, ICE_IPV4_OFOS_HW }, { ICE_IPV4_IL, ICE_IPV4_IL_HW }, { ICE_IPV6_OFOS, ICE_IPV6_OFOS_HW }, { ICE_IPV6_IL, ICE_IPV6_IL_HW }, { ICE_TCP_IL, ICE_TCP_IL_HW }, { ICE_UDP_OF, ICE_UDP_OF_HW }, { ICE_UDP_ILOS, ICE_UDP_ILOS_HW }, { ICE_VXLAN, ICE_UDP_OF_HW }, { ICE_GENEVE, ICE_UDP_OF_HW }, { ICE_NVGRE, ICE_GRE_OF_HW }, { ICE_GTP, ICE_UDP_OF_HW }, { ICE_GTP_NO_PAY, ICE_UDP_ILOS_HW }, { ICE_PPPOE, ICE_PPPOE_HW }, { ICE_L2TPV3, ICE_L2TPV3_HW }, { ICE_VLAN_EX, ICE_VLAN_OF_HW }, { ICE_VLAN_IN, ICE_VLAN_OL_HW }, { ICE_HW_METADATA, ICE_META_DATA_ID_HW }, }; /** * ice_find_recp - find a recipe * @hw: pointer to the hardware structure * @lkup_exts: extension sequence to match * @rinfo: information regarding the rule e.g. priority and action info * * Returns index of matching recipe, or ICE_MAX_NUM_RECIPES if not found. */ static u16 ice_find_recp(struct ice_hw *hw, struct ice_prot_lkup_ext *lkup_exts, const struct ice_adv_rule_info *rinfo) { bool refresh_required = true; struct ice_sw_recipe *recp; u8 i; /* Walk through existing recipes to find a match */ recp = hw->switch_info->recp_list; for (i = 0; i < ICE_MAX_NUM_RECIPES; i++) { /* If recipe was not created for this ID, in SW bookkeeping, * check if FW has an entry for this recipe. If the FW has an * entry update it in our SW bookkeeping and continue with the * matching. */ if (!recp[i].recp_created) if (ice_get_recp_frm_fw(hw, hw->switch_info->recp_list, i, &refresh_required)) continue; /* Skip inverse action recipes */ if (recp[i].root_buf && recp[i].root_buf->content.act_ctrl & ICE_AQ_RECIPE_ACT_INV_ACT) continue; /* if number of words we are looking for match */ if (lkup_exts->n_val_words == recp[i].lkup_exts.n_val_words) { struct ice_fv_word *ar = recp[i].lkup_exts.fv_words; struct ice_fv_word *be = lkup_exts->fv_words; u16 *cr = recp[i].lkup_exts.field_mask; u16 *de = lkup_exts->field_mask; bool found = true; u8 pe, qr; /* ar, cr, and qr are related to the recipe words, while * be, de, and pe are related to the lookup words */ for (pe = 0; pe < lkup_exts->n_val_words; pe++) { for (qr = 0; qr < recp[i].lkup_exts.n_val_words; qr++) { if (ar[qr].off == be[pe].off && ar[qr].prot_id == be[pe].prot_id && cr[qr] == de[pe]) /* Found the "pe"th word in the * given recipe */ break; } /* After walking through all the words in the * "i"th recipe if "p"th word was not found then * this recipe is not what we are looking for. * So break out from this loop and try the next * recipe */ if (qr >= recp[i].lkup_exts.n_val_words) { found = false; break; } } /* If for "i"th recipe the found was never set to false * then it means we found our match * Also tun type and *_pass_l2 of recipe needs to be * checked */ if (found && recp[i].tun_type == rinfo->tun_type && recp[i].need_pass_l2 == rinfo->need_pass_l2 && recp[i].allow_pass_l2 == rinfo->allow_pass_l2) return i; /* Return the recipe ID */ } } return ICE_MAX_NUM_RECIPES; } /** * ice_change_proto_id_to_dvm - change proto id in prot_id_tbl * * As protocol id for outer vlan is different in dvm and svm, if dvm is * supported protocol array record for outer vlan has to be modified to * reflect the value proper for DVM. */ void ice_change_proto_id_to_dvm(void) { u8 i; for (i = 0; i < ARRAY_SIZE(ice_prot_id_tbl); i++) if (ice_prot_id_tbl[i].type == ICE_VLAN_OFOS && ice_prot_id_tbl[i].protocol_id != ICE_VLAN_OF_HW) ice_prot_id_tbl[i].protocol_id = ICE_VLAN_OF_HW; } /** * ice_prot_type_to_id - get protocol ID from protocol type * @type: protocol type * @id: pointer to variable that will receive the ID * * Returns true if found, false otherwise */ static bool ice_prot_type_to_id(enum ice_protocol_type type, u8 *id) { u8 i; for (i = 0; i < ARRAY_SIZE(ice_prot_id_tbl); i++) if (ice_prot_id_tbl[i].type == type) { *id = ice_prot_id_tbl[i].protocol_id; return true; } return false; } /** * ice_fill_valid_words - count valid words * @rule: advanced rule with lookup information * @lkup_exts: byte offset extractions of the words that are valid * * calculate valid words in a lookup rule using mask value */ static u8 ice_fill_valid_words(struct ice_adv_lkup_elem *rule, struct ice_prot_lkup_ext *lkup_exts) { u8 j, word, prot_id, ret_val; if (!ice_prot_type_to_id(rule->type, &prot_id)) return 0; word = lkup_exts->n_val_words; for (j = 0; j < sizeof(rule->m_u) / sizeof(u16); j++) if (((u16 *)&rule->m_u)[j] && rule->type < ARRAY_SIZE(ice_prot_ext)) { /* No more space to accommodate */ if (word >= ICE_MAX_CHAIN_WORDS) return 0; lkup_exts->fv_words[word].off = ice_prot_ext[rule->type].offs[j]; lkup_exts->fv_words[word].prot_id = ice_prot_id_tbl[rule->type].protocol_id; lkup_exts->field_mask[word] = be16_to_cpu(((__force __be16 *)&rule->m_u)[j]); word++; } ret_val = word - lkup_exts->n_val_words; lkup_exts->n_val_words = word; return ret_val; } /** * ice_create_first_fit_recp_def - Create a recipe grouping * @hw: pointer to the hardware structure * @lkup_exts: an array of protocol header extractions * @rg_list: pointer to a list that stores new recipe groups * @recp_cnt: pointer to a variable that stores returned number of recipe groups * * Using first fit algorithm, take all the words that are still not done * and start grouping them in 4-word groups. Each group makes up one * recipe. */ static int ice_create_first_fit_recp_def(struct ice_hw *hw, struct ice_prot_lkup_ext *lkup_exts, struct list_head *rg_list, u8 *recp_cnt) { struct ice_pref_recipe_group *grp = NULL; u8 j; *recp_cnt = 0; /* Walk through every word in the rule to check if it is not done. If so * then this word needs to be part of a new recipe. */ for (j = 0; j < lkup_exts->n_val_words; j++) if (!test_bit(j, lkup_exts->done)) { if (!grp || grp->n_val_pairs == ICE_NUM_WORDS_RECIPE) { struct ice_recp_grp_entry *entry; entry = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*entry), GFP_KERNEL); if (!entry) return -ENOMEM; list_add(&entry->l_entry, rg_list); grp = &entry->r_group; (*recp_cnt)++; } grp->pairs[grp->n_val_pairs].prot_id = lkup_exts->fv_words[j].prot_id; grp->pairs[grp->n_val_pairs].off = lkup_exts->fv_words[j].off; grp->mask[grp->n_val_pairs] = lkup_exts->field_mask[j]; grp->n_val_pairs++; } return 0; } /** * ice_fill_fv_word_index - fill in the field vector indices for a recipe group * @hw: pointer to the hardware structure * @fv_list: field vector with the extraction sequence information * @rg_list: recipe groupings with protocol-offset pairs * * Helper function to fill in the field vector indices for protocol-offset * pairs. These indexes are then ultimately programmed into a recipe. */ static int ice_fill_fv_word_index(struct ice_hw *hw, struct list_head *fv_list, struct list_head *rg_list) { struct ice_sw_fv_list_entry *fv; struct ice_recp_grp_entry *rg; struct ice_fv_word *fv_ext; if (list_empty(fv_list)) return 0; fv = list_first_entry(fv_list, struct ice_sw_fv_list_entry, list_entry); fv_ext = fv->fv_ptr->ew; list_for_each_entry(rg, rg_list, l_entry) { u8 i; for (i = 0; i < rg->r_group.n_val_pairs; i++) { struct ice_fv_word *pr; bool found = false; u16 mask; u8 j; pr = &rg->r_group.pairs[i]; mask = rg->r_group.mask[i]; for (j = 0; j < hw->blk[ICE_BLK_SW].es.fvw; j++) if (fv_ext[j].prot_id == pr->prot_id && fv_ext[j].off == pr->off) { found = true; /* Store index of field vector */ rg->fv_idx[i] = j; rg->fv_mask[i] = mask; break; } /* Protocol/offset could not be found, caller gave an * invalid pair */ if (!found) return -EINVAL; } } return 0; } /** * ice_find_free_recp_res_idx - find free result indexes for recipe * @hw: pointer to hardware structure * @profiles: bitmap of profiles that will be associated with the new recipe * @free_idx: pointer to variable to receive the free index bitmap * * The algorithm used here is: * 1. When creating a new recipe, create a set P which contains all * Profiles that will be associated with our new recipe * * 2. For each Profile p in set P: * a. Add all recipes associated with Profile p into set R * b. Optional : PossibleIndexes &= profile[p].possibleIndexes * [initially PossibleIndexes should be 0xFFFFFFFFFFFFFFFF] * i. Or just assume they all have the same possible indexes: * 44, 45, 46, 47 * i.e., PossibleIndexes = 0x0000F00000000000 * * 3. For each Recipe r in set R: * a. UsedIndexes |= (bitwise or ) recipe[r].res_indexes * b. FreeIndexes = UsedIndexes ^ PossibleIndexes * * FreeIndexes will contain the bits indicating the indexes free for use, * then the code needs to update the recipe[r].used_result_idx_bits to * indicate which indexes were selected for use by this recipe. */ static u16 ice_find_free_recp_res_idx(struct ice_hw *hw, const unsigned long *profiles, unsigned long *free_idx) { DECLARE_BITMAP(possible_idx, ICE_MAX_FV_WORDS); DECLARE_BITMAP(recipes, ICE_MAX_NUM_RECIPES); DECLARE_BITMAP(used_idx, ICE_MAX_FV_WORDS); u16 bit; bitmap_zero(recipes, ICE_MAX_NUM_RECIPES); bitmap_zero(used_idx, ICE_MAX_FV_WORDS); bitmap_fill(possible_idx, ICE_MAX_FV_WORDS); /* For each profile we are going to associate the recipe with, add the * recipes that are associated with that profile. This will give us * the set of recipes that our recipe may collide with. Also, determine * what possible result indexes are usable given this set of profiles. */ for_each_set_bit(bit, profiles, ICE_MAX_NUM_PROFILES) { bitmap_or(recipes, recipes, profile_to_recipe[bit], ICE_MAX_NUM_RECIPES); bitmap_and(possible_idx, possible_idx, hw->switch_info->prof_res_bm[bit], ICE_MAX_FV_WORDS); } /* For each recipe that our new recipe may collide with, determine * which indexes have been used. */ for_each_set_bit(bit, recipes, ICE_MAX_NUM_RECIPES) bitmap_or(used_idx, used_idx, hw->switch_info->recp_list[bit].res_idxs, ICE_MAX_FV_WORDS); bitmap_xor(free_idx, used_idx, possible_idx, ICE_MAX_FV_WORDS); /* return number of free indexes */ return (u16)bitmap_weight(free_idx, ICE_MAX_FV_WORDS); } /** * ice_add_sw_recipe - function to call AQ calls to create switch recipe * @hw: pointer to hardware structure * @rm: recipe management list entry * @profiles: bitmap of profiles that will be associated. */ static int ice_add_sw_recipe(struct ice_hw *hw, struct ice_sw_recipe *rm, unsigned long *profiles) { DECLARE_BITMAP(result_idx_bm, ICE_MAX_FV_WORDS); struct ice_aqc_recipe_content *content; struct ice_aqc_recipe_data_elem *tmp; struct ice_aqc_recipe_data_elem *buf; struct ice_recp_grp_entry *entry; u16 free_res_idx; u16 recipe_count; u8 chain_idx; u8 recps = 0; int status; /* When more than one recipe are required, another recipe is needed to * chain them together. Matching a tunnel metadata ID takes up one of * the match fields in the chaining recipe reducing the number of * chained recipes by one. */ /* check number of free result indices */ bitmap_zero(result_idx_bm, ICE_MAX_FV_WORDS); free_res_idx = ice_find_free_recp_res_idx(hw, profiles, result_idx_bm); ice_debug(hw, ICE_DBG_SW, "Result idx slots: %d, need %d\n", free_res_idx, rm->n_grp_count); if (rm->n_grp_count > 1) { if (rm->n_grp_count > free_res_idx) return -ENOSPC; rm->n_grp_count++; } if (rm->n_grp_count > ICE_MAX_CHAIN_RECIPE) return -ENOSPC; tmp = kcalloc(ICE_MAX_NUM_RECIPES, sizeof(*tmp), GFP_KERNEL); if (!tmp) return -ENOMEM; buf = devm_kcalloc(ice_hw_to_dev(hw), rm->n_grp_count, sizeof(*buf), GFP_KERNEL); if (!buf) { status = -ENOMEM; goto err_mem; } bitmap_zero(rm->r_bitmap, ICE_MAX_NUM_RECIPES); recipe_count = ICE_MAX_NUM_RECIPES; status = ice_aq_get_recipe(hw, tmp, &recipe_count, ICE_SW_LKUP_MAC, NULL); if (status || recipe_count == 0) goto err_unroll; /* Allocate the recipe resources, and configure them according to the * match fields from protocol headers and extracted field vectors. */ chain_idx = find_first_bit(result_idx_bm, ICE_MAX_FV_WORDS); list_for_each_entry(entry, &rm->rg_list, l_entry) { u8 i; status = ice_alloc_recipe(hw, &entry->rid); if (status) goto err_unroll; content = &buf[recps].content; /* Clear the result index of the located recipe, as this will be * updated, if needed, later in the recipe creation process. */ tmp[0].content.result_indx = 0; buf[recps] = tmp[0]; buf[recps].recipe_indx = (u8)entry->rid; /* if the recipe is a non-root recipe RID should be programmed * as 0 for the rules to be applied correctly. */ content->rid = 0; memset(&content->lkup_indx, 0, sizeof(content->lkup_indx)); /* All recipes use look-up index 0 to match switch ID. */ content->lkup_indx[0] = ICE_AQ_SW_ID_LKUP_IDX; content->mask[0] = cpu_to_le16(ICE_AQ_SW_ID_LKUP_MASK); /* Setup lkup_indx 1..4 to INVALID/ignore and set the mask * to be 0 */ for (i = 1; i <= ICE_NUM_WORDS_RECIPE; i++) { content->lkup_indx[i] = 0x80; content->mask[i] = 0; } for (i = 0; i < entry->r_group.n_val_pairs; i++) { content->lkup_indx[i + 1] = entry->fv_idx[i]; content->mask[i + 1] = cpu_to_le16(entry->fv_mask[i]); } if (rm->n_grp_count > 1) { /* Checks to see if there really is a valid result index * that can be used. */ if (chain_idx >= ICE_MAX_FV_WORDS) { ice_debug(hw, ICE_DBG_SW, "No chain index available\n"); status = -ENOSPC; goto err_unroll; } entry->chain_idx = chain_idx; content->result_indx = ICE_AQ_RECIPE_RESULT_EN | ((chain_idx << ICE_AQ_RECIPE_RESULT_DATA_S) & ICE_AQ_RECIPE_RESULT_DATA_M); clear_bit(chain_idx, result_idx_bm); chain_idx = find_first_bit(result_idx_bm, ICE_MAX_FV_WORDS); } /* fill recipe dependencies */ bitmap_zero((unsigned long *)buf[recps].recipe_bitmap, ICE_MAX_NUM_RECIPES); set_bit(buf[recps].recipe_indx, (unsigned long *)buf[recps].recipe_bitmap); content->act_ctrl_fwd_priority = rm->priority; if (rm->need_pass_l2) content->act_ctrl |= ICE_AQ_RECIPE_ACT_NEED_PASS_L2; if (rm->allow_pass_l2) content->act_ctrl |= ICE_AQ_RECIPE_ACT_ALLOW_PASS_L2; recps++; } if (rm->n_grp_count == 1) { rm->root_rid = buf[0].recipe_indx; set_bit(buf[0].recipe_indx, rm->r_bitmap); buf[0].content.rid = rm->root_rid | ICE_AQ_RECIPE_ID_IS_ROOT; if (sizeof(buf[0].recipe_bitmap) >= sizeof(rm->r_bitmap)) { memcpy(buf[0].recipe_bitmap, rm->r_bitmap, sizeof(buf[0].recipe_bitmap)); } else { status = -EINVAL; goto err_unroll; } /* Applicable only for ROOT_RECIPE, set the fwd_priority for * the recipe which is getting created if specified * by user. Usually any advanced switch filter, which results * into new extraction sequence, ended up creating a new recipe * of type ROOT and usually recipes are associated with profiles * Switch rule referreing newly created recipe, needs to have * either/or 'fwd' or 'join' priority, otherwise switch rule * evaluation will not happen correctly. In other words, if * switch rule to be evaluated on priority basis, then recipe * needs to have priority, otherwise it will be evaluated last. */ buf[0].content.act_ctrl_fwd_priority = rm->priority; } else { struct ice_recp_grp_entry *last_chain_entry; u16 rid, i; /* Allocate the last recipe that will chain the outcomes of the * other recipes together */ status = ice_alloc_recipe(hw, &rid); if (status) goto err_unroll; content = &buf[recps].content; buf[recps].recipe_indx = (u8)rid; content->rid = (u8)rid; content->rid |= ICE_AQ_RECIPE_ID_IS_ROOT; /* the new entry created should also be part of rg_list to * make sure we have complete recipe */ last_chain_entry = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*last_chain_entry), GFP_KERNEL); if (!last_chain_entry) { status = -ENOMEM; goto err_unroll; } last_chain_entry->rid = rid; memset(&content->lkup_indx, 0, sizeof(content->lkup_indx)); /* All recipes use look-up index 0 to match switch ID. */ content->lkup_indx[0] = ICE_AQ_SW_ID_LKUP_IDX; content->mask[0] = cpu_to_le16(ICE_AQ_SW_ID_LKUP_MASK); for (i = 1; i <= ICE_NUM_WORDS_RECIPE; i++) { content->lkup_indx[i] = ICE_AQ_RECIPE_LKUP_IGNORE; content->mask[i] = 0; } i = 1; /* update r_bitmap with the recp that is used for chaining */ set_bit(rid, rm->r_bitmap); /* this is the recipe that chains all the other recipes so it * should not have a chaining ID to indicate the same */ last_chain_entry->chain_idx = ICE_INVAL_CHAIN_IND; list_for_each_entry(entry, &rm->rg_list, l_entry) { last_chain_entry->fv_idx[i] = entry->chain_idx; content->lkup_indx[i] = entry->chain_idx; content->mask[i++] = cpu_to_le16(0xFFFF); set_bit(entry->rid, rm->r_bitmap); } list_add(&last_chain_entry->l_entry, &rm->rg_list); if (sizeof(buf[recps].recipe_bitmap) >= sizeof(rm->r_bitmap)) { memcpy(buf[recps].recipe_bitmap, rm->r_bitmap, sizeof(buf[recps].recipe_bitmap)); } else { status = -EINVAL; goto err_unroll; } content->act_ctrl_fwd_priority = rm->priority; recps++; rm->root_rid = (u8)rid; } status = ice_acquire_change_lock(hw, ICE_RES_WRITE); if (status) goto err_unroll; status = ice_aq_add_recipe(hw, buf, rm->n_grp_count, NULL); ice_release_change_lock(hw); if (status) goto err_unroll; /* Every recipe that just got created add it to the recipe * book keeping list */ list_for_each_entry(entry, &rm->rg_list, l_entry) { struct ice_switch_info *sw = hw->switch_info; bool is_root, idx_found = false; struct ice_sw_recipe *recp; u16 idx, buf_idx = 0; /* find buffer index for copying some data */ for (idx = 0; idx < rm->n_grp_count; idx++) if (buf[idx].recipe_indx == entry->rid) { buf_idx = idx; idx_found = true; } if (!idx_found) { status = -EIO; goto err_unroll; } recp = &sw->recp_list[entry->rid]; is_root = (rm->root_rid == entry->rid); recp->is_root = is_root; recp->root_rid = entry->rid; recp->big_recp = (is_root && rm->n_grp_count > 1); memcpy(&recp->ext_words, entry->r_group.pairs, entry->r_group.n_val_pairs * sizeof(struct ice_fv_word)); memcpy(recp->r_bitmap, buf[buf_idx].recipe_bitmap, sizeof(recp->r_bitmap)); /* Copy non-result fv index values and masks to recipe. This * call will also update the result recipe bitmask. */ ice_collect_result_idx(&buf[buf_idx], recp); /* for non-root recipes, also copy to the root, this allows * easier matching of a complete chained recipe */ if (!is_root) ice_collect_result_idx(&buf[buf_idx], &sw->recp_list[rm->root_rid]); recp->n_ext_words = entry->r_group.n_val_pairs; recp->chain_idx = entry->chain_idx; recp->priority = buf[buf_idx].content.act_ctrl_fwd_priority; recp->n_grp_count = rm->n_grp_count; recp->tun_type = rm->tun_type; recp->need_pass_l2 = rm->need_pass_l2; recp->allow_pass_l2 = rm->allow_pass_l2; recp->recp_created = true; } rm->root_buf = buf; kfree(tmp); return status; err_unroll: err_mem: kfree(tmp); devm_kfree(ice_hw_to_dev(hw), buf); return status; } /** * ice_create_recipe_group - creates recipe group * @hw: pointer to hardware structure * @rm: recipe management list entry * @lkup_exts: lookup elements */ static int ice_create_recipe_group(struct ice_hw *hw, struct ice_sw_recipe *rm, struct ice_prot_lkup_ext *lkup_exts) { u8 recp_count = 0; int status; rm->n_grp_count = 0; /* Create recipes for words that are marked not done by packing them * as best fit. */ status = ice_create_first_fit_recp_def(hw, lkup_exts, &rm->rg_list, &recp_count); if (!status) { rm->n_grp_count += recp_count; rm->n_ext_words = lkup_exts->n_val_words; memcpy(&rm->ext_words, lkup_exts->fv_words, sizeof(rm->ext_words)); memcpy(rm->word_masks, lkup_exts->field_mask, sizeof(rm->word_masks)); } return status; } /* ice_get_compat_fv_bitmap - Get compatible field vector bitmap for rule * @hw: pointer to hardware structure * @rinfo: other information regarding the rule e.g. priority and action info * @bm: pointer to memory for returning the bitmap of field vectors */ static void ice_get_compat_fv_bitmap(struct ice_hw *hw, struct ice_adv_rule_info *rinfo, unsigned long *bm) { enum ice_prof_type prof_type; bitmap_zero(bm, ICE_MAX_NUM_PROFILES); switch (rinfo->tun_type) { case ICE_NON_TUN: prof_type = ICE_PROF_NON_TUN; break; case ICE_ALL_TUNNELS: prof_type = ICE_PROF_TUN_ALL; break; case ICE_SW_TUN_GENEVE: case ICE_SW_TUN_VXLAN: prof_type = ICE_PROF_TUN_UDP; break; case ICE_SW_TUN_NVGRE: prof_type = ICE_PROF_TUN_GRE; break; case ICE_SW_TUN_GTPU: prof_type = ICE_PROF_TUN_GTPU; break; case ICE_SW_TUN_GTPC: prof_type = ICE_PROF_TUN_GTPC; break; case ICE_SW_TUN_AND_NON_TUN: default: prof_type = ICE_PROF_ALL; break; } ice_get_sw_fv_bitmap(hw, prof_type, bm); } /** * ice_add_adv_recipe - Add an advanced recipe that is not part of the default * @hw: pointer to hardware structure * @lkups: lookup elements or match criteria for the advanced recipe, one * structure per protocol header * @lkups_cnt: number of protocols * @rinfo: other information regarding the rule e.g. priority and action info * @rid: return the recipe ID of the recipe created */ static int ice_add_adv_recipe(struct ice_hw *hw, struct ice_adv_lkup_elem *lkups, u16 lkups_cnt, struct ice_adv_rule_info *rinfo, u16 *rid) { DECLARE_BITMAP(fv_bitmap, ICE_MAX_NUM_PROFILES); DECLARE_BITMAP(profiles, ICE_MAX_NUM_PROFILES); struct ice_prot_lkup_ext *lkup_exts; struct ice_recp_grp_entry *r_entry; struct ice_sw_fv_list_entry *fvit; struct ice_recp_grp_entry *r_tmp; struct ice_sw_fv_list_entry *tmp; struct ice_sw_recipe *rm; int status = 0; u8 i; if (!lkups_cnt) return -EINVAL; lkup_exts = kzalloc(sizeof(*lkup_exts), GFP_KERNEL); if (!lkup_exts) return -ENOMEM; /* Determine the number of words to be matched and if it exceeds a * recipe's restrictions */ for (i = 0; i < lkups_cnt; i++) { u16 count; if (lkups[i].type >= ICE_PROTOCOL_LAST) { status = -EIO; goto err_free_lkup_exts; } count = ice_fill_valid_words(&lkups[i], lkup_exts); if (!count) { status = -EIO; goto err_free_lkup_exts; } } rm = kzalloc(sizeof(*rm), GFP_KERNEL); if (!rm) { status = -ENOMEM; goto err_free_lkup_exts; } /* Get field vectors that contain fields extracted from all the protocol * headers being programmed. */ INIT_LIST_HEAD(&rm->fv_list); INIT_LIST_HEAD(&rm->rg_list); /* Get bitmap of field vectors (profiles) that are compatible with the * rule request; only these will be searched in the subsequent call to * ice_get_sw_fv_list. */ ice_get_compat_fv_bitmap(hw, rinfo, fv_bitmap); status = ice_get_sw_fv_list(hw, lkup_exts, fv_bitmap, &rm->fv_list); if (status) goto err_unroll; /* Group match words into recipes using preferred recipe grouping * criteria. */ status = ice_create_recipe_group(hw, rm, lkup_exts); if (status) goto err_unroll; /* set the recipe priority if specified */ rm->priority = (u8)rinfo->priority; rm->need_pass_l2 = rinfo->need_pass_l2; rm->allow_pass_l2 = rinfo->allow_pass_l2; /* Find offsets from the field vector. Pick the first one for all the * recipes. */ status = ice_fill_fv_word_index(hw, &rm->fv_list, &rm->rg_list); if (status) goto err_unroll; /* get bitmap of all profiles the recipe will be associated with */ bitmap_zero(profiles, ICE_MAX_NUM_PROFILES); list_for_each_entry(fvit, &rm->fv_list, list_entry) { ice_debug(hw, ICE_DBG_SW, "profile: %d\n", fvit->profile_id); set_bit((u16)fvit->profile_id, profiles); } /* Look for a recipe which matches our requested fv / mask list */ *rid = ice_find_recp(hw, lkup_exts, rinfo); if (*rid < ICE_MAX_NUM_RECIPES) /* Success if found a recipe that match the existing criteria */ goto err_unroll; rm->tun_type = rinfo->tun_type; /* Recipe we need does not exist, add a recipe */ status = ice_add_sw_recipe(hw, rm, profiles); if (status) goto err_unroll; /* Associate all the recipes created with all the profiles in the * common field vector. */ list_for_each_entry(fvit, &rm->fv_list, list_entry) { DECLARE_BITMAP(r_bitmap, ICE_MAX_NUM_RECIPES); u16 j; status = ice_aq_get_recipe_to_profile(hw, fvit->profile_id, (u8 *)r_bitmap, NULL); if (status) goto err_unroll; bitmap_or(r_bitmap, r_bitmap, rm->r_bitmap, ICE_MAX_NUM_RECIPES); status = ice_acquire_change_lock(hw, ICE_RES_WRITE); if (status) goto err_unroll; status = ice_aq_map_recipe_to_profile(hw, fvit->profile_id, (u8 *)r_bitmap, NULL); ice_release_change_lock(hw); if (status) goto err_unroll; /* Update profile to recipe bitmap array */ bitmap_copy(profile_to_recipe[fvit->profile_id], r_bitmap, ICE_MAX_NUM_RECIPES); /* Update recipe to profile bitmap array */ for_each_set_bit(j, rm->r_bitmap, ICE_MAX_NUM_RECIPES) set_bit((u16)fvit->profile_id, recipe_to_profile[j]); } *rid = rm->root_rid; memcpy(&hw->switch_info->recp_list[*rid].lkup_exts, lkup_exts, sizeof(*lkup_exts)); err_unroll: list_for_each_entry_safe(r_entry, r_tmp, &rm->rg_list, l_entry) { list_del(&r_entry->l_entry); devm_kfree(ice_hw_to_dev(hw), r_entry); } list_for_each_entry_safe(fvit, tmp, &rm->fv_list, list_entry) { list_del(&fvit->list_entry); devm_kfree(ice_hw_to_dev(hw), fvit); } devm_kfree(ice_hw_to_dev(hw), rm->root_buf); kfree(rm); err_free_lkup_exts: kfree(lkup_exts); return status; } /** * ice_dummy_packet_add_vlan - insert VLAN header to dummy pkt * * @dummy_pkt: dummy packet profile pattern to which VLAN tag(s) will be added * @num_vlan: number of VLAN tags */ static struct ice_dummy_pkt_profile * ice_dummy_packet_add_vlan(const struct ice_dummy_pkt_profile *dummy_pkt, u32 num_vlan) { struct ice_dummy_pkt_profile *profile; struct ice_dummy_pkt_offsets *offsets; u32 buf_len, off, etype_off, i; u8 *pkt; if (num_vlan < 1 || num_vlan > 2) return ERR_PTR(-EINVAL); off = num_vlan * VLAN_HLEN; buf_len = array_size(num_vlan, sizeof(ice_dummy_vlan_packet_offsets)) + dummy_pkt->offsets_len; offsets = kzalloc(buf_len, GFP_KERNEL); if (!offsets) return ERR_PTR(-ENOMEM); offsets[0] = dummy_pkt->offsets[0]; if (num_vlan == 2) { offsets[1] = ice_dummy_qinq_packet_offsets[0]; offsets[2] = ice_dummy_qinq_packet_offsets[1]; } else if (num_vlan == 1) { offsets[1] = ice_dummy_vlan_packet_offsets[0]; } for (i = 1; dummy_pkt->offsets[i].type != ICE_PROTOCOL_LAST; i++) { offsets[i + num_vlan].type = dummy_pkt->offsets[i].type; offsets[i + num_vlan].offset = dummy_pkt->offsets[i].offset + off; } offsets[i + num_vlan] = dummy_pkt->offsets[i]; etype_off = dummy_pkt->offsets[1].offset; buf_len = array_size(num_vlan, sizeof(ice_dummy_vlan_packet)) + dummy_pkt->pkt_len; pkt = kzalloc(buf_len, GFP_KERNEL); if (!pkt) { kfree(offsets); return ERR_PTR(-ENOMEM); } memcpy(pkt, dummy_pkt->pkt, etype_off); memcpy(pkt + etype_off, num_vlan == 2 ? ice_dummy_qinq_packet : ice_dummy_vlan_packet, off); memcpy(pkt + etype_off + off, dummy_pkt->pkt + etype_off, dummy_pkt->pkt_len - etype_off); profile = kzalloc(sizeof(*profile), GFP_KERNEL); if (!profile) { kfree(offsets); kfree(pkt); return ERR_PTR(-ENOMEM); } profile->offsets = offsets; profile->pkt = pkt; profile->pkt_len = buf_len; profile->match |= ICE_PKT_KMALLOC; return profile; } /** * ice_find_dummy_packet - find dummy packet * * @lkups: lookup elements or match criteria for the advanced recipe, one * structure per protocol header * @lkups_cnt: number of protocols * @tun_type: tunnel type * * Returns the &ice_dummy_pkt_profile corresponding to these lookup params. */ static const struct ice_dummy_pkt_profile * ice_find_dummy_packet(struct ice_adv_lkup_elem *lkups, u16 lkups_cnt, enum ice_sw_tunnel_type tun_type) { const struct ice_dummy_pkt_profile *ret = ice_dummy_pkt_profiles; u32 match = 0, vlan_count = 0; u16 i; switch (tun_type) { case ICE_SW_TUN_GTPC: match |= ICE_PKT_TUN_GTPC; break; case ICE_SW_TUN_GTPU: match |= ICE_PKT_TUN_GTPU; break; case ICE_SW_TUN_NVGRE: match |= ICE_PKT_TUN_NVGRE; break; case ICE_SW_TUN_GENEVE: case ICE_SW_TUN_VXLAN: match |= ICE_PKT_TUN_UDP; break; default: break; } for (i = 0; i < lkups_cnt; i++) { if (lkups[i].type == ICE_UDP_ILOS) match |= ICE_PKT_INNER_UDP; else if (lkups[i].type == ICE_TCP_IL) match |= ICE_PKT_INNER_TCP; else if (lkups[i].type == ICE_IPV6_OFOS) match |= ICE_PKT_OUTER_IPV6; else if (lkups[i].type == ICE_VLAN_OFOS || lkups[i].type == ICE_VLAN_EX) vlan_count++; else if (lkups[i].type == ICE_VLAN_IN) vlan_count++; else if (lkups[i].type == ICE_ETYPE_OL && lkups[i].h_u.ethertype.ethtype_id == cpu_to_be16(ICE_IPV6_ETHER_ID) && lkups[i].m_u.ethertype.ethtype_id == cpu_to_be16(0xFFFF)) match |= ICE_PKT_OUTER_IPV6; else if (lkups[i].type == ICE_ETYPE_IL && lkups[i].h_u.ethertype.ethtype_id == cpu_to_be16(ICE_IPV6_ETHER_ID) && lkups[i].m_u.ethertype.ethtype_id == cpu_to_be16(0xFFFF)) match |= ICE_PKT_INNER_IPV6; else if (lkups[i].type == ICE_IPV6_IL) match |= ICE_PKT_INNER_IPV6; else if (lkups[i].type == ICE_GTP_NO_PAY) match |= ICE_PKT_GTP_NOPAY; else if (lkups[i].type == ICE_PPPOE) { match |= ICE_PKT_PPPOE; if (lkups[i].h_u.pppoe_hdr.ppp_prot_id == htons(PPP_IPV6)) match |= ICE_PKT_OUTER_IPV6; } else if (lkups[i].type == ICE_L2TPV3) match |= ICE_PKT_L2TPV3; } while (ret->match && (match & ret->match) != ret->match) ret++; if (vlan_count != 0) ret = ice_dummy_packet_add_vlan(ret, vlan_count); return ret; } /** * ice_fill_adv_dummy_packet - fill a dummy packet with given match criteria * * @lkups: lookup elements or match criteria for the advanced recipe, one * structure per protocol header * @lkups_cnt: number of protocols * @s_rule: stores rule information from the match criteria * @profile: dummy packet profile (the template, its size and header offsets) */ static int ice_fill_adv_dummy_packet(struct ice_adv_lkup_elem *lkups, u16 lkups_cnt, struct ice_sw_rule_lkup_rx_tx *s_rule, const struct ice_dummy_pkt_profile *profile) { u8 *pkt; u16 i; /* Start with a packet with a pre-defined/dummy content. Then, fill * in the header values to be looked up or matched. */ pkt = s_rule->hdr_data; memcpy(pkt, profile->pkt, profile->pkt_len); for (i = 0; i < lkups_cnt; i++) { const struct ice_dummy_pkt_offsets *offsets = profile->offsets; enum ice_protocol_type type; u16 offset = 0, len = 0, j; bool found = false; /* find the start of this layer; it should be found since this * was already checked when search for the dummy packet */ type = lkups[i].type; /* metadata isn't present in the packet */ if (type == ICE_HW_METADATA) continue; for (j = 0; offsets[j].type != ICE_PROTOCOL_LAST; j++) { if (type == offsets[j].type) { offset = offsets[j].offset; found = true; break; } } /* this should never happen in a correct calling sequence */ if (!found) return -EINVAL; switch (lkups[i].type) { case ICE_MAC_OFOS: case ICE_MAC_IL: len = sizeof(struct ice_ether_hdr); break; case ICE_ETYPE_OL: case ICE_ETYPE_IL: len = sizeof(struct ice_ethtype_hdr); break; case ICE_VLAN_OFOS: case ICE_VLAN_EX: case ICE_VLAN_IN: len = sizeof(struct ice_vlan_hdr); break; case ICE_IPV4_OFOS: case ICE_IPV4_IL: len = sizeof(struct ice_ipv4_hdr); break; case ICE_IPV6_OFOS: case ICE_IPV6_IL: len = sizeof(struct ice_ipv6_hdr); break; case ICE_TCP_IL: case ICE_UDP_OF: case ICE_UDP_ILOS: len = sizeof(struct ice_l4_hdr); break; case ICE_SCTP_IL: len = sizeof(struct ice_sctp_hdr); break; case ICE_NVGRE: len = sizeof(struct ice_nvgre_hdr); break; case ICE_VXLAN: case ICE_GENEVE: len = sizeof(struct ice_udp_tnl_hdr); break; case ICE_GTP_NO_PAY: case ICE_GTP: len = sizeof(struct ice_udp_gtp_hdr); break; case ICE_PPPOE: len = sizeof(struct ice_pppoe_hdr); break; case ICE_L2TPV3: len = sizeof(struct ice_l2tpv3_sess_hdr); break; default: return -EINVAL; } /* the length should be a word multiple */ if (len % ICE_BYTES_PER_WORD) return -EIO; /* We have the offset to the header start, the length, the * caller's header values and mask. Use this information to * copy the data into the dummy packet appropriately based on * the mask. Note that we need to only write the bits as * indicated by the mask to make sure we don't improperly write * over any significant packet data. */ for (j = 0; j < len / sizeof(u16); j++) { u16 *ptr = (u16 *)(pkt + offset); u16 mask = lkups[i].m_raw[j]; if (!mask) continue; ptr[j] = (ptr[j] & ~mask) | (lkups[i].h_raw[j] & mask); } } s_rule->hdr_len = cpu_to_le16(profile->pkt_len); return 0; } /** * ice_fill_adv_packet_tun - fill dummy packet with udp tunnel port * @hw: pointer to the hardware structure * @tun_type: tunnel type * @pkt: dummy packet to fill in * @offsets: offset info for the dummy packet */ static int ice_fill_adv_packet_tun(struct ice_hw *hw, enum ice_sw_tunnel_type tun_type, u8 *pkt, const struct ice_dummy_pkt_offsets *offsets) { u16 open_port, i; switch (tun_type) { case ICE_SW_TUN_VXLAN: if (!ice_get_open_tunnel_port(hw, &open_port, TNL_VXLAN)) return -EIO; break; case ICE_SW_TUN_GENEVE: if (!ice_get_open_tunnel_port(hw, &open_port, TNL_GENEVE)) return -EIO; break; default: /* Nothing needs to be done for this tunnel type */ return 0; } /* Find the outer UDP protocol header and insert the port number */ for (i = 0; offsets[i].type != ICE_PROTOCOL_LAST; i++) { if (offsets[i].type == ICE_UDP_OF) { struct ice_l4_hdr *hdr; u16 offset; offset = offsets[i].offset; hdr = (struct ice_l4_hdr *)&pkt[offset]; hdr->dst_port = cpu_to_be16(open_port); return 0; } } return -EIO; } /** * ice_fill_adv_packet_vlan - fill dummy packet with VLAN tag type * @hw: pointer to hw structure * @vlan_type: VLAN tag type * @pkt: dummy packet to fill in * @offsets: offset info for the dummy packet */ static int ice_fill_adv_packet_vlan(struct ice_hw *hw, u16 vlan_type, u8 *pkt, const struct ice_dummy_pkt_offsets *offsets) { u16 i; /* Check if there is something to do */ if (!vlan_type || !ice_is_dvm_ena(hw)) return 0; /* Find VLAN header and insert VLAN TPID */ for (i = 0; offsets[i].type != ICE_PROTOCOL_LAST; i++) { if (offsets[i].type == ICE_VLAN_OFOS || offsets[i].type == ICE_VLAN_EX) { struct ice_vlan_hdr *hdr; u16 offset; offset = offsets[i].offset; hdr = (struct ice_vlan_hdr *)&pkt[offset]; hdr->type = cpu_to_be16(vlan_type); return 0; } } return -EIO; } static bool ice_rules_equal(const struct ice_adv_rule_info *first, const struct ice_adv_rule_info *second) { return first->sw_act.flag == second->sw_act.flag && first->tun_type == second->tun_type && first->vlan_type == second->vlan_type && first->src_vsi == second->src_vsi && first->need_pass_l2 == second->need_pass_l2 && first->allow_pass_l2 == second->allow_pass_l2; } /** * ice_find_adv_rule_entry - Search a rule entry * @hw: pointer to the hardware structure * @lkups: lookup elements or match criteria for the advanced recipe, one * structure per protocol header * @lkups_cnt: number of protocols * @recp_id: recipe ID for which we are finding the rule * @rinfo: other information regarding the rule e.g. priority and action info * * Helper function to search for a given advance rule entry * Returns pointer to entry storing the rule if found */ static struct ice_adv_fltr_mgmt_list_entry * ice_find_adv_rule_entry(struct ice_hw *hw, struct ice_adv_lkup_elem *lkups, u16 lkups_cnt, u16 recp_id, struct ice_adv_rule_info *rinfo) { struct ice_adv_fltr_mgmt_list_entry *list_itr; struct ice_switch_info *sw = hw->switch_info; int i; list_for_each_entry(list_itr, &sw->recp_list[recp_id].filt_rules, list_entry) { bool lkups_matched = true; if (lkups_cnt != list_itr->lkups_cnt) continue; for (i = 0; i < list_itr->lkups_cnt; i++) if (memcmp(&list_itr->lkups[i], &lkups[i], sizeof(*lkups))) { lkups_matched = false; break; } if (ice_rules_equal(rinfo, &list_itr->rule_info) && lkups_matched) return list_itr; } return NULL; } /** * ice_adv_add_update_vsi_list * @hw: pointer to the hardware structure * @m_entry: pointer to current adv filter management list entry * @cur_fltr: filter information from the book keeping entry * @new_fltr: filter information with the new VSI to be added * * Call AQ command to add or update previously created VSI list with new VSI. * * Helper function to do book keeping associated with adding filter information * The algorithm to do the booking keeping is described below : * When a VSI needs to subscribe to a given advanced filter * if only one VSI has been added till now * Allocate a new VSI list and add two VSIs * to this list using switch rule command * Update the previously created switch rule with the * newly created VSI list ID * if a VSI list was previously created * Add the new VSI to the previously created VSI list set * using the update switch rule command */ static int ice_adv_add_update_vsi_list(struct ice_hw *hw, struct ice_adv_fltr_mgmt_list_entry *m_entry, struct ice_adv_rule_info *cur_fltr, struct ice_adv_rule_info *new_fltr) { u16 vsi_list_id = 0; int status; if (cur_fltr->sw_act.fltr_act == ICE_FWD_TO_Q || cur_fltr->sw_act.fltr_act == ICE_FWD_TO_QGRP || cur_fltr->sw_act.fltr_act == ICE_DROP_PACKET) return -EOPNOTSUPP; if ((new_fltr->sw_act.fltr_act == ICE_FWD_TO_Q || new_fltr->sw_act.fltr_act == ICE_FWD_TO_QGRP) && (cur_fltr->sw_act.fltr_act == ICE_FWD_TO_VSI || cur_fltr->sw_act.fltr_act == ICE_FWD_TO_VSI_LIST)) return -EOPNOTSUPP; if (m_entry->vsi_count < 2 && !m_entry->vsi_list_info) { /* Only one entry existed in the mapping and it was not already * a part of a VSI list. So, create a VSI list with the old and * new VSIs. */ struct ice_fltr_info tmp_fltr; u16 vsi_handle_arr[2]; /* A rule already exists with the new VSI being added */ if (cur_fltr->sw_act.fwd_id.hw_vsi_id == new_fltr->sw_act.fwd_id.hw_vsi_id) return -EEXIST; vsi_handle_arr[0] = cur_fltr->sw_act.vsi_handle; vsi_handle_arr[1] = new_fltr->sw_act.vsi_handle; status = ice_create_vsi_list_rule(hw, &vsi_handle_arr[0], 2, &vsi_list_id, ICE_SW_LKUP_LAST); if (status) return status; memset(&tmp_fltr, 0, sizeof(tmp_fltr)); tmp_fltr.flag = m_entry->rule_info.sw_act.flag; tmp_fltr.fltr_rule_id = cur_fltr->fltr_rule_id; tmp_fltr.fltr_act = ICE_FWD_TO_VSI_LIST; tmp_fltr.fwd_id.vsi_list_id = vsi_list_id; tmp_fltr.lkup_type = ICE_SW_LKUP_LAST; /* Update the previous switch rule of "forward to VSI" to * "fwd to VSI list" */ status = ice_update_pkt_fwd_rule(hw, &tmp_fltr); if (status) return status; cur_fltr->sw_act.fwd_id.vsi_list_id = vsi_list_id; cur_fltr->sw_act.fltr_act = ICE_FWD_TO_VSI_LIST; m_entry->vsi_list_info = ice_create_vsi_list_map(hw, &vsi_handle_arr[0], 2, vsi_list_id); } else { u16 vsi_handle = new_fltr->sw_act.vsi_handle; if (!m_entry->vsi_list_info) return -EIO; /* A rule already exists with the new VSI being added */ if (test_bit(vsi_handle, m_entry->vsi_list_info->vsi_map)) return 0; /* Update the previously created VSI list set with * the new VSI ID passed in */ vsi_list_id = cur_fltr->sw_act.fwd_id.vsi_list_id; status = ice_update_vsi_list_rule(hw, &vsi_handle, 1, vsi_list_id, false, ice_aqc_opc_update_sw_rules, ICE_SW_LKUP_LAST); /* update VSI list mapping info with new VSI ID */ if (!status) set_bit(vsi_handle, m_entry->vsi_list_info->vsi_map); } if (!status) m_entry->vsi_count++; return status; } void ice_rule_add_tunnel_metadata(struct ice_adv_lkup_elem *lkup) { lkup->type = ICE_HW_METADATA; lkup->m_u.metadata.flags[ICE_PKT_FLAGS_MDID21] |= cpu_to_be16(ICE_PKT_TUNNEL_MASK); } void ice_rule_add_direction_metadata(struct ice_adv_lkup_elem *lkup) { lkup->type = ICE_HW_METADATA; lkup->m_u.metadata.flags[ICE_PKT_FLAGS_MDID20] |= cpu_to_be16(ICE_PKT_FROM_NETWORK); } void ice_rule_add_vlan_metadata(struct ice_adv_lkup_elem *lkup) { lkup->type = ICE_HW_METADATA; lkup->m_u.metadata.flags[ICE_PKT_FLAGS_MDID20] |= cpu_to_be16(ICE_PKT_VLAN_MASK); } void ice_rule_add_src_vsi_metadata(struct ice_adv_lkup_elem *lkup) { lkup->type = ICE_HW_METADATA; lkup->m_u.metadata.source_vsi = cpu_to_be16(ICE_MDID_SOURCE_VSI_MASK); } /** * ice_add_adv_rule - helper function to create an advanced switch rule * @hw: pointer to the hardware structure * @lkups: information on the words that needs to be looked up. All words * together makes one recipe * @lkups_cnt: num of entries in the lkups array * @rinfo: other information related to the rule that needs to be programmed * @added_entry: this will return recipe_id, rule_id and vsi_handle. should be * ignored is case of error. * * This function can program only 1 rule at a time. The lkups is used to * describe the all the words that forms the "lookup" portion of the recipe. * These words can span multiple protocols. Callers to this function need to * pass in a list of protocol headers with lookup information along and mask * that determines which words are valid from the given protocol header. * rinfo describes other information related to this rule such as forwarding * IDs, priority of this rule, etc. */ int ice_add_adv_rule(struct ice_hw *hw, struct ice_adv_lkup_elem *lkups, u16 lkups_cnt, struct ice_adv_rule_info *rinfo, struct ice_rule_query_data *added_entry) { struct ice_adv_fltr_mgmt_list_entry *m_entry, *adv_fltr = NULL; struct ice_sw_rule_lkup_rx_tx *s_rule = NULL; const struct ice_dummy_pkt_profile *profile; u16 rid = 0, i, rule_buf_sz, vsi_handle; struct list_head *rule_head; struct ice_switch_info *sw; u16 word_cnt; u32 act = 0; int status; u8 q_rgn; /* Initialize profile to result index bitmap */ if (!hw->switch_info->prof_res_bm_init) { hw->switch_info->prof_res_bm_init = 1; ice_init_prof_result_bm(hw); } if (!lkups_cnt) return -EINVAL; /* get # of words we need to match */ word_cnt = 0; for (i = 0; i < lkups_cnt; i++) { u16 j; for (j = 0; j < ARRAY_SIZE(lkups->m_raw); j++) if (lkups[i].m_raw[j]) word_cnt++; } if (!word_cnt) return -EINVAL; if (word_cnt > ICE_MAX_CHAIN_WORDS) return -ENOSPC; /* locate a dummy packet */ profile = ice_find_dummy_packet(lkups, lkups_cnt, rinfo->tun_type); if (IS_ERR(profile)) return PTR_ERR(profile); if (!(rinfo->sw_act.fltr_act == ICE_FWD_TO_VSI || rinfo->sw_act.fltr_act == ICE_FWD_TO_Q || rinfo->sw_act.fltr_act == ICE_FWD_TO_QGRP || rinfo->sw_act.fltr_act == ICE_DROP_PACKET || rinfo->sw_act.fltr_act == ICE_NOP)) { status = -EIO; goto free_pkt_profile; } vsi_handle = rinfo->sw_act.vsi_handle; if (!ice_is_vsi_valid(hw, vsi_handle)) { status = -EINVAL; goto free_pkt_profile; } if (rinfo->sw_act.fltr_act == ICE_FWD_TO_VSI || rinfo->sw_act.fltr_act == ICE_NOP) rinfo->sw_act.fwd_id.hw_vsi_id = ice_get_hw_vsi_num(hw, vsi_handle); if (rinfo->src_vsi) rinfo->sw_act.src = ice_get_hw_vsi_num(hw, rinfo->src_vsi); else rinfo->sw_act.src = ice_get_hw_vsi_num(hw, vsi_handle); status = ice_add_adv_recipe(hw, lkups, lkups_cnt, rinfo, &rid); if (status) goto free_pkt_profile; m_entry = ice_find_adv_rule_entry(hw, lkups, lkups_cnt, rid, rinfo); if (m_entry) { /* we have to add VSI to VSI_LIST and increment vsi_count. * Also Update VSI list so that we can change forwarding rule * if the rule already exists, we will check if it exists with * same vsi_id, if not then add it to the VSI list if it already * exists if not then create a VSI list and add the existing VSI * ID and the new VSI ID to the list * We will add that VSI to the list */ status = ice_adv_add_update_vsi_list(hw, m_entry, &m_entry->rule_info, rinfo); if (added_entry) { added_entry->rid = rid; added_entry->rule_id = m_entry->rule_info.fltr_rule_id; added_entry->vsi_handle = rinfo->sw_act.vsi_handle; } goto free_pkt_profile; } rule_buf_sz = ICE_SW_RULE_RX_TX_HDR_SIZE(s_rule, profile->pkt_len); s_rule = kzalloc(rule_buf_sz, GFP_KERNEL); if (!s_rule) { status = -ENOMEM; goto free_pkt_profile; } if (!rinfo->flags_info.act_valid) { act |= ICE_SINGLE_ACT_LAN_ENABLE; act |= ICE_SINGLE_ACT_LB_ENABLE; } else { act |= rinfo->flags_info.act & (ICE_SINGLE_ACT_LAN_ENABLE | ICE_SINGLE_ACT_LB_ENABLE); } switch (rinfo->sw_act.fltr_act) { case ICE_FWD_TO_VSI: act |= (rinfo->sw_act.fwd_id.hw_vsi_id << ICE_SINGLE_ACT_VSI_ID_S) & ICE_SINGLE_ACT_VSI_ID_M; act |= ICE_SINGLE_ACT_VSI_FORWARDING | ICE_SINGLE_ACT_VALID_BIT; break; case ICE_FWD_TO_Q: act |= ICE_SINGLE_ACT_TO_Q; act |= (rinfo->sw_act.fwd_id.q_id << ICE_SINGLE_ACT_Q_INDEX_S) & ICE_SINGLE_ACT_Q_INDEX_M; break; case ICE_FWD_TO_QGRP: q_rgn = rinfo->sw_act.qgrp_size > 0 ? (u8)ilog2(rinfo->sw_act.qgrp_size) : 0; act |= ICE_SINGLE_ACT_TO_Q; act |= (rinfo->sw_act.fwd_id.q_id << ICE_SINGLE_ACT_Q_INDEX_S) & ICE_SINGLE_ACT_Q_INDEX_M; act |= (q_rgn << ICE_SINGLE_ACT_Q_REGION_S) & ICE_SINGLE_ACT_Q_REGION_M; break; case ICE_DROP_PACKET: act |= ICE_SINGLE_ACT_VSI_FORWARDING | ICE_SINGLE_ACT_DROP | ICE_SINGLE_ACT_VALID_BIT; break; case ICE_NOP: act |= FIELD_PREP(ICE_SINGLE_ACT_VSI_ID_M, rinfo->sw_act.fwd_id.hw_vsi_id); act &= ~ICE_SINGLE_ACT_VALID_BIT; break; default: status = -EIO; goto err_ice_add_adv_rule; } /* If there is no matching criteria for direction there * is only one difference between Rx and Tx: * - get switch id base on VSI number from source field (Tx) * - get switch id base on port number (Rx) * * If matching on direction metadata is chose rule direction is * extracted from type value set here. */ if (rinfo->sw_act.flag & ICE_FLTR_TX) { s_rule->hdr.type = cpu_to_le16(ICE_AQC_SW_RULES_T_LKUP_TX); s_rule->src = cpu_to_le16(rinfo->sw_act.src); } else { s_rule->hdr.type = cpu_to_le16(ICE_AQC_SW_RULES_T_LKUP_RX); s_rule->src = cpu_to_le16(hw->port_info->lport); } s_rule->recipe_id = cpu_to_le16(rid); s_rule->act = cpu_to_le32(act); status = ice_fill_adv_dummy_packet(lkups, lkups_cnt, s_rule, profile); if (status) goto err_ice_add_adv_rule; status = ice_fill_adv_packet_tun(hw, rinfo->tun_type, s_rule->hdr_data, profile->offsets); if (status) goto err_ice_add_adv_rule; status = ice_fill_adv_packet_vlan(hw, rinfo->vlan_type, s_rule->hdr_data, profile->offsets); if (status) goto err_ice_add_adv_rule; status = ice_aq_sw_rules(hw, (struct ice_aqc_sw_rules *)s_rule, rule_buf_sz, 1, ice_aqc_opc_add_sw_rules, NULL); if (status) goto err_ice_add_adv_rule; adv_fltr = devm_kzalloc(ice_hw_to_dev(hw), sizeof(struct ice_adv_fltr_mgmt_list_entry), GFP_KERNEL); if (!adv_fltr) { status = -ENOMEM; goto err_ice_add_adv_rule; } adv_fltr->lkups = devm_kmemdup(ice_hw_to_dev(hw), lkups, lkups_cnt * sizeof(*lkups), GFP_KERNEL); if (!adv_fltr->lkups) { status = -ENOMEM; goto err_ice_add_adv_rule; } adv_fltr->lkups_cnt = lkups_cnt; adv_fltr->rule_info = *rinfo; adv_fltr->rule_info.fltr_rule_id = le16_to_cpu(s_rule->index); sw = hw->switch_info; sw->recp_list[rid].adv_rule = true; rule_head = &sw->recp_list[rid].filt_rules; if (rinfo->sw_act.fltr_act == ICE_FWD_TO_VSI) adv_fltr->vsi_count = 1; /* Add rule entry to book keeping list */ list_add(&adv_fltr->list_entry, rule_head); if (added_entry) { added_entry->rid = rid; added_entry->rule_id = adv_fltr->rule_info.fltr_rule_id; added_entry->vsi_handle = rinfo->sw_act.vsi_handle; } err_ice_add_adv_rule: if (status && adv_fltr) { devm_kfree(ice_hw_to_dev(hw), adv_fltr->lkups); devm_kfree(ice_hw_to_dev(hw), adv_fltr); } kfree(s_rule); free_pkt_profile: if (profile->match & ICE_PKT_KMALLOC) { kfree(profile->offsets); kfree(profile->pkt); kfree(profile); } return status; } /** * ice_replay_vsi_fltr - Replay filters for requested VSI * @hw: pointer to the hardware structure * @vsi_handle: driver VSI handle * @recp_id: Recipe ID for which rules need to be replayed * @list_head: list for which filters need to be replayed * * Replays the filter of recipe recp_id for a VSI represented via vsi_handle. * It is required to pass valid VSI handle. */ static int ice_replay_vsi_fltr(struct ice_hw *hw, u16 vsi_handle, u8 recp_id, struct list_head *list_head) { struct ice_fltr_mgmt_list_entry *itr; int status = 0; u16 hw_vsi_id; if (list_empty(list_head)) return status; hw_vsi_id = ice_get_hw_vsi_num(hw, vsi_handle); list_for_each_entry(itr, list_head, list_entry) { struct ice_fltr_list_entry f_entry; f_entry.fltr_info = itr->fltr_info; if (itr->vsi_count < 2 && recp_id != ICE_SW_LKUP_VLAN && itr->fltr_info.vsi_handle == vsi_handle) { /* update the src in case it is VSI num */ if (f_entry.fltr_info.src_id == ICE_SRC_ID_VSI) f_entry.fltr_info.src = hw_vsi_id; status = ice_add_rule_internal(hw, recp_id, &f_entry); if (status) goto end; continue; } if (!itr->vsi_list_info || !test_bit(vsi_handle, itr->vsi_list_info->vsi_map)) continue; /* Clearing it so that the logic can add it back */ clear_bit(vsi_handle, itr->vsi_list_info->vsi_map); f_entry.fltr_info.vsi_handle = vsi_handle; f_entry.fltr_info.fltr_act = ICE_FWD_TO_VSI; /* update the src in case it is VSI num */ if (f_entry.fltr_info.src_id == ICE_SRC_ID_VSI) f_entry.fltr_info.src = hw_vsi_id; if (recp_id == ICE_SW_LKUP_VLAN) status = ice_add_vlan_internal(hw, &f_entry); else status = ice_add_rule_internal(hw, recp_id, &f_entry); if (status) goto end; } end: return status; } /** * ice_adv_rem_update_vsi_list * @hw: pointer to the hardware structure * @vsi_handle: VSI handle of the VSI to remove * @fm_list: filter management entry for which the VSI list management needs to * be done */ static int ice_adv_rem_update_vsi_list(struct ice_hw *hw, u16 vsi_handle, struct ice_adv_fltr_mgmt_list_entry *fm_list) { struct ice_vsi_list_map_info *vsi_list_info; enum ice_sw_lkup_type lkup_type; u16 vsi_list_id; int status; if (fm_list->rule_info.sw_act.fltr_act != ICE_FWD_TO_VSI_LIST || fm_list->vsi_count == 0) return -EINVAL; /* A rule with the VSI being removed does not exist */ if (!test_bit(vsi_handle, fm_list->vsi_list_info->vsi_map)) return -ENOENT; lkup_type = ICE_SW_LKUP_LAST; vsi_list_id = fm_list->rule_info.sw_act.fwd_id.vsi_list_id; status = ice_update_vsi_list_rule(hw, &vsi_handle, 1, vsi_list_id, true, ice_aqc_opc_update_sw_rules, lkup_type); if (status) return status; fm_list->vsi_count--; clear_bit(vsi_handle, fm_list->vsi_list_info->vsi_map); vsi_list_info = fm_list->vsi_list_info; if (fm_list->vsi_count == 1) { struct ice_fltr_info tmp_fltr; u16 rem_vsi_handle; rem_vsi_handle = find_first_bit(vsi_list_info->vsi_map, ICE_MAX_VSI); if (!ice_is_vsi_valid(hw, rem_vsi_handle)) return -EIO; /* Make sure VSI list is empty before removing it below */ status = ice_update_vsi_list_rule(hw, &rem_vsi_handle, 1, vsi_list_id, true, ice_aqc_opc_update_sw_rules, lkup_type); if (status) return status; memset(&tmp_fltr, 0, sizeof(tmp_fltr)); tmp_fltr.flag = fm_list->rule_info.sw_act.flag; tmp_fltr.fltr_rule_id = fm_list->rule_info.fltr_rule_id; fm_list->rule_info.sw_act.fltr_act = ICE_FWD_TO_VSI; tmp_fltr.fltr_act = ICE_FWD_TO_VSI; tmp_fltr.fwd_id.hw_vsi_id = ice_get_hw_vsi_num(hw, rem_vsi_handle); fm_list->rule_info.sw_act.fwd_id.hw_vsi_id = ice_get_hw_vsi_num(hw, rem_vsi_handle); fm_list->rule_info.sw_act.vsi_handle = rem_vsi_handle; /* Update the previous switch rule of "MAC forward to VSI" to * "MAC fwd to VSI list" */ status = ice_update_pkt_fwd_rule(hw, &tmp_fltr); if (status) { ice_debug(hw, ICE_DBG_SW, "Failed to update pkt fwd rule to FWD_TO_VSI on HW VSI %d, error %d\n", tmp_fltr.fwd_id.hw_vsi_id, status); return status; } fm_list->vsi_list_info->ref_cnt--; /* Remove the VSI list since it is no longer used */ status = ice_remove_vsi_list_rule(hw, vsi_list_id, lkup_type); if (status) { ice_debug(hw, ICE_DBG_SW, "Failed to remove VSI list %d, error %d\n", vsi_list_id, status); return status; } list_del(&vsi_list_info->list_entry); devm_kfree(ice_hw_to_dev(hw), vsi_list_info); fm_list->vsi_list_info = NULL; } return status; } /** * ice_rem_adv_rule - removes existing advanced switch rule * @hw: pointer to the hardware structure * @lkups: information on the words that needs to be looked up. All words * together makes one recipe * @lkups_cnt: num of entries in the lkups array * @rinfo: Its the pointer to the rule information for the rule * * This function can be used to remove 1 rule at a time. The lkups is * used to describe all the words that forms the "lookup" portion of the * rule. These words can span multiple protocols. Callers to this function * need to pass in a list of protocol headers with lookup information along * and mask that determines which words are valid from the given protocol * header. rinfo describes other information related to this rule such as * forwarding IDs, priority of this rule, etc. */ static int ice_rem_adv_rule(struct ice_hw *hw, struct ice_adv_lkup_elem *lkups, u16 lkups_cnt, struct ice_adv_rule_info *rinfo) { struct ice_adv_fltr_mgmt_list_entry *list_elem; struct ice_prot_lkup_ext lkup_exts; bool remove_rule = false; struct mutex *rule_lock; /* Lock to protect filter rule list */ u16 i, rid, vsi_handle; int status = 0; memset(&lkup_exts, 0, sizeof(lkup_exts)); for (i = 0; i < lkups_cnt; i++) { u16 count; if (lkups[i].type >= ICE_PROTOCOL_LAST) return -EIO; count = ice_fill_valid_words(&lkups[i], &lkup_exts); if (!count) return -EIO; } rid = ice_find_recp(hw, &lkup_exts, rinfo); /* If did not find a recipe that match the existing criteria */ if (rid == ICE_MAX_NUM_RECIPES) return -EINVAL; rule_lock = &hw->switch_info->recp_list[rid].filt_rule_lock; list_elem = ice_find_adv_rule_entry(hw, lkups, lkups_cnt, rid, rinfo); /* the rule is already removed */ if (!list_elem) return 0; mutex_lock(rule_lock); if (list_elem->rule_info.sw_act.fltr_act != ICE_FWD_TO_VSI_LIST) { remove_rule = true; } else if (list_elem->vsi_count > 1) { remove_rule = false; vsi_handle = rinfo->sw_act.vsi_handle; status = ice_adv_rem_update_vsi_list(hw, vsi_handle, list_elem); } else { vsi_handle = rinfo->sw_act.vsi_handle; status = ice_adv_rem_update_vsi_list(hw, vsi_handle, list_elem); if (status) { mutex_unlock(rule_lock); return status; } if (list_elem->vsi_count == 0) remove_rule = true; } mutex_unlock(rule_lock); if (remove_rule) { struct ice_sw_rule_lkup_rx_tx *s_rule; u16 rule_buf_sz; rule_buf_sz = ICE_SW_RULE_RX_TX_NO_HDR_SIZE(s_rule); s_rule = kzalloc(rule_buf_sz, GFP_KERNEL); if (!s_rule) return -ENOMEM; s_rule->act = 0; s_rule->index = cpu_to_le16(list_elem->rule_info.fltr_rule_id); s_rule->hdr_len = 0; status = ice_aq_sw_rules(hw, (struct ice_aqc_sw_rules *)s_rule, rule_buf_sz, 1, ice_aqc_opc_remove_sw_rules, NULL); if (!status || status == -ENOENT) { struct ice_switch_info *sw = hw->switch_info; mutex_lock(rule_lock); list_del(&list_elem->list_entry); devm_kfree(ice_hw_to_dev(hw), list_elem->lkups); devm_kfree(ice_hw_to_dev(hw), list_elem); mutex_unlock(rule_lock); if (list_empty(&sw->recp_list[rid].filt_rules)) sw->recp_list[rid].adv_rule = false; } kfree(s_rule); } return status; } /** * ice_rem_adv_rule_by_id - removes existing advanced switch rule by ID * @hw: pointer to the hardware structure * @remove_entry: data struct which holds rule_id, VSI handle and recipe ID * * This function is used to remove 1 rule at a time. The removal is based on * the remove_entry parameter. This function will remove rule for a given * vsi_handle with a given rule_id which is passed as parameter in remove_entry */ int ice_rem_adv_rule_by_id(struct ice_hw *hw, struct ice_rule_query_data *remove_entry) { struct ice_adv_fltr_mgmt_list_entry *list_itr; struct list_head *list_head; struct ice_adv_rule_info rinfo; struct ice_switch_info *sw; sw = hw->switch_info; if (!sw->recp_list[remove_entry->rid].recp_created) return -EINVAL; list_head = &sw->recp_list[remove_entry->rid].filt_rules; list_for_each_entry(list_itr, list_head, list_entry) { if (list_itr->rule_info.fltr_rule_id == remove_entry->rule_id) { rinfo = list_itr->rule_info; rinfo.sw_act.vsi_handle = remove_entry->vsi_handle; return ice_rem_adv_rule(hw, list_itr->lkups, list_itr->lkups_cnt, &rinfo); } } /* either list is empty or unable to find rule */ return -ENOENT; } /** * ice_replay_vsi_adv_rule - Replay advanced rule for requested VSI * @hw: pointer to the hardware structure * @vsi_handle: driver VSI handle * @list_head: list for which filters need to be replayed * * Replay the advanced rule for the given VSI. */ static int ice_replay_vsi_adv_rule(struct ice_hw *hw, u16 vsi_handle, struct list_head *list_head) { struct ice_rule_query_data added_entry = { 0 }; struct ice_adv_fltr_mgmt_list_entry *adv_fltr; int status = 0; if (list_empty(list_head)) return status; list_for_each_entry(adv_fltr, list_head, list_entry) { struct ice_adv_rule_info *rinfo = &adv_fltr->rule_info; u16 lk_cnt = adv_fltr->lkups_cnt; if (vsi_handle != rinfo->sw_act.vsi_handle) continue; status = ice_add_adv_rule(hw, adv_fltr->lkups, lk_cnt, rinfo, &added_entry); if (status) break; } return status; } /** * ice_replay_vsi_all_fltr - replay all filters stored in bookkeeping lists * @hw: pointer to the hardware structure * @vsi_handle: driver VSI handle * * Replays filters for requested VSI via vsi_handle. */ int ice_replay_vsi_all_fltr(struct ice_hw *hw, u16 vsi_handle) { struct ice_switch_info *sw = hw->switch_info; int status; u8 i; for (i = 0; i < ICE_MAX_NUM_RECIPES; i++) { struct list_head *head; head = &sw->recp_list[i].filt_replay_rules; if (!sw->recp_list[i].adv_rule) status = ice_replay_vsi_fltr(hw, vsi_handle, i, head); else status = ice_replay_vsi_adv_rule(hw, vsi_handle, head); if (status) return status; } return status; } /** * ice_rm_all_sw_replay_rule_info - deletes filter replay rules * @hw: pointer to the HW struct * * Deletes the filter replay rules. */ void ice_rm_all_sw_replay_rule_info(struct ice_hw *hw) { struct ice_switch_info *sw = hw->switch_info; u8 i; if (!sw) return; for (i = 0; i < ICE_MAX_NUM_RECIPES; i++) { if (!list_empty(&sw->recp_list[i].filt_replay_rules)) { struct list_head *l_head; l_head = &sw->recp_list[i].filt_replay_rules; if (!sw->recp_list[i].adv_rule) ice_rem_sw_rule_info(hw, l_head); else ice_rem_adv_rule_info(hw, l_head); } } }
linux-master
drivers/net/ethernet/intel/ice/ice_switch.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2019, Intel Corporation. */ #include "ice_common.h" #include "ice_sched.h" #include "ice_dcb.h" /** * ice_aq_get_lldp_mib * @hw: pointer to the HW struct * @bridge_type: type of bridge requested * @mib_type: Local, Remote or both Local and Remote MIBs * @buf: pointer to the caller-supplied buffer to store the MIB block * @buf_size: size of the buffer (in bytes) * @local_len: length of the returned Local LLDP MIB * @remote_len: length of the returned Remote LLDP MIB * @cd: pointer to command details structure or NULL * * Requests the complete LLDP MIB (entire packet). (0x0A00) */ static int ice_aq_get_lldp_mib(struct ice_hw *hw, u8 bridge_type, u8 mib_type, void *buf, u16 buf_size, u16 *local_len, u16 *remote_len, struct ice_sq_cd *cd) { struct ice_aqc_lldp_get_mib *cmd; struct ice_aq_desc desc; int status; cmd = &desc.params.lldp_get_mib; if (buf_size == 0 || !buf) return -EINVAL; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_lldp_get_mib); cmd->type = mib_type & ICE_AQ_LLDP_MIB_TYPE_M; cmd->type |= (bridge_type << ICE_AQ_LLDP_BRID_TYPE_S) & ICE_AQ_LLDP_BRID_TYPE_M; desc.datalen = cpu_to_le16(buf_size); status = ice_aq_send_cmd(hw, &desc, buf, buf_size, cd); if (!status) { if (local_len) *local_len = le16_to_cpu(cmd->local_len); if (remote_len) *remote_len = le16_to_cpu(cmd->remote_len); } return status; } /** * ice_aq_cfg_lldp_mib_change * @hw: pointer to the HW struct * @ena_update: Enable or Disable event posting * @cd: pointer to command details structure or NULL * * Enable or Disable posting of an event on ARQ when LLDP MIB * associated with the interface changes (0x0A01) */ static int ice_aq_cfg_lldp_mib_change(struct ice_hw *hw, bool ena_update, struct ice_sq_cd *cd) { struct ice_aqc_lldp_set_mib_change *cmd; struct ice_aq_desc desc; cmd = &desc.params.lldp_set_event; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_lldp_set_mib_change); if (!ena_update) cmd->command |= ICE_AQ_LLDP_MIB_UPDATE_DIS; else cmd->command |= FIELD_PREP(ICE_AQ_LLDP_MIB_PENDING_M, ICE_AQ_LLDP_MIB_PENDING_ENABLE); return ice_aq_send_cmd(hw, &desc, NULL, 0, cd); } /** * ice_aq_stop_lldp * @hw: pointer to the HW struct * @shutdown_lldp_agent: True if LLDP Agent needs to be Shutdown * False if LLDP Agent needs to be Stopped * @persist: True if Stop/Shutdown of LLDP Agent needs to be persistent across * reboots * @cd: pointer to command details structure or NULL * * Stop or Shutdown the embedded LLDP Agent (0x0A05) */ int ice_aq_stop_lldp(struct ice_hw *hw, bool shutdown_lldp_agent, bool persist, struct ice_sq_cd *cd) { struct ice_aqc_lldp_stop *cmd; struct ice_aq_desc desc; cmd = &desc.params.lldp_stop; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_lldp_stop); if (shutdown_lldp_agent) cmd->command |= ICE_AQ_LLDP_AGENT_SHUTDOWN; if (persist) cmd->command |= ICE_AQ_LLDP_AGENT_PERSIST_DIS; return ice_aq_send_cmd(hw, &desc, NULL, 0, cd); } /** * ice_aq_start_lldp * @hw: pointer to the HW struct * @persist: True if Start of LLDP Agent needs to be persistent across reboots * @cd: pointer to command details structure or NULL * * Start the embedded LLDP Agent on all ports. (0x0A06) */ int ice_aq_start_lldp(struct ice_hw *hw, bool persist, struct ice_sq_cd *cd) { struct ice_aqc_lldp_start *cmd; struct ice_aq_desc desc; cmd = &desc.params.lldp_start; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_lldp_start); cmd->command = ICE_AQ_LLDP_AGENT_START; if (persist) cmd->command |= ICE_AQ_LLDP_AGENT_PERSIST_ENA; return ice_aq_send_cmd(hw, &desc, NULL, 0, cd); } /** * ice_get_dcbx_status * @hw: pointer to the HW struct * * Get the DCBX status from the Firmware */ static u8 ice_get_dcbx_status(struct ice_hw *hw) { u32 reg; reg = rd32(hw, PRTDCB_GENS); return (u8)((reg & PRTDCB_GENS_DCBX_STATUS_M) >> PRTDCB_GENS_DCBX_STATUS_S); } /** * ice_parse_ieee_ets_common_tlv * @buf: Data buffer to be parsed for ETS CFG/REC data * @ets_cfg: Container to store parsed data * * Parses the common data of IEEE 802.1Qaz ETS CFG/REC TLV */ static void ice_parse_ieee_ets_common_tlv(u8 *buf, struct ice_dcb_ets_cfg *ets_cfg) { u8 offset = 0; int i; /* Priority Assignment Table (4 octets) * Octets:| 1 | 2 | 3 | 4 | * ----------------------------------------- * |pri0|pri1|pri2|pri3|pri4|pri5|pri6|pri7| * ----------------------------------------- * Bits:|7 4|3 0|7 4|3 0|7 4|3 0|7 4|3 0| * ----------------------------------------- */ for (i = 0; i < 4; i++) { ets_cfg->prio_table[i * 2] = ((buf[offset] & ICE_IEEE_ETS_PRIO_1_M) >> ICE_IEEE_ETS_PRIO_1_S); ets_cfg->prio_table[i * 2 + 1] = ((buf[offset] & ICE_IEEE_ETS_PRIO_0_M) >> ICE_IEEE_ETS_PRIO_0_S); offset++; } /* TC Bandwidth Table (8 octets) * Octets:| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * --------------------------------- * |tc0|tc1|tc2|tc3|tc4|tc5|tc6|tc7| * --------------------------------- * * TSA Assignment Table (8 octets) * Octets:| 9 | 10| 11| 12| 13| 14| 15| 16| * --------------------------------- * |tc0|tc1|tc2|tc3|tc4|tc5|tc6|tc7| * --------------------------------- */ ice_for_each_traffic_class(i) { ets_cfg->tcbwtable[i] = buf[offset]; ets_cfg->tsatable[i] = buf[ICE_MAX_TRAFFIC_CLASS + offset++]; } } /** * ice_parse_ieee_etscfg_tlv * @tlv: IEEE 802.1Qaz ETS CFG TLV * @dcbcfg: Local store to update ETS CFG data * * Parses IEEE 802.1Qaz ETS CFG TLV */ static void ice_parse_ieee_etscfg_tlv(struct ice_lldp_org_tlv *tlv, struct ice_dcbx_cfg *dcbcfg) { struct ice_dcb_ets_cfg *etscfg; u8 *buf = tlv->tlvinfo; /* First Octet post subtype * -------------------------- * |will-|CBS | Re- | Max | * |ing | |served| TCs | * -------------------------- * |1bit | 1bit|3 bits|3bits| */ etscfg = &dcbcfg->etscfg; etscfg->willing = ((buf[0] & ICE_IEEE_ETS_WILLING_M) >> ICE_IEEE_ETS_WILLING_S); etscfg->cbs = ((buf[0] & ICE_IEEE_ETS_CBS_M) >> ICE_IEEE_ETS_CBS_S); etscfg->maxtcs = ((buf[0] & ICE_IEEE_ETS_MAXTC_M) >> ICE_IEEE_ETS_MAXTC_S); /* Begin parsing at Priority Assignment Table (offset 1 in buf) */ ice_parse_ieee_ets_common_tlv(&buf[1], etscfg); } /** * ice_parse_ieee_etsrec_tlv * @tlv: IEEE 802.1Qaz ETS REC TLV * @dcbcfg: Local store to update ETS REC data * * Parses IEEE 802.1Qaz ETS REC TLV */ static void ice_parse_ieee_etsrec_tlv(struct ice_lldp_org_tlv *tlv, struct ice_dcbx_cfg *dcbcfg) { u8 *buf = tlv->tlvinfo; /* Begin parsing at Priority Assignment Table (offset 1 in buf) */ ice_parse_ieee_ets_common_tlv(&buf[1], &dcbcfg->etsrec); } /** * ice_parse_ieee_pfccfg_tlv * @tlv: IEEE 802.1Qaz PFC CFG TLV * @dcbcfg: Local store to update PFC CFG data * * Parses IEEE 802.1Qaz PFC CFG TLV */ static void ice_parse_ieee_pfccfg_tlv(struct ice_lldp_org_tlv *tlv, struct ice_dcbx_cfg *dcbcfg) { u8 *buf = tlv->tlvinfo; /* ---------------------------------------- * |will-|MBC | Re- | PFC | PFC Enable | * |ing | |served| cap | | * ----------------------------------------- * |1bit | 1bit|2 bits|4bits| 1 octet | */ dcbcfg->pfc.willing = ((buf[0] & ICE_IEEE_PFC_WILLING_M) >> ICE_IEEE_PFC_WILLING_S); dcbcfg->pfc.mbc = ((buf[0] & ICE_IEEE_PFC_MBC_M) >> ICE_IEEE_PFC_MBC_S); dcbcfg->pfc.pfccap = ((buf[0] & ICE_IEEE_PFC_CAP_M) >> ICE_IEEE_PFC_CAP_S); dcbcfg->pfc.pfcena = buf[1]; } /** * ice_parse_ieee_app_tlv * @tlv: IEEE 802.1Qaz APP TLV * @dcbcfg: Local store to update APP PRIO data * * Parses IEEE 802.1Qaz APP PRIO TLV */ static void ice_parse_ieee_app_tlv(struct ice_lldp_org_tlv *tlv, struct ice_dcbx_cfg *dcbcfg) { u16 offset = 0; u16 typelen; int i = 0; u16 len; u8 *buf; typelen = ntohs(tlv->typelen); len = ((typelen & ICE_LLDP_TLV_LEN_M) >> ICE_LLDP_TLV_LEN_S); buf = tlv->tlvinfo; /* Removing sizeof(ouisubtype) and reserved byte from len. * Remaining len div 3 is number of APP TLVs. */ len -= (sizeof(tlv->ouisubtype) + 1); /* Move offset to App Priority Table */ offset++; /* Application Priority Table (3 octets) * Octets:| 1 | 2 | 3 | * ----------------------------------------- * |Priority|Rsrvd| Sel | Protocol ID | * ----------------------------------------- * Bits:|23 21|20 19|18 16|15 0| * ----------------------------------------- */ while (offset < len) { dcbcfg->app[i].priority = ((buf[offset] & ICE_IEEE_APP_PRIO_M) >> ICE_IEEE_APP_PRIO_S); dcbcfg->app[i].selector = ((buf[offset] & ICE_IEEE_APP_SEL_M) >> ICE_IEEE_APP_SEL_S); dcbcfg->app[i].prot_id = (buf[offset + 1] << 0x8) | buf[offset + 2]; /* Move to next app */ offset += 3; i++; if (i >= ICE_DCBX_MAX_APPS) break; } dcbcfg->numapps = i; } /** * ice_parse_ieee_tlv * @tlv: IEEE 802.1Qaz TLV * @dcbcfg: Local store to update ETS REC data * * Get the TLV subtype and send it to parsing function * based on the subtype value */ static void ice_parse_ieee_tlv(struct ice_lldp_org_tlv *tlv, struct ice_dcbx_cfg *dcbcfg) { u32 ouisubtype; u8 subtype; ouisubtype = ntohl(tlv->ouisubtype); subtype = (u8)((ouisubtype & ICE_LLDP_TLV_SUBTYPE_M) >> ICE_LLDP_TLV_SUBTYPE_S); switch (subtype) { case ICE_IEEE_SUBTYPE_ETS_CFG: ice_parse_ieee_etscfg_tlv(tlv, dcbcfg); break; case ICE_IEEE_SUBTYPE_ETS_REC: ice_parse_ieee_etsrec_tlv(tlv, dcbcfg); break; case ICE_IEEE_SUBTYPE_PFC_CFG: ice_parse_ieee_pfccfg_tlv(tlv, dcbcfg); break; case ICE_IEEE_SUBTYPE_APP_PRI: ice_parse_ieee_app_tlv(tlv, dcbcfg); break; default: break; } } /** * ice_parse_cee_pgcfg_tlv * @tlv: CEE DCBX PG CFG TLV * @dcbcfg: Local store to update ETS CFG data * * Parses CEE DCBX PG CFG TLV */ static void ice_parse_cee_pgcfg_tlv(struct ice_cee_feat_tlv *tlv, struct ice_dcbx_cfg *dcbcfg) { struct ice_dcb_ets_cfg *etscfg; u8 *buf = tlv->tlvinfo; u16 offset = 0; int i; etscfg = &dcbcfg->etscfg; if (tlv->en_will_err & ICE_CEE_FEAT_TLV_WILLING_M) etscfg->willing = 1; etscfg->cbs = 0; /* Priority Group Table (4 octets) * Octets:| 1 | 2 | 3 | 4 | * ----------------------------------------- * |pri0|pri1|pri2|pri3|pri4|pri5|pri6|pri7| * ----------------------------------------- * Bits:|7 4|3 0|7 4|3 0|7 4|3 0|7 4|3 0| * ----------------------------------------- */ for (i = 0; i < 4; i++) { etscfg->prio_table[i * 2] = ((buf[offset] & ICE_CEE_PGID_PRIO_1_M) >> ICE_CEE_PGID_PRIO_1_S); etscfg->prio_table[i * 2 + 1] = ((buf[offset] & ICE_CEE_PGID_PRIO_0_M) >> ICE_CEE_PGID_PRIO_0_S); offset++; } /* PG Percentage Table (8 octets) * Octets:| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * --------------------------------- * |pg0|pg1|pg2|pg3|pg4|pg5|pg6|pg7| * --------------------------------- */ ice_for_each_traffic_class(i) { etscfg->tcbwtable[i] = buf[offset++]; if (etscfg->prio_table[i] == ICE_CEE_PGID_STRICT) dcbcfg->etscfg.tsatable[i] = ICE_IEEE_TSA_STRICT; else dcbcfg->etscfg.tsatable[i] = ICE_IEEE_TSA_ETS; } /* Number of TCs supported (1 octet) */ etscfg->maxtcs = buf[offset]; } /** * ice_parse_cee_pfccfg_tlv * @tlv: CEE DCBX PFC CFG TLV * @dcbcfg: Local store to update PFC CFG data * * Parses CEE DCBX PFC CFG TLV */ static void ice_parse_cee_pfccfg_tlv(struct ice_cee_feat_tlv *tlv, struct ice_dcbx_cfg *dcbcfg) { u8 *buf = tlv->tlvinfo; if (tlv->en_will_err & ICE_CEE_FEAT_TLV_WILLING_M) dcbcfg->pfc.willing = 1; /* ------------------------ * | PFC Enable | PFC TCs | * ------------------------ * | 1 octet | 1 octet | */ dcbcfg->pfc.pfcena = buf[0]; dcbcfg->pfc.pfccap = buf[1]; } /** * ice_parse_cee_app_tlv * @tlv: CEE DCBX APP TLV * @dcbcfg: Local store to update APP PRIO data * * Parses CEE DCBX APP PRIO TLV */ static void ice_parse_cee_app_tlv(struct ice_cee_feat_tlv *tlv, struct ice_dcbx_cfg *dcbcfg) { u16 len, typelen, offset = 0; struct ice_cee_app_prio *app; u8 i; typelen = ntohs(tlv->hdr.typelen); len = ((typelen & ICE_LLDP_TLV_LEN_M) >> ICE_LLDP_TLV_LEN_S); dcbcfg->numapps = len / sizeof(*app); if (!dcbcfg->numapps) return; if (dcbcfg->numapps > ICE_DCBX_MAX_APPS) dcbcfg->numapps = ICE_DCBX_MAX_APPS; for (i = 0; i < dcbcfg->numapps; i++) { u8 up, selector; app = (struct ice_cee_app_prio *)(tlv->tlvinfo + offset); for (up = 0; up < ICE_MAX_USER_PRIORITY; up++) if (app->prio_map & BIT(up)) break; dcbcfg->app[i].priority = up; /* Get Selector from lower 2 bits, and convert to IEEE */ selector = (app->upper_oui_sel & ICE_CEE_APP_SELECTOR_M); switch (selector) { case ICE_CEE_APP_SEL_ETHTYPE: dcbcfg->app[i].selector = ICE_APP_SEL_ETHTYPE; break; case ICE_CEE_APP_SEL_TCPIP: dcbcfg->app[i].selector = ICE_APP_SEL_TCPIP; break; default: /* Keep selector as it is for unknown types */ dcbcfg->app[i].selector = selector; } dcbcfg->app[i].prot_id = ntohs(app->protocol); /* Move to next app */ offset += sizeof(*app); } } /** * ice_parse_cee_tlv * @tlv: CEE DCBX TLV * @dcbcfg: Local store to update DCBX config data * * Get the TLV subtype and send it to parsing function * based on the subtype value */ static void ice_parse_cee_tlv(struct ice_lldp_org_tlv *tlv, struct ice_dcbx_cfg *dcbcfg) { struct ice_cee_feat_tlv *sub_tlv; u8 subtype, feat_tlv_count = 0; u16 len, tlvlen, typelen; u32 ouisubtype; ouisubtype = ntohl(tlv->ouisubtype); subtype = (u8)((ouisubtype & ICE_LLDP_TLV_SUBTYPE_M) >> ICE_LLDP_TLV_SUBTYPE_S); /* Return if not CEE DCBX */ if (subtype != ICE_CEE_DCBX_TYPE) return; typelen = ntohs(tlv->typelen); tlvlen = ((typelen & ICE_LLDP_TLV_LEN_M) >> ICE_LLDP_TLV_LEN_S); len = sizeof(tlv->typelen) + sizeof(ouisubtype) + sizeof(struct ice_cee_ctrl_tlv); /* Return if no CEE DCBX Feature TLVs */ if (tlvlen <= len) return; sub_tlv = (struct ice_cee_feat_tlv *)((char *)tlv + len); while (feat_tlv_count < ICE_CEE_MAX_FEAT_TYPE) { u16 sublen; typelen = ntohs(sub_tlv->hdr.typelen); sublen = ((typelen & ICE_LLDP_TLV_LEN_M) >> ICE_LLDP_TLV_LEN_S); subtype = (u8)((typelen & ICE_LLDP_TLV_TYPE_M) >> ICE_LLDP_TLV_TYPE_S); switch (subtype) { case ICE_CEE_SUBTYPE_PG_CFG: ice_parse_cee_pgcfg_tlv(sub_tlv, dcbcfg); break; case ICE_CEE_SUBTYPE_PFC_CFG: ice_parse_cee_pfccfg_tlv(sub_tlv, dcbcfg); break; case ICE_CEE_SUBTYPE_APP_PRI: ice_parse_cee_app_tlv(sub_tlv, dcbcfg); break; default: return; /* Invalid Sub-type return */ } feat_tlv_count++; /* Move to next sub TLV */ sub_tlv = (struct ice_cee_feat_tlv *) ((char *)sub_tlv + sizeof(sub_tlv->hdr.typelen) + sublen); } } /** * ice_parse_org_tlv * @tlv: Organization specific TLV * @dcbcfg: Local store to update ETS REC data * * Currently IEEE 802.1Qaz and CEE DCBX TLV are supported, others * will be returned */ static void ice_parse_org_tlv(struct ice_lldp_org_tlv *tlv, struct ice_dcbx_cfg *dcbcfg) { u32 ouisubtype; u32 oui; ouisubtype = ntohl(tlv->ouisubtype); oui = ((ouisubtype & ICE_LLDP_TLV_OUI_M) >> ICE_LLDP_TLV_OUI_S); switch (oui) { case ICE_IEEE_8021QAZ_OUI: ice_parse_ieee_tlv(tlv, dcbcfg); break; case ICE_CEE_DCBX_OUI: ice_parse_cee_tlv(tlv, dcbcfg); break; default: break; /* Other OUIs not supported */ } } /** * ice_lldp_to_dcb_cfg * @lldpmib: LLDPDU to be parsed * @dcbcfg: store for LLDPDU data * * Parse DCB configuration from the LLDPDU */ static int ice_lldp_to_dcb_cfg(u8 *lldpmib, struct ice_dcbx_cfg *dcbcfg) { struct ice_lldp_org_tlv *tlv; u16 offset = 0; int ret = 0; u16 typelen; u16 type; u16 len; if (!lldpmib || !dcbcfg) return -EINVAL; /* set to the start of LLDPDU */ lldpmib += ETH_HLEN; tlv = (struct ice_lldp_org_tlv *)lldpmib; while (1) { typelen = ntohs(tlv->typelen); type = ((typelen & ICE_LLDP_TLV_TYPE_M) >> ICE_LLDP_TLV_TYPE_S); len = ((typelen & ICE_LLDP_TLV_LEN_M) >> ICE_LLDP_TLV_LEN_S); offset += sizeof(typelen) + len; /* END TLV or beyond LLDPDU size */ if (type == ICE_TLV_TYPE_END || offset > ICE_LLDPDU_SIZE) break; switch (type) { case ICE_TLV_TYPE_ORG: ice_parse_org_tlv(tlv, dcbcfg); break; default: break; } /* Move to next TLV */ tlv = (struct ice_lldp_org_tlv *) ((char *)tlv + sizeof(tlv->typelen) + len); } return ret; } /** * ice_aq_get_dcb_cfg * @hw: pointer to the HW struct * @mib_type: MIB type for the query * @bridgetype: bridge type for the query (remote) * @dcbcfg: store for LLDPDU data * * Query DCB configuration from the firmware */ int ice_aq_get_dcb_cfg(struct ice_hw *hw, u8 mib_type, u8 bridgetype, struct ice_dcbx_cfg *dcbcfg) { u8 *lldpmib; int ret; /* Allocate the LLDPDU */ lldpmib = devm_kzalloc(ice_hw_to_dev(hw), ICE_LLDPDU_SIZE, GFP_KERNEL); if (!lldpmib) return -ENOMEM; ret = ice_aq_get_lldp_mib(hw, bridgetype, mib_type, (void *)lldpmib, ICE_LLDPDU_SIZE, NULL, NULL, NULL); if (!ret) /* Parse LLDP MIB to get DCB configuration */ ret = ice_lldp_to_dcb_cfg(lldpmib, dcbcfg); devm_kfree(ice_hw_to_dev(hw), lldpmib); return ret; } /** * ice_aq_start_stop_dcbx - Start/Stop DCBX service in FW * @hw: pointer to the HW struct * @start_dcbx_agent: True if DCBX Agent needs to be started * False if DCBX Agent needs to be stopped * @dcbx_agent_status: FW indicates back the DCBX agent status * True if DCBX Agent is active * False if DCBX Agent is stopped * @cd: pointer to command details structure or NULL * * Start/Stop the embedded dcbx Agent. In case that this wrapper function * returns 0, caller will need to check if FW returns back the same * value as stated in dcbx_agent_status, and react accordingly. (0x0A09) */ int ice_aq_start_stop_dcbx(struct ice_hw *hw, bool start_dcbx_agent, bool *dcbx_agent_status, struct ice_sq_cd *cd) { struct ice_aqc_lldp_stop_start_specific_agent *cmd; struct ice_aq_desc desc; u16 opcode; int status; cmd = &desc.params.lldp_agent_ctrl; opcode = ice_aqc_opc_lldp_stop_start_specific_agent; ice_fill_dflt_direct_cmd_desc(&desc, opcode); if (start_dcbx_agent) cmd->command = ICE_AQC_START_STOP_AGENT_START_DCBX; status = ice_aq_send_cmd(hw, &desc, NULL, 0, cd); *dcbx_agent_status = false; if (!status && cmd->command == ICE_AQC_START_STOP_AGENT_START_DCBX) *dcbx_agent_status = true; return status; } /** * ice_aq_get_cee_dcb_cfg * @hw: pointer to the HW struct * @buff: response buffer that stores CEE operational configuration * @cd: pointer to command details structure or NULL * * Get CEE DCBX mode operational configuration from firmware (0x0A07) */ static int ice_aq_get_cee_dcb_cfg(struct ice_hw *hw, struct ice_aqc_get_cee_dcb_cfg_resp *buff, struct ice_sq_cd *cd) { struct ice_aq_desc desc; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_get_cee_dcb_cfg); return ice_aq_send_cmd(hw, &desc, (void *)buff, sizeof(*buff), cd); } /** * ice_aq_set_pfc_mode - Set PFC mode * @hw: pointer to the HW struct * @pfc_mode: value of PFC mode to set * @cd: pointer to command details structure or NULL * * This AQ call configures the PFC mode to DSCP-based PFC mode or * VLAN-based PFC (0x0303) */ int ice_aq_set_pfc_mode(struct ice_hw *hw, u8 pfc_mode, struct ice_sq_cd *cd) { struct ice_aqc_set_query_pfc_mode *cmd; struct ice_aq_desc desc; int status; if (pfc_mode > ICE_AQC_PFC_DSCP_BASED_PFC) return -EINVAL; cmd = &desc.params.set_query_pfc_mode; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_set_pfc_mode); cmd->pfc_mode = pfc_mode; status = ice_aq_send_cmd(hw, &desc, NULL, 0, cd); if (status) return status; /* FW will write the PFC mode set back into cmd->pfc_mode, but if DCB is * disabled, FW will write back 0 to cmd->pfc_mode. After the AQ has * been executed, check if cmd->pfc_mode is what was requested. If not, * return an error. */ if (cmd->pfc_mode != pfc_mode) return -EOPNOTSUPP; return 0; } /** * ice_cee_to_dcb_cfg * @cee_cfg: pointer to CEE configuration struct * @pi: port information structure * * Convert CEE configuration from firmware to DCB configuration */ static void ice_cee_to_dcb_cfg(struct ice_aqc_get_cee_dcb_cfg_resp *cee_cfg, struct ice_port_info *pi) { u32 status, tlv_status = le32_to_cpu(cee_cfg->tlv_status); u32 ice_aqc_cee_status_mask, ice_aqc_cee_status_shift, j; u8 i, err, sync, oper, app_index, ice_app_sel_type; u16 app_prio = le16_to_cpu(cee_cfg->oper_app_prio); u16 ice_aqc_cee_app_mask, ice_aqc_cee_app_shift; struct ice_dcbx_cfg *cmp_dcbcfg, *dcbcfg; u16 ice_app_prot_id_type; dcbcfg = &pi->qos_cfg.local_dcbx_cfg; dcbcfg->dcbx_mode = ICE_DCBX_MODE_CEE; dcbcfg->tlv_status = tlv_status; /* CEE PG data */ dcbcfg->etscfg.maxtcs = cee_cfg->oper_num_tc; /* Note that the FW creates the oper_prio_tc nibbles reversed * from those in the CEE Priority Group sub-TLV. */ for (i = 0; i < ICE_MAX_TRAFFIC_CLASS / 2; i++) { dcbcfg->etscfg.prio_table[i * 2] = ((cee_cfg->oper_prio_tc[i] & ICE_CEE_PGID_PRIO_0_M) >> ICE_CEE_PGID_PRIO_0_S); dcbcfg->etscfg.prio_table[i * 2 + 1] = ((cee_cfg->oper_prio_tc[i] & ICE_CEE_PGID_PRIO_1_M) >> ICE_CEE_PGID_PRIO_1_S); } ice_for_each_traffic_class(i) { dcbcfg->etscfg.tcbwtable[i] = cee_cfg->oper_tc_bw[i]; if (dcbcfg->etscfg.prio_table[i] == ICE_CEE_PGID_STRICT) { /* Map it to next empty TC */ dcbcfg->etscfg.prio_table[i] = cee_cfg->oper_num_tc - 1; dcbcfg->etscfg.tsatable[i] = ICE_IEEE_TSA_STRICT; } else { dcbcfg->etscfg.tsatable[i] = ICE_IEEE_TSA_ETS; } } /* CEE PFC data */ dcbcfg->pfc.pfcena = cee_cfg->oper_pfc_en; dcbcfg->pfc.pfccap = ICE_MAX_TRAFFIC_CLASS; /* CEE APP TLV data */ if (dcbcfg->app_mode == ICE_DCBX_APPS_NON_WILLING) cmp_dcbcfg = &pi->qos_cfg.desired_dcbx_cfg; else cmp_dcbcfg = &pi->qos_cfg.remote_dcbx_cfg; app_index = 0; for (i = 0; i < 3; i++) { if (i == 0) { /* FCoE APP */ ice_aqc_cee_status_mask = ICE_AQC_CEE_FCOE_STATUS_M; ice_aqc_cee_status_shift = ICE_AQC_CEE_FCOE_STATUS_S; ice_aqc_cee_app_mask = ICE_AQC_CEE_APP_FCOE_M; ice_aqc_cee_app_shift = ICE_AQC_CEE_APP_FCOE_S; ice_app_sel_type = ICE_APP_SEL_ETHTYPE; ice_app_prot_id_type = ETH_P_FCOE; } else if (i == 1) { /* iSCSI APP */ ice_aqc_cee_status_mask = ICE_AQC_CEE_ISCSI_STATUS_M; ice_aqc_cee_status_shift = ICE_AQC_CEE_ISCSI_STATUS_S; ice_aqc_cee_app_mask = ICE_AQC_CEE_APP_ISCSI_M; ice_aqc_cee_app_shift = ICE_AQC_CEE_APP_ISCSI_S; ice_app_sel_type = ICE_APP_SEL_TCPIP; ice_app_prot_id_type = ISCSI_LISTEN_PORT; for (j = 0; j < cmp_dcbcfg->numapps; j++) { u16 prot_id = cmp_dcbcfg->app[j].prot_id; u8 sel = cmp_dcbcfg->app[j].selector; if (sel == ICE_APP_SEL_TCPIP && (prot_id == ISCSI_LISTEN_PORT || prot_id == ICE_APP_PROT_ID_ISCSI_860)) { ice_app_prot_id_type = prot_id; break; } } } else { /* FIP APP */ ice_aqc_cee_status_mask = ICE_AQC_CEE_FIP_STATUS_M; ice_aqc_cee_status_shift = ICE_AQC_CEE_FIP_STATUS_S; ice_aqc_cee_app_mask = ICE_AQC_CEE_APP_FIP_M; ice_aqc_cee_app_shift = ICE_AQC_CEE_APP_FIP_S; ice_app_sel_type = ICE_APP_SEL_ETHTYPE; ice_app_prot_id_type = ETH_P_FIP; } status = (tlv_status & ice_aqc_cee_status_mask) >> ice_aqc_cee_status_shift; err = (status & ICE_TLV_STATUS_ERR) ? 1 : 0; sync = (status & ICE_TLV_STATUS_SYNC) ? 1 : 0; oper = (status & ICE_TLV_STATUS_OPER) ? 1 : 0; /* Add FCoE/iSCSI/FIP APP if Error is False and * Oper/Sync is True */ if (!err && sync && oper) { dcbcfg->app[app_index].priority = (app_prio & ice_aqc_cee_app_mask) >> ice_aqc_cee_app_shift; dcbcfg->app[app_index].selector = ice_app_sel_type; dcbcfg->app[app_index].prot_id = ice_app_prot_id_type; app_index++; } } dcbcfg->numapps = app_index; } /** * ice_get_ieee_or_cee_dcb_cfg * @pi: port information structure * @dcbx_mode: mode of DCBX (IEEE or CEE) * * Get IEEE or CEE mode DCB configuration from the Firmware */ static int ice_get_ieee_or_cee_dcb_cfg(struct ice_port_info *pi, u8 dcbx_mode) { struct ice_dcbx_cfg *dcbx_cfg = NULL; int ret; if (!pi) return -EINVAL; if (dcbx_mode == ICE_DCBX_MODE_IEEE) dcbx_cfg = &pi->qos_cfg.local_dcbx_cfg; else if (dcbx_mode == ICE_DCBX_MODE_CEE) dcbx_cfg = &pi->qos_cfg.desired_dcbx_cfg; /* Get Local DCB Config in case of ICE_DCBX_MODE_IEEE * or get CEE DCB Desired Config in case of ICE_DCBX_MODE_CEE */ ret = ice_aq_get_dcb_cfg(pi->hw, ICE_AQ_LLDP_MIB_LOCAL, ICE_AQ_LLDP_BRID_TYPE_NEAREST_BRID, dcbx_cfg); if (ret) goto out; /* Get Remote DCB Config */ dcbx_cfg = &pi->qos_cfg.remote_dcbx_cfg; ret = ice_aq_get_dcb_cfg(pi->hw, ICE_AQ_LLDP_MIB_REMOTE, ICE_AQ_LLDP_BRID_TYPE_NEAREST_BRID, dcbx_cfg); /* Don't treat ENOENT as an error for Remote MIBs */ if (pi->hw->adminq.sq_last_status == ICE_AQ_RC_ENOENT) ret = 0; out: return ret; } /** * ice_get_dcb_cfg * @pi: port information structure * * Get DCB configuration from the Firmware */ int ice_get_dcb_cfg(struct ice_port_info *pi) { struct ice_aqc_get_cee_dcb_cfg_resp cee_cfg; struct ice_dcbx_cfg *dcbx_cfg; int ret; if (!pi) return -EINVAL; ret = ice_aq_get_cee_dcb_cfg(pi->hw, &cee_cfg, NULL); if (!ret) { /* CEE mode */ ret = ice_get_ieee_or_cee_dcb_cfg(pi, ICE_DCBX_MODE_CEE); ice_cee_to_dcb_cfg(&cee_cfg, pi); } else if (pi->hw->adminq.sq_last_status == ICE_AQ_RC_ENOENT) { /* CEE mode not enabled try querying IEEE data */ dcbx_cfg = &pi->qos_cfg.local_dcbx_cfg; dcbx_cfg->dcbx_mode = ICE_DCBX_MODE_IEEE; ret = ice_get_ieee_or_cee_dcb_cfg(pi, ICE_DCBX_MODE_IEEE); } return ret; } /** * ice_get_dcb_cfg_from_mib_change * @pi: port information structure * @event: pointer to the admin queue receive event * * Set DCB configuration from received MIB Change event */ void ice_get_dcb_cfg_from_mib_change(struct ice_port_info *pi, struct ice_rq_event_info *event) { struct ice_dcbx_cfg *dcbx_cfg = &pi->qos_cfg.local_dcbx_cfg; struct ice_aqc_lldp_get_mib *mib; u8 change_type, dcbx_mode; mib = (struct ice_aqc_lldp_get_mib *)&event->desc.params.raw; change_type = FIELD_GET(ICE_AQ_LLDP_MIB_TYPE_M, mib->type); if (change_type == ICE_AQ_LLDP_MIB_REMOTE) dcbx_cfg = &pi->qos_cfg.remote_dcbx_cfg; dcbx_mode = FIELD_GET(ICE_AQ_LLDP_DCBX_M, mib->type); switch (dcbx_mode) { case ICE_AQ_LLDP_DCBX_IEEE: dcbx_cfg->dcbx_mode = ICE_DCBX_MODE_IEEE; ice_lldp_to_dcb_cfg(event->msg_buf, dcbx_cfg); break; case ICE_AQ_LLDP_DCBX_CEE: pi->qos_cfg.desired_dcbx_cfg = pi->qos_cfg.local_dcbx_cfg; ice_cee_to_dcb_cfg((struct ice_aqc_get_cee_dcb_cfg_resp *) event->msg_buf, pi); break; } } /** * ice_init_dcb * @hw: pointer to the HW struct * @enable_mib_change: enable MIB change event * * Update DCB configuration from the Firmware */ int ice_init_dcb(struct ice_hw *hw, bool enable_mib_change) { struct ice_qos_cfg *qos_cfg = &hw->port_info->qos_cfg; int ret = 0; if (!hw->func_caps.common_cap.dcb) return -EOPNOTSUPP; qos_cfg->is_sw_lldp = true; /* Get DCBX status */ qos_cfg->dcbx_status = ice_get_dcbx_status(hw); if (qos_cfg->dcbx_status == ICE_DCBX_STATUS_DONE || qos_cfg->dcbx_status == ICE_DCBX_STATUS_IN_PROGRESS || qos_cfg->dcbx_status == ICE_DCBX_STATUS_NOT_STARTED) { /* Get current DCBX configuration */ ret = ice_get_dcb_cfg(hw->port_info); if (ret) return ret; qos_cfg->is_sw_lldp = false; } else if (qos_cfg->dcbx_status == ICE_DCBX_STATUS_DIS) { return -EBUSY; } /* Configure the LLDP MIB change event */ if (enable_mib_change) { ret = ice_aq_cfg_lldp_mib_change(hw, true, NULL); if (ret) qos_cfg->is_sw_lldp = true; } return ret; } /** * ice_cfg_lldp_mib_change * @hw: pointer to the HW struct * @ena_mib: enable/disable MIB change event * * Configure (disable/enable) MIB */ int ice_cfg_lldp_mib_change(struct ice_hw *hw, bool ena_mib) { struct ice_qos_cfg *qos_cfg = &hw->port_info->qos_cfg; int ret; if (!hw->func_caps.common_cap.dcb) return -EOPNOTSUPP; /* Get DCBX status */ qos_cfg->dcbx_status = ice_get_dcbx_status(hw); if (qos_cfg->dcbx_status == ICE_DCBX_STATUS_DIS) return -EBUSY; ret = ice_aq_cfg_lldp_mib_change(hw, ena_mib, NULL); if (!ret) qos_cfg->is_sw_lldp = !ena_mib; return ret; } /** * ice_add_ieee_ets_common_tlv * @buf: Data buffer to be populated with ice_dcb_ets_cfg data * @ets_cfg: Container for ice_dcb_ets_cfg data * * Populate the TLV buffer with ice_dcb_ets_cfg data */ static void ice_add_ieee_ets_common_tlv(u8 *buf, struct ice_dcb_ets_cfg *ets_cfg) { u8 priority0, priority1; u8 offset = 0; int i; /* Priority Assignment Table (4 octets) * Octets:| 1 | 2 | 3 | 4 | * ----------------------------------------- * |pri0|pri1|pri2|pri3|pri4|pri5|pri6|pri7| * ----------------------------------------- * Bits:|7 4|3 0|7 4|3 0|7 4|3 0|7 4|3 0| * ----------------------------------------- */ for (i = 0; i < ICE_MAX_TRAFFIC_CLASS / 2; i++) { priority0 = ets_cfg->prio_table[i * 2] & 0xF; priority1 = ets_cfg->prio_table[i * 2 + 1] & 0xF; buf[offset] = (priority0 << ICE_IEEE_ETS_PRIO_1_S) | priority1; offset++; } /* TC Bandwidth Table (8 octets) * Octets:| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * --------------------------------- * |tc0|tc1|tc2|tc3|tc4|tc5|tc6|tc7| * --------------------------------- * * TSA Assignment Table (8 octets) * Octets:| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * --------------------------------- * |tc0|tc1|tc2|tc3|tc4|tc5|tc6|tc7| * --------------------------------- */ ice_for_each_traffic_class(i) { buf[offset] = ets_cfg->tcbwtable[i]; buf[ICE_MAX_TRAFFIC_CLASS + offset] = ets_cfg->tsatable[i]; offset++; } } /** * ice_add_ieee_ets_tlv - Prepare ETS TLV in IEEE format * @tlv: Fill the ETS config data in IEEE format * @dcbcfg: Local store which holds the DCB Config * * Prepare IEEE 802.1Qaz ETS CFG TLV */ static void ice_add_ieee_ets_tlv(struct ice_lldp_org_tlv *tlv, struct ice_dcbx_cfg *dcbcfg) { struct ice_dcb_ets_cfg *etscfg; u8 *buf = tlv->tlvinfo; u8 maxtcwilling = 0; u32 ouisubtype; u16 typelen; typelen = ((ICE_TLV_TYPE_ORG << ICE_LLDP_TLV_TYPE_S) | ICE_IEEE_ETS_TLV_LEN); tlv->typelen = htons(typelen); ouisubtype = ((ICE_IEEE_8021QAZ_OUI << ICE_LLDP_TLV_OUI_S) | ICE_IEEE_SUBTYPE_ETS_CFG); tlv->ouisubtype = htonl(ouisubtype); /* First Octet post subtype * -------------------------- * |will-|CBS | Re- | Max | * |ing | |served| TCs | * -------------------------- * |1bit | 1bit|3 bits|3bits| */ etscfg = &dcbcfg->etscfg; if (etscfg->willing) maxtcwilling = BIT(ICE_IEEE_ETS_WILLING_S); maxtcwilling |= etscfg->maxtcs & ICE_IEEE_ETS_MAXTC_M; buf[0] = maxtcwilling; /* Begin adding at Priority Assignment Table (offset 1 in buf) */ ice_add_ieee_ets_common_tlv(&buf[1], etscfg); } /** * ice_add_ieee_etsrec_tlv - Prepare ETS Recommended TLV in IEEE format * @tlv: Fill ETS Recommended TLV in IEEE format * @dcbcfg: Local store which holds the DCB Config * * Prepare IEEE 802.1Qaz ETS REC TLV */ static void ice_add_ieee_etsrec_tlv(struct ice_lldp_org_tlv *tlv, struct ice_dcbx_cfg *dcbcfg) { struct ice_dcb_ets_cfg *etsrec; u8 *buf = tlv->tlvinfo; u32 ouisubtype; u16 typelen; typelen = ((ICE_TLV_TYPE_ORG << ICE_LLDP_TLV_TYPE_S) | ICE_IEEE_ETS_TLV_LEN); tlv->typelen = htons(typelen); ouisubtype = ((ICE_IEEE_8021QAZ_OUI << ICE_LLDP_TLV_OUI_S) | ICE_IEEE_SUBTYPE_ETS_REC); tlv->ouisubtype = htonl(ouisubtype); etsrec = &dcbcfg->etsrec; /* First Octet is reserved */ /* Begin adding at Priority Assignment Table (offset 1 in buf) */ ice_add_ieee_ets_common_tlv(&buf[1], etsrec); } /** * ice_add_ieee_pfc_tlv - Prepare PFC TLV in IEEE format * @tlv: Fill PFC TLV in IEEE format * @dcbcfg: Local store which holds the PFC CFG data * * Prepare IEEE 802.1Qaz PFC CFG TLV */ static void ice_add_ieee_pfc_tlv(struct ice_lldp_org_tlv *tlv, struct ice_dcbx_cfg *dcbcfg) { u8 *buf = tlv->tlvinfo; u32 ouisubtype; u16 typelen; typelen = ((ICE_TLV_TYPE_ORG << ICE_LLDP_TLV_TYPE_S) | ICE_IEEE_PFC_TLV_LEN); tlv->typelen = htons(typelen); ouisubtype = ((ICE_IEEE_8021QAZ_OUI << ICE_LLDP_TLV_OUI_S) | ICE_IEEE_SUBTYPE_PFC_CFG); tlv->ouisubtype = htonl(ouisubtype); /* ---------------------------------------- * |will-|MBC | Re- | PFC | PFC Enable | * |ing | |served| cap | | * ----------------------------------------- * |1bit | 1bit|2 bits|4bits| 1 octet | */ if (dcbcfg->pfc.willing) buf[0] = BIT(ICE_IEEE_PFC_WILLING_S); if (dcbcfg->pfc.mbc) buf[0] |= BIT(ICE_IEEE_PFC_MBC_S); buf[0] |= dcbcfg->pfc.pfccap & 0xF; buf[1] = dcbcfg->pfc.pfcena; } /** * ice_add_ieee_app_pri_tlv - Prepare APP TLV in IEEE format * @tlv: Fill APP TLV in IEEE format * @dcbcfg: Local store which holds the APP CFG data * * Prepare IEEE 802.1Qaz APP CFG TLV */ static void ice_add_ieee_app_pri_tlv(struct ice_lldp_org_tlv *tlv, struct ice_dcbx_cfg *dcbcfg) { u16 typelen, len, offset = 0; u8 priority, selector, i = 0; u8 *buf = tlv->tlvinfo; u32 ouisubtype; /* No APP TLVs then just return */ if (dcbcfg->numapps == 0) return; ouisubtype = ((ICE_IEEE_8021QAZ_OUI << ICE_LLDP_TLV_OUI_S) | ICE_IEEE_SUBTYPE_APP_PRI); tlv->ouisubtype = htonl(ouisubtype); /* Move offset to App Priority Table */ offset++; /* Application Priority Table (3 octets) * Octets:| 1 | 2 | 3 | * ----------------------------------------- * |Priority|Rsrvd| Sel | Protocol ID | * ----------------------------------------- * Bits:|23 21|20 19|18 16|15 0| * ----------------------------------------- */ while (i < dcbcfg->numapps) { priority = dcbcfg->app[i].priority & 0x7; selector = dcbcfg->app[i].selector & 0x7; buf[offset] = (priority << ICE_IEEE_APP_PRIO_S) | selector; buf[offset + 1] = (dcbcfg->app[i].prot_id >> 0x8) & 0xFF; buf[offset + 2] = dcbcfg->app[i].prot_id & 0xFF; /* Move to next app */ offset += 3; i++; if (i >= ICE_DCBX_MAX_APPS) break; } /* len includes size of ouisubtype + 1 reserved + 3*numapps */ len = sizeof(tlv->ouisubtype) + 1 + (i * 3); typelen = ((ICE_TLV_TYPE_ORG << ICE_LLDP_TLV_TYPE_S) | (len & 0x1FF)); tlv->typelen = htons(typelen); } /** * ice_add_dscp_up_tlv - Prepare DSCP to UP TLV * @tlv: location to build the TLV data * @dcbcfg: location of data to convert to TLV */ static void ice_add_dscp_up_tlv(struct ice_lldp_org_tlv *tlv, struct ice_dcbx_cfg *dcbcfg) { u8 *buf = tlv->tlvinfo; u32 ouisubtype; u16 typelen; int i; typelen = ((ICE_TLV_TYPE_ORG << ICE_LLDP_TLV_TYPE_S) | ICE_DSCP_UP_TLV_LEN); tlv->typelen = htons(typelen); ouisubtype = (u32)((ICE_DSCP_OUI << ICE_LLDP_TLV_OUI_S) | ICE_DSCP_SUBTYPE_DSCP2UP); tlv->ouisubtype = htonl(ouisubtype); /* bytes 0 - 63 - IPv4 DSCP2UP LUT */ for (i = 0; i < ICE_DSCP_NUM_VAL; i++) { /* IPv4 mapping */ buf[i] = dcbcfg->dscp_map[i]; /* IPv6 mapping */ buf[i + ICE_DSCP_IPV6_OFFSET] = dcbcfg->dscp_map[i]; } /* byte 64 - IPv4 untagged traffic */ buf[i] = 0; /* byte 144 - IPv6 untagged traffic */ buf[i + ICE_DSCP_IPV6_OFFSET] = 0; } #define ICE_BYTES_PER_TC 8 /** * ice_add_dscp_enf_tlv - Prepare DSCP Enforcement TLV * @tlv: location to build the TLV data */ static void ice_add_dscp_enf_tlv(struct ice_lldp_org_tlv *tlv) { u8 *buf = tlv->tlvinfo; u32 ouisubtype; u16 typelen; typelen = ((ICE_TLV_TYPE_ORG << ICE_LLDP_TLV_TYPE_S) | ICE_DSCP_ENF_TLV_LEN); tlv->typelen = htons(typelen); ouisubtype = (u32)((ICE_DSCP_OUI << ICE_LLDP_TLV_OUI_S) | ICE_DSCP_SUBTYPE_ENFORCE); tlv->ouisubtype = htonl(ouisubtype); /* Allow all DSCP values to be valid for all TC's (IPv4 and IPv6) */ memset(buf, 0, 2 * (ICE_MAX_TRAFFIC_CLASS * ICE_BYTES_PER_TC)); } /** * ice_add_dscp_tc_bw_tlv - Prepare DSCP BW for TC TLV * @tlv: location to build the TLV data * @dcbcfg: location of the data to convert to TLV */ static void ice_add_dscp_tc_bw_tlv(struct ice_lldp_org_tlv *tlv, struct ice_dcbx_cfg *dcbcfg) { struct ice_dcb_ets_cfg *etscfg; u8 *buf = tlv->tlvinfo; u32 ouisubtype; u8 offset = 0; u16 typelen; int i; typelen = ((ICE_TLV_TYPE_ORG << ICE_LLDP_TLV_TYPE_S) | ICE_DSCP_TC_BW_TLV_LEN); tlv->typelen = htons(typelen); ouisubtype = (u32)((ICE_DSCP_OUI << ICE_LLDP_TLV_OUI_S) | ICE_DSCP_SUBTYPE_TCBW); tlv->ouisubtype = htonl(ouisubtype); /* First Octect after subtype * ---------------------------- * | RSV | CBS | RSV | Max TCs | * | 1b | 1b | 3b | 3b | * ---------------------------- */ etscfg = &dcbcfg->etscfg; buf[0] = etscfg->maxtcs & ICE_IEEE_ETS_MAXTC_M; /* bytes 1 - 4 reserved */ offset = 5; /* TC BW table * bytes 0 - 7 for TC 0 - 7 * * TSA Assignment table * bytes 8 - 15 for TC 0 - 7 */ for (i = 0; i < ICE_MAX_TRAFFIC_CLASS; i++) { buf[offset] = etscfg->tcbwtable[i]; buf[offset + ICE_MAX_TRAFFIC_CLASS] = etscfg->tsatable[i]; offset++; } } /** * ice_add_dscp_pfc_tlv - Prepare DSCP PFC TLV * @tlv: Fill PFC TLV in IEEE format * @dcbcfg: Local store which holds the PFC CFG data */ static void ice_add_dscp_pfc_tlv(struct ice_lldp_org_tlv *tlv, struct ice_dcbx_cfg *dcbcfg) { u8 *buf = tlv->tlvinfo; u32 ouisubtype; u16 typelen; typelen = ((ICE_TLV_TYPE_ORG << ICE_LLDP_TLV_TYPE_S) | ICE_DSCP_PFC_TLV_LEN); tlv->typelen = htons(typelen); ouisubtype = (u32)((ICE_DSCP_OUI << ICE_LLDP_TLV_OUI_S) | ICE_DSCP_SUBTYPE_PFC); tlv->ouisubtype = htonl(ouisubtype); buf[0] = dcbcfg->pfc.pfccap & 0xF; buf[1] = dcbcfg->pfc.pfcena; } /** * ice_add_dcb_tlv - Add all IEEE or DSCP TLVs * @tlv: Fill TLV data in IEEE format * @dcbcfg: Local store which holds the DCB Config * @tlvid: Type of IEEE TLV * * Add tlv information */ static void ice_add_dcb_tlv(struct ice_lldp_org_tlv *tlv, struct ice_dcbx_cfg *dcbcfg, u16 tlvid) { if (dcbcfg->pfc_mode == ICE_QOS_MODE_VLAN) { switch (tlvid) { case ICE_IEEE_TLV_ID_ETS_CFG: ice_add_ieee_ets_tlv(tlv, dcbcfg); break; case ICE_IEEE_TLV_ID_ETS_REC: ice_add_ieee_etsrec_tlv(tlv, dcbcfg); break; case ICE_IEEE_TLV_ID_PFC_CFG: ice_add_ieee_pfc_tlv(tlv, dcbcfg); break; case ICE_IEEE_TLV_ID_APP_PRI: ice_add_ieee_app_pri_tlv(tlv, dcbcfg); break; default: break; } } else { /* pfc_mode == ICE_QOS_MODE_DSCP */ switch (tlvid) { case ICE_TLV_ID_DSCP_UP: ice_add_dscp_up_tlv(tlv, dcbcfg); break; case ICE_TLV_ID_DSCP_ENF: ice_add_dscp_enf_tlv(tlv); break; case ICE_TLV_ID_DSCP_TC_BW: ice_add_dscp_tc_bw_tlv(tlv, dcbcfg); break; case ICE_TLV_ID_DSCP_TO_PFC: ice_add_dscp_pfc_tlv(tlv, dcbcfg); break; default: break; } } } /** * ice_dcb_cfg_to_lldp - Convert DCB configuration to MIB format * @lldpmib: pointer to the HW struct * @miblen: length of LLDP MIB * @dcbcfg: Local store which holds the DCB Config * * Convert the DCB configuration to MIB format */ static void ice_dcb_cfg_to_lldp(u8 *lldpmib, u16 *miblen, struct ice_dcbx_cfg *dcbcfg) { u16 len, offset = 0, tlvid = ICE_TLV_ID_START; struct ice_lldp_org_tlv *tlv; u16 typelen; tlv = (struct ice_lldp_org_tlv *)lldpmib; while (1) { ice_add_dcb_tlv(tlv, dcbcfg, tlvid++); typelen = ntohs(tlv->typelen); len = (typelen & ICE_LLDP_TLV_LEN_M) >> ICE_LLDP_TLV_LEN_S; if (len) offset += len + 2; /* END TLV or beyond LLDPDU size */ if (tlvid >= ICE_TLV_ID_END_OF_LLDPPDU || offset > ICE_LLDPDU_SIZE) break; /* Move to next TLV */ if (len) tlv = (struct ice_lldp_org_tlv *) ((char *)tlv + sizeof(tlv->typelen) + len); } *miblen = offset; } /** * ice_set_dcb_cfg - Set the local LLDP MIB to FW * @pi: port information structure * * Set DCB configuration to the Firmware */ int ice_set_dcb_cfg(struct ice_port_info *pi) { u8 mib_type, *lldpmib = NULL; struct ice_dcbx_cfg *dcbcfg; struct ice_hw *hw; u16 miblen; int ret; if (!pi) return -EINVAL; hw = pi->hw; /* update the HW local config */ dcbcfg = &pi->qos_cfg.local_dcbx_cfg; /* Allocate the LLDPDU */ lldpmib = devm_kzalloc(ice_hw_to_dev(hw), ICE_LLDPDU_SIZE, GFP_KERNEL); if (!lldpmib) return -ENOMEM; mib_type = SET_LOCAL_MIB_TYPE_LOCAL_MIB; if (dcbcfg->app_mode == ICE_DCBX_APPS_NON_WILLING) mib_type |= SET_LOCAL_MIB_TYPE_CEE_NON_WILLING; ice_dcb_cfg_to_lldp(lldpmib, &miblen, dcbcfg); ret = ice_aq_set_lldp_mib(hw, mib_type, (void *)lldpmib, miblen, NULL); devm_kfree(ice_hw_to_dev(hw), lldpmib); return ret; } /** * ice_aq_query_port_ets - query port ETS configuration * @pi: port information structure * @buf: pointer to buffer * @buf_size: buffer size in bytes * @cd: pointer to command details structure or NULL * * query current port ETS configuration */ static int ice_aq_query_port_ets(struct ice_port_info *pi, struct ice_aqc_port_ets_elem *buf, u16 buf_size, struct ice_sq_cd *cd) { struct ice_aqc_query_port_ets *cmd; struct ice_aq_desc desc; int status; if (!pi) return -EINVAL; cmd = &desc.params.port_ets; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_query_port_ets); cmd->port_teid = pi->root->info.node_teid; status = ice_aq_send_cmd(pi->hw, &desc, buf, buf_size, cd); return status; } /** * ice_update_port_tc_tree_cfg - update TC tree configuration * @pi: port information structure * @buf: pointer to buffer * * update the SW DB with the new TC changes */ static int ice_update_port_tc_tree_cfg(struct ice_port_info *pi, struct ice_aqc_port_ets_elem *buf) { struct ice_sched_node *node, *tc_node; struct ice_aqc_txsched_elem_data elem; u32 teid1, teid2; int status = 0; u8 i, j; if (!pi) return -EINVAL; /* suspend the missing TC nodes */ for (i = 0; i < pi->root->num_children; i++) { teid1 = le32_to_cpu(pi->root->children[i]->info.node_teid); ice_for_each_traffic_class(j) { teid2 = le32_to_cpu(buf->tc_node_teid[j]); if (teid1 == teid2) break; } if (j < ICE_MAX_TRAFFIC_CLASS) continue; /* TC is missing */ pi->root->children[i]->in_use = false; } /* add the new TC nodes */ ice_for_each_traffic_class(j) { teid2 = le32_to_cpu(buf->tc_node_teid[j]); if (teid2 == ICE_INVAL_TEID) continue; /* Is it already present in the tree ? */ for (i = 0; i < pi->root->num_children; i++) { tc_node = pi->root->children[i]; if (!tc_node) continue; teid1 = le32_to_cpu(tc_node->info.node_teid); if (teid1 == teid2) { tc_node->tc_num = j; tc_node->in_use = true; break; } } if (i < pi->root->num_children) continue; /* new TC */ status = ice_sched_query_elem(pi->hw, teid2, &elem); if (!status) status = ice_sched_add_node(pi, 1, &elem, NULL); if (status) break; /* update the TC number */ node = ice_sched_find_node_by_teid(pi->root, teid2); if (node) node->tc_num = j; } return status; } /** * ice_query_port_ets - query port ETS configuration * @pi: port information structure * @buf: pointer to buffer * @buf_size: buffer size in bytes * @cd: pointer to command details structure or NULL * * query current port ETS configuration and update the * SW DB with the TC changes */ int ice_query_port_ets(struct ice_port_info *pi, struct ice_aqc_port_ets_elem *buf, u16 buf_size, struct ice_sq_cd *cd) { int status; mutex_lock(&pi->sched_lock); status = ice_aq_query_port_ets(pi, buf, buf_size, cd); if (!status) status = ice_update_port_tc_tree_cfg(pi, buf); mutex_unlock(&pi->sched_lock); return status; }
linux-master
drivers/net/ethernet/intel/ice/ice_dcb.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2018, Intel Corporation. */ /* Intel(R) Ethernet Connection E800 Series Linux Driver */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <generated/utsrelease.h> #include "ice.h" #include "ice_base.h" #include "ice_lib.h" #include "ice_fltr.h" #include "ice_dcb_lib.h" #include "ice_dcb_nl.h" #include "ice_devlink.h" /* Including ice_trace.h with CREATE_TRACE_POINTS defined will generate the * ice tracepoint functions. This must be done exactly once across the * ice driver. */ #define CREATE_TRACE_POINTS #include "ice_trace.h" #include "ice_eswitch.h" #include "ice_tc_lib.h" #include "ice_vsi_vlan_ops.h" #include <net/xdp_sock_drv.h> #define DRV_SUMMARY "Intel(R) Ethernet Connection E800 Series Linux Driver" static const char ice_driver_string[] = DRV_SUMMARY; static const char ice_copyright[] = "Copyright (c) 2018, Intel Corporation."; /* DDP Package file located in firmware search paths (e.g. /lib/firmware/) */ #define ICE_DDP_PKG_PATH "intel/ice/ddp/" #define ICE_DDP_PKG_FILE ICE_DDP_PKG_PATH "ice.pkg" MODULE_AUTHOR("Intel Corporation, <[email protected]>"); MODULE_DESCRIPTION(DRV_SUMMARY); MODULE_LICENSE("GPL v2"); MODULE_FIRMWARE(ICE_DDP_PKG_FILE); static int debug = -1; module_param(debug, int, 0644); #ifndef CONFIG_DYNAMIC_DEBUG MODULE_PARM_DESC(debug, "netif level (0=none,...,16=all), hw debug_mask (0x8XXXXXXX)"); #else MODULE_PARM_DESC(debug, "netif level (0=none,...,16=all)"); #endif /* !CONFIG_DYNAMIC_DEBUG */ DEFINE_STATIC_KEY_FALSE(ice_xdp_locking_key); EXPORT_SYMBOL(ice_xdp_locking_key); /** * ice_hw_to_dev - Get device pointer from the hardware structure * @hw: pointer to the device HW structure * * Used to access the device pointer from compilation units which can't easily * include the definition of struct ice_pf without leading to circular header * dependencies. */ struct device *ice_hw_to_dev(struct ice_hw *hw) { struct ice_pf *pf = container_of(hw, struct ice_pf, hw); return &pf->pdev->dev; } static struct workqueue_struct *ice_wq; struct workqueue_struct *ice_lag_wq; static const struct net_device_ops ice_netdev_safe_mode_ops; static const struct net_device_ops ice_netdev_ops; static void ice_rebuild(struct ice_pf *pf, enum ice_reset_req reset_type); static void ice_vsi_release_all(struct ice_pf *pf); static int ice_rebuild_channels(struct ice_pf *pf); static void ice_remove_q_channels(struct ice_vsi *vsi, bool rem_adv_fltr); static int ice_indr_setup_tc_cb(struct net_device *netdev, struct Qdisc *sch, void *cb_priv, enum tc_setup_type type, void *type_data, void *data, void (*cleanup)(struct flow_block_cb *block_cb)); bool netif_is_ice(const struct net_device *dev) { return dev && (dev->netdev_ops == &ice_netdev_ops); } /** * ice_get_tx_pending - returns number of Tx descriptors not processed * @ring: the ring of descriptors */ static u16 ice_get_tx_pending(struct ice_tx_ring *ring) { u16 head, tail; head = ring->next_to_clean; tail = ring->next_to_use; if (head != tail) return (head < tail) ? tail - head : (tail + ring->count - head); return 0; } /** * ice_check_for_hang_subtask - check for and recover hung queues * @pf: pointer to PF struct */ static void ice_check_for_hang_subtask(struct ice_pf *pf) { struct ice_vsi *vsi = NULL; struct ice_hw *hw; unsigned int i; int packets; u32 v; ice_for_each_vsi(pf, v) if (pf->vsi[v] && pf->vsi[v]->type == ICE_VSI_PF) { vsi = pf->vsi[v]; break; } if (!vsi || test_bit(ICE_VSI_DOWN, vsi->state)) return; if (!(vsi->netdev && netif_carrier_ok(vsi->netdev))) return; hw = &vsi->back->hw; ice_for_each_txq(vsi, i) { struct ice_tx_ring *tx_ring = vsi->tx_rings[i]; struct ice_ring_stats *ring_stats; if (!tx_ring) continue; if (ice_ring_ch_enabled(tx_ring)) continue; ring_stats = tx_ring->ring_stats; if (!ring_stats) continue; if (tx_ring->desc) { /* If packet counter has not changed the queue is * likely stalled, so force an interrupt for this * queue. * * prev_pkt would be negative if there was no * pending work. */ packets = ring_stats->stats.pkts & INT_MAX; if (ring_stats->tx_stats.prev_pkt == packets) { /* Trigger sw interrupt to revive the queue */ ice_trigger_sw_intr(hw, tx_ring->q_vector); continue; } /* Memory barrier between read of packet count and call * to ice_get_tx_pending() */ smp_rmb(); ring_stats->tx_stats.prev_pkt = ice_get_tx_pending(tx_ring) ? packets : -1; } } } /** * ice_init_mac_fltr - Set initial MAC filters * @pf: board private structure * * Set initial set of MAC filters for PF VSI; configure filters for permanent * address and broadcast address. If an error is encountered, netdevice will be * unregistered. */ static int ice_init_mac_fltr(struct ice_pf *pf) { struct ice_vsi *vsi; u8 *perm_addr; vsi = ice_get_main_vsi(pf); if (!vsi) return -EINVAL; perm_addr = vsi->port_info->mac.perm_addr; return ice_fltr_add_mac_and_broadcast(vsi, perm_addr, ICE_FWD_TO_VSI); } /** * ice_add_mac_to_sync_list - creates list of MAC addresses to be synced * @netdev: the net device on which the sync is happening * @addr: MAC address to sync * * This is a callback function which is called by the in kernel device sync * functions (like __dev_uc_sync, __dev_mc_sync, etc). This function only * populates the tmp_sync_list, which is later used by ice_add_mac to add the * MAC filters from the hardware. */ static int ice_add_mac_to_sync_list(struct net_device *netdev, const u8 *addr) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; if (ice_fltr_add_mac_to_list(vsi, &vsi->tmp_sync_list, addr, ICE_FWD_TO_VSI)) return -EINVAL; return 0; } /** * ice_add_mac_to_unsync_list - creates list of MAC addresses to be unsynced * @netdev: the net device on which the unsync is happening * @addr: MAC address to unsync * * This is a callback function which is called by the in kernel device unsync * functions (like __dev_uc_unsync, __dev_mc_unsync, etc). This function only * populates the tmp_unsync_list, which is later used by ice_remove_mac to * delete the MAC filters from the hardware. */ static int ice_add_mac_to_unsync_list(struct net_device *netdev, const u8 *addr) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; /* Under some circumstances, we might receive a request to delete our * own device address from our uc list. Because we store the device * address in the VSI's MAC filter list, we need to ignore such * requests and not delete our device address from this list. */ if (ether_addr_equal(addr, netdev->dev_addr)) return 0; if (ice_fltr_add_mac_to_list(vsi, &vsi->tmp_unsync_list, addr, ICE_FWD_TO_VSI)) return -EINVAL; return 0; } /** * ice_vsi_fltr_changed - check if filter state changed * @vsi: VSI to be checked * * returns true if filter state has changed, false otherwise. */ static bool ice_vsi_fltr_changed(struct ice_vsi *vsi) { return test_bit(ICE_VSI_UMAC_FLTR_CHANGED, vsi->state) || test_bit(ICE_VSI_MMAC_FLTR_CHANGED, vsi->state); } /** * ice_set_promisc - Enable promiscuous mode for a given PF * @vsi: the VSI being configured * @promisc_m: mask of promiscuous config bits * */ static int ice_set_promisc(struct ice_vsi *vsi, u8 promisc_m) { int status; if (vsi->type != ICE_VSI_PF) return 0; if (ice_vsi_has_non_zero_vlans(vsi)) { promisc_m |= (ICE_PROMISC_VLAN_RX | ICE_PROMISC_VLAN_TX); status = ice_fltr_set_vlan_vsi_promisc(&vsi->back->hw, vsi, promisc_m); } else { status = ice_fltr_set_vsi_promisc(&vsi->back->hw, vsi->idx, promisc_m, 0); } if (status && status != -EEXIST) return status; netdev_dbg(vsi->netdev, "set promisc filter bits for VSI %i: 0x%x\n", vsi->vsi_num, promisc_m); return 0; } /** * ice_clear_promisc - Disable promiscuous mode for a given PF * @vsi: the VSI being configured * @promisc_m: mask of promiscuous config bits * */ static int ice_clear_promisc(struct ice_vsi *vsi, u8 promisc_m) { int status; if (vsi->type != ICE_VSI_PF) return 0; if (ice_vsi_has_non_zero_vlans(vsi)) { promisc_m |= (ICE_PROMISC_VLAN_RX | ICE_PROMISC_VLAN_TX); status = ice_fltr_clear_vlan_vsi_promisc(&vsi->back->hw, vsi, promisc_m); } else { status = ice_fltr_clear_vsi_promisc(&vsi->back->hw, vsi->idx, promisc_m, 0); } netdev_dbg(vsi->netdev, "clear promisc filter bits for VSI %i: 0x%x\n", vsi->vsi_num, promisc_m); return status; } /** * ice_vsi_sync_fltr - Update the VSI filter list to the HW * @vsi: ptr to the VSI * * Push any outstanding VSI filter changes through the AdminQ. */ static int ice_vsi_sync_fltr(struct ice_vsi *vsi) { struct ice_vsi_vlan_ops *vlan_ops = ice_get_compat_vsi_vlan_ops(vsi); struct device *dev = ice_pf_to_dev(vsi->back); struct net_device *netdev = vsi->netdev; bool promisc_forced_on = false; struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; u32 changed_flags = 0; int err; if (!vsi->netdev) return -EINVAL; while (test_and_set_bit(ICE_CFG_BUSY, vsi->state)) usleep_range(1000, 2000); changed_flags = vsi->current_netdev_flags ^ vsi->netdev->flags; vsi->current_netdev_flags = vsi->netdev->flags; INIT_LIST_HEAD(&vsi->tmp_sync_list); INIT_LIST_HEAD(&vsi->tmp_unsync_list); if (ice_vsi_fltr_changed(vsi)) { clear_bit(ICE_VSI_UMAC_FLTR_CHANGED, vsi->state); clear_bit(ICE_VSI_MMAC_FLTR_CHANGED, vsi->state); /* grab the netdev's addr_list_lock */ netif_addr_lock_bh(netdev); __dev_uc_sync(netdev, ice_add_mac_to_sync_list, ice_add_mac_to_unsync_list); __dev_mc_sync(netdev, ice_add_mac_to_sync_list, ice_add_mac_to_unsync_list); /* our temp lists are populated. release lock */ netif_addr_unlock_bh(netdev); } /* Remove MAC addresses in the unsync list */ err = ice_fltr_remove_mac_list(vsi, &vsi->tmp_unsync_list); ice_fltr_free_list(dev, &vsi->tmp_unsync_list); if (err) { netdev_err(netdev, "Failed to delete MAC filters\n"); /* if we failed because of alloc failures, just bail */ if (err == -ENOMEM) goto out; } /* Add MAC addresses in the sync list */ err = ice_fltr_add_mac_list(vsi, &vsi->tmp_sync_list); ice_fltr_free_list(dev, &vsi->tmp_sync_list); /* If filter is added successfully or already exists, do not go into * 'if' condition and report it as error. Instead continue processing * rest of the function. */ if (err && err != -EEXIST) { netdev_err(netdev, "Failed to add MAC filters\n"); /* If there is no more space for new umac filters, VSI * should go into promiscuous mode. There should be some * space reserved for promiscuous filters. */ if (hw->adminq.sq_last_status == ICE_AQ_RC_ENOSPC && !test_and_set_bit(ICE_FLTR_OVERFLOW_PROMISC, vsi->state)) { promisc_forced_on = true; netdev_warn(netdev, "Reached MAC filter limit, forcing promisc mode on VSI %d\n", vsi->vsi_num); } else { goto out; } } err = 0; /* check for changes in promiscuous modes */ if (changed_flags & IFF_ALLMULTI) { if (vsi->current_netdev_flags & IFF_ALLMULTI) { err = ice_set_promisc(vsi, ICE_MCAST_PROMISC_BITS); if (err) { vsi->current_netdev_flags &= ~IFF_ALLMULTI; goto out_promisc; } } else { /* !(vsi->current_netdev_flags & IFF_ALLMULTI) */ err = ice_clear_promisc(vsi, ICE_MCAST_PROMISC_BITS); if (err) { vsi->current_netdev_flags |= IFF_ALLMULTI; goto out_promisc; } } } if (((changed_flags & IFF_PROMISC) || promisc_forced_on) || test_bit(ICE_VSI_PROMISC_CHANGED, vsi->state)) { clear_bit(ICE_VSI_PROMISC_CHANGED, vsi->state); if (vsi->current_netdev_flags & IFF_PROMISC) { /* Apply Rx filter rule to get traffic from wire */ if (!ice_is_dflt_vsi_in_use(vsi->port_info)) { err = ice_set_dflt_vsi(vsi); if (err && err != -EEXIST) { netdev_err(netdev, "Error %d setting default VSI %i Rx rule\n", err, vsi->vsi_num); vsi->current_netdev_flags &= ~IFF_PROMISC; goto out_promisc; } err = 0; vlan_ops->dis_rx_filtering(vsi); /* promiscuous mode implies allmulticast so * that VSIs that are in promiscuous mode are * subscribed to multicast packets coming to * the port */ err = ice_set_promisc(vsi, ICE_MCAST_PROMISC_BITS); if (err) goto out_promisc; } } else { /* Clear Rx filter to remove traffic from wire */ if (ice_is_vsi_dflt_vsi(vsi)) { err = ice_clear_dflt_vsi(vsi); if (err) { netdev_err(netdev, "Error %d clearing default VSI %i Rx rule\n", err, vsi->vsi_num); vsi->current_netdev_flags |= IFF_PROMISC; goto out_promisc; } if (vsi->netdev->features & NETIF_F_HW_VLAN_CTAG_FILTER) vlan_ops->ena_rx_filtering(vsi); } /* disable allmulti here, but only if allmulti is not * still enabled for the netdev */ if (!(vsi->current_netdev_flags & IFF_ALLMULTI)) { err = ice_clear_promisc(vsi, ICE_MCAST_PROMISC_BITS); if (err) { netdev_err(netdev, "Error %d clearing multicast promiscuous on VSI %i\n", err, vsi->vsi_num); } } } } goto exit; out_promisc: set_bit(ICE_VSI_PROMISC_CHANGED, vsi->state); goto exit; out: /* if something went wrong then set the changed flag so we try again */ set_bit(ICE_VSI_UMAC_FLTR_CHANGED, vsi->state); set_bit(ICE_VSI_MMAC_FLTR_CHANGED, vsi->state); exit: clear_bit(ICE_CFG_BUSY, vsi->state); return err; } /** * ice_sync_fltr_subtask - Sync the VSI filter list with HW * @pf: board private structure */ static void ice_sync_fltr_subtask(struct ice_pf *pf) { int v; if (!pf || !(test_bit(ICE_FLAG_FLTR_SYNC, pf->flags))) return; clear_bit(ICE_FLAG_FLTR_SYNC, pf->flags); ice_for_each_vsi(pf, v) if (pf->vsi[v] && ice_vsi_fltr_changed(pf->vsi[v]) && ice_vsi_sync_fltr(pf->vsi[v])) { /* come back and try again later */ set_bit(ICE_FLAG_FLTR_SYNC, pf->flags); break; } } /** * ice_pf_dis_all_vsi - Pause all VSIs on a PF * @pf: the PF * @locked: is the rtnl_lock already held */ static void ice_pf_dis_all_vsi(struct ice_pf *pf, bool locked) { int node; int v; ice_for_each_vsi(pf, v) if (pf->vsi[v]) ice_dis_vsi(pf->vsi[v], locked); for (node = 0; node < ICE_MAX_PF_AGG_NODES; node++) pf->pf_agg_node[node].num_vsis = 0; for (node = 0; node < ICE_MAX_VF_AGG_NODES; node++) pf->vf_agg_node[node].num_vsis = 0; } /** * ice_clear_sw_switch_recipes - clear switch recipes * @pf: board private structure * * Mark switch recipes as not created in sw structures. There are cases where * rules (especially advanced rules) need to be restored, either re-read from * hardware or added again. For example after the reset. 'recp_created' flag * prevents from doing that and need to be cleared upfront. */ static void ice_clear_sw_switch_recipes(struct ice_pf *pf) { struct ice_sw_recipe *recp; u8 i; recp = pf->hw.switch_info->recp_list; for (i = 0; i < ICE_MAX_NUM_RECIPES; i++) recp[i].recp_created = false; } /** * ice_prepare_for_reset - prep for reset * @pf: board private structure * @reset_type: reset type requested * * Inform or close all dependent features in prep for reset. */ static void ice_prepare_for_reset(struct ice_pf *pf, enum ice_reset_req reset_type) { struct ice_hw *hw = &pf->hw; struct ice_vsi *vsi; struct ice_vf *vf; unsigned int bkt; dev_dbg(ice_pf_to_dev(pf), "reset_type=%d\n", reset_type); /* already prepared for reset */ if (test_bit(ICE_PREPARED_FOR_RESET, pf->state)) return; ice_unplug_aux_dev(pf); /* Notify VFs of impending reset */ if (ice_check_sq_alive(hw, &hw->mailboxq)) ice_vc_notify_reset(pf); /* Disable VFs until reset is completed */ mutex_lock(&pf->vfs.table_lock); ice_for_each_vf(pf, bkt, vf) ice_set_vf_state_dis(vf); mutex_unlock(&pf->vfs.table_lock); if (ice_is_eswitch_mode_switchdev(pf)) { if (reset_type != ICE_RESET_PFR) ice_clear_sw_switch_recipes(pf); } /* release ADQ specific HW and SW resources */ vsi = ice_get_main_vsi(pf); if (!vsi) goto skip; /* to be on safe side, reset orig_rss_size so that normal flow * of deciding rss_size can take precedence */ vsi->orig_rss_size = 0; if (test_bit(ICE_FLAG_TC_MQPRIO, pf->flags)) { if (reset_type == ICE_RESET_PFR) { vsi->old_ena_tc = vsi->all_enatc; vsi->old_numtc = vsi->all_numtc; } else { ice_remove_q_channels(vsi, true); /* for other reset type, do not support channel rebuild * hence reset needed info */ vsi->old_ena_tc = 0; vsi->all_enatc = 0; vsi->old_numtc = 0; vsi->all_numtc = 0; vsi->req_txq = 0; vsi->req_rxq = 0; clear_bit(ICE_FLAG_TC_MQPRIO, pf->flags); memset(&vsi->mqprio_qopt, 0, sizeof(vsi->mqprio_qopt)); } } skip: /* clear SW filtering DB */ ice_clear_hw_tbls(hw); /* disable the VSIs and their queues that are not already DOWN */ ice_pf_dis_all_vsi(pf, false); if (test_bit(ICE_FLAG_PTP_SUPPORTED, pf->flags)) ice_ptp_prepare_for_reset(pf); if (ice_is_feature_supported(pf, ICE_F_GNSS)) ice_gnss_exit(pf); if (hw->port_info) ice_sched_clear_port(hw->port_info); ice_shutdown_all_ctrlq(hw); set_bit(ICE_PREPARED_FOR_RESET, pf->state); } /** * ice_do_reset - Initiate one of many types of resets * @pf: board private structure * @reset_type: reset type requested before this function was called. */ static void ice_do_reset(struct ice_pf *pf, enum ice_reset_req reset_type) { struct device *dev = ice_pf_to_dev(pf); struct ice_hw *hw = &pf->hw; dev_dbg(dev, "reset_type 0x%x requested\n", reset_type); if (pf->lag && pf->lag->bonded && reset_type == ICE_RESET_PFR) { dev_dbg(dev, "PFR on a bonded interface, promoting to CORER\n"); reset_type = ICE_RESET_CORER; } ice_prepare_for_reset(pf, reset_type); /* trigger the reset */ if (ice_reset(hw, reset_type)) { dev_err(dev, "reset %d failed\n", reset_type); set_bit(ICE_RESET_FAILED, pf->state); clear_bit(ICE_RESET_OICR_RECV, pf->state); clear_bit(ICE_PREPARED_FOR_RESET, pf->state); clear_bit(ICE_PFR_REQ, pf->state); clear_bit(ICE_CORER_REQ, pf->state); clear_bit(ICE_GLOBR_REQ, pf->state); wake_up(&pf->reset_wait_queue); return; } /* PFR is a bit of a special case because it doesn't result in an OICR * interrupt. So for PFR, rebuild after the reset and clear the reset- * associated state bits. */ if (reset_type == ICE_RESET_PFR) { pf->pfr_count++; ice_rebuild(pf, reset_type); clear_bit(ICE_PREPARED_FOR_RESET, pf->state); clear_bit(ICE_PFR_REQ, pf->state); wake_up(&pf->reset_wait_queue); ice_reset_all_vfs(pf); } } /** * ice_reset_subtask - Set up for resetting the device and driver * @pf: board private structure */ static void ice_reset_subtask(struct ice_pf *pf) { enum ice_reset_req reset_type = ICE_RESET_INVAL; /* When a CORER/GLOBR/EMPR is about to happen, the hardware triggers an * OICR interrupt. The OICR handler (ice_misc_intr) determines what type * of reset is pending and sets bits in pf->state indicating the reset * type and ICE_RESET_OICR_RECV. So, if the latter bit is set * prepare for pending reset if not already (for PF software-initiated * global resets the software should already be prepared for it as * indicated by ICE_PREPARED_FOR_RESET; for global resets initiated * by firmware or software on other PFs, that bit is not set so prepare * for the reset now), poll for reset done, rebuild and return. */ if (test_bit(ICE_RESET_OICR_RECV, pf->state)) { /* Perform the largest reset requested */ if (test_and_clear_bit(ICE_CORER_RECV, pf->state)) reset_type = ICE_RESET_CORER; if (test_and_clear_bit(ICE_GLOBR_RECV, pf->state)) reset_type = ICE_RESET_GLOBR; if (test_and_clear_bit(ICE_EMPR_RECV, pf->state)) reset_type = ICE_RESET_EMPR; /* return if no valid reset type requested */ if (reset_type == ICE_RESET_INVAL) return; ice_prepare_for_reset(pf, reset_type); /* make sure we are ready to rebuild */ if (ice_check_reset(&pf->hw)) { set_bit(ICE_RESET_FAILED, pf->state); } else { /* done with reset. start rebuild */ pf->hw.reset_ongoing = false; ice_rebuild(pf, reset_type); /* clear bit to resume normal operations, but * ICE_NEEDS_RESTART bit is set in case rebuild failed */ clear_bit(ICE_RESET_OICR_RECV, pf->state); clear_bit(ICE_PREPARED_FOR_RESET, pf->state); clear_bit(ICE_PFR_REQ, pf->state); clear_bit(ICE_CORER_REQ, pf->state); clear_bit(ICE_GLOBR_REQ, pf->state); wake_up(&pf->reset_wait_queue); ice_reset_all_vfs(pf); } return; } /* No pending resets to finish processing. Check for new resets */ if (test_bit(ICE_PFR_REQ, pf->state)) { reset_type = ICE_RESET_PFR; if (pf->lag && pf->lag->bonded) { dev_dbg(ice_pf_to_dev(pf), "PFR on a bonded interface, promoting to CORER\n"); reset_type = ICE_RESET_CORER; } } if (test_bit(ICE_CORER_REQ, pf->state)) reset_type = ICE_RESET_CORER; if (test_bit(ICE_GLOBR_REQ, pf->state)) reset_type = ICE_RESET_GLOBR; /* If no valid reset type requested just return */ if (reset_type == ICE_RESET_INVAL) return; /* reset if not already down or busy */ if (!test_bit(ICE_DOWN, pf->state) && !test_bit(ICE_CFG_BUSY, pf->state)) { ice_do_reset(pf, reset_type); } } /** * ice_print_topo_conflict - print topology conflict message * @vsi: the VSI whose topology status is being checked */ static void ice_print_topo_conflict(struct ice_vsi *vsi) { switch (vsi->port_info->phy.link_info.topo_media_conflict) { case ICE_AQ_LINK_TOPO_CONFLICT: case ICE_AQ_LINK_MEDIA_CONFLICT: case ICE_AQ_LINK_TOPO_UNREACH_PRT: case ICE_AQ_LINK_TOPO_UNDRUTIL_PRT: case ICE_AQ_LINK_TOPO_UNDRUTIL_MEDIA: netdev_info(vsi->netdev, "Potential misconfiguration of the Ethernet port detected. If it was not intended, please use the Intel (R) Ethernet Port Configuration Tool to address the issue.\n"); break; case ICE_AQ_LINK_TOPO_UNSUPP_MEDIA: if (test_bit(ICE_FLAG_LINK_LENIENT_MODE_ENA, vsi->back->flags)) netdev_warn(vsi->netdev, "An unsupported module type was detected. Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules\n"); else netdev_err(vsi->netdev, "Rx/Tx is disabled on this device because an unsupported module type was detected. Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n"); break; default: break; } } /** * ice_print_link_msg - print link up or down message * @vsi: the VSI whose link status is being queried * @isup: boolean for if the link is now up or down */ void ice_print_link_msg(struct ice_vsi *vsi, bool isup) { struct ice_aqc_get_phy_caps_data *caps; const char *an_advertised; const char *fec_req; const char *speed; const char *fec; const char *fc; const char *an; int status; if (!vsi) return; if (vsi->current_isup == isup) return; vsi->current_isup = isup; if (!isup) { netdev_info(vsi->netdev, "NIC Link is Down\n"); return; } switch (vsi->port_info->phy.link_info.link_speed) { case ICE_AQ_LINK_SPEED_100GB: speed = "100 G"; break; case ICE_AQ_LINK_SPEED_50GB: speed = "50 G"; break; case ICE_AQ_LINK_SPEED_40GB: speed = "40 G"; break; case ICE_AQ_LINK_SPEED_25GB: speed = "25 G"; break; case ICE_AQ_LINK_SPEED_20GB: speed = "20 G"; break; case ICE_AQ_LINK_SPEED_10GB: speed = "10 G"; break; case ICE_AQ_LINK_SPEED_5GB: speed = "5 G"; break; case ICE_AQ_LINK_SPEED_2500MB: speed = "2.5 G"; break; case ICE_AQ_LINK_SPEED_1000MB: speed = "1 G"; break; case ICE_AQ_LINK_SPEED_100MB: speed = "100 M"; break; default: speed = "Unknown "; break; } switch (vsi->port_info->fc.current_mode) { case ICE_FC_FULL: fc = "Rx/Tx"; break; case ICE_FC_TX_PAUSE: fc = "Tx"; break; case ICE_FC_RX_PAUSE: fc = "Rx"; break; case ICE_FC_NONE: fc = "None"; break; default: fc = "Unknown"; break; } /* Get FEC mode based on negotiated link info */ switch (vsi->port_info->phy.link_info.fec_info) { case ICE_AQ_LINK_25G_RS_528_FEC_EN: case ICE_AQ_LINK_25G_RS_544_FEC_EN: fec = "RS-FEC"; break; case ICE_AQ_LINK_25G_KR_FEC_EN: fec = "FC-FEC/BASE-R"; break; default: fec = "NONE"; break; } /* check if autoneg completed, might be false due to not supported */ if (vsi->port_info->phy.link_info.an_info & ICE_AQ_AN_COMPLETED) an = "True"; else an = "False"; /* Get FEC mode requested based on PHY caps last SW configuration */ caps = kzalloc(sizeof(*caps), GFP_KERNEL); if (!caps) { fec_req = "Unknown"; an_advertised = "Unknown"; goto done; } status = ice_aq_get_phy_caps(vsi->port_info, false, ICE_AQC_REPORT_ACTIVE_CFG, caps, NULL); if (status) netdev_info(vsi->netdev, "Get phy capability failed.\n"); an_advertised = ice_is_phy_caps_an_enabled(caps) ? "On" : "Off"; if (caps->link_fec_options & ICE_AQC_PHY_FEC_25G_RS_528_REQ || caps->link_fec_options & ICE_AQC_PHY_FEC_25G_RS_544_REQ) fec_req = "RS-FEC"; else if (caps->link_fec_options & ICE_AQC_PHY_FEC_10G_KR_40G_KR4_REQ || caps->link_fec_options & ICE_AQC_PHY_FEC_25G_KR_REQ) fec_req = "FC-FEC/BASE-R"; else fec_req = "NONE"; kfree(caps); done: netdev_info(vsi->netdev, "NIC Link is up %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg Advertised: %s, Autoneg Negotiated: %s, Flow Control: %s\n", speed, fec_req, fec, an_advertised, an, fc); ice_print_topo_conflict(vsi); } /** * ice_vsi_link_event - update the VSI's netdev * @vsi: the VSI on which the link event occurred * @link_up: whether or not the VSI needs to be set up or down */ static void ice_vsi_link_event(struct ice_vsi *vsi, bool link_up) { if (!vsi) return; if (test_bit(ICE_VSI_DOWN, vsi->state) || !vsi->netdev) return; if (vsi->type == ICE_VSI_PF) { if (link_up == netif_carrier_ok(vsi->netdev)) return; if (link_up) { netif_carrier_on(vsi->netdev); netif_tx_wake_all_queues(vsi->netdev); } else { netif_carrier_off(vsi->netdev); netif_tx_stop_all_queues(vsi->netdev); } } } /** * ice_set_dflt_mib - send a default config MIB to the FW * @pf: private PF struct * * This function sends a default configuration MIB to the FW. * * If this function errors out at any point, the driver is still able to * function. The main impact is that LFC may not operate as expected. * Therefore an error state in this function should be treated with a DBG * message and continue on with driver rebuild/reenable. */ static void ice_set_dflt_mib(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); u8 mib_type, *buf, *lldpmib = NULL; u16 len, typelen, offset = 0; struct ice_lldp_org_tlv *tlv; struct ice_hw *hw = &pf->hw; u32 ouisubtype; mib_type = SET_LOCAL_MIB_TYPE_LOCAL_MIB; lldpmib = kzalloc(ICE_LLDPDU_SIZE, GFP_KERNEL); if (!lldpmib) { dev_dbg(dev, "%s Failed to allocate MIB memory\n", __func__); return; } /* Add ETS CFG TLV */ tlv = (struct ice_lldp_org_tlv *)lldpmib; typelen = ((ICE_TLV_TYPE_ORG << ICE_LLDP_TLV_TYPE_S) | ICE_IEEE_ETS_TLV_LEN); tlv->typelen = htons(typelen); ouisubtype = ((ICE_IEEE_8021QAZ_OUI << ICE_LLDP_TLV_OUI_S) | ICE_IEEE_SUBTYPE_ETS_CFG); tlv->ouisubtype = htonl(ouisubtype); buf = tlv->tlvinfo; buf[0] = 0; /* ETS CFG all UPs map to TC 0. Next 4 (1 - 4) Octets = 0. * Octets 5 - 12 are BW values, set octet 5 to 100% BW. * Octets 13 - 20 are TSA values - leave as zeros */ buf[5] = 0x64; len = (typelen & ICE_LLDP_TLV_LEN_M) >> ICE_LLDP_TLV_LEN_S; offset += len + 2; tlv = (struct ice_lldp_org_tlv *) ((char *)tlv + sizeof(tlv->typelen) + len); /* Add ETS REC TLV */ buf = tlv->tlvinfo; tlv->typelen = htons(typelen); ouisubtype = ((ICE_IEEE_8021QAZ_OUI << ICE_LLDP_TLV_OUI_S) | ICE_IEEE_SUBTYPE_ETS_REC); tlv->ouisubtype = htonl(ouisubtype); /* First octet of buf is reserved * Octets 1 - 4 map UP to TC - all UPs map to zero * Octets 5 - 12 are BW values - set TC 0 to 100%. * Octets 13 - 20 are TSA value - leave as zeros */ buf[5] = 0x64; offset += len + 2; tlv = (struct ice_lldp_org_tlv *) ((char *)tlv + sizeof(tlv->typelen) + len); /* Add PFC CFG TLV */ typelen = ((ICE_TLV_TYPE_ORG << ICE_LLDP_TLV_TYPE_S) | ICE_IEEE_PFC_TLV_LEN); tlv->typelen = htons(typelen); ouisubtype = ((ICE_IEEE_8021QAZ_OUI << ICE_LLDP_TLV_OUI_S) | ICE_IEEE_SUBTYPE_PFC_CFG); tlv->ouisubtype = htonl(ouisubtype); /* Octet 1 left as all zeros - PFC disabled */ buf[0] = 0x08; len = (typelen & ICE_LLDP_TLV_LEN_M) >> ICE_LLDP_TLV_LEN_S; offset += len + 2; if (ice_aq_set_lldp_mib(hw, mib_type, (void *)lldpmib, offset, NULL)) dev_dbg(dev, "%s Failed to set default LLDP MIB\n", __func__); kfree(lldpmib); } /** * ice_check_phy_fw_load - check if PHY FW load failed * @pf: pointer to PF struct * @link_cfg_err: bitmap from the link info structure * * check if external PHY FW load failed and print an error message if it did */ static void ice_check_phy_fw_load(struct ice_pf *pf, u8 link_cfg_err) { if (!(link_cfg_err & ICE_AQ_LINK_EXTERNAL_PHY_LOAD_FAILURE)) { clear_bit(ICE_FLAG_PHY_FW_LOAD_FAILED, pf->flags); return; } if (test_bit(ICE_FLAG_PHY_FW_LOAD_FAILED, pf->flags)) return; if (link_cfg_err & ICE_AQ_LINK_EXTERNAL_PHY_LOAD_FAILURE) { dev_err(ice_pf_to_dev(pf), "Device failed to load the FW for the external PHY. Please download and install the latest NVM for your device and try again\n"); set_bit(ICE_FLAG_PHY_FW_LOAD_FAILED, pf->flags); } } /** * ice_check_module_power * @pf: pointer to PF struct * @link_cfg_err: bitmap from the link info structure * * check module power level returned by a previous call to aq_get_link_info * and print error messages if module power level is not supported */ static void ice_check_module_power(struct ice_pf *pf, u8 link_cfg_err) { /* if module power level is supported, clear the flag */ if (!(link_cfg_err & (ICE_AQ_LINK_INVAL_MAX_POWER_LIMIT | ICE_AQ_LINK_MODULE_POWER_UNSUPPORTED))) { clear_bit(ICE_FLAG_MOD_POWER_UNSUPPORTED, pf->flags); return; } /* if ICE_FLAG_MOD_POWER_UNSUPPORTED was previously set and the * above block didn't clear this bit, there's nothing to do */ if (test_bit(ICE_FLAG_MOD_POWER_UNSUPPORTED, pf->flags)) return; if (link_cfg_err & ICE_AQ_LINK_INVAL_MAX_POWER_LIMIT) { dev_err(ice_pf_to_dev(pf), "The installed module is incompatible with the device's NVM image. Cannot start link\n"); set_bit(ICE_FLAG_MOD_POWER_UNSUPPORTED, pf->flags); } else if (link_cfg_err & ICE_AQ_LINK_MODULE_POWER_UNSUPPORTED) { dev_err(ice_pf_to_dev(pf), "The module's power requirements exceed the device's power supply. Cannot start link\n"); set_bit(ICE_FLAG_MOD_POWER_UNSUPPORTED, pf->flags); } } /** * ice_check_link_cfg_err - check if link configuration failed * @pf: pointer to the PF struct * @link_cfg_err: bitmap from the link info structure * * print if any link configuration failure happens due to the value in the * link_cfg_err parameter in the link info structure */ static void ice_check_link_cfg_err(struct ice_pf *pf, u8 link_cfg_err) { ice_check_module_power(pf, link_cfg_err); ice_check_phy_fw_load(pf, link_cfg_err); } /** * ice_link_event - process the link event * @pf: PF that the link event is associated with * @pi: port_info for the port that the link event is associated with * @link_up: true if the physical link is up and false if it is down * @link_speed: current link speed received from the link event * * Returns 0 on success and negative on failure */ static int ice_link_event(struct ice_pf *pf, struct ice_port_info *pi, bool link_up, u16 link_speed) { struct device *dev = ice_pf_to_dev(pf); struct ice_phy_info *phy_info; struct ice_vsi *vsi; u16 old_link_speed; bool old_link; int status; phy_info = &pi->phy; phy_info->link_info_old = phy_info->link_info; old_link = !!(phy_info->link_info_old.link_info & ICE_AQ_LINK_UP); old_link_speed = phy_info->link_info_old.link_speed; /* update the link info structures and re-enable link events, * don't bail on failure due to other book keeping needed */ status = ice_update_link_info(pi); if (status) dev_dbg(dev, "Failed to update link status on port %d, err %d aq_err %s\n", pi->lport, status, ice_aq_str(pi->hw->adminq.sq_last_status)); ice_check_link_cfg_err(pf, pi->phy.link_info.link_cfg_err); /* Check if the link state is up after updating link info, and treat * this event as an UP event since the link is actually UP now. */ if (phy_info->link_info.link_info & ICE_AQ_LINK_UP) link_up = true; vsi = ice_get_main_vsi(pf); if (!vsi || !vsi->port_info) return -EINVAL; /* turn off PHY if media was removed */ if (!test_bit(ICE_FLAG_NO_MEDIA, pf->flags) && !(pi->phy.link_info.link_info & ICE_AQ_MEDIA_AVAILABLE)) { set_bit(ICE_FLAG_NO_MEDIA, pf->flags); ice_set_link(vsi, false); } /* if the old link up/down and speed is the same as the new */ if (link_up == old_link && link_speed == old_link_speed) return 0; ice_ptp_link_change(pf, pf->hw.pf_id, link_up); if (ice_is_dcb_active(pf)) { if (test_bit(ICE_FLAG_DCB_ENA, pf->flags)) ice_dcb_rebuild(pf); } else { if (link_up) ice_set_dflt_mib(pf); } ice_vsi_link_event(vsi, link_up); ice_print_link_msg(vsi, link_up); ice_vc_notify_link_state(pf); return 0; } /** * ice_watchdog_subtask - periodic tasks not using event driven scheduling * @pf: board private structure */ static void ice_watchdog_subtask(struct ice_pf *pf) { int i; /* if interface is down do nothing */ if (test_bit(ICE_DOWN, pf->state) || test_bit(ICE_CFG_BUSY, pf->state)) return; /* make sure we don't do these things too often */ if (time_before(jiffies, pf->serv_tmr_prev + pf->serv_tmr_period)) return; pf->serv_tmr_prev = jiffies; /* Update the stats for active netdevs so the network stack * can look at updated numbers whenever it cares to */ ice_update_pf_stats(pf); ice_for_each_vsi(pf, i) if (pf->vsi[i] && pf->vsi[i]->netdev) ice_update_vsi_stats(pf->vsi[i]); } /** * ice_init_link_events - enable/initialize link events * @pi: pointer to the port_info instance * * Returns -EIO on failure, 0 on success */ static int ice_init_link_events(struct ice_port_info *pi) { u16 mask; mask = ~((u16)(ICE_AQ_LINK_EVENT_UPDOWN | ICE_AQ_LINK_EVENT_MEDIA_NA | ICE_AQ_LINK_EVENT_MODULE_QUAL_FAIL | ICE_AQ_LINK_EVENT_PHY_FW_LOAD_FAIL)); if (ice_aq_set_event_mask(pi->hw, pi->lport, mask, NULL)) { dev_dbg(ice_hw_to_dev(pi->hw), "Failed to set link event mask for port %d\n", pi->lport); return -EIO; } if (ice_aq_get_link_info(pi, true, NULL, NULL)) { dev_dbg(ice_hw_to_dev(pi->hw), "Failed to enable link events for port %d\n", pi->lport); return -EIO; } return 0; } /** * ice_handle_link_event - handle link event via ARQ * @pf: PF that the link event is associated with * @event: event structure containing link status info */ static int ice_handle_link_event(struct ice_pf *pf, struct ice_rq_event_info *event) { struct ice_aqc_get_link_status_data *link_data; struct ice_port_info *port_info; int status; link_data = (struct ice_aqc_get_link_status_data *)event->msg_buf; port_info = pf->hw.port_info; if (!port_info) return -EINVAL; status = ice_link_event(pf, port_info, !!(link_data->link_info & ICE_AQ_LINK_UP), le16_to_cpu(link_data->link_speed)); if (status) dev_dbg(ice_pf_to_dev(pf), "Could not process link event, error %d\n", status); return status; } /** * ice_aq_prep_for_event - Prepare to wait for an AdminQ event from firmware * @pf: pointer to the PF private structure * @task: intermediate helper storage and identifier for waiting * @opcode: the opcode to wait for * * Prepares to wait for a specific AdminQ completion event on the ARQ for * a given PF. Actual wait would be done by a call to ice_aq_wait_for_event(). * * Calls are separated to allow caller registering for event before sending * the command, which mitigates a race between registering and FW responding. * * To obtain only the descriptor contents, pass an task->event with null * msg_buf. If the complete data buffer is desired, allocate the * task->event.msg_buf with enough space ahead of time. */ void ice_aq_prep_for_event(struct ice_pf *pf, struct ice_aq_task *task, u16 opcode) { INIT_HLIST_NODE(&task->entry); task->opcode = opcode; task->state = ICE_AQ_TASK_WAITING; spin_lock_bh(&pf->aq_wait_lock); hlist_add_head(&task->entry, &pf->aq_wait_list); spin_unlock_bh(&pf->aq_wait_lock); } /** * ice_aq_wait_for_event - Wait for an AdminQ event from firmware * @pf: pointer to the PF private structure * @task: ptr prepared by ice_aq_prep_for_event() * @timeout: how long to wait, in jiffies * * Waits for a specific AdminQ completion event on the ARQ for a given PF. The * current thread will be put to sleep until the specified event occurs or * until the given timeout is reached. * * Returns: zero on success, or a negative error code on failure. */ int ice_aq_wait_for_event(struct ice_pf *pf, struct ice_aq_task *task, unsigned long timeout) { enum ice_aq_task_state *state = &task->state; struct device *dev = ice_pf_to_dev(pf); unsigned long start = jiffies; long ret; int err; ret = wait_event_interruptible_timeout(pf->aq_wait_queue, *state != ICE_AQ_TASK_WAITING, timeout); switch (*state) { case ICE_AQ_TASK_NOT_PREPARED: WARN(1, "call to %s without ice_aq_prep_for_event()", __func__); err = -EINVAL; break; case ICE_AQ_TASK_WAITING: err = ret < 0 ? ret : -ETIMEDOUT; break; case ICE_AQ_TASK_CANCELED: err = ret < 0 ? ret : -ECANCELED; break; case ICE_AQ_TASK_COMPLETE: err = ret < 0 ? ret : 0; break; default: WARN(1, "Unexpected AdminQ wait task state %u", *state); err = -EINVAL; break; } dev_dbg(dev, "Waited %u msecs (max %u msecs) for firmware response to op 0x%04x\n", jiffies_to_msecs(jiffies - start), jiffies_to_msecs(timeout), task->opcode); spin_lock_bh(&pf->aq_wait_lock); hlist_del(&task->entry); spin_unlock_bh(&pf->aq_wait_lock); return err; } /** * ice_aq_check_events - Check if any thread is waiting for an AdminQ event * @pf: pointer to the PF private structure * @opcode: the opcode of the event * @event: the event to check * * Loops over the current list of pending threads waiting for an AdminQ event. * For each matching task, copy the contents of the event into the task * structure and wake up the thread. * * If multiple threads wait for the same opcode, they will all be woken up. * * Note that event->msg_buf will only be duplicated if the event has a buffer * with enough space already allocated. Otherwise, only the descriptor and * message length will be copied. * * Returns: true if an event was found, false otherwise */ static void ice_aq_check_events(struct ice_pf *pf, u16 opcode, struct ice_rq_event_info *event) { struct ice_rq_event_info *task_ev; struct ice_aq_task *task; bool found = false; spin_lock_bh(&pf->aq_wait_lock); hlist_for_each_entry(task, &pf->aq_wait_list, entry) { if (task->state != ICE_AQ_TASK_WAITING) continue; if (task->opcode != opcode) continue; task_ev = &task->event; memcpy(&task_ev->desc, &event->desc, sizeof(event->desc)); task_ev->msg_len = event->msg_len; /* Only copy the data buffer if a destination was set */ if (task_ev->msg_buf && task_ev->buf_len >= event->buf_len) { memcpy(task_ev->msg_buf, event->msg_buf, event->buf_len); task_ev->buf_len = event->buf_len; } task->state = ICE_AQ_TASK_COMPLETE; found = true; } spin_unlock_bh(&pf->aq_wait_lock); if (found) wake_up(&pf->aq_wait_queue); } /** * ice_aq_cancel_waiting_tasks - Immediately cancel all waiting tasks * @pf: the PF private structure * * Set all waiting tasks to ICE_AQ_TASK_CANCELED, and wake up their threads. * This will then cause ice_aq_wait_for_event to exit with -ECANCELED. */ static void ice_aq_cancel_waiting_tasks(struct ice_pf *pf) { struct ice_aq_task *task; spin_lock_bh(&pf->aq_wait_lock); hlist_for_each_entry(task, &pf->aq_wait_list, entry) task->state = ICE_AQ_TASK_CANCELED; spin_unlock_bh(&pf->aq_wait_lock); wake_up(&pf->aq_wait_queue); } #define ICE_MBX_OVERFLOW_WATERMARK 64 /** * __ice_clean_ctrlq - helper function to clean controlq rings * @pf: ptr to struct ice_pf * @q_type: specific Control queue type */ static int __ice_clean_ctrlq(struct ice_pf *pf, enum ice_ctl_q q_type) { struct device *dev = ice_pf_to_dev(pf); struct ice_rq_event_info event; struct ice_hw *hw = &pf->hw; struct ice_ctl_q_info *cq; u16 pending, i = 0; const char *qtype; u32 oldval, val; /* Do not clean control queue if/when PF reset fails */ if (test_bit(ICE_RESET_FAILED, pf->state)) return 0; switch (q_type) { case ICE_CTL_Q_ADMIN: cq = &hw->adminq; qtype = "Admin"; break; case ICE_CTL_Q_SB: cq = &hw->sbq; qtype = "Sideband"; break; case ICE_CTL_Q_MAILBOX: cq = &hw->mailboxq; qtype = "Mailbox"; /* we are going to try to detect a malicious VF, so set the * state to begin detection */ hw->mbx_snapshot.mbx_buf.state = ICE_MAL_VF_DETECT_STATE_NEW_SNAPSHOT; break; default: dev_warn(dev, "Unknown control queue type 0x%x\n", q_type); return 0; } /* check for error indications - PF_xx_AxQLEN register layout for * FW/MBX/SB are identical so just use defines for PF_FW_AxQLEN. */ val = rd32(hw, cq->rq.len); if (val & (PF_FW_ARQLEN_ARQVFE_M | PF_FW_ARQLEN_ARQOVFL_M | PF_FW_ARQLEN_ARQCRIT_M)) { oldval = val; if (val & PF_FW_ARQLEN_ARQVFE_M) dev_dbg(dev, "%s Receive Queue VF Error detected\n", qtype); if (val & PF_FW_ARQLEN_ARQOVFL_M) { dev_dbg(dev, "%s Receive Queue Overflow Error detected\n", qtype); } if (val & PF_FW_ARQLEN_ARQCRIT_M) dev_dbg(dev, "%s Receive Queue Critical Error detected\n", qtype); val &= ~(PF_FW_ARQLEN_ARQVFE_M | PF_FW_ARQLEN_ARQOVFL_M | PF_FW_ARQLEN_ARQCRIT_M); if (oldval != val) wr32(hw, cq->rq.len, val); } val = rd32(hw, cq->sq.len); if (val & (PF_FW_ATQLEN_ATQVFE_M | PF_FW_ATQLEN_ATQOVFL_M | PF_FW_ATQLEN_ATQCRIT_M)) { oldval = val; if (val & PF_FW_ATQLEN_ATQVFE_M) dev_dbg(dev, "%s Send Queue VF Error detected\n", qtype); if (val & PF_FW_ATQLEN_ATQOVFL_M) { dev_dbg(dev, "%s Send Queue Overflow Error detected\n", qtype); } if (val & PF_FW_ATQLEN_ATQCRIT_M) dev_dbg(dev, "%s Send Queue Critical Error detected\n", qtype); val &= ~(PF_FW_ATQLEN_ATQVFE_M | PF_FW_ATQLEN_ATQOVFL_M | PF_FW_ATQLEN_ATQCRIT_M); if (oldval != val) wr32(hw, cq->sq.len, val); } event.buf_len = cq->rq_buf_size; event.msg_buf = kzalloc(event.buf_len, GFP_KERNEL); if (!event.msg_buf) return 0; do { struct ice_mbx_data data = {}; u16 opcode; int ret; ret = ice_clean_rq_elem(hw, cq, &event, &pending); if (ret == -EALREADY) break; if (ret) { dev_err(dev, "%s Receive Queue event error %d\n", qtype, ret); break; } opcode = le16_to_cpu(event.desc.opcode); /* Notify any thread that might be waiting for this event */ ice_aq_check_events(pf, opcode, &event); switch (opcode) { case ice_aqc_opc_get_link_status: if (ice_handle_link_event(pf, &event)) dev_err(dev, "Could not handle link event\n"); break; case ice_aqc_opc_event_lan_overflow: ice_vf_lan_overflow_event(pf, &event); break; case ice_mbx_opc_send_msg_to_pf: data.num_msg_proc = i; data.num_pending_arq = pending; data.max_num_msgs_mbx = hw->mailboxq.num_rq_entries; data.async_watermark_val = ICE_MBX_OVERFLOW_WATERMARK; ice_vc_process_vf_msg(pf, &event, &data); break; case ice_aqc_opc_fw_logging: ice_output_fw_log(hw, &event.desc, event.msg_buf); break; case ice_aqc_opc_lldp_set_mib_change: ice_dcb_process_lldp_set_mib_change(pf, &event); break; default: dev_dbg(dev, "%s Receive Queue unknown event 0x%04x ignored\n", qtype, opcode); break; } } while (pending && (i++ < ICE_DFLT_IRQ_WORK)); kfree(event.msg_buf); return pending && (i == ICE_DFLT_IRQ_WORK); } /** * ice_ctrlq_pending - check if there is a difference between ntc and ntu * @hw: pointer to hardware info * @cq: control queue information * * returns true if there are pending messages in a queue, false if there aren't */ static bool ice_ctrlq_pending(struct ice_hw *hw, struct ice_ctl_q_info *cq) { u16 ntu; ntu = (u16)(rd32(hw, cq->rq.head) & cq->rq.head_mask); return cq->rq.next_to_clean != ntu; } /** * ice_clean_adminq_subtask - clean the AdminQ rings * @pf: board private structure */ static void ice_clean_adminq_subtask(struct ice_pf *pf) { struct ice_hw *hw = &pf->hw; if (!test_bit(ICE_ADMINQ_EVENT_PENDING, pf->state)) return; if (__ice_clean_ctrlq(pf, ICE_CTL_Q_ADMIN)) return; clear_bit(ICE_ADMINQ_EVENT_PENDING, pf->state); /* There might be a situation where new messages arrive to a control * queue between processing the last message and clearing the * EVENT_PENDING bit. So before exiting, check queue head again (using * ice_ctrlq_pending) and process new messages if any. */ if (ice_ctrlq_pending(hw, &hw->adminq)) __ice_clean_ctrlq(pf, ICE_CTL_Q_ADMIN); ice_flush(hw); } /** * ice_clean_mailboxq_subtask - clean the MailboxQ rings * @pf: board private structure */ static void ice_clean_mailboxq_subtask(struct ice_pf *pf) { struct ice_hw *hw = &pf->hw; if (!test_bit(ICE_MAILBOXQ_EVENT_PENDING, pf->state)) return; if (__ice_clean_ctrlq(pf, ICE_CTL_Q_MAILBOX)) return; clear_bit(ICE_MAILBOXQ_EVENT_PENDING, pf->state); if (ice_ctrlq_pending(hw, &hw->mailboxq)) __ice_clean_ctrlq(pf, ICE_CTL_Q_MAILBOX); ice_flush(hw); } /** * ice_clean_sbq_subtask - clean the Sideband Queue rings * @pf: board private structure */ static void ice_clean_sbq_subtask(struct ice_pf *pf) { struct ice_hw *hw = &pf->hw; /* Nothing to do here if sideband queue is not supported */ if (!ice_is_sbq_supported(hw)) { clear_bit(ICE_SIDEBANDQ_EVENT_PENDING, pf->state); return; } if (!test_bit(ICE_SIDEBANDQ_EVENT_PENDING, pf->state)) return; if (__ice_clean_ctrlq(pf, ICE_CTL_Q_SB)) return; clear_bit(ICE_SIDEBANDQ_EVENT_PENDING, pf->state); if (ice_ctrlq_pending(hw, &hw->sbq)) __ice_clean_ctrlq(pf, ICE_CTL_Q_SB); ice_flush(hw); } /** * ice_service_task_schedule - schedule the service task to wake up * @pf: board private structure * * If not already scheduled, this puts the task into the work queue. */ void ice_service_task_schedule(struct ice_pf *pf) { if (!test_bit(ICE_SERVICE_DIS, pf->state) && !test_and_set_bit(ICE_SERVICE_SCHED, pf->state) && !test_bit(ICE_NEEDS_RESTART, pf->state)) queue_work(ice_wq, &pf->serv_task); } /** * ice_service_task_complete - finish up the service task * @pf: board private structure */ static void ice_service_task_complete(struct ice_pf *pf) { WARN_ON(!test_bit(ICE_SERVICE_SCHED, pf->state)); /* force memory (pf->state) to sync before next service task */ smp_mb__before_atomic(); clear_bit(ICE_SERVICE_SCHED, pf->state); } /** * ice_service_task_stop - stop service task and cancel works * @pf: board private structure * * Return 0 if the ICE_SERVICE_DIS bit was not already set, * 1 otherwise. */ static int ice_service_task_stop(struct ice_pf *pf) { int ret; ret = test_and_set_bit(ICE_SERVICE_DIS, pf->state); if (pf->serv_tmr.function) del_timer_sync(&pf->serv_tmr); if (pf->serv_task.func) cancel_work_sync(&pf->serv_task); clear_bit(ICE_SERVICE_SCHED, pf->state); return ret; } /** * ice_service_task_restart - restart service task and schedule works * @pf: board private structure * * This function is needed for suspend and resume works (e.g WoL scenario) */ static void ice_service_task_restart(struct ice_pf *pf) { clear_bit(ICE_SERVICE_DIS, pf->state); ice_service_task_schedule(pf); } /** * ice_service_timer - timer callback to schedule service task * @t: pointer to timer_list */ static void ice_service_timer(struct timer_list *t) { struct ice_pf *pf = from_timer(pf, t, serv_tmr); mod_timer(&pf->serv_tmr, round_jiffies(pf->serv_tmr_period + jiffies)); ice_service_task_schedule(pf); } /** * ice_handle_mdd_event - handle malicious driver detect event * @pf: pointer to the PF structure * * Called from service task. OICR interrupt handler indicates MDD event. * VF MDD logging is guarded by net_ratelimit. Additional PF and VF log * messages are wrapped by netif_msg_[rx|tx]_err. Since VF Rx MDD events * disable the queue, the PF can be configured to reset the VF using ethtool * private flag mdd-auto-reset-vf. */ static void ice_handle_mdd_event(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); struct ice_hw *hw = &pf->hw; struct ice_vf *vf; unsigned int bkt; u32 reg; if (!test_and_clear_bit(ICE_MDD_EVENT_PENDING, pf->state)) { /* Since the VF MDD event logging is rate limited, check if * there are pending MDD events. */ ice_print_vfs_mdd_events(pf); return; } /* find what triggered an MDD event */ reg = rd32(hw, GL_MDET_TX_PQM); if (reg & GL_MDET_TX_PQM_VALID_M) { u8 pf_num = (reg & GL_MDET_TX_PQM_PF_NUM_M) >> GL_MDET_TX_PQM_PF_NUM_S; u16 vf_num = (reg & GL_MDET_TX_PQM_VF_NUM_M) >> GL_MDET_TX_PQM_VF_NUM_S; u8 event = (reg & GL_MDET_TX_PQM_MAL_TYPE_M) >> GL_MDET_TX_PQM_MAL_TYPE_S; u16 queue = ((reg & GL_MDET_TX_PQM_QNUM_M) >> GL_MDET_TX_PQM_QNUM_S); if (netif_msg_tx_err(pf)) dev_info(dev, "Malicious Driver Detection event %d on TX queue %d PF# %d VF# %d\n", event, queue, pf_num, vf_num); wr32(hw, GL_MDET_TX_PQM, 0xffffffff); } reg = rd32(hw, GL_MDET_TX_TCLAN); if (reg & GL_MDET_TX_TCLAN_VALID_M) { u8 pf_num = (reg & GL_MDET_TX_TCLAN_PF_NUM_M) >> GL_MDET_TX_TCLAN_PF_NUM_S; u16 vf_num = (reg & GL_MDET_TX_TCLAN_VF_NUM_M) >> GL_MDET_TX_TCLAN_VF_NUM_S; u8 event = (reg & GL_MDET_TX_TCLAN_MAL_TYPE_M) >> GL_MDET_TX_TCLAN_MAL_TYPE_S; u16 queue = ((reg & GL_MDET_TX_TCLAN_QNUM_M) >> GL_MDET_TX_TCLAN_QNUM_S); if (netif_msg_tx_err(pf)) dev_info(dev, "Malicious Driver Detection event %d on TX queue %d PF# %d VF# %d\n", event, queue, pf_num, vf_num); wr32(hw, GL_MDET_TX_TCLAN, 0xffffffff); } reg = rd32(hw, GL_MDET_RX); if (reg & GL_MDET_RX_VALID_M) { u8 pf_num = (reg & GL_MDET_RX_PF_NUM_M) >> GL_MDET_RX_PF_NUM_S; u16 vf_num = (reg & GL_MDET_RX_VF_NUM_M) >> GL_MDET_RX_VF_NUM_S; u8 event = (reg & GL_MDET_RX_MAL_TYPE_M) >> GL_MDET_RX_MAL_TYPE_S; u16 queue = ((reg & GL_MDET_RX_QNUM_M) >> GL_MDET_RX_QNUM_S); if (netif_msg_rx_err(pf)) dev_info(dev, "Malicious Driver Detection event %d on RX queue %d PF# %d VF# %d\n", event, queue, pf_num, vf_num); wr32(hw, GL_MDET_RX, 0xffffffff); } /* check to see if this PF caused an MDD event */ reg = rd32(hw, PF_MDET_TX_PQM); if (reg & PF_MDET_TX_PQM_VALID_M) { wr32(hw, PF_MDET_TX_PQM, 0xFFFF); if (netif_msg_tx_err(pf)) dev_info(dev, "Malicious Driver Detection event TX_PQM detected on PF\n"); } reg = rd32(hw, PF_MDET_TX_TCLAN); if (reg & PF_MDET_TX_TCLAN_VALID_M) { wr32(hw, PF_MDET_TX_TCLAN, 0xFFFF); if (netif_msg_tx_err(pf)) dev_info(dev, "Malicious Driver Detection event TX_TCLAN detected on PF\n"); } reg = rd32(hw, PF_MDET_RX); if (reg & PF_MDET_RX_VALID_M) { wr32(hw, PF_MDET_RX, 0xFFFF); if (netif_msg_rx_err(pf)) dev_info(dev, "Malicious Driver Detection event RX detected on PF\n"); } /* Check to see if one of the VFs caused an MDD event, and then * increment counters and set print pending */ mutex_lock(&pf->vfs.table_lock); ice_for_each_vf(pf, bkt, vf) { reg = rd32(hw, VP_MDET_TX_PQM(vf->vf_id)); if (reg & VP_MDET_TX_PQM_VALID_M) { wr32(hw, VP_MDET_TX_PQM(vf->vf_id), 0xFFFF); vf->mdd_tx_events.count++; set_bit(ICE_MDD_VF_PRINT_PENDING, pf->state); if (netif_msg_tx_err(pf)) dev_info(dev, "Malicious Driver Detection event TX_PQM detected on VF %d\n", vf->vf_id); } reg = rd32(hw, VP_MDET_TX_TCLAN(vf->vf_id)); if (reg & VP_MDET_TX_TCLAN_VALID_M) { wr32(hw, VP_MDET_TX_TCLAN(vf->vf_id), 0xFFFF); vf->mdd_tx_events.count++; set_bit(ICE_MDD_VF_PRINT_PENDING, pf->state); if (netif_msg_tx_err(pf)) dev_info(dev, "Malicious Driver Detection event TX_TCLAN detected on VF %d\n", vf->vf_id); } reg = rd32(hw, VP_MDET_TX_TDPU(vf->vf_id)); if (reg & VP_MDET_TX_TDPU_VALID_M) { wr32(hw, VP_MDET_TX_TDPU(vf->vf_id), 0xFFFF); vf->mdd_tx_events.count++; set_bit(ICE_MDD_VF_PRINT_PENDING, pf->state); if (netif_msg_tx_err(pf)) dev_info(dev, "Malicious Driver Detection event TX_TDPU detected on VF %d\n", vf->vf_id); } reg = rd32(hw, VP_MDET_RX(vf->vf_id)); if (reg & VP_MDET_RX_VALID_M) { wr32(hw, VP_MDET_RX(vf->vf_id), 0xFFFF); vf->mdd_rx_events.count++; set_bit(ICE_MDD_VF_PRINT_PENDING, pf->state); if (netif_msg_rx_err(pf)) dev_info(dev, "Malicious Driver Detection event RX detected on VF %d\n", vf->vf_id); /* Since the queue is disabled on VF Rx MDD events, the * PF can be configured to reset the VF through ethtool * private flag mdd-auto-reset-vf. */ if (test_bit(ICE_FLAG_MDD_AUTO_RESET_VF, pf->flags)) { /* VF MDD event counters will be cleared by * reset, so print the event prior to reset. */ ice_print_vf_rx_mdd_event(vf); ice_reset_vf(vf, ICE_VF_RESET_LOCK); } } } mutex_unlock(&pf->vfs.table_lock); ice_print_vfs_mdd_events(pf); } /** * ice_force_phys_link_state - Force the physical link state * @vsi: VSI to force the physical link state to up/down * @link_up: true/false indicates to set the physical link to up/down * * Force the physical link state by getting the current PHY capabilities from * hardware and setting the PHY config based on the determined capabilities. If * link changes a link event will be triggered because both the Enable Automatic * Link Update and LESM Enable bits are set when setting the PHY capabilities. * * Returns 0 on success, negative on failure */ static int ice_force_phys_link_state(struct ice_vsi *vsi, bool link_up) { struct ice_aqc_get_phy_caps_data *pcaps; struct ice_aqc_set_phy_cfg_data *cfg; struct ice_port_info *pi; struct device *dev; int retcode; if (!vsi || !vsi->port_info || !vsi->back) return -EINVAL; if (vsi->type != ICE_VSI_PF) return 0; dev = ice_pf_to_dev(vsi->back); pi = vsi->port_info; pcaps = kzalloc(sizeof(*pcaps), GFP_KERNEL); if (!pcaps) return -ENOMEM; retcode = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_ACTIVE_CFG, pcaps, NULL); if (retcode) { dev_err(dev, "Failed to get phy capabilities, VSI %d error %d\n", vsi->vsi_num, retcode); retcode = -EIO; goto out; } /* No change in link */ if (link_up == !!(pcaps->caps & ICE_AQC_PHY_EN_LINK) && link_up == !!(pi->phy.link_info.link_info & ICE_AQ_LINK_UP)) goto out; /* Use the current user PHY configuration. The current user PHY * configuration is initialized during probe from PHY capabilities * software mode, and updated on set PHY configuration. */ cfg = kmemdup(&pi->phy.curr_user_phy_cfg, sizeof(*cfg), GFP_KERNEL); if (!cfg) { retcode = -ENOMEM; goto out; } cfg->caps |= ICE_AQ_PHY_ENA_AUTO_LINK_UPDT; if (link_up) cfg->caps |= ICE_AQ_PHY_ENA_LINK; else cfg->caps &= ~ICE_AQ_PHY_ENA_LINK; retcode = ice_aq_set_phy_cfg(&vsi->back->hw, pi, cfg, NULL); if (retcode) { dev_err(dev, "Failed to set phy config, VSI %d error %d\n", vsi->vsi_num, retcode); retcode = -EIO; } kfree(cfg); out: kfree(pcaps); return retcode; } /** * ice_init_nvm_phy_type - Initialize the NVM PHY type * @pi: port info structure * * Initialize nvm_phy_type_[low|high] for link lenient mode support */ static int ice_init_nvm_phy_type(struct ice_port_info *pi) { struct ice_aqc_get_phy_caps_data *pcaps; struct ice_pf *pf = pi->hw->back; int err; pcaps = kzalloc(sizeof(*pcaps), GFP_KERNEL); if (!pcaps) return -ENOMEM; err = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_TOPO_CAP_NO_MEDIA, pcaps, NULL); if (err) { dev_err(ice_pf_to_dev(pf), "Get PHY capability failed.\n"); goto out; } pf->nvm_phy_type_hi = pcaps->phy_type_high; pf->nvm_phy_type_lo = pcaps->phy_type_low; out: kfree(pcaps); return err; } /** * ice_init_link_dflt_override - Initialize link default override * @pi: port info structure * * Initialize link default override and PHY total port shutdown during probe */ static void ice_init_link_dflt_override(struct ice_port_info *pi) { struct ice_link_default_override_tlv *ldo; struct ice_pf *pf = pi->hw->back; ldo = &pf->link_dflt_override; if (ice_get_link_default_override(ldo, pi)) return; if (!(ldo->options & ICE_LINK_OVERRIDE_PORT_DIS)) return; /* Enable Total Port Shutdown (override/replace link-down-on-close * ethtool private flag) for ports with Port Disable bit set. */ set_bit(ICE_FLAG_TOTAL_PORT_SHUTDOWN_ENA, pf->flags); set_bit(ICE_FLAG_LINK_DOWN_ON_CLOSE_ENA, pf->flags); } /** * ice_init_phy_cfg_dflt_override - Initialize PHY cfg default override settings * @pi: port info structure * * If default override is enabled, initialize the user PHY cfg speed and FEC * settings using the default override mask from the NVM. * * The PHY should only be configured with the default override settings the * first time media is available. The ICE_LINK_DEFAULT_OVERRIDE_PENDING state * is used to indicate that the user PHY cfg default override is initialized * and the PHY has not been configured with the default override settings. The * state is set here, and cleared in ice_configure_phy the first time the PHY is * configured. * * This function should be called only if the FW doesn't support default * configuration mode, as reported by ice_fw_supports_report_dflt_cfg. */ static void ice_init_phy_cfg_dflt_override(struct ice_port_info *pi) { struct ice_link_default_override_tlv *ldo; struct ice_aqc_set_phy_cfg_data *cfg; struct ice_phy_info *phy = &pi->phy; struct ice_pf *pf = pi->hw->back; ldo = &pf->link_dflt_override; /* If link default override is enabled, use to mask NVM PHY capabilities * for speed and FEC default configuration. */ cfg = &phy->curr_user_phy_cfg; if (ldo->phy_type_low || ldo->phy_type_high) { cfg->phy_type_low = pf->nvm_phy_type_lo & cpu_to_le64(ldo->phy_type_low); cfg->phy_type_high = pf->nvm_phy_type_hi & cpu_to_le64(ldo->phy_type_high); } cfg->link_fec_opt = ldo->fec_options; phy->curr_user_fec_req = ICE_FEC_AUTO; set_bit(ICE_LINK_DEFAULT_OVERRIDE_PENDING, pf->state); } /** * ice_init_phy_user_cfg - Initialize the PHY user configuration * @pi: port info structure * * Initialize the current user PHY configuration, speed, FEC, and FC requested * mode to default. The PHY defaults are from get PHY capabilities topology * with media so call when media is first available. An error is returned if * called when media is not available. The PHY initialization completed state is * set here. * * These configurations are used when setting PHY * configuration. The user PHY configuration is updated on set PHY * configuration. Returns 0 on success, negative on failure */ static int ice_init_phy_user_cfg(struct ice_port_info *pi) { struct ice_aqc_get_phy_caps_data *pcaps; struct ice_phy_info *phy = &pi->phy; struct ice_pf *pf = pi->hw->back; int err; if (!(phy->link_info.link_info & ICE_AQ_MEDIA_AVAILABLE)) return -EIO; pcaps = kzalloc(sizeof(*pcaps), GFP_KERNEL); if (!pcaps) return -ENOMEM; if (ice_fw_supports_report_dflt_cfg(pi->hw)) err = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_DFLT_CFG, pcaps, NULL); else err = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_TOPO_CAP_MEDIA, pcaps, NULL); if (err) { dev_err(ice_pf_to_dev(pf), "Get PHY capability failed.\n"); goto err_out; } ice_copy_phy_caps_to_cfg(pi, pcaps, &pi->phy.curr_user_phy_cfg); /* check if lenient mode is supported and enabled */ if (ice_fw_supports_link_override(pi->hw) && !(pcaps->module_compliance_enforcement & ICE_AQC_MOD_ENFORCE_STRICT_MODE)) { set_bit(ICE_FLAG_LINK_LENIENT_MODE_ENA, pf->flags); /* if the FW supports default PHY configuration mode, then the driver * does not have to apply link override settings. If not, * initialize user PHY configuration with link override values */ if (!ice_fw_supports_report_dflt_cfg(pi->hw) && (pf->link_dflt_override.options & ICE_LINK_OVERRIDE_EN)) { ice_init_phy_cfg_dflt_override(pi); goto out; } } /* if link default override is not enabled, set user flow control and * FEC settings based on what get_phy_caps returned */ phy->curr_user_fec_req = ice_caps_to_fec_mode(pcaps->caps, pcaps->link_fec_options); phy->curr_user_fc_req = ice_caps_to_fc_mode(pcaps->caps); out: phy->curr_user_speed_req = ICE_AQ_LINK_SPEED_M; set_bit(ICE_PHY_INIT_COMPLETE, pf->state); err_out: kfree(pcaps); return err; } /** * ice_configure_phy - configure PHY * @vsi: VSI of PHY * * Set the PHY configuration. If the current PHY configuration is the same as * the curr_user_phy_cfg, then do nothing to avoid link flap. Otherwise * configure the based get PHY capabilities for topology with media. */ static int ice_configure_phy(struct ice_vsi *vsi) { struct device *dev = ice_pf_to_dev(vsi->back); struct ice_port_info *pi = vsi->port_info; struct ice_aqc_get_phy_caps_data *pcaps; struct ice_aqc_set_phy_cfg_data *cfg; struct ice_phy_info *phy = &pi->phy; struct ice_pf *pf = vsi->back; int err; /* Ensure we have media as we cannot configure a medialess port */ if (!(phy->link_info.link_info & ICE_AQ_MEDIA_AVAILABLE)) return -EPERM; ice_print_topo_conflict(vsi); if (!test_bit(ICE_FLAG_LINK_LENIENT_MODE_ENA, pf->flags) && phy->link_info.topo_media_conflict == ICE_AQ_LINK_TOPO_UNSUPP_MEDIA) return -EPERM; if (test_bit(ICE_FLAG_LINK_DOWN_ON_CLOSE_ENA, pf->flags)) return ice_force_phys_link_state(vsi, true); pcaps = kzalloc(sizeof(*pcaps), GFP_KERNEL); if (!pcaps) return -ENOMEM; /* Get current PHY config */ err = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_ACTIVE_CFG, pcaps, NULL); if (err) { dev_err(dev, "Failed to get PHY configuration, VSI %d error %d\n", vsi->vsi_num, err); goto done; } /* If PHY enable link is configured and configuration has not changed, * there's nothing to do */ if (pcaps->caps & ICE_AQC_PHY_EN_LINK && ice_phy_caps_equals_cfg(pcaps, &phy->curr_user_phy_cfg)) goto done; /* Use PHY topology as baseline for configuration */ memset(pcaps, 0, sizeof(*pcaps)); if (ice_fw_supports_report_dflt_cfg(pi->hw)) err = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_DFLT_CFG, pcaps, NULL); else err = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_TOPO_CAP_MEDIA, pcaps, NULL); if (err) { dev_err(dev, "Failed to get PHY caps, VSI %d error %d\n", vsi->vsi_num, err); goto done; } cfg = kzalloc(sizeof(*cfg), GFP_KERNEL); if (!cfg) { err = -ENOMEM; goto done; } ice_copy_phy_caps_to_cfg(pi, pcaps, cfg); /* Speed - If default override pending, use curr_user_phy_cfg set in * ice_init_phy_user_cfg_ldo. */ if (test_and_clear_bit(ICE_LINK_DEFAULT_OVERRIDE_PENDING, vsi->back->state)) { cfg->phy_type_low = phy->curr_user_phy_cfg.phy_type_low; cfg->phy_type_high = phy->curr_user_phy_cfg.phy_type_high; } else { u64 phy_low = 0, phy_high = 0; ice_update_phy_type(&phy_low, &phy_high, pi->phy.curr_user_speed_req); cfg->phy_type_low = pcaps->phy_type_low & cpu_to_le64(phy_low); cfg->phy_type_high = pcaps->phy_type_high & cpu_to_le64(phy_high); } /* Can't provide what was requested; use PHY capabilities */ if (!cfg->phy_type_low && !cfg->phy_type_high) { cfg->phy_type_low = pcaps->phy_type_low; cfg->phy_type_high = pcaps->phy_type_high; } /* FEC */ ice_cfg_phy_fec(pi, cfg, phy->curr_user_fec_req); /* Can't provide what was requested; use PHY capabilities */ if (cfg->link_fec_opt != (cfg->link_fec_opt & pcaps->link_fec_options)) { cfg->caps |= pcaps->caps & ICE_AQC_PHY_EN_AUTO_FEC; cfg->link_fec_opt = pcaps->link_fec_options; } /* Flow Control - always supported; no need to check against * capabilities */ ice_cfg_phy_fc(pi, cfg, phy->curr_user_fc_req); /* Enable link and link update */ cfg->caps |= ICE_AQ_PHY_ENA_AUTO_LINK_UPDT | ICE_AQ_PHY_ENA_LINK; err = ice_aq_set_phy_cfg(&pf->hw, pi, cfg, NULL); if (err) dev_err(dev, "Failed to set phy config, VSI %d error %d\n", vsi->vsi_num, err); kfree(cfg); done: kfree(pcaps); return err; } /** * ice_check_media_subtask - Check for media * @pf: pointer to PF struct * * If media is available, then initialize PHY user configuration if it is not * been, and configure the PHY if the interface is up. */ static void ice_check_media_subtask(struct ice_pf *pf) { struct ice_port_info *pi; struct ice_vsi *vsi; int err; /* No need to check for media if it's already present */ if (!test_bit(ICE_FLAG_NO_MEDIA, pf->flags)) return; vsi = ice_get_main_vsi(pf); if (!vsi) return; /* Refresh link info and check if media is present */ pi = vsi->port_info; err = ice_update_link_info(pi); if (err) return; ice_check_link_cfg_err(pf, pi->phy.link_info.link_cfg_err); if (pi->phy.link_info.link_info & ICE_AQ_MEDIA_AVAILABLE) { if (!test_bit(ICE_PHY_INIT_COMPLETE, pf->state)) ice_init_phy_user_cfg(pi); /* PHY settings are reset on media insertion, reconfigure * PHY to preserve settings. */ if (test_bit(ICE_VSI_DOWN, vsi->state) && test_bit(ICE_FLAG_LINK_DOWN_ON_CLOSE_ENA, vsi->back->flags)) return; err = ice_configure_phy(vsi); if (!err) clear_bit(ICE_FLAG_NO_MEDIA, pf->flags); /* A Link Status Event will be generated; the event handler * will complete bringing the interface up */ } } /** * ice_service_task - manage and run subtasks * @work: pointer to work_struct contained by the PF struct */ static void ice_service_task(struct work_struct *work) { struct ice_pf *pf = container_of(work, struct ice_pf, serv_task); unsigned long start_time = jiffies; /* subtasks */ /* process reset requests first */ ice_reset_subtask(pf); /* bail if a reset/recovery cycle is pending or rebuild failed */ if (ice_is_reset_in_progress(pf->state) || test_bit(ICE_SUSPENDED, pf->state) || test_bit(ICE_NEEDS_RESTART, pf->state)) { ice_service_task_complete(pf); return; } if (test_and_clear_bit(ICE_AUX_ERR_PENDING, pf->state)) { struct iidc_event *event; event = kzalloc(sizeof(*event), GFP_KERNEL); if (event) { set_bit(IIDC_EVENT_CRIT_ERR, event->type); /* report the entire OICR value to AUX driver */ swap(event->reg, pf->oicr_err_reg); ice_send_event_to_aux(pf, event); kfree(event); } } /* unplug aux dev per request, if an unplug request came in * while processing a plug request, this will handle it */ if (test_and_clear_bit(ICE_FLAG_UNPLUG_AUX_DEV, pf->flags)) ice_unplug_aux_dev(pf); /* Plug aux device per request */ if (test_and_clear_bit(ICE_FLAG_PLUG_AUX_DEV, pf->flags)) ice_plug_aux_dev(pf); if (test_and_clear_bit(ICE_FLAG_MTU_CHANGED, pf->flags)) { struct iidc_event *event; event = kzalloc(sizeof(*event), GFP_KERNEL); if (event) { set_bit(IIDC_EVENT_AFTER_MTU_CHANGE, event->type); ice_send_event_to_aux(pf, event); kfree(event); } } ice_clean_adminq_subtask(pf); ice_check_media_subtask(pf); ice_check_for_hang_subtask(pf); ice_sync_fltr_subtask(pf); ice_handle_mdd_event(pf); ice_watchdog_subtask(pf); if (ice_is_safe_mode(pf)) { ice_service_task_complete(pf); return; } ice_process_vflr_event(pf); ice_clean_mailboxq_subtask(pf); ice_clean_sbq_subtask(pf); ice_sync_arfs_fltrs(pf); ice_flush_fdir_ctx(pf); /* Clear ICE_SERVICE_SCHED flag to allow scheduling next event */ ice_service_task_complete(pf); /* If the tasks have taken longer than one service timer period * or there is more work to be done, reset the service timer to * schedule the service task now. */ if (time_after(jiffies, (start_time + pf->serv_tmr_period)) || test_bit(ICE_MDD_EVENT_PENDING, pf->state) || test_bit(ICE_VFLR_EVENT_PENDING, pf->state) || test_bit(ICE_MAILBOXQ_EVENT_PENDING, pf->state) || test_bit(ICE_FD_VF_FLUSH_CTX, pf->state) || test_bit(ICE_SIDEBANDQ_EVENT_PENDING, pf->state) || test_bit(ICE_ADMINQ_EVENT_PENDING, pf->state)) mod_timer(&pf->serv_tmr, jiffies); } /** * ice_set_ctrlq_len - helper function to set controlq length * @hw: pointer to the HW instance */ static void ice_set_ctrlq_len(struct ice_hw *hw) { hw->adminq.num_rq_entries = ICE_AQ_LEN; hw->adminq.num_sq_entries = ICE_AQ_LEN; hw->adminq.rq_buf_size = ICE_AQ_MAX_BUF_LEN; hw->adminq.sq_buf_size = ICE_AQ_MAX_BUF_LEN; hw->mailboxq.num_rq_entries = PF_MBX_ARQLEN_ARQLEN_M; hw->mailboxq.num_sq_entries = ICE_MBXSQ_LEN; hw->mailboxq.rq_buf_size = ICE_MBXQ_MAX_BUF_LEN; hw->mailboxq.sq_buf_size = ICE_MBXQ_MAX_BUF_LEN; hw->sbq.num_rq_entries = ICE_SBQ_LEN; hw->sbq.num_sq_entries = ICE_SBQ_LEN; hw->sbq.rq_buf_size = ICE_SBQ_MAX_BUF_LEN; hw->sbq.sq_buf_size = ICE_SBQ_MAX_BUF_LEN; } /** * ice_schedule_reset - schedule a reset * @pf: board private structure * @reset: reset being requested */ int ice_schedule_reset(struct ice_pf *pf, enum ice_reset_req reset) { struct device *dev = ice_pf_to_dev(pf); /* bail out if earlier reset has failed */ if (test_bit(ICE_RESET_FAILED, pf->state)) { dev_dbg(dev, "earlier reset has failed\n"); return -EIO; } /* bail if reset/recovery already in progress */ if (ice_is_reset_in_progress(pf->state)) { dev_dbg(dev, "Reset already in progress\n"); return -EBUSY; } switch (reset) { case ICE_RESET_PFR: set_bit(ICE_PFR_REQ, pf->state); break; case ICE_RESET_CORER: set_bit(ICE_CORER_REQ, pf->state); break; case ICE_RESET_GLOBR: set_bit(ICE_GLOBR_REQ, pf->state); break; default: return -EINVAL; } ice_service_task_schedule(pf); return 0; } /** * ice_irq_affinity_notify - Callback for affinity changes * @notify: context as to what irq was changed * @mask: the new affinity mask * * This is a callback function used by the irq_set_affinity_notifier function * so that we may register to receive changes to the irq affinity masks. */ static void ice_irq_affinity_notify(struct irq_affinity_notify *notify, const cpumask_t *mask) { struct ice_q_vector *q_vector = container_of(notify, struct ice_q_vector, affinity_notify); cpumask_copy(&q_vector->affinity_mask, mask); } /** * ice_irq_affinity_release - Callback for affinity notifier release * @ref: internal core kernel usage * * This is a callback function used by the irq_set_affinity_notifier function * to inform the current notification subscriber that they will no longer * receive notifications. */ static void ice_irq_affinity_release(struct kref __always_unused *ref) {} /** * ice_vsi_ena_irq - Enable IRQ for the given VSI * @vsi: the VSI being configured */ static int ice_vsi_ena_irq(struct ice_vsi *vsi) { struct ice_hw *hw = &vsi->back->hw; int i; ice_for_each_q_vector(vsi, i) ice_irq_dynamic_ena(hw, vsi, vsi->q_vectors[i]); ice_flush(hw); return 0; } /** * ice_vsi_req_irq_msix - get MSI-X vectors from the OS for the VSI * @vsi: the VSI being configured * @basename: name for the vector */ static int ice_vsi_req_irq_msix(struct ice_vsi *vsi, char *basename) { int q_vectors = vsi->num_q_vectors; struct ice_pf *pf = vsi->back; struct device *dev; int rx_int_idx = 0; int tx_int_idx = 0; int vector, err; int irq_num; dev = ice_pf_to_dev(pf); for (vector = 0; vector < q_vectors; vector++) { struct ice_q_vector *q_vector = vsi->q_vectors[vector]; irq_num = q_vector->irq.virq; if (q_vector->tx.tx_ring && q_vector->rx.rx_ring) { snprintf(q_vector->name, sizeof(q_vector->name) - 1, "%s-%s-%d", basename, "TxRx", rx_int_idx++); tx_int_idx++; } else if (q_vector->rx.rx_ring) { snprintf(q_vector->name, sizeof(q_vector->name) - 1, "%s-%s-%d", basename, "rx", rx_int_idx++); } else if (q_vector->tx.tx_ring) { snprintf(q_vector->name, sizeof(q_vector->name) - 1, "%s-%s-%d", basename, "tx", tx_int_idx++); } else { /* skip this unused q_vector */ continue; } if (vsi->type == ICE_VSI_CTRL && vsi->vf) err = devm_request_irq(dev, irq_num, vsi->irq_handler, IRQF_SHARED, q_vector->name, q_vector); else err = devm_request_irq(dev, irq_num, vsi->irq_handler, 0, q_vector->name, q_vector); if (err) { netdev_err(vsi->netdev, "MSIX request_irq failed, error: %d\n", err); goto free_q_irqs; } /* register for affinity change notifications */ if (!IS_ENABLED(CONFIG_RFS_ACCEL)) { struct irq_affinity_notify *affinity_notify; affinity_notify = &q_vector->affinity_notify; affinity_notify->notify = ice_irq_affinity_notify; affinity_notify->release = ice_irq_affinity_release; irq_set_affinity_notifier(irq_num, affinity_notify); } /* assign the mask for this irq */ irq_set_affinity_hint(irq_num, &q_vector->affinity_mask); } err = ice_set_cpu_rx_rmap(vsi); if (err) { netdev_err(vsi->netdev, "Failed to setup CPU RMAP on VSI %u: %pe\n", vsi->vsi_num, ERR_PTR(err)); goto free_q_irqs; } vsi->irqs_ready = true; return 0; free_q_irqs: while (vector--) { irq_num = vsi->q_vectors[vector]->irq.virq; if (!IS_ENABLED(CONFIG_RFS_ACCEL)) irq_set_affinity_notifier(irq_num, NULL); irq_set_affinity_hint(irq_num, NULL); devm_free_irq(dev, irq_num, &vsi->q_vectors[vector]); } return err; } /** * ice_xdp_alloc_setup_rings - Allocate and setup Tx rings for XDP * @vsi: VSI to setup Tx rings used by XDP * * Return 0 on success and negative value on error */ static int ice_xdp_alloc_setup_rings(struct ice_vsi *vsi) { struct device *dev = ice_pf_to_dev(vsi->back); struct ice_tx_desc *tx_desc; int i, j; ice_for_each_xdp_txq(vsi, i) { u16 xdp_q_idx = vsi->alloc_txq + i; struct ice_ring_stats *ring_stats; struct ice_tx_ring *xdp_ring; xdp_ring = kzalloc(sizeof(*xdp_ring), GFP_KERNEL); if (!xdp_ring) goto free_xdp_rings; ring_stats = kzalloc(sizeof(*ring_stats), GFP_KERNEL); if (!ring_stats) { ice_free_tx_ring(xdp_ring); goto free_xdp_rings; } xdp_ring->ring_stats = ring_stats; xdp_ring->q_index = xdp_q_idx; xdp_ring->reg_idx = vsi->txq_map[xdp_q_idx]; xdp_ring->vsi = vsi; xdp_ring->netdev = NULL; xdp_ring->dev = dev; xdp_ring->count = vsi->num_tx_desc; WRITE_ONCE(vsi->xdp_rings[i], xdp_ring); if (ice_setup_tx_ring(xdp_ring)) goto free_xdp_rings; ice_set_ring_xdp(xdp_ring); spin_lock_init(&xdp_ring->tx_lock); for (j = 0; j < xdp_ring->count; j++) { tx_desc = ICE_TX_DESC(xdp_ring, j); tx_desc->cmd_type_offset_bsz = 0; } } return 0; free_xdp_rings: for (; i >= 0; i--) { if (vsi->xdp_rings[i] && vsi->xdp_rings[i]->desc) { kfree_rcu(vsi->xdp_rings[i]->ring_stats, rcu); vsi->xdp_rings[i]->ring_stats = NULL; ice_free_tx_ring(vsi->xdp_rings[i]); } } return -ENOMEM; } /** * ice_vsi_assign_bpf_prog - set or clear bpf prog pointer on VSI * @vsi: VSI to set the bpf prog on * @prog: the bpf prog pointer */ static void ice_vsi_assign_bpf_prog(struct ice_vsi *vsi, struct bpf_prog *prog) { struct bpf_prog *old_prog; int i; old_prog = xchg(&vsi->xdp_prog, prog); ice_for_each_rxq(vsi, i) WRITE_ONCE(vsi->rx_rings[i]->xdp_prog, vsi->xdp_prog); if (old_prog) bpf_prog_put(old_prog); } /** * ice_prepare_xdp_rings - Allocate, configure and setup Tx rings for XDP * @vsi: VSI to bring up Tx rings used by XDP * @prog: bpf program that will be assigned to VSI * * Return 0 on success and negative value on error */ int ice_prepare_xdp_rings(struct ice_vsi *vsi, struct bpf_prog *prog) { u16 max_txqs[ICE_MAX_TRAFFIC_CLASS] = { 0 }; int xdp_rings_rem = vsi->num_xdp_txq; struct ice_pf *pf = vsi->back; struct ice_qs_cfg xdp_qs_cfg = { .qs_mutex = &pf->avail_q_mutex, .pf_map = pf->avail_txqs, .pf_map_size = pf->max_pf_txqs, .q_count = vsi->num_xdp_txq, .scatter_count = ICE_MAX_SCATTER_TXQS, .vsi_map = vsi->txq_map, .vsi_map_offset = vsi->alloc_txq, .mapping_mode = ICE_VSI_MAP_CONTIG }; struct device *dev; int i, v_idx; int status; dev = ice_pf_to_dev(pf); vsi->xdp_rings = devm_kcalloc(dev, vsi->num_xdp_txq, sizeof(*vsi->xdp_rings), GFP_KERNEL); if (!vsi->xdp_rings) return -ENOMEM; vsi->xdp_mapping_mode = xdp_qs_cfg.mapping_mode; if (__ice_vsi_get_qs(&xdp_qs_cfg)) goto err_map_xdp; if (static_key_enabled(&ice_xdp_locking_key)) netdev_warn(vsi->netdev, "Could not allocate one XDP Tx ring per CPU, XDP_TX/XDP_REDIRECT actions will be slower\n"); if (ice_xdp_alloc_setup_rings(vsi)) goto clear_xdp_rings; /* follow the logic from ice_vsi_map_rings_to_vectors */ ice_for_each_q_vector(vsi, v_idx) { struct ice_q_vector *q_vector = vsi->q_vectors[v_idx]; int xdp_rings_per_v, q_id, q_base; xdp_rings_per_v = DIV_ROUND_UP(xdp_rings_rem, vsi->num_q_vectors - v_idx); q_base = vsi->num_xdp_txq - xdp_rings_rem; for (q_id = q_base; q_id < (q_base + xdp_rings_per_v); q_id++) { struct ice_tx_ring *xdp_ring = vsi->xdp_rings[q_id]; xdp_ring->q_vector = q_vector; xdp_ring->next = q_vector->tx.tx_ring; q_vector->tx.tx_ring = xdp_ring; } xdp_rings_rem -= xdp_rings_per_v; } ice_for_each_rxq(vsi, i) { if (static_key_enabled(&ice_xdp_locking_key)) { vsi->rx_rings[i]->xdp_ring = vsi->xdp_rings[i % vsi->num_xdp_txq]; } else { struct ice_q_vector *q_vector = vsi->rx_rings[i]->q_vector; struct ice_tx_ring *ring; ice_for_each_tx_ring(ring, q_vector->tx) { if (ice_ring_is_xdp(ring)) { vsi->rx_rings[i]->xdp_ring = ring; break; } } } ice_tx_xsk_pool(vsi, i); } /* omit the scheduler update if in reset path; XDP queues will be * taken into account at the end of ice_vsi_rebuild, where * ice_cfg_vsi_lan is being called */ if (ice_is_reset_in_progress(pf->state)) return 0; /* tell the Tx scheduler that right now we have * additional queues */ for (i = 0; i < vsi->tc_cfg.numtc; i++) max_txqs[i] = vsi->num_txq + vsi->num_xdp_txq; status = ice_cfg_vsi_lan(vsi->port_info, vsi->idx, vsi->tc_cfg.ena_tc, max_txqs); if (status) { dev_err(dev, "Failed VSI LAN queue config for XDP, error: %d\n", status); goto clear_xdp_rings; } /* assign the prog only when it's not already present on VSI; * this flow is a subject of both ethtool -L and ndo_bpf flows; * VSI rebuild that happens under ethtool -L can expose us to * the bpf_prog refcount issues as we would be swapping same * bpf_prog pointers from vsi->xdp_prog and calling bpf_prog_put * on it as it would be treated as an 'old_prog'; for ndo_bpf * this is not harmful as dev_xdp_install bumps the refcount * before calling the op exposed by the driver; */ if (!ice_is_xdp_ena_vsi(vsi)) ice_vsi_assign_bpf_prog(vsi, prog); return 0; clear_xdp_rings: ice_for_each_xdp_txq(vsi, i) if (vsi->xdp_rings[i]) { kfree_rcu(vsi->xdp_rings[i], rcu); vsi->xdp_rings[i] = NULL; } err_map_xdp: mutex_lock(&pf->avail_q_mutex); ice_for_each_xdp_txq(vsi, i) { clear_bit(vsi->txq_map[i + vsi->alloc_txq], pf->avail_txqs); vsi->txq_map[i + vsi->alloc_txq] = ICE_INVAL_Q_INDEX; } mutex_unlock(&pf->avail_q_mutex); devm_kfree(dev, vsi->xdp_rings); return -ENOMEM; } /** * ice_destroy_xdp_rings - undo the configuration made by ice_prepare_xdp_rings * @vsi: VSI to remove XDP rings * * Detach XDP rings from irq vectors, clean up the PF bitmap and free * resources */ int ice_destroy_xdp_rings(struct ice_vsi *vsi) { u16 max_txqs[ICE_MAX_TRAFFIC_CLASS] = { 0 }; struct ice_pf *pf = vsi->back; int i, v_idx; /* q_vectors are freed in reset path so there's no point in detaching * rings; in case of rebuild being triggered not from reset bits * in pf->state won't be set, so additionally check first q_vector * against NULL */ if (ice_is_reset_in_progress(pf->state) || !vsi->q_vectors[0]) goto free_qmap; ice_for_each_q_vector(vsi, v_idx) { struct ice_q_vector *q_vector = vsi->q_vectors[v_idx]; struct ice_tx_ring *ring; ice_for_each_tx_ring(ring, q_vector->tx) if (!ring->tx_buf || !ice_ring_is_xdp(ring)) break; /* restore the value of last node prior to XDP setup */ q_vector->tx.tx_ring = ring; } free_qmap: mutex_lock(&pf->avail_q_mutex); ice_for_each_xdp_txq(vsi, i) { clear_bit(vsi->txq_map[i + vsi->alloc_txq], pf->avail_txqs); vsi->txq_map[i + vsi->alloc_txq] = ICE_INVAL_Q_INDEX; } mutex_unlock(&pf->avail_q_mutex); ice_for_each_xdp_txq(vsi, i) if (vsi->xdp_rings[i]) { if (vsi->xdp_rings[i]->desc) { synchronize_rcu(); ice_free_tx_ring(vsi->xdp_rings[i]); } kfree_rcu(vsi->xdp_rings[i]->ring_stats, rcu); vsi->xdp_rings[i]->ring_stats = NULL; kfree_rcu(vsi->xdp_rings[i], rcu); vsi->xdp_rings[i] = NULL; } devm_kfree(ice_pf_to_dev(pf), vsi->xdp_rings); vsi->xdp_rings = NULL; if (static_key_enabled(&ice_xdp_locking_key)) static_branch_dec(&ice_xdp_locking_key); if (ice_is_reset_in_progress(pf->state) || !vsi->q_vectors[0]) return 0; ice_vsi_assign_bpf_prog(vsi, NULL); /* notify Tx scheduler that we destroyed XDP queues and bring * back the old number of child nodes */ for (i = 0; i < vsi->tc_cfg.numtc; i++) max_txqs[i] = vsi->num_txq; /* change number of XDP Tx queues to 0 */ vsi->num_xdp_txq = 0; return ice_cfg_vsi_lan(vsi->port_info, vsi->idx, vsi->tc_cfg.ena_tc, max_txqs); } /** * ice_vsi_rx_napi_schedule - Schedule napi on RX queues from VSI * @vsi: VSI to schedule napi on */ static void ice_vsi_rx_napi_schedule(struct ice_vsi *vsi) { int i; ice_for_each_rxq(vsi, i) { struct ice_rx_ring *rx_ring = vsi->rx_rings[i]; if (rx_ring->xsk_pool) napi_schedule(&rx_ring->q_vector->napi); } } /** * ice_vsi_determine_xdp_res - figure out how many Tx qs can XDP have * @vsi: VSI to determine the count of XDP Tx qs * * returns 0 if Tx qs count is higher than at least half of CPU count, * -ENOMEM otherwise */ int ice_vsi_determine_xdp_res(struct ice_vsi *vsi) { u16 avail = ice_get_avail_txq_count(vsi->back); u16 cpus = num_possible_cpus(); if (avail < cpus / 2) return -ENOMEM; vsi->num_xdp_txq = min_t(u16, avail, cpus); if (vsi->num_xdp_txq < cpus) static_branch_inc(&ice_xdp_locking_key); return 0; } /** * ice_max_xdp_frame_size - returns the maximum allowed frame size for XDP * @vsi: Pointer to VSI structure */ static int ice_max_xdp_frame_size(struct ice_vsi *vsi) { if (test_bit(ICE_FLAG_LEGACY_RX, vsi->back->flags)) return ICE_RXBUF_1664; else return ICE_RXBUF_3072; } /** * ice_xdp_setup_prog - Add or remove XDP eBPF program * @vsi: VSI to setup XDP for * @prog: XDP program * @extack: netlink extended ack */ static int ice_xdp_setup_prog(struct ice_vsi *vsi, struct bpf_prog *prog, struct netlink_ext_ack *extack) { unsigned int frame_size = vsi->netdev->mtu + ICE_ETH_PKT_HDR_PAD; bool if_running = netif_running(vsi->netdev); int ret = 0, xdp_ring_err = 0; if (prog && !prog->aux->xdp_has_frags) { if (frame_size > ice_max_xdp_frame_size(vsi)) { NL_SET_ERR_MSG_MOD(extack, "MTU is too large for linear frames and XDP prog does not support frags"); return -EOPNOTSUPP; } } /* hot swap progs and avoid toggling link */ if (ice_is_xdp_ena_vsi(vsi) == !!prog) { ice_vsi_assign_bpf_prog(vsi, prog); return 0; } /* need to stop netdev while setting up the program for Rx rings */ if (if_running && !test_and_set_bit(ICE_VSI_DOWN, vsi->state)) { ret = ice_down(vsi); if (ret) { NL_SET_ERR_MSG_MOD(extack, "Preparing device for XDP attach failed"); return ret; } } if (!ice_is_xdp_ena_vsi(vsi) && prog) { xdp_ring_err = ice_vsi_determine_xdp_res(vsi); if (xdp_ring_err) { NL_SET_ERR_MSG_MOD(extack, "Not enough Tx resources for XDP"); } else { xdp_ring_err = ice_prepare_xdp_rings(vsi, prog); if (xdp_ring_err) NL_SET_ERR_MSG_MOD(extack, "Setting up XDP Tx resources failed"); } xdp_features_set_redirect_target(vsi->netdev, true); /* reallocate Rx queues that are used for zero-copy */ xdp_ring_err = ice_realloc_zc_buf(vsi, true); if (xdp_ring_err) NL_SET_ERR_MSG_MOD(extack, "Setting up XDP Rx resources failed"); } else if (ice_is_xdp_ena_vsi(vsi) && !prog) { xdp_features_clear_redirect_target(vsi->netdev); xdp_ring_err = ice_destroy_xdp_rings(vsi); if (xdp_ring_err) NL_SET_ERR_MSG_MOD(extack, "Freeing XDP Tx resources failed"); /* reallocate Rx queues that were used for zero-copy */ xdp_ring_err = ice_realloc_zc_buf(vsi, false); if (xdp_ring_err) NL_SET_ERR_MSG_MOD(extack, "Freeing XDP Rx resources failed"); } if (if_running) ret = ice_up(vsi); if (!ret && prog) ice_vsi_rx_napi_schedule(vsi); return (ret || xdp_ring_err) ? -ENOMEM : 0; } /** * ice_xdp_safe_mode - XDP handler for safe mode * @dev: netdevice * @xdp: XDP command */ static int ice_xdp_safe_mode(struct net_device __always_unused *dev, struct netdev_bpf *xdp) { NL_SET_ERR_MSG_MOD(xdp->extack, "Please provide working DDP firmware package in order to use XDP\n" "Refer to Documentation/networking/device_drivers/ethernet/intel/ice.rst"); return -EOPNOTSUPP; } /** * ice_xdp - implements XDP handler * @dev: netdevice * @xdp: XDP command */ static int ice_xdp(struct net_device *dev, struct netdev_bpf *xdp) { struct ice_netdev_priv *np = netdev_priv(dev); struct ice_vsi *vsi = np->vsi; if (vsi->type != ICE_VSI_PF) { NL_SET_ERR_MSG_MOD(xdp->extack, "XDP can be loaded only on PF VSI"); return -EINVAL; } switch (xdp->command) { case XDP_SETUP_PROG: return ice_xdp_setup_prog(vsi, xdp->prog, xdp->extack); case XDP_SETUP_XSK_POOL: return ice_xsk_pool_setup(vsi, xdp->xsk.pool, xdp->xsk.queue_id); default: return -EINVAL; } } /** * ice_ena_misc_vector - enable the non-queue interrupts * @pf: board private structure */ static void ice_ena_misc_vector(struct ice_pf *pf) { struct ice_hw *hw = &pf->hw; u32 val; /* Disable anti-spoof detection interrupt to prevent spurious event * interrupts during a function reset. Anti-spoof functionally is * still supported. */ val = rd32(hw, GL_MDCK_TX_TDPU); val |= GL_MDCK_TX_TDPU_RCU_ANTISPOOF_ITR_DIS_M; wr32(hw, GL_MDCK_TX_TDPU, val); /* clear things first */ wr32(hw, PFINT_OICR_ENA, 0); /* disable all */ rd32(hw, PFINT_OICR); /* read to clear */ val = (PFINT_OICR_ECC_ERR_M | PFINT_OICR_MAL_DETECT_M | PFINT_OICR_GRST_M | PFINT_OICR_PCI_EXCEPTION_M | PFINT_OICR_VFLR_M | PFINT_OICR_HMC_ERR_M | PFINT_OICR_PE_PUSH_M | PFINT_OICR_PE_CRITERR_M); wr32(hw, PFINT_OICR_ENA, val); /* SW_ITR_IDX = 0, but don't change INTENA */ wr32(hw, GLINT_DYN_CTL(pf->oicr_irq.index), GLINT_DYN_CTL_SW_ITR_INDX_M | GLINT_DYN_CTL_INTENA_MSK_M); } /** * ice_misc_intr - misc interrupt handler * @irq: interrupt number * @data: pointer to a q_vector */ static irqreturn_t ice_misc_intr(int __always_unused irq, void *data) { struct ice_pf *pf = (struct ice_pf *)data; struct ice_hw *hw = &pf->hw; struct device *dev; u32 oicr, ena_mask; dev = ice_pf_to_dev(pf); set_bit(ICE_ADMINQ_EVENT_PENDING, pf->state); set_bit(ICE_MAILBOXQ_EVENT_PENDING, pf->state); set_bit(ICE_SIDEBANDQ_EVENT_PENDING, pf->state); oicr = rd32(hw, PFINT_OICR); ena_mask = rd32(hw, PFINT_OICR_ENA); if (oicr & PFINT_OICR_SWINT_M) { ena_mask &= ~PFINT_OICR_SWINT_M; pf->sw_int_count++; } if (oicr & PFINT_OICR_MAL_DETECT_M) { ena_mask &= ~PFINT_OICR_MAL_DETECT_M; set_bit(ICE_MDD_EVENT_PENDING, pf->state); } if (oicr & PFINT_OICR_VFLR_M) { /* disable any further VFLR event notifications */ if (test_bit(ICE_VF_RESETS_DISABLED, pf->state)) { u32 reg = rd32(hw, PFINT_OICR_ENA); reg &= ~PFINT_OICR_VFLR_M; wr32(hw, PFINT_OICR_ENA, reg); } else { ena_mask &= ~PFINT_OICR_VFLR_M; set_bit(ICE_VFLR_EVENT_PENDING, pf->state); } } if (oicr & PFINT_OICR_GRST_M) { u32 reset; /* we have a reset warning */ ena_mask &= ~PFINT_OICR_GRST_M; reset = (rd32(hw, GLGEN_RSTAT) & GLGEN_RSTAT_RESET_TYPE_M) >> GLGEN_RSTAT_RESET_TYPE_S; if (reset == ICE_RESET_CORER) pf->corer_count++; else if (reset == ICE_RESET_GLOBR) pf->globr_count++; else if (reset == ICE_RESET_EMPR) pf->empr_count++; else dev_dbg(dev, "Invalid reset type %d\n", reset); /* If a reset cycle isn't already in progress, we set a bit in * pf->state so that the service task can start a reset/rebuild. */ if (!test_and_set_bit(ICE_RESET_OICR_RECV, pf->state)) { if (reset == ICE_RESET_CORER) set_bit(ICE_CORER_RECV, pf->state); else if (reset == ICE_RESET_GLOBR) set_bit(ICE_GLOBR_RECV, pf->state); else set_bit(ICE_EMPR_RECV, pf->state); /* There are couple of different bits at play here. * hw->reset_ongoing indicates whether the hardware is * in reset. This is set to true when a reset interrupt * is received and set back to false after the driver * has determined that the hardware is out of reset. * * ICE_RESET_OICR_RECV in pf->state indicates * that a post reset rebuild is required before the * driver is operational again. This is set above. * * As this is the start of the reset/rebuild cycle, set * both to indicate that. */ hw->reset_ongoing = true; } } if (oicr & PFINT_OICR_TSYN_TX_M) { ena_mask &= ~PFINT_OICR_TSYN_TX_M; if (!hw->reset_ongoing) set_bit(ICE_MISC_THREAD_TX_TSTAMP, pf->misc_thread); } if (oicr & PFINT_OICR_TSYN_EVNT_M) { u8 tmr_idx = hw->func_caps.ts_func_info.tmr_index_owned; u32 gltsyn_stat = rd32(hw, GLTSYN_STAT(tmr_idx)); ena_mask &= ~PFINT_OICR_TSYN_EVNT_M; if (hw->func_caps.ts_func_info.src_tmr_owned) { /* Save EVENTs from GLTSYN register */ pf->ptp.ext_ts_irq |= gltsyn_stat & (GLTSYN_STAT_EVENT0_M | GLTSYN_STAT_EVENT1_M | GLTSYN_STAT_EVENT2_M); set_bit(ICE_MISC_THREAD_EXTTS_EVENT, pf->misc_thread); } } #define ICE_AUX_CRIT_ERR (PFINT_OICR_PE_CRITERR_M | PFINT_OICR_HMC_ERR_M | PFINT_OICR_PE_PUSH_M) if (oicr & ICE_AUX_CRIT_ERR) { pf->oicr_err_reg |= oicr; set_bit(ICE_AUX_ERR_PENDING, pf->state); ena_mask &= ~ICE_AUX_CRIT_ERR; } /* Report any remaining unexpected interrupts */ oicr &= ena_mask; if (oicr) { dev_dbg(dev, "unhandled interrupt oicr=0x%08x\n", oicr); /* If a critical error is pending there is no choice but to * reset the device. */ if (oicr & (PFINT_OICR_PCI_EXCEPTION_M | PFINT_OICR_ECC_ERR_M)) { set_bit(ICE_PFR_REQ, pf->state); } } return IRQ_WAKE_THREAD; } /** * ice_misc_intr_thread_fn - misc interrupt thread function * @irq: interrupt number * @data: pointer to a q_vector */ static irqreturn_t ice_misc_intr_thread_fn(int __always_unused irq, void *data) { struct ice_pf *pf = data; struct ice_hw *hw; hw = &pf->hw; if (ice_is_reset_in_progress(pf->state)) return IRQ_HANDLED; ice_service_task_schedule(pf); if (test_and_clear_bit(ICE_MISC_THREAD_EXTTS_EVENT, pf->misc_thread)) ice_ptp_extts_event(pf); if (test_and_clear_bit(ICE_MISC_THREAD_TX_TSTAMP, pf->misc_thread)) { /* Process outstanding Tx timestamps. If there is more work, * re-arm the interrupt to trigger again. */ if (ice_ptp_process_ts(pf) == ICE_TX_TSTAMP_WORK_PENDING) { wr32(hw, PFINT_OICR, PFINT_OICR_TSYN_TX_M); ice_flush(hw); } } ice_irq_dynamic_ena(hw, NULL, NULL); return IRQ_HANDLED; } /** * ice_dis_ctrlq_interrupts - disable control queue interrupts * @hw: pointer to HW structure */ static void ice_dis_ctrlq_interrupts(struct ice_hw *hw) { /* disable Admin queue Interrupt causes */ wr32(hw, PFINT_FW_CTL, rd32(hw, PFINT_FW_CTL) & ~PFINT_FW_CTL_CAUSE_ENA_M); /* disable Mailbox queue Interrupt causes */ wr32(hw, PFINT_MBX_CTL, rd32(hw, PFINT_MBX_CTL) & ~PFINT_MBX_CTL_CAUSE_ENA_M); wr32(hw, PFINT_SB_CTL, rd32(hw, PFINT_SB_CTL) & ~PFINT_SB_CTL_CAUSE_ENA_M); /* disable Control queue Interrupt causes */ wr32(hw, PFINT_OICR_CTL, rd32(hw, PFINT_OICR_CTL) & ~PFINT_OICR_CTL_CAUSE_ENA_M); ice_flush(hw); } /** * ice_free_irq_msix_misc - Unroll misc vector setup * @pf: board private structure */ static void ice_free_irq_msix_misc(struct ice_pf *pf) { int misc_irq_num = pf->oicr_irq.virq; struct ice_hw *hw = &pf->hw; ice_dis_ctrlq_interrupts(hw); /* disable OICR interrupt */ wr32(hw, PFINT_OICR_ENA, 0); ice_flush(hw); synchronize_irq(misc_irq_num); devm_free_irq(ice_pf_to_dev(pf), misc_irq_num, pf); ice_free_irq(pf, pf->oicr_irq); } /** * ice_ena_ctrlq_interrupts - enable control queue interrupts * @hw: pointer to HW structure * @reg_idx: HW vector index to associate the control queue interrupts with */ static void ice_ena_ctrlq_interrupts(struct ice_hw *hw, u16 reg_idx) { u32 val; val = ((reg_idx & PFINT_OICR_CTL_MSIX_INDX_M) | PFINT_OICR_CTL_CAUSE_ENA_M); wr32(hw, PFINT_OICR_CTL, val); /* enable Admin queue Interrupt causes */ val = ((reg_idx & PFINT_FW_CTL_MSIX_INDX_M) | PFINT_FW_CTL_CAUSE_ENA_M); wr32(hw, PFINT_FW_CTL, val); /* enable Mailbox queue Interrupt causes */ val = ((reg_idx & PFINT_MBX_CTL_MSIX_INDX_M) | PFINT_MBX_CTL_CAUSE_ENA_M); wr32(hw, PFINT_MBX_CTL, val); /* This enables Sideband queue Interrupt causes */ val = ((reg_idx & PFINT_SB_CTL_MSIX_INDX_M) | PFINT_SB_CTL_CAUSE_ENA_M); wr32(hw, PFINT_SB_CTL, val); ice_flush(hw); } /** * ice_req_irq_msix_misc - Setup the misc vector to handle non queue events * @pf: board private structure * * This sets up the handler for MSIX 0, which is used to manage the * non-queue interrupts, e.g. AdminQ and errors. This is not used * when in MSI or Legacy interrupt mode. */ static int ice_req_irq_msix_misc(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); struct ice_hw *hw = &pf->hw; struct msi_map oicr_irq; int err = 0; if (!pf->int_name[0]) snprintf(pf->int_name, sizeof(pf->int_name) - 1, "%s-%s:misc", dev_driver_string(dev), dev_name(dev)); /* Do not request IRQ but do enable OICR interrupt since settings are * lost during reset. Note that this function is called only during * rebuild path and not while reset is in progress. */ if (ice_is_reset_in_progress(pf->state)) goto skip_req_irq; /* reserve one vector in irq_tracker for misc interrupts */ oicr_irq = ice_alloc_irq(pf, false); if (oicr_irq.index < 0) return oicr_irq.index; pf->oicr_irq = oicr_irq; err = devm_request_threaded_irq(dev, pf->oicr_irq.virq, ice_misc_intr, ice_misc_intr_thread_fn, 0, pf->int_name, pf); if (err) { dev_err(dev, "devm_request_threaded_irq for %s failed: %d\n", pf->int_name, err); ice_free_irq(pf, pf->oicr_irq); return err; } skip_req_irq: ice_ena_misc_vector(pf); ice_ena_ctrlq_interrupts(hw, pf->oicr_irq.index); wr32(hw, GLINT_ITR(ICE_RX_ITR, pf->oicr_irq.index), ITR_REG_ALIGN(ICE_ITR_8K) >> ICE_ITR_GRAN_S); ice_flush(hw); ice_irq_dynamic_ena(hw, NULL, NULL); return 0; } /** * ice_napi_add - register NAPI handler for the VSI * @vsi: VSI for which NAPI handler is to be registered * * This function is only called in the driver's load path. Registering the NAPI * handler is done in ice_vsi_alloc_q_vector() for all other cases (i.e. resume, * reset/rebuild, etc.) */ static void ice_napi_add(struct ice_vsi *vsi) { int v_idx; if (!vsi->netdev) return; ice_for_each_q_vector(vsi, v_idx) netif_napi_add(vsi->netdev, &vsi->q_vectors[v_idx]->napi, ice_napi_poll); } /** * ice_set_ops - set netdev and ethtools ops for the given netdev * @vsi: the VSI associated with the new netdev */ static void ice_set_ops(struct ice_vsi *vsi) { struct net_device *netdev = vsi->netdev; struct ice_pf *pf = ice_netdev_to_pf(netdev); if (ice_is_safe_mode(pf)) { netdev->netdev_ops = &ice_netdev_safe_mode_ops; ice_set_ethtool_safe_mode_ops(netdev); return; } netdev->netdev_ops = &ice_netdev_ops; netdev->udp_tunnel_nic_info = &pf->hw.udp_tunnel_nic; ice_set_ethtool_ops(netdev); if (vsi->type != ICE_VSI_PF) return; netdev->xdp_features = NETDEV_XDP_ACT_BASIC | NETDEV_XDP_ACT_REDIRECT | NETDEV_XDP_ACT_XSK_ZEROCOPY | NETDEV_XDP_ACT_RX_SG; netdev->xdp_zc_max_segs = ICE_MAX_BUF_TXD; } /** * ice_set_netdev_features - set features for the given netdev * @netdev: netdev instance */ static void ice_set_netdev_features(struct net_device *netdev) { struct ice_pf *pf = ice_netdev_to_pf(netdev); bool is_dvm_ena = ice_is_dvm_ena(&pf->hw); netdev_features_t csumo_features; netdev_features_t vlano_features; netdev_features_t dflt_features; netdev_features_t tso_features; if (ice_is_safe_mode(pf)) { /* safe mode */ netdev->features = NETIF_F_SG | NETIF_F_HIGHDMA; netdev->hw_features = netdev->features; return; } dflt_features = NETIF_F_SG | NETIF_F_HIGHDMA | NETIF_F_NTUPLE | NETIF_F_RXHASH; csumo_features = NETIF_F_RXCSUM | NETIF_F_IP_CSUM | NETIF_F_SCTP_CRC | NETIF_F_IPV6_CSUM; vlano_features = NETIF_F_HW_VLAN_CTAG_FILTER | NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX; /* Enable CTAG/STAG filtering by default in Double VLAN Mode (DVM) */ if (is_dvm_ena) vlano_features |= NETIF_F_HW_VLAN_STAG_FILTER; tso_features = NETIF_F_TSO | NETIF_F_TSO_ECN | NETIF_F_TSO6 | NETIF_F_GSO_GRE | NETIF_F_GSO_UDP_TUNNEL | NETIF_F_GSO_GRE_CSUM | NETIF_F_GSO_UDP_TUNNEL_CSUM | NETIF_F_GSO_PARTIAL | NETIF_F_GSO_IPXIP4 | NETIF_F_GSO_IPXIP6 | NETIF_F_GSO_UDP_L4; netdev->gso_partial_features |= NETIF_F_GSO_UDP_TUNNEL_CSUM | NETIF_F_GSO_GRE_CSUM; /* set features that user can change */ netdev->hw_features = dflt_features | csumo_features | vlano_features | tso_features; /* add support for HW_CSUM on packets with MPLS header */ netdev->mpls_features = NETIF_F_HW_CSUM | NETIF_F_TSO | NETIF_F_TSO6; /* enable features */ netdev->features |= netdev->hw_features; netdev->hw_features |= NETIF_F_HW_TC; netdev->hw_features |= NETIF_F_LOOPBACK; /* encap and VLAN devices inherit default, csumo and tso features */ netdev->hw_enc_features |= dflt_features | csumo_features | tso_features; netdev->vlan_features |= dflt_features | csumo_features | tso_features; /* advertise support but don't enable by default since only one type of * VLAN offload can be enabled at a time (i.e. CTAG or STAG). When one * type turns on the other has to be turned off. This is enforced by the * ice_fix_features() ndo callback. */ if (is_dvm_ena) netdev->hw_features |= NETIF_F_HW_VLAN_STAG_RX | NETIF_F_HW_VLAN_STAG_TX; /* Leave CRC / FCS stripping enabled by default, but allow the value to * be changed at runtime */ netdev->hw_features |= NETIF_F_RXFCS; netif_set_tso_max_size(netdev, ICE_MAX_TSO_SIZE); } /** * ice_fill_rss_lut - Fill the RSS lookup table with default values * @lut: Lookup table * @rss_table_size: Lookup table size * @rss_size: Range of queue number for hashing */ void ice_fill_rss_lut(u8 *lut, u16 rss_table_size, u16 rss_size) { u16 i; for (i = 0; i < rss_table_size; i++) lut[i] = i % rss_size; } /** * ice_pf_vsi_setup - Set up a PF VSI * @pf: board private structure * @pi: pointer to the port_info instance * * Returns pointer to the successfully allocated VSI software struct * on success, otherwise returns NULL on failure. */ static struct ice_vsi * ice_pf_vsi_setup(struct ice_pf *pf, struct ice_port_info *pi) { struct ice_vsi_cfg_params params = {}; params.type = ICE_VSI_PF; params.pi = pi; params.flags = ICE_VSI_FLAG_INIT; return ice_vsi_setup(pf, &params); } static struct ice_vsi * ice_chnl_vsi_setup(struct ice_pf *pf, struct ice_port_info *pi, struct ice_channel *ch) { struct ice_vsi_cfg_params params = {}; params.type = ICE_VSI_CHNL; params.pi = pi; params.ch = ch; params.flags = ICE_VSI_FLAG_INIT; return ice_vsi_setup(pf, &params); } /** * ice_ctrl_vsi_setup - Set up a control VSI * @pf: board private structure * @pi: pointer to the port_info instance * * Returns pointer to the successfully allocated VSI software struct * on success, otherwise returns NULL on failure. */ static struct ice_vsi * ice_ctrl_vsi_setup(struct ice_pf *pf, struct ice_port_info *pi) { struct ice_vsi_cfg_params params = {}; params.type = ICE_VSI_CTRL; params.pi = pi; params.flags = ICE_VSI_FLAG_INIT; return ice_vsi_setup(pf, &params); } /** * ice_lb_vsi_setup - Set up a loopback VSI * @pf: board private structure * @pi: pointer to the port_info instance * * Returns pointer to the successfully allocated VSI software struct * on success, otherwise returns NULL on failure. */ struct ice_vsi * ice_lb_vsi_setup(struct ice_pf *pf, struct ice_port_info *pi) { struct ice_vsi_cfg_params params = {}; params.type = ICE_VSI_LB; params.pi = pi; params.flags = ICE_VSI_FLAG_INIT; return ice_vsi_setup(pf, &params); } /** * ice_vlan_rx_add_vid - Add a VLAN ID filter to HW offload * @netdev: network interface to be adjusted * @proto: VLAN TPID * @vid: VLAN ID to be added * * net_device_ops implementation for adding VLAN IDs */ static int ice_vlan_rx_add_vid(struct net_device *netdev, __be16 proto, u16 vid) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi_vlan_ops *vlan_ops; struct ice_vsi *vsi = np->vsi; struct ice_vlan vlan; int ret; /* VLAN 0 is added by default during load/reset */ if (!vid) return 0; while (test_and_set_bit(ICE_CFG_BUSY, vsi->state)) usleep_range(1000, 2000); /* Add multicast promisc rule for the VLAN ID to be added if * all-multicast is currently enabled. */ if (vsi->current_netdev_flags & IFF_ALLMULTI) { ret = ice_fltr_set_vsi_promisc(&vsi->back->hw, vsi->idx, ICE_MCAST_VLAN_PROMISC_BITS, vid); if (ret) goto finish; } vlan_ops = ice_get_compat_vsi_vlan_ops(vsi); /* Add a switch rule for this VLAN ID so its corresponding VLAN tagged * packets aren't pruned by the device's internal switch on Rx */ vlan = ICE_VLAN(be16_to_cpu(proto), vid, 0); ret = vlan_ops->add_vlan(vsi, &vlan); if (ret) goto finish; /* If all-multicast is currently enabled and this VLAN ID is only one * besides VLAN-0 we have to update look-up type of multicast promisc * rule for VLAN-0 from ICE_SW_LKUP_PROMISC to ICE_SW_LKUP_PROMISC_VLAN. */ if ((vsi->current_netdev_flags & IFF_ALLMULTI) && ice_vsi_num_non_zero_vlans(vsi) == 1) { ice_fltr_clear_vsi_promisc(&vsi->back->hw, vsi->idx, ICE_MCAST_PROMISC_BITS, 0); ice_fltr_set_vsi_promisc(&vsi->back->hw, vsi->idx, ICE_MCAST_VLAN_PROMISC_BITS, 0); } finish: clear_bit(ICE_CFG_BUSY, vsi->state); return ret; } /** * ice_vlan_rx_kill_vid - Remove a VLAN ID filter from HW offload * @netdev: network interface to be adjusted * @proto: VLAN TPID * @vid: VLAN ID to be removed * * net_device_ops implementation for removing VLAN IDs */ static int ice_vlan_rx_kill_vid(struct net_device *netdev, __be16 proto, u16 vid) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi_vlan_ops *vlan_ops; struct ice_vsi *vsi = np->vsi; struct ice_vlan vlan; int ret; /* don't allow removal of VLAN 0 */ if (!vid) return 0; while (test_and_set_bit(ICE_CFG_BUSY, vsi->state)) usleep_range(1000, 2000); ret = ice_clear_vsi_promisc(&vsi->back->hw, vsi->idx, ICE_MCAST_VLAN_PROMISC_BITS, vid); if (ret) { netdev_err(netdev, "Error clearing multicast promiscuous mode on VSI %i\n", vsi->vsi_num); vsi->current_netdev_flags |= IFF_ALLMULTI; } vlan_ops = ice_get_compat_vsi_vlan_ops(vsi); /* Make sure VLAN delete is successful before updating VLAN * information */ vlan = ICE_VLAN(be16_to_cpu(proto), vid, 0); ret = vlan_ops->del_vlan(vsi, &vlan); if (ret) goto finish; /* Remove multicast promisc rule for the removed VLAN ID if * all-multicast is enabled. */ if (vsi->current_netdev_flags & IFF_ALLMULTI) ice_fltr_clear_vsi_promisc(&vsi->back->hw, vsi->idx, ICE_MCAST_VLAN_PROMISC_BITS, vid); if (!ice_vsi_has_non_zero_vlans(vsi)) { /* Update look-up type of multicast promisc rule for VLAN 0 * from ICE_SW_LKUP_PROMISC_VLAN to ICE_SW_LKUP_PROMISC when * all-multicast is enabled and VLAN 0 is the only VLAN rule. */ if (vsi->current_netdev_flags & IFF_ALLMULTI) { ice_fltr_clear_vsi_promisc(&vsi->back->hw, vsi->idx, ICE_MCAST_VLAN_PROMISC_BITS, 0); ice_fltr_set_vsi_promisc(&vsi->back->hw, vsi->idx, ICE_MCAST_PROMISC_BITS, 0); } } finish: clear_bit(ICE_CFG_BUSY, vsi->state); return ret; } /** * ice_rep_indr_tc_block_unbind * @cb_priv: indirection block private data */ static void ice_rep_indr_tc_block_unbind(void *cb_priv) { struct ice_indr_block_priv *indr_priv = cb_priv; list_del(&indr_priv->list); kfree(indr_priv); } /** * ice_tc_indir_block_unregister - Unregister TC indirect block notifications * @vsi: VSI struct which has the netdev */ static void ice_tc_indir_block_unregister(struct ice_vsi *vsi) { struct ice_netdev_priv *np = netdev_priv(vsi->netdev); flow_indr_dev_unregister(ice_indr_setup_tc_cb, np, ice_rep_indr_tc_block_unbind); } /** * ice_tc_indir_block_register - Register TC indirect block notifications * @vsi: VSI struct which has the netdev * * Returns 0 on success, negative value on failure */ static int ice_tc_indir_block_register(struct ice_vsi *vsi) { struct ice_netdev_priv *np; if (!vsi || !vsi->netdev) return -EINVAL; np = netdev_priv(vsi->netdev); INIT_LIST_HEAD(&np->tc_indr_block_priv_list); return flow_indr_dev_register(ice_indr_setup_tc_cb, np); } /** * ice_get_avail_q_count - Get count of queues in use * @pf_qmap: bitmap to get queue use count from * @lock: pointer to a mutex that protects access to pf_qmap * @size: size of the bitmap */ static u16 ice_get_avail_q_count(unsigned long *pf_qmap, struct mutex *lock, u16 size) { unsigned long bit; u16 count = 0; mutex_lock(lock); for_each_clear_bit(bit, pf_qmap, size) count++; mutex_unlock(lock); return count; } /** * ice_get_avail_txq_count - Get count of Tx queues in use * @pf: pointer to an ice_pf instance */ u16 ice_get_avail_txq_count(struct ice_pf *pf) { return ice_get_avail_q_count(pf->avail_txqs, &pf->avail_q_mutex, pf->max_pf_txqs); } /** * ice_get_avail_rxq_count - Get count of Rx queues in use * @pf: pointer to an ice_pf instance */ u16 ice_get_avail_rxq_count(struct ice_pf *pf) { return ice_get_avail_q_count(pf->avail_rxqs, &pf->avail_q_mutex, pf->max_pf_rxqs); } /** * ice_deinit_pf - Unrolls initialziations done by ice_init_pf * @pf: board private structure to initialize */ static void ice_deinit_pf(struct ice_pf *pf) { ice_service_task_stop(pf); mutex_destroy(&pf->lag_mutex); mutex_destroy(&pf->adev_mutex); mutex_destroy(&pf->sw_mutex); mutex_destroy(&pf->tc_mutex); mutex_destroy(&pf->avail_q_mutex); mutex_destroy(&pf->vfs.table_lock); if (pf->avail_txqs) { bitmap_free(pf->avail_txqs); pf->avail_txqs = NULL; } if (pf->avail_rxqs) { bitmap_free(pf->avail_rxqs); pf->avail_rxqs = NULL; } if (pf->ptp.clock) ptp_clock_unregister(pf->ptp.clock); } /** * ice_set_pf_caps - set PFs capability flags * @pf: pointer to the PF instance */ static void ice_set_pf_caps(struct ice_pf *pf) { struct ice_hw_func_caps *func_caps = &pf->hw.func_caps; clear_bit(ICE_FLAG_RDMA_ENA, pf->flags); if (func_caps->common_cap.rdma) set_bit(ICE_FLAG_RDMA_ENA, pf->flags); clear_bit(ICE_FLAG_DCB_CAPABLE, pf->flags); if (func_caps->common_cap.dcb) set_bit(ICE_FLAG_DCB_CAPABLE, pf->flags); clear_bit(ICE_FLAG_SRIOV_CAPABLE, pf->flags); if (func_caps->common_cap.sr_iov_1_1) { set_bit(ICE_FLAG_SRIOV_CAPABLE, pf->flags); pf->vfs.num_supported = min_t(int, func_caps->num_allocd_vfs, ICE_MAX_SRIOV_VFS); } clear_bit(ICE_FLAG_RSS_ENA, pf->flags); if (func_caps->common_cap.rss_table_size) set_bit(ICE_FLAG_RSS_ENA, pf->flags); clear_bit(ICE_FLAG_FD_ENA, pf->flags); if (func_caps->fd_fltr_guar > 0 || func_caps->fd_fltr_best_effort > 0) { u16 unused; /* ctrl_vsi_idx will be set to a valid value when flow director * is setup by ice_init_fdir */ pf->ctrl_vsi_idx = ICE_NO_VSI; set_bit(ICE_FLAG_FD_ENA, pf->flags); /* force guaranteed filter pool for PF */ ice_alloc_fd_guar_item(&pf->hw, &unused, func_caps->fd_fltr_guar); /* force shared filter pool for PF */ ice_alloc_fd_shrd_item(&pf->hw, &unused, func_caps->fd_fltr_best_effort); } clear_bit(ICE_FLAG_PTP_SUPPORTED, pf->flags); if (func_caps->common_cap.ieee_1588) set_bit(ICE_FLAG_PTP_SUPPORTED, pf->flags); pf->max_pf_txqs = func_caps->common_cap.num_txq; pf->max_pf_rxqs = func_caps->common_cap.num_rxq; } /** * ice_init_pf - Initialize general software structures (struct ice_pf) * @pf: board private structure to initialize */ static int ice_init_pf(struct ice_pf *pf) { ice_set_pf_caps(pf); mutex_init(&pf->sw_mutex); mutex_init(&pf->tc_mutex); mutex_init(&pf->adev_mutex); mutex_init(&pf->lag_mutex); INIT_HLIST_HEAD(&pf->aq_wait_list); spin_lock_init(&pf->aq_wait_lock); init_waitqueue_head(&pf->aq_wait_queue); init_waitqueue_head(&pf->reset_wait_queue); /* setup service timer and periodic service task */ timer_setup(&pf->serv_tmr, ice_service_timer, 0); pf->serv_tmr_period = HZ; INIT_WORK(&pf->serv_task, ice_service_task); clear_bit(ICE_SERVICE_SCHED, pf->state); mutex_init(&pf->avail_q_mutex); pf->avail_txqs = bitmap_zalloc(pf->max_pf_txqs, GFP_KERNEL); if (!pf->avail_txqs) return -ENOMEM; pf->avail_rxqs = bitmap_zalloc(pf->max_pf_rxqs, GFP_KERNEL); if (!pf->avail_rxqs) { bitmap_free(pf->avail_txqs); pf->avail_txqs = NULL; return -ENOMEM; } mutex_init(&pf->vfs.table_lock); hash_init(pf->vfs.table); ice_mbx_init_snapshot(&pf->hw); return 0; } /** * ice_is_wol_supported - check if WoL is supported * @hw: pointer to hardware info * * Check if WoL is supported based on the HW configuration. * Returns true if NVM supports and enables WoL for this port, false otherwise */ bool ice_is_wol_supported(struct ice_hw *hw) { u16 wol_ctrl; /* A bit set to 1 in the NVM Software Reserved Word 2 (WoL control * word) indicates WoL is not supported on the corresponding PF ID. */ if (ice_read_sr_word(hw, ICE_SR_NVM_WOL_CFG, &wol_ctrl)) return false; return !(BIT(hw->port_info->lport) & wol_ctrl); } /** * ice_vsi_recfg_qs - Change the number of queues on a VSI * @vsi: VSI being changed * @new_rx: new number of Rx queues * @new_tx: new number of Tx queues * @locked: is adev device_lock held * * Only change the number of queues if new_tx, or new_rx is non-0. * * Returns 0 on success. */ int ice_vsi_recfg_qs(struct ice_vsi *vsi, int new_rx, int new_tx, bool locked) { struct ice_pf *pf = vsi->back; int err = 0, timeout = 50; if (!new_rx && !new_tx) return -EINVAL; while (test_and_set_bit(ICE_CFG_BUSY, pf->state)) { timeout--; if (!timeout) return -EBUSY; usleep_range(1000, 2000); } if (new_tx) vsi->req_txq = (u16)new_tx; if (new_rx) vsi->req_rxq = (u16)new_rx; /* set for the next time the netdev is started */ if (!netif_running(vsi->netdev)) { ice_vsi_rebuild(vsi, ICE_VSI_FLAG_NO_INIT); dev_dbg(ice_pf_to_dev(pf), "Link is down, queue count change happens when link is brought up\n"); goto done; } ice_vsi_close(vsi); ice_vsi_rebuild(vsi, ICE_VSI_FLAG_NO_INIT); ice_pf_dcb_recfg(pf, locked); ice_vsi_open(vsi); done: clear_bit(ICE_CFG_BUSY, pf->state); return err; } /** * ice_set_safe_mode_vlan_cfg - configure PF VSI to allow all VLANs in safe mode * @pf: PF to configure * * No VLAN offloads/filtering are advertised in safe mode so make sure the PF * VSI can still Tx/Rx VLAN tagged packets. */ static void ice_set_safe_mode_vlan_cfg(struct ice_pf *pf) { struct ice_vsi *vsi = ice_get_main_vsi(pf); struct ice_vsi_ctx *ctxt; struct ice_hw *hw; int status; if (!vsi) return; ctxt = kzalloc(sizeof(*ctxt), GFP_KERNEL); if (!ctxt) return; hw = &pf->hw; ctxt->info = vsi->info; ctxt->info.valid_sections = cpu_to_le16(ICE_AQ_VSI_PROP_VLAN_VALID | ICE_AQ_VSI_PROP_SECURITY_VALID | ICE_AQ_VSI_PROP_SW_VALID); /* disable VLAN anti-spoof */ ctxt->info.sec_flags &= ~(ICE_AQ_VSI_SEC_TX_VLAN_PRUNE_ENA << ICE_AQ_VSI_SEC_TX_PRUNE_ENA_S); /* disable VLAN pruning and keep all other settings */ ctxt->info.sw_flags2 &= ~ICE_AQ_VSI_SW_FLAG_RX_VLAN_PRUNE_ENA; /* allow all VLANs on Tx and don't strip on Rx */ ctxt->info.inner_vlan_flags = ICE_AQ_VSI_INNER_VLAN_TX_MODE_ALL | ICE_AQ_VSI_INNER_VLAN_EMODE_NOTHING; status = ice_update_vsi(hw, vsi->idx, ctxt, NULL); if (status) { dev_err(ice_pf_to_dev(vsi->back), "Failed to update VSI for safe mode VLANs, err %d aq_err %s\n", status, ice_aq_str(hw->adminq.sq_last_status)); } else { vsi->info.sec_flags = ctxt->info.sec_flags; vsi->info.sw_flags2 = ctxt->info.sw_flags2; vsi->info.inner_vlan_flags = ctxt->info.inner_vlan_flags; } kfree(ctxt); } /** * ice_log_pkg_init - log result of DDP package load * @hw: pointer to hardware info * @state: state of package load */ static void ice_log_pkg_init(struct ice_hw *hw, enum ice_ddp_state state) { struct ice_pf *pf = hw->back; struct device *dev; dev = ice_pf_to_dev(pf); switch (state) { case ICE_DDP_PKG_SUCCESS: dev_info(dev, "The DDP package was successfully loaded: %s version %d.%d.%d.%d\n", hw->active_pkg_name, hw->active_pkg_ver.major, hw->active_pkg_ver.minor, hw->active_pkg_ver.update, hw->active_pkg_ver.draft); break; case ICE_DDP_PKG_SAME_VERSION_ALREADY_LOADED: dev_info(dev, "DDP package already present on device: %s version %d.%d.%d.%d\n", hw->active_pkg_name, hw->active_pkg_ver.major, hw->active_pkg_ver.minor, hw->active_pkg_ver.update, hw->active_pkg_ver.draft); break; case ICE_DDP_PKG_ALREADY_LOADED_NOT_SUPPORTED: dev_err(dev, "The device has a DDP package that is not supported by the driver. The device has package '%s' version %d.%d.x.x. The driver requires version %d.%d.x.x. Entering Safe Mode.\n", hw->active_pkg_name, hw->active_pkg_ver.major, hw->active_pkg_ver.minor, ICE_PKG_SUPP_VER_MAJ, ICE_PKG_SUPP_VER_MNR); break; case ICE_DDP_PKG_COMPATIBLE_ALREADY_LOADED: dev_info(dev, "The driver could not load the DDP package file because a compatible DDP package is already present on the device. The device has package '%s' version %d.%d.%d.%d. The package file found by the driver: '%s' version %d.%d.%d.%d.\n", hw->active_pkg_name, hw->active_pkg_ver.major, hw->active_pkg_ver.minor, hw->active_pkg_ver.update, hw->active_pkg_ver.draft, hw->pkg_name, hw->pkg_ver.major, hw->pkg_ver.minor, hw->pkg_ver.update, hw->pkg_ver.draft); break; case ICE_DDP_PKG_FW_MISMATCH: dev_err(dev, "The firmware loaded on the device is not compatible with the DDP package. Please update the device's NVM. Entering safe mode.\n"); break; case ICE_DDP_PKG_INVALID_FILE: dev_err(dev, "The DDP package file is invalid. Entering Safe Mode.\n"); break; case ICE_DDP_PKG_FILE_VERSION_TOO_HIGH: dev_err(dev, "The DDP package file version is higher than the driver supports. Please use an updated driver. Entering Safe Mode.\n"); break; case ICE_DDP_PKG_FILE_VERSION_TOO_LOW: dev_err(dev, "The DDP package file version is lower than the driver supports. The driver requires version %d.%d.x.x. Please use an updated DDP Package file. Entering Safe Mode.\n", ICE_PKG_SUPP_VER_MAJ, ICE_PKG_SUPP_VER_MNR); break; case ICE_DDP_PKG_FILE_SIGNATURE_INVALID: dev_err(dev, "The DDP package could not be loaded because its signature is not valid. Please use a valid DDP Package. Entering Safe Mode.\n"); break; case ICE_DDP_PKG_FILE_REVISION_TOO_LOW: dev_err(dev, "The DDP Package could not be loaded because its security revision is too low. Please use an updated DDP Package. Entering Safe Mode.\n"); break; case ICE_DDP_PKG_LOAD_ERROR: dev_err(dev, "An error occurred on the device while loading the DDP package. The device will be reset.\n"); /* poll for reset to complete */ if (ice_check_reset(hw)) dev_err(dev, "Error resetting device. Please reload the driver\n"); break; case ICE_DDP_PKG_ERR: default: dev_err(dev, "An unknown error occurred when loading the DDP package. Entering Safe Mode.\n"); break; } } /** * ice_load_pkg - load/reload the DDP Package file * @firmware: firmware structure when firmware requested or NULL for reload * @pf: pointer to the PF instance * * Called on probe and post CORER/GLOBR rebuild to load DDP Package and * initialize HW tables. */ static void ice_load_pkg(const struct firmware *firmware, struct ice_pf *pf) { enum ice_ddp_state state = ICE_DDP_PKG_ERR; struct device *dev = ice_pf_to_dev(pf); struct ice_hw *hw = &pf->hw; /* Load DDP Package */ if (firmware && !hw->pkg_copy) { state = ice_copy_and_init_pkg(hw, firmware->data, firmware->size); ice_log_pkg_init(hw, state); } else if (!firmware && hw->pkg_copy) { /* Reload package during rebuild after CORER/GLOBR reset */ state = ice_init_pkg(hw, hw->pkg_copy, hw->pkg_size); ice_log_pkg_init(hw, state); } else { dev_err(dev, "The DDP package file failed to load. Entering Safe Mode.\n"); } if (!ice_is_init_pkg_successful(state)) { /* Safe Mode */ clear_bit(ICE_FLAG_ADV_FEATURES, pf->flags); return; } /* Successful download package is the precondition for advanced * features, hence setting the ICE_FLAG_ADV_FEATURES flag */ set_bit(ICE_FLAG_ADV_FEATURES, pf->flags); } /** * ice_verify_cacheline_size - verify driver's assumption of 64 Byte cache lines * @pf: pointer to the PF structure * * There is no error returned here because the driver should be able to handle * 128 Byte cache lines, so we only print a warning in case issues are seen, * specifically with Tx. */ static void ice_verify_cacheline_size(struct ice_pf *pf) { if (rd32(&pf->hw, GLPCI_CNF2) & GLPCI_CNF2_CACHELINE_SIZE_M) dev_warn(ice_pf_to_dev(pf), "%d Byte cache line assumption is invalid, driver may have Tx timeouts!\n", ICE_CACHE_LINE_BYTES); } /** * ice_send_version - update firmware with driver version * @pf: PF struct * * Returns 0 on success, else error code */ static int ice_send_version(struct ice_pf *pf) { struct ice_driver_ver dv; dv.major_ver = 0xff; dv.minor_ver = 0xff; dv.build_ver = 0xff; dv.subbuild_ver = 0; strscpy((char *)dv.driver_string, UTS_RELEASE, sizeof(dv.driver_string)); return ice_aq_send_driver_ver(&pf->hw, &dv, NULL); } /** * ice_init_fdir - Initialize flow director VSI and configuration * @pf: pointer to the PF instance * * returns 0 on success, negative on error */ static int ice_init_fdir(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); struct ice_vsi *ctrl_vsi; int err; /* Side Band Flow Director needs to have a control VSI. * Allocate it and store it in the PF. */ ctrl_vsi = ice_ctrl_vsi_setup(pf, pf->hw.port_info); if (!ctrl_vsi) { dev_dbg(dev, "could not create control VSI\n"); return -ENOMEM; } err = ice_vsi_open_ctrl(ctrl_vsi); if (err) { dev_dbg(dev, "could not open control VSI\n"); goto err_vsi_open; } mutex_init(&pf->hw.fdir_fltr_lock); err = ice_fdir_create_dflt_rules(pf); if (err) goto err_fdir_rule; return 0; err_fdir_rule: ice_fdir_release_flows(&pf->hw); ice_vsi_close(ctrl_vsi); err_vsi_open: ice_vsi_release(ctrl_vsi); if (pf->ctrl_vsi_idx != ICE_NO_VSI) { pf->vsi[pf->ctrl_vsi_idx] = NULL; pf->ctrl_vsi_idx = ICE_NO_VSI; } return err; } static void ice_deinit_fdir(struct ice_pf *pf) { struct ice_vsi *vsi = ice_get_ctrl_vsi(pf); if (!vsi) return; ice_vsi_manage_fdir(vsi, false); ice_vsi_release(vsi); if (pf->ctrl_vsi_idx != ICE_NO_VSI) { pf->vsi[pf->ctrl_vsi_idx] = NULL; pf->ctrl_vsi_idx = ICE_NO_VSI; } mutex_destroy(&(&pf->hw)->fdir_fltr_lock); } /** * ice_get_opt_fw_name - return optional firmware file name or NULL * @pf: pointer to the PF instance */ static char *ice_get_opt_fw_name(struct ice_pf *pf) { /* Optional firmware name same as default with additional dash * followed by a EUI-64 identifier (PCIe Device Serial Number) */ struct pci_dev *pdev = pf->pdev; char *opt_fw_filename; u64 dsn; /* Determine the name of the optional file using the DSN (two * dwords following the start of the DSN Capability). */ dsn = pci_get_dsn(pdev); if (!dsn) return NULL; opt_fw_filename = kzalloc(NAME_MAX, GFP_KERNEL); if (!opt_fw_filename) return NULL; snprintf(opt_fw_filename, NAME_MAX, "%sice-%016llx.pkg", ICE_DDP_PKG_PATH, dsn); return opt_fw_filename; } /** * ice_request_fw - Device initialization routine * @pf: pointer to the PF instance */ static void ice_request_fw(struct ice_pf *pf) { char *opt_fw_filename = ice_get_opt_fw_name(pf); const struct firmware *firmware = NULL; struct device *dev = ice_pf_to_dev(pf); int err = 0; /* optional device-specific DDP (if present) overrides the default DDP * package file. kernel logs a debug message if the file doesn't exist, * and warning messages for other errors. */ if (opt_fw_filename) { err = firmware_request_nowarn(&firmware, opt_fw_filename, dev); if (err) { kfree(opt_fw_filename); goto dflt_pkg_load; } /* request for firmware was successful. Download to device */ ice_load_pkg(firmware, pf); kfree(opt_fw_filename); release_firmware(firmware); return; } dflt_pkg_load: err = request_firmware(&firmware, ICE_DDP_PKG_FILE, dev); if (err) { dev_err(dev, "The DDP package file was not found or could not be read. Entering Safe Mode\n"); return; } /* request for firmware was successful. Download to device */ ice_load_pkg(firmware, pf); release_firmware(firmware); } /** * ice_print_wake_reason - show the wake up cause in the log * @pf: pointer to the PF struct */ static void ice_print_wake_reason(struct ice_pf *pf) { u32 wus = pf->wakeup_reason; const char *wake_str; /* if no wake event, nothing to print */ if (!wus) return; if (wus & PFPM_WUS_LNKC_M) wake_str = "Link\n"; else if (wus & PFPM_WUS_MAG_M) wake_str = "Magic Packet\n"; else if (wus & PFPM_WUS_MNG_M) wake_str = "Management\n"; else if (wus & PFPM_WUS_FW_RST_WK_M) wake_str = "Firmware Reset\n"; else wake_str = "Unknown\n"; dev_info(ice_pf_to_dev(pf), "Wake reason: %s", wake_str); } /** * ice_register_netdev - register netdev * @vsi: pointer to the VSI struct */ static int ice_register_netdev(struct ice_vsi *vsi) { int err; if (!vsi || !vsi->netdev) return -EIO; err = register_netdev(vsi->netdev); if (err) return err; set_bit(ICE_VSI_NETDEV_REGISTERED, vsi->state); netif_carrier_off(vsi->netdev); netif_tx_stop_all_queues(vsi->netdev); return 0; } static void ice_unregister_netdev(struct ice_vsi *vsi) { if (!vsi || !vsi->netdev) return; unregister_netdev(vsi->netdev); clear_bit(ICE_VSI_NETDEV_REGISTERED, vsi->state); } /** * ice_cfg_netdev - Allocate, configure and register a netdev * @vsi: the VSI associated with the new netdev * * Returns 0 on success, negative value on failure */ static int ice_cfg_netdev(struct ice_vsi *vsi) { struct ice_netdev_priv *np; struct net_device *netdev; u8 mac_addr[ETH_ALEN]; netdev = alloc_etherdev_mqs(sizeof(*np), vsi->alloc_txq, vsi->alloc_rxq); if (!netdev) return -ENOMEM; set_bit(ICE_VSI_NETDEV_ALLOCD, vsi->state); vsi->netdev = netdev; np = netdev_priv(netdev); np->vsi = vsi; ice_set_netdev_features(netdev); ice_set_ops(vsi); if (vsi->type == ICE_VSI_PF) { SET_NETDEV_DEV(netdev, ice_pf_to_dev(vsi->back)); ether_addr_copy(mac_addr, vsi->port_info->mac.perm_addr); eth_hw_addr_set(netdev, mac_addr); } netdev->priv_flags |= IFF_UNICAST_FLT; /* Setup netdev TC information */ ice_vsi_cfg_netdev_tc(vsi, vsi->tc_cfg.ena_tc); netdev->max_mtu = ICE_MAX_MTU; return 0; } static void ice_decfg_netdev(struct ice_vsi *vsi) { clear_bit(ICE_VSI_NETDEV_ALLOCD, vsi->state); free_netdev(vsi->netdev); vsi->netdev = NULL; } static int ice_start_eth(struct ice_vsi *vsi) { int err; err = ice_init_mac_fltr(vsi->back); if (err) return err; err = ice_vsi_open(vsi); if (err) ice_fltr_remove_all(vsi); return err; } static void ice_stop_eth(struct ice_vsi *vsi) { ice_fltr_remove_all(vsi); ice_vsi_close(vsi); } static int ice_init_eth(struct ice_pf *pf) { struct ice_vsi *vsi = ice_get_main_vsi(pf); int err; if (!vsi) return -EINVAL; /* init channel list */ INIT_LIST_HEAD(&vsi->ch_list); err = ice_cfg_netdev(vsi); if (err) return err; /* Setup DCB netlink interface */ ice_dcbnl_setup(vsi); err = ice_init_mac_fltr(pf); if (err) goto err_init_mac_fltr; err = ice_devlink_create_pf_port(pf); if (err) goto err_devlink_create_pf_port; SET_NETDEV_DEVLINK_PORT(vsi->netdev, &pf->devlink_port); err = ice_register_netdev(vsi); if (err) goto err_register_netdev; err = ice_tc_indir_block_register(vsi); if (err) goto err_tc_indir_block_register; ice_napi_add(vsi); return 0; err_tc_indir_block_register: ice_unregister_netdev(vsi); err_register_netdev: ice_devlink_destroy_pf_port(pf); err_devlink_create_pf_port: err_init_mac_fltr: ice_decfg_netdev(vsi); return err; } static void ice_deinit_eth(struct ice_pf *pf) { struct ice_vsi *vsi = ice_get_main_vsi(pf); if (!vsi) return; ice_vsi_close(vsi); ice_unregister_netdev(vsi); ice_devlink_destroy_pf_port(pf); ice_tc_indir_block_unregister(vsi); ice_decfg_netdev(vsi); } /** * ice_wait_for_fw - wait for full FW readiness * @hw: pointer to the hardware structure * @timeout: milliseconds that can elapse before timing out */ static int ice_wait_for_fw(struct ice_hw *hw, u32 timeout) { int fw_loading; u32 elapsed = 0; while (elapsed <= timeout) { fw_loading = rd32(hw, GL_MNG_FWSM) & GL_MNG_FWSM_FW_LOADING_M; /* firmware was not yet loaded, we have to wait more */ if (fw_loading) { elapsed += 100; msleep(100); continue; } return 0; } return -ETIMEDOUT; } static int ice_init_dev(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); struct ice_hw *hw = &pf->hw; int err; err = ice_init_hw(hw); if (err) { dev_err(dev, "ice_init_hw failed: %d\n", err); return err; } /* Some cards require longer initialization times * due to necessity of loading FW from an external source. * This can take even half a minute. */ if (ice_is_pf_c827(hw)) { err = ice_wait_for_fw(hw, 30000); if (err) { dev_err(dev, "ice_wait_for_fw timed out"); return err; } } ice_init_feature_support(pf); ice_request_fw(pf); /* if ice_request_fw fails, ICE_FLAG_ADV_FEATURES bit won't be * set in pf->state, which will cause ice_is_safe_mode to return * true */ if (ice_is_safe_mode(pf)) { /* we already got function/device capabilities but these don't * reflect what the driver needs to do in safe mode. Instead of * adding conditional logic everywhere to ignore these * device/function capabilities, override them. */ ice_set_safe_mode_caps(hw); } err = ice_init_pf(pf); if (err) { dev_err(dev, "ice_init_pf failed: %d\n", err); goto err_init_pf; } pf->hw.udp_tunnel_nic.set_port = ice_udp_tunnel_set_port; pf->hw.udp_tunnel_nic.unset_port = ice_udp_tunnel_unset_port; pf->hw.udp_tunnel_nic.flags = UDP_TUNNEL_NIC_INFO_MAY_SLEEP; pf->hw.udp_tunnel_nic.shared = &pf->hw.udp_tunnel_shared; if (pf->hw.tnl.valid_count[TNL_VXLAN]) { pf->hw.udp_tunnel_nic.tables[0].n_entries = pf->hw.tnl.valid_count[TNL_VXLAN]; pf->hw.udp_tunnel_nic.tables[0].tunnel_types = UDP_TUNNEL_TYPE_VXLAN; } if (pf->hw.tnl.valid_count[TNL_GENEVE]) { pf->hw.udp_tunnel_nic.tables[1].n_entries = pf->hw.tnl.valid_count[TNL_GENEVE]; pf->hw.udp_tunnel_nic.tables[1].tunnel_types = UDP_TUNNEL_TYPE_GENEVE; } err = ice_init_interrupt_scheme(pf); if (err) { dev_err(dev, "ice_init_interrupt_scheme failed: %d\n", err); err = -EIO; goto err_init_interrupt_scheme; } /* In case of MSIX we are going to setup the misc vector right here * to handle admin queue events etc. In case of legacy and MSI * the misc functionality and queue processing is combined in * the same vector and that gets setup at open. */ err = ice_req_irq_msix_misc(pf); if (err) { dev_err(dev, "setup of misc vector failed: %d\n", err); goto err_req_irq_msix_misc; } return 0; err_req_irq_msix_misc: ice_clear_interrupt_scheme(pf); err_init_interrupt_scheme: ice_deinit_pf(pf); err_init_pf: ice_deinit_hw(hw); return err; } static void ice_deinit_dev(struct ice_pf *pf) { ice_free_irq_msix_misc(pf); ice_deinit_pf(pf); ice_deinit_hw(&pf->hw); /* Service task is already stopped, so call reset directly. */ ice_reset(&pf->hw, ICE_RESET_PFR); pci_wait_for_pending_transaction(pf->pdev); ice_clear_interrupt_scheme(pf); } static void ice_init_features(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); if (ice_is_safe_mode(pf)) return; /* initialize DDP driven features */ if (test_bit(ICE_FLAG_PTP_SUPPORTED, pf->flags)) ice_ptp_init(pf); if (ice_is_feature_supported(pf, ICE_F_GNSS)) ice_gnss_init(pf); /* Note: Flow director init failure is non-fatal to load */ if (ice_init_fdir(pf)) dev_err(dev, "could not initialize flow director\n"); /* Note: DCB init failure is non-fatal to load */ if (ice_init_pf_dcb(pf, false)) { clear_bit(ICE_FLAG_DCB_CAPABLE, pf->flags); clear_bit(ICE_FLAG_DCB_ENA, pf->flags); } else { ice_cfg_lldp_mib_change(&pf->hw, true); } if (ice_init_lag(pf)) dev_warn(dev, "Failed to init link aggregation support\n"); } static void ice_deinit_features(struct ice_pf *pf) { ice_deinit_lag(pf); if (test_bit(ICE_FLAG_DCB_CAPABLE, pf->flags)) ice_cfg_lldp_mib_change(&pf->hw, false); ice_deinit_fdir(pf); if (ice_is_feature_supported(pf, ICE_F_GNSS)) ice_gnss_exit(pf); if (test_bit(ICE_FLAG_PTP_SUPPORTED, pf->flags)) ice_ptp_release(pf); } static void ice_init_wakeup(struct ice_pf *pf) { /* Save wakeup reason register for later use */ pf->wakeup_reason = rd32(&pf->hw, PFPM_WUS); /* check for a power management event */ ice_print_wake_reason(pf); /* clear wake status, all bits */ wr32(&pf->hw, PFPM_WUS, U32_MAX); /* Disable WoL at init, wait for user to enable */ device_set_wakeup_enable(ice_pf_to_dev(pf), false); } static int ice_init_link(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); int err; err = ice_init_link_events(pf->hw.port_info); if (err) { dev_err(dev, "ice_init_link_events failed: %d\n", err); return err; } /* not a fatal error if this fails */ err = ice_init_nvm_phy_type(pf->hw.port_info); if (err) dev_err(dev, "ice_init_nvm_phy_type failed: %d\n", err); /* not a fatal error if this fails */ err = ice_update_link_info(pf->hw.port_info); if (err) dev_err(dev, "ice_update_link_info failed: %d\n", err); ice_init_link_dflt_override(pf->hw.port_info); ice_check_link_cfg_err(pf, pf->hw.port_info->phy.link_info.link_cfg_err); /* if media available, initialize PHY settings */ if (pf->hw.port_info->phy.link_info.link_info & ICE_AQ_MEDIA_AVAILABLE) { /* not a fatal error if this fails */ err = ice_init_phy_user_cfg(pf->hw.port_info); if (err) dev_err(dev, "ice_init_phy_user_cfg failed: %d\n", err); if (!test_bit(ICE_FLAG_LINK_DOWN_ON_CLOSE_ENA, pf->flags)) { struct ice_vsi *vsi = ice_get_main_vsi(pf); if (vsi) ice_configure_phy(vsi); } } else { set_bit(ICE_FLAG_NO_MEDIA, pf->flags); } return err; } static int ice_init_pf_sw(struct ice_pf *pf) { bool dvm = ice_is_dvm_ena(&pf->hw); struct ice_vsi *vsi; int err; /* create switch struct for the switch element created by FW on boot */ pf->first_sw = kzalloc(sizeof(*pf->first_sw), GFP_KERNEL); if (!pf->first_sw) return -ENOMEM; if (pf->hw.evb_veb) pf->first_sw->bridge_mode = BRIDGE_MODE_VEB; else pf->first_sw->bridge_mode = BRIDGE_MODE_VEPA; pf->first_sw->pf = pf; /* record the sw_id available for later use */ pf->first_sw->sw_id = pf->hw.port_info->sw_id; err = ice_aq_set_port_params(pf->hw.port_info, dvm, NULL); if (err) goto err_aq_set_port_params; vsi = ice_pf_vsi_setup(pf, pf->hw.port_info); if (!vsi) { err = -ENOMEM; goto err_pf_vsi_setup; } return 0; err_pf_vsi_setup: err_aq_set_port_params: kfree(pf->first_sw); return err; } static void ice_deinit_pf_sw(struct ice_pf *pf) { struct ice_vsi *vsi = ice_get_main_vsi(pf); if (!vsi) return; ice_vsi_release(vsi); kfree(pf->first_sw); } static int ice_alloc_vsis(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); pf->num_alloc_vsi = pf->hw.func_caps.guar_num_vsi; if (!pf->num_alloc_vsi) return -EIO; if (pf->num_alloc_vsi > UDP_TUNNEL_NIC_MAX_SHARING_DEVICES) { dev_warn(dev, "limiting the VSI count due to UDP tunnel limitation %d > %d\n", pf->num_alloc_vsi, UDP_TUNNEL_NIC_MAX_SHARING_DEVICES); pf->num_alloc_vsi = UDP_TUNNEL_NIC_MAX_SHARING_DEVICES; } pf->vsi = devm_kcalloc(dev, pf->num_alloc_vsi, sizeof(*pf->vsi), GFP_KERNEL); if (!pf->vsi) return -ENOMEM; pf->vsi_stats = devm_kcalloc(dev, pf->num_alloc_vsi, sizeof(*pf->vsi_stats), GFP_KERNEL); if (!pf->vsi_stats) { devm_kfree(dev, pf->vsi); return -ENOMEM; } return 0; } static void ice_dealloc_vsis(struct ice_pf *pf) { devm_kfree(ice_pf_to_dev(pf), pf->vsi_stats); pf->vsi_stats = NULL; pf->num_alloc_vsi = 0; devm_kfree(ice_pf_to_dev(pf), pf->vsi); pf->vsi = NULL; } static int ice_init_devlink(struct ice_pf *pf) { int err; err = ice_devlink_register_params(pf); if (err) return err; ice_devlink_init_regions(pf); ice_devlink_register(pf); return 0; } static void ice_deinit_devlink(struct ice_pf *pf) { ice_devlink_unregister(pf); ice_devlink_destroy_regions(pf); ice_devlink_unregister_params(pf); } static int ice_init(struct ice_pf *pf) { int err; err = ice_init_dev(pf); if (err) return err; err = ice_alloc_vsis(pf); if (err) goto err_alloc_vsis; err = ice_init_pf_sw(pf); if (err) goto err_init_pf_sw; ice_init_wakeup(pf); err = ice_init_link(pf); if (err) goto err_init_link; err = ice_send_version(pf); if (err) goto err_init_link; ice_verify_cacheline_size(pf); if (ice_is_safe_mode(pf)) ice_set_safe_mode_vlan_cfg(pf); else /* print PCI link speed and width */ pcie_print_link_status(pf->pdev); /* ready to go, so clear down state bit */ clear_bit(ICE_DOWN, pf->state); clear_bit(ICE_SERVICE_DIS, pf->state); /* since everything is good, start the service timer */ mod_timer(&pf->serv_tmr, round_jiffies(jiffies + pf->serv_tmr_period)); return 0; err_init_link: ice_deinit_pf_sw(pf); err_init_pf_sw: ice_dealloc_vsis(pf); err_alloc_vsis: ice_deinit_dev(pf); return err; } static void ice_deinit(struct ice_pf *pf) { set_bit(ICE_SERVICE_DIS, pf->state); set_bit(ICE_DOWN, pf->state); ice_deinit_pf_sw(pf); ice_dealloc_vsis(pf); ice_deinit_dev(pf); } /** * ice_load - load pf by init hw and starting VSI * @pf: pointer to the pf instance */ int ice_load(struct ice_pf *pf) { struct ice_vsi_cfg_params params = {}; struct ice_vsi *vsi; int err; err = ice_init_dev(pf); if (err) return err; vsi = ice_get_main_vsi(pf); params = ice_vsi_to_params(vsi); params.flags = ICE_VSI_FLAG_INIT; rtnl_lock(); err = ice_vsi_cfg(vsi, &params); if (err) goto err_vsi_cfg; err = ice_start_eth(ice_get_main_vsi(pf)); if (err) goto err_start_eth; rtnl_unlock(); err = ice_init_rdma(pf); if (err) goto err_init_rdma; ice_init_features(pf); ice_service_task_restart(pf); clear_bit(ICE_DOWN, pf->state); return 0; err_init_rdma: ice_vsi_close(ice_get_main_vsi(pf)); rtnl_lock(); err_start_eth: ice_vsi_decfg(ice_get_main_vsi(pf)); err_vsi_cfg: rtnl_unlock(); ice_deinit_dev(pf); return err; } /** * ice_unload - unload pf by stopping VSI and deinit hw * @pf: pointer to the pf instance */ void ice_unload(struct ice_pf *pf) { ice_deinit_features(pf); ice_deinit_rdma(pf); rtnl_lock(); ice_stop_eth(ice_get_main_vsi(pf)); ice_vsi_decfg(ice_get_main_vsi(pf)); rtnl_unlock(); ice_deinit_dev(pf); } /** * ice_probe - Device initialization routine * @pdev: PCI device information struct * @ent: entry in ice_pci_tbl * * Returns 0 on success, negative on failure */ static int ice_probe(struct pci_dev *pdev, const struct pci_device_id __always_unused *ent) { struct device *dev = &pdev->dev; struct ice_pf *pf; struct ice_hw *hw; int err; if (pdev->is_virtfn) { dev_err(dev, "can't probe a virtual function\n"); return -EINVAL; } /* this driver uses devres, see * Documentation/driver-api/driver-model/devres.rst */ err = pcim_enable_device(pdev); if (err) return err; err = pcim_iomap_regions(pdev, BIT(ICE_BAR0), dev_driver_string(dev)); if (err) { dev_err(dev, "BAR0 I/O map error %d\n", err); return err; } pf = ice_allocate_pf(dev); if (!pf) return -ENOMEM; /* initialize Auxiliary index to invalid value */ pf->aux_idx = -1; /* set up for high or low DMA */ err = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(64)); if (err) { dev_err(dev, "DMA configuration failed: 0x%x\n", err); return err; } pci_set_master(pdev); pf->pdev = pdev; pci_set_drvdata(pdev, pf); set_bit(ICE_DOWN, pf->state); /* Disable service task until DOWN bit is cleared */ set_bit(ICE_SERVICE_DIS, pf->state); hw = &pf->hw; hw->hw_addr = pcim_iomap_table(pdev)[ICE_BAR0]; pci_save_state(pdev); hw->back = pf; hw->port_info = NULL; hw->vendor_id = pdev->vendor; hw->device_id = pdev->device; pci_read_config_byte(pdev, PCI_REVISION_ID, &hw->revision_id); hw->subsystem_vendor_id = pdev->subsystem_vendor; hw->subsystem_device_id = pdev->subsystem_device; hw->bus.device = PCI_SLOT(pdev->devfn); hw->bus.func = PCI_FUNC(pdev->devfn); ice_set_ctrlq_len(hw); pf->msg_enable = netif_msg_init(debug, ICE_DFLT_NETIF_M); #ifndef CONFIG_DYNAMIC_DEBUG if (debug < -1) hw->debug_mask = debug; #endif err = ice_init(pf); if (err) goto err_init; err = ice_init_eth(pf); if (err) goto err_init_eth; err = ice_init_rdma(pf); if (err) goto err_init_rdma; err = ice_init_devlink(pf); if (err) goto err_init_devlink; ice_init_features(pf); return 0; err_init_devlink: ice_deinit_rdma(pf); err_init_rdma: ice_deinit_eth(pf); err_init_eth: ice_deinit(pf); err_init: pci_disable_device(pdev); return err; } /** * ice_set_wake - enable or disable Wake on LAN * @pf: pointer to the PF struct * * Simple helper for WoL control */ static void ice_set_wake(struct ice_pf *pf) { struct ice_hw *hw = &pf->hw; bool wol = pf->wol_ena; /* clear wake state, otherwise new wake events won't fire */ wr32(hw, PFPM_WUS, U32_MAX); /* enable / disable APM wake up, no RMW needed */ wr32(hw, PFPM_APM, wol ? PFPM_APM_APME_M : 0); /* set magic packet filter enabled */ wr32(hw, PFPM_WUFC, wol ? PFPM_WUFC_MAG_M : 0); } /** * ice_setup_mc_magic_wake - setup device to wake on multicast magic packet * @pf: pointer to the PF struct * * Issue firmware command to enable multicast magic wake, making * sure that any locally administered address (LAA) is used for * wake, and that PF reset doesn't undo the LAA. */ static void ice_setup_mc_magic_wake(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); struct ice_hw *hw = &pf->hw; u8 mac_addr[ETH_ALEN]; struct ice_vsi *vsi; int status; u8 flags; if (!pf->wol_ena) return; vsi = ice_get_main_vsi(pf); if (!vsi) return; /* Get current MAC address in case it's an LAA */ if (vsi->netdev) ether_addr_copy(mac_addr, vsi->netdev->dev_addr); else ether_addr_copy(mac_addr, vsi->port_info->mac.perm_addr); flags = ICE_AQC_MAN_MAC_WR_MC_MAG_EN | ICE_AQC_MAN_MAC_UPDATE_LAA_WOL | ICE_AQC_MAN_MAC_WR_WOL_LAA_PFR_KEEP; status = ice_aq_manage_mac_write(hw, mac_addr, flags, NULL); if (status) dev_err(dev, "Failed to enable Multicast Magic Packet wake, err %d aq_err %s\n", status, ice_aq_str(hw->adminq.sq_last_status)); } /** * ice_remove - Device removal routine * @pdev: PCI device information struct */ static void ice_remove(struct pci_dev *pdev) { struct ice_pf *pf = pci_get_drvdata(pdev); int i; for (i = 0; i < ICE_MAX_RESET_WAIT; i++) { if (!ice_is_reset_in_progress(pf->state)) break; msleep(100); } if (test_bit(ICE_FLAG_SRIOV_ENA, pf->flags)) { set_bit(ICE_VF_RESETS_DISABLED, pf->state); ice_free_vfs(pf); } ice_service_task_stop(pf); ice_aq_cancel_waiting_tasks(pf); set_bit(ICE_DOWN, pf->state); if (!ice_is_safe_mode(pf)) ice_remove_arfs(pf); ice_deinit_features(pf); ice_deinit_devlink(pf); ice_deinit_rdma(pf); ice_deinit_eth(pf); ice_deinit(pf); ice_vsi_release_all(pf); ice_setup_mc_magic_wake(pf); ice_set_wake(pf); pci_disable_device(pdev); } /** * ice_shutdown - PCI callback for shutting down device * @pdev: PCI device information struct */ static void ice_shutdown(struct pci_dev *pdev) { struct ice_pf *pf = pci_get_drvdata(pdev); ice_remove(pdev); if (system_state == SYSTEM_POWER_OFF) { pci_wake_from_d3(pdev, pf->wol_ena); pci_set_power_state(pdev, PCI_D3hot); } } #ifdef CONFIG_PM /** * ice_prepare_for_shutdown - prep for PCI shutdown * @pf: board private structure * * Inform or close all dependent features in prep for PCI device shutdown */ static void ice_prepare_for_shutdown(struct ice_pf *pf) { struct ice_hw *hw = &pf->hw; u32 v; /* Notify VFs of impending reset */ if (ice_check_sq_alive(hw, &hw->mailboxq)) ice_vc_notify_reset(pf); dev_dbg(ice_pf_to_dev(pf), "Tearing down internal switch for shutdown\n"); /* disable the VSIs and their queues that are not already DOWN */ ice_pf_dis_all_vsi(pf, false); ice_for_each_vsi(pf, v) if (pf->vsi[v]) pf->vsi[v]->vsi_num = 0; ice_shutdown_all_ctrlq(hw); } /** * ice_reinit_interrupt_scheme - Reinitialize interrupt scheme * @pf: board private structure to reinitialize * * This routine reinitialize interrupt scheme that was cleared during * power management suspend callback. * * This should be called during resume routine to re-allocate the q_vectors * and reacquire interrupts. */ static int ice_reinit_interrupt_scheme(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); int ret, v; /* Since we clear MSIX flag during suspend, we need to * set it back during resume... */ ret = ice_init_interrupt_scheme(pf); if (ret) { dev_err(dev, "Failed to re-initialize interrupt %d\n", ret); return ret; } /* Remap vectors and rings, after successful re-init interrupts */ ice_for_each_vsi(pf, v) { if (!pf->vsi[v]) continue; ret = ice_vsi_alloc_q_vectors(pf->vsi[v]); if (ret) goto err_reinit; ice_vsi_map_rings_to_vectors(pf->vsi[v]); } ret = ice_req_irq_msix_misc(pf); if (ret) { dev_err(dev, "Setting up misc vector failed after device suspend %d\n", ret); goto err_reinit; } return 0; err_reinit: while (v--) if (pf->vsi[v]) ice_vsi_free_q_vectors(pf->vsi[v]); return ret; } /** * ice_suspend * @dev: generic device information structure * * Power Management callback to quiesce the device and prepare * for D3 transition. */ static int __maybe_unused ice_suspend(struct device *dev) { struct pci_dev *pdev = to_pci_dev(dev); struct ice_pf *pf; int disabled, v; pf = pci_get_drvdata(pdev); if (!ice_pf_state_is_nominal(pf)) { dev_err(dev, "Device is not ready, no need to suspend it\n"); return -EBUSY; } /* Stop watchdog tasks until resume completion. * Even though it is most likely that the service task is * disabled if the device is suspended or down, the service task's * state is controlled by a different state bit, and we should * store and honor whatever state that bit is in at this point. */ disabled = ice_service_task_stop(pf); ice_unplug_aux_dev(pf); /* Already suspended?, then there is nothing to do */ if (test_and_set_bit(ICE_SUSPENDED, pf->state)) { if (!disabled) ice_service_task_restart(pf); return 0; } if (test_bit(ICE_DOWN, pf->state) || ice_is_reset_in_progress(pf->state)) { dev_err(dev, "can't suspend device in reset or already down\n"); if (!disabled) ice_service_task_restart(pf); return 0; } ice_setup_mc_magic_wake(pf); ice_prepare_for_shutdown(pf); ice_set_wake(pf); /* Free vectors, clear the interrupt scheme and release IRQs * for proper hibernation, especially with large number of CPUs. * Otherwise hibernation might fail when mapping all the vectors back * to CPU0. */ ice_free_irq_msix_misc(pf); ice_for_each_vsi(pf, v) { if (!pf->vsi[v]) continue; ice_vsi_free_q_vectors(pf->vsi[v]); } ice_clear_interrupt_scheme(pf); pci_save_state(pdev); pci_wake_from_d3(pdev, pf->wol_ena); pci_set_power_state(pdev, PCI_D3hot); return 0; } /** * ice_resume - PM callback for waking up from D3 * @dev: generic device information structure */ static int __maybe_unused ice_resume(struct device *dev) { struct pci_dev *pdev = to_pci_dev(dev); enum ice_reset_req reset_type; struct ice_pf *pf; struct ice_hw *hw; int ret; pci_set_power_state(pdev, PCI_D0); pci_restore_state(pdev); pci_save_state(pdev); if (!pci_device_is_present(pdev)) return -ENODEV; ret = pci_enable_device_mem(pdev); if (ret) { dev_err(dev, "Cannot enable device after suspend\n"); return ret; } pf = pci_get_drvdata(pdev); hw = &pf->hw; pf->wakeup_reason = rd32(hw, PFPM_WUS); ice_print_wake_reason(pf); /* We cleared the interrupt scheme when we suspended, so we need to * restore it now to resume device functionality. */ ret = ice_reinit_interrupt_scheme(pf); if (ret) dev_err(dev, "Cannot restore interrupt scheme: %d\n", ret); clear_bit(ICE_DOWN, pf->state); /* Now perform PF reset and rebuild */ reset_type = ICE_RESET_PFR; /* re-enable service task for reset, but allow reset to schedule it */ clear_bit(ICE_SERVICE_DIS, pf->state); if (ice_schedule_reset(pf, reset_type)) dev_err(dev, "Reset during resume failed.\n"); clear_bit(ICE_SUSPENDED, pf->state); ice_service_task_restart(pf); /* Restart the service task */ mod_timer(&pf->serv_tmr, round_jiffies(jiffies + pf->serv_tmr_period)); return 0; } #endif /* CONFIG_PM */ /** * ice_pci_err_detected - warning that PCI error has been detected * @pdev: PCI device information struct * @err: the type of PCI error * * Called to warn that something happened on the PCI bus and the error handling * is in progress. Allows the driver to gracefully prepare/handle PCI errors. */ static pci_ers_result_t ice_pci_err_detected(struct pci_dev *pdev, pci_channel_state_t err) { struct ice_pf *pf = pci_get_drvdata(pdev); if (!pf) { dev_err(&pdev->dev, "%s: unrecoverable device error %d\n", __func__, err); return PCI_ERS_RESULT_DISCONNECT; } if (!test_bit(ICE_SUSPENDED, pf->state)) { ice_service_task_stop(pf); if (!test_bit(ICE_PREPARED_FOR_RESET, pf->state)) { set_bit(ICE_PFR_REQ, pf->state); ice_prepare_for_reset(pf, ICE_RESET_PFR); } } return PCI_ERS_RESULT_NEED_RESET; } /** * ice_pci_err_slot_reset - a PCI slot reset has just happened * @pdev: PCI device information struct * * Called to determine if the driver can recover from the PCI slot reset by * using a register read to determine if the device is recoverable. */ static pci_ers_result_t ice_pci_err_slot_reset(struct pci_dev *pdev) { struct ice_pf *pf = pci_get_drvdata(pdev); pci_ers_result_t result; int err; u32 reg; err = pci_enable_device_mem(pdev); if (err) { dev_err(&pdev->dev, "Cannot re-enable PCI device after reset, error %d\n", err); result = PCI_ERS_RESULT_DISCONNECT; } else { pci_set_master(pdev); pci_restore_state(pdev); pci_save_state(pdev); pci_wake_from_d3(pdev, false); /* Check for life */ reg = rd32(&pf->hw, GLGEN_RTRIG); if (!reg) result = PCI_ERS_RESULT_RECOVERED; else result = PCI_ERS_RESULT_DISCONNECT; } return result; } /** * ice_pci_err_resume - restart operations after PCI error recovery * @pdev: PCI device information struct * * Called to allow the driver to bring things back up after PCI error and/or * reset recovery have finished */ static void ice_pci_err_resume(struct pci_dev *pdev) { struct ice_pf *pf = pci_get_drvdata(pdev); if (!pf) { dev_err(&pdev->dev, "%s failed, device is unrecoverable\n", __func__); return; } if (test_bit(ICE_SUSPENDED, pf->state)) { dev_dbg(&pdev->dev, "%s failed to resume normal operations!\n", __func__); return; } ice_restore_all_vfs_msi_state(pdev); ice_do_reset(pf, ICE_RESET_PFR); ice_service_task_restart(pf); mod_timer(&pf->serv_tmr, round_jiffies(jiffies + pf->serv_tmr_period)); } /** * ice_pci_err_reset_prepare - prepare device driver for PCI reset * @pdev: PCI device information struct */ static void ice_pci_err_reset_prepare(struct pci_dev *pdev) { struct ice_pf *pf = pci_get_drvdata(pdev); if (!test_bit(ICE_SUSPENDED, pf->state)) { ice_service_task_stop(pf); if (!test_bit(ICE_PREPARED_FOR_RESET, pf->state)) { set_bit(ICE_PFR_REQ, pf->state); ice_prepare_for_reset(pf, ICE_RESET_PFR); } } } /** * ice_pci_err_reset_done - PCI reset done, device driver reset can begin * @pdev: PCI device information struct */ static void ice_pci_err_reset_done(struct pci_dev *pdev) { ice_pci_err_resume(pdev); } /* ice_pci_tbl - PCI Device ID Table * * Wildcard entries (PCI_ANY_ID) should come last * Last entry must be all 0s * * { Vendor ID, Device ID, SubVendor ID, SubDevice ID, * Class, Class Mask, private data (not used) } */ static const struct pci_device_id ice_pci_tbl[] = { { PCI_VDEVICE(INTEL, ICE_DEV_ID_E810C_BACKPLANE), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E810C_QSFP), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E810C_SFP), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E810_XXV_BACKPLANE), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E810_XXV_QSFP), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E810_XXV_SFP), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823C_BACKPLANE), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823C_QSFP), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823C_SFP), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823C_10G_BASE_T), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823C_SGMII), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822C_BACKPLANE), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822C_QSFP), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822C_SFP), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822C_10G_BASE_T), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822C_SGMII), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822L_BACKPLANE), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822L_SFP), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822L_10G_BASE_T), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822L_SGMII), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823L_BACKPLANE), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823L_SFP), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823L_10G_BASE_T), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823L_1GBE), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823L_QSFP), 0 }, { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822_SI_DFLT), 0 }, /* required last entry */ { 0, } }; MODULE_DEVICE_TABLE(pci, ice_pci_tbl); static __maybe_unused SIMPLE_DEV_PM_OPS(ice_pm_ops, ice_suspend, ice_resume); static const struct pci_error_handlers ice_pci_err_handler = { .error_detected = ice_pci_err_detected, .slot_reset = ice_pci_err_slot_reset, .reset_prepare = ice_pci_err_reset_prepare, .reset_done = ice_pci_err_reset_done, .resume = ice_pci_err_resume }; static struct pci_driver ice_driver = { .name = KBUILD_MODNAME, .id_table = ice_pci_tbl, .probe = ice_probe, .remove = ice_remove, #ifdef CONFIG_PM .driver.pm = &ice_pm_ops, #endif /* CONFIG_PM */ .shutdown = ice_shutdown, .sriov_configure = ice_sriov_configure, .err_handler = &ice_pci_err_handler }; /** * ice_module_init - Driver registration routine * * ice_module_init is the first routine called when the driver is * loaded. All it does is register with the PCI subsystem. */ static int __init ice_module_init(void) { int status = -ENOMEM; pr_info("%s\n", ice_driver_string); pr_info("%s\n", ice_copyright); ice_wq = alloc_workqueue("%s", 0, 0, KBUILD_MODNAME); if (!ice_wq) { pr_err("Failed to create workqueue\n"); return status; } ice_lag_wq = alloc_ordered_workqueue("ice_lag_wq", 0); if (!ice_lag_wq) { pr_err("Failed to create LAG workqueue\n"); goto err_dest_wq; } status = pci_register_driver(&ice_driver); if (status) { pr_err("failed to register PCI driver, err %d\n", status); goto err_dest_lag_wq; } return 0; err_dest_lag_wq: destroy_workqueue(ice_lag_wq); err_dest_wq: destroy_workqueue(ice_wq); return status; } module_init(ice_module_init); /** * ice_module_exit - Driver exit cleanup routine * * ice_module_exit is called just before the driver is removed * from memory. */ static void __exit ice_module_exit(void) { pci_unregister_driver(&ice_driver); destroy_workqueue(ice_wq); destroy_workqueue(ice_lag_wq); pr_info("module unloaded\n"); } module_exit(ice_module_exit); /** * ice_set_mac_address - NDO callback to set MAC address * @netdev: network interface device structure * @pi: pointer to an address structure * * Returns 0 on success, negative on failure */ static int ice_set_mac_address(struct net_device *netdev, void *pi) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; struct sockaddr *addr = pi; u8 old_mac[ETH_ALEN]; u8 flags = 0; u8 *mac; int err; mac = (u8 *)addr->sa_data; if (!is_valid_ether_addr(mac)) return -EADDRNOTAVAIL; if (test_bit(ICE_DOWN, pf->state) || ice_is_reset_in_progress(pf->state)) { netdev_err(netdev, "can't set mac %pM. device not ready\n", mac); return -EBUSY; } if (ice_chnl_dmac_fltr_cnt(pf)) { netdev_err(netdev, "can't set mac %pM. Device has tc-flower filters, delete all of them and try again\n", mac); return -EAGAIN; } netif_addr_lock_bh(netdev); ether_addr_copy(old_mac, netdev->dev_addr); /* change the netdev's MAC address */ eth_hw_addr_set(netdev, mac); netif_addr_unlock_bh(netdev); /* Clean up old MAC filter. Not an error if old filter doesn't exist */ err = ice_fltr_remove_mac(vsi, old_mac, ICE_FWD_TO_VSI); if (err && err != -ENOENT) { err = -EADDRNOTAVAIL; goto err_update_filters; } /* Add filter for new MAC. If filter exists, return success */ err = ice_fltr_add_mac(vsi, mac, ICE_FWD_TO_VSI); if (err == -EEXIST) { /* Although this MAC filter is already present in hardware it's * possible in some cases (e.g. bonding) that dev_addr was * modified outside of the driver and needs to be restored back * to this value. */ netdev_dbg(netdev, "filter for MAC %pM already exists\n", mac); return 0; } else if (err) { /* error if the new filter addition failed */ err = -EADDRNOTAVAIL; } err_update_filters: if (err) { netdev_err(netdev, "can't set MAC %pM. filter update failed\n", mac); netif_addr_lock_bh(netdev); eth_hw_addr_set(netdev, old_mac); netif_addr_unlock_bh(netdev); return err; } netdev_dbg(vsi->netdev, "updated MAC address to %pM\n", netdev->dev_addr); /* write new MAC address to the firmware */ flags = ICE_AQC_MAN_MAC_UPDATE_LAA_WOL; err = ice_aq_manage_mac_write(hw, mac, flags, NULL); if (err) { netdev_err(netdev, "can't set MAC %pM. write to firmware failed error %d\n", mac, err); } return 0; } /** * ice_set_rx_mode - NDO callback to set the netdev filters * @netdev: network interface device structure */ static void ice_set_rx_mode(struct net_device *netdev) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; if (!vsi || ice_is_switchdev_running(vsi->back)) return; /* Set the flags to synchronize filters * ndo_set_rx_mode may be triggered even without a change in netdev * flags */ set_bit(ICE_VSI_UMAC_FLTR_CHANGED, vsi->state); set_bit(ICE_VSI_MMAC_FLTR_CHANGED, vsi->state); set_bit(ICE_FLAG_FLTR_SYNC, vsi->back->flags); /* schedule our worker thread which will take care of * applying the new filter changes */ ice_service_task_schedule(vsi->back); } /** * ice_set_tx_maxrate - NDO callback to set the maximum per-queue bitrate * @netdev: network interface device structure * @queue_index: Queue ID * @maxrate: maximum bandwidth in Mbps */ static int ice_set_tx_maxrate(struct net_device *netdev, int queue_index, u32 maxrate) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; u16 q_handle; int status; u8 tc; /* Validate maxrate requested is within permitted range */ if (maxrate && (maxrate > (ICE_SCHED_MAX_BW / 1000))) { netdev_err(netdev, "Invalid max rate %d specified for the queue %d\n", maxrate, queue_index); return -EINVAL; } q_handle = vsi->tx_rings[queue_index]->q_handle; tc = ice_dcb_get_tc(vsi, queue_index); vsi = ice_locate_vsi_using_queue(vsi, queue_index); if (!vsi) { netdev_err(netdev, "Invalid VSI for given queue %d\n", queue_index); return -EINVAL; } /* Set BW back to default, when user set maxrate to 0 */ if (!maxrate) status = ice_cfg_q_bw_dflt_lmt(vsi->port_info, vsi->idx, tc, q_handle, ICE_MAX_BW); else status = ice_cfg_q_bw_lmt(vsi->port_info, vsi->idx, tc, q_handle, ICE_MAX_BW, maxrate * 1000); if (status) netdev_err(netdev, "Unable to set Tx max rate, error %d\n", status); return status; } /** * ice_fdb_add - add an entry to the hardware database * @ndm: the input from the stack * @tb: pointer to array of nladdr (unused) * @dev: the net device pointer * @addr: the MAC address entry being added * @vid: VLAN ID * @flags: instructions from stack about fdb operation * @extack: netlink extended ack */ static int ice_fdb_add(struct ndmsg *ndm, struct nlattr __always_unused *tb[], struct net_device *dev, const unsigned char *addr, u16 vid, u16 flags, struct netlink_ext_ack __always_unused *extack) { int err; if (vid) { netdev_err(dev, "VLANs aren't supported yet for dev_uc|mc_add()\n"); return -EINVAL; } if (ndm->ndm_state && !(ndm->ndm_state & NUD_PERMANENT)) { netdev_err(dev, "FDB only supports static addresses\n"); return -EINVAL; } if (is_unicast_ether_addr(addr) || is_link_local_ether_addr(addr)) err = dev_uc_add_excl(dev, addr); else if (is_multicast_ether_addr(addr)) err = dev_mc_add_excl(dev, addr); else err = -EINVAL; /* Only return duplicate errors if NLM_F_EXCL is set */ if (err == -EEXIST && !(flags & NLM_F_EXCL)) err = 0; return err; } /** * ice_fdb_del - delete an entry from the hardware database * @ndm: the input from the stack * @tb: pointer to array of nladdr (unused) * @dev: the net device pointer * @addr: the MAC address entry being added * @vid: VLAN ID * @extack: netlink extended ack */ static int ice_fdb_del(struct ndmsg *ndm, __always_unused struct nlattr *tb[], struct net_device *dev, const unsigned char *addr, __always_unused u16 vid, struct netlink_ext_ack *extack) { int err; if (ndm->ndm_state & NUD_PERMANENT) { netdev_err(dev, "FDB only supports static addresses\n"); return -EINVAL; } if (is_unicast_ether_addr(addr)) err = dev_uc_del(dev, addr); else if (is_multicast_ether_addr(addr)) err = dev_mc_del(dev, addr); else err = -EINVAL; return err; } #define NETIF_VLAN_OFFLOAD_FEATURES (NETIF_F_HW_VLAN_CTAG_RX | \ NETIF_F_HW_VLAN_CTAG_TX | \ NETIF_F_HW_VLAN_STAG_RX | \ NETIF_F_HW_VLAN_STAG_TX) #define NETIF_VLAN_STRIPPING_FEATURES (NETIF_F_HW_VLAN_CTAG_RX | \ NETIF_F_HW_VLAN_STAG_RX) #define NETIF_VLAN_FILTERING_FEATURES (NETIF_F_HW_VLAN_CTAG_FILTER | \ NETIF_F_HW_VLAN_STAG_FILTER) /** * ice_fix_features - fix the netdev features flags based on device limitations * @netdev: ptr to the netdev that flags are being fixed on * @features: features that need to be checked and possibly fixed * * Make sure any fixups are made to features in this callback. This enables the * driver to not have to check unsupported configurations throughout the driver * because that's the responsiblity of this callback. * * Single VLAN Mode (SVM) Supported Features: * NETIF_F_HW_VLAN_CTAG_FILTER * NETIF_F_HW_VLAN_CTAG_RX * NETIF_F_HW_VLAN_CTAG_TX * * Double VLAN Mode (DVM) Supported Features: * NETIF_F_HW_VLAN_CTAG_FILTER * NETIF_F_HW_VLAN_CTAG_RX * NETIF_F_HW_VLAN_CTAG_TX * * NETIF_F_HW_VLAN_STAG_FILTER * NETIF_HW_VLAN_STAG_RX * NETIF_HW_VLAN_STAG_TX * * Features that need fixing: * Cannot simultaneously enable CTAG and STAG stripping and/or insertion. * These are mutually exlusive as the VSI context cannot support multiple * VLAN ethertypes simultaneously for stripping and/or insertion. If this * is not done, then default to clearing the requested STAG offload * settings. * * All supported filtering has to be enabled or disabled together. For * example, in DVM, CTAG and STAG filtering have to be enabled and disabled * together. If this is not done, then default to VLAN filtering disabled. * These are mutually exclusive as there is currently no way to * enable/disable VLAN filtering based on VLAN ethertype when using VLAN * prune rules. */ static netdev_features_t ice_fix_features(struct net_device *netdev, netdev_features_t features) { struct ice_netdev_priv *np = netdev_priv(netdev); netdev_features_t req_vlan_fltr, cur_vlan_fltr; bool cur_ctag, cur_stag, req_ctag, req_stag; cur_vlan_fltr = netdev->features & NETIF_VLAN_FILTERING_FEATURES; cur_ctag = cur_vlan_fltr & NETIF_F_HW_VLAN_CTAG_FILTER; cur_stag = cur_vlan_fltr & NETIF_F_HW_VLAN_STAG_FILTER; req_vlan_fltr = features & NETIF_VLAN_FILTERING_FEATURES; req_ctag = req_vlan_fltr & NETIF_F_HW_VLAN_CTAG_FILTER; req_stag = req_vlan_fltr & NETIF_F_HW_VLAN_STAG_FILTER; if (req_vlan_fltr != cur_vlan_fltr) { if (ice_is_dvm_ena(&np->vsi->back->hw)) { if (req_ctag && req_stag) { features |= NETIF_VLAN_FILTERING_FEATURES; } else if (!req_ctag && !req_stag) { features &= ~NETIF_VLAN_FILTERING_FEATURES; } else if ((!cur_ctag && req_ctag && !cur_stag) || (!cur_stag && req_stag && !cur_ctag)) { features |= NETIF_VLAN_FILTERING_FEATURES; netdev_warn(netdev, "802.1Q and 802.1ad VLAN filtering must be either both on or both off. VLAN filtering has been enabled for both types.\n"); } else if ((cur_ctag && !req_ctag && cur_stag) || (cur_stag && !req_stag && cur_ctag)) { features &= ~NETIF_VLAN_FILTERING_FEATURES; netdev_warn(netdev, "802.1Q and 802.1ad VLAN filtering must be either both on or both off. VLAN filtering has been disabled for both types.\n"); } } else { if (req_vlan_fltr & NETIF_F_HW_VLAN_STAG_FILTER) netdev_warn(netdev, "cannot support requested 802.1ad filtering setting in SVM mode\n"); if (req_vlan_fltr & NETIF_F_HW_VLAN_CTAG_FILTER) features |= NETIF_F_HW_VLAN_CTAG_FILTER; } } if ((features & (NETIF_F_HW_VLAN_CTAG_RX | NETIF_F_HW_VLAN_CTAG_TX)) && (features & (NETIF_F_HW_VLAN_STAG_RX | NETIF_F_HW_VLAN_STAG_TX))) { netdev_warn(netdev, "cannot support CTAG and STAG VLAN stripping and/or insertion simultaneously since CTAG and STAG offloads are mutually exclusive, clearing STAG offload settings\n"); features &= ~(NETIF_F_HW_VLAN_STAG_RX | NETIF_F_HW_VLAN_STAG_TX); } if (!(netdev->features & NETIF_F_RXFCS) && (features & NETIF_F_RXFCS) && (features & NETIF_VLAN_STRIPPING_FEATURES) && !ice_vsi_has_non_zero_vlans(np->vsi)) { netdev_warn(netdev, "Disabling VLAN stripping as FCS/CRC stripping is also disabled and there is no VLAN configured\n"); features &= ~NETIF_VLAN_STRIPPING_FEATURES; } return features; } /** * ice_set_vlan_offload_features - set VLAN offload features for the PF VSI * @vsi: PF's VSI * @features: features used to determine VLAN offload settings * * First, determine the vlan_ethertype based on the VLAN offload bits in * features. Then determine if stripping and insertion should be enabled or * disabled. Finally enable or disable VLAN stripping and insertion. */ static int ice_set_vlan_offload_features(struct ice_vsi *vsi, netdev_features_t features) { bool enable_stripping = true, enable_insertion = true; struct ice_vsi_vlan_ops *vlan_ops; int strip_err = 0, insert_err = 0; u16 vlan_ethertype = 0; vlan_ops = ice_get_compat_vsi_vlan_ops(vsi); if (features & (NETIF_F_HW_VLAN_STAG_RX | NETIF_F_HW_VLAN_STAG_TX)) vlan_ethertype = ETH_P_8021AD; else if (features & (NETIF_F_HW_VLAN_CTAG_RX | NETIF_F_HW_VLAN_CTAG_TX)) vlan_ethertype = ETH_P_8021Q; if (!(features & (NETIF_F_HW_VLAN_STAG_RX | NETIF_F_HW_VLAN_CTAG_RX))) enable_stripping = false; if (!(features & (NETIF_F_HW_VLAN_STAG_TX | NETIF_F_HW_VLAN_CTAG_TX))) enable_insertion = false; if (enable_stripping) strip_err = vlan_ops->ena_stripping(vsi, vlan_ethertype); else strip_err = vlan_ops->dis_stripping(vsi); if (enable_insertion) insert_err = vlan_ops->ena_insertion(vsi, vlan_ethertype); else insert_err = vlan_ops->dis_insertion(vsi); if (strip_err || insert_err) return -EIO; return 0; } /** * ice_set_vlan_filtering_features - set VLAN filtering features for the PF VSI * @vsi: PF's VSI * @features: features used to determine VLAN filtering settings * * Enable or disable Rx VLAN filtering based on the VLAN filtering bits in the * features. */ static int ice_set_vlan_filtering_features(struct ice_vsi *vsi, netdev_features_t features) { struct ice_vsi_vlan_ops *vlan_ops = ice_get_compat_vsi_vlan_ops(vsi); int err = 0; /* support Single VLAN Mode (SVM) and Double VLAN Mode (DVM) by checking * if either bit is set */ if (features & (NETIF_F_HW_VLAN_CTAG_FILTER | NETIF_F_HW_VLAN_STAG_FILTER)) err = vlan_ops->ena_rx_filtering(vsi); else err = vlan_ops->dis_rx_filtering(vsi); return err; } /** * ice_set_vlan_features - set VLAN settings based on suggested feature set * @netdev: ptr to the netdev being adjusted * @features: the feature set that the stack is suggesting * * Only update VLAN settings if the requested_vlan_features are different than * the current_vlan_features. */ static int ice_set_vlan_features(struct net_device *netdev, netdev_features_t features) { netdev_features_t current_vlan_features, requested_vlan_features; struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; int err; current_vlan_features = netdev->features & NETIF_VLAN_OFFLOAD_FEATURES; requested_vlan_features = features & NETIF_VLAN_OFFLOAD_FEATURES; if (current_vlan_features ^ requested_vlan_features) { if ((features & NETIF_F_RXFCS) && (features & NETIF_VLAN_STRIPPING_FEATURES)) { dev_err(ice_pf_to_dev(vsi->back), "To enable VLAN stripping, you must first enable FCS/CRC stripping\n"); return -EIO; } err = ice_set_vlan_offload_features(vsi, features); if (err) return err; } current_vlan_features = netdev->features & NETIF_VLAN_FILTERING_FEATURES; requested_vlan_features = features & NETIF_VLAN_FILTERING_FEATURES; if (current_vlan_features ^ requested_vlan_features) { err = ice_set_vlan_filtering_features(vsi, features); if (err) return err; } return 0; } /** * ice_set_loopback - turn on/off loopback mode on underlying PF * @vsi: ptr to VSI * @ena: flag to indicate the on/off setting */ static int ice_set_loopback(struct ice_vsi *vsi, bool ena) { bool if_running = netif_running(vsi->netdev); int ret; if (if_running && !test_and_set_bit(ICE_VSI_DOWN, vsi->state)) { ret = ice_down(vsi); if (ret) { netdev_err(vsi->netdev, "Preparing device to toggle loopback failed\n"); return ret; } } ret = ice_aq_set_mac_loopback(&vsi->back->hw, ena, NULL); if (ret) netdev_err(vsi->netdev, "Failed to toggle loopback state\n"); if (if_running) ret = ice_up(vsi); return ret; } /** * ice_set_features - set the netdev feature flags * @netdev: ptr to the netdev being adjusted * @features: the feature set that the stack is suggesting */ static int ice_set_features(struct net_device *netdev, netdev_features_t features) { netdev_features_t changed = netdev->features ^ features; struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; struct ice_pf *pf = vsi->back; int ret = 0; /* Don't set any netdev advanced features with device in Safe Mode */ if (ice_is_safe_mode(pf)) { dev_err(ice_pf_to_dev(pf), "Device is in Safe Mode - not enabling advanced netdev features\n"); return ret; } /* Do not change setting during reset */ if (ice_is_reset_in_progress(pf->state)) { dev_err(ice_pf_to_dev(pf), "Device is resetting, changing advanced netdev features temporarily unavailable.\n"); return -EBUSY; } /* Multiple features can be changed in one call so keep features in * separate if/else statements to guarantee each feature is checked */ if (changed & NETIF_F_RXHASH) ice_vsi_manage_rss_lut(vsi, !!(features & NETIF_F_RXHASH)); ret = ice_set_vlan_features(netdev, features); if (ret) return ret; /* Turn on receive of FCS aka CRC, and after setting this * flag the packet data will have the 4 byte CRC appended */ if (changed & NETIF_F_RXFCS) { if ((features & NETIF_F_RXFCS) && (features & NETIF_VLAN_STRIPPING_FEATURES)) { dev_err(ice_pf_to_dev(vsi->back), "To disable FCS/CRC stripping, you must first disable VLAN stripping\n"); return -EIO; } ice_vsi_cfg_crc_strip(vsi, !!(features & NETIF_F_RXFCS)); ret = ice_down_up(vsi); if (ret) return ret; } if (changed & NETIF_F_NTUPLE) { bool ena = !!(features & NETIF_F_NTUPLE); ice_vsi_manage_fdir(vsi, ena); ena ? ice_init_arfs(vsi) : ice_clear_arfs(vsi); } /* don't turn off hw_tc_offload when ADQ is already enabled */ if (!(features & NETIF_F_HW_TC) && ice_is_adq_active(pf)) { dev_err(ice_pf_to_dev(pf), "ADQ is active, can't turn hw_tc_offload off\n"); return -EACCES; } if (changed & NETIF_F_HW_TC) { bool ena = !!(features & NETIF_F_HW_TC); ena ? set_bit(ICE_FLAG_CLS_FLOWER, pf->flags) : clear_bit(ICE_FLAG_CLS_FLOWER, pf->flags); } if (changed & NETIF_F_LOOPBACK) ret = ice_set_loopback(vsi, !!(features & NETIF_F_LOOPBACK)); return ret; } /** * ice_vsi_vlan_setup - Setup VLAN offload properties on a PF VSI * @vsi: VSI to setup VLAN properties for */ static int ice_vsi_vlan_setup(struct ice_vsi *vsi) { int err; err = ice_set_vlan_offload_features(vsi, vsi->netdev->features); if (err) return err; err = ice_set_vlan_filtering_features(vsi, vsi->netdev->features); if (err) return err; return ice_vsi_add_vlan_zero(vsi); } /** * ice_vsi_cfg_lan - Setup the VSI lan related config * @vsi: the VSI being configured * * Return 0 on success and negative value on error */ int ice_vsi_cfg_lan(struct ice_vsi *vsi) { int err; if (vsi->netdev && vsi->type == ICE_VSI_PF) { ice_set_rx_mode(vsi->netdev); err = ice_vsi_vlan_setup(vsi); if (err) return err; } ice_vsi_cfg_dcb_rings(vsi); err = ice_vsi_cfg_lan_txqs(vsi); if (!err && ice_is_xdp_ena_vsi(vsi)) err = ice_vsi_cfg_xdp_txqs(vsi); if (!err) err = ice_vsi_cfg_rxqs(vsi); return err; } /* THEORY OF MODERATION: * The ice driver hardware works differently than the hardware that DIMLIB was * originally made for. ice hardware doesn't have packet count limits that * can trigger an interrupt, but it *does* have interrupt rate limit support, * which is hard-coded to a limit of 250,000 ints/second. * If not using dynamic moderation, the INTRL value can be modified * by ethtool rx-usecs-high. */ struct ice_dim { /* the throttle rate for interrupts, basically worst case delay before * an initial interrupt fires, value is stored in microseconds. */ u16 itr; }; /* Make a different profile for Rx that doesn't allow quite so aggressive * moderation at the high end (it maxes out at 126us or about 8k interrupts a * second. */ static const struct ice_dim rx_profile[] = { {2}, /* 500,000 ints/s, capped at 250K by INTRL */ {8}, /* 125,000 ints/s */ {16}, /* 62,500 ints/s */ {62}, /* 16,129 ints/s */ {126} /* 7,936 ints/s */ }; /* The transmit profile, which has the same sorts of values * as the previous struct */ static const struct ice_dim tx_profile[] = { {2}, /* 500,000 ints/s, capped at 250K by INTRL */ {8}, /* 125,000 ints/s */ {40}, /* 16,125 ints/s */ {128}, /* 7,812 ints/s */ {256} /* 3,906 ints/s */ }; static void ice_tx_dim_work(struct work_struct *work) { struct ice_ring_container *rc; struct dim *dim; u16 itr; dim = container_of(work, struct dim, work); rc = dim->priv; WARN_ON(dim->profile_ix >= ARRAY_SIZE(tx_profile)); /* look up the values in our local table */ itr = tx_profile[dim->profile_ix].itr; ice_trace(tx_dim_work, container_of(rc, struct ice_q_vector, tx), dim); ice_write_itr(rc, itr); dim->state = DIM_START_MEASURE; } static void ice_rx_dim_work(struct work_struct *work) { struct ice_ring_container *rc; struct dim *dim; u16 itr; dim = container_of(work, struct dim, work); rc = dim->priv; WARN_ON(dim->profile_ix >= ARRAY_SIZE(rx_profile)); /* look up the values in our local table */ itr = rx_profile[dim->profile_ix].itr; ice_trace(rx_dim_work, container_of(rc, struct ice_q_vector, rx), dim); ice_write_itr(rc, itr); dim->state = DIM_START_MEASURE; } #define ICE_DIM_DEFAULT_PROFILE_IX 1 /** * ice_init_moderation - set up interrupt moderation * @q_vector: the vector containing rings to be configured * * Set up interrupt moderation registers, with the intent to do the right thing * when called from reset or from probe, and whether or not dynamic moderation * is enabled or not. Take special care to write all the registers in both * dynamic moderation mode or not in order to make sure hardware is in a known * state. */ static void ice_init_moderation(struct ice_q_vector *q_vector) { struct ice_ring_container *rc; bool tx_dynamic, rx_dynamic; rc = &q_vector->tx; INIT_WORK(&rc->dim.work, ice_tx_dim_work); rc->dim.mode = DIM_CQ_PERIOD_MODE_START_FROM_EQE; rc->dim.profile_ix = ICE_DIM_DEFAULT_PROFILE_IX; rc->dim.priv = rc; tx_dynamic = ITR_IS_DYNAMIC(rc); /* set the initial TX ITR to match the above */ ice_write_itr(rc, tx_dynamic ? tx_profile[rc->dim.profile_ix].itr : rc->itr_setting); rc = &q_vector->rx; INIT_WORK(&rc->dim.work, ice_rx_dim_work); rc->dim.mode = DIM_CQ_PERIOD_MODE_START_FROM_EQE; rc->dim.profile_ix = ICE_DIM_DEFAULT_PROFILE_IX; rc->dim.priv = rc; rx_dynamic = ITR_IS_DYNAMIC(rc); /* set the initial RX ITR to match the above */ ice_write_itr(rc, rx_dynamic ? rx_profile[rc->dim.profile_ix].itr : rc->itr_setting); ice_set_q_vector_intrl(q_vector); } /** * ice_napi_enable_all - Enable NAPI for all q_vectors in the VSI * @vsi: the VSI being configured */ static void ice_napi_enable_all(struct ice_vsi *vsi) { int q_idx; if (!vsi->netdev) return; ice_for_each_q_vector(vsi, q_idx) { struct ice_q_vector *q_vector = vsi->q_vectors[q_idx]; ice_init_moderation(q_vector); if (q_vector->rx.rx_ring || q_vector->tx.tx_ring) napi_enable(&q_vector->napi); } } /** * ice_up_complete - Finish the last steps of bringing up a connection * @vsi: The VSI being configured * * Return 0 on success and negative value on error */ static int ice_up_complete(struct ice_vsi *vsi) { struct ice_pf *pf = vsi->back; int err; ice_vsi_cfg_msix(vsi); /* Enable only Rx rings, Tx rings were enabled by the FW when the * Tx queue group list was configured and the context bits were * programmed using ice_vsi_cfg_txqs */ err = ice_vsi_start_all_rx_rings(vsi); if (err) return err; clear_bit(ICE_VSI_DOWN, vsi->state); ice_napi_enable_all(vsi); ice_vsi_ena_irq(vsi); if (vsi->port_info && (vsi->port_info->phy.link_info.link_info & ICE_AQ_LINK_UP) && vsi->netdev && vsi->type == ICE_VSI_PF) { ice_print_link_msg(vsi, true); netif_tx_start_all_queues(vsi->netdev); netif_carrier_on(vsi->netdev); ice_ptp_link_change(pf, pf->hw.pf_id, true); } /* Perform an initial read of the statistics registers now to * set the baseline so counters are ready when interface is up */ ice_update_eth_stats(vsi); if (vsi->type == ICE_VSI_PF) ice_service_task_schedule(pf); return 0; } /** * ice_up - Bring the connection back up after being down * @vsi: VSI being configured */ int ice_up(struct ice_vsi *vsi) { int err; err = ice_vsi_cfg_lan(vsi); if (!err) err = ice_up_complete(vsi); return err; } /** * ice_fetch_u64_stats_per_ring - get packets and bytes stats per ring * @syncp: pointer to u64_stats_sync * @stats: stats that pkts and bytes count will be taken from * @pkts: packets stats counter * @bytes: bytes stats counter * * This function fetches stats from the ring considering the atomic operations * that needs to be performed to read u64 values in 32 bit machine. */ void ice_fetch_u64_stats_per_ring(struct u64_stats_sync *syncp, struct ice_q_stats stats, u64 *pkts, u64 *bytes) { unsigned int start; do { start = u64_stats_fetch_begin(syncp); *pkts = stats.pkts; *bytes = stats.bytes; } while (u64_stats_fetch_retry(syncp, start)); } /** * ice_update_vsi_tx_ring_stats - Update VSI Tx ring stats counters * @vsi: the VSI to be updated * @vsi_stats: the stats struct to be updated * @rings: rings to work on * @count: number of rings */ static void ice_update_vsi_tx_ring_stats(struct ice_vsi *vsi, struct rtnl_link_stats64 *vsi_stats, struct ice_tx_ring **rings, u16 count) { u16 i; for (i = 0; i < count; i++) { struct ice_tx_ring *ring; u64 pkts = 0, bytes = 0; ring = READ_ONCE(rings[i]); if (!ring || !ring->ring_stats) continue; ice_fetch_u64_stats_per_ring(&ring->ring_stats->syncp, ring->ring_stats->stats, &pkts, &bytes); vsi_stats->tx_packets += pkts; vsi_stats->tx_bytes += bytes; vsi->tx_restart += ring->ring_stats->tx_stats.restart_q; vsi->tx_busy += ring->ring_stats->tx_stats.tx_busy; vsi->tx_linearize += ring->ring_stats->tx_stats.tx_linearize; } } /** * ice_update_vsi_ring_stats - Update VSI stats counters * @vsi: the VSI to be updated */ static void ice_update_vsi_ring_stats(struct ice_vsi *vsi) { struct rtnl_link_stats64 *net_stats, *stats_prev; struct rtnl_link_stats64 *vsi_stats; u64 pkts, bytes; int i; vsi_stats = kzalloc(sizeof(*vsi_stats), GFP_ATOMIC); if (!vsi_stats) return; /* reset non-netdev (extended) stats */ vsi->tx_restart = 0; vsi->tx_busy = 0; vsi->tx_linearize = 0; vsi->rx_buf_failed = 0; vsi->rx_page_failed = 0; rcu_read_lock(); /* update Tx rings counters */ ice_update_vsi_tx_ring_stats(vsi, vsi_stats, vsi->tx_rings, vsi->num_txq); /* update Rx rings counters */ ice_for_each_rxq(vsi, i) { struct ice_rx_ring *ring = READ_ONCE(vsi->rx_rings[i]); struct ice_ring_stats *ring_stats; ring_stats = ring->ring_stats; ice_fetch_u64_stats_per_ring(&ring_stats->syncp, ring_stats->stats, &pkts, &bytes); vsi_stats->rx_packets += pkts; vsi_stats->rx_bytes += bytes; vsi->rx_buf_failed += ring_stats->rx_stats.alloc_buf_failed; vsi->rx_page_failed += ring_stats->rx_stats.alloc_page_failed; } /* update XDP Tx rings counters */ if (ice_is_xdp_ena_vsi(vsi)) ice_update_vsi_tx_ring_stats(vsi, vsi_stats, vsi->xdp_rings, vsi->num_xdp_txq); rcu_read_unlock(); net_stats = &vsi->net_stats; stats_prev = &vsi->net_stats_prev; /* clear prev counters after reset */ if (vsi_stats->tx_packets < stats_prev->tx_packets || vsi_stats->rx_packets < stats_prev->rx_packets) { stats_prev->tx_packets = 0; stats_prev->tx_bytes = 0; stats_prev->rx_packets = 0; stats_prev->rx_bytes = 0; } /* update netdev counters */ net_stats->tx_packets += vsi_stats->tx_packets - stats_prev->tx_packets; net_stats->tx_bytes += vsi_stats->tx_bytes - stats_prev->tx_bytes; net_stats->rx_packets += vsi_stats->rx_packets - stats_prev->rx_packets; net_stats->rx_bytes += vsi_stats->rx_bytes - stats_prev->rx_bytes; stats_prev->tx_packets = vsi_stats->tx_packets; stats_prev->tx_bytes = vsi_stats->tx_bytes; stats_prev->rx_packets = vsi_stats->rx_packets; stats_prev->rx_bytes = vsi_stats->rx_bytes; kfree(vsi_stats); } /** * ice_update_vsi_stats - Update VSI stats counters * @vsi: the VSI to be updated */ void ice_update_vsi_stats(struct ice_vsi *vsi) { struct rtnl_link_stats64 *cur_ns = &vsi->net_stats; struct ice_eth_stats *cur_es = &vsi->eth_stats; struct ice_pf *pf = vsi->back; if (test_bit(ICE_VSI_DOWN, vsi->state) || test_bit(ICE_CFG_BUSY, pf->state)) return; /* get stats as recorded by Tx/Rx rings */ ice_update_vsi_ring_stats(vsi); /* get VSI stats as recorded by the hardware */ ice_update_eth_stats(vsi); cur_ns->tx_errors = cur_es->tx_errors; cur_ns->rx_dropped = cur_es->rx_discards; cur_ns->tx_dropped = cur_es->tx_discards; cur_ns->multicast = cur_es->rx_multicast; /* update some more netdev stats if this is main VSI */ if (vsi->type == ICE_VSI_PF) { cur_ns->rx_crc_errors = pf->stats.crc_errors; cur_ns->rx_errors = pf->stats.crc_errors + pf->stats.illegal_bytes + pf->stats.rx_len_errors + pf->stats.rx_undersize + pf->hw_csum_rx_error + pf->stats.rx_jabber + pf->stats.rx_fragments + pf->stats.rx_oversize; cur_ns->rx_length_errors = pf->stats.rx_len_errors; /* record drops from the port level */ cur_ns->rx_missed_errors = pf->stats.eth.rx_discards; } } /** * ice_update_pf_stats - Update PF port stats counters * @pf: PF whose stats needs to be updated */ void ice_update_pf_stats(struct ice_pf *pf) { struct ice_hw_port_stats *prev_ps, *cur_ps; struct ice_hw *hw = &pf->hw; u16 fd_ctr_base; u8 port; port = hw->port_info->lport; prev_ps = &pf->stats_prev; cur_ps = &pf->stats; if (ice_is_reset_in_progress(pf->state)) pf->stat_prev_loaded = false; ice_stat_update40(hw, GLPRT_GORCL(port), pf->stat_prev_loaded, &prev_ps->eth.rx_bytes, &cur_ps->eth.rx_bytes); ice_stat_update40(hw, GLPRT_UPRCL(port), pf->stat_prev_loaded, &prev_ps->eth.rx_unicast, &cur_ps->eth.rx_unicast); ice_stat_update40(hw, GLPRT_MPRCL(port), pf->stat_prev_loaded, &prev_ps->eth.rx_multicast, &cur_ps->eth.rx_multicast); ice_stat_update40(hw, GLPRT_BPRCL(port), pf->stat_prev_loaded, &prev_ps->eth.rx_broadcast, &cur_ps->eth.rx_broadcast); ice_stat_update32(hw, PRTRPB_RDPC, pf->stat_prev_loaded, &prev_ps->eth.rx_discards, &cur_ps->eth.rx_discards); ice_stat_update40(hw, GLPRT_GOTCL(port), pf->stat_prev_loaded, &prev_ps->eth.tx_bytes, &cur_ps->eth.tx_bytes); ice_stat_update40(hw, GLPRT_UPTCL(port), pf->stat_prev_loaded, &prev_ps->eth.tx_unicast, &cur_ps->eth.tx_unicast); ice_stat_update40(hw, GLPRT_MPTCL(port), pf->stat_prev_loaded, &prev_ps->eth.tx_multicast, &cur_ps->eth.tx_multicast); ice_stat_update40(hw, GLPRT_BPTCL(port), pf->stat_prev_loaded, &prev_ps->eth.tx_broadcast, &cur_ps->eth.tx_broadcast); ice_stat_update32(hw, GLPRT_TDOLD(port), pf->stat_prev_loaded, &prev_ps->tx_dropped_link_down, &cur_ps->tx_dropped_link_down); ice_stat_update40(hw, GLPRT_PRC64L(port), pf->stat_prev_loaded, &prev_ps->rx_size_64, &cur_ps->rx_size_64); ice_stat_update40(hw, GLPRT_PRC127L(port), pf->stat_prev_loaded, &prev_ps->rx_size_127, &cur_ps->rx_size_127); ice_stat_update40(hw, GLPRT_PRC255L(port), pf->stat_prev_loaded, &prev_ps->rx_size_255, &cur_ps->rx_size_255); ice_stat_update40(hw, GLPRT_PRC511L(port), pf->stat_prev_loaded, &prev_ps->rx_size_511, &cur_ps->rx_size_511); ice_stat_update40(hw, GLPRT_PRC1023L(port), pf->stat_prev_loaded, &prev_ps->rx_size_1023, &cur_ps->rx_size_1023); ice_stat_update40(hw, GLPRT_PRC1522L(port), pf->stat_prev_loaded, &prev_ps->rx_size_1522, &cur_ps->rx_size_1522); ice_stat_update40(hw, GLPRT_PRC9522L(port), pf->stat_prev_loaded, &prev_ps->rx_size_big, &cur_ps->rx_size_big); ice_stat_update40(hw, GLPRT_PTC64L(port), pf->stat_prev_loaded, &prev_ps->tx_size_64, &cur_ps->tx_size_64); ice_stat_update40(hw, GLPRT_PTC127L(port), pf->stat_prev_loaded, &prev_ps->tx_size_127, &cur_ps->tx_size_127); ice_stat_update40(hw, GLPRT_PTC255L(port), pf->stat_prev_loaded, &prev_ps->tx_size_255, &cur_ps->tx_size_255); ice_stat_update40(hw, GLPRT_PTC511L(port), pf->stat_prev_loaded, &prev_ps->tx_size_511, &cur_ps->tx_size_511); ice_stat_update40(hw, GLPRT_PTC1023L(port), pf->stat_prev_loaded, &prev_ps->tx_size_1023, &cur_ps->tx_size_1023); ice_stat_update40(hw, GLPRT_PTC1522L(port), pf->stat_prev_loaded, &prev_ps->tx_size_1522, &cur_ps->tx_size_1522); ice_stat_update40(hw, GLPRT_PTC9522L(port), pf->stat_prev_loaded, &prev_ps->tx_size_big, &cur_ps->tx_size_big); fd_ctr_base = hw->fd_ctr_base; ice_stat_update40(hw, GLSTAT_FD_CNT0L(ICE_FD_SB_STAT_IDX(fd_ctr_base)), pf->stat_prev_loaded, &prev_ps->fd_sb_match, &cur_ps->fd_sb_match); ice_stat_update32(hw, GLPRT_LXONRXC(port), pf->stat_prev_loaded, &prev_ps->link_xon_rx, &cur_ps->link_xon_rx); ice_stat_update32(hw, GLPRT_LXOFFRXC(port), pf->stat_prev_loaded, &prev_ps->link_xoff_rx, &cur_ps->link_xoff_rx); ice_stat_update32(hw, GLPRT_LXONTXC(port), pf->stat_prev_loaded, &prev_ps->link_xon_tx, &cur_ps->link_xon_tx); ice_stat_update32(hw, GLPRT_LXOFFTXC(port), pf->stat_prev_loaded, &prev_ps->link_xoff_tx, &cur_ps->link_xoff_tx); ice_update_dcb_stats(pf); ice_stat_update32(hw, GLPRT_CRCERRS(port), pf->stat_prev_loaded, &prev_ps->crc_errors, &cur_ps->crc_errors); ice_stat_update32(hw, GLPRT_ILLERRC(port), pf->stat_prev_loaded, &prev_ps->illegal_bytes, &cur_ps->illegal_bytes); ice_stat_update32(hw, GLPRT_MLFC(port), pf->stat_prev_loaded, &prev_ps->mac_local_faults, &cur_ps->mac_local_faults); ice_stat_update32(hw, GLPRT_MRFC(port), pf->stat_prev_loaded, &prev_ps->mac_remote_faults, &cur_ps->mac_remote_faults); ice_stat_update32(hw, GLPRT_RLEC(port), pf->stat_prev_loaded, &prev_ps->rx_len_errors, &cur_ps->rx_len_errors); ice_stat_update32(hw, GLPRT_RUC(port), pf->stat_prev_loaded, &prev_ps->rx_undersize, &cur_ps->rx_undersize); ice_stat_update32(hw, GLPRT_RFC(port), pf->stat_prev_loaded, &prev_ps->rx_fragments, &cur_ps->rx_fragments); ice_stat_update32(hw, GLPRT_ROC(port), pf->stat_prev_loaded, &prev_ps->rx_oversize, &cur_ps->rx_oversize); ice_stat_update32(hw, GLPRT_RJC(port), pf->stat_prev_loaded, &prev_ps->rx_jabber, &cur_ps->rx_jabber); cur_ps->fd_sb_status = test_bit(ICE_FLAG_FD_ENA, pf->flags) ? 1 : 0; pf->stat_prev_loaded = true; } /** * ice_get_stats64 - get statistics for network device structure * @netdev: network interface device structure * @stats: main device statistics structure */ static void ice_get_stats64(struct net_device *netdev, struct rtnl_link_stats64 *stats) { struct ice_netdev_priv *np = netdev_priv(netdev); struct rtnl_link_stats64 *vsi_stats; struct ice_vsi *vsi = np->vsi; vsi_stats = &vsi->net_stats; if (!vsi->num_txq || !vsi->num_rxq) return; /* netdev packet/byte stats come from ring counter. These are obtained * by summing up ring counters (done by ice_update_vsi_ring_stats). * But, only call the update routine and read the registers if VSI is * not down. */ if (!test_bit(ICE_VSI_DOWN, vsi->state)) ice_update_vsi_ring_stats(vsi); stats->tx_packets = vsi_stats->tx_packets; stats->tx_bytes = vsi_stats->tx_bytes; stats->rx_packets = vsi_stats->rx_packets; stats->rx_bytes = vsi_stats->rx_bytes; /* The rest of the stats can be read from the hardware but instead we * just return values that the watchdog task has already obtained from * the hardware. */ stats->multicast = vsi_stats->multicast; stats->tx_errors = vsi_stats->tx_errors; stats->tx_dropped = vsi_stats->tx_dropped; stats->rx_errors = vsi_stats->rx_errors; stats->rx_dropped = vsi_stats->rx_dropped; stats->rx_crc_errors = vsi_stats->rx_crc_errors; stats->rx_length_errors = vsi_stats->rx_length_errors; } /** * ice_napi_disable_all - Disable NAPI for all q_vectors in the VSI * @vsi: VSI having NAPI disabled */ static void ice_napi_disable_all(struct ice_vsi *vsi) { int q_idx; if (!vsi->netdev) return; ice_for_each_q_vector(vsi, q_idx) { struct ice_q_vector *q_vector = vsi->q_vectors[q_idx]; if (q_vector->rx.rx_ring || q_vector->tx.tx_ring) napi_disable(&q_vector->napi); cancel_work_sync(&q_vector->tx.dim.work); cancel_work_sync(&q_vector->rx.dim.work); } } /** * ice_down - Shutdown the connection * @vsi: The VSI being stopped * * Caller of this function is expected to set the vsi->state ICE_DOWN bit */ int ice_down(struct ice_vsi *vsi) { int i, tx_err, rx_err, vlan_err = 0; WARN_ON(!test_bit(ICE_VSI_DOWN, vsi->state)); if (vsi->netdev && vsi->type == ICE_VSI_PF) { vlan_err = ice_vsi_del_vlan_zero(vsi); ice_ptp_link_change(vsi->back, vsi->back->hw.pf_id, false); netif_carrier_off(vsi->netdev); netif_tx_disable(vsi->netdev); } else if (vsi->type == ICE_VSI_SWITCHDEV_CTRL) { ice_eswitch_stop_all_tx_queues(vsi->back); } ice_vsi_dis_irq(vsi); tx_err = ice_vsi_stop_lan_tx_rings(vsi, ICE_NO_RESET, 0); if (tx_err) netdev_err(vsi->netdev, "Failed stop Tx rings, VSI %d error %d\n", vsi->vsi_num, tx_err); if (!tx_err && ice_is_xdp_ena_vsi(vsi)) { tx_err = ice_vsi_stop_xdp_tx_rings(vsi); if (tx_err) netdev_err(vsi->netdev, "Failed stop XDP rings, VSI %d error %d\n", vsi->vsi_num, tx_err); } rx_err = ice_vsi_stop_all_rx_rings(vsi); if (rx_err) netdev_err(vsi->netdev, "Failed stop Rx rings, VSI %d error %d\n", vsi->vsi_num, rx_err); ice_napi_disable_all(vsi); ice_for_each_txq(vsi, i) ice_clean_tx_ring(vsi->tx_rings[i]); if (ice_is_xdp_ena_vsi(vsi)) ice_for_each_xdp_txq(vsi, i) ice_clean_tx_ring(vsi->xdp_rings[i]); ice_for_each_rxq(vsi, i) ice_clean_rx_ring(vsi->rx_rings[i]); if (tx_err || rx_err || vlan_err) { netdev_err(vsi->netdev, "Failed to close VSI 0x%04X on switch 0x%04X\n", vsi->vsi_num, vsi->vsw->sw_id); return -EIO; } return 0; } /** * ice_down_up - shutdown the VSI connection and bring it up * @vsi: the VSI to be reconnected */ int ice_down_up(struct ice_vsi *vsi) { int ret; /* if DOWN already set, nothing to do */ if (test_and_set_bit(ICE_VSI_DOWN, vsi->state)) return 0; ret = ice_down(vsi); if (ret) return ret; ret = ice_up(vsi); if (ret) { netdev_err(vsi->netdev, "reallocating resources failed during netdev features change, may need to reload driver\n"); return ret; } return 0; } /** * ice_vsi_setup_tx_rings - Allocate VSI Tx queue resources * @vsi: VSI having resources allocated * * Return 0 on success, negative on failure */ int ice_vsi_setup_tx_rings(struct ice_vsi *vsi) { int i, err = 0; if (!vsi->num_txq) { dev_err(ice_pf_to_dev(vsi->back), "VSI %d has 0 Tx queues\n", vsi->vsi_num); return -EINVAL; } ice_for_each_txq(vsi, i) { struct ice_tx_ring *ring = vsi->tx_rings[i]; if (!ring) return -EINVAL; if (vsi->netdev) ring->netdev = vsi->netdev; err = ice_setup_tx_ring(ring); if (err) break; } return err; } /** * ice_vsi_setup_rx_rings - Allocate VSI Rx queue resources * @vsi: VSI having resources allocated * * Return 0 on success, negative on failure */ int ice_vsi_setup_rx_rings(struct ice_vsi *vsi) { int i, err = 0; if (!vsi->num_rxq) { dev_err(ice_pf_to_dev(vsi->back), "VSI %d has 0 Rx queues\n", vsi->vsi_num); return -EINVAL; } ice_for_each_rxq(vsi, i) { struct ice_rx_ring *ring = vsi->rx_rings[i]; if (!ring) return -EINVAL; if (vsi->netdev) ring->netdev = vsi->netdev; err = ice_setup_rx_ring(ring); if (err) break; } return err; } /** * ice_vsi_open_ctrl - open control VSI for use * @vsi: the VSI to open * * Initialization of the Control VSI * * Returns 0 on success, negative value on error */ int ice_vsi_open_ctrl(struct ice_vsi *vsi) { char int_name[ICE_INT_NAME_STR_LEN]; struct ice_pf *pf = vsi->back; struct device *dev; int err; dev = ice_pf_to_dev(pf); /* allocate descriptors */ err = ice_vsi_setup_tx_rings(vsi); if (err) goto err_setup_tx; err = ice_vsi_setup_rx_rings(vsi); if (err) goto err_setup_rx; err = ice_vsi_cfg_lan(vsi); if (err) goto err_setup_rx; snprintf(int_name, sizeof(int_name) - 1, "%s-%s:ctrl", dev_driver_string(dev), dev_name(dev)); err = ice_vsi_req_irq_msix(vsi, int_name); if (err) goto err_setup_rx; ice_vsi_cfg_msix(vsi); err = ice_vsi_start_all_rx_rings(vsi); if (err) goto err_up_complete; clear_bit(ICE_VSI_DOWN, vsi->state); ice_vsi_ena_irq(vsi); return 0; err_up_complete: ice_down(vsi); err_setup_rx: ice_vsi_free_rx_rings(vsi); err_setup_tx: ice_vsi_free_tx_rings(vsi); return err; } /** * ice_vsi_open - Called when a network interface is made active * @vsi: the VSI to open * * Initialization of the VSI * * Returns 0 on success, negative value on error */ int ice_vsi_open(struct ice_vsi *vsi) { char int_name[ICE_INT_NAME_STR_LEN]; struct ice_pf *pf = vsi->back; int err; /* allocate descriptors */ err = ice_vsi_setup_tx_rings(vsi); if (err) goto err_setup_tx; err = ice_vsi_setup_rx_rings(vsi); if (err) goto err_setup_rx; err = ice_vsi_cfg_lan(vsi); if (err) goto err_setup_rx; snprintf(int_name, sizeof(int_name) - 1, "%s-%s", dev_driver_string(ice_pf_to_dev(pf)), vsi->netdev->name); err = ice_vsi_req_irq_msix(vsi, int_name); if (err) goto err_setup_rx; ice_vsi_cfg_netdev_tc(vsi, vsi->tc_cfg.ena_tc); if (vsi->type == ICE_VSI_PF) { /* Notify the stack of the actual queue counts. */ err = netif_set_real_num_tx_queues(vsi->netdev, vsi->num_txq); if (err) goto err_set_qs; err = netif_set_real_num_rx_queues(vsi->netdev, vsi->num_rxq); if (err) goto err_set_qs; } err = ice_up_complete(vsi); if (err) goto err_up_complete; return 0; err_up_complete: ice_down(vsi); err_set_qs: ice_vsi_free_irq(vsi); err_setup_rx: ice_vsi_free_rx_rings(vsi); err_setup_tx: ice_vsi_free_tx_rings(vsi); return err; } /** * ice_vsi_release_all - Delete all VSIs * @pf: PF from which all VSIs are being removed */ static void ice_vsi_release_all(struct ice_pf *pf) { int err, i; if (!pf->vsi) return; ice_for_each_vsi(pf, i) { if (!pf->vsi[i]) continue; if (pf->vsi[i]->type == ICE_VSI_CHNL) continue; err = ice_vsi_release(pf->vsi[i]); if (err) dev_dbg(ice_pf_to_dev(pf), "Failed to release pf->vsi[%d], err %d, vsi_num = %d\n", i, err, pf->vsi[i]->vsi_num); } } /** * ice_vsi_rebuild_by_type - Rebuild VSI of a given type * @pf: pointer to the PF instance * @type: VSI type to rebuild * * Iterates through the pf->vsi array and rebuilds VSIs of the requested type */ static int ice_vsi_rebuild_by_type(struct ice_pf *pf, enum ice_vsi_type type) { struct device *dev = ice_pf_to_dev(pf); int i, err; ice_for_each_vsi(pf, i) { struct ice_vsi *vsi = pf->vsi[i]; if (!vsi || vsi->type != type) continue; /* rebuild the VSI */ err = ice_vsi_rebuild(vsi, ICE_VSI_FLAG_INIT); if (err) { dev_err(dev, "rebuild VSI failed, err %d, VSI index %d, type %s\n", err, vsi->idx, ice_vsi_type_str(type)); return err; } /* replay filters for the VSI */ err = ice_replay_vsi(&pf->hw, vsi->idx); if (err) { dev_err(dev, "replay VSI failed, error %d, VSI index %d, type %s\n", err, vsi->idx, ice_vsi_type_str(type)); return err; } /* Re-map HW VSI number, using VSI handle that has been * previously validated in ice_replay_vsi() call above */ vsi->vsi_num = ice_get_hw_vsi_num(&pf->hw, vsi->idx); /* enable the VSI */ err = ice_ena_vsi(vsi, false); if (err) { dev_err(dev, "enable VSI failed, err %d, VSI index %d, type %s\n", err, vsi->idx, ice_vsi_type_str(type)); return err; } dev_info(dev, "VSI rebuilt. VSI index %d, type %s\n", vsi->idx, ice_vsi_type_str(type)); } return 0; } /** * ice_update_pf_netdev_link - Update PF netdev link status * @pf: pointer to the PF instance */ static void ice_update_pf_netdev_link(struct ice_pf *pf) { bool link_up; int i; ice_for_each_vsi(pf, i) { struct ice_vsi *vsi = pf->vsi[i]; if (!vsi || vsi->type != ICE_VSI_PF) return; ice_get_link_status(pf->vsi[i]->port_info, &link_up); if (link_up) { netif_carrier_on(pf->vsi[i]->netdev); netif_tx_wake_all_queues(pf->vsi[i]->netdev); } else { netif_carrier_off(pf->vsi[i]->netdev); netif_tx_stop_all_queues(pf->vsi[i]->netdev); } } } /** * ice_rebuild - rebuild after reset * @pf: PF to rebuild * @reset_type: type of reset * * Do not rebuild VF VSI in this flow because that is already handled via * ice_reset_all_vfs(). This is because requirements for resetting a VF after a * PFR/CORER/GLOBER/etc. are different than the normal flow. Also, we don't want * to reset/rebuild all the VF VSI twice. */ static void ice_rebuild(struct ice_pf *pf, enum ice_reset_req reset_type) { struct device *dev = ice_pf_to_dev(pf); struct ice_hw *hw = &pf->hw; bool dvm; int err; if (test_bit(ICE_DOWN, pf->state)) goto clear_recovery; dev_dbg(dev, "rebuilding PF after reset_type=%d\n", reset_type); #define ICE_EMP_RESET_SLEEP_MS 5000 if (reset_type == ICE_RESET_EMPR) { /* If an EMP reset has occurred, any previously pending flash * update will have completed. We no longer know whether or * not the NVM update EMP reset is restricted. */ pf->fw_emp_reset_disabled = false; msleep(ICE_EMP_RESET_SLEEP_MS); } err = ice_init_all_ctrlq(hw); if (err) { dev_err(dev, "control queues init failed %d\n", err); goto err_init_ctrlq; } /* if DDP was previously loaded successfully */ if (!ice_is_safe_mode(pf)) { /* reload the SW DB of filter tables */ if (reset_type == ICE_RESET_PFR) ice_fill_blk_tbls(hw); else /* Reload DDP Package after CORER/GLOBR reset */ ice_load_pkg(NULL, pf); } err = ice_clear_pf_cfg(hw); if (err) { dev_err(dev, "clear PF configuration failed %d\n", err); goto err_init_ctrlq; } ice_clear_pxe_mode(hw); err = ice_init_nvm(hw); if (err) { dev_err(dev, "ice_init_nvm failed %d\n", err); goto err_init_ctrlq; } err = ice_get_caps(hw); if (err) { dev_err(dev, "ice_get_caps failed %d\n", err); goto err_init_ctrlq; } err = ice_aq_set_mac_cfg(hw, ICE_AQ_SET_MAC_FRAME_SIZE_MAX, NULL); if (err) { dev_err(dev, "set_mac_cfg failed %d\n", err); goto err_init_ctrlq; } dvm = ice_is_dvm_ena(hw); err = ice_aq_set_port_params(pf->hw.port_info, dvm, NULL); if (err) goto err_init_ctrlq; err = ice_sched_init_port(hw->port_info); if (err) goto err_sched_init_port; /* start misc vector */ err = ice_req_irq_msix_misc(pf); if (err) { dev_err(dev, "misc vector setup failed: %d\n", err); goto err_sched_init_port; } if (test_bit(ICE_FLAG_FD_ENA, pf->flags)) { wr32(hw, PFQF_FD_ENA, PFQF_FD_ENA_FD_ENA_M); if (!rd32(hw, PFQF_FD_SIZE)) { u16 unused, guar, b_effort; guar = hw->func_caps.fd_fltr_guar; b_effort = hw->func_caps.fd_fltr_best_effort; /* force guaranteed filter pool for PF */ ice_alloc_fd_guar_item(hw, &unused, guar); /* force shared filter pool for PF */ ice_alloc_fd_shrd_item(hw, &unused, b_effort); } } if (test_bit(ICE_FLAG_DCB_ENA, pf->flags)) ice_dcb_rebuild(pf); /* If the PF previously had enabled PTP, PTP init needs to happen before * the VSI rebuild. If not, this causes the PTP link status events to * fail. */ if (test_bit(ICE_FLAG_PTP_SUPPORTED, pf->flags)) ice_ptp_reset(pf); if (ice_is_feature_supported(pf, ICE_F_GNSS)) ice_gnss_init(pf); /* rebuild PF VSI */ err = ice_vsi_rebuild_by_type(pf, ICE_VSI_PF); if (err) { dev_err(dev, "PF VSI rebuild failed: %d\n", err); goto err_vsi_rebuild; } /* configure PTP timestamping after VSI rebuild */ if (test_bit(ICE_FLAG_PTP_SUPPORTED, pf->flags)) ice_ptp_cfg_timestamp(pf, false); err = ice_vsi_rebuild_by_type(pf, ICE_VSI_SWITCHDEV_CTRL); if (err) { dev_err(dev, "Switchdev CTRL VSI rebuild failed: %d\n", err); goto err_vsi_rebuild; } if (reset_type == ICE_RESET_PFR) { err = ice_rebuild_channels(pf); if (err) { dev_err(dev, "failed to rebuild and replay ADQ VSIs, err %d\n", err); goto err_vsi_rebuild; } } /* If Flow Director is active */ if (test_bit(ICE_FLAG_FD_ENA, pf->flags)) { err = ice_vsi_rebuild_by_type(pf, ICE_VSI_CTRL); if (err) { dev_err(dev, "control VSI rebuild failed: %d\n", err); goto err_vsi_rebuild; } /* replay HW Flow Director recipes */ if (hw->fdir_prof) ice_fdir_replay_flows(hw); /* replay Flow Director filters */ ice_fdir_replay_fltrs(pf); ice_rebuild_arfs(pf); } ice_update_pf_netdev_link(pf); /* tell the firmware we are up */ err = ice_send_version(pf); if (err) { dev_err(dev, "Rebuild failed due to error sending driver version: %d\n", err); goto err_vsi_rebuild; } ice_replay_post(hw); /* if we get here, reset flow is successful */ clear_bit(ICE_RESET_FAILED, pf->state); ice_plug_aux_dev(pf); if (ice_is_feature_supported(pf, ICE_F_SRIOV_LAG)) ice_lag_rebuild(pf); return; err_vsi_rebuild: err_sched_init_port: ice_sched_cleanup_all(hw); err_init_ctrlq: ice_shutdown_all_ctrlq(hw); set_bit(ICE_RESET_FAILED, pf->state); clear_recovery: /* set this bit in PF state to control service task scheduling */ set_bit(ICE_NEEDS_RESTART, pf->state); dev_err(dev, "Rebuild failed, unload and reload driver\n"); } /** * ice_change_mtu - NDO callback to change the MTU * @netdev: network interface device structure * @new_mtu: new value for maximum frame size * * Returns 0 on success, negative on failure */ static int ice_change_mtu(struct net_device *netdev, int new_mtu) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; struct ice_pf *pf = vsi->back; struct bpf_prog *prog; u8 count = 0; int err = 0; if (new_mtu == (int)netdev->mtu) { netdev_warn(netdev, "MTU is already %u\n", netdev->mtu); return 0; } prog = vsi->xdp_prog; if (prog && !prog->aux->xdp_has_frags) { int frame_size = ice_max_xdp_frame_size(vsi); if (new_mtu + ICE_ETH_PKT_HDR_PAD > frame_size) { netdev_err(netdev, "max MTU for XDP usage is %d\n", frame_size - ICE_ETH_PKT_HDR_PAD); return -EINVAL; } } else if (test_bit(ICE_FLAG_LEGACY_RX, pf->flags)) { if (new_mtu + ICE_ETH_PKT_HDR_PAD > ICE_MAX_FRAME_LEGACY_RX) { netdev_err(netdev, "Too big MTU for legacy-rx; Max is %d\n", ICE_MAX_FRAME_LEGACY_RX - ICE_ETH_PKT_HDR_PAD); return -EINVAL; } } /* if a reset is in progress, wait for some time for it to complete */ do { if (ice_is_reset_in_progress(pf->state)) { count++; usleep_range(1000, 2000); } else { break; } } while (count < 100); if (count == 100) { netdev_err(netdev, "can't change MTU. Device is busy\n"); return -EBUSY; } netdev->mtu = (unsigned int)new_mtu; err = ice_down_up(vsi); if (err) return err; netdev_dbg(netdev, "changed MTU to %d\n", new_mtu); set_bit(ICE_FLAG_MTU_CHANGED, pf->flags); return err; } /** * ice_eth_ioctl - Access the hwtstamp interface * @netdev: network interface device structure * @ifr: interface request data * @cmd: ioctl command */ static int ice_eth_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_pf *pf = np->vsi->back; switch (cmd) { case SIOCGHWTSTAMP: return ice_ptp_get_ts_config(pf, ifr); case SIOCSHWTSTAMP: return ice_ptp_set_ts_config(pf, ifr); default: return -EOPNOTSUPP; } } /** * ice_aq_str - convert AQ err code to a string * @aq_err: the AQ error code to convert */ const char *ice_aq_str(enum ice_aq_err aq_err) { switch (aq_err) { case ICE_AQ_RC_OK: return "OK"; case ICE_AQ_RC_EPERM: return "ICE_AQ_RC_EPERM"; case ICE_AQ_RC_ENOENT: return "ICE_AQ_RC_ENOENT"; case ICE_AQ_RC_ENOMEM: return "ICE_AQ_RC_ENOMEM"; case ICE_AQ_RC_EBUSY: return "ICE_AQ_RC_EBUSY"; case ICE_AQ_RC_EEXIST: return "ICE_AQ_RC_EEXIST"; case ICE_AQ_RC_EINVAL: return "ICE_AQ_RC_EINVAL"; case ICE_AQ_RC_ENOSPC: return "ICE_AQ_RC_ENOSPC"; case ICE_AQ_RC_ENOSYS: return "ICE_AQ_RC_ENOSYS"; case ICE_AQ_RC_EMODE: return "ICE_AQ_RC_EMODE"; case ICE_AQ_RC_ENOSEC: return "ICE_AQ_RC_ENOSEC"; case ICE_AQ_RC_EBADSIG: return "ICE_AQ_RC_EBADSIG"; case ICE_AQ_RC_ESVN: return "ICE_AQ_RC_ESVN"; case ICE_AQ_RC_EBADMAN: return "ICE_AQ_RC_EBADMAN"; case ICE_AQ_RC_EBADBUF: return "ICE_AQ_RC_EBADBUF"; } return "ICE_AQ_RC_UNKNOWN"; } /** * ice_set_rss_lut - Set RSS LUT * @vsi: Pointer to VSI structure * @lut: Lookup table * @lut_size: Lookup table size * * Returns 0 on success, negative on failure */ int ice_set_rss_lut(struct ice_vsi *vsi, u8 *lut, u16 lut_size) { struct ice_aq_get_set_rss_lut_params params = {}; struct ice_hw *hw = &vsi->back->hw; int status; if (!lut) return -EINVAL; params.vsi_handle = vsi->idx; params.lut_size = lut_size; params.lut_type = vsi->rss_lut_type; params.lut = lut; status = ice_aq_set_rss_lut(hw, &params); if (status) dev_err(ice_pf_to_dev(vsi->back), "Cannot set RSS lut, err %d aq_err %s\n", status, ice_aq_str(hw->adminq.sq_last_status)); return status; } /** * ice_set_rss_key - Set RSS key * @vsi: Pointer to the VSI structure * @seed: RSS hash seed * * Returns 0 on success, negative on failure */ int ice_set_rss_key(struct ice_vsi *vsi, u8 *seed) { struct ice_hw *hw = &vsi->back->hw; int status; if (!seed) return -EINVAL; status = ice_aq_set_rss_key(hw, vsi->idx, (struct ice_aqc_get_set_rss_keys *)seed); if (status) dev_err(ice_pf_to_dev(vsi->back), "Cannot set RSS key, err %d aq_err %s\n", status, ice_aq_str(hw->adminq.sq_last_status)); return status; } /** * ice_get_rss_lut - Get RSS LUT * @vsi: Pointer to VSI structure * @lut: Buffer to store the lookup table entries * @lut_size: Size of buffer to store the lookup table entries * * Returns 0 on success, negative on failure */ int ice_get_rss_lut(struct ice_vsi *vsi, u8 *lut, u16 lut_size) { struct ice_aq_get_set_rss_lut_params params = {}; struct ice_hw *hw = &vsi->back->hw; int status; if (!lut) return -EINVAL; params.vsi_handle = vsi->idx; params.lut_size = lut_size; params.lut_type = vsi->rss_lut_type; params.lut = lut; status = ice_aq_get_rss_lut(hw, &params); if (status) dev_err(ice_pf_to_dev(vsi->back), "Cannot get RSS lut, err %d aq_err %s\n", status, ice_aq_str(hw->adminq.sq_last_status)); return status; } /** * ice_get_rss_key - Get RSS key * @vsi: Pointer to VSI structure * @seed: Buffer to store the key in * * Returns 0 on success, negative on failure */ int ice_get_rss_key(struct ice_vsi *vsi, u8 *seed) { struct ice_hw *hw = &vsi->back->hw; int status; if (!seed) return -EINVAL; status = ice_aq_get_rss_key(hw, vsi->idx, (struct ice_aqc_get_set_rss_keys *)seed); if (status) dev_err(ice_pf_to_dev(vsi->back), "Cannot get RSS key, err %d aq_err %s\n", status, ice_aq_str(hw->adminq.sq_last_status)); return status; } /** * ice_bridge_getlink - Get the hardware bridge mode * @skb: skb buff * @pid: process ID * @seq: RTNL message seq * @dev: the netdev being configured * @filter_mask: filter mask passed in * @nlflags: netlink flags passed in * * Return the bridge mode (VEB/VEPA) */ static int ice_bridge_getlink(struct sk_buff *skb, u32 pid, u32 seq, struct net_device *dev, u32 filter_mask, int nlflags) { struct ice_netdev_priv *np = netdev_priv(dev); struct ice_vsi *vsi = np->vsi; struct ice_pf *pf = vsi->back; u16 bmode; bmode = pf->first_sw->bridge_mode; return ndo_dflt_bridge_getlink(skb, pid, seq, dev, bmode, 0, 0, nlflags, filter_mask, NULL); } /** * ice_vsi_update_bridge_mode - Update VSI for switching bridge mode (VEB/VEPA) * @vsi: Pointer to VSI structure * @bmode: Hardware bridge mode (VEB/VEPA) * * Returns 0 on success, negative on failure */ static int ice_vsi_update_bridge_mode(struct ice_vsi *vsi, u16 bmode) { struct ice_aqc_vsi_props *vsi_props; struct ice_hw *hw = &vsi->back->hw; struct ice_vsi_ctx *ctxt; int ret; vsi_props = &vsi->info; ctxt = kzalloc(sizeof(*ctxt), GFP_KERNEL); if (!ctxt) return -ENOMEM; ctxt->info = vsi->info; if (bmode == BRIDGE_MODE_VEB) /* change from VEPA to VEB mode */ ctxt->info.sw_flags |= ICE_AQ_VSI_SW_FLAG_ALLOW_LB; else /* change from VEB to VEPA mode */ ctxt->info.sw_flags &= ~ICE_AQ_VSI_SW_FLAG_ALLOW_LB; ctxt->info.valid_sections = cpu_to_le16(ICE_AQ_VSI_PROP_SW_VALID); ret = ice_update_vsi(hw, vsi->idx, ctxt, NULL); if (ret) { dev_err(ice_pf_to_dev(vsi->back), "update VSI for bridge mode failed, bmode = %d err %d aq_err %s\n", bmode, ret, ice_aq_str(hw->adminq.sq_last_status)); goto out; } /* Update sw flags for book keeping */ vsi_props->sw_flags = ctxt->info.sw_flags; out: kfree(ctxt); return ret; } /** * ice_bridge_setlink - Set the hardware bridge mode * @dev: the netdev being configured * @nlh: RTNL message * @flags: bridge setlink flags * @extack: netlink extended ack * * Sets the bridge mode (VEB/VEPA) of the switch to which the netdev (VSI) is * hooked up to. Iterates through the PF VSI list and sets the loopback mode (if * not already set for all VSIs connected to this switch. And also update the * unicast switch filter rules for the corresponding switch of the netdev. */ static int ice_bridge_setlink(struct net_device *dev, struct nlmsghdr *nlh, u16 __always_unused flags, struct netlink_ext_ack __always_unused *extack) { struct ice_netdev_priv *np = netdev_priv(dev); struct ice_pf *pf = np->vsi->back; struct nlattr *attr, *br_spec; struct ice_hw *hw = &pf->hw; struct ice_sw *pf_sw; int rem, v, err = 0; pf_sw = pf->first_sw; /* find the attribute in the netlink message */ br_spec = nlmsg_find_attr(nlh, sizeof(struct ifinfomsg), IFLA_AF_SPEC); nla_for_each_nested(attr, br_spec, rem) { __u16 mode; if (nla_type(attr) != IFLA_BRIDGE_MODE) continue; mode = nla_get_u16(attr); if (mode != BRIDGE_MODE_VEPA && mode != BRIDGE_MODE_VEB) return -EINVAL; /* Continue if bridge mode is not being flipped */ if (mode == pf_sw->bridge_mode) continue; /* Iterates through the PF VSI list and update the loopback * mode of the VSI */ ice_for_each_vsi(pf, v) { if (!pf->vsi[v]) continue; err = ice_vsi_update_bridge_mode(pf->vsi[v], mode); if (err) return err; } hw->evb_veb = (mode == BRIDGE_MODE_VEB); /* Update the unicast switch filter rules for the corresponding * switch of the netdev */ err = ice_update_sw_rule_bridge_mode(hw); if (err) { netdev_err(dev, "switch rule update failed, mode = %d err %d aq_err %s\n", mode, err, ice_aq_str(hw->adminq.sq_last_status)); /* revert hw->evb_veb */ hw->evb_veb = (pf_sw->bridge_mode == BRIDGE_MODE_VEB); return err; } pf_sw->bridge_mode = mode; } return 0; } /** * ice_tx_timeout - Respond to a Tx Hang * @netdev: network interface device structure * @txqueue: Tx queue */ static void ice_tx_timeout(struct net_device *netdev, unsigned int txqueue) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_tx_ring *tx_ring = NULL; struct ice_vsi *vsi = np->vsi; struct ice_pf *pf = vsi->back; u32 i; pf->tx_timeout_count++; /* Check if PFC is enabled for the TC to which the queue belongs * to. If yes then Tx timeout is not caused by a hung queue, no * need to reset and rebuild */ if (ice_is_pfc_causing_hung_q(pf, txqueue)) { dev_info(ice_pf_to_dev(pf), "Fake Tx hang detected on queue %u, timeout caused by PFC storm\n", txqueue); return; } /* now that we have an index, find the tx_ring struct */ ice_for_each_txq(vsi, i) if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc) if (txqueue == vsi->tx_rings[i]->q_index) { tx_ring = vsi->tx_rings[i]; break; } /* Reset recovery level if enough time has elapsed after last timeout. * Also ensure no new reset action happens before next timeout period. */ if (time_after(jiffies, (pf->tx_timeout_last_recovery + HZ * 20))) pf->tx_timeout_recovery_level = 1; else if (time_before(jiffies, (pf->tx_timeout_last_recovery + netdev->watchdog_timeo))) return; if (tx_ring) { struct ice_hw *hw = &pf->hw; u32 head, val = 0; head = (rd32(hw, QTX_COMM_HEAD(vsi->txq_map[txqueue])) & QTX_COMM_HEAD_HEAD_M) >> QTX_COMM_HEAD_HEAD_S; /* Read interrupt register */ val = rd32(hw, GLINT_DYN_CTL(tx_ring->q_vector->reg_idx)); netdev_info(netdev, "tx_timeout: VSI_num: %d, Q %u, NTC: 0x%x, HW_HEAD: 0x%x, NTU: 0x%x, INT: 0x%x\n", vsi->vsi_num, txqueue, tx_ring->next_to_clean, head, tx_ring->next_to_use, val); } pf->tx_timeout_last_recovery = jiffies; netdev_info(netdev, "tx_timeout recovery level %d, txqueue %u\n", pf->tx_timeout_recovery_level, txqueue); switch (pf->tx_timeout_recovery_level) { case 1: set_bit(ICE_PFR_REQ, pf->state); break; case 2: set_bit(ICE_CORER_REQ, pf->state); break; case 3: set_bit(ICE_GLOBR_REQ, pf->state); break; default: netdev_err(netdev, "tx_timeout recovery unsuccessful, device is in unrecoverable state.\n"); set_bit(ICE_DOWN, pf->state); set_bit(ICE_VSI_NEEDS_RESTART, vsi->state); set_bit(ICE_SERVICE_DIS, pf->state); break; } ice_service_task_schedule(pf); pf->tx_timeout_recovery_level++; } /** * ice_setup_tc_cls_flower - flower classifier offloads * @np: net device to configure * @filter_dev: device on which filter is added * @cls_flower: offload data */ static int ice_setup_tc_cls_flower(struct ice_netdev_priv *np, struct net_device *filter_dev, struct flow_cls_offload *cls_flower) { struct ice_vsi *vsi = np->vsi; if (cls_flower->common.chain_index) return -EOPNOTSUPP; switch (cls_flower->command) { case FLOW_CLS_REPLACE: return ice_add_cls_flower(filter_dev, vsi, cls_flower); case FLOW_CLS_DESTROY: return ice_del_cls_flower(vsi, cls_flower); default: return -EINVAL; } } /** * ice_setup_tc_block_cb - callback handler registered for TC block * @type: TC SETUP type * @type_data: TC flower offload data that contains user input * @cb_priv: netdev private data */ static int ice_setup_tc_block_cb(enum tc_setup_type type, void *type_data, void *cb_priv) { struct ice_netdev_priv *np = cb_priv; switch (type) { case TC_SETUP_CLSFLOWER: return ice_setup_tc_cls_flower(np, np->vsi->netdev, type_data); default: return -EOPNOTSUPP; } } /** * ice_validate_mqprio_qopt - Validate TCF input parameters * @vsi: Pointer to VSI * @mqprio_qopt: input parameters for mqprio queue configuration * * This function validates MQPRIO params, such as qcount (power of 2 wherever * needed), and make sure user doesn't specify qcount and BW rate limit * for TCs, which are more than "num_tc" */ static int ice_validate_mqprio_qopt(struct ice_vsi *vsi, struct tc_mqprio_qopt_offload *mqprio_qopt) { int non_power_of_2_qcount = 0; struct ice_pf *pf = vsi->back; int max_rss_q_cnt = 0; u64 sum_min_rate = 0; struct device *dev; int i, speed; u8 num_tc; if (vsi->type != ICE_VSI_PF) return -EINVAL; if (mqprio_qopt->qopt.offset[0] != 0 || mqprio_qopt->qopt.num_tc < 1 || mqprio_qopt->qopt.num_tc > ICE_CHNL_MAX_TC) return -EINVAL; dev = ice_pf_to_dev(pf); vsi->ch_rss_size = 0; num_tc = mqprio_qopt->qopt.num_tc; speed = ice_get_link_speed_kbps(vsi); for (i = 0; num_tc; i++) { int qcount = mqprio_qopt->qopt.count[i]; u64 max_rate, min_rate, rem; if (!qcount) return -EINVAL; if (is_power_of_2(qcount)) { if (non_power_of_2_qcount && qcount > non_power_of_2_qcount) { dev_err(dev, "qcount[%d] cannot be greater than non power of 2 qcount[%d]\n", qcount, non_power_of_2_qcount); return -EINVAL; } if (qcount > max_rss_q_cnt) max_rss_q_cnt = qcount; } else { if (non_power_of_2_qcount && qcount != non_power_of_2_qcount) { dev_err(dev, "Only one non power of 2 qcount allowed[%d,%d]\n", qcount, non_power_of_2_qcount); return -EINVAL; } if (qcount < max_rss_q_cnt) { dev_err(dev, "non power of 2 qcount[%d] cannot be less than other qcount[%d]\n", qcount, max_rss_q_cnt); return -EINVAL; } max_rss_q_cnt = qcount; non_power_of_2_qcount = qcount; } /* TC command takes input in K/N/Gbps or K/M/Gbit etc but * converts the bandwidth rate limit into Bytes/s when * passing it down to the driver. So convert input bandwidth * from Bytes/s to Kbps */ max_rate = mqprio_qopt->max_rate[i]; max_rate = div_u64(max_rate, ICE_BW_KBPS_DIVISOR); /* min_rate is minimum guaranteed rate and it can't be zero */ min_rate = mqprio_qopt->min_rate[i]; min_rate = div_u64(min_rate, ICE_BW_KBPS_DIVISOR); sum_min_rate += min_rate; if (min_rate && min_rate < ICE_MIN_BW_LIMIT) { dev_err(dev, "TC%d: min_rate(%llu Kbps) < %u Kbps\n", i, min_rate, ICE_MIN_BW_LIMIT); return -EINVAL; } if (max_rate && max_rate > speed) { dev_err(dev, "TC%d: max_rate(%llu Kbps) > link speed of %u Kbps\n", i, max_rate, speed); return -EINVAL; } iter_div_u64_rem(min_rate, ICE_MIN_BW_LIMIT, &rem); if (rem) { dev_err(dev, "TC%d: Min Rate not multiple of %u Kbps", i, ICE_MIN_BW_LIMIT); return -EINVAL; } iter_div_u64_rem(max_rate, ICE_MIN_BW_LIMIT, &rem); if (rem) { dev_err(dev, "TC%d: Max Rate not multiple of %u Kbps", i, ICE_MIN_BW_LIMIT); return -EINVAL; } /* min_rate can't be more than max_rate, except when max_rate * is zero (implies max_rate sought is max line rate). In such * a case min_rate can be more than max. */ if (max_rate && min_rate > max_rate) { dev_err(dev, "min_rate %llu Kbps can't be more than max_rate %llu Kbps\n", min_rate, max_rate); return -EINVAL; } if (i >= mqprio_qopt->qopt.num_tc - 1) break; if (mqprio_qopt->qopt.offset[i + 1] != (mqprio_qopt->qopt.offset[i] + qcount)) return -EINVAL; } if (vsi->num_rxq < (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i])) return -EINVAL; if (vsi->num_txq < (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i])) return -EINVAL; if (sum_min_rate && sum_min_rate > (u64)speed) { dev_err(dev, "Invalid min Tx rate(%llu) Kbps > speed (%u) Kbps specified\n", sum_min_rate, speed); return -EINVAL; } /* make sure vsi->ch_rss_size is set correctly based on TC's qcount */ vsi->ch_rss_size = max_rss_q_cnt; return 0; } /** * ice_add_vsi_to_fdir - add a VSI to the flow director group for PF * @pf: ptr to PF device * @vsi: ptr to VSI */ static int ice_add_vsi_to_fdir(struct ice_pf *pf, struct ice_vsi *vsi) { struct device *dev = ice_pf_to_dev(pf); bool added = false; struct ice_hw *hw; int flow; if (!(vsi->num_gfltr || vsi->num_bfltr)) return -EINVAL; hw = &pf->hw; for (flow = 0; flow < ICE_FLTR_PTYPE_MAX; flow++) { struct ice_fd_hw_prof *prof; int tun, status; u64 entry_h; if (!(hw->fdir_prof && hw->fdir_prof[flow] && hw->fdir_prof[flow]->cnt)) continue; for (tun = 0; tun < ICE_FD_HW_SEG_MAX; tun++) { enum ice_flow_priority prio; u64 prof_id; /* add this VSI to FDir profile for this flow */ prio = ICE_FLOW_PRIO_NORMAL; prof = hw->fdir_prof[flow]; prof_id = flow + tun * ICE_FLTR_PTYPE_MAX; status = ice_flow_add_entry(hw, ICE_BLK_FD, prof_id, prof->vsi_h[0], vsi->idx, prio, prof->fdir_seg[tun], &entry_h); if (status) { dev_err(dev, "channel VSI idx %d, not able to add to group %d\n", vsi->idx, flow); continue; } prof->entry_h[prof->cnt][tun] = entry_h; } /* store VSI for filter replay and delete */ prof->vsi_h[prof->cnt] = vsi->idx; prof->cnt++; added = true; dev_dbg(dev, "VSI idx %d added to fdir group %d\n", vsi->idx, flow); } if (!added) dev_dbg(dev, "VSI idx %d not added to fdir groups\n", vsi->idx); return 0; } /** * ice_add_channel - add a channel by adding VSI * @pf: ptr to PF device * @sw_id: underlying HW switching element ID * @ch: ptr to channel structure * * Add a channel (VSI) using add_vsi and queue_map */ static int ice_add_channel(struct ice_pf *pf, u16 sw_id, struct ice_channel *ch) { struct device *dev = ice_pf_to_dev(pf); struct ice_vsi *vsi; if (ch->type != ICE_VSI_CHNL) { dev_err(dev, "add new VSI failed, ch->type %d\n", ch->type); return -EINVAL; } vsi = ice_chnl_vsi_setup(pf, pf->hw.port_info, ch); if (!vsi || vsi->type != ICE_VSI_CHNL) { dev_err(dev, "create chnl VSI failure\n"); return -EINVAL; } ice_add_vsi_to_fdir(pf, vsi); ch->sw_id = sw_id; ch->vsi_num = vsi->vsi_num; ch->info.mapping_flags = vsi->info.mapping_flags; ch->ch_vsi = vsi; /* set the back pointer of channel for newly created VSI */ vsi->ch = ch; memcpy(&ch->info.q_mapping, &vsi->info.q_mapping, sizeof(vsi->info.q_mapping)); memcpy(&ch->info.tc_mapping, vsi->info.tc_mapping, sizeof(vsi->info.tc_mapping)); return 0; } /** * ice_chnl_cfg_res * @vsi: the VSI being setup * @ch: ptr to channel structure * * Configure channel specific resources such as rings, vector. */ static void ice_chnl_cfg_res(struct ice_vsi *vsi, struct ice_channel *ch) { int i; for (i = 0; i < ch->num_txq; i++) { struct ice_q_vector *tx_q_vector, *rx_q_vector; struct ice_ring_container *rc; struct ice_tx_ring *tx_ring; struct ice_rx_ring *rx_ring; tx_ring = vsi->tx_rings[ch->base_q + i]; rx_ring = vsi->rx_rings[ch->base_q + i]; if (!tx_ring || !rx_ring) continue; /* setup ring being channel enabled */ tx_ring->ch = ch; rx_ring->ch = ch; /* following code block sets up vector specific attributes */ tx_q_vector = tx_ring->q_vector; rx_q_vector = rx_ring->q_vector; if (!tx_q_vector && !rx_q_vector) continue; if (tx_q_vector) { tx_q_vector->ch = ch; /* setup Tx and Rx ITR setting if DIM is off */ rc = &tx_q_vector->tx; if (!ITR_IS_DYNAMIC(rc)) ice_write_itr(rc, rc->itr_setting); } if (rx_q_vector) { rx_q_vector->ch = ch; /* setup Tx and Rx ITR setting if DIM is off */ rc = &rx_q_vector->rx; if (!ITR_IS_DYNAMIC(rc)) ice_write_itr(rc, rc->itr_setting); } } /* it is safe to assume that, if channel has non-zero num_t[r]xq, then * GLINT_ITR register would have written to perform in-context * update, hence perform flush */ if (ch->num_txq || ch->num_rxq) ice_flush(&vsi->back->hw); } /** * ice_cfg_chnl_all_res - configure channel resources * @vsi: pte to main_vsi * @ch: ptr to channel structure * * This function configures channel specific resources such as flow-director * counter index, and other resources such as queues, vectors, ITR settings */ static void ice_cfg_chnl_all_res(struct ice_vsi *vsi, struct ice_channel *ch) { /* configure channel (aka ADQ) resources such as queues, vectors, * ITR settings for channel specific vectors and anything else */ ice_chnl_cfg_res(vsi, ch); } /** * ice_setup_hw_channel - setup new channel * @pf: ptr to PF device * @vsi: the VSI being setup * @ch: ptr to channel structure * @sw_id: underlying HW switching element ID * @type: type of channel to be created (VMDq2/VF) * * Setup new channel (VSI) based on specified type (VMDq2/VF) * and configures Tx rings accordingly */ static int ice_setup_hw_channel(struct ice_pf *pf, struct ice_vsi *vsi, struct ice_channel *ch, u16 sw_id, u8 type) { struct device *dev = ice_pf_to_dev(pf); int ret; ch->base_q = vsi->next_base_q; ch->type = type; ret = ice_add_channel(pf, sw_id, ch); if (ret) { dev_err(dev, "failed to add_channel using sw_id %u\n", sw_id); return ret; } /* configure/setup ADQ specific resources */ ice_cfg_chnl_all_res(vsi, ch); /* make sure to update the next_base_q so that subsequent channel's * (aka ADQ) VSI queue map is correct */ vsi->next_base_q = vsi->next_base_q + ch->num_rxq; dev_dbg(dev, "added channel: vsi_num %u, num_rxq %u\n", ch->vsi_num, ch->num_rxq); return 0; } /** * ice_setup_channel - setup new channel using uplink element * @pf: ptr to PF device * @vsi: the VSI being setup * @ch: ptr to channel structure * * Setup new channel (VSI) based on specified type (VMDq2/VF) * and uplink switching element */ static bool ice_setup_channel(struct ice_pf *pf, struct ice_vsi *vsi, struct ice_channel *ch) { struct device *dev = ice_pf_to_dev(pf); u16 sw_id; int ret; if (vsi->type != ICE_VSI_PF) { dev_err(dev, "unsupported parent VSI type(%d)\n", vsi->type); return false; } sw_id = pf->first_sw->sw_id; /* create channel (VSI) */ ret = ice_setup_hw_channel(pf, vsi, ch, sw_id, ICE_VSI_CHNL); if (ret) { dev_err(dev, "failed to setup hw_channel\n"); return false; } dev_dbg(dev, "successfully created channel()\n"); return ch->ch_vsi ? true : false; } /** * ice_set_bw_limit - setup BW limit for Tx traffic based on max_tx_rate * @vsi: VSI to be configured * @max_tx_rate: max Tx rate in Kbps to be configured as maximum BW limit * @min_tx_rate: min Tx rate in Kbps to be configured as minimum BW limit */ static int ice_set_bw_limit(struct ice_vsi *vsi, u64 max_tx_rate, u64 min_tx_rate) { int err; err = ice_set_min_bw_limit(vsi, min_tx_rate); if (err) return err; return ice_set_max_bw_limit(vsi, max_tx_rate); } /** * ice_create_q_channel - function to create channel * @vsi: VSI to be configured * @ch: ptr to channel (it contains channel specific params) * * This function creates channel (VSI) using num_queues specified by user, * reconfigs RSS if needed. */ static int ice_create_q_channel(struct ice_vsi *vsi, struct ice_channel *ch) { struct ice_pf *pf = vsi->back; struct device *dev; if (!ch) return -EINVAL; dev = ice_pf_to_dev(pf); if (!ch->num_txq || !ch->num_rxq) { dev_err(dev, "Invalid num_queues requested: %d\n", ch->num_rxq); return -EINVAL; } if (!vsi->cnt_q_avail || vsi->cnt_q_avail < ch->num_txq) { dev_err(dev, "cnt_q_avail (%u) less than num_queues %d\n", vsi->cnt_q_avail, ch->num_txq); return -EINVAL; } if (!ice_setup_channel(pf, vsi, ch)) { dev_info(dev, "Failed to setup channel\n"); return -EINVAL; } /* configure BW rate limit */ if (ch->ch_vsi && (ch->max_tx_rate || ch->min_tx_rate)) { int ret; ret = ice_set_bw_limit(ch->ch_vsi, ch->max_tx_rate, ch->min_tx_rate); if (ret) dev_err(dev, "failed to set Tx rate of %llu Kbps for VSI(%u)\n", ch->max_tx_rate, ch->ch_vsi->vsi_num); else dev_dbg(dev, "set Tx rate of %llu Kbps for VSI(%u)\n", ch->max_tx_rate, ch->ch_vsi->vsi_num); } vsi->cnt_q_avail -= ch->num_txq; return 0; } /** * ice_rem_all_chnl_fltrs - removes all channel filters * @pf: ptr to PF, TC-flower based filter are tracked at PF level * * Remove all advanced switch filters only if they are channel specific * tc-flower based filter */ static void ice_rem_all_chnl_fltrs(struct ice_pf *pf) { struct ice_tc_flower_fltr *fltr; struct hlist_node *node; /* to remove all channel filters, iterate an ordered list of filters */ hlist_for_each_entry_safe(fltr, node, &pf->tc_flower_fltr_list, tc_flower_node) { struct ice_rule_query_data rule; int status; /* for now process only channel specific filters */ if (!ice_is_chnl_fltr(fltr)) continue; rule.rid = fltr->rid; rule.rule_id = fltr->rule_id; rule.vsi_handle = fltr->dest_vsi_handle; status = ice_rem_adv_rule_by_id(&pf->hw, &rule); if (status) { if (status == -ENOENT) dev_dbg(ice_pf_to_dev(pf), "TC flower filter (rule_id %u) does not exist\n", rule.rule_id); else dev_err(ice_pf_to_dev(pf), "failed to delete TC flower filter, status %d\n", status); } else if (fltr->dest_vsi) { /* update advanced switch filter count */ if (fltr->dest_vsi->type == ICE_VSI_CHNL) { u32 flags = fltr->flags; fltr->dest_vsi->num_chnl_fltr--; if (flags & (ICE_TC_FLWR_FIELD_DST_MAC | ICE_TC_FLWR_FIELD_ENC_DST_MAC)) pf->num_dmac_chnl_fltrs--; } } hlist_del(&fltr->tc_flower_node); kfree(fltr); } } /** * ice_remove_q_channels - Remove queue channels for the TCs * @vsi: VSI to be configured * @rem_fltr: delete advanced switch filter or not * * Remove queue channels for the TCs */ static void ice_remove_q_channels(struct ice_vsi *vsi, bool rem_fltr) { struct ice_channel *ch, *ch_tmp; struct ice_pf *pf = vsi->back; int i; /* remove all tc-flower based filter if they are channel filters only */ if (rem_fltr) ice_rem_all_chnl_fltrs(pf); /* remove ntuple filters since queue configuration is being changed */ if (vsi->netdev->features & NETIF_F_NTUPLE) { struct ice_hw *hw = &pf->hw; mutex_lock(&hw->fdir_fltr_lock); ice_fdir_del_all_fltrs(vsi); mutex_unlock(&hw->fdir_fltr_lock); } /* perform cleanup for channels if they exist */ list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) { struct ice_vsi *ch_vsi; list_del(&ch->list); ch_vsi = ch->ch_vsi; if (!ch_vsi) { kfree(ch); continue; } /* Reset queue contexts */ for (i = 0; i < ch->num_rxq; i++) { struct ice_tx_ring *tx_ring; struct ice_rx_ring *rx_ring; tx_ring = vsi->tx_rings[ch->base_q + i]; rx_ring = vsi->rx_rings[ch->base_q + i]; if (tx_ring) { tx_ring->ch = NULL; if (tx_ring->q_vector) tx_ring->q_vector->ch = NULL; } if (rx_ring) { rx_ring->ch = NULL; if (rx_ring->q_vector) rx_ring->q_vector->ch = NULL; } } /* Release FD resources for the channel VSI */ ice_fdir_rem_adq_chnl(&pf->hw, ch->ch_vsi->idx); /* clear the VSI from scheduler tree */ ice_rm_vsi_lan_cfg(ch->ch_vsi->port_info, ch->ch_vsi->idx); /* Delete VSI from FW, PF and HW VSI arrays */ ice_vsi_delete(ch->ch_vsi); /* free the channel */ kfree(ch); } /* clear the channel VSI map which is stored in main VSI */ ice_for_each_chnl_tc(i) vsi->tc_map_vsi[i] = NULL; /* reset main VSI's all TC information */ vsi->all_enatc = 0; vsi->all_numtc = 0; } /** * ice_rebuild_channels - rebuild channel * @pf: ptr to PF * * Recreate channel VSIs and replay filters */ static int ice_rebuild_channels(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); struct ice_vsi *main_vsi; bool rem_adv_fltr = true; struct ice_channel *ch; struct ice_vsi *vsi; int tc_idx = 1; int i, err; main_vsi = ice_get_main_vsi(pf); if (!main_vsi) return 0; if (!test_bit(ICE_FLAG_TC_MQPRIO, pf->flags) || main_vsi->old_numtc == 1) return 0; /* nothing to be done */ /* reconfigure main VSI based on old value of TC and cached values * for MQPRIO opts */ err = ice_vsi_cfg_tc(main_vsi, main_vsi->old_ena_tc); if (err) { dev_err(dev, "failed configuring TC(ena_tc:0x%02x) for HW VSI=%u\n", main_vsi->old_ena_tc, main_vsi->vsi_num); return err; } /* rebuild ADQ VSIs */ ice_for_each_vsi(pf, i) { enum ice_vsi_type type; vsi = pf->vsi[i]; if (!vsi || vsi->type != ICE_VSI_CHNL) continue; type = vsi->type; /* rebuild ADQ VSI */ err = ice_vsi_rebuild(vsi, ICE_VSI_FLAG_INIT); if (err) { dev_err(dev, "VSI (type:%s) at index %d rebuild failed, err %d\n", ice_vsi_type_str(type), vsi->idx, err); goto cleanup; } /* Re-map HW VSI number, using VSI handle that has been * previously validated in ice_replay_vsi() call above */ vsi->vsi_num = ice_get_hw_vsi_num(&pf->hw, vsi->idx); /* replay filters for the VSI */ err = ice_replay_vsi(&pf->hw, vsi->idx); if (err) { dev_err(dev, "VSI (type:%s) replay failed, err %d, VSI index %d\n", ice_vsi_type_str(type), err, vsi->idx); rem_adv_fltr = false; goto cleanup; } dev_info(dev, "VSI (type:%s) at index %d rebuilt successfully\n", ice_vsi_type_str(type), vsi->idx); /* store ADQ VSI at correct TC index in main VSI's * map of TC to VSI */ main_vsi->tc_map_vsi[tc_idx++] = vsi; } /* ADQ VSI(s) has been rebuilt successfully, so setup * channel for main VSI's Tx and Rx rings */ list_for_each_entry(ch, &main_vsi->ch_list, list) { struct ice_vsi *ch_vsi; ch_vsi = ch->ch_vsi; if (!ch_vsi) continue; /* reconfig channel resources */ ice_cfg_chnl_all_res(main_vsi, ch); /* replay BW rate limit if it is non-zero */ if (!ch->max_tx_rate && !ch->min_tx_rate) continue; err = ice_set_bw_limit(ch_vsi, ch->max_tx_rate, ch->min_tx_rate); if (err) dev_err(dev, "failed (err:%d) to rebuild BW rate limit, max_tx_rate: %llu Kbps, min_tx_rate: %llu Kbps for VSI(%u)\n", err, ch->max_tx_rate, ch->min_tx_rate, ch_vsi->vsi_num); else dev_dbg(dev, "successfully rebuild BW rate limit, max_tx_rate: %llu Kbps, min_tx_rate: %llu Kbps for VSI(%u)\n", ch->max_tx_rate, ch->min_tx_rate, ch_vsi->vsi_num); } /* reconfig RSS for main VSI */ if (main_vsi->ch_rss_size) ice_vsi_cfg_rss_lut_key(main_vsi); return 0; cleanup: ice_remove_q_channels(main_vsi, rem_adv_fltr); return err; } /** * ice_create_q_channels - Add queue channel for the given TCs * @vsi: VSI to be configured * * Configures queue channel mapping to the given TCs */ static int ice_create_q_channels(struct ice_vsi *vsi) { struct ice_pf *pf = vsi->back; struct ice_channel *ch; int ret = 0, i; ice_for_each_chnl_tc(i) { if (!(vsi->all_enatc & BIT(i))) continue; ch = kzalloc(sizeof(*ch), GFP_KERNEL); if (!ch) { ret = -ENOMEM; goto err_free; } INIT_LIST_HEAD(&ch->list); ch->num_rxq = vsi->mqprio_qopt.qopt.count[i]; ch->num_txq = vsi->mqprio_qopt.qopt.count[i]; ch->base_q = vsi->mqprio_qopt.qopt.offset[i]; ch->max_tx_rate = vsi->mqprio_qopt.max_rate[i]; ch->min_tx_rate = vsi->mqprio_qopt.min_rate[i]; /* convert to Kbits/s */ if (ch->max_tx_rate) ch->max_tx_rate = div_u64(ch->max_tx_rate, ICE_BW_KBPS_DIVISOR); if (ch->min_tx_rate) ch->min_tx_rate = div_u64(ch->min_tx_rate, ICE_BW_KBPS_DIVISOR); ret = ice_create_q_channel(vsi, ch); if (ret) { dev_err(ice_pf_to_dev(pf), "failed creating channel TC:%d\n", i); kfree(ch); goto err_free; } list_add_tail(&ch->list, &vsi->ch_list); vsi->tc_map_vsi[i] = ch->ch_vsi; dev_dbg(ice_pf_to_dev(pf), "successfully created channel: VSI %pK\n", ch->ch_vsi); } return 0; err_free: ice_remove_q_channels(vsi, false); return ret; } /** * ice_setup_tc_mqprio_qdisc - configure multiple traffic classes * @netdev: net device to configure * @type_data: TC offload data */ static int ice_setup_tc_mqprio_qdisc(struct net_device *netdev, void *type_data) { struct tc_mqprio_qopt_offload *mqprio_qopt = type_data; struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; struct ice_pf *pf = vsi->back; u16 mode, ena_tc_qdisc = 0; int cur_txq, cur_rxq; u8 hw = 0, num_tcf; struct device *dev; int ret, i; dev = ice_pf_to_dev(pf); num_tcf = mqprio_qopt->qopt.num_tc; hw = mqprio_qopt->qopt.hw; mode = mqprio_qopt->mode; if (!hw) { clear_bit(ICE_FLAG_TC_MQPRIO, pf->flags); vsi->ch_rss_size = 0; memcpy(&vsi->mqprio_qopt, mqprio_qopt, sizeof(*mqprio_qopt)); goto config_tcf; } /* Generate queue region map for number of TCF requested */ for (i = 0; i < num_tcf; i++) ena_tc_qdisc |= BIT(i); switch (mode) { case TC_MQPRIO_MODE_CHANNEL: if (pf->hw.port_info->is_custom_tx_enabled) { dev_err(dev, "Custom Tx scheduler feature enabled, can't configure ADQ\n"); return -EBUSY; } ice_tear_down_devlink_rate_tree(pf); ret = ice_validate_mqprio_qopt(vsi, mqprio_qopt); if (ret) { netdev_err(netdev, "failed to validate_mqprio_qopt(), ret %d\n", ret); return ret; } memcpy(&vsi->mqprio_qopt, mqprio_qopt, sizeof(*mqprio_qopt)); set_bit(ICE_FLAG_TC_MQPRIO, pf->flags); /* don't assume state of hw_tc_offload during driver load * and set the flag for TC flower filter if hw_tc_offload * already ON */ if (vsi->netdev->features & NETIF_F_HW_TC) set_bit(ICE_FLAG_CLS_FLOWER, pf->flags); break; default: return -EINVAL; } config_tcf: /* Requesting same TCF configuration as already enabled */ if (ena_tc_qdisc == vsi->tc_cfg.ena_tc && mode != TC_MQPRIO_MODE_CHANNEL) return 0; /* Pause VSI queues */ ice_dis_vsi(vsi, true); if (!hw && !test_bit(ICE_FLAG_TC_MQPRIO, pf->flags)) ice_remove_q_channels(vsi, true); if (!hw && !test_bit(ICE_FLAG_TC_MQPRIO, pf->flags)) { vsi->req_txq = min_t(int, ice_get_avail_txq_count(pf), num_online_cpus()); vsi->req_rxq = min_t(int, ice_get_avail_rxq_count(pf), num_online_cpus()); } else { /* logic to rebuild VSI, same like ethtool -L */ u16 offset = 0, qcount_tx = 0, qcount_rx = 0; for (i = 0; i < num_tcf; i++) { if (!(ena_tc_qdisc & BIT(i))) continue; offset = vsi->mqprio_qopt.qopt.offset[i]; qcount_rx = vsi->mqprio_qopt.qopt.count[i]; qcount_tx = vsi->mqprio_qopt.qopt.count[i]; } vsi->req_txq = offset + qcount_tx; vsi->req_rxq = offset + qcount_rx; /* store away original rss_size info, so that it gets reused * form ice_vsi_rebuild during tc-qdisc delete stage - to * determine, what should be the rss_sizefor main VSI */ vsi->orig_rss_size = vsi->rss_size; } /* save current values of Tx and Rx queues before calling VSI rebuild * for fallback option */ cur_txq = vsi->num_txq; cur_rxq = vsi->num_rxq; /* proceed with rebuild main VSI using correct number of queues */ ret = ice_vsi_rebuild(vsi, ICE_VSI_FLAG_NO_INIT); if (ret) { /* fallback to current number of queues */ dev_info(dev, "Rebuild failed with new queues, try with current number of queues\n"); vsi->req_txq = cur_txq; vsi->req_rxq = cur_rxq; clear_bit(ICE_RESET_FAILED, pf->state); if (ice_vsi_rebuild(vsi, ICE_VSI_FLAG_NO_INIT)) { dev_err(dev, "Rebuild of main VSI failed again\n"); return ret; } } vsi->all_numtc = num_tcf; vsi->all_enatc = ena_tc_qdisc; ret = ice_vsi_cfg_tc(vsi, ena_tc_qdisc); if (ret) { netdev_err(netdev, "failed configuring TC for VSI id=%d\n", vsi->vsi_num); goto exit; } if (test_bit(ICE_FLAG_TC_MQPRIO, pf->flags)) { u64 max_tx_rate = vsi->mqprio_qopt.max_rate[0]; u64 min_tx_rate = vsi->mqprio_qopt.min_rate[0]; /* set TC0 rate limit if specified */ if (max_tx_rate || min_tx_rate) { /* convert to Kbits/s */ if (max_tx_rate) max_tx_rate = div_u64(max_tx_rate, ICE_BW_KBPS_DIVISOR); if (min_tx_rate) min_tx_rate = div_u64(min_tx_rate, ICE_BW_KBPS_DIVISOR); ret = ice_set_bw_limit(vsi, max_tx_rate, min_tx_rate); if (!ret) { dev_dbg(dev, "set Tx rate max %llu min %llu for VSI(%u)\n", max_tx_rate, min_tx_rate, vsi->vsi_num); } else { dev_err(dev, "failed to set Tx rate max %llu min %llu for VSI(%u)\n", max_tx_rate, min_tx_rate, vsi->vsi_num); goto exit; } } ret = ice_create_q_channels(vsi); if (ret) { netdev_err(netdev, "failed configuring queue channels\n"); goto exit; } else { netdev_dbg(netdev, "successfully configured channels\n"); } } if (vsi->ch_rss_size) ice_vsi_cfg_rss_lut_key(vsi); exit: /* if error, reset the all_numtc and all_enatc */ if (ret) { vsi->all_numtc = 0; vsi->all_enatc = 0; } /* resume VSI */ ice_ena_vsi(vsi, true); return ret; } static LIST_HEAD(ice_block_cb_list); static int ice_setup_tc(struct net_device *netdev, enum tc_setup_type type, void *type_data) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_pf *pf = np->vsi->back; bool locked = false; int err; switch (type) { case TC_SETUP_BLOCK: return flow_block_cb_setup_simple(type_data, &ice_block_cb_list, ice_setup_tc_block_cb, np, np, true); case TC_SETUP_QDISC_MQPRIO: if (ice_is_eswitch_mode_switchdev(pf)) { netdev_err(netdev, "TC MQPRIO offload not supported, switchdev is enabled\n"); return -EOPNOTSUPP; } if (pf->adev) { mutex_lock(&pf->adev_mutex); device_lock(&pf->adev->dev); locked = true; if (pf->adev->dev.driver) { netdev_err(netdev, "Cannot change qdisc when RDMA is active\n"); err = -EBUSY; goto adev_unlock; } } /* setup traffic classifier for receive side */ mutex_lock(&pf->tc_mutex); err = ice_setup_tc_mqprio_qdisc(netdev, type_data); mutex_unlock(&pf->tc_mutex); adev_unlock: if (locked) { device_unlock(&pf->adev->dev); mutex_unlock(&pf->adev_mutex); } return err; default: return -EOPNOTSUPP; } return -EOPNOTSUPP; } static struct ice_indr_block_priv * ice_indr_block_priv_lookup(struct ice_netdev_priv *np, struct net_device *netdev) { struct ice_indr_block_priv *cb_priv; list_for_each_entry(cb_priv, &np->tc_indr_block_priv_list, list) { if (!cb_priv->netdev) return NULL; if (cb_priv->netdev == netdev) return cb_priv; } return NULL; } static int ice_indr_setup_block_cb(enum tc_setup_type type, void *type_data, void *indr_priv) { struct ice_indr_block_priv *priv = indr_priv; struct ice_netdev_priv *np = priv->np; switch (type) { case TC_SETUP_CLSFLOWER: return ice_setup_tc_cls_flower(np, priv->netdev, (struct flow_cls_offload *) type_data); default: return -EOPNOTSUPP; } } static int ice_indr_setup_tc_block(struct net_device *netdev, struct Qdisc *sch, struct ice_netdev_priv *np, struct flow_block_offload *f, void *data, void (*cleanup)(struct flow_block_cb *block_cb)) { struct ice_indr_block_priv *indr_priv; struct flow_block_cb *block_cb; if (!ice_is_tunnel_supported(netdev) && !(is_vlan_dev(netdev) && vlan_dev_real_dev(netdev) == np->vsi->netdev)) return -EOPNOTSUPP; if (f->binder_type != FLOW_BLOCK_BINDER_TYPE_CLSACT_INGRESS) return -EOPNOTSUPP; switch (f->command) { case FLOW_BLOCK_BIND: indr_priv = ice_indr_block_priv_lookup(np, netdev); if (indr_priv) return -EEXIST; indr_priv = kzalloc(sizeof(*indr_priv), GFP_KERNEL); if (!indr_priv) return -ENOMEM; indr_priv->netdev = netdev; indr_priv->np = np; list_add(&indr_priv->list, &np->tc_indr_block_priv_list); block_cb = flow_indr_block_cb_alloc(ice_indr_setup_block_cb, indr_priv, indr_priv, ice_rep_indr_tc_block_unbind, f, netdev, sch, data, np, cleanup); if (IS_ERR(block_cb)) { list_del(&indr_priv->list); kfree(indr_priv); return PTR_ERR(block_cb); } flow_block_cb_add(block_cb, f); list_add_tail(&block_cb->driver_list, &ice_block_cb_list); break; case FLOW_BLOCK_UNBIND: indr_priv = ice_indr_block_priv_lookup(np, netdev); if (!indr_priv) return -ENOENT; block_cb = flow_block_cb_lookup(f->block, ice_indr_setup_block_cb, indr_priv); if (!block_cb) return -ENOENT; flow_indr_block_cb_remove(block_cb, f); list_del(&block_cb->driver_list); break; default: return -EOPNOTSUPP; } return 0; } static int ice_indr_setup_tc_cb(struct net_device *netdev, struct Qdisc *sch, void *cb_priv, enum tc_setup_type type, void *type_data, void *data, void (*cleanup)(struct flow_block_cb *block_cb)) { switch (type) { case TC_SETUP_BLOCK: return ice_indr_setup_tc_block(netdev, sch, cb_priv, type_data, data, cleanup); default: return -EOPNOTSUPP; } } /** * ice_open - Called when a network interface becomes active * @netdev: network interface device structure * * The open entry point is called when a network interface is made * active by the system (IFF_UP). At this point all resources needed * for transmit and receive operations are allocated, the interrupt * handler is registered with the OS, the netdev watchdog is enabled, * and the stack is notified that the interface is ready. * * Returns 0 on success, negative value on failure */ int ice_open(struct net_device *netdev) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_pf *pf = np->vsi->back; if (ice_is_reset_in_progress(pf->state)) { netdev_err(netdev, "can't open net device while reset is in progress"); return -EBUSY; } return ice_open_internal(netdev); } /** * ice_open_internal - Called when a network interface becomes active * @netdev: network interface device structure * * Internal ice_open implementation. Should not be used directly except for ice_open and reset * handling routine * * Returns 0 on success, negative value on failure */ int ice_open_internal(struct net_device *netdev) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; struct ice_pf *pf = vsi->back; struct ice_port_info *pi; int err; if (test_bit(ICE_NEEDS_RESTART, pf->state)) { netdev_err(netdev, "driver needs to be unloaded and reloaded\n"); return -EIO; } netif_carrier_off(netdev); pi = vsi->port_info; err = ice_update_link_info(pi); if (err) { netdev_err(netdev, "Failed to get link info, error %d\n", err); return err; } ice_check_link_cfg_err(pf, pi->phy.link_info.link_cfg_err); /* Set PHY if there is media, otherwise, turn off PHY */ if (pi->phy.link_info.link_info & ICE_AQ_MEDIA_AVAILABLE) { clear_bit(ICE_FLAG_NO_MEDIA, pf->flags); if (!test_bit(ICE_PHY_INIT_COMPLETE, pf->state)) { err = ice_init_phy_user_cfg(pi); if (err) { netdev_err(netdev, "Failed to initialize PHY settings, error %d\n", err); return err; } } err = ice_configure_phy(vsi); if (err) { netdev_err(netdev, "Failed to set physical link up, error %d\n", err); return err; } } else { set_bit(ICE_FLAG_NO_MEDIA, pf->flags); ice_set_link(vsi, false); } err = ice_vsi_open(vsi); if (err) netdev_err(netdev, "Failed to open VSI 0x%04X on switch 0x%04X\n", vsi->vsi_num, vsi->vsw->sw_id); /* Update existing tunnels information */ udp_tunnel_get_rx_info(netdev); return err; } /** * ice_stop - Disables a network interface * @netdev: network interface device structure * * The stop entry point is called when an interface is de-activated by the OS, * and the netdevice enters the DOWN state. The hardware is still under the * driver's control, but the netdev interface is disabled. * * Returns success only - not allowed to fail */ int ice_stop(struct net_device *netdev) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; struct ice_pf *pf = vsi->back; if (ice_is_reset_in_progress(pf->state)) { netdev_err(netdev, "can't stop net device while reset is in progress"); return -EBUSY; } if (test_bit(ICE_FLAG_LINK_DOWN_ON_CLOSE_ENA, vsi->back->flags)) { int link_err = ice_force_phys_link_state(vsi, false); if (link_err) { netdev_err(vsi->netdev, "Failed to set physical link down, VSI %d error %d\n", vsi->vsi_num, link_err); return -EIO; } } ice_vsi_close(vsi); return 0; } /** * ice_features_check - Validate encapsulated packet conforms to limits * @skb: skb buffer * @netdev: This port's netdev * @features: Offload features that the stack believes apply */ static netdev_features_t ice_features_check(struct sk_buff *skb, struct net_device __always_unused *netdev, netdev_features_t features) { bool gso = skb_is_gso(skb); size_t len; /* No point in doing any of this if neither checksum nor GSO are * being requested for this frame. We can rule out both by just * checking for CHECKSUM_PARTIAL */ if (skb->ip_summed != CHECKSUM_PARTIAL) return features; /* We cannot support GSO if the MSS is going to be less than * 64 bytes. If it is then we need to drop support for GSO. */ if (gso && (skb_shinfo(skb)->gso_size < ICE_TXD_CTX_MIN_MSS)) features &= ~NETIF_F_GSO_MASK; len = skb_network_offset(skb); if (len > ICE_TXD_MACLEN_MAX || len & 0x1) goto out_rm_features; len = skb_network_header_len(skb); if (len > ICE_TXD_IPLEN_MAX || len & 0x1) goto out_rm_features; if (skb->encapsulation) { /* this must work for VXLAN frames AND IPIP/SIT frames, and in * the case of IPIP frames, the transport header pointer is * after the inner header! So check to make sure that this * is a GRE or UDP_TUNNEL frame before doing that math. */ if (gso && (skb_shinfo(skb)->gso_type & (SKB_GSO_GRE | SKB_GSO_UDP_TUNNEL))) { len = skb_inner_network_header(skb) - skb_transport_header(skb); if (len > ICE_TXD_L4LEN_MAX || len & 0x1) goto out_rm_features; } len = skb_inner_network_header_len(skb); if (len > ICE_TXD_IPLEN_MAX || len & 0x1) goto out_rm_features; } return features; out_rm_features: return features & ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK); } static const struct net_device_ops ice_netdev_safe_mode_ops = { .ndo_open = ice_open, .ndo_stop = ice_stop, .ndo_start_xmit = ice_start_xmit, .ndo_set_mac_address = ice_set_mac_address, .ndo_validate_addr = eth_validate_addr, .ndo_change_mtu = ice_change_mtu, .ndo_get_stats64 = ice_get_stats64, .ndo_tx_timeout = ice_tx_timeout, .ndo_bpf = ice_xdp_safe_mode, }; static const struct net_device_ops ice_netdev_ops = { .ndo_open = ice_open, .ndo_stop = ice_stop, .ndo_start_xmit = ice_start_xmit, .ndo_select_queue = ice_select_queue, .ndo_features_check = ice_features_check, .ndo_fix_features = ice_fix_features, .ndo_set_rx_mode = ice_set_rx_mode, .ndo_set_mac_address = ice_set_mac_address, .ndo_validate_addr = eth_validate_addr, .ndo_change_mtu = ice_change_mtu, .ndo_get_stats64 = ice_get_stats64, .ndo_set_tx_maxrate = ice_set_tx_maxrate, .ndo_eth_ioctl = ice_eth_ioctl, .ndo_set_vf_spoofchk = ice_set_vf_spoofchk, .ndo_set_vf_mac = ice_set_vf_mac, .ndo_get_vf_config = ice_get_vf_cfg, .ndo_set_vf_trust = ice_set_vf_trust, .ndo_set_vf_vlan = ice_set_vf_port_vlan, .ndo_set_vf_link_state = ice_set_vf_link_state, .ndo_get_vf_stats = ice_get_vf_stats, .ndo_set_vf_rate = ice_set_vf_bw, .ndo_vlan_rx_add_vid = ice_vlan_rx_add_vid, .ndo_vlan_rx_kill_vid = ice_vlan_rx_kill_vid, .ndo_setup_tc = ice_setup_tc, .ndo_set_features = ice_set_features, .ndo_bridge_getlink = ice_bridge_getlink, .ndo_bridge_setlink = ice_bridge_setlink, .ndo_fdb_add = ice_fdb_add, .ndo_fdb_del = ice_fdb_del, #ifdef CONFIG_RFS_ACCEL .ndo_rx_flow_steer = ice_rx_flow_steer, #endif .ndo_tx_timeout = ice_tx_timeout, .ndo_bpf = ice_xdp, .ndo_xdp_xmit = ice_xdp_xmit, .ndo_xsk_wakeup = ice_xsk_wakeup, };
linux-master
drivers/net/ethernet/intel/ice/ice_main.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2021, Intel Corporation. */ #include "ice.h" #include "ice_base.h" #include "ice_lib.h" #include "ice_flow.h" #include "ice_vf_lib_private.h" #define to_fltr_conf_from_desc(p) \ container_of(p, struct virtchnl_fdir_fltr_conf, input) #define ICE_FLOW_PROF_TYPE_S 0 #define ICE_FLOW_PROF_TYPE_M (0xFFFFFFFFULL << ICE_FLOW_PROF_TYPE_S) #define ICE_FLOW_PROF_VSI_S 32 #define ICE_FLOW_PROF_VSI_M (0xFFFFFFFFULL << ICE_FLOW_PROF_VSI_S) /* Flow profile ID format: * [0:31] - flow type, flow + tun_offs * [32:63] - VSI index */ #define ICE_FLOW_PROF_FD(vsi, flow, tun_offs) \ ((u64)(((((flow) + (tun_offs)) & ICE_FLOW_PROF_TYPE_M)) | \ (((u64)(vsi) << ICE_FLOW_PROF_VSI_S) & ICE_FLOW_PROF_VSI_M))) #define GTPU_TEID_OFFSET 4 #define GTPU_EH_QFI_OFFSET 1 #define GTPU_EH_QFI_MASK 0x3F #define PFCP_S_OFFSET 0 #define PFCP_S_MASK 0x1 #define PFCP_PORT_NR 8805 #define FDIR_INSET_FLAG_ESP_S 0 #define FDIR_INSET_FLAG_ESP_M BIT_ULL(FDIR_INSET_FLAG_ESP_S) #define FDIR_INSET_FLAG_ESP_UDP BIT_ULL(FDIR_INSET_FLAG_ESP_S) #define FDIR_INSET_FLAG_ESP_IPSEC (0ULL << FDIR_INSET_FLAG_ESP_S) enum ice_fdir_tunnel_type { ICE_FDIR_TUNNEL_TYPE_NONE = 0, ICE_FDIR_TUNNEL_TYPE_GTPU, ICE_FDIR_TUNNEL_TYPE_GTPU_EH, }; struct virtchnl_fdir_fltr_conf { struct ice_fdir_fltr input; enum ice_fdir_tunnel_type ttype; u64 inset_flag; u32 flow_id; }; struct virtchnl_fdir_inset_map { enum virtchnl_proto_hdr_field field; enum ice_flow_field fld; u64 flag; u64 mask; }; static const struct virtchnl_fdir_inset_map fdir_inset_map[] = { {VIRTCHNL_PROTO_HDR_ETH_ETHERTYPE, ICE_FLOW_FIELD_IDX_ETH_TYPE, 0, 0}, {VIRTCHNL_PROTO_HDR_IPV4_SRC, ICE_FLOW_FIELD_IDX_IPV4_SA, 0, 0}, {VIRTCHNL_PROTO_HDR_IPV4_DST, ICE_FLOW_FIELD_IDX_IPV4_DA, 0, 0}, {VIRTCHNL_PROTO_HDR_IPV4_DSCP, ICE_FLOW_FIELD_IDX_IPV4_DSCP, 0, 0}, {VIRTCHNL_PROTO_HDR_IPV4_TTL, ICE_FLOW_FIELD_IDX_IPV4_TTL, 0, 0}, {VIRTCHNL_PROTO_HDR_IPV4_PROT, ICE_FLOW_FIELD_IDX_IPV4_PROT, 0, 0}, {VIRTCHNL_PROTO_HDR_IPV6_SRC, ICE_FLOW_FIELD_IDX_IPV6_SA, 0, 0}, {VIRTCHNL_PROTO_HDR_IPV6_DST, ICE_FLOW_FIELD_IDX_IPV6_DA, 0, 0}, {VIRTCHNL_PROTO_HDR_IPV6_TC, ICE_FLOW_FIELD_IDX_IPV6_DSCP, 0, 0}, {VIRTCHNL_PROTO_HDR_IPV6_HOP_LIMIT, ICE_FLOW_FIELD_IDX_IPV6_TTL, 0, 0}, {VIRTCHNL_PROTO_HDR_IPV6_PROT, ICE_FLOW_FIELD_IDX_IPV6_PROT, 0, 0}, {VIRTCHNL_PROTO_HDR_UDP_SRC_PORT, ICE_FLOW_FIELD_IDX_UDP_SRC_PORT, 0, 0}, {VIRTCHNL_PROTO_HDR_UDP_DST_PORT, ICE_FLOW_FIELD_IDX_UDP_DST_PORT, 0, 0}, {VIRTCHNL_PROTO_HDR_TCP_SRC_PORT, ICE_FLOW_FIELD_IDX_TCP_SRC_PORT, 0, 0}, {VIRTCHNL_PROTO_HDR_TCP_DST_PORT, ICE_FLOW_FIELD_IDX_TCP_DST_PORT, 0, 0}, {VIRTCHNL_PROTO_HDR_SCTP_SRC_PORT, ICE_FLOW_FIELD_IDX_SCTP_SRC_PORT, 0, 0}, {VIRTCHNL_PROTO_HDR_SCTP_DST_PORT, ICE_FLOW_FIELD_IDX_SCTP_DST_PORT, 0, 0}, {VIRTCHNL_PROTO_HDR_GTPU_IP_TEID, ICE_FLOW_FIELD_IDX_GTPU_IP_TEID, 0, 0}, {VIRTCHNL_PROTO_HDR_GTPU_EH_QFI, ICE_FLOW_FIELD_IDX_GTPU_EH_QFI, 0, 0}, {VIRTCHNL_PROTO_HDR_ESP_SPI, ICE_FLOW_FIELD_IDX_ESP_SPI, FDIR_INSET_FLAG_ESP_IPSEC, FDIR_INSET_FLAG_ESP_M}, {VIRTCHNL_PROTO_HDR_ESP_SPI, ICE_FLOW_FIELD_IDX_NAT_T_ESP_SPI, FDIR_INSET_FLAG_ESP_UDP, FDIR_INSET_FLAG_ESP_M}, {VIRTCHNL_PROTO_HDR_AH_SPI, ICE_FLOW_FIELD_IDX_AH_SPI, 0, 0}, {VIRTCHNL_PROTO_HDR_L2TPV3_SESS_ID, ICE_FLOW_FIELD_IDX_L2TPV3_SESS_ID, 0, 0}, {VIRTCHNL_PROTO_HDR_PFCP_S_FIELD, ICE_FLOW_FIELD_IDX_UDP_DST_PORT, 0, 0}, }; /** * ice_vc_fdir_param_check * @vf: pointer to the VF structure * @vsi_id: VF relative VSI ID * * Check for the valid VSI ID, PF's state and VF's state * * Return: 0 on success, and -EINVAL on error. */ static int ice_vc_fdir_param_check(struct ice_vf *vf, u16 vsi_id) { struct ice_pf *pf = vf->pf; if (!test_bit(ICE_FLAG_FD_ENA, pf->flags)) return -EINVAL; if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) return -EINVAL; if (!(vf->driver_caps & VIRTCHNL_VF_OFFLOAD_FDIR_PF)) return -EINVAL; if (vsi_id != vf->lan_vsi_num) return -EINVAL; if (!ice_vc_isvalid_vsi_id(vf, vsi_id)) return -EINVAL; if (!ice_get_vf_vsi(vf)) return -EINVAL; return 0; } /** * ice_vf_start_ctrl_vsi * @vf: pointer to the VF structure * * Allocate ctrl_vsi for the first time and open the ctrl_vsi port for VF * * Return: 0 on success, and other on error. */ static int ice_vf_start_ctrl_vsi(struct ice_vf *vf) { struct ice_pf *pf = vf->pf; struct ice_vsi *ctrl_vsi; struct device *dev; int err; dev = ice_pf_to_dev(pf); if (vf->ctrl_vsi_idx != ICE_NO_VSI) return -EEXIST; ctrl_vsi = ice_vf_ctrl_vsi_setup(vf); if (!ctrl_vsi) { dev_dbg(dev, "Could not setup control VSI for VF %d\n", vf->vf_id); return -ENOMEM; } err = ice_vsi_open_ctrl(ctrl_vsi); if (err) { dev_dbg(dev, "Could not open control VSI for VF %d\n", vf->vf_id); goto err_vsi_open; } return 0; err_vsi_open: ice_vsi_release(ctrl_vsi); if (vf->ctrl_vsi_idx != ICE_NO_VSI) { pf->vsi[vf->ctrl_vsi_idx] = NULL; vf->ctrl_vsi_idx = ICE_NO_VSI; } return err; } /** * ice_vc_fdir_alloc_prof - allocate profile for this filter flow type * @vf: pointer to the VF structure * @flow: filter flow type * * Return: 0 on success, and other on error. */ static int ice_vc_fdir_alloc_prof(struct ice_vf *vf, enum ice_fltr_ptype flow) { struct ice_vf_fdir *fdir = &vf->fdir; if (!fdir->fdir_prof) { fdir->fdir_prof = devm_kcalloc(ice_pf_to_dev(vf->pf), ICE_FLTR_PTYPE_MAX, sizeof(*fdir->fdir_prof), GFP_KERNEL); if (!fdir->fdir_prof) return -ENOMEM; } if (!fdir->fdir_prof[flow]) { fdir->fdir_prof[flow] = devm_kzalloc(ice_pf_to_dev(vf->pf), sizeof(**fdir->fdir_prof), GFP_KERNEL); if (!fdir->fdir_prof[flow]) return -ENOMEM; } return 0; } /** * ice_vc_fdir_free_prof - free profile for this filter flow type * @vf: pointer to the VF structure * @flow: filter flow type */ static void ice_vc_fdir_free_prof(struct ice_vf *vf, enum ice_fltr_ptype flow) { struct ice_vf_fdir *fdir = &vf->fdir; if (!fdir->fdir_prof) return; if (!fdir->fdir_prof[flow]) return; devm_kfree(ice_pf_to_dev(vf->pf), fdir->fdir_prof[flow]); fdir->fdir_prof[flow] = NULL; } /** * ice_vc_fdir_free_prof_all - free all the profile for this VF * @vf: pointer to the VF structure */ static void ice_vc_fdir_free_prof_all(struct ice_vf *vf) { struct ice_vf_fdir *fdir = &vf->fdir; enum ice_fltr_ptype flow; if (!fdir->fdir_prof) return; for (flow = ICE_FLTR_PTYPE_NONF_NONE; flow < ICE_FLTR_PTYPE_MAX; flow++) ice_vc_fdir_free_prof(vf, flow); devm_kfree(ice_pf_to_dev(vf->pf), fdir->fdir_prof); fdir->fdir_prof = NULL; } /** * ice_vc_fdir_parse_flow_fld * @proto_hdr: virtual channel protocol filter header * @conf: FDIR configuration for each filter * @fld: field type array * @fld_cnt: field counter * * Parse the virtual channel filter header and store them into field type array * * Return: 0 on success, and other on error. */ static int ice_vc_fdir_parse_flow_fld(struct virtchnl_proto_hdr *proto_hdr, struct virtchnl_fdir_fltr_conf *conf, enum ice_flow_field *fld, int *fld_cnt) { struct virtchnl_proto_hdr hdr; u32 i; memcpy(&hdr, proto_hdr, sizeof(hdr)); for (i = 0; (i < ARRAY_SIZE(fdir_inset_map)) && VIRTCHNL_GET_PROTO_HDR_FIELD(&hdr); i++) if (VIRTCHNL_TEST_PROTO_HDR(&hdr, fdir_inset_map[i].field)) { if (fdir_inset_map[i].mask && ((fdir_inset_map[i].mask & conf->inset_flag) != fdir_inset_map[i].flag)) continue; fld[*fld_cnt] = fdir_inset_map[i].fld; *fld_cnt += 1; if (*fld_cnt >= ICE_FLOW_FIELD_IDX_MAX) return -EINVAL; VIRTCHNL_DEL_PROTO_HDR_FIELD(&hdr, fdir_inset_map[i].field); } return 0; } /** * ice_vc_fdir_set_flow_fld * @vf: pointer to the VF structure * @fltr: virtual channel add cmd buffer * @conf: FDIR configuration for each filter * @seg: array of one or more packet segments that describe the flow * * Parse the virtual channel add msg buffer's field vector and store them into * flow's packet segment field * * Return: 0 on success, and other on error. */ static int ice_vc_fdir_set_flow_fld(struct ice_vf *vf, struct virtchnl_fdir_add *fltr, struct virtchnl_fdir_fltr_conf *conf, struct ice_flow_seg_info *seg) { struct virtchnl_fdir_rule *rule = &fltr->rule_cfg; enum ice_flow_field fld[ICE_FLOW_FIELD_IDX_MAX]; struct device *dev = ice_pf_to_dev(vf->pf); struct virtchnl_proto_hdrs *proto; int fld_cnt = 0; int i; proto = &rule->proto_hdrs; for (i = 0; i < proto->count; i++) { struct virtchnl_proto_hdr *hdr = &proto->proto_hdr[i]; int ret; ret = ice_vc_fdir_parse_flow_fld(hdr, conf, fld, &fld_cnt); if (ret) return ret; } if (fld_cnt == 0) { dev_dbg(dev, "Empty input set for VF %d\n", vf->vf_id); return -EINVAL; } for (i = 0; i < fld_cnt; i++) ice_flow_set_fld(seg, fld[i], ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, false); return 0; } /** * ice_vc_fdir_set_flow_hdr - config the flow's packet segment header * @vf: pointer to the VF structure * @conf: FDIR configuration for each filter * @seg: array of one or more packet segments that describe the flow * * Return: 0 on success, and other on error. */ static int ice_vc_fdir_set_flow_hdr(struct ice_vf *vf, struct virtchnl_fdir_fltr_conf *conf, struct ice_flow_seg_info *seg) { enum ice_fltr_ptype flow = conf->input.flow_type; enum ice_fdir_tunnel_type ttype = conf->ttype; struct device *dev = ice_pf_to_dev(vf->pf); switch (flow) { case ICE_FLTR_PTYPE_NON_IP_L2: ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_ETH_NON_IP); break; case ICE_FLTR_PTYPE_NONF_IPV4_L2TPV3: ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_L2TPV3 | ICE_FLOW_SEG_HDR_IPV4 | ICE_FLOW_SEG_HDR_IPV_OTHER); break; case ICE_FLTR_PTYPE_NONF_IPV4_ESP: ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_ESP | ICE_FLOW_SEG_HDR_IPV4 | ICE_FLOW_SEG_HDR_IPV_OTHER); break; case ICE_FLTR_PTYPE_NONF_IPV4_AH: ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_AH | ICE_FLOW_SEG_HDR_IPV4 | ICE_FLOW_SEG_HDR_IPV_OTHER); break; case ICE_FLTR_PTYPE_NONF_IPV4_NAT_T_ESP: ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_NAT_T_ESP | ICE_FLOW_SEG_HDR_IPV4 | ICE_FLOW_SEG_HDR_IPV_OTHER); break; case ICE_FLTR_PTYPE_NONF_IPV4_PFCP_NODE: ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_PFCP_NODE | ICE_FLOW_SEG_HDR_IPV4 | ICE_FLOW_SEG_HDR_IPV_OTHER); break; case ICE_FLTR_PTYPE_NONF_IPV4_PFCP_SESSION: ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_PFCP_SESSION | ICE_FLOW_SEG_HDR_IPV4 | ICE_FLOW_SEG_HDR_IPV_OTHER); break; case ICE_FLTR_PTYPE_NONF_IPV4_OTHER: ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_IPV4 | ICE_FLOW_SEG_HDR_IPV_OTHER); break; case ICE_FLTR_PTYPE_NONF_IPV4_TCP: ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_TCP | ICE_FLOW_SEG_HDR_IPV4 | ICE_FLOW_SEG_HDR_IPV_OTHER); break; case ICE_FLTR_PTYPE_NONF_IPV4_UDP: ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_UDP | ICE_FLOW_SEG_HDR_IPV4 | ICE_FLOW_SEG_HDR_IPV_OTHER); break; case ICE_FLTR_PTYPE_NONF_IPV4_GTPU_IPV4_UDP: case ICE_FLTR_PTYPE_NONF_IPV4_GTPU_IPV4_TCP: case ICE_FLTR_PTYPE_NONF_IPV4_GTPU_IPV4_ICMP: case ICE_FLTR_PTYPE_NONF_IPV4_GTPU_IPV4_OTHER: if (ttype == ICE_FDIR_TUNNEL_TYPE_GTPU) { ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_GTPU_IP | ICE_FLOW_SEG_HDR_IPV4 | ICE_FLOW_SEG_HDR_IPV_OTHER); } else if (ttype == ICE_FDIR_TUNNEL_TYPE_GTPU_EH) { ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_GTPU_EH | ICE_FLOW_SEG_HDR_GTPU_IP | ICE_FLOW_SEG_HDR_IPV4 | ICE_FLOW_SEG_HDR_IPV_OTHER); } else { dev_dbg(dev, "Invalid tunnel type 0x%x for VF %d\n", flow, vf->vf_id); return -EINVAL; } break; case ICE_FLTR_PTYPE_NONF_IPV4_SCTP: ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_SCTP | ICE_FLOW_SEG_HDR_IPV4 | ICE_FLOW_SEG_HDR_IPV_OTHER); break; case ICE_FLTR_PTYPE_NONF_IPV6_L2TPV3: ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_L2TPV3 | ICE_FLOW_SEG_HDR_IPV6 | ICE_FLOW_SEG_HDR_IPV_OTHER); break; case ICE_FLTR_PTYPE_NONF_IPV6_ESP: ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_ESP | ICE_FLOW_SEG_HDR_IPV6 | ICE_FLOW_SEG_HDR_IPV_OTHER); break; case ICE_FLTR_PTYPE_NONF_IPV6_AH: ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_AH | ICE_FLOW_SEG_HDR_IPV6 | ICE_FLOW_SEG_HDR_IPV_OTHER); break; case ICE_FLTR_PTYPE_NONF_IPV6_NAT_T_ESP: ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_NAT_T_ESP | ICE_FLOW_SEG_HDR_IPV6 | ICE_FLOW_SEG_HDR_IPV_OTHER); break; case ICE_FLTR_PTYPE_NONF_IPV6_PFCP_NODE: ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_PFCP_NODE | ICE_FLOW_SEG_HDR_IPV6 | ICE_FLOW_SEG_HDR_IPV_OTHER); break; case ICE_FLTR_PTYPE_NONF_IPV6_PFCP_SESSION: ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_PFCP_SESSION | ICE_FLOW_SEG_HDR_IPV6 | ICE_FLOW_SEG_HDR_IPV_OTHER); break; case ICE_FLTR_PTYPE_NONF_IPV6_OTHER: ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_IPV6 | ICE_FLOW_SEG_HDR_IPV_OTHER); break; case ICE_FLTR_PTYPE_NONF_IPV6_TCP: ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_TCP | ICE_FLOW_SEG_HDR_IPV6 | ICE_FLOW_SEG_HDR_IPV_OTHER); break; case ICE_FLTR_PTYPE_NONF_IPV6_UDP: ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_UDP | ICE_FLOW_SEG_HDR_IPV6 | ICE_FLOW_SEG_HDR_IPV_OTHER); break; case ICE_FLTR_PTYPE_NONF_IPV6_SCTP: ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_SCTP | ICE_FLOW_SEG_HDR_IPV6 | ICE_FLOW_SEG_HDR_IPV_OTHER); break; default: dev_dbg(dev, "Invalid flow type 0x%x for VF %d failed\n", flow, vf->vf_id); return -EINVAL; } return 0; } /** * ice_vc_fdir_rem_prof - remove profile for this filter flow type * @vf: pointer to the VF structure * @flow: filter flow type * @tun: 0 implies non-tunnel type filter, 1 implies tunnel type filter */ static void ice_vc_fdir_rem_prof(struct ice_vf *vf, enum ice_fltr_ptype flow, int tun) { struct ice_vf_fdir *fdir = &vf->fdir; struct ice_fd_hw_prof *vf_prof; struct ice_pf *pf = vf->pf; struct ice_vsi *vf_vsi; struct device *dev; struct ice_hw *hw; u64 prof_id; int i; dev = ice_pf_to_dev(pf); hw = &pf->hw; if (!fdir->fdir_prof || !fdir->fdir_prof[flow]) return; vf_prof = fdir->fdir_prof[flow]; vf_vsi = ice_get_vf_vsi(vf); if (!vf_vsi) { dev_dbg(dev, "NULL vf %d vsi pointer\n", vf->vf_id); return; } if (!fdir->prof_entry_cnt[flow][tun]) return; prof_id = ICE_FLOW_PROF_FD(vf_vsi->vsi_num, flow, tun ? ICE_FLTR_PTYPE_MAX : 0); for (i = 0; i < fdir->prof_entry_cnt[flow][tun]; i++) if (vf_prof->entry_h[i][tun]) { u16 vsi_num = ice_get_hw_vsi_num(hw, vf_prof->vsi_h[i]); ice_rem_prof_id_flow(hw, ICE_BLK_FD, vsi_num, prof_id); ice_flow_rem_entry(hw, ICE_BLK_FD, vf_prof->entry_h[i][tun]); vf_prof->entry_h[i][tun] = 0; } ice_flow_rem_prof(hw, ICE_BLK_FD, prof_id); devm_kfree(dev, vf_prof->fdir_seg[tun]); vf_prof->fdir_seg[tun] = NULL; for (i = 0; i < vf_prof->cnt; i++) vf_prof->vsi_h[i] = 0; fdir->prof_entry_cnt[flow][tun] = 0; } /** * ice_vc_fdir_rem_prof_all - remove profile for this VF * @vf: pointer to the VF structure */ static void ice_vc_fdir_rem_prof_all(struct ice_vf *vf) { enum ice_fltr_ptype flow; for (flow = ICE_FLTR_PTYPE_NONF_NONE; flow < ICE_FLTR_PTYPE_MAX; flow++) { ice_vc_fdir_rem_prof(vf, flow, 0); ice_vc_fdir_rem_prof(vf, flow, 1); } } /** * ice_vc_fdir_reset_cnt_all - reset all FDIR counters for this VF FDIR * @fdir: pointer to the VF FDIR structure */ static void ice_vc_fdir_reset_cnt_all(struct ice_vf_fdir *fdir) { enum ice_fltr_ptype flow; for (flow = ICE_FLTR_PTYPE_NONF_NONE; flow < ICE_FLTR_PTYPE_MAX; flow++) { fdir->fdir_fltr_cnt[flow][0] = 0; fdir->fdir_fltr_cnt[flow][1] = 0; } } /** * ice_vc_fdir_has_prof_conflict * @vf: pointer to the VF structure * @conf: FDIR configuration for each filter * * Check if @conf has conflicting profile with existing profiles * * Return: true on success, and false on error. */ static bool ice_vc_fdir_has_prof_conflict(struct ice_vf *vf, struct virtchnl_fdir_fltr_conf *conf) { struct ice_fdir_fltr *desc; list_for_each_entry(desc, &vf->fdir.fdir_rule_list, fltr_node) { struct virtchnl_fdir_fltr_conf *existing_conf; enum ice_fltr_ptype flow_type_a, flow_type_b; struct ice_fdir_fltr *a, *b; existing_conf = to_fltr_conf_from_desc(desc); a = &existing_conf->input; b = &conf->input; flow_type_a = a->flow_type; flow_type_b = b->flow_type; /* No need to compare two rules with different tunnel types or * with the same protocol type. */ if (existing_conf->ttype != conf->ttype || flow_type_a == flow_type_b) continue; switch (flow_type_a) { case ICE_FLTR_PTYPE_NONF_IPV4_UDP: case ICE_FLTR_PTYPE_NONF_IPV4_TCP: case ICE_FLTR_PTYPE_NONF_IPV4_SCTP: if (flow_type_b == ICE_FLTR_PTYPE_NONF_IPV4_OTHER) return true; break; case ICE_FLTR_PTYPE_NONF_IPV4_OTHER: if (flow_type_b == ICE_FLTR_PTYPE_NONF_IPV4_UDP || flow_type_b == ICE_FLTR_PTYPE_NONF_IPV4_TCP || flow_type_b == ICE_FLTR_PTYPE_NONF_IPV4_SCTP) return true; break; case ICE_FLTR_PTYPE_NONF_IPV6_UDP: case ICE_FLTR_PTYPE_NONF_IPV6_TCP: case ICE_FLTR_PTYPE_NONF_IPV6_SCTP: if (flow_type_b == ICE_FLTR_PTYPE_NONF_IPV6_OTHER) return true; break; case ICE_FLTR_PTYPE_NONF_IPV6_OTHER: if (flow_type_b == ICE_FLTR_PTYPE_NONF_IPV6_UDP || flow_type_b == ICE_FLTR_PTYPE_NONF_IPV6_TCP || flow_type_b == ICE_FLTR_PTYPE_NONF_IPV6_SCTP) return true; break; default: break; } } return false; } /** * ice_vc_fdir_write_flow_prof * @vf: pointer to the VF structure * @flow: filter flow type * @seg: array of one or more packet segments that describe the flow * @tun: 0 implies non-tunnel type filter, 1 implies tunnel type filter * * Write the flow's profile config and packet segment into the hardware * * Return: 0 on success, and other on error. */ static int ice_vc_fdir_write_flow_prof(struct ice_vf *vf, enum ice_fltr_ptype flow, struct ice_flow_seg_info *seg, int tun) { struct ice_vf_fdir *fdir = &vf->fdir; struct ice_vsi *vf_vsi, *ctrl_vsi; struct ice_flow_seg_info *old_seg; struct ice_flow_prof *prof = NULL; struct ice_fd_hw_prof *vf_prof; struct device *dev; struct ice_pf *pf; struct ice_hw *hw; u64 entry1_h = 0; u64 entry2_h = 0; u64 prof_id; int ret; pf = vf->pf; dev = ice_pf_to_dev(pf); hw = &pf->hw; vf_vsi = ice_get_vf_vsi(vf); if (!vf_vsi) return -EINVAL; ctrl_vsi = pf->vsi[vf->ctrl_vsi_idx]; if (!ctrl_vsi) return -EINVAL; vf_prof = fdir->fdir_prof[flow]; old_seg = vf_prof->fdir_seg[tun]; if (old_seg) { if (!memcmp(old_seg, seg, sizeof(*seg))) { dev_dbg(dev, "Duplicated profile for VF %d!\n", vf->vf_id); return -EEXIST; } if (fdir->fdir_fltr_cnt[flow][tun]) { ret = -EINVAL; dev_dbg(dev, "Input set conflicts for VF %d\n", vf->vf_id); goto err_exit; } /* remove previously allocated profile */ ice_vc_fdir_rem_prof(vf, flow, tun); } prof_id = ICE_FLOW_PROF_FD(vf_vsi->vsi_num, flow, tun ? ICE_FLTR_PTYPE_MAX : 0); ret = ice_flow_add_prof(hw, ICE_BLK_FD, ICE_FLOW_RX, prof_id, seg, tun + 1, &prof); if (ret) { dev_dbg(dev, "Could not add VSI flow 0x%x for VF %d\n", flow, vf->vf_id); goto err_exit; } ret = ice_flow_add_entry(hw, ICE_BLK_FD, prof_id, vf_vsi->idx, vf_vsi->idx, ICE_FLOW_PRIO_NORMAL, seg, &entry1_h); if (ret) { dev_dbg(dev, "Could not add flow 0x%x VSI entry for VF %d\n", flow, vf->vf_id); goto err_prof; } ret = ice_flow_add_entry(hw, ICE_BLK_FD, prof_id, vf_vsi->idx, ctrl_vsi->idx, ICE_FLOW_PRIO_NORMAL, seg, &entry2_h); if (ret) { dev_dbg(dev, "Could not add flow 0x%x Ctrl VSI entry for VF %d\n", flow, vf->vf_id); goto err_entry_1; } vf_prof->fdir_seg[tun] = seg; vf_prof->cnt = 0; fdir->prof_entry_cnt[flow][tun] = 0; vf_prof->entry_h[vf_prof->cnt][tun] = entry1_h; vf_prof->vsi_h[vf_prof->cnt] = vf_vsi->idx; vf_prof->cnt++; fdir->prof_entry_cnt[flow][tun]++; vf_prof->entry_h[vf_prof->cnt][tun] = entry2_h; vf_prof->vsi_h[vf_prof->cnt] = ctrl_vsi->idx; vf_prof->cnt++; fdir->prof_entry_cnt[flow][tun]++; return 0; err_entry_1: ice_rem_prof_id_flow(hw, ICE_BLK_FD, ice_get_hw_vsi_num(hw, vf_vsi->idx), prof_id); ice_flow_rem_entry(hw, ICE_BLK_FD, entry1_h); err_prof: ice_flow_rem_prof(hw, ICE_BLK_FD, prof_id); err_exit: return ret; } /** * ice_vc_fdir_config_input_set * @vf: pointer to the VF structure * @fltr: virtual channel add cmd buffer * @conf: FDIR configuration for each filter * @tun: 0 implies non-tunnel type filter, 1 implies tunnel type filter * * Config the input set type and value for virtual channel add msg buffer * * Return: 0 on success, and other on error. */ static int ice_vc_fdir_config_input_set(struct ice_vf *vf, struct virtchnl_fdir_add *fltr, struct virtchnl_fdir_fltr_conf *conf, int tun) { struct ice_fdir_fltr *input = &conf->input; struct device *dev = ice_pf_to_dev(vf->pf); struct ice_flow_seg_info *seg; enum ice_fltr_ptype flow; int ret; ret = ice_vc_fdir_has_prof_conflict(vf, conf); if (ret) { dev_dbg(dev, "Found flow profile conflict for VF %d\n", vf->vf_id); return ret; } flow = input->flow_type; ret = ice_vc_fdir_alloc_prof(vf, flow); if (ret) { dev_dbg(dev, "Alloc flow prof for VF %d failed\n", vf->vf_id); return ret; } seg = devm_kzalloc(dev, sizeof(*seg), GFP_KERNEL); if (!seg) return -ENOMEM; ret = ice_vc_fdir_set_flow_fld(vf, fltr, conf, seg); if (ret) { dev_dbg(dev, "Set flow field for VF %d failed\n", vf->vf_id); goto err_exit; } ret = ice_vc_fdir_set_flow_hdr(vf, conf, seg); if (ret) { dev_dbg(dev, "Set flow hdr for VF %d failed\n", vf->vf_id); goto err_exit; } ret = ice_vc_fdir_write_flow_prof(vf, flow, seg, tun); if (ret == -EEXIST) { devm_kfree(dev, seg); } else if (ret) { dev_dbg(dev, "Write flow profile for VF %d failed\n", vf->vf_id); goto err_exit; } return 0; err_exit: devm_kfree(dev, seg); return ret; } /** * ice_vc_fdir_parse_pattern * @vf: pointer to the VF info * @fltr: virtual channel add cmd buffer * @conf: FDIR configuration for each filter * * Parse the virtual channel filter's pattern and store them into conf * * Return: 0 on success, and other on error. */ static int ice_vc_fdir_parse_pattern(struct ice_vf *vf, struct virtchnl_fdir_add *fltr, struct virtchnl_fdir_fltr_conf *conf) { struct virtchnl_proto_hdrs *proto = &fltr->rule_cfg.proto_hdrs; enum virtchnl_proto_hdr_type l3 = VIRTCHNL_PROTO_HDR_NONE; enum virtchnl_proto_hdr_type l4 = VIRTCHNL_PROTO_HDR_NONE; struct device *dev = ice_pf_to_dev(vf->pf); struct ice_fdir_fltr *input = &conf->input; int i; if (proto->count > VIRTCHNL_MAX_NUM_PROTO_HDRS) { dev_dbg(dev, "Invalid protocol count:0x%x for VF %d\n", proto->count, vf->vf_id); return -EINVAL; } for (i = 0; i < proto->count; i++) { struct virtchnl_proto_hdr *hdr = &proto->proto_hdr[i]; struct ip_esp_hdr *esph; struct ip_auth_hdr *ah; struct sctphdr *sctph; struct ipv6hdr *ip6h; struct udphdr *udph; struct tcphdr *tcph; struct ethhdr *eth; struct iphdr *iph; u8 s_field; u8 *rawh; switch (hdr->type) { case VIRTCHNL_PROTO_HDR_ETH: eth = (struct ethhdr *)hdr->buffer; input->flow_type = ICE_FLTR_PTYPE_NON_IP_L2; if (hdr->field_selector) input->ext_data.ether_type = eth->h_proto; break; case VIRTCHNL_PROTO_HDR_IPV4: iph = (struct iphdr *)hdr->buffer; l3 = VIRTCHNL_PROTO_HDR_IPV4; input->flow_type = ICE_FLTR_PTYPE_NONF_IPV4_OTHER; if (hdr->field_selector) { input->ip.v4.src_ip = iph->saddr; input->ip.v4.dst_ip = iph->daddr; input->ip.v4.tos = iph->tos; input->ip.v4.proto = iph->protocol; } break; case VIRTCHNL_PROTO_HDR_IPV6: ip6h = (struct ipv6hdr *)hdr->buffer; l3 = VIRTCHNL_PROTO_HDR_IPV6; input->flow_type = ICE_FLTR_PTYPE_NONF_IPV6_OTHER; if (hdr->field_selector) { memcpy(input->ip.v6.src_ip, ip6h->saddr.in6_u.u6_addr8, sizeof(ip6h->saddr)); memcpy(input->ip.v6.dst_ip, ip6h->daddr.in6_u.u6_addr8, sizeof(ip6h->daddr)); input->ip.v6.tc = ((u8)(ip6h->priority) << 4) | (ip6h->flow_lbl[0] >> 4); input->ip.v6.proto = ip6h->nexthdr; } break; case VIRTCHNL_PROTO_HDR_TCP: tcph = (struct tcphdr *)hdr->buffer; if (l3 == VIRTCHNL_PROTO_HDR_IPV4) input->flow_type = ICE_FLTR_PTYPE_NONF_IPV4_TCP; else if (l3 == VIRTCHNL_PROTO_HDR_IPV6) input->flow_type = ICE_FLTR_PTYPE_NONF_IPV6_TCP; if (hdr->field_selector) { if (l3 == VIRTCHNL_PROTO_HDR_IPV4) { input->ip.v4.src_port = tcph->source; input->ip.v4.dst_port = tcph->dest; } else if (l3 == VIRTCHNL_PROTO_HDR_IPV6) { input->ip.v6.src_port = tcph->source; input->ip.v6.dst_port = tcph->dest; } } break; case VIRTCHNL_PROTO_HDR_UDP: udph = (struct udphdr *)hdr->buffer; if (l3 == VIRTCHNL_PROTO_HDR_IPV4) input->flow_type = ICE_FLTR_PTYPE_NONF_IPV4_UDP; else if (l3 == VIRTCHNL_PROTO_HDR_IPV6) input->flow_type = ICE_FLTR_PTYPE_NONF_IPV6_UDP; if (hdr->field_selector) { if (l3 == VIRTCHNL_PROTO_HDR_IPV4) { input->ip.v4.src_port = udph->source; input->ip.v4.dst_port = udph->dest; } else if (l3 == VIRTCHNL_PROTO_HDR_IPV6) { input->ip.v6.src_port = udph->source; input->ip.v6.dst_port = udph->dest; } } break; case VIRTCHNL_PROTO_HDR_SCTP: sctph = (struct sctphdr *)hdr->buffer; if (l3 == VIRTCHNL_PROTO_HDR_IPV4) input->flow_type = ICE_FLTR_PTYPE_NONF_IPV4_SCTP; else if (l3 == VIRTCHNL_PROTO_HDR_IPV6) input->flow_type = ICE_FLTR_PTYPE_NONF_IPV6_SCTP; if (hdr->field_selector) { if (l3 == VIRTCHNL_PROTO_HDR_IPV4) { input->ip.v4.src_port = sctph->source; input->ip.v4.dst_port = sctph->dest; } else if (l3 == VIRTCHNL_PROTO_HDR_IPV6) { input->ip.v6.src_port = sctph->source; input->ip.v6.dst_port = sctph->dest; } } break; case VIRTCHNL_PROTO_HDR_L2TPV3: if (l3 == VIRTCHNL_PROTO_HDR_IPV4) input->flow_type = ICE_FLTR_PTYPE_NONF_IPV4_L2TPV3; else if (l3 == VIRTCHNL_PROTO_HDR_IPV6) input->flow_type = ICE_FLTR_PTYPE_NONF_IPV6_L2TPV3; if (hdr->field_selector) input->l2tpv3_data.session_id = *((__be32 *)hdr->buffer); break; case VIRTCHNL_PROTO_HDR_ESP: esph = (struct ip_esp_hdr *)hdr->buffer; if (l3 == VIRTCHNL_PROTO_HDR_IPV4 && l4 == VIRTCHNL_PROTO_HDR_UDP) input->flow_type = ICE_FLTR_PTYPE_NONF_IPV4_NAT_T_ESP; else if (l3 == VIRTCHNL_PROTO_HDR_IPV6 && l4 == VIRTCHNL_PROTO_HDR_UDP) input->flow_type = ICE_FLTR_PTYPE_NONF_IPV6_NAT_T_ESP; else if (l3 == VIRTCHNL_PROTO_HDR_IPV4 && l4 == VIRTCHNL_PROTO_HDR_NONE) input->flow_type = ICE_FLTR_PTYPE_NONF_IPV4_ESP; else if (l3 == VIRTCHNL_PROTO_HDR_IPV6 && l4 == VIRTCHNL_PROTO_HDR_NONE) input->flow_type = ICE_FLTR_PTYPE_NONF_IPV6_ESP; if (l4 == VIRTCHNL_PROTO_HDR_UDP) conf->inset_flag |= FDIR_INSET_FLAG_ESP_UDP; else conf->inset_flag |= FDIR_INSET_FLAG_ESP_IPSEC; if (hdr->field_selector) { if (l3 == VIRTCHNL_PROTO_HDR_IPV4) input->ip.v4.sec_parm_idx = esph->spi; else if (l3 == VIRTCHNL_PROTO_HDR_IPV6) input->ip.v6.sec_parm_idx = esph->spi; } break; case VIRTCHNL_PROTO_HDR_AH: ah = (struct ip_auth_hdr *)hdr->buffer; if (l3 == VIRTCHNL_PROTO_HDR_IPV4) input->flow_type = ICE_FLTR_PTYPE_NONF_IPV4_AH; else if (l3 == VIRTCHNL_PROTO_HDR_IPV6) input->flow_type = ICE_FLTR_PTYPE_NONF_IPV6_AH; if (hdr->field_selector) { if (l3 == VIRTCHNL_PROTO_HDR_IPV4) input->ip.v4.sec_parm_idx = ah->spi; else if (l3 == VIRTCHNL_PROTO_HDR_IPV6) input->ip.v6.sec_parm_idx = ah->spi; } break; case VIRTCHNL_PROTO_HDR_PFCP: rawh = (u8 *)hdr->buffer; s_field = (rawh[0] >> PFCP_S_OFFSET) & PFCP_S_MASK; if (l3 == VIRTCHNL_PROTO_HDR_IPV4 && s_field == 0) input->flow_type = ICE_FLTR_PTYPE_NONF_IPV4_PFCP_NODE; else if (l3 == VIRTCHNL_PROTO_HDR_IPV4 && s_field == 1) input->flow_type = ICE_FLTR_PTYPE_NONF_IPV4_PFCP_SESSION; else if (l3 == VIRTCHNL_PROTO_HDR_IPV6 && s_field == 0) input->flow_type = ICE_FLTR_PTYPE_NONF_IPV6_PFCP_NODE; else if (l3 == VIRTCHNL_PROTO_HDR_IPV6 && s_field == 1) input->flow_type = ICE_FLTR_PTYPE_NONF_IPV6_PFCP_SESSION; if (hdr->field_selector) { if (l3 == VIRTCHNL_PROTO_HDR_IPV4) input->ip.v4.dst_port = cpu_to_be16(PFCP_PORT_NR); else if (l3 == VIRTCHNL_PROTO_HDR_IPV6) input->ip.v6.dst_port = cpu_to_be16(PFCP_PORT_NR); } break; case VIRTCHNL_PROTO_HDR_GTPU_IP: rawh = (u8 *)hdr->buffer; input->flow_type = ICE_FLTR_PTYPE_NONF_IPV4_GTPU_IPV4_OTHER; if (hdr->field_selector) input->gtpu_data.teid = *(__be32 *)(&rawh[GTPU_TEID_OFFSET]); conf->ttype = ICE_FDIR_TUNNEL_TYPE_GTPU; break; case VIRTCHNL_PROTO_HDR_GTPU_EH: rawh = (u8 *)hdr->buffer; if (hdr->field_selector) input->gtpu_data.qfi = rawh[GTPU_EH_QFI_OFFSET] & GTPU_EH_QFI_MASK; conf->ttype = ICE_FDIR_TUNNEL_TYPE_GTPU_EH; break; default: dev_dbg(dev, "Invalid header type 0x:%x for VF %d\n", hdr->type, vf->vf_id); return -EINVAL; } } return 0; } /** * ice_vc_fdir_parse_action * @vf: pointer to the VF info * @fltr: virtual channel add cmd buffer * @conf: FDIR configuration for each filter * * Parse the virtual channel filter's action and store them into conf * * Return: 0 on success, and other on error. */ static int ice_vc_fdir_parse_action(struct ice_vf *vf, struct virtchnl_fdir_add *fltr, struct virtchnl_fdir_fltr_conf *conf) { struct virtchnl_filter_action_set *as = &fltr->rule_cfg.action_set; struct device *dev = ice_pf_to_dev(vf->pf); struct ice_fdir_fltr *input = &conf->input; u32 dest_num = 0; u32 mark_num = 0; int i; if (as->count > VIRTCHNL_MAX_NUM_ACTIONS) { dev_dbg(dev, "Invalid action numbers:0x%x for VF %d\n", as->count, vf->vf_id); return -EINVAL; } for (i = 0; i < as->count; i++) { struct virtchnl_filter_action *action = &as->actions[i]; switch (action->type) { case VIRTCHNL_ACTION_PASSTHRU: dest_num++; input->dest_ctl = ICE_FLTR_PRGM_DESC_DEST_DIRECT_PKT_OTHER; break; case VIRTCHNL_ACTION_DROP: dest_num++; input->dest_ctl = ICE_FLTR_PRGM_DESC_DEST_DROP_PKT; break; case VIRTCHNL_ACTION_QUEUE: dest_num++; input->dest_ctl = ICE_FLTR_PRGM_DESC_DEST_DIRECT_PKT_QINDEX; input->q_index = action->act_conf.queue.index; break; case VIRTCHNL_ACTION_Q_REGION: dest_num++; input->dest_ctl = ICE_FLTR_PRGM_DESC_DEST_DIRECT_PKT_QGROUP; input->q_index = action->act_conf.queue.index; input->q_region = action->act_conf.queue.region; break; case VIRTCHNL_ACTION_MARK: mark_num++; input->fltr_id = action->act_conf.mark_id; input->fdid_prio = ICE_FXD_FLTR_QW1_FDID_PRI_THREE; break; default: dev_dbg(dev, "Invalid action type:0x%x for VF %d\n", action->type, vf->vf_id); return -EINVAL; } } if (dest_num == 0 || dest_num >= 2) { dev_dbg(dev, "Invalid destination action for VF %d\n", vf->vf_id); return -EINVAL; } if (mark_num >= 2) { dev_dbg(dev, "Too many mark actions for VF %d\n", vf->vf_id); return -EINVAL; } return 0; } /** * ice_vc_validate_fdir_fltr - validate the virtual channel filter * @vf: pointer to the VF info * @fltr: virtual channel add cmd buffer * @conf: FDIR configuration for each filter * * Return: 0 on success, and other on error. */ static int ice_vc_validate_fdir_fltr(struct ice_vf *vf, struct virtchnl_fdir_add *fltr, struct virtchnl_fdir_fltr_conf *conf) { struct virtchnl_proto_hdrs *proto = &fltr->rule_cfg.proto_hdrs; int ret; if (!ice_vc_validate_pattern(vf, proto)) return -EINVAL; ret = ice_vc_fdir_parse_pattern(vf, fltr, conf); if (ret) return ret; return ice_vc_fdir_parse_action(vf, fltr, conf); } /** * ice_vc_fdir_comp_rules - compare if two filter rules have the same value * @conf_a: FDIR configuration for filter a * @conf_b: FDIR configuration for filter b * * Return: 0 on success, and other on error. */ static bool ice_vc_fdir_comp_rules(struct virtchnl_fdir_fltr_conf *conf_a, struct virtchnl_fdir_fltr_conf *conf_b) { struct ice_fdir_fltr *a = &conf_a->input; struct ice_fdir_fltr *b = &conf_b->input; if (conf_a->ttype != conf_b->ttype) return false; if (a->flow_type != b->flow_type) return false; if (memcmp(&a->ip, &b->ip, sizeof(a->ip))) return false; if (memcmp(&a->mask, &b->mask, sizeof(a->mask))) return false; if (memcmp(&a->gtpu_data, &b->gtpu_data, sizeof(a->gtpu_data))) return false; if (memcmp(&a->gtpu_mask, &b->gtpu_mask, sizeof(a->gtpu_mask))) return false; if (memcmp(&a->l2tpv3_data, &b->l2tpv3_data, sizeof(a->l2tpv3_data))) return false; if (memcmp(&a->l2tpv3_mask, &b->l2tpv3_mask, sizeof(a->l2tpv3_mask))) return false; if (memcmp(&a->ext_data, &b->ext_data, sizeof(a->ext_data))) return false; if (memcmp(&a->ext_mask, &b->ext_mask, sizeof(a->ext_mask))) return false; return true; } /** * ice_vc_fdir_is_dup_fltr * @vf: pointer to the VF info * @conf: FDIR configuration for each filter * * Check if there is duplicated rule with same conf value * * Return: 0 true success, and false on error. */ static bool ice_vc_fdir_is_dup_fltr(struct ice_vf *vf, struct virtchnl_fdir_fltr_conf *conf) { struct ice_fdir_fltr *desc; bool ret; list_for_each_entry(desc, &vf->fdir.fdir_rule_list, fltr_node) { struct virtchnl_fdir_fltr_conf *node = to_fltr_conf_from_desc(desc); ret = ice_vc_fdir_comp_rules(node, conf); if (ret) return true; } return false; } /** * ice_vc_fdir_insert_entry * @vf: pointer to the VF info * @conf: FDIR configuration for each filter * @id: pointer to ID value allocated by driver * * Insert FDIR conf entry into list and allocate ID for this filter * * Return: 0 true success, and other on error. */ static int ice_vc_fdir_insert_entry(struct ice_vf *vf, struct virtchnl_fdir_fltr_conf *conf, u32 *id) { struct ice_fdir_fltr *input = &conf->input; int i; /* alloc ID corresponding with conf */ i = idr_alloc(&vf->fdir.fdir_rule_idr, conf, 0, ICE_FDIR_MAX_FLTRS, GFP_KERNEL); if (i < 0) return -EINVAL; *id = i; list_add(&input->fltr_node, &vf->fdir.fdir_rule_list); return 0; } /** * ice_vc_fdir_remove_entry - remove FDIR conf entry by ID value * @vf: pointer to the VF info * @conf: FDIR configuration for each filter * @id: filter rule's ID */ static void ice_vc_fdir_remove_entry(struct ice_vf *vf, struct virtchnl_fdir_fltr_conf *conf, u32 id) { struct ice_fdir_fltr *input = &conf->input; idr_remove(&vf->fdir.fdir_rule_idr, id); list_del(&input->fltr_node); } /** * ice_vc_fdir_lookup_entry - lookup FDIR conf entry by ID value * @vf: pointer to the VF info * @id: filter rule's ID * * Return: NULL on error, and other on success. */ static struct virtchnl_fdir_fltr_conf * ice_vc_fdir_lookup_entry(struct ice_vf *vf, u32 id) { return idr_find(&vf->fdir.fdir_rule_idr, id); } /** * ice_vc_fdir_flush_entry - remove all FDIR conf entry * @vf: pointer to the VF info */ static void ice_vc_fdir_flush_entry(struct ice_vf *vf) { struct virtchnl_fdir_fltr_conf *conf; struct ice_fdir_fltr *desc, *temp; list_for_each_entry_safe(desc, temp, &vf->fdir.fdir_rule_list, fltr_node) { conf = to_fltr_conf_from_desc(desc); list_del(&desc->fltr_node); devm_kfree(ice_pf_to_dev(vf->pf), conf); } } /** * ice_vc_fdir_write_fltr - write filter rule into hardware * @vf: pointer to the VF info * @conf: FDIR configuration for each filter * @add: true implies add rule, false implies del rules * @is_tun: false implies non-tunnel type filter, true implies tunnel filter * * Return: 0 on success, and other on error. */ static int ice_vc_fdir_write_fltr(struct ice_vf *vf, struct virtchnl_fdir_fltr_conf *conf, bool add, bool is_tun) { struct ice_fdir_fltr *input = &conf->input; struct ice_vsi *vsi, *ctrl_vsi; struct ice_fltr_desc desc; struct device *dev; struct ice_pf *pf; struct ice_hw *hw; int ret; u8 *pkt; pf = vf->pf; dev = ice_pf_to_dev(pf); hw = &pf->hw; vsi = ice_get_vf_vsi(vf); if (!vsi) { dev_dbg(dev, "Invalid vsi for VF %d\n", vf->vf_id); return -EINVAL; } input->dest_vsi = vsi->idx; input->comp_report = ICE_FXD_FLTR_QW0_COMP_REPORT_SW; ctrl_vsi = pf->vsi[vf->ctrl_vsi_idx]; if (!ctrl_vsi) { dev_dbg(dev, "Invalid ctrl_vsi for VF %d\n", vf->vf_id); return -EINVAL; } pkt = devm_kzalloc(dev, ICE_FDIR_MAX_RAW_PKT_SIZE, GFP_KERNEL); if (!pkt) return -ENOMEM; ice_fdir_get_prgm_desc(hw, input, &desc, add); ret = ice_fdir_get_gen_prgm_pkt(hw, input, pkt, false, is_tun); if (ret) { dev_dbg(dev, "Gen training pkt for VF %d ptype %d failed\n", vf->vf_id, input->flow_type); goto err_free_pkt; } ret = ice_prgm_fdir_fltr(ctrl_vsi, &desc, pkt); if (ret) goto err_free_pkt; return 0; err_free_pkt: devm_kfree(dev, pkt); return ret; } /** * ice_vf_fdir_timer - FDIR program waiting timer interrupt handler * @t: pointer to timer_list */ static void ice_vf_fdir_timer(struct timer_list *t) { struct ice_vf_fdir_ctx *ctx_irq = from_timer(ctx_irq, t, rx_tmr); struct ice_vf_fdir_ctx *ctx_done; struct ice_vf_fdir *fdir; unsigned long flags; struct ice_vf *vf; struct ice_pf *pf; fdir = container_of(ctx_irq, struct ice_vf_fdir, ctx_irq); vf = container_of(fdir, struct ice_vf, fdir); ctx_done = &fdir->ctx_done; pf = vf->pf; spin_lock_irqsave(&fdir->ctx_lock, flags); if (!(ctx_irq->flags & ICE_VF_FDIR_CTX_VALID)) { spin_unlock_irqrestore(&fdir->ctx_lock, flags); WARN_ON_ONCE(1); return; } ctx_irq->flags &= ~ICE_VF_FDIR_CTX_VALID; ctx_done->flags |= ICE_VF_FDIR_CTX_VALID; ctx_done->conf = ctx_irq->conf; ctx_done->stat = ICE_FDIR_CTX_TIMEOUT; ctx_done->v_opcode = ctx_irq->v_opcode; spin_unlock_irqrestore(&fdir->ctx_lock, flags); set_bit(ICE_FD_VF_FLUSH_CTX, pf->state); ice_service_task_schedule(pf); } /** * ice_vc_fdir_irq_handler - ctrl_vsi Rx queue interrupt handler * @ctrl_vsi: pointer to a VF's CTRL VSI * @rx_desc: pointer to FDIR Rx queue descriptor */ void ice_vc_fdir_irq_handler(struct ice_vsi *ctrl_vsi, union ice_32b_rx_flex_desc *rx_desc) { struct ice_pf *pf = ctrl_vsi->back; struct ice_vf *vf = ctrl_vsi->vf; struct ice_vf_fdir_ctx *ctx_done; struct ice_vf_fdir_ctx *ctx_irq; struct ice_vf_fdir *fdir; unsigned long flags; struct device *dev; int ret; if (WARN_ON(!vf)) return; fdir = &vf->fdir; ctx_done = &fdir->ctx_done; ctx_irq = &fdir->ctx_irq; dev = ice_pf_to_dev(pf); spin_lock_irqsave(&fdir->ctx_lock, flags); if (!(ctx_irq->flags & ICE_VF_FDIR_CTX_VALID)) { spin_unlock_irqrestore(&fdir->ctx_lock, flags); WARN_ON_ONCE(1); return; } ctx_irq->flags &= ~ICE_VF_FDIR_CTX_VALID; ctx_done->flags |= ICE_VF_FDIR_CTX_VALID; ctx_done->conf = ctx_irq->conf; ctx_done->stat = ICE_FDIR_CTX_IRQ; ctx_done->v_opcode = ctx_irq->v_opcode; memcpy(&ctx_done->rx_desc, rx_desc, sizeof(*rx_desc)); spin_unlock_irqrestore(&fdir->ctx_lock, flags); ret = del_timer(&ctx_irq->rx_tmr); if (!ret) dev_err(dev, "VF %d: Unexpected inactive timer!\n", vf->vf_id); set_bit(ICE_FD_VF_FLUSH_CTX, pf->state); ice_service_task_schedule(pf); } /** * ice_vf_fdir_dump_info - dump FDIR information for diagnosis * @vf: pointer to the VF info */ static void ice_vf_fdir_dump_info(struct ice_vf *vf) { struct ice_vsi *vf_vsi; u32 fd_size, fd_cnt; struct device *dev; struct ice_pf *pf; struct ice_hw *hw; u16 vsi_num; pf = vf->pf; hw = &pf->hw; dev = ice_pf_to_dev(pf); vf_vsi = ice_get_vf_vsi(vf); if (!vf_vsi) { dev_dbg(dev, "VF %d: invalid VSI pointer\n", vf->vf_id); return; } vsi_num = ice_get_hw_vsi_num(hw, vf_vsi->idx); fd_size = rd32(hw, VSIQF_FD_SIZE(vsi_num)); fd_cnt = rd32(hw, VSIQF_FD_CNT(vsi_num)); dev_dbg(dev, "VF %d: space allocated: guar:0x%x, be:0x%x, space consumed: guar:0x%x, be:0x%x\n", vf->vf_id, (fd_size & VSIQF_FD_CNT_FD_GCNT_M) >> VSIQF_FD_CNT_FD_GCNT_S, (fd_size & VSIQF_FD_CNT_FD_BCNT_M) >> VSIQF_FD_CNT_FD_BCNT_S, (fd_cnt & VSIQF_FD_CNT_FD_GCNT_M) >> VSIQF_FD_CNT_FD_GCNT_S, (fd_cnt & VSIQF_FD_CNT_FD_BCNT_M) >> VSIQF_FD_CNT_FD_BCNT_S); } /** * ice_vf_verify_rx_desc - verify received FDIR programming status descriptor * @vf: pointer to the VF info * @ctx: FDIR context info for post processing * @status: virtchnl FDIR program status * * Return: 0 on success, and other on error. */ static int ice_vf_verify_rx_desc(struct ice_vf *vf, struct ice_vf_fdir_ctx *ctx, enum virtchnl_fdir_prgm_status *status) { struct device *dev = ice_pf_to_dev(vf->pf); u32 stat_err, error, prog_id; int ret; stat_err = le16_to_cpu(ctx->rx_desc.wb.status_error0); if (((stat_err & ICE_FXD_FLTR_WB_QW1_DD_M) >> ICE_FXD_FLTR_WB_QW1_DD_S) != ICE_FXD_FLTR_WB_QW1_DD_YES) { *status = VIRTCHNL_FDIR_FAILURE_RULE_NORESOURCE; dev_err(dev, "VF %d: Desc Done not set\n", vf->vf_id); ret = -EINVAL; goto err_exit; } prog_id = (stat_err & ICE_FXD_FLTR_WB_QW1_PROG_ID_M) >> ICE_FXD_FLTR_WB_QW1_PROG_ID_S; if (prog_id == ICE_FXD_FLTR_WB_QW1_PROG_ADD && ctx->v_opcode != VIRTCHNL_OP_ADD_FDIR_FILTER) { dev_err(dev, "VF %d: Desc show add, but ctx not", vf->vf_id); *status = VIRTCHNL_FDIR_FAILURE_RULE_INVALID; ret = -EINVAL; goto err_exit; } if (prog_id == ICE_FXD_FLTR_WB_QW1_PROG_DEL && ctx->v_opcode != VIRTCHNL_OP_DEL_FDIR_FILTER) { dev_err(dev, "VF %d: Desc show del, but ctx not", vf->vf_id); *status = VIRTCHNL_FDIR_FAILURE_RULE_INVALID; ret = -EINVAL; goto err_exit; } error = (stat_err & ICE_FXD_FLTR_WB_QW1_FAIL_M) >> ICE_FXD_FLTR_WB_QW1_FAIL_S; if (error == ICE_FXD_FLTR_WB_QW1_FAIL_YES) { if (prog_id == ICE_FXD_FLTR_WB_QW1_PROG_ADD) { dev_err(dev, "VF %d, Failed to add FDIR rule due to no space in the table", vf->vf_id); *status = VIRTCHNL_FDIR_FAILURE_RULE_NORESOURCE; } else { dev_err(dev, "VF %d, Failed to remove FDIR rule, attempt to remove non-existent entry", vf->vf_id); *status = VIRTCHNL_FDIR_FAILURE_RULE_NONEXIST; } ret = -EINVAL; goto err_exit; } error = (stat_err & ICE_FXD_FLTR_WB_QW1_FAIL_PROF_M) >> ICE_FXD_FLTR_WB_QW1_FAIL_PROF_S; if (error == ICE_FXD_FLTR_WB_QW1_FAIL_PROF_YES) { dev_err(dev, "VF %d: Profile matching error", vf->vf_id); *status = VIRTCHNL_FDIR_FAILURE_RULE_NORESOURCE; ret = -EINVAL; goto err_exit; } *status = VIRTCHNL_FDIR_SUCCESS; return 0; err_exit: ice_vf_fdir_dump_info(vf); return ret; } /** * ice_vc_add_fdir_fltr_post * @vf: pointer to the VF structure * @ctx: FDIR context info for post processing * @status: virtchnl FDIR program status * @success: true implies success, false implies failure * * Post process for flow director add command. If success, then do post process * and send back success msg by virtchnl. Otherwise, do context reversion and * send back failure msg by virtchnl. * * Return: 0 on success, and other on error. */ static int ice_vc_add_fdir_fltr_post(struct ice_vf *vf, struct ice_vf_fdir_ctx *ctx, enum virtchnl_fdir_prgm_status status, bool success) { struct virtchnl_fdir_fltr_conf *conf = ctx->conf; struct device *dev = ice_pf_to_dev(vf->pf); enum virtchnl_status_code v_ret; struct virtchnl_fdir_add *resp; int ret, len, is_tun; v_ret = VIRTCHNL_STATUS_SUCCESS; len = sizeof(*resp); resp = kzalloc(len, GFP_KERNEL); if (!resp) { len = 0; v_ret = VIRTCHNL_STATUS_ERR_NO_MEMORY; dev_dbg(dev, "VF %d: Alloc resp buf fail", vf->vf_id); goto err_exit; } if (!success) goto err_exit; is_tun = 0; resp->status = status; resp->flow_id = conf->flow_id; vf->fdir.fdir_fltr_cnt[conf->input.flow_type][is_tun]++; ret = ice_vc_send_msg_to_vf(vf, ctx->v_opcode, v_ret, (u8 *)resp, len); kfree(resp); dev_dbg(dev, "VF %d: flow_id:0x%X, FDIR %s success!\n", vf->vf_id, conf->flow_id, (ctx->v_opcode == VIRTCHNL_OP_ADD_FDIR_FILTER) ? "add" : "del"); return ret; err_exit: if (resp) resp->status = status; ice_vc_fdir_remove_entry(vf, conf, conf->flow_id); devm_kfree(dev, conf); ret = ice_vc_send_msg_to_vf(vf, ctx->v_opcode, v_ret, (u8 *)resp, len); kfree(resp); return ret; } /** * ice_vc_del_fdir_fltr_post * @vf: pointer to the VF structure * @ctx: FDIR context info for post processing * @status: virtchnl FDIR program status * @success: true implies success, false implies failure * * Post process for flow director del command. If success, then do post process * and send back success msg by virtchnl. Otherwise, do context reversion and * send back failure msg by virtchnl. * * Return: 0 on success, and other on error. */ static int ice_vc_del_fdir_fltr_post(struct ice_vf *vf, struct ice_vf_fdir_ctx *ctx, enum virtchnl_fdir_prgm_status status, bool success) { struct virtchnl_fdir_fltr_conf *conf = ctx->conf; struct device *dev = ice_pf_to_dev(vf->pf); enum virtchnl_status_code v_ret; struct virtchnl_fdir_del *resp; int ret, len, is_tun; v_ret = VIRTCHNL_STATUS_SUCCESS; len = sizeof(*resp); resp = kzalloc(len, GFP_KERNEL); if (!resp) { len = 0; v_ret = VIRTCHNL_STATUS_ERR_NO_MEMORY; dev_dbg(dev, "VF %d: Alloc resp buf fail", vf->vf_id); goto err_exit; } if (!success) goto err_exit; is_tun = 0; resp->status = status; ice_vc_fdir_remove_entry(vf, conf, conf->flow_id); vf->fdir.fdir_fltr_cnt[conf->input.flow_type][is_tun]--; ret = ice_vc_send_msg_to_vf(vf, ctx->v_opcode, v_ret, (u8 *)resp, len); kfree(resp); dev_dbg(dev, "VF %d: flow_id:0x%X, FDIR %s success!\n", vf->vf_id, conf->flow_id, (ctx->v_opcode == VIRTCHNL_OP_ADD_FDIR_FILTER) ? "add" : "del"); devm_kfree(dev, conf); return ret; err_exit: if (resp) resp->status = status; if (success) devm_kfree(dev, conf); ret = ice_vc_send_msg_to_vf(vf, ctx->v_opcode, v_ret, (u8 *)resp, len); kfree(resp); return ret; } /** * ice_flush_fdir_ctx * @pf: pointer to the PF structure * * Flush all the pending event on ctx_done list and process them. */ void ice_flush_fdir_ctx(struct ice_pf *pf) { struct ice_vf *vf; unsigned int bkt; if (!test_and_clear_bit(ICE_FD_VF_FLUSH_CTX, pf->state)) return; mutex_lock(&pf->vfs.table_lock); ice_for_each_vf(pf, bkt, vf) { struct device *dev = ice_pf_to_dev(pf); enum virtchnl_fdir_prgm_status status; struct ice_vf_fdir_ctx *ctx; unsigned long flags; int ret; if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) continue; if (vf->ctrl_vsi_idx == ICE_NO_VSI) continue; ctx = &vf->fdir.ctx_done; spin_lock_irqsave(&vf->fdir.ctx_lock, flags); if (!(ctx->flags & ICE_VF_FDIR_CTX_VALID)) { spin_unlock_irqrestore(&vf->fdir.ctx_lock, flags); continue; } spin_unlock_irqrestore(&vf->fdir.ctx_lock, flags); WARN_ON(ctx->stat == ICE_FDIR_CTX_READY); if (ctx->stat == ICE_FDIR_CTX_TIMEOUT) { status = VIRTCHNL_FDIR_FAILURE_RULE_TIMEOUT; dev_err(dev, "VF %d: ctrl_vsi irq timeout\n", vf->vf_id); goto err_exit; } ret = ice_vf_verify_rx_desc(vf, ctx, &status); if (ret) goto err_exit; if (ctx->v_opcode == VIRTCHNL_OP_ADD_FDIR_FILTER) ice_vc_add_fdir_fltr_post(vf, ctx, status, true); else if (ctx->v_opcode == VIRTCHNL_OP_DEL_FDIR_FILTER) ice_vc_del_fdir_fltr_post(vf, ctx, status, true); else dev_err(dev, "VF %d: Unsupported opcode\n", vf->vf_id); spin_lock_irqsave(&vf->fdir.ctx_lock, flags); ctx->flags &= ~ICE_VF_FDIR_CTX_VALID; spin_unlock_irqrestore(&vf->fdir.ctx_lock, flags); continue; err_exit: if (ctx->v_opcode == VIRTCHNL_OP_ADD_FDIR_FILTER) ice_vc_add_fdir_fltr_post(vf, ctx, status, false); else if (ctx->v_opcode == VIRTCHNL_OP_DEL_FDIR_FILTER) ice_vc_del_fdir_fltr_post(vf, ctx, status, false); else dev_err(dev, "VF %d: Unsupported opcode\n", vf->vf_id); spin_lock_irqsave(&vf->fdir.ctx_lock, flags); ctx->flags &= ~ICE_VF_FDIR_CTX_VALID; spin_unlock_irqrestore(&vf->fdir.ctx_lock, flags); } mutex_unlock(&pf->vfs.table_lock); } /** * ice_vc_fdir_set_irq_ctx - set FDIR context info for later IRQ handler * @vf: pointer to the VF structure * @conf: FDIR configuration for each filter * @v_opcode: virtual channel operation code * * Return: 0 on success, and other on error. */ static int ice_vc_fdir_set_irq_ctx(struct ice_vf *vf, struct virtchnl_fdir_fltr_conf *conf, enum virtchnl_ops v_opcode) { struct device *dev = ice_pf_to_dev(vf->pf); struct ice_vf_fdir_ctx *ctx; unsigned long flags; ctx = &vf->fdir.ctx_irq; spin_lock_irqsave(&vf->fdir.ctx_lock, flags); if ((vf->fdir.ctx_irq.flags & ICE_VF_FDIR_CTX_VALID) || (vf->fdir.ctx_done.flags & ICE_VF_FDIR_CTX_VALID)) { spin_unlock_irqrestore(&vf->fdir.ctx_lock, flags); dev_dbg(dev, "VF %d: Last request is still in progress\n", vf->vf_id); return -EBUSY; } ctx->flags |= ICE_VF_FDIR_CTX_VALID; spin_unlock_irqrestore(&vf->fdir.ctx_lock, flags); ctx->conf = conf; ctx->v_opcode = v_opcode; ctx->stat = ICE_FDIR_CTX_READY; timer_setup(&ctx->rx_tmr, ice_vf_fdir_timer, 0); mod_timer(&ctx->rx_tmr, round_jiffies(msecs_to_jiffies(10) + jiffies)); return 0; } /** * ice_vc_fdir_clear_irq_ctx - clear FDIR context info for IRQ handler * @vf: pointer to the VF structure * * Return: 0 on success, and other on error. */ static void ice_vc_fdir_clear_irq_ctx(struct ice_vf *vf) { struct ice_vf_fdir_ctx *ctx = &vf->fdir.ctx_irq; unsigned long flags; del_timer(&ctx->rx_tmr); spin_lock_irqsave(&vf->fdir.ctx_lock, flags); ctx->flags &= ~ICE_VF_FDIR_CTX_VALID; spin_unlock_irqrestore(&vf->fdir.ctx_lock, flags); } /** * ice_vc_add_fdir_fltr - add a FDIR filter for VF by the msg buffer * @vf: pointer to the VF info * @msg: pointer to the msg buffer * * Return: 0 on success, and other on error. */ int ice_vc_add_fdir_fltr(struct ice_vf *vf, u8 *msg) { struct virtchnl_fdir_add *fltr = (struct virtchnl_fdir_add *)msg; struct virtchnl_fdir_add *stat = NULL; struct virtchnl_fdir_fltr_conf *conf; enum virtchnl_status_code v_ret; struct device *dev; struct ice_pf *pf; int is_tun = 0; int len = 0; int ret; pf = vf->pf; dev = ice_pf_to_dev(pf); ret = ice_vc_fdir_param_check(vf, fltr->vsi_id); if (ret) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; dev_dbg(dev, "Parameter check for VF %d failed\n", vf->vf_id); goto err_exit; } ret = ice_vf_start_ctrl_vsi(vf); if (ret && (ret != -EEXIST)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; dev_err(dev, "Init FDIR for VF %d failed, ret:%d\n", vf->vf_id, ret); goto err_exit; } stat = kzalloc(sizeof(*stat), GFP_KERNEL); if (!stat) { v_ret = VIRTCHNL_STATUS_ERR_NO_MEMORY; dev_dbg(dev, "Alloc stat for VF %d failed\n", vf->vf_id); goto err_exit; } conf = devm_kzalloc(dev, sizeof(*conf), GFP_KERNEL); if (!conf) { v_ret = VIRTCHNL_STATUS_ERR_NO_MEMORY; dev_dbg(dev, "Alloc conf for VF %d failed\n", vf->vf_id); goto err_exit; } len = sizeof(*stat); ret = ice_vc_validate_fdir_fltr(vf, fltr, conf); if (ret) { v_ret = VIRTCHNL_STATUS_SUCCESS; stat->status = VIRTCHNL_FDIR_FAILURE_RULE_INVALID; dev_dbg(dev, "Invalid FDIR filter from VF %d\n", vf->vf_id); goto err_free_conf; } if (fltr->validate_only) { v_ret = VIRTCHNL_STATUS_SUCCESS; stat->status = VIRTCHNL_FDIR_SUCCESS; devm_kfree(dev, conf); ret = ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_ADD_FDIR_FILTER, v_ret, (u8 *)stat, len); goto exit; } ret = ice_vc_fdir_config_input_set(vf, fltr, conf, is_tun); if (ret) { v_ret = VIRTCHNL_STATUS_SUCCESS; stat->status = VIRTCHNL_FDIR_FAILURE_RULE_CONFLICT; dev_err(dev, "VF %d: FDIR input set configure failed, ret:%d\n", vf->vf_id, ret); goto err_free_conf; } ret = ice_vc_fdir_is_dup_fltr(vf, conf); if (ret) { v_ret = VIRTCHNL_STATUS_SUCCESS; stat->status = VIRTCHNL_FDIR_FAILURE_RULE_EXIST; dev_dbg(dev, "VF %d: duplicated FDIR rule detected\n", vf->vf_id); goto err_free_conf; } ret = ice_vc_fdir_insert_entry(vf, conf, &conf->flow_id); if (ret) { v_ret = VIRTCHNL_STATUS_SUCCESS; stat->status = VIRTCHNL_FDIR_FAILURE_RULE_NORESOURCE; dev_dbg(dev, "VF %d: insert FDIR list failed\n", vf->vf_id); goto err_free_conf; } ret = ice_vc_fdir_set_irq_ctx(vf, conf, VIRTCHNL_OP_ADD_FDIR_FILTER); if (ret) { v_ret = VIRTCHNL_STATUS_SUCCESS; stat->status = VIRTCHNL_FDIR_FAILURE_RULE_NORESOURCE; dev_dbg(dev, "VF %d: set FDIR context failed\n", vf->vf_id); goto err_rem_entry; } ret = ice_vc_fdir_write_fltr(vf, conf, true, is_tun); if (ret) { v_ret = VIRTCHNL_STATUS_SUCCESS; stat->status = VIRTCHNL_FDIR_FAILURE_RULE_NORESOURCE; dev_err(dev, "VF %d: writing FDIR rule failed, ret:%d\n", vf->vf_id, ret); goto err_clr_irq; } exit: kfree(stat); return ret; err_clr_irq: ice_vc_fdir_clear_irq_ctx(vf); err_rem_entry: ice_vc_fdir_remove_entry(vf, conf, conf->flow_id); err_free_conf: devm_kfree(dev, conf); err_exit: ret = ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_ADD_FDIR_FILTER, v_ret, (u8 *)stat, len); kfree(stat); return ret; } /** * ice_vc_del_fdir_fltr - delete a FDIR filter for VF by the msg buffer * @vf: pointer to the VF info * @msg: pointer to the msg buffer * * Return: 0 on success, and other on error. */ int ice_vc_del_fdir_fltr(struct ice_vf *vf, u8 *msg) { struct virtchnl_fdir_del *fltr = (struct virtchnl_fdir_del *)msg; struct virtchnl_fdir_del *stat = NULL; struct virtchnl_fdir_fltr_conf *conf; enum virtchnl_status_code v_ret; struct device *dev; struct ice_pf *pf; int is_tun = 0; int len = 0; int ret; pf = vf->pf; dev = ice_pf_to_dev(pf); ret = ice_vc_fdir_param_check(vf, fltr->vsi_id); if (ret) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; dev_dbg(dev, "Parameter check for VF %d failed\n", vf->vf_id); goto err_exit; } stat = kzalloc(sizeof(*stat), GFP_KERNEL); if (!stat) { v_ret = VIRTCHNL_STATUS_ERR_NO_MEMORY; dev_dbg(dev, "Alloc stat for VF %d failed\n", vf->vf_id); goto err_exit; } len = sizeof(*stat); conf = ice_vc_fdir_lookup_entry(vf, fltr->flow_id); if (!conf) { v_ret = VIRTCHNL_STATUS_SUCCESS; stat->status = VIRTCHNL_FDIR_FAILURE_RULE_NONEXIST; dev_dbg(dev, "VF %d: FDIR invalid flow_id:0x%X\n", vf->vf_id, fltr->flow_id); goto err_exit; } /* Just return failure when ctrl_vsi idx is invalid */ if (vf->ctrl_vsi_idx == ICE_NO_VSI) { v_ret = VIRTCHNL_STATUS_SUCCESS; stat->status = VIRTCHNL_FDIR_FAILURE_RULE_NORESOURCE; dev_err(dev, "Invalid FDIR ctrl_vsi for VF %d\n", vf->vf_id); goto err_exit; } ret = ice_vc_fdir_set_irq_ctx(vf, conf, VIRTCHNL_OP_DEL_FDIR_FILTER); if (ret) { v_ret = VIRTCHNL_STATUS_SUCCESS; stat->status = VIRTCHNL_FDIR_FAILURE_RULE_NORESOURCE; dev_dbg(dev, "VF %d: set FDIR context failed\n", vf->vf_id); goto err_exit; } ret = ice_vc_fdir_write_fltr(vf, conf, false, is_tun); if (ret) { v_ret = VIRTCHNL_STATUS_SUCCESS; stat->status = VIRTCHNL_FDIR_FAILURE_RULE_NORESOURCE; dev_err(dev, "VF %d: writing FDIR rule failed, ret:%d\n", vf->vf_id, ret); goto err_del_tmr; } kfree(stat); return ret; err_del_tmr: ice_vc_fdir_clear_irq_ctx(vf); err_exit: ret = ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_DEL_FDIR_FILTER, v_ret, (u8 *)stat, len); kfree(stat); return ret; } /** * ice_vf_fdir_init - init FDIR resource for VF * @vf: pointer to the VF info */ void ice_vf_fdir_init(struct ice_vf *vf) { struct ice_vf_fdir *fdir = &vf->fdir; idr_init(&fdir->fdir_rule_idr); INIT_LIST_HEAD(&fdir->fdir_rule_list); spin_lock_init(&fdir->ctx_lock); fdir->ctx_irq.flags = 0; fdir->ctx_done.flags = 0; ice_vc_fdir_reset_cnt_all(fdir); } /** * ice_vf_fdir_exit - destroy FDIR resource for VF * @vf: pointer to the VF info */ void ice_vf_fdir_exit(struct ice_vf *vf) { ice_vc_fdir_flush_entry(vf); idr_destroy(&vf->fdir.fdir_rule_idr); ice_vc_fdir_rem_prof_all(vf); ice_vc_fdir_free_prof_all(vf); }
linux-master
drivers/net/ethernet/intel/ice/ice_virtchnl_fdir.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2021, Intel Corporation. */ #include "ice_virtchnl_allowlist.h" /* Purpose of this file is to share functionality to allowlist or denylist * opcodes used in PF <-> VF communication. Group of opcodes: * - default -> should be always allowed after creating VF, * default_allowlist_opcodes * - opcodes needed by VF to work correctly, but not associated with caps -> * should be allowed after successful VF resources allocation, * working_allowlist_opcodes * - opcodes needed by VF when caps are activated * * Caps that don't use new opcodes (no opcodes should be allowed): * - VIRTCHNL_VF_OFFLOAD_RSS_AQ * - VIRTCHNL_VF_OFFLOAD_RSS_REG * - VIRTCHNL_VF_OFFLOAD_WB_ON_ITR * - VIRTCHNL_VF_OFFLOAD_CRC * - VIRTCHNL_VF_OFFLOAD_RX_POLLING * - VIRTCHNL_VF_OFFLOAD_RSS_PCTYPE_V2 * - VIRTCHNL_VF_OFFLOAD_ENCAP * - VIRTCHNL_VF_OFFLOAD_ENCAP_CSUM * - VIRTCHNL_VF_OFFLOAD_RX_ENCAP_CSUM * - VIRTCHNL_VF_OFFLOAD_USO */ /* default opcodes to communicate with VF */ static const u32 default_allowlist_opcodes[] = { VIRTCHNL_OP_GET_VF_RESOURCES, VIRTCHNL_OP_VERSION, VIRTCHNL_OP_RESET_VF, }; /* opcodes supported after successful VIRTCHNL_OP_GET_VF_RESOURCES */ static const u32 working_allowlist_opcodes[] = { VIRTCHNL_OP_CONFIG_TX_QUEUE, VIRTCHNL_OP_CONFIG_RX_QUEUE, VIRTCHNL_OP_CONFIG_VSI_QUEUES, VIRTCHNL_OP_CONFIG_IRQ_MAP, VIRTCHNL_OP_ENABLE_QUEUES, VIRTCHNL_OP_DISABLE_QUEUES, VIRTCHNL_OP_GET_STATS, VIRTCHNL_OP_EVENT, }; /* VIRTCHNL_VF_OFFLOAD_L2 */ static const u32 l2_allowlist_opcodes[] = { VIRTCHNL_OP_ADD_ETH_ADDR, VIRTCHNL_OP_DEL_ETH_ADDR, VIRTCHNL_OP_CONFIG_PROMISCUOUS_MODE, }; /* VIRTCHNL_VF_OFFLOAD_REQ_QUEUES */ static const u32 req_queues_allowlist_opcodes[] = { VIRTCHNL_OP_REQUEST_QUEUES, }; /* VIRTCHNL_VF_OFFLOAD_VLAN */ static const u32 vlan_allowlist_opcodes[] = { VIRTCHNL_OP_ADD_VLAN, VIRTCHNL_OP_DEL_VLAN, VIRTCHNL_OP_ENABLE_VLAN_STRIPPING, VIRTCHNL_OP_DISABLE_VLAN_STRIPPING, }; /* VIRTCHNL_VF_OFFLOAD_VLAN_V2 */ static const u32 vlan_v2_allowlist_opcodes[] = { VIRTCHNL_OP_GET_OFFLOAD_VLAN_V2_CAPS, VIRTCHNL_OP_ADD_VLAN_V2, VIRTCHNL_OP_DEL_VLAN_V2, VIRTCHNL_OP_ENABLE_VLAN_STRIPPING_V2, VIRTCHNL_OP_DISABLE_VLAN_STRIPPING_V2, VIRTCHNL_OP_ENABLE_VLAN_INSERTION_V2, VIRTCHNL_OP_DISABLE_VLAN_INSERTION_V2, }; /* VIRTCHNL_VF_OFFLOAD_RSS_PF */ static const u32 rss_pf_allowlist_opcodes[] = { VIRTCHNL_OP_CONFIG_RSS_KEY, VIRTCHNL_OP_CONFIG_RSS_LUT, VIRTCHNL_OP_GET_RSS_HENA_CAPS, VIRTCHNL_OP_SET_RSS_HENA, }; /* VIRTCHNL_VF_OFFLOAD_RX_FLEX_DESC */ static const u32 rx_flex_desc_allowlist_opcodes[] = { VIRTCHNL_OP_GET_SUPPORTED_RXDIDS, }; /* VIRTCHNL_VF_OFFLOAD_ADV_RSS_PF */ static const u32 adv_rss_pf_allowlist_opcodes[] = { VIRTCHNL_OP_ADD_RSS_CFG, VIRTCHNL_OP_DEL_RSS_CFG, }; /* VIRTCHNL_VF_OFFLOAD_FDIR_PF */ static const u32 fdir_pf_allowlist_opcodes[] = { VIRTCHNL_OP_ADD_FDIR_FILTER, VIRTCHNL_OP_DEL_FDIR_FILTER, }; struct allowlist_opcode_info { const u32 *opcodes; size_t size; }; #define BIT_INDEX(caps) (HWEIGHT((caps) - 1)) #define ALLOW_ITEM(caps, list) \ [BIT_INDEX(caps)] = { \ .opcodes = list, \ .size = ARRAY_SIZE(list) \ } static const struct allowlist_opcode_info allowlist_opcodes[] = { ALLOW_ITEM(VIRTCHNL_VF_OFFLOAD_L2, l2_allowlist_opcodes), ALLOW_ITEM(VIRTCHNL_VF_OFFLOAD_REQ_QUEUES, req_queues_allowlist_opcodes), ALLOW_ITEM(VIRTCHNL_VF_OFFLOAD_VLAN, vlan_allowlist_opcodes), ALLOW_ITEM(VIRTCHNL_VF_OFFLOAD_RSS_PF, rss_pf_allowlist_opcodes), ALLOW_ITEM(VIRTCHNL_VF_OFFLOAD_RX_FLEX_DESC, rx_flex_desc_allowlist_opcodes), ALLOW_ITEM(VIRTCHNL_VF_OFFLOAD_ADV_RSS_PF, adv_rss_pf_allowlist_opcodes), ALLOW_ITEM(VIRTCHNL_VF_OFFLOAD_FDIR_PF, fdir_pf_allowlist_opcodes), ALLOW_ITEM(VIRTCHNL_VF_OFFLOAD_VLAN_V2, vlan_v2_allowlist_opcodes), }; /** * ice_vc_is_opcode_allowed - check if this opcode is allowed on this VF * @vf: pointer to VF structure * @opcode: virtchnl opcode * * Return true if message is allowed on this VF */ bool ice_vc_is_opcode_allowed(struct ice_vf *vf, u32 opcode) { if (opcode >= VIRTCHNL_OP_MAX) return false; return test_bit(opcode, vf->opcodes_allowlist); } /** * ice_vc_allowlist_opcodes - allowlist selected opcodes * @vf: pointer to VF structure * @opcodes: array of opocodes to allowlist * @size: size of opcodes array * * Function should be called to allowlist opcodes on VF. */ static void ice_vc_allowlist_opcodes(struct ice_vf *vf, const u32 *opcodes, size_t size) { unsigned int i; for (i = 0; i < size; i++) set_bit(opcodes[i], vf->opcodes_allowlist); } /** * ice_vc_clear_allowlist - clear all allowlist opcodes * @vf: pointer to VF structure */ static void ice_vc_clear_allowlist(struct ice_vf *vf) { bitmap_zero(vf->opcodes_allowlist, VIRTCHNL_OP_MAX); } /** * ice_vc_set_default_allowlist - allowlist default opcodes for VF * @vf: pointer to VF structure */ void ice_vc_set_default_allowlist(struct ice_vf *vf) { ice_vc_clear_allowlist(vf); ice_vc_allowlist_opcodes(vf, default_allowlist_opcodes, ARRAY_SIZE(default_allowlist_opcodes)); } /** * ice_vc_set_working_allowlist - allowlist opcodes needed to by VF to work * @vf: pointer to VF structure * * allowlist opcodes that aren't associated with specific caps, but * are needed by VF to work. */ void ice_vc_set_working_allowlist(struct ice_vf *vf) { ice_vc_allowlist_opcodes(vf, working_allowlist_opcodes, ARRAY_SIZE(working_allowlist_opcodes)); } /** * ice_vc_set_caps_allowlist - allowlist VF opcodes according caps * @vf: pointer to VF structure */ void ice_vc_set_caps_allowlist(struct ice_vf *vf) { unsigned long caps = vf->driver_caps; unsigned int i; for_each_set_bit(i, &caps, ARRAY_SIZE(allowlist_opcodes)) ice_vc_allowlist_opcodes(vf, allowlist_opcodes[i].opcodes, allowlist_opcodes[i].size); }
linux-master
drivers/net/ethernet/intel/ice/ice_virtchnl_allowlist.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2018, Intel Corporation. */ /* The driver transmit and receive code */ #include <linux/mm.h> #include <linux/netdevice.h> #include <linux/prefetch.h> #include <linux/bpf_trace.h> #include <net/dsfield.h> #include <net/mpls.h> #include <net/xdp.h> #include "ice_txrx_lib.h" #include "ice_lib.h" #include "ice.h" #include "ice_trace.h" #include "ice_dcb_lib.h" #include "ice_xsk.h" #include "ice_eswitch.h" #define ICE_RX_HDR_SIZE 256 #define FDIR_DESC_RXDID 0x40 #define ICE_FDIR_CLEAN_DELAY 10 /** * ice_prgm_fdir_fltr - Program a Flow Director filter * @vsi: VSI to send dummy packet * @fdir_desc: flow director descriptor * @raw_packet: allocated buffer for flow director */ int ice_prgm_fdir_fltr(struct ice_vsi *vsi, struct ice_fltr_desc *fdir_desc, u8 *raw_packet) { struct ice_tx_buf *tx_buf, *first; struct ice_fltr_desc *f_desc; struct ice_tx_desc *tx_desc; struct ice_tx_ring *tx_ring; struct device *dev; dma_addr_t dma; u32 td_cmd; u16 i; /* VSI and Tx ring */ if (!vsi) return -ENOENT; tx_ring = vsi->tx_rings[0]; if (!tx_ring || !tx_ring->desc) return -ENOENT; dev = tx_ring->dev; /* we are using two descriptors to add/del a filter and we can wait */ for (i = ICE_FDIR_CLEAN_DELAY; ICE_DESC_UNUSED(tx_ring) < 2; i--) { if (!i) return -EAGAIN; msleep_interruptible(1); } dma = dma_map_single(dev, raw_packet, ICE_FDIR_MAX_RAW_PKT_SIZE, DMA_TO_DEVICE); if (dma_mapping_error(dev, dma)) return -EINVAL; /* grab the next descriptor */ i = tx_ring->next_to_use; first = &tx_ring->tx_buf[i]; f_desc = ICE_TX_FDIRDESC(tx_ring, i); memcpy(f_desc, fdir_desc, sizeof(*f_desc)); i++; i = (i < tx_ring->count) ? i : 0; tx_desc = ICE_TX_DESC(tx_ring, i); tx_buf = &tx_ring->tx_buf[i]; i++; tx_ring->next_to_use = (i < tx_ring->count) ? i : 0; memset(tx_buf, 0, sizeof(*tx_buf)); dma_unmap_len_set(tx_buf, len, ICE_FDIR_MAX_RAW_PKT_SIZE); dma_unmap_addr_set(tx_buf, dma, dma); tx_desc->buf_addr = cpu_to_le64(dma); td_cmd = ICE_TXD_LAST_DESC_CMD | ICE_TX_DESC_CMD_DUMMY | ICE_TX_DESC_CMD_RE; tx_buf->type = ICE_TX_BUF_DUMMY; tx_buf->raw_buf = raw_packet; tx_desc->cmd_type_offset_bsz = ice_build_ctob(td_cmd, 0, ICE_FDIR_MAX_RAW_PKT_SIZE, 0); /* Force memory write to complete before letting h/w know * there are new descriptors to fetch. */ wmb(); /* mark the data descriptor to be watched */ first->next_to_watch = tx_desc; writel(tx_ring->next_to_use, tx_ring->tail); return 0; } /** * ice_unmap_and_free_tx_buf - Release a Tx buffer * @ring: the ring that owns the buffer * @tx_buf: the buffer to free */ static void ice_unmap_and_free_tx_buf(struct ice_tx_ring *ring, struct ice_tx_buf *tx_buf) { if (dma_unmap_len(tx_buf, len)) dma_unmap_page(ring->dev, dma_unmap_addr(tx_buf, dma), dma_unmap_len(tx_buf, len), DMA_TO_DEVICE); switch (tx_buf->type) { case ICE_TX_BUF_DUMMY: devm_kfree(ring->dev, tx_buf->raw_buf); break; case ICE_TX_BUF_SKB: dev_kfree_skb_any(tx_buf->skb); break; case ICE_TX_BUF_XDP_TX: page_frag_free(tx_buf->raw_buf); break; case ICE_TX_BUF_XDP_XMIT: xdp_return_frame(tx_buf->xdpf); break; } tx_buf->next_to_watch = NULL; tx_buf->type = ICE_TX_BUF_EMPTY; dma_unmap_len_set(tx_buf, len, 0); /* tx_buf must be completely set up in the transmit path */ } static struct netdev_queue *txring_txq(const struct ice_tx_ring *ring) { return netdev_get_tx_queue(ring->netdev, ring->q_index); } /** * ice_clean_tx_ring - Free any empty Tx buffers * @tx_ring: ring to be cleaned */ void ice_clean_tx_ring(struct ice_tx_ring *tx_ring) { u32 size; u16 i; if (ice_ring_is_xdp(tx_ring) && tx_ring->xsk_pool) { ice_xsk_clean_xdp_ring(tx_ring); goto tx_skip_free; } /* ring already cleared, nothing to do */ if (!tx_ring->tx_buf) return; /* Free all the Tx ring sk_buffs */ for (i = 0; i < tx_ring->count; i++) ice_unmap_and_free_tx_buf(tx_ring, &tx_ring->tx_buf[i]); tx_skip_free: memset(tx_ring->tx_buf, 0, sizeof(*tx_ring->tx_buf) * tx_ring->count); size = ALIGN(tx_ring->count * sizeof(struct ice_tx_desc), PAGE_SIZE); /* Zero out the descriptor ring */ memset(tx_ring->desc, 0, size); tx_ring->next_to_use = 0; tx_ring->next_to_clean = 0; if (!tx_ring->netdev) return; /* cleanup Tx queue statistics */ netdev_tx_reset_queue(txring_txq(tx_ring)); } /** * ice_free_tx_ring - Free Tx resources per queue * @tx_ring: Tx descriptor ring for a specific queue * * Free all transmit software resources */ void ice_free_tx_ring(struct ice_tx_ring *tx_ring) { u32 size; ice_clean_tx_ring(tx_ring); devm_kfree(tx_ring->dev, tx_ring->tx_buf); tx_ring->tx_buf = NULL; if (tx_ring->desc) { size = ALIGN(tx_ring->count * sizeof(struct ice_tx_desc), PAGE_SIZE); dmam_free_coherent(tx_ring->dev, size, tx_ring->desc, tx_ring->dma); tx_ring->desc = NULL; } } /** * ice_clean_tx_irq - Reclaim resources after transmit completes * @tx_ring: Tx ring to clean * @napi_budget: Used to determine if we are in netpoll * * Returns true if there's any budget left (e.g. the clean is finished) */ static bool ice_clean_tx_irq(struct ice_tx_ring *tx_ring, int napi_budget) { unsigned int total_bytes = 0, total_pkts = 0; unsigned int budget = ICE_DFLT_IRQ_WORK; struct ice_vsi *vsi = tx_ring->vsi; s16 i = tx_ring->next_to_clean; struct ice_tx_desc *tx_desc; struct ice_tx_buf *tx_buf; /* get the bql data ready */ netdev_txq_bql_complete_prefetchw(txring_txq(tx_ring)); tx_buf = &tx_ring->tx_buf[i]; tx_desc = ICE_TX_DESC(tx_ring, i); i -= tx_ring->count; prefetch(&vsi->state); do { struct ice_tx_desc *eop_desc = tx_buf->next_to_watch; /* if next_to_watch is not set then there is no work pending */ if (!eop_desc) break; /* follow the guidelines of other drivers */ prefetchw(&tx_buf->skb->users); smp_rmb(); /* prevent any other reads prior to eop_desc */ ice_trace(clean_tx_irq, tx_ring, tx_desc, tx_buf); /* if the descriptor isn't done, no work yet to do */ if (!(eop_desc->cmd_type_offset_bsz & cpu_to_le64(ICE_TX_DESC_DTYPE_DESC_DONE))) break; /* clear next_to_watch to prevent false hangs */ tx_buf->next_to_watch = NULL; /* update the statistics for this packet */ total_bytes += tx_buf->bytecount; total_pkts += tx_buf->gso_segs; /* free the skb */ napi_consume_skb(tx_buf->skb, napi_budget); /* unmap skb header data */ dma_unmap_single(tx_ring->dev, dma_unmap_addr(tx_buf, dma), dma_unmap_len(tx_buf, len), DMA_TO_DEVICE); /* clear tx_buf data */ tx_buf->type = ICE_TX_BUF_EMPTY; dma_unmap_len_set(tx_buf, len, 0); /* unmap remaining buffers */ while (tx_desc != eop_desc) { ice_trace(clean_tx_irq_unmap, tx_ring, tx_desc, tx_buf); tx_buf++; tx_desc++; i++; if (unlikely(!i)) { i -= tx_ring->count; tx_buf = tx_ring->tx_buf; tx_desc = ICE_TX_DESC(tx_ring, 0); } /* unmap any remaining paged data */ if (dma_unmap_len(tx_buf, len)) { dma_unmap_page(tx_ring->dev, dma_unmap_addr(tx_buf, dma), dma_unmap_len(tx_buf, len), DMA_TO_DEVICE); dma_unmap_len_set(tx_buf, len, 0); } } ice_trace(clean_tx_irq_unmap_eop, tx_ring, tx_desc, tx_buf); /* move us one more past the eop_desc for start of next pkt */ tx_buf++; tx_desc++; i++; if (unlikely(!i)) { i -= tx_ring->count; tx_buf = tx_ring->tx_buf; tx_desc = ICE_TX_DESC(tx_ring, 0); } prefetch(tx_desc); /* update budget accounting */ budget--; } while (likely(budget)); i += tx_ring->count; tx_ring->next_to_clean = i; ice_update_tx_ring_stats(tx_ring, total_pkts, total_bytes); netdev_tx_completed_queue(txring_txq(tx_ring), total_pkts, total_bytes); #define TX_WAKE_THRESHOLD ((s16)(DESC_NEEDED * 2)) if (unlikely(total_pkts && netif_carrier_ok(tx_ring->netdev) && (ICE_DESC_UNUSED(tx_ring) >= TX_WAKE_THRESHOLD))) { /* Make sure that anybody stopping the queue after this * sees the new next_to_clean. */ smp_mb(); if (netif_tx_queue_stopped(txring_txq(tx_ring)) && !test_bit(ICE_VSI_DOWN, vsi->state)) { netif_tx_wake_queue(txring_txq(tx_ring)); ++tx_ring->ring_stats->tx_stats.restart_q; } } return !!budget; } /** * ice_setup_tx_ring - Allocate the Tx descriptors * @tx_ring: the Tx ring to set up * * Return 0 on success, negative on error */ int ice_setup_tx_ring(struct ice_tx_ring *tx_ring) { struct device *dev = tx_ring->dev; u32 size; if (!dev) return -ENOMEM; /* warn if we are about to overwrite the pointer */ WARN_ON(tx_ring->tx_buf); tx_ring->tx_buf = devm_kcalloc(dev, sizeof(*tx_ring->tx_buf), tx_ring->count, GFP_KERNEL); if (!tx_ring->tx_buf) return -ENOMEM; /* round up to nearest page */ size = ALIGN(tx_ring->count * sizeof(struct ice_tx_desc), PAGE_SIZE); tx_ring->desc = dmam_alloc_coherent(dev, size, &tx_ring->dma, GFP_KERNEL); if (!tx_ring->desc) { dev_err(dev, "Unable to allocate memory for the Tx descriptor ring, size=%d\n", size); goto err; } tx_ring->next_to_use = 0; tx_ring->next_to_clean = 0; tx_ring->ring_stats->tx_stats.prev_pkt = -1; return 0; err: devm_kfree(dev, tx_ring->tx_buf); tx_ring->tx_buf = NULL; return -ENOMEM; } /** * ice_clean_rx_ring - Free Rx buffers * @rx_ring: ring to be cleaned */ void ice_clean_rx_ring(struct ice_rx_ring *rx_ring) { struct xdp_buff *xdp = &rx_ring->xdp; struct device *dev = rx_ring->dev; u32 size; u16 i; /* ring already cleared, nothing to do */ if (!rx_ring->rx_buf) return; if (rx_ring->xsk_pool) { ice_xsk_clean_rx_ring(rx_ring); goto rx_skip_free; } if (xdp->data) { xdp_return_buff(xdp); xdp->data = NULL; } /* Free all the Rx ring sk_buffs */ for (i = 0; i < rx_ring->count; i++) { struct ice_rx_buf *rx_buf = &rx_ring->rx_buf[i]; if (!rx_buf->page) continue; /* Invalidate cache lines that may have been written to by * device so that we avoid corrupting memory. */ dma_sync_single_range_for_cpu(dev, rx_buf->dma, rx_buf->page_offset, rx_ring->rx_buf_len, DMA_FROM_DEVICE); /* free resources associated with mapping */ dma_unmap_page_attrs(dev, rx_buf->dma, ice_rx_pg_size(rx_ring), DMA_FROM_DEVICE, ICE_RX_DMA_ATTR); __page_frag_cache_drain(rx_buf->page, rx_buf->pagecnt_bias); rx_buf->page = NULL; rx_buf->page_offset = 0; } rx_skip_free: if (rx_ring->xsk_pool) memset(rx_ring->xdp_buf, 0, array_size(rx_ring->count, sizeof(*rx_ring->xdp_buf))); else memset(rx_ring->rx_buf, 0, array_size(rx_ring->count, sizeof(*rx_ring->rx_buf))); /* Zero out the descriptor ring */ size = ALIGN(rx_ring->count * sizeof(union ice_32byte_rx_desc), PAGE_SIZE); memset(rx_ring->desc, 0, size); rx_ring->next_to_alloc = 0; rx_ring->next_to_clean = 0; rx_ring->first_desc = 0; rx_ring->next_to_use = 0; } /** * ice_free_rx_ring - Free Rx resources * @rx_ring: ring to clean the resources from * * Free all receive software resources */ void ice_free_rx_ring(struct ice_rx_ring *rx_ring) { u32 size; ice_clean_rx_ring(rx_ring); if (rx_ring->vsi->type == ICE_VSI_PF) if (xdp_rxq_info_is_reg(&rx_ring->xdp_rxq)) xdp_rxq_info_unreg(&rx_ring->xdp_rxq); rx_ring->xdp_prog = NULL; if (rx_ring->xsk_pool) { kfree(rx_ring->xdp_buf); rx_ring->xdp_buf = NULL; } else { kfree(rx_ring->rx_buf); rx_ring->rx_buf = NULL; } if (rx_ring->desc) { size = ALIGN(rx_ring->count * sizeof(union ice_32byte_rx_desc), PAGE_SIZE); dmam_free_coherent(rx_ring->dev, size, rx_ring->desc, rx_ring->dma); rx_ring->desc = NULL; } } /** * ice_setup_rx_ring - Allocate the Rx descriptors * @rx_ring: the Rx ring to set up * * Return 0 on success, negative on error */ int ice_setup_rx_ring(struct ice_rx_ring *rx_ring) { struct device *dev = rx_ring->dev; u32 size; if (!dev) return -ENOMEM; /* warn if we are about to overwrite the pointer */ WARN_ON(rx_ring->rx_buf); rx_ring->rx_buf = kcalloc(rx_ring->count, sizeof(*rx_ring->rx_buf), GFP_KERNEL); if (!rx_ring->rx_buf) return -ENOMEM; /* round up to nearest page */ size = ALIGN(rx_ring->count * sizeof(union ice_32byte_rx_desc), PAGE_SIZE); rx_ring->desc = dmam_alloc_coherent(dev, size, &rx_ring->dma, GFP_KERNEL); if (!rx_ring->desc) { dev_err(dev, "Unable to allocate memory for the Rx descriptor ring, size=%d\n", size); goto err; } rx_ring->next_to_use = 0; rx_ring->next_to_clean = 0; rx_ring->first_desc = 0; if (ice_is_xdp_ena_vsi(rx_ring->vsi)) WRITE_ONCE(rx_ring->xdp_prog, rx_ring->vsi->xdp_prog); if (rx_ring->vsi->type == ICE_VSI_PF && !xdp_rxq_info_is_reg(&rx_ring->xdp_rxq)) if (xdp_rxq_info_reg(&rx_ring->xdp_rxq, rx_ring->netdev, rx_ring->q_index, rx_ring->q_vector->napi.napi_id)) goto err; return 0; err: kfree(rx_ring->rx_buf); rx_ring->rx_buf = NULL; return -ENOMEM; } /** * ice_rx_frame_truesize * @rx_ring: ptr to Rx ring * @size: size * * calculate the truesize with taking into the account PAGE_SIZE of * underlying arch */ static unsigned int ice_rx_frame_truesize(struct ice_rx_ring *rx_ring, const unsigned int size) { unsigned int truesize; #if (PAGE_SIZE < 8192) truesize = ice_rx_pg_size(rx_ring) / 2; /* Must be power-of-2 */ #else truesize = rx_ring->rx_offset ? SKB_DATA_ALIGN(rx_ring->rx_offset + size) + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) : SKB_DATA_ALIGN(size); #endif return truesize; } /** * ice_run_xdp - Executes an XDP program on initialized xdp_buff * @rx_ring: Rx ring * @xdp: xdp_buff used as input to the XDP program * @xdp_prog: XDP program to run * @xdp_ring: ring to be used for XDP_TX action * @rx_buf: Rx buffer to store the XDP action * * Returns any of ICE_XDP_{PASS, CONSUMED, TX, REDIR} */ static void ice_run_xdp(struct ice_rx_ring *rx_ring, struct xdp_buff *xdp, struct bpf_prog *xdp_prog, struct ice_tx_ring *xdp_ring, struct ice_rx_buf *rx_buf) { unsigned int ret = ICE_XDP_PASS; u32 act; if (!xdp_prog) goto exit; act = bpf_prog_run_xdp(xdp_prog, xdp); switch (act) { case XDP_PASS: break; case XDP_TX: if (static_branch_unlikely(&ice_xdp_locking_key)) spin_lock(&xdp_ring->tx_lock); ret = __ice_xmit_xdp_ring(xdp, xdp_ring, false); if (static_branch_unlikely(&ice_xdp_locking_key)) spin_unlock(&xdp_ring->tx_lock); if (ret == ICE_XDP_CONSUMED) goto out_failure; break; case XDP_REDIRECT: if (xdp_do_redirect(rx_ring->netdev, xdp, xdp_prog)) goto out_failure; ret = ICE_XDP_REDIR; break; default: bpf_warn_invalid_xdp_action(rx_ring->netdev, xdp_prog, act); fallthrough; case XDP_ABORTED: out_failure: trace_xdp_exception(rx_ring->netdev, xdp_prog, act); fallthrough; case XDP_DROP: ret = ICE_XDP_CONSUMED; } exit: rx_buf->act = ret; if (unlikely(xdp_buff_has_frags(xdp))) ice_set_rx_bufs_act(xdp, rx_ring, ret); } /** * ice_xmit_xdp_ring - submit frame to XDP ring for transmission * @xdpf: XDP frame that will be converted to XDP buff * @xdp_ring: XDP ring for transmission */ static int ice_xmit_xdp_ring(const struct xdp_frame *xdpf, struct ice_tx_ring *xdp_ring) { struct xdp_buff xdp; xdp.data_hard_start = (void *)xdpf; xdp.data = xdpf->data; xdp.data_end = xdp.data + xdpf->len; xdp.frame_sz = xdpf->frame_sz; xdp.flags = xdpf->flags; return __ice_xmit_xdp_ring(&xdp, xdp_ring, true); } /** * ice_xdp_xmit - submit packets to XDP ring for transmission * @dev: netdev * @n: number of XDP frames to be transmitted * @frames: XDP frames to be transmitted * @flags: transmit flags * * Returns number of frames successfully sent. Failed frames * will be free'ed by XDP core. * For error cases, a negative errno code is returned and no-frames * are transmitted (caller must handle freeing frames). */ int ice_xdp_xmit(struct net_device *dev, int n, struct xdp_frame **frames, u32 flags) { struct ice_netdev_priv *np = netdev_priv(dev); unsigned int queue_index = smp_processor_id(); struct ice_vsi *vsi = np->vsi; struct ice_tx_ring *xdp_ring; struct ice_tx_buf *tx_buf; int nxmit = 0, i; if (test_bit(ICE_VSI_DOWN, vsi->state)) return -ENETDOWN; if (!ice_is_xdp_ena_vsi(vsi)) return -ENXIO; if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK)) return -EINVAL; if (static_branch_unlikely(&ice_xdp_locking_key)) { queue_index %= vsi->num_xdp_txq; xdp_ring = vsi->xdp_rings[queue_index]; spin_lock(&xdp_ring->tx_lock); } else { /* Generally, should not happen */ if (unlikely(queue_index >= vsi->num_xdp_txq)) return -ENXIO; xdp_ring = vsi->xdp_rings[queue_index]; } tx_buf = &xdp_ring->tx_buf[xdp_ring->next_to_use]; for (i = 0; i < n; i++) { const struct xdp_frame *xdpf = frames[i]; int err; err = ice_xmit_xdp_ring(xdpf, xdp_ring); if (err != ICE_XDP_TX) break; nxmit++; } tx_buf->rs_idx = ice_set_rs_bit(xdp_ring); if (unlikely(flags & XDP_XMIT_FLUSH)) ice_xdp_ring_update_tail(xdp_ring); if (static_branch_unlikely(&ice_xdp_locking_key)) spin_unlock(&xdp_ring->tx_lock); return nxmit; } /** * ice_alloc_mapped_page - recycle or make a new page * @rx_ring: ring to use * @bi: rx_buf struct to modify * * Returns true if the page was successfully allocated or * reused. */ static bool ice_alloc_mapped_page(struct ice_rx_ring *rx_ring, struct ice_rx_buf *bi) { struct page *page = bi->page; dma_addr_t dma; /* since we are recycling buffers we should seldom need to alloc */ if (likely(page)) return true; /* alloc new page for storage */ page = dev_alloc_pages(ice_rx_pg_order(rx_ring)); if (unlikely(!page)) { rx_ring->ring_stats->rx_stats.alloc_page_failed++; return false; } /* map page for use */ dma = dma_map_page_attrs(rx_ring->dev, page, 0, ice_rx_pg_size(rx_ring), DMA_FROM_DEVICE, ICE_RX_DMA_ATTR); /* if mapping failed free memory back to system since * there isn't much point in holding memory we can't use */ if (dma_mapping_error(rx_ring->dev, dma)) { __free_pages(page, ice_rx_pg_order(rx_ring)); rx_ring->ring_stats->rx_stats.alloc_page_failed++; return false; } bi->dma = dma; bi->page = page; bi->page_offset = rx_ring->rx_offset; page_ref_add(page, USHRT_MAX - 1); bi->pagecnt_bias = USHRT_MAX; return true; } /** * ice_alloc_rx_bufs - Replace used receive buffers * @rx_ring: ring to place buffers on * @cleaned_count: number of buffers to replace * * Returns false if all allocations were successful, true if any fail. Returning * true signals to the caller that we didn't replace cleaned_count buffers and * there is more work to do. * * First, try to clean "cleaned_count" Rx buffers. Then refill the cleaned Rx * buffers. Then bump tail at most one time. Grouping like this lets us avoid * multiple tail writes per call. */ bool ice_alloc_rx_bufs(struct ice_rx_ring *rx_ring, unsigned int cleaned_count) { union ice_32b_rx_flex_desc *rx_desc; u16 ntu = rx_ring->next_to_use; struct ice_rx_buf *bi; /* do nothing if no valid netdev defined */ if ((!rx_ring->netdev && rx_ring->vsi->type != ICE_VSI_CTRL) || !cleaned_count) return false; /* get the Rx descriptor and buffer based on next_to_use */ rx_desc = ICE_RX_DESC(rx_ring, ntu); bi = &rx_ring->rx_buf[ntu]; do { /* if we fail here, we have work remaining */ if (!ice_alloc_mapped_page(rx_ring, bi)) break; /* sync the buffer for use by the device */ dma_sync_single_range_for_device(rx_ring->dev, bi->dma, bi->page_offset, rx_ring->rx_buf_len, DMA_FROM_DEVICE); /* Refresh the desc even if buffer_addrs didn't change * because each write-back erases this info. */ rx_desc->read.pkt_addr = cpu_to_le64(bi->dma + bi->page_offset); rx_desc++; bi++; ntu++; if (unlikely(ntu == rx_ring->count)) { rx_desc = ICE_RX_DESC(rx_ring, 0); bi = rx_ring->rx_buf; ntu = 0; } /* clear the status bits for the next_to_use descriptor */ rx_desc->wb.status_error0 = 0; cleaned_count--; } while (cleaned_count); if (rx_ring->next_to_use != ntu) ice_release_rx_desc(rx_ring, ntu); return !!cleaned_count; } /** * ice_rx_buf_adjust_pg_offset - Prepare Rx buffer for reuse * @rx_buf: Rx buffer to adjust * @size: Size of adjustment * * Update the offset within page so that Rx buf will be ready to be reused. * For systems with PAGE_SIZE < 8192 this function will flip the page offset * so the second half of page assigned to Rx buffer will be used, otherwise * the offset is moved by "size" bytes */ static void ice_rx_buf_adjust_pg_offset(struct ice_rx_buf *rx_buf, unsigned int size) { #if (PAGE_SIZE < 8192) /* flip page offset to other buffer */ rx_buf->page_offset ^= size; #else /* move offset up to the next cache line */ rx_buf->page_offset += size; #endif } /** * ice_can_reuse_rx_page - Determine if page can be reused for another Rx * @rx_buf: buffer containing the page * * If page is reusable, we have a green light for calling ice_reuse_rx_page, * which will assign the current buffer to the buffer that next_to_alloc is * pointing to; otherwise, the DMA mapping needs to be destroyed and * page freed */ static bool ice_can_reuse_rx_page(struct ice_rx_buf *rx_buf) { unsigned int pagecnt_bias = rx_buf->pagecnt_bias; struct page *page = rx_buf->page; /* avoid re-using remote and pfmemalloc pages */ if (!dev_page_is_reusable(page)) return false; #if (PAGE_SIZE < 8192) /* if we are only owner of page we can reuse it */ if (unlikely(rx_buf->pgcnt - pagecnt_bias > 1)) return false; #else #define ICE_LAST_OFFSET \ (SKB_WITH_OVERHEAD(PAGE_SIZE) - ICE_RXBUF_2048) if (rx_buf->page_offset > ICE_LAST_OFFSET) return false; #endif /* PAGE_SIZE < 8192) */ /* If we have drained the page fragment pool we need to update * the pagecnt_bias and page count so that we fully restock the * number of references the driver holds. */ if (unlikely(pagecnt_bias == 1)) { page_ref_add(page, USHRT_MAX - 1); rx_buf->pagecnt_bias = USHRT_MAX; } return true; } /** * ice_add_xdp_frag - Add contents of Rx buffer to xdp buf as a frag * @rx_ring: Rx descriptor ring to transact packets on * @xdp: xdp buff to place the data into * @rx_buf: buffer containing page to add * @size: packet length from rx_desc * * This function will add the data contained in rx_buf->page to the xdp buf. * It will just attach the page as a frag. */ static int ice_add_xdp_frag(struct ice_rx_ring *rx_ring, struct xdp_buff *xdp, struct ice_rx_buf *rx_buf, const unsigned int size) { struct skb_shared_info *sinfo = xdp_get_shared_info_from_buff(xdp); if (!size) return 0; if (!xdp_buff_has_frags(xdp)) { sinfo->nr_frags = 0; sinfo->xdp_frags_size = 0; xdp_buff_set_frags_flag(xdp); } if (unlikely(sinfo->nr_frags == MAX_SKB_FRAGS)) { if (unlikely(xdp_buff_has_frags(xdp))) ice_set_rx_bufs_act(xdp, rx_ring, ICE_XDP_CONSUMED); return -ENOMEM; } __skb_fill_page_desc_noacc(sinfo, sinfo->nr_frags++, rx_buf->page, rx_buf->page_offset, size); sinfo->xdp_frags_size += size; if (page_is_pfmemalloc(rx_buf->page)) xdp_buff_set_frag_pfmemalloc(xdp); return 0; } /** * ice_reuse_rx_page - page flip buffer and store it back on the ring * @rx_ring: Rx descriptor ring to store buffers on * @old_buf: donor buffer to have page reused * * Synchronizes page for reuse by the adapter */ static void ice_reuse_rx_page(struct ice_rx_ring *rx_ring, struct ice_rx_buf *old_buf) { u16 nta = rx_ring->next_to_alloc; struct ice_rx_buf *new_buf; new_buf = &rx_ring->rx_buf[nta]; /* update, and store next to alloc */ nta++; rx_ring->next_to_alloc = (nta < rx_ring->count) ? nta : 0; /* Transfer page from old buffer to new buffer. * Move each member individually to avoid possible store * forwarding stalls and unnecessary copy of skb. */ new_buf->dma = old_buf->dma; new_buf->page = old_buf->page; new_buf->page_offset = old_buf->page_offset; new_buf->pagecnt_bias = old_buf->pagecnt_bias; } /** * ice_get_rx_buf - Fetch Rx buffer and synchronize data for use * @rx_ring: Rx descriptor ring to transact packets on * @size: size of buffer to add to skb * @ntc: index of next to clean element * * This function will pull an Rx buffer from the ring and synchronize it * for use by the CPU. */ static struct ice_rx_buf * ice_get_rx_buf(struct ice_rx_ring *rx_ring, const unsigned int size, const unsigned int ntc) { struct ice_rx_buf *rx_buf; rx_buf = &rx_ring->rx_buf[ntc]; rx_buf->pgcnt = #if (PAGE_SIZE < 8192) page_count(rx_buf->page); #else 0; #endif prefetchw(rx_buf->page); if (!size) return rx_buf; /* we are reusing so sync this buffer for CPU use */ dma_sync_single_range_for_cpu(rx_ring->dev, rx_buf->dma, rx_buf->page_offset, size, DMA_FROM_DEVICE); /* We have pulled a buffer for use, so decrement pagecnt_bias */ rx_buf->pagecnt_bias--; return rx_buf; } /** * ice_build_skb - Build skb around an existing buffer * @rx_ring: Rx descriptor ring to transact packets on * @xdp: xdp_buff pointing to the data * * This function builds an skb around an existing XDP buffer, taking care * to set up the skb correctly and avoid any memcpy overhead. Driver has * already combined frags (if any) to skb_shared_info. */ static struct sk_buff * ice_build_skb(struct ice_rx_ring *rx_ring, struct xdp_buff *xdp) { u8 metasize = xdp->data - xdp->data_meta; struct skb_shared_info *sinfo = NULL; unsigned int nr_frags; struct sk_buff *skb; if (unlikely(xdp_buff_has_frags(xdp))) { sinfo = xdp_get_shared_info_from_buff(xdp); nr_frags = sinfo->nr_frags; } /* Prefetch first cache line of first page. If xdp->data_meta * is unused, this points exactly as xdp->data, otherwise we * likely have a consumer accessing first few bytes of meta * data, and then actual data. */ net_prefetch(xdp->data_meta); /* build an skb around the page buffer */ skb = napi_build_skb(xdp->data_hard_start, xdp->frame_sz); if (unlikely(!skb)) return NULL; /* must to record Rx queue, otherwise OS features such as * symmetric queue won't work */ skb_record_rx_queue(skb, rx_ring->q_index); /* update pointers within the skb to store the data */ skb_reserve(skb, xdp->data - xdp->data_hard_start); __skb_put(skb, xdp->data_end - xdp->data); if (metasize) skb_metadata_set(skb, metasize); if (unlikely(xdp_buff_has_frags(xdp))) xdp_update_skb_shared_info(skb, nr_frags, sinfo->xdp_frags_size, nr_frags * xdp->frame_sz, xdp_buff_is_frag_pfmemalloc(xdp)); return skb; } /** * ice_construct_skb - Allocate skb and populate it * @rx_ring: Rx descriptor ring to transact packets on * @xdp: xdp_buff pointing to the data * * This function allocates an skb. It then populates it with the page * data from the current receive descriptor, taking care to set up the * skb correctly. */ static struct sk_buff * ice_construct_skb(struct ice_rx_ring *rx_ring, struct xdp_buff *xdp) { unsigned int size = xdp->data_end - xdp->data; struct skb_shared_info *sinfo = NULL; struct ice_rx_buf *rx_buf; unsigned int nr_frags = 0; unsigned int headlen; struct sk_buff *skb; /* prefetch first cache line of first page */ net_prefetch(xdp->data); if (unlikely(xdp_buff_has_frags(xdp))) { sinfo = xdp_get_shared_info_from_buff(xdp); nr_frags = sinfo->nr_frags; } /* allocate a skb to store the frags */ skb = __napi_alloc_skb(&rx_ring->q_vector->napi, ICE_RX_HDR_SIZE, GFP_ATOMIC | __GFP_NOWARN); if (unlikely(!skb)) return NULL; rx_buf = &rx_ring->rx_buf[rx_ring->first_desc]; skb_record_rx_queue(skb, rx_ring->q_index); /* Determine available headroom for copy */ headlen = size; if (headlen > ICE_RX_HDR_SIZE) headlen = eth_get_headlen(skb->dev, xdp->data, ICE_RX_HDR_SIZE); /* align pull length to size of long to optimize memcpy performance */ memcpy(__skb_put(skb, headlen), xdp->data, ALIGN(headlen, sizeof(long))); /* if we exhaust the linear part then add what is left as a frag */ size -= headlen; if (size) { /* besides adding here a partial frag, we are going to add * frags from xdp_buff, make sure there is enough space for * them */ if (unlikely(nr_frags >= MAX_SKB_FRAGS - 1)) { dev_kfree_skb(skb); return NULL; } skb_add_rx_frag(skb, 0, rx_buf->page, rx_buf->page_offset + headlen, size, xdp->frame_sz); } else { /* buffer is unused, change the act that should be taken later * on; data was copied onto skb's linear part so there's no * need for adjusting page offset and we can reuse this buffer * as-is */ rx_buf->act = ICE_SKB_CONSUMED; } if (unlikely(xdp_buff_has_frags(xdp))) { struct skb_shared_info *skinfo = skb_shinfo(skb); memcpy(&skinfo->frags[skinfo->nr_frags], &sinfo->frags[0], sizeof(skb_frag_t) * nr_frags); xdp_update_skb_shared_info(skb, skinfo->nr_frags + nr_frags, sinfo->xdp_frags_size, nr_frags * xdp->frame_sz, xdp_buff_is_frag_pfmemalloc(xdp)); } return skb; } /** * ice_put_rx_buf - Clean up used buffer and either recycle or free * @rx_ring: Rx descriptor ring to transact packets on * @rx_buf: Rx buffer to pull data from * * This function will clean up the contents of the rx_buf. It will either * recycle the buffer or unmap it and free the associated resources. */ static void ice_put_rx_buf(struct ice_rx_ring *rx_ring, struct ice_rx_buf *rx_buf) { if (!rx_buf) return; if (ice_can_reuse_rx_page(rx_buf)) { /* hand second half of page back to the ring */ ice_reuse_rx_page(rx_ring, rx_buf); } else { /* we are not reusing the buffer so unmap it */ dma_unmap_page_attrs(rx_ring->dev, rx_buf->dma, ice_rx_pg_size(rx_ring), DMA_FROM_DEVICE, ICE_RX_DMA_ATTR); __page_frag_cache_drain(rx_buf->page, rx_buf->pagecnt_bias); } /* clear contents of buffer_info */ rx_buf->page = NULL; } /** * ice_clean_rx_irq - Clean completed descriptors from Rx ring - bounce buf * @rx_ring: Rx descriptor ring to transact packets on * @budget: Total limit on number of packets to process * * This function provides a "bounce buffer" approach to Rx interrupt * processing. The advantage to this is that on systems that have * expensive overhead for IOMMU access this provides a means of avoiding * it by maintaining the mapping of the page to the system. * * Returns amount of work completed */ int ice_clean_rx_irq(struct ice_rx_ring *rx_ring, int budget) { unsigned int total_rx_bytes = 0, total_rx_pkts = 0; unsigned int offset = rx_ring->rx_offset; struct xdp_buff *xdp = &rx_ring->xdp; u32 cached_ntc = rx_ring->first_desc; struct ice_tx_ring *xdp_ring = NULL; struct bpf_prog *xdp_prog = NULL; u32 ntc = rx_ring->next_to_clean; u32 cnt = rx_ring->count; u32 xdp_xmit = 0; u32 cached_ntu; bool failure; u32 first; /* Frame size depend on rx_ring setup when PAGE_SIZE=4K */ #if (PAGE_SIZE < 8192) xdp->frame_sz = ice_rx_frame_truesize(rx_ring, 0); #endif xdp_prog = READ_ONCE(rx_ring->xdp_prog); if (xdp_prog) { xdp_ring = rx_ring->xdp_ring; cached_ntu = xdp_ring->next_to_use; } /* start the loop to process Rx packets bounded by 'budget' */ while (likely(total_rx_pkts < (unsigned int)budget)) { union ice_32b_rx_flex_desc *rx_desc; struct ice_rx_buf *rx_buf; struct sk_buff *skb; unsigned int size; u16 stat_err_bits; u16 vlan_tag = 0; u16 rx_ptype; /* get the Rx desc from Rx ring based on 'next_to_clean' */ rx_desc = ICE_RX_DESC(rx_ring, ntc); /* status_error_len will always be zero for unused descriptors * because it's cleared in cleanup, and overlaps with hdr_addr * which is always zero because packet split isn't used, if the * hardware wrote DD then it will be non-zero */ stat_err_bits = BIT(ICE_RX_FLEX_DESC_STATUS0_DD_S); if (!ice_test_staterr(rx_desc->wb.status_error0, stat_err_bits)) break; /* This memory barrier is needed to keep us from reading * any other fields out of the rx_desc until we know the * DD bit is set. */ dma_rmb(); ice_trace(clean_rx_irq, rx_ring, rx_desc); if (rx_desc->wb.rxdid == FDIR_DESC_RXDID || !rx_ring->netdev) { struct ice_vsi *ctrl_vsi = rx_ring->vsi; if (rx_desc->wb.rxdid == FDIR_DESC_RXDID && ctrl_vsi->vf) ice_vc_fdir_irq_handler(ctrl_vsi, rx_desc); if (++ntc == cnt) ntc = 0; rx_ring->first_desc = ntc; continue; } size = le16_to_cpu(rx_desc->wb.pkt_len) & ICE_RX_FLX_DESC_PKT_LEN_M; /* retrieve a buffer from the ring */ rx_buf = ice_get_rx_buf(rx_ring, size, ntc); if (!xdp->data) { void *hard_start; hard_start = page_address(rx_buf->page) + rx_buf->page_offset - offset; xdp_prepare_buff(xdp, hard_start, offset, size, !!offset); #if (PAGE_SIZE > 4096) /* At larger PAGE_SIZE, frame_sz depend on len size */ xdp->frame_sz = ice_rx_frame_truesize(rx_ring, size); #endif xdp_buff_clear_frags_flag(xdp); } else if (ice_add_xdp_frag(rx_ring, xdp, rx_buf, size)) { break; } if (++ntc == cnt) ntc = 0; /* skip if it is NOP desc */ if (ice_is_non_eop(rx_ring, rx_desc)) continue; ice_run_xdp(rx_ring, xdp, xdp_prog, xdp_ring, rx_buf); if (rx_buf->act == ICE_XDP_PASS) goto construct_skb; total_rx_bytes += xdp_get_buff_len(xdp); total_rx_pkts++; xdp->data = NULL; rx_ring->first_desc = ntc; continue; construct_skb: if (likely(ice_ring_uses_build_skb(rx_ring))) skb = ice_build_skb(rx_ring, xdp); else skb = ice_construct_skb(rx_ring, xdp); /* exit if we failed to retrieve a buffer */ if (!skb) { rx_ring->ring_stats->rx_stats.alloc_page_failed++; rx_buf->act = ICE_XDP_CONSUMED; if (unlikely(xdp_buff_has_frags(xdp))) ice_set_rx_bufs_act(xdp, rx_ring, ICE_XDP_CONSUMED); xdp->data = NULL; rx_ring->first_desc = ntc; break; } xdp->data = NULL; rx_ring->first_desc = ntc; stat_err_bits = BIT(ICE_RX_FLEX_DESC_STATUS0_RXE_S); if (unlikely(ice_test_staterr(rx_desc->wb.status_error0, stat_err_bits))) { dev_kfree_skb_any(skb); continue; } vlan_tag = ice_get_vlan_tag_from_rx_desc(rx_desc); /* pad the skb if needed, to make a valid ethernet frame */ if (eth_skb_pad(skb)) continue; /* probably a little skewed due to removing CRC */ total_rx_bytes += skb->len; /* populate checksum, VLAN, and protocol */ rx_ptype = le16_to_cpu(rx_desc->wb.ptype_flex_flags0) & ICE_RX_FLEX_DESC_PTYPE_M; ice_process_skb_fields(rx_ring, rx_desc, skb, rx_ptype); ice_trace(clean_rx_irq_indicate, rx_ring, rx_desc, skb); /* send completed skb up the stack */ ice_receive_skb(rx_ring, skb, vlan_tag); /* update budget accounting */ total_rx_pkts++; } first = rx_ring->first_desc; while (cached_ntc != first) { struct ice_rx_buf *buf = &rx_ring->rx_buf[cached_ntc]; if (buf->act & (ICE_XDP_TX | ICE_XDP_REDIR)) { ice_rx_buf_adjust_pg_offset(buf, xdp->frame_sz); xdp_xmit |= buf->act; } else if (buf->act & ICE_XDP_CONSUMED) { buf->pagecnt_bias++; } else if (buf->act == ICE_XDP_PASS) { ice_rx_buf_adjust_pg_offset(buf, xdp->frame_sz); } ice_put_rx_buf(rx_ring, buf); if (++cached_ntc >= cnt) cached_ntc = 0; } rx_ring->next_to_clean = ntc; /* return up to cleaned_count buffers to hardware */ failure = ice_alloc_rx_bufs(rx_ring, ICE_RX_DESC_UNUSED(rx_ring)); if (xdp_xmit) ice_finalize_xdp_rx(xdp_ring, xdp_xmit, cached_ntu); if (rx_ring->ring_stats) ice_update_rx_ring_stats(rx_ring, total_rx_pkts, total_rx_bytes); /* guarantee a trip back through this routine if there was a failure */ return failure ? budget : (int)total_rx_pkts; } static void __ice_update_sample(struct ice_q_vector *q_vector, struct ice_ring_container *rc, struct dim_sample *sample, bool is_tx) { u64 packets = 0, bytes = 0; if (is_tx) { struct ice_tx_ring *tx_ring; ice_for_each_tx_ring(tx_ring, *rc) { struct ice_ring_stats *ring_stats; ring_stats = tx_ring->ring_stats; if (!ring_stats) continue; packets += ring_stats->stats.pkts; bytes += ring_stats->stats.bytes; } } else { struct ice_rx_ring *rx_ring; ice_for_each_rx_ring(rx_ring, *rc) { struct ice_ring_stats *ring_stats; ring_stats = rx_ring->ring_stats; if (!ring_stats) continue; packets += ring_stats->stats.pkts; bytes += ring_stats->stats.bytes; } } dim_update_sample(q_vector->total_events, packets, bytes, sample); sample->comp_ctr = 0; /* if dim settings get stale, like when not updated for 1 * second or longer, force it to start again. This addresses the * frequent case of an idle queue being switched to by the * scheduler. The 1,000 here means 1,000 milliseconds. */ if (ktime_ms_delta(sample->time, rc->dim.start_sample.time) >= 1000) rc->dim.state = DIM_START_MEASURE; } /** * ice_net_dim - Update net DIM algorithm * @q_vector: the vector associated with the interrupt * * Create a DIM sample and notify net_dim() so that it can possibly decide * a new ITR value based on incoming packets, bytes, and interrupts. * * This function is a no-op if the ring is not configured to dynamic ITR. */ static void ice_net_dim(struct ice_q_vector *q_vector) { struct ice_ring_container *tx = &q_vector->tx; struct ice_ring_container *rx = &q_vector->rx; if (ITR_IS_DYNAMIC(tx)) { struct dim_sample dim_sample; __ice_update_sample(q_vector, tx, &dim_sample, true); net_dim(&tx->dim, dim_sample); } if (ITR_IS_DYNAMIC(rx)) { struct dim_sample dim_sample; __ice_update_sample(q_vector, rx, &dim_sample, false); net_dim(&rx->dim, dim_sample); } } /** * ice_buildreg_itr - build value for writing to the GLINT_DYN_CTL register * @itr_idx: interrupt throttling index * @itr: interrupt throttling value in usecs */ static u32 ice_buildreg_itr(u16 itr_idx, u16 itr) { /* The ITR value is reported in microseconds, and the register value is * recorded in 2 microsecond units. For this reason we only need to * shift by the GLINT_DYN_CTL_INTERVAL_S - ICE_ITR_GRAN_S to apply this * granularity as a shift instead of division. The mask makes sure the * ITR value is never odd so we don't accidentally write into the field * prior to the ITR field. */ itr &= ICE_ITR_MASK; return GLINT_DYN_CTL_INTENA_M | GLINT_DYN_CTL_CLEARPBA_M | (itr_idx << GLINT_DYN_CTL_ITR_INDX_S) | (itr << (GLINT_DYN_CTL_INTERVAL_S - ICE_ITR_GRAN_S)); } /** * ice_enable_interrupt - re-enable MSI-X interrupt * @q_vector: the vector associated with the interrupt to enable * * If the VSI is down, the interrupt will not be re-enabled. Also, * when enabling the interrupt always reset the wb_on_itr to false * and trigger a software interrupt to clean out internal state. */ static void ice_enable_interrupt(struct ice_q_vector *q_vector) { struct ice_vsi *vsi = q_vector->vsi; bool wb_en = q_vector->wb_on_itr; u32 itr_val; if (test_bit(ICE_DOWN, vsi->state)) return; /* trigger an ITR delayed software interrupt when exiting busy poll, to * make sure to catch any pending cleanups that might have been missed * due to interrupt state transition. If busy poll or poll isn't * enabled, then don't update ITR, and just enable the interrupt. */ if (!wb_en) { itr_val = ice_buildreg_itr(ICE_ITR_NONE, 0); } else { q_vector->wb_on_itr = false; /* do two things here with a single write. Set up the third ITR * index to be used for software interrupt moderation, and then * trigger a software interrupt with a rate limit of 20K on * software interrupts, this will help avoid high interrupt * loads due to frequently polling and exiting polling. */ itr_val = ice_buildreg_itr(ICE_IDX_ITR2, ICE_ITR_20K); itr_val |= GLINT_DYN_CTL_SWINT_TRIG_M | ICE_IDX_ITR2 << GLINT_DYN_CTL_SW_ITR_INDX_S | GLINT_DYN_CTL_SW_ITR_INDX_ENA_M; } wr32(&vsi->back->hw, GLINT_DYN_CTL(q_vector->reg_idx), itr_val); } /** * ice_set_wb_on_itr - set WB_ON_ITR for this q_vector * @q_vector: q_vector to set WB_ON_ITR on * * We need to tell hardware to write-back completed descriptors even when * interrupts are disabled. Descriptors will be written back on cache line * boundaries without WB_ON_ITR enabled, but if we don't enable WB_ON_ITR * descriptors may not be written back if they don't fill a cache line until * the next interrupt. * * This sets the write-back frequency to whatever was set previously for the * ITR indices. Also, set the INTENA_MSK bit to make sure hardware knows we * aren't meddling with the INTENA_M bit. */ static void ice_set_wb_on_itr(struct ice_q_vector *q_vector) { struct ice_vsi *vsi = q_vector->vsi; /* already in wb_on_itr mode no need to change it */ if (q_vector->wb_on_itr) return; /* use previously set ITR values for all of the ITR indices by * specifying ICE_ITR_NONE, which will vary in adaptive (AIM) mode and * be static in non-adaptive mode (user configured) */ wr32(&vsi->back->hw, GLINT_DYN_CTL(q_vector->reg_idx), ((ICE_ITR_NONE << GLINT_DYN_CTL_ITR_INDX_S) & GLINT_DYN_CTL_ITR_INDX_M) | GLINT_DYN_CTL_INTENA_MSK_M | GLINT_DYN_CTL_WB_ON_ITR_M); q_vector->wb_on_itr = true; } /** * ice_napi_poll - NAPI polling Rx/Tx cleanup routine * @napi: napi struct with our devices info in it * @budget: amount of work driver is allowed to do this pass, in packets * * This function will clean all queues associated with a q_vector. * * Returns the amount of work done */ int ice_napi_poll(struct napi_struct *napi, int budget) { struct ice_q_vector *q_vector = container_of(napi, struct ice_q_vector, napi); struct ice_tx_ring *tx_ring; struct ice_rx_ring *rx_ring; bool clean_complete = true; int budget_per_ring; int work_done = 0; /* Since the actual Tx work is minimal, we can give the Tx a larger * budget and be more aggressive about cleaning up the Tx descriptors. */ ice_for_each_tx_ring(tx_ring, q_vector->tx) { bool wd; if (tx_ring->xsk_pool) wd = ice_xmit_zc(tx_ring); else if (ice_ring_is_xdp(tx_ring)) wd = true; else wd = ice_clean_tx_irq(tx_ring, budget); if (!wd) clean_complete = false; } /* Handle case where we are called by netpoll with a budget of 0 */ if (unlikely(budget <= 0)) return budget; /* normally we have 1 Rx ring per q_vector */ if (unlikely(q_vector->num_ring_rx > 1)) /* We attempt to distribute budget to each Rx queue fairly, but * don't allow the budget to go below 1 because that would exit * polling early. */ budget_per_ring = max_t(int, budget / q_vector->num_ring_rx, 1); else /* Max of 1 Rx ring in this q_vector so give it the budget */ budget_per_ring = budget; ice_for_each_rx_ring(rx_ring, q_vector->rx) { int cleaned; /* A dedicated path for zero-copy allows making a single * comparison in the irq context instead of many inside the * ice_clean_rx_irq function and makes the codebase cleaner. */ cleaned = rx_ring->xsk_pool ? ice_clean_rx_irq_zc(rx_ring, budget_per_ring) : ice_clean_rx_irq(rx_ring, budget_per_ring); work_done += cleaned; /* if we clean as many as budgeted, we must not be done */ if (cleaned >= budget_per_ring) clean_complete = false; } /* If work not completed, return budget and polling will return */ if (!clean_complete) { /* Set the writeback on ITR so partial completions of * cache-lines will still continue even if we're polling. */ ice_set_wb_on_itr(q_vector); return budget; } /* Exit the polling mode, but don't re-enable interrupts if stack might * poll us due to busy-polling */ if (napi_complete_done(napi, work_done)) { ice_net_dim(q_vector); ice_enable_interrupt(q_vector); } else { ice_set_wb_on_itr(q_vector); } return min_t(int, work_done, budget - 1); } /** * __ice_maybe_stop_tx - 2nd level check for Tx stop conditions * @tx_ring: the ring to be checked * @size: the size buffer we want to assure is available * * Returns -EBUSY if a stop is needed, else 0 */ static int __ice_maybe_stop_tx(struct ice_tx_ring *tx_ring, unsigned int size) { netif_tx_stop_queue(txring_txq(tx_ring)); /* Memory barrier before checking head and tail */ smp_mb(); /* Check again in a case another CPU has just made room available. */ if (likely(ICE_DESC_UNUSED(tx_ring) < size)) return -EBUSY; /* A reprieve! - use start_queue because it doesn't call schedule */ netif_tx_start_queue(txring_txq(tx_ring)); ++tx_ring->ring_stats->tx_stats.restart_q; return 0; } /** * ice_maybe_stop_tx - 1st level check for Tx stop conditions * @tx_ring: the ring to be checked * @size: the size buffer we want to assure is available * * Returns 0 if stop is not needed */ static int ice_maybe_stop_tx(struct ice_tx_ring *tx_ring, unsigned int size) { if (likely(ICE_DESC_UNUSED(tx_ring) >= size)) return 0; return __ice_maybe_stop_tx(tx_ring, size); } /** * ice_tx_map - Build the Tx descriptor * @tx_ring: ring to send buffer on * @first: first buffer info buffer to use * @off: pointer to struct that holds offload parameters * * This function loops over the skb data pointed to by *first * and gets a physical address for each memory location and programs * it and the length into the transmit descriptor. */ static void ice_tx_map(struct ice_tx_ring *tx_ring, struct ice_tx_buf *first, struct ice_tx_offload_params *off) { u64 td_offset, td_tag, td_cmd; u16 i = tx_ring->next_to_use; unsigned int data_len, size; struct ice_tx_desc *tx_desc; struct ice_tx_buf *tx_buf; struct sk_buff *skb; skb_frag_t *frag; dma_addr_t dma; bool kick; td_tag = off->td_l2tag1; td_cmd = off->td_cmd; td_offset = off->td_offset; skb = first->skb; data_len = skb->data_len; size = skb_headlen(skb); tx_desc = ICE_TX_DESC(tx_ring, i); if (first->tx_flags & ICE_TX_FLAGS_HW_VLAN) { td_cmd |= (u64)ICE_TX_DESC_CMD_IL2TAG1; td_tag = first->vid; } dma = dma_map_single(tx_ring->dev, skb->data, size, DMA_TO_DEVICE); tx_buf = first; for (frag = &skb_shinfo(skb)->frags[0];; frag++) { unsigned int max_data = ICE_MAX_DATA_PER_TXD_ALIGNED; if (dma_mapping_error(tx_ring->dev, dma)) goto dma_error; /* record length, and DMA address */ dma_unmap_len_set(tx_buf, len, size); dma_unmap_addr_set(tx_buf, dma, dma); /* align size to end of page */ max_data += -dma & (ICE_MAX_READ_REQ_SIZE - 1); tx_desc->buf_addr = cpu_to_le64(dma); /* account for data chunks larger than the hardware * can handle */ while (unlikely(size > ICE_MAX_DATA_PER_TXD)) { tx_desc->cmd_type_offset_bsz = ice_build_ctob(td_cmd, td_offset, max_data, td_tag); tx_desc++; i++; if (i == tx_ring->count) { tx_desc = ICE_TX_DESC(tx_ring, 0); i = 0; } dma += max_data; size -= max_data; max_data = ICE_MAX_DATA_PER_TXD_ALIGNED; tx_desc->buf_addr = cpu_to_le64(dma); } if (likely(!data_len)) break; tx_desc->cmd_type_offset_bsz = ice_build_ctob(td_cmd, td_offset, size, td_tag); tx_desc++; i++; if (i == tx_ring->count) { tx_desc = ICE_TX_DESC(tx_ring, 0); i = 0; } size = skb_frag_size(frag); data_len -= size; dma = skb_frag_dma_map(tx_ring->dev, frag, 0, size, DMA_TO_DEVICE); tx_buf = &tx_ring->tx_buf[i]; tx_buf->type = ICE_TX_BUF_FRAG; } /* record SW timestamp if HW timestamp is not available */ skb_tx_timestamp(first->skb); i++; if (i == tx_ring->count) i = 0; /* write last descriptor with RS and EOP bits */ td_cmd |= (u64)ICE_TXD_LAST_DESC_CMD; tx_desc->cmd_type_offset_bsz = ice_build_ctob(td_cmd, td_offset, size, td_tag); /* Force memory writes to complete before letting h/w know there * are new descriptors to fetch. * * We also use this memory barrier to make certain all of the * status bits have been updated before next_to_watch is written. */ wmb(); /* set next_to_watch value indicating a packet is present */ first->next_to_watch = tx_desc; tx_ring->next_to_use = i; ice_maybe_stop_tx(tx_ring, DESC_NEEDED); /* notify HW of packet */ kick = __netdev_tx_sent_queue(txring_txq(tx_ring), first->bytecount, netdev_xmit_more()); if (kick) /* notify HW of packet */ writel(i, tx_ring->tail); return; dma_error: /* clear DMA mappings for failed tx_buf map */ for (;;) { tx_buf = &tx_ring->tx_buf[i]; ice_unmap_and_free_tx_buf(tx_ring, tx_buf); if (tx_buf == first) break; if (i == 0) i = tx_ring->count; i--; } tx_ring->next_to_use = i; } /** * ice_tx_csum - Enable Tx checksum offloads * @first: pointer to the first descriptor * @off: pointer to struct that holds offload parameters * * Returns 0 or error (negative) if checksum offload can't happen, 1 otherwise. */ static int ice_tx_csum(struct ice_tx_buf *first, struct ice_tx_offload_params *off) { u32 l4_len = 0, l3_len = 0, l2_len = 0; struct sk_buff *skb = first->skb; union { struct iphdr *v4; struct ipv6hdr *v6; unsigned char *hdr; } ip; union { struct tcphdr *tcp; unsigned char *hdr; } l4; __be16 frag_off, protocol; unsigned char *exthdr; u32 offset, cmd = 0; u8 l4_proto = 0; if (skb->ip_summed != CHECKSUM_PARTIAL) return 0; protocol = vlan_get_protocol(skb); if (eth_p_mpls(protocol)) { ip.hdr = skb_inner_network_header(skb); l4.hdr = skb_checksum_start(skb); } else { ip.hdr = skb_network_header(skb); l4.hdr = skb_transport_header(skb); } /* compute outer L2 header size */ l2_len = ip.hdr - skb->data; offset = (l2_len / 2) << ICE_TX_DESC_LEN_MACLEN_S; /* set the tx_flags to indicate the IP protocol type. this is * required so that checksum header computation below is accurate. */ if (ip.v4->version == 4) first->tx_flags |= ICE_TX_FLAGS_IPV4; else if (ip.v6->version == 6) first->tx_flags |= ICE_TX_FLAGS_IPV6; if (skb->encapsulation) { bool gso_ena = false; u32 tunnel = 0; /* define outer network header type */ if (first->tx_flags & ICE_TX_FLAGS_IPV4) { tunnel |= (first->tx_flags & ICE_TX_FLAGS_TSO) ? ICE_TX_CTX_EIPT_IPV4 : ICE_TX_CTX_EIPT_IPV4_NO_CSUM; l4_proto = ip.v4->protocol; } else if (first->tx_flags & ICE_TX_FLAGS_IPV6) { int ret; tunnel |= ICE_TX_CTX_EIPT_IPV6; exthdr = ip.hdr + sizeof(*ip.v6); l4_proto = ip.v6->nexthdr; ret = ipv6_skip_exthdr(skb, exthdr - skb->data, &l4_proto, &frag_off); if (ret < 0) return -1; } /* define outer transport */ switch (l4_proto) { case IPPROTO_UDP: tunnel |= ICE_TXD_CTX_UDP_TUNNELING; first->tx_flags |= ICE_TX_FLAGS_TUNNEL; break; case IPPROTO_GRE: tunnel |= ICE_TXD_CTX_GRE_TUNNELING; first->tx_flags |= ICE_TX_FLAGS_TUNNEL; break; case IPPROTO_IPIP: case IPPROTO_IPV6: first->tx_flags |= ICE_TX_FLAGS_TUNNEL; l4.hdr = skb_inner_network_header(skb); break; default: if (first->tx_flags & ICE_TX_FLAGS_TSO) return -1; skb_checksum_help(skb); return 0; } /* compute outer L3 header size */ tunnel |= ((l4.hdr - ip.hdr) / 4) << ICE_TXD_CTX_QW0_EIPLEN_S; /* switch IP header pointer from outer to inner header */ ip.hdr = skb_inner_network_header(skb); /* compute tunnel header size */ tunnel |= ((ip.hdr - l4.hdr) / 2) << ICE_TXD_CTX_QW0_NATLEN_S; gso_ena = skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL; /* indicate if we need to offload outer UDP header */ if ((first->tx_flags & ICE_TX_FLAGS_TSO) && !gso_ena && (skb_shinfo(skb)->gso_type & SKB_GSO_UDP_TUNNEL_CSUM)) tunnel |= ICE_TXD_CTX_QW0_L4T_CS_M; /* record tunnel offload values */ off->cd_tunnel_params |= tunnel; /* set DTYP=1 to indicate that it's an Tx context descriptor * in IPsec tunnel mode with Tx offloads in Quad word 1 */ off->cd_qw1 |= (u64)ICE_TX_DESC_DTYPE_CTX; /* switch L4 header pointer from outer to inner */ l4.hdr = skb_inner_transport_header(skb); l4_proto = 0; /* reset type as we transition from outer to inner headers */ first->tx_flags &= ~(ICE_TX_FLAGS_IPV4 | ICE_TX_FLAGS_IPV6); if (ip.v4->version == 4) first->tx_flags |= ICE_TX_FLAGS_IPV4; if (ip.v6->version == 6) first->tx_flags |= ICE_TX_FLAGS_IPV6; } /* Enable IP checksum offloads */ if (first->tx_flags & ICE_TX_FLAGS_IPV4) { l4_proto = ip.v4->protocol; /* the stack computes the IP header already, the only time we * need the hardware to recompute it is in the case of TSO. */ if (first->tx_flags & ICE_TX_FLAGS_TSO) cmd |= ICE_TX_DESC_CMD_IIPT_IPV4_CSUM; else cmd |= ICE_TX_DESC_CMD_IIPT_IPV4; } else if (first->tx_flags & ICE_TX_FLAGS_IPV6) { cmd |= ICE_TX_DESC_CMD_IIPT_IPV6; exthdr = ip.hdr + sizeof(*ip.v6); l4_proto = ip.v6->nexthdr; if (l4.hdr != exthdr) ipv6_skip_exthdr(skb, exthdr - skb->data, &l4_proto, &frag_off); } else { return -1; } /* compute inner L3 header size */ l3_len = l4.hdr - ip.hdr; offset |= (l3_len / 4) << ICE_TX_DESC_LEN_IPLEN_S; /* Enable L4 checksum offloads */ switch (l4_proto) { case IPPROTO_TCP: /* enable checksum offloads */ cmd |= ICE_TX_DESC_CMD_L4T_EOFT_TCP; l4_len = l4.tcp->doff; offset |= l4_len << ICE_TX_DESC_LEN_L4_LEN_S; break; case IPPROTO_UDP: /* enable UDP checksum offload */ cmd |= ICE_TX_DESC_CMD_L4T_EOFT_UDP; l4_len = (sizeof(struct udphdr) >> 2); offset |= l4_len << ICE_TX_DESC_LEN_L4_LEN_S; break; case IPPROTO_SCTP: /* enable SCTP checksum offload */ cmd |= ICE_TX_DESC_CMD_L4T_EOFT_SCTP; l4_len = sizeof(struct sctphdr) >> 2; offset |= l4_len << ICE_TX_DESC_LEN_L4_LEN_S; break; default: if (first->tx_flags & ICE_TX_FLAGS_TSO) return -1; skb_checksum_help(skb); return 0; } off->td_cmd |= cmd; off->td_offset |= offset; return 1; } /** * ice_tx_prepare_vlan_flags - prepare generic Tx VLAN tagging flags for HW * @tx_ring: ring to send buffer on * @first: pointer to struct ice_tx_buf * * Checks the skb and set up correspondingly several generic transmit flags * related to VLAN tagging for the HW, such as VLAN, DCB, etc. */ static void ice_tx_prepare_vlan_flags(struct ice_tx_ring *tx_ring, struct ice_tx_buf *first) { struct sk_buff *skb = first->skb; /* nothing left to do, software offloaded VLAN */ if (!skb_vlan_tag_present(skb) && eth_type_vlan(skb->protocol)) return; /* the VLAN ethertype/tpid is determined by VSI configuration and netdev * feature flags, which the driver only allows either 802.1Q or 802.1ad * VLAN offloads exclusively so we only care about the VLAN ID here */ if (skb_vlan_tag_present(skb)) { first->vid = skb_vlan_tag_get(skb); if (tx_ring->flags & ICE_TX_FLAGS_RING_VLAN_L2TAG2) first->tx_flags |= ICE_TX_FLAGS_HW_OUTER_SINGLE_VLAN; else first->tx_flags |= ICE_TX_FLAGS_HW_VLAN; } ice_tx_prepare_vlan_flags_dcb(tx_ring, first); } /** * ice_tso - computes mss and TSO length to prepare for TSO * @first: pointer to struct ice_tx_buf * @off: pointer to struct that holds offload parameters * * Returns 0 or error (negative) if TSO can't happen, 1 otherwise. */ static int ice_tso(struct ice_tx_buf *first, struct ice_tx_offload_params *off) { struct sk_buff *skb = first->skb; union { struct iphdr *v4; struct ipv6hdr *v6; unsigned char *hdr; } ip; union { struct tcphdr *tcp; struct udphdr *udp; unsigned char *hdr; } l4; u64 cd_mss, cd_tso_len; __be16 protocol; u32 paylen; u8 l4_start; int err; if (skb->ip_summed != CHECKSUM_PARTIAL) return 0; if (!skb_is_gso(skb)) return 0; err = skb_cow_head(skb, 0); if (err < 0) return err; protocol = vlan_get_protocol(skb); if (eth_p_mpls(protocol)) ip.hdr = skb_inner_network_header(skb); else ip.hdr = skb_network_header(skb); l4.hdr = skb_checksum_start(skb); /* initialize outer IP header fields */ if (ip.v4->version == 4) { ip.v4->tot_len = 0; ip.v4->check = 0; } else { ip.v6->payload_len = 0; } if (skb_shinfo(skb)->gso_type & (SKB_GSO_GRE | SKB_GSO_GRE_CSUM | SKB_GSO_IPXIP4 | SKB_GSO_IPXIP6 | SKB_GSO_UDP_TUNNEL | SKB_GSO_UDP_TUNNEL_CSUM)) { if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL) && (skb_shinfo(skb)->gso_type & SKB_GSO_UDP_TUNNEL_CSUM)) { l4.udp->len = 0; /* determine offset of outer transport header */ l4_start = (u8)(l4.hdr - skb->data); /* remove payload length from outer checksum */ paylen = skb->len - l4_start; csum_replace_by_diff(&l4.udp->check, (__force __wsum)htonl(paylen)); } /* reset pointers to inner headers */ ip.hdr = skb_inner_network_header(skb); l4.hdr = skb_inner_transport_header(skb); /* initialize inner IP header fields */ if (ip.v4->version == 4) { ip.v4->tot_len = 0; ip.v4->check = 0; } else { ip.v6->payload_len = 0; } } /* determine offset of transport header */ l4_start = (u8)(l4.hdr - skb->data); /* remove payload length from checksum */ paylen = skb->len - l4_start; if (skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) { csum_replace_by_diff(&l4.udp->check, (__force __wsum)htonl(paylen)); /* compute length of UDP segmentation header */ off->header_len = (u8)sizeof(l4.udp) + l4_start; } else { csum_replace_by_diff(&l4.tcp->check, (__force __wsum)htonl(paylen)); /* compute length of TCP segmentation header */ off->header_len = (u8)((l4.tcp->doff * 4) + l4_start); } /* update gso_segs and bytecount */ first->gso_segs = skb_shinfo(skb)->gso_segs; first->bytecount += (first->gso_segs - 1) * off->header_len; cd_tso_len = skb->len - off->header_len; cd_mss = skb_shinfo(skb)->gso_size; /* record cdesc_qw1 with TSO parameters */ off->cd_qw1 |= (u64)(ICE_TX_DESC_DTYPE_CTX | (ICE_TX_CTX_DESC_TSO << ICE_TXD_CTX_QW1_CMD_S) | (cd_tso_len << ICE_TXD_CTX_QW1_TSO_LEN_S) | (cd_mss << ICE_TXD_CTX_QW1_MSS_S)); first->tx_flags |= ICE_TX_FLAGS_TSO; return 1; } /** * ice_txd_use_count - estimate the number of descriptors needed for Tx * @size: transmit request size in bytes * * Due to hardware alignment restrictions (4K alignment), we need to * assume that we can have no more than 12K of data per descriptor, even * though each descriptor can take up to 16K - 1 bytes of aligned memory. * Thus, we need to divide by 12K. But division is slow! Instead, * we decompose the operation into shifts and one relatively cheap * multiply operation. * * To divide by 12K, we first divide by 4K, then divide by 3: * To divide by 4K, shift right by 12 bits * To divide by 3, multiply by 85, then divide by 256 * (Divide by 256 is done by shifting right by 8 bits) * Finally, we add one to round up. Because 256 isn't an exact multiple of * 3, we'll underestimate near each multiple of 12K. This is actually more * accurate as we have 4K - 1 of wiggle room that we can fit into the last * segment. For our purposes this is accurate out to 1M which is orders of * magnitude greater than our largest possible GSO size. * * This would then be implemented as: * return (((size >> 12) * 85) >> 8) + ICE_DESCS_FOR_SKB_DATA_PTR; * * Since multiplication and division are commutative, we can reorder * operations into: * return ((size * 85) >> 20) + ICE_DESCS_FOR_SKB_DATA_PTR; */ static unsigned int ice_txd_use_count(unsigned int size) { return ((size * 85) >> 20) + ICE_DESCS_FOR_SKB_DATA_PTR; } /** * ice_xmit_desc_count - calculate number of Tx descriptors needed * @skb: send buffer * * Returns number of data descriptors needed for this skb. */ static unsigned int ice_xmit_desc_count(struct sk_buff *skb) { const skb_frag_t *frag = &skb_shinfo(skb)->frags[0]; unsigned int nr_frags = skb_shinfo(skb)->nr_frags; unsigned int count = 0, size = skb_headlen(skb); for (;;) { count += ice_txd_use_count(size); if (!nr_frags--) break; size = skb_frag_size(frag++); } return count; } /** * __ice_chk_linearize - Check if there are more than 8 buffers per packet * @skb: send buffer * * Note: This HW can't DMA more than 8 buffers to build a packet on the wire * and so we need to figure out the cases where we need to linearize the skb. * * For TSO we need to count the TSO header and segment payload separately. * As such we need to check cases where we have 7 fragments or more as we * can potentially require 9 DMA transactions, 1 for the TSO header, 1 for * the segment payload in the first descriptor, and another 7 for the * fragments. */ static bool __ice_chk_linearize(struct sk_buff *skb) { const skb_frag_t *frag, *stale; int nr_frags, sum; /* no need to check if number of frags is less than 7 */ nr_frags = skb_shinfo(skb)->nr_frags; if (nr_frags < (ICE_MAX_BUF_TXD - 1)) return false; /* We need to walk through the list and validate that each group * of 6 fragments totals at least gso_size. */ nr_frags -= ICE_MAX_BUF_TXD - 2; frag = &skb_shinfo(skb)->frags[0]; /* Initialize size to the negative value of gso_size minus 1. We * use this as the worst case scenario in which the frag ahead * of us only provides one byte which is why we are limited to 6 * descriptors for a single transmit as the header and previous * fragment are already consuming 2 descriptors. */ sum = 1 - skb_shinfo(skb)->gso_size; /* Add size of frags 0 through 4 to create our initial sum */ sum += skb_frag_size(frag++); sum += skb_frag_size(frag++); sum += skb_frag_size(frag++); sum += skb_frag_size(frag++); sum += skb_frag_size(frag++); /* Walk through fragments adding latest fragment, testing it, and * then removing stale fragments from the sum. */ for (stale = &skb_shinfo(skb)->frags[0];; stale++) { int stale_size = skb_frag_size(stale); sum += skb_frag_size(frag++); /* The stale fragment may present us with a smaller * descriptor than the actual fragment size. To account * for that we need to remove all the data on the front and * figure out what the remainder would be in the last * descriptor associated with the fragment. */ if (stale_size > ICE_MAX_DATA_PER_TXD) { int align_pad = -(skb_frag_off(stale)) & (ICE_MAX_READ_REQ_SIZE - 1); sum -= align_pad; stale_size -= align_pad; do { sum -= ICE_MAX_DATA_PER_TXD_ALIGNED; stale_size -= ICE_MAX_DATA_PER_TXD_ALIGNED; } while (stale_size > ICE_MAX_DATA_PER_TXD); } /* if sum is negative we failed to make sufficient progress */ if (sum < 0) return true; if (!nr_frags--) break; sum -= stale_size; } return false; } /** * ice_chk_linearize - Check if there are more than 8 fragments per packet * @skb: send buffer * @count: number of buffers used * * Note: Our HW can't scatter-gather more than 8 fragments to build * a packet on the wire and so we need to figure out the cases where we * need to linearize the skb. */ static bool ice_chk_linearize(struct sk_buff *skb, unsigned int count) { /* Both TSO and single send will work if count is less than 8 */ if (likely(count < ICE_MAX_BUF_TXD)) return false; if (skb_is_gso(skb)) return __ice_chk_linearize(skb); /* we can support up to 8 data buffers for a single send */ return count != ICE_MAX_BUF_TXD; } /** * ice_tstamp - set up context descriptor for hardware timestamp * @tx_ring: pointer to the Tx ring to send buffer on * @skb: pointer to the SKB we're sending * @first: Tx buffer * @off: Tx offload parameters */ static void ice_tstamp(struct ice_tx_ring *tx_ring, struct sk_buff *skb, struct ice_tx_buf *first, struct ice_tx_offload_params *off) { s8 idx; /* only timestamp the outbound packet if the user has requested it */ if (likely(!(skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP))) return; if (!tx_ring->ptp_tx) return; /* Tx timestamps cannot be sampled when doing TSO */ if (first->tx_flags & ICE_TX_FLAGS_TSO) return; /* Grab an open timestamp slot */ idx = ice_ptp_request_ts(tx_ring->tx_tstamps, skb); if (idx < 0) { tx_ring->vsi->back->ptp.tx_hwtstamp_skipped++; return; } off->cd_qw1 |= (u64)(ICE_TX_DESC_DTYPE_CTX | (ICE_TX_CTX_DESC_TSYN << ICE_TXD_CTX_QW1_CMD_S) | ((u64)idx << ICE_TXD_CTX_QW1_TSO_LEN_S)); first->tx_flags |= ICE_TX_FLAGS_TSYN; } /** * ice_xmit_frame_ring - Sends buffer on Tx ring * @skb: send buffer * @tx_ring: ring to send buffer on * * Returns NETDEV_TX_OK if sent, else an error code */ static netdev_tx_t ice_xmit_frame_ring(struct sk_buff *skb, struct ice_tx_ring *tx_ring) { struct ice_tx_offload_params offload = { 0 }; struct ice_vsi *vsi = tx_ring->vsi; struct ice_tx_buf *first; struct ethhdr *eth; unsigned int count; int tso, csum; ice_trace(xmit_frame_ring, tx_ring, skb); if (unlikely(ipv6_hopopt_jumbo_remove(skb))) goto out_drop; count = ice_xmit_desc_count(skb); if (ice_chk_linearize(skb, count)) { if (__skb_linearize(skb)) goto out_drop; count = ice_txd_use_count(skb->len); tx_ring->ring_stats->tx_stats.tx_linearize++; } /* need: 1 descriptor per page * PAGE_SIZE/ICE_MAX_DATA_PER_TXD, * + 1 desc for skb_head_len/ICE_MAX_DATA_PER_TXD, * + 4 desc gap to avoid the cache line where head is, * + 1 desc for context descriptor, * otherwise try next time */ if (ice_maybe_stop_tx(tx_ring, count + ICE_DESCS_PER_CACHE_LINE + ICE_DESCS_FOR_CTX_DESC)) { tx_ring->ring_stats->tx_stats.tx_busy++; return NETDEV_TX_BUSY; } /* prefetch for bql data which is infrequently used */ netdev_txq_bql_enqueue_prefetchw(txring_txq(tx_ring)); offload.tx_ring = tx_ring; /* record the location of the first descriptor for this packet */ first = &tx_ring->tx_buf[tx_ring->next_to_use]; first->skb = skb; first->type = ICE_TX_BUF_SKB; first->bytecount = max_t(unsigned int, skb->len, ETH_ZLEN); first->gso_segs = 1; first->tx_flags = 0; /* prepare the VLAN tagging flags for Tx */ ice_tx_prepare_vlan_flags(tx_ring, first); if (first->tx_flags & ICE_TX_FLAGS_HW_OUTER_SINGLE_VLAN) { offload.cd_qw1 |= (u64)(ICE_TX_DESC_DTYPE_CTX | (ICE_TX_CTX_DESC_IL2TAG2 << ICE_TXD_CTX_QW1_CMD_S)); offload.cd_l2tag2 = first->vid; } /* set up TSO offload */ tso = ice_tso(first, &offload); if (tso < 0) goto out_drop; /* always set up Tx checksum offload */ csum = ice_tx_csum(first, &offload); if (csum < 0) goto out_drop; /* allow CONTROL frames egress from main VSI if FW LLDP disabled */ eth = (struct ethhdr *)skb_mac_header(skb); if (unlikely((skb->priority == TC_PRIO_CONTROL || eth->h_proto == htons(ETH_P_LLDP)) && vsi->type == ICE_VSI_PF && vsi->port_info->qos_cfg.is_sw_lldp)) offload.cd_qw1 |= (u64)(ICE_TX_DESC_DTYPE_CTX | ICE_TX_CTX_DESC_SWTCH_UPLINK << ICE_TXD_CTX_QW1_CMD_S); ice_tstamp(tx_ring, skb, first, &offload); if (ice_is_switchdev_running(vsi->back)) ice_eswitch_set_target_vsi(skb, &offload); if (offload.cd_qw1 & ICE_TX_DESC_DTYPE_CTX) { struct ice_tx_ctx_desc *cdesc; u16 i = tx_ring->next_to_use; /* grab the next descriptor */ cdesc = ICE_TX_CTX_DESC(tx_ring, i); i++; tx_ring->next_to_use = (i < tx_ring->count) ? i : 0; /* setup context descriptor */ cdesc->tunneling_params = cpu_to_le32(offload.cd_tunnel_params); cdesc->l2tag2 = cpu_to_le16(offload.cd_l2tag2); cdesc->rsvd = cpu_to_le16(0); cdesc->qw1 = cpu_to_le64(offload.cd_qw1); } ice_tx_map(tx_ring, first, &offload); return NETDEV_TX_OK; out_drop: ice_trace(xmit_frame_ring_drop, tx_ring, skb); dev_kfree_skb_any(skb); return NETDEV_TX_OK; } /** * ice_start_xmit - Selects the correct VSI and Tx queue to send buffer * @skb: send buffer * @netdev: network interface device structure * * Returns NETDEV_TX_OK if sent, else an error code */ netdev_tx_t ice_start_xmit(struct sk_buff *skb, struct net_device *netdev) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; struct ice_tx_ring *tx_ring; tx_ring = vsi->tx_rings[skb->queue_mapping]; /* hardware can't handle really short frames, hardware padding works * beyond this point */ if (skb_put_padto(skb, ICE_MIN_TX_LEN)) return NETDEV_TX_OK; return ice_xmit_frame_ring(skb, tx_ring); } /** * ice_get_dscp_up - return the UP/TC value for a SKB * @dcbcfg: DCB config that contains DSCP to UP/TC mapping * @skb: SKB to query for info to determine UP/TC * * This function is to only be called when the PF is in L3 DSCP PFC mode */ static u8 ice_get_dscp_up(struct ice_dcbx_cfg *dcbcfg, struct sk_buff *skb) { u8 dscp = 0; if (skb->protocol == htons(ETH_P_IP)) dscp = ipv4_get_dsfield(ip_hdr(skb)) >> 2; else if (skb->protocol == htons(ETH_P_IPV6)) dscp = ipv6_get_dsfield(ipv6_hdr(skb)) >> 2; return dcbcfg->dscp_map[dscp]; } u16 ice_select_queue(struct net_device *netdev, struct sk_buff *skb, struct net_device *sb_dev) { struct ice_pf *pf = ice_netdev_to_pf(netdev); struct ice_dcbx_cfg *dcbcfg; dcbcfg = &pf->hw.port_info->qos_cfg.local_dcbx_cfg; if (dcbcfg->pfc_mode == ICE_QOS_MODE_DSCP) skb->priority = ice_get_dscp_up(dcbcfg, skb); return netdev_pick_tx(netdev, skb, sb_dev); } /** * ice_clean_ctrl_tx_irq - interrupt handler for flow director Tx queue * @tx_ring: tx_ring to clean */ void ice_clean_ctrl_tx_irq(struct ice_tx_ring *tx_ring) { struct ice_vsi *vsi = tx_ring->vsi; s16 i = tx_ring->next_to_clean; int budget = ICE_DFLT_IRQ_WORK; struct ice_tx_desc *tx_desc; struct ice_tx_buf *tx_buf; tx_buf = &tx_ring->tx_buf[i]; tx_desc = ICE_TX_DESC(tx_ring, i); i -= tx_ring->count; do { struct ice_tx_desc *eop_desc = tx_buf->next_to_watch; /* if next_to_watch is not set then there is no pending work */ if (!eop_desc) break; /* prevent any other reads prior to eop_desc */ smp_rmb(); /* if the descriptor isn't done, no work to do */ if (!(eop_desc->cmd_type_offset_bsz & cpu_to_le64(ICE_TX_DESC_DTYPE_DESC_DONE))) break; /* clear next_to_watch to prevent false hangs */ tx_buf->next_to_watch = NULL; tx_desc->buf_addr = 0; tx_desc->cmd_type_offset_bsz = 0; /* move past filter desc */ tx_buf++; tx_desc++; i++; if (unlikely(!i)) { i -= tx_ring->count; tx_buf = tx_ring->tx_buf; tx_desc = ICE_TX_DESC(tx_ring, 0); } /* unmap the data header */ if (dma_unmap_len(tx_buf, len)) dma_unmap_single(tx_ring->dev, dma_unmap_addr(tx_buf, dma), dma_unmap_len(tx_buf, len), DMA_TO_DEVICE); if (tx_buf->type == ICE_TX_BUF_DUMMY) devm_kfree(tx_ring->dev, tx_buf->raw_buf); /* clear next_to_watch to prevent false hangs */ tx_buf->type = ICE_TX_BUF_EMPTY; tx_buf->tx_flags = 0; tx_buf->next_to_watch = NULL; dma_unmap_len_set(tx_buf, len, 0); tx_desc->buf_addr = 0; tx_desc->cmd_type_offset_bsz = 0; /* move past eop_desc for start of next FD desc */ tx_buf++; tx_desc++; i++; if (unlikely(!i)) { i -= tx_ring->count; tx_buf = tx_ring->tx_buf; tx_desc = ICE_TX_DESC(tx_ring, 0); } budget--; } while (likely(budget)); i += tx_ring->count; tx_ring->next_to_clean = i; /* re-enable interrupt if needed */ ice_irq_dynamic_ena(&vsi->back->hw, vsi, vsi->q_vectors[0]); }
linux-master
drivers/net/ethernet/intel/ice/ice_txrx.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2019-2021, Intel Corporation. */ #include "ice_vsi_vlan_ops.h" #include "ice_vsi_vlan_lib.h" #include "ice_vlan_mode.h" #include "ice.h" #include "ice_vf_vsi_vlan_ops.h" #include "ice_sriov.h" static int noop_vlan_arg(struct ice_vsi __always_unused *vsi, struct ice_vlan __always_unused *vlan) { return 0; } static int noop_vlan(struct ice_vsi __always_unused *vsi) { return 0; } static void ice_port_vlan_on(struct ice_vsi *vsi) { struct ice_vsi_vlan_ops *vlan_ops; struct ice_pf *pf = vsi->back; if (ice_is_dvm_ena(&pf->hw)) { vlan_ops = &vsi->outer_vlan_ops; /* setup outer VLAN ops */ vlan_ops->set_port_vlan = ice_vsi_set_outer_port_vlan; vlan_ops->clear_port_vlan = ice_vsi_clear_outer_port_vlan; vlan_ops->clear_port_vlan = ice_vsi_clear_outer_port_vlan; /* setup inner VLAN ops */ vlan_ops = &vsi->inner_vlan_ops; vlan_ops->add_vlan = noop_vlan_arg; vlan_ops->del_vlan = noop_vlan_arg; vlan_ops->ena_stripping = ice_vsi_ena_inner_stripping; vlan_ops->dis_stripping = ice_vsi_dis_inner_stripping; vlan_ops->ena_insertion = ice_vsi_ena_inner_insertion; vlan_ops->dis_insertion = ice_vsi_dis_inner_insertion; } else { vlan_ops = &vsi->inner_vlan_ops; vlan_ops->set_port_vlan = ice_vsi_set_inner_port_vlan; vlan_ops->clear_port_vlan = ice_vsi_clear_inner_port_vlan; vlan_ops->clear_port_vlan = ice_vsi_clear_inner_port_vlan; } vlan_ops->ena_rx_filtering = ice_vsi_ena_rx_vlan_filtering; } static void ice_port_vlan_off(struct ice_vsi *vsi) { struct ice_vsi_vlan_ops *vlan_ops; struct ice_pf *pf = vsi->back; /* setup inner VLAN ops */ vlan_ops = &vsi->inner_vlan_ops; vlan_ops->ena_stripping = ice_vsi_ena_inner_stripping; vlan_ops->dis_stripping = ice_vsi_dis_inner_stripping; vlan_ops->ena_insertion = ice_vsi_ena_inner_insertion; vlan_ops->dis_insertion = ice_vsi_dis_inner_insertion; if (ice_is_dvm_ena(&pf->hw)) { vlan_ops = &vsi->outer_vlan_ops; vlan_ops->del_vlan = ice_vsi_del_vlan; vlan_ops->ena_stripping = ice_vsi_ena_outer_stripping; vlan_ops->dis_stripping = ice_vsi_dis_outer_stripping; vlan_ops->ena_insertion = ice_vsi_ena_outer_insertion; vlan_ops->dis_insertion = ice_vsi_dis_outer_insertion; } else { vlan_ops->del_vlan = ice_vsi_del_vlan; } if (!test_bit(ICE_FLAG_VF_VLAN_PRUNING, pf->flags)) vlan_ops->ena_rx_filtering = noop_vlan; else vlan_ops->ena_rx_filtering = ice_vsi_ena_rx_vlan_filtering; } /** * ice_vf_vsi_enable_port_vlan - Set VSI VLAN ops to support port VLAN * @vsi: VF's VSI being configured * * The function won't create port VLAN, it only allows to create port VLAN * using VLAN ops on the VF VSI. */ void ice_vf_vsi_enable_port_vlan(struct ice_vsi *vsi) { if (WARN_ON_ONCE(!vsi->vf)) return; ice_port_vlan_on(vsi); } /** * ice_vf_vsi_disable_port_vlan - Clear VSI support for creating port VLAN * @vsi: VF's VSI being configured * * The function should be called after removing port VLAN on VSI * (using VLAN ops) */ void ice_vf_vsi_disable_port_vlan(struct ice_vsi *vsi) { if (WARN_ON_ONCE(!vsi->vf)) return; ice_port_vlan_off(vsi); } /** * ice_vf_vsi_init_vlan_ops - Initialize default VSI VLAN ops for VF VSI * @vsi: VF's VSI being configured * * If Double VLAN Mode (DVM) is enabled, assume that the VF supports the new * VIRTCHNL_VF_VLAN_OFFLOAD_V2 capability and set up the VLAN ops accordingly. * If SVM is enabled maintain the same level of VLAN support previous to * VIRTCHNL_VF_VLAN_OFFLOAD_V2. */ void ice_vf_vsi_init_vlan_ops(struct ice_vsi *vsi) { struct ice_vsi_vlan_ops *vlan_ops; struct ice_pf *pf = vsi->back; struct ice_vf *vf = vsi->vf; if (WARN_ON(!vf)) return; if (ice_vf_is_port_vlan_ena(vf)) ice_port_vlan_on(vsi); else ice_port_vlan_off(vsi); vlan_ops = ice_is_dvm_ena(&pf->hw) ? &vsi->outer_vlan_ops : &vsi->inner_vlan_ops; vlan_ops->add_vlan = ice_vsi_add_vlan; vlan_ops->dis_rx_filtering = ice_vsi_dis_rx_vlan_filtering; vlan_ops->ena_tx_filtering = ice_vsi_ena_tx_vlan_filtering; vlan_ops->dis_tx_filtering = ice_vsi_dis_tx_vlan_filtering; } /** * ice_vf_vsi_cfg_dvm_legacy_vlan_mode - Config VLAN mode for old VFs in DVM * @vsi: VF's VSI being configured * * This should only be called when Double VLAN Mode (DVM) is enabled, there * is not a port VLAN enabled on this VF, and the VF negotiates * VIRTCHNL_VF_OFFLOAD_VLAN. * * This function sets up the VF VSI's inner and outer ice_vsi_vlan_ops and also * initializes software only VLAN mode (i.e. allow all VLANs). Also, use no-op * implementations for any functions that may be called during the lifetime of * the VF so these methods do nothing and succeed. */ void ice_vf_vsi_cfg_dvm_legacy_vlan_mode(struct ice_vsi *vsi) { struct ice_vsi_vlan_ops *vlan_ops; struct ice_vf *vf = vsi->vf; struct device *dev; if (WARN_ON(!vf)) return; dev = ice_pf_to_dev(vf->pf); if (!ice_is_dvm_ena(&vsi->back->hw) || ice_vf_is_port_vlan_ena(vf)) return; vlan_ops = &vsi->outer_vlan_ops; /* Rx VLAN filtering always disabled to allow software offloaded VLANs * for VFs that only support VIRTCHNL_VF_OFFLOAD_VLAN and don't have a * port VLAN configured */ vlan_ops->dis_rx_filtering = ice_vsi_dis_rx_vlan_filtering; /* Don't fail when attempting to enable Rx VLAN filtering */ vlan_ops->ena_rx_filtering = noop_vlan; /* Tx VLAN filtering always disabled to allow software offloaded VLANs * for VFs that only support VIRTCHNL_VF_OFFLOAD_VLAN and don't have a * port VLAN configured */ vlan_ops->dis_tx_filtering = ice_vsi_dis_tx_vlan_filtering; /* Don't fail when attempting to enable Tx VLAN filtering */ vlan_ops->ena_tx_filtering = noop_vlan; if (vlan_ops->dis_rx_filtering(vsi)) dev_dbg(dev, "Failed to disable Rx VLAN filtering for old VF without VIRTCHNL_VF_OFFLOAD_VLAN_V2 support\n"); if (vlan_ops->dis_tx_filtering(vsi)) dev_dbg(dev, "Failed to disable Tx VLAN filtering for old VF without VIRTHCNL_VF_OFFLOAD_VLAN_V2 support\n"); /* All outer VLAN offloads must be disabled */ vlan_ops->dis_stripping = ice_vsi_dis_outer_stripping; vlan_ops->dis_insertion = ice_vsi_dis_outer_insertion; if (vlan_ops->dis_stripping(vsi)) dev_dbg(dev, "Failed to disable outer VLAN stripping for old VF without VIRTCHNL_VF_OFFLOAD_VLAN_V2 support\n"); if (vlan_ops->dis_insertion(vsi)) dev_dbg(dev, "Failed to disable outer VLAN insertion for old VF without VIRTCHNL_VF_OFFLOAD_VLAN_V2 support\n"); /* All inner VLAN offloads must be disabled */ vlan_ops = &vsi->inner_vlan_ops; vlan_ops->dis_stripping = ice_vsi_dis_outer_stripping; vlan_ops->dis_insertion = ice_vsi_dis_outer_insertion; if (vlan_ops->dis_stripping(vsi)) dev_dbg(dev, "Failed to disable inner VLAN stripping for old VF without VIRTCHNL_VF_OFFLOAD_VLAN_V2 support\n"); if (vlan_ops->dis_insertion(vsi)) dev_dbg(dev, "Failed to disable inner VLAN insertion for old VF without VIRTCHNL_VF_OFFLOAD_VLAN_V2 support\n"); } /** * ice_vf_vsi_cfg_svm_legacy_vlan_mode - Config VLAN mode for old VFs in SVM * @vsi: VF's VSI being configured * * This should only be called when Single VLAN Mode (SVM) is enabled, there is * not a port VLAN enabled on this VF, and the VF negotiates * VIRTCHNL_VF_OFFLOAD_VLAN. * * All of the normal SVM VLAN ops are identical for this case. However, by * default Rx VLAN filtering should be turned off by default in this case. */ void ice_vf_vsi_cfg_svm_legacy_vlan_mode(struct ice_vsi *vsi) { struct ice_vf *vf = vsi->vf; if (WARN_ON(!vf)) return; if (ice_is_dvm_ena(&vsi->back->hw) || ice_vf_is_port_vlan_ena(vf)) return; if (vsi->inner_vlan_ops.dis_rx_filtering(vsi)) dev_dbg(ice_pf_to_dev(vf->pf), "Failed to disable Rx VLAN filtering for old VF with VIRTCHNL_VF_OFFLOAD_VLAN support\n"); }
linux-master
drivers/net/ethernet/intel/ice/ice_vf_vsi_vlan_ops.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2019, Intel Corporation. */ #include <linux/filter.h> #include "ice_txrx_lib.h" #include "ice_eswitch.h" #include "ice_lib.h" /** * ice_release_rx_desc - Store the new tail and head values * @rx_ring: ring to bump * @val: new head index */ void ice_release_rx_desc(struct ice_rx_ring *rx_ring, u16 val) { u16 prev_ntu = rx_ring->next_to_use & ~0x7; rx_ring->next_to_use = val; /* update next to alloc since we have filled the ring */ rx_ring->next_to_alloc = val; /* QRX_TAIL will be updated with any tail value, but hardware ignores * the lower 3 bits. This makes it so we only bump tail on meaningful * boundaries. Also, this allows us to bump tail on intervals of 8 up to * the budget depending on the current traffic load. */ val &= ~0x7; if (prev_ntu != val) { /* Force memory writes to complete before letting h/w * know there are new descriptors to fetch. (Only * applicable for weak-ordered memory model archs, * such as IA-64). */ wmb(); writel(val, rx_ring->tail); } } /** * ice_ptype_to_htype - get a hash type * @ptype: the ptype value from the descriptor * * Returns appropriate hash type (such as PKT_HASH_TYPE_L2/L3/L4) to be used by * skb_set_hash based on PTYPE as parsed by HW Rx pipeline and is part of * Rx desc. */ static enum pkt_hash_types ice_ptype_to_htype(u16 ptype) { struct ice_rx_ptype_decoded decoded = ice_decode_rx_desc_ptype(ptype); if (!decoded.known) return PKT_HASH_TYPE_NONE; if (decoded.payload_layer == ICE_RX_PTYPE_PAYLOAD_LAYER_PAY4) return PKT_HASH_TYPE_L4; if (decoded.payload_layer == ICE_RX_PTYPE_PAYLOAD_LAYER_PAY3) return PKT_HASH_TYPE_L3; if (decoded.outer_ip == ICE_RX_PTYPE_OUTER_L2) return PKT_HASH_TYPE_L2; return PKT_HASH_TYPE_NONE; } /** * ice_rx_hash - set the hash value in the skb * @rx_ring: descriptor ring * @rx_desc: specific descriptor * @skb: pointer to current skb * @rx_ptype: the ptype value from the descriptor */ static void ice_rx_hash(struct ice_rx_ring *rx_ring, union ice_32b_rx_flex_desc *rx_desc, struct sk_buff *skb, u16 rx_ptype) { struct ice_32b_rx_flex_desc_nic *nic_mdid; u32 hash; if (!(rx_ring->netdev->features & NETIF_F_RXHASH)) return; if (rx_desc->wb.rxdid != ICE_RXDID_FLEX_NIC) return; nic_mdid = (struct ice_32b_rx_flex_desc_nic *)rx_desc; hash = le32_to_cpu(nic_mdid->rss_hash); skb_set_hash(skb, hash, ice_ptype_to_htype(rx_ptype)); } /** * ice_rx_csum - Indicate in skb if checksum is good * @ring: the ring we care about * @skb: skb currently being received and modified * @rx_desc: the receive descriptor * @ptype: the packet type decoded by hardware * * skb->protocol must be set before this function is called */ static void ice_rx_csum(struct ice_rx_ring *ring, struct sk_buff *skb, union ice_32b_rx_flex_desc *rx_desc, u16 ptype) { struct ice_rx_ptype_decoded decoded; u16 rx_status0, rx_status1; bool ipv4, ipv6; rx_status0 = le16_to_cpu(rx_desc->wb.status_error0); rx_status1 = le16_to_cpu(rx_desc->wb.status_error1); decoded = ice_decode_rx_desc_ptype(ptype); /* Start with CHECKSUM_NONE and by default csum_level = 0 */ skb->ip_summed = CHECKSUM_NONE; skb_checksum_none_assert(skb); /* check if Rx checksum is enabled */ if (!(ring->netdev->features & NETIF_F_RXCSUM)) return; /* check if HW has decoded the packet and checksum */ if (!(rx_status0 & BIT(ICE_RX_FLEX_DESC_STATUS0_L3L4P_S))) return; if (!(decoded.known && decoded.outer_ip)) return; ipv4 = (decoded.outer_ip == ICE_RX_PTYPE_OUTER_IP) && (decoded.outer_ip_ver == ICE_RX_PTYPE_OUTER_IPV4); ipv6 = (decoded.outer_ip == ICE_RX_PTYPE_OUTER_IP) && (decoded.outer_ip_ver == ICE_RX_PTYPE_OUTER_IPV6); if (ipv4 && (rx_status0 & (BIT(ICE_RX_FLEX_DESC_STATUS0_XSUM_IPE_S) | BIT(ICE_RX_FLEX_DESC_STATUS0_XSUM_EIPE_S)))) goto checksum_fail; if (ipv6 && (rx_status0 & (BIT(ICE_RX_FLEX_DESC_STATUS0_IPV6EXADD_S)))) goto checksum_fail; /* check for L4 errors and handle packets that were not able to be * checksummed due to arrival speed */ if (rx_status0 & BIT(ICE_RX_FLEX_DESC_STATUS0_XSUM_L4E_S)) goto checksum_fail; /* check for outer UDP checksum error in tunneled packets */ if ((rx_status1 & BIT(ICE_RX_FLEX_DESC_STATUS1_NAT_S)) && (rx_status0 & BIT(ICE_RX_FLEX_DESC_STATUS0_XSUM_EUDPE_S))) goto checksum_fail; /* If there is an outer header present that might contain a checksum * we need to bump the checksum level by 1 to reflect the fact that * we are indicating we validated the inner checksum. */ if (decoded.tunnel_type >= ICE_RX_PTYPE_TUNNEL_IP_GRENAT) skb->csum_level = 1; /* Only report checksum unnecessary for TCP, UDP, or SCTP */ switch (decoded.inner_prot) { case ICE_RX_PTYPE_INNER_PROT_TCP: case ICE_RX_PTYPE_INNER_PROT_UDP: case ICE_RX_PTYPE_INNER_PROT_SCTP: skb->ip_summed = CHECKSUM_UNNECESSARY; break; default: break; } return; checksum_fail: ring->vsi->back->hw_csum_rx_error++; } /** * ice_process_skb_fields - Populate skb header fields from Rx descriptor * @rx_ring: Rx descriptor ring packet is being transacted on * @rx_desc: pointer to the EOP Rx descriptor * @skb: pointer to current skb being populated * @ptype: the packet type decoded by hardware * * This function checks the ring, descriptor, and packet information in * order to populate the hash, checksum, VLAN, protocol, and * other fields within the skb. */ void ice_process_skb_fields(struct ice_rx_ring *rx_ring, union ice_32b_rx_flex_desc *rx_desc, struct sk_buff *skb, u16 ptype) { ice_rx_hash(rx_ring, rx_desc, skb, ptype); /* modifies the skb - consumes the enet header */ skb->protocol = eth_type_trans(skb, rx_ring->netdev); ice_rx_csum(rx_ring, skb, rx_desc, ptype); if (rx_ring->ptp_rx) ice_ptp_rx_hwtstamp(rx_ring, rx_desc, skb); } /** * ice_receive_skb - Send a completed packet up the stack * @rx_ring: Rx ring in play * @skb: packet to send up * @vlan_tag: VLAN tag for packet * * This function sends the completed packet (via. skb) up the stack using * gro receive functions (with/without VLAN tag) */ void ice_receive_skb(struct ice_rx_ring *rx_ring, struct sk_buff *skb, u16 vlan_tag) { netdev_features_t features = rx_ring->netdev->features; bool non_zero_vlan = !!(vlan_tag & VLAN_VID_MASK); if ((features & NETIF_F_HW_VLAN_CTAG_RX) && non_zero_vlan) __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vlan_tag); else if ((features & NETIF_F_HW_VLAN_STAG_RX) && non_zero_vlan) __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021AD), vlan_tag); napi_gro_receive(&rx_ring->q_vector->napi, skb); } /** * ice_clean_xdp_tx_buf - Free and unmap XDP Tx buffer * @dev: device for DMA mapping * @tx_buf: Tx buffer to clean * @bq: XDP bulk flush struct */ static void ice_clean_xdp_tx_buf(struct device *dev, struct ice_tx_buf *tx_buf, struct xdp_frame_bulk *bq) { dma_unmap_single(dev, dma_unmap_addr(tx_buf, dma), dma_unmap_len(tx_buf, len), DMA_TO_DEVICE); dma_unmap_len_set(tx_buf, len, 0); switch (tx_buf->type) { case ICE_TX_BUF_XDP_TX: page_frag_free(tx_buf->raw_buf); break; case ICE_TX_BUF_XDP_XMIT: xdp_return_frame_bulk(tx_buf->xdpf, bq); break; } tx_buf->type = ICE_TX_BUF_EMPTY; } /** * ice_clean_xdp_irq - Reclaim resources after transmit completes on XDP ring * @xdp_ring: XDP ring to clean */ static u32 ice_clean_xdp_irq(struct ice_tx_ring *xdp_ring) { int total_bytes = 0, total_pkts = 0; struct device *dev = xdp_ring->dev; u32 ntc = xdp_ring->next_to_clean; struct ice_tx_desc *tx_desc; u32 cnt = xdp_ring->count; struct xdp_frame_bulk bq; u32 frags, xdp_tx = 0; u32 ready_frames = 0; u32 idx; u32 ret; idx = xdp_ring->tx_buf[ntc].rs_idx; tx_desc = ICE_TX_DESC(xdp_ring, idx); if (tx_desc->cmd_type_offset_bsz & cpu_to_le64(ICE_TX_DESC_DTYPE_DESC_DONE)) { if (idx >= ntc) ready_frames = idx - ntc + 1; else ready_frames = idx + cnt - ntc + 1; } if (unlikely(!ready_frames)) return 0; ret = ready_frames; xdp_frame_bulk_init(&bq); rcu_read_lock(); /* xdp_return_frame_bulk() */ while (ready_frames) { struct ice_tx_buf *tx_buf = &xdp_ring->tx_buf[ntc]; struct ice_tx_buf *head = tx_buf; /* bytecount holds size of head + frags */ total_bytes += tx_buf->bytecount; frags = tx_buf->nr_frags; total_pkts++; /* count head + frags */ ready_frames -= frags + 1; xdp_tx++; ntc++; if (ntc == cnt) ntc = 0; for (int i = 0; i < frags; i++) { tx_buf = &xdp_ring->tx_buf[ntc]; ice_clean_xdp_tx_buf(dev, tx_buf, &bq); ntc++; if (ntc == cnt) ntc = 0; } ice_clean_xdp_tx_buf(dev, head, &bq); } xdp_flush_frame_bulk(&bq); rcu_read_unlock(); tx_desc->cmd_type_offset_bsz = 0; xdp_ring->next_to_clean = ntc; xdp_ring->xdp_tx_active -= xdp_tx; ice_update_tx_ring_stats(xdp_ring, total_pkts, total_bytes); return ret; } /** * __ice_xmit_xdp_ring - submit frame to XDP ring for transmission * @xdp: XDP buffer to be placed onto Tx descriptors * @xdp_ring: XDP ring for transmission * @frame: whether this comes from .ndo_xdp_xmit() */ int __ice_xmit_xdp_ring(struct xdp_buff *xdp, struct ice_tx_ring *xdp_ring, bool frame) { struct skb_shared_info *sinfo = NULL; u32 size = xdp->data_end - xdp->data; struct device *dev = xdp_ring->dev; u32 ntu = xdp_ring->next_to_use; struct ice_tx_desc *tx_desc; struct ice_tx_buf *tx_head; struct ice_tx_buf *tx_buf; u32 cnt = xdp_ring->count; void *data = xdp->data; u32 nr_frags = 0; u32 free_space; u32 frag = 0; free_space = ICE_DESC_UNUSED(xdp_ring); if (free_space < ICE_RING_QUARTER(xdp_ring)) free_space += ice_clean_xdp_irq(xdp_ring); if (unlikely(!free_space)) goto busy; if (unlikely(xdp_buff_has_frags(xdp))) { sinfo = xdp_get_shared_info_from_buff(xdp); nr_frags = sinfo->nr_frags; if (free_space < nr_frags + 1) goto busy; } tx_desc = ICE_TX_DESC(xdp_ring, ntu); tx_head = &xdp_ring->tx_buf[ntu]; tx_buf = tx_head; for (;;) { dma_addr_t dma; dma = dma_map_single(dev, data, size, DMA_TO_DEVICE); if (dma_mapping_error(dev, dma)) goto dma_unmap; /* record length, and DMA address */ dma_unmap_len_set(tx_buf, len, size); dma_unmap_addr_set(tx_buf, dma, dma); if (frame) { tx_buf->type = ICE_TX_BUF_FRAG; } else { tx_buf->type = ICE_TX_BUF_XDP_TX; tx_buf->raw_buf = data; } tx_desc->buf_addr = cpu_to_le64(dma); tx_desc->cmd_type_offset_bsz = ice_build_ctob(0, 0, size, 0); ntu++; if (ntu == cnt) ntu = 0; if (frag == nr_frags) break; tx_desc = ICE_TX_DESC(xdp_ring, ntu); tx_buf = &xdp_ring->tx_buf[ntu]; data = skb_frag_address(&sinfo->frags[frag]); size = skb_frag_size(&sinfo->frags[frag]); frag++; } /* store info about bytecount and frag count in first desc */ tx_head->bytecount = xdp_get_buff_len(xdp); tx_head->nr_frags = nr_frags; if (frame) { tx_head->type = ICE_TX_BUF_XDP_XMIT; tx_head->xdpf = xdp->data_hard_start; } /* update last descriptor from a frame with EOP */ tx_desc->cmd_type_offset_bsz |= cpu_to_le64(ICE_TX_DESC_CMD_EOP << ICE_TXD_QW1_CMD_S); xdp_ring->xdp_tx_active++; xdp_ring->next_to_use = ntu; return ICE_XDP_TX; dma_unmap: for (;;) { tx_buf = &xdp_ring->tx_buf[ntu]; dma_unmap_page(dev, dma_unmap_addr(tx_buf, dma), dma_unmap_len(tx_buf, len), DMA_TO_DEVICE); dma_unmap_len_set(tx_buf, len, 0); if (tx_buf == tx_head) break; if (!ntu) ntu += cnt; ntu--; } return ICE_XDP_CONSUMED; busy: xdp_ring->ring_stats->tx_stats.tx_busy++; return ICE_XDP_CONSUMED; } /** * ice_finalize_xdp_rx - Bump XDP Tx tail and/or flush redirect map * @xdp_ring: XDP ring * @xdp_res: Result of the receive batch * @first_idx: index to write from caller * * This function bumps XDP Tx tail and/or flush redirect map, and * should be called when a batch of packets has been processed in the * napi loop. */ void ice_finalize_xdp_rx(struct ice_tx_ring *xdp_ring, unsigned int xdp_res, u32 first_idx) { struct ice_tx_buf *tx_buf = &xdp_ring->tx_buf[first_idx]; if (xdp_res & ICE_XDP_REDIR) xdp_do_flush_map(); if (xdp_res & ICE_XDP_TX) { if (static_branch_unlikely(&ice_xdp_locking_key)) spin_lock(&xdp_ring->tx_lock); /* store index of descriptor with RS bit set in the first * ice_tx_buf of given NAPI batch */ tx_buf->rs_idx = ice_set_rs_bit(xdp_ring); ice_xdp_ring_update_tail(xdp_ring); if (static_branch_unlikely(&ice_xdp_locking_key)) spin_unlock(&xdp_ring->tx_lock); } }
linux-master
drivers/net/ethernet/intel/ice/ice_txrx_lib.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2022, Intel Corporation. */ #include "ice_virtchnl.h" #include "ice_vf_lib_private.h" #include "ice.h" #include "ice_base.h" #include "ice_lib.h" #include "ice_fltr.h" #include "ice_virtchnl_allowlist.h" #include "ice_vf_vsi_vlan_ops.h" #include "ice_vlan.h" #include "ice_flex_pipe.h" #include "ice_dcb_lib.h" #define FIELD_SELECTOR(proto_hdr_field) \ BIT((proto_hdr_field) & PROTO_HDR_FIELD_MASK) struct ice_vc_hdr_match_type { u32 vc_hdr; /* virtchnl headers (VIRTCHNL_PROTO_HDR_XXX) */ u32 ice_hdr; /* ice headers (ICE_FLOW_SEG_HDR_XXX) */ }; static const struct ice_vc_hdr_match_type ice_vc_hdr_list[] = { {VIRTCHNL_PROTO_HDR_NONE, ICE_FLOW_SEG_HDR_NONE}, {VIRTCHNL_PROTO_HDR_ETH, ICE_FLOW_SEG_HDR_ETH}, {VIRTCHNL_PROTO_HDR_S_VLAN, ICE_FLOW_SEG_HDR_VLAN}, {VIRTCHNL_PROTO_HDR_C_VLAN, ICE_FLOW_SEG_HDR_VLAN}, {VIRTCHNL_PROTO_HDR_IPV4, ICE_FLOW_SEG_HDR_IPV4 | ICE_FLOW_SEG_HDR_IPV_OTHER}, {VIRTCHNL_PROTO_HDR_IPV6, ICE_FLOW_SEG_HDR_IPV6 | ICE_FLOW_SEG_HDR_IPV_OTHER}, {VIRTCHNL_PROTO_HDR_TCP, ICE_FLOW_SEG_HDR_TCP}, {VIRTCHNL_PROTO_HDR_UDP, ICE_FLOW_SEG_HDR_UDP}, {VIRTCHNL_PROTO_HDR_SCTP, ICE_FLOW_SEG_HDR_SCTP}, {VIRTCHNL_PROTO_HDR_PPPOE, ICE_FLOW_SEG_HDR_PPPOE}, {VIRTCHNL_PROTO_HDR_GTPU_IP, ICE_FLOW_SEG_HDR_GTPU_IP}, {VIRTCHNL_PROTO_HDR_GTPU_EH, ICE_FLOW_SEG_HDR_GTPU_EH}, {VIRTCHNL_PROTO_HDR_GTPU_EH_PDU_DWN, ICE_FLOW_SEG_HDR_GTPU_DWN}, {VIRTCHNL_PROTO_HDR_GTPU_EH_PDU_UP, ICE_FLOW_SEG_HDR_GTPU_UP}, {VIRTCHNL_PROTO_HDR_L2TPV3, ICE_FLOW_SEG_HDR_L2TPV3}, {VIRTCHNL_PROTO_HDR_ESP, ICE_FLOW_SEG_HDR_ESP}, {VIRTCHNL_PROTO_HDR_AH, ICE_FLOW_SEG_HDR_AH}, {VIRTCHNL_PROTO_HDR_PFCP, ICE_FLOW_SEG_HDR_PFCP_SESSION}, }; struct ice_vc_hash_field_match_type { u32 vc_hdr; /* virtchnl headers * (VIRTCHNL_PROTO_HDR_XXX) */ u32 vc_hash_field; /* virtchnl hash fields selector * FIELD_SELECTOR((VIRTCHNL_PROTO_HDR_ETH_XXX)) */ u64 ice_hash_field; /* ice hash fields * (BIT_ULL(ICE_FLOW_FIELD_IDX_XXX)) */ }; static const struct ice_vc_hash_field_match_type ice_vc_hash_field_list[] = { {VIRTCHNL_PROTO_HDR_ETH, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_ETH_SRC), BIT_ULL(ICE_FLOW_FIELD_IDX_ETH_SA)}, {VIRTCHNL_PROTO_HDR_ETH, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_ETH_DST), BIT_ULL(ICE_FLOW_FIELD_IDX_ETH_DA)}, {VIRTCHNL_PROTO_HDR_ETH, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_ETH_SRC) | FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_ETH_DST), ICE_FLOW_HASH_ETH}, {VIRTCHNL_PROTO_HDR_ETH, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_ETH_ETHERTYPE), BIT_ULL(ICE_FLOW_FIELD_IDX_ETH_TYPE)}, {VIRTCHNL_PROTO_HDR_S_VLAN, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_S_VLAN_ID), BIT_ULL(ICE_FLOW_FIELD_IDX_S_VLAN)}, {VIRTCHNL_PROTO_HDR_C_VLAN, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_C_VLAN_ID), BIT_ULL(ICE_FLOW_FIELD_IDX_C_VLAN)}, {VIRTCHNL_PROTO_HDR_IPV4, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV4_SRC), BIT_ULL(ICE_FLOW_FIELD_IDX_IPV4_SA)}, {VIRTCHNL_PROTO_HDR_IPV4, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV4_DST), BIT_ULL(ICE_FLOW_FIELD_IDX_IPV4_DA)}, {VIRTCHNL_PROTO_HDR_IPV4, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV4_SRC) | FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV4_DST), ICE_FLOW_HASH_IPV4}, {VIRTCHNL_PROTO_HDR_IPV4, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV4_SRC) | FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV4_PROT), BIT_ULL(ICE_FLOW_FIELD_IDX_IPV4_SA) | BIT_ULL(ICE_FLOW_FIELD_IDX_IPV4_PROT)}, {VIRTCHNL_PROTO_HDR_IPV4, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV4_DST) | FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV4_PROT), BIT_ULL(ICE_FLOW_FIELD_IDX_IPV4_DA) | BIT_ULL(ICE_FLOW_FIELD_IDX_IPV4_PROT)}, {VIRTCHNL_PROTO_HDR_IPV4, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV4_SRC) | FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV4_DST) | FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV4_PROT), ICE_FLOW_HASH_IPV4 | BIT_ULL(ICE_FLOW_FIELD_IDX_IPV4_PROT)}, {VIRTCHNL_PROTO_HDR_IPV4, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV4_PROT), BIT_ULL(ICE_FLOW_FIELD_IDX_IPV4_PROT)}, {VIRTCHNL_PROTO_HDR_IPV6, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV6_SRC), BIT_ULL(ICE_FLOW_FIELD_IDX_IPV6_SA)}, {VIRTCHNL_PROTO_HDR_IPV6, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV6_DST), BIT_ULL(ICE_FLOW_FIELD_IDX_IPV6_DA)}, {VIRTCHNL_PROTO_HDR_IPV6, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV6_SRC) | FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV6_DST), ICE_FLOW_HASH_IPV6}, {VIRTCHNL_PROTO_HDR_IPV6, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV6_SRC) | FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV6_PROT), BIT_ULL(ICE_FLOW_FIELD_IDX_IPV6_SA) | BIT_ULL(ICE_FLOW_FIELD_IDX_IPV6_PROT)}, {VIRTCHNL_PROTO_HDR_IPV6, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV6_DST) | FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV6_PROT), BIT_ULL(ICE_FLOW_FIELD_IDX_IPV6_DA) | BIT_ULL(ICE_FLOW_FIELD_IDX_IPV6_PROT)}, {VIRTCHNL_PROTO_HDR_IPV6, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV6_SRC) | FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV6_DST) | FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV6_PROT), ICE_FLOW_HASH_IPV6 | BIT_ULL(ICE_FLOW_FIELD_IDX_IPV6_PROT)}, {VIRTCHNL_PROTO_HDR_IPV6, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_IPV6_PROT), BIT_ULL(ICE_FLOW_FIELD_IDX_IPV6_PROT)}, {VIRTCHNL_PROTO_HDR_TCP, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_TCP_SRC_PORT), BIT_ULL(ICE_FLOW_FIELD_IDX_TCP_SRC_PORT)}, {VIRTCHNL_PROTO_HDR_TCP, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_TCP_DST_PORT), BIT_ULL(ICE_FLOW_FIELD_IDX_TCP_DST_PORT)}, {VIRTCHNL_PROTO_HDR_TCP, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_TCP_SRC_PORT) | FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_TCP_DST_PORT), ICE_FLOW_HASH_TCP_PORT}, {VIRTCHNL_PROTO_HDR_UDP, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_UDP_SRC_PORT), BIT_ULL(ICE_FLOW_FIELD_IDX_UDP_SRC_PORT)}, {VIRTCHNL_PROTO_HDR_UDP, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_UDP_DST_PORT), BIT_ULL(ICE_FLOW_FIELD_IDX_UDP_DST_PORT)}, {VIRTCHNL_PROTO_HDR_UDP, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_UDP_SRC_PORT) | FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_UDP_DST_PORT), ICE_FLOW_HASH_UDP_PORT}, {VIRTCHNL_PROTO_HDR_SCTP, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_SCTP_SRC_PORT), BIT_ULL(ICE_FLOW_FIELD_IDX_SCTP_SRC_PORT)}, {VIRTCHNL_PROTO_HDR_SCTP, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_SCTP_DST_PORT), BIT_ULL(ICE_FLOW_FIELD_IDX_SCTP_DST_PORT)}, {VIRTCHNL_PROTO_HDR_SCTP, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_SCTP_SRC_PORT) | FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_SCTP_DST_PORT), ICE_FLOW_HASH_SCTP_PORT}, {VIRTCHNL_PROTO_HDR_PPPOE, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_PPPOE_SESS_ID), BIT_ULL(ICE_FLOW_FIELD_IDX_PPPOE_SESS_ID)}, {VIRTCHNL_PROTO_HDR_GTPU_IP, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_GTPU_IP_TEID), BIT_ULL(ICE_FLOW_FIELD_IDX_GTPU_IP_TEID)}, {VIRTCHNL_PROTO_HDR_L2TPV3, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_L2TPV3_SESS_ID), BIT_ULL(ICE_FLOW_FIELD_IDX_L2TPV3_SESS_ID)}, {VIRTCHNL_PROTO_HDR_ESP, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_ESP_SPI), BIT_ULL(ICE_FLOW_FIELD_IDX_ESP_SPI)}, {VIRTCHNL_PROTO_HDR_AH, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_AH_SPI), BIT_ULL(ICE_FLOW_FIELD_IDX_AH_SPI)}, {VIRTCHNL_PROTO_HDR_PFCP, FIELD_SELECTOR(VIRTCHNL_PROTO_HDR_PFCP_SEID), BIT_ULL(ICE_FLOW_FIELD_IDX_PFCP_SEID)}, }; /** * ice_vc_vf_broadcast - Broadcast a message to all VFs on PF * @pf: pointer to the PF structure * @v_opcode: operation code * @v_retval: return value * @msg: pointer to the msg buffer * @msglen: msg length */ static void ice_vc_vf_broadcast(struct ice_pf *pf, enum virtchnl_ops v_opcode, enum virtchnl_status_code v_retval, u8 *msg, u16 msglen) { struct ice_hw *hw = &pf->hw; struct ice_vf *vf; unsigned int bkt; mutex_lock(&pf->vfs.table_lock); ice_for_each_vf(pf, bkt, vf) { /* Not all vfs are enabled so skip the ones that are not */ if (!test_bit(ICE_VF_STATE_INIT, vf->vf_states) && !test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) continue; /* Ignore return value on purpose - a given VF may fail, but * we need to keep going and send to all of them */ ice_aq_send_msg_to_vf(hw, vf->vf_id, v_opcode, v_retval, msg, msglen, NULL); } mutex_unlock(&pf->vfs.table_lock); } /** * ice_set_pfe_link - Set the link speed/status of the virtchnl_pf_event * @vf: pointer to the VF structure * @pfe: pointer to the virtchnl_pf_event to set link speed/status for * @ice_link_speed: link speed specified by ICE_AQ_LINK_SPEED_* * @link_up: whether or not to set the link up/down */ static void ice_set_pfe_link(struct ice_vf *vf, struct virtchnl_pf_event *pfe, int ice_link_speed, bool link_up) { if (vf->driver_caps & VIRTCHNL_VF_CAP_ADV_LINK_SPEED) { pfe->event_data.link_event_adv.link_status = link_up; /* Speed in Mbps */ pfe->event_data.link_event_adv.link_speed = ice_conv_link_speed_to_virtchnl(true, ice_link_speed); } else { pfe->event_data.link_event.link_status = link_up; /* Legacy method for virtchnl link speeds */ pfe->event_data.link_event.link_speed = (enum virtchnl_link_speed) ice_conv_link_speed_to_virtchnl(false, ice_link_speed); } } /** * ice_vc_notify_vf_link_state - Inform a VF of link status * @vf: pointer to the VF structure * * send a link status message to a single VF */ void ice_vc_notify_vf_link_state(struct ice_vf *vf) { struct virtchnl_pf_event pfe = { 0 }; struct ice_hw *hw = &vf->pf->hw; pfe.event = VIRTCHNL_EVENT_LINK_CHANGE; pfe.severity = PF_EVENT_SEVERITY_INFO; if (ice_is_vf_link_up(vf)) ice_set_pfe_link(vf, &pfe, hw->port_info->phy.link_info.link_speed, true); else ice_set_pfe_link(vf, &pfe, ICE_AQ_LINK_SPEED_UNKNOWN, false); ice_aq_send_msg_to_vf(hw, vf->vf_id, VIRTCHNL_OP_EVENT, VIRTCHNL_STATUS_SUCCESS, (u8 *)&pfe, sizeof(pfe), NULL); } /** * ice_vc_notify_link_state - Inform all VFs on a PF of link status * @pf: pointer to the PF structure */ void ice_vc_notify_link_state(struct ice_pf *pf) { struct ice_vf *vf; unsigned int bkt; mutex_lock(&pf->vfs.table_lock); ice_for_each_vf(pf, bkt, vf) ice_vc_notify_vf_link_state(vf); mutex_unlock(&pf->vfs.table_lock); } /** * ice_vc_notify_reset - Send pending reset message to all VFs * @pf: pointer to the PF structure * * indicate a pending reset to all VFs on a given PF */ void ice_vc_notify_reset(struct ice_pf *pf) { struct virtchnl_pf_event pfe; if (!ice_has_vfs(pf)) return; pfe.event = VIRTCHNL_EVENT_RESET_IMPENDING; pfe.severity = PF_EVENT_SEVERITY_CERTAIN_DOOM; ice_vc_vf_broadcast(pf, VIRTCHNL_OP_EVENT, VIRTCHNL_STATUS_SUCCESS, (u8 *)&pfe, sizeof(struct virtchnl_pf_event)); } /** * ice_vc_send_msg_to_vf - Send message to VF * @vf: pointer to the VF info * @v_opcode: virtual channel opcode * @v_retval: virtual channel return value * @msg: pointer to the msg buffer * @msglen: msg length * * send msg to VF */ int ice_vc_send_msg_to_vf(struct ice_vf *vf, u32 v_opcode, enum virtchnl_status_code v_retval, u8 *msg, u16 msglen) { struct device *dev; struct ice_pf *pf; int aq_ret; pf = vf->pf; dev = ice_pf_to_dev(pf); aq_ret = ice_aq_send_msg_to_vf(&pf->hw, vf->vf_id, v_opcode, v_retval, msg, msglen, NULL); if (aq_ret && pf->hw.mailboxq.sq_last_status != ICE_AQ_RC_ENOSYS) { dev_info(dev, "Unable to send the message to VF %d ret %d aq_err %s\n", vf->vf_id, aq_ret, ice_aq_str(pf->hw.mailboxq.sq_last_status)); return -EIO; } return 0; } /** * ice_vc_get_ver_msg * @vf: pointer to the VF info * @msg: pointer to the msg buffer * * called from the VF to request the API version used by the PF */ static int ice_vc_get_ver_msg(struct ice_vf *vf, u8 *msg) { struct virtchnl_version_info info = { VIRTCHNL_VERSION_MAJOR, VIRTCHNL_VERSION_MINOR }; vf->vf_ver = *(struct virtchnl_version_info *)msg; /* VFs running the 1.0 API expect to get 1.0 back or they will cry. */ if (VF_IS_V10(&vf->vf_ver)) info.minor = VIRTCHNL_VERSION_MINOR_NO_VF_CAPS; return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_VERSION, VIRTCHNL_STATUS_SUCCESS, (u8 *)&info, sizeof(struct virtchnl_version_info)); } /** * ice_vc_get_max_frame_size - get max frame size allowed for VF * @vf: VF used to determine max frame size * * Max frame size is determined based on the current port's max frame size and * whether a port VLAN is configured on this VF. The VF is not aware whether * it's in a port VLAN so the PF needs to account for this in max frame size * checks and sending the max frame size to the VF. */ static u16 ice_vc_get_max_frame_size(struct ice_vf *vf) { struct ice_port_info *pi = ice_vf_get_port_info(vf); u16 max_frame_size; max_frame_size = pi->phy.link_info.max_frame_size; if (ice_vf_is_port_vlan_ena(vf)) max_frame_size -= VLAN_HLEN; return max_frame_size; } /** * ice_vc_get_vlan_caps * @hw: pointer to the hw * @vf: pointer to the VF info * @vsi: pointer to the VSI * @driver_caps: current driver caps * * Return 0 if there is no VLAN caps supported, or VLAN caps value */ static u32 ice_vc_get_vlan_caps(struct ice_hw *hw, struct ice_vf *vf, struct ice_vsi *vsi, u32 driver_caps) { if (ice_is_eswitch_mode_switchdev(vf->pf)) /* In switchdev setting VLAN from VF isn't supported */ return 0; if (driver_caps & VIRTCHNL_VF_OFFLOAD_VLAN_V2) { /* VLAN offloads based on current device configuration */ return VIRTCHNL_VF_OFFLOAD_VLAN_V2; } else if (driver_caps & VIRTCHNL_VF_OFFLOAD_VLAN) { /* allow VF to negotiate VIRTCHNL_VF_OFFLOAD explicitly for * these two conditions, which amounts to guest VLAN filtering * and offloads being based on the inner VLAN or the * inner/single VLAN respectively and don't allow VF to * negotiate VIRTCHNL_VF_OFFLOAD in any other cases */ if (ice_is_dvm_ena(hw) && ice_vf_is_port_vlan_ena(vf)) { return VIRTCHNL_VF_OFFLOAD_VLAN; } else if (!ice_is_dvm_ena(hw) && !ice_vf_is_port_vlan_ena(vf)) { /* configure backward compatible support for VFs that * only support VIRTCHNL_VF_OFFLOAD_VLAN, the PF is * configured in SVM, and no port VLAN is configured */ ice_vf_vsi_cfg_svm_legacy_vlan_mode(vsi); return VIRTCHNL_VF_OFFLOAD_VLAN; } else if (ice_is_dvm_ena(hw)) { /* configure software offloaded VLAN support when DVM * is enabled, but no port VLAN is enabled */ ice_vf_vsi_cfg_dvm_legacy_vlan_mode(vsi); } } return 0; } /** * ice_vc_get_vf_res_msg * @vf: pointer to the VF info * @msg: pointer to the msg buffer * * called from the VF to request its resources */ static int ice_vc_get_vf_res_msg(struct ice_vf *vf, u8 *msg) { enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct virtchnl_vf_resource *vfres = NULL; struct ice_hw *hw = &vf->pf->hw; struct ice_vsi *vsi; int len = 0; int ret; if (ice_check_vf_init(vf)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto err; } len = virtchnl_struct_size(vfres, vsi_res, 0); vfres = kzalloc(len, GFP_KERNEL); if (!vfres) { v_ret = VIRTCHNL_STATUS_ERR_NO_MEMORY; len = 0; goto err; } if (VF_IS_V11(&vf->vf_ver)) vf->driver_caps = *(u32 *)msg; else vf->driver_caps = VIRTCHNL_VF_OFFLOAD_L2 | VIRTCHNL_VF_OFFLOAD_RSS_REG | VIRTCHNL_VF_OFFLOAD_VLAN; vfres->vf_cap_flags = VIRTCHNL_VF_OFFLOAD_L2; vsi = ice_get_vf_vsi(vf); if (!vsi) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto err; } vfres->vf_cap_flags |= ice_vc_get_vlan_caps(hw, vf, vsi, vf->driver_caps); if (vf->driver_caps & VIRTCHNL_VF_OFFLOAD_RSS_PF) { vfres->vf_cap_flags |= VIRTCHNL_VF_OFFLOAD_RSS_PF; } else { if (vf->driver_caps & VIRTCHNL_VF_OFFLOAD_RSS_AQ) vfres->vf_cap_flags |= VIRTCHNL_VF_OFFLOAD_RSS_AQ; else vfres->vf_cap_flags |= VIRTCHNL_VF_OFFLOAD_RSS_REG; } if (vf->driver_caps & VIRTCHNL_VF_OFFLOAD_RX_FLEX_DESC) vfres->vf_cap_flags |= VIRTCHNL_VF_OFFLOAD_RX_FLEX_DESC; if (vf->driver_caps & VIRTCHNL_VF_OFFLOAD_FDIR_PF) vfres->vf_cap_flags |= VIRTCHNL_VF_OFFLOAD_FDIR_PF; if (vf->driver_caps & VIRTCHNL_VF_OFFLOAD_RSS_PCTYPE_V2) vfres->vf_cap_flags |= VIRTCHNL_VF_OFFLOAD_RSS_PCTYPE_V2; if (vf->driver_caps & VIRTCHNL_VF_OFFLOAD_ENCAP) vfres->vf_cap_flags |= VIRTCHNL_VF_OFFLOAD_ENCAP; if (vf->driver_caps & VIRTCHNL_VF_OFFLOAD_ENCAP_CSUM) vfres->vf_cap_flags |= VIRTCHNL_VF_OFFLOAD_ENCAP_CSUM; if (vf->driver_caps & VIRTCHNL_VF_OFFLOAD_RX_POLLING) vfres->vf_cap_flags |= VIRTCHNL_VF_OFFLOAD_RX_POLLING; if (vf->driver_caps & VIRTCHNL_VF_OFFLOAD_WB_ON_ITR) vfres->vf_cap_flags |= VIRTCHNL_VF_OFFLOAD_WB_ON_ITR; if (vf->driver_caps & VIRTCHNL_VF_OFFLOAD_REQ_QUEUES) vfres->vf_cap_flags |= VIRTCHNL_VF_OFFLOAD_REQ_QUEUES; if (vf->driver_caps & VIRTCHNL_VF_CAP_ADV_LINK_SPEED) vfres->vf_cap_flags |= VIRTCHNL_VF_CAP_ADV_LINK_SPEED; if (vf->driver_caps & VIRTCHNL_VF_OFFLOAD_ADV_RSS_PF) vfres->vf_cap_flags |= VIRTCHNL_VF_OFFLOAD_ADV_RSS_PF; if (vf->driver_caps & VIRTCHNL_VF_OFFLOAD_USO) vfres->vf_cap_flags |= VIRTCHNL_VF_OFFLOAD_USO; vfres->num_vsis = 1; /* Tx and Rx queue are equal for VF */ vfres->num_queue_pairs = vsi->num_txq; vfres->max_vectors = vf->pf->vfs.num_msix_per; vfres->rss_key_size = ICE_VSIQF_HKEY_ARRAY_SIZE; vfres->rss_lut_size = ICE_LUT_VSI_SIZE; vfres->max_mtu = ice_vc_get_max_frame_size(vf); vfres->vsi_res[0].vsi_id = vf->lan_vsi_num; vfres->vsi_res[0].vsi_type = VIRTCHNL_VSI_SRIOV; vfres->vsi_res[0].num_queue_pairs = vsi->num_txq; ether_addr_copy(vfres->vsi_res[0].default_mac_addr, vf->hw_lan_addr); /* match guest capabilities */ vf->driver_caps = vfres->vf_cap_flags; ice_vc_set_caps_allowlist(vf); ice_vc_set_working_allowlist(vf); set_bit(ICE_VF_STATE_ACTIVE, vf->vf_states); err: /* send the response back to the VF */ ret = ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_GET_VF_RESOURCES, v_ret, (u8 *)vfres, len); kfree(vfres); return ret; } /** * ice_vc_reset_vf_msg * @vf: pointer to the VF info * * called from the VF to reset itself, * unlike other virtchnl messages, PF driver * doesn't send the response back to the VF */ static void ice_vc_reset_vf_msg(struct ice_vf *vf) { if (test_bit(ICE_VF_STATE_INIT, vf->vf_states)) ice_reset_vf(vf, 0); } /** * ice_vc_isvalid_vsi_id * @vf: pointer to the VF info * @vsi_id: VF relative VSI ID * * check for the valid VSI ID */ bool ice_vc_isvalid_vsi_id(struct ice_vf *vf, u16 vsi_id) { struct ice_pf *pf = vf->pf; struct ice_vsi *vsi; vsi = ice_find_vsi(pf, vsi_id); return (vsi && (vsi->vf == vf)); } /** * ice_vc_isvalid_q_id * @vf: pointer to the VF info * @vsi_id: VSI ID * @qid: VSI relative queue ID * * check for the valid queue ID */ static bool ice_vc_isvalid_q_id(struct ice_vf *vf, u16 vsi_id, u8 qid) { struct ice_vsi *vsi = ice_find_vsi(vf->pf, vsi_id); /* allocated Tx and Rx queues should be always equal for VF VSI */ return (vsi && (qid < vsi->alloc_txq)); } /** * ice_vc_isvalid_ring_len * @ring_len: length of ring * * check for the valid ring count, should be multiple of ICE_REQ_DESC_MULTIPLE * or zero */ static bool ice_vc_isvalid_ring_len(u16 ring_len) { return ring_len == 0 || (ring_len >= ICE_MIN_NUM_DESC && ring_len <= ICE_MAX_NUM_DESC && !(ring_len % ICE_REQ_DESC_MULTIPLE)); } /** * ice_vc_validate_pattern * @vf: pointer to the VF info * @proto: virtchnl protocol headers * * validate the pattern is supported or not. * * Return: true on success, false on error. */ bool ice_vc_validate_pattern(struct ice_vf *vf, struct virtchnl_proto_hdrs *proto) { bool is_ipv4 = false; bool is_ipv6 = false; bool is_udp = false; u16 ptype = -1; int i = 0; while (i < proto->count && proto->proto_hdr[i].type != VIRTCHNL_PROTO_HDR_NONE) { switch (proto->proto_hdr[i].type) { case VIRTCHNL_PROTO_HDR_ETH: ptype = ICE_PTYPE_MAC_PAY; break; case VIRTCHNL_PROTO_HDR_IPV4: ptype = ICE_PTYPE_IPV4_PAY; is_ipv4 = true; break; case VIRTCHNL_PROTO_HDR_IPV6: ptype = ICE_PTYPE_IPV6_PAY; is_ipv6 = true; break; case VIRTCHNL_PROTO_HDR_UDP: if (is_ipv4) ptype = ICE_PTYPE_IPV4_UDP_PAY; else if (is_ipv6) ptype = ICE_PTYPE_IPV6_UDP_PAY; is_udp = true; break; case VIRTCHNL_PROTO_HDR_TCP: if (is_ipv4) ptype = ICE_PTYPE_IPV4_TCP_PAY; else if (is_ipv6) ptype = ICE_PTYPE_IPV6_TCP_PAY; break; case VIRTCHNL_PROTO_HDR_SCTP: if (is_ipv4) ptype = ICE_PTYPE_IPV4_SCTP_PAY; else if (is_ipv6) ptype = ICE_PTYPE_IPV6_SCTP_PAY; break; case VIRTCHNL_PROTO_HDR_GTPU_IP: case VIRTCHNL_PROTO_HDR_GTPU_EH: if (is_ipv4) ptype = ICE_MAC_IPV4_GTPU; else if (is_ipv6) ptype = ICE_MAC_IPV6_GTPU; goto out; case VIRTCHNL_PROTO_HDR_L2TPV3: if (is_ipv4) ptype = ICE_MAC_IPV4_L2TPV3; else if (is_ipv6) ptype = ICE_MAC_IPV6_L2TPV3; goto out; case VIRTCHNL_PROTO_HDR_ESP: if (is_ipv4) ptype = is_udp ? ICE_MAC_IPV4_NAT_T_ESP : ICE_MAC_IPV4_ESP; else if (is_ipv6) ptype = is_udp ? ICE_MAC_IPV6_NAT_T_ESP : ICE_MAC_IPV6_ESP; goto out; case VIRTCHNL_PROTO_HDR_AH: if (is_ipv4) ptype = ICE_MAC_IPV4_AH; else if (is_ipv6) ptype = ICE_MAC_IPV6_AH; goto out; case VIRTCHNL_PROTO_HDR_PFCP: if (is_ipv4) ptype = ICE_MAC_IPV4_PFCP_SESSION; else if (is_ipv6) ptype = ICE_MAC_IPV6_PFCP_SESSION; goto out; default: break; } i++; } out: return ice_hw_ptype_ena(&vf->pf->hw, ptype); } /** * ice_vc_parse_rss_cfg - parses hash fields and headers from * a specific virtchnl RSS cfg * @hw: pointer to the hardware * @rss_cfg: pointer to the virtchnl RSS cfg * @addl_hdrs: pointer to the protocol header fields (ICE_FLOW_SEG_HDR_*) * to configure * @hash_flds: pointer to the hash bit fields (ICE_FLOW_HASH_*) to configure * * Return true if all the protocol header and hash fields in the RSS cfg could * be parsed, else return false * * This function parses the virtchnl RSS cfg to be the intended * hash fields and the intended header for RSS configuration */ static bool ice_vc_parse_rss_cfg(struct ice_hw *hw, struct virtchnl_rss_cfg *rss_cfg, u32 *addl_hdrs, u64 *hash_flds) { const struct ice_vc_hash_field_match_type *hf_list; const struct ice_vc_hdr_match_type *hdr_list; int i, hf_list_len, hdr_list_len; hf_list = ice_vc_hash_field_list; hf_list_len = ARRAY_SIZE(ice_vc_hash_field_list); hdr_list = ice_vc_hdr_list; hdr_list_len = ARRAY_SIZE(ice_vc_hdr_list); for (i = 0; i < rss_cfg->proto_hdrs.count; i++) { struct virtchnl_proto_hdr *proto_hdr = &rss_cfg->proto_hdrs.proto_hdr[i]; bool hdr_found = false; int j; /* Find matched ice headers according to virtchnl headers. */ for (j = 0; j < hdr_list_len; j++) { struct ice_vc_hdr_match_type hdr_map = hdr_list[j]; if (proto_hdr->type == hdr_map.vc_hdr) { *addl_hdrs |= hdr_map.ice_hdr; hdr_found = true; } } if (!hdr_found) return false; /* Find matched ice hash fields according to * virtchnl hash fields. */ for (j = 0; j < hf_list_len; j++) { struct ice_vc_hash_field_match_type hf_map = hf_list[j]; if (proto_hdr->type == hf_map.vc_hdr && proto_hdr->field_selector == hf_map.vc_hash_field) { *hash_flds |= hf_map.ice_hash_field; break; } } } return true; } /** * ice_vf_adv_rss_offload_ena - determine if capabilities support advanced * RSS offloads * @caps: VF driver negotiated capabilities * * Return true if VIRTCHNL_VF_OFFLOAD_ADV_RSS_PF capability is set, * else return false */ static bool ice_vf_adv_rss_offload_ena(u32 caps) { return !!(caps & VIRTCHNL_VF_OFFLOAD_ADV_RSS_PF); } /** * ice_vc_handle_rss_cfg * @vf: pointer to the VF info * @msg: pointer to the message buffer * @add: add a RSS config if true, otherwise delete a RSS config * * This function adds/deletes a RSS config */ static int ice_vc_handle_rss_cfg(struct ice_vf *vf, u8 *msg, bool add) { u32 v_opcode = add ? VIRTCHNL_OP_ADD_RSS_CFG : VIRTCHNL_OP_DEL_RSS_CFG; struct virtchnl_rss_cfg *rss_cfg = (struct virtchnl_rss_cfg *)msg; enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct device *dev = ice_pf_to_dev(vf->pf); struct ice_hw *hw = &vf->pf->hw; struct ice_vsi *vsi; if (!test_bit(ICE_FLAG_RSS_ENA, vf->pf->flags)) { dev_dbg(dev, "VF %d attempting to configure RSS, but RSS is not supported by the PF\n", vf->vf_id); v_ret = VIRTCHNL_STATUS_ERR_NOT_SUPPORTED; goto error_param; } if (!ice_vf_adv_rss_offload_ena(vf->driver_caps)) { dev_dbg(dev, "VF %d attempting to configure RSS, but Advanced RSS offload is not supported\n", vf->vf_id); v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (rss_cfg->proto_hdrs.count > VIRTCHNL_MAX_NUM_PROTO_HDRS || rss_cfg->rss_algorithm < VIRTCHNL_RSS_ALG_TOEPLITZ_ASYMMETRIC || rss_cfg->rss_algorithm > VIRTCHNL_RSS_ALG_XOR_SYMMETRIC) { dev_dbg(dev, "VF %d attempting to configure RSS, but RSS configuration is not valid\n", vf->vf_id); v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } vsi = ice_get_vf_vsi(vf); if (!vsi) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (!ice_vc_validate_pattern(vf, &rss_cfg->proto_hdrs)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (rss_cfg->rss_algorithm == VIRTCHNL_RSS_ALG_R_ASYMMETRIC) { struct ice_vsi_ctx *ctx; u8 lut_type, hash_type; int status; lut_type = ICE_AQ_VSI_Q_OPT_RSS_LUT_VSI; hash_type = add ? ICE_AQ_VSI_Q_OPT_RSS_XOR : ICE_AQ_VSI_Q_OPT_RSS_TPLZ; ctx = kzalloc(sizeof(*ctx), GFP_KERNEL); if (!ctx) { v_ret = VIRTCHNL_STATUS_ERR_NO_MEMORY; goto error_param; } ctx->info.q_opt_rss = ((lut_type << ICE_AQ_VSI_Q_OPT_RSS_LUT_S) & ICE_AQ_VSI_Q_OPT_RSS_LUT_M) | (hash_type & ICE_AQ_VSI_Q_OPT_RSS_HASH_M); /* Preserve existing queueing option setting */ ctx->info.q_opt_rss |= (vsi->info.q_opt_rss & ICE_AQ_VSI_Q_OPT_RSS_GBL_LUT_M); ctx->info.q_opt_tc = vsi->info.q_opt_tc; ctx->info.q_opt_flags = vsi->info.q_opt_rss; ctx->info.valid_sections = cpu_to_le16(ICE_AQ_VSI_PROP_Q_OPT_VALID); status = ice_update_vsi(hw, vsi->idx, ctx, NULL); if (status) { dev_err(dev, "update VSI for RSS failed, err %d aq_err %s\n", status, ice_aq_str(hw->adminq.sq_last_status)); v_ret = VIRTCHNL_STATUS_ERR_PARAM; } else { vsi->info.q_opt_rss = ctx->info.q_opt_rss; } kfree(ctx); } else { u32 addl_hdrs = ICE_FLOW_SEG_HDR_NONE; u64 hash_flds = ICE_HASH_INVALID; if (!ice_vc_parse_rss_cfg(hw, rss_cfg, &addl_hdrs, &hash_flds)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (add) { if (ice_add_rss_cfg(hw, vsi->idx, hash_flds, addl_hdrs)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; dev_err(dev, "ice_add_rss_cfg failed for vsi = %d, v_ret = %d\n", vsi->vsi_num, v_ret); } } else { int status; status = ice_rem_rss_cfg(hw, vsi->idx, hash_flds, addl_hdrs); /* We just ignore -ENOENT, because if two configurations * share the same profile remove one of them actually * removes both, since the profile is deleted. */ if (status && status != -ENOENT) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; dev_err(dev, "ice_rem_rss_cfg failed for VF ID:%d, error:%d\n", vf->vf_id, status); } } } error_param: return ice_vc_send_msg_to_vf(vf, v_opcode, v_ret, NULL, 0); } /** * ice_vc_config_rss_key * @vf: pointer to the VF info * @msg: pointer to the msg buffer * * Configure the VF's RSS key */ static int ice_vc_config_rss_key(struct ice_vf *vf, u8 *msg) { enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct virtchnl_rss_key *vrk = (struct virtchnl_rss_key *)msg; struct ice_vsi *vsi; if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (!ice_vc_isvalid_vsi_id(vf, vrk->vsi_id)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (vrk->key_len != ICE_VSIQF_HKEY_ARRAY_SIZE) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (!test_bit(ICE_FLAG_RSS_ENA, vf->pf->flags)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } vsi = ice_get_vf_vsi(vf); if (!vsi) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (ice_set_rss_key(vsi, vrk->key)) v_ret = VIRTCHNL_STATUS_ERR_ADMIN_QUEUE_ERROR; error_param: return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_CONFIG_RSS_KEY, v_ret, NULL, 0); } /** * ice_vc_config_rss_lut * @vf: pointer to the VF info * @msg: pointer to the msg buffer * * Configure the VF's RSS LUT */ static int ice_vc_config_rss_lut(struct ice_vf *vf, u8 *msg) { struct virtchnl_rss_lut *vrl = (struct virtchnl_rss_lut *)msg; enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct ice_vsi *vsi; if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (!ice_vc_isvalid_vsi_id(vf, vrl->vsi_id)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (vrl->lut_entries != ICE_LUT_VSI_SIZE) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (!test_bit(ICE_FLAG_RSS_ENA, vf->pf->flags)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } vsi = ice_get_vf_vsi(vf); if (!vsi) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (ice_set_rss_lut(vsi, vrl->lut, ICE_LUT_VSI_SIZE)) v_ret = VIRTCHNL_STATUS_ERR_ADMIN_QUEUE_ERROR; error_param: return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_CONFIG_RSS_LUT, v_ret, NULL, 0); } /** * ice_vc_cfg_promiscuous_mode_msg * @vf: pointer to the VF info * @msg: pointer to the msg buffer * * called from the VF to configure VF VSIs promiscuous mode */ static int ice_vc_cfg_promiscuous_mode_msg(struct ice_vf *vf, u8 *msg) { enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; bool rm_promisc, alluni = false, allmulti = false; struct virtchnl_promisc_info *info = (struct virtchnl_promisc_info *)msg; struct ice_vsi_vlan_ops *vlan_ops; int mcast_err = 0, ucast_err = 0; struct ice_pf *pf = vf->pf; struct ice_vsi *vsi; u8 mcast_m, ucast_m; struct device *dev; int ret = 0; if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (!ice_vc_isvalid_vsi_id(vf, info->vsi_id)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } vsi = ice_get_vf_vsi(vf); if (!vsi) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } dev = ice_pf_to_dev(pf); if (!ice_is_vf_trusted(vf)) { dev_err(dev, "Unprivileged VF %d is attempting to configure promiscuous mode\n", vf->vf_id); /* Leave v_ret alone, lie to the VF on purpose. */ goto error_param; } if (info->flags & FLAG_VF_UNICAST_PROMISC) alluni = true; if (info->flags & FLAG_VF_MULTICAST_PROMISC) allmulti = true; rm_promisc = !allmulti && !alluni; vlan_ops = ice_get_compat_vsi_vlan_ops(vsi); if (rm_promisc) ret = vlan_ops->ena_rx_filtering(vsi); else ret = vlan_ops->dis_rx_filtering(vsi); if (ret) { dev_err(dev, "Failed to configure VLAN pruning in promiscuous mode\n"); v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } ice_vf_get_promisc_masks(vf, vsi, &ucast_m, &mcast_m); if (!test_bit(ICE_FLAG_VF_TRUE_PROMISC_ENA, pf->flags)) { if (alluni) { /* in this case we're turning on promiscuous mode */ ret = ice_set_dflt_vsi(vsi); } else { /* in this case we're turning off promiscuous mode */ if (ice_is_dflt_vsi_in_use(vsi->port_info)) ret = ice_clear_dflt_vsi(vsi); } /* in this case we're turning on/off only * allmulticast */ if (allmulti) mcast_err = ice_vf_set_vsi_promisc(vf, vsi, mcast_m); else mcast_err = ice_vf_clear_vsi_promisc(vf, vsi, mcast_m); if (ret) { dev_err(dev, "Turning on/off promiscuous mode for VF %d failed, error: %d\n", vf->vf_id, ret); v_ret = VIRTCHNL_STATUS_ERR_ADMIN_QUEUE_ERROR; goto error_param; } } else { if (alluni) ucast_err = ice_vf_set_vsi_promisc(vf, vsi, ucast_m); else ucast_err = ice_vf_clear_vsi_promisc(vf, vsi, ucast_m); if (allmulti) mcast_err = ice_vf_set_vsi_promisc(vf, vsi, mcast_m); else mcast_err = ice_vf_clear_vsi_promisc(vf, vsi, mcast_m); if (ucast_err || mcast_err) v_ret = VIRTCHNL_STATUS_ERR_PARAM; } if (!mcast_err) { if (allmulti && !test_and_set_bit(ICE_VF_STATE_MC_PROMISC, vf->vf_states)) dev_info(dev, "VF %u successfully set multicast promiscuous mode\n", vf->vf_id); else if (!allmulti && test_and_clear_bit(ICE_VF_STATE_MC_PROMISC, vf->vf_states)) dev_info(dev, "VF %u successfully unset multicast promiscuous mode\n", vf->vf_id); } else { dev_err(dev, "Error while modifying multicast promiscuous mode for VF %u, error: %d\n", vf->vf_id, mcast_err); } if (!ucast_err) { if (alluni && !test_and_set_bit(ICE_VF_STATE_UC_PROMISC, vf->vf_states)) dev_info(dev, "VF %u successfully set unicast promiscuous mode\n", vf->vf_id); else if (!alluni && test_and_clear_bit(ICE_VF_STATE_UC_PROMISC, vf->vf_states)) dev_info(dev, "VF %u successfully unset unicast promiscuous mode\n", vf->vf_id); } else { dev_err(dev, "Error while modifying unicast promiscuous mode for VF %u, error: %d\n", vf->vf_id, ucast_err); } error_param: return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_CONFIG_PROMISCUOUS_MODE, v_ret, NULL, 0); } /** * ice_vc_get_stats_msg * @vf: pointer to the VF info * @msg: pointer to the msg buffer * * called from the VF to get VSI stats */ static int ice_vc_get_stats_msg(struct ice_vf *vf, u8 *msg) { enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct virtchnl_queue_select *vqs = (struct virtchnl_queue_select *)msg; struct ice_eth_stats stats = { 0 }; struct ice_vsi *vsi; if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (!ice_vc_isvalid_vsi_id(vf, vqs->vsi_id)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } vsi = ice_get_vf_vsi(vf); if (!vsi) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } ice_update_eth_stats(vsi); stats = vsi->eth_stats; error_param: /* send the response to the VF */ return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_GET_STATS, v_ret, (u8 *)&stats, sizeof(stats)); } /** * ice_vc_validate_vqs_bitmaps - validate Rx/Tx queue bitmaps from VIRTCHNL * @vqs: virtchnl_queue_select structure containing bitmaps to validate * * Return true on successful validation, else false */ static bool ice_vc_validate_vqs_bitmaps(struct virtchnl_queue_select *vqs) { if ((!vqs->rx_queues && !vqs->tx_queues) || vqs->rx_queues >= BIT(ICE_MAX_RSS_QS_PER_VF) || vqs->tx_queues >= BIT(ICE_MAX_RSS_QS_PER_VF)) return false; return true; } /** * ice_vf_ena_txq_interrupt - enable Tx queue interrupt via QINT_TQCTL * @vsi: VSI of the VF to configure * @q_idx: VF queue index used to determine the queue in the PF's space */ static void ice_vf_ena_txq_interrupt(struct ice_vsi *vsi, u32 q_idx) { struct ice_hw *hw = &vsi->back->hw; u32 pfq = vsi->txq_map[q_idx]; u32 reg; reg = rd32(hw, QINT_TQCTL(pfq)); /* MSI-X index 0 in the VF's space is always for the OICR, which means * this is most likely a poll mode VF driver, so don't enable an * interrupt that was never configured via VIRTCHNL_OP_CONFIG_IRQ_MAP */ if (!(reg & QINT_TQCTL_MSIX_INDX_M)) return; wr32(hw, QINT_TQCTL(pfq), reg | QINT_TQCTL_CAUSE_ENA_M); } /** * ice_vf_ena_rxq_interrupt - enable Tx queue interrupt via QINT_RQCTL * @vsi: VSI of the VF to configure * @q_idx: VF queue index used to determine the queue in the PF's space */ static void ice_vf_ena_rxq_interrupt(struct ice_vsi *vsi, u32 q_idx) { struct ice_hw *hw = &vsi->back->hw; u32 pfq = vsi->rxq_map[q_idx]; u32 reg; reg = rd32(hw, QINT_RQCTL(pfq)); /* MSI-X index 0 in the VF's space is always for the OICR, which means * this is most likely a poll mode VF driver, so don't enable an * interrupt that was never configured via VIRTCHNL_OP_CONFIG_IRQ_MAP */ if (!(reg & QINT_RQCTL_MSIX_INDX_M)) return; wr32(hw, QINT_RQCTL(pfq), reg | QINT_RQCTL_CAUSE_ENA_M); } /** * ice_vc_ena_qs_msg * @vf: pointer to the VF info * @msg: pointer to the msg buffer * * called from the VF to enable all or specific queue(s) */ static int ice_vc_ena_qs_msg(struct ice_vf *vf, u8 *msg) { enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct virtchnl_queue_select *vqs = (struct virtchnl_queue_select *)msg; struct ice_vsi *vsi; unsigned long q_map; u16 vf_q_id; if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (!ice_vc_isvalid_vsi_id(vf, vqs->vsi_id)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (!ice_vc_validate_vqs_bitmaps(vqs)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } vsi = ice_get_vf_vsi(vf); if (!vsi) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } /* Enable only Rx rings, Tx rings were enabled by the FW when the * Tx queue group list was configured and the context bits were * programmed using ice_vsi_cfg_txqs */ q_map = vqs->rx_queues; for_each_set_bit(vf_q_id, &q_map, ICE_MAX_RSS_QS_PER_VF) { if (!ice_vc_isvalid_q_id(vf, vqs->vsi_id, vf_q_id)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } /* Skip queue if enabled */ if (test_bit(vf_q_id, vf->rxq_ena)) continue; if (ice_vsi_ctrl_one_rx_ring(vsi, true, vf_q_id, true)) { dev_err(ice_pf_to_dev(vsi->back), "Failed to enable Rx ring %d on VSI %d\n", vf_q_id, vsi->vsi_num); v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } ice_vf_ena_rxq_interrupt(vsi, vf_q_id); set_bit(vf_q_id, vf->rxq_ena); } q_map = vqs->tx_queues; for_each_set_bit(vf_q_id, &q_map, ICE_MAX_RSS_QS_PER_VF) { if (!ice_vc_isvalid_q_id(vf, vqs->vsi_id, vf_q_id)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } /* Skip queue if enabled */ if (test_bit(vf_q_id, vf->txq_ena)) continue; ice_vf_ena_txq_interrupt(vsi, vf_q_id); set_bit(vf_q_id, vf->txq_ena); } /* Set flag to indicate that queues are enabled */ if (v_ret == VIRTCHNL_STATUS_SUCCESS) set_bit(ICE_VF_STATE_QS_ENA, vf->vf_states); error_param: /* send the response to the VF */ return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_ENABLE_QUEUES, v_ret, NULL, 0); } /** * ice_vf_vsi_dis_single_txq - disable a single Tx queue * @vf: VF to disable queue for * @vsi: VSI for the VF * @q_id: VF relative (0-based) queue ID * * Attempt to disable the Tx queue passed in. If the Tx queue was successfully * disabled then clear q_id bit in the enabled queues bitmap and return * success. Otherwise return error. */ static int ice_vf_vsi_dis_single_txq(struct ice_vf *vf, struct ice_vsi *vsi, u16 q_id) { struct ice_txq_meta txq_meta = { 0 }; struct ice_tx_ring *ring; int err; if (!test_bit(q_id, vf->txq_ena)) dev_dbg(ice_pf_to_dev(vsi->back), "Queue %u on VSI %u is not enabled, but stopping it anyway\n", q_id, vsi->vsi_num); ring = vsi->tx_rings[q_id]; if (!ring) return -EINVAL; ice_fill_txq_meta(vsi, ring, &txq_meta); err = ice_vsi_stop_tx_ring(vsi, ICE_NO_RESET, vf->vf_id, ring, &txq_meta); if (err) { dev_err(ice_pf_to_dev(vsi->back), "Failed to stop Tx ring %d on VSI %d\n", q_id, vsi->vsi_num); return err; } /* Clear enabled queues flag */ clear_bit(q_id, vf->txq_ena); return 0; } /** * ice_vc_dis_qs_msg * @vf: pointer to the VF info * @msg: pointer to the msg buffer * * called from the VF to disable all or specific queue(s) */ static int ice_vc_dis_qs_msg(struct ice_vf *vf, u8 *msg) { enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct virtchnl_queue_select *vqs = (struct virtchnl_queue_select *)msg; struct ice_vsi *vsi; unsigned long q_map; u16 vf_q_id; if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states) && !test_bit(ICE_VF_STATE_QS_ENA, vf->vf_states)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (!ice_vc_isvalid_vsi_id(vf, vqs->vsi_id)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (!ice_vc_validate_vqs_bitmaps(vqs)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } vsi = ice_get_vf_vsi(vf); if (!vsi) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (vqs->tx_queues) { q_map = vqs->tx_queues; for_each_set_bit(vf_q_id, &q_map, ICE_MAX_RSS_QS_PER_VF) { if (!ice_vc_isvalid_q_id(vf, vqs->vsi_id, vf_q_id)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (ice_vf_vsi_dis_single_txq(vf, vsi, vf_q_id)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } } } q_map = vqs->rx_queues; /* speed up Rx queue disable by batching them if possible */ if (q_map && bitmap_equal(&q_map, vf->rxq_ena, ICE_MAX_RSS_QS_PER_VF)) { if (ice_vsi_stop_all_rx_rings(vsi)) { dev_err(ice_pf_to_dev(vsi->back), "Failed to stop all Rx rings on VSI %d\n", vsi->vsi_num); v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } bitmap_zero(vf->rxq_ena, ICE_MAX_RSS_QS_PER_VF); } else if (q_map) { for_each_set_bit(vf_q_id, &q_map, ICE_MAX_RSS_QS_PER_VF) { if (!ice_vc_isvalid_q_id(vf, vqs->vsi_id, vf_q_id)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } /* Skip queue if not enabled */ if (!test_bit(vf_q_id, vf->rxq_ena)) continue; if (ice_vsi_ctrl_one_rx_ring(vsi, false, vf_q_id, true)) { dev_err(ice_pf_to_dev(vsi->back), "Failed to stop Rx ring %d on VSI %d\n", vf_q_id, vsi->vsi_num); v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } /* Clear enabled queues flag */ clear_bit(vf_q_id, vf->rxq_ena); } } /* Clear enabled queues flag */ if (v_ret == VIRTCHNL_STATUS_SUCCESS && ice_vf_has_no_qs_ena(vf)) clear_bit(ICE_VF_STATE_QS_ENA, vf->vf_states); error_param: /* send the response to the VF */ return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_DISABLE_QUEUES, v_ret, NULL, 0); } /** * ice_cfg_interrupt * @vf: pointer to the VF info * @vsi: the VSI being configured * @vector_id: vector ID * @map: vector map for mapping vectors to queues * @q_vector: structure for interrupt vector * configure the IRQ to queue map */ static int ice_cfg_interrupt(struct ice_vf *vf, struct ice_vsi *vsi, u16 vector_id, struct virtchnl_vector_map *map, struct ice_q_vector *q_vector) { u16 vsi_q_id, vsi_q_id_idx; unsigned long qmap; q_vector->num_ring_rx = 0; q_vector->num_ring_tx = 0; qmap = map->rxq_map; for_each_set_bit(vsi_q_id_idx, &qmap, ICE_MAX_RSS_QS_PER_VF) { vsi_q_id = vsi_q_id_idx; if (!ice_vc_isvalid_q_id(vf, vsi->vsi_num, vsi_q_id)) return VIRTCHNL_STATUS_ERR_PARAM; q_vector->num_ring_rx++; q_vector->rx.itr_idx = map->rxitr_idx; vsi->rx_rings[vsi_q_id]->q_vector = q_vector; ice_cfg_rxq_interrupt(vsi, vsi_q_id, vector_id, q_vector->rx.itr_idx); } qmap = map->txq_map; for_each_set_bit(vsi_q_id_idx, &qmap, ICE_MAX_RSS_QS_PER_VF) { vsi_q_id = vsi_q_id_idx; if (!ice_vc_isvalid_q_id(vf, vsi->vsi_num, vsi_q_id)) return VIRTCHNL_STATUS_ERR_PARAM; q_vector->num_ring_tx++; q_vector->tx.itr_idx = map->txitr_idx; vsi->tx_rings[vsi_q_id]->q_vector = q_vector; ice_cfg_txq_interrupt(vsi, vsi_q_id, vector_id, q_vector->tx.itr_idx); } return VIRTCHNL_STATUS_SUCCESS; } /** * ice_vc_cfg_irq_map_msg * @vf: pointer to the VF info * @msg: pointer to the msg buffer * * called from the VF to configure the IRQ to queue map */ static int ice_vc_cfg_irq_map_msg(struct ice_vf *vf, u8 *msg) { enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; u16 num_q_vectors_mapped, vsi_id, vector_id; struct virtchnl_irq_map_info *irqmap_info; struct virtchnl_vector_map *map; struct ice_pf *pf = vf->pf; struct ice_vsi *vsi; int i; irqmap_info = (struct virtchnl_irq_map_info *)msg; num_q_vectors_mapped = irqmap_info->num_vectors; /* Check to make sure number of VF vectors mapped is not greater than * number of VF vectors originally allocated, and check that * there is actually at least a single VF queue vector mapped */ if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states) || pf->vfs.num_msix_per < num_q_vectors_mapped || !num_q_vectors_mapped) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } vsi = ice_get_vf_vsi(vf); if (!vsi) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } for (i = 0; i < num_q_vectors_mapped; i++) { struct ice_q_vector *q_vector; map = &irqmap_info->vecmap[i]; vector_id = map->vector_id; vsi_id = map->vsi_id; /* vector_id is always 0-based for each VF, and can never be * larger than or equal to the max allowed interrupts per VF */ if (!(vector_id < pf->vfs.num_msix_per) || !ice_vc_isvalid_vsi_id(vf, vsi_id) || (!vector_id && (map->rxq_map || map->txq_map))) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } /* No need to map VF miscellaneous or rogue vector */ if (!vector_id) continue; /* Subtract non queue vector from vector_id passed by VF * to get actual number of VSI queue vector array index */ q_vector = vsi->q_vectors[vector_id - ICE_NONQ_VECS_VF]; if (!q_vector) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } /* lookout for the invalid queue index */ v_ret = (enum virtchnl_status_code) ice_cfg_interrupt(vf, vsi, vector_id, map, q_vector); if (v_ret) goto error_param; } error_param: /* send the response to the VF */ return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_CONFIG_IRQ_MAP, v_ret, NULL, 0); } /** * ice_vc_cfg_qs_msg * @vf: pointer to the VF info * @msg: pointer to the msg buffer * * called from the VF to configure the Rx/Tx queues */ static int ice_vc_cfg_qs_msg(struct ice_vf *vf, u8 *msg) { struct virtchnl_vsi_queue_config_info *qci = (struct virtchnl_vsi_queue_config_info *)msg; struct virtchnl_queue_pair_info *qpi; struct ice_pf *pf = vf->pf; struct ice_vsi *vsi; int i = -1, q_idx; if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) goto error_param; if (!ice_vc_isvalid_vsi_id(vf, qci->vsi_id)) goto error_param; vsi = ice_get_vf_vsi(vf); if (!vsi) goto error_param; if (qci->num_queue_pairs > ICE_MAX_RSS_QS_PER_VF || qci->num_queue_pairs > min_t(u16, vsi->alloc_txq, vsi->alloc_rxq)) { dev_err(ice_pf_to_dev(pf), "VF-%d requesting more than supported number of queues: %d\n", vf->vf_id, min_t(u16, vsi->alloc_txq, vsi->alloc_rxq)); goto error_param; } for (i = 0; i < qci->num_queue_pairs; i++) { qpi = &qci->qpair[i]; if (qpi->txq.vsi_id != qci->vsi_id || qpi->rxq.vsi_id != qci->vsi_id || qpi->rxq.queue_id != qpi->txq.queue_id || qpi->txq.headwb_enabled || !ice_vc_isvalid_ring_len(qpi->txq.ring_len) || !ice_vc_isvalid_ring_len(qpi->rxq.ring_len) || !ice_vc_isvalid_q_id(vf, qci->vsi_id, qpi->txq.queue_id)) { goto error_param; } q_idx = qpi->rxq.queue_id; /* make sure selected "q_idx" is in valid range of queues * for selected "vsi" */ if (q_idx >= vsi->alloc_txq || q_idx >= vsi->alloc_rxq) { goto error_param; } /* copy Tx queue info from VF into VSI */ if (qpi->txq.ring_len > 0) { vsi->tx_rings[i]->dma = qpi->txq.dma_ring_addr; vsi->tx_rings[i]->count = qpi->txq.ring_len; /* Disable any existing queue first */ if (ice_vf_vsi_dis_single_txq(vf, vsi, q_idx)) goto error_param; /* Configure a queue with the requested settings */ if (ice_vsi_cfg_single_txq(vsi, vsi->tx_rings, q_idx)) { dev_warn(ice_pf_to_dev(pf), "VF-%d failed to configure TX queue %d\n", vf->vf_id, i); goto error_param; } } /* copy Rx queue info from VF into VSI */ if (qpi->rxq.ring_len > 0) { u16 max_frame_size = ice_vc_get_max_frame_size(vf); u32 rxdid; vsi->rx_rings[i]->dma = qpi->rxq.dma_ring_addr; vsi->rx_rings[i]->count = qpi->rxq.ring_len; if (qpi->rxq.databuffer_size != 0 && (qpi->rxq.databuffer_size > ((16 * 1024) - 128) || qpi->rxq.databuffer_size < 1024)) goto error_param; vsi->rx_buf_len = qpi->rxq.databuffer_size; vsi->rx_rings[i]->rx_buf_len = vsi->rx_buf_len; if (qpi->rxq.max_pkt_size > max_frame_size || qpi->rxq.max_pkt_size < 64) goto error_param; vsi->max_frame = qpi->rxq.max_pkt_size; /* add space for the port VLAN since the VF driver is * not expected to account for it in the MTU * calculation */ if (ice_vf_is_port_vlan_ena(vf)) vsi->max_frame += VLAN_HLEN; if (ice_vsi_cfg_single_rxq(vsi, q_idx)) { dev_warn(ice_pf_to_dev(pf), "VF-%d failed to configure RX queue %d\n", vf->vf_id, i); goto error_param; } /* If Rx flex desc is supported, select RXDID for Rx * queues. Otherwise, use legacy 32byte descriptor * format. Legacy 16byte descriptor is not supported. * If this RXDID is selected, return error. */ if (vf->driver_caps & VIRTCHNL_VF_OFFLOAD_RX_FLEX_DESC) { rxdid = qpi->rxq.rxdid; if (!(BIT(rxdid) & pf->supported_rxdids)) goto error_param; } else { rxdid = ICE_RXDID_LEGACY_1; } ice_write_qrxflxp_cntxt(&vsi->back->hw, vsi->rxq_map[q_idx], rxdid, 0x03, false); } } /* send the response to the VF */ return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_CONFIG_VSI_QUEUES, VIRTCHNL_STATUS_SUCCESS, NULL, 0); error_param: /* disable whatever we can */ for (; i >= 0; i--) { if (ice_vsi_ctrl_one_rx_ring(vsi, false, i, true)) dev_err(ice_pf_to_dev(pf), "VF-%d could not disable RX queue %d\n", vf->vf_id, i); if (ice_vf_vsi_dis_single_txq(vf, vsi, i)) dev_err(ice_pf_to_dev(pf), "VF-%d could not disable TX queue %d\n", vf->vf_id, i); } ice_lag_move_new_vf_nodes(vf); /* send the response to the VF */ return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_CONFIG_VSI_QUEUES, VIRTCHNL_STATUS_ERR_PARAM, NULL, 0); } /** * ice_can_vf_change_mac * @vf: pointer to the VF info * * Return true if the VF is allowed to change its MAC filters, false otherwise */ static bool ice_can_vf_change_mac(struct ice_vf *vf) { /* If the VF MAC address has been set administratively (via the * ndo_set_vf_mac command), then deny permission to the VF to * add/delete unicast MAC addresses, unless the VF is trusted */ if (vf->pf_set_mac && !ice_is_vf_trusted(vf)) return false; return true; } /** * ice_vc_ether_addr_type - get type of virtchnl_ether_addr * @vc_ether_addr: used to extract the type */ static u8 ice_vc_ether_addr_type(struct virtchnl_ether_addr *vc_ether_addr) { return (vc_ether_addr->type & VIRTCHNL_ETHER_ADDR_TYPE_MASK); } /** * ice_is_vc_addr_legacy - check if the MAC address is from an older VF * @vc_ether_addr: VIRTCHNL structure that contains MAC and type */ static bool ice_is_vc_addr_legacy(struct virtchnl_ether_addr *vc_ether_addr) { u8 type = ice_vc_ether_addr_type(vc_ether_addr); return (type == VIRTCHNL_ETHER_ADDR_LEGACY); } /** * ice_is_vc_addr_primary - check if the MAC address is the VF's primary MAC * @vc_ether_addr: VIRTCHNL structure that contains MAC and type * * This function should only be called when the MAC address in * virtchnl_ether_addr is a valid unicast MAC */ static bool ice_is_vc_addr_primary(struct virtchnl_ether_addr __maybe_unused *vc_ether_addr) { u8 type = ice_vc_ether_addr_type(vc_ether_addr); return (type == VIRTCHNL_ETHER_ADDR_PRIMARY); } /** * ice_vfhw_mac_add - update the VF's cached hardware MAC if allowed * @vf: VF to update * @vc_ether_addr: structure from VIRTCHNL with MAC to add */ static void ice_vfhw_mac_add(struct ice_vf *vf, struct virtchnl_ether_addr *vc_ether_addr) { u8 *mac_addr = vc_ether_addr->addr; if (!is_valid_ether_addr(mac_addr)) return; /* only allow legacy VF drivers to set the device and hardware MAC if it * is zero and allow new VF drivers to set the hardware MAC if the type * was correctly specified over VIRTCHNL */ if ((ice_is_vc_addr_legacy(vc_ether_addr) && is_zero_ether_addr(vf->hw_lan_addr)) || ice_is_vc_addr_primary(vc_ether_addr)) { ether_addr_copy(vf->dev_lan_addr, mac_addr); ether_addr_copy(vf->hw_lan_addr, mac_addr); } /* hardware and device MACs are already set, but its possible that the * VF driver sent the VIRTCHNL_OP_ADD_ETH_ADDR message before the * VIRTCHNL_OP_DEL_ETH_ADDR when trying to update its MAC, so save it * away for the legacy VF driver case as it will be updated in the * delete flow for this case */ if (ice_is_vc_addr_legacy(vc_ether_addr)) { ether_addr_copy(vf->legacy_last_added_umac.addr, mac_addr); vf->legacy_last_added_umac.time_modified = jiffies; } } /** * ice_vc_add_mac_addr - attempt to add the MAC address passed in * @vf: pointer to the VF info * @vsi: pointer to the VF's VSI * @vc_ether_addr: VIRTCHNL MAC address structure used to add MAC */ static int ice_vc_add_mac_addr(struct ice_vf *vf, struct ice_vsi *vsi, struct virtchnl_ether_addr *vc_ether_addr) { struct device *dev = ice_pf_to_dev(vf->pf); u8 *mac_addr = vc_ether_addr->addr; int ret; /* device MAC already added */ if (ether_addr_equal(mac_addr, vf->dev_lan_addr)) return 0; if (is_unicast_ether_addr(mac_addr) && !ice_can_vf_change_mac(vf)) { dev_err(dev, "VF attempting to override administratively set MAC address, bring down and up the VF interface to resume normal operation\n"); return -EPERM; } ret = ice_fltr_add_mac(vsi, mac_addr, ICE_FWD_TO_VSI); if (ret == -EEXIST) { dev_dbg(dev, "MAC %pM already exists for VF %d\n", mac_addr, vf->vf_id); /* don't return since we might need to update * the primary MAC in ice_vfhw_mac_add() below */ } else if (ret) { dev_err(dev, "Failed to add MAC %pM for VF %d\n, error %d\n", mac_addr, vf->vf_id, ret); return ret; } else { vf->num_mac++; } ice_vfhw_mac_add(vf, vc_ether_addr); return ret; } /** * ice_is_legacy_umac_expired - check if last added legacy unicast MAC expired * @last_added_umac: structure used to check expiration */ static bool ice_is_legacy_umac_expired(struct ice_time_mac *last_added_umac) { #define ICE_LEGACY_VF_MAC_CHANGE_EXPIRE_TIME msecs_to_jiffies(3000) return time_is_before_jiffies(last_added_umac->time_modified + ICE_LEGACY_VF_MAC_CHANGE_EXPIRE_TIME); } /** * ice_update_legacy_cached_mac - update cached hardware MAC for legacy VF * @vf: VF to update * @vc_ether_addr: structure from VIRTCHNL with MAC to check * * only update cached hardware MAC for legacy VF drivers on delete * because we cannot guarantee order/type of MAC from the VF driver */ static void ice_update_legacy_cached_mac(struct ice_vf *vf, struct virtchnl_ether_addr *vc_ether_addr) { if (!ice_is_vc_addr_legacy(vc_ether_addr) || ice_is_legacy_umac_expired(&vf->legacy_last_added_umac)) return; ether_addr_copy(vf->dev_lan_addr, vf->legacy_last_added_umac.addr); ether_addr_copy(vf->hw_lan_addr, vf->legacy_last_added_umac.addr); } /** * ice_vfhw_mac_del - update the VF's cached hardware MAC if allowed * @vf: VF to update * @vc_ether_addr: structure from VIRTCHNL with MAC to delete */ static void ice_vfhw_mac_del(struct ice_vf *vf, struct virtchnl_ether_addr *vc_ether_addr) { u8 *mac_addr = vc_ether_addr->addr; if (!is_valid_ether_addr(mac_addr) || !ether_addr_equal(vf->dev_lan_addr, mac_addr)) return; /* allow the device MAC to be repopulated in the add flow and don't * clear the hardware MAC (i.e. hw_lan_addr) here as that is meant * to be persistent on VM reboot and across driver unload/load, which * won't work if we clear the hardware MAC here */ eth_zero_addr(vf->dev_lan_addr); ice_update_legacy_cached_mac(vf, vc_ether_addr); } /** * ice_vc_del_mac_addr - attempt to delete the MAC address passed in * @vf: pointer to the VF info * @vsi: pointer to the VF's VSI * @vc_ether_addr: VIRTCHNL MAC address structure used to delete MAC */ static int ice_vc_del_mac_addr(struct ice_vf *vf, struct ice_vsi *vsi, struct virtchnl_ether_addr *vc_ether_addr) { struct device *dev = ice_pf_to_dev(vf->pf); u8 *mac_addr = vc_ether_addr->addr; int status; if (!ice_can_vf_change_mac(vf) && ether_addr_equal(vf->dev_lan_addr, mac_addr)) return 0; status = ice_fltr_remove_mac(vsi, mac_addr, ICE_FWD_TO_VSI); if (status == -ENOENT) { dev_err(dev, "MAC %pM does not exist for VF %d\n", mac_addr, vf->vf_id); return -ENOENT; } else if (status) { dev_err(dev, "Failed to delete MAC %pM for VF %d, error %d\n", mac_addr, vf->vf_id, status); return -EIO; } ice_vfhw_mac_del(vf, vc_ether_addr); vf->num_mac--; return 0; } /** * ice_vc_handle_mac_addr_msg * @vf: pointer to the VF info * @msg: pointer to the msg buffer * @set: true if MAC filters are being set, false otherwise * * add guest MAC address filter */ static int ice_vc_handle_mac_addr_msg(struct ice_vf *vf, u8 *msg, bool set) { int (*ice_vc_cfg_mac) (struct ice_vf *vf, struct ice_vsi *vsi, struct virtchnl_ether_addr *virtchnl_ether_addr); enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct virtchnl_ether_addr_list *al = (struct virtchnl_ether_addr_list *)msg; struct ice_pf *pf = vf->pf; enum virtchnl_ops vc_op; struct ice_vsi *vsi; int i; if (set) { vc_op = VIRTCHNL_OP_ADD_ETH_ADDR; ice_vc_cfg_mac = ice_vc_add_mac_addr; } else { vc_op = VIRTCHNL_OP_DEL_ETH_ADDR; ice_vc_cfg_mac = ice_vc_del_mac_addr; } if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states) || !ice_vc_isvalid_vsi_id(vf, al->vsi_id)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto handle_mac_exit; } /* If this VF is not privileged, then we can't add more than a * limited number of addresses. Check to make sure that the * additions do not push us over the limit. */ if (set && !ice_is_vf_trusted(vf) && (vf->num_mac + al->num_elements) > ICE_MAX_MACADDR_PER_VF) { dev_err(ice_pf_to_dev(pf), "Can't add more MAC addresses, because VF-%d is not trusted, switch the VF to trusted mode in order to add more functionalities\n", vf->vf_id); v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto handle_mac_exit; } vsi = ice_get_vf_vsi(vf); if (!vsi) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto handle_mac_exit; } for (i = 0; i < al->num_elements; i++) { u8 *mac_addr = al->list[i].addr; int result; if (is_broadcast_ether_addr(mac_addr) || is_zero_ether_addr(mac_addr)) continue; result = ice_vc_cfg_mac(vf, vsi, &al->list[i]); if (result == -EEXIST || result == -ENOENT) { continue; } else if (result) { v_ret = VIRTCHNL_STATUS_ERR_ADMIN_QUEUE_ERROR; goto handle_mac_exit; } } handle_mac_exit: /* send the response to the VF */ return ice_vc_send_msg_to_vf(vf, vc_op, v_ret, NULL, 0); } /** * ice_vc_add_mac_addr_msg * @vf: pointer to the VF info * @msg: pointer to the msg buffer * * add guest MAC address filter */ static int ice_vc_add_mac_addr_msg(struct ice_vf *vf, u8 *msg) { return ice_vc_handle_mac_addr_msg(vf, msg, true); } /** * ice_vc_del_mac_addr_msg * @vf: pointer to the VF info * @msg: pointer to the msg buffer * * remove guest MAC address filter */ static int ice_vc_del_mac_addr_msg(struct ice_vf *vf, u8 *msg) { return ice_vc_handle_mac_addr_msg(vf, msg, false); } /** * ice_vc_request_qs_msg * @vf: pointer to the VF info * @msg: pointer to the msg buffer * * VFs get a default number of queues but can use this message to request a * different number. If the request is successful, PF will reset the VF and * return 0. If unsuccessful, PF will send message informing VF of number of * available queue pairs via virtchnl message response to VF. */ static int ice_vc_request_qs_msg(struct ice_vf *vf, u8 *msg) { enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct virtchnl_vf_res_request *vfres = (struct virtchnl_vf_res_request *)msg; u16 req_queues = vfres->num_queue_pairs; struct ice_pf *pf = vf->pf; u16 max_allowed_vf_queues; u16 tx_rx_queue_left; struct device *dev; u16 cur_queues; dev = ice_pf_to_dev(pf); if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } cur_queues = vf->num_vf_qs; tx_rx_queue_left = min_t(u16, ice_get_avail_txq_count(pf), ice_get_avail_rxq_count(pf)); max_allowed_vf_queues = tx_rx_queue_left + cur_queues; if (!req_queues) { dev_err(dev, "VF %d tried to request 0 queues. Ignoring.\n", vf->vf_id); } else if (req_queues > ICE_MAX_RSS_QS_PER_VF) { dev_err(dev, "VF %d tried to request more than %d queues.\n", vf->vf_id, ICE_MAX_RSS_QS_PER_VF); vfres->num_queue_pairs = ICE_MAX_RSS_QS_PER_VF; } else if (req_queues > cur_queues && req_queues - cur_queues > tx_rx_queue_left) { dev_warn(dev, "VF %d requested %u more queues, but only %u left.\n", vf->vf_id, req_queues - cur_queues, tx_rx_queue_left); vfres->num_queue_pairs = min_t(u16, max_allowed_vf_queues, ICE_MAX_RSS_QS_PER_VF); } else { /* request is successful, then reset VF */ vf->num_req_qs = req_queues; ice_reset_vf(vf, ICE_VF_RESET_NOTIFY); dev_info(dev, "VF %d granted request of %u queues.\n", vf->vf_id, req_queues); return 0; } error_param: /* send the response to the VF */ return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_REQUEST_QUEUES, v_ret, (u8 *)vfres, sizeof(*vfres)); } /** * ice_vf_vlan_offload_ena - determine if capabilities support VLAN offloads * @caps: VF driver negotiated capabilities * * Return true if VIRTCHNL_VF_OFFLOAD_VLAN capability is set, else return false */ static bool ice_vf_vlan_offload_ena(u32 caps) { return !!(caps & VIRTCHNL_VF_OFFLOAD_VLAN); } /** * ice_is_vlan_promisc_allowed - check if VLAN promiscuous config is allowed * @vf: VF used to determine if VLAN promiscuous config is allowed */ static bool ice_is_vlan_promisc_allowed(struct ice_vf *vf) { if ((test_bit(ICE_VF_STATE_UC_PROMISC, vf->vf_states) || test_bit(ICE_VF_STATE_MC_PROMISC, vf->vf_states)) && test_bit(ICE_FLAG_VF_TRUE_PROMISC_ENA, vf->pf->flags)) return true; return false; } /** * ice_vf_ena_vlan_promisc - Enable Tx/Rx VLAN promiscuous for the VLAN * @vsi: VF's VSI used to enable VLAN promiscuous mode * @vlan: VLAN used to enable VLAN promiscuous * * This function should only be called if VLAN promiscuous mode is allowed, * which can be determined via ice_is_vlan_promisc_allowed(). */ static int ice_vf_ena_vlan_promisc(struct ice_vsi *vsi, struct ice_vlan *vlan) { u8 promisc_m = ICE_PROMISC_VLAN_TX | ICE_PROMISC_VLAN_RX; int status; status = ice_fltr_set_vsi_promisc(&vsi->back->hw, vsi->idx, promisc_m, vlan->vid); if (status && status != -EEXIST) return status; return 0; } /** * ice_vf_dis_vlan_promisc - Disable Tx/Rx VLAN promiscuous for the VLAN * @vsi: VF's VSI used to disable VLAN promiscuous mode for * @vlan: VLAN used to disable VLAN promiscuous * * This function should only be called if VLAN promiscuous mode is allowed, * which can be determined via ice_is_vlan_promisc_allowed(). */ static int ice_vf_dis_vlan_promisc(struct ice_vsi *vsi, struct ice_vlan *vlan) { u8 promisc_m = ICE_PROMISC_VLAN_TX | ICE_PROMISC_VLAN_RX; int status; status = ice_fltr_clear_vsi_promisc(&vsi->back->hw, vsi->idx, promisc_m, vlan->vid); if (status && status != -ENOENT) return status; return 0; } /** * ice_vf_has_max_vlans - check if VF already has the max allowed VLAN filters * @vf: VF to check against * @vsi: VF's VSI * * If the VF is trusted then the VF is allowed to add as many VLANs as it * wants to, so return false. * * When the VF is untrusted compare the number of non-zero VLANs + 1 to the max * allowed VLANs for an untrusted VF. Return the result of this comparison. */ static bool ice_vf_has_max_vlans(struct ice_vf *vf, struct ice_vsi *vsi) { if (ice_is_vf_trusted(vf)) return false; #define ICE_VF_ADDED_VLAN_ZERO_FLTRS 1 return ((ice_vsi_num_non_zero_vlans(vsi) + ICE_VF_ADDED_VLAN_ZERO_FLTRS) >= ICE_MAX_VLAN_PER_VF); } /** * ice_vc_process_vlan_msg * @vf: pointer to the VF info * @msg: pointer to the msg buffer * @add_v: Add VLAN if true, otherwise delete VLAN * * Process virtchnl op to add or remove programmed guest VLAN ID */ static int ice_vc_process_vlan_msg(struct ice_vf *vf, u8 *msg, bool add_v) { enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct virtchnl_vlan_filter_list *vfl = (struct virtchnl_vlan_filter_list *)msg; struct ice_pf *pf = vf->pf; bool vlan_promisc = false; struct ice_vsi *vsi; struct device *dev; int status = 0; int i; dev = ice_pf_to_dev(pf); if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (!ice_vf_vlan_offload_ena(vf->driver_caps)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (!ice_vc_isvalid_vsi_id(vf, vfl->vsi_id)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } for (i = 0; i < vfl->num_elements; i++) { if (vfl->vlan_id[i] >= VLAN_N_VID) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; dev_err(dev, "invalid VF VLAN id %d\n", vfl->vlan_id[i]); goto error_param; } } vsi = ice_get_vf_vsi(vf); if (!vsi) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (add_v && ice_vf_has_max_vlans(vf, vsi)) { dev_info(dev, "VF-%d is not trusted, switch the VF to trusted mode, in order to add more VLAN addresses\n", vf->vf_id); /* There is no need to let VF know about being not trusted, * so we can just return success message here */ goto error_param; } /* in DVM a VF can add/delete inner VLAN filters when * VIRTCHNL_VF_OFFLOAD_VLAN is negotiated, so only reject in SVM */ if (ice_vf_is_port_vlan_ena(vf) && !ice_is_dvm_ena(&pf->hw)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } /* in DVM VLAN promiscuous is based on the outer VLAN, which would be * the port VLAN if VIRTCHNL_VF_OFFLOAD_VLAN was negotiated, so only * allow vlan_promisc = true in SVM and if no port VLAN is configured */ vlan_promisc = ice_is_vlan_promisc_allowed(vf) && !ice_is_dvm_ena(&pf->hw) && !ice_vf_is_port_vlan_ena(vf); if (add_v) { for (i = 0; i < vfl->num_elements; i++) { u16 vid = vfl->vlan_id[i]; struct ice_vlan vlan; if (ice_vf_has_max_vlans(vf, vsi)) { dev_info(dev, "VF-%d is not trusted, switch the VF to trusted mode, in order to add more VLAN addresses\n", vf->vf_id); /* There is no need to let VF know about being * not trusted, so we can just return success * message here as well. */ goto error_param; } /* we add VLAN 0 by default for each VF so we can enable * Tx VLAN anti-spoof without triggering MDD events so * we don't need to add it again here */ if (!vid) continue; vlan = ICE_VLAN(ETH_P_8021Q, vid, 0); status = vsi->inner_vlan_ops.add_vlan(vsi, &vlan); if (status) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } /* Enable VLAN filtering on first non-zero VLAN */ if (!vlan_promisc && vid && !ice_is_dvm_ena(&pf->hw)) { if (vf->spoofchk) { status = vsi->inner_vlan_ops.ena_tx_filtering(vsi); if (status) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; dev_err(dev, "Enable VLAN anti-spoofing on VLAN ID: %d failed error-%d\n", vid, status); goto error_param; } } if (vsi->inner_vlan_ops.ena_rx_filtering(vsi)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; dev_err(dev, "Enable VLAN pruning on VLAN ID: %d failed error-%d\n", vid, status); goto error_param; } } else if (vlan_promisc) { status = ice_vf_ena_vlan_promisc(vsi, &vlan); if (status) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; dev_err(dev, "Enable Unicast/multicast promiscuous mode on VLAN ID:%d failed error-%d\n", vid, status); } } } } else { /* In case of non_trusted VF, number of VLAN elements passed * to PF for removal might be greater than number of VLANs * filter programmed for that VF - So, use actual number of * VLANS added earlier with add VLAN opcode. In order to avoid * removing VLAN that doesn't exist, which result to sending * erroneous failed message back to the VF */ int num_vf_vlan; num_vf_vlan = vsi->num_vlan; for (i = 0; i < vfl->num_elements && i < num_vf_vlan; i++) { u16 vid = vfl->vlan_id[i]; struct ice_vlan vlan; /* we add VLAN 0 by default for each VF so we can enable * Tx VLAN anti-spoof without triggering MDD events so * we don't want a VIRTCHNL request to remove it */ if (!vid) continue; vlan = ICE_VLAN(ETH_P_8021Q, vid, 0); status = vsi->inner_vlan_ops.del_vlan(vsi, &vlan); if (status) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } /* Disable VLAN filtering when only VLAN 0 is left */ if (!ice_vsi_has_non_zero_vlans(vsi)) { vsi->inner_vlan_ops.dis_tx_filtering(vsi); vsi->inner_vlan_ops.dis_rx_filtering(vsi); } if (vlan_promisc) ice_vf_dis_vlan_promisc(vsi, &vlan); } } error_param: /* send the response to the VF */ if (add_v) return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_ADD_VLAN, v_ret, NULL, 0); else return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_DEL_VLAN, v_ret, NULL, 0); } /** * ice_vc_add_vlan_msg * @vf: pointer to the VF info * @msg: pointer to the msg buffer * * Add and program guest VLAN ID */ static int ice_vc_add_vlan_msg(struct ice_vf *vf, u8 *msg) { return ice_vc_process_vlan_msg(vf, msg, true); } /** * ice_vc_remove_vlan_msg * @vf: pointer to the VF info * @msg: pointer to the msg buffer * * remove programmed guest VLAN ID */ static int ice_vc_remove_vlan_msg(struct ice_vf *vf, u8 *msg) { return ice_vc_process_vlan_msg(vf, msg, false); } /** * ice_vc_ena_vlan_stripping * @vf: pointer to the VF info * * Enable VLAN header stripping for a given VF */ static int ice_vc_ena_vlan_stripping(struct ice_vf *vf) { enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct ice_vsi *vsi; if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (!ice_vf_vlan_offload_ena(vf->driver_caps)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } vsi = ice_get_vf_vsi(vf); if (!vsi) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (vsi->inner_vlan_ops.ena_stripping(vsi, ETH_P_8021Q)) v_ret = VIRTCHNL_STATUS_ERR_PARAM; error_param: return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_ENABLE_VLAN_STRIPPING, v_ret, NULL, 0); } /** * ice_vc_dis_vlan_stripping * @vf: pointer to the VF info * * Disable VLAN header stripping for a given VF */ static int ice_vc_dis_vlan_stripping(struct ice_vf *vf) { enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct ice_vsi *vsi; if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (!ice_vf_vlan_offload_ena(vf->driver_caps)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } vsi = ice_get_vf_vsi(vf); if (!vsi) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto error_param; } if (vsi->inner_vlan_ops.dis_stripping(vsi)) v_ret = VIRTCHNL_STATUS_ERR_PARAM; error_param: return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_DISABLE_VLAN_STRIPPING, v_ret, NULL, 0); } /** * ice_vc_get_rss_hena - return the RSS HENA bits allowed by the hardware * @vf: pointer to the VF info */ static int ice_vc_get_rss_hena(struct ice_vf *vf) { enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct virtchnl_rss_hena *vrh = NULL; int len = 0, ret; if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto err; } if (!test_bit(ICE_FLAG_RSS_ENA, vf->pf->flags)) { dev_err(ice_pf_to_dev(vf->pf), "RSS not supported by PF\n"); v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto err; } len = sizeof(struct virtchnl_rss_hena); vrh = kzalloc(len, GFP_KERNEL); if (!vrh) { v_ret = VIRTCHNL_STATUS_ERR_NO_MEMORY; len = 0; goto err; } vrh->hena = ICE_DEFAULT_RSS_HENA; err: /* send the response back to the VF */ ret = ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_GET_RSS_HENA_CAPS, v_ret, (u8 *)vrh, len); kfree(vrh); return ret; } /** * ice_vc_set_rss_hena - set RSS HENA bits for the VF * @vf: pointer to the VF info * @msg: pointer to the msg buffer */ static int ice_vc_set_rss_hena(struct ice_vf *vf, u8 *msg) { struct virtchnl_rss_hena *vrh = (struct virtchnl_rss_hena *)msg; enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct ice_pf *pf = vf->pf; struct ice_vsi *vsi; struct device *dev; int status; dev = ice_pf_to_dev(pf); if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto err; } if (!test_bit(ICE_FLAG_RSS_ENA, pf->flags)) { dev_err(dev, "RSS not supported by PF\n"); v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto err; } vsi = ice_get_vf_vsi(vf); if (!vsi) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto err; } /* clear all previously programmed RSS configuration to allow VF drivers * the ability to customize the RSS configuration and/or completely * disable RSS */ status = ice_rem_vsi_rss_cfg(&pf->hw, vsi->idx); if (status && !vrh->hena) { /* only report failure to clear the current RSS configuration if * that was clearly the VF's intention (i.e. vrh->hena = 0) */ v_ret = ice_err_to_virt_err(status); goto err; } else if (status) { /* allow the VF to update the RSS configuration even on failure * to clear the current RSS confguration in an attempt to keep * RSS in a working state */ dev_warn(dev, "Failed to clear the RSS configuration for VF %u\n", vf->vf_id); } if (vrh->hena) { status = ice_add_avf_rss_cfg(&pf->hw, vsi->idx, vrh->hena); v_ret = ice_err_to_virt_err(status); } /* send the response to the VF */ err: return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_SET_RSS_HENA, v_ret, NULL, 0); } /** * ice_vc_query_rxdid - query RXDID supported by DDP package * @vf: pointer to VF info * * Called from VF to query a bitmap of supported flexible * descriptor RXDIDs of a DDP package. */ static int ice_vc_query_rxdid(struct ice_vf *vf) { enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct virtchnl_supported_rxdids *rxdid = NULL; struct ice_hw *hw = &vf->pf->hw; struct ice_pf *pf = vf->pf; int len = 0; int ret, i; u32 regval; if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto err; } if (!(vf->driver_caps & VIRTCHNL_VF_OFFLOAD_RX_FLEX_DESC)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto err; } len = sizeof(struct virtchnl_supported_rxdids); rxdid = kzalloc(len, GFP_KERNEL); if (!rxdid) { v_ret = VIRTCHNL_STATUS_ERR_NO_MEMORY; len = 0; goto err; } /* Read flexiflag registers to determine whether the * corresponding RXDID is configured and supported or not. * Since Legacy 16byte descriptor format is not supported, * start from Legacy 32byte descriptor. */ for (i = ICE_RXDID_LEGACY_1; i < ICE_FLEX_DESC_RXDID_MAX_NUM; i++) { regval = rd32(hw, GLFLXP_RXDID_FLAGS(i, 0)); if ((regval >> GLFLXP_RXDID_FLAGS_FLEXIFLAG_4N_S) & GLFLXP_RXDID_FLAGS_FLEXIFLAG_4N_M) rxdid->supported_rxdids |= BIT(i); } pf->supported_rxdids = rxdid->supported_rxdids; err: ret = ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_GET_SUPPORTED_RXDIDS, v_ret, (u8 *)rxdid, len); kfree(rxdid); return ret; } /** * ice_vf_init_vlan_stripping - enable/disable VLAN stripping on initialization * @vf: VF to enable/disable VLAN stripping for on initialization * * Set the default for VLAN stripping based on whether a port VLAN is configured * and the current VLAN mode of the device. */ static int ice_vf_init_vlan_stripping(struct ice_vf *vf) { struct ice_vsi *vsi = ice_get_vf_vsi(vf); if (!vsi) return -EINVAL; /* don't modify stripping if port VLAN is configured in SVM since the * port VLAN is based on the inner/single VLAN in SVM */ if (ice_vf_is_port_vlan_ena(vf) && !ice_is_dvm_ena(&vsi->back->hw)) return 0; if (ice_vf_vlan_offload_ena(vf->driver_caps)) return vsi->inner_vlan_ops.ena_stripping(vsi, ETH_P_8021Q); else return vsi->inner_vlan_ops.dis_stripping(vsi); } static u16 ice_vc_get_max_vlan_fltrs(struct ice_vf *vf) { if (vf->trusted) return VLAN_N_VID; else return ICE_MAX_VLAN_PER_VF; } /** * ice_vf_outer_vlan_not_allowed - check if outer VLAN can be used * @vf: VF that being checked for * * When the device is in double VLAN mode, check whether or not the outer VLAN * is allowed. */ static bool ice_vf_outer_vlan_not_allowed(struct ice_vf *vf) { if (ice_vf_is_port_vlan_ena(vf)) return true; return false; } /** * ice_vc_set_dvm_caps - set VLAN capabilities when the device is in DVM * @vf: VF that capabilities are being set for * @caps: VLAN capabilities to populate * * Determine VLAN capabilities support based on whether a port VLAN is * configured. If a port VLAN is configured then the VF should use the inner * filtering/offload capabilities since the port VLAN is using the outer VLAN * capabilies. */ static void ice_vc_set_dvm_caps(struct ice_vf *vf, struct virtchnl_vlan_caps *caps) { struct virtchnl_vlan_supported_caps *supported_caps; if (ice_vf_outer_vlan_not_allowed(vf)) { /* until support for inner VLAN filtering is added when a port * VLAN is configured, only support software offloaded inner * VLANs when a port VLAN is confgured in DVM */ supported_caps = &caps->filtering.filtering_support; supported_caps->inner = VIRTCHNL_VLAN_UNSUPPORTED; supported_caps = &caps->offloads.stripping_support; supported_caps->inner = VIRTCHNL_VLAN_ETHERTYPE_8100 | VIRTCHNL_VLAN_TOGGLE | VIRTCHNL_VLAN_TAG_LOCATION_L2TAG1; supported_caps->outer = VIRTCHNL_VLAN_UNSUPPORTED; supported_caps = &caps->offloads.insertion_support; supported_caps->inner = VIRTCHNL_VLAN_ETHERTYPE_8100 | VIRTCHNL_VLAN_TOGGLE | VIRTCHNL_VLAN_TAG_LOCATION_L2TAG1; supported_caps->outer = VIRTCHNL_VLAN_UNSUPPORTED; caps->offloads.ethertype_init = VIRTCHNL_VLAN_ETHERTYPE_8100; caps->offloads.ethertype_match = VIRTCHNL_ETHERTYPE_STRIPPING_MATCHES_INSERTION; } else { supported_caps = &caps->filtering.filtering_support; supported_caps->inner = VIRTCHNL_VLAN_UNSUPPORTED; supported_caps->outer = VIRTCHNL_VLAN_ETHERTYPE_8100 | VIRTCHNL_VLAN_ETHERTYPE_88A8 | VIRTCHNL_VLAN_ETHERTYPE_9100 | VIRTCHNL_VLAN_ETHERTYPE_AND; caps->filtering.ethertype_init = VIRTCHNL_VLAN_ETHERTYPE_8100 | VIRTCHNL_VLAN_ETHERTYPE_88A8 | VIRTCHNL_VLAN_ETHERTYPE_9100; supported_caps = &caps->offloads.stripping_support; supported_caps->inner = VIRTCHNL_VLAN_TOGGLE | VIRTCHNL_VLAN_ETHERTYPE_8100 | VIRTCHNL_VLAN_TAG_LOCATION_L2TAG1; supported_caps->outer = VIRTCHNL_VLAN_TOGGLE | VIRTCHNL_VLAN_ETHERTYPE_8100 | VIRTCHNL_VLAN_ETHERTYPE_88A8 | VIRTCHNL_VLAN_ETHERTYPE_9100 | VIRTCHNL_VLAN_ETHERTYPE_XOR | VIRTCHNL_VLAN_TAG_LOCATION_L2TAG2_2; supported_caps = &caps->offloads.insertion_support; supported_caps->inner = VIRTCHNL_VLAN_TOGGLE | VIRTCHNL_VLAN_ETHERTYPE_8100 | VIRTCHNL_VLAN_TAG_LOCATION_L2TAG1; supported_caps->outer = VIRTCHNL_VLAN_TOGGLE | VIRTCHNL_VLAN_ETHERTYPE_8100 | VIRTCHNL_VLAN_ETHERTYPE_88A8 | VIRTCHNL_VLAN_ETHERTYPE_9100 | VIRTCHNL_VLAN_ETHERTYPE_XOR | VIRTCHNL_VLAN_TAG_LOCATION_L2TAG2; caps->offloads.ethertype_init = VIRTCHNL_VLAN_ETHERTYPE_8100; caps->offloads.ethertype_match = VIRTCHNL_ETHERTYPE_STRIPPING_MATCHES_INSERTION; } caps->filtering.max_filters = ice_vc_get_max_vlan_fltrs(vf); } /** * ice_vc_set_svm_caps - set VLAN capabilities when the device is in SVM * @vf: VF that capabilities are being set for * @caps: VLAN capabilities to populate * * Determine VLAN capabilities support based on whether a port VLAN is * configured. If a port VLAN is configured then the VF does not have any VLAN * filtering or offload capabilities since the port VLAN is using the inner VLAN * capabilities in single VLAN mode (SVM). Otherwise allow the VF to use inner * VLAN fitlering and offload capabilities. */ static void ice_vc_set_svm_caps(struct ice_vf *vf, struct virtchnl_vlan_caps *caps) { struct virtchnl_vlan_supported_caps *supported_caps; if (ice_vf_is_port_vlan_ena(vf)) { supported_caps = &caps->filtering.filtering_support; supported_caps->inner = VIRTCHNL_VLAN_UNSUPPORTED; supported_caps->outer = VIRTCHNL_VLAN_UNSUPPORTED; supported_caps = &caps->offloads.stripping_support; supported_caps->inner = VIRTCHNL_VLAN_UNSUPPORTED; supported_caps->outer = VIRTCHNL_VLAN_UNSUPPORTED; supported_caps = &caps->offloads.insertion_support; supported_caps->inner = VIRTCHNL_VLAN_UNSUPPORTED; supported_caps->outer = VIRTCHNL_VLAN_UNSUPPORTED; caps->offloads.ethertype_init = VIRTCHNL_VLAN_UNSUPPORTED; caps->offloads.ethertype_match = VIRTCHNL_VLAN_UNSUPPORTED; caps->filtering.max_filters = 0; } else { supported_caps = &caps->filtering.filtering_support; supported_caps->inner = VIRTCHNL_VLAN_ETHERTYPE_8100; supported_caps->outer = VIRTCHNL_VLAN_UNSUPPORTED; caps->filtering.ethertype_init = VIRTCHNL_VLAN_ETHERTYPE_8100; supported_caps = &caps->offloads.stripping_support; supported_caps->inner = VIRTCHNL_VLAN_ETHERTYPE_8100 | VIRTCHNL_VLAN_TOGGLE | VIRTCHNL_VLAN_TAG_LOCATION_L2TAG1; supported_caps->outer = VIRTCHNL_VLAN_UNSUPPORTED; supported_caps = &caps->offloads.insertion_support; supported_caps->inner = VIRTCHNL_VLAN_ETHERTYPE_8100 | VIRTCHNL_VLAN_TOGGLE | VIRTCHNL_VLAN_TAG_LOCATION_L2TAG1; supported_caps->outer = VIRTCHNL_VLAN_UNSUPPORTED; caps->offloads.ethertype_init = VIRTCHNL_VLAN_ETHERTYPE_8100; caps->offloads.ethertype_match = VIRTCHNL_ETHERTYPE_STRIPPING_MATCHES_INSERTION; caps->filtering.max_filters = ice_vc_get_max_vlan_fltrs(vf); } } /** * ice_vc_get_offload_vlan_v2_caps - determine VF's VLAN capabilities * @vf: VF to determine VLAN capabilities for * * This will only be called if the VF and PF successfully negotiated * VIRTCHNL_VF_OFFLOAD_VLAN_V2. * * Set VLAN capabilities based on the current VLAN mode and whether a port VLAN * is configured or not. */ static int ice_vc_get_offload_vlan_v2_caps(struct ice_vf *vf) { enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct virtchnl_vlan_caps *caps = NULL; int err, len = 0; if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } caps = kzalloc(sizeof(*caps), GFP_KERNEL); if (!caps) { v_ret = VIRTCHNL_STATUS_ERR_NO_MEMORY; goto out; } len = sizeof(*caps); if (ice_is_dvm_ena(&vf->pf->hw)) ice_vc_set_dvm_caps(vf, caps); else ice_vc_set_svm_caps(vf, caps); /* store negotiated caps to prevent invalid VF messages */ memcpy(&vf->vlan_v2_caps, caps, sizeof(*caps)); out: err = ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_GET_OFFLOAD_VLAN_V2_CAPS, v_ret, (u8 *)caps, len); kfree(caps); return err; } /** * ice_vc_validate_vlan_tpid - validate VLAN TPID * @filtering_caps: negotiated/supported VLAN filtering capabilities * @tpid: VLAN TPID used for validation * * Convert the VLAN TPID to a VIRTCHNL_VLAN_ETHERTYPE_* and then compare against * the negotiated/supported filtering caps to see if the VLAN TPID is valid. */ static bool ice_vc_validate_vlan_tpid(u16 filtering_caps, u16 tpid) { enum virtchnl_vlan_support vlan_ethertype = VIRTCHNL_VLAN_UNSUPPORTED; switch (tpid) { case ETH_P_8021Q: vlan_ethertype = VIRTCHNL_VLAN_ETHERTYPE_8100; break; case ETH_P_8021AD: vlan_ethertype = VIRTCHNL_VLAN_ETHERTYPE_88A8; break; case ETH_P_QINQ1: vlan_ethertype = VIRTCHNL_VLAN_ETHERTYPE_9100; break; } if (!(filtering_caps & vlan_ethertype)) return false; return true; } /** * ice_vc_is_valid_vlan - validate the virtchnl_vlan * @vc_vlan: virtchnl_vlan to validate * * If the VLAN TCI and VLAN TPID are 0, then this filter is invalid, so return * false. Otherwise return true. */ static bool ice_vc_is_valid_vlan(struct virtchnl_vlan *vc_vlan) { if (!vc_vlan->tci || !vc_vlan->tpid) return false; return true; } /** * ice_vc_validate_vlan_filter_list - validate the filter list from the VF * @vfc: negotiated/supported VLAN filtering capabilities * @vfl: VLAN filter list from VF to validate * * Validate all of the filters in the VLAN filter list from the VF. If any of * the checks fail then return false. Otherwise return true. */ static bool ice_vc_validate_vlan_filter_list(struct virtchnl_vlan_filtering_caps *vfc, struct virtchnl_vlan_filter_list_v2 *vfl) { u16 i; if (!vfl->num_elements) return false; for (i = 0; i < vfl->num_elements; i++) { struct virtchnl_vlan_supported_caps *filtering_support = &vfc->filtering_support; struct virtchnl_vlan_filter *vlan_fltr = &vfl->filters[i]; struct virtchnl_vlan *outer = &vlan_fltr->outer; struct virtchnl_vlan *inner = &vlan_fltr->inner; if ((ice_vc_is_valid_vlan(outer) && filtering_support->outer == VIRTCHNL_VLAN_UNSUPPORTED) || (ice_vc_is_valid_vlan(inner) && filtering_support->inner == VIRTCHNL_VLAN_UNSUPPORTED)) return false; if ((outer->tci_mask && !(filtering_support->outer & VIRTCHNL_VLAN_FILTER_MASK)) || (inner->tci_mask && !(filtering_support->inner & VIRTCHNL_VLAN_FILTER_MASK))) return false; if (((outer->tci & VLAN_PRIO_MASK) && !(filtering_support->outer & VIRTCHNL_VLAN_PRIO)) || ((inner->tci & VLAN_PRIO_MASK) && !(filtering_support->inner & VIRTCHNL_VLAN_PRIO))) return false; if ((ice_vc_is_valid_vlan(outer) && !ice_vc_validate_vlan_tpid(filtering_support->outer, outer->tpid)) || (ice_vc_is_valid_vlan(inner) && !ice_vc_validate_vlan_tpid(filtering_support->inner, inner->tpid))) return false; } return true; } /** * ice_vc_to_vlan - transform from struct virtchnl_vlan to struct ice_vlan * @vc_vlan: struct virtchnl_vlan to transform */ static struct ice_vlan ice_vc_to_vlan(struct virtchnl_vlan *vc_vlan) { struct ice_vlan vlan = { 0 }; vlan.prio = (vc_vlan->tci & VLAN_PRIO_MASK) >> VLAN_PRIO_SHIFT; vlan.vid = vc_vlan->tci & VLAN_VID_MASK; vlan.tpid = vc_vlan->tpid; return vlan; } /** * ice_vc_vlan_action - action to perform on the virthcnl_vlan * @vsi: VF's VSI used to perform the action * @vlan_action: function to perform the action with (i.e. add/del) * @vlan: VLAN filter to perform the action with */ static int ice_vc_vlan_action(struct ice_vsi *vsi, int (*vlan_action)(struct ice_vsi *, struct ice_vlan *), struct ice_vlan *vlan) { int err; err = vlan_action(vsi, vlan); if (err) return err; return 0; } /** * ice_vc_del_vlans - delete VLAN(s) from the virtchnl filter list * @vf: VF used to delete the VLAN(s) * @vsi: VF's VSI used to delete the VLAN(s) * @vfl: virthchnl filter list used to delete the filters */ static int ice_vc_del_vlans(struct ice_vf *vf, struct ice_vsi *vsi, struct virtchnl_vlan_filter_list_v2 *vfl) { bool vlan_promisc = ice_is_vlan_promisc_allowed(vf); int err; u16 i; for (i = 0; i < vfl->num_elements; i++) { struct virtchnl_vlan_filter *vlan_fltr = &vfl->filters[i]; struct virtchnl_vlan *vc_vlan; vc_vlan = &vlan_fltr->outer; if (ice_vc_is_valid_vlan(vc_vlan)) { struct ice_vlan vlan = ice_vc_to_vlan(vc_vlan); err = ice_vc_vlan_action(vsi, vsi->outer_vlan_ops.del_vlan, &vlan); if (err) return err; if (vlan_promisc) ice_vf_dis_vlan_promisc(vsi, &vlan); /* Disable VLAN filtering when only VLAN 0 is left */ if (!ice_vsi_has_non_zero_vlans(vsi) && ice_is_dvm_ena(&vsi->back->hw)) { err = vsi->outer_vlan_ops.dis_tx_filtering(vsi); if (err) return err; } } vc_vlan = &vlan_fltr->inner; if (ice_vc_is_valid_vlan(vc_vlan)) { struct ice_vlan vlan = ice_vc_to_vlan(vc_vlan); err = ice_vc_vlan_action(vsi, vsi->inner_vlan_ops.del_vlan, &vlan); if (err) return err; /* no support for VLAN promiscuous on inner VLAN unless * we are in Single VLAN Mode (SVM) */ if (!ice_is_dvm_ena(&vsi->back->hw)) { if (vlan_promisc) ice_vf_dis_vlan_promisc(vsi, &vlan); /* Disable VLAN filtering when only VLAN 0 is left */ if (!ice_vsi_has_non_zero_vlans(vsi)) { err = vsi->inner_vlan_ops.dis_tx_filtering(vsi); if (err) return err; } } } } return 0; } /** * ice_vc_remove_vlan_v2_msg - virtchnl handler for VIRTCHNL_OP_DEL_VLAN_V2 * @vf: VF the message was received from * @msg: message received from the VF */ static int ice_vc_remove_vlan_v2_msg(struct ice_vf *vf, u8 *msg) { struct virtchnl_vlan_filter_list_v2 *vfl = (struct virtchnl_vlan_filter_list_v2 *)msg; enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct ice_vsi *vsi; if (!ice_vc_validate_vlan_filter_list(&vf->vlan_v2_caps.filtering, vfl)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } if (!ice_vc_isvalid_vsi_id(vf, vfl->vport_id)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } vsi = ice_get_vf_vsi(vf); if (!vsi) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } if (ice_vc_del_vlans(vf, vsi, vfl)) v_ret = VIRTCHNL_STATUS_ERR_PARAM; out: return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_DEL_VLAN_V2, v_ret, NULL, 0); } /** * ice_vc_add_vlans - add VLAN(s) from the virtchnl filter list * @vf: VF used to add the VLAN(s) * @vsi: VF's VSI used to add the VLAN(s) * @vfl: virthchnl filter list used to add the filters */ static int ice_vc_add_vlans(struct ice_vf *vf, struct ice_vsi *vsi, struct virtchnl_vlan_filter_list_v2 *vfl) { bool vlan_promisc = ice_is_vlan_promisc_allowed(vf); int err; u16 i; for (i = 0; i < vfl->num_elements; i++) { struct virtchnl_vlan_filter *vlan_fltr = &vfl->filters[i]; struct virtchnl_vlan *vc_vlan; vc_vlan = &vlan_fltr->outer; if (ice_vc_is_valid_vlan(vc_vlan)) { struct ice_vlan vlan = ice_vc_to_vlan(vc_vlan); err = ice_vc_vlan_action(vsi, vsi->outer_vlan_ops.add_vlan, &vlan); if (err) return err; if (vlan_promisc) { err = ice_vf_ena_vlan_promisc(vsi, &vlan); if (err) return err; } /* Enable VLAN filtering on first non-zero VLAN */ if (vf->spoofchk && vlan.vid && ice_is_dvm_ena(&vsi->back->hw)) { err = vsi->outer_vlan_ops.ena_tx_filtering(vsi); if (err) return err; } } vc_vlan = &vlan_fltr->inner; if (ice_vc_is_valid_vlan(vc_vlan)) { struct ice_vlan vlan = ice_vc_to_vlan(vc_vlan); err = ice_vc_vlan_action(vsi, vsi->inner_vlan_ops.add_vlan, &vlan); if (err) return err; /* no support for VLAN promiscuous on inner VLAN unless * we are in Single VLAN Mode (SVM) */ if (!ice_is_dvm_ena(&vsi->back->hw)) { if (vlan_promisc) { err = ice_vf_ena_vlan_promisc(vsi, &vlan); if (err) return err; } /* Enable VLAN filtering on first non-zero VLAN */ if (vf->spoofchk && vlan.vid) { err = vsi->inner_vlan_ops.ena_tx_filtering(vsi); if (err) return err; } } } } return 0; } /** * ice_vc_validate_add_vlan_filter_list - validate add filter list from the VF * @vsi: VF VSI used to get number of existing VLAN filters * @vfc: negotiated/supported VLAN filtering capabilities * @vfl: VLAN filter list from VF to validate * * Validate all of the filters in the VLAN filter list from the VF during the * VIRTCHNL_OP_ADD_VLAN_V2 opcode. If any of the checks fail then return false. * Otherwise return true. */ static bool ice_vc_validate_add_vlan_filter_list(struct ice_vsi *vsi, struct virtchnl_vlan_filtering_caps *vfc, struct virtchnl_vlan_filter_list_v2 *vfl) { u16 num_requested_filters = ice_vsi_num_non_zero_vlans(vsi) + vfl->num_elements; if (num_requested_filters > vfc->max_filters) return false; return ice_vc_validate_vlan_filter_list(vfc, vfl); } /** * ice_vc_add_vlan_v2_msg - virtchnl handler for VIRTCHNL_OP_ADD_VLAN_V2 * @vf: VF the message was received from * @msg: message received from the VF */ static int ice_vc_add_vlan_v2_msg(struct ice_vf *vf, u8 *msg) { enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct virtchnl_vlan_filter_list_v2 *vfl = (struct virtchnl_vlan_filter_list_v2 *)msg; struct ice_vsi *vsi; if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } if (!ice_vc_isvalid_vsi_id(vf, vfl->vport_id)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } vsi = ice_get_vf_vsi(vf); if (!vsi) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } if (!ice_vc_validate_add_vlan_filter_list(vsi, &vf->vlan_v2_caps.filtering, vfl)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } if (ice_vc_add_vlans(vf, vsi, vfl)) v_ret = VIRTCHNL_STATUS_ERR_PARAM; out: return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_ADD_VLAN_V2, v_ret, NULL, 0); } /** * ice_vc_valid_vlan_setting - validate VLAN setting * @negotiated_settings: negotiated VLAN settings during VF init * @ethertype_setting: ethertype(s) requested for the VLAN setting */ static bool ice_vc_valid_vlan_setting(u32 negotiated_settings, u32 ethertype_setting) { if (ethertype_setting && !(negotiated_settings & ethertype_setting)) return false; /* only allow a single VIRTCHNL_VLAN_ETHERTYPE if * VIRTHCNL_VLAN_ETHERTYPE_AND is not negotiated/supported */ if (!(negotiated_settings & VIRTCHNL_VLAN_ETHERTYPE_AND) && hweight32(ethertype_setting) > 1) return false; /* ability to modify the VLAN setting was not negotiated */ if (!(negotiated_settings & VIRTCHNL_VLAN_TOGGLE)) return false; return true; } /** * ice_vc_valid_vlan_setting_msg - validate the VLAN setting message * @caps: negotiated VLAN settings during VF init * @msg: message to validate * * Used to validate any VLAN virtchnl message sent as a * virtchnl_vlan_setting structure. Validates the message against the * negotiated/supported caps during VF driver init. */ static bool ice_vc_valid_vlan_setting_msg(struct virtchnl_vlan_supported_caps *caps, struct virtchnl_vlan_setting *msg) { if ((!msg->outer_ethertype_setting && !msg->inner_ethertype_setting) || (!caps->outer && !caps->inner)) return false; if (msg->outer_ethertype_setting && !ice_vc_valid_vlan_setting(caps->outer, msg->outer_ethertype_setting)) return false; if (msg->inner_ethertype_setting && !ice_vc_valid_vlan_setting(caps->inner, msg->inner_ethertype_setting)) return false; return true; } /** * ice_vc_get_tpid - transform from VIRTCHNL_VLAN_ETHERTYPE_* to VLAN TPID * @ethertype_setting: VIRTCHNL_VLAN_ETHERTYPE_* used to get VLAN TPID * @tpid: VLAN TPID to populate */ static int ice_vc_get_tpid(u32 ethertype_setting, u16 *tpid) { switch (ethertype_setting) { case VIRTCHNL_VLAN_ETHERTYPE_8100: *tpid = ETH_P_8021Q; break; case VIRTCHNL_VLAN_ETHERTYPE_88A8: *tpid = ETH_P_8021AD; break; case VIRTCHNL_VLAN_ETHERTYPE_9100: *tpid = ETH_P_QINQ1; break; default: *tpid = 0; return -EINVAL; } return 0; } /** * ice_vc_ena_vlan_offload - enable VLAN offload based on the ethertype_setting * @vsi: VF's VSI used to enable the VLAN offload * @ena_offload: function used to enable the VLAN offload * @ethertype_setting: VIRTCHNL_VLAN_ETHERTYPE_* to enable offloads for */ static int ice_vc_ena_vlan_offload(struct ice_vsi *vsi, int (*ena_offload)(struct ice_vsi *vsi, u16 tpid), u32 ethertype_setting) { u16 tpid; int err; err = ice_vc_get_tpid(ethertype_setting, &tpid); if (err) return err; err = ena_offload(vsi, tpid); if (err) return err; return 0; } #define ICE_L2TSEL_QRX_CONTEXT_REG_IDX 3 #define ICE_L2TSEL_BIT_OFFSET 23 enum ice_l2tsel { ICE_L2TSEL_EXTRACT_FIRST_TAG_L2TAG2_2ND, ICE_L2TSEL_EXTRACT_FIRST_TAG_L2TAG1, }; /** * ice_vsi_update_l2tsel - update l2tsel field for all Rx rings on this VSI * @vsi: VSI used to update l2tsel on * @l2tsel: l2tsel setting requested * * Use the l2tsel setting to update all of the Rx queue context bits for l2tsel. * This will modify which descriptor field the first offloaded VLAN will be * stripped into. */ static void ice_vsi_update_l2tsel(struct ice_vsi *vsi, enum ice_l2tsel l2tsel) { struct ice_hw *hw = &vsi->back->hw; u32 l2tsel_bit; int i; if (l2tsel == ICE_L2TSEL_EXTRACT_FIRST_TAG_L2TAG2_2ND) l2tsel_bit = 0; else l2tsel_bit = BIT(ICE_L2TSEL_BIT_OFFSET); for (i = 0; i < vsi->alloc_rxq; i++) { u16 pfq = vsi->rxq_map[i]; u32 qrx_context_offset; u32 regval; qrx_context_offset = QRX_CONTEXT(ICE_L2TSEL_QRX_CONTEXT_REG_IDX, pfq); regval = rd32(hw, qrx_context_offset); regval &= ~BIT(ICE_L2TSEL_BIT_OFFSET); regval |= l2tsel_bit; wr32(hw, qrx_context_offset, regval); } } /** * ice_vc_ena_vlan_stripping_v2_msg * @vf: VF the message was received from * @msg: message received from the VF * * virthcnl handler for VIRTCHNL_OP_ENABLE_VLAN_STRIPPING_V2 */ static int ice_vc_ena_vlan_stripping_v2_msg(struct ice_vf *vf, u8 *msg) { enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct virtchnl_vlan_supported_caps *stripping_support; struct virtchnl_vlan_setting *strip_msg = (struct virtchnl_vlan_setting *)msg; u32 ethertype_setting; struct ice_vsi *vsi; if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } if (!ice_vc_isvalid_vsi_id(vf, strip_msg->vport_id)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } vsi = ice_get_vf_vsi(vf); if (!vsi) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } stripping_support = &vf->vlan_v2_caps.offloads.stripping_support; if (!ice_vc_valid_vlan_setting_msg(stripping_support, strip_msg)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } ethertype_setting = strip_msg->outer_ethertype_setting; if (ethertype_setting) { if (ice_vc_ena_vlan_offload(vsi, vsi->outer_vlan_ops.ena_stripping, ethertype_setting)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } else { enum ice_l2tsel l2tsel = ICE_L2TSEL_EXTRACT_FIRST_TAG_L2TAG2_2ND; /* PF tells the VF that the outer VLAN tag is always * extracted to VIRTCHNL_VLAN_TAG_LOCATION_L2TAG2_2 and * inner is always extracted to * VIRTCHNL_VLAN_TAG_LOCATION_L2TAG1. This is needed to * support outer stripping so the first tag always ends * up in L2TAG2_2ND and the second/inner tag, if * enabled, is extracted in L2TAG1. */ ice_vsi_update_l2tsel(vsi, l2tsel); } } ethertype_setting = strip_msg->inner_ethertype_setting; if (ethertype_setting && ice_vc_ena_vlan_offload(vsi, vsi->inner_vlan_ops.ena_stripping, ethertype_setting)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } out: return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_ENABLE_VLAN_STRIPPING_V2, v_ret, NULL, 0); } /** * ice_vc_dis_vlan_stripping_v2_msg * @vf: VF the message was received from * @msg: message received from the VF * * virthcnl handler for VIRTCHNL_OP_DISABLE_VLAN_STRIPPING_V2 */ static int ice_vc_dis_vlan_stripping_v2_msg(struct ice_vf *vf, u8 *msg) { enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct virtchnl_vlan_supported_caps *stripping_support; struct virtchnl_vlan_setting *strip_msg = (struct virtchnl_vlan_setting *)msg; u32 ethertype_setting; struct ice_vsi *vsi; if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } if (!ice_vc_isvalid_vsi_id(vf, strip_msg->vport_id)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } vsi = ice_get_vf_vsi(vf); if (!vsi) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } stripping_support = &vf->vlan_v2_caps.offloads.stripping_support; if (!ice_vc_valid_vlan_setting_msg(stripping_support, strip_msg)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } ethertype_setting = strip_msg->outer_ethertype_setting; if (ethertype_setting) { if (vsi->outer_vlan_ops.dis_stripping(vsi)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } else { enum ice_l2tsel l2tsel = ICE_L2TSEL_EXTRACT_FIRST_TAG_L2TAG1; /* PF tells the VF that the outer VLAN tag is always * extracted to VIRTCHNL_VLAN_TAG_LOCATION_L2TAG2_2 and * inner is always extracted to * VIRTCHNL_VLAN_TAG_LOCATION_L2TAG1. This is needed to * support inner stripping while outer stripping is * disabled so that the first and only tag is extracted * in L2TAG1. */ ice_vsi_update_l2tsel(vsi, l2tsel); } } ethertype_setting = strip_msg->inner_ethertype_setting; if (ethertype_setting && vsi->inner_vlan_ops.dis_stripping(vsi)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } out: return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_DISABLE_VLAN_STRIPPING_V2, v_ret, NULL, 0); } /** * ice_vc_ena_vlan_insertion_v2_msg * @vf: VF the message was received from * @msg: message received from the VF * * virthcnl handler for VIRTCHNL_OP_ENABLE_VLAN_INSERTION_V2 */ static int ice_vc_ena_vlan_insertion_v2_msg(struct ice_vf *vf, u8 *msg) { enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct virtchnl_vlan_supported_caps *insertion_support; struct virtchnl_vlan_setting *insertion_msg = (struct virtchnl_vlan_setting *)msg; u32 ethertype_setting; struct ice_vsi *vsi; if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } if (!ice_vc_isvalid_vsi_id(vf, insertion_msg->vport_id)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } vsi = ice_get_vf_vsi(vf); if (!vsi) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } insertion_support = &vf->vlan_v2_caps.offloads.insertion_support; if (!ice_vc_valid_vlan_setting_msg(insertion_support, insertion_msg)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } ethertype_setting = insertion_msg->outer_ethertype_setting; if (ethertype_setting && ice_vc_ena_vlan_offload(vsi, vsi->outer_vlan_ops.ena_insertion, ethertype_setting)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } ethertype_setting = insertion_msg->inner_ethertype_setting; if (ethertype_setting && ice_vc_ena_vlan_offload(vsi, vsi->inner_vlan_ops.ena_insertion, ethertype_setting)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } out: return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_ENABLE_VLAN_INSERTION_V2, v_ret, NULL, 0); } /** * ice_vc_dis_vlan_insertion_v2_msg * @vf: VF the message was received from * @msg: message received from the VF * * virthcnl handler for VIRTCHNL_OP_DISABLE_VLAN_INSERTION_V2 */ static int ice_vc_dis_vlan_insertion_v2_msg(struct ice_vf *vf, u8 *msg) { enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct virtchnl_vlan_supported_caps *insertion_support; struct virtchnl_vlan_setting *insertion_msg = (struct virtchnl_vlan_setting *)msg; u32 ethertype_setting; struct ice_vsi *vsi; if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } if (!ice_vc_isvalid_vsi_id(vf, insertion_msg->vport_id)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } vsi = ice_get_vf_vsi(vf); if (!vsi) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } insertion_support = &vf->vlan_v2_caps.offloads.insertion_support; if (!ice_vc_valid_vlan_setting_msg(insertion_support, insertion_msg)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } ethertype_setting = insertion_msg->outer_ethertype_setting; if (ethertype_setting && vsi->outer_vlan_ops.dis_insertion(vsi)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } ethertype_setting = insertion_msg->inner_ethertype_setting; if (ethertype_setting && vsi->inner_vlan_ops.dis_insertion(vsi)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto out; } out: return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_DISABLE_VLAN_INSERTION_V2, v_ret, NULL, 0); } static const struct ice_virtchnl_ops ice_virtchnl_dflt_ops = { .get_ver_msg = ice_vc_get_ver_msg, .get_vf_res_msg = ice_vc_get_vf_res_msg, .reset_vf = ice_vc_reset_vf_msg, .add_mac_addr_msg = ice_vc_add_mac_addr_msg, .del_mac_addr_msg = ice_vc_del_mac_addr_msg, .cfg_qs_msg = ice_vc_cfg_qs_msg, .ena_qs_msg = ice_vc_ena_qs_msg, .dis_qs_msg = ice_vc_dis_qs_msg, .request_qs_msg = ice_vc_request_qs_msg, .cfg_irq_map_msg = ice_vc_cfg_irq_map_msg, .config_rss_key = ice_vc_config_rss_key, .config_rss_lut = ice_vc_config_rss_lut, .get_stats_msg = ice_vc_get_stats_msg, .cfg_promiscuous_mode_msg = ice_vc_cfg_promiscuous_mode_msg, .add_vlan_msg = ice_vc_add_vlan_msg, .remove_vlan_msg = ice_vc_remove_vlan_msg, .query_rxdid = ice_vc_query_rxdid, .get_rss_hena = ice_vc_get_rss_hena, .set_rss_hena_msg = ice_vc_set_rss_hena, .ena_vlan_stripping = ice_vc_ena_vlan_stripping, .dis_vlan_stripping = ice_vc_dis_vlan_stripping, .handle_rss_cfg_msg = ice_vc_handle_rss_cfg, .add_fdir_fltr_msg = ice_vc_add_fdir_fltr, .del_fdir_fltr_msg = ice_vc_del_fdir_fltr, .get_offload_vlan_v2_caps = ice_vc_get_offload_vlan_v2_caps, .add_vlan_v2_msg = ice_vc_add_vlan_v2_msg, .remove_vlan_v2_msg = ice_vc_remove_vlan_v2_msg, .ena_vlan_stripping_v2_msg = ice_vc_ena_vlan_stripping_v2_msg, .dis_vlan_stripping_v2_msg = ice_vc_dis_vlan_stripping_v2_msg, .ena_vlan_insertion_v2_msg = ice_vc_ena_vlan_insertion_v2_msg, .dis_vlan_insertion_v2_msg = ice_vc_dis_vlan_insertion_v2_msg, }; /** * ice_virtchnl_set_dflt_ops - Switch to default virtchnl ops * @vf: the VF to switch ops */ void ice_virtchnl_set_dflt_ops(struct ice_vf *vf) { vf->virtchnl_ops = &ice_virtchnl_dflt_ops; } /** * ice_vc_repr_add_mac * @vf: pointer to VF * @msg: virtchannel message * * When port representors are created, we do not add MAC rule * to firmware, we store it so that PF could report same * MAC as VF. */ static int ice_vc_repr_add_mac(struct ice_vf *vf, u8 *msg) { enum virtchnl_status_code v_ret = VIRTCHNL_STATUS_SUCCESS; struct virtchnl_ether_addr_list *al = (struct virtchnl_ether_addr_list *)msg; struct ice_vsi *vsi; struct ice_pf *pf; int i; if (!test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states) || !ice_vc_isvalid_vsi_id(vf, al->vsi_id)) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto handle_mac_exit; } pf = vf->pf; vsi = ice_get_vf_vsi(vf); if (!vsi) { v_ret = VIRTCHNL_STATUS_ERR_PARAM; goto handle_mac_exit; } for (i = 0; i < al->num_elements; i++) { u8 *mac_addr = al->list[i].addr; if (!is_unicast_ether_addr(mac_addr) || ether_addr_equal(mac_addr, vf->hw_lan_addr)) continue; if (vf->pf_set_mac) { dev_err(ice_pf_to_dev(pf), "VF attempting to override administratively set MAC address\n"); v_ret = VIRTCHNL_STATUS_ERR_NOT_SUPPORTED; goto handle_mac_exit; } ice_vfhw_mac_add(vf, &al->list[i]); vf->num_mac++; break; } handle_mac_exit: return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_ADD_ETH_ADDR, v_ret, NULL, 0); } /** * ice_vc_repr_del_mac - response with success for deleting MAC * @vf: pointer to VF * @msg: virtchannel message * * Respond with success to not break normal VF flow. * For legacy VF driver try to update cached MAC address. */ static int ice_vc_repr_del_mac(struct ice_vf __always_unused *vf, u8 __always_unused *msg) { struct virtchnl_ether_addr_list *al = (struct virtchnl_ether_addr_list *)msg; ice_update_legacy_cached_mac(vf, &al->list[0]); return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_DEL_ETH_ADDR, VIRTCHNL_STATUS_SUCCESS, NULL, 0); } static int ice_vc_repr_cfg_promiscuous_mode(struct ice_vf *vf, u8 __always_unused *msg) { dev_dbg(ice_pf_to_dev(vf->pf), "Can't config promiscuous mode in switchdev mode for VF %d\n", vf->vf_id); return ice_vc_send_msg_to_vf(vf, VIRTCHNL_OP_CONFIG_PROMISCUOUS_MODE, VIRTCHNL_STATUS_ERR_NOT_SUPPORTED, NULL, 0); } static const struct ice_virtchnl_ops ice_virtchnl_repr_ops = { .get_ver_msg = ice_vc_get_ver_msg, .get_vf_res_msg = ice_vc_get_vf_res_msg, .reset_vf = ice_vc_reset_vf_msg, .add_mac_addr_msg = ice_vc_repr_add_mac, .del_mac_addr_msg = ice_vc_repr_del_mac, .cfg_qs_msg = ice_vc_cfg_qs_msg, .ena_qs_msg = ice_vc_ena_qs_msg, .dis_qs_msg = ice_vc_dis_qs_msg, .request_qs_msg = ice_vc_request_qs_msg, .cfg_irq_map_msg = ice_vc_cfg_irq_map_msg, .config_rss_key = ice_vc_config_rss_key, .config_rss_lut = ice_vc_config_rss_lut, .get_stats_msg = ice_vc_get_stats_msg, .cfg_promiscuous_mode_msg = ice_vc_repr_cfg_promiscuous_mode, .add_vlan_msg = ice_vc_add_vlan_msg, .remove_vlan_msg = ice_vc_remove_vlan_msg, .query_rxdid = ice_vc_query_rxdid, .get_rss_hena = ice_vc_get_rss_hena, .set_rss_hena_msg = ice_vc_set_rss_hena, .ena_vlan_stripping = ice_vc_ena_vlan_stripping, .dis_vlan_stripping = ice_vc_dis_vlan_stripping, .handle_rss_cfg_msg = ice_vc_handle_rss_cfg, .add_fdir_fltr_msg = ice_vc_add_fdir_fltr, .del_fdir_fltr_msg = ice_vc_del_fdir_fltr, .get_offload_vlan_v2_caps = ice_vc_get_offload_vlan_v2_caps, .add_vlan_v2_msg = ice_vc_add_vlan_v2_msg, .remove_vlan_v2_msg = ice_vc_remove_vlan_v2_msg, .ena_vlan_stripping_v2_msg = ice_vc_ena_vlan_stripping_v2_msg, .dis_vlan_stripping_v2_msg = ice_vc_dis_vlan_stripping_v2_msg, .ena_vlan_insertion_v2_msg = ice_vc_ena_vlan_insertion_v2_msg, .dis_vlan_insertion_v2_msg = ice_vc_dis_vlan_insertion_v2_msg, }; /** * ice_virtchnl_set_repr_ops - Switch to representor virtchnl ops * @vf: the VF to switch ops */ void ice_virtchnl_set_repr_ops(struct ice_vf *vf) { vf->virtchnl_ops = &ice_virtchnl_repr_ops; } /** * ice_is_malicious_vf - check if this vf might be overflowing mailbox * @vf: the VF to check * @mbxdata: data about the state of the mailbox * * Detect if a given VF might be malicious and attempting to overflow the PF * mailbox. If so, log a warning message and ignore this event. */ static bool ice_is_malicious_vf(struct ice_vf *vf, struct ice_mbx_data *mbxdata) { bool report_malvf = false; struct device *dev; struct ice_pf *pf; int status; pf = vf->pf; dev = ice_pf_to_dev(pf); if (test_bit(ICE_VF_STATE_DIS, vf->vf_states)) return vf->mbx_info.malicious; /* check to see if we have a newly malicious VF */ status = ice_mbx_vf_state_handler(&pf->hw, mbxdata, &vf->mbx_info, &report_malvf); if (status) dev_warn_ratelimited(dev, "Unable to check status of mailbox overflow for VF %u MAC %pM, status %d\n", vf->vf_id, vf->dev_lan_addr, status); if (report_malvf) { struct ice_vsi *pf_vsi = ice_get_main_vsi(pf); u8 zero_addr[ETH_ALEN] = {}; dev_warn(dev, "VF MAC %pM on PF MAC %pM is generating asynchronous messages and may be overflowing the PF message queue. Please see the Adapter User Guide for more information\n", vf->dev_lan_addr, pf_vsi ? pf_vsi->netdev->dev_addr : zero_addr); } return vf->mbx_info.malicious; } /** * ice_vc_process_vf_msg - Process request from VF * @pf: pointer to the PF structure * @event: pointer to the AQ event * @mbxdata: information used to detect VF attempting mailbox overflow * * called from the common asq/arq handler to * process request from VF */ void ice_vc_process_vf_msg(struct ice_pf *pf, struct ice_rq_event_info *event, struct ice_mbx_data *mbxdata) { u32 v_opcode = le32_to_cpu(event->desc.cookie_high); s16 vf_id = le16_to_cpu(event->desc.retval); const struct ice_virtchnl_ops *ops; u16 msglen = event->msg_len; u8 *msg = event->msg_buf; struct ice_vf *vf = NULL; struct device *dev; int err = 0; dev = ice_pf_to_dev(pf); vf = ice_get_vf_by_id(pf, vf_id); if (!vf) { dev_err(dev, "Unable to locate VF for message from VF ID %d, opcode %d, len %d\n", vf_id, v_opcode, msglen); return; } mutex_lock(&vf->cfg_lock); /* Check if the VF is trying to overflow the mailbox */ if (ice_is_malicious_vf(vf, mbxdata)) goto finish; /* Check if VF is disabled. */ if (test_bit(ICE_VF_STATE_DIS, vf->vf_states)) { err = -EPERM; goto error_handler; } ops = vf->virtchnl_ops; /* Perform basic checks on the msg */ err = virtchnl_vc_validate_vf_msg(&vf->vf_ver, v_opcode, msg, msglen); if (err) { if (err == VIRTCHNL_STATUS_ERR_PARAM) err = -EPERM; else err = -EINVAL; } error_handler: if (err) { ice_vc_send_msg_to_vf(vf, v_opcode, VIRTCHNL_STATUS_ERR_PARAM, NULL, 0); dev_err(dev, "Invalid message from VF %d, opcode %d, len %d, error %d\n", vf_id, v_opcode, msglen, err); goto finish; } if (!ice_vc_is_opcode_allowed(vf, v_opcode)) { ice_vc_send_msg_to_vf(vf, v_opcode, VIRTCHNL_STATUS_ERR_NOT_SUPPORTED, NULL, 0); goto finish; } switch (v_opcode) { case VIRTCHNL_OP_VERSION: err = ops->get_ver_msg(vf, msg); break; case VIRTCHNL_OP_GET_VF_RESOURCES: err = ops->get_vf_res_msg(vf, msg); if (ice_vf_init_vlan_stripping(vf)) dev_dbg(dev, "Failed to initialize VLAN stripping for VF %d\n", vf->vf_id); ice_vc_notify_vf_link_state(vf); break; case VIRTCHNL_OP_RESET_VF: ops->reset_vf(vf); break; case VIRTCHNL_OP_ADD_ETH_ADDR: err = ops->add_mac_addr_msg(vf, msg); break; case VIRTCHNL_OP_DEL_ETH_ADDR: err = ops->del_mac_addr_msg(vf, msg); break; case VIRTCHNL_OP_CONFIG_VSI_QUEUES: err = ops->cfg_qs_msg(vf, msg); break; case VIRTCHNL_OP_ENABLE_QUEUES: err = ops->ena_qs_msg(vf, msg); ice_vc_notify_vf_link_state(vf); break; case VIRTCHNL_OP_DISABLE_QUEUES: err = ops->dis_qs_msg(vf, msg); break; case VIRTCHNL_OP_REQUEST_QUEUES: err = ops->request_qs_msg(vf, msg); break; case VIRTCHNL_OP_CONFIG_IRQ_MAP: err = ops->cfg_irq_map_msg(vf, msg); break; case VIRTCHNL_OP_CONFIG_RSS_KEY: err = ops->config_rss_key(vf, msg); break; case VIRTCHNL_OP_CONFIG_RSS_LUT: err = ops->config_rss_lut(vf, msg); break; case VIRTCHNL_OP_GET_STATS: err = ops->get_stats_msg(vf, msg); break; case VIRTCHNL_OP_CONFIG_PROMISCUOUS_MODE: err = ops->cfg_promiscuous_mode_msg(vf, msg); break; case VIRTCHNL_OP_ADD_VLAN: err = ops->add_vlan_msg(vf, msg); break; case VIRTCHNL_OP_DEL_VLAN: err = ops->remove_vlan_msg(vf, msg); break; case VIRTCHNL_OP_GET_SUPPORTED_RXDIDS: err = ops->query_rxdid(vf); break; case VIRTCHNL_OP_GET_RSS_HENA_CAPS: err = ops->get_rss_hena(vf); break; case VIRTCHNL_OP_SET_RSS_HENA: err = ops->set_rss_hena_msg(vf, msg); break; case VIRTCHNL_OP_ENABLE_VLAN_STRIPPING: err = ops->ena_vlan_stripping(vf); break; case VIRTCHNL_OP_DISABLE_VLAN_STRIPPING: err = ops->dis_vlan_stripping(vf); break; case VIRTCHNL_OP_ADD_FDIR_FILTER: err = ops->add_fdir_fltr_msg(vf, msg); break; case VIRTCHNL_OP_DEL_FDIR_FILTER: err = ops->del_fdir_fltr_msg(vf, msg); break; case VIRTCHNL_OP_ADD_RSS_CFG: err = ops->handle_rss_cfg_msg(vf, msg, true); break; case VIRTCHNL_OP_DEL_RSS_CFG: err = ops->handle_rss_cfg_msg(vf, msg, false); break; case VIRTCHNL_OP_GET_OFFLOAD_VLAN_V2_CAPS: err = ops->get_offload_vlan_v2_caps(vf); break; case VIRTCHNL_OP_ADD_VLAN_V2: err = ops->add_vlan_v2_msg(vf, msg); break; case VIRTCHNL_OP_DEL_VLAN_V2: err = ops->remove_vlan_v2_msg(vf, msg); break; case VIRTCHNL_OP_ENABLE_VLAN_STRIPPING_V2: err = ops->ena_vlan_stripping_v2_msg(vf, msg); break; case VIRTCHNL_OP_DISABLE_VLAN_STRIPPING_V2: err = ops->dis_vlan_stripping_v2_msg(vf, msg); break; case VIRTCHNL_OP_ENABLE_VLAN_INSERTION_V2: err = ops->ena_vlan_insertion_v2_msg(vf, msg); break; case VIRTCHNL_OP_DISABLE_VLAN_INSERTION_V2: err = ops->dis_vlan_insertion_v2_msg(vf, msg); break; case VIRTCHNL_OP_UNKNOWN: default: dev_err(dev, "Unsupported opcode %d from VF %d\n", v_opcode, vf_id); err = ice_vc_send_msg_to_vf(vf, v_opcode, VIRTCHNL_STATUS_ERR_NOT_SUPPORTED, NULL, 0); break; } if (err) { /* Helper function cares less about error return values here * as it is busy with pending work. */ dev_info(dev, "PF failed to honor VF %d, opcode %d, error %d\n", vf_id, v_opcode, err); } finish: mutex_unlock(&vf->cfg_lock); ice_put_vf(vf); }
linux-master
drivers/net/ethernet/intel/ice/ice_virtchnl.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2021, Intel Corporation. */ /* Inter-Driver Communication */ #include "ice.h" #include "ice_lib.h" #include "ice_dcb_lib.h" static DEFINE_XARRAY_ALLOC1(ice_aux_id); /** * ice_get_auxiliary_drv - retrieve iidc_auxiliary_drv struct * @pf: pointer to PF struct * * This function has to be called with a device_lock on the * pf->adev.dev to avoid race conditions. */ static struct iidc_auxiliary_drv *ice_get_auxiliary_drv(struct ice_pf *pf) { struct auxiliary_device *adev; adev = pf->adev; if (!adev || !adev->dev.driver) return NULL; return container_of(adev->dev.driver, struct iidc_auxiliary_drv, adrv.driver); } /** * ice_send_event_to_aux - send event to RDMA AUX driver * @pf: pointer to PF struct * @event: event struct */ void ice_send_event_to_aux(struct ice_pf *pf, struct iidc_event *event) { struct iidc_auxiliary_drv *iadrv; if (WARN_ON_ONCE(!in_task())) return; mutex_lock(&pf->adev_mutex); if (!pf->adev) goto finish; device_lock(&pf->adev->dev); iadrv = ice_get_auxiliary_drv(pf); if (iadrv && iadrv->event_handler) iadrv->event_handler(pf, event); device_unlock(&pf->adev->dev); finish: mutex_unlock(&pf->adev_mutex); } /** * ice_add_rdma_qset - Add Leaf Node for RDMA Qset * @pf: PF struct * @qset: Resource to be allocated */ int ice_add_rdma_qset(struct ice_pf *pf, struct iidc_rdma_qset_params *qset) { u16 max_rdmaqs[ICE_MAX_TRAFFIC_CLASS]; struct ice_vsi *vsi; struct device *dev; u32 qset_teid; u16 qs_handle; int status; int i; if (WARN_ON(!pf || !qset)) return -EINVAL; dev = ice_pf_to_dev(pf); if (!ice_is_rdma_ena(pf)) return -EINVAL; vsi = ice_get_main_vsi(pf); if (!vsi) { dev_err(dev, "RDMA QSet invalid VSI\n"); return -EINVAL; } ice_for_each_traffic_class(i) max_rdmaqs[i] = 0; max_rdmaqs[qset->tc]++; qs_handle = qset->qs_handle; status = ice_cfg_vsi_rdma(vsi->port_info, vsi->idx, vsi->tc_cfg.ena_tc, max_rdmaqs); if (status) { dev_err(dev, "Failed VSI RDMA Qset config\n"); return status; } status = ice_ena_vsi_rdma_qset(vsi->port_info, vsi->idx, qset->tc, &qs_handle, 1, &qset_teid); if (status) { dev_err(dev, "Failed VSI RDMA Qset enable\n"); return status; } vsi->qset_handle[qset->tc] = qset->qs_handle; qset->teid = qset_teid; return 0; } EXPORT_SYMBOL_GPL(ice_add_rdma_qset); /** * ice_del_rdma_qset - Delete leaf node for RDMA Qset * @pf: PF struct * @qset: Resource to be freed */ int ice_del_rdma_qset(struct ice_pf *pf, struct iidc_rdma_qset_params *qset) { struct ice_vsi *vsi; u32 teid; u16 q_id; if (WARN_ON(!pf || !qset)) return -EINVAL; vsi = ice_find_vsi(pf, qset->vport_id); if (!vsi) { dev_err(ice_pf_to_dev(pf), "RDMA Invalid VSI\n"); return -EINVAL; } q_id = qset->qs_handle; teid = qset->teid; vsi->qset_handle[qset->tc] = 0; return ice_dis_vsi_rdma_qset(vsi->port_info, 1, &teid, &q_id); } EXPORT_SYMBOL_GPL(ice_del_rdma_qset); /** * ice_rdma_request_reset - accept request from RDMA to perform a reset * @pf: struct for PF * @reset_type: type of reset */ int ice_rdma_request_reset(struct ice_pf *pf, enum iidc_reset_type reset_type) { enum ice_reset_req reset; if (WARN_ON(!pf)) return -EINVAL; switch (reset_type) { case IIDC_PFR: reset = ICE_RESET_PFR; break; case IIDC_CORER: reset = ICE_RESET_CORER; break; case IIDC_GLOBR: reset = ICE_RESET_GLOBR; break; default: dev_err(ice_pf_to_dev(pf), "incorrect reset request\n"); return -EINVAL; } return ice_schedule_reset(pf, reset); } EXPORT_SYMBOL_GPL(ice_rdma_request_reset); /** * ice_rdma_update_vsi_filter - update main VSI filters for RDMA * @pf: pointer to struct for PF * @vsi_id: VSI HW idx to update filter on * @enable: bool whether to enable or disable filters */ int ice_rdma_update_vsi_filter(struct ice_pf *pf, u16 vsi_id, bool enable) { struct ice_vsi *vsi; int status; if (WARN_ON(!pf)) return -EINVAL; vsi = ice_find_vsi(pf, vsi_id); if (!vsi) return -EINVAL; status = ice_cfg_rdma_fltr(&pf->hw, vsi->idx, enable); if (status) { dev_err(ice_pf_to_dev(pf), "Failed to %sable RDMA filtering\n", enable ? "en" : "dis"); } else { if (enable) vsi->info.q_opt_flags |= ICE_AQ_VSI_Q_OPT_PE_FLTR_EN; else vsi->info.q_opt_flags &= ~ICE_AQ_VSI_Q_OPT_PE_FLTR_EN; } return status; } EXPORT_SYMBOL_GPL(ice_rdma_update_vsi_filter); /** * ice_get_qos_params - parse QoS params for RDMA consumption * @pf: pointer to PF struct * @qos: set of QoS values */ void ice_get_qos_params(struct ice_pf *pf, struct iidc_qos_params *qos) { struct ice_dcbx_cfg *dcbx_cfg; unsigned int i; u32 up2tc; dcbx_cfg = &pf->hw.port_info->qos_cfg.local_dcbx_cfg; up2tc = rd32(&pf->hw, PRTDCB_TUP2TC); qos->num_tc = ice_dcb_get_num_tc(dcbx_cfg); for (i = 0; i < IIDC_MAX_USER_PRIORITY; i++) qos->up2tc[i] = (up2tc >> (i * 3)) & 0x7; for (i = 0; i < IEEE_8021QAZ_MAX_TCS; i++) qos->tc_info[i].rel_bw = dcbx_cfg->etscfg.tcbwtable[i]; qos->pfc_mode = dcbx_cfg->pfc_mode; if (qos->pfc_mode == IIDC_DSCP_PFC_MODE) for (i = 0; i < IIDC_MAX_DSCP_MAPPING; i++) qos->dscp_map[i] = dcbx_cfg->dscp_map[i]; } EXPORT_SYMBOL_GPL(ice_get_qos_params); /** * ice_alloc_rdma_qvectors - Allocate vector resources for RDMA driver * @pf: board private structure to initialize */ static int ice_alloc_rdma_qvectors(struct ice_pf *pf) { if (ice_is_rdma_ena(pf)) { int i; pf->msix_entries = kcalloc(pf->num_rdma_msix, sizeof(*pf->msix_entries), GFP_KERNEL); if (!pf->msix_entries) return -ENOMEM; /* RDMA is the only user of pf->msix_entries array */ pf->rdma_base_vector = 0; for (i = 0; i < pf->num_rdma_msix; i++) { struct msix_entry *entry = &pf->msix_entries[i]; struct msi_map map; map = ice_alloc_irq(pf, false); if (map.index < 0) break; entry->entry = map.index; entry->vector = map.virq; } } return 0; } /** * ice_free_rdma_qvector - free vector resources reserved for RDMA driver * @pf: board private structure to initialize */ static void ice_free_rdma_qvector(struct ice_pf *pf) { int i; if (!pf->msix_entries) return; for (i = 0; i < pf->num_rdma_msix; i++) { struct msi_map map; map.index = pf->msix_entries[i].entry; map.virq = pf->msix_entries[i].vector; ice_free_irq(pf, map); } kfree(pf->msix_entries); pf->msix_entries = NULL; } /** * ice_adev_release - function to be mapped to AUX dev's release op * @dev: pointer to device to free */ static void ice_adev_release(struct device *dev) { struct iidc_auxiliary_dev *iadev; iadev = container_of(dev, struct iidc_auxiliary_dev, adev.dev); kfree(iadev); } /** * ice_plug_aux_dev - allocate and register AUX device * @pf: pointer to pf struct */ int ice_plug_aux_dev(struct ice_pf *pf) { struct iidc_auxiliary_dev *iadev; struct auxiliary_device *adev; int ret; /* if this PF doesn't support a technology that requires auxiliary * devices, then gracefully exit */ if (!ice_is_rdma_ena(pf)) return 0; iadev = kzalloc(sizeof(*iadev), GFP_KERNEL); if (!iadev) return -ENOMEM; adev = &iadev->adev; iadev->pf = pf; adev->id = pf->aux_idx; adev->dev.release = ice_adev_release; adev->dev.parent = &pf->pdev->dev; adev->name = pf->rdma_mode & IIDC_RDMA_PROTOCOL_ROCEV2 ? "roce" : "iwarp"; ret = auxiliary_device_init(adev); if (ret) { kfree(iadev); return ret; } ret = auxiliary_device_add(adev); if (ret) { auxiliary_device_uninit(adev); return ret; } mutex_lock(&pf->adev_mutex); pf->adev = adev; mutex_unlock(&pf->adev_mutex); return 0; } /* ice_unplug_aux_dev - unregister and free AUX device * @pf: pointer to pf struct */ void ice_unplug_aux_dev(struct ice_pf *pf) { struct auxiliary_device *adev; mutex_lock(&pf->adev_mutex); adev = pf->adev; pf->adev = NULL; mutex_unlock(&pf->adev_mutex); if (adev) { auxiliary_device_delete(adev); auxiliary_device_uninit(adev); } } /** * ice_init_rdma - initializes PF for RDMA use * @pf: ptr to ice_pf */ int ice_init_rdma(struct ice_pf *pf) { struct device *dev = &pf->pdev->dev; int ret; if (!ice_is_rdma_ena(pf)) { dev_warn(dev, "RDMA is not supported on this device\n"); return 0; } ret = xa_alloc(&ice_aux_id, &pf->aux_idx, NULL, XA_LIMIT(1, INT_MAX), GFP_KERNEL); if (ret) { dev_err(dev, "Failed to allocate device ID for AUX driver\n"); return -ENOMEM; } /* Reserve vector resources */ ret = ice_alloc_rdma_qvectors(pf); if (ret < 0) { dev_err(dev, "failed to reserve vectors for RDMA\n"); goto err_reserve_rdma_qvector; } pf->rdma_mode |= IIDC_RDMA_PROTOCOL_ROCEV2; ret = ice_plug_aux_dev(pf); if (ret) goto err_plug_aux_dev; return 0; err_plug_aux_dev: ice_free_rdma_qvector(pf); err_reserve_rdma_qvector: pf->adev = NULL; xa_erase(&ice_aux_id, pf->aux_idx); return ret; } /** * ice_deinit_rdma - deinitialize RDMA on PF * @pf: ptr to ice_pf */ void ice_deinit_rdma(struct ice_pf *pf) { if (!ice_is_rdma_ena(pf)) return; ice_unplug_aux_dev(pf); ice_free_rdma_qvector(pf); xa_erase(&ice_aux_id, pf->aux_idx); }
linux-master
drivers/net/ethernet/intel/ice/ice_idc.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2018-2021, Intel Corporation. */ /* Link Aggregation code */ #include "ice.h" #include "ice_lib.h" #include "ice_lag.h" #define ICE_LAG_RES_SHARED BIT(14) #define ICE_LAG_RES_VALID BIT(15) #define LACP_TRAIN_PKT_LEN 16 static const u8 lacp_train_pkt[LACP_TRAIN_PKT_LEN] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x88, 0x09, 0, 0 }; #define ICE_RECIPE_LEN 64 static const u8 ice_dflt_vsi_rcp[ICE_RECIPE_LEN] = { 0x05, 0, 0, 0, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x85, 0, 0x01, 0, 0, 0, 0xff, 0xff, 0x08, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /** * ice_lag_set_primary - set PF LAG state as Primary * @lag: LAG info struct */ static void ice_lag_set_primary(struct ice_lag *lag) { struct ice_pf *pf = lag->pf; if (!pf) return; if (lag->role != ICE_LAG_UNSET && lag->role != ICE_LAG_BACKUP) { dev_warn(ice_pf_to_dev(pf), "%s: Attempt to be Primary, but incompatible state.\n", netdev_name(lag->netdev)); return; } lag->role = ICE_LAG_PRIMARY; } /** * ice_lag_set_backup - set PF LAG state to Backup * @lag: LAG info struct */ static void ice_lag_set_backup(struct ice_lag *lag) { struct ice_pf *pf = lag->pf; if (!pf) return; if (lag->role != ICE_LAG_UNSET && lag->role != ICE_LAG_PRIMARY) { dev_dbg(ice_pf_to_dev(pf), "%s: Attempt to be Backup, but incompatible state\n", netdev_name(lag->netdev)); return; } lag->role = ICE_LAG_BACKUP; } /** * netif_is_same_ice - determine if netdev is on the same ice NIC as local PF * @pf: local PF struct * @netdev: netdev we are evaluating */ static bool netif_is_same_ice(struct ice_pf *pf, struct net_device *netdev) { struct ice_netdev_priv *np; struct ice_pf *test_pf; struct ice_vsi *vsi; if (!netif_is_ice(netdev)) return false; np = netdev_priv(netdev); if (!np) return false; vsi = np->vsi; if (!vsi) return false; test_pf = vsi->back; if (!test_pf) return false; if (pf->pdev->bus != test_pf->pdev->bus || pf->pdev->slot != test_pf->pdev->slot) return false; return true; } /** * ice_netdev_to_lag - return pointer to associated lag struct from netdev * @netdev: pointer to net_device struct to query */ static struct ice_lag *ice_netdev_to_lag(struct net_device *netdev) { struct ice_netdev_priv *np; struct ice_vsi *vsi; if (!netif_is_ice(netdev)) return NULL; np = netdev_priv(netdev); if (!np) return NULL; vsi = np->vsi; if (!vsi) return NULL; return vsi->back->lag; } /** * ice_lag_find_hw_by_lport - return an hw struct from bond members lport * @lag: lag struct * @lport: lport value to search for */ static struct ice_hw * ice_lag_find_hw_by_lport(struct ice_lag *lag, u8 lport) { struct ice_lag_netdev_list *entry; struct net_device *tmp_netdev; struct ice_netdev_priv *np; struct ice_hw *hw; list_for_each_entry(entry, lag->netdev_head, node) { tmp_netdev = entry->netdev; if (!tmp_netdev || !netif_is_ice(tmp_netdev)) continue; np = netdev_priv(tmp_netdev); if (!np || !np->vsi) continue; hw = &np->vsi->back->hw; if (hw->port_info->lport == lport) return hw; } return NULL; } /** * ice_lag_find_primary - returns pointer to primary interfaces lag struct * @lag: local interfaces lag struct */ static struct ice_lag *ice_lag_find_primary(struct ice_lag *lag) { struct ice_lag *primary_lag = NULL; struct list_head *tmp; list_for_each(tmp, lag->netdev_head) { struct ice_lag_netdev_list *entry; struct ice_lag *tmp_lag; entry = list_entry(tmp, struct ice_lag_netdev_list, node); tmp_lag = ice_netdev_to_lag(entry->netdev); if (tmp_lag && tmp_lag->primary) { primary_lag = tmp_lag; break; } } return primary_lag; } /** * ice_lag_cfg_dflt_fltr - Add/Remove default VSI rule for LAG * @lag: lag struct for local interface * @add: boolean on whether we are adding filters */ static int ice_lag_cfg_dflt_fltr(struct ice_lag *lag, bool add) { struct ice_sw_rule_lkup_rx_tx *s_rule; u16 s_rule_sz, vsi_num; struct ice_hw *hw; u32 act, opc; u8 *eth_hdr; int err; hw = &lag->pf->hw; vsi_num = ice_get_hw_vsi_num(hw, 0); s_rule_sz = ICE_SW_RULE_RX_TX_ETH_HDR_SIZE(s_rule); s_rule = kzalloc(s_rule_sz, GFP_KERNEL); if (!s_rule) { dev_err(ice_pf_to_dev(lag->pf), "error allocating rule for LAG default VSI\n"); return -ENOMEM; } if (add) { eth_hdr = s_rule->hdr_data; ice_fill_eth_hdr(eth_hdr); act = (vsi_num << ICE_SINGLE_ACT_VSI_ID_S) & ICE_SINGLE_ACT_VSI_ID_M; act |= ICE_SINGLE_ACT_VSI_FORWARDING | ICE_SINGLE_ACT_VALID_BIT | ICE_SINGLE_ACT_LAN_ENABLE; s_rule->hdr.type = cpu_to_le16(ICE_AQC_SW_RULES_T_LKUP_RX); s_rule->recipe_id = cpu_to_le16(lag->pf_recipe); s_rule->src = cpu_to_le16(hw->port_info->lport); s_rule->act = cpu_to_le32(act); s_rule->hdr_len = cpu_to_le16(DUMMY_ETH_HDR_LEN); opc = ice_aqc_opc_add_sw_rules; } else { s_rule->index = cpu_to_le16(lag->pf_rule_id); opc = ice_aqc_opc_remove_sw_rules; } err = ice_aq_sw_rules(&lag->pf->hw, s_rule, s_rule_sz, 1, opc, NULL); if (err) goto dflt_fltr_free; if (add) lag->pf_rule_id = le16_to_cpu(s_rule->index); else lag->pf_rule_id = 0; dflt_fltr_free: kfree(s_rule); return err; } /** * ice_lag_cfg_pf_fltrs - set filters up for new active port * @lag: local interfaces lag struct * @ptr: opaque data containing notifier event */ static void ice_lag_cfg_pf_fltrs(struct ice_lag *lag, void *ptr) { struct netdev_notifier_bonding_info *info; struct netdev_bonding_info *bonding_info; struct net_device *event_netdev; struct device *dev; event_netdev = netdev_notifier_info_to_dev(ptr); /* not for this netdev */ if (event_netdev != lag->netdev) return; info = (struct netdev_notifier_bonding_info *)ptr; bonding_info = &info->bonding_info; dev = ice_pf_to_dev(lag->pf); /* interface not active - remove old default VSI rule */ if (bonding_info->slave.state && lag->pf_rule_id) { if (ice_lag_cfg_dflt_fltr(lag, false)) dev_err(dev, "Error removing old default VSI filter\n"); return; } /* interface becoming active - add new default VSI rule */ if (!bonding_info->slave.state && !lag->pf_rule_id) if (ice_lag_cfg_dflt_fltr(lag, true)) dev_err(dev, "Error adding new default VSI filter\n"); } /** * ice_display_lag_info - print LAG info * @lag: LAG info struct */ static void ice_display_lag_info(struct ice_lag *lag) { const char *name, *upper, *role, *bonded, *primary; struct device *dev = &lag->pf->pdev->dev; name = lag->netdev ? netdev_name(lag->netdev) : "unset"; upper = lag->upper_netdev ? netdev_name(lag->upper_netdev) : "unset"; primary = lag->primary ? "TRUE" : "FALSE"; bonded = lag->bonded ? "BONDED" : "UNBONDED"; switch (lag->role) { case ICE_LAG_NONE: role = "NONE"; break; case ICE_LAG_PRIMARY: role = "PRIMARY"; break; case ICE_LAG_BACKUP: role = "BACKUP"; break; case ICE_LAG_UNSET: role = "UNSET"; break; default: role = "ERROR"; } dev_dbg(dev, "%s %s, upper:%s, role:%s, primary:%s\n", name, bonded, upper, role, primary); } /** * ice_lag_qbuf_recfg - generate a buffer of queues for a reconfigure command * @hw: HW struct that contains the queue contexts * @qbuf: pointer to buffer to populate * @vsi_num: index of the VSI in PF space * @numq: number of queues to search for * @tc: traffic class that contains the queues * * function returns the number of valid queues in buffer */ static u16 ice_lag_qbuf_recfg(struct ice_hw *hw, struct ice_aqc_cfg_txqs_buf *qbuf, u16 vsi_num, u16 numq, u8 tc) { struct ice_q_ctx *q_ctx; u16 qid, count = 0; struct ice_pf *pf; int i; pf = hw->back; for (i = 0; i < numq; i++) { q_ctx = ice_get_lan_q_ctx(hw, vsi_num, tc, i); if (!q_ctx) { dev_dbg(ice_hw_to_dev(hw), "%s queue %d NO Q CONTEXT\n", __func__, i); continue; } if (q_ctx->q_teid == ICE_INVAL_TEID) { dev_dbg(ice_hw_to_dev(hw), "%s queue %d INVAL TEID\n", __func__, i); continue; } if (q_ctx->q_handle == ICE_INVAL_Q_HANDLE) { dev_dbg(ice_hw_to_dev(hw), "%s queue %d INVAL Q HANDLE\n", __func__, i); continue; } qid = pf->vsi[vsi_num]->txq_map[q_ctx->q_handle]; qbuf->queue_info[count].q_handle = cpu_to_le16(qid); qbuf->queue_info[count].tc = tc; qbuf->queue_info[count].q_teid = cpu_to_le32(q_ctx->q_teid); count++; } return count; } /** * ice_lag_get_sched_parent - locate or create a sched node parent * @hw: HW struct for getting parent in * @tc: traffic class on parent/node */ static struct ice_sched_node * ice_lag_get_sched_parent(struct ice_hw *hw, u8 tc) { struct ice_sched_node *tc_node, *aggnode, *parent = NULL; u16 num_nodes[ICE_AQC_TOPO_MAX_LEVEL_NUM] = { 0 }; struct ice_port_info *pi = hw->port_info; struct device *dev; u8 aggl, vsil; int n; dev = ice_hw_to_dev(hw); tc_node = ice_sched_get_tc_node(pi, tc); if (!tc_node) { dev_warn(dev, "Failure to find TC node for LAG move\n"); return parent; } aggnode = ice_sched_get_agg_node(pi, tc_node, ICE_DFLT_AGG_ID); if (!aggnode) { dev_warn(dev, "Failure to find aggregate node for LAG move\n"); return parent; } aggl = ice_sched_get_agg_layer(hw); vsil = ice_sched_get_vsi_layer(hw); for (n = aggl + 1; n < vsil; n++) num_nodes[n] = 1; for (n = 0; n < aggnode->num_children; n++) { parent = ice_sched_get_free_vsi_parent(hw, aggnode->children[n], num_nodes); if (parent) return parent; } /* if free parent not found - add one */ parent = aggnode; for (n = aggl + 1; n < vsil; n++) { u16 num_nodes_added; u32 first_teid; int err; err = ice_sched_add_nodes_to_layer(pi, tc_node, parent, n, num_nodes[n], &first_teid, &num_nodes_added); if (err || num_nodes[n] != num_nodes_added) return NULL; if (num_nodes_added) parent = ice_sched_find_node_by_teid(tc_node, first_teid); else parent = parent->children[0]; if (!parent) { dev_warn(dev, "Failure to add new parent for LAG move\n"); return parent; } } return parent; } /** * ice_lag_move_vf_node_tc - move scheduling nodes for one VF on one TC * @lag: lag info struct * @oldport: lport of previous nodes location * @newport: lport of destination nodes location * @vsi_num: array index of VSI in PF space * @tc: traffic class to move */ static void ice_lag_move_vf_node_tc(struct ice_lag *lag, u8 oldport, u8 newport, u16 vsi_num, u8 tc) { u16 numq, valq, buf_size, num_moved, qbuf_size; struct device *dev = ice_pf_to_dev(lag->pf); struct ice_aqc_cfg_txqs_buf *qbuf; struct ice_aqc_move_elem *buf; struct ice_sched_node *n_prt; struct ice_hw *new_hw = NULL; __le32 teid, parent_teid; struct ice_vsi_ctx *ctx; u32 tmp_teid; ctx = ice_get_vsi_ctx(&lag->pf->hw, vsi_num); if (!ctx) { dev_warn(dev, "Unable to locate VSI context for LAG failover\n"); return; } /* check to see if this VF is enabled on this TC */ if (!ctx->sched.vsi_node[tc]) return; /* locate HW struct for destination port */ new_hw = ice_lag_find_hw_by_lport(lag, newport); if (!new_hw) { dev_warn(dev, "Unable to locate HW struct for LAG node destination\n"); return; } numq = ctx->num_lan_q_entries[tc]; teid = ctx->sched.vsi_node[tc]->info.node_teid; tmp_teid = le32_to_cpu(teid); parent_teid = ctx->sched.vsi_node[tc]->info.parent_teid; /* if no teid assigned or numq == 0, then this TC is not active */ if (!tmp_teid || !numq) return; /* suspend VSI subtree for Traffic Class "tc" on * this VF's VSI */ if (ice_sched_suspend_resume_elems(&lag->pf->hw, 1, &tmp_teid, true)) dev_dbg(dev, "Problem suspending traffic for LAG node move\n"); /* reconfigure all VF's queues on this Traffic Class * to new port */ qbuf_size = struct_size(qbuf, queue_info, numq); qbuf = kzalloc(qbuf_size, GFP_KERNEL); if (!qbuf) { dev_warn(dev, "Failure allocating memory for VF queue recfg buffer\n"); goto resume_traffic; } /* add the per queue info for the reconfigure command buffer */ valq = ice_lag_qbuf_recfg(&lag->pf->hw, qbuf, vsi_num, numq, tc); if (!valq) { dev_dbg(dev, "No valid queues found for LAG failover\n"); goto qbuf_none; } if (ice_aq_cfg_lan_txq(&lag->pf->hw, qbuf, qbuf_size, valq, oldport, newport, NULL)) { dev_warn(dev, "Failure to configure queues for LAG failover\n"); goto qbuf_err; } qbuf_none: kfree(qbuf); /* find new parent in destination port's tree for VF VSI node on this * Traffic Class */ n_prt = ice_lag_get_sched_parent(new_hw, tc); if (!n_prt) goto resume_traffic; /* Move Vf's VSI node for this TC to newport's scheduler tree */ buf_size = struct_size(buf, teid, 1); buf = kzalloc(buf_size, GFP_KERNEL); if (!buf) { dev_warn(dev, "Failure to alloc memory for VF node failover\n"); goto resume_traffic; } buf->hdr.src_parent_teid = parent_teid; buf->hdr.dest_parent_teid = n_prt->info.node_teid; buf->hdr.num_elems = cpu_to_le16(1); buf->hdr.mode = ICE_AQC_MOVE_ELEM_MODE_KEEP_OWN; buf->teid[0] = teid; if (ice_aq_move_sched_elems(&lag->pf->hw, 1, buf, buf_size, &num_moved, NULL)) dev_warn(dev, "Failure to move VF nodes for failover\n"); else ice_sched_update_parent(n_prt, ctx->sched.vsi_node[tc]); kfree(buf); goto resume_traffic; qbuf_err: kfree(qbuf); resume_traffic: /* restart traffic for VSI node */ if (ice_sched_suspend_resume_elems(&lag->pf->hw, 1, &tmp_teid, false)) dev_dbg(dev, "Problem restarting traffic for LAG node move\n"); } /** * ice_lag_move_single_vf_nodes - Move Tx scheduling nodes for single VF * @lag: primary interface LAG struct * @oldport: lport of previous interface * @newport: lport of destination interface * @vsi_num: SW index of VF's VSI */ static void ice_lag_move_single_vf_nodes(struct ice_lag *lag, u8 oldport, u8 newport, u16 vsi_num) { u8 tc; ice_for_each_traffic_class(tc) ice_lag_move_vf_node_tc(lag, oldport, newport, vsi_num, tc); } /** * ice_lag_move_new_vf_nodes - Move Tx scheduling nodes for a VF if required * @vf: the VF to move Tx nodes for * * Called just after configuring new VF queues. Check whether the VF Tx * scheduling nodes need to be updated to fail over to the active port. If so, * move them now. */ void ice_lag_move_new_vf_nodes(struct ice_vf *vf) { struct ice_lag_netdev_list ndlist; struct list_head *tmp, *n; u8 pri_port, act_port; struct ice_lag *lag; struct ice_vsi *vsi; struct ice_pf *pf; vsi = ice_get_vf_vsi(vf); if (WARN_ON(!vsi)) return; if (WARN_ON(vsi->type != ICE_VSI_VF)) return; pf = vf->pf; lag = pf->lag; mutex_lock(&pf->lag_mutex); if (!lag->bonded) goto new_vf_unlock; pri_port = pf->hw.port_info->lport; act_port = lag->active_port; if (lag->upper_netdev) { struct ice_lag_netdev_list *nl; struct net_device *tmp_nd; INIT_LIST_HEAD(&ndlist.node); rcu_read_lock(); for_each_netdev_in_bond_rcu(lag->upper_netdev, tmp_nd) { nl = kzalloc(sizeof(*nl), GFP_KERNEL); if (!nl) break; nl->netdev = tmp_nd; list_add(&nl->node, &ndlist.node); } rcu_read_unlock(); } lag->netdev_head = &ndlist.node; if (ice_is_feature_supported(pf, ICE_F_SRIOV_LAG) && lag->bonded && lag->primary && pri_port != act_port && !list_empty(lag->netdev_head)) ice_lag_move_single_vf_nodes(lag, pri_port, act_port, vsi->idx); list_for_each_safe(tmp, n, &ndlist.node) { struct ice_lag_netdev_list *entry; entry = list_entry(tmp, struct ice_lag_netdev_list, node); list_del(&entry->node); kfree(entry); } lag->netdev_head = NULL; new_vf_unlock: mutex_unlock(&pf->lag_mutex); } /** * ice_lag_move_vf_nodes - move Tx scheduling nodes for all VFs to new port * @lag: lag info struct * @oldport: lport of previous interface * @newport: lport of destination interface */ static void ice_lag_move_vf_nodes(struct ice_lag *lag, u8 oldport, u8 newport) { struct ice_pf *pf; int i; if (!lag->primary) return; pf = lag->pf; ice_for_each_vsi(pf, i) if (pf->vsi[i] && (pf->vsi[i]->type == ICE_VSI_VF || pf->vsi[i]->type == ICE_VSI_SWITCHDEV_CTRL)) ice_lag_move_single_vf_nodes(lag, oldport, newport, i); } #define ICE_LAG_SRIOV_CP_RECIPE 10 #define ICE_LAG_SRIOV_TRAIN_PKT_LEN 16 /** * ice_lag_cfg_cp_fltr - configure filter for control packets * @lag: local interface's lag struct * @add: add or remove rule */ static void ice_lag_cfg_cp_fltr(struct ice_lag *lag, bool add) { struct ice_sw_rule_lkup_rx_tx *s_rule = NULL; struct ice_vsi *vsi; u16 buf_len, opc; vsi = lag->pf->vsi[0]; buf_len = ICE_SW_RULE_RX_TX_HDR_SIZE(s_rule, ICE_LAG_SRIOV_TRAIN_PKT_LEN); s_rule = kzalloc(buf_len, GFP_KERNEL); if (!s_rule) { netdev_warn(lag->netdev, "-ENOMEM error configuring CP filter\n"); return; } if (add) { s_rule->hdr.type = cpu_to_le16(ICE_AQC_SW_RULES_T_LKUP_RX); s_rule->recipe_id = cpu_to_le16(ICE_LAG_SRIOV_CP_RECIPE); s_rule->src = cpu_to_le16(vsi->port_info->lport); s_rule->act = cpu_to_le32(ICE_FWD_TO_VSI | ICE_SINGLE_ACT_LAN_ENABLE | ICE_SINGLE_ACT_VALID_BIT | ((vsi->vsi_num << ICE_SINGLE_ACT_VSI_ID_S) & ICE_SINGLE_ACT_VSI_ID_M)); s_rule->hdr_len = cpu_to_le16(ICE_LAG_SRIOV_TRAIN_PKT_LEN); memcpy(s_rule->hdr_data, lacp_train_pkt, LACP_TRAIN_PKT_LEN); opc = ice_aqc_opc_add_sw_rules; } else { opc = ice_aqc_opc_remove_sw_rules; s_rule->index = cpu_to_le16(lag->cp_rule_idx); } if (ice_aq_sw_rules(&lag->pf->hw, s_rule, buf_len, 1, opc, NULL)) { netdev_warn(lag->netdev, "Error %s CP rule for fail-over\n", add ? "ADDING" : "REMOVING"); goto cp_free; } if (add) lag->cp_rule_idx = le16_to_cpu(s_rule->index); else lag->cp_rule_idx = 0; cp_free: kfree(s_rule); } /** * ice_lag_info_event - handle NETDEV_BONDING_INFO event * @lag: LAG info struct * @ptr: opaque data pointer * * ptr is to be cast to (netdev_notifier_bonding_info *) */ static void ice_lag_info_event(struct ice_lag *lag, void *ptr) { struct netdev_notifier_bonding_info *info; struct netdev_bonding_info *bonding_info; struct net_device *event_netdev; const char *lag_netdev_name; event_netdev = netdev_notifier_info_to_dev(ptr); info = ptr; lag_netdev_name = netdev_name(lag->netdev); bonding_info = &info->bonding_info; if (event_netdev != lag->netdev || !lag->bonded || !lag->upper_netdev) return; if (bonding_info->master.bond_mode != BOND_MODE_ACTIVEBACKUP) { netdev_dbg(lag->netdev, "Bonding event recv, but mode not active/backup\n"); goto lag_out; } if (strcmp(bonding_info->slave.slave_name, lag_netdev_name)) { netdev_dbg(lag->netdev, "Bonding event recv, but secondary info not for us\n"); goto lag_out; } if (bonding_info->slave.state) ice_lag_set_backup(lag); else ice_lag_set_primary(lag); lag_out: ice_display_lag_info(lag); } /** * ice_lag_reclaim_vf_tc - move scheduling nodes back to primary interface * @lag: primary interface lag struct * @src_hw: HW struct current node location * @vsi_num: VSI index in PF space * @tc: traffic class to move */ static void ice_lag_reclaim_vf_tc(struct ice_lag *lag, struct ice_hw *src_hw, u16 vsi_num, u8 tc) { u16 numq, valq, buf_size, num_moved, qbuf_size; struct device *dev = ice_pf_to_dev(lag->pf); struct ice_aqc_cfg_txqs_buf *qbuf; struct ice_aqc_move_elem *buf; struct ice_sched_node *n_prt; __le32 teid, parent_teid; struct ice_vsi_ctx *ctx; struct ice_hw *hw; u32 tmp_teid; hw = &lag->pf->hw; ctx = ice_get_vsi_ctx(hw, vsi_num); if (!ctx) { dev_warn(dev, "Unable to locate VSI context for LAG reclaim\n"); return; } /* check to see if this VF is enabled on this TC */ if (!ctx->sched.vsi_node[tc]) return; numq = ctx->num_lan_q_entries[tc]; teid = ctx->sched.vsi_node[tc]->info.node_teid; tmp_teid = le32_to_cpu(teid); parent_teid = ctx->sched.vsi_node[tc]->info.parent_teid; /* if !teid or !numq, then this TC is not active */ if (!tmp_teid || !numq) return; /* suspend traffic */ if (ice_sched_suspend_resume_elems(hw, 1, &tmp_teid, true)) dev_dbg(dev, "Problem suspending traffic for LAG node move\n"); /* reconfig queues for new port */ qbuf_size = struct_size(qbuf, queue_info, numq); qbuf = kzalloc(qbuf_size, GFP_KERNEL); if (!qbuf) { dev_warn(dev, "Failure allocating memory for VF queue recfg buffer\n"); goto resume_reclaim; } /* add the per queue info for the reconfigure command buffer */ valq = ice_lag_qbuf_recfg(hw, qbuf, vsi_num, numq, tc); if (!valq) { dev_dbg(dev, "No valid queues found for LAG reclaim\n"); goto reclaim_none; } if (ice_aq_cfg_lan_txq(hw, qbuf, qbuf_size, numq, src_hw->port_info->lport, hw->port_info->lport, NULL)) { dev_warn(dev, "Failure to configure queues for LAG failover\n"); goto reclaim_qerr; } reclaim_none: kfree(qbuf); /* find parent in primary tree */ n_prt = ice_lag_get_sched_parent(hw, tc); if (!n_prt) goto resume_reclaim; /* Move node to new parent */ buf_size = struct_size(buf, teid, 1); buf = kzalloc(buf_size, GFP_KERNEL); if (!buf) { dev_warn(dev, "Failure to alloc memory for VF node failover\n"); goto resume_reclaim; } buf->hdr.src_parent_teid = parent_teid; buf->hdr.dest_parent_teid = n_prt->info.node_teid; buf->hdr.num_elems = cpu_to_le16(1); buf->hdr.mode = ICE_AQC_MOVE_ELEM_MODE_KEEP_OWN; buf->teid[0] = teid; if (ice_aq_move_sched_elems(&lag->pf->hw, 1, buf, buf_size, &num_moved, NULL)) dev_warn(dev, "Failure to move VF nodes for LAG reclaim\n"); else ice_sched_update_parent(n_prt, ctx->sched.vsi_node[tc]); kfree(buf); goto resume_reclaim; reclaim_qerr: kfree(qbuf); resume_reclaim: /* restart traffic */ if (ice_sched_suspend_resume_elems(hw, 1, &tmp_teid, false)) dev_warn(dev, "Problem restarting traffic for LAG node reclaim\n"); } /** * ice_lag_reclaim_vf_nodes - When interface leaving bond primary reclaims nodes * @lag: primary interface lag struct * @src_hw: HW struct for current node location */ static void ice_lag_reclaim_vf_nodes(struct ice_lag *lag, struct ice_hw *src_hw) { struct ice_pf *pf; int i, tc; if (!lag->primary || !src_hw) return; pf = lag->pf; ice_for_each_vsi(pf, i) if (pf->vsi[i] && (pf->vsi[i]->type == ICE_VSI_VF || pf->vsi[i]->type == ICE_VSI_SWITCHDEV_CTRL)) ice_for_each_traffic_class(tc) ice_lag_reclaim_vf_tc(lag, src_hw, i, tc); } /** * ice_lag_link - handle LAG link event * @lag: LAG info struct */ static void ice_lag_link(struct ice_lag *lag) { struct ice_pf *pf = lag->pf; if (lag->bonded) dev_warn(ice_pf_to_dev(pf), "%s Already part of a bond\n", netdev_name(lag->netdev)); lag->bonded = true; lag->role = ICE_LAG_UNSET; netdev_info(lag->netdev, "Shared SR-IOV resources in bond are active\n"); } /** * ice_lag_unlink - handle unlink event * @lag: LAG info struct */ static void ice_lag_unlink(struct ice_lag *lag) { u8 pri_port, act_port, loc_port; struct ice_pf *pf = lag->pf; if (!lag->bonded) { netdev_dbg(lag->netdev, "bonding unlink event on non-LAG netdev\n"); return; } if (lag->primary) { act_port = lag->active_port; pri_port = lag->pf->hw.port_info->lport; if (act_port != pri_port && act_port != ICE_LAG_INVALID_PORT) ice_lag_move_vf_nodes(lag, act_port, pri_port); lag->primary = false; lag->active_port = ICE_LAG_INVALID_PORT; } else { struct ice_lag *primary_lag; primary_lag = ice_lag_find_primary(lag); if (primary_lag) { act_port = primary_lag->active_port; pri_port = primary_lag->pf->hw.port_info->lport; loc_port = pf->hw.port_info->lport; if (act_port == loc_port && act_port != ICE_LAG_INVALID_PORT) { ice_lag_reclaim_vf_nodes(primary_lag, &lag->pf->hw); primary_lag->active_port = ICE_LAG_INVALID_PORT; } } } lag->bonded = false; lag->role = ICE_LAG_NONE; lag->upper_netdev = NULL; } /** * ice_lag_link_unlink - helper function to call lag_link/unlink * @lag: lag info struct * @ptr: opaque pointer data */ static void ice_lag_link_unlink(struct ice_lag *lag, void *ptr) { struct net_device *netdev = netdev_notifier_info_to_dev(ptr); struct netdev_notifier_changeupper_info *info = ptr; if (netdev != lag->netdev) return; if (info->linking) ice_lag_link(lag); else ice_lag_unlink(lag); } /** * ice_lag_set_swid - set the SWID on secondary interface * @primary_swid: primary interface's SWID * @local_lag: local interfaces LAG struct * @link: Is this a linking activity * * If link is false, then primary_swid should be expected to not be valid * This function should never be called in interrupt context. */ static void ice_lag_set_swid(u16 primary_swid, struct ice_lag *local_lag, bool link) { struct ice_aqc_alloc_free_res_elem *buf; struct ice_aqc_set_port_params *cmd; struct ice_aq_desc desc; u16 buf_len, swid; int status, i; buf_len = struct_size(buf, elem, 1); buf = kzalloc(buf_len, GFP_KERNEL); if (!buf) { dev_err(ice_pf_to_dev(local_lag->pf), "-ENOMEM error setting SWID\n"); return; } buf->num_elems = cpu_to_le16(1); buf->res_type = cpu_to_le16(ICE_AQC_RES_TYPE_SWID); /* if unlinnking need to free the shared resource */ if (!link && local_lag->bond_swid) { buf->elem[0].e.sw_resp = cpu_to_le16(local_lag->bond_swid); status = ice_aq_alloc_free_res(&local_lag->pf->hw, buf, buf_len, ice_aqc_opc_free_res); if (status) dev_err(ice_pf_to_dev(local_lag->pf), "Error freeing SWID during LAG unlink\n"); local_lag->bond_swid = 0; } if (link) { buf->res_type |= cpu_to_le16(ICE_LAG_RES_SHARED | ICE_LAG_RES_VALID); /* store the primary's SWID in case it leaves bond first */ local_lag->bond_swid = primary_swid; buf->elem[0].e.sw_resp = cpu_to_le16(local_lag->bond_swid); } else { buf->elem[0].e.sw_resp = cpu_to_le16(local_lag->pf->hw.port_info->sw_id); } status = ice_aq_alloc_free_res(&local_lag->pf->hw, buf, buf_len, ice_aqc_opc_alloc_res); if (status) dev_err(ice_pf_to_dev(local_lag->pf), "Error subscribing to SWID 0x%04X\n", local_lag->bond_swid); kfree(buf); /* Configure port param SWID to correct value */ if (link) swid = primary_swid; else swid = local_lag->pf->hw.port_info->sw_id; cmd = &desc.params.set_port_params; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_set_port_params); cmd->swid = cpu_to_le16(ICE_AQC_PORT_SWID_VALID | swid); /* If this is happening in reset context, it is possible that the * primary interface has not finished setting its SWID to SHARED * yet. Allow retries to account for this timing issue between * interfaces. */ for (i = 0; i < ICE_LAG_RESET_RETRIES; i++) { status = ice_aq_send_cmd(&local_lag->pf->hw, &desc, NULL, 0, NULL); if (!status) break; usleep_range(1000, 2000); } if (status) dev_err(ice_pf_to_dev(local_lag->pf), "Error setting SWID in port params %d\n", status); } /** * ice_lag_primary_swid - set/clear the SHARED attrib of primary's SWID * @lag: primary interface's lag struct * @link: is this a linking activity * * Implement setting primary SWID as shared using 0x020B */ static void ice_lag_primary_swid(struct ice_lag *lag, bool link) { struct ice_hw *hw; u16 swid; hw = &lag->pf->hw; swid = hw->port_info->sw_id; if (ice_share_res(hw, ICE_AQC_RES_TYPE_SWID, link, swid)) dev_warn(ice_pf_to_dev(lag->pf), "Failure to set primary interface shared status\n"); } /** * ice_lag_add_prune_list - Adds event_pf's VSI to primary's prune list * @lag: lag info struct * @event_pf: PF struct for VSI we are adding to primary's prune list */ static void ice_lag_add_prune_list(struct ice_lag *lag, struct ice_pf *event_pf) { u16 num_vsi, rule_buf_sz, vsi_list_id, event_vsi_num, prim_vsi_idx; struct ice_sw_rule_vsi_list *s_rule = NULL; struct device *dev; num_vsi = 1; dev = ice_pf_to_dev(lag->pf); event_vsi_num = event_pf->vsi[0]->vsi_num; prim_vsi_idx = lag->pf->vsi[0]->idx; if (!ice_find_vsi_list_entry(&lag->pf->hw, ICE_SW_LKUP_VLAN, prim_vsi_idx, &vsi_list_id)) { dev_warn(dev, "Could not locate prune list when setting up SRIOV LAG\n"); return; } rule_buf_sz = (u16)ICE_SW_RULE_VSI_LIST_SIZE(s_rule, num_vsi); s_rule = kzalloc(rule_buf_sz, GFP_KERNEL); if (!s_rule) { dev_warn(dev, "Error allocating space for prune list when configuring SRIOV LAG\n"); return; } s_rule->hdr.type = cpu_to_le16(ICE_AQC_SW_RULES_T_PRUNE_LIST_SET); s_rule->index = cpu_to_le16(vsi_list_id); s_rule->number_vsi = cpu_to_le16(num_vsi); s_rule->vsi[0] = cpu_to_le16(event_vsi_num); if (ice_aq_sw_rules(&event_pf->hw, s_rule, rule_buf_sz, 1, ice_aqc_opc_update_sw_rules, NULL)) dev_warn(dev, "Error adding VSI prune list\n"); kfree(s_rule); } /** * ice_lag_del_prune_list - Remove secondary's vsi from primary's prune list * @lag: primary interface's ice_lag struct * @event_pf: PF struct for unlinking interface */ static void ice_lag_del_prune_list(struct ice_lag *lag, struct ice_pf *event_pf) { u16 num_vsi, vsi_num, vsi_idx, rule_buf_sz, vsi_list_id; struct ice_sw_rule_vsi_list *s_rule = NULL; struct device *dev; num_vsi = 1; dev = ice_pf_to_dev(lag->pf); vsi_num = event_pf->vsi[0]->vsi_num; vsi_idx = lag->pf->vsi[0]->idx; if (!ice_find_vsi_list_entry(&lag->pf->hw, ICE_SW_LKUP_VLAN, vsi_idx, &vsi_list_id)) { dev_warn(dev, "Could not locate prune list when unwinding SRIOV LAG\n"); return; } rule_buf_sz = (u16)ICE_SW_RULE_VSI_LIST_SIZE(s_rule, num_vsi); s_rule = kzalloc(rule_buf_sz, GFP_KERNEL); if (!s_rule) { dev_warn(dev, "Error allocating prune list when unwinding SRIOV LAG\n"); return; } s_rule->hdr.type = cpu_to_le16(ICE_AQC_SW_RULES_T_PRUNE_LIST_CLEAR); s_rule->index = cpu_to_le16(vsi_list_id); s_rule->number_vsi = cpu_to_le16(num_vsi); s_rule->vsi[0] = cpu_to_le16(vsi_num); if (ice_aq_sw_rules(&event_pf->hw, (struct ice_aqc_sw_rules *)s_rule, rule_buf_sz, 1, ice_aqc_opc_update_sw_rules, NULL)) dev_warn(dev, "Error clearing VSI prune list\n"); kfree(s_rule); } /** * ice_lag_init_feature_support_flag - Check for NVM support for LAG * @pf: PF struct */ static void ice_lag_init_feature_support_flag(struct ice_pf *pf) { struct ice_hw_common_caps *caps; caps = &pf->hw.dev_caps.common_cap; if (caps->roce_lag) ice_set_feature_support(pf, ICE_F_ROCE_LAG); else ice_clear_feature_support(pf, ICE_F_ROCE_LAG); if (caps->sriov_lag) ice_set_feature_support(pf, ICE_F_SRIOV_LAG); else ice_clear_feature_support(pf, ICE_F_SRIOV_LAG); } /** * ice_lag_changeupper_event - handle LAG changeupper event * @lag: LAG info struct * @ptr: opaque pointer data */ static void ice_lag_changeupper_event(struct ice_lag *lag, void *ptr) { struct netdev_notifier_changeupper_info *info; struct ice_lag *primary_lag; struct net_device *netdev; info = ptr; netdev = netdev_notifier_info_to_dev(ptr); /* not for this netdev */ if (netdev != lag->netdev) return; primary_lag = ice_lag_find_primary(lag); if (info->linking) { lag->upper_netdev = info->upper_dev; /* If there is not already a primary interface in the LAG, * then mark this one as primary. */ if (!primary_lag) { lag->primary = true; /* Configure primary's SWID to be shared */ ice_lag_primary_swid(lag, true); primary_lag = lag; } else { u16 swid; swid = primary_lag->pf->hw.port_info->sw_id; ice_lag_set_swid(swid, lag, true); ice_lag_add_prune_list(primary_lag, lag->pf); } /* add filter for primary control packets */ ice_lag_cfg_cp_fltr(lag, true); } else { if (!primary_lag && lag->primary) primary_lag = lag; if (!lag->primary) { ice_lag_set_swid(0, lag, false); } else { if (primary_lag && lag->primary) { ice_lag_primary_swid(lag, false); ice_lag_del_prune_list(primary_lag, lag->pf); } } /* remove filter for control packets */ ice_lag_cfg_cp_fltr(lag, false); } } /** * ice_lag_monitor_link - monitor interfaces entering/leaving the aggregate * @lag: lag info struct * @ptr: opaque data containing notifier event * * This function only operates after a primary has been set. */ static void ice_lag_monitor_link(struct ice_lag *lag, void *ptr) { struct netdev_notifier_changeupper_info *info; struct ice_hw *prim_hw, *active_hw; struct net_device *event_netdev; struct ice_pf *pf; u8 prim_port; if (!lag->primary) return; event_netdev = netdev_notifier_info_to_dev(ptr); if (!netif_is_same_ice(lag->pf, event_netdev)) return; pf = lag->pf; prim_hw = &pf->hw; prim_port = prim_hw->port_info->lport; info = (struct netdev_notifier_changeupper_info *)ptr; if (info->upper_dev != lag->upper_netdev) return; if (!info->linking) { /* Since there are only two interfaces allowed in SRIOV+LAG, if * one port is leaving, then nodes need to be on primary * interface. */ if (prim_port != lag->active_port && lag->active_port != ICE_LAG_INVALID_PORT) { active_hw = ice_lag_find_hw_by_lport(lag, lag->active_port); ice_lag_reclaim_vf_nodes(lag, active_hw); lag->active_port = ICE_LAG_INVALID_PORT; } } } /** * ice_lag_monitor_active - main PF keep track of which port is active * @lag: lag info struct * @ptr: opaque data containing notifier event * * This function is for the primary PF to monitor changes in which port is * active and handle changes for SRIOV VF functionality */ static void ice_lag_monitor_active(struct ice_lag *lag, void *ptr) { struct net_device *event_netdev, *event_upper; struct netdev_notifier_bonding_info *info; struct netdev_bonding_info *bonding_info; struct ice_netdev_priv *event_np; struct ice_pf *pf, *event_pf; u8 prim_port, event_port; if (!lag->primary) return; pf = lag->pf; if (!pf) return; event_netdev = netdev_notifier_info_to_dev(ptr); rcu_read_lock(); event_upper = netdev_master_upper_dev_get_rcu(event_netdev); rcu_read_unlock(); if (!netif_is_ice(event_netdev) || event_upper != lag->upper_netdev) return; event_np = netdev_priv(event_netdev); event_pf = event_np->vsi->back; event_port = event_pf->hw.port_info->lport; prim_port = pf->hw.port_info->lport; info = (struct netdev_notifier_bonding_info *)ptr; bonding_info = &info->bonding_info; if (!bonding_info->slave.state) { /* if no port is currently active, then nodes and filters exist * on primary port, check if we need to move them */ if (lag->active_port == ICE_LAG_INVALID_PORT) { if (event_port != prim_port) ice_lag_move_vf_nodes(lag, prim_port, event_port); lag->active_port = event_port; return; } /* active port is already set and is current event port */ if (lag->active_port == event_port) return; /* new active port */ ice_lag_move_vf_nodes(lag, lag->active_port, event_port); lag->active_port = event_port; } else { /* port not set as currently active (e.g. new active port * has already claimed the nodes and filters */ if (lag->active_port != event_port) return; /* This is the case when neither port is active (both link down) * Link down on the bond - set active port to invalid and move * nodes and filters back to primary if not already there */ if (event_port != prim_port) ice_lag_move_vf_nodes(lag, event_port, prim_port); lag->active_port = ICE_LAG_INVALID_PORT; } } /** * ice_lag_chk_comp - evaluate bonded interface for feature support * @lag: lag info struct * @ptr: opaque data for netdev event info */ static bool ice_lag_chk_comp(struct ice_lag *lag, void *ptr) { struct net_device *event_netdev, *event_upper; struct netdev_notifier_bonding_info *info; struct netdev_bonding_info *bonding_info; struct list_head *tmp; struct device *dev; int count = 0; if (!lag->primary) return true; event_netdev = netdev_notifier_info_to_dev(ptr); rcu_read_lock(); event_upper = netdev_master_upper_dev_get_rcu(event_netdev); rcu_read_unlock(); if (event_upper != lag->upper_netdev) return true; dev = ice_pf_to_dev(lag->pf); /* only supporting switchdev mode for SRIOV VF LAG. * primary interface has to be in switchdev mode */ if (!ice_is_switchdev_running(lag->pf)) { dev_info(dev, "Primary interface not in switchdev mode - VF LAG disabled\n"); return false; } info = (struct netdev_notifier_bonding_info *)ptr; bonding_info = &info->bonding_info; lag->bond_mode = bonding_info->master.bond_mode; if (lag->bond_mode != BOND_MODE_ACTIVEBACKUP) { dev_info(dev, "Bond Mode not ACTIVE-BACKUP - VF LAG disabled\n"); return false; } list_for_each(tmp, lag->netdev_head) { struct ice_dcbx_cfg *dcb_cfg, *peer_dcb_cfg; struct ice_lag_netdev_list *entry; struct ice_netdev_priv *peer_np; struct net_device *peer_netdev; struct ice_vsi *vsi, *peer_vsi; struct ice_pf *peer_pf; entry = list_entry(tmp, struct ice_lag_netdev_list, node); peer_netdev = entry->netdev; if (!netif_is_ice(peer_netdev)) { dev_info(dev, "Found %s non-ice netdev in LAG - VF LAG disabled\n", netdev_name(peer_netdev)); return false; } count++; if (count > 2) { dev_info(dev, "Found more than two netdevs in LAG - VF LAG disabled\n"); return false; } peer_np = netdev_priv(peer_netdev); vsi = ice_get_main_vsi(lag->pf); peer_vsi = peer_np->vsi; if (lag->pf->pdev->bus != peer_vsi->back->pdev->bus || lag->pf->pdev->slot != peer_vsi->back->pdev->slot) { dev_info(dev, "Found %s on different device in LAG - VF LAG disabled\n", netdev_name(peer_netdev)); return false; } dcb_cfg = &vsi->port_info->qos_cfg.local_dcbx_cfg; peer_dcb_cfg = &peer_vsi->port_info->qos_cfg.local_dcbx_cfg; if (memcmp(dcb_cfg, peer_dcb_cfg, sizeof(struct ice_dcbx_cfg))) { dev_info(dev, "Found %s with different DCB in LAG - VF LAG disabled\n", netdev_name(peer_netdev)); return false; } peer_pf = peer_vsi->back; if (test_bit(ICE_FLAG_FW_LLDP_AGENT, peer_pf->flags)) { dev_warn(dev, "Found %s with FW LLDP agent active - VF LAG disabled\n", netdev_name(peer_netdev)); return false; } } return true; } /** * ice_lag_unregister - handle netdev unregister events * @lag: LAG info struct * @event_netdev: netdev struct for target of notifier event */ static void ice_lag_unregister(struct ice_lag *lag, struct net_device *event_netdev) { struct ice_netdev_priv *np; struct ice_pf *event_pf; struct ice_lag *p_lag; p_lag = ice_lag_find_primary(lag); np = netdev_priv(event_netdev); event_pf = np->vsi->back; if (p_lag) { if (p_lag->active_port != p_lag->pf->hw.port_info->lport && p_lag->active_port != ICE_LAG_INVALID_PORT) { struct ice_hw *active_hw; active_hw = ice_lag_find_hw_by_lport(lag, p_lag->active_port); if (active_hw) ice_lag_reclaim_vf_nodes(p_lag, active_hw); lag->active_port = ICE_LAG_INVALID_PORT; } } /* primary processing for primary */ if (lag->primary && lag->netdev == event_netdev) ice_lag_primary_swid(lag, false); /* primary processing for secondary */ if (lag->primary && lag->netdev != event_netdev) ice_lag_del_prune_list(lag, event_pf); /* secondary processing for secondary */ if (!lag->primary && lag->netdev == event_netdev) ice_lag_set_swid(0, lag, false); } /** * ice_lag_monitor_rdma - set and clear rdma functionality * @lag: pointer to lag struct * @ptr: opaque data for netdev event info */ static void ice_lag_monitor_rdma(struct ice_lag *lag, void *ptr) { struct netdev_notifier_changeupper_info *info; struct net_device *netdev; info = ptr; netdev = netdev_notifier_info_to_dev(ptr); if (netdev != lag->netdev) return; if (info->linking) ice_clear_rdma_cap(lag->pf); else ice_set_rdma_cap(lag->pf); } /** * ice_lag_chk_disabled_bond - monitor interfaces entering/leaving disabled bond * @lag: lag info struct * @ptr: opaque data containing event * * as interfaces enter a bond - determine if the bond is currently * SRIOV LAG compliant and flag if not. As interfaces leave the * bond, reset their compliant status. */ static void ice_lag_chk_disabled_bond(struct ice_lag *lag, void *ptr) { struct net_device *netdev = netdev_notifier_info_to_dev(ptr); struct netdev_notifier_changeupper_info *info = ptr; struct ice_lag *prim_lag; if (netdev != lag->netdev) return; if (info->linking) { prim_lag = ice_lag_find_primary(lag); if (prim_lag && !ice_is_feature_supported(prim_lag->pf, ICE_F_SRIOV_LAG)) { ice_clear_feature_support(lag->pf, ICE_F_SRIOV_LAG); netdev_info(netdev, "Interface added to non-compliant SRIOV LAG aggregate\n"); } } else { ice_lag_init_feature_support_flag(lag->pf); } } /** * ice_lag_disable_sriov_bond - set members of bond as not supporting SRIOV LAG * @lag: primary interfaces lag struct */ static void ice_lag_disable_sriov_bond(struct ice_lag *lag) { struct ice_lag_netdev_list *entry; struct ice_netdev_priv *np; struct net_device *netdev; struct ice_pf *pf; list_for_each_entry(entry, lag->netdev_head, node) { netdev = entry->netdev; np = netdev_priv(netdev); pf = np->vsi->back; ice_clear_feature_support(pf, ICE_F_SRIOV_LAG); } } /** * ice_lag_process_event - process a task assigned to the lag_wq * @work: pointer to work_struct */ static void ice_lag_process_event(struct work_struct *work) { struct netdev_notifier_changeupper_info *info; struct ice_lag_work *lag_work; struct net_device *netdev; struct list_head *tmp, *n; struct ice_pf *pf; lag_work = container_of(work, struct ice_lag_work, lag_task); pf = lag_work->lag->pf; mutex_lock(&pf->lag_mutex); lag_work->lag->netdev_head = &lag_work->netdev_list.node; switch (lag_work->event) { case NETDEV_CHANGEUPPER: info = &lag_work->info.changeupper_info; ice_lag_chk_disabled_bond(lag_work->lag, info); if (ice_is_feature_supported(pf, ICE_F_SRIOV_LAG)) { ice_lag_monitor_link(lag_work->lag, info); ice_lag_changeupper_event(lag_work->lag, info); ice_lag_link_unlink(lag_work->lag, info); } ice_lag_monitor_rdma(lag_work->lag, info); break; case NETDEV_BONDING_INFO: if (ice_is_feature_supported(pf, ICE_F_SRIOV_LAG)) { if (!ice_lag_chk_comp(lag_work->lag, &lag_work->info.bonding_info)) { netdev = lag_work->info.bonding_info.info.dev; ice_lag_disable_sriov_bond(lag_work->lag); ice_lag_unregister(lag_work->lag, netdev); goto lag_cleanup; } ice_lag_monitor_active(lag_work->lag, &lag_work->info.bonding_info); ice_lag_cfg_pf_fltrs(lag_work->lag, &lag_work->info.bonding_info); } ice_lag_info_event(lag_work->lag, &lag_work->info.bonding_info); break; case NETDEV_UNREGISTER: if (ice_is_feature_supported(pf, ICE_F_SRIOV_LAG)) { netdev = lag_work->info.bonding_info.info.dev; if ((netdev == lag_work->lag->netdev || lag_work->lag->primary) && lag_work->lag->bonded) ice_lag_unregister(lag_work->lag, netdev); } break; default: break; } lag_cleanup: /* cleanup resources allocated for this work item */ list_for_each_safe(tmp, n, &lag_work->netdev_list.node) { struct ice_lag_netdev_list *entry; entry = list_entry(tmp, struct ice_lag_netdev_list, node); list_del(&entry->node); kfree(entry); } lag_work->lag->netdev_head = NULL; mutex_unlock(&pf->lag_mutex); kfree(lag_work); } /** * ice_lag_event_handler - handle LAG events from netdev * @notif_blk: notifier block registered by this netdev * @event: event type * @ptr: opaque data containing notifier event */ static int ice_lag_event_handler(struct notifier_block *notif_blk, unsigned long event, void *ptr) { struct net_device *netdev = netdev_notifier_info_to_dev(ptr); struct net_device *upper_netdev; struct ice_lag_work *lag_work; struct ice_lag *lag; if (!netif_is_ice(netdev)) return NOTIFY_DONE; if (event != NETDEV_CHANGEUPPER && event != NETDEV_BONDING_INFO && event != NETDEV_UNREGISTER) return NOTIFY_DONE; if (!(netdev->priv_flags & IFF_BONDING)) return NOTIFY_DONE; lag = container_of(notif_blk, struct ice_lag, notif_block); if (!lag->netdev) return NOTIFY_DONE; if (!net_eq(dev_net(netdev), &init_net)) return NOTIFY_DONE; /* This memory will be freed at the end of ice_lag_process_event */ lag_work = kzalloc(sizeof(*lag_work), GFP_KERNEL); if (!lag_work) return -ENOMEM; lag_work->event_netdev = netdev; lag_work->lag = lag; lag_work->event = event; if (event == NETDEV_CHANGEUPPER) { struct netdev_notifier_changeupper_info *info; info = ptr; upper_netdev = info->upper_dev; } else { upper_netdev = netdev_master_upper_dev_get(netdev); } INIT_LIST_HEAD(&lag_work->netdev_list.node); if (upper_netdev) { struct ice_lag_netdev_list *nd_list; struct net_device *tmp_nd; rcu_read_lock(); for_each_netdev_in_bond_rcu(upper_netdev, tmp_nd) { nd_list = kzalloc(sizeof(*nd_list), GFP_KERNEL); if (!nd_list) break; nd_list->netdev = tmp_nd; list_add(&nd_list->node, &lag_work->netdev_list.node); } rcu_read_unlock(); } switch (event) { case NETDEV_CHANGEUPPER: lag_work->info.changeupper_info = *((struct netdev_notifier_changeupper_info *)ptr); break; case NETDEV_BONDING_INFO: lag_work->info.bonding_info = *((struct netdev_notifier_bonding_info *)ptr); break; default: lag_work->info.notifier_info = *((struct netdev_notifier_info *)ptr); break; } INIT_WORK(&lag_work->lag_task, ice_lag_process_event); queue_work(ice_lag_wq, &lag_work->lag_task); return NOTIFY_DONE; } /** * ice_register_lag_handler - register LAG handler on netdev * @lag: LAG struct */ static int ice_register_lag_handler(struct ice_lag *lag) { struct device *dev = ice_pf_to_dev(lag->pf); struct notifier_block *notif_blk; notif_blk = &lag->notif_block; if (!notif_blk->notifier_call) { notif_blk->notifier_call = ice_lag_event_handler; if (register_netdevice_notifier(notif_blk)) { notif_blk->notifier_call = NULL; dev_err(dev, "FAIL register LAG event handler!\n"); return -EINVAL; } dev_dbg(dev, "LAG event handler registered\n"); } return 0; } /** * ice_unregister_lag_handler - unregister LAG handler on netdev * @lag: LAG struct */ static void ice_unregister_lag_handler(struct ice_lag *lag) { struct device *dev = ice_pf_to_dev(lag->pf); struct notifier_block *notif_blk; notif_blk = &lag->notif_block; if (notif_blk->notifier_call) { unregister_netdevice_notifier(notif_blk); dev_dbg(dev, "LAG event handler unregistered\n"); } } /** * ice_create_lag_recipe * @hw: pointer to HW struct * @rid: pointer to u16 to pass back recipe index * @base_recipe: recipe to base the new recipe on * @prio: priority for new recipe * * function returns 0 on error */ static int ice_create_lag_recipe(struct ice_hw *hw, u16 *rid, const u8 *base_recipe, u8 prio) { struct ice_aqc_recipe_data_elem *new_rcp; int err; err = ice_alloc_recipe(hw, rid); if (err) return err; new_rcp = kzalloc(ICE_RECIPE_LEN * ICE_MAX_NUM_RECIPES, GFP_KERNEL); if (!new_rcp) return -ENOMEM; memcpy(new_rcp, base_recipe, ICE_RECIPE_LEN); new_rcp->content.act_ctrl_fwd_priority = prio; new_rcp->content.rid = *rid | ICE_AQ_RECIPE_ID_IS_ROOT; new_rcp->recipe_indx = *rid; bitmap_zero((unsigned long *)new_rcp->recipe_bitmap, ICE_MAX_NUM_RECIPES); set_bit(*rid, (unsigned long *)new_rcp->recipe_bitmap); err = ice_aq_add_recipe(hw, new_rcp, 1, NULL); if (err) *rid = 0; kfree(new_rcp); return err; } /** * ice_lag_move_vf_nodes_tc_sync - move a VF's nodes for a tc during reset * @lag: primary interfaces lag struct * @dest_hw: HW struct for destination's interface * @vsi_num: VSI index in PF space * @tc: traffic class to move */ static void ice_lag_move_vf_nodes_tc_sync(struct ice_lag *lag, struct ice_hw *dest_hw, u16 vsi_num, u8 tc) { u16 numq, valq, buf_size, num_moved, qbuf_size; struct device *dev = ice_pf_to_dev(lag->pf); struct ice_aqc_cfg_txqs_buf *qbuf; struct ice_aqc_move_elem *buf; struct ice_sched_node *n_prt; __le32 teid, parent_teid; struct ice_vsi_ctx *ctx; struct ice_hw *hw; u32 tmp_teid; hw = &lag->pf->hw; ctx = ice_get_vsi_ctx(hw, vsi_num); if (!ctx) { dev_warn(dev, "LAG rebuild failed after reset due to VSI Context failure\n"); return; } if (!ctx->sched.vsi_node[tc]) return; numq = ctx->num_lan_q_entries[tc]; teid = ctx->sched.vsi_node[tc]->info.node_teid; tmp_teid = le32_to_cpu(teid); parent_teid = ctx->sched.vsi_node[tc]->info.parent_teid; if (!tmp_teid || !numq) return; if (ice_sched_suspend_resume_elems(hw, 1, &tmp_teid, true)) dev_dbg(dev, "Problem suspending traffic during reset rebuild\n"); /* reconfig queues for new port */ qbuf_size = struct_size(qbuf, queue_info, numq); qbuf = kzalloc(qbuf_size, GFP_KERNEL); if (!qbuf) { dev_warn(dev, "Failure allocating VF queue recfg buffer for reset rebuild\n"); goto resume_sync; } /* add the per queue info for the reconfigure command buffer */ valq = ice_lag_qbuf_recfg(hw, qbuf, vsi_num, numq, tc); if (!valq) { dev_warn(dev, "Failure to reconfig queues for LAG reset rebuild\n"); goto sync_none; } if (ice_aq_cfg_lan_txq(hw, qbuf, qbuf_size, numq, hw->port_info->lport, dest_hw->port_info->lport, NULL)) { dev_warn(dev, "Failure to configure queues for LAG reset rebuild\n"); goto sync_qerr; } sync_none: kfree(qbuf); /* find parent in destination tree */ n_prt = ice_lag_get_sched_parent(dest_hw, tc); if (!n_prt) goto resume_sync; /* Move node to new parent */ buf_size = struct_size(buf, teid, 1); buf = kzalloc(buf_size, GFP_KERNEL); if (!buf) { dev_warn(dev, "Failure to alloc for VF node move in reset rebuild\n"); goto resume_sync; } buf->hdr.src_parent_teid = parent_teid; buf->hdr.dest_parent_teid = n_prt->info.node_teid; buf->hdr.num_elems = cpu_to_le16(1); buf->hdr.mode = ICE_AQC_MOVE_ELEM_MODE_KEEP_OWN; buf->teid[0] = teid; if (ice_aq_move_sched_elems(&lag->pf->hw, 1, buf, buf_size, &num_moved, NULL)) dev_warn(dev, "Failure to move VF nodes for LAG reset rebuild\n"); else ice_sched_update_parent(n_prt, ctx->sched.vsi_node[tc]); kfree(buf); goto resume_sync; sync_qerr: kfree(qbuf); resume_sync: if (ice_sched_suspend_resume_elems(hw, 1, &tmp_teid, false)) dev_warn(dev, "Problem restarting traffic for LAG node reset rebuild\n"); } /** * ice_lag_move_vf_nodes_sync - move vf nodes to active interface * @lag: primary interfaces lag struct * @dest_hw: lport value for currently active port * * This function is used in a reset context, outside of event handling, * to move the VF nodes to the secondary interface when that interface * is the active interface during a reset rebuild */ static void ice_lag_move_vf_nodes_sync(struct ice_lag *lag, struct ice_hw *dest_hw) { struct ice_pf *pf; int i, tc; if (!lag->primary || !dest_hw) return; pf = lag->pf; ice_for_each_vsi(pf, i) if (pf->vsi[i] && (pf->vsi[i]->type == ICE_VSI_VF || pf->vsi[i]->type == ICE_VSI_SWITCHDEV_CTRL)) ice_for_each_traffic_class(tc) ice_lag_move_vf_nodes_tc_sync(lag, dest_hw, i, tc); } /** * ice_init_lag - initialize support for LAG * @pf: PF struct * * Alloc memory for LAG structs and initialize the elements. * Memory will be freed in ice_deinit_lag */ int ice_init_lag(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); struct ice_lag *lag; struct ice_vsi *vsi; u64 recipe_bits = 0; int n, err; ice_lag_init_feature_support_flag(pf); pf->lag = kzalloc(sizeof(*lag), GFP_KERNEL); if (!pf->lag) return -ENOMEM; lag = pf->lag; vsi = ice_get_main_vsi(pf); if (!vsi) { dev_err(dev, "couldn't get main vsi, link aggregation init fail\n"); err = -EIO; goto lag_error; } lag->pf = pf; lag->netdev = vsi->netdev; lag->role = ICE_LAG_NONE; lag->active_port = ICE_LAG_INVALID_PORT; lag->bonded = false; lag->upper_netdev = NULL; lag->notif_block.notifier_call = NULL; err = ice_register_lag_handler(lag); if (err) { dev_warn(dev, "INIT LAG: Failed to register event handler\n"); goto lag_error; } err = ice_create_lag_recipe(&pf->hw, &lag->pf_recipe, ice_dflt_vsi_rcp, 1); if (err) goto lag_error; /* associate recipes to profiles */ for (n = 0; n < ICE_PROFID_IPV6_GTPU_IPV6_TCP_INNER; n++) { err = ice_aq_get_recipe_to_profile(&pf->hw, n, (u8 *)&recipe_bits, NULL); if (err) continue; if (recipe_bits & BIT(ICE_SW_LKUP_DFLT)) { recipe_bits |= BIT(lag->pf_recipe); ice_aq_map_recipe_to_profile(&pf->hw, n, (u8 *)&recipe_bits, NULL); } } ice_display_lag_info(lag); dev_dbg(dev, "INIT LAG complete\n"); return 0; lag_error: kfree(lag); pf->lag = NULL; return err; } /** * ice_deinit_lag - Clean up LAG * @pf: PF struct * * Clean up kernel LAG info and free memory * This function is meant to only be called on driver remove/shutdown */ void ice_deinit_lag(struct ice_pf *pf) { struct ice_lag *lag; lag = pf->lag; if (!lag) return; if (lag->pf) ice_unregister_lag_handler(lag); flush_workqueue(ice_lag_wq); ice_free_hw_res(&pf->hw, ICE_AQC_RES_TYPE_RECIPE, 1, &pf->lag->pf_recipe); kfree(lag); pf->lag = NULL; } /** * ice_lag_rebuild - rebuild lag resources after reset * @pf: pointer to local pf struct * * PF resets are promoted to CORER resets when interface in an aggregate. This * means that we need to rebuild the PF resources for the interface. Since * this will happen outside the normal event processing, need to acquire the lag * lock. * * This function will also evaluate the VF resources if this is the primary * interface. */ void ice_lag_rebuild(struct ice_pf *pf) { struct ice_lag_netdev_list ndlist; struct ice_lag *lag, *prim_lag; struct list_head *tmp, *n; u8 act_port, loc_port; if (!pf->lag || !pf->lag->bonded) return; mutex_lock(&pf->lag_mutex); lag = pf->lag; if (lag->primary) { prim_lag = lag; } else { struct ice_lag_netdev_list *nl; struct net_device *tmp_nd; INIT_LIST_HEAD(&ndlist.node); rcu_read_lock(); for_each_netdev_in_bond_rcu(lag->upper_netdev, tmp_nd) { nl = kzalloc(sizeof(*nl), GFP_KERNEL); if (!nl) break; nl->netdev = tmp_nd; list_add(&nl->node, &ndlist.node); } rcu_read_unlock(); lag->netdev_head = &ndlist.node; prim_lag = ice_lag_find_primary(lag); } if (!prim_lag) { dev_dbg(ice_pf_to_dev(pf), "No primary interface in aggregate, can't rebuild\n"); goto lag_rebuild_out; } act_port = prim_lag->active_port; loc_port = lag->pf->hw.port_info->lport; /* configure SWID for this port */ if (lag->primary) { ice_lag_primary_swid(lag, true); } else { ice_lag_set_swid(prim_lag->pf->hw.port_info->sw_id, lag, true); ice_lag_add_prune_list(prim_lag, pf); if (act_port == loc_port) ice_lag_move_vf_nodes_sync(prim_lag, &pf->hw); } ice_lag_cfg_cp_fltr(lag, true); if (lag->pf_rule_id) if (ice_lag_cfg_dflt_fltr(lag, true)) dev_err(ice_pf_to_dev(pf), "Error adding default VSI rule in rebuild\n"); ice_clear_rdma_cap(pf); lag_rebuild_out: list_for_each_safe(tmp, n, &ndlist.node) { struct ice_lag_netdev_list *entry; entry = list_entry(tmp, struct ice_lag_netdev_list, node); list_del(&entry->node); kfree(entry); } mutex_unlock(&pf->lag_mutex); }
linux-master
drivers/net/ethernet/intel/ice/ice_lag.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2019-2021, Intel Corporation. */ #include "ice.h" #include "ice_tc_lib.h" #include "ice_fltr.h" #include "ice_lib.h" #include "ice_protocol_type.h" #define ICE_TC_METADATA_LKUP_IDX 0 /** * ice_tc_count_lkups - determine lookup count for switch filter * @flags: TC-flower flags * @headers: Pointer to TC flower filter header structure * @fltr: Pointer to outer TC filter structure * * Determine lookup count based on TC flower input for switch filter. */ static int ice_tc_count_lkups(u32 flags, struct ice_tc_flower_lyr_2_4_hdrs *headers, struct ice_tc_flower_fltr *fltr) { int lkups_cnt = 1; /* 0th lookup is metadata */ /* Always add metadata as the 0th lookup. Included elements: * - Direction flag (always present) * - ICE_TC_FLWR_FIELD_VLAN_TPID (present if specified) * - Tunnel flag (present if tunnel) */ if (flags & ICE_TC_FLWR_FIELD_TENANT_ID) lkups_cnt++; if (flags & ICE_TC_FLWR_FIELD_ENC_DST_MAC) lkups_cnt++; if (flags & ICE_TC_FLWR_FIELD_ENC_OPTS) lkups_cnt++; if (flags & (ICE_TC_FLWR_FIELD_ENC_SRC_IPV4 | ICE_TC_FLWR_FIELD_ENC_DEST_IPV4 | ICE_TC_FLWR_FIELD_ENC_SRC_IPV6 | ICE_TC_FLWR_FIELD_ENC_DEST_IPV6)) lkups_cnt++; if (flags & (ICE_TC_FLWR_FIELD_ENC_IP_TOS | ICE_TC_FLWR_FIELD_ENC_IP_TTL)) lkups_cnt++; if (flags & ICE_TC_FLWR_FIELD_ENC_DEST_L4_PORT) lkups_cnt++; if (flags & ICE_TC_FLWR_FIELD_ETH_TYPE_ID) lkups_cnt++; /* are MAC fields specified? */ if (flags & (ICE_TC_FLWR_FIELD_DST_MAC | ICE_TC_FLWR_FIELD_SRC_MAC)) lkups_cnt++; /* is VLAN specified? */ if (flags & (ICE_TC_FLWR_FIELD_VLAN | ICE_TC_FLWR_FIELD_VLAN_PRIO)) lkups_cnt++; /* is CVLAN specified? */ if (flags & (ICE_TC_FLWR_FIELD_CVLAN | ICE_TC_FLWR_FIELD_CVLAN_PRIO)) lkups_cnt++; /* are PPPoE options specified? */ if (flags & (ICE_TC_FLWR_FIELD_PPPOE_SESSID | ICE_TC_FLWR_FIELD_PPP_PROTO)) lkups_cnt++; /* are IPv[4|6] fields specified? */ if (flags & (ICE_TC_FLWR_FIELD_DEST_IPV4 | ICE_TC_FLWR_FIELD_SRC_IPV4 | ICE_TC_FLWR_FIELD_DEST_IPV6 | ICE_TC_FLWR_FIELD_SRC_IPV6)) lkups_cnt++; if (flags & (ICE_TC_FLWR_FIELD_IP_TOS | ICE_TC_FLWR_FIELD_IP_TTL)) lkups_cnt++; /* are L2TPv3 options specified? */ if (flags & ICE_TC_FLWR_FIELD_L2TPV3_SESSID) lkups_cnt++; /* is L4 (TCP/UDP/any other L4 protocol fields) specified? */ if (flags & (ICE_TC_FLWR_FIELD_DEST_L4_PORT | ICE_TC_FLWR_FIELD_SRC_L4_PORT)) lkups_cnt++; return lkups_cnt; } static enum ice_protocol_type ice_proto_type_from_mac(bool inner) { return inner ? ICE_MAC_IL : ICE_MAC_OFOS; } static enum ice_protocol_type ice_proto_type_from_etype(bool inner) { return inner ? ICE_ETYPE_IL : ICE_ETYPE_OL; } static enum ice_protocol_type ice_proto_type_from_ipv4(bool inner) { return inner ? ICE_IPV4_IL : ICE_IPV4_OFOS; } static enum ice_protocol_type ice_proto_type_from_ipv6(bool inner) { return inner ? ICE_IPV6_IL : ICE_IPV6_OFOS; } static enum ice_protocol_type ice_proto_type_from_l4_port(u16 ip_proto) { switch (ip_proto) { case IPPROTO_TCP: return ICE_TCP_IL; case IPPROTO_UDP: return ICE_UDP_ILOS; } return 0; } static enum ice_protocol_type ice_proto_type_from_tunnel(enum ice_tunnel_type type) { switch (type) { case TNL_VXLAN: return ICE_VXLAN; case TNL_GENEVE: return ICE_GENEVE; case TNL_GRETAP: return ICE_NVGRE; case TNL_GTPU: /* NO_PAY profiles will not work with GTP-U */ return ICE_GTP; case TNL_GTPC: return ICE_GTP_NO_PAY; default: return 0; } } static enum ice_sw_tunnel_type ice_sw_type_from_tunnel(enum ice_tunnel_type type) { switch (type) { case TNL_VXLAN: return ICE_SW_TUN_VXLAN; case TNL_GENEVE: return ICE_SW_TUN_GENEVE; case TNL_GRETAP: return ICE_SW_TUN_NVGRE; case TNL_GTPU: return ICE_SW_TUN_GTPU; case TNL_GTPC: return ICE_SW_TUN_GTPC; default: return ICE_NON_TUN; } } static u16 ice_check_supported_vlan_tpid(u16 vlan_tpid) { switch (vlan_tpid) { case ETH_P_8021Q: case ETH_P_8021AD: case ETH_P_QINQ1: return vlan_tpid; default: return 0; } } static int ice_tc_fill_tunnel_outer(u32 flags, struct ice_tc_flower_fltr *fltr, struct ice_adv_lkup_elem *list, int i) { struct ice_tc_flower_lyr_2_4_hdrs *hdr = &fltr->outer_headers; if (flags & ICE_TC_FLWR_FIELD_TENANT_ID) { u32 tenant_id; list[i].type = ice_proto_type_from_tunnel(fltr->tunnel_type); switch (fltr->tunnel_type) { case TNL_VXLAN: case TNL_GENEVE: tenant_id = be32_to_cpu(fltr->tenant_id) << 8; list[i].h_u.tnl_hdr.vni = cpu_to_be32(tenant_id); memcpy(&list[i].m_u.tnl_hdr.vni, "\xff\xff\xff\x00", 4); i++; break; case TNL_GRETAP: list[i].h_u.nvgre_hdr.tni_flow = fltr->tenant_id; memcpy(&list[i].m_u.nvgre_hdr.tni_flow, "\xff\xff\xff\xff", 4); i++; break; case TNL_GTPC: case TNL_GTPU: list[i].h_u.gtp_hdr.teid = fltr->tenant_id; memcpy(&list[i].m_u.gtp_hdr.teid, "\xff\xff\xff\xff", 4); i++; break; default: break; } } if (flags & ICE_TC_FLWR_FIELD_ENC_DST_MAC) { list[i].type = ice_proto_type_from_mac(false); ether_addr_copy(list[i].h_u.eth_hdr.dst_addr, hdr->l2_key.dst_mac); ether_addr_copy(list[i].m_u.eth_hdr.dst_addr, hdr->l2_mask.dst_mac); i++; } if (flags & ICE_TC_FLWR_FIELD_ENC_OPTS && (fltr->tunnel_type == TNL_GTPU || fltr->tunnel_type == TNL_GTPC)) { list[i].type = ice_proto_type_from_tunnel(fltr->tunnel_type); if (fltr->gtp_pdu_info_masks.pdu_type) { list[i].h_u.gtp_hdr.pdu_type = fltr->gtp_pdu_info_keys.pdu_type << 4; memcpy(&list[i].m_u.gtp_hdr.pdu_type, "\xf0", 1); } if (fltr->gtp_pdu_info_masks.qfi) { list[i].h_u.gtp_hdr.qfi = fltr->gtp_pdu_info_keys.qfi; memcpy(&list[i].m_u.gtp_hdr.qfi, "\x3f", 1); } i++; } if (flags & (ICE_TC_FLWR_FIELD_ENC_SRC_IPV4 | ICE_TC_FLWR_FIELD_ENC_DEST_IPV4)) { list[i].type = ice_proto_type_from_ipv4(false); if (flags & ICE_TC_FLWR_FIELD_ENC_SRC_IPV4) { list[i].h_u.ipv4_hdr.src_addr = hdr->l3_key.src_ipv4; list[i].m_u.ipv4_hdr.src_addr = hdr->l3_mask.src_ipv4; } if (flags & ICE_TC_FLWR_FIELD_ENC_DEST_IPV4) { list[i].h_u.ipv4_hdr.dst_addr = hdr->l3_key.dst_ipv4; list[i].m_u.ipv4_hdr.dst_addr = hdr->l3_mask.dst_ipv4; } i++; } if (flags & (ICE_TC_FLWR_FIELD_ENC_SRC_IPV6 | ICE_TC_FLWR_FIELD_ENC_DEST_IPV6)) { list[i].type = ice_proto_type_from_ipv6(false); if (flags & ICE_TC_FLWR_FIELD_ENC_SRC_IPV6) { memcpy(&list[i].h_u.ipv6_hdr.src_addr, &hdr->l3_key.src_ipv6_addr, sizeof(hdr->l3_key.src_ipv6_addr)); memcpy(&list[i].m_u.ipv6_hdr.src_addr, &hdr->l3_mask.src_ipv6_addr, sizeof(hdr->l3_mask.src_ipv6_addr)); } if (flags & ICE_TC_FLWR_FIELD_ENC_DEST_IPV6) { memcpy(&list[i].h_u.ipv6_hdr.dst_addr, &hdr->l3_key.dst_ipv6_addr, sizeof(hdr->l3_key.dst_ipv6_addr)); memcpy(&list[i].m_u.ipv6_hdr.dst_addr, &hdr->l3_mask.dst_ipv6_addr, sizeof(hdr->l3_mask.dst_ipv6_addr)); } i++; } if (fltr->inner_headers.l2_key.n_proto == htons(ETH_P_IP) && (flags & (ICE_TC_FLWR_FIELD_ENC_IP_TOS | ICE_TC_FLWR_FIELD_ENC_IP_TTL))) { list[i].type = ice_proto_type_from_ipv4(false); if (flags & ICE_TC_FLWR_FIELD_ENC_IP_TOS) { list[i].h_u.ipv4_hdr.tos = hdr->l3_key.tos; list[i].m_u.ipv4_hdr.tos = hdr->l3_mask.tos; } if (flags & ICE_TC_FLWR_FIELD_ENC_IP_TTL) { list[i].h_u.ipv4_hdr.time_to_live = hdr->l3_key.ttl; list[i].m_u.ipv4_hdr.time_to_live = hdr->l3_mask.ttl; } i++; } if (fltr->inner_headers.l2_key.n_proto == htons(ETH_P_IPV6) && (flags & (ICE_TC_FLWR_FIELD_ENC_IP_TOS | ICE_TC_FLWR_FIELD_ENC_IP_TTL))) { struct ice_ipv6_hdr *hdr_h, *hdr_m; hdr_h = &list[i].h_u.ipv6_hdr; hdr_m = &list[i].m_u.ipv6_hdr; list[i].type = ice_proto_type_from_ipv6(false); if (flags & ICE_TC_FLWR_FIELD_ENC_IP_TOS) { be32p_replace_bits(&hdr_h->be_ver_tc_flow, hdr->l3_key.tos, ICE_IPV6_HDR_TC_MASK); be32p_replace_bits(&hdr_m->be_ver_tc_flow, hdr->l3_mask.tos, ICE_IPV6_HDR_TC_MASK); } if (flags & ICE_TC_FLWR_FIELD_ENC_IP_TTL) { hdr_h->hop_limit = hdr->l3_key.ttl; hdr_m->hop_limit = hdr->l3_mask.ttl; } i++; } if ((flags & ICE_TC_FLWR_FIELD_ENC_DEST_L4_PORT) && hdr->l3_key.ip_proto == IPPROTO_UDP) { list[i].type = ICE_UDP_OF; list[i].h_u.l4_hdr.dst_port = hdr->l4_key.dst_port; list[i].m_u.l4_hdr.dst_port = hdr->l4_mask.dst_port; i++; } /* always fill matching on tunneled packets in metadata */ ice_rule_add_tunnel_metadata(&list[ICE_TC_METADATA_LKUP_IDX]); return i; } /** * ice_tc_fill_rules - fill filter rules based on TC fltr * @hw: pointer to HW structure * @flags: tc flower field flags * @tc_fltr: pointer to TC flower filter * @list: list of advance rule elements * @rule_info: pointer to information about rule * @l4_proto: pointer to information such as L4 proto type * * Fill ice_adv_lkup_elem list based on TC flower flags and * TC flower headers. This list should be used to add * advance filter in hardware. */ static int ice_tc_fill_rules(struct ice_hw *hw, u32 flags, struct ice_tc_flower_fltr *tc_fltr, struct ice_adv_lkup_elem *list, struct ice_adv_rule_info *rule_info, u16 *l4_proto) { struct ice_tc_flower_lyr_2_4_hdrs *headers = &tc_fltr->outer_headers; bool inner = false; u16 vlan_tpid = 0; int i = 1; /* 0th lookup is metadata */ rule_info->vlan_type = vlan_tpid; /* Always add direction metadata */ ice_rule_add_direction_metadata(&list[ICE_TC_METADATA_LKUP_IDX]); rule_info->tun_type = ice_sw_type_from_tunnel(tc_fltr->tunnel_type); if (tc_fltr->tunnel_type != TNL_LAST) { i = ice_tc_fill_tunnel_outer(flags, tc_fltr, list, i); headers = &tc_fltr->inner_headers; inner = true; } if (flags & ICE_TC_FLWR_FIELD_ETH_TYPE_ID) { list[i].type = ice_proto_type_from_etype(inner); list[i].h_u.ethertype.ethtype_id = headers->l2_key.n_proto; list[i].m_u.ethertype.ethtype_id = headers->l2_mask.n_proto; i++; } if (flags & (ICE_TC_FLWR_FIELD_DST_MAC | ICE_TC_FLWR_FIELD_SRC_MAC)) { struct ice_tc_l2_hdr *l2_key, *l2_mask; l2_key = &headers->l2_key; l2_mask = &headers->l2_mask; list[i].type = ice_proto_type_from_mac(inner); if (flags & ICE_TC_FLWR_FIELD_DST_MAC) { ether_addr_copy(list[i].h_u.eth_hdr.dst_addr, l2_key->dst_mac); ether_addr_copy(list[i].m_u.eth_hdr.dst_addr, l2_mask->dst_mac); } if (flags & ICE_TC_FLWR_FIELD_SRC_MAC) { ether_addr_copy(list[i].h_u.eth_hdr.src_addr, l2_key->src_mac); ether_addr_copy(list[i].m_u.eth_hdr.src_addr, l2_mask->src_mac); } i++; } /* copy VLAN info */ if (flags & (ICE_TC_FLWR_FIELD_VLAN | ICE_TC_FLWR_FIELD_VLAN_PRIO)) { if (flags & ICE_TC_FLWR_FIELD_CVLAN) list[i].type = ICE_VLAN_EX; else list[i].type = ICE_VLAN_OFOS; if (flags & ICE_TC_FLWR_FIELD_VLAN) { list[i].h_u.vlan_hdr.vlan = headers->vlan_hdr.vlan_id; list[i].m_u.vlan_hdr.vlan = cpu_to_be16(0x0FFF); } if (flags & ICE_TC_FLWR_FIELD_VLAN_PRIO) { if (flags & ICE_TC_FLWR_FIELD_VLAN) { list[i].m_u.vlan_hdr.vlan = cpu_to_be16(0xEFFF); } else { list[i].m_u.vlan_hdr.vlan = cpu_to_be16(0xE000); list[i].h_u.vlan_hdr.vlan = 0; } list[i].h_u.vlan_hdr.vlan |= headers->vlan_hdr.vlan_prio; } i++; } if (flags & ICE_TC_FLWR_FIELD_VLAN_TPID) { vlan_tpid = be16_to_cpu(headers->vlan_hdr.vlan_tpid); rule_info->vlan_type = ice_check_supported_vlan_tpid(vlan_tpid); ice_rule_add_vlan_metadata(&list[ICE_TC_METADATA_LKUP_IDX]); } if (flags & (ICE_TC_FLWR_FIELD_CVLAN | ICE_TC_FLWR_FIELD_CVLAN_PRIO)) { list[i].type = ICE_VLAN_IN; if (flags & ICE_TC_FLWR_FIELD_CVLAN) { list[i].h_u.vlan_hdr.vlan = headers->cvlan_hdr.vlan_id; list[i].m_u.vlan_hdr.vlan = cpu_to_be16(0x0FFF); } if (flags & ICE_TC_FLWR_FIELD_CVLAN_PRIO) { if (flags & ICE_TC_FLWR_FIELD_CVLAN) { list[i].m_u.vlan_hdr.vlan = cpu_to_be16(0xEFFF); } else { list[i].m_u.vlan_hdr.vlan = cpu_to_be16(0xE000); list[i].h_u.vlan_hdr.vlan = 0; } list[i].h_u.vlan_hdr.vlan |= headers->cvlan_hdr.vlan_prio; } i++; } if (flags & (ICE_TC_FLWR_FIELD_PPPOE_SESSID | ICE_TC_FLWR_FIELD_PPP_PROTO)) { struct ice_pppoe_hdr *vals, *masks; vals = &list[i].h_u.pppoe_hdr; masks = &list[i].m_u.pppoe_hdr; list[i].type = ICE_PPPOE; if (flags & ICE_TC_FLWR_FIELD_PPPOE_SESSID) { vals->session_id = headers->pppoe_hdr.session_id; masks->session_id = cpu_to_be16(0xFFFF); } if (flags & ICE_TC_FLWR_FIELD_PPP_PROTO) { vals->ppp_prot_id = headers->pppoe_hdr.ppp_proto; masks->ppp_prot_id = cpu_to_be16(0xFFFF); } i++; } /* copy L3 (IPv[4|6]: src, dest) address */ if (flags & (ICE_TC_FLWR_FIELD_DEST_IPV4 | ICE_TC_FLWR_FIELD_SRC_IPV4)) { struct ice_tc_l3_hdr *l3_key, *l3_mask; list[i].type = ice_proto_type_from_ipv4(inner); l3_key = &headers->l3_key; l3_mask = &headers->l3_mask; if (flags & ICE_TC_FLWR_FIELD_DEST_IPV4) { list[i].h_u.ipv4_hdr.dst_addr = l3_key->dst_ipv4; list[i].m_u.ipv4_hdr.dst_addr = l3_mask->dst_ipv4; } if (flags & ICE_TC_FLWR_FIELD_SRC_IPV4) { list[i].h_u.ipv4_hdr.src_addr = l3_key->src_ipv4; list[i].m_u.ipv4_hdr.src_addr = l3_mask->src_ipv4; } i++; } else if (flags & (ICE_TC_FLWR_FIELD_DEST_IPV6 | ICE_TC_FLWR_FIELD_SRC_IPV6)) { struct ice_ipv6_hdr *ipv6_hdr, *ipv6_mask; struct ice_tc_l3_hdr *l3_key, *l3_mask; list[i].type = ice_proto_type_from_ipv6(inner); ipv6_hdr = &list[i].h_u.ipv6_hdr; ipv6_mask = &list[i].m_u.ipv6_hdr; l3_key = &headers->l3_key; l3_mask = &headers->l3_mask; if (flags & ICE_TC_FLWR_FIELD_DEST_IPV6) { memcpy(&ipv6_hdr->dst_addr, &l3_key->dst_ipv6_addr, sizeof(l3_key->dst_ipv6_addr)); memcpy(&ipv6_mask->dst_addr, &l3_mask->dst_ipv6_addr, sizeof(l3_mask->dst_ipv6_addr)); } if (flags & ICE_TC_FLWR_FIELD_SRC_IPV6) { memcpy(&ipv6_hdr->src_addr, &l3_key->src_ipv6_addr, sizeof(l3_key->src_ipv6_addr)); memcpy(&ipv6_mask->src_addr, &l3_mask->src_ipv6_addr, sizeof(l3_mask->src_ipv6_addr)); } i++; } if (headers->l2_key.n_proto == htons(ETH_P_IP) && (flags & (ICE_TC_FLWR_FIELD_IP_TOS | ICE_TC_FLWR_FIELD_IP_TTL))) { list[i].type = ice_proto_type_from_ipv4(inner); if (flags & ICE_TC_FLWR_FIELD_IP_TOS) { list[i].h_u.ipv4_hdr.tos = headers->l3_key.tos; list[i].m_u.ipv4_hdr.tos = headers->l3_mask.tos; } if (flags & ICE_TC_FLWR_FIELD_IP_TTL) { list[i].h_u.ipv4_hdr.time_to_live = headers->l3_key.ttl; list[i].m_u.ipv4_hdr.time_to_live = headers->l3_mask.ttl; } i++; } if (headers->l2_key.n_proto == htons(ETH_P_IPV6) && (flags & (ICE_TC_FLWR_FIELD_IP_TOS | ICE_TC_FLWR_FIELD_IP_TTL))) { struct ice_ipv6_hdr *hdr_h, *hdr_m; hdr_h = &list[i].h_u.ipv6_hdr; hdr_m = &list[i].m_u.ipv6_hdr; list[i].type = ice_proto_type_from_ipv6(inner); if (flags & ICE_TC_FLWR_FIELD_IP_TOS) { be32p_replace_bits(&hdr_h->be_ver_tc_flow, headers->l3_key.tos, ICE_IPV6_HDR_TC_MASK); be32p_replace_bits(&hdr_m->be_ver_tc_flow, headers->l3_mask.tos, ICE_IPV6_HDR_TC_MASK); } if (flags & ICE_TC_FLWR_FIELD_IP_TTL) { hdr_h->hop_limit = headers->l3_key.ttl; hdr_m->hop_limit = headers->l3_mask.ttl; } i++; } if (flags & ICE_TC_FLWR_FIELD_L2TPV3_SESSID) { list[i].type = ICE_L2TPV3; list[i].h_u.l2tpv3_sess_hdr.session_id = headers->l2tpv3_hdr.session_id; list[i].m_u.l2tpv3_sess_hdr.session_id = cpu_to_be32(0xFFFFFFFF); i++; } /* copy L4 (src, dest) port */ if (flags & (ICE_TC_FLWR_FIELD_DEST_L4_PORT | ICE_TC_FLWR_FIELD_SRC_L4_PORT)) { struct ice_tc_l4_hdr *l4_key, *l4_mask; list[i].type = ice_proto_type_from_l4_port(headers->l3_key.ip_proto); l4_key = &headers->l4_key; l4_mask = &headers->l4_mask; if (flags & ICE_TC_FLWR_FIELD_DEST_L4_PORT) { list[i].h_u.l4_hdr.dst_port = l4_key->dst_port; list[i].m_u.l4_hdr.dst_port = l4_mask->dst_port; } if (flags & ICE_TC_FLWR_FIELD_SRC_L4_PORT) { list[i].h_u.l4_hdr.src_port = l4_key->src_port; list[i].m_u.l4_hdr.src_port = l4_mask->src_port; } i++; } return i; } /** * ice_tc_tun_get_type - get the tunnel type * @tunnel_dev: ptr to tunnel device * * This function detects appropriate tunnel_type if specified device is * tunnel device such as VXLAN/Geneve */ static int ice_tc_tun_get_type(struct net_device *tunnel_dev) { if (netif_is_vxlan(tunnel_dev)) return TNL_VXLAN; if (netif_is_geneve(tunnel_dev)) return TNL_GENEVE; if (netif_is_gretap(tunnel_dev) || netif_is_ip6gretap(tunnel_dev)) return TNL_GRETAP; /* Assume GTP-U by default in case of GTP netdev. * GTP-C may be selected later, based on enc_dst_port. */ if (netif_is_gtp(tunnel_dev)) return TNL_GTPU; return TNL_LAST; } bool ice_is_tunnel_supported(struct net_device *dev) { return ice_tc_tun_get_type(dev) != TNL_LAST; } static int ice_eswitch_tc_parse_action(struct ice_tc_flower_fltr *fltr, struct flow_action_entry *act) { struct ice_repr *repr; switch (act->id) { case FLOW_ACTION_DROP: fltr->action.fltr_act = ICE_DROP_PACKET; break; case FLOW_ACTION_REDIRECT: fltr->action.fltr_act = ICE_FWD_TO_VSI; if (ice_is_port_repr_netdev(act->dev)) { repr = ice_netdev_to_repr(act->dev); fltr->dest_vsi = repr->src_vsi; fltr->direction = ICE_ESWITCH_FLTR_INGRESS; } else if (netif_is_ice(act->dev) || ice_is_tunnel_supported(act->dev)) { fltr->direction = ICE_ESWITCH_FLTR_EGRESS; } else { NL_SET_ERR_MSG_MOD(fltr->extack, "Unsupported netdevice in switchdev mode"); return -EINVAL; } break; default: NL_SET_ERR_MSG_MOD(fltr->extack, "Unsupported action in switchdev mode"); return -EINVAL; } return 0; } static int ice_eswitch_add_tc_fltr(struct ice_vsi *vsi, struct ice_tc_flower_fltr *fltr) { struct ice_tc_flower_lyr_2_4_hdrs *headers = &fltr->outer_headers; struct ice_adv_rule_info rule_info = { 0 }; struct ice_rule_query_data rule_added; struct ice_hw *hw = &vsi->back->hw; struct ice_adv_lkup_elem *list; u32 flags = fltr->flags; int lkups_cnt; int ret; int i; if (!flags || (flags & ICE_TC_FLWR_FIELD_ENC_SRC_L4_PORT)) { NL_SET_ERR_MSG_MOD(fltr->extack, "Unsupported encap field(s)"); return -EOPNOTSUPP; } lkups_cnt = ice_tc_count_lkups(flags, headers, fltr); list = kcalloc(lkups_cnt, sizeof(*list), GFP_ATOMIC); if (!list) return -ENOMEM; i = ice_tc_fill_rules(hw, flags, fltr, list, &rule_info, NULL); if (i != lkups_cnt) { ret = -EINVAL; goto exit; } /* egress traffic is always redirect to uplink */ if (fltr->direction == ICE_ESWITCH_FLTR_EGRESS) fltr->dest_vsi = vsi->back->switchdev.uplink_vsi; rule_info.sw_act.fltr_act = fltr->action.fltr_act; if (fltr->action.fltr_act != ICE_DROP_PACKET) rule_info.sw_act.vsi_handle = fltr->dest_vsi->idx; /* For now, making priority to be highest, and it also becomes * the priority for recipe which will get created as a result of * new extraction sequence based on input set. * Priority '7' is max val for switch recipe, higher the number * results into order of switch rule evaluation. */ rule_info.priority = 7; rule_info.flags_info.act_valid = true; if (fltr->direction == ICE_ESWITCH_FLTR_INGRESS) { rule_info.sw_act.flag |= ICE_FLTR_RX; rule_info.sw_act.src = hw->pf_id; rule_info.flags_info.act = ICE_SINGLE_ACT_LB_ENABLE; } else { rule_info.sw_act.flag |= ICE_FLTR_TX; rule_info.sw_act.src = vsi->idx; rule_info.flags_info.act = ICE_SINGLE_ACT_LAN_ENABLE; } /* specify the cookie as filter_rule_id */ rule_info.fltr_rule_id = fltr->cookie; ret = ice_add_adv_rule(hw, list, lkups_cnt, &rule_info, &rule_added); if (ret == -EEXIST) { NL_SET_ERR_MSG_MOD(fltr->extack, "Unable to add filter because it already exist"); ret = -EINVAL; goto exit; } else if (ret) { NL_SET_ERR_MSG_MOD(fltr->extack, "Unable to add filter due to error"); goto exit; } /* store the output params, which are needed later for removing * advanced switch filter */ fltr->rid = rule_added.rid; fltr->rule_id = rule_added.rule_id; fltr->dest_vsi_handle = rule_added.vsi_handle; exit: kfree(list); return ret; } /** * ice_locate_vsi_using_queue - locate VSI using queue (forward to queue action) * @vsi: Pointer to VSI * @queue: Queue index * * Locate the VSI using specified "queue". When ADQ is not enabled, * always return input VSI, otherwise locate corresponding * VSI based on per channel "offset" and "qcount" */ struct ice_vsi * ice_locate_vsi_using_queue(struct ice_vsi *vsi, int queue) { int num_tc, tc; /* if ADQ is not active, passed VSI is the candidate VSI */ if (!ice_is_adq_active(vsi->back)) return vsi; /* Locate the VSI (it could still be main PF VSI or CHNL_VSI depending * upon queue number) */ num_tc = vsi->mqprio_qopt.qopt.num_tc; for (tc = 0; tc < num_tc; tc++) { int qcount = vsi->mqprio_qopt.qopt.count[tc]; int offset = vsi->mqprio_qopt.qopt.offset[tc]; if (queue >= offset && queue < offset + qcount) { /* for non-ADQ TCs, passed VSI is the candidate VSI */ if (tc < ICE_CHNL_START_TC) return vsi; else return vsi->tc_map_vsi[tc]; } } return NULL; } static struct ice_rx_ring * ice_locate_rx_ring_using_queue(struct ice_vsi *vsi, struct ice_tc_flower_fltr *tc_fltr) { u16 queue = tc_fltr->action.fwd.q.queue; return queue < vsi->num_rxq ? vsi->rx_rings[queue] : NULL; } /** * ice_tc_forward_action - Determine destination VSI and queue for the action * @vsi: Pointer to VSI * @tc_fltr: Pointer to TC flower filter structure * * Validates the tc forward action and determines the destination VSI and queue * for the forward action. */ static struct ice_vsi * ice_tc_forward_action(struct ice_vsi *vsi, struct ice_tc_flower_fltr *tc_fltr) { struct ice_rx_ring *ring = NULL; struct ice_vsi *dest_vsi = NULL; struct ice_pf *pf = vsi->back; struct device *dev; u32 tc_class; int q; dev = ice_pf_to_dev(pf); /* Get the destination VSI and/or destination queue and validate them */ switch (tc_fltr->action.fltr_act) { case ICE_FWD_TO_VSI: tc_class = tc_fltr->action.fwd.tc.tc_class; /* Select the destination VSI */ if (tc_class < ICE_CHNL_START_TC) { NL_SET_ERR_MSG_MOD(tc_fltr->extack, "Unable to add filter because of unsupported destination"); return ERR_PTR(-EOPNOTSUPP); } /* Locate ADQ VSI depending on hw_tc number */ dest_vsi = vsi->tc_map_vsi[tc_class]; break; case ICE_FWD_TO_Q: /* Locate the Rx queue */ ring = ice_locate_rx_ring_using_queue(vsi, tc_fltr); if (!ring) { dev_err(dev, "Unable to locate Rx queue for action fwd_to_queue: %u\n", tc_fltr->action.fwd.q.queue); return ERR_PTR(-EINVAL); } /* Determine destination VSI even though the action is * FWD_TO_QUEUE, because QUEUE is associated with VSI */ q = tc_fltr->action.fwd.q.queue; dest_vsi = ice_locate_vsi_using_queue(vsi, q); break; default: dev_err(dev, "Unable to add filter because of unsupported action %u (supported actions: fwd to tc, fwd to queue)\n", tc_fltr->action.fltr_act); return ERR_PTR(-EINVAL); } /* Must have valid dest_vsi (it could be main VSI or ADQ VSI) */ if (!dest_vsi) { dev_err(dev, "Unable to add filter because specified destination VSI doesn't exist\n"); return ERR_PTR(-EINVAL); } return dest_vsi; } /** * ice_add_tc_flower_adv_fltr - add appropriate filter rules * @vsi: Pointer to VSI * @tc_fltr: Pointer to TC flower filter structure * * based on filter parameters using Advance recipes supported * by OS package. */ static int ice_add_tc_flower_adv_fltr(struct ice_vsi *vsi, struct ice_tc_flower_fltr *tc_fltr) { struct ice_tc_flower_lyr_2_4_hdrs *headers = &tc_fltr->outer_headers; struct ice_adv_rule_info rule_info = {0}; struct ice_rule_query_data rule_added; struct ice_adv_lkup_elem *list; struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; u32 flags = tc_fltr->flags; struct ice_vsi *dest_vsi; struct device *dev; u16 lkups_cnt = 0; u16 l4_proto = 0; int ret = 0; u16 i = 0; dev = ice_pf_to_dev(pf); if (ice_is_safe_mode(pf)) { NL_SET_ERR_MSG_MOD(tc_fltr->extack, "Unable to add filter because driver is in safe mode"); return -EOPNOTSUPP; } if (!flags || (flags & (ICE_TC_FLWR_FIELD_ENC_DEST_IPV4 | ICE_TC_FLWR_FIELD_ENC_SRC_IPV4 | ICE_TC_FLWR_FIELD_ENC_DEST_IPV6 | ICE_TC_FLWR_FIELD_ENC_SRC_IPV6 | ICE_TC_FLWR_FIELD_ENC_SRC_L4_PORT))) { NL_SET_ERR_MSG_MOD(tc_fltr->extack, "Unsupported encap field(s)"); return -EOPNOTSUPP; } /* validate forwarding action VSI and queue */ if (ice_is_forward_action(tc_fltr->action.fltr_act)) { dest_vsi = ice_tc_forward_action(vsi, tc_fltr); if (IS_ERR(dest_vsi)) return PTR_ERR(dest_vsi); } lkups_cnt = ice_tc_count_lkups(flags, headers, tc_fltr); list = kcalloc(lkups_cnt, sizeof(*list), GFP_ATOMIC); if (!list) return -ENOMEM; i = ice_tc_fill_rules(hw, flags, tc_fltr, list, &rule_info, &l4_proto); if (i != lkups_cnt) { ret = -EINVAL; goto exit; } rule_info.sw_act.fltr_act = tc_fltr->action.fltr_act; /* specify the cookie as filter_rule_id */ rule_info.fltr_rule_id = tc_fltr->cookie; switch (tc_fltr->action.fltr_act) { case ICE_FWD_TO_VSI: rule_info.sw_act.vsi_handle = dest_vsi->idx; rule_info.priority = ICE_SWITCH_FLTR_PRIO_VSI; rule_info.sw_act.src = hw->pf_id; dev_dbg(dev, "add switch rule for TC:%u vsi_idx:%u, lkups_cnt:%u\n", tc_fltr->action.fwd.tc.tc_class, rule_info.sw_act.vsi_handle, lkups_cnt); break; case ICE_FWD_TO_Q: /* HW queue number in global space */ rule_info.sw_act.fwd_id.q_id = tc_fltr->action.fwd.q.hw_queue; rule_info.sw_act.vsi_handle = dest_vsi->idx; rule_info.priority = ICE_SWITCH_FLTR_PRIO_QUEUE; rule_info.sw_act.src = hw->pf_id; dev_dbg(dev, "add switch rule action to forward to queue:%u (HW queue %u), lkups_cnt:%u\n", tc_fltr->action.fwd.q.queue, tc_fltr->action.fwd.q.hw_queue, lkups_cnt); break; case ICE_DROP_PACKET: rule_info.sw_act.flag |= ICE_FLTR_RX; rule_info.sw_act.src = hw->pf_id; rule_info.priority = ICE_SWITCH_FLTR_PRIO_VSI; break; default: ret = -EOPNOTSUPP; goto exit; } ret = ice_add_adv_rule(hw, list, lkups_cnt, &rule_info, &rule_added); if (ret == -EEXIST) { NL_SET_ERR_MSG_MOD(tc_fltr->extack, "Unable to add filter because it already exist"); ret = -EINVAL; goto exit; } else if (ret) { NL_SET_ERR_MSG_MOD(tc_fltr->extack, "Unable to add filter due to error"); goto exit; } /* store the output params, which are needed later for removing * advanced switch filter */ tc_fltr->rid = rule_added.rid; tc_fltr->rule_id = rule_added.rule_id; tc_fltr->dest_vsi_handle = rule_added.vsi_handle; if (tc_fltr->action.fltr_act == ICE_FWD_TO_VSI || tc_fltr->action.fltr_act == ICE_FWD_TO_Q) { tc_fltr->dest_vsi = dest_vsi; /* keep track of advanced switch filter for * destination VSI */ dest_vsi->num_chnl_fltr++; /* keeps track of channel filters for PF VSI */ if (vsi->type == ICE_VSI_PF && (flags & (ICE_TC_FLWR_FIELD_DST_MAC | ICE_TC_FLWR_FIELD_ENC_DST_MAC))) pf->num_dmac_chnl_fltrs++; } switch (tc_fltr->action.fltr_act) { case ICE_FWD_TO_VSI: dev_dbg(dev, "added switch rule (lkups_cnt %u, flags 0x%x), action is forward to TC %u, rid %u, rule_id %u, vsi_idx %u\n", lkups_cnt, flags, tc_fltr->action.fwd.tc.tc_class, rule_added.rid, rule_added.rule_id, rule_added.vsi_handle); break; case ICE_FWD_TO_Q: dev_dbg(dev, "added switch rule (lkups_cnt %u, flags 0x%x), action is forward to queue: %u (HW queue %u) , rid %u, rule_id %u\n", lkups_cnt, flags, tc_fltr->action.fwd.q.queue, tc_fltr->action.fwd.q.hw_queue, rule_added.rid, rule_added.rule_id); break; case ICE_DROP_PACKET: dev_dbg(dev, "added switch rule (lkups_cnt %u, flags 0x%x), action is drop, rid %u, rule_id %u\n", lkups_cnt, flags, rule_added.rid, rule_added.rule_id); break; default: break; } exit: kfree(list); return ret; } /** * ice_tc_set_pppoe - Parse PPPoE fields from TC flower filter * @match: Pointer to flow match structure * @fltr: Pointer to filter structure * @headers: Pointer to outer header fields * @returns PPP protocol used in filter (ppp_ses or ppp_disc) */ static u16 ice_tc_set_pppoe(struct flow_match_pppoe *match, struct ice_tc_flower_fltr *fltr, struct ice_tc_flower_lyr_2_4_hdrs *headers) { if (match->mask->session_id) { fltr->flags |= ICE_TC_FLWR_FIELD_PPPOE_SESSID; headers->pppoe_hdr.session_id = match->key->session_id; } if (match->mask->ppp_proto) { fltr->flags |= ICE_TC_FLWR_FIELD_PPP_PROTO; headers->pppoe_hdr.ppp_proto = match->key->ppp_proto; } return be16_to_cpu(match->key->type); } /** * ice_tc_set_ipv4 - Parse IPv4 addresses from TC flower filter * @match: Pointer to flow match structure * @fltr: Pointer to filter structure * @headers: inner or outer header fields * @is_encap: set true for tunnel IPv4 address */ static int ice_tc_set_ipv4(struct flow_match_ipv4_addrs *match, struct ice_tc_flower_fltr *fltr, struct ice_tc_flower_lyr_2_4_hdrs *headers, bool is_encap) { if (match->key->dst) { if (is_encap) fltr->flags |= ICE_TC_FLWR_FIELD_ENC_DEST_IPV4; else fltr->flags |= ICE_TC_FLWR_FIELD_DEST_IPV4; headers->l3_key.dst_ipv4 = match->key->dst; headers->l3_mask.dst_ipv4 = match->mask->dst; } if (match->key->src) { if (is_encap) fltr->flags |= ICE_TC_FLWR_FIELD_ENC_SRC_IPV4; else fltr->flags |= ICE_TC_FLWR_FIELD_SRC_IPV4; headers->l3_key.src_ipv4 = match->key->src; headers->l3_mask.src_ipv4 = match->mask->src; } return 0; } /** * ice_tc_set_ipv6 - Parse IPv6 addresses from TC flower filter * @match: Pointer to flow match structure * @fltr: Pointer to filter structure * @headers: inner or outer header fields * @is_encap: set true for tunnel IPv6 address */ static int ice_tc_set_ipv6(struct flow_match_ipv6_addrs *match, struct ice_tc_flower_fltr *fltr, struct ice_tc_flower_lyr_2_4_hdrs *headers, bool is_encap) { struct ice_tc_l3_hdr *l3_key, *l3_mask; /* src and dest IPV6 address should not be LOOPBACK * (0:0:0:0:0:0:0:1), which can be represented as ::1 */ if (ipv6_addr_loopback(&match->key->dst) || ipv6_addr_loopback(&match->key->src)) { NL_SET_ERR_MSG_MOD(fltr->extack, "Bad IPv6, addr is LOOPBACK"); return -EINVAL; } /* if src/dest IPv6 address is *,* error */ if (ipv6_addr_any(&match->mask->dst) && ipv6_addr_any(&match->mask->src)) { NL_SET_ERR_MSG_MOD(fltr->extack, "Bad src/dest IPv6, addr is any"); return -EINVAL; } if (!ipv6_addr_any(&match->mask->dst)) { if (is_encap) fltr->flags |= ICE_TC_FLWR_FIELD_ENC_DEST_IPV6; else fltr->flags |= ICE_TC_FLWR_FIELD_DEST_IPV6; } if (!ipv6_addr_any(&match->mask->src)) { if (is_encap) fltr->flags |= ICE_TC_FLWR_FIELD_ENC_SRC_IPV6; else fltr->flags |= ICE_TC_FLWR_FIELD_SRC_IPV6; } l3_key = &headers->l3_key; l3_mask = &headers->l3_mask; if (fltr->flags & (ICE_TC_FLWR_FIELD_ENC_SRC_IPV6 | ICE_TC_FLWR_FIELD_SRC_IPV6)) { memcpy(&l3_key->src_ipv6_addr, &match->key->src.s6_addr, sizeof(match->key->src.s6_addr)); memcpy(&l3_mask->src_ipv6_addr, &match->mask->src.s6_addr, sizeof(match->mask->src.s6_addr)); } if (fltr->flags & (ICE_TC_FLWR_FIELD_ENC_DEST_IPV6 | ICE_TC_FLWR_FIELD_DEST_IPV6)) { memcpy(&l3_key->dst_ipv6_addr, &match->key->dst.s6_addr, sizeof(match->key->dst.s6_addr)); memcpy(&l3_mask->dst_ipv6_addr, &match->mask->dst.s6_addr, sizeof(match->mask->dst.s6_addr)); } return 0; } /** * ice_tc_set_tos_ttl - Parse IP ToS/TTL from TC flower filter * @match: Pointer to flow match structure * @fltr: Pointer to filter structure * @headers: inner or outer header fields * @is_encap: set true for tunnel */ static void ice_tc_set_tos_ttl(struct flow_match_ip *match, struct ice_tc_flower_fltr *fltr, struct ice_tc_flower_lyr_2_4_hdrs *headers, bool is_encap) { if (match->mask->tos) { if (is_encap) fltr->flags |= ICE_TC_FLWR_FIELD_ENC_IP_TOS; else fltr->flags |= ICE_TC_FLWR_FIELD_IP_TOS; headers->l3_key.tos = match->key->tos; headers->l3_mask.tos = match->mask->tos; } if (match->mask->ttl) { if (is_encap) fltr->flags |= ICE_TC_FLWR_FIELD_ENC_IP_TTL; else fltr->flags |= ICE_TC_FLWR_FIELD_IP_TTL; headers->l3_key.ttl = match->key->ttl; headers->l3_mask.ttl = match->mask->ttl; } } /** * ice_tc_set_port - Parse ports from TC flower filter * @match: Flow match structure * @fltr: Pointer to filter structure * @headers: inner or outer header fields * @is_encap: set true for tunnel port */ static int ice_tc_set_port(struct flow_match_ports match, struct ice_tc_flower_fltr *fltr, struct ice_tc_flower_lyr_2_4_hdrs *headers, bool is_encap) { if (match.key->dst) { if (is_encap) fltr->flags |= ICE_TC_FLWR_FIELD_ENC_DEST_L4_PORT; else fltr->flags |= ICE_TC_FLWR_FIELD_DEST_L4_PORT; headers->l4_key.dst_port = match.key->dst; headers->l4_mask.dst_port = match.mask->dst; } if (match.key->src) { if (is_encap) fltr->flags |= ICE_TC_FLWR_FIELD_ENC_SRC_L4_PORT; else fltr->flags |= ICE_TC_FLWR_FIELD_SRC_L4_PORT; headers->l4_key.src_port = match.key->src; headers->l4_mask.src_port = match.mask->src; } return 0; } static struct net_device * ice_get_tunnel_device(struct net_device *dev, struct flow_rule *rule) { struct flow_action_entry *act; int i; if (ice_is_tunnel_supported(dev)) return dev; flow_action_for_each(i, act, &rule->action) { if (act->id == FLOW_ACTION_REDIRECT && ice_is_tunnel_supported(act->dev)) return act->dev; } return NULL; } /** * ice_parse_gtp_type - Sets GTP tunnel type to GTP-U or GTP-C * @match: Flow match structure * @fltr: Pointer to filter structure * * GTP-C/GTP-U is selected based on destination port number (enc_dst_port). * Before calling this funtcion, fltr->tunnel_type should be set to TNL_GTPU, * therefore making GTP-U the default choice (when destination port number is * not specified). */ static int ice_parse_gtp_type(struct flow_match_ports match, struct ice_tc_flower_fltr *fltr) { u16 dst_port; if (match.key->dst) { dst_port = be16_to_cpu(match.key->dst); switch (dst_port) { case 2152: break; case 2123: fltr->tunnel_type = TNL_GTPC; break; default: NL_SET_ERR_MSG_MOD(fltr->extack, "Unsupported GTP port number"); return -EINVAL; } } return 0; } static int ice_parse_tunnel_attr(struct net_device *dev, struct flow_rule *rule, struct ice_tc_flower_fltr *fltr) { struct ice_tc_flower_lyr_2_4_hdrs *headers = &fltr->outer_headers; struct flow_match_control enc_control; fltr->tunnel_type = ice_tc_tun_get_type(dev); headers->l3_key.ip_proto = IPPROTO_UDP; if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ENC_KEYID)) { struct flow_match_enc_keyid enc_keyid; flow_rule_match_enc_keyid(rule, &enc_keyid); if (!enc_keyid.mask->keyid || enc_keyid.mask->keyid != cpu_to_be32(ICE_TC_FLOWER_MASK_32)) return -EINVAL; fltr->flags |= ICE_TC_FLWR_FIELD_TENANT_ID; fltr->tenant_id = enc_keyid.key->keyid; } flow_rule_match_enc_control(rule, &enc_control); if (enc_control.key->addr_type == FLOW_DISSECTOR_KEY_IPV4_ADDRS) { struct flow_match_ipv4_addrs match; flow_rule_match_enc_ipv4_addrs(rule, &match); if (ice_tc_set_ipv4(&match, fltr, headers, true)) return -EINVAL; } else if (enc_control.key->addr_type == FLOW_DISSECTOR_KEY_IPV6_ADDRS) { struct flow_match_ipv6_addrs match; flow_rule_match_enc_ipv6_addrs(rule, &match); if (ice_tc_set_ipv6(&match, fltr, headers, true)) return -EINVAL; } if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ENC_IP)) { struct flow_match_ip match; flow_rule_match_enc_ip(rule, &match); ice_tc_set_tos_ttl(&match, fltr, headers, true); } if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ENC_PORTS) && fltr->tunnel_type != TNL_VXLAN && fltr->tunnel_type != TNL_GENEVE) { struct flow_match_ports match; flow_rule_match_enc_ports(rule, &match); if (fltr->tunnel_type != TNL_GTPU) { if (ice_tc_set_port(match, fltr, headers, true)) return -EINVAL; } else { if (ice_parse_gtp_type(match, fltr)) return -EINVAL; } } if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ENC_OPTS)) { struct flow_match_enc_opts match; flow_rule_match_enc_opts(rule, &match); memcpy(&fltr->gtp_pdu_info_keys, &match.key->data[0], sizeof(struct gtp_pdu_session_info)); memcpy(&fltr->gtp_pdu_info_masks, &match.mask->data[0], sizeof(struct gtp_pdu_session_info)); fltr->flags |= ICE_TC_FLWR_FIELD_ENC_OPTS; } return 0; } /** * ice_parse_cls_flower - Parse TC flower filters provided by kernel * @vsi: Pointer to the VSI * @filter_dev: Pointer to device on which filter is being added * @f: Pointer to struct flow_cls_offload * @fltr: Pointer to filter structure */ static int ice_parse_cls_flower(struct net_device *filter_dev, struct ice_vsi *vsi, struct flow_cls_offload *f, struct ice_tc_flower_fltr *fltr) { struct ice_tc_flower_lyr_2_4_hdrs *headers = &fltr->outer_headers; struct flow_rule *rule = flow_cls_offload_flow_rule(f); u16 n_proto_mask = 0, n_proto_key = 0, addr_type = 0; struct flow_dissector *dissector; struct net_device *tunnel_dev; dissector = rule->match.dissector; 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_ENC_CONTROL) | 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_PORTS) | BIT_ULL(FLOW_DISSECTOR_KEY_ENC_OPTS) | BIT_ULL(FLOW_DISSECTOR_KEY_IP) | BIT_ULL(FLOW_DISSECTOR_KEY_ENC_IP) | BIT_ULL(FLOW_DISSECTOR_KEY_PORTS) | BIT_ULL(FLOW_DISSECTOR_KEY_PPPOE) | BIT_ULL(FLOW_DISSECTOR_KEY_L2TPV3))) { NL_SET_ERR_MSG_MOD(fltr->extack, "Unsupported key used"); return -EOPNOTSUPP; } tunnel_dev = ice_get_tunnel_device(filter_dev, rule); if (tunnel_dev) { int err; filter_dev = tunnel_dev; err = ice_parse_tunnel_attr(filter_dev, rule, fltr); if (err) { NL_SET_ERR_MSG_MOD(fltr->extack, "Failed to parse TC flower tunnel attributes"); return err; } /* header pointers should point to the inner headers, outer * header were already set by ice_parse_tunnel_attr */ headers = &fltr->inner_headers; } else if (dissector->used_keys & (BIT_ULL(FLOW_DISSECTOR_KEY_ENC_IPV4_ADDRS) | BIT_ULL(FLOW_DISSECTOR_KEY_ENC_IPV6_ADDRS) | BIT_ULL(FLOW_DISSECTOR_KEY_ENC_KEYID) | BIT_ULL(FLOW_DISSECTOR_KEY_ENC_PORTS))) { NL_SET_ERR_MSG_MOD(fltr->extack, "Tunnel key used, but device isn't a tunnel"); return -EOPNOTSUPP; } else { fltr->tunnel_type = TNL_LAST; } if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_BASIC)) { struct flow_match_basic match; flow_rule_match_basic(rule, &match); n_proto_key = ntohs(match.key->n_proto); n_proto_mask = ntohs(match.mask->n_proto); if (n_proto_key == ETH_P_ALL || n_proto_key == 0 || fltr->tunnel_type == TNL_GTPU || fltr->tunnel_type == TNL_GTPC) { n_proto_key = 0; n_proto_mask = 0; } else { fltr->flags |= ICE_TC_FLWR_FIELD_ETH_TYPE_ID; } headers->l2_key.n_proto = cpu_to_be16(n_proto_key); headers->l2_mask.n_proto = cpu_to_be16(n_proto_mask); headers->l3_key.ip_proto = match.key->ip_proto; } if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ETH_ADDRS)) { struct flow_match_eth_addrs match; flow_rule_match_eth_addrs(rule, &match); if (!is_zero_ether_addr(match.key->dst)) { ether_addr_copy(headers->l2_key.dst_mac, match.key->dst); ether_addr_copy(headers->l2_mask.dst_mac, match.mask->dst); fltr->flags |= ICE_TC_FLWR_FIELD_DST_MAC; } if (!is_zero_ether_addr(match.key->src)) { ether_addr_copy(headers->l2_key.src_mac, match.key->src); ether_addr_copy(headers->l2_mask.src_mac, match.mask->src); fltr->flags |= ICE_TC_FLWR_FIELD_SRC_MAC; } } if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_VLAN) || is_vlan_dev(filter_dev)) { struct flow_dissector_key_vlan mask; struct flow_dissector_key_vlan key; struct flow_match_vlan match; if (is_vlan_dev(filter_dev)) { match.key = &key; match.key->vlan_id = vlan_dev_vlan_id(filter_dev); match.key->vlan_priority = 0; match.mask = &mask; memset(match.mask, 0xff, sizeof(*match.mask)); match.mask->vlan_priority = 0; } else { flow_rule_match_vlan(rule, &match); } if (match.mask->vlan_id) { if (match.mask->vlan_id == VLAN_VID_MASK) { fltr->flags |= ICE_TC_FLWR_FIELD_VLAN; headers->vlan_hdr.vlan_id = cpu_to_be16(match.key->vlan_id & VLAN_VID_MASK); } else { NL_SET_ERR_MSG_MOD(fltr->extack, "Bad VLAN mask"); return -EINVAL; } } if (match.mask->vlan_priority) { fltr->flags |= ICE_TC_FLWR_FIELD_VLAN_PRIO; headers->vlan_hdr.vlan_prio = be16_encode_bits(match.key->vlan_priority, VLAN_PRIO_MASK); } if (match.mask->vlan_tpid) { headers->vlan_hdr.vlan_tpid = match.key->vlan_tpid; fltr->flags |= ICE_TC_FLWR_FIELD_VLAN_TPID; } } if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_CVLAN)) { struct flow_match_vlan match; if (!ice_is_dvm_ena(&vsi->back->hw)) { NL_SET_ERR_MSG_MOD(fltr->extack, "Double VLAN mode is not enabled"); return -EINVAL; } flow_rule_match_cvlan(rule, &match); if (match.mask->vlan_id) { if (match.mask->vlan_id == VLAN_VID_MASK) { fltr->flags |= ICE_TC_FLWR_FIELD_CVLAN; headers->cvlan_hdr.vlan_id = cpu_to_be16(match.key->vlan_id & VLAN_VID_MASK); } else { NL_SET_ERR_MSG_MOD(fltr->extack, "Bad CVLAN mask"); return -EINVAL; } } if (match.mask->vlan_priority) { fltr->flags |= ICE_TC_FLWR_FIELD_CVLAN_PRIO; headers->cvlan_hdr.vlan_prio = be16_encode_bits(match.key->vlan_priority, VLAN_PRIO_MASK); } } if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_PPPOE)) { struct flow_match_pppoe match; flow_rule_match_pppoe(rule, &match); n_proto_key = ice_tc_set_pppoe(&match, fltr, headers); /* If ethertype equals ETH_P_PPP_SES, n_proto might be * overwritten by encapsulated protocol (ppp_proto field) or set * to 0. To correct this, flow_match_pppoe provides the type * field, which contains the actual ethertype (ETH_P_PPP_SES). */ headers->l2_key.n_proto = cpu_to_be16(n_proto_key); headers->l2_mask.n_proto = cpu_to_be16(0xFFFF); fltr->flags |= ICE_TC_FLWR_FIELD_ETH_TYPE_ID; } if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_CONTROL)) { struct flow_match_control match; flow_rule_match_control(rule, &match); addr_type = match.key->addr_type; } if (addr_type == FLOW_DISSECTOR_KEY_IPV4_ADDRS) { struct flow_match_ipv4_addrs match; flow_rule_match_ipv4_addrs(rule, &match); if (ice_tc_set_ipv4(&match, fltr, headers, false)) return -EINVAL; } if (addr_type == FLOW_DISSECTOR_KEY_IPV6_ADDRS) { struct flow_match_ipv6_addrs match; flow_rule_match_ipv6_addrs(rule, &match); if (ice_tc_set_ipv6(&match, fltr, headers, false)) return -EINVAL; } if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_IP)) { struct flow_match_ip match; flow_rule_match_ip(rule, &match); ice_tc_set_tos_ttl(&match, fltr, headers, false); } if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_L2TPV3)) { struct flow_match_l2tpv3 match; flow_rule_match_l2tpv3(rule, &match); fltr->flags |= ICE_TC_FLWR_FIELD_L2TPV3_SESSID; headers->l2tpv3_hdr.session_id = match.key->session_id; } if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_PORTS)) { struct flow_match_ports match; flow_rule_match_ports(rule, &match); if (ice_tc_set_port(match, fltr, headers, false)) return -EINVAL; switch (headers->l3_key.ip_proto) { case IPPROTO_TCP: case IPPROTO_UDP: break; default: NL_SET_ERR_MSG_MOD(fltr->extack, "Only UDP and TCP transport are supported"); return -EINVAL; } } return 0; } /** * ice_add_switch_fltr - Add TC flower filters * @vsi: Pointer to VSI * @fltr: Pointer to struct ice_tc_flower_fltr * * Add filter in HW switch block */ static int ice_add_switch_fltr(struct ice_vsi *vsi, struct ice_tc_flower_fltr *fltr) { if (fltr->action.fltr_act == ICE_FWD_TO_QGRP) return -EOPNOTSUPP; if (ice_is_eswitch_mode_switchdev(vsi->back)) return ice_eswitch_add_tc_fltr(vsi, fltr); return ice_add_tc_flower_adv_fltr(vsi, fltr); } /** * ice_prep_adq_filter - Prepare ADQ filter with the required additional headers * @vsi: Pointer to VSI * @fltr: Pointer to TC flower filter structure * * Prepare ADQ filter with the required additional header fields */ static int ice_prep_adq_filter(struct ice_vsi *vsi, struct ice_tc_flower_fltr *fltr) { if ((fltr->flags & ICE_TC_FLWR_FIELD_TENANT_ID) && (fltr->flags & (ICE_TC_FLWR_FIELD_DST_MAC | ICE_TC_FLWR_FIELD_SRC_MAC))) { NL_SET_ERR_MSG_MOD(fltr->extack, "Unable to add filter because filter using tunnel key and inner MAC is unsupported combination"); return -EOPNOTSUPP; } /* For ADQ, filter must include dest MAC address, otherwise unwanted * packets with unrelated MAC address get delivered to ADQ VSIs as long * as remaining filter criteria is satisfied such as dest IP address * and dest/src L4 port. Below code handles the following cases: * 1. For non-tunnel, if user specify MAC addresses, use them. * 2. For non-tunnel, if user didn't specify MAC address, add implicit * dest MAC to be lower netdev's active unicast MAC address * 3. For tunnel, as of now TC-filter through flower classifier doesn't * have provision for user to specify outer DMAC, hence driver to * implicitly add outer dest MAC to be lower netdev's active unicast * MAC address. */ if (fltr->tunnel_type != TNL_LAST && !(fltr->flags & ICE_TC_FLWR_FIELD_ENC_DST_MAC)) fltr->flags |= ICE_TC_FLWR_FIELD_ENC_DST_MAC; if (fltr->tunnel_type == TNL_LAST && !(fltr->flags & ICE_TC_FLWR_FIELD_DST_MAC)) fltr->flags |= ICE_TC_FLWR_FIELD_DST_MAC; if (fltr->flags & (ICE_TC_FLWR_FIELD_DST_MAC | ICE_TC_FLWR_FIELD_ENC_DST_MAC)) { ether_addr_copy(fltr->outer_headers.l2_key.dst_mac, vsi->netdev->dev_addr); eth_broadcast_addr(fltr->outer_headers.l2_mask.dst_mac); } /* Make sure VLAN is already added to main VSI, before allowing ADQ to * add a VLAN based filter such as MAC + VLAN + L4 port. */ if (fltr->flags & ICE_TC_FLWR_FIELD_VLAN) { u16 vlan_id = be16_to_cpu(fltr->outer_headers.vlan_hdr.vlan_id); if (!ice_vlan_fltr_exist(&vsi->back->hw, vlan_id, vsi->idx)) { NL_SET_ERR_MSG_MOD(fltr->extack, "Unable to add filter because legacy VLAN filter for specified destination doesn't exist"); return -EINVAL; } } return 0; } /** * ice_handle_tclass_action - Support directing to a traffic class * @vsi: Pointer to VSI * @cls_flower: Pointer to TC flower offload structure * @fltr: Pointer to TC flower filter structure * * Support directing traffic to a traffic class/queue-set */ static int ice_handle_tclass_action(struct ice_vsi *vsi, struct flow_cls_offload *cls_flower, struct ice_tc_flower_fltr *fltr) { int tc = tc_classid_to_hwtc(vsi->netdev, cls_flower->classid); /* user specified hw_tc (must be non-zero for ADQ TC), action is forward * to hw_tc (i.e. ADQ channel number) */ if (tc < ICE_CHNL_START_TC) { NL_SET_ERR_MSG_MOD(fltr->extack, "Unable to add filter because of unsupported destination"); return -EOPNOTSUPP; } if (!(vsi->all_enatc & BIT(tc))) { NL_SET_ERR_MSG_MOD(fltr->extack, "Unable to add filter because of non-existence destination"); return -EINVAL; } fltr->action.fltr_act = ICE_FWD_TO_VSI; fltr->action.fwd.tc.tc_class = tc; return ice_prep_adq_filter(vsi, fltr); } static int ice_tc_forward_to_queue(struct ice_vsi *vsi, struct ice_tc_flower_fltr *fltr, struct flow_action_entry *act) { struct ice_vsi *ch_vsi = NULL; u16 queue = act->rx_queue; if (queue >= vsi->num_rxq) { NL_SET_ERR_MSG_MOD(fltr->extack, "Unable to add filter because specified queue is invalid"); return -EINVAL; } fltr->action.fltr_act = ICE_FWD_TO_Q; fltr->action.fwd.q.queue = queue; /* determine corresponding HW queue */ fltr->action.fwd.q.hw_queue = vsi->rxq_map[queue]; /* If ADQ is configured, and the queue belongs to ADQ VSI, then prepare * ADQ switch filter */ ch_vsi = ice_locate_vsi_using_queue(vsi, fltr->action.fwd.q.queue); if (!ch_vsi) return -EINVAL; fltr->dest_vsi = ch_vsi; if (!ice_is_chnl_fltr(fltr)) return 0; return ice_prep_adq_filter(vsi, fltr); } static int ice_tc_parse_action(struct ice_vsi *vsi, struct ice_tc_flower_fltr *fltr, struct flow_action_entry *act) { switch (act->id) { case FLOW_ACTION_RX_QUEUE_MAPPING: /* forward to queue */ return ice_tc_forward_to_queue(vsi, fltr, act); case FLOW_ACTION_DROP: fltr->action.fltr_act = ICE_DROP_PACKET; return 0; default: NL_SET_ERR_MSG_MOD(fltr->extack, "Unsupported TC action"); return -EOPNOTSUPP; } } /** * ice_parse_tc_flower_actions - Parse the actions for a TC filter * @vsi: Pointer to VSI * @cls_flower: Pointer to TC flower offload structure * @fltr: Pointer to TC flower filter structure * * Parse the actions for a TC filter */ static int ice_parse_tc_flower_actions(struct ice_vsi *vsi, struct flow_cls_offload *cls_flower, struct ice_tc_flower_fltr *fltr) { struct flow_rule *rule = flow_cls_offload_flow_rule(cls_flower); struct flow_action *flow_action = &rule->action; struct flow_action_entry *act; int i, err; if (cls_flower->classid) return ice_handle_tclass_action(vsi, cls_flower, fltr); if (!flow_action_has_entries(flow_action)) return -EINVAL; flow_action_for_each(i, act, flow_action) { if (ice_is_eswitch_mode_switchdev(vsi->back)) err = ice_eswitch_tc_parse_action(fltr, act); else err = ice_tc_parse_action(vsi, fltr, act); if (err) return err; continue; } return 0; } /** * ice_del_tc_fltr - deletes a filter from HW table * @vsi: Pointer to VSI * @fltr: Pointer to struct ice_tc_flower_fltr * * This function deletes a filter from HW table and manages book-keeping */ static int ice_del_tc_fltr(struct ice_vsi *vsi, struct ice_tc_flower_fltr *fltr) { struct ice_rule_query_data rule_rem; struct ice_pf *pf = vsi->back; int err; rule_rem.rid = fltr->rid; rule_rem.rule_id = fltr->rule_id; rule_rem.vsi_handle = fltr->dest_vsi_handle; err = ice_rem_adv_rule_by_id(&pf->hw, &rule_rem); if (err) { if (err == -ENOENT) { NL_SET_ERR_MSG_MOD(fltr->extack, "Filter does not exist"); return -ENOENT; } NL_SET_ERR_MSG_MOD(fltr->extack, "Failed to delete TC flower filter"); return -EIO; } /* update advanced switch filter count for destination * VSI if filter destination was VSI */ if (fltr->dest_vsi) { if (fltr->dest_vsi->type == ICE_VSI_CHNL) { fltr->dest_vsi->num_chnl_fltr--; /* keeps track of channel filters for PF VSI */ if (vsi->type == ICE_VSI_PF && (fltr->flags & (ICE_TC_FLWR_FIELD_DST_MAC | ICE_TC_FLWR_FIELD_ENC_DST_MAC))) pf->num_dmac_chnl_fltrs--; } } return 0; } /** * ice_add_tc_fltr - adds a TC flower filter * @netdev: Pointer to netdev * @vsi: Pointer to VSI * @f: Pointer to flower offload structure * @__fltr: Pointer to struct ice_tc_flower_fltr * * This function parses TC-flower input fields, parses action, * and adds a filter. */ static int ice_add_tc_fltr(struct net_device *netdev, struct ice_vsi *vsi, struct flow_cls_offload *f, struct ice_tc_flower_fltr **__fltr) { struct ice_tc_flower_fltr *fltr; int err; /* by default, set output to be INVALID */ *__fltr = NULL; fltr = kzalloc(sizeof(*fltr), GFP_KERNEL); if (!fltr) return -ENOMEM; fltr->cookie = f->cookie; fltr->extack = f->common.extack; fltr->src_vsi = vsi; INIT_HLIST_NODE(&fltr->tc_flower_node); err = ice_parse_cls_flower(netdev, vsi, f, fltr); if (err < 0) goto err; err = ice_parse_tc_flower_actions(vsi, f, fltr); if (err < 0) goto err; err = ice_add_switch_fltr(vsi, fltr); if (err < 0) goto err; /* return the newly created filter */ *__fltr = fltr; return 0; err: kfree(fltr); return err; } /** * ice_find_tc_flower_fltr - Find the TC flower filter in the list * @pf: Pointer to PF * @cookie: filter specific cookie */ static struct ice_tc_flower_fltr * ice_find_tc_flower_fltr(struct ice_pf *pf, unsigned long cookie) { struct ice_tc_flower_fltr *fltr; hlist_for_each_entry(fltr, &pf->tc_flower_fltr_list, tc_flower_node) if (cookie == fltr->cookie) return fltr; return NULL; } /** * ice_add_cls_flower - add TC flower filters * @netdev: Pointer to filter device * @vsi: Pointer to VSI * @cls_flower: Pointer to flower offload structure */ int ice_add_cls_flower(struct net_device *netdev, struct ice_vsi *vsi, struct flow_cls_offload *cls_flower) { struct netlink_ext_ack *extack = cls_flower->common.extack; struct net_device *vsi_netdev = vsi->netdev; struct ice_tc_flower_fltr *fltr; struct ice_pf *pf = vsi->back; int err; if (ice_is_reset_in_progress(pf->state)) return -EBUSY; if (test_bit(ICE_FLAG_FW_LLDP_AGENT, pf->flags)) return -EINVAL; if (ice_is_port_repr_netdev(netdev)) vsi_netdev = netdev; if (!(vsi_netdev->features & NETIF_F_HW_TC) && !test_bit(ICE_FLAG_CLS_FLOWER, pf->flags)) { /* Based on TC indirect notifications from kernel, all ice * devices get an instance of rule from higher level device. * Avoid triggering explicit error in this case. */ if (netdev == vsi_netdev) NL_SET_ERR_MSG_MOD(extack, "can't apply TC flower filters, turn ON hw-tc-offload and try again"); return -EINVAL; } /* avoid duplicate entries, if exists - return error */ fltr = ice_find_tc_flower_fltr(pf, cls_flower->cookie); if (fltr) { NL_SET_ERR_MSG_MOD(extack, "filter cookie already exists, ignoring"); return -EEXIST; } /* prep and add TC-flower filter in HW */ err = ice_add_tc_fltr(netdev, vsi, cls_flower, &fltr); if (err) return err; /* add filter into an ordered list */ hlist_add_head(&fltr->tc_flower_node, &pf->tc_flower_fltr_list); return 0; } /** * ice_del_cls_flower - delete TC flower filters * @vsi: Pointer to VSI * @cls_flower: Pointer to struct flow_cls_offload */ int ice_del_cls_flower(struct ice_vsi *vsi, struct flow_cls_offload *cls_flower) { struct ice_tc_flower_fltr *fltr; struct ice_pf *pf = vsi->back; int err; /* find filter */ fltr = ice_find_tc_flower_fltr(pf, cls_flower->cookie); if (!fltr) { if (!test_bit(ICE_FLAG_TC_MQPRIO, pf->flags) && hlist_empty(&pf->tc_flower_fltr_list)) return 0; NL_SET_ERR_MSG_MOD(cls_flower->common.extack, "failed to delete TC flower filter because unable to find it"); return -EINVAL; } fltr->extack = cls_flower->common.extack; /* delete filter from HW */ err = ice_del_tc_fltr(vsi, fltr); if (err) return err; /* delete filter from an ordered list */ hlist_del(&fltr->tc_flower_node); /* free the filter node */ kfree(fltr); return 0; } /** * ice_replay_tc_fltrs - replay TC filters * @pf: pointer to PF struct */ void ice_replay_tc_fltrs(struct ice_pf *pf) { struct ice_tc_flower_fltr *fltr; struct hlist_node *node; hlist_for_each_entry_safe(fltr, node, &pf->tc_flower_fltr_list, tc_flower_node) { fltr->extack = NULL; ice_add_switch_fltr(fltr->src_vsi, fltr); } }
linux-master
drivers/net/ethernet/intel/ice/ice_tc_lib.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2022, Intel Corporation. */ #include "ice_common.h" #include "ice.h" #include "ice_ddp.h" /* For supporting double VLAN mode, it is necessary to enable or disable certain * boost tcam entries. The metadata labels names that match the following * prefixes will be saved to allow enabling double VLAN mode. */ #define ICE_DVM_PRE "BOOST_MAC_VLAN_DVM" /* enable these entries */ #define ICE_SVM_PRE "BOOST_MAC_VLAN_SVM" /* disable these entries */ /* To support tunneling entries by PF, the package will append the PF number to * the label; for example TNL_VXLAN_PF0, TNL_VXLAN_PF1, TNL_VXLAN_PF2, etc. */ #define ICE_TNL_PRE "TNL_" static const struct ice_tunnel_type_scan tnls[] = { { TNL_VXLAN, "TNL_VXLAN_PF" }, { TNL_GENEVE, "TNL_GENEVE_PF" }, { TNL_LAST, "" } }; /** * ice_verify_pkg - verify package * @pkg: pointer to the package buffer * @len: size of the package buffer * * Verifies various attributes of the package file, including length, format * version, and the requirement of at least one segment. */ static enum ice_ddp_state ice_verify_pkg(struct ice_pkg_hdr *pkg, u32 len) { u32 seg_count; u32 i; if (len < struct_size(pkg, seg_offset, 1)) return ICE_DDP_PKG_INVALID_FILE; if (pkg->pkg_format_ver.major != ICE_PKG_FMT_VER_MAJ || pkg->pkg_format_ver.minor != ICE_PKG_FMT_VER_MNR || pkg->pkg_format_ver.update != ICE_PKG_FMT_VER_UPD || pkg->pkg_format_ver.draft != ICE_PKG_FMT_VER_DFT) return ICE_DDP_PKG_INVALID_FILE; /* pkg must have at least one segment */ seg_count = le32_to_cpu(pkg->seg_count); if (seg_count < 1) return ICE_DDP_PKG_INVALID_FILE; /* make sure segment array fits in package length */ if (len < struct_size(pkg, seg_offset, seg_count)) return ICE_DDP_PKG_INVALID_FILE; /* all segments must fit within length */ for (i = 0; i < seg_count; i++) { u32 off = le32_to_cpu(pkg->seg_offset[i]); struct ice_generic_seg_hdr *seg; /* segment header must fit */ if (len < off + sizeof(*seg)) return ICE_DDP_PKG_INVALID_FILE; seg = (struct ice_generic_seg_hdr *)((u8 *)pkg + off); /* segment body must fit */ if (len < off + le32_to_cpu(seg->seg_size)) return ICE_DDP_PKG_INVALID_FILE; } return ICE_DDP_PKG_SUCCESS; } /** * ice_free_seg - free package segment pointer * @hw: pointer to the hardware structure * * Frees the package segment pointer in the proper manner, depending on if the * segment was allocated or just the passed in pointer was stored. */ void ice_free_seg(struct ice_hw *hw) { if (hw->pkg_copy) { devm_kfree(ice_hw_to_dev(hw), hw->pkg_copy); hw->pkg_copy = NULL; hw->pkg_size = 0; } hw->seg = NULL; } /** * ice_chk_pkg_version - check package version for compatibility with driver * @pkg_ver: pointer to a version structure to check * * Check to make sure that the package about to be downloaded is compatible with * the driver. To be compatible, the major and minor components of the package * version must match our ICE_PKG_SUPP_VER_MAJ and ICE_PKG_SUPP_VER_MNR * definitions. */ static enum ice_ddp_state ice_chk_pkg_version(struct ice_pkg_ver *pkg_ver) { if (pkg_ver->major > ICE_PKG_SUPP_VER_MAJ || (pkg_ver->major == ICE_PKG_SUPP_VER_MAJ && pkg_ver->minor > ICE_PKG_SUPP_VER_MNR)) return ICE_DDP_PKG_FILE_VERSION_TOO_HIGH; else if (pkg_ver->major < ICE_PKG_SUPP_VER_MAJ || (pkg_ver->major == ICE_PKG_SUPP_VER_MAJ && pkg_ver->minor < ICE_PKG_SUPP_VER_MNR)) return ICE_DDP_PKG_FILE_VERSION_TOO_LOW; return ICE_DDP_PKG_SUCCESS; } /** * ice_pkg_val_buf * @buf: pointer to the ice buffer * * This helper function validates a buffer's header. */ static struct ice_buf_hdr *ice_pkg_val_buf(struct ice_buf *buf) { struct ice_buf_hdr *hdr; u16 section_count; u16 data_end; hdr = (struct ice_buf_hdr *)buf->buf; /* verify data */ section_count = le16_to_cpu(hdr->section_count); if (section_count < ICE_MIN_S_COUNT || section_count > ICE_MAX_S_COUNT) return NULL; data_end = le16_to_cpu(hdr->data_end); if (data_end < ICE_MIN_S_DATA_END || data_end > ICE_MAX_S_DATA_END) return NULL; return hdr; } /** * ice_find_buf_table * @ice_seg: pointer to the ice segment * * Returns the address of the buffer table within the ice segment. */ static struct ice_buf_table *ice_find_buf_table(struct ice_seg *ice_seg) { struct ice_nvm_table *nvms = (struct ice_nvm_table *) (ice_seg->device_table + le32_to_cpu(ice_seg->device_table_count)); return (__force struct ice_buf_table *)(nvms->vers + le32_to_cpu(nvms->table_count)); } /** * ice_pkg_enum_buf * @ice_seg: pointer to the ice segment (or NULL on subsequent calls) * @state: pointer to the enum state * * This function will enumerate all the buffers in the ice segment. The first * call is made with the ice_seg parameter non-NULL; on subsequent calls, * ice_seg is set to NULL which continues the enumeration. When the function * returns a NULL pointer, then the end of the buffers has been reached, or an * unexpected value has been detected (for example an invalid section count or * an invalid buffer end value). */ static struct ice_buf_hdr *ice_pkg_enum_buf(struct ice_seg *ice_seg, struct ice_pkg_enum *state) { if (ice_seg) { state->buf_table = ice_find_buf_table(ice_seg); if (!state->buf_table) return NULL; state->buf_idx = 0; return ice_pkg_val_buf(state->buf_table->buf_array); } if (++state->buf_idx < le32_to_cpu(state->buf_table->buf_count)) return ice_pkg_val_buf(state->buf_table->buf_array + state->buf_idx); else return NULL; } /** * ice_pkg_advance_sect * @ice_seg: pointer to the ice segment (or NULL on subsequent calls) * @state: pointer to the enum state * * This helper function will advance the section within the ice segment, * also advancing the buffer if needed. */ static bool ice_pkg_advance_sect(struct ice_seg *ice_seg, struct ice_pkg_enum *state) { if (!ice_seg && !state->buf) return false; if (!ice_seg && state->buf) if (++state->sect_idx < le16_to_cpu(state->buf->section_count)) return true; state->buf = ice_pkg_enum_buf(ice_seg, state); if (!state->buf) return false; /* start of new buffer, reset section index */ state->sect_idx = 0; return true; } /** * ice_pkg_enum_section * @ice_seg: pointer to the ice segment (or NULL on subsequent calls) * @state: pointer to the enum state * @sect_type: section type to enumerate * * This function will enumerate all the sections of a particular type in the * ice segment. The first call is made with the ice_seg parameter non-NULL; * on subsequent calls, ice_seg is set to NULL which continues the enumeration. * When the function returns a NULL pointer, then the end of the matching * sections has been reached. */ void *ice_pkg_enum_section(struct ice_seg *ice_seg, struct ice_pkg_enum *state, u32 sect_type) { u16 offset, size; if (ice_seg) state->type = sect_type; if (!ice_pkg_advance_sect(ice_seg, state)) return NULL; /* scan for next matching section */ while (state->buf->section_entry[state->sect_idx].type != cpu_to_le32(state->type)) if (!ice_pkg_advance_sect(NULL, state)) return NULL; /* validate section */ offset = le16_to_cpu(state->buf->section_entry[state->sect_idx].offset); if (offset < ICE_MIN_S_OFF || offset > ICE_MAX_S_OFF) return NULL; size = le16_to_cpu(state->buf->section_entry[state->sect_idx].size); if (size < ICE_MIN_S_SZ || size > ICE_MAX_S_SZ) return NULL; /* make sure the section fits in the buffer */ if (offset + size > ICE_PKG_BUF_SIZE) return NULL; state->sect_type = le32_to_cpu(state->buf->section_entry[state->sect_idx].type); /* calc pointer to this section */ state->sect = ((u8 *)state->buf) + le16_to_cpu(state->buf->section_entry[state->sect_idx].offset); return state->sect; } /** * ice_pkg_enum_entry * @ice_seg: pointer to the ice segment (or NULL on subsequent calls) * @state: pointer to the enum state * @sect_type: section type to enumerate * @offset: pointer to variable that receives the offset in the table (optional) * @handler: function that handles access to the entries into the section type * * This function will enumerate all the entries in particular section type in * the ice segment. The first call is made with the ice_seg parameter non-NULL; * on subsequent calls, ice_seg is set to NULL which continues the enumeration. * When the function returns a NULL pointer, then the end of the entries has * been reached. * * Since each section may have a different header and entry size, the handler * function is needed to determine the number and location entries in each * section. * * The offset parameter is optional, but should be used for sections that * contain an offset for each section table. For such cases, the section handler * function must return the appropriate offset + index to give the absolution * offset for each entry. For example, if the base for a section's header * indicates a base offset of 10, and the index for the entry is 2, then * section handler function should set the offset to 10 + 2 = 12. */ static void *ice_pkg_enum_entry(struct ice_seg *ice_seg, struct ice_pkg_enum *state, u32 sect_type, u32 *offset, void *(*handler)(u32 sect_type, void *section, u32 index, u32 *offset)) { void *entry; if (ice_seg) { if (!handler) return NULL; if (!ice_pkg_enum_section(ice_seg, state, sect_type)) return NULL; state->entry_idx = 0; state->handler = handler; } else { state->entry_idx++; } if (!state->handler) return NULL; /* get entry */ entry = state->handler(state->sect_type, state->sect, state->entry_idx, offset); if (!entry) { /* end of a section, look for another section of this type */ if (!ice_pkg_enum_section(NULL, state, 0)) return NULL; state->entry_idx = 0; entry = state->handler(state->sect_type, state->sect, state->entry_idx, offset); } return entry; } /** * ice_sw_fv_handler * @sect_type: section type * @section: pointer to section * @index: index of the field vector entry to be returned * @offset: ptr to variable that receives the offset in the field vector table * * This is a callback function that can be passed to ice_pkg_enum_entry. * This function treats the given section as of type ice_sw_fv_section and * enumerates offset field. "offset" is an index into the field vector table. */ static void *ice_sw_fv_handler(u32 sect_type, void *section, u32 index, u32 *offset) { struct ice_sw_fv_section *fv_section = section; if (!section || sect_type != ICE_SID_FLD_VEC_SW) return NULL; if (index >= le16_to_cpu(fv_section->count)) return NULL; if (offset) /* "index" passed in to this function is relative to a given * 4k block. To get to the true index into the field vector * table need to add the relative index to the base_offset * field of this section */ *offset = le16_to_cpu(fv_section->base_offset) + index; return fv_section->fv + index; } /** * ice_get_prof_index_max - get the max profile index for used profile * @hw: pointer to the HW struct * * Calling this function will get the max profile index for used profile * and store the index number in struct ice_switch_info *switch_info * in HW for following use. */ static int ice_get_prof_index_max(struct ice_hw *hw) { u16 prof_index = 0, j, max_prof_index = 0; struct ice_pkg_enum state; struct ice_seg *ice_seg; bool flag = false; struct ice_fv *fv; u32 offset; memset(&state, 0, sizeof(state)); if (!hw->seg) return -EINVAL; ice_seg = hw->seg; do { fv = ice_pkg_enum_entry(ice_seg, &state, ICE_SID_FLD_VEC_SW, &offset, ice_sw_fv_handler); if (!fv) break; ice_seg = NULL; /* in the profile that not be used, the prot_id is set to 0xff * and the off is set to 0x1ff for all the field vectors. */ for (j = 0; j < hw->blk[ICE_BLK_SW].es.fvw; j++) if (fv->ew[j].prot_id != ICE_PROT_INVALID || fv->ew[j].off != ICE_FV_OFFSET_INVAL) flag = true; if (flag && prof_index > max_prof_index) max_prof_index = prof_index; prof_index++; flag = false; } while (fv); hw->switch_info->max_used_prof_index = max_prof_index; return 0; } /** * ice_get_ddp_pkg_state - get DDP pkg state after download * @hw: pointer to the HW struct * @already_loaded: indicates if pkg was already loaded onto the device */ static enum ice_ddp_state ice_get_ddp_pkg_state(struct ice_hw *hw, bool already_loaded) { if (hw->pkg_ver.major == hw->active_pkg_ver.major && hw->pkg_ver.minor == hw->active_pkg_ver.minor && hw->pkg_ver.update == hw->active_pkg_ver.update && hw->pkg_ver.draft == hw->active_pkg_ver.draft && !memcmp(hw->pkg_name, hw->active_pkg_name, sizeof(hw->pkg_name))) { if (already_loaded) return ICE_DDP_PKG_SAME_VERSION_ALREADY_LOADED; else return ICE_DDP_PKG_SUCCESS; } else if (hw->active_pkg_ver.major != ICE_PKG_SUPP_VER_MAJ || hw->active_pkg_ver.minor != ICE_PKG_SUPP_VER_MNR) { return ICE_DDP_PKG_ALREADY_LOADED_NOT_SUPPORTED; } else if (hw->active_pkg_ver.major == ICE_PKG_SUPP_VER_MAJ && hw->active_pkg_ver.minor == ICE_PKG_SUPP_VER_MNR) { return ICE_DDP_PKG_COMPATIBLE_ALREADY_LOADED; } else { return ICE_DDP_PKG_ERR; } } /** * ice_init_pkg_regs - initialize additional package registers * @hw: pointer to the hardware structure */ static void ice_init_pkg_regs(struct ice_hw *hw) { #define ICE_SW_BLK_INP_MASK_L 0xFFFFFFFF #define ICE_SW_BLK_INP_MASK_H 0x0000FFFF #define ICE_SW_BLK_IDX 0 /* setup Switch block input mask, which is 48-bits in two parts */ wr32(hw, GL_PREEXT_L2_PMASK0(ICE_SW_BLK_IDX), ICE_SW_BLK_INP_MASK_L); wr32(hw, GL_PREEXT_L2_PMASK1(ICE_SW_BLK_IDX), ICE_SW_BLK_INP_MASK_H); } /** * ice_marker_ptype_tcam_handler * @sect_type: section type * @section: pointer to section * @index: index of the Marker PType TCAM entry to be returned * @offset: pointer to receive absolute offset, always 0 for ptype TCAM sections * * This is a callback function that can be passed to ice_pkg_enum_entry. * Handles enumeration of individual Marker PType TCAM entries. */ static void *ice_marker_ptype_tcam_handler(u32 sect_type, void *section, u32 index, u32 *offset) { struct ice_marker_ptype_tcam_section *marker_ptype; if (sect_type != ICE_SID_RXPARSER_MARKER_PTYPE) return NULL; if (index > ICE_MAX_MARKER_PTYPE_TCAMS_IN_BUF) return NULL; if (offset) *offset = 0; marker_ptype = section; if (index >= le16_to_cpu(marker_ptype->count)) return NULL; return marker_ptype->tcam + index; } /** * ice_add_dvm_hint * @hw: pointer to the HW structure * @val: value of the boost entry * @enable: true if entry needs to be enabled, or false if needs to be disabled */ static void ice_add_dvm_hint(struct ice_hw *hw, u16 val, bool enable) { if (hw->dvm_upd.count < ICE_DVM_MAX_ENTRIES) { hw->dvm_upd.tbl[hw->dvm_upd.count].boost_addr = val; hw->dvm_upd.tbl[hw->dvm_upd.count].enable = enable; hw->dvm_upd.count++; } } /** * ice_add_tunnel_hint * @hw: pointer to the HW structure * @label_name: label text * @val: value of the tunnel port boost entry */ static void ice_add_tunnel_hint(struct ice_hw *hw, char *label_name, u16 val) { if (hw->tnl.count < ICE_TUNNEL_MAX_ENTRIES) { u16 i; for (i = 0; tnls[i].type != TNL_LAST; i++) { size_t len = strlen(tnls[i].label_prefix); /* Look for matching label start, before continuing */ if (strncmp(label_name, tnls[i].label_prefix, len)) continue; /* Make sure this label matches our PF. Note that the PF * character ('0' - '7') will be located where our * prefix string's null terminator is located. */ if ((label_name[len] - '0') == hw->pf_id) { hw->tnl.tbl[hw->tnl.count].type = tnls[i].type; hw->tnl.tbl[hw->tnl.count].valid = false; hw->tnl.tbl[hw->tnl.count].boost_addr = val; hw->tnl.tbl[hw->tnl.count].port = 0; hw->tnl.count++; break; } } } } /** * ice_label_enum_handler * @sect_type: section type * @section: pointer to section * @index: index of the label entry to be returned * @offset: pointer to receive absolute offset, always zero for label sections * * This is a callback function that can be passed to ice_pkg_enum_entry. * Handles enumeration of individual label entries. */ static void *ice_label_enum_handler(u32 __always_unused sect_type, void *section, u32 index, u32 *offset) { struct ice_label_section *labels; if (!section) return NULL; if (index > ICE_MAX_LABELS_IN_BUF) return NULL; if (offset) *offset = 0; labels = section; if (index >= le16_to_cpu(labels->count)) return NULL; return labels->label + index; } /** * ice_enum_labels * @ice_seg: pointer to the ice segment (NULL on subsequent calls) * @type: the section type that will contain the label (0 on subsequent calls) * @state: ice_pkg_enum structure that will hold the state of the enumeration * @value: pointer to a value that will return the label's value if found * * Enumerates a list of labels in the package. The caller will call * ice_enum_labels(ice_seg, type, ...) to start the enumeration, then call * ice_enum_labels(NULL, 0, ...) to continue. When the function returns a NULL * the end of the list has been reached. */ static char *ice_enum_labels(struct ice_seg *ice_seg, u32 type, struct ice_pkg_enum *state, u16 *value) { struct ice_label *label; /* Check for valid label section on first call */ if (type && !(type >= ICE_SID_LBL_FIRST && type <= ICE_SID_LBL_LAST)) return NULL; label = ice_pkg_enum_entry(ice_seg, state, type, NULL, ice_label_enum_handler); if (!label) return NULL; *value = le16_to_cpu(label->value); return label->name; } /** * ice_boost_tcam_handler * @sect_type: section type * @section: pointer to section * @index: index of the boost TCAM entry to be returned * @offset: pointer to receive absolute offset, always 0 for boost TCAM sections * * This is a callback function that can be passed to ice_pkg_enum_entry. * Handles enumeration of individual boost TCAM entries. */ static void *ice_boost_tcam_handler(u32 sect_type, void *section, u32 index, u32 *offset) { struct ice_boost_tcam_section *boost; if (!section) return NULL; if (sect_type != ICE_SID_RXPARSER_BOOST_TCAM) return NULL; if (index > ICE_MAX_BST_TCAMS_IN_BUF) return NULL; if (offset) *offset = 0; boost = section; if (index >= le16_to_cpu(boost->count)) return NULL; return boost->tcam + index; } /** * ice_find_boost_entry * @ice_seg: pointer to the ice segment (non-NULL) * @addr: Boost TCAM address of entry to search for * @entry: returns pointer to the entry * * Finds a particular Boost TCAM entry and returns a pointer to that entry * if it is found. The ice_seg parameter must not be NULL since the first call * to ice_pkg_enum_entry requires a pointer to an actual ice_segment structure. */ static int ice_find_boost_entry(struct ice_seg *ice_seg, u16 addr, struct ice_boost_tcam_entry **entry) { struct ice_boost_tcam_entry *tcam; struct ice_pkg_enum state; memset(&state, 0, sizeof(state)); if (!ice_seg) return -EINVAL; do { tcam = ice_pkg_enum_entry(ice_seg, &state, ICE_SID_RXPARSER_BOOST_TCAM, NULL, ice_boost_tcam_handler); if (tcam && le16_to_cpu(tcam->addr) == addr) { *entry = tcam; return 0; } ice_seg = NULL; } while (tcam); *entry = NULL; return -EIO; } /** * ice_is_init_pkg_successful - check if DDP init was successful * @state: state of the DDP pkg after download */ bool ice_is_init_pkg_successful(enum ice_ddp_state state) { switch (state) { case ICE_DDP_PKG_SUCCESS: case ICE_DDP_PKG_SAME_VERSION_ALREADY_LOADED: case ICE_DDP_PKG_COMPATIBLE_ALREADY_LOADED: return true; default: return false; } } /** * ice_pkg_buf_alloc * @hw: pointer to the HW structure * * Allocates a package buffer and returns a pointer to the buffer header. * Note: all package contents must be in Little Endian form. */ struct ice_buf_build *ice_pkg_buf_alloc(struct ice_hw *hw) { struct ice_buf_build *bld; struct ice_buf_hdr *buf; bld = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*bld), GFP_KERNEL); if (!bld) return NULL; buf = (struct ice_buf_hdr *)bld; buf->data_end = cpu_to_le16(offsetof(struct ice_buf_hdr, section_entry)); return bld; } static bool ice_is_gtp_u_profile(u16 prof_idx) { return (prof_idx >= ICE_PROFID_IPV6_GTPU_TEID && prof_idx <= ICE_PROFID_IPV6_GTPU_IPV6_TCP_INNER) || prof_idx == ICE_PROFID_IPV4_GTPU_TEID; } static bool ice_is_gtp_c_profile(u16 prof_idx) { switch (prof_idx) { case ICE_PROFID_IPV4_GTPC_TEID: case ICE_PROFID_IPV4_GTPC_NO_TEID: case ICE_PROFID_IPV6_GTPC_TEID: case ICE_PROFID_IPV6_GTPC_NO_TEID: return true; default: return false; } } /** * ice_get_sw_prof_type - determine switch profile type * @hw: pointer to the HW structure * @fv: pointer to the switch field vector * @prof_idx: profile index to check */ static enum ice_prof_type ice_get_sw_prof_type(struct ice_hw *hw, struct ice_fv *fv, u32 prof_idx) { u16 i; if (ice_is_gtp_c_profile(prof_idx)) return ICE_PROF_TUN_GTPC; if (ice_is_gtp_u_profile(prof_idx)) return ICE_PROF_TUN_GTPU; for (i = 0; i < hw->blk[ICE_BLK_SW].es.fvw; i++) { /* UDP tunnel will have UDP_OF protocol ID and VNI offset */ if (fv->ew[i].prot_id == (u8)ICE_PROT_UDP_OF && fv->ew[i].off == ICE_VNI_OFFSET) return ICE_PROF_TUN_UDP; /* GRE tunnel will have GRE protocol */ if (fv->ew[i].prot_id == (u8)ICE_PROT_GRE_OF) return ICE_PROF_TUN_GRE; } return ICE_PROF_NON_TUN; } /** * ice_get_sw_fv_bitmap - Get switch field vector bitmap based on profile type * @hw: pointer to hardware structure * @req_profs: type of profiles requested * @bm: pointer to memory for returning the bitmap of field vectors */ void ice_get_sw_fv_bitmap(struct ice_hw *hw, enum ice_prof_type req_profs, unsigned long *bm) { struct ice_pkg_enum state; struct ice_seg *ice_seg; struct ice_fv *fv; if (req_profs == ICE_PROF_ALL) { bitmap_set(bm, 0, ICE_MAX_NUM_PROFILES); return; } memset(&state, 0, sizeof(state)); bitmap_zero(bm, ICE_MAX_NUM_PROFILES); ice_seg = hw->seg; do { enum ice_prof_type prof_type; u32 offset; fv = ice_pkg_enum_entry(ice_seg, &state, ICE_SID_FLD_VEC_SW, &offset, ice_sw_fv_handler); ice_seg = NULL; if (fv) { /* Determine field vector type */ prof_type = ice_get_sw_prof_type(hw, fv, offset); if (req_profs & prof_type) set_bit((u16)offset, bm); } } while (fv); } /** * ice_get_sw_fv_list * @hw: pointer to the HW structure * @lkups: list of protocol types * @bm: bitmap of field vectors to consider * @fv_list: Head of a list * * Finds all the field vector entries from switch block that contain * a given protocol ID and offset and returns a list of structures of type * "ice_sw_fv_list_entry". Every structure in the list has a field vector * definition and profile ID information * NOTE: The caller of the function is responsible for freeing the memory * allocated for every list entry. */ int ice_get_sw_fv_list(struct ice_hw *hw, struct ice_prot_lkup_ext *lkups, unsigned long *bm, struct list_head *fv_list) { struct ice_sw_fv_list_entry *fvl; struct ice_sw_fv_list_entry *tmp; struct ice_pkg_enum state; struct ice_seg *ice_seg; struct ice_fv *fv; u32 offset; memset(&state, 0, sizeof(state)); if (!lkups->n_val_words || !hw->seg) return -EINVAL; ice_seg = hw->seg; do { u16 i; fv = ice_pkg_enum_entry(ice_seg, &state, ICE_SID_FLD_VEC_SW, &offset, ice_sw_fv_handler); if (!fv) break; ice_seg = NULL; /* If field vector is not in the bitmap list, then skip this * profile. */ if (!test_bit((u16)offset, bm)) continue; for (i = 0; i < lkups->n_val_words; i++) { int j; for (j = 0; j < hw->blk[ICE_BLK_SW].es.fvw; j++) if (fv->ew[j].prot_id == lkups->fv_words[i].prot_id && fv->ew[j].off == lkups->fv_words[i].off) break; if (j >= hw->blk[ICE_BLK_SW].es.fvw) break; if (i + 1 == lkups->n_val_words) { fvl = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*fvl), GFP_KERNEL); if (!fvl) goto err; fvl->fv_ptr = fv; fvl->profile_id = offset; list_add(&fvl->list_entry, fv_list); break; } } } while (fv); if (list_empty(fv_list)) { dev_warn(ice_hw_to_dev(hw), "Required profiles not found in currently loaded DDP package"); return -EIO; } return 0; err: list_for_each_entry_safe(fvl, tmp, fv_list, list_entry) { list_del(&fvl->list_entry); devm_kfree(ice_hw_to_dev(hw), fvl); } return -ENOMEM; } /** * ice_init_prof_result_bm - Initialize the profile result index bitmap * @hw: pointer to hardware structure */ void ice_init_prof_result_bm(struct ice_hw *hw) { struct ice_pkg_enum state; struct ice_seg *ice_seg; struct ice_fv *fv; memset(&state, 0, sizeof(state)); if (!hw->seg) return; ice_seg = hw->seg; do { u32 off; u16 i; fv = ice_pkg_enum_entry(ice_seg, &state, ICE_SID_FLD_VEC_SW, &off, ice_sw_fv_handler); ice_seg = NULL; if (!fv) break; bitmap_zero(hw->switch_info->prof_res_bm[off], ICE_MAX_FV_WORDS); /* Determine empty field vector indices, these can be * used for recipe results. Skip index 0, since it is * always used for Switch ID. */ for (i = 1; i < ICE_MAX_FV_WORDS; i++) if (fv->ew[i].prot_id == ICE_PROT_INVALID && fv->ew[i].off == ICE_FV_OFFSET_INVAL) set_bit(i, hw->switch_info->prof_res_bm[off]); } while (fv); } /** * ice_pkg_buf_free * @hw: pointer to the HW structure * @bld: pointer to pkg build (allocated by ice_pkg_buf_alloc()) * * Frees a package buffer */ void ice_pkg_buf_free(struct ice_hw *hw, struct ice_buf_build *bld) { devm_kfree(ice_hw_to_dev(hw), bld); } /** * ice_pkg_buf_reserve_section * @bld: pointer to pkg build (allocated by ice_pkg_buf_alloc()) * @count: the number of sections to reserve * * Reserves one or more section table entries in a package buffer. This routine * can be called multiple times as long as they are made before calling * ice_pkg_buf_alloc_section(). Once ice_pkg_buf_alloc_section() * is called once, the number of sections that can be allocated will not be able * to be increased; not using all reserved sections is fine, but this will * result in some wasted space in the buffer. * Note: all package contents must be in Little Endian form. */ int ice_pkg_buf_reserve_section(struct ice_buf_build *bld, u16 count) { struct ice_buf_hdr *buf; u16 section_count; u16 data_end; if (!bld) return -EINVAL; buf = (struct ice_buf_hdr *)&bld->buf; /* already an active section, can't increase table size */ section_count = le16_to_cpu(buf->section_count); if (section_count > 0) return -EIO; if (bld->reserved_section_table_entries + count > ICE_MAX_S_COUNT) return -EIO; bld->reserved_section_table_entries += count; data_end = le16_to_cpu(buf->data_end) + flex_array_size(buf, section_entry, count); buf->data_end = cpu_to_le16(data_end); return 0; } /** * ice_pkg_buf_alloc_section * @bld: pointer to pkg build (allocated by ice_pkg_buf_alloc()) * @type: the section type value * @size: the size of the section to reserve (in bytes) * * Reserves memory in the buffer for a section's content and updates the * buffers' status accordingly. This routine returns a pointer to the first * byte of the section start within the buffer, which is used to fill in the * section contents. * Note: all package contents must be in Little Endian form. */ void *ice_pkg_buf_alloc_section(struct ice_buf_build *bld, u32 type, u16 size) { struct ice_buf_hdr *buf; u16 sect_count; u16 data_end; if (!bld || !type || !size) return NULL; buf = (struct ice_buf_hdr *)&bld->buf; /* check for enough space left in buffer */ data_end = le16_to_cpu(buf->data_end); /* section start must align on 4 byte boundary */ data_end = ALIGN(data_end, 4); if ((data_end + size) > ICE_MAX_S_DATA_END) return NULL; /* check for more available section table entries */ sect_count = le16_to_cpu(buf->section_count); if (sect_count < bld->reserved_section_table_entries) { void *section_ptr = ((u8 *)buf) + data_end; buf->section_entry[sect_count].offset = cpu_to_le16(data_end); buf->section_entry[sect_count].size = cpu_to_le16(size); buf->section_entry[sect_count].type = cpu_to_le32(type); data_end += size; buf->data_end = cpu_to_le16(data_end); buf->section_count = cpu_to_le16(sect_count + 1); return section_ptr; } /* no free section table entries */ return NULL; } /** * ice_pkg_buf_alloc_single_section * @hw: pointer to the HW structure * @type: the section type value * @size: the size of the section to reserve (in bytes) * @section: returns pointer to the section * * Allocates a package buffer with a single section. * Note: all package contents must be in Little Endian form. */ struct ice_buf_build *ice_pkg_buf_alloc_single_section(struct ice_hw *hw, u32 type, u16 size, void **section) { struct ice_buf_build *buf; if (!section) return NULL; buf = ice_pkg_buf_alloc(hw); if (!buf) return NULL; if (ice_pkg_buf_reserve_section(buf, 1)) goto ice_pkg_buf_alloc_single_section_err; *section = ice_pkg_buf_alloc_section(buf, type, size); if (!*section) goto ice_pkg_buf_alloc_single_section_err; return buf; ice_pkg_buf_alloc_single_section_err: ice_pkg_buf_free(hw, buf); return NULL; } /** * ice_pkg_buf_get_active_sections * @bld: pointer to pkg build (allocated by ice_pkg_buf_alloc()) * * Returns the number of active sections. Before using the package buffer * in an update package command, the caller should make sure that there is at * least one active section - otherwise, the buffer is not legal and should * not be used. * Note: all package contents must be in Little Endian form. */ u16 ice_pkg_buf_get_active_sections(struct ice_buf_build *bld) { struct ice_buf_hdr *buf; if (!bld) return 0; buf = (struct ice_buf_hdr *)&bld->buf; return le16_to_cpu(buf->section_count); } /** * ice_pkg_buf * @bld: pointer to pkg build (allocated by ice_pkg_buf_alloc()) * * Return a pointer to the buffer's header */ struct ice_buf *ice_pkg_buf(struct ice_buf_build *bld) { if (!bld) return NULL; return &bld->buf; } static enum ice_ddp_state ice_map_aq_err_to_ddp_state(enum ice_aq_err aq_err) { switch (aq_err) { case ICE_AQ_RC_ENOSEC: case ICE_AQ_RC_EBADSIG: return ICE_DDP_PKG_FILE_SIGNATURE_INVALID; case ICE_AQ_RC_ESVN: return ICE_DDP_PKG_FILE_REVISION_TOO_LOW; case ICE_AQ_RC_EBADMAN: case ICE_AQ_RC_EBADBUF: return ICE_DDP_PKG_LOAD_ERROR; default: return ICE_DDP_PKG_ERR; } } /** * ice_acquire_global_cfg_lock * @hw: pointer to the HW structure * @access: access type (read or write) * * This function will request ownership of the global config lock for reading * or writing of the package. When attempting to obtain write access, the * caller must check for the following two return values: * * 0 - Means the caller has acquired the global config lock * and can perform writing of the package. * -EALREADY - Indicates another driver has already written the * package or has found that no update was necessary; in * this case, the caller can just skip performing any * update of the package. */ static int ice_acquire_global_cfg_lock(struct ice_hw *hw, enum ice_aq_res_access_type access) { int status; status = ice_acquire_res(hw, ICE_GLOBAL_CFG_LOCK_RES_ID, access, ICE_GLOBAL_CFG_LOCK_TIMEOUT); if (!status) mutex_lock(&ice_global_cfg_lock_sw); else if (status == -EALREADY) ice_debug(hw, ICE_DBG_PKG, "Global config lock: No work to do\n"); return status; } /** * ice_release_global_cfg_lock * @hw: pointer to the HW structure * * This function will release the global config lock. */ static void ice_release_global_cfg_lock(struct ice_hw *hw) { mutex_unlock(&ice_global_cfg_lock_sw); ice_release_res(hw, ICE_GLOBAL_CFG_LOCK_RES_ID); } /** * ice_aq_download_pkg * @hw: pointer to the hardware structure * @pkg_buf: the package buffer to transfer * @buf_size: the size of the package buffer * @last_buf: last buffer indicator * @error_offset: returns error offset * @error_info: returns error information * @cd: pointer to command details structure or NULL * * Download Package (0x0C40) */ static int ice_aq_download_pkg(struct ice_hw *hw, struct ice_buf_hdr *pkg_buf, u16 buf_size, bool last_buf, u32 *error_offset, u32 *error_info, struct ice_sq_cd *cd) { struct ice_aqc_download_pkg *cmd; struct ice_aq_desc desc; int status; if (error_offset) *error_offset = 0; if (error_info) *error_info = 0; cmd = &desc.params.download_pkg; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_download_pkg); desc.flags |= cpu_to_le16(ICE_AQ_FLAG_RD); if (last_buf) cmd->flags |= ICE_AQC_DOWNLOAD_PKG_LAST_BUF; status = ice_aq_send_cmd(hw, &desc, pkg_buf, buf_size, cd); if (status == -EIO) { /* Read error from buffer only when the FW returned an error */ struct ice_aqc_download_pkg_resp *resp; resp = (struct ice_aqc_download_pkg_resp *)pkg_buf; if (error_offset) *error_offset = le32_to_cpu(resp->error_offset); if (error_info) *error_info = le32_to_cpu(resp->error_info); } return status; } /** * ice_dwnld_cfg_bufs * @hw: pointer to the hardware structure * @bufs: pointer to an array of buffers * @count: the number of buffers in the array * * Obtains global config lock and downloads the package configuration buffers * to the firmware. Metadata buffers are skipped, and the first metadata buffer * found indicates that the rest of the buffers are all metadata buffers. */ static enum ice_ddp_state ice_dwnld_cfg_bufs(struct ice_hw *hw, struct ice_buf *bufs, u32 count) { enum ice_ddp_state state = ICE_DDP_PKG_SUCCESS; struct ice_buf_hdr *bh; enum ice_aq_err err; u32 offset, info, i; int status; if (!bufs || !count) return ICE_DDP_PKG_ERR; /* If the first buffer's first section has its metadata bit set * then there are no buffers to be downloaded, and the operation is * considered a success. */ bh = (struct ice_buf_hdr *)bufs; if (le32_to_cpu(bh->section_entry[0].type) & ICE_METADATA_BUF) return ICE_DDP_PKG_SUCCESS; status = ice_acquire_global_cfg_lock(hw, ICE_RES_WRITE); if (status) { if (status == -EALREADY) return ICE_DDP_PKG_ALREADY_LOADED; return ice_map_aq_err_to_ddp_state(hw->adminq.sq_last_status); } for (i = 0; i < count; i++) { bool last = ((i + 1) == count); if (!last) { /* check next buffer for metadata flag */ bh = (struct ice_buf_hdr *)(bufs + i + 1); /* A set metadata flag in the next buffer will signal * that the current buffer will be the last buffer * downloaded */ if (le16_to_cpu(bh->section_count)) if (le32_to_cpu(bh->section_entry[0].type) & ICE_METADATA_BUF) last = true; } bh = (struct ice_buf_hdr *)(bufs + i); status = ice_aq_download_pkg(hw, bh, ICE_PKG_BUF_SIZE, last, &offset, &info, NULL); /* Save AQ status from download package */ if (status) { ice_debug(hw, ICE_DBG_PKG, "Pkg download failed: err %d off %d inf %d\n", status, offset, info); err = hw->adminq.sq_last_status; state = ice_map_aq_err_to_ddp_state(err); break; } if (last) break; } if (!status) { status = ice_set_vlan_mode(hw); if (status) ice_debug(hw, ICE_DBG_PKG, "Failed to set VLAN mode: err %d\n", status); } ice_release_global_cfg_lock(hw); return state; } /** * ice_aq_get_pkg_info_list * @hw: pointer to the hardware structure * @pkg_info: the buffer which will receive the information list * @buf_size: the size of the pkg_info information buffer * @cd: pointer to command details structure or NULL * * Get Package Info List (0x0C43) */ static int ice_aq_get_pkg_info_list(struct ice_hw *hw, struct ice_aqc_get_pkg_info_resp *pkg_info, u16 buf_size, struct ice_sq_cd *cd) { struct ice_aq_desc desc; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_get_pkg_info_list); return ice_aq_send_cmd(hw, &desc, pkg_info, buf_size, cd); } /** * ice_download_pkg * @hw: pointer to the hardware structure * @ice_seg: pointer to the segment of the package to be downloaded * * Handles the download of a complete package. */ static enum ice_ddp_state ice_download_pkg(struct ice_hw *hw, struct ice_seg *ice_seg) { struct ice_buf_table *ice_buf_tbl; int status; ice_debug(hw, ICE_DBG_PKG, "Segment format version: %d.%d.%d.%d\n", ice_seg->hdr.seg_format_ver.major, ice_seg->hdr.seg_format_ver.minor, ice_seg->hdr.seg_format_ver.update, ice_seg->hdr.seg_format_ver.draft); ice_debug(hw, ICE_DBG_PKG, "Seg: type 0x%X, size %d, name %s\n", le32_to_cpu(ice_seg->hdr.seg_type), le32_to_cpu(ice_seg->hdr.seg_size), ice_seg->hdr.seg_id); ice_buf_tbl = ice_find_buf_table(ice_seg); ice_debug(hw, ICE_DBG_PKG, "Seg buf count: %d\n", le32_to_cpu(ice_buf_tbl->buf_count)); status = ice_dwnld_cfg_bufs(hw, ice_buf_tbl->buf_array, le32_to_cpu(ice_buf_tbl->buf_count)); ice_post_pkg_dwnld_vlan_mode_cfg(hw); return status; } /** * ice_aq_update_pkg * @hw: pointer to the hardware structure * @pkg_buf: the package cmd buffer * @buf_size: the size of the package cmd buffer * @last_buf: last buffer indicator * @error_offset: returns error offset * @error_info: returns error information * @cd: pointer to command details structure or NULL * * Update Package (0x0C42) */ static int ice_aq_update_pkg(struct ice_hw *hw, struct ice_buf_hdr *pkg_buf, u16 buf_size, bool last_buf, u32 *error_offset, u32 *error_info, struct ice_sq_cd *cd) { struct ice_aqc_download_pkg *cmd; struct ice_aq_desc desc; int status; if (error_offset) *error_offset = 0; if (error_info) *error_info = 0; cmd = &desc.params.download_pkg; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_update_pkg); desc.flags |= cpu_to_le16(ICE_AQ_FLAG_RD); if (last_buf) cmd->flags |= ICE_AQC_DOWNLOAD_PKG_LAST_BUF; status = ice_aq_send_cmd(hw, &desc, pkg_buf, buf_size, cd); if (status == -EIO) { /* Read error from buffer only when the FW returned an error */ struct ice_aqc_download_pkg_resp *resp; resp = (struct ice_aqc_download_pkg_resp *)pkg_buf; if (error_offset) *error_offset = le32_to_cpu(resp->error_offset); if (error_info) *error_info = le32_to_cpu(resp->error_info); } return status; } /** * ice_aq_upload_section * @hw: pointer to the hardware structure * @pkg_buf: the package buffer which will receive the section * @buf_size: the size of the package buffer * @cd: pointer to command details structure or NULL * * Upload Section (0x0C41) */ int ice_aq_upload_section(struct ice_hw *hw, struct ice_buf_hdr *pkg_buf, u16 buf_size, struct ice_sq_cd *cd) { struct ice_aq_desc desc; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_upload_section); desc.flags |= cpu_to_le16(ICE_AQ_FLAG_RD); return ice_aq_send_cmd(hw, &desc, pkg_buf, buf_size, cd); } /** * ice_update_pkg_no_lock * @hw: pointer to the hardware structure * @bufs: pointer to an array of buffers * @count: the number of buffers in the array */ int ice_update_pkg_no_lock(struct ice_hw *hw, struct ice_buf *bufs, u32 count) { int status = 0; u32 i; for (i = 0; i < count; i++) { struct ice_buf_hdr *bh = (struct ice_buf_hdr *)(bufs + i); bool last = ((i + 1) == count); u32 offset, info; status = ice_aq_update_pkg(hw, bh, le16_to_cpu(bh->data_end), last, &offset, &info, NULL); if (status) { ice_debug(hw, ICE_DBG_PKG, "Update pkg failed: err %d off %d inf %d\n", status, offset, info); break; } } return status; } /** * ice_update_pkg * @hw: pointer to the hardware structure * @bufs: pointer to an array of buffers * @count: the number of buffers in the array * * Obtains change lock and updates package. */ int ice_update_pkg(struct ice_hw *hw, struct ice_buf *bufs, u32 count) { int status; status = ice_acquire_change_lock(hw, ICE_RES_WRITE); if (status) return status; status = ice_update_pkg_no_lock(hw, bufs, count); ice_release_change_lock(hw); return status; } /** * ice_find_seg_in_pkg * @hw: pointer to the hardware structure * @seg_type: the segment type to search for (i.e., SEGMENT_TYPE_CPK) * @pkg_hdr: pointer to the package header to be searched * * This function searches a package file for a particular segment type. On * success it returns a pointer to the segment header, otherwise it will * return NULL. */ static struct ice_generic_seg_hdr * ice_find_seg_in_pkg(struct ice_hw *hw, u32 seg_type, struct ice_pkg_hdr *pkg_hdr) { u32 i; ice_debug(hw, ICE_DBG_PKG, "Package format version: %d.%d.%d.%d\n", pkg_hdr->pkg_format_ver.major, pkg_hdr->pkg_format_ver.minor, pkg_hdr->pkg_format_ver.update, pkg_hdr->pkg_format_ver.draft); /* Search all package segments for the requested segment type */ for (i = 0; i < le32_to_cpu(pkg_hdr->seg_count); i++) { struct ice_generic_seg_hdr *seg; seg = (struct ice_generic_seg_hdr *)((u8 *)pkg_hdr + le32_to_cpu(pkg_hdr->seg_offset[i])); if (le32_to_cpu(seg->seg_type) == seg_type) return seg; } return NULL; } /** * ice_init_pkg_info * @hw: pointer to the hardware structure * @pkg_hdr: pointer to the driver's package hdr * * Saves off the package details into the HW structure. */ static enum ice_ddp_state ice_init_pkg_info(struct ice_hw *hw, struct ice_pkg_hdr *pkg_hdr) { struct ice_generic_seg_hdr *seg_hdr; if (!pkg_hdr) return ICE_DDP_PKG_ERR; seg_hdr = ice_find_seg_in_pkg(hw, SEGMENT_TYPE_ICE, pkg_hdr); if (seg_hdr) { struct ice_meta_sect *meta; struct ice_pkg_enum state; memset(&state, 0, sizeof(state)); /* Get package information from the Metadata Section */ meta = ice_pkg_enum_section((struct ice_seg *)seg_hdr, &state, ICE_SID_METADATA); if (!meta) { ice_debug(hw, ICE_DBG_INIT, "Did not find ice metadata section in package\n"); return ICE_DDP_PKG_INVALID_FILE; } hw->pkg_ver = meta->ver; memcpy(hw->pkg_name, meta->name, sizeof(meta->name)); ice_debug(hw, ICE_DBG_PKG, "Pkg: %d.%d.%d.%d, %s\n", meta->ver.major, meta->ver.minor, meta->ver.update, meta->ver.draft, meta->name); hw->ice_seg_fmt_ver = seg_hdr->seg_format_ver; memcpy(hw->ice_seg_id, seg_hdr->seg_id, sizeof(hw->ice_seg_id)); ice_debug(hw, ICE_DBG_PKG, "Ice Seg: %d.%d.%d.%d, %s\n", seg_hdr->seg_format_ver.major, seg_hdr->seg_format_ver.minor, seg_hdr->seg_format_ver.update, seg_hdr->seg_format_ver.draft, seg_hdr->seg_id); } else { ice_debug(hw, ICE_DBG_INIT, "Did not find ice segment in driver package\n"); return ICE_DDP_PKG_INVALID_FILE; } return ICE_DDP_PKG_SUCCESS; } /** * ice_get_pkg_info * @hw: pointer to the hardware structure * * Store details of the package currently loaded in HW into the HW structure. */ static enum ice_ddp_state ice_get_pkg_info(struct ice_hw *hw) { enum ice_ddp_state state = ICE_DDP_PKG_SUCCESS; struct ice_aqc_get_pkg_info_resp *pkg_info; u16 size; u32 i; size = struct_size(pkg_info, pkg_info, ICE_PKG_CNT); pkg_info = kzalloc(size, GFP_KERNEL); if (!pkg_info) return ICE_DDP_PKG_ERR; if (ice_aq_get_pkg_info_list(hw, pkg_info, size, NULL)) { state = ICE_DDP_PKG_ERR; goto init_pkg_free_alloc; } for (i = 0; i < le32_to_cpu(pkg_info->count); i++) { #define ICE_PKG_FLAG_COUNT 4 char flags[ICE_PKG_FLAG_COUNT + 1] = { 0 }; u8 place = 0; if (pkg_info->pkg_info[i].is_active) { flags[place++] = 'A'; hw->active_pkg_ver = pkg_info->pkg_info[i].ver; hw->active_track_id = le32_to_cpu(pkg_info->pkg_info[i].track_id); memcpy(hw->active_pkg_name, pkg_info->pkg_info[i].name, sizeof(pkg_info->pkg_info[i].name)); hw->active_pkg_in_nvm = pkg_info->pkg_info[i].is_in_nvm; } if (pkg_info->pkg_info[i].is_active_at_boot) flags[place++] = 'B'; if (pkg_info->pkg_info[i].is_modified) flags[place++] = 'M'; if (pkg_info->pkg_info[i].is_in_nvm) flags[place++] = 'N'; ice_debug(hw, ICE_DBG_PKG, "Pkg[%d]: %d.%d.%d.%d,%s,%s\n", i, pkg_info->pkg_info[i].ver.major, pkg_info->pkg_info[i].ver.minor, pkg_info->pkg_info[i].ver.update, pkg_info->pkg_info[i].ver.draft, pkg_info->pkg_info[i].name, flags); } init_pkg_free_alloc: kfree(pkg_info); return state; } /** * ice_chk_pkg_compat * @hw: pointer to the hardware structure * @ospkg: pointer to the package hdr * @seg: pointer to the package segment hdr * * This function checks the package version compatibility with driver and NVM */ static enum ice_ddp_state ice_chk_pkg_compat(struct ice_hw *hw, struct ice_pkg_hdr *ospkg, struct ice_seg **seg) { struct ice_aqc_get_pkg_info_resp *pkg; enum ice_ddp_state state; u16 size; u32 i; /* Check package version compatibility */ state = ice_chk_pkg_version(&hw->pkg_ver); if (state) { ice_debug(hw, ICE_DBG_INIT, "Package version check failed.\n"); return state; } /* find ICE segment in given package */ *seg = (struct ice_seg *)ice_find_seg_in_pkg(hw, SEGMENT_TYPE_ICE, ospkg); if (!*seg) { ice_debug(hw, ICE_DBG_INIT, "no ice segment in package.\n"); return ICE_DDP_PKG_INVALID_FILE; } /* Check if FW is compatible with the OS package */ size = struct_size(pkg, pkg_info, ICE_PKG_CNT); pkg = kzalloc(size, GFP_KERNEL); if (!pkg) return ICE_DDP_PKG_ERR; if (ice_aq_get_pkg_info_list(hw, pkg, size, NULL)) { state = ICE_DDP_PKG_LOAD_ERROR; goto fw_ddp_compat_free_alloc; } for (i = 0; i < le32_to_cpu(pkg->count); i++) { /* loop till we find the NVM package */ if (!pkg->pkg_info[i].is_in_nvm) continue; if ((*seg)->hdr.seg_format_ver.major != pkg->pkg_info[i].ver.major || (*seg)->hdr.seg_format_ver.minor > pkg->pkg_info[i].ver.minor) { state = ICE_DDP_PKG_FW_MISMATCH; ice_debug(hw, ICE_DBG_INIT, "OS package is not compatible with NVM.\n"); } /* done processing NVM package so break */ break; } fw_ddp_compat_free_alloc: kfree(pkg); return state; } /** * ice_init_pkg_hints * @hw: pointer to the HW structure * @ice_seg: pointer to the segment of the package scan (non-NULL) * * This function will scan the package and save off relevant information * (hints or metadata) for driver use. The ice_seg parameter must not be NULL * since the first call to ice_enum_labels requires a pointer to an actual * ice_seg structure. */ static void ice_init_pkg_hints(struct ice_hw *hw, struct ice_seg *ice_seg) { struct ice_pkg_enum state; char *label_name; u16 val; int i; memset(&hw->tnl, 0, sizeof(hw->tnl)); memset(&state, 0, sizeof(state)); if (!ice_seg) return; label_name = ice_enum_labels(ice_seg, ICE_SID_LBL_RXPARSER_TMEM, &state, &val); while (label_name) { if (!strncmp(label_name, ICE_TNL_PRE, strlen(ICE_TNL_PRE))) /* check for a tunnel entry */ ice_add_tunnel_hint(hw, label_name, val); /* check for a dvm mode entry */ else if (!strncmp(label_name, ICE_DVM_PRE, strlen(ICE_DVM_PRE))) ice_add_dvm_hint(hw, val, true); /* check for a svm mode entry */ else if (!strncmp(label_name, ICE_SVM_PRE, strlen(ICE_SVM_PRE))) ice_add_dvm_hint(hw, val, false); label_name = ice_enum_labels(NULL, 0, &state, &val); } /* Cache the appropriate boost TCAM entry pointers for tunnels */ for (i = 0; i < hw->tnl.count; i++) { ice_find_boost_entry(ice_seg, hw->tnl.tbl[i].boost_addr, &hw->tnl.tbl[i].boost_entry); if (hw->tnl.tbl[i].boost_entry) { hw->tnl.tbl[i].valid = true; if (hw->tnl.tbl[i].type < __TNL_TYPE_CNT) hw->tnl.valid_count[hw->tnl.tbl[i].type]++; } } /* Cache the appropriate boost TCAM entry pointers for DVM and SVM */ for (i = 0; i < hw->dvm_upd.count; i++) ice_find_boost_entry(ice_seg, hw->dvm_upd.tbl[i].boost_addr, &hw->dvm_upd.tbl[i].boost_entry); } /** * ice_fill_hw_ptype - fill the enabled PTYPE bit information * @hw: pointer to the HW structure */ static void ice_fill_hw_ptype(struct ice_hw *hw) { struct ice_marker_ptype_tcam_entry *tcam; struct ice_seg *seg = hw->seg; struct ice_pkg_enum state; bitmap_zero(hw->hw_ptype, ICE_FLOW_PTYPE_MAX); if (!seg) return; memset(&state, 0, sizeof(state)); do { tcam = ice_pkg_enum_entry(seg, &state, ICE_SID_RXPARSER_MARKER_PTYPE, NULL, ice_marker_ptype_tcam_handler); if (tcam && le16_to_cpu(tcam->addr) < ICE_MARKER_PTYPE_TCAM_ADDR_MAX && le16_to_cpu(tcam->ptype) < ICE_FLOW_PTYPE_MAX) set_bit(le16_to_cpu(tcam->ptype), hw->hw_ptype); seg = NULL; } while (tcam); } /** * ice_init_pkg - initialize/download package * @hw: pointer to the hardware structure * @buf: pointer to the package buffer * @len: size of the package buffer * * This function initializes a package. The package contains HW tables * required to do packet processing. First, the function extracts package * information such as version. Then it finds the ice configuration segment * within the package; this function then saves a copy of the segment pointer * within the supplied package buffer. Next, the function will cache any hints * from the package, followed by downloading the package itself. Note, that if * a previous PF driver has already downloaded the package successfully, then * the current driver will not have to download the package again. * * The local package contents will be used to query default behavior and to * update specific sections of the HW's version of the package (e.g. to update * the parse graph to understand new protocols). * * This function stores a pointer to the package buffer memory, and it is * expected that the supplied buffer will not be freed immediately. If the * package buffer needs to be freed, such as when read from a file, use * ice_copy_and_init_pkg() instead of directly calling ice_init_pkg() in this * case. */ enum ice_ddp_state ice_init_pkg(struct ice_hw *hw, u8 *buf, u32 len) { bool already_loaded = false; enum ice_ddp_state state; struct ice_pkg_hdr *pkg; struct ice_seg *seg; if (!buf || !len) return ICE_DDP_PKG_ERR; pkg = (struct ice_pkg_hdr *)buf; state = ice_verify_pkg(pkg, len); if (state) { ice_debug(hw, ICE_DBG_INIT, "failed to verify pkg (err: %d)\n", state); return state; } /* initialize package info */ state = ice_init_pkg_info(hw, pkg); if (state) return state; /* before downloading the package, check package version for * compatibility with driver */ state = ice_chk_pkg_compat(hw, pkg, &seg); if (state) return state; /* initialize package hints and then download package */ ice_init_pkg_hints(hw, seg); state = ice_download_pkg(hw, seg); if (state == ICE_DDP_PKG_ALREADY_LOADED) { ice_debug(hw, ICE_DBG_INIT, "package previously loaded - no work.\n"); already_loaded = true; } /* Get information on the package currently loaded in HW, then make sure * the driver is compatible with this version. */ if (!state || state == ICE_DDP_PKG_ALREADY_LOADED) { state = ice_get_pkg_info(hw); if (!state) state = ice_get_ddp_pkg_state(hw, already_loaded); } if (ice_is_init_pkg_successful(state)) { hw->seg = seg; /* on successful package download update other required * registers to support the package and fill HW tables * with package content. */ ice_init_pkg_regs(hw); ice_fill_blk_tbls(hw); ice_fill_hw_ptype(hw); ice_get_prof_index_max(hw); } else { ice_debug(hw, ICE_DBG_INIT, "package load failed, %d\n", state); } return state; } /** * ice_copy_and_init_pkg - initialize/download a copy of the package * @hw: pointer to the hardware structure * @buf: pointer to the package buffer * @len: size of the package buffer * * This function copies the package buffer, and then calls ice_init_pkg() to * initialize the copied package contents. * * The copying is necessary if the package buffer supplied is constant, or if * the memory may disappear shortly after calling this function. * * If the package buffer resides in the data segment and can be modified, the * caller is free to use ice_init_pkg() instead of ice_copy_and_init_pkg(). * * However, if the package buffer needs to be copied first, such as when being * read from a file, the caller should use ice_copy_and_init_pkg(). * * This function will first copy the package buffer, before calling * ice_init_pkg(). The caller is free to immediately destroy the original * package buffer, as the new copy will be managed by this function and * related routines. */ enum ice_ddp_state ice_copy_and_init_pkg(struct ice_hw *hw, const u8 *buf, u32 len) { enum ice_ddp_state state; u8 *buf_copy; if (!buf || !len) return ICE_DDP_PKG_ERR; buf_copy = devm_kmemdup(ice_hw_to_dev(hw), buf, len, GFP_KERNEL); state = ice_init_pkg(hw, buf_copy, len); if (!ice_is_init_pkg_successful(state)) { /* Free the copy, since we failed to initialize the package */ devm_kfree(ice_hw_to_dev(hw), buf_copy); } else { /* Track the copied pkg so we can free it later */ hw->pkg_copy = buf_copy; hw->pkg_size = len; } return state; }
linux-master
drivers/net/ethernet/intel/ice/ice_ddp.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2018-2019, Intel Corporation. */ #include <asm/unaligned.h> #include <linux/uuid.h> #include <linux/crc32.h> #include <linux/pldmfw.h> #include "ice.h" #include "ice_fw_update.h" struct ice_fwu_priv { struct pldmfw context; struct ice_pf *pf; struct netlink_ext_ack *extack; /* Track which NVM banks to activate at the end of the update */ u8 activate_flags; /* Track the firmware response of the required reset to complete the * flash update. * * 0 - ICE_AQC_NVM_POR_FLAG - A full power on is required * 1 - ICE_AQC_NVM_PERST_FLAG - A cold PCIe reset is required * 2 - ICE_AQC_NVM_EMPR_FLAG - An EMP reset is required */ u8 reset_level; /* Track if EMP reset is available */ u8 emp_reset_available; }; /** * ice_send_package_data - Send record package data to firmware * @context: PLDM fw update structure * @data: pointer to the package data * @length: length of the package data * * Send a copy of the package data associated with the PLDM record matching * this device to the firmware. * * Note that this function sends an AdminQ command that will fail unless the * NVM resource has been acquired. * * Returns: zero on success, or a negative error code on failure. */ static int ice_send_package_data(struct pldmfw *context, const u8 *data, u16 length) { struct ice_fwu_priv *priv = container_of(context, struct ice_fwu_priv, context); struct netlink_ext_ack *extack = priv->extack; struct device *dev = context->dev; struct ice_pf *pf = priv->pf; struct ice_hw *hw = &pf->hw; u8 *package_data; int status; dev_dbg(dev, "Sending PLDM record package data to firmware\n"); package_data = kmemdup(data, length, GFP_KERNEL); if (!package_data) return -ENOMEM; status = ice_nvm_set_pkg_data(hw, false, package_data, length, NULL); kfree(package_data); if (status) { dev_err(dev, "Failed to send record package data to firmware, err %d aq_err %s\n", status, ice_aq_str(hw->adminq.sq_last_status)); NL_SET_ERR_MSG_MOD(extack, "Failed to record package data to firmware"); return -EIO; } return 0; } /** * ice_check_component_response - Report firmware response to a component * @pf: device private data structure * @id: component id being checked * @response: indicates whether this component can be updated * @code: code indicating reason for response * @extack: netlink extended ACK structure * * Check whether firmware indicates if this component can be updated. Report * a suitable error message over the netlink extended ACK if the component * cannot be updated. * * Returns: zero if the component can be updated, or -ECANCELED of the * firmware indicates the component cannot be updated. */ static int ice_check_component_response(struct ice_pf *pf, u16 id, u8 response, u8 code, struct netlink_ext_ack *extack) { struct device *dev = ice_pf_to_dev(pf); const char *component; switch (id) { case NVM_COMP_ID_OROM: component = "fw.undi"; break; case NVM_COMP_ID_NVM: component = "fw.mgmt"; break; case NVM_COMP_ID_NETLIST: component = "fw.netlist"; break; default: WARN(1, "Unexpected unknown component identifier 0x%02x", id); return -EINVAL; } dev_dbg(dev, "%s: firmware response 0x%x, code 0x%x\n", component, response, code); switch (response) { case ICE_AQ_NVM_PASS_COMP_CAN_BE_UPDATED: /* firmware indicated this update is good to proceed */ return 0; case ICE_AQ_NVM_PASS_COMP_CAN_MAY_BE_UPDATEABLE: dev_warn(dev, "firmware recommends not updating %s, as it may result in a downgrade. continuing anyways\n", component); return 0; case ICE_AQ_NVM_PASS_COMP_CAN_NOT_BE_UPDATED: dev_info(dev, "firmware has rejected updating %s\n", component); break; } switch (code) { case ICE_AQ_NVM_PASS_COMP_STAMP_IDENTICAL_CODE: dev_err(dev, "Component comparison stamp for %s is identical to the running image\n", component); NL_SET_ERR_MSG_MOD(extack, "Component comparison stamp is identical to running image"); break; case ICE_AQ_NVM_PASS_COMP_STAMP_LOWER: dev_err(dev, "Component comparison stamp for %s is lower than the running image\n", component); NL_SET_ERR_MSG_MOD(extack, "Component comparison stamp is lower than running image"); break; case ICE_AQ_NVM_PASS_COMP_INVALID_STAMP_CODE: dev_err(dev, "Component comparison stamp for %s is invalid\n", component); NL_SET_ERR_MSG_MOD(extack, "Component comparison stamp is invalid"); break; case ICE_AQ_NVM_PASS_COMP_CONFLICT_CODE: dev_err(dev, "%s conflicts with a previous component table\n", component); NL_SET_ERR_MSG_MOD(extack, "Component table conflict occurred"); break; case ICE_AQ_NVM_PASS_COMP_PRE_REQ_NOT_MET_CODE: dev_err(dev, "Pre-requisites for component %s have not been met\n", component); NL_SET_ERR_MSG_MOD(extack, "Component pre-requisites not met"); break; case ICE_AQ_NVM_PASS_COMP_NOT_SUPPORTED_CODE: dev_err(dev, "%s is not a supported component\n", component); NL_SET_ERR_MSG_MOD(extack, "Component not supported"); break; case ICE_AQ_NVM_PASS_COMP_CANNOT_DOWNGRADE_CODE: dev_err(dev, "Security restrictions prevent %s from being downgraded\n", component); NL_SET_ERR_MSG_MOD(extack, "Component cannot be downgraded"); break; case ICE_AQ_NVM_PASS_COMP_INCOMPLETE_IMAGE_CODE: dev_err(dev, "Received an incomplete component image for %s\n", component); NL_SET_ERR_MSG_MOD(extack, "Incomplete component image"); break; case ICE_AQ_NVM_PASS_COMP_VER_STR_IDENTICAL_CODE: dev_err(dev, "Component version for %s is identical to the running image\n", component); NL_SET_ERR_MSG_MOD(extack, "Component version is identical to running image"); break; case ICE_AQ_NVM_PASS_COMP_VER_STR_LOWER_CODE: dev_err(dev, "Component version for %s is lower than the running image\n", component); NL_SET_ERR_MSG_MOD(extack, "Component version is lower than the running image"); break; default: dev_err(dev, "Unexpected response code 0x02%x for %s\n", code, component); NL_SET_ERR_MSG_MOD(extack, "Received unexpected response code from firmware"); break; } return -ECANCELED; } /** * ice_send_component_table - Send PLDM component table to firmware * @context: PLDM fw update structure * @component: the component to process * @transfer_flag: relative transfer order of this component * * Read relevant data from the component and forward it to the device * firmware. Check the response to determine if the firmware indicates that * the update can proceed. * * This function sends AdminQ commands related to the NVM, and assumes that * the NVM resource has been acquired. * * Returns: zero on success, or a negative error code on failure. */ static int ice_send_component_table(struct pldmfw *context, struct pldmfw_component *component, u8 transfer_flag) { struct ice_fwu_priv *priv = container_of(context, struct ice_fwu_priv, context); struct netlink_ext_ack *extack = priv->extack; struct ice_aqc_nvm_comp_tbl *comp_tbl; u8 comp_response, comp_response_code; struct device *dev = context->dev; struct ice_pf *pf = priv->pf; struct ice_hw *hw = &pf->hw; size_t length; int status; switch (component->identifier) { case NVM_COMP_ID_OROM: case NVM_COMP_ID_NVM: case NVM_COMP_ID_NETLIST: break; default: dev_err(dev, "Unable to update due to a firmware component with unknown ID %u\n", component->identifier); NL_SET_ERR_MSG_MOD(extack, "Unable to update due to unknown firmware component"); return -EOPNOTSUPP; } length = struct_size(comp_tbl, cvs, component->version_len); comp_tbl = kzalloc(length, GFP_KERNEL); if (!comp_tbl) return -ENOMEM; comp_tbl->comp_class = cpu_to_le16(component->classification); comp_tbl->comp_id = cpu_to_le16(component->identifier); comp_tbl->comp_class_idx = FWU_COMP_CLASS_IDX_NOT_USE; comp_tbl->comp_cmp_stamp = cpu_to_le32(component->comparison_stamp); comp_tbl->cvs_type = component->version_type; comp_tbl->cvs_len = component->version_len; memcpy(comp_tbl->cvs, component->version_string, component->version_len); dev_dbg(dev, "Sending component table to firmware:\n"); status = ice_nvm_pass_component_tbl(hw, (u8 *)comp_tbl, length, transfer_flag, &comp_response, &comp_response_code, NULL); kfree(comp_tbl); if (status) { dev_err(dev, "Failed to transfer component table to firmware, err %d aq_err %s\n", status, ice_aq_str(hw->adminq.sq_last_status)); NL_SET_ERR_MSG_MOD(extack, "Failed to transfer component table to firmware"); return -EIO; } return ice_check_component_response(pf, component->identifier, comp_response, comp_response_code, extack); } /** * ice_write_one_nvm_block - Write an NVM block and await completion response * @pf: the PF data structure * @module: the module to write to * @offset: offset in bytes * @block_size: size of the block to write, up to 4k * @block: pointer to block of data to write * @last_cmd: whether this is the last command * @reset_level: storage for reset level required * @extack: netlink extended ACK structure * * Write a block of data to a flash module, and await for the completion * response message from firmware. * * Note this function assumes the caller has acquired the NVM resource. * * On successful return, reset level indicates the device reset required to * complete the update. * * 0 - ICE_AQC_NVM_POR_FLAG - A full power on is required * 1 - ICE_AQC_NVM_PERST_FLAG - A cold PCIe reset is required * 2 - ICE_AQC_NVM_EMPR_FLAG - An EMP reset is required * * Returns: zero on success, or a negative error code on failure. */ static int ice_write_one_nvm_block(struct ice_pf *pf, u16 module, u32 offset, u16 block_size, u8 *block, bool last_cmd, u8 *reset_level, struct netlink_ext_ack *extack) { u16 completion_module, completion_retval; struct device *dev = ice_pf_to_dev(pf); struct ice_aq_task task = {}; struct ice_hw *hw = &pf->hw; struct ice_aq_desc *desc; u32 completion_offset; int err; dev_dbg(dev, "Writing block of %u bytes for module 0x%02x at offset %u\n", block_size, module, offset); ice_aq_prep_for_event(pf, &task, ice_aqc_opc_nvm_write); err = ice_aq_update_nvm(hw, module, offset, block_size, block, last_cmd, 0, NULL); if (err) { dev_err(dev, "Failed to flash module 0x%02x with block of size %u at offset %u, err %d aq_err %s\n", module, block_size, offset, err, ice_aq_str(hw->adminq.sq_last_status)); NL_SET_ERR_MSG_MOD(extack, "Failed to program flash module"); return -EIO; } /* In most cases, firmware reports a write completion within a few * milliseconds. However, it has been observed that a completion might * take more than a second to complete in some cases. The timeout here * is conservative and is intended to prevent failure to update when * firmware is slow to respond. */ err = ice_aq_wait_for_event(pf, &task, 15 * HZ); if (err) { dev_err(dev, "Timed out while trying to flash module 0x%02x with block of size %u at offset %u, err %d\n", module, block_size, offset, err); NL_SET_ERR_MSG_MOD(extack, "Timed out waiting for firmware"); return -EIO; } desc = &task.event.desc; completion_module = le16_to_cpu(desc->params.nvm.module_typeid); completion_retval = le16_to_cpu(desc->retval); completion_offset = le16_to_cpu(desc->params.nvm.offset_low); completion_offset |= desc->params.nvm.offset_high << 16; if (completion_module != module) { dev_err(dev, "Unexpected module_typeid in write completion: got 0x%x, expected 0x%x\n", completion_module, module); NL_SET_ERR_MSG_MOD(extack, "Unexpected firmware response"); return -EIO; } if (completion_offset != offset) { dev_err(dev, "Unexpected offset in write completion: got %u, expected %u\n", completion_offset, offset); NL_SET_ERR_MSG_MOD(extack, "Unexpected firmware response"); return -EIO; } if (completion_retval) { dev_err(dev, "Firmware failed to flash module 0x%02x with block of size %u at offset %u, err %s\n", module, block_size, offset, ice_aq_str((enum ice_aq_err)completion_retval)); NL_SET_ERR_MSG_MOD(extack, "Firmware failed to program flash module"); return -EIO; } /* For the last command to write the NVM bank, newer versions of * firmware indicate the required level of reset to complete * activation of firmware. If the firmware supports this, cache the * response for indicating to the user later. Otherwise, assume that * a full power cycle is required. */ if (reset_level && last_cmd && module == ICE_SR_1ST_NVM_BANK_PTR) { if (hw->dev_caps.common_cap.pcie_reset_avoidance) { *reset_level = desc->params.nvm.cmd_flags & ICE_AQC_NVM_RESET_LVL_M; dev_dbg(dev, "Firmware reported required reset level as %u\n", *reset_level); } else { *reset_level = ICE_AQC_NVM_POR_FLAG; dev_dbg(dev, "Firmware doesn't support indicating required reset level. Assuming a power cycle is required\n"); } } return 0; } /** * ice_write_nvm_module - Write data to an NVM module * @pf: the PF driver structure * @module: the module id to program * @component: the name of the component being updated * @image: buffer of image data to write to the NVM * @length: length of the buffer * @reset_level: storage for reset level required * @extack: netlink extended ACK structure * * Loop over the data for a given NVM module and program it in 4 Kb * blocks. Notify devlink core of progress after each block is programmed. * Loops over a block of data and programs the NVM in 4k block chunks. * * Note this function assumes the caller has acquired the NVM resource. * * Returns: zero on success, or a negative error code on failure. */ static int ice_write_nvm_module(struct ice_pf *pf, u16 module, const char *component, const u8 *image, u32 length, u8 *reset_level, struct netlink_ext_ack *extack) { struct device *dev = ice_pf_to_dev(pf); struct devlink *devlink; u32 offset = 0; bool last_cmd; u8 *block; int err; dev_dbg(dev, "Beginning write of flash component '%s', module 0x%02x\n", component, module); devlink = priv_to_devlink(pf); devlink_flash_update_status_notify(devlink, "Flashing", component, 0, length); block = kzalloc(ICE_AQ_MAX_BUF_LEN, GFP_KERNEL); if (!block) return -ENOMEM; do { u32 block_size; block_size = min_t(u32, ICE_AQ_MAX_BUF_LEN, length - offset); last_cmd = !(offset + block_size < length); /* ice_aq_update_nvm may copy the firmware response into the * buffer, so we must make a copy since the source data is * constant. */ memcpy(block, image + offset, block_size); err = ice_write_one_nvm_block(pf, module, offset, block_size, block, last_cmd, reset_level, extack); if (err) break; offset += block_size; devlink_flash_update_status_notify(devlink, "Flashing", component, offset, length); } while (!last_cmd); dev_dbg(dev, "Completed write of flash component '%s', module 0x%02x\n", component, module); if (err) devlink_flash_update_status_notify(devlink, "Flashing failed", component, length, length); else devlink_flash_update_status_notify(devlink, "Flashing done", component, length, length); kfree(block); return err; } /* Length in seconds to wait before timing out when erasing a flash module. * Yes, erasing really can take minutes to complete. */ #define ICE_FW_ERASE_TIMEOUT 300 /** * ice_erase_nvm_module - Erase an NVM module and await firmware completion * @pf: the PF data structure * @module: the module to erase * @component: name of the component being updated * @extack: netlink extended ACK structure * * Erase the inactive NVM bank associated with this module, and await for * a completion response message from firmware. * * Note this function assumes the caller has acquired the NVM resource. * * Returns: zero on success, or a negative error code on failure. */ static int ice_erase_nvm_module(struct ice_pf *pf, u16 module, const char *component, struct netlink_ext_ack *extack) { u16 completion_module, completion_retval; struct device *dev = ice_pf_to_dev(pf); struct ice_aq_task task = {}; struct ice_hw *hw = &pf->hw; struct ice_aq_desc *desc; struct devlink *devlink; int err; dev_dbg(dev, "Beginning erase of flash component '%s', module 0x%02x\n", component, module); devlink = priv_to_devlink(pf); devlink_flash_update_timeout_notify(devlink, "Erasing", component, ICE_FW_ERASE_TIMEOUT); ice_aq_prep_for_event(pf, &task, ice_aqc_opc_nvm_erase); err = ice_aq_erase_nvm(hw, module, NULL); if (err) { dev_err(dev, "Failed to erase %s (module 0x%02x), err %d aq_err %s\n", component, module, err, ice_aq_str(hw->adminq.sq_last_status)); NL_SET_ERR_MSG_MOD(extack, "Failed to erase flash module"); err = -EIO; goto out_notify_devlink; } err = ice_aq_wait_for_event(pf, &task, ICE_FW_ERASE_TIMEOUT * HZ); if (err) { dev_err(dev, "Timed out waiting for firmware to respond with erase completion for %s (module 0x%02x), err %d\n", component, module, err); NL_SET_ERR_MSG_MOD(extack, "Timed out waiting for firmware"); goto out_notify_devlink; } desc = &task.event.desc; completion_module = le16_to_cpu(desc->params.nvm.module_typeid); completion_retval = le16_to_cpu(desc->retval); if (completion_module != module) { dev_err(dev, "Unexpected module_typeid in erase completion for %s: got 0x%x, expected 0x%x\n", component, completion_module, module); NL_SET_ERR_MSG_MOD(extack, "Unexpected firmware response"); err = -EIO; goto out_notify_devlink; } if (completion_retval) { dev_err(dev, "Firmware failed to erase %s (module 0x02%x), aq_err %s\n", component, module, ice_aq_str((enum ice_aq_err)completion_retval)); NL_SET_ERR_MSG_MOD(extack, "Firmware failed to erase flash"); err = -EIO; goto out_notify_devlink; } dev_dbg(dev, "Completed erase of flash component '%s', module 0x%02x\n", component, module); out_notify_devlink: if (err) devlink_flash_update_status_notify(devlink, "Erasing failed", component, 0, 0); else devlink_flash_update_status_notify(devlink, "Erasing done", component, 0, 0); return err; } /** * ice_switch_flash_banks - Tell firmware to switch NVM banks * @pf: Pointer to the PF data structure * @activate_flags: flags used for the activation command * @emp_reset_available: on return, indicates if EMP reset is available * @extack: netlink extended ACK structure * * Notify firmware to activate the newly written flash banks, and wait for the * firmware response. * * Returns: zero on success or an error code on failure. */ static int ice_switch_flash_banks(struct ice_pf *pf, u8 activate_flags, u8 *emp_reset_available, struct netlink_ext_ack *extack) { struct device *dev = ice_pf_to_dev(pf); struct ice_aq_task task = {}; struct ice_hw *hw = &pf->hw; u16 completion_retval; u8 response_flags; int err; ice_aq_prep_for_event(pf, &task, ice_aqc_opc_nvm_write_activate); err = ice_nvm_write_activate(hw, activate_flags, &response_flags); if (err) { dev_err(dev, "Failed to switch active flash banks, err %d aq_err %s\n", err, ice_aq_str(hw->adminq.sq_last_status)); NL_SET_ERR_MSG_MOD(extack, "Failed to switch active flash banks"); return -EIO; } /* Newer versions of firmware have support to indicate whether an EMP * reset to reload firmware is available. For older firmware, EMP * reset is always available. */ if (emp_reset_available) { if (hw->dev_caps.common_cap.reset_restrict_support) { *emp_reset_available = response_flags & ICE_AQC_NVM_EMPR_ENA; dev_dbg(dev, "Firmware indicated that EMP reset is %s\n", *emp_reset_available ? "available" : "not available"); } else { *emp_reset_available = ICE_AQC_NVM_EMPR_ENA; dev_dbg(dev, "Firmware does not support restricting EMP reset availability\n"); } } err = ice_aq_wait_for_event(pf, &task, 30 * HZ); if (err) { dev_err(dev, "Timed out waiting for firmware to switch active flash banks, err %d\n", err); NL_SET_ERR_MSG_MOD(extack, "Timed out waiting for firmware"); return err; } completion_retval = le16_to_cpu(task.event.desc.retval); if (completion_retval) { dev_err(dev, "Firmware failed to switch active flash banks aq_err %s\n", ice_aq_str((enum ice_aq_err)completion_retval)); NL_SET_ERR_MSG_MOD(extack, "Firmware failed to switch active flash banks"); return -EIO; } return 0; } /** * ice_flash_component - Flash a component of the NVM * @context: PLDM fw update structure * @component: the component table to program * * Program the flash contents for a given component. First, determine the * module id. Then, erase the secondary bank for this module. Finally, write * the contents of the component to the NVM. * * Note this function assumes the caller has acquired the NVM resource. * * Returns: zero on success, or a negative error code on failure. */ static int ice_flash_component(struct pldmfw *context, struct pldmfw_component *component) { struct ice_fwu_priv *priv = container_of(context, struct ice_fwu_priv, context); struct netlink_ext_ack *extack = priv->extack; struct ice_pf *pf = priv->pf; const char *name; u8 *reset_level; u16 module; u8 flag; int err; switch (component->identifier) { case NVM_COMP_ID_OROM: module = ICE_SR_1ST_OROM_BANK_PTR; flag = ICE_AQC_NVM_ACTIV_SEL_OROM; reset_level = NULL; name = "fw.undi"; break; case NVM_COMP_ID_NVM: module = ICE_SR_1ST_NVM_BANK_PTR; flag = ICE_AQC_NVM_ACTIV_SEL_NVM; reset_level = &priv->reset_level; name = "fw.mgmt"; break; case NVM_COMP_ID_NETLIST: module = ICE_SR_NETLIST_BANK_PTR; flag = ICE_AQC_NVM_ACTIV_SEL_NETLIST; reset_level = NULL; name = "fw.netlist"; break; default: /* This should not trigger, since we check the id before * sending the component table to firmware. */ WARN(1, "Unexpected unknown component identifier 0x%02x", component->identifier); return -EINVAL; } /* Mark this component for activating at the end */ priv->activate_flags |= flag; err = ice_erase_nvm_module(pf, module, name, extack); if (err) return err; return ice_write_nvm_module(pf, module, name, component->component_data, component->component_size, reset_level, extack); } /** * ice_finalize_update - Perform last steps to complete device update * @context: PLDM fw update structure * * Called as the last step of the update process. Complete the update by * telling the firmware to switch active banks, and perform a reset of * configured. * * Returns: 0 on success, or an error code on failure. */ static int ice_finalize_update(struct pldmfw *context) { struct ice_fwu_priv *priv = container_of(context, struct ice_fwu_priv, context); struct netlink_ext_ack *extack = priv->extack; struct ice_pf *pf = priv->pf; struct devlink *devlink; int err; /* Finally, notify firmware to activate the written NVM banks */ err = ice_switch_flash_banks(pf, priv->activate_flags, &priv->emp_reset_available, extack); if (err) return err; devlink = priv_to_devlink(pf); /* If the required reset is EMPR, but EMPR is disabled, report that * a reboot is required instead. */ if (priv->reset_level == ICE_AQC_NVM_EMPR_FLAG && !priv->emp_reset_available) { dev_dbg(ice_pf_to_dev(pf), "Firmware indicated EMP reset as sufficient, but EMP reset is disabled\n"); priv->reset_level = ICE_AQC_NVM_PERST_FLAG; } switch (priv->reset_level) { case ICE_AQC_NVM_EMPR_FLAG: devlink_flash_update_status_notify(devlink, "Activate new firmware by devlink reload", NULL, 0, 0); break; case ICE_AQC_NVM_PERST_FLAG: devlink_flash_update_status_notify(devlink, "Activate new firmware by rebooting the system", NULL, 0, 0); break; case ICE_AQC_NVM_POR_FLAG: default: devlink_flash_update_status_notify(devlink, "Activate new firmware by power cycling the system", NULL, 0, 0); break; } pf->fw_emp_reset_disabled = !priv->emp_reset_available; return 0; } struct ice_pldm_pci_record_id { u32 vendor; u32 device; u32 subsystem_vendor; u32 subsystem_device; }; /** * ice_op_pci_match_record - Check if a PCI device matches the record * @context: PLDM fw update structure * @record: list of records extracted from the PLDM image * * Determine if the PCI device associated with this device matches the record * data provided. * * Searches the descriptor TLVs and extracts the relevant descriptor data into * a pldm_pci_record_id. This is then compared against the PCI device ID * information. * * Returns: true if the device matches the record, false otherwise. */ static bool ice_op_pci_match_record(struct pldmfw *context, struct pldmfw_record *record) { struct pci_dev *pdev = to_pci_dev(context->dev); struct ice_pldm_pci_record_id id = { .vendor = PCI_ANY_ID, .device = PCI_ANY_ID, .subsystem_vendor = PCI_ANY_ID, .subsystem_device = PCI_ANY_ID, }; struct pldmfw_desc_tlv *desc; list_for_each_entry(desc, &record->descs, entry) { u16 value; int *ptr; switch (desc->type) { case PLDM_DESC_ID_PCI_VENDOR_ID: ptr = &id.vendor; break; case PLDM_DESC_ID_PCI_DEVICE_ID: ptr = &id.device; break; case PLDM_DESC_ID_PCI_SUBVENDOR_ID: ptr = &id.subsystem_vendor; break; case PLDM_DESC_ID_PCI_SUBDEV_ID: ptr = &id.subsystem_device; break; default: /* Skip unrelated TLVs */ continue; } value = get_unaligned_le16(desc->data); /* A value of zero for one of the descriptors is sometimes * used when the record should ignore this field when matching * device. For example if the record applies to any subsystem * device or vendor. */ if (value) *ptr = value; else *ptr = PCI_ANY_ID; } /* the E822 device can have a generic device ID so check for that */ if ((id.vendor == PCI_ANY_ID || id.vendor == pdev->vendor) && (id.device == PCI_ANY_ID || id.device == pdev->device || id.device == ICE_DEV_ID_E822_SI_DFLT) && (id.subsystem_vendor == PCI_ANY_ID || id.subsystem_vendor == pdev->subsystem_vendor) && (id.subsystem_device == PCI_ANY_ID || id.subsystem_device == pdev->subsystem_device)) return true; return false; } static const struct pldmfw_ops ice_fwu_ops_e810 = { .match_record = &pldmfw_op_pci_match_record, .send_package_data = &ice_send_package_data, .send_component_table = &ice_send_component_table, .flash_component = &ice_flash_component, .finalize_update = &ice_finalize_update, }; static const struct pldmfw_ops ice_fwu_ops_e822 = { .match_record = &ice_op_pci_match_record, .send_package_data = &ice_send_package_data, .send_component_table = &ice_send_component_table, .flash_component = &ice_flash_component, .finalize_update = &ice_finalize_update, }; /** * ice_get_pending_updates - Check if the component has a pending update * @pf: the PF driver structure * @pending: on return, bitmap of updates pending * @extack: Netlink extended ACK * * Check if the device has any pending updates on any flash components. * * Returns: zero on success, or a negative error code on failure. Updates * pending with the bitmap of pending updates. */ int ice_get_pending_updates(struct ice_pf *pf, u8 *pending, struct netlink_ext_ack *extack) { struct device *dev = ice_pf_to_dev(pf); struct ice_hw_dev_caps *dev_caps; struct ice_hw *hw = &pf->hw; int err; dev_caps = kzalloc(sizeof(*dev_caps), GFP_KERNEL); if (!dev_caps) return -ENOMEM; /* Read the most recent device capabilities from firmware. Do not use * the cached values in hw->dev_caps, because the pending update flag * may have changed, e.g. if an update was previously completed and * the system has not yet rebooted. */ err = ice_discover_dev_caps(hw, dev_caps); if (err) { NL_SET_ERR_MSG_MOD(extack, "Unable to read device capabilities"); kfree(dev_caps); return err; } *pending = 0; if (dev_caps->common_cap.nvm_update_pending_nvm) { dev_info(dev, "The fw.mgmt flash component has a pending update\n"); *pending |= ICE_AQC_NVM_ACTIV_SEL_NVM; } if (dev_caps->common_cap.nvm_update_pending_orom) { dev_info(dev, "The fw.undi flash component has a pending update\n"); *pending |= ICE_AQC_NVM_ACTIV_SEL_OROM; } if (dev_caps->common_cap.nvm_update_pending_netlist) { dev_info(dev, "The fw.netlist flash component has a pending update\n"); *pending |= ICE_AQC_NVM_ACTIV_SEL_NETLIST; } kfree(dev_caps); return 0; } /** * ice_cancel_pending_update - Cancel any pending update for a component * @pf: the PF driver structure * @component: if not NULL, the name of the component being updated * @extack: Netlink extended ACK structure * * Cancel any pending update for the specified component. If component is * NULL, all device updates will be canceled. * * Returns: zero on success, or a negative error code on failure. */ static int ice_cancel_pending_update(struct ice_pf *pf, const char *component, struct netlink_ext_ack *extack) { struct devlink *devlink = priv_to_devlink(pf); struct device *dev = ice_pf_to_dev(pf); struct ice_hw *hw = &pf->hw; u8 pending; int err; err = ice_get_pending_updates(pf, &pending, extack); if (err) return err; /* If the flash_update request is for a specific component, ignore all * of the other components. */ if (component) { if (strcmp(component, "fw.mgmt") == 0) pending &= ICE_AQC_NVM_ACTIV_SEL_NVM; else if (strcmp(component, "fw.undi") == 0) pending &= ICE_AQC_NVM_ACTIV_SEL_OROM; else if (strcmp(component, "fw.netlist") == 0) pending &= ICE_AQC_NVM_ACTIV_SEL_NETLIST; else WARN(1, "Unexpected flash component %s", component); } /* There is no previous pending update, so this request may continue */ if (!pending) return 0; /* In order to allow overwriting a previous pending update, notify * firmware to cancel that update by issuing the appropriate command. */ devlink_flash_update_status_notify(devlink, "Canceling previous pending update", component, 0, 0); err = ice_acquire_nvm(hw, ICE_RES_WRITE); if (err) { dev_err(dev, "Failed to acquire device flash lock, err %d aq_err %s\n", err, ice_aq_str(hw->adminq.sq_last_status)); NL_SET_ERR_MSG_MOD(extack, "Failed to acquire device flash lock"); return err; } pending |= ICE_AQC_NVM_REVERT_LAST_ACTIV; err = ice_switch_flash_banks(pf, pending, NULL, extack); ice_release_nvm(hw); /* Since we've canceled the pending update, we no longer know if EMP * reset is restricted. */ pf->fw_emp_reset_disabled = false; return err; } /** * ice_devlink_flash_update - Write a firmware image to the device * @devlink: pointer to devlink associated with the device to update * @params: devlink flash update parameters * @extack: netlink extended ACK structure * * Parse the data for a given firmware file, verifying that it is a valid PLDM * formatted image that matches this device. * * Extract the device record Package Data and Component Tables and send them * to the firmware. Extract and write the flash data for each of the three * main flash components, "fw.mgmt", "fw.undi", and "fw.netlist". Notify * firmware once the data is written to the inactive banks. * * Returns: zero on success or a negative error code on failure. */ int ice_devlink_flash_update(struct devlink *devlink, struct devlink_flash_update_params *params, struct netlink_ext_ack *extack) { struct ice_pf *pf = devlink_priv(devlink); struct device *dev = ice_pf_to_dev(pf); struct ice_hw *hw = &pf->hw; struct ice_fwu_priv priv; u8 preservation; int err; if (!params->overwrite_mask) { /* preserve all settings and identifiers */ preservation = ICE_AQC_NVM_PRESERVE_ALL; } else if (params->overwrite_mask == DEVLINK_FLASH_OVERWRITE_SETTINGS) { /* overwrite settings, but preserve the vital device identifiers */ preservation = ICE_AQC_NVM_PRESERVE_SELECTED; } else if (params->overwrite_mask == (DEVLINK_FLASH_OVERWRITE_SETTINGS | DEVLINK_FLASH_OVERWRITE_IDENTIFIERS)) { /* overwrite both settings and identifiers, preserve nothing */ preservation = ICE_AQC_NVM_NO_PRESERVATION; } else { NL_SET_ERR_MSG_MOD(extack, "Requested overwrite mask is not supported"); return -EOPNOTSUPP; } if (!hw->dev_caps.common_cap.nvm_unified_update) { NL_SET_ERR_MSG_MOD(extack, "Current firmware does not support unified update"); return -EOPNOTSUPP; } memset(&priv, 0, sizeof(priv)); /* the E822 device needs a slightly different ops */ if (hw->mac_type == ICE_MAC_GENERIC) priv.context.ops = &ice_fwu_ops_e822; else priv.context.ops = &ice_fwu_ops_e810; priv.context.dev = dev; priv.extack = extack; priv.pf = pf; priv.activate_flags = preservation; devlink_flash_update_status_notify(devlink, "Preparing to flash", NULL, 0, 0); err = ice_cancel_pending_update(pf, NULL, extack); if (err) return err; err = ice_acquire_nvm(hw, ICE_RES_WRITE); if (err) { dev_err(dev, "Failed to acquire device flash lock, err %d aq_err %s\n", err, ice_aq_str(hw->adminq.sq_last_status)); NL_SET_ERR_MSG_MOD(extack, "Failed to acquire device flash lock"); return err; } err = pldmfw_flash_image(&priv.context, params->fw); if (err == -ENOENT) { dev_err(dev, "Firmware image has no record matching this device\n"); NL_SET_ERR_MSG_MOD(extack, "Firmware image has no record matching this device"); } else if (err) { /* Do not set a generic extended ACK message here. A more * specific message may already have been set by one of our * ops. */ dev_err(dev, "Failed to flash PLDM image, err %d", err); } ice_release_nvm(hw); return err; }
linux-master
drivers/net/ethernet/intel/ice/ice_fw_update.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2019, Intel Corporation. */ #include <net/xdp_sock_drv.h> #include "ice_base.h" #include "ice_lib.h" #include "ice_dcb_lib.h" #include "ice_sriov.h" /** * __ice_vsi_get_qs_contig - Assign a contiguous chunk of queues to VSI * @qs_cfg: gathered variables needed for PF->VSI queues assignment * * Return 0 on success and -ENOMEM in case of no left space in PF queue bitmap */ static int __ice_vsi_get_qs_contig(struct ice_qs_cfg *qs_cfg) { unsigned int offset, i; mutex_lock(qs_cfg->qs_mutex); offset = bitmap_find_next_zero_area(qs_cfg->pf_map, qs_cfg->pf_map_size, 0, qs_cfg->q_count, 0); if (offset >= qs_cfg->pf_map_size) { mutex_unlock(qs_cfg->qs_mutex); return -ENOMEM; } bitmap_set(qs_cfg->pf_map, offset, qs_cfg->q_count); for (i = 0; i < qs_cfg->q_count; i++) qs_cfg->vsi_map[i + qs_cfg->vsi_map_offset] = (u16)(i + offset); mutex_unlock(qs_cfg->qs_mutex); return 0; } /** * __ice_vsi_get_qs_sc - Assign a scattered queues from PF to VSI * @qs_cfg: gathered variables needed for pf->vsi queues assignment * * Return 0 on success and -ENOMEM in case of no left space in PF queue bitmap */ static int __ice_vsi_get_qs_sc(struct ice_qs_cfg *qs_cfg) { unsigned int i, index = 0; mutex_lock(qs_cfg->qs_mutex); for (i = 0; i < qs_cfg->q_count; i++) { index = find_next_zero_bit(qs_cfg->pf_map, qs_cfg->pf_map_size, index); if (index >= qs_cfg->pf_map_size) goto err_scatter; set_bit(index, qs_cfg->pf_map); qs_cfg->vsi_map[i + qs_cfg->vsi_map_offset] = (u16)index; } mutex_unlock(qs_cfg->qs_mutex); return 0; err_scatter: for (index = 0; index < i; index++) { clear_bit(qs_cfg->vsi_map[index], qs_cfg->pf_map); qs_cfg->vsi_map[index + qs_cfg->vsi_map_offset] = 0; } mutex_unlock(qs_cfg->qs_mutex); return -ENOMEM; } /** * ice_pf_rxq_wait - Wait for a PF's Rx queue to be enabled or disabled * @pf: the PF being configured * @pf_q: the PF queue * @ena: enable or disable state of the queue * * This routine will wait for the given Rx queue of the PF to reach the * enabled or disabled state. * Returns -ETIMEDOUT in case of failing to reach the requested state after * multiple retries; else will return 0 in case of success. */ static int ice_pf_rxq_wait(struct ice_pf *pf, int pf_q, bool ena) { int i; for (i = 0; i < ICE_Q_WAIT_MAX_RETRY; i++) { if (ena == !!(rd32(&pf->hw, QRX_CTRL(pf_q)) & QRX_CTRL_QENA_STAT_M)) return 0; usleep_range(20, 40); } return -ETIMEDOUT; } /** * ice_vsi_alloc_q_vector - Allocate memory for a single interrupt vector * @vsi: the VSI being configured * @v_idx: index of the vector in the VSI struct * * We allocate one q_vector and set default value for ITR setting associated * with this q_vector. If allocation fails we return -ENOMEM. */ static int ice_vsi_alloc_q_vector(struct ice_vsi *vsi, u16 v_idx) { struct ice_pf *pf = vsi->back; struct ice_q_vector *q_vector; int err; /* allocate q_vector */ q_vector = kzalloc(sizeof(*q_vector), GFP_KERNEL); if (!q_vector) return -ENOMEM; q_vector->vsi = vsi; q_vector->v_idx = v_idx; q_vector->tx.itr_setting = ICE_DFLT_TX_ITR; q_vector->rx.itr_setting = ICE_DFLT_RX_ITR; q_vector->tx.itr_mode = ITR_DYNAMIC; q_vector->rx.itr_mode = ITR_DYNAMIC; q_vector->tx.type = ICE_TX_CONTAINER; q_vector->rx.type = ICE_RX_CONTAINER; q_vector->irq.index = -ENOENT; if (vsi->type == ICE_VSI_VF) { q_vector->reg_idx = ice_calc_vf_reg_idx(vsi->vf, q_vector); goto out; } else if (vsi->type == ICE_VSI_CTRL && vsi->vf) { struct ice_vsi *ctrl_vsi = ice_get_vf_ctrl_vsi(pf, vsi); if (ctrl_vsi) { if (unlikely(!ctrl_vsi->q_vectors)) { err = -ENOENT; goto err_free_q_vector; } q_vector->irq = ctrl_vsi->q_vectors[0]->irq; goto skip_alloc; } } q_vector->irq = ice_alloc_irq(pf, vsi->irq_dyn_alloc); if (q_vector->irq.index < 0) { err = -ENOMEM; goto err_free_q_vector; } skip_alloc: q_vector->reg_idx = q_vector->irq.index; /* only set affinity_mask if the CPU is online */ if (cpu_online(v_idx)) cpumask_set_cpu(v_idx, &q_vector->affinity_mask); /* This will not be called in the driver load path because the netdev * will not be created yet. All other cases with register the NAPI * handler here (i.e. resume, reset/rebuild, etc.) */ if (vsi->netdev) netif_napi_add(vsi->netdev, &q_vector->napi, ice_napi_poll); out: /* tie q_vector and VSI together */ vsi->q_vectors[v_idx] = q_vector; return 0; err_free_q_vector: kfree(q_vector); return err; } /** * ice_free_q_vector - Free memory allocated for a specific interrupt vector * @vsi: VSI having the memory freed * @v_idx: index of the vector to be freed */ static void ice_free_q_vector(struct ice_vsi *vsi, int v_idx) { struct ice_q_vector *q_vector; struct ice_pf *pf = vsi->back; struct ice_tx_ring *tx_ring; struct ice_rx_ring *rx_ring; struct device *dev; dev = ice_pf_to_dev(pf); if (!vsi->q_vectors[v_idx]) { dev_dbg(dev, "Queue vector at index %d not found\n", v_idx); return; } q_vector = vsi->q_vectors[v_idx]; ice_for_each_tx_ring(tx_ring, q_vector->tx) tx_ring->q_vector = NULL; ice_for_each_rx_ring(rx_ring, q_vector->rx) rx_ring->q_vector = NULL; /* only VSI with an associated netdev is set up with NAPI */ if (vsi->netdev) netif_napi_del(&q_vector->napi); /* release MSIX interrupt if q_vector had interrupt allocated */ if (q_vector->irq.index < 0) goto free_q_vector; /* only free last VF ctrl vsi interrupt */ if (vsi->type == ICE_VSI_CTRL && vsi->vf && ice_get_vf_ctrl_vsi(pf, vsi)) goto free_q_vector; ice_free_irq(pf, q_vector->irq); free_q_vector: kfree(q_vector); vsi->q_vectors[v_idx] = NULL; } /** * ice_cfg_itr_gran - set the ITR granularity to 2 usecs if not already set * @hw: board specific structure */ static void ice_cfg_itr_gran(struct ice_hw *hw) { u32 regval = rd32(hw, GLINT_CTL); /* no need to update global register if ITR gran is already set */ if (!(regval & GLINT_CTL_DIS_AUTOMASK_M) && (((regval & GLINT_CTL_ITR_GRAN_200_M) >> GLINT_CTL_ITR_GRAN_200_S) == ICE_ITR_GRAN_US) && (((regval & GLINT_CTL_ITR_GRAN_100_M) >> GLINT_CTL_ITR_GRAN_100_S) == ICE_ITR_GRAN_US) && (((regval & GLINT_CTL_ITR_GRAN_50_M) >> GLINT_CTL_ITR_GRAN_50_S) == ICE_ITR_GRAN_US) && (((regval & GLINT_CTL_ITR_GRAN_25_M) >> GLINT_CTL_ITR_GRAN_25_S) == ICE_ITR_GRAN_US)) return; regval = ((ICE_ITR_GRAN_US << GLINT_CTL_ITR_GRAN_200_S) & GLINT_CTL_ITR_GRAN_200_M) | ((ICE_ITR_GRAN_US << GLINT_CTL_ITR_GRAN_100_S) & GLINT_CTL_ITR_GRAN_100_M) | ((ICE_ITR_GRAN_US << GLINT_CTL_ITR_GRAN_50_S) & GLINT_CTL_ITR_GRAN_50_M) | ((ICE_ITR_GRAN_US << GLINT_CTL_ITR_GRAN_25_S) & GLINT_CTL_ITR_GRAN_25_M); wr32(hw, GLINT_CTL, regval); } /** * ice_calc_txq_handle - calculate the queue handle * @vsi: VSI that ring belongs to * @ring: ring to get the absolute queue index * @tc: traffic class number */ static u16 ice_calc_txq_handle(struct ice_vsi *vsi, struct ice_tx_ring *ring, u8 tc) { WARN_ONCE(ice_ring_is_xdp(ring) && tc, "XDP ring can't belong to TC other than 0\n"); if (ring->ch) return ring->q_index - ring->ch->base_q; /* Idea here for calculation is that we subtract the number of queue * count from TC that ring belongs to from it's absolute queue index * and as a result we get the queue's index within TC. */ return ring->q_index - vsi->tc_cfg.tc_info[tc].qoffset; } /** * ice_eswitch_calc_txq_handle * @ring: pointer to ring which unique index is needed * * To correctly work with many netdevs ring->q_index of Tx rings on switchdev * VSI can repeat. Hardware ring setup requires unique q_index. Calculate it * here by finding index in vsi->tx_rings of this ring. * * Return ICE_INVAL_Q_INDEX when index wasn't found. Should never happen, * because VSI is get from ring->vsi, so it has to be present in this VSI. */ static u16 ice_eswitch_calc_txq_handle(struct ice_tx_ring *ring) { struct ice_vsi *vsi = ring->vsi; int i; ice_for_each_txq(vsi, i) { if (vsi->tx_rings[i] == ring) return i; } return ICE_INVAL_Q_INDEX; } /** * ice_cfg_xps_tx_ring - Configure XPS for a Tx ring * @ring: The Tx ring to configure * * This enables/disables XPS for a given Tx descriptor ring * based on the TCs enabled for the VSI that ring belongs to. */ static void ice_cfg_xps_tx_ring(struct ice_tx_ring *ring) { if (!ring->q_vector || !ring->netdev) return; /* We only initialize XPS once, so as not to overwrite user settings */ if (test_and_set_bit(ICE_TX_XPS_INIT_DONE, ring->xps_state)) return; netif_set_xps_queue(ring->netdev, &ring->q_vector->affinity_mask, ring->q_index); } /** * ice_setup_tx_ctx - setup a struct ice_tlan_ctx instance * @ring: The Tx ring to configure * @tlan_ctx: Pointer to the Tx LAN queue context structure to be initialized * @pf_q: queue index in the PF space * * Configure the Tx descriptor ring in TLAN context. */ static void ice_setup_tx_ctx(struct ice_tx_ring *ring, struct ice_tlan_ctx *tlan_ctx, u16 pf_q) { struct ice_vsi *vsi = ring->vsi; struct ice_hw *hw = &vsi->back->hw; tlan_ctx->base = ring->dma >> ICE_TLAN_CTX_BASE_S; tlan_ctx->port_num = vsi->port_info->lport; /* Transmit Queue Length */ tlan_ctx->qlen = ring->count; ice_set_cgd_num(tlan_ctx, ring->dcb_tc); /* PF number */ tlan_ctx->pf_num = hw->pf_id; /* queue belongs to a specific VSI type * VF / VM index should be programmed per vmvf_type setting: * for vmvf_type = VF, it is VF number between 0-256 * for vmvf_type = VM, it is VM number between 0-767 * for PF or EMP this field should be set to zero */ switch (vsi->type) { case ICE_VSI_LB: case ICE_VSI_CTRL: case ICE_VSI_PF: if (ring->ch) tlan_ctx->vmvf_type = ICE_TLAN_CTX_VMVF_TYPE_VMQ; else tlan_ctx->vmvf_type = ICE_TLAN_CTX_VMVF_TYPE_PF; break; case ICE_VSI_VF: /* Firmware expects vmvf_num to be absolute VF ID */ tlan_ctx->vmvf_num = hw->func_caps.vf_base_id + vsi->vf->vf_id; tlan_ctx->vmvf_type = ICE_TLAN_CTX_VMVF_TYPE_VF; break; case ICE_VSI_SWITCHDEV_CTRL: tlan_ctx->vmvf_type = ICE_TLAN_CTX_VMVF_TYPE_VMQ; break; default: return; } /* make sure the context is associated with the right VSI */ if (ring->ch) tlan_ctx->src_vsi = ring->ch->vsi_num; else tlan_ctx->src_vsi = ice_get_hw_vsi_num(hw, vsi->idx); /* Restrict Tx timestamps to the PF VSI */ switch (vsi->type) { case ICE_VSI_PF: tlan_ctx->tsyn_ena = 1; break; default: break; } tlan_ctx->tso_ena = ICE_TX_LEGACY; tlan_ctx->tso_qnum = pf_q; /* Legacy or Advanced Host Interface: * 0: Advanced Host Interface * 1: Legacy Host Interface */ tlan_ctx->legacy_int = ICE_TX_LEGACY; } /** * ice_rx_offset - Return expected offset into page to access data * @rx_ring: Ring we are requesting offset of * * Returns the offset value for ring into the data buffer. */ static unsigned int ice_rx_offset(struct ice_rx_ring *rx_ring) { if (ice_ring_uses_build_skb(rx_ring)) return ICE_SKB_PAD; return 0; } /** * ice_setup_rx_ctx - Configure a receive ring context * @ring: The Rx ring to configure * * Configure the Rx descriptor ring in RLAN context. */ static int ice_setup_rx_ctx(struct ice_rx_ring *ring) { struct ice_vsi *vsi = ring->vsi; u32 rxdid = ICE_RXDID_FLEX_NIC; struct ice_rlan_ctx rlan_ctx; struct ice_hw *hw; u16 pf_q; int err; hw = &vsi->back->hw; /* what is Rx queue number in global space of 2K Rx queues */ pf_q = vsi->rxq_map[ring->q_index]; /* clear the context structure first */ memset(&rlan_ctx, 0, sizeof(rlan_ctx)); /* Receive Queue Base Address. * Indicates the starting address of the descriptor queue defined in * 128 Byte units. */ rlan_ctx.base = ring->dma >> ICE_RLAN_BASE_S; rlan_ctx.qlen = ring->count; /* Receive Packet Data Buffer Size. * The Packet Data Buffer Size is defined in 128 byte units. */ rlan_ctx.dbuf = DIV_ROUND_UP(ring->rx_buf_len, BIT_ULL(ICE_RLAN_CTX_DBUF_S)); /* use 32 byte descriptors */ rlan_ctx.dsize = 1; /* Strip the Ethernet CRC bytes before the packet is posted to host * memory. */ rlan_ctx.crcstrip = !(ring->flags & ICE_RX_FLAGS_CRC_STRIP_DIS); /* L2TSEL flag defines the reported L2 Tags in the receive descriptor * and it needs to remain 1 for non-DVM capable configurations to not * break backward compatibility for VF drivers. Setting this field to 0 * will cause the single/outer VLAN tag to be stripped to the L2TAG2_2ND * field in the Rx descriptor. Setting it to 1 allows the VLAN tag to * be stripped in L2TAG1 of the Rx descriptor, which is where VFs will * check for the tag */ if (ice_is_dvm_ena(hw)) if (vsi->type == ICE_VSI_VF && ice_vf_is_port_vlan_ena(vsi->vf)) rlan_ctx.l2tsel = 1; else rlan_ctx.l2tsel = 0; else rlan_ctx.l2tsel = 1; rlan_ctx.dtype = ICE_RX_DTYPE_NO_SPLIT; rlan_ctx.hsplit_0 = ICE_RLAN_RX_HSPLIT_0_NO_SPLIT; rlan_ctx.hsplit_1 = ICE_RLAN_RX_HSPLIT_1_NO_SPLIT; /* This controls whether VLAN is stripped from inner headers * The VLAN in the inner L2 header is stripped to the receive * descriptor if enabled by this flag. */ rlan_ctx.showiv = 0; /* Max packet size for this queue - must not be set to a larger value * than 5 x DBUF */ rlan_ctx.rxmax = min_t(u32, vsi->max_frame, ICE_MAX_CHAINED_RX_BUFS * ring->rx_buf_len); /* Rx queue threshold in units of 64 */ rlan_ctx.lrxqthresh = 1; /* Enable Flexible Descriptors in the queue context which * allows this driver to select a specific receive descriptor format * increasing context priority to pick up profile ID; default is 0x01; * setting to 0x03 to ensure profile is programming if prev context is * of same priority */ if (vsi->type != ICE_VSI_VF) ice_write_qrxflxp_cntxt(hw, pf_q, rxdid, 0x3, true); else ice_write_qrxflxp_cntxt(hw, pf_q, ICE_RXDID_LEGACY_1, 0x3, false); /* Absolute queue number out of 2K needs to be passed */ err = ice_write_rxq_ctx(hw, &rlan_ctx, pf_q); if (err) { dev_err(ice_pf_to_dev(vsi->back), "Failed to set LAN Rx queue context for absolute Rx queue %d error: %d\n", pf_q, err); return -EIO; } if (vsi->type == ICE_VSI_VF) return 0; /* configure Rx buffer alignment */ if (!vsi->netdev || test_bit(ICE_FLAG_LEGACY_RX, vsi->back->flags)) ice_clear_ring_build_skb_ena(ring); else ice_set_ring_build_skb_ena(ring); ring->rx_offset = ice_rx_offset(ring); /* init queue specific tail register */ ring->tail = hw->hw_addr + QRX_TAIL(pf_q); writel(0, ring->tail); return 0; } /** * ice_vsi_cfg_rxq - Configure an Rx queue * @ring: the ring being configured * * Return 0 on success and a negative value on error. */ int ice_vsi_cfg_rxq(struct ice_rx_ring *ring) { struct device *dev = ice_pf_to_dev(ring->vsi->back); u32 num_bufs = ICE_RX_DESC_UNUSED(ring); int err; ring->rx_buf_len = ring->vsi->rx_buf_len; if (ring->vsi->type == ICE_VSI_PF) { if (!xdp_rxq_info_is_reg(&ring->xdp_rxq)) /* coverity[check_return] */ __xdp_rxq_info_reg(&ring->xdp_rxq, ring->netdev, ring->q_index, ring->q_vector->napi.napi_id, ring->vsi->rx_buf_len); ring->xsk_pool = ice_xsk_pool(ring); if (ring->xsk_pool) { xdp_rxq_info_unreg_mem_model(&ring->xdp_rxq); ring->rx_buf_len = xsk_pool_get_rx_frame_size(ring->xsk_pool); err = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq, MEM_TYPE_XSK_BUFF_POOL, NULL); if (err) return err; xsk_pool_set_rxq_info(ring->xsk_pool, &ring->xdp_rxq); dev_info(dev, "Registered XDP mem model MEM_TYPE_XSK_BUFF_POOL on Rx ring %d\n", ring->q_index); } else { if (!xdp_rxq_info_is_reg(&ring->xdp_rxq)) /* coverity[check_return] */ __xdp_rxq_info_reg(&ring->xdp_rxq, ring->netdev, ring->q_index, ring->q_vector->napi.napi_id, ring->vsi->rx_buf_len); err = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq, MEM_TYPE_PAGE_SHARED, NULL); if (err) return err; } } xdp_init_buff(&ring->xdp, ice_rx_pg_size(ring) / 2, &ring->xdp_rxq); ring->xdp.data = NULL; err = ice_setup_rx_ctx(ring); if (err) { dev_err(dev, "ice_setup_rx_ctx failed for RxQ %d, err %d\n", ring->q_index, err); return err; } if (ring->xsk_pool) { bool ok; if (!xsk_buff_can_alloc(ring->xsk_pool, num_bufs)) { dev_warn(dev, "XSK buffer pool does not provide enough addresses to fill %d buffers on Rx ring %d\n", num_bufs, ring->q_index); dev_warn(dev, "Change Rx ring/fill queue size to avoid performance issues\n"); return 0; } ok = ice_alloc_rx_bufs_zc(ring, num_bufs); if (!ok) { u16 pf_q = ring->vsi->rxq_map[ring->q_index]; dev_info(dev, "Failed to allocate some buffers on XSK buffer pool enabled Rx ring %d (pf_q %d)\n", ring->q_index, pf_q); } return 0; } ice_alloc_rx_bufs(ring, num_bufs); return 0; } /** * __ice_vsi_get_qs - helper function for assigning queues from PF to VSI * @qs_cfg: gathered variables needed for pf->vsi queues assignment * * This function first tries to find contiguous space. If it is not successful, * it tries with the scatter approach. * * Return 0 on success and -ENOMEM in case of no left space in PF queue bitmap */ int __ice_vsi_get_qs(struct ice_qs_cfg *qs_cfg) { int ret = 0; ret = __ice_vsi_get_qs_contig(qs_cfg); if (ret) { /* contig failed, so try with scatter approach */ qs_cfg->mapping_mode = ICE_VSI_MAP_SCATTER; qs_cfg->q_count = min_t(unsigned int, qs_cfg->q_count, qs_cfg->scatter_count); ret = __ice_vsi_get_qs_sc(qs_cfg); } return ret; } /** * ice_vsi_ctrl_one_rx_ring - start/stop VSI's Rx ring with no busy wait * @vsi: the VSI being configured * @ena: start or stop the Rx ring * @rxq_idx: 0-based Rx queue index for the VSI passed in * @wait: wait or don't wait for configuration to finish in hardware * * Return 0 on success and negative on error. */ int ice_vsi_ctrl_one_rx_ring(struct ice_vsi *vsi, bool ena, u16 rxq_idx, bool wait) { int pf_q = vsi->rxq_map[rxq_idx]; struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; u32 rx_reg; rx_reg = rd32(hw, QRX_CTRL(pf_q)); /* Skip if the queue is already in the requested state */ if (ena == !!(rx_reg & QRX_CTRL_QENA_STAT_M)) return 0; /* turn on/off the queue */ if (ena) rx_reg |= QRX_CTRL_QENA_REQ_M; else rx_reg &= ~QRX_CTRL_QENA_REQ_M; wr32(hw, QRX_CTRL(pf_q), rx_reg); if (!wait) return 0; ice_flush(hw); return ice_pf_rxq_wait(pf, pf_q, ena); } /** * ice_vsi_wait_one_rx_ring - wait for a VSI's Rx ring to be stopped/started * @vsi: the VSI being configured * @ena: true/false to verify Rx ring has been enabled/disabled respectively * @rxq_idx: 0-based Rx queue index for the VSI passed in * * This routine will wait for the given Rx queue of the VSI to reach the * enabled or disabled state. Returns -ETIMEDOUT in case of failing to reach * the requested state after multiple retries; else will return 0 in case of * success. */ int ice_vsi_wait_one_rx_ring(struct ice_vsi *vsi, bool ena, u16 rxq_idx) { int pf_q = vsi->rxq_map[rxq_idx]; struct ice_pf *pf = vsi->back; return ice_pf_rxq_wait(pf, pf_q, ena); } /** * ice_vsi_alloc_q_vectors - Allocate memory for interrupt vectors * @vsi: the VSI being configured * * We allocate one q_vector per queue interrupt. If allocation fails we * return -ENOMEM. */ int ice_vsi_alloc_q_vectors(struct ice_vsi *vsi) { struct device *dev = ice_pf_to_dev(vsi->back); u16 v_idx; int err; if (vsi->q_vectors[0]) { dev_dbg(dev, "VSI %d has existing q_vectors\n", vsi->vsi_num); return -EEXIST; } for (v_idx = 0; v_idx < vsi->num_q_vectors; v_idx++) { err = ice_vsi_alloc_q_vector(vsi, v_idx); if (err) goto err_out; } return 0; err_out: while (v_idx--) ice_free_q_vector(vsi, v_idx); dev_err(dev, "Failed to allocate %d q_vector for VSI %d, ret=%d\n", vsi->num_q_vectors, vsi->vsi_num, err); vsi->num_q_vectors = 0; return err; } /** * ice_vsi_map_rings_to_vectors - Map VSI rings to interrupt vectors * @vsi: the VSI being configured * * This function maps descriptor rings to the queue-specific vectors allotted * through the MSI-X enabling code. On a constrained vector budget, we map Tx * and Rx rings to the vector as "efficiently" as possible. */ void ice_vsi_map_rings_to_vectors(struct ice_vsi *vsi) { int q_vectors = vsi->num_q_vectors; u16 tx_rings_rem, rx_rings_rem; int v_id; /* initially assigning remaining rings count to VSIs num queue value */ tx_rings_rem = vsi->num_txq; rx_rings_rem = vsi->num_rxq; for (v_id = 0; v_id < q_vectors; v_id++) { struct ice_q_vector *q_vector = vsi->q_vectors[v_id]; u8 tx_rings_per_v, rx_rings_per_v; u16 q_id, q_base; /* Tx rings mapping to vector */ tx_rings_per_v = (u8)DIV_ROUND_UP(tx_rings_rem, q_vectors - v_id); q_vector->num_ring_tx = tx_rings_per_v; q_vector->tx.tx_ring = NULL; q_vector->tx.itr_idx = ICE_TX_ITR; q_base = vsi->num_txq - tx_rings_rem; for (q_id = q_base; q_id < (q_base + tx_rings_per_v); q_id++) { struct ice_tx_ring *tx_ring = vsi->tx_rings[q_id]; tx_ring->q_vector = q_vector; tx_ring->next = q_vector->tx.tx_ring; q_vector->tx.tx_ring = tx_ring; } tx_rings_rem -= tx_rings_per_v; /* Rx rings mapping to vector */ rx_rings_per_v = (u8)DIV_ROUND_UP(rx_rings_rem, q_vectors - v_id); q_vector->num_ring_rx = rx_rings_per_v; q_vector->rx.rx_ring = NULL; q_vector->rx.itr_idx = ICE_RX_ITR; q_base = vsi->num_rxq - rx_rings_rem; for (q_id = q_base; q_id < (q_base + rx_rings_per_v); q_id++) { struct ice_rx_ring *rx_ring = vsi->rx_rings[q_id]; rx_ring->q_vector = q_vector; rx_ring->next = q_vector->rx.rx_ring; q_vector->rx.rx_ring = rx_ring; } rx_rings_rem -= rx_rings_per_v; } } /** * ice_vsi_free_q_vectors - Free memory allocated for interrupt vectors * @vsi: the VSI having memory freed */ void ice_vsi_free_q_vectors(struct ice_vsi *vsi) { int v_idx; ice_for_each_q_vector(vsi, v_idx) ice_free_q_vector(vsi, v_idx); vsi->num_q_vectors = 0; } /** * ice_vsi_cfg_txq - Configure single Tx queue * @vsi: the VSI that queue belongs to * @ring: Tx ring to be configured * @qg_buf: queue group buffer */ int ice_vsi_cfg_txq(struct ice_vsi *vsi, struct ice_tx_ring *ring, struct ice_aqc_add_tx_qgrp *qg_buf) { u8 buf_len = struct_size(qg_buf, txqs, 1); struct ice_tlan_ctx tlan_ctx = { 0 }; struct ice_aqc_add_txqs_perq *txq; struct ice_channel *ch = ring->ch; struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; int status; u16 pf_q; u8 tc; /* Configure XPS */ ice_cfg_xps_tx_ring(ring); pf_q = ring->reg_idx; ice_setup_tx_ctx(ring, &tlan_ctx, pf_q); /* copy context contents into the qg_buf */ qg_buf->txqs[0].txq_id = cpu_to_le16(pf_q); ice_set_ctx(hw, (u8 *)&tlan_ctx, qg_buf->txqs[0].txq_ctx, ice_tlan_ctx_info); /* init queue specific tail reg. It is referred as * transmit comm scheduler queue doorbell. */ ring->tail = hw->hw_addr + QTX_COMM_DBELL(pf_q); if (IS_ENABLED(CONFIG_DCB)) tc = ring->dcb_tc; else tc = 0; /* Add unique software queue handle of the Tx queue per * TC into the VSI Tx ring */ if (vsi->type == ICE_VSI_SWITCHDEV_CTRL) { ring->q_handle = ice_eswitch_calc_txq_handle(ring); if (ring->q_handle == ICE_INVAL_Q_INDEX) return -ENODEV; } else { ring->q_handle = ice_calc_txq_handle(vsi, ring, tc); } if (ch) status = ice_ena_vsi_txq(vsi->port_info, ch->ch_vsi->idx, 0, ring->q_handle, 1, qg_buf, buf_len, NULL); else status = ice_ena_vsi_txq(vsi->port_info, vsi->idx, tc, ring->q_handle, 1, qg_buf, buf_len, NULL); if (status) { dev_err(ice_pf_to_dev(pf), "Failed to set LAN Tx queue context, error: %d\n", status); return status; } /* Add Tx Queue TEID into the VSI Tx ring from the * response. This will complete configuring and * enabling the queue. */ txq = &qg_buf->txqs[0]; if (pf_q == le16_to_cpu(txq->txq_id)) ring->txq_teid = le32_to_cpu(txq->q_teid); return 0; } /** * ice_cfg_itr - configure the initial interrupt throttle values * @hw: pointer to the HW structure * @q_vector: interrupt vector that's being configured * * Configure interrupt throttling values for the ring containers that are * associated with the interrupt vector passed in. */ void ice_cfg_itr(struct ice_hw *hw, struct ice_q_vector *q_vector) { ice_cfg_itr_gran(hw); if (q_vector->num_ring_rx) ice_write_itr(&q_vector->rx, q_vector->rx.itr_setting); if (q_vector->num_ring_tx) ice_write_itr(&q_vector->tx, q_vector->tx.itr_setting); ice_write_intrl(q_vector, q_vector->intrl); } /** * ice_cfg_txq_interrupt - configure interrupt on Tx queue * @vsi: the VSI being configured * @txq: Tx queue being mapped to MSI-X vector * @msix_idx: MSI-X vector index within the function * @itr_idx: ITR index of the interrupt cause * * Configure interrupt on Tx queue by associating Tx queue to MSI-X vector * within the function space. */ void ice_cfg_txq_interrupt(struct ice_vsi *vsi, u16 txq, u16 msix_idx, u16 itr_idx) { struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; u32 val; itr_idx = (itr_idx << QINT_TQCTL_ITR_INDX_S) & QINT_TQCTL_ITR_INDX_M; val = QINT_TQCTL_CAUSE_ENA_M | itr_idx | ((msix_idx << QINT_TQCTL_MSIX_INDX_S) & QINT_TQCTL_MSIX_INDX_M); wr32(hw, QINT_TQCTL(vsi->txq_map[txq]), val); if (ice_is_xdp_ena_vsi(vsi)) { u32 xdp_txq = txq + vsi->num_xdp_txq; wr32(hw, QINT_TQCTL(vsi->txq_map[xdp_txq]), val); } ice_flush(hw); } /** * ice_cfg_rxq_interrupt - configure interrupt on Rx queue * @vsi: the VSI being configured * @rxq: Rx queue being mapped to MSI-X vector * @msix_idx: MSI-X vector index within the function * @itr_idx: ITR index of the interrupt cause * * Configure interrupt on Rx queue by associating Rx queue to MSI-X vector * within the function space. */ void ice_cfg_rxq_interrupt(struct ice_vsi *vsi, u16 rxq, u16 msix_idx, u16 itr_idx) { struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; u32 val; itr_idx = (itr_idx << QINT_RQCTL_ITR_INDX_S) & QINT_RQCTL_ITR_INDX_M; val = QINT_RQCTL_CAUSE_ENA_M | itr_idx | ((msix_idx << QINT_RQCTL_MSIX_INDX_S) & QINT_RQCTL_MSIX_INDX_M); wr32(hw, QINT_RQCTL(vsi->rxq_map[rxq]), val); ice_flush(hw); } /** * ice_trigger_sw_intr - trigger a software interrupt * @hw: pointer to the HW structure * @q_vector: interrupt vector to trigger the software interrupt for */ void ice_trigger_sw_intr(struct ice_hw *hw, struct ice_q_vector *q_vector) { wr32(hw, GLINT_DYN_CTL(q_vector->reg_idx), (ICE_ITR_NONE << GLINT_DYN_CTL_ITR_INDX_S) | GLINT_DYN_CTL_SWINT_TRIG_M | GLINT_DYN_CTL_INTENA_M); } /** * ice_vsi_stop_tx_ring - Disable single Tx ring * @vsi: the VSI being configured * @rst_src: reset source * @rel_vmvf_num: Relative ID of VF/VM * @ring: Tx ring to be stopped * @txq_meta: Meta data of Tx ring to be stopped */ int ice_vsi_stop_tx_ring(struct ice_vsi *vsi, enum ice_disq_rst_src rst_src, u16 rel_vmvf_num, struct ice_tx_ring *ring, struct ice_txq_meta *txq_meta) { struct ice_pf *pf = vsi->back; struct ice_q_vector *q_vector; struct ice_hw *hw = &pf->hw; int status; u32 val; /* clear cause_ena bit for disabled queues */ val = rd32(hw, QINT_TQCTL(ring->reg_idx)); val &= ~QINT_TQCTL_CAUSE_ENA_M; wr32(hw, QINT_TQCTL(ring->reg_idx), val); /* software is expected to wait for 100 ns */ ndelay(100); /* trigger a software interrupt for the vector * associated to the queue to schedule NAPI handler */ q_vector = ring->q_vector; if (q_vector && !(vsi->vf && ice_is_vf_disabled(vsi->vf))) ice_trigger_sw_intr(hw, q_vector); status = ice_dis_vsi_txq(vsi->port_info, txq_meta->vsi_idx, txq_meta->tc, 1, &txq_meta->q_handle, &txq_meta->q_id, &txq_meta->q_teid, rst_src, rel_vmvf_num, NULL); /* if the disable queue command was exercised during an * active reset flow, -EBUSY is returned. * This is not an error as the reset operation disables * queues at the hardware level anyway. */ if (status == -EBUSY) { dev_dbg(ice_pf_to_dev(vsi->back), "Reset in progress. LAN Tx queues already disabled\n"); } else if (status == -ENOENT) { dev_dbg(ice_pf_to_dev(vsi->back), "LAN Tx queues do not exist, nothing to disable\n"); } else if (status) { dev_dbg(ice_pf_to_dev(vsi->back), "Failed to disable LAN Tx queues, error: %d\n", status); return status; } return 0; } /** * ice_fill_txq_meta - Prepare the Tx queue's meta data * @vsi: VSI that ring belongs to * @ring: ring that txq_meta will be based on * @txq_meta: a helper struct that wraps Tx queue's information * * Set up a helper struct that will contain all the necessary fields that * are needed for stopping Tx queue */ void ice_fill_txq_meta(struct ice_vsi *vsi, struct ice_tx_ring *ring, struct ice_txq_meta *txq_meta) { struct ice_channel *ch = ring->ch; u8 tc; if (IS_ENABLED(CONFIG_DCB)) tc = ring->dcb_tc; else tc = 0; txq_meta->q_id = ring->reg_idx; txq_meta->q_teid = ring->txq_teid; txq_meta->q_handle = ring->q_handle; if (ch) { txq_meta->vsi_idx = ch->ch_vsi->idx; txq_meta->tc = 0; } else { txq_meta->vsi_idx = vsi->idx; txq_meta->tc = tc; } }
linux-master
drivers/net/ethernet/intel/ice/ice_base.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2019-2021, Intel Corporation. */ #include "ice_pf_vsi_vlan_ops.h" #include "ice_vf_vsi_vlan_ops.h" #include "ice_lib.h" #include "ice.h" static int op_unsupported_vlan_arg(struct ice_vsi * __always_unused vsi, struct ice_vlan * __always_unused vlan) { return -EOPNOTSUPP; } static int op_unsupported_tpid_arg(struct ice_vsi *__always_unused vsi, u16 __always_unused tpid) { return -EOPNOTSUPP; } static int op_unsupported(struct ice_vsi *__always_unused vsi) { return -EOPNOTSUPP; } /* If any new ops are added to the VSI VLAN ops interface then an unsupported * implementation should be set here. */ static struct ice_vsi_vlan_ops ops_unsupported = { .add_vlan = op_unsupported_vlan_arg, .del_vlan = op_unsupported_vlan_arg, .ena_stripping = op_unsupported_tpid_arg, .dis_stripping = op_unsupported, .ena_insertion = op_unsupported_tpid_arg, .dis_insertion = op_unsupported, .ena_rx_filtering = op_unsupported, .dis_rx_filtering = op_unsupported, .ena_tx_filtering = op_unsupported, .dis_tx_filtering = op_unsupported, .set_port_vlan = op_unsupported_vlan_arg, }; /** * ice_vsi_init_unsupported_vlan_ops - init all VSI VLAN ops to unsupported * @vsi: VSI to initialize VSI VLAN ops to unsupported for * * By default all inner and outer VSI VLAN ops return -EOPNOTSUPP. This was done * as oppsed to leaving the ops null to prevent unexpected crashes. Instead if * an unsupported VSI VLAN op is called it will just return -EOPNOTSUPP. * */ static void ice_vsi_init_unsupported_vlan_ops(struct ice_vsi *vsi) { vsi->outer_vlan_ops = ops_unsupported; vsi->inner_vlan_ops = ops_unsupported; } /** * ice_vsi_init_vlan_ops - initialize type specific VSI VLAN ops * @vsi: VSI to initialize ops for * * If any VSI types are added and/or require different ops than the PF or VF VSI * then they will have to add a case here to handle that. Also, VSI type * specific files should be added in the same manner that was done for PF VSI. */ void ice_vsi_init_vlan_ops(struct ice_vsi *vsi) { /* Initialize all VSI types to have unsupported VSI VLAN ops */ ice_vsi_init_unsupported_vlan_ops(vsi); switch (vsi->type) { case ICE_VSI_PF: case ICE_VSI_SWITCHDEV_CTRL: ice_pf_vsi_init_vlan_ops(vsi); break; case ICE_VSI_VF: ice_vf_vsi_init_vlan_ops(vsi); break; default: dev_dbg(ice_pf_to_dev(vsi->back), "%s does not support VLAN operations\n", ice_vsi_type_str(vsi->type)); break; } } /** * ice_get_compat_vsi_vlan_ops - Get VSI VLAN ops based on VLAN mode * @vsi: VSI used to get the VSI VLAN ops * * This function is meant to be used when the caller doesn't know which VLAN ops * to use (i.e. inner or outer). This allows backward compatibility for VLANs * since most of the Outer VSI VLAN functins are not supported when * the device is configured in Single VLAN Mode (SVM). */ struct ice_vsi_vlan_ops *ice_get_compat_vsi_vlan_ops(struct ice_vsi *vsi) { if (ice_is_dvm_ena(&vsi->back->hw)) return &vsi->outer_vlan_ops; else return &vsi->inner_vlan_ops; }
linux-master
drivers/net/ethernet/intel/ice/ice_vsi_vlan_ops.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2018, Intel Corporation. */ #include "ice.h" #include "ice_base.h" #include "ice_flow.h" #include "ice_lib.h" #include "ice_fltr.h" #include "ice_dcb_lib.h" #include "ice_devlink.h" #include "ice_vsi_vlan_ops.h" /** * ice_vsi_type_str - maps VSI type enum to string equivalents * @vsi_type: VSI type enum */ const char *ice_vsi_type_str(enum ice_vsi_type vsi_type) { switch (vsi_type) { case ICE_VSI_PF: return "ICE_VSI_PF"; case ICE_VSI_VF: return "ICE_VSI_VF"; case ICE_VSI_CTRL: return "ICE_VSI_CTRL"; case ICE_VSI_CHNL: return "ICE_VSI_CHNL"; case ICE_VSI_LB: return "ICE_VSI_LB"; case ICE_VSI_SWITCHDEV_CTRL: return "ICE_VSI_SWITCHDEV_CTRL"; default: return "unknown"; } } /** * ice_vsi_ctrl_all_rx_rings - Start or stop a VSI's Rx rings * @vsi: the VSI being configured * @ena: start or stop the Rx rings * * First enable/disable all of the Rx rings, flush any remaining writes, and * then verify that they have all been enabled/disabled successfully. This will * let all of the register writes complete when enabling/disabling the Rx rings * before waiting for the change in hardware to complete. */ static int ice_vsi_ctrl_all_rx_rings(struct ice_vsi *vsi, bool ena) { int ret = 0; u16 i; ice_for_each_rxq(vsi, i) ice_vsi_ctrl_one_rx_ring(vsi, ena, i, false); ice_flush(&vsi->back->hw); ice_for_each_rxq(vsi, i) { ret = ice_vsi_wait_one_rx_ring(vsi, ena, i); if (ret) break; } return ret; } /** * ice_vsi_alloc_arrays - Allocate queue and vector pointer arrays for the VSI * @vsi: VSI pointer * * On error: returns error code (negative) * On success: returns 0 */ static int ice_vsi_alloc_arrays(struct ice_vsi *vsi) { struct ice_pf *pf = vsi->back; struct device *dev; dev = ice_pf_to_dev(pf); if (vsi->type == ICE_VSI_CHNL) return 0; /* allocate memory for both Tx and Rx ring pointers */ vsi->tx_rings = devm_kcalloc(dev, vsi->alloc_txq, sizeof(*vsi->tx_rings), GFP_KERNEL); if (!vsi->tx_rings) return -ENOMEM; vsi->rx_rings = devm_kcalloc(dev, vsi->alloc_rxq, sizeof(*vsi->rx_rings), GFP_KERNEL); if (!vsi->rx_rings) goto err_rings; /* txq_map needs to have enough space to track both Tx (stack) rings * and XDP rings; at this point vsi->num_xdp_txq might not be set, * so use num_possible_cpus() as we want to always provide XDP ring * per CPU, regardless of queue count settings from user that might * have come from ethtool's set_channels() callback; */ vsi->txq_map = devm_kcalloc(dev, (vsi->alloc_txq + num_possible_cpus()), sizeof(*vsi->txq_map), GFP_KERNEL); if (!vsi->txq_map) goto err_txq_map; vsi->rxq_map = devm_kcalloc(dev, vsi->alloc_rxq, sizeof(*vsi->rxq_map), GFP_KERNEL); if (!vsi->rxq_map) goto err_rxq_map; /* There is no need to allocate q_vectors for a loopback VSI. */ if (vsi->type == ICE_VSI_LB) return 0; /* allocate memory for q_vector pointers */ vsi->q_vectors = devm_kcalloc(dev, vsi->num_q_vectors, sizeof(*vsi->q_vectors), GFP_KERNEL); if (!vsi->q_vectors) goto err_vectors; vsi->af_xdp_zc_qps = bitmap_zalloc(max_t(int, vsi->alloc_txq, vsi->alloc_rxq), GFP_KERNEL); if (!vsi->af_xdp_zc_qps) goto err_zc_qps; return 0; err_zc_qps: devm_kfree(dev, vsi->q_vectors); err_vectors: devm_kfree(dev, vsi->rxq_map); err_rxq_map: devm_kfree(dev, vsi->txq_map); err_txq_map: devm_kfree(dev, vsi->rx_rings); err_rings: devm_kfree(dev, vsi->tx_rings); return -ENOMEM; } /** * ice_vsi_set_num_desc - Set number of descriptors for queues on this VSI * @vsi: the VSI being configured */ static void ice_vsi_set_num_desc(struct ice_vsi *vsi) { switch (vsi->type) { case ICE_VSI_PF: case ICE_VSI_SWITCHDEV_CTRL: case ICE_VSI_CTRL: case ICE_VSI_LB: /* a user could change the values of num_[tr]x_desc using * ethtool -G so we should keep those values instead of * overwriting them with the defaults. */ if (!vsi->num_rx_desc) vsi->num_rx_desc = ICE_DFLT_NUM_RX_DESC; if (!vsi->num_tx_desc) vsi->num_tx_desc = ICE_DFLT_NUM_TX_DESC; break; default: dev_dbg(ice_pf_to_dev(vsi->back), "Not setting number of Tx/Rx descriptors for VSI type %d\n", vsi->type); break; } } /** * ice_vsi_set_num_qs - Set number of queues, descriptors and vectors for a VSI * @vsi: the VSI being configured * * Return 0 on success and a negative value on error */ static void ice_vsi_set_num_qs(struct ice_vsi *vsi) { enum ice_vsi_type vsi_type = vsi->type; struct ice_pf *pf = vsi->back; struct ice_vf *vf = vsi->vf; if (WARN_ON(vsi_type == ICE_VSI_VF && !vf)) return; switch (vsi_type) { case ICE_VSI_PF: if (vsi->req_txq) { vsi->alloc_txq = vsi->req_txq; vsi->num_txq = vsi->req_txq; } else { vsi->alloc_txq = min3(pf->num_lan_msix, ice_get_avail_txq_count(pf), (u16)num_online_cpus()); } pf->num_lan_tx = vsi->alloc_txq; /* only 1 Rx queue unless RSS is enabled */ if (!test_bit(ICE_FLAG_RSS_ENA, pf->flags)) { vsi->alloc_rxq = 1; } else { if (vsi->req_rxq) { vsi->alloc_rxq = vsi->req_rxq; vsi->num_rxq = vsi->req_rxq; } else { vsi->alloc_rxq = min3(pf->num_lan_msix, ice_get_avail_rxq_count(pf), (u16)num_online_cpus()); } } pf->num_lan_rx = vsi->alloc_rxq; vsi->num_q_vectors = min_t(int, pf->num_lan_msix, max_t(int, vsi->alloc_rxq, vsi->alloc_txq)); break; case ICE_VSI_SWITCHDEV_CTRL: /* The number of queues for ctrl VSI is equal to number of VFs. * Each ring is associated to the corresponding VF_PR netdev. */ vsi->alloc_txq = ice_get_num_vfs(pf); vsi->alloc_rxq = vsi->alloc_txq; vsi->num_q_vectors = 1; break; case ICE_VSI_VF: if (vf->num_req_qs) vf->num_vf_qs = vf->num_req_qs; vsi->alloc_txq = vf->num_vf_qs; vsi->alloc_rxq = vf->num_vf_qs; /* pf->vfs.num_msix_per includes (VF miscellaneous vector + * data queue interrupts). Since vsi->num_q_vectors is number * of queues vectors, subtract 1 (ICE_NONQ_VECS_VF) from the * original vector count */ vsi->num_q_vectors = pf->vfs.num_msix_per - ICE_NONQ_VECS_VF; break; case ICE_VSI_CTRL: vsi->alloc_txq = 1; vsi->alloc_rxq = 1; vsi->num_q_vectors = 1; break; case ICE_VSI_CHNL: vsi->alloc_txq = 0; vsi->alloc_rxq = 0; break; case ICE_VSI_LB: vsi->alloc_txq = 1; vsi->alloc_rxq = 1; break; default: dev_warn(ice_pf_to_dev(pf), "Unknown VSI type %d\n", vsi_type); break; } ice_vsi_set_num_desc(vsi); } /** * ice_get_free_slot - get the next non-NULL location index in array * @array: array to search * @size: size of the array * @curr: last known occupied index to be used as a search hint * * void * is being used to keep the functionality generic. This lets us use this * function on any array of pointers. */ static int ice_get_free_slot(void *array, int size, int curr) { int **tmp_array = (int **)array; int next; if (curr < (size - 1) && !tmp_array[curr + 1]) { next = curr + 1; } else { int i = 0; while ((i < size) && (tmp_array[i])) i++; if (i == size) next = ICE_NO_VSI; else next = i; } return next; } /** * ice_vsi_delete_from_hw - delete a VSI from the switch * @vsi: pointer to VSI being removed */ static void ice_vsi_delete_from_hw(struct ice_vsi *vsi) { struct ice_pf *pf = vsi->back; struct ice_vsi_ctx *ctxt; int status; ice_fltr_remove_all(vsi); ctxt = kzalloc(sizeof(*ctxt), GFP_KERNEL); if (!ctxt) return; if (vsi->type == ICE_VSI_VF) ctxt->vf_num = vsi->vf->vf_id; ctxt->vsi_num = vsi->vsi_num; memcpy(&ctxt->info, &vsi->info, sizeof(ctxt->info)); status = ice_free_vsi(&pf->hw, vsi->idx, ctxt, false, NULL); if (status) dev_err(ice_pf_to_dev(pf), "Failed to delete VSI %i in FW - error: %d\n", vsi->vsi_num, status); kfree(ctxt); } /** * ice_vsi_free_arrays - De-allocate queue and vector pointer arrays for the VSI * @vsi: pointer to VSI being cleared */ static void ice_vsi_free_arrays(struct ice_vsi *vsi) { struct ice_pf *pf = vsi->back; struct device *dev; dev = ice_pf_to_dev(pf); bitmap_free(vsi->af_xdp_zc_qps); vsi->af_xdp_zc_qps = NULL; /* free the ring and vector containers */ devm_kfree(dev, vsi->q_vectors); vsi->q_vectors = NULL; devm_kfree(dev, vsi->tx_rings); vsi->tx_rings = NULL; devm_kfree(dev, vsi->rx_rings); vsi->rx_rings = NULL; devm_kfree(dev, vsi->txq_map); vsi->txq_map = NULL; devm_kfree(dev, vsi->rxq_map); vsi->rxq_map = NULL; } /** * ice_vsi_free_stats - Free the ring statistics structures * @vsi: VSI pointer */ static void ice_vsi_free_stats(struct ice_vsi *vsi) { struct ice_vsi_stats *vsi_stat; struct ice_pf *pf = vsi->back; int i; if (vsi->type == ICE_VSI_CHNL) return; if (!pf->vsi_stats) return; vsi_stat = pf->vsi_stats[vsi->idx]; if (!vsi_stat) return; ice_for_each_alloc_txq(vsi, i) { if (vsi_stat->tx_ring_stats[i]) { kfree_rcu(vsi_stat->tx_ring_stats[i], rcu); WRITE_ONCE(vsi_stat->tx_ring_stats[i], NULL); } } ice_for_each_alloc_rxq(vsi, i) { if (vsi_stat->rx_ring_stats[i]) { kfree_rcu(vsi_stat->rx_ring_stats[i], rcu); WRITE_ONCE(vsi_stat->rx_ring_stats[i], NULL); } } kfree(vsi_stat->tx_ring_stats); kfree(vsi_stat->rx_ring_stats); kfree(vsi_stat); pf->vsi_stats[vsi->idx] = NULL; } /** * ice_vsi_alloc_ring_stats - Allocates Tx and Rx ring stats for the VSI * @vsi: VSI which is having stats allocated */ static int ice_vsi_alloc_ring_stats(struct ice_vsi *vsi) { struct ice_ring_stats **tx_ring_stats; struct ice_ring_stats **rx_ring_stats; struct ice_vsi_stats *vsi_stats; struct ice_pf *pf = vsi->back; u16 i; vsi_stats = pf->vsi_stats[vsi->idx]; tx_ring_stats = vsi_stats->tx_ring_stats; rx_ring_stats = vsi_stats->rx_ring_stats; /* Allocate Tx ring stats */ ice_for_each_alloc_txq(vsi, i) { struct ice_ring_stats *ring_stats; struct ice_tx_ring *ring; ring = vsi->tx_rings[i]; ring_stats = tx_ring_stats[i]; if (!ring_stats) { ring_stats = kzalloc(sizeof(*ring_stats), GFP_KERNEL); if (!ring_stats) goto err_out; WRITE_ONCE(tx_ring_stats[i], ring_stats); } ring->ring_stats = ring_stats; } /* Allocate Rx ring stats */ ice_for_each_alloc_rxq(vsi, i) { struct ice_ring_stats *ring_stats; struct ice_rx_ring *ring; ring = vsi->rx_rings[i]; ring_stats = rx_ring_stats[i]; if (!ring_stats) { ring_stats = kzalloc(sizeof(*ring_stats), GFP_KERNEL); if (!ring_stats) goto err_out; WRITE_ONCE(rx_ring_stats[i], ring_stats); } ring->ring_stats = ring_stats; } return 0; err_out: ice_vsi_free_stats(vsi); return -ENOMEM; } /** * ice_vsi_free - clean up and deallocate the provided VSI * @vsi: pointer to VSI being cleared * * This deallocates the VSI's queue resources, removes it from the PF's * VSI array if necessary, and deallocates the VSI */ static void ice_vsi_free(struct ice_vsi *vsi) { struct ice_pf *pf = NULL; struct device *dev; if (!vsi || !vsi->back) return; pf = vsi->back; dev = ice_pf_to_dev(pf); if (!pf->vsi[vsi->idx] || pf->vsi[vsi->idx] != vsi) { dev_dbg(dev, "vsi does not exist at pf->vsi[%d]\n", vsi->idx); return; } mutex_lock(&pf->sw_mutex); /* updates the PF for this cleared VSI */ pf->vsi[vsi->idx] = NULL; pf->next_vsi = vsi->idx; ice_vsi_free_stats(vsi); ice_vsi_free_arrays(vsi); mutex_unlock(&pf->sw_mutex); devm_kfree(dev, vsi); } void ice_vsi_delete(struct ice_vsi *vsi) { ice_vsi_delete_from_hw(vsi); ice_vsi_free(vsi); } /** * ice_msix_clean_ctrl_vsi - MSIX mode interrupt handler for ctrl VSI * @irq: interrupt number * @data: pointer to a q_vector */ static irqreturn_t ice_msix_clean_ctrl_vsi(int __always_unused irq, void *data) { struct ice_q_vector *q_vector = (struct ice_q_vector *)data; if (!q_vector->tx.tx_ring) return IRQ_HANDLED; #define FDIR_RX_DESC_CLEAN_BUDGET 64 ice_clean_rx_irq(q_vector->rx.rx_ring, FDIR_RX_DESC_CLEAN_BUDGET); ice_clean_ctrl_tx_irq(q_vector->tx.tx_ring); return IRQ_HANDLED; } /** * ice_msix_clean_rings - MSIX mode Interrupt Handler * @irq: interrupt number * @data: pointer to a q_vector */ static irqreturn_t ice_msix_clean_rings(int __always_unused irq, void *data) { struct ice_q_vector *q_vector = (struct ice_q_vector *)data; if (!q_vector->tx.tx_ring && !q_vector->rx.rx_ring) return IRQ_HANDLED; q_vector->total_events++; napi_schedule(&q_vector->napi); return IRQ_HANDLED; } static irqreturn_t ice_eswitch_msix_clean_rings(int __always_unused irq, void *data) { struct ice_q_vector *q_vector = (struct ice_q_vector *)data; struct ice_pf *pf = q_vector->vsi->back; struct ice_vf *vf; unsigned int bkt; if (!q_vector->tx.tx_ring && !q_vector->rx.rx_ring) return IRQ_HANDLED; rcu_read_lock(); ice_for_each_vf_rcu(pf, bkt, vf) napi_schedule(&vf->repr->q_vector->napi); rcu_read_unlock(); return IRQ_HANDLED; } /** * ice_vsi_alloc_stat_arrays - Allocate statistics arrays * @vsi: VSI pointer */ static int ice_vsi_alloc_stat_arrays(struct ice_vsi *vsi) { struct ice_vsi_stats *vsi_stat; struct ice_pf *pf = vsi->back; if (vsi->type == ICE_VSI_CHNL) return 0; if (!pf->vsi_stats) return -ENOENT; if (pf->vsi_stats[vsi->idx]) /* realloc will happen in rebuild path */ return 0; vsi_stat = kzalloc(sizeof(*vsi_stat), GFP_KERNEL); if (!vsi_stat) return -ENOMEM; vsi_stat->tx_ring_stats = kcalloc(vsi->alloc_txq, sizeof(*vsi_stat->tx_ring_stats), GFP_KERNEL); if (!vsi_stat->tx_ring_stats) goto err_alloc_tx; vsi_stat->rx_ring_stats = kcalloc(vsi->alloc_rxq, sizeof(*vsi_stat->rx_ring_stats), GFP_KERNEL); if (!vsi_stat->rx_ring_stats) goto err_alloc_rx; pf->vsi_stats[vsi->idx] = vsi_stat; return 0; err_alloc_rx: kfree(vsi_stat->rx_ring_stats); err_alloc_tx: kfree(vsi_stat->tx_ring_stats); kfree(vsi_stat); pf->vsi_stats[vsi->idx] = NULL; return -ENOMEM; } /** * ice_vsi_alloc_def - set default values for already allocated VSI * @vsi: ptr to VSI * @ch: ptr to channel */ static int ice_vsi_alloc_def(struct ice_vsi *vsi, struct ice_channel *ch) { if (vsi->type != ICE_VSI_CHNL) { ice_vsi_set_num_qs(vsi); if (ice_vsi_alloc_arrays(vsi)) return -ENOMEM; } switch (vsi->type) { case ICE_VSI_SWITCHDEV_CTRL: /* Setup eswitch MSIX irq handler for VSI */ vsi->irq_handler = ice_eswitch_msix_clean_rings; break; case ICE_VSI_PF: /* Setup default MSIX irq handler for VSI */ vsi->irq_handler = ice_msix_clean_rings; break; case ICE_VSI_CTRL: /* Setup ctrl VSI MSIX irq handler */ vsi->irq_handler = ice_msix_clean_ctrl_vsi; break; case ICE_VSI_CHNL: if (!ch) return -EINVAL; vsi->num_rxq = ch->num_rxq; vsi->num_txq = ch->num_txq; vsi->next_base_q = ch->base_q; break; case ICE_VSI_VF: case ICE_VSI_LB: break; default: ice_vsi_free_arrays(vsi); return -EINVAL; } return 0; } /** * ice_vsi_alloc - Allocates the next available struct VSI in the PF * @pf: board private structure * * Reserves a VSI index from the PF and allocates an empty VSI structure * without a type. The VSI structure must later be initialized by calling * ice_vsi_cfg(). * * returns a pointer to a VSI on success, NULL on failure. */ static struct ice_vsi *ice_vsi_alloc(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); struct ice_vsi *vsi = NULL; /* Need to protect the allocation of the VSIs at the PF level */ mutex_lock(&pf->sw_mutex); /* If we have already allocated our maximum number of VSIs, * pf->next_vsi will be ICE_NO_VSI. If not, pf->next_vsi index * is available to be populated */ if (pf->next_vsi == ICE_NO_VSI) { dev_dbg(dev, "out of VSI slots!\n"); goto unlock_pf; } vsi = devm_kzalloc(dev, sizeof(*vsi), GFP_KERNEL); if (!vsi) goto unlock_pf; vsi->back = pf; set_bit(ICE_VSI_DOWN, vsi->state); /* fill slot and make note of the index */ vsi->idx = pf->next_vsi; pf->vsi[pf->next_vsi] = vsi; /* prepare pf->next_vsi for next use */ pf->next_vsi = ice_get_free_slot(pf->vsi, pf->num_alloc_vsi, pf->next_vsi); unlock_pf: mutex_unlock(&pf->sw_mutex); return vsi; } /** * ice_alloc_fd_res - Allocate FD resource for a VSI * @vsi: pointer to the ice_vsi * * This allocates the FD resources * * Returns 0 on success, -EPERM on no-op or -EIO on failure */ static int ice_alloc_fd_res(struct ice_vsi *vsi) { struct ice_pf *pf = vsi->back; u32 g_val, b_val; /* Flow Director filters are only allocated/assigned to the PF VSI or * CHNL VSI which passes the traffic. The CTRL VSI is only used to * add/delete filters so resources are not allocated to it */ if (!test_bit(ICE_FLAG_FD_ENA, pf->flags)) return -EPERM; if (!(vsi->type == ICE_VSI_PF || vsi->type == ICE_VSI_VF || vsi->type == ICE_VSI_CHNL)) return -EPERM; /* FD filters from guaranteed pool per VSI */ g_val = pf->hw.func_caps.fd_fltr_guar; if (!g_val) return -EPERM; /* FD filters from best effort pool */ b_val = pf->hw.func_caps.fd_fltr_best_effort; if (!b_val) return -EPERM; /* PF main VSI gets only 64 FD resources from guaranteed pool * when ADQ is configured. */ #define ICE_PF_VSI_GFLTR 64 /* determine FD filter resources per VSI from shared(best effort) and * dedicated pool */ if (vsi->type == ICE_VSI_PF) { vsi->num_gfltr = g_val; /* if MQPRIO is configured, main VSI doesn't get all FD * resources from guaranteed pool. PF VSI gets 64 FD resources */ if (test_bit(ICE_FLAG_TC_MQPRIO, pf->flags)) { if (g_val < ICE_PF_VSI_GFLTR) return -EPERM; /* allow bare minimum entries for PF VSI */ vsi->num_gfltr = ICE_PF_VSI_GFLTR; } /* each VSI gets same "best_effort" quota */ vsi->num_bfltr = b_val; } else if (vsi->type == ICE_VSI_VF) { vsi->num_gfltr = 0; /* each VSI gets same "best_effort" quota */ vsi->num_bfltr = b_val; } else { struct ice_vsi *main_vsi; int numtc; main_vsi = ice_get_main_vsi(pf); if (!main_vsi) return -EPERM; if (!main_vsi->all_numtc) return -EINVAL; /* figure out ADQ numtc */ numtc = main_vsi->all_numtc - ICE_CHNL_START_TC; /* only one TC but still asking resources for channels, * invalid config */ if (numtc < ICE_CHNL_START_TC) return -EPERM; g_val -= ICE_PF_VSI_GFLTR; /* channel VSIs gets equal share from guaranteed pool */ vsi->num_gfltr = g_val / numtc; /* each VSI gets same "best_effort" quota */ vsi->num_bfltr = b_val; } return 0; } /** * ice_vsi_get_qs - Assign queues from PF to VSI * @vsi: the VSI to assign queues to * * Returns 0 on success and a negative value on error */ static int ice_vsi_get_qs(struct ice_vsi *vsi) { struct ice_pf *pf = vsi->back; struct ice_qs_cfg tx_qs_cfg = { .qs_mutex = &pf->avail_q_mutex, .pf_map = pf->avail_txqs, .pf_map_size = pf->max_pf_txqs, .q_count = vsi->alloc_txq, .scatter_count = ICE_MAX_SCATTER_TXQS, .vsi_map = vsi->txq_map, .vsi_map_offset = 0, .mapping_mode = ICE_VSI_MAP_CONTIG }; struct ice_qs_cfg rx_qs_cfg = { .qs_mutex = &pf->avail_q_mutex, .pf_map = pf->avail_rxqs, .pf_map_size = pf->max_pf_rxqs, .q_count = vsi->alloc_rxq, .scatter_count = ICE_MAX_SCATTER_RXQS, .vsi_map = vsi->rxq_map, .vsi_map_offset = 0, .mapping_mode = ICE_VSI_MAP_CONTIG }; int ret; if (vsi->type == ICE_VSI_CHNL) return 0; ret = __ice_vsi_get_qs(&tx_qs_cfg); if (ret) return ret; vsi->tx_mapping_mode = tx_qs_cfg.mapping_mode; ret = __ice_vsi_get_qs(&rx_qs_cfg); if (ret) return ret; vsi->rx_mapping_mode = rx_qs_cfg.mapping_mode; return 0; } /** * ice_vsi_put_qs - Release queues from VSI to PF * @vsi: the VSI that is going to release queues */ static void ice_vsi_put_qs(struct ice_vsi *vsi) { struct ice_pf *pf = vsi->back; int i; mutex_lock(&pf->avail_q_mutex); ice_for_each_alloc_txq(vsi, i) { clear_bit(vsi->txq_map[i], pf->avail_txqs); vsi->txq_map[i] = ICE_INVAL_Q_INDEX; } ice_for_each_alloc_rxq(vsi, i) { clear_bit(vsi->rxq_map[i], pf->avail_rxqs); vsi->rxq_map[i] = ICE_INVAL_Q_INDEX; } mutex_unlock(&pf->avail_q_mutex); } /** * ice_is_safe_mode * @pf: pointer to the PF struct * * returns true if driver is in safe mode, false otherwise */ bool ice_is_safe_mode(struct ice_pf *pf) { return !test_bit(ICE_FLAG_ADV_FEATURES, pf->flags); } /** * ice_is_rdma_ena * @pf: pointer to the PF struct * * returns true if RDMA is currently supported, false otherwise */ bool ice_is_rdma_ena(struct ice_pf *pf) { return test_bit(ICE_FLAG_RDMA_ENA, pf->flags); } /** * ice_vsi_clean_rss_flow_fld - Delete RSS configuration * @vsi: the VSI being cleaned up * * This function deletes RSS input set for all flows that were configured * for this VSI */ static void ice_vsi_clean_rss_flow_fld(struct ice_vsi *vsi) { struct ice_pf *pf = vsi->back; int status; if (ice_is_safe_mode(pf)) return; status = ice_rem_vsi_rss_cfg(&pf->hw, vsi->idx); if (status) dev_dbg(ice_pf_to_dev(pf), "ice_rem_vsi_rss_cfg failed for vsi = %d, error = %d\n", vsi->vsi_num, status); } /** * ice_rss_clean - Delete RSS related VSI structures and configuration * @vsi: the VSI being removed */ static void ice_rss_clean(struct ice_vsi *vsi) { struct ice_pf *pf = vsi->back; struct device *dev; dev = ice_pf_to_dev(pf); devm_kfree(dev, vsi->rss_hkey_user); devm_kfree(dev, vsi->rss_lut_user); ice_vsi_clean_rss_flow_fld(vsi); /* remove RSS replay list */ if (!ice_is_safe_mode(pf)) ice_rem_vsi_rss_list(&pf->hw, vsi->idx); } /** * ice_vsi_set_rss_params - Setup RSS capabilities per VSI type * @vsi: the VSI being configured */ static void ice_vsi_set_rss_params(struct ice_vsi *vsi) { struct ice_hw_common_caps *cap; struct ice_pf *pf = vsi->back; u16 max_rss_size; if (!test_bit(ICE_FLAG_RSS_ENA, pf->flags)) { vsi->rss_size = 1; return; } cap = &pf->hw.func_caps.common_cap; max_rss_size = BIT(cap->rss_table_entry_width); switch (vsi->type) { case ICE_VSI_CHNL: case ICE_VSI_PF: /* PF VSI will inherit RSS instance of PF */ vsi->rss_table_size = (u16)cap->rss_table_size; if (vsi->type == ICE_VSI_CHNL) vsi->rss_size = min_t(u16, vsi->num_rxq, max_rss_size); else vsi->rss_size = min_t(u16, num_online_cpus(), max_rss_size); vsi->rss_lut_type = ICE_LUT_PF; break; case ICE_VSI_SWITCHDEV_CTRL: vsi->rss_table_size = ICE_LUT_VSI_SIZE; vsi->rss_size = min_t(u16, num_online_cpus(), max_rss_size); vsi->rss_lut_type = ICE_LUT_VSI; break; case ICE_VSI_VF: /* VF VSI will get a small RSS table. * For VSI_LUT, LUT size should be set to 64 bytes. */ vsi->rss_table_size = ICE_LUT_VSI_SIZE; vsi->rss_size = ICE_MAX_RSS_QS_PER_VF; vsi->rss_lut_type = ICE_LUT_VSI; break; case ICE_VSI_LB: break; default: dev_dbg(ice_pf_to_dev(pf), "Unsupported VSI type %s\n", ice_vsi_type_str(vsi->type)); break; } } /** * ice_set_dflt_vsi_ctx - Set default VSI context before adding a VSI * @hw: HW structure used to determine the VLAN mode of the device * @ctxt: the VSI context being set * * This initializes a default VSI context for all sections except the Queues. */ static void ice_set_dflt_vsi_ctx(struct ice_hw *hw, struct ice_vsi_ctx *ctxt) { u32 table = 0; memset(&ctxt->info, 0, sizeof(ctxt->info)); /* VSI's should be allocated from shared pool */ ctxt->alloc_from_pool = true; /* Src pruning enabled by default */ ctxt->info.sw_flags = ICE_AQ_VSI_SW_FLAG_SRC_PRUNE; /* Traffic from VSI can be sent to LAN */ ctxt->info.sw_flags2 = ICE_AQ_VSI_SW_FLAG_LAN_ENA; /* allow all untagged/tagged packets by default on Tx */ ctxt->info.inner_vlan_flags = ((ICE_AQ_VSI_INNER_VLAN_TX_MODE_ALL & ICE_AQ_VSI_INNER_VLAN_TX_MODE_M) >> ICE_AQ_VSI_INNER_VLAN_TX_MODE_S); /* SVM - by default bits 3 and 4 in inner_vlan_flags are 0's which * results in legacy behavior (show VLAN, DEI, and UP) in descriptor. * * DVM - leave inner VLAN in packet by default */ if (ice_is_dvm_ena(hw)) { ctxt->info.inner_vlan_flags |= ICE_AQ_VSI_INNER_VLAN_EMODE_NOTHING; ctxt->info.outer_vlan_flags = (ICE_AQ_VSI_OUTER_VLAN_TX_MODE_ALL << ICE_AQ_VSI_OUTER_VLAN_TX_MODE_S) & ICE_AQ_VSI_OUTER_VLAN_TX_MODE_M; ctxt->info.outer_vlan_flags |= (ICE_AQ_VSI_OUTER_TAG_VLAN_8100 << ICE_AQ_VSI_OUTER_TAG_TYPE_S) & ICE_AQ_VSI_OUTER_TAG_TYPE_M; ctxt->info.outer_vlan_flags |= FIELD_PREP(ICE_AQ_VSI_OUTER_VLAN_EMODE_M, ICE_AQ_VSI_OUTER_VLAN_EMODE_NOTHING); } /* Have 1:1 UP mapping for both ingress/egress tables */ table |= ICE_UP_TABLE_TRANSLATE(0, 0); table |= ICE_UP_TABLE_TRANSLATE(1, 1); table |= ICE_UP_TABLE_TRANSLATE(2, 2); table |= ICE_UP_TABLE_TRANSLATE(3, 3); table |= ICE_UP_TABLE_TRANSLATE(4, 4); table |= ICE_UP_TABLE_TRANSLATE(5, 5); table |= ICE_UP_TABLE_TRANSLATE(6, 6); table |= ICE_UP_TABLE_TRANSLATE(7, 7); ctxt->info.ingress_table = cpu_to_le32(table); ctxt->info.egress_table = cpu_to_le32(table); /* Have 1:1 UP mapping for outer to inner UP table */ ctxt->info.outer_up_table = cpu_to_le32(table); /* No Outer tag support outer_tag_flags remains to zero */ } /** * ice_vsi_setup_q_map - Setup a VSI queue map * @vsi: the VSI being configured * @ctxt: VSI context structure */ static int ice_vsi_setup_q_map(struct ice_vsi *vsi, struct ice_vsi_ctx *ctxt) { u16 offset = 0, qmap = 0, tx_count = 0, rx_count = 0, pow = 0; u16 num_txq_per_tc, num_rxq_per_tc; u16 qcount_tx = vsi->alloc_txq; u16 qcount_rx = vsi->alloc_rxq; u8 netdev_tc = 0; int i; if (!vsi->tc_cfg.numtc) { /* at least TC0 should be enabled by default */ vsi->tc_cfg.numtc = 1; vsi->tc_cfg.ena_tc = 1; } num_rxq_per_tc = min_t(u16, qcount_rx / vsi->tc_cfg.numtc, ICE_MAX_RXQS_PER_TC); if (!num_rxq_per_tc) num_rxq_per_tc = 1; num_txq_per_tc = qcount_tx / vsi->tc_cfg.numtc; if (!num_txq_per_tc) num_txq_per_tc = 1; /* find the (rounded up) power-of-2 of qcount */ pow = (u16)order_base_2(num_rxq_per_tc); /* TC mapping is a function of the number of Rx queues assigned to the * VSI for each traffic class and the offset of these queues. * The first 10 bits are for queue offset for TC0, next 4 bits for no:of * queues allocated to TC0. No:of queues is a power-of-2. * * If TC is not enabled, the queue offset is set to 0, and allocate one * queue, this way, traffic for the given TC will be sent to the default * queue. * * Setup number and offset of Rx queues for all TCs for the VSI */ ice_for_each_traffic_class(i) { if (!(vsi->tc_cfg.ena_tc & BIT(i))) { /* TC is not enabled */ vsi->tc_cfg.tc_info[i].qoffset = 0; vsi->tc_cfg.tc_info[i].qcount_rx = 1; vsi->tc_cfg.tc_info[i].qcount_tx = 1; vsi->tc_cfg.tc_info[i].netdev_tc = 0; ctxt->info.tc_mapping[i] = 0; continue; } /* TC is enabled */ vsi->tc_cfg.tc_info[i].qoffset = offset; vsi->tc_cfg.tc_info[i].qcount_rx = num_rxq_per_tc; vsi->tc_cfg.tc_info[i].qcount_tx = num_txq_per_tc; vsi->tc_cfg.tc_info[i].netdev_tc = netdev_tc++; qmap = ((offset << ICE_AQ_VSI_TC_Q_OFFSET_S) & ICE_AQ_VSI_TC_Q_OFFSET_M) | ((pow << ICE_AQ_VSI_TC_Q_NUM_S) & ICE_AQ_VSI_TC_Q_NUM_M); offset += num_rxq_per_tc; tx_count += num_txq_per_tc; ctxt->info.tc_mapping[i] = cpu_to_le16(qmap); } /* if offset is non-zero, means it is calculated correctly based on * enabled TCs for a given VSI otherwise qcount_rx will always * be correct and non-zero because it is based off - VSI's * allocated Rx queues which is at least 1 (hence qcount_tx will be * at least 1) */ if (offset) rx_count = offset; else rx_count = num_rxq_per_tc; if (rx_count > vsi->alloc_rxq) { dev_err(ice_pf_to_dev(vsi->back), "Trying to use more Rx queues (%u), than were allocated (%u)!\n", rx_count, vsi->alloc_rxq); return -EINVAL; } if (tx_count > vsi->alloc_txq) { dev_err(ice_pf_to_dev(vsi->back), "Trying to use more Tx queues (%u), than were allocated (%u)!\n", tx_count, vsi->alloc_txq); return -EINVAL; } vsi->num_txq = tx_count; vsi->num_rxq = rx_count; if (vsi->type == ICE_VSI_VF && vsi->num_txq != vsi->num_rxq) { dev_dbg(ice_pf_to_dev(vsi->back), "VF VSI should have same number of Tx and Rx queues. Hence making them equal\n"); /* since there is a chance that num_rxq could have been changed * in the above for loop, make num_txq equal to num_rxq. */ vsi->num_txq = vsi->num_rxq; } /* Rx queue mapping */ ctxt->info.mapping_flags |= cpu_to_le16(ICE_AQ_VSI_Q_MAP_CONTIG); /* q_mapping buffer holds the info for the first queue allocated for * this VSI in the PF space and also the number of queues associated * with this VSI. */ ctxt->info.q_mapping[0] = cpu_to_le16(vsi->rxq_map[0]); ctxt->info.q_mapping[1] = cpu_to_le16(vsi->num_rxq); return 0; } /** * ice_set_fd_vsi_ctx - Set FD VSI context before adding a VSI * @ctxt: the VSI context being set * @vsi: the VSI being configured */ static void ice_set_fd_vsi_ctx(struct ice_vsi_ctx *ctxt, struct ice_vsi *vsi) { u8 dflt_q_group, dflt_q_prio; u16 dflt_q, report_q, val; if (vsi->type != ICE_VSI_PF && vsi->type != ICE_VSI_CTRL && vsi->type != ICE_VSI_VF && vsi->type != ICE_VSI_CHNL) return; val = ICE_AQ_VSI_PROP_FLOW_DIR_VALID; ctxt->info.valid_sections |= cpu_to_le16(val); dflt_q = 0; dflt_q_group = 0; report_q = 0; dflt_q_prio = 0; /* enable flow director filtering/programming */ val = ICE_AQ_VSI_FD_ENABLE | ICE_AQ_VSI_FD_PROG_ENABLE; ctxt->info.fd_options = cpu_to_le16(val); /* max of allocated flow director filters */ ctxt->info.max_fd_fltr_dedicated = cpu_to_le16(vsi->num_gfltr); /* max of shared flow director filters any VSI may program */ ctxt->info.max_fd_fltr_shared = cpu_to_le16(vsi->num_bfltr); /* default queue index within the VSI of the default FD */ val = ((dflt_q << ICE_AQ_VSI_FD_DEF_Q_S) & ICE_AQ_VSI_FD_DEF_Q_M); /* target queue or queue group to the FD filter */ val |= ((dflt_q_group << ICE_AQ_VSI_FD_DEF_GRP_S) & ICE_AQ_VSI_FD_DEF_GRP_M); ctxt->info.fd_def_q = cpu_to_le16(val); /* queue index on which FD filter completion is reported */ val = ((report_q << ICE_AQ_VSI_FD_REPORT_Q_S) & ICE_AQ_VSI_FD_REPORT_Q_M); /* priority of the default qindex action */ val |= ((dflt_q_prio << ICE_AQ_VSI_FD_DEF_PRIORITY_S) & ICE_AQ_VSI_FD_DEF_PRIORITY_M); ctxt->info.fd_report_opt = cpu_to_le16(val); } /** * ice_set_rss_vsi_ctx - Set RSS VSI context before adding a VSI * @ctxt: the VSI context being set * @vsi: the VSI being configured */ static void ice_set_rss_vsi_ctx(struct ice_vsi_ctx *ctxt, struct ice_vsi *vsi) { u8 lut_type, hash_type; struct device *dev; struct ice_pf *pf; pf = vsi->back; dev = ice_pf_to_dev(pf); switch (vsi->type) { case ICE_VSI_CHNL: case ICE_VSI_PF: /* PF VSI will inherit RSS instance of PF */ lut_type = ICE_AQ_VSI_Q_OPT_RSS_LUT_PF; hash_type = ICE_AQ_VSI_Q_OPT_RSS_TPLZ; break; case ICE_VSI_VF: /* VF VSI will gets a small RSS table which is a VSI LUT type */ lut_type = ICE_AQ_VSI_Q_OPT_RSS_LUT_VSI; hash_type = ICE_AQ_VSI_Q_OPT_RSS_TPLZ; break; default: dev_dbg(dev, "Unsupported VSI type %s\n", ice_vsi_type_str(vsi->type)); return; } ctxt->info.q_opt_rss = ((lut_type << ICE_AQ_VSI_Q_OPT_RSS_LUT_S) & ICE_AQ_VSI_Q_OPT_RSS_LUT_M) | ((hash_type << ICE_AQ_VSI_Q_OPT_RSS_HASH_S) & ICE_AQ_VSI_Q_OPT_RSS_HASH_M); } static void ice_chnl_vsi_setup_q_map(struct ice_vsi *vsi, struct ice_vsi_ctx *ctxt) { struct ice_pf *pf = vsi->back; u16 qcount, qmap; u8 offset = 0; int pow; qcount = min_t(int, vsi->num_rxq, pf->num_lan_msix); pow = order_base_2(qcount); qmap = ((offset << ICE_AQ_VSI_TC_Q_OFFSET_S) & ICE_AQ_VSI_TC_Q_OFFSET_M) | ((pow << ICE_AQ_VSI_TC_Q_NUM_S) & ICE_AQ_VSI_TC_Q_NUM_M); ctxt->info.tc_mapping[0] = cpu_to_le16(qmap); ctxt->info.mapping_flags |= cpu_to_le16(ICE_AQ_VSI_Q_MAP_CONTIG); ctxt->info.q_mapping[0] = cpu_to_le16(vsi->next_base_q); ctxt->info.q_mapping[1] = cpu_to_le16(qcount); } /** * ice_vsi_is_vlan_pruning_ena - check if VLAN pruning is enabled or not * @vsi: VSI to check whether or not VLAN pruning is enabled. * * returns true if Rx VLAN pruning is enabled and false otherwise. */ static bool ice_vsi_is_vlan_pruning_ena(struct ice_vsi *vsi) { return vsi->info.sw_flags2 & ICE_AQ_VSI_SW_FLAG_RX_VLAN_PRUNE_ENA; } /** * ice_vsi_init - Create and initialize a VSI * @vsi: the VSI being configured * @vsi_flags: VSI configuration flags * * Set ICE_FLAG_VSI_INIT to initialize a new VSI context, clear it to * reconfigure an existing context. * * This initializes a VSI context depending on the VSI type to be added and * passes it down to the add_vsi aq command to create a new VSI. */ static int ice_vsi_init(struct ice_vsi *vsi, u32 vsi_flags) { struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; struct ice_vsi_ctx *ctxt; struct device *dev; int ret = 0; dev = ice_pf_to_dev(pf); ctxt = kzalloc(sizeof(*ctxt), GFP_KERNEL); if (!ctxt) return -ENOMEM; switch (vsi->type) { case ICE_VSI_CTRL: case ICE_VSI_LB: case ICE_VSI_PF: ctxt->flags = ICE_AQ_VSI_TYPE_PF; break; case ICE_VSI_SWITCHDEV_CTRL: case ICE_VSI_CHNL: ctxt->flags = ICE_AQ_VSI_TYPE_VMDQ2; break; case ICE_VSI_VF: ctxt->flags = ICE_AQ_VSI_TYPE_VF; /* VF number here is the absolute VF number (0-255) */ ctxt->vf_num = vsi->vf->vf_id + hw->func_caps.vf_base_id; break; default: ret = -ENODEV; goto out; } /* Handle VLAN pruning for channel VSI if main VSI has VLAN * prune enabled */ if (vsi->type == ICE_VSI_CHNL) { struct ice_vsi *main_vsi; main_vsi = ice_get_main_vsi(pf); if (main_vsi && ice_vsi_is_vlan_pruning_ena(main_vsi)) ctxt->info.sw_flags2 |= ICE_AQ_VSI_SW_FLAG_RX_VLAN_PRUNE_ENA; else ctxt->info.sw_flags2 &= ~ICE_AQ_VSI_SW_FLAG_RX_VLAN_PRUNE_ENA; } ice_set_dflt_vsi_ctx(hw, ctxt); if (test_bit(ICE_FLAG_FD_ENA, pf->flags)) ice_set_fd_vsi_ctx(ctxt, vsi); /* if the switch is in VEB mode, allow VSI loopback */ if (vsi->vsw->bridge_mode == BRIDGE_MODE_VEB) ctxt->info.sw_flags |= ICE_AQ_VSI_SW_FLAG_ALLOW_LB; /* Set LUT type and HASH type if RSS is enabled */ if (test_bit(ICE_FLAG_RSS_ENA, pf->flags) && vsi->type != ICE_VSI_CTRL) { ice_set_rss_vsi_ctx(ctxt, vsi); /* if updating VSI context, make sure to set valid_section: * to indicate which section of VSI context being updated */ if (!(vsi_flags & ICE_VSI_FLAG_INIT)) ctxt->info.valid_sections |= cpu_to_le16(ICE_AQ_VSI_PROP_Q_OPT_VALID); } ctxt->info.sw_id = vsi->port_info->sw_id; if (vsi->type == ICE_VSI_CHNL) { ice_chnl_vsi_setup_q_map(vsi, ctxt); } else { ret = ice_vsi_setup_q_map(vsi, ctxt); if (ret) goto out; if (!(vsi_flags & ICE_VSI_FLAG_INIT)) /* means VSI being updated */ /* must to indicate which section of VSI context are * being modified */ ctxt->info.valid_sections |= cpu_to_le16(ICE_AQ_VSI_PROP_RXQ_MAP_VALID); } /* Allow control frames out of main VSI */ if (vsi->type == ICE_VSI_PF) { ctxt->info.sec_flags |= ICE_AQ_VSI_SEC_FLAG_ALLOW_DEST_OVRD; ctxt->info.valid_sections |= cpu_to_le16(ICE_AQ_VSI_PROP_SECURITY_VALID); } if (vsi_flags & ICE_VSI_FLAG_INIT) { ret = ice_add_vsi(hw, vsi->idx, ctxt, NULL); if (ret) { dev_err(dev, "Add VSI failed, err %d\n", ret); ret = -EIO; goto out; } } else { ret = ice_update_vsi(hw, vsi->idx, ctxt, NULL); if (ret) { dev_err(dev, "Update VSI failed, err %d\n", ret); ret = -EIO; goto out; } } /* keep context for update VSI operations */ vsi->info = ctxt->info; /* record VSI number returned */ vsi->vsi_num = ctxt->vsi_num; out: kfree(ctxt); return ret; } /** * ice_vsi_clear_rings - Deallocates the Tx and Rx rings for VSI * @vsi: the VSI having rings deallocated */ static void ice_vsi_clear_rings(struct ice_vsi *vsi) { int i; /* Avoid stale references by clearing map from vector to ring */ if (vsi->q_vectors) { ice_for_each_q_vector(vsi, i) { struct ice_q_vector *q_vector = vsi->q_vectors[i]; if (q_vector) { q_vector->tx.tx_ring = NULL; q_vector->rx.rx_ring = NULL; } } } if (vsi->tx_rings) { ice_for_each_alloc_txq(vsi, i) { if (vsi->tx_rings[i]) { kfree_rcu(vsi->tx_rings[i], rcu); WRITE_ONCE(vsi->tx_rings[i], NULL); } } } if (vsi->rx_rings) { ice_for_each_alloc_rxq(vsi, i) { if (vsi->rx_rings[i]) { kfree_rcu(vsi->rx_rings[i], rcu); WRITE_ONCE(vsi->rx_rings[i], NULL); } } } } /** * ice_vsi_alloc_rings - Allocates Tx and Rx rings for the VSI * @vsi: VSI which is having rings allocated */ static int ice_vsi_alloc_rings(struct ice_vsi *vsi) { bool dvm_ena = ice_is_dvm_ena(&vsi->back->hw); struct ice_pf *pf = vsi->back; struct device *dev; u16 i; dev = ice_pf_to_dev(pf); /* Allocate Tx rings */ ice_for_each_alloc_txq(vsi, i) { struct ice_tx_ring *ring; /* allocate with kzalloc(), free with kfree_rcu() */ ring = kzalloc(sizeof(*ring), GFP_KERNEL); if (!ring) goto err_out; ring->q_index = i; ring->reg_idx = vsi->txq_map[i]; ring->vsi = vsi; ring->tx_tstamps = &pf->ptp.port.tx; ring->dev = dev; ring->count = vsi->num_tx_desc; ring->txq_teid = ICE_INVAL_TEID; if (dvm_ena) ring->flags |= ICE_TX_FLAGS_RING_VLAN_L2TAG2; else ring->flags |= ICE_TX_FLAGS_RING_VLAN_L2TAG1; WRITE_ONCE(vsi->tx_rings[i], ring); } /* Allocate Rx rings */ ice_for_each_alloc_rxq(vsi, i) { struct ice_rx_ring *ring; /* allocate with kzalloc(), free with kfree_rcu() */ ring = kzalloc(sizeof(*ring), GFP_KERNEL); if (!ring) goto err_out; ring->q_index = i; ring->reg_idx = vsi->rxq_map[i]; ring->vsi = vsi; ring->netdev = vsi->netdev; ring->dev = dev; ring->count = vsi->num_rx_desc; ring->cached_phctime = pf->ptp.cached_phc_time; WRITE_ONCE(vsi->rx_rings[i], ring); } return 0; err_out: ice_vsi_clear_rings(vsi); return -ENOMEM; } /** * ice_vsi_manage_rss_lut - disable/enable RSS * @vsi: the VSI being changed * @ena: boolean value indicating if this is an enable or disable request * * In the event of disable request for RSS, this function will zero out RSS * LUT, while in the event of enable request for RSS, it will reconfigure RSS * LUT. */ void ice_vsi_manage_rss_lut(struct ice_vsi *vsi, bool ena) { u8 *lut; lut = kzalloc(vsi->rss_table_size, GFP_KERNEL); if (!lut) return; if (ena) { if (vsi->rss_lut_user) memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size); else ice_fill_rss_lut(lut, vsi->rss_table_size, vsi->rss_size); } ice_set_rss_lut(vsi, lut, vsi->rss_table_size); kfree(lut); } /** * ice_vsi_cfg_crc_strip - Configure CRC stripping for a VSI * @vsi: VSI to be configured * @disable: set to true to have FCS / CRC in the frame data */ void ice_vsi_cfg_crc_strip(struct ice_vsi *vsi, bool disable) { int i; ice_for_each_rxq(vsi, i) if (disable) vsi->rx_rings[i]->flags |= ICE_RX_FLAGS_CRC_STRIP_DIS; else vsi->rx_rings[i]->flags &= ~ICE_RX_FLAGS_CRC_STRIP_DIS; } /** * ice_vsi_cfg_rss_lut_key - Configure RSS params for a VSI * @vsi: VSI to be configured */ int ice_vsi_cfg_rss_lut_key(struct ice_vsi *vsi) { struct ice_pf *pf = vsi->back; struct device *dev; u8 *lut, *key; int err; dev = ice_pf_to_dev(pf); if (vsi->type == ICE_VSI_PF && vsi->ch_rss_size && (test_bit(ICE_FLAG_TC_MQPRIO, pf->flags))) { vsi->rss_size = min_t(u16, vsi->rss_size, vsi->ch_rss_size); } else { vsi->rss_size = min_t(u16, vsi->rss_size, vsi->num_rxq); /* If orig_rss_size is valid and it is less than determined * main VSI's rss_size, update main VSI's rss_size to be * orig_rss_size so that when tc-qdisc is deleted, main VSI * RSS table gets programmed to be correct (whatever it was * to begin with (prior to setup-tc for ADQ config) */ if (vsi->orig_rss_size && vsi->rss_size < vsi->orig_rss_size && vsi->orig_rss_size <= vsi->num_rxq) { vsi->rss_size = vsi->orig_rss_size; /* now orig_rss_size is used, reset it to zero */ vsi->orig_rss_size = 0; } } lut = kzalloc(vsi->rss_table_size, GFP_KERNEL); if (!lut) return -ENOMEM; if (vsi->rss_lut_user) memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size); else ice_fill_rss_lut(lut, vsi->rss_table_size, vsi->rss_size); err = ice_set_rss_lut(vsi, lut, vsi->rss_table_size); if (err) { dev_err(dev, "set_rss_lut failed, error %d\n", err); goto ice_vsi_cfg_rss_exit; } key = kzalloc(ICE_GET_SET_RSS_KEY_EXTEND_KEY_SIZE, GFP_KERNEL); if (!key) { err = -ENOMEM; goto ice_vsi_cfg_rss_exit; } if (vsi->rss_hkey_user) memcpy(key, vsi->rss_hkey_user, ICE_GET_SET_RSS_KEY_EXTEND_KEY_SIZE); else netdev_rss_key_fill((void *)key, ICE_GET_SET_RSS_KEY_EXTEND_KEY_SIZE); err = ice_set_rss_key(vsi, key); if (err) dev_err(dev, "set_rss_key failed, error %d\n", err); kfree(key); ice_vsi_cfg_rss_exit: kfree(lut); return err; } /** * ice_vsi_set_vf_rss_flow_fld - Sets VF VSI RSS input set for different flows * @vsi: VSI to be configured * * This function will only be called during the VF VSI setup. Upon successful * completion of package download, this function will configure default RSS * input sets for VF VSI. */ static void ice_vsi_set_vf_rss_flow_fld(struct ice_vsi *vsi) { struct ice_pf *pf = vsi->back; struct device *dev; int status; dev = ice_pf_to_dev(pf); if (ice_is_safe_mode(pf)) { dev_dbg(dev, "Advanced RSS disabled. Package download failed, vsi num = %d\n", vsi->vsi_num); return; } status = ice_add_avf_rss_cfg(&pf->hw, vsi->idx, ICE_DEFAULT_RSS_HENA); if (status) dev_dbg(dev, "ice_add_avf_rss_cfg failed for vsi = %d, error = %d\n", vsi->vsi_num, status); } /** * ice_vsi_set_rss_flow_fld - Sets RSS input set for different flows * @vsi: VSI to be configured * * This function will only be called after successful download package call * during initialization of PF. Since the downloaded package will erase the * RSS section, this function will configure RSS input sets for different * flow types. The last profile added has the highest priority, therefore 2 * tuple profiles (i.e. IPv4 src/dst) are added before 4 tuple profiles * (i.e. IPv4 src/dst TCP src/dst port). */ static void ice_vsi_set_rss_flow_fld(struct ice_vsi *vsi) { u16 vsi_handle = vsi->idx, vsi_num = vsi->vsi_num; struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; struct device *dev; int status; dev = ice_pf_to_dev(pf); if (ice_is_safe_mode(pf)) { dev_dbg(dev, "Advanced RSS disabled. Package download failed, vsi num = %d\n", vsi_num); return; } /* configure RSS for IPv4 with input set IP src/dst */ status = ice_add_rss_cfg(hw, vsi_handle, ICE_FLOW_HASH_IPV4, ICE_FLOW_SEG_HDR_IPV4); if (status) dev_dbg(dev, "ice_add_rss_cfg failed for ipv4 flow, vsi = %d, error = %d\n", vsi_num, status); /* configure RSS for IPv6 with input set IPv6 src/dst */ status = ice_add_rss_cfg(hw, vsi_handle, ICE_FLOW_HASH_IPV6, ICE_FLOW_SEG_HDR_IPV6); if (status) dev_dbg(dev, "ice_add_rss_cfg failed for ipv6 flow, vsi = %d, error = %d\n", vsi_num, status); /* configure RSS for tcp4 with input set IP src/dst, TCP src/dst */ status = ice_add_rss_cfg(hw, vsi_handle, ICE_HASH_TCP_IPV4, ICE_FLOW_SEG_HDR_TCP | ICE_FLOW_SEG_HDR_IPV4); if (status) dev_dbg(dev, "ice_add_rss_cfg failed for tcp4 flow, vsi = %d, error = %d\n", vsi_num, status); /* configure RSS for udp4 with input set IP src/dst, UDP src/dst */ status = ice_add_rss_cfg(hw, vsi_handle, ICE_HASH_UDP_IPV4, ICE_FLOW_SEG_HDR_UDP | ICE_FLOW_SEG_HDR_IPV4); if (status) dev_dbg(dev, "ice_add_rss_cfg failed for udp4 flow, vsi = %d, error = %d\n", vsi_num, status); /* configure RSS for sctp4 with input set IP src/dst */ status = ice_add_rss_cfg(hw, vsi_handle, ICE_FLOW_HASH_IPV4, ICE_FLOW_SEG_HDR_SCTP | ICE_FLOW_SEG_HDR_IPV4); if (status) dev_dbg(dev, "ice_add_rss_cfg failed for sctp4 flow, vsi = %d, error = %d\n", vsi_num, status); /* configure RSS for tcp6 with input set IPv6 src/dst, TCP src/dst */ status = ice_add_rss_cfg(hw, vsi_handle, ICE_HASH_TCP_IPV6, ICE_FLOW_SEG_HDR_TCP | ICE_FLOW_SEG_HDR_IPV6); if (status) dev_dbg(dev, "ice_add_rss_cfg failed for tcp6 flow, vsi = %d, error = %d\n", vsi_num, status); /* configure RSS for udp6 with input set IPv6 src/dst, UDP src/dst */ status = ice_add_rss_cfg(hw, vsi_handle, ICE_HASH_UDP_IPV6, ICE_FLOW_SEG_HDR_UDP | ICE_FLOW_SEG_HDR_IPV6); if (status) dev_dbg(dev, "ice_add_rss_cfg failed for udp6 flow, vsi = %d, error = %d\n", vsi_num, status); /* configure RSS for sctp6 with input set IPv6 src/dst */ status = ice_add_rss_cfg(hw, vsi_handle, ICE_FLOW_HASH_IPV6, ICE_FLOW_SEG_HDR_SCTP | ICE_FLOW_SEG_HDR_IPV6); if (status) dev_dbg(dev, "ice_add_rss_cfg failed for sctp6 flow, vsi = %d, error = %d\n", vsi_num, status); status = ice_add_rss_cfg(hw, vsi_handle, ICE_FLOW_HASH_ESP_SPI, ICE_FLOW_SEG_HDR_ESP); if (status) dev_dbg(dev, "ice_add_rss_cfg failed for esp/spi flow, vsi = %d, error = %d\n", vsi_num, status); } /** * ice_vsi_cfg_frame_size - setup max frame size and Rx buffer length * @vsi: VSI */ static void ice_vsi_cfg_frame_size(struct ice_vsi *vsi) { if (!vsi->netdev || test_bit(ICE_FLAG_LEGACY_RX, vsi->back->flags)) { vsi->max_frame = ICE_MAX_FRAME_LEGACY_RX; vsi->rx_buf_len = ICE_RXBUF_1664; #if (PAGE_SIZE < 8192) } else if (!ICE_2K_TOO_SMALL_WITH_PADDING && (vsi->netdev->mtu <= ETH_DATA_LEN)) { vsi->max_frame = ICE_RXBUF_1536 - NET_IP_ALIGN; vsi->rx_buf_len = ICE_RXBUF_1536 - NET_IP_ALIGN; #endif } else { vsi->max_frame = ICE_AQ_SET_MAC_FRAME_SIZE_MAX; vsi->rx_buf_len = ICE_RXBUF_3072; } } /** * ice_pf_state_is_nominal - checks the PF for nominal state * @pf: pointer to PF to check * * Check the PF's state for a collection of bits that would indicate * the PF is in a state that would inhibit normal operation for * driver functionality. * * Returns true if PF is in a nominal state, false otherwise */ bool ice_pf_state_is_nominal(struct ice_pf *pf) { DECLARE_BITMAP(check_bits, ICE_STATE_NBITS) = { 0 }; if (!pf) return false; bitmap_set(check_bits, 0, ICE_STATE_NOMINAL_CHECK_BITS); if (bitmap_intersects(pf->state, check_bits, ICE_STATE_NBITS)) return false; return true; } /** * ice_update_eth_stats - Update VSI-specific ethernet statistics counters * @vsi: the VSI to be updated */ void ice_update_eth_stats(struct ice_vsi *vsi) { struct ice_eth_stats *prev_es, *cur_es; struct ice_hw *hw = &vsi->back->hw; struct ice_pf *pf = vsi->back; u16 vsi_num = vsi->vsi_num; /* HW absolute index of a VSI */ prev_es = &vsi->eth_stats_prev; cur_es = &vsi->eth_stats; if (ice_is_reset_in_progress(pf->state)) vsi->stat_offsets_loaded = false; ice_stat_update40(hw, GLV_GORCL(vsi_num), vsi->stat_offsets_loaded, &prev_es->rx_bytes, &cur_es->rx_bytes); ice_stat_update40(hw, GLV_UPRCL(vsi_num), vsi->stat_offsets_loaded, &prev_es->rx_unicast, &cur_es->rx_unicast); ice_stat_update40(hw, GLV_MPRCL(vsi_num), vsi->stat_offsets_loaded, &prev_es->rx_multicast, &cur_es->rx_multicast); ice_stat_update40(hw, GLV_BPRCL(vsi_num), vsi->stat_offsets_loaded, &prev_es->rx_broadcast, &cur_es->rx_broadcast); ice_stat_update32(hw, GLV_RDPC(vsi_num), vsi->stat_offsets_loaded, &prev_es->rx_discards, &cur_es->rx_discards); ice_stat_update40(hw, GLV_GOTCL(vsi_num), vsi->stat_offsets_loaded, &prev_es->tx_bytes, &cur_es->tx_bytes); ice_stat_update40(hw, GLV_UPTCL(vsi_num), vsi->stat_offsets_loaded, &prev_es->tx_unicast, &cur_es->tx_unicast); ice_stat_update40(hw, GLV_MPTCL(vsi_num), vsi->stat_offsets_loaded, &prev_es->tx_multicast, &cur_es->tx_multicast); ice_stat_update40(hw, GLV_BPTCL(vsi_num), vsi->stat_offsets_loaded, &prev_es->tx_broadcast, &cur_es->tx_broadcast); ice_stat_update32(hw, GLV_TEPC(vsi_num), vsi->stat_offsets_loaded, &prev_es->tx_errors, &cur_es->tx_errors); vsi->stat_offsets_loaded = true; } /** * ice_write_qrxflxp_cntxt - write/configure QRXFLXP_CNTXT register * @hw: HW pointer * @pf_q: index of the Rx queue in the PF's queue space * @rxdid: flexible descriptor RXDID * @prio: priority for the RXDID for this queue * @ena_ts: true to enable timestamp and false to disable timestamp */ void ice_write_qrxflxp_cntxt(struct ice_hw *hw, u16 pf_q, u32 rxdid, u32 prio, bool ena_ts) { int regval = rd32(hw, QRXFLXP_CNTXT(pf_q)); /* clear any previous values */ regval &= ~(QRXFLXP_CNTXT_RXDID_IDX_M | QRXFLXP_CNTXT_RXDID_PRIO_M | QRXFLXP_CNTXT_TS_M); regval |= (rxdid << QRXFLXP_CNTXT_RXDID_IDX_S) & QRXFLXP_CNTXT_RXDID_IDX_M; regval |= (prio << QRXFLXP_CNTXT_RXDID_PRIO_S) & QRXFLXP_CNTXT_RXDID_PRIO_M; if (ena_ts) /* Enable TimeSync on this queue */ regval |= QRXFLXP_CNTXT_TS_M; wr32(hw, QRXFLXP_CNTXT(pf_q), regval); } int ice_vsi_cfg_single_rxq(struct ice_vsi *vsi, u16 q_idx) { if (q_idx >= vsi->num_rxq) return -EINVAL; return ice_vsi_cfg_rxq(vsi->rx_rings[q_idx]); } int ice_vsi_cfg_single_txq(struct ice_vsi *vsi, struct ice_tx_ring **tx_rings, u16 q_idx) { struct ice_aqc_add_tx_qgrp *qg_buf; int err; if (q_idx >= vsi->alloc_txq || !tx_rings || !tx_rings[q_idx]) return -EINVAL; qg_buf = kzalloc(struct_size(qg_buf, txqs, 1), GFP_KERNEL); if (!qg_buf) return -ENOMEM; qg_buf->num_txqs = 1; err = ice_vsi_cfg_txq(vsi, tx_rings[q_idx], qg_buf); kfree(qg_buf); return err; } /** * ice_vsi_cfg_rxqs - Configure the VSI for Rx * @vsi: the VSI being configured * * Return 0 on success and a negative value on error * Configure the Rx VSI for operation. */ int ice_vsi_cfg_rxqs(struct ice_vsi *vsi) { u16 i; if (vsi->type == ICE_VSI_VF) goto setup_rings; ice_vsi_cfg_frame_size(vsi); setup_rings: /* set up individual rings */ ice_for_each_rxq(vsi, i) { int err = ice_vsi_cfg_rxq(vsi->rx_rings[i]); if (err) return err; } return 0; } /** * ice_vsi_cfg_txqs - Configure the VSI for Tx * @vsi: the VSI being configured * @rings: Tx ring array to be configured * @count: number of Tx ring array elements * * Return 0 on success and a negative value on error * Configure the Tx VSI for operation. */ static int ice_vsi_cfg_txqs(struct ice_vsi *vsi, struct ice_tx_ring **rings, u16 count) { struct ice_aqc_add_tx_qgrp *qg_buf; u16 q_idx = 0; int err = 0; qg_buf = kzalloc(struct_size(qg_buf, txqs, 1), GFP_KERNEL); if (!qg_buf) return -ENOMEM; qg_buf->num_txqs = 1; for (q_idx = 0; q_idx < count; q_idx++) { err = ice_vsi_cfg_txq(vsi, rings[q_idx], qg_buf); if (err) goto err_cfg_txqs; } err_cfg_txqs: kfree(qg_buf); return err; } /** * ice_vsi_cfg_lan_txqs - Configure the VSI for Tx * @vsi: the VSI being configured * * Return 0 on success and a negative value on error * Configure the Tx VSI for operation. */ int ice_vsi_cfg_lan_txqs(struct ice_vsi *vsi) { return ice_vsi_cfg_txqs(vsi, vsi->tx_rings, vsi->num_txq); } /** * ice_vsi_cfg_xdp_txqs - Configure Tx queues dedicated for XDP in given VSI * @vsi: the VSI being configured * * Return 0 on success and a negative value on error * Configure the Tx queues dedicated for XDP in given VSI for operation. */ int ice_vsi_cfg_xdp_txqs(struct ice_vsi *vsi) { int ret; int i; ret = ice_vsi_cfg_txqs(vsi, vsi->xdp_rings, vsi->num_xdp_txq); if (ret) return ret; ice_for_each_rxq(vsi, i) ice_tx_xsk_pool(vsi, i); return 0; } /** * ice_intrl_usec_to_reg - convert interrupt rate limit to register value * @intrl: interrupt rate limit in usecs * @gran: interrupt rate limit granularity in usecs * * This function converts a decimal interrupt rate limit in usecs to the format * expected by firmware. */ static u32 ice_intrl_usec_to_reg(u8 intrl, u8 gran) { u32 val = intrl / gran; if (val) return val | GLINT_RATE_INTRL_ENA_M; return 0; } /** * ice_write_intrl - write throttle rate limit to interrupt specific register * @q_vector: pointer to interrupt specific structure * @intrl: throttle rate limit in microseconds to write */ void ice_write_intrl(struct ice_q_vector *q_vector, u8 intrl) { struct ice_hw *hw = &q_vector->vsi->back->hw; wr32(hw, GLINT_RATE(q_vector->reg_idx), ice_intrl_usec_to_reg(intrl, ICE_INTRL_GRAN_ABOVE_25)); } static struct ice_q_vector *ice_pull_qvec_from_rc(struct ice_ring_container *rc) { switch (rc->type) { case ICE_RX_CONTAINER: if (rc->rx_ring) return rc->rx_ring->q_vector; break; case ICE_TX_CONTAINER: if (rc->tx_ring) return rc->tx_ring->q_vector; break; default: break; } return NULL; } /** * __ice_write_itr - write throttle rate to register * @q_vector: pointer to interrupt data structure * @rc: pointer to ring container * @itr: throttle rate in microseconds to write */ static void __ice_write_itr(struct ice_q_vector *q_vector, struct ice_ring_container *rc, u16 itr) { struct ice_hw *hw = &q_vector->vsi->back->hw; wr32(hw, GLINT_ITR(rc->itr_idx, q_vector->reg_idx), ITR_REG_ALIGN(itr) >> ICE_ITR_GRAN_S); } /** * ice_write_itr - write throttle rate to queue specific register * @rc: pointer to ring container * @itr: throttle rate in microseconds to write */ void ice_write_itr(struct ice_ring_container *rc, u16 itr) { struct ice_q_vector *q_vector; q_vector = ice_pull_qvec_from_rc(rc); if (!q_vector) return; __ice_write_itr(q_vector, rc, itr); } /** * ice_set_q_vector_intrl - set up interrupt rate limiting * @q_vector: the vector to be configured * * Interrupt rate limiting is local to the vector, not per-queue so we must * detect if either ring container has dynamic moderation enabled to decide * what to set the interrupt rate limit to via INTRL settings. In the case that * dynamic moderation is disabled on both, write the value with the cached * setting to make sure INTRL register matches the user visible value. */ void ice_set_q_vector_intrl(struct ice_q_vector *q_vector) { if (ITR_IS_DYNAMIC(&q_vector->tx) || ITR_IS_DYNAMIC(&q_vector->rx)) { /* in the case of dynamic enabled, cap each vector to no more * than (4 us) 250,000 ints/sec, which allows low latency * but still less than 500,000 interrupts per second, which * reduces CPU a bit in the case of the lowest latency * setting. The 4 here is a value in microseconds. */ ice_write_intrl(q_vector, 4); } else { ice_write_intrl(q_vector, q_vector->intrl); } } /** * ice_vsi_cfg_msix - MSIX mode Interrupt Config in the HW * @vsi: the VSI being configured * * This configures MSIX mode interrupts for the PF VSI, and should not be used * for the VF VSI. */ void ice_vsi_cfg_msix(struct ice_vsi *vsi) { struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; u16 txq = 0, rxq = 0; int i, q; ice_for_each_q_vector(vsi, i) { struct ice_q_vector *q_vector = vsi->q_vectors[i]; u16 reg_idx = q_vector->reg_idx; ice_cfg_itr(hw, q_vector); /* Both Transmit Queue Interrupt Cause Control register * and Receive Queue Interrupt Cause control register * expects MSIX_INDX field to be the vector index * within the function space and not the absolute * vector index across PF or across device. * For SR-IOV VF VSIs queue vector index always starts * with 1 since first vector index(0) is used for OICR * in VF space. Since VMDq and other PF VSIs are within * the PF function space, use the vector index that is * tracked for this PF. */ for (q = 0; q < q_vector->num_ring_tx; q++) { ice_cfg_txq_interrupt(vsi, txq, reg_idx, q_vector->tx.itr_idx); txq++; } for (q = 0; q < q_vector->num_ring_rx; q++) { ice_cfg_rxq_interrupt(vsi, rxq, reg_idx, q_vector->rx.itr_idx); rxq++; } } } /** * ice_vsi_start_all_rx_rings - start/enable all of a VSI's Rx rings * @vsi: the VSI whose rings are to be enabled * * Returns 0 on success and a negative value on error */ int ice_vsi_start_all_rx_rings(struct ice_vsi *vsi) { return ice_vsi_ctrl_all_rx_rings(vsi, true); } /** * ice_vsi_stop_all_rx_rings - stop/disable all of a VSI's Rx rings * @vsi: the VSI whose rings are to be disabled * * Returns 0 on success and a negative value on error */ int ice_vsi_stop_all_rx_rings(struct ice_vsi *vsi) { return ice_vsi_ctrl_all_rx_rings(vsi, false); } /** * ice_vsi_stop_tx_rings - Disable Tx rings * @vsi: the VSI being configured * @rst_src: reset source * @rel_vmvf_num: Relative ID of VF/VM * @rings: Tx ring array to be stopped * @count: number of Tx ring array elements */ static int ice_vsi_stop_tx_rings(struct ice_vsi *vsi, enum ice_disq_rst_src rst_src, u16 rel_vmvf_num, struct ice_tx_ring **rings, u16 count) { u16 q_idx; if (vsi->num_txq > ICE_LAN_TXQ_MAX_QDIS) return -EINVAL; for (q_idx = 0; q_idx < count; q_idx++) { struct ice_txq_meta txq_meta = { }; int status; if (!rings || !rings[q_idx]) return -EINVAL; ice_fill_txq_meta(vsi, rings[q_idx], &txq_meta); status = ice_vsi_stop_tx_ring(vsi, rst_src, rel_vmvf_num, rings[q_idx], &txq_meta); if (status) return status; } return 0; } /** * ice_vsi_stop_lan_tx_rings - Disable LAN Tx rings * @vsi: the VSI being configured * @rst_src: reset source * @rel_vmvf_num: Relative ID of VF/VM */ int ice_vsi_stop_lan_tx_rings(struct ice_vsi *vsi, enum ice_disq_rst_src rst_src, u16 rel_vmvf_num) { return ice_vsi_stop_tx_rings(vsi, rst_src, rel_vmvf_num, vsi->tx_rings, vsi->num_txq); } /** * ice_vsi_stop_xdp_tx_rings - Disable XDP Tx rings * @vsi: the VSI being configured */ int ice_vsi_stop_xdp_tx_rings(struct ice_vsi *vsi) { return ice_vsi_stop_tx_rings(vsi, ICE_NO_RESET, 0, vsi->xdp_rings, vsi->num_xdp_txq); } /** * ice_vsi_is_rx_queue_active * @vsi: the VSI being configured * * Return true if at least one queue is active. */ bool ice_vsi_is_rx_queue_active(struct ice_vsi *vsi) { struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; int i; ice_for_each_rxq(vsi, i) { u32 rx_reg; int pf_q; pf_q = vsi->rxq_map[i]; rx_reg = rd32(hw, QRX_CTRL(pf_q)); if (rx_reg & QRX_CTRL_QENA_STAT_M) return true; } return false; } static void ice_vsi_set_tc_cfg(struct ice_vsi *vsi) { if (!test_bit(ICE_FLAG_DCB_ENA, vsi->back->flags)) { vsi->tc_cfg.ena_tc = ICE_DFLT_TRAFFIC_CLASS; vsi->tc_cfg.numtc = 1; return; } /* set VSI TC information based on DCB config */ ice_vsi_set_dcb_tc_cfg(vsi); } /** * ice_cfg_sw_lldp - Config switch rules for LLDP packet handling * @vsi: the VSI being configured * @tx: bool to determine Tx or Rx rule * @create: bool to determine create or remove Rule */ void ice_cfg_sw_lldp(struct ice_vsi *vsi, bool tx, bool create) { int (*eth_fltr)(struct ice_vsi *v, u16 type, u16 flag, enum ice_sw_fwd_act_type act); struct ice_pf *pf = vsi->back; struct device *dev; int status; dev = ice_pf_to_dev(pf); eth_fltr = create ? ice_fltr_add_eth : ice_fltr_remove_eth; if (tx) { status = eth_fltr(vsi, ETH_P_LLDP, ICE_FLTR_TX, ICE_DROP_PACKET); } else { if (ice_fw_supports_lldp_fltr_ctrl(&pf->hw)) { status = ice_lldp_fltr_add_remove(&pf->hw, vsi->vsi_num, create); } else { status = eth_fltr(vsi, ETH_P_LLDP, ICE_FLTR_RX, ICE_FWD_TO_VSI); } } if (status) dev_dbg(dev, "Fail %s %s LLDP rule on VSI %i error: %d\n", create ? "adding" : "removing", tx ? "TX" : "RX", vsi->vsi_num, status); } /** * ice_set_agg_vsi - sets up scheduler aggregator node and move VSI into it * @vsi: pointer to the VSI * * This function will allocate new scheduler aggregator now if needed and will * move specified VSI into it. */ static void ice_set_agg_vsi(struct ice_vsi *vsi) { struct device *dev = ice_pf_to_dev(vsi->back); struct ice_agg_node *agg_node_iter = NULL; u32 agg_id = ICE_INVALID_AGG_NODE_ID; struct ice_agg_node *agg_node = NULL; int node_offset, max_agg_nodes = 0; struct ice_port_info *port_info; struct ice_pf *pf = vsi->back; u32 agg_node_id_start = 0; int status; /* create (as needed) scheduler aggregator node and move VSI into * corresponding aggregator node * - PF aggregator node to contains VSIs of type _PF and _CTRL * - VF aggregator nodes will contain VF VSI */ port_info = pf->hw.port_info; if (!port_info) return; switch (vsi->type) { case ICE_VSI_CTRL: case ICE_VSI_CHNL: case ICE_VSI_LB: case ICE_VSI_PF: case ICE_VSI_SWITCHDEV_CTRL: max_agg_nodes = ICE_MAX_PF_AGG_NODES; agg_node_id_start = ICE_PF_AGG_NODE_ID_START; agg_node_iter = &pf->pf_agg_node[0]; break; case ICE_VSI_VF: /* user can create 'n' VFs on a given PF, but since max children * per aggregator node can be only 64. Following code handles * aggregator(s) for VF VSIs, either selects a agg_node which * was already created provided num_vsis < 64, otherwise * select next available node, which will be created */ max_agg_nodes = ICE_MAX_VF_AGG_NODES; agg_node_id_start = ICE_VF_AGG_NODE_ID_START; agg_node_iter = &pf->vf_agg_node[0]; break; default: /* other VSI type, handle later if needed */ dev_dbg(dev, "unexpected VSI type %s\n", ice_vsi_type_str(vsi->type)); return; } /* find the appropriate aggregator node */ for (node_offset = 0; node_offset < max_agg_nodes; node_offset++) { /* see if we can find space in previously created * node if num_vsis < 64, otherwise skip */ if (agg_node_iter->num_vsis && agg_node_iter->num_vsis == ICE_MAX_VSIS_IN_AGG_NODE) { agg_node_iter++; continue; } if (agg_node_iter->valid && agg_node_iter->agg_id != ICE_INVALID_AGG_NODE_ID) { agg_id = agg_node_iter->agg_id; agg_node = agg_node_iter; break; } /* find unclaimed agg_id */ if (agg_node_iter->agg_id == ICE_INVALID_AGG_NODE_ID) { agg_id = node_offset + agg_node_id_start; agg_node = agg_node_iter; break; } /* move to next agg_node */ agg_node_iter++; } if (!agg_node) return; /* if selected aggregator node was not created, create it */ if (!agg_node->valid) { status = ice_cfg_agg(port_info, agg_id, ICE_AGG_TYPE_AGG, (u8)vsi->tc_cfg.ena_tc); if (status) { dev_err(dev, "unable to create aggregator node with agg_id %u\n", agg_id); return; } /* aggregator node is created, store the needed info */ agg_node->valid = true; agg_node->agg_id = agg_id; } /* move VSI to corresponding aggregator node */ status = ice_move_vsi_to_agg(port_info, agg_id, vsi->idx, (u8)vsi->tc_cfg.ena_tc); if (status) { dev_err(dev, "unable to move VSI idx %u into aggregator %u node", vsi->idx, agg_id); return; } /* keep active children count for aggregator node */ agg_node->num_vsis++; /* cache the 'agg_id' in VSI, so that after reset - VSI will be moved * to aggregator node */ vsi->agg_node = agg_node; dev_dbg(dev, "successfully moved VSI idx %u tc_bitmap 0x%x) into aggregator node %d which has num_vsis %u\n", vsi->idx, vsi->tc_cfg.ena_tc, vsi->agg_node->agg_id, vsi->agg_node->num_vsis); } static int ice_vsi_cfg_tc_lan(struct ice_pf *pf, struct ice_vsi *vsi) { u16 max_txqs[ICE_MAX_TRAFFIC_CLASS] = { 0 }; struct device *dev = ice_pf_to_dev(pf); int ret, i; /* configure VSI nodes based on number of queues and TC's */ ice_for_each_traffic_class(i) { if (!(vsi->tc_cfg.ena_tc & BIT(i))) continue; if (vsi->type == ICE_VSI_CHNL) { if (!vsi->alloc_txq && vsi->num_txq) max_txqs[i] = vsi->num_txq; else max_txqs[i] = pf->num_lan_tx; } else { max_txqs[i] = vsi->alloc_txq; } } dev_dbg(dev, "vsi->tc_cfg.ena_tc = %d\n", vsi->tc_cfg.ena_tc); ret = ice_cfg_vsi_lan(vsi->port_info, vsi->idx, vsi->tc_cfg.ena_tc, max_txqs); if (ret) { dev_err(dev, "VSI %d failed lan queue config, error %d\n", vsi->vsi_num, ret); return ret; } return 0; } /** * ice_vsi_cfg_def - configure default VSI based on the type * @vsi: pointer to VSI * @params: the parameters to configure this VSI with */ static int ice_vsi_cfg_def(struct ice_vsi *vsi, struct ice_vsi_cfg_params *params) { struct device *dev = ice_pf_to_dev(vsi->back); struct ice_pf *pf = vsi->back; int ret; vsi->vsw = pf->first_sw; ret = ice_vsi_alloc_def(vsi, params->ch); if (ret) return ret; /* allocate memory for Tx/Rx ring stat pointers */ ret = ice_vsi_alloc_stat_arrays(vsi); if (ret) goto unroll_vsi_alloc; ice_alloc_fd_res(vsi); ret = ice_vsi_get_qs(vsi); if (ret) { dev_err(dev, "Failed to allocate queues. vsi->idx = %d\n", vsi->idx); goto unroll_vsi_alloc_stat; } /* set RSS capabilities */ ice_vsi_set_rss_params(vsi); /* set TC configuration */ ice_vsi_set_tc_cfg(vsi); /* create the VSI */ ret = ice_vsi_init(vsi, params->flags); if (ret) goto unroll_get_qs; ice_vsi_init_vlan_ops(vsi); switch (vsi->type) { case ICE_VSI_CTRL: case ICE_VSI_SWITCHDEV_CTRL: case ICE_VSI_PF: ret = ice_vsi_alloc_q_vectors(vsi); if (ret) goto unroll_vsi_init; ret = ice_vsi_alloc_rings(vsi); if (ret) goto unroll_vector_base; ret = ice_vsi_alloc_ring_stats(vsi); if (ret) goto unroll_vector_base; ice_vsi_map_rings_to_vectors(vsi); vsi->stat_offsets_loaded = false; if (ice_is_xdp_ena_vsi(vsi)) { ret = ice_vsi_determine_xdp_res(vsi); if (ret) goto unroll_vector_base; ret = ice_prepare_xdp_rings(vsi, vsi->xdp_prog); if (ret) goto unroll_vector_base; } /* ICE_VSI_CTRL does not need RSS so skip RSS processing */ if (vsi->type != ICE_VSI_CTRL) /* Do not exit if configuring RSS had an issue, at * least receive traffic on first queue. Hence no * need to capture return value */ if (test_bit(ICE_FLAG_RSS_ENA, pf->flags)) { ice_vsi_cfg_rss_lut_key(vsi); ice_vsi_set_rss_flow_fld(vsi); } ice_init_arfs(vsi); break; case ICE_VSI_CHNL: if (test_bit(ICE_FLAG_RSS_ENA, pf->flags)) { ice_vsi_cfg_rss_lut_key(vsi); ice_vsi_set_rss_flow_fld(vsi); } break; case ICE_VSI_VF: /* VF driver will take care of creating netdev for this type and * map queues to vectors through Virtchnl, PF driver only * creates a VSI and corresponding structures for bookkeeping * purpose */ ret = ice_vsi_alloc_q_vectors(vsi); if (ret) goto unroll_vsi_init; ret = ice_vsi_alloc_rings(vsi); if (ret) goto unroll_alloc_q_vector; ret = ice_vsi_alloc_ring_stats(vsi); if (ret) goto unroll_vector_base; vsi->stat_offsets_loaded = false; /* Do not exit if configuring RSS had an issue, at least * receive traffic on first queue. Hence no need to capture * return value */ if (test_bit(ICE_FLAG_RSS_ENA, pf->flags)) { ice_vsi_cfg_rss_lut_key(vsi); ice_vsi_set_vf_rss_flow_fld(vsi); } break; case ICE_VSI_LB: ret = ice_vsi_alloc_rings(vsi); if (ret) goto unroll_vsi_init; ret = ice_vsi_alloc_ring_stats(vsi); if (ret) goto unroll_vector_base; break; default: /* clean up the resources and exit */ ret = -EINVAL; goto unroll_vsi_init; } return 0; unroll_vector_base: /* reclaim SW interrupts back to the common pool */ unroll_alloc_q_vector: ice_vsi_free_q_vectors(vsi); unroll_vsi_init: ice_vsi_delete_from_hw(vsi); unroll_get_qs: ice_vsi_put_qs(vsi); unroll_vsi_alloc_stat: ice_vsi_free_stats(vsi); unroll_vsi_alloc: ice_vsi_free_arrays(vsi); return ret; } /** * ice_vsi_cfg - configure a previously allocated VSI * @vsi: pointer to VSI * @params: parameters used to configure this VSI */ int ice_vsi_cfg(struct ice_vsi *vsi, struct ice_vsi_cfg_params *params) { struct ice_pf *pf = vsi->back; int ret; if (WARN_ON(params->type == ICE_VSI_VF && !params->vf)) return -EINVAL; vsi->type = params->type; vsi->port_info = params->pi; /* For VSIs which don't have a connected VF, this will be NULL */ vsi->vf = params->vf; ret = ice_vsi_cfg_def(vsi, params); if (ret) return ret; ret = ice_vsi_cfg_tc_lan(vsi->back, vsi); if (ret) ice_vsi_decfg(vsi); if (vsi->type == ICE_VSI_CTRL) { if (vsi->vf) { WARN_ON(vsi->vf->ctrl_vsi_idx != ICE_NO_VSI); vsi->vf->ctrl_vsi_idx = vsi->idx; } else { WARN_ON(pf->ctrl_vsi_idx != ICE_NO_VSI); pf->ctrl_vsi_idx = vsi->idx; } } return ret; } /** * ice_vsi_decfg - remove all VSI configuration * @vsi: pointer to VSI */ void ice_vsi_decfg(struct ice_vsi *vsi) { struct ice_pf *pf = vsi->back; int err; /* The Rx rule will only exist to remove if the LLDP FW * engine is currently stopped */ if (!ice_is_safe_mode(pf) && vsi->type == ICE_VSI_PF && !test_bit(ICE_FLAG_FW_LLDP_AGENT, pf->flags)) ice_cfg_sw_lldp(vsi, false, false); ice_rm_vsi_lan_cfg(vsi->port_info, vsi->idx); err = ice_rm_vsi_rdma_cfg(vsi->port_info, vsi->idx); if (err) dev_err(ice_pf_to_dev(pf), "Failed to remove RDMA scheduler config for VSI %u, err %d\n", vsi->vsi_num, err); if (ice_is_xdp_ena_vsi(vsi)) /* return value check can be skipped here, it always returns * 0 if reset is in progress */ ice_destroy_xdp_rings(vsi); ice_vsi_clear_rings(vsi); ice_vsi_free_q_vectors(vsi); ice_vsi_put_qs(vsi); ice_vsi_free_arrays(vsi); /* SR-IOV determines needed MSIX resources all at once instead of per * VSI since when VFs are spawned we know how many VFs there are and how * many interrupts each VF needs. SR-IOV MSIX resources are also * cleared in the same manner. */ if (vsi->type == ICE_VSI_VF && vsi->agg_node && vsi->agg_node->valid) vsi->agg_node->num_vsis--; if (vsi->agg_node) { vsi->agg_node->valid = false; vsi->agg_node->agg_id = 0; } } /** * ice_vsi_setup - Set up a VSI by a given type * @pf: board private structure * @params: parameters to use when creating the VSI * * This allocates the sw VSI structure and its queue resources. * * Returns pointer to the successfully allocated and configured VSI sw struct on * success, NULL on failure. */ struct ice_vsi * ice_vsi_setup(struct ice_pf *pf, struct ice_vsi_cfg_params *params) { struct device *dev = ice_pf_to_dev(pf); struct ice_vsi *vsi; int ret; /* ice_vsi_setup can only initialize a new VSI, and we must have * a port_info structure for it. */ if (WARN_ON(!(params->flags & ICE_VSI_FLAG_INIT)) || WARN_ON(!params->pi)) return NULL; vsi = ice_vsi_alloc(pf); if (!vsi) { dev_err(dev, "could not allocate VSI\n"); return NULL; } ret = ice_vsi_cfg(vsi, params); if (ret) goto err_vsi_cfg; /* Add switch rule to drop all Tx Flow Control Frames, of look up * type ETHERTYPE from VSIs, and restrict malicious VF from sending * out PAUSE or PFC frames. If enabled, FW can still send FC frames. * The rule is added once for PF VSI in order to create appropriate * recipe, since VSI/VSI list is ignored with drop action... * Also add rules to handle LLDP Tx packets. Tx LLDP packets need to * be dropped so that VFs cannot send LLDP packets to reconfig DCB * settings in the HW. */ if (!ice_is_safe_mode(pf) && vsi->type == ICE_VSI_PF) { ice_fltr_add_eth(vsi, ETH_P_PAUSE, ICE_FLTR_TX, ICE_DROP_PACKET); ice_cfg_sw_lldp(vsi, true, true); } if (!vsi->agg_node) ice_set_agg_vsi(vsi); return vsi; err_vsi_cfg: ice_vsi_free(vsi); return NULL; } /** * ice_vsi_release_msix - Clear the queue to Interrupt mapping in HW * @vsi: the VSI being cleaned up */ static void ice_vsi_release_msix(struct ice_vsi *vsi) { struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; u32 txq = 0; u32 rxq = 0; int i, q; ice_for_each_q_vector(vsi, i) { struct ice_q_vector *q_vector = vsi->q_vectors[i]; ice_write_intrl(q_vector, 0); for (q = 0; q < q_vector->num_ring_tx; q++) { ice_write_itr(&q_vector->tx, 0); wr32(hw, QINT_TQCTL(vsi->txq_map[txq]), 0); if (ice_is_xdp_ena_vsi(vsi)) { u32 xdp_txq = txq + vsi->num_xdp_txq; wr32(hw, QINT_TQCTL(vsi->txq_map[xdp_txq]), 0); } txq++; } for (q = 0; q < q_vector->num_ring_rx; q++) { ice_write_itr(&q_vector->rx, 0); wr32(hw, QINT_RQCTL(vsi->rxq_map[rxq]), 0); rxq++; } } ice_flush(hw); } /** * ice_vsi_free_irq - Free the IRQ association with the OS * @vsi: the VSI being configured */ void ice_vsi_free_irq(struct ice_vsi *vsi) { struct ice_pf *pf = vsi->back; int i; if (!vsi->q_vectors || !vsi->irqs_ready) return; ice_vsi_release_msix(vsi); if (vsi->type == ICE_VSI_VF) return; vsi->irqs_ready = false; ice_free_cpu_rx_rmap(vsi); ice_for_each_q_vector(vsi, i) { int irq_num; irq_num = vsi->q_vectors[i]->irq.virq; /* free only the irqs that were actually requested */ if (!vsi->q_vectors[i] || !(vsi->q_vectors[i]->num_ring_tx || vsi->q_vectors[i]->num_ring_rx)) continue; /* clear the affinity notifier in the IRQ descriptor */ if (!IS_ENABLED(CONFIG_RFS_ACCEL)) irq_set_affinity_notifier(irq_num, NULL); /* clear the affinity_mask in the IRQ descriptor */ irq_set_affinity_hint(irq_num, NULL); synchronize_irq(irq_num); devm_free_irq(ice_pf_to_dev(pf), irq_num, vsi->q_vectors[i]); } } /** * ice_vsi_free_tx_rings - Free Tx resources for VSI queues * @vsi: the VSI having resources freed */ void ice_vsi_free_tx_rings(struct ice_vsi *vsi) { int i; if (!vsi->tx_rings) return; ice_for_each_txq(vsi, i) if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc) ice_free_tx_ring(vsi->tx_rings[i]); } /** * ice_vsi_free_rx_rings - Free Rx resources for VSI queues * @vsi: the VSI having resources freed */ void ice_vsi_free_rx_rings(struct ice_vsi *vsi) { int i; if (!vsi->rx_rings) return; ice_for_each_rxq(vsi, i) if (vsi->rx_rings[i] && vsi->rx_rings[i]->desc) ice_free_rx_ring(vsi->rx_rings[i]); } /** * ice_vsi_close - Shut down a VSI * @vsi: the VSI being shut down */ void ice_vsi_close(struct ice_vsi *vsi) { if (!test_and_set_bit(ICE_VSI_DOWN, vsi->state)) ice_down(vsi); ice_vsi_free_irq(vsi); ice_vsi_free_tx_rings(vsi); ice_vsi_free_rx_rings(vsi); } /** * ice_ena_vsi - resume a VSI * @vsi: the VSI being resume * @locked: is the rtnl_lock already held */ int ice_ena_vsi(struct ice_vsi *vsi, bool locked) { int err = 0; if (!test_bit(ICE_VSI_NEEDS_RESTART, vsi->state)) return 0; clear_bit(ICE_VSI_NEEDS_RESTART, vsi->state); if (vsi->netdev && vsi->type == ICE_VSI_PF) { if (netif_running(vsi->netdev)) { if (!locked) rtnl_lock(); err = ice_open_internal(vsi->netdev); if (!locked) rtnl_unlock(); } } else if (vsi->type == ICE_VSI_CTRL) { err = ice_vsi_open_ctrl(vsi); } return err; } /** * ice_dis_vsi - pause a VSI * @vsi: the VSI being paused * @locked: is the rtnl_lock already held */ void ice_dis_vsi(struct ice_vsi *vsi, bool locked) { if (test_bit(ICE_VSI_DOWN, vsi->state)) return; set_bit(ICE_VSI_NEEDS_RESTART, vsi->state); if (vsi->type == ICE_VSI_PF && vsi->netdev) { if (netif_running(vsi->netdev)) { if (!locked) rtnl_lock(); ice_vsi_close(vsi); if (!locked) rtnl_unlock(); } else { ice_vsi_close(vsi); } } else if (vsi->type == ICE_VSI_CTRL || vsi->type == ICE_VSI_SWITCHDEV_CTRL) { ice_vsi_close(vsi); } } /** * ice_vsi_dis_irq - Mask off queue interrupt generation on the VSI * @vsi: the VSI being un-configured */ void ice_vsi_dis_irq(struct ice_vsi *vsi) { struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; u32 val; int i; /* disable interrupt causation from each queue */ if (vsi->tx_rings) { ice_for_each_txq(vsi, i) { if (vsi->tx_rings[i]) { u16 reg; reg = vsi->tx_rings[i]->reg_idx; val = rd32(hw, QINT_TQCTL(reg)); val &= ~QINT_TQCTL_CAUSE_ENA_M; wr32(hw, QINT_TQCTL(reg), val); } } } if (vsi->rx_rings) { ice_for_each_rxq(vsi, i) { if (vsi->rx_rings[i]) { u16 reg; reg = vsi->rx_rings[i]->reg_idx; val = rd32(hw, QINT_RQCTL(reg)); val &= ~QINT_RQCTL_CAUSE_ENA_M; wr32(hw, QINT_RQCTL(reg), val); } } } /* disable each interrupt */ ice_for_each_q_vector(vsi, i) { if (!vsi->q_vectors[i]) continue; wr32(hw, GLINT_DYN_CTL(vsi->q_vectors[i]->reg_idx), 0); } ice_flush(hw); /* don't call synchronize_irq() for VF's from the host */ if (vsi->type == ICE_VSI_VF) return; ice_for_each_q_vector(vsi, i) synchronize_irq(vsi->q_vectors[i]->irq.virq); } /** * ice_vsi_release - Delete a VSI and free its resources * @vsi: the VSI being removed * * Returns 0 on success or < 0 on error */ int ice_vsi_release(struct ice_vsi *vsi) { struct ice_pf *pf; if (!vsi->back) return -ENODEV; pf = vsi->back; if (test_bit(ICE_FLAG_RSS_ENA, pf->flags)) ice_rss_clean(vsi); ice_vsi_close(vsi); ice_vsi_decfg(vsi); /* retain SW VSI data structure since it is needed to unregister and * free VSI netdev when PF is not in reset recovery pending state,\ * for ex: during rmmod. */ if (!ice_is_reset_in_progress(pf->state)) ice_vsi_delete(vsi); return 0; } /** * ice_vsi_rebuild_get_coalesce - get coalesce from all q_vectors * @vsi: VSI connected with q_vectors * @coalesce: array of struct with stored coalesce * * Returns array size. */ static int ice_vsi_rebuild_get_coalesce(struct ice_vsi *vsi, struct ice_coalesce_stored *coalesce) { int i; ice_for_each_q_vector(vsi, i) { struct ice_q_vector *q_vector = vsi->q_vectors[i]; coalesce[i].itr_tx = q_vector->tx.itr_settings; coalesce[i].itr_rx = q_vector->rx.itr_settings; coalesce[i].intrl = q_vector->intrl; if (i < vsi->num_txq) coalesce[i].tx_valid = true; if (i < vsi->num_rxq) coalesce[i].rx_valid = true; } return vsi->num_q_vectors; } /** * ice_vsi_rebuild_set_coalesce - set coalesce from earlier saved arrays * @vsi: VSI connected with q_vectors * @coalesce: pointer to array of struct with stored coalesce * @size: size of coalesce array * * Before this function, ice_vsi_rebuild_get_coalesce should be called to save * ITR params in arrays. If size is 0 or coalesce wasn't stored set coalesce * to default value. */ static void ice_vsi_rebuild_set_coalesce(struct ice_vsi *vsi, struct ice_coalesce_stored *coalesce, int size) { struct ice_ring_container *rc; int i; if ((size && !coalesce) || !vsi) return; /* There are a couple of cases that have to be handled here: * 1. The case where the number of queue vectors stays the same, but * the number of Tx or Rx rings changes (the first for loop) * 2. The case where the number of queue vectors increased (the * second for loop) */ for (i = 0; i < size && i < vsi->num_q_vectors; i++) { /* There are 2 cases to handle here and they are the same for * both Tx and Rx: * if the entry was valid previously (coalesce[i].[tr]x_valid * and the loop variable is less than the number of rings * allocated, then write the previous values * * if the entry was not valid previously, but the number of * rings is less than are allocated (this means the number of * rings increased from previously), then write out the * values in the first element * * Also, always write the ITR, even if in ITR_IS_DYNAMIC * as there is no harm because the dynamic algorithm * will just overwrite. */ if (i < vsi->alloc_rxq && coalesce[i].rx_valid) { rc = &vsi->q_vectors[i]->rx; rc->itr_settings = coalesce[i].itr_rx; ice_write_itr(rc, rc->itr_setting); } else if (i < vsi->alloc_rxq) { rc = &vsi->q_vectors[i]->rx; rc->itr_settings = coalesce[0].itr_rx; ice_write_itr(rc, rc->itr_setting); } if (i < vsi->alloc_txq && coalesce[i].tx_valid) { rc = &vsi->q_vectors[i]->tx; rc->itr_settings = coalesce[i].itr_tx; ice_write_itr(rc, rc->itr_setting); } else if (i < vsi->alloc_txq) { rc = &vsi->q_vectors[i]->tx; rc->itr_settings = coalesce[0].itr_tx; ice_write_itr(rc, rc->itr_setting); } vsi->q_vectors[i]->intrl = coalesce[i].intrl; ice_set_q_vector_intrl(vsi->q_vectors[i]); } /* the number of queue vectors increased so write whatever is in * the first element */ for (; i < vsi->num_q_vectors; i++) { /* transmit */ rc = &vsi->q_vectors[i]->tx; rc->itr_settings = coalesce[0].itr_tx; ice_write_itr(rc, rc->itr_setting); /* receive */ rc = &vsi->q_vectors[i]->rx; rc->itr_settings = coalesce[0].itr_rx; ice_write_itr(rc, rc->itr_setting); vsi->q_vectors[i]->intrl = coalesce[0].intrl; ice_set_q_vector_intrl(vsi->q_vectors[i]); } } /** * ice_vsi_realloc_stat_arrays - Frees unused stat structures * @vsi: VSI pointer * @prev_txq: Number of Tx rings before ring reallocation * @prev_rxq: Number of Rx rings before ring reallocation */ static void ice_vsi_realloc_stat_arrays(struct ice_vsi *vsi, int prev_txq, int prev_rxq) { struct ice_vsi_stats *vsi_stat; struct ice_pf *pf = vsi->back; int i; if (!prev_txq || !prev_rxq) return; if (vsi->type == ICE_VSI_CHNL) return; vsi_stat = pf->vsi_stats[vsi->idx]; if (vsi->num_txq < prev_txq) { for (i = vsi->num_txq; i < prev_txq; i++) { if (vsi_stat->tx_ring_stats[i]) { kfree_rcu(vsi_stat->tx_ring_stats[i], rcu); WRITE_ONCE(vsi_stat->tx_ring_stats[i], NULL); } } } if (vsi->num_rxq < prev_rxq) { for (i = vsi->num_rxq; i < prev_rxq; i++) { if (vsi_stat->rx_ring_stats[i]) { kfree_rcu(vsi_stat->rx_ring_stats[i], rcu); WRITE_ONCE(vsi_stat->rx_ring_stats[i], NULL); } } } } /** * ice_vsi_rebuild - Rebuild VSI after reset * @vsi: VSI to be rebuild * @vsi_flags: flags used for VSI rebuild flow * * Set vsi_flags to ICE_VSI_FLAG_INIT to initialize a new VSI, or * ICE_VSI_FLAG_NO_INIT to rebuild an existing VSI in hardware. * * Returns 0 on success and negative value on failure */ int ice_vsi_rebuild(struct ice_vsi *vsi, u32 vsi_flags) { struct ice_vsi_cfg_params params = {}; struct ice_coalesce_stored *coalesce; int ret, prev_txq, prev_rxq; int prev_num_q_vectors = 0; struct ice_pf *pf; if (!vsi) return -EINVAL; params = ice_vsi_to_params(vsi); params.flags = vsi_flags; pf = vsi->back; if (WARN_ON(vsi->type == ICE_VSI_VF && !vsi->vf)) return -EINVAL; coalesce = kcalloc(vsi->num_q_vectors, sizeof(struct ice_coalesce_stored), GFP_KERNEL); if (!coalesce) return -ENOMEM; prev_num_q_vectors = ice_vsi_rebuild_get_coalesce(vsi, coalesce); prev_txq = vsi->num_txq; prev_rxq = vsi->num_rxq; ice_vsi_decfg(vsi); ret = ice_vsi_cfg_def(vsi, &params); if (ret) goto err_vsi_cfg; ret = ice_vsi_cfg_tc_lan(pf, vsi); if (ret) { if (vsi_flags & ICE_VSI_FLAG_INIT) { ret = -EIO; goto err_vsi_cfg_tc_lan; } kfree(coalesce); return ice_schedule_reset(pf, ICE_RESET_PFR); } ice_vsi_realloc_stat_arrays(vsi, prev_txq, prev_rxq); ice_vsi_rebuild_set_coalesce(vsi, coalesce, prev_num_q_vectors); kfree(coalesce); return 0; err_vsi_cfg_tc_lan: ice_vsi_decfg(vsi); err_vsi_cfg: kfree(coalesce); return ret; } /** * ice_is_reset_in_progress - check for a reset in progress * @state: PF state field */ bool ice_is_reset_in_progress(unsigned long *state) { return test_bit(ICE_RESET_OICR_RECV, state) || test_bit(ICE_PFR_REQ, state) || test_bit(ICE_CORER_REQ, state) || test_bit(ICE_GLOBR_REQ, state); } /** * ice_wait_for_reset - Wait for driver to finish reset and rebuild * @pf: pointer to the PF structure * @timeout: length of time to wait, in jiffies * * Wait (sleep) for a short time until the driver finishes cleaning up from * a device reset. The caller must be able to sleep. Use this to delay * operations that could fail while the driver is cleaning up after a device * reset. * * Returns 0 on success, -EBUSY if the reset is not finished within the * timeout, and -ERESTARTSYS if the thread was interrupted. */ int ice_wait_for_reset(struct ice_pf *pf, unsigned long timeout) { long ret; ret = wait_event_interruptible_timeout(pf->reset_wait_queue, !ice_is_reset_in_progress(pf->state), timeout); if (ret < 0) return ret; else if (!ret) return -EBUSY; else return 0; } /** * ice_vsi_update_q_map - update our copy of the VSI info with new queue map * @vsi: VSI being configured * @ctx: the context buffer returned from AQ VSI update command */ static void ice_vsi_update_q_map(struct ice_vsi *vsi, struct ice_vsi_ctx *ctx) { vsi->info.mapping_flags = ctx->info.mapping_flags; memcpy(&vsi->info.q_mapping, &ctx->info.q_mapping, sizeof(vsi->info.q_mapping)); memcpy(&vsi->info.tc_mapping, ctx->info.tc_mapping, sizeof(vsi->info.tc_mapping)); } /** * ice_vsi_cfg_netdev_tc - Setup the netdev TC configuration * @vsi: the VSI being configured * @ena_tc: TC map to be enabled */ void ice_vsi_cfg_netdev_tc(struct ice_vsi *vsi, u8 ena_tc) { struct net_device *netdev = vsi->netdev; struct ice_pf *pf = vsi->back; int numtc = vsi->tc_cfg.numtc; struct ice_dcbx_cfg *dcbcfg; u8 netdev_tc; int i; if (!netdev) return; /* CHNL VSI doesn't have it's own netdev, hence, no netdev_tc */ if (vsi->type == ICE_VSI_CHNL) return; if (!ena_tc) { netdev_reset_tc(netdev); return; } if (vsi->type == ICE_VSI_PF && ice_is_adq_active(pf)) numtc = vsi->all_numtc; if (netdev_set_num_tc(netdev, numtc)) return; dcbcfg = &pf->hw.port_info->qos_cfg.local_dcbx_cfg; ice_for_each_traffic_class(i) if (vsi->tc_cfg.ena_tc & BIT(i)) netdev_set_tc_queue(netdev, vsi->tc_cfg.tc_info[i].netdev_tc, vsi->tc_cfg.tc_info[i].qcount_tx, vsi->tc_cfg.tc_info[i].qoffset); /* setup TC queue map for CHNL TCs */ ice_for_each_chnl_tc(i) { if (!(vsi->all_enatc & BIT(i))) break; if (!vsi->mqprio_qopt.qopt.count[i]) break; netdev_set_tc_queue(netdev, i, vsi->mqprio_qopt.qopt.count[i], vsi->mqprio_qopt.qopt.offset[i]); } if (test_bit(ICE_FLAG_TC_MQPRIO, pf->flags)) return; for (i = 0; i < ICE_MAX_USER_PRIORITY; i++) { u8 ets_tc = dcbcfg->etscfg.prio_table[i]; /* Get the mapped netdev TC# for the UP */ netdev_tc = vsi->tc_cfg.tc_info[ets_tc].netdev_tc; netdev_set_prio_tc_map(netdev, i, netdev_tc); } } /** * ice_vsi_setup_q_map_mqprio - Prepares mqprio based tc_config * @vsi: the VSI being configured, * @ctxt: VSI context structure * @ena_tc: number of traffic classes to enable * * Prepares VSI tc_config to have queue configurations based on MQPRIO options. */ static int ice_vsi_setup_q_map_mqprio(struct ice_vsi *vsi, struct ice_vsi_ctx *ctxt, u8 ena_tc) { u16 pow, offset = 0, qcount_tx = 0, qcount_rx = 0, qmap; u16 tc0_offset = vsi->mqprio_qopt.qopt.offset[0]; int tc0_qcount = vsi->mqprio_qopt.qopt.count[0]; u16 new_txq, new_rxq; u8 netdev_tc = 0; int i; vsi->tc_cfg.ena_tc = ena_tc ? ena_tc : 1; pow = order_base_2(tc0_qcount); qmap = ((tc0_offset << ICE_AQ_VSI_TC_Q_OFFSET_S) & ICE_AQ_VSI_TC_Q_OFFSET_M) | ((pow << ICE_AQ_VSI_TC_Q_NUM_S) & ICE_AQ_VSI_TC_Q_NUM_M); ice_for_each_traffic_class(i) { if (!(vsi->tc_cfg.ena_tc & BIT(i))) { /* TC is not enabled */ vsi->tc_cfg.tc_info[i].qoffset = 0; vsi->tc_cfg.tc_info[i].qcount_rx = 1; vsi->tc_cfg.tc_info[i].qcount_tx = 1; vsi->tc_cfg.tc_info[i].netdev_tc = 0; ctxt->info.tc_mapping[i] = 0; continue; } offset = vsi->mqprio_qopt.qopt.offset[i]; qcount_rx = vsi->mqprio_qopt.qopt.count[i]; qcount_tx = vsi->mqprio_qopt.qopt.count[i]; vsi->tc_cfg.tc_info[i].qoffset = offset; vsi->tc_cfg.tc_info[i].qcount_rx = qcount_rx; vsi->tc_cfg.tc_info[i].qcount_tx = qcount_tx; vsi->tc_cfg.tc_info[i].netdev_tc = netdev_tc++; } if (vsi->all_numtc && vsi->all_numtc != vsi->tc_cfg.numtc) { ice_for_each_chnl_tc(i) { if (!(vsi->all_enatc & BIT(i))) continue; offset = vsi->mqprio_qopt.qopt.offset[i]; qcount_rx = vsi->mqprio_qopt.qopt.count[i]; qcount_tx = vsi->mqprio_qopt.qopt.count[i]; } } new_txq = offset + qcount_tx; if (new_txq > vsi->alloc_txq) { dev_err(ice_pf_to_dev(vsi->back), "Trying to use more Tx queues (%u), than were allocated (%u)!\n", new_txq, vsi->alloc_txq); return -EINVAL; } new_rxq = offset + qcount_rx; if (new_rxq > vsi->alloc_rxq) { dev_err(ice_pf_to_dev(vsi->back), "Trying to use more Rx queues (%u), than were allocated (%u)!\n", new_rxq, vsi->alloc_rxq); return -EINVAL; } /* Set actual Tx/Rx queue pairs */ vsi->num_txq = new_txq; vsi->num_rxq = new_rxq; /* Setup queue TC[0].qmap for given VSI context */ ctxt->info.tc_mapping[0] = cpu_to_le16(qmap); ctxt->info.q_mapping[0] = cpu_to_le16(vsi->rxq_map[0]); ctxt->info.q_mapping[1] = cpu_to_le16(tc0_qcount); /* Find queue count available for channel VSIs and starting offset * for channel VSIs */ if (tc0_qcount && tc0_qcount < vsi->num_rxq) { vsi->cnt_q_avail = vsi->num_rxq - tc0_qcount; vsi->next_base_q = tc0_qcount; } dev_dbg(ice_pf_to_dev(vsi->back), "vsi->num_txq = %d\n", vsi->num_txq); dev_dbg(ice_pf_to_dev(vsi->back), "vsi->num_rxq = %d\n", vsi->num_rxq); dev_dbg(ice_pf_to_dev(vsi->back), "all_numtc %u, all_enatc: 0x%04x, tc_cfg.numtc %u\n", vsi->all_numtc, vsi->all_enatc, vsi->tc_cfg.numtc); return 0; } /** * ice_vsi_cfg_tc - Configure VSI Tx Sched for given TC map * @vsi: VSI to be configured * @ena_tc: TC bitmap * * VSI queues expected to be quiesced before calling this function */ int ice_vsi_cfg_tc(struct ice_vsi *vsi, u8 ena_tc) { u16 max_txqs[ICE_MAX_TRAFFIC_CLASS] = { 0 }; struct ice_pf *pf = vsi->back; struct ice_tc_cfg old_tc_cfg; struct ice_vsi_ctx *ctx; struct device *dev; int i, ret = 0; u8 num_tc = 0; dev = ice_pf_to_dev(pf); if (vsi->tc_cfg.ena_tc == ena_tc && vsi->mqprio_qopt.mode != TC_MQPRIO_MODE_CHANNEL) return 0; ice_for_each_traffic_class(i) { /* build bitmap of enabled TCs */ if (ena_tc & BIT(i)) num_tc++; /* populate max_txqs per TC */ max_txqs[i] = vsi->alloc_txq; /* Update max_txqs if it is CHNL VSI, because alloc_t[r]xq are * zero for CHNL VSI, hence use num_txq instead as max_txqs */ if (vsi->type == ICE_VSI_CHNL && test_bit(ICE_FLAG_TC_MQPRIO, pf->flags)) max_txqs[i] = vsi->num_txq; } memcpy(&old_tc_cfg, &vsi->tc_cfg, sizeof(old_tc_cfg)); vsi->tc_cfg.ena_tc = ena_tc; vsi->tc_cfg.numtc = num_tc; ctx = kzalloc(sizeof(*ctx), GFP_KERNEL); if (!ctx) return -ENOMEM; ctx->vf_num = 0; ctx->info = vsi->info; if (vsi->type == ICE_VSI_PF && test_bit(ICE_FLAG_TC_MQPRIO, pf->flags)) ret = ice_vsi_setup_q_map_mqprio(vsi, ctx, ena_tc); else ret = ice_vsi_setup_q_map(vsi, ctx); if (ret) { memcpy(&vsi->tc_cfg, &old_tc_cfg, sizeof(vsi->tc_cfg)); goto out; } /* must to indicate which section of VSI context are being modified */ ctx->info.valid_sections = cpu_to_le16(ICE_AQ_VSI_PROP_RXQ_MAP_VALID); ret = ice_update_vsi(&pf->hw, vsi->idx, ctx, NULL); if (ret) { dev_info(dev, "Failed VSI Update\n"); goto out; } if (vsi->type == ICE_VSI_PF && test_bit(ICE_FLAG_TC_MQPRIO, pf->flags)) ret = ice_cfg_vsi_lan(vsi->port_info, vsi->idx, 1, max_txqs); else ret = ice_cfg_vsi_lan(vsi->port_info, vsi->idx, vsi->tc_cfg.ena_tc, max_txqs); if (ret) { dev_err(dev, "VSI %d failed TC config, error %d\n", vsi->vsi_num, ret); goto out; } ice_vsi_update_q_map(vsi, ctx); vsi->info.valid_sections = 0; ice_vsi_cfg_netdev_tc(vsi, ena_tc); out: kfree(ctx); return ret; } /** * ice_update_ring_stats - Update ring statistics * @stats: stats to be updated * @pkts: number of processed packets * @bytes: number of processed bytes * * This function assumes that caller has acquired a u64_stats_sync lock. */ static void ice_update_ring_stats(struct ice_q_stats *stats, u64 pkts, u64 bytes) { stats->bytes += bytes; stats->pkts += pkts; } /** * ice_update_tx_ring_stats - Update Tx ring specific counters * @tx_ring: ring to update * @pkts: number of processed packets * @bytes: number of processed bytes */ void ice_update_tx_ring_stats(struct ice_tx_ring *tx_ring, u64 pkts, u64 bytes) { u64_stats_update_begin(&tx_ring->ring_stats->syncp); ice_update_ring_stats(&tx_ring->ring_stats->stats, pkts, bytes); u64_stats_update_end(&tx_ring->ring_stats->syncp); } /** * ice_update_rx_ring_stats - Update Rx ring specific counters * @rx_ring: ring to update * @pkts: number of processed packets * @bytes: number of processed bytes */ void ice_update_rx_ring_stats(struct ice_rx_ring *rx_ring, u64 pkts, u64 bytes) { u64_stats_update_begin(&rx_ring->ring_stats->syncp); ice_update_ring_stats(&rx_ring->ring_stats->stats, pkts, bytes); u64_stats_update_end(&rx_ring->ring_stats->syncp); } /** * ice_is_dflt_vsi_in_use - check if the default forwarding VSI is being used * @pi: port info of the switch with default VSI * * Return true if the there is a single VSI in default forwarding VSI list */ bool ice_is_dflt_vsi_in_use(struct ice_port_info *pi) { bool exists = false; ice_check_if_dflt_vsi(pi, 0, &exists); return exists; } /** * ice_is_vsi_dflt_vsi - check if the VSI passed in is the default VSI * @vsi: VSI to compare against default forwarding VSI * * If this VSI passed in is the default forwarding VSI then return true, else * return false */ bool ice_is_vsi_dflt_vsi(struct ice_vsi *vsi) { return ice_check_if_dflt_vsi(vsi->port_info, vsi->idx, NULL); } /** * ice_set_dflt_vsi - set the default forwarding VSI * @vsi: VSI getting set as the default forwarding VSI on the switch * * If the VSI passed in is already the default VSI and it's enabled just return * success. * * Otherwise try to set the VSI passed in as the switch's default VSI and * return the result. */ int ice_set_dflt_vsi(struct ice_vsi *vsi) { struct device *dev; int status; if (!vsi) return -EINVAL; dev = ice_pf_to_dev(vsi->back); /* the VSI passed in is already the default VSI */ if (ice_is_vsi_dflt_vsi(vsi)) { dev_dbg(dev, "VSI %d passed in is already the default forwarding VSI, nothing to do\n", vsi->vsi_num); return 0; } status = ice_cfg_dflt_vsi(vsi->port_info, vsi->idx, true, ICE_FLTR_RX); if (status) { dev_err(dev, "Failed to set VSI %d as the default forwarding VSI, error %d\n", vsi->vsi_num, status); return status; } return 0; } /** * ice_clear_dflt_vsi - clear the default forwarding VSI * @vsi: VSI to remove from filter list * * If the switch has no default VSI or it's not enabled then return error. * * Otherwise try to clear the default VSI and return the result. */ int ice_clear_dflt_vsi(struct ice_vsi *vsi) { struct device *dev; int status; if (!vsi) return -EINVAL; dev = ice_pf_to_dev(vsi->back); /* there is no default VSI configured */ if (!ice_is_dflt_vsi_in_use(vsi->port_info)) return -ENODEV; status = ice_cfg_dflt_vsi(vsi->port_info, vsi->idx, false, ICE_FLTR_RX); if (status) { dev_err(dev, "Failed to clear the default forwarding VSI %d, error %d\n", vsi->vsi_num, status); return -EIO; } return 0; } /** * ice_get_link_speed_mbps - get link speed in Mbps * @vsi: the VSI whose link speed is being queried * * Return current VSI link speed and 0 if the speed is unknown. */ int ice_get_link_speed_mbps(struct ice_vsi *vsi) { unsigned int link_speed; link_speed = vsi->port_info->phy.link_info.link_speed; return (int)ice_get_link_speed(fls(link_speed) - 1); } /** * ice_get_link_speed_kbps - get link speed in Kbps * @vsi: the VSI whose link speed is being queried * * Return current VSI link speed and 0 if the speed is unknown. */ int ice_get_link_speed_kbps(struct ice_vsi *vsi) { int speed_mbps; speed_mbps = ice_get_link_speed_mbps(vsi); return speed_mbps * 1000; } /** * ice_set_min_bw_limit - setup minimum BW limit for Tx based on min_tx_rate * @vsi: VSI to be configured * @min_tx_rate: min Tx rate in Kbps to be configured as BW limit * * If the min_tx_rate is specified as 0 that means to clear the minimum BW limit * profile, otherwise a non-zero value will force a minimum BW limit for the VSI * on TC 0. */ int ice_set_min_bw_limit(struct ice_vsi *vsi, u64 min_tx_rate) { struct ice_pf *pf = vsi->back; struct device *dev; int status; int speed; dev = ice_pf_to_dev(pf); if (!vsi->port_info) { dev_dbg(dev, "VSI %d, type %u specified doesn't have valid port_info\n", vsi->idx, vsi->type); return -EINVAL; } speed = ice_get_link_speed_kbps(vsi); if (min_tx_rate > (u64)speed) { dev_err(dev, "invalid min Tx rate %llu Kbps specified for %s %d is greater than current link speed %u Kbps\n", min_tx_rate, ice_vsi_type_str(vsi->type), vsi->idx, speed); return -EINVAL; } /* Configure min BW for VSI limit */ if (min_tx_rate) { status = ice_cfg_vsi_bw_lmt_per_tc(vsi->port_info, vsi->idx, 0, ICE_MIN_BW, min_tx_rate); if (status) { dev_err(dev, "failed to set min Tx rate(%llu Kbps) for %s %d\n", min_tx_rate, ice_vsi_type_str(vsi->type), vsi->idx); return status; } dev_dbg(dev, "set min Tx rate(%llu Kbps) for %s\n", min_tx_rate, ice_vsi_type_str(vsi->type)); } else { status = ice_cfg_vsi_bw_dflt_lmt_per_tc(vsi->port_info, vsi->idx, 0, ICE_MIN_BW); if (status) { dev_err(dev, "failed to clear min Tx rate configuration for %s %d\n", ice_vsi_type_str(vsi->type), vsi->idx); return status; } dev_dbg(dev, "cleared min Tx rate configuration for %s %d\n", ice_vsi_type_str(vsi->type), vsi->idx); } return 0; } /** * ice_set_max_bw_limit - setup maximum BW limit for Tx based on max_tx_rate * @vsi: VSI to be configured * @max_tx_rate: max Tx rate in Kbps to be configured as BW limit * * If the max_tx_rate is specified as 0 that means to clear the maximum BW limit * profile, otherwise a non-zero value will force a maximum BW limit for the VSI * on TC 0. */ int ice_set_max_bw_limit(struct ice_vsi *vsi, u64 max_tx_rate) { struct ice_pf *pf = vsi->back; struct device *dev; int status; int speed; dev = ice_pf_to_dev(pf); if (!vsi->port_info) { dev_dbg(dev, "VSI %d, type %u specified doesn't have valid port_info\n", vsi->idx, vsi->type); return -EINVAL; } speed = ice_get_link_speed_kbps(vsi); if (max_tx_rate > (u64)speed) { dev_err(dev, "invalid max Tx rate %llu Kbps specified for %s %d is greater than current link speed %u Kbps\n", max_tx_rate, ice_vsi_type_str(vsi->type), vsi->idx, speed); return -EINVAL; } /* Configure max BW for VSI limit */ if (max_tx_rate) { status = ice_cfg_vsi_bw_lmt_per_tc(vsi->port_info, vsi->idx, 0, ICE_MAX_BW, max_tx_rate); if (status) { dev_err(dev, "failed setting max Tx rate(%llu Kbps) for %s %d\n", max_tx_rate, ice_vsi_type_str(vsi->type), vsi->idx); return status; } dev_dbg(dev, "set max Tx rate(%llu Kbps) for %s %d\n", max_tx_rate, ice_vsi_type_str(vsi->type), vsi->idx); } else { status = ice_cfg_vsi_bw_dflt_lmt_per_tc(vsi->port_info, vsi->idx, 0, ICE_MAX_BW); if (status) { dev_err(dev, "failed clearing max Tx rate configuration for %s %d\n", ice_vsi_type_str(vsi->type), vsi->idx); return status; } dev_dbg(dev, "cleared max Tx rate configuration for %s %d\n", ice_vsi_type_str(vsi->type), vsi->idx); } return 0; } /** * ice_set_link - turn on/off physical link * @vsi: VSI to modify physical link on * @ena: turn on/off physical link */ int ice_set_link(struct ice_vsi *vsi, bool ena) { struct device *dev = ice_pf_to_dev(vsi->back); struct ice_port_info *pi = vsi->port_info; struct ice_hw *hw = pi->hw; int status; if (vsi->type != ICE_VSI_PF) return -EINVAL; status = ice_aq_set_link_restart_an(pi, ena, NULL); /* if link is owned by manageability, FW will return ICE_AQ_RC_EMODE. * this is not a fatal error, so print a warning message and return * a success code. Return an error if FW returns an error code other * than ICE_AQ_RC_EMODE */ if (status == -EIO) { if (hw->adminq.sq_last_status == ICE_AQ_RC_EMODE) dev_dbg(dev, "can't set link to %s, err %d aq_err %s. not fatal, continuing\n", (ena ? "ON" : "OFF"), status, ice_aq_str(hw->adminq.sq_last_status)); } else if (status) { dev_err(dev, "can't set link to %s, err %d aq_err %s\n", (ena ? "ON" : "OFF"), status, ice_aq_str(hw->adminq.sq_last_status)); return status; } return 0; } /** * ice_vsi_add_vlan_zero - add VLAN 0 filter(s) for this VSI * @vsi: VSI used to add VLAN filters * * In Single VLAN Mode (SVM), single VLAN filters via ICE_SW_LKUP_VLAN are based * on the inner VLAN ID, so the VLAN TPID (i.e. 0x8100 or 0x888a8) doesn't * matter. In Double VLAN Mode (DVM), outer/single VLAN filters via * ICE_SW_LKUP_VLAN are based on the outer/single VLAN ID + VLAN TPID. * * For both modes add a VLAN 0 + no VLAN TPID filter to handle untagged traffic * when VLAN pruning is enabled. Also, this handles VLAN 0 priority tagged * traffic in SVM, since the VLAN TPID isn't part of filtering. * * If DVM is enabled then an explicit VLAN 0 + VLAN TPID filter needs to be * added to allow VLAN 0 priority tagged traffic in DVM, since the VLAN TPID is * part of filtering. */ int ice_vsi_add_vlan_zero(struct ice_vsi *vsi) { struct ice_vsi_vlan_ops *vlan_ops = ice_get_compat_vsi_vlan_ops(vsi); struct ice_vlan vlan; int err; vlan = ICE_VLAN(0, 0, 0); err = vlan_ops->add_vlan(vsi, &vlan); if (err && err != -EEXIST) return err; /* in SVM both VLAN 0 filters are identical */ if (!ice_is_dvm_ena(&vsi->back->hw)) return 0; vlan = ICE_VLAN(ETH_P_8021Q, 0, 0); err = vlan_ops->add_vlan(vsi, &vlan); if (err && err != -EEXIST) return err; return 0; } /** * ice_vsi_del_vlan_zero - delete VLAN 0 filter(s) for this VSI * @vsi: VSI used to add VLAN filters * * Delete the VLAN 0 filters in the same manner that they were added in * ice_vsi_add_vlan_zero. */ int ice_vsi_del_vlan_zero(struct ice_vsi *vsi) { struct ice_vsi_vlan_ops *vlan_ops = ice_get_compat_vsi_vlan_ops(vsi); struct ice_vlan vlan; int err; vlan = ICE_VLAN(0, 0, 0); err = vlan_ops->del_vlan(vsi, &vlan); if (err && err != -EEXIST) return err; /* in SVM both VLAN 0 filters are identical */ if (!ice_is_dvm_ena(&vsi->back->hw)) return 0; vlan = ICE_VLAN(ETH_P_8021Q, 0, 0); err = vlan_ops->del_vlan(vsi, &vlan); if (err && err != -EEXIST) return err; /* when deleting the last VLAN filter, make sure to disable the VLAN * promisc mode so the filter isn't left by accident */ return ice_clear_vsi_promisc(&vsi->back->hw, vsi->idx, ICE_MCAST_VLAN_PROMISC_BITS, 0); } /** * ice_vsi_num_zero_vlans - get number of VLAN 0 filters based on VLAN mode * @vsi: VSI used to get the VLAN mode * * If DVM is enabled then 2 VLAN 0 filters are added, else if SVM is enabled * then 1 VLAN 0 filter is added. See ice_vsi_add_vlan_zero for more details. */ static u16 ice_vsi_num_zero_vlans(struct ice_vsi *vsi) { #define ICE_DVM_NUM_ZERO_VLAN_FLTRS 2 #define ICE_SVM_NUM_ZERO_VLAN_FLTRS 1 /* no VLAN 0 filter is created when a port VLAN is active */ if (vsi->type == ICE_VSI_VF) { if (WARN_ON(!vsi->vf)) return 0; if (ice_vf_is_port_vlan_ena(vsi->vf)) return 0; } if (ice_is_dvm_ena(&vsi->back->hw)) return ICE_DVM_NUM_ZERO_VLAN_FLTRS; else return ICE_SVM_NUM_ZERO_VLAN_FLTRS; } /** * ice_vsi_has_non_zero_vlans - check if VSI has any non-zero VLANs * @vsi: VSI used to determine if any non-zero VLANs have been added */ bool ice_vsi_has_non_zero_vlans(struct ice_vsi *vsi) { return (vsi->num_vlan > ice_vsi_num_zero_vlans(vsi)); } /** * ice_vsi_num_non_zero_vlans - get the number of non-zero VLANs for this VSI * @vsi: VSI used to get the number of non-zero VLANs added */ u16 ice_vsi_num_non_zero_vlans(struct ice_vsi *vsi) { return (vsi->num_vlan - ice_vsi_num_zero_vlans(vsi)); } /** * ice_is_feature_supported * @pf: pointer to the struct ice_pf instance * @f: feature enum to be checked * * returns true if feature is supported, false otherwise */ bool ice_is_feature_supported(struct ice_pf *pf, enum ice_feature f) { if (f < 0 || f >= ICE_F_MAX) return false; return test_bit(f, pf->features); } /** * ice_set_feature_support * @pf: pointer to the struct ice_pf instance * @f: feature enum to set */ void ice_set_feature_support(struct ice_pf *pf, enum ice_feature f) { if (f < 0 || f >= ICE_F_MAX) return; set_bit(f, pf->features); } /** * ice_clear_feature_support * @pf: pointer to the struct ice_pf instance * @f: feature enum to clear */ void ice_clear_feature_support(struct ice_pf *pf, enum ice_feature f) { if (f < 0 || f >= ICE_F_MAX) return; clear_bit(f, pf->features); } /** * ice_init_feature_support * @pf: pointer to the struct ice_pf instance * * called during init to setup supported feature */ void ice_init_feature_support(struct ice_pf *pf) { switch (pf->hw.device_id) { case ICE_DEV_ID_E810C_BACKPLANE: case ICE_DEV_ID_E810C_QSFP: case ICE_DEV_ID_E810C_SFP: ice_set_feature_support(pf, ICE_F_DSCP); ice_set_feature_support(pf, ICE_F_PTP_EXTTS); if (ice_is_e810t(&pf->hw)) { ice_set_feature_support(pf, ICE_F_SMA_CTRL); if (ice_gnss_is_gps_present(&pf->hw)) ice_set_feature_support(pf, ICE_F_GNSS); } break; default: break; } } /** * ice_vsi_update_security - update security block in VSI * @vsi: pointer to VSI structure * @fill: function pointer to fill ctx */ int ice_vsi_update_security(struct ice_vsi *vsi, void (*fill)(struct ice_vsi_ctx *)) { struct ice_vsi_ctx ctx = { 0 }; ctx.info = vsi->info; ctx.info.valid_sections = cpu_to_le16(ICE_AQ_VSI_PROP_SECURITY_VALID); fill(&ctx); if (ice_update_vsi(&vsi->back->hw, vsi->idx, &ctx, NULL)) return -ENODEV; vsi->info = ctx.info; return 0; } /** * ice_vsi_ctx_set_antispoof - set antispoof function in VSI ctx * @ctx: pointer to VSI ctx structure */ void ice_vsi_ctx_set_antispoof(struct ice_vsi_ctx *ctx) { ctx->info.sec_flags |= ICE_AQ_VSI_SEC_FLAG_ENA_MAC_ANTI_SPOOF | (ICE_AQ_VSI_SEC_TX_VLAN_PRUNE_ENA << ICE_AQ_VSI_SEC_TX_PRUNE_ENA_S); } /** * ice_vsi_ctx_clear_antispoof - clear antispoof function in VSI ctx * @ctx: pointer to VSI ctx structure */ void ice_vsi_ctx_clear_antispoof(struct ice_vsi_ctx *ctx) { ctx->info.sec_flags &= ~ICE_AQ_VSI_SEC_FLAG_ENA_MAC_ANTI_SPOOF & ~(ICE_AQ_VSI_SEC_TX_VLAN_PRUNE_ENA << ICE_AQ_VSI_SEC_TX_PRUNE_ENA_S); } /** * ice_vsi_ctx_set_allow_override - allow destination override on VSI * @ctx: pointer to VSI ctx structure */ void ice_vsi_ctx_set_allow_override(struct ice_vsi_ctx *ctx) { ctx->info.sec_flags |= ICE_AQ_VSI_SEC_FLAG_ALLOW_DEST_OVRD; } /** * ice_vsi_ctx_clear_allow_override - turn off destination override on VSI * @ctx: pointer to VSI ctx structure */ void ice_vsi_ctx_clear_allow_override(struct ice_vsi_ctx *ctx) { ctx->info.sec_flags &= ~ICE_AQ_VSI_SEC_FLAG_ALLOW_DEST_OVRD; } /** * ice_vsi_update_local_lb - update sw block in VSI with local loopback bit * @vsi: pointer to VSI structure * @set: set or unset the bit */ int ice_vsi_update_local_lb(struct ice_vsi *vsi, bool set) { struct ice_vsi_ctx ctx = { .info = vsi->info, }; ctx.info.valid_sections = cpu_to_le16(ICE_AQ_VSI_PROP_SW_VALID); if (set) ctx.info.sw_flags |= ICE_AQ_VSI_SW_FLAG_LOCAL_LB; else ctx.info.sw_flags &= ~ICE_AQ_VSI_SW_FLAG_LOCAL_LB; if (ice_update_vsi(&vsi->back->hw, vsi->idx, &ctx, NULL)) return -ENODEV; vsi->info = ctx.info; return 0; }
linux-master
drivers/net/ethernet/intel/ice/ice_lib.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2018-2020, Intel Corporation. */ #include "ice.h" #include "ice_fltr.h" /** * ice_fltr_free_list - free filter lists helper * @dev: pointer to the device struct * @h: pointer to the list head to be freed * * Helper function to free filter lists previously created using * ice_fltr_add_mac_to_list */ void ice_fltr_free_list(struct device *dev, struct list_head *h) { struct ice_fltr_list_entry *e, *tmp; list_for_each_entry_safe(e, tmp, h, list_entry) { list_del(&e->list_entry); devm_kfree(dev, e); } } /** * ice_fltr_add_entry_to_list - allocate and add filter entry to list * @dev: pointer to device needed by alloc function * @info: filter info struct that gets added to the passed in list * @list: pointer to the list which contains MAC filters entry */ static int ice_fltr_add_entry_to_list(struct device *dev, struct ice_fltr_info *info, struct list_head *list) { struct ice_fltr_list_entry *entry; entry = devm_kzalloc(dev, sizeof(*entry), GFP_ATOMIC); if (!entry) return -ENOMEM; entry->fltr_info = *info; INIT_LIST_HEAD(&entry->list_entry); list_add(&entry->list_entry, list); return 0; } /** * ice_fltr_set_vlan_vsi_promisc * @hw: pointer to the hardware structure * @vsi: the VSI being configured * @promisc_mask: mask of promiscuous config bits * * Set VSI with all associated VLANs to given promiscuous mode(s) */ int ice_fltr_set_vlan_vsi_promisc(struct ice_hw *hw, struct ice_vsi *vsi, u8 promisc_mask) { struct ice_pf *pf = hw->back; int result; result = ice_set_vlan_vsi_promisc(hw, vsi->idx, promisc_mask, false); if (result && result != -EEXIST) dev_err(ice_pf_to_dev(pf), "Error setting promisc mode on VSI %i (rc=%d)\n", vsi->vsi_num, result); return result; } /** * ice_fltr_clear_vlan_vsi_promisc * @hw: pointer to the hardware structure * @vsi: the VSI being configured * @promisc_mask: mask of promiscuous config bits * * Clear VSI with all associated VLANs to given promiscuous mode(s) */ int ice_fltr_clear_vlan_vsi_promisc(struct ice_hw *hw, struct ice_vsi *vsi, u8 promisc_mask) { struct ice_pf *pf = hw->back; int result; result = ice_set_vlan_vsi_promisc(hw, vsi->idx, promisc_mask, true); if (result && result != -EEXIST) dev_err(ice_pf_to_dev(pf), "Error clearing promisc mode on VSI %i (rc=%d)\n", vsi->vsi_num, result); return result; } /** * ice_fltr_clear_vsi_promisc - clear specified promiscuous mode(s) * @hw: pointer to the hardware structure * @vsi_handle: VSI handle to clear mode * @promisc_mask: mask of promiscuous config bits to clear * @vid: VLAN ID to clear VLAN promiscuous */ int ice_fltr_clear_vsi_promisc(struct ice_hw *hw, u16 vsi_handle, u8 promisc_mask, u16 vid) { struct ice_pf *pf = hw->back; int result; result = ice_clear_vsi_promisc(hw, vsi_handle, promisc_mask, vid); if (result && result != -EEXIST) dev_err(ice_pf_to_dev(pf), "Error clearing promisc mode on VSI %i for VID %u (rc=%d)\n", ice_get_hw_vsi_num(hw, vsi_handle), vid, result); return result; } /** * ice_fltr_set_vsi_promisc - set given VSI to given promiscuous mode(s) * @hw: pointer to the hardware structure * @vsi_handle: VSI handle to configure * @promisc_mask: mask of promiscuous config bits * @vid: VLAN ID to set VLAN promiscuous */ int ice_fltr_set_vsi_promisc(struct ice_hw *hw, u16 vsi_handle, u8 promisc_mask, u16 vid) { struct ice_pf *pf = hw->back; int result; result = ice_set_vsi_promisc(hw, vsi_handle, promisc_mask, vid); if (result && result != -EEXIST) dev_err(ice_pf_to_dev(pf), "Error setting promisc mode on VSI %i for VID %u (rc=%d)\n", ice_get_hw_vsi_num(hw, vsi_handle), vid, result); return result; } /** * ice_fltr_add_mac_list - add list of MAC filters * @vsi: pointer to VSI struct * @list: list of filters */ int ice_fltr_add_mac_list(struct ice_vsi *vsi, struct list_head *list) { return ice_add_mac(&vsi->back->hw, list); } /** * ice_fltr_remove_mac_list - remove list of MAC filters * @vsi: pointer to VSI struct * @list: list of filters */ int ice_fltr_remove_mac_list(struct ice_vsi *vsi, struct list_head *list) { return ice_remove_mac(&vsi->back->hw, list); } /** * ice_fltr_add_vlan_list - add list of VLAN filters * @vsi: pointer to VSI struct * @list: list of filters */ static int ice_fltr_add_vlan_list(struct ice_vsi *vsi, struct list_head *list) { return ice_add_vlan(&vsi->back->hw, list); } /** * ice_fltr_remove_vlan_list - remove list of VLAN filters * @vsi: pointer to VSI struct * @list: list of filters */ static int ice_fltr_remove_vlan_list(struct ice_vsi *vsi, struct list_head *list) { return ice_remove_vlan(&vsi->back->hw, list); } /** * ice_fltr_add_eth_list - add list of ethertype filters * @vsi: pointer to VSI struct * @list: list of filters */ static int ice_fltr_add_eth_list(struct ice_vsi *vsi, struct list_head *list) { return ice_add_eth_mac(&vsi->back->hw, list); } /** * ice_fltr_remove_eth_list - remove list of ethertype filters * @vsi: pointer to VSI struct * @list: list of filters */ static int ice_fltr_remove_eth_list(struct ice_vsi *vsi, struct list_head *list) { return ice_remove_eth_mac(&vsi->back->hw, list); } /** * ice_fltr_remove_all - remove all filters associated with VSI * @vsi: pointer to VSI struct */ void ice_fltr_remove_all(struct ice_vsi *vsi) { ice_remove_vsi_fltr(&vsi->back->hw, vsi->idx); /* sync netdev filters if exist */ if (vsi->netdev) { __dev_uc_unsync(vsi->netdev, NULL); __dev_mc_unsync(vsi->netdev, NULL); } } /** * ice_fltr_add_mac_to_list - add MAC filter info to exsisting list * @vsi: pointer to VSI struct * @list: list to add filter info to * @mac: MAC address to add * @action: filter action */ int ice_fltr_add_mac_to_list(struct ice_vsi *vsi, struct list_head *list, const u8 *mac, enum ice_sw_fwd_act_type action) { struct ice_fltr_info info = { 0 }; info.flag = ICE_FLTR_TX; info.src_id = ICE_SRC_ID_VSI; info.lkup_type = ICE_SW_LKUP_MAC; info.fltr_act = action; info.vsi_handle = vsi->idx; ether_addr_copy(info.l_data.mac.mac_addr, mac); return ice_fltr_add_entry_to_list(ice_pf_to_dev(vsi->back), &info, list); } /** * ice_fltr_add_vlan_to_list - add VLAN filter info to exsisting list * @vsi: pointer to VSI struct * @list: list to add filter info to * @vlan: VLAN filter details */ static int ice_fltr_add_vlan_to_list(struct ice_vsi *vsi, struct list_head *list, struct ice_vlan *vlan) { struct ice_fltr_info info = { 0 }; info.flag = ICE_FLTR_TX; info.src_id = ICE_SRC_ID_VSI; info.lkup_type = ICE_SW_LKUP_VLAN; info.fltr_act = ICE_FWD_TO_VSI; info.vsi_handle = vsi->idx; info.l_data.vlan.vlan_id = vlan->vid; info.l_data.vlan.tpid = vlan->tpid; info.l_data.vlan.tpid_valid = true; return ice_fltr_add_entry_to_list(ice_pf_to_dev(vsi->back), &info, list); } /** * ice_fltr_add_eth_to_list - add ethertype filter info to exsisting list * @vsi: pointer to VSI struct * @list: list to add filter info to * @ethertype: ethertype of packet that matches filter * @flag: filter direction, Tx or Rx * @action: filter action */ static int ice_fltr_add_eth_to_list(struct ice_vsi *vsi, struct list_head *list, u16 ethertype, u16 flag, enum ice_sw_fwd_act_type action) { struct ice_fltr_info info = { 0 }; info.flag = flag; info.lkup_type = ICE_SW_LKUP_ETHERTYPE; info.fltr_act = action; info.vsi_handle = vsi->idx; info.l_data.ethertype_mac.ethertype = ethertype; if (flag == ICE_FLTR_TX) info.src_id = ICE_SRC_ID_VSI; else info.src_id = ICE_SRC_ID_LPORT; return ice_fltr_add_entry_to_list(ice_pf_to_dev(vsi->back), &info, list); } /** * ice_fltr_prepare_mac - add or remove MAC rule * @vsi: pointer to VSI struct * @mac: MAC address to add * @action: action to be performed on filter match * @mac_action: pointer to add or remove MAC function */ static int ice_fltr_prepare_mac(struct ice_vsi *vsi, const u8 *mac, enum ice_sw_fwd_act_type action, int (*mac_action)(struct ice_vsi *, struct list_head *)) { LIST_HEAD(tmp_list); int result; if (ice_fltr_add_mac_to_list(vsi, &tmp_list, mac, action)) { ice_fltr_free_list(ice_pf_to_dev(vsi->back), &tmp_list); return -ENOMEM; } result = mac_action(vsi, &tmp_list); ice_fltr_free_list(ice_pf_to_dev(vsi->back), &tmp_list); return result; } /** * ice_fltr_prepare_mac_and_broadcast - add or remove MAC and broadcast filter * @vsi: pointer to VSI struct * @mac: MAC address to add * @action: action to be performed on filter match * @mac_action: pointer to add or remove MAC function */ static int ice_fltr_prepare_mac_and_broadcast(struct ice_vsi *vsi, const u8 *mac, enum ice_sw_fwd_act_type action, int(*mac_action) (struct ice_vsi *, struct list_head *)) { u8 broadcast[ETH_ALEN]; LIST_HEAD(tmp_list); int result; eth_broadcast_addr(broadcast); if (ice_fltr_add_mac_to_list(vsi, &tmp_list, mac, action) || ice_fltr_add_mac_to_list(vsi, &tmp_list, broadcast, action)) { ice_fltr_free_list(ice_pf_to_dev(vsi->back), &tmp_list); return -ENOMEM; } result = mac_action(vsi, &tmp_list); ice_fltr_free_list(ice_pf_to_dev(vsi->back), &tmp_list); return result; } /** * ice_fltr_prepare_vlan - add or remove VLAN filter * @vsi: pointer to VSI struct * @vlan: VLAN filter details * @vlan_action: pointer to add or remove VLAN function */ static int ice_fltr_prepare_vlan(struct ice_vsi *vsi, struct ice_vlan *vlan, int (*vlan_action)(struct ice_vsi *, struct list_head *)) { LIST_HEAD(tmp_list); int result; if (ice_fltr_add_vlan_to_list(vsi, &tmp_list, vlan)) return -ENOMEM; result = vlan_action(vsi, &tmp_list); ice_fltr_free_list(ice_pf_to_dev(vsi->back), &tmp_list); return result; } /** * ice_fltr_prepare_eth - add or remove ethertype filter * @vsi: pointer to VSI struct * @ethertype: ethertype of packet to be filtered * @flag: direction of packet, Tx or Rx * @action: action to be performed on filter match * @eth_action: pointer to add or remove ethertype function */ static int ice_fltr_prepare_eth(struct ice_vsi *vsi, u16 ethertype, u16 flag, enum ice_sw_fwd_act_type action, int (*eth_action)(struct ice_vsi *, struct list_head *)) { LIST_HEAD(tmp_list); int result; if (ice_fltr_add_eth_to_list(vsi, &tmp_list, ethertype, flag, action)) return -ENOMEM; result = eth_action(vsi, &tmp_list); ice_fltr_free_list(ice_pf_to_dev(vsi->back), &tmp_list); return result; } /** * ice_fltr_add_mac - add single MAC filter * @vsi: pointer to VSI struct * @mac: MAC to add * @action: action to be performed on filter match */ int ice_fltr_add_mac(struct ice_vsi *vsi, const u8 *mac, enum ice_sw_fwd_act_type action) { return ice_fltr_prepare_mac(vsi, mac, action, ice_fltr_add_mac_list); } /** * ice_fltr_add_mac_and_broadcast - add single MAC and broadcast * @vsi: pointer to VSI struct * @mac: MAC to add * @action: action to be performed on filter match */ int ice_fltr_add_mac_and_broadcast(struct ice_vsi *vsi, const u8 *mac, enum ice_sw_fwd_act_type action) { return ice_fltr_prepare_mac_and_broadcast(vsi, mac, action, ice_fltr_add_mac_list); } /** * ice_fltr_remove_mac - remove MAC filter * @vsi: pointer to VSI struct * @mac: filter MAC to remove * @action: action to remove */ int ice_fltr_remove_mac(struct ice_vsi *vsi, const u8 *mac, enum ice_sw_fwd_act_type action) { return ice_fltr_prepare_mac(vsi, mac, action, ice_fltr_remove_mac_list); } /** * ice_fltr_add_vlan - add single VLAN filter * @vsi: pointer to VSI struct * @vlan: VLAN filter details */ int ice_fltr_add_vlan(struct ice_vsi *vsi, struct ice_vlan *vlan) { return ice_fltr_prepare_vlan(vsi, vlan, ice_fltr_add_vlan_list); } /** * ice_fltr_remove_vlan - remove VLAN filter * @vsi: pointer to VSI struct * @vlan: VLAN filter details */ int ice_fltr_remove_vlan(struct ice_vsi *vsi, struct ice_vlan *vlan) { return ice_fltr_prepare_vlan(vsi, vlan, ice_fltr_remove_vlan_list); } /** * ice_fltr_add_eth - add specyfic ethertype filter * @vsi: pointer to VSI struct * @ethertype: ethertype of filter * @flag: direction of packet to be filtered, Tx or Rx * @action: action to be performed on filter match */ int ice_fltr_add_eth(struct ice_vsi *vsi, u16 ethertype, u16 flag, enum ice_sw_fwd_act_type action) { return ice_fltr_prepare_eth(vsi, ethertype, flag, action, ice_fltr_add_eth_list); } /** * ice_fltr_remove_eth - remove ethertype filter * @vsi: pointer to VSI struct * @ethertype: ethertype of filter * @flag: direction of filter * @action: action to remove */ int ice_fltr_remove_eth(struct ice_vsi *vsi, u16 ethertype, u16 flag, enum ice_sw_fwd_act_type action) { return ice_fltr_prepare_eth(vsi, ethertype, flag, action, ice_fltr_remove_eth_list); }
linux-master
drivers/net/ethernet/intel/ice/ice_fltr.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2022, Intel Corporation. */ #include "ice_vf_lib_private.h" #include "ice.h" #include "ice_lib.h" #include "ice_fltr.h" #include "ice_virtchnl_allowlist.h" /* Public functions which may be accessed by all driver files */ /** * ice_get_vf_by_id - Get pointer to VF by ID * @pf: the PF private structure * @vf_id: the VF ID to locate * * Locate and return a pointer to the VF structure associated with a given ID. * Returns NULL if the ID does not have a valid VF structure associated with * it. * * This function takes a reference to the VF, which must be released by * calling ice_put_vf() once the caller is finished accessing the VF structure * returned. */ struct ice_vf *ice_get_vf_by_id(struct ice_pf *pf, u16 vf_id) { struct ice_vf *vf; rcu_read_lock(); hash_for_each_possible_rcu(pf->vfs.table, vf, entry, vf_id) { if (vf->vf_id == vf_id) { struct ice_vf *found; if (kref_get_unless_zero(&vf->refcnt)) found = vf; else found = NULL; rcu_read_unlock(); return found; } } rcu_read_unlock(); return NULL; } /** * ice_release_vf - Release VF associated with a refcount * @ref: the kref decremented to zero * * Callback function for kref_put to release a VF once its reference count has * hit zero. */ static void ice_release_vf(struct kref *ref) { struct ice_vf *vf = container_of(ref, struct ice_vf, refcnt); vf->vf_ops->free(vf); } /** * ice_put_vf - Release a reference to a VF * @vf: the VF structure to decrease reference count on * * Decrease the reference count for a VF, and free the entry if it is no * longer in use. * * This must be called after ice_get_vf_by_id() once the reference to the VF * structure is no longer used. Otherwise, the VF structure will never be * freed. */ void ice_put_vf(struct ice_vf *vf) { kref_put(&vf->refcnt, ice_release_vf); } /** * ice_has_vfs - Return true if the PF has any associated VFs * @pf: the PF private structure * * Return whether or not the PF has any allocated VFs. * * Note that this function only guarantees that there are no VFs at the point * of calling it. It does not guarantee that no more VFs will be added. */ bool ice_has_vfs(struct ice_pf *pf) { /* A simple check that the hash table is not empty does not require * the mutex or rcu_read_lock. */ return !hash_empty(pf->vfs.table); } /** * ice_get_num_vfs - Get number of allocated VFs * @pf: the PF private structure * * Return the total number of allocated VFs. NOTE: VF IDs are not guaranteed * to be contiguous. Do not assume that a VF ID is guaranteed to be less than * the output of this function. */ u16 ice_get_num_vfs(struct ice_pf *pf) { struct ice_vf *vf; unsigned int bkt; u16 num_vfs = 0; rcu_read_lock(); ice_for_each_vf_rcu(pf, bkt, vf) num_vfs++; rcu_read_unlock(); return num_vfs; } /** * ice_get_vf_vsi - get VF's VSI based on the stored index * @vf: VF used to get VSI */ struct ice_vsi *ice_get_vf_vsi(struct ice_vf *vf) { if (vf->lan_vsi_idx == ICE_NO_VSI) return NULL; return vf->pf->vsi[vf->lan_vsi_idx]; } /** * ice_is_vf_disabled * @vf: pointer to the VF info * * If the PF has been disabled, there is no need resetting VF until PF is * active again. Similarly, if the VF has been disabled, this means something * else is resetting the VF, so we shouldn't continue. * * Returns true if the caller should consider the VF as disabled whether * because that single VF is explicitly disabled or because the PF is * currently disabled. */ bool ice_is_vf_disabled(struct ice_vf *vf) { struct ice_pf *pf = vf->pf; return (test_bit(ICE_VF_DIS, pf->state) || test_bit(ICE_VF_STATE_DIS, vf->vf_states)); } /** * ice_wait_on_vf_reset - poll to make sure a given VF is ready after reset * @vf: The VF being resseting * * The max poll time is about ~800ms, which is about the maximum time it takes * for a VF to be reset and/or a VF driver to be removed. */ static void ice_wait_on_vf_reset(struct ice_vf *vf) { int i; for (i = 0; i < ICE_MAX_VF_RESET_TRIES; i++) { if (test_bit(ICE_VF_STATE_INIT, vf->vf_states)) break; msleep(ICE_MAX_VF_RESET_SLEEP_MS); } } /** * ice_check_vf_ready_for_cfg - check if VF is ready to be configured/queried * @vf: VF to check if it's ready to be configured/queried * * The purpose of this function is to make sure the VF is not in reset, not * disabled, and initialized so it can be configured and/or queried by a host * administrator. */ int ice_check_vf_ready_for_cfg(struct ice_vf *vf) { ice_wait_on_vf_reset(vf); if (ice_is_vf_disabled(vf)) return -EINVAL; if (ice_check_vf_init(vf)) return -EBUSY; return 0; } /** * ice_trigger_vf_reset - Reset a VF on HW * @vf: pointer to the VF structure * @is_vflr: true if VFLR was issued, false if not * @is_pfr: true if the reset was triggered due to a previous PFR * * Trigger hardware to start a reset for a particular VF. Expects the caller * to wait the proper amount of time to allow hardware to reset the VF before * it cleans up and restores VF functionality. */ static void ice_trigger_vf_reset(struct ice_vf *vf, bool is_vflr, bool is_pfr) { /* Inform VF that it is no longer active, as a warning */ clear_bit(ICE_VF_STATE_ACTIVE, vf->vf_states); /* Disable VF's configuration API during reset. The flag is re-enabled * when it's safe again to access VF's VSI. */ clear_bit(ICE_VF_STATE_INIT, vf->vf_states); /* VF_MBX_ARQLEN and VF_MBX_ATQLEN are cleared by PFR, so the driver * needs to clear them in the case of VFR/VFLR. If this is done for * PFR, it can mess up VF resets because the VF driver may already * have started cleanup by the time we get here. */ if (!is_pfr) vf->vf_ops->clear_mbx_register(vf); vf->vf_ops->trigger_reset_register(vf, is_vflr); } static void ice_vf_clear_counters(struct ice_vf *vf) { struct ice_vsi *vsi = ice_get_vf_vsi(vf); if (vsi) vsi->num_vlan = 0; vf->num_mac = 0; memset(&vf->mdd_tx_events, 0, sizeof(vf->mdd_tx_events)); memset(&vf->mdd_rx_events, 0, sizeof(vf->mdd_rx_events)); } /** * ice_vf_pre_vsi_rebuild - tasks to be done prior to VSI rebuild * @vf: VF to perform pre VSI rebuild tasks * * These tasks are items that don't need to be amortized since they are most * likely called in a for loop with all VF(s) in the reset_all_vfs() case. */ static void ice_vf_pre_vsi_rebuild(struct ice_vf *vf) { /* Close any IRQ mapping now */ if (vf->vf_ops->irq_close) vf->vf_ops->irq_close(vf); ice_vf_clear_counters(vf); vf->vf_ops->clear_reset_trigger(vf); } /** * ice_vf_recreate_vsi - Release and re-create the VF's VSI * @vf: VF to recreate the VSI for * * This is only called when a single VF is being reset (i.e. VVF, VFLR, host * VF configuration change, etc) * * It releases and then re-creates a new VSI. */ static int ice_vf_recreate_vsi(struct ice_vf *vf) { struct ice_pf *pf = vf->pf; int err; ice_vf_vsi_release(vf); err = vf->vf_ops->create_vsi(vf); if (err) { dev_err(ice_pf_to_dev(pf), "Failed to recreate the VF%u's VSI, error %d\n", vf->vf_id, err); return err; } return 0; } /** * ice_vf_rebuild_vsi - rebuild the VF's VSI * @vf: VF to rebuild the VSI for * * This is only called when all VF(s) are being reset (i.e. PCIe Reset on the * host, PFR, CORER, etc.). * * It reprograms the VSI configuration back into hardware. */ static int ice_vf_rebuild_vsi(struct ice_vf *vf) { struct ice_vsi *vsi = ice_get_vf_vsi(vf); struct ice_pf *pf = vf->pf; if (WARN_ON(!vsi)) return -EINVAL; if (ice_vsi_rebuild(vsi, ICE_VSI_FLAG_INIT)) { dev_err(ice_pf_to_dev(pf), "failed to rebuild VF %d VSI\n", vf->vf_id); return -EIO; } /* vsi->idx will remain the same in this case so don't update * vf->lan_vsi_idx */ vsi->vsi_num = ice_get_hw_vsi_num(&pf->hw, vsi->idx); vf->lan_vsi_num = vsi->vsi_num; return 0; } /** * ice_vf_rebuild_host_vlan_cfg - add VLAN 0 filter or rebuild the Port VLAN * @vf: VF to add MAC filters for * @vsi: Pointer to VSI * * Called after a VF VSI has been re-added/rebuilt during reset. The PF driver * always re-adds either a VLAN 0 or port VLAN based filter after reset. */ static int ice_vf_rebuild_host_vlan_cfg(struct ice_vf *vf, struct ice_vsi *vsi) { struct ice_vsi_vlan_ops *vlan_ops = ice_get_compat_vsi_vlan_ops(vsi); struct device *dev = ice_pf_to_dev(vf->pf); int err; if (ice_vf_is_port_vlan_ena(vf)) { err = vlan_ops->set_port_vlan(vsi, &vf->port_vlan_info); if (err) { dev_err(dev, "failed to configure port VLAN via VSI parameters for VF %u, error %d\n", vf->vf_id, err); return err; } err = vlan_ops->add_vlan(vsi, &vf->port_vlan_info); } else { err = ice_vsi_add_vlan_zero(vsi); } if (err) { dev_err(dev, "failed to add VLAN %u filter for VF %u during VF rebuild, error %d\n", ice_vf_is_port_vlan_ena(vf) ? ice_vf_get_port_vlan_id(vf) : 0, vf->vf_id, err); return err; } err = vlan_ops->ena_rx_filtering(vsi); if (err) dev_warn(dev, "failed to enable Rx VLAN filtering for VF %d VSI %d during VF rebuild, error %d\n", vf->vf_id, vsi->idx, err); return 0; } /** * ice_vf_rebuild_host_tx_rate_cfg - re-apply the Tx rate limiting configuration * @vf: VF to re-apply the configuration for * * Called after a VF VSI has been re-added/rebuild during reset. The PF driver * needs to re-apply the host configured Tx rate limiting configuration. */ static int ice_vf_rebuild_host_tx_rate_cfg(struct ice_vf *vf) { struct device *dev = ice_pf_to_dev(vf->pf); struct ice_vsi *vsi = ice_get_vf_vsi(vf); int err; if (WARN_ON(!vsi)) return -EINVAL; if (vf->min_tx_rate) { err = ice_set_min_bw_limit(vsi, (u64)vf->min_tx_rate * 1000); if (err) { dev_err(dev, "failed to set min Tx rate to %d Mbps for VF %u, error %d\n", vf->min_tx_rate, vf->vf_id, err); return err; } } if (vf->max_tx_rate) { err = ice_set_max_bw_limit(vsi, (u64)vf->max_tx_rate * 1000); if (err) { dev_err(dev, "failed to set max Tx rate to %d Mbps for VF %u, error %d\n", vf->max_tx_rate, vf->vf_id, err); return err; } } return 0; } /** * ice_vf_set_host_trust_cfg - set trust setting based on pre-reset value * @vf: VF to configure trust setting for */ static void ice_vf_set_host_trust_cfg(struct ice_vf *vf) { assign_bit(ICE_VIRTCHNL_VF_CAP_PRIVILEGE, &vf->vf_caps, vf->trusted); } /** * ice_vf_rebuild_host_mac_cfg - add broadcast and the VF's perm_addr/LAA * @vf: VF to add MAC filters for * * Called after a VF VSI has been re-added/rebuilt during reset. The PF driver * always re-adds a broadcast filter and the VF's perm_addr/LAA after reset. */ static int ice_vf_rebuild_host_mac_cfg(struct ice_vf *vf) { struct device *dev = ice_pf_to_dev(vf->pf); struct ice_vsi *vsi = ice_get_vf_vsi(vf); u8 broadcast[ETH_ALEN]; int status; if (WARN_ON(!vsi)) return -EINVAL; if (ice_is_eswitch_mode_switchdev(vf->pf)) return 0; eth_broadcast_addr(broadcast); status = ice_fltr_add_mac(vsi, broadcast, ICE_FWD_TO_VSI); if (status) { dev_err(dev, "failed to add broadcast MAC filter for VF %u, error %d\n", vf->vf_id, status); return status; } vf->num_mac++; if (is_valid_ether_addr(vf->hw_lan_addr)) { status = ice_fltr_add_mac(vsi, vf->hw_lan_addr, ICE_FWD_TO_VSI); if (status) { dev_err(dev, "failed to add default unicast MAC filter %pM for VF %u, error %d\n", &vf->hw_lan_addr[0], vf->vf_id, status); return status; } vf->num_mac++; ether_addr_copy(vf->dev_lan_addr, vf->hw_lan_addr); } return 0; } /** * ice_vf_rebuild_aggregator_node_cfg - rebuild aggregator node config * @vsi: Pointer to VSI * * This function moves VSI into corresponding scheduler aggregator node * based on cached value of "aggregator node info" per VSI */ static void ice_vf_rebuild_aggregator_node_cfg(struct ice_vsi *vsi) { struct ice_pf *pf = vsi->back; struct device *dev; int status; if (!vsi->agg_node) return; dev = ice_pf_to_dev(pf); if (vsi->agg_node->num_vsis == ICE_MAX_VSIS_IN_AGG_NODE) { dev_dbg(dev, "agg_id %u already has reached max_num_vsis %u\n", vsi->agg_node->agg_id, vsi->agg_node->num_vsis); return; } status = ice_move_vsi_to_agg(pf->hw.port_info, vsi->agg_node->agg_id, vsi->idx, vsi->tc_cfg.ena_tc); if (status) dev_dbg(dev, "unable to move VSI idx %u into aggregator %u node", vsi->idx, vsi->agg_node->agg_id); else vsi->agg_node->num_vsis++; } /** * ice_vf_rebuild_host_cfg - host admin configuration is persistent across reset * @vf: VF to rebuild host configuration on */ static void ice_vf_rebuild_host_cfg(struct ice_vf *vf) { struct device *dev = ice_pf_to_dev(vf->pf); struct ice_vsi *vsi = ice_get_vf_vsi(vf); if (WARN_ON(!vsi)) return; ice_vf_set_host_trust_cfg(vf); if (ice_vf_rebuild_host_mac_cfg(vf)) dev_err(dev, "failed to rebuild default MAC configuration for VF %d\n", vf->vf_id); if (ice_vf_rebuild_host_vlan_cfg(vf, vsi)) dev_err(dev, "failed to rebuild VLAN configuration for VF %u\n", vf->vf_id); if (ice_vf_rebuild_host_tx_rate_cfg(vf)) dev_err(dev, "failed to rebuild Tx rate limiting configuration for VF %u\n", vf->vf_id); if (ice_vsi_apply_spoofchk(vsi, vf->spoofchk)) dev_err(dev, "failed to rebuild spoofchk configuration for VF %d\n", vf->vf_id); /* rebuild aggregator node config for main VF VSI */ ice_vf_rebuild_aggregator_node_cfg(vsi); } /** * ice_set_vf_state_qs_dis - Set VF queues state to disabled * @vf: pointer to the VF structure */ static void ice_set_vf_state_qs_dis(struct ice_vf *vf) { /* Clear Rx/Tx enabled queues flag */ bitmap_zero(vf->txq_ena, ICE_MAX_RSS_QS_PER_VF); bitmap_zero(vf->rxq_ena, ICE_MAX_RSS_QS_PER_VF); clear_bit(ICE_VF_STATE_QS_ENA, vf->vf_states); } /** * ice_vf_set_initialized - VF is ready for VIRTCHNL communication * @vf: VF to set in initialized state * * After this function the VF will be ready to receive/handle the * VIRTCHNL_OP_GET_VF_RESOURCES message */ static void ice_vf_set_initialized(struct ice_vf *vf) { ice_set_vf_state_qs_dis(vf); clear_bit(ICE_VF_STATE_MC_PROMISC, vf->vf_states); clear_bit(ICE_VF_STATE_UC_PROMISC, vf->vf_states); clear_bit(ICE_VF_STATE_DIS, vf->vf_states); set_bit(ICE_VF_STATE_INIT, vf->vf_states); memset(&vf->vlan_v2_caps, 0, sizeof(vf->vlan_v2_caps)); } /** * ice_vf_post_vsi_rebuild - Reset tasks that occur after VSI rebuild * @vf: the VF being reset * * Perform reset tasks which must occur after the VSI has been re-created or * rebuilt during a VF reset. */ static void ice_vf_post_vsi_rebuild(struct ice_vf *vf) { ice_vf_rebuild_host_cfg(vf); ice_vf_set_initialized(vf); vf->vf_ops->post_vsi_rebuild(vf); } /** * ice_is_any_vf_in_unicast_promisc - check if any VF(s) * are in unicast promiscuous mode * @pf: PF structure for accessing VF(s) * * Return false if no VF(s) are in unicast promiscuous mode, * else return true */ bool ice_is_any_vf_in_unicast_promisc(struct ice_pf *pf) { bool is_vf_promisc = false; struct ice_vf *vf; unsigned int bkt; rcu_read_lock(); ice_for_each_vf_rcu(pf, bkt, vf) { /* found a VF that has promiscuous mode configured */ if (test_bit(ICE_VF_STATE_UC_PROMISC, vf->vf_states)) { is_vf_promisc = true; break; } } rcu_read_unlock(); return is_vf_promisc; } /** * ice_vf_get_promisc_masks - Calculate masks for promiscuous modes * @vf: the VF pointer * @vsi: the VSI to configure * @ucast_m: promiscuous mask to apply to unicast * @mcast_m: promiscuous mask to apply to multicast * * Decide which mask should be used for unicast and multicast filter, * based on presence of VLANs */ void ice_vf_get_promisc_masks(struct ice_vf *vf, struct ice_vsi *vsi, u8 *ucast_m, u8 *mcast_m) { if (ice_vf_is_port_vlan_ena(vf) || ice_vsi_has_non_zero_vlans(vsi)) { *mcast_m = ICE_MCAST_VLAN_PROMISC_BITS; *ucast_m = ICE_UCAST_VLAN_PROMISC_BITS; } else { *mcast_m = ICE_MCAST_PROMISC_BITS; *ucast_m = ICE_UCAST_PROMISC_BITS; } } /** * ice_vf_clear_all_promisc_modes - Clear promisc/allmulticast on VF VSI * @vf: the VF pointer * @vsi: the VSI to configure * * Clear all promiscuous/allmulticast filters for a VF */ static int ice_vf_clear_all_promisc_modes(struct ice_vf *vf, struct ice_vsi *vsi) { struct ice_pf *pf = vf->pf; u8 ucast_m, mcast_m; int ret = 0; ice_vf_get_promisc_masks(vf, vsi, &ucast_m, &mcast_m); if (test_bit(ICE_VF_STATE_UC_PROMISC, vf->vf_states)) { if (!test_bit(ICE_FLAG_VF_TRUE_PROMISC_ENA, pf->flags)) { if (ice_is_dflt_vsi_in_use(vsi->port_info)) ret = ice_clear_dflt_vsi(vsi); } else { ret = ice_vf_clear_vsi_promisc(vf, vsi, ucast_m); } if (ret) { dev_err(ice_pf_to_dev(vf->pf), "Disabling promiscuous mode failed\n"); } else { clear_bit(ICE_VF_STATE_UC_PROMISC, vf->vf_states); dev_info(ice_pf_to_dev(vf->pf), "Disabling promiscuous mode succeeded\n"); } } if (test_bit(ICE_VF_STATE_MC_PROMISC, vf->vf_states)) { ret = ice_vf_clear_vsi_promisc(vf, vsi, mcast_m); if (ret) { dev_err(ice_pf_to_dev(vf->pf), "Disabling allmulticast mode failed\n"); } else { clear_bit(ICE_VF_STATE_MC_PROMISC, vf->vf_states); dev_info(ice_pf_to_dev(vf->pf), "Disabling allmulticast mode succeeded\n"); } } return ret; } /** * ice_vf_set_vsi_promisc - Enable promiscuous mode for a VF VSI * @vf: the VF to configure * @vsi: the VF's VSI * @promisc_m: the promiscuous mode to enable */ int ice_vf_set_vsi_promisc(struct ice_vf *vf, struct ice_vsi *vsi, u8 promisc_m) { struct ice_hw *hw = &vsi->back->hw; int status; if (ice_vf_is_port_vlan_ena(vf)) status = ice_fltr_set_vsi_promisc(hw, vsi->idx, promisc_m, ice_vf_get_port_vlan_id(vf)); else if (ice_vsi_has_non_zero_vlans(vsi)) status = ice_fltr_set_vlan_vsi_promisc(hw, vsi, promisc_m); else status = ice_fltr_set_vsi_promisc(hw, vsi->idx, promisc_m, 0); if (status && status != -EEXIST) { dev_err(ice_pf_to_dev(vsi->back), "enable Tx/Rx filter promiscuous mode on VF-%u failed, error: %d\n", vf->vf_id, status); return status; } return 0; } /** * ice_vf_clear_vsi_promisc - Disable promiscuous mode for a VF VSI * @vf: the VF to configure * @vsi: the VF's VSI * @promisc_m: the promiscuous mode to disable */ int ice_vf_clear_vsi_promisc(struct ice_vf *vf, struct ice_vsi *vsi, u8 promisc_m) { struct ice_hw *hw = &vsi->back->hw; int status; if (ice_vf_is_port_vlan_ena(vf)) status = ice_fltr_clear_vsi_promisc(hw, vsi->idx, promisc_m, ice_vf_get_port_vlan_id(vf)); else if (ice_vsi_has_non_zero_vlans(vsi)) status = ice_fltr_clear_vlan_vsi_promisc(hw, vsi, promisc_m); else status = ice_fltr_clear_vsi_promisc(hw, vsi->idx, promisc_m, 0); if (status && status != -ENOENT) { dev_err(ice_pf_to_dev(vsi->back), "disable Tx/Rx filter promiscuous mode on VF-%u failed, error: %d\n", vf->vf_id, status); return status; } return 0; } /** * ice_reset_all_vfs - reset all allocated VFs in one go * @pf: pointer to the PF structure * * Reset all VFs at once, in response to a PF or other device reset. * * First, tell the hardware to reset each VF, then do all the waiting in one * chunk, and finally finish restoring each VF after the wait. This is useful * during PF routines which need to reset all VFs, as otherwise it must perform * these resets in a serialized fashion. */ void ice_reset_all_vfs(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); struct ice_hw *hw = &pf->hw; struct ice_vf *vf; unsigned int bkt; /* If we don't have any VFs, then there is nothing to reset */ if (!ice_has_vfs(pf)) return; mutex_lock(&pf->vfs.table_lock); /* clear all malicious info if the VFs are getting reset */ ice_for_each_vf(pf, bkt, vf) ice_mbx_clear_malvf(&vf->mbx_info); /* If VFs have been disabled, there is no need to reset */ if (test_and_set_bit(ICE_VF_DIS, pf->state)) { mutex_unlock(&pf->vfs.table_lock); return; } /* Begin reset on all VFs at once */ ice_for_each_vf(pf, bkt, vf) ice_trigger_vf_reset(vf, true, true); /* HW requires some time to make sure it can flush the FIFO for a VF * when it resets it. Now that we've triggered all of the VFs, iterate * the table again and wait for each VF to complete. */ ice_for_each_vf(pf, bkt, vf) { if (!vf->vf_ops->poll_reset_status(vf)) { /* Display a warning if at least one VF didn't manage * to reset in time, but continue on with the * operation. */ dev_warn(dev, "VF %u reset check timeout\n", vf->vf_id); break; } } /* free VF resources to begin resetting the VSI state */ ice_for_each_vf(pf, bkt, vf) { mutex_lock(&vf->cfg_lock); vf->driver_caps = 0; ice_vc_set_default_allowlist(vf); ice_vf_fdir_exit(vf); ice_vf_fdir_init(vf); /* clean VF control VSI when resetting VFs since it should be * setup only when VF creates its first FDIR rule. */ if (vf->ctrl_vsi_idx != ICE_NO_VSI) ice_vf_ctrl_invalidate_vsi(vf); ice_vf_pre_vsi_rebuild(vf); ice_vf_rebuild_vsi(vf); ice_vf_post_vsi_rebuild(vf); mutex_unlock(&vf->cfg_lock); } if (ice_is_eswitch_mode_switchdev(pf)) if (ice_eswitch_rebuild(pf)) dev_warn(dev, "eswitch rebuild failed\n"); ice_flush(hw); clear_bit(ICE_VF_DIS, pf->state); mutex_unlock(&pf->vfs.table_lock); } /** * ice_notify_vf_reset - Notify VF of a reset event * @vf: pointer to the VF structure */ static void ice_notify_vf_reset(struct ice_vf *vf) { struct ice_hw *hw = &vf->pf->hw; struct virtchnl_pf_event pfe; /* Bail out if VF is in disabled state, neither initialized, nor active * state - otherwise proceed with notifications */ if ((!test_bit(ICE_VF_STATE_INIT, vf->vf_states) && !test_bit(ICE_VF_STATE_ACTIVE, vf->vf_states)) || test_bit(ICE_VF_STATE_DIS, vf->vf_states)) return; pfe.event = VIRTCHNL_EVENT_RESET_IMPENDING; pfe.severity = PF_EVENT_SEVERITY_CERTAIN_DOOM; ice_aq_send_msg_to_vf(hw, vf->vf_id, VIRTCHNL_OP_EVENT, VIRTCHNL_STATUS_SUCCESS, (u8 *)&pfe, sizeof(pfe), NULL); } /** * ice_reset_vf - Reset a particular VF * @vf: pointer to the VF structure * @flags: flags controlling behavior of the reset * * Flags: * ICE_VF_RESET_VFLR - Indicates a reset is due to VFLR event * ICE_VF_RESET_NOTIFY - Send VF a notification prior to reset * ICE_VF_RESET_LOCK - Acquire VF cfg_lock before resetting * * Returns 0 if the VF is currently in reset, if resets are disabled, or if * the VF resets successfully. Returns an error code if the VF fails to * rebuild. */ int ice_reset_vf(struct ice_vf *vf, u32 flags) { struct ice_pf *pf = vf->pf; struct ice_vsi *vsi; struct device *dev; int err = 0; bool rsd; dev = ice_pf_to_dev(pf); if (flags & ICE_VF_RESET_NOTIFY) ice_notify_vf_reset(vf); if (test_bit(ICE_VF_RESETS_DISABLED, pf->state)) { dev_dbg(dev, "Trying to reset VF %d, but all VF resets are disabled\n", vf->vf_id); return 0; } if (flags & ICE_VF_RESET_LOCK) mutex_lock(&vf->cfg_lock); else lockdep_assert_held(&vf->cfg_lock); if (ice_is_vf_disabled(vf)) { vsi = ice_get_vf_vsi(vf); if (!vsi) { dev_dbg(dev, "VF is already removed\n"); err = -EINVAL; goto out_unlock; } ice_vsi_stop_lan_tx_rings(vsi, ICE_NO_RESET, vf->vf_id); if (ice_vsi_is_rx_queue_active(vsi)) ice_vsi_stop_all_rx_rings(vsi); dev_dbg(dev, "VF is already disabled, there is no need for resetting it, telling VM, all is fine %d\n", vf->vf_id); goto out_unlock; } /* Set VF disable bit state here, before triggering reset */ set_bit(ICE_VF_STATE_DIS, vf->vf_states); ice_trigger_vf_reset(vf, flags & ICE_VF_RESET_VFLR, false); vsi = ice_get_vf_vsi(vf); if (WARN_ON(!vsi)) { err = -EIO; goto out_unlock; } ice_dis_vf_qs(vf); /* Call Disable LAN Tx queue AQ whether or not queues are * enabled. This is needed for successful completion of VFR. */ ice_dis_vsi_txq(vsi->port_info, vsi->idx, 0, 0, NULL, NULL, NULL, vf->vf_ops->reset_type, vf->vf_id, NULL); /* poll VPGEN_VFRSTAT reg to make sure * that reset is complete */ rsd = vf->vf_ops->poll_reset_status(vf); /* Display a warning if VF didn't manage to reset in time, but need to * continue on with the operation. */ if (!rsd) dev_warn(dev, "VF reset check timeout on VF %d\n", vf->vf_id); vf->driver_caps = 0; ice_vc_set_default_allowlist(vf); /* disable promiscuous modes in case they were enabled * ignore any error if disabling process failed */ ice_vf_clear_all_promisc_modes(vf, vsi); ice_vf_fdir_exit(vf); ice_vf_fdir_init(vf); /* clean VF control VSI when resetting VF since it should be setup * only when VF creates its first FDIR rule. */ if (vf->ctrl_vsi_idx != ICE_NO_VSI) ice_vf_ctrl_vsi_release(vf); ice_vf_pre_vsi_rebuild(vf); if (ice_vf_recreate_vsi(vf)) { dev_err(dev, "Failed to release and setup the VF%u's VSI\n", vf->vf_id); err = -EFAULT; goto out_unlock; } ice_vf_post_vsi_rebuild(vf); vsi = ice_get_vf_vsi(vf); if (WARN_ON(!vsi)) { err = -EINVAL; goto out_unlock; } ice_eswitch_update_repr(vsi); /* if the VF has been reset allow it to come up again */ ice_mbx_clear_malvf(&vf->mbx_info); out_unlock: if (flags & ICE_VF_RESET_LOCK) mutex_unlock(&vf->cfg_lock); return err; } /** * ice_set_vf_state_dis - Set VF state to disabled * @vf: pointer to the VF structure */ void ice_set_vf_state_dis(struct ice_vf *vf) { ice_set_vf_state_qs_dis(vf); vf->vf_ops->clear_reset_state(vf); } /* Private functions only accessed from other virtualization files */ /** * ice_initialize_vf_entry - Initialize a VF entry * @vf: pointer to the VF structure */ void ice_initialize_vf_entry(struct ice_vf *vf) { struct ice_pf *pf = vf->pf; struct ice_vfs *vfs; vfs = &pf->vfs; /* assign default capabilities */ vf->spoofchk = true; vf->num_vf_qs = vfs->num_qps_per; ice_vc_set_default_allowlist(vf); ice_virtchnl_set_dflt_ops(vf); /* ctrl_vsi_idx will be set to a valid value only when iAVF * creates its first fdir rule. */ ice_vf_ctrl_invalidate_vsi(vf); ice_vf_fdir_init(vf); /* Initialize mailbox info for this VF */ ice_mbx_init_vf_info(&pf->hw, &vf->mbx_info); mutex_init(&vf->cfg_lock); } /** * ice_dis_vf_qs - Disable the VF queues * @vf: pointer to the VF structure */ void ice_dis_vf_qs(struct ice_vf *vf) { struct ice_vsi *vsi = ice_get_vf_vsi(vf); if (WARN_ON(!vsi)) return; ice_vsi_stop_lan_tx_rings(vsi, ICE_NO_RESET, vf->vf_id); ice_vsi_stop_all_rx_rings(vsi); ice_set_vf_state_qs_dis(vf); } /** * ice_err_to_virt_err - translate errors for VF return code * @err: error return code */ enum virtchnl_status_code ice_err_to_virt_err(int err) { switch (err) { case 0: return VIRTCHNL_STATUS_SUCCESS; case -EINVAL: case -ENODEV: return VIRTCHNL_STATUS_ERR_PARAM; case -ENOMEM: return VIRTCHNL_STATUS_ERR_NO_MEMORY; case -EALREADY: case -EBUSY: case -EIO: case -ENOSPC: return VIRTCHNL_STATUS_ERR_ADMIN_QUEUE_ERROR; default: return VIRTCHNL_STATUS_ERR_NOT_SUPPORTED; } } /** * ice_check_vf_init - helper to check if VF init complete * @vf: the pointer to the VF to check */ int ice_check_vf_init(struct ice_vf *vf) { struct ice_pf *pf = vf->pf; if (!test_bit(ICE_VF_STATE_INIT, vf->vf_states)) { dev_err(ice_pf_to_dev(pf), "VF ID: %u in reset. Try again.\n", vf->vf_id); return -EBUSY; } return 0; } /** * ice_vf_get_port_info - Get the VF's port info structure * @vf: VF used to get the port info structure for */ struct ice_port_info *ice_vf_get_port_info(struct ice_vf *vf) { return vf->pf->hw.port_info; } /** * ice_cfg_mac_antispoof - Configure MAC antispoof checking behavior * @vsi: the VSI to configure * @enable: whether to enable or disable the spoof checking * * Configure a VSI to enable (or disable) spoof checking behavior. */ static int ice_cfg_mac_antispoof(struct ice_vsi *vsi, bool enable) { struct ice_vsi_ctx *ctx; int err; ctx = kzalloc(sizeof(*ctx), GFP_KERNEL); if (!ctx) return -ENOMEM; ctx->info.sec_flags = vsi->info.sec_flags; ctx->info.valid_sections = cpu_to_le16(ICE_AQ_VSI_PROP_SECURITY_VALID); if (enable) ctx->info.sec_flags |= ICE_AQ_VSI_SEC_FLAG_ENA_MAC_ANTI_SPOOF; else ctx->info.sec_flags &= ~ICE_AQ_VSI_SEC_FLAG_ENA_MAC_ANTI_SPOOF; err = ice_update_vsi(&vsi->back->hw, vsi->idx, ctx, NULL); if (err) dev_err(ice_pf_to_dev(vsi->back), "Failed to configure Tx MAC anti-spoof %s for VSI %d, error %d\n", enable ? "ON" : "OFF", vsi->vsi_num, err); else vsi->info.sec_flags = ctx->info.sec_flags; kfree(ctx); return err; } /** * ice_vsi_ena_spoofchk - enable Tx spoof checking for this VSI * @vsi: VSI to enable Tx spoof checking for */ static int ice_vsi_ena_spoofchk(struct ice_vsi *vsi) { struct ice_vsi_vlan_ops *vlan_ops; int err = 0; vlan_ops = ice_get_compat_vsi_vlan_ops(vsi); /* Allow VF with VLAN 0 only to send all tagged traffic */ if (vsi->type != ICE_VSI_VF || ice_vsi_has_non_zero_vlans(vsi)) { err = vlan_ops->ena_tx_filtering(vsi); if (err) return err; } return ice_cfg_mac_antispoof(vsi, true); } /** * ice_vsi_dis_spoofchk - disable Tx spoof checking for this VSI * @vsi: VSI to disable Tx spoof checking for */ static int ice_vsi_dis_spoofchk(struct ice_vsi *vsi) { struct ice_vsi_vlan_ops *vlan_ops; int err; vlan_ops = ice_get_compat_vsi_vlan_ops(vsi); err = vlan_ops->dis_tx_filtering(vsi); if (err) return err; return ice_cfg_mac_antispoof(vsi, false); } /** * ice_vsi_apply_spoofchk - Apply Tx spoof checking setting to a VSI * @vsi: VSI associated to the VF * @enable: whether to enable or disable the spoof checking */ int ice_vsi_apply_spoofchk(struct ice_vsi *vsi, bool enable) { int err; if (enable) err = ice_vsi_ena_spoofchk(vsi); else err = ice_vsi_dis_spoofchk(vsi); return err; } /** * ice_is_vf_trusted * @vf: pointer to the VF info */ bool ice_is_vf_trusted(struct ice_vf *vf) { return test_bit(ICE_VIRTCHNL_VF_CAP_PRIVILEGE, &vf->vf_caps); } /** * ice_vf_has_no_qs_ena - check if the VF has any Rx or Tx queues enabled * @vf: the VF to check * * Returns true if the VF has no Rx and no Tx queues enabled and returns false * otherwise */ bool ice_vf_has_no_qs_ena(struct ice_vf *vf) { return (!bitmap_weight(vf->rxq_ena, ICE_MAX_RSS_QS_PER_VF) && !bitmap_weight(vf->txq_ena, ICE_MAX_RSS_QS_PER_VF)); } /** * ice_is_vf_link_up - check if the VF's link is up * @vf: VF to check if link is up */ bool ice_is_vf_link_up(struct ice_vf *vf) { struct ice_port_info *pi = ice_vf_get_port_info(vf); if (ice_check_vf_init(vf)) return false; if (ice_vf_has_no_qs_ena(vf)) return false; else if (vf->link_forced) return vf->link_up; else return pi->phy.link_info.link_info & ICE_AQ_LINK_UP; } /** * ice_vf_ctrl_invalidate_vsi - invalidate ctrl_vsi_idx to remove VSI access * @vf: VF that control VSI is being invalidated on */ void ice_vf_ctrl_invalidate_vsi(struct ice_vf *vf) { vf->ctrl_vsi_idx = ICE_NO_VSI; } /** * ice_vf_ctrl_vsi_release - invalidate the VF's control VSI after freeing it * @vf: VF that control VSI is being released on */ void ice_vf_ctrl_vsi_release(struct ice_vf *vf) { ice_vsi_release(vf->pf->vsi[vf->ctrl_vsi_idx]); ice_vf_ctrl_invalidate_vsi(vf); } /** * ice_vf_ctrl_vsi_setup - Set up a VF control VSI * @vf: VF to setup control VSI for * * Returns pointer to the successfully allocated VSI struct on success, * otherwise returns NULL on failure. */ struct ice_vsi *ice_vf_ctrl_vsi_setup(struct ice_vf *vf) { struct ice_vsi_cfg_params params = {}; struct ice_pf *pf = vf->pf; struct ice_vsi *vsi; params.type = ICE_VSI_CTRL; params.pi = ice_vf_get_port_info(vf); params.vf = vf; params.flags = ICE_VSI_FLAG_INIT; vsi = ice_vsi_setup(pf, &params); if (!vsi) { dev_err(ice_pf_to_dev(pf), "Failed to create VF control VSI\n"); ice_vf_ctrl_invalidate_vsi(vf); } return vsi; } /** * ice_vf_init_host_cfg - Initialize host admin configuration * @vf: VF to initialize * @vsi: the VSI created at initialization * * Initialize the VF host configuration. Called during VF creation to setup * VLAN 0, add the VF VSI broadcast filter, and setup spoof checking. It * should only be called during VF creation. */ int ice_vf_init_host_cfg(struct ice_vf *vf, struct ice_vsi *vsi) { struct ice_vsi_vlan_ops *vlan_ops; struct ice_pf *pf = vf->pf; u8 broadcast[ETH_ALEN]; struct device *dev; int err; dev = ice_pf_to_dev(pf); err = ice_vsi_add_vlan_zero(vsi); if (err) { dev_warn(dev, "Failed to add VLAN 0 filter for VF %d\n", vf->vf_id); return err; } vlan_ops = ice_get_compat_vsi_vlan_ops(vsi); err = vlan_ops->ena_rx_filtering(vsi); if (err) { dev_warn(dev, "Failed to enable Rx VLAN filtering for VF %d\n", vf->vf_id); return err; } eth_broadcast_addr(broadcast); err = ice_fltr_add_mac(vsi, broadcast, ICE_FWD_TO_VSI); if (err) { dev_err(dev, "Failed to add broadcast MAC filter for VF %d, status %d\n", vf->vf_id, err); return err; } vf->num_mac = 1; err = ice_vsi_apply_spoofchk(vsi, vf->spoofchk); if (err) { dev_warn(dev, "Failed to initialize spoofchk setting for VF %d\n", vf->vf_id); return err; } return 0; } /** * ice_vf_invalidate_vsi - invalidate vsi_idx/vsi_num to remove VSI access * @vf: VF to remove access to VSI for */ void ice_vf_invalidate_vsi(struct ice_vf *vf) { vf->lan_vsi_idx = ICE_NO_VSI; vf->lan_vsi_num = ICE_NO_VSI; } /** * ice_vf_vsi_release - Release the VF VSI and invalidate indexes * @vf: pointer to the VF structure * * Release the VF associated with this VSI and then invalidate the VSI * indexes. */ void ice_vf_vsi_release(struct ice_vf *vf) { struct ice_vsi *vsi = ice_get_vf_vsi(vf); if (WARN_ON(!vsi)) return; ice_vsi_release(vsi); ice_vf_invalidate_vsi(vf); } /** * ice_get_vf_ctrl_vsi - Get first VF control VSI pointer * @pf: the PF private structure * @vsi: pointer to the VSI * * Return first found VF control VSI other than the vsi * passed by parameter. This function is used to determine * whether new resources have to be allocated for control VSI * or they can be shared with existing one. * * Return found VF control VSI pointer other itself. Return * NULL Otherwise. * */ struct ice_vsi *ice_get_vf_ctrl_vsi(struct ice_pf *pf, struct ice_vsi *vsi) { struct ice_vsi *ctrl_vsi = NULL; struct ice_vf *vf; unsigned int bkt; rcu_read_lock(); ice_for_each_vf_rcu(pf, bkt, vf) { if (vf != vsi->vf && vf->ctrl_vsi_idx != ICE_NO_VSI) { ctrl_vsi = pf->vsi[vf->ctrl_vsi_idx]; break; } } rcu_read_unlock(); return ctrl_vsi; }
linux-master
drivers/net/ethernet/intel/ice/ice_vf_lib.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2018-2020, Intel Corporation. */ /* flow director ethtool support for ice */ #include "ice.h" #include "ice_lib.h" #include "ice_fdir.h" #include "ice_flow.h" static struct in6_addr full_ipv6_addr_mask = { .in6_u = { .u6_addr8 = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, } } }; static struct in6_addr zero_ipv6_addr_mask = { .in6_u = { .u6_addr8 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, } } }; /* calls to ice_flow_add_prof require the number of segments in the array * for segs_cnt. In this code that is one more than the index. */ #define TNL_SEG_CNT(_TNL_) ((_TNL_) + 1) /** * ice_fltr_to_ethtool_flow - convert filter type values to ethtool * flow type values * @flow: filter type to be converted * * Returns the corresponding ethtool flow type. */ static int ice_fltr_to_ethtool_flow(enum ice_fltr_ptype flow) { switch (flow) { case ICE_FLTR_PTYPE_NONF_IPV4_TCP: return TCP_V4_FLOW; case ICE_FLTR_PTYPE_NONF_IPV4_UDP: return UDP_V4_FLOW; case ICE_FLTR_PTYPE_NONF_IPV4_SCTP: return SCTP_V4_FLOW; case ICE_FLTR_PTYPE_NONF_IPV4_OTHER: return IPV4_USER_FLOW; case ICE_FLTR_PTYPE_NONF_IPV6_TCP: return TCP_V6_FLOW; case ICE_FLTR_PTYPE_NONF_IPV6_UDP: return UDP_V6_FLOW; case ICE_FLTR_PTYPE_NONF_IPV6_SCTP: return SCTP_V6_FLOW; case ICE_FLTR_PTYPE_NONF_IPV6_OTHER: return IPV6_USER_FLOW; default: /* 0 is undefined ethtool flow */ return 0; } } /** * ice_ethtool_flow_to_fltr - convert ethtool flow type to filter enum * @eth: Ethtool flow type to be converted * * Returns flow enum */ static enum ice_fltr_ptype ice_ethtool_flow_to_fltr(int eth) { switch (eth) { case TCP_V4_FLOW: return ICE_FLTR_PTYPE_NONF_IPV4_TCP; case UDP_V4_FLOW: return ICE_FLTR_PTYPE_NONF_IPV4_UDP; case SCTP_V4_FLOW: return ICE_FLTR_PTYPE_NONF_IPV4_SCTP; case IPV4_USER_FLOW: return ICE_FLTR_PTYPE_NONF_IPV4_OTHER; case TCP_V6_FLOW: return ICE_FLTR_PTYPE_NONF_IPV6_TCP; case UDP_V6_FLOW: return ICE_FLTR_PTYPE_NONF_IPV6_UDP; case SCTP_V6_FLOW: return ICE_FLTR_PTYPE_NONF_IPV6_SCTP; case IPV6_USER_FLOW: return ICE_FLTR_PTYPE_NONF_IPV6_OTHER; default: return ICE_FLTR_PTYPE_NONF_NONE; } } /** * ice_is_mask_valid - check mask field set * @mask: full mask to check * @field: field for which mask should be valid * * If the mask is fully set return true. If it is not valid for field return * false. */ static bool ice_is_mask_valid(u64 mask, u64 field) { return (mask & field) == field; } /** * ice_get_ethtool_fdir_entry - fill ethtool structure with fdir filter data * @hw: hardware structure that contains filter list * @cmd: ethtool command data structure to receive the filter data * * Returns 0 on success and -EINVAL on failure */ int ice_get_ethtool_fdir_entry(struct ice_hw *hw, struct ethtool_rxnfc *cmd) { struct ethtool_rx_flow_spec *fsp; struct ice_fdir_fltr *rule; int ret = 0; u16 idx; fsp = (struct ethtool_rx_flow_spec *)&cmd->fs; mutex_lock(&hw->fdir_fltr_lock); rule = ice_fdir_find_fltr_by_idx(hw, fsp->location); if (!rule || fsp->location != rule->fltr_id) { ret = -EINVAL; goto release_lock; } fsp->flow_type = ice_fltr_to_ethtool_flow(rule->flow_type); memset(&fsp->m_u, 0, sizeof(fsp->m_u)); memset(&fsp->m_ext, 0, sizeof(fsp->m_ext)); switch (fsp->flow_type) { case IPV4_USER_FLOW: fsp->h_u.usr_ip4_spec.ip_ver = ETH_RX_NFC_IP4; fsp->h_u.usr_ip4_spec.proto = 0; fsp->h_u.usr_ip4_spec.l4_4_bytes = rule->ip.v4.l4_header; fsp->h_u.usr_ip4_spec.tos = rule->ip.v4.tos; fsp->h_u.usr_ip4_spec.ip4src = rule->ip.v4.src_ip; fsp->h_u.usr_ip4_spec.ip4dst = rule->ip.v4.dst_ip; fsp->m_u.usr_ip4_spec.ip4src = rule->mask.v4.src_ip; fsp->m_u.usr_ip4_spec.ip4dst = rule->mask.v4.dst_ip; fsp->m_u.usr_ip4_spec.ip_ver = 0xFF; fsp->m_u.usr_ip4_spec.proto = 0; fsp->m_u.usr_ip4_spec.l4_4_bytes = rule->mask.v4.l4_header; fsp->m_u.usr_ip4_spec.tos = rule->mask.v4.tos; break; case TCP_V4_FLOW: case UDP_V4_FLOW: case SCTP_V4_FLOW: fsp->h_u.tcp_ip4_spec.psrc = rule->ip.v4.src_port; fsp->h_u.tcp_ip4_spec.pdst = rule->ip.v4.dst_port; fsp->h_u.tcp_ip4_spec.ip4src = rule->ip.v4.src_ip; fsp->h_u.tcp_ip4_spec.ip4dst = rule->ip.v4.dst_ip; fsp->m_u.tcp_ip4_spec.psrc = rule->mask.v4.src_port; fsp->m_u.tcp_ip4_spec.pdst = rule->mask.v4.dst_port; fsp->m_u.tcp_ip4_spec.ip4src = rule->mask.v4.src_ip; fsp->m_u.tcp_ip4_spec.ip4dst = rule->mask.v4.dst_ip; break; case IPV6_USER_FLOW: fsp->h_u.usr_ip6_spec.l4_4_bytes = rule->ip.v6.l4_header; fsp->h_u.usr_ip6_spec.tclass = rule->ip.v6.tc; fsp->h_u.usr_ip6_spec.l4_proto = rule->ip.v6.proto; memcpy(fsp->h_u.tcp_ip6_spec.ip6src, rule->ip.v6.src_ip, sizeof(struct in6_addr)); memcpy(fsp->h_u.tcp_ip6_spec.ip6dst, rule->ip.v6.dst_ip, sizeof(struct in6_addr)); memcpy(fsp->m_u.tcp_ip6_spec.ip6src, rule->mask.v6.src_ip, sizeof(struct in6_addr)); memcpy(fsp->m_u.tcp_ip6_spec.ip6dst, rule->mask.v6.dst_ip, sizeof(struct in6_addr)); fsp->m_u.usr_ip6_spec.l4_4_bytes = rule->mask.v6.l4_header; fsp->m_u.usr_ip6_spec.tclass = rule->mask.v6.tc; fsp->m_u.usr_ip6_spec.l4_proto = rule->mask.v6.proto; break; case TCP_V6_FLOW: case UDP_V6_FLOW: case SCTP_V6_FLOW: memcpy(fsp->h_u.tcp_ip6_spec.ip6src, rule->ip.v6.src_ip, sizeof(struct in6_addr)); memcpy(fsp->h_u.tcp_ip6_spec.ip6dst, rule->ip.v6.dst_ip, sizeof(struct in6_addr)); fsp->h_u.tcp_ip6_spec.psrc = rule->ip.v6.src_port; fsp->h_u.tcp_ip6_spec.pdst = rule->ip.v6.dst_port; memcpy(fsp->m_u.tcp_ip6_spec.ip6src, rule->mask.v6.src_ip, sizeof(struct in6_addr)); memcpy(fsp->m_u.tcp_ip6_spec.ip6dst, rule->mask.v6.dst_ip, sizeof(struct in6_addr)); fsp->m_u.tcp_ip6_spec.psrc = rule->mask.v6.src_port; fsp->m_u.tcp_ip6_spec.pdst = rule->mask.v6.dst_port; fsp->h_u.tcp_ip6_spec.tclass = rule->ip.v6.tc; fsp->m_u.tcp_ip6_spec.tclass = rule->mask.v6.tc; break; default: break; } if (rule->dest_ctl == ICE_FLTR_PRGM_DESC_DEST_DROP_PKT) fsp->ring_cookie = RX_CLS_FLOW_DISC; else fsp->ring_cookie = rule->orig_q_index; idx = ice_ethtool_flow_to_fltr(fsp->flow_type); if (idx == ICE_FLTR_PTYPE_NONF_NONE) { dev_err(ice_hw_to_dev(hw), "Missing input index for flow_type %d\n", rule->flow_type); ret = -EINVAL; } release_lock: mutex_unlock(&hw->fdir_fltr_lock); return ret; } /** * ice_get_fdir_fltr_ids - fill buffer with filter IDs of active filters * @hw: hardware structure containing the filter list * @cmd: ethtool command data structure * @rule_locs: ethtool array passed in from OS to receive filter IDs * * Returns 0 as expected for success by ethtool */ int ice_get_fdir_fltr_ids(struct ice_hw *hw, struct ethtool_rxnfc *cmd, u32 *rule_locs) { struct ice_fdir_fltr *f_rule; unsigned int cnt = 0; int val = 0; /* report total rule count */ cmd->data = ice_get_fdir_cnt_all(hw); mutex_lock(&hw->fdir_fltr_lock); list_for_each_entry(f_rule, &hw->fdir_list_head, fltr_node) { if (cnt == cmd->rule_cnt) { val = -EMSGSIZE; goto release_lock; } rule_locs[cnt] = f_rule->fltr_id; cnt++; } release_lock: mutex_unlock(&hw->fdir_fltr_lock); if (!val) cmd->rule_cnt = cnt; return val; } /** * ice_fdir_remap_entries - update the FDir entries in profile * @prof: FDir structure pointer * @tun: tunneled or non-tunneled packet * @idx: FDir entry index */ static void ice_fdir_remap_entries(struct ice_fd_hw_prof *prof, int tun, int idx) { if (idx != prof->cnt && tun < ICE_FD_HW_SEG_MAX) { int i; for (i = idx; i < (prof->cnt - 1); i++) { u64 old_entry_h; old_entry_h = prof->entry_h[i + 1][tun]; prof->entry_h[i][tun] = old_entry_h; prof->vsi_h[i] = prof->vsi_h[i + 1]; } prof->entry_h[i][tun] = 0; prof->vsi_h[i] = 0; } } /** * ice_fdir_rem_adq_chnl - remove an ADQ channel from HW filter rules * @hw: hardware structure containing filter list * @vsi_idx: VSI handle */ void ice_fdir_rem_adq_chnl(struct ice_hw *hw, u16 vsi_idx) { int status, flow; if (!hw->fdir_prof) return; for (flow = 0; flow < ICE_FLTR_PTYPE_MAX; flow++) { struct ice_fd_hw_prof *prof = hw->fdir_prof[flow]; int tun, i; if (!prof || !prof->cnt) continue; for (tun = 0; tun < ICE_FD_HW_SEG_MAX; tun++) { u64 prof_id; prof_id = flow + tun * ICE_FLTR_PTYPE_MAX; for (i = 0; i < prof->cnt; i++) { if (prof->vsi_h[i] != vsi_idx) continue; prof->entry_h[i][tun] = 0; prof->vsi_h[i] = 0; break; } /* after clearing FDir entries update the remaining */ ice_fdir_remap_entries(prof, tun, i); /* find flow profile corresponding to prof_id and clear * vsi_idx from bitmap. */ status = ice_flow_rem_vsi_prof(hw, vsi_idx, prof_id); if (status) { dev_err(ice_hw_to_dev(hw), "ice_flow_rem_vsi_prof() failed status=%d\n", status); } } prof->cnt--; } } /** * ice_fdir_get_hw_prof - return the ice_fd_hw_proc associated with a flow * @hw: hardware structure containing the filter list * @blk: hardware block * @flow: FDir flow type to release */ static struct ice_fd_hw_prof * ice_fdir_get_hw_prof(struct ice_hw *hw, enum ice_block blk, int flow) { if (blk == ICE_BLK_FD && hw->fdir_prof) return hw->fdir_prof[flow]; return NULL; } /** * ice_fdir_erase_flow_from_hw - remove a flow from the HW profile tables * @hw: hardware structure containing the filter list * @blk: hardware block * @flow: FDir flow type to release */ static void ice_fdir_erase_flow_from_hw(struct ice_hw *hw, enum ice_block blk, int flow) { struct ice_fd_hw_prof *prof = ice_fdir_get_hw_prof(hw, blk, flow); int tun; if (!prof) return; for (tun = 0; tun < ICE_FD_HW_SEG_MAX; tun++) { u64 prof_id; int j; prof_id = flow + tun * ICE_FLTR_PTYPE_MAX; for (j = 0; j < prof->cnt; j++) { u16 vsi_num; if (!prof->entry_h[j][tun] || !prof->vsi_h[j]) continue; vsi_num = ice_get_hw_vsi_num(hw, prof->vsi_h[j]); ice_rem_prof_id_flow(hw, blk, vsi_num, prof_id); ice_flow_rem_entry(hw, blk, prof->entry_h[j][tun]); prof->entry_h[j][tun] = 0; } ice_flow_rem_prof(hw, blk, prof_id); } } /** * ice_fdir_rem_flow - release the ice_flow structures for a filter type * @hw: hardware structure containing the filter list * @blk: hardware block * @flow_type: FDir flow type to release */ static void ice_fdir_rem_flow(struct ice_hw *hw, enum ice_block blk, enum ice_fltr_ptype flow_type) { int flow = (int)flow_type & ~FLOW_EXT; struct ice_fd_hw_prof *prof; int tun, i; prof = ice_fdir_get_hw_prof(hw, blk, flow); if (!prof) return; ice_fdir_erase_flow_from_hw(hw, blk, flow); for (i = 0; i < prof->cnt; i++) prof->vsi_h[i] = 0; for (tun = 0; tun < ICE_FD_HW_SEG_MAX; tun++) { if (!prof->fdir_seg[tun]) continue; devm_kfree(ice_hw_to_dev(hw), prof->fdir_seg[tun]); prof->fdir_seg[tun] = NULL; } prof->cnt = 0; } /** * ice_fdir_release_flows - release all flows in use for later replay * @hw: pointer to HW instance */ void ice_fdir_release_flows(struct ice_hw *hw) { int flow; /* release Flow Director HW table entries */ for (flow = 0; flow < ICE_FLTR_PTYPE_MAX; flow++) ice_fdir_erase_flow_from_hw(hw, ICE_BLK_FD, flow); } /** * ice_fdir_replay_flows - replay HW Flow Director filter info * @hw: pointer to HW instance */ void ice_fdir_replay_flows(struct ice_hw *hw) { int flow; for (flow = 0; flow < ICE_FLTR_PTYPE_MAX; flow++) { int tun; if (!hw->fdir_prof[flow] || !hw->fdir_prof[flow]->cnt) continue; for (tun = 0; tun < ICE_FD_HW_SEG_MAX; tun++) { struct ice_flow_prof *hw_prof; struct ice_fd_hw_prof *prof; u64 prof_id; int j; prof = hw->fdir_prof[flow]; prof_id = flow + tun * ICE_FLTR_PTYPE_MAX; ice_flow_add_prof(hw, ICE_BLK_FD, ICE_FLOW_RX, prof_id, prof->fdir_seg[tun], TNL_SEG_CNT(tun), &hw_prof); for (j = 0; j < prof->cnt; j++) { enum ice_flow_priority prio; u64 entry_h = 0; int err; prio = ICE_FLOW_PRIO_NORMAL; err = ice_flow_add_entry(hw, ICE_BLK_FD, prof_id, prof->vsi_h[0], prof->vsi_h[j], prio, prof->fdir_seg, &entry_h); if (err) { dev_err(ice_hw_to_dev(hw), "Could not replay Flow Director, flow type %d\n", flow); continue; } prof->entry_h[j][tun] = entry_h; } } } } /** * ice_parse_rx_flow_user_data - deconstruct user-defined data * @fsp: pointer to ethtool Rx flow specification * @data: pointer to userdef data structure for storage * * Returns 0 on success, negative error value on failure */ static int ice_parse_rx_flow_user_data(struct ethtool_rx_flow_spec *fsp, struct ice_rx_flow_userdef *data) { u64 value, mask; memset(data, 0, sizeof(*data)); if (!(fsp->flow_type & FLOW_EXT)) return 0; value = be64_to_cpu(*((__force __be64 *)fsp->h_ext.data)); mask = be64_to_cpu(*((__force __be64 *)fsp->m_ext.data)); if (!mask) return 0; #define ICE_USERDEF_FLEX_WORD_M GENMASK_ULL(15, 0) #define ICE_USERDEF_FLEX_OFFS_S 16 #define ICE_USERDEF_FLEX_OFFS_M GENMASK_ULL(31, ICE_USERDEF_FLEX_OFFS_S) #define ICE_USERDEF_FLEX_FLTR_M GENMASK_ULL(31, 0) /* 0x1fe is the maximum value for offsets stored in the internal * filtering tables. */ #define ICE_USERDEF_FLEX_MAX_OFFS_VAL 0x1fe if (!ice_is_mask_valid(mask, ICE_USERDEF_FLEX_FLTR_M) || value > ICE_USERDEF_FLEX_FLTR_M) return -EINVAL; data->flex_word = value & ICE_USERDEF_FLEX_WORD_M; data->flex_offset = (value & ICE_USERDEF_FLEX_OFFS_M) >> ICE_USERDEF_FLEX_OFFS_S; if (data->flex_offset > ICE_USERDEF_FLEX_MAX_OFFS_VAL) return -EINVAL; data->flex_fltr = true; return 0; } /** * ice_fdir_num_avail_fltr - return the number of unused flow director filters * @hw: pointer to hardware structure * @vsi: software VSI structure * * There are 2 filter pools: guaranteed and best effort(shared). Each VSI can * use filters from either pool. The guaranteed pool is divided between VSIs. * The best effort filter pool is common to all VSIs and is a device shared * resource pool. The number of filters available to this VSI is the sum of * the VSIs guaranteed filter pool and the global available best effort * filter pool. * * Returns the number of available flow director filters to this VSI */ static int ice_fdir_num_avail_fltr(struct ice_hw *hw, struct ice_vsi *vsi) { u16 vsi_num = ice_get_hw_vsi_num(hw, vsi->idx); u16 num_guar; u16 num_be; /* total guaranteed filters assigned to this VSI */ num_guar = vsi->num_gfltr; /* minus the guaranteed filters programed by this VSI */ num_guar -= (rd32(hw, VSIQF_FD_CNT(vsi_num)) & VSIQF_FD_CNT_FD_GCNT_M) >> VSIQF_FD_CNT_FD_GCNT_S; /* total global best effort filters */ num_be = hw->func_caps.fd_fltr_best_effort; /* minus the global best effort filters programmed */ num_be -= (rd32(hw, GLQF_FD_CNT) & GLQF_FD_CNT_FD_BCNT_M) >> GLQF_FD_CNT_FD_BCNT_S; return num_guar + num_be; } /** * ice_fdir_alloc_flow_prof - allocate FDir flow profile structure(s) * @hw: HW structure containing the FDir flow profile structure(s) * @flow: flow type to allocate the flow profile for * * Allocate the fdir_prof and fdir_prof[flow] if not already created. Return 0 * on success and negative on error. */ static int ice_fdir_alloc_flow_prof(struct ice_hw *hw, enum ice_fltr_ptype flow) { if (!hw) return -EINVAL; if (!hw->fdir_prof) { hw->fdir_prof = devm_kcalloc(ice_hw_to_dev(hw), ICE_FLTR_PTYPE_MAX, sizeof(*hw->fdir_prof), GFP_KERNEL); if (!hw->fdir_prof) return -ENOMEM; } if (!hw->fdir_prof[flow]) { hw->fdir_prof[flow] = devm_kzalloc(ice_hw_to_dev(hw), sizeof(**hw->fdir_prof), GFP_KERNEL); if (!hw->fdir_prof[flow]) return -ENOMEM; } return 0; } /** * ice_fdir_prof_vsi_idx - find or insert a vsi_idx in structure * @prof: pointer to flow director HW profile * @vsi_idx: vsi_idx to locate * * return the index of the vsi_idx. if vsi_idx is not found insert it * into the vsi_h table. */ static u16 ice_fdir_prof_vsi_idx(struct ice_fd_hw_prof *prof, int vsi_idx) { u16 idx = 0; for (idx = 0; idx < prof->cnt; idx++) if (prof->vsi_h[idx] == vsi_idx) return idx; if (idx == prof->cnt) prof->vsi_h[prof->cnt++] = vsi_idx; return idx; } /** * ice_fdir_set_hw_fltr_rule - Configure HW tables to generate a FDir rule * @pf: pointer to the PF structure * @seg: protocol header description pointer * @flow: filter enum * @tun: FDir segment to program */ static int ice_fdir_set_hw_fltr_rule(struct ice_pf *pf, struct ice_flow_seg_info *seg, enum ice_fltr_ptype flow, enum ice_fd_hw_seg tun) { struct device *dev = ice_pf_to_dev(pf); struct ice_vsi *main_vsi, *ctrl_vsi; struct ice_flow_seg_info *old_seg; struct ice_flow_prof *prof = NULL; struct ice_fd_hw_prof *hw_prof; struct ice_hw *hw = &pf->hw; u64 entry1_h = 0; u64 entry2_h = 0; bool del_last; u64 prof_id; int err; int idx; main_vsi = ice_get_main_vsi(pf); if (!main_vsi) return -EINVAL; ctrl_vsi = ice_get_ctrl_vsi(pf); if (!ctrl_vsi) return -EINVAL; err = ice_fdir_alloc_flow_prof(hw, flow); if (err) return err; hw_prof = hw->fdir_prof[flow]; old_seg = hw_prof->fdir_seg[tun]; if (old_seg) { /* This flow_type already has a changed input set. * If it matches the requested input set then we are * done. Or, if it's different then it's an error. */ if (!memcmp(old_seg, seg, sizeof(*seg))) return -EEXIST; /* if there are FDir filters using this flow, * then return error. */ if (hw->fdir_fltr_cnt[flow]) { dev_err(dev, "Failed to add filter. Flow director filters on each port must have the same input set.\n"); return -EINVAL; } if (ice_is_arfs_using_perfect_flow(hw, flow)) { dev_err(dev, "aRFS using perfect flow type %d, cannot change input set\n", flow); return -EINVAL; } /* remove HW filter definition */ ice_fdir_rem_flow(hw, ICE_BLK_FD, flow); } /* Adding a profile, but there is only one header supported. * That is the final parameters are 1 header (segment), no * actions (NULL) and zero actions 0. */ prof_id = flow + tun * ICE_FLTR_PTYPE_MAX; err = ice_flow_add_prof(hw, ICE_BLK_FD, ICE_FLOW_RX, prof_id, seg, TNL_SEG_CNT(tun), &prof); if (err) return err; err = ice_flow_add_entry(hw, ICE_BLK_FD, prof_id, main_vsi->idx, main_vsi->idx, ICE_FLOW_PRIO_NORMAL, seg, &entry1_h); if (err) goto err_prof; err = ice_flow_add_entry(hw, ICE_BLK_FD, prof_id, main_vsi->idx, ctrl_vsi->idx, ICE_FLOW_PRIO_NORMAL, seg, &entry2_h); if (err) goto err_entry; hw_prof->fdir_seg[tun] = seg; hw_prof->entry_h[0][tun] = entry1_h; hw_prof->entry_h[1][tun] = entry2_h; hw_prof->vsi_h[0] = main_vsi->idx; hw_prof->vsi_h[1] = ctrl_vsi->idx; if (!hw_prof->cnt) hw_prof->cnt = 2; for (idx = 1; idx < ICE_CHNL_MAX_TC; idx++) { u16 vsi_idx; u16 vsi_h; if (!ice_is_adq_active(pf) || !main_vsi->tc_map_vsi[idx]) continue; entry1_h = 0; vsi_h = main_vsi->tc_map_vsi[idx]->idx; err = ice_flow_add_entry(hw, ICE_BLK_FD, prof_id, main_vsi->idx, vsi_h, ICE_FLOW_PRIO_NORMAL, seg, &entry1_h); if (err) { dev_err(dev, "Could not add Channel VSI %d to flow group\n", idx); goto err_unroll; } vsi_idx = ice_fdir_prof_vsi_idx(hw_prof, main_vsi->tc_map_vsi[idx]->idx); hw_prof->entry_h[vsi_idx][tun] = entry1_h; } return 0; err_unroll: entry1_h = 0; hw_prof->fdir_seg[tun] = NULL; /* The variable del_last will be used to determine when to clean up * the VSI group data. The VSI data is not needed if there are no * segments. */ del_last = true; for (idx = 0; idx < ICE_FD_HW_SEG_MAX; idx++) if (hw_prof->fdir_seg[idx]) { del_last = false; break; } for (idx = 0; idx < hw_prof->cnt; idx++) { u16 vsi_num = ice_get_hw_vsi_num(hw, hw_prof->vsi_h[idx]); if (!hw_prof->entry_h[idx][tun]) continue; ice_rem_prof_id_flow(hw, ICE_BLK_FD, vsi_num, prof_id); ice_flow_rem_entry(hw, ICE_BLK_FD, hw_prof->entry_h[idx][tun]); hw_prof->entry_h[idx][tun] = 0; if (del_last) hw_prof->vsi_h[idx] = 0; } if (del_last) hw_prof->cnt = 0; err_entry: ice_rem_prof_id_flow(hw, ICE_BLK_FD, ice_get_hw_vsi_num(hw, main_vsi->idx), prof_id); ice_flow_rem_entry(hw, ICE_BLK_FD, entry1_h); err_prof: ice_flow_rem_prof(hw, ICE_BLK_FD, prof_id); dev_err(dev, "Failed to add filter. Flow director filters on each port must have the same input set.\n"); return err; } /** * ice_set_init_fdir_seg * @seg: flow segment for programming * @l3_proto: ICE_FLOW_SEG_HDR_IPV4 or ICE_FLOW_SEG_HDR_IPV6 * @l4_proto: ICE_FLOW_SEG_HDR_TCP or ICE_FLOW_SEG_HDR_UDP * * Set the configuration for perfect filters to the provided flow segment for * programming the HW filter. This is to be called only when initializing * filters as this function it assumes no filters exist. */ static int ice_set_init_fdir_seg(struct ice_flow_seg_info *seg, enum ice_flow_seg_hdr l3_proto, enum ice_flow_seg_hdr l4_proto) { enum ice_flow_field src_addr, dst_addr, src_port, dst_port; if (!seg) return -EINVAL; if (l3_proto == ICE_FLOW_SEG_HDR_IPV4) { src_addr = ICE_FLOW_FIELD_IDX_IPV4_SA; dst_addr = ICE_FLOW_FIELD_IDX_IPV4_DA; } else if (l3_proto == ICE_FLOW_SEG_HDR_IPV6) { src_addr = ICE_FLOW_FIELD_IDX_IPV6_SA; dst_addr = ICE_FLOW_FIELD_IDX_IPV6_DA; } else { return -EINVAL; } if (l4_proto == ICE_FLOW_SEG_HDR_TCP) { src_port = ICE_FLOW_FIELD_IDX_TCP_SRC_PORT; dst_port = ICE_FLOW_FIELD_IDX_TCP_DST_PORT; } else if (l4_proto == ICE_FLOW_SEG_HDR_UDP) { src_port = ICE_FLOW_FIELD_IDX_UDP_SRC_PORT; dst_port = ICE_FLOW_FIELD_IDX_UDP_DST_PORT; } else { return -EINVAL; } ICE_FLOW_SET_HDRS(seg, l3_proto | l4_proto); /* IP source address */ ice_flow_set_fld(seg, src_addr, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, false); /* IP destination address */ ice_flow_set_fld(seg, dst_addr, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, false); /* Layer 4 source port */ ice_flow_set_fld(seg, src_port, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, false); /* Layer 4 destination port */ ice_flow_set_fld(seg, dst_port, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, false); return 0; } /** * ice_create_init_fdir_rule * @pf: PF structure * @flow: filter enum * * Return error value or 0 on success. */ static int ice_create_init_fdir_rule(struct ice_pf *pf, enum ice_fltr_ptype flow) { struct ice_flow_seg_info *seg, *tun_seg; struct device *dev = ice_pf_to_dev(pf); struct ice_hw *hw = &pf->hw; int ret; /* if there is already a filter rule for kind return -EINVAL */ if (hw->fdir_prof && hw->fdir_prof[flow] && hw->fdir_prof[flow]->fdir_seg[0]) return -EINVAL; seg = devm_kzalloc(dev, sizeof(*seg), GFP_KERNEL); if (!seg) return -ENOMEM; tun_seg = devm_kcalloc(dev, ICE_FD_HW_SEG_MAX, sizeof(*tun_seg), GFP_KERNEL); if (!tun_seg) { devm_kfree(dev, seg); return -ENOMEM; } if (flow == ICE_FLTR_PTYPE_NONF_IPV4_TCP) ret = ice_set_init_fdir_seg(seg, ICE_FLOW_SEG_HDR_IPV4, ICE_FLOW_SEG_HDR_TCP); else if (flow == ICE_FLTR_PTYPE_NONF_IPV4_UDP) ret = ice_set_init_fdir_seg(seg, ICE_FLOW_SEG_HDR_IPV4, ICE_FLOW_SEG_HDR_UDP); else if (flow == ICE_FLTR_PTYPE_NONF_IPV6_TCP) ret = ice_set_init_fdir_seg(seg, ICE_FLOW_SEG_HDR_IPV6, ICE_FLOW_SEG_HDR_TCP); else if (flow == ICE_FLTR_PTYPE_NONF_IPV6_UDP) ret = ice_set_init_fdir_seg(seg, ICE_FLOW_SEG_HDR_IPV6, ICE_FLOW_SEG_HDR_UDP); else ret = -EINVAL; if (ret) goto err_exit; /* add filter for outer headers */ ret = ice_fdir_set_hw_fltr_rule(pf, seg, flow, ICE_FD_HW_SEG_NON_TUN); if (ret) /* could not write filter, free memory */ goto err_exit; /* make tunneled filter HW entries if possible */ memcpy(&tun_seg[1], seg, sizeof(*seg)); ret = ice_fdir_set_hw_fltr_rule(pf, tun_seg, flow, ICE_FD_HW_SEG_TUN); if (ret) /* could not write tunnel filter, but outer header filter * exists */ devm_kfree(dev, tun_seg); set_bit(flow, hw->fdir_perfect_fltr); return ret; err_exit: devm_kfree(dev, tun_seg); devm_kfree(dev, seg); return -EOPNOTSUPP; } /** * ice_set_fdir_ip4_seg * @seg: flow segment for programming * @tcp_ip4_spec: mask data from ethtool * @l4_proto: Layer 4 protocol to program * @perfect_fltr: only valid on success; returns true if perfect filter, * false if not * * Set the mask data into the flow segment to be used to program HW * table based on provided L4 protocol for IPv4 */ static int ice_set_fdir_ip4_seg(struct ice_flow_seg_info *seg, struct ethtool_tcpip4_spec *tcp_ip4_spec, enum ice_flow_seg_hdr l4_proto, bool *perfect_fltr) { enum ice_flow_field src_port, dst_port; /* make sure we don't have any empty rule */ if (!tcp_ip4_spec->psrc && !tcp_ip4_spec->ip4src && !tcp_ip4_spec->pdst && !tcp_ip4_spec->ip4dst) return -EINVAL; /* filtering on TOS not supported */ if (tcp_ip4_spec->tos) return -EOPNOTSUPP; if (l4_proto == ICE_FLOW_SEG_HDR_TCP) { src_port = ICE_FLOW_FIELD_IDX_TCP_SRC_PORT; dst_port = ICE_FLOW_FIELD_IDX_TCP_DST_PORT; } else if (l4_proto == ICE_FLOW_SEG_HDR_UDP) { src_port = ICE_FLOW_FIELD_IDX_UDP_SRC_PORT; dst_port = ICE_FLOW_FIELD_IDX_UDP_DST_PORT; } else if (l4_proto == ICE_FLOW_SEG_HDR_SCTP) { src_port = ICE_FLOW_FIELD_IDX_SCTP_SRC_PORT; dst_port = ICE_FLOW_FIELD_IDX_SCTP_DST_PORT; } else { return -EOPNOTSUPP; } *perfect_fltr = true; ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_IPV4 | l4_proto); /* IP source address */ if (tcp_ip4_spec->ip4src == htonl(0xFFFFFFFF)) ice_flow_set_fld(seg, ICE_FLOW_FIELD_IDX_IPV4_SA, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, false); else if (!tcp_ip4_spec->ip4src) *perfect_fltr = false; else return -EOPNOTSUPP; /* IP destination address */ if (tcp_ip4_spec->ip4dst == htonl(0xFFFFFFFF)) ice_flow_set_fld(seg, ICE_FLOW_FIELD_IDX_IPV4_DA, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, false); else if (!tcp_ip4_spec->ip4dst) *perfect_fltr = false; else return -EOPNOTSUPP; /* Layer 4 source port */ if (tcp_ip4_spec->psrc == htons(0xFFFF)) ice_flow_set_fld(seg, src_port, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, false); else if (!tcp_ip4_spec->psrc) *perfect_fltr = false; else return -EOPNOTSUPP; /* Layer 4 destination port */ if (tcp_ip4_spec->pdst == htons(0xFFFF)) ice_flow_set_fld(seg, dst_port, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, false); else if (!tcp_ip4_spec->pdst) *perfect_fltr = false; else return -EOPNOTSUPP; return 0; } /** * ice_set_fdir_ip4_usr_seg * @seg: flow segment for programming * @usr_ip4_spec: ethtool userdef packet offset * @perfect_fltr: only valid on success; returns true if perfect filter, * false if not * * Set the offset data into the flow segment to be used to program HW * table for IPv4 */ static int ice_set_fdir_ip4_usr_seg(struct ice_flow_seg_info *seg, struct ethtool_usrip4_spec *usr_ip4_spec, bool *perfect_fltr) { /* first 4 bytes of Layer 4 header */ if (usr_ip4_spec->l4_4_bytes) return -EINVAL; if (usr_ip4_spec->tos) return -EINVAL; if (usr_ip4_spec->ip_ver) return -EINVAL; /* Filtering on Layer 4 protocol not supported */ if (usr_ip4_spec->proto) return -EOPNOTSUPP; /* empty rules are not valid */ if (!usr_ip4_spec->ip4src && !usr_ip4_spec->ip4dst) return -EINVAL; *perfect_fltr = true; ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_IPV4); /* IP source address */ if (usr_ip4_spec->ip4src == htonl(0xFFFFFFFF)) ice_flow_set_fld(seg, ICE_FLOW_FIELD_IDX_IPV4_SA, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, false); else if (!usr_ip4_spec->ip4src) *perfect_fltr = false; else return -EOPNOTSUPP; /* IP destination address */ if (usr_ip4_spec->ip4dst == htonl(0xFFFFFFFF)) ice_flow_set_fld(seg, ICE_FLOW_FIELD_IDX_IPV4_DA, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, false); else if (!usr_ip4_spec->ip4dst) *perfect_fltr = false; else return -EOPNOTSUPP; return 0; } /** * ice_set_fdir_ip6_seg * @seg: flow segment for programming * @tcp_ip6_spec: mask data from ethtool * @l4_proto: Layer 4 protocol to program * @perfect_fltr: only valid on success; returns true if perfect filter, * false if not * * Set the mask data into the flow segment to be used to program HW * table based on provided L4 protocol for IPv6 */ static int ice_set_fdir_ip6_seg(struct ice_flow_seg_info *seg, struct ethtool_tcpip6_spec *tcp_ip6_spec, enum ice_flow_seg_hdr l4_proto, bool *perfect_fltr) { enum ice_flow_field src_port, dst_port; /* make sure we don't have any empty rule */ if (!memcmp(tcp_ip6_spec->ip6src, &zero_ipv6_addr_mask, sizeof(struct in6_addr)) && !memcmp(tcp_ip6_spec->ip6dst, &zero_ipv6_addr_mask, sizeof(struct in6_addr)) && !tcp_ip6_spec->psrc && !tcp_ip6_spec->pdst) return -EINVAL; /* filtering on TC not supported */ if (tcp_ip6_spec->tclass) return -EOPNOTSUPP; if (l4_proto == ICE_FLOW_SEG_HDR_TCP) { src_port = ICE_FLOW_FIELD_IDX_TCP_SRC_PORT; dst_port = ICE_FLOW_FIELD_IDX_TCP_DST_PORT; } else if (l4_proto == ICE_FLOW_SEG_HDR_UDP) { src_port = ICE_FLOW_FIELD_IDX_UDP_SRC_PORT; dst_port = ICE_FLOW_FIELD_IDX_UDP_DST_PORT; } else if (l4_proto == ICE_FLOW_SEG_HDR_SCTP) { src_port = ICE_FLOW_FIELD_IDX_SCTP_SRC_PORT; dst_port = ICE_FLOW_FIELD_IDX_SCTP_DST_PORT; } else { return -EINVAL; } *perfect_fltr = true; ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_IPV6 | l4_proto); if (!memcmp(tcp_ip6_spec->ip6src, &full_ipv6_addr_mask, sizeof(struct in6_addr))) ice_flow_set_fld(seg, ICE_FLOW_FIELD_IDX_IPV6_SA, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, false); else if (!memcmp(tcp_ip6_spec->ip6src, &zero_ipv6_addr_mask, sizeof(struct in6_addr))) *perfect_fltr = false; else return -EOPNOTSUPP; if (!memcmp(tcp_ip6_spec->ip6dst, &full_ipv6_addr_mask, sizeof(struct in6_addr))) ice_flow_set_fld(seg, ICE_FLOW_FIELD_IDX_IPV6_DA, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, false); else if (!memcmp(tcp_ip6_spec->ip6dst, &zero_ipv6_addr_mask, sizeof(struct in6_addr))) *perfect_fltr = false; else return -EOPNOTSUPP; /* Layer 4 source port */ if (tcp_ip6_spec->psrc == htons(0xFFFF)) ice_flow_set_fld(seg, src_port, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, false); else if (!tcp_ip6_spec->psrc) *perfect_fltr = false; else return -EOPNOTSUPP; /* Layer 4 destination port */ if (tcp_ip6_spec->pdst == htons(0xFFFF)) ice_flow_set_fld(seg, dst_port, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, false); else if (!tcp_ip6_spec->pdst) *perfect_fltr = false; else return -EOPNOTSUPP; return 0; } /** * ice_set_fdir_ip6_usr_seg * @seg: flow segment for programming * @usr_ip6_spec: ethtool userdef packet offset * @perfect_fltr: only valid on success; returns true if perfect filter, * false if not * * Set the offset data into the flow segment to be used to program HW * table for IPv6 */ static int ice_set_fdir_ip6_usr_seg(struct ice_flow_seg_info *seg, struct ethtool_usrip6_spec *usr_ip6_spec, bool *perfect_fltr) { /* filtering on Layer 4 bytes not supported */ if (usr_ip6_spec->l4_4_bytes) return -EOPNOTSUPP; /* filtering on TC not supported */ if (usr_ip6_spec->tclass) return -EOPNOTSUPP; /* filtering on Layer 4 protocol not supported */ if (usr_ip6_spec->l4_proto) return -EOPNOTSUPP; /* empty rules are not valid */ if (!memcmp(usr_ip6_spec->ip6src, &zero_ipv6_addr_mask, sizeof(struct in6_addr)) && !memcmp(usr_ip6_spec->ip6dst, &zero_ipv6_addr_mask, sizeof(struct in6_addr))) return -EINVAL; *perfect_fltr = true; ICE_FLOW_SET_HDRS(seg, ICE_FLOW_SEG_HDR_IPV6); if (!memcmp(usr_ip6_spec->ip6src, &full_ipv6_addr_mask, sizeof(struct in6_addr))) ice_flow_set_fld(seg, ICE_FLOW_FIELD_IDX_IPV6_SA, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, false); else if (!memcmp(usr_ip6_spec->ip6src, &zero_ipv6_addr_mask, sizeof(struct in6_addr))) *perfect_fltr = false; else return -EOPNOTSUPP; if (!memcmp(usr_ip6_spec->ip6dst, &full_ipv6_addr_mask, sizeof(struct in6_addr))) ice_flow_set_fld(seg, ICE_FLOW_FIELD_IDX_IPV6_DA, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, false); else if (!memcmp(usr_ip6_spec->ip6dst, &zero_ipv6_addr_mask, sizeof(struct in6_addr))) *perfect_fltr = false; else return -EOPNOTSUPP; return 0; } /** * ice_cfg_fdir_xtrct_seq - Configure extraction sequence for the given filter * @pf: PF structure * @fsp: pointer to ethtool Rx flow specification * @user: user defined data from flow specification * * Returns 0 on success. */ static int ice_cfg_fdir_xtrct_seq(struct ice_pf *pf, struct ethtool_rx_flow_spec *fsp, struct ice_rx_flow_userdef *user) { struct ice_flow_seg_info *seg, *tun_seg; struct device *dev = ice_pf_to_dev(pf); enum ice_fltr_ptype fltr_idx; struct ice_hw *hw = &pf->hw; bool perfect_filter; int ret; seg = devm_kzalloc(dev, sizeof(*seg), GFP_KERNEL); if (!seg) return -ENOMEM; tun_seg = devm_kcalloc(dev, ICE_FD_HW_SEG_MAX, sizeof(*tun_seg), GFP_KERNEL); if (!tun_seg) { devm_kfree(dev, seg); return -ENOMEM; } switch (fsp->flow_type & ~FLOW_EXT) { case TCP_V4_FLOW: ret = ice_set_fdir_ip4_seg(seg, &fsp->m_u.tcp_ip4_spec, ICE_FLOW_SEG_HDR_TCP, &perfect_filter); break; case UDP_V4_FLOW: ret = ice_set_fdir_ip4_seg(seg, &fsp->m_u.tcp_ip4_spec, ICE_FLOW_SEG_HDR_UDP, &perfect_filter); break; case SCTP_V4_FLOW: ret = ice_set_fdir_ip4_seg(seg, &fsp->m_u.tcp_ip4_spec, ICE_FLOW_SEG_HDR_SCTP, &perfect_filter); break; case IPV4_USER_FLOW: ret = ice_set_fdir_ip4_usr_seg(seg, &fsp->m_u.usr_ip4_spec, &perfect_filter); break; case TCP_V6_FLOW: ret = ice_set_fdir_ip6_seg(seg, &fsp->m_u.tcp_ip6_spec, ICE_FLOW_SEG_HDR_TCP, &perfect_filter); break; case UDP_V6_FLOW: ret = ice_set_fdir_ip6_seg(seg, &fsp->m_u.tcp_ip6_spec, ICE_FLOW_SEG_HDR_UDP, &perfect_filter); break; case SCTP_V6_FLOW: ret = ice_set_fdir_ip6_seg(seg, &fsp->m_u.tcp_ip6_spec, ICE_FLOW_SEG_HDR_SCTP, &perfect_filter); break; case IPV6_USER_FLOW: ret = ice_set_fdir_ip6_usr_seg(seg, &fsp->m_u.usr_ip6_spec, &perfect_filter); break; default: ret = -EINVAL; } if (ret) goto err_exit; /* tunnel segments are shifted up one. */ memcpy(&tun_seg[1], seg, sizeof(*seg)); if (user && user->flex_fltr) { perfect_filter = false; ice_flow_add_fld_raw(seg, user->flex_offset, ICE_FLTR_PRGM_FLEX_WORD_SIZE, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL); ice_flow_add_fld_raw(&tun_seg[1], user->flex_offset, ICE_FLTR_PRGM_FLEX_WORD_SIZE, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL); } fltr_idx = ice_ethtool_flow_to_fltr(fsp->flow_type & ~FLOW_EXT); assign_bit(fltr_idx, hw->fdir_perfect_fltr, perfect_filter); /* add filter for outer headers */ ret = ice_fdir_set_hw_fltr_rule(pf, seg, fltr_idx, ICE_FD_HW_SEG_NON_TUN); if (ret == -EEXIST) { /* Rule already exists, free memory and count as success */ ret = 0; goto err_exit; } else if (ret) { /* could not write filter, free memory */ goto err_exit; } /* make tunneled filter HW entries if possible */ memcpy(&tun_seg[1], seg, sizeof(*seg)); ret = ice_fdir_set_hw_fltr_rule(pf, tun_seg, fltr_idx, ICE_FD_HW_SEG_TUN); if (ret == -EEXIST) { /* Rule already exists, free memory and count as success */ devm_kfree(dev, tun_seg); ret = 0; } else if (ret) { /* could not write tunnel filter, but outer filter exists */ devm_kfree(dev, tun_seg); } return ret; err_exit: devm_kfree(dev, tun_seg); devm_kfree(dev, seg); return ret; } /** * ice_update_per_q_fltr * @vsi: ptr to VSI * @q_index: queue index * @inc: true to increment or false to decrement per queue filter count * * This function is used to keep track of per queue sideband filters */ static void ice_update_per_q_fltr(struct ice_vsi *vsi, u32 q_index, bool inc) { struct ice_rx_ring *rx_ring; if (!vsi->num_rxq || q_index >= vsi->num_rxq) return; rx_ring = vsi->rx_rings[q_index]; if (!rx_ring || !rx_ring->ch) return; if (inc) atomic_inc(&rx_ring->ch->num_sb_fltr); else atomic_dec_if_positive(&rx_ring->ch->num_sb_fltr); } /** * ice_fdir_write_fltr - send a flow director filter to the hardware * @pf: PF data structure * @input: filter structure * @add: true adds filter and false removed filter * @is_tun: true adds inner filter on tunnel and false outer headers * * returns 0 on success and negative value on error */ int ice_fdir_write_fltr(struct ice_pf *pf, struct ice_fdir_fltr *input, bool add, bool is_tun) { struct device *dev = ice_pf_to_dev(pf); struct ice_hw *hw = &pf->hw; struct ice_fltr_desc desc; struct ice_vsi *ctrl_vsi; u8 *pkt, *frag_pkt; bool has_frag; int err; ctrl_vsi = ice_get_ctrl_vsi(pf); if (!ctrl_vsi) return -EINVAL; pkt = devm_kzalloc(dev, ICE_FDIR_MAX_RAW_PKT_SIZE, GFP_KERNEL); if (!pkt) return -ENOMEM; frag_pkt = devm_kzalloc(dev, ICE_FDIR_MAX_RAW_PKT_SIZE, GFP_KERNEL); if (!frag_pkt) { err = -ENOMEM; goto err_free; } ice_fdir_get_prgm_desc(hw, input, &desc, add); err = ice_fdir_get_gen_prgm_pkt(hw, input, pkt, false, is_tun); if (err) goto err_free_all; err = ice_prgm_fdir_fltr(ctrl_vsi, &desc, pkt); if (err) goto err_free_all; /* repeat for fragment packet */ has_frag = ice_fdir_has_frag(input->flow_type); if (has_frag) { /* does not return error */ ice_fdir_get_prgm_desc(hw, input, &desc, add); err = ice_fdir_get_gen_prgm_pkt(hw, input, frag_pkt, true, is_tun); if (err) goto err_frag; err = ice_prgm_fdir_fltr(ctrl_vsi, &desc, frag_pkt); if (err) goto err_frag; } else { devm_kfree(dev, frag_pkt); } return 0; err_free_all: devm_kfree(dev, frag_pkt); err_free: devm_kfree(dev, pkt); return err; err_frag: devm_kfree(dev, frag_pkt); return err; } /** * ice_fdir_write_all_fltr - send a flow director filter to the hardware * @pf: PF data structure * @input: filter structure * @add: true adds filter and false removed filter * * returns 0 on success and negative value on error */ static int ice_fdir_write_all_fltr(struct ice_pf *pf, struct ice_fdir_fltr *input, bool add) { u16 port_num; int tun; for (tun = 0; tun < ICE_FD_HW_SEG_MAX; tun++) { bool is_tun = tun == ICE_FD_HW_SEG_TUN; int err; if (is_tun && !ice_get_open_tunnel_port(&pf->hw, &port_num, TNL_ALL)) continue; err = ice_fdir_write_fltr(pf, input, add, is_tun); if (err) return err; } return 0; } /** * ice_fdir_replay_fltrs - replay filters from the HW filter list * @pf: board private structure */ void ice_fdir_replay_fltrs(struct ice_pf *pf) { struct ice_fdir_fltr *f_rule; struct ice_hw *hw = &pf->hw; list_for_each_entry(f_rule, &hw->fdir_list_head, fltr_node) { int err = ice_fdir_write_all_fltr(pf, f_rule, true); if (err) dev_dbg(ice_pf_to_dev(pf), "Flow Director error %d, could not reprogram filter %d\n", err, f_rule->fltr_id); } } /** * ice_fdir_create_dflt_rules - create default perfect filters * @pf: PF data structure * * Returns 0 for success or error. */ int ice_fdir_create_dflt_rules(struct ice_pf *pf) { int err; /* Create perfect TCP and UDP rules in hardware. */ err = ice_create_init_fdir_rule(pf, ICE_FLTR_PTYPE_NONF_IPV4_TCP); if (err) return err; err = ice_create_init_fdir_rule(pf, ICE_FLTR_PTYPE_NONF_IPV4_UDP); if (err) return err; err = ice_create_init_fdir_rule(pf, ICE_FLTR_PTYPE_NONF_IPV6_TCP); if (err) return err; err = ice_create_init_fdir_rule(pf, ICE_FLTR_PTYPE_NONF_IPV6_UDP); return err; } /** * ice_fdir_del_all_fltrs - Delete all flow director filters * @vsi: the VSI being changed * * This function needs to be called while holding hw->fdir_fltr_lock */ void ice_fdir_del_all_fltrs(struct ice_vsi *vsi) { struct ice_fdir_fltr *f_rule, *tmp; struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; list_for_each_entry_safe(f_rule, tmp, &hw->fdir_list_head, fltr_node) { ice_fdir_write_all_fltr(pf, f_rule, false); ice_fdir_update_cntrs(hw, f_rule->flow_type, false); list_del(&f_rule->fltr_node); devm_kfree(ice_pf_to_dev(pf), f_rule); } } /** * ice_vsi_manage_fdir - turn on/off flow director * @vsi: the VSI being changed * @ena: boolean value indicating if this is an enable or disable request */ void ice_vsi_manage_fdir(struct ice_vsi *vsi, bool ena) { struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; enum ice_fltr_ptype flow; if (ena) { set_bit(ICE_FLAG_FD_ENA, pf->flags); ice_fdir_create_dflt_rules(pf); return; } mutex_lock(&hw->fdir_fltr_lock); if (!test_and_clear_bit(ICE_FLAG_FD_ENA, pf->flags)) goto release_lock; ice_fdir_del_all_fltrs(vsi); if (hw->fdir_prof) for (flow = ICE_FLTR_PTYPE_NONF_NONE; flow < ICE_FLTR_PTYPE_MAX; flow++) if (hw->fdir_prof[flow]) ice_fdir_rem_flow(hw, ICE_BLK_FD, flow); release_lock: mutex_unlock(&hw->fdir_fltr_lock); } /** * ice_fdir_do_rem_flow - delete flow and possibly add perfect flow * @pf: PF structure * @flow_type: FDir flow type to release */ static void ice_fdir_do_rem_flow(struct ice_pf *pf, enum ice_fltr_ptype flow_type) { struct ice_hw *hw = &pf->hw; bool need_perfect = false; if (flow_type == ICE_FLTR_PTYPE_NONF_IPV4_TCP || flow_type == ICE_FLTR_PTYPE_NONF_IPV4_UDP || flow_type == ICE_FLTR_PTYPE_NONF_IPV6_TCP || flow_type == ICE_FLTR_PTYPE_NONF_IPV6_UDP) need_perfect = true; if (need_perfect && test_bit(flow_type, hw->fdir_perfect_fltr)) return; ice_fdir_rem_flow(hw, ICE_BLK_FD, flow_type); if (need_perfect) ice_create_init_fdir_rule(pf, flow_type); } /** * ice_fdir_update_list_entry - add or delete a filter from the filter list * @pf: PF structure * @input: filter structure * @fltr_idx: ethtool index of filter to modify * * returns 0 on success and negative on errors */ static int ice_fdir_update_list_entry(struct ice_pf *pf, struct ice_fdir_fltr *input, int fltr_idx) { struct ice_fdir_fltr *old_fltr; struct ice_hw *hw = &pf->hw; struct ice_vsi *vsi; int err = -ENOENT; /* Do not update filters during reset */ if (ice_is_reset_in_progress(pf->state)) return -EBUSY; vsi = ice_get_main_vsi(pf); if (!vsi) return -EINVAL; old_fltr = ice_fdir_find_fltr_by_idx(hw, fltr_idx); if (old_fltr) { err = ice_fdir_write_all_fltr(pf, old_fltr, false); if (err) return err; ice_fdir_update_cntrs(hw, old_fltr->flow_type, false); /* update sb-filters count, specific to ring->channel */ ice_update_per_q_fltr(vsi, old_fltr->orig_q_index, false); if (!input && !hw->fdir_fltr_cnt[old_fltr->flow_type]) /* we just deleted the last filter of flow_type so we * should also delete the HW filter info. */ ice_fdir_do_rem_flow(pf, old_fltr->flow_type); list_del(&old_fltr->fltr_node); devm_kfree(ice_hw_to_dev(hw), old_fltr); } if (!input) return err; ice_fdir_list_add_fltr(hw, input); /* update sb-filters count, specific to ring->channel */ ice_update_per_q_fltr(vsi, input->orig_q_index, true); ice_fdir_update_cntrs(hw, input->flow_type, true); return 0; } /** * ice_del_fdir_ethtool - delete Flow Director filter * @vsi: pointer to target VSI * @cmd: command to add or delete Flow Director filter * * Returns 0 on success and negative values for failure */ int ice_del_fdir_ethtool(struct ice_vsi *vsi, struct ethtool_rxnfc *cmd) { struct ethtool_rx_flow_spec *fsp = (struct ethtool_rx_flow_spec *)&cmd->fs; struct ice_pf *pf = vsi->back; struct ice_hw *hw = &pf->hw; int val; if (!test_bit(ICE_FLAG_FD_ENA, pf->flags)) return -EOPNOTSUPP; /* Do not delete filters during reset */ if (ice_is_reset_in_progress(pf->state)) { dev_err(ice_pf_to_dev(pf), "Device is resetting - deleting Flow Director filters not supported during reset\n"); return -EBUSY; } if (test_bit(ICE_FD_FLUSH_REQ, pf->state)) return -EBUSY; mutex_lock(&hw->fdir_fltr_lock); val = ice_fdir_update_list_entry(pf, NULL, fsp->location); mutex_unlock(&hw->fdir_fltr_lock); return val; } /** * ice_update_ring_dest_vsi - update dest ring and dest VSI * @vsi: pointer to target VSI * @dest_vsi: ptr to dest VSI index * @ring: ptr to dest ring * * This function updates destination VSI and queue if user specifies * target queue which falls in channel's (aka ADQ) queue region */ static void ice_update_ring_dest_vsi(struct ice_vsi *vsi, u16 *dest_vsi, u32 *ring) { struct ice_channel *ch; list_for_each_entry(ch, &vsi->ch_list, list) { if (!ch->ch_vsi) continue; /* make sure to locate corresponding channel based on "queue" * specified */ if ((*ring < ch->base_q) || (*ring >= (ch->base_q + ch->num_rxq))) continue; /* update the dest_vsi based on channel */ *dest_vsi = ch->ch_vsi->idx; /* update the "ring" to be correct based on channel */ *ring -= ch->base_q; } } /** * ice_set_fdir_input_set - Set the input set for Flow Director * @vsi: pointer to target VSI * @fsp: pointer to ethtool Rx flow specification * @input: filter structure */ static int ice_set_fdir_input_set(struct ice_vsi *vsi, struct ethtool_rx_flow_spec *fsp, struct ice_fdir_fltr *input) { u16 dest_vsi, q_index = 0; u16 orig_q_index = 0; struct ice_pf *pf; struct ice_hw *hw; int flow_type; u8 dest_ctl; if (!vsi || !fsp || !input) return -EINVAL; pf = vsi->back; hw = &pf->hw; dest_vsi = vsi->idx; if (fsp->ring_cookie == RX_CLS_FLOW_DISC) { dest_ctl = ICE_FLTR_PRGM_DESC_DEST_DROP_PKT; } else { u32 ring = ethtool_get_flow_spec_ring(fsp->ring_cookie); u8 vf = ethtool_get_flow_spec_ring_vf(fsp->ring_cookie); if (vf) { dev_err(ice_pf_to_dev(pf), "Failed to add filter. Flow director filters are not supported on VF queues.\n"); return -EINVAL; } if (ring >= vsi->num_rxq) return -EINVAL; orig_q_index = ring; ice_update_ring_dest_vsi(vsi, &dest_vsi, &ring); dest_ctl = ICE_FLTR_PRGM_DESC_DEST_DIRECT_PKT_QINDEX; q_index = ring; } input->fltr_id = fsp->location; input->q_index = q_index; flow_type = fsp->flow_type & ~FLOW_EXT; /* Record the original queue index as specified by user. * with channel configuration 'q_index' becomes relative * to TC (channel). */ input->orig_q_index = orig_q_index; input->dest_vsi = dest_vsi; input->dest_ctl = dest_ctl; input->fltr_status = ICE_FLTR_PRGM_DESC_FD_STATUS_FD_ID; input->cnt_index = ICE_FD_SB_STAT_IDX(hw->fd_ctr_base); input->flow_type = ice_ethtool_flow_to_fltr(flow_type); if (fsp->flow_type & FLOW_EXT) { memcpy(input->ext_data.usr_def, fsp->h_ext.data, sizeof(input->ext_data.usr_def)); input->ext_data.vlan_type = fsp->h_ext.vlan_etype; input->ext_data.vlan_tag = fsp->h_ext.vlan_tci; memcpy(input->ext_mask.usr_def, fsp->m_ext.data, sizeof(input->ext_mask.usr_def)); input->ext_mask.vlan_type = fsp->m_ext.vlan_etype; input->ext_mask.vlan_tag = fsp->m_ext.vlan_tci; } switch (flow_type) { case TCP_V4_FLOW: case UDP_V4_FLOW: case SCTP_V4_FLOW: input->ip.v4.dst_port = fsp->h_u.tcp_ip4_spec.pdst; input->ip.v4.src_port = fsp->h_u.tcp_ip4_spec.psrc; input->ip.v4.dst_ip = fsp->h_u.tcp_ip4_spec.ip4dst; input->ip.v4.src_ip = fsp->h_u.tcp_ip4_spec.ip4src; input->mask.v4.dst_port = fsp->m_u.tcp_ip4_spec.pdst; input->mask.v4.src_port = fsp->m_u.tcp_ip4_spec.psrc; input->mask.v4.dst_ip = fsp->m_u.tcp_ip4_spec.ip4dst; input->mask.v4.src_ip = fsp->m_u.tcp_ip4_spec.ip4src; break; case IPV4_USER_FLOW: input->ip.v4.dst_ip = fsp->h_u.usr_ip4_spec.ip4dst; input->ip.v4.src_ip = fsp->h_u.usr_ip4_spec.ip4src; input->ip.v4.l4_header = fsp->h_u.usr_ip4_spec.l4_4_bytes; input->ip.v4.proto = fsp->h_u.usr_ip4_spec.proto; input->ip.v4.ip_ver = fsp->h_u.usr_ip4_spec.ip_ver; input->ip.v4.tos = fsp->h_u.usr_ip4_spec.tos; input->mask.v4.dst_ip = fsp->m_u.usr_ip4_spec.ip4dst; input->mask.v4.src_ip = fsp->m_u.usr_ip4_spec.ip4src; input->mask.v4.l4_header = fsp->m_u.usr_ip4_spec.l4_4_bytes; input->mask.v4.proto = fsp->m_u.usr_ip4_spec.proto; input->mask.v4.ip_ver = fsp->m_u.usr_ip4_spec.ip_ver; input->mask.v4.tos = fsp->m_u.usr_ip4_spec.tos; break; case TCP_V6_FLOW: case UDP_V6_FLOW: case SCTP_V6_FLOW: memcpy(input->ip.v6.dst_ip, fsp->h_u.usr_ip6_spec.ip6dst, sizeof(struct in6_addr)); memcpy(input->ip.v6.src_ip, fsp->h_u.usr_ip6_spec.ip6src, sizeof(struct in6_addr)); input->ip.v6.dst_port = fsp->h_u.tcp_ip6_spec.pdst; input->ip.v6.src_port = fsp->h_u.tcp_ip6_spec.psrc; input->ip.v6.tc = fsp->h_u.tcp_ip6_spec.tclass; memcpy(input->mask.v6.dst_ip, fsp->m_u.tcp_ip6_spec.ip6dst, sizeof(struct in6_addr)); memcpy(input->mask.v6.src_ip, fsp->m_u.tcp_ip6_spec.ip6src, sizeof(struct in6_addr)); input->mask.v6.dst_port = fsp->m_u.tcp_ip6_spec.pdst; input->mask.v6.src_port = fsp->m_u.tcp_ip6_spec.psrc; input->mask.v6.tc = fsp->m_u.tcp_ip6_spec.tclass; break; case IPV6_USER_FLOW: memcpy(input->ip.v6.dst_ip, fsp->h_u.usr_ip6_spec.ip6dst, sizeof(struct in6_addr)); memcpy(input->ip.v6.src_ip, fsp->h_u.usr_ip6_spec.ip6src, sizeof(struct in6_addr)); input->ip.v6.l4_header = fsp->h_u.usr_ip6_spec.l4_4_bytes; input->ip.v6.tc = fsp->h_u.usr_ip6_spec.tclass; /* if no protocol requested, use IPPROTO_NONE */ if (!fsp->m_u.usr_ip6_spec.l4_proto) input->ip.v6.proto = IPPROTO_NONE; else input->ip.v6.proto = fsp->h_u.usr_ip6_spec.l4_proto; memcpy(input->mask.v6.dst_ip, fsp->m_u.usr_ip6_spec.ip6dst, sizeof(struct in6_addr)); memcpy(input->mask.v6.src_ip, fsp->m_u.usr_ip6_spec.ip6src, sizeof(struct in6_addr)); input->mask.v6.l4_header = fsp->m_u.usr_ip6_spec.l4_4_bytes; input->mask.v6.tc = fsp->m_u.usr_ip6_spec.tclass; input->mask.v6.proto = fsp->m_u.usr_ip6_spec.l4_proto; break; default: /* not doing un-parsed flow types */ return -EINVAL; } return 0; } /** * ice_add_fdir_ethtool - Add/Remove Flow Director filter * @vsi: pointer to target VSI * @cmd: command to add or delete Flow Director filter * * Returns 0 on success and negative values for failure */ int ice_add_fdir_ethtool(struct ice_vsi *vsi, struct ethtool_rxnfc *cmd) { struct ice_rx_flow_userdef userdata; struct ethtool_rx_flow_spec *fsp; struct ice_fdir_fltr *input; struct device *dev; struct ice_pf *pf; struct ice_hw *hw; int fltrs_needed; u16 tunnel_port; int ret; if (!vsi) return -EINVAL; pf = vsi->back; hw = &pf->hw; dev = ice_pf_to_dev(pf); if (!test_bit(ICE_FLAG_FD_ENA, pf->flags)) return -EOPNOTSUPP; /* Do not program filters during reset */ if (ice_is_reset_in_progress(pf->state)) { dev_err(dev, "Device is resetting - adding Flow Director filters not supported during reset\n"); return -EBUSY; } fsp = (struct ethtool_rx_flow_spec *)&cmd->fs; if (ice_parse_rx_flow_user_data(fsp, &userdata)) return -EINVAL; if (fsp->flow_type & FLOW_MAC_EXT) return -EINVAL; ret = ice_cfg_fdir_xtrct_seq(pf, fsp, &userdata); if (ret) return ret; if (fsp->location >= ice_get_fdir_cnt_all(hw)) { dev_err(dev, "Failed to add filter. The maximum number of flow director filters has been reached.\n"); return -ENOSPC; } /* return error if not an update and no available filters */ fltrs_needed = ice_get_open_tunnel_port(hw, &tunnel_port, TNL_ALL) ? 2 : 1; if (!ice_fdir_find_fltr_by_idx(hw, fsp->location) && ice_fdir_num_avail_fltr(hw, pf->vsi[vsi->idx]) < fltrs_needed) { dev_err(dev, "Failed to add filter. The maximum number of flow director filters has been reached.\n"); return -ENOSPC; } input = devm_kzalloc(dev, sizeof(*input), GFP_KERNEL); if (!input) return -ENOMEM; ret = ice_set_fdir_input_set(vsi, fsp, input); if (ret) goto free_input; mutex_lock(&hw->fdir_fltr_lock); if (ice_fdir_is_dup_fltr(hw, input)) { ret = -EINVAL; goto release_lock; } if (userdata.flex_fltr) { input->flex_fltr = true; input->flex_word = cpu_to_be16(userdata.flex_word); input->flex_offset = userdata.flex_offset; } input->cnt_ena = ICE_FXD_FLTR_QW0_STAT_ENA_PKTS; input->fdid_prio = ICE_FXD_FLTR_QW1_FDID_PRI_THREE; input->comp_report = ICE_FXD_FLTR_QW0_COMP_REPORT_SW_FAIL; /* input struct is added to the HW filter list */ ret = ice_fdir_update_list_entry(pf, input, fsp->location); if (ret) goto release_lock; ret = ice_fdir_write_all_fltr(pf, input, true); if (ret) goto remove_sw_rule; goto release_lock; remove_sw_rule: ice_fdir_update_cntrs(hw, input->flow_type, false); /* update sb-filters count, specific to ring->channel */ ice_update_per_q_fltr(vsi, input->orig_q_index, false); list_del(&input->fltr_node); release_lock: mutex_unlock(&hw->fdir_fltr_lock); free_input: if (ret) devm_kfree(dev, input); return ret; }
linux-master
drivers/net/ethernet/intel/ice/ice_ethtool_fdir.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2019, Intel Corporation. */ #include "ice_common.h" #include "ice_flex_pipe.h" #include "ice_flow.h" #include "ice.h" static const u32 ice_sect_lkup[ICE_BLK_COUNT][ICE_SECT_COUNT] = { /* SWITCH */ { ICE_SID_XLT0_SW, ICE_SID_XLT_KEY_BUILDER_SW, ICE_SID_XLT1_SW, ICE_SID_XLT2_SW, ICE_SID_PROFID_TCAM_SW, ICE_SID_PROFID_REDIR_SW, ICE_SID_FLD_VEC_SW, ICE_SID_CDID_KEY_BUILDER_SW, ICE_SID_CDID_REDIR_SW }, /* ACL */ { ICE_SID_XLT0_ACL, ICE_SID_XLT_KEY_BUILDER_ACL, ICE_SID_XLT1_ACL, ICE_SID_XLT2_ACL, ICE_SID_PROFID_TCAM_ACL, ICE_SID_PROFID_REDIR_ACL, ICE_SID_FLD_VEC_ACL, ICE_SID_CDID_KEY_BUILDER_ACL, ICE_SID_CDID_REDIR_ACL }, /* FD */ { ICE_SID_XLT0_FD, ICE_SID_XLT_KEY_BUILDER_FD, ICE_SID_XLT1_FD, ICE_SID_XLT2_FD, ICE_SID_PROFID_TCAM_FD, ICE_SID_PROFID_REDIR_FD, ICE_SID_FLD_VEC_FD, ICE_SID_CDID_KEY_BUILDER_FD, ICE_SID_CDID_REDIR_FD }, /* RSS */ { ICE_SID_XLT0_RSS, ICE_SID_XLT_KEY_BUILDER_RSS, ICE_SID_XLT1_RSS, ICE_SID_XLT2_RSS, ICE_SID_PROFID_TCAM_RSS, ICE_SID_PROFID_REDIR_RSS, ICE_SID_FLD_VEC_RSS, ICE_SID_CDID_KEY_BUILDER_RSS, ICE_SID_CDID_REDIR_RSS }, /* PE */ { ICE_SID_XLT0_PE, ICE_SID_XLT_KEY_BUILDER_PE, ICE_SID_XLT1_PE, ICE_SID_XLT2_PE, ICE_SID_PROFID_TCAM_PE, ICE_SID_PROFID_REDIR_PE, ICE_SID_FLD_VEC_PE, ICE_SID_CDID_KEY_BUILDER_PE, ICE_SID_CDID_REDIR_PE } }; /** * ice_sect_id - returns section ID * @blk: block type * @sect: section type * * This helper function returns the proper section ID given a block type and a * section type. */ static u32 ice_sect_id(enum ice_block blk, enum ice_sect sect) { return ice_sect_lkup[blk][sect]; } /** * ice_hw_ptype_ena - check if the PTYPE is enabled or not * @hw: pointer to the HW structure * @ptype: the hardware PTYPE */ bool ice_hw_ptype_ena(struct ice_hw *hw, u16 ptype) { return ptype < ICE_FLOW_PTYPE_MAX && test_bit(ptype, hw->hw_ptype); } /* Key creation */ #define ICE_DC_KEY 0x1 /* don't care */ #define ICE_DC_KEYINV 0x1 #define ICE_NM_KEY 0x0 /* never match */ #define ICE_NM_KEYINV 0x0 #define ICE_0_KEY 0x1 /* match 0 */ #define ICE_0_KEYINV 0x0 #define ICE_1_KEY 0x0 /* match 1 */ #define ICE_1_KEYINV 0x1 /** * ice_gen_key_word - generate 16-bits of a key/mask word * @val: the value * @valid: valid bits mask (change only the valid bits) * @dont_care: don't care mask * @nvr_mtch: never match mask * @key: pointer to an array of where the resulting key portion * @key_inv: pointer to an array of where the resulting key invert portion * * This function generates 16-bits from a 8-bit value, an 8-bit don't care mask * and an 8-bit never match mask. The 16-bits of output are divided into 8 bits * of key and 8 bits of key invert. * * '0' = b01, always match a 0 bit * '1' = b10, always match a 1 bit * '?' = b11, don't care bit (always matches) * '~' = b00, never match bit * * Input: * val: b0 1 0 1 0 1 * dont_care: b0 0 1 1 0 0 * never_mtch: b0 0 0 0 1 1 * ------------------------------ * Result: key: b01 10 11 11 00 00 */ static int ice_gen_key_word(u8 val, u8 valid, u8 dont_care, u8 nvr_mtch, u8 *key, u8 *key_inv) { u8 in_key = *key, in_key_inv = *key_inv; u8 i; /* 'dont_care' and 'nvr_mtch' masks cannot overlap */ if ((dont_care ^ nvr_mtch) != (dont_care | nvr_mtch)) return -EIO; *key = 0; *key_inv = 0; /* encode the 8 bits into 8-bit key and 8-bit key invert */ for (i = 0; i < 8; i++) { *key >>= 1; *key_inv >>= 1; if (!(valid & 0x1)) { /* change only valid bits */ *key |= (in_key & 0x1) << 7; *key_inv |= (in_key_inv & 0x1) << 7; } else if (dont_care & 0x1) { /* don't care bit */ *key |= ICE_DC_KEY << 7; *key_inv |= ICE_DC_KEYINV << 7; } else if (nvr_mtch & 0x1) { /* never match bit */ *key |= ICE_NM_KEY << 7; *key_inv |= ICE_NM_KEYINV << 7; } else if (val & 0x01) { /* exact 1 match */ *key |= ICE_1_KEY << 7; *key_inv |= ICE_1_KEYINV << 7; } else { /* exact 0 match */ *key |= ICE_0_KEY << 7; *key_inv |= ICE_0_KEYINV << 7; } dont_care >>= 1; nvr_mtch >>= 1; valid >>= 1; val >>= 1; in_key >>= 1; in_key_inv >>= 1; } return 0; } /** * ice_bits_max_set - determine if the number of bits set is within a maximum * @mask: pointer to the byte array which is the mask * @size: the number of bytes in the mask * @max: the max number of set bits * * This function determines if there are at most 'max' number of bits set in an * array. Returns true if the number for bits set is <= max or will return false * otherwise. */ static bool ice_bits_max_set(const u8 *mask, u16 size, u16 max) { u16 count = 0; u16 i; /* check each byte */ for (i = 0; i < size; i++) { /* if 0, go to next byte */ if (!mask[i]) continue; /* We know there is at least one set bit in this byte because of * the above check; if we already have found 'max' number of * bits set, then we can return failure now. */ if (count == max) return false; /* count the bits in this byte, checking threshold */ count += hweight8(mask[i]); if (count > max) return false; } return true; } /** * ice_set_key - generate a variable sized key with multiples of 16-bits * @key: pointer to where the key will be stored * @size: the size of the complete key in bytes (must be even) * @val: array of 8-bit values that makes up the value portion of the key * @upd: array of 8-bit masks that determine what key portion to update * @dc: array of 8-bit masks that make up the don't care mask * @nm: array of 8-bit masks that make up the never match mask * @off: the offset of the first byte in the key to update * @len: the number of bytes in the key update * * This function generates a key from a value, a don't care mask and a never * match mask. * upd, dc, and nm are optional parameters, and can be NULL: * upd == NULL --> upd mask is all 1's (update all bits) * dc == NULL --> dc mask is all 0's (no don't care bits) * nm == NULL --> nm mask is all 0's (no never match bits) */ static int ice_set_key(u8 *key, u16 size, u8 *val, u8 *upd, u8 *dc, u8 *nm, u16 off, u16 len) { u16 half_size; u16 i; /* size must be a multiple of 2 bytes. */ if (size % 2) return -EIO; half_size = size / 2; if (off + len > half_size) return -EIO; /* Make sure at most one bit is set in the never match mask. Having more * than one never match mask bit set will cause HW to consume excessive * power otherwise; this is a power management efficiency check. */ #define ICE_NVR_MTCH_BITS_MAX 1 if (nm && !ice_bits_max_set(nm, len, ICE_NVR_MTCH_BITS_MAX)) return -EIO; for (i = 0; i < len; i++) if (ice_gen_key_word(val[i], upd ? upd[i] : 0xff, dc ? dc[i] : 0, nm ? nm[i] : 0, key + off + i, key + half_size + off + i)) return -EIO; return 0; } /** * ice_acquire_change_lock * @hw: pointer to the HW structure * @access: access type (read or write) * * This function will request ownership of the change lock. */ int ice_acquire_change_lock(struct ice_hw *hw, enum ice_aq_res_access_type access) { return ice_acquire_res(hw, ICE_CHANGE_LOCK_RES_ID, access, ICE_CHANGE_LOCK_TIMEOUT); } /** * ice_release_change_lock * @hw: pointer to the HW structure * * This function will release the change lock using the proper Admin Command. */ void ice_release_change_lock(struct ice_hw *hw) { ice_release_res(hw, ICE_CHANGE_LOCK_RES_ID); } /** * ice_get_open_tunnel_port - retrieve an open tunnel port * @hw: pointer to the HW structure * @port: returns open port * @type: type of tunnel, can be TNL_LAST if it doesn't matter */ bool ice_get_open_tunnel_port(struct ice_hw *hw, u16 *port, enum ice_tunnel_type type) { bool res = false; u16 i; mutex_lock(&hw->tnl_lock); for (i = 0; i < hw->tnl.count && i < ICE_TUNNEL_MAX_ENTRIES; i++) if (hw->tnl.tbl[i].valid && hw->tnl.tbl[i].port && (type == TNL_LAST || type == hw->tnl.tbl[i].type)) { *port = hw->tnl.tbl[i].port; res = true; break; } mutex_unlock(&hw->tnl_lock); return res; } /** * ice_upd_dvm_boost_entry * @hw: pointer to the HW structure * @entry: pointer to double vlan boost entry info */ static int ice_upd_dvm_boost_entry(struct ice_hw *hw, struct ice_dvm_entry *entry) { struct ice_boost_tcam_section *sect_rx, *sect_tx; int status = -ENOSPC; struct ice_buf_build *bld; u8 val, dc, nm; bld = ice_pkg_buf_alloc(hw); if (!bld) return -ENOMEM; /* allocate 2 sections, one for Rx parser, one for Tx parser */ if (ice_pkg_buf_reserve_section(bld, 2)) goto ice_upd_dvm_boost_entry_err; sect_rx = ice_pkg_buf_alloc_section(bld, ICE_SID_RXPARSER_BOOST_TCAM, struct_size(sect_rx, tcam, 1)); if (!sect_rx) goto ice_upd_dvm_boost_entry_err; sect_rx->count = cpu_to_le16(1); sect_tx = ice_pkg_buf_alloc_section(bld, ICE_SID_TXPARSER_BOOST_TCAM, struct_size(sect_tx, tcam, 1)); if (!sect_tx) goto ice_upd_dvm_boost_entry_err; sect_tx->count = cpu_to_le16(1); /* copy original boost entry to update package buffer */ memcpy(sect_rx->tcam, entry->boost_entry, sizeof(*sect_rx->tcam)); /* re-write the don't care and never match bits accordingly */ if (entry->enable) { /* all bits are don't care */ val = 0x00; dc = 0xFF; nm = 0x00; } else { /* disable, one never match bit, the rest are don't care */ val = 0x00; dc = 0xF7; nm = 0x08; } ice_set_key((u8 *)&sect_rx->tcam[0].key, sizeof(sect_rx->tcam[0].key), &val, NULL, &dc, &nm, 0, sizeof(u8)); /* exact copy of entry to Tx section entry */ memcpy(sect_tx->tcam, sect_rx->tcam, sizeof(*sect_tx->tcam)); status = ice_update_pkg_no_lock(hw, ice_pkg_buf(bld), 1); ice_upd_dvm_boost_entry_err: ice_pkg_buf_free(hw, bld); return status; } /** * ice_set_dvm_boost_entries * @hw: pointer to the HW structure * * Enable double vlan by updating the appropriate boost tcam entries. */ int ice_set_dvm_boost_entries(struct ice_hw *hw) { u16 i; for (i = 0; i < hw->dvm_upd.count; i++) { int status; status = ice_upd_dvm_boost_entry(hw, &hw->dvm_upd.tbl[i]); if (status) return status; } return 0; } /** * ice_tunnel_idx_to_entry - convert linear index to the sparse one * @hw: pointer to the HW structure * @type: type of tunnel * @idx: linear index * * Stack assumes we have 2 linear tables with indexes [0, count_valid), * but really the port table may be sprase, and types are mixed, so convert * the stack index into the device index. */ static u16 ice_tunnel_idx_to_entry(struct ice_hw *hw, enum ice_tunnel_type type, u16 idx) { u16 i; for (i = 0; i < hw->tnl.count && i < ICE_TUNNEL_MAX_ENTRIES; i++) if (hw->tnl.tbl[i].valid && hw->tnl.tbl[i].type == type && idx-- == 0) return i; WARN_ON_ONCE(1); return 0; } /** * ice_create_tunnel * @hw: pointer to the HW structure * @index: device table entry * @type: type of tunnel * @port: port of tunnel to create * * Create a tunnel by updating the parse graph in the parser. We do that by * creating a package buffer with the tunnel info and issuing an update package * command. */ static int ice_create_tunnel(struct ice_hw *hw, u16 index, enum ice_tunnel_type type, u16 port) { struct ice_boost_tcam_section *sect_rx, *sect_tx; struct ice_buf_build *bld; int status = -ENOSPC; mutex_lock(&hw->tnl_lock); bld = ice_pkg_buf_alloc(hw); if (!bld) { status = -ENOMEM; goto ice_create_tunnel_end; } /* allocate 2 sections, one for Rx parser, one for Tx parser */ if (ice_pkg_buf_reserve_section(bld, 2)) goto ice_create_tunnel_err; sect_rx = ice_pkg_buf_alloc_section(bld, ICE_SID_RXPARSER_BOOST_TCAM, struct_size(sect_rx, tcam, 1)); if (!sect_rx) goto ice_create_tunnel_err; sect_rx->count = cpu_to_le16(1); sect_tx = ice_pkg_buf_alloc_section(bld, ICE_SID_TXPARSER_BOOST_TCAM, struct_size(sect_tx, tcam, 1)); if (!sect_tx) goto ice_create_tunnel_err; sect_tx->count = cpu_to_le16(1); /* copy original boost entry to update package buffer */ memcpy(sect_rx->tcam, hw->tnl.tbl[index].boost_entry, sizeof(*sect_rx->tcam)); /* over-write the never-match dest port key bits with the encoded port * bits */ ice_set_key((u8 *)&sect_rx->tcam[0].key, sizeof(sect_rx->tcam[0].key), (u8 *)&port, NULL, NULL, NULL, (u16)offsetof(struct ice_boost_key_value, hv_dst_port_key), sizeof(sect_rx->tcam[0].key.key.hv_dst_port_key)); /* exact copy of entry to Tx section entry */ memcpy(sect_tx->tcam, sect_rx->tcam, sizeof(*sect_tx->tcam)); status = ice_update_pkg(hw, ice_pkg_buf(bld), 1); if (!status) hw->tnl.tbl[index].port = port; ice_create_tunnel_err: ice_pkg_buf_free(hw, bld); ice_create_tunnel_end: mutex_unlock(&hw->tnl_lock); return status; } /** * ice_destroy_tunnel * @hw: pointer to the HW structure * @index: device table entry * @type: type of tunnel * @port: port of tunnel to destroy (ignored if the all parameter is true) * * Destroys a tunnel or all tunnels by creating an update package buffer * targeting the specific updates requested and then performing an update * package. */ static int ice_destroy_tunnel(struct ice_hw *hw, u16 index, enum ice_tunnel_type type, u16 port) { struct ice_boost_tcam_section *sect_rx, *sect_tx; struct ice_buf_build *bld; int status = -ENOSPC; mutex_lock(&hw->tnl_lock); if (WARN_ON(!hw->tnl.tbl[index].valid || hw->tnl.tbl[index].type != type || hw->tnl.tbl[index].port != port)) { status = -EIO; goto ice_destroy_tunnel_end; } bld = ice_pkg_buf_alloc(hw); if (!bld) { status = -ENOMEM; goto ice_destroy_tunnel_end; } /* allocate 2 sections, one for Rx parser, one for Tx parser */ if (ice_pkg_buf_reserve_section(bld, 2)) goto ice_destroy_tunnel_err; sect_rx = ice_pkg_buf_alloc_section(bld, ICE_SID_RXPARSER_BOOST_TCAM, struct_size(sect_rx, tcam, 1)); if (!sect_rx) goto ice_destroy_tunnel_err; sect_rx->count = cpu_to_le16(1); sect_tx = ice_pkg_buf_alloc_section(bld, ICE_SID_TXPARSER_BOOST_TCAM, struct_size(sect_tx, tcam, 1)); if (!sect_tx) goto ice_destroy_tunnel_err; sect_tx->count = cpu_to_le16(1); /* copy original boost entry to update package buffer, one copy to Rx * section, another copy to the Tx section */ memcpy(sect_rx->tcam, hw->tnl.tbl[index].boost_entry, sizeof(*sect_rx->tcam)); memcpy(sect_tx->tcam, hw->tnl.tbl[index].boost_entry, sizeof(*sect_tx->tcam)); status = ice_update_pkg(hw, ice_pkg_buf(bld), 1); if (!status) hw->tnl.tbl[index].port = 0; ice_destroy_tunnel_err: ice_pkg_buf_free(hw, bld); ice_destroy_tunnel_end: mutex_unlock(&hw->tnl_lock); return status; } int ice_udp_tunnel_set_port(struct net_device *netdev, unsigned int table, unsigned int idx, struct udp_tunnel_info *ti) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; struct ice_pf *pf = vsi->back; enum ice_tunnel_type tnl_type; int status; u16 index; tnl_type = ti->type == UDP_TUNNEL_TYPE_VXLAN ? TNL_VXLAN : TNL_GENEVE; index = ice_tunnel_idx_to_entry(&pf->hw, tnl_type, idx); status = ice_create_tunnel(&pf->hw, index, tnl_type, ntohs(ti->port)); if (status) { netdev_err(netdev, "Error adding UDP tunnel - %d\n", status); return -EIO; } udp_tunnel_nic_set_port_priv(netdev, table, idx, index); return 0; } int ice_udp_tunnel_unset_port(struct net_device *netdev, unsigned int table, unsigned int idx, struct udp_tunnel_info *ti) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_vsi *vsi = np->vsi; struct ice_pf *pf = vsi->back; enum ice_tunnel_type tnl_type; int status; tnl_type = ti->type == UDP_TUNNEL_TYPE_VXLAN ? TNL_VXLAN : TNL_GENEVE; status = ice_destroy_tunnel(&pf->hw, ti->hw_priv, tnl_type, ntohs(ti->port)); if (status) { netdev_err(netdev, "Error removing UDP tunnel - %d\n", status); return -EIO; } return 0; } /** * ice_find_prot_off - find prot ID and offset pair, based on prof and FV index * @hw: pointer to the hardware structure * @blk: hardware block * @prof: profile ID * @fv_idx: field vector word index * @prot: variable to receive the protocol ID * @off: variable to receive the protocol offset */ int ice_find_prot_off(struct ice_hw *hw, enum ice_block blk, u8 prof, u16 fv_idx, u8 *prot, u16 *off) { struct ice_fv_word *fv_ext; if (prof >= hw->blk[blk].es.count) return -EINVAL; if (fv_idx >= hw->blk[blk].es.fvw) return -EINVAL; fv_ext = hw->blk[blk].es.t + (prof * hw->blk[blk].es.fvw); *prot = fv_ext[fv_idx].prot_id; *off = fv_ext[fv_idx].off; return 0; } /* PTG Management */ /** * ice_ptg_find_ptype - Search for packet type group using packet type (ptype) * @hw: pointer to the hardware structure * @blk: HW block * @ptype: the ptype to search for * @ptg: pointer to variable that receives the PTG * * This function will search the PTGs for a particular ptype, returning the * PTG ID that contains it through the PTG parameter, with the value of * ICE_DEFAULT_PTG (0) meaning it is part the default PTG. */ static int ice_ptg_find_ptype(struct ice_hw *hw, enum ice_block blk, u16 ptype, u8 *ptg) { if (ptype >= ICE_XLT1_CNT || !ptg) return -EINVAL; *ptg = hw->blk[blk].xlt1.ptypes[ptype].ptg; return 0; } /** * ice_ptg_alloc_val - Allocates a new packet type group ID by value * @hw: pointer to the hardware structure * @blk: HW block * @ptg: the PTG to allocate * * This function allocates a given packet type group ID specified by the PTG * parameter. */ static void ice_ptg_alloc_val(struct ice_hw *hw, enum ice_block blk, u8 ptg) { hw->blk[blk].xlt1.ptg_tbl[ptg].in_use = true; } /** * ice_ptg_remove_ptype - Removes ptype from a particular packet type group * @hw: pointer to the hardware structure * @blk: HW block * @ptype: the ptype to remove * @ptg: the PTG to remove the ptype from * * This function will remove the ptype from the specific PTG, and move it to * the default PTG (ICE_DEFAULT_PTG). */ static int ice_ptg_remove_ptype(struct ice_hw *hw, enum ice_block blk, u16 ptype, u8 ptg) { struct ice_ptg_ptype **ch; struct ice_ptg_ptype *p; if (ptype > ICE_XLT1_CNT - 1) return -EINVAL; if (!hw->blk[blk].xlt1.ptg_tbl[ptg].in_use) return -ENOENT; /* Should not happen if .in_use is set, bad config */ if (!hw->blk[blk].xlt1.ptg_tbl[ptg].first_ptype) return -EIO; /* find the ptype within this PTG, and bypass the link over it */ p = hw->blk[blk].xlt1.ptg_tbl[ptg].first_ptype; ch = &hw->blk[blk].xlt1.ptg_tbl[ptg].first_ptype; while (p) { if (ptype == (p - hw->blk[blk].xlt1.ptypes)) { *ch = p->next_ptype; break; } ch = &p->next_ptype; p = p->next_ptype; } hw->blk[blk].xlt1.ptypes[ptype].ptg = ICE_DEFAULT_PTG; hw->blk[blk].xlt1.ptypes[ptype].next_ptype = NULL; return 0; } /** * ice_ptg_add_mv_ptype - Adds/moves ptype to a particular packet type group * @hw: pointer to the hardware structure * @blk: HW block * @ptype: the ptype to add or move * @ptg: the PTG to add or move the ptype to * * This function will either add or move a ptype to a particular PTG depending * on if the ptype is already part of another group. Note that using a * destination PTG ID of ICE_DEFAULT_PTG (0) will move the ptype to the * default PTG. */ static int ice_ptg_add_mv_ptype(struct ice_hw *hw, enum ice_block blk, u16 ptype, u8 ptg) { u8 original_ptg; int status; if (ptype > ICE_XLT1_CNT - 1) return -EINVAL; if (!hw->blk[blk].xlt1.ptg_tbl[ptg].in_use && ptg != ICE_DEFAULT_PTG) return -ENOENT; status = ice_ptg_find_ptype(hw, blk, ptype, &original_ptg); if (status) return status; /* Is ptype already in the correct PTG? */ if (original_ptg == ptg) return 0; /* Remove from original PTG and move back to the default PTG */ if (original_ptg != ICE_DEFAULT_PTG) ice_ptg_remove_ptype(hw, blk, ptype, original_ptg); /* Moving to default PTG? Then we're done with this request */ if (ptg == ICE_DEFAULT_PTG) return 0; /* Add ptype to PTG at beginning of list */ hw->blk[blk].xlt1.ptypes[ptype].next_ptype = hw->blk[blk].xlt1.ptg_tbl[ptg].first_ptype; hw->blk[blk].xlt1.ptg_tbl[ptg].first_ptype = &hw->blk[blk].xlt1.ptypes[ptype]; hw->blk[blk].xlt1.ptypes[ptype].ptg = ptg; hw->blk[blk].xlt1.t[ptype] = ptg; return 0; } /* Block / table size info */ struct ice_blk_size_details { u16 xlt1; /* # XLT1 entries */ u16 xlt2; /* # XLT2 entries */ u16 prof_tcam; /* # profile ID TCAM entries */ u16 prof_id; /* # profile IDs */ u8 prof_cdid_bits; /* # CDID one-hot bits used in key */ u16 prof_redir; /* # profile redirection entries */ u16 es; /* # extraction sequence entries */ u16 fvw; /* # field vector words */ u8 overwrite; /* overwrite existing entries allowed */ u8 reverse; /* reverse FV order */ }; static const struct ice_blk_size_details blk_sizes[ICE_BLK_COUNT] = { /** * Table Definitions * XLT1 - Number of entries in XLT1 table * XLT2 - Number of entries in XLT2 table * TCAM - Number of entries Profile ID TCAM table * CDID - Control Domain ID of the hardware block * PRED - Number of entries in the Profile Redirection Table * FV - Number of entries in the Field Vector * FVW - Width (in WORDs) of the Field Vector * OVR - Overwrite existing table entries * REV - Reverse FV */ /* XLT1 , XLT2 ,TCAM, PID,CDID,PRED, FV, FVW */ /* Overwrite , Reverse FV */ /* SW */ { ICE_XLT1_CNT, ICE_XLT2_CNT, 512, 256, 0, 256, 256, 48, false, false }, /* ACL */ { ICE_XLT1_CNT, ICE_XLT2_CNT, 512, 128, 0, 128, 128, 32, false, false }, /* FD */ { ICE_XLT1_CNT, ICE_XLT2_CNT, 512, 128, 0, 128, 128, 24, false, true }, /* RSS */ { ICE_XLT1_CNT, ICE_XLT2_CNT, 512, 128, 0, 128, 128, 24, true, true }, /* PE */ { ICE_XLT1_CNT, ICE_XLT2_CNT, 64, 32, 0, 32, 32, 24, false, false }, }; enum ice_sid_all { ICE_SID_XLT1_OFF = 0, ICE_SID_XLT2_OFF, ICE_SID_PR_OFF, ICE_SID_PR_REDIR_OFF, ICE_SID_ES_OFF, ICE_SID_OFF_COUNT, }; /* Characteristic handling */ /** * ice_match_prop_lst - determine if properties of two lists match * @list1: first properties list * @list2: second properties list * * Count, cookies and the order must match in order to be considered equivalent. */ static bool ice_match_prop_lst(struct list_head *list1, struct list_head *list2) { struct ice_vsig_prof *tmp1; struct ice_vsig_prof *tmp2; u16 chk_count = 0; u16 count = 0; /* compare counts */ list_for_each_entry(tmp1, list1, list) count++; list_for_each_entry(tmp2, list2, list) chk_count++; if (!count || count != chk_count) return false; tmp1 = list_first_entry(list1, struct ice_vsig_prof, list); tmp2 = list_first_entry(list2, struct ice_vsig_prof, list); /* profile cookies must compare, and in the exact same order to take * into account priority */ while (count--) { if (tmp2->profile_cookie != tmp1->profile_cookie) return false; tmp1 = list_next_entry(tmp1, list); tmp2 = list_next_entry(tmp2, list); } return true; } /* VSIG Management */ /** * ice_vsig_find_vsi - find a VSIG that contains a specified VSI * @hw: pointer to the hardware structure * @blk: HW block * @vsi: VSI of interest * @vsig: pointer to receive the VSI group * * This function will lookup the VSI entry in the XLT2 list and return * the VSI group its associated with. */ static int ice_vsig_find_vsi(struct ice_hw *hw, enum ice_block blk, u16 vsi, u16 *vsig) { if (!vsig || vsi >= ICE_MAX_VSI) return -EINVAL; /* As long as there's a default or valid VSIG associated with the input * VSI, the functions returns a success. Any handling of VSIG will be * done by the following add, update or remove functions. */ *vsig = hw->blk[blk].xlt2.vsis[vsi].vsig; return 0; } /** * ice_vsig_alloc_val - allocate a new VSIG by value * @hw: pointer to the hardware structure * @blk: HW block * @vsig: the VSIG to allocate * * This function will allocate a given VSIG specified by the VSIG parameter. */ static u16 ice_vsig_alloc_val(struct ice_hw *hw, enum ice_block blk, u16 vsig) { u16 idx = vsig & ICE_VSIG_IDX_M; if (!hw->blk[blk].xlt2.vsig_tbl[idx].in_use) { INIT_LIST_HEAD(&hw->blk[blk].xlt2.vsig_tbl[idx].prop_lst); hw->blk[blk].xlt2.vsig_tbl[idx].in_use = true; } return ICE_VSIG_VALUE(idx, hw->pf_id); } /** * ice_vsig_alloc - Finds a free entry and allocates a new VSIG * @hw: pointer to the hardware structure * @blk: HW block * * This function will iterate through the VSIG list and mark the first * unused entry for the new VSIG entry as used and return that value. */ static u16 ice_vsig_alloc(struct ice_hw *hw, enum ice_block blk) { u16 i; for (i = 1; i < ICE_MAX_VSIGS; i++) if (!hw->blk[blk].xlt2.vsig_tbl[i].in_use) return ice_vsig_alloc_val(hw, blk, i); return ICE_DEFAULT_VSIG; } /** * ice_find_dup_props_vsig - find VSI group with a specified set of properties * @hw: pointer to the hardware structure * @blk: HW block * @chs: characteristic list * @vsig: returns the VSIG with the matching profiles, if found * * Each VSIG is associated with a characteristic set; i.e. all VSIs under * a group have the same characteristic set. To check if there exists a VSIG * which has the same characteristics as the input characteristics; this * function will iterate through the XLT2 list and return the VSIG that has a * matching configuration. In order to make sure that priorities are accounted * for, the list must match exactly, including the order in which the * characteristics are listed. */ static int ice_find_dup_props_vsig(struct ice_hw *hw, enum ice_block blk, struct list_head *chs, u16 *vsig) { struct ice_xlt2 *xlt2 = &hw->blk[blk].xlt2; u16 i; for (i = 0; i < xlt2->count; i++) if (xlt2->vsig_tbl[i].in_use && ice_match_prop_lst(chs, &xlt2->vsig_tbl[i].prop_lst)) { *vsig = ICE_VSIG_VALUE(i, hw->pf_id); return 0; } return -ENOENT; } /** * ice_vsig_free - free VSI group * @hw: pointer to the hardware structure * @blk: HW block * @vsig: VSIG to remove * * The function will remove all VSIs associated with the input VSIG and move * them to the DEFAULT_VSIG and mark the VSIG available. */ static int ice_vsig_free(struct ice_hw *hw, enum ice_block blk, u16 vsig) { struct ice_vsig_prof *dtmp, *del; struct ice_vsig_vsi *vsi_cur; u16 idx; idx = vsig & ICE_VSIG_IDX_M; if (idx >= ICE_MAX_VSIGS) return -EINVAL; if (!hw->blk[blk].xlt2.vsig_tbl[idx].in_use) return -ENOENT; hw->blk[blk].xlt2.vsig_tbl[idx].in_use = false; vsi_cur = hw->blk[blk].xlt2.vsig_tbl[idx].first_vsi; /* If the VSIG has at least 1 VSI then iterate through the * list and remove the VSIs before deleting the group. */ if (vsi_cur) { /* remove all vsis associated with this VSIG XLT2 entry */ do { struct ice_vsig_vsi *tmp = vsi_cur->next_vsi; vsi_cur->vsig = ICE_DEFAULT_VSIG; vsi_cur->changed = 1; vsi_cur->next_vsi = NULL; vsi_cur = tmp; } while (vsi_cur); /* NULL terminate head of VSI list */ hw->blk[blk].xlt2.vsig_tbl[idx].first_vsi = NULL; } /* free characteristic list */ list_for_each_entry_safe(del, dtmp, &hw->blk[blk].xlt2.vsig_tbl[idx].prop_lst, list) { list_del(&del->list); devm_kfree(ice_hw_to_dev(hw), del); } /* if VSIG characteristic list was cleared for reset * re-initialize the list head */ INIT_LIST_HEAD(&hw->blk[blk].xlt2.vsig_tbl[idx].prop_lst); return 0; } /** * ice_vsig_remove_vsi - remove VSI from VSIG * @hw: pointer to the hardware structure * @blk: HW block * @vsi: VSI to remove * @vsig: VSI group to remove from * * The function will remove the input VSI from its VSI group and move it * to the DEFAULT_VSIG. */ static int ice_vsig_remove_vsi(struct ice_hw *hw, enum ice_block blk, u16 vsi, u16 vsig) { struct ice_vsig_vsi **vsi_head, *vsi_cur, *vsi_tgt; u16 idx; idx = vsig & ICE_VSIG_IDX_M; if (vsi >= ICE_MAX_VSI || idx >= ICE_MAX_VSIGS) return -EINVAL; if (!hw->blk[blk].xlt2.vsig_tbl[idx].in_use) return -ENOENT; /* entry already in default VSIG, don't have to remove */ if (idx == ICE_DEFAULT_VSIG) return 0; vsi_head = &hw->blk[blk].xlt2.vsig_tbl[idx].first_vsi; if (!(*vsi_head)) return -EIO; vsi_tgt = &hw->blk[blk].xlt2.vsis[vsi]; vsi_cur = (*vsi_head); /* iterate the VSI list, skip over the entry to be removed */ while (vsi_cur) { if (vsi_tgt == vsi_cur) { (*vsi_head) = vsi_cur->next_vsi; break; } vsi_head = &vsi_cur->next_vsi; vsi_cur = vsi_cur->next_vsi; } /* verify if VSI was removed from group list */ if (!vsi_cur) return -ENOENT; vsi_cur->vsig = ICE_DEFAULT_VSIG; vsi_cur->changed = 1; vsi_cur->next_vsi = NULL; return 0; } /** * ice_vsig_add_mv_vsi - add or move a VSI to a VSI group * @hw: pointer to the hardware structure * @blk: HW block * @vsi: VSI to move * @vsig: destination VSI group * * This function will move or add the input VSI to the target VSIG. * The function will find the original VSIG the VSI belongs to and * move the entry to the DEFAULT_VSIG, update the original VSIG and * then move entry to the new VSIG. */ static int ice_vsig_add_mv_vsi(struct ice_hw *hw, enum ice_block blk, u16 vsi, u16 vsig) { struct ice_vsig_vsi *tmp; u16 orig_vsig, idx; int status; idx = vsig & ICE_VSIG_IDX_M; if (vsi >= ICE_MAX_VSI || idx >= ICE_MAX_VSIGS) return -EINVAL; /* if VSIG not in use and VSIG is not default type this VSIG * doesn't exist. */ if (!hw->blk[blk].xlt2.vsig_tbl[idx].in_use && vsig != ICE_DEFAULT_VSIG) return -ENOENT; status = ice_vsig_find_vsi(hw, blk, vsi, &orig_vsig); if (status) return status; /* no update required if vsigs match */ if (orig_vsig == vsig) return 0; if (orig_vsig != ICE_DEFAULT_VSIG) { /* remove entry from orig_vsig and add to default VSIG */ status = ice_vsig_remove_vsi(hw, blk, vsi, orig_vsig); if (status) return status; } if (idx == ICE_DEFAULT_VSIG) return 0; /* Create VSI entry and add VSIG and prop_mask values */ hw->blk[blk].xlt2.vsis[vsi].vsig = vsig; hw->blk[blk].xlt2.vsis[vsi].changed = 1; /* Add new entry to the head of the VSIG list */ tmp = hw->blk[blk].xlt2.vsig_tbl[idx].first_vsi; hw->blk[blk].xlt2.vsig_tbl[idx].first_vsi = &hw->blk[blk].xlt2.vsis[vsi]; hw->blk[blk].xlt2.vsis[vsi].next_vsi = tmp; hw->blk[blk].xlt2.t[vsi] = vsig; return 0; } /** * ice_prof_has_mask_idx - determine if profile index masking is identical * @hw: pointer to the hardware structure * @blk: HW block * @prof: profile to check * @idx: profile index to check * @mask: mask to match */ static bool ice_prof_has_mask_idx(struct ice_hw *hw, enum ice_block blk, u8 prof, u16 idx, u16 mask) { bool expect_no_mask = false; bool found = false; bool match = false; u16 i; /* If mask is 0x0000 or 0xffff, then there is no masking */ if (mask == 0 || mask == 0xffff) expect_no_mask = true; /* Scan the enabled masks on this profile, for the specified idx */ for (i = hw->blk[blk].masks.first; i < hw->blk[blk].masks.first + hw->blk[blk].masks.count; i++) if (hw->blk[blk].es.mask_ena[prof] & BIT(i)) if (hw->blk[blk].masks.masks[i].in_use && hw->blk[blk].masks.masks[i].idx == idx) { found = true; if (hw->blk[blk].masks.masks[i].mask == mask) match = true; break; } if (expect_no_mask) { if (found) return false; } else { if (!match) return false; } return true; } /** * ice_prof_has_mask - determine if profile masking is identical * @hw: pointer to the hardware structure * @blk: HW block * @prof: profile to check * @masks: masks to match */ static bool ice_prof_has_mask(struct ice_hw *hw, enum ice_block blk, u8 prof, u16 *masks) { u16 i; /* es->mask_ena[prof] will have the mask */ for (i = 0; i < hw->blk[blk].es.fvw; i++) if (!ice_prof_has_mask_idx(hw, blk, prof, i, masks[i])) return false; return true; } /** * ice_find_prof_id_with_mask - find profile ID for a given field vector * @hw: pointer to the hardware structure * @blk: HW block * @fv: field vector to search for * @masks: masks for FV * @prof_id: receives the profile ID */ static int ice_find_prof_id_with_mask(struct ice_hw *hw, enum ice_block blk, struct ice_fv_word *fv, u16 *masks, u8 *prof_id) { struct ice_es *es = &hw->blk[blk].es; u8 i; /* For FD, we don't want to re-use a existed profile with the same * field vector and mask. This will cause rule interference. */ if (blk == ICE_BLK_FD) return -ENOENT; for (i = 0; i < (u8)es->count; i++) { u16 off = i * es->fvw; if (memcmp(&es->t[off], fv, es->fvw * sizeof(*fv))) continue; /* check if masks settings are the same for this profile */ if (masks && !ice_prof_has_mask(hw, blk, i, masks)) continue; *prof_id = i; return 0; } return -ENOENT; } /** * ice_prof_id_rsrc_type - get profile ID resource type for a block type * @blk: the block type * @rsrc_type: pointer to variable to receive the resource type */ static bool ice_prof_id_rsrc_type(enum ice_block blk, u16 *rsrc_type) { switch (blk) { case ICE_BLK_FD: *rsrc_type = ICE_AQC_RES_TYPE_FD_PROF_BLDR_PROFID; break; case ICE_BLK_RSS: *rsrc_type = ICE_AQC_RES_TYPE_HASH_PROF_BLDR_PROFID; break; default: return false; } return true; } /** * ice_tcam_ent_rsrc_type - get TCAM entry resource type for a block type * @blk: the block type * @rsrc_type: pointer to variable to receive the resource type */ static bool ice_tcam_ent_rsrc_type(enum ice_block blk, u16 *rsrc_type) { switch (blk) { case ICE_BLK_FD: *rsrc_type = ICE_AQC_RES_TYPE_FD_PROF_BLDR_TCAM; break; case ICE_BLK_RSS: *rsrc_type = ICE_AQC_RES_TYPE_HASH_PROF_BLDR_TCAM; break; default: return false; } return true; } /** * ice_alloc_tcam_ent - allocate hardware TCAM entry * @hw: pointer to the HW struct * @blk: the block to allocate the TCAM for * @btm: true to allocate from bottom of table, false to allocate from top * @tcam_idx: pointer to variable to receive the TCAM entry * * This function allocates a new entry in a Profile ID TCAM for a specific * block. */ static int ice_alloc_tcam_ent(struct ice_hw *hw, enum ice_block blk, bool btm, u16 *tcam_idx) { u16 res_type; if (!ice_tcam_ent_rsrc_type(blk, &res_type)) return -EINVAL; return ice_alloc_hw_res(hw, res_type, 1, btm, tcam_idx); } /** * ice_free_tcam_ent - free hardware TCAM entry * @hw: pointer to the HW struct * @blk: the block from which to free the TCAM entry * @tcam_idx: the TCAM entry to free * * This function frees an entry in a Profile ID TCAM for a specific block. */ static int ice_free_tcam_ent(struct ice_hw *hw, enum ice_block blk, u16 tcam_idx) { u16 res_type; if (!ice_tcam_ent_rsrc_type(blk, &res_type)) return -EINVAL; return ice_free_hw_res(hw, res_type, 1, &tcam_idx); } /** * ice_alloc_prof_id - allocate profile ID * @hw: pointer to the HW struct * @blk: the block to allocate the profile ID for * @prof_id: pointer to variable to receive the profile ID * * This function allocates a new profile ID, which also corresponds to a Field * Vector (Extraction Sequence) entry. */ static int ice_alloc_prof_id(struct ice_hw *hw, enum ice_block blk, u8 *prof_id) { u16 res_type; u16 get_prof; int status; if (!ice_prof_id_rsrc_type(blk, &res_type)) return -EINVAL; status = ice_alloc_hw_res(hw, res_type, 1, false, &get_prof); if (!status) *prof_id = (u8)get_prof; return status; } /** * ice_free_prof_id - free profile ID * @hw: pointer to the HW struct * @blk: the block from which to free the profile ID * @prof_id: the profile ID to free * * This function frees a profile ID, which also corresponds to a Field Vector. */ static int ice_free_prof_id(struct ice_hw *hw, enum ice_block blk, u8 prof_id) { u16 tmp_prof_id = (u16)prof_id; u16 res_type; if (!ice_prof_id_rsrc_type(blk, &res_type)) return -EINVAL; return ice_free_hw_res(hw, res_type, 1, &tmp_prof_id); } /** * ice_prof_inc_ref - increment reference count for profile * @hw: pointer to the HW struct * @blk: the block from which to free the profile ID * @prof_id: the profile ID for which to increment the reference count */ static int ice_prof_inc_ref(struct ice_hw *hw, enum ice_block blk, u8 prof_id) { if (prof_id > hw->blk[blk].es.count) return -EINVAL; hw->blk[blk].es.ref_count[prof_id]++; return 0; } /** * ice_write_prof_mask_reg - write profile mask register * @hw: pointer to the HW struct * @blk: hardware block * @mask_idx: mask index * @idx: index of the FV which will use the mask * @mask: the 16-bit mask */ static void ice_write_prof_mask_reg(struct ice_hw *hw, enum ice_block blk, u16 mask_idx, u16 idx, u16 mask) { u32 offset; u32 val; switch (blk) { case ICE_BLK_RSS: offset = GLQF_HMASK(mask_idx); val = (idx << GLQF_HMASK_MSK_INDEX_S) & GLQF_HMASK_MSK_INDEX_M; val |= (mask << GLQF_HMASK_MASK_S) & GLQF_HMASK_MASK_M; break; case ICE_BLK_FD: offset = GLQF_FDMASK(mask_idx); val = (idx << GLQF_FDMASK_MSK_INDEX_S) & GLQF_FDMASK_MSK_INDEX_M; val |= (mask << GLQF_FDMASK_MASK_S) & GLQF_FDMASK_MASK_M; break; default: ice_debug(hw, ICE_DBG_PKG, "No profile masks for block %d\n", blk); return; } wr32(hw, offset, val); ice_debug(hw, ICE_DBG_PKG, "write mask, blk %d (%d): %x = %x\n", blk, idx, offset, val); } /** * ice_write_prof_mask_enable_res - write profile mask enable register * @hw: pointer to the HW struct * @blk: hardware block * @prof_id: profile ID * @enable_mask: enable mask */ static void ice_write_prof_mask_enable_res(struct ice_hw *hw, enum ice_block blk, u16 prof_id, u32 enable_mask) { u32 offset; switch (blk) { case ICE_BLK_RSS: offset = GLQF_HMASK_SEL(prof_id); break; case ICE_BLK_FD: offset = GLQF_FDMASK_SEL(prof_id); break; default: ice_debug(hw, ICE_DBG_PKG, "No profile masks for block %d\n", blk); return; } wr32(hw, offset, enable_mask); ice_debug(hw, ICE_DBG_PKG, "write mask enable, blk %d (%d): %x = %x\n", blk, prof_id, offset, enable_mask); } /** * ice_init_prof_masks - initial prof masks * @hw: pointer to the HW struct * @blk: hardware block */ static void ice_init_prof_masks(struct ice_hw *hw, enum ice_block blk) { u16 per_pf; u16 i; mutex_init(&hw->blk[blk].masks.lock); per_pf = ICE_PROF_MASK_COUNT / hw->dev_caps.num_funcs; hw->blk[blk].masks.count = per_pf; hw->blk[blk].masks.first = hw->pf_id * per_pf; memset(hw->blk[blk].masks.masks, 0, sizeof(hw->blk[blk].masks.masks)); for (i = hw->blk[blk].masks.first; i < hw->blk[blk].masks.first + hw->blk[blk].masks.count; i++) ice_write_prof_mask_reg(hw, blk, i, 0, 0); } /** * ice_init_all_prof_masks - initialize all prof masks * @hw: pointer to the HW struct */ static void ice_init_all_prof_masks(struct ice_hw *hw) { ice_init_prof_masks(hw, ICE_BLK_RSS); ice_init_prof_masks(hw, ICE_BLK_FD); } /** * ice_alloc_prof_mask - allocate profile mask * @hw: pointer to the HW struct * @blk: hardware block * @idx: index of FV which will use the mask * @mask: the 16-bit mask * @mask_idx: variable to receive the mask index */ static int ice_alloc_prof_mask(struct ice_hw *hw, enum ice_block blk, u16 idx, u16 mask, u16 *mask_idx) { bool found_unused = false, found_copy = false; u16 unused_idx = 0, copy_idx = 0; int status = -ENOSPC; u16 i; if (blk != ICE_BLK_RSS && blk != ICE_BLK_FD) return -EINVAL; mutex_lock(&hw->blk[blk].masks.lock); for (i = hw->blk[blk].masks.first; i < hw->blk[blk].masks.first + hw->blk[blk].masks.count; i++) if (hw->blk[blk].masks.masks[i].in_use) { /* if mask is in use and it exactly duplicates the * desired mask and index, then in can be reused */ if (hw->blk[blk].masks.masks[i].mask == mask && hw->blk[blk].masks.masks[i].idx == idx) { found_copy = true; copy_idx = i; break; } } else { /* save off unused index, but keep searching in case * there is an exact match later on */ if (!found_unused) { found_unused = true; unused_idx = i; } } if (found_copy) i = copy_idx; else if (found_unused) i = unused_idx; else goto err_ice_alloc_prof_mask; /* update mask for a new entry */ if (found_unused) { hw->blk[blk].masks.masks[i].in_use = true; hw->blk[blk].masks.masks[i].mask = mask; hw->blk[blk].masks.masks[i].idx = idx; hw->blk[blk].masks.masks[i].ref = 0; ice_write_prof_mask_reg(hw, blk, i, idx, mask); } hw->blk[blk].masks.masks[i].ref++; *mask_idx = i; status = 0; err_ice_alloc_prof_mask: mutex_unlock(&hw->blk[blk].masks.lock); return status; } /** * ice_free_prof_mask - free profile mask * @hw: pointer to the HW struct * @blk: hardware block * @mask_idx: index of mask */ static int ice_free_prof_mask(struct ice_hw *hw, enum ice_block blk, u16 mask_idx) { if (blk != ICE_BLK_RSS && blk != ICE_BLK_FD) return -EINVAL; if (!(mask_idx >= hw->blk[blk].masks.first && mask_idx < hw->blk[blk].masks.first + hw->blk[blk].masks.count)) return -ENOENT; mutex_lock(&hw->blk[blk].masks.lock); if (!hw->blk[blk].masks.masks[mask_idx].in_use) goto exit_ice_free_prof_mask; if (hw->blk[blk].masks.masks[mask_idx].ref > 1) { hw->blk[blk].masks.masks[mask_idx].ref--; goto exit_ice_free_prof_mask; } /* remove mask */ hw->blk[blk].masks.masks[mask_idx].in_use = false; hw->blk[blk].masks.masks[mask_idx].mask = 0; hw->blk[blk].masks.masks[mask_idx].idx = 0; /* update mask as unused entry */ ice_debug(hw, ICE_DBG_PKG, "Free mask, blk %d, mask %d\n", blk, mask_idx); ice_write_prof_mask_reg(hw, blk, mask_idx, 0, 0); exit_ice_free_prof_mask: mutex_unlock(&hw->blk[blk].masks.lock); return 0; } /** * ice_free_prof_masks - free all profile masks for a profile * @hw: pointer to the HW struct * @blk: hardware block * @prof_id: profile ID */ static int ice_free_prof_masks(struct ice_hw *hw, enum ice_block blk, u16 prof_id) { u32 mask_bm; u16 i; if (blk != ICE_BLK_RSS && blk != ICE_BLK_FD) return -EINVAL; mask_bm = hw->blk[blk].es.mask_ena[prof_id]; for (i = 0; i < BITS_PER_BYTE * sizeof(mask_bm); i++) if (mask_bm & BIT(i)) ice_free_prof_mask(hw, blk, i); return 0; } /** * ice_shutdown_prof_masks - releases lock for masking * @hw: pointer to the HW struct * @blk: hardware block * * This should be called before unloading the driver */ static void ice_shutdown_prof_masks(struct ice_hw *hw, enum ice_block blk) { u16 i; mutex_lock(&hw->blk[blk].masks.lock); for (i = hw->blk[blk].masks.first; i < hw->blk[blk].masks.first + hw->blk[blk].masks.count; i++) { ice_write_prof_mask_reg(hw, blk, i, 0, 0); hw->blk[blk].masks.masks[i].in_use = false; hw->blk[blk].masks.masks[i].idx = 0; hw->blk[blk].masks.masks[i].mask = 0; } mutex_unlock(&hw->blk[blk].masks.lock); mutex_destroy(&hw->blk[blk].masks.lock); } /** * ice_shutdown_all_prof_masks - releases all locks for masking * @hw: pointer to the HW struct * * This should be called before unloading the driver */ static void ice_shutdown_all_prof_masks(struct ice_hw *hw) { ice_shutdown_prof_masks(hw, ICE_BLK_RSS); ice_shutdown_prof_masks(hw, ICE_BLK_FD); } /** * ice_update_prof_masking - set registers according to masking * @hw: pointer to the HW struct * @blk: hardware block * @prof_id: profile ID * @masks: masks */ static int ice_update_prof_masking(struct ice_hw *hw, enum ice_block blk, u16 prof_id, u16 *masks) { bool err = false; u32 ena_mask = 0; u16 idx; u16 i; /* Only support FD and RSS masking, otherwise nothing to be done */ if (blk != ICE_BLK_RSS && blk != ICE_BLK_FD) return 0; for (i = 0; i < hw->blk[blk].es.fvw; i++) if (masks[i] && masks[i] != 0xFFFF) { if (!ice_alloc_prof_mask(hw, blk, i, masks[i], &idx)) { ena_mask |= BIT(idx); } else { /* not enough bitmaps */ err = true; break; } } if (err) { /* free any bitmaps we have allocated */ for (i = 0; i < BITS_PER_BYTE * sizeof(ena_mask); i++) if (ena_mask & BIT(i)) ice_free_prof_mask(hw, blk, i); return -EIO; } /* enable the masks for this profile */ ice_write_prof_mask_enable_res(hw, blk, prof_id, ena_mask); /* store enabled masks with profile so that they can be freed later */ hw->blk[blk].es.mask_ena[prof_id] = ena_mask; return 0; } /** * ice_write_es - write an extraction sequence to hardware * @hw: pointer to the HW struct * @blk: the block in which to write the extraction sequence * @prof_id: the profile ID to write * @fv: pointer to the extraction sequence to write - NULL to clear extraction */ static void ice_write_es(struct ice_hw *hw, enum ice_block blk, u8 prof_id, struct ice_fv_word *fv) { u16 off; off = prof_id * hw->blk[blk].es.fvw; if (!fv) { memset(&hw->blk[blk].es.t[off], 0, hw->blk[blk].es.fvw * sizeof(*fv)); hw->blk[blk].es.written[prof_id] = false; } else { memcpy(&hw->blk[blk].es.t[off], fv, hw->blk[blk].es.fvw * sizeof(*fv)); } } /** * ice_prof_dec_ref - decrement reference count for profile * @hw: pointer to the HW struct * @blk: the block from which to free the profile ID * @prof_id: the profile ID for which to decrement the reference count */ static int ice_prof_dec_ref(struct ice_hw *hw, enum ice_block blk, u8 prof_id) { if (prof_id > hw->blk[blk].es.count) return -EINVAL; if (hw->blk[blk].es.ref_count[prof_id] > 0) { if (!--hw->blk[blk].es.ref_count[prof_id]) { ice_write_es(hw, blk, prof_id, NULL); ice_free_prof_masks(hw, blk, prof_id); return ice_free_prof_id(hw, blk, prof_id); } } return 0; } /* Block / table section IDs */ static const u32 ice_blk_sids[ICE_BLK_COUNT][ICE_SID_OFF_COUNT] = { /* SWITCH */ { ICE_SID_XLT1_SW, ICE_SID_XLT2_SW, ICE_SID_PROFID_TCAM_SW, ICE_SID_PROFID_REDIR_SW, ICE_SID_FLD_VEC_SW }, /* ACL */ { ICE_SID_XLT1_ACL, ICE_SID_XLT2_ACL, ICE_SID_PROFID_TCAM_ACL, ICE_SID_PROFID_REDIR_ACL, ICE_SID_FLD_VEC_ACL }, /* FD */ { ICE_SID_XLT1_FD, ICE_SID_XLT2_FD, ICE_SID_PROFID_TCAM_FD, ICE_SID_PROFID_REDIR_FD, ICE_SID_FLD_VEC_FD }, /* RSS */ { ICE_SID_XLT1_RSS, ICE_SID_XLT2_RSS, ICE_SID_PROFID_TCAM_RSS, ICE_SID_PROFID_REDIR_RSS, ICE_SID_FLD_VEC_RSS }, /* PE */ { ICE_SID_XLT1_PE, ICE_SID_XLT2_PE, ICE_SID_PROFID_TCAM_PE, ICE_SID_PROFID_REDIR_PE, ICE_SID_FLD_VEC_PE } }; /** * ice_init_sw_xlt1_db - init software XLT1 database from HW tables * @hw: pointer to the hardware structure * @blk: the HW block to initialize */ static void ice_init_sw_xlt1_db(struct ice_hw *hw, enum ice_block blk) { u16 pt; for (pt = 0; pt < hw->blk[blk].xlt1.count; pt++) { u8 ptg; ptg = hw->blk[blk].xlt1.t[pt]; if (ptg != ICE_DEFAULT_PTG) { ice_ptg_alloc_val(hw, blk, ptg); ice_ptg_add_mv_ptype(hw, blk, pt, ptg); } } } /** * ice_init_sw_xlt2_db - init software XLT2 database from HW tables * @hw: pointer to the hardware structure * @blk: the HW block to initialize */ static void ice_init_sw_xlt2_db(struct ice_hw *hw, enum ice_block blk) { u16 vsi; for (vsi = 0; vsi < hw->blk[blk].xlt2.count; vsi++) { u16 vsig; vsig = hw->blk[blk].xlt2.t[vsi]; if (vsig) { ice_vsig_alloc_val(hw, blk, vsig); ice_vsig_add_mv_vsi(hw, blk, vsi, vsig); /* no changes at this time, since this has been * initialized from the original package */ hw->blk[blk].xlt2.vsis[vsi].changed = 0; } } } /** * ice_init_sw_db - init software database from HW tables * @hw: pointer to the hardware structure */ static void ice_init_sw_db(struct ice_hw *hw) { u16 i; for (i = 0; i < ICE_BLK_COUNT; i++) { ice_init_sw_xlt1_db(hw, (enum ice_block)i); ice_init_sw_xlt2_db(hw, (enum ice_block)i); } } /** * ice_fill_tbl - Reads content of a single table type into database * @hw: pointer to the hardware structure * @block_id: Block ID of the table to copy * @sid: Section ID of the table to copy * * Will attempt to read the entire content of a given table of a single block * into the driver database. We assume that the buffer will always * be as large or larger than the data contained in the package. If * this condition is not met, there is most likely an error in the package * contents. */ static void ice_fill_tbl(struct ice_hw *hw, enum ice_block block_id, u32 sid) { u32 dst_len, sect_len, offset = 0; struct ice_prof_redir_section *pr; struct ice_prof_id_section *pid; struct ice_xlt1_section *xlt1; struct ice_xlt2_section *xlt2; struct ice_sw_fv_section *es; struct ice_pkg_enum state; u8 *src, *dst; void *sect; /* if the HW segment pointer is null then the first iteration of * ice_pkg_enum_section() will fail. In this case the HW tables will * not be filled and return success. */ if (!hw->seg) { ice_debug(hw, ICE_DBG_PKG, "hw->seg is NULL, tables are not filled\n"); return; } memset(&state, 0, sizeof(state)); sect = ice_pkg_enum_section(hw->seg, &state, sid); while (sect) { switch (sid) { case ICE_SID_XLT1_SW: case ICE_SID_XLT1_FD: case ICE_SID_XLT1_RSS: case ICE_SID_XLT1_ACL: case ICE_SID_XLT1_PE: xlt1 = sect; src = xlt1->value; sect_len = le16_to_cpu(xlt1->count) * sizeof(*hw->blk[block_id].xlt1.t); dst = hw->blk[block_id].xlt1.t; dst_len = hw->blk[block_id].xlt1.count * sizeof(*hw->blk[block_id].xlt1.t); break; case ICE_SID_XLT2_SW: case ICE_SID_XLT2_FD: case ICE_SID_XLT2_RSS: case ICE_SID_XLT2_ACL: case ICE_SID_XLT2_PE: xlt2 = sect; src = (__force u8 *)xlt2->value; sect_len = le16_to_cpu(xlt2->count) * sizeof(*hw->blk[block_id].xlt2.t); dst = (u8 *)hw->blk[block_id].xlt2.t; dst_len = hw->blk[block_id].xlt2.count * sizeof(*hw->blk[block_id].xlt2.t); break; case ICE_SID_PROFID_TCAM_SW: case ICE_SID_PROFID_TCAM_FD: case ICE_SID_PROFID_TCAM_RSS: case ICE_SID_PROFID_TCAM_ACL: case ICE_SID_PROFID_TCAM_PE: pid = sect; src = (u8 *)pid->entry; sect_len = le16_to_cpu(pid->count) * sizeof(*hw->blk[block_id].prof.t); dst = (u8 *)hw->blk[block_id].prof.t; dst_len = hw->blk[block_id].prof.count * sizeof(*hw->blk[block_id].prof.t); break; case ICE_SID_PROFID_REDIR_SW: case ICE_SID_PROFID_REDIR_FD: case ICE_SID_PROFID_REDIR_RSS: case ICE_SID_PROFID_REDIR_ACL: case ICE_SID_PROFID_REDIR_PE: pr = sect; src = pr->redir_value; sect_len = le16_to_cpu(pr->count) * sizeof(*hw->blk[block_id].prof_redir.t); dst = hw->blk[block_id].prof_redir.t; dst_len = hw->blk[block_id].prof_redir.count * sizeof(*hw->blk[block_id].prof_redir.t); break; case ICE_SID_FLD_VEC_SW: case ICE_SID_FLD_VEC_FD: case ICE_SID_FLD_VEC_RSS: case ICE_SID_FLD_VEC_ACL: case ICE_SID_FLD_VEC_PE: es = sect; src = (u8 *)es->fv; sect_len = (u32)(le16_to_cpu(es->count) * hw->blk[block_id].es.fvw) * sizeof(*hw->blk[block_id].es.t); dst = (u8 *)hw->blk[block_id].es.t; dst_len = (u32)(hw->blk[block_id].es.count * hw->blk[block_id].es.fvw) * sizeof(*hw->blk[block_id].es.t); break; default: return; } /* if the section offset exceeds destination length, terminate * table fill. */ if (offset > dst_len) return; /* if the sum of section size and offset exceed destination size * then we are out of bounds of the HW table size for that PF. * Changing section length to fill the remaining table space * of that PF. */ if ((offset + sect_len) > dst_len) sect_len = dst_len - offset; memcpy(dst + offset, src, sect_len); offset += sect_len; sect = ice_pkg_enum_section(NULL, &state, sid); } } /** * ice_fill_blk_tbls - Read package context for tables * @hw: pointer to the hardware structure * * Reads the current package contents and populates the driver * database with the data iteratively for all advanced feature * blocks. Assume that the HW tables have been allocated. */ void ice_fill_blk_tbls(struct ice_hw *hw) { u8 i; for (i = 0; i < ICE_BLK_COUNT; i++) { enum ice_block blk_id = (enum ice_block)i; ice_fill_tbl(hw, blk_id, hw->blk[blk_id].xlt1.sid); ice_fill_tbl(hw, blk_id, hw->blk[blk_id].xlt2.sid); ice_fill_tbl(hw, blk_id, hw->blk[blk_id].prof.sid); ice_fill_tbl(hw, blk_id, hw->blk[blk_id].prof_redir.sid); ice_fill_tbl(hw, blk_id, hw->blk[blk_id].es.sid); } ice_init_sw_db(hw); } /** * ice_free_prof_map - free profile map * @hw: pointer to the hardware structure * @blk_idx: HW block index */ static void ice_free_prof_map(struct ice_hw *hw, u8 blk_idx) { struct ice_es *es = &hw->blk[blk_idx].es; struct ice_prof_map *del, *tmp; mutex_lock(&es->prof_map_lock); list_for_each_entry_safe(del, tmp, &es->prof_map, list) { list_del(&del->list); devm_kfree(ice_hw_to_dev(hw), del); } INIT_LIST_HEAD(&es->prof_map); mutex_unlock(&es->prof_map_lock); } /** * ice_free_flow_profs - free flow profile entries * @hw: pointer to the hardware structure * @blk_idx: HW block index */ static void ice_free_flow_profs(struct ice_hw *hw, u8 blk_idx) { struct ice_flow_prof *p, *tmp; mutex_lock(&hw->fl_profs_locks[blk_idx]); list_for_each_entry_safe(p, tmp, &hw->fl_profs[blk_idx], l_entry) { struct ice_flow_entry *e, *t; list_for_each_entry_safe(e, t, &p->entries, l_entry) ice_flow_rem_entry(hw, (enum ice_block)blk_idx, ICE_FLOW_ENTRY_HNDL(e)); list_del(&p->l_entry); mutex_destroy(&p->entries_lock); devm_kfree(ice_hw_to_dev(hw), p); } mutex_unlock(&hw->fl_profs_locks[blk_idx]); /* if driver is in reset and tables are being cleared * re-initialize the flow profile list heads */ INIT_LIST_HEAD(&hw->fl_profs[blk_idx]); } /** * ice_free_vsig_tbl - free complete VSIG table entries * @hw: pointer to the hardware structure * @blk: the HW block on which to free the VSIG table entries */ static void ice_free_vsig_tbl(struct ice_hw *hw, enum ice_block blk) { u16 i; if (!hw->blk[blk].xlt2.vsig_tbl) return; for (i = 1; i < ICE_MAX_VSIGS; i++) if (hw->blk[blk].xlt2.vsig_tbl[i].in_use) ice_vsig_free(hw, blk, i); } /** * ice_free_hw_tbls - free hardware table memory * @hw: pointer to the hardware structure */ void ice_free_hw_tbls(struct ice_hw *hw) { struct ice_rss_cfg *r, *rt; u8 i; for (i = 0; i < ICE_BLK_COUNT; i++) { if (hw->blk[i].is_list_init) { struct ice_es *es = &hw->blk[i].es; ice_free_prof_map(hw, i); mutex_destroy(&es->prof_map_lock); ice_free_flow_profs(hw, i); mutex_destroy(&hw->fl_profs_locks[i]); hw->blk[i].is_list_init = false; } ice_free_vsig_tbl(hw, (enum ice_block)i); devm_kfree(ice_hw_to_dev(hw), hw->blk[i].xlt1.ptypes); devm_kfree(ice_hw_to_dev(hw), hw->blk[i].xlt1.ptg_tbl); devm_kfree(ice_hw_to_dev(hw), hw->blk[i].xlt1.t); devm_kfree(ice_hw_to_dev(hw), hw->blk[i].xlt2.t); devm_kfree(ice_hw_to_dev(hw), hw->blk[i].xlt2.vsig_tbl); devm_kfree(ice_hw_to_dev(hw), hw->blk[i].xlt2.vsis); devm_kfree(ice_hw_to_dev(hw), hw->blk[i].prof.t); devm_kfree(ice_hw_to_dev(hw), hw->blk[i].prof_redir.t); devm_kfree(ice_hw_to_dev(hw), hw->blk[i].es.t); devm_kfree(ice_hw_to_dev(hw), hw->blk[i].es.ref_count); devm_kfree(ice_hw_to_dev(hw), hw->blk[i].es.written); devm_kfree(ice_hw_to_dev(hw), hw->blk[i].es.mask_ena); } list_for_each_entry_safe(r, rt, &hw->rss_list_head, l_entry) { list_del(&r->l_entry); devm_kfree(ice_hw_to_dev(hw), r); } mutex_destroy(&hw->rss_locks); ice_shutdown_all_prof_masks(hw); memset(hw->blk, 0, sizeof(hw->blk)); } /** * ice_init_flow_profs - init flow profile locks and list heads * @hw: pointer to the hardware structure * @blk_idx: HW block index */ static void ice_init_flow_profs(struct ice_hw *hw, u8 blk_idx) { mutex_init(&hw->fl_profs_locks[blk_idx]); INIT_LIST_HEAD(&hw->fl_profs[blk_idx]); } /** * ice_clear_hw_tbls - clear HW tables and flow profiles * @hw: pointer to the hardware structure */ void ice_clear_hw_tbls(struct ice_hw *hw) { u8 i; for (i = 0; i < ICE_BLK_COUNT; i++) { struct ice_prof_redir *prof_redir = &hw->blk[i].prof_redir; struct ice_prof_tcam *prof = &hw->blk[i].prof; struct ice_xlt1 *xlt1 = &hw->blk[i].xlt1; struct ice_xlt2 *xlt2 = &hw->blk[i].xlt2; struct ice_es *es = &hw->blk[i].es; if (hw->blk[i].is_list_init) { ice_free_prof_map(hw, i); ice_free_flow_profs(hw, i); } ice_free_vsig_tbl(hw, (enum ice_block)i); memset(xlt1->ptypes, 0, xlt1->count * sizeof(*xlt1->ptypes)); memset(xlt1->ptg_tbl, 0, ICE_MAX_PTGS * sizeof(*xlt1->ptg_tbl)); memset(xlt1->t, 0, xlt1->count * sizeof(*xlt1->t)); memset(xlt2->vsis, 0, xlt2->count * sizeof(*xlt2->vsis)); memset(xlt2->vsig_tbl, 0, xlt2->count * sizeof(*xlt2->vsig_tbl)); memset(xlt2->t, 0, xlt2->count * sizeof(*xlt2->t)); memset(prof->t, 0, prof->count * sizeof(*prof->t)); memset(prof_redir->t, 0, prof_redir->count * sizeof(*prof_redir->t)); memset(es->t, 0, es->count * sizeof(*es->t) * es->fvw); memset(es->ref_count, 0, es->count * sizeof(*es->ref_count)); memset(es->written, 0, es->count * sizeof(*es->written)); memset(es->mask_ena, 0, es->count * sizeof(*es->mask_ena)); } } /** * ice_init_hw_tbls - init hardware table memory * @hw: pointer to the hardware structure */ int ice_init_hw_tbls(struct ice_hw *hw) { u8 i; mutex_init(&hw->rss_locks); INIT_LIST_HEAD(&hw->rss_list_head); ice_init_all_prof_masks(hw); for (i = 0; i < ICE_BLK_COUNT; i++) { struct ice_prof_redir *prof_redir = &hw->blk[i].prof_redir; struct ice_prof_tcam *prof = &hw->blk[i].prof; struct ice_xlt1 *xlt1 = &hw->blk[i].xlt1; struct ice_xlt2 *xlt2 = &hw->blk[i].xlt2; struct ice_es *es = &hw->blk[i].es; u16 j; if (hw->blk[i].is_list_init) continue; ice_init_flow_profs(hw, i); mutex_init(&es->prof_map_lock); INIT_LIST_HEAD(&es->prof_map); hw->blk[i].is_list_init = true; hw->blk[i].overwrite = blk_sizes[i].overwrite; es->reverse = blk_sizes[i].reverse; xlt1->sid = ice_blk_sids[i][ICE_SID_XLT1_OFF]; xlt1->count = blk_sizes[i].xlt1; xlt1->ptypes = devm_kcalloc(ice_hw_to_dev(hw), xlt1->count, sizeof(*xlt1->ptypes), GFP_KERNEL); if (!xlt1->ptypes) goto err; xlt1->ptg_tbl = devm_kcalloc(ice_hw_to_dev(hw), ICE_MAX_PTGS, sizeof(*xlt1->ptg_tbl), GFP_KERNEL); if (!xlt1->ptg_tbl) goto err; xlt1->t = devm_kcalloc(ice_hw_to_dev(hw), xlt1->count, sizeof(*xlt1->t), GFP_KERNEL); if (!xlt1->t) goto err; xlt2->sid = ice_blk_sids[i][ICE_SID_XLT2_OFF]; xlt2->count = blk_sizes[i].xlt2; xlt2->vsis = devm_kcalloc(ice_hw_to_dev(hw), xlt2->count, sizeof(*xlt2->vsis), GFP_KERNEL); if (!xlt2->vsis) goto err; xlt2->vsig_tbl = devm_kcalloc(ice_hw_to_dev(hw), xlt2->count, sizeof(*xlt2->vsig_tbl), GFP_KERNEL); if (!xlt2->vsig_tbl) goto err; for (j = 0; j < xlt2->count; j++) INIT_LIST_HEAD(&xlt2->vsig_tbl[j].prop_lst); xlt2->t = devm_kcalloc(ice_hw_to_dev(hw), xlt2->count, sizeof(*xlt2->t), GFP_KERNEL); if (!xlt2->t) goto err; prof->sid = ice_blk_sids[i][ICE_SID_PR_OFF]; prof->count = blk_sizes[i].prof_tcam; prof->max_prof_id = blk_sizes[i].prof_id; prof->cdid_bits = blk_sizes[i].prof_cdid_bits; prof->t = devm_kcalloc(ice_hw_to_dev(hw), prof->count, sizeof(*prof->t), GFP_KERNEL); if (!prof->t) goto err; prof_redir->sid = ice_blk_sids[i][ICE_SID_PR_REDIR_OFF]; prof_redir->count = blk_sizes[i].prof_redir; prof_redir->t = devm_kcalloc(ice_hw_to_dev(hw), prof_redir->count, sizeof(*prof_redir->t), GFP_KERNEL); if (!prof_redir->t) goto err; es->sid = ice_blk_sids[i][ICE_SID_ES_OFF]; es->count = blk_sizes[i].es; es->fvw = blk_sizes[i].fvw; es->t = devm_kcalloc(ice_hw_to_dev(hw), (u32)(es->count * es->fvw), sizeof(*es->t), GFP_KERNEL); if (!es->t) goto err; es->ref_count = devm_kcalloc(ice_hw_to_dev(hw), es->count, sizeof(*es->ref_count), GFP_KERNEL); if (!es->ref_count) goto err; es->written = devm_kcalloc(ice_hw_to_dev(hw), es->count, sizeof(*es->written), GFP_KERNEL); if (!es->written) goto err; es->mask_ena = devm_kcalloc(ice_hw_to_dev(hw), es->count, sizeof(*es->mask_ena), GFP_KERNEL); if (!es->mask_ena) goto err; } return 0; err: ice_free_hw_tbls(hw); return -ENOMEM; } /** * ice_prof_gen_key - generate profile ID key * @hw: pointer to the HW struct * @blk: the block in which to write profile ID to * @ptg: packet type group (PTG) portion of key * @vsig: VSIG portion of key * @cdid: CDID portion of key * @flags: flag portion of key * @vl_msk: valid mask * @dc_msk: don't care mask * @nm_msk: never match mask * @key: output of profile ID key */ static int ice_prof_gen_key(struct ice_hw *hw, enum ice_block blk, u8 ptg, u16 vsig, u8 cdid, u16 flags, u8 vl_msk[ICE_TCAM_KEY_VAL_SZ], u8 dc_msk[ICE_TCAM_KEY_VAL_SZ], u8 nm_msk[ICE_TCAM_KEY_VAL_SZ], u8 key[ICE_TCAM_KEY_SZ]) { struct ice_prof_id_key inkey; inkey.xlt1 = ptg; inkey.xlt2_cdid = cpu_to_le16(vsig); inkey.flags = cpu_to_le16(flags); switch (hw->blk[blk].prof.cdid_bits) { case 0: break; case 2: #define ICE_CD_2_M 0xC000U #define ICE_CD_2_S 14 inkey.xlt2_cdid &= ~cpu_to_le16(ICE_CD_2_M); inkey.xlt2_cdid |= cpu_to_le16(BIT(cdid) << ICE_CD_2_S); break; case 4: #define ICE_CD_4_M 0xF000U #define ICE_CD_4_S 12 inkey.xlt2_cdid &= ~cpu_to_le16(ICE_CD_4_M); inkey.xlt2_cdid |= cpu_to_le16(BIT(cdid) << ICE_CD_4_S); break; case 8: #define ICE_CD_8_M 0xFF00U #define ICE_CD_8_S 16 inkey.xlt2_cdid &= ~cpu_to_le16(ICE_CD_8_M); inkey.xlt2_cdid |= cpu_to_le16(BIT(cdid) << ICE_CD_8_S); break; default: ice_debug(hw, ICE_DBG_PKG, "Error in profile config\n"); break; } return ice_set_key(key, ICE_TCAM_KEY_SZ, (u8 *)&inkey, vl_msk, dc_msk, nm_msk, 0, ICE_TCAM_KEY_SZ / 2); } /** * ice_tcam_write_entry - write TCAM entry * @hw: pointer to the HW struct * @blk: the block in which to write profile ID to * @idx: the entry index to write to * @prof_id: profile ID * @ptg: packet type group (PTG) portion of key * @vsig: VSIG portion of key * @cdid: CDID portion of key * @flags: flag portion of key * @vl_msk: valid mask * @dc_msk: don't care mask * @nm_msk: never match mask */ static int ice_tcam_write_entry(struct ice_hw *hw, enum ice_block blk, u16 idx, u8 prof_id, u8 ptg, u16 vsig, u8 cdid, u16 flags, u8 vl_msk[ICE_TCAM_KEY_VAL_SZ], u8 dc_msk[ICE_TCAM_KEY_VAL_SZ], u8 nm_msk[ICE_TCAM_KEY_VAL_SZ]) { struct ice_prof_tcam_entry; int status; status = ice_prof_gen_key(hw, blk, ptg, vsig, cdid, flags, vl_msk, dc_msk, nm_msk, hw->blk[blk].prof.t[idx].key); if (!status) { hw->blk[blk].prof.t[idx].addr = cpu_to_le16(idx); hw->blk[blk].prof.t[idx].prof_id = prof_id; } return status; } /** * ice_vsig_get_ref - returns number of VSIs belong to a VSIG * @hw: pointer to the hardware structure * @blk: HW block * @vsig: VSIG to query * @refs: pointer to variable to receive the reference count */ static int ice_vsig_get_ref(struct ice_hw *hw, enum ice_block blk, u16 vsig, u16 *refs) { u16 idx = vsig & ICE_VSIG_IDX_M; struct ice_vsig_vsi *ptr; *refs = 0; if (!hw->blk[blk].xlt2.vsig_tbl[idx].in_use) return -ENOENT; ptr = hw->blk[blk].xlt2.vsig_tbl[idx].first_vsi; while (ptr) { (*refs)++; ptr = ptr->next_vsi; } return 0; } /** * ice_has_prof_vsig - check to see if VSIG has a specific profile * @hw: pointer to the hardware structure * @blk: HW block * @vsig: VSIG to check against * @hdl: profile handle */ static bool ice_has_prof_vsig(struct ice_hw *hw, enum ice_block blk, u16 vsig, u64 hdl) { u16 idx = vsig & ICE_VSIG_IDX_M; struct ice_vsig_prof *ent; list_for_each_entry(ent, &hw->blk[blk].xlt2.vsig_tbl[idx].prop_lst, list) if (ent->profile_cookie == hdl) return true; ice_debug(hw, ICE_DBG_INIT, "Characteristic list for VSI group %d not found.\n", vsig); return false; } /** * ice_prof_bld_es - build profile ID extraction sequence changes * @hw: pointer to the HW struct * @blk: hardware block * @bld: the update package buffer build to add to * @chgs: the list of changes to make in hardware */ static int ice_prof_bld_es(struct ice_hw *hw, enum ice_block blk, struct ice_buf_build *bld, struct list_head *chgs) { u16 vec_size = hw->blk[blk].es.fvw * sizeof(struct ice_fv_word); struct ice_chs_chg *tmp; list_for_each_entry(tmp, chgs, list_entry) if (tmp->type == ICE_PTG_ES_ADD && tmp->add_prof) { u16 off = tmp->prof_id * hw->blk[blk].es.fvw; struct ice_pkg_es *p; u32 id; id = ice_sect_id(blk, ICE_VEC_TBL); p = ice_pkg_buf_alloc_section(bld, id, struct_size(p, es, 1) + vec_size - sizeof(p->es[0])); if (!p) return -ENOSPC; p->count = cpu_to_le16(1); p->offset = cpu_to_le16(tmp->prof_id); memcpy(p->es, &hw->blk[blk].es.t[off], vec_size); } return 0; } /** * ice_prof_bld_tcam - build profile ID TCAM changes * @hw: pointer to the HW struct * @blk: hardware block * @bld: the update package buffer build to add to * @chgs: the list of changes to make in hardware */ static int ice_prof_bld_tcam(struct ice_hw *hw, enum ice_block blk, struct ice_buf_build *bld, struct list_head *chgs) { struct ice_chs_chg *tmp; list_for_each_entry(tmp, chgs, list_entry) if (tmp->type == ICE_TCAM_ADD && tmp->add_tcam_idx) { struct ice_prof_id_section *p; u32 id; id = ice_sect_id(blk, ICE_PROF_TCAM); p = ice_pkg_buf_alloc_section(bld, id, struct_size(p, entry, 1)); if (!p) return -ENOSPC; p->count = cpu_to_le16(1); p->entry[0].addr = cpu_to_le16(tmp->tcam_idx); p->entry[0].prof_id = tmp->prof_id; memcpy(p->entry[0].key, &hw->blk[blk].prof.t[tmp->tcam_idx].key, sizeof(hw->blk[blk].prof.t->key)); } return 0; } /** * ice_prof_bld_xlt1 - build XLT1 changes * @blk: hardware block * @bld: the update package buffer build to add to * @chgs: the list of changes to make in hardware */ static int ice_prof_bld_xlt1(enum ice_block blk, struct ice_buf_build *bld, struct list_head *chgs) { struct ice_chs_chg *tmp; list_for_each_entry(tmp, chgs, list_entry) if (tmp->type == ICE_PTG_ES_ADD && tmp->add_ptg) { struct ice_xlt1_section *p; u32 id; id = ice_sect_id(blk, ICE_XLT1); p = ice_pkg_buf_alloc_section(bld, id, struct_size(p, value, 1)); if (!p) return -ENOSPC; p->count = cpu_to_le16(1); p->offset = cpu_to_le16(tmp->ptype); p->value[0] = tmp->ptg; } return 0; } /** * ice_prof_bld_xlt2 - build XLT2 changes * @blk: hardware block * @bld: the update package buffer build to add to * @chgs: the list of changes to make in hardware */ static int ice_prof_bld_xlt2(enum ice_block blk, struct ice_buf_build *bld, struct list_head *chgs) { struct ice_chs_chg *tmp; list_for_each_entry(tmp, chgs, list_entry) { struct ice_xlt2_section *p; u32 id; switch (tmp->type) { case ICE_VSIG_ADD: case ICE_VSI_MOVE: case ICE_VSIG_REM: id = ice_sect_id(blk, ICE_XLT2); p = ice_pkg_buf_alloc_section(bld, id, struct_size(p, value, 1)); if (!p) return -ENOSPC; p->count = cpu_to_le16(1); p->offset = cpu_to_le16(tmp->vsi); p->value[0] = cpu_to_le16(tmp->vsig); break; default: break; } } return 0; } /** * ice_upd_prof_hw - update hardware using the change list * @hw: pointer to the HW struct * @blk: hardware block * @chgs: the list of changes to make in hardware */ static int ice_upd_prof_hw(struct ice_hw *hw, enum ice_block blk, struct list_head *chgs) { struct ice_buf_build *b; struct ice_chs_chg *tmp; u16 pkg_sects; u16 xlt1 = 0; u16 xlt2 = 0; u16 tcam = 0; u16 es = 0; int status; u16 sects; /* count number of sections we need */ list_for_each_entry(tmp, chgs, list_entry) { switch (tmp->type) { case ICE_PTG_ES_ADD: if (tmp->add_ptg) xlt1++; if (tmp->add_prof) es++; break; case ICE_TCAM_ADD: tcam++; break; case ICE_VSIG_ADD: case ICE_VSI_MOVE: case ICE_VSIG_REM: xlt2++; break; default: break; } } sects = xlt1 + xlt2 + tcam + es; if (!sects) return 0; /* Build update package buffer */ b = ice_pkg_buf_alloc(hw); if (!b) return -ENOMEM; status = ice_pkg_buf_reserve_section(b, sects); if (status) goto error_tmp; /* Preserve order of table update: ES, TCAM, PTG, VSIG */ if (es) { status = ice_prof_bld_es(hw, blk, b, chgs); if (status) goto error_tmp; } if (tcam) { status = ice_prof_bld_tcam(hw, blk, b, chgs); if (status) goto error_tmp; } if (xlt1) { status = ice_prof_bld_xlt1(blk, b, chgs); if (status) goto error_tmp; } if (xlt2) { status = ice_prof_bld_xlt2(blk, b, chgs); if (status) goto error_tmp; } /* After package buffer build check if the section count in buffer is * non-zero and matches the number of sections detected for package * update. */ pkg_sects = ice_pkg_buf_get_active_sections(b); if (!pkg_sects || pkg_sects != sects) { status = -EINVAL; goto error_tmp; } /* update package */ status = ice_update_pkg(hw, ice_pkg_buf(b), 1); if (status == -EIO) ice_debug(hw, ICE_DBG_INIT, "Unable to update HW profile\n"); error_tmp: ice_pkg_buf_free(hw, b); return status; } /** * ice_update_fd_mask - set Flow Director Field Vector mask for a profile * @hw: pointer to the HW struct * @prof_id: profile ID * @mask_sel: mask select * * This function enable any of the masks selected by the mask select parameter * for the profile specified. */ static void ice_update_fd_mask(struct ice_hw *hw, u16 prof_id, u32 mask_sel) { wr32(hw, GLQF_FDMASK_SEL(prof_id), mask_sel); ice_debug(hw, ICE_DBG_INIT, "fd mask(%d): %x = %x\n", prof_id, GLQF_FDMASK_SEL(prof_id), mask_sel); } struct ice_fd_src_dst_pair { u8 prot_id; u8 count; u16 off; }; static const struct ice_fd_src_dst_pair ice_fd_pairs[] = { /* These are defined in pairs */ { ICE_PROT_IPV4_OF_OR_S, 2, 12 }, { ICE_PROT_IPV4_OF_OR_S, 2, 16 }, { ICE_PROT_IPV4_IL, 2, 12 }, { ICE_PROT_IPV4_IL, 2, 16 }, { ICE_PROT_IPV6_OF_OR_S, 8, 8 }, { ICE_PROT_IPV6_OF_OR_S, 8, 24 }, { ICE_PROT_IPV6_IL, 8, 8 }, { ICE_PROT_IPV6_IL, 8, 24 }, { ICE_PROT_TCP_IL, 1, 0 }, { ICE_PROT_TCP_IL, 1, 2 }, { ICE_PROT_UDP_OF, 1, 0 }, { ICE_PROT_UDP_OF, 1, 2 }, { ICE_PROT_UDP_IL_OR_S, 1, 0 }, { ICE_PROT_UDP_IL_OR_S, 1, 2 }, { ICE_PROT_SCTP_IL, 1, 0 }, { ICE_PROT_SCTP_IL, 1, 2 } }; #define ICE_FD_SRC_DST_PAIR_COUNT ARRAY_SIZE(ice_fd_pairs) /** * ice_update_fd_swap - set register appropriately for a FD FV extraction * @hw: pointer to the HW struct * @prof_id: profile ID * @es: extraction sequence (length of array is determined by the block) */ static int ice_update_fd_swap(struct ice_hw *hw, u16 prof_id, struct ice_fv_word *es) { DECLARE_BITMAP(pair_list, ICE_FD_SRC_DST_PAIR_COUNT); u8 pair_start[ICE_FD_SRC_DST_PAIR_COUNT] = { 0 }; #define ICE_FD_FV_NOT_FOUND (-2) s8 first_free = ICE_FD_FV_NOT_FOUND; u8 used[ICE_MAX_FV_WORDS] = { 0 }; s8 orig_free, si; u32 mask_sel = 0; u8 i, j, k; bitmap_zero(pair_list, ICE_FD_SRC_DST_PAIR_COUNT); /* This code assumes that the Flow Director field vectors are assigned * from the end of the FV indexes working towards the zero index, that * only complete fields will be included and will be consecutive, and * that there are no gaps between valid indexes. */ /* Determine swap fields present */ for (i = 0; i < hw->blk[ICE_BLK_FD].es.fvw; i++) { /* Find the first free entry, assuming right to left population. * This is where we can start adding additional pairs if needed. */ if (first_free == ICE_FD_FV_NOT_FOUND && es[i].prot_id != ICE_PROT_INVALID) first_free = i - 1; for (j = 0; j < ICE_FD_SRC_DST_PAIR_COUNT; j++) if (es[i].prot_id == ice_fd_pairs[j].prot_id && es[i].off == ice_fd_pairs[j].off) { __set_bit(j, pair_list); pair_start[j] = i; } } orig_free = first_free; /* determine missing swap fields that need to be added */ for (i = 0; i < ICE_FD_SRC_DST_PAIR_COUNT; i += 2) { u8 bit1 = test_bit(i + 1, pair_list); u8 bit0 = test_bit(i, pair_list); if (bit0 ^ bit1) { u8 index; /* add the appropriate 'paired' entry */ if (!bit0) index = i; else index = i + 1; /* check for room */ if (first_free + 1 < (s8)ice_fd_pairs[index].count) return -ENOSPC; /* place in extraction sequence */ for (k = 0; k < ice_fd_pairs[index].count; k++) { es[first_free - k].prot_id = ice_fd_pairs[index].prot_id; es[first_free - k].off = ice_fd_pairs[index].off + (k * 2); if (k > first_free) return -EIO; /* keep track of non-relevant fields */ mask_sel |= BIT(first_free - k); } pair_start[index] = first_free; first_free -= ice_fd_pairs[index].count; } } /* fill in the swap array */ si = hw->blk[ICE_BLK_FD].es.fvw - 1; while (si >= 0) { u8 indexes_used = 1; /* assume flat at this index */ #define ICE_SWAP_VALID 0x80 used[si] = si | ICE_SWAP_VALID; if (orig_free == ICE_FD_FV_NOT_FOUND || si <= orig_free) { si -= indexes_used; continue; } /* check for a swap location */ for (j = 0; j < ICE_FD_SRC_DST_PAIR_COUNT; j++) if (es[si].prot_id == ice_fd_pairs[j].prot_id && es[si].off == ice_fd_pairs[j].off) { u8 idx; /* determine the appropriate matching field */ idx = j + ((j % 2) ? -1 : 1); indexes_used = ice_fd_pairs[idx].count; for (k = 0; k < indexes_used; k++) { used[si - k] = (pair_start[idx] - k) | ICE_SWAP_VALID; } break; } si -= indexes_used; } /* for each set of 4 swap and 4 inset indexes, write the appropriate * register */ for (j = 0; j < hw->blk[ICE_BLK_FD].es.fvw / 4; j++) { u32 raw_swap = 0; u32 raw_in = 0; for (k = 0; k < 4; k++) { u8 idx; idx = (j * 4) + k; if (used[idx] && !(mask_sel & BIT(idx))) { raw_swap |= used[idx] << (k * BITS_PER_BYTE); #define ICE_INSET_DFLT 0x9f raw_in |= ICE_INSET_DFLT << (k * BITS_PER_BYTE); } } /* write the appropriate swap register set */ wr32(hw, GLQF_FDSWAP(prof_id, j), raw_swap); ice_debug(hw, ICE_DBG_INIT, "swap wr(%d, %d): %x = %08x\n", prof_id, j, GLQF_FDSWAP(prof_id, j), raw_swap); /* write the appropriate inset register set */ wr32(hw, GLQF_FDINSET(prof_id, j), raw_in); ice_debug(hw, ICE_DBG_INIT, "inset wr(%d, %d): %x = %08x\n", prof_id, j, GLQF_FDINSET(prof_id, j), raw_in); } /* initially clear the mask select for this profile */ ice_update_fd_mask(hw, prof_id, 0); return 0; } /* The entries here needs to match the order of enum ice_ptype_attrib */ static const struct ice_ptype_attrib_info ice_ptype_attributes[] = { { ICE_GTP_PDU_EH, ICE_GTP_PDU_FLAG_MASK }, { ICE_GTP_SESSION, ICE_GTP_FLAGS_MASK }, { ICE_GTP_DOWNLINK, ICE_GTP_FLAGS_MASK }, { ICE_GTP_UPLINK, ICE_GTP_FLAGS_MASK }, }; /** * ice_get_ptype_attrib_info - get PTYPE attribute information * @type: attribute type * @info: pointer to variable to the attribute information */ static void ice_get_ptype_attrib_info(enum ice_ptype_attrib_type type, struct ice_ptype_attrib_info *info) { *info = ice_ptype_attributes[type]; } /** * ice_add_prof_attrib - add any PTG with attributes to profile * @prof: pointer to the profile to which PTG entries will be added * @ptg: PTG to be added * @ptype: PTYPE that needs to be looked up * @attr: array of attributes that will be considered * @attr_cnt: number of elements in the attribute array */ static int ice_add_prof_attrib(struct ice_prof_map *prof, u8 ptg, u16 ptype, const struct ice_ptype_attributes *attr, u16 attr_cnt) { bool found = false; u16 i; for (i = 0; i < attr_cnt; i++) if (attr[i].ptype == ptype) { found = true; prof->ptg[prof->ptg_cnt] = ptg; ice_get_ptype_attrib_info(attr[i].attrib, &prof->attr[prof->ptg_cnt]); if (++prof->ptg_cnt >= ICE_MAX_PTG_PER_PROFILE) return -ENOSPC; } if (!found) return -ENOENT; return 0; } /** * ice_add_prof - add profile * @hw: pointer to the HW struct * @blk: hardware block * @id: profile tracking ID * @ptypes: array of bitmaps indicating ptypes (ICE_FLOW_PTYPE_MAX bits) * @attr: array of attributes * @attr_cnt: number of elements in attr array * @es: extraction sequence (length of array is determined by the block) * @masks: mask for extraction sequence * * This function registers a profile, which matches a set of PTYPES with a * particular extraction sequence. While the hardware profile is allocated * it will not be written until the first call to ice_add_flow that specifies * the ID value used here. */ int ice_add_prof(struct ice_hw *hw, enum ice_block blk, u64 id, u8 ptypes[], const struct ice_ptype_attributes *attr, u16 attr_cnt, struct ice_fv_word *es, u16 *masks) { u32 bytes = DIV_ROUND_UP(ICE_FLOW_PTYPE_MAX, BITS_PER_BYTE); DECLARE_BITMAP(ptgs_used, ICE_XLT1_CNT); struct ice_prof_map *prof; u8 byte = 0; u8 prof_id; int status; bitmap_zero(ptgs_used, ICE_XLT1_CNT); mutex_lock(&hw->blk[blk].es.prof_map_lock); /* search for existing profile */ status = ice_find_prof_id_with_mask(hw, blk, es, masks, &prof_id); if (status) { /* allocate profile ID */ status = ice_alloc_prof_id(hw, blk, &prof_id); if (status) goto err_ice_add_prof; if (blk == ICE_BLK_FD) { /* For Flow Director block, the extraction sequence may * need to be altered in the case where there are paired * fields that have no match. This is necessary because * for Flow Director, src and dest fields need to paired * for filter programming and these values are swapped * during Tx. */ status = ice_update_fd_swap(hw, prof_id, es); if (status) goto err_ice_add_prof; } status = ice_update_prof_masking(hw, blk, prof_id, masks); if (status) goto err_ice_add_prof; /* and write new es */ ice_write_es(hw, blk, prof_id, es); } ice_prof_inc_ref(hw, blk, prof_id); /* add profile info */ prof = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*prof), GFP_KERNEL); if (!prof) { status = -ENOMEM; goto err_ice_add_prof; } prof->profile_cookie = id; prof->prof_id = prof_id; prof->ptg_cnt = 0; prof->context = 0; /* build list of ptgs */ while (bytes && prof->ptg_cnt < ICE_MAX_PTG_PER_PROFILE) { u8 bit; if (!ptypes[byte]) { bytes--; byte++; continue; } /* Examine 8 bits per byte */ for_each_set_bit(bit, (unsigned long *)&ptypes[byte], BITS_PER_BYTE) { u16 ptype; u8 ptg; ptype = byte * BITS_PER_BYTE + bit; /* The package should place all ptypes in a non-zero * PTG, so the following call should never fail. */ if (ice_ptg_find_ptype(hw, blk, ptype, &ptg)) continue; /* If PTG is already added, skip and continue */ if (test_bit(ptg, ptgs_used)) continue; __set_bit(ptg, ptgs_used); /* Check to see there are any attributes for * this PTYPE, and add them if found. */ status = ice_add_prof_attrib(prof, ptg, ptype, attr, attr_cnt); if (status == -ENOSPC) break; if (status) { /* This is simple a PTYPE/PTG with no * attribute */ prof->ptg[prof->ptg_cnt] = ptg; prof->attr[prof->ptg_cnt].flags = 0; prof->attr[prof->ptg_cnt].mask = 0; if (++prof->ptg_cnt >= ICE_MAX_PTG_PER_PROFILE) break; } } bytes--; byte++; } list_add(&prof->list, &hw->blk[blk].es.prof_map); status = 0; err_ice_add_prof: mutex_unlock(&hw->blk[blk].es.prof_map_lock); return status; } /** * ice_search_prof_id - Search for a profile tracking ID * @hw: pointer to the HW struct * @blk: hardware block * @id: profile tracking ID * * This will search for a profile tracking ID which was previously added. * The profile map lock should be held before calling this function. */ static struct ice_prof_map * ice_search_prof_id(struct ice_hw *hw, enum ice_block blk, u64 id) { struct ice_prof_map *entry = NULL; struct ice_prof_map *map; list_for_each_entry(map, &hw->blk[blk].es.prof_map, list) if (map->profile_cookie == id) { entry = map; break; } return entry; } /** * ice_vsig_prof_id_count - count profiles in a VSIG * @hw: pointer to the HW struct * @blk: hardware block * @vsig: VSIG to remove the profile from */ static u16 ice_vsig_prof_id_count(struct ice_hw *hw, enum ice_block blk, u16 vsig) { u16 idx = vsig & ICE_VSIG_IDX_M, count = 0; struct ice_vsig_prof *p; list_for_each_entry(p, &hw->blk[blk].xlt2.vsig_tbl[idx].prop_lst, list) count++; return count; } /** * ice_rel_tcam_idx - release a TCAM index * @hw: pointer to the HW struct * @blk: hardware block * @idx: the index to release */ static int ice_rel_tcam_idx(struct ice_hw *hw, enum ice_block blk, u16 idx) { /* Masks to invoke a never match entry */ u8 vl_msk[ICE_TCAM_KEY_VAL_SZ] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; u8 dc_msk[ICE_TCAM_KEY_VAL_SZ] = { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF }; u8 nm_msk[ICE_TCAM_KEY_VAL_SZ] = { 0x01, 0x00, 0x00, 0x00, 0x00 }; int status; /* write the TCAM entry */ status = ice_tcam_write_entry(hw, blk, idx, 0, 0, 0, 0, 0, vl_msk, dc_msk, nm_msk); if (status) return status; /* release the TCAM entry */ status = ice_free_tcam_ent(hw, blk, idx); return status; } /** * ice_rem_prof_id - remove one profile from a VSIG * @hw: pointer to the HW struct * @blk: hardware block * @prof: pointer to profile structure to remove */ static int ice_rem_prof_id(struct ice_hw *hw, enum ice_block blk, struct ice_vsig_prof *prof) { int status; u16 i; for (i = 0; i < prof->tcam_count; i++) if (prof->tcam[i].in_use) { prof->tcam[i].in_use = false; status = ice_rel_tcam_idx(hw, blk, prof->tcam[i].tcam_idx); if (status) return -EIO; } return 0; } /** * ice_rem_vsig - remove VSIG * @hw: pointer to the HW struct * @blk: hardware block * @vsig: the VSIG to remove * @chg: the change list */ static int ice_rem_vsig(struct ice_hw *hw, enum ice_block blk, u16 vsig, struct list_head *chg) { u16 idx = vsig & ICE_VSIG_IDX_M; struct ice_vsig_vsi *vsi_cur; struct ice_vsig_prof *d, *t; /* remove TCAM entries */ list_for_each_entry_safe(d, t, &hw->blk[blk].xlt2.vsig_tbl[idx].prop_lst, list) { int status; status = ice_rem_prof_id(hw, blk, d); if (status) return status; list_del(&d->list); devm_kfree(ice_hw_to_dev(hw), d); } /* Move all VSIS associated with this VSIG to the default VSIG */ vsi_cur = hw->blk[blk].xlt2.vsig_tbl[idx].first_vsi; /* If the VSIG has at least 1 VSI then iterate through the list * and remove the VSIs before deleting the group. */ if (vsi_cur) do { struct ice_vsig_vsi *tmp = vsi_cur->next_vsi; struct ice_chs_chg *p; p = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*p), GFP_KERNEL); if (!p) return -ENOMEM; p->type = ICE_VSIG_REM; p->orig_vsig = vsig; p->vsig = ICE_DEFAULT_VSIG; p->vsi = vsi_cur - hw->blk[blk].xlt2.vsis; list_add(&p->list_entry, chg); vsi_cur = tmp; } while (vsi_cur); return ice_vsig_free(hw, blk, vsig); } /** * ice_rem_prof_id_vsig - remove a specific profile from a VSIG * @hw: pointer to the HW struct * @blk: hardware block * @vsig: VSIG to remove the profile from * @hdl: profile handle indicating which profile to remove * @chg: list to receive a record of changes */ static int ice_rem_prof_id_vsig(struct ice_hw *hw, enum ice_block blk, u16 vsig, u64 hdl, struct list_head *chg) { u16 idx = vsig & ICE_VSIG_IDX_M; struct ice_vsig_prof *p, *t; list_for_each_entry_safe(p, t, &hw->blk[blk].xlt2.vsig_tbl[idx].prop_lst, list) if (p->profile_cookie == hdl) { int status; if (ice_vsig_prof_id_count(hw, blk, vsig) == 1) /* this is the last profile, remove the VSIG */ return ice_rem_vsig(hw, blk, vsig, chg); status = ice_rem_prof_id(hw, blk, p); if (!status) { list_del(&p->list); devm_kfree(ice_hw_to_dev(hw), p); } return status; } return -ENOENT; } /** * ice_rem_flow_all - remove all flows with a particular profile * @hw: pointer to the HW struct * @blk: hardware block * @id: profile tracking ID */ static int ice_rem_flow_all(struct ice_hw *hw, enum ice_block blk, u64 id) { struct ice_chs_chg *del, *tmp; struct list_head chg; int status; u16 i; INIT_LIST_HEAD(&chg); for (i = 1; i < ICE_MAX_VSIGS; i++) if (hw->blk[blk].xlt2.vsig_tbl[i].in_use) { if (ice_has_prof_vsig(hw, blk, i, id)) { status = ice_rem_prof_id_vsig(hw, blk, i, id, &chg); if (status) goto err_ice_rem_flow_all; } } status = ice_upd_prof_hw(hw, blk, &chg); err_ice_rem_flow_all: list_for_each_entry_safe(del, tmp, &chg, list_entry) { list_del(&del->list_entry); devm_kfree(ice_hw_to_dev(hw), del); } return status; } /** * ice_rem_prof - remove profile * @hw: pointer to the HW struct * @blk: hardware block * @id: profile tracking ID * * This will remove the profile specified by the ID parameter, which was * previously created through ice_add_prof. If any existing entries * are associated with this profile, they will be removed as well. */ int ice_rem_prof(struct ice_hw *hw, enum ice_block blk, u64 id) { struct ice_prof_map *pmap; int status; mutex_lock(&hw->blk[blk].es.prof_map_lock); pmap = ice_search_prof_id(hw, blk, id); if (!pmap) { status = -ENOENT; goto err_ice_rem_prof; } /* remove all flows with this profile */ status = ice_rem_flow_all(hw, blk, pmap->profile_cookie); if (status) goto err_ice_rem_prof; /* dereference profile, and possibly remove */ ice_prof_dec_ref(hw, blk, pmap->prof_id); list_del(&pmap->list); devm_kfree(ice_hw_to_dev(hw), pmap); err_ice_rem_prof: mutex_unlock(&hw->blk[blk].es.prof_map_lock); return status; } /** * ice_get_prof - get profile * @hw: pointer to the HW struct * @blk: hardware block * @hdl: profile handle * @chg: change list */ static int ice_get_prof(struct ice_hw *hw, enum ice_block blk, u64 hdl, struct list_head *chg) { struct ice_prof_map *map; struct ice_chs_chg *p; int status = 0; u16 i; mutex_lock(&hw->blk[blk].es.prof_map_lock); /* Get the details on the profile specified by the handle ID */ map = ice_search_prof_id(hw, blk, hdl); if (!map) { status = -ENOENT; goto err_ice_get_prof; } for (i = 0; i < map->ptg_cnt; i++) if (!hw->blk[blk].es.written[map->prof_id]) { /* add ES to change list */ p = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*p), GFP_KERNEL); if (!p) { status = -ENOMEM; goto err_ice_get_prof; } p->type = ICE_PTG_ES_ADD; p->ptype = 0; p->ptg = map->ptg[i]; p->add_ptg = 0; p->add_prof = 1; p->prof_id = map->prof_id; hw->blk[blk].es.written[map->prof_id] = true; list_add(&p->list_entry, chg); } err_ice_get_prof: mutex_unlock(&hw->blk[blk].es.prof_map_lock); /* let caller clean up the change list */ return status; } /** * ice_get_profs_vsig - get a copy of the list of profiles from a VSIG * @hw: pointer to the HW struct * @blk: hardware block * @vsig: VSIG from which to copy the list * @lst: output list * * This routine makes a copy of the list of profiles in the specified VSIG. */ static int ice_get_profs_vsig(struct ice_hw *hw, enum ice_block blk, u16 vsig, struct list_head *lst) { struct ice_vsig_prof *ent1, *ent2; u16 idx = vsig & ICE_VSIG_IDX_M; list_for_each_entry(ent1, &hw->blk[blk].xlt2.vsig_tbl[idx].prop_lst, list) { struct ice_vsig_prof *p; /* copy to the input list */ p = devm_kmemdup(ice_hw_to_dev(hw), ent1, sizeof(*p), GFP_KERNEL); if (!p) goto err_ice_get_profs_vsig; list_add_tail(&p->list, lst); } return 0; err_ice_get_profs_vsig: list_for_each_entry_safe(ent1, ent2, lst, list) { list_del(&ent1->list); devm_kfree(ice_hw_to_dev(hw), ent1); } return -ENOMEM; } /** * ice_add_prof_to_lst - add profile entry to a list * @hw: pointer to the HW struct * @blk: hardware block * @lst: the list to be added to * @hdl: profile handle of entry to add */ static int ice_add_prof_to_lst(struct ice_hw *hw, enum ice_block blk, struct list_head *lst, u64 hdl) { struct ice_prof_map *map; struct ice_vsig_prof *p; int status = 0; u16 i; mutex_lock(&hw->blk[blk].es.prof_map_lock); map = ice_search_prof_id(hw, blk, hdl); if (!map) { status = -ENOENT; goto err_ice_add_prof_to_lst; } p = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*p), GFP_KERNEL); if (!p) { status = -ENOMEM; goto err_ice_add_prof_to_lst; } p->profile_cookie = map->profile_cookie; p->prof_id = map->prof_id; p->tcam_count = map->ptg_cnt; for (i = 0; i < map->ptg_cnt; i++) { p->tcam[i].prof_id = map->prof_id; p->tcam[i].tcam_idx = ICE_INVALID_TCAM; p->tcam[i].ptg = map->ptg[i]; } list_add(&p->list, lst); err_ice_add_prof_to_lst: mutex_unlock(&hw->blk[blk].es.prof_map_lock); return status; } /** * ice_move_vsi - move VSI to another VSIG * @hw: pointer to the HW struct * @blk: hardware block * @vsi: the VSI to move * @vsig: the VSIG to move the VSI to * @chg: the change list */ static int ice_move_vsi(struct ice_hw *hw, enum ice_block blk, u16 vsi, u16 vsig, struct list_head *chg) { struct ice_chs_chg *p; u16 orig_vsig; int status; p = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*p), GFP_KERNEL); if (!p) return -ENOMEM; status = ice_vsig_find_vsi(hw, blk, vsi, &orig_vsig); if (!status) status = ice_vsig_add_mv_vsi(hw, blk, vsi, vsig); if (status) { devm_kfree(ice_hw_to_dev(hw), p); return status; } p->type = ICE_VSI_MOVE; p->vsi = vsi; p->orig_vsig = orig_vsig; p->vsig = vsig; list_add(&p->list_entry, chg); return 0; } /** * ice_rem_chg_tcam_ent - remove a specific TCAM entry from change list * @hw: pointer to the HW struct * @idx: the index of the TCAM entry to remove * @chg: the list of change structures to search */ static void ice_rem_chg_tcam_ent(struct ice_hw *hw, u16 idx, struct list_head *chg) { struct ice_chs_chg *pos, *tmp; list_for_each_entry_safe(tmp, pos, chg, list_entry) if (tmp->type == ICE_TCAM_ADD && tmp->tcam_idx == idx) { list_del(&tmp->list_entry); devm_kfree(ice_hw_to_dev(hw), tmp); } } /** * ice_prof_tcam_ena_dis - add enable or disable TCAM change * @hw: pointer to the HW struct * @blk: hardware block * @enable: true to enable, false to disable * @vsig: the VSIG of the TCAM entry * @tcam: pointer the TCAM info structure of the TCAM to disable * @chg: the change list * * This function appends an enable or disable TCAM entry in the change log */ static int ice_prof_tcam_ena_dis(struct ice_hw *hw, enum ice_block blk, bool enable, u16 vsig, struct ice_tcam_inf *tcam, struct list_head *chg) { struct ice_chs_chg *p; int status; u8 vl_msk[ICE_TCAM_KEY_VAL_SZ] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; u8 dc_msk[ICE_TCAM_KEY_VAL_SZ] = { 0xFF, 0xFF, 0x00, 0x00, 0x00 }; u8 nm_msk[ICE_TCAM_KEY_VAL_SZ] = { 0x00, 0x00, 0x00, 0x00, 0x00 }; /* if disabling, free the TCAM */ if (!enable) { status = ice_rel_tcam_idx(hw, blk, tcam->tcam_idx); /* if we have already created a change for this TCAM entry, then * we need to remove that entry, in order to prevent writing to * a TCAM entry we no longer will have ownership of. */ ice_rem_chg_tcam_ent(hw, tcam->tcam_idx, chg); tcam->tcam_idx = 0; tcam->in_use = 0; return status; } /* for re-enabling, reallocate a TCAM */ /* for entries with empty attribute masks, allocate entry from * the bottom of the TCAM table; otherwise, allocate from the * top of the table in order to give it higher priority */ status = ice_alloc_tcam_ent(hw, blk, tcam->attr.mask == 0, &tcam->tcam_idx); if (status) return status; /* add TCAM to change list */ p = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*p), GFP_KERNEL); if (!p) return -ENOMEM; status = ice_tcam_write_entry(hw, blk, tcam->tcam_idx, tcam->prof_id, tcam->ptg, vsig, 0, tcam->attr.flags, vl_msk, dc_msk, nm_msk); if (status) goto err_ice_prof_tcam_ena_dis; tcam->in_use = 1; p->type = ICE_TCAM_ADD; p->add_tcam_idx = true; p->prof_id = tcam->prof_id; p->ptg = tcam->ptg; p->vsig = 0; p->tcam_idx = tcam->tcam_idx; /* log change */ list_add(&p->list_entry, chg); return 0; err_ice_prof_tcam_ena_dis: devm_kfree(ice_hw_to_dev(hw), p); return status; } /** * ice_adj_prof_priorities - adjust profile based on priorities * @hw: pointer to the HW struct * @blk: hardware block * @vsig: the VSIG for which to adjust profile priorities * @chg: the change list */ static int ice_adj_prof_priorities(struct ice_hw *hw, enum ice_block blk, u16 vsig, struct list_head *chg) { DECLARE_BITMAP(ptgs_used, ICE_XLT1_CNT); struct ice_vsig_prof *t; int status; u16 idx; bitmap_zero(ptgs_used, ICE_XLT1_CNT); idx = vsig & ICE_VSIG_IDX_M; /* Priority is based on the order in which the profiles are added. The * newest added profile has highest priority and the oldest added * profile has the lowest priority. Since the profile property list for * a VSIG is sorted from newest to oldest, this code traverses the list * in order and enables the first of each PTG that it finds (that is not * already enabled); it also disables any duplicate PTGs that it finds * in the older profiles (that are currently enabled). */ list_for_each_entry(t, &hw->blk[blk].xlt2.vsig_tbl[idx].prop_lst, list) { u16 i; for (i = 0; i < t->tcam_count; i++) { /* Scan the priorities from newest to oldest. * Make sure that the newest profiles take priority. */ if (test_bit(t->tcam[i].ptg, ptgs_used) && t->tcam[i].in_use) { /* need to mark this PTG as never match, as it * was already in use and therefore duplicate * (and lower priority) */ status = ice_prof_tcam_ena_dis(hw, blk, false, vsig, &t->tcam[i], chg); if (status) return status; } else if (!test_bit(t->tcam[i].ptg, ptgs_used) && !t->tcam[i].in_use) { /* need to enable this PTG, as it in not in use * and not enabled (highest priority) */ status = ice_prof_tcam_ena_dis(hw, blk, true, vsig, &t->tcam[i], chg); if (status) return status; } /* keep track of used ptgs */ __set_bit(t->tcam[i].ptg, ptgs_used); } } return 0; } /** * ice_add_prof_id_vsig - add profile to VSIG * @hw: pointer to the HW struct * @blk: hardware block * @vsig: the VSIG to which this profile is to be added * @hdl: the profile handle indicating the profile to add * @rev: true to add entries to the end of the list * @chg: the change list */ static int ice_add_prof_id_vsig(struct ice_hw *hw, enum ice_block blk, u16 vsig, u64 hdl, bool rev, struct list_head *chg) { /* Masks that ignore flags */ u8 vl_msk[ICE_TCAM_KEY_VAL_SZ] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; u8 dc_msk[ICE_TCAM_KEY_VAL_SZ] = { 0xFF, 0xFF, 0x00, 0x00, 0x00 }; u8 nm_msk[ICE_TCAM_KEY_VAL_SZ] = { 0x00, 0x00, 0x00, 0x00, 0x00 }; struct ice_prof_map *map; struct ice_vsig_prof *t; struct ice_chs_chg *p; u16 vsig_idx, i; int status = 0; /* Error, if this VSIG already has this profile */ if (ice_has_prof_vsig(hw, blk, vsig, hdl)) return -EEXIST; /* new VSIG profile structure */ t = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*t), GFP_KERNEL); if (!t) return -ENOMEM; mutex_lock(&hw->blk[blk].es.prof_map_lock); /* Get the details on the profile specified by the handle ID */ map = ice_search_prof_id(hw, blk, hdl); if (!map) { status = -ENOENT; goto err_ice_add_prof_id_vsig; } t->profile_cookie = map->profile_cookie; t->prof_id = map->prof_id; t->tcam_count = map->ptg_cnt; /* create TCAM entries */ for (i = 0; i < map->ptg_cnt; i++) { u16 tcam_idx; /* add TCAM to change list */ p = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*p), GFP_KERNEL); if (!p) { status = -ENOMEM; goto err_ice_add_prof_id_vsig; } /* allocate the TCAM entry index */ /* for entries with empty attribute masks, allocate entry from * the bottom of the TCAM table; otherwise, allocate from the * top of the table in order to give it higher priority */ status = ice_alloc_tcam_ent(hw, blk, map->attr[i].mask == 0, &tcam_idx); if (status) { devm_kfree(ice_hw_to_dev(hw), p); goto err_ice_add_prof_id_vsig; } t->tcam[i].ptg = map->ptg[i]; t->tcam[i].prof_id = map->prof_id; t->tcam[i].tcam_idx = tcam_idx; t->tcam[i].attr = map->attr[i]; t->tcam[i].in_use = true; p->type = ICE_TCAM_ADD; p->add_tcam_idx = true; p->prof_id = t->tcam[i].prof_id; p->ptg = t->tcam[i].ptg; p->vsig = vsig; p->tcam_idx = t->tcam[i].tcam_idx; /* write the TCAM entry */ status = ice_tcam_write_entry(hw, blk, t->tcam[i].tcam_idx, t->tcam[i].prof_id, t->tcam[i].ptg, vsig, 0, 0, vl_msk, dc_msk, nm_msk); if (status) { devm_kfree(ice_hw_to_dev(hw), p); goto err_ice_add_prof_id_vsig; } /* log change */ list_add(&p->list_entry, chg); } /* add profile to VSIG */ vsig_idx = vsig & ICE_VSIG_IDX_M; if (rev) list_add_tail(&t->list, &hw->blk[blk].xlt2.vsig_tbl[vsig_idx].prop_lst); else list_add(&t->list, &hw->blk[blk].xlt2.vsig_tbl[vsig_idx].prop_lst); mutex_unlock(&hw->blk[blk].es.prof_map_lock); return status; err_ice_add_prof_id_vsig: mutex_unlock(&hw->blk[blk].es.prof_map_lock); /* let caller clean up the change list */ devm_kfree(ice_hw_to_dev(hw), t); return status; } /** * ice_create_prof_id_vsig - add a new VSIG with a single profile * @hw: pointer to the HW struct * @blk: hardware block * @vsi: the initial VSI that will be in VSIG * @hdl: the profile handle of the profile that will be added to the VSIG * @chg: the change list */ static int ice_create_prof_id_vsig(struct ice_hw *hw, enum ice_block blk, u16 vsi, u64 hdl, struct list_head *chg) { struct ice_chs_chg *p; u16 new_vsig; int status; p = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*p), GFP_KERNEL); if (!p) return -ENOMEM; new_vsig = ice_vsig_alloc(hw, blk); if (!new_vsig) { status = -EIO; goto err_ice_create_prof_id_vsig; } status = ice_move_vsi(hw, blk, vsi, new_vsig, chg); if (status) goto err_ice_create_prof_id_vsig; status = ice_add_prof_id_vsig(hw, blk, new_vsig, hdl, false, chg); if (status) goto err_ice_create_prof_id_vsig; p->type = ICE_VSIG_ADD; p->vsi = vsi; p->orig_vsig = ICE_DEFAULT_VSIG; p->vsig = new_vsig; list_add(&p->list_entry, chg); return 0; err_ice_create_prof_id_vsig: /* let caller clean up the change list */ devm_kfree(ice_hw_to_dev(hw), p); return status; } /** * ice_create_vsig_from_lst - create a new VSIG with a list of profiles * @hw: pointer to the HW struct * @blk: hardware block * @vsi: the initial VSI that will be in VSIG * @lst: the list of profile that will be added to the VSIG * @new_vsig: return of new VSIG * @chg: the change list */ static int ice_create_vsig_from_lst(struct ice_hw *hw, enum ice_block blk, u16 vsi, struct list_head *lst, u16 *new_vsig, struct list_head *chg) { struct ice_vsig_prof *t; int status; u16 vsig; vsig = ice_vsig_alloc(hw, blk); if (!vsig) return -EIO; status = ice_move_vsi(hw, blk, vsi, vsig, chg); if (status) return status; list_for_each_entry(t, lst, list) { /* Reverse the order here since we are copying the list */ status = ice_add_prof_id_vsig(hw, blk, vsig, t->profile_cookie, true, chg); if (status) return status; } *new_vsig = vsig; return 0; } /** * ice_find_prof_vsig - find a VSIG with a specific profile handle * @hw: pointer to the HW struct * @blk: hardware block * @hdl: the profile handle of the profile to search for * @vsig: returns the VSIG with the matching profile */ static bool ice_find_prof_vsig(struct ice_hw *hw, enum ice_block blk, u64 hdl, u16 *vsig) { struct ice_vsig_prof *t; struct list_head lst; int status; INIT_LIST_HEAD(&lst); t = kzalloc(sizeof(*t), GFP_KERNEL); if (!t) return false; t->profile_cookie = hdl; list_add(&t->list, &lst); status = ice_find_dup_props_vsig(hw, blk, &lst, vsig); list_del(&t->list); kfree(t); return !status; } /** * ice_add_prof_id_flow - add profile flow * @hw: pointer to the HW struct * @blk: hardware block * @vsi: the VSI to enable with the profile specified by ID * @hdl: profile handle * * Calling this function will update the hardware tables to enable the * profile indicated by the ID parameter for the VSIs specified in the VSI * array. Once successfully called, the flow will be enabled. */ int ice_add_prof_id_flow(struct ice_hw *hw, enum ice_block blk, u16 vsi, u64 hdl) { struct ice_vsig_prof *tmp1, *del1; struct ice_chs_chg *tmp, *del; struct list_head union_lst; struct list_head chg; int status; u16 vsig; INIT_LIST_HEAD(&union_lst); INIT_LIST_HEAD(&chg); /* Get profile */ status = ice_get_prof(hw, blk, hdl, &chg); if (status) return status; /* determine if VSI is already part of a VSIG */ status = ice_vsig_find_vsi(hw, blk, vsi, &vsig); if (!status && vsig) { bool only_vsi; u16 or_vsig; u16 ref; /* found in VSIG */ or_vsig = vsig; /* make sure that there is no overlap/conflict between the new * characteristics and the existing ones; we don't support that * scenario */ if (ice_has_prof_vsig(hw, blk, vsig, hdl)) { status = -EEXIST; goto err_ice_add_prof_id_flow; } /* last VSI in the VSIG? */ status = ice_vsig_get_ref(hw, blk, vsig, &ref); if (status) goto err_ice_add_prof_id_flow; only_vsi = (ref == 1); /* create a union of the current profiles and the one being * added */ status = ice_get_profs_vsig(hw, blk, vsig, &union_lst); if (status) goto err_ice_add_prof_id_flow; status = ice_add_prof_to_lst(hw, blk, &union_lst, hdl); if (status) goto err_ice_add_prof_id_flow; /* search for an existing VSIG with an exact charc match */ status = ice_find_dup_props_vsig(hw, blk, &union_lst, &vsig); if (!status) { /* move VSI to the VSIG that matches */ status = ice_move_vsi(hw, blk, vsi, vsig, &chg); if (status) goto err_ice_add_prof_id_flow; /* VSI has been moved out of or_vsig. If the or_vsig had * only that VSI it is now empty and can be removed. */ if (only_vsi) { status = ice_rem_vsig(hw, blk, or_vsig, &chg); if (status) goto err_ice_add_prof_id_flow; } } else if (only_vsi) { /* If the original VSIG only contains one VSI, then it * will be the requesting VSI. In this case the VSI is * not sharing entries and we can simply add the new * profile to the VSIG. */ status = ice_add_prof_id_vsig(hw, blk, vsig, hdl, false, &chg); if (status) goto err_ice_add_prof_id_flow; /* Adjust priorities */ status = ice_adj_prof_priorities(hw, blk, vsig, &chg); if (status) goto err_ice_add_prof_id_flow; } else { /* No match, so we need a new VSIG */ status = ice_create_vsig_from_lst(hw, blk, vsi, &union_lst, &vsig, &chg); if (status) goto err_ice_add_prof_id_flow; /* Adjust priorities */ status = ice_adj_prof_priorities(hw, blk, vsig, &chg); if (status) goto err_ice_add_prof_id_flow; } } else { /* need to find or add a VSIG */ /* search for an existing VSIG with an exact charc match */ if (ice_find_prof_vsig(hw, blk, hdl, &vsig)) { /* found an exact match */ /* add or move VSI to the VSIG that matches */ status = ice_move_vsi(hw, blk, vsi, vsig, &chg); if (status) goto err_ice_add_prof_id_flow; } else { /* we did not find an exact match */ /* we need to add a VSIG */ status = ice_create_prof_id_vsig(hw, blk, vsi, hdl, &chg); if (status) goto err_ice_add_prof_id_flow; } } /* update hardware */ if (!status) status = ice_upd_prof_hw(hw, blk, &chg); err_ice_add_prof_id_flow: list_for_each_entry_safe(del, tmp, &chg, list_entry) { list_del(&del->list_entry); devm_kfree(ice_hw_to_dev(hw), del); } list_for_each_entry_safe(del1, tmp1, &union_lst, list) { list_del(&del1->list); devm_kfree(ice_hw_to_dev(hw), del1); } return status; } /** * ice_rem_prof_from_list - remove a profile from list * @hw: pointer to the HW struct * @lst: list to remove the profile from * @hdl: the profile handle indicating the profile to remove */ static int ice_rem_prof_from_list(struct ice_hw *hw, struct list_head *lst, u64 hdl) { struct ice_vsig_prof *ent, *tmp; list_for_each_entry_safe(ent, tmp, lst, list) if (ent->profile_cookie == hdl) { list_del(&ent->list); devm_kfree(ice_hw_to_dev(hw), ent); return 0; } return -ENOENT; } /** * ice_rem_prof_id_flow - remove flow * @hw: pointer to the HW struct * @blk: hardware block * @vsi: the VSI from which to remove the profile specified by ID * @hdl: profile tracking handle * * Calling this function will update the hardware tables to remove the * profile indicated by the ID parameter for the VSIs specified in the VSI * array. Once successfully called, the flow will be disabled. */ int ice_rem_prof_id_flow(struct ice_hw *hw, enum ice_block blk, u16 vsi, u64 hdl) { struct ice_vsig_prof *tmp1, *del1; struct ice_chs_chg *tmp, *del; struct list_head chg, copy; int status; u16 vsig; INIT_LIST_HEAD(&copy); INIT_LIST_HEAD(&chg); /* determine if VSI is already part of a VSIG */ status = ice_vsig_find_vsi(hw, blk, vsi, &vsig); if (!status && vsig) { bool last_profile; bool only_vsi; u16 ref; /* found in VSIG */ last_profile = ice_vsig_prof_id_count(hw, blk, vsig) == 1; status = ice_vsig_get_ref(hw, blk, vsig, &ref); if (status) goto err_ice_rem_prof_id_flow; only_vsi = (ref == 1); if (only_vsi) { /* If the original VSIG only contains one reference, * which will be the requesting VSI, then the VSI is not * sharing entries and we can simply remove the specific * characteristics from the VSIG. */ if (last_profile) { /* If there are no profiles left for this VSIG, * then simply remove the VSIG. */ status = ice_rem_vsig(hw, blk, vsig, &chg); if (status) goto err_ice_rem_prof_id_flow; } else { status = ice_rem_prof_id_vsig(hw, blk, vsig, hdl, &chg); if (status) goto err_ice_rem_prof_id_flow; /* Adjust priorities */ status = ice_adj_prof_priorities(hw, blk, vsig, &chg); if (status) goto err_ice_rem_prof_id_flow; } } else { /* Make a copy of the VSIG's list of Profiles */ status = ice_get_profs_vsig(hw, blk, vsig, &copy); if (status) goto err_ice_rem_prof_id_flow; /* Remove specified profile entry from the list */ status = ice_rem_prof_from_list(hw, &copy, hdl); if (status) goto err_ice_rem_prof_id_flow; if (list_empty(&copy)) { status = ice_move_vsi(hw, blk, vsi, ICE_DEFAULT_VSIG, &chg); if (status) goto err_ice_rem_prof_id_flow; } else if (!ice_find_dup_props_vsig(hw, blk, &copy, &vsig)) { /* found an exact match */ /* add or move VSI to the VSIG that matches */ /* Search for a VSIG with a matching profile * list */ /* Found match, move VSI to the matching VSIG */ status = ice_move_vsi(hw, blk, vsi, vsig, &chg); if (status) goto err_ice_rem_prof_id_flow; } else { /* since no existing VSIG supports this * characteristic pattern, we need to create a * new VSIG and TCAM entries */ status = ice_create_vsig_from_lst(hw, blk, vsi, &copy, &vsig, &chg); if (status) goto err_ice_rem_prof_id_flow; /* Adjust priorities */ status = ice_adj_prof_priorities(hw, blk, vsig, &chg); if (status) goto err_ice_rem_prof_id_flow; } } } else { status = -ENOENT; } /* update hardware tables */ if (!status) status = ice_upd_prof_hw(hw, blk, &chg); err_ice_rem_prof_id_flow: list_for_each_entry_safe(del, tmp, &chg, list_entry) { list_del(&del->list_entry); devm_kfree(ice_hw_to_dev(hw), del); } list_for_each_entry_safe(del1, tmp1, &copy, list) { list_del(&del1->list); devm_kfree(ice_hw_to_dev(hw), del1); } return status; }
linux-master
drivers/net/ethernet/intel/ice/ice_flex_pipe.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2021-2022, Intel Corporation. */ #include "ice.h" #include "ice_lib.h" /** * ice_gnss_do_write - Write data to internal GNSS receiver * @pf: board private structure * @buf: command buffer * @size: command buffer size * * Write UBX command data to the GNSS receiver * * Return: * * number of bytes written - success * * negative - error code */ static int ice_gnss_do_write(struct ice_pf *pf, const unsigned char *buf, unsigned int size) { struct ice_aqc_link_topo_addr link_topo; struct ice_hw *hw = &pf->hw; unsigned int offset = 0; int err = 0; memset(&link_topo, 0, sizeof(struct ice_aqc_link_topo_addr)); link_topo.topo_params.index = ICE_E810T_GNSS_I2C_BUS; link_topo.topo_params.node_type_ctx |= FIELD_PREP(ICE_AQC_LINK_TOPO_NODE_CTX_M, ICE_AQC_LINK_TOPO_NODE_CTX_OVERRIDE); /* It's not possible to write a single byte to u-blox. * Write all bytes in a loop until there are 6 or less bytes left. If * there are exactly 6 bytes left, the last write would be only a byte. * In this case, do 4+2 bytes writes instead of 5+1. Otherwise, do the * last 2 to 5 bytes write. */ while (size - offset > ICE_GNSS_UBX_WRITE_BYTES + 1) { err = ice_aq_write_i2c(hw, link_topo, ICE_GNSS_UBX_I2C_BUS_ADDR, cpu_to_le16(buf[offset]), ICE_MAX_I2C_WRITE_BYTES, &buf[offset + 1], NULL); if (err) goto err_out; offset += ICE_GNSS_UBX_WRITE_BYTES; } /* Single byte would be written. Write 4 bytes instead of 5. */ if (size - offset == ICE_GNSS_UBX_WRITE_BYTES + 1) { err = ice_aq_write_i2c(hw, link_topo, ICE_GNSS_UBX_I2C_BUS_ADDR, cpu_to_le16(buf[offset]), ICE_MAX_I2C_WRITE_BYTES - 1, &buf[offset + 1], NULL); if (err) goto err_out; offset += ICE_GNSS_UBX_WRITE_BYTES - 1; } /* Do the last write, 2 to 5 bytes. */ err = ice_aq_write_i2c(hw, link_topo, ICE_GNSS_UBX_I2C_BUS_ADDR, cpu_to_le16(buf[offset]), size - offset - 1, &buf[offset + 1], NULL); if (err) goto err_out; return size; err_out: dev_err(ice_pf_to_dev(pf), "GNSS failed to write, offset=%u, size=%u, err=%d\n", offset, size, err); return err; } /** * ice_gnss_read - Read data from internal GNSS module * @work: GNSS read work structure * * Read the data from internal GNSS receiver, write it to gnss_dev. */ static void ice_gnss_read(struct kthread_work *work) { struct gnss_serial *gnss = container_of(work, struct gnss_serial, read_work.work); unsigned long delay = ICE_GNSS_POLL_DATA_DELAY_TIME; unsigned int i, bytes_read, data_len, count; struct ice_aqc_link_topo_addr link_topo; struct ice_pf *pf; struct ice_hw *hw; __be16 data_len_b; char *buf = NULL; u8 i2c_params; int err = 0; pf = gnss->back; if (!pf || !test_bit(ICE_FLAG_GNSS, pf->flags)) return; hw = &pf->hw; memset(&link_topo, 0, sizeof(struct ice_aqc_link_topo_addr)); link_topo.topo_params.index = ICE_E810T_GNSS_I2C_BUS; link_topo.topo_params.node_type_ctx |= FIELD_PREP(ICE_AQC_LINK_TOPO_NODE_CTX_M, ICE_AQC_LINK_TOPO_NODE_CTX_OVERRIDE); i2c_params = ICE_GNSS_UBX_DATA_LEN_WIDTH | ICE_AQC_I2C_USE_REPEATED_START; err = ice_aq_read_i2c(hw, link_topo, ICE_GNSS_UBX_I2C_BUS_ADDR, cpu_to_le16(ICE_GNSS_UBX_DATA_LEN_H), i2c_params, (u8 *)&data_len_b, NULL); if (err) goto requeue; data_len = be16_to_cpu(data_len_b); if (data_len == 0 || data_len == U16_MAX) goto requeue; /* The u-blox has data_len bytes for us to read */ data_len = min_t(typeof(data_len), data_len, PAGE_SIZE); buf = (char *)get_zeroed_page(GFP_KERNEL); if (!buf) { err = -ENOMEM; goto requeue; } /* Read received data */ for (i = 0; i < data_len; i += bytes_read) { unsigned int bytes_left = data_len - i; bytes_read = min_t(typeof(bytes_left), bytes_left, ICE_MAX_I2C_DATA_SIZE); err = ice_aq_read_i2c(hw, link_topo, ICE_GNSS_UBX_I2C_BUS_ADDR, cpu_to_le16(ICE_GNSS_UBX_EMPTY_DATA), bytes_read, &buf[i], NULL); if (err) goto free_buf; } count = gnss_insert_raw(pf->gnss_dev, buf, i); if (count != i) dev_warn(ice_pf_to_dev(pf), "gnss_insert_raw ret=%d size=%d\n", count, i); delay = ICE_GNSS_TIMER_DELAY_TIME; free_buf: free_page((unsigned long)buf); requeue: kthread_queue_delayed_work(gnss->kworker, &gnss->read_work, delay); if (err) dev_dbg(ice_pf_to_dev(pf), "GNSS failed to read err=%d\n", err); } /** * ice_gnss_struct_init - Initialize GNSS receiver * @pf: Board private structure * * Initialize GNSS structures and workers. * * Return: * * pointer to initialized gnss_serial struct - success * * NULL - error */ static struct gnss_serial *ice_gnss_struct_init(struct ice_pf *pf) { struct device *dev = ice_pf_to_dev(pf); struct kthread_worker *kworker; struct gnss_serial *gnss; gnss = kzalloc(sizeof(*gnss), GFP_KERNEL); if (!gnss) return NULL; gnss->back = pf; pf->gnss_serial = gnss; kthread_init_delayed_work(&gnss->read_work, ice_gnss_read); kworker = kthread_create_worker(0, "ice-gnss-%s", dev_name(dev)); if (IS_ERR(kworker)) { kfree(gnss); return NULL; } gnss->kworker = kworker; return gnss; } /** * ice_gnss_open - Open GNSS device * @gdev: pointer to the gnss device struct * * Open GNSS device and start filling the read buffer for consumer. * * Return: * * 0 - success * * negative - error code */ static int ice_gnss_open(struct gnss_device *gdev) { struct ice_pf *pf = gnss_get_drvdata(gdev); struct gnss_serial *gnss; if (!pf) return -EFAULT; if (!test_bit(ICE_FLAG_GNSS, pf->flags)) return -EFAULT; gnss = pf->gnss_serial; if (!gnss) return -ENODEV; kthread_queue_delayed_work(gnss->kworker, &gnss->read_work, 0); return 0; } /** * ice_gnss_close - Close GNSS device * @gdev: pointer to the gnss device struct * * Close GNSS device, cancel worker, stop filling the read buffer. */ static void ice_gnss_close(struct gnss_device *gdev) { struct ice_pf *pf = gnss_get_drvdata(gdev); struct gnss_serial *gnss; if (!pf) return; gnss = pf->gnss_serial; if (!gnss) return; kthread_cancel_delayed_work_sync(&gnss->read_work); } /** * ice_gnss_write - Write to GNSS device * @gdev: pointer to the gnss device struct * @buf: pointer to the user data * @count: size of the buffer to be sent to the GNSS device * * Return: * * number of written bytes - success * * negative - error code */ static int ice_gnss_write(struct gnss_device *gdev, const unsigned char *buf, size_t count) { struct ice_pf *pf = gnss_get_drvdata(gdev); struct gnss_serial *gnss; /* We cannot write a single byte using our I2C implementation. */ if (count <= 1 || count > ICE_GNSS_TTY_WRITE_BUF) return -EINVAL; if (!pf) return -EFAULT; if (!test_bit(ICE_FLAG_GNSS, pf->flags)) return -EFAULT; gnss = pf->gnss_serial; if (!gnss) return -ENODEV; return ice_gnss_do_write(pf, buf, count); } static const struct gnss_operations ice_gnss_ops = { .open = ice_gnss_open, .close = ice_gnss_close, .write_raw = ice_gnss_write, }; /** * ice_gnss_register - Register GNSS receiver * @pf: Board private structure * * Allocate and register GNSS receiver in the Linux GNSS subsystem. * * Return: * * 0 - success * * negative - error code */ static int ice_gnss_register(struct ice_pf *pf) { struct gnss_device *gdev; int ret; gdev = gnss_allocate_device(ice_pf_to_dev(pf)); if (!gdev) { dev_err(ice_pf_to_dev(pf), "gnss_allocate_device returns NULL\n"); return -ENOMEM; } gdev->ops = &ice_gnss_ops; gdev->type = GNSS_TYPE_UBX; gnss_set_drvdata(gdev, pf); ret = gnss_register_device(gdev); if (ret) { dev_err(ice_pf_to_dev(pf), "gnss_register_device err=%d\n", ret); gnss_put_device(gdev); } else { pf->gnss_dev = gdev; } return ret; } /** * ice_gnss_deregister - Deregister GNSS receiver * @pf: Board private structure * * Deregister GNSS receiver from the Linux GNSS subsystem, * release its resources. */ static void ice_gnss_deregister(struct ice_pf *pf) { if (pf->gnss_dev) { gnss_deregister_device(pf->gnss_dev); gnss_put_device(pf->gnss_dev); pf->gnss_dev = NULL; } } /** * ice_gnss_init - Initialize GNSS support * @pf: Board private structure */ void ice_gnss_init(struct ice_pf *pf) { int ret; pf->gnss_serial = ice_gnss_struct_init(pf); if (!pf->gnss_serial) return; ret = ice_gnss_register(pf); if (!ret) { set_bit(ICE_FLAG_GNSS, pf->flags); dev_info(ice_pf_to_dev(pf), "GNSS init successful\n"); } else { ice_gnss_exit(pf); dev_err(ice_pf_to_dev(pf), "GNSS init failure\n"); } } /** * ice_gnss_exit - Disable GNSS TTY support * @pf: Board private structure */ void ice_gnss_exit(struct ice_pf *pf) { ice_gnss_deregister(pf); clear_bit(ICE_FLAG_GNSS, pf->flags); if (pf->gnss_serial) { struct gnss_serial *gnss = pf->gnss_serial; kthread_cancel_delayed_work_sync(&gnss->read_work); kthread_destroy_worker(gnss->kworker); gnss->kworker = NULL; kfree(gnss); pf->gnss_serial = NULL; } } /** * ice_gnss_is_gps_present - Check if GPS HW is present * @hw: pointer to HW struct */ bool ice_gnss_is_gps_present(struct ice_hw *hw) { if (!hw->func_caps.ts_func_info.src_tmr_owned) return false; #if IS_ENABLED(CONFIG_PTP_1588_CLOCK) if (ice_is_e810t(hw)) { int err; u8 data; err = ice_read_pca9575_reg_e810t(hw, ICE_PCA9575_P0_IN, &data); if (err || !!(data & ICE_E810T_P0_GNSS_PRSNT_N)) return false; } else { return false; } #else if (!ice_is_e810t(hw)) return false; #endif /* IS_ENABLED(CONFIG_PTP_1588_CLOCK) */ return true; }
linux-master
drivers/net/ethernet/intel/ice/ice_gnss.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2020, Intel Corporation. */ #include <linux/vmalloc.h> #include "ice.h" #include "ice_lib.h" #include "ice_devlink.h" #include "ice_eswitch.h" #include "ice_fw_update.h" #include "ice_dcb_lib.h" static int ice_active_port_option = -1; /* context for devlink info version reporting */ struct ice_info_ctx { char buf[128]; struct ice_orom_info pending_orom; struct ice_nvm_info pending_nvm; struct ice_netlist_info pending_netlist; struct ice_hw_dev_caps dev_caps; }; /* The following functions are used to format specific strings for various * devlink info versions. The ctx parameter is used to provide the storage * buffer, as well as any ancillary information calculated when the info * request was made. * * If a version does not exist, for example when attempting to get the * inactive version of flash when there is no pending update, the function * should leave the buffer in the ctx structure empty. */ static void ice_info_get_dsn(struct ice_pf *pf, struct ice_info_ctx *ctx) { u8 dsn[8]; /* Copy the DSN into an array in Big Endian format */ put_unaligned_be64(pci_get_dsn(pf->pdev), dsn); snprintf(ctx->buf, sizeof(ctx->buf), "%8phD", dsn); } static void ice_info_pba(struct ice_pf *pf, struct ice_info_ctx *ctx) { struct ice_hw *hw = &pf->hw; int status; status = ice_read_pba_string(hw, (u8 *)ctx->buf, sizeof(ctx->buf)); if (status) /* We failed to locate the PBA, so just skip this entry */ dev_dbg(ice_pf_to_dev(pf), "Failed to read Product Board Assembly string, status %d\n", status); } static void ice_info_fw_mgmt(struct ice_pf *pf, struct ice_info_ctx *ctx) { struct ice_hw *hw = &pf->hw; snprintf(ctx->buf, sizeof(ctx->buf), "%u.%u.%u", hw->fw_maj_ver, hw->fw_min_ver, hw->fw_patch); } static void ice_info_fw_api(struct ice_pf *pf, struct ice_info_ctx *ctx) { struct ice_hw *hw = &pf->hw; snprintf(ctx->buf, sizeof(ctx->buf), "%u.%u.%u", hw->api_maj_ver, hw->api_min_ver, hw->api_patch); } static void ice_info_fw_build(struct ice_pf *pf, struct ice_info_ctx *ctx) { struct ice_hw *hw = &pf->hw; snprintf(ctx->buf, sizeof(ctx->buf), "0x%08x", hw->fw_build); } static void ice_info_orom_ver(struct ice_pf *pf, struct ice_info_ctx *ctx) { struct ice_orom_info *orom = &pf->hw.flash.orom; snprintf(ctx->buf, sizeof(ctx->buf), "%u.%u.%u", orom->major, orom->build, orom->patch); } static void ice_info_pending_orom_ver(struct ice_pf __always_unused *pf, struct ice_info_ctx *ctx) { struct ice_orom_info *orom = &ctx->pending_orom; if (ctx->dev_caps.common_cap.nvm_update_pending_orom) snprintf(ctx->buf, sizeof(ctx->buf), "%u.%u.%u", orom->major, orom->build, orom->patch); } static void ice_info_nvm_ver(struct ice_pf *pf, struct ice_info_ctx *ctx) { struct ice_nvm_info *nvm = &pf->hw.flash.nvm; snprintf(ctx->buf, sizeof(ctx->buf), "%x.%02x", nvm->major, nvm->minor); } static void ice_info_pending_nvm_ver(struct ice_pf __always_unused *pf, struct ice_info_ctx *ctx) { struct ice_nvm_info *nvm = &ctx->pending_nvm; if (ctx->dev_caps.common_cap.nvm_update_pending_nvm) snprintf(ctx->buf, sizeof(ctx->buf), "%x.%02x", nvm->major, nvm->minor); } static void ice_info_eetrack(struct ice_pf *pf, struct ice_info_ctx *ctx) { struct ice_nvm_info *nvm = &pf->hw.flash.nvm; snprintf(ctx->buf, sizeof(ctx->buf), "0x%08x", nvm->eetrack); } static void ice_info_pending_eetrack(struct ice_pf *pf, struct ice_info_ctx *ctx) { struct ice_nvm_info *nvm = &ctx->pending_nvm; if (ctx->dev_caps.common_cap.nvm_update_pending_nvm) snprintf(ctx->buf, sizeof(ctx->buf), "0x%08x", nvm->eetrack); } static void ice_info_ddp_pkg_name(struct ice_pf *pf, struct ice_info_ctx *ctx) { struct ice_hw *hw = &pf->hw; snprintf(ctx->buf, sizeof(ctx->buf), "%s", hw->active_pkg_name); } static void ice_info_ddp_pkg_version(struct ice_pf *pf, struct ice_info_ctx *ctx) { struct ice_pkg_ver *pkg = &pf->hw.active_pkg_ver; snprintf(ctx->buf, sizeof(ctx->buf), "%u.%u.%u.%u", pkg->major, pkg->minor, pkg->update, pkg->draft); } static void ice_info_ddp_pkg_bundle_id(struct ice_pf *pf, struct ice_info_ctx *ctx) { snprintf(ctx->buf, sizeof(ctx->buf), "0x%08x", pf->hw.active_track_id); } static void ice_info_netlist_ver(struct ice_pf *pf, struct ice_info_ctx *ctx) { struct ice_netlist_info *netlist = &pf->hw.flash.netlist; /* The netlist version fields are BCD formatted */ snprintf(ctx->buf, sizeof(ctx->buf), "%x.%x.%x-%x.%x.%x", netlist->major, netlist->minor, netlist->type >> 16, netlist->type & 0xFFFF, netlist->rev, netlist->cust_ver); } static void ice_info_netlist_build(struct ice_pf *pf, struct ice_info_ctx *ctx) { struct ice_netlist_info *netlist = &pf->hw.flash.netlist; snprintf(ctx->buf, sizeof(ctx->buf), "0x%08x", netlist->hash); } static void ice_info_pending_netlist_ver(struct ice_pf __always_unused *pf, struct ice_info_ctx *ctx) { struct ice_netlist_info *netlist = &ctx->pending_netlist; /* The netlist version fields are BCD formatted */ if (ctx->dev_caps.common_cap.nvm_update_pending_netlist) snprintf(ctx->buf, sizeof(ctx->buf), "%x.%x.%x-%x.%x.%x", netlist->major, netlist->minor, netlist->type >> 16, netlist->type & 0xFFFF, netlist->rev, netlist->cust_ver); } static void ice_info_pending_netlist_build(struct ice_pf __always_unused *pf, struct ice_info_ctx *ctx) { struct ice_netlist_info *netlist = &ctx->pending_netlist; if (ctx->dev_caps.common_cap.nvm_update_pending_netlist) snprintf(ctx->buf, sizeof(ctx->buf), "0x%08x", netlist->hash); } #define fixed(key, getter) { ICE_VERSION_FIXED, key, getter, NULL } #define running(key, getter) { ICE_VERSION_RUNNING, key, getter, NULL } #define stored(key, getter, fallback) { ICE_VERSION_STORED, key, getter, fallback } /* The combined() macro inserts both the running entry as well as a stored * entry. The running entry will always report the version from the active * handler. The stored entry will first try the pending handler, and fallback * to the active handler if the pending function does not report a version. * The pending handler should check the status of a pending update for the * relevant flash component. It should only fill in the buffer in the case * where a valid pending version is available. This ensures that the related * stored and running versions remain in sync, and that stored versions are * correctly reported as expected. */ #define combined(key, active, pending) \ running(key, active), \ stored(key, pending, active) enum ice_version_type { ICE_VERSION_FIXED, ICE_VERSION_RUNNING, ICE_VERSION_STORED, }; static const struct ice_devlink_version { enum ice_version_type type; const char *key; void (*getter)(struct ice_pf *pf, struct ice_info_ctx *ctx); void (*fallback)(struct ice_pf *pf, struct ice_info_ctx *ctx); } ice_devlink_versions[] = { fixed(DEVLINK_INFO_VERSION_GENERIC_BOARD_ID, ice_info_pba), running(DEVLINK_INFO_VERSION_GENERIC_FW_MGMT, ice_info_fw_mgmt), running("fw.mgmt.api", ice_info_fw_api), running("fw.mgmt.build", ice_info_fw_build), combined(DEVLINK_INFO_VERSION_GENERIC_FW_UNDI, ice_info_orom_ver, ice_info_pending_orom_ver), combined("fw.psid.api", ice_info_nvm_ver, ice_info_pending_nvm_ver), combined(DEVLINK_INFO_VERSION_GENERIC_FW_BUNDLE_ID, ice_info_eetrack, ice_info_pending_eetrack), running("fw.app.name", ice_info_ddp_pkg_name), running(DEVLINK_INFO_VERSION_GENERIC_FW_APP, ice_info_ddp_pkg_version), running("fw.app.bundle_id", ice_info_ddp_pkg_bundle_id), combined("fw.netlist", ice_info_netlist_ver, ice_info_pending_netlist_ver), combined("fw.netlist.build", ice_info_netlist_build, ice_info_pending_netlist_build), }; /** * ice_devlink_info_get - .info_get devlink handler * @devlink: devlink instance structure * @req: the devlink info request * @extack: extended netdev ack structure * * Callback for the devlink .info_get operation. Reports information about the * device. * * Return: zero on success or an error code on failure. */ static int ice_devlink_info_get(struct devlink *devlink, struct devlink_info_req *req, struct netlink_ext_ack *extack) { struct ice_pf *pf = devlink_priv(devlink); struct device *dev = ice_pf_to_dev(pf); struct ice_hw *hw = &pf->hw; struct ice_info_ctx *ctx; size_t i; int err; err = ice_wait_for_reset(pf, 10 * HZ); if (err) { NL_SET_ERR_MSG_MOD(extack, "Device is busy resetting"); return err; } ctx = kzalloc(sizeof(*ctx), GFP_KERNEL); if (!ctx) return -ENOMEM; /* discover capabilities first */ err = ice_discover_dev_caps(hw, &ctx->dev_caps); if (err) { dev_dbg(dev, "Failed to discover device capabilities, status %d aq_err %s\n", err, ice_aq_str(hw->adminq.sq_last_status)); NL_SET_ERR_MSG_MOD(extack, "Unable to discover device capabilities"); goto out_free_ctx; } if (ctx->dev_caps.common_cap.nvm_update_pending_orom) { err = ice_get_inactive_orom_ver(hw, &ctx->pending_orom); if (err) { dev_dbg(dev, "Unable to read inactive Option ROM version data, status %d aq_err %s\n", err, ice_aq_str(hw->adminq.sq_last_status)); /* disable display of pending Option ROM */ ctx->dev_caps.common_cap.nvm_update_pending_orom = false; } } if (ctx->dev_caps.common_cap.nvm_update_pending_nvm) { err = ice_get_inactive_nvm_ver(hw, &ctx->pending_nvm); if (err) { dev_dbg(dev, "Unable to read inactive NVM version data, status %d aq_err %s\n", err, ice_aq_str(hw->adminq.sq_last_status)); /* disable display of pending Option ROM */ ctx->dev_caps.common_cap.nvm_update_pending_nvm = false; } } if (ctx->dev_caps.common_cap.nvm_update_pending_netlist) { err = ice_get_inactive_netlist_ver(hw, &ctx->pending_netlist); if (err) { dev_dbg(dev, "Unable to read inactive Netlist version data, status %d aq_err %s\n", err, ice_aq_str(hw->adminq.sq_last_status)); /* disable display of pending Option ROM */ ctx->dev_caps.common_cap.nvm_update_pending_netlist = false; } } ice_info_get_dsn(pf, ctx); err = devlink_info_serial_number_put(req, ctx->buf); if (err) { NL_SET_ERR_MSG_MOD(extack, "Unable to set serial number"); goto out_free_ctx; } for (i = 0; i < ARRAY_SIZE(ice_devlink_versions); i++) { enum ice_version_type type = ice_devlink_versions[i].type; const char *key = ice_devlink_versions[i].key; memset(ctx->buf, 0, sizeof(ctx->buf)); ice_devlink_versions[i].getter(pf, ctx); /* If the default getter doesn't report a version, use the * fallback function. This is primarily useful in the case of * "stored" versions that want to report the same value as the * running version in the normal case of no pending update. */ if (ctx->buf[0] == '\0' && ice_devlink_versions[i].fallback) ice_devlink_versions[i].fallback(pf, ctx); /* Do not report missing versions */ if (ctx->buf[0] == '\0') continue; switch (type) { case ICE_VERSION_FIXED: err = devlink_info_version_fixed_put(req, key, ctx->buf); if (err) { NL_SET_ERR_MSG_MOD(extack, "Unable to set fixed version"); goto out_free_ctx; } break; case ICE_VERSION_RUNNING: err = devlink_info_version_running_put(req, key, ctx->buf); if (err) { NL_SET_ERR_MSG_MOD(extack, "Unable to set running version"); goto out_free_ctx; } break; case ICE_VERSION_STORED: err = devlink_info_version_stored_put(req, key, ctx->buf); if (err) { NL_SET_ERR_MSG_MOD(extack, "Unable to set stored version"); goto out_free_ctx; } break; } } out_free_ctx: kfree(ctx); return err; } /** * ice_devlink_reload_empr_start - Start EMP reset to activate new firmware * @pf: pointer to the pf instance * @extack: netlink extended ACK structure * * Allow user to activate new Embedded Management Processor firmware by * issuing device specific EMP reset. Called in response to * a DEVLINK_CMD_RELOAD with the DEVLINK_RELOAD_ACTION_FW_ACTIVATE. * * Note that teardown and rebuild of the driver state happens automatically as * part of an interrupt and watchdog task. This is because all physical * functions on the device must be able to reset when an EMP reset occurs from * any source. */ static int ice_devlink_reload_empr_start(struct ice_pf *pf, struct netlink_ext_ack *extack) { struct device *dev = ice_pf_to_dev(pf); struct ice_hw *hw = &pf->hw; u8 pending; int err; err = ice_get_pending_updates(pf, &pending, extack); if (err) return err; /* pending is a bitmask of which flash banks have a pending update, * including the main NVM bank, the Option ROM bank, and the netlist * bank. If any of these bits are set, then there is a pending update * waiting to be activated. */ if (!pending) { NL_SET_ERR_MSG_MOD(extack, "No pending firmware update"); return -ECANCELED; } if (pf->fw_emp_reset_disabled) { NL_SET_ERR_MSG_MOD(extack, "EMP reset is not available. To activate firmware, a reboot or power cycle is needed"); return -ECANCELED; } dev_dbg(dev, "Issuing device EMP reset to activate firmware\n"); err = ice_aq_nvm_update_empr(hw); if (err) { dev_err(dev, "Failed to trigger EMP device reset to reload firmware, err %d aq_err %s\n", err, ice_aq_str(hw->adminq.sq_last_status)); NL_SET_ERR_MSG_MOD(extack, "Failed to trigger EMP device reset to reload firmware"); return err; } return 0; } /** * ice_devlink_reload_down - prepare for reload * @devlink: pointer to the devlink instance to reload * @netns_change: if true, the network namespace is changing * @action: the action to perform * @limit: limits on what reload should do, such as not resetting * @extack: netlink extended ACK structure */ static int ice_devlink_reload_down(struct devlink *devlink, bool netns_change, enum devlink_reload_action action, enum devlink_reload_limit limit, struct netlink_ext_ack *extack) { struct ice_pf *pf = devlink_priv(devlink); switch (action) { case DEVLINK_RELOAD_ACTION_DRIVER_REINIT: if (ice_is_eswitch_mode_switchdev(pf)) { NL_SET_ERR_MSG_MOD(extack, "Go to legacy mode before doing reinit\n"); return -EOPNOTSUPP; } if (ice_is_adq_active(pf)) { NL_SET_ERR_MSG_MOD(extack, "Turn off ADQ before doing reinit\n"); return -EOPNOTSUPP; } if (ice_has_vfs(pf)) { NL_SET_ERR_MSG_MOD(extack, "Remove all VFs before doing reinit\n"); return -EOPNOTSUPP; } ice_unload(pf); return 0; case DEVLINK_RELOAD_ACTION_FW_ACTIVATE: return ice_devlink_reload_empr_start(pf, extack); default: WARN_ON(1); return -EOPNOTSUPP; } } /** * ice_devlink_reload_empr_finish - Wait for EMP reset to finish * @pf: pointer to the pf instance * @extack: netlink extended ACK structure * * Wait for driver to finish rebuilding after EMP reset is completed. This * includes time to wait for both the actual device reset as well as the time * for the driver's rebuild to complete. */ static int ice_devlink_reload_empr_finish(struct ice_pf *pf, struct netlink_ext_ack *extack) { int err; err = ice_wait_for_reset(pf, 60 * HZ); if (err) { NL_SET_ERR_MSG_MOD(extack, "Device still resetting after 1 minute"); return err; } return 0; } /** * ice_devlink_port_opt_speed_str - convert speed to a string * @speed: speed value */ static const char *ice_devlink_port_opt_speed_str(u8 speed) { switch (speed & ICE_AQC_PORT_OPT_MAX_LANE_M) { case ICE_AQC_PORT_OPT_MAX_LANE_100M: return "0.1"; case ICE_AQC_PORT_OPT_MAX_LANE_1G: return "1"; case ICE_AQC_PORT_OPT_MAX_LANE_2500M: return "2.5"; case ICE_AQC_PORT_OPT_MAX_LANE_5G: return "5"; case ICE_AQC_PORT_OPT_MAX_LANE_10G: return "10"; case ICE_AQC_PORT_OPT_MAX_LANE_25G: return "25"; case ICE_AQC_PORT_OPT_MAX_LANE_50G: return "50"; case ICE_AQC_PORT_OPT_MAX_LANE_100G: return "100"; } return "-"; } #define ICE_PORT_OPT_DESC_LEN 50 /** * ice_devlink_port_options_print - Print available port split options * @pf: the PF to print split port options * * Prints a table with available port split options and max port speeds */ static void ice_devlink_port_options_print(struct ice_pf *pf) { u8 i, j, options_count, cnt, speed, pending_idx, active_idx; struct ice_aqc_get_port_options_elem *options, *opt; struct device *dev = ice_pf_to_dev(pf); bool active_valid, pending_valid; char desc[ICE_PORT_OPT_DESC_LEN]; const char *str; int status; options = kcalloc(ICE_AQC_PORT_OPT_MAX * ICE_MAX_PORT_PER_PCI_DEV, sizeof(*options), GFP_KERNEL); if (!options) return; for (i = 0; i < ICE_MAX_PORT_PER_PCI_DEV; i++) { opt = options + i * ICE_AQC_PORT_OPT_MAX; options_count = ICE_AQC_PORT_OPT_MAX; active_valid = 0; status = ice_aq_get_port_options(&pf->hw, opt, &options_count, i, true, &active_idx, &active_valid, &pending_idx, &pending_valid); if (status) { dev_dbg(dev, "Couldn't read port option for port %d, err %d\n", i, status); goto err; } } dev_dbg(dev, "Available port split options and max port speeds (Gbps):\n"); dev_dbg(dev, "Status Split Quad 0 Quad 1\n"); dev_dbg(dev, " count L0 L1 L2 L3 L4 L5 L6 L7\n"); for (i = 0; i < options_count; i++) { cnt = 0; if (i == ice_active_port_option) str = "Active"; else if ((i == pending_idx) && pending_valid) str = "Pending"; else str = ""; cnt += snprintf(&desc[cnt], ICE_PORT_OPT_DESC_LEN - cnt, "%-8s", str); cnt += snprintf(&desc[cnt], ICE_PORT_OPT_DESC_LEN - cnt, "%-6u", options[i].pmd); for (j = 0; j < ICE_MAX_PORT_PER_PCI_DEV; ++j) { speed = options[i + j * ICE_AQC_PORT_OPT_MAX].max_lane_speed; str = ice_devlink_port_opt_speed_str(speed); cnt += snprintf(&desc[cnt], ICE_PORT_OPT_DESC_LEN - cnt, "%3s ", str); } dev_dbg(dev, "%s\n", desc); } err: kfree(options); } /** * ice_devlink_aq_set_port_option - Send set port option admin queue command * @pf: the PF to print split port options * @option_idx: selected port option * @extack: extended netdev ack structure * * Sends set port option admin queue command with selected port option and * calls NVM write activate. */ static int ice_devlink_aq_set_port_option(struct ice_pf *pf, u8 option_idx, struct netlink_ext_ack *extack) { struct device *dev = ice_pf_to_dev(pf); int status; status = ice_aq_set_port_option(&pf->hw, 0, true, option_idx); if (status) { dev_dbg(dev, "ice_aq_set_port_option, err %d aq_err %d\n", status, pf->hw.adminq.sq_last_status); NL_SET_ERR_MSG_MOD(extack, "Port split request failed"); return -EIO; } status = ice_acquire_nvm(&pf->hw, ICE_RES_WRITE); if (status) { dev_dbg(dev, "ice_acquire_nvm failed, err %d aq_err %d\n", status, pf->hw.adminq.sq_last_status); NL_SET_ERR_MSG_MOD(extack, "Failed to acquire NVM semaphore"); return -EIO; } status = ice_nvm_write_activate(&pf->hw, ICE_AQC_NVM_ACTIV_REQ_EMPR, NULL); if (status) { dev_dbg(dev, "ice_nvm_write_activate failed, err %d aq_err %d\n", status, pf->hw.adminq.sq_last_status); NL_SET_ERR_MSG_MOD(extack, "Port split request failed to save data"); ice_release_nvm(&pf->hw); return -EIO; } ice_release_nvm(&pf->hw); NL_SET_ERR_MSG_MOD(extack, "Reboot required to finish port split"); return 0; } /** * ice_devlink_port_split - .port_split devlink handler * @devlink: devlink instance structure * @port: devlink port structure * @count: number of ports to split to * @extack: extended netdev ack structure * * Callback for the devlink .port_split operation. * * Unfortunately, the devlink expression of available options is limited * to just a number, so search for an FW port option which supports * the specified number. As there could be multiple FW port options with * the same port split count, allow switching between them. When the same * port split count request is issued again, switch to the next FW port * option with the same port split count. * * Return: zero on success or an error code on failure. */ static int ice_devlink_port_split(struct devlink *devlink, struct devlink_port *port, unsigned int count, struct netlink_ext_ack *extack) { struct ice_aqc_get_port_options_elem options[ICE_AQC_PORT_OPT_MAX]; u8 i, j, active_idx, pending_idx, new_option; struct ice_pf *pf = devlink_priv(devlink); u8 option_count = ICE_AQC_PORT_OPT_MAX; struct device *dev = ice_pf_to_dev(pf); bool active_valid, pending_valid; int status; status = ice_aq_get_port_options(&pf->hw, options, &option_count, 0, true, &active_idx, &active_valid, &pending_idx, &pending_valid); if (status) { dev_dbg(dev, "Couldn't read port split options, err = %d\n", status); NL_SET_ERR_MSG_MOD(extack, "Failed to get available port split options"); return -EIO; } new_option = ICE_AQC_PORT_OPT_MAX; active_idx = pending_valid ? pending_idx : active_idx; for (i = 1; i <= option_count; i++) { /* In order to allow switching between FW port options with * the same port split count, search for a new option starting * from the active/pending option (with array wrap around). */ j = (active_idx + i) % option_count; if (count == options[j].pmd) { new_option = j; break; } } if (new_option == active_idx) { dev_dbg(dev, "request to split: count: %u is already set and there are no other options\n", count); NL_SET_ERR_MSG_MOD(extack, "Requested split count is already set"); ice_devlink_port_options_print(pf); return -EINVAL; } if (new_option == ICE_AQC_PORT_OPT_MAX) { dev_dbg(dev, "request to split: count: %u not found\n", count); NL_SET_ERR_MSG_MOD(extack, "Port split requested unsupported port config"); ice_devlink_port_options_print(pf); return -EINVAL; } status = ice_devlink_aq_set_port_option(pf, new_option, extack); if (status) return status; ice_devlink_port_options_print(pf); return 0; } /** * ice_devlink_port_unsplit - .port_unsplit devlink handler * @devlink: devlink instance structure * @port: devlink port structure * @extack: extended netdev ack structure * * Callback for the devlink .port_unsplit operation. * Calls ice_devlink_port_split with split count set to 1. * There could be no FW option available with split count 1. * * Return: zero on success or an error code on failure. */ static int ice_devlink_port_unsplit(struct devlink *devlink, struct devlink_port *port, struct netlink_ext_ack *extack) { return ice_devlink_port_split(devlink, port, 1, extack); } /** * ice_tear_down_devlink_rate_tree - removes devlink-rate exported tree * @pf: pf struct * * This function tears down tree exported during VF's creation. */ void ice_tear_down_devlink_rate_tree(struct ice_pf *pf) { struct devlink *devlink; struct ice_vf *vf; unsigned int bkt; devlink = priv_to_devlink(pf); devl_lock(devlink); mutex_lock(&pf->vfs.table_lock); ice_for_each_vf(pf, bkt, vf) { if (vf->devlink_port.devlink_rate) devl_rate_leaf_destroy(&vf->devlink_port); } mutex_unlock(&pf->vfs.table_lock); devl_rate_nodes_destroy(devlink); devl_unlock(devlink); } /** * ice_enable_custom_tx - try to enable custom Tx feature * @pf: pf struct * * This function tries to enable custom Tx feature, * it's not possible to enable it, if DCB or ADQ is active. */ static bool ice_enable_custom_tx(struct ice_pf *pf) { struct ice_port_info *pi = ice_get_main_vsi(pf)->port_info; struct device *dev = ice_pf_to_dev(pf); if (pi->is_custom_tx_enabled) /* already enabled, return true */ return true; if (ice_is_adq_active(pf)) { dev_err(dev, "ADQ active, can't modify Tx scheduler tree\n"); return false; } if (ice_is_dcb_active(pf)) { dev_err(dev, "DCB active, can't modify Tx scheduler tree\n"); return false; } pi->is_custom_tx_enabled = true; return true; } /** * ice_traverse_tx_tree - traverse Tx scheduler tree * @devlink: devlink struct * @node: current node, used for recursion * @tc_node: tc_node struct, that is treated as a root * @pf: pf struct * * This function traverses Tx scheduler tree and exports * entire structure to the devlink-rate. */ static void ice_traverse_tx_tree(struct devlink *devlink, struct ice_sched_node *node, struct ice_sched_node *tc_node, struct ice_pf *pf) { struct devlink_rate *rate_node = NULL; struct ice_vf *vf; int i; if (node->parent == tc_node) { /* create root node */ rate_node = devl_rate_node_create(devlink, node, node->name, NULL); } else if (node->vsi_handle && pf->vsi[node->vsi_handle]->vf) { vf = pf->vsi[node->vsi_handle]->vf; if (!vf->devlink_port.devlink_rate) /* leaf nodes doesn't have children * so we don't set rate_node */ devl_rate_leaf_create(&vf->devlink_port, node, node->parent->rate_node); } else if (node->info.data.elem_type != ICE_AQC_ELEM_TYPE_LEAF && node->parent->rate_node) { rate_node = devl_rate_node_create(devlink, node, node->name, node->parent->rate_node); } if (rate_node && !IS_ERR(rate_node)) node->rate_node = rate_node; for (i = 0; i < node->num_children; i++) ice_traverse_tx_tree(devlink, node->children[i], tc_node, pf); } /** * ice_devlink_rate_init_tx_topology - export Tx scheduler tree to devlink rate * @devlink: devlink struct * @vsi: main vsi struct * * This function finds a root node, then calls ice_traverse_tx tree, which * traverses the tree and exports it's contents to devlink rate. */ int ice_devlink_rate_init_tx_topology(struct devlink *devlink, struct ice_vsi *vsi) { struct ice_port_info *pi = vsi->port_info; struct ice_sched_node *tc_node; struct ice_pf *pf = vsi->back; int i; tc_node = pi->root->children[0]; mutex_lock(&pi->sched_lock); devl_lock(devlink); for (i = 0; i < tc_node->num_children; i++) ice_traverse_tx_tree(devlink, tc_node->children[i], tc_node, pf); devl_unlock(devlink); mutex_unlock(&pi->sched_lock); return 0; } /** * ice_set_object_tx_share - sets node scheduling parameter * @pi: devlink struct instance * @node: node struct instance * @bw: bandwidth in bytes per second * @extack: extended netdev ack structure * * This function sets ICE_MIN_BW scheduling BW limit. */ static int ice_set_object_tx_share(struct ice_port_info *pi, struct ice_sched_node *node, u64 bw, struct netlink_ext_ack *extack) { int status; mutex_lock(&pi->sched_lock); /* converts bytes per second to kilo bits per second */ node->tx_share = div_u64(bw, 125); status = ice_sched_set_node_bw_lmt(pi, node, ICE_MIN_BW, node->tx_share); mutex_unlock(&pi->sched_lock); if (status) NL_SET_ERR_MSG_MOD(extack, "Can't set scheduling node tx_share"); return status; } /** * ice_set_object_tx_max - sets node scheduling parameter * @pi: devlink struct instance * @node: node struct instance * @bw: bandwidth in bytes per second * @extack: extended netdev ack structure * * This function sets ICE_MAX_BW scheduling BW limit. */ static int ice_set_object_tx_max(struct ice_port_info *pi, struct ice_sched_node *node, u64 bw, struct netlink_ext_ack *extack) { int status; mutex_lock(&pi->sched_lock); /* converts bytes per second value to kilo bits per second */ node->tx_max = div_u64(bw, 125); status = ice_sched_set_node_bw_lmt(pi, node, ICE_MAX_BW, node->tx_max); mutex_unlock(&pi->sched_lock); if (status) NL_SET_ERR_MSG_MOD(extack, "Can't set scheduling node tx_max"); return status; } /** * ice_set_object_tx_priority - sets node scheduling parameter * @pi: devlink struct instance * @node: node struct instance * @priority: value representing priority for strict priority arbitration * @extack: extended netdev ack structure * * This function sets priority of node among siblings. */ static int ice_set_object_tx_priority(struct ice_port_info *pi, struct ice_sched_node *node, u32 priority, struct netlink_ext_ack *extack) { int status; if (priority >= 8) { NL_SET_ERR_MSG_MOD(extack, "Priority should be less than 8"); return -EINVAL; } mutex_lock(&pi->sched_lock); node->tx_priority = priority; status = ice_sched_set_node_priority(pi, node, node->tx_priority); mutex_unlock(&pi->sched_lock); if (status) NL_SET_ERR_MSG_MOD(extack, "Can't set scheduling node tx_priority"); return status; } /** * ice_set_object_tx_weight - sets node scheduling parameter * @pi: devlink struct instance * @node: node struct instance * @weight: value represeting relative weight for WFQ arbitration * @extack: extended netdev ack structure * * This function sets node weight for WFQ algorithm. */ static int ice_set_object_tx_weight(struct ice_port_info *pi, struct ice_sched_node *node, u32 weight, struct netlink_ext_ack *extack) { int status; if (weight > 200 || weight < 1) { NL_SET_ERR_MSG_MOD(extack, "Weight must be between 1 and 200"); return -EINVAL; } mutex_lock(&pi->sched_lock); node->tx_weight = weight; status = ice_sched_set_node_weight(pi, node, node->tx_weight); mutex_unlock(&pi->sched_lock); if (status) NL_SET_ERR_MSG_MOD(extack, "Can't set scheduling node tx_weight"); return status; } /** * ice_get_pi_from_dev_rate - get port info from devlink_rate * @rate_node: devlink struct instance * * This function returns corresponding port_info struct of devlink_rate */ static struct ice_port_info *ice_get_pi_from_dev_rate(struct devlink_rate *rate_node) { struct ice_pf *pf = devlink_priv(rate_node->devlink); return ice_get_main_vsi(pf)->port_info; } static int ice_devlink_rate_node_new(struct devlink_rate *rate_node, void **priv, struct netlink_ext_ack *extack) { struct ice_sched_node *node; struct ice_port_info *pi; pi = ice_get_pi_from_dev_rate(rate_node); if (!ice_enable_custom_tx(devlink_priv(rate_node->devlink))) return -EBUSY; /* preallocate memory for ice_sched_node */ node = devm_kzalloc(ice_hw_to_dev(pi->hw), sizeof(*node), GFP_KERNEL); *priv = node; return 0; } static int ice_devlink_rate_node_del(struct devlink_rate *rate_node, void *priv, struct netlink_ext_ack *extack) { struct ice_sched_node *node, *tc_node; struct ice_port_info *pi; pi = ice_get_pi_from_dev_rate(rate_node); tc_node = pi->root->children[0]; node = priv; if (!rate_node->parent || !node || tc_node == node || !extack) return 0; if (!ice_enable_custom_tx(devlink_priv(rate_node->devlink))) return -EBUSY; /* can't allow to delete a node with children */ if (node->num_children) return -EINVAL; mutex_lock(&pi->sched_lock); ice_free_sched_node(pi, node); mutex_unlock(&pi->sched_lock); return 0; } static int ice_devlink_rate_leaf_tx_max_set(struct devlink_rate *rate_leaf, void *priv, u64 tx_max, struct netlink_ext_ack *extack) { struct ice_sched_node *node = priv; if (!ice_enable_custom_tx(devlink_priv(rate_leaf->devlink))) return -EBUSY; if (!node) return 0; return ice_set_object_tx_max(ice_get_pi_from_dev_rate(rate_leaf), node, tx_max, extack); } static int ice_devlink_rate_leaf_tx_share_set(struct devlink_rate *rate_leaf, void *priv, u64 tx_share, struct netlink_ext_ack *extack) { struct ice_sched_node *node = priv; if (!ice_enable_custom_tx(devlink_priv(rate_leaf->devlink))) return -EBUSY; if (!node) return 0; return ice_set_object_tx_share(ice_get_pi_from_dev_rate(rate_leaf), node, tx_share, extack); } static int ice_devlink_rate_leaf_tx_priority_set(struct devlink_rate *rate_leaf, void *priv, u32 tx_priority, struct netlink_ext_ack *extack) { struct ice_sched_node *node = priv; if (!ice_enable_custom_tx(devlink_priv(rate_leaf->devlink))) return -EBUSY; if (!node) return 0; return ice_set_object_tx_priority(ice_get_pi_from_dev_rate(rate_leaf), node, tx_priority, extack); } static int ice_devlink_rate_leaf_tx_weight_set(struct devlink_rate *rate_leaf, void *priv, u32 tx_weight, struct netlink_ext_ack *extack) { struct ice_sched_node *node = priv; if (!ice_enable_custom_tx(devlink_priv(rate_leaf->devlink))) return -EBUSY; if (!node) return 0; return ice_set_object_tx_weight(ice_get_pi_from_dev_rate(rate_leaf), node, tx_weight, extack); } static int ice_devlink_rate_node_tx_max_set(struct devlink_rate *rate_node, void *priv, u64 tx_max, struct netlink_ext_ack *extack) { struct ice_sched_node *node = priv; if (!ice_enable_custom_tx(devlink_priv(rate_node->devlink))) return -EBUSY; if (!node) return 0; return ice_set_object_tx_max(ice_get_pi_from_dev_rate(rate_node), node, tx_max, extack); } static int ice_devlink_rate_node_tx_share_set(struct devlink_rate *rate_node, void *priv, u64 tx_share, struct netlink_ext_ack *extack) { struct ice_sched_node *node = priv; if (!ice_enable_custom_tx(devlink_priv(rate_node->devlink))) return -EBUSY; if (!node) return 0; return ice_set_object_tx_share(ice_get_pi_from_dev_rate(rate_node), node, tx_share, extack); } static int ice_devlink_rate_node_tx_priority_set(struct devlink_rate *rate_node, void *priv, u32 tx_priority, struct netlink_ext_ack *extack) { struct ice_sched_node *node = priv; if (!ice_enable_custom_tx(devlink_priv(rate_node->devlink))) return -EBUSY; if (!node) return 0; return ice_set_object_tx_priority(ice_get_pi_from_dev_rate(rate_node), node, tx_priority, extack); } static int ice_devlink_rate_node_tx_weight_set(struct devlink_rate *rate_node, void *priv, u32 tx_weight, struct netlink_ext_ack *extack) { struct ice_sched_node *node = priv; if (!ice_enable_custom_tx(devlink_priv(rate_node->devlink))) return -EBUSY; if (!node) return 0; return ice_set_object_tx_weight(ice_get_pi_from_dev_rate(rate_node), node, tx_weight, extack); } static int ice_devlink_set_parent(struct devlink_rate *devlink_rate, struct devlink_rate *parent, void *priv, void *parent_priv, struct netlink_ext_ack *extack) { struct ice_port_info *pi = ice_get_pi_from_dev_rate(devlink_rate); struct ice_sched_node *tc_node, *node, *parent_node; u16 num_nodes_added; u32 first_node_teid; u32 node_teid; int status; tc_node = pi->root->children[0]; node = priv; if (!extack) return 0; if (!ice_enable_custom_tx(devlink_priv(devlink_rate->devlink))) return -EBUSY; if (!parent) { if (!node || tc_node == node || node->num_children) return -EINVAL; mutex_lock(&pi->sched_lock); ice_free_sched_node(pi, node); mutex_unlock(&pi->sched_lock); return 0; } parent_node = parent_priv; /* if the node doesn't exist, create it */ if (!node->parent) { mutex_lock(&pi->sched_lock); status = ice_sched_add_elems(pi, tc_node, parent_node, parent_node->tx_sched_layer + 1, 1, &num_nodes_added, &first_node_teid, &node); mutex_unlock(&pi->sched_lock); if (status) { NL_SET_ERR_MSG_MOD(extack, "Can't add a new node"); return status; } if (devlink_rate->tx_share) ice_set_object_tx_share(pi, node, devlink_rate->tx_share, extack); if (devlink_rate->tx_max) ice_set_object_tx_max(pi, node, devlink_rate->tx_max, extack); if (devlink_rate->tx_priority) ice_set_object_tx_priority(pi, node, devlink_rate->tx_priority, extack); if (devlink_rate->tx_weight) ice_set_object_tx_weight(pi, node, devlink_rate->tx_weight, extack); } else { node_teid = le32_to_cpu(node->info.node_teid); mutex_lock(&pi->sched_lock); status = ice_sched_move_nodes(pi, parent_node, 1, &node_teid); mutex_unlock(&pi->sched_lock); if (status) NL_SET_ERR_MSG_MOD(extack, "Can't move existing node to a new parent"); } return status; } /** * ice_devlink_reload_up - do reload up after reinit * @devlink: pointer to the devlink instance reloading * @action: the action requested * @limit: limits imposed by userspace, such as not resetting * @actions_performed: on return, indicate what actions actually performed * @extack: netlink extended ACK structure */ static int ice_devlink_reload_up(struct devlink *devlink, enum devlink_reload_action action, enum devlink_reload_limit limit, u32 *actions_performed, struct netlink_ext_ack *extack) { struct ice_pf *pf = devlink_priv(devlink); switch (action) { case DEVLINK_RELOAD_ACTION_DRIVER_REINIT: *actions_performed = BIT(DEVLINK_RELOAD_ACTION_DRIVER_REINIT); return ice_load(pf); case DEVLINK_RELOAD_ACTION_FW_ACTIVATE: *actions_performed = BIT(DEVLINK_RELOAD_ACTION_FW_ACTIVATE); return ice_devlink_reload_empr_finish(pf, extack); default: WARN_ON(1); return -EOPNOTSUPP; } } static const struct devlink_ops ice_devlink_ops = { .supported_flash_update_params = DEVLINK_SUPPORT_FLASH_UPDATE_OVERWRITE_MASK, .reload_actions = BIT(DEVLINK_RELOAD_ACTION_DRIVER_REINIT) | BIT(DEVLINK_RELOAD_ACTION_FW_ACTIVATE), .reload_down = ice_devlink_reload_down, .reload_up = ice_devlink_reload_up, .eswitch_mode_get = ice_eswitch_mode_get, .eswitch_mode_set = ice_eswitch_mode_set, .info_get = ice_devlink_info_get, .flash_update = ice_devlink_flash_update, .rate_node_new = ice_devlink_rate_node_new, .rate_node_del = ice_devlink_rate_node_del, .rate_leaf_tx_max_set = ice_devlink_rate_leaf_tx_max_set, .rate_leaf_tx_share_set = ice_devlink_rate_leaf_tx_share_set, .rate_leaf_tx_priority_set = ice_devlink_rate_leaf_tx_priority_set, .rate_leaf_tx_weight_set = ice_devlink_rate_leaf_tx_weight_set, .rate_node_tx_max_set = ice_devlink_rate_node_tx_max_set, .rate_node_tx_share_set = ice_devlink_rate_node_tx_share_set, .rate_node_tx_priority_set = ice_devlink_rate_node_tx_priority_set, .rate_node_tx_weight_set = ice_devlink_rate_node_tx_weight_set, .rate_leaf_parent_set = ice_devlink_set_parent, .rate_node_parent_set = ice_devlink_set_parent, }; static int ice_devlink_enable_roce_get(struct devlink *devlink, u32 id, struct devlink_param_gset_ctx *ctx) { struct ice_pf *pf = devlink_priv(devlink); ctx->val.vbool = pf->rdma_mode & IIDC_RDMA_PROTOCOL_ROCEV2 ? true : false; return 0; } static int ice_devlink_enable_roce_set(struct devlink *devlink, u32 id, struct devlink_param_gset_ctx *ctx) { struct ice_pf *pf = devlink_priv(devlink); bool roce_ena = ctx->val.vbool; int ret; if (!roce_ena) { ice_unplug_aux_dev(pf); pf->rdma_mode &= ~IIDC_RDMA_PROTOCOL_ROCEV2; return 0; } pf->rdma_mode |= IIDC_RDMA_PROTOCOL_ROCEV2; ret = ice_plug_aux_dev(pf); if (ret) pf->rdma_mode &= ~IIDC_RDMA_PROTOCOL_ROCEV2; return ret; } static int ice_devlink_enable_roce_validate(struct devlink *devlink, u32 id, union devlink_param_value val, struct netlink_ext_ack *extack) { struct ice_pf *pf = devlink_priv(devlink); if (!test_bit(ICE_FLAG_RDMA_ENA, pf->flags)) return -EOPNOTSUPP; if (pf->rdma_mode & IIDC_RDMA_PROTOCOL_IWARP) { NL_SET_ERR_MSG_MOD(extack, "iWARP is currently enabled. This device cannot enable iWARP and RoCEv2 simultaneously"); return -EOPNOTSUPP; } return 0; } static int ice_devlink_enable_iw_get(struct devlink *devlink, u32 id, struct devlink_param_gset_ctx *ctx) { struct ice_pf *pf = devlink_priv(devlink); ctx->val.vbool = pf->rdma_mode & IIDC_RDMA_PROTOCOL_IWARP; return 0; } static int ice_devlink_enable_iw_set(struct devlink *devlink, u32 id, struct devlink_param_gset_ctx *ctx) { struct ice_pf *pf = devlink_priv(devlink); bool iw_ena = ctx->val.vbool; int ret; if (!iw_ena) { ice_unplug_aux_dev(pf); pf->rdma_mode &= ~IIDC_RDMA_PROTOCOL_IWARP; return 0; } pf->rdma_mode |= IIDC_RDMA_PROTOCOL_IWARP; ret = ice_plug_aux_dev(pf); if (ret) pf->rdma_mode &= ~IIDC_RDMA_PROTOCOL_IWARP; return ret; } static int ice_devlink_enable_iw_validate(struct devlink *devlink, u32 id, union devlink_param_value val, struct netlink_ext_ack *extack) { struct ice_pf *pf = devlink_priv(devlink); if (!test_bit(ICE_FLAG_RDMA_ENA, pf->flags)) return -EOPNOTSUPP; if (pf->rdma_mode & IIDC_RDMA_PROTOCOL_ROCEV2) { NL_SET_ERR_MSG_MOD(extack, "RoCEv2 is currently enabled. This device cannot enable iWARP and RoCEv2 simultaneously"); return -EOPNOTSUPP; } return 0; } static const struct devlink_param ice_devlink_params[] = { DEVLINK_PARAM_GENERIC(ENABLE_ROCE, BIT(DEVLINK_PARAM_CMODE_RUNTIME), ice_devlink_enable_roce_get, ice_devlink_enable_roce_set, ice_devlink_enable_roce_validate), DEVLINK_PARAM_GENERIC(ENABLE_IWARP, BIT(DEVLINK_PARAM_CMODE_RUNTIME), ice_devlink_enable_iw_get, ice_devlink_enable_iw_set, ice_devlink_enable_iw_validate), }; static void ice_devlink_free(void *devlink_ptr) { devlink_free((struct devlink *)devlink_ptr); } /** * ice_allocate_pf - Allocate devlink and return PF structure pointer * @dev: the device to allocate for * * Allocate a devlink instance for this device and return the private area as * the PF structure. The devlink memory is kept track of through devres by * adding an action to remove it when unwinding. */ struct ice_pf *ice_allocate_pf(struct device *dev) { struct devlink *devlink; devlink = devlink_alloc(&ice_devlink_ops, sizeof(struct ice_pf), dev); if (!devlink) return NULL; /* Add an action to teardown the devlink when unwinding the driver */ if (devm_add_action_or_reset(dev, ice_devlink_free, devlink)) return NULL; return devlink_priv(devlink); } /** * ice_devlink_register - Register devlink interface for this PF * @pf: the PF to register the devlink for. * * Register the devlink instance associated with this physical function. * * Return: zero on success or an error code on failure. */ void ice_devlink_register(struct ice_pf *pf) { struct devlink *devlink = priv_to_devlink(pf); devlink_register(devlink); } /** * ice_devlink_unregister - Unregister devlink resources for this PF. * @pf: the PF structure to cleanup * * Releases resources used by devlink and cleans up associated memory. */ void ice_devlink_unregister(struct ice_pf *pf) { devlink_unregister(priv_to_devlink(pf)); } /** * ice_devlink_set_switch_id - Set unique switch id based on pci dsn * @pf: the PF to create a devlink port for * @ppid: struct with switch id information */ static void ice_devlink_set_switch_id(struct ice_pf *pf, struct netdev_phys_item_id *ppid) { struct pci_dev *pdev = pf->pdev; u64 id; id = pci_get_dsn(pdev); ppid->id_len = sizeof(id); put_unaligned_be64(id, &ppid->id); } int ice_devlink_register_params(struct ice_pf *pf) { struct devlink *devlink = priv_to_devlink(pf); return devlink_params_register(devlink, ice_devlink_params, ARRAY_SIZE(ice_devlink_params)); } void ice_devlink_unregister_params(struct ice_pf *pf) { devlink_params_unregister(priv_to_devlink(pf), ice_devlink_params, ARRAY_SIZE(ice_devlink_params)); } /** * ice_devlink_set_port_split_options - Set port split options * @pf: the PF to set port split options * @attrs: devlink attributes * * Sets devlink port split options based on available FW port options */ static void ice_devlink_set_port_split_options(struct ice_pf *pf, struct devlink_port_attrs *attrs) { struct ice_aqc_get_port_options_elem options[ICE_AQC_PORT_OPT_MAX]; u8 i, active_idx, pending_idx, option_count = ICE_AQC_PORT_OPT_MAX; bool active_valid, pending_valid; int status; status = ice_aq_get_port_options(&pf->hw, options, &option_count, 0, true, &active_idx, &active_valid, &pending_idx, &pending_valid); if (status) { dev_dbg(ice_pf_to_dev(pf), "Couldn't read port split options, err = %d\n", status); return; } /* find the biggest available port split count */ for (i = 0; i < option_count; i++) attrs->lanes = max_t(int, attrs->lanes, options[i].pmd); attrs->splittable = attrs->lanes ? 1 : 0; ice_active_port_option = active_idx; } static const struct devlink_port_ops ice_devlink_port_ops = { .port_split = ice_devlink_port_split, .port_unsplit = ice_devlink_port_unsplit, }; /** * ice_devlink_create_pf_port - Create a devlink port for this PF * @pf: the PF to create a devlink port for * * Create and register a devlink_port for this PF. * * Return: zero on success or an error code on failure. */ int ice_devlink_create_pf_port(struct ice_pf *pf) { struct devlink_port_attrs attrs = {}; struct devlink_port *devlink_port; struct devlink *devlink; struct ice_vsi *vsi; struct device *dev; int err; dev = ice_pf_to_dev(pf); devlink_port = &pf->devlink_port; vsi = ice_get_main_vsi(pf); if (!vsi) return -EIO; attrs.flavour = DEVLINK_PORT_FLAVOUR_PHYSICAL; attrs.phys.port_number = pf->hw.bus.func; /* As FW supports only port split options for whole device, * set port split options only for first PF. */ if (pf->hw.pf_id == 0) ice_devlink_set_port_split_options(pf, &attrs); ice_devlink_set_switch_id(pf, &attrs.switch_id); devlink_port_attrs_set(devlink_port, &attrs); devlink = priv_to_devlink(pf); err = devlink_port_register_with_ops(devlink, devlink_port, vsi->idx, &ice_devlink_port_ops); if (err) { dev_err(dev, "Failed to create devlink port for PF %d, error %d\n", pf->hw.pf_id, err); return err; } return 0; } /** * ice_devlink_destroy_pf_port - Destroy the devlink_port for this PF * @pf: the PF to cleanup * * Unregisters the devlink_port structure associated with this PF. */ void ice_devlink_destroy_pf_port(struct ice_pf *pf) { devlink_port_unregister(&pf->devlink_port); } /** * ice_devlink_create_vf_port - Create a devlink port for this VF * @vf: the VF to create a port for * * Create and register a devlink_port for this VF. * * Return: zero on success or an error code on failure. */ int ice_devlink_create_vf_port(struct ice_vf *vf) { struct devlink_port_attrs attrs = {}; struct devlink_port *devlink_port; struct devlink *devlink; struct ice_vsi *vsi; struct device *dev; struct ice_pf *pf; int err; pf = vf->pf; dev = ice_pf_to_dev(pf); devlink_port = &vf->devlink_port; vsi = ice_get_vf_vsi(vf); if (!vsi) return -EINVAL; attrs.flavour = DEVLINK_PORT_FLAVOUR_PCI_VF; attrs.pci_vf.pf = pf->hw.bus.func; attrs.pci_vf.vf = vf->vf_id; ice_devlink_set_switch_id(pf, &attrs.switch_id); devlink_port_attrs_set(devlink_port, &attrs); devlink = priv_to_devlink(pf); err = devlink_port_register(devlink, devlink_port, vsi->idx); if (err) { dev_err(dev, "Failed to create devlink port for VF %d, error %d\n", vf->vf_id, err); return err; } return 0; } /** * ice_devlink_destroy_vf_port - Destroy the devlink_port for this VF * @vf: the VF to cleanup * * Unregisters the devlink_port structure associated with this VF. */ void ice_devlink_destroy_vf_port(struct ice_vf *vf) { devl_rate_leaf_destroy(&vf->devlink_port); devlink_port_unregister(&vf->devlink_port); } #define ICE_DEVLINK_READ_BLK_SIZE (1024 * 1024) static const struct devlink_region_ops ice_nvm_region_ops; static const struct devlink_region_ops ice_sram_region_ops; /** * ice_devlink_nvm_snapshot - Capture a snapshot of the NVM flash contents * @devlink: the devlink instance * @ops: the devlink region to snapshot * @extack: extended ACK response structure * @data: on exit points to snapshot data buffer * * This function is called in response to a DEVLINK_CMD_REGION_NEW for either * the nvm-flash or shadow-ram region. * * It captures a snapshot of the NVM or Shadow RAM flash contents. This * snapshot can then later be viewed via the DEVLINK_CMD_REGION_READ netlink * interface. * * @returns zero on success, and updates the data pointer. Returns a non-zero * error code on failure. */ static int ice_devlink_nvm_snapshot(struct devlink *devlink, const struct devlink_region_ops *ops, struct netlink_ext_ack *extack, u8 **data) { struct ice_pf *pf = devlink_priv(devlink); struct device *dev = ice_pf_to_dev(pf); struct ice_hw *hw = &pf->hw; bool read_shadow_ram; u8 *nvm_data, *tmp, i; u32 nvm_size, left; s8 num_blks; int status; if (ops == &ice_nvm_region_ops) { read_shadow_ram = false; nvm_size = hw->flash.flash_size; } else if (ops == &ice_sram_region_ops) { read_shadow_ram = true; nvm_size = hw->flash.sr_words * 2u; } else { NL_SET_ERR_MSG_MOD(extack, "Unexpected region in snapshot function"); return -EOPNOTSUPP; } nvm_data = vzalloc(nvm_size); if (!nvm_data) return -ENOMEM; num_blks = DIV_ROUND_UP(nvm_size, ICE_DEVLINK_READ_BLK_SIZE); tmp = nvm_data; left = nvm_size; /* Some systems take longer to read the NVM than others which causes the * FW to reclaim the NVM lock before the entire NVM has been read. Fix * this by breaking the reads of the NVM into smaller chunks that will * probably not take as long. This has some overhead since we are * increasing the number of AQ commands, but it should always work */ for (i = 0; i < num_blks; i++) { u32 read_sz = min_t(u32, ICE_DEVLINK_READ_BLK_SIZE, left); status = ice_acquire_nvm(hw, ICE_RES_READ); if (status) { dev_dbg(dev, "ice_acquire_nvm failed, err %d aq_err %d\n", status, hw->adminq.sq_last_status); NL_SET_ERR_MSG_MOD(extack, "Failed to acquire NVM semaphore"); vfree(nvm_data); return -EIO; } status = ice_read_flat_nvm(hw, i * ICE_DEVLINK_READ_BLK_SIZE, &read_sz, tmp, read_shadow_ram); if (status) { dev_dbg(dev, "ice_read_flat_nvm failed after reading %u bytes, err %d aq_err %d\n", read_sz, status, hw->adminq.sq_last_status); NL_SET_ERR_MSG_MOD(extack, "Failed to read NVM contents"); ice_release_nvm(hw); vfree(nvm_data); return -EIO; } ice_release_nvm(hw); tmp += read_sz; left -= read_sz; } *data = nvm_data; return 0; } /** * ice_devlink_nvm_read - Read a portion of NVM flash contents * @devlink: the devlink instance * @ops: the devlink region to snapshot * @extack: extended ACK response structure * @offset: the offset to start at * @size: the amount to read * @data: the data buffer to read into * * This function is called in response to DEVLINK_CMD_REGION_READ to directly * read a section of the NVM contents. * * It reads from either the nvm-flash or shadow-ram region contents. * * @returns zero on success, and updates the data pointer. Returns a non-zero * error code on failure. */ static int ice_devlink_nvm_read(struct devlink *devlink, const struct devlink_region_ops *ops, struct netlink_ext_ack *extack, u64 offset, u32 size, u8 *data) { struct ice_pf *pf = devlink_priv(devlink); struct device *dev = ice_pf_to_dev(pf); struct ice_hw *hw = &pf->hw; bool read_shadow_ram; u64 nvm_size; int status; if (ops == &ice_nvm_region_ops) { read_shadow_ram = false; nvm_size = hw->flash.flash_size; } else if (ops == &ice_sram_region_ops) { read_shadow_ram = true; nvm_size = hw->flash.sr_words * 2u; } else { NL_SET_ERR_MSG_MOD(extack, "Unexpected region in snapshot function"); return -EOPNOTSUPP; } if (offset + size >= nvm_size) { NL_SET_ERR_MSG_MOD(extack, "Cannot read beyond the region size"); return -ERANGE; } status = ice_acquire_nvm(hw, ICE_RES_READ); if (status) { dev_dbg(dev, "ice_acquire_nvm failed, err %d aq_err %d\n", status, hw->adminq.sq_last_status); NL_SET_ERR_MSG_MOD(extack, "Failed to acquire NVM semaphore"); return -EIO; } status = ice_read_flat_nvm(hw, (u32)offset, &size, data, read_shadow_ram); if (status) { dev_dbg(dev, "ice_read_flat_nvm failed after reading %u bytes, err %d aq_err %d\n", size, status, hw->adminq.sq_last_status); NL_SET_ERR_MSG_MOD(extack, "Failed to read NVM contents"); ice_release_nvm(hw); return -EIO; } ice_release_nvm(hw); return 0; } /** * ice_devlink_devcaps_snapshot - Capture snapshot of device capabilities * @devlink: the devlink instance * @ops: the devlink region being snapshotted * @extack: extended ACK response structure * @data: on exit points to snapshot data buffer * * This function is called in response to the DEVLINK_CMD_REGION_TRIGGER for * the device-caps devlink region. It captures a snapshot of the device * capabilities reported by firmware. * * @returns zero on success, and updates the data pointer. Returns a non-zero * error code on failure. */ static int ice_devlink_devcaps_snapshot(struct devlink *devlink, const struct devlink_region_ops *ops, struct netlink_ext_ack *extack, u8 **data) { struct ice_pf *pf = devlink_priv(devlink); struct device *dev = ice_pf_to_dev(pf); struct ice_hw *hw = &pf->hw; void *devcaps; int status; devcaps = vzalloc(ICE_AQ_MAX_BUF_LEN); if (!devcaps) return -ENOMEM; status = ice_aq_list_caps(hw, devcaps, ICE_AQ_MAX_BUF_LEN, NULL, ice_aqc_opc_list_dev_caps, NULL); if (status) { dev_dbg(dev, "ice_aq_list_caps: failed to read device capabilities, err %d aq_err %d\n", status, hw->adminq.sq_last_status); NL_SET_ERR_MSG_MOD(extack, "Failed to read device capabilities"); vfree(devcaps); return status; } *data = (u8 *)devcaps; return 0; } static const struct devlink_region_ops ice_nvm_region_ops = { .name = "nvm-flash", .destructor = vfree, .snapshot = ice_devlink_nvm_snapshot, .read = ice_devlink_nvm_read, }; static const struct devlink_region_ops ice_sram_region_ops = { .name = "shadow-ram", .destructor = vfree, .snapshot = ice_devlink_nvm_snapshot, .read = ice_devlink_nvm_read, }; static const struct devlink_region_ops ice_devcaps_region_ops = { .name = "device-caps", .destructor = vfree, .snapshot = ice_devlink_devcaps_snapshot, }; /** * ice_devlink_init_regions - Initialize devlink regions * @pf: the PF device structure * * Create devlink regions used to enable access to dump the contents of the * flash memory on the device. */ void ice_devlink_init_regions(struct ice_pf *pf) { struct devlink *devlink = priv_to_devlink(pf); struct device *dev = ice_pf_to_dev(pf); u64 nvm_size, sram_size; nvm_size = pf->hw.flash.flash_size; pf->nvm_region = devlink_region_create(devlink, &ice_nvm_region_ops, 1, nvm_size); if (IS_ERR(pf->nvm_region)) { dev_err(dev, "failed to create NVM devlink region, err %ld\n", PTR_ERR(pf->nvm_region)); pf->nvm_region = NULL; } sram_size = pf->hw.flash.sr_words * 2u; pf->sram_region = devlink_region_create(devlink, &ice_sram_region_ops, 1, sram_size); if (IS_ERR(pf->sram_region)) { dev_err(dev, "failed to create shadow-ram devlink region, err %ld\n", PTR_ERR(pf->sram_region)); pf->sram_region = NULL; } pf->devcaps_region = devlink_region_create(devlink, &ice_devcaps_region_ops, 10, ICE_AQ_MAX_BUF_LEN); if (IS_ERR(pf->devcaps_region)) { dev_err(dev, "failed to create device-caps devlink region, err %ld\n", PTR_ERR(pf->devcaps_region)); pf->devcaps_region = NULL; } } /** * ice_devlink_destroy_regions - Destroy devlink regions * @pf: the PF device structure * * Remove previously created regions for this PF. */ void ice_devlink_destroy_regions(struct ice_pf *pf) { if (pf->nvm_region) devlink_region_destroy(pf->nvm_region); if (pf->sram_region) devlink_region_destroy(pf->sram_region); if (pf->devcaps_region) devlink_region_destroy(pf->devcaps_region); }
linux-master
drivers/net/ethernet/intel/ice/ice_devlink.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2018, Intel Corporation. */ #include <net/devlink.h> #include "ice_sched.h" /** * ice_sched_add_root_node - Insert the Tx scheduler root node in SW DB * @pi: port information structure * @info: Scheduler element information from firmware * * This function inserts the root node of the scheduling tree topology * to the SW DB. */ static int ice_sched_add_root_node(struct ice_port_info *pi, struct ice_aqc_txsched_elem_data *info) { struct ice_sched_node *root; struct ice_hw *hw; if (!pi) return -EINVAL; hw = pi->hw; root = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*root), GFP_KERNEL); if (!root) return -ENOMEM; /* coverity[suspicious_sizeof] */ root->children = devm_kcalloc(ice_hw_to_dev(hw), hw->max_children[0], sizeof(*root), GFP_KERNEL); if (!root->children) { devm_kfree(ice_hw_to_dev(hw), root); return -ENOMEM; } memcpy(&root->info, info, sizeof(*info)); pi->root = root; return 0; } /** * ice_sched_find_node_by_teid - Find the Tx scheduler node in SW DB * @start_node: pointer to the starting ice_sched_node struct in a sub-tree * @teid: node TEID to search * * This function searches for a node matching the TEID in the scheduling tree * from the SW DB. The search is recursive and is restricted by the number of * layers it has searched through; stopping at the max supported layer. * * This function needs to be called when holding the port_info->sched_lock */ struct ice_sched_node * ice_sched_find_node_by_teid(struct ice_sched_node *start_node, u32 teid) { u16 i; /* The TEID is same as that of the start_node */ if (ICE_TXSCHED_GET_NODE_TEID(start_node) == teid) return start_node; /* The node has no children or is at the max layer */ if (!start_node->num_children || start_node->tx_sched_layer >= ICE_AQC_TOPO_MAX_LEVEL_NUM || start_node->info.data.elem_type == ICE_AQC_ELEM_TYPE_LEAF) return NULL; /* Check if TEID matches to any of the children nodes */ for (i = 0; i < start_node->num_children; i++) if (ICE_TXSCHED_GET_NODE_TEID(start_node->children[i]) == teid) return start_node->children[i]; /* Search within each child's sub-tree */ for (i = 0; i < start_node->num_children; i++) { struct ice_sched_node *tmp; tmp = ice_sched_find_node_by_teid(start_node->children[i], teid); if (tmp) return tmp; } return NULL; } /** * ice_aqc_send_sched_elem_cmd - send scheduling elements cmd * @hw: pointer to the HW struct * @cmd_opc: cmd opcode * @elems_req: number of elements to request * @buf: pointer to buffer * @buf_size: buffer size in bytes * @elems_resp: returns total number of elements response * @cd: pointer to command details structure or NULL * * This function sends a scheduling elements cmd (cmd_opc) */ static int ice_aqc_send_sched_elem_cmd(struct ice_hw *hw, enum ice_adminq_opc cmd_opc, u16 elems_req, void *buf, u16 buf_size, u16 *elems_resp, struct ice_sq_cd *cd) { struct ice_aqc_sched_elem_cmd *cmd; struct ice_aq_desc desc; int status; cmd = &desc.params.sched_elem_cmd; ice_fill_dflt_direct_cmd_desc(&desc, cmd_opc); cmd->num_elem_req = cpu_to_le16(elems_req); desc.flags |= cpu_to_le16(ICE_AQ_FLAG_RD); status = ice_aq_send_cmd(hw, &desc, buf, buf_size, cd); if (!status && elems_resp) *elems_resp = le16_to_cpu(cmd->num_elem_resp); return status; } /** * ice_aq_query_sched_elems - query scheduler elements * @hw: pointer to the HW struct * @elems_req: number of elements to query * @buf: pointer to buffer * @buf_size: buffer size in bytes * @elems_ret: returns total number of elements returned * @cd: pointer to command details structure or NULL * * Query scheduling elements (0x0404) */ int ice_aq_query_sched_elems(struct ice_hw *hw, u16 elems_req, struct ice_aqc_txsched_elem_data *buf, u16 buf_size, u16 *elems_ret, struct ice_sq_cd *cd) { return ice_aqc_send_sched_elem_cmd(hw, ice_aqc_opc_get_sched_elems, elems_req, (void *)buf, buf_size, elems_ret, cd); } /** * ice_sched_add_node - Insert the Tx scheduler node in SW DB * @pi: port information structure * @layer: Scheduler layer of the node * @info: Scheduler element information from firmware * @prealloc_node: preallocated ice_sched_node struct for SW DB * * This function inserts a scheduler node to the SW DB. */ int ice_sched_add_node(struct ice_port_info *pi, u8 layer, struct ice_aqc_txsched_elem_data *info, struct ice_sched_node *prealloc_node) { struct ice_aqc_txsched_elem_data elem; struct ice_sched_node *parent; struct ice_sched_node *node; struct ice_hw *hw; int status; if (!pi) return -EINVAL; hw = pi->hw; /* A valid parent node should be there */ parent = ice_sched_find_node_by_teid(pi->root, le32_to_cpu(info->parent_teid)); if (!parent) { ice_debug(hw, ICE_DBG_SCHED, "Parent Node not found for parent_teid=0x%x\n", le32_to_cpu(info->parent_teid)); return -EINVAL; } /* query the current node information from FW before adding it * to the SW DB */ status = ice_sched_query_elem(hw, le32_to_cpu(info->node_teid), &elem); if (status) return status; if (prealloc_node) node = prealloc_node; else node = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*node), GFP_KERNEL); if (!node) return -ENOMEM; if (hw->max_children[layer]) { /* coverity[suspicious_sizeof] */ node->children = devm_kcalloc(ice_hw_to_dev(hw), hw->max_children[layer], sizeof(*node), GFP_KERNEL); if (!node->children) { devm_kfree(ice_hw_to_dev(hw), node); return -ENOMEM; } } node->in_use = true; node->parent = parent; node->tx_sched_layer = layer; parent->children[parent->num_children++] = node; node->info = elem; return 0; } /** * ice_aq_delete_sched_elems - delete scheduler elements * @hw: pointer to the HW struct * @grps_req: number of groups to delete * @buf: pointer to buffer * @buf_size: buffer size in bytes * @grps_del: returns total number of elements deleted * @cd: pointer to command details structure or NULL * * Delete scheduling elements (0x040F) */ static int ice_aq_delete_sched_elems(struct ice_hw *hw, u16 grps_req, struct ice_aqc_delete_elem *buf, u16 buf_size, u16 *grps_del, struct ice_sq_cd *cd) { return ice_aqc_send_sched_elem_cmd(hw, ice_aqc_opc_delete_sched_elems, grps_req, (void *)buf, buf_size, grps_del, cd); } /** * ice_sched_remove_elems - remove nodes from HW * @hw: pointer to the HW struct * @parent: pointer to the parent node * @num_nodes: number of nodes * @node_teids: array of node teids to be deleted * * This function remove nodes from HW */ static int ice_sched_remove_elems(struct ice_hw *hw, struct ice_sched_node *parent, u16 num_nodes, u32 *node_teids) { struct ice_aqc_delete_elem *buf; u16 i, num_groups_removed = 0; u16 buf_size; int status; buf_size = struct_size(buf, teid, num_nodes); buf = devm_kzalloc(ice_hw_to_dev(hw), buf_size, GFP_KERNEL); if (!buf) return -ENOMEM; buf->hdr.parent_teid = parent->info.node_teid; buf->hdr.num_elems = cpu_to_le16(num_nodes); for (i = 0; i < num_nodes; i++) buf->teid[i] = cpu_to_le32(node_teids[i]); status = ice_aq_delete_sched_elems(hw, 1, buf, buf_size, &num_groups_removed, NULL); if (status || num_groups_removed != 1) ice_debug(hw, ICE_DBG_SCHED, "remove node failed FW error %d\n", hw->adminq.sq_last_status); devm_kfree(ice_hw_to_dev(hw), buf); return status; } /** * ice_sched_get_first_node - get the first node of the given layer * @pi: port information structure * @parent: pointer the base node of the subtree * @layer: layer number * * This function retrieves the first node of the given layer from the subtree */ static struct ice_sched_node * ice_sched_get_first_node(struct ice_port_info *pi, struct ice_sched_node *parent, u8 layer) { return pi->sib_head[parent->tc_num][layer]; } /** * ice_sched_get_tc_node - get pointer to TC node * @pi: port information structure * @tc: TC number * * This function returns the TC node pointer */ struct ice_sched_node *ice_sched_get_tc_node(struct ice_port_info *pi, u8 tc) { u8 i; if (!pi || !pi->root) return NULL; for (i = 0; i < pi->root->num_children; i++) if (pi->root->children[i]->tc_num == tc) return pi->root->children[i]; return NULL; } /** * ice_free_sched_node - Free a Tx scheduler node from SW DB * @pi: port information structure * @node: pointer to the ice_sched_node struct * * This function frees up a node from SW DB as well as from HW * * This function needs to be called with the port_info->sched_lock held */ void ice_free_sched_node(struct ice_port_info *pi, struct ice_sched_node *node) { struct ice_sched_node *parent; struct ice_hw *hw = pi->hw; u8 i, j; /* Free the children before freeing up the parent node * The parent array is updated below and that shifts the nodes * in the array. So always pick the first child if num children > 0 */ while (node->num_children) ice_free_sched_node(pi, node->children[0]); /* Leaf, TC and root nodes can't be deleted by SW */ if (node->tx_sched_layer >= hw->sw_entry_point_layer && node->info.data.elem_type != ICE_AQC_ELEM_TYPE_TC && node->info.data.elem_type != ICE_AQC_ELEM_TYPE_ROOT_PORT && node->info.data.elem_type != ICE_AQC_ELEM_TYPE_LEAF) { u32 teid = le32_to_cpu(node->info.node_teid); ice_sched_remove_elems(hw, node->parent, 1, &teid); } parent = node->parent; /* root has no parent */ if (parent) { struct ice_sched_node *p; /* update the parent */ for (i = 0; i < parent->num_children; i++) if (parent->children[i] == node) { for (j = i + 1; j < parent->num_children; j++) parent->children[j - 1] = parent->children[j]; parent->num_children--; break; } p = ice_sched_get_first_node(pi, node, node->tx_sched_layer); while (p) { if (p->sibling == node) { p->sibling = node->sibling; break; } p = p->sibling; } /* update the sibling head if head is getting removed */ if (pi->sib_head[node->tc_num][node->tx_sched_layer] == node) pi->sib_head[node->tc_num][node->tx_sched_layer] = node->sibling; } devm_kfree(ice_hw_to_dev(hw), node->children); kfree(node->name); xa_erase(&pi->sched_node_ids, node->id); devm_kfree(ice_hw_to_dev(hw), node); } /** * ice_aq_get_dflt_topo - gets default scheduler topology * @hw: pointer to the HW struct * @lport: logical port number * @buf: pointer to buffer * @buf_size: buffer size in bytes * @num_branches: returns total number of queue to port branches * @cd: pointer to command details structure or NULL * * Get default scheduler topology (0x400) */ static int ice_aq_get_dflt_topo(struct ice_hw *hw, u8 lport, struct ice_aqc_get_topo_elem *buf, u16 buf_size, u8 *num_branches, struct ice_sq_cd *cd) { struct ice_aqc_get_topo *cmd; struct ice_aq_desc desc; int status; cmd = &desc.params.get_topo; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_get_dflt_topo); cmd->port_num = lport; status = ice_aq_send_cmd(hw, &desc, buf, buf_size, cd); if (!status && num_branches) *num_branches = cmd->num_branches; return status; } /** * ice_aq_add_sched_elems - adds scheduling element * @hw: pointer to the HW struct * @grps_req: the number of groups that are requested to be added * @buf: pointer to buffer * @buf_size: buffer size in bytes * @grps_added: returns total number of groups added * @cd: pointer to command details structure or NULL * * Add scheduling elements (0x0401) */ static int ice_aq_add_sched_elems(struct ice_hw *hw, u16 grps_req, struct ice_aqc_add_elem *buf, u16 buf_size, u16 *grps_added, struct ice_sq_cd *cd) { return ice_aqc_send_sched_elem_cmd(hw, ice_aqc_opc_add_sched_elems, grps_req, (void *)buf, buf_size, grps_added, cd); } /** * ice_aq_cfg_sched_elems - configures scheduler elements * @hw: pointer to the HW struct * @elems_req: number of elements to configure * @buf: pointer to buffer * @buf_size: buffer size in bytes * @elems_cfgd: returns total number of elements configured * @cd: pointer to command details structure or NULL * * Configure scheduling elements (0x0403) */ static int ice_aq_cfg_sched_elems(struct ice_hw *hw, u16 elems_req, struct ice_aqc_txsched_elem_data *buf, u16 buf_size, u16 *elems_cfgd, struct ice_sq_cd *cd) { return ice_aqc_send_sched_elem_cmd(hw, ice_aqc_opc_cfg_sched_elems, elems_req, (void *)buf, buf_size, elems_cfgd, cd); } /** * ice_aq_move_sched_elems - move scheduler elements * @hw: pointer to the HW struct * @grps_req: number of groups to move * @buf: pointer to buffer * @buf_size: buffer size in bytes * @grps_movd: returns total number of groups moved * @cd: pointer to command details structure or NULL * * Move scheduling elements (0x0408) */ int ice_aq_move_sched_elems(struct ice_hw *hw, u16 grps_req, struct ice_aqc_move_elem *buf, u16 buf_size, u16 *grps_movd, struct ice_sq_cd *cd) { return ice_aqc_send_sched_elem_cmd(hw, ice_aqc_opc_move_sched_elems, grps_req, (void *)buf, buf_size, grps_movd, cd); } /** * ice_aq_suspend_sched_elems - suspend scheduler elements * @hw: pointer to the HW struct * @elems_req: number of elements to suspend * @buf: pointer to buffer * @buf_size: buffer size in bytes * @elems_ret: returns total number of elements suspended * @cd: pointer to command details structure or NULL * * Suspend scheduling elements (0x0409) */ static int ice_aq_suspend_sched_elems(struct ice_hw *hw, u16 elems_req, __le32 *buf, u16 buf_size, u16 *elems_ret, struct ice_sq_cd *cd) { return ice_aqc_send_sched_elem_cmd(hw, ice_aqc_opc_suspend_sched_elems, elems_req, (void *)buf, buf_size, elems_ret, cd); } /** * ice_aq_resume_sched_elems - resume scheduler elements * @hw: pointer to the HW struct * @elems_req: number of elements to resume * @buf: pointer to buffer * @buf_size: buffer size in bytes * @elems_ret: returns total number of elements resumed * @cd: pointer to command details structure or NULL * * resume scheduling elements (0x040A) */ static int ice_aq_resume_sched_elems(struct ice_hw *hw, u16 elems_req, __le32 *buf, u16 buf_size, u16 *elems_ret, struct ice_sq_cd *cd) { return ice_aqc_send_sched_elem_cmd(hw, ice_aqc_opc_resume_sched_elems, elems_req, (void *)buf, buf_size, elems_ret, cd); } /** * ice_aq_query_sched_res - query scheduler resource * @hw: pointer to the HW struct * @buf_size: buffer size in bytes * @buf: pointer to buffer * @cd: pointer to command details structure or NULL * * Query scheduler resource allocation (0x0412) */ static int ice_aq_query_sched_res(struct ice_hw *hw, u16 buf_size, struct ice_aqc_query_txsched_res_resp *buf, struct ice_sq_cd *cd) { struct ice_aq_desc desc; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_query_sched_res); return ice_aq_send_cmd(hw, &desc, buf, buf_size, cd); } /** * ice_sched_suspend_resume_elems - suspend or resume HW nodes * @hw: pointer to the HW struct * @num_nodes: number of nodes * @node_teids: array of node teids to be suspended or resumed * @suspend: true means suspend / false means resume * * This function suspends or resumes HW nodes */ int ice_sched_suspend_resume_elems(struct ice_hw *hw, u8 num_nodes, u32 *node_teids, bool suspend) { u16 i, buf_size, num_elem_ret = 0; __le32 *buf; int status; buf_size = sizeof(*buf) * num_nodes; buf = devm_kzalloc(ice_hw_to_dev(hw), buf_size, GFP_KERNEL); if (!buf) return -ENOMEM; for (i = 0; i < num_nodes; i++) buf[i] = cpu_to_le32(node_teids[i]); if (suspend) status = ice_aq_suspend_sched_elems(hw, num_nodes, buf, buf_size, &num_elem_ret, NULL); else status = ice_aq_resume_sched_elems(hw, num_nodes, buf, buf_size, &num_elem_ret, NULL); if (status || num_elem_ret != num_nodes) ice_debug(hw, ICE_DBG_SCHED, "suspend/resume failed\n"); devm_kfree(ice_hw_to_dev(hw), buf); return status; } /** * ice_alloc_lan_q_ctx - allocate LAN queue contexts for the given VSI and TC * @hw: pointer to the HW struct * @vsi_handle: VSI handle * @tc: TC number * @new_numqs: number of queues */ static int ice_alloc_lan_q_ctx(struct ice_hw *hw, u16 vsi_handle, u8 tc, u16 new_numqs) { struct ice_vsi_ctx *vsi_ctx; struct ice_q_ctx *q_ctx; u16 idx; vsi_ctx = ice_get_vsi_ctx(hw, vsi_handle); if (!vsi_ctx) return -EINVAL; /* allocate LAN queue contexts */ if (!vsi_ctx->lan_q_ctx[tc]) { q_ctx = devm_kcalloc(ice_hw_to_dev(hw), new_numqs, sizeof(*q_ctx), GFP_KERNEL); if (!q_ctx) return -ENOMEM; for (idx = 0; idx < new_numqs; idx++) { q_ctx[idx].q_handle = ICE_INVAL_Q_HANDLE; q_ctx[idx].q_teid = ICE_INVAL_TEID; } vsi_ctx->lan_q_ctx[tc] = q_ctx; vsi_ctx->num_lan_q_entries[tc] = new_numqs; return 0; } /* num queues are increased, update the queue contexts */ if (new_numqs > vsi_ctx->num_lan_q_entries[tc]) { u16 prev_num = vsi_ctx->num_lan_q_entries[tc]; q_ctx = devm_kcalloc(ice_hw_to_dev(hw), new_numqs, sizeof(*q_ctx), GFP_KERNEL); if (!q_ctx) return -ENOMEM; memcpy(q_ctx, vsi_ctx->lan_q_ctx[tc], prev_num * sizeof(*q_ctx)); devm_kfree(ice_hw_to_dev(hw), vsi_ctx->lan_q_ctx[tc]); for (idx = prev_num; idx < new_numqs; idx++) { q_ctx[idx].q_handle = ICE_INVAL_Q_HANDLE; q_ctx[idx].q_teid = ICE_INVAL_TEID; } vsi_ctx->lan_q_ctx[tc] = q_ctx; vsi_ctx->num_lan_q_entries[tc] = new_numqs; } return 0; } /** * ice_alloc_rdma_q_ctx - allocate RDMA queue contexts for the given VSI and TC * @hw: pointer to the HW struct * @vsi_handle: VSI handle * @tc: TC number * @new_numqs: number of queues */ static int ice_alloc_rdma_q_ctx(struct ice_hw *hw, u16 vsi_handle, u8 tc, u16 new_numqs) { struct ice_vsi_ctx *vsi_ctx; struct ice_q_ctx *q_ctx; vsi_ctx = ice_get_vsi_ctx(hw, vsi_handle); if (!vsi_ctx) return -EINVAL; /* allocate RDMA queue contexts */ if (!vsi_ctx->rdma_q_ctx[tc]) { vsi_ctx->rdma_q_ctx[tc] = devm_kcalloc(ice_hw_to_dev(hw), new_numqs, sizeof(*q_ctx), GFP_KERNEL); if (!vsi_ctx->rdma_q_ctx[tc]) return -ENOMEM; vsi_ctx->num_rdma_q_entries[tc] = new_numqs; return 0; } /* num queues are increased, update the queue contexts */ if (new_numqs > vsi_ctx->num_rdma_q_entries[tc]) { u16 prev_num = vsi_ctx->num_rdma_q_entries[tc]; q_ctx = devm_kcalloc(ice_hw_to_dev(hw), new_numqs, sizeof(*q_ctx), GFP_KERNEL); if (!q_ctx) return -ENOMEM; memcpy(q_ctx, vsi_ctx->rdma_q_ctx[tc], prev_num * sizeof(*q_ctx)); devm_kfree(ice_hw_to_dev(hw), vsi_ctx->rdma_q_ctx[tc]); vsi_ctx->rdma_q_ctx[tc] = q_ctx; vsi_ctx->num_rdma_q_entries[tc] = new_numqs; } return 0; } /** * ice_aq_rl_profile - performs a rate limiting task * @hw: pointer to the HW struct * @opcode: opcode for add, query, or remove profile(s) * @num_profiles: the number of profiles * @buf: pointer to buffer * @buf_size: buffer size in bytes * @num_processed: number of processed add or remove profile(s) to return * @cd: pointer to command details structure * * RL profile function to add, query, or remove profile(s) */ static int ice_aq_rl_profile(struct ice_hw *hw, enum ice_adminq_opc opcode, u16 num_profiles, struct ice_aqc_rl_profile_elem *buf, u16 buf_size, u16 *num_processed, struct ice_sq_cd *cd) { struct ice_aqc_rl_profile *cmd; struct ice_aq_desc desc; int status; cmd = &desc.params.rl_profile; ice_fill_dflt_direct_cmd_desc(&desc, opcode); desc.flags |= cpu_to_le16(ICE_AQ_FLAG_RD); cmd->num_profiles = cpu_to_le16(num_profiles); status = ice_aq_send_cmd(hw, &desc, buf, buf_size, cd); if (!status && num_processed) *num_processed = le16_to_cpu(cmd->num_processed); return status; } /** * ice_aq_add_rl_profile - adds rate limiting profile(s) * @hw: pointer to the HW struct * @num_profiles: the number of profile(s) to be add * @buf: pointer to buffer * @buf_size: buffer size in bytes * @num_profiles_added: total number of profiles added to return * @cd: pointer to command details structure * * Add RL profile (0x0410) */ static int ice_aq_add_rl_profile(struct ice_hw *hw, u16 num_profiles, struct ice_aqc_rl_profile_elem *buf, u16 buf_size, u16 *num_profiles_added, struct ice_sq_cd *cd) { return ice_aq_rl_profile(hw, ice_aqc_opc_add_rl_profiles, num_profiles, buf, buf_size, num_profiles_added, cd); } /** * ice_aq_remove_rl_profile - removes RL profile(s) * @hw: pointer to the HW struct * @num_profiles: the number of profile(s) to remove * @buf: pointer to buffer * @buf_size: buffer size in bytes * @num_profiles_removed: total number of profiles removed to return * @cd: pointer to command details structure or NULL * * Remove RL profile (0x0415) */ static int ice_aq_remove_rl_profile(struct ice_hw *hw, u16 num_profiles, struct ice_aqc_rl_profile_elem *buf, u16 buf_size, u16 *num_profiles_removed, struct ice_sq_cd *cd) { return ice_aq_rl_profile(hw, ice_aqc_opc_remove_rl_profiles, num_profiles, buf, buf_size, num_profiles_removed, cd); } /** * ice_sched_del_rl_profile - remove RL profile * @hw: pointer to the HW struct * @rl_info: rate limit profile information * * If the profile ID is not referenced anymore, it removes profile ID with * its associated parameters from HW DB,and locally. The caller needs to * hold scheduler lock. */ static int ice_sched_del_rl_profile(struct ice_hw *hw, struct ice_aqc_rl_profile_info *rl_info) { struct ice_aqc_rl_profile_elem *buf; u16 num_profiles_removed; u16 num_profiles = 1; int status; if (rl_info->prof_id_ref != 0) return -EBUSY; /* Safe to remove profile ID */ buf = &rl_info->profile; status = ice_aq_remove_rl_profile(hw, num_profiles, buf, sizeof(*buf), &num_profiles_removed, NULL); if (status || num_profiles_removed != num_profiles) return -EIO; /* Delete stale entry now */ list_del(&rl_info->list_entry); devm_kfree(ice_hw_to_dev(hw), rl_info); return status; } /** * ice_sched_clear_rl_prof - clears RL prof entries * @pi: port information structure * * This function removes all RL profile from HW as well as from SW DB. */ static void ice_sched_clear_rl_prof(struct ice_port_info *pi) { u16 ln; for (ln = 0; ln < pi->hw->num_tx_sched_layers; ln++) { struct ice_aqc_rl_profile_info *rl_prof_elem; struct ice_aqc_rl_profile_info *rl_prof_tmp; list_for_each_entry_safe(rl_prof_elem, rl_prof_tmp, &pi->rl_prof_list[ln], list_entry) { struct ice_hw *hw = pi->hw; int status; rl_prof_elem->prof_id_ref = 0; status = ice_sched_del_rl_profile(hw, rl_prof_elem); if (status) { ice_debug(hw, ICE_DBG_SCHED, "Remove rl profile failed\n"); /* On error, free mem required */ list_del(&rl_prof_elem->list_entry); devm_kfree(ice_hw_to_dev(hw), rl_prof_elem); } } } } /** * ice_sched_clear_agg - clears the aggregator related information * @hw: pointer to the hardware structure * * This function removes aggregator list and free up aggregator related memory * previously allocated. */ void ice_sched_clear_agg(struct ice_hw *hw) { struct ice_sched_agg_info *agg_info; struct ice_sched_agg_info *atmp; list_for_each_entry_safe(agg_info, atmp, &hw->agg_list, list_entry) { struct ice_sched_agg_vsi_info *agg_vsi_info; struct ice_sched_agg_vsi_info *vtmp; list_for_each_entry_safe(agg_vsi_info, vtmp, &agg_info->agg_vsi_list, list_entry) { list_del(&agg_vsi_info->list_entry); devm_kfree(ice_hw_to_dev(hw), agg_vsi_info); } list_del(&agg_info->list_entry); devm_kfree(ice_hw_to_dev(hw), agg_info); } } /** * ice_sched_clear_tx_topo - clears the scheduler tree nodes * @pi: port information structure * * This function removes all the nodes from HW as well as from SW DB. */ static void ice_sched_clear_tx_topo(struct ice_port_info *pi) { if (!pi) return; /* remove RL profiles related lists */ ice_sched_clear_rl_prof(pi); if (pi->root) { ice_free_sched_node(pi, pi->root); pi->root = NULL; } } /** * ice_sched_clear_port - clear the scheduler elements from SW DB for a port * @pi: port information structure * * Cleanup scheduling elements from SW DB */ void ice_sched_clear_port(struct ice_port_info *pi) { if (!pi || pi->port_state != ICE_SCHED_PORT_STATE_READY) return; pi->port_state = ICE_SCHED_PORT_STATE_INIT; mutex_lock(&pi->sched_lock); ice_sched_clear_tx_topo(pi); mutex_unlock(&pi->sched_lock); mutex_destroy(&pi->sched_lock); } /** * ice_sched_cleanup_all - cleanup scheduler elements from SW DB for all ports * @hw: pointer to the HW struct * * Cleanup scheduling elements from SW DB for all the ports */ void ice_sched_cleanup_all(struct ice_hw *hw) { if (!hw) return; devm_kfree(ice_hw_to_dev(hw), hw->layer_info); hw->layer_info = NULL; ice_sched_clear_port(hw->port_info); hw->num_tx_sched_layers = 0; hw->num_tx_sched_phys_layers = 0; hw->flattened_layers = 0; hw->max_cgds = 0; } /** * ice_sched_add_elems - add nodes to HW and SW DB * @pi: port information structure * @tc_node: pointer to the branch node * @parent: pointer to the parent node * @layer: layer number to add nodes * @num_nodes: number of nodes * @num_nodes_added: pointer to num nodes added * @first_node_teid: if new nodes are added then return the TEID of first node * @prealloc_nodes: preallocated nodes struct for software DB * * This function add nodes to HW as well as to SW DB for a given layer */ int ice_sched_add_elems(struct ice_port_info *pi, struct ice_sched_node *tc_node, struct ice_sched_node *parent, u8 layer, u16 num_nodes, u16 *num_nodes_added, u32 *first_node_teid, struct ice_sched_node **prealloc_nodes) { struct ice_sched_node *prev, *new_node; struct ice_aqc_add_elem *buf; u16 i, num_groups_added = 0; struct ice_hw *hw = pi->hw; size_t buf_size; int status = 0; u32 teid; buf_size = struct_size(buf, generic, num_nodes); buf = devm_kzalloc(ice_hw_to_dev(hw), buf_size, GFP_KERNEL); if (!buf) return -ENOMEM; buf->hdr.parent_teid = parent->info.node_teid; buf->hdr.num_elems = cpu_to_le16(num_nodes); for (i = 0; i < num_nodes; i++) { buf->generic[i].parent_teid = parent->info.node_teid; buf->generic[i].data.elem_type = ICE_AQC_ELEM_TYPE_SE_GENERIC; buf->generic[i].data.valid_sections = ICE_AQC_ELEM_VALID_GENERIC | ICE_AQC_ELEM_VALID_CIR | ICE_AQC_ELEM_VALID_EIR; buf->generic[i].data.generic = 0; buf->generic[i].data.cir_bw.bw_profile_idx = cpu_to_le16(ICE_SCHED_DFLT_RL_PROF_ID); buf->generic[i].data.cir_bw.bw_alloc = cpu_to_le16(ICE_SCHED_DFLT_BW_WT); buf->generic[i].data.eir_bw.bw_profile_idx = cpu_to_le16(ICE_SCHED_DFLT_RL_PROF_ID); buf->generic[i].data.eir_bw.bw_alloc = cpu_to_le16(ICE_SCHED_DFLT_BW_WT); } status = ice_aq_add_sched_elems(hw, 1, buf, buf_size, &num_groups_added, NULL); if (status || num_groups_added != 1) { ice_debug(hw, ICE_DBG_SCHED, "add node failed FW Error %d\n", hw->adminq.sq_last_status); devm_kfree(ice_hw_to_dev(hw), buf); return -EIO; } *num_nodes_added = num_nodes; /* add nodes to the SW DB */ for (i = 0; i < num_nodes; i++) { if (prealloc_nodes) status = ice_sched_add_node(pi, layer, &buf->generic[i], prealloc_nodes[i]); else status = ice_sched_add_node(pi, layer, &buf->generic[i], NULL); if (status) { ice_debug(hw, ICE_DBG_SCHED, "add nodes in SW DB failed status =%d\n", status); break; } teid = le32_to_cpu(buf->generic[i].node_teid); new_node = ice_sched_find_node_by_teid(parent, teid); if (!new_node) { ice_debug(hw, ICE_DBG_SCHED, "Node is missing for teid =%d\n", teid); break; } new_node->sibling = NULL; new_node->tc_num = tc_node->tc_num; new_node->tx_weight = ICE_SCHED_DFLT_BW_WT; new_node->tx_share = ICE_SCHED_DFLT_BW; new_node->tx_max = ICE_SCHED_DFLT_BW; new_node->name = kzalloc(SCHED_NODE_NAME_MAX_LEN, GFP_KERNEL); if (!new_node->name) return -ENOMEM; status = xa_alloc(&pi->sched_node_ids, &new_node->id, NULL, XA_LIMIT(0, UINT_MAX), GFP_KERNEL); if (status) { ice_debug(hw, ICE_DBG_SCHED, "xa_alloc failed for sched node status =%d\n", status); break; } snprintf(new_node->name, SCHED_NODE_NAME_MAX_LEN, "node_%u", new_node->id); /* add it to previous node sibling pointer */ /* Note: siblings are not linked across branches */ prev = ice_sched_get_first_node(pi, tc_node, layer); if (prev && prev != new_node) { while (prev->sibling) prev = prev->sibling; prev->sibling = new_node; } /* initialize the sibling head */ if (!pi->sib_head[tc_node->tc_num][layer]) pi->sib_head[tc_node->tc_num][layer] = new_node; if (i == 0) *first_node_teid = teid; } devm_kfree(ice_hw_to_dev(hw), buf); return status; } /** * ice_sched_add_nodes_to_hw_layer - Add nodes to HW layer * @pi: port information structure * @tc_node: pointer to TC node * @parent: pointer to parent node * @layer: layer number to add nodes * @num_nodes: number of nodes to be added * @first_node_teid: pointer to the first node TEID * @num_nodes_added: pointer to number of nodes added * * Add nodes into specific HW layer. */ static int ice_sched_add_nodes_to_hw_layer(struct ice_port_info *pi, struct ice_sched_node *tc_node, struct ice_sched_node *parent, u8 layer, u16 num_nodes, u32 *first_node_teid, u16 *num_nodes_added) { u16 max_child_nodes; *num_nodes_added = 0; if (!num_nodes) return 0; if (!parent || layer < pi->hw->sw_entry_point_layer) return -EINVAL; /* max children per node per layer */ max_child_nodes = pi->hw->max_children[parent->tx_sched_layer]; /* current number of children + required nodes exceed max children */ if ((parent->num_children + num_nodes) > max_child_nodes) { /* Fail if the parent is a TC node */ if (parent == tc_node) return -EIO; return -ENOSPC; } return ice_sched_add_elems(pi, tc_node, parent, layer, num_nodes, num_nodes_added, first_node_teid, NULL); } /** * ice_sched_add_nodes_to_layer - Add nodes to a given layer * @pi: port information structure * @tc_node: pointer to TC node * @parent: pointer to parent node * @layer: layer number to add nodes * @num_nodes: number of nodes to be added * @first_node_teid: pointer to the first node TEID * @num_nodes_added: pointer to number of nodes added * * This function add nodes to a given layer. */ int ice_sched_add_nodes_to_layer(struct ice_port_info *pi, struct ice_sched_node *tc_node, struct ice_sched_node *parent, u8 layer, u16 num_nodes, u32 *first_node_teid, u16 *num_nodes_added) { u32 *first_teid_ptr = first_node_teid; u16 new_num_nodes = num_nodes; int status = 0; *num_nodes_added = 0; while (*num_nodes_added < num_nodes) { u16 max_child_nodes, num_added = 0; u32 temp; status = ice_sched_add_nodes_to_hw_layer(pi, tc_node, parent, layer, new_num_nodes, first_teid_ptr, &num_added); if (!status) *num_nodes_added += num_added; /* added more nodes than requested ? */ if (*num_nodes_added > num_nodes) { ice_debug(pi->hw, ICE_DBG_SCHED, "added extra nodes %d %d\n", num_nodes, *num_nodes_added); status = -EIO; break; } /* break if all the nodes are added successfully */ if (!status && (*num_nodes_added == num_nodes)) break; /* break if the error is not max limit */ if (status && status != -ENOSPC) break; /* Exceeded the max children */ max_child_nodes = pi->hw->max_children[parent->tx_sched_layer]; /* utilize all the spaces if the parent is not full */ if (parent->num_children < max_child_nodes) { new_num_nodes = max_child_nodes - parent->num_children; } else { /* This parent is full, try the next sibling */ parent = parent->sibling; /* Don't modify the first node TEID memory if the * first node was added already in the above call. * Instead send some temp memory for all other * recursive calls. */ if (num_added) first_teid_ptr = &temp; new_num_nodes = num_nodes - *num_nodes_added; } } return status; } /** * ice_sched_get_qgrp_layer - get the current queue group layer number * @hw: pointer to the HW struct * * This function returns the current queue group layer number */ static u8 ice_sched_get_qgrp_layer(struct ice_hw *hw) { /* It's always total layers - 1, the array is 0 relative so -2 */ return hw->num_tx_sched_layers - ICE_QGRP_LAYER_OFFSET; } /** * ice_sched_get_vsi_layer - get the current VSI layer number * @hw: pointer to the HW struct * * This function returns the current VSI layer number */ u8 ice_sched_get_vsi_layer(struct ice_hw *hw) { /* Num Layers VSI layer * 9 6 * 7 4 * 5 or less sw_entry_point_layer */ /* calculate the VSI layer based on number of layers. */ if (hw->num_tx_sched_layers > ICE_VSI_LAYER_OFFSET + 1) { u8 layer = hw->num_tx_sched_layers - ICE_VSI_LAYER_OFFSET; if (layer > hw->sw_entry_point_layer) return layer; } return hw->sw_entry_point_layer; } /** * ice_sched_get_agg_layer - get the current aggregator layer number * @hw: pointer to the HW struct * * This function returns the current aggregator layer number */ u8 ice_sched_get_agg_layer(struct ice_hw *hw) { /* Num Layers aggregator layer * 9 4 * 7 or less sw_entry_point_layer */ /* calculate the aggregator layer based on number of layers. */ if (hw->num_tx_sched_layers > ICE_AGG_LAYER_OFFSET + 1) { u8 layer = hw->num_tx_sched_layers - ICE_AGG_LAYER_OFFSET; if (layer > hw->sw_entry_point_layer) return layer; } return hw->sw_entry_point_layer; } /** * ice_rm_dflt_leaf_node - remove the default leaf node in the tree * @pi: port information structure * * This function removes the leaf node that was created by the FW * during initialization */ static void ice_rm_dflt_leaf_node(struct ice_port_info *pi) { struct ice_sched_node *node; node = pi->root; while (node) { if (!node->num_children) break; node = node->children[0]; } if (node && node->info.data.elem_type == ICE_AQC_ELEM_TYPE_LEAF) { u32 teid = le32_to_cpu(node->info.node_teid); int status; /* remove the default leaf node */ status = ice_sched_remove_elems(pi->hw, node->parent, 1, &teid); if (!status) ice_free_sched_node(pi, node); } } /** * ice_sched_rm_dflt_nodes - free the default nodes in the tree * @pi: port information structure * * This function frees all the nodes except root and TC that were created by * the FW during initialization */ static void ice_sched_rm_dflt_nodes(struct ice_port_info *pi) { struct ice_sched_node *node; ice_rm_dflt_leaf_node(pi); /* remove the default nodes except TC and root nodes */ node = pi->root; while (node) { if (node->tx_sched_layer >= pi->hw->sw_entry_point_layer && node->info.data.elem_type != ICE_AQC_ELEM_TYPE_TC && node->info.data.elem_type != ICE_AQC_ELEM_TYPE_ROOT_PORT) { ice_free_sched_node(pi, node); break; } if (!node->num_children) break; node = node->children[0]; } } /** * ice_sched_init_port - Initialize scheduler by querying information from FW * @pi: port info structure for the tree to cleanup * * This function is the initial call to find the total number of Tx scheduler * resources, default topology created by firmware and storing the information * in SW DB. */ int ice_sched_init_port(struct ice_port_info *pi) { struct ice_aqc_get_topo_elem *buf; struct ice_hw *hw; u8 num_branches; u16 num_elems; int status; u8 i, j; if (!pi) return -EINVAL; hw = pi->hw; /* Query the Default Topology from FW */ buf = kzalloc(ICE_AQ_MAX_BUF_LEN, GFP_KERNEL); if (!buf) return -ENOMEM; /* Query default scheduling tree topology */ status = ice_aq_get_dflt_topo(hw, pi->lport, buf, ICE_AQ_MAX_BUF_LEN, &num_branches, NULL); if (status) goto err_init_port; /* num_branches should be between 1-8 */ if (num_branches < 1 || num_branches > ICE_TXSCHED_MAX_BRANCHES) { ice_debug(hw, ICE_DBG_SCHED, "num_branches unexpected %d\n", num_branches); status = -EINVAL; goto err_init_port; } /* get the number of elements on the default/first branch */ num_elems = le16_to_cpu(buf[0].hdr.num_elems); /* num_elems should always be between 1-9 */ if (num_elems < 1 || num_elems > ICE_AQC_TOPO_MAX_LEVEL_NUM) { ice_debug(hw, ICE_DBG_SCHED, "num_elems unexpected %d\n", num_elems); status = -EINVAL; goto err_init_port; } /* If the last node is a leaf node then the index of the queue group * layer is two less than the number of elements. */ if (num_elems > 2 && buf[0].generic[num_elems - 1].data.elem_type == ICE_AQC_ELEM_TYPE_LEAF) pi->last_node_teid = le32_to_cpu(buf[0].generic[num_elems - 2].node_teid); else pi->last_node_teid = le32_to_cpu(buf[0].generic[num_elems - 1].node_teid); /* Insert the Tx Sched root node */ status = ice_sched_add_root_node(pi, &buf[0].generic[0]); if (status) goto err_init_port; /* Parse the default tree and cache the information */ for (i = 0; i < num_branches; i++) { num_elems = le16_to_cpu(buf[i].hdr.num_elems); /* Skip root element as already inserted */ for (j = 1; j < num_elems; j++) { /* update the sw entry point */ if (buf[0].generic[j].data.elem_type == ICE_AQC_ELEM_TYPE_ENTRY_POINT) hw->sw_entry_point_layer = j; status = ice_sched_add_node(pi, j, &buf[i].generic[j], NULL); if (status) goto err_init_port; } } /* Remove the default nodes. */ if (pi->root) ice_sched_rm_dflt_nodes(pi); /* initialize the port for handling the scheduler tree */ pi->port_state = ICE_SCHED_PORT_STATE_READY; mutex_init(&pi->sched_lock); for (i = 0; i < ICE_AQC_TOPO_MAX_LEVEL_NUM; i++) INIT_LIST_HEAD(&pi->rl_prof_list[i]); err_init_port: if (status && pi->root) { ice_free_sched_node(pi, pi->root); pi->root = NULL; } kfree(buf); return status; } /** * ice_sched_query_res_alloc - query the FW for num of logical sched layers * @hw: pointer to the HW struct * * query FW for allocated scheduler resources and store in HW struct */ int ice_sched_query_res_alloc(struct ice_hw *hw) { struct ice_aqc_query_txsched_res_resp *buf; __le16 max_sibl; int status = 0; u16 i; if (hw->layer_info) return status; buf = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*buf), GFP_KERNEL); if (!buf) return -ENOMEM; status = ice_aq_query_sched_res(hw, sizeof(*buf), buf, NULL); if (status) goto sched_query_out; hw->num_tx_sched_layers = le16_to_cpu(buf->sched_props.logical_levels); hw->num_tx_sched_phys_layers = le16_to_cpu(buf->sched_props.phys_levels); hw->flattened_layers = buf->sched_props.flattening_bitmap; hw->max_cgds = buf->sched_props.max_pf_cgds; /* max sibling group size of current layer refers to the max children * of the below layer node. * layer 1 node max children will be layer 2 max sibling group size * layer 2 node max children will be layer 3 max sibling group size * and so on. This array will be populated from root (index 0) to * qgroup layer 7. Leaf node has no children. */ for (i = 0; i < hw->num_tx_sched_layers - 1; i++) { max_sibl = buf->layer_props[i + 1].max_sibl_grp_sz; hw->max_children[i] = le16_to_cpu(max_sibl); } hw->layer_info = devm_kmemdup(ice_hw_to_dev(hw), buf->layer_props, (hw->num_tx_sched_layers * sizeof(*hw->layer_info)), GFP_KERNEL); if (!hw->layer_info) { status = -ENOMEM; goto sched_query_out; } sched_query_out: devm_kfree(ice_hw_to_dev(hw), buf); return status; } /** * ice_sched_get_psm_clk_freq - determine the PSM clock frequency * @hw: pointer to the HW struct * * Determine the PSM clock frequency and store in HW struct */ void ice_sched_get_psm_clk_freq(struct ice_hw *hw) { u32 val, clk_src; val = rd32(hw, GLGEN_CLKSTAT_SRC); clk_src = (val & GLGEN_CLKSTAT_SRC_PSM_CLK_SRC_M) >> GLGEN_CLKSTAT_SRC_PSM_CLK_SRC_S; #define PSM_CLK_SRC_367_MHZ 0x0 #define PSM_CLK_SRC_416_MHZ 0x1 #define PSM_CLK_SRC_446_MHZ 0x2 #define PSM_CLK_SRC_390_MHZ 0x3 switch (clk_src) { case PSM_CLK_SRC_367_MHZ: hw->psm_clk_freq = ICE_PSM_CLK_367MHZ_IN_HZ; break; case PSM_CLK_SRC_416_MHZ: hw->psm_clk_freq = ICE_PSM_CLK_416MHZ_IN_HZ; break; case PSM_CLK_SRC_446_MHZ: hw->psm_clk_freq = ICE_PSM_CLK_446MHZ_IN_HZ; break; case PSM_CLK_SRC_390_MHZ: hw->psm_clk_freq = ICE_PSM_CLK_390MHZ_IN_HZ; break; default: ice_debug(hw, ICE_DBG_SCHED, "PSM clk_src unexpected %u\n", clk_src); /* fall back to a safe default */ hw->psm_clk_freq = ICE_PSM_CLK_446MHZ_IN_HZ; } } /** * ice_sched_find_node_in_subtree - Find node in part of base node subtree * @hw: pointer to the HW struct * @base: pointer to the base node * @node: pointer to the node to search * * This function checks whether a given node is part of the base node * subtree or not */ static bool ice_sched_find_node_in_subtree(struct ice_hw *hw, struct ice_sched_node *base, struct ice_sched_node *node) { u8 i; for (i = 0; i < base->num_children; i++) { struct ice_sched_node *child = base->children[i]; if (node == child) return true; if (child->tx_sched_layer > node->tx_sched_layer) return false; /* this recursion is intentional, and wouldn't * go more than 8 calls */ if (ice_sched_find_node_in_subtree(hw, child, node)) return true; } return false; } /** * ice_sched_get_free_qgrp - Scan all queue group siblings and find a free node * @pi: port information structure * @vsi_node: software VSI handle * @qgrp_node: first queue group node identified for scanning * @owner: LAN or RDMA * * This function retrieves a free LAN or RDMA queue group node by scanning * qgrp_node and its siblings for the queue group with the fewest number * of queues currently assigned. */ static struct ice_sched_node * ice_sched_get_free_qgrp(struct ice_port_info *pi, struct ice_sched_node *vsi_node, struct ice_sched_node *qgrp_node, u8 owner) { struct ice_sched_node *min_qgrp; u8 min_children; if (!qgrp_node) return qgrp_node; min_children = qgrp_node->num_children; if (!min_children) return qgrp_node; min_qgrp = qgrp_node; /* scan all queue groups until find a node which has less than the * minimum number of children. This way all queue group nodes get * equal number of shares and active. The bandwidth will be equally * distributed across all queues. */ while (qgrp_node) { /* make sure the qgroup node is part of the VSI subtree */ if (ice_sched_find_node_in_subtree(pi->hw, vsi_node, qgrp_node)) if (qgrp_node->num_children < min_children && qgrp_node->owner == owner) { /* replace the new min queue group node */ min_qgrp = qgrp_node; min_children = min_qgrp->num_children; /* break if it has no children, */ if (!min_children) break; } qgrp_node = qgrp_node->sibling; } return min_qgrp; } /** * ice_sched_get_free_qparent - Get a free LAN or RDMA queue group node * @pi: port information structure * @vsi_handle: software VSI handle * @tc: branch number * @owner: LAN or RDMA * * This function retrieves a free LAN or RDMA queue group node */ struct ice_sched_node * ice_sched_get_free_qparent(struct ice_port_info *pi, u16 vsi_handle, u8 tc, u8 owner) { struct ice_sched_node *vsi_node, *qgrp_node; struct ice_vsi_ctx *vsi_ctx; u16 max_children; u8 qgrp_layer; qgrp_layer = ice_sched_get_qgrp_layer(pi->hw); max_children = pi->hw->max_children[qgrp_layer]; vsi_ctx = ice_get_vsi_ctx(pi->hw, vsi_handle); if (!vsi_ctx) return NULL; vsi_node = vsi_ctx->sched.vsi_node[tc]; /* validate invalid VSI ID */ if (!vsi_node) return NULL; /* get the first queue group node from VSI sub-tree */ qgrp_node = ice_sched_get_first_node(pi, vsi_node, qgrp_layer); while (qgrp_node) { /* make sure the qgroup node is part of the VSI subtree */ if (ice_sched_find_node_in_subtree(pi->hw, vsi_node, qgrp_node)) if (qgrp_node->num_children < max_children && qgrp_node->owner == owner) break; qgrp_node = qgrp_node->sibling; } /* Select the best queue group */ return ice_sched_get_free_qgrp(pi, vsi_node, qgrp_node, owner); } /** * ice_sched_get_vsi_node - Get a VSI node based on VSI ID * @pi: pointer to the port information structure * @tc_node: pointer to the TC node * @vsi_handle: software VSI handle * * This function retrieves a VSI node for a given VSI ID from a given * TC branch */ static struct ice_sched_node * ice_sched_get_vsi_node(struct ice_port_info *pi, struct ice_sched_node *tc_node, u16 vsi_handle) { struct ice_sched_node *node; u8 vsi_layer; vsi_layer = ice_sched_get_vsi_layer(pi->hw); node = ice_sched_get_first_node(pi, tc_node, vsi_layer); /* Check whether it already exists */ while (node) { if (node->vsi_handle == vsi_handle) return node; node = node->sibling; } return node; } /** * ice_sched_get_agg_node - Get an aggregator node based on aggregator ID * @pi: pointer to the port information structure * @tc_node: pointer to the TC node * @agg_id: aggregator ID * * This function retrieves an aggregator node for a given aggregator ID from * a given TC branch */ struct ice_sched_node * ice_sched_get_agg_node(struct ice_port_info *pi, struct ice_sched_node *tc_node, u32 agg_id) { struct ice_sched_node *node; struct ice_hw *hw = pi->hw; u8 agg_layer; if (!hw) return NULL; agg_layer = ice_sched_get_agg_layer(hw); node = ice_sched_get_first_node(pi, tc_node, agg_layer); /* Check whether it already exists */ while (node) { if (node->agg_id == agg_id) return node; node = node->sibling; } return node; } /** * ice_sched_calc_vsi_child_nodes - calculate number of VSI child nodes * @hw: pointer to the HW struct * @num_qs: number of queues * @num_nodes: num nodes array * * This function calculates the number of VSI child nodes based on the * number of queues. */ static void ice_sched_calc_vsi_child_nodes(struct ice_hw *hw, u16 num_qs, u16 *num_nodes) { u16 num = num_qs; u8 i, qgl, vsil; qgl = ice_sched_get_qgrp_layer(hw); vsil = ice_sched_get_vsi_layer(hw); /* calculate num nodes from queue group to VSI layer */ for (i = qgl; i > vsil; i--) { /* round to the next integer if there is a remainder */ num = DIV_ROUND_UP(num, hw->max_children[i]); /* need at least one node */ num_nodes[i] = num ? num : 1; } } /** * ice_sched_add_vsi_child_nodes - add VSI child nodes to tree * @pi: port information structure * @vsi_handle: software VSI handle * @tc_node: pointer to the TC node * @num_nodes: pointer to the num nodes that needs to be added per layer * @owner: node owner (LAN or RDMA) * * This function adds the VSI child nodes to tree. It gets called for * LAN and RDMA separately. */ static int ice_sched_add_vsi_child_nodes(struct ice_port_info *pi, u16 vsi_handle, struct ice_sched_node *tc_node, u16 *num_nodes, u8 owner) { struct ice_sched_node *parent, *node; struct ice_hw *hw = pi->hw; u32 first_node_teid; u16 num_added = 0; u8 i, qgl, vsil; qgl = ice_sched_get_qgrp_layer(hw); vsil = ice_sched_get_vsi_layer(hw); parent = ice_sched_get_vsi_node(pi, tc_node, vsi_handle); for (i = vsil + 1; i <= qgl; i++) { int status; if (!parent) return -EIO; status = ice_sched_add_nodes_to_layer(pi, tc_node, parent, i, num_nodes[i], &first_node_teid, &num_added); if (status || num_nodes[i] != num_added) return -EIO; /* The newly added node can be a new parent for the next * layer nodes */ if (num_added) { parent = ice_sched_find_node_by_teid(tc_node, first_node_teid); node = parent; while (node) { node->owner = owner; node = node->sibling; } } else { parent = parent->children[0]; } } return 0; } /** * ice_sched_calc_vsi_support_nodes - calculate number of VSI support nodes * @pi: pointer to the port info structure * @tc_node: pointer to TC node * @num_nodes: pointer to num nodes array * * This function calculates the number of supported nodes needed to add this * VSI into Tx tree including the VSI, parent and intermediate nodes in below * layers */ static void ice_sched_calc_vsi_support_nodes(struct ice_port_info *pi, struct ice_sched_node *tc_node, u16 *num_nodes) { struct ice_sched_node *node; u8 vsil; int i; vsil = ice_sched_get_vsi_layer(pi->hw); for (i = vsil; i >= pi->hw->sw_entry_point_layer; i--) /* Add intermediate nodes if TC has no children and * need at least one node for VSI */ if (!tc_node->num_children || i == vsil) { num_nodes[i]++; } else { /* If intermediate nodes are reached max children * then add a new one. */ node = ice_sched_get_first_node(pi, tc_node, (u8)i); /* scan all the siblings */ while (node) { if (node->num_children < pi->hw->max_children[i]) break; node = node->sibling; } /* tree has one intermediate node to add this new VSI. * So no need to calculate supported nodes for below * layers. */ if (node) break; /* all the nodes are full, allocate a new one */ num_nodes[i]++; } } /** * ice_sched_add_vsi_support_nodes - add VSI supported nodes into Tx tree * @pi: port information structure * @vsi_handle: software VSI handle * @tc_node: pointer to TC node * @num_nodes: pointer to num nodes array * * This function adds the VSI supported nodes into Tx tree including the * VSI, its parent and intermediate nodes in below layers */ static int ice_sched_add_vsi_support_nodes(struct ice_port_info *pi, u16 vsi_handle, struct ice_sched_node *tc_node, u16 *num_nodes) { struct ice_sched_node *parent = tc_node; u32 first_node_teid; u16 num_added = 0; u8 i, vsil; if (!pi) return -EINVAL; vsil = ice_sched_get_vsi_layer(pi->hw); for (i = pi->hw->sw_entry_point_layer; i <= vsil; i++) { int status; status = ice_sched_add_nodes_to_layer(pi, tc_node, parent, i, num_nodes[i], &first_node_teid, &num_added); if (status || num_nodes[i] != num_added) return -EIO; /* The newly added node can be a new parent for the next * layer nodes */ if (num_added) parent = ice_sched_find_node_by_teid(tc_node, first_node_teid); else parent = parent->children[0]; if (!parent) return -EIO; if (i == vsil) parent->vsi_handle = vsi_handle; } return 0; } /** * ice_sched_add_vsi_to_topo - add a new VSI into tree * @pi: port information structure * @vsi_handle: software VSI handle * @tc: TC number * * This function adds a new VSI into scheduler tree */ static int ice_sched_add_vsi_to_topo(struct ice_port_info *pi, u16 vsi_handle, u8 tc) { u16 num_nodes[ICE_AQC_TOPO_MAX_LEVEL_NUM] = { 0 }; struct ice_sched_node *tc_node; tc_node = ice_sched_get_tc_node(pi, tc); if (!tc_node) return -EINVAL; /* calculate number of supported nodes needed for this VSI */ ice_sched_calc_vsi_support_nodes(pi, tc_node, num_nodes); /* add VSI supported nodes to TC subtree */ return ice_sched_add_vsi_support_nodes(pi, vsi_handle, tc_node, num_nodes); } /** * ice_sched_update_vsi_child_nodes - update VSI child nodes * @pi: port information structure * @vsi_handle: software VSI handle * @tc: TC number * @new_numqs: new number of max queues * @owner: owner of this subtree * * This function updates the VSI child nodes based on the number of queues */ static int ice_sched_update_vsi_child_nodes(struct ice_port_info *pi, u16 vsi_handle, u8 tc, u16 new_numqs, u8 owner) { u16 new_num_nodes[ICE_AQC_TOPO_MAX_LEVEL_NUM] = { 0 }; struct ice_sched_node *vsi_node; struct ice_sched_node *tc_node; struct ice_vsi_ctx *vsi_ctx; struct ice_hw *hw = pi->hw; u16 prev_numqs; int status = 0; tc_node = ice_sched_get_tc_node(pi, tc); if (!tc_node) return -EIO; vsi_node = ice_sched_get_vsi_node(pi, tc_node, vsi_handle); if (!vsi_node) return -EIO; vsi_ctx = ice_get_vsi_ctx(hw, vsi_handle); if (!vsi_ctx) return -EINVAL; if (owner == ICE_SCHED_NODE_OWNER_LAN) prev_numqs = vsi_ctx->sched.max_lanq[tc]; else prev_numqs = vsi_ctx->sched.max_rdmaq[tc]; /* num queues are not changed or less than the previous number */ if (new_numqs <= prev_numqs) return status; if (owner == ICE_SCHED_NODE_OWNER_LAN) { status = ice_alloc_lan_q_ctx(hw, vsi_handle, tc, new_numqs); if (status) return status; } else { status = ice_alloc_rdma_q_ctx(hw, vsi_handle, tc, new_numqs); if (status) return status; } if (new_numqs) ice_sched_calc_vsi_child_nodes(hw, new_numqs, new_num_nodes); /* Keep the max number of queue configuration all the time. Update the * tree only if number of queues > previous number of queues. This may * leave some extra nodes in the tree if number of queues < previous * number but that wouldn't harm anything. Removing those extra nodes * may complicate the code if those nodes are part of SRL or * individually rate limited. */ status = ice_sched_add_vsi_child_nodes(pi, vsi_handle, tc_node, new_num_nodes, owner); if (status) return status; if (owner == ICE_SCHED_NODE_OWNER_LAN) vsi_ctx->sched.max_lanq[tc] = new_numqs; else vsi_ctx->sched.max_rdmaq[tc] = new_numqs; return 0; } /** * ice_sched_cfg_vsi - configure the new/existing VSI * @pi: port information structure * @vsi_handle: software VSI handle * @tc: TC number * @maxqs: max number of queues * @owner: LAN or RDMA * @enable: TC enabled or disabled * * This function adds/updates VSI nodes based on the number of queues. If TC is * enabled and VSI is in suspended state then resume the VSI back. If TC is * disabled then suspend the VSI if it is not already. */ int ice_sched_cfg_vsi(struct ice_port_info *pi, u16 vsi_handle, u8 tc, u16 maxqs, u8 owner, bool enable) { struct ice_sched_node *vsi_node, *tc_node; struct ice_vsi_ctx *vsi_ctx; struct ice_hw *hw = pi->hw; int status = 0; ice_debug(pi->hw, ICE_DBG_SCHED, "add/config VSI %d\n", vsi_handle); tc_node = ice_sched_get_tc_node(pi, tc); if (!tc_node) return -EINVAL; vsi_ctx = ice_get_vsi_ctx(hw, vsi_handle); if (!vsi_ctx) return -EINVAL; vsi_node = ice_sched_get_vsi_node(pi, tc_node, vsi_handle); /* suspend the VSI if TC is not enabled */ if (!enable) { if (vsi_node && vsi_node->in_use) { u32 teid = le32_to_cpu(vsi_node->info.node_teid); status = ice_sched_suspend_resume_elems(hw, 1, &teid, true); if (!status) vsi_node->in_use = false; } return status; } /* TC is enabled, if it is a new VSI then add it to the tree */ if (!vsi_node) { status = ice_sched_add_vsi_to_topo(pi, vsi_handle, tc); if (status) return status; vsi_node = ice_sched_get_vsi_node(pi, tc_node, vsi_handle); if (!vsi_node) return -EIO; vsi_ctx->sched.vsi_node[tc] = vsi_node; vsi_node->in_use = true; /* invalidate the max queues whenever VSI gets added first time * into the scheduler tree (boot or after reset). We need to * recreate the child nodes all the time in these cases. */ vsi_ctx->sched.max_lanq[tc] = 0; vsi_ctx->sched.max_rdmaq[tc] = 0; } /* update the VSI child nodes */ status = ice_sched_update_vsi_child_nodes(pi, vsi_handle, tc, maxqs, owner); if (status) return status; /* TC is enabled, resume the VSI if it is in the suspend state */ if (!vsi_node->in_use) { u32 teid = le32_to_cpu(vsi_node->info.node_teid); status = ice_sched_suspend_resume_elems(hw, 1, &teid, false); if (!status) vsi_node->in_use = true; } return status; } /** * ice_sched_rm_agg_vsi_info - remove aggregator related VSI info entry * @pi: port information structure * @vsi_handle: software VSI handle * * This function removes single aggregator VSI info entry from * aggregator list. */ static void ice_sched_rm_agg_vsi_info(struct ice_port_info *pi, u16 vsi_handle) { struct ice_sched_agg_info *agg_info; struct ice_sched_agg_info *atmp; list_for_each_entry_safe(agg_info, atmp, &pi->hw->agg_list, list_entry) { struct ice_sched_agg_vsi_info *agg_vsi_info; struct ice_sched_agg_vsi_info *vtmp; list_for_each_entry_safe(agg_vsi_info, vtmp, &agg_info->agg_vsi_list, list_entry) if (agg_vsi_info->vsi_handle == vsi_handle) { list_del(&agg_vsi_info->list_entry); devm_kfree(ice_hw_to_dev(pi->hw), agg_vsi_info); return; } } } /** * ice_sched_is_leaf_node_present - check for a leaf node in the sub-tree * @node: pointer to the sub-tree node * * This function checks for a leaf node presence in a given sub-tree node. */ static bool ice_sched_is_leaf_node_present(struct ice_sched_node *node) { u8 i; for (i = 0; i < node->num_children; i++) if (ice_sched_is_leaf_node_present(node->children[i])) return true; /* check for a leaf node */ return (node->info.data.elem_type == ICE_AQC_ELEM_TYPE_LEAF); } /** * ice_sched_rm_vsi_cfg - remove the VSI and its children nodes * @pi: port information structure * @vsi_handle: software VSI handle * @owner: LAN or RDMA * * This function removes the VSI and its LAN or RDMA children nodes from the * scheduler tree. */ static int ice_sched_rm_vsi_cfg(struct ice_port_info *pi, u16 vsi_handle, u8 owner) { struct ice_vsi_ctx *vsi_ctx; int status = -EINVAL; u8 i; ice_debug(pi->hw, ICE_DBG_SCHED, "removing VSI %d\n", vsi_handle); if (!ice_is_vsi_valid(pi->hw, vsi_handle)) return status; mutex_lock(&pi->sched_lock); vsi_ctx = ice_get_vsi_ctx(pi->hw, vsi_handle); if (!vsi_ctx) goto exit_sched_rm_vsi_cfg; ice_for_each_traffic_class(i) { struct ice_sched_node *vsi_node, *tc_node; u8 j = 0; tc_node = ice_sched_get_tc_node(pi, i); if (!tc_node) continue; vsi_node = ice_sched_get_vsi_node(pi, tc_node, vsi_handle); if (!vsi_node) continue; if (ice_sched_is_leaf_node_present(vsi_node)) { ice_debug(pi->hw, ICE_DBG_SCHED, "VSI has leaf nodes in TC %d\n", i); status = -EBUSY; goto exit_sched_rm_vsi_cfg; } while (j < vsi_node->num_children) { if (vsi_node->children[j]->owner == owner) { ice_free_sched_node(pi, vsi_node->children[j]); /* reset the counter again since the num * children will be updated after node removal */ j = 0; } else { j++; } } /* remove the VSI if it has no children */ if (!vsi_node->num_children) { ice_free_sched_node(pi, vsi_node); vsi_ctx->sched.vsi_node[i] = NULL; /* clean up aggregator related VSI info if any */ ice_sched_rm_agg_vsi_info(pi, vsi_handle); } if (owner == ICE_SCHED_NODE_OWNER_LAN) vsi_ctx->sched.max_lanq[i] = 0; else vsi_ctx->sched.max_rdmaq[i] = 0; } status = 0; exit_sched_rm_vsi_cfg: mutex_unlock(&pi->sched_lock); return status; } /** * ice_rm_vsi_lan_cfg - remove VSI and its LAN children nodes * @pi: port information structure * @vsi_handle: software VSI handle * * This function clears the VSI and its LAN children nodes from scheduler tree * for all TCs. */ int ice_rm_vsi_lan_cfg(struct ice_port_info *pi, u16 vsi_handle) { return ice_sched_rm_vsi_cfg(pi, vsi_handle, ICE_SCHED_NODE_OWNER_LAN); } /** * ice_rm_vsi_rdma_cfg - remove VSI and its RDMA children nodes * @pi: port information structure * @vsi_handle: software VSI handle * * This function clears the VSI and its RDMA children nodes from scheduler tree * for all TCs. */ int ice_rm_vsi_rdma_cfg(struct ice_port_info *pi, u16 vsi_handle) { return ice_sched_rm_vsi_cfg(pi, vsi_handle, ICE_SCHED_NODE_OWNER_RDMA); } /** * ice_get_agg_info - get the aggregator ID * @hw: pointer to the hardware structure * @agg_id: aggregator ID * * This function validates aggregator ID. The function returns info if * aggregator ID is present in list otherwise it returns null. */ static struct ice_sched_agg_info * ice_get_agg_info(struct ice_hw *hw, u32 agg_id) { struct ice_sched_agg_info *agg_info; list_for_each_entry(agg_info, &hw->agg_list, list_entry) if (agg_info->agg_id == agg_id) return agg_info; return NULL; } /** * ice_sched_get_free_vsi_parent - Find a free parent node in aggregator subtree * @hw: pointer to the HW struct * @node: pointer to a child node * @num_nodes: num nodes count array * * This function walks through the aggregator subtree to find a free parent * node */ struct ice_sched_node * ice_sched_get_free_vsi_parent(struct ice_hw *hw, struct ice_sched_node *node, u16 *num_nodes) { u8 l = node->tx_sched_layer; u8 vsil, i; vsil = ice_sched_get_vsi_layer(hw); /* Is it VSI parent layer ? */ if (l == vsil - 1) return (node->num_children < hw->max_children[l]) ? node : NULL; /* We have intermediate nodes. Let's walk through the subtree. If the * intermediate node has space to add a new node then clear the count */ if (node->num_children < hw->max_children[l]) num_nodes[l] = 0; /* The below recursive call is intentional and wouldn't go more than * 2 or 3 iterations. */ for (i = 0; i < node->num_children; i++) { struct ice_sched_node *parent; parent = ice_sched_get_free_vsi_parent(hw, node->children[i], num_nodes); if (parent) return parent; } return NULL; } /** * ice_sched_update_parent - update the new parent in SW DB * @new_parent: pointer to a new parent node * @node: pointer to a child node * * This function removes the child from the old parent and adds it to a new * parent */ void ice_sched_update_parent(struct ice_sched_node *new_parent, struct ice_sched_node *node) { struct ice_sched_node *old_parent; u8 i, j; old_parent = node->parent; /* update the old parent children */ for (i = 0; i < old_parent->num_children; i++) if (old_parent->children[i] == node) { for (j = i + 1; j < old_parent->num_children; j++) old_parent->children[j - 1] = old_parent->children[j]; old_parent->num_children--; break; } /* now move the node to a new parent */ new_parent->children[new_parent->num_children++] = node; node->parent = new_parent; node->info.parent_teid = new_parent->info.node_teid; } /** * ice_sched_move_nodes - move child nodes to a given parent * @pi: port information structure * @parent: pointer to parent node * @num_items: number of child nodes to be moved * @list: pointer to child node teids * * This function move the child nodes to a given parent. */ int ice_sched_move_nodes(struct ice_port_info *pi, struct ice_sched_node *parent, u16 num_items, u32 *list) { struct ice_aqc_move_elem *buf; struct ice_sched_node *node; u16 i, grps_movd = 0; struct ice_hw *hw; int status = 0; u16 buf_len; hw = pi->hw; if (!parent || !num_items) return -EINVAL; /* Does parent have enough space */ if (parent->num_children + num_items > hw->max_children[parent->tx_sched_layer]) return -ENOSPC; buf_len = struct_size(buf, teid, 1); buf = kzalloc(buf_len, GFP_KERNEL); if (!buf) return -ENOMEM; for (i = 0; i < num_items; i++) { node = ice_sched_find_node_by_teid(pi->root, list[i]); if (!node) { status = -EINVAL; goto move_err_exit; } buf->hdr.src_parent_teid = node->info.parent_teid; buf->hdr.dest_parent_teid = parent->info.node_teid; buf->teid[0] = node->info.node_teid; buf->hdr.num_elems = cpu_to_le16(1); status = ice_aq_move_sched_elems(hw, 1, buf, buf_len, &grps_movd, NULL); if (status && grps_movd != 1) { status = -EIO; goto move_err_exit; } /* update the SW DB */ ice_sched_update_parent(parent, node); } move_err_exit: kfree(buf); return status; } /** * ice_sched_move_vsi_to_agg - move VSI to aggregator node * @pi: port information structure * @vsi_handle: software VSI handle * @agg_id: aggregator ID * @tc: TC number * * This function moves a VSI to an aggregator node or its subtree. * Intermediate nodes may be created if required. */ static int ice_sched_move_vsi_to_agg(struct ice_port_info *pi, u16 vsi_handle, u32 agg_id, u8 tc) { struct ice_sched_node *vsi_node, *agg_node, *tc_node, *parent; u16 num_nodes[ICE_AQC_TOPO_MAX_LEVEL_NUM] = { 0 }; u32 first_node_teid, vsi_teid; u16 num_nodes_added; u8 aggl, vsil, i; int status; tc_node = ice_sched_get_tc_node(pi, tc); if (!tc_node) return -EIO; agg_node = ice_sched_get_agg_node(pi, tc_node, agg_id); if (!agg_node) return -ENOENT; vsi_node = ice_sched_get_vsi_node(pi, tc_node, vsi_handle); if (!vsi_node) return -ENOENT; /* Is this VSI already part of given aggregator? */ if (ice_sched_find_node_in_subtree(pi->hw, agg_node, vsi_node)) return 0; aggl = ice_sched_get_agg_layer(pi->hw); vsil = ice_sched_get_vsi_layer(pi->hw); /* set intermediate node count to 1 between aggregator and VSI layers */ for (i = aggl + 1; i < vsil; i++) num_nodes[i] = 1; /* Check if the aggregator subtree has any free node to add the VSI */ for (i = 0; i < agg_node->num_children; i++) { parent = ice_sched_get_free_vsi_parent(pi->hw, agg_node->children[i], num_nodes); if (parent) goto move_nodes; } /* add new nodes */ parent = agg_node; for (i = aggl + 1; i < vsil; i++) { status = ice_sched_add_nodes_to_layer(pi, tc_node, parent, i, num_nodes[i], &first_node_teid, &num_nodes_added); if (status || num_nodes[i] != num_nodes_added) return -EIO; /* The newly added node can be a new parent for the next * layer nodes */ if (num_nodes_added) parent = ice_sched_find_node_by_teid(tc_node, first_node_teid); else parent = parent->children[0]; if (!parent) return -EIO; } move_nodes: vsi_teid = le32_to_cpu(vsi_node->info.node_teid); return ice_sched_move_nodes(pi, parent, 1, &vsi_teid); } /** * ice_move_all_vsi_to_dflt_agg - move all VSI(s) to default aggregator * @pi: port information structure * @agg_info: aggregator info * @tc: traffic class number * @rm_vsi_info: true or false * * This function move all the VSI(s) to the default aggregator and delete * aggregator VSI info based on passed in boolean parameter rm_vsi_info. The * caller holds the scheduler lock. */ static int ice_move_all_vsi_to_dflt_agg(struct ice_port_info *pi, struct ice_sched_agg_info *agg_info, u8 tc, bool rm_vsi_info) { struct ice_sched_agg_vsi_info *agg_vsi_info; struct ice_sched_agg_vsi_info *tmp; int status = 0; list_for_each_entry_safe(agg_vsi_info, tmp, &agg_info->agg_vsi_list, list_entry) { u16 vsi_handle = agg_vsi_info->vsi_handle; /* Move VSI to default aggregator */ if (!ice_is_tc_ena(agg_vsi_info->tc_bitmap[0], tc)) continue; status = ice_sched_move_vsi_to_agg(pi, vsi_handle, ICE_DFLT_AGG_ID, tc); if (status) break; clear_bit(tc, agg_vsi_info->tc_bitmap); if (rm_vsi_info && !agg_vsi_info->tc_bitmap[0]) { list_del(&agg_vsi_info->list_entry); devm_kfree(ice_hw_to_dev(pi->hw), agg_vsi_info); } } return status; } /** * ice_sched_is_agg_inuse - check whether the aggregator is in use or not * @pi: port information structure * @node: node pointer * * This function checks whether the aggregator is attached with any VSI or not. */ static bool ice_sched_is_agg_inuse(struct ice_port_info *pi, struct ice_sched_node *node) { u8 vsil, i; vsil = ice_sched_get_vsi_layer(pi->hw); if (node->tx_sched_layer < vsil - 1) { for (i = 0; i < node->num_children; i++) if (ice_sched_is_agg_inuse(pi, node->children[i])) return true; return false; } else { return node->num_children ? true : false; } } /** * ice_sched_rm_agg_cfg - remove the aggregator node * @pi: port information structure * @agg_id: aggregator ID * @tc: TC number * * This function removes the aggregator node and intermediate nodes if any * from the given TC */ static int ice_sched_rm_agg_cfg(struct ice_port_info *pi, u32 agg_id, u8 tc) { struct ice_sched_node *tc_node, *agg_node; struct ice_hw *hw = pi->hw; tc_node = ice_sched_get_tc_node(pi, tc); if (!tc_node) return -EIO; agg_node = ice_sched_get_agg_node(pi, tc_node, agg_id); if (!agg_node) return -ENOENT; /* Can't remove the aggregator node if it has children */ if (ice_sched_is_agg_inuse(pi, agg_node)) return -EBUSY; /* need to remove the whole subtree if aggregator node is the * only child. */ while (agg_node->tx_sched_layer > hw->sw_entry_point_layer) { struct ice_sched_node *parent = agg_node->parent; if (!parent) return -EIO; if (parent->num_children > 1) break; agg_node = parent; } ice_free_sched_node(pi, agg_node); return 0; } /** * ice_rm_agg_cfg_tc - remove aggregator configuration for TC * @pi: port information structure * @agg_info: aggregator ID * @tc: TC number * @rm_vsi_info: bool value true or false * * This function removes aggregator reference to VSI of given TC. It removes * the aggregator configuration completely for requested TC. The caller needs * to hold the scheduler lock. */ static int ice_rm_agg_cfg_tc(struct ice_port_info *pi, struct ice_sched_agg_info *agg_info, u8 tc, bool rm_vsi_info) { int status = 0; /* If nothing to remove - return success */ if (!ice_is_tc_ena(agg_info->tc_bitmap[0], tc)) goto exit_rm_agg_cfg_tc; status = ice_move_all_vsi_to_dflt_agg(pi, agg_info, tc, rm_vsi_info); if (status) goto exit_rm_agg_cfg_tc; /* Delete aggregator node(s) */ status = ice_sched_rm_agg_cfg(pi, agg_info->agg_id, tc); if (status) goto exit_rm_agg_cfg_tc; clear_bit(tc, agg_info->tc_bitmap); exit_rm_agg_cfg_tc: return status; } /** * ice_save_agg_tc_bitmap - save aggregator TC bitmap * @pi: port information structure * @agg_id: aggregator ID * @tc_bitmap: 8 bits TC bitmap * * Save aggregator TC bitmap. This function needs to be called with scheduler * lock held. */ static int ice_save_agg_tc_bitmap(struct ice_port_info *pi, u32 agg_id, unsigned long *tc_bitmap) { struct ice_sched_agg_info *agg_info; agg_info = ice_get_agg_info(pi->hw, agg_id); if (!agg_info) return -EINVAL; bitmap_copy(agg_info->replay_tc_bitmap, tc_bitmap, ICE_MAX_TRAFFIC_CLASS); return 0; } /** * ice_sched_add_agg_cfg - create an aggregator node * @pi: port information structure * @agg_id: aggregator ID * @tc: TC number * * This function creates an aggregator node and intermediate nodes if required * for the given TC */ static int ice_sched_add_agg_cfg(struct ice_port_info *pi, u32 agg_id, u8 tc) { struct ice_sched_node *parent, *agg_node, *tc_node; u16 num_nodes[ICE_AQC_TOPO_MAX_LEVEL_NUM] = { 0 }; struct ice_hw *hw = pi->hw; u32 first_node_teid; u16 num_nodes_added; int status = 0; u8 i, aggl; tc_node = ice_sched_get_tc_node(pi, tc); if (!tc_node) return -EIO; agg_node = ice_sched_get_agg_node(pi, tc_node, agg_id); /* Does Agg node already exist ? */ if (agg_node) return status; aggl = ice_sched_get_agg_layer(hw); /* need one node in Agg layer */ num_nodes[aggl] = 1; /* Check whether the intermediate nodes have space to add the * new aggregator. If they are full, then SW needs to allocate a new * intermediate node on those layers */ for (i = hw->sw_entry_point_layer; i < aggl; i++) { parent = ice_sched_get_first_node(pi, tc_node, i); /* scan all the siblings */ while (parent) { if (parent->num_children < hw->max_children[i]) break; parent = parent->sibling; } /* all the nodes are full, reserve one for this layer */ if (!parent) num_nodes[i]++; } /* add the aggregator node */ parent = tc_node; for (i = hw->sw_entry_point_layer; i <= aggl; i++) { if (!parent) return -EIO; status = ice_sched_add_nodes_to_layer(pi, tc_node, parent, i, num_nodes[i], &first_node_teid, &num_nodes_added); if (status || num_nodes[i] != num_nodes_added) return -EIO; /* The newly added node can be a new parent for the next * layer nodes */ if (num_nodes_added) { parent = ice_sched_find_node_by_teid(tc_node, first_node_teid); /* register aggregator ID with the aggregator node */ if (parent && i == aggl) parent->agg_id = agg_id; } else { parent = parent->children[0]; } } return 0; } /** * ice_sched_cfg_agg - configure aggregator node * @pi: port information structure * @agg_id: aggregator ID * @agg_type: aggregator type queue, VSI, or aggregator group * @tc_bitmap: bits TC bitmap * * It registers a unique aggregator node into scheduler services. It * allows a user to register with a unique ID to track it's resources. * The aggregator type determines if this is a queue group, VSI group * or aggregator group. It then creates the aggregator node(s) for requested * TC(s) or removes an existing aggregator node including its configuration * if indicated via tc_bitmap. Call ice_rm_agg_cfg to release aggregator * resources and remove aggregator ID. * This function needs to be called with scheduler lock held. */ static int ice_sched_cfg_agg(struct ice_port_info *pi, u32 agg_id, enum ice_agg_type agg_type, unsigned long *tc_bitmap) { struct ice_sched_agg_info *agg_info; struct ice_hw *hw = pi->hw; int status = 0; u8 tc; agg_info = ice_get_agg_info(hw, agg_id); if (!agg_info) { /* Create new entry for new aggregator ID */ agg_info = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*agg_info), GFP_KERNEL); if (!agg_info) return -ENOMEM; agg_info->agg_id = agg_id; agg_info->agg_type = agg_type; agg_info->tc_bitmap[0] = 0; /* Initialize the aggregator VSI list head */ INIT_LIST_HEAD(&agg_info->agg_vsi_list); /* Add new entry in aggregator list */ list_add(&agg_info->list_entry, &hw->agg_list); } /* Create aggregator node(s) for requested TC(s) */ ice_for_each_traffic_class(tc) { if (!ice_is_tc_ena(*tc_bitmap, tc)) { /* Delete aggregator cfg TC if it exists previously */ status = ice_rm_agg_cfg_tc(pi, agg_info, tc, false); if (status) break; continue; } /* Check if aggregator node for TC already exists */ if (ice_is_tc_ena(agg_info->tc_bitmap[0], tc)) continue; /* Create new aggregator node for TC */ status = ice_sched_add_agg_cfg(pi, agg_id, tc); if (status) break; /* Save aggregator node's TC information */ set_bit(tc, agg_info->tc_bitmap); } return status; } /** * ice_cfg_agg - config aggregator node * @pi: port information structure * @agg_id: aggregator ID * @agg_type: aggregator type queue, VSI, or aggregator group * @tc_bitmap: bits TC bitmap * * This function configures aggregator node(s). */ int ice_cfg_agg(struct ice_port_info *pi, u32 agg_id, enum ice_agg_type agg_type, u8 tc_bitmap) { unsigned long bitmap = tc_bitmap; int status; mutex_lock(&pi->sched_lock); status = ice_sched_cfg_agg(pi, agg_id, agg_type, &bitmap); if (!status) status = ice_save_agg_tc_bitmap(pi, agg_id, &bitmap); mutex_unlock(&pi->sched_lock); return status; } /** * ice_get_agg_vsi_info - get the aggregator ID * @agg_info: aggregator info * @vsi_handle: software VSI handle * * The function returns aggregator VSI info based on VSI handle. This function * needs to be called with scheduler lock held. */ static struct ice_sched_agg_vsi_info * ice_get_agg_vsi_info(struct ice_sched_agg_info *agg_info, u16 vsi_handle) { struct ice_sched_agg_vsi_info *agg_vsi_info; list_for_each_entry(agg_vsi_info, &agg_info->agg_vsi_list, list_entry) if (agg_vsi_info->vsi_handle == vsi_handle) return agg_vsi_info; return NULL; } /** * ice_get_vsi_agg_info - get the aggregator info of VSI * @hw: pointer to the hardware structure * @vsi_handle: Sw VSI handle * * The function returns aggregator info of VSI represented via vsi_handle. The * VSI has in this case a different aggregator than the default one. This * function needs to be called with scheduler lock held. */ static struct ice_sched_agg_info * ice_get_vsi_agg_info(struct ice_hw *hw, u16 vsi_handle) { struct ice_sched_agg_info *agg_info; list_for_each_entry(agg_info, &hw->agg_list, list_entry) { struct ice_sched_agg_vsi_info *agg_vsi_info; agg_vsi_info = ice_get_agg_vsi_info(agg_info, vsi_handle); if (agg_vsi_info) return agg_info; } return NULL; } /** * ice_save_agg_vsi_tc_bitmap - save aggregator VSI TC bitmap * @pi: port information structure * @agg_id: aggregator ID * @vsi_handle: software VSI handle * @tc_bitmap: TC bitmap of enabled TC(s) * * Save VSI to aggregator TC bitmap. This function needs to call with scheduler * lock held. */ static int ice_save_agg_vsi_tc_bitmap(struct ice_port_info *pi, u32 agg_id, u16 vsi_handle, unsigned long *tc_bitmap) { struct ice_sched_agg_vsi_info *agg_vsi_info; struct ice_sched_agg_info *agg_info; agg_info = ice_get_agg_info(pi->hw, agg_id); if (!agg_info) return -EINVAL; /* check if entry already exist */ agg_vsi_info = ice_get_agg_vsi_info(agg_info, vsi_handle); if (!agg_vsi_info) return -EINVAL; bitmap_copy(agg_vsi_info->replay_tc_bitmap, tc_bitmap, ICE_MAX_TRAFFIC_CLASS); return 0; } /** * ice_sched_assoc_vsi_to_agg - associate/move VSI to new/default aggregator * @pi: port information structure * @agg_id: aggregator ID * @vsi_handle: software VSI handle * @tc_bitmap: TC bitmap of enabled TC(s) * * This function moves VSI to a new or default aggregator node. If VSI is * already associated to the aggregator node then no operation is performed on * the tree. This function needs to be called with scheduler lock held. */ static int ice_sched_assoc_vsi_to_agg(struct ice_port_info *pi, u32 agg_id, u16 vsi_handle, unsigned long *tc_bitmap) { struct ice_sched_agg_vsi_info *agg_vsi_info, *iter, *old_agg_vsi_info = NULL; struct ice_sched_agg_info *agg_info, *old_agg_info; struct ice_hw *hw = pi->hw; int status = 0; u8 tc; if (!ice_is_vsi_valid(pi->hw, vsi_handle)) return -EINVAL; agg_info = ice_get_agg_info(hw, agg_id); if (!agg_info) return -EINVAL; /* If the VSI is already part of another aggregator then update * its VSI info list */ old_agg_info = ice_get_vsi_agg_info(hw, vsi_handle); if (old_agg_info && old_agg_info != agg_info) { struct ice_sched_agg_vsi_info *vtmp; list_for_each_entry_safe(iter, vtmp, &old_agg_info->agg_vsi_list, list_entry) if (iter->vsi_handle == vsi_handle) { old_agg_vsi_info = iter; break; } } /* check if entry already exist */ agg_vsi_info = ice_get_agg_vsi_info(agg_info, vsi_handle); if (!agg_vsi_info) { /* Create new entry for VSI under aggregator list */ agg_vsi_info = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*agg_vsi_info), GFP_KERNEL); if (!agg_vsi_info) return -EINVAL; /* add VSI ID into the aggregator list */ agg_vsi_info->vsi_handle = vsi_handle; list_add(&agg_vsi_info->list_entry, &agg_info->agg_vsi_list); } /* Move VSI node to new aggregator node for requested TC(s) */ ice_for_each_traffic_class(tc) { if (!ice_is_tc_ena(*tc_bitmap, tc)) continue; /* Move VSI to new aggregator */ status = ice_sched_move_vsi_to_agg(pi, vsi_handle, agg_id, tc); if (status) break; set_bit(tc, agg_vsi_info->tc_bitmap); if (old_agg_vsi_info) clear_bit(tc, old_agg_vsi_info->tc_bitmap); } if (old_agg_vsi_info && !old_agg_vsi_info->tc_bitmap[0]) { list_del(&old_agg_vsi_info->list_entry); devm_kfree(ice_hw_to_dev(pi->hw), old_agg_vsi_info); } return status; } /** * ice_sched_rm_unused_rl_prof - remove unused RL profile * @pi: port information structure * * This function removes unused rate limit profiles from the HW and * SW DB. The caller needs to hold scheduler lock. */ static void ice_sched_rm_unused_rl_prof(struct ice_port_info *pi) { u16 ln; for (ln = 0; ln < pi->hw->num_tx_sched_layers; ln++) { struct ice_aqc_rl_profile_info *rl_prof_elem; struct ice_aqc_rl_profile_info *rl_prof_tmp; list_for_each_entry_safe(rl_prof_elem, rl_prof_tmp, &pi->rl_prof_list[ln], list_entry) { if (!ice_sched_del_rl_profile(pi->hw, rl_prof_elem)) ice_debug(pi->hw, ICE_DBG_SCHED, "Removed rl profile\n"); } } } /** * ice_sched_update_elem - update element * @hw: pointer to the HW struct * @node: pointer to node * @info: node info to update * * Update the HW DB, and local SW DB of node. Update the scheduling * parameters of node from argument info data buffer (Info->data buf) and * returns success or error on config sched element failure. The caller * needs to hold scheduler lock. */ static int ice_sched_update_elem(struct ice_hw *hw, struct ice_sched_node *node, struct ice_aqc_txsched_elem_data *info) { struct ice_aqc_txsched_elem_data buf; u16 elem_cfgd = 0; u16 num_elems = 1; int status; buf = *info; /* Parent TEID is reserved field in this aq call */ buf.parent_teid = 0; /* Element type is reserved field in this aq call */ buf.data.elem_type = 0; /* Flags is reserved field in this aq call */ buf.data.flags = 0; /* Update HW DB */ /* Configure element node */ status = ice_aq_cfg_sched_elems(hw, num_elems, &buf, sizeof(buf), &elem_cfgd, NULL); if (status || elem_cfgd != num_elems) { ice_debug(hw, ICE_DBG_SCHED, "Config sched elem error\n"); return -EIO; } /* Config success case */ /* Now update local SW DB */ /* Only copy the data portion of info buffer */ node->info.data = info->data; return status; } /** * ice_sched_cfg_node_bw_alloc - configure node BW weight/alloc params * @hw: pointer to the HW struct * @node: sched node to configure * @rl_type: rate limit type CIR, EIR, or shared * @bw_alloc: BW weight/allocation * * This function configures node element's BW allocation. */ static int ice_sched_cfg_node_bw_alloc(struct ice_hw *hw, struct ice_sched_node *node, enum ice_rl_type rl_type, u16 bw_alloc) { struct ice_aqc_txsched_elem_data buf; struct ice_aqc_txsched_elem *data; buf = node->info; data = &buf.data; if (rl_type == ICE_MIN_BW) { data->valid_sections |= ICE_AQC_ELEM_VALID_CIR; data->cir_bw.bw_alloc = cpu_to_le16(bw_alloc); } else if (rl_type == ICE_MAX_BW) { data->valid_sections |= ICE_AQC_ELEM_VALID_EIR; data->eir_bw.bw_alloc = cpu_to_le16(bw_alloc); } else { return -EINVAL; } /* Configure element */ return ice_sched_update_elem(hw, node, &buf); } /** * ice_move_vsi_to_agg - moves VSI to new or default aggregator * @pi: port information structure * @agg_id: aggregator ID * @vsi_handle: software VSI handle * @tc_bitmap: TC bitmap of enabled TC(s) * * Move or associate VSI to a new or default aggregator node. */ int ice_move_vsi_to_agg(struct ice_port_info *pi, u32 agg_id, u16 vsi_handle, u8 tc_bitmap) { unsigned long bitmap = tc_bitmap; int status; mutex_lock(&pi->sched_lock); status = ice_sched_assoc_vsi_to_agg(pi, agg_id, vsi_handle, (unsigned long *)&bitmap); if (!status) status = ice_save_agg_vsi_tc_bitmap(pi, agg_id, vsi_handle, (unsigned long *)&bitmap); mutex_unlock(&pi->sched_lock); return status; } /** * ice_set_clear_cir_bw - set or clear CIR BW * @bw_t_info: bandwidth type information structure * @bw: bandwidth in Kbps - Kilo bits per sec * * Save or clear CIR bandwidth (BW) in the passed param bw_t_info. */ static void ice_set_clear_cir_bw(struct ice_bw_type_info *bw_t_info, u32 bw) { if (bw == ICE_SCHED_DFLT_BW) { clear_bit(ICE_BW_TYPE_CIR, bw_t_info->bw_t_bitmap); bw_t_info->cir_bw.bw = 0; } else { /* Save type of BW information */ set_bit(ICE_BW_TYPE_CIR, bw_t_info->bw_t_bitmap); bw_t_info->cir_bw.bw = bw; } } /** * ice_set_clear_eir_bw - set or clear EIR BW * @bw_t_info: bandwidth type information structure * @bw: bandwidth in Kbps - Kilo bits per sec * * Save or clear EIR bandwidth (BW) in the passed param bw_t_info. */ static void ice_set_clear_eir_bw(struct ice_bw_type_info *bw_t_info, u32 bw) { if (bw == ICE_SCHED_DFLT_BW) { clear_bit(ICE_BW_TYPE_EIR, bw_t_info->bw_t_bitmap); bw_t_info->eir_bw.bw = 0; } else { /* EIR BW and Shared BW profiles are mutually exclusive and * hence only one of them may be set for any given element. * First clear earlier saved shared BW information. */ clear_bit(ICE_BW_TYPE_SHARED, bw_t_info->bw_t_bitmap); bw_t_info->shared_bw = 0; /* save EIR BW information */ set_bit(ICE_BW_TYPE_EIR, bw_t_info->bw_t_bitmap); bw_t_info->eir_bw.bw = bw; } } /** * ice_set_clear_shared_bw - set or clear shared BW * @bw_t_info: bandwidth type information structure * @bw: bandwidth in Kbps - Kilo bits per sec * * Save or clear shared bandwidth (BW) in the passed param bw_t_info. */ static void ice_set_clear_shared_bw(struct ice_bw_type_info *bw_t_info, u32 bw) { if (bw == ICE_SCHED_DFLT_BW) { clear_bit(ICE_BW_TYPE_SHARED, bw_t_info->bw_t_bitmap); bw_t_info->shared_bw = 0; } else { /* EIR BW and Shared BW profiles are mutually exclusive and * hence only one of them may be set for any given element. * First clear earlier saved EIR BW information. */ clear_bit(ICE_BW_TYPE_EIR, bw_t_info->bw_t_bitmap); bw_t_info->eir_bw.bw = 0; /* save shared BW information */ set_bit(ICE_BW_TYPE_SHARED, bw_t_info->bw_t_bitmap); bw_t_info->shared_bw = bw; } } /** * ice_sched_save_vsi_bw - save VSI node's BW information * @pi: port information structure * @vsi_handle: sw VSI handle * @tc: traffic class * @rl_type: rate limit type min, max, or shared * @bw: bandwidth in Kbps - Kilo bits per sec * * Save BW information of VSI type node for post replay use. */ static int ice_sched_save_vsi_bw(struct ice_port_info *pi, u16 vsi_handle, u8 tc, enum ice_rl_type rl_type, u32 bw) { struct ice_vsi_ctx *vsi_ctx; if (!ice_is_vsi_valid(pi->hw, vsi_handle)) return -EINVAL; vsi_ctx = ice_get_vsi_ctx(pi->hw, vsi_handle); if (!vsi_ctx) return -EINVAL; switch (rl_type) { case ICE_MIN_BW: ice_set_clear_cir_bw(&vsi_ctx->sched.bw_t_info[tc], bw); break; case ICE_MAX_BW: ice_set_clear_eir_bw(&vsi_ctx->sched.bw_t_info[tc], bw); break; case ICE_SHARED_BW: ice_set_clear_shared_bw(&vsi_ctx->sched.bw_t_info[tc], bw); break; default: return -EINVAL; } return 0; } /** * ice_sched_calc_wakeup - calculate RL profile wakeup parameter * @hw: pointer to the HW struct * @bw: bandwidth in Kbps * * This function calculates the wakeup parameter of RL profile. */ static u16 ice_sched_calc_wakeup(struct ice_hw *hw, s32 bw) { s64 bytes_per_sec, wakeup_int, wakeup_a, wakeup_b, wakeup_f; s32 wakeup_f_int; u16 wakeup = 0; /* Get the wakeup integer value */ bytes_per_sec = div64_long(((s64)bw * 1000), BITS_PER_BYTE); wakeup_int = div64_long(hw->psm_clk_freq, bytes_per_sec); if (wakeup_int > 63) { wakeup = (u16)((1 << 15) | wakeup_int); } else { /* Calculate fraction value up to 4 decimals * Convert Integer value to a constant multiplier */ wakeup_b = (s64)ICE_RL_PROF_MULTIPLIER * wakeup_int; wakeup_a = div64_long((s64)ICE_RL_PROF_MULTIPLIER * hw->psm_clk_freq, bytes_per_sec); /* Get Fraction value */ wakeup_f = wakeup_a - wakeup_b; /* Round up the Fractional value via Ceil(Fractional value) */ if (wakeup_f > div64_long(ICE_RL_PROF_MULTIPLIER, 2)) wakeup_f += 1; wakeup_f_int = (s32)div64_long(wakeup_f * ICE_RL_PROF_FRACTION, ICE_RL_PROF_MULTIPLIER); wakeup |= (u16)(wakeup_int << 9); wakeup |= (u16)(0x1ff & wakeup_f_int); } return wakeup; } /** * ice_sched_bw_to_rl_profile - convert BW to profile parameters * @hw: pointer to the HW struct * @bw: bandwidth in Kbps * @profile: profile parameters to return * * This function converts the BW to profile structure format. */ static int ice_sched_bw_to_rl_profile(struct ice_hw *hw, u32 bw, struct ice_aqc_rl_profile_elem *profile) { s64 bytes_per_sec, ts_rate, mv_tmp; int status = -EINVAL; bool found = false; s32 encode = 0; s64 mv = 0; s32 i; /* Bw settings range is from 0.5Mb/sec to 100Gb/sec */ if (bw < ICE_SCHED_MIN_BW || bw > ICE_SCHED_MAX_BW) return status; /* Bytes per second from Kbps */ bytes_per_sec = div64_long(((s64)bw * 1000), BITS_PER_BYTE); /* encode is 6 bits but really useful are 5 bits */ for (i = 0; i < 64; i++) { u64 pow_result = BIT_ULL(i); ts_rate = div64_long((s64)hw->psm_clk_freq, pow_result * ICE_RL_PROF_TS_MULTIPLIER); if (ts_rate <= 0) continue; /* Multiplier value */ mv_tmp = div64_long(bytes_per_sec * ICE_RL_PROF_MULTIPLIER, ts_rate); /* Round to the nearest ICE_RL_PROF_MULTIPLIER */ mv = round_up_64bit(mv_tmp, ICE_RL_PROF_MULTIPLIER); /* First multiplier value greater than the given * accuracy bytes */ if (mv > ICE_RL_PROF_ACCURACY_BYTES) { encode = i; found = true; break; } } if (found) { u16 wm; wm = ice_sched_calc_wakeup(hw, bw); profile->rl_multiply = cpu_to_le16(mv); profile->wake_up_calc = cpu_to_le16(wm); profile->rl_encode = cpu_to_le16(encode); status = 0; } else { status = -ENOENT; } return status; } /** * ice_sched_add_rl_profile - add RL profile * @pi: port information structure * @rl_type: type of rate limit BW - min, max, or shared * @bw: bandwidth in Kbps - Kilo bits per sec * @layer_num: specifies in which layer to create profile * * This function first checks the existing list for corresponding BW * parameter. If it exists, it returns the associated profile otherwise * it creates a new rate limit profile for requested BW, and adds it to * the HW DB and local list. It returns the new profile or null on error. * The caller needs to hold the scheduler lock. */ static struct ice_aqc_rl_profile_info * ice_sched_add_rl_profile(struct ice_port_info *pi, enum ice_rl_type rl_type, u32 bw, u8 layer_num) { struct ice_aqc_rl_profile_info *rl_prof_elem; u16 profiles_added = 0, num_profiles = 1; struct ice_aqc_rl_profile_elem *buf; struct ice_hw *hw; u8 profile_type; int status; if (layer_num >= ICE_AQC_TOPO_MAX_LEVEL_NUM) return NULL; switch (rl_type) { case ICE_MIN_BW: profile_type = ICE_AQC_RL_PROFILE_TYPE_CIR; break; case ICE_MAX_BW: profile_type = ICE_AQC_RL_PROFILE_TYPE_EIR; break; case ICE_SHARED_BW: profile_type = ICE_AQC_RL_PROFILE_TYPE_SRL; break; default: return NULL; } if (!pi) return NULL; hw = pi->hw; list_for_each_entry(rl_prof_elem, &pi->rl_prof_list[layer_num], list_entry) if ((rl_prof_elem->profile.flags & ICE_AQC_RL_PROFILE_TYPE_M) == profile_type && rl_prof_elem->bw == bw) /* Return existing profile ID info */ return rl_prof_elem; /* Create new profile ID */ rl_prof_elem = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*rl_prof_elem), GFP_KERNEL); if (!rl_prof_elem) return NULL; status = ice_sched_bw_to_rl_profile(hw, bw, &rl_prof_elem->profile); if (status) goto exit_add_rl_prof; rl_prof_elem->bw = bw; /* layer_num is zero relative, and fw expects level from 1 to 9 */ rl_prof_elem->profile.level = layer_num + 1; rl_prof_elem->profile.flags = profile_type; rl_prof_elem->profile.max_burst_size = cpu_to_le16(hw->max_burst_size); /* Create new entry in HW DB */ buf = &rl_prof_elem->profile; status = ice_aq_add_rl_profile(hw, num_profiles, buf, sizeof(*buf), &profiles_added, NULL); if (status || profiles_added != num_profiles) goto exit_add_rl_prof; /* Good entry - add in the list */ rl_prof_elem->prof_id_ref = 0; list_add(&rl_prof_elem->list_entry, &pi->rl_prof_list[layer_num]); return rl_prof_elem; exit_add_rl_prof: devm_kfree(ice_hw_to_dev(hw), rl_prof_elem); return NULL; } /** * ice_sched_cfg_node_bw_lmt - configure node sched params * @hw: pointer to the HW struct * @node: sched node to configure * @rl_type: rate limit type CIR, EIR, or shared * @rl_prof_id: rate limit profile ID * * This function configures node element's BW limit. */ static int ice_sched_cfg_node_bw_lmt(struct ice_hw *hw, struct ice_sched_node *node, enum ice_rl_type rl_type, u16 rl_prof_id) { struct ice_aqc_txsched_elem_data buf; struct ice_aqc_txsched_elem *data; buf = node->info; data = &buf.data; switch (rl_type) { case ICE_MIN_BW: data->valid_sections |= ICE_AQC_ELEM_VALID_CIR; data->cir_bw.bw_profile_idx = cpu_to_le16(rl_prof_id); break; case ICE_MAX_BW: /* EIR BW and Shared BW profiles are mutually exclusive and * hence only one of them may be set for any given element */ if (data->valid_sections & ICE_AQC_ELEM_VALID_SHARED) return -EIO; data->valid_sections |= ICE_AQC_ELEM_VALID_EIR; data->eir_bw.bw_profile_idx = cpu_to_le16(rl_prof_id); break; case ICE_SHARED_BW: /* Check for removing shared BW */ if (rl_prof_id == ICE_SCHED_NO_SHARED_RL_PROF_ID) { /* remove shared profile */ data->valid_sections &= ~ICE_AQC_ELEM_VALID_SHARED; data->srl_id = 0; /* clear SRL field */ /* enable back EIR to default profile */ data->valid_sections |= ICE_AQC_ELEM_VALID_EIR; data->eir_bw.bw_profile_idx = cpu_to_le16(ICE_SCHED_DFLT_RL_PROF_ID); break; } /* EIR BW and Shared BW profiles are mutually exclusive and * hence only one of them may be set for any given element */ if ((data->valid_sections & ICE_AQC_ELEM_VALID_EIR) && (le16_to_cpu(data->eir_bw.bw_profile_idx) != ICE_SCHED_DFLT_RL_PROF_ID)) return -EIO; /* EIR BW is set to default, disable it */ data->valid_sections &= ~ICE_AQC_ELEM_VALID_EIR; /* Okay to enable shared BW now */ data->valid_sections |= ICE_AQC_ELEM_VALID_SHARED; data->srl_id = cpu_to_le16(rl_prof_id); break; default: /* Unknown rate limit type */ return -EINVAL; } /* Configure element */ return ice_sched_update_elem(hw, node, &buf); } /** * ice_sched_get_node_rl_prof_id - get node's rate limit profile ID * @node: sched node * @rl_type: rate limit type * * If existing profile matches, it returns the corresponding rate * limit profile ID, otherwise it returns an invalid ID as error. */ static u16 ice_sched_get_node_rl_prof_id(struct ice_sched_node *node, enum ice_rl_type rl_type) { u16 rl_prof_id = ICE_SCHED_INVAL_PROF_ID; struct ice_aqc_txsched_elem *data; data = &node->info.data; switch (rl_type) { case ICE_MIN_BW: if (data->valid_sections & ICE_AQC_ELEM_VALID_CIR) rl_prof_id = le16_to_cpu(data->cir_bw.bw_profile_idx); break; case ICE_MAX_BW: if (data->valid_sections & ICE_AQC_ELEM_VALID_EIR) rl_prof_id = le16_to_cpu(data->eir_bw.bw_profile_idx); break; case ICE_SHARED_BW: if (data->valid_sections & ICE_AQC_ELEM_VALID_SHARED) rl_prof_id = le16_to_cpu(data->srl_id); break; default: break; } return rl_prof_id; } /** * ice_sched_get_rl_prof_layer - selects rate limit profile creation layer * @pi: port information structure * @rl_type: type of rate limit BW - min, max, or shared * @layer_index: layer index * * This function returns requested profile creation layer. */ static u8 ice_sched_get_rl_prof_layer(struct ice_port_info *pi, enum ice_rl_type rl_type, u8 layer_index) { struct ice_hw *hw = pi->hw; if (layer_index >= hw->num_tx_sched_layers) return ICE_SCHED_INVAL_LAYER_NUM; switch (rl_type) { case ICE_MIN_BW: if (hw->layer_info[layer_index].max_cir_rl_profiles) return layer_index; break; case ICE_MAX_BW: if (hw->layer_info[layer_index].max_eir_rl_profiles) return layer_index; break; case ICE_SHARED_BW: /* if current layer doesn't support SRL profile creation * then try a layer up or down. */ if (hw->layer_info[layer_index].max_srl_profiles) return layer_index; else if (layer_index < hw->num_tx_sched_layers - 1 && hw->layer_info[layer_index + 1].max_srl_profiles) return layer_index + 1; else if (layer_index > 0 && hw->layer_info[layer_index - 1].max_srl_profiles) return layer_index - 1; break; default: break; } return ICE_SCHED_INVAL_LAYER_NUM; } /** * ice_sched_get_srl_node - get shared rate limit node * @node: tree node * @srl_layer: shared rate limit layer * * This function returns SRL node to be used for shared rate limit purpose. * The caller needs to hold scheduler lock. */ static struct ice_sched_node * ice_sched_get_srl_node(struct ice_sched_node *node, u8 srl_layer) { if (srl_layer > node->tx_sched_layer) return node->children[0]; else if (srl_layer < node->tx_sched_layer) /* Node can't be created without a parent. It will always * have a valid parent except root node. */ return node->parent; else return node; } /** * ice_sched_rm_rl_profile - remove RL profile ID * @pi: port information structure * @layer_num: layer number where profiles are saved * @profile_type: profile type like EIR, CIR, or SRL * @profile_id: profile ID to remove * * This function removes rate limit profile from layer 'layer_num' of type * 'profile_type' and profile ID as 'profile_id'. The caller needs to hold * scheduler lock. */ static int ice_sched_rm_rl_profile(struct ice_port_info *pi, u8 layer_num, u8 profile_type, u16 profile_id) { struct ice_aqc_rl_profile_info *rl_prof_elem; int status = 0; if (layer_num >= ICE_AQC_TOPO_MAX_LEVEL_NUM) return -EINVAL; /* Check the existing list for RL profile */ list_for_each_entry(rl_prof_elem, &pi->rl_prof_list[layer_num], list_entry) if ((rl_prof_elem->profile.flags & ICE_AQC_RL_PROFILE_TYPE_M) == profile_type && le16_to_cpu(rl_prof_elem->profile.profile_id) == profile_id) { if (rl_prof_elem->prof_id_ref) rl_prof_elem->prof_id_ref--; /* Remove old profile ID from database */ status = ice_sched_del_rl_profile(pi->hw, rl_prof_elem); if (status && status != -EBUSY) ice_debug(pi->hw, ICE_DBG_SCHED, "Remove rl profile failed\n"); break; } if (status == -EBUSY) status = 0; return status; } /** * ice_sched_set_node_bw_dflt - set node's bandwidth limit to default * @pi: port information structure * @node: pointer to node structure * @rl_type: rate limit type min, max, or shared * @layer_num: layer number where RL profiles are saved * * This function configures node element's BW rate limit profile ID of * type CIR, EIR, or SRL to default. This function needs to be called * with the scheduler lock held. */ static int ice_sched_set_node_bw_dflt(struct ice_port_info *pi, struct ice_sched_node *node, enum ice_rl_type rl_type, u8 layer_num) { struct ice_hw *hw; u8 profile_type; u16 rl_prof_id; u16 old_id; int status; hw = pi->hw; switch (rl_type) { case ICE_MIN_BW: profile_type = ICE_AQC_RL_PROFILE_TYPE_CIR; rl_prof_id = ICE_SCHED_DFLT_RL_PROF_ID; break; case ICE_MAX_BW: profile_type = ICE_AQC_RL_PROFILE_TYPE_EIR; rl_prof_id = ICE_SCHED_DFLT_RL_PROF_ID; break; case ICE_SHARED_BW: profile_type = ICE_AQC_RL_PROFILE_TYPE_SRL; /* No SRL is configured for default case */ rl_prof_id = ICE_SCHED_NO_SHARED_RL_PROF_ID; break; default: return -EINVAL; } /* Save existing RL prof ID for later clean up */ old_id = ice_sched_get_node_rl_prof_id(node, rl_type); /* Configure BW scheduling parameters */ status = ice_sched_cfg_node_bw_lmt(hw, node, rl_type, rl_prof_id); if (status) return status; /* Remove stale RL profile ID */ if (old_id == ICE_SCHED_DFLT_RL_PROF_ID || old_id == ICE_SCHED_INVAL_PROF_ID) return 0; return ice_sched_rm_rl_profile(pi, layer_num, profile_type, old_id); } /** * ice_sched_set_eir_srl_excl - set EIR/SRL exclusiveness * @pi: port information structure * @node: pointer to node structure * @layer_num: layer number where rate limit profiles are saved * @rl_type: rate limit type min, max, or shared * @bw: bandwidth value * * This function prepares node element's bandwidth to SRL or EIR exclusively. * EIR BW and Shared BW profiles are mutually exclusive and hence only one of * them may be set for any given element. This function needs to be called * with the scheduler lock held. */ static int ice_sched_set_eir_srl_excl(struct ice_port_info *pi, struct ice_sched_node *node, u8 layer_num, enum ice_rl_type rl_type, u32 bw) { if (rl_type == ICE_SHARED_BW) { /* SRL node passed in this case, it may be different node */ if (bw == ICE_SCHED_DFLT_BW) /* SRL being removed, ice_sched_cfg_node_bw_lmt() * enables EIR to default. EIR is not set in this * case, so no additional action is required. */ return 0; /* SRL being configured, set EIR to default here. * ice_sched_cfg_node_bw_lmt() disables EIR when it * configures SRL */ return ice_sched_set_node_bw_dflt(pi, node, ICE_MAX_BW, layer_num); } else if (rl_type == ICE_MAX_BW && node->info.data.valid_sections & ICE_AQC_ELEM_VALID_SHARED) { /* Remove Shared profile. Set default shared BW call * removes shared profile for a node. */ return ice_sched_set_node_bw_dflt(pi, node, ICE_SHARED_BW, layer_num); } return 0; } /** * ice_sched_set_node_bw - set node's bandwidth * @pi: port information structure * @node: tree node * @rl_type: rate limit type min, max, or shared * @bw: bandwidth in Kbps - Kilo bits per sec * @layer_num: layer number * * This function adds new profile corresponding to requested BW, configures * node's RL profile ID of type CIR, EIR, or SRL, and removes old profile * ID from local database. The caller needs to hold scheduler lock. */ int ice_sched_set_node_bw(struct ice_port_info *pi, struct ice_sched_node *node, enum ice_rl_type rl_type, u32 bw, u8 layer_num) { struct ice_aqc_rl_profile_info *rl_prof_info; struct ice_hw *hw = pi->hw; u16 old_id, rl_prof_id; int status = -EINVAL; rl_prof_info = ice_sched_add_rl_profile(pi, rl_type, bw, layer_num); if (!rl_prof_info) return status; rl_prof_id = le16_to_cpu(rl_prof_info->profile.profile_id); /* Save existing RL prof ID for later clean up */ old_id = ice_sched_get_node_rl_prof_id(node, rl_type); /* Configure BW scheduling parameters */ status = ice_sched_cfg_node_bw_lmt(hw, node, rl_type, rl_prof_id); if (status) return status; /* New changes has been applied */ /* Increment the profile ID reference count */ rl_prof_info->prof_id_ref++; /* Check for old ID removal */ if ((old_id == ICE_SCHED_DFLT_RL_PROF_ID && rl_type != ICE_SHARED_BW) || old_id == ICE_SCHED_INVAL_PROF_ID || old_id == rl_prof_id) return 0; return ice_sched_rm_rl_profile(pi, layer_num, rl_prof_info->profile.flags & ICE_AQC_RL_PROFILE_TYPE_M, old_id); } /** * ice_sched_set_node_priority - set node's priority * @pi: port information structure * @node: tree node * @priority: number 0-7 representing priority among siblings * * This function sets priority of a node among it's siblings. */ int ice_sched_set_node_priority(struct ice_port_info *pi, struct ice_sched_node *node, u16 priority) { struct ice_aqc_txsched_elem_data buf; struct ice_aqc_txsched_elem *data; buf = node->info; data = &buf.data; data->valid_sections |= ICE_AQC_ELEM_VALID_GENERIC; data->generic |= FIELD_PREP(ICE_AQC_ELEM_GENERIC_PRIO_M, priority); return ice_sched_update_elem(pi->hw, node, &buf); } /** * ice_sched_set_node_weight - set node's weight * @pi: port information structure * @node: tree node * @weight: number 1-200 representing weight for WFQ * * This function sets weight of the node for WFQ algorithm. */ int ice_sched_set_node_weight(struct ice_port_info *pi, struct ice_sched_node *node, u16 weight) { struct ice_aqc_txsched_elem_data buf; struct ice_aqc_txsched_elem *data; buf = node->info; data = &buf.data; data->valid_sections = ICE_AQC_ELEM_VALID_CIR | ICE_AQC_ELEM_VALID_EIR | ICE_AQC_ELEM_VALID_GENERIC; data->cir_bw.bw_alloc = cpu_to_le16(weight); data->eir_bw.bw_alloc = cpu_to_le16(weight); data->generic |= FIELD_PREP(ICE_AQC_ELEM_GENERIC_SP_M, 0x0); return ice_sched_update_elem(pi->hw, node, &buf); } /** * ice_sched_set_node_bw_lmt - set node's BW limit * @pi: port information structure * @node: tree node * @rl_type: rate limit type min, max, or shared * @bw: bandwidth in Kbps - Kilo bits per sec * * It updates node's BW limit parameters like BW RL profile ID of type CIR, * EIR, or SRL. The caller needs to hold scheduler lock. */ int ice_sched_set_node_bw_lmt(struct ice_port_info *pi, struct ice_sched_node *node, enum ice_rl_type rl_type, u32 bw) { struct ice_sched_node *cfg_node = node; int status; struct ice_hw *hw; u8 layer_num; if (!pi) return -EINVAL; hw = pi->hw; /* Remove unused RL profile IDs from HW and SW DB */ ice_sched_rm_unused_rl_prof(pi); layer_num = ice_sched_get_rl_prof_layer(pi, rl_type, node->tx_sched_layer); if (layer_num >= hw->num_tx_sched_layers) return -EINVAL; if (rl_type == ICE_SHARED_BW) { /* SRL node may be different */ cfg_node = ice_sched_get_srl_node(node, layer_num); if (!cfg_node) return -EIO; } /* EIR BW and Shared BW profiles are mutually exclusive and * hence only one of them may be set for any given element */ status = ice_sched_set_eir_srl_excl(pi, cfg_node, layer_num, rl_type, bw); if (status) return status; if (bw == ICE_SCHED_DFLT_BW) return ice_sched_set_node_bw_dflt(pi, cfg_node, rl_type, layer_num); return ice_sched_set_node_bw(pi, cfg_node, rl_type, bw, layer_num); } /** * ice_sched_set_node_bw_dflt_lmt - set node's BW limit to default * @pi: port information structure * @node: pointer to node structure * @rl_type: rate limit type min, max, or shared * * This function configures node element's BW rate limit profile ID of * type CIR, EIR, or SRL to default. This function needs to be called * with the scheduler lock held. */ static int ice_sched_set_node_bw_dflt_lmt(struct ice_port_info *pi, struct ice_sched_node *node, enum ice_rl_type rl_type) { return ice_sched_set_node_bw_lmt(pi, node, rl_type, ICE_SCHED_DFLT_BW); } /** * ice_sched_validate_srl_node - Check node for SRL applicability * @node: sched node to configure * @sel_layer: selected SRL layer * * This function checks if the SRL can be applied to a selected layer node on * behalf of the requested node (first argument). This function needs to be * called with scheduler lock held. */ static int ice_sched_validate_srl_node(struct ice_sched_node *node, u8 sel_layer) { /* SRL profiles are not available on all layers. Check if the * SRL profile can be applied to a node above or below the * requested node. SRL configuration is possible only if the * selected layer's node has single child. */ if (sel_layer == node->tx_sched_layer || ((sel_layer == node->tx_sched_layer + 1) && node->num_children == 1) || ((sel_layer == node->tx_sched_layer - 1) && (node->parent && node->parent->num_children == 1))) return 0; return -EIO; } /** * ice_sched_save_q_bw - save queue node's BW information * @q_ctx: queue context structure * @rl_type: rate limit type min, max, or shared * @bw: bandwidth in Kbps - Kilo bits per sec * * Save BW information of queue type node for post replay use. */ static int ice_sched_save_q_bw(struct ice_q_ctx *q_ctx, enum ice_rl_type rl_type, u32 bw) { switch (rl_type) { case ICE_MIN_BW: ice_set_clear_cir_bw(&q_ctx->bw_t_info, bw); break; case ICE_MAX_BW: ice_set_clear_eir_bw(&q_ctx->bw_t_info, bw); break; case ICE_SHARED_BW: ice_set_clear_shared_bw(&q_ctx->bw_t_info, bw); break; default: return -EINVAL; } return 0; } /** * ice_sched_set_q_bw_lmt - sets queue BW limit * @pi: port information structure * @vsi_handle: sw VSI handle * @tc: traffic class * @q_handle: software queue handle * @rl_type: min, max, or shared * @bw: bandwidth in Kbps * * This function sets BW limit of queue scheduling node. */ static int ice_sched_set_q_bw_lmt(struct ice_port_info *pi, u16 vsi_handle, u8 tc, u16 q_handle, enum ice_rl_type rl_type, u32 bw) { struct ice_sched_node *node; struct ice_q_ctx *q_ctx; int status = -EINVAL; if (!ice_is_vsi_valid(pi->hw, vsi_handle)) return -EINVAL; mutex_lock(&pi->sched_lock); q_ctx = ice_get_lan_q_ctx(pi->hw, vsi_handle, tc, q_handle); if (!q_ctx) goto exit_q_bw_lmt; node = ice_sched_find_node_by_teid(pi->root, q_ctx->q_teid); if (!node) { ice_debug(pi->hw, ICE_DBG_SCHED, "Wrong q_teid\n"); goto exit_q_bw_lmt; } /* Return error if it is not a leaf node */ if (node->info.data.elem_type != ICE_AQC_ELEM_TYPE_LEAF) goto exit_q_bw_lmt; /* SRL bandwidth layer selection */ if (rl_type == ICE_SHARED_BW) { u8 sel_layer; /* selected layer */ sel_layer = ice_sched_get_rl_prof_layer(pi, rl_type, node->tx_sched_layer); if (sel_layer >= pi->hw->num_tx_sched_layers) { status = -EINVAL; goto exit_q_bw_lmt; } status = ice_sched_validate_srl_node(node, sel_layer); if (status) goto exit_q_bw_lmt; } if (bw == ICE_SCHED_DFLT_BW) status = ice_sched_set_node_bw_dflt_lmt(pi, node, rl_type); else status = ice_sched_set_node_bw_lmt(pi, node, rl_type, bw); if (!status) status = ice_sched_save_q_bw(q_ctx, rl_type, bw); exit_q_bw_lmt: mutex_unlock(&pi->sched_lock); return status; } /** * ice_cfg_q_bw_lmt - configure queue BW limit * @pi: port information structure * @vsi_handle: sw VSI handle * @tc: traffic class * @q_handle: software queue handle * @rl_type: min, max, or shared * @bw: bandwidth in Kbps * * This function configures BW limit of queue scheduling node. */ int ice_cfg_q_bw_lmt(struct ice_port_info *pi, u16 vsi_handle, u8 tc, u16 q_handle, enum ice_rl_type rl_type, u32 bw) { return ice_sched_set_q_bw_lmt(pi, vsi_handle, tc, q_handle, rl_type, bw); } /** * ice_cfg_q_bw_dflt_lmt - configure queue BW default limit * @pi: port information structure * @vsi_handle: sw VSI handle * @tc: traffic class * @q_handle: software queue handle * @rl_type: min, max, or shared * * This function configures BW default limit of queue scheduling node. */ int ice_cfg_q_bw_dflt_lmt(struct ice_port_info *pi, u16 vsi_handle, u8 tc, u16 q_handle, enum ice_rl_type rl_type) { return ice_sched_set_q_bw_lmt(pi, vsi_handle, tc, q_handle, rl_type, ICE_SCHED_DFLT_BW); } /** * ice_sched_get_node_by_id_type - get node from ID type * @pi: port information structure * @id: identifier * @agg_type: type of aggregator * @tc: traffic class * * This function returns node identified by ID of type aggregator, and * based on traffic class (TC). This function needs to be called with * the scheduler lock held. */ static struct ice_sched_node * ice_sched_get_node_by_id_type(struct ice_port_info *pi, u32 id, enum ice_agg_type agg_type, u8 tc) { struct ice_sched_node *node = NULL; switch (agg_type) { case ICE_AGG_TYPE_VSI: { struct ice_vsi_ctx *vsi_ctx; u16 vsi_handle = (u16)id; if (!ice_is_vsi_valid(pi->hw, vsi_handle)) break; /* Get sched_vsi_info */ vsi_ctx = ice_get_vsi_ctx(pi->hw, vsi_handle); if (!vsi_ctx) break; node = vsi_ctx->sched.vsi_node[tc]; break; } case ICE_AGG_TYPE_AGG: { struct ice_sched_node *tc_node; tc_node = ice_sched_get_tc_node(pi, tc); if (tc_node) node = ice_sched_get_agg_node(pi, tc_node, id); break; } default: break; } return node; } /** * ice_sched_set_node_bw_lmt_per_tc - set node BW limit per TC * @pi: port information structure * @id: ID (software VSI handle or AGG ID) * @agg_type: aggregator type (VSI or AGG type node) * @tc: traffic class * @rl_type: min or max * @bw: bandwidth in Kbps * * This function sets BW limit of VSI or Aggregator scheduling node * based on TC information from passed in argument BW. */ static int ice_sched_set_node_bw_lmt_per_tc(struct ice_port_info *pi, u32 id, enum ice_agg_type agg_type, u8 tc, enum ice_rl_type rl_type, u32 bw) { struct ice_sched_node *node; int status = -EINVAL; if (!pi) return status; if (rl_type == ICE_UNKNOWN_BW) return status; mutex_lock(&pi->sched_lock); node = ice_sched_get_node_by_id_type(pi, id, agg_type, tc); if (!node) { ice_debug(pi->hw, ICE_DBG_SCHED, "Wrong id, agg type, or tc\n"); goto exit_set_node_bw_lmt_per_tc; } if (bw == ICE_SCHED_DFLT_BW) status = ice_sched_set_node_bw_dflt_lmt(pi, node, rl_type); else status = ice_sched_set_node_bw_lmt(pi, node, rl_type, bw); exit_set_node_bw_lmt_per_tc: mutex_unlock(&pi->sched_lock); return status; } /** * ice_cfg_vsi_bw_lmt_per_tc - configure VSI BW limit per TC * @pi: port information structure * @vsi_handle: software VSI handle * @tc: traffic class * @rl_type: min or max * @bw: bandwidth in Kbps * * This function configures BW limit of VSI scheduling node based on TC * information. */ int ice_cfg_vsi_bw_lmt_per_tc(struct ice_port_info *pi, u16 vsi_handle, u8 tc, enum ice_rl_type rl_type, u32 bw) { int status; status = ice_sched_set_node_bw_lmt_per_tc(pi, vsi_handle, ICE_AGG_TYPE_VSI, tc, rl_type, bw); if (!status) { mutex_lock(&pi->sched_lock); status = ice_sched_save_vsi_bw(pi, vsi_handle, tc, rl_type, bw); mutex_unlock(&pi->sched_lock); } return status; } /** * ice_cfg_vsi_bw_dflt_lmt_per_tc - configure default VSI BW limit per TC * @pi: port information structure * @vsi_handle: software VSI handle * @tc: traffic class * @rl_type: min or max * * This function configures default BW limit of VSI scheduling node based on TC * information. */ int ice_cfg_vsi_bw_dflt_lmt_per_tc(struct ice_port_info *pi, u16 vsi_handle, u8 tc, enum ice_rl_type rl_type) { int status; status = ice_sched_set_node_bw_lmt_per_tc(pi, vsi_handle, ICE_AGG_TYPE_VSI, tc, rl_type, ICE_SCHED_DFLT_BW); if (!status) { mutex_lock(&pi->sched_lock); status = ice_sched_save_vsi_bw(pi, vsi_handle, tc, rl_type, ICE_SCHED_DFLT_BW); mutex_unlock(&pi->sched_lock); } return status; } /** * ice_cfg_rl_burst_size - Set burst size value * @hw: pointer to the HW struct * @bytes: burst size in bytes * * This function configures/set the burst size to requested new value. The new * burst size value is used for future rate limit calls. It doesn't change the * existing or previously created RL profiles. */ int ice_cfg_rl_burst_size(struct ice_hw *hw, u32 bytes) { u16 burst_size_to_prog; if (bytes < ICE_MIN_BURST_SIZE_ALLOWED || bytes > ICE_MAX_BURST_SIZE_ALLOWED) return -EINVAL; if (ice_round_to_num(bytes, 64) <= ICE_MAX_BURST_SIZE_64_BYTE_GRANULARITY) { /* 64 byte granularity case */ /* Disable MSB granularity bit */ burst_size_to_prog = ICE_64_BYTE_GRANULARITY; /* round number to nearest 64 byte granularity */ bytes = ice_round_to_num(bytes, 64); /* The value is in 64 byte chunks */ burst_size_to_prog |= (u16)(bytes / 64); } else { /* k bytes granularity case */ /* Enable MSB granularity bit */ burst_size_to_prog = ICE_KBYTE_GRANULARITY; /* round number to nearest 1024 granularity */ bytes = ice_round_to_num(bytes, 1024); /* check rounding doesn't go beyond allowed */ if (bytes > ICE_MAX_BURST_SIZE_KBYTE_GRANULARITY) bytes = ICE_MAX_BURST_SIZE_KBYTE_GRANULARITY; /* The value is in k bytes */ burst_size_to_prog |= (u16)(bytes / 1024); } hw->max_burst_size = burst_size_to_prog; return 0; } /** * ice_sched_replay_node_prio - re-configure node priority * @hw: pointer to the HW struct * @node: sched node to configure * @priority: priority value * * This function configures node element's priority value. It * needs to be called with scheduler lock held. */ static int ice_sched_replay_node_prio(struct ice_hw *hw, struct ice_sched_node *node, u8 priority) { struct ice_aqc_txsched_elem_data buf; struct ice_aqc_txsched_elem *data; int status; buf = node->info; data = &buf.data; data->valid_sections |= ICE_AQC_ELEM_VALID_GENERIC; data->generic = priority; /* Configure element */ status = ice_sched_update_elem(hw, node, &buf); return status; } /** * ice_sched_replay_node_bw - replay node(s) BW * @hw: pointer to the HW struct * @node: sched node to configure * @bw_t_info: BW type information * * This function restores node's BW from bw_t_info. The caller needs * to hold the scheduler lock. */ static int ice_sched_replay_node_bw(struct ice_hw *hw, struct ice_sched_node *node, struct ice_bw_type_info *bw_t_info) { struct ice_port_info *pi = hw->port_info; int status = -EINVAL; u16 bw_alloc; if (!node) return status; if (bitmap_empty(bw_t_info->bw_t_bitmap, ICE_BW_TYPE_CNT)) return 0; if (test_bit(ICE_BW_TYPE_PRIO, bw_t_info->bw_t_bitmap)) { status = ice_sched_replay_node_prio(hw, node, bw_t_info->generic); if (status) return status; } if (test_bit(ICE_BW_TYPE_CIR, bw_t_info->bw_t_bitmap)) { status = ice_sched_set_node_bw_lmt(pi, node, ICE_MIN_BW, bw_t_info->cir_bw.bw); if (status) return status; } if (test_bit(ICE_BW_TYPE_CIR_WT, bw_t_info->bw_t_bitmap)) { bw_alloc = bw_t_info->cir_bw.bw_alloc; status = ice_sched_cfg_node_bw_alloc(hw, node, ICE_MIN_BW, bw_alloc); if (status) return status; } if (test_bit(ICE_BW_TYPE_EIR, bw_t_info->bw_t_bitmap)) { status = ice_sched_set_node_bw_lmt(pi, node, ICE_MAX_BW, bw_t_info->eir_bw.bw); if (status) return status; } if (test_bit(ICE_BW_TYPE_EIR_WT, bw_t_info->bw_t_bitmap)) { bw_alloc = bw_t_info->eir_bw.bw_alloc; status = ice_sched_cfg_node_bw_alloc(hw, node, ICE_MAX_BW, bw_alloc); if (status) return status; } if (test_bit(ICE_BW_TYPE_SHARED, bw_t_info->bw_t_bitmap)) status = ice_sched_set_node_bw_lmt(pi, node, ICE_SHARED_BW, bw_t_info->shared_bw); return status; } /** * ice_sched_get_ena_tc_bitmap - get enabled TC bitmap * @pi: port info struct * @tc_bitmap: 8 bits TC bitmap to check * @ena_tc_bitmap: 8 bits enabled TC bitmap to return * * This function returns enabled TC bitmap in variable ena_tc_bitmap. Some TCs * may be missing, it returns enabled TCs. This function needs to be called with * scheduler lock held. */ static void ice_sched_get_ena_tc_bitmap(struct ice_port_info *pi, unsigned long *tc_bitmap, unsigned long *ena_tc_bitmap) { u8 tc; /* Some TC(s) may be missing after reset, adjust for replay */ ice_for_each_traffic_class(tc) if (ice_is_tc_ena(*tc_bitmap, tc) && (ice_sched_get_tc_node(pi, tc))) set_bit(tc, ena_tc_bitmap); } /** * ice_sched_replay_agg - recreate aggregator node(s) * @hw: pointer to the HW struct * * This function recreate aggregator type nodes which are not replayed earlier. * It also replay aggregator BW information. These aggregator nodes are not * associated with VSI type node yet. */ void ice_sched_replay_agg(struct ice_hw *hw) { struct ice_port_info *pi = hw->port_info; struct ice_sched_agg_info *agg_info; mutex_lock(&pi->sched_lock); list_for_each_entry(agg_info, &hw->agg_list, list_entry) /* replay aggregator (re-create aggregator node) */ if (!bitmap_equal(agg_info->tc_bitmap, agg_info->replay_tc_bitmap, ICE_MAX_TRAFFIC_CLASS)) { DECLARE_BITMAP(replay_bitmap, ICE_MAX_TRAFFIC_CLASS); int status; bitmap_zero(replay_bitmap, ICE_MAX_TRAFFIC_CLASS); ice_sched_get_ena_tc_bitmap(pi, agg_info->replay_tc_bitmap, replay_bitmap); status = ice_sched_cfg_agg(hw->port_info, agg_info->agg_id, ICE_AGG_TYPE_AGG, replay_bitmap); if (status) { dev_info(ice_hw_to_dev(hw), "Replay agg id[%d] failed\n", agg_info->agg_id); /* Move on to next one */ continue; } } mutex_unlock(&pi->sched_lock); } /** * ice_sched_replay_agg_vsi_preinit - Agg/VSI replay pre initialization * @hw: pointer to the HW struct * * This function initialize aggregator(s) TC bitmap to zero. A required * preinit step for replaying aggregators. */ void ice_sched_replay_agg_vsi_preinit(struct ice_hw *hw) { struct ice_port_info *pi = hw->port_info; struct ice_sched_agg_info *agg_info; mutex_lock(&pi->sched_lock); list_for_each_entry(agg_info, &hw->agg_list, list_entry) { struct ice_sched_agg_vsi_info *agg_vsi_info; agg_info->tc_bitmap[0] = 0; list_for_each_entry(agg_vsi_info, &agg_info->agg_vsi_list, list_entry) agg_vsi_info->tc_bitmap[0] = 0; } mutex_unlock(&pi->sched_lock); } /** * ice_sched_replay_vsi_agg - replay aggregator & VSI to aggregator node(s) * @hw: pointer to the HW struct * @vsi_handle: software VSI handle * * This function replays aggregator node, VSI to aggregator type nodes, and * their node bandwidth information. This function needs to be called with * scheduler lock held. */ static int ice_sched_replay_vsi_agg(struct ice_hw *hw, u16 vsi_handle) { DECLARE_BITMAP(replay_bitmap, ICE_MAX_TRAFFIC_CLASS); struct ice_sched_agg_vsi_info *agg_vsi_info; struct ice_port_info *pi = hw->port_info; struct ice_sched_agg_info *agg_info; int status; bitmap_zero(replay_bitmap, ICE_MAX_TRAFFIC_CLASS); if (!ice_is_vsi_valid(hw, vsi_handle)) return -EINVAL; agg_info = ice_get_vsi_agg_info(hw, vsi_handle); if (!agg_info) return 0; /* Not present in list - default Agg case */ agg_vsi_info = ice_get_agg_vsi_info(agg_info, vsi_handle); if (!agg_vsi_info) return 0; /* Not present in list - default Agg case */ ice_sched_get_ena_tc_bitmap(pi, agg_info->replay_tc_bitmap, replay_bitmap); /* Replay aggregator node associated to vsi_handle */ status = ice_sched_cfg_agg(hw->port_info, agg_info->agg_id, ICE_AGG_TYPE_AGG, replay_bitmap); if (status) return status; bitmap_zero(replay_bitmap, ICE_MAX_TRAFFIC_CLASS); ice_sched_get_ena_tc_bitmap(pi, agg_vsi_info->replay_tc_bitmap, replay_bitmap); /* Move this VSI (vsi_handle) to above aggregator */ return ice_sched_assoc_vsi_to_agg(pi, agg_info->agg_id, vsi_handle, replay_bitmap); } /** * ice_replay_vsi_agg - replay VSI to aggregator node * @hw: pointer to the HW struct * @vsi_handle: software VSI handle * * This function replays association of VSI to aggregator type nodes, and * node bandwidth information. */ int ice_replay_vsi_agg(struct ice_hw *hw, u16 vsi_handle) { struct ice_port_info *pi = hw->port_info; int status; mutex_lock(&pi->sched_lock); status = ice_sched_replay_vsi_agg(hw, vsi_handle); mutex_unlock(&pi->sched_lock); return status; } /** * ice_sched_replay_q_bw - replay queue type node BW * @pi: port information structure * @q_ctx: queue context structure * * This function replays queue type node bandwidth. This function needs to be * called with scheduler lock held. */ int ice_sched_replay_q_bw(struct ice_port_info *pi, struct ice_q_ctx *q_ctx) { struct ice_sched_node *q_node; /* Following also checks the presence of node in tree */ q_node = ice_sched_find_node_by_teid(pi->root, q_ctx->q_teid); if (!q_node) return -EINVAL; return ice_sched_replay_node_bw(pi->hw, q_node, &q_ctx->bw_t_info); }
linux-master
drivers/net/ethernet/intel/ice/ice_sched.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2019-2021, Intel Corporation. */ #include "ice_common.h" /** * ice_pkg_get_supported_vlan_mode - determine if DDP supports Double VLAN mode * @hw: pointer to the HW struct * @dvm: output variable to determine if DDP supports DVM(true) or SVM(false) */ static int ice_pkg_get_supported_vlan_mode(struct ice_hw *hw, bool *dvm) { u16 meta_init_size = sizeof(struct ice_meta_init_section); struct ice_meta_init_section *sect; struct ice_buf_build *bld; int status; /* if anything fails, we assume there is no DVM support */ *dvm = false; bld = ice_pkg_buf_alloc_single_section(hw, ICE_SID_RXPARSER_METADATA_INIT, meta_init_size, (void **)&sect); if (!bld) return -ENOMEM; /* only need to read a single section */ sect->count = cpu_to_le16(1); sect->offset = cpu_to_le16(ICE_META_VLAN_MODE_ENTRY); status = ice_aq_upload_section(hw, (struct ice_buf_hdr *)ice_pkg_buf(bld), ICE_PKG_BUF_SIZE, NULL); if (!status) { DECLARE_BITMAP(entry, ICE_META_INIT_BITS); u32 arr[ICE_META_INIT_DW_CNT]; u16 i; /* convert to host bitmap format */ for (i = 0; i < ICE_META_INIT_DW_CNT; i++) arr[i] = le32_to_cpu(sect->entry.bm[i]); bitmap_from_arr32(entry, arr, (u16)ICE_META_INIT_BITS); /* check if DVM is supported */ *dvm = test_bit(ICE_META_VLAN_MODE_BIT, entry); } ice_pkg_buf_free(hw, bld); return status; } /** * ice_aq_get_vlan_mode - get the VLAN mode of the device * @hw: pointer to the HW structure * @get_params: structure FW fills in based on the current VLAN mode config * * Get VLAN Mode Parameters (0x020D) */ static int ice_aq_get_vlan_mode(struct ice_hw *hw, struct ice_aqc_get_vlan_mode *get_params) { struct ice_aq_desc desc; if (!get_params) return -EINVAL; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_get_vlan_mode_parameters); return ice_aq_send_cmd(hw, &desc, get_params, sizeof(*get_params), NULL); } /** * ice_aq_is_dvm_ena - query FW to check if double VLAN mode is enabled * @hw: pointer to the HW structure * * Returns true if the hardware/firmware is configured in double VLAN mode, * else return false signaling that the hardware/firmware is configured in * single VLAN mode. * * Also, return false if this call fails for any reason (i.e. firmware doesn't * support this AQ call). */ static bool ice_aq_is_dvm_ena(struct ice_hw *hw) { struct ice_aqc_get_vlan_mode get_params = { 0 }; int status; status = ice_aq_get_vlan_mode(hw, &get_params); if (status) { ice_debug(hw, ICE_DBG_AQ, "Failed to get VLAN mode, status %d\n", status); return false; } return (get_params.vlan_mode & ICE_AQ_VLAN_MODE_DVM_ENA); } /** * ice_is_dvm_ena - check if double VLAN mode is enabled * @hw: pointer to the HW structure * * The device is configured in single or double VLAN mode on initialization and * this cannot be dynamically changed during runtime. Based on this there is no * need to make an AQ call every time the driver needs to know the VLAN mode. * Instead, use the cached VLAN mode. */ bool ice_is_dvm_ena(struct ice_hw *hw) { return hw->dvm_ena; } /** * ice_cache_vlan_mode - cache VLAN mode after DDP is downloaded * @hw: pointer to the HW structure * * This is only called after downloading the DDP and after the global * configuration lock has been released because all ports on a device need to * cache the VLAN mode. */ static void ice_cache_vlan_mode(struct ice_hw *hw) { hw->dvm_ena = ice_aq_is_dvm_ena(hw) ? true : false; } /** * ice_pkg_supports_dvm - find out if DDP supports DVM * @hw: pointer to the HW structure */ static bool ice_pkg_supports_dvm(struct ice_hw *hw) { bool pkg_supports_dvm; int status; status = ice_pkg_get_supported_vlan_mode(hw, &pkg_supports_dvm); if (status) { ice_debug(hw, ICE_DBG_PKG, "Failed to get supported VLAN mode, status %d\n", status); return false; } return pkg_supports_dvm; } /** * ice_fw_supports_dvm - find out if FW supports DVM * @hw: pointer to the HW structure */ static bool ice_fw_supports_dvm(struct ice_hw *hw) { struct ice_aqc_get_vlan_mode get_vlan_mode = { 0 }; int status; /* If firmware returns success, then it supports DVM, else it only * supports SVM */ status = ice_aq_get_vlan_mode(hw, &get_vlan_mode); if (status) { ice_debug(hw, ICE_DBG_NVM, "Failed to get VLAN mode, status %d\n", status); return false; } return true; } /** * ice_is_dvm_supported - check if Double VLAN Mode is supported * @hw: pointer to the hardware structure * * Returns true if Double VLAN Mode (DVM) is supported and false if only Single * VLAN Mode (SVM) is supported. In order for DVM to be supported the DDP and * firmware must support it, otherwise only SVM is supported. This function * should only be called while the global config lock is held and after the * package has been successfully downloaded. */ static bool ice_is_dvm_supported(struct ice_hw *hw) { if (!ice_pkg_supports_dvm(hw)) { ice_debug(hw, ICE_DBG_PKG, "DDP doesn't support DVM\n"); return false; } if (!ice_fw_supports_dvm(hw)) { ice_debug(hw, ICE_DBG_PKG, "FW doesn't support DVM\n"); return false; } return true; } #define ICE_EXTERNAL_VLAN_ID_FV_IDX 11 #define ICE_SW_LKUP_VLAN_LOC_LKUP_IDX 1 #define ICE_SW_LKUP_VLAN_PKT_FLAGS_LKUP_IDX 2 #define ICE_SW_LKUP_PROMISC_VLAN_LOC_LKUP_IDX 2 #define ICE_PKT_FLAGS_0_TO_15_FV_IDX 1 static struct ice_update_recipe_lkup_idx_params ice_dvm_dflt_recipes[] = { { /* Update recipe ICE_SW_LKUP_VLAN to filter based on the * outer/single VLAN in DVM */ .rid = ICE_SW_LKUP_VLAN, .fv_idx = ICE_EXTERNAL_VLAN_ID_FV_IDX, .ignore_valid = true, .mask = 0, .mask_valid = false, /* use pre-existing mask */ .lkup_idx = ICE_SW_LKUP_VLAN_LOC_LKUP_IDX, }, { /* Update recipe ICE_SW_LKUP_VLAN to filter based on the VLAN * packet flags to support VLAN filtering on multiple VLAN * ethertypes (i.e. 0x8100 and 0x88a8) in DVM */ .rid = ICE_SW_LKUP_VLAN, .fv_idx = ICE_PKT_FLAGS_0_TO_15_FV_IDX, .ignore_valid = false, .mask = ICE_PKT_VLAN_MASK, .mask_valid = true, .lkup_idx = ICE_SW_LKUP_VLAN_PKT_FLAGS_LKUP_IDX, }, { /* Update recipe ICE_SW_LKUP_PROMISC_VLAN to filter based on the * outer/single VLAN in DVM */ .rid = ICE_SW_LKUP_PROMISC_VLAN, .fv_idx = ICE_EXTERNAL_VLAN_ID_FV_IDX, .ignore_valid = true, .mask = 0, .mask_valid = false, /* use pre-existing mask */ .lkup_idx = ICE_SW_LKUP_PROMISC_VLAN_LOC_LKUP_IDX, }, }; /** * ice_dvm_update_dflt_recipes - update default switch recipes in DVM * @hw: hardware structure used to update the recipes */ static int ice_dvm_update_dflt_recipes(struct ice_hw *hw) { unsigned long i; for (i = 0; i < ARRAY_SIZE(ice_dvm_dflt_recipes); i++) { struct ice_update_recipe_lkup_idx_params *params; int status; params = &ice_dvm_dflt_recipes[i]; status = ice_update_recipe_lkup_idx(hw, params); if (status) { ice_debug(hw, ICE_DBG_INIT, "Failed to update RID %d lkup_idx %d fv_idx %d mask_valid %s mask 0x%04x\n", params->rid, params->lkup_idx, params->fv_idx, params->mask_valid ? "true" : "false", params->mask); return status; } } return 0; } /** * ice_aq_set_vlan_mode - set the VLAN mode of the device * @hw: pointer to the HW structure * @set_params: requested VLAN mode configuration * * Set VLAN Mode Parameters (0x020C) */ static int ice_aq_set_vlan_mode(struct ice_hw *hw, struct ice_aqc_set_vlan_mode *set_params) { u8 rdma_packet, mng_vlan_prot_id; struct ice_aq_desc desc; if (!set_params) return -EINVAL; if (set_params->l2tag_prio_tagging > ICE_AQ_VLAN_PRIO_TAG_MAX) return -EINVAL; rdma_packet = set_params->rdma_packet; if (rdma_packet != ICE_AQ_SVM_VLAN_RDMA_PKT_FLAG_SETTING && rdma_packet != ICE_AQ_DVM_VLAN_RDMA_PKT_FLAG_SETTING) return -EINVAL; mng_vlan_prot_id = set_params->mng_vlan_prot_id; if (mng_vlan_prot_id != ICE_AQ_VLAN_MNG_PROTOCOL_ID_OUTER && mng_vlan_prot_id != ICE_AQ_VLAN_MNG_PROTOCOL_ID_INNER) return -EINVAL; ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_set_vlan_mode_parameters); desc.flags |= cpu_to_le16(ICE_AQ_FLAG_RD); return ice_aq_send_cmd(hw, &desc, set_params, sizeof(*set_params), NULL); } /** * ice_set_dvm - sets up software and hardware for double VLAN mode * @hw: pointer to the hardware structure */ static int ice_set_dvm(struct ice_hw *hw) { struct ice_aqc_set_vlan_mode params = { 0 }; int status; params.l2tag_prio_tagging = ICE_AQ_VLAN_PRIO_TAG_OUTER_CTAG; params.rdma_packet = ICE_AQ_DVM_VLAN_RDMA_PKT_FLAG_SETTING; params.mng_vlan_prot_id = ICE_AQ_VLAN_MNG_PROTOCOL_ID_OUTER; status = ice_aq_set_vlan_mode(hw, &params); if (status) { ice_debug(hw, ICE_DBG_INIT, "Failed to set double VLAN mode parameters, status %d\n", status); return status; } status = ice_dvm_update_dflt_recipes(hw); if (status) { ice_debug(hw, ICE_DBG_INIT, "Failed to update default recipes for double VLAN mode, status %d\n", status); return status; } status = ice_aq_set_port_params(hw->port_info, true, NULL); if (status) { ice_debug(hw, ICE_DBG_INIT, "Failed to set port in double VLAN mode, status %d\n", status); return status; } status = ice_set_dvm_boost_entries(hw); if (status) { ice_debug(hw, ICE_DBG_INIT, "Failed to set boost TCAM entries for double VLAN mode, status %d\n", status); return status; } return 0; } /** * ice_set_svm - set single VLAN mode * @hw: pointer to the HW structure */ static int ice_set_svm(struct ice_hw *hw) { struct ice_aqc_set_vlan_mode *set_params; int status; status = ice_aq_set_port_params(hw->port_info, false, NULL); if (status) { ice_debug(hw, ICE_DBG_INIT, "Failed to set port parameters for single VLAN mode\n"); return status; } set_params = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*set_params), GFP_KERNEL); if (!set_params) return -ENOMEM; /* default configuration for SVM configurations */ set_params->l2tag_prio_tagging = ICE_AQ_VLAN_PRIO_TAG_INNER_CTAG; set_params->rdma_packet = ICE_AQ_SVM_VLAN_RDMA_PKT_FLAG_SETTING; set_params->mng_vlan_prot_id = ICE_AQ_VLAN_MNG_PROTOCOL_ID_INNER; status = ice_aq_set_vlan_mode(hw, set_params); if (status) ice_debug(hw, ICE_DBG_INIT, "Failed to configure port in single VLAN mode\n"); devm_kfree(ice_hw_to_dev(hw), set_params); return status; } /** * ice_set_vlan_mode * @hw: pointer to the HW structure */ int ice_set_vlan_mode(struct ice_hw *hw) { if (!ice_is_dvm_supported(hw)) return 0; if (!ice_set_dvm(hw)) return 0; return ice_set_svm(hw); } /** * ice_print_dvm_not_supported - print if DDP and/or FW doesn't support DVM * @hw: pointer to the HW structure * * The purpose of this function is to print that QinQ is not supported due to * incompatibilty from the DDP and/or FW. This will give a hint to the user to * update one and/or both components if they expect QinQ functionality. */ static void ice_print_dvm_not_supported(struct ice_hw *hw) { bool pkg_supports_dvm = ice_pkg_supports_dvm(hw); bool fw_supports_dvm = ice_fw_supports_dvm(hw); if (!fw_supports_dvm && !pkg_supports_dvm) dev_info(ice_hw_to_dev(hw), "QinQ functionality cannot be enabled on this device. Update your DDP package and NVM to versions that support QinQ.\n"); else if (!pkg_supports_dvm) dev_info(ice_hw_to_dev(hw), "QinQ functionality cannot be enabled on this device. Update your DDP package to a version that supports QinQ.\n"); else if (!fw_supports_dvm) dev_info(ice_hw_to_dev(hw), "QinQ functionality cannot be enabled on this device. Update your NVM to a version that supports QinQ.\n"); } /** * ice_post_pkg_dwnld_vlan_mode_cfg - configure VLAN mode after DDP download * @hw: pointer to the HW structure * * This function is meant to configure any VLAN mode specific functionality * after the global configuration lock has been released and the DDP has been * downloaded. * * Since only one PF downloads the DDP and configures the VLAN mode there needs * to be a way to configure the other PFs after the DDP has been downloaded and * the global configuration lock has been released. All such code should go in * this function. */ void ice_post_pkg_dwnld_vlan_mode_cfg(struct ice_hw *hw) { ice_cache_vlan_mode(hw); if (ice_is_dvm_ena(hw)) ice_change_proto_id_to_dvm(); else ice_print_dvm_not_supported(hw); }
linux-master
drivers/net/ethernet/intel/ice/ice_vlan_mode.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2018-2020, Intel Corporation. */ #include "ice.h" /** * ice_is_arfs_active - helper to check is aRFS is active * @vsi: VSI to check */ static bool ice_is_arfs_active(struct ice_vsi *vsi) { return !!vsi->arfs_fltr_list; } /** * ice_is_arfs_using_perfect_flow - check if aRFS has active perfect filters * @hw: pointer to the HW structure * @flow_type: flow type as Flow Director understands it * * Flow Director will query this function to see if aRFS is currently using * the specified flow_type for perfect (4-tuple) filters. */ bool ice_is_arfs_using_perfect_flow(struct ice_hw *hw, enum ice_fltr_ptype flow_type) { struct ice_arfs_active_fltr_cntrs *arfs_fltr_cntrs; struct ice_pf *pf = hw->back; struct ice_vsi *vsi; vsi = ice_get_main_vsi(pf); if (!vsi) return false; arfs_fltr_cntrs = vsi->arfs_fltr_cntrs; /* active counters can be updated by multiple CPUs */ smp_mb__before_atomic(); switch (flow_type) { case ICE_FLTR_PTYPE_NONF_IPV4_UDP: return atomic_read(&arfs_fltr_cntrs->active_udpv4_cnt) > 0; case ICE_FLTR_PTYPE_NONF_IPV6_UDP: return atomic_read(&arfs_fltr_cntrs->active_udpv6_cnt) > 0; case ICE_FLTR_PTYPE_NONF_IPV4_TCP: return atomic_read(&arfs_fltr_cntrs->active_tcpv4_cnt) > 0; case ICE_FLTR_PTYPE_NONF_IPV6_TCP: return atomic_read(&arfs_fltr_cntrs->active_tcpv6_cnt) > 0; default: return false; } } /** * ice_arfs_update_active_fltr_cntrs - update active filter counters for aRFS * @vsi: VSI that aRFS is active on * @entry: aRFS entry used to change counters * @add: true to increment counter, false to decrement */ static void ice_arfs_update_active_fltr_cntrs(struct ice_vsi *vsi, struct ice_arfs_entry *entry, bool add) { struct ice_arfs_active_fltr_cntrs *fltr_cntrs = vsi->arfs_fltr_cntrs; switch (entry->fltr_info.flow_type) { case ICE_FLTR_PTYPE_NONF_IPV4_TCP: if (add) atomic_inc(&fltr_cntrs->active_tcpv4_cnt); else atomic_dec(&fltr_cntrs->active_tcpv4_cnt); break; case ICE_FLTR_PTYPE_NONF_IPV6_TCP: if (add) atomic_inc(&fltr_cntrs->active_tcpv6_cnt); else atomic_dec(&fltr_cntrs->active_tcpv6_cnt); break; case ICE_FLTR_PTYPE_NONF_IPV4_UDP: if (add) atomic_inc(&fltr_cntrs->active_udpv4_cnt); else atomic_dec(&fltr_cntrs->active_udpv4_cnt); break; case ICE_FLTR_PTYPE_NONF_IPV6_UDP: if (add) atomic_inc(&fltr_cntrs->active_udpv6_cnt); else atomic_dec(&fltr_cntrs->active_udpv6_cnt); break; default: dev_err(ice_pf_to_dev(vsi->back), "aRFS: Failed to update filter counters, invalid filter type %d\n", entry->fltr_info.flow_type); } } /** * ice_arfs_del_flow_rules - delete the rules passed in from HW * @vsi: VSI for the flow rules that need to be deleted * @del_list_head: head of the list of ice_arfs_entry(s) for rule deletion * * Loop through the delete list passed in and remove the rules from HW. After * each rule is deleted, disconnect and free the ice_arfs_entry because it is no * longer being referenced by the aRFS hash table. */ static void ice_arfs_del_flow_rules(struct ice_vsi *vsi, struct hlist_head *del_list_head) { struct ice_arfs_entry *e; struct hlist_node *n; struct device *dev; dev = ice_pf_to_dev(vsi->back); hlist_for_each_entry_safe(e, n, del_list_head, list_entry) { int result; result = ice_fdir_write_fltr(vsi->back, &e->fltr_info, false, false); if (!result) ice_arfs_update_active_fltr_cntrs(vsi, e, false); else dev_dbg(dev, "Unable to delete aRFS entry, err %d fltr_state %d fltr_id %d flow_id %d Q %d\n", result, e->fltr_state, e->fltr_info.fltr_id, e->flow_id, e->fltr_info.q_index); /* The aRFS hash table is no longer referencing this entry */ hlist_del(&e->list_entry); devm_kfree(dev, e); } } /** * ice_arfs_add_flow_rules - add the rules passed in from HW * @vsi: VSI for the flow rules that need to be added * @add_list_head: head of the list of ice_arfs_entry_ptr(s) for rule addition * * Loop through the add list passed in and remove the rules from HW. After each * rule is added, disconnect and free the ice_arfs_entry_ptr node. Don't free * the ice_arfs_entry(s) because they are still being referenced in the aRFS * hash table. */ static void ice_arfs_add_flow_rules(struct ice_vsi *vsi, struct hlist_head *add_list_head) { struct ice_arfs_entry_ptr *ep; struct hlist_node *n; struct device *dev; dev = ice_pf_to_dev(vsi->back); hlist_for_each_entry_safe(ep, n, add_list_head, list_entry) { int result; result = ice_fdir_write_fltr(vsi->back, &ep->arfs_entry->fltr_info, true, false); if (!result) ice_arfs_update_active_fltr_cntrs(vsi, ep->arfs_entry, true); else dev_dbg(dev, "Unable to add aRFS entry, err %d fltr_state %d fltr_id %d flow_id %d Q %d\n", result, ep->arfs_entry->fltr_state, ep->arfs_entry->fltr_info.fltr_id, ep->arfs_entry->flow_id, ep->arfs_entry->fltr_info.q_index); hlist_del(&ep->list_entry); devm_kfree(dev, ep); } } /** * ice_arfs_is_flow_expired - check if the aRFS entry has expired * @vsi: VSI containing the aRFS entry * @arfs_entry: aRFS entry that's being checked for expiration * * Return true if the flow has expired, else false. This function should be used * to determine whether or not an aRFS entry should be removed from the hardware * and software structures. */ static bool ice_arfs_is_flow_expired(struct ice_vsi *vsi, struct ice_arfs_entry *arfs_entry) { #define ICE_ARFS_TIME_DELTA_EXPIRATION msecs_to_jiffies(5000) if (rps_may_expire_flow(vsi->netdev, arfs_entry->fltr_info.q_index, arfs_entry->flow_id, arfs_entry->fltr_info.fltr_id)) return true; /* expiration timer only used for UDP filters */ if (arfs_entry->fltr_info.flow_type != ICE_FLTR_PTYPE_NONF_IPV4_UDP && arfs_entry->fltr_info.flow_type != ICE_FLTR_PTYPE_NONF_IPV6_UDP) return false; return time_in_range64(arfs_entry->time_activated + ICE_ARFS_TIME_DELTA_EXPIRATION, arfs_entry->time_activated, get_jiffies_64()); } /** * ice_arfs_update_flow_rules - add/delete aRFS rules in HW * @vsi: the VSI to be forwarded to * @idx: index into the table of aRFS filter lists. Obtained from skb->hash * @add_list: list to populate with filters to be added to Flow Director * @del_list: list to populate with filters to be deleted from Flow Director * * Iterate over the hlist at the index given in the aRFS hash table and * determine if there are any aRFS entries that need to be either added or * deleted in the HW. If the aRFS entry is marked as ICE_ARFS_INACTIVE the * filter needs to be added to HW, else if it's marked as ICE_ARFS_ACTIVE and * the flow has expired delete the filter from HW. The caller of this function * is expected to add/delete rules on the add_list/del_list respectively. */ static void ice_arfs_update_flow_rules(struct ice_vsi *vsi, u16 idx, struct hlist_head *add_list, struct hlist_head *del_list) { struct ice_arfs_entry *e; struct hlist_node *n; struct device *dev; dev = ice_pf_to_dev(vsi->back); /* go through the aRFS hlist at this idx and check for needed updates */ hlist_for_each_entry_safe(e, n, &vsi->arfs_fltr_list[idx], list_entry) /* check if filter needs to be added to HW */ if (e->fltr_state == ICE_ARFS_INACTIVE) { enum ice_fltr_ptype flow_type = e->fltr_info.flow_type; struct ice_arfs_entry_ptr *ep = devm_kzalloc(dev, sizeof(*ep), GFP_ATOMIC); if (!ep) continue; INIT_HLIST_NODE(&ep->list_entry); /* reference aRFS entry to add HW filter */ ep->arfs_entry = e; hlist_add_head(&ep->list_entry, add_list); e->fltr_state = ICE_ARFS_ACTIVE; /* expiration timer only used for UDP flows */ if (flow_type == ICE_FLTR_PTYPE_NONF_IPV4_UDP || flow_type == ICE_FLTR_PTYPE_NONF_IPV6_UDP) e->time_activated = get_jiffies_64(); } else if (e->fltr_state == ICE_ARFS_ACTIVE) { /* check if filter needs to be removed from HW */ if (ice_arfs_is_flow_expired(vsi, e)) { /* remove aRFS entry from hash table for delete * and to prevent referencing it the next time * through this hlist index */ hlist_del(&e->list_entry); e->fltr_state = ICE_ARFS_TODEL; /* save reference to aRFS entry for delete */ hlist_add_head(&e->list_entry, del_list); } } } /** * ice_sync_arfs_fltrs - update all aRFS filters * @pf: board private structure */ void ice_sync_arfs_fltrs(struct ice_pf *pf) { HLIST_HEAD(tmp_del_list); HLIST_HEAD(tmp_add_list); struct ice_vsi *pf_vsi; unsigned int i; pf_vsi = ice_get_main_vsi(pf); if (!pf_vsi) return; if (!ice_is_arfs_active(pf_vsi)) return; spin_lock_bh(&pf_vsi->arfs_lock); /* Once we process aRFS for the PF VSI get out */ for (i = 0; i < ICE_MAX_ARFS_LIST; i++) ice_arfs_update_flow_rules(pf_vsi, i, &tmp_add_list, &tmp_del_list); spin_unlock_bh(&pf_vsi->arfs_lock); /* use list of ice_arfs_entry(s) for delete */ ice_arfs_del_flow_rules(pf_vsi, &tmp_del_list); /* use list of ice_arfs_entry_ptr(s) for add */ ice_arfs_add_flow_rules(pf_vsi, &tmp_add_list); } /** * ice_arfs_build_entry - builds an aRFS entry based on input * @vsi: destination VSI for this flow * @fk: flow dissector keys for creating the tuple * @rxq_idx: Rx queue to steer this flow to * @flow_id: passed down from the stack and saved for flow expiration * * returns an aRFS entry on success and NULL on failure */ static struct ice_arfs_entry * ice_arfs_build_entry(struct ice_vsi *vsi, const struct flow_keys *fk, u16 rxq_idx, u32 flow_id) { struct ice_arfs_entry *arfs_entry; struct ice_fdir_fltr *fltr_info; u8 ip_proto; arfs_entry = devm_kzalloc(ice_pf_to_dev(vsi->back), sizeof(*arfs_entry), GFP_ATOMIC | __GFP_NOWARN); if (!arfs_entry) return NULL; fltr_info = &arfs_entry->fltr_info; fltr_info->q_index = rxq_idx; fltr_info->dest_ctl = ICE_FLTR_PRGM_DESC_DEST_DIRECT_PKT_QINDEX; fltr_info->dest_vsi = vsi->idx; ip_proto = fk->basic.ip_proto; if (fk->basic.n_proto == htons(ETH_P_IP)) { fltr_info->ip.v4.proto = ip_proto; fltr_info->flow_type = (ip_proto == IPPROTO_TCP) ? ICE_FLTR_PTYPE_NONF_IPV4_TCP : ICE_FLTR_PTYPE_NONF_IPV4_UDP; fltr_info->ip.v4.src_ip = fk->addrs.v4addrs.src; fltr_info->ip.v4.dst_ip = fk->addrs.v4addrs.dst; fltr_info->ip.v4.src_port = fk->ports.src; fltr_info->ip.v4.dst_port = fk->ports.dst; } else { /* ETH_P_IPV6 */ fltr_info->ip.v6.proto = ip_proto; fltr_info->flow_type = (ip_proto == IPPROTO_TCP) ? ICE_FLTR_PTYPE_NONF_IPV6_TCP : ICE_FLTR_PTYPE_NONF_IPV6_UDP; memcpy(&fltr_info->ip.v6.src_ip, &fk->addrs.v6addrs.src, sizeof(struct in6_addr)); memcpy(&fltr_info->ip.v6.dst_ip, &fk->addrs.v6addrs.dst, sizeof(struct in6_addr)); fltr_info->ip.v6.src_port = fk->ports.src; fltr_info->ip.v6.dst_port = fk->ports.dst; } arfs_entry->flow_id = flow_id; fltr_info->fltr_id = atomic_inc_return(vsi->arfs_last_fltr_id) % RPS_NO_FILTER; return arfs_entry; } /** * ice_arfs_is_perfect_flow_set - Check to see if perfect flow is set * @hw: pointer to HW structure * @l3_proto: ETH_P_IP or ETH_P_IPV6 in network order * @l4_proto: IPPROTO_UDP or IPPROTO_TCP * * We only support perfect (4-tuple) filters for aRFS. This function allows aRFS * to check if perfect (4-tuple) flow rules are currently in place by Flow * Director. */ static bool ice_arfs_is_perfect_flow_set(struct ice_hw *hw, __be16 l3_proto, u8 l4_proto) { unsigned long *perfect_fltr = hw->fdir_perfect_fltr; /* advanced Flow Director disabled, perfect filters always supported */ if (!perfect_fltr) return true; if (l3_proto == htons(ETH_P_IP) && l4_proto == IPPROTO_UDP) return test_bit(ICE_FLTR_PTYPE_NONF_IPV4_UDP, perfect_fltr); else if (l3_proto == htons(ETH_P_IP) && l4_proto == IPPROTO_TCP) return test_bit(ICE_FLTR_PTYPE_NONF_IPV4_TCP, perfect_fltr); else if (l3_proto == htons(ETH_P_IPV6) && l4_proto == IPPROTO_UDP) return test_bit(ICE_FLTR_PTYPE_NONF_IPV6_UDP, perfect_fltr); else if (l3_proto == htons(ETH_P_IPV6) && l4_proto == IPPROTO_TCP) return test_bit(ICE_FLTR_PTYPE_NONF_IPV6_TCP, perfect_fltr); return false; } /** * ice_rx_flow_steer - steer the Rx flow to where application is being run * @netdev: ptr to the netdev being adjusted * @skb: buffer with required header information * @rxq_idx: queue to which the flow needs to move * @flow_id: flow identifier provided by the netdev * * Based on the skb, rxq_idx, and flow_id passed in add/update an entry in the * aRFS hash table. Iterate over one of the hlists in the aRFS hash table and * if the flow_id already exists in the hash table but the rxq_idx has changed * mark the entry as ICE_ARFS_INACTIVE so it can get updated in HW, else * if the entry is marked as ICE_ARFS_TODEL delete it from the aRFS hash table. * If neither of the previous conditions are true then add a new entry in the * aRFS hash table, which gets set to ICE_ARFS_INACTIVE by default so it can be * added to HW. */ int ice_rx_flow_steer(struct net_device *netdev, const struct sk_buff *skb, u16 rxq_idx, u32 flow_id) { struct ice_netdev_priv *np = netdev_priv(netdev); struct ice_arfs_entry *arfs_entry; struct ice_vsi *vsi = np->vsi; struct flow_keys fk; struct ice_pf *pf; __be16 n_proto; u8 ip_proto; u16 idx; int ret; /* failed to allocate memory for aRFS so don't crash */ if (unlikely(!vsi->arfs_fltr_list)) return -ENODEV; pf = vsi->back; if (skb->encapsulation) return -EPROTONOSUPPORT; if (!skb_flow_dissect_flow_keys(skb, &fk, 0)) return -EPROTONOSUPPORT; n_proto = fk.basic.n_proto; /* Support only IPV4 and IPV6 */ if ((n_proto == htons(ETH_P_IP) && !ip_is_fragment(ip_hdr(skb))) || n_proto == htons(ETH_P_IPV6)) ip_proto = fk.basic.ip_proto; else return -EPROTONOSUPPORT; /* Support only TCP and UDP */ if (ip_proto != IPPROTO_TCP && ip_proto != IPPROTO_UDP) return -EPROTONOSUPPORT; /* only support 4-tuple filters for aRFS */ if (!ice_arfs_is_perfect_flow_set(&pf->hw, n_proto, ip_proto)) return -EOPNOTSUPP; /* choose the aRFS list bucket based on skb hash */ idx = skb_get_hash_raw(skb) & ICE_ARFS_LST_MASK; /* search for entry in the bucket */ spin_lock_bh(&vsi->arfs_lock); hlist_for_each_entry(arfs_entry, &vsi->arfs_fltr_list[idx], list_entry) { struct ice_fdir_fltr *fltr_info; /* keep searching for the already existing arfs_entry flow */ if (arfs_entry->flow_id != flow_id) continue; fltr_info = &arfs_entry->fltr_info; ret = fltr_info->fltr_id; if (fltr_info->q_index == rxq_idx || arfs_entry->fltr_state != ICE_ARFS_ACTIVE) goto out; /* update the queue to forward to on an already existing flow */ fltr_info->q_index = rxq_idx; arfs_entry->fltr_state = ICE_ARFS_INACTIVE; ice_arfs_update_active_fltr_cntrs(vsi, arfs_entry, false); goto out_schedule_service_task; } arfs_entry = ice_arfs_build_entry(vsi, &fk, rxq_idx, flow_id); if (!arfs_entry) { ret = -ENOMEM; goto out; } ret = arfs_entry->fltr_info.fltr_id; INIT_HLIST_NODE(&arfs_entry->list_entry); hlist_add_head(&arfs_entry->list_entry, &vsi->arfs_fltr_list[idx]); out_schedule_service_task: ice_service_task_schedule(pf); out: spin_unlock_bh(&vsi->arfs_lock); return ret; } /** * ice_init_arfs_cntrs - initialize aRFS counter values * @vsi: VSI that aRFS counters need to be initialized on */ static int ice_init_arfs_cntrs(struct ice_vsi *vsi) { if (!vsi || vsi->type != ICE_VSI_PF) return -EINVAL; vsi->arfs_fltr_cntrs = kzalloc(sizeof(*vsi->arfs_fltr_cntrs), GFP_KERNEL); if (!vsi->arfs_fltr_cntrs) return -ENOMEM; vsi->arfs_last_fltr_id = kzalloc(sizeof(*vsi->arfs_last_fltr_id), GFP_KERNEL); if (!vsi->arfs_last_fltr_id) { kfree(vsi->arfs_fltr_cntrs); vsi->arfs_fltr_cntrs = NULL; return -ENOMEM; } return 0; } /** * ice_init_arfs - initialize aRFS resources * @vsi: the VSI to be forwarded to */ void ice_init_arfs(struct ice_vsi *vsi) { struct hlist_head *arfs_fltr_list; unsigned int i; if (!vsi || vsi->type != ICE_VSI_PF) return; arfs_fltr_list = kcalloc(ICE_MAX_ARFS_LIST, sizeof(*arfs_fltr_list), GFP_KERNEL); if (!arfs_fltr_list) return; if (ice_init_arfs_cntrs(vsi)) goto free_arfs_fltr_list; for (i = 0; i < ICE_MAX_ARFS_LIST; i++) INIT_HLIST_HEAD(&arfs_fltr_list[i]); spin_lock_init(&vsi->arfs_lock); vsi->arfs_fltr_list = arfs_fltr_list; return; free_arfs_fltr_list: kfree(arfs_fltr_list); } /** * ice_clear_arfs - clear the aRFS hash table and any memory used for aRFS * @vsi: the VSI to be forwarded to */ void ice_clear_arfs(struct ice_vsi *vsi) { struct device *dev; unsigned int i; if (!vsi || vsi->type != ICE_VSI_PF || !vsi->back || !vsi->arfs_fltr_list) return; dev = ice_pf_to_dev(vsi->back); for (i = 0; i < ICE_MAX_ARFS_LIST; i++) { struct ice_arfs_entry *r; struct hlist_node *n; spin_lock_bh(&vsi->arfs_lock); hlist_for_each_entry_safe(r, n, &vsi->arfs_fltr_list[i], list_entry) { hlist_del(&r->list_entry); devm_kfree(dev, r); } spin_unlock_bh(&vsi->arfs_lock); } kfree(vsi->arfs_fltr_list); vsi->arfs_fltr_list = NULL; kfree(vsi->arfs_last_fltr_id); vsi->arfs_last_fltr_id = NULL; kfree(vsi->arfs_fltr_cntrs); vsi->arfs_fltr_cntrs = NULL; } /** * ice_free_cpu_rx_rmap - free setup CPU reverse map * @vsi: the VSI to be forwarded to */ void ice_free_cpu_rx_rmap(struct ice_vsi *vsi) { struct net_device *netdev; if (!vsi || vsi->type != ICE_VSI_PF) return; netdev = vsi->netdev; if (!netdev || !netdev->rx_cpu_rmap) return; free_irq_cpu_rmap(netdev->rx_cpu_rmap); netdev->rx_cpu_rmap = NULL; } /** * ice_set_cpu_rx_rmap - setup CPU reverse map for each queue * @vsi: the VSI to be forwarded to */ int ice_set_cpu_rx_rmap(struct ice_vsi *vsi) { struct net_device *netdev; struct ice_pf *pf; int i; if (!vsi || vsi->type != ICE_VSI_PF) return 0; pf = vsi->back; netdev = vsi->netdev; if (!pf || !netdev || !vsi->num_q_vectors) return -EINVAL; netdev_dbg(netdev, "Setup CPU RMAP: vsi type 0x%x, ifname %s, q_vectors %d\n", vsi->type, netdev->name, vsi->num_q_vectors); netdev->rx_cpu_rmap = alloc_irq_cpu_rmap(vsi->num_q_vectors); if (unlikely(!netdev->rx_cpu_rmap)) return -EINVAL; ice_for_each_q_vector(vsi, i) if (irq_cpu_rmap_add(netdev->rx_cpu_rmap, vsi->q_vectors[i]->irq.virq)) { ice_free_cpu_rx_rmap(vsi); return -EINVAL; } return 0; } /** * ice_remove_arfs - remove/clear all aRFS resources * @pf: device private structure */ void ice_remove_arfs(struct ice_pf *pf) { struct ice_vsi *pf_vsi; pf_vsi = ice_get_main_vsi(pf); if (!pf_vsi) return; ice_clear_arfs(pf_vsi); } /** * ice_rebuild_arfs - remove/clear all aRFS resources and rebuild after reset * @pf: device private structure */ void ice_rebuild_arfs(struct ice_pf *pf) { struct ice_vsi *pf_vsi; pf_vsi = ice_get_main_vsi(pf); if (!pf_vsi) return; ice_remove_arfs(pf); ice_init_arfs(pf_vsi); }
linux-master
drivers/net/ethernet/intel/ice/ice_arfs.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2019-2021, Intel Corporation. */ #include "ice_vsi_vlan_lib.h" #include "ice_lib.h" #include "ice_fltr.h" #include "ice.h" static void print_invalid_tpid(struct ice_vsi *vsi, u16 tpid) { dev_err(ice_pf_to_dev(vsi->back), "%s %d specified invalid VLAN tpid 0x%04x\n", ice_vsi_type_str(vsi->type), vsi->idx, tpid); } /** * validate_vlan - check if the ice_vlan passed in is valid * @vsi: VSI used for printing error message * @vlan: ice_vlan structure to validate * * Return true if the VLAN TPID is valid or if the VLAN TPID is 0 and the VLAN * VID is 0, which allows for non-zero VLAN filters with the specified VLAN TPID * and untagged VLAN 0 filters to be added to the prune list respectively. */ static bool validate_vlan(struct ice_vsi *vsi, struct ice_vlan *vlan) { if (vlan->tpid != ETH_P_8021Q && vlan->tpid != ETH_P_8021AD && vlan->tpid != ETH_P_QINQ1 && (vlan->tpid || vlan->vid)) { print_invalid_tpid(vsi, vlan->tpid); return false; } return true; } /** * ice_vsi_add_vlan - default add VLAN implementation for all VSI types * @vsi: VSI being configured * @vlan: VLAN filter to add */ int ice_vsi_add_vlan(struct ice_vsi *vsi, struct ice_vlan *vlan) { int err; if (!validate_vlan(vsi, vlan)) return -EINVAL; err = ice_fltr_add_vlan(vsi, vlan); if (err && err != -EEXIST) { dev_err(ice_pf_to_dev(vsi->back), "Failure Adding VLAN %d on VSI %i, status %d\n", vlan->vid, vsi->vsi_num, err); return err; } vsi->num_vlan++; return 0; } /** * ice_vsi_del_vlan - default del VLAN implementation for all VSI types * @vsi: VSI being configured * @vlan: VLAN filter to delete */ int ice_vsi_del_vlan(struct ice_vsi *vsi, struct ice_vlan *vlan) { struct ice_pf *pf = vsi->back; struct device *dev; int err; if (!validate_vlan(vsi, vlan)) return -EINVAL; dev = ice_pf_to_dev(pf); err = ice_fltr_remove_vlan(vsi, vlan); if (!err) vsi->num_vlan--; else if (err == -ENOENT || err == -EBUSY) err = 0; else dev_err(dev, "Error removing VLAN %d on VSI %i error: %d\n", vlan->vid, vsi->vsi_num, err); return err; } /** * ice_vsi_manage_vlan_insertion - Manage VLAN insertion for the VSI for Tx * @vsi: the VSI being changed */ static int ice_vsi_manage_vlan_insertion(struct ice_vsi *vsi) { struct ice_hw *hw = &vsi->back->hw; struct ice_vsi_ctx *ctxt; int err; ctxt = kzalloc(sizeof(*ctxt), GFP_KERNEL); if (!ctxt) return -ENOMEM; /* Here we are configuring the VSI to let the driver add VLAN tags by * setting inner_vlan_flags to ICE_AQ_VSI_INNER_VLAN_TX_MODE_ALL. The actual VLAN tag * insertion happens in the Tx hot path, in ice_tx_map. */ ctxt->info.inner_vlan_flags = ICE_AQ_VSI_INNER_VLAN_TX_MODE_ALL; /* Preserve existing VLAN strip setting */ ctxt->info.inner_vlan_flags |= (vsi->info.inner_vlan_flags & ICE_AQ_VSI_INNER_VLAN_EMODE_M); ctxt->info.valid_sections = cpu_to_le16(ICE_AQ_VSI_PROP_VLAN_VALID); err = ice_update_vsi(hw, vsi->idx, ctxt, NULL); if (err) { dev_err(ice_pf_to_dev(vsi->back), "update VSI for VLAN insert failed, err %d aq_err %s\n", err, ice_aq_str(hw->adminq.sq_last_status)); goto out; } vsi->info.inner_vlan_flags = ctxt->info.inner_vlan_flags; out: kfree(ctxt); return err; } /** * ice_vsi_manage_vlan_stripping - Manage VLAN stripping for the VSI for Rx * @vsi: the VSI being changed * @ena: boolean value indicating if this is a enable or disable request */ static int ice_vsi_manage_vlan_stripping(struct ice_vsi *vsi, bool ena) { struct ice_hw *hw = &vsi->back->hw; struct ice_vsi_ctx *ctxt; int err; /* do not allow modifying VLAN stripping when a port VLAN is configured * on this VSI */ if (vsi->info.port_based_inner_vlan) return 0; ctxt = kzalloc(sizeof(*ctxt), GFP_KERNEL); if (!ctxt) return -ENOMEM; /* Here we are configuring what the VSI should do with the VLAN tag in * the Rx packet. We can either leave the tag in the packet or put it in * the Rx descriptor. */ if (ena) /* Strip VLAN tag from Rx packet and put it in the desc */ ctxt->info.inner_vlan_flags = ICE_AQ_VSI_INNER_VLAN_EMODE_STR_BOTH; else /* Disable stripping. Leave tag in packet */ ctxt->info.inner_vlan_flags = ICE_AQ_VSI_INNER_VLAN_EMODE_NOTHING; /* Allow all packets untagged/tagged */ ctxt->info.inner_vlan_flags |= ICE_AQ_VSI_INNER_VLAN_TX_MODE_ALL; ctxt->info.valid_sections = cpu_to_le16(ICE_AQ_VSI_PROP_VLAN_VALID); err = ice_update_vsi(hw, vsi->idx, ctxt, NULL); if (err) { dev_err(ice_pf_to_dev(vsi->back), "update VSI for VLAN strip failed, ena = %d err %d aq_err %s\n", ena, err, ice_aq_str(hw->adminq.sq_last_status)); goto out; } vsi->info.inner_vlan_flags = ctxt->info.inner_vlan_flags; out: kfree(ctxt); return err; } int ice_vsi_ena_inner_stripping(struct ice_vsi *vsi, const u16 tpid) { if (tpid != ETH_P_8021Q) { print_invalid_tpid(vsi, tpid); return -EINVAL; } return ice_vsi_manage_vlan_stripping(vsi, true); } int ice_vsi_dis_inner_stripping(struct ice_vsi *vsi) { return ice_vsi_manage_vlan_stripping(vsi, false); } int ice_vsi_ena_inner_insertion(struct ice_vsi *vsi, const u16 tpid) { if (tpid != ETH_P_8021Q) { print_invalid_tpid(vsi, tpid); return -EINVAL; } return ice_vsi_manage_vlan_insertion(vsi); } int ice_vsi_dis_inner_insertion(struct ice_vsi *vsi) { return ice_vsi_manage_vlan_insertion(vsi); } static void ice_save_vlan_info(struct ice_aqc_vsi_props *info, struct ice_vsi_vlan_info *vlan) { vlan->sw_flags2 = info->sw_flags2; vlan->inner_vlan_flags = info->inner_vlan_flags; vlan->outer_vlan_flags = info->outer_vlan_flags; } static void ice_restore_vlan_info(struct ice_aqc_vsi_props *info, struct ice_vsi_vlan_info *vlan) { info->sw_flags2 = vlan->sw_flags2; info->inner_vlan_flags = vlan->inner_vlan_flags; info->outer_vlan_flags = vlan->outer_vlan_flags; } /** * __ice_vsi_set_inner_port_vlan - set port VLAN VSI context settings to enable a port VLAN * @vsi: the VSI to update * @pvid_info: VLAN ID and QoS used to set the PVID VSI context field */ static int __ice_vsi_set_inner_port_vlan(struct ice_vsi *vsi, u16 pvid_info) { struct ice_hw *hw = &vsi->back->hw; struct ice_aqc_vsi_props *info; struct ice_vsi_ctx *ctxt; int ret; ctxt = kzalloc(sizeof(*ctxt), GFP_KERNEL); if (!ctxt) return -ENOMEM; ice_save_vlan_info(&vsi->info, &vsi->vlan_info); ctxt->info = vsi->info; info = &ctxt->info; info->inner_vlan_flags = ICE_AQ_VSI_INNER_VLAN_TX_MODE_ACCEPTUNTAGGED | ICE_AQ_VSI_INNER_VLAN_INSERT_PVID | ICE_AQ_VSI_INNER_VLAN_EMODE_STR; info->sw_flags2 |= ICE_AQ_VSI_SW_FLAG_RX_VLAN_PRUNE_ENA; info->port_based_inner_vlan = cpu_to_le16(pvid_info); info->valid_sections = cpu_to_le16(ICE_AQ_VSI_PROP_VLAN_VALID | ICE_AQ_VSI_PROP_SW_VALID); ret = ice_update_vsi(hw, vsi->idx, ctxt, NULL); if (ret) { dev_info(ice_hw_to_dev(hw), "update VSI for port VLAN failed, err %d aq_err %s\n", ret, ice_aq_str(hw->adminq.sq_last_status)); goto out; } vsi->info.inner_vlan_flags = info->inner_vlan_flags; vsi->info.sw_flags2 = info->sw_flags2; vsi->info.port_based_inner_vlan = info->port_based_inner_vlan; out: kfree(ctxt); return ret; } int ice_vsi_set_inner_port_vlan(struct ice_vsi *vsi, struct ice_vlan *vlan) { u16 port_vlan_info; if (vlan->tpid != ETH_P_8021Q) return -EINVAL; if (vlan->prio > 7) return -EINVAL; port_vlan_info = vlan->vid | (vlan->prio << VLAN_PRIO_SHIFT); return __ice_vsi_set_inner_port_vlan(vsi, port_vlan_info); } int ice_vsi_clear_inner_port_vlan(struct ice_vsi *vsi) { struct ice_hw *hw = &vsi->back->hw; struct ice_aqc_vsi_props *info; struct ice_vsi_ctx *ctxt; int ret; ctxt = kzalloc(sizeof(*ctxt), GFP_KERNEL); if (!ctxt) return -ENOMEM; ice_restore_vlan_info(&vsi->info, &vsi->vlan_info); vsi->info.port_based_inner_vlan = 0; ctxt->info = vsi->info; info = &ctxt->info; info->valid_sections = cpu_to_le16(ICE_AQ_VSI_PROP_VLAN_VALID | ICE_AQ_VSI_PROP_SW_VALID); ret = ice_update_vsi(hw, vsi->idx, ctxt, NULL); if (ret) dev_err(ice_hw_to_dev(hw), "update VSI for port VLAN failed, err %d aq_err %s\n", ret, ice_aq_str(hw->adminq.sq_last_status)); kfree(ctxt); return ret; } /** * ice_cfg_vlan_pruning - enable or disable VLAN pruning on the VSI * @vsi: VSI to enable or disable VLAN pruning on * @ena: set to true to enable VLAN pruning and false to disable it * * returns 0 if VSI is updated, negative otherwise */ static int ice_cfg_vlan_pruning(struct ice_vsi *vsi, bool ena) { struct ice_vsi_ctx *ctxt; struct ice_pf *pf; int status; if (!vsi) return -EINVAL; /* Don't enable VLAN pruning if the netdev is currently in promiscuous * mode. VLAN pruning will be enabled when the interface exits * promiscuous mode if any VLAN filters are active. */ if (vsi->netdev && vsi->netdev->flags & IFF_PROMISC && ena) return 0; pf = vsi->back; ctxt = kzalloc(sizeof(*ctxt), GFP_KERNEL); if (!ctxt) return -ENOMEM; ctxt->info = vsi->info; if (ena) ctxt->info.sw_flags2 |= ICE_AQ_VSI_SW_FLAG_RX_VLAN_PRUNE_ENA; else ctxt->info.sw_flags2 &= ~ICE_AQ_VSI_SW_FLAG_RX_VLAN_PRUNE_ENA; ctxt->info.valid_sections = cpu_to_le16(ICE_AQ_VSI_PROP_SW_VALID); status = ice_update_vsi(&pf->hw, vsi->idx, ctxt, NULL); if (status) { netdev_err(vsi->netdev, "%sabling VLAN pruning on VSI handle: %d, VSI HW ID: %d failed, err = %d, aq_err = %s\n", ena ? "En" : "Dis", vsi->idx, vsi->vsi_num, status, ice_aq_str(pf->hw.adminq.sq_last_status)); goto err_out; } vsi->info.sw_flags2 = ctxt->info.sw_flags2; kfree(ctxt); return 0; err_out: kfree(ctxt); return status; } int ice_vsi_ena_rx_vlan_filtering(struct ice_vsi *vsi) { return ice_cfg_vlan_pruning(vsi, true); } int ice_vsi_dis_rx_vlan_filtering(struct ice_vsi *vsi) { return ice_cfg_vlan_pruning(vsi, false); } static int ice_cfg_vlan_antispoof(struct ice_vsi *vsi, bool enable) { struct ice_vsi_ctx *ctx; int err; ctx = kzalloc(sizeof(*ctx), GFP_KERNEL); if (!ctx) return -ENOMEM; ctx->info.sec_flags = vsi->info.sec_flags; ctx->info.valid_sections = cpu_to_le16(ICE_AQ_VSI_PROP_SECURITY_VALID); if (enable) ctx->info.sec_flags |= ICE_AQ_VSI_SEC_TX_VLAN_PRUNE_ENA << ICE_AQ_VSI_SEC_TX_PRUNE_ENA_S; else ctx->info.sec_flags &= ~(ICE_AQ_VSI_SEC_TX_VLAN_PRUNE_ENA << ICE_AQ_VSI_SEC_TX_PRUNE_ENA_S); err = ice_update_vsi(&vsi->back->hw, vsi->idx, ctx, NULL); if (err) dev_err(ice_pf_to_dev(vsi->back), "Failed to configure Tx VLAN anti-spoof %s for VSI %d, error %d\n", enable ? "ON" : "OFF", vsi->vsi_num, err); else vsi->info.sec_flags = ctx->info.sec_flags; kfree(ctx); return err; } int ice_vsi_ena_tx_vlan_filtering(struct ice_vsi *vsi) { return ice_cfg_vlan_antispoof(vsi, true); } int ice_vsi_dis_tx_vlan_filtering(struct ice_vsi *vsi) { return ice_cfg_vlan_antispoof(vsi, false); } /** * tpid_to_vsi_outer_vlan_type - convert from TPID to VSI context based tag_type * @tpid: tpid used to translate into VSI context based tag_type * @tag_type: output variable to hold the VSI context based tag type */ static int tpid_to_vsi_outer_vlan_type(u16 tpid, u8 *tag_type) { switch (tpid) { case ETH_P_8021Q: *tag_type = ICE_AQ_VSI_OUTER_TAG_VLAN_8100; break; case ETH_P_8021AD: *tag_type = ICE_AQ_VSI_OUTER_TAG_STAG; break; case ETH_P_QINQ1: *tag_type = ICE_AQ_VSI_OUTER_TAG_VLAN_9100; break; default: *tag_type = 0; return -EINVAL; } return 0; } /** * ice_vsi_ena_outer_stripping - enable outer VLAN stripping * @vsi: VSI to configure * @tpid: TPID to enable outer VLAN stripping for * * Enable outer VLAN stripping via VSI context. This function should only be * used if DVM is supported. Also, this function should never be called directly * as it should be part of ice_vsi_vlan_ops if it's needed. * * Since the VSI context only supports a single TPID for insertion and * stripping, setting the TPID for stripping will affect the TPID for insertion. * Callers need to be aware of this limitation. * * Only modify outer VLAN stripping settings and the VLAN TPID. Outer VLAN * insertion settings are unmodified. * * This enables hardware to strip a VLAN tag with the specified TPID to be * stripped from the packet and placed in the receive descriptor. */ int ice_vsi_ena_outer_stripping(struct ice_vsi *vsi, u16 tpid) { struct ice_hw *hw = &vsi->back->hw; struct ice_vsi_ctx *ctxt; u8 tag_type; int err; /* do not allow modifying VLAN stripping when a port VLAN is configured * on this VSI */ if (vsi->info.port_based_outer_vlan) return 0; if (tpid_to_vsi_outer_vlan_type(tpid, &tag_type)) return -EINVAL; ctxt = kzalloc(sizeof(*ctxt), GFP_KERNEL); if (!ctxt) return -ENOMEM; ctxt->info.valid_sections = cpu_to_le16(ICE_AQ_VSI_PROP_OUTER_TAG_VALID); /* clear current outer VLAN strip settings */ ctxt->info.outer_vlan_flags = vsi->info.outer_vlan_flags & ~(ICE_AQ_VSI_OUTER_VLAN_EMODE_M | ICE_AQ_VSI_OUTER_TAG_TYPE_M); ctxt->info.outer_vlan_flags |= ((ICE_AQ_VSI_OUTER_VLAN_EMODE_SHOW_BOTH << ICE_AQ_VSI_OUTER_VLAN_EMODE_S) | ((tag_type << ICE_AQ_VSI_OUTER_TAG_TYPE_S) & ICE_AQ_VSI_OUTER_TAG_TYPE_M)); err = ice_update_vsi(hw, vsi->idx, ctxt, NULL); if (err) dev_err(ice_pf_to_dev(vsi->back), "update VSI for enabling outer VLAN stripping failed, err %d aq_err %s\n", err, ice_aq_str(hw->adminq.sq_last_status)); else vsi->info.outer_vlan_flags = ctxt->info.outer_vlan_flags; kfree(ctxt); return err; } /** * ice_vsi_dis_outer_stripping - disable outer VLAN stripping * @vsi: VSI to configure * * Disable outer VLAN stripping via VSI context. This function should only be * used if DVM is supported. Also, this function should never be called directly * as it should be part of ice_vsi_vlan_ops if it's needed. * * Only modify the outer VLAN stripping settings. The VLAN TPID and outer VLAN * insertion settings are unmodified. * * This tells the hardware to not strip any VLAN tagged packets, thus leaving * them in the packet. This enables software offloaded VLAN stripping and * disables hardware offloaded VLAN stripping. */ int ice_vsi_dis_outer_stripping(struct ice_vsi *vsi) { struct ice_hw *hw = &vsi->back->hw; struct ice_vsi_ctx *ctxt; int err; if (vsi->info.port_based_outer_vlan) return 0; ctxt = kzalloc(sizeof(*ctxt), GFP_KERNEL); if (!ctxt) return -ENOMEM; ctxt->info.valid_sections = cpu_to_le16(ICE_AQ_VSI_PROP_OUTER_TAG_VALID); /* clear current outer VLAN strip settings */ ctxt->info.outer_vlan_flags = vsi->info.outer_vlan_flags & ~ICE_AQ_VSI_OUTER_VLAN_EMODE_M; ctxt->info.outer_vlan_flags |= ICE_AQ_VSI_OUTER_VLAN_EMODE_NOTHING << ICE_AQ_VSI_OUTER_VLAN_EMODE_S; err = ice_update_vsi(hw, vsi->idx, ctxt, NULL); if (err) dev_err(ice_pf_to_dev(vsi->back), "update VSI for disabling outer VLAN stripping failed, err %d aq_err %s\n", err, ice_aq_str(hw->adminq.sq_last_status)); else vsi->info.outer_vlan_flags = ctxt->info.outer_vlan_flags; kfree(ctxt); return err; } /** * ice_vsi_ena_outer_insertion - enable outer VLAN insertion * @vsi: VSI to configure * @tpid: TPID to enable outer VLAN insertion for * * Enable outer VLAN insertion via VSI context. This function should only be * used if DVM is supported. Also, this function should never be called directly * as it should be part of ice_vsi_vlan_ops if it's needed. * * Since the VSI context only supports a single TPID for insertion and * stripping, setting the TPID for insertion will affect the TPID for stripping. * Callers need to be aware of this limitation. * * Only modify outer VLAN insertion settings and the VLAN TPID. Outer VLAN * stripping settings are unmodified. * * This allows a VLAN tag with the specified TPID to be inserted in the transmit * descriptor. */ int ice_vsi_ena_outer_insertion(struct ice_vsi *vsi, u16 tpid) { struct ice_hw *hw = &vsi->back->hw; struct ice_vsi_ctx *ctxt; u8 tag_type; int err; if (vsi->info.port_based_outer_vlan) return 0; if (tpid_to_vsi_outer_vlan_type(tpid, &tag_type)) return -EINVAL; ctxt = kzalloc(sizeof(*ctxt), GFP_KERNEL); if (!ctxt) return -ENOMEM; ctxt->info.valid_sections = cpu_to_le16(ICE_AQ_VSI_PROP_OUTER_TAG_VALID); /* clear current outer VLAN insertion settings */ ctxt->info.outer_vlan_flags = vsi->info.outer_vlan_flags & ~(ICE_AQ_VSI_OUTER_VLAN_PORT_BASED_INSERT | ICE_AQ_VSI_OUTER_VLAN_BLOCK_TX_DESC | ICE_AQ_VSI_OUTER_VLAN_TX_MODE_M | ICE_AQ_VSI_OUTER_TAG_TYPE_M); ctxt->info.outer_vlan_flags |= ((ICE_AQ_VSI_OUTER_VLAN_TX_MODE_ALL << ICE_AQ_VSI_OUTER_VLAN_TX_MODE_S) & ICE_AQ_VSI_OUTER_VLAN_TX_MODE_M) | ((tag_type << ICE_AQ_VSI_OUTER_TAG_TYPE_S) & ICE_AQ_VSI_OUTER_TAG_TYPE_M); err = ice_update_vsi(hw, vsi->idx, ctxt, NULL); if (err) dev_err(ice_pf_to_dev(vsi->back), "update VSI for enabling outer VLAN insertion failed, err %d aq_err %s\n", err, ice_aq_str(hw->adminq.sq_last_status)); else vsi->info.outer_vlan_flags = ctxt->info.outer_vlan_flags; kfree(ctxt); return err; } /** * ice_vsi_dis_outer_insertion - disable outer VLAN insertion * @vsi: VSI to configure * * Disable outer VLAN insertion via VSI context. This function should only be * used if DVM is supported. Also, this function should never be called directly * as it should be part of ice_vsi_vlan_ops if it's needed. * * Only modify the outer VLAN insertion settings. The VLAN TPID and outer VLAN * settings are unmodified. * * This tells the hardware to not allow any VLAN tagged packets in the transmit * descriptor. This enables software offloaded VLAN insertion and disables * hardware offloaded VLAN insertion. */ int ice_vsi_dis_outer_insertion(struct ice_vsi *vsi) { struct ice_hw *hw = &vsi->back->hw; struct ice_vsi_ctx *ctxt; int err; if (vsi->info.port_based_outer_vlan) return 0; ctxt = kzalloc(sizeof(*ctxt), GFP_KERNEL); if (!ctxt) return -ENOMEM; ctxt->info.valid_sections = cpu_to_le16(ICE_AQ_VSI_PROP_OUTER_TAG_VALID); /* clear current outer VLAN insertion settings */ ctxt->info.outer_vlan_flags = vsi->info.outer_vlan_flags & ~(ICE_AQ_VSI_OUTER_VLAN_PORT_BASED_INSERT | ICE_AQ_VSI_OUTER_VLAN_TX_MODE_M); ctxt->info.outer_vlan_flags |= ICE_AQ_VSI_OUTER_VLAN_BLOCK_TX_DESC | ((ICE_AQ_VSI_OUTER_VLAN_TX_MODE_ALL << ICE_AQ_VSI_OUTER_VLAN_TX_MODE_S) & ICE_AQ_VSI_OUTER_VLAN_TX_MODE_M); err = ice_update_vsi(hw, vsi->idx, ctxt, NULL); if (err) dev_err(ice_pf_to_dev(vsi->back), "update VSI for disabling outer VLAN insertion failed, err %d aq_err %s\n", err, ice_aq_str(hw->adminq.sq_last_status)); else vsi->info.outer_vlan_flags = ctxt->info.outer_vlan_flags; kfree(ctxt); return err; } /** * __ice_vsi_set_outer_port_vlan - set the outer port VLAN and related settings * @vsi: VSI to configure * @vlan_info: packed u16 that contains the VLAN prio and ID * @tpid: TPID of the port VLAN * * Set the port VLAN prio, ID, and TPID. * * Enable VLAN pruning so the VSI doesn't receive any traffic that doesn't match * a VLAN prune rule. The caller should take care to add a VLAN prune rule that * matches the port VLAN ID and TPID. * * Tell hardware to strip outer VLAN tagged packets on receive and don't put * them in the receive descriptor. VSI(s) in port VLANs should not be aware of * the port VLAN ID or TPID they are assigned to. * * Tell hardware to prevent outer VLAN tag insertion on transmit and only allow * untagged outer packets from the transmit descriptor. * * Also, tell the hardware to insert the port VLAN on transmit. */ static int __ice_vsi_set_outer_port_vlan(struct ice_vsi *vsi, u16 vlan_info, u16 tpid) { struct ice_hw *hw = &vsi->back->hw; struct ice_vsi_ctx *ctxt; u8 tag_type; int err; if (tpid_to_vsi_outer_vlan_type(tpid, &tag_type)) return -EINVAL; ctxt = kzalloc(sizeof(*ctxt), GFP_KERNEL); if (!ctxt) return -ENOMEM; ice_save_vlan_info(&vsi->info, &vsi->vlan_info); ctxt->info = vsi->info; ctxt->info.sw_flags2 |= ICE_AQ_VSI_SW_FLAG_RX_VLAN_PRUNE_ENA; ctxt->info.port_based_outer_vlan = cpu_to_le16(vlan_info); ctxt->info.outer_vlan_flags = (ICE_AQ_VSI_OUTER_VLAN_EMODE_SHOW << ICE_AQ_VSI_OUTER_VLAN_EMODE_S) | ((tag_type << ICE_AQ_VSI_OUTER_TAG_TYPE_S) & ICE_AQ_VSI_OUTER_TAG_TYPE_M) | ICE_AQ_VSI_OUTER_VLAN_BLOCK_TX_DESC | (ICE_AQ_VSI_OUTER_VLAN_TX_MODE_ACCEPTUNTAGGED << ICE_AQ_VSI_OUTER_VLAN_TX_MODE_S) | ICE_AQ_VSI_OUTER_VLAN_PORT_BASED_INSERT; ctxt->info.valid_sections = cpu_to_le16(ICE_AQ_VSI_PROP_OUTER_TAG_VALID | ICE_AQ_VSI_PROP_SW_VALID); err = ice_update_vsi(hw, vsi->idx, ctxt, NULL); if (err) { dev_err(ice_pf_to_dev(vsi->back), "update VSI for setting outer port based VLAN failed, err %d aq_err %s\n", err, ice_aq_str(hw->adminq.sq_last_status)); } else { vsi->info.port_based_outer_vlan = ctxt->info.port_based_outer_vlan; vsi->info.outer_vlan_flags = ctxt->info.outer_vlan_flags; vsi->info.sw_flags2 = ctxt->info.sw_flags2; } kfree(ctxt); return err; } /** * ice_vsi_set_outer_port_vlan - public version of __ice_vsi_set_outer_port_vlan * @vsi: VSI to configure * @vlan: ice_vlan structure used to set the port VLAN * * Set the outer port VLAN via VSI context. This function should only be * used if DVM is supported. Also, this function should never be called directly * as it should be part of ice_vsi_vlan_ops if it's needed. * * Use the ice_vlan structure passed in to set this VSI in a port VLAN. */ int ice_vsi_set_outer_port_vlan(struct ice_vsi *vsi, struct ice_vlan *vlan) { u16 port_vlan_info; if (vlan->prio > (VLAN_PRIO_MASK >> VLAN_PRIO_SHIFT)) return -EINVAL; port_vlan_info = vlan->vid | (vlan->prio << VLAN_PRIO_SHIFT); return __ice_vsi_set_outer_port_vlan(vsi, port_vlan_info, vlan->tpid); } /** * ice_vsi_clear_outer_port_vlan - clear outer port vlan * @vsi: VSI to configure * * The function is restoring previously set vlan config (saved in * vsi->vlan_info). Setting happens in port vlan configuration. */ int ice_vsi_clear_outer_port_vlan(struct ice_vsi *vsi) { struct ice_hw *hw = &vsi->back->hw; struct ice_vsi_ctx *ctxt; int err; ctxt = kzalloc(sizeof(*ctxt), GFP_KERNEL); if (!ctxt) return -ENOMEM; ice_restore_vlan_info(&vsi->info, &vsi->vlan_info); vsi->info.port_based_outer_vlan = 0; ctxt->info = vsi->info; ctxt->info.valid_sections = cpu_to_le16(ICE_AQ_VSI_PROP_OUTER_TAG_VALID | ICE_AQ_VSI_PROP_SW_VALID); err = ice_update_vsi(hw, vsi->idx, ctxt, NULL); if (err) dev_err(ice_pf_to_dev(vsi->back), "update VSI for clearing outer port based VLAN failed, err %d aq_err %s\n", err, ice_aq_str(hw->adminq.sq_last_status)); kfree(ctxt); return err; }
linux-master
drivers/net/ethernet/intel/ice/ice_vsi_vlan_lib.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2019, Intel Corporation. */ #include "ice_common.h" #include "ice_flow.h" #include <net/gre.h> /* Describe properties of a protocol header field */ struct ice_flow_field_info { enum ice_flow_seg_hdr hdr; s16 off; /* Offset from start of a protocol header, in bits */ u16 size; /* Size of fields in bits */ u16 mask; /* 16-bit mask for field */ }; #define ICE_FLOW_FLD_INFO(_hdr, _offset_bytes, _size_bytes) { \ .hdr = _hdr, \ .off = (_offset_bytes) * BITS_PER_BYTE, \ .size = (_size_bytes) * BITS_PER_BYTE, \ .mask = 0, \ } #define ICE_FLOW_FLD_INFO_MSK(_hdr, _offset_bytes, _size_bytes, _mask) { \ .hdr = _hdr, \ .off = (_offset_bytes) * BITS_PER_BYTE, \ .size = (_size_bytes) * BITS_PER_BYTE, \ .mask = _mask, \ } /* Table containing properties of supported protocol header fields */ static const struct ice_flow_field_info ice_flds_info[ICE_FLOW_FIELD_IDX_MAX] = { /* Ether */ /* ICE_FLOW_FIELD_IDX_ETH_DA */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_ETH, 0, ETH_ALEN), /* ICE_FLOW_FIELD_IDX_ETH_SA */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_ETH, ETH_ALEN, ETH_ALEN), /* ICE_FLOW_FIELD_IDX_S_VLAN */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_VLAN, 12, sizeof(__be16)), /* ICE_FLOW_FIELD_IDX_C_VLAN */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_VLAN, 14, sizeof(__be16)), /* ICE_FLOW_FIELD_IDX_ETH_TYPE */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_ETH, 0, sizeof(__be16)), /* IPv4 / IPv6 */ /* ICE_FLOW_FIELD_IDX_IPV4_DSCP */ ICE_FLOW_FLD_INFO_MSK(ICE_FLOW_SEG_HDR_IPV4, 0, 1, 0x00fc), /* ICE_FLOW_FIELD_IDX_IPV6_DSCP */ ICE_FLOW_FLD_INFO_MSK(ICE_FLOW_SEG_HDR_IPV6, 0, 1, 0x0ff0), /* ICE_FLOW_FIELD_IDX_IPV4_TTL */ ICE_FLOW_FLD_INFO_MSK(ICE_FLOW_SEG_HDR_NONE, 8, 1, 0xff00), /* ICE_FLOW_FIELD_IDX_IPV4_PROT */ ICE_FLOW_FLD_INFO_MSK(ICE_FLOW_SEG_HDR_NONE, 8, 1, 0x00ff), /* ICE_FLOW_FIELD_IDX_IPV6_TTL */ ICE_FLOW_FLD_INFO_MSK(ICE_FLOW_SEG_HDR_NONE, 6, 1, 0x00ff), /* ICE_FLOW_FIELD_IDX_IPV6_PROT */ ICE_FLOW_FLD_INFO_MSK(ICE_FLOW_SEG_HDR_NONE, 6, 1, 0xff00), /* ICE_FLOW_FIELD_IDX_IPV4_SA */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_IPV4, 12, sizeof(struct in_addr)), /* ICE_FLOW_FIELD_IDX_IPV4_DA */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_IPV4, 16, sizeof(struct in_addr)), /* ICE_FLOW_FIELD_IDX_IPV6_SA */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_IPV6, 8, sizeof(struct in6_addr)), /* ICE_FLOW_FIELD_IDX_IPV6_DA */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_IPV6, 24, sizeof(struct in6_addr)), /* Transport */ /* ICE_FLOW_FIELD_IDX_TCP_SRC_PORT */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_TCP, 0, sizeof(__be16)), /* ICE_FLOW_FIELD_IDX_TCP_DST_PORT */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_TCP, 2, sizeof(__be16)), /* ICE_FLOW_FIELD_IDX_UDP_SRC_PORT */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_UDP, 0, sizeof(__be16)), /* ICE_FLOW_FIELD_IDX_UDP_DST_PORT */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_UDP, 2, sizeof(__be16)), /* ICE_FLOW_FIELD_IDX_SCTP_SRC_PORT */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_SCTP, 0, sizeof(__be16)), /* ICE_FLOW_FIELD_IDX_SCTP_DST_PORT */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_SCTP, 2, sizeof(__be16)), /* ICE_FLOW_FIELD_IDX_TCP_FLAGS */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_TCP, 13, 1), /* ARP */ /* ICE_FLOW_FIELD_IDX_ARP_SIP */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_ARP, 14, sizeof(struct in_addr)), /* ICE_FLOW_FIELD_IDX_ARP_DIP */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_ARP, 24, sizeof(struct in_addr)), /* ICE_FLOW_FIELD_IDX_ARP_SHA */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_ARP, 8, ETH_ALEN), /* ICE_FLOW_FIELD_IDX_ARP_DHA */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_ARP, 18, ETH_ALEN), /* ICE_FLOW_FIELD_IDX_ARP_OP */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_ARP, 6, sizeof(__be16)), /* ICMP */ /* ICE_FLOW_FIELD_IDX_ICMP_TYPE */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_ICMP, 0, 1), /* ICE_FLOW_FIELD_IDX_ICMP_CODE */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_ICMP, 1, 1), /* GRE */ /* ICE_FLOW_FIELD_IDX_GRE_KEYID */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_GRE, 12, sizeof_field(struct gre_full_hdr, key)), /* GTP */ /* ICE_FLOW_FIELD_IDX_GTPC_TEID */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_GTPC_TEID, 12, sizeof(__be32)), /* ICE_FLOW_FIELD_IDX_GTPU_IP_TEID */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_GTPU_IP, 12, sizeof(__be32)), /* ICE_FLOW_FIELD_IDX_GTPU_EH_TEID */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_GTPU_EH, 12, sizeof(__be32)), /* ICE_FLOW_FIELD_IDX_GTPU_EH_QFI */ ICE_FLOW_FLD_INFO_MSK(ICE_FLOW_SEG_HDR_GTPU_EH, 22, sizeof(__be16), 0x3f00), /* ICE_FLOW_FIELD_IDX_GTPU_UP_TEID */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_GTPU_UP, 12, sizeof(__be32)), /* ICE_FLOW_FIELD_IDX_GTPU_DWN_TEID */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_GTPU_DWN, 12, sizeof(__be32)), /* PPPoE */ /* ICE_FLOW_FIELD_IDX_PPPOE_SESS_ID */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_PPPOE, 2, sizeof(__be16)), /* PFCP */ /* ICE_FLOW_FIELD_IDX_PFCP_SEID */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_PFCP_SESSION, 12, sizeof(__be64)), /* L2TPv3 */ /* ICE_FLOW_FIELD_IDX_L2TPV3_SESS_ID */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_L2TPV3, 0, sizeof(__be32)), /* ESP */ /* ICE_FLOW_FIELD_IDX_ESP_SPI */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_ESP, 0, sizeof(__be32)), /* AH */ /* ICE_FLOW_FIELD_IDX_AH_SPI */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_AH, 4, sizeof(__be32)), /* NAT_T_ESP */ /* ICE_FLOW_FIELD_IDX_NAT_T_ESP_SPI */ ICE_FLOW_FLD_INFO(ICE_FLOW_SEG_HDR_NAT_T_ESP, 8, sizeof(__be32)), }; /* Bitmaps indicating relevant packet types for a particular protocol header * * Packet types for packets with an Outer/First/Single MAC header */ static const u32 ice_ptypes_mac_ofos[] = { 0xFDC00846, 0xBFBF7F7E, 0xF70001DF, 0xFEFDFDFB, 0x0000077E, 0x00000000, 0x00000000, 0x00000000, 0x00400000, 0x03FFF000, 0x7FFFFFE0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for packets with an Innermost/Last MAC VLAN header */ static const u32 ice_ptypes_macvlan_il[] = { 0x00000000, 0xBC000000, 0x000001DF, 0xF0000000, 0x0000077E, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for packets with an Outer/First/Single IPv4 header, does NOT * include IPv4 other PTYPEs */ static const u32 ice_ptypes_ipv4_ofos[] = { 0x1DC00000, 0x04000800, 0x00000000, 0x00000000, 0x00000000, 0x00000155, 0x00000000, 0x00000000, 0x00000000, 0x000FC000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for packets with an Outer/First/Single IPv4 header, includes * IPv4 other PTYPEs */ static const u32 ice_ptypes_ipv4_ofos_all[] = { 0x1DC00000, 0x04000800, 0x00000000, 0x00000000, 0x00000000, 0x00000155, 0x00000000, 0x00000000, 0x00000000, 0x000FC000, 0x83E0F800, 0x00000101, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for packets with an Innermost/Last IPv4 header */ static const u32 ice_ptypes_ipv4_il[] = { 0xE0000000, 0xB807700E, 0x80000003, 0xE01DC03B, 0x0000000E, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x001FF800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for packets with an Outer/First/Single IPv6 header, does NOT * include IPv6 other PTYPEs */ static const u32 ice_ptypes_ipv6_ofos[] = { 0x00000000, 0x00000000, 0x77000000, 0x10002000, 0x00000000, 0x000002AA, 0x00000000, 0x00000000, 0x00000000, 0x03F00000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for packets with an Outer/First/Single IPv6 header, includes * IPv6 other PTYPEs */ static const u32 ice_ptypes_ipv6_ofos_all[] = { 0x00000000, 0x00000000, 0x77000000, 0x10002000, 0x00000000, 0x000002AA, 0x00000000, 0x00000000, 0x00080F00, 0x03F00000, 0x7C1F0000, 0x00000206, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for packets with an Innermost/Last IPv6 header */ static const u32 ice_ptypes_ipv6_il[] = { 0x00000000, 0x03B80770, 0x000001DC, 0x0EE00000, 0x00000770, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x7FE00000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for packets with an Outer/First/Single IPv4 header - no L4 */ static const u32 ice_ptypes_ipv4_ofos_no_l4[] = { 0x10C00000, 0x04000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for packets with an Outermost/First ARP header */ static const u32 ice_ptypes_arp_of[] = { 0x00000800, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for packets with an Innermost/Last IPv4 header - no L4 */ static const u32 ice_ptypes_ipv4_il_no_l4[] = { 0x60000000, 0x18043008, 0x80000002, 0x6010c021, 0x00000008, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for packets with an Outer/First/Single IPv6 header - no L4 */ static const u32 ice_ptypes_ipv6_ofos_no_l4[] = { 0x00000000, 0x00000000, 0x43000000, 0x10002000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for packets with an Innermost/Last IPv6 header - no L4 */ static const u32 ice_ptypes_ipv6_il_no_l4[] = { 0x00000000, 0x02180430, 0x0000010c, 0x086010c0, 0x00000430, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* UDP Packet types for non-tunneled packets or tunneled * packets with inner UDP. */ static const u32 ice_ptypes_udp_il[] = { 0x81000000, 0x20204040, 0x04000010, 0x80810102, 0x00000040, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00410000, 0x90842000, 0x00000007, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for packets with an Innermost/Last TCP header */ static const u32 ice_ptypes_tcp_il[] = { 0x04000000, 0x80810102, 0x10000040, 0x02040408, 0x00000102, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00820000, 0x21084000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for packets with an Innermost/Last SCTP header */ static const u32 ice_ptypes_sctp_il[] = { 0x08000000, 0x01020204, 0x20000081, 0x04080810, 0x00000204, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01040000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for packets with an Outermost/First ICMP header */ static const u32 ice_ptypes_icmp_of[] = { 0x10000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for packets with an Innermost/Last ICMP header */ static const u32 ice_ptypes_icmp_il[] = { 0x00000000, 0x02040408, 0x40000102, 0x08101020, 0x00000408, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x42108000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for packets with an Outermost/First GRE header */ static const u32 ice_ptypes_gre_of[] = { 0x00000000, 0xBFBF7800, 0x000001DF, 0xFEFDE000, 0x0000017E, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for packets with an Innermost/Last MAC header */ static const u32 ice_ptypes_mac_il[] = { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for GTPC */ static const u32 ice_ptypes_gtpc[] = { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000180, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for GTPC with TEID */ static const u32 ice_ptypes_gtpc_tid[] = { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000060, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for GTPU */ static const struct ice_ptype_attributes ice_attr_gtpu_eh[] = { { ICE_MAC_IPV4_GTPU_IPV4_FRAG, ICE_PTYPE_ATTR_GTP_PDU_EH }, { ICE_MAC_IPV4_GTPU_IPV4_PAY, ICE_PTYPE_ATTR_GTP_PDU_EH }, { ICE_MAC_IPV4_GTPU_IPV4_UDP_PAY, ICE_PTYPE_ATTR_GTP_PDU_EH }, { ICE_MAC_IPV4_GTPU_IPV4_TCP, ICE_PTYPE_ATTR_GTP_PDU_EH }, { ICE_MAC_IPV4_GTPU_IPV4_ICMP, ICE_PTYPE_ATTR_GTP_PDU_EH }, { ICE_MAC_IPV6_GTPU_IPV4_FRAG, ICE_PTYPE_ATTR_GTP_PDU_EH }, { ICE_MAC_IPV6_GTPU_IPV4_PAY, ICE_PTYPE_ATTR_GTP_PDU_EH }, { ICE_MAC_IPV6_GTPU_IPV4_UDP_PAY, ICE_PTYPE_ATTR_GTP_PDU_EH }, { ICE_MAC_IPV6_GTPU_IPV4_TCP, ICE_PTYPE_ATTR_GTP_PDU_EH }, { ICE_MAC_IPV6_GTPU_IPV4_ICMP, ICE_PTYPE_ATTR_GTP_PDU_EH }, { ICE_MAC_IPV4_GTPU_IPV6_FRAG, ICE_PTYPE_ATTR_GTP_PDU_EH }, { ICE_MAC_IPV4_GTPU_IPV6_PAY, ICE_PTYPE_ATTR_GTP_PDU_EH }, { ICE_MAC_IPV4_GTPU_IPV6_UDP_PAY, ICE_PTYPE_ATTR_GTP_PDU_EH }, { ICE_MAC_IPV4_GTPU_IPV6_TCP, ICE_PTYPE_ATTR_GTP_PDU_EH }, { ICE_MAC_IPV4_GTPU_IPV6_ICMPV6, ICE_PTYPE_ATTR_GTP_PDU_EH }, { ICE_MAC_IPV6_GTPU_IPV6_FRAG, ICE_PTYPE_ATTR_GTP_PDU_EH }, { ICE_MAC_IPV6_GTPU_IPV6_PAY, ICE_PTYPE_ATTR_GTP_PDU_EH }, { ICE_MAC_IPV6_GTPU_IPV6_UDP_PAY, ICE_PTYPE_ATTR_GTP_PDU_EH }, { ICE_MAC_IPV6_GTPU_IPV6_TCP, ICE_PTYPE_ATTR_GTP_PDU_EH }, { ICE_MAC_IPV6_GTPU_IPV6_ICMPV6, ICE_PTYPE_ATTR_GTP_PDU_EH }, }; static const struct ice_ptype_attributes ice_attr_gtpu_down[] = { { ICE_MAC_IPV4_GTPU_IPV4_FRAG, ICE_PTYPE_ATTR_GTP_DOWNLINK }, { ICE_MAC_IPV4_GTPU_IPV4_PAY, ICE_PTYPE_ATTR_GTP_DOWNLINK }, { ICE_MAC_IPV4_GTPU_IPV4_UDP_PAY, ICE_PTYPE_ATTR_GTP_DOWNLINK }, { ICE_MAC_IPV4_GTPU_IPV4_TCP, ICE_PTYPE_ATTR_GTP_DOWNLINK }, { ICE_MAC_IPV4_GTPU_IPV4_ICMP, ICE_PTYPE_ATTR_GTP_DOWNLINK }, { ICE_MAC_IPV6_GTPU_IPV4_FRAG, ICE_PTYPE_ATTR_GTP_DOWNLINK }, { ICE_MAC_IPV6_GTPU_IPV4_PAY, ICE_PTYPE_ATTR_GTP_DOWNLINK }, { ICE_MAC_IPV6_GTPU_IPV4_UDP_PAY, ICE_PTYPE_ATTR_GTP_DOWNLINK }, { ICE_MAC_IPV6_GTPU_IPV4_TCP, ICE_PTYPE_ATTR_GTP_DOWNLINK }, { ICE_MAC_IPV6_GTPU_IPV4_ICMP, ICE_PTYPE_ATTR_GTP_DOWNLINK }, { ICE_MAC_IPV4_GTPU_IPV6_FRAG, ICE_PTYPE_ATTR_GTP_DOWNLINK }, { ICE_MAC_IPV4_GTPU_IPV6_PAY, ICE_PTYPE_ATTR_GTP_DOWNLINK }, { ICE_MAC_IPV4_GTPU_IPV6_UDP_PAY, ICE_PTYPE_ATTR_GTP_DOWNLINK }, { ICE_MAC_IPV4_GTPU_IPV6_TCP, ICE_PTYPE_ATTR_GTP_DOWNLINK }, { ICE_MAC_IPV4_GTPU_IPV6_ICMPV6, ICE_PTYPE_ATTR_GTP_DOWNLINK }, { ICE_MAC_IPV6_GTPU_IPV6_FRAG, ICE_PTYPE_ATTR_GTP_DOWNLINK }, { ICE_MAC_IPV6_GTPU_IPV6_PAY, ICE_PTYPE_ATTR_GTP_DOWNLINK }, { ICE_MAC_IPV6_GTPU_IPV6_UDP_PAY, ICE_PTYPE_ATTR_GTP_DOWNLINK }, { ICE_MAC_IPV6_GTPU_IPV6_TCP, ICE_PTYPE_ATTR_GTP_DOWNLINK }, { ICE_MAC_IPV6_GTPU_IPV6_ICMPV6, ICE_PTYPE_ATTR_GTP_DOWNLINK }, }; static const struct ice_ptype_attributes ice_attr_gtpu_up[] = { { ICE_MAC_IPV4_GTPU_IPV4_FRAG, ICE_PTYPE_ATTR_GTP_UPLINK }, { ICE_MAC_IPV4_GTPU_IPV4_PAY, ICE_PTYPE_ATTR_GTP_UPLINK }, { ICE_MAC_IPV4_GTPU_IPV4_UDP_PAY, ICE_PTYPE_ATTR_GTP_UPLINK }, { ICE_MAC_IPV4_GTPU_IPV4_TCP, ICE_PTYPE_ATTR_GTP_UPLINK }, { ICE_MAC_IPV4_GTPU_IPV4_ICMP, ICE_PTYPE_ATTR_GTP_UPLINK }, { ICE_MAC_IPV6_GTPU_IPV4_FRAG, ICE_PTYPE_ATTR_GTP_UPLINK }, { ICE_MAC_IPV6_GTPU_IPV4_PAY, ICE_PTYPE_ATTR_GTP_UPLINK }, { ICE_MAC_IPV6_GTPU_IPV4_UDP_PAY, ICE_PTYPE_ATTR_GTP_UPLINK }, { ICE_MAC_IPV6_GTPU_IPV4_TCP, ICE_PTYPE_ATTR_GTP_UPLINK }, { ICE_MAC_IPV6_GTPU_IPV4_ICMP, ICE_PTYPE_ATTR_GTP_UPLINK }, { ICE_MAC_IPV4_GTPU_IPV6_FRAG, ICE_PTYPE_ATTR_GTP_UPLINK }, { ICE_MAC_IPV4_GTPU_IPV6_PAY, ICE_PTYPE_ATTR_GTP_UPLINK }, { ICE_MAC_IPV4_GTPU_IPV6_UDP_PAY, ICE_PTYPE_ATTR_GTP_UPLINK }, { ICE_MAC_IPV4_GTPU_IPV6_TCP, ICE_PTYPE_ATTR_GTP_UPLINK }, { ICE_MAC_IPV4_GTPU_IPV6_ICMPV6, ICE_PTYPE_ATTR_GTP_UPLINK }, { ICE_MAC_IPV6_GTPU_IPV6_FRAG, ICE_PTYPE_ATTR_GTP_UPLINK }, { ICE_MAC_IPV6_GTPU_IPV6_PAY, ICE_PTYPE_ATTR_GTP_UPLINK }, { ICE_MAC_IPV6_GTPU_IPV6_UDP_PAY, ICE_PTYPE_ATTR_GTP_UPLINK }, { ICE_MAC_IPV6_GTPU_IPV6_TCP, ICE_PTYPE_ATTR_GTP_UPLINK }, { ICE_MAC_IPV6_GTPU_IPV6_ICMPV6, ICE_PTYPE_ATTR_GTP_UPLINK }, }; static const u32 ice_ptypes_gtpu[] = { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x7FFFFE00, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for PPPoE */ static const u32 ice_ptypes_pppoe[] = { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x03ffe000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for packets with PFCP NODE header */ static const u32 ice_ptypes_pfcp_node[] = { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x80000000, 0x00000002, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for packets with PFCP SESSION header */ static const u32 ice_ptypes_pfcp_session[] = { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000005, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for L2TPv3 */ static const u32 ice_ptypes_l2tpv3[] = { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000300, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for ESP */ static const u32 ice_ptypes_esp[] = { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000003, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for AH */ static const u32 ice_ptypes_ah[] = { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x0000000C, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Packet types for packets with NAT_T ESP header */ static const u32 ice_ptypes_nat_t_esp[] = { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000030, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; static const u32 ice_ptypes_mac_non_ip_ofos[] = { 0x00000846, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00400000, 0x03FFF000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; /* Manage parameters and info. used during the creation of a flow profile */ struct ice_flow_prof_params { enum ice_block blk; u16 entry_length; /* # of bytes formatted entry will require */ u8 es_cnt; struct ice_flow_prof *prof; /* For ACL, the es[0] will have the data of ICE_RX_MDID_PKT_FLAGS_15_0 * This will give us the direction flags. */ struct ice_fv_word es[ICE_MAX_FV_WORDS]; /* attributes can be used to add attributes to a particular PTYPE */ const struct ice_ptype_attributes *attr; u16 attr_cnt; u16 mask[ICE_MAX_FV_WORDS]; DECLARE_BITMAP(ptypes, ICE_FLOW_PTYPE_MAX); }; #define ICE_FLOW_RSS_HDRS_INNER_MASK \ (ICE_FLOW_SEG_HDR_PPPOE | ICE_FLOW_SEG_HDR_GTPC | \ ICE_FLOW_SEG_HDR_GTPC_TEID | ICE_FLOW_SEG_HDR_GTPU | \ ICE_FLOW_SEG_HDR_PFCP_SESSION | ICE_FLOW_SEG_HDR_L2TPV3 | \ ICE_FLOW_SEG_HDR_ESP | ICE_FLOW_SEG_HDR_AH | \ ICE_FLOW_SEG_HDR_NAT_T_ESP) #define ICE_FLOW_SEG_HDRS_L3_MASK \ (ICE_FLOW_SEG_HDR_IPV4 | ICE_FLOW_SEG_HDR_IPV6 | ICE_FLOW_SEG_HDR_ARP) #define ICE_FLOW_SEG_HDRS_L4_MASK \ (ICE_FLOW_SEG_HDR_ICMP | ICE_FLOW_SEG_HDR_TCP | ICE_FLOW_SEG_HDR_UDP | \ ICE_FLOW_SEG_HDR_SCTP) /* mask for L4 protocols that are NOT part of IPv4/6 OTHER PTYPE groups */ #define ICE_FLOW_SEG_HDRS_L4_MASK_NO_OTHER \ (ICE_FLOW_SEG_HDR_TCP | ICE_FLOW_SEG_HDR_UDP | ICE_FLOW_SEG_HDR_SCTP) /** * ice_flow_val_hdrs - validates packet segments for valid protocol headers * @segs: array of one or more packet segments that describe the flow * @segs_cnt: number of packet segments provided */ static int ice_flow_val_hdrs(struct ice_flow_seg_info *segs, u8 segs_cnt) { u8 i; for (i = 0; i < segs_cnt; i++) { /* Multiple L3 headers */ if (segs[i].hdrs & ICE_FLOW_SEG_HDRS_L3_MASK && !is_power_of_2(segs[i].hdrs & ICE_FLOW_SEG_HDRS_L3_MASK)) return -EINVAL; /* Multiple L4 headers */ if (segs[i].hdrs & ICE_FLOW_SEG_HDRS_L4_MASK && !is_power_of_2(segs[i].hdrs & ICE_FLOW_SEG_HDRS_L4_MASK)) return -EINVAL; } return 0; } /* Sizes of fixed known protocol headers without header options */ #define ICE_FLOW_PROT_HDR_SZ_MAC 14 #define ICE_FLOW_PROT_HDR_SZ_MAC_VLAN (ICE_FLOW_PROT_HDR_SZ_MAC + 2) #define ICE_FLOW_PROT_HDR_SZ_IPV4 20 #define ICE_FLOW_PROT_HDR_SZ_IPV6 40 #define ICE_FLOW_PROT_HDR_SZ_ARP 28 #define ICE_FLOW_PROT_HDR_SZ_ICMP 8 #define ICE_FLOW_PROT_HDR_SZ_TCP 20 #define ICE_FLOW_PROT_HDR_SZ_UDP 8 #define ICE_FLOW_PROT_HDR_SZ_SCTP 12 /** * ice_flow_calc_seg_sz - calculates size of a packet segment based on headers * @params: information about the flow to be processed * @seg: index of packet segment whose header size is to be determined */ static u16 ice_flow_calc_seg_sz(struct ice_flow_prof_params *params, u8 seg) { u16 sz; /* L2 headers */ sz = (params->prof->segs[seg].hdrs & ICE_FLOW_SEG_HDR_VLAN) ? ICE_FLOW_PROT_HDR_SZ_MAC_VLAN : ICE_FLOW_PROT_HDR_SZ_MAC; /* L3 headers */ if (params->prof->segs[seg].hdrs & ICE_FLOW_SEG_HDR_IPV4) sz += ICE_FLOW_PROT_HDR_SZ_IPV4; else if (params->prof->segs[seg].hdrs & ICE_FLOW_SEG_HDR_IPV6) sz += ICE_FLOW_PROT_HDR_SZ_IPV6; else if (params->prof->segs[seg].hdrs & ICE_FLOW_SEG_HDR_ARP) sz += ICE_FLOW_PROT_HDR_SZ_ARP; else if (params->prof->segs[seg].hdrs & ICE_FLOW_SEG_HDRS_L4_MASK) /* An L3 header is required if L4 is specified */ return 0; /* L4 headers */ if (params->prof->segs[seg].hdrs & ICE_FLOW_SEG_HDR_ICMP) sz += ICE_FLOW_PROT_HDR_SZ_ICMP; else if (params->prof->segs[seg].hdrs & ICE_FLOW_SEG_HDR_TCP) sz += ICE_FLOW_PROT_HDR_SZ_TCP; else if (params->prof->segs[seg].hdrs & ICE_FLOW_SEG_HDR_UDP) sz += ICE_FLOW_PROT_HDR_SZ_UDP; else if (params->prof->segs[seg].hdrs & ICE_FLOW_SEG_HDR_SCTP) sz += ICE_FLOW_PROT_HDR_SZ_SCTP; return sz; } /** * ice_flow_proc_seg_hdrs - process protocol headers present in pkt segments * @params: information about the flow to be processed * * This function identifies the packet types associated with the protocol * headers being present in packet segments of the specified flow profile. */ static int ice_flow_proc_seg_hdrs(struct ice_flow_prof_params *params) { struct ice_flow_prof *prof; u8 i; memset(params->ptypes, 0xff, sizeof(params->ptypes)); prof = params->prof; for (i = 0; i < params->prof->segs_cnt; i++) { const unsigned long *src; u32 hdrs; hdrs = prof->segs[i].hdrs; if (hdrs & ICE_FLOW_SEG_HDR_ETH) { src = !i ? (const unsigned long *)ice_ptypes_mac_ofos : (const unsigned long *)ice_ptypes_mac_il; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } if (i && hdrs & ICE_FLOW_SEG_HDR_VLAN) { src = (const unsigned long *)ice_ptypes_macvlan_il; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } if (!i && hdrs & ICE_FLOW_SEG_HDR_ARP) { bitmap_and(params->ptypes, params->ptypes, (const unsigned long *)ice_ptypes_arp_of, ICE_FLOW_PTYPE_MAX); } if ((hdrs & ICE_FLOW_SEG_HDR_IPV4) && (hdrs & ICE_FLOW_SEG_HDR_IPV_OTHER)) { src = i ? (const unsigned long *)ice_ptypes_ipv4_il : (const unsigned long *)ice_ptypes_ipv4_ofos_all; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } else if ((hdrs & ICE_FLOW_SEG_HDR_IPV6) && (hdrs & ICE_FLOW_SEG_HDR_IPV_OTHER)) { src = i ? (const unsigned long *)ice_ptypes_ipv6_il : (const unsigned long *)ice_ptypes_ipv6_ofos_all; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } else if ((hdrs & ICE_FLOW_SEG_HDR_IPV4) && !(hdrs & ICE_FLOW_SEG_HDRS_L4_MASK_NO_OTHER)) { src = !i ? (const unsigned long *)ice_ptypes_ipv4_ofos_no_l4 : (const unsigned long *)ice_ptypes_ipv4_il_no_l4; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } else if (hdrs & ICE_FLOW_SEG_HDR_IPV4) { src = !i ? (const unsigned long *)ice_ptypes_ipv4_ofos : (const unsigned long *)ice_ptypes_ipv4_il; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } else if ((hdrs & ICE_FLOW_SEG_HDR_IPV6) && !(hdrs & ICE_FLOW_SEG_HDRS_L4_MASK_NO_OTHER)) { src = !i ? (const unsigned long *)ice_ptypes_ipv6_ofos_no_l4 : (const unsigned long *)ice_ptypes_ipv6_il_no_l4; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } else if (hdrs & ICE_FLOW_SEG_HDR_IPV6) { src = !i ? (const unsigned long *)ice_ptypes_ipv6_ofos : (const unsigned long *)ice_ptypes_ipv6_il; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } if (hdrs & ICE_FLOW_SEG_HDR_ETH_NON_IP) { src = (const unsigned long *)ice_ptypes_mac_non_ip_ofos; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } else if (hdrs & ICE_FLOW_SEG_HDR_PPPOE) { src = (const unsigned long *)ice_ptypes_pppoe; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } else { src = (const unsigned long *)ice_ptypes_pppoe; bitmap_andnot(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } if (hdrs & ICE_FLOW_SEG_HDR_UDP) { src = (const unsigned long *)ice_ptypes_udp_il; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } else if (hdrs & ICE_FLOW_SEG_HDR_TCP) { bitmap_and(params->ptypes, params->ptypes, (const unsigned long *)ice_ptypes_tcp_il, ICE_FLOW_PTYPE_MAX); } else if (hdrs & ICE_FLOW_SEG_HDR_SCTP) { src = (const unsigned long *)ice_ptypes_sctp_il; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } if (hdrs & ICE_FLOW_SEG_HDR_ICMP) { src = !i ? (const unsigned long *)ice_ptypes_icmp_of : (const unsigned long *)ice_ptypes_icmp_il; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } else if (hdrs & ICE_FLOW_SEG_HDR_GRE) { if (!i) { src = (const unsigned long *)ice_ptypes_gre_of; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } } else if (hdrs & ICE_FLOW_SEG_HDR_GTPC) { src = (const unsigned long *)ice_ptypes_gtpc; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } else if (hdrs & ICE_FLOW_SEG_HDR_GTPC_TEID) { src = (const unsigned long *)ice_ptypes_gtpc_tid; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } else if (hdrs & ICE_FLOW_SEG_HDR_GTPU_DWN) { src = (const unsigned long *)ice_ptypes_gtpu; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); /* Attributes for GTP packet with downlink */ params->attr = ice_attr_gtpu_down; params->attr_cnt = ARRAY_SIZE(ice_attr_gtpu_down); } else if (hdrs & ICE_FLOW_SEG_HDR_GTPU_UP) { src = (const unsigned long *)ice_ptypes_gtpu; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); /* Attributes for GTP packet with uplink */ params->attr = ice_attr_gtpu_up; params->attr_cnt = ARRAY_SIZE(ice_attr_gtpu_up); } else if (hdrs & ICE_FLOW_SEG_HDR_GTPU_EH) { src = (const unsigned long *)ice_ptypes_gtpu; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); /* Attributes for GTP packet with Extension Header */ params->attr = ice_attr_gtpu_eh; params->attr_cnt = ARRAY_SIZE(ice_attr_gtpu_eh); } else if (hdrs & ICE_FLOW_SEG_HDR_GTPU_IP) { src = (const unsigned long *)ice_ptypes_gtpu; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } else if (hdrs & ICE_FLOW_SEG_HDR_L2TPV3) { src = (const unsigned long *)ice_ptypes_l2tpv3; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } else if (hdrs & ICE_FLOW_SEG_HDR_ESP) { src = (const unsigned long *)ice_ptypes_esp; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } else if (hdrs & ICE_FLOW_SEG_HDR_AH) { src = (const unsigned long *)ice_ptypes_ah; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } else if (hdrs & ICE_FLOW_SEG_HDR_NAT_T_ESP) { src = (const unsigned long *)ice_ptypes_nat_t_esp; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } if (hdrs & ICE_FLOW_SEG_HDR_PFCP) { if (hdrs & ICE_FLOW_SEG_HDR_PFCP_NODE) src = (const unsigned long *)ice_ptypes_pfcp_node; else src = (const unsigned long *)ice_ptypes_pfcp_session; bitmap_and(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } else { src = (const unsigned long *)ice_ptypes_pfcp_node; bitmap_andnot(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); src = (const unsigned long *)ice_ptypes_pfcp_session; bitmap_andnot(params->ptypes, params->ptypes, src, ICE_FLOW_PTYPE_MAX); } } return 0; } /** * ice_flow_xtract_fld - Create an extraction sequence entry for the given field * @hw: pointer to the HW struct * @params: information about the flow to be processed * @seg: packet segment index of the field to be extracted * @fld: ID of field to be extracted * @match: bit field of all fields * * This function determines the protocol ID, offset, and size of the given * field. It then allocates one or more extraction sequence entries for the * given field, and fill the entries with protocol ID and offset information. */ static int ice_flow_xtract_fld(struct ice_hw *hw, struct ice_flow_prof_params *params, u8 seg, enum ice_flow_field fld, u64 match) { enum ice_flow_field sib = ICE_FLOW_FIELD_IDX_MAX; enum ice_prot_id prot_id = ICE_PROT_ID_INVAL; u8 fv_words = hw->blk[params->blk].es.fvw; struct ice_flow_fld_info *flds; u16 cnt, ese_bits, i; u16 sib_mask = 0; u16 mask; u16 off; flds = params->prof->segs[seg].fields; switch (fld) { case ICE_FLOW_FIELD_IDX_ETH_DA: case ICE_FLOW_FIELD_IDX_ETH_SA: case ICE_FLOW_FIELD_IDX_S_VLAN: case ICE_FLOW_FIELD_IDX_C_VLAN: prot_id = seg == 0 ? ICE_PROT_MAC_OF_OR_S : ICE_PROT_MAC_IL; break; case ICE_FLOW_FIELD_IDX_ETH_TYPE: prot_id = seg == 0 ? ICE_PROT_ETYPE_OL : ICE_PROT_ETYPE_IL; break; case ICE_FLOW_FIELD_IDX_IPV4_DSCP: prot_id = seg == 0 ? ICE_PROT_IPV4_OF_OR_S : ICE_PROT_IPV4_IL; break; case ICE_FLOW_FIELD_IDX_IPV6_DSCP: prot_id = seg == 0 ? ICE_PROT_IPV6_OF_OR_S : ICE_PROT_IPV6_IL; break; case ICE_FLOW_FIELD_IDX_IPV4_TTL: case ICE_FLOW_FIELD_IDX_IPV4_PROT: prot_id = seg == 0 ? ICE_PROT_IPV4_OF_OR_S : ICE_PROT_IPV4_IL; /* TTL and PROT share the same extraction seq. entry. * Each is considered a sibling to the other in terms of sharing * the same extraction sequence entry. */ if (fld == ICE_FLOW_FIELD_IDX_IPV4_TTL) sib = ICE_FLOW_FIELD_IDX_IPV4_PROT; else if (fld == ICE_FLOW_FIELD_IDX_IPV4_PROT) sib = ICE_FLOW_FIELD_IDX_IPV4_TTL; /* If the sibling field is also included, that field's * mask needs to be included. */ if (match & BIT(sib)) sib_mask = ice_flds_info[sib].mask; break; case ICE_FLOW_FIELD_IDX_IPV6_TTL: case ICE_FLOW_FIELD_IDX_IPV6_PROT: prot_id = seg == 0 ? ICE_PROT_IPV6_OF_OR_S : ICE_PROT_IPV6_IL; /* TTL and PROT share the same extraction seq. entry. * Each is considered a sibling to the other in terms of sharing * the same extraction sequence entry. */ if (fld == ICE_FLOW_FIELD_IDX_IPV6_TTL) sib = ICE_FLOW_FIELD_IDX_IPV6_PROT; else if (fld == ICE_FLOW_FIELD_IDX_IPV6_PROT) sib = ICE_FLOW_FIELD_IDX_IPV6_TTL; /* If the sibling field is also included, that field's * mask needs to be included. */ if (match & BIT(sib)) sib_mask = ice_flds_info[sib].mask; break; case ICE_FLOW_FIELD_IDX_IPV4_SA: case ICE_FLOW_FIELD_IDX_IPV4_DA: prot_id = seg == 0 ? ICE_PROT_IPV4_OF_OR_S : ICE_PROT_IPV4_IL; break; case ICE_FLOW_FIELD_IDX_IPV6_SA: case ICE_FLOW_FIELD_IDX_IPV6_DA: prot_id = seg == 0 ? ICE_PROT_IPV6_OF_OR_S : ICE_PROT_IPV6_IL; break; case ICE_FLOW_FIELD_IDX_TCP_SRC_PORT: case ICE_FLOW_FIELD_IDX_TCP_DST_PORT: case ICE_FLOW_FIELD_IDX_TCP_FLAGS: prot_id = ICE_PROT_TCP_IL; break; case ICE_FLOW_FIELD_IDX_UDP_SRC_PORT: case ICE_FLOW_FIELD_IDX_UDP_DST_PORT: prot_id = ICE_PROT_UDP_IL_OR_S; break; case ICE_FLOW_FIELD_IDX_SCTP_SRC_PORT: case ICE_FLOW_FIELD_IDX_SCTP_DST_PORT: prot_id = ICE_PROT_SCTP_IL; break; case ICE_FLOW_FIELD_IDX_GTPC_TEID: case ICE_FLOW_FIELD_IDX_GTPU_IP_TEID: case ICE_FLOW_FIELD_IDX_GTPU_UP_TEID: case ICE_FLOW_FIELD_IDX_GTPU_DWN_TEID: case ICE_FLOW_FIELD_IDX_GTPU_EH_TEID: case ICE_FLOW_FIELD_IDX_GTPU_EH_QFI: /* GTP is accessed through UDP OF protocol */ prot_id = ICE_PROT_UDP_OF; break; case ICE_FLOW_FIELD_IDX_PPPOE_SESS_ID: prot_id = ICE_PROT_PPPOE; break; case ICE_FLOW_FIELD_IDX_PFCP_SEID: prot_id = ICE_PROT_UDP_IL_OR_S; break; case ICE_FLOW_FIELD_IDX_L2TPV3_SESS_ID: prot_id = ICE_PROT_L2TPV3; break; case ICE_FLOW_FIELD_IDX_ESP_SPI: prot_id = ICE_PROT_ESP_F; break; case ICE_FLOW_FIELD_IDX_AH_SPI: prot_id = ICE_PROT_ESP_2; break; case ICE_FLOW_FIELD_IDX_NAT_T_ESP_SPI: prot_id = ICE_PROT_UDP_IL_OR_S; break; case ICE_FLOW_FIELD_IDX_ARP_SIP: case ICE_FLOW_FIELD_IDX_ARP_DIP: case ICE_FLOW_FIELD_IDX_ARP_SHA: case ICE_FLOW_FIELD_IDX_ARP_DHA: case ICE_FLOW_FIELD_IDX_ARP_OP: prot_id = ICE_PROT_ARP_OF; break; case ICE_FLOW_FIELD_IDX_ICMP_TYPE: case ICE_FLOW_FIELD_IDX_ICMP_CODE: /* ICMP type and code share the same extraction seq. entry */ prot_id = (params->prof->segs[seg].hdrs & ICE_FLOW_SEG_HDR_IPV4) ? ICE_PROT_ICMP_IL : ICE_PROT_ICMPV6_IL; sib = fld == ICE_FLOW_FIELD_IDX_ICMP_TYPE ? ICE_FLOW_FIELD_IDX_ICMP_CODE : ICE_FLOW_FIELD_IDX_ICMP_TYPE; break; case ICE_FLOW_FIELD_IDX_GRE_KEYID: prot_id = ICE_PROT_GRE_OF; break; default: return -EOPNOTSUPP; } /* Each extraction sequence entry is a word in size, and extracts a * word-aligned offset from a protocol header. */ ese_bits = ICE_FLOW_FV_EXTRACT_SZ * BITS_PER_BYTE; flds[fld].xtrct.prot_id = prot_id; flds[fld].xtrct.off = (ice_flds_info[fld].off / ese_bits) * ICE_FLOW_FV_EXTRACT_SZ; flds[fld].xtrct.disp = (u8)(ice_flds_info[fld].off % ese_bits); flds[fld].xtrct.idx = params->es_cnt; flds[fld].xtrct.mask = ice_flds_info[fld].mask; /* Adjust the next field-entry index after accommodating the number of * entries this field consumes */ cnt = DIV_ROUND_UP(flds[fld].xtrct.disp + ice_flds_info[fld].size, ese_bits); /* Fill in the extraction sequence entries needed for this field */ off = flds[fld].xtrct.off; mask = flds[fld].xtrct.mask; for (i = 0; i < cnt; i++) { /* Only consume an extraction sequence entry if there is no * sibling field associated with this field or the sibling entry * already extracts the word shared with this field. */ if (sib == ICE_FLOW_FIELD_IDX_MAX || flds[sib].xtrct.prot_id == ICE_PROT_ID_INVAL || flds[sib].xtrct.off != off) { u8 idx; /* Make sure the number of extraction sequence required * does not exceed the block's capability */ if (params->es_cnt >= fv_words) return -ENOSPC; /* some blocks require a reversed field vector layout */ if (hw->blk[params->blk].es.reverse) idx = fv_words - params->es_cnt - 1; else idx = params->es_cnt; params->es[idx].prot_id = prot_id; params->es[idx].off = off; params->mask[idx] = mask | sib_mask; params->es_cnt++; } off += ICE_FLOW_FV_EXTRACT_SZ; } return 0; } /** * ice_flow_xtract_raws - Create extract sequence entries for raw bytes * @hw: pointer to the HW struct * @params: information about the flow to be processed * @seg: index of packet segment whose raw fields are to be extracted */ static int ice_flow_xtract_raws(struct ice_hw *hw, struct ice_flow_prof_params *params, u8 seg) { u16 fv_words; u16 hdrs_sz; u8 i; if (!params->prof->segs[seg].raws_cnt) return 0; if (params->prof->segs[seg].raws_cnt > ARRAY_SIZE(params->prof->segs[seg].raws)) return -ENOSPC; /* Offsets within the segment headers are not supported */ hdrs_sz = ice_flow_calc_seg_sz(params, seg); if (!hdrs_sz) return -EINVAL; fv_words = hw->blk[params->blk].es.fvw; for (i = 0; i < params->prof->segs[seg].raws_cnt; i++) { struct ice_flow_seg_fld_raw *raw; u16 off, cnt, j; raw = &params->prof->segs[seg].raws[i]; /* Storing extraction information */ raw->info.xtrct.prot_id = ICE_PROT_MAC_OF_OR_S; raw->info.xtrct.off = (raw->off / ICE_FLOW_FV_EXTRACT_SZ) * ICE_FLOW_FV_EXTRACT_SZ; raw->info.xtrct.disp = (raw->off % ICE_FLOW_FV_EXTRACT_SZ) * BITS_PER_BYTE; raw->info.xtrct.idx = params->es_cnt; /* Determine the number of field vector entries this raw field * consumes. */ cnt = DIV_ROUND_UP(raw->info.xtrct.disp + (raw->info.src.last * BITS_PER_BYTE), (ICE_FLOW_FV_EXTRACT_SZ * BITS_PER_BYTE)); off = raw->info.xtrct.off; for (j = 0; j < cnt; j++) { u16 idx; /* Make sure the number of extraction sequence required * does not exceed the block's capability */ if (params->es_cnt >= hw->blk[params->blk].es.count || params->es_cnt >= ICE_MAX_FV_WORDS) return -ENOSPC; /* some blocks require a reversed field vector layout */ if (hw->blk[params->blk].es.reverse) idx = fv_words - params->es_cnt - 1; else idx = params->es_cnt; params->es[idx].prot_id = raw->info.xtrct.prot_id; params->es[idx].off = off; params->es_cnt++; off += ICE_FLOW_FV_EXTRACT_SZ; } } return 0; } /** * ice_flow_create_xtrct_seq - Create an extraction sequence for given segments * @hw: pointer to the HW struct * @params: information about the flow to be processed * * This function iterates through all matched fields in the given segments, and * creates an extraction sequence for the fields. */ static int ice_flow_create_xtrct_seq(struct ice_hw *hw, struct ice_flow_prof_params *params) { struct ice_flow_prof *prof = params->prof; int status = 0; u8 i; for (i = 0; i < prof->segs_cnt; i++) { u64 match = params->prof->segs[i].match; enum ice_flow_field j; for_each_set_bit(j, (unsigned long *)&match, ICE_FLOW_FIELD_IDX_MAX) { status = ice_flow_xtract_fld(hw, params, i, j, match); if (status) return status; clear_bit(j, (unsigned long *)&match); } /* Process raw matching bytes */ status = ice_flow_xtract_raws(hw, params, i); if (status) return status; } return status; } /** * ice_flow_proc_segs - process all packet segments associated with a profile * @hw: pointer to the HW struct * @params: information about the flow to be processed */ static int ice_flow_proc_segs(struct ice_hw *hw, struct ice_flow_prof_params *params) { int status; status = ice_flow_proc_seg_hdrs(params); if (status) return status; status = ice_flow_create_xtrct_seq(hw, params); if (status) return status; switch (params->blk) { case ICE_BLK_FD: case ICE_BLK_RSS: status = 0; break; default: return -EOPNOTSUPP; } return status; } #define ICE_FLOW_FIND_PROF_CHK_FLDS 0x00000001 #define ICE_FLOW_FIND_PROF_CHK_VSI 0x00000002 #define ICE_FLOW_FIND_PROF_NOT_CHK_DIR 0x00000004 /** * ice_flow_find_prof_conds - Find a profile matching headers and conditions * @hw: pointer to the HW struct * @blk: classification stage * @dir: flow direction * @segs: array of one or more packet segments that describe the flow * @segs_cnt: number of packet segments provided * @vsi_handle: software VSI handle to check VSI (ICE_FLOW_FIND_PROF_CHK_VSI) * @conds: additional conditions to be checked (ICE_FLOW_FIND_PROF_CHK_*) */ static struct ice_flow_prof * ice_flow_find_prof_conds(struct ice_hw *hw, enum ice_block blk, enum ice_flow_dir dir, struct ice_flow_seg_info *segs, u8 segs_cnt, u16 vsi_handle, u32 conds) { struct ice_flow_prof *p, *prof = NULL; mutex_lock(&hw->fl_profs_locks[blk]); list_for_each_entry(p, &hw->fl_profs[blk], l_entry) if ((p->dir == dir || conds & ICE_FLOW_FIND_PROF_NOT_CHK_DIR) && segs_cnt && segs_cnt == p->segs_cnt) { u8 i; /* Check for profile-VSI association if specified */ if ((conds & ICE_FLOW_FIND_PROF_CHK_VSI) && ice_is_vsi_valid(hw, vsi_handle) && !test_bit(vsi_handle, p->vsis)) continue; /* Protocol headers must be checked. Matched fields are * checked if specified. */ for (i = 0; i < segs_cnt; i++) if (segs[i].hdrs != p->segs[i].hdrs || ((conds & ICE_FLOW_FIND_PROF_CHK_FLDS) && segs[i].match != p->segs[i].match)) break; /* A match is found if all segments are matched */ if (i == segs_cnt) { prof = p; break; } } mutex_unlock(&hw->fl_profs_locks[blk]); return prof; } /** * ice_flow_find_prof_id - Look up a profile with given profile ID * @hw: pointer to the HW struct * @blk: classification stage * @prof_id: unique ID to identify this flow profile */ static struct ice_flow_prof * ice_flow_find_prof_id(struct ice_hw *hw, enum ice_block blk, u64 prof_id) { struct ice_flow_prof *p; list_for_each_entry(p, &hw->fl_profs[blk], l_entry) if (p->id == prof_id) return p; return NULL; } /** * ice_flow_rem_entry_sync - Remove a flow entry * @hw: pointer to the HW struct * @blk: classification stage * @entry: flow entry to be removed */ static int ice_flow_rem_entry_sync(struct ice_hw *hw, enum ice_block __always_unused blk, struct ice_flow_entry *entry) { if (!entry) return -EINVAL; list_del(&entry->l_entry); devm_kfree(ice_hw_to_dev(hw), entry->entry); devm_kfree(ice_hw_to_dev(hw), entry); return 0; } /** * ice_flow_add_prof_sync - Add a flow profile for packet segments and fields * @hw: pointer to the HW struct * @blk: classification stage * @dir: flow direction * @prof_id: unique ID to identify this flow profile * @segs: array of one or more packet segments that describe the flow * @segs_cnt: number of packet segments provided * @prof: stores the returned flow profile added * * Assumption: the caller has acquired the lock to the profile list */ static int ice_flow_add_prof_sync(struct ice_hw *hw, enum ice_block blk, enum ice_flow_dir dir, u64 prof_id, struct ice_flow_seg_info *segs, u8 segs_cnt, struct ice_flow_prof **prof) { struct ice_flow_prof_params *params; int status; u8 i; if (!prof) return -EINVAL; params = kzalloc(sizeof(*params), GFP_KERNEL); if (!params) return -ENOMEM; params->prof = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*params->prof), GFP_KERNEL); if (!params->prof) { status = -ENOMEM; goto free_params; } /* initialize extraction sequence to all invalid (0xff) */ for (i = 0; i < ICE_MAX_FV_WORDS; i++) { params->es[i].prot_id = ICE_PROT_INVALID; params->es[i].off = ICE_FV_OFFSET_INVAL; } params->blk = blk; params->prof->id = prof_id; params->prof->dir = dir; params->prof->segs_cnt = segs_cnt; /* Make a copy of the segments that need to be persistent in the flow * profile instance */ for (i = 0; i < segs_cnt; i++) memcpy(&params->prof->segs[i], &segs[i], sizeof(*segs)); status = ice_flow_proc_segs(hw, params); if (status) { ice_debug(hw, ICE_DBG_FLOW, "Error processing a flow's packet segments\n"); goto out; } /* Add a HW profile for this flow profile */ status = ice_add_prof(hw, blk, prof_id, (u8 *)params->ptypes, params->attr, params->attr_cnt, params->es, params->mask); if (status) { ice_debug(hw, ICE_DBG_FLOW, "Error adding a HW flow profile\n"); goto out; } INIT_LIST_HEAD(&params->prof->entries); mutex_init(&params->prof->entries_lock); *prof = params->prof; out: if (status) devm_kfree(ice_hw_to_dev(hw), params->prof); free_params: kfree(params); return status; } /** * ice_flow_rem_prof_sync - remove a flow profile * @hw: pointer to the hardware structure * @blk: classification stage * @prof: pointer to flow profile to remove * * Assumption: the caller has acquired the lock to the profile list */ static int ice_flow_rem_prof_sync(struct ice_hw *hw, enum ice_block blk, struct ice_flow_prof *prof) { int status; /* Remove all remaining flow entries before removing the flow profile */ if (!list_empty(&prof->entries)) { struct ice_flow_entry *e, *t; mutex_lock(&prof->entries_lock); list_for_each_entry_safe(e, t, &prof->entries, l_entry) { status = ice_flow_rem_entry_sync(hw, blk, e); if (status) break; } mutex_unlock(&prof->entries_lock); } /* Remove all hardware profiles associated with this flow profile */ status = ice_rem_prof(hw, blk, prof->id); if (!status) { list_del(&prof->l_entry); mutex_destroy(&prof->entries_lock); devm_kfree(ice_hw_to_dev(hw), prof); } return status; } /** * ice_flow_assoc_prof - associate a VSI with a flow profile * @hw: pointer to the hardware structure * @blk: classification stage * @prof: pointer to flow profile * @vsi_handle: software VSI handle * * Assumption: the caller has acquired the lock to the profile list * and the software VSI handle has been validated */ static int ice_flow_assoc_prof(struct ice_hw *hw, enum ice_block blk, struct ice_flow_prof *prof, u16 vsi_handle) { int status = 0; if (!test_bit(vsi_handle, prof->vsis)) { status = ice_add_prof_id_flow(hw, blk, ice_get_hw_vsi_num(hw, vsi_handle), prof->id); if (!status) set_bit(vsi_handle, prof->vsis); else ice_debug(hw, ICE_DBG_FLOW, "HW profile add failed, %d\n", status); } return status; } /** * ice_flow_disassoc_prof - disassociate a VSI from a flow profile * @hw: pointer to the hardware structure * @blk: classification stage * @prof: pointer to flow profile * @vsi_handle: software VSI handle * * Assumption: the caller has acquired the lock to the profile list * and the software VSI handle has been validated */ static int ice_flow_disassoc_prof(struct ice_hw *hw, enum ice_block blk, struct ice_flow_prof *prof, u16 vsi_handle) { int status = 0; if (test_bit(vsi_handle, prof->vsis)) { status = ice_rem_prof_id_flow(hw, blk, ice_get_hw_vsi_num(hw, vsi_handle), prof->id); if (!status) clear_bit(vsi_handle, prof->vsis); else ice_debug(hw, ICE_DBG_FLOW, "HW profile remove failed, %d\n", status); } return status; } /** * ice_flow_add_prof - Add a flow profile for packet segments and matched fields * @hw: pointer to the HW struct * @blk: classification stage * @dir: flow direction * @prof_id: unique ID to identify this flow profile * @segs: array of one or more packet segments that describe the flow * @segs_cnt: number of packet segments provided * @prof: stores the returned flow profile added */ int ice_flow_add_prof(struct ice_hw *hw, enum ice_block blk, enum ice_flow_dir dir, u64 prof_id, struct ice_flow_seg_info *segs, u8 segs_cnt, struct ice_flow_prof **prof) { int status; if (segs_cnt > ICE_FLOW_SEG_MAX) return -ENOSPC; if (!segs_cnt) return -EINVAL; if (!segs) return -EINVAL; status = ice_flow_val_hdrs(segs, segs_cnt); if (status) return status; mutex_lock(&hw->fl_profs_locks[blk]); status = ice_flow_add_prof_sync(hw, blk, dir, prof_id, segs, segs_cnt, prof); if (!status) list_add(&(*prof)->l_entry, &hw->fl_profs[blk]); mutex_unlock(&hw->fl_profs_locks[blk]); return status; } /** * ice_flow_rem_prof - Remove a flow profile and all entries associated with it * @hw: pointer to the HW struct * @blk: the block for which the flow profile is to be removed * @prof_id: unique ID of the flow profile to be removed */ int ice_flow_rem_prof(struct ice_hw *hw, enum ice_block blk, u64 prof_id) { struct ice_flow_prof *prof; int status; mutex_lock(&hw->fl_profs_locks[blk]); prof = ice_flow_find_prof_id(hw, blk, prof_id); if (!prof) { status = -ENOENT; goto out; } /* prof becomes invalid after the call */ status = ice_flow_rem_prof_sync(hw, blk, prof); out: mutex_unlock(&hw->fl_profs_locks[blk]); return status; } /** * ice_flow_add_entry - Add a flow entry * @hw: pointer to the HW struct * @blk: classification stage * @prof_id: ID of the profile to add a new flow entry to * @entry_id: unique ID to identify this flow entry * @vsi_handle: software VSI handle for the flow entry * @prio: priority of the flow entry * @data: pointer to a data buffer containing flow entry's match values/masks * @entry_h: pointer to buffer that receives the new flow entry's handle */ int ice_flow_add_entry(struct ice_hw *hw, enum ice_block blk, u64 prof_id, u64 entry_id, u16 vsi_handle, enum ice_flow_priority prio, void *data, u64 *entry_h) { struct ice_flow_entry *e = NULL; struct ice_flow_prof *prof; int status; /* No flow entry data is expected for RSS */ if (!entry_h || (!data && blk != ICE_BLK_RSS)) return -EINVAL; if (!ice_is_vsi_valid(hw, vsi_handle)) return -EINVAL; mutex_lock(&hw->fl_profs_locks[blk]); prof = ice_flow_find_prof_id(hw, blk, prof_id); if (!prof) { status = -ENOENT; } else { /* Allocate memory for the entry being added and associate * the VSI to the found flow profile */ e = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*e), GFP_KERNEL); if (!e) status = -ENOMEM; else status = ice_flow_assoc_prof(hw, blk, prof, vsi_handle); } mutex_unlock(&hw->fl_profs_locks[blk]); if (status) goto out; e->id = entry_id; e->vsi_handle = vsi_handle; e->prof = prof; e->priority = prio; switch (blk) { case ICE_BLK_FD: case ICE_BLK_RSS: break; default: status = -EOPNOTSUPP; goto out; } mutex_lock(&prof->entries_lock); list_add(&e->l_entry, &prof->entries); mutex_unlock(&prof->entries_lock); *entry_h = ICE_FLOW_ENTRY_HNDL(e); out: if (status && e) { devm_kfree(ice_hw_to_dev(hw), e->entry); devm_kfree(ice_hw_to_dev(hw), e); } return status; } /** * ice_flow_rem_entry - Remove a flow entry * @hw: pointer to the HW struct * @blk: classification stage * @entry_h: handle to the flow entry to be removed */ int ice_flow_rem_entry(struct ice_hw *hw, enum ice_block blk, u64 entry_h) { struct ice_flow_entry *entry; struct ice_flow_prof *prof; int status = 0; if (entry_h == ICE_FLOW_ENTRY_HANDLE_INVAL) return -EINVAL; entry = ICE_FLOW_ENTRY_PTR(entry_h); /* Retain the pointer to the flow profile as the entry will be freed */ prof = entry->prof; if (prof) { mutex_lock(&prof->entries_lock); status = ice_flow_rem_entry_sync(hw, blk, entry); mutex_unlock(&prof->entries_lock); } return status; } /** * ice_flow_set_fld_ext - specifies locations of field from entry's input buffer * @seg: packet segment the field being set belongs to * @fld: field to be set * @field_type: type of the field * @val_loc: if not ICE_FLOW_FLD_OFF_INVAL, location of the value to match from * entry's input buffer * @mask_loc: if not ICE_FLOW_FLD_OFF_INVAL, location of mask value from entry's * input buffer * @last_loc: if not ICE_FLOW_FLD_OFF_INVAL, location of last/upper value from * entry's input buffer * * This helper function stores information of a field being matched, including * the type of the field and the locations of the value to match, the mask, and * the upper-bound value in the start of the input buffer for a flow entry. * This function should only be used for fixed-size data structures. * * This function also opportunistically determines the protocol headers to be * present based on the fields being set. Some fields cannot be used alone to * determine the protocol headers present. Sometimes, fields for particular * protocol headers are not matched. In those cases, the protocol headers * must be explicitly set. */ static void ice_flow_set_fld_ext(struct ice_flow_seg_info *seg, enum ice_flow_field fld, enum ice_flow_fld_match_type field_type, u16 val_loc, u16 mask_loc, u16 last_loc) { u64 bit = BIT_ULL(fld); seg->match |= bit; if (field_type == ICE_FLOW_FLD_TYPE_RANGE) seg->range |= bit; seg->fields[fld].type = field_type; seg->fields[fld].src.val = val_loc; seg->fields[fld].src.mask = mask_loc; seg->fields[fld].src.last = last_loc; ICE_FLOW_SET_HDRS(seg, ice_flds_info[fld].hdr); } /** * ice_flow_set_fld - specifies locations of field from entry's input buffer * @seg: packet segment the field being set belongs to * @fld: field to be set * @val_loc: if not ICE_FLOW_FLD_OFF_INVAL, location of the value to match from * entry's input buffer * @mask_loc: if not ICE_FLOW_FLD_OFF_INVAL, location of mask value from entry's * input buffer * @last_loc: if not ICE_FLOW_FLD_OFF_INVAL, location of last/upper value from * entry's input buffer * @range: indicate if field being matched is to be in a range * * This function specifies the locations, in the form of byte offsets from the * start of the input buffer for a flow entry, from where the value to match, * the mask value, and upper value can be extracted. These locations are then * stored in the flow profile. When adding a flow entry associated with the * flow profile, these locations will be used to quickly extract the values and * create the content of a match entry. This function should only be used for * fixed-size data structures. */ void ice_flow_set_fld(struct ice_flow_seg_info *seg, enum ice_flow_field fld, u16 val_loc, u16 mask_loc, u16 last_loc, bool range) { enum ice_flow_fld_match_type t = range ? ICE_FLOW_FLD_TYPE_RANGE : ICE_FLOW_FLD_TYPE_REG; ice_flow_set_fld_ext(seg, fld, t, val_loc, mask_loc, last_loc); } /** * ice_flow_add_fld_raw - sets locations of a raw field from entry's input buf * @seg: packet segment the field being set belongs to * @off: offset of the raw field from the beginning of the segment in bytes * @len: length of the raw pattern to be matched * @val_loc: location of the value to match from entry's input buffer * @mask_loc: location of mask value from entry's input buffer * * This function specifies the offset of the raw field to be match from the * beginning of the specified packet segment, and the locations, in the form of * byte offsets from the start of the input buffer for a flow entry, from where * the value to match and the mask value to be extracted. These locations are * then stored in the flow profile. When adding flow entries to the associated * flow profile, these locations can be used to quickly extract the values to * create the content of a match entry. This function should only be used for * fixed-size data structures. */ void ice_flow_add_fld_raw(struct ice_flow_seg_info *seg, u16 off, u8 len, u16 val_loc, u16 mask_loc) { if (seg->raws_cnt < ICE_FLOW_SEG_RAW_FLD_MAX) { seg->raws[seg->raws_cnt].off = off; seg->raws[seg->raws_cnt].info.type = ICE_FLOW_FLD_TYPE_SIZE; seg->raws[seg->raws_cnt].info.src.val = val_loc; seg->raws[seg->raws_cnt].info.src.mask = mask_loc; /* The "last" field is used to store the length of the field */ seg->raws[seg->raws_cnt].info.src.last = len; } /* Overflows of "raws" will be handled as an error condition later in * the flow when this information is processed. */ seg->raws_cnt++; } /** * ice_flow_rem_vsi_prof - remove VSI from flow profile * @hw: pointer to the hardware structure * @vsi_handle: software VSI handle * @prof_id: unique ID to identify this flow profile * * This function removes the flow entries associated to the input * VSI handle and disassociate the VSI from the flow profile. */ int ice_flow_rem_vsi_prof(struct ice_hw *hw, u16 vsi_handle, u64 prof_id) { struct ice_flow_prof *prof; int status = 0; if (!ice_is_vsi_valid(hw, vsi_handle)) return -EINVAL; /* find flow profile pointer with input package block and profile ID */ prof = ice_flow_find_prof_id(hw, ICE_BLK_FD, prof_id); if (!prof) { ice_debug(hw, ICE_DBG_PKG, "Cannot find flow profile id=%llu\n", prof_id); return -ENOENT; } /* Remove all remaining flow entries before removing the flow profile */ if (!list_empty(&prof->entries)) { struct ice_flow_entry *e, *t; mutex_lock(&prof->entries_lock); list_for_each_entry_safe(e, t, &prof->entries, l_entry) { if (e->vsi_handle != vsi_handle) continue; status = ice_flow_rem_entry_sync(hw, ICE_BLK_FD, e); if (status) break; } mutex_unlock(&prof->entries_lock); } if (status) return status; /* disassociate the flow profile from sw VSI handle */ status = ice_flow_disassoc_prof(hw, ICE_BLK_FD, prof, vsi_handle); if (status) ice_debug(hw, ICE_DBG_PKG, "ice_flow_disassoc_prof() failed with status=%d\n", status); return status; } #define ICE_FLOW_RSS_SEG_HDR_L2_MASKS \ (ICE_FLOW_SEG_HDR_ETH | ICE_FLOW_SEG_HDR_VLAN) #define ICE_FLOW_RSS_SEG_HDR_L3_MASKS \ (ICE_FLOW_SEG_HDR_IPV4 | ICE_FLOW_SEG_HDR_IPV6) #define ICE_FLOW_RSS_SEG_HDR_L4_MASKS \ (ICE_FLOW_SEG_HDR_TCP | ICE_FLOW_SEG_HDR_UDP | ICE_FLOW_SEG_HDR_SCTP) #define ICE_FLOW_RSS_SEG_HDR_VAL_MASKS \ (ICE_FLOW_RSS_SEG_HDR_L2_MASKS | \ ICE_FLOW_RSS_SEG_HDR_L3_MASKS | \ ICE_FLOW_RSS_SEG_HDR_L4_MASKS) /** * ice_flow_set_rss_seg_info - setup packet segments for RSS * @segs: pointer to the flow field segment(s) * @hash_fields: fields to be hashed on for the segment(s) * @flow_hdr: protocol header fields within a packet segment * * Helper function to extract fields from hash bitmap and use flow * header value to set flow field segment for further use in flow * profile entry or removal. */ static int ice_flow_set_rss_seg_info(struct ice_flow_seg_info *segs, u64 hash_fields, u32 flow_hdr) { u64 val; u8 i; for_each_set_bit(i, (unsigned long *)&hash_fields, ICE_FLOW_FIELD_IDX_MAX) ice_flow_set_fld(segs, (enum ice_flow_field)i, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, ICE_FLOW_FLD_OFF_INVAL, false); ICE_FLOW_SET_HDRS(segs, flow_hdr); if (segs->hdrs & ~ICE_FLOW_RSS_SEG_HDR_VAL_MASKS & ~ICE_FLOW_RSS_HDRS_INNER_MASK & ~ICE_FLOW_SEG_HDR_IPV_OTHER) return -EINVAL; val = (u64)(segs->hdrs & ICE_FLOW_RSS_SEG_HDR_L3_MASKS); if (val && !is_power_of_2(val)) return -EIO; val = (u64)(segs->hdrs & ICE_FLOW_RSS_SEG_HDR_L4_MASKS); if (val && !is_power_of_2(val)) return -EIO; return 0; } /** * ice_rem_vsi_rss_list - remove VSI from RSS list * @hw: pointer to the hardware structure * @vsi_handle: software VSI handle * * Remove the VSI from all RSS configurations in the list. */ void ice_rem_vsi_rss_list(struct ice_hw *hw, u16 vsi_handle) { struct ice_rss_cfg *r, *tmp; if (list_empty(&hw->rss_list_head)) return; mutex_lock(&hw->rss_locks); list_for_each_entry_safe(r, tmp, &hw->rss_list_head, l_entry) if (test_and_clear_bit(vsi_handle, r->vsis)) if (bitmap_empty(r->vsis, ICE_MAX_VSI)) { list_del(&r->l_entry); devm_kfree(ice_hw_to_dev(hw), r); } mutex_unlock(&hw->rss_locks); } /** * ice_rem_vsi_rss_cfg - remove RSS configurations associated with VSI * @hw: pointer to the hardware structure * @vsi_handle: software VSI handle * * This function will iterate through all flow profiles and disassociate * the VSI from that profile. If the flow profile has no VSIs it will * be removed. */ int ice_rem_vsi_rss_cfg(struct ice_hw *hw, u16 vsi_handle) { const enum ice_block blk = ICE_BLK_RSS; struct ice_flow_prof *p, *t; int status = 0; if (!ice_is_vsi_valid(hw, vsi_handle)) return -EINVAL; if (list_empty(&hw->fl_profs[blk])) return 0; mutex_lock(&hw->rss_locks); list_for_each_entry_safe(p, t, &hw->fl_profs[blk], l_entry) if (test_bit(vsi_handle, p->vsis)) { status = ice_flow_disassoc_prof(hw, blk, p, vsi_handle); if (status) break; if (bitmap_empty(p->vsis, ICE_MAX_VSI)) { status = ice_flow_rem_prof(hw, blk, p->id); if (status) break; } } mutex_unlock(&hw->rss_locks); return status; } /** * ice_rem_rss_list - remove RSS configuration from list * @hw: pointer to the hardware structure * @vsi_handle: software VSI handle * @prof: pointer to flow profile * * Assumption: lock has already been acquired for RSS list */ static void ice_rem_rss_list(struct ice_hw *hw, u16 vsi_handle, struct ice_flow_prof *prof) { struct ice_rss_cfg *r, *tmp; /* Search for RSS hash fields associated to the VSI that match the * hash configurations associated to the flow profile. If found * remove from the RSS entry list of the VSI context and delete entry. */ list_for_each_entry_safe(r, tmp, &hw->rss_list_head, l_entry) if (r->hashed_flds == prof->segs[prof->segs_cnt - 1].match && r->packet_hdr == prof->segs[prof->segs_cnt - 1].hdrs) { clear_bit(vsi_handle, r->vsis); if (bitmap_empty(r->vsis, ICE_MAX_VSI)) { list_del(&r->l_entry); devm_kfree(ice_hw_to_dev(hw), r); } return; } } /** * ice_add_rss_list - add RSS configuration to list * @hw: pointer to the hardware structure * @vsi_handle: software VSI handle * @prof: pointer to flow profile * * Assumption: lock has already been acquired for RSS list */ static int ice_add_rss_list(struct ice_hw *hw, u16 vsi_handle, struct ice_flow_prof *prof) { struct ice_rss_cfg *r, *rss_cfg; list_for_each_entry(r, &hw->rss_list_head, l_entry) if (r->hashed_flds == prof->segs[prof->segs_cnt - 1].match && r->packet_hdr == prof->segs[prof->segs_cnt - 1].hdrs) { set_bit(vsi_handle, r->vsis); return 0; } rss_cfg = devm_kzalloc(ice_hw_to_dev(hw), sizeof(*rss_cfg), GFP_KERNEL); if (!rss_cfg) return -ENOMEM; rss_cfg->hashed_flds = prof->segs[prof->segs_cnt - 1].match; rss_cfg->packet_hdr = prof->segs[prof->segs_cnt - 1].hdrs; set_bit(vsi_handle, rss_cfg->vsis); list_add_tail(&rss_cfg->l_entry, &hw->rss_list_head); return 0; } #define ICE_FLOW_PROF_HASH_S 0 #define ICE_FLOW_PROF_HASH_M (0xFFFFFFFFULL << ICE_FLOW_PROF_HASH_S) #define ICE_FLOW_PROF_HDR_S 32 #define ICE_FLOW_PROF_HDR_M (0x3FFFFFFFULL << ICE_FLOW_PROF_HDR_S) #define ICE_FLOW_PROF_ENCAP_S 63 #define ICE_FLOW_PROF_ENCAP_M (BIT_ULL(ICE_FLOW_PROF_ENCAP_S)) #define ICE_RSS_OUTER_HEADERS 1 #define ICE_RSS_INNER_HEADERS 2 /* Flow profile ID format: * [0:31] - Packet match fields * [32:62] - Protocol header * [63] - Encapsulation flag, 0 if non-tunneled, 1 if tunneled */ #define ICE_FLOW_GEN_PROFID(hash, hdr, segs_cnt) \ ((u64)(((u64)(hash) & ICE_FLOW_PROF_HASH_M) | \ (((u64)(hdr) << ICE_FLOW_PROF_HDR_S) & ICE_FLOW_PROF_HDR_M) | \ ((u8)((segs_cnt) - 1) ? ICE_FLOW_PROF_ENCAP_M : 0))) /** * ice_add_rss_cfg_sync - add an RSS configuration * @hw: pointer to the hardware structure * @vsi_handle: software VSI handle * @hashed_flds: hash bit fields (ICE_FLOW_HASH_*) to configure * @addl_hdrs: protocol header fields * @segs_cnt: packet segment count * * Assumption: lock has already been acquired for RSS list */ static int ice_add_rss_cfg_sync(struct ice_hw *hw, u16 vsi_handle, u64 hashed_flds, u32 addl_hdrs, u8 segs_cnt) { const enum ice_block blk = ICE_BLK_RSS; struct ice_flow_prof *prof = NULL; struct ice_flow_seg_info *segs; int status; if (!segs_cnt || segs_cnt > ICE_FLOW_SEG_MAX) return -EINVAL; segs = kcalloc(segs_cnt, sizeof(*segs), GFP_KERNEL); if (!segs) return -ENOMEM; /* Construct the packet segment info from the hashed fields */ status = ice_flow_set_rss_seg_info(&segs[segs_cnt - 1], hashed_flds, addl_hdrs); if (status) goto exit; /* Search for a flow profile that has matching headers, hash fields * and has the input VSI associated to it. If found, no further * operations required and exit. */ prof = ice_flow_find_prof_conds(hw, blk, ICE_FLOW_RX, segs, segs_cnt, vsi_handle, ICE_FLOW_FIND_PROF_CHK_FLDS | ICE_FLOW_FIND_PROF_CHK_VSI); if (prof) goto exit; /* Check if a flow profile exists with the same protocol headers and * associated with the input VSI. If so disassociate the VSI from * this profile. The VSI will be added to a new profile created with * the protocol header and new hash field configuration. */ prof = ice_flow_find_prof_conds(hw, blk, ICE_FLOW_RX, segs, segs_cnt, vsi_handle, ICE_FLOW_FIND_PROF_CHK_VSI); if (prof) { status = ice_flow_disassoc_prof(hw, blk, prof, vsi_handle); if (!status) ice_rem_rss_list(hw, vsi_handle, prof); else goto exit; /* Remove profile if it has no VSIs associated */ if (bitmap_empty(prof->vsis, ICE_MAX_VSI)) { status = ice_flow_rem_prof(hw, blk, prof->id); if (status) goto exit; } } /* Search for a profile that has same match fields only. If this * exists then associate the VSI to this profile. */ prof = ice_flow_find_prof_conds(hw, blk, ICE_FLOW_RX, segs, segs_cnt, vsi_handle, ICE_FLOW_FIND_PROF_CHK_FLDS); if (prof) { status = ice_flow_assoc_prof(hw, blk, prof, vsi_handle); if (!status) status = ice_add_rss_list(hw, vsi_handle, prof); goto exit; } /* Create a new flow profile with generated profile and packet * segment information. */ status = ice_flow_add_prof(hw, blk, ICE_FLOW_RX, ICE_FLOW_GEN_PROFID(hashed_flds, segs[segs_cnt - 1].hdrs, segs_cnt), segs, segs_cnt, &prof); if (status) goto exit; status = ice_flow_assoc_prof(hw, blk, prof, vsi_handle); /* If association to a new flow profile failed then this profile can * be removed. */ if (status) { ice_flow_rem_prof(hw, blk, prof->id); goto exit; } status = ice_add_rss_list(hw, vsi_handle, prof); exit: kfree(segs); return status; } /** * ice_add_rss_cfg - add an RSS configuration with specified hashed fields * @hw: pointer to the hardware structure * @vsi_handle: software VSI handle * @hashed_flds: hash bit fields (ICE_FLOW_HASH_*) to configure * @addl_hdrs: protocol header fields * * This function will generate a flow profile based on fields associated with * the input fields to hash on, the flow type and use the VSI number to add * a flow entry to the profile. */ int ice_add_rss_cfg(struct ice_hw *hw, u16 vsi_handle, u64 hashed_flds, u32 addl_hdrs) { int status; if (hashed_flds == ICE_HASH_INVALID || !ice_is_vsi_valid(hw, vsi_handle)) return -EINVAL; mutex_lock(&hw->rss_locks); status = ice_add_rss_cfg_sync(hw, vsi_handle, hashed_flds, addl_hdrs, ICE_RSS_OUTER_HEADERS); if (!status) status = ice_add_rss_cfg_sync(hw, vsi_handle, hashed_flds, addl_hdrs, ICE_RSS_INNER_HEADERS); mutex_unlock(&hw->rss_locks); return status; } /** * ice_rem_rss_cfg_sync - remove an existing RSS configuration * @hw: pointer to the hardware structure * @vsi_handle: software VSI handle * @hashed_flds: Packet hash types (ICE_FLOW_HASH_*) to remove * @addl_hdrs: Protocol header fields within a packet segment * @segs_cnt: packet segment count * * Assumption: lock has already been acquired for RSS list */ static int ice_rem_rss_cfg_sync(struct ice_hw *hw, u16 vsi_handle, u64 hashed_flds, u32 addl_hdrs, u8 segs_cnt) { const enum ice_block blk = ICE_BLK_RSS; struct ice_flow_seg_info *segs; struct ice_flow_prof *prof; int status; segs = kcalloc(segs_cnt, sizeof(*segs), GFP_KERNEL); if (!segs) return -ENOMEM; /* Construct the packet segment info from the hashed fields */ status = ice_flow_set_rss_seg_info(&segs[segs_cnt - 1], hashed_flds, addl_hdrs); if (status) goto out; prof = ice_flow_find_prof_conds(hw, blk, ICE_FLOW_RX, segs, segs_cnt, vsi_handle, ICE_FLOW_FIND_PROF_CHK_FLDS); if (!prof) { status = -ENOENT; goto out; } status = ice_flow_disassoc_prof(hw, blk, prof, vsi_handle); if (status) goto out; /* Remove RSS configuration from VSI context before deleting * the flow profile. */ ice_rem_rss_list(hw, vsi_handle, prof); if (bitmap_empty(prof->vsis, ICE_MAX_VSI)) status = ice_flow_rem_prof(hw, blk, prof->id); out: kfree(segs); return status; } /** * ice_rem_rss_cfg - remove an existing RSS config with matching hashed fields * @hw: pointer to the hardware structure * @vsi_handle: software VSI handle * @hashed_flds: Packet hash types (ICE_FLOW_HASH_*) to remove * @addl_hdrs: Protocol header fields within a packet segment * * This function will lookup the flow profile based on the input * hash field bitmap, iterate through the profile entry list of * that profile and find entry associated with input VSI to be * removed. Calls are made to underlying flow s which will APIs * turn build or update buffers for RSS XLT1 section. */ int __maybe_unused ice_rem_rss_cfg(struct ice_hw *hw, u16 vsi_handle, u64 hashed_flds, u32 addl_hdrs) { int status; if (hashed_flds == ICE_HASH_INVALID || !ice_is_vsi_valid(hw, vsi_handle)) return -EINVAL; mutex_lock(&hw->rss_locks); status = ice_rem_rss_cfg_sync(hw, vsi_handle, hashed_flds, addl_hdrs, ICE_RSS_OUTER_HEADERS); if (!status) status = ice_rem_rss_cfg_sync(hw, vsi_handle, hashed_flds, addl_hdrs, ICE_RSS_INNER_HEADERS); mutex_unlock(&hw->rss_locks); return status; } /* Mapping of AVF hash bit fields to an L3-L4 hash combination. * As the ice_flow_avf_hdr_field represent individual bit shifts in a hash, * convert its values to their appropriate flow L3, L4 values. */ #define ICE_FLOW_AVF_RSS_IPV4_MASKS \ (BIT_ULL(ICE_AVF_FLOW_FIELD_IPV4_OTHER) | \ BIT_ULL(ICE_AVF_FLOW_FIELD_FRAG_IPV4)) #define ICE_FLOW_AVF_RSS_TCP_IPV4_MASKS \ (BIT_ULL(ICE_AVF_FLOW_FIELD_IPV4_TCP_SYN_NO_ACK) | \ BIT_ULL(ICE_AVF_FLOW_FIELD_IPV4_TCP)) #define ICE_FLOW_AVF_RSS_UDP_IPV4_MASKS \ (BIT_ULL(ICE_AVF_FLOW_FIELD_UNICAST_IPV4_UDP) | \ BIT_ULL(ICE_AVF_FLOW_FIELD_MULTICAST_IPV4_UDP) | \ BIT_ULL(ICE_AVF_FLOW_FIELD_IPV4_UDP)) #define ICE_FLOW_AVF_RSS_ALL_IPV4_MASKS \ (ICE_FLOW_AVF_RSS_TCP_IPV4_MASKS | ICE_FLOW_AVF_RSS_UDP_IPV4_MASKS | \ ICE_FLOW_AVF_RSS_IPV4_MASKS | BIT_ULL(ICE_AVF_FLOW_FIELD_IPV4_SCTP)) #define ICE_FLOW_AVF_RSS_IPV6_MASKS \ (BIT_ULL(ICE_AVF_FLOW_FIELD_IPV6_OTHER) | \ BIT_ULL(ICE_AVF_FLOW_FIELD_FRAG_IPV6)) #define ICE_FLOW_AVF_RSS_UDP_IPV6_MASKS \ (BIT_ULL(ICE_AVF_FLOW_FIELD_UNICAST_IPV6_UDP) | \ BIT_ULL(ICE_AVF_FLOW_FIELD_MULTICAST_IPV6_UDP) | \ BIT_ULL(ICE_AVF_FLOW_FIELD_IPV6_UDP)) #define ICE_FLOW_AVF_RSS_TCP_IPV6_MASKS \ (BIT_ULL(ICE_AVF_FLOW_FIELD_IPV6_TCP_SYN_NO_ACK) | \ BIT_ULL(ICE_AVF_FLOW_FIELD_IPV6_TCP)) #define ICE_FLOW_AVF_RSS_ALL_IPV6_MASKS \ (ICE_FLOW_AVF_RSS_TCP_IPV6_MASKS | ICE_FLOW_AVF_RSS_UDP_IPV6_MASKS | \ ICE_FLOW_AVF_RSS_IPV6_MASKS | BIT_ULL(ICE_AVF_FLOW_FIELD_IPV6_SCTP)) /** * ice_add_avf_rss_cfg - add an RSS configuration for AVF driver * @hw: pointer to the hardware structure * @vsi_handle: software VSI handle * @avf_hash: hash bit fields (ICE_AVF_FLOW_FIELD_*) to configure * * This function will take the hash bitmap provided by the AVF driver via a * message, convert it to ICE-compatible values, and configure RSS flow * profiles. */ int ice_add_avf_rss_cfg(struct ice_hw *hw, u16 vsi_handle, u64 avf_hash) { int status = 0; u64 hash_flds; if (avf_hash == ICE_AVF_FLOW_FIELD_INVALID || !ice_is_vsi_valid(hw, vsi_handle)) return -EINVAL; /* Make sure no unsupported bits are specified */ if (avf_hash & ~(ICE_FLOW_AVF_RSS_ALL_IPV4_MASKS | ICE_FLOW_AVF_RSS_ALL_IPV6_MASKS)) return -EIO; hash_flds = avf_hash; /* Always create an L3 RSS configuration for any L4 RSS configuration */ if (hash_flds & ICE_FLOW_AVF_RSS_ALL_IPV4_MASKS) hash_flds |= ICE_FLOW_AVF_RSS_IPV4_MASKS; if (hash_flds & ICE_FLOW_AVF_RSS_ALL_IPV6_MASKS) hash_flds |= ICE_FLOW_AVF_RSS_IPV6_MASKS; /* Create the corresponding RSS configuration for each valid hash bit */ while (hash_flds) { u64 rss_hash = ICE_HASH_INVALID; if (hash_flds & ICE_FLOW_AVF_RSS_ALL_IPV4_MASKS) { if (hash_flds & ICE_FLOW_AVF_RSS_IPV4_MASKS) { rss_hash = ICE_FLOW_HASH_IPV4; hash_flds &= ~ICE_FLOW_AVF_RSS_IPV4_MASKS; } else if (hash_flds & ICE_FLOW_AVF_RSS_TCP_IPV4_MASKS) { rss_hash = ICE_FLOW_HASH_IPV4 | ICE_FLOW_HASH_TCP_PORT; hash_flds &= ~ICE_FLOW_AVF_RSS_TCP_IPV4_MASKS; } else if (hash_flds & ICE_FLOW_AVF_RSS_UDP_IPV4_MASKS) { rss_hash = ICE_FLOW_HASH_IPV4 | ICE_FLOW_HASH_UDP_PORT; hash_flds &= ~ICE_FLOW_AVF_RSS_UDP_IPV4_MASKS; } else if (hash_flds & BIT_ULL(ICE_AVF_FLOW_FIELD_IPV4_SCTP)) { rss_hash = ICE_FLOW_HASH_IPV4 | ICE_FLOW_HASH_SCTP_PORT; hash_flds &= ~BIT_ULL(ICE_AVF_FLOW_FIELD_IPV4_SCTP); } } else if (hash_flds & ICE_FLOW_AVF_RSS_ALL_IPV6_MASKS) { if (hash_flds & ICE_FLOW_AVF_RSS_IPV6_MASKS) { rss_hash = ICE_FLOW_HASH_IPV6; hash_flds &= ~ICE_FLOW_AVF_RSS_IPV6_MASKS; } else if (hash_flds & ICE_FLOW_AVF_RSS_TCP_IPV6_MASKS) { rss_hash = ICE_FLOW_HASH_IPV6 | ICE_FLOW_HASH_TCP_PORT; hash_flds &= ~ICE_FLOW_AVF_RSS_TCP_IPV6_MASKS; } else if (hash_flds & ICE_FLOW_AVF_RSS_UDP_IPV6_MASKS) { rss_hash = ICE_FLOW_HASH_IPV6 | ICE_FLOW_HASH_UDP_PORT; hash_flds &= ~ICE_FLOW_AVF_RSS_UDP_IPV6_MASKS; } else if (hash_flds & BIT_ULL(ICE_AVF_FLOW_FIELD_IPV6_SCTP)) { rss_hash = ICE_FLOW_HASH_IPV6 | ICE_FLOW_HASH_SCTP_PORT; hash_flds &= ~BIT_ULL(ICE_AVF_FLOW_FIELD_IPV6_SCTP); } } if (rss_hash == ICE_HASH_INVALID) return -EIO; status = ice_add_rss_cfg(hw, vsi_handle, rss_hash, ICE_FLOW_SEG_HDR_NONE); if (status) break; } return status; } /** * ice_replay_rss_cfg - replay RSS configurations associated with VSI * @hw: pointer to the hardware structure * @vsi_handle: software VSI handle */ int ice_replay_rss_cfg(struct ice_hw *hw, u16 vsi_handle) { struct ice_rss_cfg *r; int status = 0; if (!ice_is_vsi_valid(hw, vsi_handle)) return -EINVAL; mutex_lock(&hw->rss_locks); list_for_each_entry(r, &hw->rss_list_head, l_entry) { if (test_bit(vsi_handle, r->vsis)) { status = ice_add_rss_cfg_sync(hw, vsi_handle, r->hashed_flds, r->packet_hdr, ICE_RSS_OUTER_HEADERS); if (status) break; status = ice_add_rss_cfg_sync(hw, vsi_handle, r->hashed_flds, r->packet_hdr, ICE_RSS_INNER_HEADERS); if (status) break; } } mutex_unlock(&hw->rss_locks); return status; } /** * ice_get_rss_cfg - returns hashed fields for the given header types * @hw: pointer to the hardware structure * @vsi_handle: software VSI handle * @hdrs: protocol header type * * This function will return the match fields of the first instance of flow * profile having the given header types and containing input VSI */ u64 ice_get_rss_cfg(struct ice_hw *hw, u16 vsi_handle, u32 hdrs) { u64 rss_hash = ICE_HASH_INVALID; struct ice_rss_cfg *r; /* verify if the protocol header is non zero and VSI is valid */ if (hdrs == ICE_FLOW_SEG_HDR_NONE || !ice_is_vsi_valid(hw, vsi_handle)) return ICE_HASH_INVALID; mutex_lock(&hw->rss_locks); list_for_each_entry(r, &hw->rss_list_head, l_entry) if (test_bit(vsi_handle, r->vsis) && r->packet_hdr == hdrs) { rss_hash = r->hashed_flds; break; } mutex_unlock(&hw->rss_locks); return rss_hash; }
linux-master
drivers/net/ethernet/intel/ice/ice_flow.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2023, Intel Corporation. */ #include "ice.h" #include "ice_lib.h" #include "ice_irq.h" /** * ice_init_irq_tracker - initialize interrupt tracker * @pf: board private structure * @max_vectors: maximum number of vectors that tracker can hold * @num_static: number of preallocated interrupts */ static void ice_init_irq_tracker(struct ice_pf *pf, unsigned int max_vectors, unsigned int num_static) { pf->irq_tracker.num_entries = max_vectors; pf->irq_tracker.num_static = num_static; xa_init_flags(&pf->irq_tracker.entries, XA_FLAGS_ALLOC); } /** * ice_deinit_irq_tracker - free xarray tracker * @pf: board private structure */ static void ice_deinit_irq_tracker(struct ice_pf *pf) { xa_destroy(&pf->irq_tracker.entries); } /** * ice_free_irq_res - free a block of resources * @pf: board private structure * @index: starting index previously returned by ice_get_res */ static void ice_free_irq_res(struct ice_pf *pf, u16 index) { struct ice_irq_entry *entry; entry = xa_erase(&pf->irq_tracker.entries, index); kfree(entry); } /** * ice_get_irq_res - get an interrupt resource * @pf: board private structure * @dyn_only: force entry to be dynamically allocated * * Allocate new irq entry in the free slot of the tracker. Since xarray * is used, always allocate new entry at the lowest possible index. Set * proper allocation limit for maximum tracker entries. * * Returns allocated irq entry or NULL on failure. */ static struct ice_irq_entry *ice_get_irq_res(struct ice_pf *pf, bool dyn_only) { struct xa_limit limit = { .max = pf->irq_tracker.num_entries, .min = 0 }; unsigned int num_static = pf->irq_tracker.num_static; struct ice_irq_entry *entry; unsigned int index; int ret; entry = kzalloc(sizeof(*entry), GFP_KERNEL); if (!entry) return NULL; /* skip preallocated entries if the caller says so */ if (dyn_only) limit.min = num_static; ret = xa_alloc(&pf->irq_tracker.entries, &index, entry, limit, GFP_KERNEL); if (ret) { kfree(entry); entry = NULL; } else { entry->index = index; entry->dynamic = index >= num_static; } return entry; } /** * ice_reduce_msix_usage - Reduce usage of MSI-X vectors * @pf: board private structure * @v_remain: number of remaining MSI-X vectors to be distributed * * Reduce the usage of MSI-X vectors when entire request cannot be fulfilled. * pf->num_lan_msix and pf->num_rdma_msix values are set based on number of * remaining vectors. */ static void ice_reduce_msix_usage(struct ice_pf *pf, int v_remain) { int v_rdma; if (!ice_is_rdma_ena(pf)) { pf->num_lan_msix = v_remain; return; } /* RDMA needs at least 1 interrupt in addition to AEQ MSIX */ v_rdma = ICE_RDMA_NUM_AEQ_MSIX + 1; if (v_remain < ICE_MIN_LAN_TXRX_MSIX + ICE_MIN_RDMA_MSIX) { dev_warn(ice_pf_to_dev(pf), "Not enough MSI-X vectors to support RDMA.\n"); clear_bit(ICE_FLAG_RDMA_ENA, pf->flags); pf->num_rdma_msix = 0; pf->num_lan_msix = ICE_MIN_LAN_TXRX_MSIX; } else if ((v_remain < ICE_MIN_LAN_TXRX_MSIX + v_rdma) || (v_remain - v_rdma < v_rdma)) { /* Support minimum RDMA and give remaining vectors to LAN MSIX */ pf->num_rdma_msix = ICE_MIN_RDMA_MSIX; pf->num_lan_msix = v_remain - ICE_MIN_RDMA_MSIX; } else { /* Split remaining MSIX with RDMA after accounting for AEQ MSIX */ pf->num_rdma_msix = (v_remain - ICE_RDMA_NUM_AEQ_MSIX) / 2 + ICE_RDMA_NUM_AEQ_MSIX; pf->num_lan_msix = v_remain - pf->num_rdma_msix; } } /** * ice_ena_msix_range - Request a range of MSIX vectors from the OS * @pf: board private structure * * Compute the number of MSIX vectors wanted and request from the OS. Adjust * device usage if there are not enough vectors. Return the number of vectors * reserved or negative on failure. */ static int ice_ena_msix_range(struct ice_pf *pf) { int num_cpus, hw_num_msix, v_other, v_wanted, v_actual; struct device *dev = ice_pf_to_dev(pf); int err; hw_num_msix = pf->hw.func_caps.common_cap.num_msix_vectors; num_cpus = num_online_cpus(); /* LAN miscellaneous handler */ v_other = ICE_MIN_LAN_OICR_MSIX; /* Flow Director */ if (test_bit(ICE_FLAG_FD_ENA, pf->flags)) v_other += ICE_FDIR_MSIX; /* switchdev */ v_other += ICE_ESWITCH_MSIX; v_wanted = v_other; /* LAN traffic */ pf->num_lan_msix = num_cpus; v_wanted += pf->num_lan_msix; /* RDMA auxiliary driver */ if (ice_is_rdma_ena(pf)) { pf->num_rdma_msix = num_cpus + ICE_RDMA_NUM_AEQ_MSIX; v_wanted += pf->num_rdma_msix; } if (v_wanted > hw_num_msix) { int v_remain; dev_warn(dev, "not enough device MSI-X vectors. wanted = %d, available = %d\n", v_wanted, hw_num_msix); if (hw_num_msix < ICE_MIN_MSIX) { err = -ERANGE; goto exit_err; } v_remain = hw_num_msix - v_other; if (v_remain < ICE_MIN_LAN_TXRX_MSIX) { v_other = ICE_MIN_MSIX - ICE_MIN_LAN_TXRX_MSIX; v_remain = ICE_MIN_LAN_TXRX_MSIX; } ice_reduce_msix_usage(pf, v_remain); v_wanted = pf->num_lan_msix + pf->num_rdma_msix + v_other; dev_notice(dev, "Reducing request to %d MSI-X vectors for LAN traffic.\n", pf->num_lan_msix); if (ice_is_rdma_ena(pf)) dev_notice(dev, "Reducing request to %d MSI-X vectors for RDMA.\n", pf->num_rdma_msix); } /* actually reserve the vectors */ v_actual = pci_alloc_irq_vectors(pf->pdev, ICE_MIN_MSIX, v_wanted, PCI_IRQ_MSIX); if (v_actual < 0) { dev_err(dev, "unable to reserve MSI-X vectors\n"); err = v_actual; goto exit_err; } if (v_actual < v_wanted) { dev_warn(dev, "not enough OS MSI-X vectors. requested = %d, obtained = %d\n", v_wanted, v_actual); if (v_actual < ICE_MIN_MSIX) { /* error if we can't get minimum vectors */ pci_free_irq_vectors(pf->pdev); err = -ERANGE; goto exit_err; } else { int v_remain = v_actual - v_other; if (v_remain < ICE_MIN_LAN_TXRX_MSIX) v_remain = ICE_MIN_LAN_TXRX_MSIX; ice_reduce_msix_usage(pf, v_remain); dev_notice(dev, "Enabled %d MSI-X vectors for LAN traffic.\n", pf->num_lan_msix); if (ice_is_rdma_ena(pf)) dev_notice(dev, "Enabled %d MSI-X vectors for RDMA.\n", pf->num_rdma_msix); } } return v_actual; exit_err: pf->num_rdma_msix = 0; pf->num_lan_msix = 0; return err; } /** * ice_clear_interrupt_scheme - Undo things done by ice_init_interrupt_scheme * @pf: board private structure */ void ice_clear_interrupt_scheme(struct ice_pf *pf) { pci_free_irq_vectors(pf->pdev); ice_deinit_irq_tracker(pf); } /** * ice_init_interrupt_scheme - Determine proper interrupt scheme * @pf: board private structure to initialize */ int ice_init_interrupt_scheme(struct ice_pf *pf) { int total_vectors = pf->hw.func_caps.common_cap.num_msix_vectors; int vectors, max_vectors; vectors = ice_ena_msix_range(pf); if (vectors < 0) return -ENOMEM; if (pci_msix_can_alloc_dyn(pf->pdev)) max_vectors = total_vectors; else max_vectors = vectors; ice_init_irq_tracker(pf, max_vectors, vectors); return 0; } /** * ice_alloc_irq - Allocate new interrupt vector * @pf: board private structure * @dyn_only: force dynamic allocation of the interrupt * * Allocate new interrupt vector for a given owner id. * return struct msi_map with interrupt details and track * allocated interrupt appropriately. * * This function reserves new irq entry from the irq_tracker. * if according to the tracker information all interrupts that * were allocated with ice_pci_alloc_irq_vectors are already used * and dynamically allocated interrupts are supported then new * interrupt will be allocated with pci_msix_alloc_irq_at. * * Some callers may only support dynamically allocated interrupts. * This is indicated with dyn_only flag. * * On failure, return map with negative .index. The caller * is expected to check returned map index. * */ struct msi_map ice_alloc_irq(struct ice_pf *pf, bool dyn_only) { int sriov_base_vector = pf->sriov_base_vector; struct msi_map map = { .index = -ENOENT }; struct device *dev = ice_pf_to_dev(pf); struct ice_irq_entry *entry; entry = ice_get_irq_res(pf, dyn_only); if (!entry) return map; /* fail if we're about to violate SRIOV vectors space */ if (sriov_base_vector && entry->index >= sriov_base_vector) goto exit_free_res; if (pci_msix_can_alloc_dyn(pf->pdev) && entry->dynamic) { map = pci_msix_alloc_irq_at(pf->pdev, entry->index, NULL); if (map.index < 0) goto exit_free_res; dev_dbg(dev, "allocated new irq at index %d\n", map.index); } else { map.index = entry->index; map.virq = pci_irq_vector(pf->pdev, map.index); } return map; exit_free_res: dev_err(dev, "Could not allocate irq at idx %d\n", entry->index); ice_free_irq_res(pf, entry->index); return map; } /** * ice_free_irq - Free interrupt vector * @pf: board private structure * @map: map with interrupt details * * Remove allocated interrupt from the interrupt tracker. If interrupt was * allocated dynamically, free respective interrupt vector. */ void ice_free_irq(struct ice_pf *pf, struct msi_map map) { struct ice_irq_entry *entry; entry = xa_load(&pf->irq_tracker.entries, map.index); if (!entry) { dev_err(ice_pf_to_dev(pf), "Failed to get MSIX interrupt entry at index %d", map.index); return; } dev_dbg(ice_pf_to_dev(pf), "Free irq at index %d\n", map.index); if (entry->dynamic) pci_msix_free_irq(pf->pdev, map); ice_free_irq_res(pf, map.index); } /** * ice_get_max_used_msix_vector - Get the max used interrupt vector * @pf: board private structure * * Return index of maximum used interrupt vectors with respect to the * beginning of the MSIX table. Take into account that some interrupts * may have been dynamically allocated after MSIX was initially enabled. */ int ice_get_max_used_msix_vector(struct ice_pf *pf) { unsigned long start, index, max_idx; void *entry; /* Treat all preallocated interrupts as used */ start = pf->irq_tracker.num_static; max_idx = start - 1; xa_for_each_start(&pf->irq_tracker.entries, index, entry, start) { if (index > max_idx) max_idx = index; } return max_idx; }
linux-master
drivers/net/ethernet/intel/ice/ice_irq.c