treewide: kzalloc() -> kcalloc()
[linux-2.6-microblaze.git] / drivers / net / ethernet / intel / igb / igb_main.c
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright(c) 2007 - 2018 Intel Corporation. */
3
4 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
5
6 #include <linux/module.h>
7 #include <linux/types.h>
8 #include <linux/init.h>
9 #include <linux/bitops.h>
10 #include <linux/vmalloc.h>
11 #include <linux/pagemap.h>
12 #include <linux/netdevice.h>
13 #include <linux/ipv6.h>
14 #include <linux/slab.h>
15 #include <net/checksum.h>
16 #include <net/ip6_checksum.h>
17 #include <net/pkt_sched.h>
18 #include <net/pkt_cls.h>
19 #include <linux/net_tstamp.h>
20 #include <linux/mii.h>
21 #include <linux/ethtool.h>
22 #include <linux/if.h>
23 #include <linux/if_vlan.h>
24 #include <linux/pci.h>
25 #include <linux/pci-aspm.h>
26 #include <linux/delay.h>
27 #include <linux/interrupt.h>
28 #include <linux/ip.h>
29 #include <linux/tcp.h>
30 #include <linux/sctp.h>
31 #include <linux/if_ether.h>
32 #include <linux/aer.h>
33 #include <linux/prefetch.h>
34 #include <linux/pm_runtime.h>
35 #include <linux/etherdevice.h>
36 #ifdef CONFIG_IGB_DCA
37 #include <linux/dca.h>
38 #endif
39 #include <linux/i2c.h>
40 #include "igb.h"
41
42 #define MAJ 5
43 #define MIN 4
44 #define BUILD 0
45 #define DRV_VERSION __stringify(MAJ) "." __stringify(MIN) "." \
46 __stringify(BUILD) "-k"
47
48 enum queue_mode {
49         QUEUE_MODE_STRICT_PRIORITY,
50         QUEUE_MODE_STREAM_RESERVATION,
51 };
52
53 enum tx_queue_prio {
54         TX_QUEUE_PRIO_HIGH,
55         TX_QUEUE_PRIO_LOW,
56 };
57
58 char igb_driver_name[] = "igb";
59 char igb_driver_version[] = DRV_VERSION;
60 static const char igb_driver_string[] =
61                                 "Intel(R) Gigabit Ethernet Network Driver";
62 static const char igb_copyright[] =
63                                 "Copyright (c) 2007-2014 Intel Corporation.";
64
65 static const struct e1000_info *igb_info_tbl[] = {
66         [board_82575] = &e1000_82575_info,
67 };
68
69 static const struct pci_device_id igb_pci_tbl[] = {
70         { PCI_VDEVICE(INTEL, E1000_DEV_ID_I354_BACKPLANE_1GBPS) },
71         { PCI_VDEVICE(INTEL, E1000_DEV_ID_I354_SGMII) },
72         { PCI_VDEVICE(INTEL, E1000_DEV_ID_I354_BACKPLANE_2_5GBPS) },
73         { PCI_VDEVICE(INTEL, E1000_DEV_ID_I211_COPPER), board_82575 },
74         { PCI_VDEVICE(INTEL, E1000_DEV_ID_I210_COPPER), board_82575 },
75         { PCI_VDEVICE(INTEL, E1000_DEV_ID_I210_FIBER), board_82575 },
76         { PCI_VDEVICE(INTEL, E1000_DEV_ID_I210_SERDES), board_82575 },
77         { PCI_VDEVICE(INTEL, E1000_DEV_ID_I210_SGMII), board_82575 },
78         { PCI_VDEVICE(INTEL, E1000_DEV_ID_I210_COPPER_FLASHLESS), board_82575 },
79         { PCI_VDEVICE(INTEL, E1000_DEV_ID_I210_SERDES_FLASHLESS), board_82575 },
80         { PCI_VDEVICE(INTEL, E1000_DEV_ID_I350_COPPER), board_82575 },
81         { PCI_VDEVICE(INTEL, E1000_DEV_ID_I350_FIBER), board_82575 },
82         { PCI_VDEVICE(INTEL, E1000_DEV_ID_I350_SERDES), board_82575 },
83         { PCI_VDEVICE(INTEL, E1000_DEV_ID_I350_SGMII), board_82575 },
84         { PCI_VDEVICE(INTEL, E1000_DEV_ID_82580_COPPER), board_82575 },
85         { PCI_VDEVICE(INTEL, E1000_DEV_ID_82580_FIBER), board_82575 },
86         { PCI_VDEVICE(INTEL, E1000_DEV_ID_82580_QUAD_FIBER), board_82575 },
87         { PCI_VDEVICE(INTEL, E1000_DEV_ID_82580_SERDES), board_82575 },
88         { PCI_VDEVICE(INTEL, E1000_DEV_ID_82580_SGMII), board_82575 },
89         { PCI_VDEVICE(INTEL, E1000_DEV_ID_82580_COPPER_DUAL), board_82575 },
90         { PCI_VDEVICE(INTEL, E1000_DEV_ID_DH89XXCC_SGMII), board_82575 },
91         { PCI_VDEVICE(INTEL, E1000_DEV_ID_DH89XXCC_SERDES), board_82575 },
92         { PCI_VDEVICE(INTEL, E1000_DEV_ID_DH89XXCC_BACKPLANE), board_82575 },
93         { PCI_VDEVICE(INTEL, E1000_DEV_ID_DH89XXCC_SFP), board_82575 },
94         { PCI_VDEVICE(INTEL, E1000_DEV_ID_82576), board_82575 },
95         { PCI_VDEVICE(INTEL, E1000_DEV_ID_82576_NS), board_82575 },
96         { PCI_VDEVICE(INTEL, E1000_DEV_ID_82576_NS_SERDES), board_82575 },
97         { PCI_VDEVICE(INTEL, E1000_DEV_ID_82576_FIBER), board_82575 },
98         { PCI_VDEVICE(INTEL, E1000_DEV_ID_82576_SERDES), board_82575 },
99         { PCI_VDEVICE(INTEL, E1000_DEV_ID_82576_SERDES_QUAD), board_82575 },
100         { PCI_VDEVICE(INTEL, E1000_DEV_ID_82576_QUAD_COPPER_ET2), board_82575 },
101         { PCI_VDEVICE(INTEL, E1000_DEV_ID_82576_QUAD_COPPER), board_82575 },
102         { PCI_VDEVICE(INTEL, E1000_DEV_ID_82575EB_COPPER), board_82575 },
103         { PCI_VDEVICE(INTEL, E1000_DEV_ID_82575EB_FIBER_SERDES), board_82575 },
104         { PCI_VDEVICE(INTEL, E1000_DEV_ID_82575GB_QUAD_COPPER), board_82575 },
105         /* required last entry */
106         {0, }
107 };
108
109 MODULE_DEVICE_TABLE(pci, igb_pci_tbl);
110
111 static int igb_setup_all_tx_resources(struct igb_adapter *);
112 static int igb_setup_all_rx_resources(struct igb_adapter *);
113 static void igb_free_all_tx_resources(struct igb_adapter *);
114 static void igb_free_all_rx_resources(struct igb_adapter *);
115 static void igb_setup_mrqc(struct igb_adapter *);
116 static int igb_probe(struct pci_dev *, const struct pci_device_id *);
117 static void igb_remove(struct pci_dev *pdev);
118 static int igb_sw_init(struct igb_adapter *);
119 int igb_open(struct net_device *);
120 int igb_close(struct net_device *);
121 static void igb_configure(struct igb_adapter *);
122 static void igb_configure_tx(struct igb_adapter *);
123 static void igb_configure_rx(struct igb_adapter *);
124 static void igb_clean_all_tx_rings(struct igb_adapter *);
125 static void igb_clean_all_rx_rings(struct igb_adapter *);
126 static void igb_clean_tx_ring(struct igb_ring *);
127 static void igb_clean_rx_ring(struct igb_ring *);
128 static void igb_set_rx_mode(struct net_device *);
129 static void igb_update_phy_info(struct timer_list *);
130 static void igb_watchdog(struct timer_list *);
131 static void igb_watchdog_task(struct work_struct *);
132 static netdev_tx_t igb_xmit_frame(struct sk_buff *skb, struct net_device *);
133 static void igb_get_stats64(struct net_device *dev,
134                             struct rtnl_link_stats64 *stats);
135 static int igb_change_mtu(struct net_device *, int);
136 static int igb_set_mac(struct net_device *, void *);
137 static void igb_set_uta(struct igb_adapter *adapter, bool set);
138 static irqreturn_t igb_intr(int irq, void *);
139 static irqreturn_t igb_intr_msi(int irq, void *);
140 static irqreturn_t igb_msix_other(int irq, void *);
141 static irqreturn_t igb_msix_ring(int irq, void *);
142 #ifdef CONFIG_IGB_DCA
143 static void igb_update_dca(struct igb_q_vector *);
144 static void igb_setup_dca(struct igb_adapter *);
145 #endif /* CONFIG_IGB_DCA */
146 static int igb_poll(struct napi_struct *, int);
147 static bool igb_clean_tx_irq(struct igb_q_vector *, int);
148 static int igb_clean_rx_irq(struct igb_q_vector *, int);
149 static int igb_ioctl(struct net_device *, struct ifreq *, int cmd);
150 static void igb_tx_timeout(struct net_device *);
151 static void igb_reset_task(struct work_struct *);
152 static void igb_vlan_mode(struct net_device *netdev,
153                           netdev_features_t features);
154 static int igb_vlan_rx_add_vid(struct net_device *, __be16, u16);
155 static int igb_vlan_rx_kill_vid(struct net_device *, __be16, u16);
156 static void igb_restore_vlan(struct igb_adapter *);
157 static void igb_rar_set_index(struct igb_adapter *, u32);
158 static void igb_ping_all_vfs(struct igb_adapter *);
159 static void igb_msg_task(struct igb_adapter *);
160 static void igb_vmm_control(struct igb_adapter *);
161 static int igb_set_vf_mac(struct igb_adapter *, int, unsigned char *);
162 static void igb_flush_mac_table(struct igb_adapter *);
163 static int igb_available_rars(struct igb_adapter *, u8);
164 static void igb_set_default_mac_filter(struct igb_adapter *);
165 static int igb_uc_sync(struct net_device *, const unsigned char *);
166 static int igb_uc_unsync(struct net_device *, const unsigned char *);
167 static void igb_restore_vf_multicasts(struct igb_adapter *adapter);
168 static int igb_ndo_set_vf_mac(struct net_device *netdev, int vf, u8 *mac);
169 static int igb_ndo_set_vf_vlan(struct net_device *netdev,
170                                int vf, u16 vlan, u8 qos, __be16 vlan_proto);
171 static int igb_ndo_set_vf_bw(struct net_device *, int, int, int);
172 static int igb_ndo_set_vf_spoofchk(struct net_device *netdev, int vf,
173                                    bool setting);
174 static int igb_ndo_set_vf_trust(struct net_device *netdev, int vf,
175                                 bool setting);
176 static int igb_ndo_get_vf_config(struct net_device *netdev, int vf,
177                                  struct ifla_vf_info *ivi);
178 static void igb_check_vf_rate_limit(struct igb_adapter *);
179 static void igb_nfc_filter_exit(struct igb_adapter *adapter);
180 static void igb_nfc_filter_restore(struct igb_adapter *adapter);
181
182 #ifdef CONFIG_PCI_IOV
183 static int igb_vf_configure(struct igb_adapter *adapter, int vf);
184 static int igb_pci_enable_sriov(struct pci_dev *dev, int num_vfs);
185 static int igb_disable_sriov(struct pci_dev *dev);
186 static int igb_pci_disable_sriov(struct pci_dev *dev);
187 #endif
188
189 static int igb_suspend(struct device *);
190 static int igb_resume(struct device *);
191 static int igb_runtime_suspend(struct device *dev);
192 static int igb_runtime_resume(struct device *dev);
193 static int igb_runtime_idle(struct device *dev);
194 static const struct dev_pm_ops igb_pm_ops = {
195         SET_SYSTEM_SLEEP_PM_OPS(igb_suspend, igb_resume)
196         SET_RUNTIME_PM_OPS(igb_runtime_suspend, igb_runtime_resume,
197                         igb_runtime_idle)
198 };
199 static void igb_shutdown(struct pci_dev *);
200 static int igb_pci_sriov_configure(struct pci_dev *dev, int num_vfs);
201 #ifdef CONFIG_IGB_DCA
202 static int igb_notify_dca(struct notifier_block *, unsigned long, void *);
203 static struct notifier_block dca_notifier = {
204         .notifier_call  = igb_notify_dca,
205         .next           = NULL,
206         .priority       = 0
207 };
208 #endif
209 #ifdef CONFIG_NET_POLL_CONTROLLER
210 /* for netdump / net console */
211 static void igb_netpoll(struct net_device *);
212 #endif
213 #ifdef CONFIG_PCI_IOV
214 static unsigned int max_vfs;
215 module_param(max_vfs, uint, 0);
216 MODULE_PARM_DESC(max_vfs, "Maximum number of virtual functions to allocate per physical function");
217 #endif /* CONFIG_PCI_IOV */
218
219 static pci_ers_result_t igb_io_error_detected(struct pci_dev *,
220                      pci_channel_state_t);
221 static pci_ers_result_t igb_io_slot_reset(struct pci_dev *);
222 static void igb_io_resume(struct pci_dev *);
223
224 static const struct pci_error_handlers igb_err_handler = {
225         .error_detected = igb_io_error_detected,
226         .slot_reset = igb_io_slot_reset,
227         .resume = igb_io_resume,
228 };
229
230 static void igb_init_dmac(struct igb_adapter *adapter, u32 pba);
231
232 static struct pci_driver igb_driver = {
233         .name     = igb_driver_name,
234         .id_table = igb_pci_tbl,
235         .probe    = igb_probe,
236         .remove   = igb_remove,
237 #ifdef CONFIG_PM
238         .driver.pm = &igb_pm_ops,
239 #endif
240         .shutdown = igb_shutdown,
241         .sriov_configure = igb_pci_sriov_configure,
242         .err_handler = &igb_err_handler
243 };
244
245 MODULE_AUTHOR("Intel Corporation, <e1000-devel@lists.sourceforge.net>");
246 MODULE_DESCRIPTION("Intel(R) Gigabit Ethernet Network Driver");
247 MODULE_LICENSE("GPL");
248 MODULE_VERSION(DRV_VERSION);
249
250 #define DEFAULT_MSG_ENABLE (NETIF_MSG_DRV|NETIF_MSG_PROBE|NETIF_MSG_LINK)
251 static int debug = -1;
252 module_param(debug, int, 0);
253 MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all)");
254
255 struct igb_reg_info {
256         u32 ofs;
257         char *name;
258 };
259
260 static const struct igb_reg_info igb_reg_info_tbl[] = {
261
262         /* General Registers */
263         {E1000_CTRL, "CTRL"},
264         {E1000_STATUS, "STATUS"},
265         {E1000_CTRL_EXT, "CTRL_EXT"},
266
267         /* Interrupt Registers */
268         {E1000_ICR, "ICR"},
269
270         /* RX Registers */
271         {E1000_RCTL, "RCTL"},
272         {E1000_RDLEN(0), "RDLEN"},
273         {E1000_RDH(0), "RDH"},
274         {E1000_RDT(0), "RDT"},
275         {E1000_RXDCTL(0), "RXDCTL"},
276         {E1000_RDBAL(0), "RDBAL"},
277         {E1000_RDBAH(0), "RDBAH"},
278
279         /* TX Registers */
280         {E1000_TCTL, "TCTL"},
281         {E1000_TDBAL(0), "TDBAL"},
282         {E1000_TDBAH(0), "TDBAH"},
283         {E1000_TDLEN(0), "TDLEN"},
284         {E1000_TDH(0), "TDH"},
285         {E1000_TDT(0), "TDT"},
286         {E1000_TXDCTL(0), "TXDCTL"},
287         {E1000_TDFH, "TDFH"},
288         {E1000_TDFT, "TDFT"},
289         {E1000_TDFHS, "TDFHS"},
290         {E1000_TDFPC, "TDFPC"},
291
292         /* List Terminator */
293         {}
294 };
295
296 /* igb_regdump - register printout routine */
297 static void igb_regdump(struct e1000_hw *hw, struct igb_reg_info *reginfo)
298 {
299         int n = 0;
300         char rname[16];
301         u32 regs[8];
302
303         switch (reginfo->ofs) {
304         case E1000_RDLEN(0):
305                 for (n = 0; n < 4; n++)
306                         regs[n] = rd32(E1000_RDLEN(n));
307                 break;
308         case E1000_RDH(0):
309                 for (n = 0; n < 4; n++)
310                         regs[n] = rd32(E1000_RDH(n));
311                 break;
312         case E1000_RDT(0):
313                 for (n = 0; n < 4; n++)
314                         regs[n] = rd32(E1000_RDT(n));
315                 break;
316         case E1000_RXDCTL(0):
317                 for (n = 0; n < 4; n++)
318                         regs[n] = rd32(E1000_RXDCTL(n));
319                 break;
320         case E1000_RDBAL(0):
321                 for (n = 0; n < 4; n++)
322                         regs[n] = rd32(E1000_RDBAL(n));
323                 break;
324         case E1000_RDBAH(0):
325                 for (n = 0; n < 4; n++)
326                         regs[n] = rd32(E1000_RDBAH(n));
327                 break;
328         case E1000_TDBAL(0):
329                 for (n = 0; n < 4; n++)
330                         regs[n] = rd32(E1000_RDBAL(n));
331                 break;
332         case E1000_TDBAH(0):
333                 for (n = 0; n < 4; n++)
334                         regs[n] = rd32(E1000_TDBAH(n));
335                 break;
336         case E1000_TDLEN(0):
337                 for (n = 0; n < 4; n++)
338                         regs[n] = rd32(E1000_TDLEN(n));
339                 break;
340         case E1000_TDH(0):
341                 for (n = 0; n < 4; n++)
342                         regs[n] = rd32(E1000_TDH(n));
343                 break;
344         case E1000_TDT(0):
345                 for (n = 0; n < 4; n++)
346                         regs[n] = rd32(E1000_TDT(n));
347                 break;
348         case E1000_TXDCTL(0):
349                 for (n = 0; n < 4; n++)
350                         regs[n] = rd32(E1000_TXDCTL(n));
351                 break;
352         default:
353                 pr_info("%-15s %08x\n", reginfo->name, rd32(reginfo->ofs));
354                 return;
355         }
356
357         snprintf(rname, 16, "%s%s", reginfo->name, "[0-3]");
358         pr_info("%-15s %08x %08x %08x %08x\n", rname, regs[0], regs[1],
359                 regs[2], regs[3]);
360 }
361
362 /* igb_dump - Print registers, Tx-rings and Rx-rings */
363 static void igb_dump(struct igb_adapter *adapter)
364 {
365         struct net_device *netdev = adapter->netdev;
366         struct e1000_hw *hw = &adapter->hw;
367         struct igb_reg_info *reginfo;
368         struct igb_ring *tx_ring;
369         union e1000_adv_tx_desc *tx_desc;
370         struct my_u0 { u64 a; u64 b; } *u0;
371         struct igb_ring *rx_ring;
372         union e1000_adv_rx_desc *rx_desc;
373         u32 staterr;
374         u16 i, n;
375
376         if (!netif_msg_hw(adapter))
377                 return;
378
379         /* Print netdevice Info */
380         if (netdev) {
381                 dev_info(&adapter->pdev->dev, "Net device Info\n");
382                 pr_info("Device Name     state            trans_start\n");
383                 pr_info("%-15s %016lX %016lX\n", netdev->name,
384                         netdev->state, dev_trans_start(netdev));
385         }
386
387         /* Print Registers */
388         dev_info(&adapter->pdev->dev, "Register Dump\n");
389         pr_info(" Register Name   Value\n");
390         for (reginfo = (struct igb_reg_info *)igb_reg_info_tbl;
391              reginfo->name; reginfo++) {
392                 igb_regdump(hw, reginfo);
393         }
394
395         /* Print TX Ring Summary */
396         if (!netdev || !netif_running(netdev))
397                 goto exit;
398
399         dev_info(&adapter->pdev->dev, "TX Rings Summary\n");
400         pr_info("Queue [NTU] [NTC] [bi(ntc)->dma  ] leng ntw timestamp\n");
401         for (n = 0; n < adapter->num_tx_queues; n++) {
402                 struct igb_tx_buffer *buffer_info;
403                 tx_ring = adapter->tx_ring[n];
404                 buffer_info = &tx_ring->tx_buffer_info[tx_ring->next_to_clean];
405                 pr_info(" %5d %5X %5X %016llX %04X %p %016llX\n",
406                         n, tx_ring->next_to_use, tx_ring->next_to_clean,
407                         (u64)dma_unmap_addr(buffer_info, dma),
408                         dma_unmap_len(buffer_info, len),
409                         buffer_info->next_to_watch,
410                         (u64)buffer_info->time_stamp);
411         }
412
413         /* Print TX Rings */
414         if (!netif_msg_tx_done(adapter))
415                 goto rx_ring_summary;
416
417         dev_info(&adapter->pdev->dev, "TX Rings Dump\n");
418
419         /* Transmit Descriptor Formats
420          *
421          * Advanced Transmit Descriptor
422          *   +--------------------------------------------------------------+
423          * 0 |         Buffer Address [63:0]                                |
424          *   +--------------------------------------------------------------+
425          * 8 | PAYLEN  | PORTS  |CC|IDX | STA | DCMD  |DTYP|MAC|RSV| DTALEN |
426          *   +--------------------------------------------------------------+
427          *   63      46 45    40 39 38 36 35 32 31   24             15       0
428          */
429
430         for (n = 0; n < adapter->num_tx_queues; n++) {
431                 tx_ring = adapter->tx_ring[n];
432                 pr_info("------------------------------------\n");
433                 pr_info("TX QUEUE INDEX = %d\n", tx_ring->queue_index);
434                 pr_info("------------------------------------\n");
435                 pr_info("T [desc]     [address 63:0  ] [PlPOCIStDDM Ln] [bi->dma       ] leng  ntw timestamp        bi->skb\n");
436
437                 for (i = 0; tx_ring->desc && (i < tx_ring->count); i++) {
438                         const char *next_desc;
439                         struct igb_tx_buffer *buffer_info;
440                         tx_desc = IGB_TX_DESC(tx_ring, i);
441                         buffer_info = &tx_ring->tx_buffer_info[i];
442                         u0 = (struct my_u0 *)tx_desc;
443                         if (i == tx_ring->next_to_use &&
444                             i == tx_ring->next_to_clean)
445                                 next_desc = " NTC/U";
446                         else if (i == tx_ring->next_to_use)
447                                 next_desc = " NTU";
448                         else if (i == tx_ring->next_to_clean)
449                                 next_desc = " NTC";
450                         else
451                                 next_desc = "";
452
453                         pr_info("T [0x%03X]    %016llX %016llX %016llX %04X  %p %016llX %p%s\n",
454                                 i, le64_to_cpu(u0->a),
455                                 le64_to_cpu(u0->b),
456                                 (u64)dma_unmap_addr(buffer_info, dma),
457                                 dma_unmap_len(buffer_info, len),
458                                 buffer_info->next_to_watch,
459                                 (u64)buffer_info->time_stamp,
460                                 buffer_info->skb, next_desc);
461
462                         if (netif_msg_pktdata(adapter) && buffer_info->skb)
463                                 print_hex_dump(KERN_INFO, "",
464                                         DUMP_PREFIX_ADDRESS,
465                                         16, 1, buffer_info->skb->data,
466                                         dma_unmap_len(buffer_info, len),
467                                         true);
468                 }
469         }
470
471         /* Print RX Rings Summary */
472 rx_ring_summary:
473         dev_info(&adapter->pdev->dev, "RX Rings Summary\n");
474         pr_info("Queue [NTU] [NTC]\n");
475         for (n = 0; n < adapter->num_rx_queues; n++) {
476                 rx_ring = adapter->rx_ring[n];
477                 pr_info(" %5d %5X %5X\n",
478                         n, rx_ring->next_to_use, rx_ring->next_to_clean);
479         }
480
481         /* Print RX Rings */
482         if (!netif_msg_rx_status(adapter))
483                 goto exit;
484
485         dev_info(&adapter->pdev->dev, "RX Rings Dump\n");
486
487         /* Advanced Receive Descriptor (Read) Format
488          *    63                                           1        0
489          *    +-----------------------------------------------------+
490          *  0 |       Packet Buffer Address [63:1]           |A0/NSE|
491          *    +----------------------------------------------+------+
492          *  8 |       Header Buffer Address [63:1]           |  DD  |
493          *    +-----------------------------------------------------+
494          *
495          *
496          * Advanced Receive Descriptor (Write-Back) Format
497          *
498          *   63       48 47    32 31  30      21 20 17 16   4 3     0
499          *   +------------------------------------------------------+
500          * 0 | Packet     IP     |SPH| HDR_LEN   | RSV|Packet|  RSS |
501          *   | Checksum   Ident  |   |           |    | Type | Type |
502          *   +------------------------------------------------------+
503          * 8 | VLAN Tag | Length | Extended Error | Extended Status |
504          *   +------------------------------------------------------+
505          *   63       48 47    32 31            20 19               0
506          */
507
508         for (n = 0; n < adapter->num_rx_queues; n++) {
509                 rx_ring = adapter->rx_ring[n];
510                 pr_info("------------------------------------\n");
511                 pr_info("RX QUEUE INDEX = %d\n", rx_ring->queue_index);
512                 pr_info("------------------------------------\n");
513                 pr_info("R  [desc]      [ PktBuf     A0] [  HeadBuf   DD] [bi->dma       ] [bi->skb] <-- Adv Rx Read format\n");
514                 pr_info("RWB[desc]      [PcsmIpSHl PtRs] [vl er S cks ln] ---------------- [bi->skb] <-- Adv Rx Write-Back format\n");
515
516                 for (i = 0; i < rx_ring->count; i++) {
517                         const char *next_desc;
518                         struct igb_rx_buffer *buffer_info;
519                         buffer_info = &rx_ring->rx_buffer_info[i];
520                         rx_desc = IGB_RX_DESC(rx_ring, i);
521                         u0 = (struct my_u0 *)rx_desc;
522                         staterr = le32_to_cpu(rx_desc->wb.upper.status_error);
523
524                         if (i == rx_ring->next_to_use)
525                                 next_desc = " NTU";
526                         else if (i == rx_ring->next_to_clean)
527                                 next_desc = " NTC";
528                         else
529                                 next_desc = "";
530
531                         if (staterr & E1000_RXD_STAT_DD) {
532                                 /* Descriptor Done */
533                                 pr_info("%s[0x%03X]     %016llX %016llX ---------------- %s\n",
534                                         "RWB", i,
535                                         le64_to_cpu(u0->a),
536                                         le64_to_cpu(u0->b),
537                                         next_desc);
538                         } else {
539                                 pr_info("%s[0x%03X]     %016llX %016llX %016llX %s\n",
540                                         "R  ", i,
541                                         le64_to_cpu(u0->a),
542                                         le64_to_cpu(u0->b),
543                                         (u64)buffer_info->dma,
544                                         next_desc);
545
546                                 if (netif_msg_pktdata(adapter) &&
547                                     buffer_info->dma && buffer_info->page) {
548                                         print_hex_dump(KERN_INFO, "",
549                                           DUMP_PREFIX_ADDRESS,
550                                           16, 1,
551                                           page_address(buffer_info->page) +
552                                                       buffer_info->page_offset,
553                                           igb_rx_bufsz(rx_ring), true);
554                                 }
555                         }
556                 }
557         }
558
559 exit:
560         return;
561 }
562
563 /**
564  *  igb_get_i2c_data - Reads the I2C SDA data bit
565  *  @hw: pointer to hardware structure
566  *  @i2cctl: Current value of I2CCTL register
567  *
568  *  Returns the I2C data bit value
569  **/
570 static int igb_get_i2c_data(void *data)
571 {
572         struct igb_adapter *adapter = (struct igb_adapter *)data;
573         struct e1000_hw *hw = &adapter->hw;
574         s32 i2cctl = rd32(E1000_I2CPARAMS);
575
576         return !!(i2cctl & E1000_I2C_DATA_IN);
577 }
578
579 /**
580  *  igb_set_i2c_data - Sets the I2C data bit
581  *  @data: pointer to hardware structure
582  *  @state: I2C data value (0 or 1) to set
583  *
584  *  Sets the I2C data bit
585  **/
586 static void igb_set_i2c_data(void *data, int state)
587 {
588         struct igb_adapter *adapter = (struct igb_adapter *)data;
589         struct e1000_hw *hw = &adapter->hw;
590         s32 i2cctl = rd32(E1000_I2CPARAMS);
591
592         if (state)
593                 i2cctl |= E1000_I2C_DATA_OUT;
594         else
595                 i2cctl &= ~E1000_I2C_DATA_OUT;
596
597         i2cctl &= ~E1000_I2C_DATA_OE_N;
598         i2cctl |= E1000_I2C_CLK_OE_N;
599         wr32(E1000_I2CPARAMS, i2cctl);
600         wrfl();
601
602 }
603
604 /**
605  *  igb_set_i2c_clk - Sets the I2C SCL clock
606  *  @data: pointer to hardware structure
607  *  @state: state to set clock
608  *
609  *  Sets the I2C clock line to state
610  **/
611 static void igb_set_i2c_clk(void *data, int state)
612 {
613         struct igb_adapter *adapter = (struct igb_adapter *)data;
614         struct e1000_hw *hw = &adapter->hw;
615         s32 i2cctl = rd32(E1000_I2CPARAMS);
616
617         if (state) {
618                 i2cctl |= E1000_I2C_CLK_OUT;
619                 i2cctl &= ~E1000_I2C_CLK_OE_N;
620         } else {
621                 i2cctl &= ~E1000_I2C_CLK_OUT;
622                 i2cctl &= ~E1000_I2C_CLK_OE_N;
623         }
624         wr32(E1000_I2CPARAMS, i2cctl);
625         wrfl();
626 }
627
628 /**
629  *  igb_get_i2c_clk - Gets the I2C SCL clock state
630  *  @data: pointer to hardware structure
631  *
632  *  Gets the I2C clock state
633  **/
634 static int igb_get_i2c_clk(void *data)
635 {
636         struct igb_adapter *adapter = (struct igb_adapter *)data;
637         struct e1000_hw *hw = &adapter->hw;
638         s32 i2cctl = rd32(E1000_I2CPARAMS);
639
640         return !!(i2cctl & E1000_I2C_CLK_IN);
641 }
642
643 static const struct i2c_algo_bit_data igb_i2c_algo = {
644         .setsda         = igb_set_i2c_data,
645         .setscl         = igb_set_i2c_clk,
646         .getsda         = igb_get_i2c_data,
647         .getscl         = igb_get_i2c_clk,
648         .udelay         = 5,
649         .timeout        = 20,
650 };
651
652 /**
653  *  igb_get_hw_dev - return device
654  *  @hw: pointer to hardware structure
655  *
656  *  used by hardware layer to print debugging information
657  **/
658 struct net_device *igb_get_hw_dev(struct e1000_hw *hw)
659 {
660         struct igb_adapter *adapter = hw->back;
661         return adapter->netdev;
662 }
663
664 /**
665  *  igb_init_module - Driver Registration Routine
666  *
667  *  igb_init_module is the first routine called when the driver is
668  *  loaded. All it does is register with the PCI subsystem.
669  **/
670 static int __init igb_init_module(void)
671 {
672         int ret;
673
674         pr_info("%s - version %s\n",
675                igb_driver_string, igb_driver_version);
676         pr_info("%s\n", igb_copyright);
677
678 #ifdef CONFIG_IGB_DCA
679         dca_register_notify(&dca_notifier);
680 #endif
681         ret = pci_register_driver(&igb_driver);
682         return ret;
683 }
684
685 module_init(igb_init_module);
686
687 /**
688  *  igb_exit_module - Driver Exit Cleanup Routine
689  *
690  *  igb_exit_module is called just before the driver is removed
691  *  from memory.
692  **/
693 static void __exit igb_exit_module(void)
694 {
695 #ifdef CONFIG_IGB_DCA
696         dca_unregister_notify(&dca_notifier);
697 #endif
698         pci_unregister_driver(&igb_driver);
699 }
700
701 module_exit(igb_exit_module);
702
703 #define Q_IDX_82576(i) (((i & 0x1) << 3) + (i >> 1))
704 /**
705  *  igb_cache_ring_register - Descriptor ring to register mapping
706  *  @adapter: board private structure to initialize
707  *
708  *  Once we know the feature-set enabled for the device, we'll cache
709  *  the register offset the descriptor ring is assigned to.
710  **/
711 static void igb_cache_ring_register(struct igb_adapter *adapter)
712 {
713         int i = 0, j = 0;
714         u32 rbase_offset = adapter->vfs_allocated_count;
715
716         switch (adapter->hw.mac.type) {
717         case e1000_82576:
718                 /* The queues are allocated for virtualization such that VF 0
719                  * is allocated queues 0 and 8, VF 1 queues 1 and 9, etc.
720                  * In order to avoid collision we start at the first free queue
721                  * and continue consuming queues in the same sequence
722                  */
723                 if (adapter->vfs_allocated_count) {
724                         for (; i < adapter->rss_queues; i++)
725                                 adapter->rx_ring[i]->reg_idx = rbase_offset +
726                                                                Q_IDX_82576(i);
727                 }
728                 /* Fall through */
729         case e1000_82575:
730         case e1000_82580:
731         case e1000_i350:
732         case e1000_i354:
733         case e1000_i210:
734         case e1000_i211:
735                 /* Fall through */
736         default:
737                 for (; i < adapter->num_rx_queues; i++)
738                         adapter->rx_ring[i]->reg_idx = rbase_offset + i;
739                 for (; j < adapter->num_tx_queues; j++)
740                         adapter->tx_ring[j]->reg_idx = rbase_offset + j;
741                 break;
742         }
743 }
744
745 u32 igb_rd32(struct e1000_hw *hw, u32 reg)
746 {
747         struct igb_adapter *igb = container_of(hw, struct igb_adapter, hw);
748         u8 __iomem *hw_addr = READ_ONCE(hw->hw_addr);
749         u32 value = 0;
750
751         if (E1000_REMOVED(hw_addr))
752                 return ~value;
753
754         value = readl(&hw_addr[reg]);
755
756         /* reads should not return all F's */
757         if (!(~value) && (!reg || !(~readl(hw_addr)))) {
758                 struct net_device *netdev = igb->netdev;
759                 hw->hw_addr = NULL;
760                 netdev_err(netdev, "PCIe link lost\n");
761         }
762
763         return value;
764 }
765
766 /**
767  *  igb_write_ivar - configure ivar for given MSI-X vector
768  *  @hw: pointer to the HW structure
769  *  @msix_vector: vector number we are allocating to a given ring
770  *  @index: row index of IVAR register to write within IVAR table
771  *  @offset: column offset of in IVAR, should be multiple of 8
772  *
773  *  This function is intended to handle the writing of the IVAR register
774  *  for adapters 82576 and newer.  The IVAR table consists of 2 columns,
775  *  each containing an cause allocation for an Rx and Tx ring, and a
776  *  variable number of rows depending on the number of queues supported.
777  **/
778 static void igb_write_ivar(struct e1000_hw *hw, int msix_vector,
779                            int index, int offset)
780 {
781         u32 ivar = array_rd32(E1000_IVAR0, index);
782
783         /* clear any bits that are currently set */
784         ivar &= ~((u32)0xFF << offset);
785
786         /* write vector and valid bit */
787         ivar |= (msix_vector | E1000_IVAR_VALID) << offset;
788
789         array_wr32(E1000_IVAR0, index, ivar);
790 }
791
792 #define IGB_N0_QUEUE -1
793 static void igb_assign_vector(struct igb_q_vector *q_vector, int msix_vector)
794 {
795         struct igb_adapter *adapter = q_vector->adapter;
796         struct e1000_hw *hw = &adapter->hw;
797         int rx_queue = IGB_N0_QUEUE;
798         int tx_queue = IGB_N0_QUEUE;
799         u32 msixbm = 0;
800
801         if (q_vector->rx.ring)
802                 rx_queue = q_vector->rx.ring->reg_idx;
803         if (q_vector->tx.ring)
804                 tx_queue = q_vector->tx.ring->reg_idx;
805
806         switch (hw->mac.type) {
807         case e1000_82575:
808                 /* The 82575 assigns vectors using a bitmask, which matches the
809                  * bitmask for the EICR/EIMS/EIMC registers.  To assign one
810                  * or more queues to a vector, we write the appropriate bits
811                  * into the MSIXBM register for that vector.
812                  */
813                 if (rx_queue > IGB_N0_QUEUE)
814                         msixbm = E1000_EICR_RX_QUEUE0 << rx_queue;
815                 if (tx_queue > IGB_N0_QUEUE)
816                         msixbm |= E1000_EICR_TX_QUEUE0 << tx_queue;
817                 if (!(adapter->flags & IGB_FLAG_HAS_MSIX) && msix_vector == 0)
818                         msixbm |= E1000_EIMS_OTHER;
819                 array_wr32(E1000_MSIXBM(0), msix_vector, msixbm);
820                 q_vector->eims_value = msixbm;
821                 break;
822         case e1000_82576:
823                 /* 82576 uses a table that essentially consists of 2 columns
824                  * with 8 rows.  The ordering is column-major so we use the
825                  * lower 3 bits as the row index, and the 4th bit as the
826                  * column offset.
827                  */
828                 if (rx_queue > IGB_N0_QUEUE)
829                         igb_write_ivar(hw, msix_vector,
830                                        rx_queue & 0x7,
831                                        (rx_queue & 0x8) << 1);
832                 if (tx_queue > IGB_N0_QUEUE)
833                         igb_write_ivar(hw, msix_vector,
834                                        tx_queue & 0x7,
835                                        ((tx_queue & 0x8) << 1) + 8);
836                 q_vector->eims_value = BIT(msix_vector);
837                 break;
838         case e1000_82580:
839         case e1000_i350:
840         case e1000_i354:
841         case e1000_i210:
842         case e1000_i211:
843                 /* On 82580 and newer adapters the scheme is similar to 82576
844                  * however instead of ordering column-major we have things
845                  * ordered row-major.  So we traverse the table by using
846                  * bit 0 as the column offset, and the remaining bits as the
847                  * row index.
848                  */
849                 if (rx_queue > IGB_N0_QUEUE)
850                         igb_write_ivar(hw, msix_vector,
851                                        rx_queue >> 1,
852                                        (rx_queue & 0x1) << 4);
853                 if (tx_queue > IGB_N0_QUEUE)
854                         igb_write_ivar(hw, msix_vector,
855                                        tx_queue >> 1,
856                                        ((tx_queue & 0x1) << 4) + 8);
857                 q_vector->eims_value = BIT(msix_vector);
858                 break;
859         default:
860                 BUG();
861                 break;
862         }
863
864         /* add q_vector eims value to global eims_enable_mask */
865         adapter->eims_enable_mask |= q_vector->eims_value;
866
867         /* configure q_vector to set itr on first interrupt */
868         q_vector->set_itr = 1;
869 }
870
871 /**
872  *  igb_configure_msix - Configure MSI-X hardware
873  *  @adapter: board private structure to initialize
874  *
875  *  igb_configure_msix sets up the hardware to properly
876  *  generate MSI-X interrupts.
877  **/
878 static void igb_configure_msix(struct igb_adapter *adapter)
879 {
880         u32 tmp;
881         int i, vector = 0;
882         struct e1000_hw *hw = &adapter->hw;
883
884         adapter->eims_enable_mask = 0;
885
886         /* set vector for other causes, i.e. link changes */
887         switch (hw->mac.type) {
888         case e1000_82575:
889                 tmp = rd32(E1000_CTRL_EXT);
890                 /* enable MSI-X PBA support*/
891                 tmp |= E1000_CTRL_EXT_PBA_CLR;
892
893                 /* Auto-Mask interrupts upon ICR read. */
894                 tmp |= E1000_CTRL_EXT_EIAME;
895                 tmp |= E1000_CTRL_EXT_IRCA;
896
897                 wr32(E1000_CTRL_EXT, tmp);
898
899                 /* enable msix_other interrupt */
900                 array_wr32(E1000_MSIXBM(0), vector++, E1000_EIMS_OTHER);
901                 adapter->eims_other = E1000_EIMS_OTHER;
902
903                 break;
904
905         case e1000_82576:
906         case e1000_82580:
907         case e1000_i350:
908         case e1000_i354:
909         case e1000_i210:
910         case e1000_i211:
911                 /* Turn on MSI-X capability first, or our settings
912                  * won't stick.  And it will take days to debug.
913                  */
914                 wr32(E1000_GPIE, E1000_GPIE_MSIX_MODE |
915                      E1000_GPIE_PBA | E1000_GPIE_EIAME |
916                      E1000_GPIE_NSICR);
917
918                 /* enable msix_other interrupt */
919                 adapter->eims_other = BIT(vector);
920                 tmp = (vector++ | E1000_IVAR_VALID) << 8;
921
922                 wr32(E1000_IVAR_MISC, tmp);
923                 break;
924         default:
925                 /* do nothing, since nothing else supports MSI-X */
926                 break;
927         } /* switch (hw->mac.type) */
928
929         adapter->eims_enable_mask |= adapter->eims_other;
930
931         for (i = 0; i < adapter->num_q_vectors; i++)
932                 igb_assign_vector(adapter->q_vector[i], vector++);
933
934         wrfl();
935 }
936
937 /**
938  *  igb_request_msix - Initialize MSI-X interrupts
939  *  @adapter: board private structure to initialize
940  *
941  *  igb_request_msix allocates MSI-X vectors and requests interrupts from the
942  *  kernel.
943  **/
944 static int igb_request_msix(struct igb_adapter *adapter)
945 {
946         struct net_device *netdev = adapter->netdev;
947         int i, err = 0, vector = 0, free_vector = 0;
948
949         err = request_irq(adapter->msix_entries[vector].vector,
950                           igb_msix_other, 0, netdev->name, adapter);
951         if (err)
952                 goto err_out;
953
954         for (i = 0; i < adapter->num_q_vectors; i++) {
955                 struct igb_q_vector *q_vector = adapter->q_vector[i];
956
957                 vector++;
958
959                 q_vector->itr_register = adapter->io_addr + E1000_EITR(vector);
960
961                 if (q_vector->rx.ring && q_vector->tx.ring)
962                         sprintf(q_vector->name, "%s-TxRx-%u", netdev->name,
963                                 q_vector->rx.ring->queue_index);
964                 else if (q_vector->tx.ring)
965                         sprintf(q_vector->name, "%s-tx-%u", netdev->name,
966                                 q_vector->tx.ring->queue_index);
967                 else if (q_vector->rx.ring)
968                         sprintf(q_vector->name, "%s-rx-%u", netdev->name,
969                                 q_vector->rx.ring->queue_index);
970                 else
971                         sprintf(q_vector->name, "%s-unused", netdev->name);
972
973                 err = request_irq(adapter->msix_entries[vector].vector,
974                                   igb_msix_ring, 0, q_vector->name,
975                                   q_vector);
976                 if (err)
977                         goto err_free;
978         }
979
980         igb_configure_msix(adapter);
981         return 0;
982
983 err_free:
984         /* free already assigned IRQs */
985         free_irq(adapter->msix_entries[free_vector++].vector, adapter);
986
987         vector--;
988         for (i = 0; i < vector; i++) {
989                 free_irq(adapter->msix_entries[free_vector++].vector,
990                          adapter->q_vector[i]);
991         }
992 err_out:
993         return err;
994 }
995
996 /**
997  *  igb_free_q_vector - Free memory allocated for specific interrupt vector
998  *  @adapter: board private structure to initialize
999  *  @v_idx: Index of vector to be freed
1000  *
1001  *  This function frees the memory allocated to the q_vector.
1002  **/
1003 static void igb_free_q_vector(struct igb_adapter *adapter, int v_idx)
1004 {
1005         struct igb_q_vector *q_vector = adapter->q_vector[v_idx];
1006
1007         adapter->q_vector[v_idx] = NULL;
1008
1009         /* igb_get_stats64() might access the rings on this vector,
1010          * we must wait a grace period before freeing it.
1011          */
1012         if (q_vector)
1013                 kfree_rcu(q_vector, rcu);
1014 }
1015
1016 /**
1017  *  igb_reset_q_vector - Reset config for interrupt vector
1018  *  @adapter: board private structure to initialize
1019  *  @v_idx: Index of vector to be reset
1020  *
1021  *  If NAPI is enabled it will delete any references to the
1022  *  NAPI struct. This is preparation for igb_free_q_vector.
1023  **/
1024 static void igb_reset_q_vector(struct igb_adapter *adapter, int v_idx)
1025 {
1026         struct igb_q_vector *q_vector = adapter->q_vector[v_idx];
1027
1028         /* Coming from igb_set_interrupt_capability, the vectors are not yet
1029          * allocated. So, q_vector is NULL so we should stop here.
1030          */
1031         if (!q_vector)
1032                 return;
1033
1034         if (q_vector->tx.ring)
1035                 adapter->tx_ring[q_vector->tx.ring->queue_index] = NULL;
1036
1037         if (q_vector->rx.ring)
1038                 adapter->rx_ring[q_vector->rx.ring->queue_index] = NULL;
1039
1040         netif_napi_del(&q_vector->napi);
1041
1042 }
1043
1044 static void igb_reset_interrupt_capability(struct igb_adapter *adapter)
1045 {
1046         int v_idx = adapter->num_q_vectors;
1047
1048         if (adapter->flags & IGB_FLAG_HAS_MSIX)
1049                 pci_disable_msix(adapter->pdev);
1050         else if (adapter->flags & IGB_FLAG_HAS_MSI)
1051                 pci_disable_msi(adapter->pdev);
1052
1053         while (v_idx--)
1054                 igb_reset_q_vector(adapter, v_idx);
1055 }
1056
1057 /**
1058  *  igb_free_q_vectors - Free memory allocated for interrupt vectors
1059  *  @adapter: board private structure to initialize
1060  *
1061  *  This function frees the memory allocated to the q_vectors.  In addition if
1062  *  NAPI is enabled it will delete any references to the NAPI struct prior
1063  *  to freeing the q_vector.
1064  **/
1065 static void igb_free_q_vectors(struct igb_adapter *adapter)
1066 {
1067         int v_idx = adapter->num_q_vectors;
1068
1069         adapter->num_tx_queues = 0;
1070         adapter->num_rx_queues = 0;
1071         adapter->num_q_vectors = 0;
1072
1073         while (v_idx--) {
1074                 igb_reset_q_vector(adapter, v_idx);
1075                 igb_free_q_vector(adapter, v_idx);
1076         }
1077 }
1078
1079 /**
1080  *  igb_clear_interrupt_scheme - reset the device to a state of no interrupts
1081  *  @adapter: board private structure to initialize
1082  *
1083  *  This function resets the device so that it has 0 Rx queues, Tx queues, and
1084  *  MSI-X interrupts allocated.
1085  */
1086 static void igb_clear_interrupt_scheme(struct igb_adapter *adapter)
1087 {
1088         igb_free_q_vectors(adapter);
1089         igb_reset_interrupt_capability(adapter);
1090 }
1091
1092 /**
1093  *  igb_set_interrupt_capability - set MSI or MSI-X if supported
1094  *  @adapter: board private structure to initialize
1095  *  @msix: boolean value of MSIX capability
1096  *
1097  *  Attempt to configure interrupts using the best available
1098  *  capabilities of the hardware and kernel.
1099  **/
1100 static void igb_set_interrupt_capability(struct igb_adapter *adapter, bool msix)
1101 {
1102         int err;
1103         int numvecs, i;
1104
1105         if (!msix)
1106                 goto msi_only;
1107         adapter->flags |= IGB_FLAG_HAS_MSIX;
1108
1109         /* Number of supported queues. */
1110         adapter->num_rx_queues = adapter->rss_queues;
1111         if (adapter->vfs_allocated_count)
1112                 adapter->num_tx_queues = 1;
1113         else
1114                 adapter->num_tx_queues = adapter->rss_queues;
1115
1116         /* start with one vector for every Rx queue */
1117         numvecs = adapter->num_rx_queues;
1118
1119         /* if Tx handler is separate add 1 for every Tx queue */
1120         if (!(adapter->flags & IGB_FLAG_QUEUE_PAIRS))
1121                 numvecs += adapter->num_tx_queues;
1122
1123         /* store the number of vectors reserved for queues */
1124         adapter->num_q_vectors = numvecs;
1125
1126         /* add 1 vector for link status interrupts */
1127         numvecs++;
1128         for (i = 0; i < numvecs; i++)
1129                 adapter->msix_entries[i].entry = i;
1130
1131         err = pci_enable_msix_range(adapter->pdev,
1132                                     adapter->msix_entries,
1133                                     numvecs,
1134                                     numvecs);
1135         if (err > 0)
1136                 return;
1137
1138         igb_reset_interrupt_capability(adapter);
1139
1140         /* If we can't do MSI-X, try MSI */
1141 msi_only:
1142         adapter->flags &= ~IGB_FLAG_HAS_MSIX;
1143 #ifdef CONFIG_PCI_IOV
1144         /* disable SR-IOV for non MSI-X configurations */
1145         if (adapter->vf_data) {
1146                 struct e1000_hw *hw = &adapter->hw;
1147                 /* disable iov and allow time for transactions to clear */
1148                 pci_disable_sriov(adapter->pdev);
1149                 msleep(500);
1150
1151                 kfree(adapter->vf_mac_list);
1152                 adapter->vf_mac_list = NULL;
1153                 kfree(adapter->vf_data);
1154                 adapter->vf_data = NULL;
1155                 wr32(E1000_IOVCTL, E1000_IOVCTL_REUSE_VFQ);
1156                 wrfl();
1157                 msleep(100);
1158                 dev_info(&adapter->pdev->dev, "IOV Disabled\n");
1159         }
1160 #endif
1161         adapter->vfs_allocated_count = 0;
1162         adapter->rss_queues = 1;
1163         adapter->flags |= IGB_FLAG_QUEUE_PAIRS;
1164         adapter->num_rx_queues = 1;
1165         adapter->num_tx_queues = 1;
1166         adapter->num_q_vectors = 1;
1167         if (!pci_enable_msi(adapter->pdev))
1168                 adapter->flags |= IGB_FLAG_HAS_MSI;
1169 }
1170
1171 static void igb_add_ring(struct igb_ring *ring,
1172                          struct igb_ring_container *head)
1173 {
1174         head->ring = ring;
1175         head->count++;
1176 }
1177
1178 /**
1179  *  igb_alloc_q_vector - Allocate memory for a single interrupt vector
1180  *  @adapter: board private structure to initialize
1181  *  @v_count: q_vectors allocated on adapter, used for ring interleaving
1182  *  @v_idx: index of vector in adapter struct
1183  *  @txr_count: total number of Tx rings to allocate
1184  *  @txr_idx: index of first Tx ring to allocate
1185  *  @rxr_count: total number of Rx rings to allocate
1186  *  @rxr_idx: index of first Rx ring to allocate
1187  *
1188  *  We allocate one q_vector.  If allocation fails we return -ENOMEM.
1189  **/
1190 static int igb_alloc_q_vector(struct igb_adapter *adapter,
1191                               int v_count, int v_idx,
1192                               int txr_count, int txr_idx,
1193                               int rxr_count, int rxr_idx)
1194 {
1195         struct igb_q_vector *q_vector;
1196         struct igb_ring *ring;
1197         int ring_count, size;
1198
1199         /* igb only supports 1 Tx and/or 1 Rx queue per vector */
1200         if (txr_count > 1 || rxr_count > 1)
1201                 return -ENOMEM;
1202
1203         ring_count = txr_count + rxr_count;
1204         size = sizeof(struct igb_q_vector) +
1205                (sizeof(struct igb_ring) * ring_count);
1206
1207         /* allocate q_vector and rings */
1208         q_vector = adapter->q_vector[v_idx];
1209         if (!q_vector) {
1210                 q_vector = kzalloc(size, GFP_KERNEL);
1211         } else if (size > ksize(q_vector)) {
1212                 kfree_rcu(q_vector, rcu);
1213                 q_vector = kzalloc(size, GFP_KERNEL);
1214         } else {
1215                 memset(q_vector, 0, size);
1216         }
1217         if (!q_vector)
1218                 return -ENOMEM;
1219
1220         /* initialize NAPI */
1221         netif_napi_add(adapter->netdev, &q_vector->napi,
1222                        igb_poll, 64);
1223
1224         /* tie q_vector and adapter together */
1225         adapter->q_vector[v_idx] = q_vector;
1226         q_vector->adapter = adapter;
1227
1228         /* initialize work limits */
1229         q_vector->tx.work_limit = adapter->tx_work_limit;
1230
1231         /* initialize ITR configuration */
1232         q_vector->itr_register = adapter->io_addr + E1000_EITR(0);
1233         q_vector->itr_val = IGB_START_ITR;
1234
1235         /* initialize pointer to rings */
1236         ring = q_vector->ring;
1237
1238         /* intialize ITR */
1239         if (rxr_count) {
1240                 /* rx or rx/tx vector */
1241                 if (!adapter->rx_itr_setting || adapter->rx_itr_setting > 3)
1242                         q_vector->itr_val = adapter->rx_itr_setting;
1243         } else {
1244                 /* tx only vector */
1245                 if (!adapter->tx_itr_setting || adapter->tx_itr_setting > 3)
1246                         q_vector->itr_val = adapter->tx_itr_setting;
1247         }
1248
1249         if (txr_count) {
1250                 /* assign generic ring traits */
1251                 ring->dev = &adapter->pdev->dev;
1252                 ring->netdev = adapter->netdev;
1253
1254                 /* configure backlink on ring */
1255                 ring->q_vector = q_vector;
1256
1257                 /* update q_vector Tx values */
1258                 igb_add_ring(ring, &q_vector->tx);
1259
1260                 /* For 82575, context index must be unique per ring. */
1261                 if (adapter->hw.mac.type == e1000_82575)
1262                         set_bit(IGB_RING_FLAG_TX_CTX_IDX, &ring->flags);
1263
1264                 /* apply Tx specific ring traits */
1265                 ring->count = adapter->tx_ring_count;
1266                 ring->queue_index = txr_idx;
1267
1268                 ring->cbs_enable = false;
1269                 ring->idleslope = 0;
1270                 ring->sendslope = 0;
1271                 ring->hicredit = 0;
1272                 ring->locredit = 0;
1273
1274                 u64_stats_init(&ring->tx_syncp);
1275                 u64_stats_init(&ring->tx_syncp2);
1276
1277                 /* assign ring to adapter */
1278                 adapter->tx_ring[txr_idx] = ring;
1279
1280                 /* push pointer to next ring */
1281                 ring++;
1282         }
1283
1284         if (rxr_count) {
1285                 /* assign generic ring traits */
1286                 ring->dev = &adapter->pdev->dev;
1287                 ring->netdev = adapter->netdev;
1288
1289                 /* configure backlink on ring */
1290                 ring->q_vector = q_vector;
1291
1292                 /* update q_vector Rx values */
1293                 igb_add_ring(ring, &q_vector->rx);
1294
1295                 /* set flag indicating ring supports SCTP checksum offload */
1296                 if (adapter->hw.mac.type >= e1000_82576)
1297                         set_bit(IGB_RING_FLAG_RX_SCTP_CSUM, &ring->flags);
1298
1299                 /* On i350, i354, i210, and i211, loopback VLAN packets
1300                  * have the tag byte-swapped.
1301                  */
1302                 if (adapter->hw.mac.type >= e1000_i350)
1303                         set_bit(IGB_RING_FLAG_RX_LB_VLAN_BSWAP, &ring->flags);
1304
1305                 /* apply Rx specific ring traits */
1306                 ring->count = adapter->rx_ring_count;
1307                 ring->queue_index = rxr_idx;
1308
1309                 u64_stats_init(&ring->rx_syncp);
1310
1311                 /* assign ring to adapter */
1312                 adapter->rx_ring[rxr_idx] = ring;
1313         }
1314
1315         return 0;
1316 }
1317
1318
1319 /**
1320  *  igb_alloc_q_vectors - Allocate memory for interrupt vectors
1321  *  @adapter: board private structure to initialize
1322  *
1323  *  We allocate one q_vector per queue interrupt.  If allocation fails we
1324  *  return -ENOMEM.
1325  **/
1326 static int igb_alloc_q_vectors(struct igb_adapter *adapter)
1327 {
1328         int q_vectors = adapter->num_q_vectors;
1329         int rxr_remaining = adapter->num_rx_queues;
1330         int txr_remaining = adapter->num_tx_queues;
1331         int rxr_idx = 0, txr_idx = 0, v_idx = 0;
1332         int err;
1333
1334         if (q_vectors >= (rxr_remaining + txr_remaining)) {
1335                 for (; rxr_remaining; v_idx++) {
1336                         err = igb_alloc_q_vector(adapter, q_vectors, v_idx,
1337                                                  0, 0, 1, rxr_idx);
1338
1339                         if (err)
1340                                 goto err_out;
1341
1342                         /* update counts and index */
1343                         rxr_remaining--;
1344                         rxr_idx++;
1345                 }
1346         }
1347
1348         for (; v_idx < q_vectors; v_idx++) {
1349                 int rqpv = DIV_ROUND_UP(rxr_remaining, q_vectors - v_idx);
1350                 int tqpv = DIV_ROUND_UP(txr_remaining, q_vectors - v_idx);
1351
1352                 err = igb_alloc_q_vector(adapter, q_vectors, v_idx,
1353                                          tqpv, txr_idx, rqpv, rxr_idx);
1354
1355                 if (err)
1356                         goto err_out;
1357
1358                 /* update counts and index */
1359                 rxr_remaining -= rqpv;
1360                 txr_remaining -= tqpv;
1361                 rxr_idx++;
1362                 txr_idx++;
1363         }
1364
1365         return 0;
1366
1367 err_out:
1368         adapter->num_tx_queues = 0;
1369         adapter->num_rx_queues = 0;
1370         adapter->num_q_vectors = 0;
1371
1372         while (v_idx--)
1373                 igb_free_q_vector(adapter, v_idx);
1374
1375         return -ENOMEM;
1376 }
1377
1378 /**
1379  *  igb_init_interrupt_scheme - initialize interrupts, allocate queues/vectors
1380  *  @adapter: board private structure to initialize
1381  *  @msix: boolean value of MSIX capability
1382  *
1383  *  This function initializes the interrupts and allocates all of the queues.
1384  **/
1385 static int igb_init_interrupt_scheme(struct igb_adapter *adapter, bool msix)
1386 {
1387         struct pci_dev *pdev = adapter->pdev;
1388         int err;
1389
1390         igb_set_interrupt_capability(adapter, msix);
1391
1392         err = igb_alloc_q_vectors(adapter);
1393         if (err) {
1394                 dev_err(&pdev->dev, "Unable to allocate memory for vectors\n");
1395                 goto err_alloc_q_vectors;
1396         }
1397
1398         igb_cache_ring_register(adapter);
1399
1400         return 0;
1401
1402 err_alloc_q_vectors:
1403         igb_reset_interrupt_capability(adapter);
1404         return err;
1405 }
1406
1407 /**
1408  *  igb_request_irq - initialize interrupts
1409  *  @adapter: board private structure to initialize
1410  *
1411  *  Attempts to configure interrupts using the best available
1412  *  capabilities of the hardware and kernel.
1413  **/
1414 static int igb_request_irq(struct igb_adapter *adapter)
1415 {
1416         struct net_device *netdev = adapter->netdev;
1417         struct pci_dev *pdev = adapter->pdev;
1418         int err = 0;
1419
1420         if (adapter->flags & IGB_FLAG_HAS_MSIX) {
1421                 err = igb_request_msix(adapter);
1422                 if (!err)
1423                         goto request_done;
1424                 /* fall back to MSI */
1425                 igb_free_all_tx_resources(adapter);
1426                 igb_free_all_rx_resources(adapter);
1427
1428                 igb_clear_interrupt_scheme(adapter);
1429                 err = igb_init_interrupt_scheme(adapter, false);
1430                 if (err)
1431                         goto request_done;
1432
1433                 igb_setup_all_tx_resources(adapter);
1434                 igb_setup_all_rx_resources(adapter);
1435                 igb_configure(adapter);
1436         }
1437
1438         igb_assign_vector(adapter->q_vector[0], 0);
1439
1440         if (adapter->flags & IGB_FLAG_HAS_MSI) {
1441                 err = request_irq(pdev->irq, igb_intr_msi, 0,
1442                                   netdev->name, adapter);
1443                 if (!err)
1444                         goto request_done;
1445
1446                 /* fall back to legacy interrupts */
1447                 igb_reset_interrupt_capability(adapter);
1448                 adapter->flags &= ~IGB_FLAG_HAS_MSI;
1449         }
1450
1451         err = request_irq(pdev->irq, igb_intr, IRQF_SHARED,
1452                           netdev->name, adapter);
1453
1454         if (err)
1455                 dev_err(&pdev->dev, "Error %d getting interrupt\n",
1456                         err);
1457
1458 request_done:
1459         return err;
1460 }
1461
1462 static void igb_free_irq(struct igb_adapter *adapter)
1463 {
1464         if (adapter->flags & IGB_FLAG_HAS_MSIX) {
1465                 int vector = 0, i;
1466
1467                 free_irq(adapter->msix_entries[vector++].vector, adapter);
1468
1469                 for (i = 0; i < adapter->num_q_vectors; i++)
1470                         free_irq(adapter->msix_entries[vector++].vector,
1471                                  adapter->q_vector[i]);
1472         } else {
1473                 free_irq(adapter->pdev->irq, adapter);
1474         }
1475 }
1476
1477 /**
1478  *  igb_irq_disable - Mask off interrupt generation on the NIC
1479  *  @adapter: board private structure
1480  **/
1481 static void igb_irq_disable(struct igb_adapter *adapter)
1482 {
1483         struct e1000_hw *hw = &adapter->hw;
1484
1485         /* we need to be careful when disabling interrupts.  The VFs are also
1486          * mapped into these registers and so clearing the bits can cause
1487          * issues on the VF drivers so we only need to clear what we set
1488          */
1489         if (adapter->flags & IGB_FLAG_HAS_MSIX) {
1490                 u32 regval = rd32(E1000_EIAM);
1491
1492                 wr32(E1000_EIAM, regval & ~adapter->eims_enable_mask);
1493                 wr32(E1000_EIMC, adapter->eims_enable_mask);
1494                 regval = rd32(E1000_EIAC);
1495                 wr32(E1000_EIAC, regval & ~adapter->eims_enable_mask);
1496         }
1497
1498         wr32(E1000_IAM, 0);
1499         wr32(E1000_IMC, ~0);
1500         wrfl();
1501         if (adapter->flags & IGB_FLAG_HAS_MSIX) {
1502                 int i;
1503
1504                 for (i = 0; i < adapter->num_q_vectors; i++)
1505                         synchronize_irq(adapter->msix_entries[i].vector);
1506         } else {
1507                 synchronize_irq(adapter->pdev->irq);
1508         }
1509 }
1510
1511 /**
1512  *  igb_irq_enable - Enable default interrupt generation settings
1513  *  @adapter: board private structure
1514  **/
1515 static void igb_irq_enable(struct igb_adapter *adapter)
1516 {
1517         struct e1000_hw *hw = &adapter->hw;
1518
1519         if (adapter->flags & IGB_FLAG_HAS_MSIX) {
1520                 u32 ims = E1000_IMS_LSC | E1000_IMS_DOUTSYNC | E1000_IMS_DRSTA;
1521                 u32 regval = rd32(E1000_EIAC);
1522
1523                 wr32(E1000_EIAC, regval | adapter->eims_enable_mask);
1524                 regval = rd32(E1000_EIAM);
1525                 wr32(E1000_EIAM, regval | adapter->eims_enable_mask);
1526                 wr32(E1000_EIMS, adapter->eims_enable_mask);
1527                 if (adapter->vfs_allocated_count) {
1528                         wr32(E1000_MBVFIMR, 0xFF);
1529                         ims |= E1000_IMS_VMMB;
1530                 }
1531                 wr32(E1000_IMS, ims);
1532         } else {
1533                 wr32(E1000_IMS, IMS_ENABLE_MASK |
1534                                 E1000_IMS_DRSTA);
1535                 wr32(E1000_IAM, IMS_ENABLE_MASK |
1536                                 E1000_IMS_DRSTA);
1537         }
1538 }
1539
1540 static void igb_update_mng_vlan(struct igb_adapter *adapter)
1541 {
1542         struct e1000_hw *hw = &adapter->hw;
1543         u16 pf_id = adapter->vfs_allocated_count;
1544         u16 vid = adapter->hw.mng_cookie.vlan_id;
1545         u16 old_vid = adapter->mng_vlan_id;
1546
1547         if (hw->mng_cookie.status & E1000_MNG_DHCP_COOKIE_STATUS_VLAN) {
1548                 /* add VID to filter table */
1549                 igb_vfta_set(hw, vid, pf_id, true, true);
1550                 adapter->mng_vlan_id = vid;
1551         } else {
1552                 adapter->mng_vlan_id = IGB_MNG_VLAN_NONE;
1553         }
1554
1555         if ((old_vid != (u16)IGB_MNG_VLAN_NONE) &&
1556             (vid != old_vid) &&
1557             !test_bit(old_vid, adapter->active_vlans)) {
1558                 /* remove VID from filter table */
1559                 igb_vfta_set(hw, vid, pf_id, false, true);
1560         }
1561 }
1562
1563 /**
1564  *  igb_release_hw_control - release control of the h/w to f/w
1565  *  @adapter: address of board private structure
1566  *
1567  *  igb_release_hw_control resets CTRL_EXT:DRV_LOAD bit.
1568  *  For ASF and Pass Through versions of f/w this means that the
1569  *  driver is no longer loaded.
1570  **/
1571 static void igb_release_hw_control(struct igb_adapter *adapter)
1572 {
1573         struct e1000_hw *hw = &adapter->hw;
1574         u32 ctrl_ext;
1575
1576         /* Let firmware take over control of h/w */
1577         ctrl_ext = rd32(E1000_CTRL_EXT);
1578         wr32(E1000_CTRL_EXT,
1579                         ctrl_ext & ~E1000_CTRL_EXT_DRV_LOAD);
1580 }
1581
1582 /**
1583  *  igb_get_hw_control - get control of the h/w from f/w
1584  *  @adapter: address of board private structure
1585  *
1586  *  igb_get_hw_control sets CTRL_EXT:DRV_LOAD bit.
1587  *  For ASF and Pass Through versions of f/w this means that
1588  *  the driver is loaded.
1589  **/
1590 static void igb_get_hw_control(struct igb_adapter *adapter)
1591 {
1592         struct e1000_hw *hw = &adapter->hw;
1593         u32 ctrl_ext;
1594
1595         /* Let firmware know the driver has taken over */
1596         ctrl_ext = rd32(E1000_CTRL_EXT);
1597         wr32(E1000_CTRL_EXT,
1598                         ctrl_ext | E1000_CTRL_EXT_DRV_LOAD);
1599 }
1600
1601 static void enable_fqtss(struct igb_adapter *adapter, bool enable)
1602 {
1603         struct net_device *netdev = adapter->netdev;
1604         struct e1000_hw *hw = &adapter->hw;
1605
1606         WARN_ON(hw->mac.type != e1000_i210);
1607
1608         if (enable)
1609                 adapter->flags |= IGB_FLAG_FQTSS;
1610         else
1611                 adapter->flags &= ~IGB_FLAG_FQTSS;
1612
1613         if (netif_running(netdev))
1614                 schedule_work(&adapter->reset_task);
1615 }
1616
1617 static bool is_fqtss_enabled(struct igb_adapter *adapter)
1618 {
1619         return (adapter->flags & IGB_FLAG_FQTSS) ? true : false;
1620 }
1621
1622 static void set_tx_desc_fetch_prio(struct e1000_hw *hw, int queue,
1623                                    enum tx_queue_prio prio)
1624 {
1625         u32 val;
1626
1627         WARN_ON(hw->mac.type != e1000_i210);
1628         WARN_ON(queue < 0 || queue > 4);
1629
1630         val = rd32(E1000_I210_TXDCTL(queue));
1631
1632         if (prio == TX_QUEUE_PRIO_HIGH)
1633                 val |= E1000_TXDCTL_PRIORITY;
1634         else
1635                 val &= ~E1000_TXDCTL_PRIORITY;
1636
1637         wr32(E1000_I210_TXDCTL(queue), val);
1638 }
1639
1640 static void set_queue_mode(struct e1000_hw *hw, int queue, enum queue_mode mode)
1641 {
1642         u32 val;
1643
1644         WARN_ON(hw->mac.type != e1000_i210);
1645         WARN_ON(queue < 0 || queue > 1);
1646
1647         val = rd32(E1000_I210_TQAVCC(queue));
1648
1649         if (mode == QUEUE_MODE_STREAM_RESERVATION)
1650                 val |= E1000_TQAVCC_QUEUEMODE;
1651         else
1652                 val &= ~E1000_TQAVCC_QUEUEMODE;
1653
1654         wr32(E1000_I210_TQAVCC(queue), val);
1655 }
1656
1657 /**
1658  *  igb_configure_cbs - Configure Credit-Based Shaper (CBS)
1659  *  @adapter: pointer to adapter struct
1660  *  @queue: queue number
1661  *  @enable: true = enable CBS, false = disable CBS
1662  *  @idleslope: idleSlope in kbps
1663  *  @sendslope: sendSlope in kbps
1664  *  @hicredit: hiCredit in bytes
1665  *  @locredit: loCredit in bytes
1666  *
1667  *  Configure CBS for a given hardware queue. When disabling, idleslope,
1668  *  sendslope, hicredit, locredit arguments are ignored. Returns 0 if
1669  *  success. Negative otherwise.
1670  **/
1671 static void igb_configure_cbs(struct igb_adapter *adapter, int queue,
1672                               bool enable, int idleslope, int sendslope,
1673                               int hicredit, int locredit)
1674 {
1675         struct net_device *netdev = adapter->netdev;
1676         struct e1000_hw *hw = &adapter->hw;
1677         u32 tqavcc;
1678         u16 value;
1679
1680         WARN_ON(hw->mac.type != e1000_i210);
1681         WARN_ON(queue < 0 || queue > 1);
1682
1683         if (enable || queue == 0) {
1684                 /* i210 does not allow the queue 0 to be in the Strict
1685                  * Priority mode while the Qav mode is enabled, so,
1686                  * instead of disabling strict priority mode, we give
1687                  * queue 0 the maximum of credits possible.
1688                  *
1689                  * See section 8.12.19 of the i210 datasheet, "Note:
1690                  * Queue0 QueueMode must be set to 1b when
1691                  * TransmitMode is set to Qav."
1692                  */
1693                 if (queue == 0 && !enable) {
1694                         /* max "linkspeed" idleslope in kbps */
1695                         idleslope = 1000000;
1696                         hicredit = ETH_FRAME_LEN;
1697                 }
1698
1699                 set_tx_desc_fetch_prio(hw, queue, TX_QUEUE_PRIO_HIGH);
1700                 set_queue_mode(hw, queue, QUEUE_MODE_STREAM_RESERVATION);
1701
1702                 /* According to i210 datasheet section 7.2.7.7, we should set
1703                  * the 'idleSlope' field from TQAVCC register following the
1704                  * equation:
1705                  *
1706                  * For 100 Mbps link speed:
1707                  *
1708                  *     value = BW * 0x7735 * 0.2                          (E1)
1709                  *
1710                  * For 1000Mbps link speed:
1711                  *
1712                  *     value = BW * 0x7735 * 2                            (E2)
1713                  *
1714                  * E1 and E2 can be merged into one equation as shown below.
1715                  * Note that 'link-speed' is in Mbps.
1716                  *
1717                  *     value = BW * 0x7735 * 2 * link-speed
1718                  *                           --------------               (E3)
1719                  *                                1000
1720                  *
1721                  * 'BW' is the percentage bandwidth out of full link speed
1722                  * which can be found with the following equation. Note that
1723                  * idleSlope here is the parameter from this function which
1724                  * is in kbps.
1725                  *
1726                  *     BW =     idleSlope
1727                  *          -----------------                             (E4)
1728                  *          link-speed * 1000
1729                  *
1730                  * That said, we can come up with a generic equation to
1731                  * calculate the value we should set it TQAVCC register by
1732                  * replacing 'BW' in E3 by E4. The resulting equation is:
1733                  *
1734                  * value =     idleSlope     * 0x7735 * 2 * link-speed
1735                  *         -----------------            --------------    (E5)
1736                  *         link-speed * 1000                 1000
1737                  *
1738                  * 'link-speed' is present in both sides of the fraction so
1739                  * it is canceled out. The final equation is the following:
1740                  *
1741                  *     value = idleSlope * 61034
1742                  *             -----------------                          (E6)
1743                  *                  1000000
1744                  *
1745                  * NOTE: For i210, given the above, we can see that idleslope
1746                  *       is represented in 16.38431 kbps units by the value at
1747                  *       the TQAVCC register (1Gbps / 61034), which reduces
1748                  *       the granularity for idleslope increments.
1749                  *       For instance, if you want to configure a 2576kbps
1750                  *       idleslope, the value to be written on the register
1751                  *       would have to be 157.23. If rounded down, you end
1752                  *       up with less bandwidth available than originally
1753                  *       required (~2572 kbps). If rounded up, you end up
1754                  *       with a higher bandwidth (~2589 kbps). Below the
1755                  *       approach we take is to always round up the
1756                  *       calculated value, so the resulting bandwidth might
1757                  *       be slightly higher for some configurations.
1758                  */
1759                 value = DIV_ROUND_UP_ULL(idleslope * 61034ULL, 1000000);
1760
1761                 tqavcc = rd32(E1000_I210_TQAVCC(queue));
1762                 tqavcc &= ~E1000_TQAVCC_IDLESLOPE_MASK;
1763                 tqavcc |= value;
1764                 wr32(E1000_I210_TQAVCC(queue), tqavcc);
1765
1766                 wr32(E1000_I210_TQAVHC(queue), 0x80000000 + hicredit * 0x7735);
1767         } else {
1768                 set_tx_desc_fetch_prio(hw, queue, TX_QUEUE_PRIO_LOW);
1769                 set_queue_mode(hw, queue, QUEUE_MODE_STRICT_PRIORITY);
1770
1771                 /* Set idleSlope to zero. */
1772                 tqavcc = rd32(E1000_I210_TQAVCC(queue));
1773                 tqavcc &= ~E1000_TQAVCC_IDLESLOPE_MASK;
1774                 wr32(E1000_I210_TQAVCC(queue), tqavcc);
1775
1776                 /* Set hiCredit to zero. */
1777                 wr32(E1000_I210_TQAVHC(queue), 0);
1778         }
1779
1780         /* XXX: In i210 controller the sendSlope and loCredit parameters from
1781          * CBS are not configurable by software so we don't do any 'controller
1782          * configuration' in respect to these parameters.
1783          */
1784
1785         netdev_dbg(netdev, "CBS %s: queue %d idleslope %d sendslope %d hiCredit %d locredit %d\n",
1786                    (enable) ? "enabled" : "disabled", queue,
1787                    idleslope, sendslope, hicredit, locredit);
1788 }
1789
1790 static int igb_save_cbs_params(struct igb_adapter *adapter, int queue,
1791                                bool enable, int idleslope, int sendslope,
1792                                int hicredit, int locredit)
1793 {
1794         struct igb_ring *ring;
1795
1796         if (queue < 0 || queue > adapter->num_tx_queues)
1797                 return -EINVAL;
1798
1799         ring = adapter->tx_ring[queue];
1800
1801         ring->cbs_enable = enable;
1802         ring->idleslope = idleslope;
1803         ring->sendslope = sendslope;
1804         ring->hicredit = hicredit;
1805         ring->locredit = locredit;
1806
1807         return 0;
1808 }
1809
1810 static bool is_any_cbs_enabled(struct igb_adapter *adapter)
1811 {
1812         struct igb_ring *ring;
1813         int i;
1814
1815         for (i = 0; i < adapter->num_tx_queues; i++) {
1816                 ring = adapter->tx_ring[i];
1817
1818                 if (ring->cbs_enable)
1819                         return true;
1820         }
1821
1822         return false;
1823 }
1824
1825 static void igb_setup_tx_mode(struct igb_adapter *adapter)
1826 {
1827         struct net_device *netdev = adapter->netdev;
1828         struct e1000_hw *hw = &adapter->hw;
1829         u32 val;
1830
1831         /* Only i210 controller supports changing the transmission mode. */
1832         if (hw->mac.type != e1000_i210)
1833                 return;
1834
1835         if (is_fqtss_enabled(adapter)) {
1836                 int i, max_queue;
1837
1838                 /* Configure TQAVCTRL register: set transmit mode to 'Qav',
1839                  * set data fetch arbitration to 'round robin' and set data
1840                  * transfer arbitration to 'credit shaper algorithm.
1841                  */
1842                 val = rd32(E1000_I210_TQAVCTRL);
1843                 val |= E1000_TQAVCTRL_XMIT_MODE | E1000_TQAVCTRL_DATATRANARB;
1844                 val &= ~E1000_TQAVCTRL_DATAFETCHARB;
1845                 wr32(E1000_I210_TQAVCTRL, val);
1846
1847                 /* Configure Tx and Rx packet buffers sizes as described in
1848                  * i210 datasheet section 7.2.7.7.
1849                  */
1850                 val = rd32(E1000_TXPBS);
1851                 val &= ~I210_TXPBSIZE_MASK;
1852                 val |= I210_TXPBSIZE_PB0_8KB | I210_TXPBSIZE_PB1_8KB |
1853                         I210_TXPBSIZE_PB2_4KB | I210_TXPBSIZE_PB3_4KB;
1854                 wr32(E1000_TXPBS, val);
1855
1856                 val = rd32(E1000_RXPBS);
1857                 val &= ~I210_RXPBSIZE_MASK;
1858                 val |= I210_RXPBSIZE_PB_32KB;
1859                 wr32(E1000_RXPBS, val);
1860
1861                 /* Section 8.12.9 states that MAX_TPKT_SIZE from DTXMXPKTSZ
1862                  * register should not exceed the buffer size programmed in
1863                  * TXPBS. The smallest buffer size programmed in TXPBS is 4kB
1864                  * so according to the datasheet we should set MAX_TPKT_SIZE to
1865                  * 4kB / 64.
1866                  *
1867                  * However, when we do so, no frame from queue 2 and 3 are
1868                  * transmitted.  It seems the MAX_TPKT_SIZE should not be great
1869                  * or _equal_ to the buffer size programmed in TXPBS. For this
1870                  * reason, we set set MAX_ TPKT_SIZE to (4kB - 1) / 64.
1871                  */
1872                 val = (4096 - 1) / 64;
1873                 wr32(E1000_I210_DTXMXPKTSZ, val);
1874
1875                 /* Since FQTSS mode is enabled, apply any CBS configuration
1876                  * previously set. If no previous CBS configuration has been
1877                  * done, then the initial configuration is applied, which means
1878                  * CBS is disabled.
1879                  */
1880                 max_queue = (adapter->num_tx_queues < I210_SR_QUEUES_NUM) ?
1881                             adapter->num_tx_queues : I210_SR_QUEUES_NUM;
1882
1883                 for (i = 0; i < max_queue; i++) {
1884                         struct igb_ring *ring = adapter->tx_ring[i];
1885
1886                         igb_configure_cbs(adapter, i, ring->cbs_enable,
1887                                           ring->idleslope, ring->sendslope,
1888                                           ring->hicredit, ring->locredit);
1889                 }
1890         } else {
1891                 wr32(E1000_RXPBS, I210_RXPBSIZE_DEFAULT);
1892                 wr32(E1000_TXPBS, I210_TXPBSIZE_DEFAULT);
1893                 wr32(E1000_I210_DTXMXPKTSZ, I210_DTXMXPKTSZ_DEFAULT);
1894
1895                 val = rd32(E1000_I210_TQAVCTRL);
1896                 /* According to Section 8.12.21, the other flags we've set when
1897                  * enabling FQTSS are not relevant when disabling FQTSS so we
1898                  * don't set they here.
1899                  */
1900                 val &= ~E1000_TQAVCTRL_XMIT_MODE;
1901                 wr32(E1000_I210_TQAVCTRL, val);
1902         }
1903
1904         netdev_dbg(netdev, "FQTSS %s\n", (is_fqtss_enabled(adapter)) ?
1905                    "enabled" : "disabled");
1906 }
1907
1908 /**
1909  *  igb_configure - configure the hardware for RX and TX
1910  *  @adapter: private board structure
1911  **/
1912 static void igb_configure(struct igb_adapter *adapter)
1913 {
1914         struct net_device *netdev = adapter->netdev;
1915         int i;
1916
1917         igb_get_hw_control(adapter);
1918         igb_set_rx_mode(netdev);
1919         igb_setup_tx_mode(adapter);
1920
1921         igb_restore_vlan(adapter);
1922
1923         igb_setup_tctl(adapter);
1924         igb_setup_mrqc(adapter);
1925         igb_setup_rctl(adapter);
1926
1927         igb_nfc_filter_restore(adapter);
1928         igb_configure_tx(adapter);
1929         igb_configure_rx(adapter);
1930
1931         igb_rx_fifo_flush_82575(&adapter->hw);
1932
1933         /* call igb_desc_unused which always leaves
1934          * at least 1 descriptor unused to make sure
1935          * next_to_use != next_to_clean
1936          */
1937         for (i = 0; i < adapter->num_rx_queues; i++) {
1938                 struct igb_ring *ring = adapter->rx_ring[i];
1939                 igb_alloc_rx_buffers(ring, igb_desc_unused(ring));
1940         }
1941 }
1942
1943 /**
1944  *  igb_power_up_link - Power up the phy/serdes link
1945  *  @adapter: address of board private structure
1946  **/
1947 void igb_power_up_link(struct igb_adapter *adapter)
1948 {
1949         igb_reset_phy(&adapter->hw);
1950
1951         if (adapter->hw.phy.media_type == e1000_media_type_copper)
1952                 igb_power_up_phy_copper(&adapter->hw);
1953         else
1954                 igb_power_up_serdes_link_82575(&adapter->hw);
1955
1956         igb_setup_link(&adapter->hw);
1957 }
1958
1959 /**
1960  *  igb_power_down_link - Power down the phy/serdes link
1961  *  @adapter: address of board private structure
1962  */
1963 static void igb_power_down_link(struct igb_adapter *adapter)
1964 {
1965         if (adapter->hw.phy.media_type == e1000_media_type_copper)
1966                 igb_power_down_phy_copper_82575(&adapter->hw);
1967         else
1968                 igb_shutdown_serdes_link_82575(&adapter->hw);
1969 }
1970
1971 /**
1972  * Detect and switch function for Media Auto Sense
1973  * @adapter: address of the board private structure
1974  **/
1975 static void igb_check_swap_media(struct igb_adapter *adapter)
1976 {
1977         struct e1000_hw *hw = &adapter->hw;
1978         u32 ctrl_ext, connsw;
1979         bool swap_now = false;
1980
1981         ctrl_ext = rd32(E1000_CTRL_EXT);
1982         connsw = rd32(E1000_CONNSW);
1983
1984         /* need to live swap if current media is copper and we have fiber/serdes
1985          * to go to.
1986          */
1987
1988         if ((hw->phy.media_type == e1000_media_type_copper) &&
1989             (!(connsw & E1000_CONNSW_AUTOSENSE_EN))) {
1990                 swap_now = true;
1991         } else if (!(connsw & E1000_CONNSW_SERDESD)) {
1992                 /* copper signal takes time to appear */
1993                 if (adapter->copper_tries < 4) {
1994                         adapter->copper_tries++;
1995                         connsw |= E1000_CONNSW_AUTOSENSE_CONF;
1996                         wr32(E1000_CONNSW, connsw);
1997                         return;
1998                 } else {
1999                         adapter->copper_tries = 0;
2000                         if ((connsw & E1000_CONNSW_PHYSD) &&
2001                             (!(connsw & E1000_CONNSW_PHY_PDN))) {
2002                                 swap_now = true;
2003                                 connsw &= ~E1000_CONNSW_AUTOSENSE_CONF;
2004                                 wr32(E1000_CONNSW, connsw);
2005                         }
2006                 }
2007         }
2008
2009         if (!swap_now)
2010                 return;
2011
2012         switch (hw->phy.media_type) {
2013         case e1000_media_type_copper:
2014                 netdev_info(adapter->netdev,
2015                         "MAS: changing media to fiber/serdes\n");
2016                 ctrl_ext |=
2017                         E1000_CTRL_EXT_LINK_MODE_PCIE_SERDES;
2018                 adapter->flags |= IGB_FLAG_MEDIA_RESET;
2019                 adapter->copper_tries = 0;
2020                 break;
2021         case e1000_media_type_internal_serdes:
2022         case e1000_media_type_fiber:
2023                 netdev_info(adapter->netdev,
2024                         "MAS: changing media to copper\n");
2025                 ctrl_ext &=
2026                         ~E1000_CTRL_EXT_LINK_MODE_PCIE_SERDES;
2027                 adapter->flags |= IGB_FLAG_MEDIA_RESET;
2028                 break;
2029         default:
2030                 /* shouldn't get here during regular operation */
2031                 netdev_err(adapter->netdev,
2032                         "AMS: Invalid media type found, returning\n");
2033                 break;
2034         }
2035         wr32(E1000_CTRL_EXT, ctrl_ext);
2036 }
2037
2038 /**
2039  *  igb_up - Open the interface and prepare it to handle traffic
2040  *  @adapter: board private structure
2041  **/
2042 int igb_up(struct igb_adapter *adapter)
2043 {
2044         struct e1000_hw *hw = &adapter->hw;
2045         int i;
2046
2047         /* hardware has been reset, we need to reload some things */
2048         igb_configure(adapter);
2049
2050         clear_bit(__IGB_DOWN, &adapter->state);
2051
2052         for (i = 0; i < adapter->num_q_vectors; i++)
2053                 napi_enable(&(adapter->q_vector[i]->napi));
2054
2055         if (adapter->flags & IGB_FLAG_HAS_MSIX)
2056                 igb_configure_msix(adapter);
2057         else
2058                 igb_assign_vector(adapter->q_vector[0], 0);
2059
2060         /* Clear any pending interrupts. */
2061         rd32(E1000_TSICR);
2062         rd32(E1000_ICR);
2063         igb_irq_enable(adapter);
2064
2065         /* notify VFs that reset has been completed */
2066         if (adapter->vfs_allocated_count) {
2067                 u32 reg_data = rd32(E1000_CTRL_EXT);
2068
2069                 reg_data |= E1000_CTRL_EXT_PFRSTD;
2070                 wr32(E1000_CTRL_EXT, reg_data);
2071         }
2072
2073         netif_tx_start_all_queues(adapter->netdev);
2074
2075         /* start the watchdog. */
2076         hw->mac.get_link_status = 1;
2077         schedule_work(&adapter->watchdog_task);
2078
2079         if ((adapter->flags & IGB_FLAG_EEE) &&
2080             (!hw->dev_spec._82575.eee_disable))
2081                 adapter->eee_advert = MDIO_EEE_100TX | MDIO_EEE_1000T;
2082
2083         return 0;
2084 }
2085
2086 void igb_down(struct igb_adapter *adapter)
2087 {
2088         struct net_device *netdev = adapter->netdev;
2089         struct e1000_hw *hw = &adapter->hw;
2090         u32 tctl, rctl;
2091         int i;
2092
2093         /* signal that we're down so the interrupt handler does not
2094          * reschedule our watchdog timer
2095          */
2096         set_bit(__IGB_DOWN, &adapter->state);
2097
2098         /* disable receives in the hardware */
2099         rctl = rd32(E1000_RCTL);
2100         wr32(E1000_RCTL, rctl & ~E1000_RCTL_EN);
2101         /* flush and sleep below */
2102
2103         igb_nfc_filter_exit(adapter);
2104
2105         netif_carrier_off(netdev);
2106         netif_tx_stop_all_queues(netdev);
2107
2108         /* disable transmits in the hardware */
2109         tctl = rd32(E1000_TCTL);
2110         tctl &= ~E1000_TCTL_EN;
2111         wr32(E1000_TCTL, tctl);
2112         /* flush both disables and wait for them to finish */
2113         wrfl();
2114         usleep_range(10000, 11000);
2115
2116         igb_irq_disable(adapter);
2117
2118         adapter->flags &= ~IGB_FLAG_NEED_LINK_UPDATE;
2119
2120         for (i = 0; i < adapter->num_q_vectors; i++) {
2121                 if (adapter->q_vector[i]) {
2122                         napi_synchronize(&adapter->q_vector[i]->napi);
2123                         napi_disable(&adapter->q_vector[i]->napi);
2124                 }
2125         }
2126
2127         del_timer_sync(&adapter->watchdog_timer);
2128         del_timer_sync(&adapter->phy_info_timer);
2129
2130         /* record the stats before reset*/
2131         spin_lock(&adapter->stats64_lock);
2132         igb_update_stats(adapter);
2133         spin_unlock(&adapter->stats64_lock);
2134
2135         adapter->link_speed = 0;
2136         adapter->link_duplex = 0;
2137
2138         if (!pci_channel_offline(adapter->pdev))
2139                 igb_reset(adapter);
2140
2141         /* clear VLAN promisc flag so VFTA will be updated if necessary */
2142         adapter->flags &= ~IGB_FLAG_VLAN_PROMISC;
2143
2144         igb_clean_all_tx_rings(adapter);
2145         igb_clean_all_rx_rings(adapter);
2146 #ifdef CONFIG_IGB_DCA
2147
2148         /* since we reset the hardware DCA settings were cleared */
2149         igb_setup_dca(adapter);
2150 #endif
2151 }
2152
2153 void igb_reinit_locked(struct igb_adapter *adapter)
2154 {
2155         WARN_ON(in_interrupt());
2156         while (test_and_set_bit(__IGB_RESETTING, &adapter->state))
2157                 usleep_range(1000, 2000);
2158         igb_down(adapter);
2159         igb_up(adapter);
2160         clear_bit(__IGB_RESETTING, &adapter->state);
2161 }
2162
2163 /** igb_enable_mas - Media Autosense re-enable after swap
2164  *
2165  * @adapter: adapter struct
2166  **/
2167 static void igb_enable_mas(struct igb_adapter *adapter)
2168 {
2169         struct e1000_hw *hw = &adapter->hw;
2170         u32 connsw = rd32(E1000_CONNSW);
2171
2172         /* configure for SerDes media detect */
2173         if ((hw->phy.media_type == e1000_media_type_copper) &&
2174             (!(connsw & E1000_CONNSW_SERDESD))) {
2175                 connsw |= E1000_CONNSW_ENRGSRC;
2176                 connsw |= E1000_CONNSW_AUTOSENSE_EN;
2177                 wr32(E1000_CONNSW, connsw);
2178                 wrfl();
2179         }
2180 }
2181
2182 void igb_reset(struct igb_adapter *adapter)
2183 {
2184         struct pci_dev *pdev = adapter->pdev;
2185         struct e1000_hw *hw = &adapter->hw;
2186         struct e1000_mac_info *mac = &hw->mac;
2187         struct e1000_fc_info *fc = &hw->fc;
2188         u32 pba, hwm;
2189
2190         /* Repartition Pba for greater than 9k mtu
2191          * To take effect CTRL.RST is required.
2192          */
2193         switch (mac->type) {
2194         case e1000_i350:
2195         case e1000_i354:
2196         case e1000_82580:
2197                 pba = rd32(E1000_RXPBS);
2198                 pba = igb_rxpbs_adjust_82580(pba);
2199                 break;
2200         case e1000_82576:
2201                 pba = rd32(E1000_RXPBS);
2202                 pba &= E1000_RXPBS_SIZE_MASK_82576;
2203                 break;
2204         case e1000_82575:
2205         case e1000_i210:
2206         case e1000_i211:
2207         default:
2208                 pba = E1000_PBA_34K;
2209                 break;
2210         }
2211
2212         if (mac->type == e1000_82575) {
2213                 u32 min_rx_space, min_tx_space, needed_tx_space;
2214
2215                 /* write Rx PBA so that hardware can report correct Tx PBA */
2216                 wr32(E1000_PBA, pba);
2217
2218                 /* To maintain wire speed transmits, the Tx FIFO should be
2219                  * large enough to accommodate two full transmit packets,
2220                  * rounded up to the next 1KB and expressed in KB.  Likewise,
2221                  * the Rx FIFO should be large enough to accommodate at least
2222                  * one full receive packet and is similarly rounded up and
2223                  * expressed in KB.
2224                  */
2225                 min_rx_space = DIV_ROUND_UP(MAX_JUMBO_FRAME_SIZE, 1024);
2226
2227                 /* The Tx FIFO also stores 16 bytes of information about the Tx
2228                  * but don't include Ethernet FCS because hardware appends it.
2229                  * We only need to round down to the nearest 512 byte block
2230                  * count since the value we care about is 2 frames, not 1.
2231                  */
2232                 min_tx_space = adapter->max_frame_size;
2233                 min_tx_space += sizeof(union e1000_adv_tx_desc) - ETH_FCS_LEN;
2234                 min_tx_space = DIV_ROUND_UP(min_tx_space, 512);
2235
2236                 /* upper 16 bits has Tx packet buffer allocation size in KB */
2237                 needed_tx_space = min_tx_space - (rd32(E1000_PBA) >> 16);
2238
2239                 /* If current Tx allocation is less than the min Tx FIFO size,
2240                  * and the min Tx FIFO size is less than the current Rx FIFO
2241                  * allocation, take space away from current Rx allocation.
2242                  */
2243                 if (needed_tx_space < pba) {
2244                         pba -= needed_tx_space;
2245
2246                         /* if short on Rx space, Rx wins and must trump Tx
2247                          * adjustment
2248                          */
2249                         if (pba < min_rx_space)
2250                                 pba = min_rx_space;
2251                 }
2252
2253                 /* adjust PBA for jumbo frames */
2254                 wr32(E1000_PBA, pba);
2255         }
2256
2257         /* flow control settings
2258          * The high water mark must be low enough to fit one full frame
2259          * after transmitting the pause frame.  As such we must have enough
2260          * space to allow for us to complete our current transmit and then
2261          * receive the frame that is in progress from the link partner.
2262          * Set it to:
2263          * - the full Rx FIFO size minus one full Tx plus one full Rx frame
2264          */
2265         hwm = (pba << 10) - (adapter->max_frame_size + MAX_JUMBO_FRAME_SIZE);
2266
2267         fc->high_water = hwm & 0xFFFFFFF0;      /* 16-byte granularity */
2268         fc->low_water = fc->high_water - 16;
2269         fc->pause_time = 0xFFFF;
2270         fc->send_xon = 1;
2271         fc->current_mode = fc->requested_mode;
2272
2273         /* disable receive for all VFs and wait one second */
2274         if (adapter->vfs_allocated_count) {
2275                 int i;
2276
2277                 for (i = 0 ; i < adapter->vfs_allocated_count; i++)
2278                         adapter->vf_data[i].flags &= IGB_VF_FLAG_PF_SET_MAC;
2279
2280                 /* ping all the active vfs to let them know we are going down */
2281                 igb_ping_all_vfs(adapter);
2282
2283                 /* disable transmits and receives */
2284                 wr32(E1000_VFRE, 0);
2285                 wr32(E1000_VFTE, 0);
2286         }
2287
2288         /* Allow time for pending master requests to run */
2289         hw->mac.ops.reset_hw(hw);
2290         wr32(E1000_WUC, 0);
2291
2292         if (adapter->flags & IGB_FLAG_MEDIA_RESET) {
2293                 /* need to resetup here after media swap */
2294                 adapter->ei.get_invariants(hw);
2295                 adapter->flags &= ~IGB_FLAG_MEDIA_RESET;
2296         }
2297         if ((mac->type == e1000_82575) &&
2298             (adapter->flags & IGB_FLAG_MAS_ENABLE)) {
2299                 igb_enable_mas(adapter);
2300         }
2301         if (hw->mac.ops.init_hw(hw))
2302                 dev_err(&pdev->dev, "Hardware Error\n");
2303
2304         /* RAR registers were cleared during init_hw, clear mac table */
2305         igb_flush_mac_table(adapter);
2306         __dev_uc_unsync(adapter->netdev, NULL);
2307
2308         /* Recover default RAR entry */
2309         igb_set_default_mac_filter(adapter);
2310
2311         /* Flow control settings reset on hardware reset, so guarantee flow
2312          * control is off when forcing speed.
2313          */
2314         if (!hw->mac.autoneg)
2315                 igb_force_mac_fc(hw);
2316
2317         igb_init_dmac(adapter, pba);
2318 #ifdef CONFIG_IGB_HWMON
2319         /* Re-initialize the thermal sensor on i350 devices. */
2320         if (!test_bit(__IGB_DOWN, &adapter->state)) {
2321                 if (mac->type == e1000_i350 && hw->bus.func == 0) {
2322                         /* If present, re-initialize the external thermal sensor
2323                          * interface.
2324                          */
2325                         if (adapter->ets)
2326                                 mac->ops.init_thermal_sensor_thresh(hw);
2327                 }
2328         }
2329 #endif
2330         /* Re-establish EEE setting */
2331         if (hw->phy.media_type == e1000_media_type_copper) {
2332                 switch (mac->type) {
2333                 case e1000_i350:
2334                 case e1000_i210:
2335                 case e1000_i211:
2336                         igb_set_eee_i350(hw, true, true);
2337                         break;
2338                 case e1000_i354:
2339                         igb_set_eee_i354(hw, true, true);
2340                         break;
2341                 default:
2342                         break;
2343                 }
2344         }
2345         if (!netif_running(adapter->netdev))
2346                 igb_power_down_link(adapter);
2347
2348         igb_update_mng_vlan(adapter);
2349
2350         /* Enable h/w to recognize an 802.1Q VLAN Ethernet packet */
2351         wr32(E1000_VET, ETHERNET_IEEE_VLAN_TYPE);
2352
2353         /* Re-enable PTP, where applicable. */
2354         if (adapter->ptp_flags & IGB_PTP_ENABLED)
2355                 igb_ptp_reset(adapter);
2356
2357         igb_get_phy_info(hw);
2358 }
2359
2360 static netdev_features_t igb_fix_features(struct net_device *netdev,
2361         netdev_features_t features)
2362 {
2363         /* Since there is no support for separate Rx/Tx vlan accel
2364          * enable/disable make sure Tx flag is always in same state as Rx.
2365          */
2366         if (features & NETIF_F_HW_VLAN_CTAG_RX)
2367                 features |= NETIF_F_HW_VLAN_CTAG_TX;
2368         else
2369                 features &= ~NETIF_F_HW_VLAN_CTAG_TX;
2370
2371         return features;
2372 }
2373
2374 static int igb_set_features(struct net_device *netdev,
2375         netdev_features_t features)
2376 {
2377         netdev_features_t changed = netdev->features ^ features;
2378         struct igb_adapter *adapter = netdev_priv(netdev);
2379
2380         if (changed & NETIF_F_HW_VLAN_CTAG_RX)
2381                 igb_vlan_mode(netdev, features);
2382
2383         if (!(changed & (NETIF_F_RXALL | NETIF_F_NTUPLE)))
2384                 return 0;
2385
2386         if (!(features & NETIF_F_NTUPLE)) {
2387                 struct hlist_node *node2;
2388                 struct igb_nfc_filter *rule;
2389
2390                 spin_lock(&adapter->nfc_lock);
2391                 hlist_for_each_entry_safe(rule, node2,
2392                                           &adapter->nfc_filter_list, nfc_node) {
2393                         igb_erase_filter(adapter, rule);
2394                         hlist_del(&rule->nfc_node);
2395                         kfree(rule);
2396                 }
2397                 spin_unlock(&adapter->nfc_lock);
2398                 adapter->nfc_filter_count = 0;
2399         }
2400
2401         netdev->features = features;
2402
2403         if (netif_running(netdev))
2404                 igb_reinit_locked(adapter);
2405         else
2406                 igb_reset(adapter);
2407
2408         return 0;
2409 }
2410
2411 static int igb_ndo_fdb_add(struct ndmsg *ndm, struct nlattr *tb[],
2412                            struct net_device *dev,
2413                            const unsigned char *addr, u16 vid,
2414                            u16 flags)
2415 {
2416         /* guarantee we can provide a unique filter for the unicast address */
2417         if (is_unicast_ether_addr(addr) || is_link_local_ether_addr(addr)) {
2418                 struct igb_adapter *adapter = netdev_priv(dev);
2419                 int vfn = adapter->vfs_allocated_count;
2420
2421                 if (netdev_uc_count(dev) >= igb_available_rars(adapter, vfn))
2422                         return -ENOMEM;
2423         }
2424
2425         return ndo_dflt_fdb_add(ndm, tb, dev, addr, vid, flags);
2426 }
2427
2428 #define IGB_MAX_MAC_HDR_LEN     127
2429 #define IGB_MAX_NETWORK_HDR_LEN 511
2430
2431 static netdev_features_t
2432 igb_features_check(struct sk_buff *skb, struct net_device *dev,
2433                    netdev_features_t features)
2434 {
2435         unsigned int network_hdr_len, mac_hdr_len;
2436
2437         /* Make certain the headers can be described by a context descriptor */
2438         mac_hdr_len = skb_network_header(skb) - skb->data;
2439         if (unlikely(mac_hdr_len > IGB_MAX_MAC_HDR_LEN))
2440                 return features & ~(NETIF_F_HW_CSUM |
2441                                     NETIF_F_SCTP_CRC |
2442                                     NETIF_F_HW_VLAN_CTAG_TX |
2443                                     NETIF_F_TSO |
2444                                     NETIF_F_TSO6);
2445
2446         network_hdr_len = skb_checksum_start(skb) - skb_network_header(skb);
2447         if (unlikely(network_hdr_len >  IGB_MAX_NETWORK_HDR_LEN))
2448                 return features & ~(NETIF_F_HW_CSUM |
2449                                     NETIF_F_SCTP_CRC |
2450                                     NETIF_F_TSO |
2451                                     NETIF_F_TSO6);
2452
2453         /* We can only support IPV4 TSO in tunnels if we can mangle the
2454          * inner IP ID field, so strip TSO if MANGLEID is not supported.
2455          */
2456         if (skb->encapsulation && !(features & NETIF_F_TSO_MANGLEID))
2457                 features &= ~NETIF_F_TSO;
2458
2459         return features;
2460 }
2461
2462 static int igb_offload_cbs(struct igb_adapter *adapter,
2463                            struct tc_cbs_qopt_offload *qopt)
2464 {
2465         struct e1000_hw *hw = &adapter->hw;
2466         int err;
2467
2468         /* CBS offloading is only supported by i210 controller. */
2469         if (hw->mac.type != e1000_i210)
2470                 return -EOPNOTSUPP;
2471
2472         /* CBS offloading is only supported by queue 0 and queue 1. */
2473         if (qopt->queue < 0 || qopt->queue > 1)
2474                 return -EINVAL;
2475
2476         err = igb_save_cbs_params(adapter, qopt->queue, qopt->enable,
2477                                   qopt->idleslope, qopt->sendslope,
2478                                   qopt->hicredit, qopt->locredit);
2479         if (err)
2480                 return err;
2481
2482         if (is_fqtss_enabled(adapter)) {
2483                 igb_configure_cbs(adapter, qopt->queue, qopt->enable,
2484                                   qopt->idleslope, qopt->sendslope,
2485                                   qopt->hicredit, qopt->locredit);
2486
2487                 if (!is_any_cbs_enabled(adapter))
2488                         enable_fqtss(adapter, false);
2489
2490         } else {
2491                 enable_fqtss(adapter, true);
2492         }
2493
2494         return 0;
2495 }
2496
2497 #define ETHER_TYPE_FULL_MASK ((__force __be16)~0)
2498 #define VLAN_PRIO_FULL_MASK (0x07)
2499
2500 static int igb_parse_cls_flower(struct igb_adapter *adapter,
2501                                 struct tc_cls_flower_offload *f,
2502                                 int traffic_class,
2503                                 struct igb_nfc_filter *input)
2504 {
2505         struct netlink_ext_ack *extack = f->common.extack;
2506
2507         if (f->dissector->used_keys &
2508             ~(BIT(FLOW_DISSECTOR_KEY_BASIC) |
2509               BIT(FLOW_DISSECTOR_KEY_CONTROL) |
2510               BIT(FLOW_DISSECTOR_KEY_ETH_ADDRS) |
2511               BIT(FLOW_DISSECTOR_KEY_VLAN))) {
2512                 NL_SET_ERR_MSG_MOD(extack,
2513                                    "Unsupported key used, only BASIC, CONTROL, ETH_ADDRS and VLAN are supported");
2514                 return -EOPNOTSUPP;
2515         }
2516
2517         if (dissector_uses_key(f->dissector, FLOW_DISSECTOR_KEY_ETH_ADDRS)) {
2518                 struct flow_dissector_key_eth_addrs *key, *mask;
2519
2520                 key = skb_flow_dissector_target(f->dissector,
2521                                                 FLOW_DISSECTOR_KEY_ETH_ADDRS,
2522                                                 f->key);
2523                 mask = skb_flow_dissector_target(f->dissector,
2524                                                  FLOW_DISSECTOR_KEY_ETH_ADDRS,
2525                                                  f->mask);
2526
2527                 if (!is_zero_ether_addr(mask->dst)) {
2528                         if (!is_broadcast_ether_addr(mask->dst)) {
2529                                 NL_SET_ERR_MSG_MOD(extack, "Only full masks are supported for destination MAC address");
2530                                 return -EINVAL;
2531                         }
2532
2533                         input->filter.match_flags |=
2534                                 IGB_FILTER_FLAG_DST_MAC_ADDR;
2535                         ether_addr_copy(input->filter.dst_addr, key->dst);
2536                 }
2537
2538                 if (!is_zero_ether_addr(mask->src)) {
2539                         if (!is_broadcast_ether_addr(mask->src)) {
2540                                 NL_SET_ERR_MSG_MOD(extack, "Only full masks are supported for source MAC address");
2541                                 return -EINVAL;
2542                         }
2543
2544                         input->filter.match_flags |=
2545                                 IGB_FILTER_FLAG_SRC_MAC_ADDR;
2546                         ether_addr_copy(input->filter.src_addr, key->src);
2547                 }
2548         }
2549
2550         if (dissector_uses_key(f->dissector, FLOW_DISSECTOR_KEY_BASIC)) {
2551                 struct flow_dissector_key_basic *key, *mask;
2552
2553                 key = skb_flow_dissector_target(f->dissector,
2554                                                 FLOW_DISSECTOR_KEY_BASIC,
2555                                                 f->key);
2556                 mask = skb_flow_dissector_target(f->dissector,
2557                                                  FLOW_DISSECTOR_KEY_BASIC,
2558                                                  f->mask);
2559
2560                 if (mask->n_proto) {
2561                         if (mask->n_proto != ETHER_TYPE_FULL_MASK) {
2562                                 NL_SET_ERR_MSG_MOD(extack, "Only full mask is supported for EtherType filter");
2563                                 return -EINVAL;
2564                         }
2565
2566                         input->filter.match_flags |= IGB_FILTER_FLAG_ETHER_TYPE;
2567                         input->filter.etype = key->n_proto;
2568                 }
2569         }
2570
2571         if (dissector_uses_key(f->dissector, FLOW_DISSECTOR_KEY_VLAN)) {
2572                 struct flow_dissector_key_vlan *key, *mask;
2573
2574                 key = skb_flow_dissector_target(f->dissector,
2575                                                 FLOW_DISSECTOR_KEY_VLAN,
2576                                                 f->key);
2577                 mask = skb_flow_dissector_target(f->dissector,
2578                                                  FLOW_DISSECTOR_KEY_VLAN,
2579                                                  f->mask);
2580
2581                 if (mask->vlan_priority) {
2582                         if (mask->vlan_priority != VLAN_PRIO_FULL_MASK) {
2583                                 NL_SET_ERR_MSG_MOD(extack, "Only full mask is supported for VLAN priority");
2584                                 return -EINVAL;
2585                         }
2586
2587                         input->filter.match_flags |= IGB_FILTER_FLAG_VLAN_TCI;
2588                         input->filter.vlan_tci = key->vlan_priority;
2589                 }
2590         }
2591
2592         input->action = traffic_class;
2593         input->cookie = f->cookie;
2594
2595         return 0;
2596 }
2597
2598 static int igb_configure_clsflower(struct igb_adapter *adapter,
2599                                    struct tc_cls_flower_offload *cls_flower)
2600 {
2601         struct netlink_ext_ack *extack = cls_flower->common.extack;
2602         struct igb_nfc_filter *filter, *f;
2603         int err, tc;
2604
2605         tc = tc_classid_to_hwtc(adapter->netdev, cls_flower->classid);
2606         if (tc < 0) {
2607                 NL_SET_ERR_MSG_MOD(extack, "Invalid traffic class");
2608                 return -EINVAL;
2609         }
2610
2611         filter = kzalloc(sizeof(*filter), GFP_KERNEL);
2612         if (!filter)
2613                 return -ENOMEM;
2614
2615         err = igb_parse_cls_flower(adapter, cls_flower, tc, filter);
2616         if (err < 0)
2617                 goto err_parse;
2618
2619         spin_lock(&adapter->nfc_lock);
2620
2621         hlist_for_each_entry(f, &adapter->nfc_filter_list, nfc_node) {
2622                 if (!memcmp(&f->filter, &filter->filter, sizeof(f->filter))) {
2623                         err = -EEXIST;
2624                         NL_SET_ERR_MSG_MOD(extack,
2625                                            "This filter is already set in ethtool");
2626                         goto err_locked;
2627                 }
2628         }
2629
2630         hlist_for_each_entry(f, &adapter->cls_flower_list, nfc_node) {
2631                 if (!memcmp(&f->filter, &filter->filter, sizeof(f->filter))) {
2632                         err = -EEXIST;
2633                         NL_SET_ERR_MSG_MOD(extack,
2634                                            "This filter is already set in cls_flower");
2635                         goto err_locked;
2636                 }
2637         }
2638
2639         err = igb_add_filter(adapter, filter);
2640         if (err < 0) {
2641                 NL_SET_ERR_MSG_MOD(extack, "Could not add filter to the adapter");
2642                 goto err_locked;
2643         }
2644
2645         hlist_add_head(&filter->nfc_node, &adapter->cls_flower_list);
2646
2647         spin_unlock(&adapter->nfc_lock);
2648
2649         return 0;
2650
2651 err_locked:
2652         spin_unlock(&adapter->nfc_lock);
2653
2654 err_parse:
2655         kfree(filter);
2656
2657         return err;
2658 }
2659
2660 static int igb_delete_clsflower(struct igb_adapter *adapter,
2661                                 struct tc_cls_flower_offload *cls_flower)
2662 {
2663         struct igb_nfc_filter *filter;
2664         int err;
2665
2666         spin_lock(&adapter->nfc_lock);
2667
2668         hlist_for_each_entry(filter, &adapter->cls_flower_list, nfc_node)
2669                 if (filter->cookie == cls_flower->cookie)
2670                         break;
2671
2672         if (!filter) {
2673                 err = -ENOENT;
2674                 goto out;
2675         }
2676
2677         err = igb_erase_filter(adapter, filter);
2678         if (err < 0)
2679                 goto out;
2680
2681         hlist_del(&filter->nfc_node);
2682         kfree(filter);
2683
2684 out:
2685         spin_unlock(&adapter->nfc_lock);
2686
2687         return err;
2688 }
2689
2690 static int igb_setup_tc_cls_flower(struct igb_adapter *adapter,
2691                                    struct tc_cls_flower_offload *cls_flower)
2692 {
2693         switch (cls_flower->command) {
2694         case TC_CLSFLOWER_REPLACE:
2695                 return igb_configure_clsflower(adapter, cls_flower);
2696         case TC_CLSFLOWER_DESTROY:
2697                 return igb_delete_clsflower(adapter, cls_flower);
2698         case TC_CLSFLOWER_STATS:
2699                 return -EOPNOTSUPP;
2700         default:
2701                 return -EINVAL;
2702         }
2703 }
2704
2705 static int igb_setup_tc_block_cb(enum tc_setup_type type, void *type_data,
2706                                  void *cb_priv)
2707 {
2708         struct igb_adapter *adapter = cb_priv;
2709
2710         if (!tc_cls_can_offload_and_chain0(adapter->netdev, type_data))
2711                 return -EOPNOTSUPP;
2712
2713         switch (type) {
2714         case TC_SETUP_CLSFLOWER:
2715                 return igb_setup_tc_cls_flower(adapter, type_data);
2716
2717         default:
2718                 return -EOPNOTSUPP;
2719         }
2720 }
2721
2722 static int igb_setup_tc_block(struct igb_adapter *adapter,
2723                               struct tc_block_offload *f)
2724 {
2725         if (f->binder_type != TCF_BLOCK_BINDER_TYPE_CLSACT_INGRESS)
2726                 return -EOPNOTSUPP;
2727
2728         switch (f->command) {
2729         case TC_BLOCK_BIND:
2730                 return tcf_block_cb_register(f->block, igb_setup_tc_block_cb,
2731                                              adapter, adapter);
2732         case TC_BLOCK_UNBIND:
2733                 tcf_block_cb_unregister(f->block, igb_setup_tc_block_cb,
2734                                         adapter);
2735                 return 0;
2736         default:
2737                 return -EOPNOTSUPP;
2738         }
2739 }
2740
2741 static int igb_setup_tc(struct net_device *dev, enum tc_setup_type type,
2742                         void *type_data)
2743 {
2744         struct igb_adapter *adapter = netdev_priv(dev);
2745
2746         switch (type) {
2747         case TC_SETUP_QDISC_CBS:
2748                 return igb_offload_cbs(adapter, type_data);
2749         case TC_SETUP_BLOCK:
2750                 return igb_setup_tc_block(adapter, type_data);
2751
2752         default:
2753                 return -EOPNOTSUPP;
2754         }
2755 }
2756
2757 static const struct net_device_ops igb_netdev_ops = {
2758         .ndo_open               = igb_open,
2759         .ndo_stop               = igb_close,
2760         .ndo_start_xmit         = igb_xmit_frame,
2761         .ndo_get_stats64        = igb_get_stats64,
2762         .ndo_set_rx_mode        = igb_set_rx_mode,
2763         .ndo_set_mac_address    = igb_set_mac,
2764         .ndo_change_mtu         = igb_change_mtu,
2765         .ndo_do_ioctl           = igb_ioctl,
2766         .ndo_tx_timeout         = igb_tx_timeout,
2767         .ndo_validate_addr      = eth_validate_addr,
2768         .ndo_vlan_rx_add_vid    = igb_vlan_rx_add_vid,
2769         .ndo_vlan_rx_kill_vid   = igb_vlan_rx_kill_vid,
2770         .ndo_set_vf_mac         = igb_ndo_set_vf_mac,
2771         .ndo_set_vf_vlan        = igb_ndo_set_vf_vlan,
2772         .ndo_set_vf_rate        = igb_ndo_set_vf_bw,
2773         .ndo_set_vf_spoofchk    = igb_ndo_set_vf_spoofchk,
2774         .ndo_set_vf_trust       = igb_ndo_set_vf_trust,
2775         .ndo_get_vf_config      = igb_ndo_get_vf_config,
2776 #ifdef CONFIG_NET_POLL_CONTROLLER
2777         .ndo_poll_controller    = igb_netpoll,
2778 #endif
2779         .ndo_fix_features       = igb_fix_features,
2780         .ndo_set_features       = igb_set_features,
2781         .ndo_fdb_add            = igb_ndo_fdb_add,
2782         .ndo_features_check     = igb_features_check,
2783         .ndo_setup_tc           = igb_setup_tc,
2784 };
2785
2786 /**
2787  * igb_set_fw_version - Configure version string for ethtool
2788  * @adapter: adapter struct
2789  **/
2790 void igb_set_fw_version(struct igb_adapter *adapter)
2791 {
2792         struct e1000_hw *hw = &adapter->hw;
2793         struct e1000_fw_version fw;
2794
2795         igb_get_fw_version(hw, &fw);
2796
2797         switch (hw->mac.type) {
2798         case e1000_i210:
2799         case e1000_i211:
2800                 if (!(igb_get_flash_presence_i210(hw))) {
2801                         snprintf(adapter->fw_version,
2802                                  sizeof(adapter->fw_version),
2803                                  "%2d.%2d-%d",
2804                                  fw.invm_major, fw.invm_minor,
2805                                  fw.invm_img_type);
2806                         break;
2807                 }
2808                 /* fall through */
2809         default:
2810                 /* if option is rom valid, display its version too */
2811                 if (fw.or_valid) {
2812                         snprintf(adapter->fw_version,
2813                                  sizeof(adapter->fw_version),
2814                                  "%d.%d, 0x%08x, %d.%d.%d",
2815                                  fw.eep_major, fw.eep_minor, fw.etrack_id,
2816                                  fw.or_major, fw.or_build, fw.or_patch);
2817                 /* no option rom */
2818                 } else if (fw.etrack_id != 0X0000) {
2819                         snprintf(adapter->fw_version,
2820                             sizeof(adapter->fw_version),
2821                             "%d.%d, 0x%08x",
2822                             fw.eep_major, fw.eep_minor, fw.etrack_id);
2823                 } else {
2824                 snprintf(adapter->fw_version,
2825                     sizeof(adapter->fw_version),
2826                     "%d.%d.%d",
2827                     fw.eep_major, fw.eep_minor, fw.eep_build);
2828                 }
2829                 break;
2830         }
2831 }
2832
2833 /**
2834  * igb_init_mas - init Media Autosense feature if enabled in the NVM
2835  *
2836  * @adapter: adapter struct
2837  **/
2838 static void igb_init_mas(struct igb_adapter *adapter)
2839 {
2840         struct e1000_hw *hw = &adapter->hw;
2841         u16 eeprom_data;
2842
2843         hw->nvm.ops.read(hw, NVM_COMPAT, 1, &eeprom_data);
2844         switch (hw->bus.func) {
2845         case E1000_FUNC_0:
2846                 if (eeprom_data & IGB_MAS_ENABLE_0) {
2847                         adapter->flags |= IGB_FLAG_MAS_ENABLE;
2848                         netdev_info(adapter->netdev,
2849                                 "MAS: Enabling Media Autosense for port %d\n",
2850                                 hw->bus.func);
2851                 }
2852                 break;
2853         case E1000_FUNC_1:
2854                 if (eeprom_data & IGB_MAS_ENABLE_1) {
2855                         adapter->flags |= IGB_FLAG_MAS_ENABLE;
2856                         netdev_info(adapter->netdev,
2857                                 "MAS: Enabling Media Autosense for port %d\n",
2858                                 hw->bus.func);
2859                 }
2860                 break;
2861         case E1000_FUNC_2:
2862                 if (eeprom_data & IGB_MAS_ENABLE_2) {
2863                         adapter->flags |= IGB_FLAG_MAS_ENABLE;
2864                         netdev_info(adapter->netdev,
2865                                 "MAS: Enabling Media Autosense for port %d\n",
2866                                 hw->bus.func);
2867                 }
2868                 break;
2869         case E1000_FUNC_3:
2870                 if (eeprom_data & IGB_MAS_ENABLE_3) {
2871                         adapter->flags |= IGB_FLAG_MAS_ENABLE;
2872                         netdev_info(adapter->netdev,
2873                                 "MAS: Enabling Media Autosense for port %d\n",
2874                                 hw->bus.func);
2875                 }
2876                 break;
2877         default:
2878                 /* Shouldn't get here */
2879                 netdev_err(adapter->netdev,
2880                         "MAS: Invalid port configuration, returning\n");
2881                 break;
2882         }
2883 }
2884
2885 /**
2886  *  igb_init_i2c - Init I2C interface
2887  *  @adapter: pointer to adapter structure
2888  **/
2889 static s32 igb_init_i2c(struct igb_adapter *adapter)
2890 {
2891         s32 status = 0;
2892
2893         /* I2C interface supported on i350 devices */
2894         if (adapter->hw.mac.type != e1000_i350)
2895                 return 0;
2896
2897         /* Initialize the i2c bus which is controlled by the registers.
2898          * This bus will use the i2c_algo_bit structue that implements
2899          * the protocol through toggling of the 4 bits in the register.
2900          */
2901         adapter->i2c_adap.owner = THIS_MODULE;
2902         adapter->i2c_algo = igb_i2c_algo;
2903         adapter->i2c_algo.data = adapter;
2904         adapter->i2c_adap.algo_data = &adapter->i2c_algo;
2905         adapter->i2c_adap.dev.parent = &adapter->pdev->dev;
2906         strlcpy(adapter->i2c_adap.name, "igb BB",
2907                 sizeof(adapter->i2c_adap.name));
2908         status = i2c_bit_add_bus(&adapter->i2c_adap);
2909         return status;
2910 }
2911
2912 /**
2913  *  igb_probe - Device Initialization Routine
2914  *  @pdev: PCI device information struct
2915  *  @ent: entry in igb_pci_tbl
2916  *
2917  *  Returns 0 on success, negative on failure
2918  *
2919  *  igb_probe initializes an adapter identified by a pci_dev structure.
2920  *  The OS initialization, configuring of the adapter private structure,
2921  *  and a hardware reset occur.
2922  **/
2923 static int igb_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
2924 {
2925         struct net_device *netdev;
2926         struct igb_adapter *adapter;
2927         struct e1000_hw *hw;
2928         u16 eeprom_data = 0;
2929         s32 ret_val;
2930         static int global_quad_port_a; /* global quad port a indication */
2931         const struct e1000_info *ei = igb_info_tbl[ent->driver_data];
2932         int err, pci_using_dac;
2933         u8 part_str[E1000_PBANUM_LENGTH];
2934
2935         /* Catch broken hardware that put the wrong VF device ID in
2936          * the PCIe SR-IOV capability.
2937          */
2938         if (pdev->is_virtfn) {
2939                 WARN(1, KERN_ERR "%s (%hx:%hx) should not be a VF!\n",
2940                         pci_name(pdev), pdev->vendor, pdev->device);
2941                 return -EINVAL;
2942         }
2943
2944         err = pci_enable_device_mem(pdev);
2945         if (err)
2946                 return err;
2947
2948         pci_using_dac = 0;
2949         err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
2950         if (!err) {
2951                 pci_using_dac = 1;
2952         } else {
2953                 err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
2954                 if (err) {
2955                         dev_err(&pdev->dev,
2956                                 "No usable DMA configuration, aborting\n");
2957                         goto err_dma;
2958                 }
2959         }
2960
2961         err = pci_request_mem_regions(pdev, igb_driver_name);
2962         if (err)
2963                 goto err_pci_reg;
2964
2965         pci_enable_pcie_error_reporting(pdev);
2966
2967         pci_set_master(pdev);
2968         pci_save_state(pdev);
2969
2970         err = -ENOMEM;
2971         netdev = alloc_etherdev_mq(sizeof(struct igb_adapter),
2972                                    IGB_MAX_TX_QUEUES);
2973         if (!netdev)
2974                 goto err_alloc_etherdev;
2975
2976         SET_NETDEV_DEV(netdev, &pdev->dev);
2977
2978         pci_set_drvdata(pdev, netdev);
2979         adapter = netdev_priv(netdev);
2980         adapter->netdev = netdev;
2981         adapter->pdev = pdev;
2982         hw = &adapter->hw;
2983         hw->back = adapter;
2984         adapter->msg_enable = netif_msg_init(debug, DEFAULT_MSG_ENABLE);
2985
2986         err = -EIO;
2987         adapter->io_addr = pci_iomap(pdev, 0, 0);
2988         if (!adapter->io_addr)
2989                 goto err_ioremap;
2990         /* hw->hw_addr can be altered, we'll use adapter->io_addr for unmap */
2991         hw->hw_addr = adapter->io_addr;
2992
2993         netdev->netdev_ops = &igb_netdev_ops;
2994         igb_set_ethtool_ops(netdev);
2995         netdev->watchdog_timeo = 5 * HZ;
2996
2997         strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1);
2998
2999         netdev->mem_start = pci_resource_start(pdev, 0);
3000         netdev->mem_end = pci_resource_end(pdev, 0);
3001
3002         /* PCI config space info */
3003         hw->vendor_id = pdev->vendor;
3004         hw->device_id = pdev->device;
3005         hw->revision_id = pdev->revision;
3006         hw->subsystem_vendor_id = pdev->subsystem_vendor;
3007         hw->subsystem_device_id = pdev->subsystem_device;
3008
3009         /* Copy the default MAC, PHY and NVM function pointers */
3010         memcpy(&hw->mac.ops, ei->mac_ops, sizeof(hw->mac.ops));
3011         memcpy(&hw->phy.ops, ei->phy_ops, sizeof(hw->phy.ops));
3012         memcpy(&hw->nvm.ops, ei->nvm_ops, sizeof(hw->nvm.ops));
3013         /* Initialize skew-specific constants */
3014         err = ei->get_invariants(hw);
3015         if (err)
3016                 goto err_sw_init;
3017
3018         /* setup the private structure */
3019         err = igb_sw_init(adapter);
3020         if (err)
3021                 goto err_sw_init;
3022
3023         igb_get_bus_info_pcie(hw);
3024
3025         hw->phy.autoneg_wait_to_complete = false;
3026
3027         /* Copper options */
3028         if (hw->phy.media_type == e1000_media_type_copper) {
3029                 hw->phy.mdix = AUTO_ALL_MODES;
3030                 hw->phy.disable_polarity_correction = false;
3031                 hw->phy.ms_type = e1000_ms_hw_default;
3032         }
3033
3034         if (igb_check_reset_block(hw))
3035                 dev_info(&pdev->dev,
3036                         "PHY reset is blocked due to SOL/IDER session.\n");
3037
3038         /* features is initialized to 0 in allocation, it might have bits
3039          * set by igb_sw_init so we should use an or instead of an
3040          * assignment.
3041          */
3042         netdev->features |= NETIF_F_SG |
3043                             NETIF_F_TSO |
3044                             NETIF_F_TSO6 |
3045                             NETIF_F_RXHASH |
3046                             NETIF_F_RXCSUM |
3047                             NETIF_F_HW_CSUM;
3048
3049         if (hw->mac.type >= e1000_82576)
3050                 netdev->features |= NETIF_F_SCTP_CRC;
3051
3052         if (hw->mac.type >= e1000_i350)
3053                 netdev->features |= NETIF_F_HW_TC;
3054
3055 #define IGB_GSO_PARTIAL_FEATURES (NETIF_F_GSO_GRE | \
3056                                   NETIF_F_GSO_GRE_CSUM | \
3057                                   NETIF_F_GSO_IPXIP4 | \
3058                                   NETIF_F_GSO_IPXIP6 | \
3059                                   NETIF_F_GSO_UDP_TUNNEL | \
3060                                   NETIF_F_GSO_UDP_TUNNEL_CSUM)
3061
3062         netdev->gso_partial_features = IGB_GSO_PARTIAL_FEATURES;
3063         netdev->features |= NETIF_F_GSO_PARTIAL | IGB_GSO_PARTIAL_FEATURES;
3064
3065         /* copy netdev features into list of user selectable features */
3066         netdev->hw_features |= netdev->features |
3067                                NETIF_F_HW_VLAN_CTAG_RX |
3068                                NETIF_F_HW_VLAN_CTAG_TX |
3069                                NETIF_F_RXALL;
3070
3071         if (hw->mac.type >= e1000_i350)
3072                 netdev->hw_features |= NETIF_F_NTUPLE;
3073
3074         if (pci_using_dac)
3075                 netdev->features |= NETIF_F_HIGHDMA;
3076
3077         netdev->vlan_features |= netdev->features | NETIF_F_TSO_MANGLEID;
3078         netdev->mpls_features |= NETIF_F_HW_CSUM;
3079         netdev->hw_enc_features |= netdev->vlan_features;
3080
3081         /* set this bit last since it cannot be part of vlan_features */
3082         netdev->features |= NETIF_F_HW_VLAN_CTAG_FILTER |
3083                             NETIF_F_HW_VLAN_CTAG_RX |
3084                             NETIF_F_HW_VLAN_CTAG_TX;
3085
3086         netdev->priv_flags |= IFF_SUPP_NOFCS;
3087
3088         netdev->priv_flags |= IFF_UNICAST_FLT;
3089
3090         /* MTU range: 68 - 9216 */
3091         netdev->min_mtu = ETH_MIN_MTU;
3092         netdev->max_mtu = MAX_STD_JUMBO_FRAME_SIZE;
3093
3094         adapter->en_mng_pt = igb_enable_mng_pass_thru(hw);
3095
3096         /* before reading the NVM, reset the controller to put the device in a
3097          * known good starting state
3098          */
3099         hw->mac.ops.reset_hw(hw);
3100
3101         /* make sure the NVM is good , i211/i210 parts can have special NVM
3102          * that doesn't contain a checksum
3103          */
3104         switch (hw->mac.type) {
3105         case e1000_i210:
3106         case e1000_i211:
3107                 if (igb_get_flash_presence_i210(hw)) {
3108                         if (hw->nvm.ops.validate(hw) < 0) {
3109                                 dev_err(&pdev->dev,
3110                                         "The NVM Checksum Is Not Valid\n");
3111                                 err = -EIO;
3112                                 goto err_eeprom;
3113                         }
3114                 }
3115                 break;
3116         default:
3117                 if (hw->nvm.ops.validate(hw) < 0) {
3118                         dev_err(&pdev->dev, "The NVM Checksum Is Not Valid\n");
3119                         err = -EIO;
3120                         goto err_eeprom;
3121                 }
3122                 break;
3123         }
3124
3125         if (eth_platform_get_mac_address(&pdev->dev, hw->mac.addr)) {
3126                 /* copy the MAC address out of the NVM */
3127                 if (hw->mac.ops.read_mac_addr(hw))
3128                         dev_err(&pdev->dev, "NVM Read Error\n");
3129         }
3130
3131         memcpy(netdev->dev_addr, hw->mac.addr, netdev->addr_len);
3132
3133         if (!is_valid_ether_addr(netdev->dev_addr)) {
3134                 dev_err(&pdev->dev, "Invalid MAC Address\n");
3135                 err = -EIO;
3136                 goto err_eeprom;
3137         }
3138
3139         igb_set_default_mac_filter(adapter);
3140
3141         /* get firmware version for ethtool -i */
3142         igb_set_fw_version(adapter);
3143
3144         /* configure RXPBSIZE and TXPBSIZE */
3145         if (hw->mac.type == e1000_i210) {
3146                 wr32(E1000_RXPBS, I210_RXPBSIZE_DEFAULT);
3147                 wr32(E1000_TXPBS, I210_TXPBSIZE_DEFAULT);
3148         }
3149
3150         timer_setup(&adapter->watchdog_timer, igb_watchdog, 0);
3151         timer_setup(&adapter->phy_info_timer, igb_update_phy_info, 0);
3152
3153         INIT_WORK(&adapter->reset_task, igb_reset_task);
3154         INIT_WORK(&adapter->watchdog_task, igb_watchdog_task);
3155
3156         /* Initialize link properties that are user-changeable */
3157         adapter->fc_autoneg = true;
3158         hw->mac.autoneg = true;
3159         hw->phy.autoneg_advertised = 0x2f;
3160
3161         hw->fc.requested_mode = e1000_fc_default;
3162         hw->fc.current_mode = e1000_fc_default;
3163
3164         igb_validate_mdi_setting(hw);
3165
3166         /* By default, support wake on port A */
3167         if (hw->bus.func == 0)
3168                 adapter->flags |= IGB_FLAG_WOL_SUPPORTED;
3169
3170         /* Check the NVM for wake support on non-port A ports */
3171         if (hw->mac.type >= e1000_82580)
3172                 hw->nvm.ops.read(hw, NVM_INIT_CONTROL3_PORT_A +
3173                                  NVM_82580_LAN_FUNC_OFFSET(hw->bus.func), 1,
3174                                  &eeprom_data);
3175         else if (hw->bus.func == 1)
3176                 hw->nvm.ops.read(hw, NVM_INIT_CONTROL3_PORT_B, 1, &eeprom_data);
3177
3178         if (eeprom_data & IGB_EEPROM_APME)
3179                 adapter->flags |= IGB_FLAG_WOL_SUPPORTED;
3180
3181         /* now that we have the eeprom settings, apply the special cases where
3182          * the eeprom may be wrong or the board simply won't support wake on
3183          * lan on a particular port
3184          */
3185         switch (pdev->device) {
3186         case E1000_DEV_ID_82575GB_QUAD_COPPER:
3187                 adapter->flags &= ~IGB_FLAG_WOL_SUPPORTED;
3188                 break;
3189         case E1000_DEV_ID_82575EB_FIBER_SERDES:
3190         case E1000_DEV_ID_82576_FIBER:
3191         case E1000_DEV_ID_82576_SERDES:
3192                 /* Wake events only supported on port A for dual fiber
3193                  * regardless of eeprom setting
3194                  */
3195                 if (rd32(E1000_STATUS) & E1000_STATUS_FUNC_1)
3196                         adapter->flags &= ~IGB_FLAG_WOL_SUPPORTED;
3197                 break;
3198         case E1000_DEV_ID_82576_QUAD_COPPER:
3199         case E1000_DEV_ID_82576_QUAD_COPPER_ET2:
3200                 /* if quad port adapter, disable WoL on all but port A */
3201                 if (global_quad_port_a != 0)
3202                         adapter->flags &= ~IGB_FLAG_WOL_SUPPORTED;
3203                 else
3204                         adapter->flags |= IGB_FLAG_QUAD_PORT_A;
3205                 /* Reset for multiple quad port adapters */
3206                 if (++global_quad_port_a == 4)
3207                         global_quad_port_a = 0;
3208                 break;
3209         default:
3210                 /* If the device can't wake, don't set software support */
3211                 if (!device_can_wakeup(&adapter->pdev->dev))
3212                         adapter->flags &= ~IGB_FLAG_WOL_SUPPORTED;
3213         }
3214
3215         /* initialize the wol settings based on the eeprom settings */
3216         if (adapter->flags & IGB_FLAG_WOL_SUPPORTED)
3217                 adapter->wol |= E1000_WUFC_MAG;
3218
3219         /* Some vendors want WoL disabled by default, but still supported */
3220         if ((hw->mac.type == e1000_i350) &&
3221             (pdev->subsystem_vendor == PCI_VENDOR_ID_HP)) {
3222                 adapter->flags |= IGB_FLAG_WOL_SUPPORTED;
3223                 adapter->wol = 0;
3224         }
3225
3226         /* Some vendors want the ability to Use the EEPROM setting as
3227          * enable/disable only, and not for capability
3228          */
3229         if (((hw->mac.type == e1000_i350) ||
3230              (hw->mac.type == e1000_i354)) &&
3231             (pdev->subsystem_vendor == PCI_VENDOR_ID_DELL)) {
3232                 adapter->flags |= IGB_FLAG_WOL_SUPPORTED;
3233                 adapter->wol = 0;
3234         }
3235         if (hw->mac.type == e1000_i350) {
3236                 if (((pdev->subsystem_device == 0x5001) ||
3237                      (pdev->subsystem_device == 0x5002)) &&
3238                                 (hw->bus.func == 0)) {
3239                         adapter->flags |= IGB_FLAG_WOL_SUPPORTED;
3240                         adapter->wol = 0;
3241                 }
3242                 if (pdev->subsystem_device == 0x1F52)
3243                         adapter->flags |= IGB_FLAG_WOL_SUPPORTED;
3244         }
3245
3246         device_set_wakeup_enable(&adapter->pdev->dev,
3247                                  adapter->flags & IGB_FLAG_WOL_SUPPORTED);
3248
3249         /* reset the hardware with the new settings */
3250         igb_reset(adapter);
3251
3252         /* Init the I2C interface */
3253         err = igb_init_i2c(adapter);
3254         if (err) {
3255                 dev_err(&pdev->dev, "failed to init i2c interface\n");
3256                 goto err_eeprom;
3257         }
3258
3259         /* let the f/w know that the h/w is now under the control of the
3260          * driver.
3261          */
3262         igb_get_hw_control(adapter);
3263
3264         strcpy(netdev->name, "eth%d");
3265         err = register_netdev(netdev);
3266         if (err)
3267                 goto err_register;
3268
3269         /* carrier off reporting is important to ethtool even BEFORE open */
3270         netif_carrier_off(netdev);
3271
3272 #ifdef CONFIG_IGB_DCA
3273         if (dca_add_requester(&pdev->dev) == 0) {
3274                 adapter->flags |= IGB_FLAG_DCA_ENABLED;
3275                 dev_info(&pdev->dev, "DCA enabled\n");
3276                 igb_setup_dca(adapter);
3277         }
3278
3279 #endif
3280 #ifdef CONFIG_IGB_HWMON
3281         /* Initialize the thermal sensor on i350 devices. */
3282         if (hw->mac.type == e1000_i350 && hw->bus.func == 0) {
3283                 u16 ets_word;
3284
3285                 /* Read the NVM to determine if this i350 device supports an
3286                  * external thermal sensor.
3287                  */
3288                 hw->nvm.ops.read(hw, NVM_ETS_CFG, 1, &ets_word);
3289                 if (ets_word != 0x0000 && ets_word != 0xFFFF)
3290                         adapter->ets = true;
3291                 else
3292                         adapter->ets = false;
3293                 if (igb_sysfs_init(adapter))
3294                         dev_err(&pdev->dev,
3295                                 "failed to allocate sysfs resources\n");
3296         } else {
3297                 adapter->ets = false;
3298         }
3299 #endif
3300         /* Check if Media Autosense is enabled */
3301         adapter->ei = *ei;
3302         if (hw->dev_spec._82575.mas_capable)
3303                 igb_init_mas(adapter);
3304
3305         /* do hw tstamp init after resetting */
3306         igb_ptp_init(adapter);
3307
3308         dev_info(&pdev->dev, "Intel(R) Gigabit Ethernet Network Connection\n");
3309         /* print bus type/speed/width info, not applicable to i354 */
3310         if (hw->mac.type != e1000_i354) {
3311                 dev_info(&pdev->dev, "%s: (PCIe:%s:%s) %pM\n",
3312                          netdev->name,
3313                          ((hw->bus.speed == e1000_bus_speed_2500) ? "2.5Gb/s" :
3314                           (hw->bus.speed == e1000_bus_speed_5000) ? "5.0Gb/s" :
3315                            "unknown"),
3316                          ((hw->bus.width == e1000_bus_width_pcie_x4) ?
3317                           "Width x4" :
3318                           (hw->bus.width == e1000_bus_width_pcie_x2) ?
3319                           "Width x2" :
3320                           (hw->bus.width == e1000_bus_width_pcie_x1) ?
3321                           "Width x1" : "unknown"), netdev->dev_addr);
3322         }
3323
3324         if ((hw->mac.type >= e1000_i210 ||
3325              igb_get_flash_presence_i210(hw))) {
3326                 ret_val = igb_read_part_string(hw, part_str,
3327                                                E1000_PBANUM_LENGTH);
3328         } else {
3329                 ret_val = -E1000_ERR_INVM_VALUE_NOT_FOUND;
3330         }
3331
3332         if (ret_val)
3333                 strcpy(part_str, "Unknown");
3334         dev_info(&pdev->dev, "%s: PBA No: %s\n", netdev->name, part_str);
3335         dev_info(&pdev->dev,
3336                 "Using %s interrupts. %d rx queue(s), %d tx queue(s)\n",
3337                 (adapter->flags & IGB_FLAG_HAS_MSIX) ? "MSI-X" :
3338                 (adapter->flags & IGB_FLAG_HAS_MSI) ? "MSI" : "legacy",
3339                 adapter->num_rx_queues, adapter->num_tx_queues);
3340         if (hw->phy.media_type == e1000_media_type_copper) {
3341                 switch (hw->mac.type) {
3342                 case e1000_i350:
3343                 case e1000_i210:
3344                 case e1000_i211:
3345                         /* Enable EEE for internal copper PHY devices */
3346                         err = igb_set_eee_i350(hw, true, true);
3347                         if ((!err) &&
3348                             (!hw->dev_spec._82575.eee_disable)) {
3349                                 adapter->eee_advert =
3350                                         MDIO_EEE_100TX | MDIO_EEE_1000T;
3351                                 adapter->flags |= IGB_FLAG_EEE;
3352                         }
3353                         break;
3354                 case e1000_i354:
3355                         if ((rd32(E1000_CTRL_EXT) &
3356                             E1000_CTRL_EXT_LINK_MODE_SGMII)) {
3357                                 err = igb_set_eee_i354(hw, true, true);
3358                                 if ((!err) &&
3359                                         (!hw->dev_spec._82575.eee_disable)) {
3360                                         adapter->eee_advert =
3361                                            MDIO_EEE_100TX | MDIO_EEE_1000T;
3362                                         adapter->flags |= IGB_FLAG_EEE;
3363                                 }
3364                         }
3365                         break;
3366                 default:
3367                         break;
3368                 }
3369         }
3370         pm_runtime_put_noidle(&pdev->dev);
3371         return 0;
3372
3373 err_register:
3374         igb_release_hw_control(adapter);
3375         memset(&adapter->i2c_adap, 0, sizeof(adapter->i2c_adap));
3376 err_eeprom:
3377         if (!igb_check_reset_block(hw))
3378                 igb_reset_phy(hw);
3379
3380         if (hw->flash_address)
3381                 iounmap(hw->flash_address);
3382 err_sw_init:
3383         kfree(adapter->mac_table);
3384         kfree(adapter->shadow_vfta);
3385         igb_clear_interrupt_scheme(adapter);
3386 #ifdef CONFIG_PCI_IOV
3387         igb_disable_sriov(pdev);
3388 #endif
3389         pci_iounmap(pdev, adapter->io_addr);
3390 err_ioremap:
3391         free_netdev(netdev);
3392 err_alloc_etherdev:
3393         pci_release_mem_regions(pdev);
3394 err_pci_reg:
3395 err_dma:
3396         pci_disable_device(pdev);
3397         return err;
3398 }
3399
3400 #ifdef CONFIG_PCI_IOV
3401 static int igb_disable_sriov(struct pci_dev *pdev)
3402 {
3403         struct net_device *netdev = pci_get_drvdata(pdev);
3404         struct igb_adapter *adapter = netdev_priv(netdev);
3405         struct e1000_hw *hw = &adapter->hw;
3406
3407         /* reclaim resources allocated to VFs */
3408         if (adapter->vf_data) {
3409                 /* disable iov and allow time for transactions to clear */
3410                 if (pci_vfs_assigned(pdev)) {
3411                         dev_warn(&pdev->dev,
3412                                  "Cannot deallocate SR-IOV virtual functions while they are assigned - VFs will not be deallocated\n");
3413                         return -EPERM;
3414                 } else {
3415                         pci_disable_sriov(pdev);
3416                         msleep(500);
3417                 }
3418
3419                 kfree(adapter->vf_mac_list);
3420                 adapter->vf_mac_list = NULL;
3421                 kfree(adapter->vf_data);
3422                 adapter->vf_data = NULL;
3423                 adapter->vfs_allocated_count = 0;
3424                 wr32(E1000_IOVCTL, E1000_IOVCTL_REUSE_VFQ);
3425                 wrfl();
3426                 msleep(100);
3427                 dev_info(&pdev->dev, "IOV Disabled\n");
3428
3429                 /* Re-enable DMA Coalescing flag since IOV is turned off */
3430                 adapter->flags |= IGB_FLAG_DMAC;
3431         }
3432
3433         return 0;
3434 }
3435
3436 static int igb_enable_sriov(struct pci_dev *pdev, int num_vfs)
3437 {
3438         struct net_device *netdev = pci_get_drvdata(pdev);
3439         struct igb_adapter *adapter = netdev_priv(netdev);
3440         int old_vfs = pci_num_vf(pdev);
3441         struct vf_mac_filter *mac_list;
3442         int err = 0;
3443         int num_vf_mac_filters, i;
3444
3445         if (!(adapter->flags & IGB_FLAG_HAS_MSIX) || num_vfs > 7) {
3446                 err = -EPERM;
3447                 goto out;
3448         }
3449         if (!num_vfs)
3450                 goto out;
3451
3452         if (old_vfs) {
3453                 dev_info(&pdev->dev, "%d pre-allocated VFs found - override max_vfs setting of %d\n",
3454                          old_vfs, max_vfs);
3455                 adapter->vfs_allocated_count = old_vfs;
3456         } else
3457                 adapter->vfs_allocated_count = num_vfs;
3458
3459         adapter->vf_data = kcalloc(adapter->vfs_allocated_count,
3460                                 sizeof(struct vf_data_storage), GFP_KERNEL);
3461
3462         /* if allocation failed then we do not support SR-IOV */
3463         if (!adapter->vf_data) {
3464                 adapter->vfs_allocated_count = 0;
3465                 err = -ENOMEM;
3466                 goto out;
3467         }
3468
3469         /* Due to the limited number of RAR entries calculate potential
3470          * number of MAC filters available for the VFs. Reserve entries
3471          * for PF default MAC, PF MAC filters and at least one RAR entry
3472          * for each VF for VF MAC.
3473          */
3474         num_vf_mac_filters = adapter->hw.mac.rar_entry_count -
3475                              (1 + IGB_PF_MAC_FILTERS_RESERVED +
3476                               adapter->vfs_allocated_count);
3477
3478         adapter->vf_mac_list = kcalloc(num_vf_mac_filters,
3479                                        sizeof(struct vf_mac_filter),
3480                                        GFP_KERNEL);
3481
3482         mac_list = adapter->vf_mac_list;
3483         INIT_LIST_HEAD(&adapter->vf_macs.l);
3484
3485         if (adapter->vf_mac_list) {
3486                 /* Initialize list of VF MAC filters */
3487                 for (i = 0; i < num_vf_mac_filters; i++) {
3488                         mac_list->vf = -1;
3489                         mac_list->free = true;
3490                         list_add(&mac_list->l, &adapter->vf_macs.l);
3491                         mac_list++;
3492                 }
3493         } else {
3494                 /* If we could not allocate memory for the VF MAC filters
3495                  * we can continue without this feature but warn user.
3496                  */
3497                 dev_err(&pdev->dev,
3498                         "Unable to allocate memory for VF MAC filter list\n");
3499         }
3500
3501         /* only call pci_enable_sriov() if no VFs are allocated already */
3502         if (!old_vfs) {
3503                 err = pci_enable_sriov(pdev, adapter->vfs_allocated_count);
3504                 if (err)
3505                         goto err_out;
3506         }
3507         dev_info(&pdev->dev, "%d VFs allocated\n",
3508                  adapter->vfs_allocated_count);
3509         for (i = 0; i < adapter->vfs_allocated_count; i++)
3510                 igb_vf_configure(adapter, i);
3511
3512         /* DMA Coalescing is not supported in IOV mode. */
3513         adapter->flags &= ~IGB_FLAG_DMAC;
3514         goto out;
3515
3516 err_out:
3517         kfree(adapter->vf_mac_list);
3518         adapter->vf_mac_list = NULL;
3519         kfree(adapter->vf_data);
3520         adapter->vf_data = NULL;
3521         adapter->vfs_allocated_count = 0;
3522 out:
3523         return err;
3524 }
3525
3526 #endif
3527 /**
3528  *  igb_remove_i2c - Cleanup  I2C interface
3529  *  @adapter: pointer to adapter structure
3530  **/
3531 static void igb_remove_i2c(struct igb_adapter *adapter)
3532 {
3533         /* free the adapter bus structure */
3534         i2c_del_adapter(&adapter->i2c_adap);
3535 }
3536
3537 /**
3538  *  igb_remove - Device Removal Routine
3539  *  @pdev: PCI device information struct
3540  *
3541  *  igb_remove is called by the PCI subsystem to alert the driver
3542  *  that it should release a PCI device.  The could be caused by a
3543  *  Hot-Plug event, or because the driver is going to be removed from
3544  *  memory.
3545  **/
3546 static void igb_remove(struct pci_dev *pdev)
3547 {
3548         struct net_device *netdev = pci_get_drvdata(pdev);
3549         struct igb_adapter *adapter = netdev_priv(netdev);
3550         struct e1000_hw *hw = &adapter->hw;
3551
3552         pm_runtime_get_noresume(&pdev->dev);
3553 #ifdef CONFIG_IGB_HWMON
3554         igb_sysfs_exit(adapter);
3555 #endif
3556         igb_remove_i2c(adapter);
3557         igb_ptp_stop(adapter);
3558         /* The watchdog timer may be rescheduled, so explicitly
3559          * disable watchdog from being rescheduled.
3560          */
3561         set_bit(__IGB_DOWN, &adapter->state);
3562         del_timer_sync(&adapter->watchdog_timer);
3563         del_timer_sync(&adapter->phy_info_timer);
3564
3565         cancel_work_sync(&adapter->reset_task);
3566         cancel_work_sync(&adapter->watchdog_task);
3567
3568 #ifdef CONFIG_IGB_DCA
3569         if (adapter->flags & IGB_FLAG_DCA_ENABLED) {
3570                 dev_info(&pdev->dev, "DCA disabled\n");
3571                 dca_remove_requester(&pdev->dev);
3572                 adapter->flags &= ~IGB_FLAG_DCA_ENABLED;
3573                 wr32(E1000_DCA_CTRL, E1000_DCA_CTRL_DCA_MODE_DISABLE);
3574         }
3575 #endif
3576
3577         /* Release control of h/w to f/w.  If f/w is AMT enabled, this
3578          * would have already happened in close and is redundant.
3579          */
3580         igb_release_hw_control(adapter);
3581
3582 #ifdef CONFIG_PCI_IOV
3583         igb_disable_sriov(pdev);
3584 #endif
3585
3586         unregister_netdev(netdev);
3587
3588         igb_clear_interrupt_scheme(adapter);
3589
3590         pci_iounmap(pdev, adapter->io_addr);
3591         if (hw->flash_address)
3592                 iounmap(hw->flash_address);
3593         pci_release_mem_regions(pdev);
3594
3595         kfree(adapter->mac_table);
3596         kfree(adapter->shadow_vfta);
3597         free_netdev(netdev);
3598
3599         pci_disable_pcie_error_reporting(pdev);
3600
3601         pci_disable_device(pdev);
3602 }
3603
3604 /**
3605  *  igb_probe_vfs - Initialize vf data storage and add VFs to pci config space
3606  *  @adapter: board private structure to initialize
3607  *
3608  *  This function initializes the vf specific data storage and then attempts to
3609  *  allocate the VFs.  The reason for ordering it this way is because it is much
3610  *  mor expensive time wise to disable SR-IOV than it is to allocate and free
3611  *  the memory for the VFs.
3612  **/
3613 static void igb_probe_vfs(struct igb_adapter *adapter)
3614 {
3615 #ifdef CONFIG_PCI_IOV
3616         struct pci_dev *pdev = adapter->pdev;
3617         struct e1000_hw *hw = &adapter->hw;
3618
3619         /* Virtualization features not supported on i210 family. */
3620         if ((hw->mac.type == e1000_i210) || (hw->mac.type == e1000_i211))
3621                 return;
3622
3623         /* Of the below we really only want the effect of getting
3624          * IGB_FLAG_HAS_MSIX set (if available), without which
3625          * igb_enable_sriov() has no effect.
3626          */
3627         igb_set_interrupt_capability(adapter, true);
3628         igb_reset_interrupt_capability(adapter);
3629
3630         pci_sriov_set_totalvfs(pdev, 7);
3631         igb_enable_sriov(pdev, max_vfs);
3632
3633 #endif /* CONFIG_PCI_IOV */
3634 }
3635
3636 unsigned int igb_get_max_rss_queues(struct igb_adapter *adapter)
3637 {
3638         struct e1000_hw *hw = &adapter->hw;
3639         unsigned int max_rss_queues;
3640
3641         /* Determine the maximum number of RSS queues supported. */
3642         switch (hw->mac.type) {
3643         case e1000_i211:
3644                 max_rss_queues = IGB_MAX_RX_QUEUES_I211;
3645                 break;
3646         case e1000_82575:
3647         case e1000_i210:
3648                 max_rss_queues = IGB_MAX_RX_QUEUES_82575;
3649                 break;
3650         case e1000_i350:
3651                 /* I350 cannot do RSS and SR-IOV at the same time */
3652                 if (!!adapter->vfs_allocated_count) {
3653                         max_rss_queues = 1;
3654                         break;
3655                 }
3656                 /* fall through */
3657         case e1000_82576:
3658                 if (!!adapter->vfs_allocated_count) {
3659                         max_rss_queues = 2;
3660                         break;
3661                 }
3662                 /* fall through */
3663         case e1000_82580:
3664         case e1000_i354:
3665         default:
3666                 max_rss_queues = IGB_MAX_RX_QUEUES;
3667                 break;
3668         }
3669
3670         return max_rss_queues;
3671 }
3672
3673 static void igb_init_queue_configuration(struct igb_adapter *adapter)
3674 {
3675         u32 max_rss_queues;
3676
3677         max_rss_queues = igb_get_max_rss_queues(adapter);
3678         adapter->rss_queues = min_t(u32, max_rss_queues, num_online_cpus());
3679
3680         igb_set_flag_queue_pairs(adapter, max_rss_queues);
3681 }
3682
3683 void igb_set_flag_queue_pairs(struct igb_adapter *adapter,
3684                               const u32 max_rss_queues)
3685 {
3686         struct e1000_hw *hw = &adapter->hw;
3687
3688         /* Determine if we need to pair queues. */
3689         switch (hw->mac.type) {
3690         case e1000_82575:
3691         case e1000_i211:
3692                 /* Device supports enough interrupts without queue pairing. */
3693                 break;
3694         case e1000_82576:
3695         case e1000_82580:
3696         case e1000_i350:
3697         case e1000_i354:
3698         case e1000_i210:
3699         default:
3700                 /* If rss_queues > half of max_rss_queues, pair the queues in
3701                  * order to conserve interrupts due to limited supply.
3702                  */
3703                 if (adapter->rss_queues > (max_rss_queues / 2))
3704                         adapter->flags |= IGB_FLAG_QUEUE_PAIRS;
3705                 else
3706                         adapter->flags &= ~IGB_FLAG_QUEUE_PAIRS;
3707                 break;
3708         }
3709 }
3710
3711 /**
3712  *  igb_sw_init - Initialize general software structures (struct igb_adapter)
3713  *  @adapter: board private structure to initialize
3714  *
3715  *  igb_sw_init initializes the Adapter private data structure.
3716  *  Fields are initialized based on PCI device information and
3717  *  OS network device settings (MTU size).
3718  **/
3719 static int igb_sw_init(struct igb_adapter *adapter)
3720 {
3721         struct e1000_hw *hw = &adapter->hw;
3722         struct net_device *netdev = adapter->netdev;
3723         struct pci_dev *pdev = adapter->pdev;
3724
3725         pci_read_config_word(pdev, PCI_COMMAND, &hw->bus.pci_cmd_word);
3726
3727         /* set default ring sizes */
3728         adapter->tx_ring_count = IGB_DEFAULT_TXD;
3729         adapter->rx_ring_count = IGB_DEFAULT_RXD;
3730
3731         /* set default ITR values */
3732         adapter->rx_itr_setting = IGB_DEFAULT_ITR;
3733         adapter->tx_itr_setting = IGB_DEFAULT_ITR;
3734
3735         /* set default work limits */
3736         adapter->tx_work_limit = IGB_DEFAULT_TX_WORK;
3737
3738         adapter->max_frame_size = netdev->mtu + ETH_HLEN + ETH_FCS_LEN +
3739                                   VLAN_HLEN;
3740         adapter->min_frame_size = ETH_ZLEN + ETH_FCS_LEN;
3741
3742         spin_lock_init(&adapter->nfc_lock);
3743         spin_lock_init(&adapter->stats64_lock);
3744 #ifdef CONFIG_PCI_IOV
3745         switch (hw->mac.type) {
3746         case e1000_82576:
3747         case e1000_i350:
3748                 if (max_vfs > 7) {
3749                         dev_warn(&pdev->dev,
3750                                  "Maximum of 7 VFs per PF, using max\n");
3751                         max_vfs = adapter->vfs_allocated_count = 7;
3752                 } else
3753                         adapter->vfs_allocated_count = max_vfs;
3754                 if (adapter->vfs_allocated_count)
3755                         dev_warn(&pdev->dev,
3756                                  "Enabling SR-IOV VFs using the module parameter is deprecated - please use the pci sysfs interface.\n");
3757                 break;
3758         default:
3759                 break;
3760         }
3761 #endif /* CONFIG_PCI_IOV */
3762
3763         /* Assume MSI-X interrupts, will be checked during IRQ allocation */
3764         adapter->flags |= IGB_FLAG_HAS_MSIX;
3765
3766         adapter->mac_table = kcalloc(hw->mac.rar_entry_count,
3767                                      sizeof(struct igb_mac_addr),
3768                                      GFP_ATOMIC);
3769         if (!adapter->mac_table)
3770                 return -ENOMEM;
3771
3772         igb_probe_vfs(adapter);
3773
3774         igb_init_queue_configuration(adapter);
3775
3776         /* Setup and initialize a copy of the hw vlan table array */
3777         adapter->shadow_vfta = kcalloc(E1000_VLAN_FILTER_TBL_SIZE, sizeof(u32),
3778                                        GFP_ATOMIC);
3779         if (!adapter->shadow_vfta)
3780                 return -ENOMEM;
3781
3782         /* This call may decrease the number of queues */
3783         if (igb_init_interrupt_scheme(adapter, true)) {
3784                 dev_err(&pdev->dev, "Unable to allocate memory for queues\n");
3785                 return -ENOMEM;
3786         }
3787
3788         /* Explicitly disable IRQ since the NIC can be in any state. */
3789         igb_irq_disable(adapter);
3790
3791         if (hw->mac.type >= e1000_i350)
3792                 adapter->flags &= ~IGB_FLAG_DMAC;
3793
3794         set_bit(__IGB_DOWN, &adapter->state);
3795         return 0;
3796 }
3797
3798 /**
3799  *  igb_open - Called when a network interface is made active
3800  *  @netdev: network interface device structure
3801  *
3802  *  Returns 0 on success, negative value on failure
3803  *
3804  *  The open entry point is called when a network interface is made
3805  *  active by the system (IFF_UP).  At this point all resources needed
3806  *  for transmit and receive operations are allocated, the interrupt
3807  *  handler is registered with the OS, the watchdog timer is started,
3808  *  and the stack is notified that the interface is ready.
3809  **/
3810 static int __igb_open(struct net_device *netdev, bool resuming)
3811 {
3812         struct igb_adapter *adapter = netdev_priv(netdev);
3813         struct e1000_hw *hw = &adapter->hw;
3814         struct pci_dev *pdev = adapter->pdev;
3815         int err;
3816         int i;
3817
3818         /* disallow open during test */
3819         if (test_bit(__IGB_TESTING, &adapter->state)) {
3820                 WARN_ON(resuming);
3821                 return -EBUSY;
3822         }
3823
3824         if (!resuming)
3825                 pm_runtime_get_sync(&pdev->dev);
3826
3827         netif_carrier_off(netdev);
3828
3829         /* allocate transmit descriptors */
3830         err = igb_setup_all_tx_resources(adapter);
3831         if (err)
3832                 goto err_setup_tx;
3833
3834         /* allocate receive descriptors */
3835         err = igb_setup_all_rx_resources(adapter);
3836         if (err)
3837                 goto err_setup_rx;
3838
3839         igb_power_up_link(adapter);
3840
3841         /* before we allocate an interrupt, we must be ready to handle it.
3842          * Setting DEBUG_SHIRQ in the kernel makes it fire an interrupt
3843          * as soon as we call pci_request_irq, so we have to setup our
3844          * clean_rx handler before we do so.
3845          */
3846         igb_configure(adapter);
3847
3848         err = igb_request_irq(adapter);
3849         if (err)
3850                 goto err_req_irq;
3851
3852         /* Notify the stack of the actual queue counts. */
3853         err = netif_set_real_num_tx_queues(adapter->netdev,
3854                                            adapter->num_tx_queues);
3855         if (err)
3856                 goto err_set_queues;
3857
3858         err = netif_set_real_num_rx_queues(adapter->netdev,
3859                                            adapter->num_rx_queues);
3860         if (err)
3861                 goto err_set_queues;
3862
3863         /* From here on the code is the same as igb_up() */
3864         clear_bit(__IGB_DOWN, &adapter->state);
3865
3866         for (i = 0; i < adapter->num_q_vectors; i++)
3867                 napi_enable(&(adapter->q_vector[i]->napi));
3868
3869         /* Clear any pending interrupts. */
3870         rd32(E1000_TSICR);
3871         rd32(E1000_ICR);
3872
3873         igb_irq_enable(adapter);
3874
3875         /* notify VFs that reset has been completed */
3876         if (adapter->vfs_allocated_count) {
3877                 u32 reg_data = rd32(E1000_CTRL_EXT);
3878
3879                 reg_data |= E1000_CTRL_EXT_PFRSTD;
3880                 wr32(E1000_CTRL_EXT, reg_data);
3881         }
3882
3883         netif_tx_start_all_queues(netdev);
3884
3885         if (!resuming)
3886                 pm_runtime_put(&pdev->dev);
3887
3888         /* start the watchdog. */
3889         hw->mac.get_link_status = 1;
3890         schedule_work(&adapter->watchdog_task);
3891
3892         return 0;
3893
3894 err_set_queues:
3895         igb_free_irq(adapter);
3896 err_req_irq:
3897         igb_release_hw_control(adapter);
3898         igb_power_down_link(adapter);
3899         igb_free_all_rx_resources(adapter);
3900 err_setup_rx:
3901         igb_free_all_tx_resources(adapter);
3902 err_setup_tx:
3903         igb_reset(adapter);
3904         if (!resuming)
3905                 pm_runtime_put(&pdev->dev);
3906
3907         return err;
3908 }
3909
3910 int igb_open(struct net_device *netdev)
3911 {
3912         return __igb_open(netdev, false);
3913 }
3914
3915 /**
3916  *  igb_close - Disables a network interface
3917  *  @netdev: network interface device structure
3918  *
3919  *  Returns 0, this is not allowed to fail
3920  *
3921  *  The close entry point is called when an interface is de-activated
3922  *  by the OS.  The hardware is still under the driver's control, but
3923  *  needs to be disabled.  A global MAC reset is issued to stop the
3924  *  hardware, and all transmit and receive resources are freed.
3925  **/
3926 static int __igb_close(struct net_device *netdev, bool suspending)
3927 {
3928         struct igb_adapter *adapter = netdev_priv(netdev);
3929         struct pci_dev *pdev = adapter->pdev;
3930
3931         WARN_ON(test_bit(__IGB_RESETTING, &adapter->state));
3932
3933         if (!suspending)
3934                 pm_runtime_get_sync(&pdev->dev);
3935
3936         igb_down(adapter);
3937         igb_free_irq(adapter);
3938
3939         igb_free_all_tx_resources(adapter);
3940         igb_free_all_rx_resources(adapter);
3941
3942         if (!suspending)
3943                 pm_runtime_put_sync(&pdev->dev);
3944         return 0;
3945 }
3946
3947 int igb_close(struct net_device *netdev)
3948 {
3949         if (netif_device_present(netdev) || netdev->dismantle)
3950                 return __igb_close(netdev, false);
3951         return 0;
3952 }
3953
3954 /**
3955  *  igb_setup_tx_resources - allocate Tx resources (Descriptors)
3956  *  @tx_ring: tx descriptor ring (for a specific queue) to setup
3957  *
3958  *  Return 0 on success, negative on failure
3959  **/
3960 int igb_setup_tx_resources(struct igb_ring *tx_ring)
3961 {
3962         struct device *dev = tx_ring->dev;
3963         int size;
3964
3965         size = sizeof(struct igb_tx_buffer) * tx_ring->count;
3966
3967         tx_ring->tx_buffer_info = vmalloc(size);
3968         if (!tx_ring->tx_buffer_info)
3969                 goto err;
3970
3971         /* round up to nearest 4K */
3972         tx_ring->size = tx_ring->count * sizeof(union e1000_adv_tx_desc);
3973         tx_ring->size = ALIGN(tx_ring->size, 4096);
3974
3975         tx_ring->desc = dma_alloc_coherent(dev, tx_ring->size,
3976                                            &tx_ring->dma, GFP_KERNEL);
3977         if (!tx_ring->desc)
3978                 goto err;
3979
3980         tx_ring->next_to_use = 0;
3981         tx_ring->next_to_clean = 0;
3982
3983         return 0;
3984
3985 err:
3986         vfree(tx_ring->tx_buffer_info);
3987         tx_ring->tx_buffer_info = NULL;
3988         dev_err(dev, "Unable to allocate memory for the Tx descriptor ring\n");
3989         return -ENOMEM;
3990 }
3991
3992 /**
3993  *  igb_setup_all_tx_resources - wrapper to allocate Tx resources
3994  *                               (Descriptors) for all queues
3995  *  @adapter: board private structure
3996  *
3997  *  Return 0 on success, negative on failure
3998  **/
3999 static int igb_setup_all_tx_resources(struct igb_adapter *adapter)
4000 {
4001         struct pci_dev *pdev = adapter->pdev;
4002         int i, err = 0;
4003
4004         for (i = 0; i < adapter->num_tx_queues; i++) {
4005                 err = igb_setup_tx_resources(adapter->tx_ring[i]);
4006                 if (err) {
4007                         dev_err(&pdev->dev,
4008                                 "Allocation for Tx Queue %u failed\n", i);
4009                         for (i--; i >= 0; i--)
4010                                 igb_free_tx_resources(adapter->tx_ring[i]);
4011                         break;
4012                 }
4013         }
4014
4015         return err;
4016 }
4017
4018 /**
4019  *  igb_setup_tctl - configure the transmit control registers
4020  *  @adapter: Board private structure
4021  **/
4022 void igb_setup_tctl(struct igb_adapter *adapter)
4023 {
4024         struct e1000_hw *hw = &adapter->hw;
4025         u32 tctl;
4026
4027         /* disable queue 0 which is enabled by default on 82575 and 82576 */
4028         wr32(E1000_TXDCTL(0), 0);
4029
4030         /* Program the Transmit Control Register */
4031         tctl = rd32(E1000_TCTL);
4032         tctl &= ~E1000_TCTL_CT;
4033         tctl |= E1000_TCTL_PSP | E1000_TCTL_RTLC |
4034                 (E1000_COLLISION_THRESHOLD << E1000_CT_SHIFT);
4035
4036         igb_config_collision_dist(hw);
4037
4038         /* Enable transmits */
4039         tctl |= E1000_TCTL_EN;
4040
4041         wr32(E1000_TCTL, tctl);
4042 }
4043
4044 /**
4045  *  igb_configure_tx_ring - Configure transmit ring after Reset
4046  *  @adapter: board private structure
4047  *  @ring: tx ring to configure
4048  *
4049  *  Configure a transmit ring after a reset.
4050  **/
4051 void igb_configure_tx_ring(struct igb_adapter *adapter,
4052                            struct igb_ring *ring)
4053 {
4054         struct e1000_hw *hw = &adapter->hw;
4055         u32 txdctl = 0;
4056         u64 tdba = ring->dma;
4057         int reg_idx = ring->reg_idx;
4058
4059         wr32(E1000_TDLEN(reg_idx),
4060              ring->count * sizeof(union e1000_adv_tx_desc));
4061         wr32(E1000_TDBAL(reg_idx),
4062              tdba & 0x00000000ffffffffULL);
4063         wr32(E1000_TDBAH(reg_idx), tdba >> 32);
4064
4065         ring->tail = adapter->io_addr + E1000_TDT(reg_idx);
4066         wr32(E1000_TDH(reg_idx), 0);
4067         writel(0, ring->tail);
4068
4069         txdctl |= IGB_TX_PTHRESH;
4070         txdctl |= IGB_TX_HTHRESH << 8;
4071         txdctl |= IGB_TX_WTHRESH << 16;
4072
4073         /* reinitialize tx_buffer_info */
4074         memset(ring->tx_buffer_info, 0,
4075                sizeof(struct igb_tx_buffer) * ring->count);
4076
4077         txdctl |= E1000_TXDCTL_QUEUE_ENABLE;
4078         wr32(E1000_TXDCTL(reg_idx), txdctl);
4079 }
4080
4081 /**
4082  *  igb_configure_tx - Configure transmit Unit after Reset
4083  *  @adapter: board private structure
4084  *
4085  *  Configure the Tx unit of the MAC after a reset.
4086  **/
4087 static void igb_configure_tx(struct igb_adapter *adapter)
4088 {
4089         struct e1000_hw *hw = &adapter->hw;
4090         int i;
4091
4092         /* disable the queues */
4093         for (i = 0; i < adapter->num_tx_queues; i++)
4094                 wr32(E1000_TXDCTL(adapter->tx_ring[i]->reg_idx), 0);
4095
4096         wrfl();
4097         usleep_range(10000, 20000);
4098
4099         for (i = 0; i < adapter->num_tx_queues; i++)
4100                 igb_configure_tx_ring(adapter, adapter->tx_ring[i]);
4101 }
4102
4103 /**
4104  *  igb_setup_rx_resources - allocate Rx resources (Descriptors)
4105  *  @rx_ring: Rx descriptor ring (for a specific queue) to setup
4106  *
4107  *  Returns 0 on success, negative on failure
4108  **/
4109 int igb_setup_rx_resources(struct igb_ring *rx_ring)
4110 {
4111         struct device *dev = rx_ring->dev;
4112         int size;
4113
4114         size = sizeof(struct igb_rx_buffer) * rx_ring->count;
4115
4116         rx_ring->rx_buffer_info = vmalloc(size);
4117         if (!rx_ring->rx_buffer_info)
4118                 goto err;
4119
4120         /* Round up to nearest 4K */
4121         rx_ring->size = rx_ring->count * sizeof(union e1000_adv_rx_desc);
4122         rx_ring->size = ALIGN(rx_ring->size, 4096);
4123
4124         rx_ring->desc = dma_alloc_coherent(dev, rx_ring->size,
4125                                            &rx_ring->dma, GFP_KERNEL);
4126         if (!rx_ring->desc)
4127                 goto err;
4128
4129         rx_ring->next_to_alloc = 0;
4130         rx_ring->next_to_clean = 0;
4131         rx_ring->next_to_use = 0;
4132
4133         return 0;
4134
4135 err:
4136         vfree(rx_ring->rx_buffer_info);
4137         rx_ring->rx_buffer_info = NULL;
4138         dev_err(dev, "Unable to allocate memory for the Rx descriptor ring\n");
4139         return -ENOMEM;
4140 }
4141
4142 /**
4143  *  igb_setup_all_rx_resources - wrapper to allocate Rx resources
4144  *                               (Descriptors) for all queues
4145  *  @adapter: board private structure
4146  *
4147  *  Return 0 on success, negative on failure
4148  **/
4149 static int igb_setup_all_rx_resources(struct igb_adapter *adapter)
4150 {
4151         struct pci_dev *pdev = adapter->pdev;
4152         int i, err = 0;
4153
4154         for (i = 0; i < adapter->num_rx_queues; i++) {
4155                 err = igb_setup_rx_resources(adapter->rx_ring[i]);
4156                 if (err) {
4157                         dev_err(&pdev->dev,
4158                                 "Allocation for Rx Queue %u failed\n", i);
4159                         for (i--; i >= 0; i--)
4160                                 igb_free_rx_resources(adapter->rx_ring[i]);
4161                         break;
4162                 }
4163         }
4164
4165         return err;
4166 }
4167
4168 /**
4169  *  igb_setup_mrqc - configure the multiple receive queue control registers
4170  *  @adapter: Board private structure
4171  **/
4172 static void igb_setup_mrqc(struct igb_adapter *adapter)
4173 {
4174         struct e1000_hw *hw = &adapter->hw;
4175         u32 mrqc, rxcsum;
4176         u32 j, num_rx_queues;
4177         u32 rss_key[10];
4178
4179         netdev_rss_key_fill(rss_key, sizeof(rss_key));
4180         for (j = 0; j < 10; j++)
4181                 wr32(E1000_RSSRK(j), rss_key[j]);
4182
4183         num_rx_queues = adapter->rss_queues;
4184
4185         switch (hw->mac.type) {
4186         case e1000_82576:
4187                 /* 82576 supports 2 RSS queues for SR-IOV */
4188                 if (adapter->vfs_allocated_count)
4189                         num_rx_queues = 2;
4190                 break;
4191         default:
4192                 break;
4193         }
4194
4195         if (adapter->rss_indir_tbl_init != num_rx_queues) {
4196                 for (j = 0; j < IGB_RETA_SIZE; j++)
4197                         adapter->rss_indir_tbl[j] =
4198                         (j * num_rx_queues) / IGB_RETA_SIZE;
4199                 adapter->rss_indir_tbl_init = num_rx_queues;
4200         }
4201         igb_write_rss_indir_tbl(adapter);
4202
4203         /* Disable raw packet checksumming so that RSS hash is placed in
4204          * descriptor on writeback.  No need to enable TCP/UDP/IP checksum
4205          * offloads as they are enabled by default
4206          */
4207         rxcsum = rd32(E1000_RXCSUM);
4208         rxcsum |= E1000_RXCSUM_PCSD;
4209
4210         if (adapter->hw.mac.type >= e1000_82576)
4211                 /* Enable Receive Checksum Offload for SCTP */
4212                 rxcsum |= E1000_RXCSUM_CRCOFL;
4213
4214         /* Don't need to set TUOFL or IPOFL, they default to 1 */
4215         wr32(E1000_RXCSUM, rxcsum);
4216
4217         /* Generate RSS hash based on packet types, TCP/UDP
4218          * port numbers and/or IPv4/v6 src and dst addresses
4219          */
4220         mrqc = E1000_MRQC_RSS_FIELD_IPV4 |
4221                E1000_MRQC_RSS_FIELD_IPV4_TCP |
4222                E1000_MRQC_RSS_FIELD_IPV6 |
4223                E1000_MRQC_RSS_FIELD_IPV6_TCP |
4224                E1000_MRQC_RSS_FIELD_IPV6_TCP_EX;
4225
4226         if (adapter->flags & IGB_FLAG_RSS_FIELD_IPV4_UDP)
4227                 mrqc |= E1000_MRQC_RSS_FIELD_IPV4_UDP;
4228         if (adapter->flags & IGB_FLAG_RSS_FIELD_IPV6_UDP)
4229                 mrqc |= E1000_MRQC_RSS_FIELD_IPV6_UDP;
4230
4231         /* If VMDq is enabled then we set the appropriate mode for that, else
4232          * we default to RSS so that an RSS hash is calculated per packet even
4233          * if we are only using one queue
4234          */
4235         if (adapter->vfs_allocated_count) {
4236                 if (hw->mac.type > e1000_82575) {
4237                         /* Set the default pool for the PF's first queue */
4238                         u32 vtctl = rd32(E1000_VT_CTL);
4239
4240                         vtctl &= ~(E1000_VT_CTL_DEFAULT_POOL_MASK |
4241                                    E1000_VT_CTL_DISABLE_DEF_POOL);
4242                         vtctl |= adapter->vfs_allocated_count <<
4243                                 E1000_VT_CTL_DEFAULT_POOL_SHIFT;
4244                         wr32(E1000_VT_CTL, vtctl);
4245                 }
4246                 if (adapter->rss_queues > 1)
4247                         mrqc |= E1000_MRQC_ENABLE_VMDQ_RSS_MQ;
4248                 else
4249                         mrqc |= E1000_MRQC_ENABLE_VMDQ;
4250         } else {
4251                 if (hw->mac.type != e1000_i211)
4252                         mrqc |= E1000_MRQC_ENABLE_RSS_MQ;
4253         }
4254         igb_vmm_control(adapter);
4255
4256         wr32(E1000_MRQC, mrqc);
4257 }
4258
4259 /**
4260  *  igb_setup_rctl - configure the receive control registers
4261  *  @adapter: Board private structure
4262  **/
4263 void igb_setup_rctl(struct igb_adapter *adapter)
4264 {
4265         struct e1000_hw *hw = &adapter->hw;
4266         u32 rctl;
4267
4268         rctl = rd32(E1000_RCTL);
4269
4270         rctl &= ~(3 << E1000_RCTL_MO_SHIFT);
4271         rctl &= ~(E1000_RCTL_LBM_TCVR | E1000_RCTL_LBM_MAC);
4272
4273         rctl |= E1000_RCTL_EN | E1000_RCTL_BAM | E1000_RCTL_RDMTS_HALF |
4274                 (hw->mac.mc_filter_type << E1000_RCTL_MO_SHIFT);
4275
4276         /* enable stripping of CRC. It's unlikely this will break BMC
4277          * redirection as it did with e1000. Newer features require
4278          * that the HW strips the CRC.
4279          */
4280         rctl |= E1000_RCTL_SECRC;
4281
4282         /* disable store bad packets and clear size bits. */
4283         rctl &= ~(E1000_RCTL_SBP | E1000_RCTL_SZ_256);
4284
4285         /* enable LPE to allow for reception of jumbo frames */
4286         rctl |= E1000_RCTL_LPE;
4287
4288         /* disable queue 0 to prevent tail write w/o re-config */
4289         wr32(E1000_RXDCTL(0), 0);
4290
4291         /* Attention!!!  For SR-IOV PF driver operations you must enable
4292          * queue drop for all VF and PF queues to prevent head of line blocking
4293          * if an un-trusted VF does not provide descriptors to hardware.
4294          */
4295         if (adapter->vfs_allocated_count) {
4296                 /* set all queue drop enable bits */
4297                 wr32(E1000_QDE, ALL_QUEUES);
4298         }
4299
4300         /* This is useful for sniffing bad packets. */
4301         if (adapter->netdev->features & NETIF_F_RXALL) {
4302                 /* UPE and MPE will be handled by normal PROMISC logic
4303                  * in e1000e_set_rx_mode
4304                  */
4305                 rctl |= (E1000_RCTL_SBP | /* Receive bad packets */
4306                          E1000_RCTL_BAM | /* RX All Bcast Pkts */
4307                          E1000_RCTL_PMCF); /* RX All MAC Ctrl Pkts */
4308
4309                 rctl &= ~(E1000_RCTL_DPF | /* Allow filtered pause */
4310                           E1000_RCTL_CFIEN); /* Dis VLAN CFIEN Filter */
4311                 /* Do not mess with E1000_CTRL_VME, it affects transmit as well,
4312                  * and that breaks VLANs.
4313                  */
4314         }
4315
4316         wr32(E1000_RCTL, rctl);
4317 }
4318
4319 static inline int igb_set_vf_rlpml(struct igb_adapter *adapter, int size,
4320                                    int vfn)
4321 {
4322         struct e1000_hw *hw = &adapter->hw;
4323         u32 vmolr;
4324
4325         if (size > MAX_JUMBO_FRAME_SIZE)
4326                 size = MAX_JUMBO_FRAME_SIZE;
4327
4328         vmolr = rd32(E1000_VMOLR(vfn));
4329         vmolr &= ~E1000_VMOLR_RLPML_MASK;
4330         vmolr |= size | E1000_VMOLR_LPE;
4331         wr32(E1000_VMOLR(vfn), vmolr);
4332
4333         return 0;
4334 }
4335
4336 static inline void igb_set_vf_vlan_strip(struct igb_adapter *adapter,
4337                                          int vfn, bool enable)
4338 {
4339         struct e1000_hw *hw = &adapter->hw;
4340         u32 val, reg;
4341
4342         if (hw->mac.type < e1000_82576)
4343                 return;
4344
4345         if (hw->mac.type == e1000_i350)
4346                 reg = E1000_DVMOLR(vfn);
4347         else
4348                 reg = E1000_VMOLR(vfn);
4349
4350         val = rd32(reg);
4351         if (enable)
4352                 val |= E1000_VMOLR_STRVLAN;
4353         else
4354                 val &= ~(E1000_VMOLR_STRVLAN);
4355         wr32(reg, val);
4356 }
4357
4358 static inline void igb_set_vmolr(struct igb_adapter *adapter,
4359                                  int vfn, bool aupe)
4360 {
4361         struct e1000_hw *hw = &adapter->hw;
4362         u32 vmolr;
4363
4364         /* This register exists only on 82576 and newer so if we are older then
4365          * we should exit and do nothing
4366          */
4367         if (hw->mac.type < e1000_82576)
4368                 return;
4369
4370         vmolr = rd32(E1000_VMOLR(vfn));
4371         if (aupe)
4372                 vmolr |= E1000_VMOLR_AUPE; /* Accept untagged packets */
4373         else
4374                 vmolr &= ~(E1000_VMOLR_AUPE); /* Tagged packets ONLY */
4375
4376         /* clear all bits that might not be set */
4377         vmolr &= ~(E1000_VMOLR_BAM | E1000_VMOLR_RSSE);
4378
4379         if (adapter->rss_queues > 1 && vfn == adapter->vfs_allocated_count)
4380                 vmolr |= E1000_VMOLR_RSSE; /* enable RSS */
4381         /* for VMDq only allow the VFs and pool 0 to accept broadcast and
4382          * multicast packets
4383          */
4384         if (vfn <= adapter->vfs_allocated_count)
4385                 vmolr |= E1000_VMOLR_BAM; /* Accept broadcast */
4386
4387         wr32(E1000_VMOLR(vfn), vmolr);
4388 }
4389
4390 /**
4391  *  igb_configure_rx_ring - Configure a receive ring after Reset
4392  *  @adapter: board private structure
4393  *  @ring: receive ring to be configured
4394  *
4395  *  Configure the Rx unit of the MAC after a reset.
4396  **/
4397 void igb_configure_rx_ring(struct igb_adapter *adapter,
4398                            struct igb_ring *ring)
4399 {
4400         struct e1000_hw *hw = &adapter->hw;
4401         union e1000_adv_rx_desc *rx_desc;
4402         u64 rdba = ring->dma;
4403         int reg_idx = ring->reg_idx;
4404         u32 srrctl = 0, rxdctl = 0;
4405
4406         /* disable the queue */
4407         wr32(E1000_RXDCTL(reg_idx), 0);
4408
4409         /* Set DMA base address registers */
4410         wr32(E1000_RDBAL(reg_idx),
4411              rdba & 0x00000000ffffffffULL);
4412         wr32(E1000_RDBAH(reg_idx), rdba >> 32);
4413         wr32(E1000_RDLEN(reg_idx),
4414              ring->count * sizeof(union e1000_adv_rx_desc));
4415
4416         /* initialize head and tail */
4417         ring->tail = adapter->io_addr + E1000_RDT(reg_idx);
4418         wr32(E1000_RDH(reg_idx), 0);
4419         writel(0, ring->tail);
4420
4421         /* set descriptor configuration */
4422         srrctl = IGB_RX_HDR_LEN << E1000_SRRCTL_BSIZEHDRSIZE_SHIFT;
4423         if (ring_uses_large_buffer(ring))
4424                 srrctl |= IGB_RXBUFFER_3072 >> E1000_SRRCTL_BSIZEPKT_SHIFT;
4425         else
4426                 srrctl |= IGB_RXBUFFER_2048 >> E1000_SRRCTL_BSIZEPKT_SHIFT;
4427         srrctl |= E1000_SRRCTL_DESCTYPE_ADV_ONEBUF;
4428         if (hw->mac.type >= e1000_82580)
4429                 srrctl |= E1000_SRRCTL_TIMESTAMP;
4430         /* Only set Drop Enable if we are supporting multiple queues */
4431         if (adapter->vfs_allocated_count || adapter->num_rx_queues > 1)
4432                 srrctl |= E1000_SRRCTL_DROP_EN;
4433
4434         wr32(E1000_SRRCTL(reg_idx), srrctl);
4435
4436         /* set filtering for VMDQ pools */
4437         igb_set_vmolr(adapter, reg_idx & 0x7, true);
4438
4439         rxdctl |= IGB_RX_PTHRESH;
4440         rxdctl |= IGB_RX_HTHRESH << 8;
4441         rxdctl |= IGB_RX_WTHRESH << 16;
4442
4443         /* initialize rx_buffer_info */
4444         memset(ring->rx_buffer_info, 0,
4445                sizeof(struct igb_rx_buffer) * ring->count);
4446
4447         /* initialize Rx descriptor 0 */
4448         rx_desc = IGB_RX_DESC(ring, 0);
4449         rx_desc->wb.upper.length = 0;
4450
4451         /* enable receive descriptor fetching */
4452         rxdctl |= E1000_RXDCTL_QUEUE_ENABLE;
4453         wr32(E1000_RXDCTL(reg_idx), rxdctl);
4454 }
4455
4456 static void igb_set_rx_buffer_len(struct igb_adapter *adapter,
4457                                   struct igb_ring *rx_ring)
4458 {
4459         /* set build_skb and buffer size flags */
4460         clear_ring_build_skb_enabled(rx_ring);
4461         clear_ring_uses_large_buffer(rx_ring);
4462
4463         if (adapter->flags & IGB_FLAG_RX_LEGACY)
4464                 return;
4465
4466         set_ring_build_skb_enabled(rx_ring);
4467
4468 #if (PAGE_SIZE < 8192)
4469         if (adapter->max_frame_size <= IGB_MAX_FRAME_BUILD_SKB)
4470                 return;
4471
4472         set_ring_uses_large_buffer(rx_ring);
4473 #endif
4474 }
4475
4476 /**
4477  *  igb_configure_rx - Configure receive Unit after Reset
4478  *  @adapter: board private structure
4479  *
4480  *  Configure the Rx unit of the MAC after a reset.
4481  **/
4482 static void igb_configure_rx(struct igb_adapter *adapter)
4483 {
4484         int i;
4485
4486         /* set the correct pool for the PF default MAC address in entry 0 */
4487         igb_set_default_mac_filter(adapter);
4488
4489         /* Setup the HW Rx Head and Tail Descriptor Pointers and
4490          * the Base and Length of the Rx Descriptor Ring
4491          */
4492         for (i = 0; i < adapter->num_rx_queues; i++) {
4493                 struct igb_ring *rx_ring = adapter->rx_ring[i];
4494
4495                 igb_set_rx_buffer_len(adapter, rx_ring);
4496                 igb_configure_rx_ring(adapter, rx_ring);
4497         }
4498 }
4499
4500 /**
4501  *  igb_free_tx_resources - Free Tx Resources per Queue
4502  *  @tx_ring: Tx descriptor ring for a specific queue
4503  *
4504  *  Free all transmit software resources
4505  **/
4506 void igb_free_tx_resources(struct igb_ring *tx_ring)
4507 {
4508         igb_clean_tx_ring(tx_ring);
4509
4510         vfree(tx_ring->tx_buffer_info);
4511         tx_ring->tx_buffer_info = NULL;
4512
4513         /* if not set, then don't free */
4514         if (!tx_ring->desc)
4515                 return;
4516
4517         dma_free_coherent(tx_ring->dev, tx_ring->size,
4518                           tx_ring->desc, tx_ring->dma);
4519
4520         tx_ring->desc = NULL;
4521 }
4522
4523 /**
4524  *  igb_free_all_tx_resources - Free Tx Resources for All Queues
4525  *  @adapter: board private structure
4526  *
4527  *  Free all transmit software resources
4528  **/
4529 static void igb_free_all_tx_resources(struct igb_adapter *adapter)
4530 {
4531         int i;
4532
4533         for (i = 0; i < adapter->num_tx_queues; i++)
4534                 if (adapter->tx_ring[i])
4535                         igb_free_tx_resources(adapter->tx_ring[i]);
4536 }
4537
4538 /**
4539  *  igb_clean_tx_ring - Free Tx Buffers
4540  *  @tx_ring: ring to be cleaned
4541  **/
4542 static void igb_clean_tx_ring(struct igb_ring *tx_ring)
4543 {
4544         u16 i = tx_ring->next_to_clean;
4545         struct igb_tx_buffer *tx_buffer = &tx_ring->tx_buffer_info[i];
4546
4547         while (i != tx_ring->next_to_use) {
4548                 union e1000_adv_tx_desc *eop_desc, *tx_desc;
4549
4550                 /* Free all the Tx ring sk_buffs */
4551                 dev_kfree_skb_any(tx_buffer->skb);
4552
4553                 /* unmap skb header data */
4554                 dma_unmap_single(tx_ring->dev,
4555                                  dma_unmap_addr(tx_buffer, dma),
4556                                  dma_unmap_len(tx_buffer, len),
4557                                  DMA_TO_DEVICE);
4558
4559                 /* check for eop_desc to determine the end of the packet */
4560                 eop_desc = tx_buffer->next_to_watch;
4561                 tx_desc = IGB_TX_DESC(tx_ring, i);
4562
4563                 /* unmap remaining buffers */
4564                 while (tx_desc != eop_desc) {
4565                         tx_buffer++;
4566                         tx_desc++;
4567                         i++;
4568                         if (unlikely(i == tx_ring->count)) {
4569                                 i = 0;
4570                                 tx_buffer = tx_ring->tx_buffer_info;
4571                                 tx_desc = IGB_TX_DESC(tx_ring, 0);
4572                         }
4573
4574                         /* unmap any remaining paged data */
4575                         if (dma_unmap_len(tx_buffer, len))
4576                                 dma_unmap_page(tx_ring->dev,
4577                                                dma_unmap_addr(tx_buffer, dma),
4578                                                dma_unmap_len(tx_buffer, len),
4579                                                DMA_TO_DEVICE);
4580                 }
4581
4582                 /* move us one more past the eop_desc for start of next pkt */
4583                 tx_buffer++;
4584                 i++;
4585                 if (unlikely(i == tx_ring->count)) {
4586                         i = 0;
4587                         tx_buffer = tx_ring->tx_buffer_info;
4588                 }
4589         }
4590
4591         /* reset BQL for queue */
4592         netdev_tx_reset_queue(txring_txq(tx_ring));
4593
4594         /* reset next_to_use and next_to_clean */
4595         tx_ring->next_to_use = 0;
4596         tx_ring->next_to_clean = 0;
4597 }
4598
4599 /**
4600  *  igb_clean_all_tx_rings - Free Tx Buffers for all queues
4601  *  @adapter: board private structure
4602  **/
4603 static void igb_clean_all_tx_rings(struct igb_adapter *adapter)
4604 {
4605         int i;
4606
4607         for (i = 0; i < adapter->num_tx_queues; i++)
4608                 if (adapter->tx_ring[i])
4609                         igb_clean_tx_ring(adapter->tx_ring[i]);
4610 }
4611
4612 /**
4613  *  igb_free_rx_resources - Free Rx Resources
4614  *  @rx_ring: ring to clean the resources from
4615  *
4616  *  Free all receive software resources
4617  **/
4618 void igb_free_rx_resources(struct igb_ring *rx_ring)
4619 {
4620         igb_clean_rx_ring(rx_ring);
4621
4622         vfree(rx_ring->rx_buffer_info);
4623         rx_ring->rx_buffer_info = NULL;
4624
4625         /* if not set, then don't free */
4626         if (!rx_ring->desc)
4627                 return;
4628
4629         dma_free_coherent(rx_ring->dev, rx_ring->size,
4630                           rx_ring->desc, rx_ring->dma);
4631
4632         rx_ring->desc = NULL;
4633 }
4634
4635 /**
4636  *  igb_free_all_rx_resources - Free Rx Resources for All Queues
4637  *  @adapter: board private structure
4638  *
4639  *  Free all receive software resources
4640  **/
4641 static void igb_free_all_rx_resources(struct igb_adapter *adapter)
4642 {
4643         int i;
4644
4645         for (i = 0; i < adapter->num_rx_queues; i++)
4646                 if (adapter->rx_ring[i])
4647                         igb_free_rx_resources(adapter->rx_ring[i]);
4648 }
4649
4650 /**
4651  *  igb_clean_rx_ring - Free Rx Buffers per Queue
4652  *  @rx_ring: ring to free buffers from
4653  **/
4654 static void igb_clean_rx_ring(struct igb_ring *rx_ring)
4655 {
4656         u16 i = rx_ring->next_to_clean;
4657
4658         if (rx_ring->skb)
4659                 dev_kfree_skb(rx_ring->skb);
4660         rx_ring->skb = NULL;
4661
4662         /* Free all the Rx ring sk_buffs */
4663         while (i != rx_ring->next_to_alloc) {
4664                 struct igb_rx_buffer *buffer_info = &rx_ring->rx_buffer_info[i];
4665
4666                 /* Invalidate cache lines that may have been written to by
4667                  * device so that we avoid corrupting memory.
4668                  */
4669                 dma_sync_single_range_for_cpu(rx_ring->dev,
4670                                               buffer_info->dma,
4671                                               buffer_info->page_offset,
4672                                               igb_rx_bufsz(rx_ring),
4673                                               DMA_FROM_DEVICE);
4674
4675                 /* free resources associated with mapping */
4676                 dma_unmap_page_attrs(rx_ring->dev,
4677                                      buffer_info->dma,
4678                                      igb_rx_pg_size(rx_ring),
4679                                      DMA_FROM_DEVICE,
4680                                      IGB_RX_DMA_ATTR);
4681                 __page_frag_cache_drain(buffer_info->page,
4682                                         buffer_info->pagecnt_bias);
4683
4684                 i++;
4685                 if (i == rx_ring->count)
4686                         i = 0;
4687         }
4688
4689         rx_ring->next_to_alloc = 0;
4690         rx_ring->next_to_clean = 0;
4691         rx_ring->next_to_use = 0;
4692 }
4693
4694 /**
4695  *  igb_clean_all_rx_rings - Free Rx Buffers for all queues
4696  *  @adapter: board private structure
4697  **/
4698 static void igb_clean_all_rx_rings(struct igb_adapter *adapter)
4699 {
4700         int i;
4701
4702         for (i = 0; i < adapter->num_rx_queues; i++)
4703                 if (adapter->rx_ring[i])
4704                         igb_clean_rx_ring(adapter->rx_ring[i]);
4705 }
4706
4707 /**
4708  *  igb_set_mac - Change the Ethernet Address of the NIC
4709  *  @netdev: network interface device structure
4710  *  @p: pointer to an address structure
4711  *
4712  *  Returns 0 on success, negative on failure
4713  **/
4714 static int igb_set_mac(struct net_device *netdev, void *p)
4715 {
4716         struct igb_adapter *adapter = netdev_priv(netdev);
4717         struct e1000_hw *hw = &adapter->hw;
4718         struct sockaddr *addr = p;
4719
4720         if (!is_valid_ether_addr(addr->sa_data))
4721                 return -EADDRNOTAVAIL;
4722
4723         memcpy(netdev->dev_addr, addr->sa_data, netdev->addr_len);
4724         memcpy(hw->mac.addr, addr->sa_data, netdev->addr_len);
4725
4726         /* set the correct pool for the new PF MAC address in entry 0 */
4727         igb_set_default_mac_filter(adapter);
4728
4729         return 0;
4730 }
4731
4732 /**
4733  *  igb_write_mc_addr_list - write multicast addresses to MTA
4734  *  @netdev: network interface device structure
4735  *
4736  *  Writes multicast address list to the MTA hash table.
4737  *  Returns: -ENOMEM on failure
4738  *           0 on no addresses written
4739  *           X on writing X addresses to MTA
4740  **/
4741 static int igb_write_mc_addr_list(struct net_device *netdev)
4742 {
4743         struct igb_adapter *adapter = netdev_priv(netdev);
4744         struct e1000_hw *hw = &adapter->hw;
4745         struct netdev_hw_addr *ha;
4746         u8  *mta_list;
4747         int i;
4748
4749         if (netdev_mc_empty(netdev)) {
4750                 /* nothing to program, so clear mc list */
4751                 igb_update_mc_addr_list(hw, NULL, 0);
4752                 igb_restore_vf_multicasts(adapter);
4753                 return 0;
4754         }
4755
4756         mta_list = kcalloc(netdev_mc_count(netdev), 6, GFP_ATOMIC);
4757         if (!mta_list)
4758                 return -ENOMEM;
4759
4760         /* The shared function expects a packed array of only addresses. */
4761         i = 0;
4762         netdev_for_each_mc_addr(ha, netdev)
4763                 memcpy(mta_list + (i++ * ETH_ALEN), ha->addr, ETH_ALEN);
4764
4765         igb_update_mc_addr_list(hw, mta_list, i);
4766         kfree(mta_list);
4767
4768         return netdev_mc_count(netdev);
4769 }
4770
4771 static int igb_vlan_promisc_enable(struct igb_adapter *adapter)
4772 {
4773         struct e1000_hw *hw = &adapter->hw;
4774         u32 i, pf_id;
4775
4776         switch (hw->mac.type) {
4777         case e1000_i210:
4778         case e1000_i211:
4779         case e1000_i350:
4780                 /* VLAN filtering needed for VLAN prio filter */
4781                 if (adapter->netdev->features & NETIF_F_NTUPLE)
4782                         break;
4783                 /* fall through */
4784         case e1000_82576:
4785         case e1000_82580:
4786         case e1000_i354:
4787                 /* VLAN filtering needed for pool filtering */
4788                 if (adapter->vfs_allocated_count)
4789                         break;
4790                 /* fall through */
4791         default:
4792                 return 1;
4793         }
4794
4795         /* We are already in VLAN promisc, nothing to do */
4796         if (adapter->flags & IGB_FLAG_VLAN_PROMISC)
4797                 return 0;
4798
4799         if (!adapter->vfs_allocated_count)
4800                 goto set_vfta;
4801
4802         /* Add PF to all active pools */
4803         pf_id = adapter->vfs_allocated_count + E1000_VLVF_POOLSEL_SHIFT;
4804
4805         for (i = E1000_VLVF_ARRAY_SIZE; --i;) {
4806                 u32 vlvf = rd32(E1000_VLVF(i));
4807
4808                 vlvf |= BIT(pf_id);
4809                 wr32(E1000_VLVF(i), vlvf);
4810         }
4811
4812 set_vfta:
4813         /* Set all bits in the VLAN filter table array */
4814         for (i = E1000_VLAN_FILTER_TBL_SIZE; i--;)
4815                 hw->mac.ops.write_vfta(hw, i, ~0U);
4816
4817         /* Set flag so we don't redo unnecessary work */
4818         adapter->flags |= IGB_FLAG_VLAN_PROMISC;
4819
4820         return 0;
4821 }
4822
4823 #define VFTA_BLOCK_SIZE 8
4824 static void igb_scrub_vfta(struct igb_adapter *adapter, u32 vfta_offset)
4825 {
4826         struct e1000_hw *hw = &adapter->hw;
4827         u32 vfta[VFTA_BLOCK_SIZE] = { 0 };
4828         u32 vid_start = vfta_offset * 32;
4829         u32 vid_end = vid_start + (VFTA_BLOCK_SIZE * 32);
4830         u32 i, vid, word, bits, pf_id;
4831
4832         /* guarantee that we don't scrub out management VLAN */
4833         vid = adapter->mng_vlan_id;
4834         if (vid >= vid_start && vid < vid_end)
4835                 vfta[(vid - vid_start) / 32] |= BIT(vid % 32);
4836
4837         if (!adapter->vfs_allocated_count)
4838                 goto set_vfta;
4839
4840         pf_id = adapter->vfs_allocated_count + E1000_VLVF_POOLSEL_SHIFT;
4841
4842         for (i = E1000_VLVF_ARRAY_SIZE; --i;) {
4843                 u32 vlvf = rd32(E1000_VLVF(i));
4844
4845                 /* pull VLAN ID from VLVF */
4846                 vid = vlvf & VLAN_VID_MASK;
4847
4848                 /* only concern ourselves with a certain range */
4849                 if (vid < vid_start || vid >= vid_end)
4850                         continue;
4851
4852                 if (vlvf & E1000_VLVF_VLANID_ENABLE) {
4853                         /* record VLAN ID in VFTA */
4854                         vfta[(vid - vid_start) / 32] |= BIT(vid % 32);
4855
4856                         /* if PF is part of this then continue */
4857                         if (test_bit(vid, adapter->active_vlans))
4858                                 continue;
4859                 }
4860
4861                 /* remove PF from the pool */
4862                 bits = ~BIT(pf_id);
4863                 bits &= rd32(E1000_VLVF(i));
4864                 wr32(E1000_VLVF(i), bits);
4865         }
4866
4867 set_vfta:
4868         /* extract values from active_vlans and write back to VFTA */
4869         for (i = VFTA_BLOCK_SIZE; i--;) {
4870                 vid = (vfta_offset + i) * 32;
4871                 word = vid / BITS_PER_LONG;
4872                 bits = vid % BITS_PER_LONG;
4873
4874                 vfta[i] |= adapter->active_vlans[word] >> bits;
4875
4876                 hw->mac.ops.write_vfta(hw, vfta_offset + i, vfta[i]);
4877         }
4878 }
4879
4880 static void igb_vlan_promisc_disable(struct igb_adapter *adapter)
4881 {
4882         u32 i;
4883
4884         /* We are not in VLAN promisc, nothing to do */
4885         if (!(adapter->flags & IGB_FLAG_VLAN_PROMISC))
4886                 return;
4887
4888         /* Set flag so we don't redo unnecessary work */
4889         adapter->flags &= ~IGB_FLAG_VLAN_PROMISC;
4890
4891         for (i = 0; i < E1000_VLAN_FILTER_TBL_SIZE; i += VFTA_BLOCK_SIZE)
4892                 igb_scrub_vfta(adapter, i);
4893 }
4894
4895 /**
4896  *  igb_set_rx_mode - Secondary Unicast, Multicast and Promiscuous mode set
4897  *  @netdev: network interface device structure
4898  *
4899  *  The set_rx_mode entry point is called whenever the unicast or multicast
4900  *  address lists or the network interface flags are updated.  This routine is
4901  *  responsible for configuring the hardware for proper unicast, multicast,
4902  *  promiscuous mode, and all-multi behavior.
4903  **/
4904 static void igb_set_rx_mode(struct net_device *netdev)
4905 {
4906         struct igb_adapter *adapter = netdev_priv(netdev);
4907         struct e1000_hw *hw = &adapter->hw;
4908         unsigned int vfn = adapter->vfs_allocated_count;
4909         u32 rctl = 0, vmolr = 0, rlpml = MAX_JUMBO_FRAME_SIZE;
4910         int count;
4911
4912         /* Check for Promiscuous and All Multicast modes */
4913         if (netdev->flags & IFF_PROMISC) {
4914                 rctl |= E1000_RCTL_UPE | E1000_RCTL_MPE;
4915                 vmolr |= E1000_VMOLR_MPME;
4916
4917                 /* enable use of UTA filter to force packets to default pool */
4918                 if (hw->mac.type == e1000_82576)
4919                         vmolr |= E1000_VMOLR_ROPE;
4920         } else {
4921                 if (netdev->flags & IFF_ALLMULTI) {
4922                         rctl |= E1000_RCTL_MPE;
4923                         vmolr |= E1000_VMOLR_MPME;
4924                 } else {
4925                         /* Write addresses to the MTA, if the attempt fails
4926                          * then we should just turn on promiscuous mode so
4927                          * that we can at least receive multicast traffic
4928                          */
4929                         count = igb_write_mc_addr_list(netdev);
4930                         if (count < 0) {
4931                                 rctl |= E1000_RCTL_MPE;
4932                                 vmolr |= E1000_VMOLR_MPME;
4933                         } else if (count) {
4934                                 vmolr |= E1000_VMOLR_ROMPE;
4935                         }
4936                 }
4937         }
4938
4939         /* Write addresses to available RAR registers, if there is not
4940          * sufficient space to store all the addresses then enable
4941          * unicast promiscuous mode
4942          */
4943         if (__dev_uc_sync(netdev, igb_uc_sync, igb_uc_unsync)) {
4944                 rctl |= E1000_RCTL_UPE;
4945                 vmolr |= E1000_VMOLR_ROPE;
4946         }
4947
4948         /* enable VLAN filtering by default */
4949         rctl |= E1000_RCTL_VFE;
4950
4951         /* disable VLAN filtering for modes that require it */
4952         if ((netdev->flags & IFF_PROMISC) ||
4953             (netdev->features & NETIF_F_RXALL)) {
4954                 /* if we fail to set all rules then just clear VFE */
4955                 if (igb_vlan_promisc_enable(adapter))
4956                         rctl &= ~E1000_RCTL_VFE;
4957         } else {
4958                 igb_vlan_promisc_disable(adapter);
4959         }
4960
4961         /* update state of unicast, multicast, and VLAN filtering modes */
4962         rctl |= rd32(E1000_RCTL) & ~(E1000_RCTL_UPE | E1000_RCTL_MPE |
4963                                      E1000_RCTL_VFE);
4964         wr32(E1000_RCTL, rctl);
4965
4966 #if (PAGE_SIZE < 8192)
4967         if (!adapter->vfs_allocated_count) {
4968                 if (adapter->max_frame_size <= IGB_MAX_FRAME_BUILD_SKB)
4969                         rlpml = IGB_MAX_FRAME_BUILD_SKB;
4970         }
4971 #endif
4972         wr32(E1000_RLPML, rlpml);
4973
4974         /* In order to support SR-IOV and eventually VMDq it is necessary to set
4975          * the VMOLR to enable the appropriate modes.  Without this workaround
4976          * we will have issues with VLAN tag stripping not being done for frames
4977          * that are only arriving because we are the default pool
4978          */
4979         if ((hw->mac.type < e1000_82576) || (hw->mac.type > e1000_i350))
4980                 return;
4981
4982         /* set UTA to appropriate mode */
4983         igb_set_uta(adapter, !!(vmolr & E1000_VMOLR_ROPE));
4984
4985         vmolr |= rd32(E1000_VMOLR(vfn)) &
4986                  ~(E1000_VMOLR_ROPE | E1000_VMOLR_MPME | E1000_VMOLR_ROMPE);
4987
4988         /* enable Rx jumbo frames, restrict as needed to support build_skb */
4989         vmolr &= ~E1000_VMOLR_RLPML_MASK;
4990 #if (PAGE_SIZE < 8192)
4991         if (adapter->max_frame_size <= IGB_MAX_FRAME_BUILD_SKB)
4992                 vmolr |= IGB_MAX_FRAME_BUILD_SKB;
4993         else
4994 #endif
4995                 vmolr |= MAX_JUMBO_FRAME_SIZE;
4996         vmolr |= E1000_VMOLR_LPE;
4997
4998         wr32(E1000_VMOLR(vfn), vmolr);
4999
5000         igb_restore_vf_multicasts(adapter);
5001 }
5002
5003 static void igb_check_wvbr(struct igb_adapter *adapter)
5004 {
5005         struct e1000_hw *hw = &adapter->hw;
5006         u32 wvbr = 0;
5007
5008         switch (hw->mac.type) {
5009         case e1000_82576:
5010         case e1000_i350:
5011                 wvbr = rd32(E1000_WVBR);
5012                 if (!wvbr)
5013                         return;
5014                 break;
5015         default:
5016                 break;
5017         }
5018
5019         adapter->wvbr |= wvbr;
5020 }
5021
5022 #define IGB_STAGGERED_QUEUE_OFFSET 8
5023
5024 static void igb_spoof_check(struct igb_adapter *adapter)
5025 {
5026         int j;
5027
5028         if (!adapter->wvbr)
5029                 return;
5030
5031         for (j = 0; j < adapter->vfs_allocated_count; j++) {
5032                 if (adapter->wvbr & BIT(j) ||
5033                     adapter->wvbr & BIT(j + IGB_STAGGERED_QUEUE_OFFSET)) {
5034                         dev_warn(&adapter->pdev->dev,
5035                                 "Spoof event(s) detected on VF %d\n", j);
5036                         adapter->wvbr &=
5037                                 ~(BIT(j) |
5038                                   BIT(j + IGB_STAGGERED_QUEUE_OFFSET));
5039                 }
5040         }
5041 }
5042
5043 /* Need to wait a few seconds after link up to get diagnostic information from
5044  * the phy
5045  */
5046 static void igb_update_phy_info(struct timer_list *t)
5047 {
5048         struct igb_adapter *adapter = from_timer(adapter, t, phy_info_timer);
5049         igb_get_phy_info(&adapter->hw);
5050 }
5051
5052 /**
5053  *  igb_has_link - check shared code for link and determine up/down
5054  *  @adapter: pointer to driver private info
5055  **/
5056 bool igb_has_link(struct igb_adapter *adapter)
5057 {
5058         struct e1000_hw *hw = &adapter->hw;
5059         bool link_active = false;
5060
5061         /* get_link_status is set on LSC (link status) interrupt or
5062          * rx sequence error interrupt.  get_link_status will stay
5063          * false until the e1000_check_for_link establishes link
5064          * for copper adapters ONLY
5065          */
5066         switch (hw->phy.media_type) {
5067         case e1000_media_type_copper:
5068                 if (!hw->mac.get_link_status)
5069                         return true;
5070         case e1000_media_type_internal_serdes:
5071                 hw->mac.ops.check_for_link(hw);
5072                 link_active = !hw->mac.get_link_status;
5073                 break;
5074         default:
5075         case e1000_media_type_unknown:
5076                 break;
5077         }
5078
5079         if (((hw->mac.type == e1000_i210) ||
5080              (hw->mac.type == e1000_i211)) &&
5081              (hw->phy.id == I210_I_PHY_ID)) {
5082                 if (!netif_carrier_ok(adapter->netdev)) {
5083                         adapter->flags &= ~IGB_FLAG_NEED_LINK_UPDATE;
5084                 } else if (!(adapter->flags & IGB_FLAG_NEED_LINK_UPDATE)) {
5085                         adapter->flags |= IGB_FLAG_NEED_LINK_UPDATE;
5086                         adapter->link_check_timeout = jiffies;
5087                 }
5088         }
5089
5090         return link_active;
5091 }
5092
5093 static bool igb_thermal_sensor_event(struct e1000_hw *hw, u32 event)
5094 {
5095         bool ret = false;
5096         u32 ctrl_ext, thstat;
5097
5098         /* check for thermal sensor event on i350 copper only */
5099         if (hw->mac.type == e1000_i350) {
5100                 thstat = rd32(E1000_THSTAT);
5101                 ctrl_ext = rd32(E1000_CTRL_EXT);
5102
5103                 if ((hw->phy.media_type == e1000_media_type_copper) &&
5104                     !(ctrl_ext & E1000_CTRL_EXT_LINK_MODE_SGMII))
5105                         ret = !!(thstat & event);
5106         }
5107
5108         return ret;
5109 }
5110
5111 /**
5112  *  igb_check_lvmmc - check for malformed packets received
5113  *  and indicated in LVMMC register
5114  *  @adapter: pointer to adapter
5115  **/
5116 static void igb_check_lvmmc(struct igb_adapter *adapter)
5117 {
5118         struct e1000_hw *hw = &adapter->hw;
5119         u32 lvmmc;
5120
5121         lvmmc = rd32(E1000_LVMMC);
5122         if (lvmmc) {
5123                 if (unlikely(net_ratelimit())) {
5124                         netdev_warn(adapter->netdev,
5125                                     "malformed Tx packet detected and dropped, LVMMC:0x%08x\n",
5126                                     lvmmc);
5127                 }
5128         }
5129 }
5130
5131 /**
5132  *  igb_watchdog - Timer Call-back
5133  *  @data: pointer to adapter cast into an unsigned long
5134  **/
5135 static void igb_watchdog(struct timer_list *t)
5136 {
5137         struct igb_adapter *adapter = from_timer(adapter, t, watchdog_timer);
5138         /* Do the rest outside of interrupt context */
5139         schedule_work(&adapter->watchdog_task);
5140 }
5141
5142 static void igb_watchdog_task(struct work_struct *work)
5143 {
5144         struct igb_adapter *adapter = container_of(work,
5145                                                    struct igb_adapter,
5146                                                    watchdog_task);
5147         struct e1000_hw *hw = &adapter->hw;
5148         struct e1000_phy_info *phy = &hw->phy;
5149         struct net_device *netdev = adapter->netdev;
5150         u32 link;
5151         int i;
5152         u32 connsw;
5153         u16 phy_data, retry_count = 20;
5154
5155         link = igb_has_link(adapter);
5156
5157         if (adapter->flags & IGB_FLAG_NEED_LINK_UPDATE) {
5158                 if (time_after(jiffies, (adapter->link_check_timeout + HZ)))
5159                         adapter->flags &= ~IGB_FLAG_NEED_LINK_UPDATE;
5160                 else
5161                         link = false;
5162         }
5163
5164         /* Force link down if we have fiber to swap to */
5165         if (adapter->flags & IGB_FLAG_MAS_ENABLE) {
5166                 if (hw->phy.media_type == e1000_media_type_copper) {
5167                         connsw = rd32(E1000_CONNSW);
5168                         if (!(connsw & E1000_CONNSW_AUTOSENSE_EN))
5169                                 link = 0;
5170                 }
5171         }
5172         if (link) {
5173                 /* Perform a reset if the media type changed. */
5174                 if (hw->dev_spec._82575.media_changed) {
5175                         hw->dev_spec._82575.media_changed = false;
5176                         adapter->flags |= IGB_FLAG_MEDIA_RESET;
5177                         igb_reset(adapter);
5178                 }
5179                 /* Cancel scheduled suspend requests. */
5180                 pm_runtime_resume(netdev->dev.parent);
5181
5182                 if (!netif_carrier_ok(netdev)) {
5183                         u32 ctrl;
5184
5185                         hw->mac.ops.get_speed_and_duplex(hw,
5186                                                          &adapter->link_speed,
5187                                                          &adapter->link_duplex);
5188
5189                         ctrl = rd32(E1000_CTRL);
5190                         /* Links status message must follow this format */
5191                         netdev_info(netdev,
5192                                "igb: %s NIC Link is Up %d Mbps %s Duplex, Flow Control: %s\n",
5193                                netdev->name,
5194                                adapter->link_speed,
5195                                adapter->link_duplex == FULL_DUPLEX ?
5196                                "Full" : "Half",
5197                                (ctrl & E1000_CTRL_TFCE) &&
5198                                (ctrl & E1000_CTRL_RFCE) ? "RX/TX" :
5199                                (ctrl & E1000_CTRL_RFCE) ?  "RX" :
5200                                (ctrl & E1000_CTRL_TFCE) ?  "TX" : "None");
5201
5202                         /* disable EEE if enabled */
5203                         if ((adapter->flags & IGB_FLAG_EEE) &&
5204                                 (adapter->link_duplex == HALF_DUPLEX)) {
5205                                 dev_info(&adapter->pdev->dev,
5206                                 "EEE Disabled: unsupported at half duplex. Re-enable using ethtool when at full duplex.\n");
5207                                 adapter->hw.dev_spec._82575.eee_disable = true;
5208                                 adapter->flags &= ~IGB_FLAG_EEE;
5209                         }
5210
5211                         /* check if SmartSpeed worked */
5212                         igb_check_downshift(hw);
5213                         if (phy->speed_downgraded)
5214                                 netdev_warn(netdev, "Link Speed was downgraded by SmartSpeed\n");
5215
5216                         /* check for thermal sensor event */
5217                         if (igb_thermal_sensor_event(hw,
5218                             E1000_THSTAT_LINK_THROTTLE))
5219                                 netdev_info(netdev, "The network adapter link speed was downshifted because it overheated\n");
5220
5221                         /* adjust timeout factor according to speed/duplex */
5222                         adapter->tx_timeout_factor = 1;
5223                         switch (adapter->link_speed) {
5224                         case SPEED_10:
5225                                 adapter->tx_timeout_factor = 14;
5226                                 break;
5227                         case SPEED_100:
5228                                 /* maybe add some timeout factor ? */
5229                                 break;
5230                         }
5231
5232                         if (adapter->link_speed != SPEED_1000)
5233                                 goto no_wait;
5234
5235                         /* wait for Remote receiver status OK */
5236 retry_read_status:
5237                         if (!igb_read_phy_reg(hw, PHY_1000T_STATUS,
5238                                               &phy_data)) {
5239                                 if (!(phy_data & SR_1000T_REMOTE_RX_STATUS) &&
5240                                     retry_count) {
5241                                         msleep(100);
5242                                         retry_count--;
5243                                         goto retry_read_status;
5244                                 } else if (!retry_count) {
5245                                         dev_err(&adapter->pdev->dev, "exceed max 2 second\n");
5246                                 }
5247                         } else {
5248                                 dev_err(&adapter->pdev->dev, "read 1000Base-T Status Reg\n");
5249                         }
5250 no_wait:
5251                         netif_carrier_on(netdev);
5252
5253                         igb_ping_all_vfs(adapter);
5254                         igb_check_vf_rate_limit(adapter);
5255
5256                         /* link state has changed, schedule phy info update */
5257                         if (!test_bit(__IGB_DOWN, &adapter->state))
5258                                 mod_timer(&adapter->phy_info_timer,
5259                                           round_jiffies(jiffies + 2 * HZ));
5260                 }
5261         } else {
5262                 if (netif_carrier_ok(netdev)) {
5263                         adapter->link_speed = 0;
5264                         adapter->link_duplex = 0;
5265
5266                         /* check for thermal sensor event */
5267                         if (igb_thermal_sensor_event(hw,
5268                             E1000_THSTAT_PWR_DOWN)) {
5269                                 netdev_err(netdev, "The network adapter was stopped because it overheated\n");
5270                         }
5271
5272                         /* Links status message must follow this format */
5273                         netdev_info(netdev, "igb: %s NIC Link is Down\n",
5274                                netdev->name);
5275                         netif_carrier_off(netdev);
5276
5277                         igb_ping_all_vfs(adapter);
5278
5279                         /* link state has changed, schedule phy info update */
5280                         if (!test_bit(__IGB_DOWN, &adapter->state))
5281                                 mod_timer(&adapter->phy_info_timer,
5282                                           round_jiffies(jiffies + 2 * HZ));
5283
5284                         /* link is down, time to check for alternate media */
5285                         if (adapter->flags & IGB_FLAG_MAS_ENABLE) {
5286                                 igb_check_swap_media(adapter);
5287                                 if (adapter->flags & IGB_FLAG_MEDIA_RESET) {
5288                                         schedule_work(&adapter->reset_task);
5289                                         /* return immediately */
5290                                         return;
5291                                 }
5292                         }
5293                         pm_schedule_suspend(netdev->dev.parent,
5294                                             MSEC_PER_SEC * 5);
5295
5296                 /* also check for alternate media here */
5297                 } else if (!netif_carrier_ok(netdev) &&
5298                            (adapter->flags & IGB_FLAG_MAS_ENABLE)) {
5299                         igb_check_swap_media(adapter);
5300                         if (adapter->flags & IGB_FLAG_MEDIA_RESET) {
5301                                 schedule_work(&adapter->reset_task);
5302                                 /* return immediately */
5303                                 return;
5304                         }
5305                 }
5306         }
5307
5308         spin_lock(&adapter->stats64_lock);
5309         igb_update_stats(adapter);
5310         spin_unlock(&adapter->stats64_lock);
5311
5312         for (i = 0; i < adapter->num_tx_queues; i++) {
5313                 struct igb_ring *tx_ring = adapter->tx_ring[i];
5314                 if (!netif_carrier_ok(netdev)) {
5315                         /* We've lost link, so the controller stops DMA,
5316                          * but we've got queued Tx work that's never going
5317                          * to get done, so reset controller to flush Tx.
5318                          * (Do the reset outside of interrupt context).
5319                          */
5320                         if (igb_desc_unused(tx_ring) + 1 < tx_ring->count) {
5321                                 adapter->tx_timeout_count++;
5322                                 schedule_work(&adapter->reset_task);
5323                                 /* return immediately since reset is imminent */
5324                                 return;
5325                         }
5326                 }
5327
5328                 /* Force detection of hung controller every watchdog period */
5329                 set_bit(IGB_RING_FLAG_TX_DETECT_HANG, &tx_ring->flags);
5330         }
5331
5332         /* Cause software interrupt to ensure Rx ring is cleaned */
5333         if (adapter->flags & IGB_FLAG_HAS_MSIX) {
5334                 u32 eics = 0;
5335
5336                 for (i = 0; i < adapter->num_q_vectors; i++)
5337                         eics |= adapter->q_vector[i]->eims_value;
5338                 wr32(E1000_EICS, eics);
5339         } else {
5340                 wr32(E1000_ICS, E1000_ICS_RXDMT0);
5341         }
5342
5343         igb_spoof_check(adapter);
5344         igb_ptp_rx_hang(adapter);
5345         igb_ptp_tx_hang(adapter);
5346
5347         /* Check LVMMC register on i350/i354 only */
5348         if ((adapter->hw.mac.type == e1000_i350) ||
5349             (adapter->hw.mac.type == e1000_i354))
5350                 igb_check_lvmmc(adapter);
5351
5352         /* Reset the timer */
5353         if (!test_bit(__IGB_DOWN, &adapter->state)) {
5354                 if (adapter->flags & IGB_FLAG_NEED_LINK_UPDATE)
5355                         mod_timer(&adapter->watchdog_timer,
5356                                   round_jiffies(jiffies +  HZ));
5357                 else
5358                         mod_timer(&adapter->watchdog_timer,
5359                                   round_jiffies(jiffies + 2 * HZ));
5360         }
5361 }
5362
5363 enum latency_range {
5364         lowest_latency = 0,
5365         low_latency = 1,
5366         bulk_latency = 2,
5367         latency_invalid = 255
5368 };
5369
5370 /**
5371  *  igb_update_ring_itr - update the dynamic ITR value based on packet size
5372  *  @q_vector: pointer to q_vector
5373  *
5374  *  Stores a new ITR value based on strictly on packet size.  This
5375  *  algorithm is less sophisticated than that used in igb_update_itr,
5376  *  due to the difficulty of synchronizing statistics across multiple
5377  *  receive rings.  The divisors and thresholds used by this function
5378  *  were determined based on theoretical maximum wire speed and testing
5379  *  data, in order to minimize response time while increasing bulk
5380  *  throughput.
5381  *  This functionality is controlled by ethtool's coalescing settings.
5382  *  NOTE:  This function is called only when operating in a multiqueue
5383  *         receive environment.
5384  **/
5385 static void igb_update_ring_itr(struct igb_q_vector *q_vector)
5386 {
5387         int new_val = q_vector->itr_val;
5388         int avg_wire_size = 0;
5389         struct igb_adapter *adapter = q_vector->adapter;
5390         unsigned int packets;
5391
5392         /* For non-gigabit speeds, just fix the interrupt rate at 4000
5393          * ints/sec - ITR timer value of 120 ticks.
5394          */
5395         if (adapter->link_speed != SPEED_1000) {
5396                 new_val = IGB_4K_ITR;
5397                 goto set_itr_val;
5398         }
5399
5400         packets = q_vector->rx.total_packets;
5401         if (packets)
5402                 avg_wire_size = q_vector->rx.total_bytes / packets;
5403
5404         packets = q_vector->tx.total_packets;
5405         if (packets)
5406                 avg_wire_size = max_t(u32, avg_wire_size,
5407                                       q_vector->tx.total_bytes / packets);
5408
5409         /* if avg_wire_size isn't set no work was done */
5410         if (!avg_wire_size)
5411                 goto clear_counts;
5412
5413         /* Add 24 bytes to size to account for CRC, preamble, and gap */
5414         avg_wire_size += 24;
5415
5416         /* Don't starve jumbo frames */
5417         avg_wire_size = min(avg_wire_size, 3000);
5418
5419         /* Give a little boost to mid-size frames */
5420         if ((avg_wire_size > 300) && (avg_wire_size < 1200))
5421                 new_val = avg_wire_size / 3;
5422         else
5423                 new_val = avg_wire_size / 2;
5424
5425         /* conservative mode (itr 3) eliminates the lowest_latency setting */
5426         if (new_val < IGB_20K_ITR &&
5427             ((q_vector->rx.ring && adapter->rx_itr_setting == 3) ||
5428              (!q_vector->rx.ring && adapter->tx_itr_setting == 3)))
5429                 new_val = IGB_20K_ITR;
5430
5431 set_itr_val:
5432         if (new_val != q_vector->itr_val) {
5433                 q_vector->itr_val = new_val;
5434                 q_vector->set_itr = 1;
5435         }
5436 clear_counts:
5437         q_vector->rx.total_bytes = 0;
5438         q_vector->rx.total_packets = 0;
5439         q_vector->tx.total_bytes = 0;
5440         q_vector->tx.total_packets = 0;
5441 }
5442
5443 /**
5444  *  igb_update_itr - update the dynamic ITR value based on statistics
5445  *  @q_vector: pointer to q_vector
5446  *  @ring_container: ring info to update the itr for
5447  *
5448  *  Stores a new ITR value based on packets and byte
5449  *  counts during the last interrupt.  The advantage of per interrupt
5450  *  computation is faster updates and more accurate ITR for the current
5451  *  traffic pattern.  Constants in this function were computed
5452  *  based on theoretical maximum wire speed and thresholds were set based
5453  *  on testing data as well as attempting to minimize response time
5454  *  while increasing bulk throughput.
5455  *  This functionality is controlled by ethtool's coalescing settings.
5456  *  NOTE:  These calculations are only valid when operating in a single-
5457  *         queue environment.
5458  **/
5459 static void igb_update_itr(struct igb_q_vector *q_vector,
5460                            struct igb_ring_container *ring_container)
5461 {
5462         unsigned int packets = ring_container->total_packets;
5463         unsigned int bytes = ring_container->total_bytes;
5464         u8 itrval = ring_container->itr;
5465
5466         /* no packets, exit with status unchanged */
5467         if (packets == 0)
5468                 return;
5469
5470         switch (itrval) {
5471         case lowest_latency:
5472                 /* handle TSO and jumbo frames */
5473                 if (bytes/packets > 8000)
5474                         itrval = bulk_latency;
5475                 else if ((packets < 5) && (bytes > 512))
5476                         itrval = low_latency;
5477                 break;
5478         case low_latency:  /* 50 usec aka 20000 ints/s */
5479                 if (bytes > 10000) {
5480                         /* this if handles the TSO accounting */
5481                         if (bytes/packets > 8000)
5482                                 itrval = bulk_latency;
5483                         else if ((packets < 10) || ((bytes/packets) > 1200))
5484                                 itrval = bulk_latency;
5485                         else if ((packets > 35))
5486                                 itrval = lowest_latency;
5487                 } else if (bytes/packets > 2000) {
5488                         itrval = bulk_latency;
5489                 } else if (packets <= 2 && bytes < 512) {
5490                         itrval = lowest_latency;
5491                 }
5492                 break;
5493         case bulk_latency: /* 250 usec aka 4000 ints/s */
5494                 if (bytes > 25000) {
5495                         if (packets > 35)
5496                                 itrval = low_latency;
5497                 } else if (bytes < 1500) {
5498                         itrval = low_latency;
5499                 }
5500                 break;
5501         }
5502
5503         /* clear work counters since we have the values we need */
5504         ring_container->total_bytes = 0;
5505         ring_container->total_packets = 0;
5506
5507         /* write updated itr to ring container */
5508         ring_container->itr = itrval;
5509 }
5510
5511 static void igb_set_itr(struct igb_q_vector *q_vector)
5512 {
5513         struct igb_adapter *adapter = q_vector->adapter;
5514         u32 new_itr = q_vector->itr_val;
5515         u8 current_itr = 0;
5516
5517         /* for non-gigabit speeds, just fix the interrupt rate at 4000 */
5518         if (adapter->link_speed != SPEED_1000) {
5519                 current_itr = 0;
5520                 new_itr = IGB_4K_ITR;
5521                 goto set_itr_now;
5522         }
5523
5524         igb_update_itr(q_vector, &q_vector->tx);
5525         igb_update_itr(q_vector, &q_vector->rx);
5526
5527         current_itr = max(q_vector->rx.itr, q_vector->tx.itr);
5528
5529         /* conservative mode (itr 3) eliminates the lowest_latency setting */
5530         if (current_itr == lowest_latency &&
5531             ((q_vector->rx.ring && adapter->rx_itr_setting == 3) ||
5532              (!q_vector->rx.ring && adapter->tx_itr_setting == 3)))
5533                 current_itr = low_latency;
5534
5535         switch (current_itr) {
5536         /* counts and packets in update_itr are dependent on these numbers */
5537         case lowest_latency:
5538                 new_itr = IGB_70K_ITR; /* 70,000 ints/sec */
5539                 break;
5540         case low_latency:
5541                 new_itr = IGB_20K_ITR; /* 20,000 ints/sec */
5542                 break;
5543         case bulk_latency:
5544                 new_itr = IGB_4K_ITR;  /* 4,000 ints/sec */
5545                 break;
5546         default:
5547                 break;
5548         }
5549
5550 set_itr_now:
5551         if (new_itr != q_vector->itr_val) {
5552                 /* this attempts to bias the interrupt rate towards Bulk
5553                  * by adding intermediate steps when interrupt rate is
5554                  * increasing
5555                  */
5556                 new_itr = new_itr > q_vector->itr_val ?
5557                           max((new_itr * q_vector->itr_val) /
5558                           (new_itr + (q_vector->itr_val >> 2)),
5559                           new_itr) : new_itr;
5560                 /* Don't write the value here; it resets the adapter's
5561                  * internal timer, and causes us to delay far longer than
5562                  * we should between interrupts.  Instead, we write the ITR
5563                  * value at the beginning of the next interrupt so the timing
5564                  * ends up being correct.
5565                  */
5566                 q_vector->itr_val = new_itr;
5567                 q_vector->set_itr = 1;
5568         }
5569 }
5570
5571 static void igb_tx_ctxtdesc(struct igb_ring *tx_ring, u32 vlan_macip_lens,
5572                             u32 type_tucmd, u32 mss_l4len_idx)
5573 {
5574         struct e1000_adv_tx_context_desc *context_desc;
5575         u16 i = tx_ring->next_to_use;
5576
5577         context_desc = IGB_TX_CTXTDESC(tx_ring, i);
5578
5579         i++;
5580         tx_ring->next_to_use = (i < tx_ring->count) ? i : 0;
5581
5582         /* set bits to identify this as an advanced context descriptor */
5583         type_tucmd |= E1000_TXD_CMD_DEXT | E1000_ADVTXD_DTYP_CTXT;
5584
5585         /* For 82575, context index must be unique per ring. */
5586         if (test_bit(IGB_RING_FLAG_TX_CTX_IDX, &tx_ring->flags))
5587                 mss_l4len_idx |= tx_ring->reg_idx << 4;
5588
5589         context_desc->vlan_macip_lens   = cpu_to_le32(vlan_macip_lens);
5590         context_desc->seqnum_seed       = 0;
5591         context_desc->type_tucmd_mlhl   = cpu_to_le32(type_tucmd);
5592         context_desc->mss_l4len_idx     = cpu_to_le32(mss_l4len_idx);
5593 }
5594
5595 static int igb_tso(struct igb_ring *tx_ring,
5596                    struct igb_tx_buffer *first,
5597                    u8 *hdr_len)
5598 {
5599         u32 vlan_macip_lens, type_tucmd, mss_l4len_idx;
5600         struct sk_buff *skb = first->skb;
5601         union {
5602                 struct iphdr *v4;
5603                 struct ipv6hdr *v6;
5604                 unsigned char *hdr;
5605         } ip;
5606         union {
5607                 struct tcphdr *tcp;
5608                 unsigned char *hdr;
5609         } l4;
5610         u32 paylen, l4_offset;
5611         int err;
5612
5613         if (skb->ip_summed != CHECKSUM_PARTIAL)
5614                 return 0;
5615
5616         if (!skb_is_gso(skb))
5617                 return 0;
5618
5619         err = skb_cow_head(skb, 0);
5620         if (err < 0)
5621                 return err;
5622
5623         ip.hdr = skb_network_header(skb);
5624         l4.hdr = skb_checksum_start(skb);
5625
5626         /* ADV DTYP TUCMD MKRLOC/ISCSIHEDLEN */
5627         type_tucmd = E1000_ADVTXD_TUCMD_L4T_TCP;
5628
5629         /* initialize outer IP header fields */
5630         if (ip.v4->version == 4) {
5631                 unsigned char *csum_start = skb_checksum_start(skb);
5632                 unsigned char *trans_start = ip.hdr + (ip.v4->ihl * 4);
5633
5634                 /* IP header will have to cancel out any data that
5635                  * is not a part of the outer IP header
5636                  */
5637                 ip.v4->check = csum_fold(csum_partial(trans_start,
5638                                                       csum_start - trans_start,
5639                                                       0));
5640                 type_tucmd |= E1000_ADVTXD_TUCMD_IPV4;
5641
5642                 ip.v4->tot_len = 0;
5643                 first->tx_flags |= IGB_TX_FLAGS_TSO |
5644                                    IGB_TX_FLAGS_CSUM |
5645                                    IGB_TX_FLAGS_IPV4;
5646         } else {
5647                 ip.v6->payload_len = 0;
5648                 first->tx_flags |= IGB_TX_FLAGS_TSO |
5649                                    IGB_TX_FLAGS_CSUM;
5650         }
5651
5652         /* determine offset of inner transport header */
5653         l4_offset = l4.hdr - skb->data;
5654
5655         /* compute length of segmentation header */
5656         *hdr_len = (l4.tcp->doff * 4) + l4_offset;
5657
5658         /* remove payload length from inner checksum */
5659         paylen = skb->len - l4_offset;
5660         csum_replace_by_diff(&l4.tcp->check, htonl(paylen));
5661
5662         /* update gso size and bytecount with header size */
5663         first->gso_segs = skb_shinfo(skb)->gso_segs;
5664         first->bytecount += (first->gso_segs - 1) * *hdr_len;
5665
5666         /* MSS L4LEN IDX */
5667         mss_l4len_idx = (*hdr_len - l4_offset) << E1000_ADVTXD_L4LEN_SHIFT;
5668         mss_l4len_idx |= skb_shinfo(skb)->gso_size << E1000_ADVTXD_MSS_SHIFT;
5669
5670         /* VLAN MACLEN IPLEN */
5671         vlan_macip_lens = l4.hdr - ip.hdr;
5672         vlan_macip_lens |= (ip.hdr - skb->data) << E1000_ADVTXD_MACLEN_SHIFT;
5673         vlan_macip_lens |= first->tx_flags & IGB_TX_FLAGS_VLAN_MASK;
5674
5675         igb_tx_ctxtdesc(tx_ring, vlan_macip_lens, type_tucmd, mss_l4len_idx);
5676
5677         return 1;
5678 }
5679
5680 static inline bool igb_ipv6_csum_is_sctp(struct sk_buff *skb)
5681 {
5682         unsigned int offset = 0;
5683
5684         ipv6_find_hdr(skb, &offset, IPPROTO_SCTP, NULL, NULL);
5685
5686         return offset == skb_checksum_start_offset(skb);
5687 }
5688
5689 static void igb_tx_csum(struct igb_ring *tx_ring, struct igb_tx_buffer *first)
5690 {
5691         struct sk_buff *skb = first->skb;
5692         u32 vlan_macip_lens = 0;
5693         u32 type_tucmd = 0;
5694
5695         if (skb->ip_summed != CHECKSUM_PARTIAL) {
5696 csum_failed:
5697                 if (!(first->tx_flags & IGB_TX_FLAGS_VLAN))
5698                         return;
5699                 goto no_csum;
5700         }
5701
5702         switch (skb->csum_offset) {
5703         case offsetof(struct tcphdr, check):
5704                 type_tucmd = E1000_ADVTXD_TUCMD_L4T_TCP;
5705                 /* fall through */
5706         case offsetof(struct udphdr, check):
5707                 break;
5708         case offsetof(struct sctphdr, checksum):
5709                 /* validate that this is actually an SCTP request */
5710                 if (((first->protocol == htons(ETH_P_IP)) &&
5711                      (ip_hdr(skb)->protocol == IPPROTO_SCTP)) ||
5712                     ((first->protocol == htons(ETH_P_IPV6)) &&
5713                      igb_ipv6_csum_is_sctp(skb))) {
5714                         type_tucmd = E1000_ADVTXD_TUCMD_L4T_SCTP;
5715                         break;
5716                 }
5717         default:
5718                 skb_checksum_help(skb);
5719                 goto csum_failed;
5720         }
5721
5722         /* update TX checksum flag */
5723         first->tx_flags |= IGB_TX_FLAGS_CSUM;
5724         vlan_macip_lens = skb_checksum_start_offset(skb) -
5725                           skb_network_offset(skb);
5726 no_csum:
5727         vlan_macip_lens |= skb_network_offset(skb) << E1000_ADVTXD_MACLEN_SHIFT;
5728         vlan_macip_lens |= first->tx_flags & IGB_TX_FLAGS_VLAN_MASK;
5729
5730         igb_tx_ctxtdesc(tx_ring, vlan_macip_lens, type_tucmd, 0);
5731 }
5732
5733 #define IGB_SET_FLAG(_input, _flag, _result) \
5734         ((_flag <= _result) ? \
5735          ((u32)(_input & _flag) * (_result / _flag)) : \
5736          ((u32)(_input & _flag) / (_flag / _result)))
5737
5738 static u32 igb_tx_cmd_type(struct sk_buff *skb, u32 tx_flags)
5739 {
5740         /* set type for advanced descriptor with frame checksum insertion */
5741         u32 cmd_type = E1000_ADVTXD_DTYP_DATA |
5742                        E1000_ADVTXD_DCMD_DEXT |
5743                        E1000_ADVTXD_DCMD_IFCS;
5744
5745         /* set HW vlan bit if vlan is present */
5746         cmd_type |= IGB_SET_FLAG(tx_flags, IGB_TX_FLAGS_VLAN,
5747                                  (E1000_ADVTXD_DCMD_VLE));
5748
5749         /* set segmentation bits for TSO */
5750         cmd_type |= IGB_SET_FLAG(tx_flags, IGB_TX_FLAGS_TSO,
5751                                  (E1000_ADVTXD_DCMD_TSE));
5752
5753         /* set timestamp bit if present */
5754         cmd_type |= IGB_SET_FLAG(tx_flags, IGB_TX_FLAGS_TSTAMP,
5755                                  (E1000_ADVTXD_MAC_TSTAMP));
5756
5757         /* insert frame checksum */
5758         cmd_type ^= IGB_SET_FLAG(skb->no_fcs, 1, E1000_ADVTXD_DCMD_IFCS);
5759
5760         return cmd_type;
5761 }
5762
5763 static void igb_tx_olinfo_status(struct igb_ring *tx_ring,
5764                                  union e1000_adv_tx_desc *tx_desc,
5765                                  u32 tx_flags, unsigned int paylen)
5766 {
5767         u32 olinfo_status = paylen << E1000_ADVTXD_PAYLEN_SHIFT;
5768
5769         /* 82575 requires a unique index per ring */
5770         if (test_bit(IGB_RING_FLAG_TX_CTX_IDX, &tx_ring->flags))
5771                 olinfo_status |= tx_ring->reg_idx << 4;
5772
5773         /* insert L4 checksum */
5774         olinfo_status |= IGB_SET_FLAG(tx_flags,
5775                                       IGB_TX_FLAGS_CSUM,
5776                                       (E1000_TXD_POPTS_TXSM << 8));
5777
5778         /* insert IPv4 checksum */
5779         olinfo_status |= IGB_SET_FLAG(tx_flags,
5780                                       IGB_TX_FLAGS_IPV4,
5781                                       (E1000_TXD_POPTS_IXSM << 8));
5782
5783         tx_desc->read.olinfo_status = cpu_to_le32(olinfo_status);
5784 }
5785
5786 static int __igb_maybe_stop_tx(struct igb_ring *tx_ring, const u16 size)
5787 {
5788         struct net_device *netdev = tx_ring->netdev;
5789
5790         netif_stop_subqueue(netdev, tx_ring->queue_index);
5791
5792         /* Herbert's original patch had:
5793          *  smp_mb__after_netif_stop_queue();
5794          * but since that doesn't exist yet, just open code it.
5795          */
5796         smp_mb();
5797
5798         /* We need to check again in a case another CPU has just
5799          * made room available.
5800          */
5801         if (igb_desc_unused(tx_ring) < size)
5802                 return -EBUSY;
5803
5804         /* A reprieve! */
5805         netif_wake_subqueue(netdev, tx_ring->queue_index);
5806
5807         u64_stats_update_begin(&tx_ring->tx_syncp2);
5808         tx_ring->tx_stats.restart_queue2++;
5809         u64_stats_update_end(&tx_ring->tx_syncp2);
5810
5811         return 0;
5812 }
5813
5814 static inline int igb_maybe_stop_tx(struct igb_ring *tx_ring, const u16 size)
5815 {
5816         if (igb_desc_unused(tx_ring) >= size)
5817                 return 0;
5818         return __igb_maybe_stop_tx(tx_ring, size);
5819 }
5820
5821 static int igb_tx_map(struct igb_ring *tx_ring,
5822                       struct igb_tx_buffer *first,
5823                       const u8 hdr_len)
5824 {
5825         struct sk_buff *skb = first->skb;
5826         struct igb_tx_buffer *tx_buffer;
5827         union e1000_adv_tx_desc *tx_desc;
5828         struct skb_frag_struct *frag;
5829         dma_addr_t dma;
5830         unsigned int data_len, size;
5831         u32 tx_flags = first->tx_flags;
5832         u32 cmd_type = igb_tx_cmd_type(skb, tx_flags);
5833         u16 i = tx_ring->next_to_use;
5834
5835         tx_desc = IGB_TX_DESC(tx_ring, i);
5836
5837         igb_tx_olinfo_status(tx_ring, tx_desc, tx_flags, skb->len - hdr_len);
5838
5839         size = skb_headlen(skb);
5840         data_len = skb->data_len;
5841
5842         dma = dma_map_single(tx_ring->dev, skb->data, size, DMA_TO_DEVICE);
5843
5844         tx_buffer = first;
5845
5846         for (frag = &skb_shinfo(skb)->frags[0];; frag++) {
5847                 if (dma_mapping_error(tx_ring->dev, dma))
5848                         goto dma_error;
5849
5850                 /* record length, and DMA address */
5851                 dma_unmap_len_set(tx_buffer, len, size);
5852                 dma_unmap_addr_set(tx_buffer, dma, dma);
5853
5854                 tx_desc->read.buffer_addr = cpu_to_le64(dma);
5855
5856                 while (unlikely(size > IGB_MAX_DATA_PER_TXD)) {
5857                         tx_desc->read.cmd_type_len =
5858                                 cpu_to_le32(cmd_type ^ IGB_MAX_DATA_PER_TXD);
5859
5860                         i++;
5861                         tx_desc++;
5862                         if (i == tx_ring->count) {
5863                                 tx_desc = IGB_TX_DESC(tx_ring, 0);
5864                                 i = 0;
5865                         }
5866                         tx_desc->read.olinfo_status = 0;
5867
5868                         dma += IGB_MAX_DATA_PER_TXD;
5869                         size -= IGB_MAX_DATA_PER_TXD;
5870
5871                         tx_desc->read.buffer_addr = cpu_to_le64(dma);
5872                 }
5873
5874                 if (likely(!data_len))
5875                         break;
5876
5877                 tx_desc->read.cmd_type_len = cpu_to_le32(cmd_type ^ size);
5878
5879                 i++;
5880                 tx_desc++;
5881                 if (i == tx_ring->count) {
5882                         tx_desc = IGB_TX_DESC(tx_ring, 0);
5883                         i = 0;
5884                 }
5885                 tx_desc->read.olinfo_status = 0;
5886
5887                 size = skb_frag_size(frag);
5888                 data_len -= size;
5889
5890                 dma = skb_frag_dma_map(tx_ring->dev, frag, 0,
5891                                        size, DMA_TO_DEVICE);
5892
5893                 tx_buffer = &tx_ring->tx_buffer_info[i];
5894         }
5895
5896         /* write last descriptor with RS and EOP bits */
5897         cmd_type |= size | IGB_TXD_DCMD;
5898         tx_desc->read.cmd_type_len = cpu_to_le32(cmd_type);
5899
5900         netdev_tx_sent_queue(txring_txq(tx_ring), first->bytecount);
5901
5902         /* set the timestamp */
5903         first->time_stamp = jiffies;
5904
5905         /* Force memory writes to complete before letting h/w know there
5906          * are new descriptors to fetch.  (Only applicable for weak-ordered
5907          * memory model archs, such as IA-64).
5908          *
5909          * We also need this memory barrier to make certain all of the
5910          * status bits have been updated before next_to_watch is written.
5911          */
5912         wmb();
5913
5914         /* set next_to_watch value indicating a packet is present */
5915         first->next_to_watch = tx_desc;
5916
5917         i++;
5918         if (i == tx_ring->count)
5919                 i = 0;
5920
5921         tx_ring->next_to_use = i;
5922
5923         /* Make sure there is space in the ring for the next send. */
5924         igb_maybe_stop_tx(tx_ring, DESC_NEEDED);
5925
5926         if (netif_xmit_stopped(txring_txq(tx_ring)) || !skb->xmit_more) {
5927                 writel(i, tx_ring->tail);
5928
5929                 /* we need this if more than one processor can write to our tail
5930                  * at a time, it synchronizes IO on IA64/Altix systems
5931                  */
5932                 mmiowb();
5933         }
5934         return 0;
5935
5936 dma_error:
5937         dev_err(tx_ring->dev, "TX DMA map failed\n");
5938         tx_buffer = &tx_ring->tx_buffer_info[i];
5939
5940         /* clear dma mappings for failed tx_buffer_info map */
5941         while (tx_buffer != first) {
5942                 if (dma_unmap_len(tx_buffer, len))
5943                         dma_unmap_page(tx_ring->dev,
5944                                        dma_unmap_addr(tx_buffer, dma),
5945                                        dma_unmap_len(tx_buffer, len),
5946                                        DMA_TO_DEVICE);
5947                 dma_unmap_len_set(tx_buffer, len, 0);
5948
5949                 if (i-- == 0)
5950                         i += tx_ring->count;
5951                 tx_buffer = &tx_ring->tx_buffer_info[i];
5952         }
5953
5954         if (dma_unmap_len(tx_buffer, len))
5955                 dma_unmap_single(tx_ring->dev,
5956                                  dma_unmap_addr(tx_buffer, dma),
5957                                  dma_unmap_len(tx_buffer, len),
5958                                  DMA_TO_DEVICE);
5959         dma_unmap_len_set(tx_buffer, len, 0);
5960
5961         dev_kfree_skb_any(tx_buffer->skb);
5962         tx_buffer->skb = NULL;
5963
5964         tx_ring->next_to_use = i;
5965
5966         return -1;
5967 }
5968
5969 netdev_tx_t igb_xmit_frame_ring(struct sk_buff *skb,
5970                                 struct igb_ring *tx_ring)
5971 {
5972         struct igb_tx_buffer *first;
5973         int tso;
5974         u32 tx_flags = 0;
5975         unsigned short f;
5976         u16 count = TXD_USE_COUNT(skb_headlen(skb));
5977         __be16 protocol = vlan_get_protocol(skb);
5978         u8 hdr_len = 0;
5979
5980         /* need: 1 descriptor per page * PAGE_SIZE/IGB_MAX_DATA_PER_TXD,
5981          *       + 1 desc for skb_headlen/IGB_MAX_DATA_PER_TXD,
5982          *       + 2 desc gap to keep tail from touching head,
5983          *       + 1 desc for context descriptor,
5984          * otherwise try next time
5985          */
5986         for (f = 0; f < skb_shinfo(skb)->nr_frags; f++)
5987                 count += TXD_USE_COUNT(skb_shinfo(skb)->frags[f].size);
5988
5989         if (igb_maybe_stop_tx(tx_ring, count + 3)) {
5990                 /* this is a hard error */
5991                 return NETDEV_TX_BUSY;
5992         }
5993
5994         /* record the location of the first descriptor for this packet */
5995         first = &tx_ring->tx_buffer_info[tx_ring->next_to_use];
5996         first->skb = skb;
5997         first->bytecount = skb->len;
5998         first->gso_segs = 1;
5999
6000         if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP)) {
6001                 struct igb_adapter *adapter = netdev_priv(tx_ring->netdev);
6002
6003                 if (adapter->tstamp_config.tx_type == HWTSTAMP_TX_ON &&
6004                     !test_and_set_bit_lock(__IGB_PTP_TX_IN_PROGRESS,
6005                                            &adapter->state)) {
6006                         skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS;
6007                         tx_flags |= IGB_TX_FLAGS_TSTAMP;
6008
6009                         adapter->ptp_tx_skb = skb_get(skb);
6010                         adapter->ptp_tx_start = jiffies;
6011                         if (adapter->hw.mac.type == e1000_82576)
6012                                 schedule_work(&adapter->ptp_tx_work);
6013                 } else {
6014                         adapter->tx_hwtstamp_skipped++;
6015                 }
6016         }
6017
6018         skb_tx_timestamp(skb);
6019
6020         if (skb_vlan_tag_present(skb)) {
6021                 tx_flags |= IGB_TX_FLAGS_VLAN;
6022                 tx_flags |= (skb_vlan_tag_get(skb) << IGB_TX_FLAGS_VLAN_SHIFT);
6023         }
6024
6025         /* record initial flags and protocol */
6026         first->tx_flags = tx_flags;
6027         first->protocol = protocol;
6028
6029         tso = igb_tso(tx_ring, first, &hdr_len);
6030         if (tso < 0)
6031                 goto out_drop;
6032         else if (!tso)
6033                 igb_tx_csum(tx_ring, first);
6034
6035         if (igb_tx_map(tx_ring, first, hdr_len))
6036                 goto cleanup_tx_tstamp;
6037
6038         return NETDEV_TX_OK;
6039
6040 out_drop:
6041         dev_kfree_skb_any(first->skb);
6042         first->skb = NULL;
6043 cleanup_tx_tstamp:
6044         if (unlikely(tx_flags & IGB_TX_FLAGS_TSTAMP)) {
6045                 struct igb_adapter *adapter = netdev_priv(tx_ring->netdev);
6046
6047                 dev_kfree_skb_any(adapter->ptp_tx_skb);
6048                 adapter->ptp_tx_skb = NULL;
6049                 if (adapter->hw.mac.type == e1000_82576)
6050                         cancel_work_sync(&adapter->ptp_tx_work);
6051                 clear_bit_unlock(__IGB_PTP_TX_IN_PROGRESS, &adapter->state);
6052         }
6053
6054         return NETDEV_TX_OK;
6055 }
6056
6057 static inline struct igb_ring *igb_tx_queue_mapping(struct igb_adapter *adapter,
6058                                                     struct sk_buff *skb)
6059 {
6060         unsigned int r_idx = skb->queue_mapping;
6061
6062         if (r_idx >= adapter->num_tx_queues)
6063                 r_idx = r_idx % adapter->num_tx_queues;
6064
6065         return adapter->tx_ring[r_idx];
6066 }
6067
6068 static netdev_tx_t igb_xmit_frame(struct sk_buff *skb,
6069                                   struct net_device *netdev)
6070 {
6071         struct igb_adapter *adapter = netdev_priv(netdev);
6072
6073         /* The minimum packet size with TCTL.PSP set is 17 so pad the skb
6074          * in order to meet this minimum size requirement.
6075          */
6076         if (skb_put_padto(skb, 17))
6077                 return NETDEV_TX_OK;
6078
6079         return igb_xmit_frame_ring(skb, igb_tx_queue_mapping(adapter, skb));
6080 }
6081
6082 /**
6083  *  igb_tx_timeout - Respond to a Tx Hang
6084  *  @netdev: network interface device structure
6085  **/
6086 static void igb_tx_timeout(struct net_device *netdev)
6087 {
6088         struct igb_adapter *adapter = netdev_priv(netdev);
6089         struct e1000_hw *hw = &adapter->hw;
6090
6091         /* Do the reset outside of interrupt context */
6092         adapter->tx_timeout_count++;
6093
6094         if (hw->mac.type >= e1000_82580)
6095                 hw->dev_spec._82575.global_device_reset = true;
6096
6097         schedule_work(&adapter->reset_task);
6098         wr32(E1000_EICS,
6099              (adapter->eims_enable_mask & ~adapter->eims_other));
6100 }
6101
6102 static void igb_reset_task(struct work_struct *work)
6103 {
6104         struct igb_adapter *adapter;
6105         adapter = container_of(work, struct igb_adapter, reset_task);
6106
6107         igb_dump(adapter);
6108         netdev_err(adapter->netdev, "Reset adapter\n");
6109         igb_reinit_locked(adapter);
6110 }
6111
6112 /**
6113  *  igb_get_stats64 - Get System Network Statistics
6114  *  @netdev: network interface device structure
6115  *  @stats: rtnl_link_stats64 pointer
6116  **/
6117 static void igb_get_stats64(struct net_device *netdev,
6118                             struct rtnl_link_stats64 *stats)
6119 {
6120         struct igb_adapter *adapter = netdev_priv(netdev);
6121
6122         spin_lock(&adapter->stats64_lock);
6123         igb_update_stats(adapter);
6124         memcpy(stats, &adapter->stats64, sizeof(*stats));
6125         spin_unlock(&adapter->stats64_lock);
6126 }
6127
6128 /**
6129  *  igb_change_mtu - Change the Maximum Transfer Unit
6130  *  @netdev: network interface device structure
6131  *  @new_mtu: new value for maximum frame size
6132  *
6133  *  Returns 0 on success, negative on failure
6134  **/
6135 static int igb_change_mtu(struct net_device *netdev, int new_mtu)
6136 {
6137         struct igb_adapter *adapter = netdev_priv(netdev);
6138         struct pci_dev *pdev = adapter->pdev;
6139         int max_frame = new_mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN;
6140
6141         /* adjust max frame to be at least the size of a standard frame */
6142         if (max_frame < (ETH_FRAME_LEN + ETH_FCS_LEN))
6143                 max_frame = ETH_FRAME_LEN + ETH_FCS_LEN;
6144
6145         while (test_and_set_bit(__IGB_RESETTING, &adapter->state))
6146                 usleep_range(1000, 2000);
6147
6148         /* igb_down has a dependency on max_frame_size */
6149         adapter->max_frame_size = max_frame;
6150
6151         if (netif_running(netdev))
6152                 igb_down(adapter);
6153
6154         dev_info(&pdev->dev, "changing MTU from %d to %d\n",
6155                  netdev->mtu, new_mtu);
6156         netdev->mtu = new_mtu;
6157
6158         if (netif_running(netdev))
6159                 igb_up(adapter);
6160         else
6161                 igb_reset(adapter);
6162
6163         clear_bit(__IGB_RESETTING, &adapter->state);
6164
6165         return 0;
6166 }
6167
6168 /**
6169  *  igb_update_stats - Update the board statistics counters
6170  *  @adapter: board private structure
6171  **/
6172 void igb_update_stats(struct igb_adapter *adapter)
6173 {
6174         struct rtnl_link_stats64 *net_stats = &adapter->stats64;
6175         struct e1000_hw *hw = &adapter->hw;
6176         struct pci_dev *pdev = adapter->pdev;
6177         u32 reg, mpc;
6178         int i;
6179         u64 bytes, packets;
6180         unsigned int start;
6181         u64 _bytes, _packets;
6182
6183         /* Prevent stats update while adapter is being reset, or if the pci
6184          * connection is down.
6185          */
6186         if (adapter->link_speed == 0)
6187                 return;
6188         if (pci_channel_offline(pdev))
6189                 return;
6190
6191         bytes = 0;
6192         packets = 0;
6193
6194         rcu_read_lock();
6195         for (i = 0; i < adapter->num_rx_queues; i++) {
6196                 struct igb_ring *ring = adapter->rx_ring[i];
6197                 u32 rqdpc = rd32(E1000_RQDPC(i));
6198                 if (hw->mac.type >= e1000_i210)
6199                         wr32(E1000_RQDPC(i), 0);
6200
6201                 if (rqdpc) {
6202                         ring->rx_stats.drops += rqdpc;
6203                         net_stats->rx_fifo_errors += rqdpc;
6204                 }
6205
6206                 do {
6207                         start = u64_stats_fetch_begin_irq(&ring->rx_syncp);
6208                         _bytes = ring->rx_stats.bytes;
6209                         _packets = ring->rx_stats.packets;
6210                 } while (u64_stats_fetch_retry_irq(&ring->rx_syncp, start));
6211                 bytes += _bytes;
6212                 packets += _packets;
6213         }
6214
6215         net_stats->rx_bytes = bytes;
6216         net_stats->rx_packets = packets;
6217
6218         bytes = 0;
6219         packets = 0;
6220         for (i = 0; i < adapter->num_tx_queues; i++) {
6221                 struct igb_ring *ring = adapter->tx_ring[i];
6222                 do {
6223                         start = u64_stats_fetch_begin_irq(&ring->tx_syncp);
6224                         _bytes = ring->tx_stats.bytes;
6225                         _packets = ring->tx_stats.packets;
6226                 } while (u64_stats_fetch_retry_irq(&ring->tx_syncp, start));
6227                 bytes += _bytes;
6228                 packets += _packets;
6229         }
6230         net_stats->tx_bytes = bytes;
6231         net_stats->tx_packets = packets;
6232         rcu_read_unlock();
6233
6234         /* read stats registers */
6235         adapter->stats.crcerrs += rd32(E1000_CRCERRS);
6236         adapter->stats.gprc += rd32(E1000_GPRC);
6237         adapter->stats.gorc += rd32(E1000_GORCL);
6238         rd32(E1000_GORCH); /* clear GORCL */
6239         adapter->stats.bprc += rd32(E1000_BPRC);
6240         adapter->stats.mprc += rd32(E1000_MPRC);
6241         adapter->stats.roc += rd32(E1000_ROC);
6242
6243         adapter->stats.prc64 += rd32(E1000_PRC64);
6244         adapter->stats.prc127 += rd32(E1000_PRC127);
6245         adapter->stats.prc255 += rd32(E1000_PRC255);
6246         adapter->stats.prc511 += rd32(E1000_PRC511);
6247         adapter->stats.prc1023 += rd32(E1000_PRC1023);
6248         adapter->stats.prc1522 += rd32(E1000_PRC1522);
6249         adapter->stats.symerrs += rd32(E1000_SYMERRS);
6250         adapter->stats.sec += rd32(E1000_SEC);
6251
6252         mpc = rd32(E1000_MPC);
6253         adapter->stats.mpc += mpc;
6254         net_stats->rx_fifo_errors += mpc;
6255         adapter->stats.scc += rd32(E1000_SCC);
6256         adapter->stats.ecol += rd32(E1000_ECOL);
6257         adapter->stats.mcc += rd32(E1000_MCC);
6258         adapter->stats.latecol += rd32(E1000_LATECOL);
6259         adapter->stats.dc += rd32(E1000_DC);
6260         adapter->stats.rlec += rd32(E1000_RLEC);
6261         adapter->stats.xonrxc += rd32(E1000_XONRXC);
6262         adapter->stats.xontxc += rd32(E1000_XONTXC);
6263         adapter->stats.xoffrxc += rd32(E1000_XOFFRXC);
6264         adapter->stats.xofftxc += rd32(E1000_XOFFTXC);
6265         adapter->stats.fcruc += rd32(E1000_FCRUC);
6266         adapter->stats.gptc += rd32(E1000_GPTC);
6267         adapter->stats.gotc += rd32(E1000_GOTCL);
6268         rd32(E1000_GOTCH); /* clear GOTCL */
6269         adapter->stats.rnbc += rd32(E1000_RNBC);
6270         adapter->stats.ruc += rd32(E1000_RUC);
6271         adapter->stats.rfc += rd32(E1000_RFC);
6272         adapter->stats.rjc += rd32(E1000_RJC);
6273         adapter->stats.tor += rd32(E1000_TORH);
6274         adapter->stats.tot += rd32(E1000_TOTH);
6275         adapter->stats.tpr += rd32(E1000_TPR);
6276
6277         adapter->stats.ptc64 += rd32(E1000_PTC64);
6278         adapter->stats.ptc127 += rd32(E1000_PTC127);
6279         adapter->stats.ptc255 += rd32(E1000_PTC255);
6280         adapter->stats.ptc511 += rd32(E1000_PTC511);
6281         adapter->stats.ptc1023 += rd32(E1000_PTC1023);
6282         adapter->stats.ptc1522 += rd32(E1000_PTC1522);
6283
6284         adapter->stats.mptc += rd32(E1000_MPTC);
6285         adapter->stats.bptc += rd32(E1000_BPTC);
6286
6287         adapter->stats.tpt += rd32(E1000_TPT);
6288         adapter->stats.colc += rd32(E1000_COLC);
6289
6290         adapter->stats.algnerrc += rd32(E1000_ALGNERRC);
6291         /* read internal phy specific stats */
6292         reg = rd32(E1000_CTRL_EXT);
6293         if (!(reg & E1000_CTRL_EXT_LINK_MODE_MASK)) {
6294                 adapter->stats.rxerrc += rd32(E1000_RXERRC);
6295
6296                 /* this stat has invalid values on i210/i211 */
6297                 if ((hw->mac.type != e1000_i210) &&
6298                     (hw->mac.type != e1000_i211))
6299                         adapter->stats.tncrs += rd32(E1000_TNCRS);
6300         }
6301
6302         adapter->stats.tsctc += rd32(E1000_TSCTC);
6303         adapter->stats.tsctfc += rd32(E1000_TSCTFC);
6304
6305         adapter->stats.iac += rd32(E1000_IAC);
6306         adapter->stats.icrxoc += rd32(E1000_ICRXOC);
6307         adapter->stats.icrxptc += rd32(E1000_ICRXPTC);
6308         adapter->stats.icrxatc += rd32(E1000_ICRXATC);
6309         adapter->stats.ictxptc += rd32(E1000_ICTXPTC);
6310         adapter->stats.ictxatc += rd32(E1000_ICTXATC);
6311         adapter->stats.ictxqec += rd32(E1000_ICTXQEC);
6312         adapter->stats.ictxqmtc += rd32(E1000_ICTXQMTC);
6313         adapter->stats.icrxdmtc += rd32(E1000_ICRXDMTC);
6314
6315         /* Fill out the OS statistics structure */
6316         net_stats->multicast = adapter->stats.mprc;
6317         net_stats->collisions = adapter->stats.colc;
6318
6319         /* Rx Errors */
6320
6321         /* RLEC on some newer hardware can be incorrect so build
6322          * our own version based on RUC and ROC
6323          */
6324         net_stats->rx_errors = adapter->stats.rxerrc +
6325                 adapter->stats.crcerrs + adapter->stats.algnerrc +
6326                 adapter->stats.ruc + adapter->stats.roc +
6327                 adapter->stats.cexterr;
6328         net_stats->rx_length_errors = adapter->stats.ruc +
6329                                       adapter->stats.roc;
6330         net_stats->rx_crc_errors = adapter->stats.crcerrs;
6331         net_stats->rx_frame_errors = adapter->stats.algnerrc;
6332         net_stats->rx_missed_errors = adapter->stats.mpc;
6333
6334         /* Tx Errors */
6335         net_stats->tx_errors = adapter->stats.ecol +
6336                                adapter->stats.latecol;
6337         net_stats->tx_aborted_errors = adapter->stats.ecol;
6338         net_stats->tx_window_errors = adapter->stats.latecol;
6339         net_stats->tx_carrier_errors = adapter->stats.tncrs;
6340
6341         /* Tx Dropped needs to be maintained elsewhere */
6342
6343         /* Management Stats */
6344         adapter->stats.mgptc += rd32(E1000_MGTPTC);
6345         adapter->stats.mgprc += rd32(E1000_MGTPRC);
6346         adapter->stats.mgpdc += rd32(E1000_MGTPDC);
6347
6348         /* OS2BMC Stats */
6349         reg = rd32(E1000_MANC);
6350         if (reg & E1000_MANC_EN_BMC2OS) {
6351                 adapter->stats.o2bgptc += rd32(E1000_O2BGPTC);
6352                 adapter->stats.o2bspc += rd32(E1000_O2BSPC);
6353                 adapter->stats.b2ospc += rd32(E1000_B2OSPC);
6354                 adapter->stats.b2ogprc += rd32(E1000_B2OGPRC);
6355         }
6356 }
6357
6358 static void igb_tsync_interrupt(struct igb_adapter *adapter)
6359 {
6360         struct e1000_hw *hw = &adapter->hw;
6361         struct ptp_clock_event event;
6362         struct timespec64 ts;
6363         u32 ack = 0, tsauxc, sec, nsec, tsicr = rd32(E1000_TSICR);
6364
6365         if (tsicr & TSINTR_SYS_WRAP) {
6366                 event.type = PTP_CLOCK_PPS;
6367                 if (adapter->ptp_caps.pps)
6368                         ptp_clock_event(adapter->ptp_clock, &event);
6369                 ack |= TSINTR_SYS_WRAP;
6370         }
6371
6372         if (tsicr & E1000_TSICR_TXTS) {
6373                 /* retrieve hardware timestamp */
6374                 schedule_work(&adapter->ptp_tx_work);
6375                 ack |= E1000_TSICR_TXTS;
6376         }
6377
6378         if (tsicr & TSINTR_TT0) {
6379                 spin_lock(&adapter->tmreg_lock);
6380                 ts = timespec64_add(adapter->perout[0].start,
6381                                     adapter->perout[0].period);
6382                 /* u32 conversion of tv_sec is safe until y2106 */
6383                 wr32(E1000_TRGTTIML0, ts.tv_nsec);
6384                 wr32(E1000_TRGTTIMH0, (u32)ts.tv_sec);
6385                 tsauxc = rd32(E1000_TSAUXC);
6386                 tsauxc |= TSAUXC_EN_TT0;
6387                 wr32(E1000_TSAUXC, tsauxc);
6388                 adapter->perout[0].start = ts;
6389                 spin_unlock(&adapter->tmreg_lock);
6390                 ack |= TSINTR_TT0;
6391         }
6392
6393         if (tsicr & TSINTR_TT1) {
6394                 spin_lock(&adapter->tmreg_lock);
6395                 ts = timespec64_add(adapter->perout[1].start,
6396                                     adapter->perout[1].period);
6397                 wr32(E1000_TRGTTIML1, ts.tv_nsec);
6398                 wr32(E1000_TRGTTIMH1, (u32)ts.tv_sec);
6399                 tsauxc = rd32(E1000_TSAUXC);
6400                 tsauxc |= TSAUXC_EN_TT1;
6401                 wr32(E1000_TSAUXC, tsauxc);
6402                 adapter->perout[1].start = ts;
6403                 spin_unlock(&adapter->tmreg_lock);
6404                 ack |= TSINTR_TT1;
6405         }
6406
6407         if (tsicr & TSINTR_AUTT0) {
6408                 nsec = rd32(E1000_AUXSTMPL0);
6409                 sec  = rd32(E1000_AUXSTMPH0);
6410                 event.type = PTP_CLOCK_EXTTS;
6411                 event.index = 0;
6412                 event.timestamp = sec * 1000000000ULL + nsec;
6413                 ptp_clock_event(adapter->ptp_clock, &event);
6414                 ack |= TSINTR_AUTT0;
6415         }
6416
6417         if (tsicr & TSINTR_AUTT1) {
6418                 nsec = rd32(E1000_AUXSTMPL1);
6419                 sec  = rd32(E1000_AUXSTMPH1);
6420                 event.type = PTP_CLOCK_EXTTS;
6421                 event.index = 1;
6422                 event.timestamp = sec * 1000000000ULL + nsec;
6423                 ptp_clock_event(adapter->ptp_clock, &event);
6424                 ack |= TSINTR_AUTT1;
6425         }
6426
6427         /* acknowledge the interrupts */
6428         wr32(E1000_TSICR, ack);
6429 }
6430
6431 static irqreturn_t igb_msix_other(int irq, void *data)
6432 {
6433         struct igb_adapter *adapter = data;
6434         struct e1000_hw *hw = &adapter->hw;
6435         u32 icr = rd32(E1000_ICR);
6436         /* reading ICR causes bit 31 of EICR to be cleared */
6437
6438         if (icr & E1000_ICR_DRSTA)
6439                 schedule_work(&adapter->reset_task);
6440
6441         if (icr & E1000_ICR_DOUTSYNC) {
6442                 /* HW is reporting DMA is out of sync */
6443                 adapter->stats.doosync++;
6444                 /* The DMA Out of Sync is also indication of a spoof event
6445                  * in IOV mode. Check the Wrong VM Behavior register to
6446                  * see if it is really a spoof event.
6447                  */
6448                 igb_check_wvbr(adapter);
6449         }
6450
6451         /* Check for a mailbox event */
6452         if (icr & E1000_ICR_VMMB)
6453                 igb_msg_task(adapter);
6454
6455         if (icr & E1000_ICR_LSC) {
6456                 hw->mac.get_link_status = 1;
6457                 /* guard against interrupt when we're going down */
6458                 if (!test_bit(__IGB_DOWN, &adapter->state))
6459                         mod_timer(&adapter->watchdog_timer, jiffies + 1);
6460         }
6461
6462         if (icr & E1000_ICR_TS)
6463                 igb_tsync_interrupt(adapter);
6464
6465         wr32(E1000_EIMS, adapter->eims_other);
6466
6467         return IRQ_HANDLED;
6468 }
6469
6470 static void igb_write_itr(struct igb_q_vector *q_vector)
6471 {
6472         struct igb_adapter *adapter = q_vector->adapter;
6473         u32 itr_val = q_vector->itr_val & 0x7FFC;
6474
6475         if (!q_vector->set_itr)
6476                 return;
6477
6478         if (!itr_val)
6479                 itr_val = 0x4;
6480
6481         if (adapter->hw.mac.type == e1000_82575)
6482                 itr_val |= itr_val << 16;
6483         else
6484                 itr_val |= E1000_EITR_CNT_IGNR;
6485
6486         writel(itr_val, q_vector->itr_register);
6487         q_vector->set_itr = 0;
6488 }
6489
6490 static irqreturn_t igb_msix_ring(int irq, void *data)
6491 {
6492         struct igb_q_vector *q_vector = data;
6493
6494         /* Write the ITR value calculated from the previous interrupt. */
6495         igb_write_itr(q_vector);
6496
6497         napi_schedule(&q_vector->napi);
6498
6499         return IRQ_HANDLED;
6500 }
6501
6502 #ifdef CONFIG_IGB_DCA
6503 static void igb_update_tx_dca(struct igb_adapter *adapter,
6504                               struct igb_ring *tx_ring,
6505                               int cpu)
6506 {
6507         struct e1000_hw *hw = &adapter->hw;
6508         u32 txctrl = dca3_get_tag(tx_ring->dev, cpu);
6509
6510         if (hw->mac.type != e1000_82575)
6511                 txctrl <<= E1000_DCA_TXCTRL_CPUID_SHIFT;
6512
6513         /* We can enable relaxed ordering for reads, but not writes when
6514          * DCA is enabled.  This is due to a known issue in some chipsets
6515          * which will cause the DCA tag to be cleared.
6516          */
6517         txctrl |= E1000_DCA_TXCTRL_DESC_RRO_EN |
6518                   E1000_DCA_TXCTRL_DATA_RRO_EN |
6519                   E1000_DCA_TXCTRL_DESC_DCA_EN;
6520
6521         wr32(E1000_DCA_TXCTRL(tx_ring->reg_idx), txctrl);
6522 }
6523
6524 static void igb_update_rx_dca(struct igb_adapter *adapter,
6525                               struct igb_ring *rx_ring,
6526                               int cpu)
6527 {
6528         struct e1000_hw *hw = &adapter->hw;
6529         u32 rxctrl = dca3_get_tag(&adapter->pdev->dev, cpu);
6530
6531         if (hw->mac.type != e1000_82575)
6532                 rxctrl <<= E1000_DCA_RXCTRL_CPUID_SHIFT;
6533
6534         /* We can enable relaxed ordering for reads, but not writes when
6535          * DCA is enabled.  This is due to a known issue in some chipsets
6536          * which will cause the DCA tag to be cleared.
6537          */
6538         rxctrl |= E1000_DCA_RXCTRL_DESC_RRO_EN |
6539                   E1000_DCA_RXCTRL_DESC_DCA_EN;
6540
6541         wr32(E1000_DCA_RXCTRL(rx_ring->reg_idx), rxctrl);
6542 }
6543
6544 static void igb_update_dca(struct igb_q_vector *q_vector)
6545 {
6546         struct igb_adapter *adapter = q_vector->adapter;
6547         int cpu = get_cpu();
6548
6549         if (q_vector->cpu == cpu)
6550                 goto out_no_update;
6551
6552         if (q_vector->tx.ring)
6553                 igb_update_tx_dca(adapter, q_vector->tx.ring, cpu);
6554
6555         if (q_vector->rx.ring)
6556                 igb_update_rx_dca(adapter, q_vector->rx.ring, cpu);
6557
6558         q_vector->cpu = cpu;
6559 out_no_update:
6560         put_cpu();
6561 }
6562
6563 static void igb_setup_dca(struct igb_adapter *adapter)
6564 {
6565         struct e1000_hw *hw = &adapter->hw;
6566         int i;
6567
6568         if (!(adapter->flags & IGB_FLAG_DCA_ENABLED))
6569                 return;
6570
6571         /* Always use CB2 mode, difference is masked in the CB driver. */
6572         wr32(E1000_DCA_CTRL, E1000_DCA_CTRL_DCA_MODE_CB2);
6573
6574         for (i = 0; i < adapter->num_q_vectors; i++) {
6575                 adapter->q_vector[i]->cpu = -1;
6576                 igb_update_dca(adapter->q_vector[i]);
6577         }
6578 }
6579
6580 static int __igb_notify_dca(struct device *dev, void *data)
6581 {
6582         struct net_device *netdev = dev_get_drvdata(dev);
6583         struct igb_adapter *adapter = netdev_priv(netdev);
6584         struct pci_dev *pdev = adapter->pdev;
6585         struct e1000_hw *hw = &adapter->hw;
6586         unsigned long event = *(unsigned long *)data;
6587
6588         switch (event) {
6589         case DCA_PROVIDER_ADD:
6590                 /* if already enabled, don't do it again */
6591                 if (adapter->flags & IGB_FLAG_DCA_ENABLED)
6592                         break;
6593                 if (dca_add_requester(dev) == 0) {
6594                         adapter->flags |= IGB_FLAG_DCA_ENABLED;
6595                         dev_info(&pdev->dev, "DCA enabled\n");
6596                         igb_setup_dca(adapter);
6597                         break;
6598                 }
6599                 /* Fall Through since DCA is disabled. */
6600         case DCA_PROVIDER_REMOVE:
6601                 if (adapter->flags & IGB_FLAG_DCA_ENABLED) {
6602                         /* without this a class_device is left
6603                          * hanging around in the sysfs model
6604                          */
6605                         dca_remove_requester(dev);
6606                         dev_info(&pdev->dev, "DCA disabled\n");
6607                         adapter->flags &= ~IGB_FLAG_DCA_ENABLED;
6608                         wr32(E1000_DCA_CTRL, E1000_DCA_CTRL_DCA_MODE_DISABLE);
6609                 }
6610                 break;
6611         }
6612
6613         return 0;
6614 }
6615
6616 static int igb_notify_dca(struct notifier_block *nb, unsigned long event,
6617                           void *p)
6618 {
6619         int ret_val;
6620
6621         ret_val = driver_for_each_device(&igb_driver.driver, NULL, &event,
6622                                          __igb_notify_dca);
6623
6624         return ret_val ? NOTIFY_BAD : NOTIFY_DONE;
6625 }
6626 #endif /* CONFIG_IGB_DCA */
6627
6628 #ifdef CONFIG_PCI_IOV
6629 static int igb_vf_configure(struct igb_adapter *adapter, int vf)
6630 {
6631         unsigned char mac_addr[ETH_ALEN];
6632
6633         eth_zero_addr(mac_addr);
6634         igb_set_vf_mac(adapter, vf, mac_addr);
6635
6636         /* By default spoof check is enabled for all VFs */
6637         adapter->vf_data[vf].spoofchk_enabled = true;
6638
6639         /* By default VFs are not trusted */
6640         adapter->vf_data[vf].trusted = false;
6641
6642         return 0;
6643 }
6644
6645 #endif
6646 static void igb_ping_all_vfs(struct igb_adapter *adapter)
6647 {
6648         struct e1000_hw *hw = &adapter->hw;
6649         u32 ping;
6650         int i;
6651
6652         for (i = 0 ; i < adapter->vfs_allocated_count; i++) {
6653                 ping = E1000_PF_CONTROL_MSG;
6654                 if (adapter->vf_data[i].flags & IGB_VF_FLAG_CTS)
6655                         ping |= E1000_VT_MSGTYPE_CTS;
6656                 igb_write_mbx(hw, &ping, 1, i);
6657         }
6658 }
6659
6660 static int igb_set_vf_promisc(struct igb_adapter *adapter, u32 *msgbuf, u32 vf)
6661 {
6662         struct e1000_hw *hw = &adapter->hw;
6663         u32 vmolr = rd32(E1000_VMOLR(vf));
6664         struct vf_data_storage *vf_data = &adapter->vf_data[vf];
6665
6666         vf_data->flags &= ~(IGB_VF_FLAG_UNI_PROMISC |
6667                             IGB_VF_FLAG_MULTI_PROMISC);
6668         vmolr &= ~(E1000_VMOLR_ROPE | E1000_VMOLR_ROMPE | E1000_VMOLR_MPME);
6669
6670         if (*msgbuf & E1000_VF_SET_PROMISC_MULTICAST) {
6671                 vmolr |= E1000_VMOLR_MPME;
6672                 vf_data->flags |= IGB_VF_FLAG_MULTI_PROMISC;
6673                 *msgbuf &= ~E1000_VF_SET_PROMISC_MULTICAST;
6674         } else {
6675                 /* if we have hashes and we are clearing a multicast promisc
6676                  * flag we need to write the hashes to the MTA as this step
6677                  * was previously skipped
6678                  */
6679                 if (vf_data->num_vf_mc_hashes > 30) {
6680                         vmolr |= E1000_VMOLR_MPME;
6681                 } else if (vf_data->num_vf_mc_hashes) {
6682                         int j;
6683
6684                         vmolr |= E1000_VMOLR_ROMPE;
6685                         for (j = 0; j < vf_data->num_vf_mc_hashes; j++)
6686                                 igb_mta_set(hw, vf_data->vf_mc_hashes[j]);
6687                 }
6688         }
6689
6690         wr32(E1000_VMOLR(vf), vmolr);
6691
6692         /* there are flags left unprocessed, likely not supported */
6693         if (*msgbuf & E1000_VT_MSGINFO_MASK)
6694                 return -EINVAL;
6695
6696         return 0;
6697 }
6698
6699 static int igb_set_vf_multicasts(struct igb_adapter *adapter,
6700                                   u32 *msgbuf, u32 vf)
6701 {
6702         int n = (msgbuf[0] & E1000_VT_MSGINFO_MASK) >> E1000_VT_MSGINFO_SHIFT;
6703         u16 *hash_list = (u16 *)&msgbuf[1];
6704         struct vf_data_storage *vf_data = &adapter->vf_data[vf];
6705         int i;
6706
6707         /* salt away the number of multicast addresses assigned
6708          * to this VF for later use to restore when the PF multi cast
6709          * list changes
6710          */
6711         vf_data->num_vf_mc_hashes = n;
6712
6713         /* only up to 30 hash values supported */
6714         if (n > 30)
6715                 n = 30;
6716
6717         /* store the hashes for later use */
6718         for (i = 0; i < n; i++)
6719                 vf_data->vf_mc_hashes[i] = hash_list[i];
6720
6721         /* Flush and reset the mta with the new values */
6722         igb_set_rx_mode(adapter->netdev);
6723
6724         return 0;
6725 }
6726
6727 static void igb_restore_vf_multicasts(struct igb_adapter *adapter)
6728 {
6729         struct e1000_hw *hw = &adapter->hw;
6730         struct vf_data_storage *vf_data;
6731         int i, j;
6732
6733         for (i = 0; i < adapter->vfs_allocated_count; i++) {
6734                 u32 vmolr = rd32(E1000_VMOLR(i));
6735
6736                 vmolr &= ~(E1000_VMOLR_ROMPE | E1000_VMOLR_MPME);
6737
6738                 vf_data = &adapter->vf_data[i];
6739
6740                 if ((vf_data->num_vf_mc_hashes > 30) ||
6741                     (vf_data->flags & IGB_VF_FLAG_MULTI_PROMISC)) {
6742                         vmolr |= E1000_VMOLR_MPME;
6743                 } else if (vf_data->num_vf_mc_hashes) {
6744                         vmolr |= E1000_VMOLR_ROMPE;
6745                         for (j = 0; j < vf_data->num_vf_mc_hashes; j++)
6746                                 igb_mta_set(hw, vf_data->vf_mc_hashes[j]);
6747                 }
6748                 wr32(E1000_VMOLR(i), vmolr);
6749         }
6750 }
6751
6752 static void igb_clear_vf_vfta(struct igb_adapter *adapter, u32 vf)
6753 {
6754         struct e1000_hw *hw = &adapter->hw;
6755         u32 pool_mask, vlvf_mask, i;
6756
6757         /* create mask for VF and other pools */
6758         pool_mask = E1000_VLVF_POOLSEL_MASK;
6759         vlvf_mask = BIT(E1000_VLVF_POOLSEL_SHIFT + vf);
6760
6761         /* drop PF from pool bits */
6762         pool_mask &= ~BIT(E1000_VLVF_POOLSEL_SHIFT +
6763                              adapter->vfs_allocated_count);
6764
6765         /* Find the vlan filter for this id */
6766         for (i = E1000_VLVF_ARRAY_SIZE; i--;) {
6767                 u32 vlvf = rd32(E1000_VLVF(i));
6768                 u32 vfta_mask, vid, vfta;
6769
6770                 /* remove the vf from the pool */
6771                 if (!(vlvf & vlvf_mask))
6772                         continue;
6773
6774                 /* clear out bit from VLVF */
6775                 vlvf ^= vlvf_mask;
6776
6777                 /* if other pools are present, just remove ourselves */
6778                 if (vlvf & pool_mask)
6779                         goto update_vlvfb;
6780
6781                 /* if PF is present, leave VFTA */
6782                 if (vlvf & E1000_VLVF_POOLSEL_MASK)
6783                         goto update_vlvf;
6784
6785                 vid = vlvf & E1000_VLVF_VLANID_MASK;
6786                 vfta_mask = BIT(vid % 32);
6787
6788                 /* clear bit from VFTA */
6789                 vfta = adapter->shadow_vfta[vid / 32];
6790                 if (vfta & vfta_mask)
6791                         hw->mac.ops.write_vfta(hw, vid / 32, vfta ^ vfta_mask);
6792 update_vlvf:
6793                 /* clear pool selection enable */
6794                 if (adapter->flags & IGB_FLAG_VLAN_PROMISC)
6795                         vlvf &= E1000_VLVF_POOLSEL_MASK;
6796                 else
6797                         vlvf = 0;
6798 update_vlvfb:
6799                 /* clear pool bits */
6800                 wr32(E1000_VLVF(i), vlvf);
6801         }
6802 }
6803
6804 static int igb_find_vlvf_entry(struct e1000_hw *hw, u32 vlan)
6805 {
6806         u32 vlvf;
6807         int idx;
6808
6809         /* short cut the special case */
6810         if (vlan == 0)
6811                 return 0;
6812
6813         /* Search for the VLAN id in the VLVF entries */
6814         for (idx = E1000_VLVF_ARRAY_SIZE; --idx;) {
6815                 vlvf = rd32(E1000_VLVF(idx));
6816                 if ((vlvf & VLAN_VID_MASK) == vlan)
6817                         break;
6818         }
6819
6820         return idx;
6821 }
6822
6823 static void igb_update_pf_vlvf(struct igb_adapter *adapter, u32 vid)
6824 {
6825         struct e1000_hw *hw = &adapter->hw;
6826         u32 bits, pf_id;
6827         int idx;
6828
6829         idx = igb_find_vlvf_entry(hw, vid);
6830         if (!idx)
6831                 return;
6832
6833         /* See if any other pools are set for this VLAN filter
6834          * entry other than the PF.
6835          */
6836         pf_id = adapter->vfs_allocated_count + E1000_VLVF_POOLSEL_SHIFT;
6837         bits = ~BIT(pf_id) & E1000_VLVF_POOLSEL_MASK;
6838         bits &= rd32(E1000_VLVF(idx));
6839
6840         /* Disable the filter so this falls into the default pool. */
6841         if (!bits) {
6842                 if (adapter->flags & IGB_FLAG_VLAN_PROMISC)
6843                         wr32(E1000_VLVF(idx), BIT(pf_id));
6844                 else
6845                         wr32(E1000_VLVF(idx), 0);
6846         }
6847 }
6848
6849 static s32 igb_set_vf_vlan(struct igb_adapter *adapter, u32 vid,
6850                            bool add, u32 vf)
6851 {
6852         int pf_id = adapter->vfs_allocated_count;
6853         struct e1000_hw *hw = &adapter->hw;
6854         int err;
6855
6856         /* If VLAN overlaps with one the PF is currently monitoring make
6857          * sure that we are able to allocate a VLVF entry.  This may be
6858          * redundant but it guarantees PF will maintain visibility to
6859          * the VLAN.
6860          */
6861         if (add && test_bit(vid, adapter->active_vlans)) {
6862                 err = igb_vfta_set(hw, vid, pf_id, true, false);
6863                 if (err)
6864                         return err;
6865         }
6866
6867         err = igb_vfta_set(hw, vid, vf, add, false);
6868
6869         if (add && !err)
6870                 return err;
6871
6872         /* If we failed to add the VF VLAN or we are removing the VF VLAN
6873          * we may need to drop the PF pool bit in order to allow us to free
6874          * up the VLVF resources.
6875          */
6876         if (test_bit(vid, adapter->active_vlans) ||
6877             (adapter->flags & IGB_FLAG_VLAN_PROMISC))
6878                 igb_update_pf_vlvf(adapter, vid);
6879
6880         return err;
6881 }
6882
6883 static void igb_set_vmvir(struct igb_adapter *adapter, u32 vid, u32 vf)
6884 {
6885         struct e1000_hw *hw = &adapter->hw;
6886
6887         if (vid)
6888                 wr32(E1000_VMVIR(vf), (vid | E1000_VMVIR_VLANA_DEFAULT));
6889         else
6890                 wr32(E1000_VMVIR(vf), 0);
6891 }
6892
6893 static int igb_enable_port_vlan(struct igb_adapter *adapter, int vf,
6894                                 u16 vlan, u8 qos)
6895 {
6896         int err;
6897
6898         err = igb_set_vf_vlan(adapter, vlan, true, vf);
6899         if (err)
6900                 return err;
6901
6902         igb_set_vmvir(adapter, vlan | (qos << VLAN_PRIO_SHIFT), vf);
6903         igb_set_vmolr(adapter, vf, !vlan);
6904
6905         /* revoke access to previous VLAN */
6906         if (vlan != adapter->vf_data[vf].pf_vlan)
6907                 igb_set_vf_vlan(adapter, adapter->vf_data[vf].pf_vlan,
6908                                 false, vf);
6909
6910         adapter->vf_data[vf].pf_vlan = vlan;
6911         adapter->vf_data[vf].pf_qos = qos;
6912         igb_set_vf_vlan_strip(adapter, vf, true);
6913         dev_info(&adapter->pdev->dev,
6914                  "Setting VLAN %d, QOS 0x%x on VF %d\n", vlan, qos, vf);
6915         if (test_bit(__IGB_DOWN, &adapter->state)) {
6916                 dev_warn(&adapter->pdev->dev,
6917                          "The VF VLAN has been set, but the PF device is not up.\n");
6918                 dev_warn(&adapter->pdev->dev,
6919                          "Bring the PF device up before attempting to use the VF device.\n");
6920         }
6921
6922         return err;
6923 }
6924
6925 static int igb_disable_port_vlan(struct igb_adapter *adapter, int vf)
6926 {
6927         /* Restore tagless access via VLAN 0 */
6928         igb_set_vf_vlan(adapter, 0, true, vf);
6929
6930         igb_set_vmvir(adapter, 0, vf);
6931         igb_set_vmolr(adapter, vf, true);
6932
6933         /* Remove any PF assigned VLAN */
6934         if (adapter->vf_data[vf].pf_vlan)
6935                 igb_set_vf_vlan(adapter, adapter->vf_data[vf].pf_vlan,
6936                                 false, vf);
6937
6938         adapter->vf_data[vf].pf_vlan = 0;
6939         adapter->vf_data[vf].pf_qos = 0;
6940         igb_set_vf_vlan_strip(adapter, vf, false);
6941
6942         return 0;
6943 }
6944
6945 static int igb_ndo_set_vf_vlan(struct net_device *netdev, int vf,
6946                                u16 vlan, u8 qos, __be16 vlan_proto)
6947 {
6948         struct igb_adapter *adapter = netdev_priv(netdev);
6949
6950         if ((vf >= adapter->vfs_allocated_count) || (vlan > 4095) || (qos > 7))
6951                 return -EINVAL;
6952
6953         if (vlan_proto != htons(ETH_P_8021Q))
6954                 return -EPROTONOSUPPORT;
6955
6956         return (vlan || qos) ? igb_enable_port_vlan(adapter, vf, vlan, qos) :
6957                                igb_disable_port_vlan(adapter, vf);
6958 }
6959
6960 static int igb_set_vf_vlan_msg(struct igb_adapter *adapter, u32 *msgbuf, u32 vf)
6961 {
6962         int add = (msgbuf[0] & E1000_VT_MSGINFO_MASK) >> E1000_VT_MSGINFO_SHIFT;
6963         int vid = (msgbuf[1] & E1000_VLVF_VLANID_MASK);
6964         int ret;
6965
6966         if (adapter->vf_data[vf].pf_vlan)
6967                 return -1;
6968
6969         /* VLAN 0 is a special case, don't allow it to be removed */
6970         if (!vid && !add)
6971                 return 0;
6972
6973         ret = igb_set_vf_vlan(adapter, vid, !!add, vf);
6974         if (!ret)
6975                 igb_set_vf_vlan_strip(adapter, vf, !!vid);
6976         return ret;
6977 }
6978
6979 static inline void igb_vf_reset(struct igb_adapter *adapter, u32 vf)
6980 {
6981         struct vf_data_storage *vf_data = &adapter->vf_data[vf];
6982
6983         /* clear flags - except flag that indicates PF has set the MAC */
6984         vf_data->flags &= IGB_VF_FLAG_PF_SET_MAC;
6985         vf_data->last_nack = jiffies;
6986
6987         /* reset vlans for device */
6988         igb_clear_vf_vfta(adapter, vf);
6989         igb_set_vf_vlan(adapter, vf_data->pf_vlan, true, vf);
6990         igb_set_vmvir(adapter, vf_data->pf_vlan |
6991                                (vf_data->pf_qos << VLAN_PRIO_SHIFT), vf);
6992         igb_set_vmolr(adapter, vf, !vf_data->pf_vlan);
6993         igb_set_vf_vlan_strip(adapter, vf, !!(vf_data->pf_vlan));
6994
6995         /* reset multicast table array for vf */
6996         adapter->vf_data[vf].num_vf_mc_hashes = 0;
6997
6998         /* Flush and reset the mta with the new values */
6999         igb_set_rx_mode(adapter->netdev);
7000 }
7001
7002 static void igb_vf_reset_event(struct igb_adapter *adapter, u32 vf)
7003 {
7004         unsigned char *vf_mac = adapter->vf_data[vf].vf_mac_addresses;
7005
7006         /* clear mac address as we were hotplug removed/added */
7007         if (!(adapter->vf_data[vf].flags & IGB_VF_FLAG_PF_SET_MAC))
7008                 eth_zero_addr(vf_mac);
7009
7010         /* process remaining reset events */
7011         igb_vf_reset(adapter, vf);
7012 }
7013
7014 static void igb_vf_reset_msg(struct igb_adapter *adapter, u32 vf)
7015 {
7016         struct e1000_hw *hw = &adapter->hw;
7017         unsigned char *vf_mac = adapter->vf_data[vf].vf_mac_addresses;
7018         u32 reg, msgbuf[3];
7019         u8 *addr = (u8 *)(&msgbuf[1]);
7020
7021         /* process all the same items cleared in a function level reset */
7022         igb_vf_reset(adapter, vf);
7023
7024         /* set vf mac address */
7025         igb_set_vf_mac(adapter, vf, vf_mac);
7026
7027         /* enable transmit and receive for vf */
7028         reg = rd32(E1000_VFTE);
7029         wr32(E1000_VFTE, reg | BIT(vf));
7030         reg = rd32(E1000_VFRE);
7031         wr32(E1000_VFRE, reg | BIT(vf));
7032
7033         adapter->vf_data[vf].flags |= IGB_VF_FLAG_CTS;
7034
7035         /* reply to reset with ack and vf mac address */
7036         if (!is_zero_ether_addr(vf_mac)) {
7037                 msgbuf[0] = E1000_VF_RESET | E1000_VT_MSGTYPE_ACK;
7038                 memcpy(addr, vf_mac, ETH_ALEN);
7039         } else {
7040                 msgbuf[0] = E1000_VF_RESET | E1000_VT_MSGTYPE_NACK;
7041         }
7042         igb_write_mbx(hw, msgbuf, 3, vf);
7043 }
7044
7045 static void igb_flush_mac_table(struct igb_adapter *adapter)
7046 {
7047         struct e1000_hw *hw = &adapter->hw;
7048         int i;
7049
7050         for (i = 0; i < hw->mac.rar_entry_count; i++) {
7051                 adapter->mac_table[i].state &= ~IGB_MAC_STATE_IN_USE;
7052                 memset(adapter->mac_table[i].addr, 0, ETH_ALEN);
7053                 adapter->mac_table[i].queue = 0;
7054                 igb_rar_set_index(adapter, i);
7055         }
7056 }
7057
7058 static int igb_available_rars(struct igb_adapter *adapter, u8 queue)
7059 {
7060         struct e1000_hw *hw = &adapter->hw;
7061         /* do not count rar entries reserved for VFs MAC addresses */
7062         int rar_entries = hw->mac.rar_entry_count -
7063                           adapter->vfs_allocated_count;
7064         int i, count = 0;
7065
7066         for (i = 0; i < rar_entries; i++) {
7067                 /* do not count default entries */
7068                 if (adapter->mac_table[i].state & IGB_MAC_STATE_DEFAULT)
7069                         continue;
7070
7071                 /* do not count "in use" entries for different queues */
7072                 if ((adapter->mac_table[i].state & IGB_MAC_STATE_IN_USE) &&
7073                     (adapter->mac_table[i].queue != queue))
7074                         continue;
7075
7076                 count++;
7077         }
7078
7079         return count;
7080 }
7081
7082 /* Set default MAC address for the PF in the first RAR entry */
7083 static void igb_set_default_mac_filter(struct igb_adapter *adapter)
7084 {
7085         struct igb_mac_addr *mac_table = &adapter->mac_table[0];
7086
7087         ether_addr_copy(mac_table->addr, adapter->hw.mac.addr);
7088         mac_table->queue = adapter->vfs_allocated_count;
7089         mac_table->state = IGB_MAC_STATE_DEFAULT | IGB_MAC_STATE_IN_USE;
7090
7091         igb_rar_set_index(adapter, 0);
7092 }
7093
7094 /* If the filter to be added and an already existing filter express
7095  * the same address and address type, it should be possible to only
7096  * override the other configurations, for example the queue to steer
7097  * traffic.
7098  */
7099 static bool igb_mac_entry_can_be_used(const struct igb_mac_addr *entry,
7100                                       const u8 *addr, const u8 flags)
7101 {
7102         if (!(entry->state & IGB_MAC_STATE_IN_USE))
7103                 return true;
7104
7105         if ((entry->state & IGB_MAC_STATE_SRC_ADDR) !=
7106             (flags & IGB_MAC_STATE_SRC_ADDR))
7107                 return false;
7108
7109         if (!ether_addr_equal(addr, entry->addr))
7110                 return false;
7111
7112         return true;
7113 }
7114
7115 /* Add a MAC filter for 'addr' directing matching traffic to 'queue',
7116  * 'flags' is used to indicate what kind of match is made, match is by
7117  * default for the destination address, if matching by source address
7118  * is desired the flag IGB_MAC_STATE_SRC_ADDR can be used.
7119  */
7120 static int igb_add_mac_filter_flags(struct igb_adapter *adapter,
7121                                     const u8 *addr, const u8 queue,
7122                                     const u8 flags)
7123 {
7124         struct e1000_hw *hw = &adapter->hw;
7125         int rar_entries = hw->mac.rar_entry_count -
7126                           adapter->vfs_allocated_count;
7127         int i;
7128
7129         if (is_zero_ether_addr(addr))
7130                 return -EINVAL;
7131
7132         /* Search for the first empty entry in the MAC table.
7133          * Do not touch entries at the end of the table reserved for the VF MAC
7134          * addresses.
7135          */
7136         for (i = 0; i < rar_entries; i++) {
7137                 if (!igb_mac_entry_can_be_used(&adapter->mac_table[i],
7138                                                addr, flags))
7139                         continue;
7140
7141                 ether_addr_copy(adapter->mac_table[i].addr, addr);
7142                 adapter->mac_table[i].queue = queue;
7143                 adapter->mac_table[i].state |= IGB_MAC_STATE_IN_USE | flags;
7144
7145                 igb_rar_set_index(adapter, i);
7146                 return i;
7147         }
7148
7149         return -ENOSPC;
7150 }
7151
7152 static int igb_add_mac_filter(struct igb_adapter *adapter, const u8 *addr,
7153                               const u8 queue)
7154 {
7155         return igb_add_mac_filter_flags(adapter, addr, queue, 0);
7156 }
7157
7158 /* Remove a MAC filter for 'addr' directing matching traffic to
7159  * 'queue', 'flags' is used to indicate what kind of match need to be
7160  * removed, match is by default for the destination address, if
7161  * matching by source address is to be removed the flag
7162  * IGB_MAC_STATE_SRC_ADDR can be used.
7163  */
7164 static int igb_del_mac_filter_flags(struct igb_adapter *adapter,
7165                                     const u8 *addr, const u8 queue,
7166                                     const u8 flags)
7167 {
7168         struct e1000_hw *hw = &adapter->hw;
7169         int rar_entries = hw->mac.rar_entry_count -
7170                           adapter->vfs_allocated_count;
7171         int i;
7172
7173         if (is_zero_ether_addr(addr))
7174                 return -EINVAL;
7175
7176         /* Search for matching entry in the MAC table based on given address
7177          * and queue. Do not touch entries at the end of the table reserved
7178          * for the VF MAC addresses.
7179          */
7180         for (i = 0; i < rar_entries; i++) {
7181                 if (!(adapter->mac_table[i].state & IGB_MAC_STATE_IN_USE))
7182                         continue;
7183                 if ((adapter->mac_table[i].state & flags) != flags)
7184                         continue;
7185                 if (adapter->mac_table[i].queue != queue)
7186                         continue;
7187                 if (!ether_addr_equal(adapter->mac_table[i].addr, addr))
7188                         continue;
7189
7190                 /* When a filter for the default address is "deleted",
7191                  * we return it to its initial configuration
7192                  */
7193                 if (adapter->mac_table[i].state & IGB_MAC_STATE_DEFAULT) {
7194                         adapter->mac_table[i].state =
7195                                 IGB_MAC_STATE_DEFAULT | IGB_MAC_STATE_IN_USE;
7196                         adapter->mac_table[i].queue =
7197                                 adapter->vfs_allocated_count;
7198                 } else {
7199                         adapter->mac_table[i].state = 0;
7200                         adapter->mac_table[i].queue = 0;
7201                         memset(adapter->mac_table[i].addr, 0, ETH_ALEN);
7202                 }
7203
7204                 igb_rar_set_index(adapter, i);
7205                 return 0;
7206         }
7207
7208         return -ENOENT;
7209 }
7210
7211 static int igb_del_mac_filter(struct igb_adapter *adapter, const u8 *addr,
7212                               const u8 queue)
7213 {
7214         return igb_del_mac_filter_flags(adapter, addr, queue, 0);
7215 }
7216
7217 int igb_add_mac_steering_filter(struct igb_adapter *adapter,
7218                                 const u8 *addr, u8 queue, u8 flags)
7219 {
7220         struct e1000_hw *hw = &adapter->hw;
7221
7222         /* In theory, this should be supported on 82575 as well, but
7223          * that part wasn't easily accessible during development.
7224          */
7225         if (hw->mac.type != e1000_i210)
7226                 return -EOPNOTSUPP;
7227
7228         return igb_add_mac_filter_flags(adapter, addr, queue,
7229                                         IGB_MAC_STATE_QUEUE_STEERING | flags);
7230 }
7231
7232 int igb_del_mac_steering_filter(struct igb_adapter *adapter,
7233                                 const u8 *addr, u8 queue, u8 flags)
7234 {
7235         return igb_del_mac_filter_flags(adapter, addr, queue,
7236                                         IGB_MAC_STATE_QUEUE_STEERING | flags);
7237 }
7238
7239 static int igb_uc_sync(struct net_device *netdev, const unsigned char *addr)
7240 {
7241         struct igb_adapter *adapter = netdev_priv(netdev);
7242         int ret;
7243
7244         ret = igb_add_mac_filter(adapter, addr, adapter->vfs_allocated_count);
7245
7246         return min_t(int, ret, 0);
7247 }
7248
7249 static int igb_uc_unsync(struct net_device *netdev, const unsigned char *addr)
7250 {
7251         struct igb_adapter *adapter = netdev_priv(netdev);
7252
7253         igb_del_mac_filter(adapter, addr, adapter->vfs_allocated_count);
7254
7255         return 0;
7256 }
7257
7258 static int igb_set_vf_mac_filter(struct igb_adapter *adapter, const int vf,
7259                                  const u32 info, const u8 *addr)
7260 {
7261         struct pci_dev *pdev = adapter->pdev;
7262         struct vf_data_storage *vf_data = &adapter->vf_data[vf];
7263         struct list_head *pos;
7264         struct vf_mac_filter *entry = NULL;
7265         int ret = 0;
7266
7267         switch (info) {
7268         case E1000_VF_MAC_FILTER_CLR:
7269                 /* remove all unicast MAC filters related to the current VF */
7270                 list_for_each(pos, &adapter->vf_macs.l) {
7271                         entry = list_entry(pos, struct vf_mac_filter, l);
7272                         if (entry->vf == vf) {
7273                                 entry->vf = -1;
7274                                 entry->free = true;
7275                                 igb_del_mac_filter(adapter, entry->vf_mac, vf);
7276                         }
7277                 }
7278                 break;
7279         case E1000_VF_MAC_FILTER_ADD:
7280                 if ((vf_data->flags & IGB_VF_FLAG_PF_SET_MAC) &&
7281                     !vf_data->trusted) {
7282                         dev_warn(&pdev->dev,
7283                                  "VF %d requested MAC filter but is administratively denied\n",
7284                                  vf);
7285                         return -EINVAL;
7286                 }
7287                 if (!is_valid_ether_addr(addr)) {
7288                         dev_warn(&pdev->dev,
7289                                  "VF %d attempted to set invalid MAC filter\n",
7290                                  vf);
7291                         return -EINVAL;
7292                 }
7293
7294                 /* try to find empty slot in the list */
7295                 list_for_each(pos, &adapter->vf_macs.l) {
7296                         entry = list_entry(pos, struct vf_mac_filter, l);
7297                         if (entry->free)
7298                                 break;
7299                 }
7300
7301                 if (entry && entry->free) {
7302                         entry->free = false;
7303                         entry->vf = vf;
7304                         ether_addr_copy(entry->vf_mac, addr);
7305
7306                         ret = igb_add_mac_filter(adapter, addr, vf);
7307                         ret = min_t(int, ret, 0);
7308                 } else {
7309                         ret = -ENOSPC;
7310                 }
7311
7312                 if (ret == -ENOSPC)
7313                         dev_warn(&pdev->dev,
7314                                  "VF %d has requested MAC filter but there is no space for it\n",
7315                                  vf);
7316                 break;
7317         default:
7318                 ret = -EINVAL;
7319                 break;
7320         }
7321
7322         return ret;
7323 }
7324
7325 static int igb_set_vf_mac_addr(struct igb_adapter *adapter, u32 *msg, int vf)
7326 {
7327         struct pci_dev *pdev = adapter->pdev;
7328         struct vf_data_storage *vf_data = &adapter->vf_data[vf];
7329         u32 info = msg[0] & E1000_VT_MSGINFO_MASK;
7330
7331         /* The VF MAC Address is stored in a packed array of bytes
7332          * starting at the second 32 bit word of the msg array
7333          */
7334         unsigned char *addr = (unsigned char *)&msg[1];
7335         int ret = 0;
7336
7337         if (!info) {
7338                 if ((vf_data->flags & IGB_VF_FLAG_PF_SET_MAC) &&
7339                     !vf_data->trusted) {
7340                         dev_warn(&pdev->dev,
7341                                  "VF %d attempted to override administratively set MAC address\nReload the VF driver to resume operations\n",
7342                                  vf);
7343                         return -EINVAL;
7344                 }
7345
7346                 if (!is_valid_ether_addr(addr)) {
7347                         dev_warn(&pdev->dev,
7348                                  "VF %d attempted to set invalid MAC\n",
7349                                  vf);
7350                         return -EINVAL;
7351                 }
7352
7353                 ret = igb_set_vf_mac(adapter, vf, addr);
7354         } else {
7355                 ret = igb_set_vf_mac_filter(adapter, vf, info, addr);
7356         }
7357
7358         return ret;
7359 }
7360
7361 static void igb_rcv_ack_from_vf(struct igb_adapter *adapter, u32 vf)
7362 {
7363         struct e1000_hw *hw = &adapter->hw;
7364         struct vf_data_storage *vf_data = &adapter->vf_data[vf];
7365         u32 msg = E1000_VT_MSGTYPE_NACK;
7366
7367         /* if device isn't clear to send it shouldn't be reading either */
7368         if (!(vf_data->flags & IGB_VF_FLAG_CTS) &&
7369             time_after(jiffies, vf_data->last_nack + (2 * HZ))) {
7370                 igb_write_mbx(hw, &msg, 1, vf);
7371                 vf_data->last_nack = jiffies;
7372         }
7373 }
7374
7375 static void igb_rcv_msg_from_vf(struct igb_adapter *adapter, u32 vf)
7376 {
7377         struct pci_dev *pdev = adapter->pdev;
7378         u32 msgbuf[E1000_VFMAILBOX_SIZE];
7379         struct e1000_hw *hw = &adapter->hw;
7380         struct vf_data_storage *vf_data = &adapter->vf_data[vf];
7381         s32 retval;
7382
7383         retval = igb_read_mbx(hw, msgbuf, E1000_VFMAILBOX_SIZE, vf, false);
7384
7385         if (retval) {
7386                 /* if receive failed revoke VF CTS stats and restart init */
7387                 dev_err(&pdev->dev, "Error receiving message from VF\n");
7388                 vf_data->flags &= ~IGB_VF_FLAG_CTS;
7389                 if (!time_after(jiffies, vf_data->last_nack + (2 * HZ)))
7390                         goto unlock;
7391                 goto out;
7392         }
7393
7394         /* this is a message we already processed, do nothing */
7395         if (msgbuf[0] & (E1000_VT_MSGTYPE_ACK | E1000_VT_MSGTYPE_NACK))
7396                 goto unlock;
7397
7398         /* until the vf completes a reset it should not be
7399          * allowed to start any configuration.
7400          */
7401         if (msgbuf[0] == E1000_VF_RESET) {
7402                 /* unlocks mailbox */
7403                 igb_vf_reset_msg(adapter, vf);
7404                 return;
7405         }
7406
7407         if (!(vf_data->flags & IGB_VF_FLAG_CTS)) {
7408                 if (!time_after(jiffies, vf_data->last_nack + (2 * HZ)))
7409                         goto unlock;
7410                 retval = -1;
7411                 goto out;
7412         }
7413
7414         switch ((msgbuf[0] & 0xFFFF)) {
7415         case E1000_VF_SET_MAC_ADDR:
7416                 retval = igb_set_vf_mac_addr(adapter, msgbuf, vf);
7417                 break;
7418         case E1000_VF_SET_PROMISC:
7419                 retval = igb_set_vf_promisc(adapter, msgbuf, vf);
7420                 break;
7421         case E1000_VF_SET_MULTICAST:
7422                 retval = igb_set_vf_multicasts(adapter, msgbuf, vf);
7423                 break;
7424         case E1000_VF_SET_LPE:
7425                 retval = igb_set_vf_rlpml(adapter, msgbuf[1], vf);
7426                 break;
7427         case E1000_VF_SET_VLAN:
7428                 retval = -1;
7429                 if (vf_data->pf_vlan)
7430                         dev_warn(&pdev->dev,
7431                                  "VF %d attempted to override administratively set VLAN tag\nReload the VF driver to resume operations\n",
7432                                  vf);
7433                 else
7434                         retval = igb_set_vf_vlan_msg(adapter, msgbuf, vf);
7435                 break;
7436         default:
7437                 dev_err(&pdev->dev, "Unhandled Msg %08x\n", msgbuf[0]);
7438                 retval = -1;
7439                 break;
7440         }
7441
7442         msgbuf[0] |= E1000_VT_MSGTYPE_CTS;
7443 out:
7444         /* notify the VF of the results of what it sent us */
7445         if (retval)
7446                 msgbuf[0] |= E1000_VT_MSGTYPE_NACK;
7447         else
7448                 msgbuf[0] |= E1000_VT_MSGTYPE_ACK;
7449
7450         /* unlocks mailbox */
7451         igb_write_mbx(hw, msgbuf, 1, vf);
7452         return;
7453
7454 unlock:
7455         igb_unlock_mbx(hw, vf);
7456 }
7457
7458 static void igb_msg_task(struct igb_adapter *adapter)
7459 {
7460         struct e1000_hw *hw = &adapter->hw;
7461         u32 vf;
7462
7463         for (vf = 0; vf < adapter->vfs_allocated_count; vf++) {
7464                 /* process any reset requests */
7465                 if (!igb_check_for_rst(hw, vf))
7466                         igb_vf_reset_event(adapter, vf);
7467
7468                 /* process any messages pending */
7469                 if (!igb_check_for_msg(hw, vf))
7470                         igb_rcv_msg_from_vf(adapter, vf);
7471
7472                 /* process any acks */
7473                 if (!igb_check_for_ack(hw, vf))
7474                         igb_rcv_ack_from_vf(adapter, vf);
7475         }
7476 }
7477
7478 /**
7479  *  igb_set_uta - Set unicast filter table address
7480  *  @adapter: board private structure
7481  *  @set: boolean indicating if we are setting or clearing bits
7482  *
7483  *  The unicast table address is a register array of 32-bit registers.
7484  *  The table is meant to be used in a way similar to how the MTA is used
7485  *  however due to certain limitations in the hardware it is necessary to
7486  *  set all the hash bits to 1 and use the VMOLR ROPE bit as a promiscuous
7487  *  enable bit to allow vlan tag stripping when promiscuous mode is enabled
7488  **/
7489 static void igb_set_uta(struct igb_adapter *adapter, bool set)
7490 {
7491         struct e1000_hw *hw = &adapter->hw;
7492         u32 uta = set ? ~0 : 0;
7493         int i;
7494
7495         /* we only need to do this if VMDq is enabled */
7496         if (!adapter->vfs_allocated_count)
7497                 return;
7498
7499         for (i = hw->mac.uta_reg_count; i--;)
7500                 array_wr32(E1000_UTA, i, uta);
7501 }
7502
7503 /**
7504  *  igb_intr_msi - Interrupt Handler
7505  *  @irq: interrupt number
7506  *  @data: pointer to a network interface device structure
7507  **/
7508 static irqreturn_t igb_intr_msi(int irq, void *data)
7509 {
7510         struct igb_adapter *adapter = data;
7511         struct igb_q_vector *q_vector = adapter->q_vector[0];
7512         struct e1000_hw *hw = &adapter->hw;
7513         /* read ICR disables interrupts using IAM */
7514         u32 icr = rd32(E1000_ICR);
7515
7516         igb_write_itr(q_vector);
7517
7518         if (icr & E1000_ICR_DRSTA)
7519                 schedule_work(&adapter->reset_task);
7520
7521         if (icr & E1000_ICR_DOUTSYNC) {
7522                 /* HW is reporting DMA is out of sync */
7523                 adapter->stats.doosync++;
7524         }
7525
7526         if (icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) {
7527                 hw->mac.get_link_status = 1;
7528                 if (!test_bit(__IGB_DOWN, &adapter->state))
7529                         mod_timer(&adapter->watchdog_timer, jiffies + 1);
7530         }
7531
7532         if (icr & E1000_ICR_TS)
7533                 igb_tsync_interrupt(adapter);
7534
7535         napi_schedule(&q_vector->napi);
7536
7537         return IRQ_HANDLED;
7538 }
7539
7540 /**
7541  *  igb_intr - Legacy Interrupt Handler
7542  *  @irq: interrupt number
7543  *  @data: pointer to a network interface device structure
7544  **/
7545 static irqreturn_t igb_intr(int irq, void *data)
7546 {
7547         struct igb_adapter *adapter = data;
7548         struct igb_q_vector *q_vector = adapter->q_vector[0];
7549         struct e1000_hw *hw = &adapter->hw;
7550         /* Interrupt Auto-Mask...upon reading ICR, interrupts are masked.  No
7551          * need for the IMC write
7552          */
7553         u32 icr = rd32(E1000_ICR);
7554
7555         /* IMS will not auto-mask if INT_ASSERTED is not set, and if it is
7556          * not set, then the adapter didn't send an interrupt
7557          */
7558         if (!(icr & E1000_ICR_INT_ASSERTED))
7559                 return IRQ_NONE;
7560
7561         igb_write_itr(q_vector);
7562
7563         if (icr & E1000_ICR_DRSTA)
7564                 schedule_work(&adapter->reset_task);
7565
7566         if (icr & E1000_ICR_DOUTSYNC) {
7567                 /* HW is reporting DMA is out of sync */
7568                 adapter->stats.doosync++;
7569         }
7570
7571         if (icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) {
7572                 hw->mac.get_link_status = 1;
7573                 /* guard against interrupt when we're going down */
7574                 if (!test_bit(__IGB_DOWN, &adapter->state))
7575                         mod_timer(&adapter->watchdog_timer, jiffies + 1);
7576         }
7577
7578         if (icr & E1000_ICR_TS)
7579                 igb_tsync_interrupt(adapter);
7580
7581         napi_schedule(&q_vector->napi);
7582
7583         return IRQ_HANDLED;
7584 }
7585
7586 static void igb_ring_irq_enable(struct igb_q_vector *q_vector)
7587 {
7588         struct igb_adapter *adapter = q_vector->adapter;
7589         struct e1000_hw *hw = &adapter->hw;
7590
7591         if ((q_vector->rx.ring && (adapter->rx_itr_setting & 3)) ||
7592             (!q_vector->rx.ring && (adapter->tx_itr_setting & 3))) {
7593                 if ((adapter->num_q_vectors == 1) && !adapter->vf_data)
7594                         igb_set_itr(q_vector);
7595                 else
7596                         igb_update_ring_itr(q_vector);
7597         }
7598
7599         if (!test_bit(__IGB_DOWN, &adapter->state)) {
7600                 if (adapter->flags & IGB_FLAG_HAS_MSIX)
7601                         wr32(E1000_EIMS, q_vector->eims_value);
7602                 else
7603                         igb_irq_enable(adapter);
7604         }
7605 }
7606
7607 /**
7608  *  igb_poll - NAPI Rx polling callback
7609  *  @napi: napi polling structure
7610  *  @budget: count of how many packets we should handle
7611  **/
7612 static int igb_poll(struct napi_struct *napi, int budget)
7613 {
7614         struct igb_q_vector *q_vector = container_of(napi,
7615                                                      struct igb_q_vector,
7616                                                      napi);
7617         bool clean_complete = true;
7618         int work_done = 0;
7619
7620 #ifdef CONFIG_IGB_DCA
7621         if (q_vector->adapter->flags & IGB_FLAG_DCA_ENABLED)
7622                 igb_update_dca(q_vector);
7623 #endif
7624         if (q_vector->tx.ring)
7625                 clean_complete = igb_clean_tx_irq(q_vector, budget);
7626
7627         if (q_vector->rx.ring) {
7628                 int cleaned = igb_clean_rx_irq(q_vector, budget);
7629
7630                 work_done += cleaned;
7631                 if (cleaned >= budget)
7632                         clean_complete = false;
7633         }
7634
7635         /* If all work not completed, return budget and keep polling */
7636         if (!clean_complete)
7637                 return budget;
7638
7639         /* If not enough Rx work done, exit the polling mode */
7640         napi_complete_done(napi, work_done);
7641         igb_ring_irq_enable(q_vector);
7642
7643         return 0;
7644 }
7645
7646 /**
7647  *  igb_clean_tx_irq - Reclaim resources after transmit completes
7648  *  @q_vector: pointer to q_vector containing needed info
7649  *  @napi_budget: Used to determine if we are in netpoll
7650  *
7651  *  returns true if ring is completely cleaned
7652  **/
7653 static bool igb_clean_tx_irq(struct igb_q_vector *q_vector, int napi_budget)
7654 {
7655         struct igb_adapter *adapter = q_vector->adapter;
7656         struct igb_ring *tx_ring = q_vector->tx.ring;
7657         struct igb_tx_buffer *tx_buffer;
7658         union e1000_adv_tx_desc *tx_desc;
7659         unsigned int total_bytes = 0, total_packets = 0;
7660         unsigned int budget = q_vector->tx.work_limit;
7661         unsigned int i = tx_ring->next_to_clean;
7662
7663         if (test_bit(__IGB_DOWN, &adapter->state))
7664                 return true;
7665
7666         tx_buffer = &tx_ring->tx_buffer_info[i];
7667         tx_desc = IGB_TX_DESC(tx_ring, i);
7668         i -= tx_ring->count;
7669
7670         do {
7671                 union e1000_adv_tx_desc *eop_desc = tx_buffer->next_to_watch;
7672
7673                 /* if next_to_watch is not set then there is no work pending */
7674                 if (!eop_desc)
7675                         break;
7676
7677                 /* prevent any other reads prior to eop_desc */
7678                 smp_rmb();
7679
7680                 /* if DD is not set pending work has not been completed */
7681                 if (!(eop_desc->wb.status & cpu_to_le32(E1000_TXD_STAT_DD)))
7682                         break;
7683
7684                 /* clear next_to_watch to prevent false hangs */
7685                 tx_buffer->next_to_watch = NULL;
7686
7687                 /* update the statistics for this packet */
7688                 total_bytes += tx_buffer->bytecount;
7689                 total_packets += tx_buffer->gso_segs;
7690
7691                 /* free the skb */
7692                 napi_consume_skb(tx_buffer->skb, napi_budget);
7693
7694                 /* unmap skb header data */
7695                 dma_unmap_single(tx_ring->dev,
7696                                  dma_unmap_addr(tx_buffer, dma),
7697                                  dma_unmap_len(tx_buffer, len),
7698                                  DMA_TO_DEVICE);
7699
7700                 /* clear tx_buffer data */
7701                 dma_unmap_len_set(tx_buffer, len, 0);
7702
7703                 /* clear last DMA location and unmap remaining buffers */
7704                 while (tx_desc != eop_desc) {
7705                         tx_buffer++;
7706                         tx_desc++;
7707                         i++;
7708                         if (unlikely(!i)) {
7709                                 i -= tx_ring->count;
7710                                 tx_buffer = tx_ring->tx_buffer_info;
7711                                 tx_desc = IGB_TX_DESC(tx_ring, 0);
7712                         }
7713
7714                         /* unmap any remaining paged data */
7715                         if (dma_unmap_len(tx_buffer, len)) {
7716                                 dma_unmap_page(tx_ring->dev,
7717                                                dma_unmap_addr(tx_buffer, dma),
7718                                                dma_unmap_len(tx_buffer, len),
7719                                                DMA_TO_DEVICE);
7720                                 dma_unmap_len_set(tx_buffer, len, 0);
7721                         }
7722                 }
7723
7724                 /* move us one more past the eop_desc for start of next pkt */
7725                 tx_buffer++;
7726                 tx_desc++;
7727                 i++;
7728                 if (unlikely(!i)) {
7729                         i -= tx_ring->count;
7730                         tx_buffer = tx_ring->tx_buffer_info;
7731                         tx_desc = IGB_TX_DESC(tx_ring, 0);
7732                 }
7733
7734                 /* issue prefetch for next Tx descriptor */
7735                 prefetch(tx_desc);
7736
7737                 /* update budget accounting */
7738                 budget--;
7739         } while (likely(budget));
7740
7741         netdev_tx_completed_queue(txring_txq(tx_ring),
7742                                   total_packets, total_bytes);
7743         i += tx_ring->count;
7744         tx_ring->next_to_clean = i;
7745         u64_stats_update_begin(&tx_ring->tx_syncp);
7746         tx_ring->tx_stats.bytes += total_bytes;
7747         tx_ring->tx_stats.packets += total_packets;
7748         u64_stats_update_end(&tx_ring->tx_syncp);
7749         q_vector->tx.total_bytes += total_bytes;
7750         q_vector->tx.total_packets += total_packets;
7751
7752         if (test_bit(IGB_RING_FLAG_TX_DETECT_HANG, &tx_ring->flags)) {
7753                 struct e1000_hw *hw = &adapter->hw;
7754
7755                 /* Detect a transmit hang in hardware, this serializes the
7756                  * check with the clearing of time_stamp and movement of i
7757                  */
7758                 clear_bit(IGB_RING_FLAG_TX_DETECT_HANG, &tx_ring->flags);
7759                 if (tx_buffer->next_to_watch &&
7760                     time_after(jiffies, tx_buffer->time_stamp +
7761                                (adapter->tx_timeout_factor * HZ)) &&
7762                     !(rd32(E1000_STATUS) & E1000_STATUS_TXOFF)) {
7763
7764                         /* detected Tx unit hang */
7765                         dev_err(tx_ring->dev,
7766                                 "Detected Tx Unit Hang\n"
7767                                 "  Tx Queue             <%d>\n"
7768                                 "  TDH                  <%x>\n"
7769                                 "  TDT                  <%x>\n"
7770                                 "  next_to_use          <%x>\n"
7771                                 "  next_to_clean        <%x>\n"
7772                                 "buffer_info[next_to_clean]\n"
7773                                 "  time_stamp           <%lx>\n"
7774                                 "  next_to_watch        <%p>\n"
7775                                 "  jiffies              <%lx>\n"
7776                                 "  desc.status          <%x>\n",
7777                                 tx_ring->queue_index,
7778                                 rd32(E1000_TDH(tx_ring->reg_idx)),
7779                                 readl(tx_ring->tail),
7780                                 tx_ring->next_to_use,
7781                                 tx_ring->next_to_clean,
7782                                 tx_buffer->time_stamp,
7783                                 tx_buffer->next_to_watch,
7784                                 jiffies,
7785                                 tx_buffer->next_to_watch->wb.status);
7786                         netif_stop_subqueue(tx_ring->netdev,
7787                                             tx_ring->queue_index);
7788
7789                         /* we are about to reset, no point in enabling stuff */
7790                         return true;
7791                 }
7792         }
7793
7794 #define TX_WAKE_THRESHOLD (DESC_NEEDED * 2)
7795         if (unlikely(total_packets &&
7796             netif_carrier_ok(tx_ring->netdev) &&
7797             igb_desc_unused(tx_ring) >= TX_WAKE_THRESHOLD)) {
7798                 /* Make sure that anybody stopping the queue after this
7799                  * sees the new next_to_clean.
7800                  */
7801                 smp_mb();
7802                 if (__netif_subqueue_stopped(tx_ring->netdev,
7803                                              tx_ring->queue_index) &&
7804                     !(test_bit(__IGB_DOWN, &adapter->state))) {
7805                         netif_wake_subqueue(tx_ring->netdev,
7806                                             tx_ring->queue_index);
7807
7808                         u64_stats_update_begin(&tx_ring->tx_syncp);
7809                         tx_ring->tx_stats.restart_queue++;
7810                         u64_stats_update_end(&tx_ring->tx_syncp);
7811                 }
7812         }
7813
7814         return !!budget;
7815 }
7816
7817 /**
7818  *  igb_reuse_rx_page - page flip buffer and store it back on the ring
7819  *  @rx_ring: rx descriptor ring to store buffers on
7820  *  @old_buff: donor buffer to have page reused
7821  *
7822  *  Synchronizes page for reuse by the adapter
7823  **/
7824 static void igb_reuse_rx_page(struct igb_ring *rx_ring,
7825                               struct igb_rx_buffer *old_buff)
7826 {
7827         struct igb_rx_buffer *new_buff;
7828         u16 nta = rx_ring->next_to_alloc;
7829
7830         new_buff = &rx_ring->rx_buffer_info[nta];
7831
7832         /* update, and store next to alloc */
7833         nta++;
7834         rx_ring->next_to_alloc = (nta < rx_ring->count) ? nta : 0;
7835
7836         /* Transfer page from old buffer to new buffer.
7837          * Move each member individually to avoid possible store
7838          * forwarding stalls.
7839          */
7840         new_buff->dma           = old_buff->dma;
7841         new_buff->page          = old_buff->page;
7842         new_buff->page_offset   = old_buff->page_offset;
7843         new_buff->pagecnt_bias  = old_buff->pagecnt_bias;
7844 }
7845
7846 static inline bool igb_page_is_reserved(struct page *page)
7847 {
7848         return (page_to_nid(page) != numa_mem_id()) || page_is_pfmemalloc(page);
7849 }
7850
7851 static bool igb_can_reuse_rx_page(struct igb_rx_buffer *rx_buffer)
7852 {
7853         unsigned int pagecnt_bias = rx_buffer->pagecnt_bias;
7854         struct page *page = rx_buffer->page;
7855
7856         /* avoid re-using remote pages */
7857         if (unlikely(igb_page_is_reserved(page)))
7858                 return false;
7859
7860 #if (PAGE_SIZE < 8192)
7861         /* if we are only owner of page we can reuse it */
7862         if (unlikely((page_ref_count(page) - pagecnt_bias) > 1))
7863                 return false;
7864 #else
7865 #define IGB_LAST_OFFSET \
7866         (SKB_WITH_OVERHEAD(PAGE_SIZE) - IGB_RXBUFFER_2048)
7867
7868         if (rx_buffer->page_offset > IGB_LAST_OFFSET)
7869                 return false;
7870 #endif
7871
7872         /* If we have drained the page fragment pool we need to update
7873          * the pagecnt_bias and page count so that we fully restock the
7874          * number of references the driver holds.
7875          */
7876         if (unlikely(!pagecnt_bias)) {
7877                 page_ref_add(page, USHRT_MAX);
7878                 rx_buffer->pagecnt_bias = USHRT_MAX;
7879         }
7880
7881         return true;
7882 }
7883
7884 /**
7885  *  igb_add_rx_frag - Add contents of Rx buffer to sk_buff
7886  *  @rx_ring: rx descriptor ring to transact packets on
7887  *  @rx_buffer: buffer containing page to add
7888  *  @skb: sk_buff to place the data into
7889  *  @size: size of buffer to be added
7890  *
7891  *  This function will add the data contained in rx_buffer->page to the skb.
7892  **/
7893 static void igb_add_rx_frag(struct igb_ring *rx_ring,
7894                             struct igb_rx_buffer *rx_buffer,
7895                             struct sk_buff *skb,
7896                             unsigned int size)
7897 {
7898 #if (PAGE_SIZE < 8192)
7899         unsigned int truesize = igb_rx_pg_size(rx_ring) / 2;
7900 #else
7901         unsigned int truesize = ring_uses_build_skb(rx_ring) ?
7902                                 SKB_DATA_ALIGN(IGB_SKB_PAD + size) :
7903                                 SKB_DATA_ALIGN(size);
7904 #endif
7905         skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, rx_buffer->page,
7906                         rx_buffer->page_offset, size, truesize);
7907 #if (PAGE_SIZE < 8192)
7908         rx_buffer->page_offset ^= truesize;
7909 #else
7910         rx_buffer->page_offset += truesize;
7911 #endif
7912 }
7913
7914 static struct sk_buff *igb_construct_skb(struct igb_ring *rx_ring,
7915                                          struct igb_rx_buffer *rx_buffer,
7916                                          union e1000_adv_rx_desc *rx_desc,
7917                                          unsigned int size)
7918 {
7919         void *va = page_address(rx_buffer->page) + rx_buffer->page_offset;
7920 #if (PAGE_SIZE < 8192)
7921         unsigned int truesize = igb_rx_pg_size(rx_ring) / 2;
7922 #else
7923         unsigned int truesize = SKB_DATA_ALIGN(size);
7924 #endif
7925         unsigned int headlen;
7926         struct sk_buff *skb;
7927
7928         /* prefetch first cache line of first page */
7929         prefetch(va);
7930 #if L1_CACHE_BYTES < 128
7931         prefetch(va + L1_CACHE_BYTES);
7932 #endif
7933
7934         /* allocate a skb to store the frags */
7935         skb = napi_alloc_skb(&rx_ring->q_vector->napi, IGB_RX_HDR_LEN);
7936         if (unlikely(!skb))
7937                 return NULL;
7938
7939         if (unlikely(igb_test_staterr(rx_desc, E1000_RXDADV_STAT_TSIP))) {
7940                 igb_ptp_rx_pktstamp(rx_ring->q_vector, va, skb);
7941                 va += IGB_TS_HDR_LEN;
7942                 size -= IGB_TS_HDR_LEN;
7943         }
7944
7945         /* Determine available headroom for copy */
7946         headlen = size;
7947         if (headlen > IGB_RX_HDR_LEN)
7948                 headlen = eth_get_headlen(va, IGB_RX_HDR_LEN);
7949
7950         /* align pull length to size of long to optimize memcpy performance */
7951         memcpy(__skb_put(skb, headlen), va, ALIGN(headlen, sizeof(long)));
7952
7953         /* update all of the pointers */
7954         size -= headlen;
7955         if (size) {
7956                 skb_add_rx_frag(skb, 0, rx_buffer->page,
7957                                 (va + headlen) - page_address(rx_buffer->page),
7958                                 size, truesize);
7959 #if (PAGE_SIZE < 8192)
7960                 rx_buffer->page_offset ^= truesize;
7961 #else
7962                 rx_buffer->page_offset += truesize;
7963 #endif
7964         } else {
7965                 rx_buffer->pagecnt_bias++;
7966         }
7967
7968         return skb;
7969 }
7970
7971 static struct sk_buff *igb_build_skb(struct igb_ring *rx_ring,
7972                                      struct igb_rx_buffer *rx_buffer,
7973                                      union e1000_adv_rx_desc *rx_desc,
7974                                      unsigned int size)
7975 {
7976         void *va = page_address(rx_buffer->page) + rx_buffer->page_offset;
7977 #if (PAGE_SIZE < 8192)
7978         unsigned int truesize = igb_rx_pg_size(rx_ring) / 2;
7979 #else
7980         unsigned int truesize = SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) +
7981                                 SKB_DATA_ALIGN(IGB_SKB_PAD + size);
7982 #endif
7983         struct sk_buff *skb;
7984
7985         /* prefetch first cache line of first page */
7986         prefetch(va);
7987 #if L1_CACHE_BYTES < 128
7988         prefetch(va + L1_CACHE_BYTES);
7989 #endif
7990
7991         /* build an skb around the page buffer */
7992         skb = build_skb(va - IGB_SKB_PAD, truesize);
7993         if (unlikely(!skb))
7994                 return NULL;
7995
7996         /* update pointers within the skb to store the data */
7997         skb_reserve(skb, IGB_SKB_PAD);
7998         __skb_put(skb, size);
7999
8000         /* pull timestamp out of packet data */
8001         if (igb_test_staterr(rx_desc, E1000_RXDADV_STAT_TSIP)) {
8002                 igb_ptp_rx_pktstamp(rx_ring->q_vector, skb->data, skb);
8003                 __skb_pull(skb, IGB_TS_HDR_LEN);
8004         }
8005
8006         /* update buffer offset */
8007 #if (PAGE_SIZE < 8192)
8008         rx_buffer->page_offset ^= truesize;
8009 #else
8010         rx_buffer->page_offset += truesize;
8011 #endif
8012
8013         return skb;
8014 }
8015
8016 static inline void igb_rx_checksum(struct igb_ring *ring,
8017                                    union e1000_adv_rx_desc *rx_desc,
8018                                    struct sk_buff *skb)
8019 {
8020         skb_checksum_none_assert(skb);
8021
8022         /* Ignore Checksum bit is set */
8023         if (igb_test_staterr(rx_desc, E1000_RXD_STAT_IXSM))
8024                 return;
8025
8026         /* Rx checksum disabled via ethtool */
8027         if (!(ring->netdev->features & NETIF_F_RXCSUM))
8028                 return;
8029
8030         /* TCP/UDP checksum error bit is set */
8031         if (igb_test_staterr(rx_desc,
8032                              E1000_RXDEXT_STATERR_TCPE |
8033                              E1000_RXDEXT_STATERR_IPE)) {
8034                 /* work around errata with sctp packets where the TCPE aka
8035                  * L4E bit is set incorrectly on 64 byte (60 byte w/o crc)
8036                  * packets, (aka let the stack check the crc32c)
8037                  */
8038                 if (!((skb->len == 60) &&
8039                       test_bit(IGB_RING_FLAG_RX_SCTP_CSUM, &ring->flags))) {
8040                         u64_stats_update_begin(&ring->rx_syncp);
8041                         ring->rx_stats.csum_err++;
8042                         u64_stats_update_end(&ring->rx_syncp);
8043                 }
8044                 /* let the stack verify checksum errors */
8045                 return;
8046         }
8047         /* It must be a TCP or UDP packet with a valid checksum */
8048         if (igb_test_staterr(rx_desc, E1000_RXD_STAT_TCPCS |
8049                                       E1000_RXD_STAT_UDPCS))
8050                 skb->ip_summed = CHECKSUM_UNNECESSARY;
8051
8052         dev_dbg(ring->dev, "cksum success: bits %08X\n",
8053                 le32_to_cpu(rx_desc->wb.upper.status_error));
8054 }
8055
8056 static inline void igb_rx_hash(struct igb_ring *ring,
8057                                union e1000_adv_rx_desc *rx_desc,
8058                                struct sk_buff *skb)
8059 {
8060         if (ring->netdev->features & NETIF_F_RXHASH)
8061                 skb_set_hash(skb,
8062                              le32_to_cpu(rx_desc->wb.lower.hi_dword.rss),
8063                              PKT_HASH_TYPE_L3);
8064 }
8065
8066 /**
8067  *  igb_is_non_eop - process handling of non-EOP buffers
8068  *  @rx_ring: Rx ring being processed
8069  *  @rx_desc: Rx descriptor for current buffer
8070  *  @skb: current socket buffer containing buffer in progress
8071  *
8072  *  This function updates next to clean.  If the buffer is an EOP buffer
8073  *  this function exits returning false, otherwise it will place the
8074  *  sk_buff in the next buffer to be chained and return true indicating
8075  *  that this is in fact a non-EOP buffer.
8076  **/
8077 static bool igb_is_non_eop(struct igb_ring *rx_ring,
8078                            union e1000_adv_rx_desc *rx_desc)
8079 {
8080         u32 ntc = rx_ring->next_to_clean + 1;
8081
8082         /* fetch, update, and store next to clean */
8083         ntc = (ntc < rx_ring->count) ? ntc : 0;
8084         rx_ring->next_to_clean = ntc;
8085
8086         prefetch(IGB_RX_DESC(rx_ring, ntc));
8087
8088         if (likely(igb_test_staterr(rx_desc, E1000_RXD_STAT_EOP)))
8089                 return false;
8090
8091         return true;
8092 }
8093
8094 /**
8095  *  igb_cleanup_headers - Correct corrupted or empty headers
8096  *  @rx_ring: rx descriptor ring packet is being transacted on
8097  *  @rx_desc: pointer to the EOP Rx descriptor
8098  *  @skb: pointer to current skb being fixed
8099  *
8100  *  Address the case where we are pulling data in on pages only
8101  *  and as such no data is present in the skb header.
8102  *
8103  *  In addition if skb is not at least 60 bytes we need to pad it so that
8104  *  it is large enough to qualify as a valid Ethernet frame.
8105  *
8106  *  Returns true if an error was encountered and skb was freed.
8107  **/
8108 static bool igb_cleanup_headers(struct igb_ring *rx_ring,
8109                                 union e1000_adv_rx_desc *rx_desc,
8110                                 struct sk_buff *skb)
8111 {
8112         if (unlikely((igb_test_staterr(rx_desc,
8113                                        E1000_RXDEXT_ERR_FRAME_ERR_MASK)))) {
8114                 struct net_device *netdev = rx_ring->netdev;
8115                 if (!(netdev->features & NETIF_F_RXALL)) {
8116                         dev_kfree_skb_any(skb);
8117                         return true;
8118                 }
8119         }
8120
8121         /* if eth_skb_pad returns an error the skb was freed */
8122         if (eth_skb_pad(skb))
8123                 return true;
8124
8125         return false;
8126 }
8127
8128 /**
8129  *  igb_process_skb_fields - Populate skb header fields from Rx descriptor
8130  *  @rx_ring: rx descriptor ring packet is being transacted on
8131  *  @rx_desc: pointer to the EOP Rx descriptor
8132  *  @skb: pointer to current skb being populated
8133  *
8134  *  This function checks the ring, descriptor, and packet information in
8135  *  order to populate the hash, checksum, VLAN, timestamp, protocol, and
8136  *  other fields within the skb.
8137  **/
8138 static void igb_process_skb_fields(struct igb_ring *rx_ring,
8139                                    union e1000_adv_rx_desc *rx_desc,
8140                                    struct sk_buff *skb)
8141 {
8142         struct net_device *dev = rx_ring->netdev;
8143
8144         igb_rx_hash(rx_ring, rx_desc, skb);
8145
8146         igb_rx_checksum(rx_ring, rx_desc, skb);
8147
8148         if (igb_test_staterr(rx_desc, E1000_RXDADV_STAT_TS) &&
8149             !igb_test_staterr(rx_desc, E1000_RXDADV_STAT_TSIP))
8150                 igb_ptp_rx_rgtstamp(rx_ring->q_vector, skb);
8151
8152         if ((dev->features & NETIF_F_HW_VLAN_CTAG_RX) &&
8153             igb_test_staterr(rx_desc, E1000_RXD_STAT_VP)) {
8154                 u16 vid;
8155
8156                 if (igb_test_staterr(rx_desc, E1000_RXDEXT_STATERR_LB) &&
8157                     test_bit(IGB_RING_FLAG_RX_LB_VLAN_BSWAP, &rx_ring->flags))
8158                         vid = be16_to_cpu(rx_desc->wb.upper.vlan);
8159                 else
8160                         vid = le16_to_cpu(rx_desc->wb.upper.vlan);
8161
8162                 __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vid);
8163         }
8164
8165         skb_record_rx_queue(skb, rx_ring->queue_index);
8166
8167         skb->protocol = eth_type_trans(skb, rx_ring->netdev);
8168 }
8169
8170 static struct igb_rx_buffer *igb_get_rx_buffer(struct igb_ring *rx_ring,
8171                                                const unsigned int size)
8172 {
8173         struct igb_rx_buffer *rx_buffer;
8174
8175         rx_buffer = &rx_ring->rx_buffer_info[rx_ring->next_to_clean];
8176         prefetchw(rx_buffer->page);
8177
8178         /* we are reusing so sync this buffer for CPU use */
8179         dma_sync_single_range_for_cpu(rx_ring->dev,
8180                                       rx_buffer->dma,
8181                                       rx_buffer->page_offset,
8182                                       size,
8183                                       DMA_FROM_DEVICE);
8184
8185         rx_buffer->pagecnt_bias--;
8186
8187         return rx_buffer;
8188 }
8189
8190 static void igb_put_rx_buffer(struct igb_ring *rx_ring,
8191                               struct igb_rx_buffer *rx_buffer)
8192 {
8193         if (igb_can_reuse_rx_page(rx_buffer)) {
8194                 /* hand second half of page back to the ring */
8195                 igb_reuse_rx_page(rx_ring, rx_buffer);
8196         } else {
8197                 /* We are not reusing the buffer so unmap it and free
8198                  * any references we are holding to it
8199                  */
8200                 dma_unmap_page_attrs(rx_ring->dev, rx_buffer->dma,
8201                                      igb_rx_pg_size(rx_ring), DMA_FROM_DEVICE,
8202                                      IGB_RX_DMA_ATTR);
8203                 __page_frag_cache_drain(rx_buffer->page,
8204                                         rx_buffer->pagecnt_bias);
8205         }
8206
8207         /* clear contents of rx_buffer */
8208         rx_buffer->page = NULL;
8209 }
8210
8211 static int igb_clean_rx_irq(struct igb_q_vector *q_vector, const int budget)
8212 {
8213         struct igb_ring *rx_ring = q_vector->rx.ring;
8214         struct sk_buff *skb = rx_ring->skb;
8215         unsigned int total_bytes = 0, total_packets = 0;
8216         u16 cleaned_count = igb_desc_unused(rx_ring);
8217
8218         while (likely(total_packets < budget)) {
8219                 union e1000_adv_rx_desc *rx_desc;
8220                 struct igb_rx_buffer *rx_buffer;
8221                 unsigned int size;
8222
8223                 /* return some buffers to hardware, one at a time is too slow */
8224                 if (cleaned_count >= IGB_RX_BUFFER_WRITE) {
8225                         igb_alloc_rx_buffers(rx_ring, cleaned_count);
8226                         cleaned_count = 0;
8227                 }
8228
8229                 rx_desc = IGB_RX_DESC(rx_ring, rx_ring->next_to_clean);
8230                 size = le16_to_cpu(rx_desc->wb.upper.length);
8231                 if (!size)
8232                         break;
8233
8234                 /* This memory barrier is needed to keep us from reading
8235                  * any other fields out of the rx_desc until we know the
8236                  * descriptor has been written back
8237                  */
8238                 dma_rmb();
8239
8240                 rx_buffer = igb_get_rx_buffer(rx_ring, size);
8241
8242                 /* retrieve a buffer from the ring */
8243                 if (skb)
8244                         igb_add_rx_frag(rx_ring, rx_buffer, skb, size);
8245                 else if (ring_uses_build_skb(rx_ring))
8246                         skb = igb_build_skb(rx_ring, rx_buffer, rx_desc, size);
8247                 else
8248                         skb = igb_construct_skb(rx_ring, rx_buffer,
8249                                                 rx_desc, size);
8250
8251                 /* exit if we failed to retrieve a buffer */
8252                 if (!skb) {
8253                         rx_ring->rx_stats.alloc_failed++;
8254                         rx_buffer->pagecnt_bias++;
8255                         break;
8256                 }
8257
8258                 igb_put_rx_buffer(rx_ring, rx_buffer);
8259                 cleaned_count++;
8260
8261                 /* fetch next buffer in frame if non-eop */
8262                 if (igb_is_non_eop(rx_ring, rx_desc))
8263                         continue;
8264
8265                 /* verify the packet layout is correct */
8266                 if (igb_cleanup_headers(rx_ring, rx_desc, skb)) {
8267                         skb = NULL;
8268                         continue;
8269                 }
8270
8271                 /* probably a little skewed due to removing CRC */
8272                 total_bytes += skb->len;
8273
8274                 /* populate checksum, timestamp, VLAN, and protocol */
8275                 igb_process_skb_fields(rx_ring, rx_desc, skb);
8276
8277                 napi_gro_receive(&q_vector->napi, skb);
8278
8279                 /* reset skb pointer */
8280                 skb = NULL;
8281
8282                 /* update budget accounting */
8283                 total_packets++;
8284         }
8285
8286         /* place incomplete frames back on ring for completion */
8287         rx_ring->skb = skb;
8288
8289         u64_stats_update_begin(&rx_ring->rx_syncp);
8290         rx_ring->rx_stats.packets += total_packets;
8291         rx_ring->rx_stats.bytes += total_bytes;
8292         u64_stats_update_end(&rx_ring->rx_syncp);
8293         q_vector->rx.total_packets += total_packets;
8294         q_vector->rx.total_bytes += total_bytes;
8295
8296         if (cleaned_count)
8297                 igb_alloc_rx_buffers(rx_ring, cleaned_count);
8298
8299         return total_packets;
8300 }
8301
8302 static inline unsigned int igb_rx_offset(struct igb_ring *rx_ring)
8303 {
8304         return ring_uses_build_skb(rx_ring) ? IGB_SKB_PAD : 0;
8305 }
8306
8307 static bool igb_alloc_mapped_page(struct igb_ring *rx_ring,
8308                                   struct igb_rx_buffer *bi)
8309 {
8310         struct page *page = bi->page;
8311         dma_addr_t dma;
8312
8313         /* since we are recycling buffers we should seldom need to alloc */
8314         if (likely(page))
8315                 return true;
8316
8317         /* alloc new page for storage */
8318         page = dev_alloc_pages(igb_rx_pg_order(rx_ring));
8319         if (unlikely(!page)) {
8320                 rx_ring->rx_stats.alloc_failed++;
8321                 return false;
8322         }
8323
8324         /* map page for use */
8325         dma = dma_map_page_attrs(rx_ring->dev, page, 0,
8326                                  igb_rx_pg_size(rx_ring),
8327                                  DMA_FROM_DEVICE,
8328                                  IGB_RX_DMA_ATTR);
8329
8330         /* if mapping failed free memory back to system since
8331          * there isn't much point in holding memory we can't use
8332          */
8333         if (dma_mapping_error(rx_ring->dev, dma)) {
8334                 __free_pages(page, igb_rx_pg_order(rx_ring));
8335
8336                 rx_ring->rx_stats.alloc_failed++;
8337                 return false;
8338         }
8339
8340         bi->dma = dma;
8341         bi->page = page;
8342         bi->page_offset = igb_rx_offset(rx_ring);
8343         bi->pagecnt_bias = 1;
8344
8345         return true;
8346 }
8347
8348 /**
8349  *  igb_alloc_rx_buffers - Replace used receive buffers; packet split
8350  *  @adapter: address of board private structure
8351  **/
8352 void igb_alloc_rx_buffers(struct igb_ring *rx_ring, u16 cleaned_count)
8353 {
8354         union e1000_adv_rx_desc *rx_desc;
8355         struct igb_rx_buffer *bi;
8356         u16 i = rx_ring->next_to_use;
8357         u16 bufsz;
8358
8359         /* nothing to do */
8360         if (!cleaned_count)
8361                 return;
8362
8363         rx_desc = IGB_RX_DESC(rx_ring, i);
8364         bi = &rx_ring->rx_buffer_info[i];
8365         i -= rx_ring->count;
8366
8367         bufsz = igb_rx_bufsz(rx_ring);
8368
8369         do {
8370                 if (!igb_alloc_mapped_page(rx_ring, bi))
8371                         break;
8372
8373                 /* sync the buffer for use by the device */
8374                 dma_sync_single_range_for_device(rx_ring->dev, bi->dma,
8375                                                  bi->page_offset, bufsz,
8376                                                  DMA_FROM_DEVICE);
8377
8378                 /* Refresh the desc even if buffer_addrs didn't change
8379                  * because each write-back erases this info.
8380                  */
8381                 rx_desc->read.pkt_addr = cpu_to_le64(bi->dma + bi->page_offset);
8382
8383                 rx_desc++;
8384                 bi++;
8385                 i++;
8386                 if (unlikely(!i)) {
8387                         rx_desc = IGB_RX_DESC(rx_ring, 0);
8388                         bi = rx_ring->rx_buffer_info;
8389                         i -= rx_ring->count;
8390                 }
8391
8392                 /* clear the length for the next_to_use descriptor */
8393                 rx_desc->wb.upper.length = 0;
8394
8395                 cleaned_count--;
8396         } while (cleaned_count);
8397
8398         i += rx_ring->count;
8399
8400         if (rx_ring->next_to_use != i) {
8401                 /* record the next descriptor to use */
8402                 rx_ring->next_to_use = i;
8403
8404                 /* update next to alloc since we have filled the ring */
8405                 rx_ring->next_to_alloc = i;
8406
8407                 /* Force memory writes to complete before letting h/w
8408                  * know there are new descriptors to fetch.  (Only
8409                  * applicable for weak-ordered memory model archs,
8410                  * such as IA-64).
8411                  */
8412                 wmb();
8413                 writel(i, rx_ring->tail);
8414         }
8415 }
8416
8417 /**
8418  * igb_mii_ioctl -
8419  * @netdev:
8420  * @ifreq:
8421  * @cmd:
8422  **/
8423 static int igb_mii_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
8424 {
8425         struct igb_adapter *adapter = netdev_priv(netdev);
8426         struct mii_ioctl_data *data = if_mii(ifr);
8427
8428         if (adapter->hw.phy.media_type != e1000_media_type_copper)
8429                 return -EOPNOTSUPP;
8430
8431         switch (cmd) {
8432         case SIOCGMIIPHY:
8433                 data->phy_id = adapter->hw.phy.addr;
8434                 break;
8435         case SIOCGMIIREG:
8436                 if (igb_read_phy_reg(&adapter->hw, data->reg_num & 0x1F,
8437                                      &data->val_out))
8438                         return -EIO;
8439                 break;
8440         case SIOCSMIIREG:
8441         default:
8442                 return -EOPNOTSUPP;
8443         }
8444         return 0;
8445 }
8446
8447 /**
8448  * igb_ioctl -
8449  * @netdev:
8450  * @ifreq:
8451  * @cmd:
8452  **/
8453 static int igb_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
8454 {
8455         switch (cmd) {
8456         case SIOCGMIIPHY:
8457         case SIOCGMIIREG:
8458         case SIOCSMIIREG:
8459                 return igb_mii_ioctl(netdev, ifr, cmd);
8460         case SIOCGHWTSTAMP:
8461                 return igb_ptp_get_ts_config(netdev, ifr);
8462         case SIOCSHWTSTAMP:
8463                 return igb_ptp_set_ts_config(netdev, ifr);
8464         default:
8465                 return -EOPNOTSUPP;
8466         }
8467 }
8468
8469 void igb_read_pci_cfg(struct e1000_hw *hw, u32 reg, u16 *value)
8470 {
8471         struct igb_adapter *adapter = hw->back;
8472
8473         pci_read_config_word(adapter->pdev, reg, value);
8474 }
8475
8476 void igb_write_pci_cfg(struct e1000_hw *hw, u32 reg, u16 *value)
8477 {
8478         struct igb_adapter *adapter = hw->back;
8479
8480         pci_write_config_word(adapter->pdev, reg, *value);
8481 }
8482
8483 s32 igb_read_pcie_cap_reg(struct e1000_hw *hw, u32 reg, u16 *value)
8484 {
8485         struct igb_adapter *adapter = hw->back;
8486
8487         if (pcie_capability_read_word(adapter->pdev, reg, value))
8488                 return -E1000_ERR_CONFIG;
8489
8490         return 0;
8491 }
8492
8493 s32 igb_write_pcie_cap_reg(struct e1000_hw *hw, u32 reg, u16 *value)
8494 {
8495         struct igb_adapter *adapter = hw->back;
8496
8497         if (pcie_capability_write_word(adapter->pdev, reg, *value))
8498                 return -E1000_ERR_CONFIG;
8499
8500         return 0;
8501 }
8502
8503 static void igb_vlan_mode(struct net_device *netdev, netdev_features_t features)
8504 {
8505         struct igb_adapter *adapter = netdev_priv(netdev);
8506         struct e1000_hw *hw = &adapter->hw;
8507         u32 ctrl, rctl;
8508         bool enable = !!(features & NETIF_F_HW_VLAN_CTAG_RX);
8509
8510         if (enable) {
8511                 /* enable VLAN tag insert/strip */
8512                 ctrl = rd32(E1000_CTRL);
8513                 ctrl |= E1000_CTRL_VME;
8514                 wr32(E1000_CTRL, ctrl);
8515
8516                 /* Disable CFI check */
8517                 rctl = rd32(E1000_RCTL);
8518                 rctl &= ~E1000_RCTL_CFIEN;
8519                 wr32(E1000_RCTL, rctl);
8520         } else {
8521                 /* disable VLAN tag insert/strip */
8522                 ctrl = rd32(E1000_CTRL);
8523                 ctrl &= ~E1000_CTRL_VME;
8524                 wr32(E1000_CTRL, ctrl);
8525         }
8526
8527         igb_set_vf_vlan_strip(adapter, adapter->vfs_allocated_count, enable);
8528 }
8529
8530 static int igb_vlan_rx_add_vid(struct net_device *netdev,
8531                                __be16 proto, u16 vid)
8532 {
8533         struct igb_adapter *adapter = netdev_priv(netdev);
8534         struct e1000_hw *hw = &adapter->hw;
8535         int pf_id = adapter->vfs_allocated_count;
8536
8537         /* add the filter since PF can receive vlans w/o entry in vlvf */
8538         if (!vid || !(adapter->flags & IGB_FLAG_VLAN_PROMISC))
8539                 igb_vfta_set(hw, vid, pf_id, true, !!vid);
8540
8541         set_bit(vid, adapter->active_vlans);
8542
8543         return 0;
8544 }
8545
8546 static int igb_vlan_rx_kill_vid(struct net_device *netdev,
8547                                 __be16 proto, u16 vid)
8548 {
8549         struct igb_adapter *adapter = netdev_priv(netdev);
8550         int pf_id = adapter->vfs_allocated_count;
8551         struct e1000_hw *hw = &adapter->hw;
8552
8553         /* remove VID from filter table */
8554         if (vid && !(adapter->flags & IGB_FLAG_VLAN_PROMISC))
8555                 igb_vfta_set(hw, vid, pf_id, false, true);
8556
8557         clear_bit(vid, adapter->active_vlans);
8558
8559         return 0;
8560 }
8561
8562 static void igb_restore_vlan(struct igb_adapter *adapter)
8563 {
8564         u16 vid = 1;
8565
8566         igb_vlan_mode(adapter->netdev, adapter->netdev->features);
8567         igb_vlan_rx_add_vid(adapter->netdev, htons(ETH_P_8021Q), 0);
8568
8569         for_each_set_bit_from(vid, adapter->active_vlans, VLAN_N_VID)
8570                 igb_vlan_rx_add_vid(adapter->netdev, htons(ETH_P_8021Q), vid);
8571 }
8572
8573 int igb_set_spd_dplx(struct igb_adapter *adapter, u32 spd, u8 dplx)
8574 {
8575         struct pci_dev *pdev = adapter->pdev;
8576         struct e1000_mac_info *mac = &adapter->hw.mac;
8577
8578         mac->autoneg = 0;
8579
8580         /* Make sure dplx is at most 1 bit and lsb of speed is not set
8581          * for the switch() below to work
8582          */
8583         if ((spd & 1) || (dplx & ~1))
8584                 goto err_inval;
8585
8586         /* Fiber NIC's only allow 1000 gbps Full duplex
8587          * and 100Mbps Full duplex for 100baseFx sfp
8588          */
8589         if (adapter->hw.phy.media_type == e1000_media_type_internal_serdes) {
8590                 switch (spd + dplx) {
8591                 case SPEED_10 + DUPLEX_HALF:
8592                 case SPEED_10 + DUPLEX_FULL:
8593                 case SPEED_100 + DUPLEX_HALF:
8594                         goto err_inval;
8595                 default:
8596                         break;
8597                 }
8598         }
8599
8600         switch (spd + dplx) {
8601         case SPEED_10 + DUPLEX_HALF:
8602                 mac->forced_speed_duplex = ADVERTISE_10_HALF;
8603                 break;
8604         case SPEED_10 + DUPLEX_FULL:
8605                 mac->forced_speed_duplex = ADVERTISE_10_FULL;
8606                 break;
8607         case SPEED_100 + DUPLEX_HALF:
8608                 mac->forced_speed_duplex = ADVERTISE_100_HALF;
8609                 break;
8610         case SPEED_100 + DUPLEX_FULL:
8611                 mac->forced_speed_duplex = ADVERTISE_100_FULL;
8612                 break;
8613         case SPEED_1000 + DUPLEX_FULL:
8614                 mac->autoneg = 1;
8615                 adapter->hw.phy.autoneg_advertised = ADVERTISE_1000_FULL;
8616                 break;
8617         case SPEED_1000 + DUPLEX_HALF: /* not supported */
8618         default:
8619                 goto err_inval;
8620         }
8621
8622         /* clear MDI, MDI(-X) override is only allowed when autoneg enabled */
8623         adapter->hw.phy.mdix = AUTO_ALL_MODES;
8624
8625         return 0;
8626
8627 err_inval:
8628         dev_err(&pdev->dev, "Unsupported Speed/Duplex configuration\n");
8629         return -EINVAL;
8630 }
8631
8632 static int __igb_shutdown(struct pci_dev *pdev, bool *enable_wake,
8633                           bool runtime)
8634 {
8635         struct net_device *netdev = pci_get_drvdata(pdev);
8636         struct igb_adapter *adapter = netdev_priv(netdev);
8637         struct e1000_hw *hw = &adapter->hw;
8638         u32 ctrl, rctl, status;
8639         u32 wufc = runtime ? E1000_WUFC_LNKC : adapter->wol;
8640 #ifdef CONFIG_PM
8641         int retval = 0;
8642 #endif
8643
8644         rtnl_lock();
8645         netif_device_detach(netdev);
8646
8647         if (netif_running(netdev))
8648                 __igb_close(netdev, true);
8649
8650         igb_ptp_suspend(adapter);
8651
8652         igb_clear_interrupt_scheme(adapter);
8653         rtnl_unlock();
8654
8655 #ifdef CONFIG_PM
8656         retval = pci_save_state(pdev);
8657         if (retval)
8658                 return retval;
8659 #endif
8660
8661         status = rd32(E1000_STATUS);
8662         if (status & E1000_STATUS_LU)
8663                 wufc &= ~E1000_WUFC_LNKC;
8664
8665         if (wufc) {
8666                 igb_setup_rctl(adapter);
8667                 igb_set_rx_mode(netdev);
8668
8669                 /* turn on all-multi mode if wake on multicast is enabled */
8670                 if (wufc & E1000_WUFC_MC) {
8671                         rctl = rd32(E1000_RCTL);
8672                         rctl |= E1000_RCTL_MPE;
8673                         wr32(E1000_RCTL, rctl);
8674                 }
8675
8676                 ctrl = rd32(E1000_CTRL);
8677                 /* advertise wake from D3Cold */
8678                 #define E1000_CTRL_ADVD3WUC 0x00100000
8679                 /* phy power management enable */
8680                 #define E1000_CTRL_EN_PHY_PWR_MGMT 0x00200000
8681                 ctrl |= E1000_CTRL_ADVD3WUC;
8682                 wr32(E1000_CTRL, ctrl);
8683
8684                 /* Allow time for pending master requests to run */
8685                 igb_disable_pcie_master(hw);
8686
8687                 wr32(E1000_WUC, E1000_WUC_PME_EN);
8688                 wr32(E1000_WUFC, wufc);
8689         } else {
8690                 wr32(E1000_WUC, 0);
8691                 wr32(E1000_WUFC, 0);
8692         }
8693
8694         *enable_wake = wufc || adapter->en_mng_pt;
8695         if (!*enable_wake)
8696                 igb_power_down_link(adapter);
8697         else
8698                 igb_power_up_link(adapter);
8699
8700         /* Release control of h/w to f/w.  If f/w is AMT enabled, this
8701          * would have already happened in close and is redundant.
8702          */
8703         igb_release_hw_control(adapter);
8704
8705         pci_disable_device(pdev);
8706
8707         return 0;
8708 }
8709
8710 static void igb_deliver_wake_packet(struct net_device *netdev)
8711 {
8712         struct igb_adapter *adapter = netdev_priv(netdev);
8713         struct e1000_hw *hw = &adapter->hw;
8714         struct sk_buff *skb;
8715         u32 wupl;
8716
8717         wupl = rd32(E1000_WUPL) & E1000_WUPL_MASK;
8718
8719         /* WUPM stores only the first 128 bytes of the wake packet.
8720          * Read the packet only if we have the whole thing.
8721          */
8722         if ((wupl == 0) || (wupl > E1000_WUPM_BYTES))
8723                 return;
8724
8725         skb = netdev_alloc_skb_ip_align(netdev, E1000_WUPM_BYTES);
8726         if (!skb)
8727                 return;
8728
8729         skb_put(skb, wupl);
8730
8731         /* Ensure reads are 32-bit aligned */
8732         wupl = roundup(wupl, 4);
8733
8734         memcpy_fromio(skb->data, hw->hw_addr + E1000_WUPM_REG(0), wupl);
8735
8736         skb->protocol = eth_type_trans(skb, netdev);
8737         netif_rx(skb);
8738 }
8739
8740 static int __maybe_unused igb_suspend(struct device *dev)
8741 {
8742         int retval;
8743         bool wake;
8744         struct pci_dev *pdev = to_pci_dev(dev);
8745
8746         retval = __igb_shutdown(pdev, &wake, 0);
8747         if (retval)
8748                 return retval;
8749
8750         if (wake) {
8751                 pci_prepare_to_sleep(pdev);
8752         } else {
8753                 pci_wake_from_d3(pdev, false);
8754                 pci_set_power_state(pdev, PCI_D3hot);
8755         }
8756
8757         return 0;
8758 }
8759
8760 static int __maybe_unused igb_resume(struct device *dev)
8761 {
8762         struct pci_dev *pdev = to_pci_dev(dev);
8763         struct net_device *netdev = pci_get_drvdata(pdev);
8764         struct igb_adapter *adapter = netdev_priv(netdev);
8765         struct e1000_hw *hw = &adapter->hw;
8766         u32 err, val;
8767
8768         pci_set_power_state(pdev, PCI_D0);
8769         pci_restore_state(pdev);
8770         pci_save_state(pdev);
8771
8772         if (!pci_device_is_present(pdev))
8773                 return -ENODEV;
8774         err = pci_enable_device_mem(pdev);
8775         if (err) {
8776                 dev_err(&pdev->dev,
8777                         "igb: Cannot enable PCI device from suspend\n");
8778                 return err;
8779         }
8780         pci_set_master(pdev);
8781
8782         pci_enable_wake(pdev, PCI_D3hot, 0);
8783         pci_enable_wake(pdev, PCI_D3cold, 0);
8784
8785         if (igb_init_interrupt_scheme(adapter, true)) {
8786                 dev_err(&pdev->dev, "Unable to allocate memory for queues\n");
8787                 return -ENOMEM;
8788         }
8789
8790         igb_reset(adapter);
8791
8792         /* let the f/w know that the h/w is now under the control of the
8793          * driver.
8794          */
8795         igb_get_hw_control(adapter);
8796
8797         val = rd32(E1000_WUS);
8798         if (val & WAKE_PKT_WUS)
8799                 igb_deliver_wake_packet(netdev);
8800
8801         wr32(E1000_WUS, ~0);
8802
8803         rtnl_lock();
8804         if (!err && netif_running(netdev))
8805                 err = __igb_open(netdev, true);
8806
8807         if (!err)
8808                 netif_device_attach(netdev);
8809         rtnl_unlock();
8810
8811         return err;
8812 }
8813
8814 static int __maybe_unused igb_runtime_idle(struct device *dev)
8815 {
8816         struct pci_dev *pdev = to_pci_dev(dev);
8817         struct net_device *netdev = pci_get_drvdata(pdev);
8818         struct igb_adapter *adapter = netdev_priv(netdev);
8819
8820         if (!igb_has_link(adapter))
8821                 pm_schedule_suspend(dev, MSEC_PER_SEC * 5);
8822
8823         return -EBUSY;
8824 }
8825
8826 static int __maybe_unused igb_runtime_suspend(struct device *dev)
8827 {
8828         struct pci_dev *pdev = to_pci_dev(dev);
8829         int retval;
8830         bool wake;
8831
8832         retval = __igb_shutdown(pdev, &wake, 1);
8833         if (retval)
8834                 return retval;
8835
8836         if (wake) {
8837                 pci_prepare_to_sleep(pdev);
8838         } else {
8839                 pci_wake_from_d3(pdev, false);
8840                 pci_set_power_state(pdev, PCI_D3hot);
8841         }
8842
8843         return 0;
8844 }
8845
8846 static int __maybe_unused igb_runtime_resume(struct device *dev)
8847 {
8848         return igb_resume(dev);
8849 }
8850
8851 static void igb_shutdown(struct pci_dev *pdev)
8852 {
8853         bool wake;
8854
8855         __igb_shutdown(pdev, &wake, 0);
8856
8857         if (system_state == SYSTEM_POWER_OFF) {
8858                 pci_wake_from_d3(pdev, wake);
8859                 pci_set_power_state(pdev, PCI_D3hot);
8860         }
8861 }
8862
8863 #ifdef CONFIG_PCI_IOV
8864 static int igb_sriov_reinit(struct pci_dev *dev)
8865 {
8866         struct net_device *netdev = pci_get_drvdata(dev);
8867         struct igb_adapter *adapter = netdev_priv(netdev);
8868         struct pci_dev *pdev = adapter->pdev;
8869
8870         rtnl_lock();
8871
8872         if (netif_running(netdev))
8873                 igb_close(netdev);
8874         else
8875                 igb_reset(adapter);
8876
8877         igb_clear_interrupt_scheme(adapter);
8878
8879         igb_init_queue_configuration(adapter);
8880
8881         if (igb_init_interrupt_scheme(adapter, true)) {
8882                 rtnl_unlock();
8883                 dev_err(&pdev->dev, "Unable to allocate memory for queues\n");
8884                 return -ENOMEM;
8885         }
8886
8887         if (netif_running(netdev))
8888                 igb_open(netdev);
8889
8890         rtnl_unlock();
8891
8892         return 0;
8893 }
8894
8895 static int igb_pci_disable_sriov(struct pci_dev *dev)
8896 {
8897         int err = igb_disable_sriov(dev);
8898
8899         if (!err)
8900                 err = igb_sriov_reinit(dev);
8901
8902         return err;
8903 }
8904
8905 static int igb_pci_enable_sriov(struct pci_dev *dev, int num_vfs)
8906 {
8907         int err = igb_enable_sriov(dev, num_vfs);
8908
8909         if (err)
8910                 goto out;
8911
8912         err = igb_sriov_reinit(dev);
8913         if (!err)
8914                 return num_vfs;
8915
8916 out:
8917         return err;
8918 }
8919
8920 #endif
8921 static int igb_pci_sriov_configure(struct pci_dev *dev, int num_vfs)
8922 {
8923 #ifdef CONFIG_PCI_IOV
8924         if (num_vfs == 0)
8925                 return igb_pci_disable_sriov(dev);
8926         else
8927                 return igb_pci_enable_sriov(dev, num_vfs);
8928 #endif
8929         return 0;
8930 }
8931
8932 #ifdef CONFIG_NET_POLL_CONTROLLER
8933 /* Polling 'interrupt' - used by things like netconsole to send skbs
8934  * without having to re-enable interrupts. It's not called while
8935  * the interrupt routine is executing.
8936  */
8937 static void igb_netpoll(struct net_device *netdev)
8938 {
8939         struct igb_adapter *adapter = netdev_priv(netdev);
8940         struct e1000_hw *hw = &adapter->hw;
8941         struct igb_q_vector *q_vector;
8942         int i;
8943
8944         for (i = 0; i < adapter->num_q_vectors; i++) {
8945                 q_vector = adapter->q_vector[i];
8946                 if (adapter->flags & IGB_FLAG_HAS_MSIX)
8947                         wr32(E1000_EIMC, q_vector->eims_value);
8948                 else
8949                         igb_irq_disable(adapter);
8950                 napi_schedule(&q_vector->napi);
8951         }
8952 }
8953 #endif /* CONFIG_NET_POLL_CONTROLLER */
8954
8955 /**
8956  *  igb_io_error_detected - called when PCI error is detected
8957  *  @pdev: Pointer to PCI device
8958  *  @state: The current pci connection state
8959  *
8960  *  This function is called after a PCI bus error affecting
8961  *  this device has been detected.
8962  **/
8963 static pci_ers_result_t igb_io_error_detected(struct pci_dev *pdev,
8964                                               pci_channel_state_t state)
8965 {
8966         struct net_device *netdev = pci_get_drvdata(pdev);
8967         struct igb_adapter *adapter = netdev_priv(netdev);
8968
8969         netif_device_detach(netdev);
8970
8971         if (state == pci_channel_io_perm_failure)
8972                 return PCI_ERS_RESULT_DISCONNECT;
8973
8974         if (netif_running(netdev))
8975                 igb_down(adapter);
8976         pci_disable_device(pdev);
8977
8978         /* Request a slot slot reset. */
8979         return PCI_ERS_RESULT_NEED_RESET;
8980 }
8981
8982 /**
8983  *  igb_io_slot_reset - called after the pci bus has been reset.
8984  *  @pdev: Pointer to PCI device
8985  *
8986  *  Restart the card from scratch, as if from a cold-boot. Implementation
8987  *  resembles the first-half of the igb_resume routine.
8988  **/
8989 static pci_ers_result_t igb_io_slot_reset(struct pci_dev *pdev)
8990 {
8991         struct net_device *netdev = pci_get_drvdata(pdev);
8992         struct igb_adapter *adapter = netdev_priv(netdev);
8993         struct e1000_hw *hw = &adapter->hw;
8994         pci_ers_result_t result;
8995         int err;
8996
8997         if (pci_enable_device_mem(pdev)) {
8998                 dev_err(&pdev->dev,
8999                         "Cannot re-enable PCI device after reset.\n");
9000                 result = PCI_ERS_RESULT_DISCONNECT;
9001         } else {
9002                 pci_set_master(pdev);
9003                 pci_restore_state(pdev);
9004                 pci_save_state(pdev);
9005
9006                 pci_enable_wake(pdev, PCI_D3hot, 0);
9007                 pci_enable_wake(pdev, PCI_D3cold, 0);
9008
9009                 /* In case of PCI error, adapter lose its HW address
9010                  * so we should re-assign it here.
9011                  */
9012                 hw->hw_addr = adapter->io_addr;
9013
9014                 igb_reset(adapter);
9015                 wr32(E1000_WUS, ~0);
9016                 result = PCI_ERS_RESULT_RECOVERED;
9017         }
9018
9019         err = pci_cleanup_aer_uncorrect_error_status(pdev);
9020         if (err) {
9021                 dev_err(&pdev->dev,
9022                         "pci_cleanup_aer_uncorrect_error_status failed 0x%0x\n",
9023                         err);
9024                 /* non-fatal, continue */
9025         }
9026
9027         return result;
9028 }
9029
9030 /**
9031  *  igb_io_resume - called when traffic can start flowing again.
9032  *  @pdev: Pointer to PCI device
9033  *
9034  *  This callback is called when the error recovery driver tells us that
9035  *  its OK to resume normal operation. Implementation resembles the
9036  *  second-half of the igb_resume routine.
9037  */
9038 static void igb_io_resume(struct pci_dev *pdev)
9039 {
9040         struct net_device *netdev = pci_get_drvdata(pdev);
9041         struct igb_adapter *adapter = netdev_priv(netdev);
9042
9043         if (netif_running(netdev)) {
9044                 if (igb_up(adapter)) {
9045                         dev_err(&pdev->dev, "igb_up failed after reset\n");
9046                         return;
9047                 }
9048         }
9049
9050         netif_device_attach(netdev);
9051
9052         /* let the f/w know that the h/w is now under the control of the
9053          * driver.
9054          */
9055         igb_get_hw_control(adapter);
9056 }
9057
9058 /**
9059  *  igb_rar_set_index - Sync RAL[index] and RAH[index] registers with MAC table
9060  *  @adapter: Pointer to adapter structure
9061  *  @index: Index of the RAR entry which need to be synced with MAC table
9062  **/
9063 static void igb_rar_set_index(struct igb_adapter *adapter, u32 index)
9064 {
9065         struct e1000_hw *hw = &adapter->hw;
9066         u32 rar_low, rar_high;
9067         u8 *addr = adapter->mac_table[index].addr;
9068
9069         /* HW expects these to be in network order when they are plugged
9070          * into the registers which are little endian.  In order to guarantee
9071          * that ordering we need to do an leXX_to_cpup here in order to be
9072          * ready for the byteswap that occurs with writel
9073          */
9074         rar_low = le32_to_cpup((__le32 *)(addr));
9075         rar_high = le16_to_cpup((__le16 *)(addr + 4));
9076
9077         /* Indicate to hardware the Address is Valid. */
9078         if (adapter->mac_table[index].state & IGB_MAC_STATE_IN_USE) {
9079                 if (is_valid_ether_addr(addr))
9080                         rar_high |= E1000_RAH_AV;
9081
9082                 if (adapter->mac_table[index].state & IGB_MAC_STATE_SRC_ADDR)
9083                         rar_high |= E1000_RAH_ASEL_SRC_ADDR;
9084
9085                 switch (hw->mac.type) {
9086                 case e1000_82575:
9087                 case e1000_i210:
9088                         if (adapter->mac_table[index].state &
9089                             IGB_MAC_STATE_QUEUE_STEERING)
9090                                 rar_high |= E1000_RAH_QSEL_ENABLE;
9091
9092                         rar_high |= E1000_RAH_POOL_1 *
9093                                     adapter->mac_table[index].queue;
9094                         break;
9095                 default:
9096                         rar_high |= E1000_RAH_POOL_1 <<
9097                                     adapter->mac_table[index].queue;
9098                         break;
9099                 }
9100         }
9101
9102         wr32(E1000_RAL(index), rar_low);
9103         wrfl();
9104         wr32(E1000_RAH(index), rar_high);
9105         wrfl();
9106 }
9107
9108 static int igb_set_vf_mac(struct igb_adapter *adapter,
9109                           int vf, unsigned char *mac_addr)
9110 {
9111         struct e1000_hw *hw = &adapter->hw;
9112         /* VF MAC addresses start at end of receive addresses and moves
9113          * towards the first, as a result a collision should not be possible
9114          */
9115         int rar_entry = hw->mac.rar_entry_count - (vf + 1);
9116         unsigned char *vf_mac_addr = adapter->vf_data[vf].vf_mac_addresses;
9117
9118         ether_addr_copy(vf_mac_addr, mac_addr);
9119         ether_addr_copy(adapter->mac_table[rar_entry].addr, mac_addr);
9120         adapter->mac_table[rar_entry].queue = vf;
9121         adapter->mac_table[rar_entry].state |= IGB_MAC_STATE_IN_USE;
9122         igb_rar_set_index(adapter, rar_entry);
9123
9124         return 0;
9125 }
9126
9127 static int igb_ndo_set_vf_mac(struct net_device *netdev, int vf, u8 *mac)
9128 {
9129         struct igb_adapter *adapter = netdev_priv(netdev);
9130
9131         if (vf >= adapter->vfs_allocated_count)
9132                 return -EINVAL;
9133
9134         /* Setting the VF MAC to 0 reverts the IGB_VF_FLAG_PF_SET_MAC
9135          * flag and allows to overwrite the MAC via VF netdev.  This
9136          * is necessary to allow libvirt a way to restore the original
9137          * MAC after unbinding vfio-pci and reloading igbvf after shutting
9138          * down a VM.
9139          */
9140         if (is_zero_ether_addr(mac)) {
9141                 adapter->vf_data[vf].flags &= ~IGB_VF_FLAG_PF_SET_MAC;
9142                 dev_info(&adapter->pdev->dev,
9143                          "remove administratively set MAC on VF %d\n",
9144                          vf);
9145         } else if (is_valid_ether_addr(mac)) {
9146                 adapter->vf_data[vf].flags |= IGB_VF_FLAG_PF_SET_MAC;
9147                 dev_info(&adapter->pdev->dev, "setting MAC %pM on VF %d\n",
9148                          mac, vf);
9149                 dev_info(&adapter->pdev->dev,
9150                          "Reload the VF driver to make this change effective.");
9151                 /* Generate additional warning if PF is down */
9152                 if (test_bit(__IGB_DOWN, &adapter->state)) {
9153                         dev_warn(&adapter->pdev->dev,
9154                                  "The VF MAC address has been set, but the PF device is not up.\n");
9155                         dev_warn(&adapter->pdev->dev,
9156                                  "Bring the PF device up before attempting to use the VF device.\n");
9157                 }
9158         } else {
9159                 return -EINVAL;
9160         }
9161         return igb_set_vf_mac(adapter, vf, mac);
9162 }
9163
9164 static int igb_link_mbps(int internal_link_speed)
9165 {
9166         switch (internal_link_speed) {
9167         case SPEED_100:
9168                 return 100;
9169         case SPEED_1000:
9170                 return 1000;
9171         default:
9172                 return 0;
9173         }
9174 }
9175
9176 static void igb_set_vf_rate_limit(struct e1000_hw *hw, int vf, int tx_rate,
9177                                   int link_speed)
9178 {
9179         int rf_dec, rf_int;
9180         u32 bcnrc_val;
9181
9182         if (tx_rate != 0) {
9183                 /* Calculate the rate factor values to set */
9184                 rf_int = link_speed / tx_rate;
9185                 rf_dec = (link_speed - (rf_int * tx_rate));
9186                 rf_dec = (rf_dec * BIT(E1000_RTTBCNRC_RF_INT_SHIFT)) /
9187                          tx_rate;
9188
9189                 bcnrc_val = E1000_RTTBCNRC_RS_ENA;
9190                 bcnrc_val |= ((rf_int << E1000_RTTBCNRC_RF_INT_SHIFT) &
9191                               E1000_RTTBCNRC_RF_INT_MASK);
9192                 bcnrc_val |= (rf_dec & E1000_RTTBCNRC_RF_DEC_MASK);
9193         } else {
9194                 bcnrc_val = 0;
9195         }
9196
9197         wr32(E1000_RTTDQSEL, vf); /* vf X uses queue X */
9198         /* Set global transmit compensation time to the MMW_SIZE in RTTBCNRM
9199          * register. MMW_SIZE=0x014 if 9728-byte jumbo is supported.
9200          */
9201         wr32(E1000_RTTBCNRM, 0x14);
9202         wr32(E1000_RTTBCNRC, bcnrc_val);
9203 }
9204
9205 static void igb_check_vf_rate_limit(struct igb_adapter *adapter)
9206 {
9207         int actual_link_speed, i;
9208         bool reset_rate = false;
9209
9210         /* VF TX rate limit was not set or not supported */
9211         if ((adapter->vf_rate_link_speed == 0) ||
9212             (adapter->hw.mac.type != e1000_82576))
9213                 return;
9214
9215         actual_link_speed = igb_link_mbps(adapter->link_speed);
9216         if (actual_link_speed != adapter->vf_rate_link_speed) {
9217                 reset_rate = true;
9218                 adapter->vf_rate_link_speed = 0;
9219                 dev_info(&adapter->pdev->dev,
9220                          "Link speed has been changed. VF Transmit rate is disabled\n");
9221         }
9222
9223         for (i = 0; i < adapter->vfs_allocated_count; i++) {
9224                 if (reset_rate)
9225                         adapter->vf_data[i].tx_rate = 0;
9226
9227                 igb_set_vf_rate_limit(&adapter->hw, i,
9228                                       adapter->vf_data[i].tx_rate,
9229                                       actual_link_speed);
9230         }
9231 }
9232
9233 static int igb_ndo_set_vf_bw(struct net_device *netdev, int vf,
9234                              int min_tx_rate, int max_tx_rate)
9235 {
9236         struct igb_adapter *adapter = netdev_priv(netdev);
9237         struct e1000_hw *hw = &adapter->hw;
9238         int actual_link_speed;
9239
9240         if (hw->mac.type != e1000_82576)
9241                 return -EOPNOTSUPP;
9242
9243         if (min_tx_rate)
9244                 return -EINVAL;
9245
9246         actual_link_speed = igb_link_mbps(adapter->link_speed);
9247         if ((vf >= adapter->vfs_allocated_count) ||
9248             (!(rd32(E1000_STATUS) & E1000_STATUS_LU)) ||
9249             (max_tx_rate < 0) ||
9250             (max_tx_rate > actual_link_speed))
9251                 return -EINVAL;
9252
9253         adapter->vf_rate_link_speed = actual_link_speed;
9254         adapter->vf_data[vf].tx_rate = (u16)max_tx_rate;
9255         igb_set_vf_rate_limit(hw, vf, max_tx_rate, actual_link_speed);
9256
9257         return 0;
9258 }
9259
9260 static int igb_ndo_set_vf_spoofchk(struct net_device *netdev, int vf,
9261                                    bool setting)
9262 {
9263         struct igb_adapter *adapter = netdev_priv(netdev);
9264         struct e1000_hw *hw = &adapter->hw;
9265         u32 reg_val, reg_offset;
9266
9267         if (!adapter->vfs_allocated_count)
9268                 return -EOPNOTSUPP;
9269
9270         if (vf >= adapter->vfs_allocated_count)
9271                 return -EINVAL;
9272
9273         reg_offset = (hw->mac.type == e1000_82576) ? E1000_DTXSWC : E1000_TXSWC;
9274         reg_val = rd32(reg_offset);
9275         if (setting)
9276                 reg_val |= (BIT(vf) |
9277                             BIT(vf + E1000_DTXSWC_VLAN_SPOOF_SHIFT));
9278         else
9279                 reg_val &= ~(BIT(vf) |
9280                              BIT(vf + E1000_DTXSWC_VLAN_SPOOF_SHIFT));
9281         wr32(reg_offset, reg_val);
9282
9283         adapter->vf_data[vf].spoofchk_enabled = setting;
9284         return 0;
9285 }
9286
9287 static int igb_ndo_set_vf_trust(struct net_device *netdev, int vf, bool setting)
9288 {
9289         struct igb_adapter *adapter = netdev_priv(netdev);
9290
9291         if (vf >= adapter->vfs_allocated_count)
9292                 return -EINVAL;
9293         if (adapter->vf_data[vf].trusted == setting)
9294                 return 0;
9295
9296         adapter->vf_data[vf].trusted = setting;
9297
9298         dev_info(&adapter->pdev->dev, "VF %u is %strusted\n",
9299                  vf, setting ? "" : "not ");
9300         return 0;
9301 }
9302
9303 static int igb_ndo_get_vf_config(struct net_device *netdev,
9304                                  int vf, struct ifla_vf_info *ivi)
9305 {
9306         struct igb_adapter *adapter = netdev_priv(netdev);
9307         if (vf >= adapter->vfs_allocated_count)
9308                 return -EINVAL;
9309         ivi->vf = vf;
9310         memcpy(&ivi->mac, adapter->vf_data[vf].vf_mac_addresses, ETH_ALEN);
9311         ivi->max_tx_rate = adapter->vf_data[vf].tx_rate;
9312         ivi->min_tx_rate = 0;
9313         ivi->vlan = adapter->vf_data[vf].pf_vlan;
9314         ivi->qos = adapter->vf_data[vf].pf_qos;
9315         ivi->spoofchk = adapter->vf_data[vf].spoofchk_enabled;
9316         ivi->trusted = adapter->vf_data[vf].trusted;
9317         return 0;
9318 }
9319
9320 static void igb_vmm_control(struct igb_adapter *adapter)
9321 {
9322         struct e1000_hw *hw = &adapter->hw;
9323         u32 reg;
9324
9325         switch (hw->mac.type) {
9326         case e1000_82575:
9327         case e1000_i210:
9328         case e1000_i211:
9329         case e1000_i354:
9330         default:
9331                 /* replication is not supported for 82575 */
9332                 return;
9333         case e1000_82576:
9334                 /* notify HW that the MAC is adding vlan tags */
9335                 reg = rd32(E1000_DTXCTL);
9336                 reg |= E1000_DTXCTL_VLAN_ADDED;
9337                 wr32(E1000_DTXCTL, reg);
9338                 /* Fall through */
9339         case e1000_82580:
9340                 /* enable replication vlan tag stripping */
9341                 reg = rd32(E1000_RPLOLR);
9342                 reg |= E1000_RPLOLR_STRVLAN;
9343                 wr32(E1000_RPLOLR, reg);
9344                 /* Fall through */
9345         case e1000_i350:
9346                 /* none of the above registers are supported by i350 */
9347                 break;
9348         }
9349
9350         if (adapter->vfs_allocated_count) {
9351                 igb_vmdq_set_loopback_pf(hw, true);
9352                 igb_vmdq_set_replication_pf(hw, true);
9353                 igb_vmdq_set_anti_spoofing_pf(hw, true,
9354                                               adapter->vfs_allocated_count);
9355         } else {
9356                 igb_vmdq_set_loopback_pf(hw, false);
9357                 igb_vmdq_set_replication_pf(hw, false);
9358         }
9359 }
9360
9361 static void igb_init_dmac(struct igb_adapter *adapter, u32 pba)
9362 {
9363         struct e1000_hw *hw = &adapter->hw;
9364         u32 dmac_thr;
9365         u16 hwm;
9366
9367         if (hw->mac.type > e1000_82580) {
9368                 if (adapter->flags & IGB_FLAG_DMAC) {
9369                         u32 reg;
9370
9371                         /* force threshold to 0. */
9372                         wr32(E1000_DMCTXTH, 0);
9373
9374                         /* DMA Coalescing high water mark needs to be greater
9375                          * than the Rx threshold. Set hwm to PBA - max frame
9376                          * size in 16B units, capping it at PBA - 6KB.
9377                          */
9378                         hwm = 64 * (pba - 6);
9379                         reg = rd32(E1000_FCRTC);
9380                         reg &= ~E1000_FCRTC_RTH_COAL_MASK;
9381                         reg |= ((hwm << E1000_FCRTC_RTH_COAL_SHIFT)
9382                                 & E1000_FCRTC_RTH_COAL_MASK);
9383                         wr32(E1000_FCRTC, reg);
9384
9385                         /* Set the DMA Coalescing Rx threshold to PBA - 2 * max
9386                          * frame size, capping it at PBA - 10KB.
9387                          */
9388                         dmac_thr = pba - 10;
9389                         reg = rd32(E1000_DMACR);
9390                         reg &= ~E1000_DMACR_DMACTHR_MASK;
9391                         reg |= ((dmac_thr << E1000_DMACR_DMACTHR_SHIFT)
9392                                 & E1000_DMACR_DMACTHR_MASK);
9393
9394                         /* transition to L0x or L1 if available..*/
9395                         reg |= (E1000_DMACR_DMAC_EN | E1000_DMACR_DMAC_LX_MASK);
9396
9397                         /* watchdog timer= +-1000 usec in 32usec intervals */
9398                         reg |= (1000 >> 5);
9399
9400                         /* Disable BMC-to-OS Watchdog Enable */
9401                         if (hw->mac.type != e1000_i354)
9402                                 reg &= ~E1000_DMACR_DC_BMC2OSW_EN;
9403
9404                         wr32(E1000_DMACR, reg);
9405
9406                         /* no lower threshold to disable
9407                          * coalescing(smart fifb)-UTRESH=0
9408                          */
9409                         wr32(E1000_DMCRTRH, 0);
9410
9411                         reg = (IGB_DMCTLX_DCFLUSH_DIS | 0x4);
9412
9413                         wr32(E1000_DMCTLX, reg);
9414
9415                         /* free space in tx packet buffer to wake from
9416                          * DMA coal
9417                          */
9418                         wr32(E1000_DMCTXTH, (IGB_MIN_TXPBSIZE -
9419                              (IGB_TX_BUF_4096 + adapter->max_frame_size)) >> 6);
9420
9421                         /* make low power state decision controlled
9422                          * by DMA coal
9423                          */
9424                         reg = rd32(E1000_PCIEMISC);
9425                         reg &= ~E1000_PCIEMISC_LX_DECISION;
9426                         wr32(E1000_PCIEMISC, reg);
9427                 } /* endif adapter->dmac is not disabled */
9428         } else if (hw->mac.type == e1000_82580) {
9429                 u32 reg = rd32(E1000_PCIEMISC);
9430
9431                 wr32(E1000_PCIEMISC, reg & ~E1000_PCIEMISC_LX_DECISION);
9432                 wr32(E1000_DMACR, 0);
9433         }
9434 }
9435
9436 /**
9437  *  igb_read_i2c_byte - Reads 8 bit word over I2C
9438  *  @hw: pointer to hardware structure
9439  *  @byte_offset: byte offset to read
9440  *  @dev_addr: device address
9441  *  @data: value read
9442  *
9443  *  Performs byte read operation over I2C interface at
9444  *  a specified device address.
9445  **/
9446 s32 igb_read_i2c_byte(struct e1000_hw *hw, u8 byte_offset,
9447                       u8 dev_addr, u8 *data)
9448 {
9449         struct igb_adapter *adapter = container_of(hw, struct igb_adapter, hw);
9450         struct i2c_client *this_client = adapter->i2c_client;
9451         s32 status;
9452         u16 swfw_mask = 0;
9453
9454         if (!this_client)
9455                 return E1000_ERR_I2C;
9456
9457         swfw_mask = E1000_SWFW_PHY0_SM;
9458
9459         if (hw->mac.ops.acquire_swfw_sync(hw, swfw_mask))
9460                 return E1000_ERR_SWFW_SYNC;
9461
9462         status = i2c_smbus_read_byte_data(this_client, byte_offset);
9463         hw->mac.ops.release_swfw_sync(hw, swfw_mask);
9464
9465         if (status < 0)
9466                 return E1000_ERR_I2C;
9467         else {
9468                 *data = status;
9469                 return 0;
9470         }
9471 }
9472
9473 /**
9474  *  igb_write_i2c_byte - Writes 8 bit word over I2C
9475  *  @hw: pointer to hardware structure
9476  *  @byte_offset: byte offset to write
9477  *  @dev_addr: device address
9478  *  @data: value to write
9479  *
9480  *  Performs byte write operation over I2C interface at
9481  *  a specified device address.
9482  **/
9483 s32 igb_write_i2c_byte(struct e1000_hw *hw, u8 byte_offset,
9484                        u8 dev_addr, u8 data)
9485 {
9486         struct igb_adapter *adapter = container_of(hw, struct igb_adapter, hw);
9487         struct i2c_client *this_client = adapter->i2c_client;
9488         s32 status;
9489         u16 swfw_mask = E1000_SWFW_PHY0_SM;
9490
9491         if (!this_client)
9492                 return E1000_ERR_I2C;
9493
9494         if (hw->mac.ops.acquire_swfw_sync(hw, swfw_mask))
9495                 return E1000_ERR_SWFW_SYNC;
9496         status = i2c_smbus_write_byte_data(this_client, byte_offset, data);
9497         hw->mac.ops.release_swfw_sync(hw, swfw_mask);
9498
9499         if (status)
9500                 return E1000_ERR_I2C;
9501         else
9502                 return 0;
9503
9504 }
9505
9506 int igb_reinit_queues(struct igb_adapter *adapter)
9507 {
9508         struct net_device *netdev = adapter->netdev;
9509         struct pci_dev *pdev = adapter->pdev;
9510         int err = 0;
9511
9512         if (netif_running(netdev))
9513                 igb_close(netdev);
9514
9515         igb_reset_interrupt_capability(adapter);
9516
9517         if (igb_init_interrupt_scheme(adapter, true)) {
9518                 dev_err(&pdev->dev, "Unable to allocate memory for queues\n");
9519                 return -ENOMEM;
9520         }
9521
9522         if (netif_running(netdev))
9523                 err = igb_open(netdev);
9524
9525         return err;
9526 }
9527
9528 static void igb_nfc_filter_exit(struct igb_adapter *adapter)
9529 {
9530         struct igb_nfc_filter *rule;
9531
9532         spin_lock(&adapter->nfc_lock);
9533
9534         hlist_for_each_entry(rule, &adapter->nfc_filter_list, nfc_node)
9535                 igb_erase_filter(adapter, rule);
9536
9537         hlist_for_each_entry(rule, &adapter->cls_flower_list, nfc_node)
9538                 igb_erase_filter(adapter, rule);
9539
9540         spin_unlock(&adapter->nfc_lock);
9541 }
9542
9543 static void igb_nfc_filter_restore(struct igb_adapter *adapter)
9544 {
9545         struct igb_nfc_filter *rule;
9546
9547         spin_lock(&adapter->nfc_lock);
9548
9549         hlist_for_each_entry(rule, &adapter->nfc_filter_list, nfc_node)
9550                 igb_add_filter(adapter, rule);
9551
9552         spin_unlock(&adapter->nfc_lock);
9553 }
9554 /* igb_main.c */